Deployment and INI files

Delphi 2009 has an unwanted side effect related with the deployment of dbExpress configuration files. This issue is expected to be solved in the Delphi 2009 Update 2, still not available at the time I was writing the book. You can probably ignore the following, if you have that update installed. In the release version of Delphi 2009, if you configure the TSQLConnection component setting a connection and a driver, your application will need to read the dbxdrivers.ini and dbxconnections.ini files...

End

In the example code you'll also find a slightly better (and more precise) version that uses GetTickCount rather then the current time (Now), although if you are looking for really precise timing you would be better off using the specific timing service offered by the QueryPerformanceCounter Windows API. Notice, though that if you execute the standard version and the one based on anonymous methods you'll get output like the following Classic (string) 00 00.588 (AnsiString) 00 0l.087 (string) 00...

New and Aliased Integral Types

Although this is not strictly a compiler change, but rather an addition in the System unit, you can now use a set of easier-to-remember aliases for signed and unsigned integral data types. These are the signed and unsigned predefined types in the compiler These types were already in Delphi 2007 and previous versions, but the 64bit ones date back only a few versions of the compiler. The Nativelnt and NativeUInt types, which should depend on the compiler version (32 bit and future 64 bit) were...

Summary of New Units and New RTL Classes

With all of the classes of the RTL introduced to support Unicode and generics, plus many extra features, it is easy to miss some of the changes. For this reason, at the end of the coverage of the run time library (which was only partially done in this chapter) it is worth having an overall look at the new units and classes of the RTL. I haven't listed global routines, as this would have been a huge task. The following are the new units of the run time library, with the list of the classes they...

Enhancements to Standard Components

If there are some new features that affect all controls, most of the improvements in the VCL in Delphi 2009 are specific to individual controls. The core standard controls, as well as the common controls, have been extended by Microsoft from one version of Windows to the next, while the VCL has often neglected supporting new these new features of the OS, sometimes for backward compatibility reasons (as similar applications might have problems running on older versions of the operating system,...

Anonymous Event Handlers

Since the early days, one of the distinguishing features of Delphi has been its implementation of event handlers using method pointers. Now with the advent of anonymous methods, it might be interesting to use this feature to attach a new behavior to an event without having to declare a separate method and capturing the method's execution context, thus avoiding adding extra fields to a form to pass parameters from one method to another. As an example, I've added an anonymous click event to a...

New UTF Conversion Functions

Beside many automatic string transformations there are also several new direct string conversion functions you can use. For example, there is a large number of new conversions functions to and from UTF-8 encoding, overloaded for the different string types function UTF8Encode( ) RawByteString ShortString function UTF8ToWideString( ) WideString UnicodeString function UTF8ToString( ) string

Unicode in Datasets Take

The TDataSet and TField classes were among the few classes already supporting Unicode since Delphi 2006. That Unicode support, though, was based on the WideString type, which is still available but is not the standard approach used in Delphi 2009 for supporting Unicode. As we saw in Chapter 2, the WideString type represents a less-optimized and non-reference counted type holding wide characters, originally introduced for COM compatibility. If you compare the source code of the database...

The Speed of Building Strings

Needless to say that most Delphi developers will immediately wonder if using the TStringBuilder class would make their code faster or slower than using plain string concatenation or other string operations. The short answer is that performance is similar, with a slight advantage for the classic string concatenation, although real-world situations probably differ from the simple tests I've performed in the StringBuilder example. I've done three different tests plain string concatenation, adding...

Behind Anonymous Methods

What is this Invoke method What happens behind the scenes in the implementation of anonymous methods The actual code generated by the compiler for anonymous methods is based on interfaces, with a single invocation method called Invoke, plus the usual reference counting support (that's useful to determine the lifetime of anonymous methods and the context they capture). You can see those interface methods in the editor if you use code completion, in the following way Querylnterfacelconst IID...

Chapter New IDE Features

The 6th incarnation62 of the Galileo IDE has only a limited set of new capabilities, if you don't take into account the fact that everything has been converted to Unicode, which was probably far from trivial. The most relevant improvements relate with the new extensions to the Project Manager and the ability to share project options among different projects, using the new options files. Windows resource management improves significantly in Delphi 2009, too. 62 I'm counting them as follows 1 was...

Type Rules on Generics

When you declare an instance of a generic type, this type gets a specific version, which is enforced by the compiler in all subsequent operations. So if you have a generic class like type TSimp1eGeneric< T> class Value T as you declare a specific object with a given type, you cannot assign a different type to the Value field. Given the following two objects, some of the assignments below (part of the TypeCompRules example) are incorrect var sgl TSimp1eGeneric< string> sg2...

Table Of Contents

The Status of Why Win32 This The Contact Chapter 1 What is Characters from the Past from ASCII to ISO Unicode An Alphabet for the Entire From Code Points to Unicode Code Points and Unicode Transformation Formats Looking at Unicode Code Point Byte Order Unicode in Unicode API Call UnicodeString Parameters in API Unicode and Fonts and Unicode Before Delphi What's Chapter 2 The Unicode String From AnsiChar to Char as an Ordinal Converting with 32-bit The New Character Of String and The Internal...

Marquee and More for Progress Bar Controls

The ProgressBar component is another common control that got extended features over the last few years that were not directly supported by the VCL. If you are not using runtime themes you can set a custom color for the bar and its background, using the BarColor and BackgroundColor properties. A nice feature, available on Windows XP and Vista, is the marquee style of the progress bar, in which the bar keeps moving to show the program is working without indicating a specific position. This is a...

Begi n

Threads I TParallel.Create suspended threads I .Proc aProc threads I .Resume end while TParallel.ThCount > 0 do begi n Application.ProcessMessages Sleep (l00) end end This global function sets up the requested number of threads, activates them, and then waits for all threads to finish. The ThCount class data of the TParallel class, in fact, is incremented by each thread on startup and decremented by the class destructor (automatically triggered by setting the FreeOnTerminate property within...

Methods Chaining in String Builder

A very specific feature of the TStringBuilder class is that most methods are functions that return the current object. This coding idiom opens up the possibility of methods chaining106, that is calling a method on the object returned by the previous one. Instead of writing sBuilder.Append(l2) sBuilder.AppendLine sBuilder.Append( 'hello') sBuilder.Append(l2).AppendLine.Append( 'hello') which can be formatted as sBuilder. Append(l2). AppendLine. Append( 'hello') I tend to like this syntax better...

Field Types and Strings

It is interesting to notice how the different field types are mapped to different native string types. I'm specifically referring to the TStringField and TWideStringField types, of course. The Value property for these field types changed from earlier versions of Delphi, but it was kept the same until Delphi 2007, despite the changes in metadata support (including the field names, mentioned earlier) TWideStringField.Value wideString WideString UnicodeString In case your program uses a...

Defining a Custom Encoding

Even if Delphi 2009 comes with a few predefined encodings, you might end up needing more. An example of a not-so-common encoding you might need is UTF-32 (little-endian). Defining and using a custom encoding is certainly possible, although there are a few rough edges. First of all, you have to define a class that inherits from either TEncoding or one of its descendants. Since there are no existing encoding classes handling 4-bytes characters, I've gone for inheriting from the base class type...

Unicode and Fonts and APIs

Another important fact to keep in mind is that whilst Windows does indeed support Unicode, it does so in different ways in different versions. The Windows 9x (an acronym meaning 95, 98, or ME - Millennium Edition) series has limited support for Unicode. If you have Windows 2000, Windows XP, or some of the server operating system versions, you can take advantage of the Supplemental Language Support. This can be installed in the Regional and Language options of the Control Panel. This extra...

The Legal Side of the Ribbon

When you install Delphi 2009, you'll be presented with a rather strange looking dialog (which was required by Microsoft) You have chosen to install the Ribbon Controls feature of the VCL. In order to use, copy, modify or distribute this set of user interface controls, you must agree toa licensing agreement with Microsoft for the Office W. You receive no rights in the Office LH from Embarcadero. Therefore, you may not distribute applications using the Office LH from us without obtaining a...

Advanced Features of Thin Plus

I upgraded the ThinPlus client and server applications to DataSnap 2009 following the steps mentioned earlier, even if these are some rather complex DataSnap programs, with several customizations. These include fetching data packets manually, using a master details structure, executing a parametric query, transferring extra data along with the data packets, and the custom remote login I've just covered. It is worth having a look at these features, even if briefly, as they should help those of...

Function Get Value T publ ic

88 The term polymorphisms in OOP languages is used to denote the situation in which you assign to a variable of a base class an object of a derived class and call one of the base class virtual methods, potentially ending up calling the version of the virtual method of the specific subclass. property Va1ue T read GetVa1ue end The Create and GetVa1ue methods of the record could simply assign and read back the value. Using this code you can create an object, create a smart pointer wrapping it, and...

Ready To Use Reference Types

Every time you use an anonymous method as a parameter you need to define a corresponding reference pointer data type. To avoid the proliferation of local types, Delphi provides a number of ready-to-use reference pointer types in the SysUtils unit. As you can see in the code snippet below, most of these type definitions use parameterized types, so that with a single generic declaration you have a different reference pointer type for each possible data type type TProc< T> reference to...

Unicode String Parameters in API calls

Although most Windows API functions taking a string as parameter are declared in the Windows unit with a PChar parameter, there are some exceptions to this rule. The GetTextExtentPoint32, ExtTextOut, LoadKeyboardLayout, DrawText, SetWindowText, LoadCursor, WinHelp, and HtmlHelp API declaration have overloaded (and inlined) versions taking a UnicodeString parameter. I guess this might help to apply the proper conversion in case you are passing a string, any string, to them (as you'll better...

Buttonededit C Builder

Action Manager.269, 304, 306p., 309, 320 305 Active ActiveX Control Wizard 294 Alan Allen Anders Anonymous methods 161, 178, 380 AnsiChar. 23pp., 44pp., 48, 69pp., 84p., 87 55p. AnsiStrings unit 95pp., 243p. 281 Application Apply Option Set dialog box 120 341 240 Basic Multilingual Plane 27, 54 356 343 203, 228, 231 BOM 29, 34, 72p., 91, 233, 268 334 Borland Resource Compiler 126 293 Byte Order C++ Capture the execution context 182 272 Character Character unit 47, 86, 243 133 Chris Class Class...

More and Less Fast Code

Over the last few versions of Delphi, CodeGear has borrowed (in a way that is compliant with the original license) several routines from the FastCode project111. Now, although these routines are still in the product, most of them related to string management and are not in the new AnsiStrings unit, and are probably not going to be used as much as the corresponding Uni-codeString routines. On the plus side, for FastCode integration, there is a new optimized version of the RoundTo in function in...

Project Manager Views

Another brand new feature is the Project Manager views configuration. On the right side of the toolbar, you can see a new Views button, that let's you change how the Project Manager shows files that have been placed in different folders. There are three options. I tested them by creating a sample program (called ProjManagerTest) with two forms in the main folder and two units in a secondary folder called Shared and placed at the same level in the file system hierarchy Directory (Nested) is the...

The Project Manager

Along with a redesign of the Project Options dialog box (which I still haven't completely covered when examining the new build configuration features) Delphi 2009 sees a significant update of the Project Manager pane, one of the most commonly used panes of the IDE. Even a cursory glance of its window will reveal some of its new features UnicodeWinApi.dprqj - Project Manager S ProjectGroupl UnkodeWinApi.exe Eh Build Configurations jr1 Debug Release You can see there is a new Build Configurations...

Managing Resources in the IDE

In the most recent versions of Delphi, you could add resource scripts (.RC files) or compiled resource files (.RES files) to the Project Manager to let it compile them along with the project linking them to the executable. In Delphi 2009 managing resources has been simplified by the inclusion of a few more tools. First, you can now drag individual resource files to the Project Manager to get them included as resources in a project. You can drag icons, bitmaps, and more. Delphi will generate a...

Actions and The Ribbon

As I mentioned a few times already, the Ribbon control is based on Delphi's ActionManager architecture. We'll see how to create a Ribbon-based UI with these components in the next example. Before I get to that, however, I need 133 This is a bug that will be fixed. As a workaround you can use the code provided in the bug report at to recap the key features of this architecture for those who've never used it134. If you used the ActionManager component in the past, you can skip the next two...

Generic Key Value Pairs

As a first example of a generic class, I've implemented a key-value pair data structure. The first code snippet below shows the data structure written in a traditional fashion, with an object used to hold the value type procedure SetKey const Value string procedure SetVa1ue const Value TObject publ ic property Key string read FKey write SetKey property Value TObject read FValue write SetValue end To use this class you can create an object, set its key and value, and use it, as in the following...

Variants and Open Arrays Parameters

When you are working with variants, most variant to string conversion code will work as expected, as there is a new variant type Unicode string 258 not OLE compatible All variant-based conversions should work properly, not causing much difference in your variant-related code, unless you have to interact to COM or OLE automation, in which case you still have to use the WideString type as before, so this is not an actual change . When working with variant open array parameters, and other untyped...

Appending and Concatenating Strings

Another type of coding you should replace whenever possible is the string concatenation code. It is not too hard to look for occurrences of AppendStr in your code also because using it causes a deprecated warning , but it is way more complicated to replace the direct string concatenation performed with the sign. Also, the suggestion is to replace direct string concatenation with the use of the TStringBuilder class in case you are performing a complex concatenation56. For showing a message made...

Unicode in DFM Files

I'm just mentioned how the Delphi IDE can treat Unicode-enabled source code files, but we have not seen what happens to DFM files as you add an extended character to one of the properties. A simple experiment would be 52 These two programs were part of my Mastering Delphi 2005 and I've not copied the code to the source code base of the current book, as they are rather simple. They can be downloaded from the source code of that book, though, at http www.mar-cocantu.com md2005. to open a brand...

The New Registered Type Libraries Pane

Delphi Add New Type Library

Once the server is registered you can double check it is in the system by opening the new Registered Type Libraries view of the Delphi IDE, using the corresponding command located under the View menu. This editor pane lists all registered type libraries or ActiveX controls on the system, let's you unregister any of them, register new ones, search the list of type libraries. As you can see below, the list should include our newly registered library QsimpleServerJTLS Qriumlmpl Type Libraries _...

Client Starting the Server and Opening Multiple Connections

As a practical example, the DsnapMethods project let's you create multiple client connections from a single instance of a client application using multiple instances will yield the same result , by creating multiple instances of the form that has the SQLConnection component and stored a local instance of the client proxy, created the first time it is used. Not only can the client create multiple client connections, but it can also start the server program with a given life cycle setting. This...

Project Configuration Manager

With the build options available directly in the Project Manager pane, you don't have to use the Configuration Manager to change the current build configuration. Still, this dialog box was quite handy as it let you change the build configuration for many projects in a project group at the same time. In fact, the Configuration Manager is also available in Delphi 2009, and in a much improved version that let's you manage the various build configuration and option sets for all of the projects of a...

Syntax and Semantic of Anonymous Methods

An anonymous method in Delphi is a mechanism to create a method value in an expression context93. A rather cryptic definition, but one encapsulating 92 More information about the jQuery JavaScript library at http jQuery.org. 93 In the words of anonymous methods implementer Barry Kelly of CodeGear R amp D, http barrkel.blogspot.com. it with a lot of precision and underlining the key difference from method pointers, the expression context. Before we get to this, though, let me start from the...

Combo Boxes and Text Hints

In the Windows API, ComboBoxes have a strict relationship with Edit boxes, as they got their name and some of their implementation code from being a combination of an Edit and a ListBox. So you should hardly be surprised to see a TextHint property also added to the TComboBox class, just like the TEdit class. Again, this feature requires Windows XP or a more modern version of Windows118. There is a simple combo box with a text hint in the EditFamilyDemo example, as you can see in the last image...

Procedure Sort overload

procedure Sort const AComparer IComparer lt T gt overload where the IComparer lt T gt interface is declared in the Generics.Defaults unit. If you call the first version the program will use the default comparer, initialized by the default constructor of TList lt T gt . In our case this will be useless. What we need to do, instead is to define a proper implementation of the IComparer lt T gt interface. For type compatibility, we need to define an implementation that works on the specific TDate...

Characters from the Past from ASCII to ISO Encodings

The American Standard Code for Information Interchange ASCII was developed in the early '60s as a standard encoding of computer characters, encompassing the 26 letters of the English alphabet, both lowercase and uppercase, the numbers, common punctuation symbols, and a number of control characters4. ASCII uses a 7 bit encoding system to represent 128 different characters. Only characters between 32 Space and 126 Tilde have a visual representation, as show in the following table While ASCII was...

Windows Install Clean Up

At times, when uninstalling Delphi to replace it with an updated version, the installer complains, stops and won't work as expected. In these cases, Code-Gear recommends cleaning all of the application folders including some hidden ones that depend on the operating system . An alternative it to use Microsoft own Windows Install Clean Up utility, that you can find at scid kb en-us 290301 Beware that using such a low-level tool can hamper your system, so proceed with caution only after reading...

New Project Options for the Compiler

In the Delphi Compiler Compiling page, which used to be called compiler, the Code Generation section has the following new options Code inlining control corresponds to the INLINE compiler directive and controls how inlining works. Emit runtime type information corresponds to - M flag on the command line or the M directive, and determines the generation of runtime time information for a given class or all of the classes of a project . Minimum enum size corresponds to - Z flag or the Z directive...

The New Ansi String Type

Differently from the past, the new AnsiString type string carries one further piece of information, the code page of the characters in the string. The DefaultSystemCodePage variable defaults to CP_ACP, the current Windows code page, but it could be modified by calling the special procedure SetMultiByteConversionCodePage. You can do this to force an entire program to work by default with characters in a given code page that the operating system installation must support, of course . 36 This...

The Delphi Class Explorer

A brand new pane in Delphi 2009 is the Delphi Class Explorer pane available from the Delphi Class Explorer item of the View menu . The Delphi Class Explorer offers a project wide representation of the symbols, differently from the Structure View68, that shows a somewhat similar graphical representation of the elements of a single unit. In the Delphi Class Explorer at the first level, you'll see a list of nodes hosting the global definition of each unit plus the project file , while the...

Ribbons for Database Applications

It is quite obvious to see how the use of the Ribbon controls would apply to a document oriented application, but what about programs doing totally different operations, like working on database data Considering that we have a set of standard database-related actions available, we might be tempted to use the Ribbon to replace the classic DBNavigator, and this is indeed posMarco Cantu, Delphi 2009 Handbook sible and also quite simple to achieve . I'm not exactly sure this respects Microsoft...

Tool Palette Search

In Delphi 2006, you could type while the Tool Palette was selected to filter components starting with those letters with the exception of the initial T . In Delphi 2007 you could do the same, but also by selecting text inside the component name, so you could pick, say, IdHTTP by typing the more obvious HTTP. In Delphi 2009, the Tool Palette has the same behavior as Delphi 2007, but with a different user interface that makes it more obvious to all users that you can search the components list by...

Using Raw ByteString

What if you need to pass an AnsiString as a parameter to a routine When the parameter is assigned to a specific string type with an encoding, it will be converted to the proper type, with the potential for data loss. That's why Delphi 2009 introduces yet another custom string type, called RawByteString and defined as type RawByteString type AnsiString ffff This is definition creates a string type with no encoding or, to be more precise, with the placeholder ffff indicating no encoding. A...

The Internal Structure of Strings

One of the key changes related to the new UnicodeString type is its internal representation. This new representation, however, is shared by all reference-counted string types, UnicodeString and AnsiString, but not by the non-reference counted string types, including the ShortString31 and WideString types. The representation of the classic AnsiString type was the following The first element counting backwards from the beginning of the string itself is the Pascal string length, the second element...

Procedure Init procedure Enforce Init pubic

Constructor Create aCustKey TCustomerKey property CustKey TCustomerKey read FCustKey write SetCustKey pub1ished read GetCustNo write SetCustNo property Company string 84 Dictionary in this case means a collection of elements each with a unique key value referring to it. It is also known as an associative array. In a classic dictionary you have words acting as keys for their definitions, but in programming terms the key doesn't have to be a string even if this is a rather frequent case . read...

From Events to Actions

Delphi's event handling architecture is very open You can write a single event handler and connect it to the OnClick events of a toolbar button and a menu. You can also connect the same event handler to different buttons or menu items, because the event handler can use the Sender parameter to refer to the object that fired the event. It's a little more difficult to synchronize the status of toolbar buttons and menu items. If you have a menu item and a toolbar button that both toggle the same...

Check Boxes in a Header

Another common control, albeit not very frequently used, is the HeaderCon-trol component. In the VCL of Delphi 2009, this control now supports fixed width header sections using the NoSizing Property , extra non-visible headers if they don't fit using the Overflow property and, more interestingly, check boxes within the header sections. To enable this feature you have to turn it on for the control as a whole and then for each individual section, as indicated by the properties of the control and...

Chapter Anonymous Methods

The Delphi language has had procedural types that is, types declaring pointers to procedures and functions91 and method pointers that is, types declaring pointers to methods for a long time. Although you might seldom use them directly, these are key features of Delphi that every developer works with. In fact, methods pointers types are the foundation for event handlers in the VCL every time you declare an event handler, even a pure 91 In case you want to learn more, procedural types are covered...

Data Pumping for dbExpress

When working with multiple databases it is often necessary to migrate data from one server to another, and with table definitions not exactly identical among different servers this operation can take time. Following approach of the old DataPump available for the BDE, the Internet services team of Code-Gear147 has built a dbExpress data pump application 147 The tool was developed by Jon Benedicto, Yorai Aminov, and John Kaster, who's the head of the Internet services team at CodeGear. John...

From DBImage to Poor Old DBGrid

A specific new feature of the DBImage control is its new Proportional property. What is also relevant is that the DBImage control inherits the ability to handle new file formats, like PNG, from the Image control. Despite rumors, the DBGrid control hasn't been revamped in Delphi 2009 and remains quite an old control with limited capabilities. What CodeGear has done, instead, is to make one of the third party grid controls available to registered users of Delphi 2009148, the InfoPower Grid...

Extended Metadata Support

A recent feature of dbExpress, even if not new to Delphi 2009, is its extended support for metadata. This feature was introduced in the December 2007 Update of Delphi 2007, but was not covered in Delphi 2007 Handbook which was released before that update . The new metadata support is used extensively by the Data Explorer pane of the Delphi IDE, but can also be used by any application. In short, you'll not only be able to browse the database structure but also to use classes and 146 This is...

Unicode in

Since the early days, the Win32 API which dates back to Windows NT has included support for Unicode characters. Most Windows API functions have two versions available, an Ansi version marked with the letter A and a wide-string version marked with the letter W. 15 As we'll see in the next chapter, the new Character unit includes methods for checking whether a Unicode code point is a symbol, a punctuation mark, a space As an example, see the following lines from Windows.pas of Delphi 2007...

Improved Graphics Support

In the early days, Delphi graphic support was mostly limited to bitmaps. Over the years, there have been extensions to the image formats you could use in the Image component, including JPEG format support125. In Delphi 2009 the support for multiple images has been extended to PNG and all formats can now be used with the Image control as well with the ImageList control. Moreover, the ImageList control supports setting a specific color depth, although increasing its value will clear all images...

Supporting Key Tips

After all of these steps we have a fully working application with a nice Fluent UI. Users can click on the various visual elements tab pages, controls to work with it. But what about using the keyboard Beside the fact you can still associate shortcut keys to the various actions like a classic Ctrl-C for Copy , the Ribbon has its own keyboard-enabled interface. All you have to do it to provide an appropriate value for the KeyTip property of each of the Ribbon user interface elements tabs,...

Radio Group Text Wrapping

The RadioGroup component the custom combination of a GroupBox with actual RadioButton controls gets a single new feature, the support for word wrapping in the radio buttons they contain. The drawback in this case is that the component won't be able to calculate the vertical spacing of the individual items properly, and if you have say an element with three lines of text, it might turn out that the top of the first line or the bottom of the last line won't be visible. An example of wrapping and...

Drivers in the Executable

Finally, to make the application work you have to add the DbxInterBase unit to your uses clause, which contains the driver and metadata information for the specific database. 145 The original code, and the rationale behind it, can be found on the blog of Chau Chee Yang, at the address This unit is generally added automatically as you set the Driver in the SQL-Connection component, but I've seen situations in which this was not managed properly, leading to the following error Debugger Exception...

The idecaption Flag

You probably know although this was a well-kept secret for many years64 that you can run multiple instances of the IDE, possibly at the same time, with different registry settings using the -R command line flag. The problem if you run two different versions of the IDE at the same time is that it is hard to tell which is which. Another companion command line parameter for the IDE is -idecaption, that takes a caption as value. Summing the two flags you could run the IDE with the following link C...

Application Menu

To complete our application, for which we hooked several custom actions but had to write no actual code, we should add two other relevant elements of the Ribbon user interface. Both are added using commands of the Ribbon component editor the shortcut menu that appears at design time when the component is selected and can be added only if the ActionManager is set. The first key element is the Application menu, the round control element in the top left corner of the Ribbon replacing the...

Returning Features Active Forms

Some other features from the Delphi 7 times got back into Delphi 2009 after a long absence. One of them is the ActiveX Control Wizard including Active Forms . Notice, though, that this wizard doesn't generate the proper HTML deployment files as it did in the past. Actually most of the COM-related wizards have been improved graphically and partially in their feature set for Delphi 2009, as you can see in the overview provided by Chris Bensen in his sneak peek blog post at...

Dont use PChar for Pointer Math

To summarize this section, stop using PChar for anything that isn't character or string related. If you need to be able to keep compiling your code in past versions of Delphi, you can use Inc and Dec and possibly change some of the other code. If all you need to support is Delphi 2009, convert the code to PByte generally the easier route or use specific pointer types and the new pointermath directive. In any case, doing a search for PChar on your entire code base is generally a good idea

Groups And Commands

Now that I have all of these actions in place, I can create a Ribbon user interface for them. After creating two tabs and a few groups, I can drag actions into the groups. Here are a couple of groups These groups host direct commands, so there is nothing specific to set. Another group has a set of non-exclusive options, like setting the text in bold and italic. For the action items of such a group it is better to pick the csCheckBox value for the CommandStyle property rather than the default...

Byte Order Mark

Files storing Unicode characters often use an initial header, called Byte Order Mark BOM as a signature indicating the Unicode format being used and the byte order form BE or LE . The following table provides a summary of the various BOM, which can be 2, 3, or 4 bytes long We'll see in the next chapter how Delphi manages the BOM within its streaming classes. The BOM appears at the very beginning of a file with the actual Unicode data immediately following it. So a UTF-8 file with the content...

Screen Tips Manager and Actions

Shell Object Editor

Even if you can use Screen Tips without a Ribbon and an ActionList or Action Manager, the latter is the scenario in which they work best and for which there is specific support. In fact, as you place a ScreenTipsManager component in a form that uses an ActionList or ActionManager with or without a Ribbon control , you'll be able to use the various features of the component editor, that is the commands of its shortcut menu The Generate Screen Tips command will help you create a basic screen tip...

Parallel For Loop

One of the core reasons behind the introduction of anonymous methods in Delphi 2009 is the desire to create a parallel library, a collection of techniques to allow applications to take advantage of the multi-core CPUs any modern computer has these days. Rather than having to manually code multi-threaded applications, such a library would let you write almost standard code that creates threads behind the scenes. This library is the subject of many blog posts by Delphi's chief architect Allen...

The Data Snap Administrative Interface

When you write a DataSnap 2009 server, you can run it, and connect the Delphi IDE to it at design time to get help in writing the client code. This help comes in the form of lists of available methods and providers and also in terms of the generation of the client side proxy classes. To accomplish this every server has an extra interface, internally called DSAdmin. In a deployed server you can disable this interface, to avoid others from writing client applications using Delphi or at least make...

Upgrading Project Configuration Files

Since the early days of Delphi, the project source code file with the .DPR extension contains Object Pascal code and uses one or more separate project configuration files for storing other settings. The format and extension of the project configuration file changed a few times in recent versions, moving from an INI file to an XML file and then to an XML file for MSBuild the .dproj file format . 65 As you might have heard, Tibur n was the field test name for Delphi 2009. Marco Cantu, Delphi 2009...

New Resource Compiler

Recent versions of Delphi, up to and including Delphi 2007, used the Borland Resource Compiler BRCC32.EXE an outdated program emitting the following historical copyright notation Copyright c 1990, 1999 Inprise Corporation. All rights reserved. Delphi 2009 ships with a new resource compiler, or to be more precise a different resource compiler the one from the Microsoft Windows SDK. This is certainly beneficial is terms of support for all of new resource formats Windows handles, but causes a few...

Conversions Slow Down the Code

The automatic conversions happening behind the scenes are extremely handy, as the system does a lot of work for you, but if you don't carefully consider what you are doing you might end up with some extremely slow code, because of continuous conversions and string copy operations. Consider the following code part of the StringConvert example strl 'Marco ' str2 'Cantu ' for I l to l0000 do strl strl str2 Depending on the actual string type of the two strings, the algorithm can be extremely fast...

The New Character Unit

To better support the new Unicode characters and also Unicode strings, of course Delphi 2009 introduces a brand new RTL unit, called Character25. The unit defines the TCharacter sealed class, which is a basically collection of static class functions26, plus a number of global routines mapped to the public and some of the private functions of the class. The unit also defines two interesting enumerated types. The first is called TUnicodeCategory and maps the various characters in broad categories...

Creating a Custom String Type

Beside using the new AnsiString type, which is tied to the default code page used when compiling the application, you can use the same mechanism to define your own custom string type. For example, you can define a Latin-1 string type as I've done in the LatinTest example by writing type Latin1String type AnsiString 28591 procedure TFormLatinTest.btnNewTypeClick str1 'a string with an accent Cantu' You can use this string type as any other one, but it will be tied to a specific code page. So if...

Data Aware Controls

At first look, considering the data-aware controls of the VCL you might see very little change. In effect, it is true that they have limited new features, if you don't consider the fact that all data-aware controls are now Unicode enabled. We also saw in the last chapter how to create a database navigator based on the Ribbon control. Still, it would be nice to have some of the features that were added to other controls of the VCL. For example, the TDBEdit class inherits from TCustomEdit, but it...

Porting a Simple Custom Dataset

For Mastering Delphi 7 I wrote143 a custom dataset based on a record-to-stream architecture. So I thought that porting that custom dataset to Delphi 2009 would be a good test of the effort involved in such a process. 143 The original code actually dates back to my Delphi Developer Handbook, written for Delphi 3, and was modified for the Delphi 7 book. I have no room here to cover in detail what it takes to write a custom dataset, as that is far from an easy task. If you are interested in...

Dont Move String Data

Accessing string data at a low level, for example with a Move call, was not a very good idea in the past, as it could defeat reference counting and cause memory overruns and other problems. Calling Move for characters is even worse now that we have multiple string representations that are incompatible at the binary level. As an example, consider the following code from the MoveStrings demo that moves data from a string to a buffer and then back to another string procedure...

Strings are Strings not Bookmarks

Although you have the new RawByteString type available to represent generic arrays of characters or bytes, my recommendation is to use string types only for processing strings of characters. You might think this is obvious, but it is not. As an example, the VCL has long used a string type to represent dataset bookmarks. The Bookmark property of the TDataSet class in Delphi 2007 was of type TBookmarkStr, defined as type The string was not really there, it was simply an alias of a pointer, but...

The Inner Exception Mechanism

What happens if you raise an exception within an exception handler The traditional Delphi answer is that new exception will replace the existing one, which is why it is a common practice to combine at least the error messages, writing code like this lacking any actual operation, and showing only the exceptions-related statements procedure TFormExceptions.ClassicReraise begi n try do something raise Exception.Create 'Hello' except on E Exception do try some fix raise Exception.Create 'Another '...

Default Fonts for Application and Screen Global Objects

Delphi applications start with a predefined default font, determined at design time. This is problematic when you might want the same executable to run smoothly on different versions of Windows, like XP and Vista, that use different default fonts. The Application global object in Delphi 2009 can provide a standard font to all forms that have ParentFont set to True. To accomplish this you can set the DefaultFont property of the Application. This can be used, for example, to migrate the look and...

Build Configurations and Configuration Settings

As I mentioned earlier and you can see from the images on the previous pages, the Project Manager has a new Build Configurations node for every project that is, in cases where you are working with a project group with multiple projects active . This node replaces the rather cumbersome separ ate window used to manage the build configuration in Delphi 2007. Using the node and its sub-nodes you can change the current build configuration with a double click, and execute an actual build directly on...

Streaming Strings Lists

The ReadFromFile and WriteToFile methods of the TStrings class can be called with an encoding. If you write a string list to text file without providing a specific encoding, the class will use TEncoding.Default, which uses the internal DefaultEncoding in turn extracted at the first occurrence by the current Windows code page. In other words, if you save a file you'll get the same ANSI file as before. Of course, you can also easily force the file to a different format, for example the UTF-16...

Introducing the Fluent User Interface

As mentioned above, the Fluent User Interface was invented by Microsoft, who are seeking a patent for it132. This patent doesn't focus on the code behind the user interface the ribbon controls used in Office 2007 , but on the design of the user interface itself. Microsoft also refers to this user interface as Microsoft for the Office UI. This means that the Microsoft patent, if granted, will still apply even if the VCL implementation available in Delphi 2009 is a brand new version of the...

Interface References vs Generic Interface Constraints

In the last example I have defined a generic class that works with any object implementing a given interface. I could have obtained a similar effect by creating a standard non-generic class based on interface references. In fact, I could have defined a class like again part of the IntfConstraint project type procedure Setl val IGetValue procedure Set2 val IGetValue function GetMin Integer function GetAverage Integer procedure IncreaseByTen end What is different between these two approaches A...

Using Readers and Writers

A totally alternative approach for building large strings or writing to and reading from streams is to use the new reader and writer classes introduced in Delphi 2009, again mapped to their .NET counterparts. In Delphi there have traditionally been a couple of similar classes TReader and TWriter but they are specifically aimed at streaming properties in and out of DFM files. The new classes, instead, are better suited for more general approaches and are focused on reading and writing textual...

Tray Icon Update

The TrayIcon component, first introduced in Delphi 2007, has a new OnBalloonClick event, used for handling a click on the area of the balloon help when this is visible. To show this in practice I've extended the MyTrayIcon example of Delphi 2007 Handbook into the new MyTrayIcon-Click example, that has the following DFM definition for its main form object FormMyTrayIconClick TFormMyTrayIconClick object TrayIcon1 TTrayIcon 124 This would have been a nice case for using a generic list or objects...

Grouping in a List View

One common control worth exploring in some more detail is the ListView, that in Delphi 2009 receives direct support for grouping. This feature requires Windows XP or Vista, with the latter providing extended features. There are three new properties in the ListView control. The Boolean GroupView enables this new kind of display, the GroupHeaderImages refers to an ImageList containing the images for the group headers, and the Groups property is a collection of group definitions. Each group can...

Thread Synchronization with the VCL

In multi-threaded applications that need to update the user interface, you cannot access to properties of visual components or in memory-objects that are part of the global thread without a synchronization mechanism. The VCL, in fact, in not thread-safe as is true for most user-interface libraries . Two threads accessing an object at the same time could compromise its state. The classic solution offered by the TThread class in Delphi is to call a special method, Synchronize, passing as a...

Actions and Ribbon in Practice

After this fast-paced introduction to Delphi's Action Manager architecture, let's start creating an actual demo. The first step, of course is to create a VCL application and add an ActionManager component to its main form. Next you can drop a Ribbon control onto the form. The control should automatically hook itself to the action manager, if not use its ActionManager property. Before adding any action to the ActionManager, add ImageList controls and connect them to it. Adding standard actions,...

Unicode String Lists

A strictly related change is the return to the TStrings type for lists of strings, instead of the replacement TWideStrings type used in recent versions. In these cases, for compatibility reasons, there is often an overloaded version that is compatible with the WideString implementation. For example, the GetFieldsList method of the TDataSet class is now defined as procedure GetFieldNames List TStrings overload virtual procedure GetFieldNames List TWideStrings overload virtual The potential...

First Simple Ribbon

My first Ribbon example is a very bare-bones demo showing how the component works, but actually providing no real user interface. As we'll see in the next section, the only real way to create a complete Ribbon-based user interface is to use the Action Manager architecture along with it. It is possible to use the Ribbon component without Actions, but it is very clumsy and extremely limited so after a simple example I'll move in that direction. We can, in fact, start some initial experiments with...

The New Category PanelGroup Control

A family of components for which we have probably seen the largest number of VCL controls available over the years has been the so-called Outlook Sidebar family, mimicking the well established interface that was originally introduced by the Microsoft email program. In modern applications, styles have changed a lot from the original collection of large icons used for the various sections of the program, but the usage of a sidebar with options and commands continues. For the first time, Delphi...

Smart Pointers in Delphi

When approaching generics, you might get the wrong first impression that this language construct is mostly used for collections. While this is the simplest case for using generic classes, and very often the first example in books and docs, generics are useful well beyond the realm of collection or container classes. In the last example of this chapter I'm going to show you a non-collection generic type, that is the definition of a smart pointer. If you come from a Delphi background, you might...

Predefined Generic Interfaces

Now that we have explored how to define generic interfaces and combine them with the use of generic and specific classes, we can get back to having a second look to the Generics.Default unit. This unit defines two generic comparison interfaces IComparer lt T gt has a Compare method IEqualityComparer lt T gt has Equals and GetHashCode methods These classes are implemented by some generic and specific classes, listed below with no implementation details type TComparer lt T gt class...

Screen Tips with No Ribbon

Delphi Edit Show Listbox

As I mentioned, you can use screen tips in applications that have no Ribbon. To show this technique can be added to any program, I've taken a classic Delphi hello, world kind of demo, a program with a list box, an edit, and a button used to add the text of the edit to the list box. I've added to classic demo a ScreenTipsManager component with default settings and three ScreenTipsPopup controls, one for each visual control. Each ScreenTipsPopup control has a ScreenTip property referring to a...

Unicode Client DataSet

Before we start looking into the changes to the database components in Delphi 2009, I think it is worth first having a look at an example of a Unicode-based database application. To keep things simple, for now, I'll use a ClientDataSet component filled dynamically with strings coming from multiple alphabets. In this example, called UniCds, the ClientDataSet data structure is defined at runtime, in the OnCreate event handler of the main form procedure TFormUniCds.FormCreate Sender TObject begi n...

Unicode Code Point Descriptions

On the Unicode Consortium web site, you can find a lot of information, including a text file with a written description of a large number of code points most of them excluding the unified ideographs for Chinese, Japanese, and Korean . I've used this file to create an extended version of the UnicodeMap program, called UnicodeData. The user interface is based on the same structure, but the program reads and parses the UnicodeData.txt14 file, and adds any available character description to the...

From PChar to PByte

If this problem is potentially troublesome, at least for a lot of low-level code, the solution is at hand. In the code above, you can simply replace the version-specific PChar type with the version-agnostic PByte type61. A pointer to byte, in fact, remains the same and behaves the same regardless of the size of characters. All you have to do in a method like the one above is to change the pointer variable declaration to var Without changing anything else in the code, recompile the program and...

Calling Ansiprefixed Functions

In StrUtils and SysUtils there used to be many functions and procedures with Ansi in their name. What happens to them in the Unicode Delphi Do you need to remove those, keep them, or what There isn't a single answer, but in general you can keep them as they are implemented for the generic string type but it would be even better to move to using the identical routines named without the Ansi prefix. In some cases, the upgrade is somewhat automatic. Most of the Ansi string functions of the RTL...