You are on page 1of 26

BLAISE

BLAISE PASCAL
PASCAL MAGAZINE
MAGAZINE
34
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,
A N D
P A S C AL
R E L A T E D
L A N G U A G E S
A N D R O I D,
I O S,
M A C,
W I N D O W S
&

L I N U X

Cary Jensen
Ode To the Code
Detlef Overbeek
Animation Lab for Android
Interview with Boian Mitov:
All about understanding the RTTI / Attributes / Functional Programming
Multiple Inheritance /Parallel Processing and GP GPU - Part 1
Rik Smit
Raize Components Version 6PART IIContinuation from issue 33
Max Kleiner
QR (Quick Response) Codes
David Dirkse Image Compression
Jeremy North
Review : Documentation Insight by DevJet Software
Cary Jensen
Introduction Local SQL with FireDAC
Michael van Canneyt
Unit testing - test driven development
Kim Madsen
Serving an off the shelf Content Management System

Publisher: Foundation for Supporting the Pascal Programming Language


in collaboration with the Dutch Pascal User Group (Pascal Gebruikers Groep)
Stichting Ondersteuning Programmeertaal Pascal

BLAISE
BLAISE PASCAL
PASCAL MAGAZINE
MAGAZINE 34
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, A N D P A S C A L R E L A T E D
L A N G U A G E S F O R A N D R O I D, I O S, M A C,
W I N D O W S & L I N U X

CONTENTS

Article overview

S O F T W A R E

Interview with Boian Mitov:

QR (Quick Response)Codes
PAGE 18 By Max Kleiner
PAGE 24

Open Wire

All about understanding the RTTI /


Attributes / Functional Programming
Multiple Inheritance /Parallel Processing
and GP GPU - Part 1 PAGE 7

By Rik Smit
Raize Components Version 6
PART II- Continuation
from issue 33
PAGE 18

Image Compression By David Dirkse


PAGE 29

Introduction Local SQL with FireDAC


By Cary Jensen
PAGE 41

Review :
Documentation Insight
by DevJet Software
By Jeremy North PAGE 36

Ode to Code:
Reflections on Software Development in Iambic Heptameter
by Cary Jensen

While true, it's said, there's work to do, and now it's time to start
This is my task, so plain and clear, it's science, love, and art
My slate starts clean, a screen pure white, no logic bears my will
Upon this page, through thought and might, it's my intent to fill
I make my plan, each step designed, my spec is well thought out
It matters much, oh yes it does, there can't be any doubt

Unit testing - test driven


development By Michael van Canneyt
PAGE 46

My fingers fly, the logic pours, a waterfall sublime


I see my goal, I type and click, I lose all sense of time

Serving an off the shelf


Content Management System
By Kim Madsen PAGE 53

My words are key, my syntax right, and subtly reserved


I own this world, I'm in control, though humble, numb, and nerved
It's getting close, the tension firms, anticipation's high
I hit F9, compile and run, I feel success is nigh
But wait! It fails! How can this be, catastrophe I feel
I've lost my touch, my senses fail, my mortal soul revealed
Oh, damn the Gods! This logic broke, a bug I cannot find
I check the source. I check each line. I think I'll lose my mind
But what is this, a misplaced test, can this thing truly be
Compile again, and it just works, I'm now in ecstasy

S
NT S

NE ER
PO LOP
OM EVE

I document the change I made, my comment explains why


I always try to take this step, to prevent a future cry
Relaxed, I am, my goal achieved, a conquest satisfied
It's what I do, a job compelled, a source of joy and pride
You beauty mine, my cherished child, the product of my soul
From white blank slate to final code, a void has morphed to whole
No eyes will see this gold I've spun, no heart with feel its beat
It lies beneath the interface, resplendent and complete
I scratch one item off my list, but I cannot pretend
With this task done, there will be more, my work will never end;
Copyright 2014 Cary Jensen. All Rights Reserved

Ode To the Code PAGE 4

Smart Mobile Studio

MOTION

has a special page on


our website, where you can
read the latest new article:

Writing a Facebook clone


with
Smart Mobile Studio Part 1
Advertisers

BLAISE
BLAISE PASCAL
PASCAL MAGAZINE
MAGAZINE
BARNSTEN TOGEHTER WITH BLAISE PASCAL MAGAZINE
ORGANIZES THIS FALL:
THE BIG DELPHI CONFERENCE 11 SEPTEMBER 2014:
4 POWER TRAINING SESSIONS 12 SEPTEMBER 2014:
LOCATION: LEIDEN, HOLIDAY INN

Barnsten
BetterOffice
Components 4 Developers
Evers Custom Technology
Raize Software
Books

SAVE THE DAY

Page
Page
Page
Page
Page
Page

35
34
60
52
28
45

Articles
Cary Jensen Ode To the Code PAGE 4
Detlef Overbeek Animation Lab for Android PAGE 5
Interview with Boian Mitov: All about understanding the RTTI / Attributes / Functional Programming
Multiple Inheritance /Parallel Processing and GP GPU - Part 1 PAGE 7
Rik Smit Raize Components Version 6PART II- Continuation from issue 33 PAGE 18
Max Kleiner QR (Quick Response)Codes PAGE 24
David Dirkse Image Compression PAGE 29
Jeremy North Review : Documentation Insight by DevJet Software PAGE 36
Cary Jensen Introduction Local SQL with FireDAC PAGE 41
Michael van Canneyt Unit testing - test driven development PAGE 46
Kim Madsen Serving an off the shelf Content Management System PAGE 53

COMPONENTS
DEVELOPERS

Nr 2 / 2014 BLAISE PASCAL MAGAZINE

Alexander Alexeev
www.alexander@blaisepascal.ru
Alexander @ blaisepascal.ru

Peter Bijlsma
-Editor peter @ blaisepascal.eu

Michal Van Canneyt,


michael @ freepascal.org

Marco Cant
www.marcocantu.com
marco.cantu @ gmail.com

David Dirkse
www.davdata.nl
E-mail: David @ davdata.nl

Daniele Teti
www.

Bruno Fierens
www.tmssoftware.com
bruno.fierens @ tmssoftware.com

Primo Gabrijeli
www.
primoz @ gabrijelcic.org

Fikret Hasovic
www.

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

Wagner R. Landgraf

Sergey Lyubeznyy

Kim Madsen
www.component4developers

Felipe Monteiro de Cavalho

Mattias Gaertner

Jeremy North

Tim Opsteeg

Detlef Overbeek
www.blaisepascal.eu
Email:editor @ blaisepascal.eu

Rik Smit

Bob Swart
www.eBob42.com
Bob @ eBob42.com

jeremy.north @ gmail.com
Howard Page Clark
E-mail: hdpc @ talktalk.net

Wim Van Ingen Schenau


-Editor
wisone @ xs4all.nl

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

editor @ blaisepascal.eu

Authors - alphabethical order


A
B
C
D
F
G
H
J

Alexander Alexeev
Peter Bijlsma,
Michal Van Canneyt, Marco Cant,
David Dirkse, Daniele Teti
Bruno Fierens
Primo Gabrijeli,
Fikret Hasovic
Cary Jensen

MOTION

L
K
M
N
O
P
S

Wagner R. Landgraf, Sergey Lyubeznyy


Max Kleiner
Kim Madsen, Felipe Monteiro de Cavalho
Jeremy North,
Tim Opsteeg, Inoussa Ouedraogo
Howard Page-Clark,
Rik Smit, Bob Swart,

BLAISE
BLAISE PASCAL
PASCAL MAGAZINE
MAGAZINE

Editor - in - chief
Detlef D. Overbeek, Netherlands Tel.: +31 (0)30 890.66.44 / Mobile: +31 (0)6 21.23.62.68
News and Press Releases email only to editor@blaisepascal.eu
Editors
Peter Bijlsma, W. (Wim) van Ingen Schenau, Rik Smit,
Correctors
Howard Page-Clark, James D. Duff
Trademarks
All trademarks used are acknowledged as the property of their respective owners.
Caveat Whilst we endeavour to ensure that what is published in the magazine is correct, we cannot accept responsibility for any errors or omissions.
If you notice something which may be incorrect, please contact the Editor and we will publish a correction where relevant.
Subscriptions ( 2013 prices )
1: Printed version: subscription 60.-- Incl. VAT 6 % (including code, programs and printed magazine,
6 issues per year excluding postage).
2: Electronic - non printed subscription 45.-- Incl. VAT 21%
(including code, programs and download magazine)
Subscriptions can be taken out online at www.blaisepascal.eu or by written order, or by sending an email to office@blaisepascal.eu
Subscriptions can start at any date. All issues published in the calendar year of the subscription will be sent as well.
Subscriptions run 365 days. Subscriptions will not be prolonged without notice. Receipt of payment will be sent by email.
Subscriptions can be paid by sending the payment to:
ABN AMRO Bank Account no. 44 19 60 863 or by credit card: Paypal
Name: Pro Pascal Foundation-Foundation for Supporting the Pascal Programming Language (Stichting Ondersteuning Programeertaal Pascal)
IBAN: NL82 ABNA 0441960863 BIC ABNANL2A VAT no.: 81 42 54 147 (Stichting Programmeertaal Pascal)
Subscription department Edelstenenbaan 21 / 3402 XA IJsselstein, The Netherlands / Tel.: + 31 (0) 30 890.66.44 / Mobile: + 31 (0) 6 21.23.62.68
office@blaisepascal.eu

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

Nr 2 / 2014 BLAISE PASCAL MAGAZINE

COMPONENTS
DEVELOPERS

Ode to Code:
Reflections on Software Development in Iambic Heptameter
by Cary Jensen

While true, it's said, there's work to do, and now it's time to start
This is my task, so plain and clear, it's science, love, and art
My slate starts clean, a screen pure white, no logic bears my will
Upon this page, through thought and might, it's my intent to fill
I make my plan, each step designed, my spec is well thought out
It matters much, oh yes it does, there can't be any doubt
My fingers fly, the logic pours, a waterfall sublime
I see my goal, I type and click, I lose all sense of time
My words are key, my syntax right, and subtly reserved
I own this world, I'm in control, though humble, numb, and nerved
It's getting close, the tension firms, anticipation's high
I hit F9, compile and run, I feel success is nigh
But wait! It fails! How can this be, catastrophe I feel
I've lost my touch, my senses fail, my mortal soul revealed
Oh, damn the Gods! This logic broke, a bug I cannot find
I check the source. I check each line. I think I'll lose my mind
But what is this, a misplaced test, can this thing truly be
Compile again, and it just works, I'm now in ecstasy
I document the change I made, my comment explains why
I always try to take this step, to prevent a future cry
Relaxed, I am, my goal achieved, a conquest satisfied
It's what I do, a job compelled, a source of joy and pride
You beauty mine, my cherished child, the product of my soul
From white blank slate to final code, a void has morphed to whole
No eyes will see this gold I've spun, no heart with feel its beat
It lies beneath the interface, resplendent and complete
I scratch one item off my list, but I cannot pretend
With this task done, there will be more, my work will never end;
Copyright 2014 Cary Jensen. All Rights Reserved

COMPONENTS
DEVELOPERS

Nr 2 / 2014 BLAISE PASCAL MAGAZINE

Animation Lab for Android


starter

By Detlef Overbeek and Boian Mitov

expert Delphi XE5 and later

This application is nothing else but an exercise


to get acquainted wit the simplicity of creating
a FireMonkeyapplication. It was a trial on
Android and very easy to do.
First of all you need to download the
animationLab_VCL_7.0.0.64.zip from your
personal download page at
www.blaisepascal.eu.
This component group is for free and made
available by Boian Mitov.
Before
All the component groups you want to download have a
very special ability: You can choose like in the old days for
a trial version without any limitation of functionality:
you can have either just for trial no source code or
professional no source code or with source code.
This seems to be very convincing for the quality.
Let's create a new blank FireMonkey mobile project.
The application we are going to build is just a very simple
demonstration of how to work with a timeline and a
button. We will do this through some simple steps.
One can do this even if you are not used to the
environment.

1.
2.

Make sure you have chosen for the Mobile you want.
Try to loacte this under the android
Search for ALTimeLine and drop a
ALTimeLine component from the Animation Lab -Tab
Samsung S4

3.

Choose Mobile and connect


First of all be aware that it would be better if you connect
your Android Phone which ever it may be to your
computer. Make sure it allows debugging on your phone.
So set the developer options, in the sense that probably a
screen comes up on your phone that asks for the allowance
of a fingerprint. The mobile I used is a Samsung Galaxy 4.
After all this you start Delphi XE 5 or another (3,4 or 6)
In case you havent yet installed the components:
Uninstall the last older version of
AnimationLab_VCL. Then reinstall
AnimationLab_VCL_7.0.0.64.zip
The installation is simple and
should not create any problems.
It offers you the choice under
which version of XE you want to
install it. When you start XE (3,4,5,6)
please make sure the components
are on the component bar. Search
for your component through
typing in the search-window:
ALTimeLine.
If that is available all works.

Nr 2 / 2014 BLAISE PASCAL MAGAZINE

Double click on the


TALTimeLine
component
to open the
TimeLine editor.

4.

Add a Single channel.

5.

Add a few 3 Linear interpolations.

COMPONENTS
DEVELOPERS

Boian Mitov

an interview by Detlef Overbeek

S O F T W A R E

Editor: And when did you start with Pascal?

During my search for solving software problems, Kim


Madsen (Component 4 Developers) told me he knew a
Developer that had astonishing ideas I made contact
and soon it seemed to become one of those
conversations that youre waiting for: everlasting,
never done with and always new aspects.
He is a very inspiring man with a great capability of
lateral thinking So in the next issues I will introduce
you to Boian Mitov, who owns a small company that
creates beautiful specialized - and unknown suites of
components. Actually I asked him about Neural
networking and thats how the discussion started

INTRODUCTION
Editor:
Boian, to start with your name:, where does it come from
and what does it mean?
Boian Mitov:
Boian is a Bulgarian name. Not widely used. Not sure of
the exact origin. I have been told that it is based maybe
on the word painter in Bulgarian, although it differs a lot
from it. There is also a famous Old Bulgarian Theater
play called "Boian the Wizard", so some people may
associate it with that too.

Boian Mitov:
My first Pascal encounter was while I served the
mandatory 2 years of military service in the Bulgarian
Army.
I was mainly developing in Assembler, and Basic, but
we got a project developed in UCSD Pascal. So I took a
course. Couple of years ago actually I have gone
through some Pascal books, so I had some familiarity
with the language already. This was approximately
1988-89.

Editor: That was before Delphi and Turbo?


Boian Mitov: Yes, it was on Apple

Editor:
So you have been working with the language since the
beginning?
Boian Mitov:
Hardly...It has existed since 1970, I was nearly 20
years late

Editor:
Yes but the first versions were on mainframes etc.
That's the period Mr Wirth was working on it...
Boian Mitov:
That does not make it any less important. I have
worked on Mini VAX, but mostly used Fortran 77 and C

Editor:
I don't recall the exact time that Apple started with it...

Editor:
When I hear your voice, you remind me of a young boyvery enthusiastic and young... So when did you come to
the states?

Boian Mitov:
Apple started 1978 so I have been 10 years late there
too. I can hardly pretend to be a pioneer there.

Boian Mitov:
Hmm... at 45 I am hardly young, but I guess I never
grew any way. I came to the states in 1996.

Editor:
I still have some of the books from that period.
What was the reason for you to start with it it? Did
you want to start your own company - was that it?

Editor:
So you already had done the biggest part of your
education...?
Boian Mitov:
Yes, and fair amount of work-experience.

Editor: What is your education?


Boian Mitov:
I have probably the equivalent of Associate Degree in
Industrial Automation from a 4 year technical school in
Bulgaria. This is not a BS degree, but a 4 year college
equivalent as the best of my understanding

Editor:
Did you do Pascal? Or started with another language?
Boian Mitov:
I started with 6800 Assembler and then 6502 Assembler,
and Apple ][ Apple soft Basic. At the time I started,
there were no personal computers in Bulgaria, so I
designed and built my own 6800 based "KIT", somewhat
similar to the Motorola 6800 kits from the period.

Boian Mitov:
I have worked with many different languages over the
years. Before Delphi 1 my primary language was C++.
When Delphi 1 appeared, it offered OOP comparable to
C++ and visual development. We had a DB related
project we needed to handle in the company I was
working for at the time, so it was a very good fit. Since
most of the development I was doing at the time was
hardware related, and often embedded, I was still
working primarily with C++, but I was always looking
for the right tool for the right task, and Delphi was the
right tool for the application. This was in 1995.
When I moved to the USA, in 1996, the C++
Builder appeared, and I was one of the first adopters.
It promised the same visual development with the full
power of C++ - templates and everything. I worked in
a number of companies in C++ Builder from 1996 to
2001. In 2001 I was hard at work on the Open Wire
architecture. At that time during a conversation with
Atanas Stoyanov, he suggested to try to port it from
C++ Builder to Delphi. The port went well. 2 years
later, the company I was working for went through
some difficult times and I decided to leave it.

Nr 2 / 2014 BLAISE PASCAL MAGAZINE


S O F T W A R E

Raize Components Version 6 (continuation 11)


TRzDBButtonEdit
The Customer field (see Figure 34, name labels written
underneath the data fields), in the Ticket Order Form (blue
highlights), is displayed by the data-aware version of the
button edit component. The AllowEdit property is False so
the user cannot change the data with the keyboard, but the
user can click the Find button (magnifying glass at the end
of the field) or press F4 to display a customer lookup dialog
box (Figure 35) that illustrates even more ways to use the
data-aware components.

Edit Controls
The other database fields are connected to TRzDBEdit,
TRzDBSpinEdit, TRzDBDateTimeEdit, TRzDBMemo,
TRzDBComboBox and TRzDBCheckBox components.

Figure 37: The data controls are flat and apear as lines
(brown in this example)

Figure 34: Composite


screenshot of the Ticket Order
Form

Figure 35: Customer


lookup dialog box

TRzDBLookupDialog
The Event field is also edited by a TRzDBButtonEdit.
However, for this field the user is allowed to type in an
Event Number. The user can also click the Find button (the
magnifying glass with hint: Search by name) to search by
Event Name using a TRzDBLookupDialog component,
which is a dialog-based component that provides an easy
way to perform lookups. In this example, the KeyField
property is set to the EventNo field while the SearchField
property is set to EventName (see Figure 36).

The controls were altered to appear as flat lines (brown


marks between the data fields en the name labels underneath, see
Figure 37) dby setting the appropriate Custom Framing
options. In particular, FrameVisible is True, FrameStyle is
fsFlat, and FrameSides is [sdBottom].
Status Controls
The status area (at the bottom side of theOrder Form, see
Figure 37) contains a TRzDBStatusPane and a
TRzDBStateStatus. The data-aware status pane displays
the current order number (107). The identifying caption is
controlled through the FieldLabel property. The
TRzDBStateStatus component shows the current state
of the Reservation database table.

Figure 36: The Select an Event form using a


TRzDBLookupDialog component

TRzDBComboBox
The Method of Payment field is edited using a
TRzDBComboBox control. The Values property contains
the coded values that map to the more descriptive strings
in the drop down list (see Figure 34). The combo box is
folded out with the choice for the means of payment in
blue. Furthermore there is a drop-down calender to enable
to select a date.

Nr 2 / 2014 BLAISE PASCAL MAGAZINE

21

Raize Components Version 6 (continuation 12)


Widgets
The appearance of the different widgets are depicted in
Figure 38 on one of the de standard win7 backgrounds,
using some Win 7 widgets as a reference.

Zend Email

Figure 39: Email message

Figure 38: Some widgets on the Win7 desktop


TRzFormShape
This custom image component is used to create the nonrectangular form displayed here. The transparent regions
of the image are removed from the form when the
application is run.
TRzCalendar
This TRzCustomPanel descendant is designed for
selecting dates. The user navigates through months and
years using the arrows at the top of the control. There are
several properties that control the appearance of the
calendar. For example, CalendarColors and Elements. The
OnGetDayFormat event allows a developer to highlight
specific days by changing the colors and font style.

TRzSendMessage
This form illustrates how to send electronic mail using the
TRzSendMessage component.
First, enter the email addresses for all recipients. Next,
enter a subject and a message body, and then select any file
attachments. Press the Send button to send the message.
Note: The TRzSendMessage component requires a MAPI
compliant messaging service such as Microsoft Outlook.
Shell Controls
This form (Figure 40) uses the Shell controls included in
Raize Components to create a Windows Explorer-like
interface.

TRzColorPicker
This component displays a grid of colour values. The user
simply clicks on a cell to select a colour. There are several
ways to customize the control. In particular, the
ShowNoColor, ShowCustomColor, ShowDefaultColor,
and ShowSystemColors properties toggle the visibility of
the various regions in the control.
TRzTimePicker
This component provides a visual way of selecting times.
The hands of the clock face are moved using the Leftmouse button (hours) and the Right-mouse button
(minutes). Holding the Ctrl key down while using the
Right-mouse button causes the minutes to be Restricted to
5 minute increments (i.e. 5, 10, 15, etc.) To always restrict
minutes, set RestrictMinutes to True. Select AM or PM by
clicking the appropriate radio button.
TRzCalculator
This component provides calculator, which can be used to
perform simple mathematical calculations. Like the other
controls on this page, the appearance of the calculator can
be customized

22

Figure 40: The Shell Controls form with some component


names added from the IDE

The following componenten are used in Figure 40:


TRzShellTree
This component is a specialized tree view for navigating
through the shell namespace.
TRzShellList
This component is a specialized list view for displaying the
contents of a shell folder.
TRzShellCombo
This component is a specialized
combo box for selecting folders in
the shell namespace.

Nr 2 / 2014 BLAISE PASCAL MAGAZINE

Raize Components Version 6 (continuation 13 - end)

Figure 41: The combo box is folded out and the splitter
just visible on the left-hand side makes the shell-list fully
visible

TRzLauncher
This nonvisual component makes it very easy to start
another application from within your program. Simply
select a file to launch. If the file is not an executable file, the
component attempts to start the application associated with
the selected file's type. TRzLauncher supports two ways
of starting another application: Launch and Execute.
Launch method:
The Launch method causes the component to become
notified when the launched application is terminated or if
an error occurs. Check the Wait Until Finished option if
you want the main application to sleep while the launched
application is running. Otherwise, a background thread is
created to wait for the launched application to terminate. In
this demo, the notification of termination is displayed
using the TRzTrayIcon.ShowBalloonHint method.
Execute method:
The Execute method simply starts the appropriate
application and immediately returns control back to the
calling program.
TRzURLLabel
This TRzLabel descendant makes it easy to create
hyperlinks within your application, which point to web
pages, email addresses, newsgroups, and more.

TRzOpenDialog & TRzSaveDialog


These components are replacements for the standard
Open/Save dialog components with many more features,
such as the ability to display a ShellTree in the dialog next
to the ShellList.
TRzSelectFolderDialog
This dialog component (see Figure 42,
cut from the IDE) allows a user to
select a folder in the Shell namespace.

Figure 42: The Dialog Boxes in de


IDE

Nr 2 / 2014 BLAISE PASCAL MAGAZINE

TRzTrayIcon
The last example:
Located in the system notification tray, you will find an
icon for this application. The icon displayed is changed as
you navigate through this application, and when you
minimize this application, the button from the task bar is
hidden. To restore the app, double click on the tray icon.
This functionality is all handled by the TRzTrayIcon
component.
Conclusion
In this article a global description is given of the
possibilities of a number of components
belonging to Raize version 6, based on the
accompanying demo. More information about
this can be found on the website:
http://www.raize.com {/Downloads/RC/RC6.zip}
Cost (per first quarter 2014): $399
Contains: more than 120 components distributed
over various main groups.

23

QR (Quick Response)Codes By Max Kleiner


Today we jump into a topic in programming called the
Quick Response Code. Using Object Pascal there are
several ways you can generate QR codes, from a web
service up to a component - to encode any text (URL,
web store, phone number, short message). QR Codes
store up to 4,296 alphanumeric characters of arbitrary
text. I'll show it in 3 ways:

WinInet API

Indy Sockets

Direct Library
Wiki says: A QR code (abbreviated from Quick Response)
is the trademark for a type of matrix bar-code (or twodimensional bar-code) first designed for the automotive
industry in Japan developed by Denso-Wave.
The point is that QR codes give users or customers
instant access to the information they need on the move;
whether its on your website, social media or another
news channel a QR service is dedicated to making access
to it quicker and easier than ever before.
We can put many information in a QR code; the code
contains information such as a website address,
telephone number, or a business card information.

QR with a lot of Things


There are two different types of QR code; "Static" and
"Dynamic". A static QR code holds all of the information
you wish to pass within the code itself. The more
information you include, the larger the QR code becomes.
Those codes are widely used in the web of things or
embedded computing with the internet.
There are three topics in here. First technologies
simply put, this part is mainly for early adopters. Its about
coding with QR code, developing toys, plugging in gadgets
on the web (and we and many others actually did that!).
The second part is about new ideas, prototyping and new
technologies that are in the lab. Its about research papers,
and software philosophy, and about researchers
worldwide. Third part is about end-users and products,
and those products need a QR code or an RFID e.g.:
Magazines and Gadgets
3D Printing Production
Web Video Cam Pictures
QR Code Mode
Now we deal with QR code and put a real script first:
The point is that QR codes give users or customers instant
access to the information they need on the move; whether
its on your website, ask.com or another news channel a QR
service is dedicated to making access to it quicker and
easier than ever before. The script you find at the examples:
393_QRCode3.TXT
393_QRCode2Direct_Detlef.TXT
But whats the matter with Web of Things? Simply that
each thing, device or gadget will have an identity to
communicate, could also be a RFID.
Statistics for whos scanning QR codes and with what
device appear to be mixed,

Using the Google Chart Tools / Image Charts (aka Chart


API) you can easily generate QR codes, this kind of images
are a special type of two-dimensional bar-codes. They are
also known as hard-links or physical world hyper-links.
The API requires 4 simple fields be posted to it:
1. cht=qr this tells Google to create a QR code;
2. chld=M the error correction level of the QR code (see
here for more info);
3. chs=wxh the width and height of the image to return
(e.g. chs=250x250);
4. chl=text the URL encoded text to be inserted into the
bar-code.
For example the Blaise Pascal URL we need the following:
Const
URLGoogleQRCODE=
'http://chart.apis.google.com/chart?
chs=%dx%d&cht=qr&chld=%s&chl=%s';
AFILENAME= 'mX3QRCode3.png';
//QDATA= 'this is maXland on a stream dream firebox';
QDATA= 'http://www.blaisepascal.eu/';
Type TQrImage_ErrCorrLevel=(L,M,Q,H);

There are 4 ECC Levels in QR Code


(enumerator) as follows:
Level L - 7% of codewords can be restored
Level M - 15% of codewords can be restored
Level Q - 25% of codewords can be restored
Level H - 30% of codewords can be restored
So what does it mean? 7% of codewords can be restored
just means that you can loose about 7% of the QR code and
the built in redundancy will be able to restore the missing
data. (i.e if you rip the QR code out of a paper advert and tear off
a small bit of the QR code then you might still be able to scan it).
This also allows small images to be overlaid without
affecting the scan. A high ECC level adds more
redundancy at the cost of using more space!

Whit that information you can type in maXbox:


//Internal mXLib
procedure getQRCodeDirect;
begin
GetQrCode3(250,250,'Q',QDATA, ExePath+AFILENAME);
OpenDoc(ExePath+AFILENAME);
end;

In a website those options ECC Level Q and resolution 250 *


250 stands for:

The call is that simple:


GetQrCode3(250,250,'Q',QDATA,
ExePath+AFILENAME);
enDoc(ExePath+AFILENAME);

This is so simple because google provides a service we use:


UrlGoogleQrCode=
'http://chart.apis.google.com/chart?
chs=%dx%d&cht=qr&chld=%s&chl=%s';

24

COMPONENTS
DEVELOPERS

Nr 2 / 2014 BLAISE PASCAL MAGAZINE

Image Compression By David Dirkse


starter

expert

Delphi

This article describes Delphi project SPIC for the


compression of pictures. The images are stored in
a bitmap. From the pixels of this bitmap, spic
generates a file of type .pic which is smaller in
byte count then the .bmp file holding the original
bitmap.
Well known formats for compressed images are :
.gif , .jpg and .png.
Later in this article I include a comparison of them
with the new .pic format.
In general, two type of images may be distinguished:
photographs and geometric figures.The first category has
many colors and no sharp boundaries, the second have
lines and rectangles filled with a single color.
My spic project is aimed at photographs and paintings. For
geometric pictures other approaches would yield better
results however, the .pic files are far from bad.

Colors.
A bitmap in true color format has 24 bit colors, which are
stored as pictured below:

Figure 2: bitmap in true color format

The intensity of the red, green and blue primary colors


ranges 00000000 .. 11111111 (0..255) so, 8 bits per color.
In the 32bit pixelformat the bits are stored in positions
0..23, bits 24..31 are not used.
Spic uses this 32 bit pixelformat because addressing the
pixels is very fast and simple.
For the human eye, the differences between colors varying
only in the lower bits, are not visible.
Some experimenting revealed that realistic colors remain
even if a color is rounded to multiples of 16. Sixteen choices
for red, green and blue make 12 bit colors ranging from 0 to
4095.

Figure 1: this is a reduced picture of spic at work:

The naval battle painting was reduced to 17,6%.


The algorithm
A bitmap with randomly colored pixels will be hard to
compress. Compression is possible only if the picture has
some regularity: repeating patterns, areas with less colors.
I tested a lot of methods and so, in an organic way, the
algorithm evolved that works best for picures like the naval
battle.
Surprisingly enough, a little number of simple commands
remained.

Nr 2 / 2014 BLAISE PASCAL MAGAZINE

This looks like a dramatic loss but how big is the "error"
caused by this rounding?
Rounding 1110 1000 to 1111 0000 is an "error" of 8/256 =
3,125%. Actually a little more because differences in the
higher colors are more visible then in the lower color
values. Another, however small, reduction is to replace the
color 0000 0000 by 0001 0000., so eliminating color 0. The
difference between 0000 0000 and 0001 0000 is not visible.
So, red, green and blue have 15 intensities: 0001 .. 1111.
The naval battle painting is shown in this format and I see
no difference with the original 24 bit pixel image.

COMPONENTS
DEVELOPERS

29

Image Compression (Continuation 5 - End)


Statistics
During the compression process several counts are
updated. They are shown on the form:
left
the times a color was copied directly f
rom it's left neighbour
exp.left the number of compressed copyleft commands
(exp = expanded)
top
the number of copies from the top neighbour
stack
the number of colors extracted from the stack
new
the number of new colors inserted
The total count equals the pixelcount.

Size
The size of a bitmap is not tested. Up to 1,5 million pixels
may not be a problem. Bigger pictures possibly require a
larger value of constant maxDir. Also temporary space
could be reserved on the heap to accomodate the director.
The paintbox on Form1 for showing the bitmaps is 800
pixels wide and 600 pixels high.

SMART MOBILE STUDIO


THE ARTICLE
WRITING A FACEBOOK CLONE
WITH SMART MOBILE STUDIO
PART 1" BY JON L. AASENDEN
IS AVAILABLE ON OUR WEBSITE

34

COMPONENTS
DEVELOPERS

Nr 2 / 2014 BLAISE PASCAL MAGAZINE

MOTION

BLAISE PASCAL MAGAZINE


BARNSTEN TOGEHTER WITH BLAISE PASCAL MAGAZINE
ORGANIZES THIS FALL:
THE BIG DELPHI CONFERENCE 11 SEPTEMBER 2014:
4 POWER TRAINING SESSIONS 12 SEPTEMBER 2014:
LOCATION: LEIDEN, HOLIDAY INN

SAVE THE DAY


Save the day in your agenda! Detailed information will follow soon.

Review :
Documentation Insight by DevJet Software By Jeremy North
Version reviewed Enterprise v3.1.4.15
Documentation insight is an IDE Expert or Plug-in that
greatly reduces the burden of documenting your source
code.
Prior to the Delphi XE6 release, a cut down version of
Documentation Insight was shipped with the IDE.
Unfortunately, this was stopped for the Delphi XE6
release most likely because the Express version was
too feature reach to encourage uses to upgrade to the
paid versions.
Excluding the now defunct Express version there are two
editions available, Professional and Enterprise. The only
difference between the two editions is the ability to
output the source code documentation into a number of
formats.

Documentation Inspector
The documentation inspector is where you will spend most
of your time documenting your code. It is an easy to use
IDE dockable form.

36

COMPONENTS
DEVELOPERS

Navigating the sections that can be modified works by


tabbing and the currently edited section is highlighted
for clarity.
One pleasing feature is live spell check which
highlights your mistakes as you type. After installation the
following languages are supported: English, French,
German, Italian and Russian. Additional dictionaries can be
downloaded from the Addictive Software website.
It is possible to use styling to enhance the generated
documentation for readability.
One downside of this is if you have team members
working on the source code, the additional tags can add
significant noise. One way around this is to have the
inspector docked in your current desktop layout in the IDE
or have the Documentation Explorer visible on a second
monitor (showing the preview view of the documentation).
You can collapse sections that you don't use however these
settings are not persisted. Which is a shame.

Nr 2 / 2014 BLAISE PASCAL MAGAZINE

Introduction Local SQL with FireDAC By Cary Jensen


starter

expert

Delphi XE3 and later


FireDAC, the new data access framework introduced in
Delphi with the release of Delphi XE3, provides a wide
range of capabilities, some of which have not been
available in Delphi before. One of these, Local SQL, is
arguably the most interesting. Local SQL permits you to
execute SQL statements against any TDataSet. For
example, you can perform a query against an FDTable
to gather simple aggregate statistics like SUM and AVG
from the data it contains. Similarly, you can query an
FDQuery and perform a left outer join to an
FDStoredProc component (in which case the stored
procedure must return a result set).

Creating a Local Heterogeneous Query


Use the following steps to create a simple query that will
perform a join between two datasets. In this particular
case, we will create a join between an Microsoft Access
database and ClientDataSet.
Begin by select File | New | VCL Forms Application.
Place on the newly created form a DBNavigator, a DGBrid,
and a DataSource. Set the DataSource property of the
DBNavigator and the DBGrid to DataSource1. Your new
form should look something like that shown in Figure 1.

Importantly, this ability to query


TDataSets is not limited to
FireDAC TDataSets.
As a result, there is nothing to
prevent you from performing a
query that performs a join
between an IBQuery, a SQLDataSet,
and a ClientDataSet.
FireDAC performs this SQL
slight-of-hand by using the SQL engine
from the SQLite open source project.
It's a very clever solution, and one
that enables a whole range of
interesting data-related solutions that
would otherwise be difficult or nearly
impossible to implement. Your joins don't have to be as
complicated as I've described, but the benefits are
significant. For example, even if you are already using
another data access framework, such as dbExpress, or even
a third-party data access framework, such as Direct Oracle
Access or UniDAC, you can use FireDAC to perform
SELECT * queries against those datasets, and then use
FireDAC's advanced features on the returned result set.

Figure 1; A basic form for displaying data

Next, select File | New | Other, and select the Data


Module wizard from the Delphi Files node of the Object
Repository. Place onto this data module two FDConnection
components, two FDQuery components, an FDLocalSQL
component, a ClientDataSet, and a FDGUIxWaitCursor.

We will begin by configuring our datasets that return the


Access and ClientDataSet data. Begin by selecting one of
Note that if you are using the original release of Delphi XE5
the FDConnections and set its Name property to
without updates, you might be missing two files that are
AccessConnection and the LoginPrompt property to False.
critical for working with SQLite. If you encounter a
compiler error indicating that one of these files is missing
Right-clicking this connection and select Connection Editor.
when building an application using the FireDAC SQLite
From the Connection Editor, set Driver ID to MSAcc. Next,
driver, install the latest update for Delphi XE5.
set Database to the dbdemos.mdb file located in Delphi's
sample data directory. In Delphi XE6 this file can be found
Using Local SQL
Local SQL is fairly easy to use, but it does have a number of in the following directory (in earlier versions of Delphi this
directory path will be similar):
specific requirements. These are:

You must have a FireDAC connection component that C:\Users\Public\Documents\Embarcadero\


is configured to use the FireDAC SQLite driver.
Studio\14.0\Samples\Data
You must add a FDLocalSQL component,

and this component must be configured to the


FDConnection created in the preceding step
The FDLocalSQL needs to refer to any dataset you

want to query in its DataSets property


You can then add one or more FDQuery components,

also configured to use the FDConnection created for


SQLite. The SQL statements can refer to any of the
datasets referred to by the FDLocalSQL component's
DataSets property.
Before any of the queries referred to in the preceding

step can be executed, the FDLocalSQL component


must be made active by setting its Active property to
True

Nr 2 / 2014 BLAISE PASCAL MAGAZINE

COMPONENTS

DEVELOPERS

41

LEARN TO PROGRAM

INCLUDING THE PDF FILE

Learn to program, using Lazarus

Special hardcover printed edition


This edition is printed on special FSC Paper
and sewn, so it will not break during reading
The PDF file is included for no charge
The PDF contains extra chapters about the
History of computing and is created in full color.

For subscribers only 25,00 shipment 15,00

by Howard Page-Clark

Separately you can order

The digital edition as PDF formatted


whichj is identical to the printed edition and
contains the chapters about the History
Price 25,00

The following items are included


in both packages

The digital edition as PDF formatted included


is identical to the printed edition and contains

the chapters about the History of computing

ISBN Number: ISBN 978-94-90968-04-5

Nr 2 / 2014 BLAISE PASCAL MAGAZINE

maxbox3.zip
Lazarus Win64.zip - Win32.zip - Laz_Mac.zip
LearningHowardPageClark.pdf
LazarusFileOverview.txt

45

Unit testing - test driven development By Michal Van Canneyt


starter

expert

Delphi and Lazarus


Abstract
Testing new code is a natural thing, done by every
programmer. Testing code in a structured manner is
also frequently found. Test driven development is
taking structured testing to the extreme:
An introduction to one of the possibilities for an Object
Pascal programmer: DUnit.

Introduction
As a software engineer, it is (hopefully) natural to test
your code before shipping your software. There are
many ways to test code. Manually, through some test
program, or using a test framework.
Test-Driven Development (TDD) takes this last
approach even one step further: the test code is written
parallel with (or even before) the actual code to be
tested.
The use of test frameworks became well-established
starting with the junit test framework for Java:
Extremely simple in its design, it is nevertheless very
powerful.

Creating unit tests in a test framework offers several


advantages:
The output of the tests is uniform.
The tests themselves are written largely in the same
manner. Test code written in a test framework is
recognisable for any programmer familiar
with the framework.
It is easily automated. The fact that the output is
uniform makes it suitable for storing.
Using some automation, it is then possible to do
automated regression testing, and it becomes doable to do
continuous delivery.
Unit testing does not mean testing a "unit'' in the Delphi
sense. The "unit'' in "unit testing'' is a single unit of
functionality: this can be a method, a procedure or
function, but can also be
a class or a Delphi unit.
Which of these possibilities
is chosen depends on the
tester. Dunit is a testframework resembling
the junit testing framework,
it is shipped with at least
Delphi XE and higher.
DUnit2 is another testframework for Delphi.
DUnit2 can work with
Free Pascal and Lazarus.
The latter ship with fpcunit,
which is to a large degree
compatible to DUnit.
In this article the use of
DUnit, as distributed with
Delphi, is demonstrated and
explained.
What to test
Normally, unit tests test a
single unit of
functionality: the test checks
whether the
functionality behaves as
expected, i.e. obeys the 'API
contract'. This usually
means constructing several
kinds of input for an

46

algorithm , and checking whether the output is what is


expected. Here input can take various forms: for a
function this may be a combination of arguments. It can
also be a complete XML or JSON document to be processed
by a component, and so on.
Typically, all functions in a unit or all public methods of a
class will be tested.
Testing also includes checking for error conditions, for
example: checking that taking the square root of a negative
number results in an error; or checking how a routine that
expects XML behaves in case it gets JSON as input.
Checking for errors becomes doubly necessary if the API
specifies a series of error codes: in that case the testsuite
should check that the proper error code is returned.
Some people take test-driven development to the
extreme by first developing the test code, watching it fail,
and then implement the actual code till it the tests succeed.
The usefullness of way of working is debatable: the
interface (contract) may not yet be known in advance; it also
supposes that the test code is written correctly: but a test
may fail because the test code is written wrongly...
Although unit testing of a GUI is possible, it is
somewhat awkward; it is difficult to simulate all possible
actions of a user. It is also difficult to integrate in an
automated build system, which is why unit testing is
usually reserved for business logic code - which should
normally be separate from GUI logic, a requirement that
requires some discipline when working in a RAD
environment such as Delphi.
Getting started
To demonstrate how DUnit works, a new fictitious
component (TMyComponent) is created in a new unit
(mycomponent), in a new package (newpackage).
The package is in a project group. Part of the component
code has been written, and now it is time to test the
implementation. So, "Add new project'' is chosen, and
under "Unit test'' the entry 'Test Project' (figure 1 )is
chosen. Upon choosing this, the new test project dialog in
figure 2 is shown (Next Page).

Figure 1: Starting a new test project

COMPONENTS
DEVELOPERS

Nr 2 / 2014 BLAISE PASCAL MAGAZINE

Serving an off the shelf Content Management System


with kbmMW Professional or Enterprise
Edition in less than 30 lines of code!
starter

expert

By Kim Madsen

DELPHI XE2 and beyond

s other articles have described, kbmMW is a


quite capable framework for building
advanced, secure, high performance web
applications with AJAX capability, containing all the
features that are required of the most demanding
web sites of today.
However the truth is also, that sometimes it's simply
easier to use an open source CMS system, instead of
building your own from scratch. Most such systems
require a WAMP/LAMP setup installed. WAMP is an
acronym for Windows/Apache/MySQL/PHP or Python,
and LAMP is an acronym for
Linux/Apache/MySQL/PHP or Python.
Installing and configuring Apache and MySQL in a
safe, but usable way, require some tinkering with
relatively lengthy configuration files.
Further you may want to take advantage of some
features you already have in your existing
infrastructure, which you may be running using
kbmMW application servers.
Over the years, kbmMW has evolved to be the Swiss
knife of n-tier solutions for Delphi/C++Builde and
since it has proven to be both stable, fast and easy
to maintain, countless times in mission criticalr/FPC,

Nr 2 / 2014 BLAISE PASCAL MAGAZINE

setups, where also life and death is involved, whats


more natural than to use kbmMW in combination
with existing open source software in a WMWP
(Windows kbmMW PHP/Phyton) setup?
The recently released kbmMW Professional Edition
and Enterprise Edition v. 4.50 includes many new
features and improvements, of which I'll list a few
important ones:
20 fold faster XML DOM parser. Probably one of
the fastest, supporting namespaces, in the
industry today.
XSD (XML Schema Definition) parser and
kbmMW object generator. It's able to parse
even very complex XSD schemas and produce
all the relevant object classes and types, that
can be used to parse and generate XML AND
JSON files in one single line of code.
FastCGI support via kbmMW's web server
services.
We will in this article primarily look at the FastCGI
support, as that is what makes it possible to host a
PHP open source CMS application like
phpSQLiteCMS, in your kbmMW application server.

COMPONENTS
DEVELOPERS

53

Serving an off the shelf Content Management System (Continuation 1)


The kbmMW application server
If you have read other articles about the kbmMW
application server, you will know that it's designed from
ground up to be extremely flexible, allowing to put
together building blocks to achieve the desired
functionality.
The building blocks within kbmMW, we will be
working with in this article, are the transport, transport
stream format, service and the FastCGI extension.
The transport is basically a component that defines how
external clients should connect to the kbmMW application
server. In our case we want to make a kbmMW application
server that acts like a web server, so we will need to use a
transport that supports TCP/IP.
The transport stream format, defines how bytes being
transmitted and received via the transport, should be
interpreted. Again, we want a web server functionality, so
in this case we should choose kbmMW's AJAX transport
stream format.
The service is a kbmMW definition for a specialized
Delphi/C++ datamodule, which contains relevant
business logic. kbmMW comes with a good number of
predefined services, that can be extended by the
developer. One of them is a web service (not to confuse
with SOAP which kbmMW ofcourse also supports,
but that's another story). The web kbmMW service,
understands GET/POST and other HTML functions, along
with HTTP cookies, headers, authorizations etc. and thus

54

COMPONENTS
DEVELOPERS

have all the functionality to make a kbmMW based web


server, with the correct transport and transport stream
format. The FastCGI extension is a kbmMW feature that
allows kbmMW to communicate and even spawn FastCGI
servers. A FastCGI server is an external process, which can
either live on the same machine as the kbmMW application
server, or on entirely different machines. Read more about
FastCGI here: http://www.fastcgi.com/drupal/
The point of a FastCGI server is basically to be ready to
receive data from a web server, process the data and return
HTML to be sent to a browser. In earlier days, CGI
(Common Gateway Interface) was the norm to use. It was an
executable that was spawned by the web server, processed
data sent to it via its stdin and environment variables, and
sent data out via its stdout and stderr, which were picked
up by the web server and sent as result to the browser.
After each call to the CGI executable, the executable died
and needed to be respawned next time a request would
require data from it. That was not very performance
friendly, why FastCGI was invented. A FastCGI server
continues to run, after being spawned, and all
communication with it is typically done via TCP/IP. A
FastCGI server can typically process requests from multiple
web server calls at the same time. kbmMW do not support
CGI applications.
In our sample we will use a PHP FastCGI server.
As multiple transports with different transport stream
formats, can be added
to any kbmMW
application server,
it's very easy to extend
your existing kbmMW
application server with
for example web
functionality.
Hence no need to add
new complexity to
your company's
infrastructure.
You can simply extend
your existing kbmMW
application server with
the new requirements.

Nr 2 / 2014 BLAISE PASCAL MAGAZINE

Serving an off the shelf Content Management System (Continuation 2)


Prerequisites
phpSQLiteCMS is required for our sample. It can be
downloaded from here http://phpsqlitecms.net/
After you have downloaded it, extract all its contents to a
subdirectory named phpsqlitecms somewhere on your
computer. Remember the directory as you will need to
refer to it later. You could choose any other PHP, Python,
Ruby or Perl (which all provides FastCGI servers) based CMS
system for your setup, but be prepared to read about how
to configure it. If you choose a PHP based CMS, this
sample will generally be ready to use it with very little
change.
Here is a selection of CMS systems.
http://en.wikipedia.org/wiki/List_of_content
_management_systems and here is a site comparing
CMS systems: http://www.opensourcecms.com/
As the sample is using a PHP based CMS system, we
obviously also need to download and install PHP from
http://www.php.net/
If you click on the Download link, you will find a section of
links to the right of the page, where you can download
Windows binary (precompiled) installers. See also the
illustartion on the last page.

A kbmMW application server must at least have a central


module or form (in this sample), which hosts a
TkbmMWServer instance and one or more kbmMW server
side transport components. Other central components may
also be placed here as needed, like database connection
pools, authorization manager components etc. but in our
sample we only need a TkbmMWServer and a
TkbmMWTCPIPIndyServerTransport component at
first, perhaps along with a couple of buttons to start/stop
the application server.
We will leave all properties default for the kbmMWServer1
component, but will need to configure a couple of
properties on the transport component.
First add a binding via the Bindings property.
Set its IP address to 0.0.0.0 and the port to 80. It means that
the server transport will listen for client connections
coming in via all network cards on port 80, which is the
port used by web browsers by default.

After downloading the Windows installer, run it.


You will typically end up with a PHP directory somewhere
(in my case in C:\PHP).
An important next step is to configure PHP. Which exact
configuration is needed will depend on the various PHP
applications that you may choose to run. As we, in this
sample, run phpSQLiteCMS, I'll explain what to configure
for that particular CMS.
Configuration of PHP is done by creating a valid php.ini
file in the PHP installation directory (the directory also
contains php.exe and php-cgi.exe. The easiest way to
define a php.ini file is to copy either php.inidevelopment or php.ini-production and make
modifications to it.
After coping one of the files and naming it php.ini,
open php.ini in Notepad.
Now search for extension_dir = "ext" and remove the ;
to uncomment the line.
Then search for extension=php_mbstring.dll and
extension=php_pdo_sqlite.dll and remove
the ; to uncomment the lines.
Then search for session.save_path = "/tmp"
and remove the ; to uncomment the line.
Further change the line to
session.save_path="C:\PHP\sessionfolder"
or whatever directory is matching your PHP
installation. The sessionfolder directory may not exist,
so you should manually create it.
That's all that is needed to configure on PHP.

Then set the StreamFormat to AJAX and VerifyTransfer to


false.
Next we need to add a new web kbmMW service. It's very
easy to do, by using the kbmMW Service Wizard, which
you will find in File/New/Other, select
Components4Developers and the kbmMW Service Wizard.
When it opens, it shows a list of various known service
types you can choose between. A couple of them are for
creating web functionality, but the one we are going to use
is the HTTP service supporting FastCGI.

A kbmMW web server


So let's get our hands dirty and
produce a kbmMW application
server that acts as a web server.
For the sake of simplicity, the
application server will be created
as a regular VCL application.
However it's just as easy to
create it as a Windows Service,
which can run the moment the
Windows machine starts up.

Nr 2 / 2014 BLAISE PASCAL MAGAZINE

COMPONENTS
DEVELOPERS

55

Serving an off the shelf Content Management System (Continuation 3)

Then click the Next step button at the bottom right corner.

56

COMPONENTS
DEVELOPERS

Nr 2 / 2014 BLAISE PASCAL MAGAZINE

Serving an off the shelf Content Management System (Continuation 4)


Leave the first path edits as is. We will deal with them
later. However we can save a little bit of time, by selecting
which form/datamodule, should contain a file pool
component. The file pool component is a component that
structures access to regular files in the file system, and also
cache access to them to speed up things.
As a traditional web server typically serves many files, like
html, css, php, js etc files, from disk, the web server needs a
file pool.
Select Form1, and leave the new options default.
Then click Next step a number of times without changing
anything until you reach this page:

COMPONENTS
DEVELOPERS

help and consultancy


4 Specialist
for kbmMW

Benno Evers is our specialist


for questions about
kbmMW. He can help you with
basic questions regarding
kbmMW as well as with turnkey
Development and Consultancy.
Hes a specialist in netwoks,
internet and hardware.

CUSTOM TECHNOLOGY
b.evers@eversct.nl

And finally click the generate button with the green


checkmark.
Now a new specialized, although seemingly empty,
datamodule will be generated for you, and the wizard will
have added a TkbmMWFilePool component to your main
form.

Add Unit1 to Unit2's implementation section uses clause,


and then set the property FilePool to of Unit2's
datamodule to point to kbmMWFilePool1 on the main
unit (Unit1).

Nr 2 / 2014 BLAISE PASCAL MAGAZINE

COMPONENTS
DEVELOPERS

57

Serving an off the shelf Content Management System (Continuation 5- End)


Now the bulk of those 30 lines of code will need to be
written. Double click the main form to create its OnCreate
event.
Add Unit2 to Unit1's implementation section uses clause.
Then write the following code in the FormCreate event
handler (you can omit comments ).

procedure TForm1.FormCreate(Sender: TObject);


var
sd:TkbmMWHTTPFastCGIServiceDefinition;
sl:TkbmMWConnectionStringArray;
begin

Whats the code doing?


sd :=
TkbmMWHTTPFastCGIServiceDefinition(kbmMWServer1.
RegisterService(TFastCGIHTTPService,false));
is registering the newly created web kbmMW service to
the TkbmMWServer instance. You can, and typically will,
have many kbmMW service modules registered. Some for
database access, some for business code and some for
web code. In our example we only need one service.
The registerservice call returns a service definition
instance. It can optionally be used to configure service
related settings. Like how many instances of the service
is allowed to run at any time, and in this case, also
information about where to find web related files like
html, js, images etc.

sd:=TkbmMWHTTPFastCGIServiceDefinition(kbmMWServer1.RegisterService(TFastCGIHTTPService,false));
// Its possible to define a default file name if no file is referenced.
// As we define a PHP FastCGI site, index.pbp is typically the default.
// Its also possible to define the default via an URL rewrite. See further down.
// sd.DefaultFile:='index.php';
// Define the root of all resources for the PHP site.
// Actual .php files are placed in the mwhfcOther category.
// Typically these values all points to the same PHP webapp root directory.
// The directory is seen from the current directory of the kbmMW server.
sd.RootPath[mwhfcHTML]:='phpsqlitecms';
sd.RootPath[mwhfcImage]:=sd.RootPath[mwhfcHTML];
sd.RootPath[mwhfcJavascript]:=sd.RootPath[mwhfcHTML];
sd.RootPath[mwhfcStyleSheet]:=sd.RootPath[mwhfcHTML];
sd.RootPath[mwhfcOther]:=sd.RootPath[mwhfcHTML];
// Most FastCGI servers require these settings to be made.
// ServerName and ServerPort is the name/port for which the server
// is accessed from the "outside" before any NAT translations or proxying.
sd.ServerName:='192.168.1.103';
sd.ServerPort:=80;
// Define how to connect to FastCGI servers serving this PHP application.
// Here we define one local PHP FastCGI server (the group name is not
// relevant as such but is used to separate different FastCGI instances
// from eachother).
// More can be defined as separate groups. kbmMW will then round robin
// loadbalance requests to them.
// As a minimum IP and Port entries must be defined for a FastCGI server.
// Optionally Launch and Parameters can be defined, to let kbmMW automatically
// start FastCGI servers as needed.
sl:=TkbmMWConnectionStringArray.Create;
try
sl.Add('<|local|>');
sl.Add('IP=192.168.1.103');
sl.Add('Port=8764');
sl.Add('Launch=c:\PHP\php-cgi.exe');
sl.Add('Parameters=-b 192.168.1.103:8764');
// Rewrite any url for files not found.
sd.Rewrites.Add('^/cms/(.*)$','/cms/index.php?qs=$1',[mwhuroIfFileNotExists,mwhuroBreak]);
sd.Rewrites.Add('^/(.*)$','/index.php?qs=$1',[mwhuroIfFileNotExists,mwhuroBreak]);
sd.FastCGIModules.RegisterFastCGIModule(KBMMW_FASTCGI_URL_MASK_PHP,sl,
'C:\svn_c4d\kbmmw\trunk\demos\FastCGIServer\phpsqlitecms'
);
finally
sl.Free;
end;
end;

58

COMPONENTS
DEVELOPERS

Nr 2 / 2014 BLAISE PASCAL MAGAZINE

Serving an off the shelf Content Management System (Continuation 6)


In this sample, we assume there will be a subdirectory
named phpsqlitecms under the directory from which the
kbmMW application server executable is run. That
subdirectory will be the one containing the open source
CMS. If you have installed the CMS in another directory,
please write the full path to that directory instead.
sd.ServerName:='192.168.1.103';
sd.ServerPort:=80;

These lines are required for most FastCGI based sites.


The CMS PHP code will use these values when it generates
dynamic links in the HTML that it produces.
The ServerName/ServerPort is the DNS name (or IP
address) and TCP/IP port that should be used when
accessing the kbmMW web server from a browser.
If you have NAT translation configured, it should be the
external IP address or DNS name that should appear here,
and typically port 80 (or 443 if you have defined that the
kbmMW application server should support SSL.
(This is not described in this article).
sl:=TkbmMWConnectionStringArray.Create;
try
sl.Add('<|local|>');
sl.Add('IP=192.168.1.103');
sl.Add('Port=8764');
sl.Add('Launch=c:\PHP\php-cgi.exe');
sl.Add('Parameters=-b 192.168.1.103:8764');

This part defines how to access (and automatically spawn)


the PHP FastCGI server on the local machine.
The IP address and port should be the internal IP address
used for the kbmMW application server to contact the
FastCGI php-cgi.exe executable.
The parameters property defines parameters for the phpcgi.exe file, and basically tells it what IP address and
port it should serve. If the php-cgi FastCGI server
runs on another machine, you should only define the IP=
and Port= lines to point to the relevant FastCGI server.
If you have multiple FastCGI servers running, which
all are able to serve the PHP CMS site you can define them
all separated by a line containing a unique name in the
form '<|uniquename|>'. In our case we are using a CMS
that use SQLite for datastorage.
And as SQLite is a flatfile local database, each server have
its own separate SQLite database, why it doesn't make
sense to define multiple FastCGI servers for our sample.
// Rewrite any url for files not found.

The order of the rewrite definitions are important, as they


are checked in order. The mwhuroIfFileNotExists
option ensures that if the given URL actually points to a
true existing file, it will not be rewritten, otherwise it will.
The mwhuroBreak option specifies that if a pattern match
is made, then no more pattern matches will be done for this
particular URL.
sd.FastCGIModules.RegisterFastCGIModule(KBMMW_FAS
TCGI_URL_MASK_PHP,sl,
'C:\svn_c4d\kbmmw\trunk\demos\FastCGIServer\phpsq
litecms' );

Finally we register the FastCGI module configurations. The


constant KBMMW_FASTCGI_URL_MASK_PHP is a
regular expression mask that match a file that is to be
considered eligible for being run by this particular FastCGI
server. Other constants for Ruby, Perl and Python are also
available. The final argument is a local root path for the
locally spawned FastCGI server. Change to match your
setup.
finally
sl.Free;
end;

Now we just need to add a line or two of codes to the


listen and don't listen buttons and also stop the server the
moment the application closes, then we are done.
Put event handlers for the btnListen.OnClick and
btnDontListen.OnClick events, and for the Form1.OnClose
event:
procedure TForm1.btnDontListenClick(Sender:
TObject);
begin
kbmMWServer1.Active:=false;
end;
procedure TForm1.btnListenClick(Sender: TObject);
begin
kbmMWServer1.Active:=true;
end;
procedure TForm1.FormClose(Sender: TObject; var
Action: TCloseAction);
begin
kbmMWServer1.Active:=false;
end;

Compile and run the kbmMW application server,


and you have a new cool CMS system readily running.
This sample can of course be extended in many ways,
like intercepting some of the data access calls, that instead
could lookup data in your corporate databases and serve
those as JSON or dynamically built HTML data.
For more information about that, please refer to older
sd.Rewrites.Add('^/cms/(.*)$','/cms/index.php?
articles in Blaise Pascal Magazine.
qs=$1',[mwhuroIfFileNotExists,mwhuroBreak]);
Whats also cool, is that the FastCGI extension is
designed to work on ALL platforms, which means you
sd.Rewrites.Add('^/(.*)$','/index.php?qs=$1',
could create an IOS kbmMW application server
[mwhuroIfFileNotExists,mwhuroBreak]);
which supports FastCGI. The actual FastCGI server
must of course already be running on another computer.
kbmMW v. 4.50 now also supports URL rewrites, which is almost a Only kbmMW application servers with FastCGI on
requirement for most Apache based web sites.
Windows can automatically launch FastCGI servers.
The purpose of an URL rewrite is to convert specific URLs (defined
Happy FastCGI'ing!
with a regular expression pattern) to some other URL that makes more
sense for the web server and FastCGI servers.
Typically the rewrites are needed in the first place to reduce more
complex URLs to simpler ones, that are more SEO (Search engine
optimization) friendly. In this case kbmMW will rewrite any URLs
starting with /cms/something to
/cms/index.php?qs=something and any remaining URLs to
/index.php?qs=whatever.

Nr 2 / 2014 BLAISE PASCAL MAGAZINE

Best regards
Kim Madsen
Components4Developers

COMPONENTS
DEVELOPERS

59

S
NT RS
E
N E

PO ELOP
M
O EV

kbmMW v. 4.50 with XE6 support just released!


kbmMemTable v. 7.63
with XE6 and Lazarus support just released!
.

kbmMW is the premier high performance, high


functionality multi tier product for serious
system development.

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
Full FastCGI hosting support.
Host PHP/Ruby/Perl/Python applications in
kbmMW!

Supports Delphi/C++Builder/RAD Studio 2009


to XE6 (32 bit, 64 bit and OSX where applicable).
kbmMW for XE5 and XE6 includes full support for
Android and IOS (client and server).!
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!

kbmMemTable and kbmMW


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

COMPONENTS
DEVELOPERS

EESB, SOA,MoM, EAI TOOLS FOR INTELLIGENT SOLUTIONS. kbmMW IS THE PREMIERE N-TIER PRODUCT FOR DELPHI / C++BUILDER
BDS DEVELOPMENT FRAMEWORK FOR WIN 32 / 64, .NET AND LINUX WITH CLIENTS RESIDING ON WIN32 / 64, .NET, LINUX, UNIX
MAINFRAMES, MINIS, EMBEDDED DEVICES, SMART PHONES AND TABLETS.

You might also like