Read all section .ini values into stringgrid - delphi

I use Delphi XE7. Is there any way to load all values from an .ini file into a stringgrid in different coloumns?
My .ini file looks like
[1038]
AValue = a1
BValue = b1
CValue = c1
DValue = d1
[1031]
AValue = a2
BValue = b2
CValue = c2
DValue = d2
I use this procedure for filling the grid:
procedure TForm1.ReadIntoGrid(const aIniFileName, aSection: string;
const aGrid: TStringGrid);
var
Ini: TIniFile;
SL: TStringList;
i: Integer;
begin
SL := TStringList.Create;
try
Ini := TIniFile.Create(aIniFileName);
try
aGrid.ColCount := 2;
Ini.ReadSectionValues(aSection, SL);
aGrid.RowCount := SL.Count;
for i := 0 to SL.Count - 1 do
begin
aGrid.Cells[0,i] := SL.Names[i];
aGrid.Cells[1,i] := SL.ValueFromIndex[i];
end;
finally
Ini.Free;
end;
finally
SL.Free;
end;
end;
It works fine, I get this:
My question is...
How can I read all section values (1038 and 1031) into the grid next to the 1038 values? Values will be fixed all time.

To give you some ideas:
First, i think you should add one paramater to your procedure:
procedure TForm1.ReadIntoGrid(const aIniFileName, aSection: string;
const aGrid: TStringGrid; const aColumn: Integer = 1);
Second, rewrite this part of your method :
for i := 0 to SL.Count - 1 do
begin
aGrid.Cells[0,i] := SL.Names[i];
aGrid.Cells[1,i] := SL.ValueFromIndex[i];
end;
replace with
for i := 0 to SL.Count - 1 do
begin
aGrid.Cells[0,i] := SL.Names[i];
aGrid.Cells[aColumn,i] := SL.ValueFromIndex[i];
end;
ps: Obviously you dont nead to rewrite the value into the first column.
So now assume you are calling the method like this:
ReadIntoGrid('MyIniFile.ini','1038', MyGrid, 1);
ReadIntoGrid('MyIniFile.ini','1031', MyGrid, 2);

Related

How to read an integer value into a TCheckColumn in Delphi FMX with TStringGrid?

I need to make the TCheckColumn from the FMX.StringGrid to work from an integer value but I don't know how.
My code reads from a JSON request and translates it to a stringgrid. In the database the "boolean" field is stored as integer, so 0 for false and 1 for true.
This is the code that reads from the request:
procedure TDM.CarregaDados(aTable: string; aGrid: TStringGrid);
begin
TThread.CreateAnonymousThread(
procedure
var
str: string;
begin
aGrid.RowCount := 0;
REST.Response := nil;
REST.Resource := aTable;
REST.Method := rmGET;
REST.Params.ClearAndResetID;
REST.Execute;
RESTDSA.Response := REST.Response;
RESTDSA.DataSet := RESTDS;
RESTDSA.Active := true;
TThread.Synchronize(nil,
procedure
var
I: Integer;
begin
aGrid.BeginUpdate;
while not RESTDS.Eof do
begin
aGrid.RowCount := aGrid.RowCount + 1;
for I := 0 to RESTDS.FieldCount - 1 do
aGrid.Cells[I, aGrid.RowCount - 1] := RESTDS.Fields.Fields
[I].AsString;
RESTDS.Next;
end;
aGrid.EndUpdate;
end);
REST.ClearBody;
REST.Params.ClearAndResetID;
end).Start;
end;
REST is the TRESTRequest component,
RESTDS is the TFDMemTable,
RESTDSA is the TRESTRequestDataSetAdapter component,
aGrid is a TStringGrid and
aTable is the endpoint resource.
What I wanna know is how I can tweak this code to make it work with TCheckColumn in my grid. Yes, Of course I have a TIntegerColumn, a TStringColumn and a TCheckColumn previously added to the grid.
This is an example JSON response:
[
{
"ID" : 1,
"Descr" : "test",
"ischeck" : 0
},
{
"ID" : 2,
"Descr" : "test",
"ischeck" : 1
}
]
Well I know It's late, but I am a newbie here, and it's the first time I use FMX.TStringGrid without Livebindings.
I found a solution to this problem, with my own data
procedure TCsv4Presta.StringGrid1CellClick(const Column: TColumn;
const Row: Integer);
begin
case Column.Index of
0 : begin // my checkboxcolumn
StringGrid1.Cells[0,Row]:= BooltoStr(Not StrToBool(StringGrid1.Cells[0,Row]),true);
Column.UpdateCell(Row); // important to refresh checkbox
end;
end;
end;
just a problem with this onclick, you have to manage click in the cell but not on the checkbox
So I can suggest you a code like
while not RESTDS.Eof do
begin
aGrid.RowCount := aGrid.RowCount + 1;
for I := 0 to RESTDS.FieldCount - 1 do
begin
if aGrid.Columns[I] is TCheckBoxColumn then
begin
aGrid.Cells[I, aGrid.RowCount - 1] := BooltoStr(RESTDS.Fields.Fields
[I].AsString='1',true) ;
// Column.UpdateCell(Row);
end
else aGrid.Cells[I, aGrid.RowCount - 1] := RESTDS.Fields.Fields
[I].AsString;
end;
RESTDS.Next;
end;

how to get two different file with this procedure in deplhi

i want to get value from two file .txt, one file contain different dimension matrix with other
i have try this code:
procedure TfrmJST.ParseDelimited(const S1: TStrings; const Value: String; const Delimiter: String);
var
dx,cx: integer;
ns,ms: String;
txt: string;
delta,teta: integer;
procedure TfrmJST.ParseDelimited(const S1: TStrings; const Value: String; const Delimiter: String);
var
dx,cx: integer;
ns,ms: String;
txt: string;
delta,teta: integer;
begin
Col := 1;
Delta := Length(Delimiter);
Txt := Value+Delimiter;;
begin
while Length(Txt) > 1 do
begin
Dx := Pos(Delimiter, Txt);
Ns := Trim(Copy(Txt, 1, Dx-1));
// S1.Add('#'+Ns+'*'); //only needed for testing
if Ns <> '' then
begin
Matrix[Row,Col] := StrToFloat(Ns); //for first matrix
Inc(Col);
end;
Txt := Copy(Txt, Dx+Delta, MaxInt);
end;
end;
Col := 1;
teta := Length(delimiter);
txt := value+delimiter;
begin
while Length(txt) > 1 do
begin
cx := Pos(delimiter, txt);
ms := Copy(txt, 1, cx-1);
if ms <> '' then
begin
ref[Row,Col] := StrToFloat(ms); ///for 2nd matrix
Inc(Col);
end;
txt := Copy(txt, cx+teta, MaxInt);
end;
end;
end;
and this is initialize of matrix:
private
{ Private declarations }
Row, Col: integer;
Matrix: array[1..140,1..141] of double;
Ref: array[1..2,1..140] of double ;
this is the implementation:
begin
Temp := TStringList.Create;
MemoSL:= TStringList.Create ;
Temp.LoadFromFile('trainer.txt');
Row := 1;
for I := 0 to Temp.Count-1 do
begin
ParseDelimited(MemoSL, Trim(Temp.Strings[I]), ' ');
Inc(Row); //stackoverflow error in this line
end;
Temp.Free;
//parsing second matrix
TempList := TStringList.Create;
Templist.LoadFromFile('refbaru.txt');
row := 1;
for J := 0 to Templist.Count-1 do
begin
T := Templist[J];
ParseDelimited(Memo1.Lines, T, ' ');
Inc(row);
end;
Templist.Free;
i tried that code but give me error,
the error was stackoverflow error in line 'inc(row)' that process first matrix.
and while i gave comment out at the second function that process 2nd matrix, Temp[i] only returns 2 rows of matrix[140x141]. does it mean the code can't process two different file? and why it only return two rows of the matrix?
anyone can help me?
while Length(Txt) > 1 do
begin
Dx := Pos(Delimiter, Txt);
Ns := Trim(Copy(Txt, 1, Dx-1));
// S1.Add('#'+Ns+'*'); //only needed for testing
if Ns <> '' then
begin
Matrix[Row,Col] := StrToFloat(Ns); //for first matrix
Inc(Col);
end;
Txt := Copy(Txt, Dx+Delta, MaxInt);
end;
Looking at this piece of code I see the posibility of an endless loop: what happens if there is no Delimiter found? It will keep running and forever increase your 'col' value. Make sure to have a condition to stop your while loop if no delimeter is found.
It is pointless to look for a specific stack overflow error when many ordinary errors already exist.
If your code is clean programmed and it is still stack overflow, then of course, is time to look deeper into the code.
But first ! As long as you can see obvious errors, you should remove them.
1.) "Row" used in the same procedure on a 140 dimension array and on a only 2 dimension array.
How can that work ?
Matrix: array[1..140,1..141] of double;
Ref: array[1..2,1..140] of double ;
File 'trainer.txt' 140 Lines
File 'refbaru.txt' 2 Lines.
for I := 0 to Temp.Count-1 do // 140 lines
// ParseDelimited() will only run properly if Row < 3
// remember -> Ref: array[1..2,1..140])
// if Row > 2 , with Ref[Row,Col] := , 137 times data is overwritten.
procedure ParseDelimited(MemoSL, Trim(Temp.Strings[I]), ' ');
....
Matrix[Row,Col] := StrToFloat(Ns);
....
Ref[Row,Col] := StrToFloat(ms);
....
end;
Inc(Row);
end;
2.) If you run the second loop with refbaru.txt and the two arrays are present together in the procedure ParseDelimited(), then you overwrite 2 values of array Matrix
recommendation
make sure: Loop through trainer.txt, writes values only to the Matrix array.
make sure: Loop through refbaru.txt, writes values only to the Ref array.
Your code could look something like:
[...]
filetoload: String;
[...]
procedure TfrmJST.ParseDelimited(S1: TStrings; Value: String; const Delimiter: String);
var
f:double;
[...]
Col := 1;
txt := Value+Delimiter;
[...]
if filetoload='trainer.txt' then begin
Delta := Length(Delimiter);
while Length(txt) > 1 do
begin
Dx := Pos(Delimiter, txt);
Ns := Trim(Copy(txt, 1, Dx-1));
if Ns <> '' then
begin
if TryStrToFloat(Ns,f) then Matrix[Row,Col]:=f;
Inc(Col);
if Col > MatrixColMax then break;
txt := Copy(txt, Dx+Delta, MaxInt);
end else txt:='';
end;
end;
if filetoload='refbaru.txt' then begin
teta := Length(delimiter);
while Length(txt) > 1 do
begin
cx := Pos(delimiter, txt);
ms := Copy(txt, 1, cx-1);
if ms <> '' then
begin
if TryStrToFloat(ms,f) then Ref[Row,Col]:=f;
Inc(Col);
if Col > RefColMax then break;
txt := Copy(txt, cx+teta, MaxInt);
end else txt:='';
end;
end;
begin
[...]
filetoload:='trainer.txt';
Temp := TStringList.Create;
Temp.LoadFromFile(filetoload);
if Temp.Count > MatrixRowMax then LinesToLoad:=MatrixRowMax-1 else
LinesToLoad:=Temp.Count-1;
for I := 0 to LinesToLoad do
[...]
ParseDelimited(MemoSL, Trim(Temp.Strings[I]), ' ');
[...]
end;
filetoload:='refbaru.txt';
TempList := TStringList.Create;
TempList.LoadFromFile(filetoload);
if TempList.Count > RefRowMax then LinesToLoad:=RefRowMax-1 else
LinesToLoad:=TempList.Count-1;
for J := 0 to LinesToLoad do
[...]
ParseDelimited(Memo1.Lines, T, ' ');
[...]
end;
end;
You should also compare the linesize of the file with the size of the arrays
RefRowMax: integer;
RefColMax: integer;
MatrixRowMax: integer;
MatrixColMax: integer;
LinesToLoad: integer;
....
RefRowMax:=2;
RefColMax:=140;
MatrixRowMax:=140;
MatrixColMax:=141;
....
procedure ParseDelimited()
if filetoload='trainer.txt' then begin
[...]
Inc(Col)
if Col > MatrixColMax then break;
end;
if filetoload='refbaru.txt' then begin
[...]
Inc(Col)
if Col > RefColMax then break;
end;
You should also look for a valid value of Ns , StrToFloat(Ns) before you write to the arrays in ParseDelimited()
function TryStrToFloat(const S: string; out Value: Double): Boolean;
or
Val();
var
f:double;
....
begin
....
if TryStrToFloat(Ns,f) then Matrix[Row,Col]:=f;
....
The OP overwritting many of used data.
And when he has enough data overwritten, he gets a stack overflow error.

Word blocks in TMemo

I am trying to make a basic Hex viewer out of a TMemo, I know this is probably not ideal but it will be only me personally using it so that does not really matter.
(1)
Firstly, suppose a Memo is filled with Hex information like so:
How could I get a count of all the text blocks shown, ignoring the white space? So using the image the result in this case would be 28.
This is what I tried and I know it is completely wrong as I am accessing the Memo lines but I don't know how to access each character.
I cant seem to solve this simple problem :(
function CountWordBlocks(Memo: TMemo): Integer;
var
i: Integer;
vCount: Integer;
begin
for i := 0 to Memo.Lines.Count - 1 do
begin
if Length(Memo.Lines.Strings[i]) = 2 then
begin
Inc(vCount);
end;
end;
Result := vCount;
end;
Here is the code I am using to display the Hex values in the Memo:
procedure ReadFileAsHex(const AFileName: string; ADestination: TStrings);
var
fs: TFileStream;
buff: Byte;
linecount: Byte;
line: string;
begin
linecount := 0;
line := '';
fs := TFileStream.Create(AFileName, fmOpenRead);
try
ADestination.BeginUpdate;
try
while fs.Position < fs.Size do
begin
fs.Read(buff, 1);
line := line + IntToHex(buff, 2) + ' ';
Inc(linecount);
if linecount = 16 then
begin
ADestination.Add(line);
line := '';
linecount := 0;
end;
end;
if Length(line) <> 0 then
ADestination.Add(line);
finally
ADestination.EndUpdate;
end;
finally
fs.Free;
end;
end;
(2)
If I click onto the Memo and a text block is under the cursor, how could I know which number the selected block is out of all the others?
So using the same first image, the caret is at the top line next to 68, so the result would be 3 as it is the third text block out of 28.
This should be so easy but I cannot think clearly, I don't have the right programming mind yet and so really struggle with basic logic and solving problems!
(3)
Finally I would like to select a block at runtime by passing a block number value. I tried this without much success:
procedure FindBlock(Memo: TMemo; BlockNumber: Integer);
var
i: Integer;
txt: string;
ThisWhite, PrevWhite: boolean;
vRead: Integer;
begin
txt := Memo.Text;
vRead:= 0;
PrevWhite := True;
for i := 1 to Length(txt) do
begin
ThisWhite := Character.IsWhiteSpace(txt[i]);
if PrevWhite and not ThisWhite then
begin
Inc(vRead);
PrevWhite := False;
end;
PrevWhite := ThisWhite;
if vRead = BlockNumber then
begin
Memo.SelStart := vRead;
Memo.SetFocus;
Exit;
end;
end;
end;
(1)
This works:
function TForm1.CountBlocks: integer;
var
i: Integer;
txt: string;
ThisWhite, PrevWhite: boolean;
begin
txt := Memo1.Text;
result:= 0;
PrevWhite := true;
for i := 1 to Length(txt) do
begin
ThisWhite := Character.IsWhiteSpace(txt[i]);
if PrevWhite and not ThisWhite then
begin
inc(result);
PrevWhite := false;
end;
PrevWhite := ThisWhite;
end;
end;
However, it can be optimized if more detailed information about the memo contents is available. For instance, if you know that each line consists of four blocks, then the number of blocks is simply 4*Memo1.Lines.Count. My code above will even accept blocks of different width.
(2)
Simply replace
for i := 1 to Length(txt) do
by
for i := 1 to Memo1.SelStart + 1 do
Since you are in control of the formatting of your lines, and the lines have a fixed format, it is very easy to calculate the number of bytes being displayed without resorting to looping through the individual lines one a time. Every line displays 3 characters per byte, and every line other than the last line displays 16 bytes, thus 48 characters per complete 16-byte line. Use those facts to your advantage to calculate the number of bytes based on the number of complete 16-byte lines present, and then you can add on the number of remaining bytes from just the last line:
function CountWordBlocks(Memo: TMemo): Integer;
var
Count: Integer;
begin
Count := Memo.Lines.Count;
if Count > 0 then
Result := (16 * (Count-1)) + (Length(Memo.Lines[Count-1]) div 3);
else
Result := 0;
end;
You can do something similar to translate a character offset within the Memo into a work block number:
function GetCurrentWordBlock(Memo: TMemo): Integer;
var
SelStart, LineStart, LineNum: Integer
begin
Result := 0;
SelStart := Memo.SelStart;
if SelStart < 0 then Exit;
LineStart := Memo.Perform(EM_LINEINDEX, SelStart, 0);
if LineStart < 0 then Exit;
LineNum := Memo.Perform(EM_LINEFROMCHAR, LineStart, 0);
Result := (16 * LineNum) + ((SelStart - LineStart) div 3) + 1;
end;
To select a given block number, you can do this:
procedure FindBlock(Memo: TMemo; BlockNumber: Integer);
var
LineNum, LineStart: Integer;
begin
if BlockNumber < 1 then Exit;
LineNum = (BlockNumber - 1) div 16;
LineStart = Memo.Perform(EM_LINEINDEX, LineNum, 0);
if LineStart < 0 then Exit;
Memo.SelStart = LineStart + (((BlockNumber - 1) - (16 * LineNum)) * 3);
Memo.SelLength := 2;
Memo.SetFocus;
end;

GetFormFieldNames not always working

I am trying to find out which form and element belongs too. The code that I now understand from this website:
http://www.cryer.co.uk/brian/delphi/twebbrowser/read_write_form_elements.htm
containing this code
function GetFormFieldNames(fromForm: IHTMLFormElement): TStringList;
var
index: integer;
field: IHTMLElement;
input: IHTMLInputElement;
select: IHTMLSelectElement;
text: IHTMLTextAreaElement;
begin
result := TStringList.Create;
for index := 0 to fromForm.length do
begin
field := fromForm.Item(index,'') as IHTMLElement;
if Assigned(field) then
begin
if field.tagName = 'INPUT' then
begin
// Input field.
input := field as IHTMLInputElement;
result.Add(input.name);
end
else if field.tagName = 'SELECT' then
begin
// Select field.
select := field as IHTMLSelectElement;
result.Add(select.name);
end
else if field.tagName = 'TEXTAREA' then
begin
// TextArea field.
text := field as IHTMLTextAreaElement;
result.Add(text.name);
end;
end;
end;
end;
seems to be working fine for most sites. However there are a few websites such as this one:
http://service.mail.com/registration.html#.1258-bluestripe-product1-undef
By looking at that code and comparing it with the active id, I can find the form it is in. However it does not work for that website. for some reason I think it has to do with htmldocument3 adn that this code is for htmldocument2. But I am not sure.
so my question is How can I extract a tstringlist from this website with all the elements names in them? hope you can help!
Edited: Added some code
begin
theForm := GetFormByNumber(webbrowser1.document as IHTMLDocument2,
0);
fields := GetFormFieldNames(theForm);
num := fields.IndexOf(theid);
end;
until (num <> -1);
One complication with locating form elements in a web page is that the page may contain frames and there may be forms in any of the frames. Basically, you have to iterate through all the frames and the forms in each frame. Once you get the form as an IHTMLFormElement, use Cryer's function to get the form element names.
The example link you gave does not have any frames and you should have had no problems getting your list of form elements, unless you tried to get the form by name because it had no name assigned. I had no problem getting the form element names and values using the following procedure
procedure GetForms(doc1: IHTMLDocument2; var sl: TStringList);
var
i, j, n: integer;
docForm: IHTMLFormElement;
slt: TStringList;
s: string;
begin
if doc1 = nil then
begin
ShowMessage('doc1 is empty [GetForms]');
Exit;
end;
slt := TStringList.Create;
n := NumberOfForms(doc1);
sl.Add('Forms: ' + IntToStr(n));
for i := 0 to n - 1 do
begin
docForm := GetFormByNumber(doc1, i);
sl.Add('Form Name: ' + docForm.Name);
slt.Clear;
slt := GetFormFieldNames(docForm);
for j := 0 to slt.Count - 1 do
begin
s := GetFieldValue(docForm, slt[j]);
sl.Add('Field Name: ' + slt[j] + ' value: "' + s + '"');
end;
end;
sl.Add('');
slt.Free;
end;
Cryer's example for navigating a frameset will not work for all web sites, see http://support.microsoft.com/support/kb/articles/Q196/3/40.ASP. The following function successfuly extracts a frame as an IHTMLDocument2 on all sites I have tried
function GetFrameByNumber(Doc:IHTMLDocument2; n:integer):IHTMLDocument2;
var
Container: IOleContainer;
Enumerator: ActiveX.IEnumUnknown;
Unknown: IUnknown;
Browser: IWebBrowser2;
Fetched: Longint;
NewDoc: IHTMLDocument2;
i : integer;
begin
// We cannot use the document's frames collection here, because
// it does not work in every case (i.e. Documents from a foreign domain).
// From: http://support.microsoft.com/support/kb/articles/Q196/3/40.ASP
i := 0;
if (Supports(Doc, IOleContainer, Container)) and
(Container.EnumObjects(OLECONTF_EMBEDDINGS, Enumerator) = S_OK) then
begin
while Enumerator.Next(1, Unknown, #Fetched) = S_OK do
begin
if (Supports(Unknown, IWebBrowser2, Browser)) and
(Supports(Browser.Document, IHTMLDocument2, NewDoc)) then
begin
// Here, NewDoc is an IHTMLDocument2 that you can query for
// all the links, text edits, etc.
if i=n then
begin
Result := NewDoc;
Exit;
end;
i := i+1;
end;
end;
end;
end;
Here is an example of how I have used GetForms and GetFrameByNumber
// from the TForm1 declaration
{ Public declarations }
wdoc: IHTMLDocument2;
procedure TForm1.btnAnalyzeClick(Sender: TObject);
begin
wdoc := WebBrowser.Document as IHTMLDocument2;
GetDoc(wdoc);
end;
procedure TForm1.GetDoc(doc1: IHTMLDocument2);
var
i, n: integer;
doc2: IHTMLDocument2;
frame_dispatch: IDispatch;
frame_win: IHTMLWindow2;
ole_index: olevariant;
sl: TStringList;
begin
if doc1 = nil then
begin
ShowMessage('Web doc is empty');
Exit;
end;
Form2.Memo1.Lines.Clear;
sl := TStringList.Create;
n := doc1.frames.length;
sl.Add('Frames: ' + IntToStr(n));
// check each frame for the data
if n = 0 then
GetForms(doc1, sl)
else
for i := 0 to n - 1 do
begin
sl.Add('--Frame: ' + IntToStr(i));
ole_index := i;
frame_dispatch := doc1.Frames.Item(ole_index);
if frame_dispatch <> nil then
begin
frame_win := frame_dispatch as IHTMLWindow2;
doc2 := frame_win.document;
// sl.Add(doc2.body.outerHTML);
GetForms(doc2,sl);
GetDoc(doc2);
end;
end;
// Form2 just contains a TMemo
Form2.Memo1.Lines.AddStrings(sl);
Form2.Show;
sl.Free;
end;
The logic in your example is faulty, 1. when there is only 1 form on the web page the list of form elements is never extracted, 2. the repeat loop will result in a access violation unless the the tag in "theid" is found
Here is your example cut down to successfully extract the form elements.
var
i : integer;
nforms : integer;
document : IHTMLDocument2;
theForm : IHTMLFormElement;
fields : TStringList;
theform1 : integer;
num : integer;
theid : string;
begin
fields := TStringList.Create;
theid := 'xx';
// original code follows
i := -1;
// nforms := NumberOfForms(webbrowser1.document as IHTMLDocument2);
// document := webbrowser1.document as IHTMLDocument2;
// if nforms = 1 then
// begin
// theForm := GetFormByNumber(webbrowser1.document as IHTMLDocument2, 0);
// theform1 := 0;
// end
// else
begin
// repeat
begin
inc(i);
theForm := GetFormByNumber(webbrowser1.document as IHTMLDocument2,
i);
fields := GetFormFieldNames(theForm);
num := fields.IndexOf(theid);
theform1 := i;
end;
// until (num <> -1);
end;
// end of original code
Memo1.Lines.Text := fields.Text;
fields.Free;
end;
Hm, are you sure this link contains any form elements? At least I did not see any visible ones. Perhaps they are hidden - did not check this myself, however.
Michael

How to expose a Delphi set type via Soap

I'm currently creating soap wrappers for some Delphi functions so that we can easily use them from PHP, C# and Delphi.
I wonder what's the best way to expose sets.
type
TCountry = (countryUnknown,countryNL,countryD,countryB,countryS,countryFIN,countryF,countryE,countryP,countryPl,countryL);
TCountrySet = set of TCountry;
function GetValidCountrySet(const LicensePlate:string; const PossibleCountriesSet:TCountrySet):TCountrySet;
I'm currently wrapping it like this for the soap server:
type
TCountryArray = array of TCountry;
function TVehicleInfo.GetValidCountrySet(const LicensePlate:string; const PossibleCountriesSet:TCountryArray):TCountryArray;
It works, but I need to write a lot of useless and ugly code to convert sets-->arrays and arrays-->sets.
Is there an easier, more elegant, or more generic way to do this?
You could use TypInfo and use a bit of clever casting.
uses TypInfo;
type
TCountry = (cnyNone, cnyNL, cnyD, cnyGB, cnyF, cnyI);
TCountrySet = set of TCountry;
TCountryArray = array of TCountry;
TEnumIntegerArray = array of Integer;
TEnumByteArray = array of Byte;
function GetEnumNamesInSet(const aTypeInfo: PTypeInfo; const aValue: Integer; const aSeparator: string = ','): string;
var
IntSet: TIntegerSet;
i: Integer;
begin
Result := '';
Integer( IntSet ) := aValue;
for i := 0 to SizeOf(Integer) * 8 - 1 do begin
if i in IntSet then begin
if Result <> '' then begin
Result := Result + ',';
end;
Result := Result + GetEnumName(aTypeInfo, i);
end;
end;
end;
function SetToIntegerArray(const aTypeInfo: PTypeInfo; const aValue: Integer): TEnumIntegerArray;
var
IntSet: TIntegerSet;
i: Integer;
begin
SetLength(Result, 0);
Integer( IntSet ) := aValue;
for i := 0 to SizeOf(Integer) * 8 - 1 do begin
if i in IntSet then begin
SetLength(Result, Length(Result) + 1);
Result[Length(Result) - 1] := i;
end;
end;
end;
function SetToByteArray(const aTypeInfo: PTypeInfo; const aValue: Byte): TEnumByteArray;
var
IntSet: TIntegerSet;
i: Integer;
begin
SetLength(Result, 0);
Integer( IntSet ) := aValue;
for i := 0 to SizeOf(Byte) * 8 - 1 do begin
if i in IntSet then begin
SetLength(Result, Length(Result) + 1);
Result[Length(Result) - 1] := i;
end;
end;
end;
Then use as:
procedure TEnumForm.FillMemo;
var
Countries: TCountrySet;
// EIA: TEnumIntegerArray;
EBA: TEnumByteArray;
CA: TCountryArray;
i: Integer;
cny: TCountry;
begin
Countries := [cnyNL, cnyD];
CountriesMemo.Text := GetEnumNamesInSet(TypeInfo(TCountry), Byte(Countries));
// if SizeOf(TCountry) > SizeOf(Byte) then begin
// EIA := SetToIntegerArray(TypeInfo(TCountry), Integer(Countries));
// end else begin
EBA := SetToByteArray(TypeInfo(TCountry), Byte(Countries));
// end;
CountriesMemo.Lines.Add('====');
CountriesMemo.Lines.Add('Values in Array: ');
// if SizeOf(TCountry) > SizeOf(Byte) then begin
// CA := TCountryArray(EIA);
// end else begin
CA := TCountryArray(EBA);
// end;
for i := 0 to Length(CA) - 1 do begin
CountriesMemo.Lines.Add(IntToStr(Ord(CA[i])));
end;
CountriesMemo.Lines.Add('====');
CountriesMemo.Lines.Add('Names in Array: ');
// if SizeOf(TCountry) > SizeOf(Byte) then begin
// CA := TCountryArray(EIA);
// end else begin
CA := TCountryArray(EBA);
// end;
for i := 0 to Length(CA) - 1 do begin
cny := CA[i];
CountriesMemo.Lines.Add(GetEnumName(TypeInfo(TCountry), Ord(cny)));
end;
end;
You will need to select the proper casting based on the size of the TCountry enum. If it has 8 members it will be a Byte, any bigger and it will be an Integer. Anyway, Delphi will complain on the cast of Byte(Countries) or Integer(Countries) when you get it wrong.
Please note:
The functions now take the TypeInfo of TCountry - the elements of the TCountrySet. They could be changed to take TypeInfo(TCountrySet). However that would mean having the functions work out what elements are in the set and I simply haven't had the time or inclination to do that yet.
Soap should be used in a platform and language agnostic way - I would design all data transfer objects (DTO) based on simple types e.g. array of string, without language specific features. Then map the DTO to the matching business objects. This also will give you an 'anticorruption layer'.

Resources