How to correctly qualify Result variable inside lambda - delphi

function TFlatBlock.SelectRow(const C:TConditionR):TArray<TFlatRow>;
begin
Result := nil;
if not Assigned(C) then Exit;
//
SearchRow(function(const R:TFlatRow):Boolean
begin
// Result from TFlatBlock.SelectRow !!!
if C(R) then Result := Result + [R];
// Result from lambda
Result := false;
end);
end;
How to qualify var Result in this case? Yes I can use local variable instead, but maybe there is a way to do this without it.

Related

How to cache function Boolean result

I have this function:
var
_WordApplicationExistsCache: Integer = -1; // Cache result
function WordApplicationExists: Boolean;
var
WordObj: OleVariant;
begin
if (_WordApplicationExistsCache = -1) then
begin
Result := False;
try
try
WordObj := CreateOleObject('Word.Application');
WordObj.Visible := False;
WordObj.Quit;
WordObj := Unassigned;
Result := True;
except
// error
end;
finally
_WordApplicationExistsCache := Ord(Result); // 0;1
end;
end
else
begin
Result := Boolean(_WordApplicationExistsCache);
end;
end;
I'm trying to call this function only once in the Application lifetime. I might not call this function at all.
Is this the correct pattern? Can this be done better?
EDIT:
Another way I can think of, in this case is to use 2 variables:
var
_WordApplicationExistsInitialized: Boolean = False; // Cache result
_WordApplicationExistsCacheResult: Boolean; // Undefined ?
function WordApplicationExists: Boolean;
var
WordObj: OleVariant;
begin
if not _WordApplicationExistsInitialized then
begin
_WordApplicationExistsInitialized := True;
Result := False;
try
try
WordObj := CreateOleObject('Word.Application');
WordObj.Visible := False;
WordObj.Quit;
WordObj := Unassigned;
Result := True;
except
// error
end;
finally
_WordApplicationExistsCacheResult := Result;
end;
end
else
begin
Result := _WordApplicationExistsCacheResult;
end;
end;
What bugs me a bit about the first version is the type casting Boolean<->Integer. If Boolean could be initialized to nil it would have been perfect (I think).
Use a TriState type for the cached result.
type
TTriState = ( tsUnknown, tsFalse, tsTrue );
var
_WordApplicationExists : TTriState = tsUnknown;
function WordApplicationExists : Boolean;
var
WordObj: OleVariant;
begin
if _WordApplicationExists = tsUnknown
then
try
WordObj := CreateOleObject('Word.Application');
WordObj.Visible := False;
WordObj.Quit;
WordObj := Unassigned;
_WordApplicationExists := tsTrue;
except
_WordApplicationExists := tsFalse;
end;
Result := _WordApplicationExists = tsTrue;
end;
This code will work fine, and is correctly implemented. A nullable boolean or a tristate enum will read better, but fundamentally the logic would be the same.
It's heavy handed and clunky approach though, invoking an instance of Word that is then thrown away. Personally I would read the registry to check whether or not the COM object is registered. I would not attempt to anticipate the case where the object is registered but cannot be created. In my view that is an exceptional case that should be handled when it occurs, but not before.
Another way to go is simply not to attempt to check ahead of time for the Word COM object being available. Just go ahead and attempt to create the object when you need to use it. If this fails, deal with that. If you wish to remember that it failed, do so. But you really should avoid creating the object twice when once will suffice.
This could be done also with a Variant type. Variants are set to Unassigned. (reference)
var
_WordApplicationCanCreate: Variant; // Unassigned (VType = varEmpty)
function WordApplicationCanCreate: Boolean;
var
WordObj: OleVariant;
begin
if VarIsEmpty(_WordApplicationCanCreate) then
try
WordObj := CreateOleObject('Word.Application');
WordObj.Visible := False;
WordObj.Quit;
WordObj := Unassigned;
_WordApplicationCanCreate := True;
except
_WordApplicationCanCreate := False;
end;
Result := _WordApplicationCanCreate = True;
end;

How to properly start, working and finish a transaction?

I'm using MySQL, and I know that Nested Connection are not allowed - use "save points" for this - but I would like create a more generic code that could also be used with other DBMS.
So, I would like know how to properly start, working and finish a transaction in the code below?
Once ExampleDAO.Save() function could be used inside other function, like OtherExampleDAO.Save(), I need verify a transaction has been started before I try start a new one.
The lines with the verification if Assigned(dbTransaction) then always returns true, so how to properly verify if dbTransaction was instantiated?
function TExampleDAO.Save(const Example: TExample): Boolean;
var
dbxTransaction: TDBXTransaction;
begin
if Assigned(Example) then // prevents invalid object, like ExampleDAO.Save(nil);
begin
try
if (_connection.TransactionsSupported) AND
((not _connection.InTransaction) OR (_connection.MultipleTransactionsSupported)) then
begin
dbxTransaction := _connection.BeginTransaction(TDBXIsolations.ReadCommitted);
end;
try
// example
_sqlQuery.Close;
_sqlQuery.SQL.Clear;
_sqlQuery.SQL.Add('INSERT INTO example(a, b) '
+ 'VALUES(:a, :b)');
_sqlQuery.ParamByName('a').AsAnsiString := Example.A;
_sqlQuery.ParamByName('b').AsDateTime := Example.B;
_sqlQuery.ExecSQL(False);
// example info
_sqlQuery.Close;
_sqlQuery.SQL.Clear;
_sqlQuery.SQL.Add('INSERT INTO example_info(c, d) '
+ 'VALUES(:c, :d)');
_sqlQuery.ParamByName('c').AsInteger := Example.Info.C;
_sqlQuery.ParamByName('d').AsFloat := Example.Info.D;
_sqlQuery.ExecSQL(False);
if Assigned(dbxTransaction) then
_connection.CommitFreeAndNil(dbxTransaction);
Result := True;
except
on Exc:Exception do
begin
if Assigned(dbxTransaction) then
_connection.RollBackFreeAndNil(dbxTransaction);
raise Exc;
Result := False;
end;
end;
finally
if Assigned(dbxTransaction) then
FreeAndNil(dbxTransaction);
end;
end
else
begin
Result := False;
end;
end;
You need to properly initialize dbxTransaction to nil at the start of your function. Local variables in Delphi (on the Win32 platform, at least) are not initialized until a value is assigned to them, meaning that the content is unknown. Passing any value other than nil to Assigned will result in True. I recommend never testing a local variable's content on any platform until it has had a value assigned in your code.
Here's an example of how to make it work. (I've also removed the unnecessary assignment to Result in the exception block.)
function TExampleDAO.Salve(const Example: TExample): Boolean;
var
dbxTransaction: TDBXTransaction;
begin
dbxTransaction := nil; // Initialize the transaction variable here
if Assigned(Example) then // prevents invalid object, like ExampleDAO.Save(nil);
begin
try
if (_connection.TransactionsSupported) AND
((not _connection.InTransaction) OR (_connection.MultipleTransactionsSupported)) then
begin
dbxTransaction := _connection.BeginTransaction(TDBXIsolations.ReadCommitted);
end;
try
// example
_sqlQuery.Close;
_sqlQuery.SQL.Clear;
_sqlQuery.SQL.Add('INSERT INTO example(a, b) '
+ 'VALUES(:a, :b)');
_sqlQuery.ParamByName('a').AsAnsiString := Example.A;
_sqlQuery.ParamByName('b').AsDateTime := Example.B;
_sqlQuery.ExecSQL(False);
// example info
_sqlQuery.Close;
_sqlQuery.SQL.Clear;
_sqlQuery.SQL.Add('INSERT INTO example_info(c, d) '
+ 'VALUES(:c, :d)');
_sqlQuery.ParamByName('c').AsInteger := Example.Info.C;
_sqlQuery.ParamByName('d').AsFloat := Example.Info.D;
_sqlQuery.ExecSQL(False);
if Assigned(dbxTransaction) then
_connection.CommitFreeAndNil(dbxTransaction);
Result := True;
except
on Exc:Exception do
begin
if Assigned(dbxTransaction) then
_connection.RollBackFreeAndNil(dbxTransaction);
raise Exc;
end;
end;
finally
if Assigned(dbxTransaction) then
FreeAndNil(dbxTransaction);
end;
end
else
begin
Result := False;
end;
end;
As was noted by #SirRufo in the comments to your question, failing to pass Example as a parameter should probably raise an exception as well, which would mean that it could become a procedure instead of a function and Result would no longer apply at all.

jSon_encode like function for Delphi which accepts TDataSet

I have been tasked with creating a Indy server in Delphi 2007 which communicates with clients and returns json formatted data from Sql based databases. Someone from our office created a prototype using php. And in the prototype they use the jSon_encode function extensively to return the data from tables. I was wondering if there was a similar Delphi function which could accept a TDataSet parameter and return properly formatted json data.
Anyone know of such function?
Update 12/10/2013 - my modification to #user2748835 answer:
function jsonencode(mString: String): String;
begin
result := StringReplace(mString,'''','\''',[rfReplaceAll,rfIgnoreCase]);
result := StringReplace(mString,'\','\\',[rfReplaceAll,rfIgnoreCase]);
result := StringReplace(result,crlf,'\n',[rfReplaceAll,rfIgnoreCase]);
result := StringReplace(result,'"','\"',[rfReplaceAll,rfIgnoreCase]);
result := StringReplace(result,'/','\/',[rfReplaceAll,rfIgnoreCase]);
result := StringReplace(result,'#9','\t',[rfReplaceAll,rfIgnoreCase]);
end;
function jSon_encode(aDataset:TDataset):string;
function fieldToJSON(thisField:TField):string;
begin
try
result := '"'+thisField.fieldName+'":';
case thisField.DataType of
ftInteger,ftSmallint,ftLargeint:
result := result+inttostr(thisField.AsInteger);
ftDateTime:
result := result+'"'+formatdatetime('YYYY-MM-DD HH:NN:SS',thisField.AsDateTime)+'"';
ftCurrency,
ftFloat:
result := result + floattostr(thisField.AsFloat);
ftString :
result := result + '"'+jsonencode(thisField.AsString)+'"';
else
end; // case
result := result + ',';
except
on e: Exception do begin
appendtolog('problem escaping field '+thisfield.fieldname);
end;
end;
end; // of fieldToJSON
function rowToJSON(ds:TDataset):string;
var
fieldIx : integer;
begin
result := '';
for fieldIx := 0 to ds.fieldcount-1 do
result := result + fieldToJSON(ds.Fields[fieldIx]);
// trim comma after last col
result := '{'+copy(result,1,length(result)-1)+'},';
end; // of rowToJSON
begin
result := '';
with aDataset do
begin
if not bof then first;
while not eof do
begin
result := result + rowToJSON(aDataset);
next;
end;
end;
//strip last comma and add
if length(result)>0 then
result := copy(result,1,length(result)-1);
result := '['+result+']';
end; // of DSToJSON
In a TDataset, you can loop through the Fields collection and construct the json output and then in the loop, check the fieldtype and encode the value accordingly.
Something like:
uses db;
function DSToJSON(aDataset:TDataset):string;
function fieldToJSON(thisField:TField):string;
begin
result := '"'+thisField.fieldName+'":';
case thisField.DataType of
ftInteger,
ftSmallint,
ftCurrency,
ftFloat,
ftLargeInt:
result := result+thisField.value+^n^j;
ftString :
result := noSingleQuotes(thisField.value)+^n^j;
else
end; // case
end; // of fieldToJSON
function rowToJSON(ds:TDataset):string;
var
fieldIx : integer;
begin
for fieldIx := 0 to ds.fieldcount-1 do
result := result + fieldToJSON(ds.Fields[fieldIx]);
// trim comma after last col
result := '{'+copy(result,1,length(result)-1)+'},';
end; // of rowToJSON
begin
result := '';
with aDataset do
begin
if not bof then first;
while not eof do
begin
result := result + rowToJSON(aDataset);
next;
end;
end;
//strip last comma and add
if length(result)>0 then
result := copy(result,1,length(result)-1);
result := '['+result+']';
end; // of DSToJSON
We just added a more complete and faster function, in our Open Source repository.
It is part of our mORMot framework, but can be used as a stand-alone unit, not tied to other features.
See in SynVirtualDataSet.pas:
function DataSetToJSON(Data: TDataSet): RawUTF8
See this commit and the associated forum thread.
You can change every row into object and use serializing http://docwiki.embarcadero.com/RADStudio/XE5/en/Serializing_User_Objects

out parameter and "ShowMessage" function

I have a function declare like this :
function execProc(ProcName,InValues:PChar;out OutValues:PChar):integer; //The "OutValues" is a out parameter.
And I call this function like this:
procedure TForm1.Button6Click(Sender: TObject);
var
v:integer;
s:pchar;
begin
Memo1.Clear;
v := execProc(pchar('PROC_TEST'),pchar('aaa'),s);
showmessage(inttostr(v)); //mark line
Memo1.Lines.Add(strpas(s));
end;
when i delete the mark line(showmessage(inttostr(v))),i will have a correct result display in the Memo1,but if i keep use the showmessage(), the memo1 will dispaly an error string : "Messag" ,Why?
Thanks for any help!
function execProc(ProcName,InValues:PChar;out OutValues:PChar):integer;
var
str: TStrings;
InValue,OutValue: string;
i,j,scount: integer;
begin
Result := -100;
i := 0;
j := 0;
str := TStringList.Create;
try
sCount := ExtractStrings(['|'], [], InValues, str);
with kbmMWClientStoredProc1 do
begin
Close;
Params.Clear;
StoredProcName := StrPas(ProcName);
FieldDefs.Updated := False;
FieldDefs.Update;
for i := 0 to Params.Count - 1 do
begin
if (Params[i].ParamType = ptUnknown) or
(Params[i].ParamType = ptInput) or
(Params[i].ParamType = ptInputOutput) then
begin
inc(j);
InValue := str[j-1];
Params[i].Value := InValue;
end;
end;
try
ExecProc;
for i := 0 to Params.Count - 1 do
begin
if (Params[i].ParamType = ptOutput) or
(Params[i].ParamType = ptInputOutput) then
OutValue := OutValue + '|' + Params[i].AsString;
end;
OutValues := PChar(Copy(OutValue,2,Length(OutValue)-1));
Result := 0;
except
on E:Exception do
begin
if E.Message = 'Connection lost.' then Result := -101;//服务器连接失败
if E.Message = 'Authorization failed.' then Result := -102;//身份验证失败
Writelog(E.Message);
end;
end;
end;
finally
str.Free;
end;
end;
The problem is in the design of your interface and the use of PChar.
OutValues := PChar(Copy(OutValue,2,Length(OutValue)-1));
This is implemented by making an implicit, hidden, local string variable which holds the value
Copy(OutValue,2,Length(OutValue)-1)
When the function returns, that string variable is destroyed and so OutValues points at deallocated memory. Sometimes your program appears to work but that's really just down to chance. Any small change can disturb that, as you have observed.
The problem is easy enough to fix. Simply use string parameters rather than PChar. This will make the code easier to read as well as making it work correctly.
function execProc(ProcName, InValues: string; out OutValues: string): integer;

Convert a DevExpress TcxFilterOperatorKind to and from a string?

Here is a codesnippet I use to get filtertype operator from a filter in a DevExpress grid:
OperatorKindToStr is used to extract operatorkind from a filter as string and store it in a xml-file.
StrToOperatorKind is used to convert back a string from xml to set an operatorkind in a filter.
const
CUSTFILTER_FILTERITEM = 'FilterItem';
function OperatorKindToStr(const aOperatorKind: TcxFilterOperatorKind): string;
begin
Result := 'foEqual';
case aOperatorKind of
foEqual: Result := 'foEqual';
foNotEqual: Result := 'foNotEqual';
foLess: Result := 'foLess';
foLessEqual: Result := 'foLessEqual';
// Plus a boring list of other constants
end;
function StrToOperatorKind(const aOpKindStr: string): TcxFilterOperatorKind;
begin
Result := foEqual;
if aOpKindStr = 'foNotEqual' then
Result := foNotEqual
else if aOpKindStr = 'foLess' then
Result := foLess
else if aOpKindStr = 'foLessEqual' then
Result := foLessEqual
else if aOpKindStr = 'foGreater' then
Result := foGreater
else if aOpKindStr = 'foGreaterEqual' then
Result := foGreaterEqual
// Plus a boring list of other if-else
end;
procedure UseStrToOperatorKind(const aFilterItem: IXmlDomElement);
begin
if aFilterItem.nodeName = CUSTFILTER_FILTERITEM then
begin // It is an FilterItem
vStr := VarToStr(aFilterItem.getAttribute(CUSTFILTER_COLPROP)); // Get the columnname
vOperatorKind := StrToOperatorKind(aFilterItem.getAttribute(CUSTFILTER_ITEMOPERATOR));
end;
procedure UseOperatorKindToStr(const aFilterItem: TcxCustomFilterCriteriaItem);
var
vStr: String;
begin
if Supports(TcxFilterCriteriaItem(aFilterItem).ItemLink, TcxGridColumn, GridCol) then
vStr := OperatorKindToStr(TcxFilterCriteriaItem(aFilterItem).OperatorKind);
end;
Apparently I want the StrToOperatorKind and OperatorKindToStr to be a bit smarter.
I have tried GetEnumProp method in VCL TypeInfo but it won't work.
So how can I extract the TcxFilterOperatorKind property from a aFilterItem variable to a string and back to a TcxFilterOperatorKind ?
Use the GetEnumName and GetEnumValue duet as Mason pointed out.
And your functions should become much simpler:
function OperatorKindToStr(const aOperatorKind: TcxFilterOperatorKind): string;
begin
Result := GetEnumName(TypeInfo(TcxFilterOperatorKind), Ord(aOperatorKind));
end;
function StrToOperatorKind(const aOpKindStr: string): TcxFilterOperatorKind;
begin
Result := TcxFilterOperatorKind(GetEnumValue(TypeInfo(TcxFilterOperatorKind), aOpKindStr));
end;
GetEnumProp didn't work because it's the wrong function for what you're trying to do. You're close, though. Try GetEnumName and GetEnumValue, which are also in the TypInfo unit.

Resources