Invoking Methods

Not only does the new extended RTTI lets you access values and fields, but it also provides a simplified way for calling methods. In this case you have to define a TValue element for each parameter of the method. There is a global Invoke function which you can call for executing a method function Invoke CodeAddress Pointer const Args TArray lt TVa1ue gt CallingConvention TCallConv AResultType PTypelnfo TValue As a better alternative, there is a simplified Invoke overloaded method in the

end 21

Now while these actions can be activated using the shortcut commands, the program has no menu to execute them, but the form adds gesture support, connecting three gestures to the actions, as you can see in the image of the Object Inspector here on the right. To have a clearer view of the actions connected to the active gestures for a control, what you can do is copy the properties of the GestureManager component, which will list the gestures binding for each control connected to it in this case...

Building a Value Replacer for UCSChar

Before we delve into the development of a debugger visualizer, let me point you to a specific situation in which the debugger provides limited information about the values of a type. Consider the following code snippet, which is part of the DebugVisual example which is also used to demonstrate the other debugger visualizers. procedure TForm39.btnUcs4CharClick Sender TObject var ShowMessage Character.ConvertFromUtf32 ch end If you put a breakpoint in the code above and look to the value of ch,...

Other New VCL Features

Not all new VCL features are advances at the operating system and SDK level related with Windows 7. The library has seen countless small improvements. I'm going to focus on them in the remaining portion of this chapter. Let me start with some noteworthy but simpler changes this is not an exhaustive list, as I picked what I felt most relevant , while I'll later focus on improved property editors and changes in multi-language support. Here is a list of these notable changes All grids DrawGrid,...

HTTP Client and Server

The HyperText Transfer Protocol is the standard at the heart of the World Wide Web, and needs no introduction. Granted, HTTP can be used by Web Browsers, but also by any other application. In Delphi applications the simplest way to write a client application that uses HTTP is to rely on the Indy HTTP client component, or IdHttp. If you call the Get method of this component, providing a URL as parameter, you can retrieve the content of any Web page and many REST servers105. At times, you might...

Processing the RSS Data with XPath

To extract the relevant information from this XML document the RssClient program uses XPath expressions. For example it reads the title of the first blog post item of the list uses the expression rss channel item 1 tit1e. 106 A video of the development of this Delphi client application step-by-step and its final result is available on YouTube at and in my blog at This is done in a cycle along with the extraction of some other information, formatted and displayed in a list box. Using XPath...

var 4

item IShellltem pch PChar pnt Pointer begin FOLDERID_DocumentsLibrary, 0, 0, IShellItem, pnt item IShellItem pnt pch Memo1.Lines.Add 'SHGetKnownFolderItem.GetDisplayName ' pch The output in this case would be I SHGetKnownFolderItem.GetDisplayName Documents To access the actual library and manipulate it, we need to perform a further step and ask the system for a COM object implementing the IShellLibrary interface that we'll later initialize with the proper IShellItem element

var 7

strlnput Request.QueryFields.Values 'in' if strlnput '' then strlnput 'Nothing to echo' strlnput strlnput ' ' Copy strlnput, Length strlnput - 4, 5 Response.Content ' lt result gt ' strlnput ' lt result gt ' Response.ContentType 'text xml' end How can you call this operation From a web browser, after we run the program and start the Web App Debugger, we can use the following URL The result will look like lt result gt hello world world lt result gt Nothing extraordinary but relatively simple. We...

Visualizer Internals

IOTADebuggerVisualizerValueReplacer The first has a method receiving a string with the value to be evaluated and returning a different one, after some custom processing the second has a method to let you add an entry to the type inspection menu item and a second method executed when the menu item is invoked. You can have only one value replacer for each data type, while you can have multiple external viewers. Building an external viewer is more complex, as you'll have to integrate the user...

Web Service Technologies SOAP vs REST

The idea of a web service is rather abstract. When it comes to technologies, there are currently two main solutions that are attracting developers. One is the use of the SOAP standard Simple Object Access Protocol, see the reference site at http www.w3 .org TR soap , another is the use of a REST Representational State Transfer approach, along with its variation XML-RPC XMLRemote Procedure Call . What is relevant to notice is that both solutions generally use HTTP as the transmission protocol...

Testing the Connection in Data Explorer

It is interesting to notice that in the Data Explorer window of the Delphi 2010 IDE you can configure and test the client connection quite easily. It is actually easier to test the connection in this pane than setting up an SQLConnection component manually. To try this out, simply run the server possibly as a stand alone application using the Run Without Debugging command , move to the Data Explorer, pick the DataSnap driver, and add a new connection. Now open the connection configuration and...

The Firebird Driver

Firebird is an open source database, developed by the Firebird Foundation, that originates from the version of Interbase that Borland released even if only temporarily as open source. Given the relationship with Interbase the database distributed with Delphi since the early days of the product and the fact that deployment of Firebird is free, it should come to no surprise that this database server is quite popular among Delphi developers. In the early days, the two database were highly...

LowLevel TValue

The TValue structure includes a few helpers that make it easy to assign or extract values of various data types to or from it. In some situations, however, it is nice to be able to copy the raw bytes of the TValue data into a specific data structure. This can be done using the Make and GetRawData methods, as in the following snippet that saves an integer value inside a newly created TValue record var aValue TValue intValue Integer begin TVa1ue.Make intVa1ue, TypeInfo Integer , aValue Of course,...

A Translation Component

The class of the component stores information about the request and encapsulates an internal HTTP client component, as you can see in its declaration type TBabelGoogleRest class TComponent protected Httpl TIdHttp FFromLang string FToLang string FActivelnForm Boolean procedure SetFromLang const Value string procedure SetToLang const Value string public function DoTranslate strln string string virtual constructor Create AOwner TComponent override class function Translate strIn, langIn, langOut...

REST Clients Written in Delphi

There are countless examples of REST servers that you can find on the Web. Even if the number of web services that uses REST on the Internet is high, most actual web services require some developer token as covered in some of the coming demos , while only a handful offer totally free and open access. For a much longer list of Delphi REST clients that I have written, you can refer to the specific section of one of my web sites I You can also find more coverage of REST clients written in Delphi...

MultiTouch Support

As I detailed in the section From Single Touch to Multi-Touch, Windows 7 and Delphi 2010 have specific support for multi-touch hardware, basically in the form of a new Windows message wm_touch and support for handling it at the VCL level. Considering the current limited crop of multi-touch enabled hardware, though, this support should probably be restricted to specific applications for quite some time. This is why the coverage of native touch, or wm_touch, in this chapter is restricted to this...

Google Geocoding Service

The first service of this category I'm going to use is Google's Geocoding service, which lets you submit an address and retrieve its latitude and longitude q address amp output format amp key key You can also type a similar URL in your browser for testing purposes, as you can see here showing New York coordinates in a browser in XML format lt krul xraln3 ,'Iittp earth. google . cora kml 2 . 0XRe3ponse gt lt name gt New York, EJS lt name gt lt Stacus gt lt addxess gt New York, NY, USA lt addxess...

Chapter Database Access And DataSnap

The development of database-oriented applications, with stand-alone, client server, or multi-tier architectures, has always been one Delphi's strong features. It is not surprising that this version brings incremental new features to the database area of the product. While Delphi 2007 introduced a new generation of dbExpress called dbEx-press IV and Delphi 2009 brought us a new generation of DataSnap often referred to as DataSnap 2009 , Delphi 2010 provides incremental features in both areas....

class constructor ExceptionCreate begin

The InitExceptions procedure was previously called in the initialization section of the SysUtils unit. In general, I think that using class constructors and destructors is better than using unit initialization and termination. In most cases, this is only syntactic sugar, so I won't go back and change existing code. However, if you face the risk of initializing data structures you'll never used because no class of that type is ever created moving to class constructors will provide a definitive...

Reading a Property with TValue

The importance of TValue lies in the fact that this is the structure used when accessing properties and field values using the extended RTTI and the Rtti unit in Delphi 2010. As an actual example of the use of TValue, we can use this record type to access both a published property and a private field of a TButton object, as in the following code part of the RttiAccess demo procedure TForm39.btnReadValuesClick Sender TObject var context TRttiContext aType TRttiType aProperty TRttiProperty aValue...

Live Templates and Code Completion

There are some very minor improvements to refactorings and live templates, including three new live templates, in Delphi 2010. All of them are quite trivial. There is a raise template and a todo template, producing the following two raise ExceptionType.Create 'Error0 TODO -oOwner -cGeneral Actionltem The third new live template is a variation of the class declaration, called classf, which produces the same code of the class template without comments in each section. Speaking of refactorings,...

Larger Executable Files

The obvious effect of adding Extended RTTI information to an executable file is that the file will grow larger which has the main drawback of a larger file to distribute, as the extra loading time and memory footprint would be almost unnoticeable . For very small programs, the effect is somewhat minimal, but in large applications the increase will be significant. I'll look at very small programs first, testing two applications I've used over the years and with multiple versions of Delphi, to...

RTTIfor Packages

Beside the methods you can use to access a type or the list of types, the record TRttiContext has another very interesting method, GetPackages, which returns a list of the run-time packages used by the current application. If you execute this method in an application compiled with no run time packages, all you get is the executable file itself. But if you execute it in an application com piled with run time packages, you'll get a list of those packages. From that point, you can delve into the...

Returning a List of Customers

The server action returning a list is called with the customers URL. In its server code, the application scans the data set and returns an XML structure with the company name and the customer ID for each customer record. With the URL You'll see an XML result like lt customers gt lt customer gt lt id gt 1221 lt id gt lt Company gt Kauai Dive Shoppe lt Company gt lt customer gt lt customer gt lt id gt 1231 lt id gt lt Company gt Unisco lt Company gt lt customer gt This XML code is generated using...

Chapter REST Web Services

Over the last few years, there has been a large expansion of and a significant shift around web services. Promised as a new way for applications to interact and exchange data, web services have long been synonymous with the SOAP technology behind them, but have been quite slow to catch up with their promises. The recent expansion in web services, both as a way to interact with major web sites and with remote applications, is mostly due to a competing technology called Representational State...

Browsing Existing Units

Beside compiler-related features and trend-setting features, there are many other extensions to the RTL, some of which are worth mentioning The TStringBuilder class has a new Clear method, that removes any data in the current buffer. In the Types unit there a new global function called PtInCircle, that clones the existing PtInRect function. As already mentioned in Chapter 2, the TTh read class has a new static class method to help with naming threads, NameThreadForDebugging. Also, the Resume...

Custom Attributes

The first part of this chapter gave you a good grasp of the extended RTTI generated by the Delphi 2010 compiler and of the RTTI access capabilities introduced by the new Rtti unit. In the second part of the chapter we can finally focus on one of the key reasons this entire architecture was introduced the possibility to define custom attributes and extend the compiler-generated RTTI in specific ways. We'll look at this technology from a rather abstract perspective, and later focus on the reasons...

Chapter Extended RTTI And Attributes

The area of the compiler that has seen the most significant update in Delphi 2010 is the generation and management of Run Time Type Information, RTTI. Traditionally, compilers of strongly, statically typed languages, such as Pascal, provided little or no information about the available types at runtime. All the information about data types was visible only during the compilation phase. The first version of Delphi broke with this tradition, by providing run time information for properties and...

for I to do begin

D2D1MakeRotateMatrix I 6, D2D1PointF 50, 50 , matrix - I 0.1 d2dCanvas.TextOut 200, 100, strText end There is a little more code to get the original transformation matrix and reassign it at the end, but the three code snippets just displayed sum up the code of the OnPaint event handler of this example. For another example of Direct2D in Delphi, you can refer to the following post by Pawel Glowacki, who translated one of the Microsoft SDK demos the Advanced Path Geometries Demo in Delphi

Accessing the REST Server with a Browser

We can test this server to see if it works. After compiling and running the program, remember to run the Web App Debugger available in Delphi's Tools menu , and start it using the corresponding button. The Web App Debugger runs on a specific port, by default 8081, so the URL will start with http localhost 8081 Next in the URL comes the application name and the Web App Debugger class name which in this case are identical , separated by a period If you open the combined URL in a Web browser you...

Updating My LargeXml Application

To better figure out the effect of the XML-related changes, I've decided to upgrade an XML-processing application I wrote for the Mastering Delphi book series, called LargeXml, to Delphi 2010. This program uses both MSXML and ADOM, and their SAX interfaces quite extensively. In short, the application connects to a database, generates ClientDataSets with a lot of data, and saves them to XML files with different techniques direct Xml Data content of the component, XML mapper, manual creation of...

A DataSnap HTTP Server with the Wizard

For that first demo I've taken an existing DataSnap application and moved it from a TCP IP connection to an HTTP connection. It is even easier to create a new application with the DataSnap Wizard and ask for either or both connectivity options. If you select the DataSnap Server in the DataSnap page of the New Item dialog box or Object Repository you'll get the following options You can pick three different application architectures, one or both communication protocols optionally asking for HTTP...

var 5

aLibrary IShellLibrary Obj IInterface item IShellItem pch PChar pnt Pointer begin FOLDERID_DocumentsLibrary, 0, 0, IShellItem, pnt item IShellItem pnt aLibrary CreateComObject CLSID_She1lLibrary as IShellLibrary aLibrary.LoadLibraryFromItem item, PropSys.GPS_READWRITE Now that we have the library interface tied to the IShellItem for the given folder, we can use it, for example to extract the list of elements it contains var anArray IObjectArray nItems Cardinal I Integer begin IObjectArray,...

Browsing Attributes

Now this code would seems totally useless if there wasn't a way to discover which attributes are defined, and possibly inject a different behavior to an object because of these attributes. Let me start focusing on the first part. The classes of the Rtti unit let you figure out which symbols have associated attributes. This is code, extracted from the RttiAttrib example shows the list of the attributes for the current class context TRttiContext attributes TArray lt TCustomAttribute gt attrib...

while True do begin

The ServerMethodsUnit1 unit has the target class automatically connected to the DSServerClass component of the main unit, as mentioned earlier with the sample method type METHODINFO ON TServerMethodsl class TPersistent public function EchoString Value string string end This is all the code generated for the server. We can try to compile and run it as it is, but how do we test it without creating a client application Turns out we can use the Data Explorer pane of the Delphi IDE.

A Basic Gesture Example

Rather than describing the complete VCL gesturing architecture in theory, let us start by building a very simple first example I've called Gesturesoi. The program has a form with a panel and a memo control, plus the GestureManager component. This last component doesn't have specific setting, as its editor let's you add custom gestures to it, something we will focus on later. The management of gestures takes place in the Touch property of the target control, for example the form. This property...

Themes Support and Other DBGrid Extensions

Even with the stronger themes support already in the VCL for a couple of versions introduced in Delphi 7, but much expanded in Delphi 2007 , not all of the visual controls got full themes support. A notable absence was in the VCL grids, both the plain ones StringGrid and DrawGrid and the data-aware version DBGrid . This has now been addressed. In the image on the side you can see the same application DbxMulti2010, the new version of a simple dbExpress demo I used in previous books with and...

Microsoft XML DOM Version

The msxml unit interfacing Microsoft XML DOM and available in the source Win32 rtl win folder now refers to version 6 of the XML engine msxml6.dll . Differently from the past103, the unit now includes almost all interfaces, including the VB version of the SAX interface. The unit with all interfaces is called msxml and its source code can be found under the source Win32 rtl win folder and not the source Win32 xml folder, which hosts the DOM mappers, including the msxmldom unit for MS XML DOM...

Extracting Subfolders

Of course, you can change that initial folder name to something more appropriate. The program can fill a list box with the list of the folders under that directory, by using the GetDirectories method of TDirectory with the TSearchOption .soAl lDirectories35 parameter and enumerating the array of strings that it returns procedure TFormIoFiles.btnSubfoldersClick Sender TObject var pathList TStringDynArray strPath string begin if TDirectory.Exists edBaseFolder.Text then begin pathList...

New Field Types and Other Core Database Extensions

Although the enhancements to the overall Delphi database architecture can be considered as minor, the new features that have been introduced will have a very significant impact for some developers. For example, for managing floating point numbers with a limited representation and time stamp offsets, there are specific TField-derived classes that you can now use TSingleField class TNumericField TSQLTimeStampOffsetField class TSQLTimeStampField Support for time stamp offset processing is now also...

The With Statement Now Preserves Read Only Properties

Beside the various extensions covered so far, the compiler in Delphi 2010 has a relevant fix which can affect existing programs that exploited this unwanted opportunity as if it were a feature. In short, if you have a with statement referring to a read-only record property, you cannot modify the record members any more. Again, this is a reasonable fix, but it might affect existing code and did affect the source of some third party controls . Here is an example, which is the 28 This is exactly...

DirectWrite

We have seen that we can use the basic text drawing functions of Direct2D most like the GDI ones, but support for the precise display of text has much improved compared to the past. The new interfaces for managing font families, text layouts, text formats, and the like are collectively known as DirectWrite. In Delphi you can access to the various DirectWrite objects using the factory object returned by the DWriteFactory global function of the Direct2D unit which creates and initializes a...

Using JSON Converters and Reverters

The JSON marshaling support works great for basic types, but when data structures become complex, you might want to customize the actual information that is saved. This is possible thanks to the ability of installing custom converters and reverters which you can register for given classes and fields. The converters and reverters are implemented using anonymous methods98. Suppose, as an example taken from the same JsonMarshal demo, that you have a class like the following type theName String...

TSQLTimeStampOffsetField TBinaryField TBytesField

TVarBytesField TBlobField TMemoField TWideMemoField widestring memo TGraphicField TObjectField TADTField Abstract Data Type TArrayField TDataSetField TReferenceField TVariantField TInterfaceField There are some other changes focused on very specific needs, like local dependent string formatting for date and time functions, the remapping of 64-bit integers to the Int64 rather than BCD, and other similar changes probably not worth covering in detail.

Building a Database Oriented REST Server

If the original idea behind DataSnap focused on moving data tables from a middle-tier server to a client application, it might be quite odd at first to realize that you cannot return a dataset from a REST server written in Delphi 2010. Well, you cannot return it directly or as easily as you return its XML representation, but you can create a JSON result with all of the data of a Delphi dataset. That's the focus my last example. The program is quite bare bones, as all it does is return the data...

Rtti Objects Lifetime Management and the TRttiContext record

If you look at the source code of the btnTypesListClick method listed earlier, there is something that looks quite wrong. The GetTypes call returns an array of types, but the code doesn't free these internal objects. The reason is that the TRttiContext record structure becomes the effective of owner for all of the Rtti objects that are being created. When the record is disposed that is, when it goes out of scope , an internal interface is cleared invoking its own destructor that clears all of...

Editing Data with jQuery

Now that we have the CRUD operations available on the REST server, we can complete our JavaScript client application with the code of the three editing buttons the image of the browser-based user interface was shown earlier . While jQuery has specific support for the get operation with different versions, including the JSON-specific one we have used earlier and some support for post operations, for the other HTTP methods you have to use the lower level and slightly more complex .ajax call. This...

Notable Differences Between Vista and Windows

Having covered in summary new features of recent version of Delphi that let you better support Windows Vista and Windows 7, I have to underline the fact that Windows 7 adds a few extra features that make existing old Delphi applications more compatible with the new operating system. There are a couple of these differences worth mentioning. The first relates with the preview of the application main form available in Windows Flip the task bar preview , Windows Flip 3D, or even the plain list of...

Returning the XML Data of a ClientDataSet

The second action, actionCustData, is the simplest to implement, on both the server and client side. All it does is return the entire data content of a ClientDataSet component, using its XML representation. The server simply returns that XML procedure TWebModule3.actionCustDataAction Sender TObject Request TWebRequest Response TWebResponse var Handled Boolean begin Response.Content cdsCustomers.XMLData Response.ContentType 'text xml' end Using the corresponding URL you can see the entire XML...

Handling wmtouch

The wm_touch message is a raw, low-level Windows message, providing a significant amount of information about the user input unlike a mouse message . Considering the limited data a Windows message can carry, this is actually not a precise description. 73 Chris is a Delphi R amp D member who worked on touch support in Delphi 2010. His blog is at http chrisbensen.blogspot.com . I got permission from him to quote the source code of this demo application in my book. What you receive in the...