0% found this document useful (0 votes)
273 views38 pages

0401

0401

Uploaded by

jivasumana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
273 views38 pages

0401

0401

Uploaded by

jivasumana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

January

2004

Volume 10 Number 1

INSIDE
ON THE COVER
Sound+Vision

3D Delphi

Get out your red/blue glasses! Alexander Gofen introduces


the three-dimensional world of anaglyphic images to Delphi
developers, discussing how theyre created, how theyre
perceived, and how to implement them on your standard PC
monitor using Delphi. Its also tons of fun!

Product Reviews: ExpressBars, Database Workbench, Pervasive.SQL v8

Delphi Informant

January 2004 vol.10, no. 1

www.DelphiZine.com

The Complete Monthly Guide to Delphi Development

FEATURES
.NET Tech

10

Delphi for .NET Resources

Using the Delphi for .NET Compiler Preview, Borlands Fernando


Vicaria shows you how to create .resources and .resx files in
code, how to use the two resource generator tools provided by the
.NET SDK (ResGen and ResXGen), and how to add a manifest to
your .NET applications.

en
etwe
cts b aos
Proje
h
ftware and C
o
S
Keep igidity
R
Create and Use

es
.NET Resourc
Roll Your Own
Hotmail Proxy Server
Extreme W
eb Sites

Cover Art by Arthur A. Dugoni Jr.

In Development

16

Practical Software Process Management: Part I

Steven Beebe and Xavier Pacheco begin a series on software


process management. Speaking from experience, they outline
the major aspects of a successful software project, and caution
against the excesses of a religious fervor for documentation and
rigid process, and its evil opposite ad hoc chaos.

On the Net

20

Writing an E-mail Proxy Server: Part I

In this highly educational series, Alfred Mirzagitov demonstrates


how to use Delphi to handle the POP and SMTP e-mail protocols,
WebDAV, and how to write a fully functional local POP/SMTP proxy
server for sending and retrieving hotmail.com e-mails using your
favorite e-mail client.

REVIEWS
26 Database Workbench
Product Review by Bill Todd

29

Pervasive.SQL v8

33

ExpressBars Suite 5

36
1

Product Review by Bill Todd

Product Review by Alan C. Moore, Ph.D.

C#Builder Kick Start

Book Review by Clay Shannon

DELPHI INFORMANT MAGAZINE | January 2004

D E PA R T M E N T S
2 Toolbox
37 File | New by Alan C. Moore, Ph.D.

T O O L B O X
PASSOLO 4.0 Service
Release Includes Delphi/
C++Builder Solution
PASS Engineering announced a new
service release of PASSOLO 4.0. PASSOLO optimizes software localization
and ensures easy compilation, exchange,
and processing of translation data. PASSOLO requires neither time-consuming
and expensive training nor programming
experience. Many errors that occur during localization are avoided or automatically recognized by PASSOLO.
This service release includes enhanced
Delphi/C++Builder support, which
provides a visual localization solution for
Delphi/C++Builder resources.
PASSOLOs Delphi/C++Builder solution integrates seamlessly with any
edition of PASSOLO 4.0 (Standard, Professional, Team, or Translator). It offers
comprehensive support of PASSOLOs
visual localization environment and
extensive options for configuration and
customization. The latest PASSOLO service release is available free of charge to
all PASSOLO 4.0 customers, and can be
downloaded from www.passolo.com/
support/index.htm.
PASS Engineering GmbH
Price: Free to PASSOLO 4.0 customers.
Contact: [email protected]
Web Site: www.passolo.com

Heaventools Software Announces Resource Tuner 1.94

Heaventools Software released


Resource Tuner 1.94, its visual
resource editor for 32-bit Windows
executable files.
Resource Tuner is a resource editing
solution that makes it easy and intuitive to change applications to reflect
your personal tastes. It also allows
experienced users to look inside Windows binary files such as EXEs, DLLs,
and ActiveX controls.
Each element of the user interface
dialog boxes, Delphi forms, menus,
icons, pictures (bitmap, jpeg, png),
string tables, XML application manifests, and more are right at your fingertips. This means you can change
any programs text, pictures, buttons,
and colors you can completely
customize any program you own.
Resource Tuner offers a thorough
look at all the resources in the file,
and allows you to make modifications
without needing to recompile the
source code. It also allows you to edit
the properties of any controls on Delphi forms within the PE file.
In addition, Resource Tuner allows legacy applications to take advantage of the
new look for common control styles on
Windows XP by enabling you to inject
the application manifest directly into the

Borland Selects Crystal Decisions as Java Reporting


Standard for JBuilder
Crystal Decisions announced Crystal Reports for Borland JBuilder will
be integrated with Borlands Enterprise Studio for Java. The release
is scheduled for general availability
later this quarter.
Shipping inside the box as the only
reporting tool, Crystal Reports will
be included as part of the default
installation of JBuilder X. Crystal
Reports for JBuilder simplifies and
accelerates the process of embedding Crystal Reports within your
JSP application. The OEM bundle
includes Crystal Decisions 100%
Java Reporting Component for
processing and rendering dynamic
reports within a J2EE application.
An interactive zero-client viewer is
included for customized end user
report interaction, including drill-

DELPHI INFORMANT MAGAZINE | January 2004

down, exporting, and printing functions. A custom tag library is also


included for developers to rapidly
integrate report viewing from within
their J2EE applications.
Borland JBuilder customers will also
be entitled to a customized edition
of Crystal Decisions popular report
design environment for generating
new reports as part of their enterprise
applications. The Java Reporting
Component is also compatible with
existing Crystal Reports RPT files,
which deploys to leading J2EE application servers such as BEA WebLogic,
IBM WebSphere, and Apache Tomcat.
Crystal Decisions
Price: Contact Crystal Decisions
Contact: North America, (800) 877-2340;
international, (604) 681-3435
Web Site: www.crystaldecisions.com

EXE file in just a few clicks.


Resource Tuner also ships with the
UPX Unpacker plug-in. This is a start-up
processing plug-in for unpacking files
compressed with UPX.
With Resource Tuner you can quickly
browse, view, extract, modify, translate,
edit, or replace any selected executable
file resources contained within 32-bit
Windows executable files with the click
of a button.
Version 1.94 now supports editing
accelerators and opening files with
modified MS-DOS stubs, saves charset settings when customizing fonts,
and all versions of UPX are supported
from 0.8 up to 1.90.
Heaventools Software
Price: Personal license, US$34.95; business license,
US$59.95. All versions include lifetime support and
free maintenance updates.
Contact: [email protected]
Web Site: www.restuner.com

DAC for MySQL 2.1.7


microOLAP Technologies announced
DAC for MySQL 2.1.7, a component
suite for Delphi/C++Builder and
MySQL. This data access library for
Delphi and C++Builder development
environments allows you to create
Delphi/C++Builder applications with
direct access to the MySQL DB without the BDE, ODBC, or dbExpress.
This is a royalty free product; is
100% native Delphi code; offers
full support of BLOB fields; boasts
a detailed help system and various
demo applications; and no additional
library (even libmysql.dll) is required.
See the microOLAP Web site for
complete details.
microOLAP Technologies LLC
Price: Single-user license without source, US$59.95;
single-user license with source, US$99.95; site
license without source, US$179.95; site license with
source, US$299.95.
Contact: [email protected]
Web Site: www.microolap.com

T O O L B O X
VssConneXion 3 for Delphi and C++Builder Available
EPocalipse Software released VssConAutomatic check-out when editneXion 3, a SourceSafe integration
ing forms and source files now offers
expert for Delphi and C++Builder
more options and works much better
that allows you to perform the most
with forms and project files. Find Last
common source control operations
Change allows you to select a line in
directly from the IDE. This version
the editor and find the last version of
introduces many new features, such
the file when this line was changed.
as Source History, which allows you
Review Changes is a great tool to enter
to see the history of a file together
check-in comments while viewing difwith the changes made to the file.
ferences before check in.
Also new is Source Analysis, which
GIS Development Toolkit
shows an overview of the changes
Component Supports
made to a file using different views
IntraWeb
(changes by user, changes by date,
TatukGIS announced a new component
my changes, and changes by count).
for the comprehensive TatukGIS DevelMultilizer 6.0 Released
oper Kernel toolkit to support IntraWeb,
Multilizer, Inc. announced the release
the popular Web application developof Multilizer 6.0, the next generation verment environment from Atozed Software
sion of their localization tool for devel(www.atozed.com).
oping multilingual VCL applications.
By supporting IntraWeb, TatukGIS offers
Multilizer localizes Delphi/
Delphi and C++Builder developers a
C++Builder binaries directly, thus simmethod of porting their DK-VCL appliplifying the localization process and min- cations to a Web server environment,
imizing developers overhead in creating
as well as the following advantages:
different language versions of software.
theres no need to change technologies
With its WYSIWYG capabilities Multifrom Borland development tools; only a
lizer 6.0 allows visual editing of dialogs,
minimum of changes are needed to the
menus, accelerators, and bitmap-type
core DK-VCL source code of any existing
resources. Multilizer 6.0 also supports
application; and it offers true WYSWIG
visual inheritance.
development. It is also reliable and easy
Multilizers comprehensive validation
to deploy, and offers an intranet user feel
rules automatically detect localization
similar to a desktop PC application.
issues that users dont even see or that
An IntraWeb license is bundled with
take too long to check manually.
Delphi 7. DK-VCL developers using
You can download free trials from the
C++Builder can obtain an IntraWeb
Multilizer Web site.
license separately from Atozed Software.
Multilizer Inc.
Price: Starts at US$1,475
Contact: [email protected]
Web Site: www.multilizer.com

C#Builder Kick Start

Joe Mayo
SAMS
ISBN: 0-672-32589-6
Cover Price: US$34.99
(461 pages, CD-ROM)
www.samspublishing.com

TatukGIS
Price: Contact TatukGIS.
Contact: [email protected]
Web Site: www.tatukgis.com

Check the EPocalipse Web site for all


the new features and enhancements.
EPocalipse Software
Price: US$59.95 per license. Multiple-license discounts are available.
Contact: [email protected]
Web Site: www.epocalipse.com

O&K Software Releases


O&K Print Watch
O&K Software released O&K Print
Watch, printing activity monitoring and
management software for Windows.
Print Watch is capable of building printer use reports that allow technicians to
schedule servicing, plan the budget, and
make decisions about printer needs.
The program can monitor any number
of printers, providing you with the following information: name of user and
computer that initiated the print job; date
and time; exact number of pages; volume
in bytes; paper size; color mode; and
whether it is double-sided. Print Watch
can also discern whether a 100-page
print job consisted of 20 copies of a fivepage document or five copies of a 20page document. In addition, Print Watch
is capable of managing printer document
traffic, such as pausing, resuming, deleting, and restarting print jobs.
The program supports any number of
printers, making it equally suitable for
small businesses and large corporations.
O&K Print Watch is distributed electronically over the Internet; a free demo version is available from the O&K Web site.
O&K Software
Price: US$149.95
Contact: [email protected]
Web Site: www.prnwatch.com

Advantage Database
Server: The Official Guide

UML 2 for Dummies

Cary Jensen, Ph.D. and


Loy Anderson, Ph.D.
McGraw-Hill/Osborne
ISBN: 0-07-223084-3
Cover Price: US$49.99
(468 pages, CD-ROM)
www.osborne.com

Michael Jesse Chonoles and


James A. Schardt
Wiley Publishing, Inc.
ISBN: 0-7645-2614-6
Cover Price: US$29.99
(412 pages)
www.wiley.com

DELPHI INFORMANT MAGAZINE | January 2004

Waltzing with Bears: Managing


Risk on Software Projects

Tom DeMarco and Timothy Lister


Dorset House Publishing
ISBN: 0-932633-60-9
Cover Price: US$27.95
(196 pages)
www.dorsethouse.com

S O U N D + V I S I O N
ANAGLYPHIC STEREO IMAGES

DELPHI 4-7

By Alexander Gofen

3D Delphi

Stereo Vision on Your Home PC

ur brains have the wonderful ability to


create 3D images by fusing two planar
images received by our eyes. The result is

a special sensation of 3D space, albeit a completely


imaginary one created in the minds eye.

Yet we take this ability for granted. Most of the time, of


course, we are in a real 3D environment inhabited with
objects of regular shapes, or those of irregular but familiar
shapes. Our brain so routinely maintains this 3D scene,
that even if the regular video input is interrupted say
one eye is closed we usually dont feel as if anything in
our perception has been lost. Ironically therefore, viewing
the real 3D world doesnt usually feel special. The real 3D
excitement occurs when we look at something we expect
to be two-dimensional, such as a computer monitor or a
hologram, and suddenly discover a 3D scene popping
out from the planar surface.
This is 3D Stereo Vision, which shouldnt be confused with
the misnomer 3D Graphics used for video cards and video
libraries. This misleading term emerged when game and
video technology switched from simplistic projections (front,
side, or top views), to more advanced oblique projections of
3D objects and scenes. These 3D Graphics actually render
3D scenes into plane isometric projections. Photos, isometric
drawings, artistic paintings (if their perspective is correct)
are all examples of such projection. We perceive them as
planar 2D projections of 3D reality. Weve all become good
at reading these projections and understanding the 3D
reality they represent. Were so used to them, in fact, that
were hardly aware of the convention.
4

DELPHI INFORMANT MAGAZINE | January 2004

Such projections were the closest we could come to 3D


imagery until the invention of the stereoscope in the 19th
century in Great Britain. The two eyepieces of a stereoscope
deliver the two planar images of a stereo pair directly to the
corresponding eyes. Then a miracle occurs: viewers perceive
the three-dimensionality of the scene as real so real that
they wish to touch the objects hanging in air. This never
happens when we look at 2D projections of the 3D world.
After the stereoscope, many other techniques were developed for displaying 3D stereo images. Except for the holograph, they all use the same basic principle as the stereoscope, i.e. deliver each of the two images of a stereo pair
to the proper eye. In contrast, holographic equipment completely reproduces the 3D light front, i.e. the 3D vector field
of the same electromagnetic waves that would be reflected
by the 3D scene if it were really there. Thus a hologram
creates a sculptural ghost of a 3D scene in the real world
as a real physical phenomenon, while a stereo pair creates this scene in our mind (the ultimate addressee in any
case). Another fundamental difference is in the quantity of
information: a stereo pair is just two planar images, while a
hologram encodes infinity of them.
Putting aside the awe and emotional excitement of stereo
vision (as well as the obvious evolutionary advantages of 3D
perception for survival of the species), let us ask ourselves
how stereo vision is better than a planar perspective projection such as a photo, painting, or drawing. Such isometric
images are good for displaying scenes with rectangular
shapes, bodies with edges, good perspective, and reflection
hints. Isometrics work poorly for smooth surfaces without
edges. For example, to effectively convey a picture of a
sphere or torus, we must add special shadows and reflections. The 2D projections become especially inefficient in

Sound+Vision

3D Delphi

ing 3D scenes encoded in artificially


created stereo pairs and displayed
with various technical tools. Not
much is known about how the brain
does this. It must start with matching the identical points, edges, curves
and other topological elements in the
two images of a stereo pair. Then the
disparities (also called parallaxes or
angular differences between the corresponding elements) are translated into
3D coordinates. Mathematicians do
this using trigonometry and a lot of
computation, but we dont know how
it happens in our heads.

The best stereo vision (i.e. the easiest


to fuse) is achievable with tools that
deliver each of the two high-quality color images of a stereo pair to
Figure 1: A 3D scene (top view) with some basic variables. Points A, B of the 3D scene are mapped to
the proper (and only to the proper)
corresponding A, B (Blue) and A, B (Red) points.
eye. For example, in stereo movies
the two images are projected onto a
the case of visualizing non-planar curves (1D manifolds, or
conventional reflective screen. The trick is that each of the
lines in space). The accompanying demonstration software
images is polarized and their planes of polarizations are peris intended exactly for that type of curves, taking the full
pendicular to each other (say horizontal and vertical). The
advantage of the 3D stereo vision (available for download;
audience watches through the polarizing filters so that each
see end of article for details).
of the two eyes receives only the proper image in full color
(human eyes ignore polarization).
This article explains the physical and psychophysical basics
of stereo vision, and describes certain hardware and softAlthough simple and efficient at movie theaters, this idea
ware implementations of stereo vision for the PC. It also
isnt applicable to computer monitors. However, another
provides a demonstration program that displays fascinating
scheme based on high-frequency altering display of left/right
3D animated stereo trajectories for several important physiimages does work for them. In this scheme the viewer has
cal problems. It also implements a 3D cursor (controlled
to wear goggles or liquid crystal glasses functioning as an
with a conventional mouse) that enables tactile exploraelectronic shutter, synchronized by the stereo projector. In
tion with audible feedback of 3D curves.
the case of the computers a special video card with proper
software is required: the card must be capable of controlling
Mathematical Model of Stereo Vision
the electronic shutter. The monitor can be conventional but
The direct problem formulates as follows: given a viewmust be relatively high end, with a frame rate of at least
ing point and a 3D scene, obtain two planar images, called
120 Hz and phosphor with a short decay rate to avoid inera stereo pair, which fuses into a given 3D scene. Note
tial overlapping of the images.
that, strictly speaking, a stereo pair depends on the viewing
point: it encodes the 3D scene only as viewed at one specific Recently Sharp introduced a 3D stereo notebook that
point. For example, all viewers in a movie theater perceive
requires no glasses (www.sharpsystems.com/news/press_
a stereo scene as though they all watched it from the same
releases/release.asp?press=45). They implemented the
point the one from which it was shot.
idea similar to that in raster stereo postcards: the left/right
images of a stereo pair are represented as intermittent very
Obtaining a stereo pair is a straightforward geometrical
narrow vertical stripes (and that halves the horizontal resoproblem as simple as construction of two perspective projec- lution). Unlike viewers in stereo theaters wearing special
tions of the 3D scene onto a plane, with the centers of proglasses or goggles and capable of perceiving the effect in a
jection in each eye (see Figure 1). The technical tools and
wide variety of positions, the 3D stereo notebook requires
schemes for obtaining stereo images (such as double-lens
the viewer to maintain position strictly at the axis of the
cameras) have been known since the invention of the stescreen (plus/minus an inch).
reoscope. (Stereo photos can even be shot sequentially with
a conventional camera.)
Another old idea, the so-called anaglyphic (Red/Blue)
glasses described in this article and implemented in the
In contrast, the reconstruction of a 3D scene from the
software, is nice because it is simple, and requires nothstereo pair is geometrically ill-defined, requiring heuristic
ing more than a conventional PC and some cardboard
assumptions and a priori knowledge about the reality.
glasses the cheapest gear possible. The two images of
Our brain somehow solves this problem quite successfully,
an anaglyphic stereo pair must be monochromatic, each in
not only decoding our actual 3D environment, but also fus- a different color of one of the basic Red/Green/Blue set.

DELPHI INFORMANT MAGAZINE | January 2004

Sound+Vision

3D Delphi

Figure 2: A pure Red/Blue anaglyphic image.

The Red/Blue pair is best because theyre further apart on


the color spectrum and therefore provide good separation.
When you look through Red/Blue glasses at a stereo pair
of Red/Blue images that overlap on a screen, each eye
receives only the proper image of the stereo pair.
This makes sense, but how does the brain then fuse
the stereo pair, each of which is in a different color? It
appears that the brain follows not a rigid, but rather
a flexible algorithm. Certain neurons fire if they find
recognizable elements in the image (disregarding color),
while the others fire if these elements happen to comprise
a meaningful stereo pair. When this occurs, the signals of these stereo-specialized neurons dominate. As
a result we fuse the 3D scene despite the fact that each
eye sees it in a different color. Different people may perceive an anaglyphic scene in monochromatic Red, Blue,
Gray, or in competing colors. In any case, fusing an
anaglyphic stereo pair is just as easy as uncompromised
stereo pairs in stereoscopes or movie theaters. This is the
case when the natural stereopsis works as-is, i.e. no extra
efforts are required to fuse the stereo pair. (In contrast,
some other types of stereo effects, such as the so-called
auto-stereograms, or for stereo pairs placed next to each
other without a separator, the eyes must be crossed in
a certain way. The brain requires more effort and some
training to fuse such a stereo pair successfully.)
Programming the Anaglyphic Stereo
PC monitors have a principle feature that is particularly
beneficial for producing anaglyphic stereo images. The
colors are implemented at the hardware and software
level by three independent monochromatic screens: Red,
Green, and Blue. Usually of course, all three work together, but we can take advantage of this feature to create two
separate monochromatic images.
Lets see how this is done with Delphi. To display three overlapping monochromatic bitmaps in Red, Green, and Blue with6

DELPHI INFORMANT MAGAZINE | January 2004

Figure 3: A half-tone Red/Blue anaglyphic image.

out corrupting each other (when viewed through the filters),


the first layer must be drawn with the following statement:
Canvas.CopyMode := cmSrcCopy

while the second and the third layers are drawn like this:
CopyMode := cmSrcPaint

// OR mode for Bitmaps, Brush.

Because the three color components occupy different bits


in TColor, they dont interfere with each other. Similarly,
when doing Pen operations, all three layers must be drawn
on the black background, thus:
Pen.Mode := pmMerge

// OR mode for pen.

As discussed, we need only two layers and two colors (Red


and Blue) for anaglyphic stereo. If viewed without the anaglyphic glasses, the overlapped Red/Blue images interfere
with each other and appear Magenta in the overlapping pixels. However, the filters of the glasses separate the images so
that only one (Red or Blue) is visible.
The sample software associated with this article displays
only lines in space, and therefore uses the pixel colors of
pure Red and Blue. However, similar techniques may be
employed for half-tone black and white stereo images as
well. Having a source black and white stereo pair, just
erase Green and Red bits in all pixels of the first image of

Sound+Vision

3D Delphi

Constant

Viewed through
Red filter

Viewed through
Blue filter

Composite Red

Light Gray [RR]

Very dark Gray [RB]

Composite Blue

Very dark Gray [BR]

Light Gray [BB]

Theyre overlapping

Some Gray [OR]

Some Gray [OB]

Figure 4: Printed color requirements for Red/Blue glasses.

the stereo pair (hence converting it into half-tone Blue),


and erase Green and Blue bits in all pixels of the second
one (making it half-tone Red). Then display the images
overlapped as explained above, and view the stunning stereo picture through your anaglyphic glasses. There are two
such photo bitmaps in the download files (see Figures 2
and 3). Other fascinating examples of anaglyphic maps are
available at www.mappinginnovations.com/gallery.html.
The method applies also for mathematical surfaces whose
images were created with half-tone shadows, reflection
hints, or texture.
To obtain a hardcopy version of an anaglyphic stereo
image, we have to convert the source screen colors Red,
Blue, and Magenta (where they overlap) into the appropriate printer colors: Cyan, Magenta, Yellow, and Black.
However, unlike the phosphors of a computer monitor
that emit light, the color pigments on paper reflect light.
For reflected light, pure Cyan is usually best in the role
of screen Blue, composite Red for screen Red, and some
mixture of Gray works best for screen Magenta. The background remains black in both cases.
In the simplest case when only the full Red and Blue
colors are used, the table in Figure 4 summarizes requirements to the printed colors for specific Red/Blue glasses.
The ideal printer color adjustment should satisfy the following conditions:
Light Gray [RR] = Light Gray [BB] = Some Gray [OR] =
Some Gray [OB]
Very dark Gray [BR] = Very dark Gray [RB] = Black
Printing half-tone Red/Blue anaglyphic images would
require much finer printer color adjustment.
Programming the Geometry
of Stereo Vision
Lets assume that the 3D scene were going to render is
located in the space relative to the screen, as shown in
Figure 1. To represent a point in 3D space, were going to
declare an object containing both the 3D coordinates of the
point, and two 2D coordinates of its left-eye and right-eye
projections, as shown in Figure 5.
We have to deal with three coordinate systems and different
scales:
1) The parallelepiped [Xmin..Xmax, Ymin..Ymax,
Zmin..Zmax] of the 3D scene where trajectories of the
physical motion take place. These values may be in any
units in any scale. The values x, y, and z in the type
T3DPoint represent these coordinates.
7

DELPHI INFORMANT MAGAZINE | January 2004

T2DPoint = record
x, y : extended
end;
T3DPoint = object
// 3D coordinates to be mapped into two 2D coordinates
// RightEyeProj and LeftEyeProj.
x, y, z : extended;
RightEyeProj, // Right-eye perspective projection.
LeftEyeProj : T2DPoint; // Left-eye ...
procedure SetRightLeft;
// With rotation.
function Init(const x1, y1, z1: extended): T3DPoint;
// Without rotation.
function InitStill(const x1, y1, z1: extended): T3DPoint;
end;

Figure 5: Declaring an object capable of storing 3D coordinates of a point, and


two 2D coordinates of its right- and left-eye projections.

cmImageWidth,
Abase, cmABase,
Dist, cmDist,
Front, cmFront,
Cx, Cy, Cz,
...

//
//
//
//
//
//

Width of the screen.


Half-distance between eyes.
Distance from eyes to the screen.
Distance from eyes to zMax,
i.e. to the Front of the 3D scene.
Coordinates of the point of fixation.

Figure 6: Selected variables for specifying the 3D scene.

procedure Set3DParams(const xMin, xMax, yMin,


yMax, zMin, zMax:extended);
var
k : extended; // Boundaries of 3D scene in source units.
begin
// Viewer-screen scale to source units factor.
k := (yMax-yMin) / cmImageWidth;
Base := k*cmBase;
Dist := k*cmDist;
Front := k*cmFront;
Cx := (xMin + xMax)*0.5;
Cy := (yMin + yMax)*0.5;
Cz := zMax + Front;
// Opposite corners of parallelepiped.
p3Min.InitStill(xMin, yMin, zMax);
// Defining the 3D scene.
p3Max.InitStill(xMax, yMax, zMax);
xMinSter := p3Min.LeftEye.x;
xMaxSter := p3Max.RightEye.x;
xSpan := xMaxSter - xMinSter;
yMinSter := p3Min.LeftEye.y;
yMaxSter := p3Max.RightEye.y;
ySpan := yMaxSter - yMinSter;
end;

Figure 7: Setting up the basic parameters of a 3D scene.

2) The proportional parallelepiped of the 3D scene corresponding to the physical sizes of your local macro-world:
your 2D screen, the distance from you to that screen,
and the distance between your eyes, say in cm. In this
scale, the 3D scene is to be projected onto the 2D plane
of your screen. The values x and y in the type T2DPoint
represent the coordinates of this screen.
3) The proportional logical screen, Canvas, with sizes and
points in pixels, corresponding to that physical 2D screen.
The simplest projection method for points (x,y,z) in 3D space
onto a 2D coordinate plane XOY, is such that projecting rays
are all parallel to the OZ axis (as if the viewing point were at

Sound+Vision

3D Delphi

procedure T3DPoint.SetRightLeft;
var
Kz : extended;
begin
Kz := Max(- z + Cz, Front);
RightEyeProj.x := Cx-Base+Dist*(x-Cx+Base)/Kz;
LeftEyeProj.x := Cx+Base+Dist*(x-Cx-Base)/Kz;
RightEyeProj.y := Cy+Dist*(y-Cy)/Kz;
// y values always equal for both projections.
LeftEyeProj.y := RightEyeProj.y
end;

Figure 8: Computing perspective projections for each eye.

function RealToIntPoint(const x1, y1: extended;


const Rct: TRect): TPoint;
begin
// xMinSter,... yMaxSter represent overlapped stereo
// pair screen.
with Rct do
Result := Point(Round((x1-xMinSter) /
xSpan*(Right-Left))+Left, Round((yMaxSter-y1) /
ySpan*(Bottom-Top))+Top) // OY axis up.
end;

Figure 9: Scaling points to a canvas.

an infinite distance). Then the projection process is simply


reduced to omitting the coordinate z so that (x,y,z)(x,y). In
perspective projection, however, the rays from different points of
the scene arent parallel: they converge in the center of an eye
lens (or in the lens of a camera), mapping the 3D coordinates
onto the 2D screen (film/retina). These 2D coordinates may be
obtained via solution of similar triangles. Note: Its during this
projection process that 3D information is lost; all points on each
projecting ray in 3D space are mapped to just one point.
The important variables for specifying the 3D scene are
shown in Figure 6. The Set3DParams procedure shown in
Figure 7 uses these variables to set up the basic parameters
of the 3D scene. The procedure in Figure 8 computes perspective projections for a given point (x,y,z) onto each of
the two plane images designated for the corresponding eyes.
Real type points of the type T2DPoint are intended for mapping
onto a Canvas of a target object, hence they must be scaled
to the sizes of that Canvas (see Figure 9). The scaling is performed by a function. Here Rct defines the rectangular area of
the screen (see Figure 10), proportional to the real type rectangular area [xMinSter..xMaxSter, yMinSter..yMaxSter] containing
the two overlapped images of the stereo pair, where:
xSpan = xMaxSter-xMinSter
ySpan = yMaxSter-yMinSter

Thus the function linearly transforms the real type coordinates into the values applicable to Canvas.Pixels with the axis
OY directed traditionally down-up. For example, the procedure in Figure 11 draws a stereo line between points p and q.
Having this, we can write a procedure that draws a triangular facet (of a polyhedron) with a certain gray color, i.e.
a certain level of half-tone Red and Blue. Now were ready
for stereo triangulation of a given surface in 3D space (surfaces are beyond the scope of this article however). Here
8

DELPHI INFORMANT MAGAZINE | January 2004

Figure 10: The overlapping Blue and Red images inside the rectangular area on
canvas of the form designated for the stereo pair.

procedure StereoLine(const p, q: T3DPoint;


const Cnv: TCanvas; const Rct : TRect);
var
a, b : TPoint;
begin
with Cnv do begin
// First x,y belong to RightEyeProj,
second - to RealToIntPoint }
with p, RightEyeProj, RealToIntPoint(x, y, Rct) do
a := Point(x,y);
with q, RightEyeProj, RealToIntPoint(x, y, Rct) do
b := Point(x,y);
Pen.Mode := pmMerge; // OR mode for pen }
Pen.Color := RightColor; PolyLine([a, b]);
with p, LeftEyeProj, RealToIntPoint(x, y, Rct) do
a := Point(x,y);
with q, LeftEyeProj, RealToIntPoint(x, y, Rct) do
b := Point(x,y);
Pen.Color := LeftColor; PolyLine([a, b])
end
end;

Figure 11: Drawing a stereo line between two points.

were going to deal with special curves only solutions of


ordinary differential equations, integrated into the frame of
an all-in-one package named the Taylor Center (for more
information, read Differential Equations in the March 2002
Delphi Informant). The points of the curves are computed
via the Taylor expansion, as explained in that article.
Playing with the DEMO Application
The DEMO application is a limited version of the Taylor
Center intended for the integration of ordinary differential
equations. It also features a variety of examples, including
several in 3D stereo, illustrating the principles of anaglyphic
stereo. To install DEMO, just unzip it into an empty folder.
Now run TCenter.exe. From the menu, select Demo | Three Bodies | Disturbed | 3D: it opens the corresponding script and compiles the problem. After clicking OK to the message Compilation successful the results appear as knotty Red and Blue
curves (see Figure 12). Now put on your anaglyphic glasses
(over those you usually use, if any) and get ready to have
fun. Its recommended to maximize the Graph window.

Sound+Vision

3D Delphi

What Youll Need to Play


Along at Home

Figure 12: The DEMO application in action.

What you hopefully perceive would look like a fishing string


hanging in thin air between the monitor and your face. These
are trajectories of three bodies moving under gravitational pull.
More specifically, this is a so-called disturbed Lagrange case.
(The Lagrange case proper is when three equal masses are
placed at vertices of an equilateral triangle with initial velocity
vectors comprising also a co-planar equilateral triangle, available by selecting Demo | Three Bodies | Symmetrical.) This fishing
string is a result of small disturbances applied perpendicularly
to the initial plane, i.e. the plane of your screen.
However, the program is capable of producing more than still
images. The Play button initiates the 3D stereo, animated,
real-time motion of the bullets representing the three bodies
with all their accelerations, decelerations, and coupling.
When they come to a stop, you can explore the elements of
the trajectories with a tactile 3D cursor. Move it into the
scene, where it transforms into a small cross. The mouse
by itself always moves in a plane parallel to the screen. To
control its depth, you have to move the mouse and simultaneously depress either C to bring the cursor closer to your
eyes or S to move it away from you. The current 3D
coordinates always appear on the top window panel.
Now, moving the mouse and helping yourself with C or
S, try to touch one of the trajectories in space with the
3D cursor. If your speakers are on, you will hear a clicking
sound when the touch occurs. This audio feedback will help
you explore points of interest in the curves.
You can turn the curves in the space with the Turns controls.
However, with the given specific sizes of the parallelepiped,
youll notice that the front side (controlled by zMax value)
prevents the curves from escaping and flattens them.
(Therefore increase zMax).
Once youre familiar with the 3D stereo features of the package, you can try several other problems. Click Main panel on
the menu to re-visualize the main form, and select Demo |
Four Bodies. The two pairs of bodies with equal masses are
all initially placed in a horizontal plane parallel to your desk
(perpendicular to the screen). The horizontal components of
the velocities provide near circular motion for each coupled
pair, while the small vertical components push the two pairs
9

DELPHI INFORMANT MAGAZINE | January 2004

To watch the effects described in the article and displayed


by the software, you will need a pair of Red/Blue glasses,
which are easily obtainable at very low cost, e.g. one
source is www.reel3d.com for 50 cents. Also, you must
have relatively healthy eyes capable of stereopsis, i.e. the
ability to naturally fuse two plane images comprising a
stereo pair into a 3D scene. Most people do (this is not
to be confused with fusing so called auto-stereograms). If
you have ever watched a stereo movie through polarized
or electronic shutter glasses, or have seen a hologram
pop out into space, your stereopsis is okay.
Alex Gofen
into a large circular motion around the center of the masses
(you can see the initial data in the Main window). At the
beginning, the trajectories spin into a braid that looks like
a torus (and like the newly discovered rings of Saturn shot
by the Voyager probe), but the braid isnt a true torus; you
can see that the velocities in both coupled pairs preserve
their initial horizontal orientation. This fact can be obtained
mathematically, but here you can simply watch it.
Finally, you can explore more 3D stereo examples by opening them as scripts. Click Main panel and select File | Open
Script. The following files produce 3D stereo images:
PendulumApple.scr (a model of spherical pendulum)
PendulumFlower.scr
KnotChain3D.scr
TrefoilKnot3D.scr
Mobius.scr
MobiusLarge.scr
Conclusion
Anaglyphic display is the simplest, most efficient way to
implement stereo vision on conventional PCs. It produces
almost uncompromised stereo effect requiring nothing more
than the natural ability of the stereopsis in viewers. Its the
best choice for displaying monochromatic stereo images.
In this article weve considered 3D stereo anaglyphic display
for points, non-planar curves, and straight lines only. However, these basic elements also make it possible to construct
surfaces, the elements of which are random dots, or random
texture, or parametric curvilinear coordinate grids, or triangles of a triangulation grid.
The DEMO program referenced in this article is available for
download on the Delphi Informant Magazine Complete
Works CD located in INFORM\2004\JAN\DI200401AG.

Alexander Gofen is a programmer at the Smith-Kettlewell Eye Research Institute


in San Francisco, CA (www.ski.org), where he has worked since 1995. Previously,
he was a senior researcher for the Institute of Computer Science (Academy of
Sciences, Russia) and Hydro-Meteorological Center in Moscow, Russia. Gofen has
been developing scientific applications in all versions of Delphi and Borlands
Pascal, varying from the Numeric Weather Forecast and the Taylor Solver to the
Macula Mapping Test (Eye Research Institute). You can reach him by phone at
(415) 345-2119, by e-mail at [email protected], or by visiting www.ski.org/gofen.

. N E T
.NET FRAMEWORK

T E C H

RESOURCES

DELPHI FOR .NET COMPILER PREVIEW

By Fernando Vicaria

Delphi for .NET Resources


An Introduction to Their Creation, Conversion, and Use

he .NET Framework introduces new ways for


developers to create and use resources in .NET
applications. The .NET SDK provides tools to

help you build these resources via the command line.


In this article well learn how to take advantage of
all that the .NET Framework and the .NET SDK has
to offer. Well be using the Delphi for .NET Compiler
Preview (update 4) in our examples. (We will not,
however, get into the details of one very important
application of resources in .NET: Localization. To learn
more about this subject check the MSDN Web site.)
Lets start by getting to know what the .NET Framework has
to offer in terms of classes dedicated to resources creation
and manipulation. These classes can be found inside the
System.Resources namespace.
The System.Resources namespace provides classes and
interfaces that allow developers to create, store, and manipulate
various culture-specific and graphic resources used in
an application. One of the most important classes of the
System.Resources namespace is ResourceManager, which allows
the user to access and control resources stored in the main
assembly or in resource satellite assemblies. Use the
ResourceManager.GetObject and ResourceManager.GetString
methods to retrieve culture-specific objects and strings.
Generate a .resources File in Code
The example in Figure 1 shows how to use the ResourceMaker
class from the System.Resources namespace to create a
.resources file, add a few resources, and use them in a separate
application. The ResourceMaker class writes resources in the
system-default format to an output file or an output stream.
ResourceWriter provides a default implementation of the
IResourceWriter interface.
10

DELPHI INFORMANT MAGAZINE | January 2004

Resources are specified as name/value pairs using the


AddResource method. Resource names are case-sensitive when
used for lookups. However, to more easily support authoring
tools and help eliminate bugs, ResourceWriter wont allow a
.resources file to have names that vary only by case.
To create a resources file, create a ResourceWriter with a
unique file name, call AddResource at least once, call Generate
to write the resources file to disk, and then call Close to
close the file. Calling Close will implicitly Generate the file if
required. Note: The resources wont necessarily be written in
the same order they were added.
The example in Figure 1 creates a resources file named
MyRes.resources that contains three graphical resources
(an icon, a cursor, and a bitmap) and a couple of strings.
We could create different .resources for different lan-

program ResMaker;
{$APPTYPE CONSOLE}
uses
System.Resources, System.Drawing, System.Windows.Forms;
var
rw: ResourceWriter;
b: Bitmap;
i: Icon;
c: Cursor;
begin
rw := ResourceWriter.Create('MyRes.resources');
b := Bitmap.Create('HANDSHAK.BMP');
I := Icon.Create('house.ico');
c := Cursor.Create('handpnt.cur');
rw.AddResource('HANDBMP', b);
rw.AddResource('MAINICON', i);
rw.AddResource('MAINCURSOR', c);
rw.AddResource('string 1', 'First String');
rw.AddResource('string 2', 'Second String');
rw.Generate;
rw.CLose
end.

Figure 1: Generating a .resources file in Delphi for .NET.

.NET

Te c h

Delphi for .NET Resources

program ResXMaker;

program ResXReader;

{$APPTYPE CONSOLE}

{$APPTYPE CONSOLE}

uses
System.Resources, System.Drawing;

uses
System.Resources, System.Collections;

var
rxw: ResXResourceWriter;
b: Bitmap;

var
rsxr: ResXResourceReader;
id: IDictionaryEnumerator;

begin
rxw := ResXResourceWriter.Create('MyResX.resx');
b := Bitmap.Create('HANDSHAK.BMP');
rxw.AddResource('HANDSHAK', b);
rxw.Generate;
rxw.Close
end.

begin
// Create a ResXResourceReader for the file MyResX.resx.
rsxr := ResXResourceReader.Create('MyResX.resx');
// Create an IDictionaryEnumerator to iterate through
// the resources.
id := rsxr.GetEnumerator;
Console.WriteLine;
Console.WriteLine(' Name ' + #9#9 + ' Type');
Console.WriteLine(
' ====================================');
// Iterate resources; display contents to console.
while id.MoveNext do
Console.WriteLine(' ' + id.Key.ToString + #9 +
id.Value.GetType.FullName);
Console.WriteLine(' ====================================');
rsxr.Close; // Close the reader.
end.

Figure 2: Generating a .resx file in Delphi for .NET.

guages and locales to avoid having to compile the project


multiple times, or having to recompile it every time any
of these resources changed.
Note: The ResourceWriter class is specifically designed to
create .resources files. Remember that you can save objects
only in .resources and .resx resource files. Only resource
files in the .resources file format should be embedded in a
run-time executable or compiled into a satellite assembly.
You can use the ResourceWriter class directly from code, or
as well see in this article, use the Resource File Generator
(ResGen.exe) to create .resources files.
Visit http://msdn.microsoft.com/library/
default.asp?url=/library/en-us/cpguide/html/
cpconresourcesinresourcesfileformat.asp for more
information on the actual structure of a .resources file format.
Generate a .resx File in Code
In the same way we generate a .resources file with
ResourceWriter we can create a .resx file with the
ResXResourceWriter class.
A .resx resource file format consists of XML entries, which
specify objects and strings inside XML tags (see Figure 2).
One advantage of a .resx file is that when opened with a text
editor (such as Notepad or Microsoft Word) it can be written
to, parsed, and manipulated. When viewing a .resx file, you
can actually see the binary form of an embedded object (a
picture for example) when this binary information is a part
of the resource manifest. Apart from this
binary information, a .resx file is completely readable and maintainable.
Note: Once created, you can manipulate a .resx file directly. However, to
avoid corrupting the file, be careful
not to modify any binary information that is stored in the file. Visit
http://msdn.microsoft.com/library/
default.asp?url=/library/en-us/cpguide/
html/cpconresourcesinresxfileformat.asp
for more information on the actual
structure of a .resx file format.
11

DELPHI INFORMANT MAGAZINE | January 2004

Figure 3: Reading the contents of a .resx file in Delphi for .NET.

Reading Resources in Code


To read the resources created in Figures 1 and 2, we
use the classes ResourceReader and ResXResourceReader
for reading XML and binary resources, respectively.
The example in Figure 3 shows how to retrieve all the
resources in a .resx file using an IEnumerator interface
descendant. As the base interface for all enumerators, the
IEnumerator interface supports a simple iteration over a
collection. Enumerators only allow reading the data in the
collection, and cannot be used to modify the underlying
collection.
Figure 4 shows a typical output of the ResXReader project.
Note that the resources file that is read is hard-coded. A
more useful application would request the name of the
.resx the user wants to inspect, but Ill leave that to you.
We can achieve exactly the same results with the
ResourceReader class and a .resources file, but this too I
will leave to you as an exercise.

Figure 4: ResXResder.dpr project output.

.NET

Te c h

Delphi for .NET Resources

{$R MyRes.resources}
procedure TMainForm.InitComponents;
var
asmb: Assembly;
rm: ResourceManager;
begin
SuspendLayout;
Text := 'Using a *.resources file';
AutoScaleBaseSize := TSize.Create(5, 13);
ClientSize := TSize.Create(500, 500);
Button1 := TButton.Create;
Button1.Top := 5;
Button1.Left := 5;
Button1.FlatStyle := FlatStyle.System;
Button1.Text := 'Load Bitmap';
Button1.Add_Click(Button1Click);
Controls.Add(Button1);
asmb := Assembly.GetExecutingAssembly;
rm := ResourceManager.Create('MyRes', asmb);
Icon := TIcon(rm.GetObject('MAINICON'));
Cursor := TCursor(rm.GetObject('MAINCURSOR'));
FImageRes := TBitmap(rm.GetObject('HANDSHAK'));
FStrRes := string(rm.GetObject('string1'));
ResumeLayout(False);
end;

Figure 5: UseResources.dpr project.

Using ResGen
Now that weve seen how to generate and retrieve resources in both XML and binary formats, its time to find out
how we can generate these resources using some of the
tools the .NET SDK provides. The first one is the Resource
File Generator (or ResGen.exe). The Resource File Generator converts .txt files and .resx (XML-based resource format) files to common language run-time binary .resources
files that can be embedded in a run-time binary executable
or compiled into satellite assemblies.

Figure 6: Loading resources from an embedded .resources file in Delphi for .NET.

files. The following ResGen.exe command creates the resource


file MyRes.resources from the input file MyRes.resx:
C:\>resgen MyRes.resx

The following command creates the .resx file, items.resx, from


the input file, items.resources. Note that in converting a .resx
file to a .resources file, all objects are preserved:
C:\>resgen items.resources items.resx

The following ResGen.exe command creates the resource file


MyStrings.resources from the input file MyStrings.txt (when
ResGen.exe reads a text file, the comments are lost and wont
be written to the resulting .resources or .resx file):
C:\>resgen strings.txt

If you want the name of the output file to be different from


the input file, you must explicitly specify the name of the
output file. The following command creates the resource file
MyApp.resources from the input file MyStrings.txt:
C:\>resgen MyStrings.txt MyApp.resources

The following command creates a text file, MyStrings.txt,


from the input file MyStrings.resources. Note that you should
perform this type of conversion only on a .resources file that
contains only strings; object references cannot be written to the
.txt file, and will be ignored:
C:\>resgen MyStrings.resources MyStrings.txt

ResGen.exe can also convert .resx files into .resources files


by wrapping the methods implemented by the ResourceWriter
class. ResGen.exe also wraps a ResourceReader, which allows
you to use the tool to convert .resources files back into .resx
12

DELPHI INFORMANT MAGAZINE | January 2004

Using ResXGen
The ResX Generator (ResXGen) is another console utility provided by the .NET SDK that converts an image file (such as a
.jpg or .bmp file) into an XML-formatted .resx file, which, as
we saw earlier, can then be compiled into a .NET-compatible
.resources files using ResGen.exe. This is a very simple tool that
wraps a ResXResourceWriter class; in fact, I find it very limiting
for any practical purpose, but for the sake of completeness I will
quickly describe it and then name a few alternatives.
The following command will add the icon MyIcon.ico into the
resource file MyRes.resx with the internal name of MAINICON:
C:\>resxgen /i:MyIcon.ico /n:MAINICON /o:MyRes.resx

There are a couple of freely available alternative tools that will


allow you to create and edit .resx files:
Resourcer. This is an editor for .resources binaries and .resx
XML file formats used with the Microsoft .NET platform.
The program allows the integration of bitmaps, icons, and
text strings into resource packages. It allows editing of
name/string pairs, import of various data formats (bitmaps,
icons, etc.), and merging of resources from different sources.
Viewers for bitmaps, icons, and cursor images are included.
The source code is available in a separate archive.

.NET

Te c h

Delphi for .NET Resources

ReXBuilder. This is one of the examples included


with the Borland C#Builder development tool. I am
including with the files for this article the executable
(designed in C#). Get C#Builder, or wait for Delphi 8 if
you want the source.

This will link the specified .resources into the project


executable (the same way Delphi 7 would do with Win32
resources). Once the project is compiled, you wont
need to include the .resources file with your application,
because its now part of the executable.

Using the .resources File in Delphi


for .NET Applications
Now that we know how to create a .resources file, in code
or using the command line, lets see how we use these
resources in our applications.

The Assemblys Manifest File


When you make your application, it is housed in an assembly.
An assembly consists of the following (see Figure 7):
Assembly Manifest. Describes assembly name and
version information, enumerates files that make up
the assembly, maps types in the assembly to files containing implementation, and enumerates other assemblies on which this assembly depends. The manifest is
a mandatory part of all .NET assemblies.
Type Metadata. Describes types contained in the assembly, such as classes, interfaces, methods, etc. Its automatically bound into the assembly. This is an optional
part of an assembly.
Microsoft Intermediate Language (MSIL). Code that
implements types in the assembly. Also optional.
Resources. Resources that can be used by the application. These can include strings, bitmaps, icons, sound
files, etc. It can be embedded or linked. Its an optional
part of a .NET assembly.

Well build two simple WinForms applications that use a


.resources file to load an icon, cursor, and bitmap, and use
it in its main form. The first example will have a .resources
file as a standalone file. The second will have it embedded
in the main assembly.
Listing One (on page 15) shows how to load and use graphic and string resources from the .resources file generated by
the ResMaker.dpr project (MyRes.resources). Figure 5 shows
the project at run time.
Having the resources for your application included in a
standalone file can be handy in situations such as when
you have to distribute your application to multiple locales
and use different languages. This would, for example,
preclude you from having to recompile your project every
time you decided to support a new language.
On the other hand, if localization isnt an issue for you,
and you prefer to have your application condensed into
a single file, you can simply embed all the .resources
files into your main assembly (.exe or .dll). The example
shown in Figure 6 demonstrates how to do this.
As you can see, the main difference is that, instead of storing the resources read from the separate .resources file into
a hash table, we now can use them directly by loading the
appropriate embedded resource from the running assembly
using the Assembly class from the Reflection namespace.
Also note that we added the following line at the top of
the project source code:
{$R MyRes.resources}

Figure 7: A typical .NET assembly.

13

DELPHI INFORMANT MAGAZINE | January 2004

Although the assembly manifest is the only required item


from the list, types and resources are usually needed to
give the assembly any meaningful functionality. The set
of resources is completely optional. When you compile
your application the manifest becomes part of an assembly, which is referred to as the main assembly.
Any code aspects of your application are part of this main
assembly. As we learned before, if you change any code
in this main assembly, you must recompile the entire
assembly. This can mean a lot of work redistributing your
application.
There are two ways to provide your assembly with a manifest.
One is by building it into your application. The other is by creating a separate .manifest file and placing it in the same directory of your application executable.
Just as we did with the .resources file, well see how to
provide a standalone manifest to the UseResources.dpr

Figure 8: UseResources.exe assembly viewed with ILDasm.

.NET

Te c h

Delphi for .NET Resources


This will generate a file named
MyManRes.res. Add this file as a
resource into your project by adding
the following line to the top of the
source code:
{$R MyManRes.res}

Now compile and run your project.


The manifest file is now part of
the executable. To confirm that this
or any other resource has been
added into your assembly, you can
use ILDasm to inspect its contents.
Figure 8 shows the UseResource
project being inspected with ILDasm.
Figure 9 shows the manifest and the
resource declaration in MSIL.

Figure 9: UseResources.exe manifest viewed with ILDasm.

project, as well as how to modify it so we can embed the


manifest file as a resource inside the assembly.
All we need to do to add a manifest to our .NET application
as a standalone file is to create a manifest file and give
it the exact name of our applications main assembly,
including the extension. For example, our UseResources.exe
would need a manifest named UseResources.exe.manifest.
Try running the example with and without the manifest file
to see if you spot the differences.
If we want to embed the manifest inside the assembly,
well first need to create a .rc file, and compile it into a
traditional Win32 resource file. The contents of the .rc file
are shown here:
1

24

"UseResources.exe.manifest"

The number 1 denotes the resource id; 24 denotes the resource


type (or RT_MANIFEST).
Compile the .rc file with brc32.exe that comes with Delphi 7 (or any other Win32 resource compiler). Use this
command if you are using brc32:
C:\>brc32 MyManRes.rc -r -32

14

DELPHI INFORMANT MAGAZINE | January 2004

Conclusion
This concludes our look into the basics
of how to use resources in .NET with
the Delphi for .NET Compiler Preview.
We learned how to create .resources and
.resx files in code, and how to use the
two resource generator tools provided
by the .NET SDK: ResGen and ResXGen. Finally, we looked
into ways of adding a manifest to our .NET applications as a
standalone file or compiled into the assembly as a resource.
Theres a lot more that can be done with resources in .NET,
and the Framework provides many ways for you to write and
retrieve resources in your assemblies. For more ideas, check
out these references:
MSDN Library: http://msdn.microsoft.com/library/
default.asp
Working with Resource Files: http://
samples.gotdotnet.com/quickstart/aspplus/doc/
resourcefiles.aspx
Lutz Roeders .NET Resourcer: www.aisto.com/
roeder/dotnet/
The files referenced in this article are available for download
on the Delphi Informant Magazine Complete Works CD
located in INFORM\2004\JAN\DI200401FV.

Fernando Vicaria is also a freelance technical author for Delphi and


C++Builder issues. Fernando specializes in VCL and CLX frameworks.
When hes not at work hes probably surfing at some secret spot in Northern
California.

.NET

Te c h

Delphi for .NET Resources

Begin Listing One Loading resources


from a standalone .resources file in
Delphi for .NET.
program UseResources;
uses
System.Collections, System.Resources, System.Drawing,
System.Windows.Forms;
type
{ .NET to
TForm
=
TButton =
TCursor =
TIcon
=
TSize
=
TBitmap =

VCL mapping }
System.Windows.Forms.Form;
System.Windows.Forms.Button;
System.Windows.Forms.Cursor;
System.Drawing.Icon;
System.Drawing.Size;
System.Drawing.Bitmap;

type
{ Application main form }
TMainForm = class(TForm)
private
FImageRes: TBitmap;
FStrRes: string;
Button1: TButton;
procedure InitComponents;
procedure Button1Click(Sender: TObject;
Args: EventArgs);
public
constructor Create(Owner: TObject);
end;
function LoadResource(resFile: string): HashTable;
var
rr: ResourceReader;
resTbl: Hashtable;
de: IDictionaryEnumerator;
begin
try
resTbl := Hashtable.Create;
rr := ResourceReader.Create(resFile);
de := IDictionaryEnumerator(rr.GetEnumerator);
while IEnumerator(de).MoveNext do
resTbl.Add(de.Key,de.Value);
rr.Close;
Result := resTbl;
except
on Exception do
Result := nil;
end;
end;

15

DELPHI INFORMANT MAGAZINE | January 2004

{ TMainForm }
constructor TMainForm.Create(Owner: TObject);
begin
inherited Create;
InitComponents;
end;
procedure TMainForm.InitComponents;
var
resTbl: HashTable;
begin
SuspendLayout;
Text := 'Using a *.resources file';
AutoScaleBaseSize := TSize.Create(5, 13);
ClientSize := TSize.Create(500, 500);
Button1 := TButton.Create;
Button1.Top := 5;
Button1.Left := 5;
Button1.FlatStyle := FlatStyle.System;
Button1.Text := 'Load Bitmap';
Button1.Add_Click(Button1Click);
Controls.Add(Button1);
try
resTbl := LoadResource('MyRes.resources');
Icon := TIcon(resTbl['MAINICON']);
Cursor := TCursor(resTbl['MAINCURSOR']);
FImageRes := TBitmap(resTbl['HANDSHAK']);
FStrRes := string(resTbl['string1']);
except
// Ignore if resource isn't there or file wasn't found.
on NullReferenceException do ;
end;
ResumeLayout(False);
end;
procedure TMainForm.Button1Click(Sender: TObject;
Args: EventArgs);
begin
BackgroundImage := FImageRes;
MessageBox.Show('String resource is: ' + FStrRes);
end;
var
MainForm: TMainForm;
[STAThread]
begin
MainForm := TMainForm.Create(nil);
Application.Run(MainForm);
MainForm.Free;
end.

End Listing One

I N

D E V E L O P M E N T

SOFTWARE PROCESS MANAGEMENT

REQUIREMENTS

MODELING

By Steven Beebe & Xavier Pacheco

Between Rigidity and Chaos


Practical Software Process Management: Part I

oftware process management today too


often falls to one of two extremes. No doubt,
youve experienced one of them:

1) Highly structured and rigid processes with an oftentimes


religious fervor for documentation and adhering to the
prescribed process. These processes are often communicated through reams of printed documentation or hours
of training/online reading material and may have their
origins from deep within academia.
2) Ad hoc processes. Perhaps too dignified a term for what
usually occurs, which is little more than seat of the pants
survival by responding to the crisis du jour. These processes are exemplified by their battle-scarred heroes and
are often born out of frustration or fear of approach #1.
It is this state of affairs that makes software process management a generally unwelcome topic in many development organizations. In the first case, developers cant
handle one more demand from the process, or the production of code will grind to a complete standstill if it
hasnt already. In the second case, the haggard organization is afraid that stopping to even consider process management will derail them from extinguishing the current
blaze, resulting in everyone being out of a job.
Regardless of where you are on the continuum between
rigidity and chaos, software process management is what
enables you to deliver. It is in fact what you do each day, if
not planned then de facto. And if done in a manner appropriate for your circumstances, will get you to market faster
with more of your sanity intact.
16

DELPHI INFORMANT MAGAZINE | January 2004

Over the next several issues, we will walk through a practical approach to software process management thats
designed to improve your success at delivering on project
objectives achieving time-to-market with the appropriate
Methodology

Establishing the overall approach to be taken;


the set of processes and supporting techniques
to be used in software development.

Requirements

Identifying the capability to be delivered;


what the software is to do.

Modeling

Conceptualizing portions or aspects of the


solution in non-narrative form.

Change
Management

Process for proposing, assessing, and


approving changes to requirements, and
other agreed upon parameters of the project.

Configuration
Management

Maintaining product structure, product


and file level versions, and coordinating
concurrent development.

Build
Management

Ensuring required components are available


and put together in the proper sequence in
light of dependencies.

Quality Assurance
Management

Managing the achievement of the quality


goals for the project.

Defect
Management

Managing the identification and resolution of


requirements not correctly implemented.

Project/Schedule
Management

Identifying the project in terms of stages or


phases of activities. Not to be confused with
managing requirements, changes, or defects.
This is listed last on purpose; dont start here!

Figure 1: Software process management components.

In

Development

Between Rigidity and Chaos

quality level, and managing project lifecycle costs. A practical approach is one that is at neither extreme, nor suggests
a one-size-fits-all solution. And it cant be practical if it isnt
within both the budget and the bandwidth of virtually every
software development team.

ogy will yield results, this is precisely the practical software


development managers approach to improved performance.
The practical approach recognizes that 80% of the benefit
comes from 20% of the effort, and that no single philosophical approach has a monopoly on success.

Im a Developer, Why Do I Care?


So why are we addressing this topic to a community of
developers? Its because the developer is typically the one
who feels the pain from lack of or excessive process. Its
also the developer, particularly seasoned developers, who
are in a position to influence the adoption of sound and
practical process management practices.

In pursuing the practical approach to methodology, well


look at assessing your organizational and business situations, and your past performance. Then well construct a
methodology by taking the pieces from various approaches that are suited to your circumstances. In brief, its
choosing the right tool for the job.

Software Process Management


Components
Software process management is comprised of a number of
components (see Figure 1). In this article, we provide an
overview of these components and in subsequent issues will
spend more time in each area. As we review each component in more depth, the goal is to guide you in identifying
areas for improving your teams performance that can be
done within your bandwidth and budget.

Requirements
Requirements management is the process of eliciting,
capturing, and validating the capabilities to be delivered.
Requirements represent the various interests of the projects stakeholders, and as such, correctly capturing and
implementing requirements is critical to project success.
Types of requirements for a given project may include:
Business requirements the business objectives to be
accomplished through the execution of the project
Features or Marketing requirements the high-level
description of the services the product will provide
Software requirements the functionality to be provided by the product, as well as non-functional attributes of the solution

Methodology
A methodology represents the philosophical approach to be
taken in software development, and embodies the set of processes and practices to be used
throughout the development
Requirements management proThe practical approach
lifecycle. This philosophical
cesses vary widely in their rigor
recognizes that 80% of the
aspect of methodology makes
and approach, primarily driven by
benefit comes from 20% of
it the area of software developthe philosophy of the methodolment process management most
ogy being employed. Requirements
the effort, and that no single
likely to generate religious zeal
may be captured in a Software
philosophical approach has a
regarding alternative approachRequirements Specification documonopoly on success.
es. Its also the area most likely
ment, containing narrative descripto strike fear in the heart of the
tions of business, marketing, and
practical software development manager as methodologies
software requirements, complete with supporting use cases.
have a reputation for being academic. Methodology propoIn more lightweight methodologies, requirements may be capnents have a tendency to offer the exclusive answer for fast
tured as simple one-sentence statements and sequenced for
time-to-market and staying on budget, and quite often only
inclusion in frequent deliverables.
promise results if you follow the methodology in its entirety.
The level of documentation and clarity necessary in a products
The Rational Unified Process and the Agile methodology are
requirements depends on a number of factors. Incorrectly
excellent examples of clearly articulated and rich methodoloassessing the need for rigor in requirements gathering can lead
gies covering the full development lifecycle. Meta-methodoloto disaster in either direction of the error. If the degree of rigor
gies, such as the Capability Maturity Model (CMM) from the
is over-estimated, precious time and resources will be lost in
Software Engineering Institute (SEI), and ISO 9000-3 from the
compiling unnecessary documents and diagrams. If underestiInternational Organization for Standardization (ISO), are also
mated, stakeholder frustration and user acceptance issues may
available to guide methodology development. Meta-methodolothreaten the future of your project.
gies differ from methodologies in that they identify the processes and capabilities needed, rather than the specific approach
As with methodologies, well look at the factors that deterused to execute the process or provide the capability. For exam- mine the level of rigor required by your project, and discuss
ple, CMM will outline what is to be covered in a requirements
practical techniques for gathering requirements as a foundadocument, but does not prescribe how to gather requirements.
tion for project success.

A significant percent of teams have neither the time nor the


budget to fully absorb most methodologies, so you might
be lead to believe these teams are doomed to fail. However, this is far from the case. Although its rare that a well
developed methodology will suggest that incremental or
opportunistic adoption of key principles from the methodol17

DELPHI INFORMANT MAGAZINE | January 2004

Modeling
Modeling is a key software development practice thats receiving much attention these days in the press, with a focus on
Model Driven Architecture (MDA). The Object Management
Group (OMG) has established a specification for MDA (see
www.omg.org/mda), and software tool vendors, including

In

Development

Between Rigidity and Chaos

Microsoft and Borland, are increasingly supporting Model


Based Development. Much of this thinking is oriented toward
having high-level models that are defined in increasing levels of
detail that ultimately result in code being generated.
For many software development teams, this extensive use of
modeling is frankly impractical. This does not mean, however,
that modeling isnt relevant in practical software development
management. Modeling adds clarity and improves communication concerning system architecture, design, and use. Since a
model is a simplified representation of a more complex reality,
modeling is also helpful in wrapping your mind around a complex software problem.
Modeling tools are available at reasonable cost to support these
activities, without requiring the wholesale adoption of any particular approach. Architecture, sequence, use case, and process
diagrams are well supported in cost effective tools. Additionally, significant productivity and effectiveness in managing data
models and database design can be gained through easy-touse and cost effective tools. Based on your project objectives,
selecting the right models and supporting tools will improve
your performance and not break your budget.
Configuration Management
Cant compile the version of the product for which you just
received a critical defect report? You know youve fixed this
problem before, but the changes just arent there? Configuration Management addresses the needs of managing multiple
product versions being worked on by multiple developers.
Of all the areas of software process management, configuration management (CM) is the area for which most teams have
established a working solution. The widespread use of CM
practices can be attributed to a number of factors:
the availability of credible low- or no-cost tools,
the need for concurrent development by multiple team
members,
the need for development on multiple versions of code, and
the high level of pain from the absence of reasonable CM
practices.
The objective of CM is to provide an electronic repository for
project documents, source files, and other electronic artifacts.
The repository should enable concurrent development, exclusive development, merging of concurrent development, version
history, comparison of different versions of files, labeling a set
of files for identifying, and working on previous builds. CM
preserves the integrity of project assets, while increasing productive collaboration and team communication.
CM solutions range from primarily procedural, relying on the
structured use of directories, to sophisticated tools providing
code-level traceability of changes. If you are lacking a CM solution commensurate with your needs, this is most likely where
you will see the fastest return for your investment.
Build Management
Customers cant install the latest release? Forgot to include the
correct version of the help file? You need to spend some time
on build management. While build management can be treated
as an area on its own, we will be handling it within the con18

DELPHI INFORMANT MAGAZINE | January 2004

text of Configuration Management. Build management is the


mechanical process of producing a specific version or build of
a product. A practical process will ensure that the correct version of all necessary files are included, and will likely provide a
level of productivity through automated tools.
Change Management
In life, change is inevitable. In software, if you think
things have stopped changing, check your pulse, you may
be dead. Some people would prefer this area to be called
Change Prevention, but with the fast pace of technological
and business change today, change prevention will most
certainly lead to product failure. Change simply cannot be
avoided. No matter how sound your requirements gathering
process is, clarity will be gained as a product begins to take
shape, to become more concrete. And this clarity will lead
to changes to the original requirements.
Change management differs from defect management in that
a change request is asking that a requirement be re-written
or modified, whereas a defect is a report of the software not
performing per requirements. (Some may argue that a request
to modify a requirement is a requirement defect. While this is
an entirely defensible position, we prefer treating requirement
modifications as change requests, and non-performance as a
defect. This allows for clear metrics on both the quality of the
requirements gathering process and the quality of requirements
implementation, i.e. architecture, design, and development.)
The goal of change management then, is to make informed
decisions concerning identified opportunities for change.
Informed decisions require understanding the cost of a
change in terms of budget and time-to-market, and the cost
of not making a change in terms of market share or competitive position. Poor change management decisions can
result in a delayed schedule that misses a critical market
opportunity, or retaining a schedule, only to deliver a product that is missing a critical competitive feature.
With so much at stake, its not unusual for there to be
emotional turmoil surrounding the change management
process. Implementing a sound process may require all
of your political skills. Project sponsors and stakeholders
will be looking for a process that ensures they can steer
the project in the direction they want it to go. Developers will be looking for a process that gives them a target
that stays still long enough to give them a decent chance
of hitting it. The needs of a practical change management process must take into account the relationships
between project sponsors, developers, and customers. A
process that fits your situation will result in collaboration
between parties with somewhat conflicting and somewhat
complementary perspectives to arrive at the best answer
for the business.
Quality Assurance Management
Defects happen; all software has defects. However, without
sound Quality Assurance practices, developers will spend the
majority of their time fixing defects rather than implementing
new functionality. To make matters worse, when the project
starts running late, its the Quality Assurance practices that are
reduced to make up for lost time.

In

Development

Between Rigidity and Chaos

Many teams have a handle on Defect Tracking with the availability of low cost tools. However, Defect Tracking is not the
only component to Quality Assurance. Testing, design reviews,
code reviews, and walkthroughs are only some of the practices
teams can employ to keep control of the overall product quality. A goal of Quality Assurance is to prevent, manage, identify,
and resolve the specific cases in which a product does not
meet relevant specifications or requirements.

tion. Without the proper balance, your project will likely be


a well organized failure.
When we take a deeper look at project management, we
cannot hope to provide thorough training on the subject, but
will walk through how to assess the level and sophistication
of project management techniques, and the tools required
by your project. Well also explore the common misapplication of project scheduling and management. The practical
approach identifies the right combination of process effort
across all components, providing a sound foundation for
solid project management to pull the overall effort together.

An effective Quality Assurance program entails a solid


understanding of product requirements, how the product is
used, strong communication skills, and a solid CM foundation. Well delve into the
area of Quality Assurance
...even the most unskilled would- Wrap-up
and discuss practices
Each of the components
be project manager [can] print a
that make sense for most
weve discussed represents
nice looking Gantt chart to hang on an important aspect of
teams, while not imposing
the wall, and thereby declare that
restrictive constraints on
practical software develthe ability to deliver highopment management.
the project has a schedule.
ly functional products.
However, not all areas
will need the same level of investment. Much of what
Project/Schedule Management
has gone wrong in software process management results
I mention project management last because it is too often
from a failure to be pragmatic; a failure to assess process
regarded as the essential capability to improve project execu- needs based on the situation and circumstances of a spetion. While project management is an important component, cific project. Achieving a higher level of sophistication in
its also subject to a great deal of malpractice. This is due in
each of these areas is very likely not the best answer for
part to the widespread availability of tools that have enabled your team. Understanding your situation and the value to
even the most unskilled would-be project manager to print
be gained from improved performance in each area will
a nice looking Gantt chart to hang on the wall, and thereby
allow you to lay out a process roadmap for your group.
declare that the project has a schedule. This of course also
Within budget and within bandwidth, anything else is
requires a supporting cast of sponsors and managers that are impractical.
ready to agree with him or her.

Re-educating sponsors and managers is not without risk,


but may be a critical task ahead of you as you seek to put
project management in the proper perspective, and deal
with project management as more than a schedule. A project schedule will identify the work to be done in terms of
stages or phases of activities, but should not be confused
with managing requirements, changes, or defects. Project
management provides the process framework for overall
work execution, identifying business objectives, constraints,
scope, stakeholders, risks, and issues. Successful project
management requires the appropriate level of competency in
the other software process management areas as a founda-

19

DELPHI INFORMANT MAGAZINE | January 2004

Steven Beebe is the chief operating officer and senior consultant with Xapware
Technologies Inc., provider of Active! Focus a practical solution for managing
a number of aspects of software projects. Steve has been developing software and
managing the development of software for over 15 years. Steves experience ranges
from managing teams from 10 to 120 professionals, in both start up and Fortune
20 companies. Steve is available for consulting engagements. You may contact him
at [email protected] or visit www.xapware.com.
Xavier Pacheco is the president and chief consultant of Xapware Technologies
Inc., provider of Active! Focus a practical solution for managing software projects
and requirements management. Xavier is the co-author of Delphi 6 Developers
Guide and has also written for publications such as Delphi Informant and Delphi
Magazine. Xavier is available for consulting and training engagements. You may
contact him at [email protected] or visit www.xapware.com.

O N

T H E

POP, SMTP, WEBDAV

N E T

HOTMAIL

E-MAIL PROXY SERVER

DELPHI 4-7

By Alfred Mirzagitov

Writing an E-mail
Proxy Server
Part I: Analyzing the HotServer Project

ve had my hotmail.com account for years. My


e-mail address at work has changed three or
four times over the years, but I am still using

the same old hotmail.com account for testing, and


backup purposes.

special ASP URL for this; the server is declared as My


mail server is an HTTP server. No such thing exists in
Eudora, or any other e-mail client application. And a
search of the Internet didnt yield any information. There
were many questions about how to use a Hotmail account
without having to use Microsoft Outlook or the Web
browser, but there were no answers.

There are advantages to using a Web-based e-mail serSo my next logical step was to write some Delphi code to solve
vice. If you travel a lot and cannot access your mail
this problem once and for all. The next few evenings I spent
server reliably, or keep changing
listening to IP packets and writing a
your Internet service providers,
This is an undocumented Delphi program. The problem had
a Web-based e-mail service can
several distinctive parts to it that are
and non-standard interface,
be very handy. Hotmail is prorelated to different Internet technoland if Microsoft Outlook
vided by Microsoft and is probogies, and I thought my experience
ably the worlds most popular
with this application could provide
isnt your software of
Web-based mailing system. It
an interesting case study for other
choice, youre out of luck.
can be irritating at times, but
programmers.
its free and very stable. In my
experience it has never been down or too slow. Of course, This two-part article series provides a small case study
a hotmail.com return address too often means that its
on how to use Delphi to handle the e-mail protocols
spam, but thats a totally different story.
POP and SMTP, WebDAV (Web Distributed Authoring
and Versioning protocol), and to write a fully functional
There are also some drawbacks to Hotmail being a Weblocal POP/SMTP proxy server for sending and retrieving
based e-mail service. You can check your e-mails only using
hotmail.com e-mails using your favorite e-mail client.
a Web browser or Microsoft Outlook. Hotmail doesnt proIt also touches on some security issues such as Internet
vide standard SMTP and POP access to its mailboxes.
Explorer security zones and filtering client connections
based on IP addresses. This month well examine the
This got me thinking about what it would take to hook
problem and technologies; next month, well implement
up my Eudora e-mail client to Hotmail. Outlook uses a
the solution.

20

DELPHI INFORMANT MAGAZINE | January 2004

On

the

Net

Writing an E-mail Proxy Server

How Standard E-mail Delivery Works


Lets start with a short review of how e-mail delivery
works, and why Hotmail deserves special consideration.
Everybody uses e-mail these days. We use e-mail client
applications to compose and send e-mails, and we use
them to receive and look at e-mails.
Eudora, Microsoft Outlook, or Pegasus are all examples of
e-mail client applications. The e-mail client is an application that runs on a client computer, provides some kind
of graphical or text-based user interface, and communicates with a server application in the background.

the server host on port 25 for sending e-mails, and a TCP


connection on port 110 for receiving e-mails. After the
connection is terminated or aborted, the e-mail server
keeps listening to ports 110 and 25 waiting for another
client connection.
The conversation between the senders e-mail client and
the outgoing server is done using Simple Mail Transfer
Protocol (SMTP). The conversation between the recipients e-mail client and the incoming mail server is done
using Post Office Protocol (POP3).

Unfortunately Hotmail is Web-based, and although it uses


The server application (often simply named server) is
SMTP protocol to talk to other mail servers to deliver mesusually located on a different computer than the client
sages, it doesnt provide standard POP or SMTP interfaces
application, although this isnt
for client connections. To send or
a requirement. On a TCP-/IPreceive an e-mail Hotmail, users
That is, youre almost
based network, the server applihave to use a Web browser or
out of luck. This is where
cation is identified by a TCP/IP
Microsoft Outlook, which commusocket, which is a combination
nicate with the Hotmail server via
our simple HotServer
of the IP address of the host
an active server page. This is an
application saves the day.
computer and a TCP port. The
undocumented and non-standard
client application and the server
interface, and if Microsoft Outlook
talk to each other using a special language, or set of
isnt your software of choice, youre out of luck.
rules. This set of rules is called a protocol.
That is, youre almost out of luck. This is where our simple
When the e-mail client application is set up for the first
HotServer application saves the day.
time, the user must specify the outgoing e-mail server
(SMTP server) and the incoming mail server (POP servAnalysis: The Problem at Hand
er). Generally, the POP server also requires a user ID and
We can safely assume that we cannot modify numerous
a password for authenticating the user.
e-mail client applications running on users computers to
accommodate Hotmails non-standard interface. Therefore
When the user hits the Send button after composing the
we want to write an e-mail proxy application or a service.
message, the e-mail client issues a request to the outgoing The proxy application will look and behave like any other
e-mail server to send the message. The server examines
standard e-mail server from the e-mail client applications
the recipient address information in the message. Usually
point of view. This is done by exposing standard SMTP
the address contains the name of the recipient and the
and POP interfaces. On the other side, the same proxy
name of the domain. The e-mail server then extracts the
application must become a Hotmail client, indistinguishdomain name and issues a DNS (name resolution) query
able from Microsoft Outlook or a Web browser. It should
for a mail exchange record (MX record) of the destination
seamlessly communicate with the hotmail.com Web mail
domain. The response is the IP address of the mail server
service exposed via an active server page.
on which the recipients mailbox is located. The server
initiates a connection using an SMTP protocol common to
Although we are talking about one application, youll immeboth servers. After initial contact and successful negotiadiately notice that it must have several independent parts:
tions, the initiator passes the e-mail message to the desti1) Port listener(s), also called TCP server(s)
nation e-mail server. After the message is passed, contact
2) E-mail server interfaces: SMTP and POP, built on top
is terminated.
of the port listeners
3) E-mail transport layer: Hotmail implementation specifics
The message is placed in the recipients mailbox (often
named maildrop) where it can be retrieved by the
Therefore, we can build our application in three steps as
recipients e-mail client application. Maildrops are adminwell, starting with a simple TCP port listener.
istered by the POP server. The recipients e-mail client
application initiates contact with the POP server, and
Implementation Details
passes it the user ID and password. After successful
Well be using Delphi 7 for building our HotServer appliauthentication, the e-mail client can send commands and
cation. However, you should be able to use older verretrieve e-mails from the POP server. At the end the client
sions of Delphi as well (you can use TServerSocket, if the
closes the connection.
TTcpServer component does not exist on your compiler).

Initially, the server host starts the SMTP service by listening on TCP port 25, and the POP service by listening on
TCP port 110. When a client wishes to make use of any
of these services, it establishes a TCP connection with
21

DELPHI INFORMANT MAGAZINE | January 2004

We start with very detailed steps to get the TCP port


listener code working. This is the skeleton for our application, and we want to get it right. After that we concentrate on explaining how things work in general rather

On

the

Net

Writing an E-mail Proxy Server

than analyzing the code line by line. The full source code
of the HotServer application is included with this series
and includes additional comments (available for download; see end of article for details).
Lets start with a new application: File | New | Application.
We dont need a big main form, so resize the main form
to be no more than a thumbnail. Change the forms Caption to HotServer. Double-click the form and modify the
FormCreate event handler thus:
procedure TForm1.FormCreate(Sender: TObject);
begin
// Parse port numbers here.
end;

The comment will keep Delphi from automatically removing the event handler until we add more code to it. Drop an
instance of TPanel and set its Name property to Quit and set
the Align property to alClient. Double-lick on the panel and
modify its event handler:
procedure TForm1.QuitClick(Sender: TObject);
begin
Close
end;

The panel serves as a Quit button for our application.


Now were ready to set up our port listeners. Our HotServer application will act as two TCP servers in one application: the SMTP server for handling the outgoing e-mails,
and the POP server for the incoming e-mails. This means
that the application is supposed to listen on two independent TCP ports simultaneously. Delphi 7 provides a component named TTcpServer on the Internet palette, which
encapsulates the network support functions for a TCP
server socket. Drop an instance of TTcpServer on the panel
and change its Name property to PopSocket. Drop another
instance of TTcpServer on the panel and change its Name to
SmtpSocket. Double-click on each of the icons and put the
code shown in Figure 1 into their event handlers.
This may look cryptic, but it all will make sense during
the test phase. Were ready to give our application its first
test run. Save the project as HotServr.DPK, and save the
unit as UHotMain.PAS.
Run the application. It will show up as a simple form
with a Quit button taking up the entire client area. Clicking on Quit closes the application. Now run the application again and leave it running.
Outside of Delphi, start a command-line window (CMD.EXE
or COMMAND.COM) and type in the following command:

procedure TForm1.PopSocketAccept(...
begin
// Show message to client.
ClientSocket.SendLn('Hello World')
Sleep(5000); // Wait 5 seconds, and disconnect.
end;
procedure TForm1.SmtpSocketAccept(...
// Make the body identical to PopSocketAccept.

Figure 1: Getting started with the TTcpServer event handlers.

When you type in the above command, telnet will connect


to our HotServer application using port 25 (you will see
the server response Hello World!), stay connected for 5
seconds, then disconnect with Connection to host lost.
If you try the same telnet command with port number 110
the behavior will be identical. That was easy, wasnt it? Our
port listener application is up and running.
Now its time to complete our FormCreate event handler, as
shown in Figure 2. By default, the POP server listens on port
110; the default for SMTP is port 25. We want to keep our
options open, so the end user can modify the port numbers
without having to recompile the application. If its necessary to change the default ports, the user of the application
will be able to specify the port numbers as command-line
parameters. For example:
HOTSERVR.EXE /smtp=2525 /pop=110
HOTSERVR.EXE /smtp=2525
HOTSERVR.EXE /pop=2511

Security Issues and IP-based Filtering


Our server is listening on two TCP ports when we run it.
Lets assume that the host computer is connected to the
Internet and has a public IP address. As soon as we run the
HotServer application, everybody else on the Internet can
connect to it using the public IP address, just as we did a
moment ago. However, we dont want anybody to probe or
tamper with our POP and SMTP servers. So, what do we do
about hackers and hooligans?
Take a look at the second parameter of the PopSocketAccept
method. This parameter contains the client information. For
now were interested in the ClientSocket.RemoteHost property, which contains the clients IP address:
procedure TForm1.PopSocketAccept(... or SmtpSocketAccept(
begin
if AcceptRemoteClient(ClientSocket.RemoteHost) then begin
ClientSocket.SendLn('Hello World') // Show message.
Sleep(5000); // Wait 5 seconds, and disconnect.
end
end;

telnet localhost 25

Telnet is an Internet protocol for creating a connection with


a remote machine. Telnet is also a terminal emulation program that allows users to conduct interactive sessions with
computers on the Internet by providing a text-based connection. In this series, well be referring to the telnet program
rather than the Internet protocol. All Windows computers
include a simple telnet program.
22

DELPHI INFORMANT MAGAZINE | January 2004

AcceptRemoteClient is a Boolean function, which doesnt


exist yet. But its very easy to write:
function AcceptRemoteClient(remoteIP: string): Boolean;
begin // Check if localhost.
Result := remoteIP = '127.0.0.1'
end;

or, to be more generic:

On

the

Net

Writing an E-mail Proxy Server

procedure TForm1.FormCreate(Sender: TObject);


var s: string;
p, i: Integer;
PopPort, SmtpPort: Integer;
begin
PopPort := -1;
SmtpPort := -1;
for i := 1 to ParamCount do begin
s := AnsiUpperCase(ParamStr(I));
p := Pos(' ',s);
while p > 0 do begin
Delete(s,p,1);
p := Pos(' ',s);
end;
p := Pos('POP=', s);
if p > 0 then begin
Delete(s, 1, p+Length('POP=')-1);
PopPort := StrToIntDef(s, 110);
end;
p := Pos('SMTP=', s);
if p > 0 then begin
Delete(s, 1, p+Length('SMTP=')-1);
SmtpPort := StrToIntDef(s, 25);
end;
end;
if PopPort <= 0 then
PopPort := 110;
if SmtpPort <= 0 then
SmtpPort := 25;
PopSocket.LocalPort := IntToStr(PopPort);
SmtpSocket.LocalPort := IntToStr(SmtpPort);
PopSocket.Open;
SmtpSocket.Open;
end;

Figure 2: This OnFormCreate event handler allows the user to change the POP
and SMTP ports.
function AcceptRemoteClient(remoteIP: string): Boolean;
begin
// IPs starting with 127 belong to localhost.
Result := Copy(remoteIP,1,4) = '127.'
end;

Now lets pause for a moment and consider a few things


before we write this function. For example, in a small
office situation, it would be nice to have our little mail
server running on a gateway computer. In this case, many
different clients could talk to it simultaneously. Also, we
dont want to limit ourselves to thinking e-mail proxy at
this point; we need to think in broader terms of creating
a generic socket server and reusable code. Today were
writing an SMTP and POP server, but tomorrow it may
be a news server or some other proxy server. The IP
address checking part of the code can probably be reused
many times. Therefore we can do better than to simply
compare the client IP to 127.0.0.1 (localhost).

The server would compare the remote clients IP address to the


ones in the list, and drop the connection if theres no match.
It would be even better if we could use standard TCP subnetting conventions. Then, if necessary, we could add the
entire subnet of 16 addresses in one line:
[AllowedClients]
allow_ip_1=209.123.123.0/28

Parsing client IP addresses can be implemented in many different ways. The UChkIP.PAS unit offers one such way. It
has only one public function named AcceptRemoteClient in
its interface section. Skipping the implementation details,
all we need to do is add UChkIP to our units uses clause.
When you run the HotServer application the first time,
it will automatically create an .INI file and add the local
host to the list. You may edit the .INI file manually to add
allowed addresses other than the local host. By default
our little application will accept connections only from
the local host.
SMTP Server Implementation
The next step is to find out what exactly an SMTP server
is supposed to do for the client. Fortunately, SMTP is
exactly what its name implies incredibly simple. SMTP
is an open standard, and well documented in the RFC 821.
Consider a typical SMTP session (see Figure 3). The
SMTP conversation is very simple and readable by a
human. You can immediately try sending an e-mail to
yourself manually using only telnet, if you know a valid
SMTP server name or IP address that will relay e-mails
from your computer. Please note that when you are in
a telnet session, you can see only the server side of the
conversation. Everything you type will be invisible, except
the first line.
The SMTP commands and replies have a rigid syntax.
Commands and replies arent case-sensitive, with the
exception of mailbox user names. For some hosts the
user name is case-sensitive, and the SMTP server must be
aware of that.
The replies from an SMTP server always have a threedigit code, followed by a space, and (optionally) text.
The session must start with code 220 and a greeting, for
example:
220 MailServer ready

Imagine a hypothetical socket server running on a gateway computer with an IP address of 209.123.123.4. Imagine
also that we have two legitimate client computers in our
office with IP addresses 209.123.123.5 and 209.123.123.6.
We want to invent an easy way of screening out IP addresses. The easiest way would be to use an INI file to which we
could add acceptable client addresses one by one:
[AllowedClients]
allow_ip_1=209.123.123.5
allow_ip_2=209.123.123.6

23

DELPHI INFORMANT MAGAZINE | January 2004

If the command is successful, the SMTP server may


respond with 2xx, or 3xx (e.g. 250). If the command
failed, then the response is 4xx or 5xx (e.g. 500).
Our SMTP server has to implement only the basic set of
SMTP commands (as shown in Figure 4).
The USmtpCon.PAS unit provides a generic base class
(or upper layer) for the SMTP server. This basic SMTP
server is implemented as a very simple Delphi class

On

the

Net

Writing an E-mail Proxy Server

S[erver]: <wait for connection on TCP port 25>


C[lient]: <open connection>
(example: C:\>telnet mx4.hotmail.com 25)

HELO <domain>

The host sending the command identifies itself with HELO; its like saying
Hello, I am <domain>. HELO must
be the first command of a session. It
can be sent only once during a session,
but the client may repeat the HELO
command after RSET.

MAIL FROM:
[email protected]

Specifies senders e-mail address. Must


follow the HELO command and be
before RCPT. This command can be
sent only once.

RCPT TO:
[email protected]

Specifies recipients e-mail address.


Must follow the MAIL FROM command
and be before DATA. This command
can be sent as many times as the client
wishes. Use one command per recipient: If there are five recipient e-mail
addresses RCPT TO must be repeated
five times with five different addresses.

DATA

This command indicates start of data


(body of the e-mail). The client must
end data entry with a single period in a
line all by itself. If the data has a single
period in it, then the client must enter it
as .. <CRLF>.<CRLF> indicates end
of data.

QUIT

End of session: disconnect.

RSET

This command specifies that the current


mail transaction is to be aborted. Any
stored sender, recipients, and mail data
must be discarded, and all buffers and
state tables cleared. The receiver must
send a 250 OK reply. This command
can be issued at any point during the
session.

S[erver]: 220 SMTP service ready


C[lient]: HELO msn.net
S[erver]: 250 Welcome msn.net, pleased to meet you!
C: MAIL FROM:<[email protected]>
S: 250 OK
C: RCPT TO:<[email protected]>
S: 250 OK
C: RCPT TO:GreenTomato
S: 500 Bad e-mail address
C: RCPT TO:<[email protected]>
S: 250 OK
C:
S:
C:
C:
C:
S:

DATA
354 Start mail input; end with <CRLF>.<CRLF>
Hello World!
...etc. etc. etc.
.
250 OK

C: QUIT
S: 221 Bye
C:<close connection>
S:<wait for next connection>

Figure 3: A typical SMTP session.

named TSmtpConnection. The TSmtpConnection class has


only three public methods: Create, Destroy, and Execute.
Create initializes some internal variables and sends a
greeting to the client. Execute starts a command loop,
which repeatedly accepts and passes the client input
to a ProcessCommand routine. The command loop is
broken only when the server application is terminated,
or if the client issues a QUIT command. Destroy frees the
resources used by an instance of TSmtpConnection.

Figure 4: SMTP commands supported by HotServer.

The ProcessCommands routine is nothing more than a


glorified case statement; it provides the functionality for
parsing the client commands, keeping track of server
states, and syntax checking of e-mail addresses. It also
stores the list of recipients, the senders address, and the
body of the e-mail message.

POP server is supposed to do when it accepts the client


connection. Having built an SMTP server, we know exactly where to start. Let us take a look at RFC 1939 Post
Office Protocol - Version 3. It has all the information we
need to build our own POP server.

Although TSmtpConnection is very simple, its already


a fully functional SMTP server with one exception:
it doesnt contain the code for actually delivering
(sending) the e-mail message. The main purpose of this
layer is to properly handle the e-mail client side of the
communications.

The POP server uses a POP3 protocol (Post Office Protocol Version 3). POP3 protocol is used for e-mail retrieval,
and it is intended to permit an e-mail client to dynamically access a maildrop on a server. POP3 protocol is used
to allow a workstation to authenticate and retrieve mail
that the server is holding for it.

Notice that building our SMTP server (and later our POP
server) in layers gives us a certain advantage of abstraction. At this point were not concerned about how the
e-mails get delivered. Later, well add the specific Hotmail
layer, but we could easily replace the Hotmail layer with a
special driver or a postal pigeon.

POP3 is not intended to provide extensive manipulation


operations of mail on the server; normally after a client
is authenticated, mail is downloaded and then deleted.
Consequently POP3 protocol is as simple as the SMTP
protocol discussed earlier. It defines less than a dozen
basic commands. These commands accomplish every task
a user might perform, such as log on to the server, list
messages on the server, preview and download messages,
and delete messages from the server.

POP Server Implementation


To build a POP server, we need to learn what exactly a
24

DELPHI INFORMANT MAGAZINE | January 2004

On

the

Net

Writing an E-mail Proxy Server

S[erver]: <wait for connection on TCP port 110>


C[lient]: <open connection>
(example: C:\>telnet pop.mydomain.com 110)
S:
C:
S:
C:
S:

+OK POP3 server ready


USER mrose
+OK password required for user mrose
PASS ********
+OK 2 messages (320 octets)

C:
S:
C:
S:
S:
S:
S:
C:
S:
S:
S:
C:
S:
C:
S:
S:
S:
C:
S:

STAT
+OK 2 320
LIST
+OK 2 messages (320 octets)
1 120
2 200
.
RETR 1
+OK 120 octets
<the POP3 server sends message 1>
.
DELE 1
+OK message 1 deleted
RETR 2
+OK 200 octets
<the POP3 server sends message 2>
.
DELE 2
+OK message 2 deleted

C:
S:

QUIT
+OK POP3 server signing off

C:
S:

<close connection>
<wait for next connection>

Figure 5: A typical POP session.

Again, lets start by looking at a typical POP session


(see Figure 5). Like SMTP, the POP3 protocol has a very
rigid command syntax. Client commands consist of a
case-insensitive keyword, and a space and command
arguments. Responses from the POP3 server consist of a
status indicator and an optional space and text. There are
two status indicators: positive, +OK, and negative, -ERR;
both must be in uppercase. Commands and responses are
terminated by a <CRLF>. Some responses may contain
multiple lines terminated with a period on a separate line.
A POP3 session has several states: authorization, transaction, and update. Once the TCP connection has been
established, the server sends a greeting and enters an
authentication state. If authentication is successful, the
session enters the transaction state. At the end of the
conversation the client issues the QUIT command and the
session enters the update state. The TCP connection is
then closed. If the client disconnects without issuing the
QUIT command, the POP session skips the update state
and the changes to the server are discarded. Our POP

25

DELPHI INFORMANT MAGAZINE | January 2004

USER <name>

Provides username to the POP3 server. Must


be followed by PASS command.

PASS <password>

Provides a password to the POP3 server.


Must follow USER command.

QUIT

Ends the POP3 session.

Figure 6: AUTHORIZATION state POP commands supported by HotServer.

STAT

Provides maildrop information (statistics).

LIST [msg]

Lists message number and size of each


message. If a message number is specified,
returns the size of the specified message.

RETR msg

Returns the full text of the specified message, and marks that message as read.

DELE msg

Marks the specified message for deletion.

NOOP

Returns a simple acknowledgement +OK,


without performing any function.

RSET

Resets any messages which have been


marked as read or deleted to the standard
unread state.

QUIT

Ends the POP3 session.

Figure 7: TRANSACTION state POP commands supported by HotServer.

server implements only the basic set of POP3 commands


(see Figures 6 and 7).
The UPopConn.PAS unit provides a generic framework for
our POP server. Its implemented as a basic class named
TPopConnection which provides the functionality for parsing
the client commands and keeping track of server states.
The structure of the source code to the TPopConnection
class is very similar to TSmtpConnection. It also employs
a similar Execute method with a command loop, and a
ProcessCommand method that handles the client input.
Conclusion
Now we have the entire framework we need. Next month,
well complete this two-part series by implementing the
back-end that allows our POP and SMTP servers to translate and pass commands to Hotmail. See you then.
The project referenced in this article is available for download on the Delphi Informant Magazine Complete Works
CD located in INFORM\2004\JAN\DI200401AM.

Alfred Mirzagitov is a senior programmer for Software Science Inc.,


located in San Rafael, CA. He has been programming in C and Pascal for
over 15 years and in Delphi since the release of version 1. You can contact
him by e-mail at [email protected].

N E W

&

U S E D

By Bill Todd

Database Workbench
Everything You Need to Develop Complex Databases

atabase Workbench is a must-have tool for


anyone who develops applications using
InterBase, Firebird, Microsoft SQL Server, or

MySQL. It gives you a single tool for creating, dropping, and modifying databases, tables, indices, constraints, stored procedures, triggers, domains, generators, exceptions, external functions, roles, users,
and every other object supported by the database
server youre using. And thats just the beginning.
Database Workbench has a very intuitive user interface.
The first thing I did after installing it was read the Getting Started section of the online help. After that I was
able to create an InterBase database, create domains,
tables, primary key constraints, foreign key constraints,
check constraints, generators, stored procedures, and triggers without using the help system again. When I did use
the online help, I found it clear, concise, and complete.

Figure 1 shows Database Workbench as it appears after


being started for the first time, and after registering three
database servers. Initially you see the toolbars at the top,
the Enterprise Manager along the left side, and the main
workspace to the right.
When you create or open a database, a tab for the database is added to the window that contains the Enterprise
Manager, as shown in Figure 2. The tree view lists all
possible database objects. To create an object, just rightclick it in the tree view, and choose New from the context
menu. Other choices on the context menu let you edit or
drop the object.
Choosing New from the Domains context menu opens the
Domain Editor shown in Figure 2. This is one of Database Workbenchs object editors. You can open multiple
instances of all object editors; each object editor has a
button on the toolbar that you can use to open a new
instance. These are drop-down buttons; clicking the arrow
to the right of the button displays a list of the open editor
windows with the topmost instance shown in bold. Just
click the instance you want to bring it to the foreground.
Like the Domain Editor in Figure 2, all of the object editors have tabs that let you enter a description, see the
DDL for the object, and see a list of objects that depend
on the object youre editing. Which tabs you see depends
on the features supported by the database engine with
which you are working.

Figure 1: The Database Workbench main window.

26

DELPHI INFORMANT MAGAZINE | January 2004

Note that the edit box for the domain name in Figure 2
already contains the characters D_. This is an example
of a name template. Name templates are predefined for
every database object. Select File | Preferences | Name templates from the menu to edit the templates to match your
naming conventions. You can also use macros in the
name templates to represent the table name, field name,
or referenced table name.

New

&

Used

Database Workbench

Figure 3: The Table Editor.


Figure 2: The Domain Editor.

Figure 3 shows the Table Editor that you use to create and
modify tables. The Column Type field is a drop-down list.
You can choose the data type by dropping down the list,
or by tapping the first letter of the type to cycle through
the choices that begin with that letter. I did find this a
bit inconvenient because, if you use the default name
template for domains in InterBase, all of the domain
names start with the letter D. This means you may need
to press D many times to get to the domain you want. I
think that Quicken-style auto-fill would be a better choice
here. On the other hand, I really like the fact that I can
enter all the information for a column, and then add the
next column using the keyboard; I never have to stop and
reach for the mouse.
Another great feature of the Table Editor is the Field Specials dialog box. Just click the Field Specials toolbar button, or press CF, and a dialog box opens that lets you
create an ascending index, a descending index, an autoincrement trigger and generator, and upper-case triggers
for the current field. Being able to create all these objects
by just clicking some checkboxes saves a lot of time when
youre creating new tables.
Figure 4 shows the Procedure Editor in the process of creating a new stored procedure. Note that the procedure was
created with a comment block at the top. You can change
the templates for stored procedures and triggers to customize the comment block to fit your documentation standards.
You can also store all the templates used by Database
Workbench on a file server, so everyone on your development team will be using the same standards. The procedure
and trigger editors and the SQL Editor support code templates that work just like code templates in the Delphi IDE.
Just type the code letters for the template you want, then
press CJ to enter the code into the editor. You can also
type CJ without entering the code for a template to display the pop-up list of templates shown in Figure 4.
Some developers like to control access to database
tables by performing all SELECTs, UPDATEs, INSERTs,
and DELETEs through stored procedures. If you use this
model, youll save a lot of time by letting Database Workbench create the procedures for you automatically in your
InterBase and Firebird databases.
27

DELPHI INFORMANT MAGAZINE | January 2004

Figure 4: The Procedure Editor.

As you would expect, Database Workbench has a SQL


Editor for creating and executing individual SQL statements, and a SQL Script editor for working with scripts.
The SQL and Code catalog that lets you copy code from
the SQL editors, or the procedure and trigger editors, and
add it to the catalog. Code in the catalog can be organized into groups, and you can select any statement in
the catalog and execute it in a new editor window. The
SQL Editor also lets you analyze statement execution
plans to help you optimize your SQL.
So far, Ive described creating a new database from scratch,
but suppose youre migrating from one database system to
another. Again, Database Workbench has all the tools you
need. The Schema Migrator will migrate the schema from
any of the databases that Database Workbench supports, or
from any database that you can connect to using ADO or
ODBC. Database Workbenchs data pump will move your
data from the old database to the new, or you can import
data from comma-separated value (CSV) files.
Test Data Generator
The first rule of writing successful database applications
is to always do all of your development and testing with
a fully populated database. That isnt too difficult if a full
set of data already exists in electronic form, so you can
import it into your new database. Its much more difficult if there is no real data available unless you are using
Database Workbench. Database Workbench has a sophisticated test data generator that will populate your tables
quickly and easily.

New

&

Used

Database Workbench

Just the Facts


Database Workbench gives you all the tools you need
to create and maintain InterBase, Firebird, MySQL, and
Microsoft SQL Server databases. You can create the
database, tables, indices, constraints, stored procedures,
triggers, domains, exceptions, and every other database
object quickly and easily. You can import the schema and
data from another database, and export metadata and
data from the database you are working with. Database
Workbench also provides tools to generate sophisticated
test data and debug stored procedures. Everything you
need to develop the most complex databases is here.
Figure 5: The Test Data Generator.

Figure 5 shows the Test Data Generator with the node for
a child table in a foreign key relationship expanded and a
VARCHAR field selected. In the Table Settings section on the
right you set the number of rows you want to generate, as
well as how often to commit and start a new transaction.
You can also choose to have the table emptied before generating the test data, and opt to have indices and/or triggers disabled while the test data is being inserted.
The real power of the Test Data Generator is in the Field
Settings section at the lower right. The Fill with drop-down
list lets you choose from Nothing, Fixed Value, Random Values,
Custom Values, Referential Link, and Values From List. In Figure 5,
Random Values is selected. If the column allows nulls, you
can choose the percentage of rows that will be set to null.
The radio buttons let you choose 11 different kinds of random data, including:
Random values within a length range
URLs
E-mail addresses
Phone numbers
Street addresses
First names
Last names
Full names
Cities
Countries
Mask values
The Mask Values option lets you define a mask containing
fixed text, random numbers of a specified length, and
random text of a specified length. If none of the random
values meet your needs, choose Value From List and enter a
list of values. The records will be created with a random
selection of values from your list. Custom Values is similar
to Values From List except that you specify a text file that
contains the values to be used. Perhaps the best feature
of the Test Data Generator is the Referential Link option.
This lets you fill a foreign key field with a random selection of values from the primary key of the parent table.
Just make sure you generate the parent tables data first
by moving it ahead of the child table in the tree view.
Do you need to get data out of an existing database? No
problem. Just choose Tools | Export Table or View, or Tools |
28

DELPHI INFORMANT MAGAZINE | January 2004

Upscene Productions
E-Mail: [email protected]
Web Site: www.upscene.com
Price: Database Workbench with all modules, US$544;
Database Workbench base module, US$74; InterBase
module, US$150; Firebird module, US$75; MySQL module, US$62; Microsoft SQL Server module, US$275.
Export Multiple Tables or Views.

You can export data as SQL


INSERT statements, dBASE files, padded (fixed-length)
text, Excel files, CSV files, Lotus 1-2-3 files, DIF files, or
XML. You can send the exported data to a file, or the
Clipboard, and for those file formats that dont support
the null state you can choose a text string to represent
nulls. If your destination is the Clipboard, you can also
choose the number of rows to export. Of course, you can
also extract and print the metadata for any or all of your
database objects.
You dont even need to leave Database Workbench to perform maintenance tasks. For example, for InterBase and
Firebird databases, you can perform a backup, restore,
sweep, database shutdown, or database restart from within Database Workbench.
Conclusion
The Delphi IDE has been a great development environment from version 1, because its written in Delphi; the
R&D team has to use it all day, every day. Database Workbench shows the same polish and ease-of-use, for the
same reason. It was written by an experienced database
developer who built a tool with the features he needed
to make his work easier. Database Workbench is intuitive, easy to use, well documented, and has every feature
you need to make it easy to develop InterBase, Firebird,
MySQL, and Microsoft SQL Server databases. Its the best
database development tool Ive ever used.

Bill Todd is president of The Database Group, Inc., a database consulting


and development firm based near Phoenix. He is co-author of four database
programming books, author of more than 100 articles, a contributing editor to
Delphi Informant Magazine, and a member of Team B, which provides technical
support on the Borland Internet newsgroups. Bill is also an internationally known
trainer and frequent speaker at Borland Developer Conferences in the United
States and Europe. Readers may reach him at [email protected].

N E W

&

U S E D

By Bill Todd

Pervasive.SQL v8
The Features You Need in an Easy-to-Deploy Package

o you have an application that uses Paradox,


dBASE, or Access tables? Would you like to
move it from the BDE and step up to a SQL

database server? Are you looking for a zero administration database for small to medium applications,
or to embed in a vertical market product?

The best way to choose the right database is to compare


the products you are considering to a list of the features
you need. What features are important to you? Consider
this list:
Transaction support
Navigational and SQL access
Stored procedures
Triggers
A full set of drivers, including native Delphi and
C++ components, ODBC, ADO, and JDBC
Encrypted tables to protect your data
Group-based user security for easy administration
Encryption of the data stream between client and server
Zero maintenance
Point-in-time crash recovery
Local and client/server versions
Runs on Windows, Linux, and NetWare
Online backups
Small disk footprint
Declarative referential integrity
Case-insensitive sorting
Multi-national character set support
GUI development tools
N-way asynchronous replication
Cost-based query optimizer
29

DELPHI INFORMANT MAGAZINE | January 2004

Good Things Come in Small Packages


Pervasive.SQL version 8 offers all these features in a small,
easy-to-deploy package. Pervasive.SQL comes in two
versions: workgroup and server. The workgroup version
uses file server architecture. For multi-user access the data
files are located on a file server and the Pervasive.SQL
engine is installed on each workstation. The workgroup
version supports up to five users, making it ideal for
single-user applications and small groups of users.
Like all file server databases, the workgroup version
is vulnerable to workstation crashes, because each
workstation writes directly to the database files.
However, Pervasive.SQL minimizes the risk of file
corruption by using double-buffered writes. When a page
must be written to disk its first written to a shadow
page and then written to its proper location in the file.
If a crash occurs during the write to the shadow page
no damage has been done to the actual data. If a crash
occurs during the write of the data page, the page in the
file may be damaged. However, the Pervasive.SQL engine
will detect that the data on the shadow page was not
PDAC Transactional

BDAC SQL

BDE

TPvSession

TPvSqlSession

TSession

TPvDatabase

TPvSqlDatabase

TDatabase

TPvTable

TTable
TPvQuery

TQuery

TPvStoredProc

TStoredProc

TPvUpdateSql

TUpdateSql

TPvBatchMove
Figure 1: Pervasive Direct Access Components (PDAC).

TBatchMove

New

&

Used

Pervasive.SQL v8

Figure 3: The Create Database Wizard.

Figure 2: The Pervasive Control Center.

successfully written and will recover by rewriting the


information on the shadow page to the correct data page.
Use the server version of Pervasive.SQL if you want the
robust performance of a true client/server environment.
Pervasive.SQL is an excellent choice for vertical market
applications, because you can switch between the
workgroup and server version without changing your
application in any way. Simply install the Pervasive.SQL
version thats right for each client, and your application
will work. Both the workgroup and server versions are
available for Windows, Linux, and NetWare.
Safety Features
Using its transaction logging mechanism, Pervasive.SQL
provides true transaction support with read-committed
isolation. If a client application crashes, any transactions
that havent been committed will automatically roll
back. If a transaction has been committed, all the
changes are in the transaction log but they may not
have been written to the data pages. If the server goes
down it will automatically read the log file on restart
and automatically write the changes to the data file.
Pervasive.SQL also supports savepoints. You can create
named savepoints at any time during a transaction and
later roll back to any savepoint by name.
The stored procedure and trigger support is great. One
of the nice features is that most DDL statements are
supported in stored procedures so you can easily write
a stored procedure that creates and drops tables and
indexes or performs other DDL functions. The trigger
implementation also provides everything you could ask
for. Both before and after triggers are available for insert,
update, and delete events and both the old and new values
for the fields are available to the trigger. One important
limitation is that triggers are not fired when you perform
operations using the record-level transactional access mode
described later in this article. To take advantage of triggers
you must use SQL to make changes to your data.
30

DELPHI INFORMANT MAGAZINE | January 2004

Another great feature you dont usually find in databases


designed for the embedded systems market is pointin-time crash recovery. If you enable Pervasive.SQLs
archival logging feature, all the changes made since the
last database backup are logged to a separate set of log
files. Ideally you will place the log files on one hard
drive and the database files on another. If the drive that
contains the database fails, you can restore the database
from your last backup and roll forward using the archival
log. Using this process you can recover the database as it
was at the time the drive failed.
Pervasive.SQL also has a mode called continuous
operations that allows you to back up your database
while it is in use. When you start continuous operations
mode, Pervasive.SQL begins writing all changes to a
set of shadow files instead of to the database files.
This allows you to back up the database files safely by
copying them or by using the backup program of your
choice. When you end continuous operation mode, the
changes in the shadow files are written to the database
files and the shadow files are deleted. Because you
cannot use both continuous operation mode and archival
logging, you must decide whether you want point-intime recovery capability or the ability to back up your
database while its in use.
How It Works
You can download a complete set of data access
components for Delphi from the Pervasive.SQL Web site.
To understand the Pervasive Direct Access Components
(PDAC) you must understand a bit about the architecture
of Pervasive.SQL. Pervasive.SQL started as the Btrieve
record manager that was purchased by Novell and
became ubiquitous in NetWare. Later, Novell spun off the
Btrieve database and it became Pervasive.SQL.
Pervasive.SQL consists of two database engines: the
transactional engine and the SQL engine. Dont confuse the
transactional engines name with database transactions.
It might better be called the record-level engine. You can
use database transactions with either access method. The

New

&

Used

Pervasive.SQL v8

Just the Facts


Pervasive.SQL, which ships in two versions (workgroup
and server), provides a small, fast database for any small
to medium application. Pervasive.SQL boasts transactions, savepoints, stored procedures, triggers, pointin-time recovery, native Delphi components, encrypted
tables, over-the-wire encryption, local and client/server
versions, declarative referential integrity, a powerful GUI
development tool, and excellent documentation.
Pervasive Software, Inc.
12365 Riata Trace Parkway
Building B
Austin, TX 78727

Figure 4: The Create Table Wizard.

transactional engine provides record-level navigational


access to data. The SQL engine provides set-oriented SQL
access. Each engine runs as a separate service. The PDAC
components include components for both methods of
access (and their correlating BDE components) and are
shown in Figure 1. There are also versions of each dataset
component designed to support Woll2Woll Softwares
InfoPower components.
As you can see, the PDAC components mirror the BDE
components. This makes converting a BDE application
to Pervasive.SQL quite easy. The only complication is
that you need separate connections to the database
for record-oriented access and SQL access. To see
the practical effect of this architecture, assume you
have a BDE application that uses Paradox tables. Also
assume that this application uses both TTable and
TQuery components and that you want to convert it
to a client/server application using the server version
of Pervasive.SQL. To do that, you need to replace your
TDatabase component with a TPvSession, a TPvDatabase,
and a TPvSqlDatabase.
You need the TPvSession because you cannot connect to
a database on a remote server with a TPvDatabase alone.
You dont need a TPvSqlSession because you can connect
to a remote database using a TPvSqlDatabase alone.
Although this may sound complex, it really isnt. Because
most applications contain a single TDatabase component,
youre simply replacing one component with three, and
setting the properties that are necessary to establish the
connection. This architecture does not penalize you in
terms of licensing, because all the connections from a
single client consume a single seat on the server.
Working with Pervasive.SQL
Working with Pervasive.SQL is easy thanks to the
Pervasive Control Center (shown in Figure 2). Control
Center lets you connect to and work with any number
of local and remote Pervasive.SQL engines. Wizards are
provided to step you through all the common tasks. To
create a database, right-click Databases in the tree and
31

DELPHI INFORMANT MAGAZINE | January 2004

Phone: (800) 287-4383


E-Mail: [email protected]
Web Site: www.pervasive.com
Price: Pervasive.SQL prices vary by seat count. Desktop
editions for small workgroups start at US$25 per seat.
Client/Server editions are available starting at US$845
for a six-user license and are available in user counts of
10, 20, 50, and higher.
choose New Database from the context menu to open the
Create Database Wizard (shown in Figure 3).
After creating your database, right-click on Tables in the
Control Center tree and choose New Table from the menu.
Figure 4 shows the Create Table Wizard. Frankly, I found
entering the table fields in the grid in Figure 4 to be
frustrating, because I constantly had to stop typing and
reach for the mouse. The first problem is that when I
add a new column, either by clicking the next blank row
in the grid or by clicking the Add Column button, I expect
to be able to start typing the column name. Instead, I
have to click in the Column Name cell before I can type.
However, clicking in the Column Name cell deselects the
default column name text, so after clicking I have to drag
over the text to reselect it so the default column name
will be replaced when I start typing. After entering the
column name I hit T expecting to move to the Data Type
column. Instead, focus jumped to the Back button. Time to
reach for the mouse again and click the Data Type cell.
You might think that once you learn the data types you can
save time by typing the data type into the cell. Sorry. You
have to reach for that rodent again, drop down the list,
scroll until you find the data type you want, then select
it. Once I had entered the information for the column I
was adding I also expected to be able to press the down
arrow key to move to the next row in the grid and add the
next column but, of course, I had to grab the mouse one
more time. Unfortunately, the fastest way to create a table
is to forget the wizard, open the SQL editor, and type the
CREATE TABLE statement from scratch. Even if you have
to go back and fix a few typos you will still save time.
With the exception of the grid behavior, Control Center is
a great tool. The layout is logical and the menu structure

New

&

Used

Pervasive.SQL v8

is intuitive. I didnt have to spend time in the manuals


trying to find features they were always where I
expected them to be.
Documentation
If youve read my past reviews you know the area I
criticize most often is documentation. The reason I am so
critical is that there is so much bad documentation out
there. In the case of Pervasive, the greatest contribution
the company could make to the software industry
would be to send their documentation team out to teach
seminars on the right way to write documentation
starting in a certain city in Washington.
You have your choice of using HTML help or PDF files.
I particularly liked the HTML help. Not only is it well
indexed so you can quickly find help on a specific topic,
but it is also laid out so you can read all or any section
like a book by clicking the Next and Back links on each
page. This is the dream of online documentation realized.
It provides well organized readable manuals for the
new user, and well indexed topical information for the
experienced user.
My most common complaint about documentation is that
it appears to have been written by someone in marketing.
It spends all of its time telling you what the product will
do without ever teaching you how to do it. Once again,
the Pervasive.SQL documentation shines. Each topic
provides a clear description of the feature and step by
step instructions for using it.
Conclusion
With a disk footprint of 13MB, Pervasive.SQL provides a
small, fast database for any small to medium application.
The Pervasive engine has a long history of reliable
performance and Pervasive.SQL is the sole product of a
publicly held company with nearly $40 million in annual
revenue so you can be confident that it will be around
for the long haul. With transactions, savepoints, stored
procedures, triggers, point-in-time recovery, native Delphi
components, encrypted tables, over-the-wire encryption,
local and client/server versions, declarative referential
integrity, a powerful GUI development tool, and excellent
documentation, Pervasive.SQL is a great product.

Bill Todd is president of The Database Group, Inc., a database consulting


and development firm based near Phoenix. He is co-author of four database
programming books, author of more than 100 articles, a contributing editor to
Delphi Informant Magazine, and a member of Team B, which provides technical
support on the Borland Internet newsgroups. Bill is also an internationally known
trainer and frequent speaker at Borland Developer Conferences in the United
States and Europe. Readers may reach him at [email protected].

32

DELPHI INFORMANT MAGAZINE | January 2004

N E W

&

U S E D

By Alan C. Moore, Ph.D.

ExpressBars Suite 5
For Building Modern, Responsive User Interfaces

his award-winning library from Developer


Express, ExpressBars Suite, is actually two
libraries in one. It includes a powerful col-

lection of components for creating bars of all kinds,


from menu bars and status bars to the kind of side
toolbar popularized in Microsoft Outlook. It also
includes advanced docking support. Well start by
listing some of the principal components and discussing some of their common features. Then well
discuss the bars and the docking support.
The library uses visual and non-visual components,
support classes, and routines to provide its extensive
functionality (see Figure 1). Theres an interesting
hierarchy and relationships between these components.
Note that the two managers TdxBarManager and
TdxDockingManager, provide large-scale management or
control of various bars or dockable controls, respectively.
There are specialized, customizable menus to enable
users to manipulate properties of bars and side bars
and other special-purpose components. And there are
components you may not even notice special docking
controls created at design time as you drop controls on
various docking sites. Lets examine the details, starting
with the various kinds of bars.
Join Me at the Bar
The main component supporting the creation and manipulation of most of the bars is the TdxBarManager. This non-visual
component allows you and your users to the extent you
allow it to create, delete, and modify controls such as toolbars and menu bars and their sub-components, including categories, items, and so on. It also provides the ability to modify

33

DELPHI INFORMANT MAGAZINE | January 2004

the behavior of these in many ways, including animations,


button-glyphs, and fonts. The list of properties goes on and on,
demonstrating the power of this component.
When you double-click the TdxBarManager icon it brings
up the component editor, which lists all the bars you created
and allows you to create new ones. By selecting a bar, you
have access to all its properties in the Object Inspector. The
approach is similar to that of Express Grid, where a Component Editor facilitates the manipulation of views and columns.
This editor also allows you to control many other aspects, such
as commands that can be triggered.
The manager has additional uses. It allows you to specify a
default background image that will be applied to all bars it
owns. If a bar is on a dock control and has no background
image specified, it will use the background image of
the underlying dock control. This means that bars are
painted transparently. Floating bars can also use the cool
AlphaBlend property that allows for different degrees of
transparency, from opaque to invisible.
One of the more interesting capabilities is the main menu
control. Again, this is not a separate component but rather
another toolbar (but with a single property set to True). However, the TdxStatusBar is a separate component that you drop
on a form in the usual manner (its capabilities are described
in Figure 1). Of course, you can also create a status bar using
TdxBarManager. Although it involves a bit more work, I chose
this approach because it gave me a bit more control over the
appearance of the toolbar. Take a look at Figure 2 from the
ExpressBars Mega Demo. Note how the toolbars at the top and
bottom use bitmap backgrounds.
The main components weve been discussing are just
a small part of the story. In addition, there are various
items and related controls available that can be used to
build toolbars. These include many combo items and

New

&

Used

ExpressBars Suite 5

Component

Purpose

TdxBarManager

Most of the various bars (including floating menu bars) are created and controlled
by this component. It provides access to
individual bars and their properties through
the Object Inspector and allows you to set
properties that affect all bars. It also manages the items associated with toolbars.

TdxBarPopupMenu

Facilitates the creation of popup menus


for TdxBarManager bar items. The TdxBarManager and the popup menu may belong
to different forms, allowing you to use a
TdxBarPopupMenu on a form that doesnt
include a TdxBarManager.

TdxBarDBNavigator

Similar to Delphis TDBNavigator, this component can be used to navigate data in a


dataset, perform data operations, and create links between TdxBarManager items and
a datasets state using specific conditions.

TdxBarLookupCombo

Maintains a list of lookup values associated


with a set of key field values.

TdxBarConverter

Convenient utility used to convert existing


menus (TMainMenu or TPopupMenu) into
ExpressBar menus.

TdxStatusBar

Specialized status bar allows insertion of


any of four types of panel: 1) a Text panel,
2) a Container panel that allows the insertion of various controls into a status bar, 3)
a Keyboard State panel that tracks the state
of the keyboard modifiers (Caps Lock, Num
Lock, etc.), and 4) a State Indicator panel
that provides visual indicators for various
device states.

TdxDockPanel

Special dock panel contains various controls. These panels dont reside directly on
forms, but may reside on a dock site or a
layout site. Otherwise, an underlying float
site is automatically created for them.

TdxDockSite

Enables users to dock controls to a form.


It can accept only dock controls, but those
controls can be docked to any edge of a
dock site, or fill its entire client area.

TdxDockingManager

Centralized component is used to control


dock controls appearance and behavior; it
includes methods to save and restore layout
of dock controls.

TdxSideBar

Creates an ExpressSideBar control. The user


may select a group, or items in a group, by
clicking on a groups button or the items
icon, respectively. Developers and users can
customize these side bars.

TdxSideBarPopupMenu

Encapsulating the properties, methods, and


events of a popup menu, with some predefined menu items, this component can be
associated with TdxSideBars GroupPopupMenu and ItemPopupMenu properties.

Figure 1: ExpressBars main components.


34

DELPHI INFORMANT MAGAZINE | January 2004

Figure 2: The ExpressBars Mega Demo shows various toolbars and a status bar
with bitmap backgrounds.

Figure 3: Another view of the Mega Demo shows an Internet Explorer-like interface.

controls, such as TdxBarColorCombo, TdxBarDateCombo,


TdxBarFontNameCombo, TdxBarImageCombo, and
TdxBarTreeViewCombo. There are other useful controls,
including TdxBarProgressItem, TdxBarSpinEdit,
TdxBarStatic (static text), TdxBarControlContainerItem
(to contain another control), and TdxBarMRUListItem
(for most-recently-used items). Each of these items also
has a corresponding control that represents its visual
appearance on the form. The items, however, facilitate the
management of the controls properties.
The TdxSideBar component is special. It provides all the functionality of the side toolbar popularized by Microsoft Outlook
(see Figure 2). The side bar enables switching from this view
to two others, including the Internet Explorer-type view shown
in Figure 3 (interestingly, this screen shot shows a visit to the
Developer Express Forum to get an answer to a question).
ExpressBars Suite provides many sophisticated features,
such as small and large icons, customization of both
groups and items, drag and drop support, and animations. There is also considerable support for its appearance using backgrounds of either gradient color fills or
background bitmaps, fonts, and various paint styles as in
other Developer Express products.

New

&

Used

ExpressBars Suite 5

Just the Facts


ExpressBars Suite 5 is an excellent component library for
creating toolbars, menu bars, status bars, and the ever popular side toolbar. The new version also includes advanced
docking support that provides all the flexibility you and your
users might desire. The documentation and example programs are excellent, covering all the main features of this
wonderful library.
Developer Express
6340 McLeod Drive, Suite 1
Las Vegas, NV 89120
Phone: (702) 262-0609
Fax: (702) 262-0619
E-Mail: [email protected]
Web Site: www.devexpress.com
Price: ExpressBars Suite 5 (single-developer license):
US$199.99 with source, US$149.99 without. Visit the Web
site for details on upgrades and special packages, as well as
the latest information.
Time to Dock
ExpressBars Suite includes docking support for its toolbars
using the BarManagers Bars DockingStyle property. But the
suite also includes an independent collection of controls and
routines, the ExpressDocking Library, which facilitates the
creation of flexible docking applications that can mimic the
appearance of Microsofts Visual Studio .NET IDE, Delphis
IDE, and similar modern applications. Working with this part
of the library is simple. Unless you need to affect special runtime behavior through code, you need only place a dock site
on a form, add some dock panels, and define their look and
functionality by adding various controls.
ExpressBars Suite handles much of the docking behavior for
you automatically, allowing you or your users to dock panels
to sites, float them, or even dock them to each other. You can
create complex dock control arrangements with tab containers
and side containers, resize panels, hide and show panels, and
more. You and/or your users have considerable control over
a user interface; its limited only by your imagination. If you
need to prohibit certain operations (e.g. docking to a particular
location), you can do so through code.

35

DELPHI INFORMANT MAGAZINE | January 2004

The painting of the dock panels can be set using four predefined View Styles: vsStandard, emulating the Delphi IDE;
vsNET, emulating Microsoft Visual Studio .NETs IDE; vsOffice11, emulating Microsoft Office 11; or vsXP, using the
Microsoft Windows XP painting style (if that operating system is current). Theres also strong support for persistence;
the docking manager enables you to allow users to save the
current layout to a text file, stream, or the registry.
Documentation, Demos, and Support
The documentation that accompanies this library is excellent. The complex architecture is explained in a clear
manner. Much of the Help file is task-oriented, showing
how to accomplish common tasks. As with other libraries
from this company, the demos were excellent, covering all
the main components and their features. However, I did
miss the type of tutorials that I found so helpful in the
ExpressQuantumGrid library. Their addition would help
developers get up to speed more quickly. More specific
examples of working with docking panels through code
would also be welcome. But dont worry! If you get stuck,
the technical staff at Developer Express will get back to
you quickly with the help you need. Their e-mail support
and special forum are excellent.
Conclusion
This is a wonderful library for building modern and
responsive user interfaces. In fact, I wont build another
one without it. Keep in mind that Ive been able to
describe only the main features; be sure to visit the
Developer Express Web site for additional information
and demonstration applications.

Alan Moore is a professor at Kentucky State University, where he teaches


music theory and humanities. He was named Distinguished Professor for
2001-2002. He has been named the Project JEDI Director for 2002-2004. He has
developed education-related applications with the Borland languages for more
than 15 years. Hes the author of The Tomes of Delphi: Win32 Multimedia
API (Wordware Publishing, 2000) and co-author (with John C. Penman) of
The Tomes of Delphi: Basic 32-Bit Communications Programming (Wordware
Publishing, 2003). He also has published a number of articles in various
technical journals. Using Delphi, he specializes in writing custom components
and implementing multimedia capabilities in applications, particularly sound
and music. You can reach Alan at [email protected].

T E X T F I L E

C#Builder Kick Start

oe Mayo is a pioneer in the


relatively nascent C# community.
Joe created the C# Station Web site
(www.csharp-station.com) shortly after
the C# language was introduced. His
very popular C# tutorials are accessed by
Web developers and Web sites throughout the world. Joe is a seasoned developer with more than 15 years of experience
and has programmed in a variety of languages, including assembler, C, C++,
VBA, and Forte 4GL. He also has varied
database experience.
Joe Mayo is a C# guru, and based on this
book he is an excellent teacher, as well.
His writing is clear, concise, and on the
money. C#Builder Kick Start is a boon
to any C#Builder developer, especially
those new to either the C# language, the
.NET Framework, or Borland tools.
Kick Start is comprised of four parts:
Overview of C#Builder and the C#
Programming Language, Windows
Forms Client Application Development, ASP.NET Web Application
Development, and Enterprise
Application Development.
The book follows a logical progression.
It begins by explaining the fundamentals of Microsofts .NET Framework and
the language Microsoft simultaneously
created, C#. The author thereafter introduces and examines Windows Forms,
ASP.NET, and ADO.NET development,
as well as how to create custom .NET
components. Web services and deployment are also covered.
This book not only tells you how to do
things, but also why. Mr. Mayo does not
clutter the book with filler and rehashed help file material. The information provided is solid. In addition to the
36

DELPHI INFORMANT MAGAZINE | January 2004

body of the material, there are numerous handy tables (C# keywords, .NET
types, etc.). In fact, one of my minor
complaints about the book is the lack of
a separate Table of Tables listing in the
front of the book.
Another recurring feature of the
book that is especially helpful are
the Shop Talk sections that provide
specific information on various topics, such as Understanding Interfaces and Installing New Components, just to name a couple.
Each chapter begins with an Overview
and ends with an In Brief section,
which reinforces the basic concepts
learned in that chapter. It is chock full of
tips that make it obvious that the author
spent a lot of time using the product.
For those anxious to get their hands
on any material whatsoever regarding Delphi 8.0 for the Microsoft .NET
Framework, much of the material in
this book will be interesting, helpful,
and applicable. After all, Delphi 8.0
for the Microsoft .NET Framework and
C#Builder share the same IDE, and of
course all the information in this book
about Microsofts .NET Framework
itself applies equally to both tools.
One thing I found a bit odd was the reference to the BCL (Base Class Library).
This is a result, apparently, of the book
being written at a time when what is
now called the FCL (Framework Class
Library) was known by a beta name
(Microsoft is constantly changing the
names of its various technologies).
Kick Start will benefit any .NET developer; it will also help any C# developer
(not just C#Builder developers), although

C#Builder Kick Start


by Joe Mayo, SAMS,
www.samspublishing.com.
ISBN: 0-672-32589-6
Cover Price: US$34.99
(461 pages, CD-ROM)

those using an IDE besides C#Builder


may prefer Mayos C# Unleashed. If
youre undecided about which C# tool
to choose, check out Mayos article
C#Builder vs. VS .NET: Choose Wisely
at www.c-sharppro.com/features/2003/
11/cs200311jm_f/cs200311jm_f.asp. The
CD that accompanies the book contains
a trial version of Borland C#Builder
Enterprise, as well as all the code for the
listings in the book.
With Kick Start youll acquire at least
a fundamental knowledge of the C#
language and the .NET Framework, as
well as an in-depth understanding of
C#Builder. As of this writing, C#Builder
Kick Start is the only C#Builder-specific
book available, and every C#Builder
developer should have a copy.
Clay Shannon

F I L E

N E W

Extreme Sites

By Alan C. Moore, Ph.D.

ast month we examined many of


the XP (Extreme Programming)
books available. These days, however,
an increasing number of people seek
information on the Internet rather than
from print. There are some general
sites that cover the XP landscape and
specialized sites that concentrate on
specific XP practices. There are also a
few XP sites that are Delphi-related.
Well begin with the general sites.
General XP sites. If youre surfing for
XP information, a great place to start
is the Extreme Programming Home at
www.extremeprogramming.org with its
main article, Extreme Programming, a
Gentle Introduction. This site includes
a wealth of information, plus the usual
pro-XP arguments. I especially liked
the various diagrams describing the
relationships between the XP elements.
On every page the topic or discipline is
in bold; by clicking on it you can see
its relationship to other XP aspects. If
you want to learn about the nuts and
bolts of XP, I recommend The Rules
and Practices of Extreme Programming
page, which divides the disciplines and
issues into four general categories: Planning, Coding, Designing, and Testing.
Well take a few minutes to examine
each of these categories.
In XP, Planning (and even coding)
involves both the programmers and
the customers. The Planning category
includes sub-topics related to user stories, release scheduling, iterations, and
other issues involving interpersonal
interactions. In the short article on User
stories I acquired a better understanding
of XP stories than from any of the books
I reviewed last month. For example, I
learned that while these stories may fulfill the same function as use cases, they
are by necessity quite different. Because
37

DELPHI INFORMANT MAGAZINE | January 2004

they are written by customers to define


the desired systems functionality, they
cannot be written in a complex language
like UML. As the article describes it,
they are in the format of about three
sentences of text written by the customer
in the customers terminology without
techno-syntax. But they do serve a
function similar to usage scenarios, and
eliminate the need for a large requirements document. Among other things,
they help to create time estimates for
release planning, they drive the creation
of the acceptance tests, and they provide
just enough detail to estimate how long
the story will take to implement.
When we think of coding we might
think of one or more developers working
alone or in groups to implement certain
functionality or remove bugs. But as this
major category of Coding demonstrates,
in XP things are different. The first subcategory is entitled The customer is
always available. That strikes me as
extreme (and other sites well discuss
offer alternative approaches). There are
also articles on the other practices weve
been discussing, including writing code
to agreed-upon standards, writing unit
tests before the units themselves, pair
programming, collective code ownership,
and my favorite no overtime.
The Designing section includes topics of particular interest to developers,
including Simplicity, Spike solutions,
and of course, Refactoring. Simplicity
is obvious, I think. The simpler the
code, the easier it is to modify later.
To keep code simple, one must resist
the temptation to introduce new functionality before its needed. I like to
think of spike solutions as enlightened
hacking. This site defines a spike as a
very simple program to explore potential solutions to technically difficult

problems. While the spike addresses


only the problem at hand, and usually
results in throw-away code, it nevertheless can be a great time saver by allowing developers to come up with a solution in a manageable environment.
The final large topic, Testing, is one
that we discussed at length earlier. In
this section you will find some helpful
articles on unit tests, acceptance, debugging, etc. Overall I found this site easy
and pleasant to navigate.
Another general site, XProgramming.com,
is hosted by Ron Jeffries and includes
articles by him and others. Those articles
cover various topics, including the current state of XP, related techniques, and
reports of first-hand experiences using
XP. There are a number of articles that
use C#. Some of Rons areas of interest
include the crucial practices of test-driven
development and refactoring. Among
other peoples articles is an Unofficial
XP FAQ written by Peter Gassman in
1999. In addition to the many articles,
youll also find resources such as testing
frameworks and software.
Along with Kent Beck, Ward Cunningham is one of the main creators of XP.
He hosts the Portland Pattern Repository,
a Wiki Wiki Web site that includes firsthand experiences using XP in various
projects. As I understand it, the Wiki
Wiki concept allows visitors to a Web
site to actually contribute to the modification or evolution of that Web site. The
specific entry point to the XP part of the
site is www.c2.com/cgi/wiki?Extreme
ProgrammingRoadmap. This site is as
rich as any Ive discussed and includes
some unique information, including the
identity of The Three Extremos (hint:
they are all mentioned by name in this
column). As you would expect, there is

File

New

information on many, if not all, of the XP


practices. More importantly, there is discussion of the implications of XP beyond
the domain of the developers. For example, an article on Extreme Management
suggests extending the paired programmer model to upper-level management.
Now thats radical!
One page on this site, Beyond
Extreme Programming, invites discussion on alternative processes beyond
XP, such as an alternative to the Onsite
Customer. Finally, this site includes
(in my opinion) the best collection of
XP links Ive seen, including international ones. There are other general XP
sites that deserve mention. Extreme
Programming the New Zealand Way
(www.xp.co.nz) includes succinct
articles on the major XP practices
and a few unusual pieces. I especially
liked the Meditation in preparation
for encountering Extreme Programming that I think was contributed by
Kent Beck. These rather contemplative questions might win some new
converts to XP. Author Willam Wakes
XPlorations (www.xp123.com/xplor)
also includes a large number of articles
on various XP topics. Theres a link
to a recent one published in Methods
& Tools called Extreme Programming
as Nested Conversations that does an
excellent job of explaining the roles of
the various players in XP.
As one of the main gurus of Refactoring,
Martin Fowler, hosts a Web site devoted
to this topic. In addition to the updates
to his book, the site includes material
that was not included in that book, a
dozen or so refactoring links, and an
online catalog of refactorings.
Theres also a site devoted exclusively to Paired Programming at
www.pairprogramming.com. It includes
academic research on the topic and
actual case histories. Im pleased to
report that I did get some feedback
from readers on the topic of Paired Programming. One developer from the UK
shared with me the obvious difficulty
of using Paired programming when
you are on your own. He went on to
share some experiences, stating that
on [my] first XP project I was never
really convinced this worked, it was my
least favorite part of XP. In his case he
found that often the dominant person
did most of the work but with more
38

DELPHI INFORMANT MAGAZINE | January 2004

difficult coding problems a second


opinion sometimes helped greatly. He
did encourage me by saying one man
bands can use XP to their advantage if
they are sensible about things and tailor
the process to their own ends.
What about Delphi XP sites? Although
there arent nearly as many as you will
find for Java, there are still a number
of Delphi XP sites available. A site I
enjoy visiting (and hope to contribute to
myself), HowToDoThings.com, is run by
a Delphi developer. It includes a link to
an article that originally appeared in The
Delphi Magazine in December, 2001 entitled Testing: Quality Time With DUnit
by Rob Bracken. If youve worked with
DUnit following Ralph Krauses informative article Extreme Testing that
appeared in the June, 2003 issue of this
magazine, youll find additional information and examples here. Or you can surf
to www.BigAtticHouse.com/qtest.php
and find an alternative to DUnit. As
stated on the site, the idea behind QTest
is to create a mechanism like DUnit that
can be used by a larger percentage of
users not necessarily comfortable with
creating their own classes in Delphi. Its
nice to have choices.
Delphi/JBuilder developer Kyle Cordes
has a nice article on XP (2001) on his
Web site (www.kylecordes.com/
story-127-extreme-programming.html)
with useful links and some discussion
of XP support for Delphi, which has
expanded somewhat since the article
was written. There are also articles on
refactoring and other related XP topics.
I suspect many of you have heard of
ANT, the Java testing tool that supports combining tests into large suites
that can be run at one time. WANT is
the Delphi version of this tool, allowing developers to automate building,
testing, and packaging of applications
and libraries. As with many open
source projects, its located on SourceForge at SourceForge.net/projects/

want. For some thoughts from one of


the Delphi giants on XP, DUnit, and
WANT, see Charlie Calverts article
on the Borland Developer Network
at community.borland.com/article/
0,1410,30049,00.html. I especially appreciated his candor in explaining when he
doesnt strictly follow the XP approach.
A general site with a good deal of Delphi
coverage is About.com, where Zarko
Gajic has many Delphi articles. One
of these, Before you start optimizing
Delphi code (delphi.about.com/library/
weekly/aa102301a.htm), promises to
help you avoid a new twist on Murphys
law: Any program will expand to fill
available memory. Interestingly, it deals
with much more than just optimizing.
There are linked articles on writing solid
and robust code, debugging techniques,
some great resources (tools), and yes
extreme programming. Zarco provides
one of the most succinct definitions of
XP Ive seen, describing it as a deliberate and disciplined approach to software
development. This methodology emphasizes teamwork. Managers, customers,
and developers are all part of a team
dedicated to delivering quality software.
But is it Extreme? In the first installment of this series I posed the question
about XP, Is it really that extreme?
In answering I must admit that it is
extremely disciplined, extremely wellconceived, and from the reports of its
devotees, extremely effective. I appreciate greatly the feedback and suggestions I received from several readers.
One pointed out the connection of XP
to the larger world of Agile Programming, an approach he described as
finding the smallest methodology
that fits the size of the problem you
are working on. This is another topic
I expect to be examining in the near
future. Ive been having much fun, in
fact too much fun, examining these
sites. The fun will continue next month
when I return to one of my favorite
topics, Delphi on the Web. Until then...

Alan Moore is a professor at Kentucky State University, where he teaches music theory and
humanities. He was named Distinguished Professor for 2001-2002. He has been named the Project
JEDI Director for 2002-2004. He has developed education-related applications with the Borland
languages for more than 15 years. Hes the author of The Tomes of Delphi: Win32 Multimedia API
(Wordware Publishing, 2000) and co-author (with John C. Penman) of The Tomes of Delphi: Basic
32-Bit Communications Programming (Wordware Publishing, 2003). He also has published a number
of articles in various technical journals. Using Delphi, he specializes in writing custom components
and implementing multimedia capabilities in applications, particularly sound and music. You can
reach Alan at [email protected].

You might also like