Discover millions of ebooks, audiobooks, and so much more with a free trial

Only $11.99/month after trial. Cancel anytime.

Delphi Cookbook
Delphi Cookbook
Delphi Cookbook
Ebook763 pages5 hours

Delphi Cookbook

Rating: 0 out of 5 stars

()

Read preview

About this ebook

With this book, you will gain valuable and practical knowledge of the latest functionalities of Delphi. Starting with the foundations, you will work on your VCL application, customize the TDBGrid, and configure your runtime class using RTTI. Going forward, you will build on this foundation and deploy FireMonkey to go cross-platform or even call FireMonkey from a VCL project, and you will fully understand how you can include Delphi on your server. Finally, you will use App Tethering, call Android and iOS SDK classes, and even use the Android TextToSpeech engine to add sounds to your phone! With this learning resource at your side, you will acquire all that a RAD Studio developer needs to know about Delphi in one complete, informative guide.

LanguageEnglish
Release dateSep 25, 2014
ISBN9781783559596
Delphi Cookbook

Related to Delphi Cookbook

Related ebooks

Programming For You

View More

Related articles

Reviews for Delphi Cookbook

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Delphi Cookbook - Daniele Teti

    Table of Contents

    Delphi Cookbook

    Credits

    About the Author

    About the Reviewers

    www.PacktPub.com

    Support files, eBooks, discount offers, and more

    Why subscribe?

    Free access for Packt account holders

    Preface

    What this book covers

    What you need for this book

    Who this book is for

    Conventions

    Reader feedback

    Customer support

    Downloading the example code

    Errata

    Piracy

    Questions

    1. Delphi Basics

    Introduction

    Changing your application's look and feel with VCL styles and no code

    Getting ready

    How to do it...

    How it works…

    There's more...

    Changing the style of your VCL application at runtime

    Getting ready

    How to do it…

    How it works…

    There's more...

    Customizing TDBGrid

    Getting ready

    How to do it…

    How it works…

    There's more...

    Using the owner's draw combos and listboxes

    Getting ready

    How to do it…

    How it works…

    There's more...

    Creating a stack of embedded forms

    Getting ready

    How to do it...

    How it works...

    There's more...

    Manipulating JSON

    Getting ready

    How to do it…

    There's more...

    Manipulating and transforming XML documents

    Getting ready

    How to do it…

    How it works…

    There's more...

    I/O in the twenty-first century – knowing streams

    Getting ready

    How to do it…

    There's more...

    Putting your VCL application in the tray

    Getting ready

    How to do it…

    How it works…

    There's more...

    Creating a Windows service

    Getting ready

    How to do it…

    There's more...

    Using the TService.LogMessage method

    Associating a file extension with your application on Windows

    Getting ready

    How to do it…

    There's more...

    2. Become a Delphi Language Ninja

    Introduction

    Fun with anonymous methods – using higher-order functions

    Getting ready

    How to do it...

    There's more...

    Writing enumerable types

    Getting ready

    How to do it...

    There's more…

    See also

    RTTI to the rescue – configuring your class at runtime

    Getting ready

    How to do it...

    There's more…

    See also

    Duck typing using RTTI

    Getting started

    How to do it...

    There's more…

    Creating helpers for your classes

    Getting ready

    How to do it...

    There's more...

    See also

    Checking strings with regular expressions

    Getting started

    How to do it...

    There's more...

    3. Going Cross Platform with FireMonkey

    Introduction

    Giving a new appearance to the standard FireMonkey controls using styles

    Getting ready

    How to do it…

    How it works...

    There's more…

    Creating a styled TListBox

    Getting started

    How to do it…

    How it works...

    There's more…

    Impressing your clients with animations

    How to do it…

    How it works...

    There's more…

    Using master/details with LiveBindings

    Getting started

    How to do it…

    How it works...

    There's more…

    Showing complex vector shapes using paths

    Getting started

    How to do it…

    How it works...

    There's more...

    Using FireMonkey in a VCL application

    Getting started

    How to do it...

    How it works…

    There's more…

    4. The Thousand Faces of Multithreading

    Introduction

    Synchronizing shared resources with TMonitor

    Getting ready

    How to do it…

    How it works…

    There's more…

    Talking with the main thread using a thread-safe queue

    Getting ready

    How to do it...

    There's more

    Synchronizing multiple threads using TEvent

    Getting ready

    How to do it...

    There's more…

    Displaying a measure on a 2D graph like an oscilloscope

    Getting ready

    How to do it...

    There's more…

    5. Putting Delphi on the Server

    Introduction

    Web client JavaScript application with WebBroker on the server

    Getting ready

    How to do it...

    Retrieving the people list

    Creating or updating a person

    Deleting a person

    Running the application

    There's more…

    Converting a console service application to a Windows service

    Getting ready

    How to do it...

    How it works...

    There's more...

    Serializing a dataset to JSON and back

    Getting ready

    How to do it...

    There's more...

    Serializing objects to JSON and back using RTTI

    Getting ready

    How to do it...

    How it works...

    There's more...

    Sending a POST HTTP request encoding parameters

    Getting ready

    How to do it...

    How it works...

    There's more...

    Implementing a RESTful interface using WebBroker

    Getting ready

    How to do it...

    How it works...

    There's more...

    Controlling remote applications using UDP

    UDP

    Getting ready

    How to do it...

    How it works...

    There's more...

    Using App Tethering to create a companion app

    Getting ready

    How to do it...

    There's more...

    Creating DataSnap Apache modules

    Getting ready

    How to do it...

    How it works...

    There's more...

    6. Riding the Mobile Revolution with FireMonkey

    Introduction

    Taking a photo, applying effects, and sharing it

    Getting ready

    How to do it...

    How it works…

    There's more…

    Using listview to show and search local data

    Getting ready

    How to do it...

    How it works...

    There's more...

    Do not block the main thread!

    Getting ready

    How to do it...

    How it works...

    There's more...

    Using SQLite databases to handle a to-do list

    Getting ready

    How to do it...

    There's more...

    Using a styled TListView to handle a long list of data

    Getting ready

    How to do it...

    How it works...

    There's more...

    Taking a photo and location and sending it to a server continuously

    Getting ready

    How to do it...

    The client side

    The server side

    There's more...

    Talking to the backend

    Getting ready

    How to do it...

    There's more...

    Making a phone call from your app!

    Getting ready

    How to do it...

    How it works...

    There's more...

    Tracking the application's life cycle

    Getting ready

    How to do it...

    There's more...

    7. Using Specific Platform Features

    Introduction

    Using Android SDK Java classes

    Getting ready

    How to do it...

    There's more...

    Using iOS Objective-C SDK classes

    Getting ready

    How to do it...

    There's more...

    Displaying PDF files in your app

    Getting ready

    How to do it...

    Showing the PDF file on Android

    Showing the PDF file on iOS

    There's more...

    Using Google Docs Viewer

    Downloading the PDF file from the server

    Sending Android intents

    Getting ready

    How to do it...

    More complex intents – sending a full flagged e-mail

    Starting an activity for results – the SpeechToText engine

    There's more...

    Letting your phone talk – using the Android TextToSpeech engine

    Getting ready

    How to do it...

    There's more...

    Index

    Delphi Cookbook


    Delphi Cookbook

    Copyright © 2014 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

    Production reference: 1190914

    Published by Packt Publishing Ltd.

    Livery Place

    35 Livery Street

    Birmingham B3 2PB, UK.

    ISBN 978-1-78355-958-9

    www.packtpub.com

    Cover image by Junaid Shah (<junaidshah111@gmail.com>)

    Credits

    Author

    Daniele Teti

    Reviewers

    Eric Van Feggelen

    Sherwin John

    Olivier Pons

    Jorge H. Rodriguez

    Commissioning Editor

    Sam Birch

    Acquisition Editor

    Richard Harvey

    Content Development Editors

    Balaji Naidu

    Pooja Nair

    Technical Editors

    Mrunal Chavan

    Dennis John

    Edwin Moses

    Copy Editors

    Roshni Banerjee

    Adithi Shetty

    Project Coordinator

    Leena Purkait

    Proofreaders

    Bridget Braund

    Paul Hindle

    Amy Johnson

    Indexers

    Monica Ajmera Mehta

    Tejal Soni

    Graphics

    Valentina D'silva

    Abhinash Sahu

    Production Coordinators

    Aparna Bhagat

    Manu Joseph

    Cover Work

    Aparna Bhagat

    About the Author

    Daniele Teti is a software architect, trainer, and consultant with over 18 years of professional experience. He writes code in a number of languages but his preferred language to compile native software is Object Pascal.

    Daniele is a well-known Delphi and programming expert in the developer community. He's the main developer and drives the development of some Delphi open source projects (DelphiMVCFramework; DORM, the Delphi ORM; Delphi Redis Client; and so on). He wrote his first program when he was 11 years old, and since then, he happily continues to write software almost every day. Apart from Delphi, he's a huge fan of design patterns, expert systems, RESTful architectures, and Android OS. When he is not busy writing software or programming (as his job or hobby), he likes to play the guitar, write songs, and do voluntary activities. Currently, he works as an R&D Director & Educational at bit Time Software (www.bittime.it), an Italian representative of Embarcadero Technologies (www.embarcadero.com). He recently became the CEO of bit Time Professionals, which is a spin-off company of bit Time Software; this company specializes in consultancy, training, and development.

    Being a software architect, consultant, and teacher for many Italian and European companies, he travels very often around the world. He is the Technical Director of ITDevCon, the biggest European Delphi conference (www.itdevcon.it). He's also an international speaker at many technical conferences.

    Daniele lives in Rome, Italy (where each photographer becomes an artist) with his beloved wife, Debora, and their little boy, Mattia.

    About the Reviewers

    Eric van Feggelen is a passionate and experienced software consultant who delivers high-quality solutions using the latest technologies available. He has about 15 years of experience as a developer and has been interested in information technology his entire life. In the past few years, he worked for major corporations, such as Microsoft and Avanade and continues to serve the Microsoft Enterprise space as a private contractor for his own company. At the time of writing this book, Eric has worked as a lead developer for a Microsoft Dynamics start-up.

    In 2013, Eric reviewed Mastering Windows 8 C++ App Development, Packt Publishing.

    Olivier Pons is a developer who's been building websites since 1997. He is a teacher at IngéSup (École Supérieure d'Ingénierie Informatique – http://www.ingesup.com/ and http://www.y-nov.com), at the University of Sciences (IUT) in Aix-en-Provence, France. At École d'Ingénieurs des Mines de Gardanne, he teaches state-of-the-art web techniques, such as MVC fundamentals, Symfony, WordPress, PHP, HTML, CSS, jQuery/jQuery Mobile, Node.js, AngularJS, Apache, Linux basics, and advanced Vim techniques. He has already worked as a technical reviewer for Ext JS 4 First Look, jQuery Hotshot, jQuery Mobile Web Development Essentials, WordPress Complete, and jQuery 2.0 for Designers Beginner's Guide Second Edition. All these books were published by Packt Publishing. In 2011, he left his full-time job as a Delphi and PHP developer to concentrate on his own company, HQF Development (http://hqf.fr). He currently runs a number of websites including http://www.battlesoop.fr, http://www.krystallopolis.fr/ (which will be released soon), http://www.livrepizzas.fr, http://www.papdevis.fr, and http://olivierpons.fr (his own web development blog). He also works as a consultant, teacher, and project manager, and sometimes, helps big companies as a senior / highly skilled developer.

    Jorge H. Rodriguez has a background in software development and more than 20 years of experience under his belt, many of them working with Delphi.

    Always on the lookout for new and exciting technologies, Jorge lives to code and spends much of his spare time reading technical books and playing online chess. During winters, he likes to go snowboarding with his only son, Camilo.

    Jorge resides in Vancouver, Canada, awaiting his Colombian girlfriend, Shana. He can be contacted at <delphi.developer@shaw.ca>.

    www.PacktPub.com

    Support files, eBooks, discount offers, and more

    You might want to visit www.PacktPub.com for support files and downloads related to your book.

    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 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.

    http://PacktLib.PacktPub.com

    Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books.

    Why subscribe?

    Fully searchable across every book published by Packt

    Copy and paste, print and bookmark content

    On demand and accessible via web browser

    Free access for Packt account holders

    If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.

    Preface

    If you've been a software developer for a long time, you certainly know how useful a conversation can be with a colleague who already did something similar to what you are doing, and can discuss it as he/she may have faced the same problem. It is not possible to include all the possible situations that a developer may face in a book, but most problems are similar at least in principle. This is the reason this book is organized as a cookbook; just like how a combination of foods can be adapted and modified to be appropriate for different types of meals. A programming recipe can provide the idea to solve many different problems.

    This book is an advanced-level guide that will help Delphi developers become experts in their every day job. The every day job and the quality of your deliverables is what contribute to the quality of your professional life. It does not make sense to reinvent the wheel repeatedly, especially when working with a well-established tool such as Delphi. The focus of this 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 this book are a result of years of development, training, and consultancy activities in the most different fields of the IT industry, from small systems with thousands of installations to large systems commissioned by any big company or government. It is not a magic book that will solve all your development problems (if you find it, tell me please!), but it can be a valid source of help 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 enumerables, extended RTTI and duck typing, LiveBindings, multithreading, FireMonkey, mobile development, server-side development and many more, you will be pleasantly surprised as to how quickly and easily you can use Delphi to write high quality, clean, readable, maintainable, and extensible code.

    I have read too many boring programming books, so I tried to maintain a relaxed and light exposition. A small applicability scenario, which 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 consist of thousands of pages; however, it is also not trivial because the IT books landscape is already full of trivial examples with a few direct applications. I tried to do a good trade-off and hope I succeeded.

    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 on the topics it talks about?, or Will it be worth the time to read this book?. Now that I'm on the other side of the river, I worked hard to put as much good quality content as possible in this book, which I hope will match your expectations.

    On a final 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 as much as I enjoyed writing it.

    What this book covers

    Chapter 1, Delphi Basics, talks about a set of general approaches that should not be ignored by any Delphi programmer. Some recipes are simple, while some are not, but all of them should be deeply understood. By the end of this chapter, you will be able to use some of the fundamental Delphi techniques related to the RTL, VCL, and OS integration.

    Chapter 2, Become a Delphi Language Ninja, focuses on the Object Pascal language. A programming language is the way you talk to the machine, so you must be fluent and should 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 lower the amount of time spent on debugging.

    Chapter 3, 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 FireMonkey supports. Moreover, you will learn about nontrivial LiveBindings utilizations.

    Chapter 4, The Thousand Faces of Multithreading, is one of the most complex chapters. It talks about thread synchronization and the mechanisms used to obtain this synchronization, including TMonitor, thread-safe queues, and TEvent. By the end of this chapter, you will be able to create and communicate with background threads, leaving the main thread free to update your GUI (or communicate with the OS).

    Chapter 5, 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; the number of Delphi server-side systems running all over the world prove it! In this chapter, we'll show how to create powerful servers that offer services over a network. Then, in one of the recipes, we'll also implement a JavaScript client that brings the database data to the user's browser. The techniques explained in this chapter open a range of possibilities, especially in the mobile and web area.

    Chapter 6, Riding the Mobile Revolution with FireMonkey, is dedicated to mobile development with Delphi and FireMonkey. If you are interested in mobile development, I think that this will be your favorite chapter! Mobiles are 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 your mobile device, how to retrieve and update remote data, and how to integrate with a mobile operating system.

    Chapter 7, 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 use the SDK classes from your Object Pascal code.

    What you need for this book

    This book talks about Delphi, so you need Delphi. Not all recipes are available in all the Delphi editions. Typically, the mobile projects can be compiled only if you have Delphi Enterprise or better (or Delphi Professional plus the mobile add-on, or RAD Studio professional, or better). All the projects are compiled and tested on Delphi XE6. Many of the recipes can also be compiled on older versions.

    If you want to run the mobile app on a phone or tablet, you can use the Android emulator or iOS simulator, but it is strongly recommended that you use 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 Mac OS X. More information is provided in the related chapters.

    Who this book is for

    This book aims to help professional Delphi developers in their day-to-day jobs. 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 in your Delphi skills. An experienced developer will benefit from this book because nontrivial problems are solved using the best practices. Where more than one way is available or the topics are too vast to be explained in the available pages, references are provided that allow interested readers to go deeper in that field. It is a book that'll hold on to your desk for the next few years.

    Conventions

    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: The TStyleManager.StyleNames property contains all names of the available styles.

    A block of code is set as follows:

    LogMessage('Your message goes here for SUCCESS',

            EVENTLOG_SUCCESS, 0, 1);

    When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

    begin

      Application.Initialize;

      Application.MainFormOnTaskbar := True;

     

    TStyleManager.TrySetStyle('Iceberg Classico');

     

      Application.CreateForm(TMainForm, MainForm);

      Application.Run;

    end.

    Any command-line input or output is written as follows:

    C:\\WindowsService.exe /install C:\\WindowsServiceOrGUI.exe /GUI

    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: Click on Start, wait for the confirmation, and the service should start to write its logfile.

    Note

    Warnings or important notes appear in a box like this.

    Tip

    Tips and tricks appear like this.

    Reader feedback

    Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

    To send us general feedback, simply send an e-mail to <feedback@packtpub.com>, and mention the book title via 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 on www.packtpub.com/authors.

    Customer support

    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.

    Downloading the example code

    You can download the example code files for all Packt books you have purchased 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.

    Errata

    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 would 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 on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

    Piracy

    Piracy of copyright 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 <copyright@packtpub.com> with a link to the suspected pirated material.

    We appreciate your help in protecting our authors, and our ability to bring you valuable content.

    Questions

    You can contact us at <questions@packtpub.com> if you are having a problem with any aspect of the book, and we will do our best to address it.

    Chapter 1. Delphi Basics

    In this chapter, we will cover the following recipes:

    Changing your application's look and feel with VCL styles

    Enjoying the preview?
    Page 1 of 1