I have created a stored procedure with following declaration:
DELIMITER $$
DROP PROCEDURE IF EXISTS my_test$$
CREATE PROCEDURE my_test(input_number INT, OUT out_number text)
BEGIN
IF (input_number = 0) THEN
SET out_number='Errorrrr';
ELSE
SET out_number='Testing';
END IF;
END$$
DELIMITER ;
Following is my ZF2 code to call this SP:
$spResponse = 0;
$prepareStmt = $this->dbGateway->createStatement ();
$prepareStmt->prepare ( 'CALL my_test(?,?)' );
$prepareStmt->getResource ()->bindParam ( 1, $spRequest );
$prepareStmt->getResource ()->bindParam ( 2, $spResponse, \PDO::PARAM_STR, 2 );
$resultSet = $prepareStmt->execute ();
This code gives me following error:
Syntax error or access violation: 1414 OUT or INOUT argument 2 for routine zf2.my_test is not a variable or NEW pseudo-variable in BEFORE trigger
Can somebody advice where the issue is? Also, How can i retrieve value of "OUT" parameter.
Appreciate your response and help.
This low level code retrieves the base PDO connection object. This way you can work the results in PHP fashion
Related
I'm trying to utilize the OVH API in Delphi using the REST client. For this OVH requires me to generate a signature, but their documentation does not provide much info on this other than:
"$1$" + SHA1_HEX(AS+"+"+CK+"+"+METHOD+"+"+QUERY+"+"+BODY+"+"+TSTAMP)
They do provide thin wrappers for other languages so I thought I could take a look at those and try to replicate it. I found the following for generating the signature in C# and have extracted the function to be used in a test application.
Test app C# code:
textBox1.Text = GenerateSignature("appSecret", "consKey", 123456789, "PUT", "/path/to/api", "TEST DATA");
The C# result is:
$1$8336ecc5d03640b976e0b3ba005234a3046ab695
I attempted the rewrite the function in Delphi and came up with the following function:
function GenerateSignature(const appSecret, consKey: string;
const currentTimeStamp: LongInt; const method, target: string;
const data: string = ''): string;
begin
var
toSign := string.Join('+', [appSecret, consKey, method, target, data,
currentTimeStamp]);
var
binaryHash := THashSHA1.GetHashBytes(toSign);
var
signature := '';
for var byte in binaryHash do
begin
signature := signature + byte.ToHexString.ToLower;
end;
Result := '$1$' + signature;
end;
And to test it:
procedure Main;
const
APP_SECRET = 'appSecret';
CONSUMER_KEY = 'consKey';
method = 'PUT';
target = '/path/to/api';
data = 'TEST DATA';
CURRENT_TIMESTAMP = 123456789;
begin
Writeln(GenerateSignature(APP_SECRET, CONSUMER_KEY, CURRENT_TIMESTAMP,
method, data));
end;
Both test applications in C# and in Delphi use the same data but produce different outputs. My expected output is:
$1$8336ecc5d03640b976e0b3ba005234a3046ab695
But I end up getting the following output from delphi:
$1$d99fd5086853e388056d6fe37a9e2d0723de151b
I do not know C# very well but it seems to get the hashbytes then convert it to hex and stitch it together. How can I modify the Delphi function I wrote so that I can get my expected result?
Thanks to the last parameter being optional you didn't notice (because no compiler error/warning) that you actually missed one parameter when calling/testing your function, resulting in a text of
'appSecret+consKey+PUT+TEST DATA++123456789' to be hashed. Which is indeed
d99fd5086853e388056d6fe37a9e2d0723de151b
Let me reformat your test to make it more obvious:
const
APP_SECRET = 'appSecret';
CONSUMER_KEY = 'consKey';
CURRENT_TIMESTAMP = 123456789;
method = 'PUT';
target = '/path/to/api'; // Where is this used?
data = 'TEST DATA';
begin
GenerateSignature
( APP_SECRET
, CONSUMER_KEY
, CURRENT_TIMESTAMP
, method
// Forgotten parameter
, data // becomes "target"
);
end;
Consider making const data: string = '' mandatory, too, instead of optional.
I have followed the previous code and try to call a stored procedure
ALTER PROCEDURE [dbo].[sp_test]
#in char(5) = ' ',
#out smallint = 0 output
AS
BEGIN
SET NOCOUNT ON;
SET #out = 100
END
Then in the VB6, i try to request this stored procedure by below
strConn = "Select * from TBL where 1=2"
Set rsCmd = objCCS.ExecuteStatement(strConn, adUseServer, adOpenDynamic, adLockBatchOptimistic)
Dim rdoqry_data2 As ADODB.Command
Set rdoqry_data2 = CreateObject("Adodb.command")
Set rdoqry_data2 = rsCmd.ActiveCommand
rdoqry_data2.CommandType = adCmdStoredProc
rdoqry_data2.CommandText = "sp_test"
rdoqry_data2(0).Direction = adParamReturnValue
rdoqry_data2(1).Direction = adParamInput
rdoqry_data2(2).Direction = adParamOutput
rdoqry_data2(2).Type = adSmallInt
rdoqry_data2(1) = "123"
rdoqry_data2.Execute
But it flow an exception ODBC driver does not support the requested properties.
Can anyone find the problem?
Thanks.
Where exactly does the exception appear? I guess the exception is the result of calling the procedure sp_test and not the result of executing objCCS.ExecuteStatement, right?
My approach to call the stored procedure sp_test from VB6 would be:
Dim rdoqry_data2 As ADODB.Command
Set rdoqry_data2 = New ADODB.Command
With rdoqry_data2
Set .ActiveConnection = (your connection object)
.Parameters.Append rdoqry_data2.CreateParameter("#in", adVarchar, adParamInput, 5, "123")
.Parameters.Append rdoqry_data2.CreateParameter("#out", adSmallInt, adParamOutput, 2)
.CommandType = adCmdStoredProc
.CommandText = "sp_test"
.Execute
End With
First you have to create the command object and assign the connection object to it. In this case you need two parameter objects. First parameter is an input parameter with a maximum size of 5 bytes (char(5)) and the content "123". Second parameter is an output parameter with a max. size of 2 bytes (smallint). Finally you have to tell the command object to call a stored procedure with the name "sp_test".
Does this work for you?
Please help. I'm trying to fix this code and I'm just not seeing the error. I am very inexperienced and appreciate any help you can give me. Thanks.
Error: UberInventory-6.8.lua:1325: attempt to index local 'tooltip' (a nil value)
Code - beginning at line 1320
function UberInventory_HookTooltip( tooltip )
-- From global to local
local UBI_Hooks = UBI_Hooks;
-- Store default script
local tooltipName = tooltip:GetName();
UBI_Hooks["OnTooltipSetItem"][tooltipName] = tooltip:GetScript( "OnTooltipSetItem" );
UBI_Hooks["OnTooltipCleared"][tooltipName] = tooltip:GetScript( "OnTooltipCleared" );
-- Set new script to handle OntooltipSetItem
tooltip:SetScript( "OnTooltipSetItem", function( self, ... )
-- From global to local
local UBI_Hooks = UBI_Hooks;
-- Get tooltip name
local tooltipName = self:GetName();
-- Call default script
if ( UBI_Hooks["OnTooltipSetItem"][tooltipName] ) then
UBI_Hooks["OnTooltipSetItem"][tooltipName]( self, ... );
end;
-- Call new script (adds the item information)
UberInventory_AddItemInfo( self );
-- Turn on UberInventory indicator
self.UBI_InfoAdded = true;
end );
-- Set new script to handle OnTooltipCleared
tooltip:SetScript( "OnTooltipCleared", function( self, ... )
-- From global to local
local UBI_Hooks = UBI_Hooks;
-- Get tooltip name
local tooltipName = self:GetName();
-- Force reset of fonts (maxlines is a custom attribute added within the UberInventory_AddItemInfo function)
if ( self.maxlines ) then
local txtLeft, txtRight;
for i = 1, self.maxlines do
txtLeft = _G[self:GetName().."TextLeft"..i];
txtRight = _G[self:GetName().."TextRight"..i];
if ( txtLeft ) then txtLeft:SetFontObject( GameTooltipText ); end;
if ( txtRight ) then txtRight:SetFontObject( GameTooltipText ); end;
end;
end;
-- Call default script
if ( UBI_Hooks["OnTooltipCleared"][tooltipName] ) then
UBI_Hooks["OnTooltipCleared"][tooltipName]( self, ... );
end;
-- Turn off UberInventory indicator
self.UBI_InfoAdded = false;
end );
end;
And here is the code from line 2074 to 2087 where "HookTooltip" is called
function UberInventory_Install_Hooks()
-- Hook the Tooltips (OnTooltipSetItem, OnTooltipCleared)
UberInventory_HookTooltip( GameTooltip );
UberInventory_HookTooltip( ItemRefTooltip );
UberInventory_HookTooltip( ShoppingTooltip1 );
UberInventory_HookTooltip( ShoppingTooltip2 );
UberInventory_HookTooltip( ShoppingTooltip3 );
-- Hook mail stuff
UBI_Hooks["ReturnInboxItem"] = ReturnInboxItem;
ReturnInboxItem = UberInventory_ReturnInboxItem;
UBI_Hooks["SendMail"] = SendMail;
SendMail = UberInventory_SendMail;
end;
The function you are calling (UberInventory_HookTooltip) gets a nil value as toolkit parameter. When you then try to call a method of that tookit object (tooltip:GetName()), you get an expected error as indicated: "attempt to index local 'tooltip' (a nil value)". The code tries to find a field GetName in the table that should be stored in tooltip and fails to do that (to "index" the table) as there value is nil. You need to check the code that calls the function to make sure it passes the correct value. It's not possible to give you any further help without seeing the code that calls UberInventory_HookTooltip.
I want to enable Lua-Scripting (Lua 5.1) in my Delphi application. For this purpose I use the header Files of Thomas Lavergne.
Now I try to register a userdata type following this example: http://www.lua.org/pil/28.2.html
At the "new array function" it uses the command *luaL_getmetatable*.
static int newarray (lua_State *L) {
int n = luaL_checkint(L, 1);
size_t nbytes = sizeof(NumArray) + (n - 1)*sizeof(double);
NumArray *a = (NumArray *)lua_newuserdata(L, nbytes);
luaL_getmetatable(L, "LuaBook.array");
lua_setmetatable(L, -2);
a->size = n;
return 1; /* new userdatum is already on the stack */
}
Unfortunately the *luaL_getmetatable* Function is marked al old at my header File and commented out. I tried to activate it again but as expected I will get an error because the dll entrancepoint couldn't be found.
This is the Delphi-translation of that example (using another non array datatype)
Type
tMyType = tWhatever;
pMyType = ^tMyType;
{...}
Function newusertype(aState : pLua_State) : LongInt; cdecl;
Var
NewData : pMyType;
Begin
Result := 0;
NewData := lua_newuserdata(aState, SizeOf(tMyType ));
NewData^ := GetInitValue;
luaL_getMetaTable(aState, 'myexcample.mytype'); // Error/unknown function
lua_setmetatable(aState, -2);
Result := 1;
End;
Now I'm looking for an replacement of luaL_getMetaTable. I haven't found any information about one. In fact I haven't found any information that luaL_getMetaTable is outdated but it seems to be :(.
use lua_newmetatable(aState, 'myexample.mytype'). The thing is (if you only want to continue if the metatable already exists) you'll need to evaluate whether it returns a 0! If it returns 0, then it's wanting to create the metatable... in which case you can lua_pop(aState, 1).
Just remember that lua_newmetatable is a function returning an Integer (which in reality should be a Boolean).
Otherwise you can wait a few weeks for me to release Lua4Delphi version 2, which makes all of this super easy (and the Professional version actually automates the registration of Delphi Types and Instances with Lua)
I have an integer field in a ClientDataSet and I need to compare to some values, something like this:
I can use const
const
mvValue1 = 1;
mvValue2 = 2;
if ClientDataSet_Field.AsInteger = mvValue1 then
or enums
TMyValues = (mvValue1 = 1, mvValue2 = 2);
if ClientDataSet_Field.AsInteger = Integer(mvValue1) then
or class const
TMyValue = class
const
Value1 = 1;
Value2 = 2;
end;
if ClientDataSet_Field.AsInteger = TMyValues.Value1 then
I like the class const approach but it seems that is not the delphi way, So I want to know what do you think
Declaration:
type
TMyValues = class
type TMyEnum = (myValue1, myValue2, myValue3, myValue4);
const MyStrVals: array [TMyEnum] of string =
('One', 'Two', 'Three', 'Four');
const MyIntVals: array [TMyEnum] of integer =
(1, 2, 3, 4);
end;
Usage:
if ClientDataSet_Field.AsInteger = TMyValues.MyIntVals[myValue1] then
A cast would generally be my last choice.
I wouldn't say that class consts are not the Delphi way. It's just they have been introduced to Delphi quite recently, and a lot of books and articles you'll find on the internet were written before their introduction, and thus you won't see them widely used. Many Delphi developers (I'd say the majority) will have started using Delphi before they were made available, and thus they're not the first thing that one thinks about.
One thing to consider is backwards compatibility - class constants are relatively new to Delphi so if your code has to be sharable with previous versions than they are out.
I typically use enumerated types, with the difference from yours is that my first enumeration is usually an 'undefined' item to represent NULL or 0 in an int field.
TmyValues = (myvUndefined, myvDescription1, myvDescription2)
if ClientDataSet_Field.AsInteger = Ord(myvDescription1) then...
To use a little bit of Jim McKeeth's answer - if you need to display to the user a text viewable version, or if you need to convert their selected text into the enumerated type, then an array comes in handy in conjuction with the type:
const MYVALS: array [TmyValues ] of string = ('', 'Description1', 'Description2');
You can then have utility functions to set/get the enumerated type to/from a string:
Function MyValString(const pMyVal:TmyValues):string;
begin
result := MYVALS[Ord(pMyVal)];
end;
Function StringToMyVal(const pMyVal:String):TMyValues;
var i:Integer;
begin
result := myvUndefined;
for i := Low(MYVALS) to High(MYVALS) do
begin
if SameText(pMyVal, MYVALS[i]) then
begin
result := TMyValues(i);
break;
end;
end;
end;
Continuing on... you can have scatter routine to set a combo/list box:
Procedure SetList(const DestList:TStrings);
begin
DestList.Clear;
for i := Low(MYVALS) to High(MYVALS) do
begin
DestList.Insert(MYVALS[i]);
end;
end;
In code: SetList(Combo1.Items) or SetList(ListBox1.Items)..
Then if you are seeing the pattern here... useful utility functions surrounding your enumeration, then you add everything to it's own class and put this class into it's own unit named MyValueEnumeration or whaterver. You end up with all the code surrounding this enumeration in one place and keep adding the utility functions as you need them. If you keep the unit clean - don't mix in other unrelated functionality then it will stay very handy for all projects related to that enumeration.
You'll see more patterns as time goes and you use the same functionality over and over again and you'll build a better mousetrap again.
When using constants I recommend assigning the type when the data type is a numeric float.
Delphi and other languages will not always evaluate values correctly if the types do not match...
TMyValue = class
const
// will not compare correctly to float values.
Value1 = 1; // true constant can be used to supply any data type value
Value2 = 2; // but should only be compared to similar data type
// will not compare correctly to a single or double.
Value3 = 3.3; // default is extended in debugger
// will not compare correctly to a single or extended.
Value1d : double = Value1; // 1.0
Value2d : double = Value2; // 2.0
end;
Compared float values in if () and while () statements should be compared to values of the same data type, so it is best to define a temporary or global variable of the float type used for any comparison statements (=<>).
When compared to the same float data type this format is more reliable for comparison operators in any programming language, not just in Delphi, but in any programming language where the defined float types vary from variable to constant.
Once you assign a type, Delphi will not allow you to use the variable to feed another constant, so true constants are good to feed any related data type, but not for comparison in loops and if statements, unless they are assigned and compared to integer values.
***Note: Casting a value from one float type to another may alter the stored value from what you entered for comparison purposes, so verify with a unit test that loops when doing this.
It is unfortunate that Delphi doesn't allow an enumeration format like...
TController : Integer = (NoController = 0, ncpod = 1, nextwave = 2);
or enforce the type name for access to the enumeration values.
or allow a class constant to be used as a parameter default in a call like...
function getControllerName( Controller : TController = TController.NoController) : string;
However, a more guarded approach that provides both types of access would be to place the enumeration inside a class.
TController = class
//const
//NoController : Integer = 1;
//ncpod : Integer = 2;
//nextwave : Integer = 3;
type
Option = (NoController = 0, ncpod = 1, nextwave = 2);
public
Class function Name( Controller : Option = NoController) : string; static;
end;
implementation
class function TController.Name( Controller : Option = NoController) : string;
begin
Result := 'CNC';
if (Controller = Option.nextwave) then
Result := Result + ' Piranha'
else if (Controller = Option.ncpod) then
Result := Result + ' Shark';
Result := Result + ' Control Panel';
end;
This approach will effectively isolate the values, provide the static approach and allow access to the values using a for () loop.
The access to the values from a floating function would be like this...
using TControllerUnit;
function getName( Controller : TController.Option = TController.Option.NoController) : string;
implementation
function getName( Controller : TController.Option = TController.Option.NoController) : string;
begin
Result := 'CNC';
if (Controller = TController.Option.nextwave) then
Result := Result + ' Piranha'
else if (Controller = TController.Option.ncpod) then
Result := Result + ' Shark';
Result := Result + ' Control Panel';
end;
so many options! :-) i prefer enums and routinely use them as you describe. one of the parts i like is that i can use them with a "for" loop. i do use class constants as well but prefer enums (even private enums) depending on what i'm trying to achieve.
TMyType=class
private const // d2007 & later i think
iMaxItems=1; // d2007 & later i think
private type // d2007 & later i think
TMyValues = (mvValue1 = 1, mvValue2 = 2); // d2007 & later i think
private
public
end;
An option you haven't thought of is to use a lookup table in the database and then you can check against the string in the database.
eg.
Select value, Description from tbl_values inner join tbl_lookup_values where tbl_values.Value = tbl_lookup_values.value
if ClientDataSet_Field.AsString = 'ValueIwant' then