blaise pascal magazine 40

48
BLAISE PASCAL MAGAZINE BLAISE PASCAL MAGAZINE BLAISE PASCAL MAGAZINE 40 40 40 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 A L 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 D E L P H I - S T E P H E N B A L L - I N T E R B A S E C H A N G E V I E W S XE 8 - D E L P H I - D E T L E F O V E R B E E K F R O M D E L P H I T O D E L P H I W H Y T H E N A M E D E L P H I D E L P H I - C A R Y J E N S E N - C L I E N T D A T A S E T S A N D FD M E M T A B L E S C O M P A R E D: P A R T 2 S T A R T W I T H F U N C T I O N T E S T I N G (M A X B O X) - M A X K L E I N E R D E L P H I - J E R E M Y N O R T H W O R K I N G W I T H B E A C O N S I N D E L P H I XE 8 D E L P H I P A W E L G L O W A C K I - I N T R O D U C T I O N T O F L A T B O X 2D P R I N T E D I S S U E P R I C E 1 5, 0 0 D O W N L O A D I S S U E P R I C E 5, 0 0

Transcript of blaise pascal magazine 40

Page 1: blaise pascal magazine 40

BLAISE PASCAL MAGAZINEBLAISE PASCAL MAGAZINEBLAISE PASCAL MAGAZINE

404040D 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 A L 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

D E L P H I - S T E P H E N B A L L - I N T E R B A S E C H A N G E V I E W S

XE 8 -

D E L P H I - D E T L E F O V E R B E E K

F R O M D E L P H I T O D E L P H IW H Y T H E N A M E D E L P H I

D E L P H I - C A R Y J E N S E N - C L I E N T D A T A S E T S A N D FD M E M T A B L E S C O M P A R E D: P A R T 2

S T A R T W I T H F U N C T I O N T E S T I N G (M A X B O X)- M A X K L E I N E R

D E L P H I - J E R E M Y N O R T H W O R K I N G W I T H B E A C O N S I N D E L P H I XE 8

D E L P H I P A W E L G L O W A C K I- I N T R O D U C T I O N T O F L A T B O X 2D

P R I N T E D I S S U E P R I C E € 1 5, 0 0D O W N L O A D I S S U E P R I C E € 5, 0 0

Page 2: blaise pascal magazine 40

CONTENTS

BLAISE PASCAL MAGAZINEBLAISE PASCAL MAGAZINE

Articles

Advertisers

Barnsten 11BetterOffice 36BLAISE PASCAL MAGAZINE 4Cary Jensen (Jensen Data Sytems) 30Components 4 Developers 48Computer Math & Games 4Daniel Teti 12FAST REPORT 22/23Raize Software 39Visuino MITOV 45

Issue Nr 2 2015 BLAISE PASCAL MAGAZINE2

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

BLAISE PASCAL MAGAZINEBLAISE PASCAL MAGAZINEBLAISE PASCAL MAGAZINE

M O T I O N

404040

Publisher: Foundation for Supporting the Pascal Programming Language in collaboration with the Dutch Pascal User Group (Pascal Gebruikers Groep)

© Stichting Ondersteuning Programmeertaal Pascal

Interbase Change Views

From Delphi to Delphi, overview of the Delphi history

Delphi - the city

Why the name Delphi?

Introduction to FlatBox2D for Delphi XE8

- By

- By Editor

- By Pawel Glowacki

Stephen P

P

P

P

P

ClientDataSets and FDMemTables Compared: Part 2 P

Start with Function Testing (maXbox) P

Working with Bluetooth beacons in Delphi XE8 P

Ball

- By Editor

- By Editor

- Cary Jensen

- By MaxKleiner

- Jeremy North

age 5

age 8

age 13

age 14

age 16

age 24

age 31

age 40

Page 3: blaise pascal magazine 40

3

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.

Copyright notice

EditorsPeter Bijlsma, W. (Wim) van Ingen Schenau, Rik Smit,Correctors Howard Page-Clark, James D. DuffTrademarksAll 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 [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-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]

Foundation for Supporting the Pascal Programming Language (Stichting Ondersteuning Programeertaal Pascal)

Editor - in - chiefDetlef D. Overbeek, Netherlands Tel.: +31 (0)30 890.66.44 / Mobile: +31 (0)6 21.23.62.68News and Press Releases email only to [email protected]

A Alexander B Peter Bijlsma, Dmitry BoyarintsevC Michaël Van Canneyt, Marco Cantù, D David Dirkse, Daniele TetiF Bruno FierensG Primož Gabrijelčič, Mattias GaertnerH Fikret HasovicJ Cary Jensen

Authors - Christian name in alphabethical orderAlexeev,

Stephen Ball,

L Wagner R. Landgraf, Sergey LyubeznyyK Max KleinerM Kim Madsen, Felipe Monteiro de CavalhoN Jeremy North,O Tim Opsteeg, Inoussa OuedraogoP Howard Page-Clark, S Rik Smit, Bob Swart,Z Siegfried Zuhr

Stephen Ballhttp://delphiaball.co.uk@DelphiABall

Peter Bijlsma-Editor peter @ blaisepascal.eu

Michaël Van Canneyt,michael @ freepascal.org

Marco Cantùwww.marcocantu.commarco.cantu @ gmail.com

David Dirksewww.davdata.nlE-mail: David @ davdata.nl

Daniele [email protected]

Bruno Fierenswww.tmssoftware.combruno.fierens @ tmssoftware.com

Primož Gabrijelčičwww.primoz @ gabrijelcic.org

Wim Van Ingen Schenau-Editor wisone @ xs4all.nl

Cary Jensenwww.jensendatasystems.comhttp://caryjensen.blogspot.nl

Wagner R. Landgrafwagner @ tmssoftware.com

Kim Madsenwww.component4developers

Jeremy Northjeremy.north @ gmail.com

Benno [email protected]

Detlef Overbeekwww.blaisepascal.euEmail:editor @ blaisepascal.eu

Howard Page ClarkE-mail: hdpc @ talktalk.net

Rik Smit-Editor rik @ blaisepascal.eu

Bob Swartwww.eBob42.com Bob @ eBob42.com

Max [email protected]

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

Issue Nr 2 2015 BLAISE PASCAL MAGAZINE

Page 4: blaise pascal magazine 40

BLAISE PASCAL MAGAZINEis proud to announce the first edition of David Dirkse’s book: COMPUTER & IN

MATHGAMES PASCAL

DAVID DIRKSEpresales at www.blaisepascal.eu/DavidDirkse/ComputerMath_Games.html

procedurevarbeginfor to dobegin

endend

;

:= ;

;

i 1 9

Page 5: blaise pascal magazine 40

5Issue Nr 2 2015 BLAISE PASCAL MAGAZINE

INTERBASE

BY STEPHEN BALLDelphi XE 7

expertstarter

CHANGE VIEWS

This is an article on InterBase Change Views and is intended to be a high level overview of the new powerful change view technology that is patent pending and part of InterBase. Following this post I plan to show more posts taking the concept of Change Views into the real world with some real application examples.

InterBase Change ViewsInterBase XE7 introduces a new way to track data changes to the database called Change Views.

Change Views are a new “subscription based” model allowing you to “subscribe” to data; once subscribed you are able to ask the database at a later time, spanning connections, for what has changed.

This is an especially cool, low cost way to reduce network traffic, mobile data costs and development time when tasked with keeping multiple remote database caches up to date. (especially if you have large tables to keep up dated).

Change Views reduce the upfront planning required, reduce the risk of errors and drastically make simpler the task of building in data change tracking..

Best of all change views has zero impact on database performance regardless of the number of subscribers!

Subscription & SubscribersA core concept to change views is that of Subscriptions and Subscribers. InterBase Change view allows multiple subscribers to a subscription.

A subscription is defined once and then can be connected to by multiple users. Once defined, you can control who can subscribe thanks to the InterBase inbuilt user security.

Subscriptions work at field level and can be defined to track either an entire table or multiple tables. Subscriptions can also be defined to track Inserts, Updates or Deletes (or a mix of)

Multiple devices per subscriberIn addition to allowing specific users to subscribe to data, you can use a single user to have multiple destinations that are subscribing. This allows a user to subscribe for different devices such as their Phone, Tablet, Laptop or for a single user to be used programatically to distinguish multiple sites – e.g. Office 1, Office 2 etc.

What Change Views are not!Change Views are not an auditing system. While you can track deleted records, Change View are about identifying what has changed without keeping every value that it has been. If you want to do that, then continue to use Triggers and logging tables for the values you need to audit.

InterBase® XE7 is a full-featured, high performance, encryptable, multiplatform and scalable relational database for developers who are looking to embed a low-cost, zero admin, lightweight secure database into their cross platform connected applications. With InterBase XE7 you get powerful access control, data change management, disaster recovery and journaling, as well as support for popular database drivers for increased deployment flexibility.

Creating a Change ViewIf you have ever spent time planning how to identify what data has changed, then change views is about to simplify the way you develop for ever!

Steps for creating a Change ViewRather than having to create and manage triggers to add records into log tables or planning additional date fields into your metadata (and hoping date & time changes don’t effect you) Change View are easily added to a project once the simplified architecture is complete.

There are two essential steps in creating a successful change view:

Defining the purpose of the Change View and the data you want to track.

Defining who can subscribe to the change view.

This is done using the “at” verb when connecting to the subscription.

Page 6: blaise pascal magazine 40

6 Issue Nr 2 2015 BLAISE PASCAL MAGAZINE

INTERBASE CHANGE VIEWS (CONTINUATION 1)

1 Creating a change viewLets start with a simple example. We want to keep our sales fulfilment application up-to-date with the latest stock and suppliers information. This data is stored in two tables, INVENTORY

and SUPPLIERS.

Example 1 – Multiple Tables

CREATE SUBSCRIPTION sub_stockON INVENTORY FOR ROW (INSERT, UPDATE, DELETE), SUPPLIERS FOR ROW (INSERT, UPDATE, DELETE)DESCRIPTION 'Track stock and supplier changes';

Subscriptions are created with the CREATE

SUBSCRIPTION statement followed by a

subscription name that you will need to use in SQL later on.The simple example tracks all columns in the tables INVENTORY and SUPPLIERS for Inserts,

Updates and Deletes.The description allows easy identification of the subscriptions purpose later on.

Example 2 – Specifying Columns

We may have a requirement to track product name changes for our application. We can do this also with a change view.

CREATE SUBSCRIPTION sub_stocknameON INVENTORY(ITEM_NAME) FOR ROW (INSERT, UPDATE, DELETE)DESCRIPTION 'Track stock name changes';

Example 2 is more granular than Example 1 and tracks only a single column ITEM_NAME in

the INVENTORY table.

This is done by providing a comma separated list of field names for the table that you want to track.

Example 3 – Tracking Deletes

We may also want to track deletions from a specific table, lets say ORDERS. A Change

Views just tracking DELETE activity on a table

CREATE SUBSCRIPTION sub_orderDeletesON ORDERS FOR ROW (DELETE)DESCRIPTION 'Track Order Deletions';

Using a Change View to track deletes is a powerful feature as you can completely recover the record at its state when it was deleted.

2 Defining who can use a change view / subscription

Once a subscription is created, you need to grant SUBSCRIBE access to the subscription.

To do this use the standard GRANT syntax. e.g.

(for user SYSDBA)

GRANT SUBSCRIBE ON SUBSCRIPTION sub_stock TO SYSDBA;

In the comming instructions we are going to explore how to use a Change View to collect data that has changed in your subscription.

Using an InterBase Change View to fetch data deltas

Once a Change View Subscription has been created and access to it has been granted (to either users or roles), then its time to start using your Change View!

The following steps are the high level overview of using a Change View.

Start a Transaction in SnapShot isolation mode. Set the Subscription active Run your select statement to fetch you delta Once you have collected the delta commit your transaction to bring your Change View up to date.

Here you can see the embedded Video for InterBase. That means if you click on the item in the pdf file you can see the video without use of the internet...

Page 7: blaise pascal magazine 40

6 7Issue Nr 2 2015 BLAISE PASCAL MAGAZINE

INTERBASE CHANGE VIEWS (CONTINUATION 2 - END)

SnapShot ModeA bit of background as we all love to know how things work..

InterBase is powered by a multi-generational architecture which is exceptionally useful when data integrity is important. imagine you need to run multiple financial reports while the system is live; Imagine a connection drops part way through a big data change how do you know what has changed? Multi-generational architectures and transactions makes this possible.

Using a transaction set to SnapShot mode we have a stable point in time that means even if records are updated at the same time as your transaction, they are not missed. When you start your next transaction you will locate those concurrently made changes! – imagine trying to do that with date time stamp tracking!

This means you can have multiple users updating the data at the same time safely without having to lock the tables

Setting the subscription activeAt this point, lets pretend we have a STOCK table and we run the following statement

Select * from STOCK

the data returned would be all the STOCK records. How do we get from

here to just getting changed data deltas? Well, first we need to activate the subscription and provide an ID that we are going to track against.

set subscription sub_stock at 'DeviceID' active;

With the subscription “sub_stock” active, running the initial statement will again return all records as its the first time data has been requested in the subscription.

At this point there are two possible next steps: Commit or Rollback.

Rollback of the transaction will ensure the data is provided again, Commit will bring the Subscription up to date for the start of the transaction.

Running the Select statement again in an active transaction with the subscription active will now return only delta’s

Preventing you data changes showing in your Change View delta

So we have covered selecting data, but what about updating data? How do you stop the changes to data you make appearing in your subscription yet still available to others? Well simply, make the changes while your subscription is active.

Start a Transaction in SnapShot isolation mode.

Set the Subscription active (using your ID) Run your update statement to modify the data Commit your transaction.

Simples!

Introduction to Change Views Video on Embarcadero website

To see a Change View code example see the InterBase XE7 FirstLook webinar:https://www.youtube.com/watch?v=h5E1QvZ1rG8

About the Author:Stephen Ball has lead development teams for over a decade within the UK and across Europe working with a range of blue chip companies including Hilton, American Express, Fitness First, Virgin Active;

Stephen is a Chartered IT Professional and is the Associate Product Manager for InterBase and also a Product Evangelist for RAD Studio, regularly speaking across EMEA.

Stephen Ballhttp://delphiaball.co.uk/2015/03/06/interbase-change-views-example-demo-skill-sprint/

Page 8: blaise pascal magazine 40

OV

ER

VIEW

OF D

ELP

HI T

O D

ELP

HI H

IS

TO

RY

Bu

ild

ing

of

Fra

nce 5

8–

52

BC

Bu

ild

ing

of

Sp

ain

91

2 a

nd

Po

rtu

gal 8

00

Dis

co

very

of

Am

erc

a b

y t

he V

ikin

gs 9

90

- 1

05

0

Dis

co

very

of

Am

eri

ca b

y C

olu

mb

us

Colu

mbus led h

is t

hre

e s

hip

s -

the N

ina,

the P

inta

and t

he S

anta

Maria -

out

of th

e S

panis

h p

ort

of Palo

s o

n A

ugust

3,

1492.

Bla

ise P

ascal (

cre

ate

s t

he f

irst

calc

ula

tors

19 J

une 1

623 –

19 A

ugust

1662)

was a

Fre

nch m

ath

em

aticia

n,

physic

ist,

invento

r, w

rite

r and C

hristian p

hilosopher.

Bla

ise P

ascal

sta

rts t

o g

am

ble

- r

esu

lt f

irst

sta

tisti

cs

Nik

lau

s W

irth

born

Febru

ary

15,

1934 H

e is a

Sw

iss

com

pute

r scie

ntist,

best

know

n for

desig

nin

g s

evera

l pro

gra

mm

ing languages,

inclu

din

g P

ascal, a

nd for

pio

neering s

evera

lcla

ssic

topic

s in s

oft

ware

engin

eering.

Win

do

ws

Lis

a -

Pascal

was a

Pascal im

ple

menta

tion for

the A

pple

Lis

a w

ork

sta

tion.

It w

as a

n e

xte

nsio

n o

f th

e e

arlie

r Apple

Pascal fo

r Apple

II

machin

es,

but

genera

ted o

bje

ct

code for

68000 p

rocessors

that

had t

o b

e lin

ked

again

st

the r

equired lib

raries in t

he L

isa O

S w

ork

shop.

Lis

a P

ascal la

id t

he foundation for

the d

evelo

pm

ent

of Cla

scal and M

ac P

ascal

the first

imple

menta

tions o

f O

bje

ct

Pascal.

Tu

rbo

Pascal

Develo

per(

s)

Anders

Hejlsberg

while

work

ing a

t Borland

Opera

ting s

yste

m C

P/M

, CP/M

-86,

DO

S,

Win

dow

s 3

.x,

Macin

tosh

Pla

tform

8080/Z

80,

8085,

x86

DELP

HI X

E8

DELP

HI 7

rele

ased

in

Au

gu

st

20

02

The first

ste

p,

in 1

981,

was t

he B

lue L

abel Soft

ware

Pascal Com

piler

- BLS P

ascal Com

piler

v1.2

, copyright

1981 b

y P

oly

-Data

mic

rocente

r ApS,

Str

andboulv

ard

en 6

3,

DK 2

100 C

openhagen -

w

ritt

en b

y A

nd

ers

Hejl

sb

erg

for

the N

ASCO

M k

it c

om

pute

r.

Th

e r

oo

ts o

f Tu

rbo

Pascal v1.0

sta

rted in D

enm

ark

.

Em

barc

ad

ero

Tech

no

log

ies i

n 2

00

8.

Co

deg

ear

Delp

hi 2

00

7.

Ch

arl

es B

ab

bag

e -

conceiv

ed o

f th

e first

pro

gra

mm

able

com

pute

r in

the 1

830

math

em

aticia

n

Babbage n

ever

built

his

Diffe

rence E

ngin

e

- a m

echanic

al calc

ula

tor

with t

housands o

f part

s -

because o

f cost

overr

uns a

nd p

olitical dis

agre

em

ents

, b

ut

the i

nven

tor

passed

on

pla

ns for

its c

om

ple

tion,

and in 1

991,

the S

cie

nce M

useum

in L

ondon a

ctu

ally

built

it (

the p

rinting c

om

ponent

was fin

ished in 2

000).

As s

uspecte

d,

it a

ctu

ally w

ork

s.

On

Feb

ruary

8,

20

06

Bo

rlan

d a

nnounced t

hat

it w

as lookin

g for

a

buyer

for

its I

DE a

nd d

ata

base lin

e o

f pro

ducts

, in

clu

din

g D

elp

hi, t

o

concentr

ate

on its

ALM

lin

e.

On N

ovem

ber

14,

2006 B

orland t

ransfe

rred

the d

evelo

pm

ent

tools

gro

up t

o a

n independent

subsid

iary

com

pany

nam

ed C

odeG

ear, inste

ad o

f sellin

g it.

Borland s

old

CodeG

ear

to

Em

barc

adero

Technolo

gie

s in 2

008.

Em

barc

adero

reta

ined t

he

CodeG

ear

div

isio

n c

reate

d b

y B

orland t

o identify

its

tool and d

ata

base

offerings,

but

identified its

ow

n d

ata

base t

ools

under

the D

ata

baseG

ear

DELP

HI

rele

ased

Feb

ruary

14

, 1

99

5

Page 9: blaise pascal magazine 40

WA

TER

CLO

CK

- C

HIN

A -

BEG

IN

NIN

G O

F T

IM

E (

BC

40

00

)Som

e a

uth

ors

cla

im t

hat

wate

r clo

cks a

ppeare

d in C

hin

a

as e

arly a

s 4

000 B

C

DELP

HI

The c

ult o

f Apollo a

t D

elp

hi pro

bably

date

s b

ack t

o

the 7

00s B

. C

.,

Pla

to i

n C

lassic

al

Att

ic;

428/4

27 o

r 424/4

23 –

348/3

47 B

C)

was a

philosopher, a

s w

ell a

s m

ath

em

aticia

n,

in C

lassic

al G

reece.

Pyth

ag

ora

s P

hilosopher

Pyth

agora

s o

f Sam

os w

as a

n

Ionia

n G

reek p

hilosopher, m

ath

em

aticia

n,

and founder

of th

e r

eligio

us m

ovem

ent

called P

yth

agore

anis

m.

Born

: 571 -

495 B

C,

Arc

him

ed

es M

ath

em

aticia

nArc

him

edes o

f Syra

cuse w

as a

n A

ncie

nt

Gre

ek m

ath

em

aticia

n,

physic

ist,

engin

eer,

invento

r, a

nd a

str

onom

er.

He is r

egard

ed a

s o

ne o

f th

e leadin

g s

cie

ntists

in

cla

ssic

al antiquity.

Wik

ipedia

Born

: 287 -

212 B

C,

Syra

cuse,

Italy

Th

ale

s P

hilosopher

Thale

s o

f M

iletu

s w

as a

pre

-Socra

tic G

reek p

hilosopher

from

Miletu

s in A

sia

Min

or

and o

ne o

f th

e

Seven S

ages o

f G

reece.

Many,

most

nota

bly

Aristo

tle,

regard

him

as t

he first

philosopher

in t

he G

reek t

raditio

n.

Born

: 624 B

C -

546

Eu

cli

d M

ath

em

aticia

nBorn

Mid

-4th

centu

ry B

C -

3rd

centu

ry B

CResid

ence A

lexandria,

Hellenis

tic E

gypt

Fie

lds M

ath

em

atics K

now

n for

Euclidean g

eom

etr

y /

Euclid's

Ele

ments

Euclidean a

lgorith

m

Ro

man

Em

pir

e 7

00

BC

Decay o

f th

e R

om

an

Em

pir

e 5

00

Bu

ild

ing

of

Eu

rop

e

Bab

bag

e D

iffe

ren

ce E

ng

ine N

o.

2

Dif

fere

nce E

ng

ine N

o.

1,

po

rtio

n,1

83

2

A combined page 8/9 file is available at page 10 as a separate pdf download in portrait format. You can enlarge this yourself to view the information in greater detail. Our authors plan to address each section of this timeline in future magazine articles.

Page 10: blaise pascal magazine 40

WATER CLOCK - CHINA - BEGINNING OF TIME (BC 4000)Some authors claim that water clocks appeared in China as early as 4000 BC

DELPHIThe cult of Apollo at Delphi probably dates back to the 700s B . C .,

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

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

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

Thales PhilosopherThales of Miletus was a pre-Socratic Greek philosopher from Miletus in Asia Minor and one of the Seven Sages of Greece. Many, most notably Aristotle, regard him as the first philosopher in the Greek tradition.Born: 624 BC - 546

Euclid MathematicianBorn Mid-4th century BC - 3rd century BCResidence Alexandria, Hellenistic EgyptFields Mathematics Known for Euclidean geometry / Euclid's ElementsEuclidean algorithm

Roman Empire 700 BC

Decay of the Roman Empire 500

Building of Europe

Babbage Difference Engine No. 2

OVERVIEW OF DELPHI TO DELPHI HISTORY

Building of France 58–52 BC

Building of Spain 912 and Portugal 800

Discovery of Amerca by the Vikings 990 - 1050

Discovery of America by ColumbusColumbus led his three ships - the Nina, the Pinta and the Santa Maria - out of the Spanish port of Palos on August 3, 1492.

Blaise Pascal (

creates the first calculators

19 June 1623 – 19 August 1662) was a French mathematician, physicist, inventor, writer and Christian philosopher.

Blaise Pascal starts to gamble - result first statistics

Niklaus Wirthborn February 15, 1934 He is a Swiss computer scientist, best known for designing several programming languages, including Pascal, and for pioneering severalclassic topics in software engineering.

Windows

Lisa - Pascal was a Pascal implementation for the Apple Lisa workstation.

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.Lisa Pascal laid the foundation for the development of Clascal and Mac Pascalthe first implementations of Object Pascal.

Turbo PascalDeveloper(s) Anders Hejlsberg while working at Borland Operating system CP/M, CP/M-86, DOS,Windows 3.x, MacintoshPlatform 8080/Z80, 8085, x86

DELPHI XE8

DELPHI 7 released in August 2002

DELPHI released February 14, 1995

Embarcadero Technologies in 2008.

Codegear Delphi 2007.

Charles Babbage -

conceived of the first programmable computer in the 1830s

mathematician

Babbage never built his Difference Engine - a mechanical calculator with thousands of parts -because of cost overruns and political disagreements, but the inventor passed on plans for its completion, and in 1991, the Science Museum in London actually built it (the printing component was finished in 2000). As suspected, it actually works.

The roots of Turbo Pascal v1.0 started in Denmark. The first step, in 1981, was the Blue Label Software Pascal Compiler - BLS Pascal Compiler v1.2, copyright 1981 by Poly-Data microcenter ApS, Strandboulvarden 63, DK 2100 Copenhagen - written by Anders Hejlsberg for the NASCOM kit computer.

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 an independent subsidiary company named CodeGear, instead of selling it. Borland sold CodeGear to Embarcadero Technologies in 2008. Embarcadero retained the CodeGear division created by Borland to identify its tool and database offerings, but identified its own database tools under the DatabaseGear name.

Difference Engine No. 1, portion,1832

Page 11: blaise pascal magazine 40

or call: +31 (0)235422227http://www.barnsten.com/default/newxe8

Click here for all information and the introductory offer

Page 12: blaise pascal magazine 40

50 hands-on recipes to master the power of Delphi for

cross-platform and mobile development on Windows,

Mac OS X, Android, and iOS

Daniele Teti

Quick answers to common problems

Delphi Cookbook

See our special offer:€ 10,00 if you subscribe for two years..€ 30,00 including VAT€ 39 including the printed book, ebookand shipping http://www.blaisepascal.eu/daniele_teti_book/DanieleTeti.html

OICH EC SRO

TI

DE

A

MAZING

BLAISE PASCAL

MAGAZINE

Page 13: blaise pascal magazine 40

Earlier myths include traditions that Pythia, or the Delphic oracle, already was the site of an important oracle in the pre-classical Greek world (as early as 1400 BC) and, rededicated, served as the major site during classical times for the worship of the god Apollo after he slew Python, "a dragon" who lived there and protected the navel of the Earth. "Python" (derived from the verb pythein, "to rot") is claimed by some to be the original name of the site in recognition of Python which Apollo defeated. The Homeric Hymn to Delphic Apollo recalled that the ancient name of this site had been Krisa

Others relate that it was named Pytho and that Pythia, the priestess serving as the oracle, was chosen from their ranks by a group of priestesses who officiated at the temple. Apollo's sacred precinct in Delphi was a panhellenic sanctuary, where every four years, starting in 586 BC athletes from all over the Greek world competed in the Pythian Games, one of the four panhellenic (or stephanitic) games, precursors of the Modern Olympics. The victors at Delphi were presented with a laurel crown (stephanos) which was ceremonially cut from a tree by a boy who re-enacted the slaying of the Python. Delphi was set apart from the other games sites because it hosted the mousikos agon, musical competitions.

is both an archaeological site and a modern town in Greece on the south-western spur of Mount Parnassus in the valley of Phocis. In myths dating to the classical period of Ancient Greece (510-323 BC), the site of Delphi was believed to be determined by Zeus when he sought to find the centre of his "Grandmother Earth" (Ge, Gaea, or Gaia). He sent two eagles flying from the eastern and western extremities, and the path of the eagles crossed over Delphi where the omphalos, or navel of Gaia was found.

DELPHI (THE CITY)

13Issue Nr 2 2015 BLAISE PASCAL MAGAZINE

Page 14: blaise pascal magazine 40

Based on an article written in 1999 by Danny Thorpe

Borland (for a time Inprise), was the company that first developed Delphi. It later moved Delphi development to its CodeGear division, which was acquired by Embarcadero Technologies in 2008. Embarcadero continues to develop the Delphi XE product line.

Borland considered that a new product codename should have no obvious connection to the product, so that if an eavesdropper overheard the name in conversation it would be unclear which product was being discussed. One of the most memorable product codenames coined

at the company was “Buddha” (the insiders' alias for Quattro Pro 4.0, a direct 1-2-3 competitor). This was because Quattro Pro had to assume the Lotus position!

"Delphi" started out as a beta codename for a closely guarded, innovative research project at Borland: a next-generation visual development environment for Windows based on Borland's Object Pascal programming language (until then known as Turbo Pascal). Gary Whizin, the Borland R&D Manager favoured the codename “Oracle”, since by mid-1993 the strategic decision had been taken to make database tools and connectivity a central part of this new Pascal product, which by then had six months of intensive research, market analysis and proof-of-concept exercises behind it.

The research group involved less than a dozen Borland staff including Anders Hejlsberg, Chuck Jazdzewski, Allen Bauer, Zack Urlocker,Richard Nelson, Danny Thorpe and Gary Whizin. However Gary's preference was not shared by the rest of the group who pointed out the confusion with the identically named company and their server product, whereas the new Pascal development environment was (then) envisaged as a client

building tool, a way to talk to Oracle and other servers.

How do you talk to an oracle? "The oracle at Delphi" was the word association that occurred to Danny Thorpe during one of many conversations in Gary's office about the best codename.

His suggestion wasn't an instant hit. It's an old name, an old place, a pagan temple in the ruins of a dead civilization. Not exactly an inspiring association for a new product! As some press articles later noted, the Delphic Oracle was famous for giving out cryptic or ambiguous answers - not a great association for a data management tool. Asking a question of the oracle was free to all, but having the oracle's answer interpreted cost the enquirer many drachmas (although the marketing guys liked that part).

Overall, though, the "Delphi" codename had a classier ring to it than most of the other suggestions that were offered. Pascal is a classic programming language, so it felt appropriate to associate a Pascal-based development tool with a classical Greek “brand”. Many codenames were used during the development of that version 1.0 product, a new one being coined for each press or corporate briefing of the beta product, in the hope of limiting rumours and allowing Borland to track the source of any leaks. The aim was to for Microsoft to discover what Borland was up to as late as possible.

WHY THE NAME "DELPHI?"

Issue Nr 2 2015 BLAISE PASCAL MAGAZINE14

Page 15: blaise pascal magazine 40

WHY THE NAME "DELPHI?" (CONTINUATION- END)

Towards the end of the development cycle, Borland marketing dropped the temporary codenames and started using the Delphi codename across all prepress and corporate briefings, and also as the codename for the finalbeta releases. That got the rumour mills talking to each other, and the tools industry was abuzz with talk about this secret project at Borland codenamed "Delphi".

When it came time to pick a retail product name, the nominations were less than inspiring. The "functional" name (the name that describes what the product actually does and is therefore easier to market and sell), would have been AppBuilder.

This name actually still appears in some Delphi IDE internals, such as the class name of the IDE main window; but AppBuilder didn't inspire people or work well internationally. Functional names are only functional in their language of origin.

A few months before Delphi was scheduled for release Novell shipped their own product called Visual AppBuilder, which finally laid the Borland AppBuilder debate to rest.

With the functional name taken out of the running, many Borlanders suggested using the Delphi codename as the product name. However the lead marketing person had legitimate concerns about the extra effort required to build name recognition in the marketplace for an "iconic" (the opposite of a functional) product name, so he requested a vote of the development team, who had a large majority in favour of Delphi. Wider market polls were conducted.

The harder people tried to dismiss "Delphi" as the product name, the more it gained support. "Delphi" has a classical ring to it.

The name has endured.

15Issue Nr 2 2015 BLAISE PASCAL MAGAZINE

Page 16: blaise pascal magazine 40

Issue Nr 2 2015 BLAISE PASCAL MAGAZINE16

INTRODUCTION TO FLATBOX2D FOR DELPHI XE8

Paweł Głowacki (Embarcadero)

Physics enginesWelcome to the world of physics! Welcome to the world of physics! It is difficult to imagine a game – or just a modern app with a sophisticated user interface – without realistic physics effects. All programmed games include a software component called a “physics engine” that is responsible for realistic display of physical interactions such as the bouncing and collision of moving bodies. Complex physics engines can simulate the interaction of objects in a 3D space; however commonly physics simulations are simplified by being restricted just two dimensions. Probably the best-known physics engine is “Box2D”, used in many popular games, including super hits like “Angry Birds”. Box2D was originally written by Erin Catto and is an open source C++ library available under the permissive zlib free software license.

FlatBox2DDelphi XE8, C++Builder XE8 and RAD Studio XE8 are introducing support for a 2D physics engine based on Box2D. You can find a new “FlatBox2D” folder under “Source” in the default XE8 installation directory. It contains some C++ header and source files and five Object Pascal units:· Box2D.Common.pas· Box2D.Collision.pas· Box2D.Dynamics.pas· Box2D.Rope.pas· Box2DTypes.pas

The name “flat” comes from the fact that original Box2D implementation was contained in many smaller files and XE8 support combines these into “flat” namespaces. If you examine the Box2D Pascal source you will see the Embarcadero copyright notice together with a note that these units were generated by “Delphi-C++ Library Bridge”. The naming convention adopted is for all Box2D type names to start with “b2…”

These Delphi units are interfaces to compiled FlatBox2D libraries that need to be deployed with a Delphi application target. There are four potential platforms: two desktop (Windows, Mac OSX) and two mobile (Android and iOS).

Additionally Windows and iOS have two different compilers for 32-bit and 64-bit support. You can find the names of these libraries at the very beginning of the “implementation” section of each FlatBox2D unit. The various versions of the FlatBox2D libraries can be found in “bin” and “lib” folders inside Delphi XE8 installation folders. They are named as follows, according to the platform and build configuration:

• Windows: FlatBox2DDyn.dll

Mac OS X: libFlatBox2DDyn.dylib

Android: libFlatBox2D.a

iOS: libFlatBox2D.a

The source code for the FlatBox2D library units is in the “Browsing Path” in Delphi's global options. A programmer does not need to do anything to use them beyond adding “Box2D” to the “uses” clauses in your project's units!

Page 17: blaise pascal magazine 40

Hello WorldWe commonly explore new software or libraries by trying to build a “Hello World” app, and FlatBox2D is no different! On the Box2D home page there is a very nice manual (http://box2d.org/manual.pdf) that explains all the important concepts of Box2D. Chapter 2 contains a “Hello World” project with detailed comments. Delphi XE8 contains a 1:1 translation of this demo project into the Object Pascal language. Rather than discussing the full Box2D functionality which you can gather from the manual, let's have a walk through the “FlatBox2DObjPasHelloWorld” multi-device project that you can find in the Object Pascal “Mobile Samples” in the default installation of Delphi XE8 (C:\Users\Public\Documents\Embarcadero\Studio\16.0\Samples\Object Pascal\Mobile Samples\Physics\Box2DHello\).

In the project there is only one form with a button and a memo. All the demo code is in the “OnClick” event of the button.

The first thing is to make sure that all relevant Box2D units are in the “uses” clause of the form.

uses . , . , . ;Box2D Common Box2D Collision Box2D Dynamics

The main class in Box2D is the “World”. World is a container for all objects that make up the simulation. The “Box2D.Dynamics” unit defines a “b2WorldWrapper” record type that encapsulates “FHandle: b2WorldHandle” that points to the actual “b2World” instance inside of the compiled FlatBox2D library.

The “b2WorldWrapper” contains a class function “Create” that acts very much like a typical Delphi constructor and initializes an internal handle to world object, along with a “Destroy” procedure that acts like a destructor that closes the internal handle.

The “Create” method accepts a 2D vector “gravity” that represents the gravitational force that affects all bodies in the simulation. All method calls to “b2WorldWrapper” should happen after the call to “Create” and before the call to “Destroy” as in the code below.

procedurevar

begin

try

finally

end

end

. ( : );

: ; : ;

:= . ( , - ); := . ( ); . ; ;

;

TForm1 Button1Click Sender TObject

gravity b2Vec2

world b2WorldWrapper

gravity b2Vec2 Create

world b2WorldWrapper Create gravity

world Destroy

// Define the gravity vector

// Construct a world object, which will hold and simulate the rigid bodies

// work with "world"

0.0 10.0

The Box2D engine uses “MKS” units (short for “Meter-Kilogram-Second”) in simulating the behavior of bodies in the physical world. For example, when we pass a gravity vector to our world's “Create” method we usually mean the Earth's gravity, which points downwards and is approximately 10 meters per second squared (m/s2).

Box2D has been optimized to work well with shapes moving between 0.1 and 10 m/s. All angles are expressed in radians (not in degrees).

Once we have a world object, we can add bodies and joints to it. Joints connect bodies together by removing certain degrees of freedom of the physical objects that are part of the simulation.

Box2D is a “rigid body” engine, which means that bodies are not elastic. In other words the distance between any two points of a given body is always constant. This contrasts wtih the more complex “soft body” physics that can be used to model behavior of, say, clothing, in which distances between arbitrary points of a sock may change as it slides down a leg of unchanging length.

It is important to realize that Box2D has its own memory management optimized for working with large numbers of transient small objects. Hence when you want to add bodies and other objects to the world, you do not use constructors, but instead use special factory functions that will allocate these objects for you. This also means that you do not have to free these objects. They will be destroyed when the whole world is destroyed.There are three types of bodies in Box2D and they are defined by the “b2BodyType” enumerated type in “Box2D.Dynamics”.

INTRODUCTION TO FLATBOX2D FOR DELPHI XE8 (CONTINUATION 1)

17Issue Nr 2 2015 BLAISE PASCAL MAGAZINE

Page 18: blaise pascal magazine 40

Issue Nr 2 2015 BLAISE PASCAL MAGAZINE18

• Dynamic Body (b2_dynamicBody). It has a mass. Forces have impact on it. It can be put into linear and angular movement. It may collide with other dynamic and static bodies. If a dynamic body has zero mass then it behaves differently and it always has zero angular velocity. In a game dynamic bodies are typically moving objects like vehicles, bullets, balls and everything else that can move through the world and collide.• Static Body (b2_staticBody).

It does not have a mass. Forces do not influence it. It cannot be put into a linear or angular movement. Dynamic bodies collide with it. In a typical game static bodies are used to define borders and limits of the game, like walls, ground, bands in a hockey game and so on.• Kinematic Body (b2_kinematicBody):

· Forces do not influence it. It can be put into linear or angular movement. It may collide with dynamic bodies, but it does not collide with other kinematic bodies. Collisions between dynamic and kinematic bodies do not change the movement of a kinematic body. For example they can be used in a game as “moving platforms” that do not react to heavy bodies that collide with them. The movement of a kinematic body is controlled by vectors of linear and angular velocity.

In order to create a body we need to call “CreateBody” factory method of the world object and in the parameter we pass an object that contains the body “definition”. This is a common pattern in Box2D. Factory methods typically accept “definition” objects that provide a lot of useful defaults (which means there is less for you to code).Let's add the “ground” body to our “Hello World” simulation.

First we need to create and initialize the ground body “definition”. The default type of a body is “static”, so we do not need to change it. We only specify the position of the body to be 10 meters “below” zero.

“b2BodyDef” is a record type. We need the “@” operator to pass a pointer to this record, rather than the record itself. The call to “Set” is prepended with the “&” operator. This is because “set” is an Object Pascal keyword and to use it as an identifier it needs to be escaped.

The Box2D “body” is an abstract notion. It does not have a shape, mass or any physical properties of the material it simulates. The class that has these properties is called a “fixture”. Fixtures belong to a body and are created using the “CreateFixture” method of a body.

The “CreateFixture” method has two variants. One that takes a fixture definition as an argument and the other that takes an instance of a “shape” class and the “density”.

b2BodyWrapper

FHandle b2BodyHandle

CreateFixture def Pb2FixtureDef Pb2Fixture

CreateFixture shape b2ShapeHandle density Single

Pb2Fixture

= : ; ( : ): ; ; ; ( : ; : ):

; ; ;

record

function overload cdecl

function

overload cdecl

// …

// …

There are four different descendants from the “b2Shape” class that defines a shape.· Circle shape (b2CircleShape):

Circle shapes have a position and radius. Circles are solid. You cannot make a hollow circle using the circle shape.· Polygon shape (b2PolygonShape):

Polygon shapes are solid convex polygons. A polygon is convex when all line segments connecting two points in the interior do not cross any edge of the polygon. Polygons are solid and never hollow. A polygon must have three or more vertices. Polygon vertices are stored with a counter clockwise winding.

· Edge shape (b2EdgeShape):

Edge shapes are line segments. These are provided to assist in making a free-form static environment for your game. A major limitation of edge shapes is that they can collide with circles and polygons but not with themselves. Edge shapes have no volume, so edge-edge collision is not possible.

var

Set

: ; : ;

:= . (); . .& ( , - );

:= . (@ );

groundBodyDef b2BodyDef

groundBody b2BodyWrapper

groundBodyDef b2BodyDef Create

groundBodyDef position

groundBody world CreateBody groundBodyDef

// …

// Define the ground body

// Call the body factory which allocates memory for the ground body

0.0 10.0

INTRODUCTION TO FLATBOX2D FOR DELPHI XE8 (CONTINUATION 2)

Page 19: blaise pascal magazine 40

var : ;

:= . (); . ( , ); . ( , );

groundBox b2PolygonShapeWrapper

groundBox b2PolygonShapeWrapper Create

groundBox SetAsBox

groundBody CreateFixture groundBox

// Define the ground box shape

// The extents are the half-widths of the box

// Add the ground fixture to the ground body50.0 10.0

0.0

Now we have one static “ground” body in our simulation. The next step is to add a dynamic body, a smaller “box” that we are going to put on top of our ground. For this we are going to use the “CreateFixture” variant that takes a fixture definition as a parameter.

var

type

Set

: ; : ; : ; : ; := . (); .& := ; . .& ( , ); := . (@ );

:= . (); . ( , );

:= . ();. := ;

. := ; . := ; . (@ );

bodyDef b2BodyDef

body b2BodyWrapper

dynamicBox b2PolygonShapeWrapper

fixtureDef b2FixtureDef

bodyDef b2BodyDef Create

bodyDef b2_DynamicBody

bodyDef position

body world CreateBody bodyDef

dynamicBox b2PolygonShapeWrapper Create

dynamicBox SetAsBox

fixtureDef b2FixtureDef Create

fixtureDef shape dynamicBox

fixtureDef density

fixtureDef friction

body CreateFixture fixtureDef

// Define another box shape for our dynamic body

// Set the box density to be non-zero, so it will be dynamic

// Override the default friction

// Add the shape to the body

0.0 4.0

1.0 1.0

1.0

1.0

The last thing is to “clean-up” definition objects. In Box2D these objects can be reused and passed to subsequent calls to “Create” methods with adjusted parameters.

// Cleanup Shape Wrappers . ; . ;

dynamicBox Destroy

groundBox Destroy

Our “Hello World” simulation is now initialized and ready to start moving. The most important method of the world object

is “Step”. Step's first parameter is the amount of time we want to advance our simulation forward.

Box2D simulation is completely neutral from any rendering and also does not have its own loop. Basically you create a simulated physics world, add objects to it and call its “Update” method – whenever you want – passing the amount of time you want the simulation toadvance. Box2D has algorithms that prevent the tunneling effect which happens when calculating positions of moving bodies in time. If the time increment is too big, you may end

up with a situation in which objects are penetrating each other instead of colliding. This is why there are two additional parameters to the “Step” method that define the number of velocity and position iterations that are calculated in each step. Typical values are 6 for velocity and 2 for position iterations at each step.

In the “Hello World” demo we display in the memo the position and rotation angle of the moving dynamic box for the first second of simulation. It is typical in games to use 1/60 second frame rate to achieve smooth animation of moving objects.

• Chain shape (b2ChainShape):

The chain shape provides an efficient way to connect many edges together to construct your static game worlds. Chain shapes automatically eliminate ghost collisions and provide two-sided collision.In our “Hello World” program the next step is to attach a polygon shape to our “ground” body. We are using the convenience method “SetAsBox” that would define our generic polygon to be a polygon with four vertices that forms a “box”. As parameters you need to pass the half-width and half-height of the resulting box.

timeStep

velocityIterations

positionIterations

i

world Step timeStep velocityIterations positionIterations

pos body GetPosition

angle body GetAngle

Memo1 Lines Add Format

pos x pos y angle

:= / ; := ; := ;

:= . ( , , );

:= . ; := . ;

. . ( ( , [ ^. , ^. , ]));

;

1 60

6

2

0 60for to dobegin

end

// Instruct the world to perform a single step of simulation.// It is generally best to keep the time step and iterations fixed

'%4.2f %4.2f %4.2f'

This is what the output of our FlatBox2D

“Hello World” program looks like -

not like “Angry Birds” at all!

INTRODUCTION TO FLATBOX2D FOR DELPHI XE8 (CONTINUATION 3)

19Issue Nr 2 2015 BLAISE PASCAL MAGAZINE

Page 20: blaise pascal magazine 40

These are the very basics. To use FlatBox2D in applications we need to create the “world” object first, add all bodies, shapes and joints to it, build our own “game loop” that would call our world's “Step” method to advance the simulation and we would also need to provide our own graphics rendering.In the default Delphi XE8 installation there are two more demo projects that go deeper into using different bodies, shapes and joints to create more complex simulations than this “Hello World” which has just two boxes.

Test BedThe FlatBox2D “Test Bed” demo is a very convenient application that acts a framework for “plugging in” different “tests” into a common codebase for rendering graphics, providing the “game loop” and processing “user input”. This the Object Pascal version of the original C++ “Test Bed”. You can find FlatBox2D “Test Bed” in C:\Users\Public\Documents\Embarcadero\Studio\16.0\Samples\Object Pascal\Mobile Samples\Physics\TestBed \TestBed.dpr

You can learn a lot by playing with one of the six predefined test cases that experiments with different aspects of the engine. You can create your own tests by extending the “TTest” class and registering your test with the application's main form. Out of the box you got the following tests:

• Chain

Varying Restitution

Tiles

Add Pair

Apply Force

Basic Slider Crank

Here is how “Tiles” test looks like in action:

INTRODUCTION TO FLATBOX2D FOR DELPHI XE8 (CONTINUATION 4)

Issue Nr 2 2015 BLAISE PASCAL MAGAZINE18

Page 21: blaise pascal magazine 40

By pressing “space” you shoot “bullets” into your simulation. That is fun!

Adding physics to appsThe third demo that comes installed with Delphi XE8 demonstrates how to add physics to a common FireMonkey multi-device app which uses standard user interface elements such as buttons, scroll bars, check boxes and the like. This demo is located inC:\Users\Public\Documents\Embarcadero\Studio\16.0\Samples\Object Pascal \FireMonkey Desktop\Physics \FormWithBox2D\FMSimplePhysics.dpr

When you open the “FMSimplePhysics” project it looks like a regular FireMonkey “Controls” demo.

After you click on the “Drop” button all controls gain “physical” properties and start falling to the bottom of the screen!

The physics support has been encapsulated into a “TFmxPhysicsDemo” class that is defined as a member of the main form's class. It has two methods that are called during the construction of the main form “AddScreenSize” and “AddControl”. “AddScreenSize” is called once, and it used to add four static boxes to the internal Box2D world, boxes that are at the same position as the borders of the screen.

The “AddControl” method is called for every control on the form to create a box representing this control inside the world.

SummaryThe FlatBox2D physics engine is a great new feature included in the new version of Embarcadero Delphi XE8, C++Builder XE8 and RAD Studio XE8. Based on a well-known open source C++ Box2D implementation it adds a solid foundation for building new generation apps with realistic graphics user interfaces.The FlatBox2D demos discussed in this article cover the basics of using Box2D

(“Hello World”), playing with more complex combinations of bodies, shapes, joints (“Test Bed”) and adding physics to a Delphi XE8 multi-device application (“FMSimplePhysics”). The next step is to build a complete game with its own graphics, but this I'm going to leave to the reader!

Have fun with Delphi and FlatBox2D programming!

INTRODUCTION TO FLATBOX2D FOR DELPHI XE8 (CONTINUATION 5 - END)

About the Author

Paweł Głowacki is Embarcadero's

European Technical Lead for Developer Tools. Previously, Paweł spent over 7 years working as a senior consultant and trainer for Delphi within Borland Education Services and CodeGear. As well as working with Embarcadero customers across the region, he also represents Embarcadero internationally as a conference and seminar speaker. For more information check out Paweł's technical blog at http://community.embarcadero.com

21Issue Nr 2 2015 BLAISE PASCAL MAGAZINE

Page 22: blaise pascal magazine 40

Fast Report 5 features:• User friendly Report Designer

(Create new reports in few clicks, report wizards, dialog designer, script editor and much more); Extended Report and script Inheritance; Many report objects:

Special Bands (Footers, Headers), HTML-formatted Texts, RTF-formatted Texts,Images, Charts, Linear barcodes, 2D Barcodes, CheckBoxes, Simple Geometric Objects, Vertical Bands, Cross-tabs;

Export filters : PDF, RTF, HTML, TXT, JPEG, BMP, TIFF, GIF, EMF, CSV, ODS, ODT, Excel Binary, Excel XML, Email, DBF;

Built-in script shell that supports 4 languages; Interactive forms, drill-down (drop) reports, call another report with

detailed information from the preview window with one mouse click; Acess to many popular database engines:

FireDAC, ADO, BDE, DBX, IBX and FIBPlus, so providing access to practically all databases, including Oracle and many third-party libraries;

Acess to any data of your application including classes with using TfrxUserDataSet component;

Convertors from : Quick Reports, Rave Reports, Report Builder;

New features in Version 5.2:

report designer and the report preview.

(SVG is a graphical vector format used in web and now FastReport allows you to export reports to this format.)

(whole report or single object) - ability to restore object properties of any object in inherited report to default values introduced in base report.

- allow to drag any count of fields from "data tree" or/and include whole data set. Create your report for few mouse clicks !

from report tree window - new enchanted "report objects tree" gives ability to select move and edit objects more easily.

- pictures and some objects like RTF may uses alpha mask during export to PDF.

- new selection modes allow to select all object of the same kind as selected.

single preview and show each in the separate tab.

••

••

••

Support of last Embarcadero RAD Studio XE7 for x32 and x64 windows platforms Initial support of Lazarus for Fast Report 5 - first beta release witch includes the

New export filter to SVG format

New feature to reset object properties to parents in inherited report

New multi-selection for data tree and ability to drag whole dataset (create band)

Interactive Report Tree with ability to move/select/edit report objects

Transparency and color mask in PDF export (Pictures/HTML-tags/RTF)

New selection mode in report designer

Changed preview tabs mechanism. TfrxPreview.EachReportInTab allows to bind few report components to a

Many of bug fixed and improvements.

Page 24: blaise pascal magazine 40

Issue Nr 2 2015 BLAISE PASCAL MAGAZINE24

CLIENTDATASETS AND FDMEMTABLES COMPARED: PART 2

by Cary Jensen

Delphi now has two distinct in-memory dataset components, the ClientDataSet, which has been

available in the Client/Server editions since Delphi 3, and found its way into the Professional edition in Delphi 6, and FDMemTable. The FDMemTable is the newcomer, making its first appearance in Delphi XE3.

I have long been an advocate for the use of in-memory datasets, noting that their features can be applied in a wide range of applications, even those not specifically associated with traditional databases. And now that there are two in-memory datasets in Delphi, the most frequent question that I get asked is this, "Which one should I use?".

The truthful answer is "It depends". They are not identical, and each has its strengths and weaknesses. In the last issue of Blaise Pascal I began taking a look at the similarities between these two in-memory datasets, as well as differences in design time operations, record persistence, and query configuration. In this issue I will conclude with a look at cached updates differences, nested datasets, DataSnap operations, and miscellaneous differences.

This section describes some of the differences between cached updates in ClientDataSets and FDMemTables.

One of the more compelling reasons to use a ClientDataSet is to enable cached updates on a TDataSet. This is not true, however, when it comes to users of Delphi's FireDAC data access framework. The reason why is that FireDAC datasets support cache updates directly (albeit through an encapsulated FDMemTable). As a result, when you want cached updates you can simply employ that feature as exposed by the FireDAC dataset, such as an FDQuery.

Before continuing, however, I want to point out that cached updates in FDMemTables works differently than in other FireDAC datasets, specifically with respect to how the ApplyUpdates method works. I will address these difference when I discuss ApplyUpdates.

Nonetheless, while both ClientDataSets and FDMemTables support cached updates operations, a number of the properties and methods associated with cached updates work differently. Examples of properties and methods that differ in function between ClientDataSets and FDMemTables

FDMEMTABLE NOT REQUIRED FOR CACHED UPDATES

DEFAULT CACHED UPDATES STATE

CACHED UPDATES AND UPDATEMODE

APPLYING UPDATES

Let's start this comparison by looking at the default cached updates state of ClientDataSets. A ClientDataSet is in a cached updates mode by default. In other words, LogChanges is True for a ClientDataSet when it is created. By comparison, FDMemTable CachedUpdates is False by default.

ClientDataSets and FDMemTables use different update mode default settings, a value that affects how updates are applied. I spent an entire article in a recent issue of Blaise Pascal Magazine discussing this issue, but permit me to recap that discussion here.

ClientDataSets, by way of the DataSetProvider.UpdateMode property, defaults to upWhereAll. This setting attempts to apply an update based on key fields and all non-BLOB (Binary Large OBject) fields. If some other user has posted a change to a record since the in-memory dataset was loaded, a change to that same record cannot be applied from cache to the underlying database. In this situation, the first user to write their changes wins.

FireDAC DataSets, including FDMemTable, use their UpdateOptions.UpdateMode property to control this process, and this property defaults to upWhereKey. When UpdateMode is set to upWhereKey, only the key fields are used to update data, which has the effect of replacing existing records with whatever the current user is writing. In other words, the last user to write to a particular record (as identified by the table's key fields) will replace any changes previously posted by another user. To put it another way, the last user to write wins.

Obviously, these are differences in default settings, and you can easily set an FDMemTable's UpdateOptions.UpdateMode property to upWhereAll. Nonetheless, you need to be aware that ClientDataSets and FDMemTables have different defaults, since the difference between these two settings are significant.

Applying cached updates is another area where ClientDataSets and FDMemTables differ significantly.

Delphi XE 7

expertstarter

Cached Updates

include CachedUpdates, StatusFilter (and its related property, FilterChanges), and ApplyUpdates.

Page 25: blaise pascal magazine 40

25Issue Nr 2 2015 BLAISE PASCAL MAGAZINE

Calling ApplyUpdates on a ClientDataSet clears each applied record from the cache (assuming that MaxErrors is not exceeded). If all updates are successfully applied, the change cache will be empty when ApplyUpdates returns. If errors are encountered, and MaxErrors is not exceeded, the applied records are cleared from the cache, with the records that produced errors remaining.

By comparison, following a call to ApplyUpdates on an FDMemTable, the cache is cleared unconditionally. In other words, if AMaxErrors (the name of the parameter passed to ApplyUpdates in FireDAC is different), all records are removed from the cache, including the errors. Yes, ApplyUpdates will return a non-zero value if errors are encountered, but those errant records are removed from cache. Apparently, if you want to process those errors, you must do so by catching them using the OnReconcileError event handler.

I mentioned earlier that FireDAC's other datasets, such as FDQuery, handle ApplyUpdates differently, both from ClientDataSets and FDMemTables. With an FDQuery, a call to ApplyUpdates doesn't clear the cache at all, even if all changes can be applied. If ApplyUpdates returns 0, indicating that all updates are applied, you must then call CommitUpdates to flush the cache of all records. If ApplyUpdates returns a positive value, indicating that one or more records could not be applied, you have to manually handle those records before flushing the cache.

Fortunately, there are easy ways to identify records in cache that could not be applied.

Figure 1. The CentralizedCachedUpdates project

FireDAC datasets flag records in the cache by exposing a property named RowError. When the current record of the dataset is one whose cached value raised an error, this property holds the exception raised during the call to ApplyUpdates, otherwise the property is nil.

FireDAC datasets also support a filter flag (used with the FilterRecord and StatusFilter properties) named rtHasErrors. You can use this flag to filter the FDMemTable records on those for which an error was raised during ApplyUpdates. ClientDataSets do not support the RowError property and do not support the rtHasErrors flag.

However, these values are only useful if the cache is intact, and from my tests, calling apply updates to an FDMemTable always clears the cache.This means that if you are going to try to handle errors in the call to ApplyUpdates, you must do so from the OnReconcileError event handler of the FDMemTable.

Regardless, following a call to ApplyUpdates on a FireDAC dataset, you must deal with the errors, on a record by record bases, before flushing the cache. In my opinion, the ClientDataSet way of doing this is much easier to deal with.

Applying Updates to Master/Detail RelationshipsA ClientDataSet can apply updates to its data, via a DataSetProvider, through a single call to ApplyUpdates. If the ClientDatasSet includes one or more nested datasets whose data has changed, the call to ApplyUpdates on the ClientDataSet applies changes to the nested dataset data as well.

CLIENTDATASETS AND FDMEMTABLES COMPARED: PART 2 (CONTINUATION 1)

Page 26: blaise pascal magazine 40

Issue Nr 2 2015 BLAISE PASCAL MAGAZINE26

Unfortunately, calling ApplyUpdates on an FDSchemaAdapter works the same way as applying updates on an FDMemTable. The cache is cleared unconditionally. If you want to handle any errors, you must do so from the FDSchemaAdapter's OnReconcileRow event handler.

ENTERING AND EXITING CACHED UPDATES

STATUSFILTER DEFAULT VALUE

Another difference is that the ClientDataSet.StatusFilter property and the FDMemTable.FilterRecords property (the FDMemTable equivalent of ClientDataSet.StatusFilter) operate differently. The default value for StatusFilter in a ClientDataSet is an empty set of TUpdateStatus flags. For an FDMemTable, it is a set that includes usUnmodified, usModified, and usInserted. Granted, the way that FDMemTable does this is more intuitive, but it is a difference nonetheless.

Dynamic Nested DataSets

Figure 2. A ClientDataSet loads linked detail tables from a DataSetProvider into nested dataset fields

This is the mechanism used by ClientDataSets to apply updates to master/detail relationships.

FireDAC uses another method for caching updates to master/detail relationships, something that FireDAC refers to as centralized cached updates.With centralized cached updates, two or more FireDAC datasets, related in a master/detail relationship, point to a single FDSchemaAdapter. While the FireDAC datasets are placed in a cached update mode manually, the FDSchemaAdapter is used to apply the updates to all of the associated FireDAC datasets.

The use of the centralized model of cached updates is demonstrated in the project named CentralizedCachedUpdates. The main form of this application is shown in Figure 1, on page23.

Another cached update difference between ClientDataSets and FDMemTables is related to entering and exiting the cached updates state. If a ClientDataSet has cached changes, you can set the LogChanges property to false, thereby terminating the cached updates state and aborting all changes. With an FDMemTable, you cannot set CachedUpdates to false when there are records in cache.

You must either apply the updates (using ApplyUpdates, and in the case of non-FDMemTable FireDAC datasets, CommitUpdates) or cancel them (using either CancelUpdates or CommitUpdates) before you can exit the cached updates mode.

When a ClientDataSet points to a master table of a dynamic master-detail relationship (one defined by MasterSource and MasterFields, or one defined by a detail query linked to a master table by way of query parameters), the ClientDataSet will load the detail table as a nested dataset (loading is actually performed by the DataSetProvider to which the ClientDataSet points).

An example of a nested dataset can be seen in Figure 2. The top DBGrid holds the values returned from a DataSetProvider to a ClientDataSet, where the DataSetProvider pointed to the master query of a dynamic master/detail relationship. The detail dataset contains the orders for the selected customer.

CLIENTDATASETS AND FDMEMTABLES COMPARED: PART 2 (CONTINUATION 2)

Page 27: blaise pascal magazine 40

27Issue Nr 2 2015 BLAISE PASCAL MAGAZINE

Note the OrdersQuery field in the top grid. This is the nested dataset. When the ellipsis is clicked on the OrdersQuery field, the nested data is display in a dynamically created grid. Also note that the lower DBGrid displays these orders as well, which was accomplished by pointing another ClientDataSet to the dataset field (OrdersQuery).While FDMemTables support the creation of nested datasets, these can only be the result of creating the FDMemTable based on defined FieldDefs or TFields of the type DataSetField. An FDMemTable that loads its data from the master table of a dynamic master-detail relationship does not obtain a nested dataset field representing the detail table.

Similarly, while FDMemTable supports nested datasets, these cannot be used to apply cached updates in the same manner as ClientDataSets. ClientDataSets can apply updates to master-detail relationships using nested datasets, FDMemTable cannot.

Nested datasets play an important role in the ClientDataSet's ability to support cached updates with master-detail relationships. As I've mentioned already, FireDAC datasets support cached updates directly, meaning that FDMemTables are not necessary is all the only feature you need from the FDMemTable is cached updates. For FireDAC datasets that need to cache updates on master-detail relationships, the datasets can employ an FDSchemaAdapter.

DataSnap

data source, typically a database, and passes it to a client application. If the client application makes changes to that data, a delta is passed from the ClientDataSet on the client to a DataSetProvider on the server, which in turn applies those changes to the underlying database.

The key to making this work, from a ClientDataSet perspective, is embodied in the ClientDataSet/DataSetProvider interaction. The DataSetProvider resides on the DataSnap server, and the ClientDataSet interacts with it by way of several client-side components. In the latest incarnation of DataSnap, those components are a dbExpress SQLConnection (employing its DataSnap driver), and a DSProviderConnection.

There are three aspects of ClientDataSets that make DataSnap work smoothly. First, opening a ClientDataSet that points to a DataSetProvider on a DataSnap server retrieves data, and calling ApplyUpdates sends the change cache back to the DataSetProvider for resolution. Second, the use of nested datasets permits changes made to related data (in a master/detail sense) to be updated with a single call to ApplyUpdates. Finally, the Params and CommandText properties of the ClientDataSet permit the ClientDataSet to effortlessly pass parameter values, and even entire queries, to the DataSetProvider, permitting a great deal of flexibility from the client-side of the DataSnap equation.

The use of ClientDataSets in a DataSnap client/server interaction is demonstrated in a set of projects located in the DataSnap directory. Figure 3 shows how the server methods unit looks in the designer.

Figure 3. The server methods module of a traditional DataSnap server

ClientDataSets were designed for MIDAS, which was released with Delphi 3. While the name has subsequently changed to DataSnap, the essential model is the same. A middle-tier server (the DataSnap server) retrieves data from a

CLIENTDATASETS AND FDMEMTABLES COMPARED: PART 2 (CONTINUATION 3)

Page 28: blaise pascal magazine 40

Issue Nr 1 2015 BLAISE PASCAL MAGAZINE28

Here is the underlying class definition.

typeclass

private

public

function string string

function string string

end

= ( ) : ; : ; : ; : ; : ; : ; : ; ( : ): ; ( : ): ; ;

TServerMethods1 TDSServerModule

FDConnection1 TFDConnection

CustomersQuery TFDQuery

CustomersQueryA TFDQuery

CustomerProvider TDataSetProvider

OrdersQueryA TFDQuery

CustomersSourceA TDataSource

CustomersOrdersProvider TDataSetProvider

EchoString Value

ReverseString Value

{ Private declarations }

{ Public declarations }

typeclass

private

public

function string string

function string string

function

function

function

procedure const

procedure const

end

= ( ) : ; : ; : ; : ; : ; : ; ( : ): ; ( : ): ; : ; : ; ( : ): ; ( : ); ( : ); ;

TServerMethods1 TDSServerModule

CustomerQuery TFDQuery

FDConnection1 TFDConnection

FDStanStorageBinLink1 TFDStanStorageBinLink

FDStanStorageJSONLink1 TFDStanStorageJSONLink

OrdersQuery TFDQuery

CustomerOrdersQuery TFDQuery

EchoString Value

ReverseString Value

GetCustomerData TFDJSONDataSets

GetCustomersOrders TFDJSONDataSets

GetOrdersForCustomer CustNo Double TFDJSONDataSets

ApplyCustomerUpdates ADeltaList TFDJSONDeltas

ApplyCustomersOrdersUpdates ADeltaList TFDJSONDeltas

{ Private declarations }

{ Public declarations }

Until recently, FDMemTables were not well suited for the DataSnap environment. Conveying data from the DataSnap server to an FDMemTable on the DataSnap client had to be performed manually. The same thing can be said regarding the FDMemTable delta (the change cache).

server can use TFDJSONDeltasApplyUpdates class to resolve the changes in the DataSnap client's change cache to the underlying database. Figure 4 - at the bottom - shows the FDMemTable version of a DataSnap server that is similar to the ClientDataSet one shown earlier. While there is not much complexity in the number of components, the underlying class structure is dramatically different, in order to expose sufficient custom methods to transfer the same data as provided for using the ClientDataSet /DataSetProvider model. This can be seen in the following class declaration. FireDACJSONReflect does not specifically address master/detail relationships, nor does it provide an infrastructure for passing query parameters or SQL statements from the client to the server.

Beginning with Update 2 of Delphi XE5, the introduction of the FireDACJSONReflect unit has partially addressed both of these issues. Specifically, you can now use the TFDJSONDataSets class to package one or more FireDAC datasets nto a specialized class, which in turn can be streamed from the DataSnap server to the DataSnap client through custom methods that you add to the server methods unit of the DataSnap server. Likewise, the TFDJSONDeltas class can be used to package the deltas of one or more FDMemTables for return to the DataSnap server, again through custom

Master/detail relationships must be configured manually on the DataSnap client (via the MasterSource and MasterFields properties of the client-side FDMemTables, or MasterSource on the detail table combined with a parameterized query on the detail table). And, if you want to convey parameters or even entire queries from the clientto the server, you will have to do this through

passed to custom server-side methods. Yet another feature, introduced in Delphi XE7, appears to provide an alternative for FireDAC, and it can handle master/detail relationships. In XE7 the FDSchemaAdapter received SaveToFile,Figure 4

methods that you add to the DataSnap server's server methods unit. From there, the DataSnap

CLIENTDATASETS AND FDMEMTABLES COMPARED: PART 2 (CONTINUATION 4)

Page 29: blaise pascal magazine 40

29Issue Nr 2 2015 BLAISE PASCAL MAGAZINE

SaveToStream, LoadFromFile, and LoadFromStream methods. These can be used to persist and restore the data managed by an FDSchemaAdapter, whether it is connected to a single FDMemTable (or FDQuery), or several, through master/detail relationships.

Using the FDSchemaAdapter, it is possible to transfer data from one or more FDMemTables on the DataSnap server, using a stream, to the DataSnap client, and back. There are only two problems with this. First, the file or stream created by the FDSchemaAdapter contains every record in the underlying FDMemTable or FDMemTables, and, when there are changes in the change cache, additional data as well. That's a lot of data to push back and forth. By comparison, when you call ApplyUpdates on a ClientDataSet in a DataSnap client, only the change cache is returned to the server. Unless you are working with just a few records, the amount of data being transferred back to the DataSnap server using an FDSchemaAdapter can be significant.

Bottom line is this. You can implement DataSnap clients and servers using FireDAC and FDMemTables, but it is going to take more work than the same application built using ClientDataSets and DataSetProviders. At least this statement is true as of the time of this writing. I anticipate that at some time in the future FDMemTables will gain additional features which will make them more suitable for the DataSnap server/DataSnap client interaction.

There are additional differences, and they all represent advantages of FDMemTables over ClientDataSets. These are:

• ClientDataSets requires MidaLib (a Delphi unit) or midas.dll (a windows dynamic link library). FDMemTable is written entirely in Object Pascal, and does not require any additional libraries.

• For in-memory operations, such as searches and filtering, FDMemTable is generally faster than ClientDataSets.

• ClientDataSets exhibit a significant performance decline when holding a large amount of data, somewhere in the 200,000 record range. FDMemTables do not exhibit this same loss in performance.

• FDMemTable supports copying multiple result sets from FireDAC datasets. When loading a ClientDataSet via a DataSetProvider, you can load only from a single data set.

Both ClientDataSets and FDMemTables are in-memory datasets that share a large number of features. At the same time, there are significant differences. Which should you use in your applications?

The answer is pretty simple. If an FDMemTable supports the features you need, use it instead of a ClientDataSet. FDMemTables are the future of in-memory datasets in Delphi. All innovations involving in-memory datasets will appear in FireDAC as Delphi continues to evolve. ClientDataSets, by comparison, are legacy components, based on a C library that is only modified if very serious bugs are discovered. You will see no new features being added to ClientDataSets by Embarcadero in the future.

There are, however, many features not supported by FDMemTables, or for which an FDMemTable would otherwise require a more burdensome solution. Clearly, cached updates is one of those areas. In those cases, use, or continue to use, a ClientDataSet.

Summary

About the AuthorCary Jensen is Chief Technology Officer of Jensen Data Systems. Since 1988 he has built and deployed database applications in a wide range of industries, and is available for development, consulting, and training. Cary is an Embarcadero MVP, a best selling author of more than 20 books on software development, and holds a Ph.D. in Engineering Psychology, specializing in human-computer interaction. He is also co-presenter with Ray Konopka on this year's Delphi Developer Days 2015 tour. Visit http://www.DelphiDeveloperDays.com to learn more.Miscellaneous

CLIENTDATASETS AND FDMEMTABLES COMPARED: PART 2 (CONTINUATION 5)

Page 30: blaise pascal magazine 40

Group discounts are available

Issue Nr 2 2015 BLAISE PASCAL MAGAZINE30

Page 31: blaise pascal magazine 40

START WITH FUNCTION TESTING

Measure Correctness and StabilityToday we step through the realm of testing and bug-finding and his visual representation in metrics and audits.

The traditional approach to quality control and testing has been to apply it after the development process completes. This approach is very limited as uncovering defects or errors at a late stage can produce long delays with high costs while the bugs are corrected, or can result in the publishing of a low-quality software product.

This function counts all sub-strings in a text or string. The point is that the function uses another functions like Pos() and StringReplace().

Do we have to test it also? No, but we need a reference value:

And with Assert we do automate that reference

value with

you set an expression value which you expect to be true:

(more on page 34):procedure const

string

( : ;

: );

Assert expr Boolean

msg

Sometimes it is helpful to track your program's execution as your program runs. Or maybe you want to see a variable's value without stopping program execution at a breakpoint to test. The OutputDebugString() function enables you to do exactly that. This function is a convenient

That's all you have to do. Because Delphi, Lazarus or Free Pascal is installed as the system debugger, any strings sent using OutputDebugString will show up in the Event Log. You can place calls to OutputDebugString anywhere you want in your

code.To view the value

of a variable, you must format a string and send that string to OutputDebugString, for example:

procedurevar

stringbegin

end

;

: ; : ;

:= ( , ); := ( , [ ]); ( ( )); ( )

;

GetOutputDebugString

x Integer S

x CountPos TESTTEXT

S Format X

OutputDebugString PChar S

writeln S

{ Some code here...}'max'

'X := %d'

// OutputDebugString(PChar(Format('[%s][%s] %s',[aCaption, GetFormatDT(StartDT), aText])));

function const string stringbegin

if or or

then

else

end

( : ; : ): ;

( ( )= ) ( ( )= ) ( ( , )= ) := := ( ( )-

( ( , , , [ ]))) div ( );

;

CountPos subtxt Text Integer

Length subtxt Length Text

Pos subtxt Text

result

result Length Text

Length StringReplace Text subtxt

rfReplaceAll Length subtxt

0 0

0

0

''

The result is 3, so we better extract our test-string in a constant:

PrintF CountPos( ,[ ( , )])'CountPos: %d' 'max' 'this is max of maXbox a max numbermax'

Const = ;( ,[ ( , )])TESTTEXT

PrintF CountPos TESTTEXT

'this is max of maXbox a max numbermax'

'CountPos: %d' 'max'

Assert CountPos TESTTEXT( ( , )= , )'max' 'count pos assert'3

• Find the position and count of all strings in another is the function to test but is the function case sensitive or not?

debugging tool that many programmers overlook, primarily because of a general lack of discussion on

the subject.

maXbox Starter 36 By Max Kleiner

Lets start with a first function and how to improve and test it:

OutputDebugString inttoStr CountPos TESTTEXT( ( ( , ))+ );

'max'

'CountPos runs..'

Also the Event Viewer is a Microsoft Management Console (MMC) snap-in that enables you to browse and manage event logs. It is an indispensable tool for monitoring the health of systems and troubleshooting issues when they arise. Look at the last entry in the Event Log shown in the next picture. That entry was generated using the code on the next page:

maXbox

maXboxIssue Nr 2 2015 BLAISE PASCAL MAGAZINE 31

Page 32: blaise pascal magazine 40

When you use Event Viewer to troubleshoot or track a problem, you need to locate events related to the problem, regardless of which event log they appear in. Event Viewer enables you to filter for specific events across multiple logs as of maXbox. We need values in

a logName, logCaption, logDetails and some RawData:

The Application log (see picture) contains events logged by applications or programs. For example, a database program might record a file error in the application log. You as a developer decide which events to log. To log a sound in a multimedia app for e.g. you have to set a song first:

playMP3 mp3path

closeMP3

DebugOutputString mp3path

( ); ; ( + ); 'closeMP3: '

In a shortlink %windir%\system32\eventvwr.msc /s

you start the eventlog:

Analytic or test events are published in high volume. They describe program operation and indicate problems that can't be handled by user tasks or intervention.

WriteToOSEventLog TESTTEXT( , , , );'mX3' 'maXbox' 'Details3'

WriteToOSEventLog logName logCaption logDetails logRawData Str( , , : ; : );const String const

WriteToOSEventLog TESTTEXT( , , , );'mX3' 'maXbox' 'ID45:detail3'

START WITH FUNCTION TESTING (CONTINUATION 1) maXbox

Issue Nr 1 2015 BLAISE PASCAL MAGAZINE32 maXbox

Page 33: blaise pascal magazine 40

Lets go back to our function to test and build a test function too.

function const string stringbegin

if or or

then else

end

( : ; : ): ;

( ( )= ) ( ( )= ) ( ( , )= ) :=

:= ( ( )- ( ( , , , [ ]))) div ( );

;

CountPos subtxt Text Integer

Length subtxt Length Text Pos subtxt Text

result

result Length Text Length StringReplace Text subtxt

rfReplaceAll Length subtxt

0 0 0

0

''

Such a small function like above contains another 3 functions (yellow) and before testing we should also check the understanding and the design of the function. For example StringReplace

which replace one or more substrings found within a string does have more parameters to test like the .On the other side we

can trust in a stable function of the runtime library otherwise we loose time not to mention the frustration caused by a bug that is difficult to find.

I asked a few lines above if the function to test is case-sensitive or not, do you remember? Yes it is and we do have to consider that in our test-string and test-function with Uppercase too.

()

[ ]rfReplaceAll

functionbegin

if

then

end

: ;

:= ; ( ( ), ( ))= := ;

;

CountPosTest boolean

result false

CountPos Uppercase Uppercase TESTTEXT

result true

'max' 4

Each time we test (or change) our function we call the test-function with a test-string and check the reference value which must be 4. Normally you test a function by creating a test application or unit and if something goes wrong or crashes you will run the test application under the debugger and watching the values.

A debugger helps you find bugs or errors in your program at runtime. But the debugging process isn't just for finding and fixing bugs - it's a development and test tool as well. Another great way to test a function is to compare the result with a already well known standard function, for example CountStr :

or check with a subroutine which both of them uses: Function Unit SysUtils

StringReplace: Replace one or more

substrings found within a string

()

function const string

var begin

while do begin

end

end

( , : ): ;: ;

:= ; := ( , ); > ( ); := ( , , + ); ;

;

CountStr ASearchFor ASearchIn Integer

Start Integer

Result

Start Pos ASearchFor ASearchIn

Start

Inc Result

Start PosEx ASearchFor ASearchIn Start

0

0

1

Or you will look at the web and ask to a search machine: How do I find and count the total

amount of times that a particular word appears? Often, as programmers gain experience in building applications,

they develop a sixth sense for locating the cause of in-correctness or access violations. With asserts you can support that feeling what could crash. An assert function is used to make sure that certain conditions which are assumed to be true are never violated. Assert provides an opportunity to intercept an unexpected condition and halt a program rather than allow execution to continue under unanticipated conditions.

If you encounter problems using any feature of Event Viewer, first ensure that the Windows EventLog service is running. If you are working with event subscriptions, ensure that the Windows

Event Collector service is running.With this call in maXbox you can run the event log from the script:

Next we go to the topic of Unit Testing but not to generate units (this is another story)

but consuming as a test-function or protocol e.g. in maXbox I do have some unit tests to check conditions before running a script!:

ExecuteCommand('cmd','/c %windir%\

system32\eventvwr.msc /s ')

// test routines with assert or assert2 builds

' 6 Units Tested with success '

' 6 Units Tests with

success!'

; ; ; ; ; ;

( ) (

);

SelftestPEM

SelfTestCFundamentUtils

SelfTestCFileUtils

SelfTestCDateTime

SelfTestCTimer

SelfTestCRandom

Writeln

ShowMessageBig

Function const string ( , : ): ;CountStr ASearchFor ASearchIn Integer

A unit is the smallest testable part of software. It usually has one or a few inputs and usually a single output. In procedural programming a unit may be an individual program, function, routine,

procedure, etc. In object-oriented programming, the smallest unit is a method, which may belong to a base/ super class, abstract class or derived/ child class.

maXboxSTART WITH FUNCTION TESTING (CONTINUATION 2)

maXboxIssue Nr 2 2015 BLAISE PASCAL MAGAZINE 33

Page 34: blaise pascal magazine 40

• For me the important thing is to isolate the development environ-ment from the test environment and make sure you are using a version control system to keep track of your test scripts and constants.

V1 SelftestPEM

V1 SelfTestCFundamentUtils

V1 SelfTestCFileUtils

V1 SelfTestCDateTime

V1 SelfTestCTimer

V0 SelfTestCRandom

. ; . ; . ; . ; . ; . ;

2.1

7.0

2.0

1.1

2.5

9.2

Lets say you have a program comprising of two units and the only test you perform is system testing between Win and Linux:

SelfTestCFileUtils

SelfTestCDateTime

Assert2 FilePath

Assert2 PathCanonical

Assert2 UnixPathToWinPath

Assert2 WinPathToUnixPath

A EncodeDateTime

Assert2 Month A

S GMTTimeToRFC1123TimeA A True

Assert2 S

S GMTDateTimeToRFC1123DateTimeA A True

Assert2

S

Assert2 TickDeltaW

Assert2

CPUClockFrequency

Assert2 Length RandomPassword

True True True

Assert2 Length

RandomPassword True True True

CompareDateTime DateOf Now DateOf Now

; ;

( ( , , , ) = , );

(( , ) = ,

); (

( ) = , ); (

( ) = , ); := ( , , , , , , ); ( ( ) = , ); := ( , ); ( = , ); := ( , ); (

= , );

(( , ) = , );

( > , );

( (( , , , , )) = , );

( (( , , , , )) =

, ); ( ( ), ( )+ )

//as an extract in test-cases:

'C' '..\X\Y' 'A\B' '\'

A\X\Y\C' 'FilePath'

'\A\B\..\C\D\..\..\..\..\' '\' '\'

'PathCanonical'

'/c/d.f' '\c\d.f' 'UnixPathToWinPath'

'\c\d.f' '/c/d.f' 'WinPathToUnixPath'

'EncodeDateTime'

'12:11:10 GMT' 'GMT'

'Sun, 02 Sep 2001 12:11:10 GMT'

'GMTDateTimeToRFC1123DateTime'

'TrickDelta'

'RTC Prepare'

'random passwd'

'random passwd'

2001 09 02 12 11 10 0

9

$FFFFFFF6 0 10

0

0 0 0

1 1

1

1

You see the screen with those test scripts notion and some calls with external dependencies.

One of a question often arises is the following:Why do I continue getting error messages even after I have written an exception handler?

Answer: In its default settings, the Delphi IDE notifies you whenever an exception occurs in your program.What’s important to realize is that at that point, none of your program’s exception-handling code has run yet. It’s all Delphi itself; its special status as a debugger allows it to get first notification of any exception in your program, even before your program knows about it.

Simply put, debugging when using exception handling can be a bit of a pain. Each runtime an exception is raised, the debugger pauses program execution at the except block just as if a breakpoint were set on that line.

maXboxSTART WITH FUNCTION TESTING (CONTINUATION 3)

Issue Nr 1 2015 BLAISE PASCAL MAGAZINE34 maXbox

Page 35: blaise pascal magazine 40

If the except block is in your code, the execution point is displayed as it would be if you had stopped at a breakpoint.You can or must restart the program again by clicking the Run button, or you can step through your code.

You might not be able to continue execution of your program after an exception is raised. Whether you can continue debugging depends on what went wrong in your program.

If an exception passes through the tryblocks in the application code, the application automatically calls the HandleException method. Unless the exception object is EAbort, HandleException calls the OnException handler, if one exists. Otherwise, it calls ShowException to display a message box indicating an error occurred.

maXbox

maXboxSTART WITH FUNCTION TESTING (CONTINUATION 4)

maXboxIssue Nr 2 2015 BLAISE PASCAL MAGAZINE 35

Page 36: blaise pascal magazine 40

Code Review Integration

Code-coverage use. So we have seen testing goes with automation to test. There are tools which automate your tests driven by software metrics.

With these tools at hand, quality managers, developers and technical architects have a complete workbench to rate application quality, perform quantitative analysis and define corrective action. Those tools measure the amount of test-cases and the metric is called code-coverage.

The cost of fixing a defect detected during unit testing or code metrics is lesser in comparison to that of defects detected at higher levels. Unit Testing is the first level of testing and is performed and logged prior to Integration Testing.

But most of the time we forget to check our code twice. To avoid this problem, metric products provide support for the so called Continuous Inspection paradigm by enabling real-time notifications when code quality defects are introduced in an application. This transparency ensures that internal quality assurance is an integral part of the software development life-cycle, rather than an afterthought.

These features enable full support of a Continuous Inspection process and produce three immediate benefits:

• They encourage developer adoption by enabling developers to quickly identify code improvements and quick wins.

• They improve quality of code produced by increasing developer knowledge and understanding of code quality issues.

• They reduce maintenance cost through early identification of quality issues.

Every step in your development work-flow that can be automated should be. You need this automation to be able to focus all your time on building your product and providing value to your customers. Testing is one of those steps where automation is key.Test the script with F9 / F2 or press Compile. So far now we’ll open the test-function example: 587_one_function_assert.txt

http://www.softwareschule.ch/examples/587_one_function_assert.txt

Hope you did already work with the Starter 24 on Clean Code topics: https://bitbucket.org/max_kleiner/maxbox3/wiki/maXbox%20Tutorials

better office benelux | asterlaan 6 5582EH waalre | 040 – 222 26 43 [email protected]

maXboxSTART WITH FUNCTION TESTING (CONTINUATION 5)

Page 37: blaise pascal magazine 40

ConclusionStepping through code is one of the most basic debugging and testing operations, yet it still needs to be mentioned here. Sometimes you fail to see the forest for the trees. (Just as sometimes authors of programming books fail to include the obvious!) Reviewing the basics from time to time can reveal something you were not previously aware of.Test functions return a boolean that you can test for conditional parts of the functionality (correctness).It is important to understand that when you catch an exception, code execution continues after executing the except block. One of the advantages to catching exceptions is that you can recover from the exception and continue program execution. Notice the Exit statement in a code snippet. In this case, you don't want to continue code execution following the exception,

so you exit the procedure after handling the exception.

Lyall Watson

“If the brain were so simple we could understand it, we would be so simple we couldn't.”

Feedback: [email protected]: Kleiner et al., Patterns konkret, 2003, Software & Support http://www.softwareschule.ch/download/codesign_2015.pdfhttp://softwaretestingfundamentals.com/unit-testing/http://www.sonarsource.com/products/features/continuous-inspection/https://www.academia.edu/5129685/Software_Quality_with_SONARhttps://github.com/maxkleiner/maXbox3/releases

Appendix: Assert and WriteToOSEventLog Study

PROCEDURE const stringvar begin

asm

end

if then begin

endend

procedure const

const Stringvar array ofbegin

if thennil

else nil

if then begintry

nil

finally

endend

end

( : ; : );, : ;

, [ + ] , , : , , [ + ] , ;

( = ) . . (

+ + ( , ) + + ( , ) );

; ;

;

( , , : ;

: = ); : ; : [ ] ;

<> := ( , ( )) := ( ,

( ( ( ( )), ))); > [ ]:= ( ); [ ]:= ( ); ( , , , , , , ( ), @ , ( )); ( ); ; ;

;

Assert Cond boolean MsgprogSeg progOfs word

mov ax bpmov es axmov ax word ptr esmov progSeg axmov ax bpmov progOfs ax

Cond FALSEmmDebug Lines Add Msg

IntToHex progSeg IntToHex progOfsShowModal

WriteToOSEventLog logName logCaptionlogDetails UnicodeString

logRawDataeventSource THandle detailsPtr PWideChar

logNameeventSource RegisterEventSourceW PWideChar logNameeventSource RegisterEventSourceW

PWideChar ChangeFileExt ExtractFileName ParamStreventSource

detailsPtr PWideChar logCaptiondetailsPtr PWideChar logDetailsReportEventW eventSource EVENTLOG_INFORMATION_TYPE

Length logRawData detailsPtr Pointer logRawData

DeregisterEventSource eventSource

04

0

02

4 4

0..1

00

01

0 02

' at location '':'

// WriteToOSEventLog

''

''

''

Check the script! Script Example: maxbox3\examples\318_excel_export3

maXboxSTART WITH FUNCTION TESTING (CONTINUATION 6 - END)

maXboxIssue Nr 2 2015 BLAISE PASCAL MAGAZINE 37

Page 38: blaise pascal magazine 40

In the Adobe PDF file it is possible to view 2 pages side by side: go to: File Edit g Preferences g Page Layout: To view some images completely you need to see the two pages side by side. You can adjust this. The modern screens allow side-by-side-view.

SERVICE ARTICLE

Page 39: blaise pascal magazine 40

BLAISE 2015

Page 40: blaise pascal magazine 40

WORKING WITH BEACONS IN DELPHI XE8

With the release of Delphi XE8 one of the new features added to the RTL is support for Bluetooth beacons. This includes support for both iBeacon and AltBeacon specifications.

What are Beacons?Beacons are low energy Bluetooth devices that transmit data. The data transmitted enables smart devices to be informed when a beacon is within range. Every beacon transmits data to a standard as well as being able to transmit manufacturer specific data as well. Each beacon transmits the following information in Advertising Mode:

By Jeremy North

Proximity UUID Unique identifying GUIDMajor Integer value used to help identify a specific BeaconMinor Integer value used to help identify a specific BeaconTxPower Indicates the signal strength 1 metre from the device

Platform Support

Beacons are supported using OS X, iOS and Android in Delphi XE8. There is no support for Windows platforms at this time.

My Beacon of choiceThe beacons I have used are the Estimote

beacons.

There is no specific reason behind using Estimote, they just happened to be the first I looked into and the development kit (which includes 3 beacons) costs $99 USD. They took about a week to ship to Australia, which wasn't bad.

Identifying a BeaconThe UUID, Major and Minor version values are used to identify a beacon. With Estimote (at least) it is not possible to setup a second beacon with the same values. All Estimote beacons are delivered with the same UUID value and random Major and Minor values. Before deploying beacons in the field, you should at least change the UUID value from the default. These three values can be thought to be hierarchical in nature and allow you some flexibility to make it easier to identify particular beacons.

Identification is very important when interacting with Beacons. With your app you can specify to scan for beacons with a UUID value, a UUID and Major version combination or for a specific beacon by specifying all three (UUID, Major and Minor).

(http://www.estimote.com/)

There is an attempt to have a global database of proximity UUID allocated to a company to help prevent collisions - https://openuuid.lime-company.eu/.

Distance and Proximity ZonesA common issue developer's face when interacting with beacons is the sometime lack of accuracy in calculating the distance between the beacon and the app interacting with it. This can mainly be attributed to radio signal interference, as a beacon is just a small radio transmitting a signal.

When using the iBeacon (Standard) mode, the distance is calculated based on the iOS Core

Location framework. For Alternate beacons, the distance is calculated based on a formula provided in an IEEE Xplore library paper.

The paper title and URL is located in the RssiToDistance method of the System.Bluetooth unit. Since the accuracy of distance calculations can be inconsistent an event (OnCalcDistance) is provided to allow for a custom distance calculation.

Proximity zones indicate the distance from a beacon you are. The values for Proximity (in the Embarcadero implementation) are Immediate, Near, Far and Away. The following table gives the distance range for each Proximity value.

Proximity Value Distance (metres)Immediate less than 0.5Near 0.5 to 3Far 3 to 30Away 30+

The proximity is based upon the RSSI (received signal strength indication) and signal power values received from the Beacon. Fluctuation will occur in the calculated distance even if neither the smart device nor Beacon is moving. This could be caused by other radio signals in the environment or even be caused by the material the building is constructed with.

The values above are taken from the beacon implementation source code from Embarcadero. Manufacturers may assign different ranges to the zones; for example, Estimote provides the following ranges with their SDK.

Issue Nr 1 2015 BLAISE PASCAL MAGAZINE40

Page 41: blaise pascal magazine 40

Using the TBeacon ComponentThere has been a lot of code written behind the scenes to make applications that require beacon support very simple. For this article I will use the new TBeacon component. This component wraps the TBeaconManager class defined in the System.Beacon unit. If you don't want to use the design time component, you can easily replicate the functionality using TBeaconManager directly.

As I have three beacons, the apps user interface will update differently for each beacon.

I will place a beacon in the office, lounge and kitchen. When the application is running and beacon scanning enabled, the office beacon will display a quote on screen, the kitchen beacon will display a recipe and the lounge will display the title of a Disney movie.

While each beacon will be able to do something different, remember the beacon has no functionality – it just broadcasts the four pieces of information. For this app the Major version value of the beacon determines what is displayed. The interface is very basic; a Switch to toggle the Enabled property of the TBeacon component and a couple of labels to output the text that accompanies each beacon as it comes into range.

Below is a screen capture of the interface at design time as well as the structure view to highlight the simplicity.

The TBeacon component has a number of properties and events. Since I am using OS X and iOS platforms for deployment, many of the properties are not used. This is due to using the built in iBeacon support for beacons in those frameworks. Below is a screen capture of the published properties for the component. For the app I only had to add an entry to the MonitorizedRegions collection. This can be done at design time however in the constructor I clear the design time entry and add the beacon region details explicitly.

I'll highlight a couple of properties that I believe are important / interesting.

Properties

ModeThis is the kind of Beacon that will be monitored. There are two beacon standards, iBeacon (referred to as Standard in the Embarcadero framework) and Alternate. AltBeacon is a competing specification with iBeacon however fortunately for us Embarcadero supports both with their beacon framework.

WORKING WITH BEACONS IN DELPHI XE8 (CONTINUATION 1)

Issue Nr 2 2015 BLAISE PASCAL MAGAZINE 41

Page 42: blaise pascal magazine 40

Enabled

CalcMode

SPC

Properties of special note

ScanningTime

ScanningSleepingTime

Events

Must be set to True to ensure monitoring of specified regions occur.

This determines how the distance is calculated. The default value of Stabilized means the beacon framework will use a common distance calculation for you. The other value is Raw and this means no calculation is done.

This is the signal processing constant which is used when calculating the distance. This property is not used for iOS deployed apps.

The following properties are not used for iOS apps but are important because both affect battery life and one may be too short depending on the signal frequency of your beacon.

This is the time spent scanning a region. The default value of 500ms might be too low if your beacons are setup to only transmit every 1000ms. The Estimote beacons default signal interval is 950ms. They will still be located, but it might take a couple of scans to discover so if speed is an issue, increasing this value will help.

This is the elapsed time in milliseconds between scans.

A number of events are provided with the TBeacon component. Three of the events provide the most use. These are OnBeaconEnter, OnBeaconExit and OnBeaconProximity.

OnBeaconEnter

The event is called when a beacon has been identified in the region specified. The event parameters include a reference to the IBeacon interface of the internally stored beacon as well as a full list of beacons within the region.

OnBeaconExit

The event signature is the same as the OnBeaconEnter event. The IBeacon parameter references the beacon that is no longer available, as well as the full list of beacons within the region.

OnBeaconProximity

This event is called when a monitored beacon has changed its proximity. In other words you are either getting closer to the beacon, or further from it. This event provides access to the beacon via the IBeacon interface as well as the new proximity value.It would have been nice if it also provided the previous proximity value.

The OnCalcDistance event is called to allow you to provide your own distance calculation of the beacon. If you are finding the default distance calculation is inaccurate with your beacon, you might try an alternate calculation available on the internet. Note: Not many SDK providers publish the formula used to calculate distance. Estimote do not publish the formula used.

The OnParseManufacturerData event is called once a beacon is located to allow interpreting the manufacture specific data available from the beacon. Many manufacturers provide additional information apart from the required values which are usually read by using their SDK. If you know the layout of the signal data, this event is called to allow you to interpret this additional data.

There are only three public methods available. They are StartScan, StopScan and Nearest. The first two are called internally when changing the Enabled property so you don't need to call them directly. The Nearest method could be of use depending on the app you are creating.

For example in the sample application, since I don't live in a mansion having three beacons around the house it is easy to be within the range of at least two at once.

Other Events

Public Methods

WORKING WITH BEACONS IN DELPHI XE8 (CONTINUATION 2)

Issue Nr 1 2015 BLAISE PASCAL MAGAZINE42

Page 43: blaise pascal magazine 40

THouseBeacon

FLocation THouseLocation

FMajor Word

FColor TAlphaColor

FTitle

FFontColor TAlphaColor

FProc THouseInfoProc

Create AMajor Word ATitle

ALocation THouseLocation

AColor AFontColor TAlphaColor

AProc THouseInfoProc

Title FTitle

Location THouseLocation FLocation

Major Word FMajor

Color TAlphaColor FColor

FontColor TAlphaColor FFontColor

Proc THouseInfoProc FProc

= : ; : ; : ; : ; : ; : ; ( : ; : ;

: ; , : ; : );

: ; : ; : ; : ; : ; : ; ;

classprivate

string

publicconstructor const const string

const

const

const

property string read

property read

property read

property read

property read

property read

end

Since the beacon details are registered, the method for updating the user interface is simple and only contains one conditional statement to cater for when no beacons are within range.

procedure const

beginif nil then

elsebegin

end

end

. ( : );

= . . := . ;

. := . ; . . := . ; . := . ; . . :=

. . ; ;

;

TfrmMain UpdateInterfaceFor ABeacon

THouseBeacon

ABeaconResetInterface

BackgroundRectangle Fill Color ABeacon Color

BeaconLabel Text ABeacon Proc

BeaconLabel TextSettings FontColor ABeacon FontColor

HeadingLabel Text ABeacon Title

HeadingLabel TextSettings FontColor

BeaconLabel TextSettings FontColor

// Call the method that gets the beacon specific content

Handled EventsThe sample handles three of the available TBeacon events. The first is the OnBeaconEnter event.

procedure const

const constvar

beginif in

thenbegin

end

end

. ( : ; : ; : );

: ;

. [ . , . ]

:= ( . ); ( ); ;

;

TfrmMain MainBeaconBeaconEnter Sender TObject

ABeacon IBeacon CurrentBeaconList TBeaconList

LBeacon THouseBeacon

ABeacon Proximity TBeaconProximity Immediate

TBeaconProximity Near

LBeacon GetBeacon ABeacon Major

UpdateInterfaceFor LBeacon

The second is the OnBeaconProximity event.

procedure

const const

beginif then

end

. ( : ; : ;

: );

>= . ;

;

TfrmMain MainBeaconBeaconProximity

Sender TObject ABeacon IBeacon

Proximity TBeaconProximity

Proximity TBeaconProximity Far

UpdateInterfaceUseNearest

Finally the OnBeaconExit event is very simple. It updates the interface to display information about the nearest beacon. If no beacon is within range, the user interface is cleared.

procedure

const

const

const

begin

end

. ( : ; : ; : );

;;

TfrmMain MainBeaconBeaconExit

Sender TObject

ABeacon IBeacon

CurrentBeaconList TBeaconList

UpdateInterfaceUseNearest

WORKING WITH BEACONS IN DELPHI XE8 (CONTINUATION 3)

By using the Nearest method in conjunction with the OnBeaconProximity, it is possible to also be showing information for the beacon the app is nearest. It is also advisable to use the Nearest method when a beacon has triggered the OnBeaconExit event to ensure your app interface doesn't go blank when there is still at least onebeacon within range.

Since the proximity zone is based on the distance calculation, it is possible to see unexpected results for proximity occasionally due to the inaccuracy in calculating distance.

The TBeacon component makes it very easy to interact with beacons so there are only a couple of interest points to cover from the accompanying app for this article to show.

A list of available beacons is created when the app starts.This allows us to update the interface based solely on the beacon Major version value. The class that holds the information is very basic and includes a method pointer for retrieving the actual content the beacon needs to display.

NOTE:

Useful Details

Code Samples

Issue Nr 2 2015 BLAISE PASCAL MAGAZINE 43

Page 44: blaise pascal magazine 40

Below is a device capture when running the app on my iPhone 5.

Using a Manufacturers SDKIt is important to point out that depending on the beacon manufacturer, additional data outside of the required information may be broadcasted. Estimote have a connectivity mode (which is an authenticated communication) where additional information can be retrieved from the beacon. For an Estimote beacon, this includes temperature, battery life, firmware updates and also the frequency at which the beacon signals. This information can only be used with using the official Estimote SDK with your app. This is not something I have attempted to do with Delphi yet.

WORKING WITH BEACONS IN DELPHI XE8 (CONTINUATION 4)

Before running the code for your beacons be sure to update the beacon identifying constants for the app.

ConclusionBeacons are an interesting addition to the world and definitely show promise in the areas of home automation and retail advertising. As beacons become more powerful, smaller (Estimote are releasing sticker Nearables soon) and additional sensors are added – the possibilities for developers to take advantage of them will increase.Hopefully I've provided a little insight into the world of beacons and have convinced you to acquire some to play around with.

About the authorJeremy Northowns a company called JED Services Pty. Ltd,which includes JED Software.He sells his components and IDE expertsthrough JED Software and does contracts underJED Services.He works exclusively on Win32 at themoment and has also done quite a bit of .Net inthe past. He wrote most of the initial release ofthe Ribbon controls for Delphi 2009.

Issue Nr 1 2015 BLAISE PASCAL MAGAZINE44

Page 45: blaise pascal magazine 40

The components found in the Visuino software represent their hardware components and you will easily be able to create and design your programs using drag and drop. No equipment or 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.

For those people who are not strong on writing code then designing, compiling and creating Arduino programs has never been easier! Why waste time on creating code when we have done all the hard work for you already? You have your Arduino board, and great hardware design, see it running in minutes, not hours!

Currently we are running a Beta program which you can be part of by joining our Google group. Join the group now to download and test the software or send an email to [email protected].

IN THE NEXT ISSUE:ALL ABOUT VISUINO

What is Visuino?Visuino is the latest innovative software from Mitov Software. A visual programming environment allowing you to program your Arduino boards. Although it currently supports the official Arduino boards, it is not restricted to their support alone and requests to support new hardware are welcome.

INTRODUCTION What is Arduino?

VISUINO IS THE LATEST INNOVATIVE PRODUCT FROM MITOV SOFTWARE.

www.visuino.com

Page 46: blaise pascal magazine 40

The number and types of devices people interact with on a daily basis have been expanding at an amazing rate. We now have phones, tablets, wearables, and more in the ever-growing “Internet of Things”. Delphi gives developers the solutions to keep up. Within the single Delphi development environment, you can build high performance, compiled native applications that easily connect with enterprise data, cloud services, devices, sensors, gadgets…and more!

Embarcadero® Delphi® XE8 is the fastest way for designing, coding, and extending “connected” apps across Windows, Mac, iOS, Android and IoT. Build industrial strength and Business ready solutions incorporating multi-ple native client platforms, mobile extensions, smart devices, cloud services, Enterprise and embedded data.

Extend and Connect Windows Apps

Multi-Device, Multi-form UI developmentDelphi XE8 multiplies developer productivity again with FireUI, enabling your team to deliver your apps natively for PCs, tablets, smartphones, and even wearables like smart watches, from a fully single codebase, in record time. Get connected apps to market faster by developing for multiple platforms and device form factors simultaneously, with one shared master form and device specific views as needed. Maintain one shared codebase without sacrificing native platform fidelity.

Mobilize with Enterprise Mobility Services

Use the new Enterprise Mobility Services (EMS), a turnkey middleware server, to connect users and apps to managed APIs, Enterprise databases and services hosted on-premises or in a private cloud. With its user management and authentication plus user and API analytics, Enterprise Mobility Services is ideal for enabling secure access from mobile and desktop apps to Enterprise SQL Databases such as Oracle, DB2, Microsoft SQL Server, Informix, Sybase, and many more.

Signi�cantly enhance performance with the new iOS 64 bit targeting native code compiling and Parallel Programming Library.

Use the FireUI Multi-Device Designer to build user interfaces once for multiple device form factors and OSs with native �delity, capabilities, and uniqueness.

Easily add proximity and location awareness to your apps with component level Beacon support.

Here’s what you can do with Delphi XE8

Extend your existing Windows applications with tethered mobile companion apps using Wi-Fi and Bluetooth connectivity.

Easily connect to popular cloud services with REST as well as BaaS providers for push noti�cations, authentication, storage and more!

Quickly deploy Enterprise Mobility Services (EMS) to publish and manage custom APls, Enterprise data, services, and analytics.

The Fastest Connected App Platform for Windows and Beyond

Delphi XE8

Tel: +31 23 542 22 27

Page 47: blaise pascal magazine 40

Features

Download a Free Trial Now! Visit www.embarcadero.com/trial

[email protected] | www.embarcadero.com

© 2015 Embarcadero Technologies, Inc. Embarcadero, the Embarcadero Technologies logos, and all other Embarcadero Technologies product or service names are trademarks or registered trademarks of Embarcadero Technologies, Inc. All other trademarks are property of their respective owners. 032415

Delphi XE8 System Requirements

• 1 GB RAM (2 GB+ recommended)

7-37 GB free hard disk space depending on edition and configuration, including space required for temporary files

• • • DVD-ROM drive (if installing from a Media Kit DVD) • Basic GPU – Any vendor DirectX 9.0 class or better (Pixel Shader Level 2) • Intel® Pentium® or compatible, 1.6 GHz minimum (2GHz+ recommended) • 1024x768 or higher-resolution monitor

• Mouse or other pointing device• Microsoft® Windows 8 or 8.1 (32-bit and 64-bit)

• Microsoft® Windows 7 SP1 (32-bit and 64-bit)

• Microsoft® Windows Server® 2008 and 2012 (32-bit and 64-bit) • Delphi can also be run on OS X by using a virtual machine (VM) such as

VMware Fusion or Parallels hosting Windows Vista, 7 or 8

For developing 64-bit Windows applications For developing Mac OS X applications For developing iOS applications Supported Deployment Platforms

PC running a 64-bit version of Windows or a 32-bit development PC connected with a PC running a 64-bit version of Windows.

PC running Windows connected with an Intel-based Mac or a Mac running Windows in a VM, with 2 GB RAM or more, running OS X 10.10 (Yosemite) or 10.9 (Mavericks).

PC running Windows connected with an Intel-based Mac or a Mac running Win-dows in a VM, with 2 GB RAM or more, running OS X 10.10 or 10.9 with Xcode 6 An Apple Developer account is required to deploy iOS apps to physical devices.

PCs and tablets with Intel/AMD processorsrunning Windows 7, 8, 8.1, Server 2008, or Server 2012. Macs running OS X 10.9or 10.10. iPhone, iPad, or iPod Touch running iOS 7. Android phones and tablets: ARMv7 devices with NEON support, running Ice Cream Sandwich (4.0.3-4.0.4), Jelly Bean (4.1.x, 4.2.x, 4.3.x) or KitKat (4.4.x) and Lollipop (5.x).

LICENSING

Indie license for hobbyists and getting started X

Full commercial development and deployment license X X X X

Earlier version access to licenses for Delphi 6 and 2007-XE7 X X X X

DATABASE AND CLOUD SERVICES

Local database connectivity to InterBase, SQLite, MySQL and more

IBLite embedded database with free unlimited deployment

Cloud computing with Amazon Web Services and Microsoft Azure

Database modeling and design with ER/Studio Developer Edition

X X X

X X X

X X X

X X X

X X X

X

X

X

X

X

X X

FRAMEWORKS, LIBRARIES, AND COMPONENTS

VCL for Windows framework with hundreds of visual components to create user interfaces, database access and more (components vary by edition)

X X X X X

VCL source code to modify, extend, and customize the included components X X X X

FireMonkey FMX multi-device framework for Windows 32-bit and 64-bit X X X X X

OS X Yosemite and Mavericks deployment support including Retina and Mac AppStore X X X X

Single-source, mobile app development for Android and iOS with the FireMonkey framework iOS (now including 64-bit andUniversal iOS apps)

Client/Server database connectivity for leading database servers including Microsoft SQL Server, Oracle, Sybase, DB2, Informix, InterBase, ODBC and more

DataSnap n-tier middleware SDK for building application and data services

REST client library and Back-end as a Service Components for Parse and Kinvey

Enterprise Mobility Services, a turnkey set of integrated services including user authentication, middleware database connectivity, custom REST API management and analytics**Requires separate per-user runtime agreement

Fast SQL database development, change management, SQL profiling and SQL tuning withDB PowerStudio® Developer Edition

RTL with file system access, sensors, Bluetooth, App tethering, parallel threading library (features vary by edition)

Parallel Programming Library for VCL and FMX

X X X Optional

Optional

Optional

Optional

OptionalX X X

Optional

X X X X X

X X X X X

Features Architect Ultimate Enterprise Pro Starter

MULTI-DEVICE APPLICATION DEVELOPMENT

X X X X X

X

FireUI Multi-Device Designers, Components, and Services X X X X

Develop natively compiled apps for 32-bit Windows X X X X

XDevelop natively compiled apps for 64-bit Windows and for Mac OS X X X X

X X X

The most productive integrated visual development environment (IDE) with UI designers, code editor, Code Insight, build and debugging tools

Develop natively compiled apps for Android and iOS (nowincluding 64-bit and Universal iOS apps)

Download a free Trial at www.barnsten.com

Barnsten | Tel: +31 23 542 22 27 | Fax: +31 84 755 52 60 | P.O. Box 5010 | 2000 GA Haarlem | The Netherlands

Tel: +31 23 542 22 27

Page 48: blaise pascal magazine 40

Supports Delphi/C++Builder/RAD Studio 2009 to XE7 (32 bit, 64 bit and OSX where applicable). kbmMW for XE5 to XE7 includes full support for Android and IOS (client and server).

kbmMemTable and kbmMW are highly addictive! Once used, and you are hooked for life!

!

kbmMemTable is the fastest and most feature rich in memory table for Embarcadero products.

- Easily supports large datasets with millions of records

- Easy data streaming support- Optional to use native SQL engine- Supports nested transactions and undo- Native and fast build in M/D,

aggregation /grouping, range selection features

- Advanced indexing features for extreme performance

Warning!

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).

- Improved performance on Indy TCP/IP

Client messaging transport for large number

of inbound messages.

Full FastCGI hosting support.

Host PHP/Ruby/Perl/Python applications in

kbmMW!

- Native high performance 100% developer

defined application server with support for

loadbalancing and failover

- Native high performance JSON and XML

(DOM and SAX) for easy integration with

external systems

- Native support for RTTI assisted object

marshalling to and from XML/JSON, now also

with new fullfeatured XML schema

(XSD) import

- High speed, unified database access

(35+ supported database APIs) with

connection pooling, metadata and

data caching on all tiers

- Multi head access to the application server,

via AJAX, native binary, Publish/Subscribe,

SOAP, XML, RTMP from web browsers,

embedded devices, linked application

servers, PCs, mobile devices, Java systems

and many more clients

-

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.

COMPONENTSDEVELOPERS4

EXTREME PERFORMANCE NOW FASTER THAN EVER!