Friday, October 2, 2009

Reasons to Migrate from Delphi 7 to Delphi 2009 By Andreano Lanusse

Many Delphi 7 users wonder whether they’ll find compelling reasons to migrate to Delphi 2009.

Here they are: a plethora of new features allied to unparalleled developer productivity, all aimed at your ability to create higher-quality applications with improved performance. Thisarticle gives a few good reasons to migrate, along with an overview of all the new featuresadded to Delphi since version 7.



We’ve changed the IDE in many different ways in order to make development faster and easier.

The project compilation options are now displayed in columns and grouped by categories in afriendly manner. It’s also now possible to save your project’s configuration options, or build configurations, as you’ll see in Figure 1.

Compiling and debugging projects are regular tasks for developers. However, the projectoptions that are used to run the final version (release) are not always the same project optionsyou use when debugging. Having to constantly change your project’s options is a time consumingtask that you can now avoid, never again being forced to spend lots of time workingwith the Project Manager. In Delphi 2009 the build configuration options are seamlesslyintegrated to the Project Manager.

In addition, project configurations can be saved in XML-format OPTSET files. Working withthese files you're able to reuse project options from previous projects, no longer having to setthem each time a new project is started.

The Component Creation and Import Wizards have been redesigned to include type libraries,ActiveX controls and assemblies. Both wizards can now install into an existing package or in anew package.

As you see in Figure 2, a new field was added to filter components, making it easier for you to locate the component you want to inherit.

COM wizards and the entire type library have been restructured. In fact, the COM Object Creation Wizards are all brand new.

What has changed? A new file type - RIDL (Restricted Interface Definition Language) – was
added to the COM architecture. RIDL files work as recording devices projects use to save typelibraries. Therefore, the tlb binary file becomes an intermediary file, like dcu, res, obj, and so on.

This means developers are now able to recompile tlb files using the command line prompt, andeven edit a tlb file using a text editor, while still keeping track of its version.

The type library now uses a text file (the RIDL file), not TLB. This is beneficial because:
• You no longer need to check the tlb file in. It’s now automatically generated based on thelast ridl
• Different developers can work with the same type library. This is so because the text file can now be merged, something that couldn’t be done with the binary file used previously
• The RIDL format provides the Type Library editor with much higher flexibility
• You can easily compare different RIDL files

The Resource Compiler allows you to choose between compiling your resources with
BRCC32.exe or RC.exe (Microsoft Platform SDK resource compiler). RC supports the use ofUnicode characters in resource files and file names. It also supports the new Windows Vistatypes (e.g., icons and alpha channel). When you use RC you must define #include explicitly both for Delphi and C++. 
The New Resource Manager allows you to add many resource files (bitmaps, icons, fonts…) toyour project. 

The Class Explorer is a very useful tool that enables you to visualize a project’s class hierarchyand its interfaces, as well as add properties, methods and variables to it. These operations canbe performed by means of UML, through the use of class models. UML is one of the manyresources that were incorporated to Delphi.

In Delphi 2006 you could filter components typing the first couple of letters of their names in the Tool Palette. 

In Delphi 2007 this feature was enhanced and you were then able to type in any portion of the component name. In Delphi 2009 an Edit field is used to achieve the same result, making this feature clearer and easy to recognize at first glance.

Users who prefer Delphi 7’s layout (i.e., components displayed at the upper portion of the IDE) will be glad to know Delphi 2009’s IDE can look just like Delphi 7’s, except for the component bar.
However, before switching to the old Delphi 7 layout, give the Tool Palette new version a try.

Locating components with ease, the orderly arrangement of categories, etc., can provide great productivity gains.

CODE EDITORThe new Live Templates feature extends your ability to create code templates in Delphi. Theseare created as XML files, and help you program with less code.

Block completion is one of the resources involved in enabling automatic begin and end. Andwho can honestly say he’s never had a hard time with begin..end?

Consider this context: you want to change the name of all variables in a selected part of thecode. Find..Replace is not a good practice for this situation. It doesn’t guarantee only variablenames will be changed in the process. Since Delphi 8 you can use Sync Edit to edit differentportions of code simultaneously, provided they share the same identifier. Taking the code
below as an example, you could select the entire block, make sure sync edit is active and thenchange the “Comm” variable a single time. 

Alongside the code block you see yellow and green marks. The yellow ones are shown for linesthat have changed since the last Save. Green marks, in turn, indicate lines that were recentlychanged and saved.
You also see the smart code line numbering. And you’re able to either expand or collapse amethod or a class right within the block.

Think about a unit with tens of methods. You hope one day you’ll have enough time to stop andset it in order, but never really find time to do so. The code above holds a region called“Methods for enabling/blocking user access”. This region has two methods for either enablingor blocking users. You can’t see those methods, unless their region is expanded. A questionremains: wouldn’t it be easier to organize and visualize the code with the assistance of suchfeatures?

Help from within the code (Help Insight): Press F1 in order to see the documentation of amethod, type, class, etc. As you can see, the code above displays the CreateCommand methodhelp info. The same thing happens with any method, type or class, provided it has a descriptionavailable.

Find references for a method, class, variable, or any other specific item. Imagine your codeholds a class named TCGC, which you want to rename to TCNPJ. Assuming you’re a carefuldeveloper, tell me where the TCGC class is referenced in the project. Find..Replace won’t workthis time. Instead, try pressing Shift + CTRL + Enter over class TCGC. The IDE then looks for allreferences in the project, as seen below.

If you’re now wondering how to rename all classes to TCNPJ, wait until we discuss Refactorings.
Another useful feature is named Surround. It works basically by allowing you to add begin/end,
if/begin/end, try/finally, try/except, etc., to a block of code.

Files are locally versioned whenever they’re changed, even in the absence of version control,
thus allowing you to make comparisons between them.

Delphi 7 users will surely love to try this resource. Refactoring is a technique you can use to
restructure and modify your existing code in such a way that the intended behavior of your code
stays the same. Refactoring allows you to streamline, simplify, and improve both performance
and readability of your application code.

Delphi includes a refactoring engine that evaluates and executes the refactoring operation. The
engine also displays a preview of the changes that will occur in a refactoring pane that appears
at the bottom of the Code Editor. The potential refactoring operations are displayed as tree
nodes, which can be expanded to show additional items that might be affected by the
refactoring, if they exist. Warnings and errors also appear in this pane. You can access the
refactoring tools from the Main menu and from context-sensitive drop down menus.

Delphi integrates an open-source testing framework, DUnit, for developing and running
automated test cases for your applications. This framework simplifies the process of developing
tests for classes and methods in your application. Using unit testing in combination with
refactoring can improve your application’s stability. Running a standard set of tests every time a
small change is made throughout the code makes it more likely that you will catch any problems
early in the development cycle.

It’s now easier to retrieve data from databases.

Using the Data Explorer along with drag-and-drop capabilities you can access tables, views, stored
procedures and other database items. Besides that, you can also search for data using SQL.
Connections are established through dbExpress. This means Data Explorer supports every database
dbExpress supports.

Each connection is assigned an alias which is saved in the dbxconnections.ini file (dbExpress’
configuration file). Aliases are treated as shared information, thus facilitating the use of Data

The Data Explorer allows developers to easily build complex SQL queries via an intuitive visual
query building interface.

The debugger now comes with the “Thread View and Wait Chain Traversal” feature, available
only for Windows Vista. This resource helps you locate deadlocks and thread contentions.

During the debug process you need to visualize the content of variables. The Watch List comes
in handy for that, but the higher the number of items added the more confusing the
visualization gets. Developers can now group Watch List variables based on custom names.

Custom variable groups are then represented as tabs in the Watch List.
After the debug is finished, all units that are opened during the process are automatically
closed; only units that remain open are the ones that were open before the debug process was

There are a lot of improvements with the visualization and usability of local variable window, call
stack and others. There is also a new tree view for the content of objects that are being
debugged, shown in Figure 11:

Since Delphi 7, the VCL and RTL have been continuously enhanced. Besides complete support
to Windows Vista and Unicode, new components have been added and existing components
have been improved by the addition of new functionalities.
All these add up to better component usability, easy creation of rich interfaces and the ability to
use Windows Vista's new functionalities. In this section, we focus on what’s new in existing
components and the changes in RTL classes.

Applications compiled in Delphi 2007 (or later) are 100% compatible with Windows Vista. The
VCL has been updated to support the new characteristics of this OS, while new components
were also added: TFileOpenDialog, TFileSaveDialog and TTaskDialog.

New classes have also been created; for instance:
• TCustomFileDialog • TFileTypeItems
• TCustomFileOpenDialog • TTaskDialogBaseButtonItem
• TCustomFileSaveDialog • TTaskDialogButtonItem
• TCustomTaskDialog • TTaskDialogButtons
• TFavoriteLinkItem • TTaskDialogButtonsEnumerator
• TFavoriteLinkItems • TTaskDialogProgressBar
• TFavoriteLinkItemsEnumerator • TTaskDialogRadioButtonItem
• TFileTypeItem

Dialog box components are now displayed in a Vista-like fashion. You are now probably
wondering what happens to applications when you run them on Windows XP. There’s no reason
to be concerned about it. VCL recognizes the OS, using its specific resources and the
appropriate interface.

The TaskMessageDlg function was designed to support Windows Vista. It has the same
functionality seen in MessageDlg, with additional parameters that support Windows Vista’s
characteristics. When you run your application on Windows XP, MessageDlg is automatically
executed. VCL is there to ensure it.

The UseLatestCommonDialogs global variable defines that all dialog components
(TOpenDialog, TSaveDialog, TOpenPictureDialog and TSavePictureDialog) should follow
Windows Vista’s design whenever it receives a TRUE statement.

The units below were enhanced to support Window’s new APIs.
• UxThemes – new
• DwnApi – new
• ActiveX – updated
• Windows – updated
• Messages – updated
• CommCtrl – updated
• ShlObj - updated

New properties - DisabledImages, LargeImages and LargeDisabledImages - that allow you to
define large and disabled images, based on the TImageList component.

The Image component supports the PNG format natively.

Support to 32-bit alpha bitmaps, along with the addition of the AlphaFormat property.

This component allows you to group many different buttons in a panel.

Windows Vista now has two new button styles, both supported by Delphi with its TButton class.

CommandLink has a different, friendlier design. You can use it to add a more detailed description of the
button functionality.

SplitButton opens a list of options when clicked. This list is presented as a PopMenu. You can also assign
images to the items.

TListView now allows you to define basic and advanced groups. The advanced group support
enables deeper customization of groups (requires Vista), allowing you to define images for each
of them.

TTreeView allows enabling/disabling nodes and images for expanded items.

The new TButtonEdit component allows you to add images within the Edit field. Images can be
placed either at the right or left side. You can also use events to control image clicking – by
means of the onLeftClick and onRightClick events.

Hints now come in Windows Vista style and allow the addition of titles, descriptions and images,
which will make your user notifications much friendlier.

This new component is very useful. It works like an Outlook bar, to which you can add many different panels. Each of these panels can contain any VCL component. You can define a title,  an image, the alignment and an icon for each of the panels, being able to expand and collapse them.

LinkLabel allows you to add HTML tags that affect the appearance of the component.

Now supports ActionBar styles.

New checkbox support.

The traditional TPanel is a visual container for other components. Within TPanel you are able to accommodate visual controls wherever you want. In other words, it works with absolute
positioning (the Top and Left coordinates of the control refer to the panel’s upper left corner).

Inspired by similar Java concepts (namely, the Layout Manager, which defines how controls are
distributed within the container) we can say we now have three kinds of layout managers:
• TPaneTPanel : absolute type, or XY. Components are placed in fixed, precise positions.
• TFlowPanel : components are placed in a sequence, according to a given order (similar
to an HTML page, neither using tables nor CSS stylesheets).

− The flow is determined by the FlowStyle property, which accepts the options you see
below. In order to understand the naming convention, keep in mind that components
are accommodated according to the direction defined by the first pair (e.g., LeftRight).
When there’s no space left in the panel, the direction is redefined by the second pair
(e.g., TopBottom):
 fsLeftRightTopBottom: left to right, top down (default)
 fsRightLeftTopBottom: right to left, top down
 fsLeftRightBottomTop: left to right, bottom up
 fsRightLeftBottomTop: right to left, bottom up
 fsTopBottomLeftRight: top down, left to right
 fsBottomTopLeftRight: bottom up, left to right
 fsTopBottomRightLeft: top down, right to left
 fsBottomTopRightLeft: bottom up, right to left

− Another relevant property is AutoWrap. When True, indicates the flow will be “broken”
towards the other direction in case the panel runs out of space. When False,
components outside the boundaries of the panel will not be visible.

− You can use this panel to automatically generate forms, with fields being dynamically
defined either in a database or a file. This way you do not need to be concerned about
positioning each of the fields.

• TGridPaneTGridPanel : the panel is partitioned by lines and columns, with each of the resulting
cells holding a component (similar to the use of HTML tables).
− Components are arranged according to the order of the lines (top down) and, within
each line, column-wise (left to right).
− The number of lines is determined by the RowCollection property, which can contain
various objects of the TRowItem class. Each item has two properties:
 SizeStyle: determines the standard by which line height is specified in the Value
• ssAbsolute: number of pixels
• ssAuto: the number is disregarded, with line height being automatically
• ssPercent: percentage in comparison to the panel height
 Value: a number expressing the height, according to the SizeStyle property.
− Similarly, the number of column is determined by the ColumnCollection property, which
contains objects of the TColumnItem class. TColumnItem has the same properties
TRowItem does, differing only in that they relate to the column width, not the row's.
− The ExpandStyle property determines an action for whenever someone tries to add a
component into a panel that is out of free cells. Its possible values are:
 emAddRows: a new line is added to the panel to accommodate the components
 emAddColumns: new columns are added to accommodate the components
 emFixedSize: an exception is raised when there’s no more free space to
accommodate new components.

This component allows you to create buttons and group them into categories, similar to what's seen in an Outlook bar. It helps you refine the design of your applications.

Think of those icons you see beside the taskbar clock, in the Windows tray. What if you could
place your application right there too? It’s now more than simple to do so. All you have to do is
place a TTrayIcon component (Win32 tab) in the main form. Set just a few properties and you’re
• Icon: Stores the icon that is displayed in the tray. You can use your application’s icon or an icon that describes a status or situation. This icon can be changed at anytime.
• Icons: references a TImageList containing a bunch of bitmaps or icons which will be used in the animation.
• Animate: When True, keeps swapping the icons in the Icons list. The index of the icon that
is being currently displayed can be either retrieved or changed using the IconIndex property.
• AnimateInterval: millisecond interval of the icon swapping process. The OnAnimate event
is generated after each iteration, allowing you to define an action to be taken.
• BalloonTitle and BalloonHint: Title and text for the balloon, displayed by the
ShowBalloonHint method. The balloon can be closed by a simple click (either on it or over
the dialog’s X). However, it goes away automatically after the interval predefined in the
BalloonTimeout property (milliseconds).
• PopupMenu: it’s common to associate a popup menu to the application’s icon; enabling
users to quickly access the most commonly used commands. All it takes for you to do so is
reference the menu in this property. To access it, left-click the icon.

You can hide the main form (using methods Hide or Visible := False) without halting the
application. In this case it’s essential to provide the tray icon with a menu or event
(OnMouseClick, for instance) to ensure the control is passed back to you right after.

IntelliMouse is how we refer to support for mouse-wheel scrolling in your application. Support
for this technology was first introduced to VCL in Delphi 2006. In order to use it, simply declare
the IMOUSE unit in your application.

The father of all components in Delphi has also been enhanced:
• New methods
− class function UnitName : string
− function Equals(Obj : TObject) : Boolean;virtual
− function GetHashcode : Integer; virtual
− function ToString ; String;virtual
• A few additional Overloads for the following methods:
− MethodAddress
− FieldAddress
• The type of return of the functions below has changed from ShortString to String in order to
support Unicode
− ClassName
− MethodName
Other components - TPanel, TProgressBar, TTrayIcon, TScreen, and TRadioGroup – also
provide a lot of improvements.

Many RTL functions have been updated to improve the application performance. FASTMM is the most relevant of such improvements. A new memory manager aimed at Win32 applications, FASTMM enables applications to have better performance by performing the compilation in Delphi 2006, and identifies memory leaks just declaring ReportMemoryLikeonShutdown := True.

It can’t be overemphasized that simply by compiling your applications in Delphi 2006 or later,
you experience performance gains, while also being able to detect memory leakages.
Three seems to be a magic number these days… Besides three new visual components, the
VCL has also been improved with three additional classes:
• TMargins
• TPadding
• TCustomTransparentControl
The TControl class now has an additional property (Margins, of
TMargins class). TMargins is used in the Margins property of
TControl and its descendants. TMargins helps define the relative
position between components on a form, and between the edges
of the form and the component. For example, when you set the
left margin for a component to 10 pixels, the component will not
come closer than 10 pixels to the edge of the container or to
another component on the left edge. The number of pixels by
which two components are separated is the sum of the pixels of
both components.
The TWinControl class adds an extra property – Padding, of
TPadding class: a TMargins descendent.
Padding adds space along the edge the control. Child controls
that are aligned to the parent are positioned inside the control
according to this spacing. Padding does not affect child controls
which are not aligned to the parent control, nor does it affect the
size of the ClientArea.
Padding is the opposite of Margins. Margins affects the
positioning of the control itself inside the parent control, but
Padding affects how all aligned child controls are positioned with
respect to the parent control.
FigurFigure 22 Margins and

The new TCustomTransparentControl class can be used for components that need to be there
while pretending they’re not. Uh oh. Well... think of it as the glass of a window or door. You
know it’s there, although you’re unable to visually perceive it. To see the difference, you can do
this test: create a new VCL application (File | New | VCL Forms Application – Delphi for Win32).
Place two TButtons and two TLabels in it, see Figure 22.

Set both buttons' Top property to 40; Button 1 and 2’s Left properties to 30 and 210,
respectively. When you’re done, type the code as below. Note that the form implements the
events OnCreate, OnDestroy and OnClick, with both buttons sharing the same OnClick event.

I’ve created a TCustomTransparentControl descendent – TTransparentControl – and a
TCustomControl descendent - TOpaqueControl. They are dynamically created by the form’s
OnCreate event, being positioned right above the other existing controls. I’ve also added an
OnClick event to our customized controls for you to observe their behavior. The result can be
seen in Figure 24.

TTransparentControl = class(TCustomTransparentControl)
procedure Paint; override;
TOpaqueControl = class(TCustomControl)
procedure Paint; override;

TfCustomTransparentControl = class(TForm)
Button1: TButton;
Button2: TButton;
Label1: TLabel;
Label2: TLabel;
procedure Button1Click(Sender: TObject);
procedure FormClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
InvCon : TTransparentControl;
VisCon : TOpaqueControl;
procedure ControlClick(Sender: TObject);
fCustomTransparentControl: TfCustomTransparentControl;
{$R *.dfm}
{ TTransparentControl }
procedure TTransparentControl.Paint;
const txt = 'Transparent';
Canvas.TextOut((Width - Canvas.TextWidth(txt)) div 2, Height div 2, txt);
{ TOpaqueControl }
procedure TOpaqueControl.Paint;
const txt = 'Opaque';
Canvas.TextOut((Width - Canvas.TextWidth(txt)) div 2, Height div 2, txt);
{ Form }
procedure TfCustomTransparentControl.FormCreate(Sender: TObject);
InvCon := TTransparentControl.Create(Self);
InvCon.Parent := Self;
InvCon.OnClick := ControlClick;
VisCon := TOpaqueControl.Create(Self);
VisCon.Parent := Self;
VisCon.OnClick := ControlClick;
procedure TfCustomTransparentControl.FormDestroy(Sender: TObject);
Reasons to Migrate to from Delphi 7 to Delphi 2009
Embarcadero Technologies - 24 -
procedure TfCustomTransparentControl.Button1Click(Sender: TObject);
ShowMessage('You have clicked on ' + (Sender as TButton).Caption);
procedure TfCustomTransparentControl.ControlClick(Sender: TObject);
ShowMessage('You have clicked on control ' + (Sender as
procedure TfCustomTransparentControl.FormClick(Sender: TObject);
ShowMessage('Form clicked!');
Most of you already know about the new Ribbon interface (used in Office 2007). Such interfaces
are designed to facilitate user access to your application’s menu options.

The VCL now comes with Ribbon Controls, a group of components that allows you to create
Ribbon-style Delphi interfaces.
Ribbon Controls integrate with Action Manager, which means that applications with Actions
and the traditional menus can be easily migrated to Ribbon.
The architecture behind Ribbon Controls is very simple. From a Ribbon control you are able to
add a Tab (which contains groups). Each of these groups contains buttons with customized
appearance. Additionally, the Ribbon control includes the Quick Access Toolbar and the
Application Menu.

One of the greatest challenges faced by our R&D team was incorporating Unicode support
throughout the entire VCL – and then the IDE – because Delphi is developed in Delphi.

Throughout this version’s development process we’ve had meetings with a number of
component development companies. Allen Bauer, our chief scientist for Delphi, posted
comments on the Unicode support in his blog. Initiatives like those proved essential in allowing
third-party components to be available to Delphi 2009 quickly, as well as in keeping developers
updated about how to work with Unicode.

Unicode is a standard that allows computers to consistently represent and handle text from any
existing system of writing.
- The Unicode Standard: Version 5.0. 5. ed. Addison-Wesley Professional, 2006. 1472 p

Many character sets – like Chinese, Japanese, and Russian, along with others of Asian
background – are represented by means of Unicode. The most commonly used encodings are
UTF (Unicode Transform Format) and UCS (Universal Character Set). To learn more about
Unicode, visit:

The result of all this is a Delphi that is 100% Unicode.. You’re now probably wondering if the
migration is that easy. Definitely yes, many things are handled by the VCL and the compiler.
One of the most relevant changes in this version is that String types are now based on
UNICODE. Previously based on the ANSI standard, the AnsiString and WideString types still
work the same way, except regarding their data size in bytes.

Unicode changes, in short:
• String maps UnicodeString, no longer AnsiString
• Char now maps WideChar (2 bytes, not 1 byte) being a UTF-16 character
• PChar maps PWideChar
• AnsiString maps the old String type

No changes were applied to:
• AnsiString
• WideString
• AnsiChar, PAnsiChar
• Short String contains AnsiChar elements
• Implicit conversions still work.
• The user's active code page controls the mode (ANSI vs. Unicode), so that ANSI strings are
still supported.

Operations that do not depend on character size:
• String concatenation
• Standard String functions. E.g., Length, Copy, Pos, and so on.
• Operators. E.g., < comparison> , CompareStr(), CompareText(), etc.
• FillChar ( )
• Windows API

Operations involving the character size (measured in bytes) may require a few changes. Nothing
too complicated, but here’s a tip: pay special attention to code in which you:
1. Assume Sizeof (Char) is 1.
2. Assume the size of a string equals the number of bytes in the string.
3. Handle String or PChars directly.
4. Saves or reads a string from/to a file.

Items 1 and 2 do not apply to Unicode, because in Unicode the Sizeof (Char) is 2 bytes and the
size of a string is twice as big as the number of bytes. Besides, the code that reads and saves
files must understand the right number of bytes to perform those operations, for a character is
no longer represented as 1 byte.

As you can see, migrating is very easy. The benefit of having Unicode support is that of allowing
Delphi developers to distribute their applications worldwide. Brazil is currently one of the most
relevant software developers in the global market. Many Brazilian companies distribute their
applications to China, Japan, Russia and other countries where Unicode is crucial.

In 2007, the Russian government acquired 1 million Delphi licenses to be used in teaching
primary and high school students to develop software with Delphi. Therefore, Unicode support
is vital for that country.

The Delphi compiler allows functions and procedures to be tagged with the inline directive to
improve performance. If the function or procedure meets certain criteria, the compiler will insert
code directly, rather than generating a call. Inlining is a performance optimization that can result
in faster code, but at the expense of space. Inlining always causes the compiler to produce a
larger binary file. The inline directive is used in function and procedure declarations and
definitions, like other directives.
program InlineDemo;
function Max(const X,Y,Z: Integer): Integer;inline
if X > Y then
if X > Z then Result := X
else Result := Z
if Y > Z then Result := Y
Reasons to Migrate to from Delphi 7 to Delphi 2009
Embarcadero Technologies - 28 -
else Result := Z
Times = 10000000; // 10 million
A,B,C,D: Integer;
Start: LongInt;
i: Integer;
Random; // 0
A := Random(4242);
B := Random(4242);
C := Random(4242);
Start := TimeGetTime;
for i:=1 to Times do
D := Max(A,B,C);
Start := TimeGetTime-Start;
writeln(A,', ',B,', ',C,': ',D);
writeln('Calling Max ',Times,' times took ',Start,' milliseconds.');

When the above code is executed, the Max method is called 10 million times. The numbers
below vary depending on your machine. Using a Pentium M 1.8GHz with 2GB RAM we’ve
obtained the following results:

With inlinWith inline Without inline 25 milliseconds 68 milliseconds

The inline directive is a suggestion to the compiler. There is no guarantee the compiler will
inline a particular routine, as there are a number of circumstances where inlining cannot be
done. The following list shows the conditions under which inlining does or does not occur:
• Inlining will not occur on any form of late-bound method. This includes virtual, dynamic, and
message methods.
• Routines containing assembly code will not be inlined.
• Constructors and destructors will not be inlined.
• The main program block, unit initialization, and unit finalization blocks cannot be inlined.
• Routines that are not defined before use cannot be inlined.
• Routines that take open array parameters cannot be inlined.
• Code can be inlined within packages, however, inlining never occurs across package
• No inlining will be done between units that are circularly dependent. This included indirect
circular dependencies, for example, unit A uses unit B, and unit B uses unit C which in turn
uses unit A. In this example, when compiling unit A, no code from unit B or unit C will be
inlined in unit A.
• The compiler can inline code when a unit is in a circular dependency, as long as the code to
be inlined comes from a unit outside the circular relationship. In the above example, if unit A

also used unit D, code from unit D could be inlined in A, since it is not involved in the
circular dependency.
• If a routine is defined in the interface section and it accesses symbols defined in the
implementation section, that routine cannot be inlined.
• If a routine marked with inline uses external symbols from other units, all of those units must
be listed in the uses statement, otherwise the routine cannot be inlined.
• Procedures and functions used in conditional expressions in while-do and repeat-until
statements cannot be expanded inline.
• Within a unit, the body for an inline function should be defined before calls to the function
are made. Otherwise, the body of the function, which is not known to the compiler when it
reaches the call site, cannot be expanded inline.

If you modify the implementation of an inlined routine, you will cause all units that use that
function to be recompiled. This is different from traditional rebuild rules, where rebuilds were
triggered only by changes in the interface section of a unit.

Delphi allows certain functions, or "operators" to be overloaded within record declarations. The
name of the operator function maps to a symbolic representation in source code. For example,
the Add operator maps to the + symbol. The compiler generates a call to the appropriate
overload, matching the context (i.e. the return type, and type of parameters used in the call), to
the signature of the operator function. The following table shows the Delphi operators that can
be overloaded:
TMyClass = class
class operator Adicionar(a, b: TMyClass): TMyClass; // Add two classes
of TMyClass type
class operator Subtrair(a, b: TMyClass): TMyclass; // Subtraction of
the TMyClass type
class operator Implicit(a: Integer): TMyClass; // Implicit
converstion from integer to the class of TMyClass type
class operator Implicit(a: TMyClass): Integer; // Implicit
conversion from the TmyClass class into an integer
class operator Explicit(a: Double): TMyClass; // Explicit
conversion from a Double to a TMyClass class
// Method implementation example. Add
class operator TMyClass.Add(a, b: TMyClass): TMyClass;
// ...
x, y: TMyClass;
x := 12; // Implicit conversion of an Integer, executes the Implicit
y := x + x; // Executes TMyClass.Add(a, b: TMyClass): TMyClass
b := b + 100; // Executes TMyClass.Add(b, TMyClass.Implicit(100))
Reasons to Migrate to from Delphi 7 to Delphi 2009
Embarcadero Technologies - 30 -

No operators other than those listed in the table may be defined on a class or record.
Overloaded operator methods cannot be referred to by name in source code. To access a
specific operator method of a specific class or record, you must use explicit typecasts on all of
the operands. Operator identifiers are not included in the class or record's list of members.

No assumptions are made regarding the distributive or commutative properties of the
operation. For binary operators, the first parameter is always the left operand, and the second
parameter is always the right operand. Association is assumed to be left-to-right in the absence
of explicit parentheses.

Resolution of operator methods is done over the union of accessible operators of the types
used in the operation (note this includes inherited operators). For an operation involving two
different types A and B, if type A has an implicit conversion to B, and B has an implicit
conversion to A, an ambiguity will occur. Implicit conversions should be provided only where
absolutely necessary, and reflexivity should be avoided. It is best to let type B implicitly convert
itself to type A, and let type A have no knowledge of type B (or vice versa).

As a general rule, operators should not modify their operands. Instead, return a new value,
constructed by performing the operation on the parameters.
Overloaded operators are used most often in records (i.e. value types).

A class helper is a type that - when associated with another class - introduces additional method
names and properties which may be used in the context of the associated class (or its
descendants). Class helpers are a way to extend a class without using inheritance. A class helper
simply introduces a wider scope for the compiler to use when resolving identifiers. When you
declare a class helper, you state the helper name, and the name of the class you are going to
extend with the helper. You can use the class helper any place where you can legally use the
extended class. The compiler's resolution scope then becomes the original class, plus the class

Class helpers provide a way to extend a class, but they should not be viewed as a design tool to
be used when developing new code. They should be used solely for their intended purpose,
which is language and platform RTL binding. You can see an example below.

TMyClass = class
procedure MyProc;
function MyFunc: Integer;
procedure TMyClass.MyProc;
var X: Integer;
X := MyFunc;
Reasons to Migrate to from Delphi 7 to Delphi 2009
Embarcadero Technologies - 31 -
function TMyClass.MyFunc: Integer;

TMyClassHelper = class helper for TMyClass
procedure HelloWorld;
function MyFunc: Integer;
procedure TMyClassHelper.HelloWorld;
writeln(Self.ClassName); // Self refers to the TMyClass class, not to
function TMyClassHelper.MyFunc: Integer;
X: TMyClass;
X := TMyClass.Create;
X.MyProc; // Executes TMyClass.MyProc
X.HelloWorld; // Executes TMyClassHelper.HelloWorld
X.MyFunc; // Executes TMyClassHelper.MyFunc

Note that the reference is always pointed to TMyClass. The compiler recognizes when it’s
appropriate to execute the call in TMyClassHelper.

In Delphi, you have two options for determining the visibility of a class’ attributes: strict private
and strict protected.
• Strict privatStrict private: class attributes are visible only within the class in which it is declared. Those
attributes can’t be seen by methods declared in the same unit, or by those that are not part
of the class.
• Strict protected: determines that class attributes and their descendents are visible.

Record data types in Delphi represent a mixed set of elements. Each element is called a field
and the declaration of a record type specifies a name and type for each field.
Records in Delphi 2006 are even more powerful, bringing features supported only in class.

• Here's a list of the new record features in Delphi 2006 Constructors
• Operator overload
• Non-virtual methods declaration
• Static methods and properties

The following example is the implementation of a record with the new characteristics:
TMyRecord = Record
TColorType = Integer;
pRed : Integer;
Class Var
Blue : Integer;
Procedure printRed();
Constructor Create(Val : Integer);
Property Red : TColorType Read pRed Write pRed;
Class Property pBlue : TColorType Read Blue Write Blue;
Constructor TMyRecord.Create(Val: Integer);
Red := Val;
Procedure TMyRecord.printRed;
WriteLn('Red: ', Red);

Now the record can use many of the functionalities that were exclusive to classes. However,
records are not classes, meaning they still have many differences:
• Records do not support inheritance.
• Records may have variable parts; classes may not.
• Records are data types and, as so, can be copied. Classes cannot.
• Records have no destructors.
• Records do not support virtual methods.

There are many ways for you to declare classes, types, variables and properties.
• Class abstract  defines an abstract class
• Class sealed  classes cannot be extended through inheritance - such a class cannot be
used as a base class for some other (derived) class
• Class const  defines a class constant that can be accessed without having to instantiate
the class
• Class type  defines a class type that can be accessed without having to instantiate the
• Class var  defines a variable from the scope of the class which you can access without
having to instantiate the class
• Class property  grants access to the property without requiring the class to be instantiated

Nested types are used throughout object-oriented programming in general. They allow you to
keep conceptually related types together, and to avoid name collisions. The same syntax for
declaring nested types may be used with the Delphi compiler. Class sample below:
TOuterClass = class
strict private
myField: Integer;
TInnerClass = class
myInnerField: Integer;
procedure innerProc;
procedure outerProc;
This is how the method is implemented:
procedure TOuterClass.TInnerClass.innerProc;
To access the method within the Nested class, see the next example:
x: TOuterClass;
y: TOuterClass.TInnerClass;
x := TOuterClass.Create;
y := TOuterClass.TInnerClass.Create;

The Delphi compiler also supports the concept of a final virtual method. When the keyword final
is applied to a virtual method, no descendent class can override that method. Use of the final
keyword is an important design decision that can help document how the class is intended to
be used. It can also give the compiler hints that allow it to optimize the code it produces.

When these classes are declared as Static they do not need to be instantiated.
Delphi 2007 brought support for element-in-collection (collections, arrays, string expressions
and set-type expressions) style iteration over containers.

Example: Iteration in an Array
IArray1: array[0..9] of Integer = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
I: Integer;
for I in IArray1 do
// do something here...

Example: Iteration in a String
C: Char;
S1, S2: String;
OS1, OS2: ShortString;
AC: AnsiChar;
S1 := ’New resources in Delphi 2009';
S2 := '';
for C in S1 do
S2 := S2 + C;
if S1 = S2 then
WriteLn('SUCCESS #1');
WriteLn('FAIL #1');
OS1 := 'Migrating from Delphi 7 to Delphi 2009...';
OS2 := '';
for AC in OS1 do
OS2 := OS2 + AC;
if OS1 = OS2 then
WriteLn('SUCCESS #2');
WriteLn('FAIL #2');

Delphi 2009 supports generics, which were previously available only for Delphi .Net.

What are generics? ‘Generics’ is the defining term for generic types. It is a resource that allows you to predefine any type of data from arrays, collections, and other sorts of lists. Write code in a generic way and have it work with a specific type of data - classes or class methods. It’s also possible to define types at runtime.

While working with Collections (data collection) you most often use some of the classes listed
• ArrayList
• HashTable
• Queue
• SortedList
• Stack

Items added to these classes are of TObject type, meaning you can only add a single type to
the list. Whenever you need to read the items you must perform the type cast for each of them,
leaving all processing for the compiler. This is nothing but additional effort for your application,
or something that can potentially impact its performance.

A relevant portion of our code can be adapted to work with generics. Below you see a sample
class whose Key property should be a String and whose Value property should be an Integer. In
this case you do not use Generics.

TSIPair = class
FKey: String;
FValue: Integer;
function GetKey: String;
procedure SetKey(Key: String);
function GetValue: Integer;
procedure SetValue(Value: Integer);
property Key: TKey read GetKey write SetKey;
property Value: TValue read GetValue write SetValue;

Using generics it’s possible to define the Key and Value properties as being of any type. This is
how you do so:
TPair= class // declares the TPair type with 2 parameters
FKey: TKey;
FValue: TValue;
function GetKey: TKey;
procedure SetKey(Key: TKey);
function GetValue: TValue;
procedure SetValue(Value: TValue);
property Key: TKey read GetKey write SetKey;
property Value: TValue read GetValue write SetValue;
You can now use this class in many different ways:
TSIPair = TPair; // declares it with types String and
TSSPair = TPair; // declares it with other types
TISPair = TPair;
TIIPair = TPair;

You’ll find many uses for generics. Examples are provided here as a simple, limited reference.

As the name suggests, an anonymous method is a procedure or function that does not have a name associated with it. An anonymous method treats a block of code as an entity that can be assigned to a variable or used as a parameter to a method. In addition, an anonymous method can refer to variables and bind values to the variables in the context in which the method is defined. Anonymous methods can be defined and used with simple syntax. They are similar to the construct of closures defined in other languages.

function MakeAdder(y: Integer): TFuncOfInt;
Result := { START anonymous method } function(x: Integer)
Result := x + y;
end; { END anonymous method }

The MakeAdder function returns a nameless function; that is, an Anonymous Method.
Note that MakeAdder returns a value of TFuncOfInt type. The type of the Anonymous Method
is declared as a reference to the method.

Example: Executing the MakeAdder function
adder: TFuncOfInt;
adder := MakeAdder(20);
Writeln(adder(22)); // prints 42
TFuncOfInt = reference to function(x: Integer): Integer;
The above statement indicates this Anonymous Method:
• Is a function
• Receives an Integer value
• Returns an Integer value
You can declare both procedures and functions as Anonymous Methods.
TSimpleProcedure = reference to procedure;
TSimpleFunction = reference to function(x: string): Integer;
Anonymous Methods offer much more than just a simple execution point in code:
• Binding in variables
• Ease to use and define methods
• Ease to parameterize the code

The $POINTERMATH directive enables mathematic operations with pointers.
When you compile your application with Delphi 2009, a couple of new warnings might appear in
your IDE’s message window. These messages regard the use of the new UnicodeString type.

One of the most significant changes in Delphi 2007, dbExpress architecture has been
restructured, and you can now count on a framework that is totally written in Delphi. We have
performed lab tests to simulate the most diverse situations with varied databases; in some of
those tests the performance was improved by 100%.

DbExpress 4 is also a milestone for applications developed in Delphi that require database connectivity. The new architecture was designed to support Win32 and .NET, enabling the same drivers to be used in both platforms.

Remember that applications developed in prior versions are 100% compatible with Delphi 2009.

The dbExpress Framework comes with a new group of classes that facilitate the task of
accessing and otherwise handling databases. Now you can find all the information regarding
the database within the framework. Previously you’d have to use components SQLConnection,
SQLDataSet, SQLQuery, and others instead.

The following example represents a console application that uses database connection
resources, reads connections parameters, sends a query and displays its result – all in a single

program DBX4Example;
aConnName: string;
aDBXConn: TDBXConnection;
aDBXTrans : TDBXTransaction;
aCmnd: TDBXCommand;
aReader: TDBXReader;
i, aColCount: integer;
aDBXConn := TDBXConnectionFactory.GetConnectionFactory.GetConnection(
'EMPLOYEE', 'sysdba','masterkey');
// Write the all connection parameters
Writeln( '================= Connection Properties ============' );
WriteLn( aDBXConn.ConnectionProperties.Properties.Text);
Writeln( '====================================================' );
Writeln( '' );
if aDBXConn <> nil then
aCmnd := aDBXConn.CreateCommand;
// Start transaction
aDBXTrans:= aDBXConn.BeginTransaction(TDBXIsolations.ReadCommitted);
// Prepare and execute the SQL Statement
aCmnd.Text := 'SELECT * FROM Country';
aReader := aCmnd.ExecuteQuery;
aColCount := aReader.ColumnCount;
Writeln( 'Results from Query: ' + aCmnd.Text );
Writeln( 'Number of Columns: ' + IntToStr(aColCount) );
Reasons to Migrate to from Delphi 7 to Delphi 2009
Embarcadero Technologies - 40 -
while aReader.Next do
Writeln( aReader.Value['Country'].GetAnsiString );
Writeln( '====================================================' );
Writeln( '' );
// Commit transaction

The new metadata support is used extensively by the Data Explorer pane of the Delphi IDE, but
can also be used by any application. In short, you'll not only be able to browse the database
structure, but also be able to use classes and objects to modify it, rather than relying directly on
the native database SQL commands for creating and modifying data structures. Not only will
the code look more object-oriented, but it will be also easier to target different database
servers with the same code, as dbExpress abstracts the metadata capabilities of each server.
The unit DBXMetaDataNames has been provided to read metadata. The dbExpress class
TDBXMetaDataCommands provides a set of constants to read various types of metadata. Set
the TDBXCommand.CommandType property to DBXCommandTypes.DBXMetadata and set
TDBXCommand.Text to one of the constants in TDBXMetaDataCommands to acquire the
designated metadata TDBXCommand.ExecuteQuery returns a TDBXReader to access the
metadata. The new classes in DBXMetaDataNames describe and provide access to this
metadata's columns. Below a list of metadata you can read using dbExpress:
• Data types
• Tables
• Columns (from tables, views, etc.)
• Indexes
• Fields from those indexes
• Foreign key
• Fields from Foreign keys
• Stored Procedures
• Stored Procedures’ parameters
• User list
• Catalogs
• Schemas
• Views
• Synonyms
• Stored Procedures’ source code
• Packaged Stored Procedures
• Packaged Stored Procedures’ source code
• Packaged Stored Procedures’ parameters
• Roles
• Reserved words

Data Explorer includes support for creating SQL dialect sensitive CREATE, ALTER, and DROP statements. dbExpress also exposes a DbxMetaDataProvider class that surfaces this capability for applications. This slightly increases the size of application, since the metadata writers must be included. The ability to generically create tables is useful for many applications. The interface allows you to describe what a table and its columns look like and pass this description to the TdbxMetaDataProvider.CreateTable method.

Below you find an example on how to create tables, primary keys, foreign keys, and indexes
using dbExpress Framework’s classes.
Provider: TDBXDataExpressMetaDataProvider;
Country, State: TDBXMetaDataTable;
IdField: TDBXInt32Column;
StrField : TDBXUnicodeVarCharColumn;
Provider := DBXGetMetaProvider(conn.DBXConnection);
// Country
Writeln('Creating Table - Country ....................');
Country := TDBXMetaDataTable.Create;
Country.TableName := 'COUNTRY';
IdCountryField := TDBXInt32Column.Create('COUNTRYID');
IdCountryField.Nullable := false;
IdCountryField.AutoIncrement := true;
StrField := TDBXUnicodeVarCharColumn.Create('COUNTRYNAME', 50);
StrField.Nullable := False;
// Defines COUNTRYID as Primary Key
AddPrimaryKey(Provider, Country.TableName, IdCountryField.ColumnName);
// Defines Unique Index as COUNTRYNAME
AddUniqueIndex(Provider, Country.TableName, StrField.ColumnName);
// State
Writeln('Creating Table - State ....................');
State := TDBXMetaDataTable.Create;
Reasons to Migrate to from Delphi 7 to Delphi 2009
Embarcadero Technologies - 42 -
State.TableName := 'STATE';
IdField := TDBXInt32Column.Create('STATEID');
IdField.Nullable := false;
IdField.AutoIncrement := true;
StrField := TDBXUnicodeVarCharColumn.Create('SHORTNAME', 2);
StrField.Nullable := False;
StrField := TDBXUnicodeVarCharColumn.Create('STATENAME', 50);
StrField.Nullable := False;
// Defines STATEID as Primary Key
AddPrimaryKey(Provider, State.TableName, idField.ColumnName);
// Defines Unique Index as STATENAME
AddUniqueIndex(Provider, State.TableName, StrField.ColumnName);
AddForeignKey(Provider, State.TableName, IdCountryField.ColumnName,
Country.TableName, IdCountryField.ColumnName);

The source code for this example is available at

Support for the latest versions of databases: InterBase 2007/2009, MySQL 4.1. 5.0, Oracle 10g.
Drivers for Oracle, InterBase and MySQL now come with Unicode support.

New concepts, called “Delegate Driver” and “Pools Connections”, are available in dbExpress
and require simple parameter configuration.

You can also extend the dbExpress framework to write delegation drivers, which provide an
extra layer between the application and the actual driver. Delegate drivers are useful for
connection pooling, driver profiling, tracing, and auditing DBXTrace is a delegate driver used
for tracing.

Below you see the log result generated by the Delegate in Delphi language. It’s easy to read,
understand, and even execute operations once again.

Trace configuration. The following example captures events according to the TraceFlags
parameter, saving the log file at c:\dbxtrace.txt. The dbExpress connection has a parameter to
indicate the trace configuration; for instance: DelegateConnection= DBXTraceConnection
Generated log result:
Log Opened ==========================================
{CONNECT } ConnectionC1.Open;
{COMMAND } CommandC1_1 := ConnectionC1.CreateCommand;
{COMMAND } CommandC1_1.CommandType := 'Dbx.SQL';
{COMMAND } CommandC1_1.CommandType := 'Dbx.SQL';
{COMMAND } CommandC1_1.Text := 'select * from employee';
{PREPARE } CommandC1_1.Prepare;
{COMMAND } ReaderC1_1_1 := CommandC1_1.ExecuteQuery;
{COMMAND } CommandC1_2 := ConnectionC1.CreateCommand;
{COMMAND } CommandC1_2.CommandType := 'Dbx.MetaData';
{COMMAND } CommandC1_2.Text := 'GetIndexes
ployee" ';
{COMMAND } ReaderC1_2_1 := CommandC1_2.ExecuteQuery;
{READER } { ReaderC1_2_1 closed. 6 row(s) read }
{READER } FreeAndNil(ReaderC1_2_1);
{COMMAND } FreeAndNil(CommandC1_2);
You can also use connection pools with dbExpress natively. Below you see an alias
(Pool_DelegateDemo) passing to DBXPoolConnection the control over the connection pool
(where the maximum number of connections is set).
Reasons to Migrate to from Delphi 7 to Delphi 2009
Embarcadero Technologies - 44 -
Interbase TransIsolation=ReadCommited
Trim Char=False

Integration between DataSnap and dbExpress is among Delphi 2009’s most significant new
features. Based on feedback received from our customers and user groups, we created the new
DataSnap. As usual, creating a multilayer application seemed easy. However, considering its
continued use and the impressive number of DataSnap applications available, many
opportunities for improvement have been identified. In this section, we explore the concepts
surrounding the creation of multilayer applications with the new DataSnap.

The new integration between DataSnap and dbExpress – which many are calling dbExpress remoting – brought great flexibility into the world of multi-layer application development.

Before that, sending and receiving data by means of ClientDataSet was the practice. Working with remote functions was something that required the use of a Type Library, consequently making you dependent on COM (present in Remote Data Module). Developers requested that we remove the COM dependency. This is a main attribute of the new DataSnap: it does not depend on any COM technology. However, this technology was not disregarded and compatibility is maintained, allowing you to use it whenever you find appropriate.

DataSnap integration with dbExpress allows dynamic execution of server methods using, for
example, SQLDataSet or the new SqlServerMethod component. The parameter and the result
of the method are defined using the Param properties.

One way to execute the methods on the server is to use the new SqlServerMethod component. this component inherits from CustomSQLDataSet, which means you can execute server side methods using a DataSet, input/output parameters will be represented by Params property.

DataSnap servers are defined by two components: DSServer and DSTCPTransport. Add these
two components to your application and you have a DataSnap server. The form/datamodule
which hosts these components can be called Server Container. From now on we will start using
a new naming convention.

DSServer is your DataSnap server. When connected to DSTCPTransport – which is where you
define the connection port, the maximum number of threads, etc. – it exposes your application
as a server.

DSTCPTransport transports information by means of TCP, thus enabling you to extend and
create new transport methods (e.g., HTTPS, SSL, to name a few). DSTCPTransport currently uses
Indy’s infrastructure for TCP connections.
If you use BSS, your application will still work in Delphi 2009. However, it’s recommended that
you migrate to the new DataSnap.

You most probably have many classes that hold business rules which would otherwise be of
better use in a multi-layer application. Using Server Methods you can easily expose all public
methods to the client side.

In order for a class to be made available as a Server Method, it must:
• Descend from TPersistent
• Have the {$MethodInfo ON} directive. This directive allows dbExpress to obtain information
about the class from RTTI.
• Be registered by means of the DSServerClass component.

Finally, we use the term Server Module to define the location of the providers, Server Methods, etc. You can create a Server Module selecting File | New | Other | Delphi Files | Server Module.

The Server Module is a DataModule that comes with the directive $MethodInfo ON by default.
Each class you make available has an associated DSServerClass component. This component is responsible for registering the class and making it available to client applications. It’s recommended that you keep your DSServerClass components in the Server Module. You can have as many Server Modules as you wish, which helps you to have a better organized application.

The various DSServerClass define the application lifetime, or the LifeCycle property:
• Server  One component instance is used per server (Singleton)
• Session  One component instance is used per DataSnapSession: (Statefull).
• Invocation  One component instance is used per invocation of a method (Stateless).

Additionally, DSServerClass comes with a few events that require you to use the OnGetClass
event to get the class registered. Below you see an example of it, with TServerMethods working
as a datamodule that holds many methods:

procedure TDMServerContainer.DSServerMethodsGetClass (DSServerClass :
TDSServerClass; var PersistentClass : TPersistentClass);
PersistenClass := TServerMethods
Proceed the same way in case you have a Remote Data Module in your application.

Since Delphi 2007 - when the dbExpress Framework was created - our goal was that of making it
a supporting infrastructure for many other technologies, extending the existing multi-layer
support and enabling Java, .NET, PHP, and other clients to connect to DataSnap servers.
DbxClient (originally created to allow Blackfish SQL connections) is now being used to connect
the client to the DataSnap server, as well. This means that in order to connect to a DataSnap
server you must use an SQLConnection, informing that the connection driver is DataSnap and
providing the hostname (server) and port. Just that simple.

There are many ways for you to execute the server methods. Let’s assume the server holds a
class that contains the HelloWorld and GetEmployee methods.

function TDMServerDB.HelloWorld(IncommingMessage : WideString ): WideString;
Result := 'Hello World';
function TDMServerDB.GetEmployee(ID : Integer): TDBXReader;
SQLDataSet1.Params[0].AsInteger := ID;
Result := TDBXDataSetReader.Create(SQLDataSet1, False);

The HelloWorld method is quite simple. It sends a string and returns another. Method
GetEmployee, in turn, sends an ID and receives a TDBXReader. In other words, it’s a cursor that
can be read client-side either as a DBXReader or as a ClientDataSet.

Still working with the HelloWorld method, you’ll now execute it using the SQLServerMethod
component. See below:
DMDataSnapClient.DSServerConnect.Open; // opens the connection by means of
SMHelloWorld.SQLConnection := DMDataSnapClient.DSServerConnect;
SMHelloWorld.Params[0].AsString := 'Message sent from Client';
ShowMessage(SMHelloWorld.Params[1].AsString); // shows the result

Let’s look at the GetEmployee method. In this example the server method is executed through
the dbExpress Framework. The same method could be executed through SqlServerMethod.
1 var
2 Command : TDBXCommand;
3 Reader : TDBXReader;
4 begin
5 DMDataSnapClient.DSServerConnect.Open;
6 With DMDataSnapClient.DSServerConnect.DBXConnection do begin
8 Command := DMDataSnapClient.DSServerConnect.DBXConnection.CreateCommand;
9 Command.CommandType := TDBXCommandTypes.DSServerMethod;
10 Command.Text := TDSAdminMethods.GetServerMethodParameters;
11 Reader := Command.ExecuteQuery;
13 TDBXDataSetReader.CopyReaderToDataSet(Reader, ClientDataSet1);
14 ClientDataSet1.Open;
15 end;

Note that the execution is performed by TDBXCommand. The return of type DBXReader is
copied to a ClientDataSet in line 13, thus allowing data to be visualized in the VCL.

In cases where you don’t need to display the data, DBXReader can be read directly.

You might be wondering… If this is all dynamic now, wouldn’t the compiler be able to detect
when server methods change? The answer could be positive in case server methods were not
represented by means of a client interface. SQLConnection includes an option called
“Generete DataSnap Client Access”, that generates a client-side unit with all the methods
available at server-side. Each method in the client class contains an implementation to execute
the server method.

See a sample class below:
TDSServerMethodsClient = class
FDBXConnection: TDBXConnection;
FGetServerDateTimeCommand: TDBXCommand;
FExecuteJobCommand: TDBXCommand;
constructor Create(ADBXConnection: TDBXConnection);
destructor Destroy; override;
function GetServerDateTime: TDateTime;
function ExecuteJob(JobId: Integer): Integer;
function TDSServerMethodsClient.GetServerDateTime: TDateTime;
if FGetServerDateTimeCommand = nil then
FGetServerDateTimeCommand := FDBXConnection.CreateCommand;
FGetServerDateTimeCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FGetServerDateTimeCommand.Text := 'TDSServerMethods.GetServerDateTime';
Result := FGetServerDateTimeCommand.Parameters[0].Value.AsDateTime;
function TDSServerMethodsClient.ExecuteJob(JobId: Integer): Integer;
if FExecuteJobCommand = nil then
FExecuteJobCommand := FDBXConnection.CreateCommand;
FExecuteJobCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FExecuteJobCommand.Text := 'TDSServerMethods.ExecuteJob';
constructor TDSServerMethodsClient.Create(ADBXConnection: TDBXConnection);
inherited Create;
if ADBXConnection = nil then
raise EInvalidOperation.Create('Connection cannot be nil. Make sure the
connection has been opened.');
FDBXConnection := ADBXConnection;
destructor TDSServerMethodsClient.Destroy;

And how do you access the DataSetProvider from the server, from a remote data module, or
from a conventional data module? That’s simple: client-side you use the new
DSProviderConnection component, which is connected to your SQLConnection (DataSnap).

The ServerClassName property indicates the class name (DataModule/RDM, usually) where the
providers are located in the server. This way the ClientDataSet use DSProviderConnection as

The new DataSnap and dbExpress Framework provide greater flexibility, not limited by what’s
presented in this section. It’s possible to dynamically access a list of methods along with their
parameters, which translates into a great opportunity for developers to create components that
control user access to the server, defining access rights specific to each of the server’s methods
and classes. You can take a look at a more complete DataSnap application sample by visiting
my blog at

The IDE-integrated translation tool is now standalone. This means the professional responsible for translating your project can now use the same tool you do, without having to install Delphi himself/herself. For each new language a translation project is generated. It’s then much easier to edit language-specific DFM files.
FigurFigure 28 Translation Tool

Any final product is expected to be first-class. Quality concerns are no different when it comes to software (especially considering they’re a core element in supporting a company’s growth efforts). Keep in mind that whenever you deliver low-quality software you are compromising your client’s success.

Since Delphi 2006 you can use UML and all of its diagrams. In addition, you can also use
LiveSource, which allows you to synchronize class diagrams and code.

Below you see a list of all diagrams available, along with their functionality:
• Use Case  it is a way to describe the interaction between a system and the real world. In
this case, the actors (either persons or systems) represent the real world.
• Class Diagram  represents the classes of the system and the relationships they establish.
• Collaboration  used for modeling the dynamic aspects of a system or subsystem.
• Activity  allows you to represent dynamic situations by means of flows (using it you can
represent the flow between different objects).
• Component  used in higher-level modeling, in cases where more complex structures are
present. This diagram illustrates systems, embedded controls, etc.
• State  specifies the sequence of events of a given object.
FigurFigure 29 Use Case Diagram

Visualizing a class diagram makes it much easier for you to understand the classes in it (as
compared with doing the same with code).

Let’s see an example in Delphi: the Buttons.pas unit has many components - TBitBtn,
TSpeedButton, among others. Now imagine how hard it would be to decipher 1946 lines of
code to learn which components are there and which relationships they established. Using
reverse-engineering it’s not a big deal...

Delphi has full reverse engineering capabilities. Embarcadero is committed to helping
developers evolve legacy code; a commitment that is reinforced by our efforts toward
continuously providing technology that allows applications to move on.

When it comes to quality, people are always concerned about delivering high-performance software. Many even tell us they do not care about the way software is written, rather with its ability to work and meet their needs. In fact, this is a mistake with the potential to impact you in the not-so-distant future. When you write unstructured code you’re impairing your ability to extend the application in the future, in case you need to. It’s then all pieced together, and your application does not grow in a structured manner. Delphi’s audits and metrics help you locate flaws in your application while you’re still developing it. They also help developers get used to writing standardized code.

How many times have you defined best-practice guidelines for coding, hoping it would prevent your staff from making mistakes of the kind that turns it into a handful of ineffective typedmatter no one understands?

Assuming your team can count on a best-practice manual, the second question that comes to
mind is: how can we ensure the instructions therein are being followed?
The answer, again: code review. Now, think of a context where your project is coded in no less
than thousands of lines. What you have here is a scheduled catastrophe.
Using Delphi’s code audit resources (QA Audits) you can set a definite group of best coding
practices, making sure they’re being followed by your projects. Clearly speaking, you detect
flaws in your application before it run.
Audits verify whether the code conforms to the rules and parameters defined by your
organization. Results show only the detected violations, in a categorized manner:
• Arrays and References
• Duplicated code
• Superfluous content
• Performance
• Branches and Loops
• Coding style
• Naming style
• Expressions
• Design flaws
• Possible Errors

Each of the audit items includes a descriptive note explaining the correct and incorrect ways of
using it. This helps developers understand how to use each specific audit item. The items can
have their severity level set to Info, Warning, or Error. It’s up to developers to define how
relevant each item is.

Often times we come across execution routines that involve many loops, requiring us to debug
it to make sure all loops are executed. Using the LBNE audit this kind of issue is detected. The
following code is a simple example of something LBNE would detect. Even more complex
cases which involve more conditions are also easily detected.
x: Boolean;
x := false;
while s do
of the selected

This is a common message for when you try to access an array position that does not exist. The snippet below generates this warning.

j :integer;
matriz : array of integer;
somatorio : double;
for i := 0 to nloops do
somatorio := 0;
for j := 0 to High(matriz) do
somatorio := somatorio + matriz[i];
FigurFigure 32 Audits
The audit has located the error, informing you that the code in line 25 tries to access a variable
that is not part of the 2nd loop. Drilling down a little:
In variable J’s ‘for’ statement I’m trying to access one of the positions in array ARR, aiming at
position I of the previous loop, while variable J’s ‘for’ statement is the place where array ARR is
being read.

Metrics help you standardize the code. After all, who has never come across code with 10
constructors for a class, 10 ifs – the first enclosing the next ones, consecutively; methods with 20
parameters, and other practices that can only assist in making code incomprehensible? This is
where metrics come in handy, allowing you to define limits for the company to follow. An
example: a class must not have more than 4 constructors, having 400 code lines tops, while
topics are to be named in conformance with Pascal’s convention, which rules the first letter of
method names is always capitalized.

Each metric has its own limit which can be customized:

After metrics are executed their results are analyzed with the assistance of a Kiviat chart. In a
Kiviat chart the red circle represents the predefined limit. Points outside this boundary mean
part of the code is breaking the metric rules.

You can analyze each of the classes separately. This way it’s easier to identify violations of your

With audits and metrics developers are able to deliver higher-quality code/applications, just as
good externally as they are in their core.

These are the things you are able to perform when your code is migrated from Delphi 7 to
Delphi 2009.

Few things are as difficult as getting developers to document their applications. Developers
develop, that’s what they do best. Delphi can change this paradigm. With the assistance of
Delphi’s diagrams, developers, analysts, and architects learn how easy it can be to write code
and document the entire application. It’s as simple as getting into the diagram and…
documenting. Taking a class diagram as an example, you simply click on the class, variable,
method, and other class attributes and you’re ready to document them.

The documentation is generated in HTML, separated as project overview, diagram view and
documentation details.

Many of the third-party components packed with Delphi were updated and now bring new
resources and compatibility with existing applications. Additionally, if you upgrade your
software to Delphi 2009 you’re eligible to download the InfoPower Grid Essentials component
pack. If you have any additional questions about some specific third-party component that you
use, the Delphi product page has a list of many third components available today

One of the components Delphi developers use the most, TeeChart, has been updated to
version 8. It’s now includes new resources aimed at working with Charts in Delphi.

Delphi 2009 comes with Rave Reports, the famous report generator, now update to version 7.6.

VCL for Web - previously called IntraWeb - allows you to create Web 2.0 applications, with transparent AJAX integration in many VCL components, and the newly added Silverlight support.

Delphi 2009 is offered in three editions: Professional, Enterprise and Architect. You can check
the list of features available in each edition at:
The Architect edition includes the ER/Studio Developer Edition modeling tool. Database
modeling is vital for developers working with applications that rely on databases to work.
ER/Studio supports the following databases: DB2 LUW V9, Hitachi HiRDB, IBM® DB/2®, Informix,
InterBase®, Microsoft® Access, SQL Server, Visual FoxPro, MySQL, NCR Teradata, Oracle,
PostgreSQL, Sybase, SQL Anywhere. Other databases can also be accessed through ODBC.
The tool provides resources as reverse-engineering, logical and physical modeling.

Delphi’s IDE has been continually improved over the past few years. Delphi 2009 is no
exception. The new Project Manager, VCL components, RTL, generics, anonymous methods
and the new DataSnap are sure to improve developers’ productivity, allowing you not only to
evolve existing applications but also develop new ones with next-generation technologies.

For additional detail drill down into what’s new in Delphi 2009, please visit:

In his role at Embarcadero, Andreano Lanusse is focused on helping make sure products are developed to meet customers’ expectations. Responsible for defining market strategies for Latin America, he spends a great deal of time attending developer conferences, tradeshows, and user groups part of his duties as Latin Lead Evangelist, while also visiting strategic customers throughout Latin America. You can read more about Andreano Lanusse on his blog and reach him at his e-mail address:

Embarcadero Technologies, Inc. is a leading provider of award-winning tools for application
developers and database professionals so they can design systems right, build them faster and
run them better, regardless of their platform or programming language. Ninety of the Fortune
100 and an active community of more than three million users worldwide rely on Embarcadero
products to increase productivity, reduce costs, simplify change management and compliance
and accelerate innovation. The company’s flagship tools include: Embarcadero® Change
Manager™, CodeGear™ RAD Studio, DBArtisan®, Delphi®, ER/Studio®, JBuilder® and Rapid
SQL®. Founded in 1993, Embarcadero is headquartered in San Francisco, with offices located
around the world. Embarcadero is online at

1 comment:

Phil Rogers said...

As I develop for an international market, I was really pleased to find Delphi 2009 is 100% Unicode. It's making my life easier already.

On the other hand, there are a number of 3rd-party components that I used which do not support Unicode, so they fail to build in Delphi 2009. To support my older applications which use those components, I still have Delphi 2005 and Delphi 7 installed on my PC.

Welcome to Delphi... Delphi... Delphi

I have been a Delphi Developer since Delphi 3 when I finally decided on Delphi in 1996 as my programming language of choice for the Windows 32 environment. So what have I created with Delphi ?

Would you believe that I had single-handedly created a full ERP2 system comprising ERP+CRM where ERP=Sales Distribution+MRP+ Procurement Management+Planning & Production +Finacial Management + Human Resources Management System.

Since 15th February 2009, we have visitors from more than 60 countries including Malaysia, United States, Brazil, Italy, Australia, India, Turkey, Russian Federation, Spain, Indonesia, Hungary, South Africa, Germany, Mexico, Argentina, Singapore, Saudi Arabia, Colombia, Czech Republic, Canada, France, Croatia,Thailand, Bulgaria, Slovenia, Hong Kong, Poland, Sri Lanka, Chile, Japan, Austria, Ukraine, Azerbaijan, Ireland, Tunisia, Greece, Taiwan, Egypt, Bolivia, Paraguay, Iran, Islamic Republic , Morocco, Angola, Belgium, Portugal, Norway, Venezuela, United Arab Emirates, Algeria, Korea, Republic Of, Slovakia, Georgia, Lebanon, Macedonia, Sweden, Philippines, Vietnam, Dominican Republic