I have VirtualStringTree (VST) with nodes that have the next data structure :
Type
PMyNodeData = ^TMyNodeData;
TMyNodeData = record
Cost:UnicodeString;
end;
The Child nodes which they don't have any children has Cost value but any parent nodes has cost value equaled to 0 and am trying to write procedure to make any parent node cost value equaled to sum of all its children cost .
I have tried the next :
procedure CalculateSum(Node:PVirtualNode);
var
Data: PMyNodeData;
ChildNode: PVirtualNode;
ChildData: PMyNodeData;
CostSum: Extended;
begin
Data := VST.GetNodeData(Node);
CostSum := 0.0;
ChildNode := VST.GetFirstChild(Node);
while Assigned(ChildNode) do
begin
ChildData := VST.GetNodeData(ChildNode);
CostSum := CostSum + StrToFloat(ChildData.Cost);
CalculateSum(ChildNode);
ChildNode := VST.GetNextSibling(ChildNode);
end;
if VST.HasChildren[Node] and (StrToFloat(Data.Cost) = 0) then
Data.Cost := FloatToStr(CostSum);
end;
The use :
CalculateSum(vst.RootNode);
But I get Access violation & the sum is not correct .. any suggestions.
You are accessing a child's Cost before it has been calculated. You need to call CalculateSum(ChildNode) before adding its Cost to CostSum, rather than after as you are currently doing.
Also, you did not specify whether PMyDataNode is ever nil, or whether TMyNodeData.Cost contains a blank string for nodes whose value is 0. StrToFloat() will raise an exception if you give it a blank string. If that is a possibility, use StrToFloatDef() or TryStrToFloat() instead.
Try something more like this:
procedure CalculateSum(Node: PVirtualNode);
var
Data, ChildData: PMyNodeData;
ChildNode: PVirtualNode;
Cost, CostSum: Extended;
begin
if not VST.HasChildren[Node] then Exit;
Data := VST.GetNodeData(Node);
if Data = nil then Exit;
CostSum := 0.0;
ChildNode := VST.GetFirstChild(Node);
while Assigned(ChildNode) do
begin
ChildData := VST.GetNodeData(ChildNode);
if ChildData <> nil then
begin
CalculateSum(ChildNode);
if TryStrToFloat(ChildData.Cost, Cost) then
CostSum := CostSum + Cost;
// or:
// CostSum := CostSum + StrToFloatDef(ChildData.Cost, 0.0);
end;
ChildNode := VST.GetNextSibling(ChildNode);
end;
Data.Cost := FloatToStr(CostSum);
end;
That being said, I would suggest storing TMyNodeData.Cost as a Double/Extended instead of a UnicodeString. All of those conversions are just unnecessary overhead.
Try this instead:
Type
PMyNodeData = ^TMyNodeData;
TMyNodeData = record
Cost: Extended;
end;
...
procedure CalculateSum(Node: PVirtualNode);
var
Data, ChildData: PMyNodeData;
ChildNode: PVirtualNode;
CostSum: Extended;
begin
if not VST.HasChildren[Node] then Exit;
Data := VST.GetNodeData(Node);
if Data = nil then Exit;
CostSum := 0.0;
ChildNode := VST.GetFirstChild(Node);
while Assigned(ChildNode) do
begin
ChildData := VST.GetNodeData(ChildNode);
if ChildData <> nil then
begin
CalculateSum(ChildNode);
CostSum := CostSum + ChildData.Cost;
end;
ChildNode := VST.GetNextSibling(ChildNode);
end;
Data.Cost := CostSum;
end;
I have solved the issue as the next :
procedure CalculateSum(Node: PVirtualNode);
var
Data: PMyNodeData;
ChildNode: PVirtualNode;
ChildData: PMyNodeData;
CostSum: Extended;
begin
Data := VST.GetNodeData(Node);
if data<>nil then
CostSum := Data.Cost else Costsum:=0.0;
ChildNode := VST.GetFirstChild(Node);
while Assigned(ChildNode) do
begin
ChildData := VST.GetNodeData(ChildNode);
if ChildData <> nil then
begin
CalculateSum(ChildNode);
CostSum := CostSum + ChildData.Cost;
end;
ChildNode := VST.GetNextSibling(ChildNode);
end;
if (VST.HasChildren[Node]) and (Data<>nil) then
Data.Cost := CostSum;
end;
Related
I have saved my TreeView inside my DataBase by using the next :
var
BlobField :TField;
Query:TADOQuery;
Stream:TStream;
...
try
Query.SQL.Text := 'Select TOP(1) * From MyTable';
DBQueryConnect(Query); // I used this Procedure to connect the Query to the database
try
Query.First;
Query.Edit;
try
BlobField := Query.FieldByName('MyField') as TField;
Stream := Query.CreateBlobStream(BlobField, bmWrite);
try
MyTreeView.SaveToStream(Stream,TEncoding.UTF8);
finally
Stream.Free;
end;
Query.Post;
except
Query.Cancel;
raise;
end;
finally
Query.Close;
end;
finally
Query.Free;
end;
end;
and I loaded back the TTreeView form the DataBase by using the next :
...
var
Query:TADOQuery;
Stream:TStream;
begin
Query:=TADOQuery.Create(Self);
try
Query.SQL.Add('Select * From MyTable') ;
DBQueryConnect(Query);
Query.First;
Stream:=Query.CreateBlobStream(Query.FieldByName('MyField'), bmread);
MyTreeView.LoadFromStream(Stream);
Stream.Free;
finally
Query.Free;
end;
how can I retrive the imageindex for my TreeView items from the saved data ..
Thank you .
Perharps we can modify exsisting SaveTreeToStream and LoadTreeFromStream like this :
function GetBufStart(Buffer,idxSeparator: string; var Level,ImageIndex: Integer): string;
var
Pos: Integer;
sidx:String;
begin
Pos := 1;
Level := 0;
ImageIndex := -1;
while (CharInSet(Buffer[Pos], [' ', #9])) do
begin
Inc(Pos);
Inc(Level);
end;
Result := Copy(Buffer, Pos, Length(Buffer) - Pos + 1);
//Check Image Index
pos:=System.SysUtils.AnsiPos(idxSeparator,Result);
if Pos>0 then begin
sidx:=copy(result,Pos + Length(idxSeparator), length(result) - Pos + 1);
ImageIndex := StrToIntDef(sidx,-1);
Result := Copy(Result, 1, Pos - 1);
end;
end;
procedure LoadTreeFromStream(Nodes:TTreeNodes; Stream:TStream; Encoding:TEncoding; idxSeparator:String='|||');
var
List: TStringList;
ANode, NextNode: TTreeNode;
ALevel, i, ImageIndex: Integer;
CurrStr: string;
begin
List := TStringList.Create;
Nodes.BeginUpdate;
try
try
Nodes.Clear;
List.LoadFromStream(Stream, Encoding);
ANode := nil;
for i := 0 to List.Count - 1 do
begin
CurrStr := GetBufStart(PChar(List[i]), idxSeparator, ALevel, ImageIndex);
if ANode = nil then
ANode := Nodes.AddChild(nil, CurrStr)
else if ANode.Level = ALevel then
ANode := Nodes.AddChild(ANode.Parent, CurrStr)
else if ANode.Level = (ALevel - 1) then
ANode := Nodes.AddChild(ANode, CurrStr)
else if ANode.Level > ALevel then
begin
NextNode := ANode.Parent;
while NextNode.Level > ALevel do
NextNode := NextNode.Parent;
ANode := Nodes.AddChild(NextNode.Parent, CurrStr);
end
else raise Exception.CreateFmt('Invalid level (%d) for item "%s"', [ALevel, CurrStr]);
ANode.ImageIndex:=ImageIndex;
end;
finally
Nodes.EndUpdate;
List.Free;
end;
except
Nodes.Owner.Invalidate; // force repaint on exception
raise;
end;
end;
procedure SaveTreeToStream(Nodes:TTreeNodes; Stream:Tstream; Encoding:TEncoding; idxSeparator:String='|||');
const
TabChar = #9;
EndOfLine = #13#10;
var
I: Integer;
ANode: TTreeNode;
NodeStr: TStringBuilder;
Buffer, Preamble: TBytes;
begin
if Nodes.Count > 0 then
begin
if Encoding = nil then
Encoding := TEncoding.Default;
//Buffer := Encoding.GetBytes('');
Preamble := Encoding.GetPreamble;
if Length(Preamble) > 0 then
Stream.WriteBuffer(Preamble{$IFNDEF CLR}[0]{$ENDIF}, Length(Preamble));
NodeStr := TStringBuilder.Create(1024);
try
ANode := Nodes[0];
while ANode <> nil do
begin
NodeStr.Length := 0;
for I := 0 to ANode.Level - 1 do
NodeStr.Append(TabChar);
NodeStr.Append(ANode.Text);
NodeStr.Append(idxSeparator);
NodeStr.Append(ANode.ImageIndex);
NodeStr.Append(EndOfLine);
Buffer := Encoding.GetBytes(NodeStr.ToString);
Stream.Write(Buffer{$IFNDEF CLR}[0]{$ENDIF}, Length(Buffer));
ANode := ANode.GetNext;
end;
finally
NodeStr.Free;
end;
end;
end;
You can replace
MyTreeView.SaveToStream(Stream,TEncoding.UTF8);
with
SaveTreeToStream(MyTreeView.Items,Stream,TEncoding.UTF8);
and MyTreeView.LoadFromStream(Stream); with LoadTreeFromStream(MyTreeView.Items,Stream,TEncoding.UTF8);
I am a newbie in Delphi programming and I need some help. I have a problem with spliting my serial data. This is my code:
procedure TForm1.ComPort1RxChar(Sender: TObject; Count: Integer);
var
DataByte : string;
x, i: integer;
save_data : TStringList;
begin
save_data := TStringList.create;
for x := 0 to Count-1 do begin
ComPort1.ReadStr(DataByte,1);
if DataByte = 'n' then
begin
memo1.Text := '';
end
else
begin
memo1.Text := memo1.Text + DataByte;
Split(' ', DataByte, save_data);
end;
end;
save_gyroX := save_data[0];
save_gyroY := save_data[1];
save_gyroZ := save_data[2];
save_accelX := save_data[3];
save_accelY := save_data[4];
save_accelZ := save_data[5];
SerialProcess();
save_data.Free;
end;
My Split(' ', DataByte, save_data); doesn't work. I don't understand because I just split String data which is taken from the serial port. This is my Split() procedure:
procedure TForm1.Split(const Delimiter: Char; Input: string; const Strings: TStrings) ;
begin
Assert(Assigned(Strings));
Strings.Clear;
Strings.Delimiter := Delimiter;
Strings.DelimitedText := Input;
end;
I do not know why my program is giving me a EStringListError error.
You are calling ReadStr() to read individual bytes, and calling Split() on every byte (except for 'n'). So the TStringList will only ever hold 1 string at a time. Like MBo said, you need to fix your loop to avoid that, eg:
procedure TForm1.ComPort1RxChar(Sender: TObject; Count: Integer);
var
DataByte : string;
x: integer;
save_data : TStringList;
begin
ComPort1.ReadStr(DataByte, Count);
for x := 1 to Length(DataByte) do
begin
if DataByte[x] = 'n' then
begin
Memo1.Text := '';
end
else
begin
Memo1.Text := Memo1.Text + DataByte[x];
end;
end;
save_data := TStringList.create;
try
Split(' ', DataByte, save_data);
save_gyroX := save_data[0];
save_gyroY := save_data[1];
save_gyroZ := save_data[2];
save_accelX := save_data[3];
save_accelY := save_data[4];
save_accelZ := save_data[5];
SerialProcess();
finally
save_data.Free;
end;
end;
That being said, you are not taking into account that the number of bytes you receive for any given OnRxChar event call is arbitrary. It is whatever raw bytes have been read at that exact moment. You are assuming a full string with at least 6 delimited substrings, and that is simply not guaranteed. You need to buffer the raw data as you receive it, and then parse and remove only completed strings from the buffer as needed.
Try something more like this:
var
DataBuffer: string;
// consider using the OnRxBuf event instead...
procedure TForm1.ComPort1RxChar(Sender: TObject; Count: Integer);
var
DataByte : string;
x: integer;
save_data : TStringList;
begin
ComPort1.ReadStr(DataByte, Count);
DataBuffer := DataBuffer + DataByte;
x := Pos('n', DataBuffer);
if x = 0 then Exit;
save_data := TStringList.Create;
try
repeat
DataByte := Copy(DataBuffer, 1, x-1);
Delete(DataBuffer, 1, x);
Memo1.Text := DataByte;
Split(' ', DataByte, save_data);
if save_data.Count >= 6 then
begin
save_gyroX := save_data[0];
save_gyroY := save_data[1];
save_gyroZ := save_data[2];
save_accelX := save_data[3];
save_accelY := save_data[4];
save_accelZ := save_data[5];
SerialProcess();
end;
x := Pos('n', DataBuffer);
until x = 0;
finally
save_data.Free;
end;
end;
if Comport is Dejan Crnila CPort class, then this line
ComPort1.ReadStr(DataByte,1);
replaces Databyte contents every time, and this string always is 1-byte length.
Just read all bytes from buffer with single call
ComPort1.ReadStr(DataByte, Count);
and do work with string
I'm using a TVirtualStringTree to store pointers to records.
Originally there is a TList that contains the list of records.
I'm using the OnInitNode event to iterate through the TList and assign each records' data to the tree's nodes.
However, when retrieving the data associated with a node in the OnNewText event handler, the pointer returned has a different address than the one originally stored in the tree.
Further, I can see through debugging that the pointer (to the record data) retrieved from the node is not the same as the one originally stored in the node. I need to save changed data to a database and need to reference the record with the changed data. It should be simple as referencing the pointer, but the problem is that the pointer is not the same.
I'm not sure what I'm doing wrong and hope someone can help me fix this.
Thanks in advance.
Here is my code:
Data structure and declarations:
TTherapData = record
TherapID: Integer;
TherapName: String[120];
TherapInstr: String[120];
Selected_DB: Byte;
Selected: Byte;
end;
PTherapData = ^TTherapData;
FTherapDataList: TList<PTherapData>;
FTherapDataListAsg_Iter: Integer;
vstRxList_Asg: TVirtualStringTree;
Loading the data into the TList, and then into the tree:
procedure TfmPatient_Conslt.LoadTherapList(const ADBLoad: Boolean = False);
var
TherapData: PTherapData;
d, x: Integer;
begin
datamod.uspLKTHERAP_S.First;
while not datamod.uspLKTHERAP_S.Eof do
begin
New(TherapData);
TherapData^.TherapID := datamod.uspLKTHERAP_SROW_ID.AsInteger;
TherapData^.TherapName := datamod.uspLKTHERAP_SIMPRTHERAP.AsString;
TherapData^.TherapInstr := EmptyStr;
TherapData^.Selected := 0;
TherapData^.Selected_DB := 0;
FTherapDataList.Add(TherapData);
datamod.uspLKTHERAP_S.Next;
end;
datamod.uspCONSLT_RX_S.First;
while not datamod.uspCONSLT_RX_S.Eof do
begin
d := datamod.uspCONSLT_RX_SRX_ID.AsInteger;
TherapData := FTherapDataList[TherapDataList_GetIndexOfID(d)];
TherapData^.TherapInstr := datamod.uspCONSLT_RX_SRX_INSTRUCTION.AsString;
TherapData^.Selected := 1;
TherapData^.Selected_DB := 1;
datamod.uspCONSLT_RX_S.Next;
end;
x := TherapDataList_CountSelectedItems;
FTherapDataListAsg_Iter := 0;
vstRxList_Asg.NodeDataSize := SizeOf(TTherapData);
vstRxList_Asg.RootNodeCount := 0;
vstRxList_Asg.RootNodeCount := x;
end;
procedure TfmPatient_Conslt.vstRxList_AsgInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode;
var InitialStates: TVirtualNodeInitStates);
var
TherapData: PTherapData;
begin
TherapData := Sender.GetNodeData(Node);
while (FTherapDataList[FTherapDataListAsg_Iter]^.Selected <> 1) do
Inc(FTherapDataListAsg_Iter);
TherapData^.TherapID := FTherapDataList[FTherapDataListAsg_Iter]^.TherapID;
TherapData^.TherapName := FTherapDataList[FTherapDataListAsg_Iter]^.TherapName;
TherapData^.TherapInstr := FTherapDataList[FTherapDataListAsg_Iter]^.TherapInstr;
{ TherapData := FTherapDataList[FTherapDataListAsg_Iter]; } //
{ TherapData^ := FTherapDataList[FTherapDataListAsg_Iter]^; } //
Inc(FTherapDataListAsg_Iter);
end;
procedure TfmPatient_Conslt.vstRxList_AsgGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex;
TextType: TVSTTextType; var CellText: string);
var
TherapData: PTherapData;
begin
TherapData := Sender.GetNodeData(Node);
if Assigned(TherapData) then
if (Column = 0) then
CellText := TherapData^.TherapName
else if (Column = 1) then
CellText := TherapData^.TherapInstr;
end;
procedure TfmPatient_Conslt.vstRxList_AsgEditing(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex;
var Allowed: Boolean);
begin
Allowed := (Column = 1);
end;
Retrieving the data. I noticed the problem here:
procedure TfmPatient_Conslt.vstRxList_AsgNewText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex;
NewText: string);
var
TherapData: PTherapData;
begin
if (Column = 1) then
begin
TherapData := Sender.GetNodeData(Node);
if Assigned(TherapData) then // <---- There is a debug breakpoint here
// and the watch window screen-shot
// is taken here
TherapData^.TherapInstr := NewText;
// Showmessage(Format('%p', [TherapData])); // <---- The pointer value is not the same
// as that originally stored !
end;
end;
This is where I save the list data to database, and the reason that I need the tree to change the original data and not a copy:
procedure TfmPatient_Conslt.SaveRxListToDB;
var
TherapData: PTherapData;
begin
for TherapData in FTherapDataList do
begin
if (TherapData^.Selected = 1) and (TherapData^.Selected_DB = 0) then
begin
// Add new entries to DB
// :ROW_ID, :CONSLT_ID, :RX_ID, :RX_INSTRUCTION
datamod.uspCONSLT_RX_I.ParamByName('ROW_ID').AsInteger := 0;
datamod.uspCONSLT_RX_I.ParamByName('CONSLT_ID').AsInteger := FConsultationID;
datamod.uspCONSLT_RX_I.ParamByName('RX_ID').AsInteger := TherapData^.TherapID;
datamod.uspCONSLT_RX_I.ParamByName('RX_INSTRUCTION').AsString := TherapData^.TherapInstr;
datamod.uspCONSLT_RX_I.PrepareSQL(False);
datamod.uspCONSLT_RX_I.ExecProc;
TherapData^.Selected_DB := 1;
end
else if (TherapData^.Selected = 1) and (TherapData^.Selected_DB = 1) then
begin
// Update existing DB entries
// :CONSLT_ID, :RX_ID, :RX_INSTRUCTION
datamod.uspCONSLT_RX_U.ParamByName('CONSLT_ID').AsInteger := FConsultationID;
datamod.uspCONSLT_RX_U.ParamByName('RX_ID').AsInteger := TherapData^.TherapID;
datamod.uspCONSLT_RX_U.ParamByName('RX_INSTRUCTION').AsString := TherapData^.TherapInstr;
datamod.uspCONSLT_RX_U.PrepareSQL(False);
datamod.uspCONSLT_RX_U.ExecProc;
end
else if (TherapData^.Selected = 0) and (TherapData^.Selected_DB = 1) then
begin
// Delete removed entries from DB
// :CONSLT_ID, :RX_ID
datamod.uspCONSLT_RX_D.ParamByName('CONSLT_ID').AsInteger := FConsultationID;
datamod.uspCONSLT_RX_D.ParamByName('RX_ID').AsInteger := TherapData^.TherapID;
datamod.uspCONSLT_RX_D.PrepareSQL(False);
datamod.uspCONSLT_RX_D.ExecProc;
TherapData^.Selected_DB := 0;
end;
end;
end;
Here's a screenshot of the from the Debug->Watch List window:
To answer to the question in the title, I would say yes, your coding approach is wrong.
The mistake is that you don't save a pointer to your data record to the VT's node, you're allocating whole (separate) TTherapData record for each node! So the "mistake" is the line
vstRxList_Asg.NodeDataSize := SizeOf(TTherapData);
in the TfmPatient_Conslt.LoadTherapList method. What you probably want is an additional record which holds pointer to the data record:
type
TVTNodeData = record
TherapData: PTherapData;
end;
PVTNodeData = ^TVTNodeData;
and use that record as node data record:
vstRxList_Asg.NodeDataSize := SizeOf(TVTNodeData);
and node init becomes something like
procedure TfmPatient_Conslt.vstRxList_AsgInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates);
var
NodeData: PVTNodeData;
begin
NodeData := Sender.GetNodeData(Node);
while (FTherapDataList[FTherapDataListAsg_Iter]^.Selected <> 1) do
Inc(FTherapDataListAsg_Iter);
NodeData^.TherapData := FTherapDataList[FTherapDataListAsg_Iter];
Inc(FTherapDataListAsg_Iter);
end;
and using the data in other tree events like
procedure TfmPatient_Conslt.vstRxList_AsgGetText(Sender: TBaseVirtualTree; Node:PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string);
var
NodeData: PVTNodeData;
TherapData: PTherapData;
begin
NodeData := Sender.GetNodeData(Node);
if Assigned(NodeData) and Assigned(NodeData.TherapData) then begin
TherapData := NodeData.TherapData;
if (Column = 0) then
CellText := TherapData^.TherapName
else if (Column = 1) then
CellText := TherapData^.TherapInstr;
end;
end;
hi i have a problem with TClientDataset in Delphi. I want to get a Dataset with the changed Data.
here is my code:
procedure TForm2.btnUpdateClick(Sender: TObject);
var
I: Integer;
counter : Integer; //for testing
value : String;
begin
if not Self.DatasetArtikel.Active then
begin
ShowMessage('Nicht aktiv');
Exit;
end;
if Self.DatasetArtikel.ChangeCount = 0 then
begin
ShowMessage('Delta is empty');
Exit;
end;
counter := DatasetArtikel.ChangeCount;
//DatasetArtikelUpdate.ClearFields;
//DatasetArtikelUpdate.CreateDataSet;
DatasetArtikel.Data := Self.DatasetArtikel.Delta; //here i want to transfer the changed data
Release;
//for I := 0 to DatasetArtikelUpdate.Fields.Count -1 do
// if not DatasetArtikelUpdate.Fields[I].IsNull then
// value := DatasetArtikelUpdate.Fields[I].NewValue;
value := DatasetArtikel.Fields[2].OldValue;
value := DatasetArtikel.Fields[2].Value;
value := DatasetArtikel.Fields[2].NewValue; //here i want the new data
end;
for example: In column 3 is the text blueblue and I changed it to redred. the counter say me that 1 is changed it is correct but the value said me that the string is blueblue...but I want the data redred :((
There is no NewValue/OldValue information stored on the field.
Delta will contain
1 Row for deleted rows
1 Row for new inserted rows
2 Rows for modified rows
For every row you can ask for delta.UpdateStatus which can be usUnmodified, usModified, usInserted or usDeleted.
Every unmodified record is followed by a Record with the modifications.
You will take a look in both records to get Old- and NewValue.
procedure TTestForm.RunInfoClick(Sender: TObject);
type
TMyFieldInfo = Record
FieldName: String;
Size: Integer;
DataType: TFieldType;
FieldKind: TFieldKind;
end;
var
I: Integer;
sl: TStringList;
old: String;
FA: Array of TMyFieldInfo;
F: TField;
// get fielddefs after openening and a a definition for a calculated field
// called Status to refect UpdateStatus
Procedure GetFields;
var
I: Integer;
begin
SetLength(FA, delta.FieldCount + 1);
for I := 0 to delta.FieldCount - 1 do
begin
FA[I].FieldName := delta.Fields[I].FieldName;
FA[I].DataType := delta.Fields[I].DataType;
FA[I].Size := delta.Fields[I].Size;
FA[I].FieldKind := fkdata;
end;
FA[High(FA)].FieldName := 'Status';
FA[High(FA)].DataType := ftString;
FA[High(FA)].Size := 10;
FA[High(FA)].FieldKind := fkcalculated;
delta.Close;
end;
// apply our fields to be able to display a calculated field
Procedure SetFields;
var
I: Integer;
begin
delta.Fields.Clear;
for I := Low(FA) to High(FA) do
begin
F := DefaultFieldClasses[FA[I].DataType].Create(delta);
With F do
begin
FieldName := FA[I].FieldName;
FieldKind := FA[I].FieldKind;
Size := FA[I].Size;
DataSet := delta;
end;
end;
delta.Open;
end;
Procedure LogSL;
begin
if sl.Count > 1 then
Memo1.Lines.Add(sl.Text);
sl.Clear;
end;
begin
Memo1.Lines.Clear;
sl := TStringList.Create;
try
delta.Close;
delta.Fields.Clear;
delta.Data := ClientDataSet1.delta;
GetFields;
SetFields;
while not delta.Eof do
begin
if delta.UpdateStatus <> usModified then
begin
LogSL;
end;
if delta.UpdateStatus = usUnmodified then
sl.Add('Unmodified:')
else if delta.UpdateStatus = usInserted then
begin
sl.Add('Insert:');
end
else if delta.UpdateStatus = usDeleted then
begin
sl.Add('Deleted:');
end
else if delta.UpdateStatus = usModified then
begin
sl[0] := ('Modified:');
end;
for I := 0 to delta.FieldCount - 2 do // ignore our calculated field
begin
if delta.UpdateStatus = usModified then
begin
if (sl.Values[delta.Fields[I].FieldName] <> delta.Fields[I].AsString) and not delta.Fields[I].IsNull then
begin // we had changes
sl[I + 1] := sl[I + 1] + ' OldValue: ' + delta.Fields[I].AsString;
end
else
begin // we did not have changes take stored OldValue
sl[I + 1] := sl[I + 1] + ' OldValue: ' + sl.Values[delta.Fields[I].FieldName];
end
end
else // delta.UpdateStatus = usModified
sl.Add(delta.Fields[I].FieldName + '=' + delta.Fields[I].AsString + old);
end;
delta.Next;
end;
LogSL;
finally
sl.Free;
end;
end;
procedure TTestForm.deltaCalcFields(DataSet: TDataSet);
begin
with TClientDataSet(DataSet) do
begin
case UpdateStatus of
usUnmodified:
FieldByName('Status').AsString := 'Unmod';
usModified:
FieldByName('Status').AsString := 'Modi';
usInserted:
FieldByName('Status').AsString := 'Ins';
usDeleted:
FieldByName('Status').AsString := 'Del';
end;
end;
end;
I have run into trouble trying to access the pointer to a record type in my record data using Delphi's RTTI.
Please check the sample code that i have been working on.
// Dummy Header
typDummyHeader = ^tysDummyHeader;
tysDummyHeader = record
MessageCode : Integer;
MessageLength : Integer;
end;
// Dummy record having header and trailer
tysDummyRecord = record
Header : tysDummyHeader;
BotAmount : Double;
SoldAmount : Double;
SoldQty : Int64;
BotQty : Int64;
Tailer : typDummyHeader; // pointer to Dummy Header
end;
TclDummy = class
class function GetFieldValue<T>(const pipInstance : Pointer;
const piclField : TRttiField) : string;
class function ParseAndReturnString<T>(piclObject : T) : string;
end;
var
frmRTTITest: TfrmRTTITest;
implementation
{$R *.dfm}
procedure TfrmRTTITest.FormCreate(Sender: TObject);
var
losDummyRecord : tysDummyRecord;
begin
FillChar(losDummyRecord, SizeOf(tysDummyRecord), #0);
losDummyRecord.Header.MessageCode := 5000;
losDummyRecord.Header.MessageLength := 54433;
losDummyRecord.BotAmount := 19.45;
losDummyRecord.SoldAmount := 34.22;
losDummyRecord.SoldQty := 102;
losDummyRecord.BotQty := 334;
losDummyRecord.Tailer := #losDummyRecord.Header;
ShowMessage(TclDummy.ParseAndReturnString<tysDummyRecord>(losDummyRecord));
end;
class function TclDummy.GetFieldValue<T>(const pipInstance : Pointer;
const piclField : TRttiField) : string;
begin
case piclField.FieldType.TypeKind of
tkFloat: Result := FloatToStr(piclField.GetValue(pipInstance).AsExtended);
tkInt64: Result := IntToStr(piclField.GetValue(pipInstance).AsInt64);
tkInteger: Result := IntToStr(piclField.GetValue(pipInstance).AsInteger);
tkString: Result := Trim(piclField.GetValue(pipInstance).AsString);
end;
end;
class function TclDummy.ParseAndReturnString<T>(piclObject : T) : string;
var
losContext : TRttiContext;
losContextType : TRttiType;
loclField : TRttiField;
losRecordRTTI : TRttiRecordType;
loclRecordField : TRttiField;
losPointerType : TRttiPointerType;
losValue : TValue;
begin
Result := EmptyStr;
losContext := TRttiContext.Create;
losContextType := losContext.GetType(TypeInfo(T));
if losContextType.TypeKind = tkRecord then
begin
for loclField in losContextType.GetFields do
begin
case loclField.FieldType.TypeKind of
tkRecord:
begin
losRecordRTTI := loclField.FieldType.AsRecord;
for loclRecordField in losRecordRTTI.GetFields do
begin
Result := Result + '|' + GetFieldValue<T>(Addr(piclObject), loclRecordField);
end;
end; // tkRecord
tkPointer:
begin
losPointerType := loclField.FieldType as TRttiPointerType;
// Check only record type pointers.
if losPointerType.ReferredType.TypeKind = tkRecord then
begin
losValue := loclField.GetValue(Addr(piclObject));
if (not losValue.IsEmpty) then
begin
for loclRecordField in losPointerType.ReferredType.GetFields do
begin
// Result := Result + '|' + ???????????
end;
end;
end;
end; // tkPointer
else
Result := Result + '|' + GetFieldValue<T>(Addr(piclObject), loclField);
end;
end;
end;
losContext.Free;
end;
In the above sample, when the field is tkPointer which is pointing to a record type, how do I read the values from that ?
Result := Result + '|' + GetFieldValue<T>(Addr(piclObject),loclRecordField);
should do the job.
Sorry for my poor English.
Answer of #bummi works but is not right.
It depends on usage.
If you use next code all works well:
var
losDummyRecord : tysDummyRecord;
begin
FillChar(losDummyRecord, SizeOf(tysDummyRecord), #0);
losDummyRecord.Header.MessageCode := 5000;
losDummyRecord.Header.MessageLength := 54433;
losDummyRecord.BotAmount := 19.45;
losDummyRecord.SoldAmount := 34.22;
losDummyRecord.SoldQty := 102;
losDummyRecord.BotQty := 334;
losDummyRecord.Tailer := #losDummyRecord.Header;
ShowMessage(TclDummy.ParseAndReturnString<tysDummyRecord>(losDummyRecord));
But if you use for example this code, parsing don't work correctly:
var
losDummyRecord : tysDummyRecord;
ExternalHeaderVar: tysDummyHeader;
begin
ExternalHeaderVar.MessageCode := 23;
ExternalHeaderVar.MessageLength := 25;
FillChar(losDummyRecord, SizeOf(tysDummyRecord), #0);
losDummyRecord.Header.MessageCode := 5000;
losDummyRecord.Header.MessageLength := 54433;
losDummyRecord.BotAmount := 19.45;
losDummyRecord.SoldAmount := 34.22;
losDummyRecord.SoldQty := 102;
losDummyRecord.BotQty := 334;
losDummyRecord.Tailer := #ExternalHeaderVar;
ShowMessage(TclDummy.ParseAndReturnString<tysDummyRecord>(losDummyRecord));
Solutions is simple and works in both cases well and prevents unexpected errors in the future use:
tkPointer:
begin
losPointerType := loclField.FieldType as TRttiPointerType;
// Check only record type pointers.
if losPointerType.ReferredType.TypeKind = tkRecord then
begin
losValue := loclField.GetValue(Addr(piclObject));
if (not losValue.IsEmpty) then
begin
losValue.ExtractRawDataNoCopy(#NativeIntVar);
for loclRecordField in losPointerType.ReferredType.GetFields do
begin
Result := Result + '|' + GetFieldValue<T>(Pointer(NativeIntVar),loclRecordField);
end;
end;
end;
end; // tkPointer