Planet Object Pascal

May 25, 2013

The road to Delphi

Hosting Preview Handlers in Delphi VCL Applications

In this post i will show you, how you can host an existing Preview Handler in your Delphi VCL App. Preview handlers are a lightweight and read-only preview of a file contents that are bound to a the preview pane window of the explorer or a another window, all this is done without launching the file’s associated application.

The Preview Handlers was introduced in Windows Vista and are used mainly by the Windows Explorer and other applications like MS Outlook. Hosting an existing preview handler in your application will able to display a preview of most major office document formats, media files, CAD files and so on.

To host a preview handler, first we need find the CLSID of the preview associated to a file extension, this info is located in the windows registry, the default value of the {8895b1c6-b41f-4c1c-a562-0d564250836f} subkey is the class identifier (CLSID) of the handler. An example of the extfile ProgID subkey is shown here, associating a handler of CLSID {11111111-2222-3333-4444-555555555555}.

HKEY_CLASSES_ROOT
   extfile
      shellex
         {8895b1c6-b41f-4c1c-a562-0d564250836f}
            (Default) = [REG_SZ] {11111111-2222-3333-4444-555555555555}

So you can wrote a method like this to get the CLSID of the preview handler associated to a file.

function GetPreviewHandlerCLSID(const AFileName: string): string;
var
  LRegistry: TRegistry;
  LKey: String;
begin
  LRegistry := TRegistry.Create();
  try
    LRegistry.RootKey := HKEY_CLASSES_ROOT;
    LKey := ExtractFileExt(AFileName) + '\shellex\{8895b1c6-b41f-4c1c-a562-0d564250836f}';
    if LRegistry.KeyExists(LKey) then
    begin
      LRegistry.OpenKeyReadOnly(LKey);
      Result:=LRegistry.ReadString('');
      LRegistry.CloseKey;
    end
    else
      Result := '';
  finally
    LRegistry.Free;
  end;
end;

Now with the proper CLSID we can create an instance the IPreviewHandler interface

var
    FPreviewHandler : IPreviewHandler;
begin
  ...
  ...
  FPreviewHandler := CreateComObject(LPreviewGUID) As IPreviewHandler;

The next step is determine how the preview handler was implemented using a IInitializeWithStream.Initialize, IInitializeWithFile, or IInitializeWithItem interface and then call the proper Initialize method.

  if FPreviewHandler.QueryInterface(IInitializeWithFile, LInitializeWithFile) = S_OK then
    LInitializeWithFile.Initialize(StringToOleStr(FFileName), STGM_READ)
  else
  if FPreviewHandler.QueryInterface(IInitializeWithStream, LInitializeWithStream) = S_OK then
  begin
    LFileStream := TFileStream.Create(FFileName, fmOpenRead);
    LIStream := TStreamAdapter.Create(LFileStream, soOwned) as IStream;
    LInitializeWithStream.Initialize(LIStream, STGM_READ);
  end
  else
  if FPreviewHandler.QueryInterface(IInitializeWithItem, LInitializeWithItem) = S_OK then
  begin
    SHCreateItemFromParsingName(PChar(FileName), nil, StringToGUID(GUID_ISHELLITEM), LShellItem);
    LInitializeWithItem.Initialize(LShellItem, 0);
  end;

Finally we need to call the SetWindow (passing the proper host window handle and TRect) and the DoPreview methods of the IPreviewHandler interface.

I encapsulate all the above code in a component called THostPreviewHandler and this is the source code.

{**************************************************************************************************}
{                                                                                                  }
{ Unit uHostPreview                                                                                }
{ component for host preview handlers                                                              }
{                                                                                                  }
{ The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); }
{ you may not use this file except in compliance with the License. You may obtain a copy of the    }
{ License at http://www.mozilla.org/MPL/                                                           }
{                                                                                                  }
{ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF   }
{ ANY KIND, either express or implied. See the License for the specific language governing rights  }
{ and limitations under the License.                                                               }
{                                                                                                  }
{ The Original Code is uHostPreview.pas.                                                           }
{                                                                                                  }
{ The Initial Developer of the Original Code is Rodrigo Ruz V.   Copyright (C) 2013.               }
{ All Rights Reserved.                                                                             }
{                                                                                                  }
{**************************************************************************************************}

unit uHostPreview;

interface

uses
  ShlObj,
  Classes,
  Messages,
  Controls;

type
  THostPreviewHandler = class(TCustomControl)
  private
    FFileStream     : TFileStream;
    FPreviewGUIDStr : string;
    FFileName: string;
    FLoaded :Boolean;
    FPreviewHandler : IPreviewHandler;
    procedure SetFileName(const Value: string);
    procedure LoadPreviewHandler;
    procedure WMSize(var Message: TWMSize); message WM_SIZE;
  protected
    procedure Paint; override;
  public
    property FileName: string read FFileName write SetFileName;
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
  end;


implementation

uses
 SysUtils,
 Windows,
 Graphics,
 ComObj,
 ActiveX,
 Registry,
 PropSys;

constructor THostPreviewHandler.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  FPreviewHandler:=nil;
  FPreviewGUIDStr:='';
  FFileStream:=nil;
end;

procedure THostPreviewHandler.Paint;
const
  Msg = 'No preview available.';
var
  lpRect: TRect;
begin
 if (FPreviewGUIDStr<>'') and (FPreviewHandler<>nil) and not FLoaded then
 begin
  FLoaded:=True;
  FPreviewHandler.DoPreview;
  FPreviewHandler.SetFocus;
 end
 else
 if FPreviewGUIDStr='' then
 begin
   lpRect:=Rect(0, 0, Self.Width, Self.Height);
   Canvas.Brush.Style :=bsClear;
   Canvas.Font.Color  :=clWindowText;
   DrawText(Canvas.Handle, PChar(Msg) ,Length(Msg), lpRect, DT_VCENTER or DT_CENTER or DT_SINGLELINE);
 end;
end;

destructor THostPreviewHandler.Destroy;
begin
  if (FPreviewHandler<>nil) then
    FPreviewHandler.Unload;

  if FFileStream<>nil then
    FFileStream.Free;

  inherited;
end;

function GetPreviewHandlerCLSID(const AFileName: string): string;
var
  LRegistry: TRegistry;
  LKey: String;
begin
  LRegistry := TRegistry.Create();
  try
    LRegistry.RootKey := HKEY_CLASSES_ROOT;
    LKey := ExtractFileExt(AFileName) + '\shellex\{8895b1c6-b41f-4c1c-a562-0d564250836f}';
    if LRegistry.KeyExists(LKey) then
    begin
      LRegistry.OpenKeyReadOnly(LKey);
      Result:=LRegistry.ReadString('');
      LRegistry.CloseKey;
    end
    else
      Result := '';
  finally
    LRegistry.Free;
  end;
end;

procedure THostPreviewHandler.LoadPreviewHandler;
const
  GUID_ISHELLITEM = '{43826d1e-e718-42ee-bc55-a1e261c37bfe}';
var
  prc                   : TRect;
  LPreviewGUID          : TGUID;
  LInitializeWithFile   : IInitializeWithFile;
  LInitializeWithStream : IInitializeWithStream;
  LInitializeWithItem   : IInitializeWithItem;
  LIStream              : IStream;
  LShellItem            : IShellItem;
begin

  FLoaded:=False;
  FPreviewGUIDStr:=GetPreviewHandlerCLSID(FFileName);
  if FPreviewGUIDStr='' then exit;

  if FFileStream<>nil then
    FFileStream.Free;

  LPreviewGUID:= StringToGUID(FPreviewGUIDStr);

  FPreviewHandler := CreateComObject(LPreviewGUID) As IPreviewHandler;
  if (FPreviewHandler = nil) then
    exit;

  if FPreviewHandler.QueryInterface(IInitializeWithFile, LInitializeWithFile) = S_OK then
    LInitializeWithFile.Initialize(StringToOleStr(FFileName), STGM_READ)
  else
  if FPreviewHandler.QueryInterface(IInitializeWithStream, LInitializeWithStream) = S_OK then
  begin
      FFileStream := TFileStream.Create(FFileName, fmOpenRead or fmShareDenyNone);
      LIStream := TStreamAdapter.Create(FFileStream, soOwned) as IStream;
      LInitializeWithStream.Initialize(LIStream, STGM_READ);
  end
  else
  if FPreviewHandler.QueryInterface(IInitializeWithItem, LInitializeWithItem) = S_OK then
  begin
    SHCreateItemFromParsingName(PChar(FileName), nil, StringToGUID(GUID_ISHELLITEM), LShellItem);
    LInitializeWithItem.Initialize(LShellItem, 0);
  end
  else
  begin
    FPreviewHandler.Unload;
    FPreviewHandler:=nil;
    exit;
  end;

  prc := ClientRect;
  FPreviewHandler.SetWindow(Self.Handle, prc);
end;

procedure THostPreviewHandler.SetFileName(const Value: string);
begin
  FFileName := Value;
  HandleNeeded;
  LoadPreviewHandler;
end;

procedure THostPreviewHandler.WMSize(var Message: TWMSize);
var
  prc  : TRect;
begin
  inherited;
  if FPreviewHandler<>nil then
  begin
    prc := ClientRect;
    FPreviewHandler.SetRect(prc);
  end;
end;

end.

And you can use it in this way

  FPreview := THostPreviewHandler.Create(Self);
  FPreview.Top := 0;
  FPreview.Left := 0;
  FPreview.Width  := Panel1.ClientWidth;
  FPreview.Height := Panel1.ClientHeight;
  FPreview.Parent := Panel1;
  FPreview.Align  := alClient;
  FPreview.FileName:=FileName;

This is a sample image of a preview handler hosted in a VCL Application.

previewhost

You can download the sample application (XE2) from here.


by Rodrigo at May 25, 2013 12:16 AM

May 24, 2013

PARMAJA

New slogan for some open source projects

1- Keep the code as it.
2- Your patch is welcome, but maybe we will not accept it
3- Send your patch, and bless for it.
4- If you hate it dont use it.
5- Write once, Compile any where, is it work?

by Zaher Dirkey at May 24, 2013 05:37 PM

The Wiert Corner - irregular stream of stuff

jpluimers

Every once in a while an AV in Delphi manifests itself in a very odd way.

Usually it is refactoring, code completion or any of the ‘insight’ features doing odd things.

This time, it got me into a Product or License Validation Error | General:

Product or License Validation Error

Your Embarcadero product or license can’t be validated.

If you see this page when you’re using a valid license and official version of the software, please submit an installation support case for further assistance.

If you need a trial license and official trial software download, visit our Trial Downloads page.

To purchase a product license and receive a certified download, please see our How to Buy page.

Too bad the error hard-quits Delphi, thereby loosing all your work since the last save. Even more reason to safe often.

None of the reasons mentioned in Starting Delphi or C++ Builder results in Product or License Validation Error applied.

Restarting Delphi XE2 solved the problem.

–jeroen


Filed under: Delphi, Delphi XE2, Development, Software Development

by jpluimers at May 24, 2013 08:06 AM

Andreano Lanusse | Technology and Software Development

Android Studio preview – The new Google IDE is out

Last week at Google I/O, Google announced the Android Studio, their new Android development environment based on IntelliJ IDEA.

Android Studio is FREE and can download the early preview version here. I just installed on my Mac, the IDE supports Windows and Linux as well. I played a little bit during the last 2 days and I’m very impressed.

Today’s Android development is supported in Eclipse through the ADT (Android Development Toolkit plugin), and every developer can take advantage of the Eclipse ecosystem. I have been using Eclipse for Android development, but certainly I see space for improvement and more specific features related to Android development.

Android Studio is built on top of IntelliJ’s community version and now with Google Engineer working on that, just imagine what they will be able to produce. I just played few hours with Android Studio, their source code editor ROCKS it goes beyond of features already applied in other IDEs, the Designer is awesome and gives you a view of your application not only for one device, but for many others include tablets. Also, you can easily import your projects from Eclipse in to Android Studio.

Android Studio

Android Studio multi device preview

Watch the following video and you will have a pretty good idea about what I’m talking about.

That’s it for now.

Andreano Lanusse | Technology and Software Development
Follow me on Twitter: @andreanolanusse

by Andreano Lanusse at May 24, 2013 02:54 AM

May 23, 2013

Andy's Blog and Tools

How to install JCL and JVCL for XE4

As the JCL and JVCL transition from Sourceforge to GitHub isn’t finished yet (JCL already on GitHub, JVCL still on Sourceforge) you have to do some extra work to get a working XE4 version. There is no official release that you could download. Also the “jedi.inc” sub project on Sourceforge isn’t updated to XE4 but the new https://github.com/project-jedi/jedi is. Unfortunately, the JVCL has the old jedi.inc as an svn:external, causing the JVCL’s svn head to have an outdated jvcl/common/jedi/jedi.inc that must be replaced by the updated one.

Here is a example command line “script” that you can use to install the JCL and JVCL.

git clone git://github.com/project-jedi/jcl.git jcl
cd jcl
git submodule init
git submodule update
cd ..

svn co https://jvcl.svn.sourceforge.net/svnroot/jvcl/trunk/jvcl jvcl
copy /Y jcl\jcl\source\include\jedi\*.inc jvcl\common\jedi

cd jcl\jcl
install.bat

cd ..\..\jvcl
install.bat
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

 

by Andreas Hausladen at May 23, 2013 10:38 PM

Behind the connection

Programmer picks: 7 must-try mobile dev tools

InfoWorld has selected Embarcadero RAD Studio XE4 in his slideshow about mobile dev tools. Established companies like Intel and Embarcadero Technologies, as well as lesser-known players are continually rolling out technologies to help meet mobile developers' needs. Read the full article at: http://www.infoworld.com/slideshow/101586/programmer-picks-7-must-try-mobile-dev-tools-218867#slide6

by François Piette (noreply@blogger.com) at May 23, 2013 08:07 PM

The Wiert Corner - irregular stream of stuff

jpluimers

So I won’t forget:

delphi – How to distinguish flash drives? – Stack Overflow.

In that answer, Dan C talks about VID / PID (Vendor ID and Product ID) and how to get some of the serials without WMI.

–jeroen


Filed under: Delphi, Delphi XE3, Development, Software Development

by jpluimers at May 23, 2013 05:00 AM

May 22, 2013

The Wiert Corner - irregular stream of stuff

jpluimers

On my research list (Thanks Uwe!): DataSnap in the Cloud – DelphiFeeds.com.

It shows you how to do DataSnap from the Azure clound, including getting some of the default Delphi database demos to work on SQL Server (erm, SQL Azure).

–jeroen


Filed under: Delphi, Delphi XE, Delphi XE2, Delphi XE3, Development, Software Development

by jpluimers at May 22, 2013 05:00 AM

May 21, 2013

Behind the connection

Internet Explorer Automation Part 4

I this article, I will explain how to extract statistics from Blogger stats page. This follows the previous article in which you learned how to automate the login process and get the stats page. The stats page is organized in a number of HTML elements. The one which is interesting for us is a table. Since there are many tables in the page, I had to find out a way to detect the correct one, even

by François Piette (noreply@blogger.com) at May 21, 2013 02:00 PM

The Wiert Corner - irregular stream of stuff

jpluimers

One of the things you must be careful with is reentrancy in your application through a message loop.

The most obvious way is Application.ProcessMessages: it will loop until all messages from the Windows message queue are processed, whether your application is ready for them or not.

A less obvious way is because of modal dialogs or forms. They have their own message loop which might cause global reentrancy in your application (for instance through TTimer objects).

That was the case for this problem: stack overflow with repeated DispatchMessageW in the call stack.

A couple of ways to try to avoid these issues:

  • Don’t cause a secondary message loop.
    You can refrain from calling Application.ProcessMessages, but you cannot always avoid modal dialogs.
  • Protect each of your event handlers by disabling the path to it as soon as it gets called.
    This means disabling the Enabled property for instances of TTimer, TControl, TAction, or other objects that cause events.

–jeroen

via: windows – stack overflow with repeated DispatchMessageW in the call stack – Stack Overflow.


Filed under: Delphi, Development, Software Development

by jpluimers at May 21, 2013 05:00 AM

May 20, 2013

Behind the connection

Pascal still an advantage for some iOS, Android developers

Just read this article. It could also interest you so I share it: http://www.zdnet.com/pascal-still-an-advantage-for-some-ios-android-developers-7000014743/ Follow me on Twitter Follow me on LinkedIn Follow me on Google+ Visit my website: http://www.overbyte.be

by François Piette (noreply@blogger.com) at May 20, 2013 07:40 PM

Firebird News

10th FDD – Subscriptions are open!

The site of the Firebird Developers Day’s 10th edition is now up and running. Interested people can already subscribe on-line to the conference.Spread the news and come to comemorate the 10th anniversary of the biggest Firebird Conference in the world. PS: FDD is a Brazilian conference for the Portuguese speakers community.

by Cantu at May 20, 2013 02:41 PM

May 19, 2013

TPersistent

Time to Jump into the Delphi Pond?

If you’re a new developer and you’re wondering what development tool to adopt you have to decide what pond you want to play in. Don’t be suckered by the vendor offering free conferences, and trial development tools. Don’t “go with the flow” and choose the most popular tool because no one ever got fired for choosing it. If you do, it doesn’t say much for your critical thinking capabilities. You will be competeing with every Tom, Dick and Harry out there who is doing the exact same thing. There may be plenty of jobs, but the pay rates are driven down by the market. If you have mobility and travelling around the world appeals to you, then consider a small technology pond. One like Delphi, that is a pleasure to work with, and has a devoted following. Employers are finding it more difficult to acquire qualified staff, and are willing to offer more to good candidates and do more to retain them. You can work throughout the world for good rates, when going with a more mainstream technology, employers will choose local resources. It’s also becoming more common place to telecommute, if that is your goal.

Now don’t get me wrong, I am not saying bet your livelihood on a niche technology. I am saying position yourself with technologies (note the pluralization) so you can maximize the revenue generated from their use. That generally happens on the bleeding edge, and the twilight years. Talk to any Cobol developer about the kind of money you can make on a technology in it’s twilight years. Talk to any SAP consultant about the kind of money they make in a niche technology, and then ask your average .NET developer about the rates they get. Talk to any Objective C developer who made a fortune on the iPhone boom. Get the picture?

As a developer you should know at least two languages you can make a living with. This mitigates the risk of one of them being a niche technology, and protects you from shorter term market fluctuations. The exposure to different techniques also makes you a better developer. Today, choosing a mobile platform is likely as important as choosing a web platform was 10 years ago. As technologies converge, it’s important to have exposure to both web and desktop. Picking a platform that supports both reduces the number of languages and technologies you have to be fluent with.

Delphi offers a long history of backwards compatibility, and significant popularity (read lots of code to maintain). It’s community members are often as zealous as Apple fans and are very helpful to newies. Delphi offers many of the same features as newer languages, and has support for web, mobile and desktop to varying degrees. If FireMonkey and Embarcadero’s mobile efforts succeed, developers could experience “bleeding edge” type results in what would otherwise be a product’s twilight years.

As a niche product, or if you are an aspiring ISV, I think Delphi is worth serious consideration.

by Larry Hengen at May 19, 2013 06:45 PM

May 17, 2013

DelphiTools.info

LLVM for DWScript

DragonMediumVery experimental support for LLVM in DWScript is now in the googlecode repository, thanks to the efforts of Christian-W Budde.

This is the beginning of the opening of new realms of possibilities for DWS!

LLVM support is currently centered around jit compilation, and at the moment doesn’t extend much beyond the needs of the Mandelbrot demo (see below for what is supported right now).

LLVM CodeGen vs dwsJIT

Note that it is a different effort from the recently announced JITter for DWS, the TdwsJIT is a simple greedy just in time compiler, which works on the same structures as the interpreter, and where a goal is that jitting should be lightweight and fast enough to be applied all the time. It’s a “cheap” boost to script execution, and a hybrid architecture (cf. future article).

The LLVM codegen on the other hand involves a bit more overhead, in terms of a large DLL and longer compilation/JITting times, but has a wealth of other benefits.

The LLVM codegen isn’t tied to the interpreted structures, so it means more work down the road to get everything working, but there is much greater optimization potential, and the natively compiled code can be cached or persisted (thus mitigating or negating the compilation overhead).

Finally LLVM is of course cross-platform, and there is the potential for compiling standalone binaries as well…

Performance

mandelTest

No exact performance figures just yet, it’s too early and they change too often!

From initial tests, LLVM with optimization level zero (no optimization) is in the same ballpark as the dwsJIT, though with a slight JIT overhead (dwsJIT has none).

When increasing the optimization level, LLVM takes a measurable amount of time, but produces the best compiled binary on the benchmark so far! It’s only behind the hand-optimized version, and not all optimizations in LLVM are active just yet…

What’s working

Note that this is a very temporary list, as things change rapidly, so use it more as “cheat list” for what you can test right now.

What is working so far:

  • Primitive expressions
    • Integer
      • Arithmetrical (Add, Sub, Mul, Div, Mod, Neg, Sqr & Abs)
      • Arithmetrical assigns (+=, *=, -=, …, see above)
      • Bit Manipulations (Sar, Shr, Shl, And, Or, Xor, Not)
      • Comparisons (Less, LessEqual, Equal, GreaterEqual, Greater)
      • Shortcuts such as Inc & Dec
      • Min & Max (inlined)
    • Float
      • Arithmetrical (Add, Sub, Mul, Div, Neg, Sqr, Abs, Sqrt, Sin, Cos, Power, Exp, Ln, Log10, Log2)
      • Arithmetrical assigns (+=, *=, -=, …, see above)
      • Conversions (Floor, Ceil, Trunc, Round)
      • Comparisons (Less, LessEqual, Equal, GreaterEqual, Greater)
      • Min & Max (inlined)
    • Boolean
      • Logical (And, Or, Xor, Not)
  • Aggregate Types
    • Arrays
      • simple array types (read only!)
      • only primitive types
    • Records
      • simple record types
      • nesting is not thoroughly tested yet
      • may not contain arrays
    • Strings
      • only constant strings
  • Control Flow Expressions
    • Branches
      • If / Then
      • If / Then / Else
      • If / Then / Else -> Value
    • Loops
      • while
      • repeat
      • for (upward / downward, fixed / variable steps)
    • Functions
      • using simple variables (no var or const yet)
      • main function (typically without declaration in DWS)
      • may be called from other functions
      • PrintLn (to print constant strings, rely on external definition)

And here’s the list of things that are not working:

  • Strings and string management (except for string constants)
    • obviously no helpers as well
  • Resource strings
  • Dynamic arrays
  • Variants
  • complex array types (containing non-primitive values)
  • complex record types (containing non-primitive values)
  • Classes
    • Fields
    • Methods
    • Constructors
    • Self
    • Visibility
  • Interfaces
  • Objects
  • Case
  • Special loop aware
    • ForCharIn / ForCharCodeIn
    • Continue / Break / Exit / Exit(Value)
  • Exceptions (try, finally, except, raise, assert)
  • Helpers
  • Connectors
  • Special math functions like Tan, Arc*, etc.

by Eric at May 17, 2013 01:19 PM

Delphi Code Monkey

A very frustrating issue with Microsoft SQL Express

Recently I had some customers complaining that they could not connect with our Delphi-powered database backed application, to their database. They were new customers and (although I did not know it) the source of their trouble is that SQL Express (like the full SQL Server product) allows you to configure incoming connection types,  those being:


  • Shared Memory
  • Named Pipes
  • TCP/IP
The first type (Shared Memory) is fine for local connections only when the SQL server is on the same machine as the client application. Across a Windows domain, named pipes and TCP/IP are commonly used.  The problem is that SQL Express not only ships with TCP/IP and Named Pipes disabled, a condition that all of us who use it are so accustomed to that it is second nature for us to enable them,  but also, TCP/IP is misconfigured out of the box, for some versions of SQL Express.  Instead of having its "static TCP port" set to 1433 and "dynamic TCP port" option set to blank (a proper default), they are set with "static TCP port" set to blank, and "dynamic TCP port" set to zero.

Now here's where that gets really fun:

  • On some client computers, using an SQL connection string that does not specify named pipes explicitly,  Named pipes will be chosen first, and everything will work.
  • On some client computers on the same local area network and domain, the same SQL connection string that does not explicitly specify named pipes, TCP/IP will be chosen first, and will fail. 
Several workarounds are possible:

  • Hack the connection string so it forces named pipes. This must be made configurable in your Delphi application though or you'll be stuck where I was stuck at the beginning of this blog post, with some of your clients (who are unable to use Named Pipes) also unable to use your application.  If this is a "set it and forget it hack" done in the background with no UI to select this hack on or off, this will solve one problem while creating another one, so you're just sweeping the issue "under a carpet" and making it harder for someone else in the future.
  • Make your connection string configurable. This is flexible, but it makes configuring your application harder.
  • Disable the misconfigured TCP/IP option completely on the server, this will make the negotiation (use named pipes? use tcp/ip? Let's check what's available and try one) go faster, but for many users Named Pipes are significantly SLOWER than working with TCP/IP.
Last but not least, is not the workaround, but the actual fix:
  • Fix the TCP/IP configuration on the server, using SQL Server Configuration Manager.   Make sure that your SQL Server static port is set to 1433, and that your dynamic port option is set to blank (not configured).  
Note that in the year 2013, Microsoft still can't decide on one SQL tool to rule them all, so you've still got SQLSCM, SSMS, SSDT,  Visual Studio, and more ways to "look at your database", and no sign of one integrated tool to rule them all.    As a free product, SQL Express is amazing, and Microsoft has done great things with it, SQL Express 2012 is particularly a fantastic product.  But it has some warts, and this is one of them.   Another is that the SSMS (management studio) that comes with all SQL 2012 editions is based on the new and disgustingly slow and bloated version of visual studio shell.  I am going to stick with the old SQL 2008 R2 management studio until someone at microsoft visual studio team gets their head out of the sand.  A slow and bloated IDE shell is my favorite thing to use all day. Said no one.  Ever.



by Warren Postma (noreply@blogger.com) at May 17, 2013 07:36 AM

May 16, 2013

Žarko Gajić

Replacing SHFileOperation With IFileOperation To Process Multiple File Operations In One Call (Delphi Code)

delphi-ifileoperation
Starting with Windows Vista (and Windows Server 2008) the Windows API arsenal has a new and more powerful way of performing file operations like copy, move, delete and similar file and folder shell actions. The old (but still valid) SHFileOperation function is now replaced by the IFileOperation interface.
The IFileOperation exposes methods to copy, move, rename, create, and delete Shell items as well as methods to provide progress and error dialogs.

If you’ve used to working with SHFileOperation, and have been hit (for example) by the MAX_PATH problem, a solution can be found in IFileOperation. Here’s how to use IFileOperation in Delphi and ensure non existing folders are created in a copy operation.

The IFileOperation has many advantages over the SHFileOperation function, like being able to perform different operations in one call. You can delete a few files, copy some more, rename a folder, apply properties to a file – all in one operation. SHFileOperation can only do one operation at a time: copy, move, rename, or delete.

In this post I’ll concentrate on copying files. To make it simple the copy operation will copy a single file from its location to a destination folder and have the file name changed at the destination.

SHFileOperation

While you can locate lots of examples on how to use the SHFileOperation in Delphi, and the Jedi library also has it nicely wrapped in a component, here’s a short code to show you how to copy a file:

uses ShellApi;

function CopyFileSHFileOperation(const srcFile, destFile : string) : boolean;
var
  shFOS : TShFileOpStruct;
begin
  ZeroMemory(@shFOS, SizeOf(TShFileOpStruct));

  shFOS.Wnd := Application.MainForm.Handle;

  shFOS.wFunc := FO_COPY;

  shFOS.pFrom := PChar(srcFile + #0);
  shFOS.pTo := PChar(destFile + #0);

  //Do not ask the user to confirm the creation of a
  //new directory if the operation requires one to be created.
  shFOS.fFlags := FOF_NOCONFIRMMKDIR;

  result := SHFileOperation(shFOS) = 0;
end;

There’s one nice feature of the SHFileOperation: if the destination folder does not exist the function will create it! The FOF_NOCONFIRMMKDIR flag ensures no dialogs are presented to the user by Windows asking if the destination folder should be created.

IFileOperation

Here’s how you can copy a file using the IFileOperation interface

uses ActiveX, ComObj, ShlObj;;

function CopyFileIFileOperation(const srcFile, destFile : string) : boolean;
//works on Windows >= Vista and 2008 server
var
  r : HRESULT;
  fileOp: IFileOperation;
  siSrcFile: IShellItem;
  siDestFolder: IShellItem;
  destFileFolder, destFileName : string;
begin
  result := false;

  destFileFolder := ExtractFileDir(destFile);
  destFileName := ExtractFileName(destFile);

  //init com
  r := CoInitializeEx(nil, COINIT_APARTMENTTHREADED or COINIT_DISABLE_OLE1DDE);
  if Succeeded(r) then
  begin
    //create IFileOperation interface
    r := CoCreateInstance(CLSID_FileOperation, nil, CLSCTX_ALL, IFileOperation, fileOp);
    if Succeeded(r) then
    begin
      //set operations flags
      r := fileOp.SetOperationFlags(FOF_NOCONFIRMATION OR FOFX_NOMINIMIZEBOX);
      if Succeeded(r) then
      begin
        //get source shell item
        r := SHCreateItemFromParsingName(PChar(srcFile), nil, IShellItem, siSrcFile);
        if Succeeded(r) then
        begin
          //get destination folder shell item
          r := SHCreateItemFromParsingName(PChar(destFileFolder), nil, IShellItem, siDestFolder);

          //add copy operation
          if Succeeded(r) then r := fileOp.CopyItem(siSrcFile, siDestFolder, PChar(destFileName), nil);
        end;

        //execute
        if Succeeded(r) then r := fileOp.PerformOperations;

        result := Succeeded(r);

        OleCheck(r);
      end;
    end;

    CoUninitialize;
  end;
end;

Note that the PerformActions method executes actions added by calling individual methods like CopyItem(s), DeleteItem(s) and alike.

However, there’s one BIG problem in using IFIleOperation: in a copy action, if the destination folder does not exist the action will fail!

This is true even if FOF_NOCONFIRMMKDIR is set using the SetOperationFlags method.

Note the line where SHCreateItemFromParsingName is used for the second time:

//get destination folder shell item
r := SHCreateItemFromParsingName(PChar(destFileFolder), nil, IShellItem, siDestFolder);

It creates and initializes the shell item for the destination folder, and if this folder does not exist the call would fail.

IFileOperation.CopyItem + Force Destination Directory

The solution is to be found in the second parameter: const pbc: IBindCtx; This is a pointer to a bind context used to pass parameters to the parsing function (in this case SHCreateItemFromParsingName). We can use the binding context to force SHCreateItemFromParsingName not to query the file system – rather to just use what we provide. And what we will provide is a complex mixture of WIN32_FIND_DATA structure (specifying FILE_ATTRIBUTE_DIRECTORY), and instance of an object implementing IFileSystemBindData interface.

Here’s the full code, and the implementation of the required interface.

uses ActiveX, ComObj, ShlObj;

function CopyFileIFileOperationForceDirectories(const srcFile, destFile : string) : boolean;
//works on Windows >= Vista and 2008 server
var
  r : HRESULT;
  fileOp: IFileOperation;
  siSrcFile: IShellItem;
  siDestFolder: IShellItem;
  destFileFolder, destFileName : string;
  pbc : IBindCtx;
  w32fd : TWin32FindData;
  ifs : TFileSystemBindData;
begin
  result := false;

  destFileFolder := ExtractFileDir(destFile);
  destFileName := ExtractFileName(destFile);

  //init com
  r := CoInitializeEx(nil, COINIT_APARTMENTTHREADED or COINIT_DISABLE_OLE1DDE);
  if Succeeded(r) then
  begin
    //create IFileOperation interface
    r := CoCreateInstance(CLSID_FileOperation, nil, CLSCTX_ALL, IFileOperation, fileOp);
    if Succeeded(r) then
    begin
      //set operations flags
      r := fileOp.SetOperationFlags(FOF_NOCONFIRMATION OR FOFX_NOMINIMIZEBOX);
      if Succeeded(r) then
      begin
        //get source shell item
        r := SHCreateItemFromParsingName(PChar(srcFile), nil, IShellItem, siSrcFile);
        if Succeeded(r) then
        begin
          //create binding context to pretend there is a folder there
          if NOT DirectoryExists(destFileFolder) then
          begin
            ZeroMemory(@w32fd, Sizeof(TWin32FindData));
            w32fd.dwFileAttributes := FILE_ATTRIBUTE_DIRECTORY;
            ifs := TFileSystemBindData.Create;
            ifs.SetFindData(w32fd);
            r := CreateBindCtx(0, pbc);
            r := pbc.RegisterObjectParam(STR_FILE_SYS_BIND_DATA, ifs);
          end
          else
            pbc := nil;

          //get destination folder shell item
          r := SHCreateItemFromParsingName(PChar(destFileFolder), pbc, IShellItem, siDestFolder);

          //add copy operation
          if Succeeded(r) then r := fileOp.CopyItem(siSrcFile, siDestFolder, PChar(destFileName), nil);
        end;

        //execute
        if Succeeded(r) then r := fileOp.PerformOperations;

        result := Succeeded(r);

        OleCheck(r);
      end;
    end;

    CoUninitialize;
  end;
end;

Here’s the TFileSystemBindData, IFileSystemBindData interface implementation:

type
  TFileSystemBindData = class (TInterfacedObject, IFileSystemBindData)
    fw32fd: TWin32FindData;

    function SetFindData(var w32fd: TWin32FindData): HRESULT; stdcall;
    function GetFindData(var w32fd: TWin32FindData): HRESULT; stdcall;
  end;
...
function TFileSystemBindData.GetFindData(var w32fd: TWin32FindData): HRESULT;
begin
  w32fd:= fw32fd;
  Result := S_OK;
end;

function TFileSystemBindData.SetFindData(var w32fd: TWin32FindData): HRESULT;
begin
  fw32fd := w32fd;
  Result := S_OK;
end;

Finally, the usage goes like:

//works even if "d:\f1\f2\f3\" does not exist!
CopyFileIFileOperationForceDirectories('c:\somefile.png', 'd:\f1\f2\f3\copiedfile.png');

That’s it, now you can use IFIleOperation instead of SHFileOperation. Of course, you need to make sure your code runs on at least Windows Vista or Windows Server 2008. You can use the TOSVersion to check the operating system your code runs on.

by zarkogajic at May 16, 2013 12:52 PM

May 15, 2013

while true do;

Book Review: “ZeroMQ” (PACKT Publishing)

Introduction Some days ago I was contacted by a representative from PACKT Publishing asking me to write a review for their last book about the ZeroMQ library. In 2009 I was looking for a fast, very fast, messaging system for a complex project and I meet ZeroMQ. At that time there was the 1.x version and I [...]

by Daniele Teti at May 15, 2013 04:08 PM

The Wiert Corner - irregular stream of stuff

jpluimers

It is unwise to pass objects allocated in one framework over a DLL boundary to a different framework.

In the case of Using C dll in delphi return nothing, someone tries to pass an Interface to some memory in the C side over to Delphi.

Unless that interface is COM based, don’t do that!

In a more general way: don’t pass memory allocated on the DLL side over to the client side, no matter what kind of client you have.

From the DLL, either pass simple types, or fill buffers allocated at the client side.

–jeroen

via: Using C dll in delphi return nothing – Stack Overflow.


Filed under: Delphi, Delphi 1, Delphi 2005, Delphi 2006, Delphi 2007, Delphi 2009, Delphi 2010, Delphi 3, Delphi 4, Delphi 5, Delphi 6, Delphi 7, Delphi 8, Delphi x64, Delphi XE, Delphi XE2, Delphi XE3, Development, Software Development

by jpluimers at May 15, 2013 05:00 AM

May 14, 2013

Behind the connection

Be-Delphi Event 3.0

Be-Delphi Event 3.0 on November 21st in Edegem, Belgium. Stay tuned for more info... Follow me on Twitter Follow me on LinkedIn Follow me on Google+ Visit my website: http://www.overbyte.be

by François Piette (noreply@blogger.com) at May 14, 2013 09:11 PM

Firebird News

Firebird Python driver FDB 1.1.1 is released

FDB release 1.1.1 is out: http://pypi.python.org/pypi/fdb Bugs Fixed: - http://tracker.firebirdsql.org/browse/PYFB-34 - http://tracker.firebirdsql.org/browse/PYFB-35

by mariuz at May 14, 2013 12:44 PM

while true do;

My Delphi STOMP Client is now compatibile with iOS

Thank you to Marco Mottadelli, one of the active contributors to my Delphi STOMP Client open source project. Now the STOMP client is compatibile with: Delphi Win32/Win64 Delphi for iOS FreePascal It use INDY or Synapse as a TCP library, obviously on iOS you have to use INDY. Project is on google code.

by Daniele Teti at May 14, 2013 12:22 PM

The Wiert Corner - irregular stream of stuff

jpluimers

I had some notes on Delphi WSDL and SOAP peculiarities somewhere, but I misplaced them.

Luckily, I found some links that explain most of my notes well:

–jeroen


Filed under: Delphi, Delphi 2007, Delphi 2009, Delphi 2010, Delphi XE, Delphi XE2, Delphi XE3, Development, SOAP/WebServices, Software Development

by jpluimers at May 14, 2013 05:00 AM

Smart Mobile StudioSmart Mobile Studio

Smart Mobile Studio 1.1 RC (build 1.1.0.400)

We are very proud to present the release candidate for Smart Mobile Studio version 1.1  (build number v1.1.0.400). If you would like to give this groundbreaking product a test drive before we officially release it, then you can download the installer directly from SmartMobileStudio.com/download/setup_v1_1_0_400_rc.exe (The context menu is replaced with Ctrl+Shift+R (start/stop recording) and Ctrl+Shift+P [...]

by Smart Mobile Studio Team at May 14, 2013 12:44 AM

May 13, 2013

DelphiTools.info

Immutable strings… in Delphi?

One of the “novelties” of the NextGen Delphi compiler is immutable strings, which I find quite puzzling, for lack of a better word, given that Delphi already had reference-counted copy-on-write strings, and the NextGen compiler uses reference-counted strings.

I always considered that Delphi’s String type was one of its remaining strong points, being a high-level abstraction (higher than Java’s or .Net’s String/StringBuilder dichotomy) with excellent low-level performance (on par with C/C++  character arrays).

From the recent discussions, it appears many don’t know what makes/made Delphi String so special, so here is a quick summary.

Immutability

String being immutable means you can keep a single reference across threads without trouble. That’s an advantage over C strings.

It also means that copying a string, be it for an assignment or a parameter passing, is just like passing a reference, you don’t have to duplicate the content if you want to be sure it isn’t modified behind your back. That’s an advantage over C strings and StringBuilder.

Note that none of the above are advantages over Delphi Strings, since the copy-on-write mechanism means that Delphi Strings are effectively immutable once they’re referenced more than once.

Reference-counting vs Garbage Collection

Every time a new assignment or parameter passing is made, the reference count of the String has to be increased, this is an atomic lock, and is related to memory management, so it’s there whether you’re using simple reference-counting or copy-on-write.

Under a GC, no atomic lock is required, a simple reference (pointer) has to be copied. This is very efficient, locally, but the memory management costs are just deferred to a later garbage collection phase. Since immutable strings don’t have reference to other objects, the GC for them can theoretically happen in parallel without any drawbacks (assuming the GC supports it).

So under a GC, an immutable String type makes a whole lot of sense, as implementing a copy-on-write one requires a lot of effort, and a mutable one is problematic multi-threading wise.

Copy-on-write mutability

Making reference-counted strings mutable doesn’t change any of the above, you just add one capability: when the reference count indicates there is no other reference to a string, then you can mutate it, ie. change characters, adjust its length, etc.

In other words, when the only reference to a string is a single variable locally scoped to a procedure, then it’s safe to do just about anything with it, the multi-threading issues can’t  apply until that string is referenced somewhere else.

This is both convenient and very efficient, since what the compiler does before applying a mutation can be summarized as:

if myString is "referenced somewhere else" then
   myString := make a local copy of my String
mutate myString

The local copy is of course referenced nowhere else, and thus is safe to mutate. Copy-on-write is really copy-on-mutate, as it encompasses just not changing the characters, but also resizing a string (re-allocations) and concatenations.

Keep in mind this is an “added-on” behavior, where you just take advantage of the memory management scheme being a reference-counting one. If you know what you’re doing and want more performance, you can even waive the COW check by using UniqueString(), which will ensure you have a local copy, and then acquiring a PChar to the string content.

It can be done under a GC, but means you have to maintain a reference count or similar information since the GC doesn’t have one. Android relies a lot on copy-on-write, and that was actually one key differentiation between Dalvik VM and more classic Java VM.

Advantages of RawByteString & UTF8String over TBytes

And this will be a bit more controversial, but Copy-On-Write is also why RawByteString/UTF8String can ofttimes make a lot more sense than TBytes for binary buffers: RawByteString isn’t just reference-counted (like TBytes), it is also supporting copy-on-write.

This means that in a multi-threaded environment, RawByteString shares the same advantages of immutability String enjoys, and which TBytes just doesn’t enjoy, as TBytes is always mutable.

Conclusion

String wraps up both advantages of Java/.Net String & StringBuilder, they have bother multi-threading immutability advantages and the mutability capability.

Performance-wise, under a speculative memory manager (like most modern allocators), you’ll also find that merely concatenating to a String is typically just as fast as using TStringBuilder, and in several occurrences  it’s actually faster because String benefits from compiler magic, while TStringBuilder does not (also some TStringBuilder implementations are a little weak).

Alas some String performance was lost during the Unicode and 64bit transition, when some FastCode routines where replaced by lower performing pure-pascal ones, and you’ll lose even more performance with TStringHelper, which introduces some algorithmically poor pure-Pascal implementations.

by Eric at May 13, 2013 06:54 AM

May 12, 2013

Behind the connection

Internet Explorer Automation Part 3

Today I will present an Internet Explorer automation which will query Blogger stats page automatically. IE automation is required because Blogger website makes heavy use of JavaScript to dynamically construct the stats page. Downloading the webpage with a HTTP component won’t work because the numbers we are looking for are not in clear! JavaScript must be executed to get hand of it. The code I

by François Piette (noreply@blogger.com) at May 12, 2013 10:03 PM

Castle Game Engine news

Development: transitionComplete, Debian packages, network tutorial, data URI, MultiTexture tests, more

Caffeine model from http://www.web3d.org/x3d/content/examples/Basic/ChemicalMarkupLanguage/index.html
data URI demo. All the textures, movies, sounds, scripts, linked 3D models here are embedded using data URI.
MultiTexture.function test
MultiTexture.mode and source test
MultiTexture blending modes test
Fireplace model, with fire rendered as animated image sequence

Various new features developed for next Castle Game Engine and view3dscene:

  1. NavigationInfo.transitionComplete support. Demo model transition_multiple_viewpoints.x3dv shows how to use it to make an animated transition between a couple of viewpoints.

  2. Thanks to Abou Al Montacir we will have packages with Castle Game Engine and view3dscene in Debian! Most of this software was developed by Michalis using Debian, so having my software in the Debian repository would feel really great for me :) See here for our forum thread, and here is the Debian bug marking ITP (Intent To Package) for engine: #706408 and for view3dscene: #707932.

  3. For developers, new chapter of our tutorial describing network support is available.

  4. Engine examples contain a simple tool examples/tools/to_data_uri.lpr that can generate data URI (to embed your texture, audio, model, etc. inside a VRML/X3D model, or a webpage, or other documents) from any file. It gets the file and guesses MIME type using our existing CastleDownload unit, so it supports local files as well as http links, and MIME type is retrieved from server or guessed based on file extension.

    There is a demo data_uri.x3dv showing how you can use data URI to embed all kinds of things inside X3D file: textures, sounds, other 3D models (to Inline or Anchor to them), scripts etc.

  5. MultiTexture.function support (forces shader pipeline rendering for given shape; there's no way to reasonably implement this using fixed-function pipeline). Demo in functions.x3dv.

  6. A set of X3D multi-texturing tests is available, testing support of view3dscene and other VRML / X3D browsers for multi-texture features. This is part of my ongoing effort to improve X3D MultiTexturing specification.

  7. There is a progress bar showing the process the downloading. The download is still blocking, but at least now you see what's going on :)

  8. If you load or save image sequences using the syntax image%d.png, for example inside our extension Movies for MovieTexture can be loaded from images sequence: the new syntax to indicate counter inside the URL will be @counter(4), where 4 is the padding. For example image%d.png has to be changed to image@counter(1).png and image%4d.png has to be changed to image@counter(4).png.

    For loading, you will have to use new syntax with @counter(<padding>) with new view3dscene / Castle Game Engine versions. You will have to update your VRML/X3D models, old syntax will unfortunately not work anymore (reasons below). For saving, the old syntax %d will continue to work for some time (along the new @counter(<padding>) syntax, and you're encouraged to upgrade to new syntax).

    The reason for this is that MovieTexture.url is now correctly treated as an URL, and this means that percent character % needs to be escaped to %25. Inside URL the sequence %4d has to mean letter M (ASCII code 77, which is 4d in hexadecimal). So there is unfortunately no way to avoid breaking compatibility — we want to correctly support URLs, which implies that %4d must be interpreted as letter "M", not as a magic counter.

    Looking back, it was an unfortunate choice to use percent character to indicate images sequence, since percent is special inside URIs. It was done for consistency with ffmpeg, that supports things like image%4d.png on the command-line (but not when using URLs; for example, ffplay /home/image%4d.png works, but ffplay file:///home/image%4d.png does not work, neither does ffplay file:///home/image%254d.png). So, one can say that it was ffmpeg that made a bad choice, but then ffmpeg did it for consistency with common string formatting functions (C sprintf, ObjectPascal Format)...

    Comments about this change are of course welcome, through forum or any other means. Right now, I just don't see a way to avoid breaking compatibility. We made a bad decision to use %d to indicate image sequence, and it has to change in order to correctly support URL encoding in new versions.

  9. A couple of bugfixes. Including bugfix to a quite horrible mistake in ShaderPart node, in some circumstances the shader code would be reloaded from file at every frame, causing a horrible slowdown. It's fixed now of course.

May 12, 2013 12:00 PM

May 11, 2013

Firebird News

Jaybird 2.2.3 (Firebird JDBC) released

The Firebird JDBC team is happy to announce the release of Jaybird 2.2.3. See http://www.firebirdsql.org/en/jdbc-driver/ for the downloadlinks. The release is also available on maven: <groupId>org.firebirdsql.jdbc</groupId> <artifactId>jaybird-jdkXX</artifactId> <version>2.2.3</version> The artifactId depends on your target Java version: jaybird-jdk15, jaybird-jdk16 or jaybird-jdk17. The following has been changed or fixed in Jaybird 2.2.3: Fixed incorrect synchronization in native [...]

by Mark Rotteveel at May 11, 2013 08:35 PM

Delphi Haven

Arnaud Bouchez on the ‘nextgen’ compiler

Arnaud Bouchez of Synopse open source fame (mORmot etc.) has written an interesting piece on the ‘nextgen’ compiler that debuted with XE4′s iOS support – check it out.


by Chris Rolliston at May 11, 2013 01:47 PM

May 09, 2013

Behind the connection

OpenSource GDI+ Library - Part 2

In a previous article, I talked about OpenSource GDI+ Library for Delphi. In this article I will present a small application which is the basic of an image processing or image drawing application. A form to display an image The application is divided into two forms. One main form and one image display form. The main form creates two instances of the image display form to show two images

by François Piette (noreply@blogger.com) at May 09, 2013 11:23 AM

OpenSource GDI+ Library

Sometimes ago, I discovered an open source GDI+ Library built by Erik Van Bilsen. I now use that Library extensively with excellent result. I used it to build an image processing system and other similar things. The Library is intended for Delphi 2009 and above. I currently use it with Delphi XE4 with no problem. It comes with a nice sample application that demonstrate the usage of GDI+

by François Piette (noreply@blogger.com) at May 09, 2013 11:22 AM

The Wiert Corner - irregular stream of stuff

May 08, 2013

Delphi Code Monkey

My app is in the App Store.

This app is pure Objective-C, using the remObjects Data Abstract + RemObjects SDK to  build the Delphi middle-tier server service.

RentalPointToGo uses a Made-for-iPhone (MFi) accessory called the Linea Pro from Infinite Peripherals, which is the same barcode-scanning hardware used with iphones, in the Apple retail stores.




by Warren Postma (noreply@blogger.com) at May 08, 2013 08:20 PM

The Wiert Corner - irregular stream of stuff

CcKkOoSsUuVvWwXxZz are much alike.

Lucida Console Sample (thanks Wikimedia!)

Lucida Console Sample (thanks Wikimedia!)

I’m in search to see if there is a better programmers font than the monospaced Lucida Console mainly to be used in Visual Studio, Delphi, the Windows console, Xcode and Eclipse.

What I love about Lucida Console design is the relatively large x-height combined with a small leading (often called “line height”).

This combines very readable text, and a lot of code lines in view.

Lucida has two small drawbacks, see the second image at the right:

  • The captial O and digit 0 (zero) are very similar.
  • Some uppercase/lowercase character pairs are alike (because of the large x-height)

But, since the font hasn’t been updated for a very long time, lots of Unicode code points that are now in current fonts, are missing from Lucida Console (unless you buy the most recent version that has 666 characters from Fonts.com)

Well, there are dozens of monospaced fonts around, so I wonder: which ones do you like?

In the mean while, I’m going to do some experimenting with fonts mentioned in these lists:CcKkOoSsUuVvWwXxZz are much alike.

A few fonts I’m considering (I only want scalable fonts, so .fon files are out):

I have tried Adobe Source Code Pro about half a year ago. That didn’t cut it: problem with italics in Delphi, and note enough lines per screen.
New Open Source monospaced font from Adobe: Source Code Pro « The Wiert Corner – irregular stream of stuff.

–jeroen


Filed under: .NET, Apple, Delphi, Delphi 2007, Delphi XE3, Development, Font, Mac, OS X, Power User, Programmers Font, Software Development, Typography, Visual Studio 11, Visual Studio 2005, Visual Studio 2008, Visual Studio 2010, Visual Studio and tools, Windows, Windows 7, Windows 8, Windows Server 2008 R2, Windows XP, xCode/Mac/iPad/iPhone/iOS/cocoa

by jpluimers at May 08, 2013 05:00 AM

May 07, 2013

Delphi Bistro

Cross-platform development the FireMonkey way

Para leer este articulo en espanol haz click aqui.

What is FireMonkey?

FireMonkey is cross-platform Framework developed by Embarcadero. FireMonkey was originally designed by Eugene Kryukov in the company “KSDev” as VGScene.

In 2011 Embarcadero acquired the rights to the software and renamed it to FireMonkey.

FireMonkey is included, along with the traditional Visual Component Library (VCL) in Delphi and C++ Builder.

FireMonkey was introduced in XE2. It’s goal is to allow developers to design cross-platform applications and interfaces that take advantage of the acceleration features available in Direct2D on Windows Vista and Windows 7, OpenGL on Mac OS X, OpenGL ES on iOS, and GDI+ on Windows platforms where Direct2D is not available

Applications and interfaces developed with FireMonkey are separated into two categories HD and 3D. HD and 3D elements can be mixed by utilizing built-in components that are included in the IDE.

HD applications are 2D applications with flat interfaces similar to software that is developed using VCL.  3D applications are 3D applications and feature an three dimensional  XYZ interface.

Firemonkey is a full software development framework, and retains many features available with VCL. The major differences are:

  • Cross-platform compatibility
  • Vector drawn interface elements
  • Any visual component can be a child of any other visual component allowing for creation of hybrid components
  • Built-in styling support
  • Support for visual effects (such as Glow, Inner Glow, Blur for example) and animation of visual components

Due to the framework being cross-platform compatible, the same source code can be used to deploy to the various platforms it supports. Originally, FireMonkey natively supported 32-bit and 64-bit executables on Windows and 32-bit executables on Mac OS X and iOS.

As of the release of XE3, iOS support has been dropped, but it is still possible to develop iOS applications using XE2 editions of the same products. FireMonkey 2 or FM² is the name of the framework in XE3, and though it provides similar features to what was shipped with XE2, there have been numerous improvements in many areas of the framework.

As of this writing (December 2012) the Embarcadero R&D team is working on iOS and Android support.

Windows 8 ARM and Linux server are targeted for the second half of 2013.

Are there alternatives to FireMonkey?

Yes! Certainly. There are even Pascal based alternatives. FPC and Lazarus are cross platform options as well as Qt (C++) wxWidgets(C++).

  • FPC/Lazarus
    • Free Pascal (aka FPK Pascal) is a 32 and 64 bit professional Pascal compiler. It can target multiple processor architectures: Intel x86, AMD64/x86-64, PowerPC, PowerPC64, SPARC, and ARM. Supported operating systems include Linux, FreeBSD, Haiku, Mac OS X/iOS/Darwin, DOS, Win32, Win64, WinCE, OS/2, MorphOS, Nintendo GBA, Nintendo DS, and Nintendo Wii. Additionally, JVM, MIPS (big and little endian variants) and Motorola 68k architecture targets are available in the development versions.
  • Qt
    • Qt is a cross-platform application and UI framework for developers using C++ or QML, a CSS & JavaScript like language. Qt Creator is the supporting Qt IDE.”
  • Mono
    • “Mono is a software platform designed to allow developers to easily create cross platform applications. Sponsored by Xamarin, Mono is an open source implementation of Microsoft’s .NET Framework based on the ECMA standards for C# and the Common Language Runtime.”
  • wxWidgets
    • “wxWidgets is a C++ library that lets developers create applications for Windows, OS X, Linux and UNIX on 32-bit and 64-bit architectures as well as several mobile platforms including Windows Mobile, iPhone SDK and embedded GTK+. It has popular language bindings for Python, Perl, Ruby and many other languages. Unlike other cross-platform toolkits, wxWidgets gives its applications a truly native look and feel because it uses the platform’s native API rather than emulating the GUI. It’s also extensive, free, open-source and mature.”

Why FireMonkey?

From a Delphi developer perspective FireMonkey is an interesting alternative to developing cross-platform solutions because it allows for leveraging on existing knowledge and concepts from the VCL and the language.

Another less often mentioned reason is the fact that Embarcadero is a software  development company and as such is hardware and platform neutral.

To better understand the previous statement let’s take a look at what happened to Qt. Qt development was started in 1994 by Trolltech, a Norwegian software company, as a way to developing cross-platform applications, including mobile platforms. In mid 2008 Nokia acquired Trolltech and imposed a new development strategy focusing mostly on it’s own hardware and Symbian mobile OS. Lots of progress were done in the mobile environment. This was done in detriment of all other platforms. Then in early 2011 Nokia announced it was dropping the Symbian OS and as a side causality the Qt Framework. Qt was sold off to Digia. As a result of that Qt is lagging on several areas of the mobile segment.

FireMonkey versions

FireMonkey was introduced in Delphi XE2. In 2012 a new version, FireMonkey 2 or FM2, was shipped with Delphi XE3. From this point onwards we are going to concentrate on what is new in FM2.

VCL vs. FMX - a quick introduction to FMX for a VCL connoisseur

Visual Component Library or VCL is a Windows only framework and can not be used in FireMonkey. FireMonkey has introduced it’s on visual library named FMX.

FMX is compatible with Windows, Mac and soon IOS, Android, Linux and Windows ARM.

FMX and VCL share some common ancestry. Both object models start with a TObject that descends to a TPersistent and then to a TComponent. After TComponent the libraries diverge. FMX goes to TFMXObject, TControl and then to TStyleControl or TShape.

FMX and VCL Object tree

TStyledControl is used as a basis for all the visual components and is the base class for customizable and user-interaction controls.

TShape is the base class for 2D primitives. TShape defines the common behavior–methods and properties–for 2D graphic primitives and it cannot be used as stand alone component.

The event model remains the same between VCL and FMX. So, when it comes to events anything that applies to the VCL will apply to FMX. The same can be said about object persistence. FMX and VCL share TPersistent. As you already may know TPersistent is the ancestor for all objects that have assignment and streaming capabilities.

In a VCL application your component can broadcast messages to all the controls in a form, send messages to a particular control (or to the application itself), or even send messages to itself.  FMX does not support component messages in the same way  the VCL does.

The coordinate system is different in FM2. While the VCL uses left and top FMX uses X, Y and Z. Left and Top are integers and X,Y and Z are floating point. This change was brought into FMX out of the need to address 3D positioning on the form.

And speaking of properties, we need to be aware some properties have changed. For example: Caption is now Text, Left and Top are now Position.X, Position.Y and Position.Z

Object Ownership mechanism remains the same across the two libraries and Object parenting is similar. The difference is that FMX does not restrict parenting to container like controls like the VCL and Child Objects share attributes from it’s parents.

In FMX TCanvas is not a direct device wrapper as it is in VCL

As in the VCL the FMX.TControl is the base class for on-screen components. However, in FMX subclasses are divided into primitive shapes (TShape) and styleable controls (TStyledControl).  FMX.TControl extends TFmxObject to present objects that are seen, by adding properties and methods for size, position, margins, alignment, visibility, mouse and keyboard interaction, focus, animations, effects and painting.

What is new in FM2

While some changes were brought in to improve performance other changes were clearly targeting enhanced crossed platform including mobile devices. One can clearly see this pattern in the new items introduced and to some extent on the changes made to the framework.

FM2 brings framework refinements, a new Multimedia components, a new Layout components, a new Platform Services class, Styled Non-Client areas, Actions, Anchors, Sensors, Touch and Gestures. It also has enhanced Styles, 3D

Unneeded properties where prevented from being surfaced everywhere. That speeds up loading and saving form info at design time and loading forms at run time

Bitmap performance enhancements where brought in FM2. FM2 switches to native bitmap as soon as possible. That means that bitmaps are moved into the GPU’s memory. This brings the side effect of not allowing direct access to bitmaps. It is possible to map pixel data to a buffer and push changes to the GPU.

FM2 now offers support to capturing data from any capture devices. For that you can use TCaptureDevice and TCaptureDeviceManager. A new Multimedia wrapper was introduced to allow playing of media files. The TMedia, TMediaPalyer and TMediaPlayer control wrap around the host OS native multimedia system.

With cross-platform development come some unique challenges. Specially if you throw into the mix some smaller devices such as phones and tablets. So, some changes were introduced to allow for better screen layout management.

Every VCL programmer knows the worth of components Anchors. Anchors were missing from the first installment of FireMonkey. But never fear, Anchors were introduced on FM2 along with some welcome layout managers; TFlowLayout and TGridLayout.

Anchors were introduced to work together with Layout Managers

TFlowLayout arranges components as if they were words in a paragraph. It allows the developer to select spacing between components, component alignment and even forced breaks using a TFlowLayoutBreak.

TGridLayout allows controls to be arranged in a grid of equally sized cells. This layout manager rearranges objects in it’s grid every time the layout changes. The components inside the a TGridLayout are resized to fit the sizes of the cells. Controls can be arranged in vertical or horizontal cells.

FM2 obsoleted TPlatform as a means to find information about supported features on a host OS because it was too rigid, desktop centered and did not adapt well to targeting diverse software and hardware platforms with different/disparate services.

In it’s place TPlatformServices (FMX.Platform) was introduced.TPlatformServices can be used to to dynamically figure out what is available. This is a registry class that can be queried and uses Supports syntax. It also allows the programmer to easily implement custom devices and services.

FM2 introduced Touch and Gestures. This feature is modeled after the VCL Gesture engine. The are a few differences between the VCL implementation and the FMX implementation.

FireMonkey does not support fewer interactive gestures on Mac OS X than the number of supported gestures on a Windows PC. In the Mac only igZoom, igPan and igRotate are supported. FireMonkey does not support custom Gestures. Mouse gestures only work on Windows 7 and Windows 8.  And on Windows interactive gestures and standard gestures cannot be used at the same time. Also FireMonkey adds TouchTargetExpansion which allows for expanded touch target around a control by adding a specified zone to be behave as if the user had touched the control itself.

FMX has introduced non-visual components that implements location and motion sensors. A great way of looking at what is coming in the sensors framework is to examine the unit System.Sensors.  (One way to test location in Windows without a location device attached to your computer is to use Geosense for Windows (http://geosenseforwindows.com). Geosense is a free software driven location sensor for Windows.)

Speaking of units, any unit that starts with “FMX.” is a FMX unit only. However, units such as System.Sensors are framework agnostic. So, based on this statement, sensors components can be used in both VCL and FMX applications

Cross-platform programming

Last but not least, we need to talk about some best practices in cross-platform programming.

Always think cross-platform. Up to now our deployment OS was Windows and our way of thinking was base of the Windows programming model. Depending on your target(s) certain services may not available. For example, a desktop will certainly have a mouse, however a phone/tablet will be just the opposite.

Same recommendation goes for resources such as storage, connectivity, CPU power,  battery, screen size, and so on. While on the desktop environment such resources are virtually endless in a mobile scenario most resources are limited and at times not available at all.

And while a desktop computer is a generic device a smartphone is a specialized device and as such it has one primary function that overrides any other function – the ability to receive and place calls at will. So programs need to be able to deal with such interruptions in a graceful manner.

One must program accordingly to such limitations and specific functions. And in some cases program to the lowest common denominator.

Unless you have a very good reason, prefer a feature that is implemented thru the framework as opposed to natively. Most often there is no valid reason to do the opposite. Let the framework do it’s job and abstract you from the OS. That will buy you compatibility with newer platforms that come in to the framework.

If you must use a platform specific functionality make sure you document why yu are doing so and provide implementations to all platforms that your project is targeting. Also, provide an easy way to warn others that that specific feature was not supported by your implementation either at compile time or at run-time on any other platform.

A good way to implement this is to surround the implementation with a set of conditional pre-compiler directives as demonstrated in the code snippet below:

{$IFDEF MSWINDOWS}
  uses Winapi.Windows;
{$ELSE IFDEF MACOS}
  uses Macapi.Mach;
{$ELSE}
  {$MESSAGE FATAL &#039;Feature not implemented!&#039;}
{$ENDIF}

Final thoughts

FireMonkey is a serious contender for the seasoned Delphi/VCL developer. It has significantly improved on it’s second version. Furthermore, Embarcadero’s product development strategy is pushing the product into a very desirable position. That position is the ability to develop once and deploy across many platforms including the two leading mobile platforms. Thus making the platform irrelevant and allowing developers to focus on the delivery of a solution.

The iOS version of FM2 is imminent, followed soon by the Android version, and later by the Windows ARM and Linux version. From where I stand I can see an exciting future ahead. Call me an incorrigible optimist if you will. I’ll take that!

by Fletch at May 07, 2013 02:28 PM

DelphiTools.info

DWScript news roundup for May 2013

dws-mirrorLanguage and Script Engine

  • Delphi XE4 is now supported, compiler hints for XE3 have been taken care of as well
  • compiler now supports “in” operator across strings, for for instance “if subString in myString then” is equivalent to “if myString.Contains(subString) then
  • added standard “helpers” for most built-in functions operating on String, Integer, Float and Boolean. These roughly follow the Delphi & .Net conventions, though standard Maths functions are accessible directly (f.i. you can do “angle.Cos” directly, rather than have to go through “Math.Cos(angle)“)
  • added some more string functions (DeleteLeft, DeleteRight, etc.)
  • added support for EmptyParam for the COM connector
  • added DivMod to the standard functions
  • improved performance of DecodeDate/Time functions
  • improvements and fixes for the JSON connector (now supports manipulating an existing JSON structure, creating, moving and deleting nodes)
  • misc. fixes and improvements

Note that there aren’t specifics DPKs for XE4, you can just copy/rename the XE2 or XE DPKs.

Changes for SmartMobileStudio / JavaScript Codegen

In addition to the  previous changes, the following will apply to the next version of SmartMS:

  • support “for str in variant” which allows enumerating members of a raw JavaScript object (compiles to “for (str in v)”)
  • improved code generation for functions with an “exit” statement
  • added specific optimizations for string copies and testing (startswidth/endwidth)
  • slightly faster code generation

 

by Eric at May 07, 2013 11:30 AM

May 06, 2013

DelphiTools.info

Smart Contest 2013 – Round #2

wartrailThe second Smart Context 2013 has been announced! As with the previous round, first prize is a tablet device of your own choice (up to USD 750). This time the theme is “Game Development”

The rules are as follows:

  • Registration before the 13th of May (registration at contest@smartmobilestudio.com)
  • Deliver your contribution before 3rd of June
  • The source code will be shared in our show case area
  • Preferable that it can run in the integrated IDE browser (but not mandatory)
  • No restrictions w.r.t game genre
  • No restrictions w.r.t project type (canvas, sprite, console, VCL)
  • You can use the trial version to make your entry

The registration date limit is not intended to be binding, but more like an “Hey I’m in”, and for the previous contest latecomers were accepted as well.

For this round I’ll be one of the judges alongside Jon Lennart Aasenden, who recently posted two articles about game development, see part1 and part2.

For more details, head to the announcement page.

by Eric at May 06, 2013 06:24 AM

The road to Delphi

Introducing TSMBIOS

logoA few weeks ago I started a new project called TSMBIOS, this is a library which allows access the SMBIOS using the Object Pascal language (Delphi or Free Pascal).

What is the SMBIOS?

SMBIOS stands for System Management BIOS , this standard is tightly related and developed by the DMTF (Desktop Management Task Force).

The SMBIOS contains a description of the system’s hardware components, the information stored in the SMBIOS typically includes system manufacturer, model name, serial numbers, BIOS version, asset tag, processors, ports, device memory installed and so on.

Note : The amount and accuracy of the SMBIOS information depends on the computer manufacturer.

Which are the advantages of use the SMBIOS?

  • You can retrieve the information without having to probe for the actual hardware. this is a good point in terms of speed and safeness.
  • The SMBIOS information is very well documented.
  • You can avoid the use of undocumented functions to get hardware info (for example the RAM type and manufacturer).
  • Useful for create a Hardware ID (machine fingerprint).

How it works?

The BIOS typically populates the SMBIOS structures at system boot time, and is not in control when the OS is running. Therefore, dynamically changing data is rarely represented in SMBIOS tables.

The SMBIOS Entry Point is located somewhere between the addresses 0xF0000 and 0xFFFFF, in early Windows systems (Win95, Win98) it was possible access this space address directly, but after with the introduction of the NT Systems and the new security changes the BIOS was accessible through section \Device\PhysicalMemory, but this last method was disabled as well in Windows Server 2003 Service Pack 1, and replaced with 2 new WinApi functions the EnumSystemFirmwareTables and GetSystemFirmwareTable, Additionally  the WMI supports reading the entire contents of SMBIOS data i using the MSSMBios_RawSMBiosTables class inside of the root\wmi namespace.

Note : you can find more information about the SMBIOS Support in Windows on this link.

The TSMBIOS can be compiled using a WinApi mode (uses the GetSystemFirmwareTable function) or using the WMI Mode (uses the MSSMBios_RawSMBiosTables class)

If you uses the WinApi Mode you  don’t need use COM and the final size of the Application will be smaller, but the WinAPI functions was introduced in Windows Vista and Windows XP x64 (So in Windows Xp x86 will fail). Otherwise using the WMI mode you will need use COM (CoInitialize and CoUninitialize), but also you will get two additional advantages 1) The WMI will work even in Windows Xp x86 systems, 2) You can read then SMBIOS data of local and remote computers.

In order to use the TSMBIOS in your application only you must add the uSMBIOS unit to your uses clause, then create a instance for the TSMBios class using the proper constructor

// Default constructor, used for populate the TSMBIOS class  using the current mode selected (WMI or WinApi)
constructor Create; overload;
// Use this constructor to load the SMBIOS data from a previously saved file.
constructor Create(const FileName : string); overload;
{$IFDEF USEWMI}
// Use this constructor to read the SMBIOS from a remote machine.
constructor Create(const RemoteMachine, UserName, Password : string); overload;
{$ENDIF}

and finally use the property which expose the SMBIOS info which you need. In this case as is show in the sample code the BatteryInformation property is used to get all the info of the batteries installed on the system.

{$APPTYPE CONSOLE}

uses
  Classes,
  SysUtils,
  uSMBIOS in '..\..\Common\uSMBIOS.pas';

procedure GetBatteryInfo;
Var
  SMBios : TSMBios;
  LBatteryInfo  : TBatteryInformation;
begin
  SMBios:=TSMBios.Create;
  try
      WriteLn('Battery Information');
      WriteLn('-------------------');
      if SMBios.HasBatteryInfo then
      for LBatteryInfo in SMBios.BatteryInformation do
      begin
        WriteLn('Location           '+LBatteryInfo.GetLocationStr);
        WriteLn('Manufacturer       '+LBatteryInfo.GetManufacturerStr);
        WriteLn('Manufacturer Date  '+LBatteryInfo.GetManufacturerDateStr);
        WriteLn('Serial Number      '+LBatteryInfo.GetSerialNumberStr);
        WriteLn('Device Name        '+LBatteryInfo.GetDeviceNameStr);
        WriteLn('Device Chemistry   '+LBatteryInfo.GetDeviceChemistry);
        WriteLn(Format('Design Capacity    %d mWatt/hours',[LBatteryInfo.RAWBatteryInfo.DesignCapacity*LBatteryInfo.RAWBatteryInfo.DesignCapacityMultiplier]));
        WriteLn(Format('Design Voltage     %d mVolts',[LBatteryInfo.RAWBatteryInfo.DesignVoltage]));
        WriteLn('SBDS Version Number  '+LBatteryInfo.GetSBDSVersionNumberStr);
        WriteLn(Format('Maximum Error in Battery Data %d%%',[LBatteryInfo.RAWBatteryInfo.MaximumErrorInBatteryData]));
        WriteLn(Format('SBDS Version Number           %.4x',[LBatteryInfo.RAWBatteryInfo.SBDSSerialNumber]));
        WriteLn('SBDS Manufacture Date  '+LBatteryInfo.GetSBDSManufactureDateStr);
        WriteLn('SBDS Device Chemistry  '+LBatteryInfo.GetSBDSDeviceChemistryStr);
        WriteLn(Format('OEM Specific                  %.8x',[LBatteryInfo.RAWBatteryInfo.OEM_Specific]));
        WriteLn;
      end
      else
      Writeln('No Battery Info was found');
  finally
   SMBios.Free;
  end;
end;

begin
 try
    GetBatteryInfo;
 except
    on E:Exception do
        Writeln(E.Classname, ':', E.Message);
 end;
 Writeln('Press Enter to exit');
 Readln;
end.

TSMBIOS Features

  • Source Full documented compatible with the help insight feature, available since Delphi 2005.
  • Supports SMBIOS Version from 2.1 to 2.7.1
  • Supports Delphi 5, 6, 7, 2005, BDS/Turbo 2006 and RAD Studio 2007, 2009, 2010, XE, XE2, XE3, XE4.
  • Compatible with FPC 2.6.0 (Windows and Linux)
  • SMBIOS Data can be obtained using WinApi, WMI or loading a saved SMBIOS dump
  • SMBIOS Data can be saved and load to a file
  • SMBIOS Data can be obtained from remote machines

SMBIOS Tables supported

The TSMBIOS is a Open Source project is hosted in the code google site.


by Rodrigo at May 06, 2013 05:24 AM

May 03, 2013

Te Waka o Pascal

Changing Your Delphi License Serial Number

Having installed and activated Delphi XE4 using the license available to me from my employer I decided that, despite the very nasty taste left in my mouth, I would pay the $49 required for the XE4 “hot-fix” release, albeit only in order to remain with the valid update window now imposed by Embarcadero, on the [...]

by Deltics at May 03, 2013 12:15 AM

May 02, 2013

The Wiert Corner - irregular stream of stuff

May 01, 2013

Te Waka o Pascal

It’s a Good Time for NZ Delphi Users to Cross-Grade

Having lost our Delphi reseller in NZ last year, and with the Kiwi dollar riding high against the US dollar, now is a good time to make purchases from online stores operating in US currency. RemObjects has such a store and they also have a cross-grade offer for Delphi customers wishing to move over to [...]

by Deltics at May 01, 2013 10:11 PM

The Wiert Corner - irregular stream of stuff

jpluimers

This is more elaborate English version of a short Dutch message I recently sent to explain the differences between VCL and FMX:

Do not regard FMX as a replacement for VCL: they are different kinds of frameworks.

VCL is a wrapper around Windows Controls. In itself, it has not much functionality: it exposes the underlying Windows functionality. The exception are data aware controls that provide basic functionality for writing data aware applications. There is a huge 3rd party market for extending VCL support, for instance providing extra Windows functionality, enriching data aware behaviour (look at all those fancy data aware grids), and many more.

FMX  is the FireMonkey X-platform framework. Major functionalities are vector based 2D, 3D drawing and controls, and support for styles and composition.

When introducing FMX in Delphi XE2, Embarcadero also introduced a new way of data binding that is shared with FMX and VCL. FMX extends this a bit to some basic data aware controls.

Gone are most of the platform specific features like drag & drop, full blown Windows Shell ListViews, etc. There are some controls that manifests themselves differently on each supported platform (like Pickers), but most of that is currently left to the 3rd party FMX component market.

So if you want FMX to replace VCL, then be prepared for quite some shopping in the 3rd party market.

CLX tried to be a full blown cross platform VCL replacement, but that didn’t work very well.

–jeroen


Filed under: Delphi, Delphi XE2, Delphi XE3, Delphi XE4, Development, FireMonkey, OS X FMX, Software Development Tagged: component market, data binding, fmx, software, technology, vcl, windows controls

by jpluimers at May 01, 2013 04:04 PM

jed-software.com

Embarcadero: Don’t hide behind bad design

Recently I created an QC report to try and get the default wizard behaviour changed to be user friendly.

The issue is that the description text for the wizard item only shows when the mouse is hovered over the item. This means that keyboard navigation will never show the description nor will just opening the dialog initially, unless you magically have your mouse in the wrong spot.

Apparently, this is the way the wizard has been designed.

Report No: 115353 (RAID: 38977) Status: Closed
The mobile wizard doesn’t show a description using you hover over the item

http://qc.embarcadero.com/wc/qcmain.aspx?d=115353

Mobile Wizard comparison screen captures

Another item that is also “As Designed” is the text used to describe the blank application item in the wizard. This text states:

“The Blank Application Template is a jumping off point for creating a completely custom mobile application.”

Now I acknowledge that English was the subject I liked the least at school but that sentence could be improved.

Here are a couple of alternatives that I’ve thought about in the past ten seconds.

  1. “The Blank Application Template is the starting point for creating a custom mobile application.”
  2. “Use the Blank Application Template to create a custom mobile application.”

Perhaps you can add your own.

by JED at May 01, 2013 12:54 PM

FireMonkey Style – TStyleTag (Part 2)

Part 1 – http://jed-software.com/blog/?p=699

Along with the missing registration of TStyleTag, the following components cannot be used in styles without hand editing FMX or Style files.

  1. TFontObject
  2. TBrushObject

I’ve updated the package to now register these missing style components so you can use them in custom styles.

Download Package

The change is straight forward if you have already downloaded and installed the previous package.

The register procedure should now look something like this:

procedure Register;
begin
  RegisterComponents('Shapes', [TStyleTag, TFontObject, TBrushObject]);
end;

NOTE: You may want to register them to a different palette location.

 

by JED at May 01, 2013 12:31 PM

Fixing FireMonkey: TMemo/TEdit – OnExit

Currently in the Delphi XE3 release there is a bug in the OnExit processing of TMemo and TEdit (possibly others) controls.

Issue

If you make a change in a TEdit or TMemo control and then exit the control, after the OnExit event is called, another OnChange event is called. This shouldn’t happen.

This doesn’t occur in the VCL framework and shouldn’t happen in FireMonkey.

Solution

TEdit

The fix for the TEdit cause is pretty simple. Since the FNeedChange field in TCustomEdit is protected we can use a class cracker to fix it. You could put the fix into either a new control or in either an OnExit or OnChange handler in your application.

type
  TEditClass = class(TEdit);
...
procedure Form1.OnExit(Sender: TObject);
begin
  TEditClass(Edit1).FNeedChange := False;
end;

It’s interesting to note for TEdit, FNeedChange is protected. This is because in the TCustomEditBox descendant (used by TSpinBox and TNumberBox controls), the FNeedChange field is set to False after the overriden Change method is called. Perhaps this should have triggered the developer making that change, to actually fix the issue in the ancester class.

TMemo

The fix for TMemo is more interesting because unlike the TCustomEdit class, FNeedChange is private. Thankfully extended RTTI comes into play.

I put this code where the memo content was saved to disk, you could put the code in the same spot in your applications (if applicable), or place it in either OnChange or OnExit events.

var
  LCtx: TRTTIContext;
  LField: TRttiField;
  LInst: TRttiInstanceType;
begin
  // save your memo contents
  LInst := LCtx.GetType(Memo1.ClassType).AsInstance;
  LField := LInst.GetField('FNeedChange');
  if LField <> nil then
    LField.SetValue(Memo1, False);
end;

If your save is triggered by the user selecting a control that takes focus from the memo, the OnExit event will trigger before executing the fix above. Under these circumstances, moving the fix to the OnExit event of the memo is advised.

Another TMemo Issue

The OnChange event is only triggered after typing two characters in a TMemo, the first character typed into the memo doesn’t trigger the OnChange event.

by JED at May 01, 2013 12:28 PM

FireMonkey: Extending TFloatAnimation to support maximum loops

Background

In response to a QC report I wrote early last year I decided to implement a LoopCount property on the TFloatAnimation component.

Report No: 105140 Status: Open
Add a LoopCount property to the TAnimation class
http://qc.embarcadero.com/wc/qcmain.aspx?d=105140

Class Definition

  TJSCustomLoopCountFloatAnimation = class(TFloatAnimation)
  public
    type
      TAnimationLoopEvent = reference to procedure (Sender: TObject; const LoopNumber: Integer; var Cancel: Boolean);
  private
    FLoopCount: Integer;
    FCheckingLooping: Boolean;
    FOnLoop: TAnimationLoopEvent;
  protected
    FLoopsComplete: Integer;
    procedure FirstFrame; override;
    procedure DoLoop(var ACancel: Boolean); virtual;
    procedure ProcessAnimation; override;
  public
    constructor Create(AOwner: TComponent); override;
    property LoopCount: Integer read FLoopCount write FLoopCount default 3;
    property OnLoop: TAnimationLoopEvent read FOnLoop write FOnLoop;
  end;

Nothing that interesting in the new descendant. New property called LoopCount to control the number of loops and a new event that gets triggered each time a loop completes.

The published component publishes the new property and event but also changes the default values for two existing properties. It makes sense to set Loop to true when the new class is for enhancing the looping ability and if you’re looping, generally AutoReverse will be set to true.

  TJSLoopCountFloatAnimation = class(TJSCustomLoopCountFloatAnimation)
  published
    property AutoReverse default True;
    property Loop default True;
    property LoopCount;
    property OnLoop;
  end;

Implementation

I won’t post all of the code here because you can download from the link provided below, just a couple of snippets.

We need to override the FirstFrame method to initialise a couple of variables we use.

  • Checking to see if the LoopCount property is valid (raise an exception if it isn’t)
  • Initialise the variable to zero that counts the interactions
  • Make sure we are going to be checking the animation process for loops

Most of the work occurs in the overridden ProcessAnimation method.

procedure TJSCustomLoopCountFloatAnimation.ProcessAnimation;
var
  LCtx: TRttiContext;
  LType: TRttiType;
  LField: TRttiField;
  LCancel: Boolean;
begin
  inherited;
  if FCheckingLooping then
  begin
    LType := LCtx.GetType(Self.ClassInfo);
    if Assigned(LType) then
    begin
      LField := LType.GetField('FTime');
      if LField <> nil then
      begin
        if LField.GetValue(Self).AsExtended = 0 then
        begin
          Inc(FLoopsComplete);
          LCancel := False;
          if FLoopsComplete > 1 then
            DoLoop(LCancel);
          // The first time through, FTime is 0 so we need to offset this by
          // adding 1 when checking for completion
          if LCancel or (FLoopsComplete = LoopCount + 1) then
          begin
            LField := LType.GetField('FRunning');
            if LField <> nil then
              LField.SetValue(Self, False);
          end;
        end;
      end;
    end;
  end;
end;

Thanks to extended RTTI we can access a couple of private fields that we need to determine if a loop has been completed. This occurs when the FTime variable is zero. There is one issue with using this value and that is that the first “Loop” should be ignored since the first time ProcessAnimation is called FTime is zero so by the logic used, a loop has completed. This is why the DoLoop method is only called if the FLoopsComplete variable is greater than one.

Naturally it is possible to handle this one-off situation differently using a “First Time Through” variable but under the circumstances, I decided to go with the solution in place.

Once the LoopsComplete value is one greater than the LoopCount (refer to the above two paragraphs if you’ve already forgotten about why) the private field FRunning is set to False. Setting FRunning to false, stops the animation immediately.

Why not just call the public Stop method instead of going to the trouble of setting a private field? The answer to that is found in the ProcessTick method of the animation control (incidently, why isn’t this method virtual?).

  ...
  ProcessAnimation; // <==== We set FRunning to false here
  DoProcess;

  if not FRunning then
  begin
    if Assigned(AniThread) then
      TAniThread(AniThread).FAniList.Remove(Self);
    DoFinish;
  end;
  ...

By setting FRunning to false within our ProcessAnimation override, we are avoiding another frame being processed before the animation is stopped. This is because the Stop method calls ProcessAnimation and DoProcess as well.

Download

You can download the component and a cheesy demo application from the link provided. There is no package for the component to install it into your IDE, this is left as an exercise for the reader :-) .

Loop Animation Demo (short video – 39KB)

Download LoopCount Component and Demo

NOTE: Before downloading the source code you must agree to the license displayed below.

License Start




This space intentionally left blank…



License End

by JED at May 01, 2013 12:28 PM

XE4 Mobile Tip #1 – Disable the GPU Canvas

If you don’t like circles with jagged edges, you can disable the GPU canvas.

Using the GPU Canvas:

GPU Canvas

Not using the GPU Canvas:

Non-GPU Canvas

Full image comparison at 200% using Beyond Compare. Click to enlarge to full size (2600 x 1540).

Canvas Comparison

NOTE: If you see other drawing issues, enable the GPU canvas again just to see if it is a canvas issue.

Disabling the GPU Canvas

To disable the GPU canvas you must modify the project file source.

Add FMX.Platform and FMX.Consts to the uses clause. I suggest adding these items after the FMX.Forms entry but before any other units. You MUST leave System.StartUpCopy as the first unit in the uses clause.

Before Application.Initialize is called, enter this line:

TPlatformServices.Current.GlobalFlags.Add(GlobalDisableiOSGPUCanvas, True);

by JED at May 01, 2013 12:28 PM

XE4 Mobile Tip #2 – Loading local HTML content

I’ve already answered this on the newsgroups however it deserves a little more attention.

The most important thing to do when deploying additional files with your app is to make sure they are prefixed with “StartUp/”. This tells the deployment manager to deploy these files with the application and place them in the folder specified after the StartUp/ prefix. This prefix is case sensitive.

Here is a screen capture of the deployment manager for the sample project available for download at the end of this post.

Deployment Manager

Verify file is included without running the app

You can even verify that the files have been deployed with the app by looking in the Applications section of your device in the XCode Organizer.

XCode Organizer

Sample code

The code below loads the content of the file into the WebBrowser control that is on the form.

unit Unit288;

interface

uses
  System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types,
  FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.WebBrowser, FMX.StdCtrls, FMX.Layouts;

type
  TForm288 = class(TForm)
    LoadHtmlButton: TButton;
    WebBrowser1: TWebBrowser;
    Layout1: TLayout;
    procedure LoadHtmlButtonClick(Sender: TObject);
  end;

var
  Form288: TForm288;

implementation

uses
  IOUtils;

{$R *.fmx}

procedure TForm288.LoadHtmlButtonClick(Sender: TObject);
var
  LFilename: string;
begin
  LFilename := TPath.GetDocumentsPath + '/index.html';
  if TFile.Exists(LFilename) then
    WebBrowser1.Navigate('file://' + LFilename)
  else
    MessageDlg(Format('File not found: %s', [LFilename]), TMsgDlgType.mtError, [TMsgDlgBtn.mbClose], 0);
end;

end.

Works on my device!

Device Test (portrait)
Device Test (landscape)

Download the Code

Download the sample project.

A couple of notes

  • You wouldn’t deploy a static file to the Documents folder unless you wanted it to be backed up (via iTunes or iCloud) with other user data.
  • The best location for static files is Library/Application Support/, this is content that is generated when the application runs, or is included with the application.

by JED at May 01, 2013 12:27 PM

Te Waka o Pascal

iOS “Support” Prior to XE4 ?

Some people have taken issue with my chagrin at the way in which iOS support has been mis-handled in Delphi, implying or in some cases directly stating, that iOS was only ever in beta before and so I had no right to expect “real” product to be delivered at no extra cost. I take issue [...]

by Deltics at May 01, 2013 12:51 AM

April 30, 2013

Te Waka o Pascal

Qualified Enum Reference That Fails to Compile in XE4 (and rightly so)

Running through some of my code last night, putting them through the new XE4 compiler, threw up a real oddity: Some code that used to compile just fine, which no longer compiles in XE4 and which should not have compiled before! It’s an odd one, because the code previously compiled – and worked – as [...]

by Deltics at April 30, 2013 08:52 PM

Behind the connection

Delphi XE4 MS-Office components

Delphi XE4 is delivered with 3 sets of Microsoft Office components (Word, Excel, Outlook, Power Point and Access): Office 2000, Office XP and Office 2010. None is installed by default. To install Office components, you must launch the IDE, select "Component" menu and then "Install packages". In the list shown, you'll find "Microsoft Office 200 sample Automation Server Wrapper Components" and

by François Piette (noreply@blogger.com) at April 30, 2013 07:47 PM

Daniel Magin's Logfile

Using InterBase Lite and InterBase ToGo in Delphi iOS Applications – Step by Step Guide

Using InterBase Lite and InterBase ToGo in Delphi iOS Applications - Step by Step Guide

With RAD Studio XE4 a new InterBase edition has been rolled out. The existing InterBase edition family (Server, Desktop, Developer and ToGo) has been enhanced by an edition called “IBLite”. This edition may be deployed for free with your applications. IBLite uses the embedded deployment model similar to the InterBase “ToGo” edition, some limitations apply though. Following is an overview of InterBase editions and their features and limitations:

 Bildschirmfoto 2013-04-23 um 09.16.33

(click on Images to enlarge)

The most important IBLite limitations are:

  • Max. 100MB database size 
  • Max. 1 simultaneous transaction

If you need more space or transactions, then your other (paid though) option for iOS devices is the “ToGo” Edition. On mobile devices 100 MB with one transaction is very likely to be sufficient though.

Developing and Deploying InterBase Applications for iOS Devices

All following steps are identical for IBLite and InterBase ToGo.

License Keys

RadStudio XE4 comes with a free IBLite serial key and an InterBase ToGo serial key for test deployments. The ToGo serial key may only be used for testing deployments and is not meant to be published with apps to the App Store. To go into production with InterBase ToGo you need a separate InterBase ToGo deployment license. Please contact you local Embarcadero office for pricing and terms. The IBLite key that comes with XE4 is good to be used in production environment - it is completely free!

The keys look like this:

IBLite XE3 for iOS Deployment License

AAAA-BBBBBB-CCCCCC-DDDD

InterBase XE3 ToGo Test Deployment

AAAA-BBBBBB-CCCCCC-DDDD

 The InterBase version that comes with RAD Studio XE4 / Delphi XE is „XE3“ - so don‘t get confused on the version numbers.

You need to register the keys and create a REG______.txt file, which will be deployed onto the device together with your app. 

Update 1:

Thanks to  Sriram Balasubramanian - Engineering Team Lead, InterBase - Embarcadero Technologies Inc. for the update how the real final email are looking for IBLite and Delphi iOS Users.

RAD Studio XE4 users -- who have the mobile bits turned on for iOS development -- also get a IBLite S/N in their RAD registration email. In order to get a deployable IBLite license file, all they need to do is click on the URL provided in the email, and enter the IBLite S/N they received and registration code mentioned in the email. Once this is entered, the web page will automatically show a supplemental terms and conditions that the user needs to accept for distributing this license with their iOS application (just one click). Once this is agreed to, the user is presented with the reg_*.txt file that they can either email to themselves or download to their computer so it can be included with their application bundle via Project | Deployment file list.

All instructions to help the developer do the above are presented once they click on the registration URL.

The Users get a email message like this:

Note:

This Embarcadero product also entitles you to a free IBLite for iOS database deployment license. To activate your deployment license, go to https://reg.codegear.com/srs6/activation.do and enter the IBLite for iOS serial number above and Registration Code: xxxxxx.

The registration process is a little tricky and hopefully Embarcadero will make that more convenient in the future. If anyone knows shortcuts to this process, then drop me a note, so that I can update this documentation.

After installing InterBase XE3 Developer Edition (which is usually done by the installation process of RAD Studio XE4) you need to launch the Embarcadero License Manager. The License Manager can be found in the InterBase bin directory.

 These are the default location of the InterBase bin directory:

 Windows 64bit

C:\Program Files (x86)\Embarcadero\RAD Studio\11.0\InterBaseXE3\bin\ LicenseManager.exe

Windows 32bit

C:\Program Files\Embarcadero\RAD Studio\11.0\InterBaseXE3\bin\ LicenseManager.exe

In the LicenseManager select Serial - Add from the Menu

In the „Add Serial Number“ Dialog type in your IBLite or InterBase ToGo key and Press OK.

Now your key should show up in the Treeview under „Unregistered serial numbers

License Registration

All license keys need to be registered with Embarcadero, to do so, open the context menu for the key you just entered and click „Register

The Embarcadero Product Registration Dialog will pop up. That is the same dialog you have seen after you installed RAD Studio /Delphi itself

The next Step is VERY IMPORTANT and different from the RAD Studio / Delphi registration process:

The online registration process does not work using this dialog, unfortunately. So, in other words: DO NOT REGISTER ONLINE with this dialog!

Did I mention this already?

DO NOT REGISTER ONLINE with this dialog!

Once again:

DO NOT REGISTER ONLINE with this dialog!

Remember:

DO NOT REGISTER ONLINE with this dialog!

Instead, open your Web browser and go to https://reg.codegear.com 

Yes, use the CodeGear domain name as the SSL certificate is still under CodeGear‘s name and not under Embarcadero‘s. (Embarcadero Web master  - I am looking at you SSL certificates are not that expensive any more. Certificate errors on embarcadero.com are ☺). 

Enter your Serial Number and Registration Code from the LicenseManager into the Web form:

Enter your Serial Number and Registration Code from the LicenseManager into the Web form:

Bildschirmfoto 2013-04-30 um 14.37.08 

Press „Next“ in the Web form. The next step requires you to login with your Embarcadero EDN Account credentials.

 Bildschirmfoto_2013-04-23_um_10.27.06

After pressing „Next“ again, you should get the following „Product Registration“ Web form:

 Bildschirmfoto_2013-04-23_um_10.30.47

At the very bottom of that Web form you will find options to download or send per email  an activation file for InterBase.

 Bildschirmfoto_2013-04-23_um_11.01.43

This activation file comes as REG___.txt, which you need to add to your iOS App, to get InterBase unlocked.

 First, rename REG____.txt, depending on the edition you have chosen:

  • reg_iblite.txt (IBLite)
  • reg_ibtogo.txt (InterBase ToGo)

Copy the registration file(s) to:

C:\Users\Public\Documents\InterBase\redist\InterBaseXE3

Now you are ready to to develop your first iOS Application with RAD Studio/Delphi XE4 and InterBase

Sample Application

Create an new FireMonkey Mobile Application

Bildschirmfoto_2013-04-23_um_11.09.23

Add a TButton and a TListbox to your blank main form.

Bildschirmfoto 2013-04-23 um 11.12.30

Now add a new connection to the employee sample database. To do so open the Data Explorer Window in Delphi and select „Add New Connection“ under the IBLite/ToGo tree item and name the connection „Employee“.

 Bildschirmfoto_2013-04-23_um_11.17.07

In the Connection Configuration dialog add the path to Employee.gdb. This file can usually be found in Delphi‘s Sample folder, under „Data“. Default user name is „sysdba“, default password is „masterkey“ (without quotes). See the screenshot for details:

Bildschirmfoto 2013-04-23 um 11.16.51

 

Double click / open the new „employee“ tree node to see all tables, that come with Employee.gdb.

Bildschirmfoto 2013-04-23 um 11.20.29

Now drag and drop „employee“ from the tree onto your main form. This will automatically create a correctly configured TSQLConnection component on your form:

Bildschirmfoto_2013-04-23_um_11.22.05

Remarks: In my sample I am storing Employee.gdb on the iOS device under 

/Documents/data/employee.gdb. Of course you can use any directory which is available to your app on the device. Using the Documents folder has the advantage that everything in here will be included in the iOS Device backup process. This is true for local backups with iTunes or iCloud backups. The /tmp/ folder in contrast would not be backed up.

 To connect to the database at runtime (on the iOS device that is), an IFDEF IOS is used in the „BeforeConnect“ event of the TSQLConnection to set the path to the database file.

Bildschirmfoto 2013-04-23 um 11.26.53

In the „ButtonClick“ event add the following code:

Bildschirmfoto 2013-04-23 um 12.01.11

Before running the App on the iOS simulator or iOS device we have to add some items to the Deployment Manager in which can be opened via menu item „Project - Deployment“

Bildschirmfoto_2013-04-23_um_11.36.36

The Deployment Manager lists all files that get bundled and deployed with your App on the device. Important to note is that all items have a local path (on your development machine) and a remote path on the iOS device:

Bildschirmfoto 2013-04-23 um 11.38.31

You need to add InterBase client files and the license file  that you created earlier.

Remarks: Select „All Configurations“ in the Deployment Manager. Otherwise you will have to perform these steps for Simulator, Device and Debug/Release configurations separately.

First add some items from the „Featured Files“ dialog:

 Bildschirmfoto_2013-04-23_um_11.44.57

For IBLite use „InterBase ToGo“ too, as the different behavior between IBLite and InterBase ToGo is controlled by the license file.

 After adding these items you will find them in the Deployment Manager‘s items list. You will also see two license files: reg_iblite.txt and reg_ibtogo.txt. Make sure that only ONE of them gets deployed, i.e. disable or remove either of them.

Bildschirmfoto_2013-04-23_um_11.48.10

Now add the EMPLOYEE.GDB File to Deployment Manger:

Bildschirmfoto_2013-04-23_um_11.50.53

After adding the file you need to change its remote path for the simulator and the device! To do so, double click the „Remote Path“ cell. Enter: „StartUp\Documents\data\

 Bildschirmfoto 2013-04-23 um 12.00.36

Now save all files and run your first InterBase App on the iOS Device.

Bildschirmfoto 2013-04-23 um 12.02.08

Good luck and have fun 

Daniel Magin , Olaf Monien, Daniel Wolf

info ( a t ) Developer-Experts.net

Embarcadero MVP

by dmagin at April 30, 2013 12:44 PM

Behind the connection

Getting Network Share List

Network neighborhood can be obtained programmatically in any application. It’s just a matter of a single Windows API call to the NetShareEnum function. MSDN publish the complete description of NetShareEnum at http://msdn.microsoft.com/en-us/library/windows/desktop/bb525387(v=vs.85).aspx Since Delphi doesn’t provide the definition, we have to define it our self. With the help of MSDN we find

by François Piette (noreply@blogger.com) at April 30, 2013 10:11 AM

DelphiTools.info

Gaining Visual Basic OLE super-powers

Visual Basic in its various incarnations and off-springs has super-powers when it comes to OLE Automation, aka late-bound COM through IDispatch.

Super Powers?

For instance, when doing MS Word OLE automation, you can in VBS and VBA write things like

WordApp.Documents[1].Name

which in Delphi (and many others) has to be written as

WordApp.Documents.Item(1).Name

and it can also call some methods like

set v1 = WordApp.CentimetersToPoints(2.5)
set v2 = WordApp.InchesToPoints(2.5)

which Delphi, FreePascal, PowerBasic, Python, C++’s CComPtr and others are unable to call, and which instead result in an “unspecified error” without further description.

While trying to solve the above riddle, I found posts about it for various languages and frameworks, dating back to the beginning of the millennium with no solutions, just specific workarounds.

Until today that is, bit thanks to David Heffernan and Hans Passant, two StackOverflow super-stars.

The reason is that some “methods” like CentimetersToPoints aren’t methods, they’re really indexed properties that you can’t call as indexed properties (ie.  WordApp.CentimetersToPoints[2.5] will fail in Delphi as well).

The Magic Potion

If you want to get the same super-power, the fix is basically to not follow the spec when calling IDispatch.Invoke, and instead of using DISPATCH_METHOD, use DISPATCH_METHOD or DISPATCH_PROPERTYGET.

In Delphi’s ComObjDispatchInvoke function that means the

end else
  if (InvKind = DISPATCH_METHOD) and (ArgCount = 0) and (Result <> nil) then
    InvKind := DISPATCH_METHOD or DISPATCH_PROPERTYGET;

should be changed to just

end else
  if (InvKind = DISPATCH_METHOD) then
    InvKind := DISPATCH_METHOD or DISPATCH_PROPERTYGET;

And the call will now go through. So all the previously mentioned languages and environment that follow the spec are doomed to fail.

Similarly, investigations have showed that for some OLE automation properties “get” to pass, you need to use DISPATCH_METHOD or DISPATCH_PROPERTYGET, and using just DISPATCH_PROPERTYGET will fail.

Speculations

There is a suspicious bit in the MSDN documentation for Getting and Setting properties:

 Properties are accessed in the same way as methods, except you specify DISPATCH_PROPERTYGET or DISPATCH_PROPERTYPUT instead of DISPATCH_METHOD. Some languages cannot distinguish between retrieving a property and calling a method. In this case, you should set the flags DISPATCH_PROPERTYGET or DISPATCH_METHOD.

Do you know a language that can’t distinguish between properties and methods? Visual Basic.

Given that Visual Basic was a primary user of OLE Automation, it’s likely using DISPATCH_PROPERTYGET or DISPATCH_METHOD all the time indiscriminately, so I’ll speculate that at some point, using both dispatch flags became the effective spec. I suppose Raymond Chen might be able to provide some further insight?

Bottom Line

DWScript COM Connector now has the same OLE Automation super-powers, and it’ll work without modifying the ComObj unit.

The COM connector uses its own IDispatch.Invoke wrapper, distinct from Delphi, which is incidentally also capable of working with Single precision floats (requires a workaround in Delphi).

by Eric at April 30, 2013 06:53 AM

Te Waka o Pascal

Adding Insult to Injury

Having just installed Delphi XE4 “Professional”, provided as part of my employer’s current SA, the initial “Welcome” to the new version, and seemingly the “baked in” Start Here landing page invites me to set-up Delphi for iOS development: And this for a product that doesn’t actually include this capability because we haven’t paid for it. [...]

by Deltics at April 30, 2013 02:43 AM

April 29, 2013

Behind the connection

Delphi XE4 and AnsiString

I already ported a lot of my applications to Delphi XE4. This represent hundreds of thousands lines of code. All in all this was very easy, coming from XE3. There is only one changed feature that forced me to slightly update my source code: in XE4, all AnsiString routines have been moved to a new unit named System.AnsiStrings. I had to add this unit where ever I used on of those routines. If you

by François Piette (noreply@blogger.com) at April 29, 2013 12:42 PM

April 28, 2013

The Wiert Corner - irregular stream of stuff

twm’s blog

experimental GExperts + code formatter for Delphi XE4

There isn’t yet any official release of GExperts for Delphi XE4 but if you don’t mind a little bit of manual work for installing, you can have it anyway.

WARNING: I have just now made this version compile with Delphi XE4. I have not done any tests. You are on your own and responsible for any damage this version might do to your computer and your files. If you don’t accept this responsibility, do not download the software!

Download
GExperts-XE4-1.37-experimental-twm-2013-04-28.zip
and unpack it to a folder of your choice
(e.g. c:\program files\GExperts for RAD Studio XE4)
Copy the expert you want to use from one of the subdirectories created:

  • EditorExpert
  • RegularExpert

to the main directory.

Use the ExpertManager tool to register GExperts to Delphi XE4.
Voila, you are done.

This version is based on the current source code from the GExperts svn repository. I have not released it for any other Delphi versions because nothing has changed since the last release.

by dummzeuch at April 28, 2013 01:12 PM

Delphi Haven

FMX anti-pattern: returning nil rather than raising an exception on an invalid state or arguments

In the Delphi RTL and VCL, a method called LoadFromFile or the like will raise an exception if the file doesn’t exist or is invalid. Similarly, if an object property getter implements a lazy-loading pattern (meaning, the value of the property will only be initialised when first needed), it will raise an exception if the situation is such that nothing valid can be loaded or initialised. This is pretty basic exception programming – when an error arises, the flow of the calling code is forcibly interupted with a clear account of what call was invalid. Imagine if (say) TBitmap.LoadFromFile didn’t raise an exception when the file name passed to it didn’t refer to a valid bitmap file – calling code could go happily on its way assuming a graphic has been loaded when it hasn’t. Likewise, what if the Items property getter for TList<T> just returned nil (or equivalent) with an out of bounds index? If T is a class type, then off-by-one errors in the calling code will end up with cryptic access violations later on that might be nowhere near where the erroneous call was actually made!

Alas, but such basic understanding of exception programming is not grasped by at least one developer on the FMX team. Repeatedly across the XE2, XE3 and now (I learn) XE4 releases, methods that an experienced Delphi programmer would expect to raise an exception when nothing valid can be returned do not. As soon as one case is fixed – e.g., the TFmxObject.Children property getter was done so in XE3, albeit implicitly – another one or two are added, and frankly, it needs to stop now. The latest cases I learn are the HScrollBar and VScrollBar property getters on TScrollBox – done properly in XE3, the anti-pattern has however been introduced in XE4, causing ‘random’ access violations in TMemo (the FMX TMemo inherits from TScrollBox).


by Chris Rolliston at April 28, 2013 10:30 AM

Behind the connection

Enabling floating form designer in Delphi XE4

Delphi XE4 has an interesting feature removed from previous versions: the floating VCL form designer. You can enable it again easily, at your own risk. While the IDE is not running, launch the registry editor, locate the key  HKEY_CURRENT_USER\Software\Embarcadero\BDS\11.0\Form Design and set the "Embedded Designer" to False. Note: Don't do that if you use FireMonkey. It's form designer

by François Piette (noreply@blogger.com) at April 28, 2013 11:25 AM

April 27, 2013

PARMAJA

MiniLib on Git

MiniLib, http://sourceforge.net/projects/minilib/

Git now is the version control,  instead of SubVersion, for 2 of reasons.

1 – I like to work offline, commenting and show log, while I can’t have a permanent internet connection.

2 – Branching merging, it merge the full history from where to everywhere.

But I still like the version numbers in SVN it is more useful and it is easy human trace the changes.

by Zaher Dirkey at April 27, 2013 01:37 PM

It's a blong, blong, blong road...

Delphi for iOS (aka Delphi XE4 aka RAD Studio XE4) has appeared

We’ve heard lots of noises about Embo’s pending Delphi support for iOS over the last 6 months or more and now the wait is over.

RAD Studio XE4 Installer

The iOS support has arrived, but not as the largely expected add-on to XE3, but instead as a new version: XE4 (available with or without iOS support). Delphi XE4 has arrived (along with C++Builder XE4 and RAD Studio XE4) and now targets:

  • 32-bit Windows
  • 64-bit Windows
  • 32-bit OS X
  • iOS Simulator (Intel)
  • iOS (ARM)

There is a flurry of activity about this new release over the blogosphere and here’s a summary of the key points regarding information about the product and regarding the product itself.

Information

Product details

The main thrust of this release is the Delphi support for iOS, specifically two new cross-compilers that support targeting the iOS simulator (Intel) and native iOS (ARM) called dccios32.exe and dcciosarm.exe.

As you might expect there have been a raft of changes in FireMonkey to support this wider platform range and improve the existing platform support. Indeed FireMonkey has now changed from being known as FM2 to now being FM3. The online help has much information on the changes to FireMonkey.

The IDE has new mobile form designers (no longer floatable although see François’ post here if you really want a floating designer for VCL development) and new target platforms to get your app on the simulator or iOS device. Of course FireDAC is in the box too.

InterBase ToGo is now supplied as an option for an embedded database in your application, including iOS applications. Note that InterBase ToGo requires a license to be bought, whereas IBLite does not (and also does not support encryption, more than 1 core, more than 1 connection, etc.). More info on InterBase ToGo is available in this quick-start guide.

iOS support has been added for SQLite, IBExpress and the MIDAS client components (notably TClientDataSet).

The iOS compilers introduce the Next Generation Delphi language, which some of you will have seen hints of in the Delphi XE3 source code via the NEXTGEN conditional compilation symbol that is checked for in many places. This Next Generation Delphi support is currently only available in the iOS compilers, though it’s a safe bet we’ll also see it in the Android compiler, whenever that appears.

The Next Generation Delphi compiler takes the opportunity to off-load some aspects of the Delphi language that are a little archaic and at the same time bring in some new helpful features.

Things that have gone/changed include:

  • Some of the many string types have gone (AnsiString, UTF8String, RawByteString, WideString, AnsiChar, PAnsiChar, PWideChar, OpenString, ShortString) leaving just the basic type string , an alias for UnicodeString.
  • Pointer support is gone. For interfacing with external library APIs there is a new TMarshaller record, which works with the TPtrWrapper record.
  • Strings are 0-indexed instead of 1-indexed by default. It is recommended you employ TStringHelper (introduced in XE3) to work with strings as it knows about the string indexing on the different platforms.
  • Strings are to be considered immutable. Currently you can change string contents but will get a warning for your trouble. This is to encourage you to change the code to use a TStringBuilder to build a new string. Future versions may change the warning to an error.
  • Inline assembler support is gone.
  • You are advised to rewrite code that uses with as this is likely to be removed in future versions. I can see the benefit in enforcing this, as I have bumped into so many scope errors caused by over-zealous with usage over the years…

New things include:

  • Automatic Reference Counting (ARC) for objects.
  • Weak references
  • Atomic intrinsic functions:
  • New predefined conditional symbols (* the content of this table is subject to change based on proper testing - the corresponding documentation page is incomplete/incorrect, so some educated guesswork has gone on thus far):
    Symbol:

    Defined:

    For compilers:
    AUTOREFCOUNT if ARC is available dcciosarm, dccios32
    CPUARM if the CPU is ARM-based dcciosarm
    EXTERNAL_LINKER for compilers with an external linker dcciosarm, dccios32
    IOS target platform is iOS dcciosarm, dccios32
    NEXTGEN for Next Generation Delphi compiler dcciosarm, dccios32
    UNDERSCOREIMPORTNAME for compilers that add leading underscores when importing libs dcc32, dccosx, dccios32
    WEAKREF for compilers that can use weak references dcciosarm, dccios32
    WEAKINSTREF when weak references are defined for instances dcciosarm, dccios32
    WEAKINTFREF when weak references are defined for interfaces dcciosarm, dccios32
  • New compiler directives:
    • {$ZEROBASEDSTRINGS ON/OFF} controls whether 0-based or 1-based string indexing is active. You can, for example, use this to force 1-based indexing in mobile code that you haven’t yet updated
    • {$EXTENDEDCOMPATIBILITY ON/OFF} allows use of Extended data type on platforms that do not normally support it (Win64 and iOS). The given support offers the expected 10 bytes storage but doesn’t offer the higher floating-point support that Win32 Extended gives.
  • New compiler attributes:
    • [volatile] to indicate the field may be changed by other threads (it’s a hint to the code optimiser).
    • [weak] to mark a weak reference.
    • [Ref] to ensure constant parameters are passed by reference rather than by value.

Given these changes there is a page that talks about how to migrate code from the desktop to iOS.

Taking all the above onboard, it looks currently like Embo offer a common component framework (also, slightly confusingly, referred to as a platform) to program against for different target platforms (Win32, Win64, OS X, iOS) in FireMonkey (aka FMX aka FM3). As for your Delphi code, however, it would currently appear that desktop code and mobile code will look a bit different, thanks to the string changes (1-indexing to 0-indexing and the push towards immutability) and of course the specific form factors of the UI on the respective platforms.

So, you build a mobile UI and you build a desktop UI. With the desktop UI you take great care to ensure the app looks like a Windows app when compiled for and running on Windows (menu layout, button order and placement on dialogs), and looks like a Mac app when compiled for and running on OS X.

Then when you come to build the code base, you write it once for the desktop using all the standard Delphi-desktop paradigms of creating objects and ensuring they are destroyed with try/finally/free/end. On the mobile side you skip all that and let objects be cleaned up by ARC, and ensure weak references are specified where appropriate.

I’m sure the desktop compiler will catch up with these changes at some point, but in the interim there is a requirement for quite a bit of conditional compilation, or making use of no-op calls in the mobile code. And if/when the desktop compiler catches up, that will potentially force a big hit in massaging desktop code into the new realm of Next Generation Delphi.

It’s all a bit up in the air as to how things will pan out, but to my eyes currently, the only common thing is the FireMonkey framework. Other than that, the coding and design looks to require dedication per platform targeted. Which is no bad thing. In my opinion, when targeting a given platform you should put some effort into making sure the application works gracefully and looks in keeping with its peers.

With that mindset in place, the iOS support looks pretty neat and the changes to the language make Delphi behave a little more like many of the other popular languages in existence. I’ve certainly got no issues with kicking out with and dropping to a single string type. Let’s just be careful to not play the “write once run anywhere” card too frequently, eh?

[Updates]

I added a link to François Piette’s article about re-enabling the floating form designer (only advisable if you develop solely for VCL).

I added a link to the QC fix list for XE4.

by Brian Long (noreply@blogger.com) at April 27, 2013 09:37 AM

April 26, 2013

DelphiTools.info

What would get you to buy a newer Delphi version?

This is a practical poll question, what would get you to buy a newer Delphi version?
What would you like to see most and foremost, and would most have a use for?
To force you to choose, you can only pick two items!

Note: There is a poll embedded within this post, please visit the site to participate in this post's poll.

by Eric at April 26, 2013 07:19 AM

April 25, 2013

The road to Delphi

Delphi Code Monkey

Hey Marco, Here's how to fix Delphi: Make it fast.

The title of this blog post is a bit provocative.  I think that Embarcadero is doing well with Delphi and I am excited about XE4.  I have been using it. But I need to complain today.

 I get paid to write Windows applications, and Delphi is still the best tool for that job.  But it needs some improvements. Here are the improvements that I believe would benefit everybody using Delphi.  Delphi's speed issues slowed me down today, and that's not acceptable.  I work with large applications in Delphi, some of which approach 1.5 million lines of code.  Delphi just doesn't handle them well.

1.  Ditch the Microsoft Document Explorer.  Even Microsoft has ditched it.    


2. Give me F1 context sensitive help that is faster than Googling or searching Stack Overflow.

3. Get rid of the 3-5 second delay popping down the Edit menu when you have a large project open.

4.  Fix the useless Error-Insight compiler.  Get rid of all the various parsers in your product and replace them all with one new one that can do all the parsing you need done.   The differences in the parser's support for various Delphi language features added between Delphi 7 and XE4 has resulted in the broken mess of code-insight, error-insight, and code-completion, not to mention code-formatting glitches.

5.  Learn from all the Java and C++ IDEs out there about using a background process to do do scans of the edit buffer so that it does not freeze up the editor, ever. It's never okay to block the user from inputting text while you have a big fat think. Never. Fix anything that freezes the editor long enough to cause users to lose data because the IDE is frozen while they were typing code.  This slowed me down and caused me to lose a good chunk of my productive working time today.


6. Some of my forms and data modules take 8 to 10 seconds to  open and become editable on a Xeon computer with 8 cores. This is just not cool.  What kind of stupid algorithms are you doing at DFM load time that could take 10 seconds to parse a DFM?  I could compile 100 megabytes of Delphi code in that time from the command-line compiler.




7. Make one checkbox in the preferences that says "Make it fast". Turn off all the slow stuff with that one checkbox, so that when what I need is an editor that has Delphi syntax highlighting, and a compiler and error list, it gets that right, and forgets everything else.

As cool as the Mac stuff is, and I will blog about how cool it is soon, what I want is a fast Delphi.




by Warren Postma (noreply@blogger.com) at April 25, 2013 05:23 AM

April 24, 2013

Andreano Lanusse | Technology and Software Development

Delphi XE4 official announcement coming

In general you expect a new version of Delphi around August, this year is going to be different, Delphi XE4 is coming next week.

I just heard that next week Embarcadero is going to announce Delphi XE4, which is part of RAD Studio XE4 and will include C++Builder XE4 and HTML5 Builder.

An important change initiated last year related to Prism (Delphi for .NET) will affect RAD Studio this year, I think you won’t see Prism included in RAD Studio, of course REM Objects continue to develop their compiler and integration with Visual Studio, so you will have order directly from them.

What’s new in Delphi XE4?

Delphi XE4 will bring Embarcadero’s new ARM compiler and will allow Delphi developers to compile FireMonkey apps to iOS devices at this point. The project around this new compiler started years ago, I had the opportunity to talk about this project with many Delphi developers, so the new compiler is really new and a beginning that will allow to move Delphi language much easier to other platforms, as you already heard Embarcadero is already promising Android support and it suppose to come soon.

The iOS support is going to be better them what you saw in XE2 and you are expecting something way better. A very important point is the focus on iOS, trying to make everything you use for Windows available on iOS is not the way to go, so in XE4 you will see what is specific for iOS when developing for iOS and this is good.

Of course Embarcadero will promote FireDAC as a new feature in XE4, even it came recently on XE3 still a good point to talk about this, since FireDAC is way better them dbExpress. I blogged about that recently and you can read here.

I believe you will see InterBase for iOS on this release, even you already have SQLite on iOS devices I see a lot of space for InterBase on iOS, especially for developers that need protect their data on mobile devices.

Upgrade and pricing

Embarcadero will release all the SKUs and upgrade paths. Early this year they mention about to release iOS support as add-on, maybe you will be able to buy just this piece, let’s wait and see.

There is a webinar scheduled for next Wednesday April 24th and it will show this new release.

I will be back in the following days and will share my comments about this release.

I just published an article covering What’s new in Delphi XE4 after the official launch, you can find that here.

Andreano Lanusse | Technology and Software Development
Follow me on Twitter: @andreanolanusse

by Andreano Lanusse at April 24, 2013 03:14 PM

Firebird News

CopyCat replication engine v. 3.04.0

Ladies and Gentlemen! Microtec Communications is pleased to announce a new release of CopyCat, version 3.04.0! You will find the full list of changes at the end of this email. This release also includes the changes from version 3.03.0, which had not been made publicly available till now. CopyCat is a Delphi / C++Builder component [...]

by jonneve at April 24, 2013 01:23 PM

DelphiTools.info

Not in (interpreted) Kansas anymore

dws-mirrorFor a few weeks now, an experimental JIT compiler has been available in the DWScript SVN for 32bits code. A more detailed article into the hows and whats and WTFs will come later.

Consider this article as an extended teaser, and a sort of call for test cases, benchmarks and eyeballs on the source code.

Following benchmarks were compiled in XE2 with full optimization, no stack frames and no range checking. Absolute values aren’t meaningful, just consider them relatively.

Mandelbrot fractal

bench_mandelbrot(lower is better)

Delphi XE2-32bit : 515
Delphi XE3-64bit: 162
DWScript JIT 32bit: 281

The JIT was initially tested on the Mandelbrot benchmark, so that’s one of the cases where JITing is almost complete, with the exception of the SetPixel() call.

SciMark 2

bench_scimark(higher is better)

Delphi XE2-32bit : 507
Delphi XE3-64bit: 682
DWScript JIT 32bit: 215

Delphi version uses pointers, DWScript version was slightly updated to use dynamic arrays instead  and JITting is partial at the moment.

The benchmark involves fairly large matrices, and DWScript use of Variant (16 bytes) rather than Double (8 bytes) means the data no longer fits in the CPU cache, which partly accounts for the poor showing of the JIT.

Array statistics

bench_array_stats(lower is better)

Delphi XE2-32bit : 208
Delphi XE3-64bit: 47
DWScript JIT 32bit: 63

This test measures of execution time of the following code (fully JITted), which computes the base values for common array statistics (range, average, deviation, etc.). The Delphi 32bit compiler really suffers because of Min/Max (despite having inlined them).

// "a" a floating point array of non-ordered values
for v in a do begin
   s := s + v;
   s2 := s2 + v*v;
   mi := Min(mi, v);
   ma := Max(ma, v);
end;

What next?

The DWScript JIT compiler relies on SSE2 to outperform the Delphi 32bit compiler, its current main limitations are:

  • JIT centers around floating point and a limited subset of integer and Boolean operations, the rest isn’t JITted yet.
  • Function calls aren’t JITted at the moment, and neither are a variety of other statements.
  • The JIT works with the same data structures as the interpreted engine, that means script debuggers and everything else works on JITted code as if it was still interpreted, but that also means the basic data unit is still the 16 bytes Variant at the moment.
  • The JIT register allocator is currently limited to floating point (ie. no integer or pointer allocations).
  • DWScript Integer type is 64bit sized, so for 32bit values, Integer performance is lower than what Delphi 32 can do, even though the JIT can generate typically faster code for it than the Delphi 32bit compiler does for Int64.

The JIT also suffers against a 64bit compiler as there are 64bit CPU instructions (and registers) not accessible in 32bit mode, but a 64bit JIT should be able to go farther.

If you’re interested and want to help, I’m currently looking for benchmarks and test cases, if you have code that compiles in both Delphi and DWScript,  particularly on integer maths (encryption, etc.) or object-oriented manipulations (graphs, trees…) that could help. You’re even allowed to have the Delphi version use pointers and other tricks, the comparison doesn’t need to be fair ;-)

by Eric at April 24, 2013 10:10 AM

Firebird News

Database Workbench 4.4.0 released

Upscene Productions is proud to announce the next version of the popular multi-DBMS development tool: ” Database Workbench 4.4.0 Pro ” For more information, see here. This version includes small new features, enhancements and fixes for issues as reported by our users. Changes include: improved SQL Insight improved stored routine debugging improved Unicode support And [...]

by Martijn Tonies at April 24, 2013 09:22 AM

The Wiert Corner - irregular stream of stuff

April 23, 2013

Behind the connection

Delphi XE4 is available

With Embarcadero RAD Studio XE4 you can create true native apps for PCs, tablets, and smartphones from a single code base, and get them to markets and users fast. True native apps run directly on the device, getting full access to all underlying capabilities, tighter security, and a better user experience. Try it! http://embt.co/RADXE4Trial Now you have one set of development tools to create

by François Piette (noreply@blogger.com) at April 23, 2013 10:19 PM

The Podcast at Delphi.org

52 – Marco Cantu & Delphi XE4 for iOS

The big news for Today, April 22nd, 2013 is the release of RAD Studio XE4 which includes the new Delphi for iOS. I thought it would be fitting to talk with Marco Cantu, long time Delphi author and supporter who recently took over as the Delphi product manager.

The big news for Today, April 22nd, 2013 is the release of RAD Studio XE4 which includes the new Delphi for iOS. I thought it would be fitting to talk with Marco Cantu, long time Delphi author and supporter who recently took over as the Delphi product manager.

by jim@delphi.org at April 23, 2013 06:02 AM

The Wiert Corner - irregular stream of stuff

jpluimers

You might think the below question on CodePage zero is Delphi related, but most of it is not.

It is about CP_ACP (the currently Active CodePage, and has some interesting observations:

CP_ACP is the major reason people have difficulties exchanging the data in text files between applications on different computers.

Oh and you can get the actual value of the active Active CodePage using GetACP, but CP_ACP isn’t always slower..

–jeroen

via: delphi – What is Codepage 0? – Stack Overflow.


Filed under: .NET, Delphi, Development, Software Development

by jpluimers at April 23, 2013 05:00 AM

April 22, 2013

Te Waka o Pascal

DPROJ Woes

I spent the best part of half a day last week trying to get to the bottom of a very strange issue on a project I was working on. I had just created a new unit in the project and had reached a point where I needed to add that unit to the uses list [...]

by Deltics at April 22, 2013 11:12 PM

Behind the connection

Serial Port Programming RS232 / RS485

Using the serial port is a common task and there are a huge number of components for doing that. I'm using TCiaComPort by Wilfried Mestdagh for years. It is a freeware with source code available at: http://www.mestdagh.biz/soft_components.html Recently, I have updated the source code for Unicode enabled Delphi versions. I use it with Delphi XE3 but it should be OK starting from D2009. My use

by François Piette (noreply@blogger.com) at April 22, 2013 09:33 PM

Delphi Code Monkey

Delphi Prism is dead, long live Oxygene.

I just learned that Rad Studio XE4 will not include the "Prism"  (delphi compiler for .Net) product in the bundle anymore.

I for one am not surprised.  RemObject's delphi-flavored "Oxygene" language that powered the "Delphi Prism" product (a rebranding of Oxygene, since day one) has been more of a threat to Embarcadero than an asset, since the move towards iOS ("Nougat") and Java.

Embarcadero has a really nice plan, a cross-platform-Delphi go-to-market strategy, and I believe that their plans and RemObject's plans have been on a collision course for some time. As a consumer who purchases products from both, I am happy.  As I should be.  Because that means there will be competition.  I believe that the perception from inside the Embarcadero camp might be that they are a serious producer of compilers and native-code-generation tools, and the idea that .Net based "JIT" is "native development" is laughed at inside the hallowed halls of Delphi's developers, the idea being that  Delphi's core compiler and IDE technology is of an order of magnitude more importance and sophistication than the tiny little product known as "Prism" inside the RAD Studio box, and Oxygene everywhere else.

I don't actively use Oxygene/Prism, but I'm definitely interested in both it, and in XE4's cross-platform abilities when they ship.  As I have already learned iOS and Objective-C I don't need anyone to spare me that learning curve. It's done.  But I could use a tool that will let me build one app and target more than one mobile platform at once.

RemObjects' products, including Oxygene, are powerful precisely because they are built on top of a big open source ecosystem (Mono on non-Windows platforms) and by being built atop .Net are also leveraging powerful .Net platform capabilities, on Windows.

Ironically, the era of doing your own compiler from scratch is drawing to a close as Embarcadero prepares for a future where a new llvm-based Delphi compiler allows for native-compilation on iOS, and Android.  This is an era of collaboration and an era of competition, at the same time.  While Embarcadero may be "big" compared to RemObjects, both are small compared to the real juggernauts in the software industry.  Microsoft has the Windows platform just about sewn up, and VisualStudio has a commanding presence on Windows.   As Embarcadero and RemObjects set sail on the "blue ocean" of cross-platform development I wish them both the best of luck.

My personal bet is on the Embarcadero horse, because I like the idea of an llvm-based compiler and no runtime overhead and full static optimizing compiler tech, on mobile, windows, and mac.  But if that falls short of its promise for some reason, I am glad that there is another horse in this race.  Having Embarcadero and RemObjects as competitors is better for me, the intended target market for both company's products.

I am not on any Delphi XE4 field tests or betas and the information in this post is based purely on what I have read in public websites.

Update:I was not aware that the ios apps emitted by nougat were native compiled binaries... However I do not consider the dalvik stuff any less of a jit based java tech, dalvik does do preJit compilation, just a change of degree not of nature. Optimizers happen at device load time and are less effective. There is still an overhead in dalvik but it is part of android and you don't redistribute any runtimes. So when I say "native" I mean non jvm and non jit. If I am truly mistaken here I ask to be corrected.
Update 2: I just read the docs for Xe4. Zero based immutable strings? What the hell were you thinking, Alan? I have reversed my bet and am now betting on remobjects. I guess oxygene strings are like .net strings and are thus zero based and immutable but if I have to bear that kind of semantic seismic shift I think I also would like it named something other than Delphi when you're quite finished turning delphi into objective c with begin and end keywords.oh well. I must admit that Arc is pretty damn cool, I forgive you Alan, I am still super excited to try this out when it ships! This is probably the price for using a string type in the new compiler which participates fully in objective c classes as a toll free bridged equivalent to nsstring.
Update 3: I plan a followup that covers the reality better as soon as I get hands on time eith both xe4 Rtm and Nougat RTM. Color me a possible Oxygene customer.

by Warren Postma (noreply@blogger.com) at April 22, 2013 06:02 PM

Andreano Lanusse | Technology and Software Development

What’s new in Delphi XE4?

This time you didn’t have to way a full year to see a new Delphi release, 8 months after XE3 release Delphi XE4 is out.

iOS development is the major topic of course and bring the second version of FireMonkey to iOS, a lot of expectation on this topic specially after XE2.

Also there is a bunch of new stuffs to talk about, like:

  • New Delphi compiler for mobile platform, which brings several changes in the language and set a future path to the Delphi language, obvious these changes will affect desktop development in the future and you need to start learning about that now.
  • The SQLite and InterBase support for iOS
  • ClientDataSet available on iOS
  • Several FireMonkey changes for iOS, componentes, new classes
  • Etc..

RAD Studio XE4 now includes only Delphi, C++Builder and HTML5Builder. Delphi Prism is no longer part of RAD Studio, the name is dead and from now you have to refer to Oxygene from RemObjects. You can check the official communication from RemObjects here, where Marc Hoffman provide more details about the future related to .NET development with Oxygene (old Prism) and their support to iOS and Android development.

Trial is already available here or if you prefer download the full Delphi and C++Builder ISO here.

The Delphi XE4 documentation has a extensive list of What’s new in Delphi and C++Builder XE4, below the table of content:

That’s it for now.

Andreano Lanusse | Technology and Software Development
Follow me on Twitter: @andreanolanusse

by Andreano Lanusse at April 22, 2013 03:33 PM

April 21, 2013

Delphi Haven

XE4 documentation is up

Just noticed this:

http://docwiki.embarcadero.com/RADStudio/XE4/en/What%27s_New_in_Delphi_and_C%2B%2BBuilder_XE4

I don’t know whether someone has jumped the gun or not, but from a ‘conceptual overview’ and ‘getting started’ POV it’s pretty comprehensive.


by Chris Rolliston at April 21, 2013 09:53 AM

April 20, 2013

Behind the connection

TabOrder blues

In every Windows form, the user is allowed to use the tab key to cycle thru all controls on the form. When building a form, the developer can select the tab order to fit his needs. For example if the form looks like a grid, he set tab order so that the focus goes horizontally first. Alternatively, he can select that controls are visited in column order. Of course the crazy developer can select

by François Piette (noreply@blogger.com) at April 20, 2013 08:38 PM

Subclassing a window

What is it? Subclassing a window is the process of intercepting all calls to the window procedure of a given window. When you subclass a window, you can get hand on every message sent/posted to the window you’ve subclassed. Why subclass? Why would you want to subclass a window ? For example if a windows does almost everything you want, but you need a few more features, you can change or add

by François Piette (noreply@blogger.com) at April 20, 2013 01:26 PM

April 19, 2013

Delphi Haven

Delphi XE4 pricing

It’s not exactly a ‘leak’ given it comes from an official promo video, albeit in Russian, but anyhow, the US pricing for Delphi XE4 has come out:

Screen Shot 2013-04-18 at 22.00.44

See here (for some reason, the video couldn’t show on Firefox, my usual browser, but it ran fine in Safari). In a nutshell, the XE4 upgrade will be a ‘nominal’ $49 for XE3 Professional edition owners uninterested in iOS support, or $499 if they are. In contrast, the upgrade cost from XE3 for Enterprise and above will be a flat $499. Slightly disappointingly (well, in my view at least), nothing clever has been done with the Starter edition – that remains Win32 only.

Does $499 (I shan’t guess the exchange rate for outside the US) fulfil the promise of iOS support being a ‘low cost add-on’ for XE3 Professional owners? Probably not, and while I’d prefer it lower, I’m not sure it’s particularly expensive for the market either:

  • RemObjects are currently running a ‘limited offer’ promotion for getting Oxygene for Windows, OS X, iOS and Android for $499. While this is more platforms than Delphi, at least for now, you’re only getting a vaguely Delphi-like language – ignoring the lack of a shared visual component library (which RemObjects are no doubt quite sincere in dismissing the very idea of), there’s no shared RTL either, at least at the level of Delphi’s, let alone .NET’s.
  • Xamarin sell their eponymous Mono-based tools for $299 per platform for ‘indie’ developers, and $999 per platform per seat for ‘business’ customers. Since only the ‘business’ (or beyond that, ‘enterprise’) edition comes with Visual Studio integration, if you want that, you’re looking at $2,697.30 (!) for all supported platforms (this includes a multiplatform discount). On the other hand, unlike Oxygene, you are buying a commercial licence for not just a language (C# in Xamarin’s case – and a very fine language it is too), but an extensive RTL (i.e., their implementation of the .NET BCL) and a dedicated IDE, which Xamarin ships alongside (or in the case of the ‘indie’ edition, instead of) its VS integration.

Of course, beyond pricing, there is the quality issue to consider too. Put briefly, it’s all very well promising the moon, but if you end up delivering a trip to a boggy field instead, the original promise will backfire. Time will tell…

[PS - I'd forgotten about Software Assurance when I wrote this post (silly!). I've no idea how that will be handled. Pure speculation, but maybe XE3 Professional users on SA will get iOS support, but with higher renewal charges kicking in if they want to keep it for later releases...?]

[PPS - Joylon Smith has posted further comments on his blog (link). As there's no point in fragmenting the discussion, please feel free to comment there, or the thread I started on Embarcadero's Delphi Non-Technical forum (link), rather than here.]


by Chris Rolliston at April 19, 2013 07:26 PM

Castle Game Engine news

Development: better Mac OS X support, networking, CAD level 2, more

view3dscene on Mac OS X, with nice icon, menu bar, file dialog
view3dscene on Mac OS X, with nice icon, menu
Model with textures loaded from network, URL dialog
CAD example model from http://www.web3d.org/wiki/index.php/X3DOM_CAD#X3D_Models

Hello everyone!

  1. There is a contest for best open-source project on Polish portal http://www.spinacz.edu.pl/. Please take a moment to vote for our Castle Game Engine!

  2. Our engine was submitted to devmaster.net, with lots of information and screenshots. You're welcome to review and rate us there!

  3. We also want to remind that we have a Google+ page about our Castle Game Engine, you can follow it to see (a little more frequent) news about our engine development.

New engine features in development:

  1. Mac OS X with native look. This is already much more user-friendly than our previous GTK-based releases for Mac OS X. See development details. Hopefully, this will allow us to release next view3dscene as normal Mac OS X application, that will be trivial to install for Mac OS X users.

  2. Network (http) support. Most "FileName" parameters and properties are now URLs. You can use protocols like file: and http: and data: everywhere, and of course http will be automatically downloaded. Try view3dscene from snapshots, enable "Preferences->Download Resources From Network" and then use menu item (Ctrl+L) to load URL, or pass URL on the command-line.

    This is a little user-unfriendly, as the downloading is blocking (the process waits for the download to finish, instead of letting you enjoy the game and download in the background; there isn't even any nice way to cancel the download, or even notification about it, except for --debug-log message). For this reason, it is disabled by default: you have to explicitly allow it by "Preferences->Download Resources From Network" (in code: CastleDownload.EnableNetwork variable).

    For some test scenes on the Internet, try e.g. Inline demo or Texture demo or AudioClip demo. (from ConformanceNist X3D Examples Archive). Or see our demo models through http, by browsing through SVN http link.

    view3dscene automatically downloads the model, as well as all linked resources (textures, inline models, sounds, scripts etc.). You can also use VRML/X3D Anchors to jump to any URL (for example, you can jump from a local file to a model available through http). Also data: URI handling is now more uniform. Also the engine uses now MIME types more, instead of merely file extensions. This makes us work with http transfers, and improves cooperation with data: URIs.

    In a game, you could also use URLs inside files like level.xml and resource.xml. For example, you could distribute now a level.xml file that contains URLs to levels on your server, downloaded each time.

  3. Clipboard (Ctrl+C, Ctrl+V, Ctrl+X in message boxes, especially handy to copy/paste URLs). For developers: use Clipboard.AsText property. Implemented for CastleWindow WinAPI, GTK, LCL backends.

  4. CAD level 2 support (CADXxx nodes).

  5. Improvements to 2D rendering. They also workaround crashes on some Mesa 9 drivers.

  6. Support for 8 and 16 samples for anti-aliasing, there are (at least NVidia) GPUs supporting it.

  7. Renamed our event Idle to Update.

    This reflects our implementation and usage of this event clearer. This event is for continuous tasks, called even when the application is not "idle" (when application is processing something, like mouse moves). Our Update event doesn't correspond 100% to normal (as used by LCL or GTK) meaning of "idle" (which is also evidenced by code if TCastleWindow LCL and GTK backends, that cannot simply use LCL/GTK "idle" concepts to implement our Update).

  8. TCastleControl.AggressiveUpdate* are removed. The (simplified and improved) version of this mechanism is now always "on" and automatically makes mouse look work better. It's still not perfect (it seems LCL event loop is just too slow to process events during mouse look fast enough), but it's better now. If you want perfectly smooth mouse look, you should still consider TCastleWindow instead of TCastleControl.

April 19, 2013 12:00 PM

while true do;

Sneak peek to simple integration between DMVCFramework and DORM

This is a really simple (not optimized and dirty) integration between the upcoming DMVCFramework (WebBroker based MVC framework) and DORM, “the Delphi ORM”. This is the DMVCFramework controller with the relative mapping and methods. In the method “GetUsers” dorm is used to execute a select to the database using the sanitized parameter passed on the url. unit [...]

by Daniele Teti at April 19, 2013 10:03 AM

April 18, 2013

Te Waka o Pascal

XE4 Pricing Revealed

Chris Rolliston just posted a link to a video (from Russia) where-in the pricing for XE4 is revealed. All $ amounts mentioned in this article are US $ prices. Your local price may vary depending on how much exchange rate gouging is added on top of the gouging already built in. In a nutshell, Delphi [...]

by Deltics at April 18, 2013 11:14 PM

The Wiert Corner - irregular stream of stuff

jpluimers

Link clearance, mostly centered around “HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Ports” and “HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\DOS Devices“:

–jeroen


Filed under: .NET, Delphi, Development, Software Development

by jpluimers at April 18, 2013 05:00 AM

April 17, 2013

The Wiert Corner - irregular stream of stuff

jpluimers

Some notes if I ever want to do something like this.

In this case I worked around it by having the Items include different text (since I had object pointers in the TStrings anyway) so I could stick to the csDropDown Style.

A very easy way to show different string values than the Items is to set the Style property fromcsDropDown to csOwnerDrawFixed as Andreas Rejbrand has answered a few years ago.

The thing is: as soon as you do that, you loose Windows Theming support.
The same limitation applies to using csOwnerDrawVariable

These two Style values get translated into adding the CBS_OWNERDRAWFIXED orCBS_OWNERDRAWVARIABLE (in addition to CBS_DROPDOWNLISTstyles of the Windows COMBOBOX control.

In turn, CBS_OWNERDRAWFIXED or CBS_OWNERDRAWVARIABLE cause you to instantly loose the Windows theming support.

When you do full custom painting like a colour picker, that is all fine. But when you only want to replace the drawn text, it is not.

The Windows COMBOBOX control does not seem to have a way around this, so I’m wondering: how can you simulate the Windows theming from Delphi?

I assume it has to do with DrawThemedBackground, but it has been a while since I’ve done serious Delphi Control work, so any pointers on how to get started there are fine too (even if they invalidate my assumption).

share|edit|close|delete|flag
75% accept rate
1
Just change the text in the control and let Windows do the work. – David Heffernan Sep 9 at 11:08
@DavidHeffernan That is a lot of work, so I wonder if simulating the theming is less work. And it would be a good exercise to learn more about how the theming support actually functions. – Jeroen Wiert Pluimers Sep 9 at 11:14
2
up voted
I cannot imagine that ComboBox1.Items.Assign is harder than working out theming. Very easy to get themed painting wrong as you can see from the VCL. Windows gets it right. – David Heffernan Sep 9 at 11:38
@DavidHeffernan The problem is not the Assign, but the mapping back to what I want. But I appreciate your point. Just waiting to see if someone comes with an answer into the theming direction and if not, work on the mapping. – Jeroen Wiert Pluimers Sep 9 at 12:21
1
up voted
Can you work it out by reading the code for TComboBoxStyleHook. – David Heffernan Sep 9 at 13:13
I tried, not much success yet, but when I do, I will post. First some non work though (: – Jeroen Wiert PluimersSep 9 at 13:24
1
up voted
As david says, I really don’t see the point of your question. You’re doing it the hard slow way, instead of the fast easy way (Just change the item text?) – Warren P Sep 10 at 3:21
I simplified the question a lot. Doing the reverse mapping requires me to enumerate over all items, which I’d rather not do (especially since I’d need abstract that for multiple not so similar kinds of occasions that are in different parts of the class hierarchy). – Jeroen Wiert Pluimers Sep 10 at 11:03
 
@JeroenWiertPluimers But you need to do that mapping at some point. The text has to come from somewhere. – David Heffernan Sep 10 at 12:09
@DavidHeffernan But now I need to do the reverse mapping… It’s not impossible like a trapdoor, but it is impractical. But probably less impractical than doing the theming. – Jeroen Wiert Pluimers Sep 10 at 14:19
1
up voted
If you can work the text out to paint it, you can work the text out to stuff into the combo box items. – David Heffernan Sep 10 at 14:42
@DavidHeffernan stuffing the text into the items isn’t the problem. The reverse (getting the right underlying item back from that text) is. That’s my mapping problem, hence the reference to the trapdoor. – Jeroen Wiert Pluimers Sep 10 at 15:14
 
OK, now I understand. I guess at this point you wished you had a better separation between business logic and UI! – David Heffernan Sep 10 at 15:15
I usually want, as most code I maintain at clients has very bad separation. But in this case the separation is quite OK. The Business Layer gives me a TStrings with the Objects filled (it is pre-Delphi-2009, so no generics yet). That’s why I can get out the Text sou easy (: First I need to finish about a week of .NET work though. – Jeroen Wiert Pluimers Sep 10 at 16:03
 
I actually wish that I had a completely VCL-implementation of TComboBox if only due to the issues in the Standard Control ComboBox setting its item height however it wants. If I was stuck in your situation, I think I’d almost write my own TExtComboBox and its own VCL styles feature. – Warren P Sep 10 at 20:45
The comments by @DavidHeffernan did give me some thought. Since the Object instance references are already in the TStrings, I wrote a small function to return a new temporary TStrings that has the string values with the captions I needed and keep the Object references. Since it has the same item ordering, and same Object references I don’t need any mapping at all. Just need to make sure I free the new TStrings at the right moment. – Jeroen Wiert Pluimers Sep 10 at 21:24

add comment

–jeroen

via: delphi – How to simulate Windows Theme behaviour when TComboBox uses csOwnerDrawFixed or csOwnerDrawVariable? – Stack Overflow.


Filed under: Delphi, Delphi XE2, Delphi XE3, Development, Software Development

by jpluimers at April 17, 2013 05:00 AM

April 16, 2013

while true do;

#3 “dorm, the Delphi ORM” bullettin

A veeery log time after the last dorm bullettin. But, as usual, I was been very busy on some projects (not only dorm) and the time goes by… However, dorm has been extended, polished and improved over the last few months. Has been used in a couple other projects in my compoany (www.bittime.it). So, here’s a small [...]

by Daniele Teti at April 16, 2013 12:54 PM

April 15, 2013

Delphi Code Monkey

Programming For Non-Programmers : No Silver Bullets, No Free Lunches.

Programmers tend to be fond of these aphorisms:

  • There Ain't No Such Thing As A Free Lunch (TANSTAAFL) -- Robert Heinlein
  • There Are No Silver Bullets -- Fred Brooks
But leaving aside our cynicism for a while, we also like to imagine local violations of these general-relativity-principles, and one of those areas of perennial optimism is the Programming Language for Non-Programmers.   That was, if you remember far enough back, the impetus for COBOL,  for the Fourth Generation Language (4GL) idea, for tools like PowerBuilder, and Visual Basic, and even, to a certain extent, for Delphi itself.  It resulted in some horrific syntactical nightmares, like AppleScript.

Where Delphi differs from the typical "tools used by people who write code who are not primarily programmers" is that Delphi offers a programming language with elegance, sophistication, and expressive power, that is not broken or hobbled by its syntax.  Not so with just about everything else in that list.   

However, it's time for people to try again, and the newest attempt I've see at "programming for everybody", is called LiveCode, from RunRev.  Go download it now, I'll wait.

What's great about LiveCode? A few things:

  • The core product is free, and is supported by revenues from their tutorial videos (LiveCode Academy) as well as from their sales and support for their premium product.
  • It's cross platform, on Windows, Linux, mobile, and Mac, in fact, it claims to support all the platforms that Delphi still has on the distant future roadmap.
What's not so great about LiveCode?   Well, if you remember back in the good old Borland TurboPascal days, one of the things they did was give you a language introduction in a book, like this:


Inside was a systematic, carefully laid out, and orderly presentation of core concepts, like this:


After a few pages, you begin to grasp a few concepts which you can use over and over again throughout your working life with Pascal.  That's another way of saying that Pascal syntax is orderly, does not try to be english, but is nevertheless readable, and the language is orthogonal to the task it performs.  Now let's look at how coding works in liveCode.  You drop a button and an edit box on a form.  Score for LiveCode is good so far.  You don't need a PhD or a tutorial video to figure out how to use it.  So far, it's as friendly as Visual Basic, C#, and Delphi, and far friendlier than Java.


Double clicking on the Button does not do what it should do. I invoke Visual Basic, Delphi, and C# as three common environments that know what's what. When you double click a button, you should immediately be given the coding context where you will write what happens when the button is pressed.  Instead you have to locate the properties-inspector analog, and find a button that looks like a CD player Play button, and click that and then click Edit Script:


Now we get the code window:


I'm rather proud of myself. It only took me 20 minutes to figure out that the way to set A = B is:

   put "Test2" into Field "Field1"


Let's unpack the concepts here for pedagogical types:

1.  LiveCode owes a debt most of all to 4GLs, AppleScript and HyperCard, and borrows some good ideas from all three.
2.  Put is one of the ways of writing assignments.
3.  The value that is put into something else is the first thing you write. This is backwards to most of us, who learned BASIC,  which has LET A = 5, which has always made perfect sense to me.  Instead we PUT 5 INTO A in this language.  Already, that's too much typing for me.
4. Next let's note that a field has a name "Field1" and that it is a Field, and that unlike a Delphi edit box named Edit1,  we must refer to it always as Field "Field1", not as just Field1.  

I managed to type a few malformed versions of that above line of code that froze the IDE completely, requiring me to Force Quit (end task), like this one:

put "Test" into Field "Field" to "thing"

The above statement passes the grammar-checker in LiveCode, and then goes into the internal works, and does something that wreaks havoc with the internals.  That, my friends, is the steep cliff that all "friendly" languages have lurking at all times.  Designing a grammar is a difficult task, and designing your own language leads to all manner of quirks.   

The lifecycle of these technologies, it seems to me is, well known, and is documented in various places and by various names, most famously as the Hype Cycle:




Am I saying that LiveCode is unimportant? No, far from it. I'm deeply impressed by the author's goal, and I, like them, dream of being able to teach 8 year olds to make video games, or do whatever else they want to do, in a language free of accidental complexity. But I disagree that emulating english with all its ambiguities is the way to do it.  I think that something more like Python is close to ideal for teaching programming. Nevertheless,  Python lacks a true Delphi-style RAD IDE.

There is a very delphi-like free and open source IDE out there that has enough of the basic Delphi IDE features, and enough power in the backing compiler to be most of what I want, but I still think Pascal is not as friendly as it could be, and so I have some hope still for LiveCode.  Since it's open source, I've been wondering if I could hack a bit on their language choices, and try to do things like this:

  • Let users pick items and combine them using menus and toolbars that will result in code templates being generated, for common tasks like variable declarations and assignment, looping, and conditional checks.
  • Let users write in a simple declarative style without line-noise or overhead:
       Field1 = "test"
  • When users type something that is not understood, provide some kind of interactive help that helps them navigate their way out of the mess or confusion they are in.

Anyways, as an inveterate tinkerer, this gets top marks from me just for existing, and for being open source. (The code is all on github.) Check it out.

Update: I found a pretty nice open courseware (training) program here.  I have to admit, that what I said above about the concepts of the Delphi language being pretty, while that may not apply to the LiveCode language, which is an ugly duckling in the same family as HyperCard/AppleScript, but its parts/components style of visual composition of elements to build software, like the images of "lego blocks" in the training course I linked to, is a compelling way to introduce the construction of software systems to non-programmers.  Score another point for LiveCode.

Update 2: I forgot to mention two of LiveCode's ugliest warts.  The first ugly wart is that live-code stores its applications in a binary ".livecode"  file that you can't use version control with.  That means anybody who works with it is basically working without version control.   The second ugly fact is that it is not completely working with Unicode and UTF8.  There are many open issues with people using languages like Arabic (Right to Left Input, etc), and who cannot get dialogs to contain unicode data.
I think the most important change that LiveCode needs to make is to move to using a .livecode named folder, containing auto-named content files which are JSON format, and can thus be cleanly version controlled.  Even image-based development environments like Smalltalk have their own version control systems that work inside the image (letting you commit and revert, and check in and out right from inside smalltalk) but LiveCode does not. No version control in 2013? That's crappy.







by Warren Postma (noreply@blogger.com) at April 15, 2013 02:50 PM

April 14, 2013

twm’s blog

Storing gnugettext translations as resources

I always wondered why the assemble tool in dxgettext appends the translation files directly to the executable rather than using the existing mechanism of resources. This is no longer necessary. I have updated the gnugettext code to optionally use RCDATA resources named after the files.

So you e.g. create a translations.rc file as

LOCALE_DE_DEFAULT RCDATA ..\locale\de\LC_MESSAGES\default.mo
LOCALE_DE_DELPHI RCDATA ..\locale\de\LC_MESSAGES\delphi2007.mo
LOCALE_DE_DZLIB RCDATA ..\locale\de\LC_MESSAGES\dzlib.mo
LOCALE_EN_DEFAULT RCDATA ..\locale\en\LC_MESSAGES\default.mo
LOCALE_EN_DELPHI RCDATA ..\locale\en\LC_MESSAGES\delphi2007.mo
LOCALE_EN_DZLIB RCDATA ..\locale\en\LC_MESSAGES\dzlib.mo

Compile it using a resource compiler e.g. brcc32 to translations.res and add it to the executable.

The new code in gnugettext will automatically find and use these resources, all you have to do is add the conditional define dx_SupportsResources.

// if the conditional dx_SupportsResources is defined the .mo files
// can also be added to the executable as Windows resources
// Be warned: This has not been thoroughly tested.
// Default is turned off.
{.$define dx_SupportsResources}

You can find the updated gnugettext.pas in the dxgettext subversion repository on sourceforge.

Disclaimer: I have only cursorily tested this code. Use it at your own risk!

by dummzeuch at April 14, 2013 05:32 PM

setfacl woes

Ever since I switched my Linux server to using ACLs (access control lists) for advanced access rights management I have struggled with rights being set too restrictive on new directories and files. Now it seems that I have solved the issue and this post is meant to remind me how to change the whole directory tree to the rights I want it to have:

sudo setfacl -Rm d:u::rwX,u::rwX,d:g::rwX,g::rwX,d:o:rX,o:rX directoryname

This recursively sets default and actual rights for directoryname and subdirectories as:

  • users: rw for files and directoryies, x for directories only
  • groups: the same
  • others: r for files and directories, x for directories only

I really hope that this is the last time I have to troubleshoot access rights issues. I want to concentrate on developing software rather than administrating bloody servers.

by dummzeuch at April 14, 2013 05:13 PM

April 12, 2013

The road to Delphi

Added support to TSMBIOS for SMBIOS 2.8 spec.

A few weeks ago (3 Apr 2013) a new update to the System Management BIOS (SMBIOS) Reference Specification was introduced by the DMTF. So the TSMBIOS project was updated to support the SMBIOS 2.8.

The following changes was added to the 2.8 version:

  • Processor Information (Type 4):
  1. SMBIOSCR00106: processor family name correction (48h)
  2. SMBIOSCR00107: new processor family types
  3. SMBIOSCR00108: new processor family type
  4. SMBIOSCR00110: correct typo in table 24 (processor upgrade)
  5. SMBIOSCR00118: new processor family types
  6. SMBIOSCR00121: new processor family type
  7. SMBIOSCR00122: new processor upgrade type
  8. SMBIOSCR00125: add new Intel socket type
  • Memory Device (Type 17):
  1. SMBIOSCR00109: add minimum, maximum and configured voltages
  2. SMBIOSCR00114: add LRDIMM to memory device list
  • Other:
  1. SMBIOSCR00116: correct/clarify structure length fields
  2. SMBIOSCR00120: add new supported processor architectures
  3. SMBIOSCR00123: update referenced specifications
  4. Wording updates for clarity and consistency

by Rodrigo at April 12, 2013 04:41 PM

April 11, 2013

Firebird News

PHP 5.5 beta3 is released and pdo_firebird.dll is re-added to builds and ready for testers

The PHP development team announces the release of the 3rd beta of PHP 5.5.0. This release fixes some bugs against beta 2. PHP 5.5.0beta3 is shipped with some bug fixes and improvements. Here is an incomplete list: Drop support for bison < 2.4 when building PHP from GIT source. Fixed bug #54567 (DateTimeZone serialize/unserialize) Fixed [...]

by mariuz at April 11, 2013 02:26 PM

The Wiert Corner - irregular stream of stuff

jpluimers

A small duh moment when I found this out myself the hard way: when repeatedly drawing anti-aliased text, it will alter the background on each draw.

So you cannot do that. Not in Delphi, not in .NET, not in Cocoa, nowhere (:

–jeroen

via: delphi – “Additive” text rendering on TCanvas? – Stack Overflow.


Filed under: .NET, Delphi, Development, FireMonkey, Software Development, User Experience, WinForms, WPF, XNA

by jpluimers at April 11, 2013 05:00 AM

April 10, 2013

Firebird News

isql documentation update

The manual for isql has been hugely updated, tidied up and is now online at http://www.firebirdsql.org/file/documentation/reference_manuals/user_manuals/html/isql.html for the html and at http://www.firebirdsql.org/file/documentation/reference_manuals/user_manuals/Firebird-isql.pdf for the pdf version. If you get an older version that document 0.5 then the cache needs to be flushed. It’s still not fully complete, but it’s a lot further down the line [...]

by Cantu at April 10, 2013 01:52 PM

Firebird Python driver FDB release 1.1 is out

FDB release 1.1 is out: http://pypi.python.org/pypi/fdb New Features: - Context Manager for transactions. Bugs Fixed: - http://tracker.firebirdsql.org/browse/PYFB-30

by mariuz at April 10, 2013 06:51 AM

The Wiert Corner - irregular stream of stuff

jpluimers

For my research queue:

I should look at the below ConnectionStrings to access dBase with ADO from Delphi, If I ever need to do that.

Thanks Cromulent for asking, Nelson for editing and Pieter for answering:

Microsoft dBase ODBC driver

Driver={Microsoft dBASE Driver (*.dbf)};DriverID=277;OLE DB Services = -1;Extended Properties=dBase IV;Dbq=c:\mypath

doing operations like ADOTable1.Open are very fast (good) but GetIndexNames returns nothing (bad).

Microsoft Jet OLEDB 4.0 driver

Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=dBASE IV;OLE DB Services=-1;Data Source=c:\mypath

doing operations like ADOTable1.Open are exceedingly slow (bad) while GetIndexNames does return index names the way it should (good).

How do I get both speed and the index info via ADO for the dBase tables?

Microsoft Paradox Driver 7.x

“We use the following connection string which works really well.”

Provider=MSDASQL.1;Persist Security Info=False;Extended Properties="Driver={Microsoft Visual FoxPro Driver};UID=;SourceDB=c:\mypath;SourceType=DBF;Exclusive=No;BackgroundFetch=Yes;Collate=Machine;Null=Yes;Deleted=Yes;"

–jeroen

via Delphi + ADO + dBase – Stack Overflow.


Filed under: Delphi, Delphi 2005, Delphi 2006, Delphi 2007, Delphi 2009, Delphi 2010, Delphi 5, Delphi 6, Delphi 7, Delphi XE, Delphi XE2, Delphi XE3, Development, Software Development

by jpluimers at April 10, 2013 05:00 AM

The road to Delphi

Added Linux support to the TSMBIOS Project

Great news for the Free Pascal developers, I just added Linux support to the TSMBIOS project.

Linux_TSMbios

Note : The TSMBIOS read the SMBIOS info using the /dev/mem device file  which provides access to system physical memory, so the code must be executed using a user with the proper permissions.


by Rodrigo at April 10, 2013 03:19 AM

How distinguish when Windows was installed in Legacy BIOS or UEFI mode using Delphi?

As part of the TSMBIOS project, I needed a method to distinguish when Windows was installed in Legacy BIOS or UEFI mode. The solution was provided by the GetFirmwareEnvironmentVariable function.

The msdn documentation states

Firmware variables are not supported on a legacy BIOS-based system. The GetFirmwareEnvironmentVariable function will always fail on a legacy BIOS-based system, or if Windows was installed using legacy BIOS on a system that supports both legacy BIOS and UEFI. To identify these conditions, call the function with a dummy firmware environment name such as an empty string (“”) for the lpName parameter and a dummy GUID such as “{00000000-0000-0000-0000-000000000000}” for the lpGuid parameter. On a legacy BIOS-based system, or on a system that supports both legacy BIOS and UEFI where Windows was installed using legacy BIOS, the function will fail with ERROR_INVALID_FUNCTION. On a UEFI-based system, the function will fail with an error specific to the firmware, such as ERROR_NOACCESS, to indicate that the dummy GUID namespace does not exist.
.

So the Delphi code to detect such condition will be something like so

{$APPTYPE CONSOLE}

uses
  Windows,
  SysUtils;

function GetFirmwareEnvironmentVariableA(lpName, lpGuid: LPCSTR; pBuffer: Pointer;
  nSize: DWORD): DWORD; stdcall; external kernel32 name 'GetFirmwareEnvironmentVariableA';

begin
  try
    GetFirmwareEnvironmentVariableA('','{00000000-0000-0000-0000-000000000000}', nil,0);
    if (GetLastError = ERROR_INVALID_FUNCTION) then
      Writeln('Legacy BIOS')
    else
      Writeln('UEFI Boot Mode');
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
  Readln;
end.

by Rodrigo at April 10, 2013 03:19 AM

Added new vcl style hook to the Vcl Styles Utils to fix QC #108678, #108875 (XE2 and XE3)

I just added a new vcl style hook (TListViewStyleHookFix) for the TListView component in the Vcl Styles Utils project to fix the QC #108678, #108875 (XE2 and XE3)

The issue reported in both reports, is that the images are not displayed in the TListView header with the VCL Styles enabled.

When you uses the Windows Theme in a TListView with images in the header will look like so

LVWindows

But if you enable the Vcl Styles, the images in the header are lost.

LVStyles2

The issue is located in the TListViewStyleHook.DrawHeaderSection method, this method must paint the image and text of each section of the header of the ListView.

This is part of the code with the bug

  ...
  ...
  ImageList := SendMessage(Handle, HDM_GETIMAGELIST, 0, 0);
  Item.Mask := HDI_FORMAT or HDI_IMAGE;
  InflateRect(R, -2, -2);
  if (ImageList <> 0) and Header_GetItem(Handle, Index, Item) then
  begin
    if Item.fmt and HDF_IMAGE = HDF_IMAGE then
      ImageList_Draw(ImageList, Item.iImage, Canvas.Handle, R.Left, R.Top, ILD_TRANSPARENT);
    ImageList_GetIconSize(ImageList, IconWidth, IconHeight);
    Inc(R.Left, IconWidth + 5);
  end;
  ...
  ...

The problem with the above code is that the SendMessage function with the HDM_GETIMAGELIST message (which is used to get the current imagelist) is not using the proper Handle. The above code is passing the handle of the ListView, but must pass the handle of the Header control, the same applies to the call to the Header_GetItem method.

The TListViewStyleHookFix introduces a new DrawHeaderSection method which passes the handle of the header control and fix the issue. You can use this Stylehook adding Vcl.Styles.Fixes unit to you uses clause and then register the hook on this way.

initialization
   TStyleManager.Engine.RegisterStyleHook(TListView, TListViewStyleHookFix);

LVStylesFix


by Rodrigo at April 10, 2013 03:19 AM

Getting Memory Device Info using Object Pascal (Delphi / FPC) and the TSMBIOS

dram-moduleIf you need to know what type of RAM is installed in your system or how is the manufacturer of your memory device, you can try reading the SPD (Serial presence detect) info directly (but not all the memory devices exposes the SPD info and reading the SPD require Kernel Mode access) , use the Win32_PhysicalMemory WMI class (but depending of the manufacturer the WMI fails to get info about some memory properties like the memory type) or using the SMBIOS.

Using the SMBIOS you can get most of the info related to the memory devices installed like manufacturer, type, speed, serial number and so on. The next snippet show how using the TSMBIOS and Delphi (or FPC) you can retrieve such data.

{$IFDEF FPC}{$mode objfpc}{$H+}
{$ELSE}
{$APPTYPE CONSOLE}
{$ENDIF}

uses
  Classes,
  SysUtils,
  uSMBIOS;

procedure GetMemoryDeviceInfo;
Var
  SMBios : TSMBios;
  LMemoryDevice  : TMemoryDeviceInformation;
begin
  SMBios:=TSMBios.Create;
  try
      WriteLn('Memory Device Information');
      WriteLn('-------------------------');

      if SMBios.HasMemoryDeviceInfo then
      for LMemoryDevice in SMBios.MemoryDeviceInformation do
      begin
        WriteLn(Format('Total Width    %d bits',[LMemoryDevice.RAWMemoryDeviceInfo^.TotalWidth]));
        WriteLn(Format('Data Width     %d bits',[LMemoryDevice.RAWMemoryDeviceInfo^.DataWidth]));
        WriteLn(Format('Size           %d Mbytes',[LMemoryDevice.GetSize]));
        WriteLn(Format('Form Factor    %s',[LMemoryDevice.GetFormFactor]));
        WriteLn(Format('Device Locator %s',[LMemoryDevice.GetDeviceLocatorStr]));
        WriteLn(Format('Bank Locator   %s',[LMemoryDevice.GetBankLocatorStr]));
        WriteLn(Format('Memory Type    %s',[LMemoryDevice.GetMemoryTypeStr]));
        WriteLn(Format('Speed          %d MHz',[LMemoryDevice.RAWMemoryDeviceInfo^.Speed]));
        WriteLn(Format('Manufacturer   %s',[LMemoryDevice.ManufacturerStr]));
        WriteLn(Format('Serial Number  %s',[LMemoryDevice.SerialNumberStr]));
        WriteLn(Format('Asset Tag      %s',[LMemoryDevice.AssetTagStr]));
        WriteLn(Format('Part Number    %s',[LMemoryDevice.PartNumberStr]));

        WriteLn;

        if LMemoryDevice.RAWMemoryDeviceInfo^.PhysicalMemoryArrayHandle>0 then
        begin
          WriteLn('  Physical Memory Array');
          WriteLn('  ---------------------');
          WriteLn('  Location         '+LMemoryDevice.PhysicalMemoryArray.GetLocationStr);
          WriteLn('  Use              '+LMemoryDevice.PhysicalMemoryArray.GetUseStr);
          WriteLn('  Error Correction '+LMemoryDevice.PhysicalMemoryArray.GetErrorCorrectionStr);
          if LMemoryDevice.PhysicalMemoryArray.RAWPhysicalMemoryArrayInformation^.MaximumCapacity<>$80000000 then
            WriteLn(Format('  Maximum Capacity %d Kb',[LMemoryDevice.PhysicalMemoryArray.RAWPhysicalMemoryArrayInformation^.MaximumCapacity]))
          else
            WriteLn(Format('  Maximum Capacity %d bytes',[LMemoryDevice.PhysicalMemoryArray.RAWPhysicalMemoryArrayInformation^.ExtendedMaximumCapacity]));

          WriteLn(Format('  Memory devices   %d',[LMemoryDevice.PhysicalMemoryArray.RAWPhysicalMemoryArrayInformation^.NumberofMemoryDevices]));
        end;
        WriteLn;
      end
      else
      Writeln('No Memory Device Info was found');
  finally
   SMBios.Free;
  end;
end;

begin
 try
    GetMemoryDeviceInfo;
 except
    on E:Exception do
        Writeln(E.Classname, ':', E.Message);
 end;
 Writeln('Press Enter to exit');
 Readln;
end.

memoryInfo

Note: Remember if you uses FPC, you can use this library in linux as well :)


by Rodrigo at April 10, 2013 03:19 AM

Vcl Styles Utils updated to fix QC #114040, #114032 (XE2 and XE3)

I just commit in the Vcl Styles Project two new fixes to patch the QC 114040 and QC 114032 (these issues exist in Delphi XE2 and XE3), both reports are related to the Highlight colors used to draw the TColorBox and TComboBoxEx components when the Vcl Styles are active.

QC 114032

As you can see in the below image the TColorBox component doesn’t use the proper highlight color, but the TColorListBox uses the highlight color of the current Vcl Style.

TColorBoxQC

The TColorBox control doesn’t use a Style Hook, so the fix was done using a interposer class. To apply the path just add the Vcl.Styles.Fixes unit to your uses list after of the Vcl.ExtCtrls unit. And the result will be

TColorBoxFix

QC 114040

The TComboBoxEx control have a similar issue.

TcomboboxExQc

In this case fixing the Style Hook related to the TComboBoxEx control was the key.

TcomboboxExFix

To apply this fix, just register the TComboBoxExStyleHookFix style hook located in the Vcl.Styles.Fixes unit.


by Rodrigo at April 10, 2013 03:18 AM