The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 1,862 other subscribers

Archive for the ‘Delphi’ Category

file – String format procedure similar to writeln – Stack Overflow

Posted by jpluimers on 2021/05/11

Cool Format feature from [WayBack] file – String format procedure similar to writeln – Stack Overflow:

The cool thing about using Format is that you use for Format Strings not only to parameterize things like width and precision inside that Format String, but also as parameters like you normally would provide values.

You can get very close to using a width of 8 and a precision of 2, like the example in your question.

For instance, to quote the documentation:

Format ('%*.*f', [8, 2, 123.456]);

is equivalent to:

Format ('%8.2f', [123.456]);

That is a much overlooked feature of Format and Format Strings.

Edit 20250910:

This was part of my answer¹ there to mimic WriteLn formatting behaviour which was not even documented at the now deleted [Wayback/Archive] Standard Routines and I/O.

Normally deleted information like above results in worse information at their current documentation site.

This time however was an exception: the current documentation is better².

¹ the start of my answer:

Read the rest of this entry »

Posted in Conference Topics, Conferences, Delphi, Development, Event, Software Development, Undocumented Delphi | Leave a Comment »

Delphi: types you cannot deprecate

Posted by jpluimers on 2021/05/06

Deprecating all types in a unit besides deprecating the unit itself will cause a hint and warning storm. Especially in projects having a lot of hints and warnings (taking over maintenance of a legacy project comes to mind) this can be very helpful to spot these locations inside many files where some obscure unmaintained unit like GIFImage.pas is still used.

[WayBack] TGIFImage for Delphi | MelanderBlog got donated to (then CodeGear, now Embarcadero) for inclusion in Delphi 2007. It was, as GifImg unit, but only documented since the [WayBack] Delphi 2009 GIFImg Namespace). For more information: delphi 2007 gifimg unit – Google Search

Delphi allows you to deprecate a lot of types, but you cannot deprecate these forms:

  • array [...] of TSomeType
  • ^TSomeType
  • class of TSomeType
  • procedure(...) ...
  • function(...): TSomeType ...
  • reference to procedure(...) ...
  • reference to function(...): TSomeType ...

Putting a deprecated 'use SomeUnit.TSomeOtherType' will fail with:

  • either a compiler error  pair
    • E2029 ';' expected but identifier 'deprecated' found“.
    • E2029 '=' expected but string constant found
  • a compiler error
    • E1030 Invalid compiler directive: 'DEPRECATED'

You can enumerate these kinds of types:

  • enumerations
  • records
  • classes, but only a full class declaration, so
    • not the class forward declaration like TMyClass = class
    • not a shortened class declaration like TMyException = class(Exception), this has to be the full TMyException = class(Exception) end deprecated 'reason';
  • methods only after the last separating ; of the method (so the virtual form is like procedure Name(...); virtual; deprecated 'use another method';)
  • named constants
  • global variables

The last few are not technically types, but included for completeness.

–jeroen

Posted in Conference Topics, Conferences, Delphi, Development, Event, Software Development | Leave a Comment »

Delphi 10.2 Tokyo introduced a “with” warning: for most “with” statements, W1048 is raised ([RSP-17326] with statements generate W1048 unsafe typecast warning – Embarcadero Technologies)

Posted by jpluimers on 2021/05/05

A cool feature introduced in Delphi 10.2 Tokyo: often [RSP-17326] with statements generate W1048 unsafe typecast warning – Embarcadero Technologies.

Only 2 upvotes, so I assume the “anti with camp” people are finally winning (:

Notes:

Quoted from the bug-report (as they cannot be archived in the wayback machine)

  1. RAD Studio
  2. RSP-17326

with statements generate W1048 unsafe typecast warning

Details

  • Type:Bug Bug
  • Status:Reported Reported
  • Priority:Major Major
  • Resolution:Unresolved
  • Affects Version/s:10.2 Tokyo
  • Fix Version/s:None
  • Component/s:Delphi Compiler
  • Labels: None
  • Build No: 25.0.25948.9960
  • Platform: All
  • Language Version: English
  • Edition: Enterprise
  • InternalID: RS-82298
  • InternalStatus: Validation

Description

All with statements generate this warning. I am on board with the theory that all with statements are inherently somewhat unsafe, but with 1.5 million lines of legacy code (and over 500 new warnings), I would significantly prefer to have a separate warning for with statements.
As it happens I would like to go through and do this work, especially if we can have refactoring to restore non-with code – see RSP-13978. BUT, Godzilla is generating new extra warnings (including unsafe typecasts) in this legacy code and I would prefer to be able to attack these first and attend to with statements later.

Activity

Comments

Jira-Quality Sync Service added a comment – 

Jason Sprenger requested more info in order to validate the issue and commented: Not any code involving “with” statements produces an unsafe typecast warning.

For instance,

program RS82298;

{$APPTYPE CONSOLE}

uses
  System.SysUtils;

procedure Use(var X);
begin<
end;

type
  TMyClass = class
    FValue: Integer;
    property Value: Integer read FValue write FValue;
  end;

procedure RunRS82298;
var
  MyClass: TMyClass;
begin
  MyClass := TMyClass.Create;
  with MyClass do
    begin
      Value := 42;
    end;
  with MyClass do
    WriteLn('MyClass.Value=', MyClass.Value);

  Use(MyClass);
end;

begin
  try
    RunRS82298
  except
    on E: Exception do
      begin
        WriteLn('FAIL - Unexpected Exception');
        WriteLn('  ClassName=', E.ClassName);
        WriteLn('    Message=', E.Message);
      end;
  end;
end.

What sort of source involving “with” statements is generating these warnings for you?

With this information our development team can consider addressing your particular circumstance.

Stuart Seath [X] (Inactive) added a comment – 

Try this (obviously a simple made-up example), and you do need to enable W1048 first in the project options:

program Project18;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils;

type
  TAnother = class
  private
    FAmbiguous : Boolean;
  public
    property Ambiguous : Boolean read FAmbiguous write FAmbiguous;
  end;

  TFirst = class
  private
    FAnother : TAnother;
  public
    procedure Doit;
  end;

var
  First : TFirst;

{ TFirst }

procedure TFirst.Doit;
begin
  FAnother := TAnother.Create;
  with FAnother do // WARNING
  begin
    Ambiguous := true;
  end;
end;

var
  XAnother : TAnother;

begin
  try
    XAnother := TAnother.Create;
    with XAnother do // NO WARNING HERE
    begin
      Ambiguous := true;
    end;

  except
    on E: Exception do
  Writeln(E.ClassName, ': ', E.Message);
end;
end.

–jeroen

Posted in Delphi, Delphi 10.2 Tokyo (Godzilla), Development, Software Development | 1 Comment »

Delphi …hide the scrollbars of a DBGrid?

Posted by jpluimers on 2021/05/04

Recently I needed a plain TDBGrid without a horizontal scrollbar. I based it on the below solutions, but using an interposer class (type TDBGrid = class(TDBGrid) ... end;).

Another solution is to redirect the WinProc for a single grid component to a different method (you can apply it to the similar TDBCtrlGrid class as well):

unit DBGridFormUnit;
uses
  Winapi.Messages,
  Vcl.DBGrids,
  Vcl.Forms;

type
  TDBGridForm = class(TForm)
    DBGrid: TDBGrid;
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
  strict private
    OriginalDBGridWindowProc : TWndMethod;
    procedure DBGridWindowProc(var Message: TMessage);
  end;

implementation

uses
  Winapi.Windows;
procedure TDBGridForm.FormCreate(Sender: TObject);
begin
  OriginalDBGridWindowProc := DBGrid.WindowProc;
  DBGrid.WindowProc := DBGridWindowProc;
end;

procedure TDBGridForm.FormDestroy(Sender: TObject);
begin
  DBGrid.WindowProc := OriginalDBGridWindowProc;
end;

procedure TDBGridForm.DBGridWindowProc(var Message: TMessage);
const 
  ScrollStylesToExclude = WS_VSCROLL or WS_HSCROLL;
var 
  Style: Integer;
begin
  if Message.Msg = WM_NCCALCSIZE then
  begin
    Style := GetWindowLong(Handle, GWL_STYLE);
    if (Style and ScrollStylesToExclude) <> 0 then // any scroll style to exclude present?
      SetWindowLong(Handle, GWL_STYLE, Style and not ScrollStylesToExclude);
  end
  else
    OrigWndProc(Message);
end;
end.

I think the SwissDelphiCenter solution in [WayBack] …hide the scrollbars of a DBGrid? originally has been copied from the 2003 post by Peter Below at [WayBack] how to hide DBCtrlGrid scrollbars – delphi.

(*
Q:
I want to hide the vertical scrollbar on a dbgrid when the record count
exceed a number. How can I do that?

A:
Make a descendent of the TDBGrid class. Add a handler for the
WM_NCCALCSIZE message.

Title: ...hide the scrollbars of a DBGrid?

Author: P. Below 

Category: VCL
*)
type
  TNoScrollDBGrid = class(TDBGrid)
  private
    procedure WMNCCalcSize(var Msg: TMessage);
    message WM_NCCALCSIZE;
  end;

procedure TNoScrollDBGrid.WMNCCalcSize(var Msg: TMessage);
const
  Scrollstyles = WS_VSCROLL or WS_HSCROLL;
var
  Style: Integer;
begin
  Style := GetWindowLong(Handle, GWL_STYLE);
  if (Style and Scrollstyles) <> 0 then
    SetWindowLong(Handle, GWL_STYLE, Style and not Scrollstyles);
  inherited;
end;

//This removes both scrollbars. If you want to remove only the vertical one
//change the scrollstyles constant accordingly.

I like this derived class from [WayBack] Delphi VCL Component • View topic • Hiding Scrollbars in DBGRID by Chris Luck based on the code from Peter Below more (I slightly condensed it from non-relevant code):

unit NoScrollDBGrid;

interface

uses
  Windows, Messages, DBGrids;

type
  TNoScrollDBGrid = class(TDBGrid)
  private
    FVertScroll: Boolean;
    FHorzScroll: Boolean;
    procedure WMNCCalcSize(var msg: TMessage); message WM_NCCALCSIZE;
    procedure SetVertScroll(Value: Boolean);
    procedure SetHorzScroll(Value: Boolean);
  published
    property VertScroll: Boolean read FVertScroll write SetVertScroll;
    property HorzScroll: Boolean read FHorzScroll write SetHorzScroll;
  end;

procedure Register;

implementation

uses
  Classes;
procedure TNoScrollDBGrid.SetVertScroll(Value: Boolean);
begin
  if FVertScroll <> Value then
  begin
    FVertScroll := Value;
    RecreateWnd;
  end;
end;

procedure TNoScrollDBGrid.SetHorzScroll(Value: Boolean);
begin
  if FHorzScroll <> Value then
  begin
    FHorzScroll := Value;
    RecreateWnd;
  end;
end;

procedure TNoScrollDBGrid.WMNCCalcSize(var msg: TMessage);
var
  style: Integer;
begin
  style := getWindowLong( handle, GWL_STYLE );

  if (NOT(FHorzScroll)) AND ((style and WS_HSCROLL) <> 0) then
    SetWindowLong( handle, GWL_STYLE, style and not WS_HSCROLL );

  if (NOT(FVertScroll)) AND ((style and WS_VSCROLL) <> 0) then
    SetWindowLong( handle, GWL_STYLE, style and not WS_VSCROLL );

  inherited;
end;

procedure Register;
begin
  RegisterComponents('Samples', [TNoScrollDBGrid]);
end;

end.

–jeroen

Posted in Delphi, Development, Software Development | Leave a Comment »

Some links on Delphi and CHM help files

Posted by jpluimers on 2021/04/29

I hardly use help files, but some older systems do, and when porting really old Delphi code, often odd implementations of accessing them through HHCTRL.OCX are used.

Since I tend to forget the correct way using the HtmlHelpViewer unit, here are some links:

Very old code involving the OCX file:

Quote from the first link [WayBack] How to Connect HTML Help with your Delphi Application:

Linking HTML Help (CHM) Files

You should add the “HTMLHelpViewer” unit to the “Uses” clause in the main form of your application. Then set the full path to your CHM file to Application.HelpFile property. To do so, you can add the following line to the main form’s “On Create” event handler:

Application.HelpFile := ExtractFilePath(Application.ExeName) + 'HelpFile.chm';

where “HelpFile.chm” is the actual name of your HTML Help file, located in the same directory as your application’s executable file.

Using HTML Help from Code

When you need to display your help file or a specific help topic, or perform others actions, you can use the following calls:

Displaying a help topic

Application.HelpContext(IDH_TOPIC);

where IDH_TOPIC is the ContextId value of the topic to display.

Displaying the Table of Contents tab

HtmlHelp(0, Application.HelpFile, HH_DISPLAY_TOC, 0);

Displaying the Index tab

HtmlHelp(0, Application.HelpFile, HH_DISPLAY_INDEX, DWORD(PWideChar('Test')));

Displaying the Search tab

var
  Query: THH_Fts_QueryW;
begin
  with Query do
  begin
    cbStruct := SizeOf(THH_Fts_QueryW);
    fUniCodeStrings := True;
    pszSearchQuery := '';
    iProximity := 0;
    fStemmedSearch := True;
    fTitleOnly := False;
    fExecute := True;
    pszWindow := nil;
  end;
  HtmlHelp(0, Application.HelpFile, HH_DISPLAY_SEARCH, DWORD(@Query));
end;

Performing Keyword Lookup

Application.HelpKeyword('Test');

Providing Help for Controls

You can link specific help topics with any controls located on the form. In this case a control will automatically display the corresponding help topic when the user focuses it and presses F1. Also, you can add the standard [?] button to the caption area of the form: using the Object Inspector, set the form’s BorderStyle property as bsDialog and biHelp member of the BorderIcons property to True. Then set the controls’ HelpContext properties that should correspond to the topic ContextId values as defined in your help project.

–jeroen

Read the rest of this entry »

Posted in Delphi, Development, Software Development | Leave a Comment »

Little Delphi tip: after “Build the current build group”, do not be surprised debugging fails

Posted by jpluimers on 2021/04/28

The Delphi Build groups are great for quickly building a lot of projects in your project group with their various build configuration.

One very important tip though: it builds in DEBUG, then RELEASE mode, then leaves the IDE thinking all projects have been built in the project manager “Build Configuration”.

That assumption is only true, if no “Build Configuration” is “DEBUG”.

It means that if you start debugging your application right after performing a “Build the current build group”, and those include RELEASE as final mode, that your debugger will be using a RELEASE mode build instead of a DEBUG build.

Quick screenshot:

–jeroen

Posted in Delphi, Development, Software Development | Leave a Comment »

Delphi and DUnitX: ensure you catch the ENoTestsRegistered exception

Posted by jpluimers on 2021/04/27

If you setup an empty test project, then DUnitX will throw an ENoTestsRegistered.

This exception is not handled, which results in two things:

  • a run-time error 217 if your application is a non-UI application
  • a memory leak detected by FastMM4

So better catch the ENoTestsRegistered exception in your .dpr level: a caught exception will be destroyed by the exception handling mechanism.

–jeroen

Read the rest of this entry »

Posted in Delphi, Development, Software Development | Leave a Comment »

Delphi: migrating applications + DLLs that use ShareMem to using FastMM

Posted by jpluimers on 2021/04/22

Notes to myself:

I bumped into some legacy code with a windows process and DLLs both using ShareMem (now System.ShareMem) so that strings could be shared between the instances.

There were lots of memory leaks, so migrating to FastMM was important.

I followed these steps to get rid of ShareMem:

  1. Put FastMM4 at the top of the uses lists for both the application and DLL projects
  2. Remove ShareMem from these uses lists (in fact from any unit used)
  3. Follow the FAQ ensuring these defines are globally in all projects involved: ShareMM;ShareMMIfLibrary;AttemptToUseSharedMM in each project file or the below in a fork of the FastMM4 repository file FastMM4Options.inc
    {$define ShareMM}
    {$define ShareMMIfLibrary}
    {$define AttemptToUseSharedMM}
    
    • Q: How do I get my DLL and main application to share FastMM so I can safely pass long strings and dynamic arrays between them?
    • A: The easiest way is to define ShareMM, ShareMMIfLibrary and AttemptToUseSharedMM in FastMM4.pas and add FastMM4.pas to the top of the uses section of the .dpr for both the main application and the DLL.
  4. Resolve any error like [dcc32 Error] E2201 Need imported data reference ($G) to access 'IsMultiThread' from unit 'FastMM4': in projects that depend on run-time packages. Luckily, how to do that is in the FAQ too:
    • Q: I get the following error when I try to use FastMM with an application compiled to use packages: “[Error] Need imported data reference ($G) to access ‘IsMultiThread‘ from unit ‘FastMM4‘”. How do I get it to work?
    • A: Enable the “UseRuntimePackages” option in FastMM4Options.inc.

Related:

Note:

  • I did not use SimpleShareMem (now System.SimpleShareMem) as the source of it did not tell me anything about FastMM4 compatibility.
  • A long time ago, FastMM changed the EnableBackwardCompatibleMMSharing from the old EnableSharingWithDefaultMM conditional define.

–jeroen

Posted in Delphi, Development, FastMM, Software Development | Leave a Comment »

XSLT for DUnit TXMLTestListener output

Posted by jpluimers on 2021/04/21

I totally missed this, even though the file has been around for a very long time:

Related: Some links on DUnit, JUnit and NUnit XSD specifications of their XML formats (JUnit is actually Ant XML)

–jeroen

Posted in Delphi, Development, DUnit, Software Development | Leave a Comment »

Windows DLL and EXE rebase

Posted by jpluimers on 2021/04/20

Some links on rebase for Windows DLLs and EXE files, including effects on .NET CLR.

–jeroen

Posted in .NET, Delphi, Development, Software Development, Windows Development | Leave a Comment »