Categories
Source Code webinar

FireDAC: Local SQL

Here are the additional resources for the FireDAC: Local SQL Skill Sprint from this morning. The TFDLocalSQL provides a powerful engine allowing you to run local SQL queries against any TDataSet descendant.

Here is the video replay. It is about half Q&A and half presentation.

If you want to download my sample application: LocalSQL-demo

Slides:

FireDAC Local SQL Skill Sprint from Jim McKeeth

The demo and full replay are coming soon.

DocWiki

Videos

 

 

Categories
Source Code webinar

FireDAC In-Memory DataSet: TFDMemTable

More information and resources on TFDMemTable from the FireDAC Skill Sprint.

If you missed the Skill Sprint, or want to review it, here is the video with the recording of the Q&A. The presentation is 15-20 minutes, and the other 30 minutes is from the Q&A.

Here are the slides for now, the replay will be available soon.

FireDAC Skill Sprint: In-Memory DataSet – TFDMemTable from Jim McKeeth

Common code samples:

Delphi / Object Pascal

// Create Field Definitions
FDMemTable1.FieldDefs.Add('ID', ftInteger, 0, False);
FDMemTable1.FieldDefs.Add('Name', ftString, 20, False);
FDMemTable1.CreateDataSet;

// Append data
FDMemTable1.Open;
FDMemTable1.AppendRecord([1, 'Jim']);

// Load from another DataSet
FDMemTable1.CopyDataSet(DataSet1, [coStructure, coRestart, coAppend]);

C++

// Create Field Definitions
FDMemTable1->FieldDefs->Add("ID", ftInteger, 0, False);
FDMemTable1->FieldDefs->Add("Name", ftString, 20, False);
FDMemTable1->CreateDataSet();

// Append Data
FDMemTable1->Open();
FDMemTable1->Append();
FDMemTable1->FieldByName("ID")->AsInteger = 1;
FDMemTable1->FieldByName("Name")->AsString = "Jim";
FDMemTable1->Post();

// Load from another DataSet
FDMemTable1->CopyDataSet(DataSet1, TFDCopyDataSetOptions() << coStructure << coRestart << coAppend);

More information:

  • Samples
    • C:\Users\Public\Documents\Embarcadero\Studio\15.0\Samples\Object Pascal\Database\FireDAC\Samples\Comp Layer\TFDMemTable
    • C:\Users\Public\Documents\Embarcadero\Studio\15.0\Samples\Object Pascal\Database\FireDAC\Samples\Comp Layer\TFDLocalSQL
  • DocWiki

Cary Jensen’s CodeRage 9 Video: TFDMemTable & ClientDataSet Compared [Q&A Log]

Dmitry Arefiev’s CodeRage 9 FireDAC Tips, Tricks and News

Categories
Android Funny iOS Source Code Video podCast

Code Monkey in Delphi Code

In this special musical number I’ve created a music video based on Jonathan Coulton’s Code Monkey written in Delphi’s Object Pascal.

[Download the code] [Download the video (mp4)]

Categories
Source Code

Deep Dive into Futures and the Parallel Programming Library

To follow-up with my Parallel For Loops skill sprint last week (lots of good resources there), today I did a deep dive into the Parallel Programming Library (PPL) including Futures, Tasks and custom thread pools.

Here are the slides:

Deep Dive into Futures and the Parallel Programming Library from Jim McKeeth

And you can download my Tasks and Futures sample to see how to create, start, check and cancel both Tasks and Futures. Check out the C++ Parallel Examples to see how to use Futures and the PPL in C++.

Until the replay of my Skill Sprint is posted, you can watch this video from Allen Bauer covering the Parallel Programming Library Architecture from CodeRage 9.

Be sure to sign up for and check out the other Skill Sprints.

Categories
Source Code

Factorials, Combinations & Permutaions

This is some code I wrote a long time ago as part of the TDAG mailing list. It calculates Factorials, the number of Combinations and Permutations. This is the mathematics, it calculates the number of Combinations and Permutations, it doesn’t create each different Combination and Permutation.

They take Cardinals as parameters because it doesn’t make sense to accept negative numbers. Keep in mind that factorials get big really, really quickly, so if you use too large of numbers then it will overflow even the Int64.

unit FactCombPerm;

interface

// Parameters are Cardinal because Int64 isn't Ordinal
//  Besides, Factorial(100) will overflow Int64 already.
function Factorial(const ANumber: Cardinal): Int64; overload;
function Factorial(const ANumber: Cardinal;
                   const AStop: Cardinal): Int64; overload;
function CombinationUnOpt(const ACount, AChoose: Cardinal): Int64;
function Combination(const ACount, AChoose: Cardinal): Int64;
function Permutation(const ACount, AChoose: Cardinal): Int64;

implementation

function Factorial(const ANumber: Cardinal): Int64; overload;
// n! = n * (n-1) . . . n(2)
var
  lCtr: Cardinal;
begin
  Result := 1;
  for lCtr := ANumber downto 2 do
    Result := Result * lCtr;
end;

function Factorial(const ANumber: Cardinal;
                   const AStop: Cardinal): Int64; overload;
// Factorial with a stop point (needed in the optimized Combination routine
// if no AStop is specified then is the same as Factorial
var
  lCtr: Cardinal;
begin
  Result := 1;
  if ANumber >= AStop then
    for lCtr := ANumber downto AStop do
      Result := Result * lCtr;
end;

function CombinationUnOpt(const ACount, AChoose: Cardinal): Int64;
// n!
// n_C_k = ----------
// k!(n - k)!
begin
  if AChoose < ACount then
    Result := Factorial(ACount)
      div (Factorial(AChoose) * Factorial(ACount - AChoose))
  else
    Result := 0;
end;

function Combination(const ACount, AChoose: Cardinal): Int64;
// n!
// n_C_k = ----------
// k!(n - k)!
// with optimizations even!
begin
  if AChoose < ACount then
    Result := Factorial(ACount, succ(ACount - AChoose))
      div (Factorial(AChoose))
  else
    Result := 0;
end;

function Permutation(const ACount, AChoose: Cardinal): Int64;
// n!
// n_P_k = --------
// (n - k)!
begin
  if AChoose < ACount then
    Result := Factorial(ACount)
      div Factorial(ACount - AChoose)
  else
    Result := 0;
end;

end.

My original optimization had a bug in it, but Bryan Mayland fixed it for me. This is old code, and there are probably some options to optimize it better. I’d love input, suggestions, etc.

Categories
Android Architecture iOS Mobile Source Code

Parallel For Loops

Parallel For Loops are a hassle-free way to supercharge your program with the Parallel Programming Library. The syntax is similar to the standard For loop, with the advantage of each iteration running on in a different task on the thread pool. This allows multiple iterations to run at the same time, taking advantage of the multi-core and hyper-threaded architecture common on laptops, desktops and mobile devices today.

Here is the replay of the Skill Sprint:

Here are the slides:

Parallel For Loops with the Parallel Programming Library from Jim McKeeth

Update: I was chatting with Allen Bauer today and he mentioned that while you technically can use Queue and Synchronize from within a Parallel For loop, he wouldn’t recommend it because it will dramatically reduce the speed of the loop. It is still faster than a linear loop, but not as fast as it could be. I’ll leave these examples here, but keep that in mind when optimizing your parallel code.

Here is the syntax in Object Pascal. The stride is the first parameter is it is optional. It controls how the iterations are grouped when being sent to the CPUs. Min and Max are your usual start and stop range for the loop. The last parameter is an anonymous method that represents the code to be executed on each iterations. It takes an Index parameter that is either an Integer or Int64 that provides the value of the current iteration.

TParallel.For(Stride, Min, Max, procedure (Idx: Integer)
begin
  if IsPrime(Idx) then
  begin
    TInterlocked.Increment (Tot);
    TThread.Queue(TThread.CurrentThread, procedure
    begin
      Memo1.Lines.Add(Idx.ToString);
    end);
  end;
end);

Here is the C++ code syntax. It takes a event instead of an anonymous method.

// . . .
TParallel::For(NULL, Min, Max, MyIteratorEvent);
// . . . 

void __fastcall TFormThreading::MyIteratorEvent(TObject *Sender, int AIndex)
{
	if(IsPrime(AIndex)){
		TInterlocked::Increment(Tot);
	};
}

There are some great blog posts and videos on the Parallel Programming Library

Stephen Ball has a series of blog posts on the Parallel Programming Library, including a Quick Introduction and one on managing the thread pool. As Stephen points out, while you can customize the thread pool, that doesn’t alway mean you should. Malcolm Groves also has some great blog posts on PPL.

Danny Wind has a great Code Rage 9 session on the Parallel Programming Library (be sure to download his samples). David I. did the C++ version.

Allen Bauer, our Chief Scientist, also has a CodeRage 9 session on the PPL Architecture.

If you want to take advantage of the new C++11 Lambda syntax on Win64 and mobile, then check out this community article or watch this CodeRage 9 video snippet. Get Bruneau and David’s code for C++ and Parallel libraries.

Update: Keep in mind that a Parallel For loop isn’t always the best performance option, but it is really easy to use. Check out Stefan Glienke’s Stack Overflow answer for an alternative using the PPL TTask for even better performance.

Categories
Source Code

Run Outside the Handler or Making a Non-Blocking Call

Have you ever had some code you wanted to run outside of the event handler that causes the code to run? If not, then this blog post isn’t for you. I’m not here to debate why you would want to do that, or if it is a good idea or not. I just know there’ve been times I’ve needed my code to run outside the event handler, or just a bit later.

One use case example: You are calling a slow routine (Network I/O maybe) and don’t want to freeze the UI while you wait for it to execute.

Still with me? Good. What I used to do was drop a TTimer on the form and set the Interval to 1, then enable it to trigger the code to run later. This worked, but it was messy. You had a timer to deal with, and you had to remember to disable it in the event handler, so it didn’t run multiple times. You also could have used a TThread, which may have been a better solution, but still seemed kind of messy, especially if you wanted to update the UI from your code.

Thanks to the new System.Threading library introduced with XE7, I’ve created a simple procedure that makes this a breeze to do. I call the procedure NonBlocking, but you could just as easily call it RunALittleLaterRunOutsideHandler, etc.

uses System.Threading;

procedure NonBlocking(const Proc: TThreadProcedure);
begin
  TTask.Create(procedure begin
    TThread.Queue(nil, Proc);
  end).Start;
end;

All this does is create a task, and then inside the task queue an update back to the main thread to execute the code that is passed to this procedure as an anonymous method. You could easily just write this code inline, but I thought it worthwhile creating a procedure to handle it for me.

Lets look at a normal execution scenario:

  //...
  ListBox1.Items.Add('Before Handler');
  EventHandler;
  ListBox1.Items.Add('After Handler');
  //....

procedure TForm1.EventHandler;
begin
  ListBox1.Items.Add('Inside Handler');
end;

When this is run, our ListBox1 will look like

  • Before Handler
  • Inside Handler
  • After Handler

which is what we would expect. Now when we introduce a call to our new procedure in the EventHandler:

  //...
  ListBox1.Items.Add('Before Handler');
  EventHandler;
  ListBox1.Items.Add('After Handler');
  //....

procedure TForm1.EventHandler;
begin
  ListBox1.Items.Add('Inside Handler 1');
  NonBlocking(procedure begin
    ListBox1.Items.Add('Outside Handler'); // This will run last
  end);
  ListBox1.Items.Add('Inside Handler 2');
end;

Our ListBox1 will look like

  • Before Handler
  • Inside Handler 1
  • Inside Handler 2
  • After Handler
  • Outside Handler

Notice that Outside Handler was the very last line added, even though it is written between Inside Handler 1 and Inside Handler 2. It even occurs after the After Handler line. Also, this works across all platforms: iOS, Android, Windows and OS X.

Everything before and within the call to NonBlocking will execute in order, but the code within NonBlocking will execute after the code that comes after that anonymous method.

If you have a ShowMessage or something else that blocks the UI thread in the event handler, then the code you passed to the NonBlocking procedure will be executed early, which is fine since the UI thread was already blocked.

 

Categories
Android Source Code

Hello Moto 360 from Delphi XE7

Moto 360I really like my Moto 360 watch. It looks fabulous, and does great as an extension of my Android phone, but of course the most important question is how to make an app for it. Turns out it just works with RAD Studio X7, Delphi or C++. Thanks to the new FireUI Multi-Device designer I can actually create a custom view in the UI to make designing the perfect user interface a breeze. Here are some of the details of what I discovered along the way, followed by a download of my sample and the custom view.

The bottom line is it just works, which really isn’t a surprise. Most new Android devices use ARMv7 and the NEON instruction set. (NEON is kind of like the MMX standard on the Intel platform. At first not everyone used those instructions, but once they caught on, everyone did.) So it is no surprise that the Moto 360 does too. Unlike some of the other watches, the Moto 360 does not have a micro USB port. So you have to use ADB over BlueTooth. This requires a few extra steps to setup, and is really slow to deploy over. So slow I canceled the first two deployments because I thought I set something up wrong.

First of all, the Moto 360 display is not perfectly round. It has a flat area on the bottom. If you look closely you can see the light sensor there. Not sure if that was why it wasn’t round, or if there was another design reason. In any case, the screen resolution is 320 x 290 pixels at 213 Pixels Per Inch. This means at design time you have a usable area of 240 x 218 pixels. This is the information we need to create a custom view. Just put the following code in a package.

  TDeviceinfo.AddDevice(TDeviceinfo.TDeviceClass.Tablet, ViewName,
    // The Moto360 is 320x290 phyiscal and 240x218 logical with 213 PPI
    TSize.Create(320, 290), TSize.Create(240, 218),
    TOSVersion.TPlatform.pfAndroid, 213,
    True); // Exclusive

The Device class enumeration actually has a Watch class, but looking in the code that detects the class at runtime and it doesn’t know how to detect a watch yet. So it defaults to Tablet. It makes sense if you think about the fact that XE7 was released before the Moto 360. I imagine an update will address this.

The requirement to get the custom view to show up in the IDE is you need to update the XML file found at %AppData%\Roaming\Embarcadero\BDS\15.0\MobileDevices.xml to reference the new view. Inside the MobileDevices element, add the following:

  <MobileDevice>
    <Displayname>Moto360</Displayname>
    <Name>Moto360</Name>
    <DevicePlatform>3</DevicePlatform>
    <FormFactor>2</FormFactor>
    <Portrait Enabled="True" Width="240" Height="218" Top="102" Left="29" StatusbarHeight="0" StatusBarPos="0" Artwork="C:\Users\jim\Documents\Embarcadero\Studio\Projects\HelloMoto360\Moto360.png" />
    <UpsideDown Enabled="False" Width="240" Height="218" Top="0" Left="0" StatusbarHeight="0" StatusBarPos="0" Artwork="" />
    <LandscapeLeft Enabled="False" Width="240" Height="218" Top="0" Left="0" StatusbarHeight="0" StatusBarPos="0" Artwork="" />
    <LandscapeRight Enabled="False" Width="240" Height="218" Top="0" Left="0" StatusbarHeight="0" StatusBarPos="0" Artwork="" />
  </MobileDevice>

You’ll need to update the path to that Artwork to point to the correct location of the PNG on your system. Or you can just leave it blank. Here is what it all looks like when setup in the IDE.

Hello Moto 360 in the XE7 IDE

You’ll notice a red circle on the design surface. I added this to see where the corners are (since the display is round). At runtime you can just barely see the red if you hold the watch right. In production I’d hide this at runtime. I placed the TCircle at -1, -1 and set the size to 242 x 242. This way the circle follows the bezel and not the display area of the screen. I suppose if I bumped it out another pixel it would disappear completely at runtime.

To get the Moto 360 to show up as a target device you first need to enable Bluetooth debugging.

  1. Hold the side button in until Settings appears
  2. Swipe down to About and tap it.
  3. Tap on build number until it tells you that you are a developer.
  4. Swipe back to settings and then tap on Developer options.
  5. Tap on ADB Debugging until it says Enabled.
  6. Tap on Debug over Bluetooth until it says Enabled.
  7. On your paired phone, go into Android Wear settings (gears in the upper right)
  8. Enable Debugging over Bluetooth.
    1. It should show
      • Host: disconnected
      • Target: connected
    2. Target is the watch, Host is your computer.

Then you connect your phone that is connected to the Moto 360 via USB and run the following commands (assuming ADB is on your system path) to connect via Bluetooth. I made a batch file.

 @echo off
 REM optional cleaning up
 adb disconnect localhost:4444
 adb -d forward --remove-all
 REM this is the connection
 adb -d forward tcp:4444 localabstract:/adb-hub
 adb -d connect localhost:4444
 REM these lines are to see if it worked
 echo Here is the forwarded ports . . . .
 adb forward --list
 echo.
 echo Wait a second for it to connect . . . .
 pause
 adb devices

The ADB Devices list should show something like

List of devices attached 
123456abcd device 
localhost:4444 device

Now the Android Wear app on your phone should show

  • Host: connected
  • Target: connected

Be sure that your Moto 360 app uses the unit that defines the Moto 360 device (from your package). This way your app can select it at runtime. If you do all that, you’ll see something similar to this with it running on the Moto 360:

Hello Moto 360 from Delphi XE7

My camera had a hard time focusing on it, but rest assured it looks fabulous! I tried C++ too, and no surprises, it works as well. More experimenting to do, but it is nice to know I have a tool that will take me everywhere I want to go.

If you don’t have a Moto 360, you can setup an Android emulator (AVD) instead. I did that before mine showed up. You need to download the Android 4.4W (API20) SDK Platform and ARM System image.

Android Wear SDK Download

Then create an AVD with the new Emulator.

Android Wear AVD Settings

It actually gives you the rectangle screen with a round bezel. Also it is 320 x 320 (so completely round) and 240 PPI. This means the view I created (since it was exclusive) won’t work on the emulator. You’ll need to create a new custom view for the emulator, but I’ll leave that up to to.

you can download all of my code for the custom view, Bluetooth ADB batch file, and sample apps from Github. (Update: Added a view for Galaxy Gear Live & LG-G) BTW, XE7 adds local Git support, which is another great new feature. Download the trial and check it out.

Categories
Android iOS Mobile REST Source Code webinar

Mobile Summer School 6: REST & BaaS

Here are the slides and downloads from my mobile summer school session on REST & BAAS. If you just want the slides they are on Slide Share. I’ll post the video and more details here later.

For more information on BaaS, check out Sarina’s excellent series of blog posts.

Categories
Mobile Source Code webinar

Mobile Summer School Lesson 5: App Tethering Round-Up

I substituted for David I. yesterday for Developer Direct Mobile Summer School on Lesson 5: Connecting Mobile and Desktop together using App Tethering. The Summer School landing page and David’s blog maintain a list of downloads for all the previous lessons, but here are the resources from my session in the meantime.

I’ll post the replay videos here when they are available too.

You can download my slides and code samples from Code Central. I believe I fixed the issue where some people were not able to download it.

cc.embarcadero.com/item/29907

Here are the links to more information on App Tethering:

Here is the Developer Skill Sprint I did previously on App Tethering

And this is Al Mannarino’s C++ Mobile Day session on the topic

And some blog posts on the topic too:

There was some interest in the code sample that bypasses App Tethering’s autodiscovery to connect directly to a specific IP address. I’m working on getting that tested before posting it. Leave a comment if you are interest and I’ll see that you are notified when it is ready.