41,99 €
Over 60 hands-on recipes to help you master the power of Delphi for cross-platform and mobile development on multiple platforms
If you are an intermediate developer with a basic knowledge of Delphi and you want to develop cross-platform applications, then this book is for you. Familiarity with the fundamentals of RAD (Rapid Application Development) Studio is expected.
Delphi is a cross-platform Integrated Development Environment (IDE) that supports rapid application development for Microsoft Windows, Apple Mac OS X, Google Android, and Apple iOS. It helps you to concentrate on the real business and save yourself the pain of wandering amid GUI widget details, or having to tackle inter-platform incompatibilities. It also has a wide range of drag-and-drop controls, helping you code your business logic into your business model, and it compiles natively for desktop and mobile platforms.
This book will teach you how to design and develop applications, deploy them on the cloud platform, and distribute them within an organization via Google Play and other similar platforms.
You will begin with the basics of Delphi and get acquainted with JSON format strings, XSLT transformations, unicode encodings and various types of streams. We then move on to more advanced topics such as developing higher-order functions and using enumerators and RTTI. You will get an understanding of how Delphi RTL functions and how to use FireMonkey in a VCL application. We will then cover topics such as multithreading, using the parallel programming library and putting Delphi on a server. We will also take a look at the new feature of WebBroker Apache modules and then ride the mobile revolution with FireMonkey.
By the end of the book, you will be able to develop and deploy cross-platform applications using Delphi.
Delphi Cookbook is an easy-to-follow guide, rich with hands-on examples of real-world programming tasks in Delphi.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 495
Veröffentlichungsjahr: 2016
Copyright © 2016 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: September 2014
Second edition: June 2016
Production reference: 1280616
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78528-742-8
www.packtpub.com
Author
Daniele Teti
Reviewer
Roman Yankovsky
Commissioning Editor
Priya Singh
Acquisition Editor
Rahul Nair
Content Development Editor
Deepti Thore
Technical Editor
Mohita Vyas
Copy Editor
Merilyn Periera
Project Coordinator
Shweta H. Birwatkar
Proofreader
Safis Editing
Indexer
Monica Ajmera Mehta
Graphics
Disha Haria
Production Coordinator
Arvindkumar Gupta
Cover Work
Arvindkumar Gupta
Daniele Teti is a software architect, trainer, and consultant with over 20 years of professional experience. He writes code in a number of languages but his preferred language for compiled native software, is Object Pascal.
Daniele is an Embarcadero MVP and is a well known Delphi and programming expert in the developers' community. He's the main developer and drives the development of some Delphi open source projects (DelphiMVCFramework, LoggerPro, DORM—"The Delphi ORM", Delphi Redis Client, Delphi STOMP Client, and so on). After writing some articles for the most important programming magazines in Italy and a number of on-line publications, Daniele started to write books. His Delphi Cookbook, published in late 2014, has been a bestseller. Daniele wrote his first program when he was 11 year old, and since then happily continues to write software almost every day. Apart from Delphi, he's a huge fan of design patterns, open source, distributed architectures, RESTful architectures, and Android OS. Daniele has been the project manager for a lot of big projects in Italy and in Europe, for private companies and public institutions. When is not busy writing software or writing about programming (for a job or for a hobby), he like to play guitar, write songs, and do voluntary activities. Currently he is CEO of BIT Time Professionals, an Italian company specializing in high level consultancy, training, and development. The company specializes in high performance software, web and mobile solutions, and distributed architecture. Bit Time Professionals is also an Italian leader about indoor proximity solutions using beacon technology, where it provides solutions for museums, supermarkets, art galleries, fairs, and events in general.
Daniele acts as a consultant and teacher for many Italian and European companies, so he travels very often around the world.
Daniele is the technical director for the ITDevCon conference, the biggest European Delphi conference (www.itdevcon.it). He's also an international speaker at technical conferences.
Daniele lives in Rome, Italy, with his beloved wife Debora and their little boy Mattia.
Thank you to my wife Debora and my son Mattia.
Roman Yankovsky is a long time Delphi developer who has been working with Delphi since Delphi 2. He has developed and maintained various applications in different industries. Currently he is working with ShareBike, developing a public bike sharing system. Roman is an Embarcadero MVP and a frequent speaker at developer conferences. Most recently, his focus is on the development of productivity tools for developers. He is the author of the FixInsight static analysis tool for Delphi.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
If you've been a software developer for a long time, you certainly know how useful a conversation can be with a colleague who has already done something similar to what you are doing and can explain it, as they faced the same problem. It is not possible to put all the possible situations that a developer can face in a book, but many problems are similar at least in principle. This is the reason this book is organized as a cookbook: just like a combination of foods can be adapted and modified to be appropriate for different types of dinner, a "programming recipe" can provide the idea to solve many different problems.
This book is an advanced level guide that will help Delphi developers get a higher expertise in their everyday job. The everyday job, and the quality of your deliverables, is what contributes to the quality of your professional life. If it does not make sense, reinvent the wheel repeatedly, especially when working with a well-established tool, such as Delphi. The focus of the book is to provide readers with comprehensive and detailed examples on how effectively the Delphi software can be designed and written. All the recipes in the book are the result of years of development, training, and consultancy activities in many different fields of the IT industries, from the small systems with thousands of installations to the large systems commissioned by big companies or by the government. It is not a magic book that will solve all your development problems (if you find it, tell me, please!), but can be helpful to get a different point of view on a specific problem, or a hint on how to solve problems.
Armed with the knowledge of advanced concepts, such as high order functions and anonymous methods, generics and enumerable, extended RTTI and duck typing, LiveBindings, multi-threading, FireMonkey, mobile development, server-side development, and so on, you will be pleasantly surprised as to how quickly and easily you can use Delphi to write high quality, clean, readable, fast, maintainable, and extensible code.
I read too many boring programming books, so I tried to maintain a relaxed and light exposition. A small applicability scenario that describes a situation where a particular technology, approach, or design pattern can be used successfully introduces all the recipes. The recipes are not too complex, because otherwise the book may become thousands of pages long, but also not trivial because the IT books' landscape is already full of simple examples with few direct applicability. I tried to do a good tradeoff and I hope to be able to do it.
Every time I start to read a new book, I ask myself, "Will the author have something interesting to say?", "How much will this book change my point of view about the topics mentioned?", "Is it worth the time spent to read it?" Now, in spite of being from the other side of the river, I worked hard to put as much good quality contents in my books as possible, I hope that will match your expectations.
One last note. Writing hundreds of pages about advanced programming is not an easy task. However, I am very pleased to have done it and I hope you will enjoy reading it at least how I enjoyed writing it.
Chapter 1, Delphi Basics, talks about a set of general approaches that should not be ignored by any Delphi programmer. Some topics are simple and immediate and some are not but all of them should be well understood. By the end of this chapter, the reader is able to use some of the fundamental Delphi techniques related to the RTL, to the VCL, and to the OS integration.
Chapter 2, Becoming a Delphi Language Ninja, focuses on the Object Pascal language. The programming language is the way you talk to the machine, so you must be fluent and know all the possibilities offered. This chapter talks about higher-order functions, practical utilization of the extended RTTI, regular expressions, and other things useful to augment the power of your code and to lower the amount of time spent on debugging.
Chapter 3, Knowing Your Friends – the Delphi RTL, focuses on the Delphi' RTL. There isn't a detailed description of all the Delphi's RTLs (you would need 10 books like this one, which will be particularly boring, I guess) but you can find some recipes that explain some of the most important RTL features and some less know but really useful classes. You'll learn how to use regular expressions, the most popular encoding format used by HTTP base applications, and how to use the built-in data de/compression-related classes.
Chapter 4, Going Cross-Platform with FireMonkey, is dedicated to the FireMonkey framework in general. What you will learn from this chapter can be used in many of the platforms that FireMonkey supports. Moreover, you will learn about non-trivial LiveBindings utilizations.
Chapter 5, The Thousand Faces of Multithreading, talks about thread synchronization and the mechanisms used to obtain this synchronization, such as TMonitor, thread-safe queues, and TEvent. It is also one of the most complex chapters. By the end of this chapter, the reader will be able to create and communicate with background threads, leaving your main thread free to update your GUI (or to communicate with the OS).
Chapter 6, Putting Delphi on the Server, focuses on how well Delphi can behave when running on a server. Some people think that Delphi is a client-only tool, but it is not true. In this chapter, we'll show how to create powerful servers that offer services over a network. Then, in some recipe, we'll also implement a JavaScript client that brings the database data into the user browser. Techniques explained in this chapter open a range of possibilities, especially in the mobile and web area.
Chapter 7, Riding the Mobile Revolution with FireMonkey, is dedicated to the mobile development with Delphi and FireMonkey. If you are interested in mobile development, I think that will be your favorite chapter! Mobile is everywhere, and this chapter will explain how to write software for your Android or iOS device, what are the best practices to use, how to save your data on the mobile, how to retrieve and update remote data, and how to integrate with the mobile operating system.
Chapter 8, Using Specific Platform Features, shows you how to integrate your app with the underlying mobile operating systems beyond what FireMonkey offers. You will learn how to import Java and Objective C libraries in your app and how to use the SDK classes from your Object Pascal code.
This book talks about Delphi, so you need it. Not all the recipes are available in all the Delphi editions. Typically, the mobile projects can be compiled only if you have Delphi Enterprise or higher (or Delphi Professional plus the mobile add-on, or RAD Studio professional or higher). All the projects are compiled and tested with the latest Delphi version at the time of writing, but many recipes can be compiled also on older versions.
If you want to run the mobile app on a phone or a tablet, you could use the Android emulator or the iOS simulator, but we strongly suggest an actual device to see how the app really behaves. To deploy an iOS app on your device, you also need an Apple computer with MacOSX.
This book aims to help the professional Delphi developers in their day-to-day job. This book will teach you about the newest Delphi technologies and its hidden gems. It is not a book for a newbie, but the practical approach will help you reach a new level with your Delphi skills. The experienced developer can benefit from this book because nontrivial problems are solved using best practices. Where more than one way is available or the topic is too broad to be explained in the available pages, references are provided to allow you to go deeper in that field. It is a book to have on your desk for the next few years.
In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "Style manipulation at runtime is done using the class methods of the TStyleManager class."
A block of code is set as follows:
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
Any command-line input or output is written as follows:
New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "Add all the columns to TDBGrid by right-clicking and selecting Columns Editor".
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Delphi-Cookbook-Second-Edition. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.
In this chapter, we will cover the following topics:
This chapter will explain some of the day-to-day needs of a Delphi programmer. These are ready-to-use recipes that will be useful every day and have been selected ahead of a lot of others because, although they may be obvious for some experienced users, they are still very useful. Even if there isn't specifically database-related code, many of the recipes can also be used (or sometimes, especially used) when you are dealing with data.
Visual Component Library (VCL) styles are a major new entry in the latest versions of Delphi. They have been introduced in Delphi XE2 and are still one of the lesser known features for the good old Delphi developers. However, as usual, some businessmen say "looks matter" so the look and feel of your application could be one of the reasons to choose one product over another from a competitor. Consider that with a few mouse clicks, you can apply many different styles to your application to change the look and feel of your applications. So, why not to give it a try?
VCL styles can be used to revamp an old application or to create a new one with a non-standard GUI. VCL styles are a completely different beast to FireMonkey styles. They are both styles, but with completely different approaches and behavior.
To get started with VCL styles, we'll use a new application. So, let's create a new VCL application and drag and drop some components onto the main form (for example, two TButton, one TListBox, one TComboBox, and a couple of TCheckBox).
You can now see the resultant form that is running on my Windows 8.1 machine:
Figure 1.1: A form without style
Now, we've got to apply a set of nice styles by following these steps:
Figure 1.2: The same form as Figure 1.1 but with the Iceberg Classico style applied
Selecting one or more styles from Project | Options | Application | Appearance will cause the Delphi linker to link the style resource into your executable. It is possible to link many styles into your executable, but you can use only one style at a time. So, how does Delphi know which style you want to use when there are more than one? If you check the Project file (the file with the .dpr extension) by going to Project | View Source Menu, you can see where and how this little magic happens.
The following lines are the interesting section:
When we've selected the Iceberg Classico style as the default style, the Delphi IDE added a line just before the creation of the main form, setting the default style for all the applications using TStyleManager.TrySetStyle static methods.
TStyleManager is very important class when dealing with VCL styles. We'll see more about it in the upcoming recipe, where you'll learn how to change styles at runtime.
Delphi and C++ Builder 10.1 Berlin come with 36 VCL styles available in the folder (with a standard installation):
C:\Program Files (x86)\Embarcadero\Studio\18.0\Redist\styles\vcl\
Moreover, it is possible to create your own styles or modify the existing ones using the Bitmap Style Designer. You can access it by going to Tools | Bitmap Style Designer Menu.
For more details on how to create or customize a VCL style, visit http://docwiki.embarcadero.com/RADStudio/en/Creating_a_Style_using_the_Bitmap_Style_Designer.
The Bitmap Style Designer also provides test applications to test VCL styles.
VCL styles are a powerful way to change the appearance of your application. One of the main features of VCL styles is the ability to change the style while the application is running.
Because a VCL Style is simply a particular kind of binary file, we can allow our users to load their preferred styles at runtime. We could even provide new styles by publishing them on a website or sending them by e-mail to our customers.
In this recipe, we'll change the style while the application is running using a style already linked at design time, or let the user choose between a set of styles deployed inside a folder.
Style manipulation at runtime is done using the class methods of the TStyleManager class. Follow these steps to change the style of your VCL application at runtime:
Figure 2.1: The Style Chooser form with a Torquoise Gray style loaded
The TStyleManager class has all the methods we need to:
After loading new styles from the disk, the new styles are completely similar to the styles linked in the executable during the compile and link phases and can be used in the same way.
Other things to consider are third-party controls. If your application uses third-party controls, take care with their style support (some third-party controls are not be style aware). If your external components do not support styles, you will end up with some styled controls (the original included in Delphi) and some not styled (your external third-party controls)!
Go to Tools | Bitmap Style Designer. Using a custom VCL style we can also:
Figure 2.2: The Bitmap Style Designer while it is working on a custom style
Owner draw controls are powerful. They allow you to completely tune your GUI for the needs of your users and potentially enable your application to display data in a more familiar way. In the end, owner draw controls improve the user experience with your application. However, owner draw controls do not always fit well with the VCL custom styles. Why? Because if you try to draw something by yourself, you could be tempted to use a "fixed" color, such clRed or clYellow, or you could be tempted to use the operating system color, such as clBtnFace or clWindow. Doing so, your owner draw controls will be not style aware and will be drawn in the same way regardless of the current VCL style. In this recipe, you'll learn how to make custom graphics remaining being in topic with the selected VCL style.
Let's say you are in charge of developing a controller panel for a hotel's light system. You have a list of lamps to power on, and you, using some hardware, have to power on some lamps by clicking on a button. Customers tell you that buttons should show some additional information about the lamp, for example:
The question is how to implement this kind of UI. One of the possible ways is to use TDrawGrid and draw all the needed details in each cell, using the cell also as a button. Using TDrawGrid, you have a grid of buttons for free. You have also the greatest flexibility about the information displayed because you are using the TCanvas method to custom draw each cell. This is quite a popular solution for this kind of non-standard UI. However, when you deploy this application, the customers ask about the possibility of changing the style of the application to fit the needs of the current user. So, you think about VCL styles, and you are right. However, the graphics drawn into the cells don't follow the currently selected VCL style, and your beautiful application becomes a bad mix of colors. In other words, when users change the selected VCL style, all the controls reflect the new style, but the owner drawn grid, which is unaware to the selected style, doesn't look as nice as the rest of the UI. How to solve this problem? How to draw custom graphics by adhering to the selected VCL style? In this recipe, you'll learn how to do it using the lamp control grid example.
At design time, the form looks like the one shown in the following screenshot:
Figure 5.1 The form as it looks at design time
When the form is created, the list of available styles is loaded in the Radio group using code similar to the following one:
Then, a list of the TLampInfo object is created and initialized using the information contained in the Zones array. After that, the draw grid is initialized according to the LAMPS_FOR_EACH_ROW constant. Here's the relevant code:
The FormCreate event handler initializes the styles list and the list of the lamps (the model) of the form. Now, we'll see how the other event handlers will use them.
The TDrawGrid OnSelectCell event, as the name suggests, is used to address the current "lamp" from the FLamps and to toggle its state. That's it. If the lamp is on, then the lamp will be powered down, else the lamp will be powered on. After that, the code forces the grid to redraw using the Invalidate method:
Now, really interesting things happened in the DrawThemed method called inside the TDrawGrid OnDrawCell event. This method receives information about the coordinates of the cell to draw, and then it draws a button on the canvas using the information contained in the correspond TLampInfo instance. The code is quite long, but an interesting concept is that no specific colors are used. When it is necessary to draw something, the code asks StyleService to get the correct color according to the current style. This approach is also used for font color and for system colors. Here's a handy table that summarizes these concepts:
Method name
Description
StyleServices.GetStyleColor(Color: TStyleColor)
Returns the color defined in the style for the element specified by Color
StyleServices.StyleFontColor(Font: TStyleFont)
Returns the font color for the element specified by Font
StyleServices.GetSystemColor(Color: TColor)
Returns the system color defined in the current style
So, when we have to highlight the (pseudo) button, if there are electrical problems on the power line, we will use the following code:
When we've got to draw normal text, we will use the following code:
It is clear that the paradigm is:
Clicking on the Simulate Problems button, it is possible to see how the graphics is drawn in the case of problems on the power line. The images are drawn directly from the image list using the following code:
Using this approach, the application created in this recipe, which has a lot of custom graphics, behaves very well even on VCL styles. Here are some screenshots:
Fig. 5.2 The application while it is using the Windows style
Fig. 5.3 The application while it is using the Luna style
Fig. 5.4 The application while it is using the Charcoal Dark Slate style
As you see, the application correctly draws the owner draw parts of the UI using the right colors from the selected style.
The VCL style infrastructure is very powerful. In the case of TWinControl descendants, you can even define specific hooks for you components using TStyleHook. TStyleHook is a class that handles messages for controls acting as a wrapper for the hooked control. If you have a custom control that you want to be style enabled, inherit from TStyleHook and provide custom processing for that control. As examples, see TEditStyleHook and TComboBoxStyleHook. You need to register the style hook class with the style engine using the RegisterStyleHook method as shown in the following code:
Moreover, the StyleServices function returns an instance of TCustomStyleServices, which provides a lot of customization methods related to the VCL styles. Check out the related documentation at http://docwiki.embarcadero.com/Libraries/en/Vcl.Themes.TCustomStyleServices_Methods to see all the possibilities
Every modern browser has a tabbed interface. Also, many other kinds of "multiple views" software have this kind of interface. Why? Because it's very useful. While you are reading one page, you can rapidly check another page and still come back to the first one at the same point you left some seconds ago. You don't have to redo a search or use a lot of mouse clicks to just go back to that particular point. You simply have switched from one window to another window and back to the first. I have seen too many business applications that are composed of a bunch of dialog windows. Every form is called with the TForm.ShowModal method. So the user has to navigate into your application one form at time. This is simpler to handle for the programmer, but it's less user friendly for your customers. However, giving a "switchable" interface to your customer is not that difficult. In this recipe, we'll see a complete example of how to do it.
This recipe is a bit more complex than the previous recipes. So, I'll not explain all the code but only the fundamental parts. You can find the complete code in the book code repository (Chapter1\RECIPE06).
Let's say we want to create a tabbed interface for our software that is used to manage product orders, sales, and invoices. All the forms must be usable at the same time, without having to close the previous one. Before we begin, the following screenshot is what we want to create:
Figure 5.1: The main form containing seven embedded child forms
The project is composed of a bunch of forms. The main form has TTabControl, which allows us to switch between the active forms. All embedded forms inherit from EmbeddableForm. The most important is the method Show shown here:
