How to convert string to TPenStyle? - delphi

I saw some very similar threads here, but I couldn't find solution to my problem.
I take the value from TStringList and use it as pen style (psDot, psSolid and so on), but the compilation fails with Incompatible types: 'TPenStyle' and 'String' error message.
Here is the code:
Image1.Canvas.Pen.Style := myList.ValueFromIndex[j];
How can I convert myList.ValueFromIndex[j] to TPenStyle ?

if stored as psDot, psSolid else you have to adapt
uses TypInfo;
Image1.Canvas.Pen.Style := TPenStyle(GetEnumValue(TypeInfo(TPenStyle),myList.ValueFromIndex[j]));
as suggested by David Heffernan
Function PenStyleFromName(const Name: string):TPenStyle;
begin
Result := TPenStyle(GetEnumValue(TypeInfo(TPenStyle),Name));
end;
//....
Image1.Canvas.Pen.Style := PenStyleFromName(myList.ValueFromIndex[j]);

Related

How to get unit path in runtime with Delphi?

I assume that it is possible to get the complete path of the unit (not just the name) at runtime, since when I generate an error, Delphi already has this stored information:
try
Assert (False, '#');
except
on E: EAssertionFailed from
begin
   ShowMessage (E.Message); // this show me the path
end;
end;
Would anyone know if there is any function that returns me the path of a specific unit, or something similar?
The complete path of the unit as it was on the machine that compiled the project is only possible using Assert. However personally I don't find that information incredibly useful unless you have many units with the same name in different folders or lost control over your source repository and and library paths in effect when compiling.
To get the unit name you can turn on map file or debug information (aka TD32) and do the following:
Use the FileByLevel function from JclDebug - in your case with the default value (0).
The level parameter tells the function how many calls it look up the callstack. If you put that method into a FormCreate of a VCL form for example and pass 1 it will give you Vcl.Forms.pas as the event handler was called from there.
I hesitate to write this answer as it shows a really dirty hack to get the unit name making use of the Assert compiler magic shown above.
Use the following unit:
unit UnitNameHack;
interface
const
cUnitNameSentinel = '$$$sentinel$$$';
var
HackUnitname: string = '';
implementation
var
OrgAssertErrorProc: TAssertErrorProc = nil;
procedure MyAssertErrorProc(const Message, Filename: string; LineNumber: Integer; ErrorAddr: Pointer);
begin
if Message = cUnitNameSentinel then begin
HackUnitname:= Filename;
end
else begin
OrgAssertErrorProc(Message, Filename, LineNumber, ErrorAddr);
end;
end;
initialization
OrgAssertErrorProc := AssertErrorProc;
AssertErrorProc := MyAssertErrorProc;
finalization
AssertErrorProc := OrgAssertErrorProc;
end.
Now whenever you need the unit name call
Assert(False, cUnitNameSentinel);
and retrieve the unit name from HackUnitname.
Note that you cannot wrap the Assert call and reading HackUnitName into a function, not even if inlined.
You've said, something similar. I see that it might have been in a different context, but anyway, for objects you can inspect UnitName or UnitScope to get the name of the module where the object instance was declared, without the module path (which is not valuable information anyway).
Based on Uwe Raabe's answer:
// directly after the implementation uses:
var
ThisUnit: string = '<unknown>';
procedure MyAssertErrorProc(const Message, Filename: string; LineNumber: Integer; ErrorAddr: Pointer);
begin
ThisUnit := Filename;
end;
procedure InitThisUnit;
var
OrgAssertErrorProc: TAssertErrorProc;
begin
OrgAssertErrorProc := AssertErrorProc;
try
AssertErrorProc := MyAssertErrorProc;
Assert(False);
finally
AssertErrorProc := OrgAssertErrorProc;
end;
end;
// [...]
// call InitThisUnit in the initialization section
initialization
InitThisUnit;
end.
It's still a hack, but a bit more elegant. ;-)

How to change THash.Hash at runtime

How can I change the default THash.Hash algorythm from trhe default SHA-1 to MD5?
The following does not works:
var
StringHash: THash;
begin
StringHash.Create(nil);
StringHash.Hash := 'MD5';
end;
Edit:
Yes you are all right: I apologize for not having mentioned the fact that THash is a class of the new TurboPower LockBox 3.
My apologies again for this omission!
Anyway Sean has already given the answer I was looking for.
Thank you all
Assuming that you are referring to the THash component of TurboPower Lockbox, you can select the hashing algorithm at run-time like so:
function FindHashOfBananaBananaBanana: TBytes;
var
StringHash: THash;
Lib: TCrypographicLibrary;
begin
StringHash := THash.Create( nil);
Lib := TCrypographicLibrary( nil);
try
StringHash.CryptoLibrary := Lib;
StringHash.HashId := SHA512_ProgId; // Find constants for other algorithms
// in unit uTPLb_Constants.
StringHash.HashAnsiString('Banana banana banana');
SetLength( result, StringHash.HashOutputValue.Size);
StringHash.HashOutputValue.Read( result[0], StringHash.HashOutputValue.Size);
StringHash.Burn
finally
StringHash.Free;
Lib.Free
end
end;
Your example code is invalid. The variable type is THASH, the variable name is STRINGHASH. When you construct an instance of a class the format is typically:
var
StringHash:THash;
begin
StringHash := THash.Create();
try
DoSomethingWithStringHash;
finally
StringHash.Free()
end
end;
Fix your example and come back with more details.

Delphi: How to set field value of a generic using RTTI?

I'd like to fill the field of a generic object at runtime using D2010.
program generic_rtti_1;
{$APPTYPE CONSOLE}
uses
SysUtils, rtti;
type
TMyObject = class
FField1: string;
end;
TGeneric<TElement: class> = class
procedure FillFields(Element: TElement);
end;
procedure TGeneric<TElement>.FillFields(Element: TElement);
var
ctx: TRttiContext;
begin
ctx := TRttiContext.Create();
ctx.GetType(TypeInfo(TElement)).GetField('FField1').
SetValue(#Element, TValue.FromVariant('Some string'));
ctx.Free();
end;
When the line ctx.Free(); is executed, I get an AV at line 21986 in System.pas (function _IntfClear()). This is called from FContextToken := nil in rtti.pas. (In fact, the SetValue-induced AV pops up if I step into SetValue, however if step over it, only the ctx.Free-induced is reported. See below.)
If I remove ctx.Free();, the AV appears when calling SetValue(#Element, TValue.FromVariant('Some string'));. This too at line 21986 in System.pas.
Trying to figure this mess out, I replaced
ctx.GetType(TypeInfo(TElement)).GetField('FField1').
SetValue(#Element, TValue.FromVariant('Field 1 is set'));
with this:
rType := ctx.GetType(TypeInfo(TElement));
rField := rType.GetField('FField1');
Val := TValue.FromVariant('Field 1 is set');
rField.SetValue(#Element, Val);
This time, I got no error, however WriteLn(MyObject.FField1) printed an empty string. (The AV re-appears if I combine SetValue and TValue.FromVariant, i.e. write rField.SetValue(#Element, TValue.FromVariant('Field 1 is set'));.
In order to pinpoint the guilty line, I commented out line by line, replacing the commented code with a compound statement. By accident I forgot to comment out the Val := TValue.FromVariant('Field 1 is set');-line above, which causes the AV to disappear once more (still calling rField.SetValue(#Element, TValue.FromVariant('Field 1 is set'));). (Note that I don't actually use Val in the troublesome call, still the AV disappears.)
I'm kind'a lost at this point.
For sake of completeness, here's how I'd like to use the above code:
var
Generic: TGeneric<TMyObject>;
MyObject: TMyObject;
begin
MyObject := TMyObject.Create();
Generic := TGeneric<TMyObject>.Create();
Generic.FillFields();
WriteLn(MyObject.FField1);
Generic.Free();
MyObject.Free();
ReadLn;
end;
end.
Do anyone know what I'm doing wrong? (Is this even possible? Are there better ways to do this using generics? )
Well, I don't know if this makes sense to you guys, but here's how I solved it. Hard cast to TObject in procedure TGeneric<TElement>.FillFields works like a charm. Like so:
ctx.GetType(TypeInfo(TElement)).GetField('FField1').
SetValue(TObject(Element), TValue.FromVariant('Field 1 is set'));
Hope this is useful to someone else out there.

Why does the compiler say "Too many actual parameters" when I think I've provided the correct number?

I've declared the following function:
function next(current, next: string): Integer;
begin
form1.Label1.Caption := next;
form1.Label2.Caption := current;
form1.label3.Caption := clipboard.AsText+inttostr(c);
Result:=1;
end;
I try to execute it with this code:
if label1.Caption = '' then res := next('current', 'next');
I am getting the following error:
[Error] Unit1.pas(47): E2034 Too many
actual parameters
I think all parameters are good, so why am I getting that error?
I just tried your code on both Delphi 7 and Delphi 2010. If it works on those two, it should also work on Delphi 2005.
Conclusion: Delphi wants to use a different version of the "next" routine, because of code scope/visibility. Try ctrl+click-ing on "next" in "res := next();" and see where Delphi takes you. Alternatively post more code so we can tell you why Delphi is not choosing your version of the "next" routine. Ideally you should post a whole unit, starting from "unit name" to the final "end."
As specified by Cosmin Prund, the problem is because of the visibility.
TForm has a procedure with name Next which wont accept any parameters.
Your function uses the same name and as you are calling the function in TForm1 class implementation, compiler is treating the call as TForm1.Next and hence it was giving error.
To solve the problem, precede the unit name before the function name i.e., Unit1.Next().
So this should be your code
if label1.Caption = '' then res := Unit1.next('current', 'next');

Delphi ODAC: Disecting JMS messages from Oracle AQ

I'm trying to evaluate ODAC for using Oracle AQ.
The request queue contains JMS objects like these (but without linebreaks and other whitespace):
SYS.AQ$_JMS_BYTES_MESSAGE(
SYS.AQ$_JMS_HEADER(
'null','null','null','null','null','null',
SYS.AQ$_JMS_USERPROPARRAY(
SYS.AQ$_JMS_USERPROPERTY('Key1',100,'Value1','null',27),
SYS.AQ$_JMS_USERPROPERTY('Key2',100,'Value2','null',27),
SYS.AQ$_JMS_USERPROPERTY('Key3',100,'Value3','null',27),
SYS.AQ$_JMS_USERPROPERTY('Key4',100,'Value4','null',27),
SYS.AQ$_JMS_USERPROPERTY('Key5',100,'Value5','null',27),
SYS.AQ$_JMS_USERPROPERTY('Key6',100,'Value6','null',27),
SYS.AQ$_JMS_USERPROPERTY('Key7',100,'Value7','null',27),
SYS.AQ$_JMS_USERPROPERTY('Key8',100,'Value8','null',27),
SYS.AQ$_JMS_USERPROPERTY('Key9',100,'Value9','null',27),
SYS.AQ$_JMS_USERPROPERTY('Key10',100,'Value10.0','null',27),
SYS.AQ$_JMS_USERPROPERTY('Key11',100,'Value11','null',27),
SYS.AQ$_JMS_USERPROPERTY('Key12',100,'Value12','null',27),
SYS.AQ$_JMS_USERPROPERTY('Key13',100,'Value13','null',27),
SYS.AQ$_JMS_USERPROPERTY('Key14',100,'Value14','null',27),
SYS.AQ$_JMS_USERPROPERTY('Key15',100,'Value15','null',27),
SYS.AQ$_JMS_USERPROPERTY('Key16',100,'Value16','null',27),
SYS.AQ$_JMS_USERPROPERTY('Key17',100,'Value17','null',27)
)
),
4168,'null','oracle.sql.BLOB#959acc'
)
I can receive the underlying object (a string Payload comes back as an empty string, but a TOraObject PayLoad contains data).
I'm trying to disscect the TOraObject PayLoad, and am looking for a table that converts the DataType values into the correct AttrXxxx[Name] property calls.
OraType.AttributeCount:4
OraType.Name:"SYS"."AQ$_JMS_BYTES_MESSAGE"
OraType.DataType:15
Attribute[0].Name:HEADER
Attribute[0].DataType:15
OraType.AttributeCount:7
OraType.Name:"SYS"."AQ$_JMS_HEADER"
OraType.DataType:15
Attribute[0].Name:REPLYTO
Attribute[0].DataType:15
OraType.AttributeCount:3
OraType.Name:"SYS"."AQ$_AGENT"
OraType.DataType:15
Attribute[0].Name:NAME
Attribute[0].DataType:1
Attribute[1].Name:ADDRESS
Attribute[1].DataType:1
Attribute[2].Name:PROTOCOL
Attribute[2].DataType:5
Attribute[1].Name:TYPE
Attribute[1].DataType:1
Attribute[2].Name:USERID
Attribute[2].DataType:1
Attribute[3].Name:APPID
Attribute[3].DataType:1
Attribute[4].Name:GROUPID
Attribute[4].DataType:1
Attribute[5].Name:GROUPSEQ
Attribute[5].DataType:5
Attribute[6].Name:PROPERTIES
Attribute[6].DataType:17
OraType.AttributeCount:1
OraType.Name:"SYS"."AQ$_JMS_USERPROPARRAY"
OraType.DataType:17
Attribute[0].Name:ELEMENT
Attribute[0].DataType:15
OraType.AttributeCount:5
OraType.Name:"SYS"."AQ$_JMS_USERPROPERTY"
OraType.DataType:15
Attribute[0].Name:NAME
Attribute[0].DataType:1
Attribute[1].Name:TYPE
Attribute[1].DataType:5
Attribute[2].Name:STR_VALUE
Attribute[2].DataType:1
Attribute[3].Name:NUM_VALUE
Attribute[3].DataType:5
Attribute[4].Name:JAVA_TYPE
Attribute[4].DataType:5
Attribute[1].Name:BYTES_LEN
Attribute[1].DataType:5
Attribute[2].Name:BYTES_RAW
Attribute[2].DataType:1
Attribute[3].Name:BYTES_LOB
Attribute[3].DataType:102
By trial and error, I have come so far:
case DataType of
102:
LOB := ObjectPayLoad.AttrAsLob[Name];
15:
AttributeOraObject := ObjectPayLoad.AttrAsObject[Name];
17:
AttributeOraArray := ObjectPayLoad.AttrAsArray[Name];
else
begin
PayLoadAttributeAsString := ObjectPayLoad. AttrAsString[Name];
Logger.Log(' "%s"', [PayLoadAttributeAsString]);
end;
end;
A more complete list is welcome :-)
After this, I will need to research the other way around: generating the right TOraObject that has a JMS content in it.
Tips for that are also welcome.
--jeroen
Edit:
ODAC has multiple units defining constants.
The constant dtOraBlob with value 102 is in the OraClasses unit; constants defining DataType values start with the prefix dt, regardless of the unit that defines them.
Original:
I have found a few of these constants in the MemData unit:
case DataType of
102:
LOB := OraObject.AttrAsLob[Name];
MemData.dtObject: // 15
begin
AttributeOraObject := OraObject.AttrAsObject[Name];
LogOraObject(AttributeOraObject, Level+1);
end;
MemData.dtArray: // 17
begin
AttributeOraArray := OraObject.AttrAsArray[Name];
LogOraArray(AttributeOraArray, Level);
end;
MemData.dtFloat: // 5
begin
AttributeFloat := OraObject.AttrAsFloat[Name];
Logger.Log(Prefix+'"%g"', [AttributeFloat]);
end;
MemData.dtString: // 1
begin
PayLoadAttributeAsString := OraObject.AttrAsString[Name];
Logger.Log(Prefix+'"%s"', [PayLoadAttributeAsString]);
end;
else
begin
PayLoadAttributeAsString := OraObject.AttrAsString[Name];
Logger.Log(Prefix+'"%s"', [PayLoadAttributeAsString]);
end;
end;
I can't find the 102 constant though, but I'm pretty sure it is for a LOB field.
Anyone who can confirm that?
--jeroen

Resources