DataSetProvider - DataSet to ClientDataSet - delphi

EDIT: It seems as if the DataSetProvider doesn't have the functionality I need for this project, so I'll be implementing a custom class for loading the data into the ClientDataSet.
I am trying to take data from a TMSQuery which is connected to my DB and populate a ClientDataSet with some of that data using a DataSetProvider.
My problem is that I will need to modify some of this data before it can go into my ClientDataSet. The ClientDataSet has persistent fields that will not match up with the raw DB data. I can't even get a string from the DB into a memo field in ClientDataSet.
The ClientDataSet is a part of my data tier so I will need to conform the data from the DB to the ClientDataSet field by field (well most will be able to go right through, but many will require routing and/or conversion).
Does anyone have experience with this?

You're looking for the TDataSetProvider.BeforeUpdateRecord event. Write an event handler for this event and you can take manual control of how the data is applied back to the data base.
Something like this
procedure TDataModule1.DataSetProvider1BeforeUpdateRecord(Sender: TObject; SourceDS: TDataSet; DeltaDS: TCustomClientDataSet; UpdateKind: TUpdateKind; var Applied: Boolean);
begin
{ Set applied to tell DataSnap that you have applied this record yourself }
Applied := True;
case UpdateKind of
ukModify:
begin
Table1.Edit;
{ set the values of the fields something like this }
if not VarIsEmpty(DeltaDS.FieldByName('NewValue')) then
Table1['SomeField'] := DeltaDS.FieldByName('SomeField').NewValue;
Table1.Post;
end;
ukInsert:
begin
Table1.Insert;
{ set the values of the fields }
Table1['SomeField'] := DeltaDS['SomeField']
Table1.Post;
end;
ukDelete:
if Table1.Locate('PrimaryKeyField', DeltaDS['PrimaryKeyField'], []) then
Table1.Delete;
end; // case
end;

You can modify the data going to the ClientDataSet by implementing the TDataSetProvider.OnGetData event.
procedure TDataModule1.DataSetProvider1GetData(Sender: TObject; DataSet: TCustomClientDataSet);
begin
DataSet.First;
while not DataSet.Eof do begin
DataSet.Edit;
DataSet['Surname'] := UpperCase(DataSet['Surname']);
DataSet.Post;
DataSet.Next;
end; // while
end;
When applying updates from the ClientDataSet you can use the TDataSetProvider.OnUpdateData event. Like the OnGetData event you are operating on the whole dataset rather than a single record.
procedure TDataModule1.DataSetProvider1UpdateData(Sender: TObject; DataSet: TCustomClientDataSet);
begin
DataSet.First;
while not DataSet.Eof do begin
DataSet.Edit;
DataSet['Surname'] := LowerCase(DataSet['Surname']);
DataSet.Post;
DataSet.Next;
end; // while
end;
This OnUpdateData event is called before the OnBeforeUpdateRecord event. Also the OnGetData and OnUpdateData events operate on the whole dataset while OnBeforeUpdateRecord is called once for each modified record.

If I need a ClientDataSet to have data that doesn't exactly match the database schema, I write a query for the TQuery component that returns the data in the format that I want. I then write my own, separate, Delete, Insert, Refresh, and Update queries for the TQuery component.
Alternatively, you could create a view on the database and use the view in your TQuery component.
If you want a custom ClientDataSet that is independent of the database, what you need is an in-memory dataset. If you don't have an in-memory dataset component, Google for "TClientDataSet as in-memory dataset". What you end up with though, is basically a glorified list view component. Of course, you can hook into the OnUpdateRecord of the in-memory dataset to know when to update your real dataset.

Related

Delphi 10.4 - Sort Memtable by clicking Stringgrid Header

I feel like an idiot because my question seams so simple but I don't get it done :D
My Settings is that:
One Dataset (Memtable), One Stringgrid. The Grid is bind via live Bindungs.
I would like to sort my Columns by clicking on the GridHeader. In the OnHeaderClick Event I get an tColumn Object. I only can read the Column.Header String, but I changed the Text from the Header to a more speakable Text. When I put Column.header into Memtable.Indexfieldsname Memtable says that field does not exist, what is right, but I don't know how to get the right Fieldname from the column.
What you want is quite straightforward to do. In the example below, which uses the demo data from
the Biolife demo, I've linked the StringgRid to the FDMemTable entirely by binding objects
created in code so that there is no doubt about any of the binding steps or binding properties,
nor the method used to establish the bindings.
procedure TForm2.FormCreate(Sender: TObject);
var
BindSourceDB1 : TBindSourceDB;
LinkGridToDataSourceBindSourceDB1 : TLinkGridToDataSource;
begin
// Note : You need to load FDMemTable1 at design time from the sample Biolife.Fds datafile
// The following code creates a TBindSourceDB which Live-Binds FDMemTable1
// to StringGrid1
//
// As a result, the column header texts will be the fieldnames of FDMemTable1's fields
// However, the code that determines the column on which to sort the StringGrid does not depend
// on this
BindSourceDB1 := TBindSourceDB.Create(Self);
BindSourceDB1.DataSet := FDMemTable1;
LinkGridToDataSourceBindSourceDB1 := TLinkGridToDataSource.Create(Self);
LinkGridToDataSourceBindSourceDB1.DataSource := BindSourceDB1;
LinkGridToDataSourceBindSourceDB1.GridControl := StringGrid1;
end;
procedure TForm2.StringGrid1HeaderClick(Column: TColumn);
// Sorts the STringGrid on the column whose header has been clicked
var
ColIndex,
FieldIndex : Integer;
AFieldName : String;
begin
ColIndex := Column.Index;
FieldIndex := ColIndex;
AFieldName := FDMemTable1.Fields[FieldIndex].FieldName;
Caption := AFieldName;
// Should check here that the the field is a sortable one and not a blob like a graphic field
FDMemTable1.IndexFieldNames := AFieldName;
end;
Note that this answer assumes that there is a one-for-one correspondence between grid columns and fields of the bound dataset, which will usually be the case for bindings created using the default methods in the IDE. However, Live Binding is sophisticated enough to support situations where this correspondence does not exist, and in those circumstances it should not be assumed that the method in this answer will work.

Delphi: How to access clientdataset via delta

On the TDatasetProvider.OnBeforeUpdateRecord, how do I
access the source or originating clientdataset of the
sent DeltaDS parameter?
procedure TdmLoanPayment.dpLoanPaymentBeforeUpdateRecord(Sender: TObject;
SourceDS: TDataSet; DeltaDS: TCustomClientDataSet; UpdateKind: TUpdateKind;
var Applied: Boolean);
var
sourceCDS: TClientDataset;
begin
sourceCDS := DeltaDS.???;
...
end;
I need to access some properties from the corresponding clientdataset. Setup is TSQLDataset/TDatasetProvider/TClientDataset.
Edit:
The cause of all this hassle is, I wanted to derive a component from TDatasetProvider and assign a default OnBeforeUpdateRecord.
I think SourceDS is what are looking for.
The Sender parameter identifies the provider that is applying updates.
The SourceDS parameter is the dataset from which the data originated.
If there is no source dataset, this value is nil (Delphi) or NULL
(C++). The source dataset may not be active when the event occurs, so
set its Active property to true before trying to access its data.
The DeltaDS parameter is a client dataset containing all the updates
that are being applied. The current record represents the update that
is about to be applied.
The UpdateKind parameter indicates whether this update is the
modification of an existing record (ukModify), a new record to insert
(ukInsert), or an existing record to delete (ukDelete).
The Applied parameter controls what happens after exiting the event
handler. If the event handler sets Applied to true, the provider
ignores the update: it neither tries to apply it, nor does it log an
error indicating that the update was not applied. If the event handler
leaves Applied as false, the provider tries to apply the update after
the event handler exits.
for example:
procedure TdmLoanPayment.dpLoanPaymentBeforeUpdateRecord(Sender: TObject;
SourceDS: TDataSet; DeltaDS: TCustomClientDataSet; UpdateKind: TUpdateKind;
var Applied: Boolean);
begin
ShowMessage(TClientDataSet(SourceDS).Name); // get source name
...
end;
Edit
or
procedure TdmLoanPayment.dpLoanPaymentBeforeUpdateRecord(Sender: TObject;
SourceDS: TDataSet; DeltaDS: TCustomClientDataSet; UpdateKind: TUpdateKind;
var Applied: Boolean);
begin
if SourceDS.Name = 'Name1'then
...do something ...
if SourceDS.Name = 'Name2'then
...do something ...
end;
If you trace out of the call to your DataSetProvider1BeforeUpdateRecord, you'll
see that the dataset passed as the SourceDS parameter is the Source dataset of
the UpdateTree, and that is, AFAICS, the dataset that the DataSet property of
the Provider is set to. Of course, this is not the CDS from which the Delta
has been derived (in my test case it's actually a TAdoQuery).
Looking at the source code in Provider.Pas, I can't immediately see a
way to find the identity of the Delta's source CDS. I don't think that is particularly surprising because the Provider's operation is invoked by a CDS and not vice versa, and all the data the Provider needs from the CDS is its Delta.
On the other hand, it's a pretty fair bet that the BeforeUpdateRecord event has
been triggered by the most recent, still-pending, call to ApplyUpdates on one of your CDSs, so if
you make a note of that in their BeforeApplyUpdates event(s), that will probably
tell you what you want to know. I'd expect that to work for a single-level update, but it might be more tricky if the UpdateTree is operating on nested CDSs.
If your CDSs all have individual Providers, but the providers share a BeforeUpdateRecord event, you could identify the CDS for a given provider using code like this:
function TCDSForm.FindCDSForProvider(DataSetProvider: TDataSetProvider):
TClientDataSet;
var
i : Integer;
begin
Result := Nil;
for i := 0 to ComponentCount - 1 do begin
if Components[i] is TClientDataSet then
if TClientDataSet(Components[i]).ProviderName = DataSetProvider.Name then begin
Result := TClientDataSet(Components[i]);
Exit;
end;
end;
end;

How to insert records with DataSnap

In many tutorials i read how to select data from a database in a datasnap client, p.e. to complete a dbgrid.
But i need now to know how to insert or update a row, p.e "new client". Can everybody recommends me a book or tutorial?
I have an sqlconnection on a clientdatamodule on the clientside apart from clientclassesunit. I was prooving wuth an SQLQuery with an insert SQL Statement but it doen't function.
On the other han i have on the server side:
procedure TServerMethods1.nuevocheque(idcliente,numero,cuenta,idbanco : integer; fr,fc, titular:string ;importe:Double;cobrado:Boolean);
var
ucheque:integer;
begin
with qicheque do
begin
Open;
ParamByName('idcliente').AsInteger:=idcliente;
ParamByName('numero').AsInteger:=numero;
ParamByName('fr').AsDate:=StrToDate(fr);
ParamByName('fc').AsDate:=StrToDate(fc);
ParamByName('importe').AsFloat:=importe;
ParamByName('titular').AsString:=titular;
ParamByName('cobrado').AsBoolean:=cobrado;
ParamByName('cuenta').AsInteger:=cuenta;
ExecSQL();
end;
end;
With this method i try to insert, the statement is into SQL property of the component.
On the client side, i have a TSQLServerMethod wich calls "nuevocheque":
procedure TForm4.BGuardarClick(Sender: TObject);
var
idcliente,numero,cuenta,idbanco:integer;
titular:string;
cobrado:Boolean;
fr,fc:string;
importe:Double;
begin
ClientModule1.nuevocheque.Create(nil);
with ClientModule1.nuevocheque do
begin
idcliente:=1;
numero:=StrToInt(ENumero.Text);
cuenta:=StrToInt(Ecuenta.Text);
idbanco:=1;
titular:=ENombre.Text;
cobrado:=False;
importe:=StrToFloat(EMonto.Text);
fr:=EFechaEmision.Text;
fc:=EFechacobro.Text;
end;
end;
But it doesn´t function.
Thank for your help
Well, i achieve inserting data into mysql database i had desgined.
This is te code in delphi into a button:
procedure TForm4.BGuardarClick(Sender: TObject);
var
idcliente,numero,cuenta,idbanco:integer;
titular:string;
cobrado:Boolean;
fr,fc:string;
importe:Double;
a:TServerMethods1Client;
interes:Double;
begin
a:=TServerMethods1Client.Create(ClientModule1.SQLConnection1.DBXConnection);
begin
idcliente:=Unit3.id;
numero:=StrToInt(ENumero.Text);
cuenta:=StrToInt(Ecuenta.Text);
idbanco:=lcbbanco.KeyValue;
titular:=ENombre.Text;
cobrado:=False;
if (EP.Text<>'') then
begin
importe:=StrToFloat(EHC.Text);
end
else
begin
importe:=StrToFloat(EMonto.Text);
end;
fr:=EFechaEmision.Text;
fc:=EFechacobro.Text;
end;
a.nuevocheque(idcliente,numero,cuenta, idbanco,fr,fc,titular,importe,cobrado);
end;
I've called to method create() with the SQL component such as M Diwo said me.
Im too hapy. Thanks to all
I don't know what you use as database connection, for my own convenience I have slightly modified for dbGO (parameters passed by variant).
Also I have made a function from the server method, like this the client can be notified that there has been a problem (with the query, connection,...). Here is the server method:
//server
function TServerMethods1.NuevoCheque(idcliente, numero, cuenta,
idbanco: integer; fr, fc, titular: string; importe: Double;
cobrado: Boolean): Boolean;
begin
try
with qicheque, Parameters do
begin
Close;
ParamByName('idcliente').Value:=idcliente;
ParamByName('numero').Value:=numero;
ParamByName('fr').Value:=StrToDate(fr);
ParamByName('fc').Value:=StrToDate(fc);
ParamByName('importe').Value:=importe;
ParamByName('titular').Value:=titular;
ParamByName('cobrado').Value:=cobrado;
ParamByName('cuenta').Value:=cuenta;
ExecSQL();
end;
Result := true;
except
Result := false;
//raise; <-- uncomment if you want to handle this properly in your code
end;
end;
For the client I suppose you generated a proxy unit that generally creates an object called ServerMethods1 ?
You must pass the client dbx connection to this - I say this because I saw you put nil in your code.
// client
procedure TfrmClient.BGuardaClick(Sender: TObject);
var
sm : TServerMethods1Client; // <-- generated by proxy generator
idcliente,numero,cuenta,idbanco : integer;
fr,fc, titular : string ;
importe : Double;
cobrado : Boolean;
begin
sm := TServerMethods1Client.Create(SQL.DBXConnection);
if sm.nuevocheque(idcliente,numero,cuenta,idbanco, fr,fc, titular, importe, cobrado) then
// ok
else
// error
sm.Free;
end;
hth
You can use calls to remote methods, but they won't automatically update your data aware controls automatically. Datasnap is able to handle it. First, you need to add/update/remove data on the client. It happens in the local cache managed by the TClientDataset, even when you "Post".
When you're ready, you need to "apply" changes to the remote server calling the Apply() method.
When you call it, the provider component on the server receives a "delta" with the record to change from the client dataset, and will automatically generate the needed INSERT/UPDATED/DELETE SQL statements.
If you don't like them, or you need to perform more complex processing, you can use the provider events to perform the needed operations yourself for each changed record and then tell the provider you did it to avoid the automatic processing. Then the provider passes back the "delta" to the client, where it is used to updated the data aware controls. You can also modify the "delta" before it is passed back.
Read in the documentation the explanation of the Datasnap architecture - it's a multistep design where several components work to allow for a multi-tier implementation.

Refresh colors in cxGrid

I have a cxGrid where I change the background color of some fields based on values in some of the fields.
This is all working very fine. But if I cahnge something in the grids data, the colors aren't updated before I close an reopen my form.
What procedure to call to get this updated if the record is changing?
To my experience it does update when you switch the row. But i used it in DB-mode with TClientDataSet.
Check methods like
TcxControl.InvalidateRect
TcxControl.InvalidateRgn
TcxControl.InvalidateWithChildren
You can also invalidate node:
TcxGrid.ActiveView.Invalidate;
TcxGrid.ViewData.Records[0].Invalidate;
TcxGridViewData.Rows[0].Invalidate
TcxCustomGridTableController.FocusedRecord.Invalidate;
Events like
TcxCustomGridTableViewStyles.OnGetContentStyle
TcxCustomGridTableItem.OnCustomDrawCell
also exposes those items (with their Invalidate methods) among or inside parameters, like
ARecord: TcxCustomGridRecord;
ViewInfo -> TcxGridTableCellViewInfo.GridRecord
In other words - open the cxTL unit and grep for "invalidate" word and note every match.
If your grid is attached to a data set, and the data in the dataset changes, the OnGetContentStyle events are called automatically. Make sure that your dataset knows that the data is updated. It sounds like your editing form isn't telling the grid dataset to refresh itself. You can do that either with a callback procedure or implementing the Observer Pattern.
The following code demonstrates how to implement an OnGetContentStyle event for a grid column.
procedure TFormWithGrid.cxGrid1DBTableView1LASTNAMEStylesGetContentStyle(
Sender: TcxCustomGridTableView; ARecord: TcxCustomGridRecord;
AItem: TcxCustomGridTableItem; var AStyle: TcxStyle);
begin
if ARecord.Values[cxGrid1DBTableView1FIRSTNAME.Index] = 'test' then
begin
AStyle := TcxStyle.Create(nil);
AStyle.Color := clRed;
AStyle.Font.Style := [fsBold];
end;
end;
in my situation, this will works
cxGridDBTblVwContenido.DataController.Refresh;

Adding a calculated field to a Query at run time

I'm getting data using a query in Delphi, and would like to add a calculated field to the query before it runs. The calculated field is using values in code as well as the query so I can't just calculate it in SQL.
I know I can attach an OnCalcFields Event to actually make the calculation, but the problem is after adding the calculated field there are no other fields in the query...
I did some digging and found that all of the field defs are created but the actual fields are only created
if DefaultFields then
CreateFields
Default Fields is specified
procedure TDataSet.DoInternalOpen;
begin
FDefaultFields := FieldCount = 0;
...
end;
Which would indicate that if you add fields you only get the fields you added.
I would like all the fields in the query AS WELL AS the ones I Add.
Is this possible or do I have to add all the fields I'm using as well?
Nothing prevents you from creating all the fields first in your code,
then add your calculated fields.
You can either use a "hacked type" to use the protected CreateFields:
type
THackQuery = class(TADOQuery)
end;
[...]
MyQuery.FieldDefs.Update;
THackQuery(MyQuery).CreateFields;
or borrowing some code from CreateFields:
MyQuery.FieldDefs.Update;
// create all defaults fields
for I := 0 to MyQuery.FieldDefList.Count - 1 do
with MyQuery.FieldDefList[I] do
if (DataType <> ftUnknown) and not (DataType in ObjectFieldTypes) and
not ((faHiddenCol in Attributes) and not MyQuery.FIeldDefs.HiddenFields) then
CreateField(Self, nil, MyQuery.FieldDefList.Strings[I]);
then create your calculated fields:
MyQueryMyField := TStringField.Create(MyQuery);
with MyQueryMyField do
begin
Name := 'MyQueryMyField';
FieldKind := fkCalculated;
FieldName := 'MyField';
Size := 10;
DataSet := MyQuery;
end;
Delphi now has the option to combine automatic generated fields and calculated fields : Data.DB.TFieldOptions.AutoCreateMode an enumeration of type TFieldsAutoCreationMode. This way you can add your calculated fields at runtime. Francois wrote in his answer how to add a field at runtime.
Different modes of TFieldsAutoCreationMode :
acExclusive
When there are no persistent fields at all, then automatic fields are created. This is the default mode.
acCombineComputed
The automatic fields are created when the dataset has no persistent fields or there are only calculated persistent fields. This is a convenient way to create the persistent calculated fields at design time and let the dataset create automatic data fields.
acCombineAlways
Automatic fields for the database fields will be created when there are no persistent fields.
You need to add all fields in addition to your calculated field.
Once you add a field, you have to add all of the fields that you want in the data set.
Delphi calls this persistent fields versus dynamic fields. All fields are either persistent or dynamic. Unfortunately, you can't have a mixture of both.
Another thing to note, from the documentation is
Persistent fields component lists are
stored in your application, and do not
change even if the structure of a
database underlying a dataset is
changed.
So, be careful, if you later add additional fields to a table, you will need to add the new fields to the component. Same thing with deleting fields.
If you really don't want persistent fields, there is another solution. On any grid or control that should show the calculated field, you can custom draw it. For example, many grid controls have a OnCustomDraw event. You can do your calculation there.
If you have know your to be calculated fields names at runtime, you can use something like that.
var
initing:boolean;
procedure TSampleForm.dsSampleAfterOpen(
DataSet: TDataSet);
var
i:integer;
dmp:tfield;
begin
if not initing then
try
initing:=true;
dataset.active:=false;
dataset.FieldDefs.Update;
for i:=0 to dataset.FieldDefs.Count-1 do
begin
dmp:=DataSet.FieldDefs.Items[i].FieldClass.Create(self);
dmp.FieldName:=DataSet.FieldDefs.Items[i].DisplayName;
dmp.DataSet:=dataset;
if (dmp.fieldname='txtState') or (dmp.FieldName='txtOldState') then
begin
dmp.Calculated:=true;
dmp.DisplayWidth:=255;
dmp.size:=255;
end;
end;
dataset.active:=true;
finally
initing:=false;
end;
end;
procedure TSampleForm.dsSampleAfterClose(
DataSet: TDataSet);
var
i:integer;
dmp:TField;
begin
if not initing then
begin
for i:=DataSet.FieldCount-1 downto 0 do
begin
dmp:=pointer(DataSet.Fields.Fields[i]);
DataSet.Fields.Fields[i].DataSet:=nil;
freeandnil(dmp);
end;
DataSet.FieldDefs.Clear;
end;
end;
procedure TSampleForm.dsSampleCalcFields(
DataSet: TDataSet);
var
tmpdurum,tmpOldDurum:integer;
begin
if not initing then
begin
tmpDurum := dataset.FieldByName( 'state' ).AsInteger;
tmpOldDurum:= dataset.FieldByName( 'oldstate' ).AsInteger;
dataset.FieldByName( 'txtState' ).AsString := State2Text(tmpDurum);
dataset.FieldByName( 'txtOldState' ).AsString := State2Text(tmpOldDurum);
end;
end;
procedure TSampleForm.btnOpenClick(Sender: TObject);
begin
if dsSample.Active then
dsSample.Close;
dsSample.SQL.text:='select id,state,oldstate,"" as txtState,"" as txtOldState from states where active=1';
dsSample.Open;
end;

Resources