text stringlengths 14 6.51M |
|---|
unit ncaFrmTotal;
{
ResourceString: Dario 11/03/13
}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters,
cxContainer, cxEdit, cxPCdxBarPopupMenu, LMDPNGImage, ExtCtrls, cxPC, cxMemo,
cxLabel, cxTextEdit, cxCurrencyEdit, LMDControl, LMDCustomControl,
LMDCustomPanel, LMDCustomBevelPanel, LMDSimplePanel, Menus, StdCtrls,
cxButtons, LMDBaseControl, LMDBaseGraphicControl, LMDBaseGraphicButton,
LMDCustomSpeedButton, LMDSpeedButton;
type
TFrmTotal = class(TForm)
panTot: TLMDSimplePanel;
panInnerTot: TLMDSimplePanel;
panRec: TLMDSimplePanel;
panDif: TLMDSimplePanel;
panObsVal: TLMDSimplePanel;
LMDSimplePanel6: TLMDSimplePanel;
panObs: TLMDSimplePanel;
lbObs: TcxLabel;
edObs: TcxMemo;
pgValPontos: TcxPageControl;
tsTotVal: TcxTabSheet;
tsTotPontos: TcxTabSheet;
LMDSimplePanel1: TLMDSimplePanel;
LMDSimplePanel8: TLMDSimplePanel;
cxLabel5: TcxLabel;
LMDSimplePanel9: TLMDSimplePanel;
cxLabel6: TcxLabel;
LMDSimplePanel10: TLMDSimplePanel;
LMDSimplePanel11: TLMDSimplePanel;
lbNec: TcxLabel;
lbDisp: TcxLabel;
tsCusto: TcxTabSheet;
LMDSimplePanel3: TLMDSimplePanel;
edCustoT: TcxCurrencyEdit;
cxLabel3: TcxLabel;
cxLabel4: TcxLabel;
panOuterRec: TLMDSimplePanel;
LMDSimplePanel7: TLMDSimplePanel;
edRec: TcxCurrencyEdit;
lbRec: TcxLabel;
lbValorDif: TcxLabel;
lbNomeDif: TcxLabel;
panSimNao: TLMDSimplePanel;
lbNao: TcxLabel;
lbSim: TcxLabel;
panTot1: TLMDSimplePanel;
panTotal: TLMDSimplePanel;
edTotal: TcxCurrencyEdit;
lbTotal: TcxLabel;
panDesconto: TLMDSimplePanel;
edDesconto: TcxCurrencyEdit;
lbDesc: TcxLabel;
panSubTotal: TLMDSimplePanel;
edSubTotal: TcxCurrencyEdit;
lbSubTotal: TcxLabel;
LMDSimplePanel4: TLMDSimplePanel;
LMDSimplePanel5: TLMDSimplePanel;
LMDSimplePanel2: TLMDSimplePanel;
edCalc: TcxCurrencyEdit;
lbCalc2: TcxLabel;
lbCalc1: TcxLabel;
procedure lbDescClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure lbRecClick(Sender: TObject);
procedure edObsEnter(Sender: TObject);
procedure edObsExit(Sender: TObject);
procedure lbObsClick(Sender: TObject);
procedure btnPgTotalClick(Sender: TObject);
procedure btnZeroClick(Sender: TObject);
procedure edRecEnter(Sender: TObject);
procedure edRecExit(Sender: TObject);
procedure edRecPropertiesChange(Sender: TObject);
procedure edRecPropertiesEditValueChanged(Sender: TObject);
procedure edDescontoPropertiesChange(Sender: TObject);
procedure edDescontoPropertiesEditValueChanged(Sender: TObject);
procedure edDescontoEnter(Sender: TObject);
procedure edDescontoExit(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure lbSimClick(Sender: TObject);
procedure lbNaoClick(Sender: TObject);
procedure panTotMouseEnter(Sender: TObject);
procedure panTotMouseExit(Sender: TObject);
procedure panTotMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure FormMouseLeave(Sender: TObject);
private
FTamanho: Byte;
FAtualizando : Boolean;
FPontosNec : Double;
FDebCaption : String;
FPontosDisp : Double;
FRecAnt : Double;
FOpPagto : Byte; // 0 = manter, 1= pg.total, 2= zerar
{ Private declarations }
procedure OnTimerSelText(Sender: TObject);
function ValPanHeight : Integer;
procedure CriaTimerSelect(aObj: TObject);
procedure OnTimerNomeDif(Sender: TObject);
function GetSubTotal: Double;
procedure SetSubTotal(const Value: Double);
procedure SetPontosNec(const Value: Double);
procedure SetPontosDisp(const Value: Double);
function GetRecebido: Double;
procedure SetRecebido(const Value: Double);
procedure SetTamanho(const Value: Byte);
public
procedure InitVal(aSubTot, aDesconto, aPago, aRecebido : Double; aObs: String; aParent: TWinControl; aShowObs: Boolean = True);
procedure InitPontos(aNec, aDisp: Double; aObs: String; aParent: TWinControl; aShowObs: Boolean = True);
procedure InitCusto(aCusto: Double; aObs: String; aParent: TWinControl; aShowObs: Boolean = True);
procedure Atualiza(aUpdateRec: Boolean = False);
procedure Limpa;
procedure PagarFimAcesso;
function Debito: Double;
function Desconto: Double;
function Pago: Double;
function Total: Double;
property Tamanho: Byte
read FTamanho write SetTamanho;
property Recebido: Double
read GetRecebido write SetRecebido;
property OpPagto: Byte
read FOpPagto write FOpPagto;
property PontosDisp: Double
read FPontosDisp write SetPontosDisp;
property SubTotal: Double
read GetSubTotal write SetSubTotal;
property PontosNec: Double
read FPontosNec write SetPontosNec;
{ Public declarations }
end;
var
FrmTotal: TFrmTotal;
implementation
uses ncClassesBase, ncaDM, ncIDRecursos;
// START resource string wizard section
resourcestring
SDebitar = 'Debitar';
SDescontoNãoPodeSerMaiorQueSubTot = 'Desconto não pode ser maior que sub-total';
SPagarNoFinalDoAcesso = 'Pagar no final do acesso';
STroco = ' Troco ';
// END resource string wizard section
{$R *.dfm}
procedure TFrmTotal.lbNaoClick(Sender: TObject);
begin
edRec.Value := 0;
FOpPagto := 0;
edRec.SetFocus;
CriaTimerSelect(edRec);
end;
procedure TFrmTotal.lbRecClick(Sender: TObject);
begin
if edRec.Value<0.01 then begin
edRec.Value := edTotal.Value;
FOpPagto := 1;
end else begin
edRec.Value := 0;
FOpPagto := 0;
end;
edRec.SetFocus;
CriaTimerSelect(edRec);
end;
procedure TFrmTotal.lbSimClick(Sender: TObject);
begin
edRec.Value := edTotal.Value;
FOpPagto := 1;
edRec.SetFocus;
CriaTimerSelect(edRec);
end;
procedure TFrmTotal.Limpa;
begin
FDebCaption := SDebitar;
edDesconto.Properties.ReadOnly := not Permitido(daTraDesconto);
lbDesc.Enabled := Permitido(daTraDesconto);
FAtualizando := True;
try
FOpPagto := 0;
edSubTotal.Value := 0;
edCustoT.Value := 0;
edDesconto.Value := 0;
edTotal.Value := 0;
edRec.Value := 0;
FPontosNec := 0;
FPontosDisp := 0;
finally
FAtualizando := False;
end;
end;
function TFrmTotal.Debito: Double;
begin
if edRec.Value < edTotal.Value then
Result := edTotal.Value - edRec.Value else
Result := 0;
end;
function TFrmTotal.Desconto: Double;
begin
Result := edDesconto.Value;
end;
procedure TFrmTotal.edDescontoEnter(Sender: TObject);
begin
CriaTimerSelect(edDesconto);
end;
procedure TFrmTotal.edDescontoExit(Sender: TObject);
begin
if edDesconto.Value > edSubTotal.Value then
edDesconto.Value := edSubTotal.Value;
end;
procedure TFrmTotal.edDescontoPropertiesChange(Sender: TObject);
begin
if (edDesconto.Focused) and (edDesconto.Value > edSubTotal.Value) then begin
edDesconto.Value := edSubTotal.Value;
MessageBeep(30);
ShowMessage(SDescontoNãoPodeSerMaiorQueSubTot);
CriaTimerSelect(edDesconto);
end;
edDesconto.PostEditValue;
end;
procedure TFrmTotal.edDescontoPropertiesEditValueChanged(Sender: TObject);
begin
Atualiza(True);
end;
procedure TFrmTotal.edObsEnter(Sender: TObject);
begin
// panObs.Color := $00B3FFFF;
// pgDebTroco.Color := $00DFDFDF;
end;
procedure TFrmTotal.edObsExit(Sender: TObject);
begin
// panObs.Color := clWhite;
// pgDebTroco.Color := clWhite;
end;
procedure TFrmTotal.edRecEnter(Sender: TObject);
begin
FRecAnt := edRec.Value;
criaTimerSelect(edRec);
end;
procedure TFrmTotal.edRecExit(Sender: TObject);
begin
// panOuterRec.Width := 215;
if FRecAnt <> edRec.Value then begin
if edRec.Value = edTotal.Value then
FOpPagto := 1 else
FOpPagto := 0;
end;
end;
procedure TFrmTotal.edRecPropertiesChange(Sender: TObject);
begin
edRec.PostEditValue;
end;
procedure TFrmTotal.edRecPropertiesEditValueChanged(Sender: TObject);
begin
Atualiza;
end;
procedure TFrmTotal.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TFrmTotal.FormCreate(Sender: TObject);
begin
FTamanho := 0;
Limpa;
end;
procedure TFrmTotal.FormMouseLeave(Sender: TObject);
begin
panSimNao.Visible := False;
end;
procedure TFrmTotal.FormMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
panSimNao.Visible := (Y>panTot.Top) and panRec.Visible;
end;
function TFrmTotal.GetRecebido: Double;
begin
Result := edRec.Value;
end;
function TFrmTotal.GetSubTotal: Double;
begin
Result := edSubTotal.Value;
end;
function PontosToStr(P: Double): String;
begin
Str((Int(P*10)/10):10:1, Result);
Result := Trim(Result);
if Pos('.', Result)>0 then
while (Result>'') and (Result[Length(Result)] in ['0']) do Delete(Result, Length(Result), 1);
if Result[Length(Result)]='.' then Delete(Result, Length(Result), 1);
end;
procedure TFrmTotal.InitCusto(aCusto: Double; aObs: String;
aParent: TWinControl; aShowObs: Boolean = True);
begin
pgValPontos.ActivePage := tsCusto;
FAtualizando := True;
try
panObs.Visible := aShowObs;
edObs.Lines.Text := aObs;
edSubTotal.Value := aCusto;
edCustoT.Value := aCusto;
finally
FAtualizando := False;
end;
if aParent<>nil then
panTot.Parent := aParent;
panTot.Parent.ClientHeight := 78;
Atualiza;
end;
procedure TFrmTotal.InitPontos(aNec, aDisp: Double; aObs: String;
aParent: TWinControl; aShowObs: Boolean = True);
begin
pgValPontos.ActivePage := tsTotPontos;
FAtualizando := True;
try
panObs.Visible := aShowObs;
panRec.Visible := False;
edObs.Lines.Text := aObs;
SetPontosNec(aNec);
SetPontosDisp(aDisp);
finally
FAtualizando := False;
end;
if aParent<>nil then
panTot.Parent := aParent;
panTot.Parent.ClientHeight := 78;
end;
procedure TFrmTotal.InitVal(aSubTot, aDesconto, aPago, aRecebido: Double;
aObs: String; aParent: TWinControl; aShowObs: Boolean = True);
begin
pgValPontos.ActivePage := tsTotVal;
FAtualizando := True;
try
panObs.Visible := aShowObs;
edObs.Lines.Text := aObs;
if aRecebido<0.01 then aRecebido := aPago;
edSubTotal.Value := aSubTot;
edDesconto.Value := aDesconto;
edRec.Value := aRecebido;
finally
FAtualizando := False;
end;
if aParent<>nil then
panTot.Parent := aParent;
panTot.Parent.ClientHeight := ValPanHeight;
Atualiza;
end;
procedure TFrmTotal.lbDescClick(Sender: TObject);
begin
if edDesconto.Value>0.009 then begin
edDesconto.Value := 0;
FOpPagto := 0;
end else begin
edDesconto.Value := edSubTotal.Value;
FOpPagto := 2;
end;
edDesconto.SetFocus;
CriaTimerSelect(edDesconto);
end;
procedure TFrmTotal.lbObsClick(Sender: TObject);
begin
edObs.SetFocus;
end;
procedure TFrmTotal.OnTimerNomeDif(Sender: TObject);
begin
try
lbNomeDif.Left := 0;
lbNomeDif.Realign;
finally
Sender.Free;
end;
end;
procedure TFrmTotal.OnTimerSelText(Sender: TObject);
begin
with TcxCurrencyEdit(TTimer(Sender).Tag) do
if Focused then SelectAll;
Sender.Free;
end;
procedure TFrmTotal.PagarFimAcesso;
begin
FDebCaption := SPagarNoFinalDoAcesso;
end;
function TFrmTotal.Pago: Double;
begin
if edRec.Value > edTotal.Value then
Result := edTotal.Value else
Result := edRec.Value;
end;
procedure TFrmTotal.panTotMouseEnter(Sender: TObject);
begin
panSimNao.Visible := panRec.Visible;
end;
procedure TFrmTotal.panTotMouseExit(Sender: TObject);
begin
panSimNao.Visible := False;
end;
procedure TFrmTotal.panTotMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
panSimNao.Visible := panRec.Visible;
end;
procedure TFrmTotal.SetPontosDisp(const Value: Double);
begin
FPontosDisp := Value;
lbDisp.Caption := PontosToStr(Value);
end;
procedure TFrmTotal.SetPontosNec(const Value: Double);
begin
FPontosNec := Value;
lbNec.Caption := PontosToStr(Value);
end;
procedure TFrmTotal.SetRecebido(const Value: Double);
begin
edRec.Value := Value;
end;
procedure TFrmTotal.SetSubTotal(const Value: Double);
begin
panSimNao.Visible := (Value>0.009);
edSubTotal.Value := Value;
Atualiza(True);
end;
procedure TFrmTotal.SetTamanho(const Value: Byte);
const
minHeight = 24;
var
H : Integer;
procedure ApplyFontHeight(aSize: Integer);
begin
lbCalc1.Style.Font.Size := aSize;
lbCalc2.Style.Font.Size := aSize;
edCalc.Style.Font.Size := aSize;
lbSubTotal.Style.Font.Size := aSize;
edSubTotal.Style.Font.Size := aSize;
lbDesc.Style.Font.Size := aSize;
edDesconto.Style.Font.Size := aSize;
lbTotal.Style.Font.Size := aSize;
edTotal.Style.Font.Size := aSize;
lbRec.Style.Font.Size := aSize;
edRec.Style.Font.Size := aSize;
lbValorDif.Style.Font.Size := aSize;
lbNomeDif.Style.Font.Size := aSize-2;
if edCalc.Height > 24 then
H := edCalc.Height else
H := 24;
panObsVal.Height := (H*3)+2;
panSubTotal.Height := H;
panDesconto.Height := H;
panTotal.Height := H;
panRec.Height := H+2;
pgValPontos.Width := lbCalc1.Width + lbCalc2.Width + 5;
panOuterRec.Width := pgValPontos.Width;
edSubTotal.Width := lbCalc2.Width;
edDesconto.Width := lbCalc2.Width;
edTotal.Width := lbCalc2.Width;
edRec.Width := lbCalc2.Width;
panTot.Parent.ClientHeight := ValPanHeight;
panSimNao.Top := panTot.Parent.ClientHeight;
end;
begin
if Value=FTamanho then Exit;
if Value = tamTelaPDV1 then
ApplyFontHeight(20) else
ApplyFontHeight(10);
FTamanho := Value;
end;
function TFrmTotal.Total: Double;
begin
Result := edTotal.Value;
end;
function TFrmTotal.ValPanHeight: Integer;
begin
Result := panSimNao.Height + panRec.Height + panObsVal.Height + 6;
end;
procedure TFrmTotal.Atualiza(aUpdateRec: Boolean = False);
begin
if FAtualizando then Exit;
FAtualizando := True;
try
edCustoT.Value := edSubTotal.Value;
if edDesconto.Value < edSubTotal.Value then
edTotal.Value := edSubTotal.Value - edDesconto.Value else
edTotal.Value := 0;
if edDesconto.Value > 0 then
edDesconto.Style.TextColor := clRed else
edDesconto.Style.TextColor := clSilver;
if edTotal.Value < 0.01 then
edRec.Value := 0
else
if aUpdateRec then
case FOpPagto of
1 : edRec.Value := edTotal.Value;
2 : edRec.Value := 0;
end;
if edRec.Value > edTotal.Value then begin
lbValorDif.Visible := True;
lbNomeDif.Visible := True;
lbNomeDif.Style.Color := clGreen;
lbNomeDif.Caption := STroco;
lbValorDif.Style.Color := clGreen;
lbValorDif.Caption := FloatToStrF(Abs(edRec.Value - edTotal.Value), ffCurrency, 10, 2)+' ';
lbNomeDif.Left := 0;
lbValorDif.Left := panOuterRec.Left-1;
end else
if edRec.Value < edTotal.Value then begin
lbValorDif.Visible := True;
lbNomeDif.Visible := True;
lbNomeDif.Left := 0;
lbValorDif.Left := panOuterRec.Left-1;
lbNomeDif.Style.Color := clRed;
lbNomeDif.Caption := ' '+FDebCaption+' ';
lbValorDif.Style.Color := clRed;
lbValorDif.Caption := FloatToStrF(Abs(edRec.Value - edTotal.Value), ffCurrency, 10, 2)+' ';
end else begin
lbNomeDif.Visible := False;
lbValorDif.Visible := False;
end;
lbNomeDif.Left := 0;
with TTimer.Create(Self) do begin
Interval := 50;
OnTimer := OnTimerNomeDif;
Enabled := True;
end;
finally
FAtualizando := False;
end;
end;
procedure TFrmTotal.btnPgTotalClick(Sender: TObject);
begin
edRec.Value := edTotal.Value;
FOpPagto := 1;
edRec.SetFocus;
CriaTimerSelect(edRec);
end;
procedure TFrmTotal.btnZeroClick(Sender: TObject);
begin
edRec.Value := 0;
FOpPagto := 2;
edRec.SetFocus;
CriaTimerSelect(edRec);
end;
procedure TFrmTotal.CriaTimerSelect(aObj: TObject);
begin
with TTimer.Create(Self) do begin
Tag := Integer(aObj);
Interval := 50;
OnTimer := OnTimerSelText;
Enabled := True;
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi LiveBindings Framework }
{ }
{ Copyright(c) 2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit BindCompNewStd;
interface
uses Winapi.Windows, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Forms, Vcl.Controls, Vcl.StdCtrls,
Vcl.Buttons, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.ActnList, Data.Bind.Components, DesignIntf;
type
TNewStdDataBindingDlg = class(TForm)
HelpBtn: TButton;
OKBtn: TButton;
CancelBtn: TButton;
ActionList1: TActionList;
AcceptAction: TAction;
ActionTree: TTreeView;
Label1: TLabel;
procedure HelpBtnClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure DataBindingListCompare(Sender: TObject; Item1, Item2: TListItem;
Data: Integer; var Compare: Integer);
procedure DataBindingListDblClick(Sender: TObject);
procedure AcceptActionUpdate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
FSortColumn: Integer;
FActiveClassGroup: TPersistentClass;
FDesigner: IDesigner;
FAllowClass: TFunc<TContainedBindCompClass, Boolean>;
procedure AddDataBinding(const Category: string; DataBindingClass: TContainedBindCompClass;
Info: Pointer);
function GetRegKey: string;
procedure ReadSettings;
procedure WriteSettings;
procedure SetDesigner(const Value: IDesigner);
procedure SetAllowClass(
const Value: TFunc<TContainedBindCompClass, Boolean>);
public
property DesignerIntf: IDesigner read FDesigner write SetDesigner;
property AllowClass: TFunc<TContainedBindCompClass, Boolean> read FAllowClass write SetAllowClass;
end;
implementation
{$R *.dfm}
uses DsnConst, System.Win.Registry;
procedure TNewStdDataBindingDlg.HelpBtnClick(Sender: TObject);
begin
Application.HelpContext(HelpContext);
end;
procedure TNewStdDataBindingDlg.AddDataBinding(const Category: string;
DataBindingClass: TContainedBindCompClass; Info: Pointer);
var
Node: TTreeNode;
ACat: String;
LClassGroup: TPersistentClass;
begin
Assert(FActiveClassGroup <> nil);
LClassGroup := System.Classes.ClassGroupOf(DataBindingClass);
//if not (LClassGroup = TPersistent) or (LClassGroup = FActiveClassGroup) then
if not FActiveClassGroup.InheritsFrom(LClassGroup) then
Exit;
if Assigned(FAllowClass) then
if not FAllowClass(DataBindingClass) then
Exit;
Node := nil;
ACat := Category;
if Length(ACat) = 0 then
ACat := SActionCategoryNone;
if ActionTree.Items.Count > 0 then
begin
Node := ActionTree.Items[0];
while Assigned(Node) do
if AnsiCompareText(Node.Text, ACat) = 0 then
Break
else
Node := Node.getNextSibling;
end;
if not Assigned(Node) then
Node := ActionTree.Items.AddObject(nil, ACat, nil);
ActionTree.Items.AddChildObject(Node, DataBindingClass.ClassName, Pointer(DataBindingClass));
Node.Expanded := True;
end;
function TNewStdDataBindingDlg.GetRegKey: string;
begin
// Result := Designer.GetBaseRegKey + '\' + sIniEditorsName + '\ActionList Editor';
end;
procedure TNewStdDataBindingDlg.ReadSettings;
//var
// I: Integer;
begin
{ with TRegIniFile.Create(GetRegKey) do
try
I := ReadInteger('StandardActionsDlg', 'Width', Width);
if I <= Screen.Width then
Width := I;
I := ReadInteger('StandardActionsDlg', 'Height', Height);
if I <= Screen.Height then
Height := I;
finally
Free;
end;}
end;
procedure TNewStdDataBindingDlg.SetAllowClass(
const Value: TFunc<TContainedBindCompClass, Boolean>);
begin
FAllowClass := Value;
end;
procedure TNewStdDataBindingDlg.SetDesigner(const Value: IDesigner);
begin
FDesigner := Value;
FActiveClassGroup := FDesigner.ActiveClassGroup;
end;
procedure TNewStdDataBindingDlg.WriteSettings;
begin
{ with TRegIniFile.Create(GetRegKey) do
begin
EraseSection('StandardActionsDlg');
WriteInteger('StandardActionsDlg', 'Width', Width);
WriteInteger('StandardActionsDlg', 'Height', Height);
end;}
end;
procedure TNewStdDataBindingDlg.FormCreate(Sender: TObject);
begin
//
end;
procedure TNewStdDataBindingDlg.FormShow(Sender: TObject);
var
Item: TTreeNode;
begin
Assert(FDesigner <> nil);
ReadSettings;
ActionTree.Items.BeginUpdate;
try
EnumRegisteredBindComponents(AddDataBinding, nil);
// ActionTree.AlphaSort;
finally
ActionTree.Items.EndUpdate;
end;
Item := nil;
if ActionTree.Items.Count > 1 then
Item := ActionTree.Items[1]
else if ActionTree.Items.Count > 0 then
Item := ActionTree.Items[0];
if Item <> nil then
begin
Item.Selected := True;
Item.Focused := True;
end;
ActionTree.SetFocus;
end;
procedure TNewStdDataBindingDlg.DataBindingListCompare(Sender: TObject; Item1,
Item2: TListItem; Data: Integer; var Compare: Integer);
begin
if Abs(FSortColumn) = 1 then
Compare := FSortColumn * AnsiCompareText(Item1.Caption, Item2.Caption) else
Compare := FSortColumn * AnsiCompareText(Item1.SubItems[0], Item2.SubItems[0]);
end;
procedure TNewStdDataBindingDlg.DataBindingListDblClick(Sender: TObject);
begin
if OKBtn.Enabled then OKBtn.Click;
end;
procedure TNewStdDataBindingDlg.AcceptActionUpdate(Sender: TObject);
begin
AcceptAction.Enabled := (ActionTree.Selected <> nil) and
Assigned(ActionTree.Selected.Data);
end;
procedure TNewStdDataBindingDlg.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
WriteSettings;
end;
end.
|
PROGRAM tp1_7;
{Practica Estructura de Datos 2012. Practica 1, Ejercicio 7}
USES pila_chr,Crt;
VAR
b: Boolean;
function esBalanceada(s:String):Boolean;
const
OPEN_CHR = ['(','{','['];
CLOSE_CHR = [')','}',']'];
var
auxP: tipo_pila_chr;
i: integer;
c: char;
begin
esBalanceada:=false;
Pchr_Crear(auxP);
{i:=1;}
{el while no es lo mas eficiente pero luego me permite el uso de i para
asegurar que se recorrio todo el string sin usar el Break
Al final use un for y un exit para salir del procedure, lamento no tener
un return..}
{while (i <= Length(s)) do}
for i:=1 to Length(s) do
begin
if s[i] in OPEN_CHR
{agrego un elemento de apertura a una lista auxiliar para
luego comparar}
then Pchr_Agregar(auxP, s[i]);
if s[i] in CLOSE_CHR
{se encontro un elemento de cierre, debo ver
si ya se ingreso uno de apertura correspondiente}
then begin
if PChr_Vacia(auxP)
{si quiero cerrar un elemento y no abri ninguno
antes entonces no es balanceada
TODO: usar excepciones?}
then Exit{Break}
else begin
PChr_Sacar(auxP,c);
{compara cada caso
TODO: tiene que haber otra forma..}
if (c = '(') and NOT(s[i] = ')') then Exit;{Break;}
if (c = '{') and NOT(s[i] = '}') then Exit;{Break;}
if (c = '[') and NOT(s[i] = ']') then Exit;{Break;}
end;
end;
{i:= i+1;}
end;
{si i es igual al largo del string + 1 significa que se recorrio
todo el string sin cortar la ejecucion del while.
si auxP es vacia significa que no queda ningun elemento por cerrar}
if {(i=Length(s)+1) AND} PChr_Vacia(auxP) then esBalanceada:=true;
end;
Begin
clrscr;
{test strings}
b:= esBalanceada(''); {TRUE}
writeln(b);
b:= esBalanceada(')'); {FALSE}
writeln(b);
b:= esBalanceada('('); {FALSE}
writeln(b);
b:= esBalanceada('asdasdasd'); {TRUE}
writeln(b);
b:= esBalanceada('())'); {FALSE}
writeln(b);
b:= esBalanceada('(()'); {FALSE}
writeln(b);
b:= esBalanceada('({)}'); {FALSE}
writeln(b);
b:= esBalanceada('function b(asd,[b]){function a()[{b},{a}]}'); {TRUE}
writeln(b);
readln;
End. |
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC ODBC API wrapping classes }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.Phys.ODBCWrapper;
interface
uses
System.Classes, Data.FMTBcd,
FireDAC.Stan.Intf, FireDAC.Stan.Error, FireDAC.Stan.Util,
FireDAC.Phys.ODBCCli;
type
TFDODBCNativeError = class;
EODBCNativeException = class;
EODBCNativeExceptionClass = class of EODBCNativeException;
TODBCLib = class;
TODBCLibClass = class of TODBCLib;
TODBCHandle = class;
TODBCEnvironment = class;
TODBCConnection = class;
TODBCSelectItem = class;
TODBCVariable = class;
TODBCParameter = class;
TODBCLongDataStream = class;
TODBCColumn = class;
TODBCVariableList = class;
TODBCPageBuffer = class;
TODBCStatementBase = class;
TODBCCommandStatement = class;
TODBCMetaInfoStatement = class;
TODBCParseErrorEvent = procedure (AHandle: TODBCHandle; ARecNum: SQLSmallint;
const ASQLState: String; ANativeError: SQLInteger; const ADiagMessage: String;
const ACommandText: String; var AObj: String; var AKind: TFDCommandExceptionKind;
var ACmdOffset: Integer) of object;
TODBCGetMaxSizesEvent = procedure (AStrDataType: SQLSmallint; AFixedLen: Boolean;
out ACharSize, AByteSize: Integer) of object;
TFDODBCNativeError = class(TFDDBError)
private
FSQLState: String;
FDiagMessage: String;
protected
procedure Assign(ASrc: TFDDBError); override;
procedure LoadFromStorage(const AStorage: IFDStanStorage); override;
procedure SaveToStorage(const AStorage: IFDStanStorage); override;
public
property SQLState: String read FSQLState;
property DiagMessage: String read FDiagMessage;
end;
EODBCNativeException = class(EFDDBEngineException)
private
function GetErrors(AIndex: Integer): TFDODBCNativeError;
protected
function GetErrorClass: TFDDBErrorClass; override;
public
constructor Create(AStatus: SQLReturn; AOwner: TODBCHandle); overload; virtual;
function AppendError(AHandle: TODBCHandle; ARecNum: SQLSmallint;
const ASQLState: String; ANativeError: SQLInteger; const ADiagMessage,
AResultMessage, ACommandText, AObject: String; AKind: TFDCommandExceptionKind;
ACmdOffset, ARowIndex: Integer): TFDDBError; virtual;
property Errors[Index: Integer]: TFDODBCNativeError read GetErrors; default;
end;
{$IFDEF FireDAC_MONITOR}
TODBCTracer = class(TThread)
private
FMonitor: IFDMoniClient;
FLib: TODBCLib;
{$IFDEF MSWINDOWS}
FLockOutput: Integer;
{$ENDIF}
FEncoder: TFDEncoder;
protected
procedure Execute; override;
public
constructor Create(const AMonitor: IFDMoniClient; ALib: TODBCLib);
destructor Destroy; override;
end;
{$ENDIF}
TODBCLib = class(TFDLibrary)
private
{$IFDEF FireDAC_MONITOR}
FTracer: TODBCTracer;
FTraceClients: TFDObjList;
FTracing: Boolean;
{$ENDIF}
FhCPLib: THandle;
function GetTRACE: Boolean;
function GetTRACEFILE: string;
procedure SetTRACE(AValue: Boolean);
procedure SetTRACEFILE(const AValue: string);
protected
function GetODBCTextProcAddress(const AProcName: String; ARequired: Boolean = True): Pointer;
procedure LoadLibrary(const ADLLNames: array of String; ARequired: Boolean); override;
procedure LoadEntries; override;
public
SQLAllocHandle: TSQLAllocHandle;
SQLBindCol: TSQLBindCol;
SQLBindParameter: TSQLBindParameter;
SQLCancel: TSQLCancel;
SQLColAttribute: TSQLColAttribute;
SQLColAttributeInt: TSQLColAttributeInt;
SQLColAttributeString: TSQLColAttributeString;
SQLColumns: TSQLColumns;
SQLConnect: TSQLConnect;
SQLDataSources: TSQLDataSources;
SQLDescribeCol: TSQLDescribeCol;
SQLDescribeParam: TSQLDescribeParam;
SQLDisconnect: TSQLDisconnect;
SQLDriverConnect: TSQLDriverConnect;
SQLBrowseConnect: TSQLBrowseConnect;
SQLDrivers: TSQLDrivers;
SQLEndTran: TSQLEndTran;
SQLExecDirect: TSQLExecDirect;
SQLExecute: TSQLExecute;
SQLFetch: TSQLFetch;
SQLForeignKeys: TSQLForeignKeys;
SQLFreeHandle: TSQLFreeHandle;
SQLFreeStmt: TSQLFreeStmt;
SQLGetConnectAttr: TSQLGetConnectAttr;
SQLGetCursorName: TSQLGetCursorName;
SQLGetData: TSQLGetData;
SQLGetDescField: TSQLGetDescField;
SQLGetDescRec: TSQLGetDescRec;
SQLGetDiagRec: TSQLGetDiagRec;
SQLGetDiagField: TSQLGetDiagField;
SQLGetEnvAttr: TSQLGetEnvAttr;
SQLGetFunctions: TSQLGetFunctions;
SQLGetInfo: TSQLGetInfo;
SQLGetInfoSQLLen: TSQLGetInfoSQLLen;
SQLGetInfoInt: TSQLGetInfoInt;
SQLGetInfoSmallint: TSQLGetInfoSmallint;
SQLGetInfoString: TSQLGetInfoString;
SQLGetStmtAttr: TSQLGetStmtAttr;
SQLGetTypeInfo: TSQLGetTypeInfo;
SQLMoreResults: TSQLMoreResults;
SQLNumParams: TSQLNumParams;
SQLNumResultCols: TSQLNumResultCols;
SQLParamData: TSQLParamData;
SQLPrepare: TSQLPrepare;
SQLPrimaryKeys: TSQLPrimaryKeys;
SQLProcedureColumns: TSQLProcedureColumns;
SQLProcedures: TSQLProcedures;
SQLPutData: TSQLPutData;
SQLRowCount: TSQLRowCount;
SQLSetConnectAttr: TSQLSetConnectAttr;
SQLSetCursorName: TSQLSetCursorName;
SQLSetDescField: TSQLSetDescField;
SQLSetDescRec: TSQLSetDescRec;
SQLSetEnvAttr: TSQLSetEnvAttr;
SQLSetPos: TSQLSetPos;
SQLSetStmtAttr: TSQLSetStmtAttr;
SQLSpecialColumns: TSQLSpecialColumns;
SQLStatistics: TSQLStatistics;
SQLTablePrivileges: TSQLTablePrivileges;
SQLTables: TSQLTables;
// ODBCCP
SQLConfigDataSource: TSQLConfigDataSource;
SQLInstallerError: TSQLInstallerError;
constructor Create(AOwningObj: TObject = nil);
destructor Destroy; override;
procedure Load(const AHome, ALib: String);
procedure Unload; override;
class function Allocate(const AHome, ALib: String; AOwningObj: TObject = nil): TODBCLib;
class procedure Release(ALib: TODBCLib);
class function DecorateKeyValue(const AValue: String): String;
// Properties
{$IFDEF FireDAC_MONITOR}
property Tracing: Boolean read FTracing;
procedure ActivateTracing(const AMonitor: IFDMoniClient; AClient: TObject);
procedure DeactivateTracing(AClient: TObject);
{$ENDIF}
// ODBC
property TRACE: Boolean read GetTRACE write SetTRACE;
property TRACEFILE: string read GetTRACEFILE write SetTRACEFILE;
end;
TODBCHandle = class(TObject)
private
FHandle: SQLHandle;
FHandleType: SQLSmallint;
FOwnHandle: Boolean;
FODBCLib: TODBCLib;
FOwner: TODBCHandle;
[weak] FOwningObj: TObject;
FIgnoreErrors: Boolean;
function GetConnection: TODBCConnection;
procedure ProcessError(AStatus: SQLReturn);
{$IFDEF FireDAC_MONITOR}
function GetTracing: Boolean;
{$ENDIF}
protected
procedure GetNonStrAttribute(AAttr: SQLInteger; ApValue: SQLPointer); virtual;
procedure GetStrAttribute(AAttr: SQLInteger; out AValue: String); virtual;
function GetCharAttribute(AAttr: SQLInteger): string;
function GetIntAttribute(AAttr: SQLInteger): SQLInteger;
function GetPSQLPAttribute(AAttr: SQLInteger): SQLPointer;
function GetPUIntAttribute(AAttr: SQLInteger): PSQLUInteger;
function GetPUSmIntAttribute(AAttr: SQLInteger): PSQLUSmallint;
function GetUIntAttribute(AAttr: SQLInteger): SQLUInteger;
function GetUSmIntAttribute(AAttr: SQLInteger): SQLUSmallint;
function GetPtrAttribute(AAttr: SQLInteger): Pointer;
function GetSQLLenAttribute(AAttr: SQLInteger): SQLLen;
function GetSQLULenAttribute(AAttr: SQLInteger): SQLULen;
function GetPSQLULenAttribute(AAttr: SQLInteger): PSQLULen;
procedure SetAttribute(AAttr: SQLInteger; ApValue: SQLPointer; AType: SQLInteger); virtual;
procedure SetPtrAttribute(AAttr: SQLInteger; AValue: Pointer);
procedure SetCharAttribute(AAttr: SQLInteger; const AValue: String);
procedure SetIntAttribute(AAttr: SQLInteger; AValue: SQLInteger);
procedure SetPUIntAttribute(AAttr: SQLInteger; AValue: PSQLUInteger);
procedure SetPUSmIntAttribute(AAttr: SQLInteger; AValue: PSQLUSmallint);
procedure SetUIntAttribute(AAttr: SQLInteger; AValue: SQLUInteger);
procedure SetUSmIntAttribute(AAttr: SQLInteger; AValue: SQLUSmallint);
procedure SetSQLLenAttribute(AAttr: SQLInteger; AValue: SQLLen);
procedure SetSQLULenAttribute(AAttr: SQLInteger; AValue: SQLULen);
procedure SetPSQLULenAttribute(AAttr: SQLInteger; AValue: PSQLULen);
procedure AllocHandle;
procedure FreeHandle;
{$IFDEF FireDAC_MONITOR}
procedure Trace(AKind: TFDMoniEventKind; AStep: TFDMoniEventStep;
const AMsg: String; const AArgs: array of const);
property Tracing: Boolean read GetTracing;
{$ENDIF}
procedure FilterServerOuput(AConn: TODBCConnection; AExc: EODBCNativeException);
public
constructor Create;
constructor CreateUsingHandle(AHandle: SQLHandle);
destructor Destroy; override;
procedure Check(AStatus: SQLReturn);
property Handle: SQLHandle read FHandle;
property HandleType: SQLSmallint read FHandleType;
property IgnoreErrors: Boolean read FIgnoreErrors write FIgnoreErrors;
property Lib: TODBCLib read FODBCLib;
property Connection: TODBCConnection read GetConnection;
property Owner: TODBCHandle read FOwner;
property OwningObj: TObject read FOwningObj;
end;
TODBCEnvironment = class(TODBCHandle)
private
function DoDrivers(ADirection: SQLUSmallint; out ADriverDesc: String;
out ADriverAttr: String): Boolean;
function DoDSNs(ADirection: SQLUSmallint; out AServerName: String;
out ADescription: String): Boolean;
protected
procedure GetNonStrAttribute(AAttr: SQLInteger; ApValue: SQLPointer); override;
procedure GetStrAttribute(AAttr: SQLInteger; out AValue: String); override;
procedure SetAttribute(AAttr: SQLInteger; ApValue: SQLPointer; AType: SQLInteger); override;
public
constructor Create(ALib: TODBCLib; AOwningObj: TObject = nil; AODBCVer: SQLUInteger = SQL_OV_ODBC3_80);
constructor CreateUsingHandle(ALib: TODBCLib; AHandle: SQLHEnv; AOwningObj: TObject = nil);
destructor Destroy; override;
function DriverFirst(out ADriverDesc: String; out ADriverAttr: String): Boolean;
function DriverNext(out ADriverDesc: String; out ADriverAttr: String): Boolean;
function DSNFirst(out AServerName: String; out ADescription: String): Boolean;
function DSNNext(out AServerName: String; out ADescription: String): Boolean;
procedure GetDrivers(AList: TStrings; ADecorate: Boolean = False);
procedure GetDSNs(AList: TStrings; AWithDescription: Boolean = False; ADecorate: Boolean = False);
// Properties
// ODBC
property CONNECTION_POOLING: SQLUInteger index SQL_ATTR_CONNECTION_POOLING read GetUIntAttribute write SetUIntAttribute;
property CP_MATCH: SQLUInteger index SQL_ATTR_CP_MATCH read GetUIntAttribute write SetUIntAttribute;
property ODBC_VERSION: SQLUInteger index SQL_ATTR_ODBC_VERSION read GetUIntAttribute write SetUIntAttribute;
property OUTPUT_NTS: SQLInteger index SQL_ATTR_OUTPUT_NTS read GetIntAttribute write SetIntAttribute;
// Data Direct extensions
property APP_UNICODE_TYPE: SQLInteger index SQL_ATTR_APP_UNICODE_TYPE read GetIntAttribute write SetIntAttribute;
end;
TODBCDriverKind = (dkOther, dkSQLSrv, dkSQLNC, dkSQLOdbc, dkFreeTDS, dkSQLSrvOther,
dkDB2, dkMySQL, dkOracleOra, dkOracleMS, dkOracleOther, dkMSAccessJet,
dkMSAccessACE, dkFirebird, dkInterbase, dkSQLAnywhere, dkSQLite, dkPostgreSQL,
dkAdvantage, dkNexusDB, dkSybaseASE, dkInformix, dkPWMicroFocus, dkDBF,
dkSQLBase, dkElevateDB, dkDBISAM, dkSolidDB, dkCache, dkTeradata, dkPervasive,
dkDB2_400, dkQuickBooks);
TODBCConnection = class(TODBCHandle)
private
FEncoder: TFDEncoder;
FInfo: EODBCNativeException;
FOnParseError: TODBCParseErrorEvent;
FOnGetMaxSizes: TODBCGetMaxSizesEvent;
FRdbmsKind: TFDRDBMSKind;
FDriverKind: TODBCDriverKind;
FConnected: Boolean;
FDecimalSepPar: Char;
FDecimalSepCol: Char;
FLastCommandText: String;
FExceptionClass: EODBCNativeExceptionClass;
FTransID: LongWord;
FMaxColumnNameLen: SQLUSmallint;
FDriverVersion: TFDVersion;
FDriverODBCVersion: TFDVersion;
FDriverEnvVersion: TFDVersion;
FMSSQLVariantBinary: Boolean;
{$IFDEF FireDAC_MONITOR}
FTracing: Boolean;
function GetTracing: Boolean;
{$ENDIF}
function GetInfoOptionSmInt(AInfoType: Integer): SQLUSmallint; inline;
function GetInfoOptionUInt(AInfoType: Integer): SQLUInteger; inline;
function GetInfoOptionULen(AInfoType: Integer): SQLULen; inline;
function GetInfoOptionStr(AInfoType: Integer): String; inline;
function GetKeywords: string;
function GetInfoBase(AInfoType: SQLUSmallint;
var AInfoValue: String): SQLReturn;
procedure AfterConnect;
procedure EndTran(AType: SQLSmallint);
function GetIsolation: SQLInteger;
procedure SetIsolation(const AValue: SQLInteger);
protected
procedure GetNonStrAttribute(AAttr: SQLInteger; ApValue: SQLPointer); override;
procedure GetStrAttribute(AAttr: SQLInteger; out AValue: String); override;
procedure SetAttribute(AAttr: SQLInteger; ApValue: SQLPointer; AType: SQLInteger); override;
procedure GetInfo(AInfoType: SQLUSmallint; var AInfoValue: String); overload;
{$IFDEF FireDAC_64}
procedure GetInfo(AInfoType: SQLUSmallint; var AInfoValue: SQLULen); overload;
{$ENDIF}
procedure GetInfo(AInfoType: SQLUSmallint; var AInfoValue: SQLUInteger); overload;
procedure GetInfo(AInfoType: SQLUSmallint; var AInfoValue: SQLUSmallint); overload;
procedure ClearInfo;
public
constructor Create(AOwner: TODBCEnvironment; AOwningObj: TObject = nil);
constructor CreateUsingHandle(AOwner: TODBCEnvironment; AHandle: SQLHDbc;
AOwningObj: TObject = nil);
destructor Destroy; override;
function DriverConnect(const AConnString: String;
ADriverCompletion: SQLUSmallint; AParentWnd: SQLHWnd): String;
function Connect(const AConnString: String): String;
procedure Disconnect;
function GetFunctions(AFuncID: SQLUSmallint): SQLUSmallint;
function EncodeName(const ACat, ASch, AObj: String): String;
procedure ListServers(const AConnString: String; AList: TStrings);
procedure Commit;
procedure Rollback;
procedure StartTransaction;
// RW
property RdbmsKind: TFDRDBMSKind read FRdbmsKind write FRdbmsKind;
property DecimalSepCol: Char read FDecimalSepCol write FDecimalSepCol;
property DecimalSepPar: Char read FDecimalSepPar write FDecimalSepPar;
property MSSQLVariantBinary: Boolean read FMSSQLVariantBinary write FMSSQLVariantBinary;
property TransID: LongWord read FTransID write FTransID;
property ExceptionClass: EODBCNativeExceptionClass read FExceptionClass write FExceptionClass;
property Info: EODBCNativeException read FInfo write FInfo;
{$IFDEF FireDAC_MONITOR}
property Tracing: Boolean read GetTracing write FTracing;
{$ENDIF}
// RO
property Encoder: TFDEncoder read FEncoder;
property Connected: Boolean read FConnected;
property LastCommandText: String read FLastCommandText;
property DriverKind: TODBCDriverKind read FDriverKind;
property DriverVersion: TFDVersion read FDriverVersion;
property DriverODBCVersion: TFDVersion read FDriverODBCVersion;
property DriverEnvVersion: TFDVersion read FDriverEnvVersion;
// ODBC attributes ----------
property ACCESS_MODE: SQLUInteger index SQL_ATTR_ACCESS_MODE read GetUIntAttribute write SetUIntAttribute;
property AUTOCOMMIT: SQLUInteger index SQL_ATTR_AUTOCOMMIT read GetUIntAttribute write SetUIntAttribute;
property CONCURRENCY: SQLInteger index SQL_CONCURRENCY read GetIntAttribute write SetIntAttribute;
property CURRENT_CATALOG: string index SQL_ATTR_CURRENT_CATALOG read GetCharAttribute write SetCharAttribute;
property CURSOR_TYPE: SQLInteger index SQL_CURSOR_TYPE read GetIntAttribute write SetIntAttribute;
property LOGIN_TIMEOUT: SQLUInteger index SQL_ATTR_LOGIN_TIMEOUT read GetUIntAttribute write SetUIntAttribute;
property TXN_ISOLATION: SQLInteger read GetIsolation write SetIsolation;
// MSSQL ----------
property SS_PRESERVE_CURSORS: SQLUInteger index SQL_COPT_SS_PRESERVE_CURSORS read GetUIntAttribute write SetUIntAttribute;
property SS_OLDPWD: string index SQL_COPT_SS_OLDPWD read GetCharAttribute write SetCharAttribute;
property SS_BROWSE_CONNECT: SQLUInteger index SQL_COPT_SS_BROWSE_CONNECT read GetUIntAttribute write SetUIntAttribute;
// ASA ----------
property REGISTER_MESSAGE_CALLBACK: Pointer index SA_REGISTER_MESSAGE_CALLBACK read GetPtrAttribute write SetPtrAttribute;
// DB2 ----------
property LONGDATA_COMPAT: SQLUSmallint index SQL_ATTR_LONGDATA_COMPAT read GetUSmIntAttribute write SetUSmIntAttribute;
property MAPCHAR: SQLUSmallint index SQL_ATTR_MAPCHAR read GetUSmIntAttribute write SetUSmIntAttribute;
property DESCRIBE_OUTPUT_LEVEL: Integer index SQL_ATTR_DESCRIBE_OUTPUT_LEVEL read GetIntAttribute write SetIntAttribute;
property USE_TRUSTED_CONTEXT: SQLUInteger index SQL_ATTR_USE_TRUSTED_CONTEXT read GetUIntAttribute write SetUIntAttribute;
// Informix ----------
property INFX_LO_AUTOMATIC: SQLUInteger index SQL_INFX_ATTR_LO_AUTOMATIC read GetUIntAttribute write SetUIntAttribute;
property INFX_ODBC_TYPES_ONLY: SQLUInteger index SQL_INFX_ATTR_ODBC_TYPES_ONLY read GetUIntAttribute write SetUIntAttribute;
property INFX_DEFAULT_UDT_FETCH_TYPE: SQLUInteger index SQL_INFX_ATTR_DEFAULT_UDT_FETCH_TYPE read GetUIntAttribute write SetUIntAttribute;
property INFX_IDSISAMERRMSG: SQLUInteger index SQL_INFX_ATTR_IDSISAMERRMSG read GetUIntAttribute write SetUIntAttribute;
// ODBC info ----------
property CATALOG_USAGE: SQLUInteger index SQL_CATALOG_USAGE read GetInfoOptionUInt;
property CATALOG_NAME_SEPARATOR: String index SQL_CATALOG_NAME_SEPARATOR read GetInfoOptionStr;
property CATALOG_LOCATION: SQLUSmallint index SQL_CATALOG_LOCATION read GetInfoOptionSmInt;
property CATALOG_TERM: String index SQL_CATALOG_TERM read GetInfoOptionStr;
property DRIVER_HENV: SQLULen index SQL_DRIVER_HENV read GetInfoOptionULen;
property FILE_USAGE: SQLUSmallint index SQL_FILE_USAGE read GetInfoOptionSmInt;
property GETDATA_EXTENSIONS: SQLUInteger index SQL_GETDATA_EXTENSIONS read GetInfoOptionUInt;
property IDENTIFIER_CASE: SQLUSmallint index SQL_IDENTIFIER_CASE read GetInfoOptionSmInt;
property IDENTIFIER_QUOTE_CHAR: string index SQL_IDENTIFIER_QUOTE_CHAR read GetInfoOptionStr;
property QUOTED_IDENTIFIER_CASE: SQLUSmallint index SQL_QUOTED_IDENTIFIER_CASE read GetInfoOptionSmInt;
property MAX_CATALOG_NAME_LEN: SQLUSmallint index SQL_MAX_CATALOG_NAME_LEN read GetInfoOptionSmInt;
property MAX_SCHEMA_NAME_LEN: SQLUSmallint index SQL_MAX_SCHEMA_NAME_LEN read GetInfoOptionSmInt;
property MAX_TABLE_NAME_LEN: SQLUSmallint index SQL_MAX_TABLE_NAME_LEN read GetInfoOptionSmInt;
// Renamed from MAX_COLUMN_NAME_LEN to MAX_COL_NAME_LEN to avoid conflict with C++Builder
// with MAX_COLUMN_NAME_LEN defined in shlobj.h
property MAX_COL_NAME_LEN: SQLUSmallint read FMaxColumnNameLen;
property MAX_CONCURRENT_ACTIVITIES: SQLUSmallint index SQL_MAX_CONCURRENT_ACTIVITIES read GetInfoOptionSmInt;
property MAX_IDENTIFIER_LEN: SQLUSmallint index SQL_MAX_IDENTIFIER_LEN read GetInfoOptionSmInt;
property MAX_ROW_SIZE: SQLUSmallint index SQL_MAX_ROW_SIZE read GetInfoOptionSmInt;
property MULTIPLE_ACTIVE_TXN: String index SQL_MULTIPLE_ACTIVE_TXN read GetInfoOptionStr;
property SCHEMA_USAGE: SQLUInteger index SQL_SCHEMA_USAGE read GetInfoOptionUInt;
property TXN_CAPABLE: SQLUSmallint index SQL_TXN_CAPABLE read GetInfoOptionSmInt;
property TXN_ISOLATION_OPTION: SQLUInteger index SQL_TXN_ISOLATION_OPTION read GetInfoOptionUInt;
property DM_VER: string index SQL_DM_VER read GetInfoOptionStr;
property DM_ODBC_VER: string index SQL_ODBC_VER read GetInfoOptionStr;
property DBMS_NAME: string index SQL_DBMS_NAME read GetInfoOptionStr;
property DBMS_VER: string index SQL_DBMS_VER read GetInfoOptionStr;
property DRIVER_NAME: string index SQL_DRIVER_NAME read GetInfoOptionStr;
property DRIVER_VER: string index SQL_DRIVER_VER read GetInfoOptionStr;
property DRIVER_ODBC_VER: string index SQL_DRIVER_ODBC_VER read GetInfoOptionStr;
property INTERFACE_CONFORMANCE: SQLUInteger index SQL_ODBC_INTERFACE_CONFORMANCE read GetInfoOptionUInt;
property API_CONFORMANCE: SQLUInteger index SQL_ODBC_API_CONFORMANCE read GetInfoOptionUInt;
property PARAM_ARRAY_ROW_COUNTS: SQLUInteger index SQL_PARAM_ARRAY_ROW_COUNTS read GetInfoOptionUInt;
property PARAM_ARRAY_SELECTS: SQLUInteger index SQL_PARAM_ARRAY_SELECTS read GetInfoOptionUInt;
property KEYWORDS: string read GetKeywords;
property USER_NAME: string index SQL_USER_NAME read GetInfoOptionStr;
property DATABASE_NAME: string index SQL_DATABASE_NAME read GetInfoOptionStr;
property CURSOR_COMMIT_BEHAVIOR: SQLUSmallint index SQL_CURSOR_COMMIT_BEHAVIOR read GetInfoOptionSmInt;
property CURSOR_ROLLBACK_BEHAVIOR: SQLUSmallint index SQL_CURSOR_ROLLBACK_BEHAVIOR read GetInfoOptionSmInt;
property NULL_COLLATION: SQLUSmallint index SQL_NULL_COLLATION read GetInfoOptionSmInt;
// Events
property OnParseError: TODBCParseErrorEvent read FOnParseError write FOnParseError;
property OnGetMaxSizes: TODBCGetMaxSizesEvent read FOnGetMaxSizes write FOnGetMaxSizes;
end;
TODBCSelectItem = class(TObject)
private
FColumnSize: SQLULen;
FName: string;
FNullable: SQLSmallint;
FPosition: SQLSmallint;
FScale: SQLSmallint;
FSQLDataType: SQLSmallint;
FStmt: TODBCStatementBase;
function GetStrAttr(AIndex: Integer): String;
function GetIntAttr(AIndex: Integer): SQLInteger;
function GetIntAttrSilent(AIndex: Integer): SQLInteger;
function GetSmallintAttr(AIndex: Integer): SQLSmallint;
function GetSmallintAttrSilent(AIndex: Integer): SQLSmallint;
function GetIsFixedLen: Boolean;
function GetROWVER: SQLLen;
public
constructor Create(AOwner: TODBCStatementBase; AColNum: SQLSmallint);
property AUTO_UNIQUE_VALUE: SQLInteger index SQL_DESC_AUTO_UNIQUE_VALUE read GetIntAttr;
property ColumnSize: SQLULen read FColumnSize;
property FIXED_PREC_SCALE: SQLInteger index SQL_DESC_FIXED_PREC_SCALE read GetIntAttr;
property IsFixedLen: Boolean read GetIsFixedLen;
property Name: String read FName;
property NULLABLE: SQLSmallint read FNullable;
property Position: SQLSmallint read FPosition;
property ROWVER: SQLLen read GetROWVER;
property Scale: SQLSmallint read FScale;
property SEARCHABLE: SQLInteger index SQL_DESC_SEARCHABLE read GetIntAttr;
property SQLDataType: SQLSmallint read FSQLDataType;
property UNSIGNED: SQLInteger index SQL_DESC_UNSIGNED read GetIntAttr;
property UPDATABLE: SQLInteger index SQL_DESC_UPDATABLE read GetIntAttr;
property BASE_CATALOG_NAME: String index SQL_DESC_CATALOG_NAME read GetStrAttr;
property BASE_SCHEMA_NAME: String index SQL_DESC_SCHEMA_NAME read GetStrAttr;
property BASE_TABLE_NAME: String index SQL_DESC_BASE_TABLE_NAME read GetStrAttr;
property BASE_COLUMN_NAME: String index SQL_DESC_BASE_COLUMN_NAME read GetStrAttr;
property DATETIME_INTERVAL_PRECISION: SQLInteger index SQL_DESC_DATETIME_INTERVAL_PRECISION read GetIntAttrSilent;
property DATETIME_INTERVAL_CODE: SQLSmallint index SQL_DESC_DATETIME_INTERVAL_CODE read GetSmallintAttrSilent;
property PRECISION: SQLSmallint index SQL_DESC_PRECISION read GetSmallintAttr;
property TYPE_NAME: String index SQL_DESC_TYPE_NAME read GetStrAttr;
// MSSQL ----------
// MSSQL 2005 & XML
property XML_SCHEMACOLLECTION_CATALOG_NAME: String index SQL_CA_SS_XML_SCHEMACOLLECTION_CATALOG_NAME read GetStrAttr;
property XML_SCHEMACOLLECTION_SCHEMA_NAME: String index SQL_CA_SS_XML_SCHEMACOLLECTION_SCHEMA_NAME read GetStrAttr;
property XML_SCHEMACOLLECTION_NAME: String index SQL_CA_SS_XML_SCHEMACOLLECTION_NAME read GetStrAttr;
// MSSQL 2005 & UDT
property UDT_CATALOG_NAME: String index SQL_CA_SS_UDT_CATALOG_NAME read GetStrAttr;
property UDT_SCHEMA_NAME: String index SQL_CA_SS_UDT_SCHEMA_NAME read GetStrAttr;
property UDT_TYPE_NAME: String index SQL_CA_SS_UDT_TYPE_NAME read GetStrAttr;
property UDT_ASSEMBLY_TYPE_NAME: String index SQL_CA_SS_UDT_ASSEMBLY_TYPE_NAME read GetStrAttr;
end;
TODBCVariable = class(TObject)
private
FCDataType: SQLSmallint;
FColumnSize: SQLULen;
FDataSize: SQLLen;
FLastDataSize: SQLLen;
FLocalBuffer: SQLPointer;
FLocalBufIndicator: PSQLLen;
FParamType: SQLSmallint;
FPosition: SQLSmallint;
FName: String;
FScale: SQLInteger;
FSQLDataType: SQLSmallint;
FCVariantSbType: SQLSmallint;
[weak] FList: TODBCVariableList;
FForceLongData: Boolean;
FLongData: Boolean;
FBinded: Boolean;
FStreamed: Boolean;
FFlagsUpdated: Boolean;
FForceLateBinding: Boolean;
FLateBinding: Boolean;
FIsParameter: Boolean;
FIsCurrency: Boolean;
FMSAccBoolean: Boolean;
FMSSQLVariantBinary: Boolean;
FDataReader: IUnknown;
{$IFDEF FireDAC_MONITOR}
FDumpLabel: String;
{$ENDIF}
function GetConnection: TODBCConnection; inline;
function GetStatement: TODBCStatementBase; inline;
function GetDumpLabel: String;
function CalcDataSize(AColumnSize: SQLULen): SQLLen;
procedure VarTypeUnsup(ACType: SQLSmallint);
procedure SetCDataType(const AValue: SQLSmallint);
procedure SetDataSize(const AValue: SQLLen);
procedure SetSQLDataType(const AValue: SQLSmallint);
procedure SetForceLongData(const AValue: Boolean);
procedure SetForceLateBinding(const AValue: Boolean);
function AllocLongData(AIndex: SQLULen; ASize: SQLLen): PSQLPointer;
procedure FreeLongData(AIndex: SQLULen);
function GetAsStrings(AIndex: SQLULen): String;
procedure SetColumnSize(const AValue: SQLULen);
procedure SetBindAttributes(ADescKind: SQLInteger);
protected
function GetDataInd(AIndex: SQLULen; out ApData: SQLPointer;
out ApInd: PSQLLen): PSQLPointer;
function GetDataPtr(AIndex: SQLULen; out ApData: SQLPointer;
out ASize: SQLLen; out ApInd: PSQLLen): PSQLPointer;
procedure InternalBind; virtual; abstract;
function GetDecimalSeparator: Char; virtual; abstract;
class function GetDescriptorType: SQLSmallint; virtual; abstract;
property LocalBuffer: SQLPointer read FLocalBuffer write FLocalBuffer;
property LocalBufIndicator: PSQLLen read FLocalBufIndicator
write FLocalBufIndicator;
public
constructor Create;
destructor Destroy; override;
procedure UpdateFlags;
procedure ResetFlagsUpdated;
procedure Bind;
function GetData(AIndex: SQLULen; var ApData: SQLPointer;
var ASize: SQLLen; AByRef: Boolean = False): Boolean;
procedure SetData(AIndex: SQLULen; ApData: SQLPointer;
ASize: SQLLen);
procedure SetDataReader(AIndex: SQLULen; ApData: SQLPointer);
{$IFDEF FireDAC_MONITOR}
function DumpValue(AIndex: SQLULen; var ASize: SQLLen): String; overload;
function DumpValue(AIndex: SQLULen): String; overload;
function DumpCDataType: String;
function DumpParamType: String;
{$ENDIF}
// properties
// RO
property Connection: TODBCConnection read GetConnection;
property Statement: TODBCStatementBase read GetStatement;
property Binded: Boolean read FBinded;
property IsParameter: Boolean read FIsParameter;
property ParamType: SQLSmallint read FParamType;
property LongData: Boolean read FLongData;
property LateBinding: Boolean read FLateBinding;
property DecimalSeparator: Char read GetDecimalSeparator;
property DescriptorType: SQLSmallint read GetDescriptorType;
property IsCurrency: Boolean read FIsCurrency;
property AsStrings[AIndex: SQLULen]: String read GetAsStrings;
property DataReader: IUnknown read FDataReader;
// RW
property SQLDataType: SQLSmallint read FSQLDataType write SetSQLDataType;
property CDataType: SQLSmallint read FCDataType write SetCDataType;
property DataSize: SQLLen read FDataSize write SetDataSize;
property ColumnSize: SQLULen read FColumnSize write SetColumnSize;
property Scale: SQLInteger read FScale write FScale;
property CVariantSbType: SQLSmallint read FCVariantSbType write FCVariantSbType;
property Position: SQLSmallint read FPosition write FPosition;
property ForceLongData: Boolean read FForceLongData write SetForceLongData;
property ForceLateBinding: Boolean read FForceLateBinding write SetForceLateBinding;
property Streamed: Boolean read FStreamed write FStreamed;
property MSAccBoolean: Boolean read FMSAccBoolean write FMSAccBoolean;
property MSSQLVariantBinary: Boolean read FMSSQLVariantBinary write FMSSQLVariantBinary;
property Name: String read FName write FName;
{$IFDEF FireDAC_MONITOR}
property DumpLabel: String read GetDumpLabel write FDumpLabel;
{$ENDIF}
end;
TODBCParameter = class(TODBCVariable)
private
FColumnList: TODBCVariableList;
FDataTypeName: String;
procedure SetParamType(const AValue: SQLSmallint);
function GetColumnList: TODBCVariableList;
protected
procedure InternalBind; override;
function GetDecimalSeparator: Char; override;
class function GetDescriptorType: SQLSmallint; override;
public
constructor Create;
destructor Destroy; override;
property ParamType write SetParamType;
property ColumnList: TODBCVariableList read GetColumnList;
property DataTypeName: String read FDataTypeName write FDataTypeName;
end;
TODBCLongDataStream = class(TStream)
private
FParam: TODBCParameter;
FMode: TFDStreamMode;
FPosition: SQLLen;
FState: Integer;
FSize: SQLLen;
FModified: Boolean;
procedure CheckMode(AMode: TFDStreamMode; const AMsg: String);
function GetStmt: TODBCCommandStatement;
protected
function GetSize: Int64; override;
public
constructor Create(AParam: TODBCParameter; AMode: TFDStreamMode);
function Read(var Buffer; Count: Longint): Longint; override;
function Write(const Buffer; Count: Longint): Longint; override;
function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override;
procedure Flush;
property Param: TODBCParameter read FParam;
property Stmt: TODBCCommandStatement read GetStmt;
end;
TODBCColumn = class(TODBCVariable)
protected
procedure InternalBind; override;
function GetDecimalSeparator: Char; override;
class function GetDescriptorType: SQLSmallint; override;
public
constructor Create;
end;
TODBCVariableList = class(TObject)
private
FList: TFDObjList;
[weak] FOwner: TODBCStatementBase;
FParameters: Boolean;
FBuffer: TODBCPageBuffer;
FHasLateBindedVars: Boolean;
FChildList: Boolean;
function GetCount: Integer;
function GetItems(AIndex: Integer): TODBCVariable;
procedure Rebind(AFixedLenOnly: Boolean = False);
procedure UpdateHasLateBindedVars;
public
constructor Create(AOwner: TODBCStatementBase; AParams, AChildList: Boolean);
destructor Destroy; override;
function Add(AVar: TODBCVariable): TODBCVariable;
procedure Bind(ARowCount: SQLULen; AFixedLenOnly: Boolean);
function FindByToken(ApToken: SQLPointer): TODBCVariable;
procedure Clear;
procedure ResetDataReaders;
property Count: Integer read GetCount;
property Items[Index: Integer]: TODBCVariable read GetItems; default;
property Owner: TODBCStatementBase read FOwner;
property Parameters: Boolean read FParameters;
property HasLateBindedVars: Boolean read FHasLateBindedVars;
property ChildList: Boolean read FChildList;
end;
TODBCPageBuffer = class(TObject)
private
FIsAllocated: Boolean;
FRowCount: SQLULen;
FRowsProcessed: SQLULen;
FRowStatusArr: array of SQLUSmallint;
FRowOperationArr: array of SQLUSmallint;
FVariableList: TODBCVariableList;
FShifted: SQLLen;
function GetPageSize: SQLULen;
function GetRowSize: SQLULen;
function GetRowStatusArr(AIndex: SQLULen): SQLUSmallint;
function GetRowOperationArr(AIndex: SQLULen): SQLUSmallint;
protected
procedure SetStmtAttributes;
procedure AllocBuffers;
procedure FreeBuffers;
procedure GetDataPtr(AVar: TODBCVariable; AIndex: SQLULen;
out ApData: SQLPointer; out ApInd: PSQLLen);
procedure ShiftBuffersPtr(ARowCount: SQLLen);
procedure UnShift;
procedure SetOperationRange(ARowCount, AOffset: SQLULen);
public
constructor Create(AVarList: TODBCVariableList);
destructor Destroy; override;
property Shifted: SQLLen read FShifted;
property PageSize: SQLULen read GetPageSize;
property RowCount: SQLULen read FRowCount;
property RowSize: SQLULen read GetRowSize;
property RowsProcessed: SQLULen read FRowsProcessed;
property RowStatusArr[AIndex: SQLULen]: SQLUSmallint read GetRowStatusArr;
property RowOperationArr[AIndex: SQLULen]: SQLUSmallint read GetRowOperationArr;
end;
TODBCStatementBase = class(TODBCHandle)
private
FColumnList: TODBCVariableList;
FMaxStringSize: SQLUInteger;
FStrsTrim: Boolean;
FStrsEmpty2Null: Boolean;
FStrsTrim2Len: Boolean;
FExecuted: Boolean;
FNoMoreResults: Boolean;
FResultCols: SQLSmallint;
FPieceBuffLen: SQLInteger;
FMoneySupported: Boolean;
FQueryTimeout: SQLULen;
FRowSetSupported: Boolean;
function GetLongVarPiece(AVar: TODBCVariable; ApData: SQLPointer;
ASize: SQLLen; ApInd: PSQLLen): SQLReturn; overload;
function GetLongVarPiece(AVar: TODBCVariable; AIndex: Integer;
ASize: SQLLen): SQLReturn; overload;
function GetLongVarFinished(ASize: SQLLen; ARet: SQLReturn; AInd: SQLLen): Boolean;
procedure GetLongVar(AVar: TODBCVariable; AIndex: Integer);
procedure FetchLateBindedColumns(AIndex: SQLULen);
function GetCursorName: String;
procedure SetCursorName(const AValue: String);
{$IFDEF FireDAC_MONITOR}
procedure DumpColumns(ARows: SQLULen; AEof: Boolean);
{$ENDIF}
function GetSQLLenDiag(ARecNo, ADiagID: Integer): SQLLen;
function GetIntDiag(ARecNo, ADiagID: Integer): SQLInteger;
function GetStrDiag(ARecNo, ADiagID: Integer): String;
function GetUSmallIntDiag(ARecNo, ADiagID: Integer): SQLUSmallint;
procedure SetQueryTimeout(const AValue: SQLULen);
function GetQueryTimeout: SQLULen;
protected
procedure ColAttributeInt(AColNum, AFieldId: SQLUSmallint;
var AAttr: SQLLen);
procedure ColAttributeIntSilent(AColNum, AFieldId: SQLUSmallint;
var AAttr: SQLLen);
procedure ColAttributeSmallint(AColNum, AFieldId: SQLUSmallint;
var AAttr: SQLSmallint);
procedure ColAttributeSmallintSilent(AColNum, AFieldId: SQLUSmallint;
var AAttr: SQLSmallint);
procedure ColAttributeString(AColNum, AFieldId: SQLUSmallint;
var AAttr: String);
procedure GetNonStrAttribute(AAttr: SQLInteger; ApValue: SQLPointer); override;
procedure GetStrAttribute(AAttr: SQLInteger; out AValue: String); override;
procedure SetAttribute(AAttr: SQLInteger; ApValue: SQLPointer; AType: SQLInteger); override;
public
constructor Create(AOwner: TODBCConnection; AOwningObj: TObject = nil);
destructor Destroy; override;
function NumResultCols: SQLSmallint;
function ResultColsExists: Boolean;
procedure BindColumns(ARowCount: SQLULen);
procedure UnbindColumns;
function AddCol(APos, ASQLType, ACType: SQLSmallint; ALen: SQLULen = MAXINT): TODBCColumn;
function Fetch(ARowCount: SQLLen = SQL_NULL_DATA): SQLULen;
function MoreResults: Boolean;
procedure Cancel;
procedure Close;
procedure Unprepare; virtual;
// properties
property ColumnList: TODBCVariableList read FColumnList;
property Executed: Boolean read FExecuted;
property NoMoreResults: Boolean read FNoMoreResults;
// FireDAC
property MaxStringSize: SQLUInteger read FMaxStringSize write FMaxStringSize;
property StrsTrim: Boolean read FStrsTrim write FStrsTrim;
property StrsEmpty2Null: Boolean read FStrsEmpty2Null write FStrsEmpty2Null;
property StrsTrim2Len: Boolean read FStrsTrim2Len write FStrsTrim2Len;
property PieceBuffLen: SQLInteger read FPieceBuffLen write FPieceBuffLen;
property MoneySupported: Boolean read FMoneySupported write FMoneySupported;
property RowSetSupported: Boolean read FRowSetSupported write FRowSetSupported;
// ODBC ----------
property CURSOR_TYPE: SQLULen index SQL_ATTR_CURSOR_TYPE read GetSQLULenAttribute write SetSQLULenAttribute;
property CURSOR_NAME: String read GetCursorName write SetCursorName;
property CONCURRENCY: SQLULen index SQL_ATTR_CONCURRENCY read GetSQLULenAttribute write SetSQLULenAttribute;
property IMP_PARAM_DESC: SQLPointer index SQL_ATTR_IMP_PARAM_DESC read GetPSQLPAttribute;
property MAX_ROWS: SQLULen index SQL_ATTR_MAX_ROWS read GetSQLULenAttribute write SetSQLULenAttribute;
property NOSCAN: SQLULen index SQL_ATTR_NOSCAN read GetSQLULenAttribute write SetSQLULenAttribute;
property QUERY_TIMEOUT: SQLULen read GetQueryTimeout write SetQueryTimeout;
property ROWS_FETCHED_PTR: PSQLULen index SQL_ATTR_ROWS_FETCHED_PTR read GetPSQLULenAttribute write SetPSQLULenAttribute;
property ROW_ARRAY_SIZE: SQLULen index SQL_ATTR_ROW_ARRAY_SIZE read GetSQLULenAttribute write SetSQLULenAttribute;
property ROW_BIND_TYPE: SQLULen index SQL_ATTR_ROW_BIND_TYPE read GetSQLULenAttribute write SetSQLULenAttribute;
property ROW_STATUS_PTR: PSQLUSmallint index SQL_ATTR_ROW_STATUS_PTR read GetPUSmIntAttribute write SetPUSmIntAttribute;
property ROW_OPERATION_PTR: PSQLUSmallint index SQL_ATTR_ROW_OPERATION_PTR read GetPUSmIntAttribute write SetPUSmIntAttribute;
// MSSQL ----------
property SS_NOCOUNT_STATUS: SQLLen index SQL_SOPT_SS_NOCOUNT_STATUS read GetSQLLenAttribute write SetSQLLenAttribute;
property SS_CURSOR_OPTIONS: SQLLen index SQL_SOPT_SS_CURSOR_OPTIONS read GetSQLLenAttribute write SetSQLLenAttribute;
// MSSQL 2005 & Query Notification
property SS_QUERYNOTIFICATION_TIMEOUT: SQLLen index SQL_SOPT_SS_QUERYNOTIFICATION_TIMEOUT read GetSQLLenAttribute write SetSQLLenAttribute;
property SS_QUERYNOTIFICATION_MSGTEXT: String index SQL_SOPT_SS_QUERYNOTIFICATION_MSGTEXT read GetCharAttribute write SetCharAttribute;
property SS_QUERYNOTIFICATION_OPTIONS: String index SQL_SOPT_SS_QUERYNOTIFICATION_OPTIONS read GetCharAttribute write SetCharAttribute;
// Informix ----------
property INFX_LO_AUTOMATIC: SQLUInteger index SQL_INFX_ATTR_LO_AUTOMATIC read GetUIntAttribute write SetUIntAttribute;
property INFX_ODBC_TYPES_ONLY: SQLUInteger index SQL_INFX_ATTR_ODBC_TYPES_ONLY read GetUIntAttribute write SetUIntAttribute;
property INFX_DEFAULT_UDT_FETCH_TYPE: SQLUInteger index SQL_INFX_ATTR_DEFAULT_UDT_FETCH_TYPE read GetUIntAttribute write SetUIntAttribute;
// Teradata
property TDATA_AGKR: SQLUInteger index SQL_ATTR_AGKR read GetUIntAttribute write SetUIntAttribute;
// Diagnostic ----------
property DIAG_SQLSTATE[ARecNo: Integer]: String index SQL_DIAG_SQLSTATE read GetStrDiag;
property DIAG_ROW_NUMBER[ARecNo: Integer]: SQLLen index SQL_DIAG_ROW_NUMBER read GetSQLLenDiag;
property DIAG_COLUMN_NUMBER[ARecNo: Integer]: SQLInteger index SQL_DIAG_COLUMN_NUMBER read GetIntDiag;
// MSSQL
property DIAG_SS_LINE[ARecNo: Integer]: SQLUSmallint index SQL_DIAG_SS_LINE read GetUSmallIntDiag;
property DIAG_SS_MSGSTATE[ARecNo: Integer]: SQLInteger index SQL_DIAG_SS_MSGSTATE read GetIntDiag;
property DIAG_SS_SEVERITY[ARecNo: Integer]: SQLInteger index SQL_DIAG_SS_SEVERITY read GetIntDiag;
property DIAG_SS_PROCNAME[ARecNo: Integer]: String index SQL_DIAG_SS_PROCNAME read GetStrDiag;
property DIAG_SS_SRVNAME[ARecNo: Integer]: String index SQL_DIAG_SS_SRVNAME read GetStrDiag;
// property DIAG_SS_TABLE_COLUMN_NUMBER[ARecNo: Integer]: SQLInteger index SQL_DIAG_SS_TABLE_COLUMN_NUMBER read GetIntDiag;
// property DIAG_SS_TABLE_ROW_NUMBER[ARecNo: Integer]: SQLInteger index SQL_DIAG_SS_TABLE_ROW_NUMBER read GetIntDiag;
// Informix
property DIAG_INFX_ISAM_ERROR[ARecNo: Integer]: SQLInteger index SQL_DIAG_ISAM_ERROR read GetIntDiag;
end;
TODBCCommandStatement = class(TODBCStatementBase)
private
FParamList: TODBCVariableList;
FParamSetSupported: Boolean;
[weak] FFocusedParam: TODBCParameter;
FFocusedResult: SQLReturn;
procedure PutBlobParam(AParam: TODBCParameter; AIndex: Integer);
procedure PutTableParam(AParam: TODBCParameter; AIndex: Integer; AFirst: Boolean);
procedure PutStreamParam(AParam: TODBCParameter; AIndex: Integer);
function PutLongParams: SQLReturn;
procedure GetStreamParam(AParam: TODBCParameter; AIndex: Integer);
function GetLongParams: SQLReturn;
{$IFDEF FireDAC_MONITOR}
procedure DumpParameters(AInput: Boolean; AOffset, ATimes: Integer);
{$ENDIF}
function GetPARAMSET_SIZE: SQLULen;
procedure SetPARAMSET_SIZE(const AValue: SQLULen);
public
constructor Create(AOwner: TODBCConnection; AOwningObj: TObject = nil);
destructor Destroy; override;
procedure BindParameters(ARowCount: SQLUInteger; AFixedLenOnly: Boolean);
procedure UnbindParameters;
procedure UpdateRowsAffected(var ACount: SQLLen);
procedure Execute(ARowCount, AOffset: SQLUInteger; var ACount: SQLLen;
AExact: Boolean; const AExecDirectCommand: String);
procedure FlushLongData;
procedure Open(ARowCount: SQLUInteger; const AExecDirectCommand: String);
function NumParams: SQLSmallint;
procedure Prepare(const ACommandText: String);
procedure Unprepare; override;
// Properties
// FireDAC ----------
property FocusedParam: TODBCParameter read FFocusedParam;
property FocusedResult: SQLReturn read FFocusedResult;
property ParamList: TODBCVariableList read FParamList;
property ParamSetSupported: Boolean read FParamSetSupported write FParamSetSupported;
// ODBC ----------
property PARAMSET_SIZE: SQLULen read GetPARAMSET_SIZE write SetPARAMSET_SIZE;
property PARAMS_PROCESSED_PTR: PSQLULen index SQL_ATTR_PARAMS_PROCESSED_PTR read GetPSQLULenAttribute write SetPSQLULenAttribute;
property PARAM_BIND_TYPE: SQLULen index SQL_ATTR_PARAM_BIND_TYPE read GetSQLULenAttribute write SetSQLULenAttribute;
property PARAM_STATUS_PTR: PSQLUSmallint index SQL_ATTR_PARAM_STATUS_PTR read GetPUSmIntAttribute write SetPUSmIntAttribute;
property PARAM_OPERATION_PTR: PSQLUSmallint index SQL_ATTR_PARAM_OPERATION_PTR read GetPUSmIntAttribute write SetPUSmIntAttribute;
// DB2 ----------
property PARAMOPT_ATOMIC: SQLInteger index SQL_ATTR_PARAMOPT_ATOMIC read GetIntAttribute write SetIntAttribute;
// MSSQL ----------
property SS_PARAM_FOCUS: SQLUInteger index SQL_SOPT_SS_PARAM_FOCUS read GetUIntAttribute write SetUIntAttribute;
end;
TODBCMetaInfoStatement = class(TODBCStatementBase)
private
FMode: Integer;
FCatalog, FSchema, FObject: String;
FColumn: String;
FFKCatalog, FFKSchema, FFKTable: String;
FIdentifierType: SQLUSmallint;
FUnique: SQLUSmallint;
FTableTypes: String;
public
procedure Columns(const ACatalog, ASchema, ATable, AColumn: String);
procedure TypeColumns(const ACatalog, ASchema, ATable, AColumn: String);
procedure ForeignKeys(const APKCatalog, APKSchema, APKTable, AFKCatalog,
AFKSchema, AFKTable: String);
procedure PrimaryKeys(const ACatalog, ASchema, ATable: String);
procedure Procedures(const ACatalog, ASchema, AProc: String);
procedure ProcedureColumns(const ACatalog, ASchema, AProc, AColumn: String);
procedure SpecialColumns(const ACatalog, ASchema, ATable: String;
AIdentifierType: SQLUSmallint);
procedure Statistics(const ACatalog, ASchema, ATable: String; AUnique: SQLUSmallint);
procedure Tables(const ACatalog, ASchema, ATable, ATableTypes: String);
procedure Catalogs;
procedure Schemas;
procedure Execute;
// MSSQL ----------
property SS_NAME_SCOPE: SQLUInteger index SQL_SOPT_SS_NAME_SCOPE read GetUIntAttribute write SetUIntAttribute;
end;
const
C_DEF_NUM_PREC = 31;
C_DEF_NUM_SCALE = 6;
procedure ODBCNumeric2BCD(const ANum: TSQLNumericRec; out ABcd: TBcd);
procedure ODBCBcd2Numeric(const ABcd: TBcd; out ANum: TSQLNumericRec);
procedure ODBCNumeric2Currency(const ANum: TSQLNumericRec; out ACurr: Currency);
procedure ODBCCurrency2Numeric(ACurr: Currency; out ANum: TSQLNumericRec);
{-------------------------------------------------------------------------------}
implementation
uses
{$IFDEF MSWINDOWS}
Winapi.Windows,
{$ENDIF}
System.SysUtils, System.SyncObjs, Data.SqlTimSt, System.DateUtils, Data.DB,
System.Generics.Collections, System.Types,
FireDAC.Stan.Consts, FireDAC.Stan.SQLTimeInt,
FireDAC.Phys.Intf;
const
CStateUndef = '<undef>';
CErrorItemTextFmt = 'SQL state: %s. Native error: %d. Error message: ' + C_FD_EOL + '%s';
CInfoItemTextFmt = 'SQL state: %s. Native code: %d. Message: ' + C_FD_EOL + '%s';
const
C_RETURNED_STRING_MAXLEN = 1024;
C_DRIVER_DESC_MAXLEN = 255;
C_STRING_ATTR_MAXLEN = 255;
C_DRIVER_ATTR_MAXLEN = 4000;
{$IFDEF FireDAC_MONITOR}
C_BuffSize = 4096;
C_PipeName: String = '\\.\pipe\fdodbc';
{$ENDIF}
var
GODBCLib: TODBCLib = nil;
GODBCLibClients: Integer = 0;
GLock: TCriticalSection = nil;
{-------------------------------------------------------------------------------}
procedure ODBCSetLength(var AStr: String; ALen: Integer);
begin
if ALen <= Length(AStr) then begin
while (ALen > 0) and (AStr[ALen] = #0) do
Dec(ALen);
SetLength(AStr, ALen);
end;
end;
{-------------------------------------------------------------------------------}
{ TFDODBCNativeError }
{-------------------------------------------------------------------------------}
procedure TFDODBCNativeError.Assign(ASrc: TFDDBError);
begin
inherited Assign(ASrc);
if ASrc is TFDODBCNativeError then begin
FSQLState := TFDODBCNativeError(ASrc).FSQLState;
FDiagMessage := TFDODBCNativeError(ASrc).FDiagMessage;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDODBCNativeError.LoadFromStorage(const AStorage: IFDStanStorage);
begin
inherited LoadFromStorage(AStorage);
FSQLState := AStorage.ReadString('SQLState', '');
FDiagMessage := AStorage.ReadString('DiagMessage', '');
end;
{-------------------------------------------------------------------------------}
procedure TFDODBCNativeError.SaveToStorage(const AStorage: IFDStanStorage);
begin
inherited SaveToStorage(AStorage);
AStorage.WriteString('SQLState', SQLState, '');
AStorage.WriteString('DiagMessage', DiagMessage, '');
end;
{-------------------------------------------------------------------------------}
{ EODBCNativeException }
{-------------------------------------------------------------------------------}
constructor EODBCNativeException.Create(AStatus: SQLReturn; AOwner: TODBCHandle);
var
iRecNum: SQLSmallint;
iDiagMesLen: SQLSmallint;
iNativeError: SQLInteger;
sDrv, sSQLState,
sDiagMessage, sRetCode,
sResultMes, sCmd: string;
aDiagMesBuffer: array [0 .. SQL_MAX_MESSAGE_LENGTH] of SQLChar;
eKind: TFDCommandExceptionKind;
oHandle: TODBCHandle;
oConn: TODBCConnection;
iFDCode: Integer;
begin
eKind := ekOther;
iFDCode := er_FD_ODBCGeneral;
case AStatus of
SQL_SUCCESS: sRetCode := 'SQL_SUCCESS';
SQL_SUCCESS_WITH_INFO: sRetCode := 'SQL_SUCCESS_WITH_INFO';
SQL_ERROR: sRetCode := 'SQL_ERROR';
SQL_INVALID_HANDLE: sRetCode := 'SQL_INVALID_HANDLE';
SQL_STILL_EXECUTING: sRetCode := 'SQL_STILL_EXECUTING';
SQL_NEED_DATA: sRetCode := 'SQL_NEED_DATA';
SQL_NO_DATA:
begin
sRetCode := 'SQL_NO_DATA';
eKind := ekNoDataFound;
iFDCode := er_FD_AccExactMismatch;
end;
SQL_PARAM_DATA_AVAILABLE:
begin
sRetCode := 'SQL_PARAM_DATA_AVAILABLE';
eKind := ekTooManyRows;
iFDCode := er_FD_AccExactMismatch;
end;
end;
oConn := AOwner.Connection;
if (oConn <> nil) and oConn.Connected then begin
sDrv := '';
oConn.GetInfoBase(SQL_DRIVER_NAME, sDrv);
sCmd := oConn.LastCommandText;
end
else begin
sDrv := 'CLI';
sCmd := '';
end;
oHandle := AOwner;
while (oHandle <> nil) and (oHandle.Handle = nil) do
oHandle := oHandle.Owner;
inherited Create(iFDCode,
FDExceptionLayers([S_FD_LPhys, S_FD_ODBCId, sDrv]) + ' ' + sRetCode);
if AStatus <> SQL_SUCCESS then begin
SetLength(sSQLState, 5);
iRecNum := 1;
while True do begin
iDiagMesLen := 0;
iNativeError := 0;
if not (oHandle.Lib.SQLGetDiagRec(oHandle.HandleType, oHandle.Handle,
iRecNum, PSQLChar(sSQLState), iNativeError, @aDiagMesBuffer[0],
SQL_MAX_MESSAGE_LENGTH, iDiagMesLen) in [SQL_SUCCESS, SQL_SUCCESS_WITH_INFO]) then
Break;
// Oracle: workaround for bug, when iDiagMesLen is number of bytes instead of characters
if aDiagMesBuffer[iDiagMesLen div SizeOf(SQLChar)] = #0 then
iDiagMesLen := iDiagMesLen div SizeOf(SQLChar);
SetString(sDiagMessage, PChar(@aDiagMesBuffer[0]), iDiagMesLen);
if sSQLState[1] = #0 then
sSQLState := CStateUndef;
if AStatus = SQL_SUCCESS_WITH_INFO then
sResultMes := Format(CInfoItemTextFmt, [sSQLState, iNativeError, sDiagMessage])
else
sResultMes := Format(CErrorItemTextFmt, [sSQLState, iNativeError, sDiagMessage]);
if iRecNum = 1 then
Message := FDExceptionLayers([S_FD_LPhys, S_FD_ODBCId]) + sDiagMessage;
AppendError(oHandle, iRecNum, sSQLState, iNativeError, sDiagMessage,
sResultMes, sCmd, '', eKind, -1, -1);
{$IFDEF FireDAC_MONITOR}
AOwner.Trace(ekError, esProgress, sDiagMessage,
['SQLState', sSQLState, 'NativeError', iNativeError, 'RecNum', iRecNum]);
{$ENDIF}
Inc(iRecNum);
end;
if iRecNum = 1 then
inherited AppendError(iRecNum, AStatus, sRetCode, '', eKind, -1, -1);
end;
end;
{-------------------------------------------------------------------------------}
function EODBCNativeException.AppendError(AHandle: TODBCHandle;
ARecNum: SQLSmallint; const ASQLState: String; ANativeError: SQLInteger;
const ADiagMessage, AResultMessage, ACommandText, AObject: String;
AKind: TFDCommandExceptionKind; ACmdOffset, ARowIndex: Integer): TFDDBError;
var
oStmt: TODBCCommandStatement;
oErr: TFDODBCNativeError;
lPrevIgnoreErrors: Boolean;
iRowNum: SQLInteger;
begin
if AKind = ekOther then
if ASQLState = 'HY008' then
AKind := ekCmdAborted
else if (ASQLState = 'HYT01') or (ASQLState = 'HYT00') then begin
AKind := ekCmdAborted;
FDCode := er_FD_StanTimeout;
end
else if (ASQLState = '08S01') or (ASQLState = '08S02') or
(ASQLState = '08007') or (ASQLState = '08001') or
(ASQLState = '08003') or (ASQLState = '08004') then
AKind := ekServerGone
else if (ASQLState = '07001') or (ASQLState = '07002') then
AKind := ekInvalidParams;
if (AHandle is TODBCCommandStatement) and (ARowIndex = -1) then begin
oStmt := TODBCCommandStatement(AHandle);
lPrevIgnoreErrors := oStmt.IgnoreErrors;
oStmt.IgnoreErrors := True;
try
iRowNum := SQLInteger(oStmt.DIAG_ROW_NUMBER[ARecNum]);
if (iRowNum <> SQL_NO_ROW_NUMBER) and (iRowNum <> SQL_ROW_NUMBER_UNKNOWN) then
ARowIndex := iRowNum - 1
else
ARowIndex := -1;
finally
oStmt.IgnoreErrors := lPrevIgnoreErrors;
end;
if ARowIndex < 0 then
ARowIndex := -1
else if TODBCCommandStatement(AHandle).ParamList.FBuffer <> nil then
Inc(ARowIndex, TODBCCommandStatement(AHandle).ParamList.FBuffer.Shifted);
end;
Result := inherited AppendError(ARecNum, ANativeError, AResultMessage, AObject,
AKind, ACmdOffset, ARowIndex);
oErr := TFDODBCNativeError(Result);
oErr.FSQLState := ASQLState;
oErr.FDiagMessage := ADiagMessage;
end;
{-------------------------------------------------------------------------------}
function EODBCNativeException.GetErrorClass: TFDDBErrorClass;
begin
Result := TFDODBCNativeError;
end;
{-------------------------------------------------------------------------------}
function EODBCNativeException.GetErrors(AIndex: Integer): TFDODBCNativeError;
begin
Result := inherited Errors[AIndex] as TFDODBCNativeError;
end;
{$IFDEF FireDAC_MONITOR}
{-------------------------------------------------------------------------------}
{ TODBCTracer }
{-------------------------------------------------------------------------------}
{$WARNINGS OFF}
constructor TODBCTracer.Create(const AMonitor: IFDMoniClient; ALib: TODBCLib);
begin
{$IFDEF MSWINDOWS}
inherited Create(True);
FreeOnTerminate := True;
FMonitor := AMonitor;
FLib := ALib;
ALib.FTracer := Self;
FEncoder := TFDEncoder.Create(nil);
FEncoder.Encoding := ecANSI;
Resume;
Sleep(200);
Inc(FLockOutput);
try
ALib.TRACEFILE := C_PipeName;
ALib.TRACE := True;
if ALib.TRACE then
ALib.FTracing := True;
finally
Dec(FLockOutput);
end;
{$ELSE}
FDCapabilityNotSupported(nil, [S_FD_LPhys, S_FD_ODBCId]);
{$ENDIF}
end;
{$WARNINGS ON}
{-------------------------------------------------------------------------------}
destructor TODBCTracer.Destroy;
begin
FDFreeAndNil(FEncoder);
FLib.FTracer := nil;
FLib.FTracing := False;
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
{$IFDEF MSWINDOWS}
procedure TODBCTracer.Execute;
var
hPipe: THandle;
dwTotalBytesAvail: DWORD;
dwBytesRead: DWORD;
aBuff: array [0 .. C_BuffSize - 1] of Byte;
sMsg: String;
i, iLen: Cardinal;
pStr: PChar;
pMsg: PChar;
procedure NotifyError;
begin
if not Terminated then
FMonitor.Notify(ekError, esProgress, FLib.OwningObj,
'ODBC tracer failed: ' + FDLastSystemErrorMsg, []);
end;
begin
hPipe := CreateNamedPipe(PChar(C_PipeName), PIPE_ACCESS_INBOUND,
PIPE_TYPE_BYTE or PIPE_READMODE_BYTE or PIPE_WAIT, 1,
C_BuffSize, C_BuffSize, INFINITE, nil);
if hPipe = INVALID_HANDLE_VALUE then begin
NotifyError;
Exit;
end;
if not ConnectNamedPipe(hPipe, nil) then begin
NotifyError;
CloseHandle(hPipe);
Exit;
end;
try
while not Terminated and FMonitor.Tracing do begin
dwTotalBytesAvail := 0;
dwBytesRead := 0;
if not PeekNamedPipe(hPipe, nil, 0, nil, @dwTotalBytesAvail, nil) or
(dwTotalBytesAvail > 0) and
not ReadFile(hPipe, aBuff, C_BuffSize, dwBytesRead, nil) and
(GetLastError <> ERROR_MORE_DATA) then begin
NotifyError;
Terminate;
end
else if (dwTotalBytesAvail > 0) and (dwBytesRead > 0) then begin
if FLockOutput = 0 then begin
pMsg := nil;
iLen := Cardinal(FEncoder.Decode(@aBuff, dwBytesRead, Pointer(pMsg)));
i := 0;
while (i < iLen) and ((pMsg[i] = #13) or (pMsg[i] = #10)) do
Inc(i);
// cut app name, thread id, etc from ODBC trace message
pStr := StrPos(pMsg + i, PChar(#9'ENTER '));
if pStr <> nil then begin
Inc(pStr);
iLen := iLen - i - Cardinal(pStr - (pMsg + i));
end
else begin
pStr := StrPos(pMsg + i, PChar(#9'EXIT '));
if pStr <> nil then begin
Inc(pStr);
iLen := iLen - i - Cardinal(pStr - (pMsg + i));
end
else begin
pStr := pMsg + i;
iLen := iLen - i;
end;
end;
SetString(sMsg, pStr, iLen);
FMonitor.Notify(ekVendor, esProgress, FLib.OwningObj, sMsg, []);
end;
end
else if dwTotalBytesAvail = 0 then
Sleep(1);
end;
finally
FMonitor := nil;
DisconnectNamedPipe(hPipe);
CloseHandle(hPipe);
end;
end;
{$ELSE}
procedure TODBCTracer.Execute;
begin
end;
{$ENDIF}
{$ENDIF}
{-------------------------------------------------------------------------------}
{ TODBCLib }
{-------------------------------------------------------------------------------}
constructor TODBCLib.Create(AOwningObj: TObject = nil);
begin
inherited Create(S_FD_ODBCId, AOwningObj);
{$IFDEF FireDAC_MONITOR}
FTraceClients := TFDObjList.Create;
{$ENDIF}
end;
{-------------------------------------------------------------------------------}
destructor TODBCLib.Destroy;
begin
{$IFDEF FireDAC_MONITOR}
DeactivateTracing(nil);
FDFreeAndNil(FTraceClients);
{$ENDIF}
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
procedure TODBCLib.Load(const AHome, ALib: String);
var
sDllName: String;
begin
if ALib = '' then
sDllName := C_ODBC
else
sDllName := ALib;
if AHome <> '' then
sDllName := FDNormPath(AHome) + sDllName;
inherited Load([sDllName], True);
end;
{-------------------------------------------------------------------------------}
procedure TODBCLib.Unload;
begin
inherited Unload;
if FhCPLib <> 0 then begin
FreeLibrary(FhCPLib);
FhCPLib := 0;
end;
end;
{-------------------------------------------------------------------------------}
class function TODBCLib.Allocate(const AHome, ALib: String; AOwningObj: TObject): TODBCLib;
begin
if GLock <> nil then
GLock.Enter;
try
Inc(GODBCLibClients);
if GODBCLibClients = 1 then begin
GODBCLib := TODBCLib.Create(AOwningObj);
GODBCLib.Load(AHome, ALib);
end;
Result := GODBCLib;
finally
if GLock <> nil then
GLock.Leave;
end;
end;
{-------------------------------------------------------------------------------}
class procedure TODBCLib.Release(ALib: TODBCLib);
begin
if GLock <> nil then
GLock.Enter;
try
if (ALib = GODBCLib) and (GODBCLibClients > 0) then begin
Dec(GODBCLibClients);
if GODBCLibClients = 0 then
FDFreeAndNil(GODBCLib);
end;
finally
if GLock <> nil then
GLock.Leave;
end;
end;
{-------------------------------------------------------------------------------}
function TODBCLib.GetODBCTextProcAddress(const AProcName: String; ARequired: Boolean = True): Pointer;
begin
Result := GetProc(AProcName + 'W', ARequired);
end;
{-------------------------------------------------------------------------------}
function TODBCLib.GetTRACE: Boolean;
var
iStringLen: SQLInteger;
iValue: SQLUInteger;
begin
iStringLen := 0;
SQLGetConnectAttr(nil, SQL_ATTR_TRACE, @iValue, 0, iStringLen);
Result := iValue = SQL_TRUE;
end;
{-------------------------------------------------------------------------------}
function TODBCLib.GetTRACEFILE: string;
var
iStringLen: SQLInteger;
begin
SetLength(Result, SQL_MAX_MESSAGE_LENGTH);
iStringLen := 0;
SQLGetConnectAttr(nil, SQL_ATTR_TRACEFILE, PChar(Result), SQL_MAX_MESSAGE_LENGTH,
iStringLen);
SetLength(Result, iStringLen);
end;
{-------------------------------------------------------------------------------}
procedure TODBCLib.LoadLibrary(const ADLLNames: array of String; ARequired: Boolean);
begin
inherited LoadLibrary(ADLLNames, ARequired);
FhCPLib := SafeLoadLibrary(C_ODBCCP);
end;
{-------------------------------------------------------------------------------}
procedure TODBCLib.LoadEntries;
var
hPrev: THandle;
begin
@SQLAllocHandle := GetProc('SQLAllocHandle');
@SQLBindCol := GetProc('SQLBindCol');
@SQLBindParameter := GetProc('SQLBindParameter');
@SQLCancel := GetProc('SQLCancel');
@SQLColAttribute := GetODBCTextProcAddress('SQLColAttribute');
@SQLColAttributeString := @SQLColAttribute;
@SQLColAttributeInt := @SQLColAttribute;
@SQLColumns := GetODBCTextProcAddress('SQLColumns');
@SQLDataSources := GetODBCTextProcAddress('SQLDataSources', False);
@SQLDescribeCol := GetODBCTextProcAddress('SQLDescribeCol');
@SQLDisconnect := GetProc('SQLDisconnect');
@SQLDescribeParam := GetProc('SQLDescribeParam');
@SQLDriverConnect := GetODBCTextProcAddress('SQLDriverConnect');
@SQLBrowseConnect := GetODBCTextProcAddress('SQLBrowseConnect');
@SQLDrivers := GetODBCTextProcAddress('SQLDrivers', False);
@SQLEndTran := GetProc('SQLEndTran');
@SQLExecDirect := GetODBCTextProcAddress('SQLExecDirect');
@SQLExecute := GetProc('SQLExecute');
@SQLFetch := GetProc('SQLFetch');
@SQLForeignKeys := GetODBCTextProcAddress('SQLForeignKeys');
@SQLFreeHandle := GetProc('SQLFreeHandle');
@SQLFreeStmt := GetProc('SQLFreeStmt');
@SQLGetConnectAttr := GetODBCTextProcAddress('SQLGetConnectAttr');
@SQLGetCursorName := GetODBCTextProcAddress('SQLGetCursorName');
@SQLGetData := GetProc('SQLGetData');
@SQLGetDescField := GetODBCTextProcAddress('SQLGetDescField');
@SQLGetDescRec := GetODBCTextProcAddress('SQLGetDescRec');
@SQLGetDiagRec := GetODBCTextProcAddress('SQLGetDiagRec');
@SQLGetDiagField := GetODBCTextProcAddress('SQLGetDiagField');
@SQLGetEnvAttr := GetProc('SQLGetEnvAttr');
@SQLGetFunctions := GetProc('SQLGetFunctions');
@SQLGetInfo := GetODBCTextProcAddress('SQLGetInfo');
@SQLGetInfoString := @SQLGetInfo;
@SQLGetInfoSmallint := @SQLGetInfo;
@SQLGetInfoInt := @SQLGetInfo;
@SQLGetInfoSQLLen := @SQLGetInfo;
@SQLGetStmtAttr := GetODBCTextProcAddress('SQLGetStmtAttr');
@SQLGetTypeInfo := GetODBCTextProcAddress('SQLGetTypeInfo');
@SQLMoreResults := GetProc('SQLMoreResults');
@SQLNumParams := GetProc('SQLNumParams');
@SQLNumResultCols := GetProc('SQLNumResultCols');
@SQLParamData := GetProc('SQLParamData');
@SQLPrepare := GetODBCTextProcAddress('SQLPrepare');
@SQLPrimaryKeys := GetODBCTextProcAddress('SQLPrimaryKeys');
@SQLProcedureColumns := GetODBCTextProcAddress('SQLProcedureColumns');
@SQLProcedures := GetODBCTextProcAddress('SQLProcedures');
@SQLPutData := GetProc('SQLPutData');
@SQLRowCount := GetProc('SQLRowCount');
@SQLSetConnectAttr := GetODBCTextProcAddress('SQLSetConnectAttr');
@SQLSetCursorName := GetODBCTextProcAddress('SQLSetCursorName');
@SQLSetDescField := GetODBCTextProcAddress('SQLSetDescField');
@SQLSetDescRec := GetProc('SQLSetDescRec');
@SQLSetEnvAttr := GetProc('SQLSetEnvAttr');
@SQLSetPos := GetProc('SQLSetPos');
@SQLSetStmtAttr := GetODBCTextProcAddress('SQLSetStmtAttr');
@SQLSpecialColumns := GetODBCTextProcAddress('SQLSpecialColumns');
@SQLStatistics := GetODBCTextProcAddress('SQLStatistics');
@SQLTablePrivileges := GetODBCTextProcAddress('SQLTablePrivileges');
@SQLTables := GetODBCTextProcAddress('SQLTables');
// ODBCCP
hPrev := FhDLL;
FhDLL := FhCPLib;
try
// Some ODBC managers may not export these entries (eg, Data Direct
// ODBC manager on Linux)
@SQLConfigDataSource := GetODBCTextProcAddress('SQLConfigDataSource' {$IFDEF POSIX}, False {$ENDIF});
@SQLInstallerError := GetODBCTextProcAddress('SQLInstallerError' {$IFDEF POSIX}, False {$ENDIF});
finally
FhDLL := hPrev;
end;
end;
{-------------------------------------------------------------------------------}
procedure TODBCLib.SetTRACE(AValue: Boolean);
begin
SQLSetConnectAttr(nil, SQL_ATTR_TRACE, SQLPointer(NativeUInt(AValue)), SQL_IS_INTEGER);
end;
{-------------------------------------------------------------------------------}
procedure TODBCLib.SetTRACEFILE(const AValue: string);
begin
SQLSetConnectAttr(nil, SQL_ATTR_TRACEFILE, PChar(AValue), SQL_NTS);
end;
{$IFDEF FireDAC_MONITOR}
{-------------------------------------------------------------------------------}
procedure TODBCLib.ActivateTracing(const AMonitor: IFDMoniClient; AClient: TObject);
begin
if GLock <> nil then
GLock.Enter;
try
if FTraceClients.IndexOf(AClient) = -1 then
FTraceClients.Add(AClient);
if (FTraceClients.Count > 0) and (FTracer = nil) then
TODBCTracer.Create(AMonitor, Self);
finally
if GLock <> nil then
GLock.Release;
end;
end;
{-------------------------------------------------------------------------------}
procedure TODBCLib.DeactivateTracing(AClient: TObject);
begin
if GLock <> nil then
GLock.Enter;
try
if AClient = nil then
FTraceClients.Clear
else
FTraceClients.Remove(AClient);
if (FTraceClients.Count = 0) and (FTracer <> nil) then begin
FTracer.Terminate;
TRACE := False;
Sleep(200);
end;
finally
if GLock <> nil then
GLock.Release;
end;
end;
{$ENDIF}
{-------------------------------------------------------------------------------}
class function TODBCLib.DecorateKeyValue(const AValue: String): String;
var
i: Integer;
begin
Result := AValue;
for i := 1 to Length(Result) do
if Pos(Result[i], '[]{}(),;?*=!@') <> 0 then begin
Result := '{' + Result + '}';
Break;
end;
end;
{-------------------------------------------------------------------------------}
{ TODBCHandle }
{-------------------------------------------------------------------------------}
constructor TODBCHandle.Create;
begin
inherited Create;
FOwner := nil;
FHandleType := 0;
FHandle := SQL_NULL_HDBC;
FODBCLib := nil;
FOwnHandle := True;
end;
{-------------------------------------------------------------------------------}
constructor TODBCHandle.CreateUsingHandle(AHandle: SQLHandle);
begin
inherited Create;
FOwner := nil;
FHandleType := 0;
FHandle := AHandle;
FODBCLib := nil;
FOwnHandle := False;
end;
{-------------------------------------------------------------------------------}
destructor TODBCHandle.Destroy;
begin
if FHandle <> SQL_NULL_HANDLE then
FreeHandle;
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
function TODBCHandle.GetConnection: TODBCConnection;
var
oHndl: TODBCHandle;
begin
oHndl := Self;
while (oHndl <> nil) and not (oHndl is TODBCConnection) do
oHndl := oHndl.Owner;
Result := TODBCConnection(oHndl);
end;
{-------------------------------------------------------------------------------}
procedure TODBCHandle.AllocHandle;
var
InputHandle: SQLHandle;
begin
ASSERT(FHandle = nil);
if FOwner <> nil then
InputHandle := FOwner.Handle
else
InputHandle := SQL_NULL_HANDLE;
Check(Lib.SQLAllocHandle(FHandleType, InputHandle, FHandle));
end;
{-------------------------------------------------------------------------------}
procedure TODBCHandle.FilterServerOuput(AConn: TODBCConnection; AExc: EODBCNativeException);
var
i: Integer;
begin
i := 0;
while i <= AExc.ErrorCount - 1 do
if AExc.Errors[i].Kind = ekServerOutput then begin
if AConn.FInfo = nil then
AConn.FInfo := EODBCNativeException.Create(SQL_SUCCESS, Self);
AConn.FInfo.Append(AExc.Errors[i]);
AExc.Remove(AExc.Errors[i]);
end
else
Inc(i);
end;
{-------------------------------------------------------------------------------}
procedure TODBCHandle.ProcessError(AStatus: SQLReturn);
var
oConn: TODBCConnection;
oExc: EODBCNativeException;
begin
FIgnoreErrors := True;
try
oConn := Connection;
case AStatus of
SQL_SUCCESS_WITH_INFO:
if oConn <> nil then begin
oExc := oConn.ExceptionClass.Create(AStatus, Self);
if (oConn.DriverKind in [dkSQLSrv, dkSQLNC, dkSQLOdbc, dkFreeTDS, dkSQLSrvOther]) and (
// MSSQL:
// if "The statement has been terminated" and few error items,
// then most probable batch has been terminated due to errors
(oExc.ErrorCount > 1) and (oExc.Errors[oExc.ErrorCount - 1].ErrorCode = 3621) or
// if severity level is greater than or equal to 11, then it is error
(Self is TODBCStatementBase) and (TODBCStatementBase(Self).DIAG_SS_SEVERITY[1] >= 11)
// if "Duplicate key was ignored", then severity is 16, not 10 as described in BOL
) and not ((oExc.ErrorCount >= 1) and (oExc.Errors[0].ErrorCode = 3604)) then begin
FilterServerOuput(oConn, oExc);
FDException(OwningObj, oExc {$IFDEF FireDAC_Monitor}, oConn.Tracing {$ENDIF});
end
else if (oConn.DriverKind in [dkDB2, dkDB2_400]) and
// DB2:
// SQL0803N One or more values in the INSERT statement, UPDATE statement,
// or foreign key update caused by a DELETE statement are not valid because
// the primary key, unique constraint or unique index identified ....
(oExc.ErrorCount = 1) and (oExc.Errors[0].ErrorCode = -803) then
FDException(OwningObj, oExc {$IFDEF FireDAC_Monitor}, oConn.Tracing {$ENDIF})
else if (oConn.DriverKind = dkInformix) and (oExc.ErrorCount >= 1) and (
// Informix:
// most errors are reported as SQL_SUCCESS_WITH_INFO
// 01 - warning class
(Copy(oExc.Errors[0].SQLState, 1, 2) <> '01') and
// IM - warning class
(Copy(oExc.Errors[0].SQLState, 1, 2) <> 'IM') and
// empty SQL State - real SQL_SUCCESS_WITH_INFO
(oExc.Errors[0].SQLState <> '')) then
FDException(OwningObj, oExc {$IFDEF FireDAC_Monitor}, oConn.Tracing {$ENDIF})
else begin
if oConn.FInfo <> nil then begin
oConn.FInfo.Merge(oExc, oConn.FInfo.ErrorCount);
FDFree(oExc);
end
else
oConn.FInfo := oExc;
end;
end;
SQL_NEED_DATA,
SQL_INVALID_HANDLE,
SQL_STILL_EXECUTING,
SQL_ERROR,
SQL_NO_DATA,
SQL_PARAM_DATA_AVAILABLE:
begin
if oConn <> nil then begin
oExc := oConn.ExceptionClass.Create(AStatus, Self);
FilterServerOuput(oConn, oExc);
end
else
oExc := EODBCNativeException.Create(AStatus, Self);
FDException(OwningObj, oExc
{$IFDEF FireDAC_Monitor}, (oConn <> nil) and oConn.Tracing {$ENDIF});
end;
end;
finally
FIgnoreErrors := False;
end;
end;
{-------------------------------------------------------------------------------}
procedure TODBCHandle.Check(AStatus: SQLReturn);
begin
if (AStatus <> SQL_SUCCESS) and not FIgnoreErrors then
ProcessError(AStatus);
end;
{-------------------------------------------------------------------------------}
procedure TODBCHandle.FreeHandle;
begin
if FOwnHandle then
Check(Lib.SQLFreeHandle(FHandleType, FHandle));
FHandle := SQL_NULL_HANDLE;
end;
{-------------------------------------------------------------------------------}
function TODBCHandle.GetCharAttribute(AAttr: SQLInteger): string;
begin
GetStrAttribute(AAttr, Result);
end;
{-------------------------------------------------------------------------------}
function TODBCHandle.GetIntAttribute(AAttr: SQLInteger): SQLInteger;
begin
GetNonStrAttribute(AAttr, @Result);
end;
{-------------------------------------------------------------------------------}
function TODBCHandle.GetPSQLPAttribute(AAttr: SQLInteger): SQLPointer;
begin
Result := nil;
GetNonStrAttribute(AAttr, @Result);
end;
{-------------------------------------------------------------------------------}
function TODBCHandle.GetPUIntAttribute(AAttr: SQLInteger): PSQLUInteger;
begin
Result := nil;
GetNonStrAttribute(AAttr, Result);
end;
{-------------------------------------------------------------------------------}
function TODBCHandle.GetPUSmIntAttribute(AAttr: SQLInteger): PSQLUSmallint;
begin
Result := nil;
GetNonStrAttribute(AAttr, Result);
end;
{-------------------------------------------------------------------------------}
function TODBCHandle.GetUIntAttribute(AAttr: SQLInteger): SQLUInteger;
begin
GetNonStrAttribute(AAttr, @Result);
end;
{-------------------------------------------------------------------------------}
function TODBCHandle.GetUSmIntAttribute(AAttr: SQLInteger): SQLUSmallint;
begin
GetNonStrAttribute(AAttr, @Result);
end;
{-------------------------------------------------------------------------------}
function TODBCHandle.GetSQLLenAttribute(AAttr: SQLInteger): SQLLen;
begin
GetNonStrAttribute(AAttr, @Result);
end;
{-------------------------------------------------------------------------------}
function TODBCHandle.GetSQLULenAttribute(AAttr: SQLInteger): SQLULen;
begin
GetNonStrAttribute(AAttr, @Result);
end;
{-------------------------------------------------------------------------------}
function TODBCHandle.GetPSQLULenAttribute(AAttr: SQLInteger): PSQLULen;
begin
Result := nil;
GetNonStrAttribute(AAttr, Result);
end;
{-------------------------------------------------------------------------------}
procedure TODBCHandle.GetNonStrAttribute(AAttr: SQLInteger; ApValue: SQLPointer);
begin
ASSERT(False);
end;
{-------------------------------------------------------------------------------}
procedure TODBCHandle.GetStrAttribute(AAttr: SQLInteger; out AValue: String);
begin
ASSERT(False);
end;
{-------------------------------------------------------------------------------}
function TODBCHandle.GetPtrAttribute(AAttr: SQLInteger): Pointer;
begin
Result := nil;
GetNonStrAttribute(AAttr, @Result);
end;
{-------------------------------------------------------------------------------}
procedure TODBCHandle.SetCharAttribute(AAttr: SQLInteger; const AValue: String);
const
C_Null: SQLChar = #0;
var
pCh: PSQLChar;
begin
if AValue = '' then
pCh := @C_Null
else
pCh := PSQLChar(AValue);
SetAttribute(AAttr, pCh, SQL_NTS);
end;
{-------------------------------------------------------------------------------}
procedure TODBCHandle.SetIntAttribute(AAttr: SQLInteger; AValue: SQLInteger);
begin
SetAttribute(AAttr, PSQLInteger(AValue), SQL_IS_INTEGER);
end;
{-------------------------------------------------------------------------------}
procedure TODBCHandle.SetPUIntAttribute(AAttr: SQLInteger; AValue: PSQLUInteger);
begin
SetAttribute(AAttr, AValue, SQL_IS_POINTER);
end;
{-------------------------------------------------------------------------------}
procedure TODBCHandle.SetPUSmIntAttribute(AAttr: SQLInteger; AValue: PSQLUSmallint);
begin
SetAttribute(AAttr, AValue, SQL_IS_POINTER);
end;
{-------------------------------------------------------------------------------}
procedure TODBCHandle.SetUIntAttribute(AAttr: SQLInteger; AValue: SQLUInteger);
begin
SetAttribute(AAttr, PSQLUInteger(AValue), SQL_IS_UINTEGER);
end;
{-------------------------------------------------------------------------------}
procedure TODBCHandle.SetUSmIntAttribute(AAttr: SQLInteger; AValue: SQLUSmallint);
begin
SetAttribute(AAttr, PSQLUSmallint(AValue), SQL_IS_USMALLINT);
end;
{-------------------------------------------------------------------------------}
procedure TODBCHandle.SetSQLLenAttribute(AAttr: SQLInteger; AValue: SQLLen);
begin
SetAttribute(AAttr, PSQLLen(AValue), SQL_IS_INTEGER);
end;
{-------------------------------------------------------------------------------}
procedure TODBCHandle.SetSQLULenAttribute(AAttr: SQLInteger; AValue: SQLULen);
begin
SetAttribute(AAttr, PSQLULen(AValue), SQL_IS_UINTEGER);
end;
{-------------------------------------------------------------------------------}
procedure TODBCHandle.SetPSQLULenAttribute(AAttr: SQLInteger; AValue: PSQLULen);
begin
SetAttribute(AAttr, AValue, SQL_IS_POINTER);
end;
{-------------------------------------------------------------------------------}
procedure TODBCHandle.SetPtrAttribute(AAttr: SQLInteger; AValue: Pointer);
begin
SetAttribute(AAttr, AValue, SQL_IS_POINTER);
end;
{-------------------------------------------------------------------------------}
procedure TODBCHandle.SetAttribute(AAttr: SQLInteger; ApValue: SQLPointer; AType: SQLInteger);
begin
ASSERT(False);
end;
{$IFDEF FireDAC_MONITOR}
{-------------------------------------------------------------------------------}
procedure TODBCHandle.Trace(AKind: TFDMoniEventKind; AStep: TFDMoniEventStep;
const AMsg: String; const AArgs: array of const);
begin
if Tracing then
Lib.FTracer.FMonitor.Notify(AKind, AStep, OwningObj, AMsg, AArgs);
end;
{-------------------------------------------------------------------------------}
function TODBCHandle.GetTracing: Boolean;
begin
Result := (Self <> nil) and Lib.Tracing and (Lib.FTracer <> nil) and
(Lib.FTracer.FMonitor <> nil);
end;
{$ENDIF}
{-------------------------------------------------------------------------------}
{ TODBCEnvironment }
{-------------------------------------------------------------------------------}
constructor TODBCEnvironment.Create(ALib: TODBCLib; AOwningObj: TObject;
AODBCVer: SQLUInteger);
begin
inherited Create;
FOwningObj := AOwningObj;
FHandleType := SQL_HANDLE_ENV;
FODBCLib := ALib;
AllocHandle;
if AODBCVer = SQL_OV_ODBC3_80 then begin
if Lib.SQLSetEnvAttr(FHandle, SQL_ATTR_ODBC_VERSION,
PSQLUInteger(SQL_OV_ODBC3_80), SQL_IS_UINTEGER) = SQL_ERROR then
ODBC_VERSION := SQL_OV_ODBC3;
end
else
ODBC_VERSION := AODBCVer;
{$IFDEF POSIX}
APP_UNICODE_TYPE := SQL_DD_CP_UTF16;
{$ENDIF}
end;
{-------------------------------------------------------------------------------}
constructor TODBCEnvironment.CreateUsingHandle(ALib: TODBCLib;
AHandle: SQLHEnv; AOwningObj: TObject);
begin
inherited CreateUsingHandle(AHandle);
FOwningObj := AOwningObj;
FHandleType := SQL_HANDLE_ENV;
FODBCLib := ALib;
end;
{-------------------------------------------------------------------------------}
destructor TODBCEnvironment.Destroy;
begin
// Informix: after connection losting releasing ENV handle mai raise exception
IgnoreErrors := True;
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
procedure TODBCEnvironment.GetNonStrAttribute(AAttr: SQLInteger; ApValue: SQLPointer);
var
iStringLen: SQLInteger;
begin
iStringLen := 0;
Check(Lib.SQLGetEnvAttr(FHandle, AAttr, ApValue, 0, iStringLen));
end;
{-------------------------------------------------------------------------------}
procedure TODBCEnvironment.GetStrAttribute(AAttr: SQLInteger; out AValue: String);
begin
FDCapabilityNotSupported(Self, [S_FD_LPhys, S_FD_ODBCId]);
end;
{-------------------------------------------------------------------------------}
procedure TODBCEnvironment.SetAttribute(AAttr: SQLInteger; ApValue: SQLPointer;
AType: SQLInteger);
begin
Check(Lib.SQLSetEnvAttr(FHandle, AAttr, ApValue, 0));
end;
{-------------------------------------------------------------------------------}
function TODBCEnvironment.DoDrivers(ADirection: SQLUSmallint; out ADriverDesc: String;
out ADriverAttr: String): Boolean;
var
iDriverDescLen: SQLSmallint;
iDriverAttrLen: SQLSmallint;
iRet: SQLReturn;
begin
if not Assigned(Lib.SQLDrivers) then begin
Result := False;
Exit;
end;
SetLength(ADriverDesc, C_DRIVER_DESC_MAXLEN);
SetLength(ADriverAttr, C_DRIVER_ATTR_MAXLEN);
iDriverDescLen := 0;
iDriverAttrLen := 0;
iRet := Lib.SQLDrivers(FHandle, ADirection, PSQLChar(ADriverDesc),
C_DRIVER_DESC_MAXLEN, iDriverDescLen, PSQLChar(ADriverAttr),
C_DRIVER_ATTR_MAXLEN, iDriverAttrLen);
if iRet = SQL_NO_DATA then
Result := False
else begin
Check(iRet);
Result := True;
end;
SetLength(ADriverDesc, iDriverDescLen);
SetLength(ADriverAttr, iDriverAttrLen);
end;
{-------------------------------------------------------------------------------}
function TODBCEnvironment.DriverFirst(out ADriverDesc: String;
out ADriverAttr: String): Boolean;
begin
Result := DoDrivers(SQL_FETCH_FIRST, ADriverDesc, ADriverAttr);
end;
{-------------------------------------------------------------------------------}
function TODBCEnvironment.DriverNext(out ADriverDesc: String;
out ADriverAttr: String): Boolean;
begin
Result := DoDrivers(SQL_FETCH_NEXT, ADriverDesc, ADriverAttr);
end;
{-------------------------------------------------------------------------------}
function TODBCEnvironment.DoDSNs(ADirection: SQLUSmallint; out AServerName,
ADescription: String): Boolean;
var
iServerNameLen: SQLSmallint;
iDescriptionLen: SQLSmallint;
iRet: SQLReturn;
begin
if not Assigned(Lib.SQLDataSources) then begin
Result := False;
Exit;
end;
SetLength(AServerName, SQL_MAX_DSN_LENGTH);
SetLength(ADescription, C_DRIVER_DESC_MAXLEN);
iServerNameLen := 0;
iDescriptionLen := 0;
iRet := Lib.SQLDataSources(FHandle, ADirection, PSQLChar(AServerName),
SQL_MAX_DSN_LENGTH, iServerNameLen, PSQLChar(ADescription),
C_DRIVER_DESC_MAXLEN, iDescriptionLen);
if iRet = SQL_NO_DATA then
Result := False
else begin
Check(iRet);
Result := True;
end;
SetLength(AServerName, iServerNameLen);
SetLength(ADescription, iDescriptionLen);
end;
{-------------------------------------------------------------------------------}
function TODBCEnvironment.DSNFirst(out AServerName, ADescription: String): Boolean;
begin
Result := DoDSNs(SQL_FETCH_FIRST, AServerName, ADescription);
end;
{-------------------------------------------------------------------------------}
function TODBCEnvironment.DSNNext(out AServerName, ADescription: String): Boolean;
begin
Result := DoDSNs(SQL_FETCH_NEXT, AServerName, ADescription);
end;
{-------------------------------------------------------------------------------}
procedure TODBCEnvironment.GetDrivers(AList: TStrings; ADecorate: Boolean = False);
var
sDriver, sAttr: String;
oStrs: TFDStringList;
i: Integer;
begin
AList.BeginUpdate;
oStrs := TFDStringList.Create;
try
AList.Clear;
if DriverFirst(sDriver, sAttr) then
repeat
oStrs.Add(sDriver);
until not DriverNext(sDriver, sAttr);
oStrs.Sort;
if ADecorate then
for i := 0 to oStrs.Count - 1 do
oStrs[i] := TODBCLib.DecorateKeyValue(oStrs[i]);
AList.SetStrings(oStrs);
finally
FDFree(oStrs);
AList.EndUpdate;
end;
end;
{-------------------------------------------------------------------------------}
procedure TODBCEnvironment.GetDSNs(AList: TStrings; AWithDescription: Boolean = False;
ADecorate: Boolean = False);
var
sDSN, sDesc: String;
oStrs: TFDStringList;
i: Integer;
begin
AList.BeginUpdate;
oStrs := TFDStringList.Create;
try
AList.Clear;
if DSNFirst(sDSN, sDesc) then
repeat
if AWithDescription then
sDSN := sDSN + '=' + sDesc;
oStrs.Add(sDSN);
until not DSNNext(sDSN, sDesc);
oStrs.Sort;
if ADecorate then
for i := 0 to oStrs.Count - 1 do
oStrs[i] := TODBCLib.DecorateKeyValue(oStrs[i]);
AList.SetStrings(oStrs);
finally
FDFree(oStrs);
AList.EndUpdate;
end;
end;
{-------------------------------------------------------------------------------}
{ TODBCConnection }
{-------------------------------------------------------------------------------}
constructor TODBCConnection.Create(AOwner: TODBCEnvironment; AOwningObj: TObject);
begin
ASSERT(AOwner <> nil);
inherited Create;
FExceptionClass := EODBCNativeException;
FOwner := AOwner;
FOwningObj := AOwningObj;
FHandleType := SQL_HANDLE_DBC;
FODBCLib := FOwner.Lib;
FDecimalSepPar := '.';
FDecimalSepCol := '.';
FEncoder := TFDEncoder.Create(nil);
FEncoder.Encoding := ecANSI;
AllocHandle;
end;
{-------------------------------------------------------------------------------}
constructor TODBCConnection.CreateUsingHandle(AOwner: TODBCEnvironment;
AHandle: SQLHDbc; AOwningObj: TObject);
begin
ASSERT(AOwner <> nil);
inherited CreateUsingHandle(AHandle);
FExceptionClass := EODBCNativeException;
FOwner := AOwner;
FOwningObj := AOwningObj;
FHandleType := SQL_HANDLE_DBC;
FODBCLib := FOwner.Lib;
FDecimalSepPar := '.';
FDecimalSepCol := '.';
FEncoder := TFDEncoder.Create(nil);
FEncoder.Encoding := ecANSI;
AfterConnect;
end;
{-------------------------------------------------------------------------------}
destructor TODBCConnection.Destroy;
begin
// Informix: after connection losting releasing ENV handle mai raise exception
IgnoreErrors := True;
if Connected then
Disconnect;
ClearInfo;
FDFreeAndNil(FEncoder);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
procedure TODBCConnection.ClearInfo;
begin
FDFreeAndNil(FInfo);
end;
{-------------------------------------------------------------------------------}
procedure TODBCConnection.AfterConnect;
var
sDrv, sDbms: string;
iEnvVer: SQLUInteger;
function Match(const AName: String): Boolean;
begin
Result := Copy(sDrv, 1, Length(AName)) = AName;
end;
begin
sDrv := UpperCase(DRIVER_NAME);
sDbms := UpperCase(DBMS_NAME);
FDriverKind := dkOther;
FRdbmsKind := TFDRDBMSKinds.Other;
if Match('SQLSRV') then
FDriverKind := dkSQLSrv
else if Match('SQLNCLI') then
FDriverKind := dkSQLNC
else if Match('MSODBCSQL') or Match('LIBMSODBCSQL') then
FDriverKind := dkSQLOdbc
else if Match('LIBTDSODBC') then
FDriverKind := dkFreeTDS
else if Match('IVSS') or Match('IVMSSS') or Match('PBSS') or
((Copy(sDrv, 1, 3) = 'NTL') and (sDrv[5] = 'M')) then
FDriverKind := dkSQLSrvOther
else if Match('CWBODBC') then
FDriverKind := dkDB2_400
else if Match('DB2CLI') or Match('LIBDB2') or Match('IVDB2') or Match('PBDB2') or
// IBM DB2 ODBC driver has a bug and returns ODBC_VER instead of DRIVER_NAME
(Copy(sDbms, 1, 3) = 'DB2') then
FDriverKind := dkDB2
else if Match('MYODBC') then
FDriverKind := dkMySQL
else if Match('SQORA') then
FDriverKind := dkOracleOra
else if Match('MSORCL') then
FDriverKind := dkOracleMS
else if Match('IVOR') or Match('PBOR') then
FDriverKind := dkOracleOther
else if Match('ODBCJT') and (sDbms = 'ACCESS') then
FDriverKind := dkMSAccessJet
else if Match('ACEODBC') and (sDbms = 'ACCESS') then
FDriverKind := dkMSAccessACE
else if Match('ODBCFB') then
FDriverKind := dkFirebird
else if Match('IB') then
FDriverKind := dkInterbase
else if Match('SQL ANYWHERE') or Match('DBODBC') and (sDbms <> 'DBISAM') or Match('WOD') then
FDriverKind := dkSQLAnywhere
else if Match('SQLITEODBC') then
FDriverKind := dkSQLite
else if Match('PSQLODBC') then
FDriverKind := dkPostgreSQL
else if Match('ADSODBC') then
FDriverKind := dkAdvantage
else if Match('NXODBCDRIVER') then
FDriverKind := dkNexusDB
else if Match('ADAPTIVE SERVER ENTERPRISE') or Match('SYODASE') or Match('SYSYBNT') then
FDriverKind := dkSybaseASE
else if Match('ICLI') then
FDriverKind := dkInformix
else if Match('PWDRMF') then
FDriverKind := dkPWMicroFocus
else if Match('ODBCJT') and (sDbms = 'DBASE') then
FDriverKind := dkDBF
else if Match('SQLBASEODBC') then
FDriverKind := dkSQLBase
else if Match('EDBODBC') then
FDriverKind := dkElevateDB
else if Match('DBODBC') and (sDbms = 'DBISAM') then
FDriverKind := dkDBISAM
else if Match('SOC') or Match('SAC') then
FDriverKind := dkSolidDB
else if Match('CACHEODBC') then
FDriverKind := dkCache
else if Match('TDATA') then
FDriverKind := dkTeradata
else if Match('W3ODBCCI') then
FDriverKind := dkPervasive
else if Match('FQQB') then
FDriverKind := dkQuickBooks;
case DriverKind of
dkSQLSrv,
dkSQLNC,
dkSQLOdbc,
dkFreeTDS,
dkSQLSrvOther:
FRdbmsKind := TFDRDBMSKinds.MSSQL;
dkDB2,
dkDB2_400:
FRdbmsKind := TFDRDBMSKinds.DB2;
dkMySQL:
FRdbmsKind := TFDRDBMSKinds.MySQL;
dkOracleOra,
dkOracleMS,
dkOracleOther:
FRdbmsKind := TFDRDBMSKinds.Oracle;
dkMSAccessJet,
dkMSAccessACE:
FRdbmsKind := TFDRDBMSKinds.MSAccess;
dkInterbase:
FRdbmsKind := TFDRDBMSKinds.Interbase;
dkFirebird:
FRdbmsKind := TFDRDBMSKinds.Firebird;
dkSQLAnywhere:
FRdbmsKind := TFDRDBMSKinds.SQLAnywhere;
dkSQLite:
FRdbmsKind := TFDRDBMSKinds.SQLite;
dkPostgreSQL:
FRdbmsKind := TFDRDBMSKinds.PostgreSQL;
dkAdvantage:
FRdbmsKind := TFDRDBMSKinds.Advantage;
dkNexusDB:
FRdbmsKind := TFDRDBMSKinds.NexusDB;
dkInformix:
FRdbmsKind := TFDRDBMSKinds.Informix;
dkTeradata:
FRdbmsKind := TFDRDBMSKinds.Teradata;
end;
FMaxColumnNameLen := GetInfoOptionSmInt(SQL_MAX_COLUMN_NAME_LEN);
FDriverVersion := FDVerStr2Int(DRIVER_VER);
FDriverODBCVersion := FDVerStr2Int(DRIVER_ODBC_VER);
iEnvVer := TODBCEnvironment(Owner).ODBC_VERSION;
if (iEnvVer >= SQL_OV_ODBC3_80) and (FDriverODBCVersion >= ovODBC38) then
FDriverEnvVersion := ovODBC38
else if (iEnvVer >= SQL_OV_ODBC3) and (FDriverODBCVersion >= ovODBC3) then
FDriverEnvVersion := ovODBC3
else
FDriverEnvVersion := ovODBC2;
end;
{-------------------------------------------------------------------------------}
function TODBCConnection.Connect(const AConnString: String): String;
begin
Result := DriverConnect(AConnString, SQL_DRIVER_NOPROMPT, 0);
end;
{-------------------------------------------------------------------------------}
function TODBCConnection.DriverConnect(const AConnString: String;
ADriverCompletion: SQLUSmallint; AParentWnd: SQLHWnd): String;
var
iOutConnStrLen: SQLSmallint;
{$IFDEF FireDAC_MONITOR}
s: String;
i1, i2: Integer;
{$ENDIF}
begin
{$IFDEF FireDAC_MONITOR}
if Tracing then begin
s := AConnString;
i1 := Pos('PWD=', UpperCase(s));
if i1 <> 0 then begin
i2 := Pos(';', s, i1);
if i2 = 0 then
i2 := Length(s) + 1;
Inc(i1, 4);
while i1 < i2 do begin
s[i1] := '*';
Inc(i1);
end;
end;
Trace(ekVendor, esProgress, 'SQLDriverConnect', ['szConnStr', s]);
end;
{$ENDIF}
SetLength(Result, C_RETURNED_STRING_MAXLEN);
FillChar(Result[1], C_RETURNED_STRING_MAXLEN * SizeOf(Char), 0);
iOutConnStrLen := 0;
Check(Lib.SQLDriverConnect(FHandle, AParentWnd, PSQLChar(AConnString), SQL_NTS,
PSQLChar(Result), C_RETURNED_STRING_MAXLEN, iOutConnStrLen, ADriverCompletion));
FConnected := True;
AfterConnect;
ODBCSetLength(Result, iOutConnStrLen);
end;
{-------------------------------------------------------------------------------}
procedure TODBCConnection.Disconnect;
begin
FConnected := False;
Check(Lib.SQLDisconnect(FHandle));
end;
{-------------------------------------------------------------------------------}
procedure TODBCConnection.ListServers(const AConnString: String; AList: TStrings);
var
iOutLen: SQLSmallint;
sOutStr, sSrv: String;
i1, i2, i: Integer;
rFmt: TFDParseFmtSettings;
begin
AList.BeginUpdate;
try
AList.Clear;
SetLength(sOutStr, C_RETURNED_STRING_MAXLEN);
if (Lib.SQLBrowseConnect(Handle, PSQLChar(AConnString), SQL_NTS,
PSQLChar(sOutStr), C_RETURNED_STRING_MAXLEN,
iOutLen)) <> SQL_NEED_DATA then
Exit;
if C_RETURNED_STRING_MAXLEN < iOutLen then begin
SetLength(sOutStr, iOutLen + 1);
if (Lib.SQLBrowseConnect(Handle, PSQLChar(AConnString), SQL_NTS,
PSQLChar(sOutStr), iOutLen + 1,
iOutLen)) <> SQL_NEED_DATA then
Exit;
end;
ODBCSetLength(sOutStr, iOutLen);
i1 := Pos('{', sOutStr);
i2 := Pos('}', sOutStr, i1 + 1);
if (i1 <> 0) and (i2 <> 0) then
sOutStr := Copy(sOutstr, i1 + 1, i2 - i1 - 1);
rFmt.FDelimiter := ',';
rFmt.FQuote := #0;
rFmt.FQuote1 := '{';
rFmt.FQuote2 := '}';
i := 1;
while i <= Length(sOutStr) do begin
sSrv := FDExtractFieldName(sOutStr, i, rFmt);
i1 := Pos(';', sSrv);
if i1 > 0 then
sSrv := Copy(sSrv, 1, i1 - 1);
if AList.IndexOf(sSrv) = -1 then
AList.Add(sSrv);
end;
finally
AList.EndUpdate;
end;
end;
{-------------------------------------------------------------------------------}
function TODBCConnection.GetFunctions(AFuncID: SQLUSmallint): SQLUSmallint;
begin
Result := 0;
Check(Lib.SQLGetFunctions(FHandle, AFuncID, Result));
end;
{-------------------------------------------------------------------------------}
procedure TODBCConnection.GetInfo(AInfoType: SQLUSmallint; var AInfoValue: String);
begin
Check(GetInfoBase(AInfoType, AInfoValue));
end;
{-------------------------------------------------------------------------------}
function TODBCConnection.GetInfoBase(AInfoType: SQLUSmallint; var AInfoValue: String): SQLReturn;
var
iInfoLength: SQLSmallint;
begin
if Length(AInfoValue) < C_RETURNED_STRING_MAXLEN then
SetLength(AInfoValue, C_RETURNED_STRING_MAXLEN);
iInfoLength := 0;
Result := Lib.SQLGetInfoString(FHandle, AInfoType, PSQLChar(AInfoValue),
SQLSmallint(Length(AInfoValue)) * SizeOf(Char), iInfoLength);
ODBCSetLength(AInfoValue, iInfoLength div SizeOf(Char));
end;
{-------------------------------------------------------------------------------}
{$IFDEF FireDAC_64}
procedure TODBCConnection.GetInfo(AInfoType: SQLUSmallint; var AInfoValue: SQLULen);
begin
AInfoValue := 0;
Check(Lib.SQLGetInfoSQLLen(FHandle, AInfoType, AInfoValue, SQLSmallint(SizeOf(AInfoValue)), nil));
end;
{$ENDIF}
{-------------------------------------------------------------------------------}
procedure TODBCConnection.GetInfo(AInfoType: SQLUSmallint; var AInfoValue: SQLUInteger);
begin
AInfoValue := 0;
Check(Lib.SQLGetInfoInt(FHandle, AInfoType, AInfoValue, SQLSmallint(SizeOf(AInfoValue)), nil));
end;
{-------------------------------------------------------------------------------}
procedure TODBCConnection.GetInfo(AInfoType: SQLUSmallint; var AInfoValue: SQLUSmallint);
var
iValue: SQLUInteger;
begin
iValue := 0;
AInfoValue := 0;
Check(Lib.SQLGetInfoInt(FHandle, AInfoType, iValue, SQLSmallint(SizeOf(AInfoValue)), nil));
AInfoValue := SQLUSmallint(iValue);
end;
{-------------------------------------------------------------------------------}
function TODBCConnection.GetInfoOptionSmInt(AInfoType: Integer): SQLUSmallint;
begin
GetInfo(SQLUSmallint(AInfoType), Result);
end;
{-------------------------------------------------------------------------------}
function TODBCConnection.GetInfoOptionUInt(AInfoType: Integer): SQLUInteger;
begin
GetInfo(SQLUSmallint(AInfoType), Result);
end;
{-------------------------------------------------------------------------------}
function TODBCConnection.GetInfoOptionULen(AInfoType: Integer): SQLULen;
begin
GetInfo(SQLUSmallint(AInfoType), Result);
end;
{-------------------------------------------------------------------------------}
function TODBCConnection.GetInfoOptionStr(AInfoType: Integer): string;
begin
GetInfo(SQLUSmallint(AInfoType), Result);
end;
{-------------------------------------------------------------------------------}
function TODBCConnection.GetKeywords: string;
const
C_DefKeywords =
'ABSOLUTE,IS,ACTION,ISOLATION,ADA,JOIN,ADD,KEY,' +
'ALL,LANGUAGE,ALLOCATE,LAST,ALTER,LEADING,AND,LEFT,' +
'ANY,LEVEL,ARE,LIKE,AS,LOCAL,ASC,LOWER,ASSERTION,MATCH,' +
'AT,MAX,AUTHORIZATION,MIN,AVG,MINUTE,BEGIN,MODULE,' +
'BETWEEN,MONTH,BIT,NAMES,BIT_LENGTH,NATIONAL,BOTH,NATURAL,' +
'BY,NCHAR,CASCADE,NEXT,CASCADED,NO,CASE,NONE,CAST,NOT,' +
'CATALOG,NULL,CHAR,NULLIF,CHAR_LENGTH,NUMERIC,' +
'CHARACTER,OCTET_LENGTH,CHARACTER_LENGTH,OF,CHECK,ON,' +
'CLOSE,ONLY,COALESCE,OPEN,COLLATE,OPTION,COLLATION,OR,' +
'COLUMN,ORDER,COMMIT,OUTER,CONNECT,OUTPUT,CONNECTION,OVERLAPS,' +
'CONSTRAINT,PFD,CONSTRAINTS,PARTIAL,CONTINUE,PASCAL,' +
'CONVERT,POSITION,CORRESPONDING,PRECISION,COUNT,PREPARE,' +
'CREATE,PRESERVE,CROSS,PRIMARY,CURRENT,PRIOR,N,' +
'CURRENT_DATE,PRIVILEGES,CURRENT_TIME,PROCEDURE,' +
'CURRENT_TIMESTAMP,PUBLIC,CURRENT_USER,READ,CURSOR,REAL,' +
'DATE,REFERENCES,DAY,RELATIVE,DEALLOCATE,RESTRICT,' +
'DEC,REVOKE,DECIMAL,RIGHT,DECLARE,ROLLBACK,DEFAULT,ROWS,' +
'DEFERRABLE,SCHEMA,DEFERRED,SCROLL,DELETE,SECOND,' +
'DESC,SECTION,DESCRIBE,SELECT,DESCRIPTOR,SESSION,' +
'DIAGNOSTICS,SESSION_USER,DISCONNECT,SET,DISTINCT,SIZE,' +
'DOMAIN,SMALLINT,DOUBLE,SOME,DROP,SPACE,ELSE,SQL,' +
'END,SQLCA,END-EXEC,SQLCODE,ESCAPE,SQLERROR,EXCEPT,SQLSTATE,' +
'EXCEPTION,SQLWARNING,EXEC,SUBSTRING,EXECUTE,SUM,' +
'EXISTS,SYSTEM_USER,EXTERNAL,TABLE,EXTRACT,TEMPORARY,' +
'FALSE,THEN,FETCH,TIME,FIRST,TIMESTAMP,FLOAT,TIMEZONE_HOUR,' +
'FOR,TIMEZONE_MINUTE,FOREIGN,TO,FORTRAN,TRAILING,' +
'FOUND,TRANSACTION,FROM,TRANSLATE,FULL,TRANSLATION,' +
'GET,TRIM,GLOBAL,TRUE,GO,UNION,GOTO,UNIQUE,GRANT,UNKNOWN,' +
'GROUP,UPDATE,HAVING,UPPER,HOUR,USAGE,IDENTITY,USER,' +
'IMMEDIATE,USING,IN,VALUE,INCLUDE,VALUES,INDEX,VARCHAR,' +
'INDICATOR,VARYING,INITIALLY,VIEW,INNER,WHEN,INPUT,WHENEVER,' +
'INSENSITIVE,WHERE,INSERT,WITH,INT,WORK,INTEGER,WRITE,' +
'INTERSECT,YEAR,INTERVAL,ZONE,INTO,';
C_MSAccAdditionalKeywords =
',LONGTEXT,MEMO,MONEY,NOTE,NUMBER,' +
'OLEOBJECT,OWNERACCESS,PARAMETERS,' +
'PERCENT,PIVOT,SHORT,SINGLE,SINGLEFLOAT,' +
'STDEV,STDEVP,STRING,TABLEID,TEXT,TOP,' +
'TRANSFORM,UNSIGNEDBYTE,VAR,VARBINARY,' +
'VARP,YESNO';
begin
// Informix: on 3.70.TC5DE SQL_KEYWORDS leads to AV
if DriverKind = dkInformix then
Result := C_DefKeywords
else begin
// ASA: "div" in next SetLength is needed to avoid SQL_ERROR on
// "SQL Anywhere 11" driver in Unicode mode.
SetLength(Result, $3FFF div SizeOf(Char));
GetInfo(SQLUSmallint(SQL_KEYWORDS), Result);
Result := C_DefKeywords + Result;
end;
// MSAcc: The following is a workaround for the Access 2007 driver,
// which truncates the key word list.
if (DriverKind in [dkMSAccessJet, dkMSAccessACE]) and (Pos(',TEXT,', Result) = 0) then
Result := Result + C_MSAccAdditionalKeywords;
end;
{-------------------------------------------------------------------------------}
procedure TODBCConnection.GetNonStrAttribute(AAttr: SQLInteger; ApValue: SQLPointer);
var
iStringLen: SQLInteger;
begin
iStringLen := 0;
Check(Lib.SQLGetConnectAttr(FHandle, AAttr, ApValue, 0, iStringLen));
end;
{-------------------------------------------------------------------------------}
procedure TODBCConnection.GetStrAttribute(AAttr: SQLInteger; out AValue: String);
var
iStringLen: SQLInteger;
begin
SetLength(AValue, SQL_MAX_MESSAGE_LENGTH);
iStringLen := 0;
Check(Lib.SQLGetConnectAttr(FHandle, AAttr, PChar(AValue),
SQL_MAX_MESSAGE_LENGTH * SizeOf(Char), iStringLen));
ODBCSetLength(AValue, iStringLen div SizeOf(Char));
end;
{-------------------------------------------------------------------------------}
procedure TODBCConnection.SetAttribute(AAttr: SQLInteger; ApValue: SQLPointer;
AType: SQLInteger);
begin
if ((AType = 0) or (AType = SQL_NTS)) and (ApValue <> nil) then
AType := StrLen(PChar(ApValue)) * SizeOf(Char);
Check(Lib.SQLSetConnectAttr(FHandle, AAttr, ApValue, AType));
end;
{$IFDEF FireDAC_MONITOR}
{-------------------------------------------------------------------------------}
function TODBCConnection.GetTracing: Boolean;
begin
Result := FTracing and inherited GetTracing;
end;
{$ENDIF}
{-------------------------------------------------------------------------------}
function TODBCConnection.EncodeName(const ACat, ASch, AObj: String): String;
var
sQuote: String;
begin
sQuote := IDENTIFIER_QUOTE_CHAR;
Result := '';
if ((CATALOG_USAGE and SQL_CU_DML_STATEMENTS) <> 0) and
(CATALOG_LOCATION = SQL_CL_START) then
if ACat <> '' then
Result := sQuote + ACat + sQuote + CATALOG_NAME_SEPARATOR;
if (SCHEMA_USAGE and SQL_SU_DML_STATEMENTS) <> 0 then
if ASch <> '' then
Result := Result + sQuote + ASch + sQuote + '.';
Result := Result + sQuote + AObj + sQuote;
if ((CATALOG_USAGE and SQL_CU_DML_STATEMENTS) <> 0) and
(CATALOG_LOCATION = SQL_CL_END) then
if ACat <> '' then
Result := CATALOG_NAME_SEPARATOR + sQuote + ACat + sQuote;
end;
{-------------------------------------------------------------------------------}
procedure TODBCConnection.EndTran(AType: SQLSmallint);
begin
Check(Lib.SQLEndTran(HandleType, Handle, AType));
end;
{-------------------------------------------------------------------------------}
procedure TODBCConnection.Commit;
begin
EndTran(SQL_COMMIT);
end;
{-------------------------------------------------------------------------------}
procedure TODBCConnection.Rollback;
begin
EndTran(SQL_ROLLBACK);
end;
{-------------------------------------------------------------------------------}
procedure TODBCConnection.StartTransaction;
begin
AUTOCOMMIT := SQL_AUTOCOMMIT_OFF;
end;
{-------------------------------------------------------------------------------}
function TODBCConnection.GetIsolation: SQLInteger;
begin
if DriverKind in [dkSQLNC, dkSQLOdbc] then
Result := GetIntAttribute(SQL_COPT_SS_TXN_ISOLATION)
else
Result := GetIntAttribute(SQL_ATTR_TXN_ISOLATION);
end;
{-------------------------------------------------------------------------------}
procedure TODBCConnection.SetIsolation(const AValue: SQLInteger);
begin
if DriverKind in [dkSQLNC, dkSQLOdbc] then
SetIntAttribute(SQL_COPT_SS_TXN_ISOLATION, AValue)
else
SetIntAttribute(SQL_ATTR_TXN_ISOLATION, AValue);
end;
{-------------------------------------------------------------------------------}
{ TODBCSelectItem }
{-------------------------------------------------------------------------------}
constructor TODBCSelectItem.Create(AOwner: TODBCStatementBase; AColNum: SQLSmallint);
var
iNameLen: SQLSmallint;
iColMaxLen: SQLUSmallint;
begin
inherited Create;
FStmt := AOwner;
FPosition := AColNum;
iColMaxLen := FStmt.Connection.MAX_COL_NAME_LEN;
// FIPS Intermediate level conformant value
if iColMaxLen < 128 then
iColMaxLen := 128;
SetLength(FName, iColMaxLen);
iNameLen := 0;
FStmt.Check(FStmt.Lib.SQLDescribeCol(FStmt.FHandle, FPosition, PSQLChar(FName),
iColMaxLen, iNameLen, FSQLDataType, FColumnSize, FScale, FNullable));
ODBCSetLength(FName, iNameLen);
case FStmt.Connection.DriverKind of
dkSQLNC,
dkSQLOdbc,
dkFreeTDS,
dkSQLSrvOther:
if (FColumnSize = SQL_SS_LENGTH_UNLIMITED) and
((SQLDataType = SQL_VARCHAR) or (SQLDataType = SQL_VARBINARY) or
(SQLDataType = SQL_WVARCHAR) or (SQLDataType = SQL_SS_XML) or
(SQLDataType = SQL_SS_UDT)) then
FColumnSize := MAXINT;
dkMSAccessJet,
dkMSAccessACE:
// MSAccess: workaround for http://support.microsoft.com/kb/941877
if (FColumnSize = 2147483598) and
((SQLDataType = SQL_VARCHAR) or (SQLDataType = SQL_VARBINARY) or
(SQLDataType = SQL_WVARCHAR)) then
FColumnSize := 255;
end;
if (SQLDataType >= SQL_INTERVAL_YEAR) and
(SQLDataType <= SQL_INTERVAL_MINUTE_TO_SECOND) then begin
FColumnSize := DATETIME_INTERVAL_PRECISION;
FScale := PRECISION;
end;
if ((SQLDataType = SQL_DECIMAL) or (SQLDataType = SQL_NUMERIC) or
(SQLDataType = SQL_DECFLOAT)) and
(FScale > FColumnSize) then
FScale := FColumnSize;
end;
{-------------------------------------------------------------------------------}
function TODBCSelectItem.GetStrAttr(AIndex: Integer): String;
begin
Result := '';
FStmt.ColAttributeString(FPosition, AIndex, Result);
end;
{-------------------------------------------------------------------------------}
function TODBCSelectItem.GetIntAttr(AIndex: Integer): SQLInteger;
var
iVal: SQLLen;
begin
iVal := 0;
FStmt.ColAttributeInt(FPosition, AIndex, iVal);
Result := iVal;
end;
{-------------------------------------------------------------------------------}
function TODBCSelectItem.GetIntAttrSilent(AIndex: Integer): SQLInteger;
var
iVal: SQLLen;
begin
iVal := 0;
FStmt.ColAttributeIntSilent(FPosition, AIndex, iVal);
Result := iVal;
end;
{-------------------------------------------------------------------------------}
function TODBCSelectItem.GetSmallintAttr(AIndex: Integer): SQLSmallint;
begin
Result := 0;
FStmt.ColAttributeSmallint(FPosition, AIndex, Result);
end;
{-------------------------------------------------------------------------------}
function TODBCSelectItem.GetSmallintAttrSilent(AIndex: Integer): SQLSmallint;
begin
Result := 0;
FStmt.ColAttributeSmallintSilent(FPosition, AIndex, Result);
end;
{-------------------------------------------------------------------------------}
function TODBCSelectItem.GetIsFixedLen: Boolean;
begin
case SQLDataType of
SQL_CHAR,
SQL_WCHAR,
SQL_GUID,
SQL_BINARY,
SQL_GRAPHIC:
Result := True
else
Result := False;
end;
end;
{-------------------------------------------------------------------------------}
function TODBCSelectItem.GetROWVER: SQLLen;
begin
Result := SQL_FALSE;
if FStmt.Lib.SQLColAttributeInt(FStmt.FHandle, FPosition, SQL_DESC_ROWVER, nil,
0, nil, Result) <> SQL_SUCCESS then
Result := SQL_FALSE;
end;
{-------------------------------------------------------------------------------}
{ General data type conversion }
{-------------------------------------------------------------------------------}
procedure ODBCNumeric2BCD(const ANum: TSQLNumericRec; out ABcd: TBcd);
var
i, j, iNum, iBcd: integer;
iRem, iTmp: word;
aVal: array [0..SQL_MAX_NUMERIC_LEN - 1] of Byte;
begin
FillChar(ABcd, SizeOf(ABcd), 0);
iNum := SQL_MAX_NUMERIC_LEN - 1;
// check for 0
while (iNum >= 0) and (ANum.val[iNum] = 0) do
Dec(iNum);
if iNum < 0 then begin
ABcd.Precision := 10;
ABcd.SignSpecialPlaces := 2;
Exit;
end;
// fill fraction
Move(ANum.val[0], aVal[0], iNum + 1);
iBcd := SizeOfFraction - 1;
while iNum >= 0 do begin
iRem := 0;
for i := iNum downto 0 do begin
iTmp := (Byte(aVal[i]) + iRem);
aVal[i] := iTmp div 100;
iRem := (iTmp mod 100) shl 8;
end;
ABcd.Fraction[iBcd] := (iRem shr 8) mod 10 + ((iRem shr 8) div 10) shl 4;
Dec(iBcd);
if aVal[iNum] = 0 then
Dec(iNum);
end;
// setup bcd
if ANum.sign = 0 then
ABcd.SignSpecialPlaces := (1 shl 7) + ANum.scale
else
ABcd.SignSpecialPlaces := (0 shl 7) + ANum.scale;
ABcd.Precision := ANum.precision;
// normalize fraction
i := SizeOfFraction - 1 - (ANum.precision div 2);
if i >= 0 then begin
if ANum.scale > ANum.precision then begin
Dec(i, (ANum.scale - ANum.precision + 1) div 2);
Inc(ABcd.Precision, ANum.scale - ANum.precision);
end;
j := i;
if (ABcd.Precision mod 2) = 1 then begin
while i < SizeOfFraction - 1 do begin
ABcd.Fraction[i - j] := (ABcd.Fraction[i] and $0F) shl 4 + ABcd.Fraction[i + 1] shr 4;
Inc(i);
end;
ABcd.Fraction[i - j] := (ABcd.Fraction[i] and $0F) shl 4;
end
else
Move(ABcd.Fraction[i + 1], ABcd.Fraction[i - j], SizeOfFraction - 1 - i);
FillChar(ABcd.Fraction[SizeOfFraction - j], j, 0);
end;
end;
{-------------------------------------------------------------------------------}
procedure ODBCBcd2Numeric(const ABcd: TBcd; out ANum: TSQLNumericRec);
const
MaxWords = SQL_MAX_NUMERIC_LEN div SizeOf(Cardinal);
var
i, j, k: Integer;
iMulDer: Integer;
iNibble: Integer;
iDev, iVal: Int64;
aMul: array [0..MaxWords - 1] of Cardinal;
aVal: array [0..MaxWords - 1] of Cardinal;
iMulSize: Integer;
iValSize: Integer;
begin
FillChar(ANum, SizeOf(TSQLNumericRec), 0);
iMulSize := 1;
iValSize := 1;
aMul[0] := 1;
FillChar(aVal[0], MaxWords * SizeOf(Cardinal), 0);
k := (ABcd.Precision div 2);
if (ABcd.Precision mod 2) = 0 then
Dec(k);
for i := k downto 0 do begin
iMulDer := 100;
if i = k then begin
if (ABcd.Precision mod 2) = 0 then
iNibble := ABcd.Fraction[i] and 15 + (ABcd.Fraction[i] shr 4) * 10
else begin
iNibble := ABcd.Fraction[i] shr 4;
iMulDer := 10;
end;
end
else
iNibble := ABcd.Fraction[i] and 15 + (ABcd.Fraction[i] shr 4) * 10;
iDev := 0;
iValSize := iMulSize;
for j := 0 to iValSize - 1 do begin
iVal := aVal[j] + Int64(aMul[j]) * Int64(iNibble) + iDev;
aVal[j] := Cardinal(iVal and $FFFFFFFF);
iDev := iVal shr 32;
end;
if iDev <> 0 then begin
aVal[iValSize] := iDev;
Inc(iValSize);
end;
if i > 0 then begin
iDev := 0;
for j := 0 to iMulSize - 1 do begin
iVal := Int64(aMul[j]) * Int64(iMulDer) + iDev;
aMul[j] := Cardinal(iVal and $FFFFFFFF);
iDev := iVal shr 32;
end;
if iDev <> 0 then begin
aMul[iMulSize] := iDev;
Inc(iMulSize);
end;
end;
end;
Move(aVal[0], ANum.Val[0], iValSize * SizeOf(Cardinal));
ANum.precision := ABcd.Precision;
ANum.scale := ABcd.SignSpecialPlaces and $3F;
ANum.sign := Byte(ABcd.SignSpecialPlaces and (1 shl 7) = 0);
end;
{-------------------------------------------------------------------------------}
procedure ODBCNumeric2Currency(const ANum: TSQLNumericRec; out ACurr: Currency);
var
iNum: integer;
begin
iNum := SQL_MAX_NUMERIC_LEN - 1;
// check for 0
while (iNum >= 0) and (ANum.val[iNum] = 0) do
Dec(iNum);
if iNum < 0 then begin
ACurr := 0.0;
Exit;
end;
ASSERT(iNum < SizeOf(Int64));
ACurr := PCurrency(PInt64(@ANum.val[0]))^;
if ANum.scale < 4 then
ACurr := ACurr * C_FD_ScaleFactor[4 - ANum.scale]
else if ANum.scale > 4 then
ACurr := ACurr / C_FD_ScaleFactor[ANum.scale - 4];
if ANum.sign = 0 then
ACurr := - ACurr;
end;
{-------------------------------------------------------------------------------}
procedure ODBCCurrency2Numeric(ACurr: Currency; out ANum: TSQLNumericRec);
begin
ANum.precision := 19;
ANum.scale := 4;
if ACurr < 0 then begin
ANum.sign := 0;
ACurr := -ACurr;
end
else
ANum.sign := 1;
Move(ACurr, ANum.val[0], SizeOf(Currency));
FillChar(ANum.val[SizeOf(Currency)], SQL_MAX_NUMERIC_LEN - SizeOf(Currency), 0);
end;
{-------------------------------------------------------------------------------}
{ TODBCVariable }
{-------------------------------------------------------------------------------}
constructor TODBCVariable.Create;
begin
inherited Create;
FSQLDataType := SQL_UNKNOWN_TYPE;
FCDataType := SQL_UNKNOWN_TYPE;
FPosition := -1;
FDataSize := SQL_NULL_DATA;
FBinded := False;
end;
{-------------------------------------------------------------------------------}
destructor TODBCVariable.Destroy;
begin
FList := nil;
FDataReader := nil;
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
function TODBCVariable.GetConnection: TODBCConnection;
begin
Result := TODBCConnection(FList.FOwner.FOwner);
end;
{-------------------------------------------------------------------------------}
function TODBCVariable.GetStatement: TODBCStatementBase;
begin
Result := TODBCStatementBase(FList.FOwner);
end;
{-------------------------------------------------------------------------------}
procedure TODBCVariable.SetCDataType(const AValue: SQLSmallint);
begin
if FCDataType <> AValue then begin
FCDataType := AValue;
FFlagsUpdated := False;
end;
end;
{-------------------------------------------------------------------------------}
procedure TODBCVariable.SetDataSize(const AValue: SQLLen);
begin
if FDataSize <> AValue then begin
FDataSize := AValue;
FFlagsUpdated := False;
end;
end;
{-------------------------------------------------------------------------------}
procedure TODBCVariable.SetColumnSize(const AValue: SQLULen);
begin
if FColumnSize <> AValue then begin
FColumnSize := AValue;
FFlagsUpdated := False;
end;
end;
{-------------------------------------------------------------------------------}
procedure TODBCVariable.SetSQLDataType(const AValue: SQLSmallint);
begin
if SQLDataType <> AValue then begin
FSQLDataType := AValue;
FFlagsUpdated := False;
end;
end;
{-------------------------------------------------------------------------------}
procedure TODBCVariable.SetForceLongData(const AValue: Boolean);
begin
if AValue <> FForceLongData then begin
FForceLongData := AValue;
if AValue then begin
FLongData := True;
FLateBinding := True;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TODBCVariable.SetForceLateBinding(const AValue: Boolean);
begin
if AValue <> FForceLateBinding then begin
FForceLateBinding := AValue;
if AValue then
FLateBinding := True;
end;
end;
{-------------------------------------------------------------------------------}
function TODBCVariable.GetDataInd(AIndex: SQLULen; out ApData: SQLPointer;
out ApInd: PSQLLen): PSQLPointer;
begin
ASSERT((FList <> nil) and (FList.FBuffer <> nil));
FList.FBuffer.GetDataPtr(Self, AIndex, SQLPointer(Result), ApInd);
ASSERT(Result <> nil);
if LongData then
ApData := Result^
else
ApData := Result;
end;
{-------------------------------------------------------------------------------}
function TODBCVariable.GetDataPtr(AIndex: SQLULen; out ApData: SQLPointer;
out ASize: SQLLen; out ApInd: PSQLLen): PSQLPointer;
begin
ASSERT((FList <> nil) and (FList.FBuffer <> nil));
FList.FBuffer.GetDataPtr(Self, AIndex, SQLPointer(Result), ApInd);
ASSERT(Result <> nil);
if LongData then
ApData := Result^
else
ApData := Result;
if (ApInd^ = SQL_NULL_DATA) or (ApInd^ = SQL_NO_TOTAL) then
ASize := 0
else
ASize := ApInd^;
if LongData then
// This is a workaround for Sybase ASE, which for BLOB input params
// does not support SQL_LEN_DATA_AT_EXEC macro and resets indicator
// to SQL_DATA_AT_EXEC value.
if ASize = SQL_DATA_AT_EXEC then
ASize := FLastDataSize
else begin
ASSERT((ASize <= SQL_LEN_DATA_AT_EXEC_OFFSET) or (ASize >= 0));
if ApData = nil then
ASize := 0
else if ASize <= SQL_LEN_DATA_AT_EXEC_OFFSET then
ASize := SQL_LEN_DATA_AT_EXEC_OFFSET - ASize;
end;
ASSERT((SQLDataType <> SQL_SS_TABLE) and (
not LongData and (ASize >= 0) or
LongData and (ASize >= 0) or (ASize = SQL_LEN_DATA_AT_EXEC_OFFSET - SQL_DATA_AT_EXEC)
) or
(SQLDataType = SQL_SS_TABLE) and (
(ASize = 0) or (ASize = SQL_LEN_DATA_AT_EXEC_OFFSET - SQL_DATA_AT_EXEC)
));
end;
{-------------------------------------------------------------------------------}
procedure TODBCVariable.Bind;
begin
UpdateFlags;
ASSERT((FList <> nil) and (FList.FBuffer <> nil) and FList.FBuffer.FIsAllocated);
InternalBind;
end;
{-------------------------------------------------------------------------------}
procedure TODBCVariable.SetBindAttributes(ADescKind: SQLInteger);
var
hAD: SQLHDesc;
iTmp: Integer;
oConn: TODBCConnection;
oStmt: TODBCStatementBase;
begin
oConn := Connection;
if (oConn.DriverODBCVersion < ovODBC3) or
(oConn.DriverKind in [dkElevateDB, dkFreeTDS, dkCache]) then
Exit;
oStmt := Statement;
case CDataType of
SQL_C_NUMERIC:
begin
oStmt.Check(oStmt.Lib.SQLGetStmtAttr(oStmt.FHandle, ADescKind, @hAD, 0, iTmp));
oStmt.Check(oStmt.Lib.SQLSetDescField(hAD, Position, SQL_DESC_CONCISE_TYPE,
SQLPointer(CDataType), SQL_IS_SMALLINT));
oStmt.Check(oStmt.Lib.SQLSetDescField(hAD, Position, SQL_DESC_PRECISION,
SQLPointer(ColumnSize), SQL_IS_INTEGER));
oStmt.Check(oStmt.Lib.SQLSetDescField(hAD, Position, SQL_DESC_SCALE,
SQLPointer(Scale), SQL_IS_SMALLINT));
if (ADescKind = SQL_ATTR_APP_PARAM_DESC) and not LongData or
(ADescKind = SQL_ATTR_APP_ROW_DESC) and FBinded then
// MSSQL: if SQL_DESC_DATA_PTR is NOT set, then SQLExecute gives
// "Invalid string or buffer length"
oStmt.Check(oStmt.Lib.SQLSetDescField(hAD, Position, SQL_DESC_DATA_PTR,
LocalBuffer, SQL_IS_POINTER));
end;
SQL_C_INTERVAL_YEAR ..
SQL_C_INTERVAL_MINUTE_TO_SECOND:
begin
oStmt.Check(oStmt.Lib.SQLGetStmtAttr(oStmt.FHandle, ADescKind, @hAD, 0, iTmp));
oStmt.Check(oStmt.Lib.SQLSetDescField(hAD, Position, SQL_DESC_CONCISE_TYPE,
SQLPointer(CDataType), SQL_IS_SMALLINT));
oStmt.Check(oStmt.Lib.SQLSetDescField(hAD, Position, SQL_DESC_DATETIME_INTERVAL_PRECISION,
SQLPointer(ColumnSize), SQL_IS_INTEGER));
oStmt.Check(oStmt.Lib.SQLSetDescField(hAD, Position, SQL_DESC_PRECISION,
SQLPointer(Scale), SQL_IS_SMALLINT));
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TODBCVariable.VarTypeUnsup(ACType: SQLSmallint);
begin
FDException(Statement.OwningObj, [S_FD_LPhys, S_FD_ODBCId],
er_FD_OdbcVarDataTypeUnsup, [GetDumpLabel, ACType]);
end;
{-------------------------------------------------------------------------------}
function TODBCVariable.GetData(AIndex: SQLULen; var ApData: SQLPointer;
var ASize: SQLLen; AByRef: Boolean = False): Boolean;
var
pData: SQLPointer;
pInd: PSQLLen;
pText: SQLPointer;
pTail: SQLPointer;
pTime2: PSQLSSTime2Struct;
pDate: PSQLDateStruct;
pTime: PSQLTimeStruct;
pInt: PFDSQLTimeInterval;
begin
GetDataPtr(AIndex, pData, ASize, pInd);
if (pInd^ = SQL_NULL_DATA) or (pData = nil) then begin
Result := False;
ASize := 0;
if AByRef then
ApData := nil;
end
else begin
if pInd^ = SQL_NO_TOTAL then
ASize := 0;
Result := True;
case CDataType of
SQL_C_STINYINT,
SQL_C_UTINYINT,
SQL_C_TINYINT:
if AByRef then
ApData := pData
else if ApData <> nil then
PSQLByte(ApData)^ := PSQLByte(pData)^;
SQL_C_SSHORT,
SQL_C_USHORT,
SQL_C_SHORT:
if AByRef then
ApData := pData
else if ApData <> nil then
PSQLSmallint(ApData)^ := PSQLSmallint(pData)^;
SQL_C_SLONG,
SQL_C_ULONG,
SQL_C_LONG:
if AByRef then
ApData := pData
else if ApData <> nil then
PSQLInteger(ApData)^ := PSQLInteger(pData)^;
SQL_C_SBIGINT,
SQL_C_UBIGINT:
if AByRef then
ApData := pData
else if ApData <> nil then
PSQLBigInt(ApData)^ := PSQLBigInt(pData)^;
SQL_C_BIT:
if AByRef then
ApData := pData
else begin
ASize := SizeOf(WordBool);
if not AByRef and (ApData <> nil) then
PWordBool(ApData)^ := (PSQLByte(pData)^ <> 0);
end;
SQL_C_FLOAT:
if AByRef then
ApData := pData
else if ApData <> nil then
PSQLReal(ApData)^ := PSQLReal(pData)^;
SQL_C_DOUBLE:
if AByRef then
ApData := pData
else if ApData <> nil then
PSQLDouble(ApData)^ := PSQLDouble(pData)^;
SQL_C_NUMERIC:
if AByRef then
ApData := pData
else if ApData <> nil then begin
if IsCurrency then begin
ODBCNumeric2Currency(PSQLNumericRec(pData)^, PCurrency(ApData)^);
ASize := SizeOf(Currency);
end
else begin
ODBCNumeric2BCD(PSQLNumericRec(pData)^, PBcd(ApData)^);
ASize := SizeOf(TBcd);
end;
end;
SQL_C_BINARY:
begin
case SQLDataType of
SQL_SS_TIME2:
if AByRef then
ApData := pData
else if ApData <> nil then begin
pTime2 := PSQLSSTime2Struct(pData);
PInteger(ApData)^ := (pTime2^.Second + pTime2^.Minute * 60 +
pTime2^.Hour * 3600) * 1000 + pTime2^.Fraction div 1000000;
ASize := SizeOf(Integer);
end;
else
begin
if (SQLDataType = SQL_BINARY) and Statement.StrsTrim then begin
pTail := PFDAnsiString(pData) + ASize - 1;
while (ASize > 0) and (PByte(pTail)^ = 0) do begin
Dec(ASize);
Dec(PFDAnsiString(pTail));
end;
end;
if (ASize = 0) and Statement.StrsEmpty2Null then begin
Result := False;
ASize := 0;
if AByRef then
ApData := nil;
end
else if AByRef then
ApData := pData
else if ApData <> nil then begin
Move(PSQLByte(pData)^, PSQLByte(ApData)^, ASize);
if (SQLDataType = SQL_BINARY) and (ASize < DataSize) then
FillChar((PFDAnsiString(ApData) + ASize)^, DataSize - ASize, 0);
end;
end;
end;
end;
SQL_C_CHAR:
begin
if ASize = SQL_NTS then
ASize := FDAnsiStrLen(PFDAnsiString(pData));
case SQLDataType of
SQL_NUMERIC,
SQL_DECIMAL,
SQL_DECFLOAT:
if AByRef then
ApData := pData
else if ApData <> nil then begin
pText := nil;
ASize := Connection.FEncoder.Decode(pData, ASize, pText);
if IsCurrency then begin
FDStr2Curr(PChar(pText), ASize, PCurrency(ApData)^, DecimalSeparator);
ASize := SizeOf(Currency);
end
else begin
FDStr2BCD(PChar(pText), ASize, PBcd(ApData)^, DecimalSeparator);
ASize := SizeOf(TBcd);
end;
end;
else
begin
if (SQLDataType = SQL_CHAR) and Statement.StrsTrim then begin
pTail := PFDAnsiString(pData) + ASize - 1;
while (ASize > 0) and (PFDAnsiString(pTail)^ = TFDAnsiChar(' ')) do begin
Dec(ASize);
Dec(PFDAnsiString(pTail));
end;
end;
if (ASize = 0) and Statement.StrsEmpty2Null then begin
Result := False;
ASize := 0;
if AByRef then
ApData := nil;
end
else if AByRef then
ApData := pData
else if ApData <> nil then begin
Move(PFDAnsiString(pData)^, PFDAnsiString(ApData)^, ASize * SizeOf(TFDAnsiChar));
if (SQLDataType = SQL_CHAR) and (ASize * SizeOf(TFDAnsiChar) < DataSize) then
FillChar((PFDAnsiString(ApData) + ASize)^, DataSize - ASize * SizeOf(TFDAnsiChar), 0);
end;
end;
end;
end;
SQL_C_WCHAR:
begin
if ASize = SQL_NTS then
ASize := StrLen(PWideChar(pData))
else
ASize := ASize div SizeOf(WideChar);
if ((SQLDataType = SQL_WCHAR) or (SQLDataType = SQL_GRAPHIC)) and Statement.StrsTrim then begin
pTail := PWideChar(pData) + ASize - 1;
while (ASize > 0) and (PWideChar(pTail)^ = ' ') do begin
Dec(ASize);
Dec(PWideChar(pTail));
end;
end
else if ((SQLDataType = SQL_XML) or
(SQLDataType = SQL_SS_XML) or
(SQLDataType = SQL_TD_XML) or (SQLDataType = SQL_TD_JSON) or (SQLDataType = SQL_TD_WJSON)) and
(PWideChar(pData)^ = #$FEFF) then begin
Inc(PWideChar(pData));
Dec(ASize);
end;
if (ASize = 0) and Statement.StrsEmpty2Null then begin
Result := False;
ASize := 0;
if AByRef then
ApData := nil;
end
else if AByRef then
ApData := pData
else if ApData <> nil then begin
Move(PWideChar(pData)^, PWideChar(ApData)^, ASize * SizeOf(WideChar));
if ((SQLDataType = SQL_WCHAR) or (SQLDataType = SQL_GRAPHIC)) and (ASize * SizeOf(WideChar) < DataSize) then
FillChar((PWideChar(ApData) + ASize)^, DataSize - ASize * SizeOf(WideChar), 0);
end;
end;
SQL_C_TYPE_DATE,
SQL_C_DATE:
if AByRef then
ApData := pData
else if ApData <> nil then begin
pDate := PSQLDateStruct(pData);
PInteger(ApData)^ := Integer(Trunc(EncodeDate(pDate^.Year,
pDate^.Month, pDate^.Day) + DateDelta));
ASize := SizeOf(Integer);
end;
SQL_C_TYPE_TIME,
SQL_C_TIME:
if AByRef then
ApData := pData
else if ApData <> nil then begin
pTime := PSQLTimeStruct(pData);
PInteger(ApData)^ := (pTime^.Second + pTime^.Minute * 60 + pTime^.Hour * 3600) * 1000;
ASize := SizeOf(Integer);
end;
SQL_C_TYPE_TIMESTAMP,
SQL_C_TIMESTAMP:
if AByRef then
ApData := pData
else if ApData <> nil then begin
// The layout of the TODBCTimeStamp and TSQLTimeStamp is the same
PODBCTimeStamp(ApData)^ := PODBCTimeStamp(pData)^;
PSQLTimeStamp(ApData)^.Fractions := PSQLTimeStamp(ApData)^.Fractions div 1000000;
// Informix ODBC driver returns DATETIME HOUR TO MINUTE (or other
// time-only precision) with Date=(1200,1,1). For BDE / Delphi RTL
// compatibility set Date part to TDateTime(0).
if (Statement.Connection.DriverKind = dkInformix) and
(PSQLTimeStamp(ApData)^.Year = 1200) and
(PSQLTimeStamp(ApData)^.Month = 1) and
(PSQLTimeStamp(ApData)^.Day = 1) then begin
PSQLTimeStamp(ApData)^.Year := 1899;
PSQLTimeStamp(ApData)^.Month := 12;
PSQLTimeStamp(ApData)^.Day := 30;
end;
end;
SQL_C_INTERVAL_YEAR ..
SQL_C_INTERVAL_MINUTE_TO_SECOND:
if AByRef then
ApData := pData
else if ApData <> nil then begin
pInt := PFDSQLTimeInterval(ApData);
if PSQLInterval(pData)^.Interval_sign = SQL_TRUE then
pInt^.Sign := -1
else
pInt^.Sign := 1;
pInt^.Kind := TFDSQLTimeIntervalKind(PSQLInterval(pData)^.Interval_type);
case PSQLInterval(pData)^.Interval_type of
SQL_IS_YEAR,
SQL_IS_MONTH,
SQL_IS_YEAR_TO_MONTH:
begin
pInt^.Years := PSQLInterval(pData)^.YearMonth.Year;
pInt^.Months := PSQLInterval(pData)^.YearMonth.Month;
end;
SQL_IS_DAY,
SQL_IS_HOUR,
SQL_IS_MINUTE,
SQL_IS_SECOND,
SQL_IS_DAY_TO_HOUR,
SQL_IS_DAY_TO_MINUTE,
SQL_IS_DAY_TO_SECOND,
SQL_IS_HOUR_TO_MINUTE,
SQL_IS_HOUR_TO_SECOND,
SQL_IS_MINUTE_TO_SECOND:
begin
pInt^.Days := PSQLInterval(pData)^.DaySecond.Day;
pInt^.Hours := PSQLInterval(pData)^.DaySecond.Hour;
pInt^.Minutes := PSQLInterval(pData)^.DaySecond.Minute;
pInt^.Seconds := PSQLInterval(pData)^.DaySecond.Second;
pInt^.Fractions := PSQLInterval(pData)^.DaySecond.Fraction;
end;
else
ASSERT(False);
end;
ASize := SizeOf(TFDSQLTimeInterval);
end;
SQL_C_GUID:
if AByRef then
ApData := pData
else if ApData <> nil then
PGUID(ApData)^ := PGUID(pData)^;
else
VarTypeUnsup(CDataType);
end;
end;
end;
{-------------------------------------------------------------------------------}
function TODBCVariable.GetAsStrings(AIndex: SQLULen): String;
var
pVal: SQLPointer;
iSz: SQLLen;
begin
Result := '';
pVal := nil;
iSz := 0;
if GetData(AIndex, pVal, iSz, True) then
case CDataType of
SQL_C_CHAR:
Result := Connection.FEncoder.Decode(pVal, iSz, ecANSI);
SQL_C_WCHAR:
Result := Connection.FEncoder.Decode(pVal, iSz, ecUTF16);
else
ASSERT(False);
end;
end;
{-------------------------------------------------------------------------------}
procedure TODBCVariable.SetData(AIndex: SQLULen; ApData: SQLPointer; ASize: SQLLen);
var
pData: SQLPointer;
pInd: PSQLLen;
iSize: SQLLen;
iLen: Integer;
iYear, iMonth, iDay: Word;
iSeconds: Cardinal;
lIsNull: WordBool;
pTime2: PSQLSSTime2Struct;
pDate: PSQLDateStruct;
pTime: PSQLTimeStruct;
pInt: PFDSQLTimeInterval;
aBuff: array[0..255] of Byte;
rBcd: TBcd;
procedure ErrorDataTooLarge(AMax: SQLLen; AActual: Integer);
begin
FDException(Statement.OwningObj, [S_FD_LPhys, S_FD_ODBCId],
er_FD_AccDataToLarge, [GetDumpLabel, AMax, AActual]);
end;
begin
if LongData and IsParameter then
if (ParamType in [SQL_PARAM_INPUT_OUTPUT, SQL_PARAM_OUTPUT,
SQL_PARAM_INPUT_OUTPUT_STREAM, SQL_PARAM_OUTPUT_STREAM]) and
(ASize < DataSize) and (DataSize <> MaxInt) then
AllocLongData(AIndex, DataSize)
else
AllocLongData(AIndex, ASize);
GetDataPtr(AIndex, pData, iSize, pInd);
if ApData = nil then begin
lIsNull := True;
iSize := SQL_NULL_DATA;
end
else
lIsNull := False;
case CDataType of
SQL_C_STINYINT,
SQL_C_UTINYINT,
SQL_C_TINYINT:
if lIsNull then
PSQLByte(pData)^ := 0
else begin
PSQLByte(pData)^ := PSQLByte(ApData)^;
iSize := SizeOf(SQLByte);
end;
SQL_C_SSHORT,
SQL_C_USHORT,
SQL_C_SHORT:
if lIsNull then
PSQLSmallint(pData)^ := 0
else begin
if MSAccBoolean and (PSQLSmallint(ApData)^ <> 0) then
PSQLSmallint(pData)^ := -1
else
PSQLSmallint(pData)^ := PSQLSmallint(ApData)^;
iSize := SizeOf(SQLSmallint);
end;
SQL_C_SLONG,
SQL_C_ULONG,
SQL_C_LONG:
if lIsNull then
PSQLInteger(pData)^ := 0
else begin
PSQLInteger(pData)^ := PSQLInteger(ApData)^;
iSize := SizeOf(SQLInteger);
end;
SQL_C_SBIGINT,
SQL_C_UBIGINT:
if lIsNull then
PSQLBigInt(pData)^ := 0
else begin
PSQLBigInt(pData)^ := PSQLBigInt(ApData)^;
iSize := SizeOf(SQLBigInt);
end;
SQL_C_BIT:
if lIsNull then
PSQLByte(pData)^ := 0
else begin
PSQLByte(pData)^ := SQLByte(PWordBool(ApData)^ = True);
iSize := SizeOf(SQLByte);
end;
SQL_C_FLOAT:
if lIsNull then
PSQLReal(pData)^ := 0.0
else begin
PSQLReal(pData)^ := PSQLReal(ApData)^;
iSize := SizeOf(SQLReal);
end;
SQL_C_DOUBLE:
if lIsNull then
PSQLDouble(pData)^ := 0.0
else begin
PSQLDouble(pData)^ := PSQLDouble(ApData)^;
iSize := SizeOf(SQLDouble);
end;
SQL_C_NUMERIC:
if lIsNull then
FillChar(PSQLNumericRec(pData)^, SizeOf(TSQLNumericRec), 0)
else begin
if IsCurrency then
ODBCCurrency2Numeric(PCurrency(ApData)^, PSQLNumericRec(pData)^)
else begin
if (Connection.DriverKind = dkTeradata) or
(Connection.DriverKind in [dkSQLSrv, dkSQLNC, dkSQLOdbc, dkFreeTDS, dkSQLSrvOther]) and
(ParamType in [SQL_PARAM_INPUT_OUTPUT, SQL_PARAM_OUTPUT]) then begin
NormalizeBcd(PBcd(ApData)^, rBcd, ColumnSize, Scale);
ApData := @rBcd;
end;
ODBCBCD2Numeric(PBcd(ApData)^, PSQLNumericRec(pData)^);
end;
iSize := SizeOf(TSQLNumericRec);
end;
SQL_C_BINARY:
if SQLDataType = SQL_SS_TIME2 then begin
if lIsNull then
FillChar(PSQLSSTime2Struct(pData)^, SizeOf(TSQLSSTime2Struct), 0)
else begin
iSeconds := PCardinal(ApData)^ div 1000;
pTime2 := PSQLSSTime2Struct(pData);
pTime2^.Hour := SQLUSmallint(iSeconds div 3600);
pTime2^.Minute := SQLUSmallint((iSeconds div 60) mod 60);
pTime2^.Second := SQLUSmallint(iSeconds mod 60);
pTime2^.Fraction := SQLUInteger(PCardinal(ApData)^ mod 1000 * 1000000);
iSize := SizeOf(TSQLSSTime2Struct);
end;
end
else begin
if lIsNull then begin
if DataSize <> MAXINT then
FillChar(PSQLByte(pData)^, DataSize, 0);
end
else begin
iSize := ASize;
if (SQLDataType = SQL_BINARY) and Statement.StrsTrim then
while (iSize > 0) and (PByte(ApData)[iSize - 1] = 0) do
Dec(iSize);
if Statement.StrsEmpty2Null and (iSize = 0) then
iSize := SQL_NULL_DATA
else begin
if (iSize > ColumnSize) and not LongData then
if Statement.StrsTrim2Len then
iSize := ColumnSize
else
ErrorDataTooLarge(ColumnSize, iSize);
Move(PSQLByte(ApData)^, PSQLByte(pData)^, iSize);
end;
end;
end;
SQL_C_CHAR:
case SQLDataType of
SQL_NUMERIC,
SQL_DECIMAL,
SQL_DECFLOAT:
if lIsNull then begin
if DataSize > 1 then
PFDAnsiString(pData)[0] := TFDAnsiChar('0');
if DataSize > 2 then
PFDAnsiString(pData)[1] := TFDAnsiChar(DecimalSeparator);
if DataSize > 3 then begin
PFDAnsiString(pData)[2] := TFDAnsiChar('0');
PFDAnsiString(pData)[3] := TFDAnsiChar(#0);
end
else
PFDAnsiString(pData)[DataSize - 1] := TFDAnsiChar(#0);
end
else begin
if IsCurrency then
FDCurr2Str(PChar(@aBuff[0]), iLen, PCurrency(ApData)^, DecimalSeparator)
else
FDBCD2Str(PChar(@aBuff[0]), iLen, PBcd(ApData)^, DecimalSeparator);
iSize := Connection.FEncoder.Encode(PChar(@aBuff[0]), iLen, pData) *
SizeOf(TFDAnsiChar);
// add one for #0
if DataSize < iSize + 1 then
ErrorDataTooLarge(DataSize, iSize + 1);
end;
else
if lIsNull then begin
if DataSize <> MAXINT then
FillChar(PFDAnsiString(pData)^, DataSize * SizeOf(TFDAnsiChar), 0);
end
else begin
if ASize = SQL_NTS then
iSize := FDAnsiStrLen(PFDAnsiString(ApData))
else
iSize := ASize;
if (SQLDataType = SQL_CHAR) and Statement.StrsTrim then
while (iSize > 0) and (PFDAnsiString(ApData)[iSize - 1] = TFDAnsiChar(' ')) do
Dec(iSize);
if Statement.StrsEmpty2Null and (iSize = 0) then
iSize := SQL_NULL_DATA
else begin
if (iSize > ColumnSize) and not LongData then
if Statement.StrsTrim2Len then
iSize := ColumnSize
else
ErrorDataTooLarge(ColumnSize, iSize);
Move(PFDAnsiString(ApData)^, PFDAnsiString(pData)^, iSize * SizeOf(TFDAnsiChar));
iSize := iSize * SizeOf(TFDAnsiChar);
end;
end;
end;
SQL_C_WCHAR:
if lIsNull then begin
if DataSize <> MAXINT then
FillChar(PWideChar(pData)^, DataSize, 0);
end
else begin
if ASize = SQL_NTS then
iSize := StrLen(PWideChar(ApData))
else
iSize := ASize;
if ((SQLDataType = SQL_WCHAR) or (SQLDataType = SQL_GRAPHIC)) and Statement.StrsTrim then
while (iSize > 0) and (PWideChar(ApData)[iSize - 1] = ' ') do
Dec(iSize);
if Statement.StrsEmpty2Null and (iSize = 0) then
iSize := SQL_NULL_DATA
else begin
if (iSize > ColumnSize) and not LongData then
if Statement.StrsTrim2Len then
iSize := ColumnSize
else
ErrorDataTooLarge(ColumnSize, iSize);
Move(PWideChar(ApData)^, PWideChar(pData)^, iSize * SizeOf(WideChar));
iSize := iSize * SizeOf(WideChar);
end;
end;
SQL_C_TYPE_DATE,
SQL_C_DATE:
if lIsNull then
FillChar(PSQLDateStruct(pData)^, SizeOf(TSQLDateStruct), 0)
else begin
iYear := 0;
iMonth := 0;
iDay := 0;
DecodeDate(PInteger(ApData)^ - DateDelta, iYear, iMonth, iDay);
pDate := PSQLDateStruct(pData);
pDate^.Year := iYear;
pDate^.Month := iMonth;
pDate^.Day := iDay;
iSize := SizeOf(TSQLDateStruct);
end;
SQL_C_TYPE_TIME,
SQL_C_TIME:
if lIsNull then
FillChar(PSQLTimeStruct(pData)^, SizeOf(TSQLTimeStruct), 0)
else begin
iSeconds := Cardinal(PInteger(ApData)^ div 1000);
pTime := PSQLTimeStruct(pData);
pTime^.Hour := SQLUSmallint(iSeconds div 3600);
pTime^.Minute := SQLUSmallint((iSeconds div 60) mod 60);
pTime^.Second := SQLUSmallint(iSeconds mod 60);
iSize := SizeOf(TSQLTimeStruct);
end;
SQL_C_TYPE_TIMESTAMP,
SQL_C_TIMESTAMP:
if lIsNull then
FillChar(PODBCTimeStamp(pData)^, SizeOf(TSQLTimeStamp), 0)
else begin
// The layout of the TODBCTimeStamp and TSQLTimeStamp is the same
PODBCTimeStamp(pData)^ := PODBCTimeStamp(ApData)^;
PODBCTimeStamp(pData)^.Fraction := PODBCTimeStamp(pData)^.Fraction * 1000000;
iSize := SizeOf(TODBCTimeStamp);
end;
SQL_C_INTERVAL_YEAR ..
SQL_C_INTERVAL_MINUTE_TO_SECOND:
begin
FillChar(PSQLInterval(pData)^, SizeOf(TSQLInterval), 0);
if not lIsNull then begin
pInt := PFDSQLTimeInterval(ApData);
if pInt^.Sign < 0 then
PSQLInterval(pData)^.Interval_sign := SQL_TRUE
else
PSQLInterval(pData)^.Interval_sign := SQL_FALSE;
PSQLInterval(pData)^.Interval_type := SQLInteger(pInt^.Kind);
case PSQLInterval(pData)^.Interval_type of
SQL_IS_YEAR,
SQL_IS_MONTH,
SQL_IS_YEAR_TO_MONTH:
begin
PSQLInterval(pData)^.YearMonth.Year := pInt^.Years;
PSQLInterval(pData)^.YearMonth.Month := pInt^.Months;
end;
SQL_IS_DAY,
SQL_IS_HOUR,
SQL_IS_MINUTE,
SQL_IS_SECOND,
SQL_IS_DAY_TO_HOUR,
SQL_IS_DAY_TO_MINUTE,
SQL_IS_DAY_TO_SECOND,
SQL_IS_HOUR_TO_MINUTE,
SQL_IS_HOUR_TO_SECOND,
SQL_IS_MINUTE_TO_SECOND:
begin
PSQLInterval(pData)^.DaySecond.Day := pInt^.Days;
PSQLInterval(pData)^.DaySecond.Hour := pInt^.Hours;
PSQLInterval(pData)^.DaySecond.Minute := pInt^.Minutes;
PSQLInterval(pData)^.DaySecond.Second := pInt^.Seconds;
PSQLInterval(pData)^.DaySecond.Fraction := pInt^.Fractions * 1000000;
end;
else
ASSERT(False);
end;
iSize := SizeOf(TSQLInterval);
end;
end;
SQL_C_GUID:
if lIsNull then
FillChar(PSQLGUID(pData)^, SizeOf(TSQLGUID), 0)
else begin
PGUID(pData)^ := PGUID(ApData)^;
iSize := SizeOf(TSQLGUID);
end;
else
VarTypeUnsup(CDataType);
end;
FLastDataSize := iSize;
FDataReader := nil;
if not LongData or
(IsParameter and (ParamType in [SQL_PARAM_INPUT_OUTPUT, SQL_PARAM_OUTPUT,
SQL_PARAM_INPUT_OUTPUT_STREAM, SQL_PARAM_OUTPUT_STREAM])) then
pInd^ := iSize
else if iSize <> SQL_NULL_DATA then
pInd^ := SQL_LEN_DATA_AT_EXEC(iSize)
else
pInd^ := SQL_NULL_DATA;
end;
{-------------------------------------------------------------------------------}
procedure TODBCVariable.SetDataReader(AIndex: SQLULen; ApData : SQLPointer);
var
pData: SQLPointer;
pInd: PSQLLen;
iSize: SQLLen;
begin
if not ((CDataType = SQL_C_CHAR) or (CDataType = SQL_C_WCHAR) or (CDataType = SQL_C_BINARY) or
(CDataType = SQL_C_DEFAULT) and (SQLDataType = SQL_SS_TABLE)) then
VarTypeUnsup(CDataType);
try
GetDataPtr(AIndex, pData, iSize, pInd);
FLastDataSize := 0;
if ApData = nil then begin
FDataReader := nil;
pInd^ := SQL_NULL_DATA;
end
else begin
FDataReader := PUnknown(ApData)^;
pInd^ := SQL_DATA_AT_EXEC;
end;
finally
PUnknown(ApData)^ := nil;
end;
end;
{-------------------------------------------------------------------------------}
function TODBCVariable.AllocLongData(AIndex: SQLULen; ASize: SQLLen): PSQLPointer;
var
pBuffer: SQLPointer;
pInd: PSQLLen;
begin
ASSERT(LongData);
if CDataType = SQL_C_WCHAR then
ASize := ASize * SizeOf(WideChar);
Result := GetDataInd(AIndex, pBuffer, pInd);
// Allocate 1 byte long buffer when blob size=0 to avoid future conversion
// of nil buffer to NULL
if ASize = 0 then
ASize := 1;
if pBuffer = nil then
GetMem(Result^, ASize)
else
ReallocMem(Result^, ASize);
end;
{-------------------------------------------------------------------------------}
procedure TODBCVariable.FreeLongData(AIndex: SQLULen);
var
pBuffer: SQLPointer;
ppBuffer: PSQLPointer;
pInd: PSQLLen;
begin
ASSERT(LongData);
ppBuffer := GetDataInd(AIndex, pBuffer, pInd);
if pBuffer <> nil then begin
FreeMem(pBuffer);
ppBuffer^ := nil;
end;
pInd^ := SQL_NULL_DATA;
end;
{-------------------------------------------------------------------------------}
function TODBCVariable.CalcDataSize(AColumnSize: SQLULen): SQLLen;
begin
case CDataType of
SQL_C_SLONG,
SQL_C_ULONG,
SQL_C_LONG:
Result := SizeOf(SQLInteger);
SQL_C_SBIGINT,
SQL_C_UBIGINT:
Result := SizeOf(SQLBigInt);
SQL_C_BIT,
SQL_C_TINYINT,
SQL_C_STINYINT,
SQL_C_UTINYINT:
Result := SizeOf(SQLByte);
SQL_C_SHORT,
SQL_C_SSHORT,
SQL_C_USHORT:
Result := SizeOf(SQLSmallint);
SQL_C_CHAR:
if AColumnSize = MAXINT then
Result := MAXINT
else begin
case SQLDataType of
SQL_DECIMAL,
SQL_NUMERIC,
SQL_DECFLOAT:
if AColumnSize = 0 then
Result := C_FD_DefNumericSize
else
Result := AColumnSize + 2;
SQL_CHAR,
SQL_VARCHAR:
if AColumnSize = 0 then
Result := C_FD_DefStrSize
else
Result := AColumnSize;
else
if ParamType = SQL_PARAM_INPUT then
Result := C_FD_DefLongSize
else
Result := C_FD_DefStrSize;
end;
if (Result <> C_FD_DefLongSize * SizeOf(TFDAnsiChar)) and
(Result < High(SQLLen) - SizeOf(TFDAnsiChar)) then
Inc(Result, SizeOf(TFDAnsiChar));
end;
SQL_C_WCHAR:
if AColumnSize = MAXINT then
Result := MAXINT
else begin
case SQLDataType of
SQL_WCHAR,
SQL_WVARCHAR,
SQL_GRAPHIC,
SQL_VARGRAPHIC,
SQL_LONGVARGRAPHIC:
if AColumnSize = 0 then
Result := C_FD_DefStrSize
else
Result := AColumnSize;
else
if ParamType = SQL_PARAM_INPUT then
Result := C_FD_DefLongSize
else
Result := C_FD_DefStrSize;
end;
Result := Result * SizeOf(SQLWChar);
if (Result <> C_FD_DefLongSize * SizeOf(SQLWChar)) and
(Result < High(SQLLen) - SizeOf(WideChar)) then
Inc(Result, SizeOf(WideChar));
end;
SQL_C_FLOAT:
Result := SizeOf(SQLReal);
SQL_C_DOUBLE:
Result := SizeOf(SQLDouble);
SQL_C_NUMERIC:
Result := SizeOf(TSQLNumericRec);
SQL_C_GUID:
Result := SizeOf(TSQLGUID);
SQL_C_BINARY:
if SQLDataType = SQL_SS_TIME2 then
Result := SizeOf(TSQLSSTime2Struct)
else if AColumnSize = MAXINT then
Result := MAXINT
else
case SQLDataType of
SQL_BINARY,
SQL_VARBINARY:
if AColumnSize = 0 then
Result := C_FD_DefStrSize
else
Result := AColumnSize;
else
if ParamType = SQL_PARAM_INPUT then
Result := C_FD_DefLongSize
else
Result := C_FD_DefStrSize;
end;
SQL_C_DATE,
SQL_C_TYPE_DATE:
Result := SizeOf(SQL_DATE_STRUCT);
SQL_C_TIME,
SQL_C_TYPE_TIME:
Result := SizeOf(SQL_TIME_STRUCT);
SQL_C_TYPE_TIMESTAMP,
SQL_C_TIMESTAMP:
Result := SizeOf(SQL_TIMESTAMP_STRUCT);
SQL_C_INTERVAL_YEAR..
SQL_C_INTERVAL_MINUTE_TO_SECOND:
Result := SizeOf(TSQLInterval);
else
Result := 0;
VarTypeUnsup(CDataType);
end;
end;
{-------------------------------------------------------------------------------}
procedure TODBCVariable.UpdateFlags;
var
iMaxCharSize, iMaxByteSize: Integer;
lPrecUndef: Boolean;
oConn: TODBCConnection;
begin
if FFlagsUpdated then
Exit;
FIsCurrency := False;
if SQLDataType = SQL_SS_VARIANT then
// MSSQL: see comment in TODBCStatementBase.GetLongVarPiece
FMSSQLVariantBinary := Connection.MSSQLVariantBinary and
(Connection.DriverKind <> dkSQLOdbc)
else if (SQLDataType = SQL_CHAR) or (SQLDataType = SQL_VARCHAR) or
(SQLDataType = SQL_BINARY) or (SQLDataType = SQL_VARBINARY) or
(SQLDataType = SQL_WVARCHAR) or (SQLDataType = SQL_WCHAR) or
(SQLDataType = SQL_GRAPHIC) or (SQLDataType = SQL_VARGRAPHIC) or
(SQLDataType = SQL_LONGVARGRAPHIC) then begin
ASSERT((FList <> nil) and (Statement <> nil));
if FColumnSize > 0 then
FDataSize := CalcDataSize(FColumnSize);
oConn := Connection;
if Assigned(oConn.OnGetMaxSizes) and (FColumnSize <> MAXINT) then begin
iMaxCharSize := 0;
iMaxByteSize := 0;
oConn.OnGetMaxSizes(CDataType,
(SQLDataType = SQL_CHAR) or (SQLDataType = SQL_WCHAR) or
(SQLDataType = SQL_GRAPHIC) or (SQLDataType = SQL_BINARY),
iMaxCharSize, iMaxByteSize);
if (iMaxCharSize > 0) and ((FColumnSize <= 0) or (FColumnSize > iMaxCharSize)) then
FColumnSize := iMaxCharSize;
if (iMaxByteSize > 0) and ((FDataSize <= 0) or (FDataSize > iMaxByteSize)) then
if CDataType = SQL_C_CHAR then
FDataSize := iMaxByteSize + SizeOf(SQLChar)
else if CDataType = SQL_C_WCHAR then
FDataSize := iMaxByteSize + SizeOf(SQLWChar)
else
FDataSize := iMaxByteSize;
end;
if FColumnSize = 0 then begin
FColumnSize := C_FD_DefStrSize;
// MS JET DBF driver supports only up to 254 characters
if (oConn.DriverKind = dkDBF) and (FColumnSize > 254) then
FColumnSize := 254;
FDataSize := CalcDataSize(FColumnSize);
end;
end
else if (CDataType = SQL_C_TYPE_TIMESTAMP) or (CDataType = SQL_C_TIMESTAMP) then begin
FColumnSize := 23;
FScale := 3;
FDataSize := CalcDataSize(FColumnSize);
end
else if CDataType = SQL_C_TYPE_DATE then begin
FColumnSize := 10;
FScale := 0;
FDataSize := CalcDataSize(FColumnSize);
end
else if (CDataType >= SQL_C_INTERVAL_YEAR) and (CDataType <= SQL_C_INTERVAL_MINUTE_TO_SECOND) then begin
// leading interval precision
FColumnSize := 5;
// interval second fraction precision
FScale := 3;
FDataSize := CalcDataSize(FColumnSize);
end
else if (SQLDataType = SQL_NUMERIC) or (SQLDataType = SQL_DECIMAL) or
(SQLDataType = SQL_DECFLOAT) then begin
lPrecUndef := FColumnSize = 0;
if lPrecUndef then
FColumnSize := C_FD_DefNumericSize;
if (FScale = 0) and IsParameter and
((Connection.DriverKind <> dkSybaseASE) or lPrecUndef) then begin
if FColumnSize < C_FD_DefNumericSize then
FColumnSize := FColumnSize + C_DEF_NUM_SCALE;
FScale := C_DEF_NUM_SCALE;
end;
FDataSize := CalcDataSize(FColumnSize);
FIsCurrency := ((ColumnSize = 19) or (ColumnSize = 10)) and (Scale = 4) and
Statement.MoneySupported;
end
else if ((ParamType = SQL_PARAM_OUTPUT) or (ParamType = SQL_PARAM_OUTPUT_STREAM)) and (
(SQLDataType = SQL_LONGVARCHAR) or (SQLDataType = SQL_WLONGVARCHAR) or
(SQLDataType = SQL_LONGVARBINARY) or
(SQLDataType = SQL_INFX_UDT_BLOB) or (SQLDataType = SQL_INFX_UDT_CLOB)) then begin
FDataSize := 8000;
FColumnSize := FDataSize;
if SQLDataType = SQL_WLONGVARCHAR then
FColumnSize := FColumnSize div SizeOf(SQLWChar);
end
else if SQLDataType = SQL_SS_TABLE then begin
FScale := 0;
FColumnSize := High(SQLULen);
FDataSize := 0;
end
else
FDataSize := CalcDataSize(FColumnSize);
FLongData := ForceLongData;
if not LongData then
case CDataType of
SQL_C_CHAR,
SQL_C_WCHAR,
SQL_C_BINARY:
case SQLDataType of
SQL_LONGVARCHAR,
SQL_WLONGVARCHAR,
SQL_LONGVARBINARY,
SQL_DBCLOB,
SQL_XML,
SQL_BLOB,
SQL_CLOB,
SQL_SS_VARIANT,
SQL_SS_UDT,
SQL_SS_XML,
SQL_INFX_UDT_BLOB,
SQL_INFX_UDT_CLOB,
SQL_TD_XML,
SQL_TD_JSON,
SQL_TD_WJSON:
FLongData := True;
SQL_CHAR,
SQL_VARCHAR:
FLongData := (DataSize = MAXINT) or
not IsParameter and (DataSize > Statement.MaxStringSize + SizeOf(SQLChar));
SQL_BINARY,
SQL_VARBINARY:
FLongData := (DataSize = MAXINT) or
not IsParameter and (DataSize > Statement.MaxStringSize);
SQL_WCHAR,
SQL_WVARCHAR,
SQL_GRAPHIC,
SQL_VARGRAPHIC,
SQL_LONGVARGRAPHIC:
FLongData := (DataSize = MAXINT) or
not IsParameter and (DataSize > Statement.MaxStringSize + SizeOf(SQLWChar));
end;
SQL_C_DEFAULT:
case SQLDataType of
SQL_SS_TABLE:
FLongData := True;
end;
end;
if LongData and (Connection.DriverEnvVersion >= ovODBC38) then
case FParamType of
SQL_PARAM_INPUT_OUTPUT: FParamType := SQL_PARAM_INPUT_OUTPUT_STREAM;
SQL_PARAM_OUTPUT: FParamType := SQL_PARAM_OUTPUT_STREAM;
end;
FLateBinding := LongData or FForceLateBinding;
ResetFlagsUpdated;
end;
{-------------------------------------------------------------------------------}
procedure TODBCVariable.ResetFlagsUpdated;
begin
FFlagsUpdated := True;
end;
{-------------------------------------------------------------------------------}
function TODBCVariable.GetDumpLabel: string;
begin
{$IFDEF FireDAC_MONITOR}
if FDumpLabel <> '' then
Result := FDumpLabel
else
{$ENDIF}
if Name <> '' then
Result := Name
else
Result := Format('#%d', [Position]);
end;
{$IFDEF FireDAC_MONITOR}
{-------------------------------------------------------------------------------}
function TODBCVariable.DumpValue(AIndex: SQLULen; var ASize: SQLLen): String;
const
C_IntNames: array [SQL_IS_UNKNOWN .. SQL_IS_MINUTE_TO_SECOND] of String = ('', 'y',
'mo', 'd', 'h', 'mi', 's', 'y-mo', 'd-h', 'd-mi', 'd-s', 'h-mi', 'h-s', 'mi-s');
var
pData: SQLPointer;
rBCD: TBcd;
iLen: Integer;
aBuff: array [0 .. 127] of Char;
pTime2: PSQLSSTime2Struct;
pDate: PSQLDateStruct;
pTime: PSQLTimeStruct;
pTS: PODBCTimeStamp;
pInt: PSQLInterval;
begin
pData := nil;
if not GetData(AIndex, pData, ASize, True) then
Result := 'NULL'
else begin
case CDataType of
SQL_C_UTINYINT:
Result := Format('%u', [SQLByte(pData^)]);
SQL_C_STINYINT,
SQL_C_TINYINT:
Result := Format('%d', [SQLSChar(pData^)]);
SQL_C_USHORT:
Result := Format('%u', [SQLUSmallint(pData^)]);
SQL_C_SSHORT,
SQL_C_SHORT:
Result := Format('%d', [SQLSmallint(pData^)]);
SQL_C_ULONG:
Result := Format('%u', [SQLUInteger(pData^)]);
SQL_C_SLONG,
SQL_C_LONG:
Result := Format('%d', [SQLInteger(pData^)]);
SQL_C_UBIGINT:
Result := Format('%u', [SQLUBigInt(pData^)]);
SQL_C_SBIGINT:
Result := Format('%d', [SQLBigInt(pData^)]);
SQL_C_BIT:
if PSQLByte(pData)^ <> 0 then
Result := S_FD_True
else
Result := S_FD_False;
SQL_C_FLOAT:
Result := Format('%f', [SQLReal(pData^)]);
SQL_C_DOUBLE:
Result := Format('%f', [SQLDouble(pData^)]);
SQL_C_NUMERIC:
begin
ODBCNumeric2BCD(PSQLNumericRec(pData)^, rBCD);
FDBCD2Str(aBuff, iLen, rBCD, Char(DecimalSeparator));
SetString(Result, aBuff, iLen);
end;
SQL_C_BINARY:
if SQLDataType = SQL_SS_TIME2 then begin
pTime2 := PSQLSSTime2Struct(pData);
Result := Format('%.2d:%.2d:%.2d.%.3u', [pTime2^.Hour, pTime2^.Minute,
pTime2^.Second, pTime2^.Fraction]);
end
else if ASize > 512 then
Result := '(truncated at 512) ' + FDBin2Hex(pData, 512) + ' ...'
else
Result := FDBin2Hex(pData, ASize);
SQL_C_CHAR:
if ASize > 1024 then
Result := '(truncated at 1024) ''' +
Connection.FEncoder.Decode(pData, 1024, ecANSI) + ' ...'''
else
Result := '''' + Connection.FEncoder.Decode(pData, ASize, ecANSI) + '''';
SQL_C_WCHAR:
if ASize > 1024 then begin
SetString(Result, PWideChar(pData), 1024);
Result := '(truncated at 1024) ''' + Result + ' ...''';
end
else begin
SetString(Result, PWideChar(pData), ASize);
Result := '''' + Result + '''';
end;
SQL_C_TYPE_DATE,
SQL_C_DATE:
begin
pDate := PSQLDateStruct(pData);
Result := Format('%.4d-%.2d-%.2d', [pDate^.Year, pDate^.Month, pDate^.Day]);
end;
SQL_C_TYPE_TIME,
SQL_C_TIME:
begin
pTime := PSQLTimeStruct(pData);
Result := Format('%.2d:%.2d:%.2d', [pTime^.Hour, pTime^.Minute, pTime^.Second]);
end;
SQL_C_TYPE_TIMESTAMP,
SQL_C_TIMESTAMP:
begin
pTS := PODBCTimeStamp(pData);
Result := Format('%.4d-%.2d-%.2d %.2d:%.2d:%.2d.%.3d', [pTS^.Year,
pTS^.Month, pTS^.Day, pTS^.Hour, pTS^.Minute, pTS^.Second, pTS^.Fraction]);
end;
SQL_C_INTERVAL_YEAR..
SQL_C_INTERVAL_MINUTE_TO_SECOND:
begin
pInt := PSQLInterval(pData);
case pInt^.Interval_type of
SQL_IS_YEAR,
SQL_IS_MONTH,
SQL_IS_YEAR_TO_MONTH:
Result := Format('%d-%d', [pInt^.YearMonth.Year, pInt^.YearMonth.Month]);
SQL_IS_DAY,
SQL_IS_HOUR,
SQL_IS_MINUTE,
SQL_IS_SECOND,
SQL_IS_DAY_TO_HOUR,
SQL_IS_DAY_TO_MINUTE,
SQL_IS_DAY_TO_SECOND,
SQL_IS_HOUR_TO_MINUTE,
SQL_IS_HOUR_TO_SECOND,
SQL_IS_MINUTE_TO_SECOND:
Result := Format('%d %d:%d:%d.%d', [pInt^.DaySecond.Day, pInt^.DaySecond.Hour,
pInt^.DaySecond.Minute, pInt^.DaySecond.Second, pInt^.DaySecond.Fraction]);
else
ASSERT(False);
end;
if pInt^.Interval_sign = SQL_TRUE then
Result := '-' + Result;
Result := Result + ' ' + C_IntNames[pInt^.Interval_type];
end;
SQL_C_GUID:
Result := GUIDToString(PSQLGUID(pData)^);
else
Result := Format('<unsupported data type [%d]>', [CDataType]);
end;
end;
end;
{-------------------------------------------------------------------------------}
function TODBCVariable.DumpValue(AIndex: SQLULen): String;
var
iSize: SQLLen;
begin
Result := DumpValue(AIndex, iSize);
end;
{-------------------------------------------------------------------------------}
function TODBCVariable.DumpCDataType: String;
begin
case CDataType of
SQL_C_STINYINT: Result := 'STINYINT';
SQL_C_UTINYINT: Result := 'UTINYINT';
SQL_C_TINYINT: Result := 'TINYINT';
SQL_C_SSHORT: Result := 'SSHORT';
SQL_C_USHORT: Result := 'USHORT';
SQL_C_SHORT: Result := 'SHORT';
SQL_C_SLONG: Result := 'SLONG';
SQL_C_ULONG: Result := 'ULONG';
SQL_C_LONG: Result := 'LONG';
SQL_C_SBIGINT: Result := 'SBIGINT';
SQL_C_UBIGINT: Result := 'UBIGINT';
SQL_C_BIT: Result := 'BIT';
SQL_C_FLOAT: Result := 'FLOAT';
SQL_C_DOUBLE: Result := 'DOUBLE';
SQL_C_NUMERIC: Result := 'NUMERIC';
SQL_C_BINARY: Result := 'BINARY';
SQL_C_CHAR: Result := 'CHAR';
SQL_C_WCHAR: Result := 'WCHAR';
SQL_C_TYPE_DATE: Result := 'TYPE_DATE';
SQL_C_DATE: Result := 'DATE';
SQL_C_TYPE_TIME: Result := 'TYPE_TIME';
SQL_C_TIME: Result := 'TIME';
SQL_C_TYPE_TIMESTAMP: Result := 'TYPE_TIMESTAMP';
SQL_C_TIMESTAMP: Result := 'TIMESTAMP';
SQL_C_GUID: Result := 'GUID';
SQL_C_INTERVAL_YEAR: Result := 'INTERVAL_YEAR';
SQL_C_INTERVAL_MONTH: Result := 'INTERVAL_MONTH';
SQL_C_INTERVAL_DAY: Result := 'INTERVAL_DAY';
SQL_C_INTERVAL_HOUR: Result := 'INTERVAL_HOUR';
SQL_C_INTERVAL_MINUTE: Result := 'INTERVAL_MINUTE';
SQL_C_INTERVAL_SECOND: Result := 'INTERVAL_SECOND';
SQL_C_INTERVAL_YEAR_TO_MONTH: Result := 'INTERVAL_YEAR_TO_MONTH';
SQL_C_INTERVAL_DAY_TO_HOUR: Result := 'INTERVAL_DAY_TO_HOUR';
SQL_C_INTERVAL_DAY_TO_MINUTE: Result := 'INTERVAL_DAY_TO_MINUTE';
SQL_C_INTERVAL_DAY_TO_SECOND: Result := 'INTERVAL_DAY_TO_SECOND';
SQL_C_INTERVAL_HOUR_TO_MINUTE: Result := 'INTERVAL_HOUR_TO_MINUTE';
SQL_C_INTERVAL_HOUR_TO_SECOND: Result := 'INTERVAL_HOUR_TO_SECOND';
SQL_C_INTERVAL_MINUTE_TO_SECOND: Result := 'INTERVAL_MINUTE_TO_SECOND';
else Result := '#' + IntToStr(CDataType);
end;
end;
{-------------------------------------------------------------------------------}
function TODBCVariable.DumpParamType: String;
begin
case ParamType of
SQL_PARAM_TYPE_UNKNOWN: Result := 'UNKNOWN';
SQL_PARAM_INPUT: Result := 'INPUT';
SQL_PARAM_INPUT_OUTPUT: Result := 'INPUT_OUTPUT';
SQL_PARAM_INPUT_OUTPUT_STREAM: Result := 'PARAM_INPUT_OUTPUT_STREAM';
SQL_PARAM_OUTPUT: Result := 'OUTPUT';
SQL_PARAM_OUTPUT_STREAM: Result := 'PARAM_OUTPUT_STREAM';
SQL_RETURN_VALUE: Result := 'RETURN_VALUE';
SQL_RESULT_COL: Result := 'RESULT_COL';
end;
end;
{$ENDIF}
{-------------------------------------------------------------------------------}
{ TODBCParameter }
{-------------------------------------------------------------------------------}
constructor TODBCParameter.Create;
begin
inherited Create;
FIsParameter := True;
FParamType := SQL_PARAM_INPUT;
end;
{-------------------------------------------------------------------------------}
destructor TODBCParameter.Destroy;
begin
FDFreeAndNil(FColumnList);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
function TODBCParameter.GetColumnList: TODBCVariableList;
begin
if FColumnList = nil then begin
ASSERT((Statement <> nil) and (Statement is TODBCCommandStatement));
FColumnList := TODBCVariableList.Create(TODBCCommandStatement(Statement), True, True);
end;
Result := FColumnList;
end;
{-------------------------------------------------------------------------------}
procedure TODBCParameter.InternalBind;
var
oConn: TODBCConnection;
oStmt: TODBCCommandStatement;
iColSize: SQLULen;
pToken: SQLPointer;
iTokenSize: SQLLen;
begin
if SQLDataType = SQL_REFCURSOR then
Exit;
oStmt := Statement as TODBCCommandStatement;
FBinded := False;
if not LongData then begin
FBinded := True;
oStmt.Check(oStmt.Lib.SQLBindParameter(oStmt.Handle, Position, ParamType,
CDataType, SQLDataType, ColumnSize, Scale, LocalBuffer, DataSize,
LocalBufIndicator));
end
else if SQLDataType = SQL_SS_TABLE then begin
FBinded := True;
if DataTypeName <> '' then begin
pToken := PWideChar(DataTypeName);
iTokenSize := Length(DataTypeName) * SizeOf(WideChar);
end
else begin
pToken := SQLPointer(Position);
iTokenSize := 0;
end;
oStmt.Check(oStmt.Lib.SQLBindParameter(oStmt.Handle, Position, ParamType,
CDataType, SQLDataType, ColumnSize, Scale, pToken, iTokenSize, LocalBufIndicator));
end
else begin
oConn := Connection;
if (oConn.DriverKind in [dkSQLNC, dkSQLOdbc]) and (oConn.DriverVersion >= svMSSQL2005) then
iColSize := 0
else if oConn.DriverKind = dkTeradata then
if CDataType = SQL_C_WCHAR then
iColSize := 2097088000 div 2
else
iColSize := 2097088000
else
if CDataType = SQL_C_WCHAR then
iColSize := MAXINT div 2
else
iColSize := MAXINT;
if (ParamType = SQL_PARAM_INPUT_OUTPUT_STREAM) or (ParamType = SQL_PARAM_OUTPUT_STREAM) or
(ParamType = SQL_PARAM_INPUT) then begin
FBinded := True;
if FList.ChildList then
pToken := Self
else
pToken := SQLPointer(Position);
oStmt.Check(oStmt.Lib.SQLBindParameter(oStmt.Handle, Position, ParamType,
CDataType, SQLDataType, iColSize, 0, pToken, 0, LocalBufIndicator));
end
else if PSQLPointer(LocalBuffer)^ <> nil then begin
FBinded := True;
oStmt.Check(oStmt.Lib.SQLBindParameter(oStmt.Handle, Position, ParamType,
CDataType, SQLDataType, iColSize, 0, PSQLPointer(LocalBuffer)^, 0,
LocalBufIndicator));
end;
end;
if FBinded then begin
if Name <> '' then
oStmt.Check(oStmt.Lib.SQLSetDescField(oStmt.IMP_PARAM_DESC, Position,
SQL_DESC_NAME, PSQLChar(Name), Length(Name) * SizeOf(Char)));
SetBindAttributes(SQL_ATTR_APP_PARAM_DESC);
if (FColumnList <> nil) and (FColumnList.Count > 0) then begin
oStmt.SS_PARAM_FOCUS := Position;
try
FColumnList.Bind(1, True);
finally
oStmt.SS_PARAM_FOCUS := 0;
end;
end;
end;
end;
{-------------------------------------------------------------------------------}
function TODBCParameter.GetDecimalSeparator: Char;
begin
Result := Connection.DecimalSepPar;
end;
{-------------------------------------------------------------------------------}
class function TODBCParameter.GetDescriptorType: SQLSmallint;
begin
Result := SQL_APD_TYPE;
end;
{-------------------------------------------------------------------------------}
procedure TODBCParameter.SetParamType(const AValue: SQLSmallint);
begin
if FParamType <> AValue then begin
ASSERT(AValue <> SQL_RESULT_COL);
FParamType := AValue;
FFlagsUpdated := False;
end;
end;
{-------------------------------------------------------------------------------}
{ TODBCColumn }
{-------------------------------------------------------------------------------}
constructor TODBCColumn.Create;
begin
inherited Create;
FIsParameter := False;
FParamType := SQL_RESULT_COL;
end;
{-------------------------------------------------------------------------------}
procedure TODBCColumn.InternalBind;
var
oStmt: TODBCStatementBase;
begin
oStmt := Statement;
FBinded := False;
if not LateBinding then begin
FBinded := True;
oStmt.Check(oStmt.Lib.SQLBindCol(oStmt.Handle, Position, CDataType,
LocalBuffer, DataSize, LocalBufIndicator));
end;
SetBindAttributes(SQL_ATTR_APP_ROW_DESC);
end;
{-------------------------------------------------------------------------------}
function TODBCColumn.GetDecimalSeparator: Char;
begin
if SQLDataType = SQL_DECFLOAT then
Result := '.'
else
Result := Connection.DecimalSepCol;
end;
{-------------------------------------------------------------------------------}
class function TODBCColumn.GetDescriptorType: SQLSmallint;
begin
Result := SQL_ARD_TYPE;
end;
{-------------------------------------------------------------------------------}
{ TODBCVariableList }
{-------------------------------------------------------------------------------}
constructor TODBCVariableList.Create(AOwner: TODBCStatementBase; AParams, AChildList: Boolean);
begin
ASSERT(AOwner <> nil);
inherited Create;
FList := TFDObjList.Create;
FOwner := AOwner;
FParameters := AParams;
FChildList := AChildList;
end;
{-------------------------------------------------------------------------------}
destructor TODBCVariableList.Destroy;
begin
Clear;
FDFreeAndNil(FList);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
procedure TODBCVariableList.Bind(ARowCount: SQLULen; AFixedLenOnly: Boolean);
begin
ASSERT(Count > 0);
if FBuffer = nil then
FBuffer := TODBCPageBuffer.Create(Self);
if (FBuffer.RowCount <> ARowCount) or not FBuffer.FIsAllocated then begin
if FBuffer.FIsAllocated then
FBuffer.FreeBuffers;
FBuffer.FRowCount := ARowCount;
FBuffer.AllocBuffers;
Rebind(AFixedLenOnly);
UpdateHasLateBindedVars;
end;
end;
{-------------------------------------------------------------------------------}
procedure TODBCVariableList.Rebind(AFixedLenOnly: Boolean = False);
var
i: Integer;
oVar: TODBCVariable;
begin
for i := 0 to Count - 1 do begin
oVar := Items[i];
if not (AFixedLenOnly and ((oVar.CDataType = SQL_C_CHAR) or
(oVar.CDataType = SQL_C_WCHAR) or (oVar.CDataType = SQL_C_BINARY))) or
(oVar.ParamType in [SQL_PARAM_INPUT, SQL_PARAM_INPUT_OUTPUT, SQL_PARAM_INPUT_OUTPUT_STREAM]) then
oVar.Bind;
end;
end;
{-------------------------------------------------------------------------------}
function TODBCVariableList.Add(AVar: TODBCVariable): TODBCVariable;
begin
ASSERT(Parameters and (AVar is TODBCParameter) or
not Parameters and (AVar is TODBCColumn));
Result := AVar;
FList.Add(AVar);
AVar.FList := Self;
end;
{-------------------------------------------------------------------------------}
procedure TODBCVariableList.Clear;
var
i: Integer;
begin
// Do not use FreeAndNil here, because destructor will call methods
// checking that FBuffer reference is not nil
if FBuffer <> nil then begin
FDFree(FBuffer);
FBuffer := nil;
end;
for i := 0 to FList.Count - 1 do
FDFree(TODBCVariable(FList[i]));
FList.Clear;
end;
{-------------------------------------------------------------------------------}
function TODBCVariableList.GetCount: Integer;
begin
Result := FList.Count;
end;
{-------------------------------------------------------------------------------}
function TODBCVariableList.GetItems(AIndex: Integer): TODBCVariable;
begin
Result := TODBCVariable(FList[AIndex]);
end;
{-------------------------------------------------------------------------------}
procedure TODBCVariableList.UpdateHasLateBindedVars;
var
i: Integer;
begin
FHasLateBindedVars := False;
for i := 0 to Count - 1 do
if Items[i].LateBinding then begin
FHasLateBindedVars := True;
Exit;
end;
end;
{-------------------------------------------------------------------------------}
function TODBCVariableList.FindByToken(ApToken: SQLPointer): TODBCVariable;
var
i: Integer;
oVar: TODBCVariable;
oPar: TODBCParameter;
begin
if NativeUInt(ApToken) < $FFFF then
Result := Items[NativeUInt(ApToken) - 1]
else begin
Result := nil;
for i := 0 to Count - 1 do begin
oVar := Items[i];
if oVar = ApToken then
Result := oVar
else if oVar.IsParameter then begin
oPar := TODBCParameter(oVar);
if (oPar.DataTypeName <> '') and
(StrLIComp(PChar(ApToken), PChar(oPar.DataTypeName), Length(oPar.DataTypeName)) = 0) then
Result := oVar
else if oPar.FColumnList <> nil then
Result := oPar.FColumnList.FindByToken(ApToken)
end;
if Result <> nil then
Break;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TODBCVariableList.ResetDataReaders;
var
i: Integer;
begin
for i := 0 to Count - 1 do
Items[i].FDataReader := nil;
end;
{-------------------------------------------------------------------------------}
{ TODBCPageBuffer }
{-------------------------------------------------------------------------------}
// ODBC column-wise page buffer. Row-wise binding is not used due to:
// - less stable than column-wise binding
// - less performant than column-wise binding
constructor TODBCPageBuffer.Create(AVarList: TODBCVariableList);
begin
ASSERT(AVarList <> nil);
inherited Create;
FVariableList := AVarList;
AVarList.FBuffer := Self;
FRowCount := 1;
end;
{-------------------------------------------------------------------------------}
destructor TODBCPageBuffer.Destroy;
begin
if FIsAllocated then
FreeBuffers;
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
procedure TODBCPageBuffer.AllocBuffers;
var
i: Integer;
pLocal: Pointer;
oVar: TODBCVariable;
begin
ASSERT(not FIsAllocated);
FIsAllocated := True;
if not FVariableList.ChildList then
SetStmtAttributes;
for i := 0 to FVariableList.Count - 1 do begin
oVar := FVariableList[i];
oVar.UpdateFlags;
if oVar.LongData then begin
GetMem(pLocal, SizeOf(Pointer) * RowCount);
FillChar(pLocal^, SizeOf(Pointer) * RowCount, 0);
end
else
GetMem(pLocal, oVar.DataSize * NativeInt(RowCount));
oVar.LocalBuffer := pLocal;
GetMem(pLocal, SizeOf(SQLLen) * RowCount);
FillChar(pLocal^, SizeOf(SQLLen) * RowCount, $FF);
oVar.LocalBufIndicator := pLocal;
end;
end;
{-------------------------------------------------------------------------------}
procedure TODBCPageBuffer.FreeBuffers;
var
i: Integer;
j: SQLUInteger;
oVar: TODBCVariable;
begin
// Workaround for AV in ODBC drivers at reexecuting / unpreparing:
// Advantage: clear ROWS_FETCHED_PTR
// Teradata: clear ROW_STATUS_PTR
if not FVariableList.Parameters then begin
FVariableList.Owner.ROWS_FETCHED_PTR := nil;
FVariableList.Owner.ROW_STATUS_PTR := nil;
end;
ASSERT(FIsAllocated and (FVariableList.FBuffer = Self));
try
for i := 0 to FVariableList.Count - 1 do begin
oVar := FVariableList[i];
if oVar.LongData then
for j := 0 to FRowCount - 1 do
oVar.FreeLongData(j);
if oVar.LocalBuffer <> nil then begin
FreeMem(oVar.LocalBuffer);
oVar.LocalBuffer := nil;
end;
if oVar.LocalBufIndicator <> nil then begin
FreeMem(oVar.LocalBufIndicator);
oVar.LocalBufIndicator := nil;
end;
end;
finally
FIsAllocated := False;
FRowCount := 1;
end;
end;
{-------------------------------------------------------------------------------}
function TODBCPageBuffer.GetPageSize: SQLULen;
begin
Result := RowSize * RowCount;
end;
{-------------------------------------------------------------------------------}
function TODBCPageBuffer.GetRowSize: SQLULen;
var
i: Integer;
oVar: TODBCVariable;
begin
Result := 0;
for i := 0 to FVariableList.Count - 1 do begin
oVar := FVariableList[i];
if not oVar.LongData then
Inc(Result, oVar.DataSize + SizeOf(SQLLen))
else
Inc(Result, SizeOf(Pointer) + SizeOf(SQLLen));
end;
end;
{-------------------------------------------------------------------------------}
function TODBCPageBuffer.GetRowStatusArr(AIndex: SQLULen): SQLUSmallint;
begin
ASSERT((AIndex < FRowCount) and (AIndex < Length(FRowStatusArr)));
Result := FRowStatusArr[AIndex];
end;
{-------------------------------------------------------------------------------}
function TODBCPageBuffer.GetRowOperationArr(AIndex: SQLULen): SQLUSmallint;
begin
ASSERT((AIndex < FRowCount) and (AIndex < Length(FRowOperationArr)));
Result := FRowOperationArr[AIndex];
end;
{-------------------------------------------------------------------------------}
procedure TODBCPageBuffer.SetStmtAttributes;
var
oCmd: TODBCCommandStatement;
oStmt: TODBCStatementBase;
lPrevIgnoreErrors: Boolean;
begin
// Some old ODBC drivers (AcuODBC v5) return "optional feature is not
// implemented" on setting SQL_ATTR_ROW_BIND_TYPE. SQL_BIND_BY_COLUMN
// is the default value, so just ignore error.
oStmt := FVariableList.Owner;
lPrevIgnoreErrors := oStmt.IgnoreErrors;
oStmt.IgnoreErrors := True;
try
oStmt.ROW_BIND_TYPE := SQL_BIND_BY_COLUMN;
finally
oStmt.IgnoreErrors := lPrevIgnoreErrors;
end;
if FVariableList.Parameters then begin
oCmd := oStmt as TODBCCommandStatement;
if oCmd.ParamSetSupported then begin
// +1 is a workaround for AV on fetching using Parkway Micro Focus ODBC driver
SetLength(FRowStatusArr, FRowCount + 1);
oCmd.PARAMSET_SIZE := FRowCount;
oCmd.PARAM_STATUS_PTR := @FRowStatusArr[0];
oCmd.PARAMS_PROCESSED_PTR := @FRowsProcessed;
end;
end
else if oStmt.RowSetSupported then begin
// +1 is a workaround for AV on fetching using Parkway Micro Focus ODBC driver
SetLength(FRowStatusArr, FRowCount + 1);
oStmt.ROW_ARRAY_SIZE := FRowCount;
oStmt.ROW_STATUS_PTR := @FRowStatusArr[0];
oStmt.ROWS_FETCHED_PTR := @FRowsProcessed;
end;
end;
{-------------------------------------------------------------------------------}
procedure TODBCPageBuffer.GetDataPtr(AVar: TODBCVariable; AIndex: SQLULen;
out ApData: SQLPointer; out ApInd: PSQLLen);
begin
ASSERT((AVar.LocalBuffer <> nil) and (AIndex < FRowCount));
if AVar.LongData then
ApData := SQLPointer(NativeInt(AVar.LocalBuffer) + NativeInt(AIndex) * SizeOf(Pointer))
else
ApData := SQLPointer(NativeInt(AVar.LocalBuffer) + NativeInt(AIndex) * AVar.DataSize);
ApInd := PSQLLen(NativeInt(AVar.LocalBufIndicator) + NativeInt(AIndex) * SizeOf(SQLLen));
end;
{-------------------------------------------------------------------------------}
procedure TODBCPageBuffer.ShiftBuffersPtr(ARowCount: SQLLen);
var
i: Integer;
oVar: TODBCVariable;
begin
for i := 0 to FVariableList.Count - 1 do begin
oVar := FVariableList[i];
// Cast to NativeInt to avoid "Integer overflow" on x64.
// Casting to NativeUInt leads to "Integer overflow" on x32.
if not oVar.LongData then
Inc(NativeInt(oVar.FLocalBuffer), oVar.DataSize * ARowCount)
else
Inc(NativeInt(oVar.FLocalBuffer), SizeOf(SQLPointer) * ARowCount);
Inc(NativeInt(oVar.FLocalBufIndicator), SizeOf(SQLLen) * ARowCount);
end;
FShifted := FShifted + ARowCount;
FVariableList.Rebind;
end;
{-------------------------------------------------------------------------------}
procedure TODBCPageBuffer.UnShift;
begin
if Shifted <> 0 then
ShiftBuffersPtr(-Shifted);
end;
{-------------------------------------------------------------------------------}
procedure TODBCPageBuffer.SetOperationRange(ARowCount, AOffset: SQLULen);
var
i: SQLUInteger;
begin
ASSERT((AOffset >= 0) and (AOffset < FRowCount));
ASSERT((ARowCount >= 1) and (ARowCount <= FRowCount));
ASSERT(AOffset < ARowCount);
for i := 0 to AOffset - 1 do
FRowOperationArr[i] := SQL_PARAM_IGNORE;
for i := AOffset to ARowCount - 1 do
FRowOperationArr[i] := SQL_PARAM_PROCEED;
for i := ARowCount to FRowCount - 1 do
FRowOperationArr[i] := SQL_PARAM_IGNORE;
end;
{-------------------------------------------------------------------------------}
{ TODBCStatementBase }
{-------------------------------------------------------------------------------}
constructor TODBCStatementBase.Create(AOwner: TODBCConnection; AOwningObj: TObject);
begin
inherited Create;
FOwner := AOwner;
FOwningObj := AOwningObj;
FHandleType := SQL_HANDLE_STMT;
FODBCLib := FOwner.Lib;
AllocHandle;
FColumnList := TODBCVariableList.Create(Self, False, False);
FMaxStringSize := C_FD_DefMaxStrSize;
FStrsTrim := False;
FStrsEmpty2Null := True;
FPieceBuffLen := C_FD_DefPieceBuffLen;
FRowSetSupported := True;
end;
{-------------------------------------------------------------------------------}
destructor TODBCStatementBase.Destroy;
begin
// MSSQL: after connection losting releasing ENV handle mai raise exception
IgnoreErrors := True;
Unprepare;
FDFreeAndNil(FColumnList);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
procedure TODBCStatementBase.ColAttributeInt(AColNum: SQLUSmallint;
AFieldId: SQLUSmallint; var AAttr: SQLLen);
begin
Check(Lib.SQLColAttributeInt(FHandle, AColNum, AFieldId, nil, 0, nil, AAttr));
end;
{-------------------------------------------------------------------------------}
procedure TODBCStatementBase.ColAttributeIntSilent(AColNum, AFieldId: SQLUSmallint;
var AAttr: SQLLen);
var
iRet: SQLReturn;
begin
iRet := Lib.SQLColAttributeInt(FHandle, AColNum, AFieldId, nil, 0, nil, AAttr);
if not ((iRet = SQL_SUCCESS) or (iRet = SQL_SUCCESS_WITH_INFO)) then
AAttr := 0;
end;
{-------------------------------------------------------------------------------}
procedure TODBCStatementBase.ColAttributeSmallint(AColNum, AFieldId: SQLUSmallint;
var AAttr: SQLSmallint);
begin
Check(Lib.SQLColAttribute(FHandle, AColNum, AFieldId, nil, 0, nil, @AAttr));
end;
{-------------------------------------------------------------------------------}
procedure TODBCStatementBase.ColAttributeSmallintSilent(AColNum, AFieldId: SQLUSmallint;
var AAttr: SQLSmallint);
var
iRet: SQLReturn;
begin
iRet := Lib.SQLColAttribute(FHandle, AColNum, AFieldId, nil, 0, nil, @AAttr);
if not ((iRet = SQL_SUCCESS) or (iRet = SQL_SUCCESS_WITH_INFO)) then
AAttr := 0;
end;
{-------------------------------------------------------------------------------}
procedure TODBCStatementBase.ColAttributeString(AColNum, AFieldId: SQLUSmallint;
var AAttr: String);
var
iStringLen: SQLSmallint;
begin
SetLength(AAttr, C_STRING_ATTR_MAXLEN);
iStringLen := 0;
Check(Lib.SQLColAttributeString(FHandle, AColNum, AFieldId, SQLPointer(AAttr),
C_STRING_ATTR_MAXLEN * SizeOf(Char), iStringLen, nil));
ODBCSetLength(AAttr, iStringLen div SizeOf(Char));
end;
{-------------------------------------------------------------------------------}
procedure TODBCStatementBase.GetNonStrAttribute(AAttr: SQLInteger; ApValue: SQLPointer);
var
iStringLen: SQLInteger;
begin
iStringLen := 0;
Check(Lib.SQLGetStmtAttr(FHandle, AAttr, ApValue, 0, iStringLen));
end;
{-------------------------------------------------------------------------------}
procedure TODBCStatementBase.GetStrAttribute(AAttr: SQLInteger; out AValue: String);
var
iStringLen: SQLInteger;
begin
SetLength(AValue, SQL_MAX_MESSAGE_LENGTH);
iStringLen := 0;
Check(Lib.SQLGetStmtAttr(FHandle, AAttr, PChar(AValue),
SQL_MAX_MESSAGE_LENGTH * SizeOf(Char), iStringLen));
ODBCSetLength(AValue, iStringLen div SizeOf(Char));
end;
{-------------------------------------------------------------------------------}
procedure TODBCStatementBase.SetAttribute(AAttr: SQLInteger; ApValue: SQLPointer;
AType: SQLInteger);
begin
if ((AType = 0) or (AType = SQL_NTS)) and (ApValue <> nil) then
AType := StrLen(PChar(ApValue)) * SizeOf(Char);
Check(Lib.SQLSetStmtAttr(FHandle, AAttr, ApValue, AType));
end;
{-------------------------------------------------------------------------------}
function TODBCStatementBase.GetSQLLenDiag(ARecNo, ADiagID: Integer): SQLLen;
var
iLen: SQLSmallint;
iRet: SQLReturn;
begin
iLen := 0;
Result := 0;
iRet := Lib.SQLGetDiagField(FHandleType, FHandle, SQLSmallint(ARecNo),
SQLSmallint(ADiagID), @Result, SQL_IS_INTEGER, iLen);
if (iRet <> SQL_SUCCESS) and (iRet <> SQL_NO_DATA) then
Check(iRet);
end;
{-------------------------------------------------------------------------------}
function TODBCStatementBase.GetIntDiag(ARecNo, ADiagID: Integer): SQLInteger;
var
iLen: SQLSmallint;
iRet: SQLReturn;
begin
iLen := 0;
Result := 0;
iRet := Lib.SQLGetDiagField(FHandleType, FHandle, SQLSmallint(ARecNo),
SQLSmallint(ADiagID), @Result, SQL_IS_INTEGER, iLen);
if (iRet <> SQL_SUCCESS) and (iRet <> SQL_NO_DATA) then
Check(iRet);
end;
{-------------------------------------------------------------------------------}
function TODBCStatementBase.GetStrDiag(ARecNo, ADiagID: Integer): String;
var
aBuff: array [0 .. SQL_MAX_MESSAGE_LENGTH] of Char;
iLen: SQLSmallint;
iRet: SQLReturn;
begin
iLen := 0;
Result := '';
iRet := Lib.SQLGetDiagField(FHandleType, FHandle, SQLSmallint(ARecNo),
SQLSmallint(ADiagID), @aBuff[0], SQL_MAX_MESSAGE_LENGTH, iLen);
if (iRet <> SQL_SUCCESS) and (iRet <> SQL_NO_DATA) then
Check(iRet)
else
SetString(Result, aBuff, iLen div SizeOf(Char));
end;
{-------------------------------------------------------------------------------}
function TODBCStatementBase.GetUSmallIntDiag(ARecNo, ADiagID: Integer): SQLUSmallint;
var
iLen: SQLSmallint;
iRet: SQLReturn;
begin
iLen := 0;
Result := 0;
iRet := Lib.SQLGetDiagField(FHandleType, FHandle, SQLSmallint(ARecNo),
SQLSmallint(ADiagID), @Result, SQL_IS_USMALLINT, iLen);
if (iRet <> SQL_SUCCESS) and (iRet <> SQL_NO_DATA) then
Check(iRet);
end;
{-------------------------------------------------------------------------------}
function TODBCStatementBase.GetCursorName: String;
var
iBufferLen: SQLSmallint;
iStringLen: SQLSmallint;
begin
iBufferLen := Connection.GetInfoOptionSmInt(SQL_MAX_CURSOR_NAME_LEN);
// FIPS Intermediate level conformant value
if iBufferLen = 0 then
iBufferLen := 128;
SetLength(Result, iBufferLen);
iStringLen := 0;
if Lib.SQLGetCursorName(FHandle, PSQLChar(Result), iBufferLen, iStringLen) = SQL_SUCCESS then
ODBCSetLength(Result, iStringLen)
else
Result := '';
end;
{-------------------------------------------------------------------------------}
procedure TODBCStatementBase.SetCursorName(const AValue: String);
begin
Check(Lib.SQLSetCursorName(FHandle, PSQLChar(AValue), SQLSmallint(Length(AValue))));
end;
{-------------------------------------------------------------------------------}
function TODBCStatementBase.GetQueryTimeout: SQLULen;
begin
FQueryTimeout := GetSQLULenAttribute(SQL_ATTR_QUERY_TIMEOUT);
Result := FQueryTimeout;
end;
{-------------------------------------------------------------------------------}
procedure TODBCStatementBase.SetQueryTimeout(const AValue: SQLULen);
begin
if FQueryTimeout <> AValue then begin
FQueryTimeout := AValue;
SetSQLULenAttribute(SQL_ATTR_QUERY_TIMEOUT, AValue);
end;
end;
{-------------------------------------------------------------------------------}
function TODBCStatementBase.NumResultCols: SQLSmallint;
begin
if FResultCols = -1 then begin
FResultCols := 0;
Check(Lib.SQLNumResultCols(FHandle, FResultCols));
end;
Result := FResultCols;
end;
{-------------------------------------------------------------------------------}
function TODBCStatementBase.ResultColsExists: Boolean;
begin
if FResultCols = -1 then begin
FResultCols := 0;
Result := Lib.SQLNumResultCols(FHandle, FResultCols) = SQL_SUCCESS;
end
else
Result := True;
Result := Result and (FResultCols > 0);
end;
{-------------------------------------------------------------------------------}
procedure TODBCStatementBase.BindColumns(ARowCount: SQLULen);
begin
FColumnList.Bind(ARowCount, False);
end;
{-------------------------------------------------------------------------------}
procedure TODBCStatementBase.UnbindColumns;
begin
if (FColumnList <> nil) and (FColumnList.Count > 0) then begin
FColumnList.Clear;
Check(Lib.SQLFreeStmt(FHandle, SQL_UNBIND));
end;
end;
{-------------------------------------------------------------------------------}
function TODBCStatementBase.AddCol(APos, ASQLType, ACType: SQLSmallint;
ALen: SQLULen): TODBCColumn;
begin
Result := TODBCColumn(ColumnList.Add(TODBCColumn.Create));
if ALen <> MAXINT then
Result.ColumnSize := ALen;
Result.SQLDataType := ASQLType;
Result.CDataType := ACType;
Result.Position := APos;
end;
{-------------------------------------------------------------------------------}
function TODBCStatementBase.GetLongVarPiece(AVar: TODBCVariable;
ApData: SQLPointer; ASize: SQLLen; ApInd: PSQLLen): SQLReturn;
var
iDataType: SQLSmallint;
oBuffer: TODBCPageBuffer;
iPrevRows: SQLULen;
begin
// The SQLGetData call to the Oracle ODBC driver modifies a value of
// a variable pointed by the ROWS_FETCHED_PTR. But the Fetch method
// expects the number of fetched rows. So, preserve the value.
oBuffer := AVar.FList.FBuffer;
iPrevRows := oBuffer.RowsProcessed;
try
if AVar.CDataType = SQL_C_NUMERIC then
iDataType := AVar.DescriptorType
else if AVar.MSSQLVariantBinary then
if (AVar.FCVariantSbType = 0) or (ASize = 0) then
iDataType := AVar.CDataType
else if AVar.FCVariantSbType = SQL_C_NUMERIC then
iDataType := SQL_C_CHAR
else
iDataType := AVar.FCVariantSbType
else
iDataType := AVar.CDataType;
// MSSQL: SQL Server ODBC Driver 11 fails to fetch SQL_VARIANT when
// TargetValue=nil or BufferLength=0, and returns HY008 (Win) / HY009 (UIX).
Result := Lib.SQLGetData(FHandle, AVar.Position, iDataType, ApData, ASize, ApInd);
if (Result <> SQL_NO_DATA) and
(Result <> SQL_SUCCESS_WITH_INFO) and
(Result <> SQL_SUCCESS) then
Check(Result);
finally
oBuffer.FRowsProcessed := iPrevRows;
end;
end;
{-------------------------------------------------------------------------------}
function TODBCStatementBase.GetLongVarPiece(AVar: TODBCVariable;
AIndex: Integer; ASize: SQLLen): SQLReturn;
var
pData: SQLPointer;
pInd: PSQLLen;
begin
AVar.GetDataInd(AIndex, pData, pInd);
Result := GetLongVarPiece(AVar, pData, ASize, pInd);
end;
{-------------------------------------------------------------------------------}
function TODBCStatementBase.GetLongVarFinished(ASize: SQLLen; ARet: SQLReturn;
AInd: SQLLen): Boolean;
begin
Result :=
(ARet = SQL_NO_DATA) or
(AInd = SQL_NULL_DATA) or
((AInd <= ASize) and (AInd >= 0) and (ARet <> SQL_SUCCESS_WITH_INFO));
end;
{-------------------------------------------------------------------------------}
procedure TODBCStatementBase.GetLongVar(AVar: TODBCVariable; AIndex: Integer);
var
lGetAll: Boolean;
pBuffer: SQLPointer;
ppBuffer: PSQLPointer;
pInd: PSQLLen;
iCurSize, iFetchSize, iBufferLen, iZeroBytes, iVarType: SQLLen;
iIteration: SQLInteger;
iDummy: Word;
iRet: SQLReturn;
begin
// MS SQL Server VARIANT data type fetching
if AVar.MSSQLVariantBinary then begin
ppBuffer := AVar.GetDataPtr(AIndex, pBuffer, iCurSize, pInd);
ppBuffer^ := @iDummy;
GetLongVarPiece(AVar, AIndex, 0);
ppBuffer^ := pBuffer;
if pInd^ <> SQL_NULL_DATA then begin
iVarType := 0;
ColAttributeIntSilent(AVar.Position, SQL_CA_SS_VARIANT_TYPE, iVarType);
AVar.FCVariantSbType := iVarType;
if iVarType = SQL_NUMERIC then
Inc(pInd^, 2);
if iCurSize < pInd^ then
AVar.AllocLongData(AIndex, pInd^);
GetLongVarPiece(AVar, AIndex, pInd^);
end;
end
// BLOB data
else if AVar.LongData then begin
case AVar.CDataType of
SQL_C_CHAR: iZeroBytes := SizeOf(TFDAnsiChar);
SQL_C_WCHAR: iZeroBytes := SizeOf(WideChar);
else iZeroBytes := 0;
end;
AVar.GetDataPtr(AIndex, pBuffer, iCurSize, pInd);
iIteration := 0;
iCurSize := 0;
iFetchSize := FPieceBuffLen;
iBufferLen := iFetchSize;
ppBuffer := AVar.AllocLongData(AIndex, iBufferLen);
pBuffer := ppBuffer^;
try
try
repeat
Inc(iIteration);
iRet := GetLongVarPiece(AVar, AIndex, iFetchSize);
lGetAll := GetLongVarFinished(iFetchSize, iRet, pInd^);
if not lGetAll then begin
Inc(iCurSize, iFetchSize - iZeroBytes);
iFetchSize := iBufferLen;
if iBufferLen <= $3FFFFFFF then
iBufferLen := iBufferLen * 2
else
Inc(iBufferLen, $6400000); // 100Mb
ppBuffer^ := pBuffer;
ppBuffer := AVar.AllocLongData(AIndex, iBufferLen);
pBuffer := ppBuffer^;
ppBuffer^ := SQLPointer(NativeInt(ppBuffer^) +
(iBufferLen - iFetchSize - iZeroBytes * iIteration));
end;
until lGetAll;
finally
ppBuffer^ := pBuffer;
end;
if pInd^ = SQL_NULL_DATA then
AVar.FreeLongData(AIndex)
else begin
Inc(pInd^, iCurSize);
AVar.AllocLongData(AIndex, pInd^);
end;
except
on E: EODBCNativeException do begin
AVar.FreeLongData(AIndex);
raise;
end;
end;
end
// other late binding data
else
GetLongVarPiece(AVar, AIndex, AVar.DataSize);
end;
{-------------------------------------------------------------------------------}
procedure TODBCStatementBase.FetchLateBindedColumns(AIndex: SQLULen);
var
i: Integer;
oVar: TODBCVariable;
oBuffer: TODBCPageBuffer;
begin
oBuffer := FColumnList.FBuffer;
for i := 0 to FColumnList.Count - 1 do begin
oVar := FColumnList[i];
if oVar.LateBinding then begin
// set result set position
if oBuffer.RowsProcessed > 1 then
Check(Lib.SQLSetPos(FHandle, AIndex + 1, SQL_POSITION, SQL_LOCK_NO_CHANGE));
GetLongVar(oVar, AIndex);
end;
end;
end;
{-------------------------------------------------------------------------------}
function TODBCStatementBase.Fetch(ARowCount: SQLLen = SQL_NULL_DATA): SQLULen;
var
iRet: SQLReturn;
iLastFetched: SQLLen;
iRow: SQLUInteger;
oBuffer: TODBCPageBuffer;
begin
ASSERT(ARowCount <= $FFFF);
TODBCConnection(Owner).ClearInfo;
if (ColumnList.FBuffer = nil) and (ColumnList.Count > 0) then
BindColumns(ARowCount);
oBuffer := FColumnList.FBuffer;
ASSERT((oBuffer <> nil) and (oBuffer.Shifted = 0));
Result := 0;
iLastFetched := 0;
iRow := 0;
try
repeat
if iLastFetched > 0 then
oBuffer.ShiftBuffersPtr(iLastFetched);
iRet := Lib.SQLFetch(FHandle);
if iRet = SQL_NO_DATA then
iLastFetched := 0
else begin
Check(iRet);
// RowsProcessed = 0 - this is a MySQL driver bug
// RowsProcessed = 1 - 1 row fetched only - immediatelly GetLongVarPiece,
// if RDBMS table contains only 1 row - we will exit from the cycle in the next
// iteration after iRet = SQL_NO_DATA
if (oBuffer.RowsProcessed in [0, 1]) or (oBuffer.RowCount = 1) then begin
iLastFetched := 1;
if FColumnList.HasLateBindedVars then
FetchLateBindedColumns(iRow);
end
else
iLastFetched := oBuffer.RowsProcessed;
end;
Inc(Result, iLastFetched);
Inc(iRow);
until (ARowCount = SQL_NULL_DATA) or (Result = ARowCount) or (iLastFetched = 0) or
(oBuffer.RowsProcessed > 1) or (oBuffer.RowCount = Result);
finally
oBuffer.UnShift;
end;
if oBuffer.RowsProcessed in [0, 1] then begin
if Result > 0 then
oBuffer.FRowsProcessed := Result;
end
else if (Result > 0) and FColumnList.HasLateBindedVars then
for iRow := 0 to SQLUSmallint(Result - 1) do
FetchLateBindedColumns(iRow);
{$IFDEF FireDAC_MONITOR}
if Tracing then
DumpColumns(Result, ARowCount <> Result);
{$ENDIF}
end;
{-------------------------------------------------------------------------------}
function TODBCStatementBase.MoreResults: Boolean;
var
iRes: SQLReturn;
begin
Result := False;
if FNoMoreResults then
Exit;
iRes := Lib.SQLMoreResults(FHandle);
case iRes of
SQL_SUCCESS:
begin
Result := True;
FResultCols := -1;
end;
SQL_SUCCESS_WITH_INFO:
begin
Result := True;
FResultCols := -1;
Check(iRes);
end;
SQL_NO_DATA,
// ASA: SQLMoreResults cannot return SQL_NEED_DATA, but ASA driver
// returns. It seems, it is a bug in the ODBC driver.
SQL_NEED_DATA:
begin
FNoMoreResults := True;
FResultCols := 0;
end;
else
FNoMoreResults := True;
FResultCols := 0;
Check(iRes);
end;
end;
{-------------------------------------------------------------------------------}
procedure TODBCStatementBase.Cancel;
begin
Check(Lib.SQLCancel(FHandle));
end;
{-------------------------------------------------------------------------------}
procedure TODBCStatementBase.Close;
begin
if FExecuted then begin
FExecuted := False;
FNoMoreResults := True;
FResultCols := -1;
Check(Lib.SQLFreeStmt(FHandle, SQL_CLOSE));
end;
end;
{-------------------------------------------------------------------------------}
procedure TODBCStatementBase.Unprepare;
begin
TODBCConnection(Owner).ClearInfo;
try
Close;
finally
UnbindColumns;
end;
end;
{$IFDEF FireDAC_MONITOR}
{-------------------------------------------------------------------------------}
procedure TODBCStatementBase.DumpColumns(ARows: SQLULen; AEof: Boolean);
var
i, n: Integer;
j: SQLUInteger;
iLen: SQLLen;
sVal: String;
oVar: TODBCVariable;
begin
if Tracing and (ARows > 0) then begin
for j := 0 to ARows - 1 do begin
n := 1;
Trace(ekCmdDataOut, esStart, 'Fetched', ['Row', j]);
for i := 0 to FColumnList.Count - 1 do begin
oVar := FColumnList.Items[i];
iLen := 0;
sVal := oVar.DumpValue(j, iLen);
Trace(ekCmdDataOut, esProgress, 'Column',
[String('N'), n, '@Type', oVar.DumpCDataType,
'Size', oVar.ColumnSize, 'Len', iLen, '@Data', sVal]);
Inc(n);
end;
Trace(ekCmdDataOut, esEnd, 'Fetched', ['Row', j]);
end;
if AEof then
Trace(ekCmdDataOut, esProgress, 'EOF', []);
end;
end;
{$ENDIF}
{-------------------------------------------------------------------------------}
{ TODBCCommandStatement }
{-------------------------------------------------------------------------------}
constructor TODBCCommandStatement.Create(AOwner: TODBCConnection; AOwningObj: TObject);
begin
inherited Create(AOwner, AOwningObj);
FParamList := TODBCVariableList.Create(Self, True, False);
end;
{-------------------------------------------------------------------------------}
destructor TODBCCommandStatement.Destroy;
begin
inherited Destroy;
FDFreeAndNil(FParamList);
end;
{-------------------------------------------------------------------------------}
function TODBCCommandStatement.GetPARAMSET_SIZE: SQLULen;
var
iLen: SQLInteger;
begin
iLen := 0;
if Lib.SQLGetStmtAttr(FHandle, SQL_ATTR_PARAMSET_SIZE, @Result, 0, iLen) <> SQL_SUCCESS then
Result := 1;
end;
{-------------------------------------------------------------------------------}
procedure TODBCCommandStatement.SetPARAMSET_SIZE(const AValue: SQLULen);
begin
Lib.SQLSetStmtAttr(FHandle, SQL_ATTR_PARAMSET_SIZE, PSQLUInteger(AValue), 0);
end;
{-------------------------------------------------------------------------------}
procedure TODBCCommandStatement.BindParameters(ARowCount: SQLUInteger; AFixedLenOnly: Boolean);
begin
ParamList.Bind(ARowCount, AFixedLenOnly);
end;
{-------------------------------------------------------------------------------}
procedure TODBCCommandStatement.UnbindParameters;
begin
if (ParamList <> nil) and (ParamList.Count > 0) then begin
ParamList.Clear;
Check(Lib.SQLFreeStmt(Handle, SQL_RESET_PARAMS));
end;
end;
{-------------------------------------------------------------------------------}
procedure TODBCCommandStatement.PutBlobParam(AParam: TODBCParameter; AIndex: Integer);
var
pInd: PSQLLen;
pData: SQLPointer;
iSize: SQLLen;
begin
AParam.GetDataPtr(AIndex, pData, iSize, pInd);
if pInd^ = SQL_NULL_DATA then
iSize := SQL_NULL_DATA;
// ASA: SQLPutData(..., nil, 0) raises "invalid string or buffer length".
// So, set pData to a not nil value.
if (pData = nil) and ((iSize = 0) or (iSize = SQL_NULL_DATA)) then
pData := @pData;
Check(Lib.SQLPutData(FHandle, pData, iSize));
end;
{-------------------------------------------------------------------------------}
procedure TODBCCommandStatement.PutTableParam(AParam: TODBCParameter; AIndex: Integer; AFirst: Boolean);
var
oReader: IFDPhysDataSetParamReader;
i: Integer;
pBuff: Pointer;
iLen: LongWord;
begin
oReader := AParam.DataReader as IFDPhysDataSetParamReader;
if (oReader = nil) or
AFirst and not oReader.Reset or
not AFirst and not oReader.Next then
Check(Lib.SQLPutData(FHandle, nil, 0))
else begin
for i := 0 to AParam.ColumnList.Count - 1 do begin
pBuff := nil;
iLen := 0;
oReader.GetData(i, pBuff, 0, iLen, False);
AParam.ColumnList[i].SetData(0, pBuff, iLen);
end;
Check(Lib.SQLPutData(FHandle, SQLPointer(1), 1));
end;
end;
{-------------------------------------------------------------------------------}
procedure TODBCCommandStatement.PutStreamParam(AParam: TODBCParameter; AIndex: Integer);
var
oReader: IParamStreamObject;
oStr: TStream;
oBuff: TFDBuffer;
iLen: SQLLen;
lNull: Boolean;
begin
lNull := True;
oReader := AParam.DataReader as IParamStreamObject;
if oReader <> nil then begin
oStr := oReader.GetStream(False);
if oStr <> nil then begin
lNull := False;
oStr.Position := 0;
oBuff := Connection.Encoder.Buffer;
oBuff.Check(C_FD_DefPieceBuffLen);
repeat
iLen := oStr.Read(oBuff.Ptr^, oBuff.Size);
Check(Lib.SQLPutData(FHandle, oBuff.Ptr, iLen));
until iLen <> SQLLen(oBuff.Size);
end;
end;
if lNull then
Check(Lib.SQLPutData(FHandle, nil, 0));
end;
{-------------------------------------------------------------------------------}
function TODBCCommandStatement.PutLongParams: SQLReturn;
var
pParamNum: SQLPointer;
oPar, oTVPPar: TODBCParameter;
iCurNum: SQLSmallint;
iIndex: Integer;
begin
iCurNum := -1;
oPar := nil;
FFocusedParam := nil;
iIndex := 0;
oTVPPar := nil;
repeat
pParamNum := nil;
Result := Lib.SQLParamData(FHandle, pParamNum);
// Teradata: SQLParamData after last BLOB parameter returns "invalid cursor state"
if (TODBCConnection(Owner).DriverKind = dkTeradata) and
(Result = SQL_ERROR) and (DIAG_SQLSTATE[1] = '24000') then
Result := SQL_SUCCESS
else if Result = SQL_NEED_DATA then begin
// MSSQL: subsequent SQLParamData calls for TVP return pParamNum=nil
if pParamNum <> nil then
oPar := ParamList.FindByToken(pParamNum) as TODBCParameter;
ASSERT(oPar <> nil);
if (oPar.SQLDataType <> SQL_SS_TABLE) and not oPar.FList.ChildList then begin
if iCurNum >= oPar.Position then
Inc(iIndex);
iCurNum := oPar.Position;
end;
if oPar.SQLDataType = SQL_SS_TABLE then begin
PutTableParam(oPar, iIndex, oTVPPar <> oPar);
oTVPPar := oPar;
end
else if oPar.Streamed then begin
FFocusedParam := oPar;
FFocusedResult := Result;
end
else if oPar.DataReader <> nil then
PutStreamParam(oPar, iIndex)
else
PutBlobParam(oPar, iIndex);
end;
until (Result <> SQL_NEED_DATA) or (FocusedParam <> nil);
end;
{-------------------------------------------------------------------------------}
procedure TODBCCommandStatement.GetStreamParam(AParam: TODBCParameter; AIndex: Integer);
var
oReader: IParamStreamObject;
oStr: TStream;
oBuff: TFDBuffer;
pBuffer: SQLPointer;
ppBuffer: PSQLPointer;
pInd: PSQLLen;
iSize, iZeroBytes: SQLLen;
iRet: SQLReturn;
lGetAll: Boolean;
begin
oReader := AParam.DataReader as IParamStreamObject;
if oReader <> nil then begin
oStr := oReader.GetStream(False);
if oStr <> nil then begin
case AParam.CDataType of
SQL_C_CHAR: iZeroBytes := SizeOf(TFDAnsiChar);
SQL_C_WCHAR: iZeroBytes := SizeOf(WideChar);
else iZeroBytes := 0;
end;
oStr.Position := 0;
oBuff := Connection.Encoder.Buffer;
oBuff.Check(C_FD_DefPieceBuffLen);
ppBuffer := AParam.GetDataPtr(AIndex, pBuffer, iSize, pInd);
ppBuffer^ := oBuff.Ptr;
try
repeat
iRet := GetLongVarPiece(AParam, AIndex, oBuff.Size);
lGetAll :=
(iRet = SQL_NO_DATA) or
(pInd^ = SQL_NULL_DATA) or
((pInd^ <= SQLLen(oBuff.Size)) and (pInd^ >= 0) and (iRet <> SQL_SUCCESS_WITH_INFO));
if not lGetAll then
oStr.Write(oBuff.Ptr^, SQLLen(oBuff.Size) - iZeroBytes);
until lGetAll;
finally
ppBuffer^ := pBuffer;
end;
if pInd^ <> SQL_NULL_DATA then
oStr.Write(oBuff.Ptr^, pInd^);
oStr.Size := oStr.Position;
end;
end;
end;
{-------------------------------------------------------------------------------}
function TODBCCommandStatement.GetLongParams: SQLReturn;
var
pParamNum: SQLPointer;
oPar: TODBCParameter;
iCurNum: SQLSmallint;
iIndex: Integer;
begin
iCurNum := -1;
oPar := nil;
FFocusedParam := nil;
iIndex := 0;
repeat
pParamNum := nil;
Result := Lib.SQLParamData(FHandle, pParamNum);
if Result = SQL_PARAM_DATA_AVAILABLE then begin
if pParamNum <> nil then
oPar := ParamList.FindByToken(pParamNum) as TODBCParameter;
ASSERT(oPar <> nil);
if (oPar.SQLDataType <> SQL_SS_TABLE) and not oPar.FList.ChildList then begin
if iCurNum >= oPar.Position then
Inc(iIndex);
iCurNum := oPar.Position;
end;
if oPar.SQLDataType = SQL_SS_TABLE then
ASSERT(oPar.SQLDataType <> SQL_SS_TABLE)
else if oPar.Streamed then begin
FFocusedParam := oPar;
FFocusedResult := Result;
end
else if oPar.DataReader <> nil then
GetStreamParam(oPar, iIndex)
else
GetLongVar(oPar, iIndex);
end;
until (Result <> SQL_PARAM_DATA_AVAILABLE) or (FocusedParam <> nil);
end;
{-------------------------------------------------------------------------------}
procedure TODBCCommandStatement.FlushLongData;
var
iRet: SQLReturn;
begin
iRet := SQL_NEED_DATA;
repeat
if iRet = SQL_NEED_DATA then
iRet := PutLongParams();
if iRet = SQL_PARAM_DATA_AVAILABLE then
iRet := GetLongParams();
until not ((iRet = SQL_PARAM_DATA_AVAILABLE) or (iRet = SQL_NEED_DATA));
if iRet <> SQL_NO_DATA then
Check(iRet);
end;
{-------------------------------------------------------------------------------}
procedure TODBCCommandStatement.UpdateRowsAffected(var ACount: SQLLen);
begin
ACount := -1;
// MSSQL: if SET NOCOUNT ON, then there is no count
if not (TODBCConnection(Owner).DriverKind in [dkSQLSrv, dkSQLNC, dkSQLOdbc]) or
(SS_NOCOUNT_STATUS <> SQL_NC_ON) then
Lib.SQLRowCount(FHandle, ACount);
end;
{-------------------------------------------------------------------------------}
procedure TODBCCommandStatement.Execute(ARowCount, AOffset: SQLUInteger;
var ACount: SQLLen; AExact: Boolean; const AExecDirectCommand: String);
var
i: Integer;
iTimes: SQLUInteger;
iRet: SQLReturn;
oBuffer: TODBCPageBuffer;
lCheck: Boolean;
procedure AdjustRowsAffected(var ACount: SQLLen);
var
i: Integer;
iRet2: SQLReturn;
iRes: SQLLen;
begin
// if RowCount > 1, then we have array execution. In this case
// ACount must be the count of succesfully executed array items.
if (ARowCount > 1) and (oBuffer <> nil) then begin
iRes := 0;
// MSSQL: When single record to be processed, FRowStatusArr is not filled
if (TODBCConnection(Owner).DriverKind in [dkSQLSrv, dkSQLNC, dkSQLOdbc]) and
(iTimes = 1) then begin
if (oBuffer.RowsProcessed = 1) and (
(iRet = SQL_SUCCESS_WITH_INFO) and (DIAG_SS_SEVERITY[1] < 11) or
(iRet = SQL_SUCCESS)
) then
iRes := 1
end
// otherwise count error in row status array
else if oBuffer.RowsProcessed <> 0 then begin
for i := 0 to ARowCount - oBuffer.Shifted - 1 do
case oBuffer.FRowStatusArr[i] of
SQL_PARAM_SUCCESS,
SQL_INFX_PARAM_SUCCESS:
Inc(iRes);
SQL_PARAM_SUCCESS_WITH_INFO:
// DB2: returns SQL_PARAM_SUCCESS_WITH_INFO for failed items
if not (TODBCConnection(Owner).DriverKind in [dkDB2, dkDB2_400]) then
Inc(iRes);
end;
end;
end
// MSSQL: if SET NOCOUNT ON, then there is no count
else if not ((iRet = SQL_PARAM_DATA_AVAILABLE) or (iRet = SQL_NEED_DATA)) and
(TODBCConnection(Owner).DriverKind in [dkSQLSrv, dkSQLNC, dkSQLOdbc]) and
(SS_NOCOUNT_STATUS = SQL_NC_ON) then
iRes := -1
// Teradata: if execution failed, then no rows changed and
// SQLRowCount returns "Function sequence error".
else if ((iRet = SQL_ERROR) or (iRet = SQL_NO_DATA)) and
(TODBCConnection(Owner).DriverKind = dkTeradata) then
iRes := 0
else begin
iRes := -1;
iRet2 := Lib.SQLRowCount(FHandle, iRes);
// MSAccess: SQLExecute may be successful, but SQLRowCount returns
// "Function sequence error". Then, most probable, there was SQLCancel call.
if TODBCConnection(Owner).DriverKind in [dkMSAccessJet, dkMSAccessACE] then
if (iRet2 = SQL_ERROR) and
(iRet in [SQL_NEED_DATA, SQL_SUCCESS_WITH_INFO, SQL_SUCCESS]) and
(DIAG_SQLSTATE[1] = 'HY010') then
try
Check(iRet2);
except
on E: EODBCNativeException do begin
E.Errors[0].Kind := ekCmdAborted;
raise;
end;
end;
end;
if iRes = -1 then
ACount := -1
else if ACount >= 0 then
Inc(ACount, iRes);
end;
procedure AdjustRowIndex(E: EODBCNativeException);
var
i, j: Integer;
begin
if (oBuffer <> nil) and (E.ErrorCount > 0) and (E[0].RowIndex = -1) then
if iTimes > 1 then begin
j := 0;
for i := 0 to ARowCount - oBuffer.Shifted - 1 do
case oBuffer.FRowStatusArr[i] of
SQL_PARAM_ERROR,
SQL_PARAM_SUCCESS_WITH_INFO:
begin
E[j].RowIndex := oBuffer.Shifted + i;
Inc(j);
if j = E.ErrorCount then
Break;
end;
SQL_PARAM_UNUSED,
SQL_PARAM_DIAG_UNAVAILABLE:
Break;
end;
end
else
for i := 0 to E.ErrorCount - 1 do
if E[i].RowIndex = -1 then
E[i].RowIndex := oBuffer.Shifted;
end;
begin
TODBCConnection(Owner).ClearInfo;
FExecuted := True;
FResultCols := -1;
FNoMoreResults := True;
ACount := 0;
iTimes := ARowCount - AOffset;
if ParamList.Count > 0 then begin
BindParameters(ARowCount, True);
oBuffer := ParamList.FBuffer;
if AOffset > 0 then begin
oBuffer.ShiftBuffersPtr(AOffset);
PARAMSET_SIZE := iTimes;
end;
if TODBCConnection(Owner).DriverKind = dkFreeTDS then
for i := 0 to ARowCount - oBuffer.Shifted - 1 do
oBuffer.FRowStatusArr[i] := SQL_PARAM_DIAG_UNAVAILABLE;
{$IFDEF FireDAC_MONITOR}
if Tracing then
DumpParameters(True, AOffset, iTimes);
{$ENDIF}
end
else
oBuffer := nil;
try
if AExecDirectCommand = '' then
iRet := Lib.SQLExecute(FHandle)
else
iRet := Lib.SQLExecDirect(FHandle, PSQLChar(AExecDirectCommand), SQL_NTS);
try
try
if iRet = SQL_NEED_DATA then
iRet := PutLongParams();
if iRet = SQL_PARAM_DATA_AVAILABLE then
iRet := GetLongParams();
case iRet of
SQL_NEED_DATA:
lCheck := (FocusedParam = nil);
SQL_NO_DATA:
lCheck := AExact or (iTimes > 1);
SQL_PARAM_DATA_AVAILABLE:
lCheck := (FocusedParam = nil) and (AExact or (iTimes > 1));
else
lCheck := True;
end;
if lCheck then
Check(iRet);
except
on E: EODBCNativeException do begin
AdjustRowIndex(E);
raise;
end;
end;
finally
AdjustRowsAffected(ACount);
end;
{$IFDEF FireDAC_MONITOR}
if ParamList.Count > 0 then
if Tracing then
DumpParameters(False, AOffset, iTimes);
{$ENDIF}
finally
if (oBuffer <> nil) and (AOffset > 0) then begin
oBuffer.UnShift;
PARAMSET_SIZE := ARowCount;
end;
ParamList.ResetDataReaders;
end;
FNoMoreResults := False;
end;
{-------------------------------------------------------------------------------}
procedure TODBCCommandStatement.Open(ARowCount: SQLUInteger; const AExecDirectCommand: String);
var
iCnt: SQLLen;
begin
iCnt := 0;
Execute(ARowCount, 0, iCnt, False, AExecDirectCommand);
end;
{-------------------------------------------------------------------------------}
function TODBCCommandStatement.NumParams: SQLSmallint;
begin
Result := 0;
Check(Lib.SQLNumParams(FHandle, Result));
end;
{-------------------------------------------------------------------------------}
procedure TODBCCommandStatement.Prepare(const ACommandText: String);
begin
TODBCConnection(Owner).ClearInfo;
TODBCConnection(Owner).FLastCommandText := ACommandText;
Check(Lib.SQLPrepare(FHandle, PSQLChar(ACommandText), SQL_NTS));
end;
{-------------------------------------------------------------------------------}
procedure TODBCCommandStatement.Unprepare;
begin
inherited Unprepare;
UnbindParameters;
TODBCConnection(Owner).FLastCommandText := '';
FExecuted := False;
FNoMoreResults := True;
FResultCols := -1;
end;
{$IFDEF FireDAC_MONITOR}
{-------------------------------------------------------------------------------}
procedure TODBCCommandStatement.DumpParameters(AInput: Boolean; AOffset, ATimes: Integer);
var
i, j, n: Integer;
sVal: String;
iLen: SQLLen;
oVar: TODBCVariable;
begin
if Tracing then begin
n := 1;
for i := 0 to ParamList.Count - 1 do begin
oVar := ParamList.Items[i];
case oVar.ParamType of
SQL_PARAM_TYPE_UNKNOWN,
SQL_RESULT_COL:
Continue;
SQL_PARAM_INPUT:
if not AInput then
Continue;
SQL_PARAM_INPUT_OUTPUT,
SQL_PARAM_INPUT_OUTPUT_STREAM:
;
SQL_PARAM_OUTPUT,
SQL_PARAM_OUTPUT_STREAM,
SQL_RETURN_VALUE:
if AInput then
Continue;
end;
iLen := 0;
sVal := oVar.DumpValue(0, iLen);
Trace(ekCmdDataIn, esProgress, 'Param',
[String('N'), n, 'Name', oVar.DumpLabel, '@Mode', oVar.DumpParamType,
'@Type', oVar.DumpCDataType, 'Size', oVar.ColumnSize, 'Len', iLen,
'@Data(' + IntToStr(AOffset) + ')', sVal]);
for j := 1 to ATimes - 1 do begin
sVal := oVar.DumpValue(j, iLen);
Trace(ekCmdDataIn, esProgress, ' ... Data', ['I', AOffset + j, 'L', iLen, '@V', sVal]);
end;
Inc(n);
end;
end;
end;
{$ENDIF}
{-------------------------------------------------------------------------------}
{ TODBCLongDataStream
{-------------------------------------------------------------------------------}
constructor TODBCLongDataStream.Create(AParam: TODBCParameter; AMode: TFDStreamMode);
begin
inherited Create;
FParam := AParam;
FMode := AMode;
FState := -1;
FSize := -1;
end;
{-------------------------------------------------------------------------------}
function TODBCLongDataStream.GetStmt: TODBCCommandStatement;
begin
Result := Param.Statement as TODBCCommandStatement;
end;
{-------------------------------------------------------------------------------}
procedure TODBCLongDataStream.CheckMode(AMode: TFDStreamMode; const AMsg: String);
var
oStmt: TODBCCommandStatement;
pParamNum: SQLPointer;
iRet: SQLReturn;
oPar: TODBCParameter;
procedure Error;
begin
FDException(oStmt.OwningObj, [S_FD_LPhys, S_FD_ODBCId],
er_FD_AccLongDataStream, [AMsg, Param.DumpLabel]);
end;
begin
if FMode <> AMode then
Error;
if FState = -1 then begin
FState := 0;
oStmt := Stmt;
if oStmt.FocusedParam = Param then begin
iRet := oStmt.FocusedResult;
oPar := oStmt.FocusedParam;
end
else begin
pParamNum := nil;
oPar := nil;
oStmt.FFocusedParam := nil;
iRet := oStmt.Lib.SQLParamData(oStmt.FHandle, pParamNum);
if ((iRet = SQL_NEED_DATA) or (iRet = SQL_PARAM_DATA_AVAILABLE)) and (pParamNum <> nil) then
oPar := oStmt.ParamList.FindByToken(pParamNum) as TODBCParameter;
end;
if (oPar <> Param) or
(iRet = SQL_NEED_DATA) and (FMode <> smOpenWrite) or
(iRet = SQL_PARAM_DATA_AVAILABLE) and (FMode <> smOpenRead) then
Error;
end;
end;
{-------------------------------------------------------------------------------}
function TODBCLongDataStream.Read(var Buffer; Count: Longint): Longint;
var
iInd: SQLLen;
iRet: SQLReturn;
oStmt: TODBCCommandStatement;
begin
CheckMode(smOpenRead, 'read from');
if FState = 1 then begin
Result := 0;
Exit;
end;
oStmt := Stmt;
iRet := oStmt.GetLongVarPiece(Param, SQLPointer(@Buffer), SQLLen(Count), @iInd);
if oStmt.GetLongVarFinished(SQLLen(Count), iRet, iInd) then
FState := 1;
if FSize = -1 then
if iInd = SQL_NO_TOTAL then
FSize := -2
else if iInd = SQL_NULL_DATA then
FSize := 0
else
FSize := iInd;
if (iRet = SQL_NO_DATA) or (iInd = SQL_NULL_DATA) then
Result := 0
else if iRet = SQL_SUCCESS then
Result := iInd
else // SQL_SUCCESS_WITH_INFO
Result := Count;
Inc(FPosition, Result);
end;
{-------------------------------------------------------------------------------}
function TODBCLongDataStream.Write(const Buffer; Count: Longint): Longint;
var
oStmt: TODBCCommandStatement;
pData: SQLPointer;
begin
CheckMode(smOpenWrite, 'write to');
oStmt := Stmt;
// ASA: SQLPutData(..., nil, 0) raises "invalid string or buffer length".
// So, set pData to a not nil value.
if (@Buffer = nil) and (Count = 0) then
pData := @pData
else
pData := @Buffer;
oStmt.Check(oStmt.Lib.SQLPutData(oStmt.FHandle, pData, SQLLen(Count)));
Inc(FPosition, Count);
FModified := True;
Result := Count;
end;
{-------------------------------------------------------------------------------}
function TODBCLongDataStream.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64;
var
lError: Boolean;
begin
case Origin of
soBeginning: lError := Offset <> FPosition;
soCurrent: lError := Offset <> 0;
soEnd: lError := True;
else lError := False;
end;
if lError then
CheckMode(smOpenReadWrite, 'seek');
Result := FPosition;
end;
{-------------------------------------------------------------------------------}
function TODBCLongDataStream.GetSize: Int64;
begin
Result := -1;
case FMode of
smOpenRead:
if FSize >= 0 then
Result := FSize;
smOpenWrite:
Result := FPosition;
end;
end;
{-------------------------------------------------------------------------------}
procedure TODBCLongDataStream.Flush;
begin
if (FMode = smOpenWrite) and not FModified then
Write(nil^, 0);
end;
{-------------------------------------------------------------------------------}
{ TODBCMetaInfoStatement }
{-------------------------------------------------------------------------------}
procedure TODBCMetaInfoStatement.Columns(const ACatalog, ASchema, ATable, AColumn: String);
begin
FMode := 0;
FExecuted := False;
FNoMoreResults := False;
FResultCols := -1;
FCatalog := ACatalog;
FSchema := ASchema;
FObject := ATable;
FColumn := AColumn;
end;
{-------------------------------------------------------------------------------}
procedure TODBCMetaInfoStatement.TypeColumns(const ACatalog, ASchema, ATable, AColumn: String);
begin
FMode := 10;
FExecuted := False;
FNoMoreResults := False;
FResultCols := -1;
FCatalog := ACatalog;
FSchema := ASchema;
FObject := ATable;
FColumn := AColumn;
end;
{-------------------------------------------------------------------------------}
procedure TODBCMetaInfoStatement.ForeignKeys(const APKCatalog, APKSchema, APKTable,
AFKCatalog, AFKSchema, AFKTable: String);
begin
FMode := 1;
FExecuted := False;
FNoMoreResults := False;
FResultCols := -1;
FCatalog := APKCatalog;
FSchema := APKSchema;
FObject := APKTable;
FFKCatalog := AFKCatalog;
FFKSchema := AFKSchema;
FFKTable := AFKTable;
end;
{-------------------------------------------------------------------------------}
procedure TODBCMetaInfoStatement.PrimaryKeys(const ACatalog, ASchema, ATable: String);
begin
FMode := 2;
FExecuted := False;
FNoMoreResults := False;
FResultCols := -1;
FCatalog := ACatalog;
FSchema := ASchema;
FObject := ATable;
end;
{-------------------------------------------------------------------------------}
procedure TODBCMetaInfoStatement.Procedures(const ACatalog, ASchema, AProc: String);
begin
FMode := 3;
FExecuted := False;
FNoMoreResults := False;
FResultCols := -1;
FCatalog := ACatalog;
FSchema := ASchema;
FObject := AProc;
end;
{-------------------------------------------------------------------------------}
procedure TODBCMetaInfoStatement.ProcedureColumns(const ACatalog, ASchema,
AProc, AColumn: String);
begin
FMode := 4;
FExecuted := False;
FNoMoreResults := False;
FResultCols := -1;
FCatalog := ACatalog;
FSchema := ASchema;
FObject := AProc;
FColumn := AColumn;
end;
{-------------------------------------------------------------------------------}
procedure TODBCMetaInfoStatement.SpecialColumns(const ACatalog, ASchema,
ATable: String; AIdentifierType: SQLUSmallint);
begin
FMode := 5;
FExecuted := False;
FNoMoreResults := False;
FResultCols := -1;
FCatalog := ACatalog;
FSchema := ASchema;
FObject := ATable;
FIdentifierType := AIdentifierType;
end;
{-------------------------------------------------------------------------------}
procedure TODBCMetaInfoStatement.Statistics(const ACatalog, ASchema, ATable: String;
AUnique: SQLUSmallint);
begin
FMode := 6;
FExecuted := False;
FNoMoreResults := False;
FResultCols := -1;
FCatalog := ACatalog;
FSchema := ASchema;
FObject := ATable;
FUnique := AUnique;
end;
{-------------------------------------------------------------------------------}
procedure TODBCMetaInfoStatement.Tables(const ACatalog, ASchema, ATable,
ATableTypes: String);
begin
FMode := 7;
FExecuted := False;
FNoMoreResults := False;
FResultCols := -1;
FCatalog := ACatalog;
FSchema := ASchema;
FObject := ATable;
FTableTypes := ATableTypes;
end;
{-------------------------------------------------------------------------------}
procedure TODBCMetaInfoStatement.Catalogs;
begin
FMode := 8;
FExecuted := False;
FNoMoreResults := False;
FResultCols := -1;
end;
{-------------------------------------------------------------------------------}
procedure TODBCMetaInfoStatement.Schemas;
begin
FMode := 9;
FExecuted := False;
FNoMoreResults := False;
FResultCols := -1;
end;
{-------------------------------------------------------------------------------}
procedure TODBCMetaInfoStatement.Execute;
const
SQL_ALL_CATALOGS: String = '%';
SQL_ALL_SCHEMAS: String = '%';
EmptyStr: String = #0;
function Str2P(const AStr: String): PSQLChar;
begin
if AStr = '' then
Result := nil
else
Result := PSQLChar(AStr);
end;
begin
TODBCConnection(Owner).ClearInfo;
case FMode of
0: Check(Lib.SQLColumns(FHandle, Str2P(FCatalog), SQLSmallint(Length(FCatalog)),
Str2P(FSchema), SQLSmallint(Length(FSchema)), Str2P(FObject),
SQLSmallint(Length(FObject)), Str2P(FColumn), SQLSmallint(Length(FColumn))));
1: Check(Lib.SQLForeignKeys(FHandle, Str2P(FCatalog), SQLSmallint(Length(FCatalog)),
Str2P(FSchema), SQLSmallint(Length(FSchema)), Str2P(FObject),
SQLSmallint(Length(FObject)), Str2P(FFKCatalog), SQLSmallint(Length(FFKCatalog)),
Str2P(FFKSchema), SQLSmallint(Length(FFKSchema)), Str2P(FFKTable),
SQLSmallint(Length(FFKTable))));
2: Check(Lib.SQLPrimaryKeys(FHandle, Str2P(FCatalog), SQLSmallint(Length(FCatalog)),
Str2P(FSchema), SQLSmallint(Length(FSchema)), Str2P(FObject),
SQLSmallint(Length(FObject))));
3: Check(Lib.SQLProcedures(FHandle, Str2P(FCatalog), SQLSmallint(Length(FCatalog)),
Str2P(FSchema), SQLSmallint(Length(FSchema)), Str2P(FObject),
SQLSmallint(Length(FObject))));
4: Check(Lib.SQLProcedureColumns(FHandle, Str2P(FCatalog), SQLSmallint(Length(FCatalog)),
Str2P(FSchema), SQLSmallint(Length(FSchema)), Str2P(FObject),
SQLSmallint(Length(FObject)), Str2P(FColumn), SQLSmallint(Length(FColumn))));
5: Check(Lib.SQLSpecialColumns(FHandle, FIdentifierType, Str2P(FCatalog),
SQLSmallint(Length(FCatalog)), Str2P(FSchema), SQLSmallint(Length(FSchema)),
Str2P(FObject), SQLSmallint(Length(FObject)), SQL_SCOPE_CURROW, SQL_NO_NULLS));
6: Check(Lib.SQLStatistics(FHandle, Str2P(FCatalog), SQLSmallint(Length(FCatalog)),
Str2P(FSchema), SQLSmallint(Length(FSchema)), Str2P(FObject),
SQLSmallint(Length(FObject)), FUnique, SQL_QUICK));
7: Check(Lib.SQLTables(FHandle, Str2P(FCatalog), SQLSmallint(Length(FCatalog)),
Str2P(FSchema), SQLSmallint(Length(FSchema)), Str2P(FObject),
SQLSmallint(Length(FObject)), Str2P(FTableTypes), SQLSmallint(Length(FTableTypes))));
8: Check(Lib.SQLTables(FHandle, Str2P(SQL_ALL_CATALOGS), SQLSmallint(Length(SQL_ALL_CATALOGS)),
PSQLChar(EmptyStr), SQL_NTS, PSQLChar(EmptyStr), SQL_NTS, PSQLChar(EmptyStr), SQL_NTS));
9: Check(Lib.SQLTables(FHandle, PSQLChar(EmptyStr), SQL_NTS,
Str2P(SQL_ALL_SCHEMAS), SQLSmallint(Length(SQL_ALL_SCHEMAS)),
PSQLChar(EmptyStr), SQL_NTS, PSQLChar(EmptyStr), SQL_NTS));
10:
begin
if TODBCConnection(Owner).DriverKind in [dkSQLNC, dkSQLOdbc] then
SS_NAME_SCOPE := SQL_SS_NAME_SCOPE_TABLE_TYPE;
Check(Lib.SQLColumns(FHandle, Str2P(FCatalog), SQLSmallint(Length(FCatalog)),
Str2P(FSchema), SQLSmallint(Length(FSchema)), Str2P(FObject),
SQLSmallint(Length(FObject)), Str2P(FColumn), SQLSmallint(Length(FColumn))));
end;
end;
FExecuted := True;
FNoMoreResults := True;
FResultCols := -1;
end;
{-------------------------------------------------------------------------------}
function ODBCNativeExceptionLoad(const AStorage: IFDStanStorage): TObject;
begin
Result := EODBCNativeException.Create;
EODBCNativeException(Result).LoadFromStorage(AStorage);
end;
{-------------------------------------------------------------------------------}
initialization
GLock := TCriticalSection.Create;
FDStorageManager().RegisterClass(EODBCNativeException, 'ODBCNativeException',
@ODBCNativeExceptionLoad, @FDExceptionSave);
finalization
FDFreeAndNil(GLock);
end.
|
unit uCustomSplitter;
// -----------------------------------------------------------------------------
// TSplitter enhanced with grab bar
// The original author is Anders Melander, anders@melander.dk, http://melander.dk
// Copyright © 2008 Anders Melander
// -----------------------------------------------------------------------------
// License:
// Creative Commons Attribution-Share Alike 3.0 Unported
// http://creativecommons.org/licenses/by-sa/3.0/
// -----------------------------------------------------------------------------
interface
uses
ExtCtrls, Messages, Classes;
//------------------------------------------------------------------------------
//
// TSplitter enhanced with grab bar
//
//------------------------------------------------------------------------------
type
TSplitter = class(ExtCtrls.TSplitter)
protected
procedure Paint; override;
public
property OnDblClick;
end;
const DotsCount: Integer = 16;
implementation
uses
Windows, Graphics, Controls;
//------------------------------------------------------------------------------
//
// TSplitter enhanced with grab bar
//
//------------------------------------------------------------------------------
procedure TSplitter.Paint;
var
R: TRect;
X, Y: integer;
DX, DY: integer;
i: integer;
Brush: TBitmap;
begin
R := ClientRect;
Canvas.Brush.Color := Color;
Canvas.FillRect(ClientRect);
X := (R.Left+R.Right) div 2;
Y := (R.Top+R.Bottom) div 2;
if (Align in [alLeft, alRight]) then
begin
DX := 0; DY := 4;
end else begin
DX := 4; DY := 0;
end;
dec(X, DX*(DotsCount div 2));
dec(Y, DY*(DotsCount div 2));
Brush := TBitmap.Create;
try
Brush.SetSize(2, 2);
Brush.Canvas.Pixels[1, 1] := clBtnShadow; //clBtnText
Brush.Canvas.Pixels[0, 0] := clBtnHighlight;
Brush.Canvas.Pixels[0, 1] := clBtnShadow;
Brush.Canvas.Pixels[1, 0] := clBtnShadow;
for i := 0 to DotsCount do
begin
Canvas.Draw(X - 1, Y, Brush);
Canvas.Draw(X + 2, Y, Brush);
inc(X, DX);
inc(Y, DY);
end;
finally
Brush.Free;
end;
end;
end.
|
unit IdIPWatch;
interface
uses
Classes,
IdComponent, IdThread;
const
IP_WATCH_HIST_MAX = 25;
IP_WATCH_HIST_FILENAME = 'iphist.dat';
IP_WATCH_ACTIVE = False;
IP_WATCH_HIST_ENABLED = True;
IP_WATCH_INTERVAL = 1000;
type
TIdIPWatchThread = class(TIdThread)
protected
FInterval: Integer;
FSender: TObject;
FTimerEvent: TNotifyEvent;
//
procedure Run; override;
procedure TimerEvent;
end;
TIdIPWatch = class(TIdComponent)
protected
FActive: Boolean;
FCurrentIP: string;
FHistoryEnabled: Boolean;
FHistoryFilename: string;
FIPHistoryList: TStringList;
FIsOnline: Boolean;
FLocalIPHuntBusy: Boolean;
FMaxHistoryEntries: Integer;
FOnLineCount: Integer;
FOnStatusChanged: TNotifyEvent;
FPreviousIP: string;
FThread: TIdIPWatchThread;
FWatchInterval: Cardinal;
procedure AddToIPHistoryList(Value: string);
procedure CheckStatus(Sender: TObject);
procedure SetActive(Value: Boolean);
procedure SetMaxHistoryEntries(Value: Integer);
procedure SetWatchInterval(Value: Cardinal);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function ForceCheck: Boolean;
procedure LoadHistory;
function LocalIP: string;
procedure SaveHistory;
//
property CurrentIP: string read FCurrentIP;
property IPHistoryList: TStringList read FIPHistoryList;
property IsOnline: Boolean read FIsOnline;
property PreviousIP: string read FPreviousIP;
published
property Active: Boolean read FActive write SetActive default
IP_WATCH_ACTIVE;
property HistoryEnabled: Boolean read FHistoryEnabled write FHistoryEnabled
default IP_WATCH_HIST_ENABLED;
property HistoryFilename: string read FHistoryFilename write
FHistoryFilename;
property MaxHistoryEntries: Integer read FMaxHistoryEntries write
SetMaxHistoryEntries
default IP_WATCH_HIST_MAX;
property OnStatusChanged: TNotifyEvent read FOnStatusChanged write
FOnStatusChanged;
property WatchInterval: Cardinal read FWatchInterval write SetWatchInterval
default IP_WATCH_INTERVAL;
end;
implementation
uses
IdGlobal, IdStack,
SysUtils;
procedure TIdIPWatch.AddToIPHistoryList(Value: string);
begin
if (Value = '') or (Value = '127.0.0.1') then
begin
Exit;
end;
if FIPHistoryList.Count > 0 then
begin
if FIPHistoryList[FIPHistoryList.Count - 1] = Value then
begin
Exit;
end;
end;
FIPHistoryList.Add(Value);
if FIPHistoryList.Count > MaxHistoryEntries then
begin
FIPHistoryList.Delete(0);
end;
end;
procedure TIdIPWatch.CheckStatus(Sender: TObject);
var
WasOnLine: Boolean;
OldIP: string;
begin
try
if FLocalIPHuntBusy then
begin
Exit;
end;
WasOnLine := FIsOnline;
OldIP := FCurrentIP;
FCurrentIP := LocalIP;
FIsOnline := (FCurrentIP <> '127.0.0.1') and (FCurrentIP <> '');
if (WasOnline) and (not FIsOnline) then
begin
if (OldIP <> '127.0.0.1') and (OldIP <> '') then
begin
FPreviousIP := OldIP;
end;
AddToIPHistoryList(FPreviousIP);
end;
if (not WasOnline) and (FIsOnline) then
begin
if FOnlineCount = 0 then
begin
FOnlineCount := 1;
end;
if FOnlineCount = 1 then
begin
if FPreviousIP = FCurrentIP then
begin
if FIPHistoryList.Count > 0 then
begin
FIPHistoryList.Delete(FIPHistoryList.Count - 1);
end;
if FIPHistoryList.Count > 0 then
begin
FPreviousIP := FIPHistoryList[FIPHistoryList.Count - 1];
end
else
begin
FPreviousIP := '';
end;
end;
end;
FOnlineCount := 2;
end;
if ((WasOnline) and (not FIsOnline)) or ((not WasOnline) and (FIsOnline))
then
begin
if (not (csDesigning in ComponentState)) and Assigned(FOnStatusChanged)
then
begin
FOnStatusChanged(Self);
end;
end;
except
end;
end;
constructor TIdIPWatch.Create(AOwner: TComponent);
begin
inherited;
FIPHistoryList := TStringList.Create;
FIsOnLine := False;
FOnLineCount := 0;
FWatchInterval := 1000;
FActive := IP_WATCH_ACTIVE;
FPreviousIP := '';
FLocalIPHuntBusy := False;
FHistoryEnabled := IP_WATCH_HIST_ENABLED;
FHistoryFilename := IP_WATCH_HIST_FILENAME;
FMaxHistoryEntries := IP_WATCH_HIST_MAX;
end;
destructor TIdIPWatch.Destroy;
begin
if FIsOnLine then
begin
AddToIPHistoryList(FCurrentIP);
end;
Active := False;
SaveHistory;
FIPHistoryList.Free;
inherited;
end;
function TIdIPWatch.ForceCheck: Boolean;
begin
CheckStatus(nil);
Result := FIsOnline;
end;
procedure TIdIPWatch.LoadHistory;
begin
if not (csDesigning in ComponentState) then
begin
FIPHistoryList.Clear;
if (FileExists(FHistoryFilename)) and (FHistoryEnabled) then
begin
FIPHistoryList.LoadFromFile(FHistoryFileName);
if FIPHistoryList.Count > 0 then
begin
FPreviousIP := FIPHistoryList[FIPHistoryList.Count - 1];
end;
end;
end;
end;
function TIdIPWatch.LocalIP: string;
begin
FLocalIpHuntBusy := True;
try
Result := GStack.LocalAddress;
finally
FLocalIPHuntBusy := False;
end;
end;
procedure TIdIPWatch.SaveHistory;
begin
if (not (csDesigning in ComponentState)) and FHistoryEnabled then
begin
FIPHistoryList.SaveToFile(FHistoryFilename);
end;
end;
procedure TIdIPWatch.SetActive(Value: Boolean);
begin
if Value <> FActive then
begin
FActive := Value;
if not (csDesigning in ComponentState) then
begin
if FActive then
begin
FThread := TIdIPWatchThread.Create;
with FThread do
begin
FSender := Self;
FTimerEvent := CheckStatus;
FInterval := FWatchInterval;
Start;
end;
end
else
begin
FThread.TerminateAndWaitFor;
FreeAndNil(FThread);
end;
end;
end;
end;
procedure TIdIPWatch.SetMaxHistoryEntries(Value: Integer);
begin
FMaxHistoryEntries := Value;
while FIPHistoryList.Count > MaxHistoryEntries do
FIPHistoryList.Delete(0);
end;
procedure TIdIPWatch.SetWatchInterval(Value: Cardinal);
begin
if Value <> FWatchInterval then
begin
FThread.FInterval := Value;
end;
end;
procedure TIdIPWatchThread.Run;
var
LInterval: Integer;
begin
LInterval := FInterval;
while LInterval > 0 do
begin
if LInterval > 500 then
begin
Sleep(500);
LInterval := LInterval - 500;
end
else
begin
Sleep(LInterval);
LInterval := 0;
end;
if Terminated then
begin
exit;
end;
Synchronize(TimerEvent);
end;
end;
procedure TIdIPWatchThread.TimerEvent;
begin
FTimerEvent(FSender);
end;
end.
|
unit Web;
interface
uses
Windows, Classes, WinInet;
type
TWeb = class abstract
private
function IsWebAccessibleInConnectedState(
const GetFunctionResult: Boolean; const InternetConnectedState: DWORD):
Boolean;
function IsWebAccessConfigured(const InternetConnectedState: DWORD): Boolean;
public
function GetToStringList(const PathToGet: String):
TStringList; virtual; abstract;
function GetToStringStream(const PathToGet: String): TStringStream;
virtual; abstract;
function IsWebAccessible: Boolean;
protected
const
UserAgent = 'Naraeon SSD Tools';
CharacterSet = 'Unicode';
end;
implementation
{ TWeb }
function TWeb.IsWebAccessConfigured(
const InternetConnectedState: DWORD): Boolean;
begin
result :=
((InternetConnectedState and INTERNET_CONNECTION_OFFLINE) = 0) and
(InternetConnectedState <> 0);
end;
function TWeb.IsWebAccessibleInConnectedState(
const GetFunctionResult: Boolean; const InternetConnectedState: DWORD):
Boolean;
begin
result :=
GetFunctionResult and IsWebAccessConfigured(InternetConnectedState);
end;
function TWeb.IsWebAccessible: Boolean;
var
InternetConnectedState: DWORD;
GetFunctionResult: Boolean;
begin
GetFunctionResult := InternetGetConnectedState(@InternetConnectedState, 0);
result :=
IsWebAccessibleInConnectedState(GetFunctionResult, InternetConnectedState);
end;
end.
|
unit M_DataModule;
interface
uses
System.SysUtils, System.Classes, Data.DB, Datasnap.DBClient,
Datasnap.DSConnect, Data.SqlExpr, Data.DBXDataSnap, IPPeerClient,
Data.DBXCommon, M_Main_Class, DBXJSON, System.JSON, Datasnap.DSCommon,
Data.DbxHTTPLayer;
type
TDataModule1 = class(TDataModule)
M_SQLConnection: TSQLConnection;
M_DSProviderConnection: TDSProviderConnection;
Location_Trans: TClientDataSet;
Room_List: TDataSource;
Location_TransCHAT_NAME: TWideStringField;
M_ChannelManager: TDSClientCallbackChannelManager;
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
TM_Client_Callback = class(TDBXnamedCallback)
public
constructor create;
function Execute(Const args: TJSONValue): TJSONValue; override;
end;
var
DataModule1: TDataModule1;
dm: TServerMethods1Client;
hname, hlat, hlng, haddress: string;
meet_Count: integer = 0;
implementation
{ %CLASSGROUP 'FMX.Controls.TControl' }
uses M_Main;
{$R *.dfm}
{ TDataModule1 }
procedure TDataModule1.DataModuleCreate(Sender: TObject);
var
LGuid: TGuid;
begin
M_SQLConnection.Connected := true;
Location_Trans.Active := true;
dm := TServerMethods1Client.create(M_SQLConnection.DBXConnection);
CreateGuid(LGuid);
M_ChannelManager.ManagerId := GuidToString(LGuid);
end;
procedure TDataModule1.DataModuleDestroy(Sender: TObject);
begin
DataModule1.M_SQLConnection.Connected := false;
dm.Free;
end;
{ TClient_Callback }
constructor TM_Client_Callback.create;
begin
end;
function TM_Client_Callback.Execute(const args: TJSONValue): TJSONValue;
var
LJSonObject: TJsonObject;
Loc_Name, Loc_Lat, Loc_Lng, Mem_Name, Loc_Address, Chat: string;
check: string;
begin
result := TJSONTrue.create;
LJSonObject := TJsonObject(args);
with LJSonObject.Get(0) do
check := JSONvalue.Value;
if check = '0' then // 채팅
begin
with LJSonObject.Get(1) do
Chat := JSONvalue.Value;
Form3.M_Chat_List.Text := Form3.M_Chat_List.Text + Chat;
end;
if check = '1' then // 모바일 위치 마크
begin
with LJSonObject.Get(1) do
Loc_Name := JSONvalue.Value;
with LJSonObject.Get(2) do
Loc_Lat := JSONvalue.Value;
with LJSonObject.Get(3) do
Loc_Lng := JSONvalue.Value;
hname := '''' + Loc_Name + '''';
hlat := '' + Loc_Lat + '';
hlng := '' + Loc_Lng + '';
Form3.M_Loc_Mark.Enabled := True;
end;
if check = '2' then // 여기서 만나
begin
Form3.M_Meet_Click.Enabled := True;
end;
if check = '3' then // 채팅방 참여자 목록 표시
begin
with LJSonObject.Get(1) do
Mem_Name := JSONvalue.Value;
Form3.M_Join_Member.Items.Add(Mem_Name);
end;
if check = '4' then // 윈도우폼 위치 마크
begin
with LJSonObject.Get(1) do
Loc_Name := JSONvalue.Value;
with LJSonObject.Get(2) do
Loc_Address := JSONvalue.Value;
hname := '''' + Loc_Name + '''';
haddress := '''' + Loc_Address + '''';
Form3.W_Loc_Mark.Enabled := True;
end;
end;
end.
|
unit uROR_SelectorTree;
{$I Components.inc}
interface
{$IFNDEF NOVTREE}
uses
Forms, Buttons, Classes, Controls, Windows, uROR_GridView, OvcFiler,
uROR_CustomSelector, ComCtrls, VirtualTrees, uROR_Utilities, Messages,
uROR_TreeGrid, ActiveX, uROR_Selector;
type
TCCRResultTree = class(TCCRTreeGrid)
protected
procedure DoDragDrop(Source: TObject; DataObject: IDataObject;
Formats: TFormatArray; Shift: TShiftState; Pt: TPoint;
var Effect: Integer; Mode: TDropMode); override;
function DoDragOver(Source: TObject; Shift: TShiftState; State: TDragState;
Pt: TPoint; Mode: TDropMode; var Effect: Integer): Boolean; override;
procedure DoEnter; override;
function DoKeyAction(var CharCode: Word; var Shift: TShiftState): Boolean; override;
procedure DoStructureChange(Node: PVirtualNode; Reason: TChangeReason); override;
procedure HandleMouseDblClick(var Message: TWMMouse; const HitInfo: THitInfo); override;
public
procedure Clear; override;
end;
TCCRSelectorTree = class(TCCRCustomSelector)
private
function getResultTree: TCCRResultTree;
function getSourceList: TCCRSourceList;
protected
function CreateResultList: TWinControl; override;
function CreateSourceList: TWinControl; override;
procedure DoUpdateButtons(var EnableAdd, EnableAddAll, EnableRemove,
EnableRemoveAll: Boolean); override;
public
constructor Create(anOwner: TComponent); override;
procedure Add; override;
procedure AddAll; override;
procedure AddSelectedItems; virtual;
procedure Clear; override;
procedure LoadLayout(aStorage: TOvcAbstractStore; aSection: String = ''); override;
procedure Remove; override;
procedure RemoveAll; override;
procedure RemoveSelectedItems; virtual;
procedure SaveLayout(aStorage: TOvcAbstractStore; aSection: String = ''); override;
published
property Align;
//property Alignment;
property Anchors;
//property AutoSize;
property BevelInner default bvNone;
property BevelOuter default bvNone;
property BevelWidth;
property BiDiMode;
property BorderWidth;
property BorderStyle;
//property Caption;
property Color;
property Constraints;
property Ctl3D;
//property UseDockManager default True;
//property DockSite;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property FullRepaint;
property Font;
//property Locked;
property ParentBiDiMode;
{$IFDEF VERSION7}
property ParentBackground;
{$ENDIF}
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property OnCanResize;
property OnClick;
property OnConstrainedResize;
property OnContextPopup;
//property OnDockDrop;
//property OnDockOver;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
//property OnGetSiteInfo;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnResize;
property OnStartDock;
property OnStartDrag;
//property OnUnDock;
property AddRemoveMode;
property AutoSort;
property CustomAdd;
property CustomRemove;
property OnAdd;
property OnAddAll;
property OnRemove;
property OnRemoveAll;
property OnSplitterMove;
property OnUpdateButtons;
property SplitPos;
property ResultTree: TCCRResultTree read getResultTree;
property SourceList: TCCRSourceList read getSourceList;
end;
{$ENDIF}
implementation
{$IFNDEF NOVTREE}
///////////////////////////////// TCCRResultTree \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
procedure TCCRResultTree.Clear;
begin
inherited;
if Assigned(Owner) and (Owner is TCCRCustomSelector) then
TCCRCustomSelector(Owner).ResultChanged := True;
end;
procedure TCCRResultTree.DoDragDrop(Source: TObject; DataObject: IDataObject;
Formats: TFormatArray; Shift: TShiftState; Pt: TPoint;
var Effect: Integer; Mode: TDropMode);
begin
if Source is TCCRSelectorList then
if Assigned(Owner) and (Owner is TCCRSelectorTree) then
TCCRSelectorTree(Owner).Add;
end;
function TCCRResultTree.DoDragOver(Source: TObject; Shift: TShiftState;
State: TDragState; Pt: TPoint; Mode: TDropMode; var Effect: Integer): Boolean;
var
hitInfo: THitInfo;
begin
Result := False;
if Source is TCCRSelectorList then
if TCCRSelectorList(Source).Owner = Owner then
begin
Result := True;
if Assigned(OnDragOver) then
Result := inherited DoDragOver(Source, Shift, State, Pt, Mode, Effect);
if Result then
begin
GetHitTestInfoAt(Pt.X, Pt.Y, True, hitInfo);
if Assigned(hitInfo.HitNode) then
begin
ClearSelection;
Selected[hitInfo.HitNode] := True;
end;
end;
end;
end;
procedure TCCRResultTree.DoEnter;
begin
inherited;
if not Assigned(FocusedNode) then
FocusedNode := GetFirstChild(nil);
end;
function TCCRResultTree.DoKeyAction(var CharCode: Word; var Shift: TShiftState): Boolean;
begin
Result := inherited DoKeyAction(CharCode, Shift);
if not Result then
Exit;
if Shift = [] then
if (CharCode = VK_RETURN) or (CharCode = Word(' ')) then
if Assigned(Owner) and (Owner is TCCRSelectorTree) then
TCCRSelectorTree(Owner).Remove;
end;
procedure TCCRResultTree.DoStructureChange(Node: PVirtualNode; Reason: TChangeReason);
begin
inherited;
if Assigned(Owner) and (Owner is TCCRCustomSelector) then
TCCRCustomSelector(Owner).ResultChanged := True;
end;
procedure TCCRResultTree.HandleMouseDblClick(var Message: TWMMouse; const HitInfo: THitInfo);
begin
inherited;
if Assigned(Owner) and (Owner is TCCRSelectorTree) then
TCCRSelectorTree(Owner).Remove;
end;
//////////////////////////////// TCCRSelectorTree \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
constructor TCCRSelectorTree.Create(anOwner: TComponent);
begin
inherited;
with SourceList do
begin
MultiSelect := True;
ReadOnly := True;
end;
with ResultTree do
begin
DragType := dtVCL;
with TreeOptions do
begin
SelectionOptions := SelectionOptions + [toMultiSelect];
MiscOptions := MiscOptions - [toReadOnly];
end;
end;
end;
procedure TCCRSelectorTree.Add;
begin
if Assigned(SourceList.Selected) then
begin
inherited;
//--- Default processing
if not CustomAdd then
AddSelectedItems;
//--- Custom event handler
if Assigned(OnAdd) then
OnAdd(Self);
//--- Common post-processing
ResultChanged := True;
end;
end;
procedure TCCRSelectorTree.AddAll;
begin
inherited;
//--- Default processing
if not CustomAdd then
begin
SourceList.SelectAll;
AddSelectedItems;
end;
//--- Custom event handler
if Assigned(OnAddAll) then
OnAddAll(Self);
//--- Common post-processing
ResultChanged := True;
end;
procedure TCCRSelectorTree.AddSelectedItems;
var
next: TCCRGridItem;
begin
SourceList.Items.BeginUpdate;
try
// CopySelectedItems(SrcGrid, DstTree);
if AutoSort then
ResultTree.SortData;
if SourceList.SelCount > 0 then
begin
//--- Find the first item after selection
next := SourceList.Items[SourceList.Items.Count-1];
next := TCCRGridItem(GetListItemFollowingSelection(next));
//--- Remove the selected items from the list or unselect them
if AddRemoveMode = armDefault then
SourceList.DeleteSelected
else
SourceList.ClearSelection;
//--- Select the item
if Assigned(next) then
begin
SourceList.Selected := next;
SourceList.ItemFocused := SourceList.Selected;
end
else if SourceList.Items.Count > 0 then
begin
SourceList.Selected := SourceList.Items[SourceList.Items.Count-1];
SourceList.ItemFocused := SourceList.Selected;
end;
end;
finally
SourceList.Items.EndUpdate;
end;
end;
procedure TCCRSelectorTree.Clear;
begin
inherited;
SourceList.Clear;
ResultTree.Clear;
end;
{
procedure TCCRSelectorTree.CopySelectedItems(SrcLst, DstLst: TCCRSelectorList);
var
dsti, srci: TCCRGridItem;
oldCursor: TCursor;
restoreCursor: Boolean;
begin
oldCursor := Screen.Cursor;
if SrcLst.SelCount > 30 then
begin
Screen.Cursor := crHourGlass;
restoreCursor := True;
end
else
restoreCursor := False;
DstLst.Items.BeginUpdate;
try
srci := SrcLst.Selected;
while Assigned(srci) do
begin
if (srci.Caption = '') or
(DstLst.FindCaption(0, srci.Caption, False, True, False) = nil) then
begin
dsti := DstLst.Items.Add;
dsti.Assign(srci);
end;
srci := SrcLst.GetNextItem(srci, sdAll, [isSelected]);
end;
finally
DstLst.Items.EndUpdate;
if restoreCursor then
Screen.Cursor := oldCursor;
end;
end;
}
function TCCRSelectorTree.CreateResultList: TWinControl;
begin
Result := TCCRResultTree.Create(Self);
end;
function TCCRSelectorTree.CreateSourceList: TWinControl;
begin
Result := TCCRSourceList.Create(Self);
end;
procedure TCCRSelectorTree.DoUpdateButtons(var EnableAdd, EnableAddAll,
EnableRemove, EnableRemoveAll: Boolean);
begin
inherited;
if SourceList.Items.Count > 0 then
begin
EnableAdd := Assigned(SourceList.Selected);
EnableAddAll := True;
end
else
begin
EnableAdd := False;
EnableAddAll := False;
end;
if ResultTree.hasChildren[ResultTree.RootNode] then
begin
EnableRemove := (ResultTree.SelectedCount > 0);
EnableRemoveAll := True;
end
else
begin
EnableRemove := False;
EnableRemoveAll := False;
end;
end;
function TCCRSelectorTree.getResultTree: TCCRResultTree;
begin
Result := TCCRResultTree(GetResultControl);
end;
function TCCRSelectorTree.getSourceList: TCCRSourceList;
begin
Result := TCCRSourceList(GetSourceControl);
end;
procedure TCCRSelectorTree.LoadLayout(aStorage: TOvcAbstractStore; aSection: String);
var
sn: String;
begin
if aSection <> '' then
sn := aSection
else
sn := Name;
try
aStorage.Open;
try
SourceList.LoadLayout(aStorage, sn);
ResultTree.LoadLayout(aStorage, sn);
finally
aStorage.Close;
end;
except
end;
end;
procedure TCCRSelectorTree.Remove;
begin
if ResultTree.SelectedCount > 0 then
begin
inherited;
//--- Default processing
if not CustomRemove then
RemoveSelectedItems;
//--- Custom event handler
if Assigned(OnRemove) then
OnRemove(Self);
//--- Common post-processing
ResultChanged := True;
end;
end;
procedure TCCRSelectorTree.RemoveAll;
begin
inherited;
//--- Default processing
if not CustomRemove then
begin
ResultTree.SelectAll(False);
RemoveSelectedItems;
end;
//--- Custom event handler
if Assigned(OnRemoveAll) then
OnRemoveAll(Self);
//--- Common post-processing
ResultChanged := True;
end;
procedure TCCRSelectorTree.RemoveSelectedItems;
begin
end;
procedure TCCRSelectorTree.SaveLayout(aStorage: TOvcAbstractStore; aSection: String);
var
sn: String;
begin
if aSection <> '' then
sn := aSection
else
sn := Name;
try
aStorage.Open;
try
SourceList.SaveLayout(aStorage, sn);
ResultTree.SaveLayout(aStorage, sn);
finally
aStorage.Close;
end;
except
end;
end;
{
procedure TCCRSelectorTree.TransferSelectedItems(SrcLst, DstLst: TCCRSelectorList);
var
next: TCCRGridItem;
begin
SrcLst.Items.BeginUpdate;
try
if (SrcLst = SourceList) or (AddRemoveMode = armDefault) then
CopySelectedItems(SrcLst, DstLst);
if AutoSort then
DstLst.AlphaSort;
if SrcLst.SelCount > 0 then
begin
//--- Find the last selected item
next := SrcLst.Items[SrcLst.Items.Count-1];
if not next.Selected then
next := SrcLst.GetNextItem(next, sdAbove, [isSelected]);
//--- Find the next non-selected item
if Assigned(next) then
begin
next := SrcLst.GetNextItem(next, sdBelow, [isNone]);
if Assigned(next) then
if next.Selected then next := nil;
end;
//--- Remove the selected items from the list or unselect them
if (SrcLst = ResultTree) or (AddRemoveMode = armDefault) then
SrcLst.DeleteSelected
else
SrcLst.ClearSelection;
//--- Select the item
if Assigned(next) then
begin
SrcLst.Selected := next;
SrcLst.ItemFocused := SrcLst.Selected;
end
else if SrcLst.Items.Count > 0 then
begin
SrcLst.Selected := SrcLst.Items[SrcLst.Items.Count-1];
SrcLst.ItemFocused := SrcLst.Selected;
end;
end;
finally
SrcLst.Items.EndUpdate;
end;
end;
}
{$ENDIF}
end.
|
unit fGMV_DeviceSelector;
{
================================================================================
*
* Application: Vitals
* Revision: $Revision: 1 $ $Modtime: 3/02/09 9:47a $
* Developer: doma.user@domain.ext
* Site: Hines OIFO
*
* Description: Form for selecting a kernel device in applications
*
* Notes:
*
================================================================================
* $Archive: /Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_8/Source/APP-VITALSMANAGER/fGMV_DeviceSelector.pas $
*
* $History: fGMV_DeviceSelector.pas $
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 8/12/09 Time: 8:29a
* Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_8/Source/APP-VITALSMANAGER
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 3/09/09 Time: 3:38p
* Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_6/Source/APP-VITALSMANAGER
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 1/13/09 Time: 1:26p
* Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_4/Source/APP-VITALSMANAGER
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/11/07 Time: 3:12p
* Created in $/Vitals GUI 2007/Vitals-5-0-18/APP-VITALSMANAGER
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/16/06 Time: 5:40p
* Created in $/Vitals/VITALS-5-0-18/APP-VitalsManager
* GUI v. 5.0.18 updates the default vital type IENs with the local
* values.
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/16/06 Time: 5:30p
* Created in $/Vitals/Vitals-5-0-18/VITALS-5-0-18/APP-VitalsManager
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/24/05 Time: 4:56p
* Created in $/Vitals/Vitals GUI v 5.0.2.1 -5.0.3.1 - Patch GMVR-5-7 (CASMed, CCOW) - Delphi 6/VitalsManager-503
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 4/16/04 Time: 4:21p
* Created in $/Vitals/Vitals GUI Version 5.0.3 (CCOW, CPRS, Delphi 7)/VITALSMANAGER-503
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 1/26/04 Time: 1:06p
* Created in $/Vitals/Vitals GUI Version 5.0.3 (CCOW, Delphi7)/V5031-D7/Common
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 10/29/03 Time: 4:14p
* Created in $/Vitals503/Common
* Version 5.0.3
*
* ***************** Version 4 *****************
* User: Zzzzzzandria Date: 7/18/02 Time: 5:57p
* Updated in $/Vitals GUI Version 5.0/Common
*
* ***************** Version 3 *****************
* User: Zzzzzzandria Date: 7/12/02 Time: 5:01p
* Updated in $/Vitals GUI Version 5.0/Common
* GUI Version T28
*
* ***************** Version 2 *****************
* User: Zzzzzzandria Date: 7/05/02 Time: 3:49p
* Updated in $/Vitals GUI Version 5.0/Common
*
* ***************** Version 1 *****************
* User: Zzzzzzpetitd Date: 5/15/02 Time: 12:12p
* Created in $/Vitals GUI Version 5.0/Common
* Initial check-in
*
*
*
================================================================================
}
interface
uses
Windows,
Messages,
SysUtils,
Classes,
Graphics,
Controls,
Forms,
uGMV_Common,
Dialogs,
StdCtrls,
ComCtrls,
mGMV_Lookup, ExtCtrls
, mGMV_PrinterSelector
,uGMV_Const
;
type
TfrmGMV_DeviceSelector = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
btnOK: TButton;
btnCancel: TButton;
dtpTime: TDateTimePicker;
dtpDate: TDateTimePicker;
fraPrinterSelector: TfrGMV_PrinterSelector;
Panel3: TPanel;
gbQueue: TGroupBox;
gbSelected: TGroupBox;
edDevice: TEdit;
edTime: TEdit;
Panel4: TPanel;
procedure FormCreate(Sender: TObject);
procedure btnOKClick(Sender: TObject);
procedure dtpTimeChange(Sender: TObject);
procedure dtpDateChange(Sender: TObject);
procedure fraPrinterSelectorExit(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure gbQueueEnter(Sender: TObject);
procedure gbQueueExit(Sender: TObject);
procedure gbSelectedEnter(Sender: TObject);
procedure gbSelectedExit(Sender: TObject);
private
fDeviceString: string;
fQueueDateTime: Double;
CurrentTime: TDateTime;
procedure CM_UpdateSelection(var Message: TMessage); message CM_UPDATELOOKUP;
procedure updateDateTime;
public
{ Public declarations }
end;
TFMDateTime = Double;
function GetKernelDevice(var DeviceString: string; var QueueDateTime: TFMDateTime): Boolean;
implementation
uses uGMV_User, uGMV_Engine;
{$R *.DFM}
function GetKernelDevice(var DeviceString: string; var QueueDateTime: TFMDateTime): Boolean;
var
sID, sName: String;
begin
with TfrmGMV_DeviceSelector.Create(Application) do
try
sID := GMVUser.Setting[usLastVistAPrinter];
sName := getFileField('3.5','.01',sID);
if sName = '' then
fraPrinterSelector.ClearSelection
else
begin
fraPrinterSelector.DeviceIEN := sID;
fraPrinterSelector.DeviceName := sName;
fraPrinterSelector.edTarget.Text := sName;
// fraPrinterSelector.lblDevice.Caption := sName;
fraPrinterSelector.edTarget.selStart := 1;
fraPrinterSelector.edTarget.selLength := Length(sName);
edDevice.Text := sName;
end;
btnOK.Enabled := sID <> '';
Result := (ShowModal = mrOK);
if Result then
begin
DeviceString := fDeviceString;
QueueDateTime := fQueueDateTime;
end;
finally
free;
end;
end;
procedure TfrmGMV_DeviceSelector.FormCreate(Sender: TObject);
begin
CurrentTime := Now;
dtpDate.DateTime := CurrentTime;
dtpDate.MinDate := trunc(CurrentTime);
dtpTime.DateTime := CurrentTime;
end;
procedure TfrmGMV_DeviceSelector.btnOKClick(Sender: TObject);
begin
GMVUser.Setting[usLastVistaPrinter] := fraPrinterSelector.DeviceIEN;// fraDevice.IEN;
fDeviceString := fraPrinterSelector.DeviceName;// fraDevice.edtValue.Text;
fQueueDateTime := WindowsDateTimeToFMDateTime(trunc(dtpDate.Date) + (dtpTime.Time - trunc(dtpTime.Date)));
ModalResult := mrOK;
end;
procedure TfrmGMV_DeviceSelector.dtpTimeChange(Sender: TObject);
begin
if trunc(dtpDate.Date) + frac(dtpTime.Time) < CurrentTime then
dtpTime.DateTime := CurrentTime;
UpdateDateTime;
end;
procedure TfrmGMV_DeviceSelector.dtpDateChange(Sender: TObject);
begin
try
if dtpDate.DateTime < CurrentTime then
dtpDate.DateTime := CurrentTime;
except
end;
UpdateDateTime;
end;
procedure TfrmGMV_DeviceSelector.CM_UpdateSelection(var Message: TMessage);
begin
btnOK.Enabled := (fraPrinterSelector.DeviceIEN <> '');
btnOK.Default := btnOk.Enabled;
edDevice.Text := fraPrinterSelector.DeviceName;
UpdateDateTime;
end;
procedure TfrmGMV_DeviceSelector.fraPrinterSelectorExit(
Sender: TObject);
begin
btnOK.Enabled := (fraPrinterSelector.DeviceIEN <> '');
btnOK.Default := btnOk.Enabled;
end;
procedure TfrmGMV_DeviceSelector.FormKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if Key = VK_ESCAPE then ModalResult := mrCancel;
end;
procedure TfrmGMV_DeviceSelector.updateDateTime;
begin
edTime.Text := FormatDateTime('mm/dd/yyyy',dtpDate.Date)+ ' '+
FormatDateTime('hh:mm:ss',dtpTime.Time);
end;
procedure TfrmGMV_DeviceSelector.gbQueueEnter(Sender: TObject);
begin
gbQueue.Font.Style := [fsBold];
dtpDate.Font.Style := [];
dtpTime.Font.Style := [];
end;
procedure TfrmGMV_DeviceSelector.gbQueueExit(Sender: TObject);
begin
gbQueue.Font.Style := [];
end;
procedure TfrmGMV_DeviceSelector.gbSelectedEnter(Sender: TObject);
begin
gbSelected.Font.Style := [fsBold];
edDevice.FOnt.Style := [];
edTime.FOnt.Style := [];
end;
procedure TfrmGMV_DeviceSelector.gbSelectedExit(Sender: TObject);
begin
gbSelected.Font.Style := [];
end;
end.
|
{
ID: a2peter1
PROG: kimbits
LANG: PASCAL
}
{$B-,I-,Q-,R-,S-}
const
problem = 'kimbits';
MaxB = 31;
var
sol : string;
B,M,N,i,j : longword;
C : array[0..MaxB,0..MaxB] of int64;
begin
assign(input,problem + '.in'); reset(input);
assign(output,problem + '.out'); rewrite(output);
readln(B,M,N);
for i := 0 to B do C[0,i] := 1;
for i := 0 to B do C[i,0] := 1;
for i := 1 to B do
for j := 1 to B
do C[i,j] := C[i - 1,j] + C[i - 1,j - 1];
j := M;
for i := B downto 1 do
if N > C[i - 1,j] then
begin
sol := sol + '1';
dec(N,C[i - 1,j]); dec(j);
end{then ->}
else sol := sol + '0';
writeln(sol);
close(output);
end.{main}
|
{*******************************************************}
{ }
{ Delphi LiveBindings Framework }
{ }
{ Copyright(c) 2011-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit BindingGraphViewNodes;
interface
uses
System.SysUtils, Vcl.Graphics, System.Rtti, System.Bindings.Expression, GraphView;
type
TGraphNodeValue = class(TGraphNode)
private
FValueToStringCallback: TFunc<TValue, String>;
FValueAsContent: Boolean;
procedure SetValueAsContent(const Value: Boolean);
protected
function GetContent: String; override;
// if ValueVisible is True, the string returned by this method is attached
// on the next line in the caption; it returns an empty string, but
// descendant classes can use it to return emphasize important data
function GetValueString: String; virtual;
public
// specifies if the Content property is automatically set to Value
property ValueAsContent: Boolean read FValueAsContent write SetValueAsContent;
// called when ValueVisible is True and when the value of the property
// needs to be shown on the screen
property ValueToStringCallback: TFunc<TValue, String> read FValueToStringCallback
write FValueToStringCallback;
end;
// TGraphNodeExpr - maps binding expression
TGraphNodeExpr = class(TGraphNodeValue)
private
FExpression: TBindingExpression;
procedure SetExpression(const Value: TBindingExpression);
protected
// returns the result of the binding expression attached to the graph node
function GetValueString: String; override;
public
constructor Create(Owner: TGraph); override;
// the expression attached to a node
property Expression: TBindingExpression read FExpression write SetExpression;
end;
// TGraphNodeProp - maps a binding property of an object
TGraphNodeProp = class(TGraphNodeValue)
private
FRttiCtx: TRttiContext;
FPropertyInfo: TRttiProperty;
FObj: TObject;
FPropertyName: String;
procedure SetObj(const Value: TObject);
procedure SetPropertyName(const Value: String);
protected
// returns the value of ValueToStringCallback if ValueVisible is True or
// an empty string if it is False
function GetValueString: String; override;
// updates the internal fields depending on the value of Obj and PropName
procedure UpdateData;
public
constructor Create(AOwner: TGraph); override;
// the object that has the property denoted by the node
property Obj: TObject read FObj write SetObj;
// the name of the property
property PropertyName: String read FPropertyName write SetPropertyName;
// RTTI information on the property
property PropertyInfo: TRttiProperty read FPropertyInfo;
end;
implementation
{ TGraphNodeExpr }
constructor TGraphNodeExpr.Create(Owner: TGraph);
begin
inherited;
Owner.BeginUpdate;
Color := clGreen;
TextColor := clWhite;
Width := 50;
Height := 50;
KeepWidth := True;
KeepHeight := True;
Owner.EndUpdate;
end;
function TGraphNodeExpr.GetValueString: String;
begin
Result := '';
if Assigned(ValueToStringCallback) and Assigned(Expression) then
Result := ValueToStringCallback(Expression.OutputValue);
end;
procedure TGraphNodeExpr.SetExpression(const Value: TBindingExpression);
begin
if FExpression <> Value then
begin
FExpression := Value;
Update;
end;
end;
{ TGraphNodeProp }
constructor TGraphNodeProp.Create(AOwner: TGraph);
begin
inherited;
FRttiCtx := TRttiContext.Create;
Owner.BeginUpdate;
Color := clBlue;
TextColor := clWhite;
Width := 30;
Height := 30;
KeepWidth := True;
KeepHeight := True;
Owner.EndUpdate;
end;
function TGraphNodeValue.GetContent: String;
begin
if ValueAsContent then
Result := GetValueString
else
Result := inherited;
end;
function TGraphNodeValue.GetValueString: String;
begin
Result := '';
end;
function TGraphNodeProp.GetValueString: String;
begin
Result := '';
if Assigned(ValueToStringCallback) and Assigned(PropertyInfo) then
Result := ValueToStringCallback(PropertyInfo.GetValue(Obj));
end;
procedure TGraphNodeProp.SetObj(const Value: TObject);
begin
if FObj <> Value then
begin
FObj := Value;
UpdateData;
Update;
end;
end;
procedure TGraphNodeProp.SetPropertyName(const Value: String);
begin
if FPropertyName <> Value then
begin
FPropertyName := Value;
UpdateData;
Update;
end;
end;
procedure TGraphNodeValue.SetValueAsContent(const Value: Boolean);
begin
if FValueAsContent <> Value then
begin
FValueAsContent := Value;
UpdateFitText;
Update;
end;
end;
procedure TGraphNodeProp.UpdateData;
begin
FPropertyInfo := nil;
if Assigned(Obj) then
FPropertyInfo := FRttiCtx.GetType(Obj.ClassInfo).GetProperty(FPropertyName);
end;
end.
|
{$mode objfpc}{$H+}{$J-}
program Problem_4;
const
PI = 3.14; { not really needed, as Pascal has a built-in Pi operator,
which actually yields a more precise Pi value. }
var
radius: Real;
begin
writeln('Circle''s area is calculated as S = πr^2.');
end. |
unit rhlMurmur3_128;
interface
uses
rhlCore;
type
{ TrhlMurmur3_128 }
TrhlMurmur3_128 = class(TrhlHashWithKey)
private
const
CKEY: DWord = $C58F1A7B;
C1: QWord = $87C37B91114253D5;
C2: QWord = $4CF5AD432745937F;
C3: DWord = $52DCE729;
C4: DWord = $38495AB5;
C5: QWord = $FF51AFD7ED558CCD;
C6: QWord = $C4CEB9FE1A85EC53;
var
m_h1, m_h2: QWord;
m_key: DWord;
protected
procedure UpdateBlock(const ABuffer); override;
function GetKey: TBytes; override;
procedure SetKey(AValue: TBytes); override;
public
constructor Create; override;
procedure Init; override;
procedure Final(var ADigest); override;
end;
implementation
{ TrhlMurmur3_128 }
procedure TrhlMurmur3_128.UpdateBlock(const ABuffer);
var
k1, k2: QWord;
a_data: array[0..0] of Byte absolute ABuffer;
begin
k1 := QWord(a_data[0]) or QWord(a_data[1]) shl 8 or
QWord(a_data[2]) shl 16 or QWord(a_data[3]) shl 24 or
QWord(a_data[4]) shl 32 or QWord(a_data[5]) shl 40 or
QWord(a_data[6]) shl 48 or QWord(a_data[7]) shl 56;
k1 := k1 * C1;
k1 := (k1 shl 31) or (k1 shr 33);
k1 := k1 * C2;
m_h1 := m_h1 xor k1;
m_h1 := (m_h1 shl 27) or (m_h1 shr 37);
m_h1 := m_h1 + m_h2;
m_h1 := m_h1 * 5 + C3;
k2 := QWord(a_data[8]) or QWord(a_data[9]) shl 8 or
QWord(a_data[10]) shl 16 or QWord(a_data[11]) shl 24 or
QWord(a_data[12]) shl 32 or QWord(a_data[13]) shl 40 or
QWord(a_data[14]) shl 48 or QWord(a_data[15]) shl 56;
k2 *= C2;
k2 := (k2 shl 33) or (k2 shr 31);
k2 *= C1;
m_h2 := m_h2 xor k2;
m_h2 := (m_h2 shl 31) or (m_h2 shr 33);
m_h2 += m_h1;
m_h2 := m_h2 * 5 + C4;
end;
function TrhlMurmur3_128.GetKey: TBytes;
begin
SetLength(Result, SizeOf(DWord));
Move(m_key, Result[0], SizeOf(DWord));
end;
procedure TrhlMurmur3_128.SetKey(AValue: TBytes);
begin
if Length(AValue) = SizeOf(m_key) then
Move(AValue[0], m_key, SizeOf(m_key));
end;
constructor TrhlMurmur3_128.Create;
begin
HashSize := 16;
BlockSize := 16;
m_key := CKEY;
end;
procedure TrhlMurmur3_128.Init;
begin
inherited Init;
m_h1 := m_key;
m_h2 := m_key;
end;
procedure TrhlMurmur3_128.Final(var ADigest);
var
data: array[0..15] of Byte;
k2, k1: QWord;
len: Integer;
b: PByte;
begin
len := FBuffer.Pos;
FBuffer.SetZeroPadded;
Move(FBuffer.Bytes[0], data[0], SizeOf(data));
case len of
15:
begin
k2 := QWord(data[14]) << 48 xor
QWord(data[13]) << 40 xor
QWord(data[12]) << 32 xor
QWord(data[11]) << 24 xor
QWord(data[10]) << 16 xor
QWord(data[9]) << 8 xor
QWord(data[8]) << 0;
k2 *= C2;
k2 := (k2 << 33) or (k2 >> 31);
k2 *= C1;
m_h2 := m_h2 xor k2;
end;
14:
begin
k2 := QWord(data[13]) << 40 xor
QWord(data[12]) << 32 xor
QWord(data[11]) << 24 xor
QWord(data[10]) << 16 xor
QWord(data[9]) << 8 xor
QWord(data[8]) << 0;
k2 *= C2;
k2 := (k2 << 33) or (k2 >> 31);
k2 *= C1;
m_h2 := m_h2 xor k2;
end;
13:
begin
k2 := QWord(data[12]) << 32 xor
QWord(data[11]) << 24 xor
QWord(data[10]) << 16 xor
QWord(data[9]) << 8 xor
QWord(data[8]) << 0;
k2 *= C2;
k2 := (k2 << 33) or (k2 >> 31);
k2 *= C1;
m_h2 := m_h2 xor k2;
end;
12:
begin
k2 := QWord(data[11]) << 24 xor
QWord(data[10]) << 16 xor
QWord(data[9]) << 8 xor
QWord(data[8]) << 0;
k2 *= C2;
k2 := (k2 << 33) or (k2 >> 31);
k2 *= C1;
m_h2 := m_h2 xor k2;
end;
11:
begin
k2 := QWord(data[10]) << 16 xor
QWord(data[9]) << 8 xor
QWord(data[8]) << 0;
k2 *= C2;
k2 := (k2 << 33) or (k2 >> 31);
k2 *= C1;
m_h2 := m_h2 xor k2;
end;
10:
begin
k2 := QWord(data[9]) << 8 xor
QWord(data[8]) << 0;
k2 *= C2;
k2 := (k2 << 33) or (k2 >> 31);
k2 *= C1;
m_h2 := m_h2 xor k2;
end;
9:
begin
k2 := QWord(data[8]) << 0;
k2 *= C2;
k2 := (k2 << 33) or (k2 >> 31);
k2 *= C1;
m_h2 := m_h2 xor k2;
end;
end;
if (len > 8) then
len := 8;
case len of
8:
begin
k1 := QWord(data[7]) << 56 xor
QWord(data[6]) << 48 xor
QWord(data[5]) << 40 xor
QWord(data[4]) << 32 xor
QWord(data[3]) << 24 xor
QWord(data[2]) << 16 xor
QWord(data[1]) << 8 xor
QWord(data[0]) << 0;
k1 *= C1;
k1 := (k1 << 31) or (k1 >> 33);
k1 *= C2;
m_h1 := m_h1 xor k1;
end;
7:
begin
k1 := QWord(data[6]) << 48 xor
QWord(data[5]) << 40 xor
QWord(data[4]) << 32 xor
QWord(data[3]) << 24 xor
QWord(data[2]) << 16 xor
QWord(data[1]) << 8 xor
QWord(data[0]) << 0;
k1 *= C1;
k1 := (k1 << 31) or (k1 >> 33);
k1 *= C2;
m_h1 := m_h1 xor k1;
end;
6:
begin
k1 := QWord(data[5]) << 40 xor
QWord(data[4]) << 32 xor
QWord(data[3]) << 24 xor
QWord(data[2]) << 16 xor
QWord(data[1]) << 8 xor
QWord(data[0]) << 0;
k1 *= C1;
k1 := (k1 << 31) or (k1 >> 33);
k1 *= C2;
m_h1 := m_h1 xor k1;
end;
5:
begin
k1 := QWord(data[4]) << 32 xor
QWord(data[3]) << 24 xor
QWord(data[2]) << 16 xor
QWord(data[1]) << 8 xor
QWord(data[0]) << 0;
k1 *= C1;
k1 := (k1 << 31) or (k1 >> 33);
k1 *= C2;
m_h1 := m_h1 xor k1;
end;
4:
begin
k1 := QWord(data[3]) << 24 xor
QWord(data[2]) << 16 xor
QWord(data[1]) << 8 xor
QWord(data[0]) << 0;
k1 *= C1;
k1 := (k1 << 31) or (k1 >> 33);
k1 *= C2;
m_h1 := m_h1 xor k1;
end;
3:
begin
k1 := QWord(data[2]) << 16 xor
QWord(data[1]) << 8 xor
QWord(data[0]) << 0;
k1 *= C1;
k1 := (k1 << 31) or (k1 >> 33);
k1 *= C2;
m_h1 := m_h1 xor k1;
end;
2:
begin
k1 := QWord(data[1]) << 8 xor
QWord(data[0]) << 0;
k1 *= C1;
k1 := (k1 << 31) or (k1 >> 33);
k1 *= C2;
m_h1 := m_h1 xor k1;
end;
1:
begin
k1 := QWord(data[0]) << 0;
k1 *= C1;
k1 := (k1 << 31) or (k1 >> 33);
k1 *= C2;
m_h1 := m_h1 xor k1;
end;
end;
m_h1 := m_h1 xor QWord(FProcessedBytes);
m_h2 := m_h2 xor QWord(FProcessedBytes);
m_h1 += m_h2;
m_h2 += m_h1;
m_h1 := m_h1 xor (m_h1 >> 33);
m_h1 *= C5;
m_h1 := m_h1 xor (m_h1 >> 33);
m_h1 *= C6;
m_h1 := m_h1 xor (m_h1 >> 33);
m_h2 := m_h2 xor (m_h2 >> 33);
m_h2 *= C5;
m_h2 := m_h2 xor (m_h2 >> 33);
m_h2 *= C6;
m_h2 := m_h2 xor (m_h2 >> 33);
m_h1 += m_h2;
m_h2 += m_h1;
b := @ADigest;
Move(m_h1, b^, SizeOf(QWord));
Inc(b, SizeOf(QWord));
Move(m_h2, b^, SizeOf(QWord));
end;
end.
|
unit rhlCore;
{$MODESWITCH ADVANCEDRECORDS+}
interface
uses
sysutils;
type
TBytes = array of Byte;
{ TrhlHashBuffer }
TrhlHashBuffer = record
private
FBuffer: TBytes;
FPos: LongWord;
function GetSize: LongWord;
procedure SetSize(AValue: LongWord);
public
procedure Init;
function Feed(var AData; var ALength: LongWord; var AProcessedBytes: LongWord): LongWord;
function IsEmpty: Boolean;
function IsFull: Boolean;
procedure SetZeroPadded;
property Bytes: TBytes read FBuffer;
property Size: LongWord read GetSize write SetSize;
property Pos: LongWord read FPos;
end;
{ TrhlHash }
TrhlHash = class abstract(TObject)
private
function GetBlockSize: LongWord;
protected
FHashSize: LongWord;
FBuffer: TrhlHashBuffer;
FProcessedBytes: LongWord;
procedure SetHashSize(AValue: LongWord); virtual;
procedure SetBlockSize(AValue: LongWord);
procedure UpdateBuffer; virtual;
procedure UpdateBytes(const ABuffer; ASize: LongWord); virtual;
procedure UpdateBlock(const ABuffer); virtual;
public
constructor Create; virtual; abstract;
procedure Init; virtual;
procedure Update(const AStr: ansistring); virtual;
procedure Final(var ADigest); virtual; abstract;
property HashSize: LongWord read FHashSize write SetHashSize;
property BlockSize: LongWord read GetBlockSize write SetBlockSize;
end;
TrhlHashClass = class of TrhlHash;
{ TrhlHashWithKey }
TrhlHashWithKey = class abstract(TrhlHash)
protected
function GetKey: TBytes; virtual;
procedure SetKey(AValue: TBytes); virtual;
public
property Key: TBytes read GetKey write SetKey;
end;
TrhlHashWithKeyClass = class of TrhlHashWithKey;
function rhlHash(const text: ansistring; dig: TrhlHashClass): ansistring; overload;
function rhlHash(const text, key: ansistring; dig: TrhlHashWithKeyClass): ansistring; overload;
function rhlHMAC(message, key: ansistring; hash: TrhlHashClass; blocksize: Integer = 64): ansistring;
function rhlPBKDF1(const pass, salt: ansistring; count: Integer; hash: TrhlHashClass): ansistring; overload; // standard
function rhlPBKDF1(const pass, salt: ansistring; count, kLen: Integer; hash: TrhlHashClass; Reset: Boolean = True): ansistring; overload; // dotNET
function rhlPBKDF2(const pass, salt: ansistring; count, kLen: Integer; hash: TrhlHashClass): ansistring;
procedure ConvertBytesToDWordsSwapOrder(const b; l: Integer; var r);
procedure ConvertBytesToQWordsSwapOrder(const b; l: Integer; var r);
procedure ConvertQWordsToBytesSwapOrder(const w; l: Integer; var r);
procedure ConvertDWordsToBytesSwapOrder(const w; l: Integer; var r);
implementation
uses
math;
function RPad(const x: ansistring; const c: Char; const s: Integer): ansistring;
var
i: Integer;
begin
Result := x;
if Length(x) < s then
for i := 1 to s-Length(x) do
Result := Result + c;
end;
function XorBlock(s, x: ansistring): ansistring; inline;
var
i: Integer;
begin
SetLength(Result, Length(s));
for i := 1 to Length(s) do
Result[i] := Char(Byte(s[i]) xor Byte(x[i]));
end;
function rhlHash(const text: ansistring; dig: TrhlHashClass): ansistring;
var
x: TrhlHash;
begin
x := dig.Create;
try
x.Init;
x.Update(text);
SetLength(Result, x.HashSize);
x.Final(Result[1]);
finally
x.Free;
end;
end;
function rhlHash(const text, key: ansistring; dig: TrhlHashWithKeyClass
): ansistring;
var
x: TrhlHashWithKey;
b: TBytes;
i: Integer;
begin
x := dig.Create;
try
i := Length(key);
if i > 0 then
begin
SetLength(b, i);
Move(key[1], b[0], i);
x.Key := b;
end;
x.Init;
x.Update(text);
SetLength(Result, x.HashSize);
x.Final(Result[1]);
finally
x.Free;
end;
end;
function rhlHMAC(message, key: ansistring; hash: TrhlHashClass;
blocksize: Integer): ansistring;
begin
// Definition RFC 2104
if Length(key) > blocksize then
key := rhlHash(key, hash);
key := RPad(key, #0, blocksize);
Result := rhlHash(XorBlock(key, RPad('', #$36, blocksize)) + message, hash);
Result := rhlHash(XorBlock(key, RPad('', #$5c, blocksize)) + result, hash);
end;
function rhlPBKDF1(const pass, salt: ansistring; count: Integer; hash: TrhlHashClass
): ansistring;
var
i: Integer;
begin
Result := pass+salt;
for i := 0 to count-1 do
Result := rhlHash(Result, hash);
end;
function rhlPBKDF1(const pass, salt: ansistring; count, kLen: Integer;
hash: TrhlHashClass; Reset: Boolean): ansistring;
{$WRITEABLECONST ON}
const
PBKDF1_base: ansistring = '';
PBKDF1_extra: ansistring = '';
PBKDF1_extracount: Integer = 0;
PBKDF1_hashno: Integer = 0;
PBKDF1_state: Integer = 0;
{$WRITEABLECONST OFF}
var
i: Integer;
rlen: Integer;
cb: Integer;
clen: Integer;
current: ansistring;
remain: Integer;
begin
//http://stackoverflow.com/questions/9011635/how-do-i-convert-this-c-sharp-rijndael-encryption-to-php
if Reset then
begin
PBKDF1_state := 0;
PBKDF1_hashno := 0;
PBKDF1_extra := '';
PBKDF1_extracount := 0;
PBKDF1_base := '';
end;
cb := kLen;
if (PBKDF1_state = 0) then
begin
PBKDF1_hashno := 0;
PBKDF1_state := 1;
PBKDF1_base := pass + salt;
for i := 1 to count - 1 do
PBKDF1_base := rhlHash(PBKDF1_base, hash);
end;
result := '';
if (PBKDF1_extracount > 0) then
begin
rlen := Length(PBKDF1_extra) - PBKDF1_extracount;
if (rlen >= cb) then
begin
result := Copy(PBKDF1_extra, PBKDF1_extracount+1, cb);
if (rlen > cb) then
begin
PBKDF1_extracount := PBKDF1_extracount + cb;
end
else
begin
PBKDF1_extra := '';
PBKDF1_extracount := 0;
end;
//return $result;
exit;
end;
result := Copy(PBKDF1_extra, rlen+1, rlen);
end;
current := '';
clen := 0;
remain := cb - Length(result);
while (remain > clen) do
begin
if (PBKDF1_hashno = 0) then
current := rhlHash(PBKDF1_base, hash)
else
if (PBKDF1_hashno < 1000) then
current := current + rhlHash(IntToStr(PBKDF1_hashno)+PBKDF1_base, hash)
else
exit;
Inc(PBKDF1_hashno);
clen := Length(current);
end;
// $current now holds at least as many bytes as we need
result := result + Copy(current, 1, remain);
// Save any left over bytes for any future requests
if (clen > remain) then
begin
PBKDF1_extra := current;
PBKDF1_extracount := remain;
end;
//return $result;
end;
function rhlPBKDF2(const pass, salt: ansistring; count, kLen: Integer;
hash: TrhlHashClass): ansistring;
function IntX(i: Integer): ansistring; inline;
begin
Result := Char(i shr 24) + Char(i shr 16) + Char(i shr 8) + Char(i);
end;
var
D, I, J: Integer;
T, F, U: ansistring;
H: TrhlHash;
begin
H := hash.Create;
try
T := '';
D := Ceil(kLen / (H.HashSize div 8));
finally
H.Free;
end;
for i := 1 to D do
begin
F := rhlHMAC(salt + IntX(i), pass, hash);
U := F;
for j := 2 to count do
begin
U := rhlHMAC(U, pass, hash);
F := XorBlock(F, U);
end;
T := T + F;
end;
Result := Copy(T, 1, kLen);
end;
procedure ConvertBytesToDWordsSwapOrder(const b; l: Integer; var r);
var
bb: array[0..0] of Byte absolute b;
rr: array[0..0] of DWord absolute r;
i, j: DWord;
begin
i := 0;
j := 0;
while l > 0 do
begin
rr[i] :=
(bb[j ] shl 24) or
(bb[j+1] shl 16) or
(bb[j+2] shl 8) or
(bb[j+3]);
Inc(i);
Inc(j, SizeOf(DWord));
Dec(l, SizeOf(DWord));
end;
end;
procedure ConvertBytesToQWordsSwapOrder(const b; l: Integer; var r);
var
bb: array[0..0] of Byte absolute b;
rr: array[0..0] of QWord absolute r;
i, j: Integer;
begin
i := 0;
j := 0;
while l > 0 do
begin
rr[i] :=
(QWord(bb[j ]) shl 56) or
(QWord(bb[j+1]) shl 48) or
(QWord(bb[j+2]) shl 40) or
(QWord(bb[j+3]) shl 32) or
(QWord(bb[j+4]) shl 24) or
(QWord(bb[j+5]) shl 16) or
(QWord(bb[j+6]) shl 8) or
(QWord(bb[j+7]));
Inc(i);
Inc(j, SizeOf(QWord));
Dec(l, SizeOf(QWord));
end;
end;
procedure ConvertQWordsToBytesSwapOrder(const w; l: Integer; var r);
var
i, j: Integer;
ww: array[0..0] of QWord absolute w;
t: QWord;
rr: array[0..0] of Byte absolute r;
begin
j := 0;
i := 0;
while l > 0 do
begin
t := ww[i];
rr[j+0] := Byte($ff and (t shr 56));
rr[j+1] := Byte($ff and (t shr 48));
rr[j+2] := Byte($ff and (t shr 40));
rr[j+3] := Byte($ff and (t shr 32));
rr[j+4] := Byte($ff and (t shr 24));
rr[j+5] := Byte($ff and (t shr 16));
rr[j+6] := Byte($ff and (t shr 8));
rr[j+7] := Byte($ff and (t));
Inc(j, SizeOf(QWord));
Inc(i);
Dec(l);
end
end;
procedure ConvertDWordsToBytesSwapOrder(const w; l: Integer; var r);
var
ww: array[0..0] of DWord absolute w;
t: DWord;
rr: array[0..0] of Byte absolute r;
i, j: Integer;
begin
j := 0;
i := 0;
while l > 0 do
begin
t := ww[i];
rr[j+0] := $ff and (t shr 24);
rr[j+1] := $ff and (t shr 16);
rr[j+2] := $ff and (t shr 8);
rr[j+3] := $ff and (t);
Inc(j, SizeOf(DWord));
Inc(i);
Dec(l);
end
end;
{ TrhlHashWithKey }
function TrhlHashWithKey.GetKey: TBytes;
begin
end;
procedure TrhlHashWithKey.SetKey(AValue: TBytes);
begin
end;
{ TrhlHashBuffer }
function TrhlHashBuffer.GetSize: LongWord;
begin
Result := Length(FBuffer);
end;
procedure TrhlHashBuffer.SetSize(AValue: LongWord);
begin
SetLength(FBuffer, AValue);
end;
procedure TrhlHashBuffer.Init;
begin
FPos := 0;
end;
function TrhlHashBuffer.Feed(var AData; var ALength: LongWord;
var AProcessedBytes: LongWord): LongWord;
var
len: LongWord;
begin
if (ALength = 0) then
Exit(0);
len := GetSize - FPos;
if (len > ALength) then
len := ALength;
Move(AData, FBuffer[FPos], len);
Inc(FPos, len);
Inc(AProcessedBytes, len);
Dec(ALength, len);
Result := len;
end;
function TrhlHashBuffer.IsEmpty: Boolean;
begin
Result := FPos = 0;
end;
function TrhlHashBuffer.IsFull: Boolean;
begin
Result := FPos = GetSize;
end;
procedure TrhlHashBuffer.SetZeroPadded;
var
i: Integer;
begin
for i := Pos to Size - 1 do
FBuffer[i] := 0;
FPos := 0;
end;
{ TrhlHash }
procedure TrhlHash.SetBlockSize(AValue: LongWord);
begin
FBuffer.Size := AValue;
end;
function TrhlHash.GetBlockSize: LongWord;
begin
Result := FBuffer.Size;
end;
procedure TrhlHash.SetHashSize(AValue: LongWord);
begin
FHashSize := AValue;
end;
procedure TrhlHash.UpdateBuffer;
begin
UpdateBlock(FBuffer.Bytes[0]);
end;
procedure TrhlHash.UpdateBytes(const ABuffer; ASize: LongWord);
var
PBuf: ^Byte;
Offset: LongWord;
begin
PBuf := @ABuffer;
if (not FBuffer.IsEmpty) then
begin
Offset := FBuffer.Feed(PBuf^, ASize, FProcessedBytes);
if Offset > 0 then
begin
UpdateBuffer;
Inc(PBuf, Offset);
end;
end;
while (ASize >= FBuffer.Size) do
begin
Inc(FProcessedBytes, FBuffer.Size);
UpdateBlock(PBuf^);
Inc(PBuf, FBuffer.Size);
Dec(ASize, FBuffer.Size);
end;
if (ASize > 0) then
FBuffer.Feed(PBuf^, ASize, FProcessedBytes);
end;
procedure TrhlHash.UpdateBlock(const ABuffer);
begin
end;
procedure TrhlHash.Init;
begin
FBuffer.Init;
FProcessedBytes := 0;
end;
procedure TrhlHash.Update(const AStr: ansistring);
begin
UpdateBytes(AStr[1], Length(AStr));
end;
end.
|
{===============================================================================
Copyright(c) 2006-2009, 北京北研兴电力仪表有限责任公司
All rights reserved.
公用电表数据单元
+ TMeterDataItem 电表数据-数据项
+ TMeterDataGroup 电表数据-组数据
+ TMeterData 电表数据
+ TMETER_DATA_GROUP_DL645 基于标准DL645协议的组数据
===============================================================================}
unit xMeterDataRect;
interface
uses SysUtils, Classes, xFunction, xDL645Type;
type
/// <summary>
/// 电表数据-数据项
/// </summary>
TMeterDataItem = class(TPersistent)
private
FSign : Int64;
FNote : string;
FFormat : string;
FUnits : string;
FLength : Integer;
FValue : string;
FOnValueChanged: TNotifyEvent;
FTagString: string;
FTagInt: Integer;
FTagObject: TObject;
procedure SetValue( Val : string );
published
/// <summary>
/// 标识
/// </summary>
property Sign : Int64 read FSign write FSign;
/// <summary>
/// 说明
/// </summary>
property Note : string read FNote write FNote;
/// <summary>
/// 格式
/// </summary>
property Format : string read FFormat write FFormat;
/// <summary>
/// 单位
/// </summary>
property Units : string read FUnits write FUnits;
/// <summary>
/// 长度
/// </summary>
property Length : Integer read FLength write FLength;
/// <summary>
/// 值
/// </summary>
property Value : string read FValue write SetValue;
property TagInt : Integer read FTagInt write FTagInt;
property TagString : string read FTagString write FTagString;
property TagObject : TObject read FTagObject write FTagObject;
/// <summary>
/// 对象赋值
/// </summary>
procedure Assign(Source: TPersistent); override;
public
function SignInHex : string;
/// <summary>
/// 值改变
/// </summary>
property OnValueChanged : TNotifyEvent read FOnValueChanged write fOnValueChanged;
end;
type
/// <summary>
/// 电表数据-组数据
/// </summary>
TMeterDataGroup = class( TPersistent )
private
FItems : TStringList;
FGroupName: string;
FVerifyValue : Boolean;
function GetItem( nSign : Int64 ) : TMeterDataItem;
function GetItemValue( nSign : Int64 ) : string;
procedure SetItemValue( nSign : Int64; const Value : string );
procedure SetGroupName(const Value: string);
protected
public
constructor Create;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure AssignValue(Source: TPersistent);
/// <summary>
/// 是否校验数据
/// </summary>
property VerifyValue : Boolean read FVerifyValue write FVerifyValue;
/// <summary>
/// 组名称
/// </summary>
property GroupName : string read FGroupName write SetGroupName;
/// <summary>
/// 所有数据项
/// </summary>
property Items : TStringList read FItems;
/// <summary>
/// 数据项
/// </summary>
/// <param name="nSign">数据标识</param>
property Item[ nSign : Int64 ] : TMeterDataItem read GetItem;
/// <summary>
/// 数据项的值
/// </summary>
property ItemValue[ nSign : Int64 ] : string read GetItemValue write
SetItemValue;
/// <summary>
/// 新建一个数据项, 如果已存在,则返回的已有数据项
/// </summary>
/// <param name="nSign">数据标识</param>
/// <returns>数据项</returns>
function NewItem( nSign : Int64 ) : TMeterDataItem; overload;virtual;
/// <summary>
/// 删除数据项
/// </summary>
procedure DelItem( nSign : Int64 );
/// <summary>
/// 新建一个数据项, 如果已存在,则返回的已有数据项
/// </summary>
/// <param name="nSign">标识</param>
/// <param name="sFormat">格式</param>
/// <param name="nLen">长度</param>
/// <param name="sUnit">单位</param>
/// <param name="sNote">说明</param>
/// <returns>数据项</returns>
function NewItem(nSign: Int64; sFormat: string; nLen: integer;
sUnit, sNote: string) : TMeterDataItem; overload;virtual;
/// <summary>
/// 删除所有数据项
/// </summary>
procedure DeleteAllItems;
/// <summary>
/// 清空所有数据项的值
/// </summary>
procedure ClearAllItemsValue;
end;
type
/// <summary>
/// 电表数据
/// </summary>
TMeterData = class( TPersistent )
private
FAutoCreateGroup : Boolean;
FAutoCreateItem : Boolean;
FDefaultGroupName : string;
FGroups : TStringList; // 所有分组和数据项
FGroupStructure : TMeterDataGroup;
function GetDefaultGroupName : string;
procedure SetDefaultGroupName( const Value : string );
function GetGroup( sGroupName : string ) : TMeterDataGroup;
function GetGroupItem( sGroupName : string; nSign : Int64 ) :
TMeterDataItem;
function GetDefaultGroupItem( nSign : Int64 ) : TMeterDataItem;
function GetGroupItemValue( sGroupName : string; nSign : Int64 ) : string;
procedure SetGroupItemValue( sGroupName : string; nSign : Int64;
const Value: string);
function GetDefaultGroupItemValue( nSign : Int64 ) : string;
procedure SetDefaultGroupItemValue( nSign : Int64; const Value: string);
public
constructor Create;
destructor Destroy; override;
/// <summary>
/// 复制MeterData对象
/// </summary>
procedure Assign(Source: TPersistent); override;
/// <summary>
/// 新的组数据
/// </summary>
/// <param name="sGroupName">组名称</param>
/// <returns>组数据</returns>
function NewGroup( sGroupName : string ) : TMeterDataGroup;virtual;
/// <summary>
/// 删除某一组数据
/// </summary>
procedure DeleteGroup( sGroupName : string );
/// <summary>
/// 删除所有组数据
/// </summary>
procedure DeleteAllGroups;
/// <summary>
/// 清空某一组所有数据项的值
/// </summary>
procedure ClearGroupItemsValue( sGroupName : string );
/// <summary>
/// 清空所有数据
/// </summary>
procedure ClearAllGroupItemsValue;
/// <summary>
/// 清空默认组所有数据项的值
/// </summary>
procedure ClearItemsValue;
/// <summary>
/// 是否自动创建分组(读取组是如果没有组则先创建组再返回)
/// </summary>
property AutoCreateGroup : Boolean read FAutoCreateGroup
write FAutoCreateGroup;
/// <summary>
/// 是否自动创建数据项(读取数据项时如果没有数据项则先创建数据项再返回)
/// </summary>
property AutoCreateItem : Boolean read FAutoCreateItem
write FAutoCreateItem;
/// <summary>
/// 所有组数据
/// </summary>
property Groups : TStringList read FGroups;
/// <summary>
/// 默认的组结构(组中应包含的数据项)
/// </summary>
property GroupStructure : TMeterDataGroup read FGroupStructure
write FGroupStructure;
/// <summary>
/// 默认的组名称
/// </summary>
property DefaultGroupName : string read GetDefaultGroupName
write SetDefaultGroupName;
/// <summary>
/// 组数据
/// </summary>
/// <param name="sGroupName">组名称</param>
property Group[ sGroupName : string ] : TMeterDataGroup read GetGroup;
/// <summary>
/// 分组中的数据项
/// </summary>
/// <param name="sGroupName">组名称</param>
/// <param name="nSign">数据标识</param>
property GroupItem[ sGroupName : string; nSign : Int64 ]: TMeterDataItem
read GetGroupItem;
/// <summary>
/// 默认组中的数据项
/// </summary>
/// </summary>
/// <param name="sGroupName">组名称</param>
/// <param name="nSign">数据标识</param>
property Item[ nSign : Int64 ] : TMeterDataItem
read GetDefaultGroupItem;
/// <summary>
/// 分组中数据项的值
/// </summary>
/// <param name="sGroupName">组名称</param>
/// <param name="nSign">数据标识</param>
property GroupItemValue[ sGroupName : string; nSign : Int64 ]: string
read GetGroupItemValue write SetGroupItemValue;
/// <summary>
/// 默认组中数据项的值
/// </summary>
/// <param name="sGroupName">组名称</param>
/// <param name="nSign">数据标识</param>
property ItemValue[ nSign : Int64 ]: string read GetDefaultGroupItemValue
write SetDefaultGroupItemValue;
end;
type
/// <summary>
/// 基于标准DL645协议的组数据
/// </summary>
TMETER_DATA_GROUP_DL645 = class( TMeterDataGroup )
private
/// <summary>
/// 添加一般数据
/// </summary>
/// <param name="sType">数据类型</param>
/// <param name="nBaseSign">起始数据标识</param>
/// <param name="nLen">长度</param>
/// <param name="sFormat">格式</param>
/// <param name="sUnitA">有功单位</param>
/// <param name="sUnitU">无功单位</param>
procedure AddNormalData( sType: string; nBaseSign : Integer;
nLen : Integer; sFormat, sUnitA, sUnitU : string );
/// <summary>
/// 添加时段信息数据
/// </summary>
procedure AddTimePeriodData;
/// <summary>
/// 添加变量和参变量
/// </summary>
procedure AddVariableData;
public
constructor Create;
end;
/// <summary>
/// 校验电表数据项
/// </summary>
procedure VerifyMeterDataItem( AItem : TMeterDataItem );
/// <summary>
/// 核对数据格式
/// </summary>
function VerifiedStr( const sData, sFormat : string; nLen : Integer ) : string;
/// <summary>
/// 修正数据用于显示
/// </summary>
function FixDataForShow( AData: string; AFormat: string; ALen: Integer) : string; overload;
function FixDataForShow( AData: TBytes; AFormat: string; ALen: Integer) : string; overload;
implementation
{ TMETER_READING }
procedure TMeterDataItem.Assign(Source: TPersistent);
begin
Assert( Source is TMeterDataItem );
FSign := TMeterDataItem( Source ).Sign ;
FNote := TMeterDataItem( Source ).Note ;
FFormat := TMeterDataItem( Source ).Format;
FUnits := TMeterDataItem( Source ).Units ;
FLength := TMeterDataItem( Source ).Length;
FValue := TMeterDataItem( Source ).Value ;
FTagInt := TMeterDataItem( Source ).TagInt;
FTagString := TMeterDataItem( Source ).TagString ;
FTagObject := TMeterDataItem( Source ).TagObject ;
end;
{ TMeterData }
procedure TMeterData.Assign(Source: TPersistent);
var
i : Integer;
begin
Assert( Source is TMeterData );
ClearStringList( Groups );
AutoCreateGroup := TMeterData( Source ).AutoCreateGroup;
AutoCreateItem := TMeterData( Source ).AutoCreateItem;
DefaultGroupName := TMeterData( Source ).DefaultGroupName;
GroupStructure.Assign( TMeterData( Source ).GroupStructure );
Groups.Text := TMeterData( Source ).Groups.Text;
for i := 0 to TMeterData( Source ).Groups.Count -1 do
begin
Groups.Objects[ i ] := TMeterDataGroup.Create;
TMeterDataGroup( Groups.Objects[ i ] ).Assign( TMeterDataGroup(
TMeterData( Source ).Groups.Objects[ i ] ) );
end;
end;
procedure TMeterData.ClearAllGroupItemsValue;
var
i: Integer;
begin
for i := 0 to FGroups.Count - 1 do
ClearGroupItemsValue( FGroups[ i ] );
end;
procedure TMeterData.ClearGroupItemsValue(sGroupName: string);
var
mdGroup : TMeterDataGroup;
begin
mdGroup := GetGroup( sGroupName );
if Assigned( mdGroup ) then
mdGroup.ClearAllItemsValue;
end;
procedure TMeterData.ClearItemsValue;
begin
ClearGroupItemsValue( FDefaultGroupName );
end;
constructor TMeterData.Create;
begin
FGroups := TStringList.Create;
FGroupStructure := TMeterDataGroup.Create;
FAutoCreateGroup := False;
FAutoCreateItem := False;
end;
destructor TMeterData.Destroy;
begin
FGroups.Free;
FGroupStructure.Free;
inherited;
end;
procedure TMeterData.DeleteAllGroups;
var
i : Integer;
begin
for i := 0 to fgroups.Count - 1 do
FGroups.Objects[ i ].Free;
FGroups.Clear;
end;
procedure TMeterData.DeleteGroup( sGroupName : string );
var
nIndex : Integer;
begin
nIndex := FGroups.IndexOf( sGroupName );
if nIndex <> -1 then
begin
FGroups.Objects[ nIndex ].Free;
FGroups.Delete( nIndex );
end;
end;
function TMeterData.GetDefaultGroupItem(nSign: Int64): TMeterDataItem;
begin
Result := GetGroupItem( GetDefaultGroupName, nSign );
end;
function TMeterData.GetDefaultGroupItemValue(nSign: Int64): string;
begin
Result := GetGroupItemValue( GetDefaultGroupName, nSign );
end;
function TMeterData.GetDefaultGroupName: string;
begin
if FDefaultGroupName <> EmptyStr then
Result := FDefaultGroupName
else
begin
if FGroups.Count > 0 then
Result := FGroups[ 0 ]
else
Result := EmptyStr;
end;
end;
function TMeterData.GetGroup(sGroupName: string): TMeterDataGroup;
var
nIndex : Integer;
begin
nIndex := FGroups.IndexOf( sGroupName );
if nIndex = -1 then
begin
// 如果可以自动创建,创建新的组数据
if AutoCreateGroup then
begin
Result := TMeterDataGroup.Create;
FGroups.AddObject( sGroupName, Result );
end
else
Result := nil
end
else
Result := TMeterDataGroup( FGroups.Objects[ nIndex ] );
end;
function TMeterData.GetGroupItem(sGroupName: string; nSign: Int64):
TMeterDataItem;
var
mdGroup : TMeterDataGroup;
begin
mdGroup := GetGroup( sGroupName );
if not Assigned( mdGroup ) then
Result := nil
else
begin
Result := mdGroup.Item[ nSign ];
// 如果可以自动创建,创建新的数据项
if ( not Assigned( Result ) ) and AutoCreateItem then
Result := mdGroup.NewItem( nSign );
end;
end;
function TMeterData.GetGroupItemValue(sGroupName: string; nSign: Int64):
string;
var
mdItem : TMeterDataItem;
begin
mdItem := GetGroupItem( sGroupName, nSign );
if Assigned( mdItem ) then
Result := mdItem.Value
else
Result := EmptyStr;
end;
function TMeterData.NewGroup(sGroupName: string): TMeterDataGroup;
var
mdGroup : TMeterDataGroup;
begin
if sGroupName = EmptyStr then
begin
Result := nil;
Exit;
end;
mdGroup := GetGroup( sGroupName );
if not Assigned( mdGroup ) then
begin
mdGroup := TMeterDataGroup.Create;
// 使用组数据结构
mdGroup.Assign( GroupStructure );
mdGroup.GroupName := sGroupName;
FGroups.AddObject( sGroupName, mdGroup );
end;
Result := mdGroup;
end;
procedure TMeterData.SetDefaultGroupItemValue(nSign: Int64;
const Value: string);
begin
SetGroupItemValue( GetDefaultGroupName, nSign, Value );
end;
procedure TMeterData.SetDefaultGroupName(const Value: string);
begin
if FGroups.IndexOf( Value ) <> -1 then
FDefaultGroupName := Value;
end;
procedure TMeterData.SetGroupItemValue(sGroupName: string; nSign: Int64;
const Value: string);
var
mdItem : TMeterDataItem;
begin
mdItem := GetGroupItem( sGroupName, nSign );
if Assigned( mdItem ) then
mdItem.Value := Value;
end;
{ TMeterDataGroup }
procedure TMeterDataGroup.Assign(Source: TPersistent);
var
mdGroup : TMeterDataGroup;
mdItem : TMeterDataItem;
i: Integer;
begin
Assert( Source is TMeterDataGroup );
DeleteAllItems;
GroupName := TMeterDataGroup( Source ).GroupName;
mdGroup := TMeterDataGroup( Source );
FVerifyValue := mdGroup.VerifyValue;
for i := 0 to mdGroup.Items.Count - 1 do
begin
mdItem := TMeterDataItem.Create;
mdItem.Assign( TMeterDataItem( mdGroup.Items.Objects[ i ] ) );
FItems.AddObject( mdGroup.Items[ i ], mdItem );
end;
end;
procedure TMeterDataGroup.AssignValue(Source: TPersistent);
var
i: Integer;
AItem : TMeterDataItem;
begin
Assert( Source is TMeterDataGroup );
ClearAllItemsValue;
for i := 0 to Items.Count - 1 do
begin
with TMeterDataItem(Items.Objects[i]) do
begin
AItem := TMeterDataGroup(Source).Item[Sign];
if Assigned(AItem) then
Value := AItem.Value;
end;
end;
end;
procedure TMeterDataGroup.ClearAllItemsValue;
var
mdItem : TMeterDataItem;
i : Integer;
begin
for i := 0 to FItems.Count - 1 do
begin
mdItem := TMeterDataItem( FItems.Objects[ i ] );
mdItem.Value := EmptyStr;
end;
end;
constructor TMeterDataGroup.Create;
begin
FItems := TStringList.Create;
FVerifyValue := False;
end;
procedure TMeterDataGroup.DeleteAllItems;
var
i : Integer;
begin
for i := 0 to FItems.Count - 1 do
FItems.Objects[ i ].Free;
FItems.Clear;
end;
procedure TMeterDataGroup.DelItem(nSign: Int64);
var
i: Integer;
begin
for i := 0 to FItems.Count - 1 do
begin
if TMeterDataItem(FItems.Objects[i]).Sign = nSign then
begin
FItems.Objects[ i ].Free;
FItems.Delete(i);
Exit;
end;
end;
end;
destructor TMeterDataGroup.Destroy;
begin
DeleteAllItems;
FItems.Free;
inherited;
end;
function TMeterDataGroup.GetItem(nSign: Int64): TMeterDataItem;
var
nIndex : Integer;
sSign : string;
begin
// if nSign > $FFFF then
sSign := IntToHex( nSign and $FFFFFFFF, 8 );
// else
// sSign := IntToHex( nSign and C_METER_DATA_SIGN_MAX, 4 );
nIndex := FItems.IndexOf( sSign );
if nIndex = -1 then
begin
nIndex := FItems.IndexOf( IntToHex( Sign97To07(nSign) and $FFFFFFFF, 8 ) );
end;
if nIndex = -1 then
Result := nil
else
Result := TMeterDataItem( FItems.Objects[ nIndex ] );
end;
function TMeterDataGroup.GetItemValue(nSign: Int64): string;
var
mdItem : TMeterDataItem;
begin
mdItem := GetItem( nSign );
if Assigned( mdItem ) then
Result := mdItem.Value
else
Result := EmptyStr;
end;
function TMeterDataGroup.NewItem(nSign: Int64; sFormat: string;
nLen: integer; sUnit, sNote: string): TMeterDataItem;
begin
Result := NewItem( nSign );
with Result do
begin
Note := sNOTE;
Format := sFORMAT;
Units := sUNIT;
Length := nLEN;
Value := EmptyStr;
end;
end;
function TMeterDataGroup.NewItem(nSign: Int64): TMeterDataItem;
var
nIndex : Integer;
sSign : string;
begin
// if nSign > $FFFF then
sSign := IntToHex( nSign and $FFFFFFFF, 8 );
// else
// sSign := IntToHex( nSign and C_METER_DATA_SIGN_MAX, 4 );
nIndex := FItems.IndexOf( sSign );
if nIndex = -1 then
begin
Result := TMeterDataItem.Create;
Result.Sign := nSign;
FItems.AddObject( sSign, Result );
end
else
Result := TMeterDataItem( FItems.Objects[ nIndex ] );
end;
procedure TMeterDataGroup.SetGroupName(const Value: string);
begin
FGroupName := Value;
end;
procedure TMeterDataGroup.SetItemValue(nSign: Int64; const Value: string);
var
mdItem : TMeterDataItem;
begin
mdItem := GetItem( nSign );
if Assigned( mdItem ) then
begin
mdItem.Value := Value;
if VerifyValue then
VerifyMeterDataItem( mdItem );
end;
end;
{ TMETER_DATA_GROUP_DL645 }
procedure TMETER_DATA_GROUP_DL645.AddNormalData( sType: string;
nBaseSign : Integer; nLen : Integer; sFormat, sUnitA, sUnitU : string );
function GetNote(n1, n2, n3: Integer; sType : string ): string;
begin
if n1 < 2 then
Result := '(当前)'
else if n1 < 4 then
Result := '(上月)'
else
Result := '(上上月)';
if n3 in [ 1..$E ] then
begin
Result := Result + '费率' + IntToStr( n3 );
end;
case n2 of
1 : Result := Result + '正向';
2 : Result := Result + '反向';
3 : Result := Result + '一象限';
4 : Result := Result + '四象限';
5 : Result := Result + '二象限';
6 : Result := Result + '三象限';
end;
if n1 in [ 0, 2, 4 ] then
Result := Result + '有功'
else
Result := Result + '无功';
if n3 = 0 then
result := result + '总' + sType
else if n3 = $f then
result := result + sType + '数据块'
else
result := result + sType;
end;
var
i, j, k : Integer;
sUnit, sNote : string;
nSign : Int64;
begin
for i := 0 to 5 do // 月份 , 0, 2, 4有功, 1,3,5无功
begin
for j := 1 to 6 do // 象限
begin
for k := 0 to 15 do // 费率
begin
if ( i in [ 0, 2, 4 ] ) and ( j > 2 ) then // 有功没有多象限
Break;
nSign := nBaseSign;
if i in [ 0, 2, 4 ] then // 有功
begin
nSign := nSign + ( i * 2 ) shl 8 + j shl 4 + k;
sUnit := sUnitA;
end
else
begin
nSign := nSign + ( ( i - 1 ) * 2 + 1 ) shl 8 + j shl 4 + k;
sUnit := sUnitU;
end;
sNote := GetNote( i, j, k, sType );
if k < 15 then
NewItem( nSign, sFormat, nLen, sUnit, sNote )
else
NewItem( nSign, sFormat, nLen * 15, sUnit, sNote );
end;
end;
end;
end;
procedure TMETER_DATA_GROUP_DL645.AddTimePeriodData;
var
i, j : Integer;
nSign : Int64;
sNote : string;
begin
for i := 1 to 15 do
begin
nSign := $C320 + i;
sNote := Format( '%d时区起始日期及日时段表号', [ i ] );
NewItem( nSign, 'MMDDNN', 3, '', sNote );
end;
for i := 1 to 8 do
for j := 1 to 15 do
begin
nSign := $C300 + ( i + 2 ) shl 4 + j;
sNote := Format( '第%d日时段表第%d时段起始时间及费率号', [ i, j ] );
NewItem( nSign, 'hhmmNN', 3, '', sNote );
end;
for i := 1 to $D do
begin
nSign := $C410 + i;
sNote := Format( '第%d公共假日日期及日时段表号', [ i ] );
NewItem( nSign, 'MMDDNN', 3, '', sNote );
end;
end;
procedure TMETER_DATA_GROUP_DL645.AddVariableData;
begin
// 变量
NewItem( $B210, 'MMDDhhmm' , 4, '月日时分', '最近一次编程时间' );
NewItem( $B211, 'MMDDhhmm' , 4, '月日时分', '最近一次最大需量清零时间' );
NewItem( $B212, '0000' , 2, '' , '编程次数' );
NewItem( $B213, '0000' , 2, '' , '最大需量清零次数' );
NewItem( $B214, '000000' , 3, '分钟' , '电池工作时间' );
NewItem( $B310, '0000' , 2, '' , '总断相次数' );
NewItem( $B311, '0000' , 2, '' , 'A相断相次数' );
NewItem( $B312, '0000' , 2, '' , 'B相断相次数' );
NewItem( $B313, '0000' , 2, '' , 'C相断相次数' );
NewItem( $B320, '000000' , 3, '分钟' , '断相时间累计值' );
NewItem( $B321, '000000' , 3, '分钟' , 'A断相时间累计值' );
NewItem( $B322, '000000' , 3, '分钟' , 'B断相时间累计值' );
NewItem( $B323, '000000' , 3, '分钟' , 'C断相时间累计值' );
NewItem( $B330, 'MMDDhhmm' , 4, '月日时分', '最近一次断相起始时刻' );
NewItem( $B331, 'MMDDhhmm' , 4, '月日时分', 'A相最近断相起始时刻' );
NewItem( $B332, 'MMDDhhmm' , 4, '月日时分', 'B相最近断相起始时刻' );
NewItem( $B333, 'MMDDhhmm' , 4, '月日时分', 'C相最近断相起始时刻' );
NewItem( $B340, 'MMDDhhmm' , 4, '月日时分', '最近一次断相的结束时刻' );
NewItem( $B341, 'MMDDhhmm' , 4, '月日时分', 'A相最近一次断相的结束时刻' );
NewItem( $B342, 'MMDDhhmm' , 4, '月日时分', 'B相最近一次断相的结束时刻' );
NewItem( $B343, 'MMDDhhmm' , 4, '月日时分', 'C相最近一次断相的结束时刻' );
NewItem( $B611, '000' , 2, 'V' , 'A相电压' );
NewItem( $B612, '000' , 2, 'V' , 'B相电压' );
NewItem( $B613, '000' , 2, 'V' , 'C相电压' );
NewItem( $B621, '00.00' , 2, 'A' , 'A相电流' );
NewItem( $B622, '00.00' , 2, 'A' , 'B相电流' );
NewItem( $B623, '00.00' , 2, 'A' , 'C相电流' );
NewItem( $B630, '00.0000' , 3, 'kW' , '瞬时有功功率' );
NewItem( $B631, '00.0000' , 3, 'kW' , 'A相有功功率' );
NewItem( $B632, '00.0000' , 3, 'kW' , 'B相有功功率' );
NewItem( $B633, '00.0000' , 3, 'kW' , 'C相有功功率' );
NewItem( $B634, '00.00' , 2, 'kW' , '正向有功功率上限值' );
NewItem( $B635, '00.00' , 2, 'kW' , '反向有功功率上限值' );
NewItem( $B640, '00.00' , 2, 'kvarh' , '瞬时无功功率' );
NewItem( $B641, '00.00' , 2, 'kvarh' , 'A相无功功率' );
NewItem( $B642, '00.00' , 2, 'kvarh' , 'B相无功功率' );
NewItem( $B643, '00.00' , 2, 'kvarh' , 'C相无功功率' );
NewItem( $B650, '0.000' , 2, '' , '总功率因数' );
NewItem( $B651, '0.000' , 2, '' , 'A相功率因数' );
NewItem( $B652, '0.000' , 2, '' , 'B相功率因数' );
NewItem( $B653, '0.000' , 2, '' , 'C相功率因数' );
// 参变量
NewItem( $C010, 'YYMMDDWW' , 4, '年月日周', '日期及周次' );
NewItem( $C011, 'hhmmss' , 3, '时分秒' , '时间' );
NewItem( $C020, '' , 1, '' , '电表运行状态字' );
NewItem( $C021, '' , 1, '' , '电网状态字' );
NewItem( $C022, '' , 1, '' , '周休日状态字' );
NewItem( $C030, '000000' , 3, 'p/(kWh)' , '电表常数(有功)' );
NewItem( $C031, '000000' , 3, 'p/(kvarh)','电表常数(无功)' );
NewItem( $C032, '000000000000', 6, '' , '表号' );
NewItem( $C033, '000000000000', 6, '' , '用户号' );
NewItem( $C034, '000000000000', 6, '' , '设备码' );
NewItem( $C111, '00' , 1, '分钟' , '最大需量周期' );
NewItem( $C112, '00' , 1, '分钟' , '滑差时间' );
NewItem( $C113, '00' , 1, '秒' , '循显时间' );
NewItem( $C114, '00' , 1, '秒' , '停显时间 ' );
NewItem( $C115, '00' , 1, '' , '显示电能小数位数 ' );
NewItem( $C116, '00' , 1, '' , '显示功率(最大需量)小数位数' );
NewItem( $C117, 'DDhh' , 2, '日时' , '自动抄表日期' );
NewItem( $C118, '00' , 1, '' , '负荷代表日' );
NewItem( $C119, '000000.0' , 4, 'kWh' , '有功电能起始读数' );
NewItem( $C11A, '000000.0' , 4, 'kvarh' , '无功电能起始读数' );
NewItem( $C211, '0000' , 2, 'ms' , '输出脉冲宽度' );
NewItem( $C212, '00000000' , 4, '' , '密码权限及密码' );
NewItem( $C310, '00' , 1, '' , '年时区数P' );
NewItem( $C311, '00' , 1, '' , '日时段表数q' );
NewItem( $C312, '00' , 1, '' , '日时段(每日切换数)m≤10' );
NewItem( $C313, '00' , 1, '' , '费率数k≤14' );
NewItem( $C314, '00' , 1, '' , '公共假日数n' );
NewItem( $C41E, '00' , 1, '' , '周休日采用的日时段表号' );
NewItem( $C510, 'MMDDhhmm' , 4, '月日时分', '负荷记录起始时间' );
NewItem( $C511, '0000' , 2, '分钟' , '负荷记录间隔时间' );
end;
constructor TMETER_DATA_GROUP_DL645.Create;
begin
inherited;
AddNormalData( '电能', $9000, 4, '000000.00', 'kWh', 'kvarh' );
AddNormalData( '最大需量', $A000, 3, '00.0000', 'kW', 'kvar' );
AddNormalData( '最大需量发生时间', $B000, 4, 'MMDDhhmm',
'月日时分', '月日时分' );
AddVariableData;
AddTimePeriodData;
end;
procedure TMeterDataItem.SetValue(Val: string);
begin
// if Val <> FValue then
// begin
FValue := Val;
if Assigned(FOnValueChanged) then
FOnValueChanged(self);
// end;
end;
function TMeterDataItem.SignInHex: string;
begin
Result := IntToHex( Sign, 8 );
end;
procedure VerifyMeterDataItem( AItem : TMeterDataItem );
begin
AItem.Value := VerifiedStr( AItem.Value, AItem.Format, AItem.Length );
end;
function VerifiedStr( const sData, sFormat : string; nLen : Integer ) : string;
// // 修正字符串长度
// procedure ChangeStrSize( var s : string; nLen : Integer );
// var
// i : Integer;
// begin
// if Length( s ) < nLen then
// begin
// for i := 1 to nLen - Length( s ) do
// s := '0' + s;
// end
// else if Length( s ) > nLen then
// begin
// s := Copy( s, Length( s ) - nLen + 1, nLen );
// end;
// end;
//var
// nLenStr : Integer;
// dTemp : Double;
// s : string;
// aBuf : TBytes;
//begin
// s := Trim( sData );
// s := StringReplace( s, ' ', '', [rfReplaceAll] );
// s := StringReplace( s, '-', '', [rfReplaceAll] );
// s := StringReplace( s, ':', '', [rfReplaceAll] );
//
// if (sFormat <> EmptyStr) and (sFormat <> '00.0000YYMMDDhhmm') then // 有数据格式的
// begin
// // 整理浮点数据
// if ( Pos( '0.0', sFormat ) > 0 ) then
// begin
// TryStrToFloat( s, dTemp );
// s := FormatFloat( sFormat, dTemp );
// end
// else
// begin
// if Pos('X', sFormat) > 0 then
// begin
// nLenStr := Round(Length( sFormat )/2);
// ChangeStrSize( s, nLenStr );
// aBuf := StrToPacks( s );
// s := BCDPacksToStr(aBuf);
//
// s := StringReplace(s, ' ', '', [rfReplaceAll]);
// end
// else
// begin
// nLenStr := Length( sFormat );
// ChangeStrSize( s, nLenStr );
// end;
//
// end;
// end
// else
// begin
// s := StringReplace( s, '.', '', [rfReplaceAll] );
// nLenStr := nLen * 2; // 字节个数×2,因为是十六进制
// ChangeStrSize( s, nLenStr );
//
// Insert('.',s, 3);
// end;
//
// Result := s;
function ReverseString(const AText: string): string;
var
I: Integer;
P: PChar;
begin
SetLength(Result, Length(AText));
P := PChar(Result);
for I := High(AText) downto Low(AText) do
begin
P^ := AText[I];
Inc(P);
end;
end;
// 修正字符串长度
procedure ChangeStrSize( var s : string; nLen : Integer );
var
i : Integer;
begin
if Length( s ) < nLen then
begin
for i := 1 to nLen - Length( s ) do
s := '0' + s;
end;
end;
var
nIndex, nLenStr : Integer;
dTemp : Double;
s, sDF : string;
begin
s := Trim( sData );
sDF := Trim(sFormat);
if sDF <> EmptyStr then // 有数据格式的
begin
nLenStr := Length( sDF );
// 整理浮点数据
if ( Pos( '.', sDF ) > 0 ) then
begin
if ( Pos( '.', s ) = 0 ) and ( nLenStr = Length( s ) + 1 ) then
begin
nIndex := Pos( '.', ReverseString( sDF ) );
s := ReverseString( s );
s := Copy( s, 1, nIndex - 1 ) + '.' + Copy( s, nIndex, Length( s ) - nIndex + 1 );
s := ReverseString( s );
end
else
begin
TryStrToFloat( s, dTemp );
s := FormatFloat( sDF, dTemp );
end;
end;
ChangeStrSize( s, nLenStr );
end
else
begin
ChangeStrSize( s, nLen * 2 )
end;
Result := s;
end;
function FixDataForShow( AData: string; AFormat: string; ALen: Integer) : string;
const
C_DATETIME_STR = '%s-%s %s:%s';
var
nRStrLen : Integer; // .右边的字符串长度
s : string;
begin
if Pos( '.', AFormat ) > 0 then
begin
nRStrLen := Length( AFormat ) - Pos( '.', AFormat );
s := Copy( AData, 1, Length( AData ) - nRStrLen );
s := s + '.';
s := s + Copy( AData, Length( AData ) - nRStrLen + 1, nRStrLen );
Result := s;
end
else if ( UpperCase( AFormat ) = 'MMDDHHMM' ) and ( Length( AData ) = 8 ) then
begin
s := AData;
Result := Format( C_DATETIME_STR, [ Copy( s, 1, 2 ), Copy( s, 3, 2 ),
Copy( s, 5, 2 ), Copy( s, 7, 2 ) ] );
end;
end;
function FixDataForShow( AData: TBytes; AFormat: string; ALen: Integer) : string;
var
s : string;
i: Integer;
begin
s := '';
for i := 0 to Length(AData) - 1 do
s := s + IntToHex(adata[i], 2);
Result := FixDataForShow(s, AFormat, ALen);
end;
end.
|
unit uCustomTableAccess;
interface
type
TCustomTableAccess = class(TAbstractTableAccess)
private
FWriter: TCustomWriter;
FOnBufferFlushNeeded: TBufferFlushNeededEvent;
procedure SetAnyData(AIdx: integer; aType: TDataType; aPointer: Pointer; NativeFormat: boolean = true);
class procedure OwnFieldInfo(AFieldDef: TFieldDef; out AFieldInfo: TFieldInfo);
function GetAssignedTable: TDataSet;
function GetWriter: TCustomWriter;
protected
property Writer: TCustomWriter read getWriter;
function GetTableName: string; override;
procedure SetTableName(const ATableName: string); override;
function GetRecordCount: integer; override;
function GetTable: TDataSet; override;
function GetFieldAt(AIdx: integer): TField; override;
function GetFieldDefAt(AIdx: integer): TFieldDef; override;
procedure SetBuffered(AValue: boolean); override;
procedure SetOnBufferFlushNeeded(const AValue: TBufferFlushNeededEvent); override;
procedure hdlOnBufferFlushNeeded; override;
function GetIntValue(AIdx: integer): integer; override;
function GetDateTimeValue(AIdx: integer): TDateTime; override;
function GetValue(AIdx: integer): Variant; override;
...
function GetCachedUpdates: boolean; override;
function GetUpdatesPending: boolean; override;
procedure SetCachedUpdates(const AValue: boolean); override;
function GetDatabaseType: TDatabaseType; override;
public
function GetFieldDefs: TFieldDefs; override;
function GetIsEmpty: boolean; override;
function GetFields: TFields; override;
function FieldByName(const FieldName: string): TField; override;
function GetFieldIndex(const AFieldName: string): integer; override;
procedure Append; override;
procedure Cancel; override;
procedure Close; override;
function Locate(ADbKeyFields: TAbstractDataRow): boolean; override;
procedure SetFilter(ADbKeyFields: TAbstractDataRow); override;
class function GetDataType(AFieldType: TFieldType; DbSize: integer; var MaxLength: integer): TDataType; override;
procedure SetIntValue(AIdx: integer; AValue: integer); override;
...
procedure ClearField(AIdx: integer); override;
function GetIsNull(AIdx: integer): boolean; override;
function GetKeyValue(AIdx: integer): TKeyVal; override;
// data caching: usually not supported
function GetCanCacheUpdates: boolean; override;
function CommitUpdates(out AErrorMsg: string): boolean; override;
procedure CancelUpdates; override;
property DatabaseType: TDatabaseType read GetDatabaseType;
end;
const
// number of reserved words per database type
// 110 for oracle
// 306 for db2
// 13 postgresql (that are not in ansi-iso-reserved)
// 140 ansi-iso 92 sql
// 118 interbase (that are not in ansi-iso-reserved)
// 204 sybase
// 186 sql server
// 194 sql server future
// 235 odbc
CGeneralDBReservedWords: array[0..1086] of string = (
'FIELD',
'IDENTIFIER',
'ABORT ANALYZE', // postgresql reserved words
'BINARY',
'CLUSTER CONSTRAINT COPY',
'DO',
....
'WHERE',
'WHILE',
'WITH',
'WLM',
'WRITE',
'YEAR',
'YEARS'
);
implementation
var
FReservedWords: TStringList;
//----------------------------------------------------------------------------
//N,PS:
procedure TCustomTableAccess.setAnyData(AIdx: integer; aType: TDataType; aPointer: Pointer; NativeFormat: boolean = true);
begin
checkFieldIndex(AIdx);
checkAssigned(getTable);
getAssignedTable.Fields[AIdx].SetData(aPointer, NativeFormat);
end;
//----------------------------------------------------------------------------
// N,PS:
constructor TCustomTableAccess.Create(AOwnedRootTA: TSpecificTableAccess_a;
AWriter: TCustomWriter;
ADatabase: TComponent; const ATableName: string; ABlockReadSize: integer;
AOpenExclusively: boolean; ATableDestroy: boolean);
begin
inherited Create;
checkAssigned(AWriter);
checkAssigned(AOwnedRootTA);
FWriter := AWriter;
FRootTA := AOwnedRootTA;
end;
//----------------------------------------------------------------------------
// N,PS:
class function TCustomTableAccess.GetDataType(AFieldType: TFieldType; DbSize: integer; var MaxLength: integer): TDataType;
begin
MaxLength := DbSize;
case AFieldType of
ftMemo, ftWideString, ftString, ftOraClob:
begin
Result := dtString;
if DbSize = 0 then
MaxLength := MaxInt;
end;
ftSmallInt, ftInteger: Result := dtInteger;
ftFloat, ftCurrency: Result := dtDouble;
ftDate: Result := dtDate;
ftBoolean: Result := dtBoolean;
ftTime: Result := dtTime;
ftDateTime: Result := dtDateTime;
else
Result := dtUnknown;
end;
end;
//----------------------------------------------------------------------------
// N,PS:
function TCustomTableAccess.getMaxFieldLength(AProposal: integer; AType: TFieldType): integer;
begin // no inherited (abstract)
if (AType = ftString) or (AType = ftBytes) then
Result := AProposal
else
Result := 0;
end;
//----------------------------------------------------------------------------
// N,PS:
function TCustomTableAccess.getFieldTypeEq(AMetaField: PMetaField; AField: TFieldDef; ATableName: string): boolean;
begin
// no inherited (abstract)
checkAssigned(AMetaField);
Result := AField.DataType = GetFieldType(AMetaField^.DataType, AMetaField^.MaxLength);
end;
//----------------------------------------------------------------------------
// N,PS:
function TCustomTableAccess.getDfTypeEq(AType,
ANotherType: TDataType): boolean;
const
CEqualIntTypes = [dtInteger, dtAutoInc];
begin
// no inherited (abstract)
Result := (AType = ANotherType) or
((AType in CEqualIntTypes) and (ANotherType in CEqualIntTypes));
end;
//----------------------------------------------------------------------------
// N,PS:
procedure TCustomTableAccess.SetIntValue(AIdx: integer; AValue: integer);
begin
setAnyData(AIdx, dtInteger, @AValue);
end;
//----------------------------------------------------------------------------
// N,PS:
procedure TCustomTableAccess.SetInt64Value(AIdx: integer; AValue: Int64);
begin
setAnyData(AIdx, dtInt64, @AValue);
end;
//----------------------------------------------------------------------------
// N,PS T3:
function TCustomTableAccess.getIsNull(AIdx: integer): boolean;
begin
// no inherited(abstract)
checkFieldIndex(AIdx);
Result := getAssignedTable.Fields[AIdx].IsNull;
end;
//----------------------------------------------------------------------------
// N,PS:
function TCustomTableAccess.getDataSetState: TDataSetState;
begin
Result := getAssignedTable.State;
end;
//----------------------------------------------------------------------------
// N,PS:
procedure TCustomTableAccess.Append;
begin
// no inherited (abstract)
getAssignedTable.Append;
end;
//----------------------------------------------------------------------------
// N,PS:
procedure TCustomTableAccess.Cancel;
begin
// no inherited (abstract)
getAssignedTable.Cancel;
end;
//----------------------------------------------------------------------------
// N,PS:
procedure TCustomTableAccess.CleanBuffers;
begin
// no inherited (abstract)
// empty implementation here
end;
//----------------------------------------------------------------------------
// N,PS:
function TCustomTableAccess.getFiltered: boolean;
begin
// no inherited(abstract);
Result := getAssignedTable.Filtered;
end;
//----------------------------------------------------------------------------
//2003-08-26 09:18 N,PS:
//2004-10-22 09:32 C,PS T50: getAssnignedTable used
//2004-11-18 12:08 R,CT T50:
procedure TCustomTableAccess.setFilterText(AValue: string);
begin
// no inherited(abstract);
getAssignedTable.Filter := AValue;
end;
//----------------------------------------------------------------------------
// N,PS:
function TCustomTableAccess.Locate(ADbKeyFields: TAbstractDataRow): boolean;
var
i: integer;
lFields: string;
lVals: array of variant;
begin
// no inherited(abstract);
if IsEmpty then
Result := false
else
begin
setLength(lVals, ADbKeyFields.Count);
for i := 0 to ADbKeyFields.Count - 1 do
begin
lFields := SeqStr(lFields, ';', ADbKeyFields.MetaField[i].Identifier);
case ADbKeyFields.MetaField[i].DataType of
// case-order by estimated probability of occurance in data
dtString: lVals[i] := ADbKeyFields.StringValue[i];
dtInteger: lVals[i] := ADbKeyFields.IntValue[i];
...
dtDateTime: lVals[i] := ADbKeyFields.DateTimeValue[i];
dtInt64: lVals[i] := ADbKeyFields.Int64Value[i];
else
raise EIntern.Fire(nil, 'Invalid type');
end;
end;
Result := getAssignedTable.Locate(lFields, lVals, []);
end;
end;
//----------------------------------------------------------------------------
// N,PS:
function TCustomTableAccess.getFieldAt(AIdx: integer): TField;
begin
// no inherited(abstract);
Result := getAssignedTable.Fields[AIdx];
end;
//----------------------------------------------------------------------------
// N,PS:
procedure TCustomTableAccess.flushBuffers;
begin
// no inherited(abstract);
// nothing to do here
end;
//----------------------------------------------------------------------------
// N,PS:
procedure TCustomTableAccess.setBuffered(AValue: boolean);
begin
// no inherited(abstract);
// nothing to do here
end;
//----------------------------------------------------------------------------
// T42:
procedure TCustomTableAccess.hdlOnBufferFlushNeeded;
begin
// no inherited; (abstract)
if not Assigned(FOnBufferFlushNeeded) then
raise EIntern.Fire(Self, 'Mandatory event OnBufferFlushNeeded not set');
FOnBufferFlushNeeded;
end;
//----------------------------------------------------------------------------
// N,PS T42:
procedure TCustomTableAccess.setOnBufferFlushNeeded(
const AValue: TBufferFlushNeededEvent);
begin
// no inherited; (abstract)
FOnBufferFlushNeeded := AValue;
end;
//----------------------------------------------------------------------------
// N,PS T42:
constructor TCustomTableAccess.Create;
begin
raise EMethodNotSupported.Fire(Self, 'Invalid constructor used');
end;
initialization
FReservedWords := TStringList.Create;
FReservedWords.sorted := true;
FReservedWords.Duplicates := dupIgnore;
AddStringArrayToStringList(FReservedWords, CGeneralDBReservedWords);
AddStringArrayToStringList(FReservedWords, COracleReservedWords);
AddStringArrayToStringList(FReservedWords, CDB2ReservedWords);
finalization
FReservedWords.free;
end.
|
{******************************************}
{ TeeChart Pro Charting Library }
{ TriSurface Series }
{ Copyright (c) 1995-2004 by David Berneda }
{ All Rights Reserved }
{******************************************}
unit TeeTriSurface;
{$I TeeDefs.inc}
// Adapted from Andre Bester's algorithm (anb@iafrica.com)
{ This unit implements the "Tri-Surface" charting series.
A Tri-Surface is a 3D surface of triangles, automatically
calculated from all XYZ points.
All XYZ coordinates can have floating point decimals and
can be expressed in any range.
This series inherits all formatting properties like Pen,
Brush, ColorRange and Palette from its ancestor class.
Special properties:
HideTriangles : Boolean ( default True )
Triangles are ordered by Z position (hidding algorithm).
When False, display speed might be faster but incorrect.
CacheTriangles : Boolean ( default False )
When True, triangles from XYZ data are just recalculated once
instead of at every redraw.
Set CacheTriangles to False after clearing or modifying XYZ data
to force recalculating triangles.
}
interface
Uses {$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
Classes,
{$IFDEF CLX}
QGraphics, Types,
{$ELSE}
Graphics,
{$ENDIF}
TeEngine, Chart, TeCanvas, TeeProcs, TeeSurfa;
Type
{$IFNDEF CLR}
PTriangle=^TTriangle;
{$ELSE}
TTriangle=class;
PTriangle=TTriangle;
{$ENDIF}
TTriangle={$IFDEF CLR}class{$ELSE}packed record{$ENDIF}
Index : Integer;
Color : TColor;
Next : PTriangle;
Prev : PTriangle;
P : TTrianglePoints;
Z : Double;
end;
ETriSurfaceException=class(ChartException);
TCustomTriSurfaceSeries=class(TCustom3DPaletteSeries)
private
{ Private declarations }
FBorder : TChartHiddenPen;
FFastBrush : Boolean;
FHide : Boolean;
FTransp : TTeeTransparency;
FNumLines : Integer;
ICreated : Boolean;
IPT : Array of Integer;
IPL : Array of Integer;
Triangles : PTriangle;
ILastTriangle : PTriangle;
{$IFNDEF CLX}
DCBRUSH : HGDIOBJ;
CanvasDC : TTeeCanvasHandle;
{$ENDIF}
Function CalcPointResult(Index:Integer):TPoint3D;
Procedure ClearTriangles; // 7.0
function IDxchg(I1,I2,I3,I4:Integer):Integer;
Procedure SetBorder(Value:TChartHiddenPen);
procedure SetFastBrush(const Value: Boolean);
procedure SetHide(const Value: Boolean);
Procedure SetTransp(Value:TTeeTransparency);
Procedure TrianglePointsTo2D(const P:TTrianglePoints3D; Var Result:TeCanvas.TTrianglePoints);
protected
ImprovedTriangles : Boolean;
Procedure AddSampleValues(NumValues:Integer; OnlyMandatory:Boolean=False); override;
class Procedure CreateSubGallery(AddSubChart:TChartSubGalleryProc); override;
procedure DoBeforeDrawValues; override;
procedure DrawAllValues; override;
Procedure DrawMark(ValueIndex:Integer; Const St:String;
APosition:TSeriesMarkPosition); override;
class Function GetEditorClass:String; override;
Procedure PrepareForGallery(IsEnabled:Boolean); override;
class Procedure SetSubGallery(ASeries:TChartSeries; Index:Integer); override;
public
{ Public declarations }
CacheTriangles : Boolean;
NumTriangles : Integer;
Constructor Create(AOwner:TComponent); override;
Destructor Destroy;override;
Procedure Assign(Source:TPersistent); override;
Procedure Clear; override;
Function Clicked(x,y:Integer):Integer; override; // 7.0
Function NumSampleValues:Integer; override;
Function TrianglePoints(TriangleIndex:Integer):TTrianglePoints3D; // 7.0
property Border:TChartHiddenPen read FBorder write SetBorder;
property Brush;
property FastBrush:Boolean read FFastBrush write SetFastBrush default False; // 7.0
property HideTriangles:Boolean read FHide write SetHide default True;
property Pen;
property Transparency:TTeeTransparency read FTransp write SetTransp default 0;
end;
TTriSurfaceSeries=class(TCustomTriSurfaceSeries)
published
property Active;
property ColorSource;
property Cursor;
property HorizAxis;
property Marks;
property ParentChart;
property DataSource;
property PercentFormat;
property SeriesColor;
property ShowInLegend;
property Title;
property ValueFormat;
property VertAxis;
property XLabelsSource;
{ events }
property AfterDrawValues;
property BeforeDrawValues;
property OnAfterAdd;
property OnBeforeAdd;
property OnClearValues;
property OnClick;
property OnDblClick;
property OnGetMarkText;
property OnMouseEnter;
property OnMouseLeave;
property Border;
property Brush;
property EndColor;
property FastBrush;
property HideTriangles;
property LegendEvery;
property MidColor;
property Pen;
property PaletteMin;
property PaletteStep;
property PaletteSteps;
property PaletteStyle;
property StartColor;
property UseColorRange;
property UsePalette;
property UsePaletteMin;
property TimesZOrder;
property Transparency;
property XValues;
property YValues;
property ZValues;
{ events }
property OnGetColor;
end;
implementation
Uses Math, TeeConst, TeeProCo;
{ TTriSurfaceSeries }
Constructor TCustomTriSurfaceSeries.Create(AOwner:TComponent);
begin
inherited;
FBorder:=TChartHiddenPen.Create(CanvasChanged);
FBorder.Color:=clWhite;
FHide:=True; { 5.02 }
ImprovedTriangles:=True;
end;
Destructor TCustomTriSurfaceSeries.Destroy;
begin
FBorder.Free;
IPL:=nil;
IPT:=nil;
ClearTriangles;
inherited;
end;
Procedure TCustomTriSurfaceSeries.ClearTriangles;
var Triangle : PTriangle;
{$IFNDEF CLR}
tmpTriangle : PTriangle;
{$ENDIF}
begin
Triangle:=Triangles;
while Assigned(Triangle) do
begin
{ free triangle memory }
{$IFNDEF CLR}
tmpTriangle:=Triangle;
{$ENDIF}
Triangle:=Triangle.Next;
{$IFNDEF CLR}
Dispose(tmpTriangle);
{$ENDIF}
end;
Triangles:=nil;
end;
Function TCustomTriSurfaceSeries.Clicked(x,y:Integer):Integer; // 7.0
var t : Integer;
tmp : TPoint;
Triangle : PTriangle;
P : TTrianglePoints;
begin
result:=TeeNoPointClicked;
tmp:=TeePoint(x,y);
// If "hide triangles" mode, then use the list of calculated
// triangles, from Last to First.
if Assigned(ILastTriangle) then
begin
Triangle:=ILastTriangle;
while Assigned(Triangle) do
begin
if PointInPolygon(tmp,Triangle.P) then
begin
result:=Triangle.Index;
break;
end;
Triangle:=Triangle.Prev;
end;
end
else
// Search across 3D non-Z sorted list of triangles...
begin
for t:=1 to NumTriangles do
begin
TrianglePointsTo2D(TrianglePoints(t),P);
if PointInPolygon(tmp,P) then
begin
result:=t;
break;
end;
end;
end;
end;
Function TCustomTriSurfaceSeries.NumSampleValues:Integer;
begin
result:=15;
end;
Procedure TCustomTriSurfaceSeries.AddSampleValues(NumValues:Integer; OnlyMandatory:Boolean=False);
Const tmpRange = 0.001;
tmpRandom = 1000;
var t : Integer;
tmpX : Double;
tmpZ : Double;
begin
NumValues:=Max(NumValues,3);
for t:=1 to NumValues do
begin
tmpX:=RandomValue(tmpRandom)*tmpRange;
tmpZ:=RandomValue(tmpRandom)*tmpRange;
AddXYZ(tmpX,Sqr(Exp(tmpZ))*Cos(tmpX*tmpZ),tmpZ);
end;
end;
class Function TCustomTriSurfaceSeries.GetEditorClass:String;
begin
result:='TTriSurfaceSeriesEditor'; { <-- dont translate ! }
end;
Procedure TCustomTriSurfaceSeries.SetBorder(Value:TChartHiddenPen);
begin
FBorder.Assign(Value);
end;
function TCustomTriSurfaceSeries.IDxchg(I1,I2,I3,I4:Integer):Integer;
var x1,x2,x3,x4 : Double;
y1,y2,y3,y4 : Double;
u1,u2,u3,u4 : Double;
A1,A2,B1,B2,
C1,C2 : Double;
S1,S2,S3,S4 : Double;
begin
result:=0;
x1:=XValues.Value[I1];
y1:=ZValues.Value[I1];
x2:=XValues.Value[I2];
y2:=ZValues.Value[I2];
x3:=XValues.Value[I3];
y3:=ZValues.Value[I3];
x4:=XValues.Value[I4];
y4:=ZValues.Value[I4];
u3:=(y2-y3)*(x1-x3)-(x2-x3)*(y1-y3);
u4:=(y1-y4)*(x2-x4)-(x1-x4)*(y2-y4);
if (u3*u4)>0 then
begin
u1:=(y3-y1)*(x4-x1)-(x3-x1)*(y4-y1);
u2:=(y4-y2)*(x3-x2)-(x4-x2)*(y3-y2);
A1:=sqr(x1-x3)+sqr(y1-y3);
B1:=sqr(x4-x1)+sqr(y4-y1);
C1:=sqr(x3-x4)+sqr(y3-y4);
A2:=sqr(x2-x4)+sqr(y2-y4);
B2:=sqr(x3-x2)+sqr(y3-y2);
C2:=sqr(x2-x1)+sqr(y2-y1);
S1:=Sqr(u1)/(C1*Math.Max(A1,B1));
S2:=Sqr(u2)/(C1*Math.Max(A2,B2));
S3:=Sqr(u3)/(C2*Math.Max(B2,A1));
S4:=Sqr(u4)/(C2*Math.Max(B1,A2));
if Math.Min(S1,S2) < Math.Min(S3,S4) then
result:=1;
end;
end;
procedure TCustomTriSurfaceSeries.DoBeforeDrawValues;
Procedure CreateTriangles;
Var NLT3 : Integer;
ITF : Array[1..2] of Integer;
ipl1 : Integer;
ipl2 : Integer;
IPTI1: Integer;
IPTI2: Integer;
Procedure CalcBorder;
var i : Integer;
JLT3 : Integer;
IPLJ1: Integer;
IPLJ2: Integer;
begin
for i:=1 to NLT3 div 3 do
begin
JLT3:=i*3;
IPLJ1:=IPL[JLT3-2];
IPLJ2:=IPL[JLT3-1];
if ((IPLJ1=ipl1) and (IPLJ2=IPTI2)) or
((IPLJ2=ipl1) and (IPLJ1=IPTI2)) then
IPL[JLT3]:=ITF[1];
if ((IPLJ1=ipl2) and (IPLJ2=IPTI1)) or
((IPLJ2=ipl2) and (IPLJ1=IPTI1)) then
IPL[JLT3]:=ITF[2];
end;
end;
Var DSQMN : TChartValue;
IPMN1 : Integer;
IPMN2 : Integer;
ip1 : Integer;
ip2 : Integer;
NDPM1 : Integer;
xd1 : TChartValue;
xd2 : TChartValue;
yd1 : TChartValue;
yd2 : TChartValue;
NDP0 : Integer;
DSQI : Double;
tmpCount : Integer;
{ find closest pair and their midpoint }
Function FindClosestPair:Boolean;
begin
result:=False;
DSQMN:=Sqr(XValues.Value[1]-XValues.Value[0])+Sqr(ZValues.Value[1]-ZValues.Value[0]);
IPMN1:=1;
IPMN2:=2;
ip1:=1;
while (not result) and (ip1<=NDPM1) do
begin
xd1:=XValues.Value[IP1];
yd1:=ZValues.Value[IP1];
ip2:=ip1+1;
while (not result) and (ip2<=NDP0) do
begin
xd2:=XValues.Value[IP2];
yd2:=ZValues.Value[IP2];
DSQI:=Sqr(xd2-xd1)+Sqr(yd2-yd1);
if DSQI=0.0 then
begin
XValues.Value[ip2]:=XValues.Value[NDP0];
YValues.Value[ip2]:=YValues.Value[NDP0];
ZValues.Value[ip2]:=ZValues.Value[NDP0];
Dec(tmpCount);
Dec(NDP0);
Dec(NDPM1);
Dec(ip2);
// result:=True; 7.0 removed.
end
else
if DSQI<DSQMN then
begin
DSQMN:=DSQI;
IPMN1:=ip1;
IPMN2:=ip2;
end;
Inc(ip2);
end;
Inc(ip1);
end;
end;
Var JPMN : Integer;
IWL : Array of Integer;
IWP : Array of Integer;
WK : Array of Double;
Procedure SortRest;
Var XDMP : TChartValue;
YDMP : TChartValue;
jp1 : Integer;
jp2 : Integer;
tmpip1 : Integer;
tmp : Integer;
begin
XDMP:=(XValues.Value[IPMN1]+XValues.Value[IPMN2])*0.5;
YDMP:=(ZValues.Value[IPMN1]+ZValues.Value[IPMN2])*0.5;
// sort other (NDP-2) datapoints in ascending order of
// distance from midpoint and stores datapoint numbers
// in IWP array
jp1:=2;
for tmpip1:=1 to NDP0 do
if (tmpip1<>IPMN1) and (tmpip1<>IPMN2) then
begin
Inc(jp1);
IWP[jp1]:=tmpip1;
WK[jp1]:=Sqr(XValues.Value[tmpIP1]-XDMP)+Sqr(ZValues.Value[tmpIP1]-YDMP);
end;
for jp1:=3 to NDPM1 do
begin
DSQMN:=WK[jp1];
JPMN:=jp1;
for jp2:=jp1 to NDP0 do
begin
// optimized...
if WK[jp2]<DSQMN then
begin
DSQMN:=WK[jp2];
JPMN:=jp2;
end;
end;
tmp:=IWP[jp1];
IWP[jp1]:=IWP[JPMN];
IWP[JPMN]:=tmp;
WK[JPMN]:=WK[jp1];
end;
end;
Var DSQ12 : Double;
Const Ratio = 1.0E-6;
NRep = 100;
Procedure CheckColinear;
Var AR : Double;
dx21 : Double;
dy21 : Double;
CoLinear : Double;
jp : Integer;
ip : Integer;
jpmx : Integer;
i : Integer;
begin
// if necessary modifies ordering so that first
// three datapoints are not colinear
AR:=DSQ12*ratio;
xd1:=XValues.Value[IPMN1];
yd1:=ZValues.Value[IPMN1];
dx21:=XValues.Value[IPMN2]-xd1;
dy21:=ZValues.Value[IPMN2]-yd1;
ip:=0;
jp:=3;
CoLinear:=0.0;
while (jp<=NDP0) and (colinear<=AR) do
begin
ip:=IWP[jp];
CoLinear:=Abs((ZValues.Value[IP]-yd1)*dx21-(XValues.Value[IP]-xd1)*dy21);
Inc(jp);
end;
Dec(jp);
if jp=NDP0 then
raise ETriSurfaceException.Create(TeeMsg_TriSurfaceAllColinear);
if jp<>3 then
begin
jpmx:=jp;
jp:=jpmx+1;
for i:=4 to jpmx do
begin
Dec(jp);
IWP[jp]:=IWP[jp-1];
end;
IWP[3]:=ip;
end;
end;
Var NTT3 : Integer;
// forms first triangle-vertices in IPT array and border
// line segments and triangle number in IPL array
Procedure AddFirst;
function Side(Const u1,v1,u2,v2,u3,v3:Double):Double;
begin
result:=(v3-v1)*(u2-u1)-(u3-u1)*(v2-v1);
end;
Var ip3 : Integer;
begin
ip1:=IPMN1;
ip2:=IPMN2;
ip3:=IWP[3];
if Side( XValues.Value[IP1],ZValues.Value[IP1],
XValues.Value[IP2],ZValues.Value[IP2],
XValues.Value[IP3],ZValues.Value[IP3])<0 then
begin
ip1:=IPMN2;
ip2:=IPMN1;
end;
NumTriangles:=1;
NTT3:=3;
{ first triangle }
IPT[1]:=ip1;
IPT[2]:=ip2;
IPT[3]:=ip3;
FNumLines:=3;
NLT3:=9;
IPL[1]:=ip1;
IPL[2]:=ip2;
IPL[3]:=1;
IPL[4]:=ip2;
IPL[5]:=ip3;
IPL[6]:=1;
IPL[7]:=ip3;
IPL[8]:=ip1;
IPL[9]:=1;
end;
Procedure CalcTriangle(jp1:Integer);
Var DXMN : Double;
DYMN : Double;
ARMN,dxmx,dymx,dsqmx,armx:Double;
NSH,JWL : Integer;
NLN,NLNT3,
ITT3,
NLF : Integer;
tmp,
jpmx : Integer;
Procedure Part1;
var jp2 : Integer;
AR : Double;
DX,
DY : Double;
begin
for jp2:=2 to FNumLines do
begin
ip2:=IPL[3*jp2-2];
xd2:=XValues.Value[IP2];
yd2:=ZValues.Value[IP2];
DX:=xd2-xd1;
DY:=yd2-yd1;
AR:=DY*DXMN-DX*DYMN;
if AR<=ARMN then
begin
DSQI:=Sqr(DX)+Sqr(DY);
if (AR<-ARMN) or (DSQI<DSQMN) then
begin
JPMN:=jp2;
DXMN:=DX;
DYMN:=DY;
DSQMN:=DSQI;
ARMN:=DSQMN*ratio;
end;
end;
AR:=DY*DXMX-DX*DYMX;
if AR>=-ARMX then
begin
DSQI:=Sqr(DX)+Sqr(DY);
if (AR>ARMX) or (DSQI<DSQMX) then
begin
JPMX:=jp2;
DXMX:=DX;
DYMX:=DY;
DSQMX:=DSQI;
ARMX:=DSQMX*ratio;
end;
end;
end;
end;
Procedure ShiftIPLArray;
var i : Integer;
tmpSource : Integer;
begin
// shifts the IPL array to have invisible border
// line segments contained in 1st part of array
for i:=1 to NSH do
begin
tmp:=i*3;
tmpSource:=tmp+NLT3;
IPL[tmpSource-2]:=IPL[tmp-2];
IPL[tmpSource-1]:=IPL[tmp-1];
IPL[tmpSource] :=IPL[tmp];
end;
for i:=1 to NLT3 div 3 do
begin
tmp:=i*3;
tmpSource:=tmp+(NSH*3);
IPL[tmp-2]:=IPL[tmpSource-2];
IPL[tmp-1]:=IPL[tmpSource-1];
IPL[tmp] :=IPL[tmpSource];
end;
Dec(JPMX,NSH);
end;
Procedure AddTriangles;
var jp2 : Integer;
IPTI : Integer;
IT : Integer;
jp2t3 : Integer;
begin
// adds triangles to IPT array, updates border line
// segments in IPL array and sets flags for the border
// line segments to be reexamined in the iwl array
JWL:=0;
NLNT3:=0;
for jp2:=JPMX to FNumLines do
begin
jp2t3:=jp2*3;
ipl1:=IPL[jp2t3-2];
ipl2:=IPL[jp2t3-1];
IT:=IPL[jp2t3];
// add triangle to IPT array
Inc(NumTriangles);
Inc(NTT3,3);
IPT[NTT3-2]:=ipl2;
IPT[NTT3-1]:=ipl1;
IPT[NTT3]:=ip1;
// updates borderline segments in ipl array
if jp2=JPMX then
begin
IPL[jp2t3-1]:=ip1;
IPL[jp2t3]:=NumTriangles;
end;
if jp2=FNumLines then
begin
NLN:=JPMX+1;
NLNT3:=NLN*3;
IPL[NLNT3-2]:=ip1;
IPL[NLNT3-1]:=IPL[1];
IPL[NLNT3]:=NumTriangles;
end;
// determine vertex that is not on borderline segments
ITT3:=IT*3;
IPTI:=IPT[ITT3-2];
if (IPTI=ipl1) or (IPTI=ipl2) then
begin
IPTI:=IPT[ITT3-1];
if (IPTI=ipl1) or (IPTI=ipl2) then IPTI:=IPT[ITT3];
end;
// checks if exchange is necessary
if IDxchg(ip1,IPTI,ipl1,ipl2)<>0 then
begin
// modifies ipt array if necessary
IPT[ITT3-2]:=IPTI;
IPT[ITT3-1]:=ipl1;
IPT[ITT3]:=ip1;
IPT[NTT3-1]:=IPTI;
if jp2=JPMX then IPL[jp2t3]:=IT;
if (jp2=FNumLines) and (IPL[3]=IT) then IPL[3]:=NumTriangles;
// set flags in IWL array
JWL:=JWL+4;
IWL[JWL-3]:=ipl1;
IWL[JWL-2]:=IPTI;
IWL[JWL-1]:=IPTI;
IWL[JWL]:=ipl2;
end;
end;
end;
Procedure ImproveTriangles;
Var ILF : Integer;
tmpNLF : Integer;
IPT1 : Integer;
IPT2 : Integer;
IPT3 : Integer;
IREP : Integer;
IT1T3 : Integer;
IT2T3 : Integer;
LoopFlag : Boolean;
NTF : Integer;
NTT3P3 : Integer;
begin
// improve triangulation
NTT3P3:=NTT3+3;
IREP:=1;
while IREP<=NREP do
begin
for ILF:=1 to NLF do
begin
ipl1:=IWL[ILF*2-1];
ipl2:=IWL[ILF*2];
// locates in ipt array two triangles on
// both sides of flagged line segment
NTF:=0;
LoopFlag:=True;
tmp:=3;
while LoopFlag and (tmp<=NTT3) do
begin
ITT3:=NTT3P3-tmp;
IPT1:=IPT[ITT3-2];
IPT2:=IPT[ITT3-1];
IPT3:=IPT[ITT3];
if (ipl1=IPT1) or (ipl1=IPT2) or (ipl1=IPT3) then // todo: optimize?
begin
if (ipl2=IPT1) or (ipl2=IPT2) or (ipl2=IPT3) then
begin
Inc(NTF);
ITF[NTF]:=ITT3 div 3;
if NTF=2 then LoopFlag:=False;
end;
end;
Inc(tmp,3);
end;
if NTF>=2 then
begin
IT1T3:=ITF[1]*3;
IPTI1:=IPT[IT1T3-2];
if (IPTI1=ipl1) or (IPTI1=ipl2) then
begin
IPTI1:=IPT[IT1T3-1];
if (IPTI1=ipl1) or (IPTI1=ipl2) then IPTI1:=IPT[IT1T3];
end;
IT2T3:=ITF[2]*3;
IPTI2:=IPT[IT2T3-2];
if (IPTI2=ipl1) or (IPTI2=ipl2) then
begin
IPTI2:=IPT[IT2T3-1];
if (IPTI2=ipl1) or (IPTI2=ipl2) then IPTI2:=IPT[IT2T3];
end;
// checks if exchange necessary
if IDxchg(IPTI1,IPTI2,ipl1,ipl2)<>0 then
begin
IPT[IT1T3-2]:=IPTI1;
IPT[IT1T3-1]:=IPTI2;
IPT[IT1T3]:=ipl1;
IPT[IT2T3-2]:=IPTI2;
IPT[IT2T3-1]:=IPTI1;
IPT[IT2T3]:=ipl2;
JWL:=JWL+8;
IWL[JWL-7]:=ipl1;
IWL[JWL-6]:=IPTI1;
IWL[JWL-5]:=IPTI1;
IWL[JWL-4]:=ipl2;
IWL[JWL-3]:=ipl2;
IWL[JWL-2]:=IPTI2;
IWL[JWL-1]:=IPTI2;
IWL[JWL] :=ipl1;
CalcBorder;
end;
end;
end;
tmp:=NLF;
NLF:=JWL div 2;
if NLF=tmp then break
else
begin // reset IWL array for next round
JWL:=0;
tmp:=(tmp+1)*2;
tmpNLF:=2*NLF;
while tmp<=tmpNLF do
begin
Inc(JWL,2);
IWL[JWL-1]:=IWL[tmp-1];
IWL[JWL] :=IWL[tmp];
Inc(tmp,2);
end;
NLF:=JWL div 2;
end;
Inc(IREP);
end;
end;
begin
ip1:=IWP[jp1];
xd1:=XValues.Value[IP1];
yd1:=ZValues.Value[IP1];
// determine visible borderline segments
ip2:=IPL[1];
JPMN:=1;
xd2:=XValues.Value[IP2];
yd2:=ZValues.Value[IP2];
DXMN:=xd2-xd1;
DYMN:=yd2-yd1;
DSQMN:=Sqr(DXMN)+Sqr(DYMN);
ARMN:=DSQMN*Ratio;
jpmx:=1;
dxmx:=DXMN;
dymx:=DYMN;
dsqmx:=DSQMN;
armx:=ARMN;
Part1;
if jpmx<jpmn then Inc(jpmx,FNumLines);
NSH:=JPMN-1;
if NSH>0 then ShiftIPLArray;
AddTriangles;
FNumLines:=NLN;
NLT3:=NLNT3;
NLF:=JWL div 2;
if (NLF<>0) and ImprovedTriangles then
ImproveTriangles;
end;
Var jp1 : Integer;
begin
Inc(IUpdating);
AddXYZ(XValues[0],YValues[0],ZValues[0]); // 7.0 first point
try
tmpCount:=Count;
NDP0:=tmpCount-1;
NDPM1:=NDP0-1;
SetLength(IPT,6*tmpCount-15);
SetLength(IPL,6*tmpCount);
SetLength(IWL,18*tmpCount);
SetLength(IWP,tmpCount);
SetLength(WK,tmpCount);
try
if not FindClosestPair then
begin
DSQ12:=DSQMN;
SortRest;
CheckColinear;
AddFirst;
// add the remaining NDP-3 data points one by one
for jp1:=4 to NDP0 do CalcTriangle(jp1);
ICreated:=True;
end
else
begin
Visible:=False; // 7.0
raise ETriSurfaceException.Create(TeeMsg_TriSurfaceSimilar);
end;
finally
IWL:=nil;
IWP:=nil;
WK:=nil;
end;
finally
Delete(Count-1);
Dec(IUpdating);
end;
end;
begin
inherited;
if Count<3 then
begin
NumTriangles:=0;
raise ETriSurfaceException.Create(TeeMsg_TriSurfaceLess);
end
else
if (not CacheTriangles) or (not ICreated) then { 5.02 }
CreateTriangles;
end;
Function TCustomTriSurfaceSeries.CalcPointResult(Index:Integer):TPoint3D;
begin
with result do
begin
X:=CalcXPos(Index);
Y:=CalcYPos(Index);
Z:=CalcZPos(Index);
end;
end;
Function TCustomTriSurfaceSeries.TrianglePoints(TriangleIndex:Integer):TTrianglePoints3D;
Procedure CalcPoint(APoint,Index:Integer);
begin
With result[APoint] do
begin
X:=CalcXPos(Index);
Y:=CalcYPos(Index);
Z:=CalcZPos(Index);
end;
end;
var tmp : Integer;
begin
tmp:=3*TriangleIndex;
CalcPoint(0,IPT[tmp-2]);
CalcPoint(1,IPT[tmp-1]);
CalcPoint(2,IPT[tmp]);
end;
Procedure TCustomTriSurfaceSeries.TrianglePointsTo2D(const P:TTrianglePoints3D; Var Result:TeCanvas.TTrianglePoints);
begin
with ParentChart.Canvas do
begin
result[0]:=Calculate3DPosition(P[0]);
result[1]:=Calculate3DPosition(P[1]);
result[2]:=Calculate3DPosition(P[2]);
end;
end;
procedure TCustomTriSurfaceSeries.DrawAllValues;
procedure AddSortedTriangles;
var tmpForward : Boolean;
{ sort triangles by Z (draw first triangles with bigger depth) }
Procedure AddByZ(ATriangle:PTriangle);
var tmp : PTriangle;
Last : PTriangle;
begin
Last:=nil;
tmp:=Triangles;
while Assigned(tmp) do
begin
if (tmpForward and (ATriangle.Z>tmp.Z)) or
((not tmpForward) and (tmp.Z>ATriangle.Z)) then
begin
if Assigned(tmp.Prev) then
begin
ATriangle.Prev:=tmp.Prev;
tmp.Prev.Next:=ATriangle;
end
else Triangles:=ATriangle;
tmp.Prev:=ATriangle;
ATriangle.Next:=tmp;
Exit;
end;
Last:=tmp;
tmp:=tmp.Next;
end;
if Assigned(Last) then
begin
Last.Next:=ATriangle;
ATriangle.Prev:=Last;
end
else Triangles:=ATriangle;
end;
var t : Integer;
tmpTriangle : PTriangle;
tmp : Integer;
tmpPoints : TTrianglePoints3D;
begin
{ create a list of triangles sorted by Z }
tmpForward:=not ParentChart.DepthAxis.Inverted;
if ParentChart.View3D and
(not ParentChart.View3DOptions.Orthogonal) then
if (ParentChart.View3DOptions.Rotation>90) and
(ParentChart.View3DOptions.Rotation<270) then
tmpForward:=not tmpForward; // 7.0
for t:=1 to NumTriangles do
begin
tmpPoints:=TrianglePoints(t);
{$IFDEF CLR}
tmpTriangle:=TTriangle.Create;
{$ELSE}
New(tmpTriangle);
{$ENDIF}
with tmpTriangle{$IFNDEF CLR}^{$ENDIF} do
begin
Next:=nil;
Prev:=nil;
Index:=t;
// Aproximate Z to the greatest of 3 triangle corners
tmp:=3*t;
Z:=Math.Max(ZValues.Value[IPT[tmp]],
Math.Max(ZValues.Value[IPT[tmp-1]],ZValues.Value[IPT[tmp-2]]));
// Calculate XY screen positions of corners
TrianglePointsTo2D(tmpPoints,P);
//Color
Color:=ValueColor[IPT[tmp-2]];
end;
AddByZ(tmpTriangle);
end;
end;
var
tmpBlend : TTeeBlend;
procedure DrawAllUnsorted;
var t : Integer;
tmpColors : TTriangleColors3D;
tmpPoints : TTrianglePoints3D;
tmpSmooth : Boolean;
P : TTrianglePoints;
begin
tmpSmooth:=ParentChart.Canvas.SupportsFullRotation;
// draw all triangles, do not hide
for t:=1 to NumTriangles do
begin
tmpPoints:=TrianglePoints(t);
if Assigned(tmpBlend) then
begin
TrianglePointsTo2D(tmpPoints,P);
tmpBlend.SetRectangle(RectFromTriangle(P));
end;
tmpColors[0]:=ValueColor[IPT[3*t-2]];
if tmpSmooth then // 7.0
begin
tmpColors[1]:=ValueColor[IPT[3*t-1]];
tmpColors[2]:=ValueColor[IPT[3*t]];
end
else
begin
tmpColors[1]:=tmpColors[0];
tmpColors[2]:=tmpColors[0];
end;
ParentChart.Canvas.Triangle3D(tmpPoints,tmpColors);
if Assigned(tmpBlend) then
tmpBlend.DoBlend(Transparency);
end;
end;
procedure DrawAllSorted;
var Triangle : PTriangle;
begin
{$IFNDEF CLX}
if FastBrush then // 7.0
begin
CanvasDC:=ParentChart.Canvas.Handle;
SelectObject(CanvasDC,DCBRUSH);
end;
{$ENDIF}
{ draw all triangles }
Triangle:=Triangles;
while Assigned(Triangle) do
begin
{$IFNDEF CLX}
if FastBrush then // 7.0
TeeSetDCBrushColor(CanvasDC,Triangle.Color)
else
{$ENDIF}
ParentChart.Canvas.Brush.Color:=Triangle.Color;
if Assigned(tmpBlend) then
tmpBlend.SetRectangle(RectFromPolygon(Triangle.P,3));
ParentChart.Canvas.Polygon(Triangle.P);
if Assigned(tmpBlend) then
tmpBlend.DoBlend(Transparency);
ILastTriangle:=Triangle;
Triangle:=Triangle.Next;
end;
end;
var t : Integer;
begin
ILastTriangle:=nil; // for Clicked method
With ParentChart.Canvas do
begin
if Self.Pen.Visible or (Self.Brush.Style<>bsClear) then
begin
AssignBrush(Self.Brush,Self.Brush.Color);
AssignVisiblePen(Self.Pen);
if Transparency>0 then
tmpBlend:=BeginBlending(TeeRect(0,0,0,0),Transparency)
else
tmpBlend:=nil;
if HideTriangles and (not SupportsFullRotation) and (Brush.Style=bsSolid) then
begin
ClearTriangles;
AddSortedTriangles;
DrawAllSorted;
end
else
DrawAllUnsorted;
tmpBlend.Free; // Do not call EndBlending here...
end;
{ draw border }
if Self.FBorder.Visible then
begin
AssignVisiblePen(Self.FBorder);
for t:=1 to FNumLines do
begin
MoveTo3D(CalcPointResult(IPL[3*t-2]));
LineTo3D(CalcPointResult(IPL[3*t-1]));
end;
end;
end;
end;
procedure TCustomTriSurfaceSeries.SetFastBrush(const Value: Boolean);
begin
{$IFNDEF CLX}
if Assigned(@TeeSetDCBrushColor) then
begin
FFastBrush:=Value;
DCBRUSH:=GetStockObject(DC_BRUSH);
end;
{$ENDIF}
end;
Procedure TCustomTriSurfaceSeries.DrawMark( ValueIndex:Integer; Const St:String;
APosition:TSeriesMarkPosition);
begin
Marks.ZPosition:=CalcZPos(ValueIndex);
Marks.ApplyArrowLength(APosition);
inherited;
end;
procedure TCustomTriSurfaceSeries.Assign(Source: TPersistent);
begin
if Source is TCustomTriSurfaceSeries then
with TCustomTriSurfaceSeries(Source) do
begin
Self.Border:=Border;
Self.ImprovedTriangles:=ImprovedTriangles;
Self.FHide:=HideTriangles;
Self.FTransp:=Transparency;
end;
inherited;
end;
class procedure TCustomTriSurfaceSeries.CreateSubGallery(
AddSubChart: TChartSubGalleryProc);
begin
inherited;
AddSubChart(TeeMsg_WireFrame);
AddSubChart(TeeMsg_NoLine);
AddSubChart(TeeMsg_Border);
end;
Procedure TCustomTriSurfaceSeries.PrepareForGallery(IsEnabled:Boolean);
begin
inherited;
FillSampleValues;
end;
class procedure TCustomTriSurfaceSeries.SetSubGallery(
ASeries: TChartSeries; Index: Integer);
begin
With TCustomTriSurfaceSeries(ASeries) do
Case Index of
2: Brush.Style:=bsClear;
3: Pen.Hide;
4: Border.Show;
else inherited;
end;
end;
procedure TCustomTriSurfaceSeries.Clear;
begin
inherited;
ICreated:=False;
end;
procedure TCustomTriSurfaceSeries.SetHide(const Value: Boolean);
begin
SetBooleanProperty(FHide,Value);
end;
Procedure TCustomTriSurfaceSeries.SetTransp(Value:TTeeTransparency);
begin
if FTransp<>Value then
begin
FTransp:=Value;
Repaint;
end;
end;
initialization
RegisterTeeSeries( TTriSurfaceSeries, {$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryTriSurface,
{$IFNDEF CLR}@{$ENDIF}TeeMsg_Gallery3D,1);
finalization
UnRegisterTeeSeries([TTriSurfaceSeries]);
end.
|
unit dmediciontugs;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, ZDataset, ZSqlUpdate, rxmemds
,dmConexion, db, IBConnection, sqldb;
type
{ TCampoTUG }
TCampoTUG = class
private
_campoTug: string;
_tituloCampo: string;
public
property campo: string read _campoTug write _campoTug;
property titulo: string read _tituloCampo write _tituloCampo;
constructor Create;
end;
{ TTablaTUG }
TTablaTUG= class
private
_nombreTabla: string;
_tituloTabla: string;
_ListaCampos: TList;
public
property nombre: string read _nombreTabla write _nombreTabla;
property titulo: string read _tituloTabla write _tituloTabla;
procedure AgregarCampo (nombreCampo, nombreTitulo: string);
function DevolverCampo (posicion: Integer): TCampoTUG;
function CantidadCampos: integer;
constructor Create;
end;
{ TDM_EdicionTUGs }
TDM_EdicionTUGs = class(TDataModule)
tbTabla: TZTable;
procedure DataModuleCreate(Sender: TObject);
procedure tbTablaAfterInsert(DataSet: TDataSet);
private
{ private declarations }
public
function DevolverTField (elCampo: string): TField;
procedure EliminarFila;
end;
var
DM_EdicionTUGs: TDM_EdicionTUGs;
implementation
procedure TDM_EdicionTUGs.DataModuleCreate(Sender: TObject);
begin
end;
{ TDM_EdicionTUGs }
procedure TDM_EdicionTUGs.tbTablaAfterInsert(DataSet: TDataSet);
begin
With Dataset do
begin
FieldByName('id').asInteger:= -1;
FieldByName('bVisible').asInteger:= 1;
end;
end;
function TDM_EdicionTUGs.DevolverTField(elCampo: string): TField;
begin
Result:= tbTabla.FindField(elCampo);
end;
procedure TDM_EdicionTUGs.EliminarFila;
begin
with tbTabla do
begin
Edit;
FieldByName('bVisible').asInteger:= 0;
Post;
end;
end;
{ TCampoTUG }
constructor TCampoTUG.Create;
begin
inherited;
campo:= EmptyStr;
titulo:= EmptyStr;
end;
{$R *.lfm}
{ TTablaTUG }
procedure TTablaTUG.AgregarCampo(nombreCampo, nombreTitulo: string);
var
elCampo: TCampoTUG;
begin
elCampo:= TcampoTUG.Create;
elCampo.titulo:= nombreTitulo;
elCampo.campo:= nombreCampo;
_ListaCampos.Add(elCampo);
end;
function TTablaTUG.DevolverCampo(posicion: Integer): TCampoTUG;
begin
if posicion < _ListaCampos.Count then
Result:= TCampoTUG(_ListaCampos.Items[posicion])
else
Result:= nil;
end;
function TTablaTUG.CantidadCampos: integer;
begin
Result:= _ListaCampos.Count;
end;
constructor TTablaTUG.Create;
begin
inherited;
nombre:= EmptyStr;
titulo:= EmptyStr;
_ListaCampos:= TList.Create;
end;
end.
|
Unit router;
uses System;
uses System.Net;
uses System.Threading.Tasks;
type
HandlerFunc = procedure(var ctx: System.Net.HttpListenerContext);
HttpRouter = class
private
handlers: Dictionary<string, HandlerFunc>;
prefixes: List<string>;
public
constructor Create();
begin
prefixes := new List<string>;
handlers := new Dictionary<string, HandlerFunc>
end;
procedure Register(prefix :string; handler: HandlerFunc);
begin
prefixes.Add(prefix);
prefixes.Sort();
prefixes.Reverse();
handlers.Add(prefix, handler);
end;
procedure Serve(var ctx: System.Net.HttpListenerContext);
begin
var url := ctx.Request.Url.LocalPath;
{ Exact match. }
if handlers.ContainsKey(url) then begin
handlers[url](ctx);
exit;
end;
foreach var p in prefixes do begin
if (url.StartsWith(p)) then begin
handlers[p](ctx);
break;
end;
end;
end;
end;
end. |
unit Support.Samsung;
interface
uses
SysUtils, Math,
Support, Device.SMART.List;
type
TSamsungNSTSupport = class sealed(TNSTSupport)
private
InterpretingSMARTValueList: TSMARTValueList;
function GetFullSupport: TSupportStatus;
function GetTotalWrite: TTotalWrite;
function IsProductOfSamsung: Boolean;
function IsSamsung470: Boolean;
function IsSamsungOtherSSD: Boolean;
function IsSamsungSATA: Boolean;
public
function GetSupportStatus: TSupportStatus; override;
function GetSMARTInterpreted(SMARTValueList: TSMARTValueList):
TSMARTInterpreted; override;
end;
implementation
{ TSamsungNSTSupport }
function TSamsungNSTSupport.IsSamsungOtherSSD: Boolean;
begin
result :=
Pos('SSD', UpperCase(Identify.Model)) > 0;
end;
function TSamsungNSTSupport.IsSamsung470: Boolean;
begin
result :=
Pos('470', UpperCase(Identify.Model)) > 0;
end;
function TSamsungNSTSupport.IsSamsungSATA: Boolean;
begin
result :=
Pos('BX', UpperCase(Identify.Firmware)) < 5;
end;
function TSamsungNSTSupport.IsProductOfSamsung: Boolean;
begin
result :=
(Pos('SAMSUNG', UpperCase(Identify.Model)) > 0) and
(IsSamsungOtherSSD or IsSamsung470) and
IsSamsungSATA;
end;
function TSamsungNSTSupport.GetFullSupport: TSupportStatus;
begin
result.Supported := Supported;
result.FirmwareUpdate := true;
result.TotalWriteType := TTotalWriteType.WriteSupportedAsValue;
end;
function TSamsungNSTSupport.GetSupportStatus: TSupportStatus;
begin
result.Supported := NotSupported;
if IsProductOfSamsung then
result := GetFullSupport;
end;
function TSamsungNSTSupport.GetTotalWrite: TTotalWrite;
const
LBAtoMiB: Double = 1/2 * 1/1024;
IDOfHostWrite = 241;
var
RAWValue: UInt64;
begin
result.InValue.TrueHostWriteFalseNANDWrite := true;
RAWValue :=
InterpretingSMARTValueList.GetRAWByID(IDOfHostWrite);
result.InValue.ValueInMiB := Floor(RAWValue * LBAtoMiB);
end;
function TSamsungNSTSupport.GetSMARTInterpreted(
SMARTValueList: TSMARTValueList): TSMARTInterpreted;
const
IDOfEraseError = 182;
IDOfReplacedSector = 5;
IDofUsedHour = 9;
ReplacedSectorThreshold = 50;
EraseErrorThreshold = 10;
begin
InterpretingSMARTValueList := SMARTValueList;
result.TotalWrite := GetTotalWrite;
result.UsedHour :=
InterpretingSMARTValueList.GetRAWByID(IDOfUsedHour);
result.ReadEraseError.TrueReadErrorFalseEraseError := false;
result.ReadEraseError.Value :=
InterpretingSMARTValueList.GetRAWByID(IDOfEraseError);
result.SMARTAlert.ReadEraseError :=
result.ReadEraseError.Value >= EraseErrorThreshold;
result.ReplacedSectors :=
InterpretingSMARTValueList.GetRAWByID(IDOfReplacedSector);
result.SMARTAlert.ReplacedSector :=
result.ReplacedSectors >= ReplacedSectorThreshold;
end;
end.
|
{**********************************************}
{ TCandleSeries (derived from OHLCSeries) }
{ TVolumeSeries (derived from TCustomSeries) }
{ TRSIFunction (Resistance Strength Index) }
{ TADXFunction }
{ }
{ Copyright (c) 1995-2004 by David Berneda }
{**********************************************}
unit CandleCh;
{$I TeeDefs.inc}
interface
{
Financial TCandleSeries derives from TOHLCSeries (Open, High, Low & Close).
See OHLChart.pas unit for TOHLCSeries source code.
TCandleSeries overrides the TChartSeries.DrawValue method to paint its
points in several financial styles (CandleStick, Bars, OpenClose, etc).
TVolumeSeries overrides the TChartSeries.DrawValue method to paint
points as thin vertical bars.
TADXFunction is a commonly used financial indicator. It requires an
OHLC (financial) series as the datasource.
TRSIFunction (Resistence Strength Index) is a commonly used financial
indicator. It requires an OHLC (financial) series as the datasource.
}
Uses {$IFNDEF LINUX}
Windows,
{$ENDIF}
Classes,
{$IFDEF CLX}
QGraphics, Types,
{$ELSE}
Graphics,
{$ENDIF}
Chart, Series, OHLChart, TeEngine, TeCanvas;
Const DefCandleWidth = 4; { 2 + 1 + 2 Default width for Candle points }
type
TCandleStyle=(csCandleStick,csCandleBar,csOpenClose,csLine);
TCandleItem=packed record
yOpen : Integer;
yClose : Integer;
yHigh : Integer;
yLow : Integer;
tmpX : Integer;
tmpLeftWidth : Integer;
tmpRightWidth : Integer;
end;
TCandleSeries=class(TOHLCSeries)
private
FCandleStyle : TCandleStyle;
FCandleWidth : Integer;
FDownCloseColor : TColor;
FHighLowPen : TChartPen;
FShowCloseTick : Boolean;
FShowOpenTick : Boolean;
FUpCloseColor : TColor;
OldP : TPoint;
procedure CalcItem(ValueIndex:Integer; var AItem:TCandleItem);
Function GetDark3D:Boolean;
Function GetDraw3D:Boolean;
Function GetPen:TChartPen;
procedure SetCandlePen(Value:TChartPen);
Procedure SetCandleStyle(Value:TCandleStyle);
Procedure SetCandleWidth(Value:Integer);
procedure SetDark3D(Value:Boolean);
Procedure SetDownColor(Value:TColor);
procedure SetDraw3D(Value:Boolean);
Procedure SetShowCloseTick(Value:Boolean);
Procedure SetShowOpenTick(Value:Boolean);
Procedure SetUpColor(Value:TColor);
procedure SetHighLowPen(const Value: TChartPen);
protected
Function CalculateColor(ValueIndex:Integer):TColor;
class Procedure CreateSubGallery(AddSubChart:TChartSubGalleryProc); override;
procedure DrawValue(ValueIndex:Integer); override;
class Function GetEditorClass:String; override;
Procedure PrepareForGallery(IsEnabled:Boolean); override;
class Procedure SetSubGallery(ASeries:TChartSeries; Index:Integer); override;
public
Constructor Create(AOwner: TComponent); override;
Destructor Destroy; override;
Procedure Assign(Source:TPersistent); override;
Function AddCandle( Const ADate:TDateTime;
Const AOpen,AHigh,ALow,AClose:Double):Integer;
Function Clicked(x,y:Integer):Integer; override;
function ClickedCandle(ValueIndex:Integer; const P:TPoint):Boolean;
Function LegendItemColor(LegendIndex:Integer):TColor; override;
Function MaxYValue:Double; override;
Function MinYValue:Double; override;
published
property Active;
property ColorEachPoint;
property ColorSource;
property Cursor;
property Depth;
property HorizAxis;
property Marks;
property ParentChart;
property DataSource;
property PercentFormat;
property SeriesColor;
property ShowInLegend;
property Title;
property ValueFormat;
property VertAxis;
property XLabelsSource;
{ events }
property AfterDrawValues;
property BeforeDrawValues;
property OnAfterAdd;
property OnBeforeAdd;
property OnClearValues;
property OnClick;
property OnDblClick;
property OnGetMarkText;
property OnMouseEnter;
property OnMouseLeave;
property CandleStyle:TCandleStyle read FCandleStyle write SetCandleStyle
default csCandleStick;
property CandleWidth:Integer read FCandleWidth write SetCandleWidth
default DefCandleWidth;
property Draw3D:Boolean read GetDraw3D write SetDraw3D default False;
property Dark3D:Boolean read GetDark3D write SetDark3D default True;
property DownCloseColor:TColor read FDownCloseColor write SetDownColor
default clRed;
property HighLowPen:TChartPen read FHighLowPen write SetHighLowPen;
property ShowCloseTick:Boolean read FShowCloseTick write SetShowCloseTick
default True;
property ShowOpenTick:Boolean read FShowOpenTick write SetShowOpenTick
default True;
property UpCloseColor:TColor read FUpCloseColor write SetUpColor
default clWhite;
property Pen:TChartPen read GetPen write SetCandlePen;
end;
{ Used in financial charts for Volume quantities (or OpenInterest) }
{ Overrides FillSampleValues to create random POSITIVE values }
{ Overrides DrawValue to paint a thin vertical bar }
{ Declares VolumeValues (same like YValues) }
TVolumeSeries=class(TCustomSeries)
private
FUseYOrigin: Boolean;
FOrigin: Double;
IColor : TColor;
Function GetVolumeValues:TChartValueList;
Procedure PrepareCanvas(Forced:Boolean; AColor:TColor);
procedure SetOrigin(const Value: Double);
procedure SetUseOrigin(const Value: Boolean);
Procedure SetVolumeValues(Value:TChartValueList);
protected
Procedure AddSampleValues(NumValues:Integer; OnlyMandatory:Boolean=False); override;
class Procedure CreateSubGallery(AddSubChart:TChartSubGalleryProc); override;
Procedure DrawLegendShape(ValueIndex:Integer; Const Rect:TRect); override;
procedure DrawValue(ValueIndex:Integer); override;
class Function GetEditorClass:String; override;
Procedure PrepareForGallery(IsEnabled:Boolean); override;
Procedure PrepareLegendCanvas( ValueIndex:Integer; Var BackColor:TColor;
Var BrushStyle:TBrushStyle); override;
Procedure SetSeriesColor(AColor:TColor); override;
class Procedure SetSubGallery(ASeries:TChartSeries; Index:Integer); override;
public
Constructor Create(AOwner: TComponent); override;
Procedure Assign(Source:TPersistent); override;
Function NumSampleValues:Integer; override;
published
property Active;
property ColorEachPoint;
property ColorSource;
property Cursor;
property HorizAxis;
property Marks;
property ParentChart;
property DataSource;
property PercentFormat;
property SeriesColor;
property ShowInLegend;
property Title;
property ValueFormat;
property VertAxis;
property XLabelsSource;
{ events }
property AfterDrawValues;
property BeforeDrawValues;
property OnAfterAdd;
property OnBeforeAdd;
property OnClearValues;
property OnClick;
property OnDblClick;
property OnGetMarkText;
property OnMouseEnter;
property OnMouseLeave;
property LinePen;
property UseYOrigin:Boolean read FUseYOrigin write SetUseOrigin default False;
property VolumeValues:TChartValueList read GetVolumeValues write SetVolumeValues;
property XValues;
property YOrigin:Double read FOrigin write SetOrigin;
end;
{ Financial A.D.X function }
TADXFunction=class(TTeeFunction)
private
IDMDown : TFastLineSeries;
IDMUp : TFastLineSeries;
function GetDownPen: TChartPen;
function GetUpPen: TChartPen;
procedure SetDownPen(const Value: TChartPen);
procedure SetUpPen(const Value: TChartPen);
protected
class Function GetEditorClass:String; override;
Function IsValidSource(Value:TChartSeries):Boolean; override;
public
Constructor Create(AOwner:TComponent); override;
Destructor Destroy; override; { 5.01 }
procedure AddPoints(Source:TChartSeries); override;
property DMDown:TFastLineSeries read IDMDown;
property DMUp:TFastLineSeries read IDMUp;
published
property DownLinePen:TChartPen read GetDownPen write SetDownPen;
property UpLinePen:TChartPen read GetUpPen write SetUpPen;
end;
{ RSI, Relative Strentgh Index }
TRSIStyle=(rsiOpenClose,rsiClose);
TRSIFunction = class(TTeeMovingFunction)
private
FStyle : TRSIStyle;
ISeries : TChartSeries;
Opens : TChartValueList;
Closes : TChartValueList;
procedure SetStyle(Const Value:TRSIStyle);
protected
Function IsValidSource(Value:TChartSeries):Boolean; override;
public
Constructor Create(AOwner:TComponent); override;
Function Calculate( Series:TChartSeries;
FirstIndex,LastIndex:Integer):Double; override;
published
property Style:TRSIStyle read FStyle write SetStyle default rsiOpenClose;
end;
implementation
Uses {$IFDEF CLR}
{$ELSE}
Math, SysUtils,
{$ENDIF}
TeeProcs, TeeProCo, TeeConst;
{ TCandleSeries }
Constructor TCandleSeries.Create(AOwner: TComponent);
Begin
inherited;
FUpCloseColor :=clWhite;
FDownCloseColor:=clRed;
FCandleWidth :=DefCandleWidth;
FCandleStyle :=csCandleStick;
FShowOpenTick :=True;
FShowCloseTick :=True;
Pointer.Draw3D :=False;
FHighLowPen:=TChartPen.Create(CanvasChanged); // 7.0
FHighLowPen.Color:=clTeeColor;
end;
Procedure TCandleSeries.SetShowOpenTick(Value:Boolean);
Begin
SetBooleanProperty(FShowOpenTick,Value);
End;
Procedure TCandleSeries.SetShowCloseTick(Value:Boolean);
Begin
SetBooleanProperty(FShowCloseTick,Value);
End;
Function TCandleSeries.CalculateColor(ValueIndex:Integer):TColor;
Begin
result:=ValueColor[ValueIndex];
if result=SeriesColor then
begin
if OpenValues.Value[ValueIndex]>CloseValues.Value[ValueIndex] then { 5.01 }
result:=FDownCloseColor
else
if OpenValues.Value[ValueIndex]<CloseValues.Value[ValueIndex] then
result:=FUpCloseColor
else
Begin
{ color algorithm when open is equal to close }
if ValueIndex=0 then
result:=FUpCloseColor { <-- first point }
else
if CloseValues.Value[ValueIndex-1]>CloseValues.Value[ValueIndex] then
result:=FDownCloseColor
else
if CloseValues.Value[ValueIndex-1]<CloseValues.Value[ValueIndex] then
result:=FUpCloseColor
else
result:=ValueColor[ValueIndex-1];
end;
end;
end;
procedure TCandleSeries.CalcItem(ValueIndex:Integer; var AItem:TCandleItem);
begin
with AItem do
begin
tmpX:=CalcXPosValue(DateValues.Value[ValueIndex]); { The horizontal position }
{ Vertical positions of Open, High, Low & Close values for this point }
YOpen :=CalcYPosValue(OpenValues.Value[ValueIndex]);
YHigh :=CalcYPosValue(HighValues.Value[ValueIndex]);
YLow :=CalcYPosValue(LowValues.Value[ValueIndex]);
YClose:=CalcYPosValue(CloseValues.Value[ValueIndex]);
tmpLeftWidth:=FCandleWidth div 2; { calc half Candle Width }
tmpRightWidth:=FCandleWidth-tmpLeftWidth;
end;
end;
procedure TCandleSeries.DrawValue(ValueIndex:Integer);
Procedure CheckHighLowPen;
begin
with ParentChart.Canvas do
begin
if HighLowPen.Color=clTeeColor then
AssignVisiblePenColor(HighLowPen,Self.Pen.Color)
else
AssignVisiblePen(HighLowPen);
BackMode:=cbmTransparent;
end;
end;
var tmpItem : TCandleItem;
tmpTop : Integer;
tmpBottom : Integer;
P : TPoint;
tmpFirst : Integer;
begin
if Assigned(OnGetPointerStyle) then { 5.02 }
OnGetPointerStyle(Self,ValueIndex);
{ Prepare Pointer Pen and Brush styles }
Pointer.PrepareCanvas(ParentChart.Canvas,clTeeColor);
CalcItem(ValueIndex,tmpItem);
with tmpItem,ParentChart,Canvas do
begin
if (FCandleStyle=csCandleStick) or (FCandleStyle=csOpenClose) then
begin { draw Candle Stick }
CheckHighLowPen;
if View3D and Pointer.Draw3D then
begin
tmpTop:=yClose;
tmpBottom:=yOpen;
if tmpTop>tmpBottom then SwapInteger(tmpTop,tmpBottom);
{ Draw Candle Vertical Line from bottom to Low }
if FCandleStyle=csCandleStick then
VertLine3D(tmpX,tmpBottom,yLow,MiddleZ);
{ Draw 3D Candle }
Brush.Color:=CalculateColor(ValueIndex);
if Self.Pen.Visible then
if yOpen=yClose then AssignVisiblePenColor(Self.Pen,CalculateColor(ValueIndex))
else AssignVisiblePen(Self.Pen)
else
Pen.Style:=psClear; // 7.0
Cube( tmpX-tmpLeftWidth,tmpX+tmpRightWidth,tmpTop,tmpBottom,
StartZ,EndZ,Pointer.Dark3D);
CheckHighLowPen;
{ Draw Candle Vertical Line from Top to High }
if FCandleStyle=csCandleStick then
VertLine3D(tmpX,tmpTop,yHigh,MiddleZ);
end
else
begin
{ Draw Candle Vertical Line from High to Low }
if FCandleStyle=csCandleStick then
if View3D then
VertLine3D(tmpX,yLow,yHigh,MiddleZ)
else
DoVertLine(tmpX,yLow,yHigh);
{ remember that Y coordinates are inverted }
{ prevent zero height rectangles 5.02 }
{ in previous releases, an horizontal line was displayed instead
of the small candle rectangle }
if yOpen=yClose then Dec(yClose);
{ draw the candle }
Brush.Color:=CalculateColor(ValueIndex);
if Self.Pen.Visible then
if yOpen=yClose then AssignVisiblePenColor(Self.Pen,CalculateColor(ValueIndex))
else AssignVisiblePen(Self.Pen)
else
Pen.Style:=psClear; // 7.0
if View3D then
RectangleWithZ(TeeRect(tmpX-tmpLeftWidth,yOpen,tmpX+tmpRightWidth,yClose),
MiddleZ)
else
begin
if not Self.Pen.Visible then
if yOpen<yClose then Dec(yOpen) else Dec(yClose);
Rectangle(tmpX-tmpLeftWidth,yOpen,tmpX+tmpRightWidth+1,yClose);
end;
end;
end
else
if FCandleStyle=csLine then // Line
begin
P:=TeePoint(tmpX,YClose);
tmpFirst:=FirstDisplayedIndex;
if (ValueIndex<>tmpFirst) and (not IsNull(ValueIndex)) then
begin
AssignVisiblePenColor(Self.Pen,CalculateColor(ValueIndex));
BackMode:=cbmTransparent;
if View3D then LineWithZ(OldP,P,MiddleZ)
else Line(OldP,P);
end;
OldP:=P;
end
else
begin // Draw Candle bar
AssignVisiblePenColor(Self.Pen,CalculateColor(ValueIndex));
BackMode:=cbmTransparent;
// Draw Candle Vertical Line from High to Low
if View3D then
begin
VertLine3D(tmpX,yLow,yHigh,MiddleZ);
if ShowOpenTick then HorizLine3D(tmpX,tmpX-tmpLeftWidth-1,yOpen,MiddleZ);
if ShowCloseTick then HorizLine3D(tmpX,tmpX+tmpRightWidth+1,yClose,MiddleZ);
end
else
begin // 5.02
DoVertLine(tmpX,yLow,yHigh);
if ShowOpenTick then DoHorizLine(tmpX,tmpX-tmpLeftWidth-1,yOpen);
if ShowCloseTick then DoHorizLine(tmpX,tmpX+tmpRightWidth+1,yClose);
end;
end;
end;
end;
Procedure TCandleSeries.SetUpColor(Value:TColor);
Begin
SetColorProperty(FUpCloseColor,Value);
end;
Procedure TCandleSeries.SetDownColor(Value:TColor);
Begin
SetColorProperty(FDownCloseColor,Value);
end;
Procedure TCandleSeries.SetCandleWidth(Value:Integer);
Begin
SetIntegerProperty(FCandleWidth,Value);
end;
Procedure TCandleSeries.SetCandleStyle(Value:TCandleStyle);
Begin
if FCandleStyle<>Value then
begin
FCandleStyle:=Value;
Pointer.Visible:=CandleStyle<>csLine;
Repaint;
end;
end;
class Function TCandleSeries.GetEditorClass:String;
Begin
result:='TCandleEditor'; { <-- do not translate }
End;
Procedure TCandleSeries.PrepareForGallery(IsEnabled:Boolean);
Begin
inherited;
FillSampleValues(4);
ColorEachPoint:=IsEnabled;
if IsEnabled then
UpCloseColor:=clBlue
else
begin
UpCloseColor:=clSilver;
DownCloseColor:=clDkGray;
Pointer.Pen.Color:=clGray;
end;
Pointer.Pen.Width:=2;
CandleWidth:=12;
end;
Procedure TCandleSeries.Assign(Source:TPersistent);
begin
if Source is TCandleSeries then
With TCandleSeries(Source) do
begin
Self.FCandleWidth :=FCandleWidth;
Self.FCandleStyle :=FCandleStyle;
Self.FUpCloseColor :=FUpCloseColor;
Self.FDownCloseColor:=FDownCloseColor;
Self.HighLowPen :=FHighLowPen;
Self.FShowOpenTick :=FShowOpenTick;
Self.FShowCloseTick :=FShowCloseTick;
end;
inherited;
end;
Function TCandleSeries.GetDraw3D:Boolean;
begin
result:=Pointer.Draw3D;
end;
procedure TCandleSeries.SetDraw3D(Value:Boolean);
begin
Pointer.Draw3D:=Value;
end;
Function TCandleSeries.GetDark3D:Boolean;
begin
result:=Pointer.Dark3D;
end;
procedure TCandleSeries.SetDark3D(Value:Boolean);
begin
Pointer.Dark3D:=Value;
end;
Function TCandleSeries.GetPen:TChartPen;
begin
result:=Pointer.Pen;
end;
procedure TCandleSeries.SetCandlePen(Value:TChartPen);
begin
Pointer.Pen.Assign(Value);
end;
Function TCandleSeries.AddCandle( Const ADate:TDateTime;
Const AOpen,AHigh,ALow,AClose:Double):Integer;
begin
result:=AddOHLC(ADate,AOpen,AHigh,ALow,AClose);
end;
class procedure TCandleSeries.CreateSubGallery(
AddSubChart: TChartSubGalleryProc);
begin
inherited;
AddSubChart(TeeMsg_CandleBar);
AddSubChart(TeeMsg_CandleNoOpen);
AddSubChart(TeeMsg_CandleNoClose);
AddSubChart(TeeMsg_NoBorder);
AddSubChart(TeeMsg_Line);
end;
class procedure TCandleSeries.SetSubGallery(ASeries: TChartSeries;
Index: Integer);
begin
With TCandleSeries(ASeries) do
Case Index of
1: CandleStyle:=csCandleBar;
2: begin Pen.Show; CandleStyle:=csCandleBar; ShowOpenTick:=False; end;
3: begin Pen.Show; CandleStyle:=csCandleBar; ShowCloseTick:=False; end;
4: begin CandleStyle:=csCandleStick; Pen.Hide; end;
5: begin CandleStyle:=csLine; end;
else inherited;
end;
end;
function TCandleSeries.ClickedCandle(ValueIndex:Integer; const P:TPoint):Boolean;
var tmpItem : TCandleItem;
tmpTop : Integer;
tmpBottom : Integer;
tmpFirst : Integer;
tmpTo : TPoint;
begin
result:=False;
CalcItem(ValueIndex,tmpItem);
With tmpItem do
Begin
if (FCandleStyle=csCandleStick) or (FCandleStyle=csOpenClose) then
begin
if ParentChart.View3D and Pointer.Draw3D then
begin
tmpTop:=yClose;
tmpBottom:=yOpen;
if tmpTop>tmpBottom then SwapInteger(tmpTop,tmpBottom);
if (FCandleStyle=csCandleStick) and
(
PointInLine(P,tmpX,tmpBottom,tmpX,yLow) or
PointInLine(P,tmpX,tmpTop,tmpX,yHigh)
) then
begin
result:=True;
exit;
end;
if PointInRect(TeeRect(tmpX-tmpLeftWidth,tmpTop,tmpX+tmpRightWidth,tmpBottom),P.X,P.Y) then
result:=True;
end
else
begin
if (FCandleStyle=csCandleStick) and
PointInLine(P,tmpX,yLow,tmpX,yHigh) then
begin
result:=True;
exit;
end;
if yOpen=yClose then Dec(yClose);
if ParentChart.View3D then
begin
if PointInRect(TeeRect(tmpX-tmpLeftWidth,yOpen,tmpX+tmpRightWidth,yClose),P.X,P.Y) then
result:=True;
end
else
begin
if not Self.Pen.Visible then
if yOpen<yClose then Dec(yOpen) else Dec(yClose);
if PointInRect(TeeRect(tmpX-tmpLeftWidth,yOpen,tmpX+tmpRightWidth+1,yClose),P.X,P.Y) then
result:=True;
end;
end;
end
else
if CandleStyle=csLine then
begin
tmpFirst:=FirstDisplayedIndex;
tmpTo:=TeePoint(tmpX,YClose);
if ValueIndex<>tmpFirst then result:=PointInLine(P,OldP,tmpTo);
OldP:=tmpTo;
end
else
if PointInLine(P,tmpX,yLow,tmpX,yHigh) or
(ShowOpenTick and PointInLine(P,tmpX,yOpen,tmpX-tmpLeftWidth-1,yOpen)) or
(ShowCloseTick and PointInLine(P,tmpX,yClose,tmpX+tmpRightWidth+1,yClose)) then
result:=True;
end;
end;
function TCandleSeries.Clicked(x, y: Integer): Integer;
var t : Integer;
P : TPoint;
begin
result:=TeeNoPointClicked;
if (FirstValueIndex>-1) and (LastValueIndex>-1) then
begin
if Assigned(ParentChart) then
ParentChart.Canvas.Calculate2DPosition(X,Y,StartZ);
P:=TeePoint(x,y);
for t:=FirstValueIndex to LastValueIndex do
if ClickedCandle(t,P) then
begin
result:=t;
break;
end;
end;
end;
function TCandleSeries.LegendItemColor(LegendIndex: Integer): TColor;
begin
result:=CalculateColor(LegendIndex);
end;
function TCandleSeries.MaxYValue: Double;
begin
if CandleStyle=csLine then result:=CloseValues.MaxValue
else result:=inherited MaxYValue;
end;
function TCandleSeries.MinYValue: Double;
begin
if CandleStyle=csLine then result:=CloseValues.MinValue
else result:=inherited MinYValue;
end;
procedure TCandleSeries.SetHighLowPen(const Value: TChartPen);
begin
FHighLowPen.Assign(Value);
end;
destructor TCandleSeries.Destroy;
begin
FHighLowPen.Free;
inherited;
end;
{ TVolumeSeries }
Constructor TVolumeSeries.Create(AOwner: TComponent);
begin
inherited;
DrawArea:=False;
DrawBetweenPoints:=False;
ClickableLine:=False;
Pointer.Hide;
FUseYOrigin:=False;
end;
Function TVolumeSeries.GetVolumeValues:TChartValueList;
Begin
result:=YValues;
end;
Procedure TVolumeSeries.SetSeriesColor(AColor:TColor);
begin
inherited;
LinePen.Color:=AColor;
end;
Procedure TVolumeSeries.SetVolumeValues(Value:TChartValueList);
Begin
SetYValues(Value);
end;
Procedure TVolumeSeries.PrepareCanvas(Forced:Boolean; AColor:TColor);
begin
if Forced or (AColor<>IColor) then
begin
ParentChart.Canvas.AssignVisiblePenColor(LinePen,AColor);
ParentChart.Canvas.BackMode:=cbmTransparent;
IColor:=AColor;
end;
end;
procedure TVolumeSeries.DrawValue(ValueIndex:Integer);
var tmpY : Integer;
Begin
PrepareCanvas(ValueIndex=FirstDisplayedIndex, ValueColor[ValueIndex]);
{ moves to x,y coordinates and draws a vertical bar to top or bottom,
depending on the vertical Axis.Inverted property }
if UseYOrigin then
tmpY:=CalcYPosValue(YOrigin) { 5.02 }
else
With GetVertAxis do
if Inverted then tmpY:=IStartPos else tmpY:=IEndPos;
with ParentChart,Canvas do
if View3D then
VertLine3D(CalcXPos(ValueIndex),CalcYPos(ValueIndex),tmpY,MiddleZ)
else
DoVertLine(CalcXPos(ValueIndex),tmpY,CalcYPos(ValueIndex)); { 5.02 }
end;
Function TVolumeSeries.NumSampleValues:Integer;
Begin
result:=40;
end;
Procedure TVolumeSeries.AddSampleValues(NumValues:Integer; OnlyMandatory:Boolean=False);
Var t : Integer;
s : TSeriesRandomBounds;
begin
s:=RandomBounds(NumValues);
with s do
for t:=1 to NumValues do
Begin
AddXY(tmpX,RandomValue(Round(DifY) div 15));
tmpX:=tmpX+StepX;
end;
end;
Procedure TVolumeSeries.PrepareForGallery(IsEnabled:Boolean);
begin
inherited;
FillSampleValues(26);
Pointer.InflateMargins:=True;
end;
class Function TVolumeSeries.GetEditorClass:String;
Begin
result:='TVolumeSeriesEditor';
End;
class procedure TVolumeSeries.CreateSubGallery(
AddSubChart: TChartSubGalleryProc);
begin
inherited;
AddSubChart(TeeMsg_Dotted);
AddSubChart(TeeMsg_Colors);
AddSubChart(TeeMsg_Origin); { 5.02 }
end;
class procedure TVolumeSeries.SetSubGallery(ASeries: TChartSeries;
Index: Integer);
begin
With TVolumeSeries(ASeries) do
Case Index of
1: Pen.SmallDots:=True;
2: ColorEachPoint:=True;
3: UseYOrigin:=True;
else inherited
end;
end;
procedure TVolumeSeries.DrawLegendShape(ValueIndex: Integer; { 5.01 }
const Rect: TRect);
begin
With Rect do ParentChart.Canvas.DoHorizLine(Left,Right,(Top+Bottom) div 2);
end;
procedure TVolumeSeries.Assign(Source: TPersistent);
begin
if Source is TVolumeSeries then
with TVolumeSeries(Source) do
begin
Self.FUseYOrigin:= UseYOrigin;
Self.FOrigin := YOrigin;
end;
inherited;
end;
procedure TVolumeSeries.SetOrigin(const Value: Double);
begin
SetDoubleProperty(FOrigin,Value);
end;
procedure TVolumeSeries.SetUseOrigin(const Value: Boolean);
begin
SetBooleanProperty(FUseYOrigin,Value);
end;
procedure TVolumeSeries.PrepareLegendCanvas(ValueIndex: Integer;
var BackColor: TColor; var BrushStyle: TBrushStyle);
begin
PrepareCanvas(True,SeriesColor);
end;
{ TADXFunction }
type TChartSeriesAccess=class(TChartSeries);
Constructor TADXFunction.Create(AOwner: TComponent);
Procedure HideSeries(ASeries:TChartSeries);
begin
ASeries.ShowInLegend:=False;
TChartSeriesAccess(ASeries).InternalUse:=True;
end;
begin
inherited;
InternalSetPeriod(14);
SingleSource:=True;
HideSourceList:=True;
IDMDown:=TFastLineSeries.Create(Self);
HideSeries(IDMDown);
IDMDown.SeriesColor:=clRed;
IDMUp:=TFastLineSeries.Create(Self);
HideSeries(IDMUp);
IDMUp.SeriesColor:=clGreen;
end;
procedure TADXFunction.AddPoints(Source: TChartSeries);
Procedure PrepareSeries(ASeries:TChartSeries);
begin
With ASeries do
begin
ParentChart:=ParentSeries.ParentChart;
CustomVertAxis:=ParentSeries.CustomVertAxis;
VertAxis:=ParentSeries.VertAxis;
XValues.DateTime:=ParentSeries.XValues.DateTime;
AfterDrawValues:=ParentSeries.AfterDrawValues;
BeforeDrawValues:=ParentSeries.BeforeDrawValues;
end;
end;
Function CalcADX(Index:Integer):Double;
begin
Index:=Index-Round(Period);
result:=(100*Abs(IDMUp.YValues.Value[Index]-IDMDown.YValues.Value[Index])/
(IDMUp.YValues.Value[Index]+IDMDown.YValues.Value[Index]));
end;
var tmpTR,
tmpDMUp,
tmpDMDown : Array of Double;
t : Integer;
tt : Integer;
tmpClose : Double;
Closes,
Highs,
Lows : TChartValueList;
tmpTR2,
tmpUp2,
tmpDown2 : Double;
tmpX : Double;
tmp : Integer;
tmpADX : Double;
begin
if Period<2 then Exit; // 5.03
ParentSeries.Clear;
IDMUp.Clear;
IDMDown.Clear;
PrepareSeries(IDMUp);
PrepareSeries(IDMDown);
if Source.Count>=(2*Period) then
begin
With TOHLCSeries(Source) do
begin
Closes:=CloseValues;
Highs:=HighValues;
Lows:=LowValues;
end;
SetLength(tmpTR, Source.Count);
SetLength(tmpDMUp, Source.Count);
SetLength(tmpDMDown, Source.Count);
for t:=1 to Source.Count-1 do
begin
tmpClose:=Closes.Value[t-1];
tmpTR[t]:=Highs.Value[t]-Lows.Value[t];
tmpTR[t]:=Math.Max(tmpTR[t],Abs(Highs.Value[t]-tmpClose));
tmpTR[t]:=Math.Max(tmpTR[t],Abs(Lows.Value[t]-tmpClose));
if (Highs.Value[t]-Highs.Value[t-1])>(Lows.Value[t-1]-Lows.Value[t]) then
tmpDMUp[t]:=Math.Max(0,Highs.Value[t]-Highs.Value[t-1])
else
tmpDMUp[t]:=0;
if (Lows.Value[t-1]-Lows.Value[t])>(Highs.Value[t]-Highs.Value[t-1]) then
tmpDMDown[t]:=Math.Max(0,Lows.Value[t-1]-Lows.Value[t])
else
tmpDMDown[t]:=0;
end;
tmpTR2:=0;
tmpUp2:=0;
tmpDown2:=0;
tmp:=Round(Period);
for t:=tmp to Source.Count-1 do
begin
if t=tmp then
begin
for tt:=1 to Round(Period) do
begin
tmpTR2 :=tmpTR2+tmpTR[tt];
tmpUp2 :=tmpUp2+tmpDMUp[tt];
tmpDown2:=tmpDown2+tmpDMDown[tt];
end;
end
else
begin
tmpTR2:=tmpTR2-(tmpTR2/Period)+tmpTR[t];
tmpUp2:=tmpUp2-(tmpUp2/Period)+tmpDMUp[t];
tmpDown2:=tmpDown2-(tmpDown2/Period)+tmpDMDown[t];
end;
tmpX:=Source.XValues[t];
IDMUp.AddXY( tmpX, 100*(tmpUp2/tmpTR2));
IDMDown.AddXY( tmpX, 100*(tmpDown2/tmpTR2));
end;
tmpTR:=nil;
tmpDMUp:=nil;
tmpDMDown:=nil;
tmpADX:=0;
tmp:=Round((2*Period)-2);
for t:=tmp to Source.Count-1 do
begin
if t=tmp then
begin
tmpADX:=0;
for tt:=Round(Period) to tmp do tmpADX:=tmpADX+CalcADX(tt);
tmpADX:=tmpADX/(Period-1);
end
else
begin
tmpADX:=((tmpADX*(Period-1))+(CalcADX(t)))/Period;
end;
ParentSeries.AddXY(Source.XValues[t],tmpADX);
end;
end;
end;
Destructor TADXFunction.Destroy; { 5.01 }
begin
DMDown.Free;
DMUp.Free;
inherited;
end;
class function TADXFunction.GetEditorClass: String;
begin
result:='TADXFuncEditor';
end;
function TADXFunction.IsValidSource(Value: TChartSeries): Boolean;
begin
result:=Value is TOHLCSeries;
end;
function TADXFunction.GetDownPen: TChartPen;
begin
result:=DMDown.Pen;
end;
function TADXFunction.GetUpPen: TChartPen;
begin
result:=DMUp.Pen;
end;
procedure TADXFunction.SetDownPen(const Value: TChartPen);
begin
DMDown.Pen:=Value;
end;
procedure TADXFunction.SetUpPen(const Value: TChartPen);
begin
DMUp.Pen:=Value;
end;
{ R.S.I. }
Constructor TRSIFunction.Create(AOwner: TComponent);
begin
inherited;
FStyle:=rsiOpenClose;
SingleSource:=True;
HideSourceList:=True;
end;
Function TRSIFunction.Calculate( Series:TChartSeries;
FirstIndex,LastIndex:Integer):Double;
var NumPoints : Integer;
t : Integer;
tmpClose : Double;
Ups : Double;
Downs : Double;
Begin
if ISeries<>Series then
begin // Cache lists during calculation
Closes:=Series.GetYValueList('CLOSE');
Opens :=Series.GetYValueList('OPEN');
ISeries:=Series;
end;
Ups:=0;
Downs:=0;
With Series do
Begin
if Self.Style=rsiOpenClose then
begin // use today Close and Open prices (do not use "yesterday" close)
for t:=FirstIndex to LastIndex do
Begin
tmpClose:=Closes.Value[t];
if Opens.Value[t]>tmpClose then Downs:=Downs+tmpClose
else Ups :=Ups +tmpClose;
end;
end
else
begin // Use Close prices (today - yesterday)
for t:=FirstIndex+1 to LastIndex do
Begin
tmpClose:=Closes.Value[t]-Closes.Value[t-1];
if tmpClose<0 then Downs:=Downs-tmpClose
else Ups :=Ups +tmpClose;
end;
end;
end;
{ Calculate RSI }
NumPoints:=(LastIndex-FirstIndex)+1;
Downs:=Downs/NumPoints;
Ups :=Ups /NumPoints;
if Downs<>0 then
Begin
result:=100.0 - ( 100.0 / ( 1.0+Abs(Ups/Downs) ) );
if result<0 then result:=0 else
if result>100 then result:=100;
end
else result:=100; // Special case, to avoid divide by zero
end;
// R.S.I. function needs an OHLC series values to calculate.
function TRSIFunction.IsValidSource(Value: TChartSeries): Boolean;
begin
result:=Value is TOHLCSeries;
end;
procedure TRSIFunction.SetStyle(const Value: TRSIStyle);
begin
if Style<>Value then
begin
FStyle:=Value;
ReCalculate;
end;
end;
initialization
RegisterTeeSeries( TCandleSeries, {$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryCandle,
{$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryFinancial, 1);
RegisterTeeSeries( TVolumeSeries, {$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryVolume,
{$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryFinancial, 1);
RegisterTeeFunction( TADXFunction, {$IFNDEF CLR}@{$ENDIF}TeeMsg_FunctionADX,
{$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryFinancial );
RegisterTeeFunction( TRSIFunction, {$IFNDEF CLR}@{$ENDIF}TeeMsg_FunctionRSI,
{$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryFinancial );
finalization
UnRegisterTeeSeries([TCandleSeries,TVolumeSeries]);
UnRegisterTeeFunctions([ TADXFunction,TRSIFunction ]);
end.
|
unit pka4058a3;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Grids, DBGrids, OnEditBaseCtrl, OnEditStdCtrl, OnEditBtnCtrl,
OnEditCombo, ComCtrls, StdCtrls, OnFocusButton, OnLineLabel, ExtCtrls,
OnScheme, OnShapeLabel, OnGrDBGrid, CheckLst, OnListbox, DBCtrls, Db,
OnMemDataset, Tmax_DataSetText, OnInsaCommon, Tmax_DmlSet, TmaxFunc,
OnEditMemo;
type
TFM_ConForm = class(TForm)
Panel1: TPanel;
PA_Buttons: TPanel;
BT_Comfirm: TOnFocusButton;
BT_Exit: TOnFocusButton;
Label_YYMM: TOnSectionLabel;
GGrid2: TOnGrDbGrid;
Label3: TLabel;
DataSource2: TDataSource;
TDS_GRID2: TTMaxDataSet;
BT_Return: TOnFocusButton;
Panel2: TPanel;
L_korname: TOnShapeLabel;
L_empno: TOnShapeLabel;
l_CancelSayu: TOnMemo;
l_ReturnSayu: TOnMemo;
SB_Help: TStatusBar;
L_Regfrdate: TOnShapeLabel;
L_Regtodate: TOnShapeLabel;
L_REGYEARLY_CNT: TOnShapeLabel;
L_APPDATE: TOnShapeLabel;
TDS_DML: TTMaxDataSet;
Label1: TLabel;
OnGrDbGrid1: TOnGrDbGrid;
DataSource1: TDataSource;
TDS_GRID1: TTMaxDataSet;
procedure BT_ExitClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure BT_ComfirmClick(Sender: TObject);
procedure GGrid1ApplyCellAttribute(Sender: TObject; Field: TField;
Canvas: TCanvas; Rect: TRect; State: TGridDrawState);
procedure GGrid1CellClick(Column: TColumn);
procedure PL_Com_Contructor;
procedure ConRetrieve;
procedure GGrid1DblClick(Sender: TObject);
procedure GGrid2ApplyCellAttribute(Sender: TObject; Field: TField;
Canvas: TCanvas; Rect: TRect; State: TGridDrawState);
procedure DataSource2DataChange(Sender: TObject; Field: TField);
procedure BT_ReturnClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
FG_duyymm : String;
FG_deptcode : String;
FG_LastDay : String;
Day_Qry1 : String;
Day_Qry2 : String;
function PL_ConProcess_Yearly : Boolean;
end;
var
FM_ConForm: TFM_ConForm;
implementation
uses pka4058a0;
{$R *.DFM}
procedure TFM_ConForm.BT_ExitClick(Sender: TObject);
begin
Close;
end;
procedure TFM_ConForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := CaFree;
end;
procedure TFM_ConForm.FormCreate(Sender: TObject);
var
i,j : integer;
begin
Label_YYMM.Caption := '결재기준년월 : '+copy(FM_Main.GSdate,1,4)+'년 '+copy(FM_Main.GSdate,5,2)+'월';
ConRetrieve;
end;
procedure TFM_ConForm.PL_Com_Contructor;
begin
with TDS_GRID2 do
begin
Close;
ServiceName := 'HINSA_select';
ClearFieldInfo;
AddField('field1' , ftString, 100);
AddField('field2' , ftString, 100);
AddField('field3' , ftString, 100);
AddField('field4' , ftString, 100);
AddField('field5' , ftString, 100);
Sql.Clear;
end;
end;
//미등록자 리스트.
procedure TFM_ConForm.ConRetrieve;
var
FL_Sql : String;
i,j : Integer;
Field : TField;
begin
with TDS_GRID1 do
begin
ServiceName := 'PKA4058A_sel1';
Close;
Sql.Clear;
SQL.Add('SELECT APPDATE, ');
SQL.Add(' EMPNO, ');
SQL.Add(' KORNAME, ');
SQL.Add(' (SELECT PAYRA FROM PIMPMAS WHERE A.EMPNO =EMPNO) PAYRA, ');
SQL.Add(' MOD_FLAG, ');
SQL.Add(' DECODE(UPPER(MOD_FLAG),''I'',''추가'',''M'',''수정'',''D'',''취소'','''') MOD_NAME, ');
SQL.Add(' REGFRDATE, ');
SQL.Add(' REGTODATE, ');
SQL.Add(' nvl(REGYEARLY_CNT,0), ');
SQL.Add(' REGFRDATE2, ');
SQL.Add(' REGTODATE2, ');
SQL.Add(' nvl(REGYEARLY_CNT2,0), ');
SQL.Add(' MODFRDATE, ');
SQL.Add(' MODTODATE, ');
SQL.Add(' nvl(MODYEARLY_CNT,0), ');
SQL.Add(' MODFRDATE2, ');
SQL.Add(' MODTODATE2, ');
SQL.Add(' nvl(MODYEARLY_CNT2,0), ');
SQL.Add(' DUTYCODE, ');
//2014.11.03.hjku. 삭제 추가로 화면 표기 일부 변경...
//SQL.Add(' (SELECT CODENAME FROM PYCCODE WHERE CODEID =''Y112'' AND A.DUTYCODE=CODENO) DUTYNAME, ');
SQL.Add(' CASE WHEN MOD_FLAG<>''D'' THEN (SELECT CODENAME FROM PYCCODE WHERE CODEID =''Y112'' AND A.DUTYCODE=CODENO) ELSE '''' END DUTYNAME, ');
SQL.Add(' NVL(CON_YN,''N''), ');
SQL.Add(' CASE WHEN MOD_FLAG=''D'' THEN decode(NVL(CON_YN,''N''),''Y'',''결재'',''R'',''반려'',''미결재'') ELSE '''' END, ');
SQL.Add(' CANCELSAYU, ');
SQL.Add(' RETURNSAYU ');
SQL.Add(' FROM PKYEARLYMODIFY A ');
Sql.Add( 'WHERE REGFRDATE LIKE '''+ FM_Main.GSYear + '%'' ');
Sql.Add( ' AND NVL(CON_YN,''N'')<>''N'' ');
Sql.Add( ' AND MOD_FLAG =''D'' ');
if(FM_Main.All_Flag) then
Sql.Add( ' AND EXISTS(SELECT 1 FROM PIMEEMP WHERE a.empno = empno and EEMPNO ='''+FM_Main.GSConEmpno+''') ')
else Sql.Add( ' AND EXISTS(SELECT 1 FROM PIMEEMP WHERE a.empno = empno and EEMPNO ='''+FM_Main.GSempno+''') ');
Sql.Add( ' ORDER BY EMPNO,APPDATE, WRITETIME, MOD_FLAG, REGFRDATE ');
ClearFieldInfo;
//2016.12.19.hjku.. 연차휴가 등록취소 시행.. 김진호M 요청
//AddField('APPDATE' , ftString, 8);
AddField('APPDATE' , ftString, 16);
AddField('EMPNO' , ftString, 4);
AddField('KORNAME' , ftString, 12);
AddField('PAYRA' , ftString, 3);
AddField('MOD_FLAG' , ftString, 1);
AddField('MOD_NAME' , ftString, 4);
AddField('REGFRDATE' , ftString, 8);
AddField('REGTODATE' , ftString, 8);
AddField('REGYEARLY_CNT' , ftString, 10);
AddField('REGFRDATE2' , ftString, 8);
AddField('REGTODATE2' , ftString, 8);
AddField('REGYEARLY_CNT2' , ftString, 10);
AddField('MODFRDATE' , ftString, 8);
AddField('MODTODATE' , ftString, 8);
AddField('MODYEARLY_CNT' , ftString, 10);
AddField('MODFRDATE2' , ftString, 8);
AddField('MODTODATE2' , ftString, 8);
AddField('MODYEARLY_CNT2' , ftString, 10);
AddField('DUTYCODE' , ftString, 2);
AddField('DUTYNAME' , ftString, 20);
AddField('CON_YN' , ftString, 1);
AddField('CONYNNAME' , ftString, 10);
AddField('CANCELSAYU' , ftString, 200);
AddField('RETURNSAYU' , ftString, 200);
//memo1.text := sql.text;
Open;
{if TDS_GRID1.RecordCount < 1 then
begin
//MessageDlg('조회 조건에 맞는 연차휴가 변경내역이 존재하지 않습니다.',mtInformation,[mbOK],0);
SB_help.Panels[1].Text := '조회 조건에 맞는 연차휴가 변경내역이 존재하지 않습니다.';
System.Exit;
end;
}
end;
with TDS_GRID2 do
begin
ServiceName := 'PKA4058A_sel1';
Close;
Sql.Clear;
SQL.Add('SELECT APPDATE, ');
SQL.Add(' EMPNO, ');
SQL.Add(' KORNAME, ');
SQL.Add(' (SELECT PAYRA FROM PIMPMAS WHERE A.EMPNO =EMPNO) PAYRA, ');
SQL.Add(' MOD_FLAG, ');
SQL.Add(' DECODE(UPPER(MOD_FLAG),''I'',''추가'',''M'',''수정'',''D'',''취소'','''') MOD_NAME, ');
SQL.Add(' REGFRDATE, ');
SQL.Add(' REGTODATE, ');
SQL.Add(' nvl(REGYEARLY_CNT,0), ');
SQL.Add(' REGFRDATE2, ');
SQL.Add(' REGTODATE2, ');
SQL.Add(' nvl(REGYEARLY_CNT2,0), ');
SQL.Add(' MODFRDATE, ');
SQL.Add(' MODTODATE, ');
SQL.Add(' nvl(MODYEARLY_CNT,0), ');
SQL.Add(' MODFRDATE2, ');
SQL.Add(' MODTODATE2, ');
SQL.Add(' nvl(MODYEARLY_CNT2,0), ');
SQL.Add(' DUTYCODE, ');
//2014.11.03.hjku. 삭제 추가로 화면 표기 일부 변경...
//SQL.Add(' (SELECT CODENAME FROM PYCCODE WHERE CODEID =''Y112'' AND A.DUTYCODE=CODENO) DUTYNAME, ');
SQL.Add(' CASE WHEN MOD_FLAG<>''D'' THEN (SELECT CODENAME FROM PYCCODE WHERE CODEID =''Y112'' AND A.DUTYCODE=CODENO) ELSE '''' END DUTYNAME, ');
SQL.Add(' NVL(CON_YN,''N''), ');
SQL.Add(' CASE WHEN MOD_FLAG=''D'' THEN decode(NVL(CON_YN,''N''),''Y'',''결재'',''R'',''반려'',''미결재'') ELSE '''' END, ');
SQL.Add(' CANCELSAYU, ');
SQL.Add(' RETURNSAYU ');
SQL.Add(' FROM PKYEARLYMODIFY A ');
Sql.Add( 'WHERE REGFRDATE LIKE '''+ FM_Main.GSYear + '%'' ');
Sql.Add( ' AND NVL(CON_YN,''N'')=''N'' ');
Sql.Add( ' AND MOD_FLAG =''D'' ');
//Sql.Add( ' AND EXISTS(SELECT 1 FROM PIMEEMP WHERE a.empno = empno and EEMPNO ='''+FM_Main.GSConEmpno+''') ');
if(FM_Main.All_Flag) then
Sql.Add( ' AND EXISTS(SELECT 1 FROM PIMEEMP WHERE a.empno = empno and EEMPNO ='''+FM_Main.GSConEmpno+''') ')
else Sql.Add( ' AND EXISTS(SELECT 1 FROM PIMEEMP WHERE a.empno = empno and EEMPNO ='''+FM_Main.GSempno+''') ');
Sql.Add( 'ORDER BY EMPNO,APPDATE, WRITETIME, MOD_FLAG, REGFRDATE ');
ClearFieldInfo;
//2016.12.19.hjku.. 연차휴가 등록취소 시행.. 김진호M 요청
//AddField('APPDATE' , ftString, 8);
AddField('APPDATE' , ftString, 16);
AddField('EMPNO' , ftString, 4);
AddField('KORNAME' , ftString, 12);
AddField('PAYRA' , ftString, 3);
AddField('MOD_FLAG' , ftString, 1);
AddField('MOD_NAME' , ftString, 4);
AddField('REGFRDATE' , ftString, 8);
AddField('REGTODATE' , ftString, 8);
AddField('REGYEARLY_CNT' , ftString, 10);
AddField('REGFRDATE2' , ftString, 8);
AddField('REGTODATE2' , ftString, 8);
AddField('REGYEARLY_CNT2' , ftString, 10);
AddField('MODFRDATE' , ftString, 8);
AddField('MODTODATE' , ftString, 8);
AddField('MODYEARLY_CNT' , ftString, 10);
AddField('MODFRDATE2' , ftString, 8);
AddField('MODTODATE2' , ftString, 8);
AddField('MODYEARLY_CNT2' , ftString, 10);
AddField('DUTYCODE' , ftString, 2);
AddField('DUTYNAME' , ftString, 20);
AddField('CON_YN' , ftString, 1);
AddField('CONYNNAME' , ftString, 10);
AddField('CANCELSAYU' , ftString, 200);
AddField('RETURNSAYU' , ftString, 200);
//memo2.text := sql.text;
Open;
if TDS_GRID2.RecordCount < 1 then
begin
//MessageDlg('조회 조건에 맞는 연차휴가 변경내역이 존재하지 않습니다.',mtInformation,[mbOK],0);
SB_help.Panels[1].Text := '조회 조건에 맞는 연차휴가 변경내역이 존재하지 않습니다.';
System.Exit;
end;
end;
end;
procedure TFM_ConForm.BT_ComfirmClick(Sender: TObject);
var
FL_Date: String;
FL_Date2: String;
FL_Date3: Real;
CmdStr,vProgId, vRundate,vMessage : String;
update_list, insert_list, column_list :string;
yearly_cnt, yearlyplan_cnt, used_yearly_cnt, notice_yn, assign_yn :String;
begin
if TDS_Grid2.FieldbyName('APPDATE').AsString = '' then
begin
MessageDlg('선택 된 자료가 없습니다.', mtInformation, [mbok], 0) ;
System.exit;
end;
if TDS_Grid2.FieldbyName('Con_Yn').AsString <> 'N' then
begin
MessageDlg('결재처리된 자료입니다.', mtInformation, [mbok], 0) ;
System.exit;
end;
if MessageBox(FM_ConForm.HANDLE,'승인 하시겠습니까?','승인확인',MB_YESNO) = IDYES then
begin
if not PL_ConProcess_Yearly then
begin
//MessageDlg('연차기간 변경 값이 신청시와 달라졌습니다. HR팀에 문의하시기 바랍니다.', mtInformation, [mbok], 0) ;
System.exit;
end;
with TDS_DML do
begin
ServiceName := 'PKA4040A_dml';
Close;
Sql.Clear ;
Sql.Add ('UPDATE PKYEARLYMODIFY ');
Sql.Add (' SET CON_YN =''Y'', ');
Sql.Add (' CONEMPNO = '''+ FM_Main.GSempno + ''', ');
Sql.Add (' CONTIME = TO_CHAR(SYSDATE,''YYYYMMDDHH24MISS'') ');
Sql.Add ('WHERE APPDATE = ''' + TDS_Grid2.FieldbyName('APPDATE').AsString + ''' ');
Sql.Add (' AND EMPNO = ''' + TDS_Grid2.FieldbyName('EMPNO').AsString + ''' ');
Sql.Add (' AND REGFRDATE = ''' + TDS_Grid2.FieldbyName('REGFRDATE').AsString + ''' ');
Sql.Add (' AND REGTODATE = ''' + TDS_Grid2.FieldbyName('REGTODATE').AsString + ''' ');
//memo1.text := sql.text;
if Execute then
begin
FM_Main.SendProgID := 'PKA4058A';
FM_Main.SendEmpno := FM_Main.GsEmpno;
FM_Main.RcveEmpno := L_empno.ValueCaption;
FM_Main.ReceiveYN := 'N';
FM_Main.MailSubject := '[연차휴가 사용 취소 승인] 요청 문서가 결재되었습니다.';
FM_Main.MailBody := L_korname.ValueCaption
+ FM_Main.Get_JobName(TDS_Grid2.FieldbyName('PAYRA').AsString)
+ '의 연차휴가 사용계획 취소 요청이 결재되었습니다. '; //메일내용
if FM_Main.Send_WebHint(FM_Main.SendProgID, FM_Main.SendEmpno, FM_Main.RcveEmpno, FM_Main.MailSubject, FM_Main.MailBody, FM_Main.ReceiveYN) then
MessageDlg('연차휴가 사용계획 취소 결재 메일 전송이 성공 하였습니다...',mtInformation, [mbOk], 0)
else
begin
MessageDlg('연차휴가 사용계획 취소 결재 메일 전송이 실패 하였습니다...',mtError, [mbOk], 0);
exit;
end;
end
else
begin
Application.MessageBox('결재처리에 실패했습니다.','작업실패',MB_OK);
Exit;
end;
end;
end;
ConRetrieve;
// SB_Help.Panels[1].Text := '결제 되었습니다... ';
end;
procedure TFM_ConForm.GGrid1ApplyCellAttribute(Sender: TObject;
Field: TField; Canvas: TCanvas; Rect: TRect; State: TGridDrawState);
begin
if (TOnGrDbGrid(Sender).SelectedRows.CurrentRowSelected) then
Canvas.Brush.Color := $00FF9B9B;
end;
procedure TFM_ConForm.GGrid1CellClick(Column: TColumn);
begin
{ if not MD_Data1.Active then
begin
MD_Data1.Open;
end;
if Length(GGrid1.SelectedField.DisplayText) = 4 then
begin
MD_Data1.Append;
MD_Data1.FieldByName('empno').AsString := GGrid1.SelectedField.DisplayText;
MD_Data1.Post;
end;
}
end;
procedure TFM_ConForm.GGrid1DblClick(Sender: TObject);
begin
{
with FM_Main do
begin
ED_empno.OnReadEnded := nil;
ED_empno.text := GGrid1.SelectedField.DisplayText;
FG_empdate := ED_empno.empdate;
if ED_dept.Enabled then
begin
ED_dept.Text := ED_empno.deptname;
ED_dept.Hint := ED_empno.jobdept;
end;
PL_Month_Contructor;
// ED_empno.PL_get_singledata;
end;
Close;
}
end;
procedure TFM_ConForm.GGrid2ApplyCellAttribute(Sender: TObject;
Field: TField; Canvas: TCanvas; Rect: TRect; State: TGridDrawState);
begin
if (TOnGrDbGrid(Sender).SelectedRows.CurrentRowSelected) then
Canvas.Brush.Color := $00FF9B9B;
end;
procedure TFM_ConForm.DataSource2DataChange(Sender: TObject;
Field: TField);
begin
with TDS_GRID2 do
begin
L_APPDATE.ValueCaption := Copy(FieldByName('APPDATE').AsString,1,4) + '-' +
Copy(FieldByName('APPDATE').AsString,5,2) + '-' +
Copy(FieldByName('APPDATE').AsString,7,2);
L_empno.ValueCaption := FieldByName('empno').AsString;
L_korname.ValueCaption := FieldByName('korname').AsString;
L_Regfrdate.ValueCaption := Copy(FieldByName('Regfrdate').AsString,1,4) + '-' +
Copy(FieldByName('Regfrdate').AsString,5,2) + '-' +
Copy(FieldByName('Regfrdate').AsString,7,2);
L_Regtodate.ValueCaption := Copy(FieldByName('Regtodate').AsString,1,4) + '-' +
Copy(FieldByName('Regtodate').AsString,5,2) + '-' +
Copy(FieldByName('Regtodate').AsString,7,2);
L_REGYEARLY_CNT.ValueCaption := FieldByName('REGYEARLY_CNT').AsString;
l_CancelSayu.text := FieldByName('CANCELSAYU').AsString;
l_ReturnSayu.text := FieldByName('RETURNSAYU').AsString;
end;
end;
procedure TFM_ConForm.BT_ReturnClick(Sender: TObject);
begin
if(TDS_GRID2.FieldByName('empno').AsString='') then
begin
MessageDlg('결재할 자료가 없습니다.',mtInformation, [mbOk], 0);
exit;
end;
l_ReturnSayu.text := FM_Main.RemoveSpecialChar(l_ReturnSayu.text);
if(l_ReturnSayu.text='') then
begin
MessageDlg('반려사유를 입력해 주세요!!',mtInformation, [mbOk], 0);
l_ReturnSayu.SetFocus();
exit;
end;
if TDS_GRID2.FieldbyName('Con_Yn').AsString <> 'N' then
begin
MessageDlg('결재처리된 자료입니다.', mtInformation, [mbok], 0) ;
System.exit;
end;
if MessageBox(FM_ConForm.HANDLE,'반려 하시겠습니까?','반려확인',MB_YESNO) = IDYES then
begin
with TDS_DML do
begin
ServiceName := 'PKA4040A_dml';
Close;
Sql.Clear ;
Sql.Add ('UPDATE PKYEARLYMODIFY ');
Sql.Add (' SET CON_YN =''R'', ');
Sql.Add (' CONEMPNO = '''+ FM_Main.GSempno + ''', ');
Sql.Add (' RETURNSAYU = '''+ l_ReturnSayu.text + ''', ');
Sql.Add (' CONTIME = TO_CHAR(SYSDATE,''YYYYMMDDHH24MISS'') ');
Sql.Add ('WHERE APPDATE = ''' + TDS_Grid2.FieldbyName('APPDATE').AsString + ''' ');
Sql.Add (' AND EMPNO = ''' + TDS_Grid2.FieldbyName('EMPNO').AsString + ''' ');
Sql.Add (' AND REGFRDATE = ''' + TDS_Grid2.FieldbyName('REGFRDATE').AsString + ''' ');
Sql.Add (' AND REGTODATE = ''' + TDS_Grid2.FieldbyName('REGTODATE').AsString + ''' ');
if Execute then
begin
FM_Main.SendProgID := 'PKA4058A';
FM_Main.SendEmpno := FM_Main.GsEmpno;
FM_Main.RcveEmpno := L_empno.ValueCaption;
FM_Main.ReceiveYN := 'N';
FM_Main.MailSubject := '[연차휴가 사용 승인] 요청 문서가 반려되었습니다.';
FM_Main.MailBody := L_korname.ValueCaption
+ FM_Main.Get_JobName(TDS_Grid2.FieldbyName('PAYRA').AsString)
+ '의 연차휴가 사용계획 취소 요청에 대한 승인이 반려되었습니다. '; //메일내용
if FM_Main.Send_WebHint(FM_Main.SendProgID, FM_Main.SendEmpno, FM_Main.RcveEmpno, FM_Main.MailSubject, FM_Main.MailBody, FM_Main.ReceiveYN) then
MessageDlg('연차휴가 사용계획 반려 메일 전송이 성공 하였습니다...',mtInformation, [mbOk], 0)
else
begin
MessageDlg('연차휴가 사용계획 반려 메일 전송이 실패 하였습니다...',mtError, [mbOk], 0);
exit;
end;
end
else
begin
Application.MessageBox('반려처리에 실패했습니다.','작업실패',MB_OK);
Exit;
end;
end;
end;
ConRetrieve;
SB_Help.Panels[1].Text := '결제 되었습니다... ';
end;
function TFM_ConForm.PL_ConProcess_Yearly : Boolean;
var
old_yearly_cnt, new_yearly_cnt : real;
tmp_Regcnt, tmp_Modcnt :real;
tmp_Korname : string;
tmp_appdate,tmp_Mod_Flag, tmp_Regfrdate, tmp_Regtodate, tmp_Modfrdate,tmp_Modtodate, tmp_modcode : String;
update_list, insert_list, column_list :string;
yearly_cnt, yearlyplan_cnt, used_yearly_cnt, notice_yn, assign_yn :String;
tmp_check_Regcnt :real;
begin
result := false;
with(TDS_Grid2) do
begin
tmp_Korname := FieldbyName('KORNAME').AsString;
tmp_Appdate := FieldbyName('APPDATE').AsString;
tmp_Mod_Flag := FieldbyName('MOD_FLAG').AsString;
tmp_Regfrdate := FieldbyName('REGFRDATE').AsString;
tmp_Regtodate := FieldbyName('REGTODATE').AsString;
tmp_Regcnt := FieldbyName('REGYEARLY_CNT').ASFloat;
tmp_Modfrdate := FieldbyName('MODFRDATE').AsString;
tmp_Modtodate := FieldbyName('MODTODATE').AsString;
tmp_Modcnt := FieldbyName('MODYEARLY_CNT').ASFloat;
tmp_Modcode := FieldbyName('DUTYCODE').AsString;
end;
//2016.12.19.hjku.. 2016년 연차휴가 등록취소 시행.. 김진호M 요청
//연차 사용 내역 재확인
FM_Main.PL_Select_Pkyearlt(FM_Main.GSYear,L_empno.valuecaption,yearly_cnt, yearlyplan_cnt, used_yearly_cnt, notice_yn, assign_yn);
//2016.12.19.hjku.. 최소 연차사용 갯수 체크.. 김진호M
tmp_check_Regcnt := strtofloat(used_yearly_cnt)- tmp_Regcnt;
if( tmp_check_Regcnt < 3) then
begin
MessageDlg('우리 회사는 구성원의 Work & Life Balance 제고를 위해,'+#13#10+
'‘연차휴가 사용촉진제(年 10일 사용 Guide)’를 시행하고 있습니다.'+#13#10#13#10+
tmp_Korname +'M는 ‘16년 사용 실적이 ‘매우 낮음’으로 확인됩니다.'+#13#10+
'따라서, 올해 최소 3개 이상의 연차는 꼭 사용하도록 독려해 주시기 바랍니다.', mtInformation, [mbok], 0) ;
SB_help.Panels[1].Text := '확인후에 등록 해 주세요..';
System.Exit;
end;
old_yearly_cnt := FM_Main.PL_Get_Duty_Cnt(L_empno.valuecaption,tmp_Regfrdate,tmp_Regtodate,'1') ;
if(old_yearly_cnt<> tmp_Regcnt) then
begin
MessageDlg('연차기간 변경 값이 신청시와 달라졌습니다. 반려처리하신후 다시 작성하셔야 합니다.', mtWarning, [mbok], 0) ;
result := false;
exit;
end;
if not FM_Main.Make_Query(L_empno.valuecaption,tmp_Regfrdate,tmp_Regtodate,tmp_Modcode, '1', update_list, insert_list, column_list) then
begin
MessageDlg('변경 쿼리 작성시 오류가 발생하였습니다.', mtWarning, [mbok], 0) ;
exit;
end;
if not FM_Main.Update_Query(L_empno.valuecaption,tmp_Regfrdate,tmp_Regtodate, '1', update_list, insert_list, column_list) then
begin
MessageDlg('취소 연차를 근태 반영시 오류가 발생하였습니다.', mtWarning, [mbok], 0) ;
exit;
end;
result := true;
end;
end.
|
unit winros_main;
interface
uses
Windows, Messages, SysUtils, Forms, Classes, Controls, StdCtrls;
type
pTickData = ^tTickData; // формат передаваемых данных
tTickData = packed record
pkttype : longint; // тип пакета? всегда 1
unknown0 : longint; // всегда 0
datetime : longint; // unixtime
price : double; // цена (value1)
unknown1 : longint; // всегда 0
quantity : double; // кол-во (value2)
unknown2 : longint; // всегда 0
name : array[0..$3F] of char; // тикер
end;
type
TForm1 = class(TForm)
ListBox1: TListBox;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ListBox1DblClick(Sender: TObject);
private
fMMFHandle : THandle;
public
procedure WMCopyData(var msg: TWMCopyData); message WM_COPYDATA;
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
function UnixTimeToDateTime(Value: Longword; InUTC: Boolean): TDateTime;
var Days : LongWord;
Hour : Word;
Min : Word;
Sec : Word;
tz : TTimeZoneInformation;
localtime : TSystemTime;
systemtime : TSystemTime;
begin
Days := Value div SecsPerDay;
Value := Value mod SecsPerDay;
Hour := Value div 3600;
Value := Value mod 3600;
Min := Value div 60;
Sec := Value mod 60;
result:= 25569 + Days + EncodeTime(Hour, Min, Sec, 0);
if InUTC then begin
GetTimeZoneInformation(tz);
DateTimeToSystemTime(result, systemtime);
SystemTimeToTzSpecificLocalTime(@tz, systemtime, localtime);
result:= SystemTimeToDateTime(localtime);
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
var pFileData : pChar;
begin
fMMFHandle:= CreateFileMapping(INVALID_HANDLE_VALUE, nil, PAGE_READWRITE, 0, sizeof(longint), 'WR_MM_MAP_0');
if (fMMFHandle <> 0) then begin
pFileData := MapViewOfFile(fMMFHandle, FILE_MAP_WRITE, 0, 0, 0);
if Assigned(pFileData) then try
pLongint(pFileData)^:= Self.Handle;
finally UnmapViewOfFile(pFileData); end;
end;
end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin if (fMMFHandle <> 0) then CloseHandle(fMMFHandle); end;
procedure TForm1.WMCopyData(var msg: TWMCopyData);
begin
if assigned(msg.CopyDataStruct) then with msg.CopyDataStruct^ do begin
case dwData of
$0067 : if (cbData = sizeof(tTickData)) then with pTickData(lpData)^ do
listbox1.Items.Add(format('%s %d %d %s %.4f %d %.0f %d',
[name, pkttype, unknown0,
FormatDateTime('DD/MM/YYYY HH:NN:SS', UnixTimeToDateTime(datetime, true)),
price, unknown1, quantity, unknown2]));
else listbox1.Items.Add(format('arrived packet id: %d datalen: %d', [dwData, cbData]));
end;
end;
end;
procedure TForm1.ListBox1DblClick(Sender: TObject);
begin listbox1.Items.Clear; end;
end.
|
unit SelectionInt;
interface
type
ISelection = interface(IUnknown)
['{91D2CF36-DC51-41F8-BF16-75355A6ABC27}']
procedure ClearSelection();
function GetHaveFocus: Boolean;
property HaveFocus: Boolean read GetHaveFocus;
end;
implementation
end.
|
unit BD.Kontakt;
interface
uses System.Classes, System.SysUtils, BD.Adresse, BD.Land;
type
IKontakt = interface
['{E8AE44F1-EC6E-466A-A378-E7437DFC9523}']
end;
TKontakt = class
private
FNavn: String;
FKlientID: Integer;
FKontaktnr: Integer;
FPAdresse: TAdresse;
FBAdresse: TAdresse;
protected
function GetKlientID: Integer;
function GetKontaktnr: Integer;
function GetNavn: String;
procedure SetKlientID(const Value: Integer);
procedure SetKontaktnr(const Value: Integer);
procedure SetNavn(const Value: String);
function GetBesokAdresse: TAdresse;
function GetPostAdresse: IAdresse;
public
constructor Create;
published
property Navn: String read GetNavn write SetNavn;
property KlientID: Integer read GetKlientID write SetKlientID;
property Kontaktnr: Integer read GetKontaktnr write SetKontaktnr;
property PostAdresse: IAdresse read GetPostAdresse;
property BesokAdresse: TAdresse read GetBesokAdresse;
end;
implementation
{ Kontakt }
constructor TKontakt.Create;
begin
FPAdresse := TAdresse.Create;
FBAdresse := TAdresse.Create;
end;
function TKontakt.GetBesokAdresse: TAdresse;
begin
Result := FBAdresse;
end;
function TKontakt.GetKlientID: Integer;
begin
Result := FKlientID;
end;
function TKontakt.GetKontaktnr: Integer;
begin
Result := FKontaktnr;
end;
function TKontakt.GetNavn: String;
begin
Result := FNavn;
end;
function TKontakt.GetPostAdresse: IAdresse;
begin
Result := FPAdresse;
end;
procedure TKontakt.SetKlientID(const Value: Integer);
begin
FKlientID := Value;
end;
procedure TKontakt.SetKontaktnr(const Value: Integer);
begin
FKontaktnr := Value;
end;
procedure TKontakt.SetNavn(const Value: String);
begin
FNavn := Value;
end;
end.
|
unit uPessoa;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DBXFirebird, Data.DB, Data.SqlExpr,
ZAbstractConnection, ZConnection, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.FB,
FireDAC.Phys.FBDef, FireDAC.VCLUI.Wait, FireDAC.Comp.Client, FireDAC.Phys.IB,
FireDAC.Phys.IBDef, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf,
FireDAC.DApt, FireDAC.Comp.DataSet, Vcl.StdCtrls, Vcl.Mask, Vcl.DBCtrls,
Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.Grids, Vcl.DBGrids, udmPrincipal;
type
TfrmPessoa = class(TForm)
dsPessoa: TDataSource;
pgPessoa: TPageControl;
tbConsulta: TTabSheet;
tbCadastro: TTabSheet;
Panel1: TPanel;
Panel2: TPanel;
Panel3: TPanel;
btIncluir: TButton;
btnEditar: TButton;
btnExluir: TButton;
btnFechar: TButton;
dbPessoa: TDBGrid;
lbProcurar: TLabel;
edtProcurar: TEdit;
tbPessoa: TFDQuery;
Panel4: TPanel;
Panel5: TPanel;
btnCancelar: TButton;
btnSalvar: TButton;
dbeNome: TDBEdit;
lbNome: TLabel;
procedure FormShow(Sender: TObject);
procedure btIncluirClick(Sender: TObject);
procedure btnFecharClick(Sender: TObject);
procedure btnEditarClick(Sender: TObject);
procedure btnExluirClick(Sender: TObject);
procedure edtProcurarChange(Sender: TObject);
procedure btnCancelarClick(Sender: TObject);
procedure btnSalvarClick(Sender: TObject);
private
function Sequencial: Integer;
procedure DeletePessoa(CodPessoa: string);
{ Private declarations }
public
{ Public declarations }
end;
var
frmPessoa: TfrmPessoa;
mensagem : word;
const
SQL_PROCURA_PESSOA = 'SELECT IDDONO, NOME FROM PESSOA WHERE UPPER(NOME) LIKE %S';
SQL_SEQUENCIA_NOVA = 'SELECT GEN_ID(GEN_PESSOA_ID, 1) as sequencia from RDB$DATABASE;';
SQL_DELETE_PESSOA = 'DELETE FROM PESSOA WHERE IDDONO = %S';
SQL_DELETE_CAO_PESSOA = 'DELETE FROM CAO_PESSOA WHERE IDDONO = %S AND IDCAO = %S';
SQL_DELETE_CAO = 'DELETE FROM CAO WHERE IDCAO = %S';
SQL_RETORNA_CAO = 'SELECT IDCAO FROM CAO_PESSOA WHERE IDDONO = %S';
implementation
{$R *.dfm}
procedure TfrmPessoa.btIncluirClick(Sender: TObject);
begin
tbPessoa.CachedUpdates := True;
tbPessoa.Open;
tbPessoa.Insert;
tbCadastro.TabVisible := True;
pgPessoa.ActivePage := tbCadastro;
end;
procedure TfrmPessoa.btnCancelarClick(Sender: TObject);
begin
if tbPessoa.State in [dsInsert, dsEdit] then
begin
tbPessoa.Cancel;
pgPessoa.ActivePage := tbConsulta;
tbCadastro.TabVisible := false;
end;
end;
procedure TfrmPessoa.btnEditarClick(Sender: TObject);
begin
tbPessoa.Edit;
tbCadastro.TabVisible := True;
pgPessoa.ActivePage := tbCadastro;
end;
procedure TfrmPessoa.btnExluirClick(Sender: TObject);
begin
mensagem:= Messagebox(Handle, 'Deseja Realmente Excluir este Registro?', 'Informação', Mb_yesno or mb_iconinformation);
If mensagem = IDYes then
begin
if not(dmPrincipal.Connection.InTransaction) then
dmPrincipal.Connection.StartTransaction;
try
DeletePessoa(dbPessoa.Columns.Items[0].Field.AsString);
dmPrincipal.Connection.Commit;
except
on E:Exception do
begin
Showmessage('Ocorreu um erro de banco de dados! '+'Erro ao excluir registro '+#13+
'Detalhe: '+E.Message);
dmPrincipal.Connection.Rollback;
Exit;
end;
end;
end;
end;
procedure TfrmPessoa.btnFecharClick(Sender: TObject);
begin
if tbPessoa.State in [dsInsert,dsEdit] then
begin
Application.MessageBox('Atualização/Inserção deve ser concluída, antes de Fechar!', 'Alerta - Aviso do Sistema', mb_iconwarning+mb_ok);
abort;
end
else
Close;
end;
procedure TfrmPessoa.btnSalvarClick(Sender: TObject);
begin
tbPessoa.FieldByName('IDDONO').AsInteger := Sequencial;
tbPessoa.Post;
tbPessoa.ApplyUpdates(0);
tbPessoa.Close;
tbPessoa.Open;
tbPessoa.Refresh;
pgPessoa.ActivePage := tbConsulta;
tbCadastro.TabVisible := True;
end;
procedure TfrmPessoa.edtProcurarChange(Sender: TObject);
var
sTexto : String;
begin
tbPessoa.Close;
tbPessoa.SQL.Clear;
sTexto := '%' + edtProcurar.Text + '%';
tbPessoa.Open(Format(SQL_PROCURA_PESSOA,[QuotedStr(sTexto)]));
end;
procedure TfrmPessoa.FormShow(Sender: TObject);
begin
dmPrincipal.Connection.Connected := True;
tbCadastro.TabVisible := False;
pgPessoa.ActivePage := tbConsulta;
tbPessoa.Active := True;
edtProcurar.SetFocus;
end;
function TfrmPessoa.Sequencial: Integer;
var
iSeq : Integer;
Qry: TFDQuery;
begin
Qry := TFDQuery.Create(nil);
try
Qry.Connection := dmPrincipal.Connection;
Qry.SQL.Add(SQL_SEQUENCIA_NOVA);
Qry.Open;
Result := Qry.Fields[0].AsInteger;
finally
FreeAndNil(Qry);
end;
end;
procedure TfrmPessoa.DeletePessoa(CodPessoa: string);
var
QryCaoPessoa: TFDQuery;
QryPessoa : TFDQuery;
QryCao : TFDQuery;
QryEncontraCao : TFDQuery;
iIdCao : Integer;
begin
QryCaoPessoa := TFDQuery.Create(nil);
QryPessoa := TFDQuery.Create(nil);
QryCao := TFDQuery.Create(nil);
QryEncontraCao := TFDQuery.Create(nil);
try
if not(dmPrincipal.Connection.InTransaction) then
dmPrincipal.Connection.StartTransaction;
try
QryEncontraCao.Connection := dmPrincipal.Connection;
QryEncontraCao.SQL.Add(Format(SQL_RETORNA_CAO, [CodPessoa]));
QryEncontraCao.Open();
iIdCao := QryEncontraCao.FieldByName('idCao').AsInteger;
QryCaoPessoa.Connection := dmPrincipal.Connection;
QryCaoPessoa.ExecSQL(Format(SQL_DELETE_CAO_PESSOA, [CodPessoa, IntToStr(iIdCao)]));
QryCao.Connection := dmPrincipal.Connection;
QryCao.ExecSQL(Format(SQL_DELETE_CAO, [IntToStr(iIdCao)]));
QryCao.Connection := dmPrincipal.Connection;
QryCao.ExecSQL(Format(SQL_DELETE_PESSOA, [CodPessoa]));
dmPrincipal.Connection.Commit;
except
on E:Exception do
begin
Showmessage('Ocorreu um erro de banco de dados! '+'Erro ao excluir registro '+#13+
'Detalhe: '+E.Message);
dmPrincipal.Connection.Rollback;
Exit;
end;
end;
finally
FreeAndNil(QryCaoPessoa);
FreeAndNil(QryPessoa);
FreeAndNil(QryCao);
FreeAndNil(QryEncontraCao);
tbPessoa.ApplyUpdates(0);
tbPessoa.Close;
tbPessoa.Open;
tbPessoa.Refresh;
end;
end;
end.
|
unit Comp_UTypes;
interface
uses
Controls, Graphics, Types;
const
teTreeView = 'treeview';
teHeader = 'header';
{ teHeader }
tcHeader = 1;
tiHeaderNormal = 1;
tiHeaderHover = 2;
tiHeaderDown = 3;
tiHeaderPasive = 7;
tiCollapsed = 1;
tiExpanded = 2;
tcExpandingButton = 2;
{ Effects }
szShadowSize = 3;
szReflectionSize = 20;
type
// Стиль кнопки-переключателя
TScToggleButtonStyle = (tsStyleNative, tsTriangle, tsSquare, tsGlyph);
// Стиль границы
TScBorderStyle = (btSolid, btLowered, btRaised);
TScStyleOption = (soNativeStyles, soVCLStyles);
TScStyleOptions = set of TScStyleOption;
TScPaintEffects = set of (efBevel, efInnerShadow, efLight, efReflection, efShadow, efShine);
TScButtonState = set of (bsHover, bsChecked, bsFocused, bsPressed, bsSelected, bsDisabled);
TScAppearanceStyle = (stNative, stModern, stUserDefined);
TScWrapKind = (wkNone, wkEllipsis, wkPathEllipsis, wkWordEllipsis, wkWordWrap);
TScOrientation = (orHorizontal, orVertical);
TScPanelPaintStyle = class
public
class function GetFillColor(Control: TControl; DefaultColor: TColor): TColor;
end;
TScTreeStyledView = class
class procedure PaintToggle(Canvas: TCanvas; Handle: THandle; Dest: TRect;
Expanded: Boolean; State: TScButtonState; Options: TScStyleOptions);
end;
TScHeaderStyle = class
// class function GetTextColor(Control: TControl; Color: TColor;
// State: TNxButtonState): TColor;
class procedure Paint(Canvas: TCanvas; Handle: THandle; Dest: TRect;
State: TScButtonState; Options: TScStyleOptions);
// class procedure PaintInactive(Canvas: TCanvas; Handle: THandle; Dest: TRect;
// Options: TNxStyleOptions);
end;
TQuadColor = packed record
case Boolean of
True: (Blue, Green, Red, Alpha: Byte);
False: (Quad: Cardinal);
end;
PQuadColor = ^TQuadColor;
PPQuadColor = ^PQuadColor;
TScColorSchemeElement = (
seAppWorkSpace,
seBtnFace,
seBtnFaceChecked,
seBtnFacePressed,
seBtnFrame,
seBtnFramePressed,
seDivider,
seHighlight,
seMenu,
seTabFace,
seTabFaceHot,
seTabText,
seTabBtnFace,
seStatusBtnFace,
seStatusBtnFacePressed,
seStatusText,
seTrackBar,
seWindowFrame
);
{ Color Schemes }
TScColorScheme = (csDefault,
csExcel, csOutlook, csPowerPoint, csWord,
csVisualStudioBlue);
TScColorSchemes = csExcel..csVisualStudioBlue;
function Size(cx, cy: Integer): TSize;
procedure SetPadding(var Rect: TRect; Padding: TPadding);
function SupportStyle(Options: TScStyleOptions): Boolean;
function Themed: Boolean;
var
SchemeColor: array[TScColorScheme, TScColorSchemeElement] of TColor;
ColorScheme: TScColorSchemes = csOutlook;
implementation
uses
UxTheme, Math;
function Size(cx, cy: Integer): TSize;
begin
Result.cx := cx;
Result.cy := cy;
end;
procedure SetPadding(var Rect: TRect; Padding: TPadding);
begin
Inc(Rect.Left, Padding.Left);
Inc(Rect.Top, Padding.Top);
Dec(Rect.Right, Padding.Right);
Dec(Rect.Bottom, Padding.Bottom);
end;
function Themed: Boolean;
begin
Result := IsThemeActive;
end;
function StyleServicesEnabled: Boolean;
begin
{$IFDEF STYLE_SERVICES}
Result := StyleServices.Enabled and StyleServices.Available;
{$ELSE}
Result := False;
{$ENDIF}
end;
function SupportStyle(Options: TScStyleOptions): Boolean;
begin
Result := False;
if (soVCLStyles in Options)
and StyleServicesEnabled then
begin
Result := True;
Exit;
end;
if (soNativeStyles in Options)
and Themed then
begin
Result := True;
Exit;
end;
end;
{ TScPanelStyle }
class function TScPanelPaintStyle.GetFillColor(Control: TControl;
DefaultColor: TColor): TColor;
{$IFDEF STYLE_SERVICES}
var
OutColor: TColor;
Detail: TThemedPanel;
{$ENDIF}
begin
Result := DefaultColor;
if SupportStyle([soVCLStyles]) then
begin
{$IFDEF STYLE_SERVICES}
if seClient in Control.StyleElements then
begin
with StyleServices do
begin
Detail := tpPanelBackground;
if GetElementColor(GetElementDetails(Detail), ecFillColor, OutColor) then
begin
if Result <> clNone then Result := OutColor;
end;
end;
end;
{$ENDIF}
end;
end;
class procedure TScTreeStyledView.PaintToggle(Canvas: TCanvas; Handle: THandle;
Dest: TRect; Expanded: Boolean; State: TScButtonState;
Options: TScStyleOptions);
var
{$IFDEF STYLE_SERVICES}
Detail: TThemedTreeview;
{$ENDIF}
Index, C: Integer;
Theme: HTHEME;
begin
if (soVCLStyles in Options) and StyleServicesEnabled then
begin
{$IFDEF STYLE_SERVICES}
if Expanded then
Detail := ttGlyphOpened
else
Detail := ttGlyphClosed;
StyleServices.DrawElement(Canvas.Handle, StyleServices.GetElementDetails(Detail), Dest);
{$ENDIF}
end else if (soNativeStyles in Options) and Themed then
begin
Theme := OpenThemeData(Handle, teTreeView);
if Expanded then Index := tiExpanded else Index := tiCollapsed;
DrawThemeBackground(Theme, Canvas.Handle, tcExpandingButton, Index, Dest, nil);
CloseThemeData(Theme);
end else
begin
with Canvas do
begin
Pen.Color := clGray;
Brush.Color := clWhite;
Rectangle(Dest);
C := Floor(RectWidth(Dest) / 2);
Polyline([
Point(Dest.Left + 2, Dest.Top + C),
Point(Dest.Right - 2, Dest.Top + C)
]);
if not Expanded then
Polyline([
Point(Dest.Left + C, Dest.Top + 2),
Point(Dest.Left + C, Dest.Bottom - 2)
]);
end;
end;
end;
{ TScHeaderStyle }
class procedure TScHeaderStyle.Paint(Canvas: TCanvas; Handle: THandle;
Dest: TRect; State: TScButtonState; Options: TScStyleOptions);
var
{$IFDEF STYLE_SERVICES}
Detail: TThemedHeader;
{$ENDIF}
Index: Integer;
Theme: HTHEME;
begin
if (soVCLStyles in Options) and StyleServicesEnabled then
begin
{$IFDEF STYLE_SERVICES}
Detail := thHeaderItemNormal;
if bsHover in State then Detail := thHeaderItemHot;
if bsPressed in State then Detail := thHeaderItemPressed;
StyleServices.DrawElement(Canvas.Handle, StyleServices.GetElementDetails(Detail), Dest);
{$ENDIF}
end else if (soNativeStyles in Options) and Themed then
begin
Theme := OpenThemeData(Handle, teHeader);
Index := tiHeaderNormal;
if bsHover in State then Index := tiHeaderHover;
if bsPressed in State then Index := tiHeaderDown;
DrawThemeBackground(Theme, Canvas.Handle, tcHeader, Index, Dest, nil);
CloseThemeData(Theme);
end else
begin
end;
end;
initialization
{ ColorSchemes }
SchemeColor[csOutlook, seAppWorkSpace] := $00ffffff;
SchemeColor[csOutlook, seMenu] := $00c67200;
SchemeColor[csOutlook, seBtnFace] := $00f7e6cd;
SchemeColor[csOutlook, seBtnFrame] := $00ababab; { shared }
SchemeColor[csOutlook, seBtnFramePressed] := $00d48d2a;
SchemeColor[csOutlook, seBtnFacePressed] := $00e0c092;
SchemeColor[csOutlook, seBtnFaceChecked] := $00f0d6b1;
SchemeColor[csOutlook, seDivider] := $00e1e1e1; { shared }
SchemeColor[csOutlook, seHighlight] := $00f7e6cd;
SchemeColor[csOutlook, seTabBtnFace] := $00ffffff;
SchemeColor[csOutlook, seTabFace] := $00ffffff;
SchemeColor[csOutlook, seTabFaceHot] := $00f7e6cd;
SchemeColor[csOutlook, seTabText] := $00000000;
SchemeColor[csOutlook, seStatusText] := clWhite;
SchemeColor[csOutlook, seTrackBar] := clLime;
SchemeColor[csOutlook, seWindowFrame] := $00b5aca5;
SchemeColor[csWord, seAppWorkSpace] := $00ffffff;
SchemeColor[csWord, seMenu] := $009a572b; //
SchemeColor[csWord, seBtnFace] := $00f2e1d5; // $00F2E1D5
SchemeColor[csWord, seBtnFrame] := $00ababab; { shared }
SchemeColor[csWord, seBtnFramePressed] := $00b56d3e; //
SchemeColor[csWord, seBtnFacePressed] := $00e3bda3; // $00E3BDA3
SchemeColor[csWord, seBtnFaceChecked] := $00f2d5c2; // $00F2D5C2
SchemeColor[csWord, seDivider] := $00e1e1e1; { shared }
SchemeColor[csWord, seHighlight] := $00f2e1d5; //
SchemeColor[csWord, seTabBtnFace] := $00ffffff;
SchemeColor[csWord, seTabFace] := $00ffffff;
SchemeColor[csWord, seTabFaceHot] := $00f2e1d5;
SchemeColor[csWord, seTabText] := $00000000;
SchemeColor[csWord, seStatusBtnFace] := $00b56d3e;
SchemeColor[csWord, seStatusBtnFacePressed] := $008a4719;
SchemeColor[csWord, seStatusText] := clWhite;
SchemeColor[csWord, seTrackBar] := $00d9b298;
SchemeColor[csWord, seWindowFrame] := $00b5aca5; //b5aca5
SchemeColor[csPowerPoint, seAppWorkSpace] := $00ffffff;
SchemeColor[csPowerPoint, seMenu] := $002647d2; //
SchemeColor[csPowerPoint, seBtnFace] := $00dce4fc; //
SchemeColor[csPowerPoint, seBtnFrame] := $00ababab; { shared }
SchemeColor[csPowerPoint, seBtnFramePressed] := $009dbaf5;
SchemeColor[csPowerPoint, seBtnFacePressed] := $009dbaf5; //
SchemeColor[csPowerPoint, seBtnFaceChecked] := $00b6cdfc; //
SchemeColor[csPowerPoint, seDivider] := $00e1e1e1; { shared }
SchemeColor[csPowerPoint, seHighlight] := $00dce4fc; //
SchemeColor[csPowerPoint, seTabBtnFace] := $00ffffff;
SchemeColor[csPowerPoint, seTabFace] := $00ffffff;
SchemeColor[csPowerPoint, seTabFaceHot] := $00dce4fc;
SchemeColor[csPowerPoint, seTabText] := $00000000;
SchemeColor[csPowerPoint, seStatusBtnFace] := $003e62f0;
SchemeColor[csPowerPoint, seStatusBtnFacePressed] := $001d3bb8;
SchemeColor[csPowerPoint, seStatusText] := clWhite;
SchemeColor[csPowerPoint, seTrackBar] := clLime;
SchemeColor[csPowerPoint, seWindowFrame] := $00b5aca5;
SchemeColor[csExcel, seAppWorkSpace] := $00ffffff;
SchemeColor[csExcel, seMenu] := $00467321;
SchemeColor[csExcel, seBtnFace] := $00e0f0d3;
SchemeColor[csExcel, seBtnFrame] := $00ababab; { shared }
SchemeColor[csExcel, seBtnFramePressed] := $00679443;
SchemeColor[csExcel, seBtnFacePressed] := $00a0bf86;
SchemeColor[csExcel, seBtnFaceChecked] := $00b7d59f;
SchemeColor[csExcel, seDivider] := $00e1e1e1; { shared }
SchemeColor[csExcel, seHighlight] := $00dce4fc;
SchemeColor[csExcel, seTabBtnFace] := $00ffffff;
SchemeColor[csExcel, seTabFace] := $00ffffff;
SchemeColor[csExcel, seTabFaceHot] := $00e0f0d3;
SchemeColor[csExcel, seTabText] := $00000000;
SchemeColor[csExcel, seStatusBtnFace] := $00679443;
SchemeColor[csExcel, seStatusBtnFacePressed] := $0032630a;
SchemeColor[csExcel, seStatusText] := clWhite;
SchemeColor[csExcel, seTrackBar] := $00b0cc99;
SchemeColor[csExcel, seWindowFrame] := $00b5aca5;
SchemeColor[csVisualStudioBlue, seAppWorkSpace] := $00553929;
SchemeColor[csVisualStudioBlue, seMenu] := $00553929;
SchemeColor[csVisualStudioBlue, seBtnFace] := $00bff4fd;
SchemeColor[csVisualStudioBlue, seBtnFrame] := $0065c3e5;
SchemeColor[csVisualStudioBlue, seBtnFramePressed] := $0065c3e5;
SchemeColor[csVisualStudioBlue, seBtnFacePressed] := $009df2ff;
SchemeColor[csVisualStudioBlue, seBtnFaceChecked] := $009df2ff;
SchemeColor[csVisualStudioBlue, seDivider] := $00e1e1e1; { shared }
SchemeColor[csVisualStudioBlue, seHighlight] := $00bff4fd;
SchemeColor[csVisualStudioBlue, seTabFace] := $006f4e36;
SchemeColor[csVisualStudioBlue, seTabFaceHot] := $0099715b;
SchemeColor[csVisualStudioBlue, seTabText] := $00ffffff;
SchemeColor[csVisualStudioBlue, seTabBtnFace] := $00f4fcff;
SchemeColor[csVisualStudioBlue, seTrackBar] := clLime;
SchemeColor[csVisualStudioBlue, seWindowFrame] := $00b5aca5;
end.
|
unit uSaveUnitForm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
FMX.StdCtrls, FMX.Layouts, FMX.Memo, FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo.Types;
type
TSaveUnitForm = class(TForm)
Memo1: TMemo;
Panel1: TPanel;
btnClose: TButton;
btnSave: TButton;
sd: TSaveDialog;
Label1: TLabel;
StyleBook1: TStyleBook;
procedure btnCloseClick(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
procedure Memo1KeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
procedure FormKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
private
FJson: string;
function GetFileName: string;
procedure SetFileName(const Value: string);
procedure SetJson(const Value: string);
{ Private declarations }
public
{ Public declarations }
property FileName: string read GetFileName write SetFileName;
property Json: string read FJson write SetJson;
end;
implementation
{$R *.fmx}
uses
uMainForm, System.IoUtils;
procedure TSaveUnitForm.btnCloseClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TSaveUnitForm.btnSaveClick(Sender: TObject);
var
Buffer: TStringList;
ResourceStream: TResourceStream;
begin
if not sd.Execute then
exit;
Memo1.Lines.SaveToFile(FileName);
Buffer := TStringList.Create;
ResourceStream := TResourceStream.Create(HInstance, 'JsonDTO', 'PAS');
try
ResourceStream.Position := 0;
Buffer.LoadFromStream(ResourceStream);
Buffer.SaveToFile(TPath.GetDirectoryName(FileName) + TPath.DirectorySeparatorChar + 'Pkg.Json.DTO.pas');
finally
ResourceStream.Free;
Buffer.Free;
end;
end;
procedure TSaveUnitForm.FormKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
begin
if Key = 27 then
ModalResult := mrCancel;
end;
function TSaveUnitForm.GetFileName: string;
begin
Result := sd.FileName;
end;
procedure TSaveUnitForm.Memo1KeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
begin
if Key = 27 then
ModalResult := mrCancel;
end;
procedure TSaveUnitForm.SetFileName(const Value: string);
begin
sd.FileName := Value;
Caption := 'Preview Delphi Unit - ' + Value;
end;
procedure TSaveUnitForm.SetJson(const Value: string);
begin
FJson := Value;
Memo1.Lines.Text := FJson;
end;
end.
|
unit UHttpGet;
//Download by http://www.codefans.net
interface
uses UHTTPGetThread, windows;
type
TOnDoneFileEvent = procedure(FileName: string; FileSize: Integer) of object;
TOnDoneStringEvent = procedure(Result: AnsiString) of object;
THttpGet = class
private
F_URL: string; //目标url
F_GetURLThread: THTTPGetThread; //取数据的线程
F_Accept_Types: string;
F_Agent: string;
F_Binary_Data: Boolean;
F_Use_Cache: Boolean; //是否读缓存
F_File_Name: string;
F_User_Name: string; //用户名
F_Password: string; //密码
F_PostQuery: string; //方法名
F_Referer: string;
F_Mime_Type: string;
F_Wait_Thread: Boolean;
FResult: Boolean;
FProgress: TOnProgressEvent;
FDoneFile: TOnDoneFileEvent;
FDoneString: TOnDoneStringEvent;
procedure ThreadDone(Sender: TObject);
procedure progress(TotalSize, Readed: Integer);
public
constructor Create();
destructor Destroy(); override;
procedure getFile();
procedure GetString();
procedure Abort();
published
property WaitThread: Boolean read F_Wait_Thread write F_Wait_Thread;
property AcceptTypes: string read F_Accept_Types write F_Accept_Types;
property Agent: string read F_Agent write F_Agent;
property BinaryData: Boolean read F_Binary_Data write F_Binary_Data;
property URL: string read F_URL write F_URL;
property UseCache: Boolean read F_Use_Cache write F_Use_Cache;
property FileName: string read F_File_Name write F_File_Name;
property UserName: string read F_User_Name write F_User_Name;
property Password: string read F_Password write F_Password;
property PostQuery: string read F_PostQuery write F_PostQuery;
property Referer: string read F_Referer write F_Referer;
property MimeType: string read F_Mime_Type write F_Mime_Type;
property OnDoneFile: TOnDoneFileEvent read FDoneFile write FDoneFile;
property OnDoneString: TOnDoneStringEvent read FDoneString write FDoneString;
end;
implementation
{ THttpGet }
procedure THttpGet.Abort;
begin
if Assigned(F_GetURLThread) then
begin
F_GetURLThread.Terminate;
F_GetURLThread.BResult := false;
end;
end;
constructor THttpGet.Create;
begin
F_Accept_Types := '*/*';
F_Agent := 'Nokia6610/1.0 (5.52) Profile/MIDP-1.0 Configuration/CLDC-1.02';
FProgress := progress;
end;
destructor THttpGet.Destroy;
begin
end;
procedure THttpGet.getFile;
var
Msg: TMsg;
begin
if not Assigned(F_GetURLThread) then
begin
F_GetURLThread := THTTPGetThread.Create(F_Accept_Types, F_Mime_Type, F_Agent, F_URL, F_File_Name, F_User_Name, F_Password, F_PostQuery, F_Referer, F_Binary_Data, F_Use_Cache, FProgress, true);
F_GetURLThread.OnTerminate := ThreadDone;
if F_Wait_Thread then
while Assigned(F_GetURLThread) do
while PeekMessage(Msg, 0, 0, 0, PM_REMOVE) do
begin
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
end
end;
procedure THttpGet.GetString;
var
Msg: TMsg;
begin
if not Assigned(F_GetURLThread) then
begin
F_GetURLThread := THTTPGetThread.Create(F_Accept_Types, F_Mime_Type, F_Agent, F_URL, F_File_Name, F_User_Name, F_Password, F_PostQuery, F_Referer, F_Binary_Data, F_Use_Cache, FProgress, False);
F_GetURLThread.OnTerminate := ThreadDone;
if F_Wait_Thread then
while Assigned(F_GetURLThread) do
while PeekMessage(Msg, 0, 0, 0, PM_REMOVE) do begin
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
end
end;
procedure THttpGet.progress(TotalSize, Readed: Integer);
begin
end;
procedure THttpGet.ThreadDone(Sender: TObject);
begin
try
FResult := F_GetURLThread.BResult;
if FResult then
if F_GetURLThread.getToFile then begin
if Assigned(FDoneFile) then
FDoneFile(F_GetURLThread.getFileName, F_GetURLThread.getFileSize)
end else begin
if Assigned(FDoneString) then
FDoneString(F_GetURLThread.getStringResult);
end;
except
//messagebox(0, 'error', 'error', $0);
end;
//end else if Assigned(FError) then FError(Self);
F_GetURLThread := nil;
end;
end.
|
unit uFormMonitor;
interface
uses
SysUtils, Forms, Classes, Windows, Messages, ExtCtrls, Contnrs, DateUtils;
procedure SetFormMonitoring(activate: boolean);
procedure MarkFormAsStayOnTop(Form: TForm; IsStayOnTop: Boolean);
// Some forms have display tasks when first displayed that are messed up by the
// form monitor - such as making a combo box automatically drop down. These forms
// should call FormMonitorBringToFrontEvent, which will be called when the
// form monitor calls the form's BringToFront method. The Seconds parameter is the
// amount of time that must transpire before the form monitor will call
// BringToFront again, unless another form has received focus since the event was called.
procedure FormMonitorBringToFrontEvent(Form: TForm; AEvent: TNotifyEvent; Seconds: integer = 3);
implementation
const
TIMER_INTERVAL = 8;
TIMER_CHECKS_BEFORE_TIMEOUT = 1000 div TIMER_INTERVAL;
type
TFormMonitor = class
private
FOldActiveFormChangeEvent: TNotifyEvent;
FOldActivateEvent: TNotifyEvent;
FOldRestore: TNotifyEvent;
FModifyingZOrder: boolean;
FModifyPending: boolean;
FActiveForm: TForm;
FZOrderHandles: TList;
FLastModal: boolean;
fTopOnList: TList;
fTopOffList: TList;
fTimer: TTimer;
FTimerCount: integer;
FMenuPending: boolean;
FWindowsHook: HHOOK;
FRunning: boolean;
FFormEvents: TObjectList;
FLastActiveFormHandle: HWND;
procedure ManageForms;
function FormValid(form: TForm): boolean;
function HandleValid(handle: HWND): boolean;
procedure MoveOnTop(Handle: HWND);
procedure MoveOffTop(Handle: HWND);
procedure Normalize(Handle: HWND; Yes: boolean);
procedure NormalizeReset;
function IsNormalized(Handle: HWND): boolean;
function GetActiveFormHandle: HWND;
procedure StartZOrdering;
function SystemRunning: boolean;
function ModalDelphiForm: boolean;
function IsTopMost(Handle: HWND): boolean;
public
procedure Start;
procedure Stop;
procedure Timer(Sender: TObject);
procedure Activate(Sender: TObject);
procedure ActiveFormChange(Sender: TObject);
procedure Restore(Sender: TObject);
end;
TFormEvent = class(TObject)
private
FForm: TForm;
FEvent: TNotifyEvent;
FSeconds: integer;
FTimeStamp: TDateTime;
end;
var
FormMonitor: TFormMonitor = nil;
type
HDisableGhostProc = procedure(); stdcall;
const
NORMALIZED = $00000001;
UN_NORMALIZED = $FFFFFFFE;
STAY_ON_TOP = $00000002;
NORMAL_FORM = $FFFFFFFD;
procedure DisableGhosting;
const
DisableProc = 'DisableProcessWindowsGhosting';
UserDLL = 'user32.dll';
var
DisableGhostProc: HDisableGhostProc;
User32Handle: THandle;
begin
User32Handle := LoadLibrary(PChar(UserDLL));
try
if User32Handle <= HINSTANCE_ERROR then
User32Handle := 0
else
begin
DisableGhostProc := GetProcAddress(User32Handle, PChar(DisableProc));
if(assigned(DisableGhostProc)) then
begin
DisableGhostProc;
end;
end;
finally
if(User32Handle <> 0) then
FreeLibrary(User32Handle);
end;
end;
procedure SetFormMonitoring(activate: boolean);
var
running: boolean;
begin
running := assigned(FormMonitor);
if(activate <> running) then
begin
if(running) then
begin
FormMonitor.Stop;
FormMonitor.Free;
FormMonitor := nil;
end
else
begin
FormMonitor := TFormMonitor.Create;
FormMonitor.Start;
end;
end;
end;
procedure MarkFormAsStayOnTop(Form: TForm; IsStayOnTop: Boolean);
var
Data: Longint;
begin
Data := GetWindowLong(Form.Handle, GWL_USERDATA);
if(IsStayOnTop) then
begin
Data := Data or STAY_ON_TOP;
SetWindowPos(Form.Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE + SWP_NOSIZE);
end
else
begin
Data := Data and NORMAL_FORM;
SetWindowPos(Form.Handle, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE + SWP_NOSIZE);
end;
SetWindowLong(Form.Handle, GWL_USERDATA, Data);
end;
function FindFormEventIndex(Form: TForm): integer;
var
i: integer;
event: TFormEvent;
begin
Result := -1;
for i := 0 to FormMonitor.FFormEvents.Count-1 do
begin
event := TFormEvent(FormMonitor.FFormEvents[i]);
if(event.FForm = Form) then
begin
Result := i;
exit;
end;
end;
end;
function FindFormEvent(Form: TForm): TFormEvent;
var
idx: integer;
begin
idx := FindFormEventIndex(Form);
if(idx < 0) then
Result := nil
else
Result := TFormEvent(FormMonitor.FFormEvents[idx]);
end;
procedure FormMonitorBringToFrontEvent(Form: TForm; AEvent: TNotifyEvent; Seconds: integer);
var
event: TFormEvent;
idx: integer;
begin
event := FindFormEvent(Form);
if(assigned(AEvent)) then
begin
if(event = nil) then
begin
event := TFormEvent.Create;
event.FForm := Form;
event.FTimeStamp := 0;
FormMonitor.FFormEvents.Add(event);
end;
event.FEvent := AEvent;
event.FSeconds := Seconds;
end
else
if(event <> nil) then
begin
idx := FindFormEventIndex(Form);
FormMonitor.FFormEvents.Delete(idx);
// event.Free; - TObjectList frees object automatically
end;
end;
function IsFormStayOnTop(form: TForm): boolean;
begin
Result := (form.FormStyle = fsStayOnTop);
if(not Result) then
Result := ((GetWindowLong(Form.Handle, GWL_USERDATA) and STAY_ON_TOP) <> 0);
end;
{ TFormMonitor }
procedure TFormMonitor.Activate(Sender: TObject);
begin
if(Assigned(FOldActivateEvent)) then
FOldActivateEvent(Sender);
NormalizeReset;
StartZOrdering;
end;
procedure TFormMonitor.ActiveFormChange(Sender: TObject);
begin
if(Assigned(FOldActiveFormChangeEvent)) then
FOldActiveFormChangeEvent(Sender);
StartZOrdering;
end;
procedure TFormMonitor.Restore(Sender: TObject);
begin
if(Assigned(FOldRestore)) then
FOldRestore(Sender);
NormalizeReset;
StartZOrdering;
end;
function TFormMonitor.FormValid(form: TForm): boolean;
begin
Result := assigned(form);
if Result then
Result := (form.Parent = nil) and (form.ParentWindow = 0) and form.Visible and (form.Handle <> 0);
end;
function TFormMonitor.HandleValid(handle: HWND): boolean;
begin
Result := (handle <> 0);
if(Result) then
Result := IsWindow(handle) and IsWindowVisible(handle) and isWindowEnabled(handle);
end;
function FindWindowZOrder(Window: HWnd; Data: Longint): Bool; stdcall;
begin
if(IsWindow(Window) and IsWindowVisible(Window)) then
FormMonitor.FZOrderHandles.Add(Pointer(Window));
Result := True;
end;
procedure TFormMonitor.ManageForms;
var
i, j: integer;
form: TForm;
formHandle, activeHandle: HWND;
modal, doCall: boolean;
event: TFormEvent;
begin
if(FModifyingZOrder) then exit;
if(not SystemRunning) then exit;
FModifyingZOrder := TRUE;
try
activeHandle := GetActiveFormHandle;
if (activeHandle <> 0) and (not assigned(FactiveForm)) then
modal := true //assumes DLL created forms are modal
else
modal := ModalDelphiForm;
FZOrderHandles.Clear;
fTopOnList.Clear;
fTopOffList.Clear;
EnumThreadWindows(GetCurrentThreadID, @FindWindowZOrder, 0);
for i := 0 to FZOrderHandles.Count-1 do
begin
formHandle := HWND(FZOrderHandles[i]);
for j := 0 to Screen.FormCount-1 do
begin
form := Screen.Forms[j];
if(form.Handle = formHandle) then
begin
if formValid(form) and (form.Handle <> activeHandle) and IsFormStayOnTop(form) then
begin
if(modal and (not IsWindowEnabled(form.Handle))) then
fTopOffList.Add(Pointer(form.Handle))
else
fTopOnList.Add(Pointer(form.Handle));
end;
break;
end;
end;
end;
for i := fTopOffList.Count-1 downto 0 do
MoveOffTop(HWND(fTopOffList[i]));
for i := fTopOnList.Count-1 downto 0 do
MoveOnTop(HWND(fTopOnList[i]));
if(activeHandle <> 0) then
begin
if(assigned(FActiveForm)) then
begin
event := FindFormEvent(FActiveForm);
doCall := (event = nil);
if(not doCall) then
doCall := (activeHandle <> FLastActiveFormHandle);
if(not doCall) then
doCall := SecondsBetween(Now, event.FTimeStamp) > event.FSeconds;
if(doCall) then
begin
if IsFormStayOnTop(FActiveForm) then
begin
SetWindowPos(activeHandle, HWND_TOPMOST, 0, 0, 0, 0,
SWP_NOMOVE or SWP_NOSIZE);
Normalize(activeHandle, FALSE);
end;
FActiveForm.BringToFront;
if(event <> nil) then
begin
if(FormValid(event.FForm)) then
begin
event.FEvent(FActiveForm);
event.FTimeStamp := now;
end;
end;
end;
end
else
begin
if(activeHandle <> 0) then
begin
SetFocus(activeHandle);
BringWindowToTop(activeHandle);
if(IsTopMost(activeHandle)) then
SetWindowPos(activeHandle, HWND_TOPMOST, 0, 0, 0, 0,
SWP_NOMOVE or SWP_NOSIZE);
end;
end;
end;
FLastActiveFormHandle := activeHandle;
finally
FModifyingZOrder := FALSE;
end;
end;
function CallWndHook(Code: Integer; WParam: wParam; Msg: PCWPStruct): Longint; stdcall;
begin
case Msg.message of
WM_INITMENU, WM_INITMENUPOPUP, WM_ENTERMENULOOP:
FormMonitor.FMenuPending := TRUE;
WM_MENUSELECT, WM_EXITMENULOOP:
FormMonitor.FMenuPending := FALSE;
end;
Result := CallNextHookEx(FormMonitor.FWindowsHook, Code, WParam, Longint(Msg));
end;
procedure TFormMonitor.Start;
begin
if(FRunning) then exit;
FRunning := TRUE;
FTimer := TTimer.Create(Application);
fTimer.Enabled := FALSE;
FTimer.OnTimer := Timer;
FTimer.Interval := TIMER_INTERVAL;
FMenuPending := FALSE;
FLastActiveFormHandle := 0;
FZOrderHandles := TList.Create;
fTopOnList := TList.Create;
fTopOffList := TList.Create;
FFormEvents := TObjectList.Create;
FModifyingZOrder := false;
FLastModal := false;
FOldActiveFormChangeEvent := Screen.OnActiveFormChange;
Screen.OnActiveFormChange := ActiveFormChange;
FOldActivateEvent := Application.OnActivate;
Application.OnActivate := Activate;
FOldRestore := Application.OnRestore;
Application.OnRestore := Restore;
FWindowsHook := SetWindowsHookEx(WH_CALLWNDPROC, @CallWndHook, 0, GetCurrentThreadID)
end;
procedure TFormMonitor.Stop;
begin
if(not FRunning) then exit;
FRunning := FALSE;
if FWindowsHook <> 0 then
begin
UnHookWindowsHookEx(FWindowsHook);
FWindowsHook := 0;
end;
Screen.OnActiveFormChange := FOldActiveFormChangeEvent;
Application.OnActivate := FOldActivateEvent;
Application.OnRestore := FOldRestore;
FZOrderHandles.Free;
fTopOnList.Free;
fTopOffList.Free;
FFormEvents.Free;
fTimer.Enabled := FALSE;
fTimer.Free;
end;
procedure TFormMonitor.MoveOffTop(Handle: HWND);
begin
if(not IsNormalized(Handle)) then
begin
SetWindowPos(Handle, HWND_NOTOPMOST, 0, 0, 0, 0,
SWP_NOMOVE or SWP_NOSIZE or SWP_NOACTIVATE or SWP_NOOWNERZORDER);
Normalize(Handle, TRUE);
end;
end;
procedure TFormMonitor.MoveOnTop(Handle: HWND);
begin
if(isNormalized(Handle)) then
begin
SetWindowPos(Handle, HWND_TOPMOST, 0, 0, 0, 0,
SWP_NOMOVE or SWP_NOSIZE or SWP_NOACTIVATE or SWP_NOOWNERZORDER);
Normalize(Handle, FALSE);
end;
end;
procedure TFormMonitor.Normalize(Handle: HWND; Yes: boolean);
var
Data: Longint;
begin
Data := GetWindowLong(Handle, GWL_USERDATA);
if(yes) then
Data := Data or NORMALIZED
else
Data := Data and UN_NORMALIZED;
SetWindowLong(Handle, GWL_USERDATA, Data);
end;
function TFormMonitor.IsNormalized(Handle: HWND): boolean;
begin
Result := ((GetWindowLong(Handle, GWL_USERDATA) and NORMALIZED) <> 0);
end;
function TFormMonitor.IsTopMost(Handle: HWND): boolean;
begin
Result := ((GetWindowLong(Handle, GWL_EXSTYLE) and WS_EX_TOPMOST) <> 0);
end;
function FindWindows(Window: HWnd; Data: Longint): Bool; stdcall;
begin
FormMonitor.Normalize(Window, FALSE);
Result := True;
end;
procedure TFormMonitor.NormalizeReset;
begin
EnumThreadWindows(GetCurrentThreadID, @FindWindows, 0);
end;
var
uActiveWindowHandle: HWND;
uActiveWindowCount: integer;
function IsHandleOK(Handle: HWND): boolean;
var
i: integer;
begin
Result := FALSE;
if(not formMonitor.HandleValid(Handle)) or (Handle = Application.Handle) then exit;
for i := 0 to Screen.FormCount-1 do
begin
if(Handle = Screen.Forms[i].Handle) then exit;
end;
Result := TRUE;
end;
function FindActiveWindow(Window: HWnd; Data: Longint): Bool; stdcall;
begin
Result := True;
if(IsHandleOK(Window)) then
begin
inc(uActiveWindowCount);
if(uActiveWindowCount = 1) then
uActiveWindowHandle := Window
else
if(uActiveWindowCount > 1) then
Result := false;
end;
end;
function TFormMonitor.GetActiveFormHandle: HWND;
var
i: integer;
form: TForm;
begin
FActiveForm := Screen.ActiveForm;
if(assigned(FActiveForm)) then
Result := FActiveForm.Handle
else
Result := 0;
if(FormValid(FActiveForm) and IsWindowEnabled(FActiveForm.Handle)) then
exit;
for i := 0 to Screen.FormCount-1 do
begin
form := Screen.Forms[i];
if(form.Handle = Result) then
begin
if FormValid(form) and IsWindowEnabled(form.Handle) then
begin
FActiveForm := form;
Result := form.Handle;
exit;
end;
end;
end;
FActiveForm := nil;
Result := GetActiveWindow;
if(IsHandleOK(Result)) then exit;
uActiveWindowHandle := 0;
uActiveWindowCount := 0;
EnumThreadWindows(GetCurrentThreadID, @FindActiveWindow, 0);
if(uActiveWindowCount = 1) then
begin
Result := uActiveWindowHandle;
end;
end;
procedure TFormMonitor.StartZOrdering;
begin
if(FModifyPending) then exit;
if(SystemRunning) then
begin
FModifyPending := TRUE;
FTimerCount := 0;
FTimer.Enabled := TRUE;
end;
end;
function TFormMonitor.SystemRunning: boolean;
begin
Result := assigned(Application.MainForm) and
(Application.MainForm.Handle <> 0) and
IsWindowVisible(Application.MainForm.Handle);
end;
function TFormMonitor.ModalDelphiForm: boolean;
var
i: integer;
form: TForm;
begin
for i := 0 to Screen.FormCount-1 do
begin
form := screen.Forms[i];
if(FormValid(form) and (fsModal in form.FormState)) then
begin
Result := TRUE;
exit;
end;
end;
Result := FALSE;
end;
procedure TFormMonitor.Timer(Sender: TObject);
var
NoMenu: boolean;
begin
inc(FTimerCount);
if(FTimerCount > TIMER_CHECKS_BEFORE_TIMEOUT) then
begin
FTimer.Enabled := FALSE;
FMenuPending := FALSE;
FModifyPending := FALSE;
exit;
end;
if(FTimerCount <> 1) then exit;
FTimer.Enabled := FALSE;
NoMenu := not FMenuPending;
FMenuPending := FALSE;
if(NoMenu and SystemRunning) then
ManageForms;
FModifyPending := FALSE;
end;
initialization
DisableGhosting;
finalization
end.
|
unit uclAllClasses;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;
type
{enumerations definition}
TEducation = (FirstYear=0, SecondYear, ThirdYear, FinalYear);
TStream = (CSE=0, IT, Mech, ENTC);
TRating = (OneStar=0, TwoStar, ThreeStar, FourStar, FiveStar);
{==================== Course Class =====================}
TCourse = class
private
FDuration: Integer;
FCourseName: string;
FRatings: string;
procedure SetCourseName(const Value: string);
procedure SetDuration(const Value: Integer);
procedure SetRatings(const Value: string);
published
property CourseName : string read FCourseName write SetCourseName;
property CourseDuration : Integer read FDuration write SetDuration;
property Ratings : string read FRatings write SetRatings;
end;
{==================== Student Class =====================}
TStudent = class
private
// FList : TStringList;
FName : string;
FAge : Integer;
FEducation, FStream: string;
FCourse : TStringList;
procedure SetName(const Value: string);
procedure SetAge(const Value: Integer);
procedure SetEducation(const Value: string);
procedure SetStream(const Value: string);
procedure SetCourse(const Value: TStringList);
public
{public Declarations}
constructor Create;
published
property Name : string read FName write SetName;
property Age : Integer read FAge write SetAge;
property Education : string read FEducation write SetEducation;
property Stream : string read FStream write SetStream;
property Course : TStringList read FCourse write SetCourse;
end;
{==============================================================================}
implementation
{ TCourse }
procedure TCourse.SetCourseName(const Value: string);
begin
FCourseName := Value;
end;
procedure TCourse.SetDuration(const Value: Integer);
begin
FDuration := Value;
end;
procedure TCourse.SetRatings(const Value: string);
begin
FRatings := Value;
end;
{ TStudent }
{
* TStudent Class Constructor
* It will inititialize the FCourse reference.
}
constructor TStudent.Create;
begin
FCourse := TStringList.Create;
end;
{
* SetName procedure sets the FName : string private var of
TSudent class via Name property.
}
procedure TStudent.SetName(const Value: string);
begin
FName := Value;
end;
{
* SetAge procedure is called by Age property of TSudent class
to set private var FAge : Integer
}
procedure TStudent.SetAge(const Value: Integer);
begin
FAge := Value;
end;
{
* Set Education will gets a str
}
procedure TStudent.SetEducation(const Value: string);
begin
FEducation := Value;
end;
procedure TStudent.SetStream(const Value: string);
begin
FStream := Value;
end;
procedure TStudent.SetCourse(const Value: TStringList);
begin
FCourse := Value;
end;
end.//end of classes unit
|
unit uTestDrawingSupport;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, uExceptionCodes, Winapi.Windows, uExceptions, Graphics, uBase,
uEventModel, uDrawingSupport, GdiPlus, System.UITypes;
type
// Test methods for class TPoints
TestTPoints = class(TTestCase)
strict private
FPoints: TPoints;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestAdd;
procedure TestClear;
end;
TestTDrawingBox = class(TTestCase )
strict private
FDrawingBox: TDrawingBox;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestBrushes;
procedure TestPen;
procedure TestSetColor;
end;
TestDrawingAreaStatic = class( TTestCase )
published
procedure TestStatic;
end;
implementation
procedure TestTPoints.SetUp;
begin
FPoints := TPoints.Create;
end;
procedure TestTPoints.TearDown;
begin
FPoints.Free;
FPoints := nil;
end;
procedure TestTPoints.TestAdd;
var
aY: Integer;
aX: Integer;
i : integer;
P : TPoint;
begin
aX := 100;
aY := 100;
Check( FPoints.Count = 0, 'Add point XY' );
FPoints.Add(aX, aY);
Check( FPoints.Count = 1, 'Add point XY 2' );
for I := Low(Word) to High(Word) do FPoints.Add( ax, aY );
Check( FPoints.Count = High(Word) - Low(Word) + 2 , 'Add point XY 3');
P := FPoints.Point[0];
CheckEquals( 100, P.X, 'Point X');
CheckEquals( 100, P.Y, 'Point Y');
FPoints.Add( P );
Check( FPoints.Count = High(Word) - Low(Word) + 3, 'Add point Obj' );
P := FPoints.Point[1];
CheckEquals( 100, P.X );
CheckEquals( 100, P.Y );
end;
procedure TestTPoints.TestClear;
var
i : integer;
begin
for I := Low(Word) to High(Word) do FPoints.Add( 1, 1 );
Check( FPoints.Count > 100, 'Add before clear' );
FPoints.Clear;
Check( FPoints.Count = 0, 'Points clear' );
end;
{ TestTDrawingBox }
procedure TestTDrawingBox.SetUp;
begin
FDrawingBox := TDrawingBox.Create;
end;
procedure TestTDrawingBox.TearDown;
begin
FDrawingBox.Free;
FDrawingBox := nil;
end;
procedure TestTDrawingBox.TestBrushes;
begin
CheckNotNull( FDrawingBox.SolidBrush );
Check( FDrawingBox.SolidBrush is TGPSolidBrush );
end;
procedure TestTDrawingBox.TestPen;
begin
CheckNotNull( FDrawingBox.Pen );
Check( FDrawingBox.Pen is TGPPen );
end;
procedure TestTDrawingBox.TestSetColor;
var
c : TColor;
begin
c := clMenu;
FDrawingBox.SetColor( c );
CheckEquals( c, FDrawingBox.BackgroundColor );
CheckEquals( c, FDrawingBox.BorderColor );
end;
{ TestDrawingAreaStatic }
procedure TestDrawingAreaStatic.TestStatic;
begin
Check( TGPColor.Red = GPColor( clRed ).Value );
end;
initialization
RegisterTest(TestTPoints.Suite);
RegisterTest(TestTDrawingBox.Suite);
RegisterTest(TestDrawingAreaStatic.Suite);
end.
|
unit UnitCamera;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
FMX.Controls.Presentation, FMX.StdCtrls, FMX.Media, FMX.Objects,
ZXing.ScanManager,
ZXing.ReadResult,
ZXing.BarcodeFormat,
FMX.Platform, FMX.Layouts;
type
TFrmCamera = class(TForm)
CameraComponent: TCameraComponent;
lbl_erro: TLabel;
img_camera: TImage;
Layout1: TLayout;
Layout2: TLayout;
Layout31: TLayout;
Rectangle16: TRectangle;
btnVoltar: TSpeedButton;
Label1: TLabel;
Layout3: TLayout;
pb1: TProgressBar;
procedure CameraComponentSampleBufferReady(Sender: TObject;
const ATime: TMediaTime);
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnVoltarClick(Sender: TObject);
private
FScanManager : TScanManager;
FScanInProgress : Boolean;
FFrameTake : Integer;
fScanBitmap: TBitmap;
procedure ProcessarImagem;
procedure ParseImage();
{ Private declarations }
public
{ Public declarations }
codigo : string;
end;
var
FrmCamera: TFrmCamera;
implementation
{$R *.fmx}
procedure TFrmCamera.FormCreate(Sender: TObject);
begin
FScanManager := TScanManager.Create(TBarcodeFormat.Auto, nil);
end;
procedure TFrmCamera.FormDestroy(Sender: TObject);
begin
if Assigned(fScanBitmap) then
FreeAndNil(fScanBitmap);
// CameraComponent.Active := false;
// FScanManager.DisposeOf;
end;
procedure TFrmCamera.FormShow(Sender: TObject);
begin
codigo :='0';
FFrameTake :=0;
fScanBitmap := nil;
CameraComponent.Active := false;
CameraComponent.Kind := TCameraKind.BackCamera;
CameraComponent.FocusMode := TFocusMode.ContinuousAutoFocus;
CameraComponent.Quality := TVideoCaptureQuality.MediumQuality;
CameraComponent.Active := true;
end;
procedure TFrmCamera.ParseImage;
begin
TThread.CreateAnonymousThread(
procedure
var
ReadResult: TReadResult;
ScanManager: TScanManager;
begin
try
fScanInProgress := True;
ScanManager := TScanManager.Create(TBarcodeFormat.Auto, nil);
try
ReadResult := ScanManager.Scan(fScanBitmap);
except
on E: Exception do
begin
TThread.Synchronize(TThread.CurrentThread,
procedure
begin
lbl_erro.Text := E.Message;
end);
exit;
end;
end;
TThread.Synchronize(TThread.CurrentThread,
procedure
begin
if (pb1.Value>=100) then
begin
pb1.Value := 0;
end
else
pb1.Value := pb1.Value + 10;
if (ReadResult <> nil) then
begin
codigo := ReadResult.Text;
Close;
end;
end);
finally
if ReadResult <> nil then
FreeAndNil(ReadResult);
ScanManager.Free;
fScanInProgress := false;
end;
end).Start();
end;
procedure TFrmCamera.ProcessarImagem;
var
bmp : TBitmap;
ReadResult : TReadResult;
begin
CameraComponent.SampleBufferToBitmap(img_camera.Bitmap, true);
if FScanInProgress then
exit;
inc(FFrameTake);
if (FFrameTake mod 4 <> 0) then
exit;
bmp := TBitmap.Create;
bmp.Assign(img_camera.Bitmap);
ReadResult := nil;
try
FScanInProgress := true;
try
ReadResult := FScanManager.Scan(bmp);
if ReadResult <> nil then
begin
CameraComponent.Active := false;
codigo := ReadResult.text;
close;
end;
except on ex:exception do
lbl_erro.Text := ex.Message;
end;
finally
bmp.DisposeOf;
ReadResult.DisposeOf;
FScanInProgress := false;
end;
end;
procedure TFrmCamera.btnVoltarClick(Sender: TObject);
begin
CameraComponent.Active := false;
close;
end;
procedure TFrmCamera.CameraComponentSampleBufferReady(Sender: TObject;
const ATime: TMediaTime);
begin
TThread.Synchronize(TThread.CurrentThread,
procedure
begin
CameraComponent.SampleBufferToBitmap(img_Camera.Bitmap, True);
if (fScanInProgress) then
begin
exit;
end;
{ This code will take every 4 frame. }
inc(fFrameTake);
if (fFrameTake mod 4 <> 0) then
begin
exit;
end;
if Assigned(fScanBitmap) then
FreeAndNil(fScanBitmap);
fScanBitmap := TBitmap.Create();
fScanBitmap.Assign(img_Camera.Bitmap);
ParseImage();
end);
// ProcessarImagem;
end;
end.
|
unit AProcessosProducao;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios,
Componentes1, ExtCtrls, PainelGradiente, BotaoCadastro, StdCtrls, Buttons, DB,
DBClient, Tabela, CBancoDados, Grids, DBGrids, DBKeyViolation, Localizacao;
type
TFProcessosProducao = class(TFormularioPermissao)
PainelGradiente1: TPainelGradiente;
PanelColor1: TPanelColor;
GConsulta: TGridIndice;
DATAPROCESSOPRODUCAO: TDataSource;
PROCESSOPRODUCAO: TRBSQL;
BotaoCadastrar1: TBotaoCadastrar;
BotaoAlterar1: TBotaoAlterar;
BotaoConsultar1: TBotaoConsultar;
BotaoExcluir1: TBotaoExcluir;
BFechar: TBitBtn;
PanelColor2: TPanelColor;
Label1: TLabel;
ECodigo: TEditColor;
Label2: TLabel;
EDescricao: TEditColor;
EEstagio: TRBEditLocaliza;
Label3: TLabel;
BLocalizaEstagio: TSpeedButton;
PROCESSOPRODUCAOCODPROCESSOPRODUCAO: TFMTBCDField;
PROCESSOPRODUCAODESPROCESSOPRODUCAO: TWideStringField;
PROCESSOPRODUCAOCODESTAGIO: TFMTBCDField;
PROCESSOPRODUCAOQTDPRODUCAOHORA: TFMTBCDField;
PROCESSOPRODUCAOINDCONFIGURACAO: TWideStringField;
PROCESSOPRODUCAODESTEMPOCONFIGURACAO: TWideStringField;
PROCESSOPRODUCAONOMEST: TWideStringField;
ConsultaPadrao: TConsultaPadrao;
LEstagio: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BFecharClick(Sender: TObject);
procedure BotaoCadastrar1AntesAtividade(Sender: TObject);
procedure BotaoCadastrar1DepoisAtividade(Sender: TObject);
procedure GConsultaOrdem(Ordem: string);
procedure BotaoAlterar1AntesAtividade(Sender: TObject);
procedure BotaoAlterar1Atividade(Sender: TObject);
procedure BotaoAlterar1DepoisAtividade(Sender: TObject);
procedure BotaoConsultar1AntesAtividade(Sender: TObject);
procedure BotaoConsultar1Atividade(Sender: TObject);
procedure BotaoConsultar1DepoisAtividade(Sender: TObject);
procedure ECodigoKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure ECodigoExit(Sender: TObject);
procedure EEstagioFimConsulta(Sender: TObject);
procedure BotaoExcluir1Click(Sender: TObject);
procedure BotaoExcluir1DepoisAtividade(Sender: TObject);
private
{ Private declarations }
VprOrdem : String;
procedure AtualizaConsulta;
procedure AdicionaFiltrosSql(VpaSelect: TStrings);
public
{ Public declarations }
end;
var
FProcessosProducao: TFProcessosProducao;
implementation
uses APrincipal, ANovoProcessoProducao, FunSql;
{$R *.DFM}
{ **************************************************************************** }
procedure TFProcessosProducao.FormCreate(Sender: TObject);
begin
{ abre tabelas }
{ chamar a rotina de atualização de menus }
VprOrdem := 'ORDER BY CODPROCESSOPRODUCAO ';
AtualizaConsulta;
end;
{ *************************************************************************** }
procedure TFProcessosProducao.GConsultaOrdem(Ordem: string);
begin
VprOrdem:= Ordem;
end;
{ *************************************************************************** }
procedure TFProcessosProducao.AdicionaFiltrosSql(VpaSelect: TStrings);
begin
if (ECodigo.Text <> '') then
begin
VpaSelect.Add(' AND CODPROCESSOPRODUCAO = ' + ECodigo.Text);
end else
begin
if EEstagio.Text <> '' then
VpaSelect.Add(' AND CODEST = ' + EEstagio.Text);
if EDescricao.Text <> '' then
VpaSelect.Add(' AND DESPROCESSOPRODUCAO LIKE ''' + EDescricao.Text + '%''');
end;
end;
{ *************************************************************************** }
procedure TFProcessosProducao.AtualizaConsulta;
begin
PROCESSOPRODUCAO.close;
PROCESSOPRODUCAO.sql.clear;
PROCESSOPRODUCAO.sql.add(' SELECT PRO.CODPROCESSOPRODUCAO, PRO.DESPROCESSOPRODUCAO, PRO.CODESTAGIO, ' +
' PRO.QTDPRODUCAOHORA, PRO.INDCONFIGURACAO, PRO.DESTEMPOCONFIGURACAO, ' +
' EST.NOMEST ' +
' FROM PROCESSOPRODUCAO PRO, ESTAGIOPRODUCAO EST ' +
' WHERE PRO.CODESTAGIO = EST.CODEST ');
AdicionaFiltrosSql(PROCESSOPRODUCAO.SQL);
PROCESSOPRODUCAO.sql.add(VprOrdem);
PROCESSOPRODUCAO.open;
GConsulta.ALinhaSQLOrderBy := PROCESSOPRODUCAO.Sql.Count - 1;
end;
{ *************************************************************************** }
procedure TFProcessosProducao.BFecharClick(Sender: TObject);
begin
Close;
end;
{ *************************************************************************** }
procedure TFProcessosProducao.BotaoAlterar1AntesAtividade(Sender: TObject);
begin
FNovoProcessoProducao := TFNovoProcessoProducao.criarSDI(Self, '', True);
end;
{ *************************************************************************** }
procedure TFProcessosProducao.BotaoAlterar1Atividade(Sender: TObject);
begin
AdicionaSQLAbreTabela(FNovoProcessoProducao.PROCESSOPRODUCAO,
' SELECT * FROM PROCESSOPRODUCAO '+
' WHERE CODPROCESSOPRODUCAO = '+
IntToStr(PROCESSOPRODUCAOCODPROCESSOPRODUCAO.AsInteger));
end;
{ *************************************************************************** }
procedure TFProcessosProducao.BotaoAlterar1DepoisAtividade(Sender: TObject);
begin
FNovoProcessoProducao.ShowModal;
AtualizaConsulta;
end;
{ *************************************************************************** }
procedure TFProcessosProducao.BotaoCadastrar1AntesAtividade(Sender: TObject);
begin
FNovoProcessoProducao := TFNovoProcessoProducao.criarSDI(Self, '', True);
end;
{ *************************************************************************** }
procedure TFProcessosProducao.BotaoCadastrar1DepoisAtividade(Sender: TObject);
begin
FNovoProcessoProducao.ShowModal;
AtualizaConsulta;
end;
{ *************************************************************************** }
procedure TFProcessosProducao.BotaoConsultar1AntesAtividade(Sender: TObject);
begin
FNovoProcessoProducao := TFNovoProcessoProducao.criarSDI(Self, '', True);
end;
{ *************************************************************************** }
procedure TFProcessosProducao.BotaoConsultar1Atividade(Sender: TObject);
begin
AdicionaSQLAbreTabela(FNovoProcessoProducao.PROCESSOPRODUCAO,
' SELECT * FROM PROCESSOPRODUCAO '+
' WHERE CODPROCESSOPRODUCAO = '+
IntToStr(PROCESSOPRODUCAOCODPROCESSOPRODUCAO.AsInteger));
end;
{ *************************************************************************** }
procedure TFProcessosProducao.BotaoConsultar1DepoisAtividade(Sender: TObject);
begin
FNovoProcessoProducao.BotaoGravar.Enabled := False;
FNovoProcessoProducao.BotaoCancelar.Enabled := True;
FNovoProcessoProducao.ShowModal;
AtualizaConsulta;
end;
procedure TFProcessosProducao.BotaoExcluir1Click(Sender: TObject);
begin
end;
{ *************************************************************************** }
procedure TFProcessosProducao.BotaoExcluir1DepoisAtividade(Sender: TObject);
begin
FNovoProcessoProducao.Show;
AtualizaConsulta;
end;
{ *************************************************************************** }
procedure TFProcessosProducao.ECodigoExit(Sender: TObject);
begin
AtualizaConsulta;
end;
{ *************************************************************************** }
procedure TFProcessosProducao.ECodigoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
case key of
13 : ECodigoExit(Self);
end;
end;
{ *************************************************************************** }
procedure TFProcessosProducao.EEstagioFimConsulta(Sender: TObject);
begin
end;
{ *************************************************************************** }
procedure TFProcessosProducao.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{ fecha tabelas }
{ chamar a rotina de atualização de menus }
Action := CaFree;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Ações Diversas
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
Initialization
{ *************** Registra a classe para evitar duplicidade ****************** }
RegisterClasses([TFProcessosProducao]);
end.
|
{
Ultibo Text to Binary Tool.
Copyright (C) 2023 - SoftOz Pty Ltd.
Arch
====
<All>
Boards
======
<All>
Licence
=======
LGPLv2.1 with static linking exception (See COPYING.modifiedLGPL.txt)
Credits
=======
Information for this unit was obtained from:
References
==========
Text to Binary
==============
This tool takes plain text in the form of hex values seperated by spaces and
converts them to a binary output file.
The text to be converted should be in the form:
00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
1F 1E 1D 1C ...
Each pair of characters represents a byte in the binary output.
}
unit Main;
{$mode Delphi}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, ComCtrls,
ExtCtrls;
type
{ TfrmMain }
TfrmMain = class(TForm)
buttonOutput: TButton;
buttonConvert: TButton;
buttonClose: TButton;
editOutput: TLabeledEdit;
memoMain: TMemo;
panelMain: TPanel;
saveMain: TSaveDialog;
statusMain: TStatusBar;
procedure editOutputChange(Sender: TObject);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormHide(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure buttonCloseClick(Sender: TObject);
procedure buttonConvertClick(Sender: TObject);
procedure buttonOutputClick(Sender: TObject);
private
{ Private declarations }
FOutput:String;
public
{ Public declarations }
function Convert:Boolean;
end;
var
frmMain: TfrmMain;
implementation
{==============================================================================}
{==============================================================================}
{$R *.lfm}
{ TfrmMain }
function TfrmMain.Convert:Boolean;
var
Data:Byte;
Value:String;
Offset:Integer;
Source:String;
Dest:TMemoryStream;
begin
Result:=False;
if Length(Trim(editOutput.Text)) = 0 then
Exit;
try
Source:=Trim(memoMain.Text);
if Length(Source) > 0 then
begin
Dest:=TMemoryStream.Create;
try
Value:='';
Offset:=1;
while Offset <= Length(Source) do
begin
if Source[Offset] = ' ' then
Inc(Offset)
else if Source[Offset] = #10 then
Inc(Offset)
else if Source[Offset] = #13 then
Inc(Offset)
else if Source[Offset] in ['0'..'9','a'..'f','A'..'F'] then
begin
Value:=Value + Source[Offset];
Inc(Offset);
if Length(Value) = 2 then
begin
Data:=StrToInt('$' + Value);
Dest.WriteByte(Data);
Value:='';
end;
end
else
Exit;
end;
Dest.SaveToFile(Trim(editOutput.Text));
Result:=True;
finally
Dest.Free;
end;
end;
except
// Failed
end;
end;
{==============================================================================}
{==============================================================================}
procedure TfrmMain.FormCreate(Sender: TObject);
begin
FOutput:='';
end;
{==============================================================================}
procedure TfrmMain.FormDestroy(Sender: TObject);
begin
// Nothing
end;
{==============================================================================}
procedure TfrmMain.FormShow(Sender: TObject);
var
Scale:Double;
begin
editOutput.Text:=FOutput;
// Adjust Controls
if editOutput.Height > buttonOutput.Height then
begin
buttonOutput.Height:=editOutput.Height;
buttonOutput.Width:=editOutput.Height;
buttonOutput.Top:=editOutput.Top + ((editOutput.Height - buttonOutput.Height) div 2);
end
else
begin
buttonOutput.Height:=editOutput.Height + 2;
buttonOutput.Width:=editOutput.Height + 2;
buttonOutput.Top:=editOutput.Top - 1;
end;
if editOutput.Height > buttonConvert.Height then
begin
buttonConvert.Height:=editOutput.Height;
buttonConvert.Top:=editOutput.Top + ((editOutput.Height - buttonConvert.Height) div 2);
end
else
begin
buttonConvert.Height:=editOutput.Height + 2;
buttonConvert.Top:=editOutput.Top - 1;
end;
if editOutput.Height > buttonClose.Height then
begin
buttonClose.Height:=editOutput.Height;
buttonClose.Top:=editOutput.Top + ((editOutput.Height - buttonClose.Height) div 2);
end
else
begin
buttonClose.Height:=editOutput.Height + 2;
buttonClose.Top:=editOutput.Top - 1;
end;
// Check PixelsPerInch
if PixelsPerInch > 96 then
begin
// Calculate Scale
Scale:=(PixelsPerInch / 96);
// Disable Anchors}
editOutput.Anchors:=[akLeft,akTop];
buttonOutput.Anchors:=[akLeft,akTop];
buttonConvert.Anchors:=[akLeft,akTop];
buttonClose.Anchors:=[akLeft,akTop];
// Resize Form
Width:=Trunc(Width * Scale);
Height:=Trunc(Height * Scale);
// Move Controls
editOutput.Left:=panelMain.Width - Trunc(570 * Scale); {650 - 80 = 570}
buttonOutput.Left:=panelMain.Width - Trunc(261 * Scale); {650 - 389 = 261}
buttonConvert.Left:=panelMain.Width - Trunc(222 * Scale); {650 - 428 = 222}
buttonClose.Left:=panelMain.Width - Trunc(137 * Scale); {650 - 513 = 137}
// Enable Anchors
editOutput.Anchors:=[akLeft,akRight,akBottom];
buttonOutput.Anchors:=[akRight,akBottom];
buttonConvert.Anchors:=[akRight,akBottom];
buttonClose.Anchors:=[akRight,akBottom];
end;
end;
{==============================================================================}
procedure TfrmMain.FormHide(Sender: TObject);
begin
// Nothing
end;
{==============================================================================}
procedure TfrmMain.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
// Nothing
end;
{==============================================================================}
{==============================================================================}
procedure TfrmMain.editOutputChange(Sender: TObject);
begin
FOutput:=editOutput.Text;
end;
{==============================================================================}
procedure TfrmMain.buttonOutputClick(Sender: TObject);
begin
saveMain.FileName:=FOutput;
saveMain.InitialDir:=ExtractFileDir(Application.ExeName);
{$IFDEF WINDOWS}
saveMain.Filter:='All Files (*.*)|*.*';
{$ENDIF}
{$IFDEF LINUX}
saveMain.Filter:='All Files (*.*)|*';
{$ENDIF}
if saveMain.Execute then
begin
editOutput.Text:=saveMain.FileName;
end;
end;
{==============================================================================}
procedure TfrmMain.buttonConvertClick(Sender: TObject);
begin
if Convert then
begin
MessageDlg('Conversion Successful',mtInformation,[mbOk],0);
end
else
begin
MessageDlg('Conversion Failed',mtInformation,[mbOk],0);
end;
end;
{==============================================================================}
procedure TfrmMain.buttonCloseClick(Sender: TObject);
begin
Application.Terminate;
end;
{==============================================================================}
{==============================================================================}
end.
|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Data.DBXInterbaseMetaDataWriter;
interface
uses
Data.DBXCommonTable,
Data.DBXMetaDataReader,
Data.DBXMetaDataWriter,
Data.DBXPlatform;
type
TDBXInterbaseCustomMetaDataWriter = class(TDBXBaseMetaDataWriter)
protected
procedure MakeSqlDataType(const Buffer: TDBXStringBuffer; const DataType: TDBXDataTypeDescription; const ColumnRow: TDBXTableRow; const Overrides: TDBXInt32s); override;
private
procedure FormatStringType(const Buffer: TDBXStringBuffer; const DataType: TDBXDataTypeDescription; const ColumnRow: TDBXTableRow; const Overrides: TDBXInt32s);
procedure FormatBlobType(const Buffer: TDBXStringBuffer; const DataType: TDBXDataTypeDescription; const ColumnRow: TDBXTableRow; const Overrides: TDBXInt32s);
function UnicodeSpecificationRequired(const ColumnRow: TDBXTableRow): Boolean;
end;
TDBXInterbaseMetaDataWriter = class(TDBXInterbaseCustomMetaDataWriter)
public
constructor Create;
procedure Open; override;
protected
function IsIndexNamesGlobal: Boolean; override;
function IsSerializedIsolationSupported: Boolean; override;
function IsMixed_DDL_DML_Supported: Boolean; override;
function GetAlterTableSupport: Integer; override;
function GetSqlKeyGeneratedIndexName: UnicodeString; override;
function IsSchemasSupported: Boolean; override;
end;
implementation
uses
Data.DBXCommon,
Data.DBXInterbaseMetaDataReader,
Data.DBXMetaDataNames,
System.SysUtils;
procedure TDBXInterbaseCustomMetaDataWriter.MakeSqlDataType(const Buffer: TDBXStringBuffer; const DataType: TDBXDataTypeDescription; const ColumnRow: TDBXTableRow; const Overrides: TDBXInt32s);
begin
case DataType.DbxDataType of
TDBXDataTypes.AnsiStringType:
FormatStringType(Buffer, DataType, ColumnRow, Overrides);
TDBXDataTypes.BlobType:
FormatBlobType(Buffer, DataType, ColumnRow, Overrides);
else
inherited MakeSqlDataType(Buffer, DataType, ColumnRow, Overrides);
end;
end;
procedure TDBXInterbaseCustomMetaDataWriter.FormatStringType(const Buffer: TDBXStringBuffer; const DataType: TDBXDataTypeDescription; const ColumnRow: TDBXTableRow; const Overrides: TDBXInt32s);
var
Precision: Integer;
begin
Precision := Overrides[0];
if Precision < 0 then
Precision := ColumnRow.Value[TDBXColumnsIndex.Precision].GetInt32(-1);
if DataType.FixedLength then
Buffer.Append('CHAR')
else
Buffer.Append('VARCHAR');
if Precision > 0 then
begin
Buffer.Append('(');
Buffer.Append(IntToStr(Precision));
Buffer.Append(')');
end;
if UnicodeSpecificationRequired(ColumnRow) then
Buffer.Append(' CHARACTER SET UNICODE_FSS');
end;
procedure TDBXInterbaseCustomMetaDataWriter.FormatBlobType(const Buffer: TDBXStringBuffer; const DataType: TDBXDataTypeDescription; const ColumnRow: TDBXTableRow; const Overrides: TDBXInt32s);
var
Subtype: UnicodeString;
UnicodeSpecRequired: Boolean;
begin
Subtype := '0';
UnicodeSpecRequired := False;
case ColumnRow.Value[TDBXColumnsIndex.DbxDataType].GetInt32(TDBXDataTypes.BlobType) of
TDBXDataTypes.AnsiStringType:
begin
UnicodeSpecRequired := UnicodeSpecificationRequired(ColumnRow);
Subtype := '1';
end;
TDBXDataTypes.WideStringType:
begin
UnicodeSpecRequired := UnicodeSpecificationRequired(ColumnRow);
Subtype := 'TEXT';
end;
end;
Buffer.Append('BLOB SUB_TYPE ');
Buffer.Append(Subtype);
if UnicodeSpecRequired then
Buffer.Append(' CHARACTER SET UNICODE_FSS');
end;
function TDBXInterbaseCustomMetaDataWriter.UnicodeSpecificationRequired(const ColumnRow: TDBXTableRow): Boolean;
begin
Result := ColumnRow.Value[TDBXColumnsIndex.IsUnicode].GetBoolean;
end;
constructor TDBXInterbaseMetaDataWriter.Create;
begin
inherited Create;
Open;
end;
procedure TDBXInterbaseMetaDataWriter.Open;
begin
if FReader = nil then
FReader := TDBXInterbaseMetaDataReader.Create;
end;
function TDBXInterbaseMetaDataWriter.IsIndexNamesGlobal: Boolean;
begin
Result := True;
end;
function TDBXInterbaseMetaDataWriter.IsSerializedIsolationSupported: Boolean;
begin
Result := False;
end;
function TDBXInterbaseMetaDataWriter.IsMixed_DDL_DML_Supported: Boolean;
begin
Result := False;
end;
function TDBXInterbaseMetaDataWriter.GetAlterTableSupport: Integer;
begin
Result := TDBXAlterTableOperation.DropColumn or TDBXAlterTableOperation.AddColumn or TDBXAlterTableOperation.ChangeColumnType or TDBXAlterTableOperation.ChangeColumnPosition or TDBXAlterTableOperation.RenameColumn;
end;
function TDBXInterbaseMetaDataWriter.GetSqlKeyGeneratedIndexName: UnicodeString;
begin
Result := '';
end;
function TDBXInterbaseMetaDataWriter.IsSchemasSupported: Boolean;
begin
Result := False;
end;
end.
|
unit JD.Weather.Intf;
interface
{$MINENUMSIZE 4}
uses
Winapi.Windows,
DateUtils,
System.SysUtils,
System.Classes,
System.Generics.Collections,
IdHTTP;
const
clOrange = $00003AB3;
clLightOrange = $002F73FF;
clIceBlue = $00FFFFD2;
clLightRed = $00B0B0FF;
type
IWeatherProps = interface;
IWeatherGraphic = interface;
IWeatherLocation = interface;
IWeatherForecast = interface;
IWeatherAlertZone = interface;
IWeatherAlertZones = interface;
IWeatherStormVertex = interface;
IWeatherStormVerticies = interface;
IWeatherAlertStorm = interface;
IWeatherAlert = interface;
IWeatherAlerts = interface;
IWeatherMaps = interface;
IWeatherSupport = interface;
IWeatherURLs = interface;
IWeatherMultiInfo = interface;
IWeatherServiceInfo = interface;
IWeatherService = interface;
IWeatherServices = interface;
IWeatherMultiService = interface;
IJDWeather = interface;
TWeatherGraphic = class;
TWeatherInfoType = (wiConditions, wiAlerts, wiForecastSummary,
wiForecastHourly, wiForecastDaily, wiMaps, wiAlmanac, wiAstronomy,
wiHurricane, wiHistory, wiPlanner, wiStation, wiLocation);
TWeatherInfoTypes = set of TWeatherInfoType;
TWeatherLogoType = (ltColor, ltColorInvert, ltColorWide, ltColorInvertWide,
ltColorLeft, ltColorRight);
TWeatherLogoTypes = set of TWeatherLogoType;
TLogoArray = array[TWeatherLogoType] of IWeatherGraphic;
TWeatherLocationType = (wlZip, wlCityState, wlCoords, wlAutoIP, wlCityCode,
wlCountryCity, wlAirportCode, wlPWS);
TWeatherLocationTypes = set of TWeatherLocationType;
TWeatherUnits = (wuKelvin, wuImperial, wuMetric);
TWeatherUnitsSet = set of TWeatherUnits;
TWeatherForecastType = (ftSummary, ftHourly, ftDaily);
TWeatherForecastTypes = set of TWeatherForecastType;
TWeatherPropType = (wpIcon, wpCaption, wpDescription, wpDetails, wpURL,
wpStation, wpPropsMin, wpPropsMax, wpTemp, wpTempMin, wpTempMax,
wpFeelsLike, wpFeelsLikeSun, wpFeelsLikeShade, wpWindDir, wpWindSpeed,
wpWindGust, wpWindChill, wpHeatIndex, wpPressure, wpPressureGround,
wpPressureSea, wpHumidity, wpDewPoint, wpVisibility, wpSolarRad, wpUVIndex,
wpCloudCover, wpPrecipAmt, wpRainAmt, wpSnowAmt, wpIceAmt, wpSleetAmt,
wpFogAmt, wpStormAmt, wpPrecipPred, wpRainPred, wpSnowPred, wpIcePred,
wpSleetPred, wpFogPred, wpStormPred, wpWetBulb, wpCeiling, wpSunrise,
wpSunset, wpDaylight);
TWeatherPropTypes = set of TWeatherPropType;
TWeatherAlertType = (waNone, waHurricaneStat, waTornadoWarn, waTornadoWatch, waSevThundWarn,
waSevThundWatch, waWinterAdv, waFloodWarn, waFloodWatch, waHighWind, waSevStat,
waHeatAdv, waFogAdv, waSpecialStat, waFireAdv, waVolcanicStat, waHurricaneWarn,
waRecordSet, waPublicRec, waPublicStat);
TWeatherAlertTypes = set of TWeatherAlertType;
TWeatherAlertProp = (apZones, apVerticies, apStorm, apType, apDescription,
apExpires, apMessage, apPhenomena, apSignificance);
TWeatherAlertProps = set of TWeatherAlertProp;
TWeatherAlertPhenomena = (wpWind, wpHeat, wpSmallCraft);
TWeatherMapType = (mpSatellite, mpRadar, mpSatelliteRadar, mpRadarClouds,
mpClouds, mpTemp, mpTempChange, mpSnowCover, mpPrecip, mpAlerts, mpHeatIndex,
mpDewPoint, mpWindChill, mpPressureSea, mpWind,
mpAniSatellite, mpAniRadar, mpAniSatelliteRadar);
TWeatherMapTypes = set of TWeatherMapType;
TWeatherMapFormat = (wfJpg, wfPng, wfGif, wfTiff, wfBmp, wfFlash, wfHtml);
TWeatherMapFormats = set of TWeatherMapFormat;
TMapArray = array[TWeatherMapType] of TWeatherGraphic;
TDayNight = (dnDay, dnNight);
TCloudCode = (ccClear = 0, ccAlmostClear = 1, ccHalfCloudy = 2, ccBroken = 3,
ccOvercast = 4, ccThinClouds = 5, ccFog = 6);
TPrecipCode = (pcNone = 0, pcSlight = 1, pcShowers = 2, pcPrecip = 3, pcThunder = 4);
TPrecipTypeCode = (ptRain = 0, ptSleet = 1, ptSnow = 2);
TTemperature = record
Value: Double;
function GetAsFarenheit: Double;
function GetAsCelsius: Double;
function GetAsStr: String;
function GetAsFarenheitStr: String;
function GetAsCelsiusStr: String;
procedure SetAsFarenheit(const Value: Double);
procedure SetAsCelsius(const Value: Double);
property AsFarenheit: Double read GetAsFarenheit write SetAsFarenheit;
property AsCelsius: Double read GetAsCelsius write SetAsCelsius;
class operator Implicit(const Value: TTemperature): Double;
class operator Implicit(const Value: Double): TTemperature;
end;
TWeatherCode = record
public
DayNight: TDayNight;
Clouds: TCloudCode;
Precip: TPrecipCode;
PrecipType: TPrecipTypeCode;
class operator Implicit(const Value: TWeatherCode): String;
class operator Implicit(const Value: String): TWeatherCode;
class operator Implicit(const Value: TWeatherCode): Integer;
class operator Implicit(const Value: Integer): TWeatherCode;
function Description: String;
function Name: String;
function DayNightStr: String;
end;
TWeatherConditionsEvent = procedure(Sender: TObject; const Conditions: IWeatherProps) of object;
TWeatherForecastEvent = procedure(Sender: TObject; const Forecast: IWeatherForecast) of object;
TWeatherAlertEvent = procedure(Sender: TObject; const Alert: IWeatherAlerts) of object;
TWeatherMapEvent = procedure(Sender: TObject; const Image: IWeatherMaps) of object;
TCreateJDWeather = function(const LibDir: WideString): IJDWeather; stdcall;
TCreateWeatherService = function: IWeatherService; stdcall;
TGetServiceInfo = function: IWeatherServiceInfo; stdcall;
//Common Interface Definitions
IWeatherProps = interface
function GetDateTime: TDateTime;
function GetCaption: WideString;
function GetCeiling: Double;
function GetCloudCover: Double;
function GetDaylight: Double;
function GetDescription: WideString;
function GetDetails: WideString;
function GetDewPoint: Double;
function GetFeelsLike: Double;
function GetFeelsLikeShade: Double;
function GetFeelsLikeSun: Double;
function GetFogAmt: Double;
function GetFogPred: Double;
function GetHeatIndex: Double;
function GetHumidity: Double;
function GetIceAmt: Double;
function GetIcePred: Double;
function GetIcon: IWeatherGraphic;
function GetPrecipAmt: Double;
function GetPrecipPred: Double;
function GetPressure: Double;
function GetPressureGround: Double;
function GetPressureSea: Double;
function GetRainAmt: Double;
function GetRainPred: Double;
function GetSleetAmt: Double;
function GetSleetProd: Double;
function GetSnowAmt: Double;
function GetSnowPred: Double;
function GetSolarRad: Double;
function GetStation: WideString;
function GetStormAmt: Double;
function GetStormPred: Double;
function GetSunrise: TDateTime;
function GetSunset: TDateTime;
function GetTemp: Double;
function GetTempMax: Double;
function GetTempMin: Double;
function GetURL: WideString;
function GetUVIndex: Double;
function GetVisibility: Double;
function GetWetBulb: Double;
function GetWindChill: Double;
function GetWindDir: Double;
function GetWindGusts: Double;
function GetWindSpeed: Double;
procedure AddTo(const AProps: IWeatherProps; const ASupport: TWeatherPropTypes);
procedure CalcAverages;
function Support: TWeatherPropTypes;
function PropCount(const Prop: TWeatherPropType): Integer;
property DateTime: TDateTime read GetDateTime;
property Icon: IWeatherGraphic read GetIcon;
property Caption: WideString read GetCaption;
property Description: WideString read GetDescription;
property Details: WideString read GetDetails;
property URL: WideString read GetURL;
property Station: WideString read GetStation;
//property PropsMin: Boolean read GetPropsMin; //TODO
//property PropsMax: Boolean read GetPropsMax; //TODO
property Temp: Double read GetTemp;
property TempMax: Double read GetTempMax;
property TempMin: Double read GetTempMin;
property FeelsLike: Double read GetFeelsLike;
property FeelsLikeSun: Double read GetFeelsLikeSun;
property FeelsLikeShade: Double read GetFeelsLikeShade;
property WindDir: Double read GetWindDir;
property WindSpeed: Double read GetWindSpeed;
property WindGusts: Double read GetWindGusts;
property WindChill: Double read GetWindChill;
property HeatIndex: Double read GetHeatIndex;
property Pressure: Double read GetPressure;
property PressureGround: Double read GetPressureGround;
property PressureSea: Double read GetPressureSea;
property Humidity: Double read GetHumidity;
property DewPoint: Double read GetDewPoint;
property Visibility: Double read GetVisibility;
property SolarRad: Double read GetSolarRad;
property UVIndex: Double read GetUVIndex;
property CloudCover: Double read GetCloudCover;
property PrecipAmt: Double read GetPrecipAmt;
property RainAmt: Double read GetRainAmt;
property SnowAmt: Double read GetSnowAmt;
property IceAmt: Double read GetIceAmt;
property SleetAmt: Double read GetSleetAmt;
property FogAmt: Double read GetFogAmt;
property StormAmt: Double read GetStormAmt;
property PrecipPred: Double read GetPrecipPred;
property RainPred: Double read GetRainPred;
property SnowPred: Double read GetSnowPred;
property IcePred: Double read GetIcePred;
property SleetPred: Double read GetSleetProd;
property FogPred: Double read GetFogPred;
property StormPred: Double read GetStormPred;
property WetBulb: Double read GetWetBulb;
property Ceiling: Double read GetCeiling;
property Sunrise: TDateTime read GetSunrise;
property Sunset: TDateTime read GetSunset;
property Daylight: Double read GetDaylight;
end;
IWeatherGraphic = interface
function GetExt: WideString;
function GetBase64: WideString;
procedure SetBase64(const Value: WideString);
property Ext: WideString read GetExt;
property Base64: WideString read GetBase64 write SetBase64;
end;
IWeatherLocation = interface
function GetDisplayName: WideString;
function GetCity: WideString;
function GetState: WideString;
function GetStateAbbr: WideString;
function GetCountry: WideString;
function GetCountryAbbr: WideString;
function GetLongitude: Double;
function GetLatitude: Double;
function GetElevation: Double;
function GetZipCode: WideString;
property DisplayName: WideString read GetDisplayName;
property City: WideString read GetCity;
property State: WideString read GetState;
property StateAbbr: WideString read GetStateAbbr;
property Country: WideString read GetCountry;
property CountryAbbr: WideString read GetCountryAbbr;
property Longitude: Double read GetLongitude;
property Latitude: Double read GetLatitude;
property Elevation: Double read GetElevation;
property ZipCode: WideString read GetZipCode;
end;
IWeatherForecast = interface
function GetLocation: IWeatherLocation;
function GetItem(const Index: Integer): IWeatherProps;
function Count: Integer;
function MinTemp: Single;
function MaxTemp: Single;
property Location: IWeatherLocation read GetLocation;
property Items[const Index: Integer]: IWeatherProps read GetItem; default;
end;
IWeatherAlertZone = interface
function GetState: WideString;
function GetZone: WideString;
property State: WideString read GetState;
property Zone: WideString read GetZone;
end;
IWeatherAlertZones = interface
function GetItem(const Index: Integer): IWeatherAlertZone;
function Count: Integer;
property Items[const Index: Integer]: IWeatherAlertZone read GetItem; default;
end;
IWeatherStormVertex = interface
function GetLongitude: Double;
function GetLatitude: Double;
property Longitude: Double read GetLongitude;
property Latitude: Double read GetLatitude;
end;
IWeatherStormVerticies = interface
function GetItem(const Index: Integer): IWeatherStormVertex;
function Count: Integer;
property Items[const Index: Integer]: IWeatherStormVertex read GetItem; default;
end;
IWeatherAlertStorm = interface
function GetDateTime: TDateTime;
function GetDirection: Single;
function GetSpeed: Single;
function GetLongitude: Double;
function GetLatitude: Double;
function GetVerticies: IWeatherStormVerticies;
property DateTime: TDateTime read GetDateTime;
property Direction: Single read GetDirection;
property Speed: Single read GetDirection;
property Longitude: Double read GetLongitude;
property Latitude: Double read GetLatitude;
property Verticies: IWeatherStormVerticies read GetVerticies;
end;
IWeatherAlert = interface
function GetAlertType: TWeatherAlertType;
function GetDescription: WideString;
function GetDateTime: TDateTime;
function GetExpires: TDateTime;
function GetMsg: WideString;
function GetPhenomena: WideString;
function GetSignificance: WideString;
function GetZones: IWeatherAlertZones;
function GetStorm: IWeatherAlertStorm;
property AlertType: TWeatherAlertType read GetAlertType;
property Description: WideString read GetDescription;
property DateTime: TDateTime read GetDateTime;
property Expires: TDateTime read GetExpires;
property Msg: WideString read GetMsg;
property Phenomena: WideString read GetPhenomena;
property Significance: WideString read GetSignificance;
property Zones: IWeatherAlertZones read GetZones;
property Storm: IWeatherAlertStorm read GetStorm;
end;
IWeatherAlerts = interface
function GetItem(const Index: Integer): IWeatherAlert;
function Count: Integer;
property Items[const Index: Integer]: IWeatherAlert read GetItem; default;
end;
IWeatherMaps = interface
function GetMap(const MapType: TWeatherMapType): IWeatherGraphic;
property Maps[const MapType: TWeatherMapType]: IWeatherGraphic read GetMap;
end;
//Service Interface Definitions
IWeatherSupport = interface
function GetSupportedLogos: TWeatherLogoTypes;
function GetSupportedUnits: TWeatherUnitsSet;
function GetSupportedInfo: TWeatherInfoTypes;
function GetSupportedLocations: TWeatherLocationTypes;
function GetSupportedAlerts: TWeatherAlertTypes;
function GetSupportedAlertProps: TWeatherAlertProps;
function GetSupportedConditionProps: TWeatherPropTypes;
function GetSupportedForecasts: TWeatherForecastTypes;
function GetSupportedForecastSummaryProps: TWeatherPropTypes;
function GetSupportedForecastHourlyProps: TWeatherPropTypes;
function GetSupportedForecastDailyProps: TWeatherPropTypes;
function GetSupportedMaps: TWeatherMapTypes;
function GetSupportedMapFormats: TWeatherMapFormats;
property SupportedLogos: TWeatherLogoTypes read GetSupportedLogos;
property SupportedUnits: TWeatherUnitsSet read GetSupportedUnits;
property SupportedInfo: TWeatherInfoTypes read GetSupportedInfo;
property SupportedLocations: TWeatherLocationTypes read GetSupportedLocations;
property SupportedAlerts: TWeatherAlertTypes read GetSupportedAlerts;
property SupportedAlertProps: TWeatherAlertProps read GetSupportedAlertProps;
property SupportedConditionProps: TWeatherPropTypes read GetSupportedConditionProps;
property SupportedForecasts: TWeatherForecastTypes read GetSupportedForecasts;
property SupportedForecastSummaryProps: TWeatherPropTypes read GetSupportedForecastSummaryProps;
property SupportedForecastHourlyProps: TWeatherPropTypes read GetSupportedForecastHourlyProps;
property SupportedForecastDailyProps: TWeatherPropTypes read GetSupportedForecastDailyProps;
property SupportedMaps: TWeatherMapTypes read GetSupportedMaps;
property SupportedMapFormats: TWeatherMapFormats read GetSupportedMapFormats;
end;
IWeatherURLs = interface
function GetMainURL: WideString;
function GetApiURL: WideString;
function GetLoginURL: WideString;
function GetRegisterURL: WideString;
function GetLegalURL: WideString;
property MainURL: WideString read GetMainURL;
property ApiURL: WideString read GetApiURL;
property LoginURL: WideString read GetLoginURL;
property RegisterURL: WideString read GetRegisterURL;
property LegalURL: WideString read GetLegalURL;
end;
IWeatherMultiInfo = interface
function GetConditions: IWeatherProps;
function GetAlerts: IWeatherAlerts;
function GetForecastSummary: IWeatherForecast;
function GetForecastHourly: IWeatherForecast;
function GetForecastDaily: IWeatherForecast;
function GetMaps: IWeatherMaps;
property Conditions: IWeatherProps read GetConditions;
property Alerts: IWeatherAlerts read GetAlerts;
property ForecastSummary: IWeatherForecast read GetForecastSummary;
property ForecastHourly: IWeatherForecast read GetForecastHourly;
property ForecastDaily: IWeatherForecast read GetForecastDaily;
property Maps: IWeatherMaps read GetMaps;
end;
IWeatherServiceInfo = interface
function GetCaption: WideString;
function GetName: WideString;
function GetUID: WideString;
function GetURLs: IWeatherURLs;
function GetSupport: IWeatherSupport;
function GetLogo(const LT: TWeatherLogoType): IWeatherGraphic;
property Caption: WideString read GetCaption;
property Name: WideString read GetName;
property UID: WideString read GetUID;
property Support: IWeatherSupport read GetSupport;
property URLs: IWeatherURLs read GetURLs;
end;
IWeatherService = interface
function GetKey: WideString;
procedure SetKey(const Value: WideString);
function GetLocationType: TWeatherLocationType;
procedure SetLocationType(const Value: TWeatherLocationType);
function GetLocationDetail1: WideString;
procedure SetLocationDetail1(const Value: WideString);
function GetLocationDetail2: WideString;
procedure SetLocationDetail2(const Value: WideString);
function GetUnits: TWeatherUnits;
procedure SetUnits(const Value: TWeatherUnits);
function GetInfo: IWeatherServiceInfo;
function GetMultiple(const Info: TWeatherInfoTypes): IWeatherMultiInfo;
function GetLocation: IWeatherLocation;
function GetConditions: IWeatherProps;
function GetAlerts: IWeatherAlerts;
function GetForecastSummary: IWeatherForecast;
function GetForecastHourly: IWeatherForecast;
function GetForecastDaily: IWeatherForecast;
function GetMaps: IWeatherMaps;
property Info: IWeatherServiceInfo read GetInfo;
property Key: WideString read GetKey write SetKey;
property LocationType: TWeatherLocationType read GetLocationType write SetLocationType;
property LocationDetail1: WideString read GetLocationDetail1 write SetLocationDetail1;
property LocationDetail2: WideString read GetLocationDetail2 write SetLocationDetail2;
property Units: TWeatherUnits read GetUnits write SetUnits;
end;
IWeatherServices = interface
function GetItem(const Index: Integer): IWeatherService;
function Count: Integer;
procedure LoadServices(const Dir: WideString);
property Items[const Index: Integer]: IWeatherService read GetItem; default;
end;
IWeatherMultiService = interface
function GetItem(const Index: Integer): IWeatherService;
function GetCombinedConditions: IWeatherProps;
function GetCombinedAlerts: IWeatherAlerts;
function GetCombinedForecastSummary: IWeatherForecast;
function GetCombinedForecastHourly: IWeatherForecast;
function GetCombinedForecastDaily: IWeatherForecast;
procedure Add(const Svc: IWeatherService);
procedure Delete(const Index: Integer);
procedure Clear;
function Count: Integer;
property Items[const Index: Integer]: IWeatherService read GetItem; default;
end;
TWeatherMultiService = class(TInterfacedObject, IWeatherMultiService)
private
FItems: TList<IWeatherService>;
public
constructor Create;
destructor Destroy; override;
public
function GetItem(const Index: Integer): IWeatherService;
function GetCombinedConditions: IWeatherProps;
function GetCombinedAlerts: IWeatherAlerts;
function GetCombinedForecastSummary: IWeatherForecast;
function GetCombinedForecastHourly: IWeatherForecast;
function GetCombinedForecastDaily: IWeatherForecast;
procedure Add(const Svc: IWeatherService);
procedure Delete(const Index: Integer);
procedure Clear;
function Count: Integer;
property Items[const Index: Integer]: IWeatherService read GetItem; default;
end;
IJDWeather = interface
function GetServices: IWeatherServices;
procedure SetLocationType(const Value: TWeatherLocationType);
function GetLocationDetail1: WideString;
function GetLocationType: TWeatherLocationType;
procedure SetLocationDetail1(const Value: WideString);
function GetLocationDetail2: WideString;
procedure SetLocationDetail2(const Value: WideString);
function GetUnits: TWeatherUnits;
procedure SetUnits(const Value: TWeatherUnits);
property Services: IWeatherServices read GetServices;
property LocationType: TWeatherLocationType read GetLocationType write SetLocationType;
property LocationDetail1: WideString read GetLocationDetail1 write SetLocationDetail1;
property LocationDetail2: WideString read GetLocationDetail2 write SetLocationDetail2;
property Units: TWeatherUnits read GetUnits write SetUnits;
end;
{ Interface Implementation Objects }
TWeatherProps = class(TInterfacedObject, IWeatherProps)
public
FSupport: TWeatherPropTypes;
FCounts: Array[TWeatherPropType] of Integer;
FDateTime: TDateTime;
FIcon: TWeatherGraphic;
FCaption: WideString;
FDescription: WideString;
FDetails: WideString;
FURL: WideString;
FStation: WideString;
FTemp: Double;
FTempMax: Double;
FTempMin: Double;
FFeelsLike: Double;
FFeelsLikeSun: Double;
FFeelsLikeShade: Double;
FWindDir: Double;
FWindSpeed: Double;
FWindGusts: Double;
FWindChill: Double;
FHeatIndex: Double;
FPressure: Double;
FPressureGround: Double;
FPressureSea: Double;
FHumidity: Double;
FDewPoint: Double;
FVisibility: Double;
FSolarRad: Double;
FUVIndex: Double;
FCloudCover: Double;
FPrecipAmt: Double;
FRainAmt: Double;
FSnowAmt: Double;
FIceAmt: Double;
FSleetAmt: Double;
FFogAmt: Double;
FStormAmt: Double;
FPrecipPred: Double;
FRainPred: Double;
FSnowPred: Double;
FIcePred: Double;
FSleetPred: Double;
FFogPred: Double;
FStormPred: Double;
FWetBulb: Double;
FCeiling: Double;
FSunrise: TDateTime;
FSunset: TDateTime;
FDaylight: Double;
public
constructor Create;
destructor Destroy; override;
public
function GetDateTime: TDateTime;
function GetCaption: WideString;
function GetCeiling: Double;
function GetCloudCover: Double;
function GetDaylight: Double;
function GetDescription: WideString;
function GetDetails: WideString;
function GetDewPoint: Double;
function GetFeelsLike: Double;
function GetFeelsLikeShade: Double;
function GetFeelsLikeSun: Double;
function GetFogAmt: Double;
function GetFogPred: Double;
function GetHeatIndex: Double;
function GetHumidity: Double;
function GetIceAmt: Double;
function GetIcePred: Double;
function GetIcon: IWeatherGraphic;
function GetPrecipAmt: Double;
function GetPrecipPred: Double;
function GetPressure: Double;
function GetPressureGround: Double;
function GetPressureSea: Double;
function GetRainAmt: Double;
function GetRainPred: Double;
function GetSleetAmt: Double;
function GetSleetProd: Double;
function GetSnowAmt: Double;
function GetSnowPred: Double;
function GetSolarRad: Double;
function GetStation: WideString;
function GetStormAmt: Double;
function GetStormPred: Double;
function GetSunrise: TDateTime;
function GetSunset: TDateTime;
function GetTemp: Double;
function GetTempMax: Double;
function GetTempMin: Double;
function GetURL: WideString;
function GetUVIndex: Double;
function GetVisibility: Double;
function GetWetBulb: Double;
function GetWindChill: Double;
function GetWindDir: Double;
function GetWindGusts: Double;
function GetWindSpeed: Double;
procedure AddTo(const AProps: IWeatherProps; const ASupport: TWeatherPropTypes);
procedure CalcAverages;
function Support: TWeatherPropTypes;
function PropCount(const Prop: TWeatherPropType): Integer;
property DateTime: TDateTime read GetDateTime;
property Icon: IWeatherGraphic read GetIcon;
property Caption: WideString read GetCaption;
property Description: WideString read GetDescription;
property Details: WideString read GetDetails;
property URL: WideString read GetURL;
property Station: WideString read GetStation;
//property PropsMin: Boolean read GetPropsMin; //TODO
//property PropsMax: Boolean read GetPropsMax; //TODO
property Temp: Double read GetTemp;
property TempMax: Double read GetTempMax;
property TempMin: Double read GetTempMin;
property FeelsLike: Double read GetFeelsLike;
property FeelsLikeSun: Double read GetFeelsLikeSun;
property FeelsLikeShade: Double read GetFeelsLikeShade;
property WindDir: Double read GetWindDir;
property WindSpeed: Double read GetWindSpeed;
property WindGusts: Double read GetWindGusts;
property WindChill: Double read GetWindChill;
property HeatIndex: Double read GetHeatIndex;
property Pressure: Double read GetPressure;
property PressureGround: Double read GetPressureGround;
property PressureSea: Double read GetPressureSea;
property Humidity: Double read GetHumidity;
property DewPoint: Double read GetDewPoint;
property Visibility: Double read GetVisibility;
property SolarRad: Double read GetSolarRad;
property UVIndex: Double read GetUVIndex;
property CloudCover: Double read GetCloudCover;
property PrecipAmt: Double read GetPrecipAmt;
property RainAmt: Double read GetRainAmt;
property SnowAmt: Double read GetSnowAmt;
property IceAmt: Double read GetIceAmt;
property SleetAmt: Double read GetSleetAmt;
property FogAmt: Double read GetFogAmt;
property StormAmt: Double read GetStormAmt;
property PrecipPred: Double read GetPrecipPred;
property RainPred: Double read GetRainPred;
property SnowPred: Double read GetSnowPred;
property IcePred: Double read GetIcePred;
property SleetPred: Double read GetSleetProd;
property FogPred: Double read GetFogPred;
property StormPred: Double read GetStormPred;
property WetBulb: Double read GetWetBulb;
property Ceiling: Double read GetCeiling;
property Sunrise: TDateTime read GetSunrise;
property Sunset: TDateTime read GetSunset;
property Daylight: Double read GetDaylight;
end;
TWeatherGraphic = class(TInterfacedObject, IWeatherGraphic)
private
FStream: TStringStream;
FExt: WideString;
public
constructor Create; overload;
constructor Create(AStream: TStream); overload;
constructor Create(AFilename: WideString); overload;
destructor Destroy; override;
public
function GetExt: WideString;
function GetBase64: WideString;
procedure SetBase64(const Value: WideString);
property Ext: WideString read GetExt;
property Base64: WideString read GetBase64 write SetBase64;
end;
TWeatherLocation = class(TInterfacedObject, IWeatherLocation)
public
FDisplayName: WideString;
FCity: WideString;
FState: WideString;
FStateAbbr: WideString;
FCountry: WideString;
FCountryAbbr: WideString;
FLongitude: Double;
FLatitude: Double;
FElevation: Double;
FZipCode: WideString;
public
constructor Create;
destructor Destroy; override;
public
function GetDisplayName: WideString;
function GetCity: WideString;
function GetState: WideString;
function GetStateAbbr: WideString;
function GetCountry: WideString;
function GetCountryAbbr: WideString;
function GetLongitude: Double;
function GetLatitude: Double;
function GetElevation: Double;
function GetZipCode: WideString;
property DisplayName: WideString read GetDisplayName;
property City: WideString read GetCity;
property State: WideString read GetState;
property StateAbbr: WideString read GetStateAbbr;
property Country: WideString read GetCountry;
property CountryAbbr: WideString read GetCountryAbbr;
property Longitude: Double read GetLongitude;
property Latitude: Double read GetLatitude;
property Elevation: Double read GetElevation;
property ZipCode: WideString read GetZipCode;
end;
TWeatherForecast = class(TInterfacedObject, IWeatherForecast)
public
FItems: TList<IWeatherProps>;
FLocation: TWeatherLocation;
procedure Clear;
public
constructor Create;
destructor Destroy; override;
public
function GetLocation: IWeatherLocation;
function GetItem(const Index: Integer): IWeatherProps;
function Count: Integer;
function MinTemp: Single;
function MaxTemp: Single;
property Location: IWeatherLocation read GetLocation;
property Items[const Index: Integer]: IWeatherProps read GetItem; default;
end;
TWeatherStormVertex = class(TInterfacedObject, IWeatherStormVertex)
public
FLongitude: Double;
FLatitude: Double;
public
function GetLongitude: Double;
function GetLatitude: Double;
property Longitude: Double read GetLongitude;
property Latitude: Double read GetLatitude;
end;
TWeatherStormVerticies = class(TInterfacedObject, IWeatherStormVerticies)
public
FItems: TList<IWeatherStormVertex>;
procedure Clear;
public
constructor Create;
destructor Destroy; override;
public
function GetItem(const Index: Integer): IWeatherStormVertex;
function Count: Integer;
property Items[const Index: Integer]: IWeatherStormVertex read GetItem; default;
end;
TWeatherAlertStorm = class(TInterfacedObject, IWeatherAlertStorm)
public
FDateTime: TDateTime;
FDirection: Single;
FSpeed: Single;
FLongitude: Double;
FLatitude: Double;
FVerticies: TWeatherStormVerticies;
public
constructor Create;
destructor Destroy; override;
public
function GetDateTime: TDateTime;
function GetDirection: Single;
function GetSpeed: Single;
function GetLongitude: Double;
function GetLatitude: Double;
function GetVerticies: IWeatherStormVerticies;
property DateTime: TDateTime read GetDateTime;
property Direction: Single read GetDirection;
property Speed: Single read GetDirection;
property Longitude: Double read GetLongitude;
property Latitude: Double read GetLatitude;
property Verticies: IWeatherStormVerticies read GetVerticies;
end;
TWeatherAlertZone = class(TInterfacedObject, IWeatherAlertZone)
public
FState: WideString;
FZone: WideString;
public
function GetState: WideString;
function GetZone: WideString;
property State: WideString read GetState;
property Zone: WideString read GetZone;
end;
TWeatherAlertZones = class(TInterfacedObject, IWeatherAlertZones)
public
FItems: TList<TWeatherAlertZone>;
procedure Clear;
public
constructor Create;
destructor Destroy; override;
public
function GetItem(const Index: Integer): IWeatherAlertZone;
function Count: Integer;
property Items[const Index: Integer]: IWeatherAlertZone read GetItem; default;
end;
TWeatherAlert = class(TInterfacedObject, IWeatherAlert)
public
FAlertType: TWeatherAlertType;
FDescription: WideString;
FDateTime: TDateTime;
FExpires: TDateTime;
FMsg: WideString;
FPhenomena: WideString;
FSignificance: WideString;
FZones: TWeatherAlertZones;
FStorm: TWeatherAlertStorm;
public
constructor Create;
destructor Destroy; override;
public
function GetAlertType: TWeatherAlertType;
function GetDescription: WideString;
function GetDateTime: TDateTime;
function GetExpires: TDateTime;
function GetMsg: WideString;
function GetPhenomena: WideString;
function GetSignificance: WideString;
function GetZones: IWeatherAlertZones;
function GetStorm: IWeatherAlertStorm;
property AlertType: TWeatherAlertType read GetAlertType;
property Description: WideString read GetDescription;
property DateTime: TDateTime read GetDateTime;
property Expires: TDateTime read GetExpires;
property Msg: WideString read GetMsg;
property Phenomena: WideString read GetPhenomena;
property Significance: WideString read GetSignificance;
property Zones: IWeatherAlertZones read GetZones;
property Storm: IWeatherAlertStorm read GetStorm;
end;
TWeatherAlerts = class(TInterfacedObject, IWeatherAlerts)
public
FItems: TList<IWeatherAlert>;
procedure Clear;
public
constructor Create;
destructor Destroy; override;
public
function GetItem(const Index: Integer): IWeatherAlert;
function Count: Integer;
property Items[const Index: Integer]: IWeatherAlert read GetItem; default;
end;
TWeatherMaps = class(TInterfacedObject, IWeatherMaps)
public
FMaps: TMapArray;
public
constructor Create;
destructor Destroy; override;
public
function GetMap(const MapType: TWeatherMapType): IWeatherGraphic;
property Maps[const MapType: TWeatherMapType]: IWeatherGraphic read GetMap;
end;
TWeatherMultiInfo = class(TInterfacedObject, IWeatherMultiInfo)
private
FConditions: IWeatherProps;
FAlerts: TWeatherAlerts;
FForecastSummary: TWeatherForecast;
FForecastHourly: TWeatherForecast;
FForecastDaily: TWeatherForecast;
FMaps: IWeatherMaps;
public
constructor Create; virtual;
destructor Destroy; override;
procedure SetAll(Con: IWeatherProps; Alr: TWeatherAlerts;
Fos, Foh, Fod: TWeatherForecast; Map: IWeatherMaps);
public
function GetConditions: IWeatherProps;
function GetAlerts: IWeatherAlerts;
function GetForecastSummary: IWeatherForecast;
function GetForecastHourly: IWeatherForecast;
function GetForecastDaily: IWeatherForecast;
function GetMaps: IWeatherMaps;
property Conditions: IWeatherProps read GetConditions;
property Alerts: IWeatherAlerts read GetAlerts;
property ForecastSummary: IWeatherForecast read GetForecastSummary;
property ForecastHourly: IWeatherForecast read GetForecastHourly;
property ForecastDaily: IWeatherForecast read GetForecastDaily;
property Maps: IWeatherMaps read GetMaps;
end;
TWeatherServiceBase = class(TInterfacedObject)
private
//FModule: HMODULE;
FKey: WideString;
FWeb: TIdHTTP;
FLocationType: TWeatherLocationType;
FLocationDetail1: WideString;
FLocationDetail2: WideString;
FUnits: TWeatherUnits;
public
constructor Create; virtual;
destructor Destroy; override;
property Web: TIdHTTP read FWeb;
public
//function GetModule: HMODULE;
//procedure SetModule(const Value: HMODULE);
function GetKey: WideString;
procedure SetKey(const Value: WideString);
function GetLocationType: TWeatherLocationType;
procedure SetLocationType(const Value: TWeatherLocationType);
function GetLocationDetail1: WideString;
procedure SetLocationDetail1(const Value: WideString);
function GetLocationDetail2: WideString;
procedure SetLocationDetail2(const Value: WideString);
function GetUnits: TWeatherUnits;
procedure SetUnits(const Value: TWeatherUnits);
//property Module: HMODULE read GetModule write SetModule;
property Key: WideString read GetKey write SetKey;
property LocationType: TWeatherLocationType read GetLocationType write SetLocationType;
property LocationDetail1: WideString read GetLocationDetail1 write SetLocationDetail1;
property LocationDetail2: WideString read GetLocationDetail2 write SetLocationDetail2;
property Units: TWeatherUnits read GetUnits write SetUnits;
{
The following must be implemented in the inherited class...
Refer to WUnderground.dpr for a sample implementation...
function GetUID: WideString;
function GetCaption: WideString;
function GetURLs: IWeatherURLs;
function Support: IWeatherSupport;
function GetMultiple(const Info: TWeatherInfoTypes): IWeatherMultiInfo;
function GetConditions: IWeatherConditions;
function GetAlerts: IWeatherAlerts;
function GetForecastSummary: IWeatherForecast;
function GetForecastHourly: IWeatherForecast;
function GetForecastDaily: IWeatherForecast;
function GetMaps: IWeatherMaps;
property UID: WideString read GetUID;
property Caption: WideString read GetCaption;
property URLs: IWeatherURLs read GetURLs;
}
end;
function ResourceExists(const Name, ResType: String): Boolean;
{$IFDEF USE_VCL}
function TempColor(const Temp: Single): TColor;
{$ENDIF}
///<summary>
/// Converts a degree angle to a cardinal direction string
///</summary>
function DegreeToDir(const D: Single): String;
///<summary>
/// Converts an epoch integer to local TDateTime
///</summary>
function EpochLocal(const Value: Integer): TDateTime; overload;
///<summary>
/// Converts an epoch string to local TDateTime
///</summary>
function EpochLocal(const Value: String): TDateTime; overload;
function LocalDateTimeFromUTCDateTime(const UTCDateTime: TDateTime): TDateTime;
function WeatherUnitsToStr(const Value: TWeatherUnits): String;
function WeatherMapFormatToStr(const Value: TWeatherMapFormat): String;
function WeatherMapTypeToStr(const Value: TWeatherMapType): String;
//function WeatherForecastPropToStr(const Value: TWeatherForecastProp): String;
function WeatherForecastTypeToStr(const Value: TWeatherForecastType): String;
function WeatherPropToStr(const Value: TWeatherPropType): String;
function WeatherAlertPropToStr(const Value: TWeatherAlertProp): String;
function WeatherAlertTypeToStr(const Value: TWeatherAlertType): String;
//function WeatherConditionPropToStr(const Value: TWeatherConditionsProp): String;
function WeatherInfoTypeToStr(const Value: TWeatherInfoType): String;
function WeatherLocationTypeToStr(const Value: TWeatherLocationType): String;
implementation
function ResourceExists(const Name, ResType: String): Boolean;
begin
Result:= (FindResource(hInstance, PChar(Name), PChar(Name)) <> 0);
end;
function WeatherLocationTypeToStr(const Value: TWeatherLocationType): String;
begin
case Value of
wlZip: Result:= 'Zip Code';
wlCityState: Result:= 'City and State';
wlCoords: Result:= 'Coordinates';
wlAutoIP: Result:= 'Automatic IP';
wlCityCode: Result:= 'City Code';
wlCountryCity: Result:= 'City and Country';
wlAirportCode: Result:= 'Airport Code';
wlPWS: Result:= 'PWS';
end;
end;
function WeatherInfoTypeToStr(const Value: TWeatherInfoType): String;
begin
case Value of
wiLocation: Result:= 'Location Info';
wiConditions: Result:= 'Current Conditions';
wiAlerts: Result:= 'Weather Alerts';
wiForecastSummary: Result:= 'Forecast Summary';
wiForecastHourly: Result:= 'Forecast Hourly';
wiForecastDaily: Result:= 'Forecast Daily';
wiMaps: Result:= 'Maps';
wiAlmanac: Result:= 'Almanac';
wiAstronomy: Result:= 'Astronomy';
wiHurricane: Result:= 'Hurricane';
wiHistory: Result:= 'History';
wiPlanner: Result:= 'Planner';
wiStation: Result:= 'Station';
end;
end;
function WeatherAlertTypeToStr(const Value: TWeatherAlertType): String;
begin
case Value of
waNone: Result:= 'None';
waHurricaneStat: Result:= 'Hurricane Status';
waTornadoWarn: Result:= 'Tornado Warning';
waTornadoWatch: Result:= 'Tornado Watch';
waSevThundWarn: Result:= 'Severe Thunderstorm Warning';
waSevThundWatch: Result:= 'Severe Thunderstorm Watch';
waWinterAdv: Result:= 'Winter Weather Advisory';
waFloodWarn: Result:= 'Flood Warning';
waFloodWatch: Result:= 'Flood Watch';
waHighWind: Result:= 'High Wind Advisory';
waSevStat: Result:= 'Severe Weather Status';
waHeatAdv: Result:= 'Heat Advisory';
waFogAdv: Result:= 'Fog Advisory';
waSpecialStat: Result:= 'Special Weather Statement';
waFireAdv: Result:= 'Fire Advisory';
waVolcanicStat: Result:= 'Volcanic Status';
waHurricaneWarn: Result:= 'Hurricane Warning';
waRecordSet: Result:= 'Record Set';
waPublicRec: Result:= 'Public Record';
waPublicStat: Result:= 'Public Status';
end;
end;
function WeatherAlertPropToStr(const Value: TWeatherAlertProp): String;
begin
case Value of
apZones: Result:= 'Affected Zones';
apVerticies: Result:= 'Storm Verticies';
apStorm: Result:= 'Storm Information';
apType: Result:= 'Alert Type';
apDescription: Result:= 'Description';
apExpires: Result:= 'Expiration Time';
apMessage: Result:= 'Alert Message';
apPhenomena: Result:= 'Phenomena';
apSignificance: Result:= 'Significance';
end;
end;
function WeatherForecastTypeToStr(const Value: TWeatherForecastType): String;
begin
case Value of
ftSummary: Result:= 'Summary';
ftHourly: Result:= 'Hourly';
ftDaily: Result:= 'Daily';
end;
end;
function WeatherPropToStr(const Value: TWeatherPropType): String;
begin
case Value of
wpIcon: Result:= 'Weather Icon';
wpCaption: Result:= 'Caption';
wpDescription: Result:= 'Description';
wpDetails: Result:= 'Details';
wpURL: Result:= 'URL';
wpStation: Result:= 'Station';
wpPropsMin: Result:= 'Min of All Props';
wpPropsMax: Result:= 'Max of All Props';
wpTemp: Result:= 'Temperature';
wpTempMin: Result:= 'Temp Min';
wpTempMax: Result:= 'Temp Max';
wpFeelsLike: Result:= 'Feels Like';
wpFeelsLikeSun: Result:= 'Feels Like Sun';
wpFeelsLikeShade: Result:= 'Feels Like Shade';
wpWindDir: Result:= 'Wind Direction';
wpWindSpeed: Result:= 'Wind Speed';
wpWindGust: Result:= 'Wind Gusts';
wpWindChill: Result:= 'Wind Chill';
wpHeatIndex: Result:= 'Heat Index';
wpPressure: Result:= 'Air Pressure';
wpPressureGround: Result:= 'Pressure at Ground';
wpPressureSea: Result:= 'Pressure at Sea';
wpHumidity: Result:= 'Humidity';
wpDewPoint: Result:= 'Dew Point';
wpVisibility: Result:= 'Visibility';
wpSolarRad: Result:= 'Solar Radiation';
wpUVIndex: Result:= 'UV Index';
wpCloudCover: Result:= 'Cloud Cover';
wpPrecipAmt: Result:= 'Precipitation Amt';
wpRainAmt: Result:= 'Rain Amount';
wpSnowAmt: Result:= 'Snow Amount';
wpIceAmt: Result:= 'Ice Amount';
wpSleetAmt: Result:= 'Sleet Amount';
wpFogAmt: Result:= 'Fog Amount';
wpStormAmt: Result:= 'Storm Amount';
wpPrecipPred: Result:= 'Chance of Precip';
wpRainPred: Result:= 'Chance of Rain';
wpSnowPred: Result:= 'Chance of Snow';
wpIcePred: Result:= 'Chance of Ice';
wpSleetPred: Result:= 'Chance of Sleet';
wpFogPred: Result:= 'Chance of Fog';
wpStormPred: Result:= 'Chance of Storm';
wpWetBulb: Result:= 'Wet Bulb';
wpCeiling: Result:= 'Ceiling';
wpSunrise: Result:= 'Sunrise';
wpSunset: Result:= 'Sunset';
wpDaylight: Result:= 'Daylight Amount';
end;
end;
function WeatherMapTypeToStr(const Value: TWeatherMapType): String;
begin
case Value of
mpSatellite: Result:= 'Satellite';
mpRadar: Result:= 'Radar';
mpSatelliteRadar: Result:= 'Satellite and Radar';
mpRadarClouds: Result:= 'Radar and Clouds';
mpClouds: Result:= 'Clouds';
mpTemp: Result:= 'Temperature';
mpTempChange: Result:= 'Temp Change';
mpSnowCover: Result:= 'Snow Cover';
mpPrecip: Result:= 'Precipitation';
mpAlerts: Result:= 'Alerts';
mpHeatIndex: Result:= 'Heat Index';
mpDewPoint: Result:= 'Dew Point';
mpWindChill: Result:= 'Wind Chill';
mpPressureSea: Result:= 'Sea Level Pressure';
mpWind: Result:= 'Wind';
mpAniSatellite: Result:= 'Animated Satellite';
mpAniRadar: Result:= 'Animated Radar';
mpAniSatelliteRadar: Result:= 'Animated Satellite and Radar';
end;
end;
function WeatherMapFormatToStr(const Value: TWeatherMapFormat): String;
begin
case Value of
wfJpg: Result:= 'Jpg';
wfPng: Result:= 'Png';
wfGif: Result:= 'Gif';
wfTiff: Result:= 'Tiff';
wfBmp: Result:= 'Bitmap';
wfFlash: Result:= 'Flash Object';
wfHtml: Result:= 'HTML Page';
end;
end;
function WeatherUnitsToStr(const Value: TWeatherUnits): String;
begin
case Value of
wuKelvin: Result:= 'Kelvin';
wuImperial: Result:= 'Imperial';
wuMetric: Result:= 'Metric';
end;
end;
{$IFDEF USE_VCL}
function TempColor(const Temp: Single): TColor;
const
MAX_TEMP = 99999;
MIN_TEMP = -MIN_TEMP;
var
T: Integer;
begin
T:= Trunc(Temp);
case T of
-MIN_TEMP..32: Result:= clIceBlue;
33..55: Result:= clSkyBlue;
56..73: Result:= clMoneyGreen;
74..90: Result:= clLightRed;
91..MAX_TEMP: Result:= clLightOrange;
else Result:= clWhite;
end;
end;
{$ENDIF}
function DegreeToDir(const D: Single): String;
var
I: Integer;
begin
I:= Trunc(D);
case I of
0..11,348..365: Result:= 'N';
12..33: Result:= 'NNE';
34..56: Result:= 'NE';
57..78: Result:= 'ENE';
79..101: Result:= 'E';
102..123: Result:= 'ESE';
124..146: Result:= 'SE';
147..168: Result:= 'SSE';
169..191: Result:= 'S';
192..213: Result:= 'SSW';
214..236: Result:= 'SW';
237..258: Result:= 'WSW';
259..281: Result:= 'W';
282..303: Result:= 'WNW';
304..326: Result:= 'NW';
327..347: Result:= 'NNW';
end;
end;
function EpochLocal(const Value: Integer): TDateTime; overload;
begin
Result:= UnixToDateTime(Value);
Result:= LocalDateTimeFromUTCDateTime(Result);
end;
function EpochLocal(const Value: String): TDateTime; overload;
begin
Result:= EpochLocal(StrToIntDef(Value, 0));
end;
function LocalDateTimeFromUTCDateTime(const UTCDateTime: TDateTime): TDateTime;
var
LocalSystemTime: TSystemTime;
UTCSystemTime: TSystemTime;
LocalFileTime: TFileTime;
UTCFileTime: TFileTime;
begin
DateTimeToSystemTime(UTCDateTime, UTCSystemTime);
SystemTimeToFileTime(UTCSystemTime, UTCFileTime);
if FileTimeToLocalFileTime(UTCFileTime, LocalFileTime)
and FileTimeToSystemTime(LocalFileTime, LocalSystemTime) then begin
Result := SystemTimeToDateTime(LocalSystemTime);
end else begin
Result := UTCDateTime; // Default to UTC if any conversion function fails.
end;
end;
{ TWeatherCode }
class operator TWeatherCode.Implicit(const Value: TWeatherCode): String;
begin
case Value.DayNight of
dnDay: Result:= 'd';
dnNight: Result:= 'n';
end;
Result:= Result + IntToStr(Integer(Value.Clouds));
Result:= Result + IntToStr(Integer(Value.Precip));
Result:= Result + IntToStr(Integer(Value.PrecipType));
end;
class operator TWeatherCode.Implicit(const Value: String): TWeatherCode;
begin
if Length(Value) <> 4 then raise Exception.Create('Value must be 4 characters.');
case Value[1] of
'd','D': Result.DayNight:= TDayNight.dnDay;
'n','N': Result.DayNight:= TDayNight.dnNight;
else raise Exception.Create('First value must be either d, D, n, or N.');
end;
if CharInSet(Value[2], ['0'..'6']) then
Result.Clouds:= TCloudCode(StrToIntDef(Value[2], 0))
else
raise Exception.Create('Second value must be between 0 and 6.');
if CharInSet(Value[3], ['0'..'4']) then
Result.Precip:= TPrecipCode(StrToIntDef(Value[3], 0))
else
raise Exception.Create('Third value must be between 0 and 4.');
if CharInSet(Value[4], ['0'..'2']) then
Result.PrecipType:= TPrecipTypeCode(StrToIntDef(Value[4], 0))
else
raise Exception.Create('Fourth value must be between 0 and 2.');
end;
function TWeatherCode.DayNightStr: String;
begin
case DayNight of
dnDay: Result:= 'Day';
dnNight: Result:= 'Night';
end;
end;
function TWeatherCode.Description: String;
begin
case Clouds of
ccClear: Result:= 'Clear';
ccAlmostClear: Result:= 'Mostly Clear';
ccHalfCloudy: Result:= 'Partly Cloudy';
ccBroken: Result:= 'Cloudy';
ccOvercast: Result:= 'Overcast';
ccThinClouds: Result:= 'Thin High Clouds';
ccFog: Result:= 'Fog';
end;
case PrecipType of
ptRain: begin
case Precip of
pcNone: Result:= Result + '';
pcSlight: Result:= Result + ' with Light Rain';
pcShowers: Result:= Result + ' with Rain Showers';
pcPrecip: Result:= Result + ' with Rain';
pcThunder: Result:= Result + ' with Rain and Thunderstorms';
end;
end;
ptSleet: begin
case Precip of
pcNone: Result:= Result + '';
pcSlight: Result:= Result + ' with Light Sleet';
pcShowers: Result:= Result + ' with Sleet Showers';
pcPrecip: Result:= Result + ' with Sleet';
pcThunder: Result:= Result + ' with Sleet and Thunderstorms';
end;
end;
ptSnow: begin
case Precip of
pcNone: Result:= Result + '';
pcSlight: Result:= Result + ' with Light Snow';
pcShowers: Result:= Result + ' with Snow Showers';
pcPrecip: Result:= Result + ' with Snow';
pcThunder: Result:= Result + ' with Snow and Thunderstorms';
end;
end;
end;
end;
class operator TWeatherCode.Implicit(const Value: TWeatherCode): Integer;
begin
Result:= Integer(Value.DayNight);
Result:= Result + (Integer(Value.Clouds) * 10);
Result:= Result + (Integer(Value.Precip) * 100);
Result:= Result + (Integer(Value.PrecipType) * 1000);
end;
class operator TWeatherCode.Implicit(const Value: Integer): TWeatherCode;
begin
//Result.DayNight:= TDayNight();
end;
function TWeatherCode.Name: String;
begin
//TODO: Return unique standardized name
case Clouds of
ccClear: Result:= 'clear_';
ccAlmostClear: Result:= 'almost_clear_';
ccHalfCloudy: Result:= 'half_cloudy_';
ccBroken: Result:= 'broken_clouds_';
ccOvercast: Result:= 'overcast_';
ccThinClouds: Result:= 'thin_clouds_';
ccFog: Result:= 'fog_';
end;
case PrecipType of
ptRain: begin
case Precip of
pcNone: Result:= Result + '';
pcSlight: Result:= Result + 'rain_slight';
pcShowers: Result:= Result + 'rain_showers';
pcPrecip: Result:= Result + 'rain';
pcThunder: Result:= Result + 'rain_and_thunder';
end;
end;
ptSleet: begin
case Precip of
pcNone: Result:= Result + '';
pcSlight: Result:= Result + 'sleet_slight';
pcShowers: Result:= Result + 'sleet_showers';
pcPrecip: Result:= Result + 'sleet';
pcThunder: Result:= Result + 'sleet_and_thunder';
end;
end;
ptSnow: begin
case Precip of
pcNone: Result:= Result + '';
pcSlight: Result:= Result + 'snow_slight';
pcShowers: Result:= Result + 'snow_showers';
pcPrecip: Result:= Result + 'snow';
pcThunder: Result:= Result + 'snow_and_thunder';
end;
end;
end;
end;
{ TTemperature }
function TTemperature.GetAsCelsius: Double;
begin
Result:= Value;
end;
function TTemperature.GetAsCelsiusStr: String;
begin
Result:= FormatFloat('0° C', GetAsCelsius);
end;
function TTemperature.GetAsFarenheit: Double;
begin
Result:= Value - 32;
Result:= Result * 0.5556;
end;
function TTemperature.GetAsFarenheitStr: String;
begin
Result:= FormatFloat('0° F', GetAsFarenheit);
end;
function TTemperature.GetAsStr: String;
begin
Result:= FormatFloat('0°', GetAsFarenheit);
end;
procedure TTemperature.SetAsCelsius(const Value: Double);
begin
Self.Value:= Value;
end;
procedure TTemperature.SetAsFarenheit(const Value: Double);
begin
Self.Value:= Value * 1.8;
Self.Value:= Self.Value + 32;
end;
class operator TTemperature.Implicit(const Value: TTemperature): Double;
begin
Result:= Value.Value;
end;
class operator TTemperature.Implicit(const Value: Double): TTemperature;
begin
Result.Value:= Value;
end;
{ TWeatherGraphic }
constructor TWeatherGraphic.Create;
begin
FStream:= TStringStream.Create;
end;
constructor TWeatherGraphic.Create(AStream: TStream);
begin
Create;
FStream.LoadFromStream(AStream);
FStream.Position:= 0;
end;
constructor TWeatherGraphic.Create(AFilename: WideString);
begin
Create;
FStream.LoadFromFile(AFilename);
FStream.Position:= 0;
end;
destructor TWeatherGraphic.Destroy;
begin
FreeAndNil(FStream);
inherited;
end;
function TWeatherGraphic.GetBase64: WideString;
begin
Result:= FStream.DataString;
end;
function TWeatherGraphic.GetExt: WideString;
begin
Result:= FExt;
end;
procedure TWeatherGraphic.SetBase64(const Value: WideString);
begin
FStream.Clear;
FStream.WriteString(Value);
end;
{ TWeatherLocation }
constructor TWeatherLocation.Create;
begin
end;
destructor TWeatherLocation.Destroy;
begin
inherited;
end;
function TWeatherLocation.GetCity: WideString;
begin
Result:= FCity;
end;
function TWeatherLocation.GetCountry: WideString;
begin
Result:= FCountry;
end;
function TWeatherLocation.GetCountryAbbr: WideString;
begin
Result:= FCountryAbbr;
end;
function TWeatherLocation.GetDisplayName: WideString;
begin
Result:= FDisplayName;
end;
function TWeatherLocation.GetElevation: Double;
begin
Result:= FElevation;
end;
function TWeatherLocation.GetLatitude: Double;
begin
Result:= FLatitude;
end;
function TWeatherLocation.GetLongitude: Double;
begin
Result:= FLongitude;
end;
function TWeatherLocation.GetState: WideString;
begin
Result:= FState;
end;
function TWeatherLocation.GetStateAbbr: WideString;
begin
Result:= FStateAbbr;
end;
function TWeatherLocation.GetZipCode: WideString;
begin
Result:= FZipCode;
end;
{ TWeatherForecast }
constructor TWeatherForecast.Create;
begin
FItems:= TList<IWeatherProps>.Create;
FLocation:= TWeatherLocation.Create;
FLocation._AddRef;
end;
procedure TWeatherForecast.Clear;
var
X: Integer;
begin
for X := 0 to FItems.Count-1 do begin
FItems[X]._Release;
end;
FLocation._Release;
FLocation:= nil;
FItems.Clear;
end;
destructor TWeatherForecast.Destroy;
begin
Clear;
FreeAndNil(FItems);
inherited;
end;
function TWeatherForecast.Count: Integer;
begin
Result:= FItems.Count;
end;
function TWeatherForecast.GetItem(const Index: Integer): IWeatherProps;
begin
Result:= FItems[Index];
end;
function TWeatherForecast.GetLocation: IWeatherLocation;
begin
Result:= FLocation;
end;
function TWeatherForecast.MaxTemp: Single;
var
X: Integer;
begin
Result:= -9999999;
for X := 0 to FItems.Count-1 do begin
if FItems[X].Temp > Result then
Result:= FItems[X].Temp;
end;
end;
function TWeatherForecast.MinTemp: Single;
var
X: Integer;
begin
Result:= 9999999;
for X := 0 to FItems.Count-1 do begin
if FItems[X].Temp < Result then
Result:= FItems[X].Temp;
end;
end;
{ TWeatherStormVertex }
function TWeatherStormVertex.GetLatitude: Double;
begin
Result:= FLatitude;
end;
function TWeatherStormVertex.GetLongitude: Double;
begin
Result:= FLongitude;
end;
{ TWeatherStormVerticies }
constructor TWeatherStormVerticies.Create;
begin
FItems:= TList<IWeatherStormVertex>.Create;
end;
destructor TWeatherStormVerticies.Destroy;
begin
Clear;
FreeAndNil(FItems);
inherited;
end;
function TWeatherStormVerticies.Count: Integer;
begin
Result:= FItems.Count;
end;
procedure TWeatherStormVerticies.Clear;
var
X: Integer;
begin
for X := 0 to FItems.Count-1 do begin
FItems[X]._Release;
end;
FItems.Clear;
end;
function TWeatherStormVerticies.GetItem(
const Index: Integer): IWeatherStormVertex;
begin
Result:= FItems[Index];
end;
{ TWeatherAlertStorm }
constructor TWeatherAlertStorm.Create;
begin
FVerticies:= TWeatherStormVerticies.Create;
FVerticies._AddRef;
end;
destructor TWeatherAlertStorm.Destroy;
begin
FVerticies._Release;
FVerticies:= nil;
inherited;
end;
function TWeatherAlertStorm.GetDateTime: TDateTime;
begin
Result:= FDateTime;
end;
function TWeatherAlertStorm.GetDirection: Single;
begin
Result:= FDirection;
end;
function TWeatherAlertStorm.GetLatitude: Double;
begin
Result:= FLatitude;
end;
function TWeatherAlertStorm.GetLongitude: Double;
begin
Result:= FLongitude;
end;
function TWeatherAlertStorm.GetSpeed: Single;
begin
Result:= FSpeed;
end;
function TWeatherAlertStorm.GetVerticies: IWeatherStormVerticies;
begin
Result:= FVerticies;
end;
{ TWeatherAlertZone }
function TWeatherAlertZone.GetState: WideString;
begin
Result:= FState;
end;
function TWeatherAlertZone.GetZone: WideString;
begin
Result:= FZone;
end;
{ TWeatherAlertZones }
constructor TWeatherAlertZones.Create;
begin
FItems:= TList<TWeatherAlertZone>.Create;
end;
destructor TWeatherAlertZones.Destroy;
begin
Clear;
FreeAndNil(FItems);
inherited;
end;
procedure TWeatherAlertZones.Clear;
var
X: Integer;
begin
for X := 0 to FItems.Count-1 do begin
FItems[X]._Release;
end;
FItems.Clear;
end;
function TWeatherAlertZones.Count: Integer;
begin
Result:= FItems.Count;
end;
function TWeatherAlertZones.GetItem(const Index: Integer): IWeatherAlertZone;
begin
Result:= FItems[Index];
end;
{ TWeatherAlert }
constructor TWeatherAlert.Create;
begin
FZones:= TWeatherAlertZones.Create;
FZones._AddRef;
FStorm:= TWeatherAlertStorm.Create;
FStorm._AddRef;
end;
destructor TWeatherAlert.Destroy;
begin
FStorm._Release;
FStorm:= nil;
FZones._Release;
FZones:= nil;
inherited;
end;
function TWeatherAlert.GetAlertType: TWeatherAlertType;
begin
Result:= FAlertType;
end;
function TWeatherAlert.GetDateTime: TDateTime;
begin
Result:= FDateTime;
end;
function TWeatherAlert.GetDescription: WideString;
begin
Result:= FDescription;
end;
function TWeatherAlert.GetExpires: TDateTime;
begin
Result:= FExpires;
end;
function TWeatherAlert.GetMsg: WideString;
begin
Result:= FMsg;
end;
function TWeatherAlert.GetPhenomena: WideString;
begin
Result:= FPhenomena;
end;
function TWeatherAlert.GetSignificance: WideString;
begin
Result:= FSignificance;
end;
function TWeatherAlert.GetStorm: IWeatherAlertStorm;
begin
Result:= FStorm;
end;
function TWeatherAlert.GetZones: IWeatherAlertZones;
begin
Result:= FZones;
end;
{ TWeatherAlerts }
constructor TWeatherAlerts.Create;
begin
FItems:= TList<IWeatherAlert>.Create;
end;
destructor TWeatherAlerts.Destroy;
begin
Clear;
FreeAndNil(FItems);
inherited;
end;
function TWeatherAlerts.Count: Integer;
begin
Result:= FItems.Count;
end;
procedure TWeatherAlerts.Clear;
var
X: Integer;
begin
for X := 0 to FItems.Count-1 do begin
FItems[X]._Release;
end;
FItems.Clear;
end;
function TWeatherAlerts.GetItem(const Index: Integer): IWeatherAlert;
begin
Result:= FItems[Index];
end;
{ TWeatherMaps }
constructor TWeatherMaps.Create;
var
X: TWeatherMapType;
begin
{$IFDEF USE_VCL}
for X := Low(TMapArray) to High(TMapArray) do begin
FMaps[X]:= TPicture.Create;
end;
{$ELSE}
for X := Low(TMapArray) to High(TMapArray) do begin
FMaps[X]:= TWeatherGraphic.Create;
end;
{$ENDIF}
end;
destructor TWeatherMaps.Destroy;
var
X: TWeatherMapType;
{$IFDEF USE_VCL}
P: TPicture;
{$ELSE}
P: IWeatherGraphic;
{$ENDIF}
begin
for X := Low(TMapArray) to High(TMapArray) do begin
P:= FMaps[X];
{$IFDEF USE_VCL}
FreeAndNil(P);
{ELSE}
P._Release;
P:= nil;
{$ENDIF}
end;
inherited;
end;
{$IFDEF USE_VCL}
function TWeatherMaps.GetMap(const MapType: TWeatherMapType): TPicture;
{$ELSE}
function TWeatherMaps.GetMap(const MapType: TWeatherMapType): IWeatherGraphic;
{$ENDIF}
begin
Result:= FMaps[MapType];
end;
{ TWeatherMultiInfo }
constructor TWeatherMultiInfo.Create;
begin
end;
destructor TWeatherMultiInfo.Destroy;
begin
inherited;
end;
function TWeatherMultiInfo.GetAlerts: IWeatherAlerts;
begin
Result:= FAlerts;
end;
function TWeatherMultiInfo.GetConditions: IWeatherProps;
begin
Result:= FConditions;
end;
function TWeatherMultiInfo.GetForecastDaily: IWeatherForecast;
begin
Result:= FForecastDaily;
end;
function TWeatherMultiInfo.GetForecastHourly: IWeatherForecast;
begin
Result:= FForecastHourly;
end;
function TWeatherMultiInfo.GetForecastSummary: IWeatherForecast;
begin
Result:= FForecastSummary;
end;
function TWeatherMultiInfo.GetMaps: IWeatherMaps;
begin
Result:= FMaps;
end;
procedure TWeatherMultiInfo.SetAll(Con: IWeatherProps; Alr: TWeatherAlerts;
Fos, Foh, Fod: TWeatherForecast; Map: IWeatherMaps);
begin
FConditions:= Con;
FAlerts:= Alr;
FForecastSummary:= Fos;
FForecastHourly:= Foh;
FForecastDaily:= Fod;
FMaps:= Map;
end;
{ TWeatherServiceBase }
constructor TWeatherServiceBase.Create;
begin
FWeb:= TIdHTTP.Create(nil);
FLocationType:= TWeatherLocationType.wlAutoIP;
end;
destructor TWeatherServiceBase.Destroy;
begin
FreeAndNil(FWeb);
inherited;
end;
function TWeatherServiceBase.GetKey: WideString;
begin
Result:= FKey;
end;
function TWeatherServiceBase.GetLocationDetail1: WideString;
begin
Result:= FLocationDetail1;
end;
function TWeatherServiceBase.GetLocationDetail2: WideString;
begin
Result:= FLocationDetail2;
end;
function TWeatherServiceBase.GetLocationType: TWeatherLocationType;
begin
Result:= FLocationType;
end;
function TWeatherServiceBase.GetUnits: TWeatherUnits;
begin
Result:= FUnits;
end;
procedure TWeatherServiceBase.SetKey(const Value: WideString);
begin
FKey:= Value;
end;
procedure TWeatherServiceBase.SetLocationDetail1(const Value: WideString);
begin
FLocationDetail1:= Value;
end;
procedure TWeatherServiceBase.SetLocationDetail2(const Value: WideString);
begin
FLocationDetail2:= Value;
end;
procedure TWeatherServiceBase.SetLocationType(const Value: TWeatherLocationType);
begin
FLocationType:= Value;
end;
procedure TWeatherServiceBase.SetUnits(const Value: TWeatherUnits);
begin
FUnits:= Value;
end;
{ TWeatherMultiService }
constructor TWeatherMultiService.Create;
begin
FItems:= TList<IWeatherService>.Create;
end;
destructor TWeatherMultiService.Destroy;
begin
Clear;
FreeAndNil(FItems);
inherited;
end;
procedure TWeatherMultiService.Add(const Svc: IWeatherService);
begin
FItems.Add(Svc);
Svc._AddRef;
end;
procedure TWeatherMultiService.Clear;
begin
while Count > 0 do
Delete(0);
end;
function TWeatherMultiService.Count: Integer;
begin
Result:= FItems.Count;
end;
procedure TWeatherMultiService.Delete(const Index: Integer);
begin
FItems[Index]._Release;
FItems.Delete(Index);
end;
function TWeatherMultiService.GetItem(const Index: Integer): IWeatherService;
begin
Result:= FItems[Index];
end;
function TWeatherMultiService.GetCombinedConditions: IWeatherProps;
var
R: TWeatherProps;
T: IWeatherProps;
X: Integer;
P: TWeatherPropType;
S: IWeatherService;
U: Array[TWeatherPropType] of Integer;
begin
//Merge multiple services into one data set, averaging each property
R:= TWeatherProps.Create;
try
for P := Low(U) to High(U) do begin
U[P]:= 0;
end;
if FItems.Count > 0 then begin
for X := 0 to FItems.Count-1 do begin
S:= FItems[X];
T:= S.GetConditions;
R.AddTo(T, S.Info.Support.SupportedConditionProps);
//TODO: Is there a better way to do these unmergable ones?
R.FDateTime:= T.DateTime;
R.FIcon.Base64:= T.Icon.Base64;
R.FCaption:= T.Caption;
R.FDescription:= T.Description;
R.FDetails:= T.Details;
R.FURL:= T.URL;
R.FStation:= T.Station;
end;
R.CalcAverages;
end;
finally
Result:= R;
end;
end;
function TWeatherMultiService.GetCombinedForecastDaily: IWeatherForecast;
var
R: TWeatherForecast;
begin
R:= TWeatherForecast.Create;
try
//TODO: How to merge forecasts???
finally
Result:= R;
end;
end;
function TWeatherMultiService.GetCombinedForecastHourly: IWeatherForecast;
var
R: TWeatherForecast;
begin
R:= TWeatherForecast.Create;
try
//TODO: How to merge forecasts???
finally
Result:= R;
end;
end;
function TWeatherMultiService.GetCombinedForecastSummary: IWeatherForecast;
var
R: TWeatherForecast;
begin
R:= TWeatherForecast.Create;
try
//TODO: How to merge forecasts???
finally
Result:= R;
end;
end;
function TWeatherMultiService.GetCombinedAlerts: IWeatherAlerts;
var
R: TWeatherAlerts;
begin
R:= TWeatherAlerts.Create;
try
//TODO: How to merge alerts???
finally
Result:= R;
end;
end;
{ TWeatherProps }
constructor TWeatherProps.Create;
var
X: TWeatherPropType;
begin
FIcon:= TWeatherGraphic.Create;
FIcon._AddRef;
FCaption:= '';
FDescription:= '';
FDetails:= '';
FTemp:= 0;
FHumidity:= 0;
FPressure:= 0;
FWindSpeed:= 0;
FWindDir:= 0;
FVisibility:= 0;
FDewPoint:= 0;
for X := Low(TWeatherPropType) to High(TWeatherPropType) do begin
FCounts[X]:= 0;
end;
end;
destructor TWeatherProps.Destroy;
begin
FIcon._Release;
FIcon:= nil;
inherited;
end;
function TWeatherProps.GetCaption: WideString;
begin
Result:= FCaption;
end;
function TWeatherProps.GetCeiling: Double;
begin
Result:= FCeiling;
end;
function TWeatherProps.GetCloudCover: Double;
begin
Result:= FCloudCover;
end;
function TWeatherProps.GetDateTime: TDateTime;
begin
Result:= FDateTime;
end;
function TWeatherProps.GetDaylight: Double;
begin
Result:= FDaylight;
end;
function TWeatherProps.GetDescription: WideString;
begin
Result:= FDescription;
end;
function TWeatherProps.GetDetails: WideString;
begin
Result:= FDetails;
end;
function TWeatherProps.GetDewPoint: Double;
begin
Result:= FDewPoint;
end;
function TWeatherProps.GetFeelsLike: Double;
begin
Result:= FFeelsLike;
end;
function TWeatherProps.GetFeelsLikeShade: Double;
begin
Result:= FFeelsLikeShade;
end;
function TWeatherProps.GetFeelsLikeSun: Double;
begin
Result:= FFeelsLikeSun;
end;
function TWeatherProps.GetFogAmt: Double;
begin
Result:= FFogAmt;
end;
function TWeatherProps.GetFogPred: Double;
begin
Result:= FFogPred;
end;
function TWeatherProps.GetHeatIndex: Double;
begin
Result:= FHeatIndex;
end;
function TWeatherProps.GetHumidity: Double;
begin
Result:= FHumidity;
end;
function TWeatherProps.GetIceAmt: Double;
begin
Result:= FIceAmt;
end;
function TWeatherProps.GetIcePred: Double;
begin
Result:= FIcePred;
end;
function TWeatherProps.GetIcon: IWeatherGraphic;
begin
Result:= FIcon;
end;
function TWeatherProps.GetPrecipAmt: Double;
begin
Result:= FPrecipAmt;
end;
function TWeatherProps.GetPrecipPred: Double;
begin
Result:= FPrecipPred;
end;
function TWeatherProps.GetPressure: Double;
begin
Result:= FPressure;
end;
function TWeatherProps.GetPressureGround: Double;
begin
Result:= FPressureGround;
end;
function TWeatherProps.GetPressureSea: Double;
begin
Result:= FPressureSea;
end;
function TWeatherProps.GetRainAmt: Double;
begin
Result:= FRainAmt;
end;
function TWeatherProps.GetRainPred: Double;
begin
Result:= FRainPred;
end;
function TWeatherProps.GetSleetAmt: Double;
begin
Result:= FSleetAmt;
end;
function TWeatherProps.GetSleetProd: Double;
begin
Result:= FSleetPred;
end;
function TWeatherProps.GetSnowAmt: Double;
begin
Result:= FSnowAmt;
end;
function TWeatherProps.GetSnowPred: Double;
begin
Result:= FSnowPred;
end;
function TWeatherProps.GetSolarRad: Double;
begin
Result:= FSolarRad;
end;
function TWeatherProps.GetStation: WideString;
begin
Result:= FStation;
end;
function TWeatherProps.GetStormAmt: Double;
begin
Result:= FStormAmt;
end;
function TWeatherProps.GetStormPred: Double;
begin
Result:= FStormPred;
end;
function TWeatherProps.GetSunrise: TDateTime;
begin
Result:= FSunrise;
end;
function TWeatherProps.GetSunset: TDateTime;
begin
Result:= FSunset;
end;
function TWeatherProps.GetTemp: Double;
begin
Result:= FTemp;
end;
function TWeatherProps.GetTempMax: Double;
begin
Result:= FTempMax;
end;
function TWeatherProps.GetTempMin: Double;
begin
Result:= FTempMin;
end;
function TWeatherProps.GetURL: WideString;
begin
Result:= FURL;
end;
function TWeatherProps.GetUVIndex: Double;
begin
Result:= FUVIndex;
end;
function TWeatherProps.GetVisibility: Double;
begin
Result:= FVisibility;
end;
function TWeatherProps.GetWetBulb: Double;
begin
Result:= FWetBulb;
end;
function TWeatherProps.GetWindChill: Double;
begin
Result:= FWindChill;
end;
function TWeatherProps.GetWindDir: Double;
begin
Result:= FWindDir;
end;
function TWeatherProps.GetWindGusts: Double;
begin
Result:= FWindGusts;
end;
function TWeatherProps.GetWindSpeed: Double;
begin
Result:= FWindSpeed;
end;
function TWeatherProps.PropCount(const Prop: TWeatherPropType): Integer;
begin
Result:= FCounts[Prop];
end;
function TWeatherProps.Support: TWeatherPropTypes;
begin
Result:= FSupport;
end;
procedure TWeatherProps.AddTo(const AProps: IWeatherProps; const ASupport: TWeatherPropTypes);
var
T: TWeatherPropType;
begin
//Add values of specified props to this prop
for T := Low(TWeatherPropType) to High(TWeatherPropType) do begin
if T in ASupport then begin
FCounts[T]:= FCounts[T] + 1;
end;
end;
FSupport:= FSupport + ASupport;
FTemp:= FTemp + AProps.Temp;
FTempMin:= FTempMin + AProps.TempMin;
FTempMax:= FTempMax + AProps.TempMax;
FFeelsLike:= FFeelsLike + AProps.FeelsLike;
FFeelsLikeSun:= FFeelsLikeSun + AProps.FeelsLikeSun;
FFeelsLikeShade:= FFeelsLikeShade + AProps.FeelsLikeShade;
FWindDir:= FWindDir + AProps.WindDir;
FWindSpeed:= FWindSpeed + AProps.WindSpeed;
FWindGusts:= FWindGusts + AProps.WindGusts;
FWindChill:= FWindChill + AProps.WindChill;
FHeatIndex:= FHeatIndex + AProps.HeatIndex;
FPressure:= FPressure + AProps.Pressure;
FPressureGround:= FPressureGround + AProps.PressureGround;
FPressureSea:= FPressureSea + AProps.PressureSea;
FHumidity:= FHumidity + AProps.Humidity;
FDewPoint:= FDewPoint + AProps.DewPoint;
FVisibility:= FVisibility + AProps.Visibility;
FSolarRad:= FSolarRad + AProps.SolarRad;
FUVIndex:= FUVIndex + AProps.UVIndex;
FCloudCover:= FCloudCover + AProps.CloudCover;
FPrecipAmt:= FPrecipAmt + AProps.PrecipAmt;
FRainAmt:= FRainAmt + AProps.RainAmt;
FSnowAmt:= FSnowAmt + AProps.SnowAmt;
FIceAmt:= FIceAmt + AProps.IceAmt;
FSleetAmt:= FSleetAmt + AProps.SleetAmt;
FFogAmt:= FFogAmt + AProps.FogAmt;
FStormAmt:= FStormAmt + AProps.StormAmt;
FPrecipPred:= FPrecipPred + AProps.PrecipPred;
FRainPred:= FRainPred + AProps.RainPred;
FSnowPred:= FSnowPred + AProps.SnowPred;
FIcePred:= FIcePred + AProps.IceAmt;
FSleetPred:= FSleetPred + AProps.SleetPred;
FFogPred:= FFogPred + AProps.FogPred;
FStormPred:= FStormPred + AProps.StormPred;
FWetBulb:= FWetBulb + AProps.WetBulb;
FCeiling:= FCeiling + AProps.Ceiling;
FSunrise:= FSunrise + AProps.Sunrise;
FSunset:= FSunset + AProps.Sunset;
FDaylight:= FDaylight + AProps.Daylight;
end;
procedure TWeatherProps.CalcAverages;
procedure Chk(const T: TWeatherPropType; var V: Double);
begin
if FCounts[T] > 1 then begin
V:= V / FCounts[T];
FCounts[T]:= 1;
end;
end;
begin
//Calculate all averages based on totals
Chk(wpTemp, FTemp);
Chk(wpTempMin, FTempMin);
Chk(wpTempMax, FTempMax);
Chk(wpFeelsLike, FFeelsLike);
Chk(wpFeelsLikeSun, FFeelsLikeSun);
Chk(wpFeelsLikeShade, FFeelsLikeShade);
Chk(wpWindDir, FWindDir);
Chk(wpWindSpeed, FWindSpeed);
Chk(wpWindGust, FWindGusts);
Chk(wpWindChill, FWindChill);
Chk(wpHeatIndex, FHeatIndex);
Chk(wpPressure, FPressure);
Chk(wpPressureGround, FPressureGround);
Chk(wpPressureSea, FPressureSea);
Chk(wpHumidity, FHumidity);
Chk(wpDewPoint, FDewPoint);
Chk(wpVisibility, FVisibility);
Chk(wpSolarRad, FSolarRad);
Chk(wpUVIndex, FUVIndex);
Chk(wpCloudCover, FCloudCover);
Chk(wpPrecipAmt, FPrecipAmt);
Chk(wpRainAmt, FRainAmt);
Chk(wpSnowAmt, FSnowAmt);
Chk(wpIceAmt, FIceAmt);
Chk(wpSleetAmt, FSleetAmt);
Chk(wpFogAmt, FFogAmt);
Chk(wpStormAmt, FStormAmt);
Chk(wpPrecipPred, FPrecipPred);
Chk(wpRainPred, FRainPred);
Chk(wpSnowPred, FSnowPred);
Chk(wpIcePred, FIcePred);
Chk(wpSleetPred, FSleetPred);
Chk(wpFogPred, FFogPred);
Chk(wpStormPred, FStormPred);
Chk(wpWetBulb, FWetBulb);
Chk(wpCeiling, FCeiling);
if FCounts[wpSunrise] > 1 then begin
FSunrise:= FSunrise / FCounts[wpSunrise];
FCounts[wpSunrise]:= 1;
end;
if FCounts[wpSunset] > 1 then begin
FSunset:= FSunset / FCounts[wpSunset];
FCounts[wpSunset]:= 1;
end;
Chk(wpDaylight, FDaylight);
end;
end.
|
{
This unit is part of the Lua4Delphi Source Code
Copyright (C) 2009-2012, LaKraven Studios Ltd.
Copyright Protection Packet(s): L4D014
www.Lua4Delphi.com
www.LaKraven.com
--------------------------------------------------------------------
The contents of this file are subject to the Mozilla Public License
Version 1.1 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS IS"
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and
limitations under the License.
--------------------------------------------------------------------
Unit: L4D.Lua.Lua52.pas
Released: 5th February 2012
Changelog:
5th February 2012:
- Released
}
unit L4D.Lua.Lua52;
interface
{$I Lua4Delphi.inc}
uses
L4D.Lua.Common, L4D.Lua.Intf;
const
{$REGION 'DLL name defines'}
{$IFDEF MSWINDOWS}
LUA_DLL = 'lua5.2.dll';
{$ENDIF}
{$IFDEF LINUX}
LUA_DLL = 'lua5.2.so';
{$ENDIF}
{$IFDEF MACOS}
LUA_DLL = 'liblua5.2.dylib';
{$ENDIF}
{$ENDREGION}
// Thread State
LUA_ERRGCMM = 5;
LUA_ERRERR = 6;
// Basic Lua Type IDs
LUA_NUMTAGS = 9;
// predefined values in the registry
LUA_RIDX_MAINTHREAD = 1;
LUA_RIDX_GLOBALS = 2;
LUA_RIDX_LAST = LUA_RIDX_GLOBALS;
// Arithmetic functions
LUA_OPADD = 0; // ORDER TM
LUA_OPSUB = 1;
LUA_OPMUL = 2;
LUA_OPDIV = 3;
LUA_OPMOD = 4;
LUA_OPPOW = 5;
LUA_OPUNM = 6;
// Garbage Collection State IDs
LUA_GCSETMAJORINC = 8;
LUA_GCISRUNNING = 9;
LUA_GCGEN = 10;
LUA_GCINC = 11;
// Lua Library Names
LUA_BITLIBNAME = 'bit32';
// Extra Error Code for 'LuaL_load'
LUA_ERRFILE = LUA_ERRERR + 1;
type
{
TLua52Base
- The Base Class for Lua 5.2
}
TLua52Base = class(TLuaCommon, ILua52Lib, ILua52Aux)
protected
{$REGION 'ILuaLibInterchange'}
procedure lua_call(L: PLuaState; nargs, nresults: Integer); overload; override;// Macro in 5.2
function lua_cpcall(L: PLuaState; func: TLuaDelphiFunction; ud: Pointer): Integer; overload; override; // Macro in 5.2
function lua_equal(L: PLuaState; idx1, idx2: Integer): LongBool; overload; override; // Macro in 5.2
procedure lua_getfenv(L: PLuaState; idx: Integer); overload; override; // Macro in 5.2
function lua_lessthan(L: PLuaState; idx1, idx2: Integer): LongBool; overload; override; // Macro in 5.2
function lua_load(L: PLuaState; reader: TLuaReaderFunction; dt: Pointer; const chunkname: PAnsiChar): Integer; overload; override; // 5.1 version
function lua_objlen(L: PLuaState; idx: Integer): Cardinal; overload; override;
function lua_pcall(L: PLuaState; nargs, nresults, errfunc: Integer): Integer; overload; override; // Macro in 5.2
function lua_setfenv(L: PLuaState; idx: Integer): LongBool; overload; override; // External in 5.1, "lua_setuservalue" in 5.2
function lua_setmetatable(L: PLuaState; objindex: Integer): LongBool; overload; override; // 5.2 version
function lua_tointeger(L: PLuaState; idx: Integer): Integer; overload; override; // In 5.1
function lua_tonumber(L: PLuaState; idx: Integer): Double; overload; override; // In 5.1
function lua_yield(L: PLuaState; nresults: Integer): Integer; overload; override; // External in 5.1, "lua_yieldk" in 5.2
{$ENDREGION}
{$REGION 'ILua52Lib'}
function lua_absindex(L: PLuaState; idx: Integer): Integer; overload; virtual; abstract;
function lua_arith(L: PLuaState; op: Integer): Integer; overload; virtual; abstract;
procedure lua_copy(L: PLuaState; fromidx, toidx: Integer); overload; virtual; abstract;
function lua_getctx(L: PLuaState; ctx: PInteger): Integer; overload; virtual; abstract;
procedure lua_len(L: PLuaState; idx: Integer); overload; virtual; abstract;
procedure lua_pushunsigned(L: PLuaState; u: Cardinal); overload; virtual; abstract;
procedure lua_rawgetp(L: PLuaState; idx: Integer; p: Pointer); overload; virtual; abstract;
procedure lua_rawsetp(L: PLuaState; idx: Integer; p: Pointer); overload; virtual; abstract;
function lua_resume(L, from: PLuaState; narg: Integer): Integer; overload; virtual; abstract;
function lua_tounsignedx(L: PLuaState; idx: Integer; isnum: PInteger): Cardinal; overload; virtual; abstract;
function lua_upvalueid(L: PLuaState; funcidx, n: Integer): Pointer; overload; virtual; abstract;
procedure lua_upvaluejoin(L: PLuaState; fidx1, n1, fidx2, n2: Integer); overload; virtual; abstract;
function lua_version(L: PLuaState): PInteger; overload; virtual; abstract;
function luaopen_bit32(L: PLuaState): Integer; overload; virtual; abstract;
function luaopen_coroutine(L: PLuaState): Integer; overload; virtual; abstract;
{$ENDREGION}
{$REGION 'ILuaAux'}
function luaL_buffinitsize(L: PLuaState; B: PLuaLBuffer; sz: Cardinal): PAnsiChar; overload; virtual; abstract;
function luaL_checkunsigned(L: PLuaState; narg: Integer): Cardinal; overload; virtual; abstract;
procedure luaL_checkversion(L: PLuaState); overload; virtual; abstract;
function luaL_execresult(L: PLuaState; stat: Integer): Integer; overload; virtual; abstract;
function luaL_fileresult(L: PLuaState; stat: Integer; fname: PAnsiChar): Integer; overload; virtual; abstract;
function luaL_getsubtable(L: PLuaState; idx: Integer; fname: PAnsiChar): Integer; overload; virtual; abstract;
function luaL_len(L: PLuaState; idx: Integer): Integer; overload; virtual; abstract;
function luaL_loadbufferx(L: PLuaState; buff: PAnsiChar; sz: Cardinal; name, mode: PAnsiChar): Integer; overload; virtual; abstract;
function luaL_loadfilex(L: PLuaState; filename, mode: PAnsiChar): Integer; overload; virtual; abstract;
function luaL_optunsigned(L: PLuaState; narg: Integer; u: Cardinal): Cardinal; overload; virtual; abstract;
function luaL_prepbuffsize(B: PLuaLBuffer; sz: Cardinal): PAnsiChar; overload; virtual; abstract;
procedure luaL_pushresultsize(B: PLuaLBuffer; sz: Cardinal); overload; virtual; abstract;
procedure luaL_requiref(L: PLuaState; modname: PansiChar; openf: TLuaDelphiFunction; glb: Integer); overload; virtual; abstract;
procedure luaL_setfuncs(L: PLuaState; lreg: PluaLReg; nup: Integer); overload; virtual; abstract;
procedure luaL_setmetatable(L: PluaState; tname: PAnsiChar); overload; virtual; abstract;
function luaL_testudata(L: PLuaState; narg: Integer; tname: PAnsiChar): Pointer; overload; virtual; abstract;
procedure luaL_traceback(L, L1: PLuaState; msg: PAnsiChar; level: Integer); overload; virtual; abstract;
{$ENDREGION}
end;
{
TLua52Common
- The COMMON PARENT ANCESTOR for Lua 5.2 classes.
- Inherited by TLua52Static, TLua52Dynamic, TLua52Embedded
}
TLua51Common = class(TLua52Base, ILua52LibLocal, ILua52AuxLocal)
public
{$REGION 'ILua52LibLocal'}
function lua_absindex(idx: Integer): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_arith(op: Integer): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_copy(fromidx, toidx: Integer); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_getctx(ctx: PInteger): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_len(idx: Integer); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_pushunsigned(u: Cardinal); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_rawgetp(idx: Integer; p: Pointer); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_rawsetp(idx: Integer; p: Pointer); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_resume(from: PLuaState; narg: Integer; const UNUSED_PROPERTY: Boolean = True): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF} // 5.2 version
function lua_tounsignedx(idx: Integer; isnum: PInteger): Cardinal; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_upvalueid(funcidx, n: Integer): Pointer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_upvaluejoin(fidx1, n1, fidx2, n2: Integer); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_version: PInteger; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaopen_bit32: Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaopen_coroutine: Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
{$ENDREGION}
{$REGION 'ILua52AuxLocal'}
function luaL_buffinitsize(B: PLuaLBuffer; sz: Cardinal): PAnsiChar; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_checkunsigned(narg: Integer): Cardinal; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure luaL_checkversion; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_execresult(stat: Integer): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_fileresult(stat: Integer; fname: PAnsiChar): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_getsubtable(idx: Integer; fname: PAnsiChar): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_len(idx: Integer): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_loadbufferx(buff: PAnsiChar; sz: Cardinal; name, mode: PAnsiChar): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_loadfilex(filename, mode: PAnsiChar): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_optunsigned(narg: Integer; u: Cardinal): Cardinal; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure luaL_requiref(modname: PansiChar; openf: TLuaDelphiFunction; glb: Integer); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure luaL_setfuncs(lreg: PluaLReg; nup: Integer); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure luaL_setmetatable(tname: PAnsiChar); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_testudata(narg: Integer; tname: PAnsiChar): Pointer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure luaL_traceback(L1: PLuaState; msg: PAnsiChar; level: Integer); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
{$ENDREGION}
end;
implementation
{$REGION 'Lua 5.2 Base Type'}
{ TLua52Base }
procedure TLua52Base.lua_call(L: PLuaState; nargs, nresults: Integer);
begin
lua_callk(L, nargs, nresults, 0, nil);
end;
function TLua52Base.lua_cpcall(L: PLuaState; func: TLuaDelphiFunction; ud: Pointer): Integer;
begin
// Transparent Call
lua_checkstack(1);
lua_pushcfunction(func);
lua_pushlightuserdata(ud);
Result := lua_pcall(L, 0, 0, 0);
end;
function TLua52Base.lua_equal(L: PLuaState; idx1, idx2: Integer): LongBool;
begin
// Transparent Call
Result := lua_compare(L, idx1, idx2, LUA_OPEQ);
end;
procedure TLua52Base.lua_getfenv(L: PLuaState; idx: Integer);
begin
lua_getuservalue(L, idx);
end;
function TLua52Base.lua_lessthan(L: PLuaState; idx1, idx2: Integer): LongBool;
begin
Result := lua_compare(L, idx1, idx2, LUA_OPLT);
end;
function TLua52Base.lua_load(L: PLuaState; reader: TLuaReaderFunction; dt: Pointer; const chunkname: PAnsiChar): Integer;
begin
// Transparent Call
Result := lua_load(L, reader, dt, chunkname, nil);
end;
function TLua52Base.lua_objlen(L: PLuaState; idx: Integer): Cardinal;
begin
// Transparent Call
Result := lua_rawlen(L, idx);
end;
function TLua52Base.lua_pcall(L: PLuaState; nargs, nresults, errfunc: Integer): Integer;
begin
// Transparent Call
Result := lua_pcallk(L, nargs, nresults, errfunc, 0, nil);
end;
function TLua52Base.lua_setfenv(L: PLuaState; idx: Integer): LongBool;
begin
Result := True;
lua_setuservalue(L, idx);
end;
function TLua52Base.lua_setmetatable(L: PLuaState; objindex: Integer): LongBool;
begin
Result := True;
lua_setmetatable(FLuaState, objindex);
end;
function TLua52Base.lua_tointeger(L: PLuaState; idx: Integer): Integer;
begin
Result := lua_tointegerx(L, idx, nil);
end;
function TLua52Base.lua_tonumber(L: PLuaState; idx: Integer): Double;
begin
Result := lua_tonumberx(L, idx, nil);
end;
function TLua52Base.lua_yield(L: PLuaState; nresults: Integer): Integer;
begin
// Transparent Call
Result := lua_yieldk(L, nresults, 0, nil);
end;
{$ENDREGION}
{$REGION 'Lua 5.2 Common Type'}
{ TLua51Common }
function TLua51Common.luaL_buffinitsize(B: PLuaLBuffer; sz: Cardinal): PAnsiChar;
begin
Result := luaL_buffinitsize(FLuaState, B, sz);
end;
function TLua51Common.luaL_checkunsigned(narg: Integer): Cardinal;
begin
Result := luaL_checkunsigned(FLuaState, narg);
end;
procedure TLua51Common.luaL_checkversion;
begin
luaL_checkversion(FLuaState);
end;
function TLua51Common.luaL_execresult(stat: Integer): Integer;
begin
Result := luaL_execresult(FLuaState, stat);
end;
function TLua51Common.luaL_fileresult(stat: Integer; fname: PAnsiChar): Integer;
begin
Result := luaL_fileresult(FLuaState, stat, fname);
end;
function TLua51Common.luaL_getsubtable(idx: Integer; fname: PAnsiChar): Integer;
begin
Result := luaL_getsubtable(FLuaState, idx, fname);
end;
function TLua51Common.luaL_len(idx: Integer): Integer;
begin
Result := luaL_len(FLuaState, idx);
end;
function TLua51Common.luaL_loadbufferx(buff: PAnsiChar; sz: Cardinal; name, mode: PAnsiChar): Integer;
begin
Result := luaL_loadbufferx(FLuaState, sz, name, mode);
end;
function TLua51Common.luaL_loadfilex(filename, mode: PAnsiChar): Integer;
begin
Result := luaL_loadfilex(FLuaState, filename, mode);
end;
function TLua51Common.luaL_optunsigned(narg: Integer; u: Cardinal): Cardinal;
begin
Result := luaL_optunsigned(FLuaState, narg, u);
end;
procedure TLua51Common.luaL_requiref(modname: PansiChar; openf: TLuaDelphiFunction; glb: Integer);
begin
luaL_requiref(FLuaState, modname, openf, glb);
end;
procedure TLua51Common.luaL_setfuncs(lreg: PluaLReg; nup: Integer);
begin
luaL_setfuncs(FLuaState, lreg, nup);
end;
procedure TLua51Common.luaL_setmetatable(tname: PAnsiChar);
begin
luaL_setmetatable(FLuaState, tname);
end;
function TLua51Common.luaL_testudata(narg: Integer; tname: PAnsiChar): Pointer;
begin
Result := luaL_testudata(FLuaState, narg, tname);
end;
procedure TLua51Common.luaL_traceback(L1: PLuaState; msg: PAnsiChar; level: Integer);
begin
luaL_traceback(FLuaState, L1, msg, level);
end;
function TLua51Common.luaopen_bit32: Integer;
begin
Result := luaopen_bit32(FLuaState);
end;
function TLua51Common.luaopen_coroutine: Integer;
begin
Result := luaopen_coroutine(FLuaState);
end;
function TLua51Common.lua_absindex(idx: Integer): Integer;
begin
Result := lua_absindex(FLuaState, idx);
end;
function TLua51Common.lua_arith(op: Integer): Integer;
begin
Result := lua_arith(FLuaState, op);
end;
procedure TLua51Common.lua_copy(fromidx, toidx: Integer);
begin
lua_copy(FLuaState, fromidx, toidx);
end;
function TLua51Common.lua_getctx(ctx: PInteger): Integer;
begin
Result := lua_getctx(FLuaState, ctx);
end;
procedure TLua51Common.lua_len(idx: Integer);
begin
lua_len(FLuaState, idx);
end;
procedure TLua51Common.lua_pushunsigned(u: Cardinal);
begin
lua_pushunsigned(FLuaState, u);
end;
procedure TLua51Common.lua_rawgetp(idx: Integer; p: Pointer);
begin
lua_rawgetp(FLuaState, idx, p);
end;
procedure TLua51Common.lua_rawsetp(idx: Integer; p: Pointer);
begin
lua_rawsetp(FLuaState, idx, p);
end;
function TLua51Common.lua_resume(from: PLuaState; narg: Integer; const UNUSED_PROPERTY: Boolean): Integer;
begin
Result := lua_resume(FLuaState, from, narg);
end;
function TLua51Common.lua_tounsignedx(idx: Integer; isnum: PInteger): Cardinal;
begin
Result := lua_tounsignedx(FLuaState, idx, isnum);
end;
function TLua51Common.lua_upvalueid(funcidx, n: Integer): Pointer;
begin
Result := lua_upvalueid(FLuaState, funcidx, n);
end;
procedure TLua51Common.lua_upvaluejoin(fidx1, n1, fidx2, n2: Integer);
begin
lua_upvaluejoin(FLuaState, fidx1, n1, fidx2, n2);
end;
function TLua51Common.lua_version: PInteger;
begin
Result := lua_version(FLuaState);
end;
{$ENDREGION}
end.
|
{(*}
(*------------------------------------------------------------------------------
Delphi Code formatter source code
The Original Code is AlignAssign.pas, released April 2000.
The Initial Developer of the Original Code is Anthony Steele.
Portions created by Anthony Steele are Copyright (C) 1999-2008 Anthony Steele.
All Rights Reserved.
Contributor(s): Anthony Steele.
The contents of this file are subject to the Mozilla Public License Version 1.1
(the "License"). you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.mozilla.org/NPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied.
See the License for the specific language governing rights and limitations
under the License.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 or later (the "GPL")
See http://www.gnu.org/licenses/gpl.html
------------------------------------------------------------------------------*)
{*)}
unit AlignAssign;
{ AFS 3 Feb 2K
Align the RHS of consecutive assign statements
}
{$I JcfGlobal.inc}
interface
uses SourceToken, AlignBase;
type
TAlignAssign = class(TAlignBase)
private
// don't align across block nexting levels
fiStartBlockLevel: integer;
fiStartCaseLevel: integer;
protected
{ TokenProcessor overrides }
function IsTokenInContext(const pt: TSourceToken): boolean; override;
{ AlignStatements overrides }
function TokenIsAligned(const pt: TSourceToken): boolean; override;
function TokenEndsStatement(const pt: TSourceToken): boolean; override;
function TokenEndsAlignment(const pt: TSourceToken): boolean; override;
procedure ResetState; override;
public
constructor Create; override;
function IsIncludedInSettings: boolean; override;
end;
implementation
uses
{ local}
Tokens, FormatFlags, JcfSettings, TokenUtils,
ParseTreeNodeType;
{ TAlignAssign }
constructor TAlignAssign.Create;
begin
inherited;
FormatFlags := FormatFlags + [eAlignAssign];
fiStartBlockLevel := -1;
fiStartCaseLevel := -1;
end;
procedure TAlignAssign.ResetState;
begin
inherited;
fiStartBlockLevel := -1;
fiStartCaseLevel := -1;
end;
{ a token that ends an assign block }
function TAlignAssign.IsIncludedInSettings: boolean;
begin
Result := ( not JcfFormatSettings.Obfuscate.Enabled) and JcfFormatSettings.Align.AlignAssign;
end;
function TAlignAssign.IsTokenInContext(const pt: TSourceToken): boolean;
begin
Result := InStatements(pt) and pt.HasParentNode(nAssignment);
end;
function TAlignAssign.TokenEndsStatement(const pt: TSourceToken): boolean;
begin
if pt = nil then
Result := True
{ only look at solid tokens }
else if (pt.TokenType in [ttReturn, ttWhiteSpace]) then
begin
Result := False;
end
else
begin
Result := (pt.TokenType = ttSemiColon) or (pt.WordType = wtReservedWord) or
( not InStatements(pt));
end;
end;
function TAlignAssign.TokenEndsAlignment(const pt: TSourceToken): boolean;
begin
// ended by a blank line
Result := IsBlankLineEnd(pt);
end;
function TAlignAssign.TokenIsAligned(const pt: TSourceToken): boolean;
begin
{ keep the indent - don't align statement of differing indent levels }
if (fiStartBlockLevel < 0) and (pt.TokenType in AssignmentDirectives) then
fiStartBlockLevel := BlockLevel(pt);
if (fiStartCaseLevel < 0) and (pt.TokenType in AssignmentDirectives) then
fiStartCaseLevel := CaseLevel(pt);
Result := (pt.TokenType in AssignmentDirectives) and
(fiStartBlockLevel = BlockLevel(pt)) and (fiStartCaseLevel = CaseLevel(pt));
end;
end.
|
unit DW.PushClient;
(*
DelphiWorlds PushClient project
------------------------------------------
A cross-platform method of using Firebase Cloud Messaging (FCM) to receive push notifications
This project was inspired by the following article:
http://thundaxsoftware.blogspot.co.id/2017/01/firebase-cloud-messaging-with-delphi.html
*)
{$I DW.GlobalDefines.inc}
interface
uses
// RTL
System.PushNotification,
// DW
DW.RegisterFCM;
type
TPushSystem = (APS, GCM);
TRegistrationErrorEvent = procedure(Sender: TObject; const Error: string) of object;
TPushClient = class(TObject)
private
FBundleID: string;
FDeviceID: string;
FDeviceToken: string;
FPushService: TPushService;
FPushSystem: TPushSystem;
FRegisterFCM: TRegisterFCM;
FServerKey: string;
FServiceConnection: TPushServiceConnection;
FUseSandbox: Boolean;
FOnChange: TPushServiceConnection.TChangeEvent;
FOnReceiveNotification: TPushServiceConnection.TReceiveNotificationEvent;
FOnRegistrationError: TRegistrationErrorEvent;
procedure ActivateAsync;
procedure ClearDeviceInfo;
procedure CreatePushService;
procedure DoChange(AChange: TPushService.TChanges);
procedure DoRegistrationError(const AError: string);
function GetActive: Boolean;
function GetGCMAppID: string;
procedure ServiceConnectionChangeHandler(Sender: TObject; AChange: TPushService.TChanges);
procedure ServiceConnectionReceiveNotificationHandler(Sender: TObject; const ANotification: TPushServiceNotification);
procedure SetActive(const Value: Boolean);
procedure SetGCMAppID(const Value: string);
procedure RegisterFCMRequestCompleteHandler(Sender: TObject; const Success: Boolean; const RequestResult: string);
public
constructor Create;
destructor Destroy; override;
property Active: Boolean read GetActive write SetActive;
property BundleID: string read FBundleID write FBundleID;
property DeviceID: string read FDeviceID;
property DeviceToken: string read FDeviceToken;
property GCMAppID: string read GetGCMAppID write SetGCMAppID;
property PushSystem: TPushSystem read FPushSystem;
property UseSandbox: Boolean read FUseSandbox write FUseSandbox;
property ServerKey: string read FServerKey write FServerKey;
property OnChange: TPushServiceConnection.TChangeEvent read FOnChange write FOnChange;
property OnReceiveNotification: TPushServiceConnection.TReceiveNotificationEvent read FOnReceiveNotification write FOnReceiveNotification;
property OnRegistrationError: TRegistrationErrorEvent read FOnRegistrationError write FOnRegistrationError;
end;
implementation
uses
// RTL
System.SysUtils, System.Threading, System.Classes,
// FMX
{$IF Defined(IOS)}
FMX.PushNotification.iOS;
{$ENDIF}
{$IF Defined(Android)}
FMX.PushNotification.Android;
{$ENDIF}
{ TPushClient }
constructor TPushClient.Create;
begin
inherited;
CreatePushService;
end;
destructor TPushClient.Destroy;
begin
FServiceConnection.Free;
FPushService.Free;
FRegisterFCM.Free;
inherited;
end;
procedure TPushClient.CreatePushService;
begin
case TOSVersion.Platform of
TOSVersion.TPlatform.pfiOS:
begin
FPushSystem := TPushSystem.APS;
FPushService := TPushServiceManager.Instance.GetServiceByName(TPushService.TServiceNames.APS);
// FCM for iOS requires that the APNs token be "converted" to an FCM token. This is what TRegisterFCM does
FRegisterFCM := TRegisterFCM.Create;
FRegisterFCM.OnRequestComplete := RegisterFCMRequestCompleteHandler;
end;
TOSVersion.TPlatform.pfAndroid:
begin
FPushSystem := TPushSystem.GCM;
FPushService := TPushServiceManager.Instance.GetServiceByName(TPushService.TServiceNames.GCM);
end;
else
raise Exception.Create('Unsupported platform');
end;
FServiceConnection := TPushServiceConnection.Create(FPushService);
FServiceConnection.OnChange := ServiceConnectionChangeHandler;
FServiceConnection.OnReceiveNotification := ServiceConnectionReceiveNotificationHandler;
end;
procedure TPushClient.DoChange(AChange: TPushService.TChanges);
begin
if FServiceConnection.Active then
FDeviceID := FPushService.DeviceIDValue[TPushService.TDeviceIDNames.DeviceID];
if Assigned(FOnChange) then
TThread.Synchronize(nil,
procedure
begin
FOnChange(Self, AChange);
end
);
end;
procedure TPushClient.DoRegistrationError(const AError: string);
begin
if Assigned(FOnRegistrationError) then
FOnRegistrationError(Self, AError);
end;
function TPushClient.GetActive: Boolean;
begin
Result := FServiceConnection.Active;
end;
function TPushClient.GetGCMAppID: string;
begin
Result := FPushService.AppProps[TPushService.TAppPropNames.GCMAppID];
end;
procedure TPushClient.RegisterFCMRequestCompleteHandler(Sender: TObject; const Success: Boolean; const RequestResult: string);
begin
// FCM token registration has completed
if Success then
begin
FDeviceToken := RequestResult;
DoChange([TPushService.TChange.DeviceToken]);
end
else
DoRegistrationError(RequestResult);
end;
procedure TPushClient.ServiceConnectionChangeHandler(Sender: TObject; AChange: TPushService.TChanges);
var
LTokenChange: Boolean;
LDeviceToken: string;
begin
LTokenChange := TPushService.TChange.DeviceToken in AChange;
if LTokenChange then
begin
LDeviceToken := FPushService.DeviceTokenValue[TPushService.TDeviceTokenNames.DeviceToken];
// If the token needs registration with FCM, FRegisterFCM will be non-nil
if FRegisterFCM <> nil then
FRegisterFCM.RegisterAPNToken(FBundleID, FServerKey, LDeviceToken, FUseSandbox)
else
FDeviceToken := LDeviceToken;
end;
// If it's not a token change, or registration is not required, call DoChange immediately
if not LTokenChange or (FRegisterFCM = nil) then
DoChange(AChange);
end;
procedure TPushClient.ServiceConnectionReceiveNotificationHandler(Sender: TObject; const ANotification: TPushServiceNotification);
begin
if Assigned(FOnReceiveNotification) then
FOnReceiveNotification(Self, ANotification);
end;
procedure TPushClient.SetActive(const Value: Boolean);
begin
if Value = FServiceConnection.Active then
Exit; // <=======
if Value then
ActivateAsync
else
ClearDeviceInfo;
end;
procedure TPushClient.ActivateAsync;
begin
TTask.Run(
procedure
begin
FServiceConnection.Active := True;
end
);
end;
procedure TPushClient.SetGCMAppID(const Value: string);
begin
FPushService.AppProps[TPushService.TAppPropNames.GCMAppID] := Value;
end;
procedure TPushClient.ClearDeviceInfo;
begin
FDeviceID := '';
FDeviceToken := '';
end;
end.
|
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
unit frmMain;
interface
uses
Windows, Messages, Classes, Graphics, Forms, ExtCtrls, Menus,
Controls, Dialogs, SysUtils,
OpenGL, DGLUT;
type
TfrmGL = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormPaint(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
DC : HDC;
hrc : HGLRC;
procedure SetDCPixelFormat;
end;
const
GLF_START_LIST = 1000;
var
frmGL: TfrmGL;
implementation
{$R *.DFM}
{=======================================================================
Вывод текста}
procedure OutText (Litera : PChar);
begin
glListBase(GLF_START_LIST);
glCallLists(Length (Litera), GL_UNSIGNED_BYTE, Litera);
end;
{=======================================================================
Перерисовка окна}
procedure TfrmGL.FormPaint(Sender: TObject);
begin
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
// трехмерность
glLoadIdentity;
glTranslatef(0.0, 0.0, -8.0);
glRotatef(30.0, 1.0, 0.0, 0.0);
glRotatef(30.0, 0.0, 1.0, 0.0); // поворот на угол
glutSolidTeapot (1.0);
glRasterPos2f (-0.4,-1.75);
OutText ('Чайник'); // вывод текста
SwapBuffers(DC);
end;
{=======================================================================
Установка формата пикселей}
procedure TfrmGL.SetDCPixelFormat;
var
nPixelFormat: Integer;
pfd: TPixelFormatDescriptor;
begin
FillChar(pfd, SizeOf(pfd), 0);
pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER;
nPixelFormat := ChoosePixelFormat(DC, @pfd);
SetPixelFormat(DC, nPixelFormat, @pfd);
end;
{=======================================================================
Создание окна}
procedure TfrmGL.FormCreate(Sender: TObject);
begin
DC := GetDC(Handle);
SetDCPixelFormat;
hrc := wglCreateContext(DC);
wglMakeCurrent(DC, hrc);
glClearColor (0.3, 0.1, 0.5, 1.0);
wglUseFontBitmaps (Canvas.Handle, 0, 255, GLF_START_LIST);
glEnable(GL_DEPTH_TEST);// разрешаем тест глубины
glEnable(GL_LIGHTING); // разрешаем работу с освещенностью
glEnable(GL_LIGHT0); // включаем источник света 0
end;
{=======================================================================
Изменение размеров окна}
procedure TfrmGL.FormResize(Sender: TObject);
begin
glViewport(0, 0, ClientWidth, ClientHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity;
gluPerspective(30.0, ClientWidth / ClientHeight, 1.0, 20.0);
glMatrixMode(GL_MODELVIEW);
InvalidateRect(Handle, nil, False);
end;
{=======================================================================
Конец работы приложения}
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
glDeleteLists (GLF_START_LIST, 256);
wglMakeCurrent(0, 0);
wglDeleteContext(hrc);
ReleaseDC(Handle, DC);
DeleteDC(DC);
end;
procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
If Key = VK_ESCAPE then Close
end;
end.
|
unit Security.Internal;
interface
uses
Vcl.Controls, Vcl.ExtCtrls, System.SysUtils, Vcl.StdCtrls, System.Hash
, Security.Login.Interfaces
, Security.ChangePassword.Interfaces
, Security.Permission.Interfaces
, Security.Matrix.Interfaces
;
type
Internal = class
private
public
class function RemoveAcento(const aValue: string): String;
class function TrimInOut(aValue: string): string;
class function UpperTrim(const aValue: string): string;
class function Empty(const aValue: string): boolean;
class function IsEmpty(aValue: string): boolean;
class function MD5(const aValue: string; aUpperCase: boolean = True): string;
class procedure Die(aMessage: string);
class procedure Required(const aValue: Int64; const aError: string = ''); overload;
class procedure Required(const aValue: string; const aError: string = ''); overload;
class procedure Required(const aControl: TWinControl; const aValue: string); overload;
class procedure Required(const aControl: TWinControl; const aValue: string; const aError: string); overload;
class procedure Required(const aValue: TResultNotifyEvent; const aError: string = 'O evento de Retorno não foi definido.'); overload;
class procedure Required(const aValue: TAuthNotifyEvent; const aError: string = 'O evento de Login não foi definido.'); overload;
class procedure Required(const aValue: TChangePasswordNotifyEvent; const aError: string = 'O evento de Alteração de Senha não foi definido.'); overload;
class procedure Required(const aValue: TPermissionNotifyEvent; const aError: string = 'O evento de Manutenção da Permissão não foi definido.'); overload;
class procedure Required(const aValue: TMatrixNotifyEvent; const aError: string = 'O evento de Manutenção da Matriz de permissões não foi definido.'); overload;
class procedure Validate(aEdit: TEdit); overload;
class procedure Validate(aError: string; aEdit: TEdit; aImage: TImage; aPanel: TPanel); overload;
class procedure Validate(
const aControl: TWinControl;
const aTest: boolean;
const aMessageErroTestFalse: string;
const aPanelImageError: TPanel;
const aImageError: TImage
); overload;
end;
implementation
class function Internal.RemoveAcento(const aValue: string): String;
type
USASCIIString = type AnsiString(20127); // 20127 = us ascii
begin
Result := String(USASCIIString(aValue));
end;
class function Internal.TrimInOut(aValue: string): string;
var
LSize: integer;
begin
while True do
begin
LSize := Length(aValue);
aValue := StringReplace(aValue, #32#32, #32, [rfReplaceAll, rfIgnoreCase]);
if LSize = Length(aValue) then
Break;
end;
Result := Trim(aValue);
end;
class function Internal.UpperTrim(const aValue: string): string;
begin
Result := Internal.TrimInOut(UpperCase(aValue));
end;
class function Internal.Empty(const aValue: string): boolean;
begin
Result :=
(
(Length(aValue.Trim) = 0)
or
(aValue = format(' %s %s ', [TFormatSettings.Create.DateSeparator, TFormatSettings.Create.DateSeparator]))
or
(aValue = format(' %s %s ', [TFormatSettings.Create.DateSeparator, TFormatSettings.Create.DateSeparator]))
or
(aValue = ' - - ') or (aValue = ' - - ')
or
(aValue = ' . . ') or (aValue = ' . . ')
or
(aValue = ' / / ') or (aValue = ' / / ')
);
end;
class function Internal.IsEmpty(aValue: string): boolean;
begin
Result := Internal.Empty(aValue);
end;
class procedure Internal.Die(aMessage: string);
begin
if not aMessage.IsEmpty then
raise Exception.Create(aMessage);
end;
class function Internal.MD5(const aValue: string; aUpperCase: boolean = True): string;
begin
Result := System.Hash.THashMD5.GetHashString(aValue);
if aUpperCase then
Result := UpperCase(Result);
end;
class procedure Internal.Validate(aEdit: TEdit);
begin
if not SameStr(aEdit.Text, EmptyStr) then
Exit;
aEdit.SetFocus;
Abort;
end;
class procedure Internal.Validate(aError: string; aEdit: TEdit; aImage: TImage; aPanel: TPanel);
begin
aPanel.Visible := false;
if aError.IsEmpty then
Exit;
aImage.Hint := aError;
aPanel.Visible := True;
aEdit.SetFocus;
Abort;
end;
class procedure Internal.Validate(
const aControl: TWinControl;
const aTest: boolean;
const aMessageErroTestFalse: string;
const aPanelImageError: TPanel;
const aImageError: TImage
);
begin
begin
aImageError.Hint := aMessageErroTestFalse;
aPanelImageError.Visible := aTest;
if aTest then
begin
aControl.SetFocus;
Abort;
end;
end;
end;
class procedure Internal.Required(const aValue: Int64; const aError: string);
begin
if aValue <> 0 then
Exit;
if not aError.IsEmpty then
raise Exception.Create(aError);
Abort;
end;
class procedure Internal.Required(const aValue: string; const aError: string = '');
begin
if not aValue.IsEmpty then
Exit;
if not aError.IsEmpty then
raise Exception.Create(aError);
Abort;
end;
class procedure Internal.Required(const aControl: TWinControl; const aValue: string);
begin
if not aValue.IsEmpty then
Exit;
aControl.SetFocus;
Abort;
end;
class procedure Internal.Required(const aControl: TWinControl; const aValue: string; const aError: string);
begin
if not aValue.IsEmpty then
Exit;
aControl.SetFocus;
if not aError.IsEmpty then
raise Exception.Create(aError);
Abort;
end;
class procedure Internal.Required(const aValue: TResultNotifyEvent; const aError: string);
begin
if not Assigned(aValue) then
raise Exception.Create(aError);
end;
class procedure Internal.Required(const aValue: TAuthNotifyEvent; const aError: string = 'O evento de Login não foi definido.');
begin
if not Assigned(aValue) then
raise Exception.Create(aError);
end;
class procedure Internal.Required(const aValue: TChangePasswordNotifyEvent; const aError: string = 'O evento de Alteração de Senha não foi definido.');
begin
if not Assigned(aValue) then
raise Exception.Create(aError);
end;
class procedure Internal.Required(const aValue: TPermissionNotifyEvent; const aError: string = 'O evento de Manutenção da Permissão não foi definido.');
begin
if not Assigned(aValue) then
raise Exception.Create(aError);
end;
class procedure Internal.Required(const aValue: TMatrixNotifyEvent; const aError: string);
begin
if not Assigned(aValue) then
raise Exception.Create(aError);
end;
end.
|
unit ClntForm;
{ This program works in conjunction with the Monitor.dpr project to demonstrate
advanced Win32 programming topics. See Monform.pas for more information }
interface
uses
Forms, Windows, Messages, SysUtils, StdCtrls, Classes, Controls,
IPCThrd, Dialogs, ComCtrls, Graphics;
const
WM_UPDATESTATUS = WM_USER + 2;
type
TClientForm = class(TForm)
StatusBar: TStatusBar;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure FormResize(Sender: TObject);
procedure FormClick(Sender: TObject);
private
Flags: TClientFlags;
IPCClient: TIPCClient;
//MC! FStatusText: string;
procedure OnConnect(Sender: TIPCThread; Connecting: Boolean);
procedure OnSignal(Sender: TIPCThread; Data: TEventData);
procedure UpdateStatusBar(var Msg: TMessage); message WM_UPDATESTATUS;
end;
var
ClientForm: TClientForm;
implementation
{$R *.DFM}
procedure TClientForm.FormCreate(Sender: TObject);
var
CNo, VCnt: Integer;
//MC! C, T: Integer;
begin
Caption := Format('%s (%X)', [Application.Title, GetCurrentProcessID]);
try
IPCClient := TIPCClient.Create(GetCurrentProcessID, Caption);
IPCClient.OnConnect := OnConnect;
IPCClient.OnSignal := OnSignal;
IPCClient.Activate;
if not (IPCClient.State = stConnected) then OnConnect(nil, False);
VCnt := Screen.Height div (Height + 10);
CNo := IPCClient.ClientCount - 1;
Top := (CNo mod VCnt) * (Height + 10) + 10;
Left := (Screen.Width div 2) + (CNo div VCnt) * (Width + 10);
except
Application.HandleException(ExceptObject);
Application.Terminate;
end;
end;
procedure TClientForm.FormDestroy(Sender: TObject);
begin
IPCClient.Free;
end;
procedure TClientForm.OnConnect(Sender: TIPCThread; Connecting: Boolean);
begin
PostMessage(Handle, WM_UPDATESTATUS, WPARAM(Connecting), 0);
end;
procedure TClientForm.OnSignal(Sender: TIPCThread; Data: TEventData);
begin
Flags := Data.Flags;
end;
procedure TClientForm.FormMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
var
EventData: TEventData;
begin
if cfMouseMove in Flags then
begin
EventData.X := X;
EventData.Y := Y;
EventData.Flag := cfMouseMove;
IPCClient.SignalMonitor(EventData);
end;
end;
procedure TClientForm.FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
EventData: TEventData;
begin
if cfMouseDown in Flags then
begin
EventData.X := X;
EventData.Y := Y;
EventData.Flag := cfMouseDown;
IPCClient.SignalMonitor(EventData);
end;
end;
procedure TClientForm.FormResize(Sender: TObject);
var
EventData: TEventData;
begin
if cfResize in Flags then
begin
EventData.X := Width;
EventData.Y := Height;
EventData.Flag := cfResize;
IPCClient.SignalMonitor(EventData);
end;
end;
procedure TClientForm.FormClick(Sender: TObject);
begin
if IPCClient.State <> stConnected then
IPCClient.MakeCurrent;
end;
procedure TClientForm.UpdateStatusBar(var Msg: TMessage);
const
ConnectStr: Array[Boolean] of PChar = ('Not Connected', 'Connected');
begin
StatusBar.SimpleText := ConnectStr[Boolean(Msg.WParam)];
end;
end.
|
unit Attributes;
interface
uses
System.Rtti, System.SysUtils;
type
TDataFieldAttribute = class(TCustomAttribute)
private
FCampo: string;
FValidarCampo: Boolean;
FMensagem: string;
FCampoObrigado: Boolean;
public
constructor Create(ACampo, AMsg: string; AValidar: Boolean);
procedure Validar(AValue : TValue); virtual;
property Campo: string read FCampo write FCampo;
property ValidarCampo: Boolean read FValidarCampo write FValidarCampo;
property Mensagem: string read FMensagem write FMensagem;
property CampoObrigatorio: Boolean read FCampoObrigado write FCampoObrigado;
end;
implementation
{ TDataFieldAttribute }
constructor TDataFieldAttribute.Create(ACampo, AMsg: string; AValidar: Boolean);
begin
FCampo := ACampo;
FValidarCampo := AValidar;
FMensagem := AMsg;
end;
procedure TDataFieldAttribute.Validar(AValue: TValue);
begin
if FValidarCampo then
begin
FCampoObrigado := AValue.AsString = EmptyStr;
end;
end;
{ TDataTableAttribute }
end.
|
unit str_params_1;
interface
implementation
var S: string;
procedure Test<T>(const Str: T);
begin
S := Str;
end;
initialization
Test('aaa');
finalization
Assert(S = 'aaa');
end. |
{===============================================================================
公用函数
+ function GetSpecialFolder 获取Windows系统文件夹
+ function GetTempFolder 获取Windows临时文件夹
+ procedure WaitForSeconds 延时等待函数,等待时处理其它事件
+ function IntToBCD 整型数据转换成BCD码
+ function IntToByte 从整型数据中取某一个字节
+ function CalCS 计算CS校验码
+ function BCDToDouble BCD码转换Double, nDigital为小数位数
+ procedure WriteRunLog 保存运行记录
+ function CheckAndCreateDir 检查文件夹是否存在,不存在创建
+ function GetFileVersion 获取完整文件版本信息
+ function CheckPath 检查目录的完整性
+ function GetFloatIntLength 获取浮点数据整数部分长度,不包含负号
+ function FileCopy 文件拷贝,如果显示进度,文件将被分成100段进行拷贝
+ procedure ClearStringList 清除 TStringList / TStrings 及 内部对象
+ function ApplicationExists 判断程序是否已经运行
+ function GetPartValue 获取用spart分割的值列表
+ function IntToLenStr 整型转化成固定长度的字符串,如果整型值过大则显示所有整型值
+ function FormatDT 格式化时间
+ function GetPointLen 获取两点之间的距离
+ function GetMD5 MD5计算
+ function CheckPortStatus 查询端口状态
+ procedure GetAllCommPorts 获取所有端口列表
+ function PortStatusToStr 端口状态转换成字符串
+ function PortNameToSN 串口名转换成串口号
+ function PortSNToName 串口号转换成串口名
+ function StrToPacks 字符串转换成数据包 '12 34' ---> $31 32 20 33
+ function PacksToStr 数据包转换成字符串 $31 32 20 33 ---> '12 3'
+ function StrToBCDPacks 字符串转换BCD数据包 '12 34'或'1234' ---> $12 34
+ function BCDPacksToStr BCD数据包转换成字符串 $12 34 ---> '12 34'
+ procedure HintMessage 自定义信息提示框函数
===============================================================================}
unit xFunction;
interface
uses System.Classes,EncdDecd, IOUtils, IdHash, IdGlobal,
Math, StrUtils, DateUtils, IdHashMessageDigest, xVCL_FMX,
{$IFDEF MSWINDOWS}
Winapi.Windows, ShlObj, CommCtrl, Messages,
{$ENDIF}
{$IFDEF ANDROID}
Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.JavaTypes,FMX.Helpers.Android,
Androidapi.Helpers,
{$ENDIF}
{$IFDEF IOS}
FMX.Platform.iOS,iOSapi.Foundation,Macapi.ObjectiveC,
{$ENDIF}
{$IFDEF MACOS}
FMX.Platform.Mac, Macapi.Foundation, Macapi.ObjectiveC,
{$ENDIF}
System.SysUtils;
/// <summary>
/// 获取文件路径 不存在则创建
/// </summary>
function FilePath(sFile:String = ''):String;
/// <summary>
/// BCD字节转换成整型字节
/// </summary>
function BCDToByte( n : Byte ) : Byte;
/// <summary>
/// 延时等待函数,等待时处理其它事件
/// </summary>
/// <param name="nMSeconds">毫秒</param>
procedure WaitForSeconds( nMSeconds : Cardinal );
/// <summary>
/// 整型数据转换成BCD码
/// </summary>
/// <param name="nNum">整型数据</param>
/// <param name="nLen">BCD码字节长度</param>
/// <returns>BCD码字节数组</returns>
function IntToBCD( nNum, nLen : Integer): TBytes; overload;
function IntToBCD( nNum : Int64; nLen : Integer): TBytes; overload;
/// <summary>
/// 从整型数据中取某一个字节
/// </summary>
/// <param name="n">整型数据</param>
/// <param name="nPos">从低位开始的第*个字节, nPos = 0, 1, 2, 3...</param>
/// <returns>字节数据</returns>
function IntToByte( const n, nPos : Integer ) : Byte; overload;
function IntToByte( const n : Int64; const nPos : Integer ) : Byte; overload;
/// <summary>
/// 计算CS校验码
/// </summary>
/// <param name="AData">字节数组</param>
/// <param name="AFrom">开始字节</param>
/// <param name="ATo">终止字节,-1为最大长度</param>
function CalCS( AData : TBytes; AFrom : Integer = 0; ATo : Integer = -1 ) : Byte;
/// <summary>
/// BCD转换Double, nDigital为小数位数
/// </summary>
/// <param name="aBCD"></param>
/// <param name="nDigital"></param>
/// <returns></returns>
function BCDToDouble( aBCD : TBytes; nDigital : Integer ) : Double;
/// <summary>
/// 保存运行记录
/// </summary>
/// <param name="sLogFileName">运行记录文件</param>
/// <param name="sRunMsg">运行记录</param>
procedure WriteRunLog( sLogFileName : string; sRunMsg : string );
/// <summary>
/// 检查文件夹是否存在,不存在创建
/// </summary>
/// <param name="sDirPath">文件夹路径</param>
/// <returns>是否存在</returns>
function CheckAndCreateDir( sDirPath : string ) : Boolean;
/// <summary>
/// 获取文件版本
/// </summary>
/// <param name="sFileName">文件名 如果是空 则获取当前程序版本</param>
/// <returns>文件版本号</returns>
function GetFileVersion(sFileName : string = ''):string;
/// <summary>
/// 检查目录的完整性
/// 例如 c:\windows 的完整路径为 c:\windows\
/// </summary>
/// <param name="sPath">原路径</param>
/// <param name="sDelim">分隔符 \ 或 /</param>
/// <returns>完整路径</returns>
function CheckPath( sPath, sDelim : string ) : string;
/// <summary>
/// 获取浮点数据整数部分长度,不包含负号
/// </summary>
/// <param name="d">浮点数据</param>
/// <returns>整数部分长度</returns>
function GetFloatIntLength( d : Double ) : Integer;
/// <summary>
/// 清除 TStringList / TStrings 及 内部对象
/// </summary>
/// <param name="sl">TStringList / TStrings</param>
procedure ClearStringList( sl : TStringList );
/// <summary>
/// 获取用spart分割的值列表
/// </summary>
/// <param name="slValue">值列表</param>
/// <param name="sText">值字符串</param>
/// <param name="sPart">分隔符</param>
/// <returns>是否成功</returns>
function GetPartValue( slValue : TStringList; const sText : string;
const sPart : Char ): Boolean;
/// <summary>
/// 整型转化成固定长度的字符串,如果整型值过大则显示所有整型值
/// </summary>
/// <param name="nValue">整型值</param>
/// <param name="nStrLen">转换后长度</param>
/// <param name="sStr">不够长度补齐的字符 默认为'0'</param>
/// <returns></returns>
function IntToLenStr(nValue: Int64; nStrLen : Integer; sStr : string = '0'): string;
/// <summary>
/// 获取字节的第几位的值
/// </summary>
/// <param name="nByte">传入字节</param>
/// <param name="nIndex">字节中的第几位 0-7</param>
/// <returns>字节中的第几位的值 0或者1</returns>
function GetByteBitValue(nByte, nIndex : Byte) : Byte;
/// <summary>
/// 格式化时间
/// </summary>
function FormatDT(sFormat : string; dtValue : TDateTime) : string;
/// <summary>
/// 获取列表删除某个后,当前所处序号 (一个列表删除一行后,所处行序号)
/// </summary>
/// <param name="nCount">列表行数</param>
/// <param name="nDelIndex">当前所处行 从0开始</param>
/// <returns>返回删除后所处行 从0开始</returns>
function GetDelIndex(nCount, nDelIndex : Integer) : Integer;
/// <summary>
/// 获取两点之间的距离
/// </summary>
function GetPointLen(dX1, dY1, dX2, dY2 : Double) : Double;
/// <summary>
/// MD5计算
/// </summary>
function GetMD5(const sStr: String): String;
type
/// <summary>
/// 串口状态
/// </summary>
TPORT_STATUS = (psNone, psAvail, psBusy);
/// <summary>
/// 查询端口状态
/// </summary>
function CheckPortStatus(nPort: Integer): TPORT_STATUS;
/// <summary>
/// 获取所有串口列表
/// </summary>
procedure GetAllCommPorts(APortList : TStrings);
/// <summary>
/// 获取所有串口名称
/// </summary>
function GetAllCommPortsStr : string;
/// <summary>
/// 端口状态转换成字符串
/// </summary>
function PortStatusToStr(AStatus : TPORT_STATUS) : string;
/// <summary>
/// 串口名转换成串口号
/// </summary>
function PortNameToSN(sPortName: string) : Integer;
/// <summary>
/// 串口号转换成串口名
/// </summary>
function PortSNToName(nPortSN: Byte) : string;
/// <summary>
/// 字符串转换成数据包 '12 3' ---> $31 32 20 33
/// </summary>
function StrToPacks( sData : string ) : TBytes;
/// <summary>
/// 数据包转换成字符串 $31 32 20 33 ---> '12 3'
/// </summary>
function PacksToStr(aPacks: TBytes): string;
/// <summary>
/// 字符串转换BCD数据包 '12 34'或'1234' ---> $12 34
/// </summary>
function StrToBCDPacks( sData : string ) : TBytes;
/// <summary>
/// BCD数据包转换成字符串 $12 34 ---> '12 34'
/// </summary>
function BCDPacksToStr(aPacks : TBytes): string;
/// <summary>
/// 提示信息按钮类型
/// hbtOk : 确定; hbtOkCancel: 确定/取消; hbtYesNoCancel : 是/否/取消
/// hbtYesNo : 是/否; hbtAbortRetryIgnore : 终止/重试/忽略; hbtRetryCancel:
/// 重试/取消;
/// </summary>
type
THintBtnType = (hbtOk, hbtOkCancel, hbtYesNoCancel, hbtYesNo, hbtAbortRetryIgnore
, hbtRetryCancel);
/// <summary>
/// 提示信息图标类型
/// hitNoThing : 无, hitHint : 提示, hitInquiry : 询问, hitWarning :警告
/// hitError : 错误
/// </summary>
type
THintIconType = (hitNoThing, hitHint, hitInquiry, hitWarning, hitError);
/// <summary>
/// 提示信息返回类型
/// hrtOk :确定, hrtCancel : 取消, hrtAbort : 终止, hrtRetry:重试
/// hrtIgnore :忽略, hrtYes:是, hrtNo : 否
/// hrtNothing : 无返回
/// </summary>
type
THintResultType = (hrtOk, hrtCancel, hrtAbort, hrtRetry, hrtIgnore,
hrtYes, hrtNo, hrtNothing);
/// <summary>
/// 自定义信息提示框
/// </summary>
/// <param name="nType">0:showmessage 1:messageBox 出Windows系统外统一为:showmessage</param>
/// <param name="sText">提示信息</parma>
/// <param name="sCaption">提示标题 nType为0是可以省略</param>
/// <param name="uType">MessageBox按钮类型 nType为0时就可以省略</param>
/// <param name="uiType">MessageBox图标类型 nType为0时可以省略</param>
/// <returns>MessageBox返回类型 nType为0是可以省略</returns>
function HintMessage(nType : Integer; sText : string; sCaption: string = '';
uType: THintBtnType = hbtOk;
uiType : THintIconType = hitHint) : THintResultType;
implementation
function BCDPacksToStr(aPacks : TBytes): string;
var
i : Integer;
begin
Result := EmptyStr;
for i := 0 to Length(aPacks) - 1 do
begin
if i = 0 then
Result := Result + IntToHex( aPacks[ i ], 2 )
else
Result := Result + ' ' + IntToHex( aPacks[ i ], 2 );
end;
end;
function StrToBCDPacks( sData : string ) : TBytes;
function GetIndex( sValue, sFormat : string ) : Integer;
begin
Result := Pos( sFormat, sValue );
end;
procedure AddValue(var sAddValue : string);
var
nValue : Integer;
begin
SetLength( Result, Length( Result ) + 1 );
TryStrToInt( '$' + sAddValue, nValue );
Result[ Length( Result ) - 1 ] := nValue;
sAddValue := '';
end;
var
s, sValue : string;
i: Integer;
begin
try
SetLength( Result, 0 );
// 删除空格
s := StringReplace(sData ,' ','',[rfReplaceAll]);
// 取值
{$IFDEF ANDROID}
for i := 0 to Length(s) - 1 do
begin
if s[i] <> #0 then
sValue := sValue + s[i];
if Length(sValue) = 2 then
AddValue(sValue);
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
for i := 1 to Length(s) do
begin
if s[i] <> #0 then
sValue := sValue + s[i];
if Length(sValue) = 2 then
AddValue(sValue);
end;
{$ENDIF}
if Length(sValue) = 1 then
AddValue(sValue);
except
end;
end;
function PacksToStr(aPacks: TBytes): string;
var
i: Integer;
begin
// Result := StringOf(aPacks);
Result := '';
for i := 0 to Length(aPacks) - 1 do
Result := Result + Char(aPacks[i]);
end;
function StrToPacks( sData : string ) : TBytes;
var
i: Integer;
begin
// Result := BytesOf(sData);
SetLength(Result, Length(sData));
{$IFDEF ANDROID}
for i := 0 to Length(Result) - 1 do
Result[i] := ord(sData[i]);
{$ENDIF}
{$IFDEF MSWINDOWS}
for i := 0 to Length(Result) - 1 do
Result[i] := ord(sData[i+1]);
{$ENDIF}
end;
function PortSNToName(nPortSN: Byte) : string;
begin
if nPortSN > 0 then
Result := Format( 'COM%d', [ nPortSN ] )
else
Result := EmptyStr;
end;
function PortNameToSN( sPortName : string ) : Integer;
begin
TryStrToInt( StringReplace(sPortName, 'COM', '', [rfIgnoreCase] ), Result);
end;
function PortStatusToStr(AStatus : TPORT_STATUS) : string;
begin
case AStatus of
psNone: Result := '不存在';
psAvail: Result := '可用';
psBusy: Result := '使用中';
end;
end;
function CheckPortStatus(nPort: Integer): TPORT_STATUS;
{$IFDEF MSWINDOWS}
var
hComm : Cardinal;
s : string;
begin
s := PortSNToName( nPort );
if s <> '' then
begin
hComm := CreateFile(PChar( '\\.\' + s),
GENERIC_READ or GENERIC_WRITE,
0,
nil,
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
0);
if GetLastError = ERROR_ACCESS_DENIED then
Result := psBusy
else if hComm <> 4294967295 then
begin
Result := psAvail;
CloseHandle( hComm );
end
else
begin
result := psNone;
CloseHandle( INVALID_HANDLE_VALUE );
end;
end
else
begin
Result := psNone;
end;
end;
{$ENDIF}
{$IFDEF ANDROID}
begin
Result := psNone;
end;
{$ENDIF}
procedure GetAllCommPorts( APortList : TStrings );
{$IFDEF MSWINDOWS}
var
KeyHandle: HKEY;
ErrCode, Index: Integer;
ValueName, Data: string;
ValueLen, DataLen, ValueType: DWORD;
TmpPorts: TStringList;
i: Integer;
begin
ErrCode := RegOpenKeyEx(
HKEY_LOCAL_MACHINE,
'HARDWARE\DEVICEMAP\SERIALCOMM',
0,
KEY_READ,
KeyHandle);
if ErrCode <> ERROR_SUCCESS then
begin
//raise EComPort.Create(CError_RegError, ErrCode);
exit;
end;
TmpPorts := TStringList.Create;
try
Index := 0;
repeat
ValueLen := 256;
DataLen := 256;
SetLength(ValueName, ValueLen);
SetLength(Data, DataLen);
ErrCode := RegEnumValue(
KeyHandle,
Index,
PChar(ValueName),
{$IFDEF DELPHI_4_OR_HIGHER}
Cardinal(ValueLen),
{$ELSE}
ValueLen,
{$ENDIF}
nil,
@ValueType,
PByte(PChar(Data)),
@DataLen);
if ErrCode = ERROR_SUCCESS then
begin
SetLength(Data, DataLen - 1);
TmpPorts.Add(Data);
Inc(Index);
end
else
if ErrCode <> ERROR_NO_MORE_ITEMS then break;
//raise EComPort.Create(CError_RegError, ErrCode);
until (ErrCode <> ERROR_SUCCESS) ;
TmpPorts.Sort;
for i := 0 to TmpPorts.Count - 1 do
APortList.Add(Trim(TmpPorts[i]));
APortList.Insert(0, '');
finally
RegCloseKey(KeyHandle);
TmpPorts.Free;
end;
end;
{$ENDIF}
{$IFDEF ANDROID}
begin
end;
{$ENDIF}
function GetAllCommPortsStr : string;
var
APortList : TStrings;
begin
APortList := TStringList.Create;
GetAllCommPorts(APortList);
Result := APortList.Text;
APortList.Free;
end;
function GetMD5(const sStr: String): String;
Var
MD5: TIdHashMessageDigest5;
begin
MD5 := TIdHashMessageDigest5.Create;
Try
Result := MD5.HashStringAsHex(sStr, IndyTextEncoding_UTF8).ToLower;
finally
MD5.Free;
end;
end;
function GetPointLen(dX1, dY1, dX2, dY2 : Double) : Double;
begin
Result := Sqrt(Sqr(dX2-dX1)+Sqr(dY2-dY1));
end;
function GetDelIndex(nCount, nDelIndex : Integer) : Integer;
begin
if (nCount > nDelIndex) and (nDelIndex >= 0) then
begin
if nCount - nDelIndex > 1 then
begin
Result := nDelIndex;
end
else
begin
Result := nDelIndex - 1;
end;
end
else
begin
if nCount > 0 then
Result := 0
else
Result := -1;
end;
end;
function FormatDT(sFormat : string; dtValue : TDateTime) : string;
var
nHH, nMM, nSS, nMS, nDD, nMonth, nYY : Integer;
sHH, sMM, sSS, sMS, sDD, sMonth, sYY : string;
begin
nYY := 16;
nMonth := 1;
nDD := 1;
nHH := 1;
nMM := 1;
nSS := 1;
nMS := 1;
RecodeDateTime(dtValue, nyy, nMonth, ndd, nHH, nMM, nSS, nMS);
sYY := IntToLenStr(nyy, 2);
sMonth := IntToLenStr(nMonth, 2);
sDD := IntToLenStr(ndd, 2);
sHH := IntToLenStr(nHH, 2);
sMM := IntToLenStr(nMM, 2);
sSS := IntToLenStr(nSS, 2);
sMS := IntToLenStr(nMS, 2);
if UpperCase(sFormat) = 'HH:MM:SS' then
begin
Result := sHH + ':' + sMM + ':' + sSS;
end
else if UpperCase(sFormat) = 'HHMMSS' then
begin
Result := sHH + sMM+ sSS;
end
else if UpperCase(sFormat) = 'HHMM' then
begin
Result := sHH + sMM;
end
else if UpperCase(sFormat) = 'YY-MM-DD' then
begin
Result := sYY + '-' + sMonth + '-' + sDD;
end
else if UpperCase(sFormat) = 'YY.MM.DD' then
begin
Result := sYY + '.' + sMonth + '.' + sDD;
end
else if UpperCase(sFormat) = 'YYMM' then
begin
Result := sYY+ sMonth;
end
else if UpperCase(sFormat) = 'MMDD' then
begin
Result := sMonth + sDD;
end
else if UpperCase(sFormat) = 'YYYY.MM.DD' then
begin
Result := '20' + sYY + '.' + sMonth + '.' + sDD;
end
else if UpperCase(sFormat) = 'YYMMDDHHMM' then
begin
Result := sYY + sMonth+ sDD + sHH + sMM;
end
else if UpperCase(sFormat) = 'YYMMDD' then
begin
Result := sYY + sMonth+ sDD;
end
else if UpperCase(sFormat) = 'YYYY-MM-DD HH:MM:SS' then
begin
Result := sYY + '-' + sMonth + '-' + sDD + ' '+ sHH + ':' + sMM + ':' + sSS;
end
else
begin
Result := FormatDateTime(sFormat, dtValue);
end;
end;
function BCDToByte( n : Byte ) : Byte;
begin
Result := ( n shr 4 ) * 10 + n and $F ;
end;
function GetByteBitValue(nByte, nIndex : Byte) : Byte;
begin
if ((nByte shr nIndex) and $01) = $01 then
Result := 1
else
Result := 0;
end;
function IntToLenStr(nValue: Int64; nStrLen : Integer; sStr : string): string;
var
s : string;
nLen : Integer;
begin
s := IntToStr(nValue);
nLen := nStrLen - Length(s);
if nLen > 0 then
begin
Result := DupeString(sStr, nLen) + s;
end
else
Result := s;
end;
function StrToBytes( sData : string ) : TBytes;
function GetIndex( sValue, sFormat : string ) : Integer;
begin
Result := Pos( sFormat, sValue );
end;
var
s, sValue : string;
i: Integer;
nValue : Integer;
begin
try
SetLength( Result, 0 );
// 删除空格
s := StringReplace(sData ,' ','',[rfReplaceAll]);
// 取值
for i := 1 to Length(s) do
begin
if s[i] <> #0 then
sValue := sValue + s[i];
if Length(sValue) = 2 then
begin
SetLength( Result, Length( Result ) + 1 );
TryStrToInt( '$' + sValue, nValue );
Result[ Length( Result ) - 1 ] := nValue;
sValue := '';
end;
end;
except
end;
end;
function StrToBytes1( sData : string ) : TBytes;
var
i: Integer;
begin
SetLength(Result, Length(sData));
for i := 0 to Length(Result) - 1 do
Result[i] := ord(sData[i+1]);
end;
procedure WaitForSeconds( nMSeconds : Cardinal );
var
nTick : Cardinal;
begin
nTick := TThread.GetTickCount;
repeat
MyProcessMessages;
Sleep(1);
until TThread.GetTickCount - nTick > nMSeconds;
end;
function IntToBCD( nNum, nLen : Integer): TBytes;
var
i : Integer;
begin
SetLength( Result, nLen );
for i := 0 to nLen - 1 do
begin
Result[i] := (((nNum mod 100) div 10) shl 4) + (nNum mod 10);
nNum := nNum div 100;
end;
end;
function IntToBCD( nNum : Int64; nLen : Integer): TBytes;
var
i : Integer;
begin
SetLength( Result, nLen );
for i := 0 to nLen - 1 do
begin
Result[i] := (((nNum mod 100) div 10) shl 4) + (nNum mod 10);
nNum := nNum div 100;
end;
end;
function IntToByte( const n, nPos : Integer ) : Byte;
begin
if nPos in [ 0..3 ] then
Result := n shr ( 8 * nPos ) and $FF
else
Result := $00;
end;
function IntToByte( const n : Int64; const nPos : Integer ) : Byte;
begin
if nPos in [ 0..7 ] then
Result := n shr ( 8 * nPos ) and $FF
else
Result := $00;
end;
function CalCS( AData : TBytes; AFrom : Integer = 0; ATo : Integer = -1 ) : Byte;
var
nFrom, nTo : Integer;
nSum : Integer;
i: Integer;
begin
if Length( AData ) = 0 then
begin
Result := 0;
Exit;
end;
// 确定开始和终止位置
if AFrom < Low( AData ) then
nFrom := Low( AData )
else if AFrom > High( AData ) then
nFrom := High( AData )
else
nFrom := AFrom;
if ATo = -1 then
nTo := High( AData )
else if ATo < Low( AData ) then
nTo := Low( AData )
else if ATo > High( AData ) then
nTo := High( AData )
else
nTo := ATo;
// 计算CS
nSum := 0;
for i := nFrom to nTo do
nSum := nSum + AData[ i ];
Result := nSum and $FF;
end;
function BCDToDouble( aBCD : TBytes; nDigital : Integer ) : Double;
var
i : Integer;
nInt : Integer;
begin
Result := 0;
nInt := 2 * Length( aBCD ) - nDigital; // 整数长度
for i := 0 to High( aBCD ) do
Result := Result + ( ( aBCD[ i ] shr 4 ) * 10 + ( aBCD[ i ] and $F ) ) *
Power( 10, nInt - ( i + 1 ) * 2 );
end;
procedure WriteRunLog( sLogFileName : string; sRunMsg : string );
var
fileRunLog : TextFile;
begin
AssignFile( fileRunLog, sLogFileName );
if not FileExists( sLogFileName ) then
Rewrite(fileRunLog);
try
Append( fileRunLog );
// Writeln( fileRunLog, PChar( FormatDateTime( 'YYYY-MM-DD hh:mm:ss:zzz',Now )
// + #9 + sRunMsg ));
Writeln( fileRunLog, PChar( DateTimeToStr(Now)
+ #9 + sRunMsg ));
CloseFile( fileRunLog );
except
end;
end;
function CheckAndCreateDir( sDirPath : string ) : Boolean;
begin
Result := DirectoryExists( sDirPath );
// 文件夹不存在则创建
if not Result then
Result := CreateDir( sDirPath );
end;
function GetFileVersion(sFileName: string = ''): string;
{$IFDEF MSWINDOWS}
var
VerInfoSize, VerValueSize, Dummy: DWORD;
VerInfo: Pointer;
VerValue: PVSFixedFileInfo;
sFName: string;
begin
Result := '';
if (sFileName <> '') and FileExists(sFileName) then
sFName := sFileName
else
sFName := ParamStr(0);
VerInfoSize := GetFileVersionInfoSize(PChar(sFName), Dummy);
if VerInfoSize > 0 then
begin
GetMem(VerInfo, VerInfoSize);
try
if GetFileVersionInfo(PChar(sFName), 0, VerInfoSize, VerInfo) then
begin
VerQueryValue(VerInfo, '\', Pointer(VerValue), VerValueSize);
with VerValue^ do
begin
Result := IntToStr((dwFileVersionMS shr 16) and $FFFF) + '.' + IntToStr(dwFileVersionMS and $FFFF) + '.' + IntToStr((dwFileVersionLS shr 16) and $FFFF) + '.' + IntToStr(dwFileVersionLS and $FFFF);
end;
end;
finally
FreeMem(VerInfo, VerInfoSize);
end;
end;
end;
{$ENDIF}
{$IFDEF ANDROID}
var PackageInfo: JPackageInfo;
PackageName: JString;
begin
PackageName := TAndroidHelper.Context.getPackageName;
PackageInfo := TAndroidHelper.Context.getPackageManager.getPackageInfo(PackageName, 0);
Result:= JStringToString(PackageInfo.versionName);
end;
{$ENDIF}
{$IF Defined(IOS) or Defined(MACOS)}
var AppNameKey: Pointer;
AppBundle: NSBundle;
NSAppName: NSString;
begin
AppBundle := TNSBundle.Wrap(TNSBundle.OCClass.mainBundle);
AppNameKey := (NSSTR('CFBundleVersion') as ILocalObject).GetObjectID;
NSAppName := TNSString.Wrap(AppBundle.infoDictionary.objectForKey(AppNameKey));
Result:= UTF8ToString(NSAppName.UTF8String)+#13#10;
end;
{$ENDIF}
function CheckPath( sPath, sDelim : string ) : string;
begin
if sPath <> EmptyStr then
begin
if sPath[ Length( sPath ) ] <> sDelim then
Result := sPath + sDelim
else
Result := sPath;
end;
end;
function GetFloatIntLength( d : Double ) : Integer;
var
n : Int64;
begin
// 获得整数, 并去掉正负号
n := Abs( Trunc( d ) );
if n > 0 then
Result := ( n - 1 )
else
Result := Length( IntToStr( n ) );
end;
procedure ClearStringList( sl : TStringList );
var
i : Integer;
AObject : TObject;
begin
if not Assigned( sl ) then
Exit;
for i := 0 to sl.Count - 1 do
begin
AObject := sl.Objects[i];
if Assigned(AObject) then
AObject.Free;
end;
sl.Clear;
end;
function GetPartValue( slValue : TStringList; const sText : string;
const sPart : Char ): Boolean;
var
s : string;
nIndex : Integer;
begin
Result := False;
slValue.Clear;
if not Assigned( slValue ) then
Exit;
if sText = '' then
Exit;
s := Trim(sText);
nIndex := Pos( sPart, s );
while not (nIndex = 0) do
begin
if nindex <> 1 then
slValue.Add(Copy(s, 0, nindex-1))
else
slValue.Add('');
s := Trim(Copy(s, nIndex + 1, Length(s)- nindex + 1));
nIndex := Pos( sPart, s );
end;
if (s <> '') and (s <>sPart ) then
slValue.Add(s);
Result := True;
end;
function FilePath(sFile:String=''):String;
var
FList:TStrings;
i:Integer;
procedure CheckDir;
begin
if(not TDirectory.Exists(result)) then TDirectory.CreateDirectory(result);
result:=result+PathDelim;
end;
begin
{$IF DEFINED(IOS) or DEFINED(ANDROID)}
Result:=TPath.GetDocumentsPath+PathDelim;
{$ELSE}
Result:=TPath.GetLibraryPath;
{$ENDIF}
if(sFile<>'') then begin
FList:=TStringList.Create;
FList.CommaText:=sFile;
for i:=0 to FList.Count-1 do begin //判断文件路径是否存在,不存自动创建
FList[i]:=FList[i].Trim;
if(FList[i]<>'') then begin
Result:=Result+FList[i];
CheckDir;
end;
end;
FList.Free;
end;
end;
function HintMessage(nType : Integer; sText : string; sCaption: string = '';
uType: THintbtnType = hbtOk;
uiType : THintIconType = hitHint) : THintResultType;
function IconType(nType : THintIconType): Integer;
begin
Result := 0;
{$IFDEF MSWINDOWS}
case nType of
hitHint :
begin
Result := MB_ICONINFORMATION;
end;
hitInquiry :
begin
Result := MB_ICONQUESTION;
end;
hitWarning :
begin
Result := MB_ICONWARNING;
end;
hitError :
begin
Result := MB_ICONSTOP;
end;
end;
{$ENDIF}
end;
{$IFDEF MSWINDOWS}
var
nValue : Integer;
{$ENDIF}
begin
Result := hrtNothing;
{$IFDEF MSWINDOWS}
if nType = 0 then
begin
// ShowMessage(sText);
MessageBox(0, PWideChar(sText), PWideChar(sCaption), MB_OK + IconType(uiType));
end
else
begin
case uType of
hbtOk:
begin
MessageBox(0, PWideChar(sText), PWideChar(sCaption), MB_OK + IconType(uiType));
Result := hrtOk;
end;
hbtOkCancel:
begin
nValue := MessageBox(0, PWideChar(sText), PWideChar(sCaption), MB_OKCANCEL + IconType(uiType));
if nValue = IDOK then
Result := hrtOk
else
result := hrtCancel;
end;
hbtYesNoCancel:
begin
nValue := MessageBox(0, PWideChar(sText), PWideChar(sCaption), MB_YESNOCANCEL + IconType(uiType));
if nValue = IDYES then
Result := hrtYes
else if nValue = IDNO then
Result := hrtNo
else
result := hrtCancel;
end;
hbtYesNo:
begin
nValue := MessageBox(0, PWideChar(sText), PWideChar(sCaption), MB_YESNO + IconType(uiType));
if nValue = IDYES then
Result := hrtYes
else
Result := hrtNo;
end;
hbtAbortRetryIgnore :
begin
nValue := MessageBox(0, PWideChar(sText), PWideChar(sCaption), MB_ABORTRETRYIGNORE + IconType(uiType));
if nValue = IDABORT then
Result := hrtAbort
else if nValue = IDRETRY then
Result := hrtRetry
else
result := hrtIgnore;
end;
hbtRetryCancel :
begin
nValue := MessageBox(0, PWideChar(sText), PWideChar(sCaption), MB_RETRYCANCEL + IconType(uiType));
if nValue = IDRETRY then
Result := hrtRetry
else
Result := hrtCancel;
end;
end;
end;
{$ELSE}
// ShowMessage(sText);
MessageBox(0, PWideChar(sText), PWideChar(sCaption), MB_OK + IconType(uiType));
{$ENDIF}
end;
end.
|
unit VA508ImageListLabelerPE;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, ExtCtrls, ColnEdit, ToolWnds, ImgList, DesignIntf, TypInfo,
DesignEditors, VA508ImageListLabeler, VA508MSAASupport, ToolsAPI, StdCtrls, Buttons, Menus;
const
VA508_CUSTOM_REDRAW_IMAGES = WM_USER + 123;
type
TVA508ImageListReceiver = procedure(lvItem: TListItem; item: TVA508ImageListLabel) of object;
TfrmImageListEditor = class(TCollectionEditor)
imgTemp16: TImageList;
imgTemp24: TImageList;
imgTemp32: TImageList;
private
FRedrawImages: boolean;
FSize: integer;
FBitMap1: TBitMap;
FBitMap2: TBitMap;
FBMRect: TRect;
FOldOnChange: TNotifyEvent;
FOnChangeRedirected: boolean;
procedure ImageDataChanged(Sender: TObject);
procedure IterateItems(Receiver: TVA508ImageListReceiver);
procedure RedrawImages(var Msg); message VA508_CUSTOM_REDRAW_IMAGES;
procedure GetSize;
procedure UpdateImages(lvItem: TListItem; item: TVA508ImageListLabel);
function GetImageList: TImageList;
protected
procedure ItemChange(Sender: TObject; Item: TListItem);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
TVA508ImageListItemsProperty = class(TCollectionProperty)
public
function GetAttributes: TPropertyAttributes; override;
function GetEditorClass: TCollectionEditorClass; override;
end;
TVA508ImageListComponentEditor = class(TComponentEditor)
public
procedure Edit; override;
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
TVA508ImageListComponentProperty = class(TComponentProperty)
private
FProc: TGetStrProc;
procedure FilterValues(const S: string);
public
procedure GetValues(Proc: TGetStrProc); override;
function GetValue: string; override;
procedure SetValue(const Value: string); override;
end;
TVA508LabelerImageListProperty = class(TComponentProperty)
public
function GetAttributes: TPropertyAttributes; override;
end;
TVA508LabelerRemoteLabelerProperty = class(TComponentProperty)
private
FProc: TGetStrProc;
procedure FilterValues(const S: string);
public
procedure GetValues(Proc: TGetStrProc); override;
end;
procedure Register;
implementation
{$R *.dfm}
procedure Register;
begin
RegisterPropertyEditor(TypeInfo(TVA508ImageListLabels), TVA508ImageListLabeler, 'Labels', TVA508ImageListItemsProperty);
RegisterPropertyEditor(TypeInfo(TVA508ImageListLabeler), TVA508ImageListLabeler, 'RemoteLabeler', TVA508LabelerRemoteLabelerProperty);
RegisterPropertyEditor(TypeInfo(TCustomImageList), TVA508ImageListLabeler, 'ImageList', TVA508LabelerImageListProperty);
RegisterPropertyEditor(TypeInfo(TComponent), TVA508ImageListComponent, 'Component', TVA508ImageListComponentProperty);
RegisterComponentEditor(TVA508ImageListLabeler, TVA508ImageListComponentEditor);
end;
const
GSIZE_SMALL = 16;
GSIZE_MED = 24;
GSIZE_LARGE = 32;
type
TVA508AccessImageListLabeler = class(TVA508ImageListLabeler);
constructor TfrmImageListEditor.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
// this works because refresh of images in parent class destroys and rebuilds list
ListView1.OnInsert := ItemChange;
ListView1.OnDeletion := ItemChange;
end;
{ TVA508GraphicsProperty }
function TVA508ImageListItemsProperty.GetAttributes: TPropertyAttributes;
var
comp: TVA508ImageListLabeler;
begin
comp := TVA508ImageListLabeler(GetComponent(0));
if assigned(comp) and assigned(comp.RemoteLabeler) then
Result := [paReadOnly, paDisplayReadOnly, paAutoUpdate]
else
Result := inherited GetAttributes + [paAutoUpdate];
end;
function TVA508ImageListItemsProperty.GetEditorClass: TCollectionEditorClass;
begin
Result := TfrmImageListEditor;
end;
destructor TfrmImageListEditor.Destroy;
begin
if FOnChangeRedirected then
begin
TVA508AccessImageListLabeler(Component).OnChange := FOldOnChange;
FOnChangeRedirected := FALSE;
end;
inherited;
end;
procedure TfrmImageListEditor.ImageDataChanged(Sender: TObject);
begin
ItemChange(Sender, nil);
end;
procedure TfrmImageListEditor.ItemChange(Sender: TObject;
Item: TListItem);
var
Msg: TMsg;
begin
FRedrawImages := TRUE;
if not PeekMessage(Msg, Handle, VA508_CUSTOM_REDRAW_IMAGES, VA508_CUSTOM_REDRAW_IMAGES, PM_NOREMOVE) then
PostMessage(Handle, VA508_CUSTOM_REDRAW_IMAGES, 0, 0);
end;
procedure TfrmImageListEditor.IterateItems(
Receiver: TVA508ImageListReceiver);
var
i: integer;
item: TVA508ImageListLabel;
lvItem: TListItem;
begin
if assigned(Receiver) then
begin
ListView1.items.BeginUpdate;
try
for i := 0 to ListView1.Items.Count - 1 do
begin
lvItem := ListView1.items[i];
item := TVA508ImageListLabels(Collection).Items[i];
if assigned(item) then
Receiver(lvItem, item);
end;
finally
ListView1.items.EndUpdate;
end;
end;
end;
function TfrmImageListEditor.GetImageList: TImageList;
begin
case FSize of
GSIZE_SMALL: Result := imgTemp16;
GSIZE_MED: Result := imgTemp24;
GSIZE_LARGE: Result := imgTemp32;
else Result := nil;
end;
end;
procedure TfrmImageListEditor.GetSize;
var
imgSize: integer;
imageList: TCustomImageList;
begin
imageList := TVA508AccessImageListLabeler(Component).ImageList;
if assigned(ImageList) then
begin
imgSize := ImageList.Height;
if imgSize < ImageList.Width then
imgSize := ImageList.Width;
end
else
imgSize := 0;
if FSize < imgSize then
FSize := imgSize;
end;
procedure TfrmImageListEditor.RedrawImages(var Msg);
var
i, BeforeSize: integer;
imgList: TImageList;
begin
if FRedrawImages then
begin
FRedrawImages := FALSE;
ListView1.items.BeginUpdate;
try
if not FOnChangeRedirected then
begin
FOldOnChange := TVA508AccessImageListLabeler(Component).OnChange;
TVA508AccessImageListLabeler(Component).OnChange := ImageDataChanged;
FOnChangeRedirected := TRUE;
end;
BeforeSize := FSize;
FSize := GSIZE_SMALL;
GetSize;
if FSize > GSIZE_MED then
FSize := GSIZE_LARGE
else if FSize > GSIZE_SMALL then
FSize := GSIZE_MED
else
FSize := GSIZE_SMALL;
if FSize <> BeforeSize then
ListView1.Columns[0].Width := FSize * 3;
imgList := GetImageList;
for I := imgList.Count - 1 downto 1 do
imgList.Delete(i);
ListView1.SmallImages := imgList;
ListView1.StateImages := imgList;
FBitmap1 := TBitMap.Create;
FBitmap2 := TBitMap.Create;
try
FBitmap1.Height := imgList.Height;
FBitmap1.Width := imgList.Width;
FBMRect.Left := 0;
FBMRect.Top := 0;
FBMRect.Right := FBitMap1.Width;
FBMRect.Bottom := FBitMap1.Height;
IterateItems(UpdateImages);
finally
FreeAndNil(FBitmap1);
FreeAndNil(FBitmap1);
end;
finally
ListView1.items.EndUpdate;
end;
end;
end;
procedure TfrmImageListEditor.UpdateImages(lvItem: TListItem;
item: TVA508ImageListLabel);
var
imgLst: TImageList;
stretch: boolean;
ImageList: TCustomImageList;
begin
ImageList := TVA508AccessImageListLabeler(Component).ImageList;
if assigned(ImageList) and (item.ImageIndex >= 0) then
begin
imgLst := GetImageList;
stretch := ((imgLst.Height <> ImageList.Height) or
(imgLst.Width <> ImageList.Width));
if stretch then
begin
ImageList.GetBitmap(item.ImageIndex, FBitMap2);
FBitmap1.Canvas.StretchDraw(FBMRect, FBitMap2);
end
else
ImageList.GetBitmap(item.ImageIndex, FBitMap1);
imgLst.Add(FBitMap1, nil);
lvitem.ImageIndex := imglst.Count-1;
FBitMap1.Canvas.FillRect(FBMRect);
if stretch then
FBitMap2.Canvas.FillRect(FBMRect);
end
else
lvitem.ImageIndex := 0;
end;
{ TVA508ImageListComponentEditor }
procedure TVA508ImageListComponentEditor.Edit;
begin
ShowCollectionEditorClass(Designer, TfrmImageListEditor, Component,
TVA508ImageListLabeler(Component).Labels, 'Images');
end;
procedure TVA508ImageListComponentEditor.ExecuteVerb(Index: Integer);
begin
if Index = 0 then Edit
else inherited ExecuteVerb(Index);
end;
function TVA508ImageListComponentEditor.GetVerb(Index: Integer): string;
begin
if Index = 0 then
Result := 'Edit Image List Labels...'
else
Result := inherited GetVerb(Index);
end;
function TVA508ImageListComponentEditor.GetVerbCount: Integer;
begin
Result := 1;
end;
{ TVA508ImageListComponentProperty }
procedure TVA508ImageListComponentProperty.FilterValues(const S: string);
var
comp: TComponent;
i: integer;
begin
comp := Designer.GetComponent(S);
if assigned(comp) then
begin
for i := low(VA508ImageListLabelerClasses) to high(VA508ImageListLabelerClasses) do
begin
if comp is VA508ImageListLabelerClasses[i] then
FProc(S + ' (' + comp.ClassName + ')');
end;
end;
end;
function TVA508ImageListComponentProperty.GetValue: string;
var
comp: TComponent;
begin
Result := inherited GetValue;
comp := Designer.GetComponent(Result);
if assigned(comp) then
Result := Result + ' (' + comp.ClassName + ')';
end;
procedure TVA508ImageListComponentProperty.GetValues(Proc: TGetStrProc);
begin
FProc := Proc;
Designer.GetComponentNames(GetTypeData(GetPropType), FilterValues);
end;
procedure TVA508ImageListComponentProperty.SetValue(const Value: string);
var
i: integer;
data: string;
begin
data := Value;
i := pos(' (',data);
if i > 0 then
delete(data, i, MaxInt);
inherited SetValue(Data);
end;
{ TVA508LabelerImageListProperty }
function TVA508LabelerImageListProperty.GetAttributes: TPropertyAttributes;
var
comp: TVA508ImageListLabeler;
begin
comp := TVA508ImageListLabeler(GetComponent(0));
if assigned(comp) and (not assigned(comp.RemoteLabeler)) then
Result := inherited GetAttributes
else
Result := [paReadOnly, paDisplayReadOnly, paAutoUpdate];
end;
{ TVA508LabelerRemoteLabelerProperty }
procedure TVA508LabelerRemoteLabelerProperty.FilterValues(const S: string);
begin
if pos('->', S) > 0 then
FProc(S);
end;
procedure TVA508LabelerRemoteLabelerProperty.GetValues(Proc: TGetStrProc);
begin
FProc := Proc;
Designer.GetComponentNames(GetTypeData(GetPropType), FilterValues);
end;
end.
|
object frm_ShowInfoUpdate: Tfrm_ShowInfoUpdate
Left = 317
Top = 181
Width = 530
Height = 453
HelpContext = 1034
BorderIcons = []
Caption = 'mxWebUpdate'
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
OldCreateOrder = True
Position = poScreenCenter
Scaled = False
PixelsPerInch = 96
TextHeight = 13
object Panel_Bottom: TPanel
Left = 0
Top = 385
Width = 522
Height = 41
Align = alBottom
BevelOuter = bvNone
TabOrder = 0
OnResize = Panel_BottomResize
object btn_OK: TButton
Left = 185
Top = 10
Width = 75
Height = 25
Cursor = crHandPoint
Caption = 'OK'
Default = True
ModalResult = 1
TabOrder = 0
end
object btn_Cancel: TButton
Left = 272
Top = 10
Width = 75
Height = 25
Cursor = crHandPoint
Cancel = True
Caption = 'Cancel'
ModalResult = 2
TabOrder = 1
end
end
object Panel2: TPanel
Left = 0
Top = 354
Width = 522
Height = 31
Align = alBottom
BevelOuter = bvNone
BorderStyle = bsSingle
TabOrder = 1
object chk_FutureUpdate: TCheckBox
Left = 8
Top = 6
Width = 497
Height = 17
Caption = 'chk_FutureUpdate'
Checked = True
State = cbChecked
TabOrder = 0
end
end
object Panel1: TPanel
Left = 0
Top = 0
Width = 522
Height = 354
Align = alClient
BevelInner = bvSpace
BevelOuter = bvLowered
Caption = 'Panel1'
TabOrder = 2
object WebBrowser: TWebBrowser
Left = 2
Top = 2
Width = 518
Height = 350
Align = alClient
TabOrder = 0
ControlData = {
4C000000893500002C2400000000000000000000000000000000000000000000
000000004C000000000000000000000001000000E0D057007335CF11AE690800
2B2E126208000000000000004C0000000114020000000000C000000000000046
8000000000000000000000000000000000000000000000000000000000000000
000000000000000001000000000000000000000000000000}
end
end
end
|
{ /*
MIT License
Copyright (c) 2014-2021 Wuping Xin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/ }
unit AAPI;
interface
{/* Aimsun MicroApi time notations:
ATime: Absolute simulation time in seconds;
ATimeSta: Stationary simulation time, in seconds;
ATimeTrans: Warm-up period, in seconds;
ASimStep: Simulation step. in seconds.
For example, a simulation scenario starts at 07:00, with 5 minutes of warm-up
period, and Aimsun has finished a simulation runtime of 1 minute, with 1
second as the simulation step. Thus:
ATime
= 5*60 + 60
= 360.0
ATimeSta
= 7*3600 +60
= 25260.0
ATimeTrans
= 5*60
= 300.0
ASimStep
= 1.0
Note by Wuping Xin, 2020-03-15 20:25 PM
Aimsun offical MicroApi (in C) was poorly designed, lacking in consistent naming
style with Apis logics completely dis-orgnized. It does not even have minimal
performance considerations, for example, a lot of its methods pass large struct
by value, a practice that should be avoided in the first place. This Object Pascal
porting of Aimsun's original MicroApi cannot fix those fundamental design issues
but at least with better naming style in terms of the Pascal language.
*/}
{$REGION 'Initialization Functions'}
/// <summary> Fires when Aimsun loads the MicroApi dll.
/// </summary>
/// <returns> Integer, 0 success code; negative error code.
/// </returns>
function AAPILoad: Integer; cdecl;
/// <summary> Fires when Aimsun is about to start the simulation, i.e., right
/// before running the first simulation step. This should be where to put
/// initialization code for the user logic.
/// </summary>
/// <returns> Integer, 0 success code; negative error code.
/// </returns>
function AAPIInit: Integer; cdecl;
{$ENDREGION}
{$REGION 'Timestep-wise Functions'}
/// <summary> Fires at the beginning of every simulation step.
/// </summary>
/// <returns> Integer, 0 success code; negative error code.
/// </returns>
function AAPIManage(ATime: Double; ATimeSta: Double; ATimeTrans: Double; ASimStep: Double): Integer; cdecl;
/// <summary> Fires at the end of every simulation step.
/// </summary>
/// <returns> Integer, 0 success code; negative error code.
/// </returns>
function AAPIPostManage(ATime: Double; ATimeSta: Double; ATimeTrans: Double; ASimStep: Double): Integer; cdecl;
{$ENDREGION}
{$REGION 'Finialization Functions'}
/// <summary> Fires when Aimsun has finished all simulation steps. This should
/// be where to put clean-up code of the user logic.
/// </summary>
/// <returns> Integer, 0 success code; negative error code.
/// </returns>
function AAPIFinish: Integer; cdecl;
/// <summary> Fires when Aimsun unloads the MicroApi dll.
/// </summary>
/// <returns> Integer, 0 success code; negative error code.
/// </returns>
function AAPIUnLoad: Integer; cdecl;
{$ENDREGION}
{$REGION 'Simulation Events'}
/// <summary> Fires when an vehicle enters a boundary section of the network,
/// i.e., the vehicle enters its first travelling section (not the virtual queue
/// if any).
/// </summary>
/// <returns> Integer, 0 success code; negative error code.
/// </returns>
function AAPIEnterVehicle(AVehID: Integer; ASectionID: Integer): Integer; cdecl;
/// <summary> Fires when a vehicle exits its last traveling section.
/// </summary>
/// <returns> Integer, 0 success code; negative error code.
/// </returns>
function AAPIExitVehicle(AVehID: Integer; ASectionID: Integer): Integer; cdecl;
/// <summary> Fires when a new pedestrian enters the network.
/// </summary>
/// <returns> Integer, 0 success code; negative error code.
/// </returns>
function AAPIEnterPedestrian(APedID: Integer; AOrigCentroid: Integer): Integer; cdecl;
/// <summary> Fires when a pedestrian exits the network.
/// </summary>
/// <returns> Integer, 0 success code; negative error code.
/// </returns>
function AAPIExitPedestrian(APedID: Integer; ADestCentroid: Integer): Integer; cdecl;
/// <summary> Fires when a vehicle enters a new section.
/// </summary>
/// <returns> Integer, 0 success code; negative error code.
/// </returns>
function AAPIEnterVehicleSection(AVehID: Integer; ASectionID: Integer; ATime: Double): Integer; cdecl;
/// <summary> Fires when a vehicle exits a section.
/// </summary>
/// <returns> Integer, 0 success code; negative error code.
/// </returns>
function AAPIExitVehicleSection(AVehID: Integer; ASectionID: Integer; ATime: Double): Integer; cdecl;
/// <summary> Fires before performing a new round of route choice calculation.
/// Section or turning costs can be modified here based on some user logic.
/// </summary>
/// <returns> Integer, 0 success code; negative error code.
/// </returns>
function AAPIPreRouteChoiceCalculation(ATime: Double; ATimeSta: Double): Integer; cdecl;
{$ENDREGION}
implementation
uses
System.Classes, System.SysUtils, AKIProxie;
function AAPIEnterVehicle(AVehID: Integer; ASectionID: Integer): Integer;
begin
Result := 0;
end;
function AAPIEnterVehicleSection(AVehID: Integer; ASectionID: Integer; ATime: Double): Integer;
begin
Result := 0;
end;
function AAPIExitVehicle(AVehID: Integer; ASectionID: Integer): Integer;
begin
Result := 0;
end;
function AAPIExitVehicleSection(AVehID: Integer; ASectionID: Integer; ATime: Double): Integer;
begin
Result := 0;
end;
function AAPIFinish: Integer;
begin
Result := 0;
end;
function AAPILoad: Integer;
begin
Result := 0;
end;
function AAPIInit: Integer;
begin
Result := 0;
end;
function AAPIManage(ATime: Double; ATimeSta: Double; ATimeTrans: Double; ASimStep: Double): Integer;
begin
Result := 0;
end;
function AAPIPostManage(ATime: Double; ATimeSta: Double; ATimeTrans: Double; ASimStep: Double): Integer;
begin
Result := 0;
end;
function AAPIPreRouteChoiceCalculation(ATime: Double; ATimeSta: Double): Integer;
begin
Result := 0;
end;
function AAPIUnLoad: Integer;
begin
Result := 0;
end;
function AAPIEnterPedestrian(APedID: Integer; AOrigCentroid: Integer): Integer;
begin
Result := 0;
end;
function AAPIExitPedestrian(APedID: Integer; ADestCentroid: Integer): Integer;
begin
Result := 0;
end;
end.
|
unit Unit1;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Objects,
FMX.Effects, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Filter.Effects;
type
TForm1 = class(TForm)
Image1: TImage;
Label1: TLabel;
Timer1: TTimer;
ShadowEffect1: TShadowEffect;
procedure FormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
procedure Timer1Timer(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure LabelMouseEnter(Sender: TObject);
procedure LabelMouseLeave(Sender: TObject);
procedure LabelClick(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FormMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; var Handled: Boolean);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
isFullScreen: Boolean;
TimeTime: Integer;
Target: TDateTime;
posX: Integer;
posY: Integer;
Labels: array [1 .. 13] of TLabel;
implementation
{$R *.fmx}
procedure TForm1.LabelClick(Sender: TObject);
var
TheButton: TLabel;
begin
Timer1.Enabled := true;
TheButton := Sender as TLabel;
TimeTime := StrToInt(TheButton.Text);
if (TheButton.Text = '60') then
begin
Target := now() + StrToTime('01:00:01');
end
else
begin
Target := now() + StrToTime('00:' + TheButton.Text + ':01');
end;
end;
procedure TForm1.LabelMouseEnter(Sender: TObject);
var
TheLabel: TLabel;
begin
TheLabel := Sender as TLabel;
TheLabel.StyledSettings := TheLabel.StyledSettings - [TStyledSetting.FontColor];
TheLabel.FontColor := $FFFFFFFF;
end;
procedure TForm1.LabelMouseLeave(Sender: TObject);
var
TheLabel: TLabel;
begin
TheLabel := Sender as TLabel;
TheLabel.StyledSettings := TheLabel.StyledSettings - [TStyledSetting.FontColor];
TheLabel.FontColor := $20FFFFFF;
end;
procedure TForm1.FormCreate(Sender: TObject);
var
i: Integer;
var
MyButton: TLabel;
var
times: array [1 .. 13] of string;
begin
// if LoadResourceFontByID(1, RT_FONT) then Label1.Font.Name := 'Roboto Black';
// Label1.Font.Size := 180;
Top := ((Screen.Height - Height) div 2);
Left := ((Screen.Width - Width) div 2);
times[1] := '01';
times[2] := '05';
times[3] := '10';
times[4] := '15';
times[5] := '20';
times[6] := '25';
times[7] := '30';
times[8] := '35';
times[9] := '40';
times[10] := '45';
times[11] := '50';
times[12] := '55';
times[13] := '60';
for i := 1 to Length(times) do
begin
MyButton := TLabel.Create(self);
With MyButton do
begin
StyledSettings := MyButton.StyledSettings - [TStyledSetting.Family, TStyledSetting.FontColor, TStyledSetting.Size];
Position.X := Form1.Width - 80;
Position.Y := (Form1.Height div 2) - (540 div 2) + (i * 35);
Width := 30;
Height := 30;
AutoSize := false;
Cursor := crHandPoint;
HitTest := true;
TextSettings.FontColor := $20FFFFFF;
TextSettings.Font.Size := 20;
TextSettings.Font.Family := 'Roboto Bold';
TextSettings.Font.Style := MyButton.TextSettings.Font.Style + [TFontStyle.fsBold];
Text := times[i];
TextSettings.HorzAlign := TTextAlign.Center;
TextSettings.VertAlign := TTextAlign.Center;
Parent := Form1;
OnClick := LabelClick;
OnMouseEnter := LabelMouseEnter;
OnMouseLeave := LabelMouseLeave;
end;
Labels[i] := MyButton;
end;
end;
procedure TForm1.FormMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; var Handled: Boolean);
begin
Timer1.Enabled := false;
if (WheelDelta > 0) then
begin
TimeTime := TimeTime + 1;
if (TimeTime > 60) then
begin
TimeTime := 60;
end;
end
else
begin
TimeTime := TimeTime - 1;
if (TimeTime < 0) then
begin
TimeTime := 0;
end;
end;
Target := now() + StrToTime(Format('%.2d:%.2d:01', [TimeTime div 60, TimeTime mod 60]));
Timer1.Enabled := true;
end;
procedure TForm1.FormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
var
isReturnToSmall: Boolean;
begin
isReturnToSmall := false;
if ((isFullScreen = true) and (Key = 27)) then // 27 = esc
begin
isFullScreen := false;
isReturnToSmall := true;
end;
if (KeyChar = 'f') then
begin
isFullScreen := not isFullScreen;
end;
if (isFullScreen) then
begin
posX := Form1.Left;
posY := Form1.Top;
BorderStyle := TFmxFormBorderStyle.None;
WindowState := TWindowState.wsMaximized;
end
else
begin
WindowState := TWindowState.wsNormal;
BorderStyle := TFmxFormBorderStyle.Sizeable;
end;
if (isReturnToSmall) then
begin
Form1.Left := posX;
Form1.Top := posY;
Form1.Width := 950;
Form1.Height := 580;
end;
end;
procedure TForm1.FormResize(Sender: TObject);
var
MyButton: TLabel;
var
i: Integer;
begin
for i := 1 to Length(Labels) do
begin
MyButton := Labels[i];
With MyButton do
begin
Position.X := Form1.Width - 80;
Position.Y := (Form1.Height div 2) - (540 div 2) + (i * 35);
end;
end;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
var
TimeToTarget: TDateTime;
myHour, myMin, mySec, myMilli: Word;
getMinutes: Word;
str: String;
secondInStr: String;
begin
TimeToTarget := Target - now();
DecodeTime(TimeToTarget, myHour, myMin, mySec, myMilli);
getMinutes := myHour * 60 + myMin;
str := Format('%.*d', [2, getMinutes]) + ':' + Format('%.*d', [2, mySec]);
Label1.Text := str;
if (TimeToTarget <= 0) then
begin
Timer1.Enabled := false;
end;
end;
end.
|
////////////////////////////////////////////
// Модуль проверки соединения с SQL
////////////////////////////////////////////
unit CheckConnStr;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, DB, ADODB, GMGlobals, GMConst, ActiveX, GMSqlQuery,
Threads.Base, ConnParamsStorage;
{$I ScriptVersion.inc}
type
TCheckConnStrThread = class(TGMThread)
private
FConnParams: TZConnectionParams;
procedure PostErrorMsg(const msg: string);
protected
procedure SafeExecute; override;
public
bFinished: bool;
constructor Create(Params: TZConnectionParams);
end;
TCheckConnStrDlg = class(TForm)
Button1: TButton;
lState: TLabel;
Label2: TLabel;
procedure FormDestroy(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
thr: TCheckConnStrThread;
procedure WMUpdateCOMLog(var Msg: TMessage); message WM_SQL_CONNECTION_STATE;
public
{ Public declarations }
function CheckConnectionString(Params: TZConnectionParams): bool;
end;
var
CheckConnStrDlg: TCheckConnStrDlg;
implementation
uses ComObj;
{$R *.dfm}
{ TCheckConnStrThread }
constructor TCheckConnStrThread.Create(Params: TZConnectionParams);
begin
inherited Create(false);
FConnParams := Params;
bFinished := false;
end;
procedure TCheckConnStrThread.PostErrorMsg(const msg: string);
begin
PostMessage(CheckConnStrDlg.Handle, WM_SQL_CONNECTION_STATE, WParam(TStringClass.Create(msg)), 0);
end;
procedure TCheckConnStrThread.SafeExecute;
var q: TGMSqlQuery;
action, ver: string;
begin
CoInitialize(nil);
q := TGMSqlQuery.Create(FConnParams);
repeat
try
action := 'Connecting';
q.SQL.Text := 'select 1';
q.Open();
action := 'Check script version';
q.SQL.Text := 'select PrmValue from SysConfig where PrmName = ''ScriptVersion''';
q.Open();
if q.Eof or (Trim(q.Fields[0].AsString) = '') then
raise Exception.Create('Не обнаружена версия скрипта. Прогоните последний скрипт.');
ver := Trim(q.Fields[0].AsString);
if StrToIntDef(ver, 0) < MIN_SCRIPT_VERSION then
begin
PostErrorMsg(Format('Текущая версия скрипта БД (%s) не подходит.'#13#10 +
'Прогоните скрипт версии не ниже %d.', [ver, MIN_SCRIPT_VERSION]));
end
else
begin
PostMessage(CheckConnStrDlg.Handle, WM_SQL_CONNECTION_STATE, 0, 0);
break;
end;
except
on e: Exception do
PostErrorMsg(action + #13#10 + e.Message)
end;
until Terminated;
bFinished := true;
q.Free();
end;
{ TCheckConnStrDlg }
function TCheckConnStrDlg.CheckConnectionString(Params: TZConnectionParams): bool;
begin
thr := TCheckConnStrThread.Create(Params);
Result := (ShowModal() = mrOk);
thr.Terminate(); // тут будет утечка памяти, если вышли по кнопке Отмена
// ждать завершения смысла нет, пускай будет утечка
end;
procedure TCheckConnStrDlg.WMUpdateCOMLog(var Msg: TMessage);
var sc: TStringClass;
begin
if Msg.WParam = 0 then
ModalResult := mrOk
else
begin
sc := TStringClass(Msg.WParam);
lState.Caption := sc.s;
sc.Free();
end;
end;
procedure TCheckConnStrDlg.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TCheckConnStrDlg.FormDestroy(Sender: TObject);
begin
// Если поток закончил работу, то убьем его.
// Если мы прервали ожидание, то нет смысла ждать завершения, проще пусть утечет немного памяти на выходе.
if thr.bFinished then
thr.Free();
end;
end.
|
unit uformupdatecodetemplate;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ComCtrls,
StdCtrls, Buttons, IDEIntf, ProjectIntf, LazIDEIntf, MacroIntf, LCLIntf,
ExtCtrls, IniFiles, ThreadProcess, uJavaParser, Clipbrd;
type
{ TFormUpdateCodeTemplate }
TFormUpdateCodeTemplate = class(TForm)
BitBtnOK: TBitBtn;
BitBtnClose: TBitBtn;
CheckGroupUpgradeTemplates: TCheckGroup;
ComboBoxSelectProject: TComboBox;
EditPathToWorkspace: TEdit;
LabelPathToWorkspace: TLabel;
LabelSelectProject: TLabel;
sddPath: TSelectDirectoryDialog;
SpBPathToWorkspace: TSpeedButton;
SpBSelectProject: TSpeedButton;
StatusBar1: TStatusBar;
procedure BitBtnOKClick(Sender: TObject);
procedure ComboBoxSelectProjectChange(Sender: TObject);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure SpBPathToWorkspaceClick(Sender: TObject);
procedure SpBSelectProjectClick(Sender: TObject);
private
{ private declarations }
MemoLog: TStringList;
SynMemo1: TStringList;
SynMemo2: TStringList;
ProjectPath: string;
JNIProjectPath: string;
PathToWorkspace: string;
PathToJavaTemplates: string;
PathToJavaClass: string;
PackageName: string;
JavaClassName: string; //"Controls"
APKProcess: TThreadProcess;
procedure RebuildLibrary; //by jmpessoa
procedure ShowProcOutput(AOutput: TStrings);
function ApkProcessRunning: boolean;
procedure DoTerminated(Sender: TObject);
public
{ public declarations }
end;
procedure GetSubDirectories(const directory: string; list: TStrings);
function ReplaceChar(query: string; oldchar, newchar: char): string;
var
FormUpdateCodeTemplate: TFormUpdateCodeTemplate;
implementation
{$R *.lfm}
uses LazFileUtils;
{ TFormUpdateCodeTemplate }
procedure TFormUpdateCodeTemplate.DoTerminated(Sender: TObject);
begin
Clipboard.AsText:=(MemoLog.Text);
ShowMessage('The Upgrade is Done! Please, Get the Log from Clipboard!');
end;
procedure TFormUpdateCodeTemplate.FormClose(Sender: TObject;
var CloseAction: TCloseAction);
var
AmwFile: string;
begin
AmwFile:= AppendPathDelim(LazarusIDE.GetPrimaryConfigPath) + 'JNIAndroidProject.ini';
with TInifile.Create(AmwFile) do
try
WriteString('NewProject', 'FullProjectName', ProjectPath);
WriteString('NewProject', 'PathToWorkspace', PathToWorkspace);
finally
Free;
end;
if Assigned(APKProcess) then
if not APKProcess.IsTerminated then APKProcess.Terminate;
CloseAction := caFree;
end;
procedure TFormUpdateCodeTemplate.ShowProcOutput(AOutput: TStrings);
begin
MemoLog.Add(AOutput.Text);
end;
function TFormUpdateCodeTemplate.ApkProcessRunning: boolean;
begin
Result:= False;
if Assigned(APKProcess) then
if not APKProcess.IsTerminated then
Result:= True
else
begin
APKProcess:= nil;
Result:= False;
end;
end;
procedure TFormUpdateCodeTemplate.RebuildLibrary; //by jmpessoa
var str: string;
begin
if JNIProjectPath = '' then
begin
ShowMessage('Fail! PathToLazbuild not found!' );
Exit;
end;
if Assigned(APKProcess) then
begin
if not APKProcess.IsTerminated then APKProcess.Terminate;
end;
//MemoLog.Clear;
APKProcess:= TThreadProcess.Create(True);
with APKProcess do
begin
OnTerminated:= @DoTerminated;
Dir:= Self.JNIProjectPath; //controls.lpi
str := '$MakeDir($(LazarusDir))lazbuild';
IDEMacros.SubstituteMacros(str);
Executable:= str;
Parameters.Add('controls.lpi');
OnDisplayOutput:= @ShowProcOutput;
Start;
end;
end;
procedure TFormUpdateCodeTemplate.BitBtnOKClick(Sender: TObject);
var
packList: TstringList;
fileList: TStringList;
pk, i: integer;
strAux: string;
begin
MemoLog.Clear;
if (ProjectPath = '') or (JNIProjectPath = '') then
begin
ShowMessage('Fail! Please, select a Project!');
ModalResult := mrNone;
Exit;
end;
if not FileExistsUTF8(PathToJavaTemplates + PathDelim + 'App.java')
or not FileExistsUTF8(PathToJavaTemplates + PathDelim + 'Controls.java')
or not FileExistsUTF8(PathToJavaTemplates + PathDelim + 'ControlsEvents.txt')
then begin
MessageDlg('Fail! Incorrect path to Java templates!' + sLineBreak
+ 'Can not find "App.java" or "Controls.java" or "ControlsEvents.txt" in "' + PathToJavaTemplates + '"',
mtError, [mbOk], 0);
Exit;
end;
packList:= TstringList.Create;
if FileExistsUTF8(ComboBoxSelectProject.Text+DirectorySeparator+'packagename.txt') then //for release >= 0.6/05
begin
packList.LoadFromFile(ComboBoxSelectProject.Text+DirectorySeparator+'packagename.txt');
PackageName:= Trim(packList.Strings[0]); //ex. com.example.appbuttondemo1
PathToJavaClass:= ComboBoxSelectProject.Text+DirectorySeparator+'src'+
DirectorySeparator+ReplaceChar(PackageName, '.',DirectorySeparator);
end
else //try get PackageName from 'AndroidManifest.xml'
begin
packList.LoadFromFile(ComboBoxSelectProject.Text+DirectorySeparator+'AndroidManifest.xml');
pk:= Pos('package="',packList.Text); //ex. package="com.example.appbuttondemo1"
strAux:= Copy(packList.Text, pk+Length('package="'), 200);
i:= 2; //scape first[ " ]
while strAux[i]<>'"' do
begin
i:= i+1;
end;
PackageName:= Trim(Copy(strAux, 1, i-1));
PathToJavaClass:= ComboBoxSelectProject.Text+DirectorySeparator+'src'+
DirectorySeparator+ReplaceChar(PackageName, '.',DirectorySeparator);
end;
//upgrade "App.java"
if CheckGroupUpgradeTemplates.Checked[0] then
begin
if FileExistsUTF8(PathToJavaClass+DirectorySeparator+'App.java') then
begin
fileList:= TStringList.Create;
fileList.LoadFromFile(PathToJavaClass+DirectorySeparator+'App.java');
fileList.SaveToFile(PathToJavaClass+DirectorySeparator+'App.java'+'.bak');
fileList.Free;
end;
packList.Clear;
packList.LoadFromFile(PathToJavaTemplates+DirectorySeparator+'App.java');
packList.Strings[0]:= 'package '+ PackageName+';'; //ex. package com.example.appbuttondemo1;
packList.SaveToFile(PathToJavaClass+DirectorySeparator+'App.java');
MemoLog.Add('["App.java" :: updated!]');
ShowMessage('"App.java" :: updated!');
end;
//upgrade "Controls.java"
if CheckGroupUpgradeTemplates.Checked[1] then
begin
if FileExistsUTF8(PathToJavaClass+DirectorySeparator+'Controls.java') then
begin
fileList:= TStringList.Create;
fileList.LoadFromFile(PathToJavaClass+DirectorySeparator+'Controls.java');
fileList.SaveToFile(PathToJavaClass+DirectorySeparator+'Controls.java'+'.bak');
fileList.Free;
end;
packList.Clear; //JavaClassName
packList.LoadFromFile(PathToJavaTemplates+DirectorySeparator+'Controls.java');
packList.Strings[0]:= 'package '+ PackageName+';'; //ex. package com.example.appbuttondemo1;
packList.SaveToFile(PathToJavaClass+DirectorySeparator+'Controls.java');
MemoLog.Add('["Controls.java" :: updated!]');
ShowMessage('"Controls.java" :: updated!');
end;
packList.Free;
//upgrade [library] controls.lpr
if CheckGroupUpgradeTemplates.Checked[2] then
begin
SynMemo1.Clear;
SynMemo2.Clear;
if FileExistsUTF8(JNIProjectPath+PathDelim+'controls.lpr') then
begin
// from old "controls.lpr"
SynMemo1.LoadFromFile(JNIProjectPath+PathDelim+'controls.lpr');
i := 0;
while i < SynMemo1.Count do
begin
if Copy(Trim(SynMemo1[i]) + ' ', 1, 5) = 'uses ' then
begin
repeat
SynMemo2.Add(SynMemo1[i]);
Inc(i);
until (i >= SynMemo1.Count) or (Pos(';', SynMemo1[i - 1]) > 0);
SynMemo2.Add('');
Break;
end else
SynMemo2.Add(SynMemo1[i]);
Inc(i);
end;
end else begin
SynMemo2.Add('{hint: save all files to location: '+ProjectPath+DirectorySeparator+'jni}');
SynMemo2.Add('library controls; //by Lamw: Lazarus Android Module Wizard: '+DateTimeToStr(Now)+']');
SynMemo2.Add(' ');
SynMemo2.Add('{$mode delphi}');
SynMemo2.Add(' ');
SynMemo2.Add('uses');
SynMemo2.Add(' Classes, SysUtils, And_jni, And_jni_Bridge, AndroidWidget, Laz_And_Controls,');
SynMemo2.Add(' Laz_And_Controls_Events, unit1;');
SynMemo2.Add(' ');
end;
with TJavaParser.Create(PathToJavaClass+PathDelim+JavaClassName+'.java') do
try
SynMemo2.Add(GetPascalJNIInterfaceCode(PathToJavaTemplates+PathDelim+'ControlsEvents.txt'));
finally
Free
end;
// TODO: should be taken from old "controls.lpr" (SynMemo1)
SynMemo2.Add('begin');
SynMemo2.Add(' gApp:= jApp.Create(nil);{AndroidWidget.pas}');
SynMemo2.Add(' gApp.Title:= ''My Android Bridges Library'';');
SynMemo2.Add(' gjAppName:= '''+PackageName+''';{AndroidWidget.pas}');
SynMemo2.Add(' gjClassName:= '''+ReplaceChar(PackageName, '.','/')+'/Controls'';{AndroidWidget.pas}');
SynMemo2.Add(' gApp.AppName:=gjAppName;');
SynMemo2.Add(' gApp.ClassName:=gjClassName;');
SynMemo2.Add(' gApp.Initialize;');
SynMemo2.Add(' gApp.CreateForm(TAndroidModule1, AndroidModule1);');
SynMemo2.Add('end.');
SynMemo2.Add('(*last [template] upgrade: '+DateTimeToStr(Now)+'*)');
if FileExistsUTF8(JNIProjectPath+DirectorySeparator+'controls.lpr') then
begin
CopyFile(JNIProjectPath+PathDelim+'controls.lpr',
JNIProjectPath+PathDelim+'controls.lpr.bak');
end;
SynMemo2.SaveToFile(JNIProjectPath+DirectorySeparator+'controls.lpr');
if MessageDlg('Question', 'Do you wish to re-build ".so" library?', mtConfirmation,[mbYes, mbNo],0) = mrYes then
begin
MemoLog.Add('["controls.lpr" :: update!--> ".so" :: rebuilding!]');
RebuildLibrary;
end;
end;
end;
procedure TFormUpdateCodeTemplate.ComboBoxSelectProjectChange(Sender: TObject);
begin
if ComboBoxSelectProject.ItemIndex > -1 then
begin
ProjectPath:= ComboBoxSelectProject.Text;
JNIProjectPath:= ProjectPath + DirectorySeparator + 'jni';
StatusBar1.SimpleText:= ProjectPath;
end;
end;
procedure TFormUpdateCodeTemplate.FormCreate(Sender: TObject);
var
AmwFile: string;
begin
MemoLog:= TStringList.Create;
JavaClassName:= 'Controls';
SynMemo1:= TStringList.Create;
SynMemo2:= TStringList.Create;
AmwFile:= AppendPathDelim(LazarusIDE.GetPrimaryConfigPath) + 'JNIAndroidProject.ini';
if FileExistsUTF8(AmwFile) then
begin
with TIniFile.Create(AmwFile) do // Try to use settings from Android module wizard
try
ProjectPath:= ReadString('NewProject', 'FullProjectName', '');
PathToWorkspace:= ReadString('NewProject', 'PathToWorkspace', '');
PathToJavaTemplates:= ReadString('NewProject', 'PathToJavaTemplates', '');
finally
Free
end;
end
end;
procedure TFormUpdateCodeTemplate.FormDestroy(Sender: TObject);
begin
MemoLog.Free;
SynMemo1.Free;
SynMemo2.Free;
end;
procedure TFormUpdateCodeTemplate.FormShow(Sender: TObject);
var
IDEProjectName: string;
p: integer;
begin
EditPathToWorkspace.Text:= PathToWorkspace; //by jmpessoa
ComboBoxSelectProject.Items.Clear; //by jmpessoa
if PathToWorkspace <> '' then
begin
GetSubDirectories(PathToWorkspace, ComboBoxSelectProject.Items);
end;
IDEProjectName:='';
p:= Pos(DirectorySeparator+'jni', LazarusIDE.ActiveProject.MainFile.Filename);
if p > 0 then
IDEProjectName:= Copy(LazarusIDE.ActiveProject.MainFile.Filename,1,p-1);
if IDEProjectName <> '' then
begin
ComboBoxSelectProject.Text:= IDEProjectName;
ProjectPath:= IDEProjectName;
StatusBar1.SimpleText:= 'Recent: '+ IDEProjectName; //path to most recent project ... by jmpessoa
JNIProjectPath:= IDEProjectName + DirectorySeparator + 'jni';
end;
CheckGroupUpgradeTemplates.Checked[0]:= True;
CheckGroupUpgradeTemplates.Checked[1]:= True;
CheckGroupUpgradeTemplates.Checked[2]:= True;
end;
procedure TFormUpdateCodeTemplate.SpBPathToWorkspaceClick(Sender: TObject);
begin
sddPath.Title:= 'Select Projects Workspace Path';
if Trim(EditPathToWorkspace.Text) <> '' then
if DirPathExists(EditPathToWorkspace.Text) then
sddPath.InitialDir:= EditPathToWorkspace.Text;
if sddPath.Execute then
begin
PathToWorkspace:= sddPath.FileName;
EditPathToWorkspace.Text:= PathToWorkspace;
ComboBoxSelectProject.Items.Clear;
GetSubDirectories(PathToWorkspace, ComboBoxSelectProject.Items);
end;
end;
procedure TFormUpdateCodeTemplate.SpBSelectProjectClick(Sender: TObject);
begin
PathToWorkspace:= EditPathToWorkspace.Text; //change Workspace...
ComboBoxSelectProject.Items.Clear;
GetSubDirectories(PathToWorkspace, ComboBoxSelectProject.Items);
ComboBoxSelectProject.ItemIndex:= -1;
ComboBoxSelectProject.Text:='';
end;
//helper... by jmpessoa
//http://delphi.about.com/od/delphitips2008/qt/subdirectories.htm
//fils the "list" TStrings with the subdirectories of the "directory" directory
//Warning: if not subdirectories was found return empty list [list.count = 0]!
procedure GetSubDirectories(const directory : string; list : TStrings);
var
sr : TSearchRec;
begin
try
if FindFirst(IncludeTrailingPathDelimiter(directory) + '*.*', faDirectory, sr) < 0 then Exit
else
repeat
if ((sr.Attr and faDirectory <> 0) and (sr.Name <> '.') and (sr.Name <> '..')) then
begin
List.Add(IncludeTrailingPathDelimiter(directory) + sr.Name);
end;
until FindNext(sr) <> 0;
finally
SysUtils.FindClose(sr) ;
end;
end;
//helper... by jmpessoa
function ReplaceChar(query: string; oldchar, newchar: char):string;
begin
if query <> '' then
begin
while Pos(oldchar,query) > 0 do query[pos(oldchar,query)]:= newchar;
Result:= query;
end;
end;
end.
|
{ *************************************************************************** }
{ }
{ NLDLabeledEdit - www.nldelphi.com Open Source designtime component }
{ }
{ Initiator: GeertVNieuw }
{ See http://www.nldelphi.com/Forum/showthread.php?t=14710 )
{ License: Free to use, free to modify }
{ Website: http://www.nldelphi.com/forum/forumdisplay.php?f=115 }
{ SVN path: http://svn.nldelphi.com/nldelphi/opensource/ngln/NLDDBLabeledEdit }
{ }
{ *************************************************************************** }
{ }
{ Edit by: Albert de Weerd (aka NGLN) }
{ Date: September 12, 2010 }
{ Version: 2.0.0.2 }
{ }
{ *************************************************************************** }
unit NLDDBLabeledEdit;
interface
uses
Classes, Messages, Controls, SysUtils, Windows, Graphics, StdCtrls, DBCtrls,
DB, ToolsAPI, Math, StrUtils;
type
TNLDSubLabel = class(TCustomLabel)
private
function GetGroupIndex: Integer;
procedure SetGroupIndex(Value: Integer);
procedure UnGroup(OldGroupIndex: Integer);
procedure CMDesignHitTest(var Message: TCMDesignHitTest);
message CM_DESIGNHITTEST;
procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED;
procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED;
protected
procedure Click; override;
public
constructor Create(AOwner: TComponent); override;
procedure Update; reintroduce;
property GroupIndex: Integer read GetGroupIndex write SetGroupIndex;
public
property Font;
property ParentFont;
end;
TNLDDBLabeledEdit = class(TDBEdit)
private
function DefaultLabelCaption: String;
function GetDataField: String;
function GetDataSource: TDataSource;
function GetLabelCaption: String;
function GetLabelFont: TFont;
function GetLabelGroupIndex: Integer;
function IsLabelCaptionStored: Boolean;
function IsLabelFontStored: Boolean;
procedure SetDataField(const Value: String);
procedure SetDataSource(Value: TDataSource);
procedure SetLabelCaption(const Value: String);
procedure SetLabelFont(Value: TFont);
procedure SetLabelGroupIndex(Value: Integer);
function SubLabel: TNLDSubLabel;
protected
procedure Loaded; override;
procedure SetName(const NewName: TComponentName); override;
procedure SetParent(AParent: TWinControl); override;
procedure WndProc(var Message: TMessage); override;
public
constructor Create(AOwner: TComponent); override;
procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
published
property DataField: String read GetDataField write SetDataField;
property DataSource: TDataSource read GetDataSource write SetDataSource;
property LabelCaption: String read GetLabelCaption write SetLabelCaption
stored IsLabelCaptionStored;
property LabelFont: TFont read GetLabelFont write SetLabelFont
stored IsLabelFontStored;
property LabelGroupIndex: Integer read GetLabelGroupIndex
write SetLabelGroupIndex default 0;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('NLDelphi', [TNLDDBLabeledEdit]);
end;
type
TWinControlAccess = class(TWinControl);
function GetActiveFormEditor: IOTAFormEditor;
var
ModuleServices: IOTAModuleServices;
Module: IOTAModule;
Editor: IOTAEditor;
begin
ModuleServices := BorlandIDEServices as IOTAModuleServices;
Module := ModuleServices.CurrentModule;
Editor := Module.CurrentEditor;
Result := Editor as IOTAFormEditor;
end;
function SameFont(Font1, Font2: TFont): Boolean;
begin
Result := (Font1.Handle = Font2.Handle) and (Font1.Color = Font2.Color);
end;
{ TNLDSubLabel }
const
SEditNameSuffix = 'Edit';
SHiddenSpace = '(space)';
SInvalidSubLabelOwner = 'Owner of SubLabel must be of type TWinControl.';
SSubLabelCaptionSuffix = ':';
function FindLabel(Parent: TWinControl; ControlIndex: Integer;
out Lbl: TNLDSubLabel): Boolean;
begin
if Parent.Controls[ControlIndex] is TNLDSubLabel then
Lbl := TNLDSubLabel(Parent.Controls[ControlIndex])
else
Lbl := nil;
Result := Lbl <> nil;
end;
procedure TNLDSubLabel.Click;
var
FocusControl: IOTAComponent;
begin
if not (csDesigning in ComponentState) then
TWinControl(Owner).SetFocus
else
begin
FocusControl := GetActiveFormEditor.FindComponent(Owner.Name);
if FocusControl <> nil then
FocusControl.Select(False);
end;
inherited Click;
end;
procedure TNLDSubLabel.CMDesignHitTest(var Message: TCMDesignHitTest);
begin
inherited;
Message.Result := HTCLIENT;
end;
procedure TNLDSubLabel.CMFontChanged(var Message: TMessage);
var
F: TFont;
begin
inherited;
if HasParent and (not ParentFont) and (Font.Color = clDefault) then
begin
F := TFont.Create;
try
F.Assign(Font);
F.Color := TWinControlAccess(Parent).Font.Color;
if SameFont(F, TWinControlAccess(Parent).Font) then
ParentFont := True;
finally
F.Free;
end;
end;
end;
procedure TNLDSubLabel.CMTextChanged(var Message: TMessage);
begin
inherited;
Update;
end;
constructor TNLDSubLabel.Create(AOwner: TComponent);
begin
if not (AOwner is TWinControl) then
raise EComponentError.Create(SInvalidSubLabelOwner);
inherited Create(AOwner);
AutoSize := True;
ControlStyle := [csClickEvents, csSetCaption, csOpaque, csParentBackground,
csDoubleClicks];
FocusControl := TWinControl(Owner);
Transparent := True;
end;
function TNLDSubLabel.GetGroupIndex: Integer;
begin
Result := Tag;
end;
procedure TNLDSubLabel.SetGroupIndex(Value: Integer);
var
OldGroupIndex: Integer;
begin
if GroupIndex <> Value then
begin
if GroupIndex <> 0 then
begin
OldGroupIndex := GroupIndex;
Tag := Value;
Ungroup(OldGroupIndex);
end
else
begin
Tag := Value;
Update;
end;
end;
end;
procedure TNLDSubLabel.UnGroup(OldGroupIndex: Integer);
var
i: Integer;
Lbl: TNLDSubLabel;
begin
AdjustBounds;
Update;
if Parent <> nil then
begin
for i := 0 to Parent.ControlCount - 1 do
if FindLabel(Parent, i, Lbl) then
if Lbl.GroupIndex = OldGroupIndex then
Lbl.AdjustBounds;
for i := 0 to Parent.ControlCount - 1 do
if FindLabel(Parent, i, Lbl) then
if Lbl.GroupIndex = OldGroupIndex then
begin
Lbl.Update;
Break;
end;
end;
end;
procedure TNLDSubLabel.Update;
var
i: Integer;
Lbl: TNLDSubLabel;
NewWidth: Integer;
begin
Parent := TControl(Owner).Parent;
Enabled := TControl(Owner).Enabled;
Visible := TControl(Owner).Visible;
NewWidth := 0;
if Parent <> nil then
begin
if GroupIndex = 0 then
with TControl(Owner) do
Self.SetBounds(Left - Self.Width - 3, Top + 3, Self.Width, Height)
else
begin
for i := 0 to Parent.ControlCount - 1 do
if FindLabel(Parent, i, Lbl) then
if (Lbl.GroupIndex <> 0) and (Lbl.GroupIndex = GroupIndex) then
begin
Lbl.AdjustBounds;
NewWidth := Max(NewWidth, Lbl.Width);
end;
for i := 0 to Parent.ControlCount - 1 do
if FindLabel(Parent, i, Lbl) then
if (Lbl.GroupIndex <> 0) and (Lbl.GroupIndex = GroupIndex) then
with TControl(Lbl.Owner) do
Lbl.SetBounds(Left - NewWidth - 3, Top + 3, NewWidth, Height);
end;
end;
end;
{ TNLDDBLabeledEdit }
constructor TNLDDBLabeledEdit.Create(AOwner: TComponent);
begin
TNLDSubLabel.Create(Self);
inherited Create(AOwner);
end;
function TNLDDBLabeledEdit.DefaultLabelCaption: String;
var
F: TField;
begin
if (DataField = '') or (DataSource = nil) or (DataSource.DataSet = nil) then
F := nil
else
F := DataSource.DataSet.FindField(DataField);
if F <> nil then
Result := F.DisplayLabel
else if RightStr(Name, Length(SEditNameSuffix)) = SEditNameSuffix then
Result := Copy(Name, 1, Length(Name) - Length(SEditNameSuffix))
else
Result := Name;
if Trim(Result) <> '' then
Result := Result + SSubLabelCaptionSuffix;
end;
function TNLDDBLabeledEdit.GetDataField: String;
begin
Result := inherited DataField;
end;
function TNLDDBLabeledEdit.GetDataSource: TDataSource;
begin
Result := inherited DataSource;
end;
function TNLDDBLabeledEdit.GetLabelCaption: String;
begin
Result := SubLabel.Caption;
if (Result = ' ') and (csDesigning in ComponentState) then
Result := SHiddenSpace;
end;
function TNLDDBLabeledEdit.GetLabelFont: TFont;
begin
Result := SubLabel.Font;
end;
function TNLDDBLabeledEdit.GetLabelGroupIndex: Integer;
begin
Result := SubLabel.GroupIndex ;
end;
function TNLDDBLabeledEdit.IsLabelCaptionStored: Boolean;
begin
Result := LabelCaption <> DefaultLabelCaption;
end;
function TNLDDBLabeledEdit.IsLabelFontStored: Boolean;
begin
Result := not SubLabel.ParentFont;
end;
procedure TNLDDBLabeledEdit.Loaded;
begin
inherited Loaded;
if LabelCaption = '' then
LabelCaption := DefaultLabelCaption;
end;
procedure TNLDDBLabeledEdit.SetBounds(ALeft, ATop, AWidth,
AHeight: Integer);
begin
inherited SetBounds(ALeft, ATop, AWidth, AHeight);
SubLabel.Update;
end;
procedure TNLDDBLabeledEdit.SetDataField(const Value: String);
var
SyncCaption: Boolean;
NewName: String;
begin
if DataField <> Value then
begin
SyncCaption := not (csLoading in ComponentState) and
(LabelCaption = DefaultLabelCaption);
inherited DataField := Value;
if SyncCaption then
LabelCaption := DefaultLabelCaption;
if csDesigning in ComponentState then
begin
NewName := DataField + SEditNameSuffix;
if IsValidIdent(NewName) and not SameText(Name, NewName) and
(Owner <> nil) and (Owner.FindComponent(NewName) = nil) then
try
Name := NewName;
except
{ Eat exception }
end;
end;
end;
end;
procedure TNLDDBLabeledEdit.SetDataSource(Value: TDataSource);
var
SyncCaption: Boolean;
begin
if DataSource <> Value then
begin
SyncCaption := not (csLoading in ComponentState) and
(LabelCaption = DefaultLabelCaption);
inherited DataSource := Value;
if SyncCaption then
LabelCaption := DefaultLabelCaption;
end;
end;
procedure TNLDDBLabeledEdit.SetLabelCaption(const Value: String);
begin
if LabelCaption <> Value then
begin
if Value = SHiddenSpace then
SubLabel.Caption := ' '
else if Value = '' then
SubLabel.Caption := DefaultLabelCaption
else
SubLabel.Caption := Value;
end;
end;
procedure TNLDDBLabeledEdit.SetLabelFont(Value: TFont);
begin
SubLabel.Font.Assign(Value);
end;
procedure TNLDDBLabeledEdit.SetLabelGroupIndex(Value: Integer);
begin
SubLabel.GroupIndex := Value;
end;
procedure TNLDDBLabeledEdit.SetName(const NewName: TComponentName);
var
SyncCaption: Boolean;
begin
if Name <> NewName then
begin
SyncCaption := not (csLoading in ComponentState) and
(LabelCaption = DefaultLabelCaption);
inherited SetName(NewName);
if SyncCaption then
LabelCaption := DefaultLabelCaption;
end;
end;
procedure TNLDDBLabeledEdit.SetParent(AParent: TWinControl);
begin
inherited SetParent(AParent);
SubLabel.Update;
end;
function TNLDDBLabeledEdit.SubLabel: TNLDSubLabel;
begin
Result := TNLDSubLabel(Components[0]);
end;
procedure TNLDDBLabeledEdit.WndProc(var Message: TMessage);
begin
case Message.Msg of
CM_ENABLEDCHANGED,
CM_VISIBLECHANGED,
WM_WINDOWPOSCHANGED:
SubLabel.Update;
end;
inherited WndProc(Message);
end;
end.
|
unit gsPLClient;
interface
uses
Windows, Classes, SysUtils, IBDatabase, IBSQL, IBHeader, dbclient, DB,
gdcBase, PLHeader, PLIntf;
type
TgsPLTermv = class(TObject)
private
FTerm: term_t;
FSize: LongWord;
function GetDataType(const Idx: LongWord): Integer;
function GetTerm(const Idx: LongWord): term_t;
public
constructor CreateTermv(const ASize: Integer);
procedure PutInteger(const Idx: LongWord; const AValue: Integer);
procedure PutString(const Idx: LongWord; const AValue: String);
procedure PutFloat(const Idx: LongWord; const AValue: Double);
procedure PutDateTime(const Idx: LongWord; const AValue: TDateTime);
procedure PutDate(const Idx: LongWord; const AValue: TDateTime);
procedure PutInt64(const Idx: LongWord; const AValue: Int64);
procedure PutAtom(const Idx: LongWord; const AValue: String);
procedure PutVariable(const Idx: LongWord);
function ReadInteger(const Idx: LongWord): Integer;
function ReadString(const Idx: LongWord): String;
function ReadFloat(const Idx: LongWord): Double;
function ReadDateTime(const Idx: LongWord): TDateTime;
function ReadDate(const Idx: LongWord): TDateTime;
function ReadInt64(const Idx: LongWord): Int64;
function ReadAtom(const Idx: LongWord): String;
function ToString(const Idx: LongWord): String;
procedure Reset;
property DataType[const Idx: LongWord]: Integer read GetDataType;
property Term[const Idx: LongWord]: term_t read GetTerm;
property Size: LongWord read FSize;
end;
TgsPLQuery = class(TObject)
private
FQid: qid_t;
FEof: Boolean;
FTermv: TgsPLTermv;
FPred: String;
FDeleteDataAfterClose: Boolean;
function GetEof: Boolean;
public
constructor Create;
destructor Destroy; override;
procedure OpenQuery;
procedure Close;
procedure NextSolution;
property Eof: Boolean read GetEof;
property Pred: String read FPred write FPred;
property Termv: TgsPLTermv read FTermv write FTermv;
property DeleteDataAfterClose: Boolean read FDeleteDataAfterClose write FDeleteDataAfterClose;
end;
TgsPLClient = class(TObject)
private
FInitArgv: array of PChar;
FDebug: Boolean;
function GetArity(ASql: TIBSQL): Integer; overload;
function GetArity(ADataSet: TDataSet; const AFieldList: String): Integer; overload;
function GetTempPath: String;
function GetDefaultPLInitString: String;
public
destructor Destroy; override;
function Call(const APredicateName: String; AParams: TgsPLTermv): Boolean;
function Call2(const AGoal: String): Boolean;
procedure Compound(AGoal: term_t; const AFunctor: String; ATermv: TgsPLTermv);
function Initialise(const AParams: String = ''): Boolean;
function IsInitialised: Boolean;
procedure MakePredicatesOfSQLSelect(const ASQL: String; ATr: TIBTransaction;
const APredicateName: String; const AFileName: String);
procedure MakePredicatesOfDataSet(ADataSet: TDataSet; const AFieldList: String; const APredicateName: String; const AFileName: String);
procedure MakePredicatesOfObject(const AClassName: String; const ASubType: String; const ASubSet: String;
AParams: Variant; AnExtraConditions: TStringList; const AFieldList: String; ATr: TIBTransaction;
const APredicateName: String; const AFileName: String);
procedure ExtractData(ADataSet: TClientDataSet; const APredicateName: String; ATermv: TgsPLTermv);
property Debug: Boolean read FDebug write FDebug;
end;
EgsPLClientException = class(Exception)
public
constructor CreateTypeError(const AnExpected: String; const AnActual: term_t);
constructor CreatePLError(AnException: term_t);
end;
function TermToString(ATerm: term_t): String;
implementation
uses
jclStrings, gd_GlobalParams_unit, Forms;
constructor EgsPLClientException.CreateTypeError(const AnExpected: String; const AnActual: term_t);
begin
Message := 'error(type_error(' + AnExpected + ',' + TermToString(AnActual) + '))';
end;
constructor EgsPLClientException.CreatePLError(AnException: term_t);
{var
a: term_t;
name: atom_t;
arity: Integer; }
begin
Message := TermToString(AnException);
{a := PL_new_term_ref;
if (PL_get_arg(1, AnException, a) <> 0)
and (PL_get_name_arity(a, name, arity) <> 0)
then
Message := PL_atom_chars(name); }
end;
procedure RaisePrologError;
var
ex: term_t;
begin
ex := PL_exception(0);
if ex <> 0 then
raise EgsPLClientException.CreatePLError(ex);
end;
constructor TgsPLTermv.CreateTermv(const ASize: Integer);
begin
inherited Create;
FTerm := PL_new_term_refs(ASize);
FSize := ASize;
end;
function TgsPLTermv.GetTerm(const Idx: LongWord): term_t;
begin
if Idx >= Size then
raise EgsPLClientException.Create('Invalid index!');
Result := FTerm + Idx;
end;
function TgsPLTermv.ToString(const Idx: LongWord): String;
begin
Result := TermToString(GetTerm(Idx));
end;
procedure TgsPLTermv.Reset;
var
I: Integer;
begin
for I := 0 to FSize - 1 do
PutVariable(I);
end;
procedure TgsPLTermv.PutInteger(const Idx: LongWord; const AValue: Integer);
begin
PL_put_integer(GetTerm(Idx), AValue);
end;
procedure TgsPLTermv.PutString(const Idx: LongWord; const AValue: String);
begin
PL_put_string_chars(GetTerm(Idx), PChar(AValue));
end;
procedure TgsPLTermv.PutFloat(const Idx: LongWord; const AValue: Double);
begin
PL_put_float(GetTerm(Idx), AValue);
end;
procedure TgsPLTermv.PutDateTime(const Idx: LongWord; const AValue: TDateTime);
begin
PL_put_atom_chars(GetTerm(Idx), PChar(FormatDateTime('yyyy-mm-dd hh:nn:ss', AValue)));
end;
procedure TgsPLTermv.PutDate(const Idx: LongWord; const AValue: TDateTime);
begin
PL_put_atom_chars(GetTerm(Idx), PChar(FormatDateTime('yyyy-mm-dd', AValue)));
end;
procedure TgsPLTermv.PutInt64(const Idx: LongWord; const AValue: Int64);
begin
PL_put_int64(GetTerm(Idx), AValue);
end;
procedure TgsPLTermv.PutAtom(const Idx: LongWord; const AValue: String);
begin
PL_put_atom_chars(GetTerm(Idx), PChar(AValue));
end;
procedure TgsPLTermv.PutVariable(const Idx: LongWord);
begin
PL_put_variable(GetTerm(Idx));
end;
function TgsPLTermv.ReadInteger(const Idx: LongWord): Integer;
begin
if PL_get_integer(GetTerm(Idx), Result) = 0 then
raise EgsPLClientException.CreateTypeError('integer', GetTerm(Idx));
end;
function TgsPLTermv.ReadString(const Idx: LongWord): String;
var
len: Cardinal;
S: PChar;
begin
case GetDataType(Idx) of
PL_ATOM:
if PL_get_atom_chars(GetTerm(Idx), S) <> 0 then
Result := S
else
raise EgsPLClientException.CreateTypeError('atom', GetTerm(Idx));
PL_STRING:
if PL_get_string(GetTerm(Idx), S, len) <> 0 then
Result := S
else
raise EgsPLClientException.CreateTypeError('string', GetTerm(Idx));
end;
end;
function TgsPLTermv.ReadFloat(const Idx: LongWord): Double;
begin
if PL_get_float(GetTerm(Idx), Result) = 0 then
raise EgsPLClientException.CreateTypeError('float', GetTerm(Idx));
end;
function TgsPLTermv.ReadDateTime(const Idx: LongWord): TDateTime;
var
S: String;
begin
S := ReadString(Idx);
try
Result := VarToDateTime(S);
except
on E:Exception do
raise EgsPLClientException.CreateTypeError('datetime', GetTerm(Idx));
end;
end;
function TgsPLTermv.ReadAtom(const Idx: LongWord): String;
begin
Result := ReadString(Idx);
end;
function TgsPLTermv.ReadDate(const Idx: LongWord): TDateTime;
begin
Result := ReadDateTime(Idx);
end;
function TgsPLTermv.ReadInt64(const Idx: LongWord): Int64;
begin
if PL_get_int64(GetTerm(Idx), Result) = 0 then
raise EgsPLClientException.CreateTypeError('int64', GetTerm(Idx));
end;
function TgsPLTermv.GetDataType(const Idx: LongWord): Integer;
begin
if Idx >= Size then
raise EgsPLClientException.Create('Invalid index!');
Result := PL_term_type(GetTerm(Idx));
end;
constructor TgsPLQuery.Create;
begin
inherited Create;
FQid := 0;
FEOF := False;
FDeleteDataAfterClose := False;
end;
destructor TgsPLQuery.Destroy;
begin
Close;
inherited;
end;
function TgsPLQuery.GetEof: Boolean;
begin
Result := FEof or (FQid = 0);
end;
procedure TgsPLQuery.OpenQuery;
var
p: predicate_t;
begin
p := PL_predicate(PChar(FPred), FTermv.Size, 'user');
FQid := PL_open_query(nil, PL_Q_CATCH_EXCEPTION, p, FTermv.Term[0]);
if FQid = 0 then RaisePrologError;
NextSolution;
end;
procedure TgsPLQuery.Close;
begin
try
if FDeleteDataAfterClose then
PL_close_query(FQid)
else
PL_cut_query(FQid);
finally
FQid := 0;
FEof := False;
end;
end;
procedure TgsPLQuery.NextSolution;
var
ex: term_t;
begin
if not FEof then
begin
FEof := PL_next_solution(FQid) = 0;
if FEof then
begin
ex := PL_exception(FQid);
if ex <> 0 then
raise EgsPLClientException.CreatePLError(ex);
end;
end;
end;
destructor TgsPLClient.Destroy;
begin
if IsInitialised then
PL_cleanup(0);
inherited;
end;
procedure TgsPLClient.ExtractData(ADataSet: TClientDataSet; const APredicateName: String; ATermv: TgsPLTermv);
var
Query: TgsPLQuery;
I: LongWord;
F: TField;
begin
Assert(ADataSet <> nil);
Assert(ATermv <> nil);
Query := TgsPLQuery.Create;
try
Query.Pred := APredicateName;
Query.Termv := ATermv;
Query.DeleteDataAfterClose := True;
Query.OpenQuery;
while not Query.Eof do
begin
ADataSet.Insert;
try
for I := 0 to ADataSet.Fields.Count - 1 do
begin
F := ADataSet.Fields[I];
case F.DataType of
ftSmallint, ftInteger, ftBoolean: F.AsInteger := Query.Termv.ReadInteger(I);
ftCurrency, ftBCD: F.AsCurrency := Query.Termv.ReadFloat(I);
ftFloat: F.AsFloat := Query.Termv.ReadFloat(I);
ftLargeInt: (F as TLargeIntField).AsLargeInt := Query.Termv.ReadInt64(I);
ftTime, ftDateTime: F.AsDateTime := Query.Termv.ReadDateTime(I);
ftDate: F.AsDateTime := Query.Termv.ReadDate(I);
else
F.AsString := Query.Termv.ToString(I);
end;
end;
ADataSet.Post;
finally
if ADataSet.State in dsEditModes then
ADataSet.Cancel;
end;
Query.NextSolution;
end;
finally
Query.Free;
end;
end;
function TgsPLClient.Call2(const AGoal: String): Boolean;
var
t: TgsPLTermv;
Query: TgsPLQuery;
begin
Result := False;
t := TgsPLTermv.CreateTermv(1);
try
if PL_chars_to_term(PChar(AGoal), t.Term[0]) <> 0 then
begin
Query := TgsPLQuery.Create;
try
Query.Pred := 'call';
Query.Termv := t;
Query.OpenQuery;
Result := not Query.Eof;
finally
Query.Free;
end;
end;
finally
t.Free;
end;
end;
function TgsPLClient.Call(const APredicateName: String; AParams: TgsPLTermv): Boolean;
var
Query: TgsPLQuery;
begin
Assert(APredicateName > '');
Query := TgsPLQuery.Create;
try
Query.Pred := APredicateName;
Query.Termv := AParams;
Query.OpenQuery;
Result := not Query.Eof;
finally
Query.Free;
end;
end;
procedure TgsPLClient.Compound(AGoal: term_t; const AFunctor: String; ATermv: TgsPLTermv);
begin
Assert(AFunctor > '');
if PL_cons_functor_v(AGoal,
PL_new_functor(PL_new_atom(PChar(AFunctor)), ATermv.size),
ATermv.Term[0]) = 0
then
RaisePrologError;
end;
function TermToString(ATerm: term_t): String;
var
a: term_t;
name: atom_t;
arity, I: Integer;
S: PChar;
len: Cardinal;
begin
Result := '';
case PL_term_type(ATerm) of
PL_VARIABLE:
begin
PL_get_chars(ATerm, S, CVT_VARIABLE);
Result := S;
end;
PL_ATOM, PL_INTEGER, PL_FLOAT:
begin
PL_get_chars(ATerm, S, CVT_ALL);
Result := S;
end;
PL_STRING:
begin
PL_get_string(ATerm, S, len);
Result := StrSingleQuote(S);
end;
PL_TERM:
begin
if PL_get_name_arity(ATerm, name, arity) <> 0 then
begin
Result := Result + PL_atom_chars(name) + '(';
for I := 1 to arity do
begin
a := PL_new_term_ref;
PL_get_arg(I, ATerm, a);
Result := Result + TermToString(a) + ',';
end;
SetLength(Result, Length(Result) - 1);
Result := Result + ')';
end;
end;
else
raise Exception.Create('No variable!');
end;
end;
function TgsPLClient.GetArity(ASql: TIBSQL): Integer;
var
I: Integer;
begin
Assert(ASql <> nil);
Result := 0;
for I := 0 to ASQL.Current.Count - 1 do
begin
case ASQL.Fields[I].SQLType of
SQL_DOUBLE, SQL_FLOAT, SQL_LONG, SQL_SHORT,
SQL_TIMESTAMP, SQL_D_FLOAT, SQL_TYPE_TIME,
SQL_TYPE_DATE, SQL_INT64, SQL_Text, SQL_VARYING: Inc(Result);
end;
end;
end;
function TgsPLClient.GetTempPath: String;
var
Buff: array[0..1024] of Char;
begin
Windows.GetTempPath(SizeOf(Buff), Buff);
Result := ExcludeTrailingBackslash(Buff);
end;
function TgsPLClient.GetArity(ADataSet: TDataSet; const AFieldList: String): Integer;
var
I: Integer;
begin
Assert(ADataSet <> nil);
Result := 0;
for I := 0 to ADataSet.Fields.Count - 1 do
begin
if (StrIPos(',' + ADataSet.Fields[I].FieldName + ',', ',' + AFieldList + ',') > 0)
or (AFieldList = '') then
begin
case ADataSet.Fields[I].DataType of
ftString, ftSmallint, ftInteger, ftWord,
ftBoolean, ftFloat, ftCurrency, ftDate, ftTime, ftDateTime,
ftMemo, ftLargeint: Inc(Result);
end;
end;
end;
end;
function TgsPLClient.IsInitialised: Boolean;
var
argc: Integer;
begin
argc := High(FInitArgv);
Result := (argc > -1) and TryPLLoad;
if Result then
Result := PL_is_initialised(argc, FInitArgv) <> 0;
end;
function TgsPLClient.Initialise(const AParams: String = ''): Boolean;
function GetNextElement(const S: String; var L: Integer): String;
var
F: Integer;
begin
F := L;
while (F <= Length(S)) and (S[F] <> '!') and (S[F + 1] <> '@') do
Inc(F);
Result := Trim(Copy(S, L, F - L));
Inc(F, 2);
L := F;
end;
procedure GetParamsList(const S: String; SL: TStringList);
var
P: Integer;
begin
P := 1;
while P <= Length(S) do
SL.Add(GetNextElement(S, P));
end;
var
SL: TStringList;
I: Integer;
TempS: String;
begin
if not TryPLLoad then
raise EgsPLClientException.Create('Клиентская часть Prolog не установлена!');
{if AParams > '' then
TempS := Trim(AParams)
else
TempS := GetDefaultPLInitString;
TempS := StringReplace(TempS, '],[', '!@', [rfReplaceAll]);
TempS := Copy(TempS, 2, Length(TempS) - 2);
SL := TStringList.Create;
try
if AParams = '' then
GetParamsList(TempS, SL);
SetLength(FInitArgv, SL.Count + 1);
for I := 0 to SL.Count - 1 do
FInitArgv[I] := PChar(SL[I]);
FInitArgv[High(FInitArgv)] := nil;}
//
TempS := 'c:/golden/Gedemin/gd_pl/EXE/';
SetLength(FInitArgv,8);
FInitArgv[0] := PChar('libswipl.dll');
FInitArgv[1] := PChar('-x');
FInitArgv[2] := PChar(TempS + 'swipl/gd_pl_state.dat');
FInitArgv[3] := PChar('-p');
FInitArgv[4] := PChar('foreign=' + TempS + 'swipl/lib');
FInitArgv[5] := PChar('-t');
FInitArgv[6] := PChar('true');
FInitArgv[7] := nil;
//
if not IsInitialised then
begin
Result := PL_initialise(High(FInitArgv), FInitArgv) <> 0;
if not Result then
PL_halt(1);
end else
Result := False;
{finally
SL.Free;
end;}
end;
procedure TgsPLClient.MakePredicatesOfDataSet(ADataSet: TDataSet; const AFieldList: String;
const APredicateName: String; const AFileName: String);
var
I, Arity, Idx: Integer;
Refs, Term: TgsPLTermv;
begin
Assert(ADataSet <> nil);
Assert(APredicateName > '');
Arity := GetArity(ADataSet, AFieldList);
Refs := TgsPLTermv.CreateTermv(Arity);
Term := TgsPLTermv.CreateTermv(1);
try
ADataSet.First;
while not ADataSet.Eof do
begin
Idx := 0;
for I := 0 to ADataSet.Fields.Count - 1 do
begin
if (StrIPos(',' + ADataSet.Fields[I].FieldName + ',', ',' + AFieldList + ',') > 0)
or (AFieldList = '') then
begin
case ADataSet.Fields[I].DataType of
ftSmallint, ftInteger, ftWord, ftBoolean:
Refs.PutInteger(Idx, ADataSet.Fields[I].AsInteger);
ftLargeint: Refs.PutInt64(Idx, TLargeintField(ADataSet.Fields[I]).AsLargeInt);
ftFloat: Refs.PutFloat(Idx, ADataSet.Fields[I].AsFloat);
ftCurrency: Refs.PutFloat(Idx, ADataSet.Fields[I].AsCurrency);
ftString, ftMemo: Refs.PutString(Idx, ADataSet.Fields[I].AsString);
ftDate: Refs.PutDate(Idx, ADataSet.Fields[I].AsDateTime);
ftDateTime, ftTime: Refs.PutDateTime(Idx, ADataSet.Fields[I].AsDateTime);
end;
Inc(Idx);
end;
end;
Compound(Term.Term[0], APredicateName, Refs);
Call('assert', Term);
ADataSet.Next;
end;
finally
Refs.Free;
Term.Free;
end;
end;
procedure TgsPLClient.MakePredicatesOfSQLSelect(const ASQL: String; ATr: TIBTransaction;
const APredicateName: String; const AFileName: String);
var
q: TIBSQL;
Refs, Term: TgsPLTermv;
I: LongWord;
Arity: Integer;
begin
Assert(ATr <> nil);
Assert(ATr.InTransaction);
q := TIBSQL.Create(nil);
try
q.Transaction := ATr;
q.SQL.Text := ASQL;
q.ExecQuery;
Arity := GetArity(q);
if Arity > 0 then
begin
Refs := TgsPLTermv.CreateTermv(Arity);
Term := TgsPLTermv.CreateTermv(1);
try
while not q.Eof do
begin
for I := 0 to q.Current.Count - 1 do
begin
case q.Fields[I].SQLType of
SQL_LONG, SQL_SHORT:
if q.Fields[I].AsXSQLVAR.sqlscale = 0 then
Refs.PutInteger(I, q.Fields[I].AsInteger)
else
Refs.PutFloat(I, q.Fields[I].AsCurrency);
SQL_FLOAT, SQL_D_FLOAT, SQL_DOUBLE:
Refs.PutFloat(I, q.Fields[I].AsFloat);
SQL_INT64:
if q.Fields[I].AsXSQLVAR.sqlscale = 0 then
Refs.PutInt64(I, q.Fields[I].AsInt64)
else
Refs.PutFloat(I, q.Fields[I].AsCurrency);
SQL_TYPE_DATE:
Refs.PutDate(I, q.Fields[I].AsDate);
SQL_TIMESTAMP, SQL_TYPE_TIME:
Refs.PutDateTime(I, q.Fields[I].AsDateTime);
SQL_TEXT, SQL_VARYING:
Refs.PutString(I, q.Fields[I].AsTrimString);
end;
end;
Compound(Term.Term[0], APredicateName, Refs);
Call('assert', Term);
q.Next;
end;
finally
Refs.Free;
Term.Free;
end;
end;
finally
q.Free;
end;
end;
procedure TgsPLClient.MakePredicatesOfObject(const AClassName: String; const ASubType: String; const ASubSet: String;
AParams: Variant; AnExtraConditions: TStringList; const AFieldList: String; ATr: TIBTransaction;
const APredicateName: String; const AFileName: String);
var
C: TPersistentClass;
Obj: TgdcBase;
I: Integer;
begin
Assert(ATr <> nil);
Assert(ATr.InTransaction);
Assert(AClassName > '');
Assert(ASubSet > '');
Assert(APredicateName > '');
Assert(VarIsArray(AParams));
Assert(VarArrayDimCount(AParams) = 1);
C := GetClass(AClassName);
if (C = nil) or (not C.InheritsFrom(TgdcBase)) then
raise EgsPLClientException.Create('Invalid class name ' + AClassName);
Obj := CgdcBase(C).Create(nil);
try
Obj.SubType := ASubType;
Obj.ReadTransaction := ATr;
Obj.Transaction := ATr;
if AnExtraConditions <> nil then
Obj.ExtraConditions := AnExtraConditions;
Obj.SubSet := ASubSet;
Obj.Prepare;
for I := VarArrayLowBound(AParams, 1) to VarArrayHighBound(AParams, 1) do
begin
Obj.Params[0].AsVariant := AParams[I];
Obj.Open;
if not Obj.Eof then
MakePredicatesOfDataSet(Obj, AFieldList, APredicateName, AFileName);
Obj.Close;
end;
finally
Obj.Free;
end;
end;
function TgsPLClient.GetDefaultPLInitString: String;
var
Path: String;
begin
Path := ExtractFilePath(Application.EXEName) + IncludeTrailingBackSlash(PrologPath);
Path := StringReplace(Path, '\', '/', [rfReplaceAll]);
Result := Format('[libswipl.dll],[-x],[%0:sgd_pl_state.dat],[-p],[foreign=%0:slib]', [Path]);
end;
end.
|
unit JpgToBmp;
{-----------------------------------------------------------------------------}
{ TJpgToBmp v 1.2 }
{ Copyright 1998,1999, Eric Pedrazzi. All Rights Reserved. }
{-----------------------------------------------------------------------------}
{ A component to translate a jpeg (timage or file) into a bitmap file }
{ }
{ This component can be freely used and distributed in commercial and private }
{ environments, provied this notice is not modified in any way and there is }
{ no charge for it other than nomial handling fees. Contact me directly for }
{ modifications to this agreement. }
{ }
{-----------------------------------------------------------------------------}
{ Feel free to contact me if you have any questions, comments or suggestions }
{ at epedrazzi@chez.com }
{ The latest version will always be available on the web at: }
{ http://www.chez.com/epedrazzi }
{ See JpgToBmp.txt for notes, known issues, and revision history. }
{-----------------------------------------------------------------------------}
{ Date last modified: April 1999 }
{-----------------------------------------------------------------------------}
{ v1.0 : Initial release }
{ v1.1 : bug reported by Myke Mudford (whariti@manawatu.gen.nz) }
{ "The color goes funny" bug seems to be corrected }
{ v1.2 : Rename of the methods
{ Add Image property
{ Add CopyImageToBmp method
{
{ }
{-----------------------------------------------------------------------------}
{ This unit provides an invisible component to perform a copy of a bitmap file
to a jpeg file.
Properties
----------
Image : Source Image (TImage)
JpegFile : Source file in Jpeg format
BmpFile : Destination File in bitmap format
Methods
-------
CopyJpgToBmp : Start jpg file to bmp file translation
CopyImageToBmp : Start image to bmp file translation
}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Jpeg, ExtCtrls;
type
TJpegToBmp = class(TComponent)
private
{ Déclarations privées }
FImage : TImage;
FStreamBmp, FStreamJpg : TStream;
FJpeg : TJpegImage;
FBmp : TBitmap;
FBmpFile : AnsiString;
FJpegFile: AnsiString;
protected
{ Déclarations protégées }
procedure FCopyJpegToBmp;
procedure FCopyImageToBmp;
public
{ Déclarations publiques }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure CopyJpegToBmp;
procedure CopyImageToBmp;
published
{ Déclarations publiées }
property Image : TImage read FImage write FImage;
property BmpFile : AnsiString read FBmpFile write FBmpFile;
property JpegFile: AnsiString read FJpegFile write FJpegFile;
end;
procedure Register;
implementation
procedure TJpegToBmp.FCopyImageToBmp;
begin
FStreamBmp := TFileStream.Create(FBmpFile,fmCreate);
try
FJpeg.Assign(FImage.Picture);
if FJpeg.PixelFormat = jf24bit then
FBmp.PixelFormat := pf24bit
else
FBmp.PixelFormat := pf8bit;
FBmp.Width := FJpeg.Width;
FBmp.Height := FJpeg.Height;
FBmp.Canvas.Draw(0,0,FJpeg);
FBmp.SaveToStream(FStreamBmp);
finally
FStreamBmp.Free;
end;
end;
procedure TJpegToBmp.FCopyJpegToBmp;
begin
if FileExists(FBmpFile) then DeleteFile(FBmpFile);
FStreamBmp := TFileStream.Create(FBmpFile,fmCreate);
FStreamJpg := TFileStream.Create(FJpegFile, fmOpenRead);
try
if FJpeg.PixelFormat = jf24bit then
FBmp.PixelFormat := pf24bit
else
FBmp.PixelFormat := pf8bit;
FJpeg.LoadFromStream(FStreamJpg);
FBmp.Width := FJpeg.Width;
FBmp.Height := FJpeg.Height;
FBmp.Canvas.Draw(0,0,FJpeg);
FBmp.SaveToStream(FStreamBmp);
finally
FStreamJpg.Free;
FStreamBmp.Free;
end;
end;
constructor TJpegToBmp.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FJpeg := TJpegImage.Create;
FBmp := TBitmap.Create;
end;
destructor TJpegToBmp.Destroy;
begin
FJpeg.Free;
FBmp.Free;
inherited Destroy;
end;
procedure TJpegToBmp.CopyImageToBmp;
begin
FCopyImageToBmp;
end;
procedure TJpegToBmp.CopyJpegToBmp;
begin
FCopyJpegToBmp;
end;
procedure Register;
begin
RegisterComponents('Samples', [TJpegToBmp]);
end;
end.
|
UNIT mandutil;
{ Various estimators for Mandelbrot and Julia Sets }
{$I FLOAT.INC}
interface
uses MathLib0,
MapStuff {ArcCos};
CONST
LimitIter = 500;
{ Global limit to iterations of all functions }
VAR
MaxIter : WORD;
{ User specified iteration count. May not exceed LimitIter }
(* test variables *)
MSetHit, MSetNoHit, sumiter : WORD;
FUNCTION JSet(cx,cy : FLOAT; p, q : FLOAT) : WORD;
{ returns iterations before escape or MaxIter if in Set}
FUNCTION MSet(cx,cy : FLOAT) : WORD;
{ returns iterations before escape or MaxIter if in Set}
FUNCTION JSetDist(cx,cy : FLOAT; p,q : FLOAT) : FLOAT;
{distance on complex plane to Set}
FUNCTION MSetDist(cx,cy : FLOAT) : FLOAT;
{distance on complex plane to Set}
FUNCTION MSetBD(cx,cy : FLOAT) : WORD;
{ Binary decomposition. Returns either 0 or Maxiter }
FUNCTION JSetBD(cx,cy : FLOAT; p, q : FLOAT) : WORD;
{ Binary decomposition. Returns either 0 or Maxiter }
implementation
{$DEFINE AI}
{$IFDEF AI}
CONST
RequiredRep = 5;
VAR
LastPeriod, NumRep,
LastX, LastY,
CheckEvery, Periodicity : INTEGER;
{$ENDIF}
VAR
PiAndHalf : FLOAT;
{ ---------------------------------------------------------------}
{$IFDEF AI}
FUNCTION CheckPeriodicity( VAR x,y : FLOAT) : BOOLEAN;
VAR
retval : BOOLEAN;
curX, curY : INTEGER;
BEGIN
(* constrain our scale to a coarsness *similar* to the screen *)
(* resolution. Effect is loosen periodicty requirement *)
curX := TRUNC(X * 300.0);
curY := TRUNC(Y * 300.0);
retval := FALSE;
(* Is this point the same as the one I sampled earlier? *)
IF ((CurX = Lastx) AND (CurY = Lasty)) THEN
BEGIN
(* Is the number of iterations between now and when I last
saw this point the same as the time before? *)
IF (LastPeriod = Periodicity) THEN
(* Has this pattern repeated itself 'RequiredRep' times? *)
if (NumRep = RequiredRep) THEN
retval := TRUE (* Yep, return TRUE *)
ELSE
NumRep := Succ(NumRep) (* no, but we're one closer *)
(* Nope, keep looking - maybe is will settle out *)
ELSE
BEGIN
LastPeriod := Periodicity;
Periodicity := 1;
END;
END
(* Not the same point. Time to pick a new sample point? *)
ELSE
BEGIN
if (Periodicity >= CheckEvery) THEN
BEGIN
CheckEvery := CheckEvery * 2; (* Look for larger patterns *)
Periodicity := 1;
Lastx := CurX;
Lasty := CurY;
NumRep := 0;
END
ELSE
Periodicity := Succ(Periodicity);
END;
CheckPeriodicity := retval;
END (* Check*);
{$ENDIF}
{ ---------------------------------------------------------------}
FUNCTION JSet(cx,cy : FLOAT; p, q : FLOAT) : WORD;
CONST
huge = 100.0;
VAR
iter : WORD;
temp,
x, y, x2, y2 : FLOAT;
BEGIN
x := cx;
y := cy;
x2 := sqr(x);
y2 := sqr(y);
iter := 0;
WHILE (iter < MaxIter) AND (x2 + y2 < huge) DO
BEGIN
temp := x;
x := x2 - y2 + p;
y := 2 * temp * y + q;
x2 := sqr(x);
y2 := sqr(y);
INC(iter);
END; { while }
JSet := iter;
END {JSet};
{ ---------------------------------------------------------------}
FUNCTION JSetBD(cx,cy : FLOAT; p, q : FLOAT) : WORD;
CONST
huge = 100.0;
VAR
iter : WORD;
temp,
theta,
x, y, x2, y2 : FLOAT;
BEGIN
x := cx;
y := cy;
x2 := sqr(x);
y2 := sqr(y);
iter := 0;
WHILE (iter < MaxIter) AND (x2 + y2 < huge) DO
BEGIN
x2 := sqr(x);
y2 := sqr(y);
temp := x;
x := x2 - y2 + p;
y := 2 * temp * y + q;
INC(iter);
END; { while }
{ now figure out the decomposition }
IF (x = 0) THEN
JSetBD := MaxIter
ELSE
BEGIN
theta := arccos(abs(x)/(X2 + Y2));
IF (X < 0) THEN
BEGIN
IF (Y>=0) THEN
theta := theta + HalfPi
ELSE
theta := theta + Pi;
END
ELSE IF (Y<0) THEN
theta := theta + PiAndHalf;
IF (theta > 0) AND (theta <= pi) THEN
JSetBd := MaxIter
ELSE
JSetBD := 0;
END;
END {JSetBD};
{ ---------------------------------------------------------------}
FUNCTION MSet(cx,cy : FLOAT) : WORD;
CONST
huge = 10000.0;
VAR
iter : WORD;
temp,
x, y, x2, y2 : FLOAT;
Bail : BOOLEAN;
BEGIN
{$IFDEF AI}
(* periodicity check stuff *)
Bail := FALSE;
NumRep := 0;
Periodicity := 1;
LastPeriod := 1; (* First assume a periodicity of 1 *)
CheckEvery := 3; (* Look for small patterns first *)
Lastx := 0;
Lasty := 0;
(* end periodicity check stuff *)
{$ENDIF}
x := 0;
y := 0;
x2 := 0;
y2 := 0;
iter := 0;
WHILE (iter < MaxIter) AND (x2 + y2 < huge) DO
BEGIN
temp := x2 - y2 + cx;
y := 2 * x * y + cy;
x := temp;
x2 := sqr(x);
y2 := sqr(y);
INC(iter);
{$IFDEF AI}
IF CheckPeriodicity(x,y) THEN
BEGIN
bail := TRUE;
sumiter := sumiter + iter;
INC(MSetHit);
iter := MaxIter;
END;
{$ENDIF}
END; { while }
IF (iter = MaxIter) AND NOT BAIL THEN
INC(MSetNoHit);
MSet := iter;
END {MSet};
{ ---------------------------------------------------------------}
FUNCTION MSetBD(cx,cy : FLOAT) : WORD;
CONST
huge = 10000.0;
VAR
iter : WORD;
temp,
theta,
x, y, x2, y2 : FLOAT;
BEGIN
x := 0;
y := 0;
x2 := 0;
y2 := 0;
iter := 0;
WHILE (iter < MaxIter) AND (x2 + y2 < huge) DO
BEGIN
temp := x2 - y2 + cx;
y := 2 * x * y + cy;
x := temp;
x2 := sqr(x);
y2 := sqr(y);
INC(iter);
END; { while }
{ now figure out the decomposition }
IF (X = 0) OR (iter = MaxIter) THEN
MSetBD := MaxIter
ELSE
BEGIN
theta := arccos(abs(x)/(X2 + Y2));
IF (X < 0) THEN
BEGIN
IF (Y>=0) THEN
theta := theta + HalfPi
ELSE
theta := theta + Pi;
END
ELSE IF (Y<0) THEN
theta := theta + PiAndHalf;
IF (theta > 0) AND (theta <= pi) THEN
MSetBD := 0
ELSE
MSetBD := MaxIter;
END;
END {MSetBD};
{ ---------------------------------------------------------------}
FUNCTION JSetDist(cx,cy : FLOAT; p,q : FLOAT) : FLOAT;
CONST
{$IFOPT N+}
overflow = 1.699e37; { close to max range of REAL }
{$ELSE}
overflow = 1.699e37; { close to max range of REAL }
{$ENDIF}
huge = 10000.0; { stops iteration }
TYPE
orbits = ARRAY[0.. LimitIter] OF FLOAT;
VAR
iter, i : WORD;
x, y, x2, y2 : FLOAT;
temp,
xder, yder,
dist : FLOAT;
flag : BOOLEAN;
xorbit,
yorbit : orbits;
BEGIN
dist := 0;
xorbit[0] := 0;
yorbit[0] := 0;
iter := 0;
flag := FALSE;
x := cx;
y := cy;
x2 := sqr(x);
y2 := sqr(y);
WHILE (iter < MaxIter) AND (x2 + y2 < huge) DO
BEGIN
temp := x;
x := x2 - y2 + p;
y := 2 * temp * y + q;
x2 := sqr(x);
y2 := sqr(y);
INC(iter);
xorbit[iter] := x;
yorbit[iter] := y;
END; { while }
IF x2 + y2 > huge THEN
BEGIN
xder := 0;
yder := 0;
i := 0;
flag := FALSE;
WHILE (i < iter) AND (NOT flag) DO
BEGIN
temp := 2 * (xorbit[i] * xder-yorbit[i]*yder)+1;
yder := 2 * (yorbit[i] * xder+xorbit[i]*yder);
xder := temp;
flag := (abs(xder) > overflow) OR (abs(yder) > overflow);
INC(i);
END; {while}
IF NOT flag THEN
dist := ln(x2+y2)/ln10 * sqrt(x2+y2) / sqrt(sqr(xder) + sqr(yder));
END; {IF}
JSetDist := dist;
END; {JSetDist}
{ ---------------------------------------------------------------}
FUNCTION MSetDist(cx,cy : FLOAT) : FLOAT;
CONST
{$IFOPT N+}
overflow = 1.699e37; { close to max range of REAL }
{$ELSE}
overflow = 1.699e37; { close to max range of REAL }
{$ENDIF}
huge = 10000.0; { stops iteration }
TYPE
orbits = ARRAY[0.. LimitIter] OF FLOAT;
VAR
iter, i : WORD;
x, y, x2, y2 : FLOAT;
temp,
xder, yder,
dist : FLOAT;
flag : BOOLEAN;
xorbit,
yorbit : orbits;
BEGIN
dist := 0;
x := 0;
y := 0;
x2 := 0;
y2 := 0;
xorbit[0] := 0;
yorbit[0] := 0;
iter := 0;
flag := FALSE;
WHILE (iter < MaxIter) AND (x2 + y2 < huge) DO
BEGIN
temp := x2 - y2 + cx;
y := 2 * x * y + cy;
x := temp;
x2 := sqr(x);
y2 := sqr(y);
INC(iter);
xorbit[iter] := x;
yorbit[iter] := y;
END; { while }
IF x2 + y2 > huge THEN
BEGIN
xder := 0;
yder := 0;
i := 0;
flag := FALSE;
WHILE (i < iter) AND (NOT flag) DO
BEGIN
temp := 2 * (xorbit[i] * xder-yorbit[i]*yder)+1;
yder := 2 * (yorbit[i] * xder+xorbit[i]*yder);
xder := temp;
flag := (abs(xder) > overflow) OR (abs(yder) > overflow);
INC(i);
END; {while}
IF NOT flag THEN
dist := ln(x2+y2)/ln10 * sqrt(x2+y2) / sqrt(sqr(xder) + sqr(yder));
END; {IF}
MSetDist := dist;
END {MSetDist};
{--------------------------------------------------}
BEGIN
MaxIter := 100; { nice default number }
PiAndHalf := Pi + HalfPi;
{$IFDEF AI}
MSetHit := 0;
MSetNoHit := 0;
sumiter := 0;
{$ENDIF}
END {MandUtil}. |
{***************************************************************************
*
* Orion-project.org Lazarus Helper Library
* Copyright (C) 2016-2017 by Nikolay Chunosov
*
* This file is part of the Orion-project.org Lazarus Helper Library
* https://github.com/Chunosov/orion-lazarus
*
* This Library is free software: you can redistribute it and/or modify it
* under the terms of the MIT License. See enclosed LICENSE.txt for details.
*
***************************************************************************}
unit Tests_OriMath;
{$mode objfpc}{$H+}
interface
uses
FpcUnit, TestRegistry;
type
TTest_OriMath = class(TTestCase)
published
procedure StringFromFloat;
end;
implementation
uses
SysUtils,
OriStrings, OriMath;
procedure TTest_OriMath.StringFromFloat;
var
V: Double;
S: String;
D: Char;
begin
D := DefaultFormatSettings.DecimalSeparator;
V := 12456.7556;
S := OriMath.StringFromFloat(V, 3, 3, False);
AssertEquals(ReplaceChar('1,246E+4', ',', D), S);
S := OriMath.StringFromFloat(V, 4, 3, False);
AssertEquals(ReplaceChar('1,246E+4', ',', D), S);
S := OriMath.StringFromFloat(V, 5, 3, False);
AssertEquals(ReplaceChar('12456,756', ',', D), S);
V := 0.0012;
S := OriMath.StringFromFloat(V, 4, 3, False);
AssertEquals(ReplaceChar('0,001', ',', D), S);
S := OriMath.StringFromFloat(V, 3, 2, True);
AssertEquals(ReplaceChar('1,20E-3', ',', D), S);
S := OriMath.StringFromFloat(V, 3, 2, False);
AssertEquals(ReplaceChar('1,2E-3', ',', D), S);
end;
initialization
RegisterTest(TTest_OriMath);
end.
|
unit ansi_from_unicode_1;
interface
implementation
var
SA: AnsiString;
procedure Test;
begin
SA := 'hello_ansi';
end;
initialization
Test();
finalization
Assert(SA = 'hello_ansi');
end. |
unit uFSettingsEditor;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, RTTIGrids, SynEdit, LResources, Forms, Controls, Graphics, Dialogs, ButtonPanel,
ComCtrls, ExtCtrls, Buttons, StdCtrls, EditBtn, PropEdits, ObjectInspector, ECTabCtrl, uEditorLspSettings,
SynLCHighlighter, LCLType;
resourcestring
rsFileNotSet = 'O Arquivo nao foi informado.';
rsFileNotFound = 'O Arquivo "%s" não foi encontrado.';
type
{ TFSettingsEditor }
TFSettingsEditor = class(TForm)
bbAddArqExc : TBitBtn;
bbRemoverArqExc : TBitBtn;
ButtonPanel1: TButtonPanel;
chkDefault : TCheckBox;
chkBold : TCheckBox;
chkDefaultNivel: TCheckBox;
chkItalic : TCheckBox;
chkUnder : TCheckBox;
colBackCol : TColorButton;
colTextCol : TColorButton;
CorLinhaNivel: TColorButton;
dePastaRootModulo : TDirectoryEdit;
fnArqExc : TFileNameEdit;
Label1 : TLabel;
Label2 : TLabel;
Label3 : TLabel;
Label4 : TLabel;
Label5 : TLabel;
Label6 : TLabel;
Label7: TLabel;
Label8: TLabel;
lbArqExc : TListBox;
lbNiveisIdentacao: TListBox;
lbModulos : TListBox;
lbElementosSintaxe : TListBox;
PageControl1: TPageControl;
Splitter1: TSplitter;
SynEdit1: TSynEdit;
TabSheet1 : TTabSheet;
TabSheet2: TTabSheet;
TabSheet3 : TTabSheet;
TabSheet4: TTabSheet;
TIPropertyGrid1: TTIPropertyGrid;
procedure bbAddArqExcClick(Sender : TObject);
procedure bbRemoverArqExcClick(Sender : TObject);
procedure chkDefaultChange(Sender : TObject);
procedure chkDefaultNivelChange(Sender: TObject);
procedure dePastaRootModuloChange(Sender : TObject);
procedure FormCreate(Sender: TObject);
procedure lbArqExcClick(Sender : TObject);
procedure lbElementosSintaxeSelectionChange(Sender : TObject; {%H-}User : boolean);
procedure lbModulosSelectionChange(Sender : TObject; {%H-}User : boolean);
procedure lbNiveisIdentacaoSelectionChange(Sender : TObject; {%H-}User : boolean);
procedure OKButtonClick(Sender: TObject);
private
procedure UpdateDisplayElemento(pValue:TLCElementoSintaxe);
procedure UpdateDisplayNivelIdentacao(pValue:TLCNiveisIdentacaoConfig);
{ private declarations }
public
{ public declarations }
end;
var
FSettingsEditor: TFSettingsEditor;
implementation
{$R *.lfm}
uses ufmain, LCSynEdit;
{ TFSettingsEditor }
procedure TFSettingsEditor.OKButtonClick(Sender: TObject);
begin
if lbModulos.Tag <> -1 then
begin
TModuloVetorh(lbModulos.Items.Objects[lbModulos.Tag]).PastaBase := dePastaRootModulo.Directory;
TModuloVetorh(lbModulos.Items.Objects[lbModulos.Tag]).ArquivosExcluidos.Assign(lbArqExc.Items);
end;
if lbElementosSintaxe.Tag <> -1 then
begin
TLCElementoSintaxe(lbElementosSintaxe.Items.Objects[lbElementosSintaxe.Tag]).DefaultValues := chkDefault.checked;
TLCElementoSintaxe(lbElementosSintaxe.Items.Objects[lbElementosSintaxe.Tag]).Atributos.Background := colBackCol.ButtonColor;
TLCElementoSintaxe(lbElementosSintaxe.Items.Objects[lbElementosSintaxe.Tag]).Atributos.Foreground := colTextCol.ButtonColor;
TLCElementoSintaxe(lbElementosSintaxe.Items.Objects[lbElementosSintaxe.Tag]).Atributos.Style := [];
if chkBold.Checked then
begin
TLCElementoSintaxe(lbElementosSintaxe.Items.Objects[lbElementosSintaxe.Tag]).Atributos.Style :=
TLCElementoSintaxe(lbElementosSintaxe.Items.Objects[lbElementosSintaxe.Tag]).Atributos.Style + [fsBold];
end;
if chkItalic.Checked then
begin
TLCElementoSintaxe(lbElementosSintaxe.Items.Objects[lbElementosSintaxe.Tag]).Atributos.Style :=
TLCElementoSintaxe(lbElementosSintaxe.Items.Objects[lbElementosSintaxe.Tag]).Atributos.Style + [fsItalic];
end;
if chkUnder.Checked then
begin
TLCElementoSintaxe(lbElementosSintaxe.Items.Objects[lbElementosSintaxe.Tag]).Atributos.Style :=
TLCElementoSintaxe(lbElementosSintaxe.Items.Objects[lbElementosSintaxe.Tag]).Atributos.Style + [fsUnderline];
end;
end;
if lbNiveisIdentacao.Tag <> -1 then
begin
TLCNiveisIdentacaoConfig(lbNiveisIdentacao.Items.Objects[lbNiveisIdentacao.Tag]).DefaultValues := chkDefaultNivel.checked;
TLCNiveisIdentacaoConfig(lbNiveisIdentacao.Items.Objects[lbNiveisIdentacao.Tag]).Atributos.Foreground := CorLinhaNivel.ButtonColor;
end;
FrmMain.SalvarConfiguracoes;
Self.ModalResult := mrOK;
end;
procedure TFSettingsEditor.UpdateDisplayElemento(pValue : TLCElementoSintaxe);
begin
chkDefault.checked := pValue.DefaultValues;
colBackCol.ButtonColor := pValue.Atributos.Background;
colBackCol.Hint := '$' + IntToHex(pValue.Atributos.Background, 6);
colTextCol.ButtonColor := pValue.Atributos.Foreground;
colTextCol.Hint := '$' + IntToHex(pValue.Atributos.Foreground, 6);
chkBold.Checked := fsBold in pValue.Atributos.Style;
chkItalic.Checked := fsItalic in pValue.Atributos.Style;
chkUnder.Checked := fsUnderline in pValue.Atributos.Style;
end;
procedure TFSettingsEditor.UpdateDisplayNivelIdentacao(
pValue: TLCNiveisIdentacaoConfig);
begin
chkDefaultNivel.checked := pValue.DefaultValues;
CorLinhaNivel.ButtonColor := pValue.Atributos.Foreground;
CorLinhaNivel.Hint := '$' + IntToHex(pValue.Atributos.Foreground, 6);
end;
procedure TFSettingsEditor.FormCreate(Sender: TObject);
var
item:TCollectionItem;
Modulo: TModuloVetorh;
Elemento: TLCElementoSintaxe;
Nivel:TLCNiveisIdentacaoConfig;
begin
FrmMain.AtualizarPreferencias(SynEdit1);
TIPropertyGrid1.TIObject := FrmMain.EditorSettings;
// Aba Modulos Vetorh
dePastaRootModulo.Directory := '';
lbArqExc.Items.clear;
fnArqExc.FileName := '';
lbModulos.Clear;
lbModulos.Tag := -1;
for item in FrmMain.EditorSettings.ModulosVetorh do
begin
Modulo:= TModuloVetorh(item);
lbModulos.AddItem(AbreviaturaModuloVetorh[modulo.Sigla], modulo);
end;
// Aba Elementos Sintaxe
lbElementosSintaxe.Clear;
lbElementosSintaxe.Tag := -1;
for item in FrmMain.EditorSettings.Editor.ElementosSintaxe do
begin
Elemento:= TLCElementoSintaxe(item);
lbElementosSintaxe.AddItem(Elemento.Description , Elemento);
end;
// Selecionar o primeiro item da lista
lbElementosSintaxe.ItemIndex := 0;
lbElementosSintaxe.Tag := 0;
UpdateDisplayElemento(TLCElementoSintaxe(lbElementosSintaxe.Items.Objects[0]));
// Aba Niveis de identação
lbNiveisIdentacao.Clear;
lbNiveisIdentacao.Tag := -1;
for item in FrmMain.EditorSettings.Editor.NiveisIdentacao do
begin
Nivel := TLCNiveisIdentacaoConfig(item);
lbNiveisIdentacao.AddItem(Nivel.Description , Nivel);
end;
// Selecionar o primeiro item da lista
lbNiveisIdentacao.ItemIndex := 0;
lbNiveisIdentacao.Tag := 0;
UpdateDisplayNivelIdentacao(TLCNiveisIdentacaoConfig(lbNiveisIdentacao.Items.Objects[0]));
end;
procedure TFSettingsEditor.lbArqExcClick(Sender : TObject);
begin
fnArqExc.FileName := lbArqExc.GetSelectedText;
end;
procedure TFSettingsEditor.lbElementosSintaxeSelectionChange(Sender : TObject; User : boolean);
var
i:Integer;
begin
if lbElementosSintaxe.Tag <> -1 then
begin
TLCElementoSintaxe(lbElementosSintaxe.Items.Objects[lbElementosSintaxe.Tag]).DefaultValues := chkDefault.checked;
TLCElementoSintaxe(lbElementosSintaxe.Items.Objects[lbElementosSintaxe.Tag]).Atributos.Background := colBackCol.ButtonColor;
TLCElementoSintaxe(lbElementosSintaxe.Items.Objects[lbElementosSintaxe.Tag]).Atributos.Foreground := colTextCol.ButtonColor;
TLCElementoSintaxe(lbElementosSintaxe.Items.Objects[lbElementosSintaxe.Tag]).Atributos.Style := [];
if chkBold.Checked then
begin
TLCElementoSintaxe(lbElementosSintaxe.Items.Objects[lbElementosSintaxe.Tag]).Atributos.Style :=
TLCElementoSintaxe(lbElementosSintaxe.Items.Objects[lbElementosSintaxe.Tag]).Atributos.Style + [fsBold];
end;
if chkItalic.Checked then
begin
TLCElementoSintaxe(lbElementosSintaxe.Items.Objects[lbElementosSintaxe.Tag]).Atributos.Style :=
TLCElementoSintaxe(lbElementosSintaxe.Items.Objects[lbElementosSintaxe.Tag]).Atributos.Style + [fsItalic];
end;
if chkUnder.Checked then
begin
TLCElementoSintaxe(lbElementosSintaxe.Items.Objects[lbElementosSintaxe.Tag]).Atributos.Style :=
TLCElementoSintaxe(lbElementosSintaxe.Items.Objects[lbElementosSintaxe.Tag]).Atributos.Style + [fsUnderline];
end;
end;
lbElementosSintaxe.Tag := -1;
colBackCol.Color := clNone;
colTextCol.Color := clNone;
if lbElementosSintaxe.SelCount > 0 then
begin
for i:= 0 to lbElementosSintaxe.Count - 1 do
begin
if lbElementosSintaxe.Selected[i] = true then
begin
lbElementosSintaxe.Tag := i;
UpdateDisplayElemento(TLCElementoSintaxe(lbElementosSintaxe.Items.Objects[i]));
end;
end;
end;
end;
procedure TFSettingsEditor.dePastaRootModuloChange(Sender : TObject);
begin
fnArqExc.InitialDir := dePastaRootModulo.Directory;
end;
procedure TFSettingsEditor.bbAddArqExcClick(Sender : TObject);
begin
if (fnArqExc.FileName = '') then
begin
showmessage(rsFileNotSet);
exit;
end;
if (FileExists(fnArqExc.FileName) = false) then
begin
showmessage(format(rsFileNotFound,[fnArqExc.FileName]));
exit;
end;
// Verificar se o arquivo já foi incluído
if lbArqExc.Items.IndexOf(fnArqExc.FileName) < 0 then
begin
lbArqExc.Items.Add(fnArqExc.FileName);
end;
fnArqExc.FileName := '';
end;
procedure TFSettingsEditor.bbRemoverArqExcClick(Sender : TObject);
begin
lbArqExc.DeleteSelected();
end;
procedure TFSettingsEditor.chkDefaultChange(Sender : TObject);
var
Elemento: TLCElementoSintaxe;
oPadrao: TSynLCHighlighterSettings;
begin
if chkDefault.checked = true then
begin
oPadrao:= TSynLCHighlighterSettings.Create;
Elemento := TLCElementoSintaxe.Create(nil);
try
Elemento.DefaultValues := true;
Elemento.Kind := TLCElementoSintaxe(lbElementosSintaxe.Items.Objects[lbElementosSintaxe.Tag]).Kind;
Elemento.Atributos.Assign(FrmMain.GetAttributeSettingsDefault(oPadrao, Elemento.Kind));
UpdateDisplayElemento(Elemento);
finally
FreeAndNil(Elemento);
FreeAndNil(oPadrao);
end;
end;
//colBackCol.Enabled := not chkDefault.checked;
//colTextCol.Enabled := not chkDefault.checked;
//chkBold.Enabled := not chkDefault.checked;
//chkItalic.Enabled := not chkDefault.checked;
//chkUnder.Enabled := not chkDefault.checked;
end;
procedure TFSettingsEditor.chkDefaultNivelChange(Sender: TObject);
var
oNivel: TLCNiveisIdentacaoConfig;
begin
if chkDefaultNivel.checked = true then
begin
if lbNiveisIdentacao.Tag <> -1 then
begin
oNivel := TLCNiveisIdentacaoConfig(lbNiveisIdentacao.Items.Objects[lbNiveisIdentacao.Tag]);
oNivel.DefaultValues := True;
oNivel.Atributos.Foreground := FrmMain.EditorSettings.Editor.GetCorPadraoNivelIdentacao(oNivel.Nivel);
UpdateDisplayNivelIdentacao(oNivel);
end;
end;
end;
procedure TFSettingsEditor.lbModulosSelectionChange(Sender : TObject; User : boolean);
var
i:Integer;
begin
if lbModulos.Tag <> -1 then
begin
TModuloVetorh(lbModulos.Items.Objects[lbModulos.Tag]).PastaBase := dePastaRootModulo.Directory;
TModuloVetorh(lbModulos.Items.Objects[lbModulos.Tag]).ArquivosExcluidos.Assign(lbArqExc.Items);
end;
lbModulos.Tag := -1;
dePastaRootModulo.Directory := '';
lbArqExc.Items.clear;
fnArqExc.FileName := '';
if lbModulos.SelCount > 0 then
begin
for i:= 0 to lbModulos.Count - 1 do
begin
if lbModulos.Selected[i] = true then
begin
lbModulos.Tag := i;
dePastaRootModulo.Directory := TModuloVetorh(lbModulos.Items.Objects[i]).PastaBase;
lbArqExc.Items.Assign(TModuloVetorh(lbModulos.Items.Objects[i]).ArquivosExcluidos);
end;
end;
end;
end;
procedure TFSettingsEditor.lbNiveisIdentacaoSelectionChange(Sender : TObject; User : boolean);
var
i:Integer;
begin
if lbNiveisIdentacao.Tag <> -1 then
begin
TLCNiveisIdentacaoConfig(lbNiveisIdentacao.Items.Objects[lbNiveisIdentacao.Tag]).DefaultValues := chkDefaultNivel.checked;
TLCNiveisIdentacaoConfig(lbNiveisIdentacao.Items.Objects[lbNiveisIdentacao.Tag]).Atributos.Foreground := CorLinhaNivel.ButtonColor;
end;
lbNiveisIdentacao.Tag := -1;
CorLinhaNivel.Color := clNone;
if lbNiveisIdentacao.SelCount > 0 then
begin
for i:= 0 to lbNiveisIdentacao.Count - 1 do
begin
if lbNiveisIdentacao.Selected[i] = true then
begin
lbNiveisIdentacao.Tag := i;
UpdateDisplayNivelIdentacao(TLCNiveisIdentacaoConfig(lbNiveisIdentacao.Items.Objects[i]));
end;
end;
end;
end;
initialization
end.
|
unit HintWindowEx;
interface
uses
System.Classes, Vcl.Controls, Vcl.ExtCtrls, Vcl.Forms, System.Types;
type
THintWindowEx = class(THintWindow)
private
FShowTimer: TTimer;
FHideTimer: TTimer;
FHint: string;
procedure HideTime(Sender: TObject);
procedure ShowTime(Sender: TObject);
public
constructor Create(AOwner: TComponent); override;
procedure DoActivateHint(const AHint: string);
destructor Destroy; override;
end;
implementation
uses System.sysutils;
{ THintWindowEx }
constructor THintWindowEx.Create(AOwner: TComponent);
begin
inherited;
// Canvas.Font.Size := 14;
FShowTimer := TTimer.Create(self);
FShowTimer.Interval := Application.HintPause;
FHideTimer := TTimer.Create(self);
FHideTimer.Interval := Application.HintHidePause;
end;
destructor THintWindowEx.Destroy;
begin
FHideTimer.OnTimer := nil;
FShowTimer.OnTimer := nil;
self.ReleaseHandle;
inherited;
end;
procedure THintWindowEx.DoActivateHint(const AHint: string);
begin
// Отменяем показ предыдущего хинта
HideTime(self);
if (AHint.IsEmpty) then
begin
FShowTimer.OnTimer := nil;
FHideTimer.OnTimer := nil;
Exit;
end;
FHint := AHint;
FShowTimer.OnTimer := ShowTime;
FHideTimer.OnTimer := HideTime;
end;
procedure THintWindowEx.HideTime(Sender: TObject);
begin
// hide (destroy) hint window
self.ReleaseHandle;
FHideTimer.OnTimer := nil;
end;
procedure THintWindowEx.ShowTime(Sender: TObject);
var
R: TRect;
wdth: integer;
hght: integer;
n: Integer;
begin
FShowTimer.OnTimer := nil;
if FHint.IsEmpty then
begin
FHideTimer.OnTimer := nil;
Exit;
end;
// position and resize
wdth := Canvas.TextWidth(FHint);
hght := Canvas.TextHeight(FHint);
if wdth > 600 then
begin
n := wdth div 600;
if frac(wdth / 600) > 0 then
Inc(n);
hght := hght * n;
wdth := 600;
end;
R.Left := Mouse.CursorPos.X + 16;
R.Top := Mouse.CursorPos.Y + 16;
R.Right := R.Left + wdth + 6;
R.Bottom := R.Top + hght + 4;
ActivateHint(R, FHint);
end;
end.
|
unit crc16_1;
interface
implementation
type
Word = UInt16;
Byte = UInt8;
PByte = ^UInt8;
TCRC16PolyTable = array [0..255] of Word;
PCRC16PolyTable = ^TCRC16PolyTable;
const ModBusPolyArr: TCRC16PolyTable = (
$0000, $C0C1, $C181, $0140, $C301, $03C0, $0280, $C241,
$C601, $06C0, $0780, $C741, $0500, $C5C1, $C481, $0440,
$CC01, $0CC0, $0D80, $CD41, $0F00, $CFC1, $CE81, $0E40,
$0A00, $CAC1, $CB81, $0B40, $C901, $09C0, $0880, $C841,
$D801, $18C0, $1980, $D941, $1B00, $DBC1, $DA81, $1A40,
$1E00, $DEC1, $DF81, $1F40, $DD01, $1DC0, $1C80, $DC41,
$1400, $D4C1, $D581, $1540, $D701, $17C0, $1680, $D641,
$D201, $12C0, $1380, $D341, $1100, $D1C1, $D081, $1040,
$F001, $30C0, $3180, $F141, $3300, $F3C1, $F281, $3240,
$3600, $F6C1, $F781, $3740, $F501, $35C0, $3480, $F441,
$3C00, $FCC1, $FD81, $3D40, $FF01, $3FC0, $3E80, $FE41,
$FA01, $3AC0, $3B80, $FB41, $3900, $F9C1, $F881, $3840,
$2800, $E8C1, $E981, $2940, $EB01, $2BC0, $2A80, $EA41,
$EE01, $2EC0, $2F80, $EF41, $2D00, $EDC1, $EC81, $2C40,
$E401, $24C0, $2580, $E541, $2700, $E7C1, $E681, $2640,
$2200, $E2C1, $E381, $2340, $E101, $21C0, $2080, $E041,
$A001, $60C0, $6180, $A141, $6300, $A3C1, $A281, $6240,
$6600, $A6C1, $A781, $6740, $A501, $65C0, $6480, $A441,
$6C00, $ACC1, $AD81, $6D40, $AF01, $6FC0, $6E80, $AE41,
$AA01, $6AC0, $6B80, $AB41, $6900, $A9C1, $A881, $6840,
$7800, $B8C1, $B981, $7940, $BB01, $7BC0, $7A80, $BA41,
$BE01, $7EC0, $7F80, $BF41, $7D00, $BDC1, $BC81, $7C40,
$B401, $74C0, $7580, $B541, $7700, $B7C1, $B681, $7640,
$7200, $B2C1, $B381, $7340, $B101, $71C0, $7080, $B041,
$5000, $90C1, $9181, $5140, $9301, $53C0, $5280, $9241,
$9601, $56C0, $5780, $9741, $5500, $95C1, $9481, $5440,
$9C01, $5CC0, $5D80, $9D41, $5F00, $9FC1, $9E81, $5E40,
$5A00, $9AC1, $9B81, $5B40, $9901, $59C0, $5880, $9841,
$8801, $48C0, $4980, $8941, $4B00, $8BC1, $8A81, $4A40,
$4E00, $8EC1, $8F81, $4F40, $8D01, $4DC0, $4C80, $8C41,
$4400, $84C1, $8581, $4540, $8701, $47C0, $4680, $8641,
$8201, $42C0, $4380, $8341, $4100, $81C1, $8081, $4040);
function _crc16(aTable: PCRC16PolyTable; BaseCRC: word; Data: PByte; Length: word): word; overload;
var
Idx: Word;
begin
Result := BaseCRC;
while (Length > 0) do begin
Idx := (Result shr 8) xor Data^;
Result := (Result shl 8) xor aTable[Idx];
Dec(Length);
Inc(Data);
end;
end;
function Crc16(BaseCRC: word; Data: PByte; Length: word): word; overload;
begin
Result := _crc16(@ModBusPolyArr, BaseCrc, Data, Length);
end;
function Crc16(Data: PByte; Length: word): word; overload;
begin
Result := Crc16($FFFF, Data, Length);
end;
var Data: array [16] of Int32 = ($00, $01, $02, $03, $04, $05, $06, $07, $08, $09, $0A, $0B, $0C, $0D, $0E, $0F);
CRC: Word;
procedure Test;
begin
CRC := Crc16(PByte(@Data), sizeof(Data));
end;
initialization
Test();
finalization
Assert(CRC = 63681);
end. |
unit v_msgbody_stringgrid;
{==============================================================================
UnitName = v_msgbody_stringgrid
UnitVersion = 0.91
UnitDesc = StringGrid specialized in body parameters handling
UnitCopyright = GPL by Clinique / xPL Project
==============================================================================
}
{$mode objfpc}{$H+}
interface
uses Classes, SysUtils, LCLProc, LCLType, LCLIntf,
FPCanvas, Controls, GraphType, Graphics, Forms, MStringGrid,
StdCtrls, LResources, Buttons, Grids, Menus, u_xpl_body;
type
{ TBodyMessageGrid }
TBodyMessageGrid = class(TMStringGrid)
private
fComboEdit : TComboBox;
fPossibleKey : TStringList;
// fPossibleVal : TStringList;
fReferencedBody : TxPLBody;
// fModeMenu : TMenuItem;
procedure AfterRowChanged(Sender: TObject; ARow: Integer);
procedure fComboEditEditingDone(Sender: TObject);
function GetIsValid: boolean;
public
constructor create(aOwner : TComponent); override;
destructor destroy; override;
procedure Clear;
procedure SelectEditor; override;
procedure EditingDone; override;
procedure NewLine(aKey, aValue : string);
procedure NewLine(aLine : string);
procedure Assign(aBody : TxPLBody); overload;
procedure CopyTo(aBody : TxPLBody);
function GetKey(aRow : integer) : string;
function GetValue(aRow : integer) : string;
function GetKeyValuePair(aRow : integer) : string;
property PossibleKeys : TStringList read FPossibleKey;
// property PossibleVals : TStringList read FPossibleVal;
property IsValid : boolean read GetIsValid;
end;
procedure Register;
implementation
const
// K_sg_LAB_COL = 1;
K_sg_KEY_COL = 0;
K_sg_VAL_COL = 2;
// K_sg_VLAB_COL = 5;
{resourcestring
sExpertMode = '&Expert Mode';
sBasicMode = '&Basic Mode';}
procedure Register;
begin
RegisterComponents('xPL Components',[TBodyMessageGrid]);
end;
{ TBodyMessageGrid }
constructor TBodyMessageGrid.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
// fModeMenu := AppendMenu(sBasicMode,@ModeToggle);
Options := Options + [goColSizing, goEditing,goTabs];
Options := Options - [goVertLine, goRangeSelect];
OnRowsChanged := @AfterRowChanged;
Width := 300;
Clear;
fComboEdit := TCombobox.Create(self);
fComboEdit.OnEditingDone := @fComboEditEditingDone;
fComboEdit.Visible := false;
fPossibleKey := TStringList.Create;
fPossibleKey.Sorted := true;
fPossibleKey.Duplicates := dupIgnore;
// fPossibleVal := TStringList.Create;
// fPossibleVal.Sorted := true;
// fPossibleVal.Duplicates := dupIgnore;
end;
destructor TBodyMessageGrid.Destroy;
begin
// fModeMenu.Free;
fPossibleKey.Free;
// fPossibleVal.Free;
fComboEdit.Free;
inherited;
end;
procedure TBodyMessageGrid.AfterRowChanged(Sender: TObject; ARow: Integer);
begin
if aRow = 0 then exit;
if Cells[K_sg_KEY_COL+1,aRow]<>'=' then Cells[K_sg_KEY_COL+1,aRow]:='=';
end;
procedure TBodyMessageGrid.fComboEditEditingDone(Sender: TObject);
//var //sCurrentKey, sCurrentVal : string;
//sConditionalField,sVisCondition : string;
//field, condition : string;
//bVisible : boolean;
//i,j : integer;
begin
if Cells[Col,Row]<>fComboEdit.Text then begin
Cells[Col,Row]:=fComboEdit.Text;
//***
if not assigned(fReferencedBody) then exit;
//sCurrentKey := Cells[K_sg_KEY_COL,Row];
//sCurrentVal := Cells[K_sg_VAL_COL,Row];
// Search for other fields having a visibility condition upon current key value
// for i:=0 to fReferencedBody.ItemCount-1 do begin
// sVisCondition := fReferencedBody.VisCond[i];
// sConditionalField := fReferencedBody.Keys[i];
{ if sVisCondition <> '' then begin // is there a visibility condition ?
field := '';
condition := '';
StrSplitAtChar(sVisCondition,'=',field,condition);
if field=sCurrentKey then begin // if yes, doest it apply on the value of current key
bVisible := True;
with TRegExpr.Create do try
Expression := condition;
bVisible := Exec(sCurrentVal);
for j:=1 to RowCount-1 do begin
if Cells[K_sg_KEY_COL,j]= sConditionalField then begin
if bVisible then RowHeights[j]:=15 else RowHeights[j]:=0;
end;
end;
finally free;
end;
end;
end;}
// end;
//***
end;
end;
function TBodyMessageGrid.GetIsValid: boolean;
begin
result := True; // no control on this for the moment / Todo : control that
end;
procedure TBodyMessageGrid.Clear;
begin
inherited Clear;
Clean;
RowCount := 2;
// ColCount := 6;
ColCount := 3;
FixedRows := 1;
// FixedCols := 1;
FixedCols := 0;
// Cells[0,0] := '*';
// Cells[K_sg_LAB_COL,0] := 'Labels';
Cells[K_sg_KEY_COL,0] := 'Keys';
Cells[K_sg_VAL_COL,0] := 'Values';
// Cells[K_sg_VLAB_COL,0] := 'Desc';
ColWidths[0] := 15;
// ColWidths[K_sg_LAB_COL] := 0;
ColWidths[K_sg_KEY_COL] := 150;
ColWidths[K_sg_KEY_COL+1]:= 15;
ColWidths[K_sg_VAL_COL] := 150;
// ColWidths[K_sg_VLAB_COL] := 105;
NewLine('','');
end;
procedure TBodyMessageGrid.NewLine(aKey, aValue : string);
var i : integer;
begin
i := RowCount-1;
if ( (i=0) or (length( Cells[K_sg_KEY_COL,i] + Cells[K_sg_VAL_COL,i]) > 0) ) then begin
inc(i);
RowCount := i+1;
end;
Cells[K_sg_KEY_COL ,i] := aKey;
Cells[K_sg_KEY_COL+1,i] := '=';
Cells[K_sg_VAL_COL ,i] := aValue;
end;
procedure TBodyMessageGrid.NewLine(aLine : string);
var sl : TStringList;
begin
sl := TStringList.Create;
sl.Delimiter := '=';
sl.DelimitedText := aLine;
NewLine(sl[0],sl[1]);
sl.Free;
end;
procedure TBodyMessageGrid.Assign(aBody: TxPLBody);
var i : integer;
begin
Clear;
fReferencedBody := aBody;
for i:=0 to Pred(aBody.ItemCount) do
NewLine(aBody.Keys[i],aBody.Values[i]);
end;
procedure TBodyMessageGrid.CopyTo(aBody: TxPLBody);
var i : integer;
ch : string;
begin
for i:=1 to RowCount - 1 do begin
ch := GetKeyValuePair(i);
if ch<>'' then aBody.AddKeyValue(ch);
end;
end;
function TBodyMessageGrid.GetKey(aRow: integer): string;
begin
result := Cells[K_sg_KEY_COL,aRow];
end;
function TBodyMessageGrid.GetValue(aRow: integer): string;
begin
result := Cells[K_sg_VAL_COL,aRow];
end;
function TBodyMessageGrid.GetKeyValuePair(aRow: integer): string;
begin
result := GetKey(aRow);
if result<>'' then result := result + '=' + GetValue(aRow);
end;
procedure TBodyMessageGrid.SelectEditor;
begin
inherited;
if assigned(fReferencedBody) then begin
{ if fReferencedBody.ItemCount > Row-1 then begin
// fPossibleVal.Delimiter:= ',';
// fPossibleVal.QuoteChar:= '|';
// fPossibleVal.DelimitedText:= fReferencedBody.OpLabels[Row-1];
end else begin
fPossibleVal.Clear;
end;}
end;
if not ((Col = K_sg_KEY_COL) or (Col = K_sg_VAL_COL)) then Editor := nil;
if (Col = K_sg_VAL_COL) then begin
{ if Assigned(fPossibleVal) then begin
if fPossibleVal.Count>0 then begin
fComboEdit.Items := fPossibleVal;
fComboEdit.BoundsRect := CellRect(Col,Row);
Editor := fComboEdit;
fComboEdit.Text := Cells[Col,Row];
end;
end;}
end;
if (Col = K_sg_KEY_COL) then begin
if Assigned(fPossibleKEY) then begin
if fPossibleKEY.Count>0 then begin
fComboEdit.Items := fPossibleKEY;
fComboEdit.BoundsRect := CellRect(Col,Row);
Editor := fComboEdit;
fComboEdit.Text := Cells[Col,Row];
end;
end;
end;
end;
procedure TBodyMessageGrid.EditingDone;
begin
inherited EditingDone;
end;
{procedure TBodyMessageGrid.ModeToggle(Sender: TObject);
var i : integer;
begin
if fModeMenu.Caption = sExpertMode then begin
fModeMenu.Caption := sBasicMode
end else begin
fModeMenu.Caption := sExpertMode
end;
i := ColWidths[K_sg_KEY_COL];
ColWidths[K_sg_KEY_COL]:= ColWidths[K_sg_LAB_COL];
ColWidths[K_sg_LAB_COL]:= i;
if ColWidths[K_sg_KEY_COL]>0 then ColWidths[K_sg_KEY_COL+1] := 15
else ColWidths[K_sg_KEY_COL+1] := 0;
end;}
end.
|
Unit SEANEMS;
{ **************************** EMM Functions ****************************
Fehlercodes
$00 = Kein Fehler
$80 = Fehler in der Software-Schnittstelle
$81 = Fehler in der EMS-Hardware
$83 = ungltige Handle-Nummer
$84 = ungltige Funktionsnummer
$85 = Alle Handle schon belegt
$87 = zu wenig freie Seiten
$88 = ungltige Seitenanzahl
$8A = ungltige Seitennummer
$8C = Mapping kann nicht gesichert werden
$8D = Mapping ist bereits gesichert
$8E = Mapping ist nicht gesichert gewesen }
InterFace
Uses Dos;
Var EMMResult : Word;
Function HexStr ( Number : Word) : String;
Function EMMInstalled : Boolean;
Function GetEMMStatus : Word;
Function GetEMMFrame : Word;
Function GetAllocatedHandles : Word;
Function GetAllocatedPages ( Handle : Word ) : Word;
Function Message ( Result : Word ) : String;
Procedure GetAvailablePages ( Var AvailablePages,TotalPages : Word );
Procedure AllocatePages ( Pages : Word; Var Handle : Word );
Procedure ReleasePages ( Handle : Word );
Procedure MapPages ( Handle,LogicalPage,PhysicalPage : Word );
Procedure EMMVersion ( Var High,Low : Word );
Implementation
Function HexChr ( Number : Word ) : Char;
Begin
If Number<10 Then HexChr:=Char(Number+48) Else
HexChr:=Char(Number+55);
End;
Function HexStr ( Number : Word ) : String;
Var S : String;
Begin
S:='';
S:=HexChr((Number Shr 1) Div 2048);
Number:=(((Number Shr 1) Mod 2048) Shl 1)+ (Number And 1) ;
S:=S+HexChr(Number div 256);
Number:=Number Mod 256;
S:=S+HexChr(Number div 16);
Number:=Number Mod 16;
S:=S+HexChr(Number);
HexStr:=S+'h';
End;
Function GetBit(B : Byte;Nummer : Byte) : Boolean;
Begin
GetBit:=Odd(B Shr Nummer);
End;
Procedure SetBit(Var B : Byte;Nummer : Byte);
Begin
B:=B Or 1 Shl Nummer;
End;
Procedure ClearBit(Var B : Byte;Nummer : Byte);
Begin
If GetBit(B,Nummer) Then Dec(B,1 Shl Nummer);
End;
Function HighBCDToDec(BCD : Byte) : Byte;
Var I : Integer;
B : Byte;
Begin
B:=0;
For I:=4 To 7 Do
Begin;
If GetBit(BCD,I) Then
Begin;
Case I Of
4: B:=B+1;
5: B:=B+2;
6: B:=B+4;
7: B:=B+8;
End;
End;
End;
HighBCDToDec:=B;
End;
Function LowBCDToDec(BCD : Byte) : Byte;
Var I : Integer;
B : Byte;
Begin
B:=0;
For I:=0 To 3 Do
Begin;
If GetBit(BCD,I) Then
Begin;
Case I Of
0: B:=B+1;
1: B:=B+2;
2: B:=B+4;
3: B:=B+8;
End;
End;
End;
LowBCDToDec:=B;
End;
Function EMMInstalled : Boolean;
Var F : File;
Begin
{$I-}
Assign(F,'EMMXXXX0');
ReSet(F);
{$I+}
If IOResult=0 Then
Begin;
EMMInstalled:=True;
Close(F);
End Else EMMInstalled:=False;
End;
Function GetEMMStatus : Word;
Var R : Registers;
Begin
R.Ah:=$40;
Intr($67,R);
GetEMMStatus:=R.Ah;
End;
Function GetEMMFrame : Word;
Var R : Registers;
Begin
R.Ah:=$41;
Intr($67,R);
GetEMMFrame:=R.Bx;
EMMResult:=R.Ah;
End;
Procedure GetAvailablePages ( Var AvailablePages,TotalPages : Word );
Var R : Registers;
Begin
R.Ah:=$42;
Intr($67,R);
AvailablePages:=R.Bx;
TotalPages:=R.Dx;
EMMResult:=R.Ah;
End;
Procedure AllocatePages ( Pages : Word; Var Handle : Word );
Var R : Registers;
Begin
R.Ah:=$43;
R.Bx:=Pages;
Intr($67,R);
Handle:=R.Dx;
EMMResult:=R.Ah;
End;
Procedure ReleasePages ( Handle : Word );
Var R : Registers;
Begin
R.Ah:=$45;
R.Dx:=Handle;
Intr($67,R);
EMMResult:=R.Ah;
End;
Procedure MapPages ( Handle,LogicalPage,PhysicalPage : Word );
Var R : Registers;
Begin
R.Ah:=$44;
R.Al:=PhysicalPage;
R.Bx:=LogicalPage;
R.Dx:=Handle;
Intr($67,R);
EMMResult:=R.Ah;
End;
Procedure EMMVersion ( Var High,Low : Word );
Var R : Registers;
B : Byte;
Begin
R.Ah:=$46;
Intr($67,R);
High:=HighBCDToDec(R.Al);
Low:=LowBCDToDec(R.Al);
EMMResult:=R.Ah;
End;
Function GetAllocatedHandles : Word;
Var R : Registers;
Begin
R.Ah:=$4B;
Intr($67,R);
GetAllocatedHandles:=R.Bx;
EMMResult:=R.Ah;
End;
Function GetAllocatedPages ( Handle : Word ) : Word;
Var R : Registers;
Begin
R.Ah:=$4C;
R.Dx:=Handle;
Intr($67,R);
GetAllocatedPages:=R.Bx;
EMMResult:=R.Ah;
End;
Function Message ( Result : Word ) : String;
Begin
Case Result Of
$00: Message:='no error';
$80: Message:='error with your EMM';
$81: Message:='error with your EMS-Hardware';
$83: Message:='invalid handle';
$84: Message:='invalid function';
$85: Message:='no free handle';
$87: Message:='no free pages';
$88: Message:='invalid page amount';
$8A: Message:='invalid page nr';
$8C: Message:='unable to save mapping';
$8D: Message:='mapping already saved';
$8E: Message:='mapping has not been saved';
Else Message:='unknown error';
End;
End;
Begin
End.
|
{ ***************************************************************************
Copyright (c) 2016-2020 Kike Pérez
Unit : Quick.DAO.Engine.SQLite3
Description : DAODatabase SQLite3 Provider
Author : Kike Pérez
Version : 1.0
Created : 06/07/2019
Modified : 14/04/2020
This file is part of QuickDAO: https://github.com/exilon/QuickDAO
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.DAO.Engine.SQLite3;
{$i QuickDAO.inc}
interface
uses
Classes,
SysUtils,
SQLite3,
SQLite3Wrap,
Quick.Commons,
Quick.DAO,
Quick.DAO.Database,
Quick.DAO.Query;
type
TDAODataBaseSQLite3 = class(TDAODatabase)
private
fDataBase : TSQLite3Database;
fInternalQuery : TSQLite3Statement;
protected
function CreateConnectionString: string; override;
procedure OpenSQLQuery(const aQueryText: string); override;
procedure ExecuteSQLQuery(const aQueryText: string); override;
function ExistsTable(aModel : TDAOModel) : Boolean; override;
function ExistsColumn(aModel: TDAOModel; const aFieldName: string): Boolean; override;
function GetDBFieldIndex(const aFieldName : string) : Integer;
public
constructor Create; override;
constructor CreateFromConnection(aConnection: TSQLite3Database; aOwnsConnection : Boolean);
destructor Destroy; override;
function CreateQuery(aModel : TDAOModel) : IDAOQuery<TDAORecord>; override;
function Connect : Boolean; override;
procedure Disconnect; override;
function IsConnected : Boolean; override;
function From<T : class, constructor> : IDAOLinqQuery<T>;
function Clone : TDAODatabase; override;
end;
TDAOQuerySQLite3<T : class, constructor> = class(TDAOQuery<T>)
private
fConnection : TDBConnectionSettings;
fQuery : TSQLite3Statement;
protected
function GetCurrent : T; override;
function MoveNext : Boolean; override;
function GetFieldValue(const aName : string) : Variant; override;
function OpenQuery(const aQuery : string) : Integer; override;
function ExecuteQuery(const aQuery : string) : Boolean; override;
function GetDBFieldIndex(const aFieldName : string) : Integer;
public
constructor Create(aDAODataBase : TDAODataBase; aModel : TDAOModel; aQueryGenerator : IDAOQueryGenerator); override;
destructor Destroy; override;
function CountResults : Integer; override;
function Eof : Boolean; override;
end;
implementation
{ TDAODataBaseSQLite3 }
constructor TDAODataBaseSQLite3.Create;
begin
inherited;
fDataBase := TSQLite3Database.Create;
end;
constructor TDAODataBaseSQLite3.CreateFromConnection(aConnection: TSQLite3Database; aOwnsConnection: Boolean);
begin
Create;
if OwnsConnection then fDatabase.Free;
OwnsConnection := aOwnsConnection;
fDatabase := aConnection;
end;
destructor TDAODataBaseSQLite3.Destroy;
begin
if Assigned(fInternalQuery) then fInternalQuery.Free;
if Assigned(fDataBase) then
begin
fDataBase.Close;
if OwnsConnection then fDataBase.Free;
end;
inherited;
end;
function TDAODataBaseSQLite3.Clone: TDAODatabase;
begin
Result := TDAODataBaseSQLite3.CreateFromConnection(fDataBase,False);
Result.Connection.Free;
Result.Connection := Connection.Clone;
end;
function TDAODataBaseSQLite3.Connect: Boolean;
begin
//creates connection string based on parameters of connection property
inherited;
fDataBase.Open(Connection.Database);
Result := IsConnected;
fInternalQuery := TSQLite3Statement.Create(fDataBase,'');
CreateTables;
CreateIndexes;
end;
function TDAODataBaseSQLite3.CreateConnectionString: string;
begin
//nothing to do
end;
function TDAODataBaseSQLite3.CreateQuery(aModel : TDAOModel) : IDAOQuery<TDAORecord>;
begin
Result := TDAOQuerySQLite3<TDAORecord>.Create(Self,aModel,QueryGenerator);
end;
function TDAODataBaseSQLite3.GetDBFieldIndex(const aFieldName: string): Integer;
var
i : Integer;
begin
Result := -1;
for i := 0 to fInternalQuery.ColumnCount - 1 do
begin
if CompareText(fInternalQuery.ColumnName(i),aFieldName) = 0 then Exit(i);
end;
end;
procedure TDAODataBaseSQLite3.Disconnect;
begin
inherited;
fDataBase.Close;
end;
function TDAODataBaseSQLite3.IsConnected: Boolean;
begin
Result := True;// fDataBase.Connected;
end;
procedure TDAODataBaseSQLite3.OpenSQLQuery(const aQueryText: string);
begin
fInternalQuery := fDataBase.Prepare(aQueryText);
end;
procedure TDAODataBaseSQLite3.ExecuteSQLQuery(const aQueryText: string);
begin
fDataBase.Execute(aQueryText);
end;
function TDAODataBaseSQLite3.ExistsColumn(aModel: TDAOModel; const aFieldName: string): Boolean;
begin
Result := False;
OpenSQLQuery(QueryGenerator.ExistsColumn(aModel,aFieldName));
while fInternalQuery.Step = SQLITE_ROW do
begin
if CompareText(fInternalQuery.ColumnText(GetDBFieldIndex('name')),aFieldName) = 0 then
begin
Result := True;
Break;
end;
end;
fInternalQuery.Reset;
end;
function TDAODataBaseSQLite3.ExistsTable(aModel: TDAOModel): Boolean;
begin
Result := False;
OpenSQLQuery(QueryGenerator.ExistsTable(aModel));
while fInternalQuery.Step = SQLITE_ROW do
begin
if CompareText(fInternalQuery.ColumnText(GetDBFieldIndex('name')),aModel.TableName) = 0 then
begin
Result := True;
Break;
end;
end;
fInternalQuery.Reset;
end;
function TDAODataBaseSQLite3.From<T>: IDAOLinqQuery<T>;
var
daoclass : TDAORecordclass;
begin
daoclass := TDAORecordClass(Pointer(T));
Result := TDAOQuerySQLite3<T>.Create(Self,Models.Get(daoclass),QueryGenerator);
end;
{ TDAOQuerySQLite3<T> }
constructor TDAOQuerySQLite3<T>.Create(aDAODataBase : TDAODataBase; aModel : TDAOModel; aQueryGenerator : IDAOQueryGenerator);
begin
inherited;
fQuery := TSQLite3Statement.Create(TDAODataBaseSQLite3(aDAODataBase).fDataBase,'');
fConnection := aDAODataBase.Connection;
end;
destructor TDAOQuerySQLite3<T>.Destroy;
begin
//if Assigned(fQuery) then fQuery.Free;
inherited;
end;
function TDAOQuerySQLite3<T>.Eof: Boolean;
begin
Result := False;// fQuery.Eof;
end;
function TDAOQuerySQLite3<T>.OpenQuery(const aQuery: string): Integer;
begin
fFirstIteration := True;
fQuery := TDAODataBaseSQLite3(fDAODataBase).fDataBase.Prepare(aQuery);
fHasResults := sqlite3_data_count(fQuery) > 0;
Result := sqlite3_data_count(fQuery);
end;
function TDAOQuerySQLite3<T>.ExecuteQuery(const aQuery: string): Boolean;
begin
TDAODataBaseSQLite3(fDAODataBase).fDataBase.Execute(aQuery);
fHasResults := False;
Result := True; //sqlite3_data_count(fQuery) > 0;
end;
function TDAOQuerySQLite3<T>.GetFieldValue(const aName: string): Variant;
var
idx : Integer;
begin
idx := GetDBFieldIndex(aName);
if idx = -1 then Exit;
case fQuery.ColumnType(idx) of
SQLITE_INTEGER : Result := fQuery.ColumnInt64(idx);
SQLITE_FLOAT : Result := fQuery.ColumnDouble(idx);
SQLITE_TEXT : Result := fQuery.ColumnText(idx);
SQLITE_NULL : Exit;
else Result := fQuery.ColumnText(idx);// raise Exception.Create('Unknow type');
end;
end;
function TDAOQuerySQLite3<T>.CountResults: Integer;
begin
Result := sqlite3_data_count(fQuery);
end;
function TDAOQuerySQLite3<T>.GetCurrent: T;
begin
Result := fModel.Table.Create as T;
Self.FillRecordFromDB(Result);
end;
function TDAOQuerySQLite3<T>.GetDBFieldIndex(const aFieldName: string): Integer;
var
i : Integer;
begin
Result := -1;
for i := 0 to fQuery.ColumnCount - 1 do
begin
if CompareText(fQuery.ColumnName(i),aFieldName) = 0 then Exit(i);
end;
end;
function TDAOQuerySQLite3<T>.MoveNext: Boolean;
begin
Result := fQuery.Step = SQLITE_ROW;
end;
end.
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf,
FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.SQLite,
FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs, FireDAC.VCLUI.Wait, Data.DB, FireDAC.Comp.Client, FireDAC.Stan.Param,
FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.Buttons,
FireDAC.Comp.UI, Vcl.ComCtrls;
type
TForm1 = class(TForm)
FDConnection1: TFDConnection;
FDQuery1: TFDQuery;
DataSource1: TDataSource;
DBGrid1: TDBGrid;
FDPhysSQLiteDriverLink1: TFDPhysSQLiteDriverLink;
FDGUIxWaitCursor1: TFDGUIxWaitCursor;
BitBtn1: TBitBtn;
Button1: TButton;
StatusBar1: TStatusBar;
Button2: TButton;
procedure FormCreate(Sender: TObject);
procedure BitBtn1Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
nbRecords: Integer;
{ Déclarations privées }
public
{ Déclarations publiques }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.BitBtn1Click(Sender: TObject);
begin
try
FDQuery1.Connection := FDConnection1;
FDQuery1.Active := False;
FDQuery1.Active := False;
FDQuery1.SQL.Clear;
FDQuery1.SQL.Add('select count(*) as NB from PARAMSQL');
FDQuery1.Open();
nbRecords := FDQuery1.FieldByName('NB').AsInteger;
StatusBar1.Panels[0].Text := 'Enregistrements:' + Integer.ToString(nbRecords);
FDQuery1.Active := False;
FDQuery1.SQL.Clear;
FDQuery1.SQL.Add('select * from PARAMSQL');
FDQuery1.Open();
Button1.Enabled := true;
Button2.Enabled := true;
except
on E: Exception do MessageDlg('Erreur sur requête' + E.Message, mtError, mbOKCancel, 0);
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
query: TFDQuery;
okTRansaction: Boolean;
i: Integer;
begin
okTRansaction := False;
try
query := TFDQuery.Create(nil);
try
query.Connection := FDConnection1;
query.Active := False;
FDConnection1.StartTransaction;
for i := nbRecords + 1 to nbRecords + 100000 do begin
query.SQL.Clear;
query.SQL.Add('insert into PARAMSQL(PARAMETRE, VALEUR)');
query.SQL.Add(' values("Param' + Integer.ToString(i) + '","Valeur' + Integer.ToString(i) + '")');
query.ExecSQL;
end;
FDConnection1.Commit;
okTRansaction := true;
except
on E: Exception do begin
MessageDlg('Erreur sur requête' + E.Message + ' : ' + query.SQL.Text, mtError, mbOKCancel, 0);
okTRansaction := False;
end;
end;
finally
FreeAndNil(query);
if not okTRansaction then FDConnection1.Rollback;
BitBtn1Click(Sender);
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
var
okTRansaction: Boolean;
query: TFDQuery;
begin
okTRansaction := False;
try
query := TFDQuery.Create(nil);
query.Connection := FDConnection1;
query.Active := False;
FDConnection1.StartTransaction;
query.SQL.Clear;
query.SQL.Add('delete from PARAMSQL');
query.ExecSQL;
FDConnection1.Commit;
okTRansaction := true;
finally
if assigned(query) then FreeAndNil(query);
if not okTRansaction then FDConnection1.Rollback;
BitBtn1Click(Sender);
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
FDPhysSQLiteDriverLink1.DriverID := 'SQLite';
FDConnection1.Connected := False;
FDConnection1.LoginPrompt := False;
FDConnection1.Params.DriverID := 'SQLite';
FDConnection1.Params.Database := 'C:\Opensource\SQLiteDatabaseBrowserPortable\Data\Axiodis.db';
FDConnection1.Connected := true;
DataSource1.DataSet := FDQuery1;
DBGrid1.DataSource := DataSource1;
end;
end.
|
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
unit frmMain;
interface
uses
Windows, Messages, Classes, Graphics, Forms, ExtCtrls, Menus, Controls,
SysUtils, Dialogs,
OpenGL;
type
TVector = record
x, y, z : GLfloat;
end;
TPatch = Array [0..24] of TVector;
type
TfrmGL = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
DC: HDC;
hrc: HGLRC;
AngX, AngY, AngZ : GLfloat;
procedure Init;
procedure init_surface;
procedure SetDCPixelFormat;
protected
procedure WMPaint(var Msg: TWMPaint); message WM_PAINT;
end;
const
ROZA = 1;
var
frmGL: TfrmGL;
implementation
{$R *.DFM}
{=======================================================================
Инициализация}
procedure TfrmGL.Init;
const
ambient : Array [0..3] of GLFloat = (0.2, 0.2, 0.2, 1.0);
position1 : Array [0..3] of GLFloat = (0.0, 2.0, -2.0, 0.0);
position2 : Array [0..3] of GLFloat = (0.0, 2.0, 5.0, 0.0);
mat_diffuse : Array [0..3] of GLFloat = (1.0, 0.0, 0.0, 1.0);
mat_specular : Array [0..3] of GLFloat = (1.0, 1.0, 1.0, 0.0);
mat_shininess : GLFloat = 2.0;
begin
glEnable(GL_DEPTH_TEST);
glEnable(GL_AUTO_NORMAL);
glEnable(GL_NORMALIZE);
// источник света
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_LIGHT1);
glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, 1);
glLightfv(GL_LIGHT0, GL_AMBIENT, @ambient);
glLightfv(GL_LIGHT0, GL_POSITION, @position1);
glLightfv(GL_LIGHT1, GL_POSITION, @position2);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, @mat_diffuse);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, @mat_specular);
glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, @mat_shininess);
glEnable (GL_COLOR_MATERIAL);
glClearColor (0.0, 0.75, 1.0, 1.0);
// поверхность
glEnable(GL_MAP2_VERTEX_3);
glMapGrid2f(20, 0.0, 1.0, 20, 0.0, 1.0);
init_surface;
end;
{=======================================================================
Инициализация контрольных точек поверхности}
procedure TfrmGL.Init_Surface;
var
f : TextFile;
i : Integer;
Model : TList;
wrkPatch : TPatch;
pwrkPatch : ^TPatch;
begin
Model := TList.Create;
AssignFile (f, 'Roza.txt');
ReSet (f);
While not eof (f) do begin
For i := 0 to 24 do
ReadLn (f, wrkPatch [i].x, wrkPatch [i].y, wrkPatch [i].z);
New (pwrkPatch);
pwrkPatch^ := wrkPatch;
Model.Add (pwrkPatch);
end;
CloseFile (f);
glNewList (ROZA, GL_COMPILE);
glPushMatrix;
glScalef (0.5, 0.5, 0.5);
For i := 0 to 11 do begin
glColor3f (1.0, 0.0, 0.0);
glMap2f(GL_MAP2_VERTEX_3, 0, 1, 3, 5, 0, 1, 15, 5, Model.Items[i]);
glEvalMesh2(GL_FILL, 0, 20, 0, 20);
end;
For i := 12 to Model.Count - 1 do begin
glColor3f (0.0, 1.0, 0.0);
glMap2f(GL_MAP2_VERTEX_3, 0, 1, 3, 5, 0, 1, 15, 5, Model.Items[i]);
glEvalMesh2(GL_FILL, 0, 20, 0, 20);
end;
glPopMatrix;
glEndList;
Model.Free;
end;
{=======================================================================
Перерисовка окна}
procedure TfrmGL.WMPaint(var Msg: TWMPaint);
var
ps : TPaintStruct;
begin
BeginPaint (Handle, ps);
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
glPushMatrix;
glRotatef(AngX, 1.0, 0.0, 0.0);
glRotatef(AngY, 0.0, 1.0, 0.0);
glRotatef(AngZ, 0.0, 0.0, 1.0);
glCallList (ROZA);
glPopMatrix;
SwapBuffers (DC);
EndPaint (Handle, ps);
end;
{=======================================================================
Изменение размеров окна}
procedure TfrmGL.FormResize(Sender: TObject);
begin
glViewport(0, 0, ClientWidth, ClientHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity;
gluPerspective (20.0, ClientWidth / ClientHeight, 1.0, 50.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity;
glTranslatef (0.0, 0.0, -18.0);
InvalidateRect(Handle, nil, False);
end;
{=======================================================================
Конец работы программы}
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
glDeleteLists (ROZA, 1);
wglMakeCurrent(0, 0);
wglDeleteContext(hrc);
ReleaseDC(Handle, DC);
DeleteDC (DC);
end;
{=======================================================================
Обработка нажатия клавиши}
procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
Case Key of
VK_ESCAPE : begin
Close;
Exit;
end;
VK_LEFT : AngY := AngY + 5;
VK_UP : AngZ := AngZ + 5;
VK_RIGHT : AngX := AngX + 5;
end;
InvalidateRect(Handle, nil, False);
end;
{=======================================================================
Создание окна}
procedure TfrmGL.FormCreate(Sender: TObject);
begin
DC := GetDC(Handle);
SetDCPixelFormat;
hrc := wglCreateContext(DC);
wglMakeCurrent(DC, hrc);
Init;
end;
{=======================================================================
Устанавливаем формат пикселей}
procedure TfrmGL.SetDCPixelFormat;
var
nPixelFormat: Integer;
pfd: TPixelFormatDescriptor;
begin
FillChar(pfd, SizeOf(pfd), 0);
pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or
PFD_DOUBLEBUFFER;
nPixelFormat := ChoosePixelFormat(DC, @pfd);
SetPixelFormat(DC, nPixelFormat, @pfd);
end;
end.
|
unit IM.Types;
{$IFDEF FPC}
{$mode delphi}
{$ENDIF}
interface
uses
Classes, SysUtils, Types;
type
TAppColors = record
Command, Desc, Example, Section, Key, Value,
Comment, Symbol: string;
procedure Init;
end;
TAppParams = record
Section: string; // -s, --section
Key: string; // -k, --key
NewKeyName: string; // -kn, --new-key-name
Value: string; // -v, --value
Comment: string; // -c, --comment
CommentPadding: integer; // -x
Silent: Boolean; // --silent
Encoding: TEncoding; // no option. TODO: add Encoding to options
Files: TStringDynArray; // the list of file names/masks
GithubUrl: string; // stores the GitHub repo URL
RecurseDepth: integer; // -rd, --recurse-depth
end;
var
AppParams: TAppParams;
AppColors: TAppColors;
implementation
procedure TAppColors.Init;
begin
Command := 'lightblue';
Desc := 'lightgray';
Example := 'white';
Section := 'lime';
Key := 'yellow';
Value := 'cyan';
Comment := 'fuchsia';
Symbol := 'darkgray';
end;
end.
|
unit Main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DB, Buttons, Grids, DBGrids, ToolWin, ComCtrls, MemDS, MemData,
DBAccess, DBClient, VirtualDataSet, VirtualTable, VirtualQuery, ExtCtrls,
DBCtrls;
type
TfmMain = class(TForm)
DBGrid: TDBGrid;
btClose: TSpeedButton;
DataSource: TDataSource;
ClientDataSet: TClientDataSet;
VirtualTable: TVirtualTable;
VirtualDataSet: TVirtualDataSet;
VirtualQuery: TVirtualQuery;
DBNavigator: TDBNavigator;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btCloseClick(Sender: TObject);
private
{ Private declarations }
NoteData: TStringList;
procedure OnGetRecordCount(Sender: TObject; out Count: Integer);
procedure OnGetFieldValue(Sender: TObject; Field: TField; RecNo: Integer; out Value: Variant);
public
{ Public declarations }
end;
var
fmMain: TfmMain;
implementation
{$R *.dfm}
procedure TfmMain.FormCreate(Sender: TObject);
begin
VirtualTable.LoadFromFile(ExtractFilePath(Application.ExeName) + 'Producer.xml');
ClientDataSet.FieldDefs.Add('ID', ftInteger);
ClientDataSet.FieldDefs.Add('ProducerID', ftInteger);
ClientDataSet.FieldDefs.Add('ModelName', ftString, 64);
ClientDataSet.CreateDataSet;
ClientDataSet.Open;
ClientDataSet.AppendRecord([9800, 10, 'Galaxy S7 Edge']);
ClientDataSet.AppendRecord([9830, 10, 'Galaxy Note 5']);
ClientDataSet.AppendRecord([1001, 20, 'iPhone 6']);
ClientDataSet.AppendRecord([1356, 20, 'iPhone 6 Plus']);
ClientDataSet.AppendRecord([3582, 40, 'Lumia 950 XL Dual Sim']);
NoteData := TStringList.Create;
NoteData.LoadFromFile(ExtractFilePath(Application.ExeName) + 'NoteData.txt');
VirtualDataSet.FieldDefs.Add('ID', ftInteger);
VirtualDataSet.FieldDefs.Add('Specification', ftString, 512);
VirtualDataSet.OnGetRecordCount := OnGetRecordCount;
VirtualDataSet.OnGetFieldValue := OnGetFieldValue;
VirtualTable.Open;
ClientDataSet.Open;
VirtualDataSet.Open;
VirtualQuery.Open;
VirtualQuery.FieldByName('ProducerName').ReadOnly := True;
VirtualQuery.FieldByName('ModelName').ReadOnly := False;
VirtualQuery.FieldByName('Specification').ReadOnly := False;
VirtualQuery.UpdatingTable := 'Model';
DataSource.DataSet := VirtualQuery;
end;
procedure TfmMain.FormDestroy(Sender: TObject);
begin
NoteData.Free;
end;
procedure TfmMain.OnGetFieldValue(Sender: TObject; Field: TField;
RecNo: Integer; out Value: Variant);
const
Delimeter = ' ; ';
var
Row: String;
begin
Row := NoteData.Strings[RecNo-1];
case Field.FieldNo of
1: Value := StrToInt(Copy(Row, 0, Pos(Delimeter, Row)-1));
2: Value := Copy(Row, Pos(Delimeter, Row)+Length(Delimeter), Length(Row));
end;
end;
procedure TfmMain.OnGetRecordCount(Sender: TObject; out Count: Integer);
begin
Count := NoteData.Count;
end;
procedure TfmMain.btCloseClick(Sender: TObject);
begin
Close;
end;
end.
|
unit broker;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, IdHTTP, IdURI, fpjson, jsonparser,
Dialogs, Grids, Graphics, Controls;
{
TODO : - change from JSONRequest to StrStreamRequest
- adding any result with status error or not
}
const
VERSION = '0.1';
type
{ TBroker }
TBroker = class
private
FHTTP:TIdHTTP;
FAddress:String;
FJSONRequest:TStringStream;
FResponseBody:String;
FResponseHttp:String;
FStatus: Boolean;
FToken:String;
FHost:String;
FJSONArray:TJSONArray;
FConnected:Boolean;
procedure RedirectProc(Sender: TObject; var dest: string;
var NumRedirect: Integer; var Handled: boolean; var VMethod: TIdHTTPMethod);
protected
FPage:Integer;
procedure getJSONArray(const jsonStr:String); // return [ {}, {} ]
function getJSONParser:TJSONParser;
procedure httpPost(const AUrl:String);
//procedure httpGet(const AUrl:String);
//procedure httpPatch(const AUrl:String);
//procedure httpDelete(const AUrl:String);
public
constructor Create;
destructor Destroy;
procedure setPage(const APage:Integer = 1);
procedure setHost(AHost:String);
procedure setJSONRequest(const ARequest:String);
procedure getToken(const jsonStr:String);
function httpRedirect(AURL:String):String;
published
// get hostname
property Host:String read FHost;
// check whether send/receive is success
property Status:Boolean read FStatus;
// result as response http
property responseHttp:String read FResponseHttp;
// result as response body
property responseBody:String read FResponseBody;
property responseToken:String read FToken;
// get [ {}, {} ]
property JSONArray:TJSONArray read FJSONArray;
property Page:Integer read FPage;
property Connected:Boolean read FConnected;
end;
{ TJSONGrid }
TJSONGrid = class
private
FStrGrid:TStringGrid;
FJSONArray:TJSONArray;
FStatus:Boolean;
//FTextStyle:TTextStyle;
procedure writeTitle(AJSONObject:TJSONObject);
function setAlignRight:TTextStyle;
function setAlignLeft:TTextStyle;
function setAlignCenter:TTextStyle;
protected
public
constructor Create;
//procedure setDateTimeSeparator(const ADate:Char = '/'; ATime:Char = ':');
//procedure setShortDateTime(const ADate:String = 'dd/MM/yyyy'; ATime:String = 'HH:mm:ss');
procedure getJSONArrays(AJSONArray:TJSONArray);
procedure setStringGrid(var AStrGrid:TStringGrid);
//procedure writeGrid(jsonStr:String);
procedure writeToGrid;
property Status:Boolean read FStatus;
end;
{ TJSONWebservices }
TJSONWebservices = class(TBroker)
private
// result as
FStrList:TStringList;
//FDoc:TCSVDocument;
//FXLS:TFPSpreadsheet;
protected
public
procedure getLogin;
procedure getRoot; // transaction name
procedure getTransaksi(ATransaction:String; AStart, AEnd:TDateTime; AWithStore:String = ''; AWithInvoice: String = '';
AShowPayment:SmallInt = 0);
procedure getStore(const AidStore:Integer = -1;AStore:String = ''; AShowDetail:SmallInt = 0);
procedure getStok (const ANoStok:String = ''; ANamaStok:String = '');
procedure getDetail(AId:Integer);
function getItemsStrList(AField:String):TStringList;
function getNamesStrList(const AIndex:Integer = 0):TStringList;
function getTxAliasStrList:TStringList;
function getTxName(AAlias:String):String;
function getResPage:Integer; //per halaman
function getResPages:Integer; // total halaman
end;
implementation
var
counter, i, j:integer;
FJSONObject:TJSONObject;
//FJSONArray:TJSONArray;
FParser:TJSONParser;
{ TJSONWebservices }
procedure TJSONWebservices.getLogin;
begin
//setJSONRequest(responseToken);
httpPost('/login');
getJSONArray(responseBody);
end;
procedure TJSONWebservices.getRoot;
begin
//post dengan token
setJSONRequest(responseToken);
httpPost('/');
getJSONArray(responseBody);
end;
procedure TJSONWebservices.getTransaksi(ATransaction: String; AStart,
AEnd: TDateTime; AWithStore: String; AWithInvoice: String;
AShowPayment: SmallInt);
var
FStart, FEnd, FWithStore, FWithInvoice, FShowPayment, FPath:String;
begin
// fixed parameter
FStart:='start='+FormatDateTime('yyyy-MM-dd', AStart);
FEnd:='end='+FormatDateTime('yyyy-MM-dd', AEnd);
FShowPayment:='payment='+inttostr(AShowPayment);
FWithStore:='store='+Trim(AWithStore);
FWithInvoice:='invoice='+Trim(AWithInvoice);
FPath:=FStart+'&'+FEnd+'&'+FShowPayment;
if AWithStore <> '' then
FPath:=FPath+'&'+FWithStore;
if AWithInvoice <> 'Invoices' then
FPath:=FPath+'&'+FWithInvoice;
setJSONRequest(responseToken);
httpPost('/apps/'+getTxName(ATransaction)+'/'+IntToStr(Page)+'?'+FPath); // default apps/<transaksi>/1
getJSONArray(responseBody);
end;
procedure TJSONWebservices.getStore(const AidStore: Integer; AStore: String;
AShowDetail: SmallInt);
var
FPath, FShowDetail, FStore, FIdStore:String;
begin
FShowDetail:='show_detail='+IntToStr(AShowDetail);
FIdStore:='id='+IntToStr(AIdStore);
FStore:='store='+Trim(AStore);
FPath:='?'+FShowDetail;
if AIdStore >= 0 then
FPath:=FPath+'&'+FIdStore;
if AStore <> '' then
FPath:=FPath+'&'+FStore;
//setJSONRequest(responseToken);
httpPost('/store'+FPath);
getJSONArray(responseBody);
end;
procedure TJSONWebservices.getStok(const ANoStok: String; ANamaStok: String);
var
FPath, FNoStok, FNamaStok:String;
begin
FNoStok:='nostok='+Trim(ANoStok);
FNamaStok:='namastok='+Trim(ANamaStok);
if ANoStok <> '' then
FPath:='?'+FNoStok;
if ANamaStok <> '' then
FPath:='?'+FNamaStok;
//setJSONRequest(responseToken);
httpPost('/stok'+FPath);
getJSONArray(responseBody);
end;
procedure TJSONWebservices.getDetail(AId: Integer);
begin
httpPost('/detail/'+inttostr(AId));
getJSONArray(responseBody);
end;
function TJSONWebservices.getItemsStrList(AField: String): TStringList;
begin
FStrList:=TStringList.Create;
for counter:=0 to JSONArray.Count-1 do
FStrList.Add(JSONArray.Objects[counter].Strings[AField]);
result:=FStrList;
end;
function TJSONWebservices.getNamesStrList(const AIndex: Integer): TStringList;
begin
FStrList:=TStringList.Create;
for counter:=0 to JSONArray.Count-1 do
FStrList.Add(JSONArray.Objects[counter].Names[AIndex]);
result:=FStrList;
end;
function TJSONWebservices.getTxName(AAlias: String): String;
begin
// as example TJSONObject.FindPath('$field[$id]').AsString
// case { Field:[pos_val1, pos_val2]}
//fStr:=AAlias+'[0]';
getRoot; //DISINI YG REQUEST T_T
//result:=FJSONArray.Objects[0].FindPath(fstr).AsString;
result:=FJSONArray.Objects[0].Strings[AAlias];
end;
function TJSONWebservices.getResPage: Integer;
begin
try
FJSONObject:=getJSONParser.Parse as TJSONObject;
//if (FJSONObject.Strings['page'] <> '') then
result:=strtoint(FJSONObject.Strings['page'])
except
result:=1;
end;
end;
function TJSONWebservices.getResPages: Integer;
begin
try
FJSONObject:=getJSONParser.Parse as TJSONObject;
//if (FJSONObject.Strings['pages'] <> '') then
result:=strtoint(FJSONObject.Strings['pages'])
except
result:=1;
end;
end;
function TJSONWebservices.getTxAliasStrList: TStringList;
begin
FStrList:=TStringList.Create;
// only have 1 array object
FJSONObject:=JSONArray.Objects[0];
for counter:=0 to FJSONObject.Count-1 do //begin
//fStr:=FJSONObject.Names[counter]+'[0]';
//FStrList.Add(FJSONObject.FindPath(fStr).AsString);
FStrList.Add(FJSONObject.Names[counter]);
//end;
result:=FStrList;
end;
{ TJSONGrid }
constructor TJSONGrid.Create;
begin
inherited Create;
FJSONArray:=TJSONArray.Create;
end;
procedure TJSONGrid.getJSONArrays(AJSONArray: TJSONArray);
begin
FJSONArray:=AJSONArray;
end;
procedure TJSONGrid.writeTitle(AJSONObject: TJSONObject);
begin
//FStrGrid.RowCount:=1;
if AJSONObject.Count = 0 then
FStrGrid.RowCount:=2
else
FStrGrid.ColCount:=AJSONObject.Count;
for counter:=0 to AJSONObject.Count-1 do
FStrGrid.Cells[counter, 0]:=UpperCase(AJSONObject.Names[counter]);
end;
function TJSONGrid.setAlignRight: TTextStyle;
var
FTextStyle:TTextStyle;
begin
FTextStyle:=FStrGrid.DefaultTextStyle;
FTextStyle.Alignment:=taRightJustify;
result:=FTextStyle;
end;
function TJSONGrid.setAlignLeft: TTextStyle;
var
FTextStyle:TTextStyle;
begin
FTextStyle:=FStrGrid.DefaultTextStyle;
FTextStyle.Alignment:=taLeftJustify;
result:=FTextStyle;
end;
function TJSONGrid.setAlignCenter: TTextStyle;
var
FTextStyle:TTextStyle;
begin
FTextStyle:=FStrGrid.DefaultTextStyle;
FTextStyle.Alignment:=taCenter;
result:=FTextStyle;
end;
procedure TJSONGrid.writeToGrid;
var
FTotalNetto: Currency;
begin
FStrGrid.BeginUpdate;
if FJSONArray.Count = 0 then
FStrGrid.RowCount:=2
else
begin
FStrGrid.RowCount:=FJSONArray.Count+1; // +1 untuk title
writeTitle(FJSONArray.Objects[0]); // ambil record=0 utk title
for i:=0 to FJSONArray.Count-1 do begin
FJSONObject:=FJSONArray.Objects[i];
//FStrGrid.ColCount:=FJSONObject.Count;
for j:=0 to FJSONObject.Count-1 do //begin
case FJSONObject.Names[j] of
'tgl','tglkirim': FStrGrid.Cells[j, i+1]:=FJSONObject.Items[j].AsString;
'discrp0','discrp1','ppnrp','biayarp0','biayarp1','totalbruto','totalppn','totaldisc', 'hpp', 'totalhpp':FStrGrid.Cells[j, i+1]:=FormatCurr('#,##0.#0', FJSONObject.Items[j].AsFloat);
'totalnetto': begin
FStrGrid.Cells[j, i+1]:=FormatCurr('#,##0.#0', FJSONObject.Items[j].AsFloat);
FTotalNetto:=FJSONObject.Items[j].AsFloat;
end;
'bayar': begin
FStrGrid.Cells[j, i+1]:=FormatCurr('#,##0.#0', FJSONObject.Items[j].AsFloat);
FStatus:=FTotalNetto = FJSONObject.Items[j].AsFloat;
if not FStatus then FStrGrid.Canvas.Brush.Color:=clRed;
end;
'discpersen0', 'discpersen1', 'ppnpersen', 'sisa', 'banyaknya' : FStrGrid.Cells[j, i+1]:=FormatCurr('#,##0.#0', FJSONObject.Items[j].AsFloat);
'nomor':FStrGrid.Cells[j, i+1]:=IntToStr(FJSONObject.Items[j].AsInt64);
else
FStrGrid.Cells[j, i+1]:=FJSONObject.Items[j].AsString;
end;
end;
end;
FStrGrid.AutoSizeColumns;
FStrGrid.AutoAdjustColumns;
FStrGrid.EndUpdate(True);
end;
procedure TJSONGrid.setStringGrid(var AStrGrid: TStringGrid);
begin
FStrGrid:=AStrGrid;
end;
{ TBroker }
procedure TBroker.getJSONArray(const jsonStr: String);
begin
FParser:=TJSONParser.Create(jsonStr);
FJSONObject:=FParser.Parse as TJSONObject;
FJSONArray:=FJSONObject.Arrays['result'];
end;
function TBroker.getJSONParser: TJSONParser;
begin
result:=TJSONParser.Create(FResponseBody);
end;
constructor TBroker.Create;
begin
inherited Create;
FHttp:=TIdHTTP.Create;
FPage:=1;
end;
destructor TBroker.Destroy;
begin
inherited Destroy;
FJSONRequest.Free;
FHTTP.Free;
end;
procedure TBroker.setPage(const APage: Integer);
begin
FPage:=APage;
end;
procedure TBroker.setHost(AHost: String);
begin
FHost:=AHost;
end;
procedure TBroker.setJSONRequest(const ARequest: String);
begin
try
FJSONRequest:=TStringStream.Create(ARequest);
FStatus:=True;
except
on E: EIdHTTPProtocolException do begin
ShowMessage('Please logout then login again.');
FStatus:=False;
//ShowMessage(E.Message);
//ShowMessage(E.ErrorMessage);
end;
end;
end;
procedure TBroker.httpPost(const AUrl: String);
begin
//try
if FStatus then begin
FHTTP.Request.Accept:='application/json';
FHTTP.Request.ContentType:='application/json';
FHTTP.Request.AcceptCharSet:='utf-8';
// check if URI is correct
//ShowMessage('httppost='+TIdURI.URLEncode(FHost+AURL));
FResponseBody:=FHTTP.Post(TIdURI.URLEncode(FHost+AURL), FJSONRequest);
FResponseHttp:=FHTTP.ResponseText; //response
FStatus:=True;
end;
//except
//on E: EIdHTTPProtocolException do begin
//ShowMessage(E.Message);
//ShowMessage('Please login again.');
//FStatus:=False;
//Exit;
//end;
//end;
//FJSONRequest.Free;
end;
{ Thanks to DNR <https://stackoverflow.com/users/1984211/dnr> }
procedure TBroker.RedirectProc(Sender: TObject; var dest: string;
var NumRedirect: Integer; var Handled: boolean; var VMethod: TIdHTTPMethod);
begin
FAddress := dest;
end;
// get session token after logged in
procedure TBroker.getToken(const jsonStr: String);
begin
//FParser:=TJSONParser.Create(jsonStr);
//FJSONObject:=FParser.Parse as TJSONObject;
//FJSONArray:=FJSONObject.Arrays['result'];
try
getJSONArray(jsonStr);
//FJSONObject:=FJSONArray.Objects[0]; // get {"token":""}
//FToken:=FJSONObject.AsJSON;
FToken:=FJSONArray.Objects[0].AsJSON;
FStatus:=True;
except
//on E:Exception do
// ShowMessage(E.Message);
ShowMessage('Your session has expired.');
FStatus:=False;
end;
end;
function TBroker.httpRedirect(AURL: String): String;
begin
try
with FHTTP do begin
HandleRedirects:=True;
OnRedirect:=@RedirectProc;
Get(AURL);
end;
except
on E:Exception do
ShowMessage(E.Message);
end;
result:=FAddress
end;
end.
{
program Project1;
uses
fpjson, jsonparser;
var
s:String;
Parser:TJSONParser;
Arr:TJSONArray;
i: integer;
begin
s :=
'['+
'{"NAME":"Patricia","SEX":"Female","COUNTRY":"Wales; "},'+
'{"NAME":"Pauline","SEX":"Female","COUNTRY":"Scotland; "},'+
'{"NAME":"Quinterie","SEX":"Female","COUNTRY":"France; "},'+
'{"NAME":"Salome","SEX":"Female","COUNTRY":"Israel; "},'+
'{"NAME":"Sandra","SEX":"Female","COUNTRY":"Wales; "},'+
'{"NAME":"Sigourney","SEX":"Female","COUNTRY":"England; "},'+
'{"NAME":"Silvia","SEX":"Female","COUNTRY":"Scotland; "},'+
'{"NAME":"Sonia","SEX":"Female","COUNTRY":"Italy; "},'+
'{"NAME":"Veronica","SEX":"Female","COUNTRY":"Ireland; "},'+
'{"NAME":"Viviane","SEX":"Female","COUNTRY":"France; "}'+
']';
Parser:=TJSONParser.Create(s);
Arr := Parser.Parse as TJSONArray;
WriteLn('Array of ',Arr.Count);
for i := 0 to Arr.Count - 1 do
begin
SubObj := Arr.Objects[i];
WriteLn(i+1, ': ', SubObj.Strings['NAME'], ', ', SubObj.Strings['SEX'], ', ', SubObj.Strings['COUNTRY']);
end;
readln;
//...etc
end.
procedure TJSONGrid.setStrGrid(var AStrGrid: TStringGrid);
begin
FStrGrid:=AStrGrid;
FStrGrid.BeginUpdate;
end;
function TJSONGrid.setJsonString(const AjsStr: String): TJSONObject;
begin
FJsonData:=GetJSON(AjsStr);
//FJsonObject:=TJSONObject(FJsonData);
end;
procedure TJSONGrid.setGridTitle(const AString: String); // {}
var
i:integer;
begin
FObjTitle:=TJSONObject(GetJSON(AString));
for i:=0 to FObjTitle.Count-1 do
FStrGrid.Cells[i, 0]:=FObjTitle.Names[i];
end;
procedure TJSONGrid.SetGridContent(const AString: String); // [{},{}]
var
i,j:integer;
begin
FParser:=TJSONParser.Create(AString);
FJSONArray:=FParser.Parse as TJSONArray;
for i:=0 to FJSONArray.Count-1 do begin
FObjContent:=FJSONArray.Objects[i]; //baris
for j:=0 to FObjContent.Count-1 do
FStrGrid.Cells[i+1, j]:=FObjContent.Items[j].AsString;
end;
end;
program project1;
uses
fpjson, jsonparser;
var
s:String;
Parser:TJSONParser;
Obj, SubObj:TJSONObject;
Arr:TJSONArray;
i: integer;
begin
s :=
'{'+
' "personaggi" : ['+
' {'+
' "val1" : "pippo",'+
' "val2" : "2014-11-18T10:25:38.486320Z",'+
' "val3" : 1,'+
' "val4" : 2'+
' },'+
' {'+
' "val1" : "pluto",'+
' "val2" : "2014-11-18T10:25:38.486320Z",'+
' "val3" : 1,'+
' "val4" : 2'+
' },'+
' {'+
' "val1" : "minni",'+
' "val2" : "2014-11-18T10:25:38.486320Z",'+
' "val3" : 1,'+
' "val4" : 2'+
' }'+
' ]'+
'} ';
Parser:=TJSONParser.Create(s);
Obj := Parser.Parse as TJSONObject;
Arr := Obj.Arrays['personaggi'];
WriteLn(Arr.Count);
for i := 0 to Arr.Count - 1 do
begin
SubObj := Arr.Objects[i];
WriteLn(SubObj.Strings['val1']);
WriteLn(SubObj.Strings['val2']);
WriteLn(SubObj.Strings['val3']);
WriteLn(SubObj.Strings['val4']);
end;
end.
}
|
unit UItemVariavelVinculo;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.Grids, Vcl.DBGrids,
Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.DBCtrls, Vcl.Buttons,
UDBCampoCodigo, MemDS, VirtualTable, frxClass, frxDBSet, frxExportPDF;
type
TFItemVariavelVinculo = class(TForm)
pnBotoes: TPanel;
sbDados: TScrollBox;
lbVariavelItens: TLabel;
lbcdItem: TLabel;
grDados: TDBGrid;
edcdItem: TDBCampoCodigo;
btSalvar: TBitBtn;
btFechar: TBitBtn;
dsDados: TDataSource;
btExluir: TBitBtn;
btLiberarBloquear: TBitBtn;
procedure FormCreate(Sender: TObject);
procedure btFecharClick(Sender: TObject);
procedure edcdItemERPOnEdCampoChaveExit(Sender: TObject);
procedure btSalvarClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure grDadosEditButtonClick(Sender: TObject);
procedure btExluirClick(Sender: TObject);
procedure btLiberarBloquearClick(Sender: TObject);
private
procedure SelecionaValorCodigo(const sDescLabel,
sCampoChave,
sCampoDescricao,
sCamposFiltro,
sCamposFiltroTitulo,
sSqlPesq : String;
const dtDataType : TFieldType;
const ccCharCase : TEditCharCase;
var sValorCodigo,
sValorDescricao : String
);
public
{ Public declarations }
end;
var
FFItemVariavelVinculo: TFItemVariavelVinculo;
implementation
uses
uDmERP, UTelaInicial, uFuncoes, UCampoCodigoGrid, UItemVariavelItensBloq;
{$R *.dfm}
procedure TFItemVariavelVinculo.SelecionaValorCodigo(const sDescLabel,
sCampoChave,
sCampoDescricao,
sCamposFiltro,
sCamposFiltroTitulo,
sSqlPesq : String;
const dtDataType : TFieldType;
const ccCharCase : TEditCharCase;
var sValorCodigo,
sValorDescricao : String
);
begin
if (DmERP.qyItemVinculoVariavel.Active) and (DmERP.qyItemVinculoVariavel.State in dsEditModes) then
begin
FCampoCodigoGrid := TFCampoCodigoGrid.Create(Application);
try
FCampoCodigoGrid.lbcdCampoCodigo.Caption := sDescLabel;
FCampoCodigoGrid.edcdCampoCodigo.ERPCampoChave := sCampoChave;
FCampoCodigoGrid.edcdCampoCodigo.ERPCampoDescricao := sCampoDescricao;
FCampoCodigoGrid.edcdCampoCodigo.ERPSqlPesquisa.Clear;
FCampoCodigoGrid.edcdCampoCodigo.ERPSqlPesquisa.Add(sSqlPesq);
FCampoCodigoGrid.edcdCampoCodigo.ERPCampoChaveDataType := dtDataType;
FCampoCodigoGrid.edcdCampoCodigo.ERPCharCase := ccCharCase;
FCampoCodigoGrid.edcdCampoCodigo.ERPCamposFiltro.CommaText := sCamposFiltro;
FCampoCodigoGrid.edcdCampoCodigo.ERPCamposFiltroTitulo.CommaText := sCamposFiltroTitulo;
if Trim(sValorCodigo) <> '' then
FCampoCodigoGrid.edcdCampoCodigo.ERPEdCampoChaveText := sValorCodigo;
FCampoCodigoGrid.ShowModal;
sValorCodigo := FCampoCodigoGrid.edcdCampoCodigo.ERPEdCampoChaveText;
sValorDescricao := FCampoCodigoGrid.edcdCampoCodigo.ERPLbDescricaoCaption;
finally
FreeAndNil(FCampoCodigoGrid);
end;
end;
end;
procedure TFItemVariavelVinculo.btExluirClick(Sender: TObject);
begin
DmERP.ExcluirItemVinculoVariavel;
end;
procedure TFItemVariavelVinculo.btFecharClick(Sender: TObject);
var
Tab : TTabSheet;
begin
dsDados.DataSet.Close;
Tab := FTelaInicial.pcTelas.ActivePage;
if Assigned(Tab) then
begin
Tab.Parent := nil;
Tab.PageControl := nil;
FreeAndNil(Tab);
end;
FTelaInicial.pcTelas.Visible := FTelaInicial.pcTelas.PageCount > 0;
FTelaInicial.imLogoERP.Visible := not FTelaInicial.pcTelas.Visible;
end;
procedure TFItemVariavelVinculo.btLiberarBloquearClick(Sender: TObject);
begin
if not edcdItem.ERPValorValido then
Aviso('Informe o item antes.')
else if (DmERP.qyItemVinculoVariavel.IsEmpty) or
(DmERP.qyItemVinculoVariavel.FieldByName('cdVariavel').IsNull) then
Aviso('Insira uma variável antes de liberar/bloquear os valores.')
else if DmERP.qyItemVinculoVariavel.UpdatesPending then
Aviso('Salve a variável inserida antes de liberar/bloquear os valores.')
else
begin
if DmERP.qyItemVarItensLib.Active then
DmERP.qyItemVarItensLib.Close;
DmERP.qyItemVarItensLib.ParamByName('cdItem').AsString := edcdItem.ERPEdCampoChaveText;
DmERP.qyItemVarItensLib.ParamByName('cdVariavel').AsInteger := DmERP.qyItemVinculoVariavel.FieldByName('cdVariavel').AsInteger;
DmERP.qyItemVarItensLib.Open();
if DmERP.qyItemVariavelItensBloq.Active then
DmERP.qyItemVariavelItensBloq.Close;
DmERP.qyItemVariavelItensBloq.MacroByName('filtro').Value := ' WHERE cdItem = ' + QuotedStr(edcdItem.ERPEdCampoChaveText) +
' AND cdVariavel = ' + DmERP.qyItemVinculoVariavel.FieldByName('cdVariavel').AsString;
DmERP.qyItemVariavelItensBloq.Open();
FItemVariavelItensBloq := TFItemVariavelItensBloq.Create(Application);
try
FItemVariavelItensBloq.FsItem := edcdItem.ERPEdCampoChaveText;
FItemVariavelItensBloq.ShowModal;
finally
FreeAndNil(FItemVariavelItensBloq);
end;
end;
end;
procedure TFItemVariavelVinculo.btSalvarClick(Sender: TObject);
begin
DmERP.GravarItemVinculoVariavel;
end;
procedure TFItemVariavelVinculo.edcdItemERPOnEdCampoChaveExit(Sender: TObject);
begin
if edcdItem.ERPValorValido then
begin
if DmERP.qyItemVinculoVariavel.Active then
DmERP.qyItemVinculoVariavel.Close;
DmERP.qyItemVinculoVariavel.MacroByName('filtro').Value := ' WHERE cdItem = ' + QuotedStr(edcdItem.ERPEdCampoChaveText);
DmERP.qyItemVinculoVariavel.Open();
if DmERP.qyItemVinculoVariavel.IsEmpty then
begin
DmERP.qyItemVinculoVariavel.Insert;
DmERP.qyItemVinculoVariavel.FieldByName('cdItem').AsString := edcdItem.ERPEdCampoChaveText;
if (grDados.Visible) and (grDados.Enabled) and (grDados.CanFocus) then
grDados.SetFocus;
end;
end
else if Trim(edcdItem.ERPEdCampoChaveText) <> '' then
edcdItem.ERPEdCampoChaveSetFocus;
end;
procedure TFItemVariavelVinculo.FormCreate(Sender: TObject);
begin
btSalvar.Glyph.LoadFromResourceName(HInstance, 'IMGBTSALVAR_32X32');
btExluir.Glyph.LoadFromResourceName(HInstance, 'IMGBTEXCLUIR_32X32');
btLiberarBloquear.Glyph.LoadFromResourceName(HInstance, 'IMGBTLIBBLOQ_32X32');
btFechar.Glyph.LoadFromResourceName(HInstance, 'IMGBTFECHAR_32X32');
end;
procedure TFItemVariavelVinculo.FormShow(Sender: TObject);
begin
edcdItem.ERPEdCampoChaveSetFocus;
end;
procedure TFItemVariavelVinculo.grDadosEditButtonClick(Sender: TObject);
var
sValorCodigo,
sValorDescricao : String;
begin
sValorCodigo := '';
sValorDescricao := '';
if SameText(grDados.SelectedField.FieldName , 'cdVariavel') then
begin
if not (DmERP.qyItemVinculoVariavel.State in dsEditModes) then
DmERP.qyItemVinculoVariavel.Edit;
DmERP.qyItemVinculoVariavel.FieldByName('cdVariavelItemPadrao').Clear;
if not DmERP.qyItemVinculoVariavel.FieldByName('cdVariavel').IsNull then
sValorCodigo := DmERP.qyItemVinculoVariavel.FieldByName('cdVariavel').AsString;
SelecionaValorCodigo('Variável:',
'cdVariavel',
'deVariavel',
'cdVariavel,deVariavel',
'Código,Descrição',
'SELECT t.* ' +
' FROM ( ' +
' SELECT cdVariavel, ' +
' deVariavel ' +
' FROM erp.variavel ' +
' ) t ' +
' &filtro',
ftInteger,
ecNormal,
sValorCodigo,
sValorDescricao
);
if Trim(sValorCodigo) <> '' then
begin
DmERP.qyItemVinculoVariavel.FieldByName('cdVariavel').AsString := sValorCodigo;
DmERP.qyItemVinculoVariavel.FieldByName('deVariavel').AsString := sValorDescricao;
end;
end
else if (SameText(grDados.SelectedField.FieldName, 'cdVariavelItemPadrao')) then
begin
if DmERP.qyItemVinculoVariavel.FieldByName('cdVariavel').IsNull then
Aviso('Informe a variável primeiro.')
else
begin
if not (DmERP.qyItemVinculoVariavel.State in dsEditModes) then
DmERP.qyItemVinculoVariavel.Edit;
if not DmERP.qyItemVinculoVariavel.FieldByName('cdVariavelItemPadrao').IsNull then
sValorCodigo := DmERP.qyItemVinculoVariavel.FieldByName('cdVariavelItemPadrao').AsString;
SelecionaValorCodigo('Item Var. Padrão:',
'cdVariavelItemPadrao',
'deVariavelItemPadrao',
'cdVariavelItemPadrao,deVariavelItemPadrao',
'Código,Descrição',
'SELECT t.* ' +
' FROM ( ' +
' SELECT cdVariavelItem AS cdVariavelItemPadrao, ' +
' deValor AS deVariavelItemPadrao ' +
' FROM erp.variavelItens ' +
' WHERE cdVariavel = ' + DmERP.qyItemVinculoVariavel.FieldByName('cdVariavel').AsString +
' ) t ' +
' &filtro',
ftInteger,
ecNormal,
sValorCodigo,
sValorDescricao
);
if Trim(sValorCodigo) <> '' then
begin
DmERP.qyItemVinculoVariavel.FieldByName('cdVariavelItemPadrao').AsString := sValorCodigo;
DmERP.qyItemVinculoVariavel.FieldByName('deVariavelItemPadrao').AsString := sValorDescricao;
end;
end;
end;
end;
initialization
RegisterClass(TFItemVariavelVinculo);
finalization
UnRegisterClass(TFItemVariavelVinculo);
end.
|
unit ccPlanarCapFrame;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, ExtCtrls, StdCtrls, IniFiles,
ccBaseFrame;
type
{ TPlanarCapFrame }
TPlanarCapFrame = class(TBaseFrame)
Bevel3: TBevel;
CbCapaUnits: TComboBox;
CbDistUnits: TComboBox;
CbAreaUnits: TComboBox;
CbLengthUnits: TComboBox;
CbWidthUnits: TComboBox;
EdDist: TEdit;
Panel1: TPanel;
TxtCapaPerAreaUnits: TLabel;
TxtCapaPerArea: TEdit;
TxtCapaPerLength: TEdit;
LblCapa: TLabel;
TxtArea: TEdit;
EdLength: TEdit;
EdWidth: TEdit;
EdEps: TEdit;
LblDist: TLabel;
LblArea: TLabel;
LblLength: TLabel;
LblWidth: TLabel;
LblEps: TLabel;
TxtCapa: TEdit;
LblCapaPerArea: TLabel;
LblCapaPerLength: TLabel;
TxtCapaPerLengthUnits: TLabel;
private
{ private declarations }
protected
procedure ClearResults; override;
procedure SetEditLeft(AValue: Integer); override;
public
{ public declarations }
constructor Create(AOwner: TComponent); override;
procedure Calculate; override;
procedure ReadFromIni(ini: TCustomIniFile); override;
function ValidData(out AMsg: String; out AControl: TWinControl): Boolean; override;
procedure WriteToIni(ini: TCustomIniFile); override;
end;
implementation
{$R *.lfm}
uses
ccGlobal;
{ TPlanarCapFrame }
constructor TPlanarcapFrame.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FIniKey := 'Planar';
end;
procedure TPlanarCapFrame.Calculate;
var
fL, fa, fc : double;
d, W, L, A, eps, capa : extended;
capaFmt: String;
capaUnits: String;
lengthUnits: String;
areaUnits: String;
begin
try
if (EdDist.Text = '') or not TryStrToFloat(EdDist.Text, d) then exit;
if d = 0 then exit;
if (EdLength.Text = '') or not TryStrToFloat(EdLength.Text, L) then exit;
if (EdWidth.Text = '') or not TryStrToFloat(EdWidth.Text, W) then exit;
if (EdEps.Text = '') or not TryStrToFloat(EdEps.Text, eps) then exit;
if CbDistUnits.ItemIndex = -1 then exit;
if CbLengthUnits.ItemIndex = -1 then exit;
if CbWidthUnits.ItemIndex = -1 then exit;
if CbAreaUnits.ItemIndex = -1 then exit;
if CbCapaUnits.ItemIndex = -1 then exit;
fL := LenFactor[TLenUnits(CbLengthUnits.ItemIndex)];
fa := AreaFactor[TAreaUnits(CbAreaUnits.ItemIndex)];
fc := CapaFactor[TCapaUnits(CbCapaUnits.ItemIndex)];
d := d * LenFactor[TLenUnits(CbDistUnits.ItemIndex)];
W := W * LenFactor[TLenUnits(CbWidthUnits.ItemIndex)];
L := L * fL;
A := W * L;
capa := eps0 * eps * A / d;
if CbCapaUnits.Text = 'F' then
capaFmt := CapaExpFormat else
capaFmt := CapaStdFormat;
capaUnits := CbCapaUnits.Items[CbCapaUnits.ItemIndex];
lengthUnits := CbLengthUnits.Items[CbLengthUnits.ItemIndex];
areaUnits := CbAreaUnits.Items[CbAreaUnits.ItemIndex];
// Area
TxtArea.Text := FormatFloat(AreaStdFormat, A / fa);
// Capacitance
TxtCapa.Text := FormatFloat(capaFmt, capa / fc);
// Capacitance per area
TxtCapaPerAreaUnits.Caption := Format('%s/%s', [capaUnits, areaUnits]);
TxtCapaPerArea.Text := FormatFloat(CapaPerAreaFormat, capa / A * fa / fc);
// Capacitance per length
TxtCapaPerLengthUnits.caption := Format('%s/%s', [capaUnits, lengthUnits]);
TxtCapaPerLength.Text := FormatFloat(CapaPerLengthFormat, capa / L * fL / fc);
except
ClearResults;
end;
end;
procedure TPlanarCapFrame.ClearResults;
begin
TxtArea.Clear;
TxtCapa.Clear;
TxtCapaPerArea.Clear;
TxtCapaPerLength.Clear;
end;
procedure TPlanarCapFrame.ReadFromIni(ini: TCustomIniFile);
var
fs: TFormatSettings;
s: String;
value: Extended;
begin
fs := DefaultFormatSettings;
fs.DecimalSeparator := '.';
s := ini.ReadString(FIniKey, 'Dist', '');
if (s <> '') and TryStrToFloat(s, value, fs) then
EdDist.Text := FloatToStr(value) else
EdDist.Clear;
s := ini.ReadString(FIniKey, 'Length', '');
if (s <> '') and TryStrToFloat(s, value, fs) then
EdLength.Text := FloatToStr(value) else
EdLength.Clear;
s := ini.ReadString(FIniKey, 'Width', '');
if (s <> '') and TryStrToFloat(s, value, fs) then
EdWidth.Text := FloatToStr(value) else
EdWidth.Clear;
s := ini.ReadString(FIniKey, 'eps', '');
if (s <> '') and TryStrToFloat(s, value, fs) then
EdEps.Text := FloatToStr(value) else
EdEps.Clear;
s := ini.ReadString(FIniKey, 'Dist units', '');
if (s <> '') then
CbDistUnits.ItemIndex := CbDistUnits.Items.IndexOf(s) else
CbDistUnits.ItemIndex := -1;
s := ini.ReadString(FIniKey, 'Length units', '');
if (s <> '') then
CbLengthUnits.ItemIndex := CbLengthUnits.Items.IndexOf(s) else
CbLengthUnits.ItemIndex := -1;
s := ini.ReadString(FIniKey, 'Width units', '');
if (s <> '') then
CbWidthUnits.ItemIndex := CbWidthUnits.Items.IndexOf(s) else
CbWidthUnits.ItemIndex := -1;
s := ini.ReadString(FIniKey, 'Area units', '');
if (s <> '') then
CbAreaUnits.ItemIndex := CbAreaUnits.Items.IndexOf(s) else
CbAreaUnits.ItemIndex := -1;
s := ini.ReadString(FIniKey, 'Capa units', '');
if (s <> '') then
CbCapaUnits.ItemIndex := CbCapaUnits.Items.Indexof(s) else
CbCapaUnits.ItemIndex := -1;
Calculate;
end;
procedure TPlanarCapFrame.SetEditLeft(AValue: Integer);
begin
if AValue = FEditLeft then exit;
inherited;
EdDist.Left := FEditLeft;
TxtArea.Left := FEditLeft;
panel1.Height := TxtCapaPerLength.Top + TxtCapaPerLength.Height + TxtArea.Top;
Width := CbDistUnits.Left + CbDistUnits.Width + 2*FControlDist;
end;
function TPlanarCapFrame.ValidData(out AMsg: String; out AControl: TWinControl
): Boolean;
begin
Result := false;
if not IsValidPositive(EdDist, AMsg) then begin
AControl := EdDist;
exit;
end;
if not IsValidPositive(EdLength, AMsg) then begin
AControl := EdLength;
exit;
end;
if not IsValidPositive(EdWidth, AMsg) then begin
AControl := EdWidth;
exit;
end;
if not IsValidNumber(EdEps, AMsg) then begin
AControl := EdEps;
exit;
end;
if not IsValidComboValue(CbDistUnits, AMsg) then begin
AControl := CbDistUnits;
exit;
end;
if not IsValidComboValue(CbLengthUnits, AMsg) then begin
AControl := CbLengthUnits;
exit;
end;
if not IsValidComboValue(CbWidthUnits, AMsg) then begin
AControl := CbWidthUnits;
exit;
end;
if not IsValidComboValue(CbAreaUnits, AMsg) then begin
AControl := CbAreaUnits;
exit;
end;
if not IsValidComboValue(CbCapaUnits, AMsg) then begin
AControl := CbCapaUnits;
exit;
end;
Result := true;
end;
procedure TPlanarCapFrame.WriteToIni(ini: TCustomIniFile);
var
fs: TFormatSettings;
value: Extended;
begin
fs := DefaultFormatSettings;
fs.DecimalSeparator := '.';
ini.EraseSection(FIniKey);
if (EdDist.Text <> '') and TryStrToFloat(EdDist.Text, value) then
ini.WriteString(FIniKey, 'Dist', FloatToStr(value, fs));
if CbDistUnits.ItemIndex >= 0 then
ini.WriteString(FIniKey, 'Dist units', CbDistUnits.Items[CbDistUnits.ItemIndex]);
if (EdLength.Text <> '') and TryStrToFloat(EdLength.Text, value) then
ini.WriteString(FIniKey, 'Length', FloatToStr(value, fs));
if CbLengthUnits.ItemIndex >= 0 then
ini.WriteString(FIniKey, 'Length units', CbLengthUnits.Items[CbLengthUnits.ItemIndex]);
if (EdWidth.Text <> '') and TryStrToFloat(EdWidth.Text, value) then
ini.WriteString(FIniKEy, 'Width', FloatToStr(value, fs));
if CbWidthUnits.ItemIndex >= 0 then
ini.WriteString(FIniKey, 'Width units', CbWidthUnits.Items[CbWidthUnits.ItemIndex]);
if (EdEps.Text <> '') and TryStrToFloat(EdEps.Text, value) then
ini.WriteString(FIniKey, 'eps', FloatToStr(value, fs));
if CbAreaUnits.ItemIndex >= 0 then
ini.WriteString(FIniKey, 'Area units', CbAreaUnits.Items[CbAreaUnits.ItemIndex]);
if CbCapaUnits.ItemIndex >= 0 then
ini.WriteString(FIniKey, 'Capa units', CbCapaUnits.Items[CbCapaUnits.ItemIndex]);
end;
end.
|
unit ACBrLibMDFeStaticImport;
{$IfDef FPC}
{$mode objfpc}{$H+}
{$EndIf}
{.$Define STDCALL}
interface
uses
Classes, SysUtils;
const
{$IfDef MSWINDOWS}
{$IfDef CPU64}
CACBrMDFeLIBName = 'ACBrMDFe64.dll';
{$Else}
CACBrMDFeLIBName = 'ACBrMDFe32.dll';
{$EndIf}
{$Else}
{$IfDef CPU64}
CACBrMDFeLIBName = 'ACBrMDFe64.so';
{$Else}
CACBrMDFeLIBName = 'ACBrMDFe32.so';
{$EndIf}
{$EndIf}
{$I ACBrLibErros.inc}
{%region Constructor/Destructor}
function MDFe_Inicializar(const eArqConfig, eChaveCrypt: PChar): longint;
{$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; external CACBrMDFeLIBName;
function MDFe_Finalizar: longint;
{$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; external CACBrMDFeLIBName;
{%endregion}
{%region Versao/Retorno}
function MDFe_Nome(const sNome: PChar; var esTamanho: longint): longint;
{$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; external CACBrMDFeLIBName;
function MDFe_Versao(const sVersao: PChar; var esTamanho: longint): longint;
{$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; external CACBrMDFeLIBName;
function MDFe_UltimoRetorno(const sMensagem: PChar; var esTamanho: longint): longint;
{$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; external CACBrMDFeLIBName;
{%endregion}
{%region Ler/Gravar Config }
function MDFe_ConfigLer(const eArqConfig: PChar): longint;
{$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; external CACBrMDFeLIBName;
function MDFe_ConfigGravar(const eArqConfig: PChar): longint;
{$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; external CACBrMDFeLIBName;
function MDFe_ConfigLerValor(const eSessao, eChave: PChar; sValor: PChar; var esTamanho: longint): longint;
{$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; external CACBrMDFeLIBName;
function MDFe_ConfigGravarValor(const eSessao, eChave, eValor: PChar): longint;
{$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; external CACBrMDFeLIBName;
{%endregion}
{%region MDFe}
function MDFe_CarregarXML(const eArquivoOuXML: PChar): longint;
{$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; external CACBrMDFeLIBName;
function MDFe_CarregarINI(const eArquivoOuINI: PChar): longint;
{$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; external CACBrMDFeLIBName;
function MDFe_LimparLista: longint;
{$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; external CACBrMDFeLIBName;
function MDFe_Assinar: longint;
{$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; external CACBrMDFeLIBName;
function MDFe_Validar: longint;
{$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; external CACBrMDFeLIBName;
function MDFe_ValidarRegrasdeNegocios(const sResposta: PChar; var esTamanho: longint): longint;
{$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; external CACBrMDFeLIBName;
function MDFe_VerificarAssinatura(const sResposta: PChar; var esTamanho: longint): longint;
{$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; external CACBrMDFeLIBName;
{%endregion}
{%region Servicos}
function MDFe_StatusServico(const sResposta: PChar; var esTamanho: longint): longint;
{$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; external CACBrMDFeLIBName;
function MDFe_Consultar(const eChaveOuMDFe: PChar;
const sResposta: PChar; var esTamanho: longint): longint;
{$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; external CACBrMDFeLIBName;
function MDFe_Enviar(ALote: Integer; Imprimir: Boolean;
const sResposta: PChar; var esTamanho: longint): longint;
{$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; external CACBrMDFeLIBName;
function MDFe_Cancelar(const eChave, eJustificativa, eCNPJ: PChar; ALote: Integer;
const sResposta: PChar; var esTamanho: longint): longint;
{$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; external CACBrMDFeLIBName;
function MDFe_EnviarEvento(idLote: Integer;
const sResposta: PChar; var esTamanho: longint): longint;
{$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; external CACBrMDFeLIBName;
function MDFe_DistribuicaoDFePorUltNSU(eCNPJCPF, eultNSU: PChar;
const sResposta: PChar; var esTamanho: longint): longint;
{$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; external CACBrMDFeLIBName;
function MDFe_DistribuicaoDFePorNSU(eCNPJCPF, eNSU: PChar;
const sResposta: PChar; var esTamanho: longint): longint;
{$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; external CACBrMDFeLIBName;
function MDFe_DistribuicaoDFePorChave(eCNPJCPF, echMDFe: PChar;
const sResposta: PChar; var esTamanho: longint): longint;
{$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; external CACBrMDFeLIBName;
function MDFe_EnviarEmail(const ePara, eChaveMDFe: PChar; const AEnviaPDF: Boolean;
const eAssunto, eCC, eAnexos, eMensagem: PChar): longint;
{$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; external CACBrMDFeLIBName;
function MDFe_EnviarEmailEvento(const ePara, eChaveEvento, eChaveMDFe: PChar;
const AEnviaPDF: Boolean; const eAssunto, eCC, eAnexos, eMensagem: PChar): longint;
{$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; external CACBrMDFeLIBName;
function MDFe_Imprimir: longint;
{$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; external CACBrMDFeLIBName;
function MDFe_ImprimirPDF: longint;
{$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; external CACBrMDFeLIBName;
function MDFe_ImprimirEvento(const eChaveMDFe, eChaveEvento: PChar): longint;
{$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; external CACBrMDFeLIBName;
function MDFe_ImprimirEventoPDF(const eChaveMDFe, eChaveEvento: PChar): longint;
{$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; external CACBrMDFeLIBName;
{%endregion}
implementation
end.
|
unit fProbFreetext;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, uProbs,
Dialogs, fBase508Form, VA508AccessibilityManager, ExtCtrls, StdCtrls, Buttons;
type
TfrmProbFreetext = class(TfrmBase508Form)
pnlButton: TPanel;
pnlLeft: TPanel;
pnlDialog: TPanel;
bbYes: TBitBtn;
bbNo: TBitBtn;
edtComment: TLabeledEdit;
ckbNTRT: TCheckBox;
imgIcon: TImage;
pnlNTRT: TPanel;
pnlMessage: TPanel;
memMessage: TMemo;
lblUse: TStaticText;
procedure FormCreate(Sender: TObject);
procedure ckbNTRTClick(Sender: TObject);
procedure bbYesClick(Sender: TObject);
procedure edtCommentChange(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
function CreateFreetextMessage(term: String; ICDVersion: String): TForm;
var
frmProbFreetext: TfrmProbFreetext;
implementation
{$R *.dfm}
uses
VAUtils, ORFn;
const
TXR69 = 'A suitable term was not found based on user input and current defaults.' + CRLF + 'If you proceed with this nonspecific term, an ICD code of "R69 - ILLNESS, UNSPECIFIED" will be filed.';
procedure TfrmProbFreetext.bbYesClick(Sender: TObject);
begin
inherited;
RequestNTRT := ckbNTRT.Checked;
NTRTComment := edtComment.Text;
end;
procedure TfrmProbFreetext.ckbNTRTClick(Sender: TObject);
begin
inherited;
edtComment.Visible := ckbNTRT.Checked;
if edtComment.Visible then
edtComment.SetFocus
else
edtComment.Clear;
end;
procedure TfrmProbFreetext.edtCommentChange(Sender: TObject);
begin
inherited;
bbNo.Default := False;
bbYes.Default := True;
end;
procedure TfrmProbFreetext.FormCreate(Sender: TObject);
begin
inherited;
with imgIcon do
begin
Picture.Icon.Handle := LoadIcon(0, IDI_QUESTION);
end;
memMessage.TabStop := ScreenReaderActive;
lblUse.TabStop := ScreenReaderActive;
end;
function CreateFreetextMessage(term: String; ICDVersion: String): TForm;
begin
Result := TfrmProbFreetext.Create(Application);
with Result as TfrmProbFreetext do
begin
if Piece(ICDVersion, '^', 1) = '10D' then
begin
memMessage.Lines.Clear;
memMessage.Lines[0] := TXR69;
end;
lblUse.Caption := lblUse.caption + ' ' + term + '?';
bbNo.Default := True;
ActiveControl := bbNo;
with ckbNTRT do
begin
Hint := 'Check this box if you would like ' + UpperCase(term) +
' to be considered for inclusion'#13#10'in future revisions of SNOMED CT.';
ShowHint := True;
end;
Invalidate;
end;
end;
end.
|
unit BackgroundForm;
interface
uses
ListeningFrame,
// SpeakingFrame,
ReadingFrame,
// WritingFrame,
LTClasses,
ResultGuideForm,
DAOResult,
Global,
Generics.Collections,
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls;
type
TfrBackground = class(TLTForm)
QuestionBoard: TPanel;
btNext: TButton;
fmReading: TfmReading;
fmListening: TfmListening;
procedure btNextClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
FTestContainer: TTest;
FTestResult: TTestResult;
FTestResultDetailList: TObjectList<TTestResultDetail>;
FKind: TQuizKind;
procedure SetQuestion;
procedure ShowListening;
procedure ShowSpeaking;
procedure ShowReading;
procedure ShowWriting;
procedure CreateResultGuide;
procedure SetTestResult;
procedure SetTestResultDetail(Point: integer; Correct: string); overload;
procedure SetTestResultDetail(TestResultDetail: TTestResultDetail);
overload;
procedure SetTestResultDetail(TestResultDetails: TList<TTestResultDetail>);
overload;
public
{ Public declarations }
procedure SetTest(CopyTestContainer: TTest);
end;
var
frBackground: TfrBackground;
implementation
{$R *.dfm}
procedure TfrBackground.btNextClick(Sender: TObject);
begin
case FKind of
// todo : Speaking Answer üũ
// qkSpeaking: fmSpeaking.Checkable(FTestContainer.GetCurrentQuiz);
qkReading:
SetTestResultDetail(fmReading.GetTestResultDetails);
qkListening:
SetTestResultDetail(fmListening.GetTestResultDetail);
// qkWriting:
// SetTestResultDetail(fmWriting.GetTestResultDetail);
end;
if FTestContainer.HasNextQuiz then
begin
FTestContainer.Next;
SetQuestion;
end
else
begin
ShowMessage('Complete');
SetTestResult;
CreateResultGuide;
end;
end;
procedure TfrBackground.ShowListening;
begin
fmListening.BringToFront;
end;
procedure TfrBackground.ShowReading;
begin
fmReading.BringToFront;
end;
procedure TfrBackground.CreateResultGuide;
begin
frResultGuide := TfrResultGuide.Create(Self);
frResultGuide.Parent := Application.MainForm;
frResultGuide.Show;
end;
procedure TfrBackground.FormCreate(Sender: TObject);
begin
FTestResultDetailList := TObjectList<TTestResultDetail>.Create;
end;
procedure TfrBackground.FormDestroy(Sender: TObject);
begin
FTestResultDetailList.Free;
end;
procedure TfrBackground.SetTestResult;
var
TestResultQuery: TDAOResult;
I: integer;
begin
FTestResult := TTestResult.Create;
TestResultQuery := TDAOResult.Create;
try
FTestResult.UserID := gUser.UserID;
FTestResult.TestIndex := FTestContainer.TestIndex;
FTestResult.Mark := 1;
// TestResultQuery.InsertUserTestResult(FTestResult);
//
// for I := 0 to FTestResultDetailList.Count - 1 do
// begin
// TestResultQuery.InsertUserTestResultDetail
// (FTestResultDetailList.Items[I]);
// end;
// SetTestScore(FTestResult);
// todo : Score, Right, Wrong 파악은 어디서 ?
// TestResultQuery.UpdateUserTestResult(FTestResult);
// todo : Update 하여 Right, Wrong, Score 입력 해야 함.
finally
FTestResult.Free;
TestResultQuery.Free;
end;
end;
procedure TfrBackground.SetTestResultDetail
(TestResultDetails: TList<TTestResultDetail>);
var
I: integer;
begin
for I := 0 to TestResultDetails.Count - 1 do
FTestResultDetailList.Add(TestResultDetails.Items[I]);
TestResultDetails.Free;
end;
procedure TfrBackground.SetTestResultDetail
(TestResultDetail: TTestResultDetail);
begin
FTestResultDetailList.Add(TestResultDetail);
end;
procedure TfrBackground.SetTestResultDetail(Point: integer; Correct: string);
var
TestResultDetail: TTestResultDetail;
begin
TestResultDetail := TTestResultDetail.Create;
TestResultDetail.QuizNumber := FTestContainer.GetCurrentQuiz.QuizNumber;
TestResultDetail.Answer := Correct;
TestResultDetail.Point := Point;
TestResultDetail.Section := FTestContainer.GetCurrentQuiz.Kind;
FTestResultDetailList.Add(TestResultDetail);
end;
procedure TfrBackground.ShowSpeaking;
begin
// fmSpeaking.BringToFront;
end;
procedure TfrBackground.ShowWriting;
begin
// fmWriting.BringToFront;
end;
procedure TfrBackground.SetTest(CopyTestContainer: TTest);
begin
FTestContainer := CopyTestContainer;
SetQuestion;
end;
procedure TfrBackground.SetQuestion;
begin
FKind := FTestContainer.GetCurrentQuiz.Kind;
case FKind of
qkListening:
begin
ShowListening;
fmListening.Binding(FTestContainer.GetCurrentQuiz as TLRQuiz);
end;
// qkSpeaking:
// begin
// ShowSpeaking;
// fmSpeaking.Binding(FTestContainer.GetCurrentQuiz);
// end;
qkReading:
begin
ShowReading;
fmReading.Binding(FTestContainer.GetCurrentQuiz);
end;
// qkWriting:
// begin
// ShowWriting;
// fmWriting.Binding(FTestContainer.GetCurrentQuiz as TWriting);
// end;
end;
end;
end.
|
unit UGenerico;
interface
uses DateUtils, SysUtils;
type Generico = class
protected
Id : Integer;
Descricao : string[100];
DataCadastro : TDateTime;
DataAlteracao : TDateTime;
public
Constructor CrieObjeto;
Destructor Destrua_Se;
Procedure setId (vId : integer);
Procedure setDescricao (vDescricao : string);
Procedure setDataCadastro (vDataCadastro : TDateTime);
Procedure setDataAlteracao (vDataAlteracao : TDateTime);
Function getId : integer;
Function getDescricao : string;
Function getDataCadastro :TDateTime;
Function getDataAlteracao : TDateTime;
end;
implementation
{ Generico }
constructor Generico.CrieObjeto;
var dataAtual : TDateTime;
begin
dataAtual := Date;
Id := 0;
Descricao := '';
DataCadastro := dataAtual;
DataAlteracao:= dataAtual;
end;
destructor Generico.Destrua_Se;
begin
end;
function Generico.getDataCadastro: TDateTime;
begin
Result := DataCadastro;
end;
function Generico.getDataAlteracao: TDateTime;
begin
Result := DataAlteracao;
end;
function Generico.getDescricao: string;
begin
Result := Descricao;
end;
function Generico.getId: integer;
begin
Result := Id;
end;
procedure Generico.setDataCadastro(vDataCadastro: TDateTime);
begin
DataCadastro := vDataCadastro;
end;
procedure Generico.setDataAlteracao(vDataAlteracao: TDateTime);
begin
DataAlteracao := vDataAlteracao;
end;
procedure Generico.setDescricao(vDescricao: string);
begin
Descricao := vDescricao;
end;
procedure Generico.setId(vId: integer);
begin
Id := vId;
end;
end.
|
unit xStringsF;
interface
Function NumericalWords(Word1,Word2,Word3:String;Num:integer): String;
Function DownRegister(Str:string):String;
Function Cript(CriptString:String):String;
Function UnCript(UnCriptString:String):String;
implementation
Uses SysUtils;
////////////////////////////////////////////////////////////////////////////////
//
// ФУНКЦИЯ: NumericalWords
//
// НАЗНАЧЕНИЕ: В зависимости от числа возвращает слово в правильном падеже.
//
// ПАРАМЕТРЫ:
// Word1 - Слово в Именительном падеже.
// Word2 - Слово в Родительном падеже.
// Word3 - Слово во множественом числе и Именительном падеже.
// Num - Число по которому будет определен правильный падеж и число.
//
Function NumericalWords(Word1,Word2,Word3:String;Num:integer): String;
Var
NumStr: String[32];
LenStr,TestNum: Integer;
begin
case Num of
1: NumericalWords := Word1;
2..4: NumericalWords := Word2;
5..20,0: NumericalWords := Word3;
else
begin
NumStr := IntToStr(Num);
LenStr := Length(NumStr);
if LenStr > 1 then
Try
TestNum := StrToInt(NumStr[LenStr-1]);
Except
End;
if TestNum > 1 then
Try
Delete(NumStr,1,LenStr-1);
Except
End
else
Try
Delete(NumStr,1,LenStr-2);
Except
End;
Num := StrToInt(NumStr);
case Num of
1: NumericalWords := Word1;
2..4: NumericalWords := Word2;
5..20,0: NumericalWords := Word3;
end;
end;
end;
end;
////////////////////////////////////////////////////////////////////////////////
//
// ФУНКЦИЯ: DownRegister
//
// НАЗНАЧЕНИЕ: Переводит полученную строку на нижний регистр.
//
// ПАРАМЕТРЫ:
// Str - Строка, которую необходимо перевести на пониженый регистр.
//
Function DownRegister(Str:string):String;
Var
RStr: string[128];
I,DL: integer;
begin
RStr := '';
DL := length(Str);
For I:=1 to DL do
begin
If ((ORD(Str[I])<=90) and (ORD(Str[I])>=65)) or
((ORD(Str[I])>=192) and (ORD(Str[I])<=223)) or (ORD(Str[I])=168)
then
If ORD(Str[I])=168 then
RStr := RStr + CHR(ORD(Str[I])+16)
else
RStr := RStr + CHR(ORD(Str[I])+32)
else
RStr := RStr + Str[I];
end;
DownRegister := RStr;
end;
////////////////////////////////////////////////////////////////////////////////
//
// ФУНКЦИЯ: Cript
//
// НАЗНАЧЕНИЕ: Шифрует строку путём замены символов.
//
// ПАРАМЕТРЫ:
// CriptString - Строка, которую необходимо зашифровать.
//
Function Cript(CriptString:String):String;
Var
I: integer;
R: String;
begin
R := CriptString;
For I := 1 to Length(CriptString) do {40}
CriptString[I] := Chr(Ord(R[I])+(I-20));
Cript := CriptString;
end;
////////////////////////////////////////////////////////////////////////////////
//
// ФУНКЦИЯ: UnCript
//
// НАЗНАЧЕНИЕ: Дешифрует строку путём замены символов.
//
// ПАРАМЕТРЫ:
// UnCriptString - Строка, которую необходимо дешифровать.
//
Function UnCript(UnCriptString:String):String;
Var
I: integer;
R: String;
begin
R := UnCriptString;
For I := 1 to Length(UnCriptString) do
UnCriptString[I] := Chr(Ord(R[I])-(I-20));
UnCript := UnCriptString;
end;
end.
|
unit FileInfoSet;
interface
uses Classes,
sysUtils,
InternalTypes;
type
tFileInfoSet = class(tStringList)
private
public
constructor Create();
function AddSizeFromInfo(Info : TSearchRec; LimIndex : Integer; TypeExt, Key : String) : UInt64;
function GetJSON() : AnsiString;
procedure dumpData();
end;
implementation
uses DirectoryStat;
constructor tFileInfoSet.Create();
begin
// Sorted := true;
Duplicates := dupError;
OwnsObjects := False;
end;
function tFileInfoSet.AddSizeFromInfo(Info : TSearchRec; LimIndex : Integer; TypeExt, Key : String) : UInt64;
var i : Integer;
var DirStat : tDirectoryStat;
begin
if key='' then
key := '_n/a_';
i := indexOf(Key);
if i = -1 then
begin
DirStat := tDirectoryStat.Create;
i := AddObject(Key,DirStat);
//writeln('added [',i,'] key=',Key);
end;
DirStat := Objects[i] as tDirectoryStat;
Result := DirStat.AddFileStat(info,LimIndex,TypeExt);
end;
procedure tFileInfoSet.dumpData();
var i : integer;
var DirStat : tDirectoryStat;
begin
writeln('=-=-=-=-=-=-=-=-=-=');
for i:= 0 to pred(Count) do
begin
DirStat := Objects[i] as tDirectoryStat;
writeln('[',i,']', Strings[i],':>');
DirStat.dumpData;
end;
writeln;
end;
function tFileInfoSet.GetJSON() : AnsiString;
var i : integer;
var DirStat : tDirectoryStat;
begin
Result := '"FileInfoSet" : [';
for i:= 0 to pred(Count) do
begin
DirStat := Objects[i] as tDirectoryStat;
Result := Result + '{ "Name" : "'+Strings[i]+'", '+DirStat.GetJSON() + '}' + VirguleLast[i<>pred(count)];
end;
Result := Result + ']'
end;
end. |
unit HttpCache;
interface
uses
System.Generics.Collections,
System.SysUtils;
type
EHttpCache = class(Exception);
// Simple in-memory cache
THttpCache = class
private type
TCache = TDictionary<string, string>;
private
Cache: TCache;
public
constructor Create;
destructor Destroy; override;
function Contains(const Url: string): Boolean;
function GetContent(const Url: string): string;
procedure SetContent(const Url, Content: string);
end;
implementation
constructor THttpCache.Create;
begin
inherited Create;
Cache := TCache.Create;
end;
destructor THttpCache.Destroy;
begin
Cache.Free;
inherited;
end;
function THttpCache.Contains(const Url: string): Boolean;
begin
Result := Cache.ContainsKey(Url);
end;
function THttpCache.GetContent(const Url: string): string;
begin
if not Cache.TryGetValue(Url, Result) then
raise EHttpCache.Create('THttpCache.GetContent: Url not found');
end;
procedure THttpCache.SetContent(const Url, Content: string);
begin
Cache.AddOrSetValue(Url, Content);
end;
end.
|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
/// <summary> DBX Client </summary>
unit Data.DbxSocketChannelNative;
{$Z+}
interface
uses
Data.DBXCommon,
System.SysUtils,
Data.DBXTransport,
IPPeerAPI,
Data.DBXRSAFilter
{$IFNDEF POSIX}
, System.Win.ScktComp
{$ENDIF}
;
type
TDBXSocketChannel = class(TDBXChannel)
strict private
FCommLayer: TDBXCommunicationLayer;
protected
function GetChannelInfo: TDBXChannelInfo; override;
public
constructor Create; overload;
constructor Create( const id: Integer); overload;
destructor Destroy; override;
procedure Open; override;
procedure Close; override;
procedure Terminate;
function Read(const Buffer: TBytes; const Offset: Integer; const Count: Integer): Integer; override;
function Write(const Buffer: TBytes; const Offset: Integer; const Count: Integer): Integer; override;
end;
{$IFNDEF POSIX}
TDBXTCPLayer = class(TDBXCommunicationLayer)
strict private
FTcpClient: TClientSocket;
FConnected: boolean;
public
constructor Create; override;
destructor Destroy; override;
procedure Open(const DBXProperties: TDBXProperties); override;
procedure Close; override;
function Read(const Buffer: TBytes; const Offset: Integer; const Count: Integer): Integer; override;
function Write(const Buffer: TBytes; const Offset: Integer; const Count: Integer): Integer; override;
procedure Terminate; override;
function Info: string; override;
end;
{$ENDIF}
TDBXIdTCPLayer = class(TDBXCommunicationLayer)
strict private
FIdSocket: IIPTCPClient;
FConnected: boolean;
FIPImplementationID: string;
protected
function ReadData(const Buffer: TBytes; const Offset: Integer; const Count: Integer): Integer;
function CreateClientSocket: IIPTCPClient; virtual;
public
constructor Create; override;
destructor Destroy; override;
procedure Open(const DBXProperties: TDBXProperties); override;
procedure Close; override;
function Read(const Buffer: TBytes; const Offset: Integer; const Count: Integer): Integer; override;
function Write(const Buffer: TBytes; const Offset: Integer; const Count: Integer): Integer; override;
procedure Terminate; override;
function Info: string; override;
end;
implementation
uses
Data.DBXClientResStrs;
{ TDBXSocketChannel }
procedure TDBXSocketChannel.Close;
begin
if FCommLayer <> nil then
begin
FCommLayer.Close;
FreeAndNil(FCommLayer);
end;
FreeAndNil(FChannelInfo);
end;
procedure TDBXSocketChannel.Terminate;
begin
FreeAndNil(FChannelInfo);
if FCommLayer <> nil then
begin
FCommLayer.Terminate;
try
FreeAndNil(FCommLayer);
except
// ignore
end;
end;
end;
constructor TDBXSocketChannel.Create;
begin
inherited Create;
end;
constructor TDBXSocketChannel.Create( const id: Integer);
begin
inherited Create;
end;
destructor TDBXSocketChannel.Destroy;
begin
Close;
inherited Destroy;
end;
function TDBXSocketChannel.GetChannelInfo: TDBXChannelInfo;
begin
Result := FChannelInfo;
end;
procedure TDBXSocketChannel.Open;
var
CommProtocol: String;
begin
Close;
CommProtocol := DbxProperties[TDBXPropertyNames.CommunicationProtocol];
if CommProtocol = '' then
CommProtocol := 'tcp/ip'; // default communication layer
// get communication layer from the communication factory
FCommLayer := TDBXCommunicationLayerFactory.communicationLayer(CommProtocol);
if FCommLayer = nil then
Raise TDBXError.Create(0, Format(SNoRegisteredLayer, [CommProtocol, TDBXCommunicationLayer.ClassName, TDBXCommunicationLayerFactory.ClassName]));
FCommLayer.Open(DBXProperties);
FChannelInfo := TDBXSocketChannelInfo.Create(0, FCommLayer.Info);
end;
function TDBXSocketChannel.Read(const Buffer: TBytes; const Offset,
Count: Integer): Integer;
begin
// Assert(Offset = 0);
Result := FCommLayer.Read(Buffer, Offset, Count);
end;
function TDBXSocketChannel.Write(const Buffer: TBytes; const Offset,
Count: Integer): Integer;
begin
// Assert(Offset = 0);
Result := FCommLayer.Write(Buffer, Offset, Count);
end;
{TDBXTCPLayer}
{$IFNDEF POSIX}
procedure TDBXTCPLayer.Close;
begin
if FTcpClient <> nil then
begin
if not Terminated then
begin
inherited Terminate;
FTcpClient.Close;
end;
try
FreeAndNil(FTcpClient);
except on ESocketError do
// nothing
end;
end;
end;
procedure TDBXTCPLayer.Terminate;
begin
if not Terminated then
FTcpClient.Socket.Close(true);
end;
constructor TDBXTCPLayer.Create;
begin
end;
destructor TDBXTCPLayer.Destroy;
begin
Close;
end;
function TDBXTCPLayer.Info: String;
begin
Result := FTcpClient.Address;
end;
procedure TDBXTCPLayer.Open(const DBXProperties: TDBXProperties);
var
timeout: string;
commTimeout: string;
begin
Close;
if FTcpClient = nil then
FTcpClient := TClientSocket.Create(nil);
FTcpClient.Host := DbxProperties[TDBXPropertyNames.HostName];
FTcpClient.Port := DbxProperties.GetInteger(TDBXPropertyNames.Port);
FTcpClient.ClientType := ctBlocking;
timeout := DbxProperties[TDBXPropertyNames.ConnectTimeout];
if timeout = '' then
ConnectTimeout := 0
else
ConnectTimeout := StrToInt(timeout);
commTimeout := DbxProperties[TDBXPropertyNames.CommunicationTimeout];
if commTimeout = '' then
CommunicationTimeout := 0
else
CommunicationTimeout := StrToInt(commTimeout);
FConnected := false;
FTcpClient.Open();
end;
function TDBXTCPLayer.Read(const Buffer: TBytes; const Offset,
Count: Integer): Integer;
begin
if not FTcpClient.Socket.Connected then
exit(-1);
if FConnected and (CommunicationTimeout <> 0) then
begin
try
TDBXScheduler.Instance.AddEvent(IntPtr(Pointer(Self)), procedure begin
Terminate;
end, CommunicationTimeout);
try
Result := FTcpClient.Socket.ReceiveBuf(Buffer[Offset], Count);
finally
if TDBXScheduler.Instance <> nil then
TDBXScheduler.Instance.CancelEvent(IntPtr(Pointer(Self)))
end
except
on E: Exception do
raise TDBXError.Create(SCommunicationTimeout)
end;
if Terminated then
raise TDBXError.Create(SCommunicationTimeout)
end
else if not FConnected and (ConnectTimeout <> 0) then
begin
try
TDBXScheduler.Instance.AddEvent(IntPtr(Pointer(Self)), procedure begin
if not FConnected then
Terminate;
end, ConnectTimeout);
try
Result := FTcpClient.Socket.ReceiveBuf(Buffer[Offset], Count);
finally
if TDBXScheduler.Instance <> nil then
TDBXScheduler.Instance.CancelEvent(IntPtr(Pointer(Self)))
end
except
on E: Exception do
raise TDBXError.Create(SConnectionTimeout)
end;
FConnected := true;
if Terminated then
raise TDBXError.Create(SConnectionTimeout)
end else
begin
Result := FTcpClient.Socket.ReceiveBuf(Buffer[Offset], Count);
end;
if Result = 0 then
Result := -1; // we cannot have zero with blocking - close the communication
end;
function TDBXTCPLayer.Write(const Buffer: TBytes; const Offset,
Count: Integer): Integer;
begin
// Assert(Offset = 0);
if FTcpClient <> nil then
begin
FTcpClient.Socket.SendBuf(Buffer[Offset], Count);
Result := Count
end
else
Result := -1;
end;
{$ENDIF}
{ TDBXIdTCPLayer }
procedure TDBXIdTCPLayer.Close;
begin
if FIdSocket <> nil then
begin
if not Terminated then
begin
inherited Terminate;
if FIdSocket.IOHandler <> nil then
FIdSocket.IOHandler.Close;
end;
try
FIdSocket := nil;
except on Exception do
// nothing
end;
end;
end;
constructor TDBXIdTCPLayer.Create;
begin
inherited;
end;
function TDBXIdTCPLayer.CreateClientSocket: IIPTCPClient;
begin
Result := PeerFactory.CreatePeer(FIPImplementationID, IIPTCPClient, nil) as IIPTCPClient;
end;
destructor TDBXIdTCPLayer.Destroy;
begin
Close;
inherited;
end;
function TDBXIdTCPLayer.Info: string;
begin
Result := FIdSocket.BoundIP;
end;
procedure TDBXIdTCPLayer.Open(const DBXProperties: TDBXProperties);
var
timeout: String;
commTimeout: String;
begin
Close;
FIPImplementationID := DbxProperties[TDBXPropertyNames.IPImplementationID];
if FIdSocket = nil then
FIdSocket := CreateClientSocket;
FIdSocket.Host := DbxProperties[TDBXPropertyNames.HostName];
FIdSocket.Port := DbxProperties.GetInteger(TDBXPropertyNames.Port);
timeout := DbxProperties[TDBXPropertyNames.ConnectTimeout];
if timeout = '' then
ConnectTimeout := 0
else
ConnectTimeout := StrToInt(timeout);
commTimeout := DbxProperties[TDBXPropertyNames.CommunicationTimeout];
if commTimeout = '' then
CommunicationTimeout := 0
else
CommunicationTimeout := StrToInt(commTimeout);
FIdSocket.UseNagle := false;
FIdSocket.Connect;
FConnected := false;
end;
function TDBXIdTCPLayer.Read(const Buffer: TBytes; const Offset,
Count: Integer): Integer;
begin
if Terminated then
exit(-1);
if FConnected and (CommunicationTimeout > 0) then
begin
try
TDBXScheduler.Instance.AddEvent(IntPtr(Pointer(Self)), procedure begin
Terminate;
end, CommunicationTimeout);
Result := ReadData(Buffer, Offset, Count);
if TDBXScheduler.Instance <> nil then
TDBXScheduler.Instance.CancelEvent(IntPtr(Pointer(Self)))
except
on E: Exception do
raise TDBXError.Create(SCommunicationTimeout)
end;
if Terminated then
raise TDBXError.Create(SCommunicationTimeout)
end
else if not FConnected and (ConnectTimeout > 0) then
begin
try
TDBXScheduler.Instance.AddEvent(IntPtr(Pointer(Self)), procedure begin
if not FConnected then
Terminate;
end, ConnectTimeout);
Result := ReadData(Buffer, Offset, Count);
if TDBXScheduler.Instance <> nil then
TDBXScheduler.Instance.CancelEvent(IntPtr(Pointer(Self)))
except
on E: Exception do
raise TDBXError.Create(SConnectionTimeout)
end;
if Terminated then
raise TDBXError.Create(SConnectionTimeout)
end
else
Result := ReadData(Buffer, Offset, Count);
FConnected := true;
end;
function TDBXIdTCPLayer.ReadData(const Buffer: TBytes; const Offset,
Count: Integer): Integer;
var
idx, size, available, total: Integer;
Buff: TBytes;
begin
idx := Offset;
size := Count - 1;
Buffer[idx] := FIdSocket.IOHandler.ReadByte;
Inc(idx);
total := 1;
available := FIdSocket.IOHandler.InputBuffer.Size;
while (size > 0) and (available > 0) do
begin
if size <= available then
available := size;
FIdSocket.IOHandler.ReadBytes(Buff, available, false);
Move(Buff[0], Buffer[idx], available);
idx := idx + available;
total := total + available;
size := size - available;
available := FIdSocket.IOHandler.InputBuffer.Size;
end;
exit(total);
end;
procedure TDBXIdTCPLayer.Terminate;
begin
if FIdSocket <> nil then
begin
if not Terminated then
begin
inherited Terminate;
FIdSocket.IOHandler.Close;
end;
end;
end;
function TDBXIdTCPLayer.Write(const Buffer: TBytes; const Offset,
Count: Integer): Integer;
begin
if Terminated then
exit(-1)
else if FIdSocket <> nil then
begin
FIdSocket.IOHandler.Write(Buffer, Count, Offset);
exit(Count);
end
else
exit(-1);
end;
initialization
{$IFNDEF POSIX}
TDBXCommunicationLayerFactory.RegisterLayer('xtcp/ip', TDBXTCPLayer);
{$ENDIF}
TDBXCommunicationLayerFactory.RegisterLayer('tcp/ip', TDBXIdTCPLayer);
TTransportFilterFactory.RegisterFilter(TTransportCypherFilter);
TTransportFilterFactory.RegisterFilter(TRSAFilter);
finalization
{$IFNDEF POSIX}
TDBXCommunicationLayerFactory.UnregisterLayer('xtcp/ip');
{$ENDIF}
TDBXCommunicationLayerFactory.UnregisterLayer('tcp/ip');
TTransportFilterFactory.UnregisterFilter(TTransportCypherFilter);
TTransportFilterFactory.UnregisterFilter(TRSAFilter);
end.
|
{**************************************************************************************************}
{ }
{ Project JEDI Code Library (JCL) }
{ }
{ The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); }
{ you may not use this file except in compliance with the License. You may obtain a copy of the }
{ License at http://www.mozilla.org/MPL/ }
{ }
{ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF }
{ ANY KIND, either express or implied. See the License for the specific language governing rights }
{ and limitations under the License. }
{ }
{ The Original Code is Queue.pas. }
{ }
{ The Initial Developer of the Original Code is Jean-Philippe BEMPEL aka RDM. Portions created by }
{ Jean-Philippe BEMPEL are Copyright (C) Jean-Philippe BEMPEL (rdm_30 att yahoo dott com) }
{ All rights reserved. }
{ }
{ Contributors: }
{ Florent Ouchet (outchy) }
{ }
{**************************************************************************************************}
{ }
{ The Delphi Container Library }
{ }
{**************************************************************************************************}
{ }
{ Last modified: $Date:: 2008-06-05 15:35:37 +0200 (jeu., 05 juin 2008) $ }
{ Revision: $Rev:: 2376 $ }
{ Author: $Author:: obones $ }
{ }
{**************************************************************************************************}
unit JclQueues;
{$I jcl.inc}
interface
uses
{$IFDEF UNITVERSIONING}
JclUnitVersioning,
{$ENDIF UNITVERSIONING}
{$IFDEF SUPPORTS_GENERICS}
{$IFDEF CLR}
System.Collections.Generic,
{$ENDIF CLR}
JclAlgorithms,
{$ENDIF SUPPORTS_GENERICS}
JclBase, JclAbstractContainers, JclContainerIntf, JclSynch;
{$I containers\JclContainerCommon.imp}
{$I containers\JclQueues.imp}
{$I containers\JclQueues.int}
type
(*$JPPEXPANDMACRO JCLQUEUEINT(TJclIntfQueue,IJclIntfQueue,TJclIntfAbstractContainer,JclBase.TDynIInterfaceArray, IJclIntfEqualityComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,const ,AInterface,IInterface)*)
(*$JPPEXPANDMACRO JCLQUEUEINT(TJclAnsiStrQueue,IJclAnsiStrQueue,TJclAnsiStrAbstractContainer,JclBase.TDynAnsiStringArray, IJclStrContainer\, IJclAnsiStrContainer\, IJclAnsiStrEqualityComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,const ,AString,AnsiString)*)
(*$JPPEXPANDMACRO JCLQUEUEINT(TJclWideStrQueue,IJclWideStrQueue,TJclWideStrAbstractContainer,JclBase.TDynWideStringArray, IJclStrContainer\, IJclWideStrContainer\, IJclWideStrEqualityComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,const ,AString,WideString)*)
{$IFDEF CONTAINER_ANSISTR}
TJclStrQueue = TJclAnsiStrQueue;
{$ENDIF CONTAINER_ANSISTR}
{$IFDEF CONTAINER_WIDESTR}
TJclStrQueue = TJclWideStrQueue;
{$ENDIF CONTAINER_WIDESTR}
(*$JPPEXPANDMACRO JCLQUEUEINT(TJclSingleQueue,IJclSingleQueue,TJclSingleAbstractContainer,JclBase.TDynSingleArray, IJclSingleContainer\, IJclSingleEqualityComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,const ,AValue,Single)*)
(*$JPPEXPANDMACRO JCLQUEUEINT(TJclDoubleQueue,IJclDoubleQueue,TJclDoubleAbstractContainer,JclBase.TDynDoubleArray, IJclDoubleContainer\, IJclDoubleEqualityComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,const ,AValue,Double)*)
(*$JPPEXPANDMACRO JCLQUEUEINT(TJclExtendedQueue,IJclExtendedQueue,TJclExtendedAbstractContainer,JclBase.TDynExtendedArray, IJclExtendedContainer\, IJclExtendedEqualityComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,const ,AValue,Extended)*)
{$IFDEF MATH_EXTENDED_PRECISION}
TJclFloatQueue = TJclExtendedQueue;
{$ENDIF MATH_EXTENDED_PRECISION}
{$IFDEF MATH_DOUBLE_PRECISION}
TJclFloatQueue = TJclDoubleQueue;
{$ENDIF MATH_DOUBLE_PRECISION}
{$IFDEF MATH_SINGLE_PRECISION}
TJclFloatQueue = TJclSingleQueue;
{$ENDIF MATH_SINGLE_PRECISION}
(*$JPPEXPANDMACRO JCLQUEUEINT(TJclIntegerQueue,IJclIntegerQueue,TJclIntegerAbstractContainer,JclBase.TDynIntegerArray, IJclIntegerEqualityComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,,AValue,Integer)*)
(*$JPPEXPANDMACRO JCLQUEUEINT(TJclCardinalQueue,IJclCardinalQueue,TJclCardinalAbstractContainer,JclBase.TDynCardinalArray, IJclCardinalEqualityComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,,AValue,Cardinal)*)
(*$JPPEXPANDMACRO JCLQUEUEINT(TJclInt64Queue,IJclInt64Queue,TJclInt64AbstractContainer,JclBase.TDynInt64Array, IJclInt64EqualityComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,const ,AValue,Int64)*)
{$IFNDEF CLR}
(*$JPPEXPANDMACRO JCLQUEUEINT(TJclPtrQueue,IJclPtrQueue,TJclPtrAbstractContainer,JclBase.TDynPointerArray, IJclPtrEqualityComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,,APtr,Pointer)*)
{$ENDIF ~CLR}
(*$JPPEXPANDMACRO JCLQUEUEINT(TJclQueue,IJclQueue,TJclAbstractContainer,JclBase.TDynObjectArray, IJclEqualityComparer\, IJclObjectOwner\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,; AOwnsObjects: Boolean,,AObject,TObject)*)
{$IFDEF SUPPORTS_GENERICS}
(*$JPPEXPANDMACRO JCLQUEUEINT(TJclQueue<T>,IJclQueue<T>,TJclAbstractContainer<T>,TJclBase<T>.TDynArray, IJclEqualityComparer<T>\, IJclItemOwner<T>\,,,,,; AOwnsItems: Boolean,const ,AItem,T)*)
// E = external helper to compare items for equality (GetHashCode is not used)
TJclQueueE<T> = class(TJclQueue<T>, {$IFDEF THREADSAFE} IJclLockable, {$ENDIF THREADSAFE}
IJclIntfCloneable, IJclCloneable, IJclPackable, IJclGrowable, IJclContainer, IJclQueue<T>, IJclItemOwner<T>)
private
FEqualityComparer: IEqualityComparer<T>;
protected
procedure AssignPropertiesTo(Dest: TJclAbstractContainerBase); override;
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function ItemsEqual(const A, B: T): Boolean; override;
{ IJclCloneable }
function IJclCloneable.Clone = ObjectClone;
{ IJclIntfCloneable }
function IJclIntfCloneable.Clone = IntfClone;
public
constructor Create(const AEqualityComparer: IEqualityComparer<T>; ACapacity: Integer; AOwnsItems: Boolean);
property EqualityComparer: IEqualityComparer<T> read FEqualityComparer write FEqualityComparer;
end;
// F = function to compare items for equality
TJclQueueF<T> = class(TJclQueue<T>, {$IFDEF THREADSAFE} IJclLockable, {$ENDIF THREADSAFE}
IJclIntfCloneable, IJclCloneable, IJclPackable, IJclGrowable, IJclContainer, IJclQueue<T>, IJclItemOwner<T>)
protected
function CreateEmptyContainer: TJclAbstractContainerBase; override;
{ IJclCloneable }
function IJclCloneable.Clone = ObjectClone;
{ IJclIntfCloneable }
function IJclIntfCloneable.Clone = IntfClone;
public
constructor Create(AEqualityCompare: TEqualityCompare<T>; ACapacity: Integer; AOwnsItems: Boolean);
end;
// I = items can compare themselves to an other
TJclQueueI<T: IEquatable<T>> = class(TJclQueue<T>, {$IFDEF THREADSAFE} IJclLockable, {$ENDIF THREADSAFE}
IJclIntfCloneable, IJclCloneable, IJclPackable, IJclGrowable, IJclContainer, IJclQueue<T>, IJclItemOwner<T>)
protected
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function ItemsEqual(const A, B: T): Boolean; override;
{ IJclCloneable }
function IJclCloneable.Clone = ObjectClone;
{ IJclIntfCloneable }
function IJclIntfCloneable.Clone = IntfClone;
end;
{$ENDIF SUPPORTS_GENERICS}
{$IFDEF UNITVERSIONING}
const
UnitVersioning: TUnitVersionInfo = (
RCSfile: '$URL: https://jcl.svn.sourceforge.net:443/svnroot/jcl/tags/JCL-1.102-Build3072/jcl/source/prototypes/JclQueues.pas $';
Revision: '$Revision: 2376 $';
Date: '$Date: 2008-06-05 15:35:37 +0200 (jeu., 05 juin 2008) $';
LogPath: 'JCL\source\common'
);
{$ENDIF UNITVERSIONING}
implementation
uses
SysUtils;
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclIntfQueue.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclIntfQueue.Create(Size + 1);
AssignPropertiesTo(Result);
end;
}
(*$JPPEXPANDMACRO JCLQUEUEIMP(TJclIntfQueue,,,const ,AInterface,IInterface,nil,JclBase.MoveArray,FreeObject)*)
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclAnsiStrQueue.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclAnsiStrQueue.Create(Size + 1);
AssignPropertiesTo(Result);
end;
}
(*$JPPEXPANDMACRO JCLQUEUEIMP(TJclAnsiStrQueue,,,const ,AString,AnsiString,'',JclBase.MoveArray,FreeString)*)
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclWideStrQueue.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclWideStrQueue.Create(Size + 1);
AssignPropertiesTo(Result);
end;
}
(*$JPPEXPANDMACRO JCLQUEUEIMP(TJclWideStrQueue,,,const ,AString,WideString,'',JclBase.MoveArray,FreeString)*)
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclSingleQueue.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclSingleQueue.Create(Size + 1);
AssignPropertiesTo(Result);
end;
}
(*$JPPEXPANDMACRO JCLQUEUEIMP(TJclSingleQueue,,,const ,AValue,Single,0.0,JclBase.MoveArray,FreeSingle)*)
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclDoubleQueue.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclDoubleQueue.Create(Size + 1);
AssignPropertiesTo(Result);
end;
}
(*$JPPEXPANDMACRO JCLQUEUEIMP(TJclDoubleQueue,,,const ,AValue,Double,0.0,JclBase.MoveArray,FreeDouble)*)
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclExtendedQueue.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclExtendedQueue.Create(Size + 1);
AssignPropertiesTo(Result);
end;
}
(*$JPPEXPANDMACRO JCLQUEUEIMP(TJclExtendedQueue,,,const ,AValue,Extended,0.0,JclBase.MoveArray,FreeExtended)*)
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclIntegerQueue.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclIntegerQueue.Create(Size + 1);
AssignPropertiesTo(Result);
end;
}
(*$JPPEXPANDMACRO JCLQUEUEIMP(TJclIntegerQueue,,,,AValue,Integer,0,JclBase.MoveArray,FreeInteger)*)
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclCardinalQueue.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclCardinalQueue.Create(Size + 1);
AssignPropertiesTo(Result);
end;
}
(*$JPPEXPANDMACRO JCLQUEUEIMP(TJclCardinalQueue,,,,AValue,Cardinal,0,JclBase.MoveArray,FreeCardinal)*)
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclInt64Queue.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclInt64Queue.Create(Size + 1);
AssignPropertiesTo(Result);
end;
}
(*$JPPEXPANDMACRO JCLQUEUEIMP(TJclInt64Queue,,,const ,AValue,Int64,0,JclBase.MoveArray,FreeInt64)*)
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$IFNDEF CLR}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclPtrQueue.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclPtrQueue.Create(Size + 1);
AssignPropertiesTo(Result);
end;
}
(*$JPPEXPANDMACRO JCLQUEUEIMP(TJclPtrQueue,,,,APtr,Pointer,nil,JclBase.MoveArray,FreePointer)*)
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$ENDIF ~CLR}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclQueue.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclQueue.Create(Size + 1, False);
AssignPropertiesTo(Result);
end;
}
(*$JPPEXPANDMACRO JCLQUEUEIMP(TJclQueue,; AOwnsObjects: Boolean,AOwnsObjects,,AObject,TObject,nil,JclBase.MoveArray,FreeObject)*)
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$IFDEF SUPPORTS_GENERICS}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER}
(*$JPPEXPANDMACRO JCLQUEUEIMP(TJclQueue<T>,; AOwnsItems: Boolean,AOwnsItems,const ,AItem,T,Default(T),TJclBase<T>.MoveArray,FreeItem)*)
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
//=== { TJclQueueE<T> } ======================================================
constructor TJclQueueE<T>.Create(const AEqualityComparer: IEqualityComparer<T>;
ACapacity: Integer; AOwnsItems: Boolean);
begin
inherited Create(ACapacity, AOwnsItems);
FEqualityComparer := AEqualityComparer;
end;
procedure TJclQueueE<T>.AssignPropertiesTo(Dest: TJclAbstractContainerBase);
begin
inherited AssignPropertiesTo(Dest);
if Dest is TJclQueueE<T> then
TJclQueueE<T>(Dest).FEqualityComparer := FEqualityComparer;
end;
function TJclQueueE<T>.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclQueueE<T>.Create(EqualityComparer, Size + 1, False);
AssignPropertiesTo(Result);
end;
function TJclQueueE<T>.ItemsEqual(const A, B: T): Boolean;
begin
if EqualityComparer <> nil then
Result := EqualityComparer.Equals(A, B)
else
Result := inherited ItemsEqual(A, B);
end;
//=== { TJclQueueF<T> } ======================================================
constructor TJclQueueF<T>.Create(AEqualityCompare: TEqualityCompare<T>;
ACapacity: Integer; AOwnsItems: Boolean);
begin
inherited Create(ACapacity, AOwnsItems);
SetEqualityCompare(AEqualityCompare);
end;
function TJclQueueF<T>.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclQueueF<T>.Create(EqualityCompare, Size + 1, False);
AssignPropertiesTo(Result);
end;
//=== { TJclQueueI<T> } ======================================================
function TJclQueueI<T>.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclQueueI<T>.Create(Size + 1, False);
AssignPropertiesTo(Result);
end;
function TJclQueueI<T>.ItemsEqual(const A, B: T): Boolean;
begin
if Assigned(FEqualityCompare) then
Result := FEqualityCompare(A, B)
else
if Assigned(FCompare) then
Result := FCompare(A, B) = 0
else
Result := A.Equals(B);
end;
{$ENDIF SUPPORTS_GENERICS}
{$IFDEF UNITVERSIONING}
initialization
RegisterUnitVersion(HInstance, UnitVersioning);
finalization
UnregisterUnitVersion(HInstance);
{$ENDIF UNITVERSIONING}
end.
|
program Console;
{$MODE DELPHI}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Horse,
Horse.BasicAuthentication, // It's necessary to use the unit
SysUtils;
procedure GetPing(Req: THorseRequest; Res: THorseResponse; Next: TNextProc);
begin
Res.Send('Pong');
end;
procedure OnListen(Horse: THorse);
begin
Writeln(Format('Server is runing on port %d', [Horse.Port]));
end;
function DoLogin(const AUsername, APassword: string): Boolean;
begin
// Here inside you can access your database and validate if username and password are valid
Result := AUsername.Equals('user') and APassword.Equals('password');
end;
begin
// It's necessary to add the middleware in the Horse:
THorse.Use(HorseBasicAuthentication(DoLogin));
// The default header for receiving credentials is "Authorization".
// You can change, if necessary:
// THorse.Use(HorseBasicAuthentication(MyCallbackValidation, THorseBasicAuthenticationConfig.New.Header('X-My-Header-Authorization')));
// You can also ignore routes:
// THorse.Use(HorseBasicAuthentication(MyCallbackValidation, THorseBasicAuthenticationConfig.New.SkipRoutes(['/ping'])));
THorse.Get('/ping', GetPing);
THorse.Listen(9000, OnListen);
end.
|
unit IdStack;
interface
uses
Classes,
IdException,
IdStackConsts, IdGlobal;
type
TIdServeFile = function(ASocket: TIdStackSocketHandle; AFileName: string): cardinal;
// Abstract IdStack class
TIdSunB = packed record
s_b1, s_b2, s_b3, s_b4: byte;
end;
TIdSunW = packed record
s_w1, s_w2: word;
end;
PIdInAddr = ^TIdInAddr;
TIdInAddr = record
case integer of
0: (S_un_b: TIdSunB);
1: (S_un_w: TIdSunW);
2: (S_addr: longword);
end;
TIdSocketListClass = class of TIdSocketList;
TIdSocketList = class
protected
function GetItem(AIndex: Integer): TIdStackSocketHandle; virtual; abstract;
public
procedure Add(AHandle: TIdStackSocketHandle); virtual; abstract;
class function CreateSocketList: TIdSocketList;
procedure Remove(AHandle: TIdStackSocketHandle); virtual; abstract;
function Count: Integer; virtual; abstract;
property Items[AIndex: Integer]: TIdStackSocketHandle read GetItem; default;
End;//TIdSocketList
TIdStack = class
protected
FLastError: Integer;
FLocalAddress: string;
FLocalAddresses: TStrings;
//
procedure PopulateLocalAddresses; virtual; abstract;
function WSGetLocalAddress: string; virtual; abstract;
function WSGetLocalAddresses: TStrings; virtual; abstract;
public
function CheckForSocketError(const AResult: integer = Id_SOCKET_ERROR): boolean; overload;
function CheckForSocketError(const AResult: integer; const AIgnore: array of integer)
: boolean; overload;
constructor Create; reintroduce; virtual;
destructor Destroy; override;
class function CreateStack: TIdStack;
function CreateSocketHandle(const ASocketType: Integer;
const AProtocol: Integer = Id_IPPROTO_IP): TIdStackSocketHandle;
function IsIP(AIP: string): boolean;
procedure RaiseSocketError(const AErr: integer);
function ResolveHost(const AHost: string): string;
// Resolves host passed in sHost. sHost may be an IP or a HostName.
// sIP returns string version of the IP
function WSAccept(ASocket: TIdStackSocketHandle; var VIP: string; var VPort: Integer)
: TIdStackSocketHandle; virtual; abstract;
function WSBind(ASocket: TIdStackSocketHandle; const AFamily: Integer;
const AIP: string; const APort: Integer): Integer; virtual; abstract;
function WSCloseSocket(ASocket: TIdStackSocketHandle): Integer; virtual; abstract;
function WSConnect(const ASocket: TIdStackSocketHandle; const AFamily: Integer;
const AIP: string; const APort: Integer): Integer; virtual; abstract;
function WSGetHostByName(const AHostName: string): string; virtual; abstract;
function WSGetHostName: string; virtual; abstract;
function WSGetHostByAddr(const AAddress: string): string; virtual; abstract;
function WSGetServByName(const AServiceName: string): Integer; virtual; abstract;
function WSGetServByPort(const APortNumber: Integer): TStrings; virtual; abstract;
function WSHToNs(AHostShort: Word): Word; virtual; abstract;
function WSListen(ASocket: TIdStackSocketHandle; ABackLog: Integer): Integer; virtual; abstract;
function WSNToHs(ANetShort: Word): Word; virtual; abstract;
function WSHToNL(AHostLong: LongWord): LongWord; virtual; abstract;
function WSNToHL(ANetLong: LongWord): LongWord; virtual; abstract;
function WSRecv(ASocket: TIdStackSocketHandle; var ABuffer; const ABufferLength, AFlags: Integer)
: Integer; virtual; abstract;
function WSRecvFrom(const ASocket: TIdStackSocketHandle; var ABuffer;
const ALength, AFlags: Integer; var VIP: string; var VPort: Integer): Integer; virtual;
abstract;
function WSSelect(ARead, AWrite, AErrors: TList; ATimeout: Integer): Integer; virtual; abstract;
function WSSend(ASocket: TIdStackSocketHandle; var ABuffer;
const ABufferLength, AFlags: Integer): Integer; virtual; abstract;
function WSSendTo(ASocket: TIdStackSocketHandle; var ABuffer;
const ABufferLength, AFlags: Integer; const AIP: string; const APort: integer): Integer;
virtual; abstract;
function WSSetSockOpt(ASocket: TIdStackSocketHandle; ALevel, AOptName: Integer; AOptVal: PChar;
AOptLen: Integer): Integer; virtual; abstract;
function WSSocket(AFamily, AStruct, AProtocol: Integer): TIdStackSocketHandle; virtual; abstract;
function WSShutdown(ASocket: TIdStackSocketHandle; AHow: Integer): Integer; virtual; abstract;
function WSTranslateSocketErrorMsg(const AErr: integer): string; virtual;
function WSGetLastError: Integer; virtual; abstract;
procedure WSGetPeerName(ASocket: TIdStackSocketHandle; var AFamily: Integer;
var AIP: string; var APort: Integer); virtual; abstract;
procedure WSGetSockName(ASocket: TIdStackSocketHandle; var AFamily: Integer;
var AIP: string; var APort: Integer); virtual; abstract;
function WSGetSockOpt(ASocket: TIdStackSocketHandle; Alevel, AOptname: Integer; AOptval: PChar; var AOptlen: Integer) : Integer; virtual; abstract;
function StringToTInAddr(AIP: string): TIdInAddr;
function TInAddrToString(var AInAddr): string; virtual; abstract;
procedure TranslateStringToTInAddr(AIP: string; var AInAddr); virtual; abstract;
//
property LastError: Integer read FLastError;
property LocalAddress: string read WSGetLocalAddress;
property LocalAddresses: TStrings read WSGetLocalAddresses;
end;
TIdStackClass = class of TIdStack;
EIdStackError = class (EIdException);
EIdStackInitializationFailed = class (EIdStackError);
EIdStackSetSizeExceeded = class (EIdStackError);
var
GStack: TIdStack = nil;
GStackClass: TIdStackClass = nil;
GServeFileProc: TIdServeFile = nil;
GSocketListClass: TIdSocketListClass;
implementation
uses
IdResourceStrings,
SysUtils;
{ TIdStack }
function TIdStack.CheckForSocketError(const AResult: integer): boolean;
begin
Result := CheckForSocketError(AResult, []);
end;
function TIdStack.CheckForSocketError(const AResult: integer;
const AIgnore: array of integer): boolean;
var
i: integer;
begin
Result := false;
if AResult = Id_SOCKET_ERROR then begin
FLastError := WSGetLastError;
for i := Low(AIgnore) to High(AIgnore) do begin
if LastError = AIgnore[i] then begin
Result := True;
exit;
end;
end;
RaiseSocketError(LastError);
end;
end;
function TIdStack.CreateSocketHandle(const ASocketType: Integer;
const AProtocol: Integer = Id_IPPROTO_IP): TIdStackSocketHandle;
begin
result := WSSocket(Id_PF_INET, ASocketType, AProtocol);
if result = Id_INVALID_SOCKET then begin
raise EIdInvalidSocket.Create(RSCannotAllocateSocket);
end;
end;
procedure TIdStack.RaiseSocketError(const AErr: integer);
begin
(*
RRRRR EEEEEE AAAA DDDDD MM MM EEEEEE !! !! !!
RR RR EE AA AA DD DD MMMM MMMM EE !! !! !!
RRRRR EEEE AAAAAA DD DD MM MMM MM EEEE !! !! !!
RR RR EE AA AA DD DD MM MM EE
RR RR EEEEEE AA AA DDDDD MM MM EEEEEE .. .. ..
Please read the note in the next comment.
*)
raise EIdSocketError.CreateError(AErr, WSTranslateSocketErrorMsg(AErr));
(*
It is normal to receive a 10038 exception (10038, NOT others!) here when
*shutting down* (NOT at other times!) servers (NOT clients!).
If you receive a 10038 exception here please see the FAQ at:
http://www.nevrona.com/Indy/FAQ.html
If you get a 10038 exception here, and HAVE NOT read the FAQ and ask about this in the public
forums
you will be publicly flogged, tarred and feathered and your name added to every chain
letter in existence today.
If you insist upon requesting help via our email boxes on the 10038 error that is already
answered in the FAQ and you are simply too slothful to search for your answer and ask your
question in the public forums you may be publicly flogged, tarred and feathered and your name
may be added to every chain letter / EMail in existence today."
Otherwise, if you DID read the FAQ and have further questions, please feel free to ask using
one of the methods (Carefullly note that these methods do not list email) listed on the Tech
Support link at http://www.nevrona.com/Indy/
RRRRR EEEEEE AAAA DDDDD MM MM EEEEEE !! !! !!
RR RR EE AA AA DD DD MMMM MMMM EE !! !! !!
RRRRR EEEE AAAAAA DD DD MM MMM MM EEEE !! !! !!
RR RR EE AA AA DD DD MM MM EE
RR RR EEEEEE AA AA DDDDD MM MM EEEEEE .. .. ..
*)
end;
constructor TIdStack.Create;
begin
// Here so descendants can override and call inherited for future exp since TObject's Create {Do not Localize}
// is not virtual
end;
class function TIdStack.CreateStack: TIdStack;
begin
Result := GStackClass.Create;
end;
function TIdStack.ResolveHost(const AHost: string): string;
begin
// Sometimes 95 forgets who localhost is
if AnsiSameText(AHost, 'LOCALHOST') then begin {Do not Localize}
result := '127.0.0.1'; {Do not Localize}
end else if IsIP(AHost) then begin
result := AHost;
end else begin
result := WSGetHostByName(AHost);
end;
end;
function TIdStack.WSTranslateSocketErrorMsg(const AErr: integer): string;
begin
Result := ''; {Do not Localize}
case AErr of
Id_WSAEINTR: Result := RSStackEINTR;
Id_WSAEBADF: Result := RSStackEBADF;
Id_WSAEACCES: Result := RSStackEACCES;
Id_WSAEFAULT: Result := RSStackEFAULT;
Id_WSAEINVAL: Result := RSStackEINVAL;
Id_WSAEMFILE: Result := RSStackEMFILE;
Id_WSAEWOULDBLOCK: Result := RSStackEWOULDBLOCK;
Id_WSAEINPROGRESS: Result := RSStackEINPROGRESS;
Id_WSAEALREADY: Result := RSStackEALREADY;
Id_WSAENOTSOCK: Result := RSStackENOTSOCK;
Id_WSAEDESTADDRREQ: Result := RSStackEDESTADDRREQ;
Id_WSAEMSGSIZE: Result := RSStackEMSGSIZE;
Id_WSAEPROTOTYPE: Result := RSStackEPROTOTYPE;
Id_WSAENOPROTOOPT: Result := RSStackENOPROTOOPT;
Id_WSAEPROTONOSUPPORT: Result := RSStackEPROTONOSUPPORT;
Id_WSAESOCKTNOSUPPORT: Result := RSStackESOCKTNOSUPPORT;
Id_WSAEOPNOTSUPP: Result := RSStackEOPNOTSUPP;
Id_WSAEPFNOSUPPORT: Result := RSStackEPFNOSUPPORT;
Id_WSAEAFNOSUPPORT: Result := RSStackEAFNOSUPPORT;
Id_WSAEADDRINUSE: Result := RSStackEADDRINUSE;
Id_WSAEADDRNOTAVAIL: Result := RSStackEADDRNOTAVAIL;
Id_WSAENETDOWN: Result := RSStackENETDOWN;
Id_WSAENETUNREACH: Result := RSStackENETUNREACH;
Id_WSAENETRESET: Result := RSStackENETRESET;
Id_WSAECONNABORTED: Result := RSStackECONNABORTED;
Id_WSAECONNRESET: Result := RSStackECONNRESET;
Id_WSAENOBUFS: Result := RSStackENOBUFS;
Id_WSAEISCONN: Result := RSStackEISCONN;
Id_WSAENOTCONN: Result := RSStackENOTCONN;
Id_WSAESHUTDOWN: Result := RSStackESHUTDOWN;
Id_WSAETOOMANYREFS: Result := RSStackETOOMANYREFS;
Id_WSAETIMEDOUT: Result := RSStackETIMEDOUT;
Id_WSAECONNREFUSED: Result := RSStackECONNREFUSED;
Id_WSAELOOP: Result := RSStackELOOP;
Id_WSAENAMETOOLONG: Result := RSStackENAMETOOLONG;
Id_WSAEHOSTDOWN: Result := RSStackEHOSTDOWN;
Id_WSAEHOSTUNREACH: Result := RSStackEHOSTUNREACH;
Id_WSAENOTEMPTY: Result := RSStackENOTEMPTY;
end;
Result := Format(RSStackError, [AErr, Result]);
end;
function TIdStack.IsIP(AIP: string): boolean;
var
s1, s2, s3, s4: string;
function ByteIsOk(const AByte: string): boolean;
begin
result := (StrToIntDef(AByte, -1) > -1) and (StrToIntDef(AByte, 256) < 256);
end;
begin
s1 := Fetch(AIP, '.'); {Do not Localize}
s2 := Fetch(AIP, '.'); {Do not Localize}
s3 := Fetch(AIP, '.'); {Do not Localize}
s4 := AIP;
result := ByteIsOk(s1) and ByteIsOk(s2) and ByteIsOk(s3) and ByteIsOk(s4);
end;
destructor TIdStack.Destroy;
begin
FLocalAddresses.Free;
inherited;
end;
function TIdStack.StringToTInAddr(AIP: string): TIdInAddr;
begin
TranslateStringToTInAddr(AIP, result);
end;
{ TIdSocketList }
class function TIdSocketList.CreateSocketList: TIdSocketList;
Begin
Result := GSocketListClass.Create;
End;//
end.
|
// auteur : Jean-Stéphane Varré
// date : 2010
// objet : Unite pour la lecture de fichier texte en pascal.
// UE : Info 204 - ASD - Université Lille 1
unit U_FichierTexte;
interface
uses SysUtils;
type
FinDeFichier = class(SysUtils.Exception);
procedure ouvrir (nom : STRING);
function lireMotSuivant : STRING;
function lectureTerminee : BOOLEAN;
procedure fermer;
implementation
var
fic : TEXT;
ligne : STRING;
function lectureTerminee : BOOLEAN;
begin
lectureTerminee := eof(fic);
end {lectureTerminee};
procedure ligneSuivante;
begin
if eof(fic) then
raise FinDeFichier.create('Fin de fichier');
readln(fic,ligne);
end {ligneSuivante};
procedure ouvrir (nom : STRING);
begin
assign(fic, nom);
reset(fic);
end {ouvrir};
function lireMotSuivant : STRING;
var
mot : STRING;
p : CARDINAL;
begin
if length(ligne) = 0 then
ligneSuivante;
p := pos(' ',ligne);
if p <> 0 then begin
mot := trim(copy(ligne,1,p));
delete(ligne,1,p);
ligne := trim(ligne);
end else begin
mot := ligne;
ligne := '';
end;
if length(mot) = 0 then
lireMotSuivant := lireMotSuivant
else
lireMotSuivant := mot;
end {lireMotSuivant};
procedure fermer;
begin
ligne := '';
close(fic);
end {fermer};
initialization
ligne := '';
end {U_FichierTexte}.
|
unit Vigilante.Infra.Compilacao.DataAdapter;
interface
uses
Vigilante.Aplicacao.SituacaoBuild, Vigilante.ChangeSetItem.Model;
type
ICompilacaoAdapter = interface(IInterface)
['{0D898A67-AFC6-4FB8-ADCC-7F48FF017276}']
function GetNumero: integer;
function GetNome: string;
function GetURL: string;
function GetSituacao: TSituacaoBuild;
function GetChangesSet: TArray<TChangeSetItem>;
function GetBuilding: boolean;
property Numero: integer read GetNumero;
property Nome: string read GetNome;
property URL: string read GetURL;
property Situacao: TSituacaoBuild read GetSituacao;
property Building: boolean read GetBuilding;
property ChangesSet: TArray<TChangeSetItem> read GetChangesSet;
end;
implementation
end.
|
{ *******************************************************************************
Copyright 2016-2019 Daniele Spinetti
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
******************************************************************************** }
unit Router4D.Props;
{$I Router4D.inc}
interface
uses
System.Classes,
System.SysUtils,
System.Rtti;
type
TThreadMode = (Posting, Main, Async, Background);
TCloneEventCallback = function(const AObject: TObject): TObject of object;
TCloneEventMethod = TFunc<TObject, TObject>;
IEventBus = Interface
['{7BDF4536-F2BA-4FBA-B186-09E1EE6C7E35}']
procedure RegisterSubscriber(ASubscriber: TObject);
function IsRegistered(ASubscriber: TObject): Boolean;
procedure Unregister(ASubscriber: TObject);
procedure Post(AEvent: TObject; const AContext: String = '';
AEventOwner: Boolean = true);
procedure SetOnCloneEvent(const aCloneEvent: TCloneEventCallback);
procedure AddCustomClassCloning(const AQualifiedClassName: String;
const aCloneEvent: TCloneEventMethod);
procedure RemoveCustomClassCloning(const AQualifiedClassName: String);
property OnCloneEvent: TCloneEventCallback write SetOnCloneEvent;
end;
SubscribeAttribute = class(TCustomAttribute)
private
FContext: String;
FThreadMode: TThreadMode;
public
constructor Create(AThreadMode: TThreadMode = TThreadMode.Posting;
const AContext: String = '');
property ThreadMode: TThreadMode read FThreadMode;
property Context: String read FContext;
end;
TDEBEvent<T> = class(TObject)
private
FDataOwner: Boolean;
FData: T;
procedure SetData(const Value: T);
procedure SetDataOwner(const Value: Boolean);
public
constructor Create; overload;
constructor Create(AData: T); overload;
destructor Destroy; override;
property DataOwner: Boolean read FDataOwner write SetDataOwner;
property Data: T read FData write SetData;
end;
TProps = class
private
FPropString: String;
FPropInteger: Integer;
FPropCurrency : Currency;
FPropDouble : Double;
FPropValue : TValue;
FPropObject : TObject;
FPropDateTime : TDateTime;
FKey : String;
public
constructor Create;
destructor Destroy; override;
function PropString ( aProp : String ) : TProps; overload;
function PropString : String; overload;
function PropInteger ( aProp : Integer ) : TProps; overload;
function PropInteger : Integer; overload;
function PropCurrency ( aProp : Currency ) : TProps; overload;
function PropCurrency : Currency; overload;
function PropDouble ( aProp : Double ) : TProps; overload;
function PropDouble : Double; overload;
function PropValue ( aProp : TValue ) : TProps; overload;
function PropValue : TValue; overload;
function PropObject ( aProp : TObject ) : TProps; overload;
function PropObject : TObject; overload;
function PropDateTime ( aProp : TDateTime ) : TProps; overload;
function PropDateTime : TDateTime; overload;
function Key ( aKey : String ) : TProps; overload;
function Key : String; overload;
end;
function GlobalEventBus: IEventBus;
implementation
uses
EventBus.Core, RTTIUtilsU;
var
FGlobalEventBus: IEventBus;
{ SubscribeAttribute }
constructor SubscribeAttribute.Create(AThreadMode
: TThreadMode = TThreadMode.Posting; const AContext: String = '');
begin
inherited Create;
FContext := AContext;
FThreadMode := AThreadMode;
end;
{ TDEBSimpleEvent<T> }
constructor TDEBEvent<T>.Create(AData: T);
begin
inherited Create;
DataOwner := true;
Data := AData;
end;
constructor TDEBEvent<T>.Create;
begin
inherited Create;
end;
destructor TDEBEvent<T>.Destroy;
var
LValue: TValue;
begin
LValue := TValue.From<T>(Data);
if (LValue.IsObject) and DataOwner then
LValue.AsObject.Free;
inherited;
end;
procedure TDEBEvent<T>.SetData(const Value: T);
begin
FData := Value;
end;
procedure TDEBEvent<T>.SetDataOwner(const Value: Boolean);
begin
FDataOwner := Value;
end;
function GlobalEventBus: IEventBus;
begin
if not Assigned(FGlobalEventBus) then
FGlobalEventBus := TEventBus.Create;
Result := FGlobalEventBus;
end;
{ TProps }
constructor TProps.Create;
begin
end;
destructor TProps.Destroy;
begin
inherited;
end;
function TProps.Key(aKey: String): TProps;
begin
Result := Self;
FKey := aKey;
end;
function TProps.Key: String;
begin
Result := FKey;
end;
function TProps.PropCurrency: Currency;
begin
Result := FPropCurrency;
end;
function TProps.PropDateTime: TDateTime;
begin
Result := FPropDateTime;
end;
function TProps.PropDateTime(aProp: TDateTime): TProps;
begin
Result := Self;
FPropDateTime := aProp;
end;
function TProps.PropDouble: Double;
begin
Result := FPropDouble;
end;
function TProps.PropDouble(aProp: Double): TProps;
begin
Result := Self;
FPropDouble := aProp;
end;
function TProps.PropCurrency(aProp: Currency): TProps;
begin
Result := Self;
FPropCurrency := aProp;
end;
function TProps.PropInteger: Integer;
begin
Result := FPropInteger;
end;
function TProps.PropObject: TObject;
begin
Result := FPropObject;
end;
function TProps.PropObject(aProp: TObject): TProps;
begin
Result := Self;
FPropObject := aProp;
end;
function TProps.PropInteger(aProp: Integer): TProps;
begin
Result := Self;
FPropInteger := aProp;
end;
function TProps.PropString(aProp: String): TProps;
begin
Result := Self;
FPropString := aProp;
end;
function TProps.PropString: String;
begin
Result := FPropString;
end;
function TProps.PropValue: TValue;
begin
Result := FPropValue;
end;
function TProps.PropValue(aProp: TValue): TProps;
begin
Result := Self;
FPropValue := aProp;
end;
initialization
GlobalEventBus;
finalization
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ SOAP Support }
{ }
{ Copyright (c) 2001 Borland Software Corporation }
{ }
{*******************************************************}
{ Converts a SOAP RPC request to/from an internal Delphi format using a DOM }
unit OPToSOAPDomConv;
interface
uses SysUtils, Variants, TypInfo, Classes, xmldom, XMLDoc, IntfInfo, InvokeRegistry,
XMLIntf, OPConvert, WSDLNode, SOAPEnv, SOAPDomConv, Types, XSBuiltIns, SOAPAttachIntf,
Contnrs;
const
SVarArrayType = 'VarArrayType'; { do not localize }
type
ESOAPDomConvertError = class(Exception);
TSOAPArrayElemDesc = record
MultiDim: Boolean;
Dims: TIntegerDynArray;
end;
TSOAPArrayDesc = array of TSOAPArrayElemDesc;
TMultiRefNodeMapElem = record
Instance: Pointer;
ID: string;
end;
TMultiRefNodeMap = array of TMultiRefNodeMapElem;
TXMLNodeArray = array of IXMLNode;
TMultiRefNodeElem = record
Node: IXMLNode;
MultiRefChildren: TXMLNodeArray;
end;
TMultiRefNodes = array of TMultiRefNodeElem;
ConvNodeState = (nsClientSend, nsServerReceive, nsServerSend, nsClientReceive);
TMemberDataNotReceivedEvent = procedure(const ClassName: string; const Member: string) of object;
TUnhandledNodeEvent = procedure(const Name: string; NodeXML: WideString) of object;
TSOAPDomConv = class(TSOAPDOMProcessor, IObjConverter)
private
FIDs: Integer;
FAttachments: TSoapDataList;
RefMap: TMultiRefNodeMap;
MultiRefNodes: TMultiRefNodes;
FOptions: TSOAPConvertOptions;
ObjsWriting: array of TObject;
FOnMemberDataNotReceived: TMemberDataNotReceivedEvent;
FOnUnhandledNode: TUnhandledNodeEvent;
protected
procedure AddAttachment(Attachment: TSOAPAttachment; const AContentId: string);
function FindAttachment(const AContentId: string): TSOAPAttachment;
procedure ReadHeader(const EnvNode, HdrNode: IXMLNode; Headers: THeaderList);
procedure WriteHeader(const Header: TObject; RootNode, ParentNode: IXMLNode);
function NodeIsNULL(Node: IXMLNode): Boolean;
function ChildNodesAreNull(Node: IXMLNode): Boolean;
function CreateNULLNode(RootNode, ParentNode: IXMLNode; const Name: InvString; UseParentNode: Boolean = False): IXMLNode;
function GetNewID: string;
function FindPrefixForURI(RootNode, Node: IXMLNode; const URI: InvString; DeclIfNone: Boolean = False): InvString;
function AddNamespaceDecl(Node: IXMLNode; const URI: InvString): InvString;
function GetElementType(Node: IXMLNode; var TypeURI, TypeName: InvString): Boolean;
function CreateScalarNodeXS(RootNode, ParentNode: IXMLNode; const NodeName, URI, TypeName: WideString; const Value: WideString; GenPre: Boolean = False): IXMLNode;
function GetTypeBySchemaNS(Node: IXMLNode; const URI: InvString): Variant;
function CreateTypedNode(RootNode, ParentNode: IXMLNode; const NodeName, URI: WideString; TypeName: WideString; GenPre: Boolean = False): IXMLNode;
procedure SetNodeType(RootNode, InstNode: IXMLNode; const ElemURI, TypeName: InvString);
function GetNodeAsText(Node: IXMLNode): InvString;
function GetDataNode(RootNode, Node: IXMLNode; var ID: InvString): IXMLNode;
procedure CheckEncodingStyle(Node: IXMLNode);
{ Methods to handle mutli-referenced nodes }
procedure AddMultiRefNode(const ID: string; Instance: Pointer);
function FindMultiRefNodeByInstance(Instance: Pointer): string;
function FindMultiRefNodeByID(const ID: string): Pointer;
function CreateMultiRefNode(RootNode: IXMLNode; const Name, ID: InvString): IXMLNode;
procedure FinalizeMultiRefNodes;
function FindNodeByHREF(RootNode: IXMLNode; const HREF: InvString): IXMLNode;
procedure AddObjectAsWriting(Instance: TObject);
procedure RemoveObjectAsWriting(Instance: TObject);
function IsObjectWriting(Instance: TObject): Boolean;
procedure ResetMultiRef;
{ Methods to handle Variants }
procedure ConvertVariantToSoap(RootNode, Node: IXMLNode;
const Name: InvString; Info: PTypeInfo; P: PVarData; NumIndirect: Integer; V: Variant; UseVariant: Boolean);
procedure ConvertSoapToVariant(Node: IXMLNode; InvData: Pointer);
function IsNodeAVarArray(const Node: IXMLNode; var VT: TVarType): Boolean;
procedure WriteVarArray(RootNode, Node: IXMLNode; const Name: InvString; V: Variant);
procedure WriteVariant(RootNode, Node: IXMLNode; const Name: InvString; V: Variant);
procedure ReadVariant(Node: IXMLNode; P: Pointer);
function ReadVarArrayDim(Node: IXMLNode; IsVarVArray: Boolean = False; VT: TVarType = 0): Variant;
procedure WriteVarArrayAsB64(RootNode, Node: IXMLNode; const Name: InvString; V: Variant);
{ Methods to handle native delphi array types }
function MakeArrayNode(RootNode, Node: IXMLNode; const Name, URI, TypeName: InvString;
Indices: array of Integer): IXMLNode; overload;
function MakeArrayNode(RootNode, Node: IXMLNode; const Name, URI, TypeName: InvString;
Dim, Len: Integer): IXMLNode; overload;
procedure ConvertNativeArrayToSoap(RootNode, Node: IXMLNode;
const Name: InvString; Info: PTypeInfo; P: Pointer; NumIndirect: Integer; InlineElements: Boolean = False);
procedure WriteNonRectDynArray(RootNode, Node: IXMLNode; const Name: InvString; Info: PTypeInfo; const URI, TypeName: InvString; P: Pointer; Dim: Integer);
function WriteNonRectDynArrayElem(RootNode, Node: IXMLNode; Info: PTypeInfo; const URI, TypeName: InvString; P: Pointer; Dim: Integer): Integer;
function ConvertSoapToNativeArray(DataP: Pointer; TypeInfo: PTypeInfo;
RootNode, Node: IXMLNode): Pointer;
function ConvertSoapToNativeArrayElem(ArrayInfo, ElemInfo: PTypeInfo;
RootNode, Node: IXMLNode; ArrayDesc: TSOAPArrayDesc;
Dims, CurDim: Integer; DataP: Pointer): Pointer;
procedure ConvertByteArrayToSoap(RootNode, Node: IXMLNode; const Name: InvString;
Info: PTypeInfo; P: Pointer);
procedure WriteRectDynArrayElem(RootNode, Node: IXMLNode; Info: PTypeInfo; Size, Dim: Integer; P: Pointer; const TypeName: InvString);
procedure WriteRectDynArray(RootNode, Node: IXMLNode; Info: PTypeInfo; Dims: Integer; P: Pointer; const TypeName: InvString);
procedure ReadRectDynArray(RootNode, Node: IXMLNode; Info: PTypeInfo; Dims: Integer; P: Pointer; CurElem: Integer);
procedure ReadRectDynArrayElem(RootNode, Node: IXMLNode; Info: PTypeInfo; Size, Dim: Integer; P: Pointer; var CurElem: Integer);
procedure ReadRow(RootNode, Node: IXMLNode; var CurElem: Integer; Size: Integer; P: Pointer; Info: PTypeInfo);
{ Enums }
function ConvertEnumToSoap(Info: PTypeInfo; P: Pointer; NumIndirect: Integer): InvString;
function ConvertSoapToEnum(Info: PTypeInfo; S: InvString; IsNull: Boolean): Integer;
{ Methods that handle TObjects with RTTI }
function MultiRefObject(Cls: TClass): Boolean;
function SerializationOptions(Cls: TClass): TSerializationOptions; overload;
function SerializationOptions(ATypeInfo: PTypeInfo): TSerializationOptions; overload;
function SerializationOptions(Obj: TObject): TSerializationOptions; overload;
procedure ConvertObjectToSOAP(const Name: InvString; ObjP: Pointer; RootNode, Node: IXMLNOde; NumIndirect: Integer);
function ConvertSOAPToObject(RootNode, Node: IXMLNode;
AClass: TClass; const URI, TypeName: WideString; ObjP: Pointer; NumIndirect: Integer): TObject;
function CreateObjectNode(Instance: TObject; RootNode, ParentNode: IXMLNode;
const Name, URI: InvString; ObjConvOpts: TObjectConvertOptions): InvString;
function ObjInstanceToSOAP(Instance: TObject; RootNode, ParentNode: IXMLNode;
const NodeName, NodeNamespace: InvString; ObjConvOpts: TObjectConvertOptions;
out RefID: InvString): IXMLNode;
procedure LoadObject(Instance: TObject; RootNode, Node: IXMLNode);
procedure InitObjectFromSOAP(Instance: TObject; RootNode, Node: IXMLNode);
procedure ObjectMemberNoShow(const ClassName: string; const MemberName: string);
procedure UnhandledNode(const Name: string; NodeXML: WideString);
procedure SetObjectPropFromText(Instance: TObject; PropInfo: PPropInfo; const SoapData: WideString);
function GetObjectPropAsText(Instance: TObject; PropInfo: PPropInfo): WideString;
function GetOptions: TSOAPConvertOptions;
procedure SetOptions(const Value: TSOAPConvertOptions);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure ConvertNativeDataToSoap(RootNode, Node: IXMLNode;
const Name: InvString; Info: PTypeInfo; P: Pointer; NumIndirect: Integer); dynamic;
procedure ConvertSoapToNativeData(DataP: Pointer; TypeInfo: PTypeInfo;
Context: TDataContext; RootNode, Node: IXMLNode; Translate, ByRef: Boolean; NumIndirect: Integer); dynamic;
published
property Options: TSOAPConvertOptions read FOptions write FOptions;
property OnMemberDataNotReceived: TMemberDataNotReceivedEvent read FOnMemberDataNotReceived write FOnMemberDataNotReceived;
property OnUnhandledNode: TUnhandledNodeEvent read FOnUnhandledNode write FOnUnhandledNode;
end;
TOPToSoapDomConvert = class(TSOAPDomConv, IOPConvert)
private
FWSDLView: TWSDLView;
FTempDir: string;
Envelope: TSoapEnvelope;
FEncoding: WideString;
function GetSoapNS(MD: TIntfMetaData): InvString;
procedure DOMToStream(const XMLDoc: IXMLDocument; Stream: TStream);
procedure ProcessFault(FaultNode: IXMLNode);
procedure ProcessSuccess(RespNode: IXMLNode; const IntfMD: TIntfMetaData;
const MD: TIntfMethEntry; InvContext: TInvContext);
function GetPartName(MethMD: TIntfMetaData; const ParamName: InvString): InvString;
procedure CheckWSDL;
function GetBinding: InvString;
procedure SetWSDLView(const WSDLView: TWSDLView);
function GetAttachments: TSoapDataList; virtual;
procedure SetAttachments(Value: TSoapDataList); virtual;
function GetTempDir: string; virtual;
procedure SetTempDir(const Value: string); virtual;
function GetEncoding: WideString;
procedure SetEncoding(const Encoding: WideString);
protected
function NewXMLDocument: IXMLDocument;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Attachments: TSOAPDataList read GetAttachments write SetAttachments;
{ IOPConvert }
procedure MsgToInvContext(const Request: InvString; const IntfMD: TIntfMetaData;
var MethNum: Integer; Context: TInvContext); overload; virtual;
procedure MsgToInvContext(const Request: TStream; const IntfMD: TIntfMetaData;
var MethNum: Integer; Context: TInvContext;
Headers: THeaderList); overload; virtual;
function InvContextToMsg(const IntfMD: TIntfMetaData;
MethNum: Integer;
Con: TInvContext;
Headers: THeaderList): TStream;
procedure MakeResponse(const IntfMD: TIntfMetaData;
const MethNum: Integer;
Context: TInvContext;
Response: TStream;
Headers: THeaderLIst); virtual;
procedure MakeFault(const Ex: Exception; EStream: TStream); virtual;
procedure ProcessResponse(const Resp: InvString;
const IntfMD: TIntfMetaData;
const MD: TIntfMethEntry;
Context: TInvContext); overload; virtual;
procedure ProcessResponse(const Resp: TStream;
const IntfMD: TIntfMetaData;
const MD: TIntfMethEntry;
Context: TInvContext;
Headers: THeaderList); overload; virtual;
{ Helper routine }
procedure ProcessResponse(const XMLDoc: IXMLDocument;
const IntfMD: TIntfMetaData;
const MD: TIntfMethEntry;
Context: TInvContext;
Headers: THeaderList); overload; virtual;
published
property WSDLView: TWSDLView read FWSDLView write SetWSDLView;
property TempDir: string read GetTempDir write SetTempDir;
property Encoding: WideString read GetEncoding write SetEncoding;
end;
function GetOrdPropEx(Instance: TObject; PropInfo: PPropInfo): Longint;
var
DefArrayElemName: string = 'item'; { do not lcoalize }
implementation
uses
{$IFDEF MSWINDOWS}
Windows, ComObj,
{$ENDIF}
EncdDecd, SOAPConst, InvRules, TypeTrans, OPToSOAPDomCustom, VarUtils, StrUtils,
WSDLBind, XMLSchema, HTTPUtil, WSDLItems, SOAPAttach,
oxmldom{$IFDEF MSWINDOWS}, msxmldom{$ENDIF}, xercesxmldom;
type
{ Add access to CacheFile : no data members! }
TConvertAttachment = class(TSOAPAttachment)
procedure SetCacheFile(const Value: string);
end;
procedure TConvertAttachment.SetCacheFile(const Value: string);
begin
SetSourceFile('');
InternalSetCacheFile(Value);
end;
{ util function }
function ntElementChildCount(const Node: IXMLNode): Integer;
var
I: Integer;
begin
Result := 0;
if (Node = nil) or (Node.ChildNodes = nil) then
Exit;
for I := 0 to Node.ChildNodes.Count-1 do
if Node.ChildNodes[I].NodeType = ntElement then
Inc(Result);
end;
function ntElementChild(const Node: IXMLNode; Index: Integer): IXMLNode;
var
I, J: Integer;
begin
Result := nil;
if (Node = nil) or (Node.ChildNodes = nil) then
Exit;
J := 0;
for I := 0 to Node.ChildNodes.Count-1 do
if Node.ChildNodes[I].NodeType = ntElement then
begin
if (J = Index) then
begin
Result := Node.ChildNodes[I];
Exit;
end else
Inc(J);
end;
end;
procedure ParseDims(DimString: InvString; var Dims: TSOAPArrayDesc);
var
I, J: Integer;
CurDim, NumDims, SubDims, SubDim: Integer;
StrLen: Integer;
DimSize: InvString;
begin
CurDim := 0;
NumDims := 0;
StrLen := Length(DimString);
for I := 1 to StrLen do
if DimString[I] = '[' then { do not localize }
Inc(NumDims);
SetLength(Dims, NumDims);
I := 1;
while I < StrLen do
begin
if DimString[I] = '[' then { do not localize }
begin
DimSize := '';
Inc(I);
SubDims := 1;
SubDim := 0;
if DimString[I] = ']' then { do not localize }
SetLength(Dims[CurDim].Dims, 1);
while (DimString[I] <> ']') and (I < StrLen) do { do not localize }
begin
J := I;
while (DimString[J] <> ']') and (J < StrLen) do { do not localize }
begin
if DimString[J] = ',' then
Inc(SubDims);
Inc(J);
end;
SetLength(Dims[CurDim].Dims, SubDims);
if SubDims > 1 then
begin
Dims[CurDim].MultiDim := True;
while (DimString[I] <> ']') and (I < StrLen) do { do not localize }
begin
DimSize := '';
while (DimString[I] <> ',') and (DimString[I] <> ']') and (I < StrLen) do { do not localize }
begin
DimSize := DimSize + DimString[I];
Inc(I);
end;
if DimString[I] = ',' then
Inc(I);
if trim(DimSize) <> '' then
Dims[CurDim].Dims[SubDim] := StrToInt(trim(DimSize))
else
Dims[CurDim].Dims[SubDim] := 0;
Inc(SubDim);
end
end else
begin
while (DimString[I] <> ']') and (I < StrLen) do { do not localize }
begin
DimSize := DimSize + DimString[I];
Inc(I);
end;
if trim(DimSize) <> '' then
Dims[CurDim].Dims[SubDim] := StrToInt(trim(DimSize))
else
Dims[CurDim].Dims[SubDim] := 0;
end;
end;
Inc(I);
Inc(CurDim);
end else
Inc(I);
end;
end;
{ TOPToSoapDomConvert }
type
PTObject = ^TObject;
{ Server Receives Message }
procedure TOPToSoapDomConvert.MsgToInvContext(const Request: InvString;
const IntfMD: TIntfMetaData; var MethNum: Integer; Context: TInvContext);
var
Stream: TStream;
begin
Stream := TMemoryStream.Create;
try
Stream.Write(Request[1], Length(Request) * 2);
Stream.Position := 0;
MsgToInvContext(Stream, IntfMD, MethNum, Context, nil);
finally
Stream.Free;
end;
end;
procedure TSoapDomConv.ReadHeader(const EnvNode, HdrNode: IXMLNode; Headers: THeaderList);
var
HeaderName, HeaderNamespace: InvString;
HeaderProcessor: IDOMHeaderProcessor;
HeaderHandled, AbortRequest: Boolean;
HeaderClsType: TClass;
HeaderObject: TObject;
HeaderNode: IXMLNode;
ID: InvString;
begin
HeaderNode := GetDataNode(EnvNode, HdrNode, ID);
{ Find out if we have something into which we can serialize this node }
HeaderName := ExtractLocalName(HeaderNode.NodeName);
HeaderNamespace := HeaderNode.NamespaceURI;
HeaderClsType := InvRegistry.GetHeaderClass(HeaderName, HeaderNamespace);
if HeaderClsType <> nil then
begin
if HeaderClsType.InheritsFrom(TRemotable) then
HeaderObject := TRemotableClass(HeaderClsType).Create
else
HeaderObject := HeaderClsType.Create;
ConvertSoapToNativeData(HeaderObject, HeaderClsType.ClassInfo, nil, EnvNode, HeaderNode, False, True, 0);
Headers.Add(HeaderObject);
end else
begin
{ Old -D6- Header processing logic - left here simply because....}
AbortRequest := False;
HeaderProcessor := FindHeaderProcessor(HeaderNamespace, HeaderName, '');
if HeaderProcessor <> nil then
HeaderProcessor.ProcessHeader(HeaderNode, HeaderHandled, AbortRequest)
else
begin
UnhandledNode(Format('%s:%s', [HeaderNamespace, HeaderName]), HeaderNode.XML);
DefaultProcessHeader(HeaderNode, HeaderHandled, AbortRequest);
end;
if AbortRequest then
raise ESOAPDomConvertError.CreateFmt(SHeaderError, [HeaderNamespace, HeaderName]);
end;
end;
procedure TSoapDomConv.WriteHeader(const Header: TObject; RootNode, ParentNode: IXMLNode);
begin
Options := Options + [soXXXXHdr];
try
ConvertNativeDataToSoap(RootNode, ParentNode,
Header.ClassName,
Header.ClassInfo,
Header, 0);
finally
Options := Options - [soXXXXHdr];
end;
end;
procedure TOPToSoapDomConvert.MsgToInvContext(const Request: TStream;
const IntfMD: TIntfMetaData; var MethNum: Integer; Context: TInvContext;
Headers: THeaderList);
var
XmlDoc: IXMLDocument;
I, J, K, L, ParamCount: Integer;
MethodName, InternalMethodName, ExtParamName: InvString;
EnvNode, MethNode, ParamNode, Node, HdrNode: IXMLNode;
ProcessedBody: Boolean;
MD: TIntfMethEntry;
Translate: Boolean;
ParamSerialOpts: TSerializationOptions;
begin
XmlDoc := NewXMLDocument;
Request.Position := 0;
XmlDoc.LoadFromStream(Request);
EnvNode := XmlDoc.DocumentElement;
if EnvNode = nil then
raise ESOAPDomConvertError.Create(SInvalidSOAPRequest);
if (ExtractLocalName(EnvNode.NodeName) <> SSoapEnvelope) or (EnvNode.NamespaceURI <> SSoapNameSpace) then
raise ESOAPDomConvertError.Create(SInvalidSOAPRequest);
ProcessedBody := False;
try
if EnvNode.hasChildNodes then
begin
for I := 0 to EnvNode.childNodes.Count -1 do
begin
Node := EnvNode.childNodes[I];
if Node.NodeType <> ntElement then
continue;
if ExtractLocalName(Node.NodeName) = SSoapHeader then
begin
if Node.hasChildNodes then
begin
for L := 0 to Node.childNodes.Count-1 do
begin
HdrNode := Node.childNodes[L];
if HdrNode.NodeType <> ntElement then
continue;
ReadHeader(EnvNode, HdrNode, Headers);
end;
end;
end
else if ExtractLocalName(Node.NodeName) = SSoapBody then
begin
if ProcessedBody then
raise ESOAPDomConvertError.Create(SMultiBodyNotSupported);
CheckEncodingStyle(EnvNode);
ProcessedBody := True;
if Node.ChildNodes.Count > 0 then
begin
{ Rather than assume that the first childNode is the method's
node, it would be safer to use the 'root' attribute. However,
SOAPBuilder can't seem to agree on 'root' currently. So for
now, we'll stay with this approach }
MethNode := ntElementChild(Node, 0);
CheckEncodingStyle(MethNode);
MethodName := ExtractLocalName(MethNode.NodeName);
InternalMethodName := InvRegistry.GetMethInternalName(IntfMD.Info, MethodName);
MethNum := GetMethNum(IntfMD, InternalMethodName, NtElementChildCount(MethNode));
{ Here know if there's a method for the request sent }
if MethNum = -1 then
raise ESOAPDomConvertError.CreateFmt(SNoSuchMethod, [MethodName, IntfMD.Name]);
MD := IntfMD.MDA[MethNum];
Context.SetMethodInfo(MD);
Context.AllocServerData(MD);
{ Get native parameters }
ParamCount := 0;
for K := 0 to Length(MD.Params)-1 do
if MD.Params[K].Name <> '' then
Inc(ParamCount);
for K := 0 to Length(MD.Params)-1 do
begin
{ Skip non-parameters }
if MD.Params[K].Name = '' then
continue;
{ Was parameter renamed ? }
ExtParamName := InvRegistry.GetParamExternalName(IntfMD.Info, InternalMethodName, MD.Params[K].Name);
ParamSerialOpts := SerializationOptions(MD.Params[K].Info);
for J := 0 to MethNode.childNodes.Count -1 do
begin
ParamNode := MethNode.childNodes[J];
if ParamNode.NodeType <> ntElement then
continue;
{ Warning: In case sensitive contexts, it's possible to have parameters
that differ only in case - C++ }
if SameText(ExtParamName, ExtractLocalName(ParamNode.NodeName)) then
begin
CheckEncodingStyle(ParamNode);
Translate := (pfVar in MD.Params[K].Flags)
or (pfConst in MD.Params[K].Flags)
or ([] = MD.Params[K].Flags)
or ((pfReference in MD.Params[K].Flags) and (MD.Params[K].Info.Kind = tkVariant))
or ((pfReference in MD.Params[K].Flags) and (MD.Params[K].Info.Kind = tkString));
ConvertSoapToNativeData(Context.GetParamPointer(K), MD.Params[K].Info, Context, MethNode,
ParamNode, Translate, False, 1);
break;
end
{ Here we have an unhandled parameter node }
{ Check if the name mismatches were due to wrapper classes }
else if (xoHolderClass in ParamSerialOpts) and (ParamCount = 1) then
begin
Translate := (pfVar in MD.Params[K].Flags)
or (pfConst in MD.Params[K].Flags)
or ([] = MD.Params[K].Flags)
or ((pfReference in MD.Params[K].Flags) and (MD.Params[K].Info.Kind = tkVariant))
or ((pfReference in MD.Params[K].Flags) and (MD.Params[K].Info.Kind = tkString));
ConvertSoapToNativeData(Context.GetParamPointer(K), MD.Params[K].Info, Context, MethNode,
Node, Translate, False, 1);
break;
end else
begin
{ Could not deserialize node... }
UnhandledNode(MethodName, ParamNode.XML);
end;
end;
end;
end;
end;
end;
end else
raise ESOAPDomConvertError.Create(SInvalidSOAPRequest);
finally
ResetMultiRef;
end;
end;
procedure TOPToSoapDomConvert.DOMToStream(const XMLDoc: IXMLDocument; Stream: TStream);
var
XMLWString: WideString;
StrStr: TStringStream;
begin
{ NOTE: Typically you don't want us to UTF8 Encode if you've requested
the DOM to encode; however, some implementations seem to
indiscriminately UTF8Decode - so you can force UTF8 encoding, which
will make us make the DOM ignore any encoding set
*********************************************************************
Remember to keep the Transport in sync. with any DOM encodings -
namely the 'UseUTF8InHeader' property of the transport components }
if (FEncoding = '') or (soUTF8EncodeXML in Options) then
begin
XMLDoc.SaveToXML(XMLWString);
StrStr := TStringStream.Create(UTF8Encode(XMLWString));
try
Stream.CopyFrom(StrStr, 0);
finally
StrStr.Free;
end;
end else
XMLDoc.SaveToStream(Stream);
end;
procedure TOPToSoapDomConvert.MakeResponse(const IntfMD: TIntfMetaData; const MethNum: Integer;
Context: TInvContext; Response: TStream;
Headers: THeaderList);
var
I: Integer;
XmlDoc: IXMLDocument;
EnvNode, HeaderNode, BodyNode, MethNode, RootNode: IXMLNode;
MD: TIntfMethEntry;
SoapNS: InvString;
ArgName: InvString;
P: Pointer;
Header: TObject;
begin
MD := IntfMD.MDA[MethNum];
XMLDoc := NewXMLDocument;
XMLDoc.Encoding := FEncoding;
EnvNode := Envelope.MakeEnvelope(XMLDoc, Options);
XmlDoc.DocumentElement := EnvNode;
{ Result the MultiRef IDs as we're about to create a new Response }
FIDS := 1;
FAttachments.Clear;
if (Headers <> nil) and (Headers.Count > 0) then
begin
HeaderNode := Envelope.MakeHeader(EnvNode);
if not (soDocument in Options) then
HeaderNode.SetAttributeNS(SSoapEncodingAttr, SSoapNameSpace, SSoap11EncodingS5);
for I := 0 to Headers.Count-1 do
begin
Header := Headers[I];
WriteHeader(Header, HeaderNode, HeaderNode);
end;
end;
BodyNode := Envelope.MakeBody(EnvNode);
if not (soDocument in Options) then
BodyNode.SetAttributeNS(SSoapEncodingAttr, SSoap11EncodingS5, SSoapNameSpace);
if not (soLiteralParams in Options) then
begin
SoapNS := GetSoapNS(IntfMD);
if not (soDocument in Options) then
MethNode := BodyNode.AddChild(MD.Name + SSoapResponseSuff, SoapNS, True)
else
MethNode := BodyNode.AddChild(MD.Name + SSoapResponseSuff, SoapNS)
end else
begin
{ If Literal params were not unwound, we don't need a method node }
MethNode := BodyNode;
end;
{ Compute Root Node }
{ NOTE: It's incorrect to root ref nodes to the method node - however, this was
the way D6 originally shipped; therefore we offer it as an option in
case you still have a D6 [unpatched] Service or Client that you need
to support }
if (soRootRefNodesToBody in Options) then
RootNode := BodyNode
else
RootNode := MethNode;
try
if MD.ResultInfo <> nil then
begin
ArgName := GetPartName(IntfMD, '');
ConvertNativeDataToSoap(RootNode, MethNode, ArgName, MD.ResultInfo, Context.GetResultPointer, 1);
end;
for I := 0 to MD.ParamCount - 1 do
begin
if (pfVar in MD.Params[I].Flags) or (pfOut in MD.Params[I].Flags)
then
begin
P := Context.GetParamPointer(I);
ConvertNativeDataToSoap(RootNode, MethNode, MD.Params[I].Name, MD.Params[I].Info, P, 1);
end;
end;
finally
FinalizeMultiRefNodes;
ResetMultiRef;
end;
{ Let DOM write to stream - DOM handles Encoding }
DOMToStream(XMLDoc, Response);
end;
function TOPToSoapDomConvert.GetSoapNS(MD: TIntfMetaData): InvString;
var
ExtName: WideString;
begin
if Assigned(WSDLView) then
begin
ExtName := InvRegistry.GetMethExternalName(MD.Info, WSDLVIew.Operation);
Result := WSDLView.WSDL.GetSoapBodyAttribute(GetBinding, ExtName, WSDLBind.SInput, WSDLBind.SNameSpace, 0);
{ NOTE: Document Style WSDL don't have a namespace on the input/ouput nodes }
if (Result = '') then
Result := InvRegistry.GetNamespaceByGUID(MD.IID);
end else
Result := InvRegistry.GetNamespaceByGUID(MD.IID);
end;
procedure TOPToSoapDomConvert.MakeFault(const Ex: Exception; EStream: TStream);
var
XmlDoc: IXMLDocument;
EnvNode, BodyNode, FaultNode, FA, FC, FS, FD, CustNode: IXMLNode;
I, Count: Integer;
PropList: PPropList;
URI, TypeName: WideString;
IsScalar: Boolean;
RemException: ERemotableException;
begin
XMLDoc := NewXMLDocument;
XMLDoc.Encoding := FEncoding;
EnvNode := Envelope.MakeEnvelope(XMLDoc, Options);
BodyNode := Envelope.MakeBody(EnvNode);
FaultNode := Envelope.MakeFault(BodyNode);
FA := FaultNode.AddChild(SSoapFaultActor, '');
FC := FaultNode.AddChild(SSoapFaultCode, '');
{ NOTE: We map the FaultString to Exception's Message }
FS := FaultNode.AddChild(SSoapFaultString, '');
FS.Text := Ex.Message;
if Ex.InheritsFrom(ERemotableException) then
begin
RemException := ERemotableException(Ex);
FA.Text := RemException.FaultActor;
FC.Text := MakeNodeName(SSoapNameSpacePre, RemException.FaultCode);
RemClassRegistry.ClassToURI(Ex.ClassType, URI, TypeName, IsScalar);
{ The follow logic is *NOT* as per the SOAP spec. The spec wants
specific information under the details node - not *AT* the details
node !!!! But we offer it as an option given that Delphi6, which
had limited (Delphi<->Delphi) Fault support followed that approach }
if (soCustomFaultAtDetailsNode in Options) then
begin
FD := FaultNode.AddChild(SSoapFaultDetails, URI, True);
CustNode := FD;
end
else
begin
FD := FaultNode.AddChild(SSoapFaultDetails, '');
CustNode := FD.AddChild(TypeName, URI, True);
end;
{ Set the type }
CustNode.SetAttributeNS(SSoapType, XMLSchemaInstNameSpace, MakeNodeName(CustNode.Prefix, TypeName));
Count := GetTypeData(Ex.ClassInfo)^.PropCount;
if Count > 0 then
begin
GetMem(PropList, Count * SizeOf(Pointer));
try
GetPropInfos(Ex.ClassInfo, PropList);
for I := 0 to Count - 1 do
begin
if not RemTypeRegistry.TypeInfoToXSD( (PropList[I].PropType)^, URI, TypeName) then
raise ESOAPDomConvertError.CreateFmt(SRemTypeNotRegistered, [(PropList[I].PropType)^.Name]);
CreateScalarNodeXS(CustNode, CustNode, PropList[I].Name, URI, TypeName, GetObjectPropAsText(Ex, PropList[I]));
end;
finally
FreeMem(PropList, Count * SizeOf(Pointer));
end;
end;
end else
begin
{ Fault Code }
FC.Text := MakeNodeName(SSoapNameSpacePre, 'Server'); { Do not localize }
end;
DOMToStream(XmlDoc, EStream);
end;
function TOPToSoapDomConvert.InvContextToMsg(const IntfMD: TIntfMetaData; MethNum: Integer;
Con: TInvContext; Headers: THeaderList): TStream;
var
XMLDoc: IXMLDocument;
EnvNode, HeaderNode, BodyNode, MethNode: IXMLNode;
I: Integer;
SoapMethNS: InvString;
MethMD: TIntfMethEntry;
P: Pointer;
Indir: Integer;
URI, ExtMethName, ExtParamName: InvString;
Header: TObject;
begin
MethMD := IntfMD.MDA[MethNum];
{ Here we update the WSDLView to inform it of
the Operation we're about to execute }
if Assigned(WSDLView) then
begin
WSDLView.Operation := MethMD.Name;
WSDLView.IntfInfo := IntfMD.Info;
end;
XMLDoc := NewXMLDocument;
XMLDoc.Encoding := FEncoding;
EnvNode := Envelope.MakeEnvelope(XMLDoc, Options);
{ Result MultiRef IDs are we're about to create new request }
FIDS := 1;
FAttachments.Clear;
{ Any headers }
if (Headers <> nil) and (Headers.Count > 0) then
begin
HeaderNode := Envelope.MakeHeader(EnvNode);
if not (soDocument in Options) then
HeaderNode.SetAttributeNS(SSoapEncodingAttr, SSoapNameSpace, SSoap11EncodingS5);
for I := 0 to Headers.Count-1 do
begin
Header := Headers[I];
WriteHeader(Header, HeaderNode, HeaderNode);
end;
end;
BodyNode := Envelope.MakeBody(EnvNode);
{ If we're sending literal params, then skip the method node }
if not (soLiteralParams in Options) then
begin
SoapMethNS := GetSoapNS(IntfMD);
{ Add Method node with appropriate namespace }
ExtMethName := InvRegistry.GetMethExternalName(IntfMD.Info, MethMD.Name);
if not (soDocument in Options) then
begin
MethNode := BodyNode.AddChild(ExtMethName, SoapMethNS, (SoapMethNS <> ''));
{ Use encoding style defined by SOAP 1.1 section 5 }
{ NOTE: We used to put this on the method node; it seems more intuitive on
the body node; Keep this in mind when investigating interop issues }
BodyNode.SetAttributeNS(SSoapEncodingAttr, SSoapNameSpace, SSoap11EncodingS5);
end
else
begin
{ In document mode, SoapMethNS is the default namespace }
MethNode := BodyNode.AddChild(ExtMethName, SoapMethNS);
end;
end
else
begin
MethNode := BodyNode;
end;
try
{ Add each parameter to the method node }
for I := 0 to MethMD.ParamCount - 1 do
begin
if not (pfOut in MethMD.Params[I].Flags) then
begin
{ In doc|lit mode, we use the typename for the node }
if (soDocument in Options) and (soLiteralParams in Options) then
RemTypeRegistry.TypeInfoToXSD(MethMD.Params[I].Info, URI, ExtParamName)
else
ExtParamName := InvRegistry.GetParamExternalName(IntfMD.Info, MethMD.Name, MethMD.Params[I].Name);
P := Con.GetParamPointer(I);
Indir := 1;
if IsParamByRef(MethMd.Params[I].Flags, MethMD.Params[I].Info, MethMD.CC) then
Inc(Indir);
ConvertNativeDataToSoap(BodyNode, MethNode, ExtParamName,
MethMD.Params[I].Info, P, Indir);
end;
end;
FinalizeMultiRefNodes;
finally
ResetMultiRef;
end;
Result := TMemoryStream.Create();
DOMToStream(XMLDoc, Result);
end;
procedure TOPToSoapDomConvert.ProcessSuccess(RespNode: IXMLNode;
const IntfMD: TIntfMetaData;
const MD: TIntfMethEntry;
InvContext: TInvContext);
{ This is the tricky part of deserializing; How to determine the return index;
This function should only be used if we're processing a function - IOW, this
function should only be called if the method we're processing has
MD.ResultInfo <> nil }
function FindReturnNodeIndex: integer;
var
X, Y, First, Ret, Count: Integer;
Node: IXMLNode;
ReturnParams: TStringDynArray;
begin
First := -1;
Ret := -1;
Count := 0;
{ Get array of return parameter names }
ReturnParams := StringToStringArray(InvRegistry.GetReturnParamNames(IntfMD.Info),
sReturnParamDelimiters);
for X := 0 to RespNode.ChildNodes.Count-1 do
begin
Node := RespNode.ChildNodes[X];
if Node.NodeType <> ntElement then
continue;
{ Save first valid node }
if First = -1 then
First := X;
{ Save Return param name(s) matches }
if (Ret = -1) and (Length(ReturnParams) > 0) then
begin
for Y := 0 to Length(ReturnParams)-1 do
begin
if SameText(ExtractLocalName(Node.NodeName), ReturnParams[Y]) then
Ret := X;
end;
end;
Inc(Count);
end;
if Count = 1 then
Result := First
else
Result := Ret;
end;
function IsNillable(TypeInfo: PTypeInfo): Boolean;
begin
Result := (TypeInfo.Kind = tkClass) or
(TypeInfo.Kind = tkVariant);
end;
var
I, J, RetIndex: Integer;
InvData: Pointer;
Node: IXMLNode;
ByRef: Boolean;
Indir: Integer;
ParamProcessed: TBooleanDynArray;
begin
SetLength(ParamProcessed, MD.ParamCount);
for J := 0 to Length(ParamProcessed) - 1 do
ParamProcessed[J] := False;
{ Find index of return node - if we're expecting one }
if (MD.ResultInfo <> nil) then
begin
RetIndex := FindReturnNodeIndex;
{ We'll be lenient about nillable types }
if (RetIndex = -1) and not IsNillable(MD.ResultInfo) then
raise ESOAPDomConvertError.CreateFmt(SMissingSoapReturn, [RespNode.XML]);
end
else
RetIndex := -1;
{ Process returned nodes }
if RespNode.HasChildNodes then
begin
for I := 0 to RespNode.childNodes.Count - 1 do
begin
Node := RespNode.childNodes[I];
{ Skip non-valid nodes }
if Node.NodeType <> ntElement then
continue;
{ Process Return value, if we're expecting one }
if I = RetIndex then
begin
InvData := InvContext.GetResultPointer;
ByRef := IsParamByRef([pfOut], MD.ResultInfo, MD.CC);
ConvertSoapToNativeData(InvData, MD.ResultInfo, InvContext, RespNode, Node, True, ByRef, 1);
end
else
begin
J := 0;
while J < MD.ParamCount do
begin
if MD.Params[J].Name = ExtractLocalName(Node.NodeName) then
break;
Inc(J);
end;
if (J < MD.ParamCount) and not ParamProcessed[J] then
begin
ParamProcessed[J] := True;
InvData := InvContext.GetParamPointer(J);
ByRef := IsParamByRef(MD.Params[J].Flags, MD.Params[J].Info, MD.CC);
Indir := 1;
if IsParamByRef(MD.Params[J].Flags, MD.Params[J].Info, MD.CC) then
Inc(Indir);
ConvertSoapToNativeData(InvData, MD.Params[J].Info, InvContext, RespNode, Node, True, ByRef, Indir);
end;
end;
end;
end else if (MD.ResultInfo <> nil) and IsNillable(MD.ResultInfo) then
begin
InvData := InvContext.GetResultPointer;
ByRef := IsParamByRef([pfOut], MD.ResultInfo, MD.CC);
ConvertSoapToNativeData(InvData, MD.ResultInfo, InvContext, RespNode, nil, True, ByRef, 1);
end;
end;
procedure TOPToSoapDomConvert.ProcessFault(FaultNode: IXMLNode);
var
FA, FC, FD, FS, CustNode: IXMLNode;
I, J: Integer;
AMessage: WideString;
AClass: TClass;
URI, TypeName: WideString;
Count: Integer;
PropList: PPropList;
Ex: ERemotableException;
begin
FA := nil;
FC := nil;
FD := nil;
FS := nil;
Ex := nil;
for I := 0 to FaultNode.ChildNodes.Count - 1 do
begin
if SameText(ExtractLocalName(FaultNode.ChildNodes[I].NodeName), SSoapFaultCode) then
FC := FaultNode.ChildNodes[I]
else if SameText(ExtractLocalName(FaultNode.ChildNodes[I].NodeName), SSoapFaultString) then
FS := FaultNode.ChildNodes[I]
else if SameText(ExtractLocalName(FaultNode.ChildNodes[I].NodeName), SSoapFaultDetails) then
FD := FaultNode.ChildNodes[I]
else if SameText(ExtractLocalName(FaultNode.ChildNodes[I].NodeName), SSoapFaultActor) then
FA := FaultNode.ChildNodes[I];
end;
{ Retrieve message from FaultString node }
if FS <> nil then
AMessage := FS.Text;
{ If there's a <detail> node, try to map it to a registered type }
if FD <> nil then
begin
{ Some SOAP stacks, including Delphi6 and others (see
http://softwaredev.earthweb.com/script/article/0,,12063_641361_2,00.html)
use the approach of putting custom fault info right at the <detail> node:
Listing 4 - Application Fault Details
<SOAP-ENV:Fault>
<faultcode>300</faultcode>
<faultstring>Invalid Request</faultstring>
<runcode>1</runcode>
<detail xmlns:e="GetTemperatureErr-URI"
xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"
xsi:type="e:GetTemperatureFault">
<number>5575910</number>
<description>Sensor Failure</description>
<file>GetTemperatureClass.cpp</file>
<line>481</line>
</detail>
</SOAP-ENV:Fault>
However, much more common is the approach where the type and namespace
are on the childnode of the <detail> node. Apache, MS and the SOAP spec.
seem to lean towards that approach:
Example 10 from the SOAP 1.1 Spec:
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Body>
<SOAP-ENV:Fault>
<faultcode>SOAP-ENV:Server</faultcode>
<faultstring>Server Error</faultstring>
<detail>
<e:myfaultdetails xmlns:e="Some-URI">
<message>
My application didn't work
</message>
<errorcode>
1001
</errorcode>
</e:myfaultdetails>
</detail>
</SOAP-ENV:Fault>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
For interop reasons we favor the later approach but we'll support both here!!
}
CustNode := nil;
if GetElementType(FD, URI, TypeName) then
CustNode := FD
else
begin
if ntElementChildCount(FD) > 0 then
begin
if GetElementType(ntElementChild(FD, 0), URI, TypeName) then
CustNode := ntElementChild(FD, 0);
end;
end;
AClass := RemClassRegistry.URIToClass(URI, TypeName);
if AClass <> nil then
begin
if AClass.InheritsFrom(ERemotableException) then
begin
Ex := ERemotableExceptionClass(AClass).Create(AMessage);
Count := GetTypeData(Ex.ClassInfo)^.PropCount;
if (Count > 0) and Assigned(CustNode.ChildNodes) then
begin
GetMem(PropList, Count * SizeOf(Pointer));
try
GetPropInfos(Ex.ClassInfo, PropList);
for I := 0 to Count - 1 do
begin
for J := 0 to CustNode.ChildNodes.Count - 1 do
begin
if CustNode.ChildNodes[J].NodeType <> ntElement then
continue;
if ExtractLocalName(CustNode.ChildNodes[J].NodeName) = PropList[I].Name then
SetObjectPropFromText(Ex, PropList[I], GetNodeAsText(CustNode.ChildNodes[J]));
end;
end;
finally
FreeMem(PropList, Count * SizeOf(Pointer));
end;
end;
end;
end;
end;
{ Create default SOAP invocation exception if no suitable on was found }
if Ex = nil then
Ex := ERemotableException.Create(AMessage);
if FA <> nil then
Ex.FaultActor := FA.Text;
if FC <> nil then
Ex.FaultCode := FC.Text;
if FD <> nil then
Ex.FaultDetail := FD.XML;
raise Ex;
end;
procedure TOPToSoapDomConvert.ProcessResponse(const Resp: InvString;
const IntfMD: TIntfMetaData;
const MD: TIntfMethEntry;
Context: TInvContext);
var
Stream: TMemoryStream;
begin
Stream := TMemoryStream.Create;
try
Stream.Write(Resp[1], Length(Resp));
ProcessResponse(Stream, IntfMD, MD, Context, nil);
finally
Stream.Free;
end
end;
procedure TOPToSoapDomConvert.ProcessResponse(const XMLDoc: IXMLDocument;
const IntfMD: TIntfMetaData;
const MD: TIntfMethEntry;
Context: TInvContext;
Headers: THeaderList);
var
I, J, RespNodeIndex: Integer;
EnvNode, RespNode, Node, HdrNode: IXMLNode;
ProcessedHeader, ProcessedBody: Boolean;
begin
EnvNode := XMLDoc.DocumentElement;
if EnvNode = nil then
raise ESOAPDomConvertError.Create(SInvalidResponse);
if (ExtractLocalName(EnvNode.NodeName) <> SSoapEnvelope) or
(EnvNode.NamespaceURI <> SSoapNameSpace) then
raise ESOAPDomConvertError.CreateFmt(SWrongDocElem, [SSoapNameSpace, SSoapEnvelope, EnvNode.NamespaceURI,
ExtractLocalName(EnvNode.NodeName)]);
ProcessedHeader := False;
ProcessedBody := False;
if EnvNode.hasChildNodes then
begin
for I := 0 to EnvNode.childNodes.Count -1 do
begin
{ Skip to first ntElement node }
Node := EnvNode.childNodes[I];
if Node.NodeType <> ntElement then
continue;
{ Is node a Header Node }
if ExtractLocalName(Node.NodeName) = SSoapHeader then
begin
{ If we've already processed header, we have an invalid Response }
if ProcessedHeader then
raise ESOAPDomConvertError.Create(SInvalidSOAPResponse);
ProcessedHeader := True;
if Node.hasChildNodes then
begin
for J := 0 to Node.childNodes.Count-1 do
begin
HdrNode := Node.childNodes[J];
if HdrNode.NodeType <> ntElement then
continue;
ReadHeader(EnvNode, HdrNode, Headers);
end;
end;
end
else if ExtractLocalName(Node.NodeName) = SSoapBody then
begin
if ProcessedBody then
raise ESOAPDomConvertError.Create(SInvalidSOAPResponse);
ProcessedBody := True;
{ Find the response node -- }
{ In literal mode, the body node is the response node for processing Success... }
if (soLiteralParams in Options) then
begin
RespNode := Node;
{ Unless there's a fault }
if RespNode.HasChildNodes then
if ExtractLocalName(RespNode.ChildNodes[0].NodeName) = SSoapFault then
RespNode := RespNode.ChildNodes[0];
end
else
begin
if Node.HasChildNodes then
begin
RespNode := nil;
{ Skip non-ntElement nodes }
RespNodeIndex := 0;
while (Node.childNodes[RespNodeIndex].NodeType <> ntElement) and
(RespNodeIndex < Node.ChildNodes.Count) do
Inc(RespNodeIndex);
if RespNodeIndex < Node.ChildNodes.Count then
{ Response Node found - NOTE: Much better would be to use root attribute!! }
RespNode := Node.childNodes[RespNodeIndex];
end;
end;
if RespNode <> nil then
begin
try
if ExtractLocalName(RespNode.NodeName) = SSoapFault then
ProcessFault(RespNode)
else
ProcessSuccess(RespNode, IntfMD, MD, Context);
finally
ResetMultiRef;
end;
end;
end;
end
end else
raise ESOAPDomConvertError.Create(SInvalidSOAPRequest);
end;
procedure TOPToSoapDomConvert.ProcessResponse(const Resp: TStream;
const IntfMD: TIntfMetaData;
const MD: TIntfMethEntry;
Context: TInvContext;
Headers: THeaderList);
var
XMLDoc: IXMLDocument;
begin
XMLDoc := NewXMLDocument;
XMLDoc.Encoding := FEncoding;
Resp.Position := 0;
XMLDoc.LoadFromStream(Resp);
ProcessResponse(XMLDoc, IntfMD, MD, Context, Headers);
end;
constructor TOPToSoapDomConvert.Create(AOwner: TComponent);
begin
inherited;
Envelope := TSoapEnvelope.Create;
FIDs := 1;
Options := Options + [soSendMultiRefObj,
soRootRefNodesToBody,
soTryAllSchema,
soCacheMimeResponse,
soUTF8EncodeXML ];
end;
destructor TOPToSoapDomConvert.Destroy;
begin
Envelope.Free;
inherited;
end;
function TOPToSoapDomConvert.GetAttachments: TSoapDataList;
begin
Result := FAttachments;
end;
procedure TOPToSoapDomConvert.SetAttachments(Value: TSoapDataList);
begin
FAttachments := Value;
end;
function TOPToSoapDomConvert.GetTempDir: string;
begin
Result := FTempDir;
end;
procedure TOPToSoapDomConvert.SetTempDir(const Value: string);
begin
FTempDir := Value;
if (Value <> '') and (Value[Length(Value)] <> PathDelim) then
FTempDir := FTempDir + PathDelim;
end;
function TOPToSoapDomConvert.GetEncoding: WideString;
begin
Result := FEncoding;
end;
function TOPToSoapDomConvert.NewXMLDocument: IXMLDocument;
begin
Result := XMLDoc.NewXMLDocument;
{$IFDEF MSWINDOWS}
{$IFDEF DEVELOPERS}
{ For testing purposes - make sure we handle WhiteSpace properly }
Result.Options := Result.Options + [doNodeAutoIndent];
Result.ParseOptions := Result.ParseOptions + [poPreserveWhiteSpace];
{$ENDIF}
{$ENDIF}
end;
procedure TOPToSoapDomConvert.SetEncoding(const Encoding: WideString);
begin
FEncoding := Encoding;
end;
procedure TOPToSoapDomConvert.CheckWSDL;
begin
if Assigned(WSDLView.WSDL) then
begin
WSDLView.Activate;
end
else
raise ESOAPDomConvertError.Create(SNoWSDL);
end;
function TOPToSoapDomConvert.GetBinding: InvString;
var
QName: IQualifiedName;
begin
CheckWSDL;
QName := WSDLView.WSDL.GetBindingForServicePort(WSDLView.Service, WSDLView.Port);
if QName <> nil then
Result := QName.Name;
end;
procedure TOPToSoapDomConvert.SetWSDLView(const WSDLView: TWSDLView);
begin
FWSDLView := WSDLView;
end;
{ ParamName = '' implies function return value }
function TOPToSoapDomConvert.GetPartName(MethMD: TIntfMetaData; const ParamName: InvString): InvString;
begin
if ParamName = '' then
Result := SDefaultReturnName
else
Result := InvRegistry.GetNamespaceByGUID(MethMD.IID);
end;
{ TSOAPDomConv }
constructor TSOAPDomConv.Create(AOwner: TComponent);
begin
inherited;
FAttachments := TSoapDataList.Create;
end;
destructor TSOAPDomConv.Destroy;
begin
FAttachments.Destroy;
inherited;
end;
procedure TSOAPDomConv.AddAttachment(Attachment: TSOAPAttachment; const AContentId: string);
var
Attach: TSOAPAttachmentData;
begin
Attach := TSOAPAttachmentData.Create;
with Attach do
begin
Id := AContentId;
Headers.Add(Format(SContentId + ': <%s>', [AContentId]));
if Attachment.CacheFile <> '' then
SetCacheFile(Attachment.CacheFile)
else if Assigned(Attachment.SourceStream) then
begin
SetSourceStream(Attachment.SourceStream, Attachment.Ownership);
Attachment.Ownership := soReference;
end else SourceString := Attachment.SourceString;
DataContext := Nil;
end;
Attach.ContentType := Attachment.ContentType;
Attach.Encoding := Attachment.Encoding;
FAttachments.Add(Attach);
end;
function TSOAPDomConv.FindAttachment(const AContentId: string): TSOAPAttachment;
function SameId(Id1, Id2: string): Boolean;
begin
{ if by ContentId, extract Id by removing 'cid:' and compare }
if AnsiSameText(SAttachmentIdPrefix, Copy(Id2, 2, Length(SAttachmentIdPrefix))) then
Result := AnsiSameText(Id1, '<' + Copy(Id2, Pos(':', Id2) + 1, MaxInt))
{ GLUE uses http:// to identify ContentId }
else if AnsiSameText(sHTTPPrefix, Copy(Id2, 2, Length(SHTTPPrefix))) then
Result := AnsiSameText(Id1, Id2)
else { if by location, extract Location by removing DefaultBaseURI }
begin
if Pos(SDefaultBaseURI, Id2) = 1 then
Result := AnsiSameText(Id1, Copy(Id2, Length(SDefaultBaseURI) + 1, MaxInt))
else { extract Location by removing name space }
Result := AnsiSameText(Id1, '<' + Copy(Id2, Pos(':', Id2) + 1, MaxInt));
end;
end;
var
I: Integer;
begin
Result := nil;
for I := 0 to FAttachments.Count -1 do
begin
if SameId(TSOAPAttachmentData(FAttachments[I]).ID, AContentId) then
begin
Result := FAttachments[I];
break;
end;
end;
end;
procedure TSOAPDomConv.ConvertVariantToSoap(RootNode, Node: IXMLNode;
const Name: InvString; Info: PTypeInfo; P: PVarData; NumIndirect: Integer; V: Variant; UseVariant: Boolean);
var
DataP: Pointer;
begin
if UseVariant then
begin
if VarIsNull(V) then
CreateNULLNode(RootNode, Node, Name)
else
WriteVariant(RootNode, Node, Name, V);
end else
begin
DataP := P;
if NumIndirect > 1 then
DataP := Pointer(PInteger(DataP)^);
if (DataP = nil) or VarIsNull(Variant(DataP^)) then
CreateNULLNode(RootNode,Node, Name)
else
WriteVariant(RootNode, Node, Name, Variant(DataP^));
end;
end;
function IsXMLDateTimeTypeInfo(const Info: PTypeInfo): Boolean;
begin
Result := ((Info.Kind = tkClass) and (GetTypeData(Info).ClassType = TXSDateTime)) or
((Info.Kind = tkFloat) and (Info = TypeInfo(TDateTime)));
end;
procedure TSOAPDomConv.WriteVariant(RootNode, Node: IXMLNode; const Name: InvString; V: Variant);
var
S, URI, TypeName: InvString;
Info: PTypeInfo;
IsScalar: Boolean;
begin
if VarIsArray(V) then
begin
if VarIsType(V, varByte or varArray) then
begin
WriteVarArrayAsB64(RootNode, Node, Name, V);
end
else
WriteVarArray(RootNode, Node, Name, V);
end
else
begin
if VarIsNull(V) or VarIsEmpty(V) then
CreateNULLNode(RootNode,Node, Name)
else
begin
Info := RemTypeRegistry.VariantToInfo(V, soTryAllSchema in Options);
if Info = nil then
raise ESOAPDomConvertError.Create(SUnsupportedVariant);
RemTypeRegistry.InfoToURI(Info, URI, TypeName, IsScalar);
if IsXMLDateTimeTypeInfo(Info)
{(Info.Kind = tkClass) and (GetTypeData(Info).ClassType = TXSDateTime)} then
begin
S := DateTimeToXMLTime(V);
end else
S := V;
CreateScalarNodeXS(RootNode, Node, Name, URI, TypeName, S);
end;
end;
end;
function TSOAPDomConv.MakeArrayNode(RootNode, Node: IXMLNode; const Name, URI, TypeName: InvString;
Indices: array of Integer): IXMLNode;
var
ArraySpec, Dims: InvString;
I: Integer;
First: Boolean;
SoapPre, Pre, TypeNs: InvString;
ID: string;
MultiRefNode: IXMLNode;
begin
{ Assume we have a variant type and don't create an array node }
if (URI = '') or (TypeName = '') then
begin
Result := Node.AddChild(Name);
end else
begin
if (soSendMultiRefArray in Options) and not (soDocument in Options) then
begin
ID := GetNewID;
Pre := FindPrefixForURI(RootNode, Node, URI, True);
Result := Node.AddChild(MakeNodeName(Pre, Name));
Result.Attributes[SXMLHREF] := SHREFPre + ID;
Pre := FindPrefixForURI(RootNode, Node, SSoap11EncodingS5, True);
MultiRefNode := CreateMultiRefNode(RootNode, MakeNodeName(Pre, SSoapEncodingArray), ID); { do not localize }
SetNodeType(RootNode, MultiRefNode, SSoap11EncodingS5, SSoapEncodingArray);
Result := MultiRefNode;
end else
begin
MultiRefNode := nil;
if (soDocument in Options) then
begin
TypeNS := ''
end
else
begin
TypeNS := SSoap11EncodingS5;
end;
Result := CreateTypedNode(RootNode, Node, Name, TypeNS, SSoapEncodingArray);
end;
begin
I := 0;
if Indices[I] = 0 then
begin
while (I < Length(Indices) - 1) and (Indices[I] = 0) do
begin
Dims := Dims + '[]'; { do not localize }
Inc(I);
end;
end;
First := True;
if I < Length(Indices) then
begin
Dims := Dims + '['; { do not localize }
while I < Length(Indices) do
begin
if not First then
begin
Dims := Dims + ','; { do not localize }
end;
First := False;
Dims := Dims + IntToStr(Indices[I]);
Inc(I);
end;
Dims := Dims + ']'; { do not localize }
end;
end;
if not (soSendUntyped in Options) and not (soDocument in Options) then
begin
SoapPre := FindPrefixForURI(RootNode, Node, SSoap11EncodingS5, True);
Pre := FindPrefixForURI(RootNode, Node, URI, True);
ArraySpec := Pre + ':' + TypeName + Dims; { do not localize }
Result.SetAttributeNS(SSoapEncodingArrayType, SSoap11EncodingS5, ArraySpec);
end;
end;
end;
function TSOAPDomConv.MakeArrayNode(RootNode, Node: IXMLNode; const Name, URI, TypeName: InvString;
Dim, Len: Integer): IXMLNode;
var
ArrayDims: TIntegerDynArray;
I: Integer;
begin
SetLength(ArrayDims, Dim);
for I := 0 to Dim - 2 do
ArrayDims[I] := 0;
ArrayDims[Dim-1] := Len;
Result := MakeArrayNode(RootNode, Node,
Name, URI, TypeName, ArrayDims);
end;
procedure TSOAPDomConv.WriteVarArrayAsB64(RootNode, Node: IXMLNode; const Name: InvString; V: Variant);
var
I, DimCount, VSize: Integer;
LoDim, HiDim: array of integer;
P: Pointer;
S, Encd: String;
ElemNode: IXMLNode;
begin
DimCount := VarArrayDimCount(V);
SetLength(LoDim, DimCount);
SetLength(HiDim, DimCount);
for I := 1 to DimCount do
begin
LoDim[I - 1] := VarArrayLowBound(V, I);
HiDim[I - 1] := VarArrayHighBound(V, I);
end;
VSize := 0;
for i := 0 to DimCount - 1 do
VSize := (HiDim[i] - LoDim[i] + 1);
P := VarArrayLock(V);
try
SetString(S, PChar(P), VSize);
finally
VarArrayUnlock(V);
end;
Encd := EncodeString(S);
ElemNode := CreateScalarNodeXS(RootNode, Node, Name, XMLSchemaNamespace, 'base64Binary', Encd); { do not localize }
end;
procedure TSOAPDomConv.WriteVarArray(RootNode, Node: IXMLNode; const Name: InvString; V: Variant);
var
I, DimCount: Integer;
LoDim, HiDim, Indices: array of integer;
V1: Variant;
ElemNode: IXMLNode;
VAPropSet: Boolean;
begin
if not VarIsArray(V) then
begin
WriteVariant(RootNode, Node, Name, V);
end
else
begin
ElemNode := Node.AddChild(Name);
DimCount := VarArrayDimCount(V);
SetLength(LoDim, DimCount);
SetLength(HiDim, DimCount);
for I := 1 to DimCount do
begin
LoDim[I - 1] := VarArrayLowBound(V, I);
HiDim[I - 1] := VarArrayHighBound(V, I);
end;
SetLength(Indices, DimCount);
for I := 0 to DimCount - 1 do
Indices[I] := LoDim[I];
VAPropSet := False;
while True do
begin
V1 := VarArrayGet(V, Indices);
if VarIsArray(V1) and not VarIsType(V1, varArray or varByte) then
begin
WriteVarArray(RootNode, ElemNode, SDefVariantElemName, V1);
ElemNode.SetAttributeNS(SVarArrayType, SBorlandTypeNamespace, VarType(V));
end else
begin
WriteVariant(RootNode, ElemNode, SDefVariantElemName, V1);
if not VAPropSet then
begin
ElemNode.SetAttributeNS(SVarArrayType, SBorlandTypeNamespace, VarType(V));
VAPropSet := True;
end;
end;
Inc(Indices[DimCount - 1]);
if Indices[DimCount - 1] > HiDim[DimCount - 1] then
for i := DimCount - 1 downto 0 do
if Indices[i] > HiDim[i] then
begin
if i = 0 then Exit;
Inc(Indices[i - 1]);
Indices[i] := LoDim[i];
end;
end;
end;
end;
function TSOAPDomConv.ReadVarArrayDim(Node: IXMLNode; IsVarVArray: Boolean; VT: TVarType): Variant;
var
Count, I: Integer;
SoapTypeInfo: PTypeInfo;
ChildNode: IXMLNode;
TypeURI, TypeName: InvString;
begin
{ Get count of ntElement children node }
Count := ntElementChildCount(Node);
if Count = 0 then
begin
Result := NULL;
Exit;
end;
{
Also, we could use the TVarType to (re)create a Variant of the
original array type; Using VarVariant, however, is more
resilient; and as long as no one cracks the Variant open - i.e.
casts to TVarData and starts accessing members directly - we're safe.
Sure hopes no one does that!!
}
Result := VarArrayCreate([0, Count -1], VarVariant);
for I := 0 to Node.ChildNodes.Count -1 do
begin
ChildNode := Node.ChildNodes[I];
{ Skip non-valid nodes }
if ChildNode.NodeType <> ntElement then
continue;
IsVarVArray := IsNodeAVarArray(ChildNode, VT);
if IsVarVarray or (ntElementChildCount(ChildNode) > 1) then
begin
Result[I] := ReadVarArrayDim(ChildNode, IsVarVArray, VT);
end else
begin
if not NodeIsNULL(ChildNode) then
begin
GetElementType(ChildNode, TypeURI, TypeName);
SoapTypeInfo := RemTypeRegistry.XSDToTypeInfo(TypeURI, TypeName);
if SoapTypeInfo = nil then
SoapTypeInfo := TypeInfo(System.WideString);
{ Handle 'dateTime' }
if IsXMLDateTimeTypeInfo(SoapTypeInfo)
{(SoapTypeInfo.Kind = tkClass) and (GetTypeData(SoapTypeInfo).ClassType = TXSDateTime)} then
begin
Result[I] := XMLTimeToDateTime(ChildNode.Text);
end else
Result[I] := TypeTranslator.CastSoapToVariant(SoapTypeInfo, ChildNode.Text);
end else
Result[I] := NULL;
end;
end;
end;
function TSOAPDomConv.IsNodeAVarArray(const Node: IXMLNode; var VT: TVarType): Boolean;
begin
if not VarIsNull(Node.GetAttributeNS(SVarArrayType, SBorlandTypeNamespace)) then
begin
VT := StrToInt(Node.GetAttributeNS(SVarArrayType, SBorlandTypeNamespace));
Result := True;
end else if not VarIsNull(Node.GetAttribute(SVarArrayType)) then
begin
VT := StrToInt(Node.GetAttribute(SVarArrayType));
Result := True;
end else
Result := False;
end;
procedure TSOAPDomConv.ConvertSoapToVariant(Node: IXMLNode; InvData: Pointer);
var
Info: PTypeInfo;
TypeURI, TypeName: InvString;
IsVarray: Boolean;
VT: TVarType;
Count: Integer;
begin
{ No children ?? }
if not Assigned(Node.ChildNodes) then
Exit;
{ Zero children }
Count := ntElementChildCount(Node);
if Count = 0 then
Variant(PVarData(InvData)^) := NULL;
IsVarray := IsNodeAVarArray(Node, VT);
{ TODO -oBB -cInvestigation : Why is IsTextElement relevant here? }
if (Count > 1) or Node.ChildNodes[0].IsTextElement or IsVarray then
Variant(PVarData(InvData)^) := ReadVarArrayDim(Node, IsVarray, VT)
else
begin
GetElementType(Node, TypeURI, TypeName);
Info := RemTypeRegistry.XSDToTypeInfo(TypeURI, TypeName);
{ If we can't figure out the type, map to a WideString }
if Info = nil then
Info := TypeInfo(System.WideString);
{ Handle dates }
if IsXMLDateTimeTypeInfo(Info)
{(Info.Kind = tkClass) and (GetTypeData(Info).ClassType = TXSDateTime)} then
begin
Variant(PVarData(InvData)^) := XMLTimeToDateTime(Node.Text);
end else
TypeTranslator.CastSoapToVariant(Info, GetNodeAsText(Node), InvData);
end;
end;
function TSOAPDomConv.FindNodeByHREF(RootNode: IXMLNode; const HREF: InvString): IXMLNode;
function findNode(root: IXMLNode): IXMLNode;
var
I: Integer;
V: Variant;
begin
for I := 0 to root.ChildNodes.Count -1 do
begin
V := root.ChildNodes[I].Attributes[SXMLID];
if not VarIsNull(V) and (SHREFPre + V = HREF) then
begin
Result := root.ChildNodes[I];
Exit;
end;
end;
end;
begin
Result := nil;
{ First look at the root node }
Result := findNode(RootNode);
{If we could not find it, move up one level }
if (Result = nil) and (RootNode.ParentNode <> nil) then
Result := findNode(RootNode.ParentNode);
end;
function GetDynArrayLength(P: Pointer): Integer;
begin
asm
MOV EAX, DWORD PTR P
CALL System.@DynArrayLength
MOV DWORD PTR [Result], EAX
end;
end;
function RecurseArray(P: Pointer; var Dims: Integer): Boolean;
var
I, Len, Size: Integer;
ElemDataP: Pointer;
Size2: Integer;
begin
Result := True;
if Dims > 1 then
begin
if not Assigned(P) then
Exit;
Len := GetDynArrayLength(P);
ElemDataP := Pointer(PInteger(P)^);
Size := GetDynArrayLength(ElemDataP);
for I := 0 to Len - 1 do
begin
Size2 := GetDynArrayLength(ElemDataP);
if Size <> Size2 { GetDynArrayLength(ElemDataP) } then
begin
Result := False;
Exit;
end;
if Dims > 1 then
begin
Dec(Dims);
Result := RecurseArray(ElemDataP, Dims);
if not Result then
Exit;
end;
ElemDataP := Pointer(PInteger(Pointer(Integer(P) + 4))^);
end;
end;
end;
function IsArrayRect(P: Pointer; Dims: Integer): Boolean;
var
D: Integer;
begin
D := Dims;
Result := RecurseArray(P, D);
end;
procedure GetDims(ArrP: Pointer; DimAr: TIntegerDynArray; Dims: Integer);
var
I: Integer;
begin
for I := 0 to Dims - 1 do
begin
DimAr[I] := GetDynArrayLength(ArrP);
if I < Dims - 1 then
begin
if Assigned(ArrP) then
ArrP := Pointer(PInteger(ArrP)^);
end;
end;
end;
procedure TSOAPDomConv.WriteRectDynArrayElem(RootNode, Node: IXMLNode;
Info: PTypeInfo;
Size, Dim: Integer;
P: Pointer;
const TypeName: InvString);
var
I: Integer;
S: InvString;
IsNull: Boolean;
ArNode: IXMLNode;
ElemSize: Integer;
NodeName: InvString;
begin
if Dim > 1 then
begin
Dec(Dim);
for I := 0 to Size-1 do
begin
ElemSize := GetDynArrayLength(Pointer(PInteger(P)^));
WriteRectDynArrayElem(RootNode, Node, Info, ElemSize, Dim, Pointer(PInteger(P)^), TypeName);
P := Pointer(Integer(P) + sizeof(Pointer));
end;
end
else
begin
{ Determine name of node }
if (soDocument in options) then
NodeName := TypeName
else
NodeName := DefArrayElemName;
{ Write out data }
for I := 0 to Size-1 do
begin
if Info.Kind = tkClass then
begin
ConvertObjectToSOAP(NodeName, P, RootNode, Node, 1);
end else
if Info.Kind = tkVariant then
begin
ConvertVariantToSoap(RootNode, Node, NodeName, Info, P, 1, NULL, False);
end else
begin
if Info.Kind = tkEnumeration then
S := ConvertEnumToSoap(Info, P, 1)
else
TypeTranslator.CastNativeToSoap(Info, S, P, IsNull);
{ Create node }
if (soDocument in Options) then
ArNode := Node.AddChild(NodeName)
else
ArNode := Node.AddChild(NodeName, ''); { No namespace prefix }
{ Set Value }
ArNode.Text := S;
end;
P := Pointer( Integer(P) + GetTypeSize(Info));
end;
end;
end;
procedure TSOAPDomConv.WriteRectDynArray(RootNode, Node: IXMLNode; Info: PTypeInfo; Dims: Integer; P: Pointer; const TypeName: InvString);
begin
WriteRectDynArrayElem(RootNode, Node, Info, GetDynArrayLength(P), Dims, P, TypeName);
end;
function ArrayIsNull(PObj: Pointer): Boolean;
var
P: Pointer;
begin
Result := not Assigned(PObj);
if not Result then
begin
P := Pointer(PInteger(PObj)^);
Result := (P = Pointer($0000));
end;
end;
function ByteArrayInfo(ElemInfo: PTypeInfo): Boolean;
begin
Result := ((ElemInfo.Kind = tkInteger{Pascal}) or (ElemInfo.Kind = tkChar{C++})) and
(GetTypeData(ElemInfo).OrdType = otUByte);
end;
procedure TSOAPDomConv.WriteNonRectDynArray(RootNode, Node: IXMLNode;
const Name: InvString;
Info: PTypeInfo;
const URI, TypeName: InvString;
P: Pointer; Dim: Integer);
var
I, Len: Integer;
ArrayNode: IXMLNode;
ElemInfo: PTypeInfo;
ElemURI, ElemName: WideString;
PData: Pointer;
begin
{ Null Array }
if ArrayIsNull(P) then
begin
CreateNullNode(RootNode, Node, Name);
Exit;
end;
{ Retrieve Array Element information }
ElemInfo := GetDynArrayNextInfo(Info);
RemClassRegistry.TypeInfoToXSD(ElemInfo, ElemURI, ElemName);
{ Handle array of bytes }
if (Dim = 1) and ByteArrayInfo(ElemInfo) then
begin
ConvertByteArrayToSoap(RootNode, Node, Name, Info, P);
Exit;
end;
Len := GetDynArrayLength(P);
ArrayNode := MakeArrayNode(RootNode, Node, Name, URI, TypeName, Dim, Len);
{ Write elements }
for I := 0 to Len-1 do
begin
{ If underlying element is array, pass pointer to data }
if ElemInfo.Kind = tkDynArray then
PData := Pointer(PInteger(P)^)
else
PData := P;
WriteNonRectDynArrayElem(RootNode, ArrayNode, ElemInfo, ElemURI, ElemName, PData, Dim-1);
P := Pointer(Integer(P) + GetTypeSize(ElemInfo));
end;
end;
function TSOAPDomConv.WriteNonRectDynArrayElem(RootNode, Node: IXMLNode; Info: PTypeInfo;
const URI, TypeName: InvString; P: Pointer;
Dim: Integer): Integer;
var
NodeName : InvString;
begin
Result := 0;
{ Compute NodeName }
if soDocument in Options then
NodeName := TypeName
else
NodeName := DefArrayElemName;
{ MultiD?? Recurse }
if (Dim > 0) or (Info.Kind = tkDynArray) then
begin
WriteNonRectDynArray(RootNode, Node, NodeName, Info, URI, TypeName, P, Dim);
end
else
begin
WriteRectDynArrayElem(RootNode, Node, Info, 1, 1, P, TypeName);
end;
end;
procedure TSOAPDomConv.ReadVariant(Node: IXMLNode; P: Pointer);
var
SoapTypeInfo: PTypeInfo;
URI, TypeName: InvString;
begin
Variant(PVarData(P)^) := NULL;
if Node.ChildNodes.Count > 1 then
Variant(PVarData(P)^) := ReadVarArrayDim(Node)
else
begin
GetElementType(Node, URI, TypeName);
SoapTypeInfo := RemTypeRegistry.XSDToTypeInfo(URI, TypeName);
if SoapTypeInfo = nil then
SoapTypeInfo := TypeInfo(System.WideString);
if IsXMLDateTimeTypeInfo(SoapTypeInfo)
{(SoapTypeInfo.Kind = tkClass) and (GetTypeData(SoapTypeInfo).ClassType = TXSDateTime)} then
begin
Variant(PVarData(P)^) := XMLTimeToDateTime(Node.Text);
end else
Variant(PVarData(P)^) := TypeTranslator.CastSoapToVariant(SoapTypeInfo, GetNodeAsText(Node));
end;
end;
procedure TSOAPDomConv.ReadRow(RootNode, Node: IXMLNode; var CurElem: Integer; Size: Integer; P: Pointer; Info: PTypeInfo);
var
I: Integer;
URI, TypeName, ID: InvString;
IsNull, IsScalar: Boolean;
ChildNode: IXMLNode;
begin
{ Make sure we're not trying to deserialize past the size
of data we received }
if CurElem > ntElementChildCount(Node) then
raise ESOAPDomConvertError.CreateFmt(SArrayTooManyElem, [Node.xml]);
if Info.Kind = tkClass then
begin
for I := 0 to Size-1 do
begin
RemClassRegistry.ClassToURI(GetTypeData(Info).ClassType, URI, TypeName, IsScalar);
ChildNode := ntElementChild(Node, CurElem);
PTObject(P)^ := ConvertSOAPToObject(RootNode, ChildNode,
GetTypeData(Info).ClassType, URI, TypeName, P, 1);
P := Pointer(Integer(P) + sizeof(Pointer));
Inc(CurElem);
end;
end else if Info.Kind = tkVariant then
begin
for I := 0 to Size-1 do
begin
ChildNode := ntElementChild(Node, CurElem);
ReadVariant(ChildNode, P);
P := Pointer(Integer(P) + GetTypeSize(Info));
Inc(CurElem);
end;
end else
begin
IsNull := False;
for I := 0 to Size-1 do
begin
ChildNode := ntElementChild(Node, CurElem);
ChildNode := GetDataNode(RootNode, ChildNode, ID);
TypeTranslator.CastSoapToNative(Info, ChildNode.Text, P, IsNull);
P := Pointer(Integer(P) + GetTypeSize(Info));
Inc(CurElem);
end;
end;
end;
procedure TSOAPDomConv.ReadRectDynArrayElem(RootNode, Node: IXMLNode; Info: PTypeInfo; Size, Dim: Integer; P: Pointer;
var CurElem: Integer);
var
I: Integer;
ElemSize: Integer;
ID: InvString;
begin
Node := GetDataNode(RootNode, Node, ID);
if Dim > 1 then
begin
Dec(Dim);
for I := 0 to Size - 1 do
begin
ElemSize := GetDynArrayLength(Pointer(PInteger(P)^));
ReadRectDynArrayElem(RootNode, Node, Info, ElemSize, Dim, Pointer(PInteger(P)^), CurElem);
P := Pointer(Integer(P) + sizeof(Pointer));
end;
end
else
begin
if CurElem > ntElementChildCount(Node) then
raise ESOAPDomConvertError.Create(SArrayTooManyElem);
ReadRow(RootNode, Node, CurElem, Size, P, Info);
end;
end;
procedure TSOAPDomConv.ReadRectDynArray(RootNode, Node: IXMLNode; Info: PTypeInfo; Dims: Integer; P: Pointer; CurElem: Integer);
begin
ReadRectDynArrayElem(RootNode, Node, Info, GetDynArrayLength(P), Dims, P, CurElem);
end;
function TSOAPDomConv.ConvertSoapToNativeArrayElem(ArrayInfo, ElemInfo: PTypeInfo;
RootNode, Node: IXMLNode; ArrayDesc: TSOAPArrayDesc; Dims, CurDim: Integer; DataP: Pointer): Pointer;
var
PElem, ChildP, DynP: Pointer;
Size, I: Integer;
ID: InvString;
ChildNode: IXMLNode;
NodeOffset: Integer;
CurElem: Integer;
IntVec: TIntegerDynArray;
DimCnt: Integer;
begin
Result := nil;
Node := GetDataNode(RootNode, Node, ID);
if Dims > 1 then
begin
if (Length(ArrayDesc) > 0 ) and ArrayDesc[CurDim].MultiDim then
begin
DynP := Pointer(PInteger(DataP)^);
DynArraySetLength(DynP, ArrayInfo, Length(ArrayDesc[CurDim].Dims), PLongInt(ArrayDesc[CurDim].Dims));
Result := DynP;
Size := Length(ArrayDesc[CurDim].Dims);
NodeOffset := 0;
ReadRectDynArray(RootNode, Node, ElemInfo, Size, DynP, NodeOffset);
end else
begin
Size := ntElementChildCount(Node);
DynP := Pointer(PInteger(DataP)^);
if Length(ArrayDesc) = 0 then
begin
SetLength(IntVec, 1);
DimCnt := 1;
end else
begin
SetLength(IntVec, Length(ArrayDesc[CurDim].Dims));
DimCnt := Length(ArrayDesc[CurDim].Dims);
end;
for I := 0 to Length(IntVec) -1 do
IntVec[I] := ntElementChildCount(Node);
DynArraySetLength(DynP, ArrayInfo, DimCnt, PLongInt(IntVec));
PElem := DynP;
Result := DynP;
Dec(Dims);
Inc(CurDim);
for I := 0 to Size - 1 do
begin
ChildNode := GetDataNode(RootNode, Node.ChildNodes[I], ID);
ChildP := ConvertSoapToNativeArrayElem(GetDynArrayNextInfo(ArrayInfo), ElemInfo, RootNode,
ChildNode, ArrayDesc, Dims, CurDim, PElem);
PInteger(PElem)^ := Integer(ChildP);
PElem := Pointer(Integer(PElem) + sizeof(Pointer));
end;
end;
end else if Dims = 1 then
begin
begin
Size := ntElementChildCount(Node);
if DataP <> nil then
begin
DynP := Pointer(PInteger(DataP)^);
if Length(ArrayDesc) = 0 then
begin
SetLength(IntVec, 1);
DimCnt := 1;
end else
begin
SetLength(IntVec, Length(ArrayDesc[CurDim].Dims));
DimCnt := Length(ArrayDesc[CurDim].Dims);
end;
for I := 0 to Length(IntVec) -1 do
IntVec[I] := ntElementChildCount(Node);
DynArraySetLength(DynP, ArrayInfo, DimCnt, PLongInt(IntVec) );
PElem := DynP;
Result := DynP;
CurElem := 0;
if Size > 0 then
ReadRow(RootNode, Node, CurElem, Size, PElem, ElemInfo);
end;
end;
end;
end;
function TSOAPDomConv.ConvertSoapToNativeArray(DataP: Pointer; TypeInfo: PTypeInfo;
RootNode, Node: IXMLNode): Pointer;
var
Dims: Integer;
ElemInfo: PTypeInfo;
ArrayDesc: TSOAPArrayDesc;
ArrayType: InvString;
V : Variant;
TypeURI, TypeName: InvString;
S: String;
ArrayLen: Integer;
DynP: Pointer;
begin
GetElementType(Node, TypeURI, TypeName);
GetDynArrayElTypeInfo(TypeInfo, ElemInfo, Dims);
if ElemInfo = nil then
raise ESOAPDomConvertError.CreateFmt(SNoArrayElemRTTI, [TypeInfo.Name]);
if (Dims = 1) and
((ElemInfo.Kind = tkInteger) or (ElemInfo.Kind = tkChar)) and
(GetTypeData(ElemInfo).OrdType = otUByte) and
{ Some SOAP implementations don't send the XML Namespace!! }
(({(TypeURI = SXMLSchemaURI_2001) and }(TypeName = 'base64Binary')) or
((TypeURI = SSoap11EncodingS5) and (TypeName = 'base64')) or
{ Some SOAP implementations don't send the type!! }
(TypeName = '' )) then
begin
S := DecodeString(Node.Text);
ArrayLen := Length(S);
DynP := Pointer(PInteger(DataP)^);
DynArraySetLength(DynP, TypeInfo, 1, @ArrayLen);
Move(S[1], DynP^, Length(S));
Result := DynP;
end else
begin
V := Node.GetAttributeNS(SSoapEncodingArrayType, SSoap11EncodingS5);
if not VarIsNull(V) then
begin
ArrayType := V;
ArrayType := Copy(ArrayType, Pos('[',ArrayType), High(Integer)); { do not localize }
end;
(* -- Allow array of variants to be MultiD --
if ElemnInfo.Kind = tkVariant then
begin
SetLength(ArrayDesc, Dims);
SetLength(ArrayDesc[0].Dims, 1);
end;
*)
ParseDims(ArrayType, ArrayDesc);
Result := ConvertSoapToNativeArrayElem(TypeInfo, ElemInfo, RootNode, Node, ArrayDesc, Dims, 0, DataP);
end;
end;
function TSOAPDomConv.GetNewID: string;
begin
Result := IntToStr(FIDs);
Inc(FIDs);
end;
function TSOAPDomConv.CreateMultiRefNode(RootNode: IXMLNode; const Name, ID: InvString): IXMLNode;
var
I, J: Integer;
begin
Result := RootNode.OwnerDocument.CreateNode(Name);
Result.Attributes[SXMLID] := ID;
I := 0;
while I < Length(MultiRefNodes) do
begin
if MultiRefNodes[I].Node = RootNode then
break;
Inc(I);
end;
if I = Length(MultiRefNodes) then
begin
SetLength(MultiRefNodes, I + 1);
MultiRefNodes[I].Node := RootNode;
end;
{ Parent Multi Ref right away }
RootNode.ChildNodes.Add(Result);
{ Store children with rootnode }
J := Length(MultiRefNodes[I].MultiRefChildren);
SetLength(MultiRefNodes[I].MultiRefChildren, J + 1);
MultiRefNodes[I].MultiRefChildren[J] := Result;
end;
procedure TSOAPDomConv.FinalizeMultiRefNodes;
var
I, J: Integer;
RootNode: IXMLNode;
RefNode: IXMLNode;
begin
for I := 0 to Length(MultiRefNodes) - 1 do
begin
for J := 0 to Length(MultiRefNodes[I].MultiRefChildren) - 1 do
begin
RootNode := MultiRefNodes[I].Node;
{ Get Ref node and add }
RefNode := MultiRefNodes[I].MultiRefChildren[J];
{ Parent if not already }
if RefNode.ParentNode <> RootNode then
RootNode.ChildNodes.Add(RefNode);
end;
end;
for I := 0 to Length(MultiRefNodes) - 1 do
begin
SetLength(MultiRefNodes[I].MultiRefChildren, 0);
end;
SetLength(MultiRefNodes, 0);
end;
function GetOrdPropEx(Instance: TObject; PropInfo: PPropInfo): Longint;
asm
{ -> EAX Pointer to instance }
{ EDX Pointer to property info }
{ <- EAX Longint result }
PUSH EBX
PUSH EDI
MOV EDI,[EDX].TPropInfo.PropType
MOV EDI,[EDI]
MOV BL,otSLong
CMP [EDI].TTypeInfo.Kind,tkClass
JE @@isClass
CMP [EDI].TTypeInfo.Kind,tkDynArray
JE @@isDynArray
CMP [EDI].TTypeInfo.Kind,tkInterface
JE @@isInterface
XOR ECX,ECX
MOV CL,[EDI].TTypeInfo.Name.Byte[0]
MOV BL,[EDI].TTypeInfo.Name[ECX+1].TTypeData.OrdType
@@isDynArray:
@@isInterface:
@@isClass:
MOV ECX,[EDX].TPropInfo.GetProc
CMP [EDX].TPropInfo.GetProc.Byte[3],$FE
MOV EDX,[EDX].TPropInfo.Index
JB @@isStaticMethod
JA @@isField
{ the GetProc is a virtual method }
MOVSX ECX,CX { sign extend slot offs }
ADD ECX,[EAX] { vmt + slotoffs }
CALL dword ptr [ECX] { call vmt[slot] }
JMP @@final
@@isStaticMethod:
CALL ECX
JMP @@final
@@isField:
AND ECX,$00FFFFFF
ADD ECX,EAX
MOV AL,[ECX]
CMP BL,otSWord
JB @@final
MOV AX,[ECX]
CMP BL,otSLong
JB @@final
MOV EAX,[ECX]
@@final:
CMP BL,otSLong
JAE @@exit
CMP BL,otSWord
JAE @@word
CMP BL,otSByte
MOVSX EAX,AL
JE @@exit
AND EAX,$FF
JMP @@exit
@@word:
MOVSX EAX,AX
JE @@exit
AND EAX,$FFFF
@@exit:
POP EDI
POP EBX
end;
procedure SetOrdPropEx(Instance: TObject; PropInfo: PPropInfo;
Value: Longint); assembler;
asm
{ -> EAX Pointer to instance }
{ EDX Pointer to property info }
{ ECX Value }
PUSH EBX
PUSH ESI
PUSH EDI
MOV EDI,EDX
MOV ESI,[EDI].TPropInfo.PropType
MOV ESI,[ESI]
MOV BL,otSLong
CMP [ESI].TTypeInfo.Kind,tkClass
JE @@isClass
CMP [ESI].TTypeInfo.Kind,tkDynArray
JE @@isDynArray
CMP [ESI].TTypeInfo.Kind,tkInterface
JE @@isInterface
XOR EBX,EBX
MOV BL,[ESI].TTypeInfo.Name.Byte[0]
MOV BL,[ESI].TTypeInfo.Name[EBX+1].TTypeData.OrdType
@@isDynArray:
@@isInterface:
@@isClass:
MOV EDX,[EDI].TPropInfo.Index { pass Index in DX }
CMP EDX,$80000000
JNE @@hasIndex
MOV EDX,ECX { pass value in EDX }
@@hasIndex:
MOV ESI,[EDI].TPropInfo.SetProc
CMP [EDI].TPropInfo.SetProc.Byte[3],$FE
JA @@isField
JB @@isStaticMethod
{ SetProc turned out to be a virtual method. call it }
MOVSX ESI,SI { sign extend slot offset }
ADD ESI,[EAX] { vmt + slot offset }
CALL dword ptr [ESI]
JMP @@exit
@@isStaticMethod:
CALL ESI
JMP @@exit
@@isField:
AND ESI,$00FFFFFF
ADD EAX,ESI
MOV [EAX],CL
CMP BL,otSWord
JB @@exit
MOV [EAX],CX
CMP BL,otSLong
JB @@exit
MOV [EAX],ECX
@@exit:
POP EDI
POP ESI
POP EBX
end;
function TSOAPDomConv.SerializationOptions(ATypeInfo: PTypeInfo): TSerializationOptions;
begin
if ATypeInfo.Kind = tkClass then
Result := SerializationOptions(GetTypeData(ATypeInfo).ClassType)
else
Result := [];
end;
function TSOAPDomConv.SerializationOptions(Obj: TObject): TSerializationOptions;
begin
Result := SerializationOptions(Obj.ClassType);
if Obj.InheritsFrom(TRemotable) then
Result := Result + TRemotable(Obj).SerializationOptions;
end;
function TSOAPDomConv.SerializationOptions(Cls: TClass): TSerializationOptions;
begin
Result := RemTypeRegistry.SerializeOptions(Cls);
end;
function TSOAPDomConv.MultiRefObject(Cls: TClass): Boolean;
var
MultiRefOpt: TObjMultiOptions;
SerialOpts: TSerializationOptions;
begin
if (soXXXXHdr in Options) then
begin
Result := False;
Exit;
end;
SerialOpts := SerializationOptions(Cls);
if (xoSimpleTypeWrapper in SerialOpts) then
begin
Result := False;
Exit;
end;
{ Retrieve registered options of this type }
MultiRefOpt := RemTypeRegistry.ClassOptions(Cls);
{ Are we multiref'in the node }
{ NOTE: We opt to not allow Scalars to be multirefed?? }
Result := (soSendMultiRefObj in Options)
and (MultiRefOpt <> ocNoMultiRef)
and (not (soDocument in Options))
and (not RemTypeRegistry.IsClassScalar(Cls));
end;
function TSOAPDomConv.CreateObjectNode(Instance: TObject; RootNode, ParentNode: IXMLNode;
const Name, URI: InvString;
ObjConvOpts: TObjectConvertOptions): InvString;
begin
{ Allow TRemotable_xxxx classes to perform custom serialization }
if Assigned(Instance) and Instance.InheritsFrom(TRemotable) then
TRemotable(Instance).ObjectToSOAP(RootNode, ParentNode, Self, Name, URI, ObjConvOpts, Result)
else
ObjInstanceToSOAP(Instance, RootNode, ParentNode, Name,
URI, ObjConvOpts, Result);
end;
function TSOAPDomConv.ObjInstanceToSOAP(Instance: TObject; RootNode, ParentNode: IXMLNode;
const NodeName, NodeNamespace: InvString; ObjConvOpts: TObjectConvertOptions;
out RefID: InvString): IXMLNode;
var
ID, Pre: InvString;
I, Count: Integer;
PropList: PPropList;
Kind: TTypeKind;
V: Variant;
Obj: TObject;
ElemURI, TypeName, TypeNamespace, NodeVal: InvString;
PrefixNode, InstNode, ElemNode, AttrNode: IXMLNode;
P: Pointer;
ExtPropName: InvString;
MultiRef, UsePrefix, SerializeProps, CanHaveType, HolderClass, LitParam : Boolean;
SerialOpts: TSerializationOptions;
ClsType: TClass;
begin
{ Get a new ID for this node - in case we're MultiRefing... }
RefID := GetNewID;
{ Retrieve the Serializatin options of this class }
SerialOpts := SerializationOptions(Instance);
{ Type attribute }
HolderClass := (xoHolderClass in SerialOpts);
LitParam := (xoLiteralParam in SerialOpts);
{ Object Custom Serialization flags }
UsePrefix := not (ocoDontPrefixNode in ObjConvOpts);
SerializeProps := not (ocoDontSerializeProps in ObjConvOpts);
CanHaveType := not (ocoDontPutTypeAttr in ObjConvOpts) and (not LitParam);
{ Get namespace prefix }
PrefixNode := RootNode;
{ Are we multiref'in the node }
MultiRef := MultiRefObject(Instance.ClassType);
{ No prefix in document style - or if flag set to false }
if not (soDocument in Options) and UsePrefix then
Pre := FindPrefixForURI(PrefixNode, ParentNode, NodeNamespace, True)
else
Pre := '';
{ Create the Node, if necessary }
if not HolderClass then
begin
if not MultiRef then
begin
if (soDocument in Options) then
begin
RemClassRegistry.ClassToURI(Instance.ClassType, TypeNamespace, TypeName);
if TypeNamespace = XMLSchemaNamespace then
InstNode := ParentNode.AddChild(NodeName)
else
InstNode := ParentNode.AddChild(NodeName, TypeNamespace);
end
else
begin
if UsePrefix or (Pre <> '') then
InstNode := ParentNode.AddChild(MakeNodeName(Pre, NodeName))
else
{ Create a node without any prefix }
InstNode := ParentNode.AddChild(NodeName, '');
end;
end
else
InstNode := CreateMultiRefNode(RootNode, MakeNodeName(Pre, NodeName), RefID);
end
else
{ Here this class was simply a holder - only its members are serialized!
the class itself is stealth }
InstNode := ParentNode;
{ Set Result Node }
Result := InstNode;
{ Can this type generate xsi:type attributes?? }
if CanHaveType then
begin
{ Retrieve Type Namespace }
RemClassRegistry.ClassToURI(Instance.ClassType, TypeNamespace, TypeName);
{ xsi:type=?? }
SetNodeType(PrefixNode, InstNode, TypeNamespace, TypeName);
end;
{ Store info that we multi refed' }
if MultiRef then
AddMultiRefNode(RefID, Instance);
{ Serialize Published Properties ?? }
if SerializeProps then
begin
{ Serialized published properties }
Count := GetTypeData(Instance.ClassInfo)^.PropCount;
if Count > 0 then
begin
GetMem(PropList, Count * SizeOf(Pointer));
try
GetPropInfos(Instance.ClassInfo, PropList);
{ Complex type as wrapper of a simple type }
if (xoSimpleTypeWrapper in SerialOpts) and (Count = 1) then
begin
NodeVal := GetObjectPropAsText(Instance, PropList[0]);
InstNode.Text := NodeVal;
end else
begin
for I := 0 to Count - 1 do
begin
ExtPropName := RemTypeRegistry.GetExternalPropName(Instance.ClassInfo, PropList[I].Name);
Kind := (PropList[I].PropType)^.Kind;
{ Class Property }
if Kind = tkClass then
begin
Obj := GetObjectProp(Instance, PropList[I]);
if Obj = nil then
begin
if not (soDontSendEmptyNodes in Options) then
CreateNULLNode(RootNode, InstNode, ExtPropName)
end
else
begin
ClsType := GetTypeData((PropList[I].PropType)^).ClassType;
RemClassRegistry.ClassToURI(ClsType, ElemURI, TypeName);
MultiRef := MultiRefObject(ClsType);
if not MultiRef then
begin
if IsObjectWriting(Obj) then
raise ESOAPDomConvertError.CreateFmt(SNoSerializeGraphs, [Obj.ClassName]);
AddObjectAsWriting(Instance);
{ NOTE: prefix for nested types ?? }
CreateObjectNode(Obj, RootNode, InstNode, ExtPropName, ElemURI, ObjConvOpts);
RemoveObjectAsWriting(Obj);
end else
begin
ElemNode := InstNode.AddChild(ExtPropName, '');
ID := FindMultiRefNodeByInstance(Obj);
{ NOTE: prefix for nested types ?? }
if ID = '' then
ID := CreateObjectNode(Obj, RootNode, InstNode, ExtPropName, ElemURI, ObjConvOpts);
ElemNode.Attributes[SXMLHREF] := SHREFPre + ID;
end;
end;
{ Array property }
end else if Kind = tkDynArray then
begin
P := Pointer(GetOrdPropEx(Instance, PropList[I]));
ConvertNativeArrayToSoap(RootNode, InstNode, ExtPropName,
(PropList[I].PropType)^, P, 0,
(xoInlineArrays in SerialOpts));
{ Variant property }
end else if Kind = tkVariant then
begin
V := GetVariantProp(Instance, PropList[I]);
ConvertVariantToSoap(RootNode, InstNode, ExtPropName, nil, nil, 0, V, True);
end else
{ Simple type property ?? }
begin
if not RemTypeRegistry.TypeInfoToXSD((PropList[I].PropType)^, ElemURI, TypeName) then
raise ESOAPDomConvertError.CreateFmt(SRemTypeNotRegistered, [(PropList[I].PropType)^.Name]);
{ Here we check the stored property flag - that's the flag to use an
attribute instead of a separate node - if the property is marked
stored False, we'll use an attribute instead }
if not IsStoredProp(Instance, PropList[I]) then
begin
{ Typically attributes go on the root/instance node. However, in some
cases the class serializes members and then the attribute goes on
the last member; this option allows attributes on specific members }
AttrNode := InstNode;
if (xoAttributeOnLastMember in SerialOpts) then
begin
if ntElementChildCount(InstNode) > 0 then
AttrNode := ntElementChild(InstNode, ntElementChildCount(InstNode)-1);
end;
NodeVal := GetObjectPropAsText(Instance, PropList[I]);
{ Check if user does not want to send empty nodes }
if (not (soDontSendEmptyNodes in Options)) or (NodeVal <> '') then
AttrNode.Attributes[ExtPropName] := NodeVal;
end
else
begin
NodeVal := GetObjectPropAsText(Instance, PropList[I]);
{ Check if user does not want to send empty nodes }
if (not (soDontSendEmptyNodes in Options)) or (NodeVal <> '') then
ElemNode := CreateScalarNodeXS(RootNode, InstNode, ExtPropName, ElemURI, TypeName, NodeVal);
end;
end;
end;
end;
finally
FreeMem(PropList, Count * SizeOf(Pointer));
end;
end;
end;
end;
procedure TSOAPDomConv.ConvertObjectToSOAP(const Name: InvString;
ObjP: Pointer; RootNode, Node: IXMLNOde; NumIndirect: Integer);
var
ElemNode: IXMLNOde;
I: Integer;
ID: string;
URI, TypeName: WideString;
P: Pointer;
Instance: TObject;
MultiRef: Boolean;
begin
P := ObjP;
for I := 0 to NumIndirect - 1 do
P := Pointer(PInteger(P)^);
Instance := P;
if Assigned(Instance) and not Instance.InheritsFrom(TRemotable) then
raise ESOAPDomConvertError.CreateFmt(SUnsuportedClassType, [Instance.ClassName]);
if not Assigned(Instance) then
CreateNULLNode(RootNode, Node, Name)
else
begin
{ Retrieve URI of Type }
if not RemClassRegistry.ClassToURI(Instance.ClassType, URI, TypeName) then
raise ESOAPDomConvertError.CreateFmt(SRemTypeNotRegistered, [Instance.ClassName]);
MultiRef := MultiRefObject(Instance.ClassType);
{ NOTE: SOAP Attachments will enter this path as they are never multirefed }
if not MultiRef then
begin
if IsObjectWriting(Instance) then
raise ESOAPDomConvertError.CreateFmt(SNoSerializeGraphs, [Instance.ClassName]);
AddObjectAsWriting(Instance);
{ NOTE: Prefixing nodes can cause problems with some
SOAP implementations. However, not doing so causes problems
too ?? }
CreateObjectNode(Instance, RootNode, Node, Name, URI, [ocoDontPrefixNode]);
RemoveObjectAsWriting(Instance);
end
else
begin
ID := FindMultiRefNodeByInstance(Instance);
{ NOTE: Passing 'True' to prefix here can cause problems with some
SOAP implementations. However, removing it can cause problems
too ?? }
if ID = '' then
{ NOTE: The ref'ed node must be of the TypeName - not the referring node name }
ID := CreateObjectNode(Instance, RootNode, Node, TypeName, URI, []);
ElemNode := Node.AddChild(Name, '' {No Namespace prefix});
ElemNode.Attributes[SXMLHREF] := SHREFPre + ID;
end;
end;
end;
function TSOAPDomConv.GetObjectPropAsText(Instance: TObject;
PropInfo: PPropInfo): WideString;
var
I: LongInt;
E: Extended;
I64: Int64;
DT: TDateTime;
begin
case (PropInfo.PropType)^.Kind of
tkInteger:
begin
I := GetOrdProp(Instance, PropInfo);
Result := IntToStr(I);
end;
tkFloat:
begin
E := GetFloatProp(Instance, PropInfo);
if PropInfo.PropType^ = TypeInfo(TDateTime) then
begin
DT := E;
Result := DateTimeToXMLTime(DT);
end
else
Result := FloatToStrEx(E);
end;
tkWString:
Result := GetWideStrProp(Instance, PropInfo);
tkString,
tkLString:
Result := GetStrProp(Instance, PropInfo);
tkInt64:
begin
I64 := GetInt64Prop(Instance, PropInfo);
Result := IntToStr(I64);
end;
tkEnumeration:
begin
Result := GetEnumProp(Instance, PropInfo);
if PropInfo.PropType^ = TypeInfo(System.Boolean) then
Result := Lowercase(Result);
end;
tkChar:
begin
I := GetOrdProp(Instance, PropInfo);
Result := InvString(Char(I));
end;
tkWChar:
begin
I := GetOrdProp(Instance, PropInfo);
Result := InvString(WideChar(I));
end;
tkClass:
;
tkSet,
tkMethod,
tkArray,
tkRecord,
tkInterface,
tkDynArray,
tkVariant:
raise ESOAPDomConvertError.CreateFmt(SUnexpectedDataType, [KindNameArray[(PropInfo.PropType)^.Kind]]);
end;
end;
function TSOAPDomConv.GetTypeBySchemaNS(Node: IXMLNode; const URI: InvString): Variant;
var
I: Integer;
begin
Result := Node.GetAttributeNS(SSoapType, URI);
if VarIsNull(Result) and (soTryAllSchema in Options) then
begin
for I := Low(XMLSchemaInstNamepspaces) to High(XMLSchemaInstNamepspaces) do
begin
Result := Node.GetAttributeNS(SSoapType, XMLSchemaInstNamepspaces[I]);
if not VarIsNull(Result) then
break;
end;
end;
end;
function TSOAPDomConv.GetElementType(Node: IXMLNode; var TypeURI, TypeName: InvString): Boolean;
var
S : InvString;
V: Variant;
Pre: InvString;
begin
TypeURI := '';
TypeName := '';
Result := False;
if (Node.NamespaceURI = SSoap11EncodingS5) and
(ExtractLocalName(Node.NodeName) = SSoapEncodingArray) then
begin
TypeURI := SSoap11EncodingS5;
TypeName := SSoapEncodingArray;
Result := True;
end else
begin
V := GetTypeBySchemaNS(Node, XMLSchemaInstNameSpace);
if VarIsNull(V) then
V := Node.GetAttribute(SSoapType);
if not VarIsNull(V) then
begin
S := V;
if IsPrefixed(S) then
begin
TypeName := ExtractLocalName(S);
Pre := ExtractPrefix(S);
TypeURI := Node.FindNamespaceURI(Pre);
end
else
begin
TypeName := S;
TypeURI := '';
end;
Result := True;
end;
end
end;
procedure TSOAPDomConv.SetObjectPropFromText(Instance: TObject; PropInfo: PPropInfo; const SoapData: WideString);
var
I: LongInt;
E: Extended;
I64: Int64;
begin
case (PropInfo.PropType)^.Kind of
tkInteger:
begin
I := StrToInt(SoapData);
SetOrdProp(Instance, PropInfo, I);
end;
tkFloat:
begin
if PropInfo.PropType^ = TypeInfo(TDateTime) then
begin
E := XMLTimeToDateTime(SoapData);
end
else
E := StrToFloatEx(SoapData);
SetFloatProp(Instance, PropInfo, E);
end;
tkWString:
SetWideStrProp(Instance, PropInfo, SoapData);
tkString,
tkLString:
SetStrProp(Instance, PropInfo, SoapData);
tkInt64:
begin
I64 := StrToInt64(SoapData);
SetInt64Prop(Instance, PropInfo, I64);
end;
tkEnumeration:
SetEnumPropEx(Instance, PropInfo, SoapData);
tkChar,
tkWChar:
if SoapData <> '' then
SetOrdProp(Instance, PropInfo, Integer(SoapData[1]));
tkClass:
;
tkSet,
tkMethod,
tkArray,
tkRecord,
tkInterface,
tkDynArray,
tkVariant:
raise ESOAPDomConvertError.CreateFmt(SUnexpectedDataType, [KindNameArray[(PropInfo.PropType)^.Kind]]);
end;
end;
{ This event is a convenient way to find out if a particular
member of a class was not deserialized off the wire }
procedure TSOAPDomConv.ObjectMemberNoShow(const ClassName: string; const MemberName: string);
begin
if Assigned(FOnMemberDataNotReceived) then
FOnMemberDataNotReceived(ClassName, MemberName);
end;
procedure TSOAPDomConv.UnhandledNode(const Name: string; NodeXML: WideString);
begin
if Assigned(FOnUnhandledNode) then
FOnUnhandledNode(Name, NodeXML);
end;
procedure TSOAPDomConv.LoadObject(Instance: TObject; RootNode, Node: IXMLNode);
begin
if Instance.InheritsFrom(TRemotable) then
TRemotable(Instance).SOAPToObject(RootNode, Node, Self)
else
InitObjectFromSOAP(Instance, RootNode, Node);
end;
procedure TSOAPDomConv.InitObjectFromSOAP(Instance: TObject; RootNode, Node: IXMLNode);
var
ProcessedNodes: TBooleanDynArray;
ChildNode: IXMLNode;
function FindPropNodeIndex(const Node: IXMLNode; const PropName: WideString): Integer;
var
Index: Integer;
begin
Result := -1;
for Index := 0 to Node.ChildNodes.Count-1 do
begin
if ProcessedNodes[Index] = False then
begin
ChildNode := Node.ChildNodes[Index];
if ExtractLocalName(ChildNode.NodeName) = PropName then
begin
Result := Index;
Exit
end;
end;
end;
end;
var
PropList: PPropList;
Count, NodeCount: Integer;
Kind: TTypeKind;
I, K: Integer;
Obj: TObject;
IsNull: Boolean;
URI, TypeName: InvString;
ArrayPtr: Pointer;
V: Variant;
SoapTypeInfo: PTypeInfo;
ExternalPropName: WideString;
SerialOpts: TSerializationOptions;
ID: InvString;
HolderNode, AttrNode: IXMLNode;
SimpleHolder, IsAttribute: Boolean;
begin
HolderNode := nil;
SimpleHolder := False;
SerialOpts := SerializationOptions(Instance);
{ If we have a holder class, it's to pick up properties [unless we're
in literal mode or inlining arrays ] }
if (xoHolderClass in SerialOpts) then
begin
if not (xoInlineArrays in SerialOpts) or (xoLiteralParam in SerialOpts) then
begin
{ Store the data node that was destined for this class }
{ And move up to pick up other attribute/members... }
HolderNode := Node;
Node := Node.ParentNode;
end;
{ SimpleHolder - implies we're interested in only one node }
SimpleHolder := (xoAttributeOnLastMember in SerialOpts);
end;
Count := GetTypeData(Instance.ClassInfo)^.PropCount;
if Count > 0 then
begin
GetMem(PropList, Count * SizeOf(Pointer));
try
{ Iterate through properties matching them to nodes or attributes }
GetPropInfos(Instance.ClassInfo, PropList);
{ Complex type as simple type wrapper }
if (xoSimpleTypeWrapper in SerialOpts) and (Count = 1) then
begin
SetObjectPropFromText(Instance, PropList[0], GetNodeAsText(Node));
end
else
begin
{ If we're not handling a holder, keep track of nodes we process }
{ A simple holder is only interested in it's data node }
if not SimpleHolder then
begin
NodeCount := Node.ChildNodes.Count;
SetLength(ProcessedNodes, NodeCount);
for I := 0 to NodeCount-1 do
ProcessedNodes[I] := False;
end else
SetLength(ProcessedNodes, 0);
for I := 0 to Count-1 do
begin
Kind := (PropList[I].PropType)^.Kind;
IsAttribute := not IsStoredPropConst(nil, PropList[I])
and (Kind <> tkClass)
and (Kind <> tkDynArray)
and (Kind <> tkVariant);
ExternalPropName := RemTypeRegistry.GetExternalPropName(Instance.ClassInfo, PropList[I].Name);
{ Is the property coming down as an attribute }
if IsAttribute then
begin
{ Get the potential attribute Node }
if SimpleHolder then
AttrNode := HolderNode
else
AttrNode := Node;
if AttrNode.HasAttribute(ExternalPropName) then
SetObjectPropFromText(Instance, PropList[I], AttrNode.Attributes[ExternalPropName])
else
{ Here something we were expecting did *NOT* come down the wire ?? }
ObjectMemberNoShow(Instance.ClassName, PropList[I].Name);
continue;
end
else
begin
if not SimpleHolder then
K := FindPropNodeIndex(Node, ExternalPropName)
else
K := Node.ChildNodes.IndexOf(HolderNode);
{ If we have a node to deserialize }
if K <> -1 then
begin
{ Mark node as processed }
if Length(ProcessedNodes) > K then
ProcessedNodes[K] := True;
{ Get Child with data we want node }
ChildNode := Node.ChildNodes[K];
{ Here we match the property to a Child Node }
if Kind = tkClass then
begin
Obj := ConvertSOAPToObject(RootNode, ChildNode, GetTypeData((PropList[I].PropType)^).ClassType,
'', '', nil, 0);
if Obj <> nil then
SetObjectProp(Instance, PropList[I], Obj);
end else if Kind = tkDynArray then
begin
IsNull := NodeIsNull(ChildNode);
{ In document mode, the node could have attributes that we want to retrieve }
if (not IsNull) or (soDocument in Options) then
begin
GetElementType(ChildNode, URI, TypeName);
ArrayPtr := nil;
{ Here if the object we're writing to inlines members, then here we pass a parent node }
if (xoinlineArrays in SerialOpts) then
ChildNode := ChildNode.ParentNode;
ArrayPtr := ConvertSoapToNativeArray(@ArrayPtr, (PropList[I].PropType)^,
RootNode, ChildNode);
SetOrdPropEx(Instance, PropList[I], Integer(ArrayPtr));
end;
end else if Kind = tkVariant then
begin
if ChildNode.ChildNodes.Count > 1 then
V := ReadVarArrayDim(ChildNode)
else
begin
if NodeIsNull(ChildNode) then
V := NULL
else
begin
GetElementType(ChildNode, URI, TypeName);
SoapTypeInfo := RemTypeRegistry.XSDToTypeInfo(URI, TypeName);
if SoapTypeInfo = nil then
SoapTypeInfo := TypeInfo(System.WideString);
if IsXMLDateTimeTypeInfo(SoapTypeInfo)
{(SoapTypeInfo.Kind = tkClass) and (GetTypeData(SoapTypeInfo).ClassType = TXSDateTime)} then
begin
V := XMLTimeToDateTime(ChildNode.Text);
end else
V := TypeTranslator.CastSoapToVariant(SoapTypeInfo, ChildNode.Text);
end;
end;
SetVariantProp(Instance, PropList[I], V);
end else
begin
{ Some SOAP implementations use multiref nodes even for simple types }
ChildNode := GetDataNode(RootNode, ChildNode, ID);
SetObjectPropFromText(Instance, PropList[I], GetNodeAsText(ChildNode));
end;
end else
begin
ObjectMemberNoShow(Instance.ClassName, PropList[I].Name);
end;
end;
end;
{ Here we report on Nodes that we did not deserialize }
for I := 0 to Length(ProcessedNodes)-1 do
begin
if not ProcessedNodes[I] then
UnhandledNode(Instance.ClassName, Node.ChildNodes[I].XML);
end;
end;
finally
FreeMem(PropList, Count * SizeOf(Pointer));
end;
end;
end;
function TSOAPDomConv.ConvertSOAPToObject(RootNode, Node: IXMLNode; AClass: TClass;
const URI, TypeName: WideString; ObjP: Pointer; NumIndirect: Integer): TObject;
var
ID: InvString;
ObjNode: IXMLNode;
IsScalar: Boolean;
Obj, LoadedObj: TObject;
P: Pointer;
I: Integer;
NodeClass: TClass;
NodeURI, NodeTypeName: InvString;
LegalRef: Boolean;
S: string;
begin
if NodeIsNULL(Node) then
begin
Result := nil;
{ NOTE: In document mode a node could contain attributes that we want to retrieve }
{ TODO: Clean up this logic - not good enough for cases where we don't have attrs }
if (Node = nil) or not (soDocument in Options) then
Exit;
end;
P := ObjP;
for I := 0 to NumIndirect - 1 do
P := Pointer(PInteger(P)^);
Obj := TObject(P);
S := ExtractLocalName(Node.NodeName);
ObjNode := GetDataNode(RootNode, Node, ID);
if (ID <> '') and (not AClass.InheritsFrom(TSOAPAttachment)) then
LoadedObj := FindMultiRefNodeByID(ID)
else
LoadedObj := nil;
if Assigned(LoadedObj) then
Result := LoadedObj
else
begin
GetElementType(ObjNode, NodeURI, NodeTypeName);
NodeClass := RemTypeRegistry.URIToClass(NodeURI, NodeTypeName, IsScalar);
LegalRef := True;
if Assigned(Obj) then
begin
try
if Obj.ClassType <> nil then
LegalRef := True;
except
LegalRef := False;
end;
end;
if Assigned(Obj) and LegalRef then
begin
if (NodeClass <> nil) and (NodeClass <> Obj.ClassType) then
Obj := NodeClass.Create;
end else
begin
if (NodeClass <> nil) and NodeClass.InheritsFrom(AClass) then
Obj := TRemotableClass(NodeClass).Create
else
Obj := TRemotableClass(AClass).Create;
end;
Result := Obj;
if ID <> '' then
AddMultiRefNode(ID, Obj);
LoadObject(Obj, RootNode, ObjNode);
end;
end;
procedure TSOAPDomConv.ConvertByteArrayToSoap(RootNode, Node: IXMLNode; const Name: InvString;
Info: PTypeInfo; P: Pointer);
var
S, S1: String;
begin
SetLength(S, GetDynArrayLength(P));
Move(P^, S[1], Length(S));
S1 := EncodeString(S);
CreateScalarNodeXS(RootNode, Node, Name, XMLSchemaNamespace, 'base64Binary', S1); { do not localize }
end;
procedure TSOAPDomConv.ConvertNativeArrayToSoap(RootNode, Node: IXMLNode;
const Name: InvString; Info: PTypeInfo; P: Pointer; NumIndirect: Integer; InlineElements: Boolean);
var
Dims, I: Integer;
DimAr: TIntegerDynArray;
URI, TypeName: InvString;
ElemNode: IXMLNode;
ElemInfo: PTypeInfo;
UseNonRect: Boolean;
begin
for I := 0 to NumIndirect - 1 do
P := Pointer(PInteger(P)^);
{ Retrieve dimensions and most-underlying element }
Dims := 0;
GetDynArrayElTypeInfo(Info, ElemInfo, Dims);
{ Make sure we have RTTI for element }
if not RemTypeRegistry.TypeInfoToXSD(ElemInfo, URI, TypeName) then
raise ESOAPDomConvertError.CreateFmt(SRemTypeNotRegistered, [ElemInfo.Name]);
{ Rectangular vs. Non-rectangular writers?? }
UseNonRect := Assigned(P) and ((IsArrayRect(P, Dims)=False) or
((soDocument in Options) and (Dims > 1)) or
ByteArrayInfo(ElemInfo) or
(soSendUntyped in Options)
);
if not UseNonRect then
begin
SetLength(DimAr, Dims);
if Assigned(P) then
GetDims(P, DimAr, Dims);
GetDynArrayElTypeInfo(Info, ElemInfo, Dims);
{ Array of bytes is handled separately - serialized as base64 }
if (Dims = 1) and ByteArrayInfo(ElemInfo) then
begin
ConvertByteArrayToSoap(RootNode, Node, Name, Info, P);
end else
begin
if not InlineElements then
begin
ElemNode := MakeArrayNode(RootNode, Node, Name, URI, TypeName, DimAr);
end
else
begin
{ Here we're inlining the array members }
ElemNode := Node;
{ The array elements get the typename }
TypeName := Name;
end;
WriteRectDynArray(RootNode, ElemNode, ElemInfo, Dims, P, TypeName);
{ Not exactly optimal approach - but works for now -
Check if user does not want to send empty nodes and snip
this node if it has no child nodes - another approach would
be not to parent the array node and wait until we know but... ?? }
if (soDontSendEmptyNodes in Options) and
(ElemNode.ChildNodes.Count < 1) then
begin
Node.ChildNodes.Delete(Node.ChildNodes.IndexOf(ElemNode));
end;
end;
end else
begin
WriteNonRectDynArray(RootNode, Node, Name, Info, URI, TypeName, P, Dims);
{ NOTE: For now I'm not putting the snip empty node code in non rectangular
arrays as there has not been a need for this here yet }
end;
end;
procedure TSOAPDomConv.ConvertNativeDataToSoap(RootNode, Node: IXMLNode;
const Name: InvString; Info: PTypeInfo; P: Pointer; NumIndirect: Integer);
var
ElemNode: IXMLNode;
TypeName: InvString;
URI, S: InvString;
IsNull: Boolean;
I: Integer;
IsScalar: Boolean;
begin
case Info.Kind of
tkClass:
ConvertObjectToSOAP(Name, P, RootNode, Node, NumIndirect);
tkDynArray:
ConvertNativeArrayToSoap(RootNode, Node, Name, Info, P, NumIndirect);
tkSet,
tkMethod,
tkArray,
tkRecord,
tkInterface:
raise ESOAPDomConvertError.CreateFmt(SDataTypeNotSupported, [KindNameArray[Info.Kind]]);
tkVariant:
begin
ConvertVariantToSoap(RootNode, Node, Name, Info, P, NumIndirect, NULL, False);
end;
else
begin
if Info.Kind = tkEnumeration then
begin
if not RemClassRegistry.InfoToURI(Info, URI, TypeName, IsScalar) then
raise ESOAPDomConvertError.CreateFmt(SRemTypeNotRegistered, [Info.Name]);
S := ConvertEnumToSoap(Info, P, NumIndirect);
ElemNode := CreateScalarNodeXS(RootNode, Node, Name, URI, TypeName, S);
end else
begin
if NumIndirect > 1 then
for I := 0 to NumIndirect - 2 do
P := Pointer(PInteger(P)^);
TypeTranslator.CastNativeToSoap(Info, S, P, IsNull);
if IsNull then
CreateNULLNode(RootNode,ElemNode, Name)
else
begin
if not RemTypeRegistry.TypeInfoToXSD(Info, URI, TypeName) then
raise ESOAPDomConvertError.CreateFmt(SRemTypeNotRegistered, [Info.Name]);
ElemNode := CreateScalarNodeXS(RootNode, Node, Name, URI, TypeName, S);
end;
end
end;
end;
end;
procedure TSOAPDomConv.AddMultiRefNode(const ID: string; Instance: Pointer);
var
I: Integer;
begin
for I := 0 to Length(RefMap) -1 do
if (RefMap[I].ID = ID) and ( RefMap[I].Instance = Instance) then
Exit;
I := Length(RefMap);
SetLength(RefMap, I + 1);
RefMap[I].ID := ID;
RefMap[I].Instance :=Instance;
end;
function TSOAPDomConv.FindMultiRefNodeByInstance(Instance: Pointer): string;
var
I: Integer;
begin
for I := 0 to Length(RefMap) - 1 do
if RefMap[I].Instance = Instance then
Result := RefMap[I].ID;
end;
function TSOAPDomConv.FindMultiRefNodeByID(const ID: string): Pointer;
var
I: Integer;
begin
Result := nil;
for I := 0 to Length(RefMap) - 1 do
if RefMap[I].ID = ID then
begin
Result := RefMap[I].Instance;
break;
end;
end;
procedure TSOAPDomConv.ConvertSoapToNativeData(DataP: Pointer; TypeInfo: PTypeInfo;
Context: TDataContext; RootNode, Node: IXMLNode; Translate, ByRef: Boolean;
NumIndirect: Integer);
var
TypeUri, TypeName: InvString;
IsNull: Boolean;
Obj: TObject;
P: Pointer;
I: Integer;
ID: InvString;
begin
Node := GetDataNode(RootNode, Node, ID);
IsNull := NodeIsNull(Node);
if TypeInfo.Kind = tkVariant then
begin
if NumIndirect > 1 then
DataP := Pointer(PInteger(DataP)^);
if IsNull then
begin
Variant(PVarData(DataP)^) := NULL;
end else
ConvertSoapToVariant(Node, DataP);
end else
if TypeInfo.Kind = tkDynArray then
begin
P := DataP;
for I := 0 to NumIndirect - 2 do
P := Pointer(PInteger(P)^);
P := ConvertSoapToNativeArray(P, TypeInfo, RootNode, Node);
if NumIndirect = 1 then
PInteger(DataP)^ := Integer(P)
else if NumIndirect = 2 then
begin
DataP := Pointer(PInteger(DataP)^);
PInteger(DataP)^ := Integer(P);
end;
end else
if TypeInfo.Kind = tkClass then
begin
Obj := ConvertSOAPToObject(RootNode, Node, GetTypeData(TypeInfo).ClassType, TypeURI, TypeName, DataP, NumIndirect);
if NumIndirect = 1 then
PTObject(DataP)^ := Obj
else if NumIndirect = 2 then
begin
DataP := Pointer(PInteger(DataP)^);
PTObject(DataP)^ := Obj;
end;
end else
begin
if Translate then
begin
if NumIndirect > 1 then
DataP := Pointer(PInteger(DataP)^);
if not TypeTranslator.CastSoapToNative(TypeInfo, GetNodeAsText(Node), DataP, IsNull) then
raise ESOAPDomConvertError.CreateFmt(STypeMismatchInParam, [node.nodeName]);
end;
end;
end;
function TSOAPDomConv.ConvertEnumToSoap(Info: PTypeInfo;
P: Pointer; NumIndirect: Integer): InvString;
var
Value: Pointer;
I: Integer;
begin
Value := P;
for I := 0 to NumIndirect - 2 do
Value := Pointer(PInteger(Value)^);
if NumIndirect = 0 then
Result := GetEnumName(Info, Byte(Value))
else
Result := GetEnumName(Info, PByte(Value)^);
{ NOTE: No need to use SameTypeInfo here since C++ has proper case }
if Info = TypeInfo(System.Boolean) then
Result := Lowercase(Result);
end;
function TSOAPDomConv.ConvertSoapToEnum(Info: PTypeInfo; S: InvString;
IsNull: Boolean): Integer;
begin
Result := GetEnumValueEx(Info, S);
end;
function TSOAPDomConv.CreateNULLNode(RootNode, ParentNode: IXMLNode; const Name: InvString; UseParentNode: Boolean): IXMLNode;
begin
if not UseParentNode then
Result := ParentNode.AddChild(Name, '')
else
Result := ParentNode;
Result.SetAttributeNS(SSoapNIL, XMLSchemaInstNameSpace, STrue);
end;
function TSOAPDomConv.NodeIsNULL(Node: IXMLNode): Boolean;
var
V: Variant;
begin
if Node = nil then
begin
Result := True;
Exit;
end;
Result := False;
V := Node.GetAttributeNS(SSoapNull, XMLSchemaInstNameSpace);
if VarIsNull(V) then
V := Node.GetAttributeNS(SSoapNIL, XMLSchemaInstNamespace);
if not VarIsNull(V) and ((V = '1') or SameText(V, STrue)) then { do not localize }
Result := True;
if Node.ChildNodes.Count = 0 then
begin
V := Node.Attributes[SXMLHREF];
if VarIsNull(V) then
Result := True;
end;
end;
function TSOAPDomConv.ChildNodesAreNull(Node: IXMLNode): Boolean;
var
I: Integer;
Child: IXMLNode;
begin
Result := True;
if Node.ChildNodes.Count > 0 then
begin
for I := 0 to Node.ChildNodes.Count-1 do
begin
Child := Node.ChildNodes[I];
if Child.NodeType <> ntElement then
continue;
if not NodeIsNull(Node.ChildNodes[I]) then
begin
Result := False;
Exit;
end;
end;
end;
end;
function TSOAPDomConv.FindPrefixForURI(RootNode, Node: IXMLNode; const URI: InvString; DeclIfNone: Boolean = False): InvString;
var
DeclNode: IXMLNode;
begin
DeclNode := RootNode.FindNamespaceDecl(URI);
if DeclNode <> nil then
Result := ExtractLocalName(DeclNode.NodeName);
if (Result = '') and DeclIfNone then
Result := AddNamespaceDecl(RootNode, URI);
end;
function TSOAPDomConv.AddNamespaceDecl(Node: IXMLNode; const URI: InvString): InvString;
begin
Result := Node.OwnerDocument.GeneratePrefix(Node);
Node.DeclareNamespace(Result, URI);
end;
function TSOAPDomConv.CreateTypedNode(RootNode, ParentNode: IXMLNode;
const NodeName, URI: WideString; TypeName: WideString; GenPre: Boolean = False): IXMLNode;
begin
if GenPre then
Result := ParentNode.AddChild(NodeName, URI, True)
else
begin
{ Send no namespace for nested nodes }
if (soDocument in Options) then
Result := ParentNode.AddChild(NodeName)
else
Result := ParentNode.AddChild(NodeName, '');
end;
SetNodeType(RootNode, Result, URI, TypeName);
end;
function TSOAPDomConv.CreateScalarNodeXS(RootNode, ParentNode: IXMLNode;
const NodeName, URI, TypeName: WideString; const Value: WideString; GenPre: Boolean = False): IXMLNode;
begin
Result := CreateTypedNode(RootNode, ParentNode, NodeName, URI, TypeName);
Result.Text := Value;
end;
procedure TSOAPDomConv.SetNodeType(RootNode, InstNode: IXMLNode; const ElemURI,
TypeName: InvString);
var
Pre: InvString;
begin
if not (soSendUntyped in Options) and not (soDocument in Options) then
begin
{ Namespace prefix of Typename }
if ElemURI <> '' then
Pre := FindPrefixForURI(RootNode, InstNode, ElemURI, True)
else
Pre := '';
InstNode.SetAttributeNS(SSoapType, XMLSchemaInstNameSpace, MakeNodeName(Pre, TypeName));
end;
end;
function TSOAPDomConv.GetOptions: TSOAPConvertOptions;
begin
Result := FOptions;
end;
procedure TSOAPDomConv.SetOptions(const Value: TSOAPConvertOptions);
begin
{ NOTE: Some options are mutually exclusive - for example, soDocument
does not jive well with others. We could provide logic to handle
this here or we can rely on the caller to know how to set options }
FOptions := Value;
end;
function TSOAPDomConv.GetNodeAsText(Node: IXMLNode): InvString;
var
I: Integer;
begin
Result := '';
if Node.IsTextElement then
Result := Node.Text
else
for I := 0 to Node.ChildNodes.Count - 1 do
Result := Result + Node.ChildNodes[I].XML;
end;
function TSOAPDomConv.GetDataNode(RootNode, Node: IXMLNode; var ID: InvString): IXMLNode;
var
V: Variant;
REF: InvString;
RefNode: IXMLNode;
begin
ID := '';
Result := Node;
if Result = nil then
Exit;
V := Node.Attributes[SXMLHREF];
if not VarIsNull(V) then
begin
REF := V;
if REF <> '' then
begin
RefNode := FindNodeByHREF(RootNode, REF);
{ See if RefNode is one level up }
if not Assigned(RefNode) and Assigned(RootNode.ParentNode) then
RefNode := GetDataNode(RootNode.ParentNode, Node, REF);
if Assigned(RefNode) then
begin
Result := RefNode;
ID := Copy(REF, 2, High(Integer));
end;
end;
end else
begin
V := Node.Attributes[SXMLID];
if not VarIsNull(V) then
ID := V;
end;
end;
procedure TSOAPDomConv.CheckEncodingStyle(Node: IXMLNode);
var
V: Variant;
begin
V := Node.GetAttributeNS(SSoapEncodingAttr, SSoapNameSpace);
if not VarIsNull(V) then
begin
if V <> SSoap11EncodingS5 then
raise ESOAPDomConvertError.CreateFmt(SUnsupportedEncodingSyle, [V]);
end;
end;
procedure TSOAPDomConv.AddObjectAsWriting(Instance: TObject);
var
I: Integer;
begin
{
for I := 0 to Length(ObjsWriting) - 1 do
if ObjsWriting[I] = Instance then
Exit;
}
I := Length(ObjsWriting);
SetLength(ObjsWriting, I + 1);
ObjsWriting[I] := Instance;
end;
function TSOAPDomConv.IsObjectWriting(Instance: TObject): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 to Length(ObjsWriting) -1 do
if ObjsWriting[I] = Instance then
begin
Result := True;
break;
end;
end;
procedure TSOAPDomConv.RemoveObjectAsWriting(Instance: TObject);
var
I, J: Integer;
begin
I := 0;
while I < Length(ObjsWriting) do
begin
if ObjsWriting[I] = Instance then
break;
Inc(I);
end;
if I < Length(ObjsWriting) then
begin
for J := I to Length(ObjsWriting) - 2 do
ObjsWriting[J] := ObjsWriting[J+1];
SetLength(ObjsWriting, Length(ObjsWriting) -1);
end;
end;
procedure TSOAPDomConv.ResetMultiRef;
begin
SetLength(RefMap, 0);
SetLength(ObjsWriting, 0);
end;
end.
|
unit uFrmCompareSet;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons,uDataDefine, DB, ADODB, ComCtrls;
type
TfrmCompareSet = class(TForm)
btnCancel: TSpeedButton;
btnOK: TSpeedButton;
OpenDialog1: TOpenDialog;
ADOConnection: TADOConnection;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
GroupBox1: TGroupBox;
Label1: TLabel;
btnFindSource: TSpeedButton;
edtSourceFile: TEdit;
GroupBox2: TGroupBox;
Label5: TLabel;
Label4: TLabel;
Label3: TLabel;
Label2: TLabel;
btnTest: TSpeedButton;
edtDestIP: TEdit;
edtDestUser: TEdit;
edtDestPassword: TEdit;
edtDestDBName: TEdit;
procedure btnFindSourceClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure btnOKClick(Sender: TObject);
procedure btnTestClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
//源数据库结构文件
SourceFile : string;
//目标数据库连接
DestDBConn : RDBConnection;
end;
var
frmCompareSet: TfrmCompareSet;
implementation
{$R *.dfm}
procedure TfrmCompareSet.btnCancelClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TfrmCompareSet.btnFindSourceClick(Sender: TObject);
begin
if OpenDialog1.Execute then
begin
edtSourceFile.Text := OpenDialog1.FileName;
end;
end;
procedure TfrmCompareSet.btnOKClick(Sender: TObject);
begin
DestDBConn.strIp := edtDestIP.Text;
DestDBConn.strUser := edtDestUser.Text;
DestDBConn.strPassword := edtDestPassword.Text;
DestDBConn.strDBName := edtDestDBName.Text;
SourceFile := edtSourceFile.Text;
if not FileExists(SourceFile) then
begin
Application.MessageBox('提示','源数据库文件不存在',MB_OK + MB_ICONERROR);
exit;
end;
ModalResult := mrOk;
end;
procedure TfrmCompareSet.btnTestClick(Sender: TObject);
var
connString : string;
begin
connString := 'Provider=SQLOLEDB.1;Persist Security Info=False;User ID=%s;Password=%s;Initial Catalog=%s;Data Source=%s';
connString := Format(connString,[edtDestUser.Text,
edtDestPassword.Text,edtDestDBName.Text,edtDestIP.Text]);
ADOConnection.ConnectionString := connString;
try
try
ADOConnection.Open;
Application.MessageBox('数据库连接成功','提示',MB_OK + MB_ICONINFORMATION);
except on e: Exception do
Application.MessageBox(PChar(Format('数据库连接错误:%s',[e.Message])),'提示',MB_OK + MB_ICONERROR);
end;
finally
ADOConnection.Close;
end;
end;
end.
|
unit rhlMDBase;
interface
uses
rhlCore, sysutils;
type
{ TrhlMDBase }
TrhlMDBase = class abstract(TrhlHash)
protected
FH: array of DWord;
const FC: array[1..8] of DWord =
($50a28be6, $5a827999, $5c4dd124, $6ed9eba1,
$6d703ef3, $8f1bbcdc, $7a6d76e9, $a953fd4e);
public
constructor Create; override;
procedure Init; override;
procedure Final(var ADigest); override;
end;
implementation
{ TrhlMDBase }
constructor TrhlMDBase.Create;
begin
HashSize := 16;
BlockSize := 64;
end;
procedure TrhlMDBase.Init;
begin
inherited;
SetLength(FH, HashSize div SizeOf(DWord));
FH[0] := $67452301;
FH[1] := $EFCDAB89;
FH[2] := $98BADCFE;
FH[3] := $10325476;
end;
procedure TrhlMDBase.Final(var ADigest);
var
bits: QWord;
pad: TBytes;
padIndex: QWord;
begin
bits := FProcessedBytes * 8;
if FBuffer.Pos < 56 then
padIndex := 56 - FBuffer.Pos
else
padIndex := 120 - FBuffer.Pos;
SetLength(pad, padIndex + 8);
pad[0] := $80;
Move(bits, pad[padIndex], SizeOf(bits));
Inc(padIndex, 8);
UpdateBytes(pad[0], padindex);
Move(FH[0], ADigest, Length(FH) * SizeOf(DWord));
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC GUIx layer API }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.UI.Intf;
interface
uses
{$IFDEF MSWINDOWS}
Winapi.Windows,
{$ENDIF}
System.Classes,
FireDAC.Stan.Intf, FireDAC.Stan.Error;
type
IFDGUIxLoginDialog = interface;
IFDGUIxTimer = interface;
IFDGUIxWaitCursor = interface;
IFDGUIxAsyncExecuteDialog = interface;
IFDGUIxErrorDialog = interface;
IFDGUIxScriptDialogInfoProvider = interface;
IFDGUIxScriptDialog = interface;
{ --------------------------------------------------------------------------}
{ Login dialog }
{ --------------------------------------------------------------------------}
TFDGUIxLoginAction = procedure of object;
TFDGUIxLoginHistoryStorage = (hsRegistry, hsFile);
TFDGUIxLoginDialogEvent = procedure (ASender: TObject; var AResult: Boolean) of object;
IFDGUIxLoginDialog = interface(IUnknown)
['{3E9B315B-F456-4175-A864-B2573C4A2200}']
// private
function GetConnectionDef: IFDStanConnectionDef;
function GetOnHide: TNotifyEvent;
function GetOnShow: TNotifyEvent;
function GetCaption: String;
function GetChangeExpiredPassword: Boolean;
function GetHistoryEnabled: Boolean;
function GetHistoryKey: String;
function GetHistoryStorage: TFDGUIxLoginHistoryStorage;
function GetHistoryWithPassword: Boolean;
function GetLoginRetries: Integer;
function GetOnChangePassword: TFDGUIxLoginDialogEvent;
function GetOnLogin: TFDGUIxLoginDialogEvent;
function GetVisibleItems: TStrings;
procedure SetConnectionDef(const AValue: IFDStanConnectionDef);
procedure SetOnHide(const AValue: TNotifyEvent);
procedure SetOnShow(const AValue: TNotifyEvent);
procedure SetCaption(const AValue: String);
procedure SetChangeExpiredPassword(const AValue: Boolean);
procedure SetHistoryEnabled(const AValue: Boolean);
procedure SetHistoryKey(const AValue: String);
procedure SetHistoryStorage(const AValue: TFDGUIxLoginHistoryStorage);
procedure SetHistoryWithPassword(const AValue: Boolean);
procedure SetLoginRetries(const AValue: Integer);
procedure SetOnChangePassword(const AValue: TFDGUIxLoginDialogEvent);
procedure SetOnLogin(const AValue: TFDGUIxLoginDialogEvent);
procedure SetVisibleItems(const AValue: TStrings);
// public
procedure GetAllLoginParams;
function Execute(AAction: TFDGUIxLoginAction = nil): Boolean;
property ConnectionDef: IFDStanConnectionDef read GetConnectionDef write SetConnectionDef;
property Caption: String read GetCaption write SetCaption;
property HistoryEnabled: Boolean read GetHistoryEnabled write SetHistoryEnabled;
property HistoryWithPassword: Boolean read GetHistoryWithPassword write SetHistoryWithPassword;
property HistoryStorage: TFDGUIxLoginHistoryStorage read GetHistoryStorage write SetHistoryStorage;
property HistoryKey: String read GetHistoryKey write SetHistoryKey;
property VisibleItems: TStrings read GetVisibleItems write SetVisibleItems;
property LoginRetries: Integer read GetLoginRetries write SetLoginRetries;
property ChangeExpiredPassword: Boolean read GetChangeExpiredPassword write SetChangeExpiredPassword;
property OnHide: TNotifyEvent read GetOnHide write SetOnHide;
property OnShow: TNotifyEvent read GetOnShow write SetOnShow;
property OnLogin: TFDGUIxLoginDialogEvent read GetOnLogin write SetOnLogin;
property OnChangePassword: TFDGUIxLoginDialogEvent read GetOnChangePassword write SetOnChangePassword;
end;
{ --------------------------------------------------------------------------}
{ Timer used in GUI }
{ --------------------------------------------------------------------------}
IFDGUIxTimer = interface(IUnknown)
['{3E9B315B-F456-4175-A864-B2573C4A2207}']
// private
function GetEnabled: Boolean;
procedure SetEnabled(AValue: Boolean);
// public
procedure SetEvent(AProc: TNotifyEvent; ATimeout: LongWord);
property Enabled: Boolean read GetEnabled write SetEnabled;
end;
{ --------------------------------------------------------------------------}
{ "Wait, working ..." }
{ --------------------------------------------------------------------------}
TFDGUIxScreenCursor = (gcrNone, gcrDefault, gcrHourGlass, gcrSQLWait, gcrAppWait);
IFDGUIxWaitCursor = interface(IUnknown)
['{3E9B315B-F456-4175-A864-B2573C4A2201}']
// private
function GetWaitCursor: TFDGUIxScreenCursor;
procedure SetWaitCursor(const AValue: TFDGUIxScreenCursor);
function GetOnShow: TNotifyEvent;
procedure SetOnShow(const AValue: TNotifyEvent);
function GetOnHide: TNotifyEvent;
procedure SetOnHide(const AValue: TNotifyEvent);
// public
procedure StartWait;
procedure StopWait;
procedure PushWait;
procedure PopWait;
procedure ForceStopWait;
property WaitCursor: TFDGUIxScreenCursor read GetWaitCursor write SetWaitCursor;
property OnShow: TNotifyEvent read GetOnShow write SetOnShow;
property OnHide: TNotifyEvent read GetOnHide write SetOnHide;
end;
{ --------------------------------------------------------------------------}
{ Async execution dialog }
{ --------------------------------------------------------------------------}
IFDGUIxAsyncExecuteDialog = interface (IUnknown)
['{3E9B315B-F456-4175-A864-B2573C4A2202}']
// private
function GetOnShow: TNotifyEvent;
procedure SetOnShow(const AValue: TNotifyEvent);
function GetOnHide: TNotifyEvent;
procedure SetOnHide(const AValue: TNotifyEvent);
function GetCaption: String;
procedure SetCaption(const AValue: String);
function GetPrompt: String;
procedure SetPrompt(const AValue: String);
function GetShowDelay: Integer;
procedure SetShowDelay(AValue: Integer);
function GetHideDelay: Integer;
procedure SetHideDelay(AValue: Integer);
// public
procedure Show(const AExecutor: IFDStanAsyncExecutor);
procedure Hide;
{$IFDEF MSWINDOWS}
function IsFormActive: Boolean;
function IsFormMouseMessage(const AMsg: TMsg): Boolean;
{$ENDIF}
property Caption: String read GetCaption write SetCaption;
property Prompt: String read GetPrompt write SetPrompt;
property ShowDelay: Integer read GetShowDelay write SetShowDelay;
property HideDelay: Integer read GetHideDelay write SetHideDelay;
property OnShow: TNotifyEvent read GetOnShow write SetOnShow;
property OnHide: TNotifyEvent read GetOnHide write SetOnHide;
end;
{ --------------------------------------------------------------------------}
{ Error dialog }
{ --------------------------------------------------------------------------}
TFDGUIxErrorDialogEvent = procedure (ASender: TObject; AException: EFDDBEngineException) of object;
IFDGUIxErrorDialog = interface(IUnknown)
['{3E9B315B-F456-4175-A864-B2573C4A2203}']
// private
function GetOnShow: TFDGUIxErrorDialogEvent;
procedure SetOnShow(const AValue: TFDGUIxErrorDialogEvent);
function GetOnHide: TFDGUIxErrorDialogEvent;
procedure SetOnHide(const AValue: TFDGUIxErrorDialogEvent);
function GetCaption: String;
procedure SetCaption(const AValue: String);
function GetEnabled: Boolean;
procedure SetEnabled(const AValue: Boolean);
function GetStayOnTop: Boolean;
procedure SetStayOnTop(const AValue: Boolean);
// public
procedure Execute(E: EFDDBEngineException);
property Caption: String read GetCaption write SetCaption;
property Enabled: Boolean read GetEnabled write SetEnabled;
property StayOnTop: Boolean read GetStayOnTop write SetStayOnTop;
property OnShow: TFDGUIxErrorDialogEvent read GetOnShow write SetOnShow;
property OnHide: TFDGUIxErrorDialogEvent read GetOnHide write SetOnHide;
end;
{ --------------------------------------------------------------------------}
{ Script dialog }
{ --------------------------------------------------------------------------}
IFDGUIxScriptDialogInfoProvider = interface(IUnknown)
['{3E9B315B-F456-4175-A864-B2573C4A2206}']
// private
function GetCallStack: TStrings;
function GetTotalJobSize: Integer;
function GetTotalJobDone: Integer;
function GetTotalPct10Done: Integer;
function GetTotalErrors: Integer;
function GetIsRunning: Boolean;
// public
procedure RequestStop;
property CallStack: TStrings read GetCallStack;
property TotalJobSize: Integer read GetTotalJobSize;
property TotalJobDone: Integer read GetTotalJobDone;
property TotalPct10Done: Integer read GetTotalPct10Done;
property TotalErrors: Integer read GetTotalErrors;
property IsRunning: Boolean read GetIsRunning;
end;
TFDGUIxScriptProgressEvent = procedure (ASender, AInfoProvider: TObject) of object;
TFDGUIxScriptOutputEvent = procedure (ASender: TObject; const AStr: String) of object;
TFDGUIxScriptInputEvent = procedure (ASender: TObject; const APrompt: String;
var AResult: String) of object;
TFDGUIxScriptPauseEvent = procedure (ASender: TObject; const APrompt: String) of object;
TFDGUIxScriptOptions = set of (ssCallstack, ssConsole, ssAutoHide);
TFDScriptOutputKind = (soSeparator, soEcho, soScript, soInfo, soError, soConnect,
soServerOutput, soUserOutput, soCommand, soMacro, soData, soParam);
IFDGUIxScriptDialog = interface(IUnknown)
['{3E9B315B-F456-4175-A864-B2573C4A2205}']
// private
function GetOnShow: TNotifyEvent;
procedure SetOnShow(const AValue: TNotifyEvent);
function GetOnHide: TNotifyEvent;
procedure SetOnHide(const AValue: TNotifyEvent);
function GetOnProgress: TFDGUIxScriptProgressEvent;
procedure SetOnProgress(const AValue: TFDGUIxScriptProgressEvent);
function GetOnOutput: TFDGUIxScriptOutputEvent;
procedure SetOnOutput(const AValue: TFDGUIxScriptOutputEvent);
function GetOnInput: TFDGUIxScriptInputEvent;
procedure SetOnInput(const AValue: TFDGUIxScriptInputEvent);
function GetOnPause: TFDGUIxScriptPauseEvent;
procedure SetOnPause(const AValue: TFDGUIxScriptPauseEvent);
function GetCaption: String;
procedure SetCaption(const AValue: String);
function GetOptions: TFDGUIxScriptOptions;
procedure SetOptions(AValue: TFDGUIxScriptOptions);
// public
procedure Show;
procedure Progress(const AInfoProvider: IFDGUIxScriptDialogInfoProvider);
procedure Output(const AStr: String; AKind: TFDScriptOutputKind);
procedure Input(const APrompt: String; var AResult: String);
procedure Pause(const APrompt: String);
procedure Hide;
property Caption: String read GetCaption write SetCaption;
property Options: TFDGUIxScriptOptions read GetOptions write SetOptions;
property OnShow: TNotifyEvent read GetOnShow write SetOnShow;
property OnHide: TNotifyEvent read GetOnHide write SetOnHide;
property OnProgress: TFDGUIxScriptProgressEvent read GetOnProgress write SetOnProgress;
property OnOutput: TFDGUIxScriptOutputEvent read GetOnOutput write SetOnOutput;
property OnInput: TFDGUIxScriptInputEvent read GetOnInput write SetOnInput;
property OnPause: TFDGUIxScriptPauseEvent read GetOnPause write SetOnPause;
end;
var
FFDGUIxSilentMode: Boolean;
FFDGUIxProvider: String;
function FDGUIxSilent: Boolean;
implementation
uses
System.SysUtils,
FireDAC.Stan.Consts, FireDAC.Stan.Util;
{-------------------------------------------------------------------------------}
function FDGUIxSilent: Boolean;
begin
Result := FFDGUIxSilentMode or (TThread.CurrentThread.ThreadID <> MainThreadID);
end;
{-------------------------------------------------------------------------------}
initialization
FFDGUIxSilentMode := {$IFDEF MSWINDOWS} IsConsole {$ELSE} False {$ENDIF};
{$IFDEF MSWINDOWS}
if IsConsole then
FFDGUIxProvider := C_FD_GUIxConsoleProvider
else
{$ENDIF}
if FDIsDesignTime then
FFDGUIxProvider := C_FD_GUIxFormsProvider
else if GetClass('TFmxObject') = nil then
{$IFDEF POSIX}
FFDGUIxProvider := C_FD_GUIxConsoleProvider
{$ELSE}
FFDGUIxProvider := C_FD_GUIxFormsProvider
{$ENDIF}
else
FFDGUIxProvider := C_FD_GUIxFMXProvider;
end.
|
{**********************************************}
{ TImageBarSeries Component Editor Dialog }
{ Copyright (c) 1996-2004 by David Berneda }
{**********************************************}
unit TeeImaEd;
{$I TeeDefs.inc}
interface
uses {$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
SysUtils, Classes,
{$IFDEF CLX}
QGraphics, QControls, QForms, QDialogs, QStdCtrls, QExtCtrls, QComCtrls,
{$ELSE}
Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls,
{$ENDIF}
Chart, Series, TeeProcs, ImageBar;
type
TImageBarSeriesEditor = class(TForm)
GroupBox1: TGroupBox;
Image1: TImage;
BBrowse: TButton;
CBTiled: TCheckBox;
Bevel1: TBevel;
procedure FormShow(Sender: TObject);
procedure BBrowseClick(Sender: TObject);
procedure CBTiledClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
ImageBarSeries : TImageBarSeries;
FBarForm : TCustomForm;
procedure EnableImageControls;
public
{ Public declarations }
end;
implementation
{$IFNDEF CLX}
{$R *.DFM}
{$ELSE}
{$R *.xfm}
{$ENDIF}
Uses TeePenDlg, TeeBrushDlg, TeeConst, TeeBarEdit, TeeEdiSeri, TeeEdiPane
{$IFNDEF CLX}
,ExtDlgs
{$ENDIF}
;
procedure TImageBarSeriesEditor.FormShow(Sender: TObject);
begin
ImageBarSeries:=TImageBarSeries(Tag);
if Assigned(ImageBarSeries) then
begin
With ImageBarSeries do
begin
CBTiled.Checked:=ImageTiled;
Image1.Picture.Assign(Image);
end;
if not Assigned(FBarForm) then
FBarForm:=TFormTeeSeries(Parent.Owner).InsertSeriesForm( TBarSeriesEditor,
1,TeeMsg_GalleryBar,
ImageBarSeries);
with FBarForm as TBarSeriesEditor do
begin
LStyle.Visible:=False;
CBBarStyle.Visible:=False;
end;
EnableImageControls;
end;
end;
procedure TImageBarSeriesEditor.EnableImageControls;
begin
CBTiled.Enabled:=Assigned(ImageBarSeries.Image.Graphic);
if CBTiled.Enabled then BBrowse.Caption:=TeeMsg_ClearImage
else BBrowse.Caption:=TeeMsg_BrowseImage;
Image1.Picture.Assign(ImageBarSeries.Image);
end;
procedure TImageBarSeriesEditor.BBrowseClick(Sender: TObject);
begin
TeeLoadClearImage(Self,ImageBarSeries.Image);
EnableImageControls;
end;
procedure TImageBarSeriesEditor.CBTiledClick(Sender: TObject);
begin
ImageBarSeries.ImageTiled:=CBTiled.Checked;
end;
procedure TImageBarSeriesEditor.FormCreate(Sender: TObject);
begin
BorderStyle:=TeeBorderStyle;
{$IFDEF D6}
Image1.HelpContext:=1934;
{$ENDIF}
end;
initialization
RegisterClass(TImageBarSeriesEditor);
end.
|
//Dos Graphic Unit
unit FRS;
interface
uses go32, dos;
type
TArrBuffer = array[1..200, 1..320] of byte;
FRSInstance = object
buffer: TArrBuffer;
lname: string;
verEngine, verApp: integer;
r: registers;
constructor Create(tname: string; tverEngine, tverApp: integer);
procedure Update;
destructor Destroy;
end;
var realBuffer: TArrBuffer absolute $A000:$0000;
createQ: byte;
function MakeVersion(major, minor, minor2: byte): integer;
procedure VerticalLine(var para: FRSInstance; x, y, len, color: integer);
procedure RectFill(var para: FRSInstance; x,y,width, height, color: integer);
implementation
constructor FRSInstance.Create(tname: string; tverEngine, tverApp: integer);
begin
r.ah := 0;
r.al := $13;
intr($10, r);
fillchar(buffer, 64000, 0);
lname:= tname;
verEngine := tverEngine;
verApp := tverApp;
if (createQ = 1) then
begin
Destroy;
writeln('Instance already created!');
end
else
begin
inc(createQ);
end;
end;
procedure FRSInstance.Update;
begin
while ((inportb($3DA) and 8) > 0) do;
while ((inportb($3DA) and 8) = 0) do;
realBuffer:= buffer;
end;
function MakeVersion(major, minor, minor2: byte): integer;
begin
MakeVersion:= (major shr 8) or (minor shr 6) or (minor2 shr 2);
end;
destructor FRSInstance.Destroy;
var rn: registers;
begin
rn.ah := 0;
rn.al := $03;
intr($10, rn);
end;
procedure VerticalLine(var para: FRSInstance; x, y, len, color: integer);
var p: longint;
begin
if (x>200) or (y>320) or (x<1) or (y<1) then
begin
para.Destroy;
writeln('Line at inf pos: ',x,' ',y);
readln;
end;
while (len>0) do
begin
dec(len);
if (p>64000) then
begin
para.Destroy;
writeln('Buffer Out of range!, length to much', p);
readln;
end;
para.buffer[y, x]:= color;
y:= y + 1;
end;
end;
procedure RectFill(var para: FRSInstance; x,y,width, height, color: integer);
var i: integer;
begin
while (height > 0) do
begin
dec(height);
for i:=1 to width do
para.buffer[y+height, x+i]:= color;
end;
end;
end.
end.
|
unit comm;
interface
uses Windows, SysUtils, WinSock;
// THTTP allows exchanging data with web servers via GET and POST requests.
type
THTTP = class(TObject)
private
procedure Execute(Server : AnsiString; Port : Cardinal);
public
Header : AnsiString;
Request : AnsiString;
Response : AnsiString;
constructor Create;
procedure Get(Server,URI : AnsiString; Port : Cardinal = 80);
procedure Post(Server,URI,Data : AnsiString; Port : Cardinal = 80);
procedure CropHeader;
end;
implementation
////////////////////////////////////////////////////////////////////////////////
constructor THTTP.Create;
begin
inherited Create;
Header:='';
end;
////////////////////////////////////////////////////////////////////////////////
procedure THTTP.Execute(Server : AnsiString; Port : Cardinal);
// connects to server, sends data, waits for and returns response
var
Host : PHostEnt;
Addr : PInAddr;
Info : TSockAddrIn;
S1 : Integer;
s : AnsiString;
i : Integer;
t : Cardinal;
begin
Response:='';
// find IP
Host:=gethostbyname(PAnsiChar(Server));
if Host=nil then Exit;
Addr:=PInAddr(Host^.h_addr_list^);
// initialize request
ZeroMemory(@Info,SizeOf(Info));
Info.sin_family:=AF_INET;
Info.sin_port:=htons(Port);
Info.sin_addr:=Addr^;
// send request
S1:=socket(AF_INET,SOCK_STREAM,0);
if S1=INVALID_SOCKET then Exit;
try
if connect(S1,Info,SizeOf(Info))<>0 then Exit;
if send(S1,Request[1],Length(Request),0)=SOCKET_ERROR then Exit;
// wait up to 5min for response
t:=GetTickCount;
repeat
if GetTickCount-t>300000 then Exit;
SetLength(s,4096);
i:=recv(S1,s[1],4096,0);
SetLength(s,i);
Response:=Response+s;
until i=0;
finally
closesocket(S1);
end;
end;
////////////////////////////////////////////////////////////////////////////////
procedure THTTP.Get(Server,URI : AnsiString; Port : Cardinal = 80);
// sends GET request
begin
Request:='GET '+URI+' HTTP/1.0'#13#10+
'Host: '+Server+#13#10+
Header;
Request:=Trim(Request)+#13#10#13#10;
Execute(Server,Port);
end;
////////////////////////////////////////////////////////////////////////////////
procedure THTTP.Post(Server,URI,Data : AnsiString; Port : Cardinal = 80);
// sends POST request
begin
Request:='POST '+URI+' HTTP/1.0'#13#10+
'Host: '+Server+#13#10+
'Content-Length: '+IntToStr(Length(Data))+#13#10+
Header;
Request:=Trim(Request)+#13#10#13#10+Data;
Execute(Server,Port);
end;
////////////////////////////////////////////////////////////////////////////////
procedure THTTP.CropHeader;
// removes header from response
var
Cnt : Integer;
begin
Cnt:=Pos(#13#10#13#10,Response);
Delete(Response,1,Cnt+3);
end;
////////////////////////////////////////////////////////////////////////////////
var WSData : WSAData;
initialization
WSAStartup(2,WSData);
finalization
WSACleanUp;
end.
|
unit UAdjustment;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ExtCtrls,public_unit;
type
TFAdjustment = class(TForm)
BBA1: TBitBtn;
GroupBox8: TGroupBox;
Label56: TLabel;
Label57: TLabel;
Label58: TLabel;
Label59: TLabel;
Label60: TLabel;
Shape12: TShape;
Label3: TLabel;
Label4: TLabel;
Label55: TLabel;
Label1: TLabel;
CBA2: TCheckBox;
RBA1: TRadioButton;
RBA2: TRadioButton;
RBA5: TRadioButton;
RBA6: TRadioButton;
STA1: TStaticText;
RBA3: TRadioButton;
RBA4: TRadioButton;
CBA1: TCheckBox;
CBA3: TCheckBox;
EA1: TEdit;
procedure BBA1Click(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure CBA2Click(Sender: TObject);
procedure RBA1Click(Sender: TObject);
procedure RBA2Click(Sender: TObject);
procedure RBA3Click(Sender: TObject);
procedure RBA4Click(Sender: TObject);
procedure RBA5Click(Sender: TObject);
procedure RBA6Click(Sender: TObject);
procedure CBA1Click(Sender: TObject);
procedure CBA3Click(Sender: TObject);
procedure EA1Enter(Sender: TObject);
procedure EA1KeyPress(Sender: TObject; var Key: Char);
procedure EA1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure EA1Exit(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
m_ADMod:tstrings;
m_mod1030:double;
end;
var
FAdjustment: TFAdjustment;
implementation
{$R *.dfm}
var
m_RBVal:double;
IsFirst,isSelAll:boolean;
procedure TFAdjustment.BBA1Click(Sender: TObject);
begin
close;
end;
procedure TFAdjustment.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
m_ADMod.Clear ;
if CBA1.Checked then m_ADMod.add('11');
if CBA2.Checked then
if RBA1.Checked then m_ADMod.add('12')
else if RBA2.Checked then m_ADMod.add('13')
else if RBA3.Checked then m_ADMod.add('14')
else if RBA4.Checked then m_ADMod.add('15')
else if RBA5.Checked then m_ADMod.add('16')
else if RBA6.Checked then m_ADMod.add('17');
if CBA3.Checked then
m_ADMod.add('19')
else
m_mod1030:=0;
Action:=cafree;
end;
procedure TFAdjustment.FormCreate(Sender: TObject);
begin
self.Left := trunc((screen.Width -self.Width)/2);
self.Top := trunc((Screen.Height - self.Height)/2);
m_RBVal:=0;
m_mod1030:=0;
IsFirst:=true;
isSelAll:=false;
m_ADMod:=tstringlist.Create ;
end;
procedure TFAdjustment.FormShow(Sender: TObject);
begin
if m_ADMod.Count>0 then
begin
if PosStrInList(m_ADMod,'11')>=0 then CBA1.Checked :=true;
if PosStrInList(m_ADMod,'12')>=0 then
begin
RBA1.Checked :=true;
CBA2.Checked :=true;
end;
if PosStrInList(m_ADMod,'13')>=0 then
begin
RBA2.Checked :=true;
CBA2.Checked :=true;
end;
if PosStrInList(m_ADMod,'14')>=0 then
begin
RBA3.Checked :=true;
CBA2.Checked :=true;
end;
if PosStrInList(m_ADMod,'15')>=0 then
begin
RBA4.Checked :=true;
CBA2.Checked :=true;
end;
if PosStrInList(m_ADMod,'16')>=0 then
begin
RBA5.Checked :=true;
CBA2.Checked :=true;
end;
if PosStrInList(m_ADMod,'17')>=0 then
begin
RBA6.Checked :=true;
CBA2.Checked :=true;
end;
if PosStrInList(m_ADMod,'19')>=0 then
begin
if m_mod1030<1.1 then EA1.Text :='1.10'
else if m_mod1030>1.3 then EA1.Text :='1.30'
else EA1.Text :=formatfloat('0.00',m_mod1030);
EditFormat(EA1);
CBA3.Checked :=true;
end;
end;
IsFirst:=false;
end;
procedure TFAdjustment.CBA2Click(Sender: TObject);
begin
if CBA2.Checked then
begin
RBA1.Enabled :=true;
RBA2.Enabled :=true;
RBA3.Enabled :=true;
RBA4.Enabled :=true;
RBA5.Enabled :=true;
RBA6.Enabled :=true;
if RBA1.Checked then
m_RBVal:=2
else if RBA2.Checked then
m_RBVal:=1
else if RBA3.Checked then
m_RBVal:=1.5
else if RBA4.Checked then
m_RBVal:=2
else if RBA5.Checked then
m_RBVal:=0.5
else
m_RBVal:=0.2;
STA1.Caption :=formatfloat('0.00',strtofloat(STA1.Caption)+m_RBVal);
end
else
begin
STA1.Caption :=formatfloat('0.00',strtofloat(STA1.Caption)-m_RBVal);
RBA1.Enabled :=false;
RBA2.Enabled :=false;
RBA3.Enabled :=false;
RBA4.Enabled :=false;
RBA5.Enabled :=false;
RBA6.Enabled :=false;
end;
end;
procedure TFAdjustment.RBA1Click(Sender: TObject);
begin
if IsFirst then exit;
STA1.Caption :=formatfloat('0.00',strtofloat(STA1.Caption)+2-m_RBVal);
m_RBVal:=2;
end;
procedure TFAdjustment.RBA2Click(Sender: TObject);
begin
if isfirst then exit;
STA1.Caption :=formatfloat('0.00',strtofloat(STA1.Caption)+1-m_RBVal);
m_RBVal:=1;
end;
procedure TFAdjustment.RBA3Click(Sender: TObject);
begin
if isfirst then exit;
STA1.Caption :=formatfloat('0.00',strtofloat(STA1.Caption)+1.5-m_RBVal);
m_RBVal:=1.5;
end;
procedure TFAdjustment.RBA4Click(Sender: TObject);
begin
if isfirst then exit;
STA1.Caption :=formatfloat('0.00',strtofloat(STA1.Caption)+2-m_RBVal);
m_RBVal:=2;
end;
procedure TFAdjustment.RBA5Click(Sender: TObject);
begin
if isfirst then exit;
STA1.Caption :=formatfloat('0.00',strtofloat(STA1.Caption)+0.5-m_RBVal);
m_RBVal:=0.5;
end;
procedure TFAdjustment.RBA6Click(Sender: TObject);
begin
if isfirst then exit;
STA1.Caption :=formatfloat('0.00',strtofloat(STA1.Caption)+0.2-m_RBVal);
m_RBVal:=0.2;
end;
procedure TFAdjustment.CBA1Click(Sender: TObject);
begin
if CBA1.Checked then
STA1.Caption :=formatfloat('0.00',strtofloat(STA1.Caption)+0.3)
else
STA1.Caption :=formatfloat('0.00',strtofloat(STA1.Caption)-0.3);
end;
procedure TFAdjustment.CBA3Click(Sender: TObject);
begin
if CBA3.Checked then
begin
EA1.Enabled :=true;
m_mod1030:=strtofloat(trim(EA1.text));
STA1.Caption :=formatfloat('0.00',strtofloat(STA1.Caption)+m_mod1030-1.0);
end
else
begin
STA1.Caption :=formatfloat('0.00',strtofloat(STA1.Caption)-(m_mod1030-1.00));
EA1.Enabled :=false;
end;
end;
procedure TFAdjustment.EA1Enter(Sender: TObject);
begin
tedit(sender).Text :=trim(tedit(sender).Text);
tedit(sender).SelectAll ;
isSelAll:=true;
end;
procedure TFAdjustment.EA1KeyPress(Sender: TObject; var Key: Char);
var
strHead,strEnd,strAll,strFraction:string;
iDecimalSeparator:integer;
begin
if Key = #13 then
begin
SendMessage(Handle, WM_NEXTDLGCTL, 0, 0);
Key := #0;
exit;
end;
if (TEdit(Sender).Tag=0) and (key='.') then
begin
key:=#0;
exit;
end;
if lowercase(key)='e' then
begin
key:=#0;
exit;
end;
if key=' ' then key:=#0;
if key <>chr(vk_back) then
try
strHead := copy(TEdit(Sender).Text,1,TEdit(Sender).SelStart);
strEnd := copy(TEdit(Sender).Text,TEdit(Sender).SelStart+TEdit(Sender).SelLength+1,length(TEdit(Sender).Text));
strtofloat(strHead+key+strEnd);
strAll := strHead+key+strEnd;
iDecimalSeparator:= pos('.',strAll);
if iDecimalSeparator>0 then
begin
strFraction:= copy(strall,iDecimalSeparator+1,length(strall));
if (iDecimalSeparator>0) and (length(strFraction)>TEdit(Sender).Tag) then
key:=#0;
end;
except
key:=#0;
end;
end;
procedure TFAdjustment.EA1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if isSelAll then
begin
tedit(sender).SelectAll ;
isSelAll:=false;
end;
end;
procedure TFAdjustment.EA1Exit(Sender: TObject);
begin
if trim(EA1.Text)='' then EA1.Text:='1.10';
if strtofloat(trim(EA1.Text))>1.3 then
EA1.Text :='1.30'
else if strtofloat(trim(EA1.Text))<1.10 then
EA1.Text :='1.10';
eA1.Text :=formatfloat('0.00',strtofloat(trim(eA1.Text)));
EditFormat(eA1);
STA1.Caption :=formatfloat('0.00',strtofloat(STA1.Caption)+strtofloat(trim(eA1.Text))-m_mod1030);
m_mod1030:=strtofloat(trim(EA1.text));
end;
end.
|
unit prOpcClasses;
{$I prOpcCompilerDirectives.Inc}
interface
uses
Classes, TypInfo, ActiveX, prOpcTypes, prOpcServer;
type
{abstract base class do not instantiate}
TAnalogEU = class(TInterfacedObject, IEUInfo)
private
function EUType: TEuType;
function EUInfo: OleVariant;
protected
procedure GetLimits(var Low, High: Double); virtual; abstract;
end;
{abstract base class do not instantiate}
TEnumeratedEU = class(TInterfacedObject, IEUInfo)
private
function EUType: TEuType;
function EUInfo: OleVariant;
protected
procedure GetEnumeratedNames(Names: TStrings); virtual; abstract;
end;
{ Property Support }
{abstract base class do not instantiate}
TItemProperty = class(TInterfacedObject, IItemProperty)
private
FPid: LongWord;
public
constructor Create(aPid: Integer);
function Description: string; virtual; abstract;
function DataType: Integer; virtual; abstract;
function GetPropertyValue: OleVariant; virtual; abstract;
function Pid: LongWord;
end;
TItemProperties = class(TInterfacedObject, IItemProperties)
private
FList: TInterfaceList;
protected
public
function GetPropertyItem(Index: Integer): IItemProperty;
function GetProperty(Pid: LongWord): IItemProperty;
procedure Add(const ItemProperty: IItemProperty);
function Count: Integer;
constructor Create;
destructor Destroy; override;
end;
{basic fixed analog limits. Much more sophistication than this is possible
by deriving your own class}
TAnalogLimits = class(TAnalogEU)
private
FLow, FHigh: Double;
protected
procedure GetLimits(var Low, High: Double); override;
public
constructor Create(const aLow, aHigh: Double);
end;
{for use with enumerated rtti types}
TEnumeratedEUInfoFromRtti = class(TEnumeratedEU)
private
FTypeInfo: PTypeInfo;
protected
procedure GetEnumeratedNames(Names: TStrings); override;
public
constructor Create(aTypeInfo: PTypeInfo);
end;
TEnumeratedEUInfoFromStrings = class(TEnumeratedEU, IStringsAdapter)
private
FStrings: TStrings;
procedure ReferenceStrings(S: TStrings);
procedure ReleaseStrings;
protected
procedure GetEnumeratedNames(Names: TStrings); override;
public
constructor Create(aStrings: TStrings);
end;
implementation
uses
{$IFDEF D6UP}
Variants,
{$ENDIF}
prOpcDa;
resourcestring
SPropertyAlreadyExists = 'Property %s with Pid %d already exists';
{ TItemProperties }
{ this class is inefficiently implemented - should be a sorted list
keyed on PID &&& For small property lists this is probably not
very important }
constructor TItemProperty.Create(aPid: Integer);
begin
inherited Create;
FPid:= aPid
end;
procedure TItemProperties.Add(const ItemProperty: IItemProperty);
var
Prop: IItemProperty;
begin
Prop:= GetProperty(ItemProperty.Pid);
if Prop <> nil then
raise EOpcError.CreateResFmt(@SPropertyAlreadyExists,
[Prop.Description, Prop.Pid]);
FList.Add(ItemProperty)
end;
function TItemProperties.Count: Integer;
begin
Result:= FList.Count
end;
constructor TItemProperties.Create;
begin
inherited Create;
FList:= TInterfaceList.Create
end;
destructor TItemProperties.Destroy;
begin
FList.Free;
inherited Destroy
end;
function TItemProperties.GetPropertyItem(Index: Integer): IItemProperty;
begin
Result := IItemProperty(FList[Index]);
end;
function TItemProperties.GetProperty(Pid: LongWord): IItemProperty;
var
i: Integer;
Prop: IItemProperty;
begin
Result:= nil;
for i:= 0 to FList.Count - 1 do
begin
Prop:= FList[i] as IItemProperty;
if Prop.Pid = Pid then
begin
Result:= Prop;
break
end
end
end;
{ TEUInfo }
function EUType: TOleEnum;
begin
Result:= OPC_NOENUM
end;
{ TAnalogEU }
function TAnalogEU.EUInfo: OleVariant;
var
h, l: Double;
begin
GetLimits(l, h);
Result:= VarArrayCreate([0,1], VT_R8);
Result[0]:= l;
Result[1]:= h
end;
function TAnalogEU.EUType: TEuType;
begin
Result:= euAnalog
end;
{ TEnumeratedEU }
function TEnumeratedEU.EUInfo: OleVariant;
var
s: TStringList;
i: Integer;
begin
s:= TStringList.Create;
try
GetEnumeratedNames(s);
if s.Count = 0 then
begin
Result:= Unassigned
end else
begin
Result:= VarArrayCreate([0, s.Count-1], VT_BSTR);
for i:= 0 to s.Count - 1 do
Result[i]:= s[i]
end
finally
s.Free
end
end;
function TEnumeratedEU.EUType: TEuType;
begin
Result:= euEnumerated
end;
{ TEnumeratedTypeEUInfo }
constructor TEnumeratedEUInfoFromRtti.Create(aTypeInfo: PTypeInfo);
begin
inherited Create;
FTypeInfo:= aTypeInfo {it is probably OK to keep a pointer to this
because Rtti is static global (it appears)}
end;
procedure TEnumeratedEUInfoFromRtti.GetEnumeratedNames(Names: TStrings);
var
i: Integer;
begin
with GetTypeData(FTypeInfo)^ do
for i:= MinValue to MaxValue do
Names.Add(GetEnumName(FTypeInfo, i))
end;
{ TAnalogLimits }
constructor TAnalogLimits.Create(const aLow, aHigh: Double);
begin
inherited Create;
FLow:= aLow;
FHigh:= aHigh
end;
procedure TAnalogLimits.GetLimits(var Low, High: Double);
begin
Low:= FLow;
High:= FHigh
end;
function TItemProperty.Pid: LongWord;
begin
Result:= FPid
end;
{ TEnumeratedEUInfoFromStrings }
constructor TEnumeratedEUInfoFromStrings.Create(aStrings: TStrings);
begin
inherited Create;
if Assigned(aStrings) then
aStrings.StringsAdapter:= Self
end;
procedure TEnumeratedEUInfoFromStrings.GetEnumeratedNames(Names: TStrings);
begin
if Assigned(FStrings) then
Names.AddStrings(FStrings)
end;
procedure TEnumeratedEUInfoFromStrings.ReferenceStrings(S: TStrings);
begin
FStrings:= S
end;
procedure TEnumeratedEUInfoFromStrings.ReleaseStrings;
begin
FStrings:= nil
end;
end.
|
unit U_MsgD;
{** Unit criado por Jonatan Souza
Esta unit cria uma mensagem do tipo material design - https://www.youtube.com/channel/UC6omhlEXe3ZCMDZd3WyB4_A
jonatan.souza04@gmail.com
}
interface
Uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Actions,
FMX.Graphics, FMX.Effects, FMX.Forms, FMX.ActnList, FMX.Objects, FMX.StdCtrls, FMX.Types,
FMX.Ani, FMX.Layouts, System.UIConsts;
Type
TTypeMsg = ( tMsgDNone, tMsgDInformation, tMsgDWarning, tMsgDanger );
Type
TMsgD = class
private
FFormMsg: TForm;
FActionCancel: TAction;
FActionOk: TAction;
FTitle: String;
FText: String;
FCaptionBtnOk: String;
FCaptionBtnCancel: String;
FBackgroundMsg: Boolean;
FBackgroundMsgOpacity: Single;
FHeightMaxMsg: Single;
FAutoHeight: Boolean;
FHeighhtMaxMsg: Single;
FColorBtnOk: TAlphaColor;
FColorBtnCancel: TAlphaColor;
FColorTitle: TAlphaColor;
FColorText: TAlphaColor;
FHeight: Single;
FParent: TFmxObject;
FColorBackgroundTitle: TAlphaColor;
FTypeInfo: TTypeMsg;
FActionCustom: TAction;
FColorBtnCustom: TAlphaColor;
FCaptionBtnCustom: String;
FFontName: String;
FFontSizeTitle: Integer;
FFontSizeText: Integer;
procedure SetFormMsg(const Value: TForm);
procedure SetActionCancel(const Value: TAction);
procedure SetActionOk(const Value: TAction);
procedure SetText(const Value: String);
procedure SetTitle(const Value: String);
procedure ClickRect(Sender: TObject);
procedure FinishClose(Sender: TObject);
procedure OnClickBtnOk(Sender : TObject);
procedure OnClickBtnCancel(Sender : TObject);
procedure OnClickBtnCustom(Sender : TObject);
procedure SetCaptionBtnOk(const Value: String);
procedure SetCaptionBtnCancel(const Value: String);
procedure SetBackgroundMsg(const Value: Boolean);
procedure SetBackgroundMsgOpacity(const Value: Single);
procedure SetHeightMaxMsg(const Value: Single);
procedure SetAutoHeight(const Value: Boolean);
procedure SetColorBtnOk(const Value: TAlphaColor);
procedure SetColorBtnCancel(const Value: TAlphaColor);
procedure SetColorTitle(const Value: TAlphaColor);
procedure SetColorText(const Value: TAlphaColor);
procedure ClearObj;
procedure SetHeight(const Value: Single);
procedure SetColorBackgroundTitle(const Value: TAlphaColor);
procedure SetTypeInfo(const Value: TTypeMsg);
procedure SetActionCustom(const Value: TAction);
procedure SetCaptionBtnCustom(const Value: String);
procedure SetColorBtnCustom(const Value: TAlphaColor);
procedure SetFontName(const Value: String);
procedure SetFontSizeTitle(const Value: Integer);
procedure SetFontSizeText(const Value: Integer);
Var
RectMsg, RectMsgBlack, RectMsgTransp, RectMsgBottom, RectInformation : TRectangle;
LayoutMsg : TLayout;
LabelMsgTitle, LabelText : TLabel;
btnOk, btnCancel, btnCustom : TSpeedButton;
MsgAnimate, MsgAnimateClose : TFloatAnimation;
EffectsMsg : TShadowEffect;
public
Constructor Create;
property FormMsg : TForm read FFormMsg write SetFormMsg;
property ActionCancel : TAction read FActionCancel write SetActionCancel;
property ActionOk : TAction read FActionOk write SetActionOk;
property ActionCustom : TAction read FActionCustom write SetActionCustom;
property Title : String read FTitle write SetTitle;
property Text : String read FText write SetText;
property CaptionBtnOk : String read FCaptionBtnOk write SetCaptionBtnOk;
property CaptionBtnCancel : String read FCaptionBtnCancel write SetCaptionBtnCancel;
property CaptionBtnCustom : String read FCaptionBtnCustom write SetCaptionBtnCustom;
property BackgroundMsg : Boolean read FBackgroundMsg write SetBackgroundMsg;
property BackgroundMsgOpacity : Single read FBackgroundMsgOpacity write SetBackgroundMsgOpacity;
property Height : Single read FHeight write SetHeight;
property HeightMaxMsg : Single read FHeighhtMaxMsg write SetHeightMaxMsg;
property AutoHeight : Boolean read FAutoHeight write SetAutoHeight;
property ColorBtnOk : TAlphaColor read FColorBtnOk write SetColorBtnOk;
property ColorBtnCancel : TAlphaColor read FColorBtnCancel write SetColorBtnCancel;
property ColorBtnCustom : TAlphaColor read FColorBtnCustom write SetColorBtnCustom;
property ColorTitle : TAlphaColor read FColorTitle write SetColorTitle;
property ColorText : TAlphaColor read FColorText write SetColorText;
property ColorBackgroundTitle : TAlphaColor read FColorBackgroundTitle write SetColorBackgroundTitle;
property TypeInfo : TTypeMsg read FTypeInfo write SetTypeInfo;
property FontName : String read FFontName write SetFontName;
property FontSizeTitle : Integer read FFontSizeTitle write SetFontSizeTitle;
property FontSizeText : Integer read FFontSizeText write SetFontSizeText;
procedure ShowMsgD;
procedure CloseMsgD;
procedure Clear;
Function IsShowMsgD : Boolean;
end;
implementation
{ TMsgD }
constructor TMsgD.Create;
begin
ClearObj;
end;
procedure TMsgD.Clear;
begin
ClearObj;
end;
procedure TMsgD.ClearObj;
begin
if Assigned(LayoutMsg) Then
LayoutMsg.Visible := False;
if Assigned(FFormMsg) Then
FFormMsg := Nil;
if Assigned(FActionCancel) then
FActionCancel := Nil;
if Assigned(FActionOk) then
FActionOk := Nil;
if Assigned(FActionCustom) then
FActionCustom := Nil;
FTitle := '';
FText := '';
CaptionBtnOk := '';
CaptionBtnCancel := '';
CaptionBtnCustom := '';
FBackgroundMsg := True;
FBackgroundMsgOpacity := 0.4;
FHeightMaxMsg := 0;
FAutoHeight := False;
FColorBtnOk := TAlphaColorRec.Null;
FColorBtnCancel := TAlphaColorRec.Null;
FColorBtnCustom := TAlphaColorRec.Null;
FColorTitle := TAlphaColorRec.Null;
FColorText := TAlphaColorRec.Null;
FColorBackgroundTitle := TAlphaColorRec.White;
FTypeInfo := tMsgDNone;
FFontName := 'Roboto Th';
FFontSizeTitle := 18;
FFontSizeText := 14;
end;
procedure TMsgD.ClickRect(Sender: TObject);
begin
CloseMsgD;
while IsShowMsgD do
Application.ProcessMessages;
end;
procedure TMsgD.CloseMsgD;
begin
if (RectMsgBlack <> Nil) And (RectMsg <> Nil) then
Begin
RectMsgBlack.AnimateFloat('Opacity',0,0.1);
MsgAnimateClose.Start;
End;
ClearObj;
end;
procedure TMsgD.FinishClose(Sender: TObject);
begin
if RectMsgBlack <> Nil then
RectMsgBlack.Visible := False;
if RectMsg <> Nil then
RectMsg.Visible := False;
FTitle := '';
FText := '';
FCaptionBtnOk := '';
FCaptionBtnCancel := '';
FCaptionBtnCustom := '';
end;
function TMsgD.IsShowMsgD: Boolean;
begin
if (RectMsgBlack <> Nil) And (RectMsg <> Nil) then
Result := (RectMsgBlack.Visible) or (RectMsg.Visible)
Else
Result := False;
end;
procedure TMsgD.OnClickBtnCancel(Sender: TObject);
begin
{$IFDEF IOS}
FActionCancel.Execute;
CloseMsgD;
{$ELSE}
TThread.CreateAnonymousThread(procedure ()
Begin
TThread.Synchronize (TThread.CurrentThread,
procedure ()
begin
FActionCancel.Execute;
CloseMsgD;
End);
End).Start;
{$ENDIF}
end;
procedure TMsgD.OnClickBtnCustom(Sender: TObject);
begin
TThread.CreateAnonymousThread(procedure ()
Begin
TThread.Synchronize (TThread.CurrentThread,
procedure ()
begin
FActionCustom.Execute;
End);
CloseMsgD;
End).Start;
end;
procedure TMsgD.OnClickBtnOk(Sender: TObject);
begin
TThread.CreateAnonymousThread(procedure ()
Begin
TThread.Synchronize (TThread.CurrentThread,
procedure ()
begin
FActionOk.Execute;
End);
CloseMsgD;
End).Start;
end;
procedure TMsgD.SetActionCancel(const Value: TAction);
begin
FActionCancel := Value;
end;
procedure TMsgD.SetActionCustom(const Value: TAction);
begin
FActionCustom := Value;
end;
procedure TMsgD.SetActionOk(const Value: TAction);
begin
FActionOk := Value;
end;
procedure TMsgD.SetAutoHeight(const Value: Boolean);
begin
FAutoHeight := Value;
end;
procedure TMsgD.SetBackgroundMsg(const Value: Boolean);
begin
FBackgroundMsg := Value;
end;
procedure TMsgD.SetBackgroundMsgOpacity(const Value: Single);
begin
FBackgroundMsgOpacity := Value;
end;
procedure TMsgD.SetCaptionBtnCancel(const Value: String);
begin
FCaptionBtnCancel := Value;
end;
procedure TMsgD.SetCaptionBtnCustom(const Value: String);
begin
FCaptionBtnCustom := Value;
end;
procedure TMsgD.SetCaptionBtnOk(const Value: String);
begin
FCaptionBtnOk := Value;
end;
procedure TMsgD.SetColorBackgroundTitle(const Value: TAlphaColor);
begin
FColorBackgroundTitle := Value;
end;
procedure TMsgD.SetColorBtnCancel(const Value: TAlphaColor);
begin
FColorBtnCancel := Value;
end;
procedure TMsgD.SetColorBtnCustom(const Value: TAlphaColor);
begin
FColorBtnCustom := Value;
end;
procedure TMsgD.SetColorBtnOk(const Value: TAlphaColor);
begin
FColorBtnOk := Value;
end;
procedure TMsgD.SetColorText(const Value: TAlphaColor);
begin
FColorText := Value;
end;
procedure TMsgD.SetColorTitle(const Value: TAlphaColor);
begin
FColorTitle := Value;
end;
procedure TMsgD.SetFontName(const Value: String);
begin
FFontName := Value;
end;
procedure TMsgD.SetFontSizeText(const Value: Integer);
begin
FFontSizeText := Value;
end;
procedure TMsgD.SetFontSizeTitle(const Value: Integer);
begin
FFontSizeTitle := Value;
end;
procedure TMsgD.SetFormMsg(const Value: TForm);
begin
FFormMsg := Value;
end;
procedure TMsgD.SetHeight(const Value: Single);
begin
FHeight := Value;
end;
procedure TMsgD.SetHeightMaxMsg(const Value: Single);
begin
FHeightMaxMsg := Value;
end;
procedure TMsgD.SetText(const Value: String);
begin
FText := Value;
end;
procedure TMsgD.SetTitle(const Value: String);
begin
FTitle := Value;
end;
procedure TMsgD.SetTypeInfo(const Value: TTypeMsg);
begin
FTypeInfo := Value;
end;
procedure TMsgD.ShowMsgD;
begin
if Not Assigned(LayoutMsg) then
LayoutMsg := TLayout.Create( FFormMsg );
LayoutMsg.Parent := FFormMsg;
LayoutMsg.Align := TAlignLayout.Client;
FFormMsg.AddObject(LayoutMsg);
LayoutMsg.Visible := True;
if Not Assigned( RectMsgTransp ) then
RectMsgTransp := TRectangle.Create( LayoutMsg );
RectMsgTransp.Parent := LayoutMsg;
RectMsgTransp.Fill.Color := TAlphaColorRec.Null;
RectMsgTransp.Align := TAlignLayout.Client;
RectMsgTransp.OnClick := ClickRect;
RectMsgTransp.Stroke.Color := TAlphaColorRec.Null;
LayoutMsg.AddObject( RectMsgTransp );
if FBackgroundMsg then
Begin
if Not Assigned(RectMsgBlack) then
RectMsgBlack := TRectangle.Create( RectMsgTransp );
RectMsgBlack.Parent := RectMsgTransp;
RectMsgBlack.Fill.Color := TAlphaColorRec.Black;
RectMsgBlack.Stroke.Color := TAlphaColorRec.Null;
RectMsgBlack.Opacity := FBackgroundMsgOpacity;
RectMsgBlack.Align := TAlignLayout.Client;
RectMsgBlack.Visible := True;
RectMsgBlack.Margins.Left := -100;
RectMsgBlack.Margins.Right := -100;
RectMsgBlack.Margins.Bottom := -100;
RectMsgBlack.Margins.Top := -100;
RectMsgBlack.OnClick := ClickRect;
RectMsgTransp.AddObject( RectMsgBlack );
End;
if Not Assigned(RectMsg) Then
RectMsg := TRectangle.Create( LayoutMsg );
RectMsg.Parent := LayoutMsg;
RectMsg.Opacity := 0;
if Height <= 0 then
RectMsg.Height := (FFormMsg.Height / 2) -50
Else
RectMsg.Height := FHeight;
RectMsg.Width := FFormMsg.Width - 50;
RectMsg.Fill.Color := TAlphaColorRec.White;
RectMsg.Stroke.Color := TAlphaColorRec.Null;
RectMsg.XRadius := 5;
RectMsg.YRadius := 5;
RectMsg.Margins.Top := 0;
RectMsg.Margins.Left := 15;
RectMsg.Margins.Right := 15;
RectMsg.Margins.Bottom := 20;
RectMsg.Visible := True;
RectMsg.Align := TAlignLayout.Center;
LayoutMsg.AddObject( RectMsg );
if Not Assigned(RectInformation) Then
RectInformation := TRectangle.Create( RectMsg );
RectInformation.Parent := RectMsg;
RectInformation.Align := TAlignLayout.MostTop;
RectInformation.Height := 35;
RectInformation.Stroke.Color := TAlphaColorRec.Null;
RectInformation.Margins.Left := 15;
RectInformation.Margins.Right := 15;
RectInformation.Margins.Bottom := 5;
RectInformation.Margins.Top := 10;
RectInformation.XRadius := 2;
RectInformation.YRadius := 2;
RectInformation.Fill.Color := TAlphaColorRec.White;
if FTypeInfo = tMsgDInformation then
RectInformation.Fill.Color := StringToAlphaColor('#FFB9B9FE')
Else
if FTypeInfo = tMsgDWarning then
RectInformation.Fill.Color := StringToAlphaColor('#FFFFFFB9')
Else
if FTypeInfo = tMsgDanger then
RectInformation.Fill.Color := StringToAlphaColor('#FFFF7878')
Else
if FColorBackgroundTitle <> TAlphaColorRec.Null then
RectInformation.Fill.Color := FColorBackgroundTitle;
if FTypeInfo <> tMsgDNone then
RectInformation.Margins.Bottom := 35;
RectMsg.AddObject(RectInformation);
if Not Assigned(RectMsgBottom) Then
RectMsgBottom := TRectangle.Create( RectMsg );
RectMsgBottom.Parent := RectMsg;
RectMsgBottom.Align := TAlignLayout.Bottom;
RectMsgBottom.Fill.Color := TAlphaColorRec.Null;
RectMsgBottom.Stroke.Color := TAlphaColorRec.Null;
RectMsgBottom.Height := 65;
if Not Assigned(MsgAnimateClose) then
MsgAnimateClose := TFloatAnimation.Create( RectMsg );
MsgAnimateClose.Parent := RectMsg;
MsgAnimateClose.Duration := 0.2;
MsgAnimateClose.Interpolation := TInterpolationType.Linear;
MsgAnimateClose.PropertyName := 'Opacity';
MsgAnimateClose.StartValue := 1;
MsgAnimateClose.StopValue := 0;
MsgAnimateClose.OnFinish := FinishClose;
if Not Assigned(LabelMsgTitle) then
LabelMsgTitle := TLabel.Create( RectInformation );
LabelMsgTitle.AutoSize := True;
LabelMsgTitle.Parent := RectInformation;
LabelMsgTitle.Align := TAlignLayout.Client;
LabelMsgTitle.Text := FTitle;
LabelMsgTitle.Margins.Top := 2;
LabelMsgTitle.Margins.Left := 7;
LabelMsgTitle.Margins.Right := 0;
LabelMsgTitle.Margins.Bottom:= 2;
LabelMsgTitle.StyledSettings := LabelMsgTitle.StyledSettings - [TStyledSetting.Style];
LabelMsgTitle.StyledSettings := LabelMsgTitle.StyledSettings - [TStyledSetting.Family];
LabelMsgTitle.StyledSettings := LabelMsgTitle.StyledSettings - [TStyledSetting.Size];
LabelMsgTitle.StyledSettings := LabelMsgTitle.StyledSettings - [TStyledSetting.FontColor];
LabelMsgTitle.StyledSettings := LabelMsgTitle.StyledSettings - [TStyledSetting.Other];
LabelMsgTitle.TextSettings.Font.Style := LabelMsgTitle.TextSettings.Font.Style + [ TFontStyle.fsBold ];
LabelMsgTitle.TextSettings.Font.Family := FFontName;
LabelMsgTitle.TextSettings.Font.Size := FFontSizeTitle;
LabelMsgTitle.TextSettings.WordWrap := True;
LabelMsgTitle.TextSettings.VertAlign := TTextAlign.Center;
LabelMsgTitle.TextSettings.HorzAlign := TTextAlign.Leading;
LabelMsgTitle.Visible := ( FTitle <> '' );
LabelMsgTitle.FontColor := TAlphaColorRec.Black;
if ColorTitle <> TAlphaColorRec.Null then
LabelMsgTitle.FontColor := ColorTitle
Else
if FTypeInfo = tMsgDInformation then
Begin
LabelMsgTitle.FontColor := TAlphaColorRec.White;
LabelMsgTitle.TextSettings.HorzAlign := TTextAlign.Center;
End
Else
if FTypeInfo = tMsgDWarning then
Begin
LabelMsgTitle.FontColor := TAlphaColorRec.Black;
LabelMsgTitle.TextSettings.HorzAlign := TTextAlign.Center;
End
Else
if FTypeInfo = tMsgDanger then
Begin
LabelMsgTitle.FontColor := TAlphaColorRec.White;
LabelMsgTitle.TextSettings.HorzAlign := TTextAlign.Center;
End;
RectInformation.Height := LabelMsgTitle.Height + 25;
if Not Assigned(LabelText) then
LabelText := TLabel.Create( RectMsg );
LabelText.Parent := RectMsg;
LabelText.AutoSize := True;
LabelText.Align := TAlignLayout.Top;
LabelText.Margins.Top := 5;
LabelText.Margins.Left := 20;
LabelText.Margins.Right := 20;
LabelText.Margins.Bottom:= 5;
LabelText.StyledSettings := LabelText.StyledSettings - [TStyledSetting.Style];
LabelText.StyledSettings := LabelText.StyledSettings - [TStyledSetting.Family];
LabelText.StyledSettings := LabelText.StyledSettings - [TStyledSetting.Size];
LabelText.StyledSettings := LabelText.StyledSettings - [TStyledSetting.FontColor];
LabelText.StyledSettings := LabelText.StyledSettings - [TStyledSetting.Other];
LabelText.TextSettings.Font.Family := FFontName;
LabelText.TextSettings.Font.Size := FFontSizeText;
LabelText.TextSettings.VertAlign := TTextAlign.Center;
if ColorText <> TAlphaColorRec.Null then
LabelText.FontColor := ColorText
Else
LabelText.FontColor := TAlphaColorRec.Slategray;
LabelText.Text := Text;
// RectMsg.Width := LabelText.Width - 60;
{** Btn Custom }
if Not Assigned(btnCustom) then
btnCustom := TSpeedButton.Create( RectMsgBottom );
btnCustom.Parent := RectMsgBottom;
btnCustom.Align := TAlignLayout.Left;
btnCustom.Width := 120;
btnCustom.Margins.Left := 10;
btnCustom.Margins.Right := 5;
btnCustom.StyledSettings := btnCustom.StyledSettings - [TStyledSetting.Style];
btnCustom.StyledSettings := btnCustom.StyledSettings - [TStyledSetting.Family];
btnCustom.StyledSettings := btnCustom.StyledSettings - [TStyledSetting.Size];
btnCustom.StyledSettings := btnCustom.StyledSettings - [TStyledSetting.FontColor];
btnCustom.StyledSettings := btnCustom.StyledSettings - [TStyledSetting.Other];
btnCustom.TextSettings.Font.Family := FFontName;
btnCustom.TextSettings.Font.Size := 14;
btnCustom.Text := 'Custom';
if FCaptionBtnCustom <> '' then
btnCustom.Text := FCaptionBtnCustom;
if ColorBtnCustom <> TAlphaColorRec.Null then
btnCustom.FontColor := ColorBtnCustom
Else
btnCustom.FontColor := TAlphaColorRec.Cornflowerblue;
{** Btn Ok }
if Not Assigned(btnOk) then
btnOk := TSpeedButton.Create( RectMsgBottom );
btnOk.Parent := RectMsgBottom;
btnOk.Align := TAlignLayout.Right;
btnOk.Width := 75;
btnOk.Margins.Left := 10;
btnOk.Margins.Right := 10;
btnOk.StyledSettings := btnOk.StyledSettings - [TStyledSetting.Style];
btnOk.StyledSettings := btnOk.StyledSettings - [TStyledSetting.Family];
btnOk.StyledSettings := btnOk.StyledSettings - [TStyledSetting.Size];
btnOk.StyledSettings := btnOk.StyledSettings - [TStyledSetting.FontColor];
btnOk.StyledSettings := btnOk.StyledSettings - [TStyledSetting.Other];
btnOk.TextSettings.Font.Family := FFontName;
btnOk.TextSettings.Font.Size := 14;
btnOk.Text := 'OK';
if FCaptionBtnOk <> '' then
btnOk.Text := FCaptionBtnOk;
if Length(FCaptionBtnOk) > 5 then
btnOk.Width := btnOk.Width + ( Length(FCaptionBtnOk) * 2.5 );
if ColorBtnOk <> TAlphaColorRec.Null then
btnOk.FontColor := ColorBtnOk
Else
btnOk.FontColor := TAlphaColorRec.Cornflowerblue;
{** Btn Cancek }
if Not Assigned(btnCancel) then
btnCancel := TSpeedButton.Create( RectMsgBottom );
btnCancel.Parent := RectMsgBottom;
btnCancel.Position.Y := btnOk.Position.Y;
btnCancel.Position.X := btnOk.Position.X - 75;
btnCancel.Height := btnOk.Height;
btnCancel.Width := btnOk.Width;
btnCancel.StyledSettings := btnCancel.StyledSettings - [TStyledSetting.Style];
btnCancel.StyledSettings := btnCancel.StyledSettings - [TStyledSetting.Family];
btnCancel.StyledSettings := btnCancel.StyledSettings - [TStyledSetting.Size];
btnCancel.StyledSettings := btnCancel.StyledSettings - [TStyledSetting.FontColor];
btnCancel.StyledSettings := btnCancel.StyledSettings - [TStyledSetting.Other];
btnCancel.TextSettings.Font.Family := FFontName;
btnCancel.TextSettings.Font.Size := 14;
btnCancel.Text := 'Cancelar';
btnCancel.FontColor := TAlphaColorRec.Cornflowerblue;
if ColorBtnCancel <> TAlphaColorRec.Null then
btnCancel.FontColor := ColorBtnCancel
Else
btnCancel.FontColor := TAlphaColorRec.Cornflowerblue;
if FCaptionBtnCancel <> '' then
btnCancel.Text := FCaptionBtnCancel;
if FAutoHeight then
Begin
RectMsg.Height := LabelMsgTitle.Height + LabelMsgTitle.Margins.Top + LabelMsgTitle.Margins.Bottom +
LabelText.Height + LabelText.Margins.Top + LabelText.Margins.Bottom +
RectMsgBottom.Height + RectMsgBottom.Margins.Top + RectMsgBottom.Margins.Bottom + 10;
End;
if RectMsg.Height > (FFormMsg.Height - 35) then
RectMsg.Height := (FFormMsg.Height - 35);
if ( FHeightMaxMsg > 0 ) And ( RectMsg.Height > FHeightMaxMsg ) then
RectMsg.Height := FHeightMaxMsg;
btnOk.Visible := ( ActionOk <> Nil );
btnCancel.Visible := ( ActionCancel <> Nil );
btnCustom.Visible := ( ActionCustom <> Nil );
if btnOk.Visible then
btnOk.OnClick := OnClickBtnOk;
if btnCancel.Visible then
btnCancel.OnClick := OnClickBtnCancel;
if btnCustom.Visible then
btnCustom.OnClick := OnClickBtnCustom;
LayoutMsg.BringToFront;
if Not Assigned(EffectsMsg) Then
EffectsMsg := TShadowEffect.Create( LayoutMsg );
EffectsMsg.Parent := RectMsg;
EffectsMsg.Direction := 45;
EffectsMsg.Distance := 5;
EffectsMsg.Opacity := 0.5;
EffectsMsg.Softness := 0.4;
EffectsMsg.ShadowColor := TAlphaColorRec.Black;
RectMsg.AddObject(EffectsMsg);
RectMsg.BringToFront;
RectMsg.Opacity := 1;
end;
end. |
unit Persistence.CodeGenerator.Abstract;
interface
uses
System.SysUtils,
System.Generics.Collections;
{$M+}
type
ICodeGenerator<T: class> = interface
['{6CC6482F-0257-4836-AA18-B07D984301EF}']
function GetDatabase(): T;
procedure SetDatabase(value: T);
function GetTablesWithField(): TDictionary<string, string>;
procedure SetTablesWithField(value: TDictionary<string, string>);
procedure Generate();
procedure SaveTo(AProc: TProc<string>);
property Database: T read GetDatabase write SetDatabase;
property TablesWithField: TDictionary<string, string> read GetTablesWithField write SetTablesWithField;
end;
TCodeGenerator<T: class> = class(TInterfacedObject, ICodeGenerator<T>)
strict private
FDatabase: T;
FTablesWithField: TDictionary<string, string>;
private
function GetDatabase(): T;
procedure SetDatabase(value: T);
function GetTablesWithField(): TDictionary<string, string>;
procedure SetTablesWithField(value: TDictionary<string, string>);
public
constructor Create;
destructor Destroy; override;
procedure Generate(); virtual;
procedure SaveTo(AProc: TProc<string>); virtual;
property Database: T read GetDatabase write SetDatabase;
property TablesWithField: TDictionary<string, string> read GetTablesWithField write SetTablesWithField;
end;
{$M-}
implementation
{ TCodeGenerator<T> }
constructor TCodeGenerator<T>.Create;
begin
inherited;
FTablesWithField := TDictionary<string, string>.Create;
end;
destructor TCodeGenerator<T>.Destroy;
begin
FTablesWithField.Clear;
FTablesWithField.Free;
inherited;
end;
function TCodeGenerator<T>.GetDatabase: T;
begin
Result := FDatabase;
end;
function TCodeGenerator<T>.GetTablesWithField: TDictionary<string, string>;
begin
Result := FTablesWithField;
end;
procedure TCodeGenerator<T>.SetDatabase(value: T);
begin
FDatabase := Value;
end;
procedure TCodeGenerator<T>.SetTablesWithField(value: TDictionary<string, string>);
begin
FTablesWithField := value;
end;
procedure TCodeGenerator<T>.Generate;
begin
if (not Assigned(FDatabase)) then
raise EArgumentNilException.Create('No Database found!');
end;
procedure TCodeGenerator<T>.SaveTo(AProc: TProc<string>);
var
Item: TPair<string, string>;
begin
for Item in FTablesWithField do
AProc(Item.Value);
end;
end.
|
unit Form.ImageBackground;
interface
uses
UCL.Classes, UCL.TUThemeManager, UCL.TUForm, UCL.Utils,
UCL.TUQuickButton, UCL.TUCaptionBar, UCL.TUTitleBar, UCL.TUSlider,
UCL.TUButton, UCL.TUCheckBox, UCL.TURadioButton, UCL.TUSeparator,
UCL.TUProgressBar, Vcl.StdCtrls, UCL.TUText, UCL.TUEdit,
UCL.TUSymbolButton, UCL.TUItemButton, UCL.TUPanel, UCL.TUShadow,
System.SysUtils, System.Variants, System.Classes,
Winapi.Windows, Winapi.Messages,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.Imaging.jpeg;
type
TformImageBackground = class(TUForm)
imgBackground: TImage;
titlebarMain: TUTitleBar;
sliderMain: TUSlider;
buttonOk: TUButton;
radioSystemTheme: TURadioButton;
radioLightTheme: TURadioButton;
progressMain: TUProgressBar;
radioDarkTheme: TURadioButton;
buttonSide: TUSymbolButton;
panelBottom: TUPanel;
editEmail: TUEdit;
buttonWinClose: TUQuickButton;
buttonWinMin: TUQuickButton;
buttonCancel: TUButton;
shadowMenu: TUShadow;
entryChooseTheme: TUText;
procedure FormCreate(Sender: TObject);
procedure radioSystemThemeClick(Sender: TObject);
procedure radioLightThemeClick(Sender: TObject);
procedure radioDarkThemeClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
formImageBackground: TformImageBackground;
implementation
uses
DataModule.Main;
{$R *.dfm}
procedure TformImageBackground.FormCreate(Sender: TObject);
begin
// EnableBlur(Handle, 3);
ThemeManager := dmMain.AppTheme;
end;
procedure TformImageBackground.radioSystemThemeClick(Sender: TObject);
begin
ThemeManager.UseSystemTheme := true;
ThemeManager.Reload;
end;
procedure TformImageBackground.radioLightThemeClick(Sender: TObject);
begin
ThemeManager.CustomTheme := utLight;
ThemeManager.UseSystemTheme := false;
ThemeManager.Reload;
end;
procedure TformImageBackground.radioDarkThemeClick(Sender: TObject);
begin
ThemeManager.CustomTheme := utDark;
ThemeManager.UseSystemTheme := false;
ThemeManager.Reload;
end;
end.
|
{**********************************************}
{ TTeeFont (or derived) Editor Dialog }
{ Copyright (c) 1999-2004 by David Berneda }
{**********************************************}
unit TeeEdiFont;
{$I TeeDefs.inc}
interface
uses {$IFDEF CLR}
Classes,
Borland.VCL.Controls,
Borland.VCL.Forms,
Borland.VCL.StdCtrls,
Borland.VCL.ExtCtrls,
Borland.VCL.ComCtrls,
{$ELSE}
{$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
SysUtils, Classes,
{$IFDEF CLX}
QGraphics, QControls, QForms, QDialogs, QStdCtrls, QComCtrls, QExtCtrls,
{$ELSE}
Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, ExtCtrls,
{$ENDIF}
{$ENDIF}
TeeProcs, TeCanvas, TeePenDlg;
type
TTeeFontEditor = class(TForm)
Button3: TButton;
SHText: TShape;
Label2: TLabel;
Edit2: TEdit;
UDInter: TUpDown;
BOutline: TButtonPen;
BShadow: TButton;
BGradient: TButton;
CBOutGrad: TCheckBox;
procedure BFontClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure SHTextMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure Edit2Change(Sender: TObject);
procedure BShadowClick(Sender: TObject);
procedure BGradientClick(Sender: TObject);
procedure CBOutGradClick(Sender: TObject);
private
{ Private declarations }
TheFont : TTeeFont;
public
{ Public declarations }
procedure RefreshControls(AFont:TTeeFont);
end;
Function InsertTeeFontEditor(ATab:TTabSheet):TTeeFontEditor;
Procedure EditTeeFontEx(AOwner:TComponent; AFont:TTeeFont);
implementation
{$IFNDEF CLX}
{$R *.DFM}
{$ELSE}
{$R *.xfm}
{$ENDIF}
Uses {$IFDEF CLR}
Borland.VCL.Graphics,
{$ENDIF}
TeeConst, TeeShadowEditor, TeeBrushDlg, TeeEdiGrad;
Function InsertTeeFontEditor(ATab:TTabSheet):TTeeFontEditor;
begin
result:=TTeeFontEditor.Create(ATab.Owner);
AddFormTo(result,ATab);
end;
Procedure EditTeeFontEx(AOwner:TComponent; AFont:TTeeFont);
begin
with TTeeFontEditor.Create(AOwner) do
try
BorderStyle:=TeeBorderStyle;
TheFont:=AFont;
ShowModal;
finally
Free;
end;
end;
procedure TTeeFontEditor.BFontClick(Sender: TObject);
begin
EditTeeFont(Self,TheFont);
SHText.Brush.Color:=TheFont.Color;
end;
procedure TTeeFontEditor.RefreshControls(AFont:TTeeFont);
begin
TheFont:=AFont;
With TheFont do
begin
SHText.Brush.Color:=Color;
UDInter.Position:=InterCharSize;
BOutline.LinkPen(OutLine);
CBOutGrad.Checked:=Gradient.Outline;
end;
end;
procedure TTeeFontEditor.FormShow(Sender: TObject);
begin
if Assigned(TheFont) then RefreshControls(TheFont);
{$IFDEF CLX}
EnableControls(False,[Label2,Edit2,UDInter,BOutline]);
{$ENDIF}
TeeTranslateControl(Self);
end;
procedure TTeeFontEditor.SHTextMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var tmp : TColor;
begin
tmp:=TheFont.Color;
if EditColorDialog(Self,tmp) then
begin
TheFont.Color:=tmp;
SHText.Brush.Color:=tmp;
end;
end;
procedure TTeeFontEditor.Edit2Change(Sender: TObject);
begin
if Showing then TheFont.InterCharSize:=UDInter.Position;
end;
procedure TTeeFontEditor.BShadowClick(Sender: TObject);
begin
EditTeeShadow(Owner,TheFont.Shadow);
end;
procedure TTeeFontEditor.BGradientClick(Sender: TObject);
begin
EditTeeGradient(Owner,TheFont.Gradient)
end;
procedure TTeeFontEditor.CBOutGradClick(Sender: TObject);
begin
TheFont.Gradient.Outline:=CBOutGrad.Checked;
end;
end.
|
{ send EOT, wait up to 12 seconds for an ACK, retry up to 10 times }
FUNCTION SendEOT : ResponseType;
CONST
EOT = ^D;
ACK = ^F;
VAR
retries,ticks : INTEGER;
c : CHAR;
BEGIN
{ send EOT, wait for ACK or timeout}
retries := RETRIES_MAX;
FOR ticks := 1 TO 2 DO
IF ModemInReady THEN { discard any garbage on line }
Read(Aux,c);
REPEAT
Write(Aux,EOT);
ticks := 12000;
c := #$00;
REPEAT { wait up to 12 seconds for an ACK }
IF ModemInReady THEN BEGIN
Read(Aux,c);
END ELSE BEGIN
Delay(1);
ticks := Pred(ticks);
END;
UNTIL (c <> #$00) OR (ticks <= 0);
retries := Pred(retries);
UNTIL (c = ACK) OR (retries <= 0); { retry up to 10 times }
IF c = ACK THEN
SendEOT := GotACK
ELSE
SendEOT := GotTimeout;
END;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.