You are on page 1of 20

BLAISE

BLAISE PASCAL
PASCAL MAGAZINE
D E L P H I,
MAGAZINE
L A Z A R U S, OXYGEN (P R I S M), A N D PASCAL RELATED LANGUAGES

27
27

Introduction to thread programming in Lazarus


By Michal Van Canneyt
Introduction to Databases Part 11:
DataSnap Filters and Security
By Cary Jensen
Electronic document processing tools
for Delphi made by Gnostice
By Grish Patil
Use of the "absolute" function abs(..)
By David Dirkse
Development for lazarus
By Joost van der Sluis
What is polymorphism?
By Vsevolod Leonov
Creating and using kbmMW as an Ajax back-end server
By Benno Evers

1 / 2013
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 27
27
D E L P H I, L A Z A R U S, OXYGEN (P R I S M), A N D PASCAL RELATED LANGUAGES V O L U M E 2 7, I S S N 1 8 7 6-0 5 8 9

CONTENTS Editor - in - chief


Detlef D. Overbeek, Netherlands
Tel.: +31 (0)30 890.66.44 / Mobile: +31 (0)6
Articles 21.23.62.68
News and Press Releases
Introduction to thread programming in email only to editor@blaisepascal.eu
Lazarus Authors
By Michal Van Canneyt Page 4 A Alexander Alexeev
Introduction to Databases Part 11: B Peter Bijlsma,
DataSnap Filters and Security C Michal Van Canneyt, Marco Cant,
D David Dirkse, Daniele Teti
By Cary Jensen Page 13 F Bruno Fierens
Electronic document processing tools G Primo Gabrijeli,
for Delphi made by Gnostice H Fikret Hasovic
By Grish Patil Page 23 J Cary Jensen
L Wagner R. Landgraf, Sergey Lyubeznyy
Use of the "absolute" function abs(..) M KIm Madsen, Felipe Monteiro de Cavalho
By David Dirkse Page 36 N Jeremy North,
.iOS Development for lazarus O Tim Opsteeg, Inoussa Ouedraogo
By Joost van der Sluis Page 41 P Howard Page-Clark,
S Henk Schreij, Rik Smit, Bob Swart,
What is polymorphism?
By Vsevolod Leonov Page 48 Editors
Creating and using kbmMW Peter Bijlsma, W. (Wim) van Ingen Schenau,
as an Ajax back-end server Rik Smit
By Benno Evers Page 52 Correctors
Howard Page-Clark, James D. Duff
Copyright Page 118
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.--
(including code, programs and printed magazine,
6 issues per year including postage).
2: Non printed subscription 40.--
Incl. VAT 21% (including code, programs and
download magazine)

Subscriptions can be taken out online at


Advertisers www.blaisepascal.eu
Barnsten page 47 or by written order, or by sending an email to
BetterOffice page 12 office@blaisepascal.eu
Components 4 Developers page 60 Subscriptions can start at any date. All issues
Delphi Developer Days Page 3 published in the calendar year of the subscription will
FastReport Page 40 be sent as well.
Learn to program using Lazarus page 39 / 51 Subscriptions run 365 days.
Lazarus the complete guide page 51 Subscriptions will not be prolonged without notice.
Parallel Programming Receipt of payment will be sent by email.
with Omnithread Library page 22 Subscriptions can be paid by sending the payment to:
Smart Mobile Studio page 24
ABN AMRO Bank Account no. 44 19 60 863
or by credit card: Paypal or TakeTwo
Name: Pro Pascal Foundation-Foundation for
Supporting the Pascal Programming Language
Copyright notice (Stichting Ondersteuning Programeertaal Pascal)
All material published in Blaise Pascal is copyright SOPP Stichting
IBAN: NL82 ABNA 0441960863
Ondersteuning Programeertaal Pascal unless otherwise noted and
may not be copied, distributed or republished without written BIC ABNANL2A VAT no.: 81 42 54 147
permission. Authors agree that code associated with their articles will (Stichting Programmeertaal Pascal)
be made available to subscribers after publication by placing it on the Subscription department
website of the PGG for download, and that articles and code will be Edelstenenbaan 21 / 3402 XA IJsselstein,
placed on distributable data storage media. Use of program listings The Netherlands / Tel.: + 31 (0) 30 890.66.44 /
by subscribers for research and study purposes is allowed, but not for
Mobile: + 31 (0) 6 21.23.62.68
commercial purposes. Commercial use of program listings and code
is prohibited without the written permission of the author.
office@blaisepascal.eu

2 COMPONENTS
DEVELOPERS 4 Nr 1 / 2013 BLAISE PASCAL MAGAZINE
Don't Miss! Delphi Developer Days 2013

www.DelphiDeveloperDays.com

Delphi Developer Days 2013


Featuring Bob Swart & Cary Jensen
Bob Swart and Cary Jensen present Delphi Developer Days 2013, a Delphi training tour in the
United State and Europe. Delphi Developer Days is an intense two-day live event where you
will experience both joint sessions, presented by Bob and Cary together, as well as
simultaneous tracks. Some of the topics covered include browser-based clients, essential
through advanced database development, from VCL to FireMonkey, mobile development and
Delphi's NextGen Compiler, data access components, DataSnap, REST versus DBX, XML
and JSON, SOAP, debugging applications, writing Windows services, and gestures and touch
in Delphi applications. There's also an Embarcadero keynote, plus a session by a guest
speaker.

Delphi Developer Days 2013 Dates and Cities


Date City Location
6-7 May 2013 Chicago, USA Holiday Inn Express NW O'Hare
30-31 May 2013 Frankfurt, Germany Holiday Inn Express Frankfurt

3-4 June 2013 Amsterdam, NL Park Plaza Victoria Amsterdam


Seating is limited to 42 people per city.

Attendees Receive:
An extensive course book (several hundred pages) written by Bob and Cary
that includes material covered in their joint and individual sessions
Source code examples from all of their sessions
A chance to win valuable prizes from our sponsors
Lunch on both days

Register early for an additional discount. Previous attendee and group discounts are available.

Register Now to Reserve Your Space!


www.DelphiDeveloperDays.com

Nr 1 / 2013 BLAISE PASCAL MAGAZINE 3


Introduction to thread programming in Lazarus
By Michal Van Canneyt TThreadList
starter expert Lazarus 1 This is a special list which can be locked for exclusive
access by a thread. It is declared in the classes unit.
Because of the complexity of the subject we have asked TCriticalSection
The Author (Michael van Canneyt) on behalf of showing This class can be used to make sure a particular piece of
and making Delphi and Lazarus more compattible to help code is executed only by one thread at a time. It is declared
demonstrating the processes. in the syncobjs unit.
Abstract 3 The TThread class
Thread support in Free Pascal has received an update, From the classes presented above, the most important class is
so it is compatible to thread support in Delphi XE3. Time
TThread. It has at least the following public methods:
to re-visit the subject of threads, and look at the
Start
possibilities for those not familiar with thread
programming. this will start execution of the thread if it was created in a
suspended state.
1 Introduction Terminate
Recently, FPC received a substantial upgrade in its Tells the thread to stop executing at the earliest possible time.
threading code. It has been made compatible with the WaitFor
Delphi XE3 threading possibilities. Time for a refreshment This waits for the thread to end, and returns the exit code of
on how to do threading in Lazarus/Free Pascal. the thread.
Threading means writing the code of an application so that
several parts of the code are executed simultaneously, in And some properties:
parallel. Each part of the code forms a thread of execution.
Threading requires support by the hardware: several FreeOnTerminate
processors or a processor with various cores. If the This property is described in detail below.
Handle
hardware does not allow it, the operating system mimics
An operating system handle for the thread.
simultaneous execution by giving the various parts of the
ThreadID
program time to execute in an intertwined fashion,
An operating system ID for the thread.
much like it allows multiple programs to execute ExternalThread
simultaneously. The scheduling of threads and programs A boolean indicating whether this thread was started outside
by the operating system is a huge subject in itself, and is the RTL.
done differently by each OS. Priority
The difference between threads and multiple programs An indicator of the threads priority.
is of course that all threads in a program all have access to Suspended
the same data and memory space. Programs can share A Boolean indicating whether the thread is currently
some memory by using shared memory and special executing or not.
operating system calls. Access to the shared memory by the Finished
various threads must be carefully designed, or strange A Boolean indicating whether the thread has finished
things may happen: As long as one thread only writes and executing.
another thread only reads from a shared memory location, OnTerminate
things will usually progress without problems. However, if An event handler that is calledwhen the thread has finished
threads will try to update the same memory location, executing.
strange things may happen. To prevent FatalException
this, special programming is required. In this article, well If an exception is raised during the execution of the thread,
show how this is done. but is not caught by user code, then it is caught and held here
for inspection.
2 Thread support classes in Free Pascal
The threading support of Free Pascal makes it relatively There are also some protected methods, only available inside
simple to create multi-threaded programs. FPC provides the TThread class and its descencents:
several classes and a language construct to deal with Execute
multiple threads in a program: A virtual abstract method that must be overridden.
Synchronize
TThread Allows to schedule a procedure for execution in the main
This is the heart of the threading system: thread. The thread waits till it has finished executing.
This class encapsulates a thread in a program. It is declared Queue
in the classes unit. Allows to schedule a procedure for execution in the main
threadvar thread. The thread does not wait till it has finished executing,
This is a special kind of variable: but continues at once.
global variables are normally accessible by all threads in a And 2 protected properties:
program. When they are declared as threadvar instead of ReturnValue
var, each thread in the program will receive its own copy This is an integer value that can be set to report back at the
of the global variable. end of the thread.
TMultiReadExclusiveWriteSynchronizer It is the value that is reported when WaitFor is used.
This class serves to protect access to a piece Terminated
of data such that it can be read simultaneously by various This is a flag that must be regularly checked during
threads, but can be written execution of the thread: when it is set to True, the thread
only by one thread. It is declared in the sysutils unit. should stop executing. It is set by the Terminate method.
4 COMPONENTS
DEVELOPERS 4 Nr 1 / 2013 BLAISE PASCAL MAGAZINE
Introduction to thread programming in Lazarus (Continuation 8 End)
Note that the main form does not use the critical section
About the Author
when reading the data. The result can be seen in figure 4
Michael van Canneijt
on page 18. It is left as an exercise to the reader to find out
is one of our important authors. He writes several
why it would be more correct to update the display in a
books and articles, yet an other to come:
critical section as well. The Pascal Bible a book we will present later
this year.
9 Conclusion
He is the main author behind our legendary first
Threads can be very useful when performing lengthy
tasks in the background. The thread support in Free book over Lazarus: Lazarus the complet guide.
Pascal makes it very easy to do. Having multiple threads
perform tasks in the background while accessing and He nowadays is working for MailJet in Paris.
modyfing the same shared data is a bit more tricky, but He is the main man behind FPC Pascal and has an
can be done as well with standard classes provided by enormous knowledge of Pascal, Delphi Free pascal
Free Pascal. and Lazrus in many ways.

12 COMPONENTS
DEVELOPERS 4 Nr 1 / 2013 BLAISE PASCAL MAGAZINE
Introduction to Databases Part 11: By Cary Jensen
DataSnap Filters and Security
starter expert Delphi 10 and later

In the preceding article in this series I walked you through the creation of a
simple IP-based DataSnap Server, which Embarcadero refers to as a
DataSnap DBX Server (as opposed to DataSnap REST). In this article I am
going to go into greater depth, and discuss the use of server class lifecycle,
authorization, authentication, and filters. I will begin this discussion by
exploring the various classes that are involved in the creation of a DataSnap
server (these apply to both DBX and RESTful DataSnap servers).

Figure 1. Page 2 of the DataSnap Server wizard.


DataSnap Server Components
Let's begin by creating a new DataSnap server. However, unlike the simple server that
we created in the preceding article in this series, this time we will ask the DataSnap
Server wizard to add additional capabilities to our server.

1. Close any open projects. Then, select


File | New | Other from Delphi's main menu.
2. Select the DataSnap Server tab under the
Delphi Projects tab.
3. Double-click the DataSnap Server icon to launch
the DataSnap Server wizard
4. For convenience, select the VCL Forms Application option from page 1 of the
DataSnap Server wizard. This option makes it easy to create and debug your
DataSnap server, though as I mentioned in the preceding article, you will eventually
want to convert this application to a Windows service before you deploy it. Click
Next to advance to page 2 of the DataSnap Server wizard, shown in Figure 1.

Nr 1 / 2013 BLAISE PASCAL MAGAZINE COMPONENTS


DEVELOPERS 4 13
k
ar
-Cl
ge
Pa
d
ar
ow

A Smart Book Gabrijeli


H

Primo
Gabrijeli
Primo

K
B OO
RT
MA
AS EN
T
IO
UD
PM
LO TH
VE L WI
T
ES
E
B D CA
WE PAS
L
O
IN
BI
m TM
with OmnithreadLibrary

ra 0 AR
Parallel Programming

o g SM
o Pr us 1.
n t ar
e ar Laz
L g
in
us i
jel org
barmimer.
a
G r
rog
mortp
Pwrwi.sma
SMART MOBILE

o i NE
STUDIO

ZI
im l MA
G A

Prrije SC
AL
A
ab
P
SE
AI
G B L

BLAISE PASCAL MAGAZINE


publishes two new books, written in English
Author Primo Gabrijeli
Parallel Programming
with Omnithread
Library,
and
Smart Mobile Studio
http://www.blaisepascal.eu/index.php?
actie=./subscribers/UK_Book_Department
Electronic document processing tools for Delphi By Grish Patil
made by Gnostice
The Gnostice document-processing components
for Delphi have been devloped to their present
high-performance level simply to meet the needs
of their customers - indeed necessity is the
mother of invention.
This article charts their development detailing
their present technical capabilities, and looks to
future development as well.

History
A classmate and I were working as software
consultants in the late 90s, when a customer
requested inclusion of a particular feature in
software we had developed for him: he wanted the
application to generate reports that could be
distributed easily, and viewed in any web browser.
We had developed the application using
QuickReport which, at that time, generated text-
only HTML output and did not handle deeply nested
report sub-detail. We had created a separate
QuickReport report viewer app that had to be
distributed to his employees, which was really
cumbersome to deploy. So we then developed a
WYSIWYG HTML export filter for QuickReport,
based on TQRExportFilter.

TGPQRHTMLExportFilter = class(TQRExportFilter)
// Public content-creation methods were overridden
procedure BeginDoc; override;
procedure TextOut(X, Y: Integer;
Text: string); override; Figure 1: The HTML filter was derived from
procedure EndDoc; override; the generic QuickReport export filter:
// Missing content-creation methods were introduced
procedure DrawImage(X, Y: Integer; Image: TGraphic);
procedure DrawShape (X, Y: Integer;...);

Custom controls were derived from all the QuickReport


controls (content elements) so we could send more report Evolution to the present day
We had started supporting multiple reporting tools.
content information to the new HTML filter. This enabled
The export component for each tool was a separate product
the filter to generate WYSIWYG HTML output internally:
and the code was tightly coupled with it.
TGPQRImage = class(TQRImage) We felt the need to have a single codebase and wanted to
procedure Draw(...); override; decouple the logic of the format-generation engine from
Our new custom controls' overridden Draw methods could that of report-specific code. Necessity was again driving
call our new content-creation methods introduced in the invention.
TGPQRHTMLExportFilter: We also wanted to be able to adapt to any possible
future document-creation requirement, and this was
procedure TGPQRImage.Draw(...);
achieved by supporting standard printing and Windows
if Report.Exporting and (Report.ExportFilter
is TGPQRHTMLFilter) then graphics-drawing mechanisms. Our truly multi-talented
TGPQRHTMLFilter(Report.ExportFilter).Draw eDocEngine was born out of this refactoring, offering many
Image(...); ways to create report content. eDocEngine has remained a
cutting-edge multi-format document-creation engine.
The HTML filter was a big hit with our customer and was
quickly followed by filters for other formats including
WYSIWYG filters for PDF and RTF.
Since the customer's reports had to use these custom
report controls, I created an application that went through
any reporting project and upgraded it to use the new
controls. With just a few clicks, his existing report projects
were upgraded to generate WYSIWYG HTML, PDF (and
other format) reports.
Other customers loved this product too.
It soon came to define our company's main product line.
The company we had envisioned long before Gnostice
was founded in 2002 to concentrate on developing
electronic document processing tools.

Nr 1 / 2013 BLAISE PASCAL MAGAZINE COMPONENTS


DEVELOPERS 4 23
Electronic document processing tools for Delphi (Continuation 1)
eDocEngine
Delphi HTML, RTF Your GDI or Metafiles, RTF, Content-Creation
metafile viewer API (pages,
Reporting TCanvas Drawing text, images
exporter paragraph, tables,
Tools code headers, footers
components from fields,
annotation, etc.)

eDocEngine VCL

Report - Export Interface Document - Creation


Components Components

PDF RTF HTML XLS CSV BMP PNG JPG SVG EMF WMF

Figure 2: Schematic overview of the overall system

eDocEngine can create content in: Here's how:


PDF, RTF, HTML, XHTML, EXCEL, TEXT, CSV, 1. Drop a format engine component (say PDFEngine)
Quattro Pro, LOTUS 1-2-3, DIF, SYLK, TIFF, TgtPDFEngine - to export to PDF
PNG, SVG, JPEG, GIF, BMP, EMF and WMF formats. 2. Drop the appropriate report export interface (say
FrExportInterface)
Also included are report-export adapters
TgtFRExportInterface - to connect with FastReport
(we call them Export Interfaces) for many popular Delphi
3. Wire the export interface to the format engine
reporting tools:
Select PDFEngine as the value for FREExportInterface
AceReporter,
object's Engine property
DevExpress Printing System,
Now, when we run the application and preview the report,
FastReport,
the option to save to PDF magically appears in the report.
GmPrintSuite,
(See the next page top)
QuickReport,
Rave Reports, eDocEngine's document-creation engines are really mature
ReportBuilder, and include many of the advanced features that you
ScaleRichView, usually find only in specialized tools. For example, the PDF
ThtmlViewer, engine includes support for on-the-fly digital signing
TMS Grid,
TRichView,
WPRichText,
WPTools

Figure 3: The Toolpalette


With these report-export interfaces, users can export
reports without writing any code. This lets you add
high-quality report-export capability to existing
Figure 4: It offers export of charts as vector graphics
applications in just three simple steps. and RichText content as rich text to retain hi-fidelity
24 COMPONENTS
DEVELOPERS 4 Nr 1 / 2013 BLAISE PASCAL MAGAZINE
Electronic document processing tools for Delphi (Continuation 12)
Future plans, continuing Present
Increasingly demanding requirements need ever smarter solutions! As our insight into document creation, rendering and
analysis has deepened we have struck out in fresh directions with our product technology. Our goal now is to provide a
single toolset that enables developers to perform any kind of document-processing operation in any format. Our
customers will not have to be concerned about using different toolkits for different operations on documents. They will
also be writing much less code.
This is not just an integration of all the products we have created thus far, but a fresh start and a brand-new extensible
and seamless architecture. We call this product XtremeDocumentStudio

The first area we decided to tackle was viewing of DOCX


and PDF formats. Our engineers have already done a great
job on the .NET version and we are working on the Delphi
version. For now, let us see a sample from the .NET version
using Delphi Prism. We will be creating a DocX/PDF viewer
application.

1. Create a new Windows Form project.


2. Drop a Gnostice DocumentViewer control on the form.
3. Drop other controls such as an Open File Dialog,
a toolstrip for the toolbar button and the required buttons.
4. Program event handlers of the buttons with
DocumentViewer methods such as the NextPage and
PreviousPage.
5. Program the Open button to load the selected document
into the DocumentViewer using the LoadDocument
Figure 19: Graphic depicting some of the major method.
document processing functions that That's it! We are ready to run the multi-format document
XtremeDocumentStudio will enable. viewer.

Figure 20: A multi-format document viewer created using XtremeDocumentStudio.

We know from experience that the Delphi developer community is a great adopter of tools and components. However
we were still surprised at the overwhelmingly positive response to our new tools presentation at the 2012 Delphi Tage
conference in Germany. We are very excited about the future and the upcoming releases of next-generation document-
processing toolsets both for Delphi and Delphi Prism developers.

Nr 1 / 2013 BLAISE PASCAL MAGAZINE COMPONENTS


DEVELOPERS 4 35
Use of the "absolute" function abs(..) By David Dirkse
starter expert Delphi 3 and later, and Lazarus

The Delphi "system" unit contains a function In the plot above the scale of a rectangle is 0.2
abs(x) which returns the absolute value of Point (0,0) is positioned at an acute angle in the line. This is
variable x. The parameter x can be either an a unique property of the abs function. All other functions
integer or a real value. like log, sin, cos, tan or polynomials produce smooth
curves.
So,
abs(+15) = 15 All results in this article build on the plot of the abs
abs(-15) = 15 function. Of course, the discontinuity will not always be
nicely positioned at (0,0).
Note that the abs function actually combines two functions Therefore, before continuing, we will discuss several
because: general ways to manipulate graphs of functions: how the
plots can be shifted, reflected, or scaled.
if x < 0 then abs(x) = -x
if x > 0 then abs(x) = x If we replace x by (x-1) in an arbitrary function, the
plot will shift 1 scale unit to the right.
This article demonstrates several useful applications for the To understand this, notice that the plot of y = f(x) is the
abs() function. collection of points (x,y) that satisfy the equation y =
f(x). Say point (p,q) is part of the plot, so, q = f(p).
1. Calculating Distances But if x is replaced by x-1 we no longer have p = x, but
Suppose your application paints a line using mouse-clicks we have p = x -1, so x = p + 1.
to specify the two end points. Successive clicks yield the P has changed to p + 1, so , (q,p+1) is now part of the
points (x1,y1) and (x2,y2). You store horizontal and vertical plot which means that the plot has shifted 1 scale unit to
offsets in the variables dx and dy. the right.
The following assignments will calculate these offsets: Similarly we can deduce that changing y into (y-1) shifts
the plot 1 scale unit upwards.
dx := abs(x1 - x2)
dy := abs(y1 - y2) Replacing x by (x+1) shifts the plot 1 scale unit to the left;
and replacing y by (y+1) shifts the plot 1 scale unit
Note that there is no difference between abs(x1 - x2) downwards.
and abs(x2 - x1). If x is replaced by x/2 in any function y = f(x), then the
plot is multiplied by 2 in horizontal direction (relative to the
To avoid negative distances we could have used if y-axis). Replacing y by y/2 multiplies the plot by 2 in
statements. However, this approach is slower because vertical direction (relative to the x-axis).
processors use pipelines for code execution, and an if
statement forces a restart of the pipeline, which interrupts If x is replaced by -x in any function y = f(x), then the
the instruction streaming. plot is reflected relative to the y-axis. Replacing y by -y
reflects the plot around the x-axis.
2. Calculating a lower limit
Say we have a variable x which is not allowed to take a Bearing the above transformations in mind, enables us to
negative value. This means that if x drops below zero it move the angle at (0,0) of y = abs(x) to any other position.
then has to be reset to zero. Consider the following function:
Again, we might use an if statement but the abs() function
is equally suitable. y - 2 = abs(x - 3) which means
y = abs(x - 3) + 2
To appreciate why, it may help to look at the plot of the
The point of discontinuity is moved from (0,0) to (3,2)
function y=abs(x) first.

Figure 2:
Figure 1:

36 COMPONENTS
DEVELOPERS 4 Nr 1 / 2013 BLAISE PASCAL MAGAZINE
Use of the "absolute" function abs(..) Continuation 1
Back to our initial objective: finding a function that -y = 0.5(abs(x) -x) or
automatically establishes a lower limit to a variable. y = -0.5(abs(x) -x) or
For this we combine two functions: y=abs(x) and y=x. y = 0.5(x - abs(x))
We plot y = abs(x) + x
Now for x > 0 the upper limit is 0 and for x < 0
we get y = x.
The angle may now be shifted to any position.
The slope is adjusted to 1 by the factor 0.5

Figure 3:
For x < 0 the function delivers a lower limit of zero,
however for x > 0 the slope is too steep. We need y =
x, but get y = 2x. Figure 5:
Therefore, we replace y by 2y to multiply the plot by a Say we want an upper limit of 100. Point (0,0) must be
factor 0.5 in the vertical direction. shifted to (100,100) in this case,
The function changes to so we replace x by (x-100) and y by (y-100)

2y = abs(x) + x or y = 0.5(abs(x) + x) y - 100 = 0.5((x-100) - abs(x-100)) o


y = 0.5(x - abs(x-100)) + 50

4. Providing both upper and lower limits

We plot the function y = 0.5(abs(x+1) - abs(x-1))


Note: the scale below is 0.2

Below x = -1 the function has a lower limit of -1 and


above x = 1 the upper limit is 1

Figure 4:
Say we want a lower limit of 10.
Point (0,0) must be shifted to point (10,10).
X is therefore replaced by (x-10) and y by (y-10) so,

y-10 = 0.5(abs(x-10) + (x-10) or


y = 0.5(abs(x-10) + x) + 5 does the job.

3. Calculating an upper limit Figure 6:


For an upper limit we mirror the plot around the y-axis by
changing x into -x:

y = 0.5(abs(x) - x)
note : abs(-x) = abs(x)

The function returns 0 for x > 0 and abs(x) for x < 0,


which is not quite what we want.
Reflection again, now around the x- axis (replace y by -y):

Nr 1 / 2013 BLAISE PASCAL MAGAZINE COMPONENTS


DEVELOPERS 4 37
Use of the "absolute" function abs(..) Continuation 2
Please note that 5. Painting rectangles rotated by 45 degrees.
abs(lower limit) = abs(upper limit) = 1
But how can we establish different lower and upper limits? The figure below shows a rectangle rotated 45 degrees from
We start with function the horizontal.
y = 0.5(abs(x+v) - abs(x-v)) We are looking for a simple way to draw this rectangle.
For x < -v we may write:

y = 0.5(-(x+v) - (v-x)) = -v ............lower limit

For x > v we may write

y = 0.5((x+v) - (x - v)) = v.............upper limit

And for x > -v & x < v we get

y = 0.5((x+v) - (v-x)) = x .................no correction

Say, we want a lower limit of a and an upper limit of b. Figure 7:


The distance between the limits is b - a. Let's give the top pixel coordinates (sx,sy).
So, v = (b-a)/2 for the upper limit and the lower limit See the figure below. The edges of the rectangle have
is -v = (a-b)/2. lengths h and v.
But the upper limit must be b, not (b-a)/2 so a shift is Painting is done by drawing horizontal lines from point x1
needed of (end - start) : to x2 at distance y from the top of the bitmap.

b - (b-a)/2 = (a+b)/2 ,
a shift over the line y = x
so replace x by x-(a+b)/2 and y by y-(a+b)/2

so:

y = 0.5(abs(x+v) - abs(x-v)) which yields


y - (a+b)/2 = 0.5(abs(x-(a+b)/2
+ (b-a)/2) - abs(x-(a+b)/2 - (b-a)/2))
y - (a+b)/2 = 0.5(abs(x-a) - abs(x-b))
y = 0.5(abs(x-a) - abs(x-b) + a + b)
Figure 8:
In this way a function can be constructed with any
So, the program might look like this:
arbitrary upper and lower limit, without the use of if
statements. The processor pipelines can stream var j : word;
uninterruptedly. h,v : word;
My graphics program Graphics-Explorer may be used to sx,sy : word;
visualize the results. bm : Tbitmap;
begin
.....
Download the program from the web page //creation of bitmap
http://www.davdata.nl/math/grxpl.html //setting rectangle dimensions h and v
Type y = 0.5(abs(x-a) - abs(x-b) + a + b) and click "plot". //setting position (sx,sy)
Select (right top) "replace" (not add) and "autoplot". ...
with bm.canvas do
Now click (left or right) at the a and b windows to
begin
increment or decrement constants a and b. The plot pen.color := 0;
immediately adjusts itself to the new values. pen.width := 1;
for j := 0 to h + v - 2
Below I summarize the results so far: //from top to bottom of the rectangle
begin
Variable x is assigned a y := sy + j;
lower limit a using function x1 := ???;
y = 0.5(abs(x - a) + x + a) x2 := ???;
upper limit b using function moveto(x1,y);
y = 0.5(x - abs(x - b) + b) lineto(x2,y)
both limits a, b using function end; //for j
end; //with bm
y = 0.5(abs(x - a) - abs(x - b) + a + b)
....
end;
Quite surprising, isn't it?

38 COMPONENTS
DEVELOPERS 4 Nr 1 / 2013 BLAISE PASCAL MAGAZINE
Use of the "absolute" function abs(..) Continuation 3
Let's look at the relation between x1 and j. the function becomes
For the sake of simplicity, assume the top pixel has
coordinates (0,0). x1 + 3 = abs(j - 3) or
x1 = abs(j - 3) - 3
j 0 1 2 3 4 5 6 7 8
x1 0 -1 -2 -3 -2 -1 0 1 2
If the height is not 3 but v the function changes to
Figure 9:
From this table we draw a plot. x1 = abs(j+v-1) - (v-1)
This plot appears to be bent, which reminds us of x1 =
abs(j) where (0,0) is shifted to position (3,-3) so For the final result, sx has to be added to the horizontal
position so,

x1 = sx + abs(j+v-1) - (v-1)

Similarly we calculate that

x2 = sx - abs(j-h+1) + (h-1)

Note:
moveto(0,0) followed by lineto(10,0) draws a line from (0,0)
to (9,0).
Pixel (10,0) is not included.
Therefore, 1 has to be added to x2.

This concludes my article about ways you can usefully


apply the abs( ) function.
Figure 10:

Good news for startes


BLAISE PASCAL MAGAZINE
has publishd a book in English
aimed at people who are just setting
out to learn to code.
It is called
Learn to Program
using Lazarus 1.0,
and is written by Howard Page-Clark,
our editor, corrector
and writer of many articles

Among the many topics introduced are:


Pascal types, the Lazarus IDE,
Coding discipline,
GUI editing components,
Pascal files and streams,
Object oriented principles,
debugging techniques.

NEW:
As PDF File on USB STICK (8 GB) including
Lazarus Mobile Windows (Click and go)
version 1,07 on the stick and the three
As Loose Leaf Book As PDF File Operating Sytems Linux Mac Windows
35 plus postage 17,50 25 no postage 35 plus postage 3,50

Nr 1 / 2013 BLAISE PASCAL MAGAZINE COMPONENTS


DEVELOPERS 4 39
.iOS Development for lazarus
By Joost van der Sluis The iOS Designer uses Lazarus functionality which is not
starter expert Lazarus 1.1 or higher yet available in an official release. So you need to use a
development version of Lazarus (version number 1.1 or
This is a short introduction to developing iOS higher). These versions can be downloaded from the
applications using Lazarus and the iOS Designer. For Lazarus website (or mirror sites) or orderd from our
some time it has been possible to write applications for Magazine. We will bring a special prenstalled version for
iOS using Free Pascal and you could use Lazarus as a
you in within some time, to make the use easy.
smart text editor.
http://www.blaisepascal.eu/index.php?actie=./subs
Now it is also possible to use Lazarus to design iOS cribers/UK_Book_Department
screen layouts using the iOS Designer, which makes
layout design and use much easier. However this The cross compiler for iOS devicesAn iOS device
additional functionality is rather new and is still being (iPhone, iPad) makes use of an ARM processor. That's a
developed. For instance the current installation and
different type of processor from those based on the i386
settings need a lot of improvement; but for those who
are really interested in iOS development it's definitely architecture which you find in most desktop PCs. To create
worth investing some time to learn about this new applications which run on an ARM processor you need a
capability. compiler which generates code for that type of processor.

Four resources are required in order to be able to develop Because we want to create our iOS programs on a machine
applications for iOS using Lazarus and the iOS Designer: running under OS/X, we need a 'cross compiler'. A cross
A Free Pascal cross-compiler for iOS devices or the iOS compiler runs on a different type of processor than the
Simulator. type for which code is generated.
The Pascal iOS header files. In our case the compiler runs under OS/X with an i386 (or
Knowledge of the Objective Pascal language extensions x86-64) architecture, but generates code for the ARM
in Free Pascal. architecture.
The iOS Designer and iPhoneLazExt packages installed Such a cross compiler can be downloaded from the Free
in the Lazarus IDE (v1.1). Pascal website.

Nr 1 / 2013 BLAISE PASCAL MAGAZINE COMPONENTS


DEVELOPERS 4 41
Barnsten has selected the best tools for the best developers
and is already for 20 years the expert for the Embarcadero products.
Each day we have contact with a lot of Delphi Developers to give advise,
trainings, consultancy and the use of components.
Barnsten has collected by now more then 600 components.
Here is an overview of the most used and wanted Delphi- and C++Builder
components:

Feature rich reusable PDF Fast Report


Componens Reporting must be fast

Mida converter for FireMonkey For building quick


FireMonkey Components powerfuul
for easily creating stunning apps! multimedia applications

Excellent Delphi Components A collection of over


boosting your performance 180 VCL Controls

The easiest way


Graphical components for to create unit test
Win, Mac OS and iOS/iPhone

Build your own sophisticated


user interfaces in less
A Unique set of Universel
time with less effort
Data Access Components
Embedded Database Engines
for database application developers

Take a look at the components on


http://www.barnsten.com/default/components
Is the component you are looking for not available?
Then please make contact, so we will be able to help you.
The components are deliverd electronically.

http://www.barnsten.com/default/components
What is polymorphism? By Vsevolod Leonov
What problem does polymorphism solve?
Good explanation leads to solid understanding
In the Russian-speaking world there are many printed
What problems do developers face? Well, polymorphism
books about Delphi, as well as many digital books does not solve the salary problem (at least not directly).
about Delphi. I am holding a 1,024-page Delphi book However, polymorphism allows developers to create large
now. Yet it devotes only five lines to an explanation of programs with minimal code complexity. Who needs
the term polymorphism. Whereas the TButton simple, yet powerful, code? Probably everyone! A
component requires 96 lines of text and two programmer is satisfied with high quality code. A user is
illustrations along with two source code examples. Is
also satisfied, and will not have to curse developers for yet
understanding a button component twenty times more
important than understanding polymorphism? another bug. The developer's employer also wants
polymorphism because simple, yet powerful, code is faster
As a RAD IDE Delphi is justifiably considered the best and easier to maintain, modify and develop (i. e. cheaper).
programming environment from the point of view both If you try to answer the question Why is it bad to use
of beginners and professionals. However, critics of the global variables? you'll find the answer is closely related
RAD paradigm often point to the fact that RAD to the answer given to the question What problem does
technology leads to a proliferation of bad programmers.
polymorphism solve?
The previous paragraph shows why.

Polymorhpism is voluntary
Aurora Borealis Q: Can you avoid using polymorphism?
Perhaps a good explanation of a new concept should begin
with a definition. A: Sure! Before the invention of polymorphism as a
Polymorphism is derived from a Greek term which literally programming paradigm people got along without it.
means many forms. In the field of programming However it makes no sense to ignore what has already
polymorphism means that the calling of a conceptual been well thought out, and is easy to understand.
operation is isolated from its actual implementation. In
fact, at runtime, the implementation may vary Q: Can I use polymorphism without realizing it?
considerably, depending on the type of object that
performs the operation. A: This is more than likely. However, more often you are
There is no redundancy in this three-sentence definition. A using object-oriented code written by someone else which
beginner trying to understand a shorter definition would has polymorphism at its core. Delphi programmers do this
be short-changed. We should not imagine that a supremely all the time.
crisp, succinct definition is one of the hallmarks of
polymorphism. Q: I asked my friend, who is a professional programmer, about
Try to read the above definition as you would understand polymorphism. He answered me evasively. Does that mean he
a description of the Northern lights, since polymorphism does not understand it?
likewise shines in the north. You can easily understand
what the Northern lights are simply by looking at A: He knows about it, but it is hard to explain which is
photographs. We will try to make up for the unfortunate the reason for this article. So you cannot have an excuse
fact that you cannot photograph polymorphism. any more for saying that Delphi multiplies ignoramus-
programmers.
Esoteric knowledge
Ask (a friend, a teacher, Google) about polymorphism and I have already read a lot about this, so I don't
you realize it is considered esoteric knowledge. You will be see the point of this article.
told You need to work on polymorphic constructs for a Well, you already know then that you should not be afraid
year and then maybe you'll understand. of polymorphism. Here are some pointers for writing high
A textbook explanation will conclude with: quality code:
polymorphism is a way of dealing with two or more Don't use global variables; add comments; name variables
similar but technically different tasks. In fact, however, meaningfully; utilize polymorphism.
programming is an engineering science. Its wonders and Certainly there is complexity in programming, but it is not
creativity arise from easily explained concepts, with in polymorphism as such.
nothing esoteric at all.
I'm tired of reading!
Mouse around Well, I am tired of writing! But what else can we do if
The ability to effortlessly 'mouse around' in a RAD IDE Delphi books devote only a few lines to explaining
is ultimately unhelpful if it detaches novices from the polymorphism, while devoting far more text to describing
code they are generating the properties of the TLabel component? Sometimes you
You have to understand that syntax development in must consider a topic comprehensively.
programming languages (such as adding the new paradigm of
encapsulation, inheritance and polymorphism) is designed for
very specific needs that developers have. For instance you
are not interested in the philosophy (or spirituality) of a
car's automatic transmission. It was introduced to meet a
specific need. Polymorphism likewise solves a specific
problem.

48 COMPONENTS
DEVELOPERS 4 Nr 1 / 2013 BLAISE PASCAL MAGAZINE
http://www.barnsten.com/default/development-tools

LAZARUS
THE COMPLETE GUIDE (ExtraPackage updated)

New Version 1.7


Complete Package 60,00 (Paperback)
will also include a free download subscription of
BLAISE PASCAL MAGAZINE for 1 year.
If you are a subscriber you can buy the simple pac it for just 35,00

(this excludes shipping costs).


Including Blaise Pascal Magazine it offers a complete package
The complete package contains
Lazarus the Complete Guide
1 a Windows installer for Lazarus Version 1.7
2 a Linux for Lazarus Version 1.7
3 a Mac for Lazarus Version 1.7
4 Lazarus Portable, a prenstalled copy Lazarus Version 1.7 on
a free 8 GB USB stick (Click and Go)
5 60 additional sample projects on installed CD and USB Stick
6 extra: additional prenstalled component suites on both:
DVD and USB Stick.
7 free Blaise Pascal Magazine Library on the USB Stick,

Completed up to all 26 issues, including code


BLAISE PASCAL MAGAZINE www.blaisepascal.eu

Extra Service: If you buy the complete package you will


have the book Learning to program using lazarus
for free as PDF file.
http://www.blaisepascal.eu/index.php?actie=./subscribers/UK_Book_Department

WINDOWS MAC
LINUX WinXp/Vista/Win7

LAZARUS V1 LAZARUS V1 LAZARUS V1


Pro Pascal Foundation Pro Pascal Foundation Pro Pascal Foundation

48
51
47
27
New V4.11.00 available
for DELPHI XE2 -32 and 64
On iPad and iPhone Full kbmMW support (client and server)

The Delphi Starter Edition now also has the For kbmMemtable now available: full XE2
ability to do multi tier development for no cost support (32 / 64 / osx)
at all.
Pro/Ent is available for Win32/Win64/OSX/FPC. For kbmMW there are multiple new items:
The CodeGear Edition is for Delphi XE2 / Win32 Remote Desktop Client/Server/Proxy
only and provides access to SQLite in addition Support, NEW JSON support, JSON
to the standard Delphi Starter Edition database streaming of kbmMemTable datasets,
connectivity frameworks, BDE and IBExpress. bugfixes and more.
Improved HTML template support,
Delphi Starter Edition also lacks proper XML improved Cookie Support etc. Lots of
support and the local TClientDataset, which is improvements related to using kbmMW as a
also to be found as part of kbmMW Code web server producing dynamic
Gear Edition in the form of TkbmMWDOMXML web pages. kbmMemTable on Win64.
and the high performance TkbmMemTable.
In addition its possible to upgrade to kbmMem Tests done:
Table Standard Edition for only US$30. 10 million records in memory
The upgrade includes full source for kbmMem with multiple fields and indexes...
Table, and includes kbmSQL which provides a
SQL frontend to kbmMemTable.

COMPONENTS
DEVELOPERS 4
ESB, 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.