I'm deriving from TClientdataset and trying to define an 'always run' AfterPost event. I have tried assign my AfterPost event at the constructor, but the derived component does not seem to pick it up
TMyClientDataset = class(TClientDataset)
private
FInserting: Boolean; //set to True at the MyOnNewRecord event
property FuserAfterPost: TDataSetNotifyEvent;
...
public
constructor Create(AOwner: TComponent);
...
implementation
constructor TMyClientDataset.Create(AOwner: TComponent)
begin
...
if Assigned(AfterPost) then
FuserAfterPost := AfterPost;
Afterpost := MyAfterPost;
...
end;
procedure TMyClientDataset.MyAfterPost(Dataset: TDataset);
begin
If Assigned(FuserAfterPost) then
FuserAfterPost(Dataset);
FInserting := False;
end;
What I'm trying to do: On new record, set Finserting := True; On after post, run the user supplied OnAfterPost and set FInserting := False; But the MyAfterpost event won't even run. I'm assuming the constructor is not the right place to do AfterPost := MyAfterPost;? Where should it go?
There's no good place for what you want to do. Because a user of the component may attach a handler or nil to the event handler anytime while the program is running, not just at design time. May detach an existing handler too. Then your code will not run.
For this reason, VCL employs a two step call to event handlers. First is a virtual procedure which, generally, does nothing more than to call a possible event handler. In your case, this is DoAfterPost.
TMyClientDataset = class(TClientDataset)
..
protected
procedure DoAfterPost; override;
...
procedure TMyClientDataset.DoAfterPost;
begin
inherited;
FInserting := False;
end;
For a case when no such opportunity exists, there would be no chance but properly document and hope for the user of the component reads and complies with it. Overriding Loaded would be the right place to backup an existing design-time attached handler.
Sertac's answer is excellent guidance on this type of problem. And yes it does answer the question you asked, but it's missing something.
It seems to me that you have an XY problem, and failed to ask the correct question. There is no need for you to try to manually track FInserting. Delphi already does this. Take a look at TDataSet.State and TDataSetState.
Basically your FInserting is equivalent to State = dsInsert.
Although, as you have pointed out, your FInserting flag is True in OnAfterPost (which makes it misleading, and on that basis is technically a bug).
Related
I will up the question at second time.
Do not blame me please.
Situation:
I have a form
TfrmMain = class(TForm)
private
[Inject('IniFileSettings')]
FSettings: ISettings;
public
end;
I have container initialization procedure:
procedure BuildContainer(const container: TContainer);
begin
container.RegisterType<TIniSettings>.Implements<ISettings>('IniFileSettings');
container.RegisterType<TfrmMain, TfrmMain>.DelegateTo(
function: TfrmMain
begin
Application.CreateForm(TfrmMain, Result);
end);
container.Build;
end;
So I initialize both TfrmMain as well as TIniSettings via container.
in .DPR I have:
begin
BuildContainer(GlobalContainer);
Application.Initialize;
Application.MainFormOnTaskbar := True;
Application.CreateForm(TfrmMain, frmMain);
Application.Run;
end.
Also I have a helper for TApplication:
procedure TApplicationHelper.CreateForm(InstanceClass: TComponentClass; var Reference);
var
locator: IServiceLocator;
begin
locator := TServiceLocatorAdapter.Create(GlobalContainer);
if locator.HasService(InstanceClass.ClassInfo) then
TObject(Reference) := GlobalContainer.Resolve(InstanceClass.ClassInfo).AsObject
else
inherited CreateForm(InstanceClass, Reference);
end;
Problem:
when I try to
procedure TfrmMain.FormCreate(Sender: TObject);
begin
s := FSettings.ReadString('Connection', 'Server', 'localhost');
end;
I get AV exception because FSettings currently is NIL.
What is correct way to get FSettings object from the container?
UPDATE:
FSettings := GlobalContainer.Resolve<ISettings>;
This row works perfectly... As in last time I have problem to use [Inject] attribute.
Even with solution from Stefan I can make the method working:
How to initialize main application form in Spring4D GlobalContainer?
First the reason why the container does not have a HasService anymore is because that method has been removed. You can access it as follows:
if container.Kernel.Registry.HasService(...) then // yeah yeah, I know LoD is crying right now ;)
I would avoid mixing using ServiceLocator and GlobalContainer. While they should point to the same instance it might not be the case because actually someone could point one of them to another instance. If you really want to use ServiceLocator in this case then also resolve from ServiceLocator. But keep in mind that there is nothing on it that the container does not know (even if you have to call some different parts of the kernel.
But that is not the problem you are facing here with your settings injection. The problem you have is the timing. The FormCreate method (I just guess it is attached to the OnCreate event). So the container instantiates the TfrmMain, the event gets called and then returns to the container code which afterwards does all the injections. So calling something that has not been injected via constructor in some code being called during construction is a temporal coupling.
There are different approaches to this problem:
moving your access to the FSettings to some event that gets triggered later (like OnShow or OnActivate)
don't use field injection it can be nice but that couples your code to the container because "traditional" code cannot do that. Use property injection and a setter that executes the code.
When you consider constructor injection as for dependencies that are mandatory and property injection for those that are optional I would say go for the constructor injection. But knowing that you working with a TComponent descendant I probably would use the property injection in that case although that dependency is not optional.
Originally the question had to be how to access the components in the first place, however I somehow managed to figure it out. I am just learning Delphi so I am prone to dumb and obvious questions. I am also at a stage when I'm not actually writing anything useful, but just messing with random stuff to see how it works and maybe learn something.
Wall of text incoming, i want to explain what i am exploring at the moment...
Basically i have a form1 with a button1, pressing it creates a frame2, that frame2 has a button2, pressing button2 creates a frame3 within frame2 (it being frame3's parent and owner). Each frame has an another freeandnil-button. Upon pressing each button1/2/3, it gets disabled to prevent creating multiple instances. My original problem was that after using freeandnil-button, I couldnt access the button on the previous frame (it worked fine for forms, form1.button1.enabled:=true works fine from within frame2) that got disabled in order to re-enable it (frame2.button1.enabled:=true from within frame3 creates an access violation, I think).
Suppose I write something in the future that requires such communication? So I added an editbox to each frame, with a button on the other to change the editbox text, this is my current working solution:
procedure TFrame2.Button3Click(Sender: TObject);
var i,z:integer;
begin
for i := 0 to ComponentCount - 1 do
if components[i] is tframe3 then
for z := 0 to (components[i] as tframe3).ComponentCount - 1 do
if (components[i] as tframe3).Components[z] is TEdit then
((components[i] as tframe3).Components[z] as TEdit).Text:='ping';
end;
and
procedure TFrame3.Button3Click(Sender: TObject);
var i:integer;
begin
for i := 0 to parent.ComponentCount-1 do
if parent.components[i] is TEdit then
(parent.Components[i] as TEdit).Text:='pong';
end;
If I have a bunch of editboxes or whatever the hell, I suppose I could use Tag property to identify them, however, this much component counting and passing something AS something doesn't really look right or efficient enough to me.
My questions at the moment are: can it be done in a better way? and can someone provide the reasoning why cant I access "parent-frame" components from a "child-frame" in a dumb way (ie: frame2.button1.enabled:=true from within frame3)?
A couple of points:
Controls/Components are usually set to be owned by the form/frame that controls their lifetime and parented to the control that shows them. So when you create a TEdit to sit on a TPanel on a TForm, you would set TForm as the owner and TPanel as the parent of the TEdit. With frames you do the same: the frame is the owner of all controls on it, controls are parented to whatever container on the frame (can be the frame itself) is holding and and is thus reponsible for showing (painting) it.
When you iterate over the children of a control, iterating over Components uses the Owner relation; iterating over Controls uses the Parent relation. So your code above would already do a lot less if it were to iterate over the Controls.
Of course you can reference other controls in a "dumb" way, but you will have to provide for the access method. If you want others (not just child frames) you will at the very least have to declare a method to retrieve that control. Many ways to do this. One is to "ask" the form when you need it (using a method on the form), or have the form set a property on the frame when it is created...
Avoid accessing form's and frame's published properties. They are mainly there for Delphi's streaming system. When you tie your application together using your approach described above it can very soon become one incredibly tangled mess...
Example coming up (sometime this evening), it will take me a bit of time to also explain and I have work to do...
The following example deals only with the ping-pong game between the frames. Freeing any form or frame from one of its own event handlers is not such a good idea. Use the Release method for that as it prevents the form/frame from processing messages after is was freed. (Plenty of questions about this on SO by the way). Also, when you do release a frame from one of its own buttons, you will need to take care that the frame that created it has a chance to nil the references it may have held to that frame otherwise you are setting yourself up for some interesting to debug mayhem. Look into "Notification" and "NotifyControls" and the automatic notification by forms and frames that is sent to their owner/parent so these can remove the control from their components/controls collection. In your example, if you were to release Frame3 from its own "FreeAndNil" button's OnClick event handler, you would have to make sure that the Frame2 responds to the deletion (I think) notification message and nil's any references it holds to Frame3 (besides the ones that will already be cleared automatically in the components/controls collections).
Now, the ping pong game. There are a couple of ways to go about this.
Method 1
The first way is what you already tried with a loop over the components of the other frame. While it certainly is a way to avoid having to "use" the other frame, it is cumbersome and not very concise. Plus when you get more controls on your forms/frames, you will have to add a check on the name to know that you have the correct TEdit. And then you might just as well use the name directly, especially as one frame already has the other frame in its uses clause because it is creating it.
// PingFrame (your Frame2)
uses
...
Pong_fr;
type
TPingFrame = class(TFrame)
...
procedure CreateChildBtnClick(Sender: TObject);
procedure PingPongBtnClick(Sender: TObject);
private
FPong: TPongFrame; // This is the "extra" reference you need to nil when
// freeing the TPongFrame from one of its own event handlers.
...
end;
procedure TPingFrame.CreateChildBtnClick(Sender: TObject);
begin
CreateChildBtn.Enabled := False;
FPong := TPongFrame.Create(Self);
FPong.Parent := ContainerPnl;
FPong.Align := alClient;
end;
procedure TPingFrame.PingPongBtnClick(Sender: TObject);
begin
if Assigned(FPong) then
FPong.Edit1.Text := 'Ping';
end;
And on the other end:
// PongFrame (your Frame3)
type
TPongFrame = class(TFrame)
...
procedure PingPongBtnClick(Sender: TObject);
end;
implementation
uses
Ping_fr;
procedure TPongFrame.PingPong1BtnClick(Sender: TObject);
begin
(Owner as TPingFrame).Edit1.Text := 'Pong called';
end;
This method seems all nice and dandy, but it has drawbacks:
You need to use the unit that holds the TPingFrame (Ping_fr in this example). Not too bad I guess, but... as Ping_fr already uses Pong_fr (the unit holding TPongFrame), you can't have Ping_fr using Pong_fr in the interface section and have Pong_fr using Ping_fr in the interface section as well. Doing so would have Delphi throwing an error because of a circular references. This can be solved by moving one of the uses to the implementation section (as done in the example for the use of Ping_fr in the Pong_fr unit.
A bigger drawback is that there is now a very tight coupling between the two frames. You cannot change the TEdit in either one to another type of control (unless that happens to have a Text property as well) without having to change the code in the other unit as well. Such tight coupling is a cause of major headaches and it is good practice to try and avoid it.
Method 2
One way to decrease the coupling between the frames and allow each frame to change it controls as it sees fit is not to use the controls of another form/frame directly. To do so you declare a method on each frame that the other can call. Each method updates its own controls. And from the OnClick event handlers you no longer access the other frame's controls directly, but you call that method
type
TPingFrame = class(TFrame)
...
public
procedure Ping;
end;
implementation
procedure TPingFrame.PingPongBtnClick(Sender: TObject);
begin
if Assigned(FPong) then
FPong.Ping;
end;
procedure TPingFrame.Ping;
begin
Edit1.Text := 'Someone pinged me';
end;
And on the other end:
type
TPongFrame = class(TFrame)
...
public
procedure Ping;
end;
implementation
procedure TPongFrame.PingPongBtnClick(Sender: TObject);
begin
(Owner as TPingFrame).Ping;
end;
procedure TPongFrame.Ping;
begin
Edit1.Text := 'Someone pinged me';
end;
This is better than Method 1 as it allows both frames to change their controls without having to worryabout "outsiders" referencing them, but still has the drawback of the circular reference that can only be "solved" by moving one "use" to the implementation section.
It is a good practice to try and avoid circular references altogether instead of patching them by moving units to the implementation section's uses clause. A rule of thumb I use is:
Any form/frame may know and use the public interface of the forms/frames it instantiates (though it should avoid the controls in the "default visibility" part of that interface), but no form/frame should not have any knowledge of the specific form/frame that created it.
Method 3
One way of achieving this (there are many) it to use events just like the TButton's OnClick event.
On the TPongFrame side of things you can remove the use of Ping_fr. You no longer need it.
Then you need to declare a property and the field it references and declare a method to fire the event.
type
TPongFrame = class(TFrame)
private
FOnPingPongClicked: TNotifyEvent;
protected
procedure DoPingPongClicked;
public
property OnPingPongClicked: TNotifyEvent
read FOnPingPongClicked write FOnPingPongClicked;
end;
The Ping method stays and its implementation is unchanged. The PingPongBtnClick event handler also stays, but its implementation now becomes:
procedure TPongFrame.PingPongBtnClick(Sender: TObject);
begin
DoPingPongClicked;
end;
procedure TPongFrame.DoPingPongClicked;
begin
if Assigned(FOnPingPongClicked) then
FOnPingPongClicked(Self);
end;
You could put the code from DoPingPongClicked straight in here, but it is a good practice to fire an event in a separate method. It avoids duplicating the exact same code if you would have an event that can be fired from multiple parts of your code. And it also allows descendants (when you get those) to override the "firing" method (you'll have to mark it virtual in the ancestor) and do something specific all the times the event is fired.
On the TPingFrame side of things you need to code a handler for the new event:
type
TPingFrame = class(TFrame)
...
protected
procedure HandleOnPingPongClicked(Sender: TObject);
Note that the signature of this handler needs to be what the TNotifyEvent specifies. And of course you need to ensure that this event handler gets called when the event fires in TPongFrame:
procedure TPingFrame.CreateChildBtnClick(Sender: TObject);
begin
CreateChildBtn.Enabled := False;
FPong := TPongFrame.Create(Self);
FPong.Parent := ContainerPnl;
FPong.Align := alClient;
// Listen to event fired by PongFrame whenever it's PingPingBtn is clicked
FPong.OnPingPongClicked := HandleOnPingPongClicked;
end;
In the handler code you can do what you need to do. It can be general:
procedure TPingFrame.HandleOnPingPongClicked(Sender: TObject);
begin
Edit1.Text := 'OnPingPongClicked event was fired';
end;
And of course you can also use the fact that the event passes a reference to the instance firing the event as well:
procedure TPingFrame.HandleOnPingPongClicked(Sender: TObject);
var
Pong: TPongFrame;
begin
// This checks that Sender actually is a TPongFrame and throws an exception if not
Pong := Sender as TPongFrame;
// Use properties from the Pong instance that was passed in
Edit1.Text := 'OnPingPongClicked event was fired by ' + Pong.Name;
end;
Enjoy!
I would like to add to my component the conditional state when the component cannot be loaded and inform its user (developer) that this component cannot be loaded in design time and target user at runtime (safely somehow, if possible).
How can I prevent the component from loading in its constructor and how to display message (exception) from constructor safely at design time and at runtime ?
constructor TSomeComponent.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
if csDesigning in ComponentState then
if SomeIncompatibleCondition then
begin
// how to display message (exception) about the wrong
// condition and interrupt the loading of the component ?
end;
// is it possible to do the same at runtime ?
end;
Thank you
Raise an exception, eg:
constructor TSomeComponent.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
if SomeIncompatibleCondition then
raise Exception.Create('Incompatible condition detected!');
end;
One approach:
Public
Property CreatedOK: boolean read fCreatedOK;
constructor TSomeComponent.Create(AOwner: TComponent);
begin
...
fCreatedOK := ThereIsAnIncompatibleCondition;
end;
Then, the programmer creates the object by:
MyObject := TSomeComponent.Create(Self);
if (NOT MyObject.CreatedOK) then
... deal with it...
We prefer this because it avoids lots of exception code, which can be cumbersome, and a hassle when debugging. (That's another topic though!)
Another approach we use is if the constructor has a lot of work, move the work to another method that the user has to call after constructing. This also has the advantage of letting us pass many values to the object easily.
public
constructor Create...
function InitAfterCreate:boolean;
end;
The caller does:
MyObject := TSomeComponent.Create
if (NOT MyObject.InitAfterCreate) then
... deal with it ...
or, if you're using InitAfterCreate to pass values, you'd define it as
function InitAfterCreate( Value1: Integer, etc.):boolean
Then InitAfterCreate can examine the state of the object and return a result.
One weakness of these approaches is that the programmer has to remember to call the InitAfterCreate or check MyObject.CreatedOk. To protect against them failing to do so, you can put some Asserts in the beginning of some other methods of your object like:
procedure TForm.FormShow
begin
Assert(fCreatedOK, "Programmer failed to check creation result.")
...
end;
In all cases, one challenge is to not terminate the Create leaving the object half-created, in an indeterminate state, which might make it hard for your destructor to know how much to destroy.
I inherited a GUI implemented in Delphi RadStudio2007 targeted for Windows XP embedded. I am seeing a lot of code that looks like this:
procedure TStatusForm.Status_refresh;
begin
if DataModel.CommStatus = COMM_OK then begin
if CommStatusOKImage.Visible<>True then CommStatusOKImage.Visible:=True;
if CommStatusErrorImage.Visible<>False then CommStatusErrorImage.Visible:=False;
end else begin
if CommStatusOKImage.Visible<>False then CommStatusOKImage.Visible:=False;
if CommStatusErrorImage.Visible<>True then CommStatusErrorImage.Visible:=True;
end;
end
I did find this code sample on the Embarcadero site:
procedure TForm1.ShowPaletteButtonClick(Sender: TObject);
begin
if Form2.Visible = False then Form2.Visible := True;
Form2.BringToFront;
end;
That shows a check of Visible before changing it, but there is no explanation of what is served by checking it first.
I am trying to understand why the original developer felt that it was necessary to only set the Visible flag if it was to be changed, and did not choose to code it this way instead:
procedure TStatusForm.Status_refresh;
begin
CommStatusOKImage.Visible := DataModel.CommStatus = COMM_OK;
CommStatusErrorImage.Visible := not CommStatusOKImage.Visible;
end
Are there performance issues or cosmetic issues (such as screen flicker) that I need to be aware of?
As Remy Lebeau said, Visible setter already checks if new value differs.
For example, in XE, for TImage, assignment to Visible actually invokes inherited code:
procedure TControl.SetVisible(Value: Boolean);
begin
if FVisible <> Value then
begin
VisibleChanging;
FVisible := Value;
Perform(CM_VISIBLECHANGED, Ord(Value), 0);
RequestAlign;
end;
end;
So, there is no benefits of checking it. However, might there in your code are used some third-party or rare components - for them all may be different, though, I doubt it.
You can investigate it yourself, using "Find Declaration" context menu item in editor (or simply Ctrl+click), and/or stepping into VCL code with "Use debug dcus" compiler option turned on.
Like many properties, the Visible property setter checks if the new value is different than the current value before doing anything. There is no need to check the current property value manually.
Well, I doubt it will, but maybe there could be issues specifically for forms in recent Delphi versions. The Visible property is redeclared in TCustomForm to assure the execution of the OnCreate event prior to setting the visibility. It is technically not overriden since TControl.SetVisible is not virtual, but it has the same effect:
procedure TCustomForm.SetVisible(Value: Boolean);
begin
if fsCreating in FFormState then
if Value then
Include(FFormState, fsVisible) else
Exclude(FFormState, fsVisible)
else
begin
if Value and (Visible <> Value) then SetWindowToMonitor;
inherited Visible := Value;
end;
end;
This implementation in Delphi 7 still does not require checking the visibility manually, but check this yourself for more recent versions.
Also, I agree with Larry Lustig's comment because the code you provided does not testify of accepted syntax. It could have better been written as:
procedure TForm1.ShowPaletteButtonClick(Sender: TObject);
begin
if not Form2.Visible then Form2.Visible := True;
Form2.BringToFront;
end;
I have an TUpDown control whose Associate is set to an instance of a TEdit subclass. The edit class calls RecreateWnd in its overriden DoEnter method. Unfortunately this kills the buddy connection at the API level which leads to strange behavior e.g. when clicking on the updown arrows.
My problem is that the edit instance doesn't know that it is the buddy of some updown to which it should reconnect and the updown isn't notified of the loss of its buddy. Any ideas how I could reconnect the two?
I noticed how TCustomUpDown.SetAssociate checks that updown and buddy have the same parent and uses this to avoid duplicate associations. So I tried calling my own RecreateWnd method:
procedure TAlignedEdit.RecreateWnd;
var
i: Integer;
c: TControl;
ud: TCustomUpDown;
begin
ud := nil;
for i := 0 to Pred(Parent.ControlCount) do
begin
c := Parent.Controls[i];
if c is TCustomUpDown then
if THACK_CustomUpDown(c).Associate = Self then
begin
ud := TCustomUpDown(c);
Break;
end;
end;
inherited RecreateWnd;
if Assigned(ud) then
begin
THACK_CustomUpDown(ud).Associate := nil;
THACK_CustomUpDown(ud).Associate := Self;
end;
end;
et voila - it works!
You've discovered something rather unfortunate. You set up an association between two controls at the application level, so you should be able to continue to manage that association in application-level code, but the VCL doesn't provide the framework necessary for maintaining that. Ideally, there would be a generic association framework, so associated controls could notify each other that they should update themselves.
The VCL has the beginnings of that, with the Notification method, but that only notifies of components being destroyed.
I think your proposed solution is a little too specific to the task. An edit control shouldn't necessarily know that it's attached to an up-down control, and even if it does, they shouldn't be required to share a parent. On the other hand, writing an entire generic observer framework for this problem would be overkill. I propose a compromise.
Start with a new event property on the edit control:
property OnRecreateWnd: TNotifyEvent read FOnRecreateWnd write FOnRecreateWnd;
Then override RecreateWnd as you did above, but instead of all the up-down-control-specific code, simply trigger the event:
procedure TAlignedEdit.RecreateWnd;
begin
inherited;
if Assigned(OnRecreateWnd) then
OnRecreateWnd(Self);
end;
Now, handle that event in your application code, where you know exactly which controls are associated with each other, so you don't have to search for anything, and you don't need to require any parent-child relationships:
procedure TUlrichForm.AlignedEdit1RecreateWnd(Sender: TObject);
begin
Assert(Sender = AlignedEdit1);
UpDown1.Associate := nil;
UpDown1.Associate := AlignedEdit1;
end;
Try storing the value of the Associate property in a local variable before you call RecreateWnd, then setting it back afterwards.