Quantcast
Channel: Tips, Tricks and Techniques - Embarcadero Community
Viewing all 182 articles
Browse latest View live

デベロッパーキャンプ開催計画と講師募集のお知らせ

$
0
0

海外からは、「CodeRage XI」の開催がアナウンスされましたが、日本ではむしろ先輩格にあたる「デベロッパーキャンプ」の33回目の開催計画が進んでいます。第1回の開催が2006年ですから、もう10年も経つのですね。

さて、その33回目の開催は、東京では12月の第2週(12月5日の週)で調整が進んでいます。最近は、大阪開催も併せて実施していますが、今回もその前後に実施されると見込まれます。今回は、10.1 Berlinリリースから半年以上経過し、いろいろとノウハウも蓄積されてきた中での開催なので、実践的なセッションが数多く期待できますが、同時に気になる次期バージョンの情報もご覧いただけるようになるでしょう。

東京、大阪、ともに12月上旬のカレンダーはマークしておいてください。そして、スケジュールの最終決定をお待ちください。

そして、恒例のコミュニティスピーカー募集です。

1) セッションスピーカー

以下のようなテーマで講演いただけるスピーカーを募集します。日頃の開発の成果を発表しませんか?

  • Delphi、C++などの開発言語、ツール活用のテクニック、チュートリアル
  • 旧バージョンからの移行TIPSなど
  • モバイルやタブレット向け開発、クロス開発など、新しいプラットフォームへの適用例
  • 関連する技術(データベース、ミドルウェア、IoT、ツール)の活用テクニック
  • Delphi/C++Builderユーザーの視点から見たエンバカデロのデータベースツール活用例
  • 最新のソフトウェア開発技術に関する情報
  • 最新バージョンを適用した開発例
  • エンバカデロ製品を利用した開発事例、技術的ポイントの紹介

講演時間:60分
講演料:25,000円
申込方法:デベロッパーキャンプのセッションスピーカーを希望される方は、japan.info@embarcadero.comまで、「第33回デベロッパーキャンプ講師応募」という件名で、以下の情報を記載したメールをお送りください。

  • 氏名(フリガナ)
  • 会社名
  • 部署名
  • 役職
  • プロフィール
  • メールアドレス
  • 電話番号
  • 講演内容案(テーマ/セッション概要など)
  • 対象製品/言語
  • セッションタイプ(チュートリアル/テクニカル/ケーススタディ/プレビュー/その他)
  • 講演希望場所: 東京 および/または 大阪

申込締切り:2016年10月24日

2) ライトニングトーク

最後のセッションは恒例「ライトニングトーク」。5分間のプレゼン時間で、皆さんの思いを語ってください。プログラミングに対する思い、TIPS、ご自身の経験、事例など、テーマは自由です。

出演を希望される方は、japan.info@embarcadero.comまで、「第33回ライトニングトーク出演希望」という件名で以下の情報を記載したメールをお送りください。

  • お名前 および フリガナ(ハンドル名等で参加される場合はその旨明記ください)
  • 会社名(個人として参加される場合は不要)
  • 連絡先(電話番号)
  • トークのタイトルと概要
  • PC持ち込み あり/なし(接続にはHDMIを使用します)
  • 講演希望場所: 東京 および/または 大阪

特典:懇親会に無料ご招待

皆さんの挑戦をお待ちしています。


Что почитать про продукты Embarcadero. Обзор публикаций.

$
0
0

Последние недели не удавалось публиковать посты так часто, как хотелось бы. За это время появилось достаточно много заслуживающих внимания публикаций, как на русском, так и на других языках.

Предлагаю вашему вниманию краткий обзор того, что можно было бы почитать про RAD Studio, C++, Delphi и другие продукты Embarcadero.

Для начала, о прошедших вебинарах. Записи трансляций и исходные тексты доступны для просмотра и скачивания. Первый - "Clang компилятор, синтаксис С++11 или Что нового в C++Builder 10.1 Berlin" - рассказывал о новшествах, вошедших в последний релиз Update 1, и преимуществах Clang-компилятора, поддерживающего синтаксис C++11. Запись доступна для просмотра на YouTube  https://youtu.be/vmy5Z61t_Vg 

Слушателям вебинара "Разработка WEB-ориентированных систем на RAD Server" не повезло: во время трансляции возникли спонтанные технические проблемы. Тем не менее, на YouTube - канале Embarcadero Russia доступна полная запись вебинара https://youtu.be/GDurI2Vie10, а исходные тексты примеров AngularJS и RAD Server EMSNotes можно скачать на GitHub https://github.com/jtierneyemb/EMSNotesNg

Для русскоязычных разработчиков есть приятная новость: опять заработал блог-агрегатор DelphiFeeds.ru: http://delphifeeds2.ru/ на котором собираются сообщения из разных блогов, посвященных Delphi, RAD Studio и другим продуктам Embarcadero для разработки ПО. Из последних мое внимание привлекли следующие публикации: Delphi. Битовые операции и фильтр Блума. Вступление Станислава Пантелеева и App Tethering в Delphi 10.1 Berlin Владислава Баженова.

Еще один примечательный пост привлек внимание на сайте ХабраХабр.

Статья Выбор СУБД для мобильного Delphi-приложения содержит полезную информацию, изложенную в объективной манере, и вызвала большой интерес на сайте.

И конечно, огромное число полезнейших публикаций поставляет интернациональное сообщество пользователей Embarcadero на сайте http://community.embarcadero.com и в других социальных сетях. Большинство публикаций на английском, но есть на немецком, португальском, японском и др. языках. 

InterBase уже был темой предыдущей статьи, но у некоторых пользователей, перешедших на Windows 10 Aniversary Update, могли возникнуть вопросы при подключении приложений к серверу InterBase. В этой статье InterBase and Windows 10 Anniversary Update содержится рецепт "правильной" настройки для надежной работы соединений.

Delphi - это самый быстрый в мире компилятор! В публикации Джима МакКис (Jim MCKEETH) есть весьма наглядное подтверждение этому - ссылка на видео, как Delphi компилирует миллион (!!!) строк исходного кода. Delphi 10.1 Berlin Update 1 содержит ряд улучшений компилятора, поэтому здесь вы также найдете сравнение скорости компиляции Berlin и Seattle, особенно при массивном применении Generics в коде программ. Статья Compile Time and Generics

Многие компании и разработчики уже давно понимают, что пришла пора обновлять свои средства разработки Embarcadero до последних версий, например, Berlin. Для тех, кто долгое время решал свои задачи на "старых" вариантах Delphi или C++Builder, и собирается мигрировать свои системы на Berlin, как можно более плавно, мы подготовили специальный вебинар, Центр миграции и Обновления, а также ряд инструментов.  Подробности здесь: Migrating Delphi - Case Studies; September 21 Webinar.   Тем, кто хочет понять, не устарела ли VCL, что "лучше" - VCL или FMX, на чем следует разрабатывать новые приложения, предлагается специальный пост FireMonkey vs. VCL. В ноябре-декабре мы рассмотрим подробности по этой теме на русском языке.

Без сомнения, многие читали замечательную книгу Ника Ходжеса (Nick Hodges) "Coding in Delphi". Некоторое время назад мы бесплатно раздавали ее нашим покупателям. Ник вернулся в компанию и теперь занял соответствующее место в Embarcadero. Это очень добрая новость для всех, кто разрабатывает на RAD Studio. Он продолжает писать прекрасные технические статьи и проводить вебинары. Например, 13 октября он будет вести вебинар  Connascence: How to Measure Coupling with Nick Hodges, посвященный распространенной проблеме программирования - чрезмерной связанности кода. 

Я уверен, что вы знаете, что редакции Delphi Starter и C++Builder Starter стали бесплатными. Они имеют ограниченные возможности, но несмотря на это, посмотрите, что наши немецкие коллеги сумели сделать на Delphi Starter: программа управления аэропортом

В октябре-ноябре состоится очередная онлайн-конференция Embarcadero. Приглашаем всех присоединиться к ней в качестве слушателей. Это интересно, полезно и бесплатно.

 

 

Learn to program with C++Builder: #1, Introduction and Installation

$
0
0

Welcome to the first blog post in the ‘Learning to program with C++Builder’ series - a set of five articles taking you from knowing nothing about C++ to writing a real-world, useful application.

I’m David Millington, the C++Builder Product Manager, and in parallel Pawel Glowacki is writing the same series and same app in Delphi. We may have some cross-language rivalry here ;) In the coming weeks, Pawel and I are going to publish weekly blog posts taking you step by step through programming in our respective languages, with Delphi and C++Builder. We’ll be taking you through from the very beginning, assuming you know no Delphi or C++ at all, and show you how to build a real-world, useful application - we’re currently thinking a scientific calculator, because it demonstrates UI, UI and logic separation, and many useful classes like stacks and utility methods, ie is a great overview of many areas you need to know about.

The really neat thing is that you can use both languages together in one natively compiled application, something we won’t show in this series but is one of the amazing integrations our tooling offers.

Today’s post is an introduction and will show you how to install the Starter edition of C++Builder - it's available at 100% off, ie $0, see below for more information about Starter - and then next week we’ll dive into code. We are assuming that you know some programming basics - we’re not going to explain what a class is, for example, but instead will show how to write and use one in C++.

If you are

  • a hobbyist who’s done some programming but never used C++ (or Delphi) before,
  • a student,
  • or a professional who wants to learn something new,

this series is for you.

As much as possible we will try to synchronize topics and content, so you could even switch from one track to another. It will also be very interesting to see the same application developed in two languages, written the “Delphi way” and the “C++ way.”

C++Builder is a particularly powerful C++ platform, because not only does it give you C++ (of course), but it includes a massive variety of libraries and frameworks that other C++ tooling does not. This includes tools for writing cross-platform user interfaces, including using native controls; database access for several dozen databases in a very clean and powerful library; REST, JSON and other web frameworks; and more. The libraries and frameworks are fast to use - we find that users who know our tooling can achieve polished and complete applications in fractions of the time it takes using other IDEs, whether that be C++ or other languages like C#. The end result is you can build an application once, including designing its UI for multiple platforms, and deploy it - natively compiled - to Windows, iOS, Android, and MacOS, fast. Linux is coming in the next release too.

So let’s get started! Today’s post is an introduction to the series, and shows you how to install C++Builder Starter. Starter is available at 100% off - ie for $0 - right now. The following four posts over the next few weeks will introduce you to the IDE and to C++ itself, and then go on to develop a real-world, cross-platform, useful application.

Installation

Let's install C++Builder Starter. Starter is free - go download it now!

Important note: The 10.1 Berlin Starter version does not co-exist with any other edition (SKU) of 10.1 Berlin. Ie, if you have Delphi 10.1 Berlin Pro, you cannot install 10.1 Berlin Starter. On the other hand, if you have 10.0 Seattle, ie another version, they co-exist fine. It's just that Starter Berlin doesn't co-install with AnythingElse Berlin. If you have, say, Delphi Berlin Pro (or Starter) already installed, install C++Builder Starter on another PC or in a virtual machine. If you want both, you can always download the RAD Studio trial instead - it includes both C++Builder and Delphi.

When you visit that link, you will be asked to create an EDN account if you haven't already got one. EDN is the Embarcadero Developer Network. Go ahead and fill in the info, or if you already have an account, click the Login text in the middle right to just enter your email and password.

Once done, you'll get a download automatically starting, and a notice that you've been sent an email with your license key.

and if you check your email, you'll see something like this (with my key redacted in yellow.)

So, you have the download and a license key. Run the installer:

Agree to the license agreement:

(You can ignore the Options button; there's nothing there you need to change.)

Click Next, and on the next screen select that you already have a serial number (you do; this is the key that was in your email):

When you click Next, you might see a regular install progress window for a few seconds, but pretty soon you'll be asked for the serial key in a popup dialog. Enter it in the top section. You don't need to worry about the rest of the window (EDN login details), just the license key.

...and click Register.

You'll get the install progress window for a while...

Right now, it's installing the IDE shell. (In fact, after this bit completes you'll even be able to run and use the IDE as a text editor. It just won't have Delphi or C++Builder living inside it - that comes in a moment.)

At some point, Windows will prompt you with a firewall question, saying BDS.exe wants to access the network. It's important you click the checkboxes to allow this. Starter is ok, but other editions use the network for, for example, communicating with debuggers. If you don't enable this then you might find things don't work correctly.

Pretty soon, you'll be greated with this really pretty window. This is where you select the "personalities" and platforms that live in the IDE. Since you've downloaded C++Builder Starter, there's only one - C++ for Win32. (The other versions have many more platforms, like iOS, Android, Win64, macOS, and of course possibly Delphi as well as C++.) Click Continue.

On the next page, you can click through, but I'd recommend you select to install samples and help. The samples are useful demo programs we ship to demonstrate various features, libraries, etc. The help gives you a language reference, information about the various libraries and classes, the various parts of the IDE, etc.  

Then it will install. This should go by very quickly - the installer you're seeing is known as the GetIt Feature Installer, and it uses GetIt, our package manager. It's much faster than the old installer.

Soon, you will see another dialog to install the Windows SDK. This is a Microsoft redistributable:

However, you don't need to install everything it suggests. If you want, you can install just the Windows Software Development Kit:

This might take a while. Sorry. It's not ours.

And then, oh happy day...

Success! START WORKING, now that's a good button to click.

And in a moment, you'll have the IDE!

Congratulations! You're installed, and ready for next week's post digging into the IDE. 

What is Starter Edition?

So what is Starter Edition after all? Is it free? Can it be used commercially? Can I use it as a student?

Put simply, yes (with caveats) for all three.

Starter is intended to get people started with Delphi or C++Builder, and that can be either getting started with programming in general - such as a student - or for starting something else, such as writing software for your startup company.  It is a cut-down version of the Professional version and it contains only Windows 32-bit compilation.  That’s enough to learn to program, or to write a saleable Windows program or a almost-complete mobile application (where you buy Pro + Mobile to finish and build for Android or iOS.) If you’re a startup, you can do almost all your development for no cost at all.

The only license restriction is based on revenue. This isn’t legal advice - please read the EULA - but roughly speaking, if you make enough money that you could buy Pro, we ask that you do.

  • So if you’re a hobbyist? It’s free. Enjoy!
  • If you’re a student? It’s free. Enjoy!
  • If you’re a startup? It’s free, but once you start making sales and get incoming revenue, you need to move to Professional or above.
  • If you’re an existing company? You may find the revenue / commercial use options mean that Professional, Enterprise or Architect are a better option for you. Remember there is always the fully-featured trial version if you just want to try RAD Studio out. 

That’s why we say Starter is to help you get started. If you’re using it and start making money, then please buy a copy; if you aren’t, it remains free. Either way we’re very glad you’re using our products, and this series of blogs is a great resource to get you started.

See you next week!

RAD Studio 10.1 Berlin: Die neuen Roadshowtermine stehen fest - Hamburg, Mannheim, Zürich

$
0
0

Wir sind wieder unterwegs. Und zwar am 1. November in Hamburg, am 4. November in Mannheim und am 15. November in Zürich/CH.

Volker Hillmann (adecc-Systemhaus) und ich präsentieren die Neuerungen im RAD Studio 10.1 Berlin.

Eine völlig neue Installationsroutine ermöglicht es Ihnen, genau so viel oder so wenig zu installieren, wie Sie möchten - und damit die Startzeit auf wenige Minuten zu reduzieren! Die geräteübergreifende Entwicklung wurde durch den FireUI App Preview erweitert. Sie erhalten so eine Vorschau Ihrer Formulare auf jedem beliebigen Gerät (Desktop oder Mobile). Damit Sie das Internet of Things (IoT) noch effizienter und schneller in Ihre Apps einbinden können, erhalten Sie mit der neuen Version einfach zu handhabende Tools und Bibliotheken existierender APIs.

Das alles und noch viel mehr wird Ihnen Matthias Eißing (Delphi) und Volker Hillmann vom adecc-Systemhaus (C++Builder) live an einem Tag vorstellen. Natürlich haben Sie in den Pausen Zeit, Ihre Fragen zu stellen und sich untereinander zu vernetzen. Wir laden Sie herzlich ein, dabei zu sein. Für die Tagungspauschale erheben wir einen Beitrag von 45 EUR bzw 50 CHF, damit wird den ganzen Tag für Ihr Wohl gesorgt.

Nähere Informationen zu den Veranstaltungen (Agenda, Ort, Kosten) und die Anmeldung finden Sie hier:

Hamburg / 1. November
https://www.xing-events.com/rad_roadshow_hamburg.html

Mannheim / 4. November
https://www.xing-events.com/rad_roadshow_mannheim.html

Zürich / 15. November
https://www.xing-events.com/rad_roadshow_zurich.html

 

Learn to program with C++Builder: #2, Building and Debugging

$
0
0

Welcome to the second blog post in the ‘Learning to program with C++Builder’ series - a set of five articles taking you from knowing nothing about C++ to writing a real-world, useful application. The first entry covered installing C++Builder Starter. Now it’s time to start using it! Today, we’ll cover the tools you use, creating your first app, and basic debugging.

Understanding the IDE

C++Builder, the product, is what we call the IDE (Integrated Development Environment), which is the program you see when you start C++Builder. An IDE has three general areas or things that it helps you do:

  • A code editor
  • A compiler
  • A debugger

The code editor - and because C++Builder is great for UI programming, the form designer fits into this area too - is where you write code, a text editor with special enhancements for programming. When you have a form (that is, a window you are designing), one tab of the code editor lets you edit the form.

The compiler is what converts the code into a program that Windows can run.

The debugger lets you run the program and see what it’s doing. You can pause it, look at various parts of it, run through your code step by step, and so forth, all to understand what your code is doing and find the cause of any unexpected behaviour - that is, bugs.

All three of these are integrated together and accompanied by a number of dockable tool windows, other tools, etc. You don’t even need to think of these are separate things, more as just different actions you do: “now I’m writing code”, “now I’m running my program”.

Projects

Typically, you want to use more than one single source code file to create your application. A project is how the IDE groups together multiple source code files into one app, and includes other information, things like which platform you’re compiling for, or ‘targeting’, such as Windows or Mac, if when you compile you add in extra information for the debugger so it can see more about your app’s internals, etc.

When you create a new project the IDE creates several files for you. Let's have a look at these files.

The first thing to do is create a new project. Start C++Builder, go to the File menu, and choose New > “Multi-Device Application - C++”. This create a new FireMonkey project, one that can be used on Windows, iOS, Android, etc.  (Note that Starter only supports Windows 32-bit, but you can open a project created by Starter with Pro or higher, and target, say, iOS.) In the dialog that appears, select “Blank application” and click OK.

You now have a project, and you’ll see this in the Project Manager, a window that by default is docked on the right hand side of the IDE.

Before going any further, click the Save All button. You will be prompted to save several files. Put them all in the same folder. You’ll notice they are files listed in the Project Manager.

So what are these files? Open up the folder where you saved everything and have a look. For me, many of these are labeled ‘Project2’ - for you, they might have a different number. Most likely, yours will be Project1.

  • Project*.cbproj (for me, Project2.cbproj.)  This file describes the project - what files are in it, what the settings are. It corresponds to the bold top-level node labeled ‘Project2’ in the Project Manager.
  • Project2.cpp: this is the first, main source code file for the application. Applications have an ‘entry point’, a place where they start. This file contains that.
  • Project2PCH1.h: ‘PCH’ stands for ‘precompiled header’. We’ll get to headers later, but basically this file is used as an optimisation for making your application compile faster.
  • Unit1.cpp, .fmx, and .h: C++ splits its code units into two files, the main implementation file, where your methods etc are actually written, and a header, which is where they’re declared. A header basically tells the compiler ‘this is what you should expect to see’; the implementation .cpp is where you actually implement it. These two are logically paired in the mind of any C++ programmer, but C++Builder formalises it by calling them a ‘unit’. (If you go File > New > Unit you will get a new .cpp/.h pair.) In fact, in the code editor, C++Builder opens them as a single entity too, and you switch between the .cpp and header using tabs at the bottom of the code editor.
    So what is the .fmx file? The new project created a new unit by default, but this unit is special: it is used for a form (a form is what becomes a window when you run the app.) A window has a UI design part too, and this UI is stored in the .fmx file. So for visual parts of your application, which are both code and UI, the unit has three parts: cpp, header, and form.

This app will become our calculator, and those default names are not very good. We could have saved the files with new names, but I wanted to explain what each one is first - project file, main file, precompiled header, form and unit. But let’s rename these.

In the project manager, right-click the bold Project2 node, and select Rename. Type in CppSuperCalculator. You’ll notice that the precompiled header and main file are renamed too - that’s because the IDE manages those and keeps them in sync. Then rename the unit - right-click it, Rename, and call it ‘uFormCalculator.cpp’. Notice that the unit has a + symbol next to it so you can see all three files that together form the unit - you can rename any one of these and the others will automatically rename to match.

Click Save All and check back in Explorer. The files will have been renamed.

You might see some other files - ‘*.local’, a ‘__history’ folder, etc - ignore these. The IDE uses them.

Building the project

Building is compiling - going from all the text source code to a final EXE file. You can build from either the Project menu, or by right-click the project and selecting Build. (Make is like a light build - it compiles only the bits that changed since last time. Clean wipes everything, all the intermediate saved files, so you start compiling from a clean slate next time.)

Do this, and you’ll see a window appear telling you it built successfully.

When you go back into Explorer, you’ll notice some new files and folders. There is now ‘CppSuperCalculator.res’ - this contains the program icon and version. There is also a Win32 folder, and inside that a Debug folder. These are where the temporary files are saved while building, and the final EXE is located. Win32 is the target platform (the only one available for Starter) and Debug is the build configuration - you can see this node in the Project Manager; there are two configurations by default, Debug and Release.  (Debug does less optimization and includes information helpful for the debugger to see what’s going on inside your program; Release does more optimization and less debug info. You use Debug while developing, and Release for the app you give your users.)

Going by file extensions, the .#01 (and other number) files and the .pch file are to do with precompiled headers - something that doesn’t matter now. The .obj files are object files, which are compiled versions of each source code file or unit. The .map and .tds files are used by the debugger, and the .exe file is your final program!

Running and debugging

Don’t run this EXE (although you can) - let’s make the IDE run it.

Back in the IDE, there are two toolbar buttons, one a large green arrow and one the same green arrow but smaller, over a program.

These are Run Without Debugging and Run [implied, this means Run With Debugging]. (They are in the Run menu too.) Run Without Debugging just runs the program and doesn’t do any IDE / debugger magic; the most useful, and the one you’ll want to use every single time you run, is Run, which debugs as well. Go ahead and click it.

You will see the IDE change a couple of docked windows, and lots of messages appear in a window at the bottom. Then, you will see your application appear - a blank window, currently, but it’s your app!

Congratulations. Close the app by clicking its X button in its window, or in the IDE, click the red Program Reset button near the run buttons.

Debugging

‘Programming is a mental art’, Pawel says in his Delphi version of this blog post, and he’s right. Debugging is part of it, and is the process of figuring out why your app is not doing what you want it to be doing. When you’re doing that, the debugger is a very useful tool: it lets you examine the internal of your program to see what it’s actually doing, and step through code to see why it does particular things. You can change your program too: change the values of variables, call methods, right down to changing the values in processor registers if you really want to.

In order to demonstrate this, we’re going to add some more code to what is currently a very minimal project. Make sure the blank form is visible in the center of the IDE (if it isn’t, in the Project Manager double-click uFormCalculator, then in the center part, the code, editor, click the Design tab at the bottom. You will see the form designer appear: mostly white, with a grey blank form in the middle. This corresponds to the blank grey window when you ran the app.) In the bottom right part of the IDE, below the Project Manager, you will see the Tool Palette, and this contains lots of reusable components - visible controls, like buttons or checkboxes, and non-visual controls as well which perform other actions. (Make sure your app isn’t running; the IDE has different layouts when debugging vs coding.)

Expand the Standard item, and double-click TButton. A button will appear in the middle of our form. (Note you can drag and drop a control to the form too.)

Now, double-click on the button. This creates an event handler for when the button is clicked, that is, a method that is called when the button is clicked, and moves to the code editor. The method has been generated for you. Let’s add a line to show a message dialog - change it so it looks like this:

Note you need to get this exactly right. The L prefix to the string says it's a Unicode string (specifically, this is actually a string literal using wide characters, an array of wchar_t); the " marks have to be as they are on the keyboard, not Word-style quotes that change to point slightly towards the text they enclose; you need a semicolon at the end. If you make an error here, when you click run, you will get an error message in the Messages window at the bottom of the dialog.

Click Run, and your app will run. Now click the button, and you’ll see the message:

So far so good. Go back to the code editor, and notice that the ‘ShowMessage’ line has a blue dot next to it. That means the EXE contains code relating to that line.

Click the dot, and it will turn red and highlight the line. This is called a breakpoint, and means that whenever the application reaches that line of code, it will pause.

Click the button again, and this time instead of showing the message, the IDE will bring itself to the front. The red dot now has a blue arrow over it - that indicates the current line.

The program is now paused in the debugger. You can do several things - run it, so it continues; step line by line, so it executes the ShowMessage line but stops at the next, and so forth. Have a look at the other buttons on the toolbar next to the Run buttons, and also look in the View menu, Debug Windows, at all the things you can see.

That’s it for this week. We’ve created our first project, seen what a project contains, seen how the IDE manages some parts of it, run it, and debugged it. If you want to explore before next week, experiment with the debug windows, with the Step Over button on the toolbar near the Run buttons, with the breakpoint properties (if you right-click one), with the call stack window which shows the ‘stack’ of which method has called what to get you where you are now. Next week we’ll continue this app and start turning it into a real, useful calculator.

今更ながら VCLとFireMonkey向けボーナス スタイル パックのお話し [JAPAN]

$
0
0

RAD Studio / Delphi / C++ Builder 10.1 Berlin がリリースされたのが今年2016年の4月でした。既にに6か月が過ぎようとしているのですが、この 10.1 Berlin 向けのボーナス スタイルパックが提供されています。「スタイル」は、簡単な設定を行うだけでUIの印象を大きく変えることができる便利な機能です。
5月ごろにあったデベロッパーキャンプにても、ちょっとだけご紹介したのですが、せっかくの無償 スタイルパックを提供しているものの、あまり知られていない様子でしたので、今更ながら、ご紹介いたします。

まずはダウンロードリンクはこちら:

Learn Blazing Fast App Development For Android And iOS With A Single Source Code In Delphi

$
0
0

These videos cover getting started building mobile apps for VCL developer, setting up the different target platform configurations, best practices for designing your user interfaces for mobile apps, accessing local and remote databases, previewing your app using the FireUI Live Preview feature, utilizing mobile device sensors and the Internet of Things, submiting your app to the Apple App Store and Google Play, and finally quetion and answers from the original webinar.

Getting Started Building Mobile Applications for iOS and Android Introduction in this video.


[YoutubeButton url='https://www.youtube.com/watch?v=L4VhAauDsEA']
 
How to get started building Mobile Apps and using the target platform configurations in this video.

[YoutubeButton url='https://www.youtube.com/watch?v=_n97mKMbZ8Q']
 
UI Best practices for Building Mobile Applications in this video.

[YoutubeButton url='https://www.youtube.com/watch?v=XFGeuOOqDlE']
 
Accessing Local and Remote Databases from your mobile apps in this video.

[YoutubeButton url='https://www.youtube.com/watch?v=2kV60C9jPgY']
 
FireUI Live Preview and extending the App to support custom component viewing.

[YoutubeButton url='https://www.youtube.com/watch?v=bU_J3WxeClI']
 
Working with mobile Devices, Sensors and the Internet of Things in this video.

[YoutubeButton url='https://www.youtube.com/watch?v=alrX59PrF3E']
 
Submitting apps to the Apple App Store, Google Play Store in this video.

[YoutubeButton url='https://www.youtube.com/watch?v=-JNGEvKbfeU']
 
Have questions? Check out all of the questions and answers from the original Webinar.

[YoutubeButton url='https://www.youtube.com/watch?v=oTXeo7-VzIg']
 
[DownloadButton Product='Delphi' Caption='Download Delphi And Get Started!']

Workshop with Danny Wind

$
0
0

The last two days we, DAPUG - The danish Delphi Users Group, had Danny Wind presenting various topics like Parallel Programming Library, REST servers, JSON, Firemonkey styling, IoT and home automation and many other topics. 

During Dannys presentations he showd us some very cool apps running in production in The Netherlands (which we for obvious reasons never got the code for). Later we got to play with the Vera home automation box he brought.

The Workshop went very well and on day 2, we built an auctioning Software suite, which we actually used for auctioning of StroopWafels, a dutch speciality, and also a license from www.devart.com for one of their products. (Even if the software was auctioning software, it was just somewhat luck based).

Lasse Lægteskov won the prize from Devart.

Thanks to Devart for sponsoring the license.

And thank you very much Danny Wind for coming to our workshop. It was great!!

 

For those of you that dont know, the Dapug workshop is a two day workshop with ONE speaker. Well, we did have Cary Jensen and Marco Cantú together at one of them, but other than that, its normally one speaker. We have in the past 25 years had excellent speakers. In case you wonder how we can have a Delphi users group thats older than Delphi, it started of with being a Paradox Users Group but has evolved..

Next spring we are looking forward to receiving Malcolm Groves.

 

 


Learn to program with C++Builder: #3, Design, Architecture, and UIs

$
0
0

Welcome! Last week we looked at the IDE, projects, a simple first application, and basic use of the debugger. Today we’re actually going to write code! 

Pawel and I are both going to write a scientific calculator.  It’s a useful, real-world app. You might put it on your phone and use it (and we’ll show how to do this in the last blog post of the series.)  Not only can you do normal math like addition and division, but some more advanced operations - trigonometry (sin, cos, tan), powers, and other useful functions.

Part of programming is good design. Programming is an art, and when you’re writing code, and you envisage your whole app, you feel very creative. It’s important to create well, though - to value quality. This isn’t just out of a philosophical drive to do something well if you’re going to do it at all; instead, it’s practical. Good code is code you can come back to later and keep working on after you’ve forgotten how it worked. To write code like that, it needs to be well designed, so you or anyone else can read it and figure out how it works. This makes debugging much easier, too.  Debugging is hard enough already - if your app is clear, though, you can figure out problems with it much more easily than if it’s messy.

But also important is not just to design it well, but as you make changes, to keep it designed well.

Let’s illustrate this. First we’ll create the UI, and then we’ll start coding it wrong.

Building the UI

A scientific calculator has a fairly simple UI. It has buttons for numbers 0-9, a decimal point, math operations like addition and subtraction, and equals. (We will add sin, cos, tan etc next week.) Finally, it has a display area which displays what you’re entering, or the result of the operation.

Let’s build this.

Opening the app you had last week, delete the button on the form, so it is a completely blank form. Make sure you’re in the Master view in the toolbar at the top of the form designer - we can specialize for another platform, like iOS, later. Now in the Tool Palette, find TButton (you can type in the Search field, or open the Standard section, TButton is about the eighth entry) and add enough for all the buttons you need to the form. You can drag-and-drop, or double-click to just add in the center and drag them around later.

Important considerations for design:

Give your buttons good names. What is “Button14”? Who knows. But “btnEquals” is very clear. You can change this in the Object Inspector, Properties tab, Name.

While you’re at it, change your buttons’ Text property to reflect their function - eg, change them to ‘0’ or ‘=’.

Hint

Note you can multi-select items by dragging a selection, or holding Shift while clicking. You can then edit the properties of multiple controls at once. I want my buttons to be square, so I’ve done that to change the Width and Height properties for all of them at once.

Next, add an edit box for the calculator to show its input and result. Use TEdit, and set its ReadOnly property to true - we don’t want users typing in it.

This is what mine looked like:

...partway through designing (after double-clicking on TButton a lot)

..and after moving the buttons, renaming, and setting caption Text.

UI design: done, for the moment. It's simple and we're going to improve it in a later post. Now, onto code! Bad code.

Homework question

We built a completely normal scientific calculator interface. We’ve all seen them before - we implemented the standard physical desktop calculator, with a grid of buttons and a small text area at the top.

But is implementing the norm the best approach? Yes, because we know how to use it already, but what if there’s a better way? If you were to reinvent the calculator, what would it look like? Pretend you’re Steve Jobs in 2001 - maybe the calculator could be more obvious and more intuitive? I have some ideas about this myself and would be interested to read more in the comments.

Starting coding - the wrong way

This is where it all goes wrong, and you can immediately tell the difference between a newbie and someone who has some coding experience. The aim of this article is to jump you right past being a newbie into best practices immediately.

We’re really enthusiastic. We want to get some numbers up on screen. So, let’s start making buttons do stuff.  Double-click btnZero (this auto-creates its OnClick event; you can create other events in the Events tab of the Object Inspector) and write some code:

.
void __fastcall TForm1::btnZeroClick(TObject *Sender)
{
	edtResult->Text = L"0";
}

And repeat this for the other buttons. (What is the L prefix for the string? This was briefly covered in part 2; it indicates the string is a Unicode string - specifically, this is actually a string literal using wide characters, an array of wchar_t. There are lots of string types. This one is compatible with the Windows Unicode size and the VCL's String.)

Ok, now we can make the display have a number. But how do you enter a two-digit number? Hmm, maybe take what’s already there, assume it’s a number, and add in another digit:

.
void __fastcall TForm1::btnOneClick(TObject *Sender)
{
	edtResult->Text = IntToStr(StrToInt(edtResult->Text) * 10 + 1);
}

This is already convoluted - a bad sign.  It takes the text, makes it an integer, multiples it by ten (so 2 becomes 20) then adds 1 (so 2 -> 20 -> 21), then converts it back to a string and sets the text.

If you try that, it will crash if 1 is the first button you press, because the edit has no text and so can’t be converted to an int. So let’s fix that:

.
void __fastcall TForm1::btnOneClick(TObject *Sender)
{
	if (edtResult->Text.IsEmpty()) {
		edtResult->Text = L"1";
	} else {
		edtResult->Text = IntToStr(StrToInt(edtResult->Text) * 10 + 1);
	}
}

...but this needs to work for all buttons, so copy/paste to event handlers for all the others.

But wait, this needs to keep some kind of track of the operation, so it knows if this is the first or second number in, say, a “+” operation. So maybe store the text as a std::wstring field in the form…

Hold on, all ten number events have to be updated...

No. No no no. This is getting out of control: code is convoluted, confused, hacked together, mixing data types (why is a string holding a number?), and is duplicated.

What happened?

It all started so obviously: press a number, that number displays. Then it grew. Then we had to add some logic, and that did odd things with strings and integers, for what is really a number (so why is it ever a string?) Then the code got copied ten times, even though it varies only a tiny little bit between all ten. Then we realised we needed to keep track of state, so we started adding various state fields in the form as variables. What happens when we need to implement Plus or Minus? How will we do that?

It got really messy, really fast, even though it started off perfectly logically.

The problem here is one of clean design.  The form is the user interface - just that, the interface or graphics. Nothing else. We started trying to put calculator logic inside the form, mixing the UI and the calculations and state. That’s what led to a fundamental error like reading a number from a text field (the edit box) and to getting convoluted logic.

We started from the premise, “We have a UI; let’s make it do stuff”. That was the wrong premise, but it’s a really easy one to fall into when you have software that makes building a UI easy. The right premise is, “We have a UI, let’s connect it to something else that does stuff”.

There is a really important principle in app development, which is

Separate your user interface and logic

There are many ways to do this, most with acronyms (Presentation modelMVC, MVVM, YMMV (wait a second…), etc.)

Separating your user interface and logic means having several layers. Here we only need two: the user interface, and a calculator.

This all boils down to something else:

One class should have one purpose.

Here, the UI form (which is a class) should just be the UI: respond to button presses, display pretty stuff onscreen. That’s it. You want calculations? Have something that knows how to calculate - but doesn’t directly interact with the UI. That also means that the calculator doesn’t know about a TForm, per se - it just knows about some abstract presentation layer.

The nice thing here is that not only does this keep your code clean, but it means you can change any layer. Suppose you don’t want this to be a FireMonkey application, but you want it to be a command-line application (Linux support is coming in the next release!) If all your logic was in your UI, you’d be stuck with a huge rewriting job. As it is, if you have separate UI and logic layers with a clean interface between them, you can replace the form with a command-line interface that works exactly the same way. The moment your app is in a state where you can do something like that - even if you don’t need to right now - you know it’s well designed.

Starting coding - the right way

So, we need two layers: UI and calculator.

Clear out all the UI event code so we start clean. Then let’s think about how we want the two layers, UI and calculator, to talk to each other.

We actually don’t want the calculator to know it’s talking to a form - just a presentation or UI object of some kind. Similarly, the form can know it’s talking to “a” calculator but doesn’t need to know it’s this specific class or implementation. (We could replace the calculator layer as easily as we can replace the UI layer.)

The answer to this is to program to interfaces.

C++ doesn’t have interfaces as a language feature. Delphi does, and through our C++ compiler extensions you can use real genuine interfaces from C++, but we’ll stick to fairly pure C++ code in this series. C++ instead makes you use a class with pure virtual methods - that is, virtual methods that do not have an implementation. We’re defining a base class, but it is treated like an interface.

This is an excellent time to jump into some C++ syntax…

C++ class declarations

In C++, a class is declared with the “class” keyword, a name, and optional inheritance. Members go inside the braces. Methods have the type first, name second, as do variable.  Here’s an example:

.
class Foo : public Bar {
private:
	int m_Number;
public:
	virtual void DoSomething(int a, float b);
};

This declares a class called Foo, which inherits from Bar. (You’re probably familiar with visibility specifiers in a class declaration in other languages; C++ allows those for inheritance too. It’s an advanced feature, use public by default.)

Then it has a private int member variable, and a public method which returns nothing (void, it’s a procedure not a function) and has two parameters, the first an int and the second a float. It is a virtual method, meaning it can be polymorphically overridden in a descendant class.  Note the colons after “private” and “public”, and the semicolon after the class declaration (if you miss that, it actually expects a variable. Just keep the semicolon.)

Defining interfaces

Back to our interfaces. We want two: one that represents the UI or display layer, and one that represents the calculator itself. We’ll expand these as we add more features.

Create a new unit by right-clicking the project and selecting Add New > Unit - C++ Builder. Rename it “uInterfaces” and save.  The following we’re going to put in the header half of the unit. We could also just add a header file through File > New > Other.

The display

A calculator only displays one thing: a few characters of text. (Let’s keep it text, not a number, to let the calculator control how the number is shown. A UI prints text, it does not print a number.)

Add this to the top of the .h, inside the #ifndef, #define section, so the whole file looks like this:

.
#ifndef uInterfacesH
#define uInterfacesH

#include <string>

class ICalculatorDisplay {
public:
	virtual void UpdateUI(const std::wstring& strText) = 0;
};

#endif

See that “=0” at the end of the virtual method declaration? That says it has no implementation, or is “pure”. This is how it’s an interface; ICalculatorDisplay declares methods but leaves it to a descendant to implement them; through the magic of polymorphism you can refer to an ICalculatorDisplay and the behaviour is actually that of whichever derived class, or class implementing the interface, you actually have. (C++ has multiple inheritance, so implementing an interface is just inheriting from that pure virtual class and implementing the methods, as well as possibly inheriting from concrete classes as normal.) Read more about declaring an interface here including some quirks to do with destructors not in the simple example above.

Some more C++ syntax. “std::wstring” is the variable type. Here, “std” (pronounced exactly as it’s written, no vowels like “stad” or “stod” - it’s “std” or “st’d”) is the standard namespace. C++ defines a lot of useful things in this namespace usually referred to as the STL, or standard template library, except it contains a lot more than templates. The :: accesses something inside the namespace; :: is used for all scope identification like classes, too, so MyClass::MyMethod refers to the method itself. std::wstring is a wide string, which uses a character size compatible with Windows Unicode and FMX’s String type.

The #include statement includes the string header, which is part of the STL and is where std::wstring is defined. C++ has a very basic mechanism for units and for referring to other files. A logical unit is split up into code and a header, as mentioned in part 2. Instead of “using” or “referencing” another unit, it includes the header, and that means literally includes - to the compiler, the entire contents of the “string” header will be inserted at that location. All it does it let it know the classes and methods defined in the header should exist; it won’t actually check they exist, though, until it tries to use them, which means a header can contain lots of methods (say) that don’t exist but you won’t get an error until you link. This is also where the #ifndef part comes in - it means if a header is included twice, it will only actually be included the first time, because the second time around the macro is defined and so the preprocessor will skip the contents of the ifdef block.  You’re quite right, this is crazily basic for a language in 2016. A long-awaited feature, modules, may make it better in C++19.

Includes should be at the top of the file, whether it’s a .h or .cpp file. (You can include something anywhere, but this is good practice.)

The ampersand means it is a reference. A reference means you are accessing the object itself - the parameter here is not a string object but points to a string object somewhere else. Unlike a pointer, references are guaranteed to exist - they cannot be null - and you use them with syntax exactly like a normal non-pointer stack-allocated object, not like a pointer.

Const means the reference cannot be modified; you can only call const methods (methods that don’t mutate, or change, the object state) and you cannot set strText to be something else.

The calculator

After the ICalculatorDisplay declaration, still inside the #ifdef, add the following:

.
enum class eOperator {
	eEquals,
	eAdd,
	eSubtract,
	eMultiply,
	eDivide
};

class ICalculator {
public:
	virtual void AddDigit(const int Digit) = 0;
	virtual void AddDecimalSeparator() = 0;
	virtual void SetOperator(const eOperator Op) = 0;
};

The methods in ICalculator are self-explanatory. AddDigit is for when 0-9 is pressed; AddDecimalSeparator is for when you press “.” to start entering fractional numbers, and SetOperator is to define whether it should be using plus, minus, and so forth. We will expand this interface in the future - this is a rough draft.

You can see the skeleton of a better design appearing. The calculator has no knowledge of buttons or edit boxes and it’s going to look after all its own state. The form has no knowledge of the calculator’s internals, because it will refer just to this interface - the class implementing the interface could do anything and it won’t know or care.

We have some new syntax here, defining an enumeration.  Old C++ used the “enum” keyword; in C++11 you can use enum class; the differenceis basically better type safety, so enum will behave as you might expect it to behave if you’ve used other languages. This requires C++11, so at this point make sure you’ve gone into the project options, C++ Compiler, and turned off “Use classic Borland compiler” to make sure you use the new, modern, Clang-based compiler.

Finally, let’s actually implement these interfaces.

Implementing the interfaces

In the form

In the form header, change the form’s class declaration to look like this, multiply inheriting from both TForm and from the interface:

.
class TForm1 : public TForm, ICalculatorDisplay

Then we want to implement the interface. In the public: section of the form, copy the interface method, but remove the =0 because we want it to exist in the form:

.
public:		// User declarations
	__fastcall TForm1(TComponent* Owner);
	virtual void UpdateUI(const std::wstring& strText);

And implement it in the form. You’ve already seen implemented methods in the form of event handlers (which are just methods), so go ahead and implement an empty method in the form’s .cpp file like so:

.
void TForm1::UpdateUI(const std::wstring& strText) {
	//
}

You don’t need (and in fact can’t have) the virtual keyword on the implementation, only the declaration.

Creating the calculator

Add a new unit, and rename it to uCalculator. In the header, include the interface header file, define a class inheriting from ICalculator, and containing its methods as virtual but not pure any more - exactly as in the form. It should look like this:

.
#include "uInterfaces.h"

class TCalculator : public ICalculator {
public:
	TCalculator();
	virtual ~TCalculator();
public: // ICalculator
	virtual void AddDigit(const int Digit);
	virtual void AddDecimalSeparator();
	virtual void SetOperator(const eOperator Op);
};

I’ve added a constructor and destructor, too. These have the same name as the class, except the destructor is prefixed with ~. Note that this means a C++ class can have multiple constructors with different parameters, but because the constructor is indicated by it having the same name as the class, it cannot have multiple named constructors (CreateEmpty, CreateWithFoo, etc.)

I also separated and commented the methods that come from the interface vs those introduced in the class itself. This is personal preference.

On to the .cpp file, and copy the methods and implement. Note the method is declared with ClassName::MethodName syntax, following :: described earlier.  For the time being, leave the methods empty.

.
#include "uCalculator.h"


TCalculator::TCalculator() {

}

TCalculator::~TCalculator() {

}

void TCalculator::AddDigit(const int Digit) {

}

void TCalculator::AddDecimalSeparator() {

}

void TCalculator::SetOperator(const eOperator Op) {

}

What did we cover today?

Our calculator now has a UI and a calculator class. They're not aware of each other yet, but will be in the next lesson, where we'll hook the two together and implement the calculator class to start doing math. (Why not in this lesson? Because it moves on to many other things, such as smart pointers. Cool stuff - next week!)

This week we covered:

  • Editing properties in the UI designers
  • Code design considerations:
    • Separation of UI and logic
    • Separation of responsibility
  • C++ syntax:
    • Classes
    • Methods
    • Variables
    • Interfaces
  • C++ standard library:
    • What it is
    • One small part of it, std::wstring
  • Implementing classes
  • Multiple inheritance (briefly)
  • Plus links to other interesting topics

See you next week!

Setting a Tab Item Badge Value

$
0
0

I recently received some questions on how to display a circular badge icon and badge value on a tab item in TTabControl.

Badge icons are commonly set to indicate a status change. The number displayed on the badge is frequently tied to a local notification or a push notification that's been received.

For example, popular social media apps show a badge value on the Notifications tab to show the number of new comments that you've received on a post while email clients display a badge value on the Inbox tab to indicate the number of unread emails.

In today's post, I thought I would show you how to set the badge icon and value on a selected tab item. This works with both the default native styles as well as custom styles, including the styles that are part of the premium style pack.

This demo uses a client aligned TTabControl with 3 tab items. After enabling the switch, a badge icon is shown on the "badge item" tab, and you can increment the value.

 

Note: Since this is just a quick demo to illustrate how to increment the badge value, we are using TSpinBox, but it's recommended to use a TSpeedButton with the correct "stepper" styling when adding app navigation that allows the user to increase/decrease values. This is especially true for iOS to ensure you are adhering to Apple's UI guidelines.

Example:

 

You can also customize the fill color of the circle along with the font color:

 

Platform styling:

 

 

 

Custom UI Styling using one of the premium iOS styles:

 

Download the project here.

unit TabBadgeFrm;

interface

uses
  System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
  FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.TabControl, FMX.Controls.Presentation, FMX.Edit,
  FMX.EditBox, FMX.SpinBox, FMX.StdCtrls, FMX.Layouts, FMX.ListBox,
  FMX.NumberBox;

type
  TForm16 = class(TForm)
    TabItem1: TTabItem;
    TabItem2: TTabItem;
    BadgeItem: TTabItem;
    SpinBox1: TSpinBox;
    ToolBar1: TToolBar;
    Switch1: TSwitch;
    ListBox1: TListBox;
    ListBoxItem1: TListBoxItem;
    ToolLabel: TLabel;
    TabControl1: TTabControl;
    procedure BadgeItemPaint(Sender: TObject; Canvas: TCanvas; const ARect: TRectF);
    procedure SpinBox1Change(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure Switch1Switch(Sender: TObject);
    procedure StepperUpClick(Sender: TObject);
  private
    FBadge: Integer;
    FShowBadge: Boolean;
    procedure SetBadge(const Value: Integer);
    procedure SetShowBadge(const Value: Boolean);
    { Private declarations }
  public
    { Public declarations }
    property Badge: Integer read FBadge write SetBadge;
    property ShowBadge: Boolean read FShowBadge write SetShowBadge;
  end;

var
  Form16: TForm16;

implementation

{$R *.fmx}
{$R *.iPhone55in.fmx IOS}

procedure DrawBadge(Canvas: TCanvas; const ARect: TRectF; const Text: string;
  const Color: TAlphaColor = TAlphaColorRec.Red);
const
  Padding = 2;
  HorzTextMargin = 6;
  VertTextMargin = 4;
var
  R: TRectF;
  TextSize: TSizeF;
  Brush: TBrush;
  BadgeRadius: Single;
begin
  Canvas.Font.Size := 12;
  // Measure text width
  TextSize := TSizeF.Create(Canvas.TextWidth(Text), Canvas.TextHeight(Text));
  // Calculate badge rect
  R := TRectF.Create(0, 0, HorzTextMargin * 2 + TextSize.Width, VertTextMargin * 2 + TextSize.Height);
  if R.Width < R.Height then
    R.Width := R.Height;
  // Position rect
  R := TRectF.Create(ARect.Right - R.Width, ARect.Top, ARect.Right, ARect.Top + R.Height);
  R.Offset(-Padding, Padding);
  // Draw badge
  BadgeRadius := R.Height / 2;
  Brush := TBrush.Create(TBrushKind.Solid, Color);
  try
    Canvas.FillRect(R, BadgeRadius, BadgeRadius, AllCorners, 1, Brush);
  finally
    Brush.Free;
  end;
  // Draw text
  Canvas.Fill.Color := TAlphaColorRec.White;
  Canvas.FillText(R, Text, False, 1, [], TTextAlign.Center, TTextAlign.Center);
end;

procedure TForm16.BadgeItemPaint(Sender: TObject; Canvas: TCanvas; const ARect: TRectF);
begin
  if ShowBadge then
    DrawBadge(Canvas, ARect, FBadge.ToString);
end;

procedure TForm16.FormCreate(Sender: TObject);
begin
  FBadge := 1;
end;

procedure TForm16.SetBadge(const Value: Integer);
begin
  if FBadge  Value then
  begin
    FBadge := Value;
    BadgeItem.Repaint;
  end;
end;

procedure TForm16.SetShowBadge(const Value: Boolean);
begin
  if FShowBadge  Value then
  begin
    FShowBadge := Value;
    BadgeItem.Repaint;
  end;
end;

procedure TForm16.SpinBox1Change(Sender: TObject);
begin
  Badge := Trunc(SpinBox1.Value);
end;

procedure TForm16.StepperUpClick(Sender: TObject);
begin
  Badge := Trunc(SpinBox1.Value);
end;

procedure TForm16.Switch1Switch(Sender: TObject);
begin
  ShowBadge := Switch1.IsChecked;
end;

end.

 [DownloadButton Product='Delphi' Caption='Download a RAD Studio Trial Today!']

 

 

Overview Embarcadero Conference Brazil 2016

A RAD Server Story

$
0
0

RAD Server and Delphi saved our butts.  And by “butts”, I mean our whole business.

 

We’ve used Delphi since Delphi 2 in 1996.  Back then, we built a basic app for managing appointments in Doctor’s offices.  We call it DocOffice.  Over the years it grew to manage all kinds of things, including billing, insurance codes, the works.  We did well with it, deploying to a couple of thousand doctor’s offices.  

 

There were only three of us, and we built it and deployed it when the customer needed help getting set up.  It was pretty slick.  We architected things pretty well, using datamodules to hold our data access components.  We had InterBase on the back end (that always worked great and is a total no-brainer for a doctor’s office) and accessed it via InterBase Express.  Pretty straight-forward fat client/back-office server kind of application.  Customers loved it, and they gladly paid maintenance every year for the bug fixes and new features.  We grew slow and smart, and made a nice living.  

 

But a couple of years ago, our maintenance renewals started to drop.  Apparently a number of our customers were moving to a new, Internet based system called DocsOnline.  DocsOnline was a totally web based system with a cloud-based backend and a web front end.  Doctor’s offices could literally be up and running in a day.  They even had the audacity to offer a data migration service that would migrate our database data right to their cloud service.  

 

DocsOnline was a big wakeup call to us.  Revenue continued to drop, and we knew we had to do something.  The era of the Client/Server application was coming to an end, and we had our whole codebase invested in an application that was growing less and less attractive to new customers, not to mention our existing customers.  They were leaving in droves for a service that they didn’t have to manage and administer.   We provided excellent service and support, but why would a Doctor pay for a day of our time when DocsOnline was virtually maintenance free?  

 

So we started looking at our options.  We looked at ways to create an online client with a REST API backend.  There was node.js.  There were Java solutions.  There was .Net and WebAPI.  All were capable, but they all involved a re-write of our entire codebase, and that would literally take years.  We didn’t have that kind of time.

 

Just when we were at our wits end, we got a call from our Embarcadero sales rep, and she told us about a new product that they had -- RAD Server.  She told us that it was a REST API-based backend server that let us leverage our existing code.  Heck, it turns out that we had the ability to start with it right away with our Berlin Enterprise edition. (We make it a point to stay on the most current version of Delphi.)  Sure enough, I was able to build a basic REST API server in literally two minutes using the IDE wizards.  I saw the potential right away.  We jumped at the great deployment and maintenance offer the sales rep had, and were off to the races.

 

We got started the following Monday.  In just a few weeks we had designed our API and had the basics up and running.  Our datamodules converted right over to the RAD Server design almost untouched.  We were able to serve up our data as JSON without doing anything special at all.  

 

We contracted with a front-end Javascript developer who built our web client.  She had no trouble at all because all of our REST APIs were industry standards.  In a chunk of time measured in weeks, rather than in months or years, we had most of our service up and running.  We were able to start selling right away because the back-end running in the cloud was utterly simple to replicate, and we could get our customers up and running with a fairly familiar web client and all their data running in the cloud as well.  We were beating DocsOnline at their own game.  We even stole a few of our former customers back.  Nice.

 

We couldn’t have done it without RAD Server.   We literally leveraged large swaths of our code with almost no changes at all.  We didn’t have to learn any new languages, and learning REST was quite simple.  In other words, we got to use what we already know to build a modern, new tool to create an entirely different type of application that met the competition head on.

 

 

Like I said, RAD Server saved our business.  And our butts.  

InterBase Tips and Tricks: Quickly Get Up and Running on Windows, OS X, iOS, Android, and Linux

$
0
0

CodeRage XI is just around the corner. If you haven't registered yet you can sign up now. Productivity, Platforms and Performance is the theme for this year’s CodeRage conference. Featured in this article is an on demand replay of the "InterBase Tips and Tricks: Quickly Get Up and Running on Windows, OS X, iOS, Android, and Linux" session from CodeRage X.

Join Quinn Wildman (Senior Support Engineer) for this multi-platform adventure as we see just how many Operating systems we can get InterBase up and running on in just 1 session. With tips and tricks along the way, learn how the experts get InterBase running quickly on Windows, Mac OS X, iOS, Android and Linux.


[YoutubeButton url='https://www.youtube.com/watch?v=3zMfN0s7FX8']
 
 
[DownloadButton Product='Interbase' Caption='Don't have InterBase yet? Download it now.']

FireDAC Migration Made Easy: BDE, dbExpress, AnyDAC to FireDAC

$
0
0

CodeRage XI is coming up soon and it has some great sessions for you to check out. If you haven't signed up yet you can sign up now. The theme for this year’s CodeRage conference is Productivity, Platforms and Performance. In the mean time check out this great replay session from CodeRage X about FireDAC Migration Made Easy: BDE, dbExpress, AnyDAC and Non-Integrated FD to Full FireDAC.

Want to migrate your application to leverage FireDAC's power, simplicity and stability, but you get overwhelmed by all the manual code changes required? There are tools available to help you accomplish this tedious task, but we will show you a simple to use tool and a unified way to migrate from either the BDE, dbExpress, AnyDAC or early Non-Integrated FD to full-fledged FireDAC. You won't have an excuse anymore to migrate your old application!


[YoutubeButton url='https://www.youtube.com/watch?v=97oV-y2GwQQ']

Learn to program with C++Builder: #4, Real code and Useful C++: Ownership, smart pointers, styles, and optional values

$
0
0

Welcome! Last week we looked at the architecture of a simple calculator app, showing how to design an application well by separating the UI and logic, abstracting through interfaces, and ensuring each class had a single responsibility.  That's important stuff, stuff that many developers skip, and is really important. Now we've done that, though, we can dig into the actual code. Today's blog post is almost entirely code, and will introduce you to several very interesting C++ concepts and techniques.

Important note: We’re going to use Boost, the most common C++ library.  It’s available through GetIt and is large and it takes some time to install, so I’d suggest installing it while reading through this blog post.  Open the IDE, go to the Tools menu, GetIt Package Manager, type ‘boost’ into the Search field, and when it appears, install it. For the Clang-enhanced compilers, we ship Boost 1.55, and the same installer will install an earlier version (1.39) for the old, ‘classic’ compiler. You will need to restart the IDE afterwards.

Part I: Connecting the UI and calculator, and object ownership

The code as it stands has a form, an interface representing a UI that can display results which the form implements, an interface representing a calculator, and a skeleton calculator class implementing that interface.

There are a couple of changes to the interface from last week: Equals is not an operator, but an operation, so remove it from the enumeration of operations and add a method to the ICalculator interface: void Equals(); It doesn't need to return anything because it's just for the UI to tell the calculator that Equals was pressed: results are displayed through the ICalculatorDisplay interface.

The form and the calculator need to know about each other. However, also important is the concept of ownership - which object controls the lifetime of the other?  Here, the form is going to own the calculator, so the calculator will be created when the form is and be destroyed when the form is.

Ownership is important for several reasons:

  • Preventing memory leaks. You want an object to exist for only as long as it needs to exist. You don’t want it to be created and forgotten about (a leak) and you don’t want it to be created and kept around longer than required (wasted resources).
  • Clear program logic. Suppose the calculator object wants to ask the UI to print something, but it’s not sure if the UI exists or not. It will have to check if it has (say) a null pointer instead of a valid pointer before trying to access the UI. That doesn’t make sense; better for it to be guaranteed that the UI exists. If the form owns the calculator, the calculator knows that if it is alive, the UI is alive.
    Similarly, since the form needs the calculator object for its lifetime (if the form exists, someone might press buttons and do calculations) so it too knows that it can always access its calculator object without checks. A guarantee like that isn’t required - often it’s very valid for something to maybe not exist, and in fact we’ll examine several cases like that very shortly. However, strict and clear ownership makes the rules of what exists when clear, avoiding crashes or other bugs.

Let’s first look at the calculator. It is owned by the form, and if it exists, the form is guaranteed to exist, so we can give it a reference to the UI (the form, through an interface.)

Remember, a reference is like a pointer that is guaranteed to exist, and the syntax is like a normal object (eg foo.bar()) not like a pointer (which would be foo->bar()).

To avoid leaking details about the concrete implementation, rather than the interface, we’ll create it through a factory method, so add one to the uInterfaces.h and .cpp file.

In the header:

.
ICalculator* CreateCalculator(ICalculatorDisplay& Display);

and in the implementation:

.
#include "uInterfaces.h"
#include "uCalculator.h"

ICalculator* CreateCalculator(ICalculatorDisplay& Display) {
	return new TCalculator(Display);
}

It accepts a reference to the UI, and creates a calculator returning a pointer (it is created on the heap; the Type-asterisk syntax indicates the type it returns is a pointer to Type.)  Note that this hides the existence of the calculator class completely - the form never has to #include it.  That’s good design; things are abstracted behind interfaces and unaware of the actual implementations.  In the calculator class, add this constructor and store the member reference:

In the header:

.
class TCalculator : public ICalculator {
private:
	ICalculatorDisplay& m_Display;
public:
	TCalculator(ICalculatorDisplay& Display);
	...

and in the implementation:

.
TCalculator::TCalculator(ICalculatorDisplay& Display) :
	m_Display(Display)
{
}

 

Smart pointers

More interesting is the owning object and how it owns the calculator.

C++ allows raw pointers, and old C++ code often uses them liberally. They lead to problems:

  • You have a pointer. What has to delete it (free it) and when? How many other objects have a copy of this pointer, ie are relying on it not being freed/deleted? This is ownership and lifetime
  • You have a pointer. Is it valid? What if it was deleted, but never set to null - you have an invalid pointer where accessing it will crash. How do you know? This is validity

Smart pointers are an answer to these two problems. (Other languages solve it with automatic reference counting (ARC) or a garbage collector (GC); both these effectively rely on a reference count or discovering the number of active uses of an object. C++ allows you to refcount if you wish, but also to use other patterns.)

Smart pointers are classes which manage the lifetime of pointers. They own a pointer, and they delete it. Because you know how they behave, you can use them to own a pointer and have guarantees about its lifetime and validity. Normally, they take ownership when they are created, and delete the pointer (or decrement a refcount, etc) when they are destructed.  This is particularly useful for using them as members of a class - when the class destructs, the pointers it owns are automatically deleted (or refcount decremented) too - or stack-allocated in methods, because when the smart pointer goes out of scope it is destructed, it will automatically delete (or decrement a refcount) the pointer it owns.  There are two types in C++11:

  • shared_ptr. This keeps a count of how many places are accessing the pointer, and the pointer is only deleted once the last reference disappears and the reference count drops to zero. Use this when many objects need to refer to a pointer and the pointer’s lifetime can end when the last shared_ptr referring to it is destroyed.
  • unique_ptr. Only one owner of a pointer is allowed. When the unique_ptr is destructed, the pointer it owns is deleted.

What does this mean? It means you never use the delete (freeing) keyword in your code, and you never manually manage pointer lifetime.

Destruction vs deletion

What is the difference between destruction and deletion?

Deletion is when a pointer is deleted or freed.  That is, in the code:

.
Foo* foo = new Foo();
delete foo;

An object of class Foo is created on the heap, calling its constructor; a pointer is returned; that pointer is deleted, and that destroys the object calling its destructor.  That is, deletion is one mechanism to destruct and object.

What’s the other? Stack-allocated objects are destructed when they go out of scope. Consider this code snippet:

.
{
	Foo A; // A is created on the stack
	{
		Foo B; // B is created on the stack
		// code here. This might cause an exception, but that’s ok
		B.Hello(); // let’s use B
		// code here...
	} // B is destroyed at its scope end
} // A is destroyed at its scope end

A stack-allocated object has its storage space allocated at the point it is constructed, and it is destructed when it “goes out of scope”, that is, execution leaves the scope - the block { } - where it was created. It is not ‘deleted’, because it was not ‘new’-ed (allocated on the heap), but its destructor runs.

When an exception occurs, all stack-allocated objects are destructed as the exception is propagated upwards to its handler.  That means, provided that an scope-lifetime object does not throw an exception of its own when it is destructed, that you have a guarantee the destructor will always be called - either when execution normally moves on to more code, or when an exception is thrown. Either way, in the code snippet above, both B and A will have their destructor called.

RAII

This leads to a really neat trick called Resource Acquisition Is Initialization, which uses the destruction rules to make classes that look after resources and clean them up when they are no longer needed.  When it is created, it is given a resource (it acquires - takes ownership - as it is initialized) and when it is destructed, it cleans up that resource.

Consider some code that turns on a tap. You want to make sure the tap is always turned off, not matter what happens, otherwise you will be flooded. You can write a RAII object that takes a newly turned on water resource, and in its destructor turns it off:

.
class TapHandler {
private:
	Tap& m_tap;
public
	TapHandler(Tap& tap) : m_tap(tap) {}
	~TapHandler() { m_tap.TurnOff(); }
	const Tap& get() { return m_tap; }
}

It is created with a reference to a tap, and the destructor always turns the tap off.  That means that the lifetime of the tap being turned on can be given to an instance of this object:

.
Tap tap(CreateTap());
{
	TapHandler myTap(tap);
	myTap.get().TurnOn(); // Also tap.TurnOn(), same object
	throw std::exception(); // oh no!
	myTap.get().TurnToCold(); // never called
	myTap.get().TurnOff(); // never called
}

TurnToCold() will never be called, because an exception is thrown. But myTap’s destructor is run anyway, and the tap is always turned off.  Even if an exception had not been thrown, you could rely on the tap being turned off - you never needed to remember to code it, because you used a RAII object that always did it.

If you had used a TapHandler as a member of a class, then when an instance of that class was destroyed, because all its members are destroyed too, the turned on tap would be turned off.

You can do write RAII objects for any kind of resource - Windows GDI handles, network sockets, file handles… and pointers.

Back to smart pointers

A smart pointer is an example of a RAII object.  Unique_ptr only allows one owner of a pointer; shared_ptr keeps a reference count.  Both of them control pointer lifetime in different ways; both mean that will well-written, modern C++, you should never write the keyword ‘delete’ - never manually manage lifetime.

One other thing: pointer access semantics. When you have a pointer, you use the arrow operator to access a member field or method:

.
foo->bar();

For languages like Delphi which automatically dereference pointer access and would write the above as foo.bar() even though foo is heap-allocated, this seems unnecessary. (You can do this two ways: through the arrow operator foo->bar(), which is a synonym for dereferencing the pointer and using the dot operator: (*foo).bar().  The *foo dereferences; the brackets are required because of operator precedence. Use ->.)

A smart pointer is not heap-allocated (or shouldn’t be!) so you’d think you’d use the dot operator, but it has its own methods - in fact, you can directly access the raw pointer it holds with get(), for example:

.
unique_ptr<Bar> bar(new Bar());
bar.get(); // is a Bar*

Instead, the smart pointer uses operator overloading to provide a -> operator:

.
bar->Open();

Calls the Open() method on the pointer bar is managing.

So you have a pointer, and access it using pointer semantics.

Back to connecting the UI and calculator

The form should own the calculator. Managing this ownership should now be clear: we will use a unique_ptr member field in the form, so that when the form is destroyed, the pointer to the calculator will be deleted and the calculator destroyed too, all automatically. You don’t need to write any code in the destructor; deletion is automatic.

In the header for the form, add #include <memory> to be able to use the smart pointers, and in the form class declaration add:

.
private:	// User declarations
	std::unique_ptr<ICalculator> m_Calc;

And in the .cpp, change the constructor to initialize the unique_ptr with an instance of a calculator:

.
__fastcall TfrmCalculator::TfrmCalculator(TComponent* Owner) :
	TForm(Owner),
	m_Calc(CreateCalculator(*this))
{
}

 

Now, the form or UI owns a calculator, and its lifetime is managed; the calculator knows about the form / UI. There is no manual lifetime or memory management required, no delete (as you might call .Free; in other languages); it all Just Works.

When you want to access the calculator, you use pointer semantics:

.
m_Calc->AddDigit(5);

Part II: Connecting the UI

Time for a break from C++ language features, cool though they are.  Let’s finish the UI.

Overriding the font style

FireMonkey is a styled UI, and while it can use native controls on some platforms, it mimics the native look and feel very closely - hopefully identically - in other situations.  That includes the font, where the styles for each platform specify the right platform font for button text, label text, and so forth.  But for the calculator, we want to override this and use a larger font for each button and the edit box, so each button has a large caption and the calculator entry and result has large text.

To do this, select all the controls.  (You can select one by clicking and then holding Shift while clicking others to multiselect, or click and drag a rectangle on the form.)  The Object Inspector will show the properties that are shared by the buttons and edit, and that includes the TextSettings property. Expand it by clicking the + sign, then again on the plus next to Font, and find the Size property.  Set it to 30.

The font size changed, but what happened? Scroll up, and you’ll see the StyledSettings property has changed (it’s non-default, indicated by bold text.) Expand it, and you’ll see that the Size item is not in the set of options.  The buttons and edit text are now drawing using their assigned style font, but overriding the font size set in the style. You can see the effect by clicking the checkbox next to Size on and off; it toggles between the style font size and the one you set. 

Experimenting with styles

Styles are a really useful part of the FMX UI framework.  Not only do they allow your applications to match the look and feel (and behaviour) of controls on any platform, and using system fonts is an example, but they also contain presets for a wide variety of difference but common alternatives. A button, for example, has many slight variations depending on how it’s used. Select just a button, and then find the StyleLookup property in the Object Inspector and click the dropdown arrow. Note how many different presets there are, such as ‘refreshtoolbutton’ for a tool button (one where the border becomes visible when you mouseover) with a Refresh icon. You can add your own, too.

However, clear the StyleLookup property since for the calculator, we want our buttons to look like standard buttons and show the Text we set as a caption.

Complete style changes

You can change a FMX app’s style completely.  Drop a TStyleBook on the form from the Tool Palette, and double-click it.  In the style designer tab that opens, click the Merge button, and navigate to ‘C:\Program Files (x86)\Embarcadero\Studio\18.0\Redist\styles\Fmx’. Open any style, such as ‘Blend’. Then, right-click the Style Designer tab and select close, and apply changes.

Back on the form, make sure the form’s StyleBook property is set to StyleBook1. The form will now have a completely different style.

You can load as many styles into the stylebook as you want, through its Styles list, and change them at runtime. (The Style Designer also lets you modify styles for any element. For example, a panel is normally represented by a rectangle, but it could be a roundrect or any shape or colour you want.)

However, for the time being delete the style book, which will revert to the default Windows platform style.

Connecting the UI

UI events

First, let’s connect up the operators. Select the Add button, and either double-click it, or in the Object Inspector’s Events tab, double-click the blank dropdown for the OnCreate event.  An event handler will be generated in the form.  Fill it in like so:

.
void __fastcall TfrmCalculator::btnAddClick(TObject *Sender)
{
	m_Calc->SetOperator(EOperator::eAdd);
}

Repeat this for the other operator buttons.  For the Equals button, call the calculator’s Equals method, and similarly for the decimal place button.

But what about the numbers? We could have a separate event handler for each, and repeat the same code, modified for each one.  But code duplication is bad style.  Instead, let’s make a single event handler for all buttons.  Select them all, then in the Events tab of the Object Inspector, type a name in the blank space next to OnClick - for example, type ‘btnNumberClick’, and press Enter.  An event handler will be created, and all buttons will use the same handler.  Fill in the code to add a digit:

.
m_Calc->AddDigit(0);

Obviously we need to change this depending on which button was pressed, and the Sender parameter holds that information: it is the object associated with the method, a TObject since event handlers with this signature aren’t limited to just buttons.

You could do this via a large if statement: if Sender is btnOne, call AddDigit(1), else if Sender is btnTwo… but this is messy.  We would gain very little.

FMX controls can have a data payload attached, called a tag, as a property.  There are several propreties: Tag, an integer; TagFloat, a floating-point number; TagString, a string; and TagObject, a TObject pointer, allowing you to associate almost anything.

In the Object Inspector, find the Tag property for each button and set it to match the button’s number - for example, set btnZero’s Tag property to 0, btnFive’s Tag property to 5, and so on. Now the event handler needs only a single line of code:

.
m_Calc->AddDigit(dynamic_cast<TButton*>(Sender)->Tag);

Dynamic cast is C++’s polymorphic type casting operator.  (In Delphi, this would be ‘Sender as TButton’.)  TButton is a descendant of TObject, so you can cast Sender to a TButton* and that cast will succeed if it is in fact a TButton. (It might not be.)  Once it is, we can access the Tag property.  (In fact, Tag is introduced a few levels up, so you could cast to TFmxObject.)

A dynamic cast will return nullptr if the cast fails, and accessing the Tag could then cause an access violation. Make sure you are certain of your types - or check. Here, we know that this event handler will only be called with a button as the Sender.

Display

The display interface has a method defined, UpdateUI, which is in the form but empty.  Fill it in to make the edit box display the text:

.
void TfrmCalculator::UpdateUI(const std::wstring& strText) {
	edtResult->Text = strText.c_str();
}

The edit’s Text property is String, while strText is the C++ standard wide string, but you can assign one to the other through the c_str() method returning a C-style character array pointer.

The UI is now fully hooked up to the calculator.  The calculator is given digits and operators, and the form can display a string by the calculator.

Part III: Entering a number

The final part of today’s post is to allow the user to enter a number, and to display that onscreen.

You can update the UI by calling m_Display.UpdateUI(std::wstring), but scattering calls to that throughout the calculator would be bad design - one method might update it with some text, some with another. What is better is to have a single place that is responsible for updating the UI that figures out what to display based on the calculator’s current state.

Add a private void method UpdateUI() in the header and implement it in the calculator. Until we have a number, this will display nothing.

.
void TCalculator::UpdateUI() {
	m_Display.UpdateUI(L"");
}

We’ll fill in that method later.

Entering a number

The calculator is told when the user presses a digit, but it needs to assemble those digits into a number. How? The first thing to realise is that accumulating digits is not a calculator’s responsibility - a calculator is really only responsible for doing calculations.  Separating responsibilities, and making a class only do one thing, leads to clear, concise, and understandable code.

Given that, let’s define a new class to accumulate digits, that we can query for a number.  Define this in the header:

.
class Accumulator {
private:
	int m_Whole;
public:
	Accumulator();
	int Value() const;
	void AddDigit(const int Digit);
};

This defines a class which stores an integer number, can be queried for that number, and can have a digit appended to that number.

Give the calculator a member variable:

.
class TCalculator : public ICalculator {
private:
	ICalculatorDisplay& m_Display;
	Accumulator m_Accum;
	void UpdateUI();

And initialise it in the constructor:

.
TCalculator::TCalculator(ICalculatorDisplay& Display) :
	m_Display(Display),
	m_Accum()
{
}

We can now fill in the AddDigit method to defer to this object to build the number, and update the UI:

.
void TCalculator::AddDigit(const int Digit) {
	m_Accum.AddDigit(Digit);
	UpdateUI();
}

Finally, the UI can display whatever the accumulator has got:

.
void TCalculator::UpdateUI() {
	m_Display.UpdateUI(std::to_wstring(m_Accum.Value()));
}

This uses the to_wstring method that converts an integer to a string.

Let’s fill out the accumulator class.  It’s pretty simple: initialises the number it has to 0, returns that number in the Value() method, and in AddDigit, adds that digit. That part is also simple: if the accumulator has the value 1, and the user presses 2 to turn that into 12, we just multiply the current accumulated value by ten and add the digit.

.
Accumulator::Accumulator() :
	m_Whole(0)
{}

int Accumulator::Value() const {
	return m_Whole;
}

void Accumulator::AddDigit(const int Digit) {
	m_Whole = m_Whole * 10 + Digit;
}

Things to note:

  • The constructor can initialise a list of all member variables; here we just have one, m_Whole
  • What does the ‘const’ mean after the method name, in ‘int Accumulator::Value() const’? It means that the method does not change the state of the object. This is useful for optimization and more.
  • Why ‘whole’? Because currently we only support entering an integer, or whole, number. We really want to enter a real number, a floating point number.  How are we going to do this?

If you run the app, you should now be able to type in a number and see the screen update to display it.

Handling the decimal point and introducing boost::optional

The logic for appending a digit to a integer or whole number is simple. But doing the same to the fractional side of a number is not quite so easy.

Let’s examine the basic method.  Keeping the whole part a separate number, we can track the fractional part as another integer, and append the digit the same way.  We can convert the integer to a fraction (123 to 0.123) later.  To do this, we split the append-digit logic away to another method, and call it on either the whole or fractional member variable depending on if the decimal point has been pressed. How do we track that? Keep state; add a boolean member and when the decimal point is pressed, pass that from the calculator to the accumulator.

However, how do we keep track of leading zeroes?  How do we tell the difference between 0 as no value, and 0 as something to keep and transform to ‘01’? How do we represent that in an integer, anyway?  You can’t.  Assuming we keep the fractional value as a number, we need to track the number of leading zeroes separately.  This is rapidly becoming messy.  It’s not going to be as simple as the integer whole number was, but we can simplify it.

First, let’s expand to keep track of the whole and fractional parts separately; to store if the user has pressed the ‘.’ button or not (if they are entering the fractional part); and add a digit to the appropriate half.

Extend the header to add a int m_Frac value; change Value() to return a double (a 64-bit floating-point type), add a method SetEnteringFraction to flag that the user is now typing into the fractional side, and change AddDigit to use it.  We’ll also, for reasons we’ll get to later, change Value() to get the value of the whole and fractional parts through a getter method for each.  Right now they will just return the member variable, but these will change soon.  You should end up with something like this (only the implementation shown):

.
Accumulator::Accumulator() :
	m_Whole(0),
	m_Frac(0),
	m_EnteringFraction(false)
{
}

double Accumulator::Value() const {
	return Whole() + Frac();
}

double Accumulator::Whole() const {
	return m_Whole;
}

double Accumulator::Frac() const {
	// Todo: fill in logic here
}

void Accumulator::SetEnteringFraction() {
	m_EnteringFraction = true;
}

int Accumulator::InternalAddDigit(const int& Value, const int Digit) {
	return Value * 10 + Digit;
}

void Accumulator::AddDigit(const int Digit) {
	if (m_EnteringFraction) {
		m_Frac = InternalAddDigit(m_Frac, Digit);
	} else {
		m_Whole = InternalAddDigit(m_Whole, Digit);
	}
}

The secret to the fractional value, ie turning 123 into 0.123, lies in calculating its magnitude (tens, hundreds, etc) and dividing it by that amount, which is ten to the nth power. log10(123) will give 2, whereas we want 3, to divide by 10^3 = 1000, because 123 / 1000 = 0.123.

Thus, the method looks like:

.
double Accumulator::Frac() const {
	if (m_Frac != 0) {
		return m_Frac / pow(10, floor(log10(m_Frac) + 1));
	}
	return 0.0;
}

This is the most complicated part of the whole blog series :)

This avoids doing the logarithm with a value of 0, or dividing 0 by a value, returning 0 in this situation as a fallthrough.

Now you can enter a complete, decimal-point-separated number by digits individually.  But we still haven’t addressed how to handle leading zeroes.  Let’s keep a count of them (we’ll address when to know a 0 is a leading zero in a moment), so the above line becomes:

.
return m_Frac / pow(10, floor(log10(m_Frac)) + m_FracLeadingZeroes + 1);

(Make sure you initialise the count of leading zeroes to 0 in the constructor.)

But how do we tell the difference between m_Frac being ‘not entered’, so 0 is a leading 0, and for legitimately holding a value?  Because we track leading zeroes, we can assume if m_Frac is not equal to 0, it’s a valid value.  But this logic is obscure - someone reading the code later might wonder what’s going on.

Optionals

What if there was a way to track if a variable genuinely held a value, or was empty?

In C# or Delphi, this is called a ‘nullable type.’ In C++, we use a boost template called ‘optional’. An optional may, or may not, have a value, and you can check if it does.  And while you could implement the accumulator without using them, using them makes the state clear and provides a very nice demonstration - important because we’re going to use them in a much more essential place next blog post.

Hopefully you installed boost at the beginning of this post; it takes a while. The Boost library has a vast variety of useful classes and methods; optional is just one.

An optional is declared like so:

.
boost::optional<int> m_Frac;

and has the following features:

  • Can be constructed with or without a value: m_Frac() does not have a value; m_Frac(0) has a value of 0
  • Can be reset to not hold anything: m_Frac.reset();
  • Can be checked if it has a value in an if statement, as a bool: if (m_Frac) { … } is true and goes into the body of the if only when the optional holds a value; if (!_Frac) { … } will enter the loop if the optional does not have a value.
  • Can get the value it holds - if it has one - through pointer semantics, specifically being dereferenced: int i = *mFrac;

Does this look familiar?  It’s very similar to a smart pointer, and a smart pointer, although we introduced it as a way of controlling lifetime, is also conceptually something that may have a value (a pointer) or may not (nullptr).

Include <boost/optional/optional.hpp>, and change m_Frac to boost::optional<int> m_Frac; The constructor should also be changed to initialise it as ‘m_Frac()’, ie without a value, because the accumulator starts off without the fractional part having a value.

AddDigit() can now check if it’s counting leading fractional zeroes like so:

.
if (Digit == 0 && !m_Frac) {
	++m_FracLeadingZeros;
} else { ...

If the fractional part has no value, and the user entered 0, it must be a leading zero. The else statement will add the digit as normal.

"++" here increments the value by 1. ++i is a preincrement, and i++ is a postincrement; the difference lies in evaluating.  If i has the value 1, j = ++i gives j a value of 2, and i of 2 (i is incremented first, ‘preincrement’); but j = i++ gives j a value of 1 and i a value of 2 (i is incremented second, ‘postincrement’). Pre- and pos- refers to evaluation. How often do you need this? Most often in loops, but modern C++ rarely loops via integers. It’s a holdover from C. The above code could be written either way.

The Frac() method can check if there is a fractional value and return 0.0 if not, and should get the value by *m_Frac.  Finally, since we want to avoid duplicating code, the AddDigit method now has to add a digit to either an int or a boost::optional<int>; change the whole number to an optional too, because it is valid for it not to have a value yet. It's very valid for it not to have a value: the user might go straight to entering the fraction, and while 0 is a valid value in this case, this code is meant to demonstrate optional<>. Remember to initalise it to empty, and to check if it has a value when returning its value in Whole().

Putting it all together, we get the following accumulator class:

.
Accumulator::Accumulator() :
	m_Whole(),
	m_Frac(),
	m_FracLeadingZeros(0),
	m_EnteringFraction(false)
{
}

double Accumulator::Value() const {
	return Whole() + Frac();
}

double Accumulator::Whole() const {
	if (m_Whole) {
		return *m_Whole;
	}
	return 0.0;
}

double Accumulator::Frac() const {
	// Convert an integer like 123 to 0.123
	// Magnitude can be calculated via log10
	// log10(123) -> 2, +1 -> 3
	// pow(10, 3) -> 1000
	// 123 / 100 = 0.123
	// Note leading zeroes - handle separately
	if (m_Frac && (*m_Frac != 0)) {
		return *m_Frac / pow(10, floor(log10(*m_Frac) + m_FracLeadingZeros + 1));
	}
	return 0.0;
}

void Accumulator::SetEnteringFraction() {
	m_EnteringFraction = true;
}

int Accumulator::InternalAddDigit(const boost::optional<int>& Value, const int Digit) {
	// Add a digit to the number. If it doesn't exist, the number is the digit
	if (Value) {
		return *Value * 10 + Digit;
	} else {
		return Digit;
	}
}

void Accumulator::AddDigit(const int Digit) {
	if (m_EnteringFraction) {
		// Leading zeroes won't get added, mathematically (to enter 1.00001, for
		// example, InternalAddDigit will multiply by 10 and add 0.) Track separately
		if (Digit == 0 && !m_Frac) {
			++m_FracLeadingZeros;
		} else {
			m_Frac = InternalAddDigit(m_Frac, Digit);
		}
	} else {
		m_Whole = InternalAddDigit(m_Whole, Digit);
	}
}

You can now enter a decimal fractional number.  Is using optional<> overkill here? Possibly, because it could be implemented another way, but it is clear - you can see when a variable may or may not have a value. The bit I don’t like is the logic to count the leading zeroes in AddDigit - the if statements are too nested and starting to become unclear. That logic could mostly be moved to InternalAddDigit, but the leading zero count should only occur if we’re dealing with the fractional part.  It works, but it is not as simple as I would like. Suggestions are welcome.

Overview

What have we covered this week? A lot:

  • C++:
    • Ownership: being clear what owns and is responsible for freeing what resources
    • RAII: Resource Acquisition Is Initialisation, a key C++ technique
    • Smart pointers, memory management using RAII
    • That modern C++ never uses the delete keyword: never manually manage memory
  • FireMonkey:
    • Styles
    • Overriding style elements
    • Importing completely new styles
    • Connecting event handlers and attached data to controls
  • C++ again:
    • The Boost library
    • boost::optional<>, one of many useful classes, and the concept of an optional or nullable type and (perhaps over-)use of it
    • Some math (the most complicated bit of this whole blog series!)
  • Putting it all together, a class that accumulates key presses to have optional whole and fractional parts of a number, returning the whole thing as a floating-point number

Next week, we pause for CodeRage! (Register for three free days of great C++ and Delphi content.) The week following, we examine operators (implementing addition, subtraction etc with small classes), moving a number from the accumulator to a left or right operand, and putting it all together - including a more accurate or important use of optionals - into a functioning calculator.

 


Learn to program with C++Builder: Homepage

$
0
0

Do you want to learn C++, but don't know where to begin? This series takes you through from the very beginning, assuming you have some programming knowledge but know no C++ at all, and show you how to build a real-world, useful application, demonstrating UI and logic design principles, the basics of C++, and useful classes and methods, ie a great overview of the areas you need to know about in order to confidently write well-designed modern C++.

If you are

  • a hobbyist who’s done some programming but never used C++ (or Delphi) before,
  • a student,
  • or a professional who wants to learn something new,

this five-part series is for you.

1. Introduction and Installation

Introduction to the series and what it will cover, followed by installing C++Builder to get you ready to make an app.

2. Building and Debugging

Making your first app, and running it. Then an overview of how to solve problems - how to debug, and how to use the debugging tools in C++Builder.

3. Design, Architecture, and UIs

How do you build an app well? How do you design an app so it makes sense, will have few bugs, and the code clear and understandable? Good design and architecture principles are discussed and then applied in practice, in code. The calculator app is starting to take shape. Then, the UI is built and there's a quick discussion of the UI layer and what you can achieve with it.

4. Real Code and Useful C++: Ownership, smart pointers, styles, and optional values

Let's dig into some great C++! Fundamentals about scope and RAII - and what that is - followed by smart pointers and a really neat class from the Boost library, boost::optional (a kind of nullable type.) The UI and calculator are connected and typing numbers starts making numbers appear onscreen. In addition, there's more about what you can achieve with the UI layer and styling.

5. To be written

C++-style object orientation with operand classes, and the calculator is complete! Then, moving it to mobile - making the same app run on Windows, iOS and Android.

 

We have a similar series for Delphi! Check out Pawel's five-part series on learning Delphi, written in parallel with this C++ one.

Deep Dive Into Manual Creation, Templates, Frames, And Sub-Components Of Composite Delphi VCL Controls

$
0
0

This CodeRage X replay session investigates the various techniques involved in creating composite controls including manual creation, component templates, frame components, and sub-components. Along the way, guidelines for the effective use of each technique will be presented along with the advantages and disadvantages of each approach.

The session is by Ray Konopka who is the president and founder of Raize Software, an Embarcadero Technology Partner providing high-quality, innovative developer tools since 1995. Ray is the creator of CodeSite and the Konopka Signature VCL Controls (formerly called Raize Components). He is also the author of the highly acclaimed Developing Custom Delphi Components books, a co-author of several other Delphi books, and has published numerous articles on software development. Ray specializes in user interface design, custom component development, and mobile solutions. An engaging presenter, Ray is an Embarcadero MVP and a frequent speaker at developer conferences.

Ray will also be presenting a session in CodeRage XI which is coming up soon. You can register for CodeRage XI right now and get access to all kinds of new sessions themed around Productivity, Platforms and Performance.


[YoutubeButton url='https://www.youtube.com/watch?v=emPh3_UBg-I']

FireMonkey sessions at CodeRage next week

$
0
0

CodeRage XI is next week. It's going to be a great, multi-day event. CodeRage XI is the largest, free online conference of the year from Embarcadero Technologies. As part of this year's event, we have more great sessions planned on multi-device development. This includes my FireUI Deep Dive webinar.

As part of my session, I will show how to create a custom style for a control using Photoshop and the Bitmap Style Designer.

 

View the schedule here.  My session is on Thursday, November 17th at 2 pm Pacific time.

 

 

 

 

 

 

Learn To Setup And Configure SSL & TLS For RAD Studio EMS, DataSnap, REST And Web Services

$
0
0

This replay session by Robert Love from CodeRage X will cover how to establish secure communication channels using with EMS, DataSnap, Rest, Web services, and raw Indy Sockets. It covers using SSL & TLS, OpenSSL, SSL with Indy, SSL with IIS, and how to configure ISAPI with SSL. It also covers older versions and which versions are vulnerable to POODLE. There is a demonstration of creating a self signed certificate in OpenSSL.

The next CodeRage is right around the corner and you can signup now to access all of the latest sessions in CodeRage XI. The theme this year is Productivity, Platforms and Performance. It runs from November 15-17, 2016. Be sure to check out all of the upcoming sessions and select which ones you might be interested in attending. After each session there is a live question and answer with the presenter of the session. Don't miss it!


[YoutubeButton url='https://www.youtube.com/watch?v=BMbub3QszcE']

Deferring C++ Rename Refactoring from 10.1 Berlin Update 2

$
0
0

 

A couple of weeks ago, we discussed a feature planned for the upcoming Update 2 of C++Builder 10.1 Berlin, C++ rename refactoring. This feature allows you to right-click on any identifier in your C++ code, and rename it throughout the project.

Unfortunately, we have had to defer the feature from Update 2. After having shared the potential feature with the community, this is sure to be a disappointment to you, as well as to us. I’d like to share with you why, and also give you some good news about when to expect it.

Very late in testing Update 2, we identified two critical bugs in rename refactoring. Both of these were to do with some complex situations including when the file was in a specific encoding on disk but converted to UTF8 by the editor, or other situations where encodings changed from one encoding to another, and resulted in code corruption: the replacement of an identifier with the new name could occur at the wrong location in code, offset by a few characters.

This left us in a difficult situation: should we delay releasing Update 2 by potentially a couple of weeks, or instead defer the feature?

The bug itself is relatively straightforward, but the matrix of situations in which it can and can not occur, and its effects each time, is complex. We were not confident that a quick fix would reliably address the issue.

Quality is important, and so we chose to ensure that we address the issue robustly and release the feature certain of its quality. That meant we deferred it from Update 2.

Good news

We were only able to do this because licenses are now under update subscription. Update subscription allows us to release features throughout the year, instead of having a single major release followed only by bugfixes. This means any feature that misses one release is a candidate for the next, and all update subscription customers will get the feature. Rename refactoring will be in the next release.

On a side note, as you may know, C++Builder is coming to Linux!  We plan to have a public beta of the C++ support quite soon, to which all update subscription customers will be invited.

David Millington

C++ Product Manager

Viewing all 182 articles
Browse latest View live




Latest Images