You are on page 1of 40

BLAISE

BLAISE PASCAL MAGAZINE 42


PASCAL MAGAZINE 42
D E L P H I, L A Z A R U S, O X Y G E N E, S M A R T M O B I L E,
A N D P A S C AL R E L A T E D L A N G U A G E S
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

QUANTUM COMPUTING
QUANTUM COMPUTING
QUANTUM COMPUTING
QUANTUM COMPUTING
QUANTUM COMPUTING
QUANTUM COMPUTING
QUANTUM COMPUTING
QUANTUM COMPUTING
QUANTUM COMPUTING
QUANTUM COMPUTING
QUANTUM COMPUTING
QUANTUM COMPUTING
QUANTUM COMPUTING
QUANTUM COMPUTING
QUANTUM COMPUTING

QUANT
UM CO
MPU TING

QUA
M C
OMP
UTI
NTU
QUANTUM COMPUTING
QUANTUM COMPUTING
NG

QUANTUM COMPUTING
BY EDITOR

THALES OF MILETUS - A PRE-SOCRATIC GREEK PHILOSOPHER


BY EDITOR

ARDUINO: THE VISUINO PROJECT - PART 2


COLLECT DATA AND WORK WITH IT IN DELPHI
BY BOIAN MITOV

GETTING STARTED WITH THE TMS PLANNER FOR FIREMONKEY


BY BRUNO FIERENS

MAPPING USING DELPHI


BY PETER VAN DER SMAN

LOG, DEBUG AND AUDIT THE KBMMW WAY


BY KIM MADSEN

PRINTED ISSUE PRICE 15,00


DOWNLOAD ISSUE PRICE 5,00
BLAISE
BLAISE PASCAL MAGAZINE 42
PASCAL MAGAZINE
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
F O R 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
QUANTUM COMPUTING
BY EDITOR PAGE 5

THALES OF MILETUS - A PRE-SOCRATIC GREEK PHILOSOPHER


BY EDITOR PAGE 9

ARDUINO: THE VISUINO PROJECT - PART 2


COLLECT DATA AND WORK WITH IT IN DELPHI
BY BOIAN MITOV PAGE 14

GETTING STARTED WITH THE TMS PLANNER FOR FIREMONKEY


BY BRUNO FIERENS PAGE 22

MAPPING USING DELPHI


BY PETER VAN DER SMAN PAGE 28

LOG, DEBUG AND AUDIT THE KBMMW WAY


BY KIM MADSEN PAGE 33

MOTION

BLAISE
BLAISE PASCAL
PASCAL MAGAZINE
MAGAZINE

Advertisers
Barnsten 21
Components 4 Developers 40
Computer Math & Games 4
Daniel Teti 4
Raize Software 27 Publisher: Foundation for Supporting the Pascal Programming Language
Visuino MITOV 21 in collaboration with the Dutch Pascal User Group (Pascal Gebruikers Groep)
Stichting Ondersteuning Programmeertaal Pascal

2 Issue Nr 4 2015 BLAISE PASCAL MAGAZINE


Stephen Ball Peter Bijlsma Michal Van Canneyt,
http://delphiaball.co.uk -Editor peter @ blaisepascal.eu michael @ freepascal.org
@DelphiABall

Marco Cant David Dirkse Benno Evers


www.marcocantu.com www.davdata.nl b.evers
marco.cantu @ gmail.com E-mail: David @ davdata.nl @everscustomtechnology.nl

Bruno Fierens Primo Gabrijeli Cary Jensen


www.tmssoftware.com www. www.jensendatasystems.com
bruno.fierens @ tmssoftware.com primoz @ gabrijelcic.org http://caryjensen.blogspot.nl

Max Kleiner John Kuiper Wagner R. Landgraf


www.softwareschule.ch john_kuiper@kpnmail.nl wagner @ tmssoftware.com
max@kleiner.com

Kim Madsen Peter van der Sman Jeremy North


www.component4developers sman@prisman.nl jeremy.north @ gmail.com

Detlef Overbeek - Editor in Chief Howard Page Clark Andrea Raimondi


www.blaisepascal.eu E-mail: hdpc @ talktalk.net
editor @ blaisepascal.eu

Wim Van Ingen Schenau Rik Smit Bob Swart


-Editor rik @ blaisepascal.eu www.eBob42.com
wisone @ xs4all.nl Bob @ eBob42.com

Daniele Teti
www.danieleteti.it
d.teti@bittime.it

Please note: extra space characters have been deliberately added around the @ symbol in
these email addresses, which need to be removed if you use them.
editor @ blaisepascal.eu
Authors - Christian name in alphabethical order
A Andrea Raimondi , L Wagner R. Landgraf, Sergey Lyubeznyy
B Stephen Ball, Peter Bijlsma, Dmitry Boyarintsev 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 Inoussa Ouedraogo
G Primo Gabrijeli, Mattias Gaertner P Howard Page-Clark,
H Fikret Hasovic S Rik Smit, Bob Swart,
J Cary Jensen Z Siegfried Zuhr

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 65.-- Incl. VAT 6 % (including code, programs and printed magazine,
10 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.

Issue Nr 4 2015 BLAISE PASCAL MAGAZINE 3


30,00
including VAT
39
including
DAVID DIRKSE
presales at the
printed
www.blaisepascal.eu/DavidDirkse/ComputerMath_Games.html
book,
ebook
and shipping

Quick answers to common problems

procedure ;
var
begin Delphi Cookbook
for i := 1 HOICE A
SC
to 9 do 50 hands-on recipes to master the power of Delphi for
M

R BLAISE
cross-platform and mobile development on Windows,
TO

begin PASCAL
Mac OS X, Android, and iOS MAGAZINE
DI
AZING

E
end;
end;
Daniele Teti

See our special offer:


if you take out a subscription
BLAISE PASCAL MAGAZINE
is proud to announce the first for two years the book
edition of David Dirkses book:
will cost you only 10,00
COMPUTER MATH &
GAMES IN PASCAL
http://www.blaisepascal.eu/daniele_teti_book/DanieleTeti.html
QUANTUM COMPUTERS ? PAGE 1/3
(a)
B1 B2 B3
P1 P2
A quantum computer can contain these
multiple states simultaneously, so it has the potential L2
to be infinitely more powerful than the largest and L1
best developed powerful supercomputers.
This superposition of qubits is what gives quantum 30 nm
computers their inherent parallelism. The physicist
David Deutsch, thinks parallelism allows a quantum
(b)
(b)
computer to work on a very large number
Alx Oy
(1.000.000. 10) or more computations at once, while P1 P2
our PC works on only one. A 30-qubit quantum
L1 L2
computer would equal the processing power of a S iO2 B1 B2 B3
conventional computer that could run at 10 teraflops
(trillions of floating-point operations per second). SS DD
Electron Left Left
Electron Right
Dot DotRight Dot Dot
Reservoir
Reservoir
i - Si
Today's typical desktop computers do gigaflops B1
(billions of floating-point operations per second).
Quantum computers also utilize another aspect of
quantum mechanics known as entanglement. The instant it is disturbed, it chooses one spin - or
Quantum entanglement is a physical phenomenon one value - and at the same time, the second
that occurs when pairs or groups of particles are
entangled atom will choose an opposite spin, or
generated or interact in ways such that the quantum
value
state of each particle cannot be described
independentlyinstead, a quantum state may be
given for the system as a whole. This allows scientists to know the value of the
One problem with the idea of quantum qubits without actually looking at them.
computers is that if you try to look at the Lets look at some recent advancements with
quantum computing. Computer scientists control
subatomic particles, you could bump them, and
thereby change their value. the microscopic particles that act as qubits in
If you look at a qubit(*) in superposition to quantum computers by using control devices.
determine its value, the qubit will assume the
value of either 0 or 1, but not both. Ion traps use optical or magnetic fields
(*)In quantum computing, a qubit (/ kju b t/) or (or a combination of both) to trap ions.
quantum bit is a unit of quantum informationthe Optical traps use light waves to trap and
quantum analogue of the classical bit. A qubit is a two- control particles.
state quantum-mechanical system, such as the Quantum dots are made of semiconductor
polarization of a single photon: here the two states are material and are used to contain and
vertical polarization and horizontal polarization. manipulate electrons.
Semiconductor impurities contain electrons
In a classical system, a bit would have to be in by using "unwanted" atoms found in
one state or the other. However quantum semiconductor material.
mechanics allows the qubit to be in a Superconducting circuits allow electrons
superposition of both states at the same time, a to flow with almost no resistance at
property which is fundamental to quantum very low temperatures
computing.

To create a practical quantum computer,


scientists have to devise ways of making
measurements indirectly to preserve the system's
integrity. Entanglement provides a potential
Two electrons cannot have
answer. In quantum physics, if you apply an
outside force to two atoms, it can cause them to identical quantum states
become entangled, and the second atom can take
on the properties of the first atom. So if left alone,
an atom will spin in all directions..

Issue Nr 4 2015 BLAISE PASCAL MAGAZINE 5


QUANTUM COMPUTERS ? PAGE 2/3

TEXT TAKEN OUT OF THE


WEBSITE ARTICLE FROM
THE UNIVERSITY OF
TWENTE HOLLAND

TODAY'S QUANTUM COMPUTERS In silicon, extremely long spin relaxation (T1)


Quantum computers could one day replace and coherence times (T2) are expected.
silicon chips, just like the transistor once replaced Recently, a direct measurement was performed
the vacuum tube. The most advanced quantum of the T1 of a single electron in silicon, which is
computers havent gone beyond manipulating ~6 seconds at a magnetic field of 1.5 Tesla.
more than 16 qubits, which means that they are
far from practical application. In the next issues SPIN QUBITS IN SILICON QUANTUM DOTS
we will have a look at a few of the quantum We aim at controlling the spin states of
computers that have been developed. individual electrons in silicon double quantum
dots (DQDs) with the ultimate goal of realizing
In the field of silicon quantum electronics we silicon single-electron spin quantum bits as
study the quantum-mechanical behavior of building blocks for future solid-state quantum
individual spins in silicon. computers, see e.g. Although important progress
Control and manipulation of the corresponding has been made over the last few years, it is not
spin states can be lead to applications in quantum trivial to define QDs in Si. The main issues are
computation. the large effective mass of the charge carriers and
To this end we isolate electrons or holes on the sensitivity to disorder, resulting in carrier
(artificial) atoms through spatial and electrostatic localization on short length scales, and thus
confinement. In our experiments we perform a.o. multiple QDs connected in series.
energy- and magnetic spectroscopy in electron The most successful systems for n-Si QDs are
transport measurements at low temperatures. etched silicon-on-insulator structures, two-
Four approaches to study single spins in silicon: dimensional electron gases in Si/SiGe
we isolate individual electrons and holes, either heterostructures and at Si/SiO2 interfaces (planar
in real or artificial atoms. quantum dots), and bottom-up grown nanowires.
In the NanoElectronics group we use two
Single electron spins as quantum bits material systems to isolate single electron and
Among other proposed physical realizations for hole spins in Si QDs:
quantum information processors, SI AND GE/SI NANOWIRE
semiconductor-based qubits belong to the most QUANTUM DOTS
popular suggestions. In particular, electron In the past years, science has shown great
spins in quantum dots (QDs) have received interest in semiconducting crystalline
considerable attention, and significant nanowires, cylinder-shaped wires with aspect
experimental progress has been made since ratios of 1000 or more. Nanowires have
Loss and DiVincenzo presented their original diameters up to tens of nanometers and can be
proposal. Experiments on lithographically tens of microns long. Their strength lies in the
defined QDs in GaAs/AlGaAs heterostructures precisely controlled and tunable chemical
have shown qubit initialization, single-shot composition, structure, size, and morphology.
single-electron spin read-out, and coherent The high degree of freedom in nanowire
control of single-spin and two-spin states. synthesis allows epitaxial growth of
The strong hyperfine and spin-orbit interaction heterostructures in both the radial and
in AlGaAs/GaAs QDs limit the spin coherence longitudinal direction. The doping in
time in those materials. nanowires can be varied during growth, to
make for example pn-junctions within a single
nanowire to create LEDs.

6 Issue Nr 4 2015 BLAISE PASCAL MAGAZINE


QUANTUM COMPUTERS ? PAGE 3/3

Nanowire quantum dots. (a)


Microscope image of a Ge nanowire sticking to
the tip of our micromanipulator.
Ge, Si and Ge/Si nanowires are grown at
Eindhoven University by the Vapor-Liquid-
Solid growth mechanism, see here.

After synthesis the nanowires are deposited on


an oxidized silicon substrate with predeposited
bottom gates. In a subsequent fabrication step,
source (S) and drain (D) contacts are evaporated
on top of the nanowire, see (b) for a schematic
cross-section and (c) for a top view of a real
device.
Voltages applied to the bottom gates are used to
create a quantum dot, and control both charge
occupation and tunnel barriers.
Highly tunable planar Si quantum dots
compatible with CMOS industry.

We define Si QDs in an electron or hole gas at the


Si/SiO2 interface through electrostatic gating.

See for example our recent report on Single-


hole tunneling through a two-dimensional hole
gas in intrinsic silicon.

The design with three layers of gates allows


control of all QD components: the QDs
themselves, the tunnel barriers and the densities
of states in the reservoirs. In collaboration with
the group of Prof. Dzurak at the University of
New South Wales, we are further developing the
Si QD technology towards few-electron double
quantum dot devices.

Issue Nr 4 2015 BLAISE PASCAL MAGAZINE 7


OVERVIEW OF DELPHI TO DELPHI HISTORY
DELPHI XE8
On February 8, 2006 Borland announced that it was
looking for a buyer for its IDE and database line of products,
including Delphi, to concentrate on its ALM line. On November
14, 2006 Borland transferred the development tools group to
Embarcadero Technologies in 2008.
an independent subsidiary company named CodeGear,
instead of selling it. Borland sold CodeGear to Embarcadero Codegear Delphi 2007.
Technologies in 2008. Embarcadero retained the CodeGear DELPHI 7 released in August 2002
division created by Borland to identify its tool and database
offerings, but identified its own database tools under the
DatabaseGear name. DELPHI
The roots of Turbo Pascal v1.0 started in Denmark. The first step,
released February 14, 1995
in 1981, was the Blue Label Software Pascal Compiler - BLS Pascal Turbo Pascal
Compiler v1.2, copyright 1981 by Poly-Data microcenter ApS, Developer(s) Anders Hejlsberg while
Strandboulvarden 63, DK 2100 Copenhagen - written by Anders working at Borland
Hejlsberg for the NASCOM kit computer. Operating system CP/M, CP/M-86, DOS,
Windows 3.x, Macintosh
Lisa - Pascal was a Pascal implementation for the Apple Lisa workstation. Platform 8080/Z80, 8085, x86
It was an extension of the earlier Apple Pascal for Apple II machines,
but generated object code for 68000 processors that had to be linked
against the required libraries in the Lisa OS workshop. Windows
Lisa Pascal laid the foundation for the development of Clascal and Mac Pascal
the first implementations of Object Pascal.

Charles Babbage - mathematician Niklaus Wirth


conceived of the first programmable computer in the 1830s born February 15, 1934 He is a Swiss
Babbage never built his Difference Engine computer scientist, best known for
- a mechanical calculator with thousands of parts - designing several programming languages,
because of cost overruns and political disagreements, including Pascal, and for pioneering several
but the inventor passed on plans for its completion, classic topics in software engineering.
and in 1991, the Science Museum in London actually
built it (the printing component was finished in 2000).
As suspected, it actually works.

Blaise Pascal (19 June 1623 19 August 1662)


was a French mathematician,
physicist, inventor, writer and Christian philosopher. Discovery of America by Columbus
creates the first calculators Columbus led his three ships - the Nina,
Blaise Pascal starts to gamble - result first statistics the Pinta and the Santa Maria -
out of the Spanish port of Palos on August 3, 1492.

Discovery of Amerca by the Vikings 990 - 1050


Building of Spain 912 and Portugal 800
Building of France 5852 BC

Decay of the Roman Empire 500


Building of Europe

Archimedes Mathematician
Roman Empire 700 BC
Archimedes of Syracuse was an Ancient
Greek mathematician, physicist, engineer,
inventor, and astronomer.
He is regarded as one of the leading scientists
in classical antiquity. Wikipedia
Born: 287 - 212 BC, Syracuse, Italy

Plato in Classical Attic;


428/427 or 424/423 348/347 BC)
was a philosopher, as well as mathematician,
in Classical Greece.

Euclid Mathematician
Born Mid-4th century BC - 3rd century BC
Residence Alexandria, Hellenistic Egypt
Fields Mathematics Known for
Euclidean geometry / Euclid's Elements
Euclidean algorithm

Pythagoras Philosopher
Pythagoras of Samos was an
Ionian Greek philosopher, mathematician,
and founder of the religious movement
called Pythagoreanism.
Born: 571 - 495 BC,

Thales Philosopher
Thales of Miletus was a pre-Socratic Greek philosopher Difference Engine No. 1, portion,1832
from Miletus in Asia Minor and one of the
IN THIS ISSUE (42) Seven Sages of Greece. Many, most notably Aristotle,
regard him as the first philosopher in the Greek tradition.
Born: 624 BC - 546

DELPHI
The cult of Apollo at
Delphi probably
dates back to
ISSUE 40
the 700s B . C .,

Page 9
WATER CLOCK - CHINA - BEGINNING OF TIME (BC 4000)
Some authors claim that water clocks appeared in China
as early as 4000 BC Babbage Difference Engine No. 2
THALES OF MILETUS PAGE 1/3
Thales of Miletus (c. 624 c. 546 BC)
was a pre-Socratic Greek philosopher, Diogenes Lartius quotes the chronicle of
mathematician from Miletus in Asia Apollodorus of Athens as saying that Thales
Minor and one of the Seven Sages of died at the age of 78 during the 58th Olympiad
Greece.( The Seven Sages (of Greece) (548545 BC) and attributes his death to heat
or Seven Wise Men ( hoi hepta sophoi; stroke while watching the games.
c. 620 550 BC) was the title given by
ancient Greek tradition to seven early-
6th-century BC philosophers, Thales involved himself in many activities,
statesmen and law-givers who were taking the role of an innovator.
renowned in the following centuries for
their wisdom.) Many, most notably
Aristotle, regard him as the first
philosopher in the Greek tradition.

Aristotle reported Thales' hypothesis that the


originating principle of nature and the nature of
matter was a single material substance: water.
Thales attempted to explain natural
phenomena without reference to mythology.
Almost all of the other Pre-Socratic philosophers
follow him in attempting to provide an
explanation of ultimate substance, change, and
the existence of the world without reference to
mythology.
Those philosophers were also influential and
eventually Thales' rejection of mythological
explanations became an essential idea for the
An olive mill and an olive press dating from
scientific revolution.
Roman times in Capernaum, Israel.
He was also the first to define general
principles and set forth hypotheses, and as a result
Several anecdotes suggest that Thales was not
has been dubbed the "Father of Science," though it
solely a thinker but was also involved in
is argued that Democritus is actually more
business and politics. One story recounts that he
deserving of this title.
bought all the olive presses in Miletus after
In mathematics, Thales used geometry to
predicting the weather and a good harvest for a
calculate the heights of pyramids and the distance
particular year. In another version of the same
of ships from the shore. He is credited with the
story, Aristotle explains that Thales reserved
first use of deductive reasoning applied to geometry,
presses ahead of time at a discount only to rent
by deriving four corollaries to Thales' Theorem.
them out at a high price when demand peaked,
As a result, he has been hailed as the first true
following his predictions of a particularly good
mathematician and is the first known individual
harvest. This first version of the story would
to whom a mathematical discovery has been
constitute the first creation and use of futures,
attributed.
whereas the second version would be the first
THE LIFE PERIOD creation and use of options. Aristotle explains
The current historical consensus is that Thales that Thales' objective in doing this was not to
was born in the city of Miletus around the mid enrich himself but to prove to his fellow
620s BC. Milesians that philosophy could be useful,
Miletus was an ancient Greek Ionian city on the contrary to what they thought.
western coast of Asia Minor (in what is today Aydin
Province of Turkey), near the mouth of the THEORIES
Maeander River. The Greeks often invoked idiosyncratic
The dates of Thales' life are not exactly known but explanations of natural phenomena with
are roughly established by a few datable events reference to the will of anthropomorphic gods
mentioned in the sources. According to and heroes. Instead, Thales aimed to explain
Herodotus (and as determined by modern methods), natural phenomena via rational hypotheses that
Thales predicted the solar eclipse of May 28, 585 referenced natural processes themselves.
BC (Before Christ)

Issue Nr 4 2015 BLAISE PASCAL MAGAZINE 9


THALES OF MILETUS PAGE 2/3
For example, rather than assuming that GEOMETRY
earthquakes were the result of supernatural Thales was known for his innovative use of
whims. Thales explained them by hypothesizing geometry. His understanding was theoretical as
that the Earth floats on water and that earthquakes well as practical. For example, he said:
occur when the Earth is rocked by waves. Space is the greatest thing, as it contains all
Thales was a hylozoist (one who thinks that matter is things
alive). Topos is in Newtonian-style space, since the
That interpretation by later commentators verb, chorei, has the connotation of yielding
that Thales treated matter as being alive before things, or spreading out to make room for
may have been substituted for his thinking that them, which is extension. Within this extension,
the properties of nature arise directly from things have a position. Points, lines, planes and
material processes. solids related by distances and angles follow
The latter thesis is more consistent with from this presumption.
modern ideas of how properties arise as emergent Thales understood similar triangles and right
characteristics of those complex systems involved triangles, and what is more, used that
in the processes of evolution and developmental knowledge in practical ways.
change. The story is told that he measured the height
Thales, according to Aristotle, asked what was of the pyramids by their shadows at the moment
the nature (Greek arche) of the object so that it when his own shadow was equal to his height.
would behave in its characteristic way. A right triangle with two equal legs is a 45-
Physis comes from phyein, "to grow", related to degree right triangle, all of which are similar.
our word "be". (G)natura is the way a thing is The length of the pyramid's shadow measured
"born", again with the stamp of what it is in itself. from the center of the pyramid at that moment
must have been equal to its height.
Aristotle characterizes most of the philosophers This story indicates that he was familiar with
"at first" as thinking that the "principles in the the Egyptian seked, or seqed - the ratio of the run
form of matter were the only principles of all to the rise of a slope (cotangent).
things", where "principle" is arche, "matter" is hyle The seked is at the base of problems 56, 57, 58,
("wood" or "matter", "material") and "form" is 59 and 60 of the Rhind papyrus an ancient
eidos. Egyptian mathematical document.
Arche is translated as "principle", but the two
words do not have precisely the same meaning. In present day trigonometry, cotangents require
A principle of something is merely prior (related to the same units for run and rise (base and
pro-) to it either chronologically or logically. perpendicular), but the papyrus uses cubits for
An arche ("to rule") dominates an object in some rise and palms for run, resulting in different (but
way. still characteristic) numbers. Since there were 7
If the arche is taken to be an origin, then specific palms in a cubit, the seked was 7 times the
causality is implied; that is, B is supposed to be cotangent.
characteristically B just because it comes from A,
which dominates it. To use an example often quoted in modern
The archai that Aristotle had in mind in his reference works, suppose the base of a pyramid
well-known passage on the first Greek scientists is 140 cubits and the angle of rise 5.25 seked.
are not necessarily chronologically prior to their The Egyptians expressed their fractions as the
objects, but are constituents of it. sum of fractions, but the decimals are sufficient
For example, in pluralism objects are composed of for the example. What is the rise in cubits?
earth, air, fire and water, but those elements do The run is 70 cubits, 490 palms. X, the rise, is
not disappear with the production of the object. 490 divided by 5.25 or 9313 cubits.
They remain as archai within it, as do the atoms These figures sufficed for the Egyptians and
of the atomists. Thales.
What Aristotle is really saying is that the first We would go on to calculate the cotangent as
philosophers were trying to define the 70 divided by 9313 to get 3/4 or .75 and looking
substance(s) of which all material objects are that up in a table of cotangents find that the
composed. As a matter of fact, that is exactly angle of rise is a few minutes over 53 degrees.
what modern scientists are attempting to
accomplish in nuclear physics, which is a second
reason why Thales is described as the first
western scientist.

10 Issue Nr 4 2015 BLAISE PASCAL MAGAZINE


THALES OF MILETUS PAGE 3/3
Whether the ability to use the seked, which WATER AS A FIRST PRINCIPLE
preceded Thales by about 1000 years, means that Thales' most famous philosophical position was
he was the first to define trigonometry is a matter his cosmological thesis, which comes down to us
of opinion. More practically Thales used the through a passage from Aristotle's Metaphysics.
same method to measure the distances of ships at In the work Aristotle unequivocally reported
sea, said Eudemus as reported by Proclus (in Thales hypothesis about the nature of matter
Euclidem ). According to Kirk & Raven (reference that the originating principle of nature was a
cited below), all you need for this feat is three single material substance: water.
straight sticks pinned at one end and knowledge Aristotle then proceeded to proffer a number
of your altitude. One stick goes vertically into of conjectures based on his own observations to
the ground. A second is made level. With the lend some credence to why Thales may have
third you sight the ship and calculate the seked advanced this idea (though Aristotle didnt hold it
from the height of the stick and its distance from himself). Aristotle considered Thales position to
the point of insertion to the line of sight. be roughly the equivalent to the later ideas of
The seked is a measure of the angle. Knowledge Anaximenes, who held that everything was
of two angles (the seked and a right angle) and an composed of air.
enclosed leg (the altitude) allows you to Aristotle laid out his own thinking about matter
determine by similar triangles the second leg, and form which may shed some light on the ideas
which is the distance. Thales probably had his of Thales.
own equipment rigged and recorded his own
sekeds, but that is only a guess. That from which is everything that exists and
from which it first becomes and into which it is
rendered at last, its substance remaining under
A it, but transforming in qualities, that they say is
the element and principle of things that are.
D For it is necessary that there be some nature,
either one or more than one, from which
E become the other things of the object being
saved... Thales the founder of this type of
B philosophy says that it is water.

Aristotle conjectured that Thales reached his


C conclusion by contemplating that the
DE AE AD "nourishment of all things is moist and that even
= = the hot is created from the wet and lives by it.
BC AC AB While Aristotles conjecture on why Thales
held water was the originating principle of water
THALES' THEOREM is his own thinking, his statement that Thales
Actually there are two theorems called Theorem held it was water is generally accepted as
of Thales, one having to do with a triangle genuinely originating with Thales and he is seen
inscribed in a circle and having the circle's as an incipient matter-and-formist.
diameter as one leg, the other theorem being also
called the intercept theorem. In addition Eudemus Heraclitus Homericus states that Thales drew his
attributed to him the discovery that a circle is conclusion from seeing moist substance turn into
bisected by its diameter, that the base angles of an air, slime and earth. It seems likely that Thales
isosceles triangle are equal and that vertical viewed the Earth as solidifying from the water on
angles are equal. which it floated and the oceans that surround it.
According to a historical Note, when Thales Writing centuries later, Diogenes Laertius also
visited Egypt, he observed that whenever the states that Thales taught "Water constituted
Egyptians drew two intersecting lines, they would 'stood under' the principle of all things."
measure the vertical angles to make sure that they
were equal. Thales concluded that one could
prove that all vertical angles are equal if one
accepted some general notions such as: all straight
angles are equal, equals added to equals are equal,
and equals subtracted from equals are equal. It
would be hard to imagine civilization without
these theorems.

Issue Nr 4 2015 BLAISE PASCAL MAGAZINE 11


ARDUINO: THE VISUINO PROJECT - PART 2 BY BOIAN MITOV
COLLECT DATA AND WORK WITH IT IN DELPHI
In the previous issue you learned how easy it is to In the last article I also demonstrated the ability
program Arduino with Visuino and how to receive to collect data from multiple sensors
data from Arduino and visualize it. Acquiring, and simultaneously, and send it to Visuino for
visualizing this data is great, but it is not worth
much, if we can't use it in our Delphi applications.
visualization.
So let's fire up Delphi, and see how we can get To achieve this, I needed to develop Data
that data into our Delphi applications. Packaging Arduino component, and its Delphi
As I mentioned in part one, to develop Visuino, unpackaging counterpart. It was only natural to
I needed a serial communication component. create the corresponding Package component in
To solve the problem, I could have used one of the Delphi and Un-Package component in Arduino.
existing components such as AsynchronPro or any This now allowed bidirectional packaged
other. I actually spent some time reviewing and
multichannel communication.
testing them, but I got disappointed fairly quickly.
Most are designed so the data processing is done in The ComPort, the Terminal, the Package
the main thread. and the UnPackage components formed the basis
This is an advantage, when they are used for of a new upcoming library CommunicationLab.
smaller amounts of data, or speeds, by less At present we are working to expand it with
experienced developers. But in case of large data more components, and we are planning a Beta
exchange - if the main thread gets busy rendering release soon. Here we will use the new
graphical data or any other time consuming GUI
components to demonstrate how easy it is to
related tasks - the communication will be blocked
with a number of potential issues arising ranging communicate with Arduino.
from processing delay, memory over-usage, all the It is an old tradition to start with a Hello World!
way to even potential data loss. program. We will however start with a Hello
This led me to develop a new ComPort Serial Delphi! program instead.
component, and as with most components I develop,
I made it OpenWire enabled, so it can directly Before you start, make sure you have installed
connect to other OpenWire components.
the Arduino IDE from
http://www.arduino.cc , and Visuino
The component worked well, and I wrote the from http://www.visuino.com as shown in
necessary code to receive data from it, and the previous issue.
properly populate a TMemo simulating a serial
terminal. Visuino will automatically generate all the
While doing this and debugging the necessary Arduino C++ code, and the free open
communication, I often needed to create test source Arduino IDE comes with all the necessary
Delphi applications. I discovered that, time and compiler and libraries. You do not need to know
again, I need to write small portions of data or understand any C++ code in order to program
collecting and converting code to populate Arduino. The Visuino will handle all of that under
TMemos, so this led to the creation of dedicated the hood, as demonstrated in the previous issue.
terminal component, thus speeding up my
development and debugging significantly. Start Visuino, and drop a TextValue component:

12 Issue Nr 4 2015 BLAISE PASCAL MAGAZINE


ARDUINO: THE VISUINO PROJECT - PART 2 PAGE - 2/9
COLLECT DATA AND WORK WITH IT IN DELPHI

Next connect the OutputPin of the TextValue


component to the InputPin of the Arduino Serial:

In the Object Inspector, for the Value


property type Hello Delphi!:

If you have your Arduino board connected, all you


need is to click on the button,
and the code will be
Click on the Send to Arduino IDE for Compilation compiled and uploaded.
button(or pressing F9):
If you connect to Arduino with Visuino after the
upload, by clicking on the Connect button:

and press the reset button on the Arduino board,


you will receive Hello Delphi! in the terminal.

Visuino will automatically generate the Arduino


C++ code, and will open it in the Arduino IDE,
where you can compile and upload it:

Issue Nr 4 2015 BLAISE PASCAL MAGAZINE 13


ARDUINO: THE VISUINO PROJECT - PART 2 PAGE - 3/9
COLLECT DATA AND WORK WITH IT IN DELPHI

Now that we have the Arduino code working, it is


time to see how we can connect to it from Delphi.
Start Delphi.

From the Component Palette, drop


TCLComPort, and TCLTerminal:

14
6 Issue Nr 4 2015 BLAISE PASCAL MAGAZINE
ARDUINO: THE VISUINO PROJECT - PART 2 PAGE - 4/9
COLLECT DATA AND WORK WITH IT IN DELPHI

In the Object Inspector, select the COM port to which Arduino is connected:

Switch to the OpenWire view, by clicking on the OpenWire tab and connect the OutputPin of the
CLComPort1 to the InputPin of the CLTerminal1:

Issue Nr 4 2015 BLAISE PASCAL MAGAZINE 15


ARDUINO: THE VISUINO PROJECT - PART 2 PAGE - 5/9
COLLECT DATA AND WORK WITH IT IN DELPHI

Compile and run the application. If you The data arrives in binary form. Since in this case
press the reset button on the Arduino board, we know that we are sending text, we can convert
you will see this message: the data to text:
procedure TForm1 . CLComPort1Receive (
ASender : TObject ; AData :
TArray < System . Byte >);
var AText : String ;
begin
AText := TEncoding . ASCII . GetString ( AData
);
end ;

If you want to receive data from Arduino, we can


connect a data source such as one of the analog
pins, or a Sine Generator. We will use the
generator, as it is the easiest to experiment with.
The TCLComPort also has OnReceive event From the toolbar, drop a Sine Generator, and
where you can receive and process the data from connect its output pin, to the input pin of the
your code: Arduino Serial Port:

16 Issue Nr 4 2015 BLAISE PASCAL MAGAZINE


ARDUINO: THE VISUINO PROJECT - PART 2 PAGE - 6/9
COLLECT DATA AND WORK WITH IT IN DELPHI
Press F9 to automatically generate the C++ code Receiving and visualizing data from one
and automatically open the Arduino IDE, then channel is fine, but the data arrived in text
compile and upload the sketch, as we did earlier. format, and is difficult to use directly for
calculations, and processing.
If you run your Delphi application now, you will It also limits us to a single data channel.
receive the data from Arduino: In the previous issue, we learned how we can
use the Package component, to receive data from
multiple sensors at the same time.
Here is the project we did:

Now we will create a Delphi application


that can connect to Arduino, and receive
the data.

Start a new project and drop the


following components from the
component toolbar: TCLComPort,
TCLUnpacket, TSLScope,
TILAngularGauge,
TILThermometer, and two
TILLed.

Issue Nr 4 2015 BLAISE PASCAL MAGAZINE 17


ARDUINO: THE VISUINO PROJECT - PART 2 PAGE - 7/9
COLLECT DATA AND WORK WITH IT IN DELPHI

Set the COM port as we did earlier in the


previous Delphi project. Then double click on the
CLUnpacket1, then add 2 Binary Float
channels, and 2 Binary Boolean channels:

The Bytes editor will open. In the editor,


type 5555:

Close the window.

For the CLUnpacket1, in the Object Inspector,


expand the HeadMarker property, and for the
Bytes, click on the ... elipsys-button.

18 Issue Nr 4 2015 BLAISE PASCAL MAGAZINE


ARDUINO: THE VISUINO PROJECT - PART 2 PAGE - 8/9
COLLECT DATA AND WORK WITH IT IN DELPHI

Click OK to close the editor.


Select the Angular Gauge, and set
its Max value to 1, since we expect
the data we receive to be between 0.0,
and 1.0 (The Visuino Analog Inputs,
and Outputs are normalized):

Do the same for the Thermometer. Switch to the


OpenWire View, rearrange the components, and
make the following connections:

Compile and run the application.


You will see the data arriving from Arduino and
displayed in the Scope, the Gauge, the
Thermometer, and the two LED components:

Issue Nr 4 2015 BLAISE PASCAL MAGAZINE 19


ARDUINO: THE VISUINO PROJECT - PART 2 PAGE - 9/9
COLLECT DATA AND WORK WITH IT IN DELPHI

We already know how to visualize the data easily in


Delphi. Often however we need to work with the data
inside our code. To get the Analog data in the code,
add a TSLGenericRealValue component:

You can connect the component to one of the


Analog Floating Point channels:

The SLGenericRealValue1 has There are similar components available for


OnProcessData event, where we can write our code: Boolean and other data types as well.

You have learned for you can create Arduino


code, that collects and send data, and how to
create Delphi application that receives and
processes that data over serial channel.
In the following issues we will show you how
you can do the same over the network, and how
As example we can assign the value to the position you can have multiple Arduino devices talk to
of a Progress Bar: each other and to Delphi.
procedure TForm1.SLGenericRealValue1ProcessData(
Sender: TObject; InValue: Real; In short we will introduce you
var OutValue: Real; to the Internet Of Things with Delphi
var SendOutputData: Boolean); and Visuino.
begin
ProgressBar1.Position := Round( InValue * 100 );
end;

20 Issue Nr 4 2015 BLAISE PASCAL MAGAZINE


What is Visuino?
Visuino is the latest innovative software from Mitov Software.
A visual programming environment allowing you to program

INTRODUCTION What is Arduino?

The components found in the Visuino software represent their


Discover How RAD Studio XE8 hardware components and you will easily be able to create and
design your programs using drag and drop. No equipment or
Expands Your Business hardware is needed to run the software in design mode. Once you
have completed the design, you can connect Arduino board upload
and run it.
Multi-platform FireUI
Extend Windows Apps to Mobile For those people who are not strong on writing code then designing,
Mobilize Business with EMS
Update Subscription
Get Productive
Native Platform Controls IN THE NEXT ISSUE:
Stay Informed with Analytics
ALL ABOUT VISUINO
Dealing with Multiple UI Form Factors? Revolutionize the
process with FireUI

RAD Studio XE8 and the FireUI Multi-Device Designer


delivers the only true single source solution for natively
compiled applications. Most vendors who support native
cross-platform development require separate user interfaces
to be written on each platform.

Build a common UI that works across multiple form factors


of mobile phones, tablets, and desktop systems. Most
mobile development solutions do not support the creation of
PC apps for Windows and OS X.

RAD Studio XE8 continues to enhance the process of


building great apps with FireUI! The all new Multi-Device
Preview provides a design time side-by-side view comparing
your apps UI over different form factors on a given platform
all in one window!

or call: +31 (0)235422227


www.visuino.com
http://www.barnsten.com/default/newxe8
VISUINO IS THE LATEST INNOVATIVE PRODUCT
FROM MITOV SOFTWARE.
GETTING STARTED WITH THE TMS PLANNER FOR FIREMONKEY
(PAGE 1/5) BY BRUNO FIERENS
INTRODUCTION
At TMS software, we have recently released a new
scheduling control for cross-platform application
development with the Delphi FireMonkey
framework as part of the TMS Pack for FireMonkey
(http://www.tmssoftware.com/site/tmsfmxpack.a
sp). While TMS Planner for FireMonkey design
benefits from the significant experience the TMS
team built-up with the award-winning VCL,
IntraWeb and ASP.NET Planner components, the
new component has been architected from the
ground up for cross-platform, multi-device usage.
This includes tuning for performance & footprint
to run smoothly on Android or iOS smartphones
and making the component flexible enough for
complex scheduling applications in desktop or
tablet applications.

TMS Planner for FireMonkey running on Windows,


Mac OSX, iOS, Android
In a nutshell, the TMS Planner for
FireMonkey, named TTMSFMXPlanner is a
user-interface control representing a timeline and
events for single or multiple resources.

ARCHITECTURE
The three core parts of the TTMSFMXPlanner
are: timeline, resources and items (events). RESOURCES
The TTMSFMXPlanner can display events for a
TIMELINE single resource or can deal with multiple
The timeline determines the visible period of time resources. But there is more.
on the TTMSFMXPlanner and is highly Views with multiple resources can be combined
configurable. Default, it represents the standard with multiple days.
24hr timeline but this can be easily changed to In this way, multiple resources per day and
month mode, a day period mode, a half-day multiple days per resource can be shown. And in
period mode, multi-month mode or a custom addition to this, there is also the flexible
timeline mode. With the custom timeline mode, capability to create groups of a different number
the unit of time along the timeline can be fully of resources or days, like grouping a number of
programmatically set. In one of the included days in a week or grouping a number of
demos will be a timeline in seconds mode that resources to a company etc...
represents a schedule of TV-adds. The timeline
can be displayed on the left side, right side, left ITEMS
and right side or also at the top of the Finally, the TTMSFMXPlanner hosts a collection
TTMSFMXPlanner in a 90 rotated view. of items (events). The items have a start time, end
time, title, notes, color,
Items have settings to allow moving, sizing, for
read-only, for allowing overlap or not etc.. .
Items can be edited via inplace-editing or a built-in
or custom dialog can be used for editing.

productivity software buiding blocks


22 Issue Nr 4 2015 BLAISE PASCAL MAGAZINE
tmssoftware.com
GETTING STARTED WITH THE TMS PLANNER FOR FIREMONKEY PAGE 2/5

This inserts an item on todays' date between 14h00


& 16h00. As an extra, the item is programmatically
selected, the timeslot where the item is placed is
retrieved and the TTMSFMXPlanner is vertically
programmatically scrolled to the position of the
item.

The user can drag the item by click & drag on


the left side trackbar on a desktop system or by
touch and drag on a mobile device.
By grabbing the top or bottom trackbar, the item
can be sized. On a mobile device, for sizing
handy size-handlers are displayed for the
selected item that help sizing with touch as the
size-handler (arrow in this case) is a larger touch
sensitive area for the finger.
Notice that helper hints also appear during
sizing, indicating the start and end time while
sizing. The application is notified of items being
moved or sized via various events like for
example OnAfterItemSize,
Overview of properties of an item OnAfterItemMove from where the new start
in the TTMSFMXPlanner and end time can be retrieved.
GETTING STARTED
Drop a TTMSFMXPlanner instance on the form
and you immediately see a view for 24hrs for 3
days. On a default TTMSFMXPlanner, you also
see one item already added and a yellow line
indicating the current machine time.

To programmatically create a new item,


following code can be used:
By default, the TTMSFMXPlanner is smart
Var
it: TTMSFMXPlannerItem;
enough to display the size handlers only for
pc: TTMSFMXPlannerCell; mobile touch based devices, but it can be enabled
begin for desktop as well via setting
// create the new item TTMSFMXPlanner.Interaction.SizeMode
it := TMSFMXPlanner1.Items.Add;
to psmMobile instead of psmAuto.
it.StartTime := Int(Now) + EncodeTime(14,0,0,0);
it.EndTime := Int(Now) + EncodeTime(16,0,0,0); The size handlers itself are PNG images and can
it.Title := 'New item'; also be customized under class property
it.Text := 'Description'; TTMSFMXPlanner.ItemAppearance with
// programmatically select the item SizeHandlerDownBitmap and
TMSFMXPlanner1.SelectItem(it.Index); SizeHandlerUpBitmap.
// determine the timeslot where the item is placed
pc :=
TMSFMXPlanner1.DateTimeToCell(it.StartTime);
// scroll the planner to the timeslot where the item is
TMSFMXPlanner1.ViewRow := pc.Row;
end;

Issue Nr 4 2015 BLAISE PASCAL MAGAZINE productivity software buiding blocks 23


tmssoftware.com
GETTING STARTED WITH THE TMS PLANNER FOR FIREMONKEY PAGE 3/5

To allow the user to insert new items via the user Similarly, we can setup the TTMSFMXPlanner to
interface, various options exist. First, an item canautomatically create and edit items on the selected
be inserted in the selected area from an external time slots when pressing the INS key by setting
button with code: TTMSFMXPlanner.Interaction.
var keyboardInsertMode to
it: TTMSFMXPlannerItem; pkimSelection or
begin
it := TMSFMXPlanner1.Items.Add;
pkimSelectionDialog.
it.StartTime := In a similar way, via settings
TMSFMXPlanner1.CellToDateTime(TMSFMXPlanner1.Selection.StartCell); under TTMSFMXPlanner.
it.EndTime := TMSFMXPlanner1.CellToDateTime(MakeCell( Interaction,
TMSFMXPlanner1.Selection.EndCell.Col,
it can be configured how items
TMSFMXPlanner1.Selection.EndCell.Row + 1));
end; are edited with mouse or
keyboard interaction.
TTMSFMXPlanner.
NOTE the increment of 1 for the Interaction.MouseEditMode defines
Selection.EndCell to retrieve the time at the whether the item goes in edit mode after a
end of the last timeslot in the selection. single click, double click or single click on an
Alternatively, with a simple property we can already selected item.
instruct the TTMSFMXPlanner to automatically When TTMSFMXPlanner.Interaction.
create an item after selection with KeyboardEdit = true, pressing F2 starts
TTMSFMXPlanner.Interaction. editing for the selected item.
MouseInsertMode = mimAfterSelection. The type of editing, i.e. in-place editing or editing
When an item is created this way, the via a popup dialog is chosen with
OnAfterInsertItem is triggered when the TTMSFMXPlanner.Interaction.
item is created and from there the item can further UpdateMode set to pumInplace or
customized: pumDialog.
procedure TForm1.TMSFMXPlanner1AfterInsertItem(Sender: TObject;
AStartTime,
AEndTime: TDateTime; APosition: Integer; AItem: TTMSFMXPlannerItem);
begin
AItem.Title := 'Insert';
end;

Or a step further is to automatically bring up an TIMELINE MODES AND RESOURCES


editor dialog for the new created item and this is With this default setup, the TTMSFMXPlanner
achieved by setting shows a multiday view with 24hrs for each day.
TTMSFMXPlanner.Interaction.MouseIn The number of days in this mode is determined by
sertMode = pmimDialogAfterSelection TTMSFMXPlanner.Positions.Count.
Within the 24hrs timeline, the default setting is
that time between 8h00 and 20h00 is considered
active time and displayed in 'Active' color whereas
the inactive time is displayed in 'Inactive' color,
configured respectively with
TTMSFMXPlanner.Fill.Fill.Color and
TTMSFMXPlanner.InActiveFill.Fill.Color.

Displayed time and active time can be easily


changed with
TTMSFMXPlanner.TimeLine.DisplayStart,
TTMSFMXPlanner.TimeLine.DisplayEnd,
TTMSFMXPlanner.TimeLine.ActiveStart,
TTMSFMXPlanner.TimeLine.ActiveEnd
properties.

productivity software buiding blocks


24 Issue Nr 4 2015 BLAISE PASCAL MAGAZINE
tmssoftware.com
GETTING STARTED WITH THE TMS PLANNER FOR FIREMONKEY PAGE 4/5

Many other timeline modes are built-in also In the TTMSFMXPlanner modes where multiple
and set with resources come into play, the resources are setup
TTMSFMXPlanner.Mode: via a TTMSFMXPlannerResource collection
pmDay: under TTMSFMXPlanner.Resources.
single day, multiple resources By default, there are already 3 resources added
viewpmMultiDay: but this can be easily changed to the number of
multiple day view resources required. In a simple multiresource
pmMultiDayRes: mode like the pmHalfDayPeriod mode in the
mixed multiple day / resources view screenshot above, when
pmMultiResDay: TTMSFMXPlanner.Positions is set to 3,
mixed multi resource / multiple day view it will list in the header for each position the
pmDayPeriod:
resource description found under
multiday per day timeline with TTMSFMXPlanner.Resources or when for a
multiresource view
position no resource collection is defined,
pmHalfDayPeriod:
it will get the description Position X.
multiple day per halfday timeline with
Items in the TTMSFMXPlanner are bound to a
multiresource view
pmMonth: resource via the
per month and per day with multiresource view TTMSFMXPlannerItem.Resource property.
pmMultiMonth: multiple months, single
resource view
pmCustom: custom timeline view

TTMSFMXPlanner in mode pmHalfDayPeriod CONNECTING TO THE CLOUD


showing 3 resources
The TTMSFMXPlanner can, in combination with
the TMS Cloud Pack for FireMonkey
(http://www.tmssoftware.com/site/t
msfmxcloudpack.asp), be used to view or
edit Microsoft cloud calendar or Google cloud
calendar.

Issue Nr 4 2015 BLAISE PASCAL MAGAZINE productivity software buiding blocks 25


tmssoftware.com
GETTING STARTED WITH THE TMS PLANNER FOR FIREMONKEY PAGE 5/5

This is done via a non-visual adapter component CONCLUSION


TTMSFMXPlannerLiveAdapter or With this brief introduction of the TMS Planner for
TTMSFMXPlannerGoogleAdapter. Drop this FireMonkey, we have barely scratched the surface
of the sheer number of capabilities and features.
non-visual component on the form and connect
From appearance details to details of behavior,
it to TTMSFMXPlanner.Adapter. editing to configurations of timelines, current time
Depending on the cloud calendar you want to display, overlap, everything is customizable to
connect to, drop a TTMSFMXCloudGCalendar fine-tune the TTMSFMXPlanner to the particular
or TTMSFMXCloudLiveCalendar (from requirements of your planning & scheduling
TMS Cloud Pack for FireMonkey) applications. We invite you to look at demos, trial,
instance on the form and connect it to the tips and developer guide at
http://www.tmssoftware.com/site/
LiveCalendar or GoogleCalendar property of the
tmsfmxpack.asp
TTMSFMXPlannerLiveAdapter or
TTMSFMXPlannerGoogleAdapter
respectively.
productivity software buiding blocks
The first step is to connect to the cloud calendar
and retrieve the available calendars.
After selecting a calendar, getting the events from
tmssoftware.com
the cloud calendar in the TTMSFMXPlanner is as
easy as setting the calendar ID and setting the About the author
property Active = true: Bruno Fierens
Studied civil electronic engineering at university of
TMSFMXPlannerGoogleAdapter1 . CalendarID := Ghent, Belgium (1987-1992) and started a career as
TMSFMXCloudGCalendar1 . Calendars [ idx ]. ID ; R&D digital hardware engineer. Besides the fascination
for electronics, Bruno Fierens set the first steps in
TMSFMXPlannerGoogleAdapter1.Active := true; programming with Turbo Pascal v3.0 and used all
Borland Pascal & Delphi versions since that time.
In 1996, he founded TMS software for the activity of
Default, the item properties StartTime, application and component development with Delphi.
EndTime, Title, Text, Key are TMS software became Borland Technology Partner in
synchronized with the cloud calendar event 1998, developed Delphi Informant award-winning grid
properties. & scheduling components and now has an
To synchronize more properties, the adapter international team of software developers working on
a large portfolio of components.
offers the event OnGCalendarItemToItem
Bruno Fierens is from 2012 Embarcadero MVP and
and OnItemToGCalendarItem (in case of the frequent speaker at Delphi conferences world-wide.
Google cloud calendar ). He does and oversees VCL, IntraWeb, .NET and
This event handler demonstrates how the item's FireMonkey component development.
color can be mapped on the Google cloud

procedure TForm1.TMSFMXPlannerGoogleAdapter1GCalendarItemToItem(
Sender: TObject; GoogleItem: TGCalendarItem; Item: TTMSFMXPlannerItem);
begin
case GoogleItem.Color of
icBlue : Item.Color := claBlue;
icGreen : Item.Color := claGreen;
icRed : Item.Color := claRed; i
cYellow : Item.Color := claYellow;
end;
end;

The adapter further automatically takes care of


updating, insert, deleting events on the cloud
calendar in sync with manipulations on the
TTMSFMXPlanner control.

productivity software buiding blocks


26 Issue Nr 4 2015 BLAISE PASCAL MAGAZINE
tmssoftware.com
BLAISE 2015
MAPPING USING DELPHI BY PETER VAN DER SMAN PAGE 1/5
starter expert
On internet you can find plenty of examples
Delphi doing is. The download with this article has my
own version. It is just a first start. Your options
This article describes how to build maps using are near to endless. Playing with all options you
Delphi. The good news is: we don't have to order can get your map just as you want to have it.
the latest and most extensive version to do this, Enough work for a rainy Sunday afternoon.
we can just do it with an older version we
happen to have. Even your Delphi 6 will do fine.

BUILDING STATIC MAPS.


To build a static map we can use GoogleAPI, see
https://developers.google.com/maps/
documentation/staticmaps/index
The following URL can be uses to order the
roadmap to Delphi:
http://maps.google.com/maps/api/
staticmap?center=Delfi&size=640x640

You use this URL just using your browser.


Delphi comes in sight when we want to embellish
the map. For instance we could choose for a
satellite view instead of the default roadmap.
We may want to add layers, mark special
points, add our own track or completely restyle
the map. You can do it all and all the information
can be found in the reference.
You can still use your browser. The thing is Figure: Map1.2: the roadmap to Delfi, hybrid view
you'll probably end up with typing errors in the
very long URL you need. BUILDING DYNAMIC MAPS.
It's a lot easier to build the desired URL using Static maps can be handy when you're abroad and
Delphi. After building the URL you can of course you don't want to make your provider too happy
send it to the browser, but why not getting the using then online-navigation option. Of course we
map using Delphi and then show it directly on don't have these problems at home so we can do as
your form. we want without receiving unpleasantly high bills
afterwards. For building static maps again we can
use Google:
https://developers.google.com/maps
/documentation/javascript/reference
https://developers.google.com/maps
/documentation/javascript/examples

These links show clearly we will have to deal with


Javascript. We are in luck: the examples can be
shown including the full HTML-code needed to get
things done. Saving it in a file and loading this in
your browser will provide your desired map.
Combining the examples allows you to build any
map you like.

Inside Delphi we can load the HTML-code into a


TWebbrowser component. Just like the static
maps we can then adjust the map in the way we
like. But using dynamic maps we can do a lot more:
it is a lot easier to position the map, zoom in or
Figure 1: Map 1.1: the roadmap to Delfi, using Delphi
zoom out, locate the position of the mouse in map-
coordinates, enter into thestreetviewmode,
and good many more.

28 Issue Nr 4 2015 BLAISE PASCAL MAGAZINE


MAPPING USING DELPHI PAGE 2/5
In my example program I load the HTML-code
from a TMemo and then pass it to a
TWebbrowser. Of course this looks ugly but it
has an advantage when testing the code.
We can now easily change the (HTML /Javascript)
code and reload the map and see what the results
are, without changing forms or even applications.
Of course it has a drawback: closing your
program will result in a loss of all changes.
But occasionally this will be an advantage!

Figure3:
Map 2.1: Dynamic map of Delfi

Figure 4: Map 2.2: Streetview inside Delphi

Issue Nr 4
3 2015 BLAISE PASCAL MAGAZINE 33
29
MAPPING USING DELPHI PAGE 3/5
In order to control the map inside of Delphi we MAPPING USING COMPONENTS
need to know how to call a Javascript routine in While building dynamic maps you'll soon come
the webpage our Webbrowser component is to the conclusion that it's a lot of work to get
currently showing. For the newer versions of things right, and very error-prone too. When you
Delphi you can use the procedure wonder if it would be possible to convert it to a
EvaluateJavaScript. That is if you're using FMX. handy Delphi component you're in luck. Xavier
For some unknown reason this functionality is Martinez Garsaball has taken the initiative to
not available for the VCL-component. build a complete component-set and make it
available to us. You can download it at:
So even adding it in a future version will not
http://www.cadetill.com/gmlib_en/
solve your problem as Embarcadero most likely
won't give you an update for your current, The components come with full source code and
somewhat older, version. instructions how to install them (for Delphi 6 and
higher). The base component is called
Luckily we can find examples how to do it on TGMMap. This is not, as you tend to expect, an
the internet. In the example in the download I adapted version of a TWebbrowser, but a
implemented the procedure using a helper, standalone component that connects to a
so now we can use is just as if it was embedded TWebbrowser component which you have
inside the TWebbrowser component. dropped on your form.
Using this procedure we have the possibility Furthermore there is a load of component to
to call the right Javascript and manipulate the simplify tasks like adding your own track to
map as we want. Just like with static maps we the map. In most cases these components have a
now can change the view, put all kinds of layers reference to the Google-documentation, another
on and off, and again many more, as long as we way to find out where they can be meant for.
have added the Javascript functionality needed to Besides these components the download contains
do to accomplish it. an example program MegaDemo. It gives a
But this procedure doesn't return any decent insight in the plenty of possibilities of the
information to us. Knowing where we, component set.
For too many to describe in the context of this
geographically speaking, did click on the map
article. I'll pick out just one: adding your own
could of course be handy. Again we can find
track . Using a TPolyLine allows you to
examples how to do this. Most writers write the
show a series of geographical coordinates on the
information from Javascript to a hidden
map. The MegaDemo already shows two
inputbox in the HTML context. Then search
examples.
inside Delphi for this inputbox and then read the
(text)information. To do it you need to know But of course it's more fun to show your own
about the internals of the TWebbrowser. walk on the map. As a matter of fact I rarely go
The kind of things you don't really want to know. outdoor without my GPS-unit so easy enough
I added a function in the earlier mentioned to find one to use, even in Barcelona, the location
helper, so now you can read the inputbox using shown when MegaDemo is started. But how to
just one simple statement. load it? Unfortunately this is not worked-out in
A few writers use a more direct way of retrieving MegaDemo as it is just a Demo!
data. The following (example) code can be used to So we have to code this ourselves. After some
read an existing Javascript variable directly: thinking and inspecting the code it's obvious
where we should add it, in PolylinesFrm.
Var v :OleVariant;
MyJavaX :int32;
There I added a button to add a track from a
begin external file. But how to read a file with
v := WebBrowser1.Document; geographical information in Delphi.
MyJavaX := v.parentWindow.myX; The problem is there exist quite a lot of different
end; formats. For a few I use myself I have my own
Code example: reading a Javascript-Variabele
parser but for the vast lot of them not. Luckily
enough there is a program called GPSBabel
The example code reads then variable myX. that can be used to convert most of the formats to
Be careful, all inside of Javascript is casesensitive. the format you happen to need.
So there exist both variables myX en myx. I used it to convert my track to a simple csv-
In consequence we must use the right case for our file containing a list of geographical
variable, even inside Delphi. coordinates only. Just beware of decimal comma
The code in the download contain an example or point or comma problems and the track is
where I use both ways to retrieve the same loaded.
information.

30 Issue Nr 4 2015 BLAISE PASCAL MAGAZINE


MAPPING USING DELPHI PAGE 4/5

Figure 5: Map 3.1: Walk in Barcelona shown using the


adapted GMLib Mega Demo.
The code I used for loading the track can be found
in the download at
TPolylinesFrm.BtnAddCSVClick.
MegaDemo suggests it can show a height profile
for any arbitrary track. Could this be true? So,
besides the coordinates my GPS-unit also stores
the height of my current position. So we can to
compare the measurement of the GPS-unit with the
results the map returns:

Figure 6.
Height measurement from the GPS-unit

Issue Nr 4 2015 BLAISE PASCAL MAGAZINE 31


MAPPING USING DELPHI PAGE 5/5

Figure : 7 Height measurement using the map


So the result is astonishing!
The math is not total but it comes close to it.
Did I mention the walk was mostly using paths
on a bushy hill? One gets the impression you can
first set out the track you want to walk, check its
profile and then adjust the track if it doesn't
match with the current physical condition just
until the profile is acceptable.

HOW TO CONTINUE...
This article introduces some ways to build a map
using Delphi. The effort made by cadatill opens
the way to a vary many possibilities. Let this
rainy Sunday afternoons come! Wouldn't this be
enough, also offline there is still a lotto explore.
Thanks to OpenStreetMap nowadays there are
maps available for the whole world, very
complete and accurate. The download contains
some links to give you a start.

32 Issue Nr 4 2015 BLAISE PASCAL MAGAZINE


LOG, DEBUG AND AUDIT THE KBMMW WAY
BY KIM MADSEN
COMPONENTS
DEVELOPERS 4
starter expert The system log manager use the system's default
Delphi logging mechanism (OutputDebugString on
Windows, NSLog on IOS , android_log_write
One annoying thing in Delphi during the years has
on Android and syslog on Linux/Unix like
been the lack of a centralized, customizable, single
systems). I will show later, how to replace the
style logging and auditing mechanism with enough
flexibility and high enough performance that it also default log manager with another one.
works for bug hunting in live applications.
Various 3rd party products have taken that lack of A NUMBER OF LOG MANAGERS ARE INCLUDED IN
KBMMW:
functionality up, but not one of them is as flexible
and fast as the one kbmMW v. 4.82.00 comes
IkbmMWSystemLogManager
equipped with.
In the later years, the problem has worsened, The default system log manager
because Delphi and C++Builder supports new as described above.
platforms, which themselves have their own (not
always so great) way of logging, and none of the IkbmMWLocalFileLogManager
platforms have any way to register audit data, A log manager that stores log and audit in one
which is crucial for many systems, especially the single file, or splits log into one file and audit
ones handling person critical data. to a separate file.
This article is about how to utilize kbmMW v.
4.82.00 Enterprise or Professional Edition to log,
IkbmMWTeeLogManager
debug and audit in one simple, elegant framework.
A log manager that forwards log data to two
THE FRONTEND AND THE BACKEND other log managers. This is useful if you for
The kbmMW logging framework consists of two example want to both store the log in a file,
parts, the frontend towards the developer, and send it off to another computer.
and the backend which we call the log
manager. IkbmMWProxyLogManager
The frontend is provided to the developer A log manager that forwards log data
through an interfaced (IkbmMWLog) instance of to another log manager. It is in itself not
TkbmMWLog. The moment you add the unit terribly interesting, however it can be used
kbmMWLog to your uses clause in Delphi (or include for creating a custom log manager that
kbmMWLog.hpp in your C++ application), an intercepts the log process, and do something
accessible instance of TkbmMWLog will already be with it before sending it off to
available for you via the global variable name Log. another log manager.
As Log is an interface, it is automatically
reference counted, and can be used wherever you The IkbmMWServerLogManager
find a need for logging, timing or auditing is a proxy log manager.
something.
It is also thread safe, so it can be used in threads as IkbmMWClientLogManager
you see fit. Enterprise Edition only. It forwards log via
a designated WIB client or server side
The frontend always communicates directly
with the backend (the log manager). It is the log IkbmMWServerLogManager
manager that determines how the log is processed. Enterprise Edition only. It subscribes for
WIB LOG events coming in on a designated
Is it output via the systems' own debugging client or server side transport.
mechanisms like OutputDebugString, NSLog
or Android's logging mechanism, or is the log info IkbmMWLogManager.
put into a file, or is it sent off to another server The system log manager use the system's
which will then do something about the log data, default logging mechanism
or is it a combination of multiple log managers (for (OutputDebugString on Windows,
example storing locally and at the same time sending to a NSLog on IOS, android_log_write
remote machine). on Android
The default log manager of the Log instance, and syslog on Linux/Unix like systems).
is the system log manager I will show later, how to replace the default
TkbmMWSystemLogManager - log manager with another one.
which implements the interfaces
IkbmMWSystemLogManager and
IkbmMWLogManager.

Issue Nr 4 2015 BLAISE PASCAL MAGAZINE COMPONENTS


DEVELOPERS 4 33
LOG, DEBUG AND AUDIT THE KBMMW WAY PAGE - 2/7

IkbmMWSystem
LogManager

IkbmMWLocalFile
LogManager

A log manager 1

IkbmMWTee
LogManager
Log (IkbmMWLog) A log manager 2

IkbmMWProxy
LogManager A log manager

IkbmMWClient IkbmMWServer
LogManager LogManager

kbmMW supports a number of different logging mwltAudit


types as specified in the TkbmMWLogType
Useful if you want to audit some situation.
enumeration:
For example if you want to register that
mwltDebug someone have accessed person sensitive
Useful for debug type logging. Stuff that you information or have logged into the system.
generally do not want to collect when When implementing an audit functionality
the system is running in production mode. in software, the audit should be detailed
You can however always, at runtime, enough to make it possible to do an autopsy
choose if you want to collect debug on the system after the fact,
information or not. and recognize who have done
what with critical/sensitive data.
mwltInfo
Useful for general information type logging. When logging something, it's optionally also
Stuff that is not in anyway critical, but you possible to add a level for which this log is
would like to have logged anyway. interesting.
kbmMW's log system defines a number of log
mwltWarning levels in the enumeration TkbmMWLogLevel:
Useful if something that can't be characterized
as an error, but could be of concern to someone. mwllBasic
For example that something that optionally This is of interest for all log managers which
could be enabled (and often is enabled) is have interest in the given log type.
disabled.
mwllNormal
mwltError This the standard log level used when
Useful if you want to log some error situation nothing has been specified.
that has occurred, as long as it does not affect
the system's ability to continue to operate. mwllDetailed
This is only of interest for log managers
mwltFatal that specify interest in this level or higher
Useful if you want to log an error situation for the given log type.
that is of such magnitude that the system
no longer can continue to operate.

34 COMPONENTS
DEVELOPERS 4 Issue Nr 4 2015 BLAISE PASCAL MAGAZINE
LOG, DEBUG AND AUDIT THE KBMMW WAY PAGE - 3/7
mwllAdvanced THE FRONTEND
This is only of interest for log managers that The Log object contains a number of methods in
specify interest in this level or higher for the various categories.
given log type. The basic category consists of the methods
mwllHighest Info(..), Debug(..), Warning(..),
This is only of interest for log managers that Error(..), Fatal(..) and Audit(..).
specify interest in this level or higher for The functions are overloaded to allow for
the given log type. various arguments starting with a simple string,
to providing a timestamp, an origin, a format
Typically you would use the levels in combination and a number of values. Use the version that
with for example debug to log relevant coarse makes sense for your purpose.
grained debug info at normal level Example:
and more fine grained and detailed Log.Info('This is some info');
info at a higher log level. This way Log.Debug('This is some debug info');
Log.Warn('This is a warning');
you can, at runtime, indicate on the Log.Error('This is an error');
various log managers, what level of Log.Fatal('This went very bad: %d/%s',[10,'shit happens']);
log info you want the log manager Log.Audit('This is to be stored as audit info');

to register. Finally kbmMW's log framework


currently supports a number of log data types Log.Debug(TkbmMWLogLevel.mwllDeta
(which will probably be extended over time). iled,'This is some more detailed
The enumeration TkbmMWLogDataType debug info');
provides these values:
The extended category of methods consists of a
mwldtString generic Log method, which takes a number of
The data to log consists of textual string data. arguments. Eg.
mwldtException
The data to log is coming from an exception Log.Log(TkbmMWLogType.mwltDebug,T
kbmMWLogLevel.mwllNormal,'This is
that however is handled somewhere in the
some info');
application.
mwldtUnhandledException
Some of the overloaded Log methods include an
The data to log is coming from an exception
AOrigin argument. It is a string that should
that is not handled by the application.
mwldtXML (when relevant) contain information identifying
the client (for example IP address or similar
The data to log consists of XML.
mwldtStream information).
The data to log consists of binary data
from a stream. Further the extended category includes
mwldtBytes LogXML, LogStream, LogBytes,
The data to log consists of binary data LogStack and LogException.
from a byte array.
mwldtStack LogXML
The data to log is a stack trace. Log XML data, either directly from a string,
or from a TkbmMWDOMXML
The log data type enumeration is never used or IkbmMWDOMXML instance.
directly in the frontend by the developer, LogStream
but is given implicitly by the various log methods Log stream data. It will be handled as
used. On the log manager, the data type can be binary data.
LogBytes
used for filtering out uninteresting information,
and is also used by the log manager to figure out Log TBytes (array of byte) data. It will be
how to represent the log data. handled as binary data.
For example will binary data be represented as
a nice 32 column hex dump with printable
characters shown to the right, when the debug
type is any type but audit, while when storing as
audit data, the data is handled as base 64 encoded
data.

Issue Nr 4 2015 BLAISE PASCAL MAGAZINE COMPONENTS


DEVELOPERS 4 35
LOG, DEBUG AND AUDIT THE KBMMW WAY PAGE - 4/7
LogStack NOTICE that although both kbmMW
Log the current stack trace. Professional Edition and kbmMW Enterprise
See further down about stack traces. Edition supports reading a map file, kbmMW
LogException Enterprise Edition is significantly faster (10-
Only to be used in an except/catch situation. 20x) at doing that, since it uses optimized
You can provide the exception object as an features only available in Enterprise Edition, to
argument, or leave it out, in which case speed up the disk access on Windows.
kbmMW will figure out the exception object by
itself. An exception will automatically also be kbmMW loads the map file the first time it
accompanied with a stack trace. needs it and that may result in a noticeable
delay at that particular point (especially when not
kbmMW contains automatic stack trace using kbmMW Enterprise Edition). You can force it
functionality for Win32 and Win64. to load the map file at a time of your choice, by
The stack trace will at most contain the last 60 including the unit kbmMWDebugMapInfo,
entries on the stack, but can be limited to less and somewhere in your source code put the
than that. It can also be directed to skip top following code:
elements from the stack (because they are usually TkbmMWDebugMapInfo.Global
the log calls themselves).
To make the stack trace really useful, compile This will force kbmMW to load the map file at
your application with a detailed map file, and that particular time.
place the .map file next to the executable. This is an example of a stacktrace collected
due to an exception that has been thrown:
2015-05-26T14:32:14.899+02:00 : Error : 315736/318408 : Thrown an exception
Exception
Some exception was raised
Address (hex): 00652ED9
[System.SysUtils(System.SysUtils.pas) : Line 21864]
System.SysUtils.Exception.RaisingException
[System(System.pas) : Line 20103] System.@RaiseExcept
[Vcl.Controls(Vcl.Controls.pas) : Line 7362] Vcl.Controls.TControl.Click
[Vcl.Controls(Vcl.Controls.pas) : Line 10081] Vcl.Controls.TWinControl.WndProc
[Vcl.StdCtrls(Vcl.StdCtrls.pas) : Line 5165] Vcl.StdCtrls.TButtonControl.WndProc
[Vcl.Controls(Vcl.Controls.pas) : Line 10148] Vcl.Controls.DoControlMsg
[Vcl.Controls(Vcl.Controls.pas) : Line 10081] Vcl.Controls.TWinControl.WndProc
[Vcl.Forms(Vcl.Forms.pas) : Line 4428] Vcl.Forms.TCustomForm.WndProc
[Vcl.Controls(Vcl.Controls.pas) : Line 9786] Vcl.Controls.TWinControl.MainWndProc
[System.Classes(System.Classes.pas) : Line 16883] System.Classes.StdWndProc
[Vcl.Controls(Vcl.Controls.pas) : Line 10120] Vcl.Controls.TWinControl.DefaultHandler
[Vcl.Controls(Vcl.Controls.pas) : Line 10081] Vcl.Controls.TWinControl.WndProc
[Vcl.StdCtrls(Vcl.StdCtrls.pas) : Line 5165] Vcl.StdCtrls.TButtonControl.WndProc
[System.Classes(System.Classes.pas) : Line 16883] System.Classes.StdWndProc
[Vcl.Forms(Vcl.Forms.pas) : Line 10352] Vcl.Forms.TApplication.ProcessMessage

kbmMW will then automatically load it, All log entries includes a timestamp with
and provide line number and source code timezone information, the log type, a process id
information in the stack trace. / thread id and an explanatory text. In addition
If the map file is not available, only the raw more lines may be added like a stack trace,
hexadecimal source address for the call will be binary dump etc.
presented.
2015-05-26T14:32:11.817+02:00 : Info : 315736/318408 : This is some info
2015-05-26T14:32:11.836+02:00 : Warning : 315736/318408 : This is a warning
2015-05-26T14:32:11.836+02:00 : Error : 315736/318408 : This is an error
2015-05-26T14:32:11.837+02:00 : Fatal : 315736/318408 : This went very bad: 10/shit happens
2015-05-26T14:32:13.155+02:00 : Info : 315736/318408 : Some XML
<start></start>
2015-05-26T14:32:13.156+02:00 : Debug : 315736/318408 : c:\windows\write.exe
00000000 : 4D 5A 90 00 03 00 40 00 00 00 00 00 00 00 MZ ..... ...... ....... @.......

36 COMPONENTS
DEVELOPERS 4 Issue Nr 4 2015 BLAISE PASCAL MAGAZINE
LOG, DEBUG AND AUDIT THE KBMMW WAY PAGE - 5/7
The last category of log methods is the timing All log managers have these properties available:
methods. They are powerful for performance
check specific parts of your application. LogTypeFilter
Timing a part of code is done by starting a named of type TkbmMWLogTypes,
timer, and querying it at relevant times and LogDataTypeFilter of type
finally ending it when it's no longer needed. TkbmMWLogDataTypes and
The way it has been implemented in kbmMW, LogLevelFilter
they take up very few resources, while being of type TkbmMWLogLevels.
extremely fast and with the highest precision
available on the platform. Default LogTypeFilter is set to include all
There is a limit of 100 concurrent active timers. log types, LogDataTypeFilter to include all
You can name them as you see fit. data types and LogLevelFilter to include all
You start time measuring by (specifying the timers log levels.
name as A):
Log.TimeStart('A'); However let's say you only want to log errors
and fatal errors in the default log manager, you
And can optionally log time lapse info by: do like this:
Log.TimeLapse('A','Time taken
until this point'); Log.Log.LogTypeFilter:=[TkbmMWLogType.mwltEr
LogTypeFilter:=
[TkbmMWLogType .mwltError,TkbmMWLogType.mwltFatal];
ror,TkbmMWLogType.mwltFatal];
You must always end a timer by:
Log.TimeEnd('A','Time taken until All other logs are now ignored by the log
this point');
manager.
This will free up the timer slot which can then be CHANGING THE LOG MANAGER
reused by another named timer. For now we have used the system log manager.
TimeLapse and TimeEnd both logs and Changing to use a local file log manager is easy
returns the measured time in msecs.
var filelogmgr:IkbmMWLocalFileLogManager;
begin
If you want to get the precise time, without filelogmgr:=
making a log entry, you can use: TkbmMWLocalFileLogManager.Create(
Msecs:=Log.TimeEnd('A'); '.\log.txt','.\audit.txt');
filelogmgr.DeleteOldLog:=true;
filelogmgr.DeleteOldAudit:=true;
If you do not provide an explanatory text to filelogmgr.FlushInterval:=0;
TimeEnd, it assumes you want to end the timer Log.LogManager:=filelogmgr;
and return the time taken, without logging
anything. In this case we have specified that the log should
The log entries made using the be collected in two local files. All audit logs
TimeLapse/TimeEnd methods are default should end up in audit.txt, while all
registered as type mwltDebug and level remaining logs should end up in log.txt.
mwllNormal. Each log manager has a number of properties
If you want the timings to be logged as a different that can be set. The local file log manager has
type or a different level, you can use other one, called FlushInterval.
variants of TimeLapse/TimeEnd methods Its default set to flush data to disk when more
where the log type and log level can be given. than 10 seconds have passed since last log, when
a new log entry is added.
FILTERING LOGS Setting it to 0, force it to always flush each single
Let's say that you have a lot of debug logging
logging to disk.
around in your code, and you want to filter it out
from your log presentation, without having to
remove or comment out all the log statements.
You can do that easily by manipulating properties
on the log manager.

Figure 10

Issue Nr 4 2015 BLAISE PASCAL MAGAZINE COMPONENTS


DEVELOPERS 4 37
LOG, DEBUG AND AUDIT THE KBMMW WAY PAGE - 6/7
What if you want both to write log to disk, and to
output it to the system log?
We bring in the tee log manager.
var
filelogmgr:IkbmMWLocalFileLogManager;
systemlogmgr:IkbmMWSystemLogManager;
teelogmgr:IkbmMWTeeLogManager;
begin

filelogmgr:=TkbmMWLocalFileLogManager.Create('.\log.txt','.\audit.txt');
filelogmgr.DeleteOldLog:=true;
filelogmgr.DeleteOldAudit:=true;
systemlogmgr:=TkbmMWSystemLogManager.Create;

teelogmgr:=TkbmMWTeeLogManager.Create(filelogmgr,systemlogmgr);
Log.LogManager:=teelogmgr;

First we define a system log manager and a local On the log server side, you will need to do
file log manager, and then we define a tee something similarly.
manager, which sends logs to the var
two other log managers. fm:IkbmMWLocalFileLogManager;
lm:IkbmMWServerLogManager;
begin
fm:=TkbmMWLocalFileLogManager.Create('.\loginfo.txt',0);
lm:=TkbmMWServerLogManager.Create(fm);
lm.Transport:=kbmMWTCPIPIndyMessagingServerTransport1;
Log.LogManager:=lm;
REMOTE LOGGING
A next logical step is to want to send
log from a client to a server to centralize log The server log manager will automatically
somewhere. This feature is only available in subscribe for LOG events coming from the client
kbmMW Enterprise Edition, as it uses the WIB log manager, and will forward those to a local
publish/subscribe transport. file log manager.
On the log client, we define a client log
manager. That log manager can be connected to All local logging on the server via the Log
either a client or a server WIB transport. methods, are also sent directly through the
Notice that the client log manager must be in the server log manager to the local file log manager
end where you use the Log command and and is thus interleaved with log from clients.
where you want that log to be shipped off to A couple of other properties are also available on
somewhere else. It probably is often in an the log managers.
application where you use a WIB client side
transport, but it doesn't necessarily have to be. BinaryPrettyMode can be set to
mwlbpmDefault, mwlbpmBase64
var
lm:IkbmMWClientLogManager; or mwlbpmPretty.
begin It controls how binary data is output.
// Setup log manager for remote logging. In default mode, then audit data is
lm:=TkbmMWClientLogManager.Create;
handled as base 64, while other binary
lm.Transport:=kbmMWTCPIPIndyMessagingClientTransport1;
Log.LogManager:=lm; data is handled as pretty data
(nice 32 column hexdump).
Each time you use the Log methods, their You can force it to one or the other by setting this
output will automatically be sent via the property.
messaging system and thus be placed in the Enabled is default true. If set to false, then all
outbound queue until a connection is logs via this log manager is ignored.
established to the receiving end. The log system Options control various things like if the log
does not attempt to establish that connection system should dump process and thread id
automatically. (mwloProcessThreadInfo), thread name
(mwloThreadName) and if it should dump
handled exceptions
(mwloAutoLogExceptions).

38 COMPONENTS
DEVELOPERS 4 Issue Nr 4 2015 BLAISE PASCAL MAGAZINE
LOG, DEBUG AND AUDIT THE KBMMW WAY PAGE - 7/7
ASSERT BASED LOGGING FINAL NOTES
Delphi contains an intrinsic procedure called To use assert based logging, you will have to
Assert, that normally throws an exception if a ensure that
condition is false. It's designed to check for KBMMW_INSTALL_ASSERT_HANDLER is
logical values before use in an application, while defined in kbmMWConfig.inc, or alternatively
the application is compiled for debug. you can manually call
Typically when the application is compiled kbmMWLog_InstallAssertionHandler
for release, assert is disabled, which means the before use.
compiler completely avoids including code
related to the assert statement and functions If you have installed the assert handler manually
called that are part of arguments for the assert you MUST uninstall it too, before program exit
statement. by calling
kbmMW optionally takes advantage of this kbmMWLog_UnInstallAssertionHandler
feature. .

Similarly if you want kbmMW to handle your


Let's assume you have hundreds of Debug log
exceptions automatically, you will have to ensure
calls around in your application. Then let's
that KBMMW_INSTALL_EXCEPTION_HANDLER
assume that these Debug log calls takes some
is defined in kbmMWConfig.inc or
CPU cycles to prepare argument values for, and
kbmMWLog_InstallExceptionHandler is
make the actual call to the log Debug method,
called before an exception is to be handled by
and let's assume that you will never want to see
kbmMW, and that
the debug info in an application compiled in
kbmMWLog_UnInstallExceptionHandler
release mode.
is called before program shutdown.
In that case you need to avoid using the log As kbmMW is a modular framework, one can
Debug method, and instead use the Assert choose only to use its logging capabilities,
method. its XML capabilities, its JSON capabilities,
its serialization capabilities,
assert(false,MWDEBUG('Some debug happening'));
Example:
assert(false,MWINFO ('Some info happening' ));
its application server capabilities,
assert(false,MWERROR('Some error happening')); its database capabilities,
assert(false,MWSTACK('Getting a stack dump')); its stream storage capabilities,
its memory table or its async messaging
try capabilities etc without having to use all
raise Exception.Create('some exception'); other parts of the kbmMW framework.
except
assert(false,MWEXCEPT('Exception happened')); But obviously, you will get the best of the
end; best if you take the plunge and choose to
take advantage of all the kbmMW features
These examples show that calling assert with you need in your applications as all parts are
false, and a specially formatted string, which is designed to work in perfect harmony with
each other.
formatted via some kbmMW functions
(MWDEBUG, MWINFO, MWERROR, MWSTACK,
MWEXCEPT), will result in a regular kbmMW log.
Kim Madsen / C4D
However when the application is compiled with
assert disabled (typically release mode), then every
trace around the assert call is removed from the
executable, and thus not taking up valuable CPU
cycles.

If you use assert in other situations in your


application, it will work as you are used to.
COMPONENTS
DEVELOPERS 4
Issue Nr 4 2015 BLAISE PASCAL MAGAZINE COMPONENTS
DEVELOPERS 4 39
EXTREME PERFORMANCE
NOW FASTER THAN EVER!

- Now faster than ever!


- Improved publish/subscribe message queues
- Improved XML/JSON marshalling support
- Delphi/C++Builder/RAD Studio XE8
- Native high performance 100% developer Supports Delphi/C++Builder/RAD Studio 2009
defined application server with support for to XE8 (32 bit, 64 bit and OSX where applicable).
loadbalancing and failover kbmMW for XE5 to XE8 includes full support for
- Native high performance JSON and XML Android and IOS (client and server).!
(DOM and SAX) for easy integration with
kbmMemTable is the fastest and most feature rich
external systems in memory table for Embarcadero products.
- Native support for RTTI assisted object
marshalling to and from XML/JSON, now also - Easily supports large datasets
with new fullfeatured XML schema with millions of records
(XSD) import - Easy data streaming support
- High speed, unified database access - Optional to use native SQL engine
(35+ supported database APIs) with - Supports nested transactions and undo
- Native and fast build in M/D,
connection pooling, metadata and
aggregation /grouping,
data caching on all tiers range selection features
- Multi head access to the application server, - Advanced indexing features for
via AJAX, native binary, Publish/Subscribe, extreme performance
SOAP, XML, RTMP from web browsers,
embedded devices, linked application Warning!
servers, PCs, mobile devices, Java systems kbmMemTable and kbmMW
and many more clients
- Full FastCGI hosting support. Host PHP/Ruby
are highly addictive!
Once used, and you are hooked for life!
/Perl/Python applications in kbmMW!
- KBMMW V. 4.80 AMQP support
( Advanced Message Queuing Protocol)
- Added AMQP 0.91 client side gateway
support and sample.
- Updated StreamSec TLS transport plugin
component (by StreamSec).

COMPONENTS
4
- Improved performance on Indy TCP/IP
Client messaging transport for large number
of inbound messages.
DEVELOPERS
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.