Page 1 of 1

Inject code in TDataSet Events for all datasets in a project

PostPosted: Fri Feb 08, 2019 9:59 am
by Ahmed Sayed
Hi, I am trying to inject a logging mechanism to identify the user created the record from a Users table in the database and set them on the AfterInsert, BeforePost Events for the fields (CreatedBy, CreatedDateTime, ModifiedBy, ModifiedDateTime) if they exists in the dataset instance. The (LoggerUserID, LoggerUserName ) vars are set after the user login but set them here just to test the code.

The project itself is written in C++ but because I know C++ does not support interposer classes so I had to created it in Delphi. When i use this unit in my project nothing happens I even tried to raise an exception instead of the actual code to check if it does anything or not. I am not so good at Delphi.

I don't wanna end up setting the AfterInsert, BeforePost events for about 50 TDataSet instances. Knowing that Some Datasets have their own OnAfterInsert, OnBeforePost events assigned.

Here is the code:

Code: Select all
unit DataSetLogger;


  Data.DB, System.SysUtils;

  TDataSet = class( Data.DB.TDataSet)
    procedure DoAfterInsert; override;
    procedure DoBeforePost; override;

  LoggerUserID : Integer = 99;
  LoggerUserName : string = 'Ahmed Sayed';
  CreatedByField : string = 'CreatedBy';
  CreatedDateTimeField : string = 'CreatedDateTime';
  ModifiedByField : string = 'ModifiedBy';
  ModifiedDateTimeField : string = 'ModifiedDateTime';

procedure TDataSet.DoAfterInsert;
//  inherited;
  raise Exception.Create('DoAfterInsert');
//  FindField(CreatedByField).AsInteger := LoggerUserID;
//  FindField(CreatedDateTimeField).AsDateTime := Now;
procedure TDataSet.DoBeforePost;
//  inherited;
  raise Exception.Create('DoAfterInsert');
//  FindField(ModifiedByField).AsInteger := LoggerUserID;
//  FindField(ModifiedDateTimeField).AsDateTime := Now;

Now is there any other proper way to do this? If this is the only way why doesn't it work as expected?
What am i doing wrong?

Any help will be appreciated. Thanks in advance.

Re: Inject code in TDataSet Events for all datasets in a pro

PostPosted: Sun Feb 10, 2019 8:07 pm
by HsiaLin
If what you are trying to do is mod an existing component to override some functions, i think you need make your code into a package itself and add the .bpi of the main component you want to integrate with to the "Requires" section of your modded component.