text stringlengths 14 6.51M |
|---|
unit UDosCommand;
interface
uses Windows, Classes;
function GetDosOutput(CommandLine: string; Work: string = 'C:\'): string;
implementation
//这个函数,输入一个DOS命令(比如,DIR),然后返回命令执行结果字符串。
//这个函数模拟了命令行窗口里手动输入DOS命令并抓到命令返回值。可以拿来做一些DOS命令的GUI封装,并加上对命令结果的分析代码。
function GetDosOutput(CommandLine: string; Work: string = 'C:\'): string;
var
SA: TSecurityAttributes;
SI: TStartupInfo;
PI: TProcessInformation;
StdOutPipeRead, StdOutPipeWrite: THandle;
WasOK: Boolean;
Buffer: array[0..255] of AnsiChar;
BytesRead: Cardinal;
WorkDir: string;
Handle: Boolean;
begin
Result := '';
with SA do begin
nLength := SizeOf(SA);
bInheritHandle := True;
lpSecurityDescriptor := nil;
end;
CreatePipe(StdOutPipeRead, StdOutPipeWrite, @SA, 0);
try
with SI do
begin
FillChar(SI, SizeOf(SI), 0);
cb := SizeOf(SI);
dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES;
wShowWindow := SW_HIDE;
hStdInput := GetStdHandle(STD_INPUT_HANDLE); // don't redirect stdin
hStdOutput := StdOutPipeWrite;
hStdError := StdOutPipeWrite;
end;
WorkDir := Work;
Handle := CreateProcess(nil, PChar('cmd.exe /C ' + CommandLine),
nil, nil, True, 0, nil,
PChar(WorkDir), SI, PI);
CloseHandle(StdOutPipeWrite);
if Handle then
try
repeat
WasOK := ReadFile(StdOutPipeRead, Buffer, 255, BytesRead, nil);
if BytesRead > 0 then
begin
Buffer[BytesRead] := #0;
Result := Result + Buffer;
end;
until not WasOK or (BytesRead = 0);
WaitForSingleObject(PI.hProcess, INFINITE);
finally
CloseHandle(PI.hThread);
CloseHandle(PI.hProcess);
end;
finally
CloseHandle(StdOutPipeRead);
end;
end;
end.
|
unit DIOTA.Utils.IotaUnits;
interface
type
IIotaUnit = interface
['{9EE2D8E9-E0FB-41D3-9D30-F18FFC3F8BEF}']
function GetUnit: String;
function GetValue: Int64;
function EqualTo(iotaUnit: IIotaUnit): Boolean;
end;
TIotaUnits = class
private
class function GetIOTA: IIotaUnit; static;
class function GetKILO_IOTA: IIotaUnit; static;
class function GetGIGA_IOTA: IIotaUnit; static;
class function GetMEGA_IOTA: IIotaUnit; static;
class function GetPETA_IOTA: IIotaUnit; static;
class function GetTERA_IOTA: IIotaUnit; static;
public
class property IOTA: IIotaUnit read GetIOTA;
class property KILO_IOTA: IIotaUnit read GetKILO_IOTA;
class property MEGA_IOTA: IIotaUnit read GetMEGA_IOTA;
class property GIGA_IOTA: IIotaUnit read GetGIGA_IOTA;
class property TERA_IOTA: IIotaUnit read GetTERA_IOTA;
class property PETA_IOTA: IIotaUnit read GetPETA_IOTA;
end;
implementation
type
TIotaUnit = class(TInterfacedObject, IIotaUnit)
private
FUnitName: String;
FValue: Int64;
public
constructor Create(unitName: String; value: Int64);
function GetUnit: String;
function GetValue: Int64;
function EqualTo(iotaUnit: IIotaUnit): Boolean;
end;
{ TIotaUnits }
class function TIotaUnits.GetIOTA: IIotaUnit;
begin
Result := TIotaUnit.Create('i', 0);
end;
class function TIotaUnits.GetKILO_IOTA: IIotaUnit;
begin
Result := TIotaUnit.Create('Ki', 3);
end;
class function TIotaUnits.GetMEGA_IOTA: IIotaUnit;
begin
Result := TIotaUnit.Create('Mi', 6);
end;
class function TIotaUnits.GetGIGA_IOTA: IIotaUnit;
begin
Result := TIotaUnit.Create('Gi', 9);
end;
class function TIotaUnits.GetTERA_IOTA: IIotaUnit;
begin
Result := TIotaUnit.Create('Ti', 12);
end;
class function TIotaUnits.GetPETA_IOTA: IIotaUnit;
begin
Result := TIotaUnit.Create('Pi', 15);
end;
{ TIotaUnit }
constructor TIotaUnit.Create(unitName: String; value: Int64);
begin
FUnitName := unitName;
FValue := value;
end;
function TIotaUnit.GetUnit: String;
begin
Result := FUnitName;
end;
function TIotaUnit.GetValue: Int64;
begin
Result := FValue;
end;
function TIotaUnit.EqualTo(iotaUnit: IIotaUnit): Boolean;
begin
Result := (GetUnit = iotaUnit.GetUnit) and (GetValue = iotaUnit.GetValue);
end;
end.
|
unit TSTOBCell.IO;
interface
Uses HsStreamEx, TSTOBCellIntf;
Type
ITSTOBCellFileIO = Interface(ITSTOBCellFile)
['{4B61686E-29A0-2112-A3F0-FBA086E051C1}']
Function GetAsXml() : String;
Procedure SetAsXml(Const AXmlString : String);
Procedure LoadFromStream(ASource : IStreamEx);
Procedure LoadFromFile(Const AFileName : String);
Procedure SaveToStream(ATarget : IStreamEx);
Procedure SaveToFile(Const AFileName : String);
Property AsXml : String Read GetAsXml Write SetAsXml;
End;
TTSTOBCellFileIO = Class(TObject)
Public
Class Function CreateBCellFile() : ITSTOBCellFileIO;
End;
implementation
Uses
HsXmlDocEx, TSTOBCellImpl, TSTOBCell.Bin, TSTOBCell.Xml;
Type
TTSTOBCellFileIOImpl = Class(TTSTOBCellFile, ITSTOBCellFileIO, IBinTSTOBCellFile, IXmlTSTOBCellFile)
Private
FBinImpl : IBinTSTOBCellFile;
FXmlImpl : IXmlTSTOBCellFile;
Function GetBinImplementor() : IBinTSTOBCellFile;
Function GetXmlImplementor() : IXmlTSTOBCellFile;
Protected
Property BinImpl : IBinTSTOBCellFile Read GetBinImplementor Implements IBinTSTOBCellFile;
Property XmlImpl : IXmlTSTOBCellFile Read GetXmlImplementor Implements IXmlTSTOBCellFile;
Function GetAsXml() : String;
Procedure SetAsXml(Const AXmlString : String);
Procedure LoadFromStream(ASource : IStreamEx);
Procedure LoadFromFile(Const AFileName : String);
Procedure SaveToStream(ATarget : IStreamEx);
Procedure SaveToFile(Const AFileName : String);
End;
Class Function TTSTOBCellFileIO.CreateBCellFile() : ITSTOBCellFileIO;
Begin
Result := TTSTOBCellFileIOImpl.Create();
End;
Function TTSTOBCellFileIOImpl.GetBinImplementor() : IBinTSTOBCellFile;
Begin
If Not Assigned(FBinImpl) Then
FBinImpl := TBinTSTOBCellFile.CreateBCellFile();
FBinImpl.Assign(Self);
Result := FBinImpl;
End;
Function TTSTOBCellFileIOImpl.GetXmlImplementor() : IXmlTSTOBCellFile;
Begin
If Not Assigned(FXmlImpl) Then
FXmlImpl := TXmlTSTOBCellFile.CreateBCellFile();
FXmlImpl.Assign(Self);
Result := FXmlImpl;
End;
Function TTSTOBCellFileIOImpl.GetAsXml() : String;
Begin
Result := FormatXmlData(XmlImpl.Xml);
End;
Procedure TTSTOBCellFileIOImpl.SetAsXml(Const AXmlString : String);
Begin
FXmlImpl := TXmlTSTOBCellFile.CreateBCellFile(AXmlString);
Assign(FXmlImpl);
End;
Procedure TTSTOBCellFileIOImpl.LoadFromStream(ASource : IStreamEx);
Begin
FBinImpl := TBinTSTOBCellFile.CreateBCellFile();
FBinImpl.LoadFromStream(ASource);
Assign(FBinImpl);
End;
Procedure TTSTOBCellFileIOImpl.LoadFromFile(Const AFileName : String);
Begin
FBinImpl := TBinTSTOBCellFile.CreateBCellFile();
FBinImpl.LoadFromFile(AFileName);
Assign(FBinImpl);
End;
Procedure TTSTOBCellFileIOImpl.SaveToStream(ATarget : IStreamEx);
Begin
BinImpl.SaveToStream(ATarget);
End;
Procedure TTSTOBCellFileIOImpl.SaveToFile(Const AFileName : String);
Begin
BinImpl.SaveToFile(AFileName);
End;
end.
|
unit Model.PermissionList;
interface
type
TPerm = record
Id : Integer;
Name : string;
Parent : Integer;
end;
const
arrPerms : Array[1..101] of TPerm =
((Id:100; Name:'All authorization parameters'; Parent:0),
(Id:101; Name:'User all ops'; Parent:100),
(Id:102; Name:'User add'; Parent:101),
(Id:103; Name:'User edit'; Parent:101),
(Id:104; Name:'User delete'; Parent:101),
(Id:105; Name:'User view'; Parent:101),
(Id:107; Name:'User group ops'; Parent:101),
(Id:111; Name:'Group all ops'; Parent:100),
(Id:112; Name:'Group add'; Parent:111),
(Id:113; Name:'Group edit'; Parent:111),
(Id:114; Name:'Group delete'; Parent:111),
(Id:115; Name:'Group view'; Parent:111),
(Id:121; Name:'Role all ops'; Parent:100),
(Id:122; Name:'Role add'; Parent:121),
(Id:123; Name:'Role edit'; Parent:121),
(Id:124; Name:'Role delete'; Parent:121),
(Id:125; Name:'Role view'; Parent:121),
(Id:131; Name:'Permission all ops'; Parent:100),
(Id:132; Name:'Permission add'; Parent:131),
(Id:133; Name:'Permission edit'; Parent:131),
(Id:134; Name:'Permission delete'; Parent:131),
(Id:135; Name:'Permission view'; Parent:131),
(Id:140; Name:'All authorization assignments'; Parent:100),
(Id:141; Name:'Group-User assignments'; Parent:140),
(Id:142; Name:'Role-User-Group assignments'; Parent:140),
(Id:143; Name:'Role-User-Group-Permission assignments'; Parent:140),
(Id:3000; Name:'General parameters'; Parent:100),
(Id:3001; Name:'Country all ops'; Parent:3000),
(Id:3002; Name:'Country add'; Parent:3001),
(Id:3003; Name:'Country edit'; Parent:3001),
(Id:3004; Name:'Country delete'; Parent:3001),
(Id:3005; Name:'Country view'; Parent:3001),
(Id:3011; Name:'City all ops'; Parent:3000),
(Id:3012; Name:'City add'; Parent:3011),
(Id:3013; Name:'City edit'; Parent:3011),
(Id:3014; Name:'City delete'; Parent:3011),
(Id:3015; Name:'City view'; Parent:3011),
(Id:3021; Name:'Town all ops'; Parent:3000),
(Id:3022; Name:'Town add'; Parent:3021),
(Id:3023; Name:'Town edit'; Parent:3021),
(Id:3024; Name:'Town delete'; Parent:3021),
(Id:3025; Name:'Town view'; Parent:3021),
(Id:3031; Name:'Location all ops'; Parent:3000),
(Id:3032; Name:'Location add'; Parent:3031),
(Id:3033; Name:'Location edit'; Parent:3031),
(Id:3034; Name:'Location delete'; Parent:3031),
(Id:3035; Name:'Location view'; Parent:3031),
(Id:3041; Name:'Language all ops'; Parent:3000),
(Id:3042; Name:'Language add'; Parent:3041),
(Id:3043; Name:'Language edit'; Parent:3041),
(Id:3044; Name:'Language delete'; Parent:3041),
(Id:3045; Name:'Language view'; Parent:3041),
(Id:3051; Name:'Relationship Type all ops'; Parent:3000),
(Id:3052; Name:'Relationship Type add'; Parent:3051),
(Id:3053; Name:'Relationship Type edit'; Parent:3051),
(Id:3054; Name:'Relationship Type delete'; Parent:3051),
(Id:3055; Name:'Relationship Type view'; Parent:3051),
(Id:3500; Name:'Company Parameters'; Parent:100),
(Id:3501; Name:'Company all ops'; Parent:3500),
(Id:3502; Name:'Company add'; Parent:3501),
(Id:3503; Name:'Company edit'; Parent:3501),
(Id:3504; Name:'Company delete'; Parent:3501),
(Id:3505; Name:'Company view'; Parent:3501),
(Id:3511; Name:'Department all ops'; Parent:3500),
(Id:3512; Name:'Department add'; Parent:3511),
(Id:3513; Name:'Department edit'; Parent:3511),
(Id:3514; Name:'Department delete'; Parent:3511),
(Id:3515; Name:'Department view'; Parent:3511),
(Id:3521; Name:'Title all ops'; Parent:3500),
(Id:3522; Name:'Title add'; Parent:3521),
(Id:3523; Name:'Title edit'; Parent:3521),
(Id:3524; Name:'Title delete'; Parent:3521),
(Id:3525; Name:'Title view'; Parent:3521),
(Id:3531; Name:'Bank all ops'; Parent:3500),
(Id:3532; Name:'Bank add'; Parent:3531),
(Id:3533; Name:'Bank edit'; Parent:3531),
(Id:3534; Name:'Bank delete'; Parent:3531),
(Id:3535; Name:'Bank view'; Parent:3531),
(Id:3541; Name:'Other Income&Cut all ops'; Parent:3500),
(Id:3542; Name:'Other Income&Cut add'; Parent:3541),
(Id:3543; Name:'Other Income&Cut edit'; Parent:3541),
(Id:3544; Name:'Other Income&Cut delete'; Parent:3541),
(Id:3545; Name:'Other Income&Cut view'; Parent:3541),
(Id:3900; Name:'All currency processes'; Parent:100),
(Id:3901; Name:'Currency all ops'; Parent:3900),
(Id:3902; Name:'Currency add'; Parent:3901),
(Id:3903; Name:'Currency edit'; Parent:3901),
(Id:3904; Name:'Currency delete'; Parent:3901),
(Id:3905; Name:'Currency view'; Parent:3901),
(Id:3911; Name:'Currency daily all ops'; Parent:3900),
(Id:3913; Name:'Currency daily edit'; Parent:3911),
(Id:3914; Name:'Currency daily get values from internet'; Parent:3911),
(Id:3915; Name:'Currency daily view'; Parent:3911),
(Id:3916; Name:'Currency daily options to get from internet'; Parent:3911),
(Id:5000; Name:'Employee&Payroll system'; Parent:100),
(Id:5011; Name:'Employee all ops'; Parent:5000),
(Id:5012; Name:'Employee add'; Parent:5011),
(Id:5013; Name:'Employee edit'; Parent:5011),
(Id:5014; Name:'Employee delete'; Parent:5011),
(Id:5015; Name:'Employee view'; Parent:5011),
(Id:10000; Name:'All parameter operations'; Parent:0));
implementation
end.
|
unit UzLogOperatorInfo;
interface
uses
System.SysUtils, System.Classes, StrUtils, IniFiles, Forms, Windows, Menus,
System.DateUtils, Generics.Collections, Generics.Defaults,
UzlogConst;
type
TOperatorInfo = class(TObject)
private
FCallsign: string;
FPower: string;
FAge: string;
FVoiceFiles: array[1..maxmessage] of string;
FAdditionalVoiceFiles: array[2..3] of string;
procedure SetVoiceFile(Index: Integer; S: string);
function GetVoiceFile(Index: Integer): string;
procedure SetAdditionalVoiceFile(Index: Integer; S: string);
function GetAdditionalVoiceFile(Index: Integer): string;
procedure SetPower(S: string);
public
constructor Create();
destructor Destroy(); override;
procedure Assign(src: TOperatorInfo);
property Callsign: string read FCallsign write FCallsign;
property Power: string read FPower write SetPower;
property Age: string read FAge write FAge;
property VoiceFile[Index: Integer]: string read GetVoiceFile write SetVoiceFile;
property AdditionalVoiceFile[Index: Integer]: string read GetAdditionalVoiceFile write SetAdditionalVoiceFile;
end;
TOperatorInfoList = class(TObjectList<TOperatorInfo>)
private
public
constructor Create(OwnsObjects: Boolean = True);
destructor Destroy(); override;
function ObjectOf(callsign: string): TOperatorInfo;
procedure SaveToIniFile();
procedure LoadFromIniFile();
procedure LoadFromOpList();
end;
implementation
constructor TOperatorInfo.Create();
var
i: Integer;
begin
Inherited;
FCallsign := '';
FPower := '';
FAge := '';
for i := Low(FVoiceFiles) to High(FVoiceFiles) do begin
FVoiceFiles[i] := '';
end;
for i := Low(FAdditionalVoiceFiles) to High(FAdditionalVoiceFiles) do begin
FAdditionalVoiceFiles[i] := '';
end;
end;
destructor TOperatorInfo.Destroy();
begin
Inherited;
end;
procedure TOperatorInfo.Assign(src: TOperatorInfo);
var
i: Integer;
begin
FPower := src.Power;
FAge := src.Age;
for i := Low(FVoiceFiles) to High(FVoiceFiles) do begin
FVoiceFiles[i] := src.FVoiceFiles[i];
end;
for i := Low(FAdditionalVoiceFiles) to High(FAdditionalVoiceFiles) do begin
FAdditionalVoiceFiles[i] := src.FAdditionalVoiceFiles[i];
end;
end;
function TOperatorInfo.GetVoiceFile(Index: Integer): string;
begin
Result := FVoiceFiles[Index];
end;
procedure TOperatorInfo.SetVoiceFile(Index: Integer; S: string);
begin
FVoiceFiles[Index] := S;
end;
function TOperatorInfo.GetAdditionalVoiceFile(Index: Integer): string;
begin
Result := FAdditionalVoiceFiles[Index];
end;
procedure TOperatorInfo.SetAdditionalVoiceFile(Index: Integer; S: string);
begin
FAdditionalVoiceFiles[Index] := S;
end;
procedure TOperatorInfo.SetPower(S: string);
begin
S := S + DupeString('-', 13);
FPower := Copy(S, 1, 13);
end;
{ TOperatorInfoList }
constructor TOperatorInfoList.Create(OwnsObjects: Boolean);
begin
Inherited Create(OwnsObjects);
end;
destructor TOperatorInfoList.Destroy();
begin
Inherited;
end;
function TOperatorInfoList.ObjectOf(callsign: string): TOperatorInfo;
var
i: Integer;
begin
for i := 0 to Count - 1 do begin
if Items[i].Callsign = callsign then begin
Result := Items[i];
Exit;
end;
end;
Result := nil;
end;
procedure TOperatorInfoList.SaveToIniFile();
var
ini: TMemIniFile;
i: Integer;
j: Integer;
obj: TOperatorInfo;
section: string;
filename: string;
begin
filename := ExtractFilePath(Application.ExeName) + 'zlog_oplist.ini';
if FileExists(filename) = True then begin
System.SysUtils.DeleteFile(fileName);
end;
ini := TMemIniFile.Create(filename);
try
ini.WriteInteger('operators', 'num', Count);
for i := 0 to Count - 1 do begin
obj := Items[i];
section := 'Operator#' + IntToStr(i);
ini.WriteString(section, 'Callsign', obj.Callsign);
ini.WriteString(section, 'Power', obj.Power);
ini.WriteString(section, 'Age', obj.Age);
for j := 1 to maxmessage do begin
ini.WriteString(section, 'VoiceFile#' + IntToStr(j), obj.VoiceFile[j]);
end;
for j := 2 to 3 do begin
ini.WriteString(section, 'AdditionalVoiceFile#' + IntToStr(j), obj.AdditionalVoiceFile[j]);
end;
end;
ini.UpdateFile();
finally
ini.Free();
end;
end;
procedure TOperatorInfoList.LoadFromIniFile();
var
ini: TMemIniFile;
SL: TStringList;
i: Integer;
j: Integer;
obj: TOperatorInfo;
section: string;
strVoiceFile: string;
S: string;
begin
SL := TStringList.Create();
ini := TMemIniFile.Create(ExtractFilePath(Application.ExeName) + 'zlog_oplist.ini');;
try
ini.ReadSections(SL);
for i := 0 to SL.Count - 1 do begin
section := SL[i];
if Pos('Operator#', section) = 0 then begin
Continue;
end;
S := ini.ReadString(section, 'Callsign', '');
if S = '' then begin
Continue;
end;
obj := TOperatorInfo.Create();
obj.Callsign := S;
obj.Power := ini.ReadString(section, 'Power', '');
obj.Age := ini.ReadString(section, 'Age', '');
for j := 1 to maxmessage do begin
strVoiceFile := ini.ReadString(section, 'VoiceFile#' + IntToStr(j), '');
if strVoiceFile <> '' then begin
if FileExists(strVoiceFile) = False then begin
strVoiceFile := '';
end;
end;
obj.VoiceFile[j] := strVoiceFile;
end;
for j := 2 to 3 do begin
strVoiceFile := ini.ReadString(section, 'AdditionalVoiceFile#' + IntToStr(j), '');
if strVoiceFile <> '' then begin
if FileExists(strVoiceFile) = False then begin
strVoiceFile := '';
end;
end;
obj.AdditionalVoiceFile[j] := strVoiceFile;
end;
if ObjectOf(obj.Callsign) = nil then begin
Add(obj);
end
else begin
obj.Free();
end;
end;
finally
ini.Free();
SL.Free();
end;
end;
procedure TOperatorInfoList.LoadFromOpList();
var
SL: TStringList;
filename: string;
i: Integer;
obj: TOperatorInfo;
S: string;
P: string;
L: string;
begin
SL := TStringList.Create();
try
filename := ExtractFilePath(Application.ExeName) + 'ZLOG.OP';
if FileExists(filename) = False then begin
Exit;
end;
SL.LoadFromFile(filename);
for i := 0 to SL.Count - 1 do begin
L := Trim(SL[i]);
if L = ''then begin
Continue;
end;
S := Trim(Copy(L, 1, 20));
P := Trim(Copy(L, 21));
obj := TOperatorInfo.Create();
obj.Callsign := S;
obj.Power := P;
obj.Age := '';
Add(obj);
end;
finally
SL.Free();
end;
end;
end.
|
unit DFG2;
interface
uses
NLO, SignalField, Func1D, Numerics, FrogTrace;
type
TDFG2 = class(TNLOInteraction)
public
procedure MakeSignalField(pEk: TEField; pEsig: TSignalField); override;
procedure MakeXSignalField(pEk, pERef: TEField; pEsig: TSignalField); override;
function Z(pEx: PArray; pEsig: TSignalField): double; override;
procedure GDerivative(pEk: TEField; pEsig: TSignalField; pFrogI: TFrogTrace; Derivs: PArray); override;
procedure ZDerivative(pEk: TEField; pEsig: TSignalField; Derivs: PArray); override;
function XFrogZ(pEx: PArray; pERef: TEField; pEsig: TSignalField): double; override;
procedure XFrogZDerivative(pEk, pERef: TEField; pEsig: TSignalField; Derivs: PArray); override;
procedure BasicField(pEsig: TSignalField; pEk: TEField); override;
procedure GateField(pEsig: TSignalField; pEk: TEField); override;
function CalculateMarginal(pSpec: TSpectrum; pAuto: TAutocorrelation; pSHGSpec: TSpectrum): TMarginal; override;
function Name: string; override;
function SpectrumMultiplier: double; override;
function NeedSpectrum: Boolean; override;
function NeedAutocorrelation: Boolean; override;
function NeedSHGSpectrum: Boolean; override;
function XTestLam(frogLam, refLam: double): double; override;
function XFrogLam(refLam, testLam: double): double; override;
constructor Create; override;
end;
implementation
uses sysutils;
// Difference frequency generation for XFrog only
constructor TDFG2.Create;
begin
inherited;
mNLOType := nlDFG2;
end;
function TDFG2.Name: string;
begin
Name := 'DFG2: signal = reference - test (hi freq reference)';
end;
function TDFG2.SpectrumMultiplier: double;
begin
// This really should be zero, but I think it's divided by somewhere.
// As long as it's consistent. . .
SpectrumMultiplier := 1.0;
end;
procedure TDFG2.MakeXSignalField(pEk, pERef: TEField; pEsig: TSignalField);
var
tau, t, t0, N, tp: integer;
begin
N := pEk.N;
t0 := N div 2;
for tau := 0 to N - 1 do
begin
for t := 0 to N - 1 do
begin
tp := t - (tau - t0);
if (tp < 0) or (tp >= N) then
begin
pEsig.Re^[tau*N + t] := 0.0;
pEsig.Im^[tau*N + t] := 0.0;
Continue;
end;
pEsig.Re^[tau*N + t] := pEk.Re^[tp]*pERef.Re^[t] + pEk.Im^[tp]*pERef.Im^[t];
pEsig.Im^[tau*N + t] := pEk.Re^[tp]*pERef.Im^[t] - pEk.Im^[tp]*pERef.Re^[t];
end;
end;
// To the w domain
pEsig.TransformToFreq;
end;
function TDFG2.XFrogZ(pEx: PArray; pERef: TEField; pEsig: TSignalField): double;
var
t, tau, tp, N, N2, tr, ti: integer;
sum, sigr, sigi, re, im: double;
begin
N := pEsig.N;
N2 := N div 2;
sum := 0.0;
for t := 0 to N - 1 do
for tau := 0 to N - 1 do
begin
tp := t - (tau - N2);
if (tp >= 0) and (tp < N) then
begin
tr := 2*tp;
ti := tr + 1;
sigr := pEx^[tr]*pERef.Re^[t] + pEx^[ti]*pERef.Im^[t];
sigi := pEx^[tr]*pERef.Im^[t] - pEx^[ti]*pERef.Re^[t];
end
else
begin
sigr := 0.0;
sigi := 0.0;
end;
re := pEsig.Re^[tau*N + t] - sigr;
im := pEsig.Im^[tau*N + t] - sigi;
sum := sum + re*re + im*im;
end;
XFrogZ := sum;
end;
procedure TDFG2.XFrogZDerivative(pEk, pERef: TEField; pEsig: TSignalField; Derivs: PArray);
var
t, tp, tau, N, N2, vr, vi: integer;
sigr, sigi, brakr, braki, re, im: double;
begin
N := pEk.N;
N2 := N div 2;
for t := 0 to N - 1 do
begin
vr := t*2;
vi := vr + 1;
Derivs^[vr] := 0.0;
Derivs^[vi] := 0.0;
for tau := 0 to N - 1 do
begin
tp := t + tau - N2;
if (tp < 0) or (tp >= N) then
begin
re := 0.0;
im := 0.0;
brakr := 0; braki := 0;
end
else
begin
re := pEref.Re^[tp];
im := pEref.Im^[tp];
sigr := pERef.Re^[tp]*pEk.Re^[t] + pERef.Im^[tp]*pEk.Im^[t];
sigi := -pERef.Re^[tp]*pEk.Im^[t] + pERef.Im^[tp]*pEk.Re^[t];
brakr := pEsig.Re^[tau*N + tp] - sigr;
braki := pEsig.Im^[tau*N + tp] - sigi;
end;
Derivs^[vr] := Derivs^[vr] - 2*(re*brakr + im*braki);
Derivs^[vi] := Derivs^[vi] - 2*(im*brakr - re*braki);
end; // end of tau loop
Derivs^[vr] := Derivs^[vr]/(1.0*N);
Derivs^[vi] := Derivs^[vi]/(1.0*N);
end; // end of t loop
end;
function TDFG2.XTestLam(frogLam, refLam: double): double;
var
denom: double;
begin
denom := 1.0/refLam - 1.0/frogLam;
if denom = 0.0 then
raise Exception.Create('Reference field at ' + FloatToStrF(refLam, ffGeneral, 4, 0) +
' nm and XFROG field at ' + FloatToStrF(frogLam, ffGeneral, 4, 0) +
' nm implies an infinite test beam wavelength.');
if denom < 0.0 then
raise Exception.Create('Reference field at ' + FloatToStrF(refLam, ffGeneral, 4, 0) +
' nm and XFROG field at ' + FloatToStrF(frogLam, ffGeneral, 4, 0) +
' nm implies a negative test beam wavelength.');
XTestLam := 1.0/(denom);
end;
function TDFG2.XFrogLam(refLam, testLam: double): double;
var
denom: double;
begin
denom := 1.0/refLam - 1.0/testLam;
if denom = 0.0 then
raise Exception.Create('Reference field at ' + FloatToStrF(refLam, ffGeneral, 4, 0) +
' nm and test field at ' + FloatToStrF(testLam, ffGeneral, 4, 0) +
' nm implies an infinite XFROG Trace wavelength.');
if denom < 0.0 then
raise Exception.Create('Reference field at ' + FloatToStrF(refLam, ffGeneral, 4, 0) +
' nm and test field at ' + FloatToStrF(testLam, ffGeneral, 4, 0) +
' nm implies a negative XFROG Trace wavelength.');
XFrogLam := 1.0/denom;
end;
procedure TDFG2.BasicField(pEsig: TSignalField; pEk: TEField);
var
w, tau, N, minusT: integer;
re, im: double;
begin
// Since the test field is in the E*(t-tau), we need to use the gate field
// function to get the right answer
N := pEk.N;
for tau := 0 to N - 1 do
begin
re := 0;
im := 0;
for w := 0 to N - 1 do
begin
re := re + pEsig.Re^[tau*N + w];
im := im + pEsig.Im^[tau*N + w];
end;
minusT := N - 1 - tau;
pEk.Re^[minusT] := re;
pEk.Im^[minusT] := -im;
end;
end;
procedure TDFG2.GateField(pEsig: TSignalField; pEk: TEField);
begin
end;
procedure TDFG2.MakeSignalField(pEk: TEField; pEsig: TSignalField);
begin
end;
function TDFG2.Z(pEx: PArray; pEsig: TSignalField): double;
begin
Z := 0;
end;
procedure TDFG2.ZDerivative(pEk: TEField; pEsig: TSignalField; Derivs: PArray);
begin
end;
procedure TDFG2.GDerivative(pEk: TEField; pEsig: TSignalField; pFrogI: TFrogTrace; Derivs: PArray);
begin
end;
function TDFG2.NeedSpectrum: Boolean;
begin
NeedSpectrum := True;
end;
function TDFG2.NeedAutocorrelation: Boolean;
begin
NeedAutocorrelation := True;
end;
function TDFG2.NeedSHGSpectrum: Boolean;
begin
NeedSHGSpectrum := True;
end;
function TDFG2.CalculateMarginal(pSpec: TSpectrum; pAuto: TAutocorrelation; pSHGSpec: TSpectrum): TMarginal;
begin
CalculateMarginal := nil;
end;
end. |
unit uCadastroObras;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels,
cxLookAndFeelPainters, cxStyles, cxCustomData, cxFilter, cxData, StrUtils,
cxDataStorage, cxEdit, cxNavigator, Data.DB, cxDBData, Vcl.StdCtrls,
cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxGrid, Vcl.Buttons, Vcl.Mask,
AdvSmoothEdit, AdvSmoothEditButton, AdvSmoothDatePicker, Vcl.ExtCtrls, uDmDados, uModelGrupos, uModelItensObra, uModelObra,
uObrasService, uModelPessoa, uPessoaService, uMemorialDescritivoDAO,
uMemorialService, uModelMemorialDescritivo, cxContainer, cxTextEdit,
cxCurrencyEdit, uItensObraService, uItensObraDAO, uPesquisa, Vcl.ComCtrls,
cxImage, ShellApi, Ora, uCadastroContato;
//ACBrUtil
type
TfrmCadastroObras = class(TForm)
Panel2: TPanel;
Panel3: TPanel;
btnFechar: TSpeedButton;
btnImprimir: TSpeedButton;
btnExcluir: TSpeedButton;
btnEditar: TSpeedButton;
btnSalvar: TSpeedButton;
Panel1: TPanel;
Panel4: TPanel;
btnPesquisaClientes: TSpeedButton;
Label1: TLabel;
Label10: TLabel;
Label19: TLabel;
Label2: TLabel;
Label20: TLabel;
Label21: TLabel;
Label22: TLabel;
Label23: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
Label9: TLabel;
Label25: TLabel;
cbStatus: TComboBox;
cbUF: TComboBox;
edtBairro: TEdit;
edtCEP: TEdit;
edtCidade: TEdit;
edtCliente: TEdit;
edtCodCliente: TEdit;
edtCodigo: TEdit;
edtDataCriacao: TAdvSmoothDatePicker;
edtDataPrevisao: TAdvSmoothDatePicker;
edtInscMunicipal: TEdit;
edtlogradouro: TEdit;
edtlote: TEdit;
edtNumeroAlvara: TEdit;
edtNumeroART: TEdit;
edtQuadra: TEdit;
edtUsodeSolo: TEdit;
Panel5: TPanel;
cxGridItens: TcxGrid;
cxGridItensDBTableView1: TcxGridDBTableView;
cxGridItensDBTableView1CodigoItem: TcxGridDBColumn;
cxGridItensDBTableView1CodMemorial: TcxGridDBColumn;
cxGridItensDBTableView1DescricaoMemorial: TcxGridDBColumn;
cxGridItensDBTableView1Unidade: TcxGridDBColumn;
cxGridItensDBTableView1Quantidade: TcxGridDBColumn;
cxGridItensDBTableView1PercentualUnitario: TcxGridDBColumn;
cxGridItensDBTableView1ValorUnitario: TcxGridDBColumn;
cxGridItensDBTableView1Fornecedor: TcxGridDBColumn;
cxGridItensDBTableView1Grupo: TcxGridDBColumn;
cxGridItensDBTableView1CodFornecedor: TcxGridDBColumn;
cxGridItensLevel1: TcxGridLevel;
lblQuantidadeListada: TLabel;
Label27: TLabel;
Label26: TLabel;
edtValorTotal: TEdit;
edtPercentualTotal: TEdit;
Label24: TLabel;
Label28: TLabel;
Panel6: TPanel;
Panel7: TPanel;
btnmemorial: TSpeedButton;
btnPesquisarFornecedor: TSpeedButton;
Label11: TLabel;
Label12: TLabel;
Label13: TLabel;
Label14: TLabel;
Label15: TLabel;
Label17: TLabel;
Label18: TLabel;
Label16: TLabel;
btnIncluir: TSpeedButton;
btnremover: TSpeedButton;
edtCodMemorial: TEdit;
edtMemorial: TEdit;
edtQuantidade: TEdit;
cbUnidade: TComboBox;
edtFornecedor: TEdit;
edtCodFornecedor: TEdit;
edtPercentualUnitario: TcxCurrencyEdit;
edtValorUnitario: TcxCurrencyEdit;
Shape1: TShape;
procedure edtCodClienteExit(Sender: TObject);
procedure edtCodFornecedorExit(Sender: TObject);
procedure edtCodMemorialExit(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnIncluirClick(Sender: TObject);
procedure btnFecharClick(Sender: TObject);
procedure btnPesquisaClientesClick(Sender: TObject);
procedure btnPesquisarFornecedorClick(Sender: TObject);
procedure btnmemorialClick(Sender: TObject);
procedure btnremoverClick(Sender: TObject);
procedure btnImprimirClick(Sender: TObject);
procedure btnExcluirClick(Sender: TObject);
procedure BitBtn2Click(Sender: TObject);
procedure btnSalvarClick(Sender: TObject);
procedure btnEditarClick(Sender: TObject);
private
{ Private declarations }
gObra : TObra;
gObraService : TObrasService;
gValortotal : Double;
gPercentualtotal : Double;
public
{ Public declarations }
AcaoCadastro : (acIncluir, acEditar, acVisualizar);
procedure GravarObra;
procedure LimparEditObras;
function BloqueiaEdit(bloqueado : Boolean): Boolean;
procedure NovoItem;
end;
var
frmCadastroObras: TfrmCadastroObras;
implementation
{$R *.dfm}
{ TfrmCadastroObras }
procedure TfrmCadastroObras.BitBtn2Click(Sender: TObject);
begin
ShellExecute(Handle, 'open', 'https://www10.goiania.go.gov.br/AlvaraFacil/Alvara.aspx?ProjetoId=12719' , '', '', 1);
end;
function TfrmCadastroObras.BloqueiaEdit(bloqueado: Boolean): Boolean;
var
i : Integer;
begin
for i := 0 to ComponentCount -1 do
begin
if Components[i] is TEdit then
TEdit(Components[i]).ReadOnly := bloqueado;
end;
cbUnidade.Enabled := not bloqueado;
cbUF.Enabled := not bloqueado;
cbStatus.Enabled := not bloqueado;
btnmemorial.Enabled := not bloqueado;
btnPesquisarFornecedor.Enabled := not bloqueado;
btnPesquisaClientes.Enabled := not bloqueado;
btnIncluir.Enabled := not bloqueado;
btnremover.Enabled := not bloqueado;
edtPercentualUnitario.Enabled := not bloqueado;
edtValorUnitario.Enabled := not bloqueado;
edtDataCriacao.ReadOnly := bloqueado;
edtDataPrevisao.ReadOnly := bloqueado;
end;
procedure TfrmCadastroObras.btnEditarClick(Sender: TObject);
begin
AcaoCadastro := acEditar;
BloqueiaEdit(false);
end;
procedure TfrmCadastroObras.btnExcluirClick(Sender: TObject);
var
pObra : TObra;
pObrasService : TObrasService;
begin
pObra := TObra.Create;
try
pObra.Codigo := StrtoFloat(edtCodigo.Text);
try
pObrasService := TObrasService.Create(pObra);
if pObrasService.Excluir then
ShowMessage('Obra '+ FloattoStr(pObra.Codigo) + ' excluída com sucesso!');
finally
FreeAndNil(pObrasService);
end;
finally
FreeAndNil(pObra);
Close;
end;
end;
procedure TfrmCadastroObras.btnFecharClick(Sender: TObject);
begin
close;
end;
procedure TfrmCadastroObras.btnImprimirClick(Sender: TObject);
begin
DmDados.ImprimirDadosObra(dmDados.CdsObraCODIGO.AsFloat);
end;
procedure TfrmCadastroObras.btnIncluirClick(Sender: TObject);
begin
if edtCodMemorial.Text = '' then
begin
ShowMessage('O Memorial deve ser informado');
edtCodMemorial.SetFocus;
Abort;
end;
if cbUnidade.Text = '' then
begin
ShowMessage('A Unidade deve ser informada');
cbUnidade.SetFocus;
Abort;
end;
if edtQuantidade.Text = '' then
begin
ShowMessage('A Quantidade deve ser informada');
edtQuantidade.SetFocus;
Abort;
end;
if edtValorUnitario.Text = '' then
begin
ShowMessage('O Valor Unitário deve ser informado');
edtValorUnitario.SetFocus;
Abort;
end;
if edtPercentualUnitario.Text = '' then
begin
ShowMessage('O Percentual deve ser informado');
edtPercentualUnitario.SetFocus;
Abort;
end;
if edtCodFornecedor.Text = '' then
begin
ShowMessage('O Fornecedor deve ser informado');
edtCodFornecedor.SetFocus;
Abort;
end;
dmDados.CdsItensObra.Append;
dmDados.CdsItensObraCodigoItem.AsFloat := StrToFloat(edtCodMemorial.Text);
dmDados.CdsItensObraCodMemorial.AsFloat := StrToFloat(edtCodMemorial.Text);
dmDados.CdsItensObraDescricaoMemorial.AsString := dmdados.CdsMemorialDescricao.AsString;
dmDados.CdsItensObraUnidade.AsString := cbUnidade.Text;
dmDados.CdsItensObraQuantidade.AsFloat := StrToFloat(edtQuantidade.Text);
dmDados.CdsItensObraValorUnitario.AsFloat := StrToFloat(edtValorUnitario.Text);
dmDados.CdsItensObraPercentualUnitario.AsFloat := StrToFloat(edtPercentualUnitario.Text);
dmDados.CdsItensObraCodfornecedor.AsFloat := StrToFloat(edtCodFornecedor.Text);
dmDados.CdsItensObraFornecedor.AsString := edtFornecedor.Text;
dmDados.CdsItensObraCodigoObra.AsFloat := dmDados.CdsObraCODIGO.AsFloat;
dmDados.CdsItensObraGrupo.AsString := dmdados.CdsMemorialDescricaoGrupo.AsString;
dmDados.CdsItensObra.Post;
dmDados.CdsItensObra.EnableControls;
gValorTotal := gValorTotal + (dmDados.CdsItensObraQuantidade.AsFloat * dmDados.CdsItensObraValorUnitario.AsFloat);
gPercentualtotal := gPercentualtotal + (dmDados.CdsItensObraPercentualUnitario.AsFloat);
edtPercentualTotal.Text := FormatFloat('#,##0.00',gPercentualtotal);
edtValorTotal.Text := FormatFloat('#,##0.00',gValortotal);
NovoItem;
end;
procedure TfrmCadastroObras.btnSalvarClick(Sender: TObject);
begin
GravarObra;
end;
procedure TfrmCadastroObras.edtCodClienteExit(Sender: TObject);
var
pContato, Contato : TPessoa;
pServicePessoa : TPessoaService;
begin
if edtCodCliente.Text = EmptyStr then
edtCliente.Text := EmptyStr
else
begin
pContato := TPessoa.Create;
Contato := TPessoa.Create;
pServicePessoa := TPessoaService.Create(pContato);
try
pContato.Codigo := StrToFloatDef(edtCodCliente.Text, -1);
pContato.TipoCadastro := 'CLIENTE';
pContato.Inativo := scAtivo;
edtCliente.Text := EmptyStr;
edtCodCliente.Text := EmptyStr;
for Contato in pServicePessoa.Consultar(pContato, True) do
begin
edtCodCliente.Text := FloatToStr(Contato.Codigo);
edtCliente.Text := Contato.NomeFantasia;
end;
if edtCodCliente.Text = EmptyStr then
edtCodCliente.SetFocus;
finally
FreeAndNil(pContato);
FreeAndNil(Contato);
FreeAndNil(pServicePessoa);
end;
end;
end;
procedure TfrmCadastroObras.edtCodFornecedorExit(Sender: TObject);
var
pFornecedor, Fornecedor : TPessoa;
pServiceFornecedor : TPessoaService;
begin
if edtCodFornecedor.Text = EmptyStr then
edtFornecedor.Text := EmptyStr
else
begin
pFornecedor := TPessoa.Create;
Fornecedor := TPessoa.Create;
pServiceFornecedor := TPessoaService.Create(pFornecedor);
try
pFornecedor.Codigo := StrToFloat(edtCodFornecedor.Text);
pFornecedor.TipoCadastro := 'FORNECEDOR';
pFornecedor.Inativo := scAtivo;
edtFornecedor.Text := EmptyStr;
edtCodFornecedor.Text := EmptyStr;
for Fornecedor in pServiceFornecedor.Consultar(pFornecedor, True) do
begin
edtCodFornecedor.Text := FloatToStr(Fornecedor.Codigo);
edtFornecedor.Text := Fornecedor.NomeFantasia;
end;
if edtCodFornecedor.Text = EmptyStr then
edtCodFornecedor.SetFocus;
finally
FreeAndNil(pFornecedor);
FreeAndNil(Fornecedor);
FreeAndNil(pServiceFornecedor);
end;
end;
end;
procedure TfrmCadastroObras.edtCodMemorialExit(Sender: TObject);
var
pMemorial, Memorial : TMemorial;
pServiceMemorial : TMemorialService;
begin
if edtCodMemorial.Text = EmptyStr then
edtMemorial.Text := EmptyStr
else
begin
pMemorial := TMemorial.Create;
Memorial := TMemorial.Create;
pServiceMemorial := TMemorialService.Create(pMemorial);
try
pMemorial.Codigo := StrToFloat(edtCodMemorial.Text);
pMemorial.Inativo := 'Não';
edtCodMemorial.Text := EmptyStr;
edtMemorial.Text := EmptyStr;
for Memorial in pServiceMemorial.ConsultarTodos(pMemorial) do
begin
dmdados.CdsMemorial.Edit;
edtCodMemorial.Text := FloatToStr(Memorial.Codigo);
edtMemorial.Text := Memorial.Descricao;
dmdados.CdsMemorialDescricao.AsString := Memorial.Descricao;
dmdados.CdsMemorialCodgrupo.AsFloat := Memorial.CodGrupo;
dmdados.CdsMemorialDescricaoGrupo.AsString := Memorial.DescricaoGrupo;
dmdados.CdsMemorial.Post;
end;
if edtCodMemorial.Text = EmptyStr then
edtCodMemorial.SetFocus;
finally
FreeAndNil(pMemorial);
FreeAndNil(Memorial);
FreeAndNil(pServiceMemorial);
end;
end;
end;
procedure TfrmCadastroObras.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
dmDados.CdsItensObra.EmptyDataSet;
BloqueiaEdit(false);
end;
procedure TfrmCadastroObras.FormShow(Sender: TObject);
var
pObraService : TObrasService;
pItensService : TItensObraService;
pObra : TObra;
pItensObra , Itens: TItensObra;
I : Word;
Data : TDateTime;
begin
case AcaoCadastro of
acIncluir : frmCadastroObras.Caption := 'Cadastro de Obras - Incluindo ';
acEditar : frmCadastroObras.Caption := 'Cadastro de Obras - Editando';
acVisualizar : frmCadastroObras.Caption := 'Cadastro de Obras - Visualizar';
end;
Data := now;
pObra := TObra.Create;
pObraService := TObrasService.Create(pObra);
Itens := TItensObra.Create;
pItensObra := TItensObra.Create;
pItensService := TItensObraService.Create(pItensObra);
gValortotal := 0;
gPercentualtotal := 0;
try
if AcaoCadastro = acIncluir then
begin
edtCodCliente.SetFocus;
gObra := TObra.Create;
gObraService := TObrasService.Create(gObra);
gValortotal := 0;
gPercentualtotal := 0;
edtDataCriacao.Text := DateToStr(Data);
edtDataPrevisao.Text := DateToStr(Data + 90);
end;
if AcaoCadastro = acVisualizar then
begin
edtCodigo.Text := FloatToStr(dmDados.CdsObraCODIGO.AsFloat);
edtDataCriacao.Text := DateToStr(dmDados.CdsObraDATACRIACAO.AsDateTime);
edtCodCliente.Text := FloatToStr(dmDados.CdsObraCODCLIENTE.AsFloat);
edtCodClienteExit(Sender);
edtDataPrevisao.Text := DateToStr(dmDados.CdsObraDATAPREVISAO.AsDateTime);
edtCep.Text := dmDados.CdsObraCEP.AsString;
edtLogradouro.Text := dmDados.CdsObraLOGRADOURO.AsString;
edtQuadra.Text := dmDados.CdsObraQUADRA.AsString;
edtLote.Text := dmDados.CdsObraLOTE.AsString;
edtBairro.Text := dmDados.CdsObraBAIRRO.AsString;
edtCidade.Text := dmDados.CdsObraCIDADE.AsString;
edtNumeroART.Text := dmDados.CdsObraNUMEROART.AsString;
edtNumeroAlvara.Text := dmDados.CdsObraALVARA.AsString;
edtInscMunicipal.Text := dmDados.CdsObraINSCRICAOMUNICIPAL.AsString;
for I := 0 to cbUF.Items.Count -1 do
begin
if cbUF.Items[I] = dmDados.CdsObraUF.AsString then
cbUF.ItemIndex := I;
end;
pItensObra.CodigoObra := dmDados.CdsObraCODIGO.AsFloat;
dmDados.CdsItensObra.EmptyDataSet;
for Itens in pItensService.ConsultarTodos(pItensObra) do
begin
dmDados.CdsItensObra.Append;
dmDados.CdsItensObraCodigoItem.AsFloat := Itens.CodigoItem;
dmDados.CdsItensObraCodMemorial.AsFloat := Itens.CodMemorial;
dmDados.CdsItensObraDescricaoMemorial.AsString := Itens.DescricaoMemorial;
dmDados.CdsItensObraUnidade.AsString := Itens.Unidade;
dmDados.CdsItensObraQuantidade.AsFloat := Itens.Quantidade;
dmDados.CdsItensObraValorUnitario.AsFloat := Itens.ValorUnitario;
dmDados.CdsItensObraPercentualUnitario.AsFloat := Itens.PercentualUnitario;
dmDados.CdsItensObraCodfornecedor.AsFloat := Itens.CodFornecedor;
dmDados.CdsItensObraFornecedor.AsString := Itens.DescricaoFornecedor;
dmDados.CdsItensObraCodigoObra.AsFloat := Itens.CodigoObra;
dmDados.CdsItensObraGrupo.AsString := Itens.Grupo;
dmDados.CdsItensObra.Post;
dmDados.CdsItensObra.EnableControls;
gValorTotal := gValorTotal + (dmDados.CdsItensObraQuantidade.AsFloat * dmDados.CdsItensObraValorUnitario.AsFloat);
gPercentualtotal := gPercentualtotal + (dmDados.CdsItensObraPercentualUnitario.AsFloat);
end;
BloqueiaEdit(AcaoCadastro = acVisualizar);
BloqueiaEdit(AcaoCadastro = acEditar);
end;
finally
lblQuantidadeListada.Caption := IntToStr(dmDados.CdsItensObra.RecordCount);
edtPercentualTotal.Text := FormatFloat('#,##0.00',gPercentualtotal);
edtValorTotal.Text := FormatFloat('#,##0.00',gValortotal);
FreeAndNil(pObra);
FreeAndNil(pObraService);
FreeAndNil(Itens);
FreeAndNil(pItensObra);
FreeAndNil(pItensService);
end;
end;
procedure TfrmCadastroObras.GravarObra;
var
pItens : TItensObra;
pObra : TObra;
pObraService : TObrasService;
begin
pObra := TObra.Create;
pObraService := TObrasService.Create(pObra);
dmDados.CdsObra.Append;
if AcaoCadastro = acEditar then
dmDados.CdsObraCODIGO.AsFloat := StrToFloat(edtCodigo.Text);
if AcaoCadastro = acIncluir then
dmDados.CdsObraCODIGO.AsFloat := gObraService.GerarProxCodigoObra;
dmDados.CdsObraDATACRIACAO.AsDateTime := now;
dmDados.CdsObraCODCLIENTE.AsFloat := StrtoFloatDef(edtCodCliente.Text, 0 );
dmDados.CdsObraDATAPREVISAO.AsDateTime := StrToDate(edtDataPrevisao.Text);
dmDados.CdsObraCEP.AsString := edtCep.Text;
dmDados.CdsObraLOGRADOURO.AsString := edtLogradouro.Text;
dmDados.CdsObraQUADRA.AsString := edtQuadra.Text;
dmDados.CdsObraLOTE.AsString := edtLote.Text;
dmDados.CdsObraBAIRRO.AsString := edtBairro.Text;
dmDados.CdsObraCIDADE.AsString := edtCidade.Text;
dmDados.CdsObraUF.AsString := cbUF.Text;
dmDados.CdsObraNUMEROART.AsString := edtNumeroART.Text;
dmDados.CdsObraALVARA.AsString := edtNumeroAlvara.Text;
dmDados.CdsObraINSCRICAOMUNICIPAL.AsString := edtInscMunicipal.Text;
dmDados.CdsObraUsoDeSolo.AsString := edtUsodeSolo.Text;
DmDados.CdsObraValorTotal.AsFloat := gValorTotal;
DmDados.CdsObraStatusObra.AsString := cbStatus.Text;
DmDados.CdsItensObra.First;
while NOT DmDados.CdsItensObra.Eof do
begin
pItens := TItensObra.Create;
pItens.CodigoItem := DmDados.CdsItensObraCodigoItem.AsFloat;
pItens.CodMemorial := DmDados.CdsItensObraCodMemorial.AsFloat;
pItens.Unidade := DmDados.CdsItensObraUnidade.AsString;
pItens.Quantidade := DmDados.CdsItensObraQuantidade.AsFloat;
pItens.ValorUnitario := DmDados.CdsItensObraValorUnitario.AsFloat;
pItens.PercentualUnitario := DmDados.CdsItensObraPercentualUnitario.AsFloat;
pItens.CodFornecedor := DmDados.CdsItensObraCodfornecedor.AsFloat;
pItens.CodigoObra := DmDados.CdsObraCODIGO.AsFloat;
pObraService.InserirItens(pItens);
DmDados.CdsItensObra.Next;
end;
pObra.Codigo := dmDados.CdsObraCODIGO.AsFloat;
pObra.DataCriacao := dmDados.CdsObraDATACRIACAO.AsDateTime;
pObra.CodCliente := dmDados.CdsObraCODCLIENTE.AsFloat;
pObra.DataPrevisao := dmDados.CdsObraDATAPREVISAO.AsDateTime;
pObra.CEP := dmDados.CdsObraCEP.AsString;
pObra.Logradouro := dmDados.CdsObraLOGRADOURO.AsString;
pObra.Quadra := dmDados.CdsObraQUADRA.AsString;
pObra.Lote := dmDados.CdsObraLOTE.AsString;
pObra.Bairro := dmDados.CdsObraBAIRRO.AsString;
pObra.Cidade := dmDados.CdsObraCIDADE.AsString;
pObra.UF := dmDados.CdsObraUF.AsString;
pObra.NumeroART := dmDados.CdsObraNUMEROART.AsString;
pObra.Alvara := dmDados.CdsObraALVARA.AsString;
pObra.InscricaoMunicipal := dmDados.CdsObraINSCRICAOMUNICIPAL.AsString;
pObra.UsoDeSolo := dmDados.CdsObraUsoDeSolo.AsString;
pObra.ValorTotal := dmDados.CdsObraValorTotal.AsFloat;
if cbStatus.ItemIndex = 0 then
pObra.StatusObra := soAguardandoPlanejamento;
if cbStatus.ItemIndex = 1 then
pObra.StatusObra := soEmAndamento;
if cbStatus.ItemIndex = 2 then
pObra.StatusObra := soFinalizado;
if AcaoCadastro = acEditar then
begin
pObraService.InserirCabecalho(pObra);
pObraService.Alterar;
ShowMessage('Obra ' + FloatToStr(pObra.Codigo) + ' Alterada com Sucesso!' );
Abort;
end;
if DmDados.CdsItensObra.RecordCount = 0 then
begin
case MessageDlg('Confirma a criação da Obra sem informar os Memoriais Descritivos?', mtConfirmation, [mbOK, mbCancel], 0) of mrOk:
begin
pObraService.InserirCabecalho(pObra);
pObraService.Salvar;
ShowMessage('Obra ' + FloatToStr(pObra.Codigo) + ' Criada com Sucesso!' );
end;
mrCancel:
begin
edtCodMemorial.SetFocus;
Abort;
end;
end
end
else
begin
pObraService.InserirCabecalho(pObra);
pObraService.Salvar;
ShowMessage('Obra ' + FloatToStr(pObra.Codigo) + ' Criada com Sucesso!' );
end;
BloqueiaEdit(true);
end;
procedure TfrmCadastroObras.LimparEditObras;
var
i : Integer;
begin
for i := 0 to ComponentCount -1 do
begin
if Components[i] is TEdit then
TEdit(Components[i]).Text := '';
end;
cbUnidade.ItemIndex := -1;
edtDataCriacao.Text := formatdatetime('dd/mm/yyyy', now);
edtDataPrevisao.Text := formatdatetime('dd/mm/yyyy', now + 60);
end;
procedure TfrmCadastroObras.NovoItem;
begin
edtCodMemorial.Text := EmptyStr;
edtMemorial.Text := EmptyStr;
edtFornecedor.Text := EmptyStr;
edtQuantidade.Text := EmptyStr;
edtValorUnitario.Text := EmptyStr;
edtPercentualUnitario.Text := EmptyStr;
edtCodFornecedor.Text := EmptyStr;
cbUnidade.ItemIndex := -1;
edtCodMemorial.SetFocus;
end;
procedure TfrmCadastroObras.btnmemorialClick(Sender: TObject);
var
frmPesquisa: TfrmPesquisa;
begin
frmPesquisa := TfrmPesquisa.Create(nil);
try
frmPesquisa.Caption := 'Pesquisar Memorial';
frmPesquisa.PageControl1.TabIndex := 0;
frmPesquisa.ShowModal;
edtCodMemorial.Text := FloatToStr(dmdados.CdsMemorialCodigo.AsFloat);
finally
FreeAndNil(frmPesquisa);
edtCodMemorialExit(Sender);
end;
end;
procedure TfrmCadastroObras.btnPesquisarFornecedorClick(Sender: TObject);
var
frmPesquisa: TfrmPesquisa;
begin
frmPesquisa := TfrmPesquisa.Create(nil);
try
frmPesquisa.Caption := 'Pesquisar Fornecedor';
frmPesquisa.PageControl1.TabIndex := 3;
frmPesquisa.ShowModal;
edtCodFornecedor.Text := FloatToStr(dmdados.CdsContatosCodigo.AsFloat);
finally
FreeAndNil(frmPesquisa);
edtCodFornecedorExit(Sender);
end;
end;
procedure TfrmCadastroObras.btnremoverClick(Sender: TObject);
begin
case MessageDlg('Confirma a exclusão do memorial: ' + dmdados.CdsItensObraDescricaoMemorial.AsString + ' ?', mtConfirmation, [mbOK, mbCancel], 0) of mrOk:
begin
dmdados.CdsItensObra.Delete;
end;
mrCancel:
begin
Abort;
end;
end;
end;
procedure TfrmCadastroObras.btnPesquisaClientesClick(Sender: TObject);
var
frmPesquisa: TfrmPesquisa;
begin
frmPesquisa := TfrmPesquisa.Create(nil);
try
frmPesquisa.Caption := 'Pesquisar Clientes';
frmPesquisa.PageControl1.TabIndex := 2;
frmPesquisa.ShowModal;
edtCodCliente.Text := FloatToStr(dmdados.CdsContatosCodigo.AsFloat);
finally
FreeAndNil(frmPesquisa);
edtCodClienteExit(Sender);
end;
end;
end.
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, System.SyncObjs, System.UITypes,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Winapi.ActiveX, Winapi.DirectShow9, Vcl.StdCtrls, Vcl.ExtCtrls,
DeckLinkDevice, PreviewWindow, DeckLinkAPI, DeckLinkAPI.Discovery;
type
TForm1 = class(TForm)
GroupBox1: TGroupBox;
GroupBox2: TGroupBox;
GroupBox3: TGroupBox;
m_startStopButton: TButton;
m_vitcTcF1: TLabel;
m_vitcUbF1: TLabel;
m_vitcTcF2: TLabel;
m_vitcUbF2: TLabel;
m_rp188Vitc1Tc: TLabel;
m_rp188Vitc1Ub: TLabel;
m_rp188Vitc2Tc: TLabel;
m_rp188Vitc2Ub: TLabel;
m_rp188LtcTc: TLabel;
m_rp188LtcUb: TLabel;
m_deviceListCombo: TComboBox;
m_modeListCombo: TComboBox;
Label11: TLabel;
Label12: TLabel;
Label13: TLabel;
m_applyDetectedInputModeCheckbox: TCheckBox;
m_invalidInputLabel: TLabel;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
Label9: TLabel;
Label10: TLabel;
m_previewBox: TPanel;
GroupBox4: TGroupBox;
Label14: TLabel;
sRefLocked: TShape;
sRefUnLocked: TShape;
Label15: TLabel;
sInputLocked: TShape;
sInputUnLocked: TShape;
procedure m_startStopButtonClick(Sender: TObject);
procedure bmdDeviceDiscoveryDeviceChange(const status: _bmdDiscoverStatus; const deckLinkDevice: IDeckLink);
procedure FormCreate(Sender: TObject);
procedure m_deviceListComboChange(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure RefreshVideoModeList();
procedure EnableInterface(enabled: boolean);
procedure StopCapture();
procedure StartCapture();
procedure AddDevice(deckLink: IDeckLink);
procedure RemoveDevice(deckLink: IDeckLink);
procedure OnRefreshInputStreamData(var AMessage : TMessageEx); message WM_REFRESH_INPUT_STREAM_DATA_MESSAGE;
procedure OnErrorRestartingCapture(var AMessage : TMessage); message WM_ERROR_RESTARTING_CAPTURE_MESSAGE;
procedure OnSelectVideoMode(var AMessage : TMessage); message WM_SELECT_VIDEO_MODE_MESSAGE;
procedure FormDestroy(Sender: TObject);
private
public
{ Public declarations }
end;
var
Form1: TForm1;
m_deckLinkDiscovery : TDeckLinkDeviceDiscovery;
m_selectedDevice : TDeckLinkInputDevice;
m_previewWindow : TPreviewWindow;
m_ancillaryData : TAncillaryDataStruct;
m_critSec : TCriticalSection;
implementation
{$R *.dfm}
procedure TForm1.OnRefreshInputStreamData(var AMessage : TMessageEx);
begin
// Update the UI under protection of critsec object
m_critSec.Acquire;
try
m_ancillaryData := AMessage.ads;
m_vitcTcF1.Caption := m_ancillaryData.vitcF1Timecode;
m_vitcUbF1.Caption := m_ancillaryData.vitcF1UserBits;
m_vitcTcF2.Caption := m_ancillaryData.vitcF2Timecode;
m_vitcUbF2.Caption := m_ancillaryData.vitcF2UserBits;
m_rp188Vitc1Tc.Caption := m_ancillaryData.rp188vitc1Timecode;
m_rp188Vitc1Ub.Caption := m_ancillaryData.rp188vitc1UserBits;
m_rp188Vitc2Tc.Caption := m_ancillaryData.rp188vitc2Timecode;
m_rp188Vitc2Ub.Caption := m_ancillaryData.rp188vitc2UserBits;
m_rp188LtcTc.Caption := m_ancillaryData.rp188ltcTimecode;
m_rp188LtcUb.Caption := m_ancillaryData.rp188ltcUserBits;
finally
m_critSec.Release;
end;
m_invalidInputLabel.Visible := AMessage.NoInputSource;
end;
procedure TForm1.OnErrorRestartingCapture(var AMessage : TMessage);
begin
// A change in the input video mode was detected, but the capture could not be restarted.
StopCapture();
MessageDlg('This application was unable to apply the detected input video mode.', mtError , [mbOk], 0);
end;
procedure TForm1.OnSelectVideoMode(var AMessage : TMessage);
begin
// A new video mode was selected by the user
m_modeListCombo.ItemIndex := AMessage.WParam;
end;
procedure TForm1.bmdDeviceDiscoveryDeviceChange(const status: _bmdDiscoverStatus; const deckLinkDevice: IDeckLink);
begin
case status of
BMD_ADD_DEVICE :
begin
// A new device has been connected
AddDevice(deckLinkDevice);
end;
BMD_REMOVE_DEVICE :
begin
// An existing device has been disconnected
RemoveDevice(deckLinkDevice);
end;
end;
end;
procedure TForm1.m_deviceListComboChange(Sender: TObject);
var
selectedDeviceIndex : integer;
begin
selectedDeviceIndex := m_deviceListCombo.ItemIndex;
if (selectedDeviceIndex < 0) then
exit;
m_selectedDevice := TDeckLinkinputDevice(m_deviceListCombo.Items.Objects[selectedDeviceIndex]);
// Update the video mode popup menu
RefreshVideoModeList();
// Enable the interface
EnableInterface(true);
if m_selectedDevice.SupportsFormatDetection then
m_applyDetectedInputModeCheckbox.Checked := true
else
m_applyDetectedInputModeCheckbox.Checked := false;
if m_selectedDevice.ReferenceSignalLocked then
begin
sRefUnLocked.Visible := false;
sRefLocked.Visible := true;
end else
begin
sRefUnLocked.Visible := true;
sRefLocked.Visible := false;
end
end;
procedure TForm1.m_startStopButtonClick(Sender: TObject);
begin
if not assigned(m_selectedDevice) then
exit;
if m_selectedDevice.IsCapturing then
StopCapture()
else
StartCapture();
sleep(1000);
if m_selectedDevice.VideoInputSignalLocked then
begin
sInputUnLocked.Visible := false;
sInputLocked.Visible := true;
end else
begin
sInputUnLocked.Visible := true;
sInputLocked.Visible := false;
end
end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
// Stop the capture
StopCapture();
// Release all DeckLinkDevice instances
while(m_deviceListCombo.ItemIndex > 0) do
begin
TDeckLinkinputDevice(m_deviceListCombo.Items.Objects[0]).Destroy;
m_deviceListCombo.Items.Delete(0);
end;
if assigned(m_previewWindow) then
m_previewWindow.Destroy;
// Release DeckLink discovery instance
if assigned(m_deckLinkDiscovery) then
begin
m_deckLinkDiscovery.Disable();
m_deckLinkDiscovery.Destroy;
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
coinitialize(nil);
m_critSec := TCriticalSection.Create;
m_deckLinkDiscovery := nil;
m_selectedDevice := nil;
// Empty popup menus
m_deviceListCombo.Clear;
m_modeListCombo.Clear;;
// Disable the interface
m_startStopButton.Enabled := false;
EnableInterface(false);
// Create and initialise preview and DeckLink device discovery objects
m_previewWindow := TPreviewWindow.Create;
if (m_previewWindow.init(m_previewBox) = false) then
begin
MessageDlg('This application was unable to initialise the preview window', mtError , [mbOk], 0);
exit;
end;
m_deckLinkDiscovery := TDeckLinkDeviceDiscovery.Create;
m_deckLinkDiscovery.OnDeviceChange := bmdDeviceDiscoveryDeviceChange;
if not m_deckLinkDiscovery.Enable then
MessageDlg('Please install the Blackmagic Desktop Video drivers to use the features of this application.', mtError , [mbOk], 0);
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
m_critSec.Free
end;
procedure TForm1.RefreshVideoModeList();
var
modeNames : TArray<string>;
modeIndex : integer;
begin
// Clear the menu
m_modeListCombo.clear;
// Get the mode names
m_selectedDevice.GetDisplayModeNames(modeNames);
// Add them to the menu
for modeIndex := 0 to length(modeNames)-1 do
m_modeListCombo.Items.Add(modeNames[modeIndex]);
m_modeListCombo.ItemIndex:=0;
end;
procedure TForm1.StartCapture();
var
applyDetectedInputMode : boolean;
begin
applyDetectedInputMode := m_applyDetectedInputModeCheckbox.Checked;
if (assigned(m_selectedDevice) and m_selectedDevice.StartCapture(m_modeListCombo.ItemIndex, m_previewWindow, applyDetectedInputMode)) then
begin
// Update UI
m_startStopButton.Caption := 'Stop capture';
EnableInterface(false);
end;
end;
procedure TForm1.StopCapture();
begin
if assigned(m_selectedDevice) then
m_selectedDevice.StopCapture();
// Update UI
m_startStopButton.Caption := 'Start capture';
EnableInterface(true);
m_invalidInputLabel.Visible := false;
end;
procedure TForm1.EnableInterface(enabled: boolean);
begin
m_deviceListCombo.Enabled := enabled;
m_modeListCombo.Enabled := enabled;
if (enabled) then
begin
if (assigned(m_selectedDevice) and m_selectedDevice.SupportsFormatDetection) then
begin
m_applyDetectedInputModeCheckbox.Enabled := true;
end else
begin
m_applyDetectedInputModeCheckbox.Enabled := false;
m_applyDetectedInputModeCheckbox.Checked := false;
end;
end else
m_applyDetectedInputModeCheckbox.Enabled := false;
end;
procedure TForm1.AddDevice(deckLink: IDeckLink);
var
deviceIndex : integer;
newDevice : TDeckLinkInputDevice;
begin
newDevice := TDeckLinkInputDevice.Create(self, deckLink);
// Initialise new DeckLinkDevice object
if not newDevice.Init then
begin
newDevice.Destroy;
exit;
end;
// Add this DeckLink device to the device list
deviceIndex := m_deviceListCombo.Items.AddObject(newDevice.GetDeviceName, TObject(newDevice));
if (deviceIndex < 0) then
exit;
if (m_deviceListCombo.Items.Count = 1) then
begin
// We have added our first item, refresh and enable UI
m_deviceListCombo.ItemIndex:=0;
m_deviceListComboChange(self);
m_startStopButton.Enabled := true;
EnableInterface(true);
end;
end;
procedure TForm1.RemoveDevice(deckLink: IDeckLink);
var
deviceIndex : integer;
deviceToRemove : TDeckLinkInputDevice;
begin
deviceIndex := -1;
deviceToRemove := nil;
// Find the combo box entry to remove (there may be multiple entries with the same name, but each
// will have a different data pointer).
for deviceIndex := 0 to m_deviceListCombo.Items.Count-1 do
begin
deviceToRemove := TDeckLinkInputDevice(m_deviceListCombo.Items.Objects[deviceIndex]);
if (deviceToRemove.DeckLinkInstance = deckLink) then
break;
end;
if not assigned(deviceToRemove) then
exit;;
// Stop capturing before removal
if deviceToRemove.IsCapturing then
deviceToRemove.StopCapture();
// Remove device from list
m_deviceListCombo.Items.Delete(deviceIndex);
// Refresh UI
m_startStopButton.Caption := 'Start capture';
// Check how many devices are left
if (m_deviceListCombo.ItemIndex = 0) then
begin
// We have removed the last device, disable the interface.
m_startStopButton.Enabled := false;
EnableInterface(false);
m_selectedDevice := nil;
end
else if (m_selectedDevice = deviceToRemove) then
begin
// The device that was removed was the one selected in the UI.
// Select the first available device in the list and reset the UI.
m_deviceListCombo.ItemIndex := 0;
m_deviceListComboChange(self);
m_startStopButton.Enabled := true;
m_invalidInputLabel.Visible := false;
end;
// Release DeckLinkDevice instance
//deviceToRemove->Release();
end;
end.
|
program project1;
{ Skeleton Program for the AQA AS Summer 2018 examination
this code should be used in conjunction with the Preliminary Material
written by the AQA AS Programmer Team
Version Number : 1.6
}
{$APPTYPE CONSOLE}
uses
SysUtils,
StrUtils;
Const
SPACE : Char = ' ';
EOL : Char = '#';
EMPTYSTRING : String = '';
Procedure ReportError(s : string);
begin
writeln(Format('%0:-6s', ['*']), s, Format('%0:6s', ['*']));
end;
Function StripLeadingSpaces(Transmission : String) : String;
var
TransmissionLength : Integer;
FirstSignal : Char;
begin
TransmissionLength := length(Transmission);
if TransmissionLength > 0 then
begin
FirstSignal := Transmission[1];
while (FirstSignal = SPACE) and (TransmissionLength > 0) do
begin
TransmissionLength := TransmissionLength - 1;
Transmission := RightStr(Transmission, TransmissionLength);
if TransmissionLength > 0 then
FirstSignal := Transmission[1]
end;
end;
if TransmissionLength = 0 then
ReportError('No signal received');
StripLeadingSpaces := Transmission;
end;
Function StripTrailingSpaces(Transmission : String) : String;
var
LastChar : Integer;
begin
LastChar := length(Transmission);
while Transmission[LastChar] = SPACE do
begin
LastChar := LastChar - 1;
Transmission := LeftStr(Transmission, LastChar);
end;
StripTrailingSpaces := Transmission
end;
Function GetTransmission() : String;
var
FileName : String;
FileHandle : Textfile;
Transmission : String;
begin
write('Enter file name: ');
readln(FileName);
try
assign(FileHandle,FileName);
reset(FileHandle);
readln(FileHandle, Transmission);
close(FileHandle);
Transmission := StripLeadingSpaces(Transmission);
if length(Transmission) > 0 then
begin
Transmission := StripTrailingSpaces(Transmission);
Transmission := Transmission + EOL;
end;
except
on E: exception do
begin
ReportError('No transmission found');
Transmission := EMPTYSTRING;
end;
end ;
GetTransmission := Transmission;
end;
Function GetNextSymbol(var i : Integer; Transmission : String) : String;
var
Signal : Char;
Symbol : String;
SymbolLength : Integer;
begin
if Transmission[i] = EOL then
begin
writeln;
writeln('End of transmission');
Symbol := EMPTYSTRING;
end
else
begin
SymbolLength := 0;
Signal := Transmission[i];
while (not(Signal = SPACE)) and (not(Signal = EOL)) do
begin
inc(i);
Signal := Transmission [i];
inc(SymbolLength);
end;
if SymbolLength = 1 then
Symbol := '.'
else if SymbolLength = 3 then
Symbol := '-'
else if SymbolLength = 0 then
Symbol := SPACE
else
begin
ReportError('Non-standard symbol received');
Symbol := EMPTYSTRING;
end;
end;
GetNextSymbol := Symbol;
end;
Function GetNextLetter(var i : Integer; Transmission : String): String;
var
LetterEnd : Boolean;
Symbol : String;
SymbolString : String;
begin
SymbolString := EMPTYSTRING;
LetterEnd := False;
while not(LetterEnd) do
begin
Symbol := GetNextSymbol(i, Transmission);
if Symbol = SPACE then
begin
LetterEnd := True;
i := i + 4;
end
else if Transmission[i] = EOL then
LetterEnd := True
else if (Transmission[i + 1] = SPACE) and (Transmission[i + 2] = SPACE) then
begin
LetterEnd := True;
i := i + 3;
end
else
i := i + 1;
SymbolString := SymbolString + Symbol;
end;
GetNextLetter := SymbolString;
end;
Function Decode(CodedLetter : String; Dash : Array of Integer; Letter : Array of Char; Dot : Array of Integer) : String;
var
CodedLetterLength, Pointer : Integer;
Symbol : Char;
i : Integer;
begin
CodedLetterLength := length(CodedLetter);
Pointer := 0;
for i := 1 to CodedLetterLength do
begin
Symbol := CodedLetter[i];
if Symbol = SPACE then
Result := SPACE
else
begin
if Symbol = '-' then
Pointer := Dash[Pointer]
else
Pointer := Dot[Pointer];
Result := Letter[Pointer];
end;
end;
Decode := Result;
end;
Procedure ReceiveMorseCode(Dash : Array of Integer; Letter : Array of Char; Dot : Array of Integer);
var
PlainText, MorseCodeString, Transmission , CodedLetter, PlainTextLetter : String;
LastChar, i : Integer;
begin
PlainText := EMPTYSTRING;
MorseCodeString := EMPTYSTRING;
Transmission := GetTransmission();
LastChar := length(Transmission);
i := 1;
while i < LastChar do
begin
CodedLetter := GetNextLetter(i, Transmission);
MorseCodeString := MorseCodeString + SPACE + CodedLetter;
PlainTextLetter := Decode(CodedLetter, Dash, Letter, Dot);
PlainText := PlainText + PlainTextLetter;
end;
writeln(MorseCodeString);
writeln(PlainText);
end;
Procedure SendMorseCode(MorseCode : Array of String);
var
PlainText, MorseCodeString, CodedLetter : String;
PlainTextLength, i, Index : Integer;
PlainTextLetter : Char;
begin
write('Enter your message (uppercase letters and spaces only): ');
readln(PlainText);
PlainTextLength := length(PlainText);
MorseCodeString := EMPTYSTRING;
for i := 1 to PlainTextLength do
begin
PlainTextLetter := PlainText[i];
if PlainTextLetter = SPACE then
Index := 0
else
Index := ord(PlainTextLetter) - ord('A') + 1;
CodedLetter := MorseCode[Index];
MorseCodeString := MorseCodeString + CodedLetter + SPACE;
end;
writeln(MorseCodeString);
end;
Procedure DisplayMenu();
begin
writeln;
writeln('Main Menu');
writeln('=========');
writeln('R - Receive Morse code');
writeln('S - Send Morse code');
writeln('X - Exit program');
writeln;
end;
Function GetMenuOption() : String;
var
MenuOption : String;
begin
MenuOption := EMPTYSTRING;
while length(MenuOption) <> 1 do
begin
write('Enter your choice: ');
readln(MenuOption);
end;
GetMenuOption := MenuOption;
end;
Procedure SendReceiveMessages();
const
Dash: array[0..26] of Integer = (20,23,0,0,24,1,0,17,0,21,0,25,0,15,11,0,0,0,0,22,13,0,0,10,0,0,0);
Dot : array[0..26] of Integer = (5,18,0,0,2,9,0,26,0,19,0,3,0,7,4,0,0,0,12,8,14,6,0,16,0,0,0);
Letter : array[0..26] of Char= (' ','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
MorseCode : array[0..26] of String= (' ','.-','-...','-.-.','-..','.','..-.','--.','....','..','.---','-.-','.-..','--','-.','---','.--.','--.-','.-.','...','-','..-','...-','.--','-..-','-.--','--..');
var
ProgramEnd : Boolean;
MenuOption : String;
begin
ProgramEnd := False;
while not(ProgramEnd) do
begin
DisplayMenu();
MenuOption := GetMenuOption();
if MenuOption = 'R' then
ReceiveMorseCode(Dash, Letter, Dot)
else if MenuOption = 'S' then
SendMorseCode(MorseCode)
else if MenuOption = 'X' then
ProgramEnd := True;
end;
end;
begin
SendReceiveMessages();
ReadLn;
end.
|
{/*************************************************************************** }
{ Module Name: 839P.pas }
{ Purpose: the declaration of PCL839+ functions, data structures, status codes, }
{ constants, and messages }
{ Version: 3.01 }
{ Date: 11/03/2005 }
{ Copyright (c) 2004 Advantech Corp. Ltd. }
{ All rights reserved. }
{****************************************************************************/ }
unit 839p;
const
type
Function set_base( Var address : Longint ): Longint; stdcall;
Function set_mode( Var chan : Longint; Var mode : Longint ): Longint; stdcall;
Function set_speed( Var chan : Longint; Var low_speed : Longint; Var high_speed : Longint; Var accelerate : Longint ): Longint; stdcall;
Function status( Var chan : Longint ): Longint; stdcall;
Function m_stop( Var chan : Longint ): Longint; stdcall;
Function slowdown( Var chan : Longint ): Longint; stdcall;
Function sldn_stop( Var chan : Longint ): Longint; stdcall;
Function waitrdy( Var chan : Longint ): Longint; stdcall;
Function chkbusy( ): Longint; stdcall;
Function out_port( Var port_no : Longint; Var value : Longint ): Longint; stdcall;
Function in_port( Var port_no : Longint ): Longint; stdcall;
Function In_byte( Var offset : Longint ): Longint; stdcall;
Function Out_byte( Var offset : Longint; Var value : Longint ): Longint; stdcall;
Function org( Var chan : Longint; Var dir1 : Longint; Var speed1 : Longint; Var dir2 : Longint; Var speed2 : Longint; Var dir3 : Longint; Var speed3 : Longint ): Longint; stdcall;
Function cmove( Var chan : Longint; Var dir1 : Longint; Var speed1 : Longint; Var dir2 : Longint; Var speed2 : Longint; Var dir3 : Longint; Var speed3 : Longint ): Longint; stdcall;
Function pmove( Var chan : Longint; Var dir1 : Longint; Var speed1 : Longint; Var step1 : Longint ;
Var dir2 : Longint; Var speed2 : Longint; Var step2 : Longint ; Var dir3 : Longint; Var speed3 : Longint; Var step3 : Longint ): Longint; stdcall;
{\\\\\\\\\\\\\\\\\\\\\\\\\\\\\2.1\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\}
Function arc( Var plan_ch : Longint; Var dirc : Longint; Var x1 : Longint; Var y1 : Longint; Var x2 : Longint; Var y2 : Longint ): Longint; stdcall;
Function line( Var plan_ch : Longint; Var dx : Longint; Var dy : Longint ): Longint; stdcall;
Function line3D( Var plan_ch : Longint; Var dx : Longint; Var dy : Longint; Var dz : Longint ): Longint; stdcall;
{\\\\\\\\\\\\\\\\\\\\\\\\\\\\\2.1\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\}
implementation
{\\\\\\\\\\\\\\\\\\\\\Function implement declar\\\\\\\\\\\\\\\\\\\\\\\\\\\\\}
{\\\\\\\\\\Function implement declare \\\\\\\\\\\\\\\\\\
Function set_base; external 'Ads839p.dll';
Function set_mode; external 'Ads839p.dll';
Function set_speed; external 'Ads839p.dll';
Function status; external 'Ads839p.dll';
Function m_stop; external 'Ads839p.dll';
Function slowdown; external 'Ads839p.dll';
Function sldn_stop; external 'Ads839p.dll';
Function waitrdy; external 'Ads839p.dll';
Function chkbusy; external 'Ads839p.dll';
Function out_port; external 'Ads839p.dll';
Function in_port; external 'Ads839p.dll';
Function Out_byte; external 'Ads839p.dll';
Function In_byte; external 'Ads839p.dll';
Function org; external 'Ads839p.dll';
Function cmove; external 'Ads839p.dll';
Function pmove; external 'Ads839p.dll';
Function arc; external 'Ads839p.dll';
Function line; external 'Ads839p.dll';
Function line3D; external 'Ads839p.dll';
End. |
unit Authorization;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, User,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Menus,
ListBooks;
type
TAuthorizationForm = class(TForm)
LoginEdit: TEdit;
PasswordEdit: TEdit;
LoginLabel: TLabel;
PasswordLabel: TLabel;
EntryButton: TButton;
MainMenu: TMainMenu;
HelpButton: TMenuItem;
CheckBox: TCheckBox;
LoginErrorLabel: TLabel;
PasswordErrorLabel: TLabel;
procedure LoginEditChange(Sender: TObject);
procedure PasswordEditChange(Sender: TObject);
procedure HelpButtonClick(Sender: TObject);
procedure EntryButtonClick(Sender: TObject);
Procedure CheckInput();
function CheckAccountInformation: Boolean;
procedure CheckBoxClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
AuthorizationForm: TAuthorizationForm;
implementation
{$R *.dfm}
procedure TAuthorizationForm.CheckBoxClick(Sender: TObject);
begin
if CheckBox.Checked then
PasswordEdit.PasswordChar := #0
else
PasswordEdit.PasswordChar := '*';
end;
Procedure TAuthorizationForm.CheckInput();
Begin
if (LoginEdit.Text = '') then
begin
LoginErrorLabel.Visible := True;
LoginErrorLabel.Caption := 'Отсутствует логин'
end
else
LoginErrorLabel.Caption := '';
if (PasswordEdit.Text = '') then
begin
PasswordErrorLabel.Visible := True;
PasswordErrorLabel.Caption := 'Отсутствует пароль'
end
else
PasswordErrorLabel.Caption := '';
End;
function TAuthorizationForm.CheckAccountInformation: Boolean;
var
PasswordsFile: File of TUser;
ListBooks: TBooksForm;
User: TUser;
IsCorrect: Boolean;
begin
try
if FileExists('passwords.dat') then
begin
AssignFile(PasswordsFile, 'passwords.dat');
Reset(PasswordsFile);
IsCorrect := False;
while not Eof(PasswordsFile) do
begin
Read(PasswordsFile, User);
if (LoginEdit.Text = User.Login) and
(PasswordEdit.Text = User.Password) then
IsCorrect := True;
end;
CloseFile(PasswordsFile);
CheckAccountInformation := IsCorrect;
end
else
IsCorrect := False;
if IsCorrect = False then
MessageBox(Application.Handle, 'Не удаётся войти.' + #10#13 +
'Пожалуйста, проверьте правильность написания логина и пароля.',
'Ошибка', MB_ICONERROR);
CheckAccountInformation := IsCorrect;
except
MessageBox(Handle, 'Ошибка авторизации', 'Уведомленио об ошибке',
MB_ICONERROR);
CheckAccountInformation := False;
end;
end;
procedure TAuthorizationForm.EntryButtonClick(Sender: TObject);
var
ListBooks: TBooksForm;
begin
if CheckAccountInformation then
begin
self.Hide;
ListBooks := TBooksForm.Create(self);
ListBooks.LoadUser(LoginEdit.Text);
self.Show;
LoginEdit.Text := '';
PasswordEdit.Text := '';
end
else
begin
CheckInput;
end;
end;
procedure TAuthorizationForm.HelpButtonClick(Sender: TObject);
begin
MessageBox(Handle, 'Перед Вами представлен вход в учётную запись.' + #10#13
+ 'Для входа Вам необходимо заполнить поля "Логин" и "Пароль".', 'Помощь',
MB_ICONINFORMATION);
end;
procedure TAuthorizationForm.LoginEditChange(Sender: TObject);
begin
LoginErrorLabel.Caption := '';
end;
procedure TAuthorizationForm.PasswordEditChange(Sender: TObject);
begin
PasswordErrorLabel.Caption := '';
end;
end.
|
PROGRAM RationalNumberArithmetic;
TYPE
Rational = RECORD
numerator, denominator: INTEGER;
END;
IntegerInputString = STRING[5];
PROCEDURE PrintRational(VAR rationalToPrint: Rational);
BEGIN
WriteLn(rationalToPrint.numerator, '/', rationalToPrint.denominator);
END;
FUNCTION GreatestCommonDivisor(p, q: INTEGER): INTEGER;
VAR remainder: INTEGER;
BEGIN
REPEAT
remainder := p MOD q;
IF remainder <> 0 THEN BEGIN
p := q;
q := remainder;
END;
UNTIL remainder = 0;
GreatestCommonDivisor := q;
END;
PROCEDURE ReduceRational(VAR rationalToReduce: Rational);
VAR gcd: INTEGER;
BEGIN
gcd := GreatestCommonDivisor(rationalToReduce.numerator, rationalToReduce.denominator);
rationalToReduce.numerator := rationalToReduce.numerator DIV gcd;
rationalToReduce.denominator := rationalToReduce.denominator DIV gcd;
END;
PROCEDURE ReadRational(VAR result: Rational);
VAR inputString: IntegerInputString;
errorIndex: INTEGER;
BEGIN
Write('Please enter the numerator> ');
ReadLn(inputString);
Val(inputString, result.numerator, errorIndex);
IF errorIndex <> 0 THEN BEGIN
WriteLn('You entered an invalid numerator. Please enter a valid integer number. You are allowed to enter negative numbers.');
System.Halt(1);
END;
Write('Please enter the denominator> ');
ReadLn(inputString);
Val(inputString, result.denominator, errorIndex);
IF (errorIndex <> 0) OR (result.denominator <= 0) THEN BEGIN
WriteLn('You entered an invalid denominator. Please enter an integer greater than 0. If you want to enter a negative number please enter a negative numerator.');
System.Halt(1);
END;
ReduceRational(result);
END;
PROCEDURE MultiplyRational(VAR a, b: Rational; VAR c: Rational);
BEGIN
c.numerator := a.numerator * b.numerator;
c.denominator := a.denominator * b.denominator;
ReduceRational(c);
END;
PROCEDURE DivideRational(VAR a, b: Rational; VAR c: Rational);
BEGIN
c.numerator := a.numerator * b.denominator;
c.denominator := a.denominator * b.numerator;
ReduceRational(c);
END;
PROCEDURE AddRational(VAR a, b: Rational; VAR c: Rational);
BEGIN
c.numerator := a.numerator * b.denominator + b.numerator * a.denominator;
c.denominator := a.denominator * b.denominator;
ReduceRational(c);
END;
PROCEDURE SubtractRational(VAR a, b: Rational; VAR c: Rational);
BEGIN
c.numerator := a.numerator * b.denominator - b.numerator * a.denominator;
c.denominator := a.denominator * b.denominator;
ReduceRational(c);
END;
VAR r0, r1, r2: Rational;
BEGIN
(*WriteLn(GreatestCommonDivisor(5, 13));
WriteLn(GreatestCommonDivisor(216, 378));*)
//ReadRational(r2);
r0.numerator := 2;
r0.denominator := 8;
r1.numerator := 26;
r1.denominator := 13;
(*ReduceRational(r0);
PrintRational(r0);
ReduceRational(r1);
PrintRational(r1);
ReduceRational(r2);*)
(*MultiplyRational(r0, r1, r2);
PrintRational(r2);
DivideRational(r1, r0, r2);
PrintRational(r2);
DivideRational(r0, r1, r2);
PrintRational(r2);*)
(*AddRational(r0, r1, r2);
PrintRational(r2);*)
SubtractRational(r0, r1, r2);
PrintRational(r2);
SubtractRational(r1, r0, r2);
PrintRational(r2);
SubtractRational(r1, r1, r2);
PrintRational(r2);
END. |
unit HelpBtns;
interface
USES SysUtils,Classes,Controls,Forms,Buttons,PDataHelper;
type
THelpButton = class;
TAfterHelpEvent = procedure (Sender : THelpButton; Helper : TCustomDataHelper) of object;
TBeforeHelpEvent = procedure (Sender : THelpButton) of object;
THelpButton = class(TBitBtn)
private
FHelpStr: string;
FDataCtrl: TControl;
FAfterHelp: TAfterHelpEvent;
FValues: TList;
FTextValue: string;
FBeforeHelp: TBeforeHelpEvent;
procedure SetDataCtrl(const Value: TControl);
protected
procedure Click; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
constructor Create(AOwner : TComponent); override;
Destructor Destroy;override;
property Values : TList read FValues;
property TextValue : string read FTextValue write FTextValue;
published
property HelpStr : string read FHelpStr write FHelpStr;
property DataCtrl : TControl read FDataCtrl write SetDataCtrl;
property AfterHelp : TAfterHelpEvent read FAfterHelp write FAfterHelp;
property BeforeHelp : TBeforeHelpEvent read FBeforeHelp write FBeforeHelp;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Samples',[THelpButton]);
end;
{ THelpButton }
procedure THelpButton.Click;
var
DataHelper : TCustomDataHelper;
r : integer;
begin
inherited Click;
if HelpStr<>'' then
begin
Values.Clear;
if Assigned(FBeforeHelp) then
FBeforeHelp(self);
if FDataCtrl=nil then
r:=TDataHelpManager.ExecuteHelp(self,HelpStr,FTextValue,Values,DataHelper)
else
r:=TDataHelpManager.ExecuteHelp(FDataCtrl,HelpStr,FTextValue,Values,DataHelper);
if (r>0) and Assigned(FAfterHelp) then
FAfterHelp(self,DataHelper);
end;
end;
constructor THelpButton.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FValues := TList.Create;
end;
destructor THelpButton.Destroy;
begin
FValues.free;
inherited Destroy;
end;
procedure THelpButton.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent,Operation);
if (AComponent=FDataCtrl) and (Operation=opRemove) then
FDataCtrl:=nil;
end;
procedure THelpButton.SetDataCtrl(const Value: TControl);
begin
if FDataCtrl<>value then
begin
FDataCtrl := Value;
if FDataCtrl<>nil then
FDataCtrl.FreeNotification(self);
end;
end;
end.
|
//************************************************************************
//
// Program Name : AT Library
// Platform(s) : Android, iOS, Linux, MacOS, Windows
// Framework : Console, FMX, VCL
//
// Filename : AT.Config.Storage.Intf.pas
// Date Created : 01-AUG-2014
// Author : Matthew Vesperman
//
// Description:
//
// Configuration storage interfaces.
//
// Revision History:
//
// v1.00 : Initial version
//
//************************************************************************
//
// COPYRIGHT © 2014 Angelic Technology
// ALL RIGHTS RESERVED WORLDWIDE
//
//************************************************************************
/// <summary>
/// Configuration storage interfaces.
/// </summary>
unit AT.Config.Storage.Intf;
interface
type
ICfgStgDelete = interface
['{C641AF92-A0FE-4ECF-A0B7-27B6662B31F4}']
procedure DeleteEntry(const sSection: String;
const sEntry: String);
procedure DeleteSection(const sSection: String);
end;
ICfgStgQuery = interface
['{B6366DDA-9ECB-459C-988F-339128AEC09B}']
function HasEntry(const sSection: String; const
sEntry: String): Boolean;
function HasSection(const sSection: String): Boolean;
end;
ICfgStgRead = interface
['{817B7FE0-37BC-4BC4-9DB3-95371116805E}']
function ReadBoolean(const sSection: String; const sEntry: String;
const bDefault: Boolean): Boolean;
function ReadCurrency(const sSection: String; const sEntry: String;
const cDefault: Currency): Currency;
function ReadDate(const sSection: String; const sEntry: String;
const dtDefault: TDateTime): TDateTime;
function ReadDateTime(const sSection: String; const sEntry: String;
const dtDefault: TDateTime): TDateTime;
function ReadDouble(const sSection: String; const sEntry: String;
const rDefault: Double): Double;
function ReadInteger(const sSection: String; const sEntry: String;
const iDefault: Integer): Integer;
function ReadString(const sSection: String; const sEntry: String;
const sDefault: String): string;
function ReadTime(const sSection: String; const sEntry: String;
const dtDefault: TDateTime): TDateTime;
end;
ICfgStgWrite = interface
['{3A6988B5-D337-409C-B558-D7467C673E2A}']
procedure WriteBoolean(const sSection: String; const sEntry: String;
const bValue: Boolean);
procedure WriteCurrency(const sSection: String; const sEntry: String;
const cValue: Currency);
procedure WriteDate(const sSection: String; const sEntry: String;
const dtValue: TDateTime);
procedure WriteDateTime(const sSection: String; const sEntry: String;
const dtValue: TDateTime);
procedure WriteDouble(const sSection: String; const sEntry: String;
const rValue: Double);
procedure WriteInteger(const sSection: String; const sEntry: String;
const iValue: Integer);
procedure WriteString(const sSection: String; const sEntry: String;
const sValue: String);
procedure WriteTime(const sSection: String; const sEntry: String;
const dtValue: TDateTime);
end;
implementation
end.
|
unit BCrypt;
interface
uses BCrypt.Types;
type
TBCrypt = class
public
class function GenerateHash(const APassword: string): string; overload;
class function GenerateHash(const APassword: string; ACost: Byte): string; overload;
class function GenerateHash(const APassword: string; ACost: Byte; AHashType: THashType): string; overload;
class function CompareHash(const APassword: string; const AHash: string): Boolean;
class function NeedsRehash(const AHash: string): Boolean; overload;
class function NeedsRehash(const AHash: string; ACost: Byte): Boolean; overload;
class function GetHashInfo(const AHash: string): THashInfo;
end;
implementation
uses BCrypt.Consts, BCrypt.Core;
class function TBCrypt.GenerateHash(const APassword: string): string;
begin
Result := TBCryptImpl.New.GenerateHash(UTF8String(APassword), THashType.BSD, BCRYPT_DEFAULT_COST);
end;
class function TBCrypt.GenerateHash(const APassword: string; ACost: Byte): string;
begin
Result := TBCryptImpl.New.GenerateHash(UTF8String(APassword), THashType.BSD, ACost);
end;
class function TBCrypt.GenerateHash(const APassword: string; ACost: Byte; AHashType: THashType): string;
begin
Result := TBCryptImpl.New.GenerateHash(UTF8String(APassword), AHashType, ACost);
end;
class function TBCrypt.CompareHash(const APassword: string; const AHash: string): Boolean;
begin
Result := TBCryptImpl.New.CompareHash(UTF8String(APassword), AHash);
end;
class function TBCrypt.GetHashInfo(const AHash: string): THashInfo;
begin
Result := TBCryptImpl.New.GetHashInfo(AHash);
end;
class function TBCrypt.NeedsRehash(const AHash: string; ACost: Byte): Boolean;
begin
Result := TBCryptImpl.New.NeedsRehash(AHash, ACost);
end;
class function TBCrypt.NeedsRehash(const AHash: string): Boolean;
begin
Result := TBCryptImpl.New.NeedsRehash(AHash, BCRYPT_DEFAULT_COST);
end;
end.
|
unit CertAndCRLFunctionsFrame;
{ ------------------------------------------------------------------------------ }
interface
{ ------------------------------------------------------------------------------ }
uses
Windows, Messages, SysUtils, Variants, Classes,
Forms, Dialogs, StdCtrls, ExtCtrls, Graphics, Controls,
EUSignCP, EUSignCPOwnUI, Certificates, Certificate;
{ ------------------------------------------------------------------------------ }
type
TCertAndCRLsFrame = class(TFrame)
ShowCertAndCRLPanel: TPanel;
ShowCertAndCRLUnderlineImage: TImage;
EncryptFileTitleLabel: TLabel;
ShowCertificatesButton: TButton;
ShowCRLButton: TButton;
CheckCertPanel: TPanel;
CheckCertUnderlineImage: TImage;
CheckCertLabel: TLabel;
CheckCertTitleLabel: TLabel;
CheckCertFileButton: TButton;
CheckCertFileEdit: TEdit;
ChooseCheckCertFileButton: TButton;
UpdateCertStorageButton: TButton;
SearchCertPanel: TPanel;
SearchCertUnderlineImage: TImage;
SearchCertTitleLabel: TLabel;
SearchCertButtonByNBUCode: TButton;
TargetFileOpenDialog: TOpenDialog;
SearchCertButtonByEmail: TButton;
procedure UpdateCertStorageButtonClick(Sender: TObject);
procedure ShowCertificatesButtonClick(Sender: TObject);
procedure ShowCRLButtonClick(Sender: TObject);
procedure ChooseCheckCertFileButtonClick(Sender: TObject);
procedure CheckCertFileButtonClick(Sender: TObject);
procedure SearchCertButtonByEmailClick(Sender: TObject);
procedure SearchCertButtonByNBUCodeClick(Sender: TObject);
private
CPInterface: PEUSignCP;
UseOwnUI: Boolean;
procedure ChangeControlsState(Enabled: Boolean);
public
procedure Initialize(CPInterface: PEUSignCP; UseOwnUI: Boolean);
procedure Deinitialize();
procedure WillShow();
end;
{ ------------------------------------------------------------------------------ }
implementation
{ ------------------------------------------------------------------------------ }
{$R *.dfm}
{ ============================================================================== }
procedure TCertAndCRLsFrame.ChangeControlsState(Enabled: Boolean);
begin
CheckCertFileEdit.Enabled := Enabled;
ChooseCheckCertFileButton.Enabled := Enabled;
ShowCertificatesButton.Enabled := Enabled;
ShowCRLButton.Enabled := Enabled;
CheckCertFileButton.Enabled := Enabled;
UpdateCertStorageButton.Enabled := Enabled;
SearchCertButtonByNBUCode.Enabled := Enabled;
SearchCertButtonByEmail.Enabled := Enabled;
end;
{ ------------------------------------------------------------------------------ }
procedure TCertAndCRLsFrame.Initialize(CPInterface: PEUSignCP; UseOwnUI: Boolean);
begin
self.CPInterface := CPInterface;
self.UseOwnUI := UseOwnUI;
ChangeControlsState(True);
end;
{ ------------------------------------------------------------------------------ }
procedure TCertAndCRLsFrame.Deinitialize();
begin
ChangeControlsState(False);
self.CPInterface := nil;
self.UseOwnUI := false;
end;
{ ------------------------------------------------------------------------------ }
procedure TCertAndCRLsFrame.WillShow();
var
Enabled: Boolean;
begin
Enabled := ((CPInterface <> nil) and CPInterface.IsInitialized);
ChangeControlsState(Enabled);
end;
{ ============================================================================== }
procedure TCertAndCRLsFrame.UpdateCertStorageButtonClick(Sender: TObject);
var
Error: Cardinal;
FSReload: LongBool;
begin
FSReload := (MessageBox(Handle,
'Перечитати повністю сертифікати та СВС в файловому сховищі?',
'Повідомлення оператору', MB_YESNO or MB_ICONWARNING) = IDYES);
Error := CPInterface.RefreshFileStore(FSReload);
if (Error <> EU_ERROR_NONE) then
EUShowError(Handle, Error);
end;
{ ------------------------------------------------------------------------------ }
procedure TCertAndCRLsFrame.ShowCertificatesButtonClick(Sender: TObject);
begin
if UseOwnUI then
begin
EUShowCertificates(WindowHandle, '', CPInterface, 'Сертифікати',
CertTypeEndUser, nil);
end
else
CPInterface.ShowCertificates();
end;
{ ------------------------------------------------------------------------------ }
procedure TCertAndCRLsFrame.ShowCRLButtonClick(Sender: TObject);
begin
if UseOwnUI then
begin
EUShowCRLs(WindowHandle, '', CPInterface);
end
else
CPInterface.ShowCRLs();
end;
{ ============================================================================== }
procedure TCertAndCRLsFrame.ChooseCheckCertFileButtonClick(Sender: TObject);
begin
if (not TargetFileOpenDialog.Execute(Handle)) then
Exit;
CheckCertFileEdit.Text := TargetFileOpenDialog.FileName;
end;
{ ------------------------------------------------------------------------------ }
procedure TCertAndCRLsFrame.CheckCertFileButtonClick(Sender: TObject);
var
FileName: AnsiString;
FileStream: TFileStream;
Error: Cardinal;
CertData: PByte;
CertDataSize: Int64;
begin
FileName := CheckCertFileEdit.Text;
if (FileName = '') then
begin
MessageBox(Handle, 'Сертифікат для перевірки не обрано',
'Повідомлення оператору', MB_ICONERROR);
Exit;
end;
FileStream := nil;
CertData := nil;
try
FileStream := TFileStream.Create(FileName, fmOpenRead);
FileStream.Seek(0, soBeginning);
CertDataSize := FileStream.Size;
CertData := GetMemory(CertDataSize);
FileStream.Read(CertData^, CertDataSize);
Error := CPInterface.CheckCertificate(CertData,
Cardinal(CertDataSize));
if (Error <> EU_ERROR_NONE) then
begin
EUShowError(Handle, Error);
end
else
MessageBox(Handle, 'Сертифікат успішно перевірено',
'Повідомлення оператору', MB_ICONINFORMATION);
finally
if (FileStream <> nil) then
FileStream.Destroy;
if (CertData <> nil) then
FreeMemory(CertData);
end;
end;
{ ============================================================================== }
procedure TCertAndCRLsFrame.SearchCertButtonByEmailClick(Sender: TObject);
var
Email: AnsiString;
Error: Cardinal;
OnTime: SYSTEMTIME;
Issuer: array [0..(EU_ISSUER_MAX_LENGTH - 1)] of AnsiChar;
Serial: array [0..(EU_SERIAL_MAX_LENGTH - 1)] of AnsiChar;
Info: PEUCertInfoEx;
begin
Email := AnsiString(InputBox(string('Пошук сертифіката'),
string('Введіть E-mail адресу'), ''));
if (Email = '') then
Exit;
DateTimeToSystemTime(Now(), OnTime);
Error := CPInterface.GetCertificateByEMail(PAnsiChar(Email),
EU_CERT_KEY_TYPE_DSTU4145, EU_KEY_USAGE_DIGITAL_SIGNATURE,
@OnTime, @Issuer, @Serial);
if (Error <> EU_ERROR_NONE) then
begin
EUSignCPOwnUI.EUShowError(Handle, Error);
Exit;
end;
Error := CPInterface.GetCertificateInfoEx(@Issuer, @Serial, @Info);
if (Error <> EU_ERROR_NONE) then
begin
EUSignCPOwnUI.EUShowError(Handle, Error);
Exit;
end;
EUSignCPOwnUI.EUShowCertificate(Handle, 'Сертифікат знайдений за Email',
CPInterface, Info, CertStatusDefault, False);
CPInterface.FreeCertificateInfoEx(Info);
end;
{ ------------------------------------------------------------------------------ }
procedure TCertAndCRLsFrame.SearchCertButtonByNBUCodeClick(Sender: TObject);
var
NBUCode: AnsiString;
Error: Cardinal;
OnTime: SYSTEMTIME;
Issuer: array [0..(EU_ISSUER_MAX_LENGTH - 1)] of AnsiChar;
Serial: array [0..(EU_SERIAL_MAX_LENGTH - 1)] of AnsiChar;
Info: PEUCertInfoEx;
begin
NBUCode := AnsiString(InputBox('Пошук сертифіката', 'Введіть код НБУ', ''));
if (NBUCode = '') then
Exit;
DateTimeToSystemTime(Now(), OnTime);
Error := CPInterface.GetCertificateByNBUCode(PAnsiChar(NBUCode),
EU_CERT_KEY_TYPE_DSTU4145, EU_KEY_USAGE_DIGITAL_SIGNATURE, @OnTime, @Issuer,
@Serial);
if (Error <> EU_ERROR_NONE) then
begin
EUSignCPOwnUI.EUShowError(Handle, Error);
Exit;
end;
Error := CPInterface.GetCertificateInfoEx(@Issuer, @Serial, @Info);
if (Error <> EU_ERROR_NONE) then
begin
EUSignCPOwnUI.EUShowError(Handle, Error);
Exit;
end;
EUSignCPOwnUI.EUShowCertificate(Handle, 'Сертифікат знайдений за кодом НБУ',
CPInterface, Info, CertStatusDefault, False);
CPInterface.FreeCertificateInfoEx(Info);
end;
{ ============================================================================== }
end.
|
unit uUtils;
interface
uses
System.SysUtils,
System.Math,
IntegerX;
type
TUtils = class(TObject)
public
class function CustomMatchStr(InChar: Char; const InString: String)
: Boolean; static;
class function IsNullOrEmpty(const InValue: string): Boolean; static;
class function StartsWith(const InStringOne, InStringTwo: String)
: Boolean; static;
class function EndsWith(const InStringOne, InStringTwo: String)
: Boolean; static;
class function RetreiveMax(const InString: String): Integer; static;
class function ArraytoString(const InArray: TArray<Char>): String; static;
end;
implementation
class function TUtils.CustomMatchStr(InChar: Char;
const InString: String): Boolean;
var
i: Integer;
begin
result := False;
for i := Low(InString) to High(InString) do
begin
if InString[i] = InChar then
begin
result := True;
Exit;
end;
end;
end;
class function TUtils.IsNullOrEmpty(const InValue: string): Boolean;
const
Empty = '';
begin
result := InValue = Empty;
end;
class function TUtils.StartsWith(const InStringOne,
InStringTwo: String): Boolean;
var
tempStr: String;
begin
tempStr := Copy(InStringOne, Low(InStringOne), 2);
result := AnsiSameText(tempStr, InStringTwo);
end;
class function TUtils.EndsWith(const InStringOne, InStringTwo: String): Boolean;
var
tempStr: string;
begin
tempStr := Copy(InStringOne, Length(InStringOne) - 1, 2);
result := AnsiSameText(tempStr, InStringTwo);
end;
class function TUtils.RetreiveMax(const InString: String): Integer;
var
i, MaxOrdinal, TempValue: Integer;
begin
MaxOrdinal := -1;
for i := Low(InString) to High(InString) do
begin
TempValue := Ord(InString[i]);
MaxOrdinal := Max(MaxOrdinal, TempValue);
end;
if MaxOrdinal = -1 then
begin
raise Exception.Create('A Strange Error Occurred');
end
else
result := MaxOrdinal;
end;
class function TUtils.ArraytoString(const InArray: TArray<Char>): String;
begin
SetString(result, PChar(@InArray[0]), Length(InArray));
end;
end.
|
{******************************************************************************}
{ }
{ WiRL: RESTful Library for Delphi }
{ }
{ Copyright (c) 2015-2019 WiRL Team }
{ }
{ https://github.com/delphi-blocks/WiRL }
{ }
{******************************************************************************}
unit WiRL.Tests.Framework.Response;
interface
uses
System.Classes, System.SysUtils, System.StrUtils, System.JSON,
System.NetEncoding,
DUnitX.TestFramework,
WiRL.http.Accept.MediaType,
WiRL.http.Response,
WiRL.Tests.Mock.Server;
type
[TestFixture]
TTestResponse = class(TObject)
private
FResponse: TWiRLTestResponse;
public
[Setup]
procedure Setup;
[TearDown]
procedure TearDown;
[Test]
procedure TestDate;
[Test]
procedure TestEmptyDate;
[Test]
procedure TestExpires;
[Test]
procedure TestEmptyExpires;
[Test]
procedure TestLastModified;
[Test]
procedure TestEmptyLastModified;
[Test]
procedure TestContent;
[Test]
procedure TestContentStream;
[Test]
procedure TestEmptyStatusCode;
[Test]
procedure TestReasonString;
[Test]
procedure TestContentType;
[Test]
procedure TestContentEncoding;
[Test]
procedure TestContentLength;
[Test]
procedure TestEmptyContentLength;
[Test]
procedure TestHeaderFields;
[Test]
procedure TestContentMediaType;
[Test]
procedure TestConnection;
[Test]
procedure TestAllow;
[Test]
procedure TestServer;
[Test]
procedure TestWWWAuthenticate;
[Test]
procedure TestLocation;
[Test]
procedure TestContentLanguage;
end;
implementation
{ TTestResponse }
const
OneSecond = 1 {day} / 24 { hours } / 60 { minutes } / 60 { seconds };
procedure TTestResponse.Setup;
begin
FResponse := TWiRLTestResponse.Create;
end;
procedure TTestResponse.TearDown;
begin
FResponse.Free;
end;
procedure TTestResponse.TestAllow;
begin
FResponse.Allow := 'GET, HEAD';
Assert.AreEqual('GET, HEAD', FResponse.Allow);
end;
procedure TTestResponse.TestConnection;
begin
FResponse.Connection := 'open';
Assert.AreEqual('open', FResponse.Connection);
end;
procedure TTestResponse.TestContent;
begin
FResponse.ContentType := 'text/plain; charset=utf-8';
FResponse.Content := '123';
Assert.AreEqual('123', FResponse.Content);
end;
procedure TTestResponse.TestContentEncoding;
begin
FResponse.ContentEncoding := 'gzip';
Assert.AreEqual('gzip', FResponse.ContentEncoding);
end;
procedure TTestResponse.TestContentLanguage;
begin
FResponse.ContentLanguage := 'en';
Assert.AreEqual('en', FResponse.ContentLanguage);
end;
procedure TTestResponse.TestContentLength;
begin
FResponse.ContentLength := 100;
Assert.AreEqual(True, FResponse.HasContentLength);
Assert.AreEqual<Integer>(100, FResponse.ContentLength);
end;
procedure TTestResponse.TestContentMediaType;
begin
FResponse.ContentType := 'text/plain; charset=utf-8';
Assert.AreEqual('text', FResponse.ContentMediaType.MainType);
Assert.AreEqual('plain', FResponse.ContentMediaType.SubType);
Assert.AreEqual('utf-8', FResponse.ContentMediaType.Charset);
end;
procedure TTestResponse.TestContentStream;
const
Base64Buffer = 'AAGh/w=='; // 0001A1FF
var
TestStream: TStream;
InputBuffer: TBytes;
OutputBuffer: TBytes;
begin
InputBuffer := TNetEncoding.Base64.DecodeStringToBytes(Base64Buffer);
TestStream := TBytesStream.Create(InputBuffer);
FResponse.ContentStream := TestStream;
OutputBuffer := FResponse.RawContent;
Assert.AreEqual(InputBuffer, OutputBuffer);
end;
procedure TTestResponse.TestContentType;
begin
FResponse.ContentType := 'text/plain';
Assert.AreEqual('text/plain', FResponse.ContentType);
end;
procedure TTestResponse.TestDate;
var
LTestDate: TDateTime;
begin
LTestDate := Now - 10;
FResponse.Date := LTestDate;
Assert.AreEqual(LTestDate, FResponse.Date, OneSecond);
end;
procedure TTestResponse.TestEmptyContentLength;
begin
Assert.IsFalse(FResponse.HasContentLength);
end;
procedure TTestResponse.TestEmptyDate;
begin
Assert.AreEqual(Now, FResponse.Date, OneSecond);
end;
procedure TTestResponse.TestEmptyExpires;
begin
Assert.AreEqual(0, FResponse.Expires, OneSecond);
end;
procedure TTestResponse.TestEmptyLastModified;
begin
Assert.AreEqual(0, FResponse.LastModified, OneSecond);
end;
procedure TTestResponse.TestExpires;
var
LTestDate: TDateTime;
begin
LTestDate := Now - 10;
FResponse.Expires := LTestDate;
Assert.AreEqual(LTestDate, FResponse.Expires, OneSecond);
end;
procedure TTestResponse.TestHeaderFields;
begin
FResponse.HeaderFields['x-test-header'] := 'test-value';
Assert.AreEqual('test-value', FResponse.HeaderFields['x-test-header']);
end;
procedure TTestResponse.TestLastModified;
var
LTestDate: TDateTime;
begin
LTestDate := Now - 10;
FResponse.LastModified := LTestDate;
Assert.AreEqual(LTestDate, FResponse.LastModified, OneSecond);
end;
procedure TTestResponse.TestLocation;
begin
FResponse.Location := 'https://github.com/delphi-blocks/WiRL';
Assert.AreEqual('https://github.com/delphi-blocks/WiRL', FResponse.Location);
end;
procedure TTestResponse.TestReasonString;
begin
Assert.AreEqual('OK', FResponse.ReasonString);
end;
procedure TTestResponse.TestServer;
begin
FResponse.Server := 'WiRL WebServer';
Assert.AreEqual('WiRL WebServer', FResponse.Server);
end;
procedure TTestResponse.TestWWWAuthenticate;
begin
FResponse.WWWAuthenticate := 'basic';
Assert.AreEqual('basic', FResponse.WWWAuthenticate);
end;
procedure TTestResponse.TestEmptyStatusCode;
begin
Assert.AreEqual(200, FResponse.StatusCode);
end;
initialization
TDUnitX.RegisterTestFixture(TTestResponse);
end.
|
unit unClassSemaforo;
interface
uses ExtCtrls, Classes, Controls, Graphics, MMSystem;
Type
TSemaforo = class(TImage)
private
// Fields
FTamLamp: Byte;
FTimer : TTimer;
FAtual : Byte;
FAlerta : Boolean;
FAcende : Boolean;
procedure Desenha;
procedure Lampada(Pos: Byte; Liga: Boolean);
procedure ResetAberto;
procedure ResetFechado;
procedure MudaAlerta(Init, Prox: TSemaforo);
// Eventos
procedure FTimerTimer (Sender: TObject);
procedure SetAlerta(const Value: Boolean);
public
Proximo: TSemaforo;
constructor Create(X, Y: Integer; crTamLamp: Byte; AOwner: TComponent);
destructor Destroy;
property Alerta: Boolean read FAlerta Write SetAlerta;
end;
implementation
{ TSemaforo }
constructor TSemaforo.Create(X, Y: Integer; crTamLamp: Byte;
AOwner: TComponent);
begin
inherited Create(AOwner);
Parent := TWinControl(AOwner);
Left := X;
Top := Y;
FTamLamp := CrTamLamp;
Width := 3 * FTamLamp;
Height := 6 * FTamLamp;
FAtual := 7;
FAlerta := True;
Desenha;
FTimer := TTimer.Create(AOwner);
FTimer.Interval := 500;
FTimer.Enabled := True;
FTimer.OnTimer := FTimerTImer;
end;
procedure TSemaforo.Desenha;
var i: Byte;
begin
with Canvas do
begin
Pen.Color := clBlack;
Brush.Color := clSilver;
Rectangle(0, 0, 3 * FTamLamp, 6 * FTamLamp);
for I := 1 to 13 do
Lampada(i, False);
end;
end;
destructor TSemaforo.Destroy;
begin
FTimer.Free;
inherited;
end;
procedure TSemaforo.FTimerTimer(Sender: TObject);
begin
if FAlerta then
begin
FAcende := Not FAcende;
Lampada(7, FAcende);
end
else
begin
// Incrementando o Atual
if FAtual = 13 then
FAtual := 1
else
inc(FAtual);
case FAtual of
1 : Begin
Lampada(13, False);
Lampada(1, True);
Lampada(6, True);
End;
2..7,
9..13: begin
if(FAtual = 3) AND (Proximo <> Nil) then
Proximo.FTimer.Enabled := True;
Lampada(FAtual - 1, False);
Lampada(FAtual, True);
end;
8 : begin
FTimer.Enabled := False;
Lampada(7, False);
Lampada(8, True);
Lampada(13, True);
end;
end;
end;
end;
procedure TSemaforo.Lampada(Pos: Byte; Liga: Boolean);
var x, y: Integer;
cor: TColor;
begin
case Pos of
1..6 : begin
X := FTamLamp * 2;
Y := FTamLamp * (Pos - 1);
cor := clLime;
end;
7 : begin
X := FTamLamp;
Y := FTamLamp * 5;
cor := clYellow;
end;
8..13: begin
X := 0;
Y := FTamLamp * (Pos - 8);
cor := clRed;
end;
end;
if Not Liga then
cor := clBlack;
with Canvas do
begin
Pen.Color := clBlack;
Brush.Color := clSilver;
Rectangle(x, y, x + FTamLamp, y + FTamLamp);
Brush.Color := cor;
Ellipse(x, y, x + FTamLamp, y + FTamLamp);
end;
end;
procedure TSemaforo.MudaAlerta(Init, Prox: TSemaforo);
begin
if(Init = Prox) OR (Proximo = Nil) then
with Init do
begin
Desenha;
FTimer.Enabled := False;
FAcende := False;
if Not FAlerta then
ResetAberto
else
FAtual := 7;
FTimer.Enabled := True;
end
else
with Prox do
begin
Desenha;
FTimer.Enabled := False;
FAcende := False;
FAlerta := Init.FAlerta;
if Not FAlerta then
ResetFechado
else
FAtual := 7;
if Proximo <> Nil then
MudaAlerta(Init, Proximo);
FTimer.Enabled := FAlerta;
end;
end;
procedure TSemaforo.ResetAberto;
begin
FAtual := 1;
Lampada(1, True);
Lampada(6, True);
end;
procedure TSemaforo.ResetFechado;
begin
FAtual := 8;
Lampada(8, True);
Lampada(13, True);
end;
procedure TSemaforo.SetAlerta(const Value: Boolean);
begin
if Value <> FAlerta then
begin
FAlerta := Value;
MudaAlerta(Self, Proximo);
end;
end;
end.
|
unit CreditLimitDistributor;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, AncestorDBGrid, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, cxPCdxBarPopupMenu, cxStyles, cxCustomData, cxFilter,
cxData, cxDataStorage, cxEdit, Data.DB, cxDBData,
Vcl.Menus, dsdAddOn, dxBarExtItems, dxBar, cxClasses, dsdDB,
Datasnap.DBClient, dsdAction, Vcl.ActnList, cxPropertiesStore, cxGridLevel,
cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView,
cxGrid, cxPC, cxButtonEdit, Vcl.ExtCtrls, cxSplitter, cxDropDownEdit,
dxSkinsCore, dxSkinsDefaultPainters, dxSkinscxPCPainter, dxSkinsdxBarPainter,
dxBarBuiltInMenu, cxNavigator, cxContainer, Vcl.ComCtrls, dxCore, cxDateUtils,
cxLabel, cxTextEdit, cxMaskEdit, cxCalendar, dsdGuides, cxCurrencyEdit;
type
TCreditLimitDistributorForm = class(TAncestorDBGridForm)
bbSetErased: TdxBarButton;
bbUnErased: TdxBarButton;
bbSetErasedChild: TdxBarButton;
bbUnErasedChild: TdxBarButton;
bbdsdChoiceGuides: TdxBarButton;
cxSplitter1: TcxSplitter;
Code: TcxGridDBColumn;
actInsert: TdsdInsertUpdateAction;
actUpdate: TdsdInsertUpdateAction;
dxBarButton1: TdxBarButton;
dxBarButton2: TdxBarButton;
dxBarButton3: TdxBarButton;
dxBarButton4: TdxBarButton;
dxBarButton5: TdxBarButton;
FormParams: TdsdFormParams;
HeaderSaver: THeaderSaver;
bbInsertUpdateMovement: TdxBarButton;
CreditLimit: TcxGridDBColumn;
JuridicalName: TcxGridDBColumn;
private
{ Private declarations }
public
{ Public declarations }
end;
implementation
{$R *.dfm}
initialization
RegisterClass(TCreditLimitDistributorForm);
end.
|
unit jclass_annotations;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
jclass_common,
jclass_types;
type
TJClassAnnotation = class;
{ TJClassElementValue }
TJClassElementValue = class(TJClassLoadable)
private
FTag: UInt8;
FFirstIndex: UInt16;
FSecondIndex: UInt16;
FArrayValue: TList;
FAnnotation: TJClassAnnotation;
public
procedure BuildDebugInfo(AIndent: string; AOutput: TStrings); override;
destructor Destroy; override;
procedure LoadFromStream(AStream: TStream); override;
end;
TJClassElementValuePair = record
ElementNameIndex: UInt16;
ElementValue: TJClassElementValue;
end;
{ TJClassAnnotation }
TJClassAnnotation = class(TJClassLoadable)
private
FTypeIndex: UInt16;
FElementValuePairs: array of TJClassElementValuePair;
public
procedure BuildDebugInfo(AIndent: string; AOutput: TStrings); override;
destructor Destroy; override;
procedure LoadFromStream(AStream: TStream); override;
end;
{ TJClassTypeAnnotation }
TJClassTypeAnnotation = class(TJClassLoadable)
private
FTargetType: UInt8;
FTypeParameterTarget: TJClassTypeParameterTarget;
FSupertypeTarget: TJClassSupertypeTarget;
FTypeParameterBoundTarget: TJClassTypeParameterBoundTarget;
FMethodFormalParameterTarget: TJClassMethodFormalParameterTarget;
FThrowsTarget: TJClassThrowsTarget;
FLocalvarTarget: TJClassLocalvarTarget;
FCatchTarget: TJClassCatchTarget;
FOffsetTarget: TJClassOffsetTarget;
FTypeArgumentTarget: TJClassTypeArgumentTarget;
FTypePath: array of TJClassTypePath;
FTypeIndex: UInt16;
FElementValuePairs: array of TJClassElementValuePair;
public
procedure BuildDebugInfo(AIndent: string; AOutput: TStrings); override;
destructor Destroy; override;
procedure LoadFromStream(AStream: TStream); override;
end;
implementation
uses
jclass_enum;
{ TJClassTypeAnnotation }
procedure TJClassTypeAnnotation.BuildDebugInfo(AIndent: string; AOutput: TStrings);
begin
AOutput.Add('not supported (TJClassTypeAnnotation)');
end;
destructor TJClassTypeAnnotation.Destroy;
var
i: integer;
begin
for i := 0 to Length(FElementValuePairs) do
FElementValuePairs[i].ElementValue.Free;
inherited Destroy;
end;
procedure TJClassTypeAnnotation.LoadFromStream(AStream: TStream);
var
i: integer;
begin
FTargetType := ReadByte(AStream);
case FTargetType of
0, 1: FTypeParameterTarget := ReadByte(AStream);
$10: FSupertypeTarget := ReadWord(AStream);
$11, $12:
begin
FTypeParameterBoundTarget.TypeParameterIndex := ReadByte(AStream);
FTypeParameterBoundTarget.BoundIndex := ReadByte(AStream);
end;
$16: FMethodFormalParameterTarget := ReadByte(AStream);
$17: FThrowsTarget := ReadWord(AStream);
$40, $41:
begin
SetLength(FLocalvarTarget, ReadWord(AStream));
for i := 0 to High(FLocalvarTarget) do
begin
FLocalvarTarget[i].StartPC := ReadWord(AStream);
FLocalvarTarget[i].Length := ReadWord(AStream);
FLocalvarTarget[i].Index := ReadWord(AStream);
end;
end;
$42: FCatchTarget := ReadWord(AStream);
$43, $44, $45, $46: FOffsetTarget := ReadWord(AStream);
$47, $48, $49, $4A, $4B:
begin
FTypeArgumentTarget.Offset := ReadWord(AStream);
FTypeArgumentTarget.TypeArguementIndex := ReadByte(AStream);
end;
end;
end;
{ TJClassAnnotation }
procedure TJClassAnnotation.BuildDebugInfo(AIndent: string; AOutput: TStrings);
begin
AOutput.Add('%sType: %d', [AIndent, FTypeIndex]);
AOutput.Add('%sPairs', [AIndent]);
AOutput.Add('%s Count: %d', [AIndent, Length(FElementValuePairs)]);
AOutput.Add('not supported (ElementValuePairs)');
end;
destructor TJClassAnnotation.Destroy;
var
i: integer;
begin
for i := 0 to Length(FElementValuePairs) - 1 do
FElementValuePairs[i].ElementValue.Free;
inherited Destroy;
end;
procedure TJClassAnnotation.LoadFromStream(AStream: TStream);
var
i: integer;
begin
FTypeIndex := ReadWord(AStream);
SetLength(FElementValuePairs, ReadWord(AStream));
for i := 0 to High(FElementValuePairs) do
begin
FElementValuePairs[i].ElementNameIndex := ReadWord(AStream);
FElementValuePairs[i].ElementValue := TJClassElementValue.Create;
FElementValuePairs[i].ElementValue.LoadFromStream(AStream);
end;
end;
{ TJClassElementValue }
procedure TJClassElementValue.BuildDebugInfo(AIndent: string; AOutput: TStrings);
begin
AOutput.Add('not supported (TJClassElementValue)');
end;
destructor TJClassElementValue.Destroy;
var
i: integer;
begin
if Assigned(FArrayValue) then
begin
for i := 0 to FArrayValue.Count - 1 do
TJClassElementValue(FArrayValue[i]).Free;
FArrayValue.Free;
end;
FAnnotation.Free;
inherited Destroy;
end;
procedure TJClassElementValue.LoadFromStream(AStream: TStream);
var
buf: UInt16;
i: integer;
elementValue: TJClassElementValue;
begin
FTag := ReadByte(AStream);
case char(FTag) of
'e':
begin
FFirstIndex := ReadWord(AStream);
FSecondIndex := ReadWord(AStream);
end;
'@':
begin
FAnnotation := TJClassAnnotation.Create;
FAnnotation.LoadFromStream(AStream);
end;
'[':
begin
buf := ReadWord(AStream);
FArrayValue := TList.Create;
for i := 0 to buf - 1 do
begin
elementValue := TJClassElementValue.Create;
try
elementValue.LoadFromStream(AStream);
FArrayValue.Add(elementValue);
except
elementValue.Free;
raise;
end;
end;
end
else
FFirstIndex := ReadWord(AStream);
end;
end;
end.
|
unit MainForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TForm1 = class(TForm)
GetSumButton: TButton;
aField: TEdit;
bField: TEdit;
ResultLabel: TLabel;
procedure GetSumButtonClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
paramA, paramB: Integer;
flag:boolean;
implementation
{$R *.dfm}
procedure TForm1.GetSumButtonClick(Sender: TObject);
begin
flag := true;
if not TryStrToInt(aField.Text, paramA) then
begin
ResultLabel.Caption := 'Field A does not contain int value';
flag := false;
end;
if not TryStrToInt(bField.Text, paramB) then
begin
ResultLabel.Caption := 'Field B does not contain int value';
flag := false;
end;
if(flag=true) then
ResultLabel.Caption := (paramA + paramB).ToString();
end;
end.
|
unit Main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, xmldom, XMLIntf, msxmldom, XMLDoc, Grids, ValEdit,
System.Zip;
type
TMainFrm = class(TForm)
Button1: TButton;
Memo1: TMemo;
OpenDialog1: TOpenDialog;
ValueListEditor1: TValueListEditor;
XMLDocument1: TXMLDocument;
XMLDocument2: TXMLDocument;
procedure Button1Click(Sender: TObject);
private
procedure ReadProperties(ZipFile: TZipFile; const Arquivo: String);
{ Private declarations }
public
{ Public declarations }
end;
var
MainFrm: TMainFrm;
implementation
{$R *.dfm}
procedure TMainFrm.ReadProperties(ZipFile: TZipFile; const Arquivo: String);
var
ZipStream: TStream;
i: Integer;
XmlNode: IXMLNode;
LocalHeader: TZipHeader;
begin
ZipFile.Read(Arquivo, ZipStream, LocalHeader);
try
ZipStream.Position := 0;
XMLDocument2.LoadFromStream(ZipStream);
// Read properties
for i := 0 to XMLDocument2.DocumentElement.ChildNodes.Count - 1 do begin
XmlNode := XMLDocument2.DocumentElement.ChildNodes.Nodes[i];
try
// Found new property - add
ValueListEditor1.InsertRow(XmlNode.NodeName, XmlNode.NodeValue, True);
except
// Property is not a single value - ignore
On EXMLDocError do;
// Property is null - add null value
On EVariantTypeCastError do
ValueListEditor1.InsertRow(XmlNode.NodeName, '', True);
end;
end;
finally
ZipStream.Free;
end;
end;
procedure TMainFrm.Button1Click(Sender: TObject);
var
ZipStream: TStream;
XmlNode: IXMLNode;
i: Integer;
AttType: String;
ZipFile: TZipFile;
LocalHeader: TZipHeader;
begin
if OpenDialog1.Execute then
begin
ZipFile := TZipFile.Create();
try
ZipFile.Open(OpenDialog1.FileName, TZipMode.zmRead);
// Read Relations
ZipFile.Read('_rels/.rels', ZipStream, LocalHeader);
try
ZipStream.Position := 0;
XMLDocument1.LoadFromStream(ZipStream);
Memo1.Text := XMLDoc.FormatXMLData(XMLDocument1.XML.Text);
ValueListEditor1.Strings.Clear;
// Process nodes
for i := 0 to XMLDocument1.DocumentElement.ChildNodes.Count - 1 do begin
XmlNode := XMLDocument1.DocumentElement.ChildNodes.Nodes[i];
// Get kind of relation
// It's the final part of the Type attribute
AttType := ExtractFileName(XmlNode.Attributes['Type']);
if AttType.EndsWith('core-properties') or
AttType.EndsWith('extended-properties') then
// Add properties to ValueListEditor
ReadProperties(ZipFile, XmlNode.Attributes['Target']);
end;
finally
ZipStream.Free;
end;
finally
ZipFile.Close();
ZipFile.Free;
end;
end;
end;
end.
|
unit wizard;
interface
uses Controls, Classes, Forms;
type
TWizard = class;
IWizardPage = interface;
// Simula una interface (amb interfaces peta),
// que podrÓ cridar la pÓgina per comunicarse amb el wizard
TWizardMethods = class
private
wizard: TWizard;
constructor Create(wizard: TWizard);
public
procedure NextPage;
procedure PreviousPage;
procedure FirstPage;
procedure LastPage;
procedure Close;
function getPreviousPage: TForm;
procedure AddWizardPage(const page: IWizardPage);
procedure GotoPage(const page: IWizardPage);
function getPage(const index: integer): TForm;
end;
// Simula una interface que ha d'implementar la pÓgina
IWizardPage = interface
procedure setWizardMethods(const wizardMethods: TWizardMethods);
function getForm: TForm;
end;
TOnCloseEvent = procedure of object;
TWizard = class(TObject)
private
wizardMethods: TWizardMethods;
pages: TInterfaceList;
position: integer;
FContainer: TWinControl;
FOnClose: TOnCloseEvent;
procedure CleanContainer;
function getForm(const pageNumber: integer): TForm;
procedure ShowPage(const pageNumber: integer);
public
destructor Destroy; override;
constructor Create(const Container: TWinControl); reintroduce;
procedure NextPage;
procedure PreviousPage;
procedure FirstPage;
procedure LastPage;
function getPreviousPage: TForm;
procedure AddWizardPage(const page: IWizardPage);
procedure GotoPage(const page: IWizardPage);
procedure CanClose(var CanClose: boolean);
property OnClose: TOnCloseEvent read FOnClose write FOnClose;
end;
implementation
{ TWizard }
procedure TWizard.AddWizardPage(const page: IWizardPage);
begin
pages.Add(page);
page.setWizardMethods(wizardMethods);
end;
procedure TWizard.CanClose(var CanClose: boolean);
var form: TForm;
begin
form := getForm(position);
if Assigned(form.OnCloseQuery) then
form.OnCloseQuery(Self, CanClose);
end;
procedure TWizard.CleanContainer;
begin
if FContainer.ControlCount > 0 then
FContainer.RemoveControl(FContainer.Controls[0]);
end;
constructor TWizard.Create(const Container: TWinControl);
begin
inherited Create;
pages := TInterfaceList.Create;
wizardMethods := TWizardMethods.Create(Self);
position := 0;
FContainer := Container;
end;
destructor TWizard.Destroy;
begin
wizardMethods.Free;
pages.Free;
inherited;
end;
procedure TWizard.FirstPage;
begin
ShowPage(0);
end;
function TWizard.getForm(const pageNumber: integer): TForm;
begin
result := IWizardPage(pages[pageNumber]).getForm;
end;
function TWizard.getPreviousPage: TForm;
begin
if position > 0 then begin
result := getForm(position - 1);
end
else
result := nil;
end;
procedure TWizard.GotoPage(const page: IWizardPage);
var i: integer;
begin
for i := 0 to pages.Count - 1 do begin
if IWizardPage(pages[i]).getForm = page.getForm then begin
position := i;
ShowPage(position);
exit;
end;
end;
end;
procedure TWizard.LastPage;
begin
ShowPage(pages.Count - 1);
end;
procedure TWizard.NextPage;
begin
if position < pages.Count - 1 then begin
inc(position);
ShowPage(position);
end;
end;
procedure TWizard.PreviousPage;
begin
if position > 0 then begin
dec(position);
ShowPage(position);
end;
end;
procedure TWizard.ShowPage(const pageNumber: integer);
var form: TForm;
begin
form := getForm(pageNumber);
CleanContainer;
form.Parent := FContainer;
form.BorderStyle := bsNone;
form.Align := alClient;
form.Show;
end;
{ TWizardMethods }
procedure TWizardMethods.AddWizardPage(const page: IWizardPage);
begin
wizard.AddWizardPage(page);
end;
procedure TWizardMethods.Close;
begin
if Assigned(wizard.FOnClose) then
wizard.FOnClose;
end;
constructor TWizardMethods.Create(wizard: TWizard);
begin
Self.wizard := wizard;
end;
procedure TWizardMethods.FirstPage;
begin
wizard.FirstPage;
end;
function TWizardMethods.getPage(const index: integer): TForm;
begin
result := wizard.getForm(index);
end;
function TWizardMethods.getPreviousPage: TForm;
begin
result := wizard.getPreviousPage;
end;
procedure TWizardMethods.GotoPage(const page: IWizardPage);
begin
wizard.GotoPage(page);
end;
procedure TWizardMethods.LastPage;
begin
wizard.LastPage;
end;
procedure TWizardMethods.NextPage;
begin
wizard.NextPage;
end;
procedure TWizardMethods.PreviousPage;
begin
wizard.PreviousPage;
end;
end.
|
unit AqDrop.DB.MSSQL;
interface
uses
AqDrop.DB.Adapter,
AqDrop.DB.SQL.Intf;
type
TAqDBMSSQLSQLSolver = class(TAqDBSQLSolver)
strict protected
function SolveLimit(pSelect: IAqDBSQLSelect): string; override;
function SolveOffset(pSelect: IAqDBSQLSelect): string; override;
public
function SolveSelect(pSelect: IAqDBSQLSelect): string; override;
function GetAutoIncrementQuery(const pGeneratorName: string): string; override;
end;
implementation
uses
System.SysUtils,
AqDrop.Core.Helpers;
{ TAqDBMSSQLSQLSolver }
function TAqDBMSSQLSQLSolver.GetAutoIncrementQuery(const pGeneratorName: string): string;
begin
Result := 'select @@identity';
end;
function TAqDBMSSQLSQLSolver.SolveLimit(pSelect: IAqDBSQLSelect): string;
begin
if pSelect.IsLimitDefined then
begin
Result := 'top ' + pSelect.Limit.ToString + ' ';
end else begin
Result := '';
end;
end;
function TAqDBMSSQLSQLSolver.SolveOffset(pSelect: IAqDBSQLSelect): string;
begin
if pSelect.IsOffsetDefined then
begin
Result := ' offset ' + pSelect.Offset.ToString + ' rows';
if pSelect.IsLimitDefined then
begin
Result := Result + ' fetch ' + pSelect.Limit.ToString + ' rows only';
end;
end else begin
Result := '';
end;
end;
function TAqDBMSSQLSQLSolver.SolveSelect(pSelect: IAqDBSQLSelect): string;
begin
if pSelect.IsOffsetDefined then
begin
Result := 'select ' + SolveSelectBody(pSelect) + SolveOffset(pSelect);
end else begin
Result := 'select ' + SolveLimit(pSelect) + SolveSelectBody(pSelect);
end;
end;
end.
|
unit UntPrincipal;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Layouts,
FMX.Objects, FMX.TabControl, FMX.Effects, FMX.Controls.Presentation,
FMX.StdCtrls, UntCadCli, System.Actions, FMX.ActnList;
type
TfrmPrincipal = class(TForm)
imgSuperior: TImage;
tbctrlPrincipal: TTabControl;
tbitemMenu: TTabItem;
tbitemAuxiliar: TTabItem;
lytInferior: TLayout;
recInferior: TRectangle;
imgInferior: TImage;
grdMenu: TGridLayout;
lytBotao1: TLayout;
rndBotao1: TRoundRect;
imgBotao1: TImage;
lytLblBotao1: TLayout;
lblBotao1: TLabel;
lblCapBotao1: TLabel;
ShadowEffect1: TShadowEffect;
lytBotao2: TLayout;
rndBotao2: TRoundRect;
imgBotao2: TImage;
lytCapBotao2: TLayout;
lblBotao2: TLabel;
lblCapBotao2: TLabel;
ShadowEffect2: TShadowEffect;
lytBotao3: TLayout;
RoundRect2: TRoundRect;
imgBotao3: TImage;
lytCapBotao3: TLayout;
lblBotao3: TLabel;
lblCapBotao3: TLabel;
ShadowEffect3: TShadowEffect;
lytBotao4: TLayout;
rndBotao4: TRoundRect;
imgBotao4: TImage;
lytCapBotao4: TLayout;
lblBotao4: TLabel;
lblCapBotao4: TLabel;
ShadowEffect4: TShadowEffect;
imgFundo: TImage;
lytPrincipal: TLayout;
ActionList1: TActionList;
actMudarAba: TChangeTabAction;
procedure FormCreate(Sender: TObject);
procedure imgBotao1Click(Sender: TObject);
private
FActiveForm: TForm;
procedure MostrarForm(AFormClass: TComponentClass);
procedure AjustarLayout;
public
{ Public declarations }
procedure MudarAba(ATabItem: TTabItem; Sender: TObject);
end;
var
frmPrincipal: TfrmPrincipal;
implementation
{$R *.fmx}
{ TForm1 }
procedure TfrmPrincipal.AjustarLayout;
var
iWidth : Integer;
begin
iWidth := Self.ClientWidth - 20;
grdMenu.ItemWidth := iWidth;
end;
procedure TfrmPrincipal.FormCreate(Sender: TObject);
begin
tbctrlPrincipal.TabPosition := TTabPosition.None;
tbctrlPrincipal.ActiveTab := tbitemMenu;
AjustarLayout;
end;
procedure TfrmPrincipal.imgBotao1Click(Sender: TObject);
begin
MostrarForm(TfrmCadCli);
MudarAba(tbitemAuxiliar, Sender);
end;
procedure TfrmPrincipal.MostrarForm(AFormClass: TComponentClass);
var
LayoutBase : TComponent;
BotaoMenu : TComponent;
begin
if Assigned(FActiveForm) then
begin
if FActiveForm.ClassType = AFormClass then
exit
else
begin
FActiveForm.DisposeOf;
FActiveForm := nil;
end;
end;
Application.CreateForm(aFormClass, FActiveForm);
LayoutBase := FActiveForm.FindComponent('lytBase');
if Assigned(LayoutBase) then
lytPrincipal.AddObject(TLayout(LayoutBase));
end;
procedure TfrmPrincipal.MudarAba(ATabItem: TTabItem; Sender: TObject);
begin
actMudarAba.Tab := ATabItem;
actMudarAba.ExecuteTarget(Sender);
end;
end.
|
unit uUsuario;
interface
type
IUsuario = Interface
['{DAE5DD24-E58D-49BA-B7DB-BA91CD56E204}']
function GetCodigo: Integer;
procedure SetCodigo(Cod: Integer);
function GetLogin: String;
procedure SetLogin(Login: String);
function GetSenha: String;
procedure SetSenha(Senha: String);
function GetNome: String;
procedure SetNome(Nome: String);
function GetAdministrador: Integer;
procedure SetAdministrador(Admin: Integer);
property Codigo: Integer read GetCodigo write SetCodigo;
property Login: String read GetLogin write SetLogin;
property Senha: String read GetSenha write SetSenha;
property Nome: String read GetNome write SetNome;
property Administrador: Integer read GetAdministrador write SetAdministrador;
end;
TUsuario = class(TInterfacedObject, IUsuario)
private
FCodigo: Integer;
FLogin: String;
FSenha: String;
FNome: String;
FAdministrador: Integer;
protected
{ protected declarations }
public
function GetCodigo: Integer;
procedure SetCodigo(Cod: Integer);
function GetLogin: String;
procedure SetLogin(Login: String);
function GetSenha: String;
procedure SetSenha(Senha: String);
function GetNome: String;
procedure SetNome(Nome: String);
function GetAdministrador: Integer;
procedure SetAdministrador(Admin: Integer);
end;
implementation
{ TUsuario }
function TUsuario.GetCodigo: Integer;
begin
Result := FCodigo;
end;
function TUsuario.GetLogin: String;
begin
Result := FLogin;
end;
function TUsuario.GetNome: String;
begin
Result := FNome;
end;
function TUsuario.GetSenha: String;
begin
Result := FSenha;
end;
function TUsuario.GetAdministrador: Integer;
begin
Result := FAdministrador;
end;
procedure TUsuario.SetCodigo(Cod: Integer);
begin
FCodigo := Cod;
end;
procedure TUsuario.SetLogin(Login: String);
begin
FLogin := Login;
end;
procedure TUsuario.SetNome(Nome: String);
begin
FNome := Nome;
end;
procedure TUsuario.SetSenha(Senha: String);
begin
FSenha := Senha;
end;
procedure TUsuario.SetAdministrador(Admin: Integer);
begin
FAdministrador := Admin;
end;
end.
|
unit ufrm_servidor;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
System.Actions,
System.ImageList,
Vcl.Menus,
Vcl.ActnList,
Vcl.ImgList,
Vcl.Mask,
Vcl.DBCtrls,
Vcl.Grids,
Vcl.DBGrids,
Vcl.StdCtrls,
Vcl.ExtCtrls,
Vcl.ComCtrls,
Vcl.ToolWin,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Data.DB,
FireDAC.Stan.Intf,
FireDAC.Stan.Option,
FireDAC.Stan.Param,
FireDAC.Stan.Error,
FireDAC.DatS,
FireDAC.Phys.Intf,
FireDAC.DApt.Intf,
FireDAC.DApt,
FireDAC.Comp.Client,
FireDAC.Comp.DataSet,
ACBrBase,
ACBrEnterTab,
uDWAbout,
uRESTDWPoolerDB,
uDWConstsData,
ufrm_form_default,
ufrm_dm;
type
Tfrm_servidor = class(Tfrm_form_default)
clientSQLsrv_codigo: TStringField;
clientSQLusuario_usr_codigo: TStringField;
clientSQLsrv_id: TLongWordField;
clientSQLsrv_nome: TStringField;
clientSQLsrv_status: TShortintField;
clientSQLsrv_data_deletado: TDateTimeField;
clientSQLsrv_data_registro: TDateTimeField;
dbedt_srv_nome: TDBEdit;
Label3: TLabel;
dbedt_srv_ssh_endereco: TDBEdit;
Label4: TLabel;
dbedt_srv_ssh_porta: TDBEdit;
Label5: TLabel;
dbedt_srv_ssh_usuario: TDBEdit;
Label6: TLabel;
dbedt_srv_ssh_senha: TDBEdit;
Label7: TLabel;
dbchkbox_srv_status: TDBCheckBox;
clientSQLsrv_ssh_endereco: TStringField;
clientSQLsrv_ssh_porta: TIntegerField;
clientSQLsrv_ssh_usuario: TStringField;
clientSQLsrv_ssh_senha: TStringField;
Bevel1: TBevel;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Action_salvarExecute(Sender: TObject);
procedure FormShow(Sender: TObject);
private
procedure afterInsert;
procedure afterUpdate;
procedure servidor_read(AToken: String);
function valorBoolean(ACheckBox: TDBCheckBox): ShortInt;
public
end;
var
frm_servidor: Tfrm_servidor;
implementation
{$R *.dfm}
procedure Tfrm_servidor.Action_salvarExecute(Sender: TObject);
var
storedProcInsert, storedProcUpdate : TFDStoredProc;
begin
case ds.State of
dsEdit:
try
try
if Application.MessageBox('Ao Salvar as alterações, as informações antigas não poderão ser recuperadas!', 'Deseja Salvar as Alterações?', MB_YESNO + MB_ICONINFORMATION + MB_DEFBUTTON2) = IDYES then begin
storedProcUpdate := TFDStoredProc.Create(Self);
storedProcUpdate.Connection := frm_dm.connDB;
storedProcUpdate.StoredProcName := 'proc_servidor_update';
storedProcUpdate.Prepare;
storedProcUpdate.ParamByName('p_usuario_usr_token').AsString := frm_dm.usuario_usr_token;
storedProcUpdate.ParamByName('p_srv_codigo').AsString := clientSQLsrv_codigo.AsString;
storedProcUpdate.ParamByName('p_srv_nome').AsString := dbedt_srv_nome.Text;
storedProcUpdate.ParamByName('p_srv_ssh_endereco').AsString := dbedt_srv_ssh_endereco.Text;
storedProcUpdate.ParamByName('p_srv_ssh_porta').AsInteger := StrToInt(dbedt_srv_ssh_porta.Text);
storedProcUpdate.ParamByName('p_srv_ssh_usuario').AsString := dbedt_srv_ssh_usuario.Text;
storedProcUpdate.ParamByName('p_srv_ssh_senha').AsString := dbedt_srv_ssh_senha.Text;
storedProcUpdate.ParamByName('p_srv_status').AsShortInt := valorBoolean(dbchkbox_srv_status);
storedProcUpdate.ExecProc;
afterUpdate;
end else begin
ds.DataSet.Cancel;
end;
except on E: Exception do
ShowMessage('Erro Update: ' + E.Message);
end;
finally
end;
dsInsert:
try
try
storedProcInsert := TFDStoredProc.Create(Self);
storedProcInsert.Connection := frm_dm.connDB;
storedProcInsert.StoredProcName := 'proc_servidor_create';
storedProcInsert.Prepare;
storedProcInsert.ParamByName('p_usuario_usr_token').AsString := frm_dm.usuario_usr_token;
storedProcInsert.ParamByName('p_srv_nome').AsString := dbedt_srv_nome.Text;
storedProcInsert.ParamByName('p_srv_ssh_endereco').AsString := dbedt_srv_ssh_endereco.Text;
storedProcInsert.ParamByName('p_srv_ssh_porta').AsInteger := StrToInt(dbedt_srv_ssh_porta.Text);
storedProcInsert.ParamByName('p_srv_ssh_usuario').AsString := dbedt_srv_ssh_usuario.Text;
storedProcInsert.ParamByName('p_srv_ssh_senha').AsString := dbedt_srv_ssh_senha.Text;
storedProcInsert.ParamByName('p_srv_status').AsShortInt := valorBoolean(dbchkbox_srv_status);
storedProcInsert.ExecProc;
afterInsert;
except on E: Exception do
ShowMessage('Error Inserir: ' + E.Message);
end;
finally
end;
end;
end;
procedure Tfrm_servidor.afterInsert;
begin
ShowMessage('Registro Inserido com Sucesso');
servidor_read(frm_dm.usuario_usr_token);
TabSheet_dados.Show;
ds.DataSet.Last;
end;
procedure Tfrm_servidor.afterUpdate;
begin
ds.DataSet.Post;
ShowMessage('Registro Atualizado com sucesso');
TabSheet_dados.Show;
end;
procedure Tfrm_servidor.servidor_read(AToken: String);
var
SQL: String;
begin
SQL := 'call proc_servidor_read('+ QuotedStr(AToken) +');';
clientSQL.Active := False;
clientSQL.DataBase := frm_dm.database;
clientSQL.SQL.Clear;
clientSQL.SQL.Text := SQL;
clientSQL.Active := True
end;
procedure Tfrm_servidor.FormClose(Sender: TObject; var Action: TCloseAction);
begin
inherited;
frm_servidor.Destroy;
frm_servidor := Nil;
end;
procedure Tfrm_servidor.FormShow(Sender: TObject);
begin
inherited;
servidor_read(frm_dm.usuario_usr_token);
end;
function Tfrm_servidor.valorBoolean(ACheckBox: TDBCheckBox): ShortInt;
begin
if ACheckBox.Checked then begin
Result := 1;
end else begin
Result := 0;
end;
end;
end.
|
unit MUIClass.PopString;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, fgl, Math,
Exec, Utility, AmigaDOS, Intuition, agraphics, icon, mui, muihelper,
tagsparamshelper, MUIClass.Base, MUIClass.Group, MUIClass.Area, MUIClass.Gadget;
{$M+}
type
TOpenPopEvent = function(Sender: TObject): Boolean of object;
TClosePopEvent = procedure(Sender: TObject; Success: Boolean) of object;
TMUIPopString = class(TMUIGroup)
private
FToggle: Boolean;
FButton: TMUIArea;
FString: TMUIString;
OpenHook: PHook;
CloseHook: PHook;
FOnOpen: TOpenPopEvent;
FOnClose: TClosePopEvent;
procedure SetToggle(AValue: Boolean);
procedure SetButton(AValue: TMUIArea);
procedure SetString(AValue: TMUIString);
procedure SetOnOpen(AOnOpen: TOpenPopEvent);
procedure SetOnClose(AOnClose: TClosePopEvent);
protected
procedure BeforeCreateObject; override;
procedure GetCreateTags(var ATagList: TATagList); override;
procedure AfterCreateObject; override;
public
constructor Create; override;
destructor Destroy; override;
procedure CreateObject; override;
procedure DestroyObject; override;
procedure ClearObject; override;
// Methods
procedure Open;
procedure Close(Result: Boolean);
// Fields
published
property Toggle: Boolean read FToggle write SetToggle; //
property Button: TMUIArea read FButton write SetButton; //I
property StringObj: TMUIString read FString write SetString; //I
//Events
property OnOpen: TOpenPopEvent read FOnOpen write SetOnOpen;
property OnClose: TClosePopEvent read FOnClose write SetOnClose;
end;
TMUIPopObject = class(TMUIPopString)
private
FFollow: Boolean;
FLight: Boolean;
FObject: TMUIArea;
StrObjHook: PHook;
ObjStrHook: PHook;
FOnStrObj: TOpenPopEvent;
FOnObjStr: TNotifyEvent;
FVolatile: Boolean;
procedure SetFollow(AValue: Boolean);
procedure SetLight(AValue: Boolean);
procedure SetObject(AValue: TMUIArea);
procedure SetOnStrObj(AOnStrObj: TOpenPopEvent);
procedure SetOnObjStr(AValue: TNotifyEvent);
procedure SetVolatile(AValue: Boolean);
protected
procedure BeforeCreateObject; override;
procedure GetCreateTags(var ATagList: TATagList); override;
procedure AfterCreateObject; override;
public
constructor Create; override;
destructor Destroy; override;
procedure CreateObject; override;
procedure DestroyObject; override;
procedure ClearObject; override;
published
property Follow: Boolean read FFollow write SetFollow default True; //
property Light: Boolean read FLight write SetLight default True; //
property PopObject: TMUIArea read FObject write SetObject; //I
property Volatile: Boolean read FVolatile write SetVolatile default True; //
// Events
property OnStrObj: TOpenPopEvent read FOnStrObj write SetOnStrObj;
property OnObjStr: TNotifyEvent read FOnObjStr write SetOnObjStr;
// WindowHook
end;
TMUIPoplist = class(TMUIPopObject)
private
FLArray: TStringArray;
PCs: array of PChar;
procedure SetLArray(AValue: TStringArray);
protected
procedure GetCreateTags(var ATagList: TATagList); override;
public
constructor Create; override;
procedure CreateObject; override;
published
property LArray: TStringArray read FLArray write SetLArray;
end;
TMUIPopASL = class(TMUIPopObject)
private
FASLType: LongWord;
procedure SetASLType(AValue: LongWord);
function GetActive: Boolean;
protected
procedure GetCreateTags(var ATagList: TATagList); override;
public
constructor Create; override;
procedure CreateObject; override;
property Active: Boolean read GetActive;
published
property ASLType: LongWord read FASLType write SetASLType default 0; //I ASL_*Request
// StartHook/StopHook
end;
implementation
{ TMUIPopString }
constructor TMUIPopString.Create;
begin
inherited;
FToggle := False;
FButton := nil;
FString := nil;
OpenHook := nil;
end;
destructor TMUIPopString.Destroy;
begin
if Assigned(FButton) then
FButton.ClearObject;
FButton.Free;
if Assigned(FString) then
FString.ClearObject;
FString.Free;
inherited;
end;
procedure TMUIPopString.BeforeCreateObject;
begin
inherited;
if Assigned(FButton) then
FButton.CreateObject;
if Assigned(FString) then
FString.CreateObject;
end;
procedure TMUIPopString.GetCreateTags(var ATagList: TATagList);
begin
inherited;
if FToggle then
ATagList.AddTag(MUIA_PopString_Toggle, AsTag(FToggle));
if Assigned(FButton) and FButton.HasObj then
ATagList.AddTag(MUIA_PopString_Button, AsTag(FButton.MUIObj));
if Assigned(FString) and FString.HasObj then
ATagList.AddTag(MUIA_PopString_String, AsTag(FString.MUIObj));
if Assigned(OpenHook) then
ATagList.AddTag(MUIA_PopString_OpenHook, AsTag(OpenHook));
if Assigned(CloseHook) then
ATagList.AddTag(MUIA_PopString_CloseHook, AsTag(CloseHook));
end;
procedure TMUIPopString.CreateObject;
var
TagList: TATagList;
begin
if not Assigned(FMUIObj) then
begin
BeforeCreateObject;
GetCreateTags(TagList);
FMUIObj := MUI_NewObjectA(MUIC_PopString, TagList.GetTagPointer);
AfterCreateObject
end;
end;
procedure TMUIPopString.AfterCreateObject;
var
Obj: PObject_;
begin
inherited;
if not Assigned(FButton) then
begin
Obj := GetPointerValue(MUIA_PopString_Button);
if Assigned(Obj) then
begin
FButton := TMUIArea.Create;
FButton.MUIObj := Obj;
end;
end;
if not Assigned(FString) then
begin
Obj := GetPointerValue(MUIA_PopString_String);
if Assigned(Obj) then
begin
FString := TMUIString.Create;
FString.MUIObj := Obj;
end;
end;
end;
procedure TMUIPopString.DestroyObject;
begin
inherited;
if Assigned(FButton) then
FButton.ClearObject;
if Assigned(FString) then
FString.ClearObject;
end;
procedure TMUIPopString.ClearObject;
begin
inherited;
if Assigned(FButton) then
FButton.ClearObject;
if Assigned(FString) then
FString.ClearObject;
end;
procedure TMUIPopString.SetToggle(AValue: Boolean);
begin
if AValue <> FToggle then
begin
FToggle := AValue;
if HasObj then
SetValue(MUIA_PopString_Toggle, FToggle);
end;
end;
procedure TMUIPopString.SetButton(AValue: TMUIArea);
begin
if AValue <> FButton then
begin
if Assigned(FMUIObj) then
ComplainIOnly(Self, 'MUIA_PopString_Button', HexStr(AValue))
else
FButton := AValue;
end;
end;
procedure TMUIPopString.SetString(AValue: TMUIString);
begin
if AValue <> FString then
begin
if Assigned(FMUIObj) then
ComplainIOnly(Self, 'MUIA_PopString_String', HexStr(AValue))
else
FString := AValue;
end;
end;
procedure TMUIPopString.Open;
begin
if HasObj then
DoMethod(MUIObj, [MUIM_PopString_Open]);
end;
procedure TMUIPopString.Close(Result: Boolean);
begin
if HasObj then
DoMethod(MUIObj, [MUIM_PopString_Close, AsTag(Result)]);
end;
function OpenFunc(Hook: PHook; Obj: PObject_; Msg: Pointer): PtrInt;
var
PasObj: TMUIPopString;
begin
try
Result := AsTag(False);
PasObj := TMUIPopString(Hook^.h_Data);
if Assigned(PasObj.FOnOpen) then
Result := AsTag(PasObj.FOnOpen(PasObj));
except
on E: Exception do
MUIApp.DoException(E);
end;
end;
procedure TMUIPopString.SetOnOpen(AOnOpen: TOpenPopEvent);
begin
if AOnOpen <> FOnOpen then
begin
FOnOpen := AOnOpen;
if Assigned(FOnOpen) then
begin
if not Assigned(OpenHook) then
OpenHook := HookList.GetNewHook;
MH_SetHook(OpenHook^, @OpenFunc, Self);
if HasObj then
SetValue(MUIA_PopString_OpenHook, AsTag(OpenHook));
end;
end;
end;
function CloseFunc(Hook: PHook; Obj: PObject_; Msg: Pointer): PtrInt;
type
TCloseMsg = record
S: PObject_;
Res: Integer;
end;
var
CMsg: ^TCloseMsg;
PasObj: TMUIPopString;
begin
try
Result := 0;
PasObj := TMUIPopString(Hook^.h_Data);
if Assigned(PasObj.FOnClose) then
begin
CMsg := Msg;
PasObj.FOnClose(PasObj, CMsg^.Res <> 0);
end;
except
on E: Exception do
MUIApp.DoException(E);
end;
end;
procedure TMUIPopString.SetOnClose(AOnClose: TClosePopEvent);
begin
if AOnClose <> FOnClose then
begin
FOnClose := AOnClose;
if Assigned(FOnClose) then
begin
if not Assigned(CloseHook) then
CloseHook := HookList.GetNewHook;
MH_SetHook(CloseHook^, @CloseFunc, Self);
if HasObj then
SetValue(MUIA_PopString_CloseHook, AsTag(CloseHook));
end;
end;
end;
{ TMUIPoplist }
constructor TMUIPoplist.Create;
begin
inherited;
SetLength(FLArray, 0);
end;
procedure TMUIPoplist.GetCreateTags(var ATagList: TATagList);
var
I: Integer;
begin
inherited;
if Length(FLArray) > 0 then
begin
SetLength(PCs, Length(FLArray) + 1);
for i := 0 to High(FLArray) do
PCs[i] := PChar(FLArray[i]);
PCs[High(PCs)] := nil;
ATagList.AddTag(MUIA_Poplist_Array, AsTag(@(PCs[0])));
end;
end;
procedure TMUIPoplist.CreateObject;
var
TagList: TATagList;
begin
if not Assigned(FMUIObj) then
begin
BeforeCreateObject;
GetCreateTags(TagList);
FMUIObj := MUI_NewObjectA(MUIC_Poplist, TagList.GetTagPointer);
AfterCreateObject
end;
end;
procedure TMUIPoplist.SetLArray(AValue: TStringArray);
begin
if Assigned(FMUIObj) then
ComplainIOnly(Self, 'MUIA_Poplist_Array', '<string array>')
else
FLArray := Copy(AValue);
end;
{ TMUIPopObject }
constructor TMUIPopObject.Create;
begin
inherited;
FFollow := True;
FLight := True;
FObject := nil;
StrObjHook := nil;
ObjStrHook := nil;
FVolatile := True;
end;
destructor TMUIPopObject.Destroy;
begin
if Assigned(FObject) then
FObject.ClearObject;
FObject.Free;
inherited;
end;
procedure TMUIPopObject.BeforeCreateObject;
begin
inherited;
if Assigned(FObject) then
FObject.CreateObject;
end;
procedure TMUIPopObject.GetCreateTags(var ATagList: TATagList);
begin
inherited;
if not FFollow then
ATagList.AddTag(MUIA_PopObject_Follow, AsTag(FFollow));
if not FLight then
ATagList.AddTag(MUIA_PopObject_Light, AsTag(FLight));
if Assigned(FObject) and FObject.HasObj then
ATagList.AddTag(MUIA_PopObject_Object, AsTag(FObject.MUIObj));
if Assigned(StrObjHook) then
ATagList.AddTag(MUIA_PopObject_StrObjHook, AsTag(StrObjHook));
if Assigned(ObjStrHook) then
ATagList.AddTag(MUIA_PopObject_ObjStrHook, AsTag(ObjStrHook));
if not FVolatile then
ATagList.AddTag(MUIA_PopObject_Volatile, AsTag(FVolatile));
end;
procedure TMUIPopObject.CreateObject;
var
TagList: TATagList;
begin
if not Assigned(FMUIObj) then
begin
BeforeCreateObject;
GetCreateTags(TagList);
FMUIObj := MUI_NewObjectA(MUIC_PopObject, TagList.GetTagPointer);
AfterCreateObject
end;
end;
procedure TMUIPopObject.AfterCreateObject;
var
Obj: PObject_;
begin
inherited;
if not Assigned(FObject) then
begin
Obj := GetPointerValue(MUIA_PopObject_Object);
if Assigned(Obj) then
begin
FObject := TMUIArea.Create;
FObject.MUIObj := Obj;
end;
end;
end;
procedure TMUIPopObject.DestroyObject;
begin
inherited;
if Assigned(FObject) then
FObject.ClearObject;
end;
procedure TMUIPopObject.ClearObject;
begin
inherited;
if Assigned(FObject) then
FObject.ClearObject;
end;
procedure TMUIPopObject.SetFollow(AValue: Boolean);
begin
if FFollow <> AValue then
begin
FFollow := AValue;
if HasObj then
SetValue(MUIA_PopObject_Follow, AsTag(FFollow));
end;
end;
procedure TMUIPopObject.SetLight(AValue: Boolean);
begin
if FLight <> AValue then
begin
FLight := AValue;
if HasObj then
SetValue(MUIA_PopObject_Light, AsTag(FLight));
end;
end;
procedure TMUIPopObject.SetObject(AValue: TMUIArea);
begin
if AValue <> FObject then
begin
if Assigned(FMUIObj) then
ComplainIOnly(Self, 'MUIA_PopObject_Object', HexStr(AValue))
else
FObject := AValue;
end;
end;
function StrObjFunc(Hook: PHook; Obj: PObject_; Msg: Pointer): PtrInt;
var
PasObj: TMUIPopObject;
begin
try
Result := AsTag(False);
PasObj := TMUIPopObject(Hook^.h_Data);
if Assigned(PasObj.FOnStrObj) then
Result := AsTag(PasObj.FOnStrObj(PasObj));
except
on E: Exception do
MUIApp.DoException(E);
end;
end;
function ObjStrFunc(Hook: PHook; Obj: PObject_; Msg: Pointer): PtrInt;
var
PasObj: TMUIPopObject;
begin
try
Result := 0;
PasObj := TMUIPopObject(Hook^.h_Data);
if Assigned(PasObj.FOnObjStr) then
PasObj.FOnObjStr(PasObj);
except
on E: Exception do
MUIApp.DoException(E);
end;
end;
procedure TMUIPopObject.SetOnStrObj(AOnStrObj: TOpenPopEvent);
begin
if AOnStrObj <> FOnStrObj then
begin
FOnStrObj := AOnStrObj;
if Assigned(FOnStrObj) then
begin
if not Assigned(StrObjHook) then
StrObjHook := HookList.GetNewHook;
MH_SetHook(StrObjHook^, @StrObjFunc, Self);
if HasObj then
SetValue(MUIA_PopObject_StrObjHook, AsTag(StrObjHook));
end;
end;
end;
procedure TMUIPopObject.SetOnObjStr(AValue: TNotifyEvent);
begin
if AValue <> FOnObjStr then
begin
FOnObjStr := AValue;
if Assigned(FOnObjStr) then
begin
if not Assigned(ObjStrHook) then
ObjStrHook := HookList.GetNewHook;
MH_SetHook(ObjStrHook^, @ObjStrFunc, Self);
if HasObj then
SetValue(MUIA_PopObject_ObjStrHook, AsTag(ObjStrHook));
end;
end;
end;
procedure TMUIPopObject.SetVolatile(AValue: Boolean);
begin
if FVolatile <> AValue then
begin
FVolatile := AValue;
if HasObj then
SetValue(MUIA_PopObject_Volatile, AsTag(FVolatile));
end;
end;
{ TMUIPopASL }
constructor TMUIPopASL.Create;
begin
inherited;
FASLType := 0;
end;
procedure TMUIPopASL.GetCreateTags(var ATagList: TATagList);
begin
inherited;
if FASLType <> 0 then
ATagList.AddTag(MUIA_PopASL_Type, AsTag(FASLType));
end;
procedure TMUIPopASL.CreateObject;
var
TagList: TATagList;
begin
if not Assigned(FMUIObj) then
begin
BeforeCreateObject;
GetCreateTags(TagList);
FMUIObj := MUI_NewObjectA(MUIC_PopASL, TagList.GetTagPointer);
AfterCreateObject
end;
end;
function TMUIPopASL.GetActive: Boolean;
begin
Result := False;
if HasObj then
Result := GetBoolValue(MUIA_PopASL_Active);
end;
procedure TMUIPopASL.SetASLType(AValue: LongWord);
begin
if Assigned(FMUIObj) then
ComplainIOnly(Self, 'MUIA_PopASL_Type', IntToStr(AValue))
else
FASLType := AValue;
end;
end.
|
{***********************************************************************
TALWebSocketClient is a ancestor of class like TALWinHTTPWebSocketClient
***********************************************************************}
unit Alcinoe.WebSocket.Client;
interface
uses
system.Classes,
Alcinoe.HTTP.Client;
type
{---------------------------------------------------------}
EALWebSocketClientException = class(EALHTTPClientException)
end;
{--------------------------------------------------------------------------------------------------------------------}
TALWebSocketClientReceiveEvent = procedure(sender: Tobject; const Data: AnsiString; const IsUTF8: Boolean) of object;
TALWebSocketClientErrorEvent = procedure(sender: Tobject; const &Message: AnsiString) of object;
{---------------------------------}
TALWebSocketClient = class(TObject)
private
FProxyParams: TALHttpClientProxyParams;
FRequestHeader: TALHTTPRequestHeader;
FProtocolVersion: TALHTTPProtocolVersion;
FUserName: AnsiString;
FPassword: AnsiString;
FConnectTimeout: Integer;
FSendTimeout: Integer;
FReceiveTimeout: Integer;
FOnReceive: TALWebSocketClientReceiveEvent;
fOnError: TALWebSocketClientErrorEvent;
FOnConnected: TNotifyEvent;
FOnDisconnected: TNotifyEvent;
FBufferSize: cardinal;
FAutoReconnect: Boolean;
protected
procedure SetUsername(const NameValue: AnsiString); virtual;
procedure SetPassword(const PasswordValue: AnsiString); virtual;
procedure OnProxyParamsChange(sender: Tobject; Const PropertyIndex: Integer); virtual;
procedure SetBufferSize(const Value: Cardinal); virtual;
procedure SetOnReceive(const Value: TALWebSocketClientReceiveEvent); virtual;
procedure SetOnError(const Value: TALWebSocketClientErrorEvent); virtual;
public
constructor Create; virtual;
destructor Destroy; override;
//-----
procedure Connect(const aUrl:AnsiString); virtual; abstract;
procedure Disconnect; virtual; abstract;
procedure Send(
const aData: AnsiString;
const aIsUTF8: Boolean = True); virtual; abstract;
//-----
property ConnectTimeout: Integer read FConnectTimeout write FConnectTimeout default 0;
property SendTimeout: Integer read FSendTimeout write FSendTimeout default 0;
property ReceiveTimeout: Integer read FReceiveTimeout write FReceiveTimeout default 0;
property BufferSize: cardinal read FBufferSize write SetBufferSize default $8000;
property ProxyParams: TALHttpClientProxyParams read FProxyParams;
property RequestHeader: TALHTTPRequestHeader read FRequestHeader;
Property ProtocolVersion: TALHTTPProtocolVersion read FProtocolVersion write FProtocolVersion default TALHTTPProtocolVersion.v1_1;
property UserName: AnsiString read FUserName write SetUserName;
property Password: AnsiString read FPassword write SetPassword;
property OnReceive: TALWebSocketClientReceiveEvent read FOnReceive write SetOnReceive;
property OnError: TALWebSocketClientErrorEvent read FOnError write SetOnError;
property AutoReconnect: Boolean read FAutoReconnect write FAutoReconnect;
end;
implementation
uses
Alcinoe.Common;
{************************************}
constructor TALWebSocketClient.Create;
begin
inherited;
FBufferSize := $8000;
FConnectTimeout := 0;
FSendTimeout := 0;
FReceiveTimeout := 0;
FUserName := '';
FPassword := '';
FOnReceive := nil;
FOnError := nil;
FOnConnected := nil;
FOnDisconnected := nil;
FProxyParams := TALHttpClientProxyParams.Create;
FProxyParams.OnChange := OnProxyParamsChange;
FRequestHeader := TALHTTPRequestHeader.Create;
FRequestHeader.UserAgent := 'Mozilla/3.0 (compatible; TALWebSocketClient)';
FProtocolVersion := TALHTTPProtocolVersion.v1_1;
fAutoReconnect := True;
end;
{************************************}
destructor TALWebSocketClient.Destroy;
begin
AlFreeAndNil(FProxyParams);
AlFreeAndNil(FRequestHeader);
inherited;
end;
{****************************************************************}
procedure TALWebSocketClient.SetBufferSize(const Value: Cardinal);
begin
FBufferSize := Value;
end;
{********************************************************************}
procedure TALWebSocketClient.SetUsername(const NameValue: AnsiString);
begin
FUserName := NameValue;
end;
{************************************************************************}
procedure TALWebSocketClient.SetPassword(const PasswordValue: AnsiString);
begin
FPassword := PasswordValue;
end;
{*************************************************************************************}
procedure TALWebSocketClient.SetOnReceive(const Value: TALWebSocketClientReceiveEvent);
begin
FOnReceive := Value;
end;
{*********************************************************************************}
procedure TALWebSocketClient.SetOnError(const Value: TALWebSocketClientErrorEvent);
begin
FOnError := Value;
end;
{**********************************************************************************************}
procedure TALWebSocketClient.OnProxyParamsChange(sender: Tobject; Const PropertyIndex: Integer);
begin
//virtual
end;
end.
|
unit DW.OSLog.Android;
{*******************************************************}
{ }
{ Kastri Free }
{ }
{ DelphiWorlds Cross-Platform Library }
{ }
{*******************************************************}
{$I DW.GlobalDefines.inc}
interface
uses
// DW
DW.OSLog;
type
/// <remarks>
/// DO NOT ADD ANY FMX UNITS TO THESE FUNCTIONS
/// </remarks>
TPlatformOSLog = record
public
class function GetTrace: string; static;
class procedure Log(const ALogType: TLogType; const AMsg: string); static;
class procedure Trace; static;
end;
implementation
uses
// RTL
System.SysUtils,
// Android
Androidapi.JNI.JavaTypes, Androidapi.Log, Androidapi.Helpers,
// DW
DW.Androidapi.JNI.Log;
{ TPlatformOSLog }
class procedure TPlatformOSLog.Log(const ALogType: TLogType; const AMsg: string);
var
LMarshaller: TMarshaller;
LPointer: Pointer;
begin
LPointer := LMarshaller.AsUtf8(AMsg).ToPointer;
case ALogType of
TLogType.Debug:
LOGI(LPointer);
TLogType.Warning:
LOGW(LPointer);
TLogType.Error:
LOGE(LPointer);
end;
end;
class function TPlatformOSLog.GetTrace: string;
begin
Result := JStringToString(TJutil_Log.JavaClass.getStackTraceString(TJException.JavaClass.init));
end;
class procedure TPlatformOSLog.Trace;
begin
Log(TLogType.Debug, GetTrace);
end;
end.
|
unit AbstractCardFormController;
interface
uses
AbstractFormController,
AbstractReferenceFormControllerEvents,
CardFormViewModelMapper,
AbstractCardFormControllerEvents,
Event,
EventHandler,
EventBus,
Forms,
Controls,
CardFormViewModel,
ReferenceFormRecordViewModel,
unCardForm,
SysUtils,
Classes;
type
TCardFormData = class (TFormData)
private
FViewModel: TCardFormViewModel;
procedure SetViewModel(
const Value: TCardFormViewModel);
public
constructor Create(
ViewModel: TCardFormViewModel;
Owner: TComponent;
Parent: TWinControl = nil
);
property ViewModel: TCardFormViewModel
read FViewModel write SetViewModel;
end;
TAbstractCardFormController = class abstract (TAbstractFormController, IEventHandler)
protected
FCardFormViewModelMapper: ICardFormViewModelMapper;
protected
procedure SubscribeOnEvents(EventBus: IEventBus); override;
protected
procedure SubscribeOnFormEvents(Form: TForm); override;
procedure CustomizeForm(Form: TForm; FormData: TFormData); override;
protected
procedure OnCardChangesApplyingRequestedEventHandler(
Sender: TObject;
var ViewModel: TCardFormViewModel;
var Success: Boolean
); virtual;
function IsNewCardFormViewModel(ViewModel: TCardFormViewModel): Boolean; virtual;
function IsCardFormViewModelChanged(
CardForm: TCardForm;
CurrentCardFormViewModel: TCardFormViewModel
): Boolean; virtual;
protected
procedure CreateNewCard(ViewModel: TCardFormViewModel; var Success: Boolean); virtual; abstract;
procedure ModifyCard(ViewModel: TCardFormViewModel; var Success: Boolean); virtual; abstract;
procedure RemoveCard(ViewModel: TCardFormViewModel); virtual; abstract;
function GetCardCreatedEventClass: TCardCreatedEventClass; virtual; abstract;
function GetCardModifiedEventClass: TCardModifiedEventClass; virtual; abstract;
function GetCardRemovedEventClass: TCardRemovedEventClass; virtual; abstract;
function CreateCardCreatedEvent(ViewModel: TCardFormViewModel): TCardCreatedEvent; virtual;
function CreateCardModifiedEvent(ViewModel: TCardFormViewModel): TCardModifiedEvent; virtual;
function CreateCardRemovedEvent(ViewModel: TCardFormViewModel): TCardRemovedEvent; virtual;
protected
function CreateCardFormViewModelForChangingReferenceRecordRequestHandling(
ChangingReferenceRecordRequestedEvent: TChangingReferenceRecordRequestedEvent
): TCardFormViewModel; virtual;
function CreateCardFormViewModelForAddingReferenceRecordRequestHandling(
AddingReferenceRecordRequestedEvent: TAddingReferenceRecordRequestedEvent
): TCardFormViewModel; virtual;
function CreateCardFormViewModelFrom(
ReferenceFormRecordViewModel: TReferenceFormRecordViewModel
): TCardFormViewModel;
protected
function GetAddingReferenceRecordRequestedEventClass: TAddingReferenceRecordRequestedEventClass; virtual; abstract;
function GetChangingReferenceRecordRequestedEventClass: TChangingReferenceRecordRequestedEventClass; virtual; abstract;
function GetRemovingReferenceRecordRequestedEventClass: TRemovingReferenceRecordRequestedEventClass; virtual; abstract;
protected
procedure OnAddingReferenceRecordRequestedEventHandler(
AddingReferenceRecordRequestedEvent: TAddingReferenceRecordRequestedEvent
); virtual;
procedure OnChangingReferenceRecordRequestedEventHandler(
ChangingReferenceRecordRequestedEvent: TChangingReferenceRecordRequestedEvent
); virtual;
procedure OnRemovingReferenceRecordRequestedEventHandler(
RemovingReferenceRecordRequestedEvent: TRemovingReferenceRecordRequestedEvent
); virtual;
protected
procedure OnAfterFormCreated(Form: TForm); override;
public
constructor Create(
CardFormViewModelMapper: ICardFormViewModelMapper;
EventBus: IEventBus
);
destructor Destroy; override;
procedure Handle(Event: TEvent); virtual;
function GetSelf: TObject;
end;
implementation
uses
Variants,
Disposable;
constructor TAbstractCardFormController.Create(
CardFormViewModelMapper: ICardFormViewModelMapper;
EventBus: IEventBus
);
begin
inherited Create(EventBus);
FCardFormViewModelMapper := CardFormViewModelMapper;
end;
function TAbstractCardFormController.CreateCardCreatedEvent(
ViewModel: TCardFormViewModel): TCardCreatedEvent;
begin
Result := GetCardCreatedEventClass.Create(ViewModel);
end;
function TAbstractCardFormController.
CreateCardFormViewModelForAddingReferenceRecordRequestHandling(
AddingReferenceRecordRequestedEvent: TAddingReferenceRecordRequestedEvent
): TCardFormViewModel;
begin
Result := FCardFormViewModelMapper.CreateEmptyCardFormViewModel;
end;
function TAbstractCardFormController.
CreateCardFormViewModelForChangingReferenceRecordRequestHandling(
ChangingReferenceRecordRequestedEvent: TChangingReferenceRecordRequestedEvent
): TCardFormViewModel;
begin
Result :=
CreateCardFormViewModelFrom(
ChangingReferenceRecordRequestedEvent.RecordViewModel
);
end;
function TAbstractCardFormController.CreateCardFormViewModelFrom(
ReferenceFormRecordViewModel: TReferenceFormRecordViewModel): TCardFormViewModel;
begin
Result :=
FCardFormViewModelMapper.MapCardFormViewModelFrom(
ReferenceFormRecordViewModel
);
end;
function TAbstractCardFormController.CreateCardModifiedEvent(
ViewModel: TCardFormViewModel): TCardModifiedEvent;
begin
Result := GetCardModifiedEventClass.Create(ViewModel);
end;
function TAbstractCardFormController.CreateCardRemovedEvent(
ViewModel: TCardFormViewModel): TCardRemovedEvent;
begin
Result := GetCardRemovedEventClass.Create(ViewModel);
end;
procedure TAbstractCardFormController.CustomizeForm(
Form: TForm;
FormData: TFormData
);
var CardForm: TCardForm;
CardFormData: TCardFormData;
begin
if not (FormData is TCardFormData) then
Exit;
CardForm := Form as TCardForm;
CardFormData := FormData as TCardFormData;
CardForm.ViewModel := CardFormData.ViewModel;
end;
destructor TAbstractCardFormController.Destroy;
begin
//ShowInfoMessage(0, ClassName + ' destroyed', 'M');
inherited;
end;
function TAbstractCardFormController.GetSelf: TObject;
begin
Result := Self;
end;
procedure TAbstractCardFormController.Handle(
Event: TEvent);
begin
if Event.ClassType.InheritsFrom(GetAddingReferenceRecordRequestedEventClass)
then begin
OnAddingReferenceRecordRequestedEventHandler(
Event as TAddingReferenceRecordRequestedEvent
);
end
else if Event.ClassType.InheritsFrom(GetChangingReferenceRecordRequestedEventClass)
then begin
OnChangingReferenceRecordRequestedEventHandler(
Event as TChangingReferenceRecordRequestedEvent
);
end
else if Event.ClassType.InheritsFrom(GetRemovingReferenceRecordRequestedEventClass)
then begin
OnRemovingReferenceRecordRequestedEventHandler(
Event as TRemovingReferenceRecordRequestedEvent
);
end;
end;
function TAbstractCardFormController.IsCardFormViewModelChanged(
CardForm: TCardForm;
CurrentCardFormViewModel: TCardFormViewModel
): Boolean;
begin
Result := not CardForm.ViewModel.Equals(CurrentCardFormViewModel);
end;
function TAbstractCardFormController.
IsNewCardFormViewModel(
ViewModel: TCardFormViewModel
): Boolean;
begin
if ViewModel.Id.IsSurrogate then
Result := VarIsNull(ViewModel.Id.Value)
else Result := not ViewModel.Id.ReadOnly;
end;
procedure TAbstractCardFormController.OnAddingReferenceRecordRequestedEventHandler(
AddingReferenceRecordRequestedEvent: TAddingReferenceRecordRequestedEvent);
var CardFormViewModel: TCardFormViewModel;
FreeViewModel: IDisposable;
begin
CardFormViewModel :=
CreateCardFormViewModelForAddingReferenceRecordRequestHandling(
AddingReferenceRecordRequestedEvent
);
FreeViewModel := CardFormViewModel;
ShowFormAsModal(TCardFormData.Create(CardFormViewModel, Application));
end;
procedure TAbstractCardFormController.OnAfterFormCreated(
Form: TForm);
begin
inherited;
end;
procedure TAbstractCardFormController.
OnCardChangesApplyingRequestedEventHandler(
Sender: TObject;
var ViewModel: TCardFormViewModel;
var Success: Boolean
);
var Event: TEvent;
begin
Event := nil;
try
try
Screen.Cursor := crHourGlass;
if IsNewCardFormViewModel(ViewModel) then begin
CreateNewCard(ViewModel, Success);
if Success then
Event := CreateCardCreatedEvent(ViewModel);
end
else if IsCardFormViewModelChanged(TCardForm(Sender), ViewModel)
then begin
ModifyCard(ViewModel, Success);
if Success then
Event := CreateCardModifiedEvent(ViewModel);
end;
finally
Screen.Cursor := crDefault;
end;
if Assigned(Event) then
EventBus.RaiseEvent(Event);
finally
FreeAndNil(Event);
end;
end;
procedure TAbstractCardFormController.
OnChangingReferenceRecordRequestedEventHandler(
ChangingReferenceRecordRequestedEvent: TChangingReferenceRecordRequestedEvent
);
var ViewModel: TCardFormViewModel;
FreeViewModel: IDisposable;
begin
ViewModel :=
CreateCardFormViewModelForChangingReferenceRecordRequestHandling(
ChangingReferenceRecordRequestedEvent
);
FreeViewModel := ViewModel;
if not ViewModel.Id.IsSurrogate then
ViewModel.Id.ReadOnly := True;
ShowFormAsModal(
TCardFormData.Create(ViewModel, Application)
);
end;
procedure TAbstractCardFormController.
OnRemovingReferenceRecordRequestedEventHandler(
RemovingReferenceRecordRequestedEvent: TRemovingReferenceRecordRequestedEvent
);
var CardRemovedEvent: TCardRemovedEvent;
CardFormViewModel: TCardFormViewModel;
FreeCardFormViewModel: IDisposable;
begin
CardFormViewModel :=
CreateCardFormViewModelFrom(
RemovingReferenceRecordRequestedEvent.RecordViewModel
);
FreeCardFormViewModel := CardFormViewModel;
RemoveCard(CardFormViewModel);
CardRemovedEvent := CreateCardRemovedEvent(CardFormViewModel);
try
EventBus.RaiseEvent(CardRemovedEvent);
finally
FreeAndNil(CardRemovedEvent);
end;
end;
procedure TAbstractCardFormController.SubscribeOnEvents(
EventBus: IEventBus);
begin
inherited;
EventBus.RegisterEventHandler(GetAddingReferenceRecordRequestedEventClass, Self);
EventBus.RegisterEventHandler(GetChangingReferenceRecordRequestedEventClass, Self);
EventBus.RegisterEventHandler(GetRemovingReferenceRecordRequestedEventClass, Self);
end;
procedure TAbstractCardFormController.SubscribeOnFormEvents(
Form: TForm);
var CardForm: TCardForm;
begin
inherited;
CardForm := Form as TCardForm;
CardForm.OnCardChangesApplyingRequestedEventHandler :=
OnCardChangesApplyingRequestedEventHandler;
end;
{ TCardFormData }
constructor TCardFormData.Create(ViewModel: TCardFormViewModel;
Owner: TComponent; Parent: TWinControl);
begin
inherited Create(Owner, Parent);
Self.ViewModel := ViewModel;
end;
procedure TCardFormData.SetViewModel(const Value: TCardFormViewModel);
begin
if FViewModel = Value then
Exit;
FreeAndNil(FViewModel);
FViewModel := Value;
end;
end.
|
unit uFramework;
interface
uses
Generics.Collections;
type
TRelatorio = class
public Cabecalho: string;
public Detalhes: TList<string>;
public Rodape: string;
constructor Create();
destructor Destroy(); override;
end;
// Builder (Abstrato)
TRelatorioBuilder = class abstract
protected _relatorio: TRelatorio;
function getRelatorio: TRelatorio;
// processo de construção (abstrato)
public procedure buildCabecalho(); virtual; abstract;
public procedure buildDetalhes(); virtual; abstract;
public procedure buildRodape(); virtual; abstract;
public procedure createNewRelatorioProduct();
end;
// Builder (Concreto)
TRelatorioClientesBuilder = class(TRelatorioBuilder)
public procedure buildCabecalho(); override;
public procedure buildDetalhes(); override;
public procedure buildRodape(); override;
end;
// Builder (Concreto)
TRelatorioProdutosBuilder = class(TRelatorioBuilder)
public procedure buildCabecalho(); override;
public procedure buildDetalhes(); override;
public procedure buildRodape(); override;
end;
{ Director - responsável pelo gerenciamento
da sequência correta de criação do objeto
Recebe um um Concret Builder como parâmetro e
executa as operações necessárias sobre ele }
TGerador = class
private _relatorioBuilder: TRelatorioBuilder;
public procedure setRelatorioBuilder(relatorioBuilder: TRelatorioBuilder);
public function getRelatorio(): TRelatorio;
public procedure constructRelatorio();
end;
implementation
{ RelatorioClientesBuilder }
procedure TRelatorioClientesBuilder.buildCabecalho();
begin
_relatorio.Cabecalho := 'Relatório de Clientes';
end;
procedure TRelatorioClientesBuilder.buildDetalhes();
begin
_relatorio.Detalhes.Add('Jose');
_relatorio.Detalhes.Add('Pedro');
_relatorio.Detalhes.Add('Joao');
end;
procedure TRelatorioClientesBuilder.buildRodape();
begin
_relatorio.Rodape := 'GPauli Cursos e Treinamentos';
end;
{ RelatorioProdutosBuilder }
procedure TRelatorioProdutosBuilder.buildCabecalho();
begin
_relatorio.Cabecalho := 'Relatório de Produtos';
end;
procedure TRelatorioProdutosBuilder.buildDetalhes();
begin
_relatorio.Detalhes.Add('iPhone');
_relatorio.Detalhes.Add('iPad');
_relatorio.Detalhes.Add('iPod');
end;
procedure TRelatorioProdutosBuilder.buildRodape();
begin
_relatorio.Rodape := 'GPauli Cursos e Treinamentos';
end;
{ RelatorioBuilder }
procedure TRelatorioBuilder.createNewRelatorioProduct();
begin
_relatorio := TRelatorio.Create();
end;
function TRelatorioBuilder.getRelatorio(): TRelatorio;
begin
result := _relatorio;
end;
{ Director }
procedure TGerador.constructRelatorio();
begin
_relatorioBuilder.createNewRelatorioProduct();
_relatorioBuilder.buildCabecalho();
_relatorioBuilder.buildDetalhes();
_relatorioBuilder.buildRodape();
end;
function TGerador.getRelatorio(): TRelatorio;
begin
result := _relatorioBuilder.getRelatorio();
end;
procedure TGerador.setRelatorioBuilder(
relatorioBuilder: TRelatorioBuilder);
begin
self._relatorioBuilder := relatorioBuilder;
end;
{ Relatorio }
constructor TRelatorio.Create();
begin
Detalhes := TList<string>.Create();
end;
destructor TRelatorio.Destroy();
begin
Detalhes.Free();
inherited;
end;
end.
|
unit uSoma;
interface
uses
Interfaces,
System.Generics.Collections,
System.SysUtils;
type
{ Classe que implementa a interface de iSoma }
TSoma = class(TInterfacedObject, iSoma)
private
FLista: TList<Double>; { Lista genérica }
FResultado: TEvResultado; { Variável que receberá a procedure que mostrará o resultado }
public
constructor Create;
destructor Destroy; override;
class function New: iSoma;
function add(Value: String): iSoma;
function Resultado(Value: TEvResultado): iSoma;
function Executar: iSoma;
end;
implementation
{ TSoma }
function TSoma.add(Value: String): iSoma;
var
X: Double;
begin
Result := Self;
if not TryStrToFloat(Value, X) then
raise Exception.Create('O Valor é inválido');
FLista.add(X);
end;
constructor TSoma.Create;
begin
FLista := TList<Double>.Create;
end;
destructor TSoma.Destroy;
begin
FreeAndNil(FLista);
inherited;
end;
function TSoma.Executar: iSoma;
var
LResultado: Double;
I : Integer;
begin
Result := Self;
LResultado := 0;
for I := 0 to Pred(FLista.Count) do
LResultado := LResultado + FLista.Items[I];
FResultado(FloatToStr(LResultado));
end;
class function TSoma.New: iSoma;
begin
Result := Self.Create;
end;
function TSoma.Resultado(Value: TEvResultado): iSoma;
begin
Result := Self;
FResultado := Value;
end;
end.
|
unit UDownload;
(* Copyright (c) 2002 Twiddle <hetareprog@hotmail.com> *)
interface
uses
Classes,
SysUtils,
ExtCtrls,
Dialogs,
DateUtils,
U2chCatList,
U2chCat,
U2chBoard,
U2chThread,
UAsync;
type
(*-------------------------------------------------------*)
TDownloadState = (dsFREE, dsDOWNLOAD, dsINTERVAL, dsDRAIN);
TDownloadNotify = procedure(Sender: TObject; thread: TThreadItem) of Object;
TDownloader = class (TStringList)
protected
FOwner: TComponent;
FState: TDownloadState;
FStartTime: TDateTime;
FLimitBytesPerSec: Cardinal;
FSpeedLimiter: TTimer;
FOnNotify: TDownloadNotify;
procedure SetTimer(interval: Cardinal);
procedure FreeTimer;
procedure BeginDownload;
procedure ProcessDownload;
procedure OnTimer(Sender: TObject);
procedure OnEndDownload(thread: TThreadItem);
public
constructor Create(AOwner: TComponent);
destructor Destroy; override;
procedure Add(const URI: string);
procedure Drain;
function IsLimit: boolean;
property OnNotify: TDownloadNotify read FOnNotify write FOnNotify;
end;
(*=======================================================*)
implementation
(*=======================================================*)
{$B-}
uses
Main;
const
LIMIT_BYTES_PER_SEC = (56 div 8 * 1024);
CROWDED_INTERVAL = 3000;
TEST_MAX = 30;
var
counter: Integer = 0;
constructor TDownloader.Create(AOwner: TComponent);
begin
inherited Create;
FOwner := AOwner;
FLimitBytesPerSec := LIMIT_BYTES_PER_SEC;
FStartTime := 0;
FSpeedLimiter := nil;
FOnNotify := nil;
end;
destructor TDownloader.Destroy;
begin
FreeTimer;
inherited;
end;
procedure TDownloader.FreeTimer;
begin
if Assigned(FSpeedLimiter) then
begin
FSpeedLimiter.Free;
FSpeedLimiter := nil;
end;
end;
procedure TDownloader.SetTimer(interval: Cardinal);
begin
FState := dsINTERVAL;
if not Assigned(FSpeedLimiter) then
FSpeedLimiter := TTimer.Create(FOwner);
FSpeedLimiter.OnTimer := OnTimer;
FSpeedLimiter.Interval := interval;
FSpeedLimiter.Enabled := True;
end;
procedure TDownloader.Add(const URI: string);
begin
if 0 <= IndexOf(URI) then
exit;
if IsLimit then
begin
MessageDlg('(°д°)・・・', mtWarning, [mbOK], 0);
exit;
end;
inc(counter);
inherited Add(URI);
{Log('Qニ(・∀・) ' + IntToStr(Count) + 'コ');
StatLog('リミット(・∀・)アト ' + IntToStr(TEST_MAX - counter));}
Log2(32, IntToStr(Count) + 'コ'); //ayaya
StatLog2(33, IntToStr(TEST_MAX - counter)); //ayaya
BeginDownload;
end;
procedure TDownloader.BeginDownload;
var
interval: integer;
currentTime: TDateTime;
begin
if Count <= 0 then
begin
{Log('(・∀・)オワリ');
StatLog('リミット(・∀・)アト ' + IntToStr(TEST_MAX - counter));}
Log2(34, ''); //ayaya
StatLog2(35, IntToStr(TEST_MAX - counter)); //ayaya
exit;
end;
case FState of
dsFREE:;
else
exit;
end;
currentTime := Now;
if FStartTime <= currentTime then
begin
ProcessDownload;
exit;
end;
interval := Trunc((FStartTime - currentTime) * 24 * 60 * 60 * 1000);
SetTimer(interval);
{ayaya}
if useTrace[36] then
Log('アト ' + IntToStr(Count) + traceString[36] + DateTimeToStr(FStartTime));
{//ayaya}
{Log('アト ' + IntToStr(Count) + 'コ(・∀・)ジカイハ ' + DateTimeToStr(FStartTime));}
end;
procedure TDownloader.OnTimer(Sender: TObject);
begin
FreeTimer;
if FState = dsINTERVAL then
begin
FState := dsFREE;
ProcessDownload;
end;
end;
procedure TDownloader.ProcessDownload;
var
URI: string;
board: TBoard;
thread: TThreadItem;
host, bbs, datnum: string;
oldLog: boolean;
index: integer;
begin
if FState <> dsFREE then
exit;
while 0 < Count do
begin
FState := dsDOWNLOAD;
URI := Strings[0];
Delete(0);
Get2chInfo(URI, host, bbs, datnum, index, oldLog);
if length(datnum) <= 0 then
continue;
board := Main.i2ch.FindBoard(host, bbs);
if board = nil then
continue;
board.AddRef;
thread := board.Find(datnum);
if thread <> nil then
begin
if thread.Downloading then
begin
board.Release;
continue;
end;
end
else begin
thread := TThreadItem.Create(board);
thread.datName := datnum;
thread.URI := 'http://' + host + '/' + bbs;
board.Add(thread);
end;
board.Release;
if oldLog and (thread.state <> tsComplete) then
thread.queryState := tsHistory1;
FStartTime := Now;
case thread.StartAsyncRead(OnEndDownload, nil) of
trrSuccess: exit;
trrErrorProgress,
trrErrorPermanent: continue;
trrErrorTemporary:
begin
FStartTime := 0;
Insert(0, URI);
SetTimer(CROWDED_INTERVAL);
exit;
end;
else
begin
Clear;
exit;
end;
end;
end;
FState := dsFREE;
{Log('(・∀・)オワリ');
StatLog('リミット(・∀・)アト ' + IntToStr(TEST_MAX - counter));}
Log2(37, ''); //ayaya
StatLog2(38, IntToStr(TEST_MAX - counter)); //ayaya
end;
procedure TDownloader.OnEndDownload(thread: TThreadItem);
begin
FState := dsFREE;
FStartTime := FStartTime +
(thread.TransferedSize / FLimitBytesPerSec)/(24*60*60);
if Assigned(FOnNotify) then
FOnNotify(Self, thread);
if FStartTime <= Now then
FStartTime := IncSecond(Now);
BeginDownload;
end;
procedure TDownloader.Drain;
begin
FState := dsDRAIN;
FreeTimer;
Clear;
end;
function TDownloader.IsLimit: Boolean;
begin
if 30 <= (Now - FStartTime)*24*60 then
counter := 0;
result := (TEST_MAX <= counter);
end;
end.
|
{******************************************************************************}
{ }
{ Icon Fonts ImageList: An extended ImageList for Delphi/VCL }
{ to simplify use of Icons (resize, colors and more...) }
{ }
{ Copyright (c) 2019-2023 (Ethea S.r.l.) }
{ Author: Carlo Barazzetta }
{ Contributors: }
{ Nicola Tambascia }
{ Luca Minuti }
{ }
{ https://github.com/EtheaDev/IconFontsImageList }
{ }
{******************************************************************************}
{ }
{ 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 IconFontsImageList;
interface
{$INCLUDE IconFontsImageList.inc}
uses
Classes
, ImgList
, Windows
, Graphics
{$IFDEF HiDPISupport}
, Messaging
{$ENDIF}
, IconFontsImageListBase
, IconFontsItems;
type
TIconFontsItem = IconFontsItems.TIconFontItem;
TIconFontsItems = IconFontsItems.TIconFontItems;
{TIconFontsImageList}
TIconFontsImageList = class(TIconFontsImageListBase)
private
FIconFontItems: TIconFontItems;
protected
function GetIconFontItems: TIconFontItems; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property IconFontItems;
end;
implementation
uses
SysUtils
, IconFontsUtils
, Math
, ComCtrls
{$IFDEF DXE3+}
, System.Character
, Themes
{$ENDIF}
{$IFDEF GDI+}
, Winapi.CommCtrl
{$ENDIF}
, StrUtils
;
{ TIconFontsImageList }
constructor TIconFontsImageList.Create(AOwner: TComponent);
begin
inherited;
FIconFontItems := TIconFontItems.Create(Self, TIconFontItem, OnItemChanged,
CheckFontName, GetOwnerAttributes);
end;
destructor TIconFontsImageList.Destroy;
begin
FreeAndNil(FIconFontItems);
inherited;
end;
function TIconFontsImageList.GetIconFontItems: TIconFontItems;
begin
Result := FIconFontItems;
end;
end.
|
unit UOptionsButton;
{
Copyright (c) 2014 George Wright
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License, as described at
http://www.apache.org/licenses/ and http://www.pp4s.co.uk/licenses/
}
interface
uses
W3System;
type
TOptionsButton = class(TObject)
X : float; //The x position of the button
Y : float; //the y position of the button
Width : float; //the width of the button
Height : float; //the height of the button
Text : string; //the text in the button
TextX : float; //the X of the text in the button
TextY : float; //the Y of the text in the button
constructor create(newX, newY, newWidth, newHeight : float; newText : string; newTextX,newTextY : float);
//If the x and y are in the button, it will return true as it has been clicked
function clicked(clickX, clickY : float) : boolean;
end;
implementation
constructor TOptionsButton.create(newX,newY,newWidth,newHeight : float; newText : string; newTextX,newTextY : float);
begin
X := newX;
Y := newY;
Width := newWidth;
Height := newHeight;
Text := newText;
TextX := newTextX;
TextY := newTextY;
end;
function TOptionsButton.clicked(clickX,clickY : float) : boolean;
begin
if (clickX >= X) and (clickX <= X + Width) then //if the x is in the x range
begin
if (clickY >= Y) and (clickY <= Y + Height) then //if the y is in the y range
begin
Exit(true); //return true if both passed
end;
end;
Exit(false); //otherwise return false
end;
end.
|
{
Purpose: Generates Load Order Specific Default lists for Assinged Storage.
Game: The Elder Scrolls V: Skyrim
Author: Whiskey Metz <WhiskeyMetz@gmail.com>
Version: 1.0
Usage: Apply Script to Entire load Order and Write result to
*SkyrimSE*\Data\SKSE\plugins\JCData\Domains\phiASDomain
}
Unit UserScript;
var
formIds: THashedStringList;
lightArmor,
heavyArmor,
shields,
oneHanded,
twoHanded,
bow,
staff,
jewelery,
clothesBody,
clothesChildren,
clothesHandFeet,
potionsPoisons,
potionsBeneficial,
foodItem,
foodIngredient,
ingredient,
spellTomes,
books,
scrolls,
keys,
oreAndIngots,
gems,
skinBoneLeather,
clutter,
treasures,
homeItems : TStringList;
i : integer;
verboseLogging, logDump : boolean;
saveLocation : string;
Function Initialize(): integer;
Begin
ClearMessages();
saveLocation := SelectDirectory('You are looking for Data\SKSE\plugins\JCData\Domains\phiASDomain', DataPath, '', '');
If (Length(saveLocation) = 0) Then
Begin
AddMessage('Canceled By User. Exiting Script');
Result := 1;
exit;
End;
AddMessage('Location Saved. Beginning Script. Please Wait....');
verboseLogging := true;
logDump := false;
formIds := THashedStringList.Create;
lightArmor := TStringList.Create;
heavyArmor := TStringList.Create;
shields := TStringList.Create;
oneHanded := TStringList.Create;
twoHanded := TStringList.Create;
bow := TStringList.Create;
staff := TStringList.Create;
jewelery := TStringList.Create;
clothesBody := TStringList.Create;
clothesChildren := TStringList.Create;
clothesHandFeet := TStringList.Create;
potionsPoisons := TStringList.Create;
potionsBeneficial := TStringList.Create;
foodItem := TStringList.Create;
foodIngredient := TStringList.Create;
ingredient := TStringList.Create;
spellTomes := TStringList.Create;
books := TStringList.Create;
scrolls := TStringList.Create;
keys := TStringList.Create;
oreAndIngots := TStringList.Create;
gems := TStringList.Create;
skinBoneLeather := TStringList.Create;
clutter := TStringList.Create;
treasures := TStringList.Create;
homeItems := TStringList.Create;
Result := 0;
End;
Function VerifyNewRecord(modRecord: IInterface): integer;
var
recordName, formId: string;
i : integer;
Begin
recordName := Name(modRecord);
formId := IntToHex(FixedFormID(modRecord), 5);
If (formIds.IndexOf(formID) > -1) Then
Begin
AddMessage('Found Duplicate -- ' + recordName);
Result := 0;
exit;
End;
formIds.Add(formId);
Result := 1;
End;
Function BaseRecordData(modRecord: IInterface): String;
var
recordName, formId : String;
Begin
recordName := GetFileName(modRecord);
formId := '0x' + IntToHex(FixedFormID(modRecord),5);
Result := '"__formData|' + recordName + '|' + formId + '",';
End;
Function FindKeyword(keywords: IInterface; keyword: String): integer;
var
itemList : IInterface;
var
keywordResult : string;
var
i : integer;
Begin
If ElementCount(keywords) > 0 Then
Begin
For i := 0 To ElementCount(keywords) - 1 Do
Begin
itemList := LinksTo(ElementByIndex(keywords, i));
keywordResult := GetEditValue(ElementBySignature(itemList, 'EDID'));
If (keywordResult = keyword) Then
Result := 1;
exit;
End;
End;
End;
Function LogMessage(modRecord: IInterface; category: String): integer;
Begin
If (verboseLogging = true) Then
Begin
AddMessage(Name(modRecord) + ' Added to ' + category);
End;
End;
Function DumpToLog(list : TStringList): integer;
var
i : integer;
Begin
If (logDump = true) Then
Begin
For i := 0 To list.Count -1 Do
Begin
AddMessage(list[i]);
End;
End;
End;
Function WriteToFile(list: TStringList; fileName: String): integer;
var
lastString : string;
var
stringPosition: integer;
Begin
list.Insert(0, '[');
stringPosition := List.Count -1;
lastString := list[stringPosition];
list.Delete(stringPosition);
Delete(lastString, Length(lastString), 4);
list.Add(lastString);
list.Add(']');
If (Length(saveLocation) > 0) Then
Begin
list.SaveToFile(saveLocation + '\' + fileName)
End
Else
AddMessage('Canceled writing to file.');
End;
Function RunWeaponRecord(modRecord : IInterface): integer;
var
weaponType : string;
overrideRecord : IInterface;
Begin
overrideRecord := WinningOverride(modRecord);
weaponType := GetElementEditValues(overrideRecord, 'DNAM\Animation Type');
If pos('TwoHand', weaponType) > 0 Then
Begin
twoHanded.Add(BaseRecordData(modRecord));
LogMessage(modRecord, 'Two Handed Weapons');
exit;
End;
If pos('OneHand', weaponType) > 0 Then
Begin
oneHanded.Add(BaseRecordData(modRecord));
LogMessage(modRecord, 'One Handed Weapons');
exit;
End;
If pos('Bow', weaponType) > 0 Then
Begin
bow.Add(BaseRecordData(modRecord));
LogMessage(modRecord, 'Bows');
exit;
End;
If pos('Staff', weaponType) > 0 Then
Begin
staff.Add(BaseRecordData(modRecord));
LogMessage(modRecord, 'Staff');
exit;
End;
End;
Function RunClothesRecord(modRecord: IInterface): integer;
var
edid : string;
var
gloves, boots, amulets, rings, circlets, bodies : integer;
overrideRecord : IInterface;
Begin
edid := GetEditValue(ElementBySignature(modRecord, 'EDID'));
overrideRecord := WinningOverride(modRecord);
gloves := GetElementEditValues(overrideRecord, 'BOD2\First Person Flags\33 - Hands');
boots := GetElementEditValues(overrideRecord, 'BOD2\First Person Flags\37 - Feet');
rings := GetElementEditValues(overrideRecord, 'BOD2\First Person Flags\36 - Ring');
amulets := GetElementEditValues(overrideRecord, 'BOD2\First Person Flags\35 - Amulet');
circlets := GetElementEditValues(overrideRecord, 'BOD2\First Person Flags\42 - Circlet');
bodies := GetElementEditValues(overrideRecord, 'BOD2\First Person Flags\32 - Body');
If (IntToHex(rings, 1) = '1') Or (IntToHex(amulets, 1) = '1') Or ((IntToHex(circlets, 1) = '1') And (IntToHex(bodies, 1) = '0')) Then
Begin
jewelery.Add(BaseRecordData(modRecord));
LogMessage(modRecord, 'Valuables - Jewelery');
exit;
End;
If pos('ClothesChild', edid) > 0 Then
Begin
clothesChildren.Add(BaseRecordData(modRecord));
LogMessage(modRecord, 'Childrens Clothes');
exit;
End;
If (IntToHex(gloves,1) = '1') Or (IntToHex(boots,1) = '1') Then
Begin
clothesHandFeet.Add(BaseRecordData(modRecord));
LogMessage(modRecord, 'Clothes - Gloves/Shoes');
exit;
End;
clothesBody.Add(BaseRecordData(modRecord));
LogMessage(modRecord, 'Clothes');
End;
Function RunAmmoRecord(modRecord: IInterface): integer;
var
isNotPlayable : string;
overrideRecord : IInterface;
Begin
isNotPlayable := GetElementEditValues(overrideRecord, 'DATA\Flags\Non-Playable');
If isNotPlayable = '1' Then
Begin
exit;
End;
bow.Add(BaseRecordData(modRecord));
LogMessage(modRecord, 'Bows');
End;
Function RunArmorRecord(modRecord : IInterface): integer;
var
armorType, etyp : string;
overrideRecord : IInterface;
Begin
overrideRecord := WinningOverride(modRecord);
armorType := GetElementEditValues(overrideRecord, 'BOD2\Armor Type');
etyp := GetElementEditValues(overrideRecord, 'ETYP');
If pos('Shield', etyp) > 0 Then
Begin
shields.Add(BaseRecordData(modRecord));
LogMessage(modRecord, 'Shields');
exit;
End;
If (armorType = 'Heavy Armor') Then
Begin
heavyArmor.Add(BaseRecordData(modRecord));
LogMessage(modRecord, 'Heavy Armor');
exit;
End;
If (armorType = 'Light Armor') Then
Begin
lightArmor.Add(BaseRecordData(modRecord));
LogMessage(modRecord, 'Light Armor');
End;
If (armorType = 'Clothing') Then
Begin
RunClothesRecord(modRecord);
End;
End;
Function RunAlchRecord(modRecord: IInterface): integer;
var
foodKeyword, foodRawKeyword, potionKeyword, poisonKeyword: int;
var
keywordGroup, overrideRecord : IInterface;
var
foodFlag, poisonFlag : string;
Begin
overrideRecord := WinningOverride(modRecord);
keywordGroup := ElementByName(overrideRecord, 'KWDA - Keywords');
foodKeyword := FindKeyword(keywordGroup, 'VendorItemFood');
foodRawKeyword := FindKeyword(keywordGroup, 'VendorItemFoodRaw');
potionKeyword := FindKeyword(keywordGroup, 'VendorItemPotion');
poisonKeyword := FindKeyword(keywordGroup, 'VendorItemPoison');
foodFlag := GetElementEditValues(overrideRecord, 'ENIT\Flags\Food Item');
poisonFlag := GetElementEditValues(overrideRecord, 'ENIT\Flags\Poison');
If (poisonFlag = '1') Then
Begin
potionsPoisons.Add(BaseRecordData(modRecord));
LogMessage(modRecord, 'Poisons');
exit;
End;
If (foodFlag = '1') Then
Begin
foodItem.Add(BaseRecordData(modRecord));
LogMessage(modRecord, 'Food');
exit;
End;
If (foodRawKeyword = 1) Then
Begin
foodIngredient.Add(BaseRecordData(modRecord));
LogMessage(modRecord, 'Food Ingredients');
exit;
End;
If (foodKeyword = 1) Then
Begin
foodItem.Add(BaseRecordData(modRecord));
LogMessage(modRecord, 'Food');
exit;
End;
If (potionKeyword = 1) Then
Begin
potionsBeneficial.Add(BaseRecordData(modRecord));
LogMessage(modRecord, 'Potions');
exit;
End;
If (poisonKeyword = 1) Then
Begin
potionsPoisons.Add(BaseRecordData(modRecord));
LogMessage(modRecord, 'Poisons');
exit;
End;
potionsBeneficial.Add(BaseRecordData(modRecord));
LogMessage(modRecord, 'Potions');
End;
Function RunIngredientRecord(modRecord : IInterface): integer;
Begin
ingredient.Add(BaseRecordData(modRecord));
LogMessage(modRecord, 'Ingredients');
End;
Function RunMiscRecord(modRecord: IInterface): integer;
var
keywordGroup, overrideRecord : IInterface;
OreIngot, clutterItem, tool, gem, animalHide, animalPart : integer;
Begin
overrideRecord := WinningOverride(modRecord);
If (pos('Gold001', Name(modRecord)) > 0) Or (pos('Lockpick', Name(modRecord)) > 0) Or (pos('phiAS', Name(modRecord)) > 0) Then
Begin
AddMessage(Name(modRecord) + ' has been skipped');
exit;
End;
If (pos('BYOH', Name(modRecord)) > 0)Then
Begin
homeItems.Add(BaseRecordData(modRecord));
LogMessage(modRecord, 'Housing');
exit;
End;
keywordGroup := ElementByName(overrideRecord, 'KWDA - Keywords');
OreIngot := FindKeyword(keywordGroup, 'VendorItemOreIngot');
If (OreIngot = 1)Then
Begin
oreAndIngots.Add(BaseRecordData(modRecord));
LogMessage(modRecord, 'Ores and Ingots');
exit;
End;
gem := FindKeyword(keywordGroup, 'VendorItemGem');
If (gem = 1)Then
Begin
gems.Add(BaseRecordData(modRecord));
LogMessage(modRecord, 'Gems');
exit;
End;
animalHide := FindKeyword(keywordGroup, 'VendorItemAnimalHide');
animalPart := FindKeyword(keywordGroup, 'VendorItemAnimalPart');
If (animalHide = 1) Or (animalPart = 1)Then
Begin
skinBoneLeather.Add(BaseRecordData(modRecord));
LogMessage(modRecord, 'Leather, Scale, and Bone ');
exit;
End;
tool := FindKeyword(keywordGroup, 'VendorItemTool');
clutterItem := FindKeyword(keywordGroup, 'VendorItemClutter');
If (tool = 1) Or (clutterItem = 1)Then
Begin
clutter.Add(BaseRecordData(modRecord));
LogMessage(modRecord, 'MISC - Random');
exit;
End;
treasures.add(BaseRecordData(modRecord));
LogMessage(modRecord, 'Valuables - Treasure');
End;
Function RunBookRecord(modRecord: IInterface): integer;
var
spellFlag : string;
Begin
spellFlag := GetElementEditValues(WinningOverride(modRecord), 'DATA\Flags\Teaches Spell');
If (spellFlag = '1') Then
Begin
spellTomes.Add(BaseRecordData(modRecord));
LogMessage(modRecord, 'Spell Tomes');
exit;
End;
books.Add(BaseRecordData(modRecord));
LogMessage(modRecord, 'Books');
End;
Function RunScrollRecord(modRecord: IInterface): integer;
Begin
scrolls.Add(BaseRecordData(modRecord));
LogMessage(modRecord, 'Scrolls');
End;
Function RunKeyRecord(modRecord: IInterface): integer;
Begin
keys.Add(BaseRecordData(modRecord));
LogMessage(modRecord, 'Keys');
End;
Function Process(e: IInterface): integer;
var
recordType: String;
Begin
recordType := Signature(e);
If (recordType <> 'ARMO') And
(recordType <> 'AMMO') And
(recordType <> 'WEAP') And
(recordType <> 'ALCH') And
(recordType <> 'MISC') And
(recordType <> 'BOOK') And
(recordType <> 'INGR') And
(recordType <> 'KEYM') And
(recordType <> 'SCRL') Then
Begin
exit;
End;
If (recordType = 'ARMO') Then
Begin
RunArmorRecord(e);
exit;
End;
If (recordType = 'WEAP') Then
Begin
RunWeaponRecord(e);
exit;
End;
If (recordType = 'AMMO') Then
Begin
RunAmmoRecord(e);
exit;
End;
If (recordType = 'ALCH') Then
Begin
RunAlchRecord(e);
exit;
End;
If (recordType = 'MISC') Then
Begin
RunMiscRecord(e);
exit;
End;
If (recordType = 'BOOK') Then
Begin
RunBookRecord(e);
exit;
End;
If (recordType = 'INGR') Then
Begin
RunIngredientRecord(e);
exit;
End;
If (recordType = 'KEYM') Then
Begin
RunKeyRecord(e);
exit;
End;
If (recordType = 'SCRL') Then
Begin
RunScrollRecord(e);
exit;
End;
End;
Function Finalize(): integer;
Begin
AddMessage('Writing to file...');
If (heavyArmor.Count > 0) Then
Begin
WriteToFile(heavyArmor, 'tempArmor.json');
DumpToLog(heavyArmor);
End;
If (lightArmor.Count >0) Then
Begin
WriteToFile(lightArmor, 'tempArmorL.json');
DumpToLog(lightArmor);
End;
If (shields.Count > 0) Then
Begin
WriteToFile(shields, 'tempArmorS.json');
DumpToLog(shields);
End;
If (oneHanded.Count > 0) Then
Begin
WriteToFile(oneHanded, 'tempWeapons.json');
DumpToLog(oneHanded);
End;
If (twoHanded.Count > 0) Then
Begin
WriteToFile(twoHanded, 'tempWeapons2H.json');
DumpToLog(twoHanded);
End;
If (bow.Count > 0) Then
Begin
WriteToFile(bow, 'tempWeaponsB.json');
DumpToLog(bow);
End;
If (staff.Count > 0) Then
Begin
WriteToFile(staff, 'tempWeaponsS.json');
DumpToLog(staff);
End;
If (jewelery.Count > 0) Then
Begin
WriteToFile(jewelery, 'tempValuablesJ.json');
DumpToLog(jewelery);
End;
If (clothesBody.Count > 0) Then
Begin
WriteToFile(clothesBody, 'tempClothing.json');
DumpToLog(clothesBody);
End;
If (clothesChildren.Count > 0) Then
Begin
WriteToFile(clothesChildren, 'tempClothingC.json');
DumpToLog(clothesChildren);
End;
If (clothesHandFeet.Count > 0) Then
Begin
WriteToFile(clothesHandFeet, 'tempClothingG.json');
DumpToLog(clothesHandFeet);
End;
If (potionsPoisons.Count > 0) Then
Begin
WriteToFile(potionsPoisons, 'tempPotionsPoi.json');
DumpToLog(potionsPoisons);
End;
If (potionsBeneficial.Count > 0) Then
Begin
WriteToFile(potionsBeneficial, 'tempPotionsPot.json');
DumpToLog(potionsBeneficial);
End;
If (foodItem.Count > 0) Then
Begin
WriteToFile(foodItem, 'tempFoodFD.json');
DumpToLog(foodItem);
End;
If (foodIngredient.Count > 0) Then
Begin
WriteToFile(foodIngredient, 'tempFoodCI.json');
DumpToLog(foodIngredient);
End;
If (ingredient.Count > 0) Then
Begin
WriteToFile(ingredient, 'tempAlchemy.json');
DumpToLog(ingredient);
End;
If (spellTomes.Count > 0) Then
Begin
WriteToFile(spellTomes, 'tempBooksST.json');
DumpToLog(spellTomes);
End;
If (books.Count > 0) Then
Begin
WriteToFile(books, 'tempBooksB.json');
DumpToLog(books);
End;
If (scrolls.Count > 0) Then
Begin
WriteToFile(scrolls, 'tempBooksS.json');
DumpToLog(scrolls);
End;
If (keys.Count > 0) Then
Begin
WriteToFile(keys, 'tempKeys.json');
DumpToLog(keys);
End;
If (oreAndIngots.Count > 0) Then
Begin
WriteToFile(oreAndIngots, 'tempCraftingIO.json');
DumpToLog(oreAndIngots);
End;
If (gems.Count > 0) Then
Begin
WriteToFile(gems, 'tempValuablesG.json');
DumpToLog(gems);
End;
If (skinBoneLeather.Count > 0) Then
Begin
WriteToFile(skinBoneLeather, 'tempCraftingLSB.json');
DumpToLog(skinBoneLeather);
End;
If (clutter.Count > 0) Then
Begin
WriteToFile(clutter, 'tempRandom.json');
DumpToLog(clutter);
End;
If (treasures.Count > 0) Then
Begin
WriteToFile(treasures, 'tempXGold.json');
DumpToLog(treasures);
End;
If (homeItems.Count > 0) Then
Begin
WriteToFile(homeItems, 'tempCraftingHR.json');
DumpToLog(homeItems);
End;
AddMessage('Haha. Script go brrrrr');
Result := 1;
End;
End.
|
unit GoodsBarCode;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ParentForm, cxGraphics, cxControls, cxLookAndFeels,
cxLookAndFeelPainters, cxStyles, dxSkinsCore, dxSkinsDefaultPainters, dxSkinscxPCPainter,
cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, Data.DB, cxDBData, cxGridLevel, cxClasses,
cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid,
DataModul, dxSkinsdxBarPainter, dxBar, cxPropertiesStore, Datasnap.DBClient, dxBarExtItems,
dsdAddOn, dsdDB, ExternalLoad, dsdAction, Vcl.ActnList, dxSkinBlack,
dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom,
dxSkinDarkSide, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy,
dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian,
dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMoneyTwins,
dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green,
dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black,
dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinPumpkin, dxSkinSeven,
dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus, dxSkinSilver,
dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008, dxSkinTheAsphaltWorld,
dxSkinValentine, dxSkinVS2010, dxSkinWhiteprint, dxSkinXmas2008Blue,
cxContainer, dsdGuides, cxTextEdit, cxMaskEdit, cxButtonEdit, cxLabel;
type
TGoodsBarCodeForm = class(TParentForm)
cxGridDBTableView: TcxGridDBTableView;
cxGridLevel: TcxGridLevel;
cxGrid: TcxGrid;
DataSource: TDataSource;
ClientDataSet: TClientDataSet;
cxPropertiesStore: TcxPropertiesStore;
dxBarManager: TdxBarManager;
ActionList: TActionList;
actGetImportSetting: TdsdExecStoredProc;
actRefresh: TdsdDataSetRefresh;
dsdGridToExcel: TdsdGridToExcel;
actUpdateDataSet: TdsdUpdateDataSet;
actStartLoad: TMultiAction;
actDoLoad: TExecuteImportSettingsAction;
spSelect: TdsdStoredProc;
dsdUserSettingsStorageAddOn: TdsdUserSettingsStorageAddOn;
dxBarButtonRefresh: TdxBarButton;
dxBarManagerBar1: TdxBar;
dxBarButtonGridToExcel: TdxBarButton;
spInsertUpdate: TdsdStoredProc;
Id: TcxGridDBColumn;
GoodsId: TcxGridDBColumn;
GoodsMainId: TcxGridDBColumn;
GoodsBarCodeId: TcxGridDBColumn;
GoodsJuridicalId: TcxGridDBColumn;
JuridicalId: TcxGridDBColumn;
Code: TcxGridDBColumn;
Name: TcxGridDBColumn;
ProducerName: TcxGridDBColumn;
GoodsCode: TcxGridDBColumn;
BarCode: TcxGridDBColumn;
JuridicalName: TcxGridDBColumn;
spGetImportSettingId: TdsdStoredProc;
FormParams: TdsdFormParams;
spInsertUpdateLoad: TdsdStoredProc;
dxBarButtonLoad: TdxBarButton;
ErrorText: TcxGridDBColumn;
dxBarStatic1: TdxBarStatic;
spGetImportSettingId_Price: TdsdStoredProc;
bbStartLoad2: TdxBarButton;
cxLabel3: TcxLabel;
edJuridical: TcxButtonEdit;
GuidesJuridical: TdsdGuides;
dxBarControlContainerItem1: TdxBarControlContainerItem;
dxBarControlContainerItem2: TdxBarControlContainerItem;
spInsertUpdateLoad_Price: TdsdStoredProc;
actDoLoad_Price: TExecuteImportSettingsAction;
actGetImportSetting_Price: TdsdExecStoredProc;
actStartLoad_Price: TMultiAction;
dsdStoredProc1: TdsdStoredProc;
actTest: TdsdExecStoredProc;
CodeUKTZED: TcxGridDBColumn;
private
{ Private declarations }
public
{ Public declarations }
end;
implementation
{$R *.dfm}
initialization
RegisterClass(TGoodsBarCodeForm);
end.
|
unit SpCalcPanel;
interface
uses
SysUtils, Classes, Controls, ExtCtrls, StdCtrls, Graphics;
type
TSpCalculatorPanel = class(TCustomPanel)
private
FHoursLEdit : TLabeledEdit;
FElectricityLEdit: TLabeledEdit;
FCalcButton : TButton;
FBatLabel : TLabel;
FBatAmountLabel : TLabel;
FSPanLabel : TLabel;
FSPanelAmountLabel : TLabel;
FRoofLabel : TLabel;
FRoofSpaceLabel : TLabel;
procedure BtClick(Sender:TObject);
procedure EditExit(Sender: TObject);
protected
{ Protected declarations }
public
constructor Create(AOwner:TComponent); override;
published
{ Published declarations }
end;
procedure Register;
implementation
uses SpCalculatorUnit,Dialogs;
procedure Register;
begin
RegisterComponents('Samples', [TSpCalculatorPanel]);
end;
{ TSpCalculatorPanel }
procedure TSpCalculatorPanel.EditExit(Sender: TObject);
begin
try
StrToInt(TEdit(Sender).Text);
except
on Exception do
begin
ShowMessage('Incorrect parameter value. Check your input');
TEdit(Sender).SetFocus;
end;
end;
end;
procedure TSpCalculatorPanel.BtClick(Sender: TObject);
var
SPCalcResults : TCalculationResults;
SunnyHours, WattsConsumed : Word;
ResCode, ResCode2 : Integer;
s: string;
begin
SunnyHours :=0;
WattsConsumed :=0;
try
Val(FHoursLEdit.Text,SunnyHours,ResCode);
Val(FElectricityLEdit.Text,WattsConsumed,ResCode2);
if ((ResCode<>0) or (ResCode2<>0)) then
begin
ShowMessage('Incorrect input parameter value, hours: '+FHoursLEdit.Text+' watts: '+FElectricityLEdit.Text);
Exit;
end;
except
on E:Exception do ShowMessage('Incorrect input parameter value');
end;
SPCalcResults := CalculateBatteriesPanelsAmount(SunnyHours,WattsConsumed);
Str(SPCalcResults.PanelsAmount,s);
FSPanelAmountLabel.Caption := s;
Str(SPCalcResults.BatteriesAmount,s);
FBatAmountLabel.Caption := s;
Str(SPCalcResults.RoofSpaceNeeded,s);
FRoofSpaceLabel.Caption := s;
end;
constructor TSpCalculatorPanel.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Self.Width:=468;
Self.Height:=280;
Self.Top:=2;
Self.Left:=2;
Self.Constraints.MaxHeight:=280;
Self.Constraints.MinHeight:=280;
Self.Constraints.MaxWidth:=468;
Self.Constraints.MinWidth:=468;
Self.Color:= clWhite;
FCalcButton := TButton.Create(Self);
FCalcButton.Parent := Self;
FCalcButton.Left :=13;
FCalcButton.Top :=185;
FCalcButton.Width :=100;
FCalcButton.Height :=32;
FCalcButton.Caption:='Calculate';
FCalcButton.OnClick:=BtClick;
FHoursLEdit := TLabeledEdit.Create(Self);
FHoursLEdit.Parent := Self;
FHoursLEdit.Left :=13;
FHoursLEdit.Top :=71;
FHoursLEdit.Width :=60;
FHoursLEdit.Height :=27;
FHoursLEdit.EditLabel.Caption :='Average sunny hours';
FHoursLEdit.Font.Name :='Arial';
FHoursLEdit.Font.Size :=12;
FHoursLEdit.MaxLength :=4;
FHoursLEdit.OnExit := EditExit;
FElectricityLEdit := TLabeledEdit.Create(Self);
FElectricityLEdit.Parent := Self;
FElectricityLEdit.Left :=13;
FElectricityLEdit.Top :=129;
FElectricityLEdit.Width :=60;
FElectricityLEdit.Height :=27;
FElectricityLEdit.EditLabel.Caption:='Electricity consumed, W';
FElectricityLEdit.Font.Name :='Arial';
FElectricityLEdit.Font.Size :=12;
FElectricityLEdit.MaxLength :=4;
FElectricityLEdit.OnExit := EditExit;
FBatLabel := TLabel.Create(Self);
FBatLabel.Parent := Self;
FBatLabel.Left :=270;
FBatLabel.Top :=51;
FBatLabel.Width :=149;
FBatLabel.Height :=19;
FBatLabel.Caption :='Amount of batteries';
FBatLabel.Font.Name :='Arial';
FBatLabel.Font.Size :=12;
FBatAmountLabel := TLabel.Create(Self);
FBatAmountLabel.Parent := Self;
FBatAmountLabel.Left :=336;
FBatAmountLabel.Top :=71;
FBatAmountLabel.Width :=15;
FBatAmountLabel.Height :=31;
FBatAmountLabel.Caption :='0';
FBatAmountLabel.Font.Name :='Arial';
FBatAmountLabel.Font.Size :=20;
FBatAmountLabel.Font.Color:=clBlue;
FSPanLabel := TLabel.Create(Self);
FSPanLabel.Parent := Self;
FSPanLabel.Left :=256;
FSPanLabel.Top :=112;
FSPanLabel.Width :=176;
FSPanLabel.Height :=19;
FSPanLabel.Caption :='Amount of solar panels';
FSPanLabel.Font.Name :='Arial';
FSPanLabel.Font.Size :=12;
FSPanelAmountLabel := TLabel.Create(Self);
FSPanelAmountLabel.Parent := Self;
FSPanelAmountLabel.Left :=336;
FSPanelAmountLabel.Top :=132;
FSPanelAmountLabel.Width :=15;
FSPanelAmountLabel.Height :=31;
FSPanelAmountLabel.Caption :='0';
FSPanelAmountLabel.Font.Name :='Arial';
FSPanelAmountLabel.Font.Size :=20;
FSPanelAmountLabel.Font.Color:=clBlue;
FRoofLabel := TLabel.Create(Self);
FRoofLabel.Parent := Self;
FRoofLabel.Left :=241;
FRoofLabel.Top :=176;
FRoofLabel.Width :=207;
FRoofLabel.Height :=19;
FRoofLabel.Caption :='Roof space occupied, sq.m';
FRoofLabel.Font.Name :='Arial';
FRoofLabel.Font.Size :=12;
FRoofSpaceLabel := TLabel.Create(Self);
FRoofSpaceLabel.Parent := Self;
FRoofSpaceLabel.Left :=336;
FRoofSpaceLabel.Top :=194;
FRoofSpaceLabel.Width :=15;
FRoofSpaceLabel.Height :=31;
FRoofSpaceLabel.Caption :='0';
FRoofSpaceLabel.Font.Name :='Arial';
FRoofSpaceLabel.Font.Size :=20;
FRoofSpaceLabel.Font.Color:=clBlue;
end;
end.
|
unit ValueComparerSpecs;
// 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 DUnitLite.
//
// The Initial Developer of the Original Code is Joe White.
// Portions created by Joe White are Copyright (C) 2007
// Joe White. All Rights Reserved.
//
// Contributor(s):
//
// Alternatively, the contents of this file may be used under the terms
// of the LGPL license (the "LGPL License"), in which case the
// provisions of LGPL License are applicable instead of those
// above. If you wish to allow use of your version of this file only
// under the terms of the LGPL License and not to allow others to use
// your version of this file under the MPL, indicate your decision by
// deleting the provisions above and replace them with the notice and
// other provisions required by the LGPL License. If you do not delete
// the provisions above, a recipient may use your version of this file
// under either the MPL or the LGPL License.
interface
uses
Constraints,
Specifications,
ValueComparers;
type
TValueComparerSpecification = class(TRegisterableSpecification)
strict protected
function GetComparer: IValueComparer; virtual; abstract;
procedure SpecifyThatComparing(const A, B: Extended;
SatisfiesCondition: IConstraint);
procedure SpecifyThatIndexOfFirstDifferenceBetween(const A, B: string;
SatisfiesCondition: IConstraint);
property Comparer: IValueComparer read GetComparer;
published
procedure SpecExactlyEqual;
procedure SpecLess;
procedure SpecGreater;
end;
DefaultValueComparerSpec = class(TValueComparerSpecification)
strict protected
function GetComparer: IValueComparer; override;
published
procedure SpecCloseEnough;
procedure SpecNotCloseEnough;
procedure SpecAsString;
procedure SpecIndexOfFirstDifference;
procedure SpecIndexOfFirstDifferenceWhenFirstIsLeadingSubstring;
procedure SpecIndexOfFirstDifferenceWhenSecondIsLeadingSubstring;
procedure SpecIndexOfFirstDifferenceWhenStringsAreEqual;
end;
ExactComparerSpec = class(TValueComparerSpecification)
strict protected
function GetComparer: IValueComparer; override;
published
procedure SpecCloseButNoCigar;
procedure SpecAsString;
end;
EpsilonComparerSpec = class(TValueComparerSpecification)
strict protected
function GetComparer: IValueComparer; override;
published
procedure SpecCloseEnough;
procedure SpecNotCloseEnough;
procedure SpecAsString;
end;
implementation
uses
TestValues,
TypInfo;
{ TValueComparerSpecification }
procedure TValueComparerSpecification.SpecifyThatComparing(const A, B: Extended;
SatisfiesCondition: IConstraint);
begin
Specify.That(Comparer.CompareExtendeds(A, B), SatisfiesCondition);
end;
procedure TValueComparerSpecification.SpecifyThatIndexOfFirstDifferenceBetween(
const A, B: string; SatisfiesCondition: IConstraint);
begin
Specify.That(Comparer.IndexOfFirstDifference(A, B), SatisfiesCondition);
end;
procedure TValueComparerSpecification.SpecExactlyEqual;
begin
SpecifyThatComparing(1, 1, Should.Yield(vcEqual));
end;
procedure TValueComparerSpecification.SpecGreater;
begin
SpecifyThatComparing(2, 1, Should.Yield(vcGreater));
end;
procedure TValueComparerSpecification.SpecLess;
begin
SpecifyThatComparing(1, 2, Should.Yield(vcLess));
end;
{ DefaultValueComparerSpec }
function DefaultValueComparerSpec.GetComparer: IValueComparer;
begin
Result := TDefaultValueComparer.Instance;
end;
procedure DefaultValueComparerSpec.SpecAsString;
begin
Specify.That(Comparer.AsString, Should.Equal(''));
end;
procedure DefaultValueComparerSpec.SpecCloseEnough;
begin
SpecifyThatComparing(EpsilonTestValues.BaseValue, EpsilonTestValues.SameAtDefaultEpsilon,
Should.Yield(vcEqual));
end;
procedure DefaultValueComparerSpec.SpecIndexOfFirstDifference;
begin
SpecifyThatIndexOfFirstDifferenceBetween('abc', 'axc', Should.Equal(2));
end;
procedure DefaultValueComparerSpec.SpecIndexOfFirstDifferenceWhenFirstIsLeadingSubstring;
begin
SpecifyThatIndexOfFirstDifferenceBetween('abc', 'abcde', Should.Equal(4));
end;
procedure DefaultValueComparerSpec.SpecIndexOfFirstDifferenceWhenSecondIsLeadingSubstring;
begin
SpecifyThatIndexOfFirstDifferenceBetween('abcde', 'abc', Should.Equal(4));
end;
procedure DefaultValueComparerSpec.SpecIndexOfFirstDifferenceWhenStringsAreEqual;
begin
SpecifyThatIndexOfFirstDifferenceBetween('abc', 'abc', Should.Equal(0));
end;
procedure DefaultValueComparerSpec.SpecNotCloseEnough;
begin
SpecifyThatComparing(EpsilonTestValues.BaseValue, EpsilonTestValues.DifferentAtDefaultEpsilon,
Should.Yield(vcLess));
end;
{ ExactComparerSpec }
function ExactComparerSpec.GetComparer: IValueComparer;
begin
Result := TExactValueComparer.Create;
end;
procedure ExactComparerSpec.SpecAsString;
begin
Specify.That(Comparer.AsString, Should.Equal('exactly'));
end;
procedure ExactComparerSpec.SpecCloseButNoCigar;
begin
SpecifyThatComparing(EpsilonTestValues.BaseValue, EpsilonTestValues.BarelyDifferent,
Should.Yield(vcLess));
end;
{ EpsilonComparerSpec }
function EpsilonComparerSpec.GetComparer: IValueComparer;
begin
Result := TEpsilonValueComparer.Create(0.5);
end;
procedure EpsilonComparerSpec.SpecAsString;
begin
Specify.That(Comparer.AsString, Should.Equal('to within 0.5'));
end;
procedure EpsilonComparerSpec.SpecCloseEnough;
begin
SpecifyThatComparing(1.0, 1.5, Should.Yield(vcEqual));
end;
procedure EpsilonComparerSpec.SpecNotCloseEnough;
begin
SpecifyThatComparing(1.0, 1.51, Should.Yield(vcLess));
end;
initialization
DefaultValueComparerSpec.Register;
ExactComparerSpec.Register;
EpsilonComparerSpec.Register;
end.
|
program Cuba;
Uses Graph, Crt, GrafBits;
Type
TPoint = object
X, Y: integer;
XDir, YDir: Boolean;
procedure GiveMeLife(Ex, Why: integer);
procedure GuideMe;
end;
TCube = object
Vertice: array[1..12] of TPoint;
XDir, YDir, XRotation, YRotation: Boolean;
procedure GiveMeLife;
procedure ChangeMe;
procedure DrawMe;
end;
Var
I, Num, Gd, Gm: integer;
DivX, DivY, MaxX, MaxY: integer;
Cube: TCube;
procedure TPoint.GiveMeLife(Ex, Why: integer);
begin
X:= Ex;
Y:= Why;
XDir:= True;
YDir:= True;
end;
procedure TPoint.GuideMe;
begin
if XDir = True then Inc(X, 2);
if YDir = True then Inc(Y, 2);
if XDir = False then Dec(X, 2);
if YDir = False then Dec(Y, 2);
if X> MaxX then XDir:= False;
if Y> MaxY then YDir:= False;
if X< 0 then XDir:= True;
if Y< 0 then YDir:= True;
end;
procedure TCube.GiveMeLife;
begin
Vertice[1].GiveMeLife(0, 0);
Vertice[2].GiveMeLife(70, 0);
Vertice[3].GiveMeLife(70, 30);
Vertice[4].GiveMeLife(0, 30);
Vertice[5].GiveMeLife(45, 10);
Vertice[6].GiveMeLife(115, 10);
Vertice[7].GiveMeLife(115, 40);
Vertice[8].GiveMeLife(45, 40);
Vertice[9].GiveMeLife(55, 90);
Vertice[10].GiveMeLife(185, 20);
Vertice[11].GiveMeLife(55, -50);
Vertice[12].GiveMeLife(-70, 20);
XDir:= True;
YDir:= True;
end;
procedure TCube.ChangeMe;
begin
For I:= 1 to 12 do
Vertice[I].GuideMe;
end;
procedure TCube.DrawMe;
begin
SetColor(Yellow);
Line(Vertice[1].X, Vertice[1].Y, Vertice[5].X, Vertice[5].Y);
Line(Vertice[2].X, Vertice[2].Y, Vertice[6].X, Vertice[6].Y);
Line(Vertice[3].X, Vertice[3].Y, Vertice[7].X, Vertice[7].Y);
Line(Vertice[4].X, Vertice[4].Y, Vertice[8].X, Vertice[8].Y);
SetColor(Magenta);
Line(Vertice[4].X, Vertice[4].Y, Vertice[9].X, Vertice[9].Y);
Line(Vertice[3].X, Vertice[3].Y, Vertice[9].X, Vertice[9].Y);
Line(Vertice[8].X, Vertice[8].Y, Vertice[9].X, Vertice[9].Y);
Line(Vertice[7].X, Vertice[7].Y, Vertice[9].X, Vertice[9].Y);
SetColor(Brown);
Line(Vertice[2].X, Vertice[2].Y, Vertice[10].X, Vertice[10].Y);
Line(Vertice[3].X, Vertice[3].Y, Vertice[10].X, Vertice[10].Y);
Line(Vertice[6].X, Vertice[6].Y, Vertice[10].X, Vertice[10].Y);
Line(Vertice[7].X, Vertice[7].Y, Vertice[10].X, Vertice[10].Y);
SetColor(White);
Line(Vertice[2].X, Vertice[2].Y, Vertice[11].X, Vertice[11].Y);
Line(Vertice[1].X, Vertice[1].Y, Vertice[11].X, Vertice[11].Y);
Line(Vertice[6].X, Vertice[6].Y, Vertice[11].X, Vertice[11].Y);
Line(Vertice[5].X, Vertice[5].Y, Vertice[11].X, Vertice[11].Y);
SetColor(Green);
Line(Vertice[4].X, Vertice[4].Y, Vertice[12].X, Vertice[12].Y);
Line(Vertice[1].X, Vertice[1].Y, Vertice[12].X, Vertice[12].Y);
Line(Vertice[8].X, Vertice[8].Y, Vertice[12].X, Vertice[12].Y);
Line(Vertice[5].X, Vertice[5].Y, Vertice[12].X, Vertice[12].Y);
SetColor(Blue);
Line(Vertice[1].X, Vertice[1].Y, Vertice[2].X, Vertice[2].Y);
Line(Vertice[2].X, Vertice[2].Y, Vertice[3].X, Vertice[3].Y);
Line(Vertice[3].X, Vertice[3].Y, Vertice[4].X, Vertice[4].Y);
Line(Vertice[4].X, Vertice[4].Y, Vertice[1].X, Vertice[1].Y);
SetColor(Red);
Line(Vertice[5].X, Vertice[5].Y, Vertice[6].X, Vertice[6].Y);
Line(Vertice[6].X, Vertice[6].Y, Vertice[7].X, Vertice[7].Y);
Line(Vertice[7].X, Vertice[7].Y, Vertice[8].X, Vertice[8].Y);
Line(Vertice[8].X, Vertice[8].Y, Vertice[5].X, Vertice[5].Y);
end;
begin
Gd:= EGA;
Gm:= 1;
InitGraph(Gd, Gm,'');
MaxX:= GetMaxX;
MaxY:= GetMaxY;
DivX:= MaxX div 2;
DivY:= MaxY div 2;
Cube.GiveMeLife;
Cube.DrawMe;
Repeat
SetVisualPage(0);
SetActivePage(1);
Delay(15);
ClearDevice;
Cube.ChangeMe;
Cube.DrawMe;
SetVisualPage(1);
SetActivePage(0);
Delay(15);
ClearDevice;
Cube.ChangeMe;
Cube.DrawMe;
Until KeyPressed;
CloseGraph;
end.
|
{*****************************************************************************}
{ BindAPI }
{ Copyright (C) 2020 Paolo Morandotti }
{ Unit plBindAPI.Attributes }
{*****************************************************************************}
{ }
{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 plBindAPI.Attributes;
interface
type
{Ancestor class of all attributes, with switch on and off bind instructions}
CustomBindAttribute = class(TCustomAttribute)
protected
FIsEnabled: Boolean;
FTargetClassName: string;
public
property IsEnabled: Boolean read FIsEnabled;
property TargetClassName: string read FTargetClassName;
end;
{A Class attribute describing the target class of bind action}
ClassBindAttribute = class(CustomBindAttribute)
private
FIsDefault: Boolean;
public
constructor Create(ATargetClassName: string;
IsDefaultClass: Boolean = False); overload;
constructor Create(const Enabled: Boolean; ATargetClassName: string;
IsDefaultClass: Boolean = False); overload;
property IsDefault: Boolean Read FIsDefault;
end;
{Ancestor class for class attributes binding methods and events}
MethodBindAttribute = class(CustomBindAttribute)
private
FSourceMethodName: string;
FNewMethodName: string;
public
constructor Create(const Enabled: Boolean; const AMethodName, ANewMethodName: string); overload;
constructor Create(const Enabled: Boolean; const AMethodName, ANewMethodName, ATargetClassName: string); overload;
property SourceMethodName: string read FSourceMethodName;
property NewMethodName: string read FNewMethodName;
end;
{Attribute to bind an event}
EventBindAttribute = class(MethodBindAttribute);
{Attribute to force binding on properties of GUI public/published elements}
FieldBindAttribute = class(CustomBindAttribute)
private
FFunctionName: string;
FSourcePath: string;
FTargetPath: string;
public
constructor Create(const ASourcePath, ATargetPath: string;
const AFunctionName: string = ''; const ATargetClassName: string = ''); overload;
constructor Create(const Enabled: Boolean; const ASourcePath, ATargetPath: string;
const AFunctionName: string = ''; const ATargetClassName: string = ''); overload;
property FunctionName: string read FFunctionName;
property SourcePath: string read FSourcePath;
property TargetPath: string read FTargetPath;
end;
BindFieldAttribute = class(FieldBindAttribute);
BindFieldFromAttribute = class(FieldBindAttribute);
BindFieldToAttribute = class(FieldBindAttribute);
{Ancestor class for fields and properties bind data}
PropertiesBindAttribute = class(CustomBindAttribute)
private
{Name of the validator function}
FFunctionName: string;
{Name of field or property in target class}
FTargetName: string;
public
constructor Create(const ATargetName: string;
const AFunctionName: string = ''; const ATargetClassName: string = ''); overload;
constructor Create(const Enabled: Boolean; const ATargetName: string;
const AFunctionName: string = ''; const ATargetClassName: string = ''); overload;
property FunctionName: string read FFunctionName;
property TargetClassName: string read FTargetClassName;
property TargetName: string read FTargetName;
end;
// PropertiesBindAttribute = class(AutoBindingAttribute);
BindPropertyAttribute = class(PropertiesBindAttribute);
BindPropertyFromAttribute = class(PropertiesBindAttribute);
BindPropertyToAttribute = class(PropertiesBindAttribute);
implementation
{ ClassBindAttribute }
{Syntax: [ClassBind(True, 'MyBindTargetClass')]}
constructor ClassBindAttribute.Create(const Enabled: Boolean;
ATargetClassName: string; IsDefaultClass: Boolean = False);
begin
FIsDefault := IsDefaultClass;
FTargetClassName := ATargetClassName;
FIsEnabled := Enabled;
end;
constructor ClassBindAttribute.Create(ATargetClassName: string;
IsDefaultClass: Boolean = False);
begin
FIsDefault := IsDefaultClass;
FTargetClassName := ATargetClassName;
FIsEnabled := True;
end;
{ FieldBindAttribute }
{Example: [BindFormField(True, 'myComponent.Property', 'MyTargetProperty')]}
constructor FieldBindAttribute.Create(const Enabled: Boolean; const ASourcePath,
ATargetPath: string; const AFunctionName: string = ''; const ATargetClassName: string = '');
begin
FIsEnabled := Enabled;
FFunctionName := AFunctionName;
FSourcePath := ASourcePath;
FTargetPath := ATargetPath;
FTargetClassName := ATargetClassName; // if empty, use the class name from ClassBindAttribute
end;
constructor FieldBindAttribute.Create(const ASourcePath, ATargetPath,
AFunctionName, ATargetClassName: string);
begin
FIsEnabled := True;
FFunctionName := AFunctionName;
FSourcePath := ASourcePath;
FTargetPath := ATargetPath;
FTargetClassName := ATargetClassName; // if empty, use the class name from ClassBindAttribute
end;
{ MethodBindAttribute }
{Example: [MethodBind(True, 'myPublicMethod', 'NewMethod')]}
{Example: [EventBind(True, 'Button1.OnClick', 'NewEventHandler'))]}
constructor MethodBindAttribute.Create(const Enabled: Boolean;
const AMethodName, ANewMethodName: string);
begin
FIsEnabled := Enabled;
FSourceMethodName := AMethodName;
FNewMethodName := ANewMethodName;
FTargetClassName := ''; // if empty, use the class name from ClassBindAttribute
end;
{Example: [MethodBind(True, 'myPublicMethod', 'NewMethod', 'NameOfClassExposingNewMethod')]}
constructor MethodBindAttribute.Create(const Enabled: Boolean;
const AMethodName, ANewMethodName, ATargetClassName: string);
begin
FIsEnabled := Enabled;
FSourceMethodName := AMethodName;
FNewMethodName := ANewMethodName;
FTargetClassName := ATargetClassName; // if empty, use the class name from ClassBindAttribute
end;
{ PropertiesBindAttribute }
{Example: [BindPropertyAttribute, (True, 'PropertyOfBindedClass', 'BindedClass')]}
{Example: [BindFieldFromAttribute, (True, 'FieldOfBindedClass')]}
constructor PropertiesBindAttribute.Create(const Enabled: Boolean;
const ATargetName: string; const AFunctionName: string = '';
const ATargetClassName: string = '');
begin
FIsEnabled := Enabled;
FFunctionName := AFunctionName;
FTargetName := ATargetName;
FTargetClassName := ATargetClassName; // if empty, use the class name from ClassBindAttribute
end;
constructor PropertiesBindAttribute.Create(const ATargetName, AFunctionName,
ATargetClassName: string);
begin
FIsEnabled := True;
FFunctionName := AFunctionName;
FTargetName := ATargetName;
FTargetClassName := ATargetClassName; // if empty, use the class name from ClassBindAttribute
end;
end.
|
unit NtUtils.Processes.Create.Win32;
{
The module provides support for process creation via a Win32 API.
}
interface
uses
Ntapi.ntseapi, NtUtils, NtUtils.Processes.Create;
// Create a new process via CreateProcessAsUserW
[SupportedOption(spoCurrentDirectory)]
[SupportedOption(spoSuspended)]
[SupportedOption(spoInheritHandles)]
[SupportedOption(spoBreakawayFromJob)]
[SupportedOption(spoForceBreakaway)]
[SupportedOption(spoNewConsole)]
[SupportedOption(spoRunAsInvoker)]
[SupportedOption(spoIgnoreElevation)]
[SupportedOption(spoEnvironment)]
[SupportedOption(spoSecurity)]
[SupportedOption(spoWindowMode)]
[SupportedOption(spoDesktop)]
[SupportedOption(spoToken)]
[SupportedOption(spoParentProcess)]
[SupportedOption(spoJob)]
[SupportedOption(spoHandleList)]
[SupportedOption(spoMitigationPolicies)]
[SupportedOption(spoChildPolicy)]
[SupportedOption(spoLPAC)]
[SupportedOption(spoAppContainer)]
[SupportedOption(spoPackage)]
[SupportedOption(spoPackageBreakaway)]
[SupportedOption(spoProtection)]
[RequiredPrivilege(SE_ASSIGN_PRIMARY_TOKEN_PRIVILEGE, rpSometimes)]
[RequiredPrivilege(SE_TCB_PRIVILEGE, rpSometimes)]
function AdvxCreateProcess(
const Options: TCreateProcessOptions;
out Info: TProcessInfo
): TNtxStatus;
// Create a new process via CreateProcessWithTokenW
[SupportedOption(spoCurrentDirectory)]
[SupportedOption(spoSuspended)]
[SupportedOption(spoEnvironment)]
[SupportedOption(spoWindowMode)]
[SupportedOption(spoDesktop)]
[SupportedOption(spoToken, omRequired)]
[RequiredPrivilege(SE_IMPERSONATE_PRIVILEGE, rpAlways)]
function AdvxCreateProcessWithToken(
const Options: TCreateProcessOptions;
out Info: TProcessInfo
): TNtxStatus;
// Create a new process via CreateProcessWithLogonW
[SupportedOption(spoCurrentDirectory)]
[SupportedOption(spoSuspended)]
[SupportedOption(spoEnvironment)]
[SupportedOption(spoWindowMode)]
[SupportedOption(spoDesktop)]
[SupportedOption(spoCredentials, omRequired)]
function AdvxCreateProcessWithLogon(
const Options: TCreateProcessOptions;
out Info: TProcessInfo
): TNtxStatus;
implementation
uses
Ntapi.WinNt, Ntapi.ntstatus, Ntapi.ntpsapi, Ntapi.WinBase, Ntapi.WinUser,
Ntapi.ProcessThreadsApi, NtUtils.Objects, NtUtils.Tokens,
DelphiUtils.AutoObjects;
{$BOOLEVAL OFF}
{$IFOPT R+}{$DEFINE R+}{$ENDIF}
{$IFOPT Q+}{$DEFINE Q+}{$ENDIF}
{ Process-thread attributes }
type
IPtAttributes = IMemory<PProcThreadAttributeList>;
TPtAutoMemory = class (TAutoMemory, IMemory)
Options: TCreateProcessOptions;
hParent: THandle;
HandleList: TArray<THandle>;
Capabilities: TArray<TSidAndAttributes>;
Security: TSecurityCapabilities;
AllAppPackages: TProcessAllPackagesFlags;
hJob: THandle;
ExtendedFlags: TProcExtendedFlag;
ChildPolicy: TProcessChildFlags;
Protection: TProtectionLevel;
Initilalized: Boolean;
procedure Release; override;
end;
procedure TPtAutoMemory.Release;
begin
if Assigned(FData) and Initilalized then
DeleteProcThreadAttributeList(FData);
// Call the inherited memory deallocation
inherited;
end;
function RtlxpUpdateProcThreadAttribute(
[in, out] AttributeList: PProcThreadAttributeList;
Attribute: NativeUInt;
const Value;
Size: NativeUInt
): TNtxStatus;
begin
Result.Location := 'UpdateProcThreadAttribute';
Result.LastCall.UsesInfoClass(TProcThreadAttributeNum(Attribute and
PROC_THREAD_ATTRIBUTE_NUMBER), icSet);
Result.Win32Result := UpdateProcThreadAttribute(AttributeList, 0, Attribute,
@Value, Size, nil, nil);
end;
function AllocPtAttributes(
const Options: TCreateProcessOptions;
out xMemory: IPtAttributes
): TNtxStatus;
var
PtAttributes: TPtAutoMemory;
Required: NativeUInt;
Count: Integer;
i: Integer;
begin
// Count the applied attributes
Count := 0;
if Assigned(Options.hxParentProcess) then
Inc(Count);
if (Options.Mitigations <> 0) or (Options.Mitigations2 <> 0) then
Inc(Count);
if HasAny(Options.ChildPolicy) then
Inc(Count);
if Length(Options.HandleList) > 0 then
Inc(Count);
if Assigned(Options.AppContainer) then
Inc(Count);
if poLPAC in Options.Flags then
Inc(Count);
if Options.PackageName <> '' then
Inc(Count);
if HasAny(Options.PackageBreaway) then
Inc(Count);
if Assigned(Options.hxJob) then
Inc(Count);
if [poIgnoreElevation, poForceBreakaway] * Options.Flags <> [] then
Inc(Count);
if poUseProtection in Options.Flags then
Inc(Count);
if Count = 0 then
begin
xMemory := nil;
Result.Status := STATUS_SUCCESS;
Exit;
end;
// Determine the required size
Result.Location := 'InitializeProcThreadAttributeList';
Result.Win32Result := InitializeProcThreadAttributeList(nil, Count, 0,
Required);
if Result.Status <> STATUS_BUFFER_TOO_SMALL then
Exit;
// Allocate and initialize
PtAttributes := TPtAutoMemory.Allocate(Required);
IMemory(xMemory) := PtAttributes;
Result.Win32Result := InitializeProcThreadAttributeList(xMemory.Data, Count,
0, Required);
// NOTE: Since ProcThreadAttributeList stores pointers istead of the actual
// data, we need to make sure it does not go anywhere.
if Result.IsSuccess then
PtAttributes.Initilalized := True
else
Exit;
// Prolong lifetime of the options
PtAttributes.Options := Options;
// Parent process
if Assigned(Options.hxParentProcess) then
begin
PtAttributes.hParent := Options.hxParentProcess.Handle;
Result := RtlxpUpdateProcThreadAttribute(xMemory.Data,
PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, PtAttributes.hParent,
SizeOf(THandle));
if not Result.IsSuccess then
Exit;
end;
// Mitigation policies
if (Options.Mitigations <> 0) or (Options.Mitigations2 <> 0) then
begin
// The size might be 32, 64, or 128 bits
if Options.Mitigations2 = 0 then
begin
if Options.Mitigations and $FFFFFFFF00000000 <> 0 then
Required := SizeOf(UInt64)
else
Required := SizeOf(Cardinal);
end
else
Required := 2 * SizeOf(UInt64);
Result := RtlxpUpdateProcThreadAttribute(xMemory.Data,
PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY,
PtAttributes.Options.Mitigations, Required);
if not Result.IsSuccess then
Exit;
end;
// Child process policy
if HasAny(Options.ChildPolicy) then
begin
Result := RtlxpUpdateProcThreadAttribute(xMemory.Data,
PROC_THREAD_ATTRIBUTE_CHILD_PROCESS_POLICY,
PtAttributes.Options.ChildPolicy, SizeOf(Cardinal));
if not Result.IsSuccess then
Exit;
end;
// Inherited handle list
if Length(Options.HandleList) > 0 then
begin
SetLength(PtAttributes.HandleList, Length(Options.HandleList));
for i := 0 to High(Options.HandleList) do
PtAttributes.HandleList[i] := Options.HandleList[i].Handle;
Result := RtlxpUpdateProcThreadAttribute(xMemory.Data,
PROC_THREAD_ATTRIBUTE_HANDLE_LIST, PtAttributes.HandleList,
SizeOf(THandle) * Length(Options.HandleList));
if not Result.IsSuccess then
Exit;
end;
// AppContainer
if Assigned(Options.AppContainer) then
begin
with PtAttributes.Security do
begin
AppContainerSid := Options.AppContainer.Data;
CapabilityCount := Length(Options.Capabilities);
SetLength(PtAttributes.Capabilities, Length(Options.Capabilities));
for i := 0 to High(Options.Capabilities) do
begin
PtAttributes.Capabilities[i].Sid := Options.Capabilities[i].Sid.Data;
PtAttributes.Capabilities[i].Attributes := Options.Capabilities[i].
Attributes;
end;
Capabilities := Pointer(@PtAttributes.Capabilities);
end;
Result := RtlxpUpdateProcThreadAttribute(xMemory.Data,
PROC_THREAD_ATTRIBUTE_SECURITY_CAPABILITIES, PtAttributes.Security,
SizeOf(TSecurityCapabilities));
if not Result.IsSuccess then
Exit;
end;
// Low privileged AppContainer
if poLPAC in Options.Flags then
begin
PtAttributes.AllAppPackages :=
PROCESS_CREATION_ALL_APPLICATION_PACKAGES_OPT_OUT;
Result := RtlxpUpdateProcThreadAttribute(xMemory.Data,
PROC_THREAD_ATTRIBUTE_ALL_APPLICATION_PACKAGES_POLICY,
PtAttributes.AllAppPackages, SizeOf(TProcessAllPackagesFlags));
if not Result.IsSuccess then
Exit;
end;
// Package name
if Options.PackageName <> '' then
begin
Result := RtlxpUpdateProcThreadAttribute(xMemory.Data,
PROC_THREAD_ATTRIBUTE_PACKAGE_NAME,
PWideChar(PtAttributes.Options.PackageName)^,
Length(PtAttributes.Options.PackageName) * SizeOf(WideChar));
if not Result.IsSuccess then
Exit;
end;
// Package breakaway (aka Desktop App Policy)
if HasAny(Options.PackageBreaway) then
begin
Result := RtlxpUpdateProcThreadAttribute(xMemory.Data,
PROC_THREAD_ATTRIBUTE_DESKTOP_APP_POLICY,
PtAttributes.Options.PackageBreaway, SizeOf(TProcessDesktopAppFlags));
if not Result.IsSuccess then
Exit;
end;
// Job list
if Assigned(Options.hxJob) then
begin
PtAttributes.hJob := Options.hxJob.Handle;
Result := RtlxpUpdateProcThreadAttribute(xMemory.Data,
PROC_THREAD_ATTRIBUTE_JOB_LIST, PtAttributes.hJob, SizeOf(THandle));
if not Result.IsSuccess then
Exit;
end;
// Extended attributes
if [poIgnoreElevation, poForceBreakaway] * Options.Flags <> [] then
begin
PtAttributes.ExtendedFlags := 0;
if poIgnoreElevation in Options.Flags then
PtAttributes.ExtendedFlags := PtAttributes.ExtendedFlags or
EXTENDED_PROCESS_CREATION_FLAG_FORCELUA;
if poForceBreakaway in Options.Flags then
PtAttributes.ExtendedFlags := PtAttributes.ExtendedFlags or
EXTENDED_PROCESS_CREATION_FLAG_FORCE_BREAKAWAY;
Result := RtlxpUpdateProcThreadAttribute(xMemory.Data,
PROC_THREAD_ATTRIBUTE_EXTENDED_FLAGS, PtAttributes.ExtendedFlags,
SizeOf(TProcExtendedFlag));
if not Result.IsSuccess then
Exit;
end;
if poUseProtection in Options.Flags then
begin
PtAttributes.Protection := Options.Protection;
Result := RtlxpUpdateProcThreadAttribute(xMemory.Data,
PROC_THREAD_ATTRIBUTE_PROTECTION_LEVEL, PtAttributes.Protection,
SizeOf(TProtectionLevel));
if not Result.IsSuccess then
Exit;
end;
end;
{ Startup info preparation and supplimentary routines }
function RefSA(
out SA: TSecurityAttributes;
const SD: ISecurityDescriptor
): PSecurityAttributes;
begin
if Assigned(SD) then
begin
SA.Length := SizeOf(SA);
SA.SecurityDescriptor := SD.Data;
SA.InheritHandle := False;
Result := @SA;
end
else
Result := nil;
end;
procedure PrepareStartupInfo(
out SI: TStartupInfoW;
out CreationFlags: TProcessCreateFlags;
const Options: TCreateProcessOptions
);
begin
SI := Default(TStartupInfoW);
SI.cb := SizeOf(SI);
CreationFlags := 0;
SI.Desktop := RefStrOrNil(Options.Desktop);
// Suspended state
if poSuspended in Options.Flags then
CreationFlags := CreationFlags or CREATE_SUSPENDED;
// Job escaping
if poBreakawayFromJob in Options.Flags then
CreationFlags := CreationFlags or CREATE_BREAKAWAY_FROM_JOB;
// Console
if poNewConsole in Options.Flags then
CreationFlags := CreationFlags or CREATE_NEW_CONSOLE;
// Environment
if Assigned(Options.Environment) then
CreationFlags := CreationFlags or CREATE_UNICODE_ENVIRONMENT;
// Window show mode
if poUseWindowMode in Options.Flags then
begin
SI.ShowWindow := TShowMode16(Word(Options.WindowMode));
SI.Flags := SI.Flags or STARTF_USESHOWWINDOW;
end;
// Process protection
if poUseProtection in Options.Flags then
CreationFlags := CreationFlags or CREATE_PROTECTED_PROCESS;
end;
procedure CaptureResult(
var Info: TProcessInfo;
const ProcessInfo: TProcessInformation
);
begin
Info.ValidFields := Info.ValidFields + [piProcessId, piThreadId,
piProcessHandle, piThreadHandle];
Info.ClientId.UniqueProcess := ProcessInfo.ProcessId;
Info.ClientId.UniqueThread := ProcessInfo.ThreadId;
Info.hxProcess := Auto.CaptureHandle(ProcessInfo.hProcess);
Info.hxThread := Auto.CaptureHandle(ProcessInfo.hThread);
end;
{ Public functions }
function AdvxCreateProcess;
var
CreationFlags: TProcessCreateFlags;
ProcessSA, ThreadSA: TSecurityAttributes;
hxExpandedToken: IHandle;
CommandLine: String;
SI: TStartupInfoExW;
PTA: IPtAttributes;
ProcessInfo: TProcessInformation;
RunAsInvoker: IAutoReleasable;
begin
Info := Default(TProcessInfo);
PrepareStartupInfo(SI.StartupInfo, CreationFlags, Options);
// Prepare process-thread attribute list
Result := AllocPtAttributes(Options, PTA);
if not Result.IsSuccess then
Exit;
if Assigned(PTA) then
begin
// Use -Ex vertion and include attributes
SI.StartupInfo.cb := SizeOf(TStartupInfoExW);
SI.AttributeList := PTA.Data;
CreationFlags := CreationFlags or EXTENDED_STARTUPINFO_PRESENT;
end;
// Allow using pseudo-tokens
hxExpandedToken := Options.hxToken;
Result := NtxExpandToken(hxExpandedToken, TOKEN_CREATE_PROCESS);
if not Result.IsSuccess then
Exit;
// Allow running as invoker
Result := RtlxApplyCompatLayer(poRunAsInvokerOn in Options.Flags,
poRunAsInvokerOff in Options.Flags, RunAsInvoker);
if not Result.IsSuccess then
Exit;
// CreateProcess needs the command line to be in writable memory
CommandLine := Options.CommandLine;
UniqueString(CommandLine);
Result.Location := 'CreateProcessAsUserW';
if Assigned(Options.hxToken) then
begin
Result.LastCall.ExpectedPrivilege := SE_ASSIGN_PRIMARY_TOKEN_PRIVILEGE;
Result.LastCall.Expects<TTokenAccessMask>(TOKEN_CREATE_PROCESS);
end;
if Assigned(Options.hxParentProcess) then
Result.LastCall.Expects<TProcessAccessMask>(PROCESS_CREATE_PROCESS);
if Assigned(Options.hxJob) then
Result.LastCall.Expects<TJobObjectAccessMask>(JOB_OBJECT_ASSIGN_PROCESS);
if poForceBreakaway in Options.Flags then
Result.LastCall.ExpectedPrivilege := SE_TCB_PRIVILEGE;
Result.Win32Result := CreateProcessAsUserW(
HandleOrDefault(hxExpandedToken),
RefStrOrNil(Options.ApplicationWin32),
RefStrOrNil(CommandLine),
RefSA(ProcessSA, Options.ProcessSecurity),
RefSA(ThreadSA, Options.ThreadSecurity),
poInheritHandles in Options.Flags,
CreationFlags,
Auto.RefOrNil<PEnvironment>(Options.Environment),
RefStrOrNil(Options.CurrentDirectory),
SI,
ProcessInfo
);
if Result.IsSuccess then
CaptureResult(Info, ProcessInfo);
end;
function AdvxCreateProcessWithToken;
var
hxExpandedToken: IHandle;
CreationFlags: TProcessCreateFlags;
StartupInfo: TStartupInfoW;
ProcessInfo: TProcessInformation;
begin
Info := Default(TProcessInfo);
PrepareStartupInfo(StartupInfo, CreationFlags, Options);
hxExpandedToken := Options.hxToken;
if Assigned(hxExpandedToken) then
begin
// Allow using pseudo-handles
Result := NtxExpandToken(hxExpandedToken, TOKEN_CREATE_PROCESS);
if not Result.IsSuccess then
Exit;
end;
Result.Location := 'CreateProcessWithTokenW';
Result.LastCall.ExpectedPrivilege := SE_IMPERSONATE_PRIVILEGE;
if Assigned(Options.hxToken) then
Result.LastCall.Expects<TTokenAccessMask>(TOKEN_CREATE_PROCESS);
Result.Win32Result := CreateProcessWithTokenW(
HandleOrDefault(hxExpandedToken),
Options.LogonFlags,
RefStrOrNil(Options.ApplicationWin32),
RefStrOrNil(Options.CommandLine),
CreationFlags,
Auto.RefOrNil<PEnvironment>(Options.Environment),
RefStrOrNil(Options.CurrentDirectory),
StartupInfo,
ProcessInfo
);
if Result.IsSuccess then
CaptureResult(Info, ProcessInfo);
end;
function AdvxCreateProcessWithLogon;
var
CreationFlags: TProcessCreateFlags;
StartupInfo: TStartupInfoW;
ProcessInfo: TProcessInformation;
begin
Info := Default(TProcessInfo);
PrepareStartupInfo(StartupInfo, CreationFlags, Options);
Result.Location := 'CreateProcessWithLogonW';
Result.Win32Result := CreateProcessWithLogonW(
RefStrOrNil(Options.Username),
RefStrOrNil(Options.Domain),
RefStrOrNil(Options.Password),
Options.LogonFlags,
RefStrOrNil(Options.ApplicationWin32),
RefStrOrNil(Options.CommandLine),
CreationFlags,
Auto.RefOrNil<PEnvironment>(Options.Environment),
RefStrOrNil(Options.CurrentDirectory),
StartupInfo,
ProcessInfo
);
if Result.IsSuccess then
CaptureResult(Info, ProcessInfo);
end;
end.
|
unit AqDrop.DB.DBX.FB;
{$I '..\Core\AqDrop.Core.Defines.Inc'}
interface
uses
Data.DBXCommon,
{$IFNDEF AQMOBILE}
Data.DBXFirebird,
{$ENDIF}
AqDrop.DB.Connection,
AqDrop.DB.DBX,
AqDrop.DB.SQL.Intf,
AqDrop.DB.Adapter;
type
TAqDBXFBDataConverter = class(TAqDBXDataConverter)
public
procedure BooleanToParameter(const pParameter: TDBXParameter; const pValue: Boolean); override;
end;
TAqDBXFBAdapter = class(TAqDBXAdapter)
strict protected
function GetAutoIncrementType: TAqDBAutoIncrementType; override;
class function GetDefaultConverter: TAqDBXDataConverterClass; override;
class function GetDefaultSolver: TAqDBSQLSolverClass; override;
end;
TAqDBXFBConnection = class(TAqDBXCustomConnection)
strict protected
function GetPropertyValueAsString(const pIndex: Int32): string; override;
procedure SetPropertyValueAsString(const pIndex: Int32; const pValue: string); override;
class function GetDefaultAdapter: TAqDBAdapterClass; override;
public
constructor Create; override;
property DataBase: string index $80 read GetPropertyValueAsString write SetPropertyValueAsString;
property UserName: string index $81 read GetPropertyValueAsString write SetPropertyValueAsString;
property Password: string index $82 read GetPropertyValueAsString write SetPropertyValueAsString;
end;
implementation
uses
System.SysUtils,
AqDrop.Core.Exceptions,
AqDrop.Core.Helpers,
AqDrop.DB.Types,
AqDrop.DB.FB;
{ TAqDBXFBConnection }
constructor TAqDBXFBConnection.Create;
begin
inherited;
Self.DriverName := 'Firebird';
Self.VendorLib := 'fbclient.dll';
Self.LibraryName := 'dbxfb.dll';
Self.GetDriverFunc := 'getSQLDriverINTERBASE';
end;
class function TAqDBXFBConnection.GetDefaultAdapter: TAqDBAdapterClass;
begin
Result := TAqDBXFBAdapter;
end;
function TAqDBXFBConnection.GetPropertyValueAsString(const pIndex: Int32): string;
begin
case pIndex of
$80:
Result := Properties[TDBXPropertyNames.Database];
$81:
Result := Properties[TDBXPropertyNames.UserName];
$82:
Result := Properties[TDBXPropertyNames.Password];
else
Result := inherited;
end;
end;
procedure TAqDBXFBConnection.SetPropertyValueAsString(const pIndex: Int32; const pValue: string);
begin
case pIndex of
$80:
Properties[TDBXPropertyNames.Database] := pValue;
$81:
Properties[TDBXPropertyNames.UserName] := pValue;
$82:
Properties[TDBXPropertyNames.Password] := pValue;
else
inherited;
end;
end;
{ TAqDBXFBDataConverter }
procedure TAqDBXFBDataConverter.BooleanToParameter(const pParameter: TDBXParameter; const pValue: Boolean);
begin
{$IF AQMOBILE}
pParameter.DataType := TDBXDataTypes.AnsiStringType;
if pValue then
begin
pParameter.Value.SetAnsiString('1');
end else begin
pParameter.Value.SetAnsiString('0');
end;
{$ELSE}
pParameter.DataType := TDBXDataTypes.WideStringType;
if pValue then
begin
pParameter.Value.SetString('1');
end else begin
pParameter.Value.SetString('0');
end;
{$ENDIF}
end;
{ TAqDBXFBAdapter }
function TAqDBXFBAdapter.GetAutoIncrementType: TAqDBAutoIncrementType;
begin
Result := TAqDBAutoIncrementType.aiGenerator;
end;
class function TAqDBXFBAdapter.GetDefaultConverter: TAqDBXDataConverterClass;
begin
Result := TAqDBXFBDataConverter;
end;
class function TAqDBXFBAdapter.GetDefaultSolver: TAqDBSQLSolverClass;
begin
Result := TAqDBFBSQLSolver;
end;
end.
|
unit TarFTP.Model;
interface
uses
SysUtils, TarFTP.Interfaces, TarFTP.MVC,
TarFTP.Tasks;
type
TCompressCommand = class(TCommand)
private
FArchiver: IArchiver;
FOnFileCompress: TWorkProgressEvent;
FOutputFile: String;
procedure FileProgress(CurrentItem, TotalItems : Integer;
BytesProcessed, TotalBytes : Int64);
public
{ ICommand }
procedure Execute(const Task: ITask); override;
{ Common }
constructor Create(const Archiver: IArchiver; const OutputFile: String;
OnFileCompress: TWorkProgressEvent);
destructor Destroy; override;
end;
TUploadCommand = class(TCommand)
private
FFileToUpload: String;
FFtpSender: IFtpSender;
FHost: String;
FOnFileUpload: TWorkProgressEvent;
FPassword: String;
FUserName: String;
FTask : ITask;
FAborted : Boolean;
procedure FileProgress(CurrentItem, TotalItems : Integer;
BytesProcessed, TotalBytes : Int64);
public
{ ICommand }
procedure Execute(const Task: ITask); override;
{ Common }
constructor Create(const FtpSender: IFtpSender;
const Host, UserName, Password, FileToUpload: String;
OnFileUpload: TWorkProgressEvent);
destructor Destroy; override;
end;
TModel = class(TInterfacedObject, IModel)
private
FArchiver: IArchiver;
FFtpSender: IFtpSender;
FOnFileCompress : TWorkProgressEvent;
FOnFileUpload : TWorkProgressEvent;
FOnTaskEvent : TModelNotifyEvent;
FOutputFile : String;
FHost : String;
FUserName : String;
FPassword : String;
FTask : ITask;
FActiveTask : TTaskKind;
FFactory : IFactory;
FForcedTerminate : Boolean;
FTerminated: Boolean;
procedure DoTaskEvent(Task : TTaskKind; State : TTaskState);
procedure CompressionComplete(const Task : ITask);
procedure CompressionStart(const Task: ITask);
procedure UploadingComplete(const Task: ITask);
procedure UploadingStart(const Task: ITask);
public
{ IModel }
function GetOnFileCompress : TWorkProgressEvent;
procedure SetOnFileCompress(Value : TWorkProgressEvent);
property OnFileCompress : TWorkProgressEvent read GetOnFileCompress
write SetOnFileCompress;
function GetOnFileUpload : TWorkProgressEvent;
procedure SetOnFileUpload(Value : TWorkProgressEvent);
property OnFileUpload : TWorkProgressEvent read GetOnFileUpload
write SetOnFileUpload;
function GetOnTaskEvent : TModelNotifyEvent;
procedure SetOnTaskEvent(Value : TModelNotifyEvent);
property OnTaskEvent : TModelNotifyEvent read GetOnTaskEvent
write SetOnTaskEvent;
function GetTerminated : Boolean;
property Terminated : Boolean read GetTerminated;
function GetError : Boolean;
property Error: Boolean read GetError;
procedure Reset;
procedure AddFile(const FileName : String);
procedure SetOutputFile(const OutputFile : String);
procedure SetFtpCredentials(const Host, Login, Password: string);
procedure NeedError;
procedure Compress;
procedure Upload;
procedure TerminateTask;
procedure ForcedTerminateTask;
{ Common }
constructor Create(Factory: IFactory);
destructor Destroy; override;
end;
implementation
{ TModel }
procedure TModel.AddFile(const FileName: String);
begin
FArchiver.AddFile( FileName );
end;
procedure TModel.Compress;
begin
if FActiveTask <> tkUndefined then
raise Exception.Create( 'Can not compress files while another ' +
'task is running' );
FActiveTask := tkCompress;
FTask.OnTaskStart := Self.CompressionStart;
FTask.OnTaskComplete := Self.CompressionComplete;
FTask.Run(
TCompressCommand.Create( FArchiver, FOutputFile, FOnFileCompress )
);
end;
procedure TModel.CompressionComplete(const Task: ITask);
begin
FActiveTask := tkUndefined;
DoTaskEvent( tkCompress, tsAfterFinished );
end;
constructor TModel.Create(Factory: IFactory);
begin
Assert( Assigned( Factory ), 'Factory is unassigned' );
FArchiver := Factory.CreateArchiver;
FFtpSender := Factory.CreateFtpSender;
FTask := Factory.CreateTask;
FFactory := Factory;
end;
destructor TModel.Destroy;
begin
FArchiver := nil;
FFtpSender := nil;
FTask := nil;
FFactory := nil;
inherited;
end;
procedure TModel.CompressionStart(const Task: ITask);
begin
DoTaskEvent( tkCompress, tsBeforeStarted );
end;
procedure TModel.DoTaskEvent(Task: TTaskKind; State: TTaskState);
begin
if Assigned( FOnTaskEvent ) then
FOnTaskEvent( Task, State );
end;
procedure TModel.ForcedTerminateTask;
begin
FForcedTerminate := True;
FTask.ForcedTerminate;
end;
function TModel.GetError: Boolean;
begin
Result := FTask.Error <> nil;
end;
function TModel.GetOnFileCompress: TWorkProgressEvent;
begin
Result := FOnFileCompress;
end;
function TModel.GetOnFileUpload: TWorkProgressEvent;
begin
Result := FOnFileUpload;
end;
function TModel.GetOnTaskEvent: TModelNotifyEvent;
begin
Result := FOnTaskEvent;
end;
function TModel.GetTerminated: Boolean;
begin
Result := FTerminated or FForcedTerminate;
end;
procedure TModel.NeedError;
begin
if not FForcedTerminate and Assigned( FTask.Error ) then
raise FTask.Error.Create( FTask.ErrorMessage );
end;
procedure TModel.Reset;
begin
if FActiveTask <> tkUndefined then
raise Exception.Create( 'Can not reset model while any ' +
'task is running' );
FTerminated := False;
FForcedTerminate := False;
FTask := FFactory.CreateTask;
end;
procedure TModel.SetFtpCredentials(const Host, Login, Password: string);
begin
FHost := Host;
FUserName := Login;
FPassword := Password;
end;
procedure TModel.SetOnFileCompress(Value: TWorkProgressEvent);
begin
FOnFileCompress := Value;
end;
procedure TModel.SetOnFileUpload(Value: TWorkProgressEvent);
begin
FOnFileUpload := Value;
end;
procedure TModel.SetOnTaskEvent(Value: TModelNotifyEvent);
begin
FOnTaskEvent := Value;
end;
procedure TModel.SetOutputFile(const OutputFile: String);
begin
FOutputFile := OutputFile;
end;
procedure TModel.TerminateTask;
begin
FTerminated := True;
FTask.Terminate;
end;
procedure TModel.Upload;
begin
if FActiveTask <> tkUndefined then
raise Exception.Create( 'Can not upload files while another ' +
'task is running' );
FActiveTask := tkUpload;
FTask.OnTaskStart := Self.UploadingStart;
FTask.OnTaskComplete := Self.UploadingComplete;
FTask.Run(
TUploadCommand.Create(
FFtpSender, FHost, FUserName, FPassword, FOutputFile,
FOnFileUpload
)
);
end;
procedure TModel.UploadingComplete(const Task: ITask);
begin
DoTaskEvent( tkUpload, tsAfterFinished );
FActiveTask := tkUndefined;
end;
procedure TModel.UploadingStart(const Task: ITask);
begin
DoTaskEvent( tkUpload, tsBeforeStarted );
end;
{ TCompressCommand }
constructor TCompressCommand.Create(const Archiver: IArchiver; const
OutputFile: String; OnFileCompress: TWorkProgressEvent);
begin
Assert( Assigned( Archiver ), 'Archiver is unassigned' );
FArchiver := Archiver;
FArchiver.OnProgress := FileProgress;
FOutputFile := OutputFile;
FOnFileCompress := OnFileCompress;
end;
destructor TCompressCommand.Destroy;
begin
if Assigned( FArchiver ) then
FArchiver.OnProgress := nil;
FArchiver := nil;
inherited;
end;
procedure TCompressCommand.Execute(const Task: ITask);
begin
FArchiver.CompressToFile( FOutputFile );
end;
procedure TCompressCommand.FileProgress(CurrentItem, TotalItems: Integer;
BytesProcessed, TotalBytes: Int64);
begin
if Assigned( FOnFileCompress ) then
FOnFileCompress(
CurrentItem, TotalItems, BytesProcessed, TotalBytes
);
end;
{ TUploadCommand }
constructor TUploadCommand.Create(const FtpSender: IFtpSender; const Host,
UserName, Password, FileToUpload: String; OnFileUpload: TWorkProgressEvent);
begin
Assert( Assigned( FtpSender ), 'FtpSender is unassigned' );
FFtpSender := FtpSender;
FFtpSender.OnProgress := FileProgress;
FHost := Host;
FUserName := UserName;
FPassword := Password;
FFileToUpload := FileToUpload;
FOnFileUpload := OnFileUpload;
end;
destructor TUploadCommand.Destroy;
begin
FFtpSender.OnProgress := nil;
FFtpSender := nil;
FTask := nil;
inherited;
end;
procedure TUploadCommand.Execute(const Task: ITask);
begin
FTask := Task;
FAborted := False;
FFtpSender.LogIn( FHost, FUserName, FPassword );
try
FFtpSender.UploadFile( FFileToUpload );
finally
if not FAborted then FFtpSender.Disconnect;
end;
end;
procedure TUploadCommand.FileProgress(CurrentItem, TotalItems: Integer;
BytesProcessed, TotalBytes: Int64);
begin
if Assigned( FOnFileUpload ) then
FOnFileUpload(
CurrentItem, TotalItems, BytesProcessed, TotalBytes
);
if FTask.Terminated and not FAborted then
begin
FAborted := True;
FFtpSender.Abort;
end;
end;
end.
|
unit FactoryMethod.Creators.Creator;
interface
uses
FactoryMethod.Interfaces.IProduct, FactoryMethod.Interfaces.ICreator;
// The Creator class declares the factory method that is supposed to return
// an object of a Product class. The Creator's subclasses usually provide
// the implementation of this method.
type
TCreator = class(TInterfacedObject, ICreator)
public
function FactoryMethod: IProduct; virtual; abstract;
// Also note that, despite its name, the Creator's primary
// responsibility is not creating products. Usually, it contains some
// core business logic that relies on Product objects, returned by the
// factory method. Subclasses can indirectly change that business logic
// by overriding the factory method and returning a different type of
// product from it.
// Também note que, apesar do nome, a responsablilidade primaria do creator não é criar produtos.
// Geralmente ele contém algun código de negocio que depende do objeto produto retornado pelo método
// Subclasses podem indiretamente mudar esssas regras subescrevendo o Factory method e retornando um
// diverente tipo de produto.
function SomeOperation: string; virtual;
end;
implementation
uses
System.SysUtils;
{ TCreator }
function TCreator.SomeOperation: string;
var
oProduct: IProduct;
begin
// Call the factory method to create a Product object.
// Chama o factory method para criar o objeto produto
oProduct := FactoryMethod();
// Now, use the product.
// Agora usa o produto
Result := 'Creator: The same Creators code has just worked with ' +
oProduct.Operation();
end;
end.
|
{***********************************************
from wikipedia
https://en.wikipedia.org/wiki/Cubic_function
//**************************************************
}
unit Equation_Solver;
interface
uses Z_class_u,sysutils,classes;
type
TrootsEquation=array of TZNumber;
//------------------abstarct type------------------------
TEquationAbstarct=class
private
FEquationFormla:String;
FEquaionStaps:TStringList;
FEquationDegree:word;
FEquationName:string;
procedure setEqDegree(const Value: word);
procedure setEqName(const Value: string);
procedure setFormla(const Value: string);
public
constructor create();virtual;
destructor Destroy; override;
function getRoots():TrootsEquation;virtual;abstract;
procedure Display();
function ToString: string; override;
procedure AddStap(strLits:TStrings);overload;
procedure AddStap(const str:string);overload;
function getStaps:TStringList;
procedure ClearStaps();
property EquationDegree:word read FEquationDegree write setEqDegree;
property EquationName:string read FEquationName write setEqName;
property EquationFormla:string read FEquationFormla write setFormla;
end;
//-------------------------------------------------------
//Equation 1
TEquation1=class(TEquationAbstarct)
private
Fa,Fb:TZNumber;
public
constructor create(a,b:TZNumber);
function getRoots: TrootsEquation; override;
end;
///Equation2
TEquation2=class(TEquationAbstarct)
private
Fa,Fb,Fc:TZNumber;
public
constructor create(a,b,c:TZNumber);
function getRoots: TrootsEquation; override;
end;
///Equation3
TEquation3=class(TEquationAbstarct)
private
Fa,Fb,Fc,Fd:TZNumber;
public
constructor create(a,b,c,d:TZNumber);
function getDelta_0():TZNumber;
function getDelta_1():TZNumber;
function getDelta():TZNumber;
function getC():TZNumber;
function getAllRoots():TrootsEquation;
function getRoots: TrootsEquation; override;
end;
implementation
{ TEquationAbstarct }
procedure TEquationAbstarct.AddStap(const str: string);
begin
FEquaionStaps.Add(str);
end;
procedure TEquationAbstarct.ClearStaps;
begin
if Assigned(FEquaionStaps) then
FEquaionStaps.Clear;
end;
constructor TEquationAbstarct.create;
begin
FEquaionStaps:=TStringList.Create;
end;
destructor TEquationAbstarct.Destroy;
begin
if Assigned(FEquaionStaps) then
begin
FreeAndNil(FEquaionStaps);
end;
inherited;
end;
procedure TEquationAbstarct.Display;
var
root:TrootsEquation;
count:integer;
begin
root:=getRoots;
for count := Low(root) to High(root) do
begin
writeln('root[',count,'] --> ',root[count].ToString);
end;
end;
function TEquationAbstarct.getStaps: TStringList;
begin
ClearStaps;
getRoots();
result:=TStringList.Create;
if Assigned(FEquaionStaps) then
result.AddStrings(FEquaionStaps);
end;
procedure TEquationAbstarct.setEqDegree(const Value: word);
begin
FEquationDegree := Value;
end;
procedure TEquationAbstarct.setEqName(const Value: string);
begin
FEquationName := Value;
end;
procedure TEquationAbstarct.setFormla(const Value: string);
begin
FEquationFormla := Value;
end;
procedure TEquationAbstarct.AddStap(strLits: TStrings);
begin
FEquaionStaps.AddStrings(strLits);
end;
function TEquationAbstarct.ToString: string;
begin
result:=(FEquationName);
end;
{ TEquation1 }
constructor TEquation1.create(a, b: TZNumber);
begin
inherited create;
EquationFormla:=' aX + b = 0 ';
EquationDegree:=1;
EquationName:='Equation Degree 1';
Fa:=a;
Fb:=b;
end;
function TEquation1.getRoots: TrootsEquation;
begin
AddStap(EquationFormla);
AddStap('----------------------');
AddStap('');
AddStap('a = '+Fa.ToString);
AddStap('b = '+fb.ToString);
AddStap('');
AddStap('----------------------');
AddStap('-----------Solve------------');
AddStap('X = -b/a ');
AddStap('');
if (fa=0) then
begin
AddStap('<error>');
AddStap('a = '+Fa.ToString);
AddStap(ZeroComplixNumber);
raise TComplixNumberZeroExcepion.Create(ZeroComplixNumber);
end;
SetLength(result,1);
result[0]:=(-fb)/(fa);
AddStap('X = '+result[0].ToString);
end;
{ TEquation2 }
constructor TEquation2.create(a, b, c: TZNumber);
begin
inherited create;
EquationFormla:=' aX² + bX + c = 0 ';
EquationDegree:=2;
EquationName:='Equation Degree 2';
Fa:=a;
fb:=b;
fc:=c;
end;
function TEquation2.getRoots: TrootsEquation;
var
eq1:TEquation1;
delta:TZNumber;
delta_root:TZNumber;
begin
ClearStaps;
AddStap(EquationFormla);
AddStap('----------------------');
AddStap('');
AddStap('a = '+Fa.ToString);
AddStap('b = '+fb.ToString);
AddStap('c = '+fc.ToString);
AddStap('');
AddStap('----------------------');
if(fa=0) then
begin
AddStap('a = '+Fa.ToString);
AddStap('a is Zero then the Equation is :');
AddStap('----------------------');
eq1:=TEquation1.create(fb,fc);
try
result:=eq1.getRoots;
AddStap(eq1.getStaps);
finally
FreeAndNil(eq1);
end;
end
else
begin
AddStap('-----------Solve------------');
AddStap('');
AddStap(' delta = b² -4*a*c ');
delta:=(fb*fb)-4*(fa*fc); //delta=b²-4*a*c
AddStap(' delta = '+delta.ToString);
AddStap('');
delta_root:=delta.getRoots(2)[0];//get first root
AddStap('root_delta = sqrt(Delta) ');
AddStap('root_delta = '+delta_root.ToString);
AddStap('');
SetLength(result,2);
AddStap('X1 = (-b +root_delta)/ (2*a)');
result[0]:=((-fb+delta_root))/(2*fa);//x1=(-b+sqrt(delta))/2a
AddStap('X1 = '+result[0].ToString);
AddStap('');
AddStap('X2 = (-b -root_delta)/ (2*a)');
result[1]:=((-fb-delta_root))/(2*fa);//x2=(-b-sqrt(delta))/2a
AddStap('X2 = '+result[1].ToString);
AddStap('');
end;
end;
{ TEquation3 }
constructor TEquation3.create(a, b, c, d: TZNumber);
begin
inherited create;
EquationFormla:=' aX^3 + bX² + cX + d = 0 ';
EquationDegree:=3;
EquationName:='Equation Degree 3';
fa:=a;
fb:=b;
fc:=c;
fd:=d;
end;
function TEquation3.getAllRoots: TrootsEquation;
var
c:TZNumber;
x:TZNumber;
k:integer;
mult:TZNumber;
d_0,delta:TZNumber;
begin
AddStap('-----------Solve------------');
AddStap('');
SetLength(result,3);
AddStap(' Delta = 18abcd -(4b^3)(d) +b²c² -4a(c^3) -27a²d²');
delta:=getDelta;
AddStap(' Delta = '+delta.ToString);
AddStap('');
AddStap(' d_0 = b² -3ac ');
d_0:=getDelta_0;
AddStap(' d_0 = '+d_0.ToString);
AddStap('');
//AddStap();
if(d_0=0) and (delta=0) then //triple root equal
begin
AddStap(' if d_0 =0 and delta =0 ');
AddStap(' then the equation has a single root ');
AddStap('');
AddStap(' single root = -b/(3a)');
x:=(-fb/(3*fa));
AddStap(' single root = '+x.ToString);
AddStap('');
AddStap('');
for k := low(result) to High(result) do
begin
AddStap(Format(' X%d = single root',[k]));
result[k]:=x;
AddStap(Format(' X%d = %s',[k,x.ToString]));
AddStap('');
end;
exit;
end
else
if (d_0<>0) and (delta=0) then
begin
AddStap(' if d_0 !=0 and delta =0 ');
AddStap(' then there are both a double root :');
AddStap('');
AddStap('double root = (9ad)-(bc)/(2*d_0)');
AddStap('');
x:=((9*fa*fd)-(fb*fc))/(2*d_0);
AddStap('double root = '+x.ToString);
AddStap('');
AddStap('');
AddStap(Format(' X%d = double root',[1]));
result[0]:=x;
AddStap(Format(' X%d = %s',[1,x.ToString]));
AddStap('');
AddStap('');
AddStap(Format(' X%d = double root',[2]));
result[1]:=x;
AddStap(Format(' X%d = %s',[2,x.ToString]));
AddStap('');
AddStap(' and and a simple root :');
AddStap(' simple root =( (4abc)-(9a²d)-b^3 )/(a*d_0) ');
x:=((4*fa*fb*fc)-(9*fa.PowerTo(2)*fd)-(fb.PowerTo(3)))/(fa*d_0);
AddStap(' simple root = '+x.ToString);
AddStap('');
AddStap(Format(' X%d = double root',[3]));
result[2]:=x;
AddStap(Format(' X%d = %s',[3,x.ToString]));
AddStap('');
exit;
end;
AddStap('');
AddStap(' d_1 = (2b^3) -(9abc) +(27a²d) ');
AddStap(' d_1 = '+getDelta_1.ToString);
AddStap('');
AddStap('');
AddStap(' C = { ( d_1 +sqrt( d_1² -4d_0^3 ) )/2 }^(1/3) ');
c:=getC();
AddStap(' C = '+c.ToString);
AddStap('');
AddStap('');
AddStap(' mult = ( -1/2 +i( sqrt(3)/2 ) ');
mult:=TZNumber.create(-0.5,+0.5*sqrt(3));
AddStap('');
AddStap('');
AddStap(' X_k =(-1/(3a)) *{ b+(mult^k)(C) +(d_0/((mult^k)(C)) ) }');
AddStap(' k={0,1,2}');
AddStap('');
for k := low(result) to High(result) do
begin
AddStap('');
AddStap(Format(' k= %d',[k]));
AddStap('');
x:=(-1/(3*fa)) *(Fb +(c*mult.PowerTo(k))+ (d_0/(c*mult.PowerTo(k))) );
AddStap(Format(' x_%d= %s',[k+1,x.ToString]));
result[k]:=x;
end;
end;
function TEquation3.getC: TZNumber;
var
alpha:TZNumber;
d_0,d_1:TZNumber;
C:TZNumber;
begin
d_0:=getDelta_0;
d_1:=getDelta_1;
alpha:=d_1.PowerTo(2) +(-4*d_0.PowerTo(3));
alpha:=(d_1+alpha.getRoots(2)[0])/2;//+-
C:=alpha.getRoots(3)[0];
result:=C;
end;
function TEquation3.getDelta: TZNumber;
begin
result:=(18*fa*fb*fc*fd) -(4*fb.PowerTo(3)*fd)+(fb.PowerTo(2) *fc.PowerTo(2))-(4*fa*fc.PowerTo(3))-(27* fa.PowerTo(2) *fd.PowerTo(2));
end;
function TEquation3.getDelta_0: TZNumber;
begin
result:=(Fb.PowerTo(2))-(3*fa*fc);
end;
function TEquation3.getDelta_1: TZNumber;
begin
result:=(2*Fb.PowerTo(3)) -(9*fa*fb*fc) +(27*Fa.PowerTo(2)*Fd);
end;
function TEquation3.getRoots: TrootsEquation;
var
Eq2:TEquation2;
begin
AddStap(EquationFormla);
AddStap('----------------------');
AddStap('');
AddStap('a = '+Fa.ToString);
AddStap('b = '+fb.ToString);
AddStap('c = '+fc.ToString);
AddStap('d = '+fd.ToString);
AddStap('');
AddStap('----------------------');
if(fa=0) then
begin
AddStap('a = '+Fa.ToString);
AddStap('a is Zero then the Equation is :');
AddStap('----------------------');
Eq2:=TEquation2.create(fb,fc,fd);
try
result:=Eq2.getRoots();
AddStap(Eq2.getStaps);
finally
FreeAndNil(Eq2);
end;
end
else
begin
result:=getAllRoots();
end;
end;
end.
|
{==============================================================================}
{ }
{ OpenGL Video Renderer Filter Unit }
{ Version 1.0 }
{ Date : 2010-07-10 }
{ }
{==============================================================================}
{ }
{ Copyright (C) 2010 Torsten Spaete }
{ All Rights Reserved }
{ }
{ Uses dglOpenGL (MPL 1.1) from the OpenGL Delphi Community }
{ http://delphigl.com }
{ }
{ Uses DSPack (MPL 1.1) from }
{ http://progdigy.com }
{ }
{==============================================================================}
{ The contents of this file are used with permission, 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/MPL-1.1.html }
{ }
{ 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. }
{==============================================================================}
{ History : }
{ Version 1.0 Initial Release }
{==============================================================================}
unit OVRFilter;
interface
uses
// Delphi
Messages,
Windows,
SysUtils,
Classes,
ActiveX,
// 3rd party
BaseClass,
DirectShow9,
DGLOpenGL;
const
CLSID_OpenGLVideoRenderer: TGUID = '{5BA04474-46C4-4802-B52F-3EA19B75B227}';
type
TOVRFilter = class(TBCBaseRenderer, IPersist, IDispatch,
IBasicVideo, IBasicVideo2,
IAMFilterMiscFlags,
IVideoWindow)
private
// Dispatch variables
FDispatch : TBCBaseDispatch;
function NotImplemented : HResult;
public
(*** TBCBaseRenderer methods ***)
constructor Create(ObjName: String; Unk: IUnknown; out hr : HResult);
constructor CreateFromFactory(Factory: TBCClassFactory; const Controller: IUnknown); override;
destructor Destroy; override;
function CheckMediaType(MediaType: PAMMediaType): HResult; override;
function DoRenderSample(MediaSample: IMediaSample): HResult; override;
function SetMediaType(MediaType: PAMMediaType): HResult; override;
function Active: HResult; override;
function Inactive: HResult; override;
(*** IDispatch methods ***)
function GetTypeInfoCount(out Count: Integer): HResult; stdcall;
function GetTypeInfo(Index, LocaleID: Integer; out TypeInfo): HResult; stdcall;
function GetIDsOfNames(const IID: TGUID; Names: Pointer; NameCount, LocaleID: Integer; DispIDs: Pointer): HResult; stdcall;
function Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer; Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HResult; stdcall;
(*** IBasicVideo methods ***)
function get_AvgTimePerFrame(out pAvgTimePerFrame: TRefTime): HResult; stdcall;
function get_BitRate(out pBitRate: Longint): HResult; stdcall;
function get_BitErrorRate(out pBitErrorRate: Longint): HResult; stdcall;
function get_VideoWidth(out pVideoWidth: Longint): HResult; stdcall;
function get_VideoHeight(out pVideoHeight: Longint): HResult; stdcall;
function put_SourceLeft(SourceLeft: Longint): HResult; stdcall;
function get_SourceLeft(out pSourceLeft: Longint): HResult; stdcall;
function put_SourceWidth(SourceWidth: Longint): HResult; stdcall;
function get_SourceWidth(out pSourceWidth: Longint): HResult; stdcall;
function put_SourceTop(SourceTop: Longint): HResult; stdcall;
function get_SourceTop(out pSourceTop: Longint): HResult; stdcall;
function put_SourceHeight(SourceHeight: Longint): HResult; stdcall;
function get_SourceHeight(out pSourceHeight: Longint): HResult; stdcall;
function put_DestinationLeft(DestinationLeft: Longint): HResult; stdcall;
function get_DestinationLeft(out pDestinationLeft: Longint): HResult; stdcall;
function put_DestinationWidth(DestinationWidth: Longint): HResult; stdcall;
function get_DestinationWidth(out pDestinationWidth: Longint): HResult; stdcall;
function put_DestinationTop(DestinationTop: Longint): HResult; stdcall;
function get_DestinationTop(out pDestinationTop: Longint): HResult; stdcall;
function put_DestinationHeight(DestinationHeight: Longint): HResult; stdcall;
function get_DestinationHeight(out pDestinationHeight: Longint): HResult; stdcall;
function SetSourcePosition(Left, Top, Width, Height: Longint): HResult; stdcall;
function GetSourcePosition(out pLeft, pTop, pWidth, pHeight: Longint): HResult; stdcall;
function SetDefaultSourcePosition: HResult; stdcall;
function SetDestinationPosition(Left, Top, Width, Height: Longint): HResult; stdcall;
function GetDestinationPosition(out pLeft, pTop, pWidth, pHeight: Longint): HResult; stdcall;
function SetDefaultDestinationPosition: HResult; stdcall;
function GetVideoSize(out pWidth, pHeight: Longint): HResult; stdcall;
function GetVideoPaletteEntries(StartIndex, Entries: Longint; out pRetrieved: Longint; out pPalette): HResult; stdcall;
function GetCurrentImage(var BufferSize: Longint; var pDIBImage): HResult; stdcall;
function IsUsingDefaultSource: HResult; stdcall;
function IsUsingDefaultDestination: HResult; stdcall;
(*** IBasicVideo2 methods ***)
function GetPreferredAspectRatio(out plAspectX, plAspectY: Longint): HResult; stdcall;
(*** IAMFilterMiscFlags methods ***)
function GetMiscFlags: ULONG; stdcall;
(*** IVideoWindow methods ***)
function put_Caption(strCaption: WideString): HResult; stdcall;
function get_Caption(out strCaption: WideString): HResult; stdcall;
function put_WindowStyle(WindowStyle: Longint): HResult; stdcall;
function get_WindowStyle(out WindowStyle: Longint): HResult; stdcall;
function put_WindowStyleEx(WindowStyleEx: Longint): HResult; stdcall;
function get_WindowStyleEx(out WindowStyleEx: Longint): HResult; stdcall;
function put_AutoShow(AutoShow: LongBool): HResult; stdcall;
function get_AutoShow(out AutoShow: LongBool): HResult; stdcall;
function put_WindowState(WindowState: Longint): HResult; stdcall;
function get_WindowState(out WindowState: Longint): HResult; stdcall;
function put_BackgroundPalette(BackgroundPalette: Longint): HResult; stdcall;
function get_BackgroundPalette(out pBackgroundPalette: Longint): HResult; stdcall;
function put_Visible(Visible: LongBool): HResult; stdcall;
function get_Visible(out pVisible: LongBool): HResult; stdcall;
function put_Left(Left: Longint): HResult; stdcall;
function get_Left(out pLeft: Longint): HResult; stdcall;
function put_Width(Width: Longint): HResult; stdcall;
function get_Width(out pWidth: Longint): HResult; stdcall;
function put_Top(Top: Longint): HResult; stdcall;
function get_Top(out pTop: Longint): HResult; stdcall;
function put_Height(Height: Longint): HResult; stdcall;
function get_Height(out pHeight: Longint): HResult; stdcall;
function put_Owner(Owner: OAHWND): HResult; stdcall;
function get_Owner(out Owner: OAHWND): HResult; stdcall;
function put_MessageDrain(Drain: OAHWND): HResult; stdcall;
function get_MessageDrain(out Drain: OAHWND): HResult; stdcall;
function get_BorderColor(out Color: Longint): HResult; stdcall;
function put_BorderColor(Color: Longint): HResult; stdcall;
function get_FullScreenMode(out FullScreenMode: LongBool): HResult; stdcall;
function put_FullScreenMode(FullScreenMode: LongBool): HResult; stdcall;
function SetWindowForeground(Focus: Longint): HResult; stdcall;
function NotifyOwnerMessage(hwnd: Longint; uMsg, wParam, lParam: Longint): HResult; stdcall;
function SetWindowPosition(Left, Top, Width, Height: Longint): HResult; stdcall;
function GetWindowPosition(out pLeft, pTop, pWidth, pHeight: Longint): HResult; stdcall;
function GetMinIdealImageSize(out pWidth, pHeight: Longint): HResult; stdcall;
function GetMaxIdealImageSize(out pWidth, pHeight: Longint): HResult; stdcall;
function GetRestorePosition(out pLeft, pTop, pWidth, pHeight: Longint): HResult; stdcall;
function HideCursor(HideCursor: LongBool): HResult; stdcall;
function IsCursorHidden(out CursorHidden: LongBool): HResult; stdcall;
end;
implementation
uses
// Own
OVRUtils,
OVRVideoWindow;
var
SupportedSubTypes : array of TGUID;
SupportedFormatTypes : array of TGUID;
function IsSubTypeSupported(ASubType : TGUID) : Boolean;
var I : Integer;
begin
Result := False;
For I := 0 to Length(SupportedSubTypes)-1 do
if IsEqualGuid(SupportedSubTypes[i], ASubType) then
begin
Result := True;
Exit;
end;
end;
function IsFormatTypeSupported(AFormatType : TGUID) : Boolean;
var I : Integer;
begin
Result := False;
For I := 0 to Length(SupportedFormatTypes)-1 do
if IsEqualGuid(SupportedFormatTypes[i], AFormatType) then
begin
Result := True;
Exit;
end;
end;
function CheckConnected(Pin : TBCBasePin; out Res : HRESULT) : Boolean;
begin
if not Pin.IsConnected then
begin
Res := VFW_E_NOT_CONNECTED;
Result := False;
end else
begin
Res := S_OK;
Result := True;
end;
end;
constructor TOVRFilter.Create(ObjName: String; Unk: IUnknown;
out hr: HResult);
begin
WriteTrace('Create.Enter');
WriteTrace('Inherited Create');
inherited Create(CLSID_OpenGLVideoRenderer, 'OpenGLVideoRenderer', Unk, hr);
// Initialize base dispatch
WriteTrace('Initialize dispatch handler');
fDispatch := TBCBaseDispatch.Create;
WriteTrace('Create.Leave');
end;
constructor TOVRFilter.CreateFromFactory(Factory: TBCClassFactory;
const Controller: IUnknown);
var
hr: HRESULT;
begin
WriteTrace('CreateFromFactory.Enter');
Create(Factory.Name, Controller, hr);
WriteTrace('CreateFromFactory.Leave');
end;
destructor TOVRFilter.Destroy;
begin
WriteTrace('Destroy.Enter');
// Release video window
WriteTrace('Release video window');
ReleaseVideoWindow;
// Release dispatch handler
if Assigned(fDispatch) then
begin
WriteTrace('Release dispatch handler');
FreeAndNil(fDispatch);
end;
WriteTrace('Inherited destroy');
inherited Destroy;
WriteTrace('Destroy.Leave');
end;
function TOVRFilter.NotImplemented : HResult;
begin
Result := E_POINTER;
if not CheckConnected(FInputPin,Result) then Exit;
Result := E_NOTIMPL;
end;
function TOVRFilter.Active: HResult;
begin
WriteTrace('Active.Enter');
WriteTrace('Show video window');
ShowVideoWindow;
WriteTrace('Inherited active');
Result := inherited Active;
WriteTrace('Active.Leave with result: ' + IntToStr(Result));
end;
function TOVRFilter.Inactive: HResult;
begin
WriteTrace('Inactive.Enter');
WriteTrace('Hide video window');
HideVideoWindow;
WriteTrace('Inherited inactive');
Result := inherited Inactive;
WriteTrace('Inactive.Leave with result: ' + IntToStr(Result));
end;
function TOVRFilter.CheckMediaType(MediaType: PAMMediaType): HResult;
begin
WriteTrace('CheckMediaType.Enter');
// No mediatype, exit with pointer error
if (MediaType = nil) then
begin
WriteTrace('No mediatype pointer given, exiting!');
Result := E_POINTER;
Exit;
end;
// We want only video major types to be supported
if (not IsEqualGUID(MediaType^.majortype, MEDIATYPE_Video)) then
begin
WriteTrace('Media majortype "'+MGuidToString(MediaType^.majortype)+'" not supported!');
Result := E_NOTIMPL;
Exit;
end;
// We want only supported sub types
if not IsSubTypeSupported(MediaType^.subtype) then
begin
WriteTrace('Media subtype "'+SGuidToString(MediaType^.subtype)+'" not supported!');
Result := E_NOTIMPL;
Exit;
end;
// We want only supported format types
if not IsFormatTypeSupported(MediaType^.formattype) then
begin
WriteTrace('Media formattype "'+FGuidToString(MediaType^.formattype)+'" not supported!');
Result := E_NOTIMPL;
Exit;
end;
WriteTrace('Check mediatype format pointer');
Assert(Assigned(MediaType.pbFormat));
WriteTrace('CheckMediaType.Leave with success');
Result := NOERROR;
end;
function TOVRFilter.DoRenderSample(MediaSample: IMediaSample): HResult;
begin
// No mediatype, exit with pointer error
if (MediaSample = nil) then
begin
Result := E_POINTER;
Exit;
end;
// Update sample
UpdateSample(MediaSample);
Result := NOERROR;
end;
function TOVRFilter.SetMediaType(MediaType: PAMMediaType): HResult;
begin
WriteTrace('SetMediaType.Enter');
// No mediatype, exit with pointer error
if (MediaType = nil) then
begin
WriteTrace('No mediatype pointer given, exiting!');
Result := E_POINTER;
Exit;
end;
// Release window (Clear data)
WriteTrace('Release video window');
ReleaseVideoWindow;
// Initialize window class
WriteTrace('Create video window');
if not CreateVideoWindow(MediaType) then
begin
WriteTrace('Release video window');
ReleaseVideoWindow;
WriteTrace('Video window could not be created!');
Result := E_FAIL;
Exit;
end;
Result := NOERROR;
WriteTrace('SetMediaType.Leave with success');
end;
{*** IDispatch methods *** taken from CBaseVideoWindow *** ctlutil.cpp ********}
function TOVRFilter.GetTypeInfoCount(out Count: Integer): HResult; stdcall;
begin
Result := fDispatch.GetTypeInfoCount(Count);
end;
function TOVRFilter.GetTypeInfo(Index, LocaleID: Integer; out TypeInfo): HResult; stdcall;
begin
Result := fDispatch.GetTypeInfo(IID_IVideoWindow,Index,LocaleID,TypeInfo);
end;
function TOVRFilter.GetIDsOfNames(const IID: TGUID; Names: Pointer; NameCount, LocaleID: Integer; DispIDs: Pointer): HResult; stdcall;
begin
Result := fDispatch.GetIDsOfNames(IID_IVideoWindow,Names,NameCount,LocaleID,DispIDs);
end;
function TOVRFilter.Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer; Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HResult; stdcall;
var
pti : ITypeInfo;
begin
if not IsEqualGUID(GUID_NULL,IID) then
begin
Result := DISP_E_UNKNOWNINTERFACE;
Exit;
end;
Result := GetTypeInfo(0, LocaleID, pti);
if FAILED(Result) then Exit;
Result := pti.Invoke(Pointer(Self as IVideoWindow),DispID,Flags,
TDispParams(Params),VarResult,ExcepInfo,ArgErr);
pti := nil;
end;
(*** IBasicVideo methods ******************************************************)
function TOVRFilter.get_AvgTimePerFrame(out pAvgTimePerFrame: TRefTime): HResult; stdcall;
begin
if not CheckConnected(FInputPin, Result) then Exit;
pAvgTimePerFrame := VideoWindowFormat.AvgTimePerFrame;
Result := NOERROR;
end;
function TOVRFilter.get_BitRate(out pBitRate: Longint): HResult; stdcall;
begin
if not CheckConnected(FInputPin,Result) then Exit;
pBitRate := VideoWindowFormat.dwBitRate;
Result := NOERROR;
end;
function TOVRFilter.get_BitErrorRate(out pBitErrorRate: Longint): HResult; stdcall;
begin
if not CheckConnected(FInputPin,Result) then Exit;
pBitErrorRate := VideoWindowFormat.dwBitErrorRate;
Result := NOERROR;
end;
function TOVRFilter.get_VideoWidth(out pVideoWidth: Longint): HResult; stdcall;
begin
if not CheckConnected(FInputPin,Result) then Exit;
pVideoWidth := VideoWindowFormat.bmiHeader.biWidth;
Result := NOERROR;
end;
function TOVRFilter.get_VideoHeight(out pVideoHeight: Longint): HResult; stdcall;
begin
if not CheckConnected(FInputPin,Result) then Exit;
pVideoHeight := VideoWindowFormat.bmiHeader.biHeight;
Result := NOERROR;
end;
function TOVRFilter.put_SourceLeft(SourceLeft: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.get_SourceLeft(out pSourceLeft: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.put_SourceWidth(SourceWidth: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.get_SourceWidth(out pSourceWidth: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.put_SourceTop(SourceTop: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.get_SourceTop(out pSourceTop: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.put_SourceHeight(SourceHeight: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.get_SourceHeight(out pSourceHeight: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.put_DestinationLeft(DestinationLeft: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.get_DestinationLeft(out pDestinationLeft: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.put_DestinationWidth(DestinationWidth: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.get_DestinationWidth(out pDestinationWidth: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.put_DestinationTop(DestinationTop: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.get_DestinationTop(out pDestinationTop: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.put_DestinationHeight(DestinationHeight: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.get_DestinationHeight(out pDestinationHeight: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.SetSourcePosition(Left, Top, Width, Height: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.GetSourcePosition(out pLeft, pTop, pWidth, pHeight: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.SetDefaultSourcePosition: HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.SetDestinationPosition(Left, Top, Width, Height: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.GetDestinationPosition(out pLeft, pTop, pWidth, pHeight: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.SetDefaultDestinationPosition: HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.GetVideoSize(out pWidth, pHeight: Longint): HResult; stdcall;
begin
if not CheckConnected(FInputPin,Result) then Exit;
pWidth := VideoWindowFormat.bmiHeader.biWidth;
pHeight := VideoWindowFormat.bmiHeader.biHeight;
Result := NOERROR;
end;
function TOVRFilter.GetVideoPaletteEntries(StartIndex, Entries: Longint; out pRetrieved: Longint; out pPalette): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.GetCurrentImage(var BufferSize: Longint; var pDIBImage): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.IsUsingDefaultSource: HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.IsUsingDefaultDestination: HResult; stdcall;
begin
Result := NotImplemented();
end;
(*** IBasicVideo2 methods *****************************************************)
function TOVRFilter.GetPreferredAspectRatio(out plAspectX, plAspectY: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
(*** IAMFilterMiscFlags methods ***********************************************)
function TOVRFilter.GetMiscFlags: ULONG; stdcall;
begin
Result := AM_FILTER_MISC_FLAGS_IS_RENDERER;
end;
(*** IVideoWindow methods *****************************************************)
function TOVRFilter.put_Caption(strCaption: WideString): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.get_Caption(out strCaption: WideString): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.put_WindowStyle(WindowStyle: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.get_WindowStyle(out WindowStyle: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.put_WindowStyleEx(WindowStyleEx: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.get_WindowStyleEx(out WindowStyleEx: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.put_AutoShow(AutoShow: LongBool): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.get_AutoShow(out AutoShow: LongBool): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.put_WindowState(WindowState: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.get_WindowState(out WindowState: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.put_BackgroundPalette(BackgroundPalette: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.get_BackgroundPalette(out pBackgroundPalette: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.put_Visible(Visible: LongBool): HResult; stdcall;
begin
if not SetVideoWindowVisible(Visible) then
begin
Result := E_FAIL;
Exit;
end;
Result := NOERROR;
end;
function TOVRFilter.get_Visible(out pVisible: LongBool): HResult; stdcall;
begin
pVisible := GetVideoWindowVisible;
Result := NOERROR;
end;
function TOVRFilter.put_Left(Left: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.get_Left(out pLeft: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.put_Width(Width: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.get_Width(out pWidth: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.put_Top(Top: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.get_Top(out pTop: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.put_Height(Height: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.get_Height(out pHeight: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.put_Owner(Owner: OAHWND): HResult; stdcall;
begin
if not SetVideoWindowOwner(Owner) then
begin
Result := E_FAIL;
Exit;
end;
Result := NOERROR;
end;
function TOVRFilter.get_Owner(out Owner: OAHWND): HResult; stdcall;
var
O : HWND;
begin
O := GetVideoWindowOwner;
if O = 0 then
begin
Result := E_FAIL;
Exit;
end;
Owner := O;
Result := NOERROR;
end;
function TOVRFilter.put_MessageDrain(Drain: OAHWND): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.get_MessageDrain(out Drain: OAHWND): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.get_BorderColor(out Color: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.put_BorderColor(Color: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.get_FullScreenMode(out FullScreenMode: LongBool): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.put_FullScreenMode(FullScreenMode: LongBool): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.SetWindowForeground(Focus: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.NotifyOwnerMessage(hwnd: Longint; uMsg, wParam, lParam: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.SetWindowPosition(Left, Top, Width, Height: Longint): HResult; stdcall;
begin
if not SetVideoWindowPosition(Left, Top, Width, Height) then
begin
Result := E_FAIL;
Exit;
end;
Result := NOERROR;
end;
function TOVRFilter.GetWindowPosition(out pLeft, pTop, pWidth, pHeight: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.GetMinIdealImageSize(out pWidth, pHeight: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.GetMaxIdealImageSize(out pWidth, pHeight: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.GetRestorePosition(out pLeft, pTop, pWidth, pHeight: Longint): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.HideCursor(HideCursor: LongBool): HResult; stdcall;
begin
Result := NotImplemented();
end;
function TOVRFilter.IsCursorHidden(out CursorHidden: LongBool): HResult; stdcall;
begin
Result := NotImplemented();
end;
initialization
SetLength(SupportedSubTypes, 9);
SupportedSubTypes[0] := MEDIASUBTYPE_RGB24;
SupportedSubTypes[1] := MEDIASUBTYPE_RGB32;
SupportedSubTypes[2] := MEDIASUBTYPE_RGB555;
SupportedSubTypes[3] := MEDIASUBTYPE_RGB565;
SupportedSubTypes[4] := MEDIASUBTYPE_YVYU;
SupportedSubTypes[5] := MEDIASUBTYPE_YUY2;
SupportedSubTypes[6] := MEDIASUBTYPE_YUYV;
SupportedSubTypes[7] := MEDIASUBTYPE_UYVY;
SupportedSubTypes[8] := MEDIASUBTYPE_YV12;
SetLength(SupportedFormatTypes, 4);
SupportedFormatTypes[0] := FORMAT_VideoInfo;
SupportedFormatTypes[1] := FORMAT_VideoInfo2;
SupportedFormatTypes[2] := FORMAT_MPEGVideo;
SupportedFormatTypes[3] := FORMAT_MPEG2Video;
TBCClassFactory.CreateFilter(TOVRFilter, 'OpenGLVideoRenderer',
CLSID_OpenGLVideoRenderer, CLSID_LegacyAmFilterCategory, MERIT_DO_NOT_USE,
0, nil
);
end.
|
unit UserSessionUnit;
{
This is a DataModule where you can add components or declare fields that are specific to
ONE user. Instead of creating global variables, it is better to use this datamodule. You can then
access the it using UserSession.
}
interface
uses
IWUserSessionBase, SysUtils, Classes;
type
TIWUserSession = class(TIWUserSessionBase)
private
{ Private declarations }
public
{ Public declarations }
end;
implementation
{$R *.dfm}
end. |
unit DialogConsultaEntradas;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DialogConsulta, cxGraphics, Menus, cxLookAndFeelPainters, cxStyles,
cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, ADODB,
dxLayoutControl, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGrid,
StdCtrls, cxButtons, cxTextEdit, cxContainer, cxMaskEdit, cxDropDownEdit,
DialogCobro, ExtCtrls;
type
TfrmDialogConsultaEntradas = class(TfrmDialogConsulta)
dbDatosTotalPagado: TcxGridDBColumn;
dbDatosTotalPendiente: TcxGridDBColumn;
dbDatosEntradaID: TcxGridDBColumn;
dbDatosFecha: TcxGridDBColumn;
dbDatosPacienteID: TcxGridDBColumn;
dbDatosClienteID: TcxGridDBColumn;
dbDatosNeto: TcxGridDBColumn;
dbDatosNombrePaciente: TcxGridDBColumn;
dbDatosClienteNombre: TcxGridDBColumn;
dbDatosMonedaID: TcxGridDBColumn;
dbDatosTelefonos: TcxGridDBColumn;
dbDatosHold: TcxGridDBColumn;
procedure cgDatosExit(Sender: TObject);
procedure cgDatosEnter(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure FormShow(Sender: TObject);
procedure edbuscarPropertiesChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure BuscarData;
private
{ Private declarations }
strWhere: String;
public
{ Public declarations }
procedure Run;
end;
var
frmDialogConsultaEntradas: TfrmDialogConsultaEntradas;
adentrogrid : Boolean;
implementation
uses DataModule,PuntoVenta,Main, DataBanco;
{$R *.dfm}
procedure TfrmDialogConsultaEntradas.Run;
Var
qfind : TADOQuery;
begin
showmodal;
if ModalResult = mrOk then
Begin
DMB.RetornarEntrada:= DM.qrEntradaPacienteConsRecid.AsInteger;
DMB.RetornarEntradaId:= DM.qrEntradaPacienteConsEntradaId.Value;
end
else
begin
DMB.RetornarEntrada:= 0;
DMB.RetornarEntradaId:= '';
end;
end;
procedure TfrmDialogConsultaEntradas.BuscarData;
begin
DM.qrParametro.close;
DM.qrParametro.open;
if trim(edbuscar.Text) <> '' then begin
case edbuscarpor.ItemIndex of
0 : strWhere := ' AND EntradaID like '+#39+'%'+edbuscar.Text+'%'+#39;
1 : strWhere := ' AND PacienteID like '+#39+'%'+edbuscar.Text+'%'+#39;
2 : strWhere := ' AND NombrePaciente like '+#39+'%'+'%'+edbuscar.Text+'%'+#39;
3 : strWhere := ' AND ClienteID like '+#39+'%'+edbuscar.Text+'%'+#39;
4 : strWhere := ' AND ClienteNombre like '+#39+'%'+edbuscar.Text+'%'+#39;
5 : strWhere := ' AND Telefonos like '+#39+'%'+edbuscar.Text+'%'+#39;
end;
end
else
strWhere := '';
DM.qrEntradaPacienteCons.Close;
DM.qrEntradaPacienteCons.SQL.Text := DMB.sqlString + strWhere + ' Order by fecha desc,horaentrada desc,EntradaID';
DM.qrEntradaPacienteCons.Open;
end;
procedure TfrmDialogConsultaEntradas.cgDatosEnter(Sender: TObject);
begin
inherited;
adentrogrid := true;
end;
procedure TfrmDialogConsultaEntradas.cgDatosExit(Sender: TObject);
begin
inherited;
adentrogrid := false;
end;
procedure TfrmDialogConsultaEntradas.edbuscarPropertiesChange(Sender: TObject);
begin
inherited;
BuscarData;
end;
procedure TfrmDialogConsultaEntradas.FormCreate(Sender: TObject);
begin
inherited;
strWhere := '';
DM.qrEntradaPacienteCons.Close;
DM.qrEntradaPacienteCons.SQL.Text := DMB.sqlString;
DM.qrEntradaPacienteCons.Open;
If (frmMain.Exis_Vta = True) then
edbuscarpor.ItemIndex := 2
Else
edbuscarpor.ItemIndex := 2;
end;
procedure TfrmDialogConsultaEntradas.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inherited;
if (key = Vk_Down) and (not AdentroGrid) then
PostMessage(Handle, Wm_NextDlgCtl, 0, 0);
if (key = 13) and (not AdentroGrid) then
PostMessage(Handle, Wm_NextDlgCtl, 0, 0);
if (key = 13) and (AdentroGrid) then
begin
Close;
ModalResult := mrOk;
end;
if (key = Vk_Up) and (not AdentroGrid) then
PostMessage(Handle, Wm_NextDlgCtl, 1, 0);
if (key = 27) then
begin
Close;
end;
end;
procedure TfrmDialogConsultaEntradas.FormShow(Sender: TObject);
begin
inherited;
edbuscar.SetFocus;
end;
end.
|
program ejercicio_8;
const
dimF=300;
type
cadena=string[50];
empleado=record
nombre:cadena;
salario:double;
end;
vector=array [1..dimF] of empleado;
procedure Leer(var reg:empleado);
begin
write('Ingrese el nomnre completo del emepleado: ');
readln(reg.nombre);
write('Ingrese el salario del empleado: ');
readln(reg.salario);
end;
procedure cargarVector(var vec:vector;var diml:integer);
var
reg:empleado;
begin
dimL:=0;
writeln('A continuacion ingrese datos de los empleados (Para finalizar ingrese 0 (cero) como valor de salario)');
Leer(reg);
while(dimL<dimF) and (reg.salario<>0) do begin
dimL:= dimL + 1;
vec[dimL]:=reg;
Leer(reg);
end;
end;
procedure incrementar_salario(var vec:vector;dimL:integer;X:double);
var
i:integer;
begin
for i:=1 to dimL do
vec[i].salario:=vec[i].salario+(vec[i].salario*X)
end;
procedure informar_sueldoPromedio(vec:vector;dimL:integer);
var
suma:double;
i:integer;
begin
suma:=0;
for i:=1 to dimL do
suma:=vec[i].salario + suma;
writeln('El sueldo promedio de los empleados de la empresa es: ',(suma/dimL):1:2);
end;
var
vec:vector;
dimL:integer;
X:double;
begin
cargarVector(vec,dimL);
X:=0.15;
incrementar_salario(vec,dimL,X); //Punto A
informar_sueldoPromedio(vec,dimL); // Punto B
readln;
end.
|
unit EditElementsViewModel;
interface
uses
Spring.Collections;
type
TEditElementsViewModel = class
private
FAvailableElements: IObjectList;
FSelectedElements: IObjectList;
FCurrentAvailableElement: TObject;
FCurrentSelectedElement: TObject;
public
constructor Create;
procedure AddElements(Sender: TObject);
procedure RemoveElements(Sender: TObject);
property AvailableElements: IObjectList read FAvailableElements;
property SelectedElements: IObjectList read FSelectedElements;
property CurrentAvailableElement: TObject
read FCurrentAvailableElement write FCurrentAvailableElement;
property CurrentSelectedElement: TObject
read FCurrentSelectedElement write FCurrentSelectedElement;
end;
implementation
{ TEditElementsViewModel }
constructor TEditElementsViewModel.Create;
begin
FAvailableElements := TCollections.CreateList<TObject> as IObjectList;
FSelectedElements := TCollections.CreateList<TObject> as IObjectList;
end;
procedure TEditElementsViewModel.AddElements(Sender: TObject);
begin
if Assigned(FCurrentAvailableElement) then
begin
FSelectedElements.Add(FCurrentAvailableElement);
FAvailableElements.Remove(FCurrentAvailableElement);
end;
end;
procedure TEditElementsViewModel.RemoveElements(Sender: TObject);
begin
if Assigned(FCurrentSelectedElement) then
begin
FAvailableElements.Add(FCurrentSelectedElement);
FSelectedElements.Remove(FCurrentSelectedElement);
end;
end;
end.
|
unit ProjectPropertiesUnit;
interface
uses
Windows,
Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ComCtrls, ExtCtrls, CheckLst, TypesUnit;
type
TProjectProperties = class(TForm)
PageControl: TPageControl;
TabGeneral: TTabSheet;
LabelHelpFile: TLabel;
PanelIcon: TPanel;
ImageIcon: TImage;
btnIcon: TBitBtn;
TabDirectories: TTabSheet;
CheckListBox: TCheckListBox;
btnOK: TBitBtn;
btnCancel: TBitBtn;
cbxHelpFiles: TComboBox;
btnBrowseHelp: TBitBtn;
btnAdd: TBitBtn;
btnAddPath: TBitBtn;
TabCompiler: TTabSheet;
cbxDebugInfo: TCheckBox;
cbxCompileOnly: TCheckBox;
cbxPreserveO: TCheckBox;
cbxGlobalDef: TCheckBox;
gdefName: TEdit;
gdefValue: TEdit;
cbxErrorCheck: TCheckBox;
cbxFBDebug: TCheckBox;
cbxNullPtr: TCheckBox;
cbxAddDebug: TCheckBox;
cbxResumeError: TCheckBox;
cbxPrefixPath: TCheckBox;
LabelOutExt: TLabel;
edOutExt: TEdit;
cbxArrayCheck: TCheckBox;
LabelDefInfo: TLabel;
procedure btnBrowseHelpClick(Sender: TObject);
procedure btnIconClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure btnAddClick(Sender: TObject);
procedure btnOKClick(Sender: TObject);
procedure btnAddPathClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
ProjectProperties: TProjectProperties;
implementation
{$R *.dfm}
uses MainUnit, HelperUnit;
procedure TProjectProperties.btnBrowseHelpClick(Sender: TObject);
begin
with TOpenDialog.Create(nil) do begin
Filter:='Help files (*.chm,*.hlp)|*.chm;*.hlp|All files (*.*)|*.*';
if Execute then begin
cbxHelpFiles.Text:=FileName;
if cbxHelpFiles.Items.IndexOf(FileName)=-1 then
cbxHelpFiles.Items.Add( FileName );
end;
Free
end;
end;
procedure TProjectProperties.btnIconClick(Sender: TObject);
begin
with TOpenDialog.Create(nil) do begin
Filter:='Icon File (*.ico)|*.ico';
if Execute then begin
ImageIcon.Hint:=FileName;
ImageIcon.Picture.LoadFromFile( FileName );
end;
Free
end;
end;
procedure TProjectProperties.FormShow(Sender: TObject);
var
D:TDependencie;
i:integer;
L:TStrings;
s:string;
begin
cbxDebugInfo.Checked:=ActiveProject.DebugInfo;
cbxAddDebug.Checked :=ActiveProject.Debug;
cbxCompileOnly.Checked:= ActiveProject.CompileOnly;
cbxPreserveO.Checked:= ActiveProject.PreserveO;
cbxGlobalDef.Checked :=ActiveProject.AddGlobalDef;
cbxErrorCheck.Checked :=ActiveProject.ErrorCheck;
cbxFBDebug.Checked := ActiveProject.FBDebug;
cbxResumeError.Checked := ActiveProject.ResumeError;
cbxNullPtr.Checked := ActiveProject.NullPtrCheck;
cbxArrayCheck.Checked := ActiveProject.ArrayCheck;
edOutExt.Text:=ActiveProject.ExeExt;
gDefName.Text:=ActiveProject.DefName;
gDefValue.Text:=ActiveProject.DefValue;
CheckListBox.Clear;
if (ActiveProject<>nil) and (ActiveProject.Dependencies.Count>0) then
CheckListBox.Items.Assign(ActiveProject.Dependencies)
else begin
L:=TStringList.Create;
L.Text:=StringReplace(Compiler.Switch,'-i',#10'-i',[rfreplaceall]);;
if L.Count>0 then begin
for i:=0 to L.Count-1 do begin
s:=trim(L[i]);
if pos('-i',s)>0 then begin
D:=TDependencie.Create;
D.kind:=dkPath;
D.item:=trim(copy(s,pos('"',s)+1,lastdelimiter('"',s)-pos('"',s)-1));
if CheckListBox.Items.IndexOf(D.item)=-1 then
CheckListBox.Items.AddObject(D.item,D);
end;
if pos('-include',s)>0 then begin
D:=TDependencie.Create;
D.kind:=dkFile;
D.item:=trim(copy(s,pos('"',s)+1,lastdelimiter('"',s)-pos('"',s)-1));
if CheckListBox.Items.IndexOf(D.item)=-1 then
CheckListBox.Items.AddObject(D.item,D);
end;
end;
end;
if DirectoryExists(ExtractFilePath(ActiveProject.FileName)) then begin
FindFiles(CheckListBox.Items,ExtractFilePath(ActiveProject.FileName),'*.bi');
for i:=0 to CheckListBox.Items.Count-1 do begin
D:=TDependencie.Create;
D.kind:=dkFile;
D.item:=CheckListBox.Items[i] ;
CheckListBox.Items.Objects[i]:=D;
end
end
end
end;
procedure TProjectProperties.btnAddClick(Sender: TObject);
var
D:TDependencie;
begin
with TOpenDialog.Create(nil) do begin
Caption:='Add include file for each compiled file';
Filter:='FreeBasic Files (*.bas,*.bi,*.fpk)|*.bas;*.bi;*.fpk|All files (*.*)|*.*';
if Execute then
if CheckListBox.Items.IndexOf(Filename)=-1 then begin
D:=TDependencie.Create;
D.kind:=dkFile;
D.item:=Filename;
CheckListBox.Items.AddObject(FileName,D);
end else CheckListBox.ItemIndex:=CheckListBox.Items.IndexOf(Filename);
Free
end;
end;
procedure TProjectProperties.btnOKClick(Sender: TObject);
function BuildProjectSwitch: string;
var
i:integer;
begin
result:='';
for i:=0 to CheckListBox.Items.Count-1 do begin
if DirectoryExists(CheckListBox.Items[i]) then
result:=result+format(' -i "%s"',[CheckListBox.Items[i]])
else
result:=result+format(' -include "%s"',[CheckListBox.Items[i]])
end ;
if ActiveProject.AddGlobalDef then
if ActiveProject.DefName<>'' then
if ActiveProject.DefValue<>'' then
result:=result+format(' -d #%s %s',[ActiveProject.DefName,ActiveProject.DefValue]);
if ActiveProject.DebugInfo then result:=result+' -edebuginfo';
if ActiveProject.Debug then result:=result+' -g';
if ActiveProject.CompileOnly then result:=result+' -c';
if ActiveProject.PreserveO then result:=result+' -C';
if ActiveProject.ErrorCheck then result:=result+' -e';
if ActiveProject.FBDebug then result:=result+' -edebug';
if ActiveProject.ResumeError then result:=result+' -ex';
if ActiveProject.NullPtrCheck then result:=result+' -exx';
end;
begin
if ActiveProject<>nil then begin
ActiveProject.Icon:=ImageIcon.Hint;
ActiveProject.Dependencies.Assign(CheckListBox.Items);
ActiveProject.DebugInfo:=cbxDebugInfo.Checked;
ActiveProject.Debug:=cbxAddDebug.Checked;
ActiveProject.CompileOnly:=cbxCompileOnly.Checked;
ActiveProject.PreserveO:=cbxPreserveO.Checked;
ActiveProject.AddGlobalDef:=cbxGlobalDef.Checked;
ActiveProject.ErrorCheck:=cbxErrorCheck.Checked;
ActiveProject.FBDebug:=cbxFBDebug.Checked;
ActiveProject.ResumeError:=cbxResumeError.Checked;
ActiveProject.NullPtrCheck:=cbxNullPtr.Checked;
ActiveProject.ArrayCheck:=cbxArrayCheck.Checked;
ActiveProject.ExeExt:=edOutExt.Text;
ActiveProject.DefName:=gDefName.Text;
ActiveProject.DefValue:=gDefValue.Text;
ActiveProject.Switch:=BuildProjectSwitch ;
end;
end;
procedure TProjectProperties.btnAddPathClick(Sender: TObject);
var
s:string;
D:TDependencie;
begin
if HelperUnit.BrowseForFolder(s,'Add dependecie path...') then begin
if CheckListBox.Items.IndexOf(s)=-1 then begin
D:=TDependencie.Create;
D.kind:=dkPath;
D.item:=s;
CheckListBox.Items.AddObject(s,D);
end else CheckListBox.ItemIndex:=CheckListBox.Items.IndexOf(s);
end;
end;
end.
|
{***************************************************************************}
{ }
{ DUnitX }
{ }
{ Copyright (C) 2015 Vincent Parrett & Contributors }
{ }
{ vincent@finalbuilder.com }
{ http://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ 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 DUnitX.Exceptions;
interface
{$I DUnitX.inc}
uses
{$IFDEF USE_NS}
System.SysUtils,
{$ELSE}
SysUtils,
{$ENDIF}
DUnitX.ComparableFormat;
type
ETestFrameworkException = class(Exception);
ENotImplemented = class(ETestFrameworkException);
//base exception for any internal exceptions which cause the test to stop
EAbort = class(ETestFrameworkException);
ETestFailure = class(EAbort);
ETestFailureStrCompare = class(ETestFailure)
private
FActual: string;
FExpected: string;
FMsg: string;
FFormat: TDUnitXComparableFormatClass;
public
property Actual: string read FActual;
property Expected: string read FExpected;
property Msg: string read FMsg;
property Format: TDUnitXComparableFormatClass read FFormat;
constructor Create(const aExpected, aActual, aMessage: string; const aFormat: TDUnitXComparableFormatClass); reintroduce;
end;
ETestPass = class(EAbort);
ETimedOut = class(EAbort);
ENoAssertionsMade = class(ETestFailure);
ENoTestsRegistered = class(ETestFrameworkException);
ECommandLineError = class(ETestFrameworkException);
implementation
uses
DUnitX.ResStrs;
constructor ETestFailureStrCompare.Create(const aExpected, aActual, aMessage: string; const aFormat: TDUnitXComparableFormatClass);
begin
FExpected := aExpected;
FActual := aActual;
FMsg := aMessage;
FFormat := aFormat;
inherited Create({$IFDEF USE_NS}System.{$ENDIF}SysUtils.Format(SNotEqualErrorStr,[aExpected, aActual, aMessage]));
end;
end.
|
unit UePad2;
{ ClickForms Application }
{ Bradford Technologies, Inc. }
{ All Rights Reserved }
{ Source Code Copyrighted © 1998-2005 by Bradford Technologies, Inc. }
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls,
UWinTab, UForms;
const
MaxPts = 2500;
epadHotSpotX = 100; //hard coded for now
epadHotSpotY = 486-140;
type
SgnPt = record
X: Integer;
Y: Integer;
Down: Boolean;
end;
SgnPtArray = Array of SgnPt;
TEPadSignature = class(TObject)
FName: String[63];
FReason: String[63];
FUsePSW: Boolean;
FCodedPSW: LongInt; //encoded PSW
FHotSpot: TPoint;
FBounds: TRect;
FScale: TPoint;
FColor: TColor;
FWidth: Integer;
FPts: SgnPtArray; //Array of SgnPt;
procedure ReadSignatureData(stream: TStream);
procedure WriteSignatureData(stream: TStream);
end;
TEPadInterface = class(TAdvancedForm)
SignerName: TEdit;
Label1: TLabel;
SignerReason: TComboBox;
Label2: TLabel;
btnClear: TButton;
btnCancel: TButton;
btnSignIt: TButton;
SignatureArea: TPaintBox;
procedure SignerNameChange(Sender: TObject);
procedure SignatureAreaPaint(Sender: TObject);
procedure btnClearClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure FormShow(Sender: TObject);
private
FWinTabDLL: THandle;
FWTContext: HCTX;
FWTOpened: Boolean;
FPenContactChanged: Boolean;
FPenInContact: Boolean;
FPrevPt: TPoint;
FCtxOrg: TPoint; //tablet origin
FCtxExt: TPoint; //tablet lengths
FSgnArea: TPoint; //signature area on dialog (for scaling)
FNumPts: Integer; //num pts in signature
FPts: SgnPtArray; //Array of SgnPt; //actual signature pts
function SignPtsBounds: TRect;
function GetEPadSiganture: TEPadSignature;
procedure ProcessPacketInfo(wSerial, hContext: LongInt);
procedure MsgWTPacket(var Message: TMessage); message WT_PACKET;
procedure MsgWTProximity(var Message: TMessage); message WT_PROXIMITY;
function GetPrintedName: string;
procedure SetPrintedName(const Value: string);
procedure AdjustDPISettings;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Signature: TEPadSignature read GetEPadSiganture;
property PrintedName: string read GetPrintedName write SetPrintedName;
end;
implementation
uses
Math,
UGlobals, UStatus;
{$R *.DFM}
constructor TEPadInterface.Create(AOwner: TComponent);
var
ePadInfo: array[0..255] of char;
LCntx: LOGCONTEXT;
begin
inherited Create(AOwner);
btnSignIt.enabled := False;
btnClear.enabled := False;
FPenContactChanged := False;
FPenInContact := False;
//Setup the WinTab DLL
FWinTabDLL := LoadLibrary('Wintab32.dll'); //find the DLL
if FWinTabDLL >= 32 then
begin
if LoadWinTabFunctions(FWinTabDLL) then //load the function
begin
if (WTInfo(WTI_INTERFACE, IFC_WINTABID, Pointer(@epadInfo)) >0) and
(WTInfo(WTI_DEFCONTEXT, 0, PLOGCONTEXT(@LCntx)) >0) then
begin
LCntx.lcOptions := CXO_MESSAGES {or CXO_MARGIN}; //want messages and margin
LCntx.lcPktData := PK_X or PK_Y; //want x and y
LCntx.lcPktMode := 0; //want them in absolute coords = 0
//PK_GETALL = PK_CONTEXT or PK_STATUS or PK_TIME or PK_SERIAL_NUMBER or PK_BUTTONS or PK_X or PK_Y or PK_Z;
FWTContext := WTOpen(Handle, LCntx, True);
FWTOpened := FWTContext <> 0;
FCtxOrg.x := LCntx.lcInOrgX;
FCtxOrg.y := LCntx.lcInOrgY;
FCtxExt.x := LCntx.lcInExtX;
FCtxExt.y := LCntx.lcInExtY;
FSgnArea.x := SignatureArea.width;
FSgnArea.y := SignatureArea.height;
FPenInContact := False;
FPenContactChanged := False;
FPrevPt := Point(0,0);
FNumPts := 0;
SetLength(FPts,MaxPts);
end;
end;
end
else
ShowNotice('Could not load the WinTab32 DLL. Make sure it is in the system folder.');
end;
destructor TEPadInterface.Destroy;
begin
if FWTOpened then //close the tablet
WTClose(FWTContext);
if FWinTabDLL >= 32 then //release the DLL
FreeLibrary(FWinTabDLL);
inherited Destroy; //goodbye
end;
function TEPadInterface.GetEPadSiganture: TEPadSignature;
begin
result := TEPadSignature.Create;
try
result.FName := copy(SignerName.text, 1, Min(length(SignerName.text), 63));
result.FReason := copy(SignerReason.text, 1, Min(length(SignerReason.text), 63));
result.FUsePSW := False;
result.FCodedPSW := 0;
result.FBounds := SignPtsBounds;
result.FScale := Point(FCtxExt.x, FCtxExt.y);
result.FHotSpot := Point(epadHotSpotX, epadHotSpotY);
result.FColor := clBlack;
result.FWidth := 2;
//chop our array to just real points
SetLength(FPts, FNumPts);
result.FPts := Copy(FPts, 0, length(FPts));
except
FreeAndNil(result);
end;
end;
function TEPadInterface.SignPtsBounds: TRect;
var
n: Integer;
begin
result := Rect(10000,10000, -10000,-10000);
for n := 0 to FNumPts-1 do
begin
if FPts[n].X > result.right then result.right := FPts[n].X;
if FPts[n].X < result.left then result.left := FPts[n].X;
if FPts[n].Y > result.bottom then result.bottom := FPts[n].Y;
if FPts[n].Y < result.top then result.top := FPts[n].Y;
end;
end;
procedure TEPadInterface.MsgWTProximity(var Message: TMessage);
begin
//toggle pen up and pen down conditions
FPenContactChanged := True;
FPenInContact := not FPenInContact;
if FPenInContact then
FPts[FNumPts].Down := FPenInContact
else
FPts[FNumPts-1].Down := FPenInContact; //went up on prev pt
SignerNameChange(nil); //can we enable sign it??
end;
procedure TEPadInterface.MsgWTPacket(var Message: TMessage);
begin
if Message.Msg = WT_Packet then
begin
ProcessPacketInfo(Message.WParam, message.LParam);
end;
end;
procedure TEPadInterface.ProcessPacketInfo(wSerial, hContext: LongInt);
var
PenPkt: PacketRec;
newPt: TPoint;
begin
WTPacket(HCTX(hContext), wSerial, PenPkt);
with SignatureArea.Canvas do
begin
Pen.Color := clBlack;
Pen.width := 2;
FPts[FNumPts].Down := FPenInContact;
if FPenContactChanged then
if FPenInContact then
begin
FPrevPt.x := penPkt.pkX-FCtxOrg.x;
FPrevPt.y := FCtxExt.y - (penPkt.pkY-FCtxOrg.y);
FPts[FNumPts].X := penPkt.pkX-FCtxOrg.x;
FPts[FNumPts].Y := FCtxExt.y - (penPkt.pkY-FCtxOrg.y);
Inc(FNumPts);
FPenContactChanged := False;
end
else
else
if FPenInContact then
begin
newPt.x := penPkt.PkX-FCtxOrg.x;
newPt.y := FCtxExt.y - (penPkt.pkY-FCtxOrg.y);
MoveTo(MulDiv(FPrevPt.x,FSgnArea.x,FCtxExt.x), MulDiv(FPrevPt.y,FSgnArea.y,FCtxExt.y));
LineTo(MulDiv(newPt.x,FSgnArea.x,FCtxExt.x), MulDiv(newPt.y,FSgnArea.y,FCtxExt.y));
FPrevPt.x := newPt.x;
FPrevPt.y := newPt.y;
FPts[FNumPts].X := penPkt.pkX-FCtxOrg.x;
FPts[FNumPts].Y := FCtxExt.y - (penPkt.pkY-FCtxOrg.y);
Inc(FNumPts);
btnClear.enabled := True; //have pts to clear
end;
if FnumPts > MaxPts then FNumPts := MaxPts;
(*
textout(10,5, 'nPts='+IntToStr(FNumPts));
textout(10,20, 'X='+IntToStr(FPrevPt.x)); textout(100, 20, 'Y='+IntToStr(FPrevPt.y));
textout(10,35, 'X='+IntToStr(MulDiv(FPrevPt.x,FSgnArea.x,FCtxExt.x))); textout(100,35,'Y='+IntToStr(MulDiv(FPrevPt.y,FSgnArea.y,FCtxExt.y)));
textout(10,10, 'CTX='+IntToStr(penPkt.pkContext)); textout(100, 10, 'ST='+IntToStr(penPkt.pkStatus));
textout(10,40, 'TIM='+IntToStr(penPkt.pkTime)); textout(100, 40, 'Chg='+IntToStr(penPkt.pkChanged));
textout(10,60, 'SerNm='+IntToStr(penPkt.pkSerialNumber)); textout(100, 60, 'CUR='+IntToStr(penPkt.pkCursor));
textout(10,80,'BTN='+IntToStr(penPkt.pkButtons));
textout(10,100, 'X='+IntToStr(penPkt.pkX)); textout(100, 100, 'Y='+IntToStr(penPkt.PkY)); textout(190, 100, 'Z='+IntToStr(penPkt.PkZ));
textout(10,120, 'NPRS='+IntToStr(penPkt.pkNormalPressure));
*)
end;
end;
procedure TEPadInterface.SignatureAreaPaint(Sender: TObject);
var
area: TRect;
begin
Area := Rect(0,0,signatureArea.width, signatureArea.height);
With SignatureArea.Canvas do
begin
FillRect(area);
Brush.color := clBlack;
FrameRect(area);
Brush.color := clWhite;
Pen.color := clLtGray;
Pen.width := 2;
MoveTo(MulDiv(30,345,981), MulDiv(486-140,155,486));
LineTo(MulDiv(950,345,981), MulDiv(486-140,155,486));
MoveTo(MulDiv(68,345,981), MulDiv(486-230,155,486));
LineTo(MulDiv(109,345,981), MulDiv(486-116,155,486));
MoveTo(MulDiv(26,345,981), MulDiv(486-97,155,486));
LineTo(MulDiv(138,345,981), MulDiv(486-230,155,486));
end;
end;
procedure TEPadInterface.SignerNameChange(Sender: TObject);
begin
if (length(SignerName.Text) > 0) and (FNumPts > 20) then
begin
btnSignIt.enabled := True;
if FNumPts = 0 then
FocusControl(btnSignIt);
end
else
btnSignIt.enabled := False;
end;
procedure TEPadInterface.btnClearClick(Sender: TObject);
begin
FPts := nil; //delete previous pts
FNumPts := 0;
SetLength(FPts, maxPts); //setup for new signature
SignatureAreaPaint(Sender);
SignerNameChange(Sender);
end;
procedure TEPadInterface.Button1Click(Sender: TObject);
var
n: Integer;
begin
SignatureAreaPaint(Sender);
With SignatureArea.Canvas do
begin
Pen.Color := clBlack;
Pen.width := 2;
MoveTo(MulDiv(FPts[1].X,FSgnArea.x,FCtxExt.x), MulDiv(FPts[1].Y,FSgnArea.y,FCtxExt.y));
for n := 1 to FNumPts-1 do
begin
if FPts[n-1].Down then
LineTo(MulDiv(FPts[n].X,FSgnArea.x,FCtxExt.x), MulDiv(FPts[n].Y,FSgnArea.y,FCtxExt.y))
else
MoveTo(MulDiv(FPts[n].X,FSgnArea.x,FCtxExt.x), MulDiv(FPts[n].Y,FSgnArea.y,FCtxExt.y));
end;
end;
end;
function TEPadInterface.GetPrintedName: string;
begin
result := SignerName.Text;
end;
procedure TEPadInterface.SetPrintedName(const Value: string);
begin
SignerName.Text := Value;
end;
{ TEPadSignature }
procedure TEPadSignature.WriteSignatureData(stream: TStream);
var
strBuff: Str63;
amt,arrayLen: LongInt;
begin
strBuff := FName;
Stream.WriteBuffer(strBuff, Length(strBuff) + 1); //write the signature name
strBuff := FReason;
Stream.WriteBuffer(strBuff, Length(strBuff) + 1); //write the signature reason
amt := SizeOf(Boolean);
stream.WriteBuffer(FUsePSW, amt);
amt := SizeOf(LongInt);
stream.WriteBuffer(FCodedPSW, amt);
amt := SizeOf(TPoint);
stream.WriteBuffer(FHotSpot, amt);
amt := SizeOf(TRect);
stream.WriteBuffer(FBounds, amt);
amt := SizeOf(TPoint);
stream.WriteBuffer(FScale, amt);
amt := SizeOf(TColor);
stream.WriteBuffer(FColor, amt);
amt := SizeOf(Integer);
stream.WriteBuffer(FWidth, amt);
ArrayLen := length(FPts);
amt := SizeOf(Integer);
stream.WriteBuffer(ArrayLen, amt);
amt := ArrayLen * SizeOf(SgnPt);
stream.WriteBuffer(Pointer(FPts)^, Amt);
end;
procedure TEPadSignature.ReadSignatureData(stream: TStream);
var
strBuff: Str63;
amt,arrayLen: LongInt;
begin
Stream.Read(strBuff[0], 1); //read the length of name
Stream.Read(strBuff[1], Integer(strBuff[0])); //read the chacters of name
FName := strBuff;
Stream.Read(strBuff[0], 1); //read the length of reason
Stream.Read(strBuff[1], Integer(strBuff[0])); //read the chacters of reason
FReason := strBuff;
amt := SizeOf(Boolean);
stream.Read(FUsePSW, amt);
amt := SizeOf(LongInt);
stream.Read(FCodedPSW, amt);
amt := SizeOf(TPoint);
stream.Read(FHotSpot, amt);
amt := SizeOf(TRect);
stream.Read(FBounds, amt);
amt := SizeOf(TPoint);
stream.Read(FScale, amt);
amt := SizeOf(TColor);
stream.Read(FColor, amt);
amt := SizeOf(Integer);
stream.Read(FWidth, amt);
amt := SizeOf(Integer);
stream.Read(ArrayLen, amt);
SetLength(FPts, ArrayLen);
amt := ArrayLen * SizeOf(SgnPt);
// stream.ReadBuffer(FPts, Amt);
stream.ReadBuffer(Pointer(FPts)^, Amt);
end;
procedure TEPadInterface.AdjustDPISettings;
begin
self.Width := btnSignIt.Left + btnSignIt.Width + 50;
self.height := btnSignIt.Top + btnSignIt.Height + 100;
self.Constraints.MinWidth := self.Width;
self.Constraints.MinHeight := self.Height;
end;
procedure TEPadInterface.FormShow(Sender: TObject);
begin
AdjustDPISettings;
end;
end.
|
unit UTimer;
interface
uses Windows;
type
cTimer = class
private
QPF,
pause,
realTime,
QPC: Int64;
public
constructor Create(fps: integer);
procedure SetPause(fps: integer);
function Run: Boolean;
end;
implementation
constructor cTimer.Create(fps: integer);
begin
QueryPerformanceFrequency(QPF);
pause:=qpf div fps;
QPC:=0;
end;
procedure cTimer.SetPause(fps: integer);
begin
pause:=qpf div fps;
end;
function cTimer.Run: Boolean;
begin
QueryPerformanceCounter(realTime);
if realTime > QPC then
begin
QueryPerformanceCounter(QPC);
QPC := QPC + pause;
Result := True;
end else
Result := False;
end;
end.
|
unit uInputBox;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Mask, Buttons, ExtCtrls, TipoDado, RxToolEdit, RxCurrEdit;
type
TfrmInputBox = class(TForm)
Panel1: TPanel;
panTopo: TPanel;
Label1: TLabel;
panCentro: TPanel;
panRodaPe: TPanel;
panBotoes: TPanel;
btnCancela: TBitBtn;
btnConfirma: TBitBtn;
Shape1: TShape;
Shape2: TShape;
procedure ComponenteRetornoChange(Sender: TObject);
procedure btnCancelaClick(Sender: TObject);
procedure btnConfirmaClick(Sender: TObject);
procedure ComponenteRetornoExit(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure memRetornoKeyPress(Sender: TObject; var Key: Char);
procedure FormShow(Sender: TObject);
private
FTipoRetorno :TTipoDado;
FRetorno :variant;
FComponenteRetorno :TCustomEdit;
NumDigitado :String;
tipo :String;
procedure trataRetorno;
procedure configuraTela;
procedure configuraEventos;
public
property Retorno :variant read FRetorno;
constructor Create(AOwner: TComponent; titulo: String; TipoDado :TTipoDado); overload; virtual;
end;
var
frmInputBox: TfrmInputBox;
implementation
{$R *.dfm}
constructor TfrmInputBox.Create(AOwner: TComponent; titulo: String; TipoDado :TTipoDado);
begin
self.Create(aOwner);
label1.Caption := titulo;
FTipoRetorno := tipoDado;
configuraTela;
configuraEventos;
end;
procedure TfrmInputBox.configuraEventos;
begin
case FTipoRetorno of
tpInteiro, tpMoeda, tpQuantidade:
begin
TCurrencyEdit(FComponenteRetorno).OnChange := ComponenteRetornoChange;
// TCurrencyEdit(FComponenteRetorno).OnExit := ComponenteRetornoExit;
end;
tpNome:
begin
TEdit(FComponenteRetorno).OnChange := ComponenteRetornoChange;
// TEdit(FComponenteRetorno).OnExit := ComponenteRetornoExit;
end;
tpTexto:
begin
TMemo(FComponenteRetorno).OnChange := ComponenteRetornoChange;
// TMemo(FComponenteRetorno).OnExit := ComponenteRetornoExit;
end;
tpData:
begin
TMaskEdit(FComponenteRetorno).OnChange := ComponenteRetornoChange;
TMaskEdit(FComponenteRetorno).OnExit := ComponenteRetornoExit;
end;
end;
end;
procedure TfrmInputBox.configuraTela;
begin
case FTipoRetorno of
tpInteiro:
begin
FComponenteRetorno := TCurrencyEdit.Create(nil);
TCurrencyEdit(FComponenteRetorno).DisplayFormat := '0';
TCurrencyEdit(FComponenteRetorno).Text := '0';
end;
tpMoeda:
begin
FComponenteRetorno := TCurrencyEdit.Create(nil);
TCurrencyEdit(FComponenteRetorno).DisplayFormat := 'R$ ,0.00;-,0.00';
TCurrencyEdit(FComponenteRetorno).Text := '0,001';
end;
tpQuantidade:
begin
FComponenteRetorno := TCurrencyEdit.Create(nil);
TCurrencyEdit(FComponenteRetorno).DisplayFormat := ',0.000;-,0.000';
TCurrencyEdit(FComponenteRetorno).DecimalPlaces := 3;
TCurrencyEdit(FComponenteRetorno).Text := '0,0001';
end;
tpNome:
FComponenteRetorno := TEdit.Create(nil);
tpTexto:
FComponenteRetorno := TMemo.Create(nil);
tpData:
begin
TMaskEdit(FComponenteRetorno).EditMask := '!99/99/9999;1; ';
end;
end;
FComponenteRetorno.Parent := panCentro;
case FTipoRetorno of
tpInteiro, tpMoeda, tpQuantidade:
begin
FComponenteRetorno.Left := trunc((panCentro.Width/2) - (FComponenteRetorno.Width/2));
FComponenteRetorno.top := trunc((panCentro.Height/2) - (FComponenteRetorno.Height/2));
end;
tpNome:
begin
self.Width := 500;
FComponenteRetorno.Left := 40;
FComponenteRetorno.Width := self.Width - 80;
FComponenteRetorno.Height := trunc((panCentro.Height/2) - (FComponenteRetorno.Height/2));
end;
tpTexto:
begin
self.Width := 600;
self.Height := 200;
FComponenteRetorno.Top := 5;
FComponenteRetorno.Left := 30;
FComponenteRetorno.Width := self.Width - 60;
FComponenteRetorno.Height := self.Height - 10;
end;
end;
FComponenteRetorno.SelectAll;
end;
procedure TfrmInputBox.ComponenteRetornoChange(Sender: TObject);
begin
case FTipoRetorno of
tpInteiro: FRetorno := TCurrencyEdit(Sender).AsInteger;
tpMoeda, tpQuantidade: FRetorno := TCurrencyEdit(Sender).Value;
tpNome: FRetorno := TEdit(Sender).Text;
tpTexto: FRetorno := TMemo(Sender).Lines.Text;
tpData: FRetorno := StrToDate(TMaskEdit(Sender).Text);
end;
end;
procedure TfrmInputBox.btnCancelaClick(Sender: TObject);
begin
self.ModalResult := mrCancel;
end;
procedure TfrmInputBox.btnConfirmaClick(Sender: TObject);
begin
self.ModalResult := mrOk;
end;
procedure TfrmInputBox.trataRetorno;
begin
end;
procedure TfrmInputBox.ComponenteRetornoExit(Sender: TObject);
begin
if FTipoRetorno = tpData then begin
try
strToDate(FComponenteRetorno.Text);
except
showmessage('Data inválida');
FComponenteRetorno.SetFocus;
end;
end;
end;
procedure TfrmInputBox.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if key = VK_Escape then
btnCancela.Click;
end;
procedure TfrmInputBox.FormShow(Sender: TObject);
begin
FComponenteRetorno.SetFocus;
end;
procedure TfrmInputBox.memRetornoKeyPress(Sender: TObject; var Key: Char);
begin
If ( key in[';'] ) then
key:=#0;
end;
end.
|
unit EnglishTranslator;
interface
uses Translator;
type
TEnglishTranslator = class(TTranslator)
public
constructor Create;
end;
implementation
constructor TEnglishTranslator.Create;
begin
{ main ui translations }
Self.add('searchbtn.title', 'Search');
{ car detail translations }
Self.add('car.tabpanel.general.title', 'General');
Self.add('car.tabpanel.history.title', 'History');
Self.add('car.tabpanel.tasks.title', 'Tasks');
end;
end.
|
program PL0(input,output);
{ PL/0 compiler with code generation }
{带有代码生成的 PL0 编译程序}
{常量定义}
const
norw = 13; {保留字的个数}
txmax = 100; {标识符表长度}
nmax = 14; {数字的最大位数}
al = 10; {记号的长度}
amax = 2047; {最大地址}
levmax = 3; {程序体嵌套的最大深度}
cxmax = 200; {代码数组的大小}
{类型变量定义}
type
{symbol的宏定义为一个枚举}
symbol = (
nul, ident, number, plus, minus, times, slash, oddsym, eql, neq, lss,
leq, gtr, geq, lparen, rparen, comma, semicolon, period, becomes, beginsym,
endsym, ifsym, thensym, whilesym, dosym, callsym, constsym, varsym, procsym, readsym, writesym);
alfa = packed array [1..al] of char; {alfa宏定义为含有a1个元素的合并数组,为标识符的类型}
objecttyp = (constant, variable, prosedure); {objecttyp的宏定义为一个枚举}
symset = set of symbol; {symset为symbol的集合}
fct = (lit, opr, lod, sto, cal, int, jmp, jpc, red, wrt); {functions} {fct为一个枚举,其实是PCODE的各条指令}
instruction = packed record {instruction声明为一个记录类型}
f : fct; {功能码}
l : 0..levmax; {相对层数}
a : 0..amax; {相对地址}
end;
{
LIT 0,a : 取常数 a (读取常量a到数据栈栈顶)
OPR 0,a : 执行运算 a
LOD l,a : 取层差为 l 的层﹑相对地址为 a 的变量 (读取变量放到数据栈栈顶,变量的相对地址为a,层次差为l)
STO l,a : 存到层差为 l 的层﹑相对地址为 a 的变量 (将数据栈栈顶内容存入变量,变量的相对地址为a,层次差为l)
CAL l,a : 调用层差为 l 的过程 (调用过程,过程入口指令为a,层次差为l)
INT 0,a : t 寄存器增加 a (数据栈栈顶指针增加a)
JMP 0,a : 无条件转移到指令地址 a 处
JPC 0,a : 条件转移到指令地址 a 处
red l, a : 读数据并存入变量,
wrt 0, 0 : 将栈顶内容输出
}
{全局变量定义}
var
ch : char; {最近读到的字符}
sym : symbol; {最近读到的符号}
id : alfa; {最近读到的标识符}
num : integer; {最近读到的数}
cc : integer; {当前行的字符计数}
ll : integer; {当前行的长度}
kk, err : integer; {代码数组的当前下标}
cx : integer; {当前行}
line : array [1..81] of char; {当前标识符的字符串}
a : alfa; {用来存储symbol的变量}
code : array [0..cxmax] of instruction; {中间代码数组}
word : array [1..norw] of alfa; {存放保留字的字符串}
wsym : array [1..norw] of symbol; {存放保留字的记号}
ssym : array [char] of symbol; {存放算符和标点符号的记号}
mnemonic : array [fct] of
packed array [1..5] of char; {中间代码算符的字符串}
declbegsys, statbegsys, facbegsys : symset; {声明开始,表达式开始、项开始的符号集合}
table : array [0..txmax] of {符号表}
record {表中的元素类型是记录类型}
name : alfa; {元素名}
case kind : objecttyp of {根据符号的类型保存相应的信息}
constant : (val : integer); {如果是常量,val中保存常量的值}
variable, prosedure : (level, adr : integer) {如果是变量或过程,保存存放层数和偏移地址}
end;
file_in : text; {源代码文件}
file_out : text; {输出文件}
procedure error (n : integer); {错误处理程序}
begin
writeln( file_out,'****', ' ':cc-1, '^', n:2 );{cc 为当前行已读的字符数, n 为错误号,报错提示信息,'↑'指向出错位置,并提示错误类型}
err := err + 1 {错误数 err 加 1}
end {error};
procedure getsym; {词法分析程序}
var i, j, k : integer; {声明计数变量}
procedure getch ; {取下一字符}
begin
if cc = ll {如果 cc 指向行末,读完一行(行指针与该行长度相等)}
then begin {开始读取下一行}
if eof(file_in) {如果已到文件尾}
then begin
write(file_out,'PROGRAM INCOMPLETE'); {报错}
close(file_in);
close(file_out);{关闭文件}
exit; {退出}
end;
{读新的一行}
ll := 0;
cc := 0;
write(file_out,cx : 5, ' '); {cx : 5 位数,输出代码地址,宽度为5}
while not eoln(file_in) do {如果不是行末}
begin
ll := ll + 1; {将行缓冲区的长度+1}
read(file_in,ch); {从文件中读取一个字符到ch中}
write(file_out,ch); {控制台输出ch}
line[ll] := ch {把这个字符放到当前行末尾}
end;
writeln(file_out); {换行}
readln(file_in); {源文件读取从下一行开始}
ll := ll + 1; {将行缓冲区的长度+1}
line[ll] := ' ' { process end-line } {行数组最后一个元素为空格}
end;
cc := cc + 1; {行指针+1}
ch := line[cc] {ch 取 line 中下一个字符}
end {getch}; {结束读取下一字符}
begin {getsym} {开始标识符识别}
while ch = ' ' do
getch; {跳过无用空白}
if ch in ['a'..'z'] {标识符或保留字}
then begin
k := 0;
repeat {处理字母开头的字母﹑数字串}
if k < al {如果k的大小小于标识符的最大长度}
then begin
k:= k + 1;
a[k] := ch {将ch写入标识符暂存变量a}
end;
getch
until not (ch in ['a'..'z','0'..'9']); {直到读出的不是数字或字母的时候,标识符结束}
if k >= kk {后一个标识符大于等于前一个的长度}
then kk := k {kk记录当前标识符的长度k}
else repeat {如果标识符长度不是最大长度, 后面补空白}
a[kk] := ' ';
kk := kk-1
until kk = k;
id := a; {id 中存放当前标识符或保留字的字符串}
i := 1; {i指向第一个保留字}
j := norw; {j为保留字的最大数目}
{用二分查找法在保留字表中找当前的标识符id}
repeat
k := (i+j) div 2;
if id <= word[k] then j := k-1;
if id >= word[k] then i := k+1
until i > j;
{如果找到, 当前记号 sym 为保留字, 否则 sym 为标识符}
if i-1 > j
then sym := wsym[k]
else sym := ident
end
else if ch in ['0'..'9'] {如果字符是数字}
then begin
k := 0; {记录数字的位数}
num := 0;
sym := number; {当前记号 sym 为数字}
repeat {计算数字串的值}
num := 10*num+(ord(ch)-ord('0')); {ord(ch)和 ord(0)是 ch 和 0 在 ASCII 码中的序号}
k := k + 1;
getch;
until not (ch in ['0'..'9']);
if k > nmax {当前数字串的长度超过上界,则报告错误}
then error(30)
end
else if ch = ':' {处理赋值号}
then begin
getch;
if ch = '='
then begin
sym := becomes; {将标识符置为becomes,表示复制}
getch
end
else sym := nul; {否则,将标识符设置为nul,表示非法}
end
else if ch = '<' {处理'<'}
then begin
getch;
if ch = '='
then begin
sym := leq; {表示小于等于}
getch {读下一个字符}
end
else if ch = '>' {处理'>'}
then begin
sym := neq; {表示不等于}
getch
end
else sym := lss {表示小于}
end
else if ch = '>' {处理'<'}
then begin
getch;
if ch = '='
then begin
sym := geq; {表示大于等于}
getch {读下一个字符}
end
else sym := gtr {表示大于}
end
else {处理其它算符或标点符号}
begin
sym := ssym[ch];
getch
end
end {getsym}; {结束标识符的识别}
procedure gen(x : fct; y, z : integer); {目标代码生成过程,x表示PCODE指令,y,z是指令的两个操作数}
begin
if cx > cxmax {如果当前指令序号>代码的最大长度}
then begin
write(file_out,'PROGRAM TOO LONG');
close(file_in);
close(file_out); {关闭文件}
exit
end;
with code[cx] do {在代码数组 cx 位置生成一条新代码}
begin {instruction类型的三个属性}
f := x; {功能码}
l := y; {层号}
a := z {地址}
end;
cx := cx + 1 {指令序号加 1}
end {gen};
procedure test(s1, s2 : symset; n : integer); {测试当前字符合法性过程,用于错误语法处理,若不合法则跳过单词值只读到合法单词为止}
begin
if not (sym in s1) {如果当前记号不属于集合 s1,则报告错误 n}
then begin
error(n);
s1 := s1 + s2; {将s1赋值为s1和s2的集合}
while not (sym in s1) do
getsym {跳过所有不合法的符号,直到当前记号属于 s1∪s2,恢复语法分析工作}
end
end {test};
procedure block(lev, tx : integer; fsys : symset); {进行语法分析的主程序,lev表示语法分析所在层次,tx是当前符号表指针,fsys是用来恢复错误的单词集合}
var
dx : integer; {本过程数据空间分配下标}
tx0 : integer; {本过程标识表起始下标}
cx0 : integer; {本过程代码起始下标}
procedure enter(k : objecttyp); {将对象插入到符号表中}
begin {把 object 填入符号表中}
tx := tx +1; {符号表指针加 1,指向一个空表项}
with table[tx] do{在符号表中增加新的一个条目}
begin
name := id; {当前标识符的名字}
kind := k; {当前标识符的种类}
case k of
constant : begin {当前标识符是常数名}
if num > amax
then {当前常数值大于上界,则出错} begin
error(30);
num := 0 {将常量置零}
end;
val := num {val保存该常量的值}
end;
variable : begin {当前标识符是变量名}
level := lev; {定义该变量的过程的嵌套层数}
adr := dx; {变量地址为当前过程数据空间栈顶}
dx := dx +1; {栈顶指针加 1}
end;
prosedure : level := lev; {本过程的嵌套层数}
end
end
end {enter};
function position(id : alfa) : integer; {返回 id 在符号表的入口}
var i : integer;
begin {在标识符表中查标识符 id}
table[0].name := id; {在符号表栈的最下方预填标识符 id}
i := tx; {符号表栈顶指针}
while table[i].name <> id do
i := i-1; {从符号表栈顶往下查标识符 id}
position := i {若查到,i 为 id 的入口,否则 i=0 }
end {position};
procedure constdeclaration; {处理常量声明的过程}
begin
if sym = ident
then {当前记号是常数名} begin
getsym;
if sym in [eql, becomes]
then {当前记号是等号或赋值号} begin
if sym = becomes
then error(1); {如果当前记号是赋值号,则出错,因为常量不能被赋值}
getsym;
if sym = number
then {等号后面是常数} begin
enter(constant); {将常数名加入符号表}
getsym
end
else error(2) {等号后面不是常数出错}
end
else error(3) {标识符后不是等号或赋值号出错}
end
else error(4){常数说明中没有常数名标识符}
end {constdeclaration};
procedure vardeclaration; {变量声明要求第一个sym为标识符}
begin
if sym = ident
then {如果当前记号是标识符} begin
enter(variable); {将该变量名加入符号表的下一条目}
getsym
end
else error(4) {如果变量说明未出现标识符,则出错}
end {vardeclaration};
procedure listcode; {列出PCODE的过程}
var i : integer;
begin {列出本程序体生成的代码}
for i := cx0 to cx-1 do {cx0: 本过程第一个代码的序号, cx―1: 本过程最后一个代码的序号}
with code[i] do {打印第 i 条代码}
{i: 代码序号; mnemonic[f]: 功能码的字符串; l: 相对层号(层差); a: 相对地址或运算号码}
{格式化输出}
writeln(file_out, i:5, mnemonic[f] : 7, l : 3, a : 5)
end {listcode};
procedure statement(fsys : symset); {语句处理的过程}
var i, cx1, cx2 : integer;
procedure expression(fsys : symset); {处理表达式的过程}
var addop : symbol;
procedure term(fsys : symset); {处理项的过程}
var mulop : symbol;
procedure factor(fsys : symset); {处理因子的处理程序}
var i : integer;
begin
test(facbegsys, fsys, 24); {测试当前的记号是否因子的开始符号, 否则出错, 跳过一些记号}
while sym in facbegsys do {循环处理因子}
begin
if sym = ident
then {当前记号是标识符} begin
i := position(id); {查符号表,返回 id 的入口}
if i = 0 {若在符号表中查不到 id, 则出错, 否则,做以下工作}
then error(11)
else
with table[i] do {对第i个表项的内容}
case kind of
constant : gen(lit, 0, val); {若 id 是常数, 生成LIT指令,操作数为0,val,将常数 val 取到栈顶}
variable : gen(lod,lev-level,adr); {若 id 是变量, 生成LOD指令,将该变量取到栈顶; lev: 当前语句所在过程的层号; level: 定义该变量的过程层号; adr: 变量在其过程的数据空间的相对地址}
prosedure : error(21) {若 id 是过程名, 则出错}
end;
getsym {取下一记号}
end
else if sym = number
then {当前记号是数字} begin
if num > amax
then {若数值越界,则出错} begin
error(30);
num := 0
end;
gen(lit, 0, num); {生成一条LIT指令, 将常数 num 取到栈顶}
getsym {取下一记号}
end
else if sym = lparen
then {如果当前记号是左括号} begin
getsym; {取下一记号}
expression([rparen]+fsys); {调用表达式的过程来处理,递归下降子程序方法}
if sym = rparen {如果当前记号是右括号, 则取下一记号,否则出错}
then getsym
else error(22)
end;
test(fsys, [lparen], 23) {测试当前记号是否同步, 否则出错, 跳过一些记号}
end {while}
end {factor};
begin {term} {项的分析过程开始}
factor(fsys+[times, slash]); {处理项中第一个因子}
while sym in [times, slash] do {当前记号是“乘”或“除”号}
begin
mulop := sym; {运算符存入 mulop}
getsym; {取下一记号}
factor(fsys+[times, slash]); {处理因子分析程序分析运算符后的因子}
if mulop = times
then gen(opr, 0, 4) {若 mulop 是“乘”号,生成一条乘法指令}
else gen(opr, 0, 5) {否则, mulop 是除号, 生成一条除法指令}
end
end {term};
begin {expression} {表达式的分析过程开始}
if sym in [plus, minus]
then {若第一个记号是加号或减号} begin
addop := sym; {“+”或“―”存入 addop}
getsym;
term(fsys+[plus, minus]); {处理负号后面的项}
if addop = minus
then gen(opr, 0, 1) {若第一个项前是负号, 生成一条“负运算”指令}
end
else term(fsys+[plus, minus]); {第一个记号不是加号或减号, 则处理一个项}
while sym in [plus, minus] do {若当前记号是加号或减号,可以接若干个term,使用操作符+-相连}
begin
addop := sym; {当前算符存入 addop}
getsym; {取下一记号}
term(fsys+[plus, minus]); {处理运算符后面的项}
if addop = plus
then gen(opr, 0, 2) {若 addop 是加号, 生成一条加法指令}
else gen(opr, 0, 3) {否则, addop 是减号, 生成一条减法指令}
end
end {expression};
procedure condition(fsys : symset); {条件处理过程}
var relop : symbol;
begin
if sym = oddsym
then {如果当前记号是"odd"} begin
getsym; {取下一记号}
expression(fsys); {处理算术表达式}
gen(opr, 0, 6) {生成指令,判定表达式的值是否为奇数,是,则取"真";不是, 则取"假"}
end
else {如果当前记号不是"odd"} begin
expression([eql, neq, lss, gtr, leq, geq] + fsys); {处理算术表达式,对表达式进行计算}
if not (sym in [eql, neq, lss, leq, gtr, geq]) {如果当前记号不是关系符, 则出错; 否则,做以下工作}
then error(20)
else begin
relop := sym; {关系符存入relop}
getsym; {取下一记号}
expression(fsys); {处理关系符右边的算术表达式}
case relop of
eql : gen(opr, 0, 8); {生成指令, 判定两个表达式的值是否相等}
neq : gen(opr, 0, 9); {生成指令, 判定两个表达式的值是否不等}
lss : gen(opr, 0, 10);{生成指令, 判定前一表达式是否小于后一表达式}
geq : gen(opr, 0, 11);{生成指令, 判定前一表达式是否大于等于后一表达式}
gtr : gen(opr, 0, 12);{生成指令, 判定前一表达式是否大于后一表达式}
leq : gen(opr, 0, 13);{生成指令, 判定前一表达式是否小于等于后一表达式}
end
end
end
end {condition};
begin {statement} {声明语句处理过程}
if sym = ident then {处理赋值语句}
begin
i := position(id); {在符号表中查id, 返回id在符号表中的入口}
if i = 0 then error(11) {若在符号表中查不到id, 则出错, 否则做以下工作}
else if table[i].kind <> variable then {若标识符id不是变量, 则出错}
begin
error(12);
i := 0; {对非变量赋值}
end;
getsym; {取下一记号}
if sym = becomes then getsym else error(13); {若当前是赋值号, 取下一记号, 否则出错}
expression(fsys); {处理表达式}
if i <> 0 then {若赋值号左边的变量id有定义}
with table[i] do
{lev: 当前语句所在过程的层号;
level: 定义变量id的过程的层号;
adr: 变量id在其过程的数据空间的相对地址}
gen(sto,lev-level,adr) {生成一条STO存数指令, 将栈顶(表达式)的值存入变量id中;}
end
else if sym = callsym then {处理过程调用语句}
begin
getsym; {取下一记号}
if sym <> ident then error(14){如果下一记号不是标识符(过程名),则出错,否则做以下工作}
else begin
i := position(id); {查符号表,返回id在表中的位置}
if i = 0 then error(11) else {如果在符号表中查不到, 则出错; 否则,做以下工作}
with table[i] do
if kind = prosedure {如果在符号表中id是过程名} then
gen(cal,lev-level,adr)
{生成一条过程调用指令;
lev: 当前语句所在过程的层号
level: 定义过程名id的层号;
adr: 过程id的代码中第一条指令的地址}
else error(15); {若id不是过程名,则出错}
getsym {取下一记号}
end
end
else if sym = ifsym then {处理条件语句}
begin
getsym; {取下一记号}
condition([thensym, dosym]+fsys); {处理条件表达式}
if sym = thensym then getsym else error(16);{如果当前记号是"then",则取下一记号; 否则出错}
cx1 := cx; {cx1记录下一代码的地址}
gen(jpc, 0, 0); {生成指令,表达式为"假"转到某地址(待填),否则顺序执行}
statement(fsys); {处理一个语句}
code[cx1].a := cx
{将下一个指令的地址回填到上面的jpc指令地址栏}
end
else if sym = beginsym then {处理语句序列}
begin
getsym;
statement([semicolon, endsym]+fsys); {取下一记号, 处理第一个语句}
while sym in [semicolon]+statbegsys do {如果当前记号是分号或语句的开始符号,则做以下工作}
begin
if sym = semicolon then getsym else error(10); {如果当前记号是分号,则取下一记号, 否则出错}
statement([semicolon, endsym]+fsys) {处理下一个语句}
end;
if sym = endsym then getsym else error(17) {如果当前记号是"end",则取下一记号,否则出错}
end
else if sym = whilesym then {处理循环语句}
begin
cx1 := cx; {cx1记录下一指令地址,即条件表达式的第一条代码的地址}
getsym; {取下一记号}
condition([dosym]+fsys); {处理条件表达式}
cx2 := cx; {记录下一指令的地址}
gen(jpc, 0, 0); {生成一条指令,表达式为"假"转到某地址(待回填), 否则顺序执行}
if sym = dosym then getsym else error(18);{如果当前记号是"do",则取下一记号, 否则出错}
statement(fsys); {处理"do"后面的语句}
gen(jmp, 0, cx1); {生成无条件转移指令, 转移到"while"后的条件表达式的代码的第一条指令处}
code[cx2].a := cx {把下一指令地址回填到前面生成的jpc指令的地址栏}
end
else if sym = readsym {处理read关键字} then
begin
getsym; {获取下一个sym类型}
if sym = lparen {read的后面应该接左括号}
then begin
repeat {循环开始}
getsym; {获取下一个sym类型}
if sym = ident {如果第一个sym标识符}
then begin
i := position(id); {记录当前符号在符号表中的位置}
if i = 0 {如果i为0,说明符号表中没有找到id对应的符号}
then error(11) {报11号错误}
else if table[i].kind <> variable {如果找到了,但该符号的类型不是变量}
then begin
error(12); {报12号错误,不能像常量和过程赋值}
i := 0 {将i置零}
end
else with table[i] do {如果是变量类型}
gen(red,lev-level,adr) {生成一条red指令,读取数据}
end
else error(4); {如果左括号后面跟的不是标识符,报4号错误}
getsym; {获取下一个sym类型}
until sym <> comma {直到符号不是逗号,循环结束}
end
else error(40); {如果read后面跟的不是左括号,报40号错误}
if sym <> rparen {如果上述内容之后接的不是右括号}
then error(22); {报22号错误}
getsym {获取下一个sym类型}
end
else if sym = writesym {处理write关键字} then
begin
getsym; {获取下一个sym类型}
if sym = lparen {默认write右边应该加一个左括号}
then begin
repeat {循环开始}
getsym; {获取下一个sym类型}
expression([rparen,comma]+fsys); {分析括号中的表达式}
gen(wrt,0,0); {生成一个wrt,用来输出内容}
until sym <> comma; {知道读取到的sym不是逗号}
if sym <> rparen {如果内容结束没有右括号}
then error(22); {报22号错误}
getsym {获取下一个sym类型}
end
else error(40) {如果write后面没有跟左括号}
end;
test(fsys, [ ], 19) {测试下一记号是否正常, 否则出错, 跳过一些记号}
end {statement};
begin {block}
dx := 3; {本过程数据空间栈顶指针}
tx0 := tx; {标识符表的长度(当前指针)}
table[tx].adr := cx; {本过程名的地址, 即下一条指令的序号}
gen(jmp, 0, 0); {生成一条转移指令}
if lev > levmax then error(32); {如果当前过程层号>最大层数, 则出错}
repeat
if sym = constsym then {处理常数说明语句}
begin
getsym;
repeat
constdeclaration; {处理一个常数说明}
while sym = comma do {如果当前记号是逗号}
begin
getsym;
constdeclaration
end; {处理下一个常数说明}
if sym = semicolon then getsym else error(5) {如果当前记号是分号,则常数说明已处理完, 否则出错}
until sym <> ident {跳过一些记号, 直到当前记号不是标识符(出错时才用到)}
end;
if sym = varsym then {当前记号是变量说明语句开始符号}
begin
getsym;
repeat
vardeclaration; {处理一个变量说明}
while sym = comma do {如果当前记号是逗号}
begin
getsym;
vardeclaration
end; {处理下一个变量说明}
if sym = semicolon then getsym else error(5){如果当前记号是分号,则变量说明已处理完, 否则出错}
until sym <> ident; {跳过一些记号, 直到当前记号不是标识符(出错时才用到)}
end;
while sym = procsym do {处理过程说明}
begin
getsym;
if sym = ident then {如果当前记号是过程名}
begin
enter(prosedure);
getsym
end {把过程名填入符号表}
else error(4); {否则, 缺少过程名出错}
if sym = semicolon then
getsym
else error(5);{当前记号是分号, 则取下一记号,否则,过程名后漏掉分号出错}
block(lev+1, tx, [semicolon]+fsys); {处理过程体}
{lev+1: 过程嵌套层数加1; tx: 符号表当前栈顶指针,也是新过程符号表起始位置; [semicolon]+fsys: 过程体开始和末尾符号集}
if sym = semicolon then {如果当前记号是分号}
begin
getsym; {取下一记号}
test(statbegsys+[ident, procsym], fsys, 6)
{测试当前记号是否语句开始符号或过程说明开始符号,否则报告错误6, 并跳过一些记号}
end
else error(5) {如果当前记号不是分号,则出错}
end; {while}
test(statbegsys+[ident], declbegsys, 7) {检测当前记号是否语句开始符号, 否则出错, 并跳过一些记号}
until not ( sym in declbegsys );{回到说明语句的处理(出错时才用),直到当前记号不是说明语句的开始符号}
code[table[tx0].adr].a := cx;
{table[tx0].adr是本过程名的第1条代码(jmp, 0, 0)的地址,本语句即是将下一代码(本过程语句的第
1条代码)的地址回填到该jmp指令中,得(jmp, 0, cx)}
with table[tx0] do {本过程名的第1条代码的地址改为下一指令地址cx}
begin
adr := cx; {代码开始地址}
end;
cx0 := cx; {cx0记录起始代码地址}
gen(int, 0, dx); {生成一条指令, 在栈顶为本过程留出数据空间}
statement([semicolon, endsym]+fsys); {处理一个语句}
gen(opr, 0, 0); {生成返回指令}
test(fsys, [ ], 8); {测试过程体语句后的符号是否正常,否则出错}
listcode; {打印本过程的中间代码序列}
end {block};
procedure interpret; {解释执行程序}
const stacksize = 500; {运行时数据空间(栈)的上界}
var
p, b, t : integer; {程序地址寄存器, 基地址寄存器,栈顶地址寄存器}
i : instruction; {指令寄存器}
s : array [1..stacksize] of integer; {数据存储栈}
function base(l : integer) : integer; {计算基地址的函数}
var b1 : integer; {声明计数变量}
begin
b1 := b; {顺静态链求层差为l的外层的基地址}
while l > 0 do
begin
b1 := s[b1];
l := l-1
end;
base := b1
end {base};
begin
writeln(file_out,'START PL/0');
t := 0; {栈顶地址寄存器}
b := 1; {基地址寄存器}
p := 0; {程序地址寄存器}
s[1] := 0; s[2] := 0; s[3] := 0; {最外层主程序数据空间栈最下面预留三个单元}
{每个过程运行时的数据空间的前三个单元是:SL, DL, RA;
SL: 指向本过程静态直接外层过程的SL单元;
DL: 指向调用本过程的过程的最新数据空间的第一个单元;
RA: 返回地址 }
repeat
i := code[p]; {i取程序地址寄存器p指示的当前指令}
p := p+1; {程序地址寄存器p加1,指向下一条指令}
with i do
case f of
lit : begin {当前指令是取常数指令(lit, 0, a)}
t := t+1;
s[t] := a
end; {栈顶指针加1, 把常数a取到栈顶}
opr : case a of {当前指令是运算指令(opr, 0, a)}
0 : begin {a=0时,是返回调用过程指令}
t := b-1; {恢复调用过程栈顶}
p := s[t+3]; {程序地址寄存器p取返回地址,即获得return address}
b := s[t+2]; {基地址寄存器b指向调用过程的基地址,即获得了return之后的基址}
end;
1 : s[t] := -s[t]; {一元负运算, 栈顶元素的值反号}
2 : begin {加法} {将栈顶和次栈顶中的数值求和放入新的栈顶}
t := t-1; s[t] := s[t] + s[t+1]
end;
3 : begin {减法}
t := t-1; s[t] := s[t]-s[t+1]
end;
4 : begin {乘法}
t := t-1; s[t] := s[t] * s[t+1]
end;
5 : begin {整数除法}
t := t-1; s[t] := s[t] div s[t+1]
end;
6 : s[t] := ord(odd(s[t])); {算s[t]是否奇数, 是则s[t]=1, 否则s[t]=0}
8 : begin t := t-1;
s[t] := ord(s[t] = s[t+1])
end; {判两个表达式的值是否相等,是则s[t]=1, 否则s[t]=0}
9: begin t := t-1;
s[t] := ord(s[t] <> s[t+1])
end; {判两个表达式的值是否不等,是则s[t]=1, 否则s[t]=0}
10 : begin t := t-1;
s[t] := ord(s[t] < s[t+1])
end; {判前一表达式是否小于后一表达式,是则s[t]=1, 否则s[t]=0}
11: begin t := t-1;
s[t] := ord(s[t] >= s[t+1])
end; {判前一表达式是否大于或等于后一表达式,是则s[t]=1, 否则s[t]=0}
12 : begin t := t-1;
s[t] := ord(s[t] > s[t+1])
end; {判前一表达式是否大于后一表达式,是则s[t]=1, 否则s[t]=0}
13 : begin t := t-1;
s[t] := ord(s[t] <= s[t+1])
end; {判前一表达式是否小于或等于后一表达式,是则s[t]=1, 否则s[t]=0}
end;
lod : begin {当前指令是取变量指令(lod, l, a)}
t := t + 1;
s[t] := s[base(l) + a]
{栈顶指针加1, 根据静态链SL,将层差为l,相对地址为a的变量值取到栈顶}
end;
sto : begin {当前指令是保存变量值(sto, l, a)指令}
s[base(l) + a] := s[t];
writeln(file_out,s[t]);
{根据静态链SL,将栈顶的值存入层差为l,相对地址为a的变量中}
t := t-1 {栈顶指针减1}
end;
cal : begin {当前指令是(cal, l, a)}
{为被调用过程数据空间建立连接数据}
s[t+1] := base(l); {根据层差l找到本过程的静态直接外层过程的数据空间的SL单元,将其地址存入本过程新的数据空间的SL单元}
s[t+2] := b; {调用过程的数据空间的起始地址存入本过程DL单元}
s[t+3] := p; {调用过程cal指令的下一条的地址存入本过程RA单元}
b := t+1; {b指向被调用过程新的数据空间起始地址}
p := a {指令地址寄存储器指向被调用过程的地址a}
end;
int : t := t + a; {若当前指令是(int, 0, a), 则数据空间栈顶留出a大小的空间}
jmp : p := a; {若当前指令是(jmp, 0, a), 则程序转到地址a执行}
jpc : begin {当前指令是(jpc, 0, a)}
if s[t] = 0 then p := a;{如果当前运算结果为"假"(0), 程序转到地址a执行, 否则顺序执行}
t := t-1 {数据栈顶指针减1}
end;
red : begin {对red指令}
writeln('请输入: '); {输出提示信息到标准输出即屏幕}
readln(s[base(l)+a]); {读一行数据,读入到相差l层,层内偏移为a的数据栈中的数据的信息}
end;
wrt : begin {对wrt指令}
writeln(file_out,s[t]); {输出栈顶的信息}
t := t+1 {栈顶上移}
end
end {with, case}
until p = 0; {程序一直执行到p取最外层主程序的返回地址0时为止}
writeln(file_out,'END PL/0');
end {interpret};
begin {主程序}
assign(file_in,paramstr(1));
assign(file_out,paramstr(2)); {将文件名字符串变量赋值给文件变量}
reset(file_in);
rewrite(file_out); {打开文件}
for ch := 'A' to ';' do ssym[ch] := nul; {ASCII码的顺序}
word[1] := 'begin '; word[2] := 'call ';
word[3] := 'const '; word[4] := 'do ';
word[5] := 'end '; word[6] := 'if ';
word[7] := 'odd '; word[8] := 'procedure ';
word[9] := 'read '; word[10] := 'then ';
word[11] := 'var '; word[12] := 'while ';
word[13] := 'write '; {保留字表改为小写字母,所有字符都预留的相同的长度}
wsym[1] := beginsym; wsym[2] := callsym;
wsym[3] := constsym; wsym[4] := dosym;
wsym[5] := endsym; wsym[6] := ifsym;
wsym[7] := oddsym; wsym[8] := procsym;
wsym[9] := readsym; wsym[10] := thensym;
wsym[11] := varsym; wsym[12] := whilesym;
wsym[13] := writesym; {保留字对应的记号,添加read和write的保留字记号}
ssym['+'] := plus; ssym['-'] := minus;
ssym['*'] := times; ssym['/'] := slash;
ssym['('] := lparen; ssym[')'] := rparen;
ssym['='] := eql; ssym[','] := comma;
ssym['.'] := period; ssym['<'] := lss;
ssym['>'] := gtr; ssym[';'] := semicolon; {算符和标点符号的记号}
mnemonic[lit] := 'LIT '; mnemonic[opr] := 'OPR ';
mnemonic[lod] := 'LOD '; mnemonic[sto] := 'STO ';
mnemonic[cal] := 'CAL '; mnemonic[int] := 'INT ';
mnemonic[jmp] := 'JMP '; mnemonic[jpc] := 'JPC ';
mnemonic[red] := 'RED '; mnemonic[wrt] := 'WRT ';{中间代码指令的字符串,长度为5}
declbegsys := [constsym, varsym, procsym]; {说明语句的开始符号}
statbegsys := [beginsym, callsym, ifsym, whilesym , writesym, readsym]; {语句的开始符号}
facbegsys := [ident, number, lparen]; {因子的开始符号}
err := 0; {发现错误的个数}
cc := 0; {当前行中输入字符的指针}
cx := 0; {代码数组的当前指针}
ll := 0; {输入当前行的长度}
ch := ' '; {当前输入的字符}
kk := al; {标识符的长度}
getsym; {取下一个记号}
block(0, 0, [period]+declbegsys+statbegsys); {处理程序体}
if sym <> period then error(9); {如果当前记号不是句号, 则出错}
if err = 0 then interpret {如果编译无错误, 则解释执行中间代码}
else write('ERRORS IN PL/0 PROGRAM');
close(file_in);
close(file_out); {关闭文件}
end.
|
unit RarUnit;
interface
uses Windows, Classes, BTMemoryModule;
const
ERAR_END_ARCHIVE = 10;
ERAR_NO_MEMORY = 11;
ERAR_BAD_DATA = 12;
ERAR_BAD_ARCHIVE = 13;
ERAR_UNKNOWN_FORMAT = 14;
ERAR_EOPEN = 15;
ERAR_ECREATE = 16;
ERAR_ECLOSE = 17;
ERAR_EREAD = 18;
ERAR_EWRITE = 19;
ERAR_SMALL_BUF = 20;
RAR_OM_LIST = 0;
RAR_OM_EXTRACT = 1;
RAR_SKIP = 0;
RAR_TEST = 1;
RAR_EXTRACT = 2;
RAR_VOL_ASK = 0;
RAR_VOL_NOTIFY = 1;
type
RARHeaderData=record
ArcName:array[1..260] of char;
FileName:array[1..260]of char;
Flags,
PackSize,
UnpSize,
HostOS,
FileCRC,
FileTime,
UnpVer,
Method,
FileAttr: cardinal;
CmtBuf:PChar;
CmtBufSize,
CmtSize,
CmtState: cardinal;
end;
RAROpenArchiveData=Record
ArcName:PChar;
OpenMode, OpenResult:cardinal;
CmtBuf:PChar;
CmtBufSize, CmtSize, CmtState:cardinal;
end;
type
TChangeVolProc=Function(ArcName:pchar; Mode:integer):integer; cdecl;
TProcessDataProc=Function(Addr:PChar; Size:integer):integer; cdecl;
TRAROpenArchive=function(var ArchiveData:RAROpenArchiveData):THandle;stdcall;
TRARCloseArchive=function(hArcData:THandle):integer;stdcall;
TRARReadHeader=function(hArcData:THandle; var HeaderData:RARHeaderData):integer;stdcall;
TRARProcessFile=function(hArcData:THandle; Operation:Integer; DestPath, DestName:PChar):integer;stdcall;
TRARSetChangeVolProc=procedure(hArcData:THandle; CVP:TChangeVolProc);stdcall;
TRARSetProcessDataProc=procedure(hArcData:THandle; PDP:TProcessDataProc);stdcall;
TRARSetPassword=procedure(hArcData:THandle; Password:PChar);stdcall;
var mp_DllData: Pointer;
m_DllDataSize: Integer;
mp_MemoryModule: PBTMemoryModule;
//Procedure's
RAROpenArchive:TRAROpenArchive;
RARCloseArchive:TRARCloseArchive;
RARReadHeader:TRARReadHeader;
RARProcessFile:TRARProcessFile;
RARSetChangeVolProc:TRARSetChangeVolProc;
RARSetProcessDataProc:TRARSetProcessDataProc;
RARSetPassword:TRARSetPassword;
procedure LoadDll(hInst:Cardinal);
procedure FreeDll;
implementation
{$R Rar.res}
procedure LoadDll(hInst:Cardinal);
Var ResStream:TResourceStream;
Begin
ResStream:=TResourceStream.Create(hInst,'UNRAR','DLL');
ResStream.Position := 0;
m_DllDataSize := ResStream.Size;
mp_DllData := GetMemory(m_DllDataSize);
ResStream.Read(mp_DllData^, m_DllDataSize);
ResStream.Free;
mp_MemoryModule := BTMemoryLoadLibary(mp_DllData, m_DllDataSize);
try
@RAROpenArchive:=BTMemoryGetProcAddress(mp_MemoryModule,'RAROpenArchive');
@RARCloseArchive:=BTMemoryGetProcAddress(mp_MemoryModule,'RARCloseArchive');
@RARReadHeader:=BTMemoryGetProcAddress(mp_MemoryModule,'RARReadHeader');
@RARProcessFile:=BTMemoryGetProcAddress(mp_MemoryModule,'RARProcessFile');
@RARSetChangeVolProc:=BTMemoryGetProcAddress(mp_MemoryModule,'RARSetChangeVolProc');
@RARSetProcessDataProc:=BTMemoryGetProcAddress(mp_MemoryModule,'RARSetProcessDataProc');
@RARSetPassword:=BTMemoryGetProcAddress(mp_MemoryModule,'RARSetPassword');
finally
end;
End;
procedure FreeDll;
begin
if mp_MemoryModule <> nil then
BTMemoryFreeLibrary(mp_MemoryModule);
FreeMemory(mp_DllData);
end;
end.
|
// Ported to Delphi from C++ by @davidberneda
// david@steema.com
unit MyoDLL;
{$MINENUMSIZE 4}
interface
const Myo_DLL =
{$IFDEF MACOS}
{$IFDEF IOS}
// The MyoKit library file should be copied to ie:
// $(BDSPLATFORMSDKSDIR)\iPhoneOS7.1.sdk
'/MyoKit'
{$ELSE}
'myo.86'
{$ENDIF}
{$ELSE}
{$IFDEF CPUX86}
'myo32.dll'
{$ELSE}
{$IFDEF CPUX64}
'myo64.dll'
{$ELSE}
'myo32.dll' // Delphi 7
{$ENDIF}
{$ENDIF}
{$ENDIF}
;
type
float=Single;
int8_t=Byte;
libmyo_hub_t = Pointer;
/// \defgroup errors Error Handling
/// @{
/// Function result codes.
/// All libmyo functions that can fail return a value of this type.
type
libmyo_result_t = (
libmyo_success,
libmyo_error,
libmyo_error_invalid_argument,
libmyo_error_runtime
);
/// Opaque handle to detailed error information.
type
libmyo_error_details_t = Pointer;
/// Return a null-terminated string with a detailed error message.
function libmyo_error_cstring(details:libmyo_error_details_t):{$IFDEF MACOS}MarshaledAString{$ELSE}PAnsiChar{$ENDIF}; cdecl;
external Myo_DLL {$IFDEF MACOS}name '_libmyo_error_cstring'{$ENDIF};
/// Returns the kind of error that occurred.
function libmyo_error_kind(details:libmyo_error_details_t):libmyo_result_t; cdecl;
external Myo_DLL {$IFDEF MACOS}name '_libmyo_error_kind'{$ENDIF};
/// Free the resources allocated by an error object.
procedure libmyo_free_error_details(details:libmyo_error_details_t); cdecl;
external Myo_DLL {$IFDEF MACOS}name '_libmyo_free_error_details'{$ENDIF};
/// @}
/// @defgroup libmyo_hub Hub instance
/// @{
/// Initialize a connection to the hub.
/// \a application_identifier must follow a reverse domain name format (ex. com.domainname.appname). Application
/// identifiers can be formed from the set of alphanumeric ASCII characters (a-z, A-Z, 0-9). The hyphen (-) and
/// underscore (_) characters are permitted if they are not adjacent to a period (.) character (i.e. not at the start or
/// end of each segment), but are not permitted in the top-level domain. Application identifiers must have three or more
/// segments. For example, if a company's domain is example.com and the application is named hello-world, one could use
/// "com.example.hello-world" as a valid application identifier. \a application_identifier can be NULL or empty.
/// @returns libmyo_success if the connection is successfully established, otherwise:
/// - libmyo_error_runtime if a connection could not be established
/// - libmyo_error_invalid_argument if \a out_hub is NULL
/// - libmyo_error_invalid_argument if \a application_identifier is longer than 255 characters
/// - libmyo_error_invalid_argument if \a application_identifier is not in the proper reverse domain name format
function libmyo_init_hub(out out_hub:libmyo_hub_t;
const application_identifier:{$IFDEF MACOS}MarshaledAString{$ELSE}PAnsiChar{$ENDIF};
var out_error:libmyo_error_details_t):libmyo_result_t; cdecl;
external Myo_DLL {$IFDEF MACOS}name '_libmyo_init_hub'{$ENDIF};
/// Free the resources allocated to a hub.
/// @returns libmyo_success if shutdown is successful, otherwise:
/// - libmyo_error_invalid_argument if \a hub is NULL
/// - libmyo_error if \a hub is not a valid hub
function libmyo_shutdown_hub(hub:libmyo_hub_t; var out_error:libmyo_error_details_t):libmyo_result_t; cdecl;
external Myo_DLL {$IFDEF MACOS}name '_libmyo_shutdown_hub'{$ENDIF};
// Locking policies.
type
libmyo_locking_policy_t = (
libmyo_locking_policy_none, ///< Pose events are always sent.
libmyo_locking_policy_standard ///< Pose events are not sent while a Myo is locked.
);
/// Set the locking policy for Myos connected to the hub.
/// @returns libmyo_success if the locking policy is successfully set, otherwise
/// - libmyo_error_invalid_argument if \a hub is NULL
/// - libmyo_error if \a hub is not a valid hub
function libmyo_set_locking_policy(hub:libmyo_hub_t; locking_policy:libmyo_locking_policy_t;
var out_error:libmyo_error_details_t):libmyo_result_t; cdecl;
external Myo_DLL {$IFDEF MACOS}name '_libmyo_set_locking_policy'{$ENDIF}
/// @}
/// @defgroup libmyo_myo Myo instances
/// @{
/// Opaque type corresponding to a known Myo device.
type
libmyo_myo_t = Pointer;
/// Types of vibration
type
libmyo_vibration_type_t = (
libmyo_vibration_short,
libmyo_vibration_medium,
libmyo_vibration_long
);
/// Vibrate the given myo.
/// Can be called when a Myo is paired.
/// @returns libmyo_success if the Myo successfully vibrated, otherwise
/// - libmyo_error_invalid_argument if \a myo is NULL
function libmyo_vibrate(myo:libmyo_myo_t; vibration:libmyo_vibration_type_t; var out_error:libmyo_error_details_t):libmyo_result_t; cdecl;
external Myo_DLL {$IFDEF MACOS}name '_libmyo_vibrate'{$ENDIF};
/// Request the RSSI for a given myo.
/// Can be called when a Myo is paired. A libmyo_event_rssi event will likely be generated with the value of the RSSI.
/// @returns libmyo_success if the Myo successfully got the RSSI, otherwise
/// - libmyo_error_invalid_argument if \a myo is NULL
function libmyo_request_rssi(myo:libmyo_myo_t; var out_error:libmyo_error_details_t):libmyo_result_t; cdecl;
external Myo_DLL {$IFDEF MACOS}name '_libmyo_request_rssi'{$ENDIF};
/// @}
/// @defgroup libmyo_poses Pose recognition.
/// @{
/// Supported poses.
type
libmyo_pose_t = (
libmyo_pose_rest = 0, ///< Rest pose.
libmyo_pose_fist = 1, ///< User is making a fist.
libmyo_pose_wave_in = 2, ///< User has an open palm rotated towards the posterior of their wrist.
libmyo_pose_wave_out = 3, ///< User has an open palm rotated towards the anterior of their wrist.
libmyo_pose_fingers_spread = 4, ///< User has an open palm with their fingers spread away from each other.
libmyo_pose_double_tap = 5, ///< User is touching the tip of their thumb to the tip of their pinky.
libmyo_num_poses, ///< Number of poses supported; not a valid pose.
libmyo_pose_unknown = $ffff ///< Unknown pose.
);
/// @}
/// @defgroup libmyo_locking Myo locking mechanism
/// Valid unlock types.
type
libmyo_unlock_type_t = (
libmyo_unlock_timed = 0, ///< Unlock for a fixed period of time.
libmyo_unlock_hold = 1 ///< Unlock until explicitly told to re-lock.
);
/// Unlock the given Myo.
/// Can be called when a Myo is paired. A libmyo_event_unlocked event will be generated if the Myo was locked.
/// @returns libmyo_success if the Myo was successfully unlocked, otherwise
/// - libmyo_error_invalid_argument if \a myo is NULL
function libmyo_myo_unlock(myo:libmyo_myo_t; _type:libmyo_unlock_type_t; var out_error:libmyo_error_details_t):libmyo_result_t; cdecl;
external Myo_DLL {$IFDEF MACOS}name '_libmyo_myo_unlock'{$ENDIF};
/// Lock the given Myo immediately.
/// Can be called when a Myo is paired. A libmyo_event_locked event will be generated if the Myo was unlocked.
/// @returns libmyo_success if the Myo was successfully locked, otherwise
/// - libmyo_error_invalid_argument if \a myo is NULL
function libmyo_myo_lock(myo:libmyo_myo_t; var out_error:libmyo_error_details_t):libmyo_result_t; cdecl;
external Myo_DLL {$IFDEF MACOS}name '_libmyo_myo_lock'{$ENDIF};
/// User action types.
type
libmyo_user_action_type_t = (
libmyo_user_action_single = 0 ///< User did a single, discrete action, such as pausing a video.
);
/// Notify the given Myo that a user action was recognized.
/// Can be called when a Myo is paired. Will cause Myo to vibrate.
/// @returns libmyo_success if the Myo was successfully notified, otherwise
/// - libmyo_error_invalid_argument if \a myo is NULL
function libmyo_myo_notify_user_action(myo:libmyo_myo_t; _type:libmyo_user_action_type_t;
var out_error:libmyo_error_details_t):libmyo_result_t; cdecl;
external Myo_DLL {$IFDEF MACOS}name '_libmyo_myo_notify_user_action'{$ENDIF};
/// @}
/// @defgroup libmyo_events Event Handling
/// @{
/// Types of events.
type
libmyo_event_type_t = (
libmyo_event_paired, ///< Successfully paired with a Myo.
libmyo_event_unpaired, ///< Successfully unpaired from a Myo.
libmyo_event_connected, ///< A Myo has successfully connected.
libmyo_event_disconnected, ///< A Myo has been disconnected.
libmyo_event_arm_synced, ///< A Myo has recognized that the sync gesture has been successfully performed.
libmyo_event_arm_unsynced, ///< A Myo has been moved or removed from the arm.
libmyo_event_orientation, ///< Orientation data has been received.
libmyo_event_pose, ///< A change in pose has been detected. @see libmyo_pose_t.
libmyo_event_rssi, ///< An RSSI value has been received.
libmyo_event_unlocked, ///< A Myo has become unlocked.
libmyo_event_locked ///< A Myo has become locked.
);
/// Information about an event.
type
libmyo_event_t = Pointer;
/// Retrieve the type of an event.
function libmyo_event_get_type(event:libmyo_event_t):libmyo_event_type_t; cdecl;
external Myo_DLL {$IFDEF MACOS}name '_libmyo_event_get_type'{$ENDIF};
/// Retrieve the timestamp of an event.
/// @see libmyo_now() for details on timestamps.
function libmyo_event_get_timestamp(event:libmyo_event_t):UInt64; cdecl;
external Myo_DLL {$IFDEF MACOS}name '_libmyo_event_get_timestamp'{$ENDIF};
/// Retrieve the Myo associated with an event.
function libmyo_event_get_myo(event:libmyo_event_t):libmyo_myo_t; cdecl;
external Myo_DLL {$IFDEF MACOS}name '_libmyo_event_get_myo'{$ENDIF};
/// Components of version.
type
libmyo_version_component_t = (
libmyo_version_major, ///< Major version.
libmyo_version_minor, ///< Minor version.
libmyo_version_patch, ///< Patch version.
libmyo_version_hardware_rev ///< Hardware revision.
);
/// Hardware revisions.
type
libmyo_hardware_rev_t = (
libmyo_hardware_rev_c = 1, ///< Alpha units
libmyo_hardware_rev_d = 2 ///< Consumer units
);
{$IFNDEF D9}
type
UInt32=Cardinal;
{$ENDIF}
/// Retrieve the Myo armband's firmware version from this event.
/// Valid for libmyo_event_paired and libmyo_event_connected events.
function libmyo_event_get_firmware_version(event:libmyo_event_t; version:libmyo_version_component_t):UInt32; cdecl;
external Myo_DLL {$IFDEF MACOS}name '_libmyo_event_get_firmware_version'{$ENDIF};
/// Enumeration identifying a right arm or left arm. @see libmyo_event_get_arm().
type
libmyo_arm_t = (
libmyo_arm_right, ///< Myo is on the right arm.
libmyo_arm_left, ///< Myo is on the left arm.
libmyo_arm_unknown ///< Unknown arm.
);
/// Retrieve the arm associated with an event.
/// Valid for libmyo_event_arm_synced events only.
function libmyo_event_get_arm(event:libmyo_event_t):libmyo_arm_t; cdecl;
external Myo_DLL {$IFDEF MACOS}name '_libmyo_event_get_arm'{$ENDIF};
/// Possible directions for Myo's +x axis relative to a user's arm.
type
libmyo_x_direction_t = (
libmyo_x_direction_toward_wrist, ///< Myo's +x axis is pointing toward the user's wrist.
libmyo_x_direction_toward_elbow, ///< Myo's +x axis is pointing toward the user's elbow.
libmyo_x_direction_unknown ///< Unknown +x axis direction.
);
/// Retrieve the x-direction associated with an event.
/// The x-direction specifies which way Myo's +x axis is pointing relative to the user's arm.
/// Valid for libmyo_event_arm_synced events only.
function libmyo_event_get_x_direction(event:libmyo_event_t):libmyo_x_direction_t; cdecl;
external Myo_DLL {$IFDEF MACOS}name '_libmyo_event_get_x_direction'{$ENDIF};
/// Index into orientation data, which is provided as a quaternion.
/// Orientation data is returned as a unit quaternion of floats, represented as `w + x * i + y * j + z * k`.
type
libmyo_orientation_index = (
libmyo_orientation_x = 0, ///< First component of the quaternion's vector part
libmyo_orientation_y = 1, ///< Second component of the quaternion's vector part
libmyo_orientation_z = 2, ///< Third component of the quaternion's vector part
libmyo_orientation_w = 3 ///< Scalar component of the quaternion.
);
/// Retrieve orientation data associated with an event.
/// Valid for libmyo_event_orientation events only.
/// @see libmyo_orientation_index
function libmyo_event_get_orientation(event:libmyo_event_t; index:libmyo_orientation_index):float; cdecl;
external Myo_DLL {$IFDEF MACOS}name '_libmyo_event_get_orientation'{$ENDIF};
/// Retrieve raw accelerometer data associated with an event in units of g.
/// Valid for libmyo_event_orientation events only.
/// Requires `index < 3`.
function libmyo_event_get_accelerometer(event:libmyo_event_t; index:UInt32):float; cdecl;
external Myo_DLL {$IFDEF MACOS}name '_libmyo_event_get_accelerometer'{$ENDIF};
/// Retrieve raw gyroscope data associated with an event in units of deg/s.
/// Valid for libmyo_event_orientation events only.
/// Requires `index < 3`.
function libmyo_event_get_gyroscope(event:libmyo_event_t; index:UInt32):float; cdecl;
external Myo_DLL {$IFDEF MACOS}name '_libmyo_event_get_gyroscope'{$ENDIF};
/// Retrieve the pose associated with an event.
/// Valid for libmyo_event_pose events only.
function libmyo_event_get_pose(event:libmyo_event_t):libmyo_pose_t; cdecl;
external Myo_DLL {$IFDEF MACOS}name '_libmyo_event_get_pose'{$ENDIF};
/// Retreive the RSSI associated with an event.
/// Valid for libmyo_event_rssi events only.
function libmyo_event_get_rssi(event:libmyo_event_t):int8_t; cdecl;
external Myo_DLL {$IFDEF MACOS}name '_libmyo_event_get_rssi'{$ENDIF};
/// Return type for event handlers.
type
libmyo_handler_result_t = (
libmyo_handler_continue, ///< Continue processing events
libmyo_handler_stop ///< Stop processing events
);
/// Callback function type to handle events as they occur from libmyo_run().
type
libmyo_handler_t = function(user_data:Pointer; event:libmyo_event_t):libmyo_handler_result_t; cdecl;
plibmyo_handler_t = ^libmyo_handler_t;
/// Process events and call the provided callback as they occur.
/// Runs for up to approximately \a duration_ms milliseconds or until a called handler returns libmyo_handler_stop.
/// @returns libmyo_success after a successful run, otherwise
/// - libmyo_error_invalid_argument if \a hub is NULL
/// - libmyo_error_invalid_argument if \a handler is NULL
function libmyo_run(hub:libmyo_hub_t; duration_ms:UInt32; handler:plibmyo_handler_t;
user_data:Pointer;
var out_error:libmyo_error_details_t):libmyo_result_t; cdecl;
external Myo_DLL {$IFDEF MACOS}name '_libmyo_run'{$ENDIF};
implementation
end.
|
unit dbEnumTest;
interface
uses TestFramework, ZConnection, ZDataset;
type
TdbEnumTest = class (TTestCase)
private
ZConnection: TZConnection;
ZQuery: TZQuery;
protected
// подготавливаем данные для тестирования
procedure SetUp; override;
// возвращаем данные для тестирования
procedure TearDown; override;
published
procedure InsertObjectEnum;
end;
var
EnumPath: string = '..\DATABASE\Boat\METADATA\Enum\';
implementation
{ TdbEnumTest }
uses zLibUtil, UtilConst;
procedure TdbEnumTest.InsertObjectEnum;
begin
ExecFile(EnumPath + 'CreateObjectEnumFunction.sql', ZQuery);
ExecFile(EnumPath + 'InsertObjectEnum.sql', ZQuery);
ExecFile(EnumPath + 'InsertObjectEnum_01.sql', ZQuery);
end;
procedure TdbEnumTest.SetUp;
begin
inherited;
ZConnection := TConnectionFactory.GetConnection;
ZConnection.Connected := true;
ZQuery := TZQuery.Create(nil);
ZQuery.Connection := ZConnection;
end;
procedure TdbEnumTest.TearDown;
begin
inherited;
ZConnection.Free;
ZQuery.Free;
end;
initialization
TestFramework.RegisterTest('Перечисления и служебные', TdbEnumTest.Suite);
end.
|
unit DIOTA.Utils.TrytesConverter;
interface
type
//This class allows to convert between ASCII and tryte encoded strings.
TTrytesConverter = class
public
{
* Conversion of ASCII encoded bytes to trytes.
* Input is a string (can be stringified JSON object), return value is Trytes
*
* How the conversion works:
* 2 Trytes === 1 Byte
* There are a total of 27 different tryte values: 9ABCDEFGHIJKLMNOPQRSTUVWXYZ
*
* 1. We get the decimal value of an individual ASCII character
* 2. From the decimal value, we then derive the two tryte values by basically calculating the tryte equivalent (e.g. 100 === 19 + 3 * 27)
* a. The first tryte value is the decimal value modulo 27 (27 trytes)
* b. The second value is the remainder (decimal value - first value), divided by 27
* 3. The two values returned from Step 2. are then input as indices into the available values list ('9ABCDEFGHIJKLMNOPQRSTUVWXYZ') to get the correct tryte value
*
*
* EXAMPLE
*
* Lets say we want to convert the ASCII character "Z".
* 1. 'Z' has a decimal value of 90.
* 2. 90 can be represented as 9 + 3 * 27. To make it simpler:
* a. First value: 90 modulo 27 is 9. This is now our first value
* b. Second value: (90 - 9) / 27 is 3. This is our second value.
* 3. Our two values are now 9 and 3. To get the tryte value now we simply insert it as indices into '9ABCDEFGHIJKLMNOPQRSTUVWXYZ'
* a. The first tryte value is '9ABCDEFGHIJKLMNOPQRSTUVWXYZ'[9] === "I"
* b. The second tryte value is '9ABCDEFGHIJKLMNOPQRSTUVWXYZ'[3] === "C"
* Our tryte pair is "IC"
*
* @param inputString The input String.
* @return The ASCII char "Z" is represented as "IC" in trytes.
}
class function AsciiToTrytes(AInputString: String): String;
{
* Converts Trytes of even length to an ASCII string.
* Reverse operation from the asciiToTrytes
* 2 Trytes == 1 Byte
* @param inputTrytes the trytes we want to convert
* @return an ASCII string or null when the inputTrytes are uneven
* @throws ArgumentException When the trytes in the string are an odd number
}
class function TrytesToAscii(AInputTrytes: String): String;
end;
implementation
uses
System.SysUtils,
DIOTA.Utils.Constants;
{ TTrytesConverter }
class function TTrytesConverter.AsciiToTrytes(AInputString: String): String;
var
i: Integer;
AChar: Char;
AFirstValue: Integer;
ASecondValue: Integer;
begin
Result := '';
for i:= 1 to Length(AInputString) do
begin
AChar := AInputString[i];
// If not recognizable ASCII character, replace with space
if Ord(AChar) > 255 then
AChar := #32;
AFirstValue := Ord(AChar) mod 27;
ASecondValue := (Ord(AChar) - AFirstValue) div 27;
Result := Result + TRYTE_ALPHABET[AFirstValue + 1] + TRYTE_ALPHABET[ASecondValue + 1];
end;
end;
class function TTrytesConverter.TrytesToAscii(AInputTrytes: String): String;
var
i: Integer;
AFirstValue: Integer;
ASecondValue: Integer;
begin
Result := '';
// If input length is odd, return empty string
if (Length(AInputTrytes) mod 2) = 0 then
raise Exception.Create('Odd amount of trytes supplied')
else
begin
i := 1;
while (i < Length(AInputTrytes)) do
begin
AFirstValue := Pos(AInputTrytes[i], TRYTE_ALPHABET) - 1;
ASecondValue := Pos(AInputTrytes[i + 1], TRYTE_ALPHABET) - 1;
Result := Result + Chr(AFirstValue + ASecondValue * 27);
Inc(i, 2);
end;
end;
end;
end.
|
{
Description: vPlot wave class.
Copyright (C) 2017-2019 Melchiorre Caruso <melchiorrecaruso@gmail.com>
This source is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation; either version 2 of the License, or (at your option)
any later version.
This code is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
details.
A copy of the GNU General Public License is available on the World Wide Web
at <http://www.gnu.org/copyleft/gpl.html>. You can also obtain it by writing
to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
MA 02111-1307, USA.
}
unit vpwave;
{$mode objfpc}
interface
uses
classes, sysutils, vpmath;
type
tdegres = 0..10;
tpolynome = packed record
coefs: array[tdegres] of vpfloat;
deg: tdegres;
end;
twavemesh = array[0..8] of tvppoint;
tspacewave = class
private
lax, lay: tpolynome;
lbx, lby: tpolynome;
lcx, lcy: tpolynome;
fenabled: boolean;
fscale: vpfloat;
public
constructor create(xmax, ymax, scale: vpfloat; const mesh: twavemesh);
destructor destroy; override;
function update(const p: tvppoint): tvppoint;
procedure debug;
published
property enabled: boolean read fenabled write fenabled;
end;
function polyeval(const apoly: tpolynome; x: vpfloat): vpfloat;
var
spacewave: tspacewave = nil;
implementation
uses
matrix;
// polynomial evaluation
function polyeval(const apoly: tpolynome; x: vpfloat): vpfloat;
var
i: tdegres;
begin
with apoly do
begin
result := 0;
for i := deg downto low(coefs) do
result := result * x + coefs[i];
end;
end;
// tspacewave
constructor tspacewave.create(xmax, ymax, scale: vpfloat; const mesh: twavemesh);
var
a, aa: tvector3_double;
b, bb: tvector3_double;
c, cc: tvector3_double;
dy: tvector3_double;
dx: tvector3_double;
y: tmatrix3_double;
x: tmatrix3_double;
begin
inherited create;
xmax := abs(xmax);
ymax := abs(ymax);
x.init(1, -xmax, sqr(-xmax), 1, 0, 0, 1, +xmax, sqr(+xmax));
y.init(1, +ymax, sqr(+ymax), 1, 0, 0, 1, -ymax, sqr(-ymax));
x := x.inverse(x.determinant);
y := y.inverse(y.determinant);
// calculate y-mirror
dy.init(mesh[0].y, mesh[1].y, mesh[2].y); a := x * dy;
dy.init(mesh[3].y, mesh[4].y, mesh[5].y); b := x * dy;
dy.init(mesh[6].y, mesh[7].y, mesh[8].y); c := x * dy;
dx.init(a.data[0], b.data[0], c.data[0]); cc := y * dx;
dx.init(a.data[1], b.data[1], c.data[1]); bb := y * dx;
dx.init(a.data[2], b.data[2], c.data[2]); aa := y * dx;
lay.deg :=2;
lay.coefs[2] := aa.data[2];
lay.coefs[1] := aa.data[1];
lay.coefs[0] := aa.data[0];
lby.deg :=2;
lby.coefs[2] := bb.data[2];
lby.coefs[1] := bb.data[1];
lby.coefs[0] := bb.data[0];
lcy.deg :=2;
lcy.coefs[2] := cc.data[2];
lcy.coefs[1] := cc.data[1];
lcy.coefs[0] := cc.data[0];
// calculate x-mirror
dx.init(mesh[0].x, mesh[3].x, mesh[6].x); a := y * dx;
dx.init(mesh[1].x, mesh[4].x, mesh[7].x); b := y * dx;
dx.init(mesh[2].x, mesh[5].x, mesh[8].x); c := y * dx;
dy.init(a.data[0], b.data[0], c.data[0]); cc := x * dy;
dy.init(a.data[1], b.data[1], c.data[1]); bb := x * dy;
dy.init(a.data[2], b.data[2], c.data[2]); aa := x * dy;
lax.deg :=2;
lax.coefs[2] := aa.data[2];
lax.coefs[1] := aa.data[1];
lax.coefs[0] := aa.data[0];
lbx.deg :=2;
lbx.coefs[2] := bb.data[2];
lbx.coefs[1] := bb.data[1];
lbx.coefs[0] := bb.data[0];
lcx.deg :=2;
lcx.coefs[2] := cc.data[2];
lcx.coefs[1] := cc.data[1];
lcx.coefs[0] := cc.data[0];
fscale := scale;
fenabled := false;
end;
destructor tspacewave.destroy;
begin
inherited destroy;
end;
function tspacewave.update(const p: tvppoint): tvppoint;
var
ly,
lx: tpolynome;
pp: tvppoint;
begin
if enabled then
begin
pp.x := p.x * fscale;
pp.y := p.y * fscale;
ly.deg :=2;
ly.coefs[2] := polyeval(lay, pp.y);
ly.coefs[1] := polyeval(lby, pp.y);
ly.coefs[0] := polyeval(lcy, pp.y);
lx.deg :=2;
lx.coefs[2] := polyeval(lax, pp.x);
lx.coefs[1] := polyeval(lbx, pp.x);
lx.coefs[0] := polyeval(lcx, pp.x);
result.x := pp.x + polyeval(lx, pp.y);
result.y := pp.y + polyeval(ly, pp.x);
end else
begin
result.x := p.x;
result.y := p.y;
end;
end;
procedure tspacewave.debug;
var
p0,p1: tvppoint;
procedure test_print;
begin
writeln(format(' WAVING::P.X = %12.5f P''.X = %12.5f', [p0.x, p1.x]));
writeln(format(' WAVING::P.Y = %12.5f P''.Y = %12.5f', [p0.y, p1.y]));
end;
begin
if enabledebug then
begin
p0.x := -594.5; p0.y := +420.5; p1 := update(p0); test_print;
p0.x := +0.000; p0.y := +420.5; p1 := update(p0); test_print;
p0.x := +594.5; p0.y := +420.5; p1 := update(p0); test_print;
p0.x := -594.5; p0.y := +0.000; p1 := update(p0); test_print;
p0.x := +0.000; p0.y := +0.000; p1 := update(p0); test_print;
p0.x := +594.5; p0.y := +0.000; p1 := update(p0); test_print;
p0.x := -594.5; p0.y := -420.5; p1 := update(p0); test_print;
p0.x := +0.000; p0.y := -420.5; p1 := update(p0); test_print;
p0.x := +594.5; p0.y := -420.5; p1 := update(p0); test_print;
end;
end;
end.
|
unit libkz;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, INIFiles;
Type
TMsg = Record
MsgStr : String[32]; // Arbitrary length up to 255 characters.
Data : ShortString;
end;
TKZObj=class(TObject)
var
UUID:TGuid;
INI:TINIFile;
_Name:ShortString;
constructor create;
constructor Load(GUID:UTF8String);
procedure info(Var i:TMsg); message 'Info';
procedure GetName(Var i:TMsg); message 'Name';
procedure DefaultHandlerStr(var message); override;
Procedure NormalMethod;
Function GetGUID:UTF8String;
destructor destroy;
end;
implementation
constructor TKZObj.create;
Var
FileName:UTF8String;
begin
CreateGUID(UUID);
FileName := GetAppConfigDir(false) + GUIDToString(UUID)+'.ini';
INI := TINIFile.Create(FileName, False);
end;
constructor TKZObj.Load(Guid:UTF8String);
Var
FileName:UTF8String;
begin
UUID := StringToGuid(Guid);
FileName := GetAppConfigDir(False) + GUIDToString(UUID)+'.ini';
INI := TINIFile.Create(FileName, False);
end;
Procedure TKZObj.GetName(Var i:TMsg);
begin
_Name := ini.ReadString('General', 'Name', 'The Basement');
Writeln(_Name);
end;
procedure TKZObj.info(Var i:TMsg);
begin
writeln('Information goes here.');
end;
procedure TKZObj.DefaultHandlerStr(var message);
begin
writeln('Unknown command');
end;
procedure TKZObj.NormalMethod;
begin
Writeln('This is a normal method call');
end;
Function TKZObj.GetGUID:UTF8String;
begin
Result := GUIDToString(uuid);
end;
destructor TKZObj.destroy;
begin
ini.WriteString('General', 'Name', _Name);
ini.WriteString('General', 'Used', 'No');
ini.WriteDateTime('General', 'LastUpdated', Now);
ini.UpdateFile;
ini.Free;
inherited Destroy;
end;
end.
|
unit ubox;
interface
uses Classes, Types, Graphics, Controls;
type
TBox = class
private
FOpenChilds: TList;
FClosedChilds: TList;
FParent: TBox;
FId:Integer;
public
constructor Create(Parent:TBox);
destructor Destroy ; override;
procedure Paint(ACanvas:TCanvas); virtual;
function MouseDown(p:TPoint; Button : TMouseButton):Boolean; virtual;
function MouseUp(p:TPoint; Button : TMouseButton):Boolean; virtual;
function MouseMove(pold, p:TPoint; Shift:TShiftState):Boolean; virtual;
property OpenChilds: TList read FOpenChilds;
property ClosedChilds: TList read FClosedChilds;
property Parent:TBox read FParent write FParent;
property Id: Integer read FId;
end;
implementation
uses
Windows,
Contnrs;
{ TBox }
var NextBoxId :Integer = 0;
constructor TBox.Create(Parent: TBox);
begin
inherited Create;
FParent:= Parent;
FOpenChilds:= TObjectList.Create;
FClosedChilds:= TObjectList.Create;
FId:= NextBoxId;
inc(NextBoxId);
end;
destructor TBox.Destroy;
begin
FOpenChilds.Free;
FClosedChilds.Free;
inherited;
end;
function TBox.MouseDown(p: TPoint; Button: TMouseButton): Boolean;
var i:Integer;
begin
for i:= 0 to FClosedChilds.Count-1 do
if TBox(FClosedChilds[i]).MouseDown(p,Button)
then
begin
result:=True;
exit;
end;
for i:= 0 to FOpenChilds.Count-1 do
if TBox(FOpenChilds[i]).MouseDown(p,Button)
then
begin
result:=True;
exit;
end;
Result:=False;
end;
function TBox.MouseMove(pold, p: TPoint; Shift:TShiftState): Boolean;
var i:Integer;
begin
for i:= 0 to FClosedChilds.Count-1 do
if TBox(FClosedChilds[i]).MouseMove(pold,p,Shift)
then
begin
result:=True;
exit;
end;
for i:= 0 to FOpenChilds.Count-1 do
if TBox(FOpenChilds[i]).MouseMove(pold,p,Shift)
then
begin
result:=True;
exit;
end;
Result:=False;
end;
function TBox.MouseUp(p: TPoint; Button: TMouseButton): Boolean;
var i:Integer;
begin
for i:= 0 to FClosedChilds.Count-1 do
if TBox(FClosedChilds[i]).MouseUp(p,Button)
then
begin
result:=True;
exit;
end;
for i:= 0 to FOpenChilds.Count-1 do
if TBox(FOpenChilds[i]).MouseUp(p,Button)
then
begin
result:=True;
exit;
end;
Result:=False;
end;
procedure TBox.Paint(ACanvas: TCanvas);
var i:Integer;
begin
for i:= FOpenChilds.Count-1 downto 0 do
TBox(FOpenChilds[i]).Paint(ACanvas);
for i:= FClosedChilds.Count-1 downto 0 do
TBox(FClosedChilds[i]).Paint(ACanvas);
end;
end.
|
unit html_helperclass;
interface
uses
Classes, SysUtils, WStrings;
type
TNodeList = class
public
FOwnerNode: Pointer{TNode};
FList: TList;
public
function GetLength: Integer; virtual;
function NodeListIndexOf(node: Pointer{TNode}): Integer;
procedure NodeListAdd(node: Pointer{TNode});
procedure NodeListDelete(I: Integer);
procedure NodeListInsert(I: Integer; node: Pointer{TNode});
procedure NodeListRemove(node: Pointer{TNode});
procedure NodeListClear(WithItems: Boolean);
property ownerNode: Pointer{TNode} read FOwnerNode;
constructor Create(AOwnerNode: Pointer{TNode});
public
destructor Destroy; override;
function item(index: Integer): Pointer{TNode}; virtual;
property length: Integer read GetLength;
end;
TNamedNodeMap = class(TNodeList)
public
function getNamedItem(const name: WideString): Pointer{TNode};
function setNamedItem(arg: Pointer{TNode}): Pointer{TNode};
function removeNamedItem(const name: WideString): Pointer{TNode};
function getNamedItemNS(const namespaceURI, localName: WideString): Pointer{TNode};
function setNamedItemNS(arg: Pointer{TNode}): Pointer{TNode};
function removeNamedItemNS(const namespaceURI, localName: WideString): Pointer{TNode};
end;
TSearchNodeList = class(TNodeList)
public
FNamespaceParam : WideString;
FNameParam : WideString;
FSynchronized: Boolean;
function GetLength: Integer; override;
function acceptNode(node: Pointer{TNode}): Boolean;
procedure TraverseTree(rootNode: Pointer{TNode});
procedure Rebuild;
public
constructor Create(AOwnerNode: Pointer{TNode}; const namespaceURI, name: WideString);
destructor Destroy; override;
procedure Invalidate;
function item(index: Integer): Pointer{TNode}; override;
end;
TNamespaceURIList = class
public
FList: TWStringList;
function GetItem(I: Integer): WideString;
public
constructor Create;
destructor Destroy; override;
procedure Clear;
function Add(const NamespaceURI: WideString): Integer;
property Item[I: Integer]: WideString read GetItem; default;
end;
TURLSchemes = class(TStringList)
private
FMaxLen: Integer;
public
function Add(const S: String): Integer; override;
function IsURL(const S: String): Boolean;
function GetScheme(const S: String): String;
property MaxLen: Integer read FMaxLen;
end;
var
URLSchemes: TURLSchemes = nil;
implementation
uses
html_utils,
HTMLParserAll3,
define_htmldom;
constructor TNodeList.Create(AOwnerNode: Pointer{TNode});
begin
inherited Create;
FOwnerNode := AOwnerNode;
FList := TList.Create
end;
destructor TNodeList.Destroy;
begin
FList.Free;
inherited Destroy
end;
function TNodeList.NodeListIndexOf(node: Pointer{TNode}): Integer;
begin
Result := FList.IndexOf(node)
end;
function TNodeList.GetLength: Integer;
begin
Result := FList.Count
end;
procedure TNodeList.NodeListInsert(I: Integer; Node: Pointer{TNode});
begin
FList.Insert(I, Node)
end;
procedure TNodeList.NodeListDelete(I: Integer);
begin
FList.Delete(I)
end;
procedure TNodeList.NodeListAdd(node: Pointer{TNode});
begin
FList.Add(node)
end;
procedure TNodeList.NodeListRemove(node: Pointer{TNode});
begin
FList.Remove(node)
end;
function TNodeList.item(index: Integer): Pointer{TNode};
begin
if (index >= 0) and (index < length) then
Result := FList[index]
else
Result := nil
end;
procedure TNodeList.NodeListClear(WithItems: Boolean);
var
I: Integer;
tmpDomNode: PHtmlDomNode;
begin
if WithItems then
begin
for I := length - 1 downto 0 do
begin
tmpDomNode := item(I);
HtmlDomNodeFree(tmpDomNode);
end;
end;
FList.Clear
end;
constructor TSearchNodeList.Create(AOwnerNode: Pointer{TNode}; const namespaceURI, name: WideString);
begin
inherited Create(AOwnerNode);
FNamespaceParam := namespaceURI;
FNameParam := name;
Rebuild
end;
procedure HtmlDocRemoveSearchNodeList(ADocument: PHtmlDocDomNode; NodeList: TNodeList);
begin
ADocument.SearchNodeLists.Remove(NodeList)
end;
destructor TSearchNodeList.Destroy;
begin
if (nil <> ownerNode) then
begin
if (nil <> PHtmlDomNode(ownerNode).ownerDocument) then
begin
HtmlDocRemoveSearchNodeList(PHtmlDomNode(ownerNode).ownerDocument, Self);
end;
end;
inherited Destroy
end;
function TSearchNodeList.GetLength: Integer;
begin
if not FSynchronized then
Rebuild;
Result := inherited GetLength
end;
function HtmlDomNodeGetNamespaceURI(AHtmlDomNode: PHtmlDomNode): WideString;
begin
Result := AHtmlDomNode.ownerDocument.namespaceURIList[AHtmlDomNode.NamespaceURI]
end;
function HtmlDomNodeGetLocalName(AHtmlDomNode: PHtmlDomNode): WideString;
begin
Result := AHtmlDomNode.NodeName;
end;
function TSearchNodeList.acceptNode(node: Pointer{TNode}): Boolean;
begin
Result := (PHtmlDomNode(Node).NodeType = HTMLDOM_NODE_ELEMENT) and
((FNamespaceParam = '*') or (FNamespaceParam = HtmlDomNodeGetNamespaceURI(node))) and
((FNameParam = '*') or (FNameParam = HtmlDomNodeGetLocalName(node)))
end;
procedure TSearchNodeList.TraverseTree(rootNode: Pointer{TNode});
var
I: Integer;
begin
if (rootNode <> ownerNode) and acceptNode(rootNode) then
NodeListAdd(rootNode);
for I := 0 to PhtmlDomNode(rootNode).childNodes.length - 1 do
TraverseTree(PhtmlDomNode(rootNode).childNodes.item(I))
end;
procedure HtmlDocAddSearchNodeList(ADocument: PHtmlDocDomNode; NodeList: TNodeList);
begin
if ADocument.SearchNodeLists.IndexOf(NodeList) < 0 then
ADocument.SearchNodeLists.Add(Nodelist)
end;
procedure TSearchNodeList.Rebuild;
begin
NodeListClear(false);
if (nil <> ownerNode) and (nil <> PHtmlDomNode(ownerNode).ownerDocument) then
begin
TraverseTree(ownerNode);
HtmlDocAddSearchNodeList(PHtmlDomNode(ownerNode).ownerDocument, Self)
end;
Fsynchronized := true
end;
procedure TSearchNodeList.Invalidate;
begin
FSynchronized := false
end;
function TSearchNodeList.item(index: Integer): Pointer{TNode};
begin
if not FSynchronized then
Rebuild;
Result := inherited item(index)
end;
function TNamedNodeMap.getNamedItem(const name: WideString): Pointer{TNode};
var
I: Integer;
begin
for I := 0 to length - 1 do
begin
Result := item(I);
if HtmlDomNodeGetName(Result) = name then
Exit
end;
Result := nil
end;
function TNamedNodeMap.setNamedItem(arg: Pointer{TNode}): Pointer{TNode};
var
Attr: PHtmlAttribDomNode;
tmpOwnerElement: PHtmlElementDomNode;
begin
if PHtmlDomNode(arg).ownerDocument <> PHtmlDomNode(ownerNode).ownerDocument then
raise DomException(ERR_WRONG_DOCUMENT);
if PHtmlDomNode(arg).NodeType = HTMLDOM_NODE_ATTRIBUTE then
begin
Attr := PHtmlAttribDomNode(arg);
tmpOwnerElement := AttrGetOwnerElement(PHtmlAttribDomNode(Attr));
if (nil <> tmpOwnerElement) and
(tmpOwnerElement <> ownerNode) then
raise DomException(ERR_INUSE_ATTRIBUTE)
end;
Result := getNamedItem(HtmlDomNodeGetName(arg));
if (nil <> Result) then
NodeListRemove(Result);
NodeListAdd(arg)
end;
function TNamedNodeMap.removeNamedItem(const name: WideString): Pointer{TNode};
var
Node: PHtmlDomNode;
begin
Node := getNamedItem(name);
if Node = nil then
raise DomException.Create(ERR_NOT_FOUND);
NodeListRemove(Node);
Result := Node
end;
function TNamedNodeMap.getNamedItemNS(const namespaceURI, localName: WideString): Pointer{TNode};
var
I: Integer;
begin
for I := 0 to length - 1 do
begin
Result := item(I);
if (HtmlDomNodeGetLocalName(Result) = localName) and
(HtmlDomNodeGetNamespaceURI(Result) = namespaceURI) then
Exit
end;
Result := nil
end;
function TNamedNodeMap.setNamedItemNS(arg: Pointer{TNode}): Pointer{TNode};
var
Attr: PHtmlAttribDomNode;
tmpOwnerElement: PHtmlElementDomNode;
begin
if PHtmlDomNode(arg).ownerDocument <> PHtmlDomNode(ownerNode).ownerDocument then
raise DomException(ERR_WRONG_DOCUMENT);
if PHtmlDomNode(arg).NodeType = HTMLDOM_NODE_ATTRIBUTE then
begin
Attr := arg;
tmpOwnerElement := AttrGetOwnerElement(PHtmlAttribDomNode(Attr));
if (nil <> tmpOwnerElement) and
(tmpOwnerElement <> ownerNode) then
raise DomException(ERR_INUSE_ATTRIBUTE)
end;
Result := getNamedItemNS(HtmlDomNodeGetNamespaceURI(arg), HtmlDomNodeGetLocalName(arg));
if (nil <> Result) then
NodeListRemove(Result);
NodeListAdd(arg)
end;
function TNamedNodeMap.removeNamedItemNS(const namespaceURI, localName: WideString): Pointer{TNode};
var
Node: PHtmlDomNode;
begin
Node := getNamedItemNS(namespaceURI, localName);
if Node = nil then
raise DomException.Create(ERR_NOT_FOUND);
NodeListRemove(Node);
Result := Node
end;
constructor TNamespaceURIList.Create;
begin
inherited Create;
FList := TWStringList.Create;
FList.Add('')
end;
destructor TNamespaceURIList.Destroy;
begin
FList.Free;
inherited Destroy
end;
procedure TNamespaceURIList.Clear;
begin
FList.Clear
end;
function TNamespaceURIList.GetItem(I: Integer): WideString;
begin
Result := FList[I]
end;
function TNamespaceURIList.Add(const NamespaceURI: WideString): Integer;
var
I: Integer;
begin
for I := 0 to FList.Count - 1 do
if FList[I] = NamespaceURI then
begin
Result := I;
Exit
end;
Result := FList.Add(NamespaceURI)
end;
function TURLSchemes.Add(const S: String): Integer;
begin
if Length(S) > FMaxLen then
FMaxLen := Length(S);
Result := inherited Add(S)
end;
function TURLSchemes.IsURL(const S: String): Boolean;
begin
Result := IndexOf(LowerCase(S)) >= 0
end;
function TURLSchemes.GetScheme(const S: String): String;
const
SchemeChars = [Ord('A')..Ord('Z'), Ord('a')..Ord('z')];
var
I: Integer;
begin
Result := '';
for I := 1 to MaxLen + 1 do
begin
if I > Length(S) then
Exit;
if S[I] = ':' then
begin
if IsURL(Copy(S, 1, I - 1)) then
Result := Copy(S, 1, I - 1);
Exit
end
end
end;
initialization
URLSchemes := TURLSchemes.Create;
URLSchemes.Add('http');
URLSchemes.Add('https');
URLSchemes.Add('ftp');
URLSchemes.Add('mailto');
URLSchemes.Add('news');
URLSchemes.Add('nntp');
URLSchemes.Add('gopher');
finalization
URLSchemes.Free;
end.
|
unit SegmentProperties;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls,
TrackItems;
type
TSegmentPropertiesForm = class(TForm)
Label1: TLabel;
StartXTEdit: TEdit;
Label2: TLabel;
StartYTEdit: TEdit;
Label3: TLabel;
FinishXTEdit: TEdit;
Label4: TLabel;
FinishYTEdit: TEdit;
Label5: TLabel;
Label6: TLabel;
Button1: TButton;
Button2: TButton;
WarningTLabel: TLabel;
WidthTEdit: TEdit;
Label7: TLabel;
Label8: TLabel;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Segment : TteSegment;
BoardRect_D : TRect;
end;
var
SegmentPropertiesForm: TSegmentPropertiesForm;
implementation
{$R *.dfm}
procedure TSegmentPropertiesForm.FormShow(Sender: TObject);
begin
// display current start & finish coords of segment
StartXTEdit.Text := IntToStr( Segment.Start_1000.X );
StartYTEdit.Text := IntToStr( Segment.Start_1000.Y );
FinishXTEdit.Text := IntToStr( Segment.Finish_1000.X );
FinishYTEdit.Text := IntToStr( Segment.Finish_1000.Y );
WidthTEdit.Text := IntToStr( Segment.Width_1000 );
// nothing to warn of yet
WarningTLabel.Caption := '';
end;
procedure TSegmentPropertiesForm.FormClose(Sender: TObject; var Action: TCloseAction);
var
Start_D : TPoint;
Finish_D : TPoint;
Width_D : integer;
begin
// if escaping form
if ModalResult <> mrOK then begin
exit;
end;
// read values from controls into temporary variables
try
Start_D.X := StrToInt( StartXTEdit.Text );
Start_D.Y := StrToInt( StartYTEdit.Text );
Finish_D.X := StrToInt( FinishXTEdit.Text );
Finish_D.Y := StrToInt( FinishYTEdit.Text );
Width_D := StrToInt( WidthTEdit.Text );
except
WarningTLabel.Caption := 'Only numerals allowed!';
Action := caNone;
exit;
end;
// values all acceptable, so store them
Segment.Start_1000.X := Start_D.X;
Segment.Start_1000.Y := Start_D.Y;
Segment.Finish_1000.X := Finish_D.X;
Segment.Finish_1000.Y := Finish_D.Y;
Segment.Width_1000 := Width_D;
// keep segment on screen
Segment.PullInsideRect_D( BoardRect_D );
end;
end.
|
unit TanqueDAO;
interface
uses
Data.SqlExpr, SysUtils, Forms, Windows, Util, Tanque;
type
TTanqueDAO = class
private
{ private declarations }
public
function ObterListaTanques(Descricao: String = ''):TSQLQuery;
function ObterTanquePorId(Id :Integer):TTanque;
function UltimoTanque:TTanque;
procedure Salvar(Tanque: TTAnque);
procedure Excluir(Tanque: TTanque);
end;
implementation
{ TTanqueDAO }
procedure TTanqueDAO.Excluir(Tanque: TTanque);
var
Query: TSQLQuery;
begin
try
TUtil.CriarQuery(Query);
Query.SQL.Add('DELETE FROM Tanque');
Query.SQL.Add(' WHERE Id = :Id');
Query.ParamByName('Id').AsInteger := Tanque.Id;
Query.ExecSQL();
TUtil.DestruirQuery(Query);
except on E: Exception do
begin
raise Exception.Create(E.Message);
end;
end;
end;
function TTanqueDAO.ObterListaTanques(Descricao: String = ''): TSQLQuery;
var
Query: TSQLQuery;
begin
try
TUtil.CriarQuery(Query);
Query.SQL.Add('SELECT t.Id');
Query.SQL.Add(' ,t.Descricao');
Query.SQL.Add(' ,t.Tipo');
Query.SQL.Add(' FROM Tanque t');
if (Trim(Descricao) <> '') then
begin
Query.SQL.Add(' WHERE t.Descricao LIKE ''%'+Trim(Descricao)+'%''');
end;
Query.SQL.Add(' ORDER BY t.Id');
Query.Open();
if not(Query.IsEmpty) then
begin
Result := Query;
end
else
begin
Result := nil;
TUtil.DestruirQuery(Query);
end;
except on E: Exception do
begin
raise Exception.Create(E.Message);
end;
end;
end;
function TTanqueDAO.ObterTanquePorId(Id: Integer): TTanque;
var
Query: TSQLQuery;
Tanque: TTanque;
begin
try
TUtil.CriarQuery(Query);
Query.SQL.Add('SELECT t.Id');
Query.SQL.Add(' ,t.Descricao');
Query.SQL.Add(' ,t.Tipo');
Query.SQL.Add(' FROM Tanque t');
Query.SQL.Add(' WHERE t.Id = :Id');
Query.ParamByName('Id').AsInteger := Id;
Query.Open();
if not(Query.IsEmpty) then
begin
Tanque := TTanque.Create;
Tanque.Id := Query.FieldByName('Id').AsInteger;
Tanque.Descricao := Trim(Query.FieldByName('Descricao').AsString);
case (Query.FieldByName('Tipo').AsInteger) of
0 : Tanque.Tipo := Gasolina;
1 : Tanque.Tipo := OleoDiesel;
end;
Result := Tanque;
end
else
begin
Result := nil;
end;
TUtil.DestruirQuery(Query);
except on E: Exception do
begin
raise Exception.Create(E.Message);
end;
end;
end;
procedure TTanqueDAO.Salvar(Tanque: TTAnque);
var
Query: TSQLQuery;
begin
try
TUtil.CriarQuery(Query);
if (Tanque.Id = 0) then
begin
Query.SQL.Add('INSERT INTO Tanque');
Query.SQL.Add(' (Descricao');
Query.SQL.Add(' ,Tipo)');
Query.SQL.Add(' VALUES(:Descricao');
Query.SQL.Add(' ,:Tipo)');
end
else
begin
Query.SQL.Add('UPDATE Tanque');
Query.SQL.Add(' SET Descricao = :Descricao');
Query.SQL.Add(' ,Tipo = :Tipo');
Query.SQL.Add(' WHERE Id = :Id');
Query.ParamByName('Id').AsInteger := Tanque.Id;
end;
Query.ParamByName('Descricao').AsString := Tanque.Descricao;
case (Tanque.Tipo) of
Gasolina : Query.ParamByName('Tipo').AsInteger := 0;
OleoDiesel : Query.ParamByName('Tipo').AsInteger := 1;
end;
Query.ExecSQL();
TUtil.DestruirQuery(Query);
except on E: Exception do
begin
raise Exception.Create(E.Message);
end;
end;
end;
function TTanqueDAO.UltimoTanque: TTanque;
var
Query: TSQLQuery;
Tanque: TTanque;
begin
try
TUtil.CriarQuery(Query);
Query.SQL.Add('SELECT t.Id');
Query.SQL.Add(' ,t.Descricao');
Query.SQL.Add(' ,t.Tipo');
Query.SQL.Add(' FROM Tanque t');
Query.SQL.Add(' WHERE t.Id = (SELECT MAX(Id)');
Query.SQL.Add(' FROM Tanque)');
Query.Open();
if not(Query.IsEmpty) then
begin
Tanque := TTanque.Create;
Tanque.Id := Query.FieldByName('Id').AsInteger;
Tanque.Descricao := Trim(Query.FieldByName('Descricao').AsString);
case (Query.FieldByName('Tipo').AsInteger) of
0 : Tanque.Tipo := Gasolina;
1 : Tanque.Tipo := OleoDiesel;
end;
Result := Tanque;
end
else
begin
Result := nil;
end;
TUtil.DestruirQuery(Query);
except on E: Exception do
begin
raise Exception.Create(E.Message);
end;
end;
end;
end.
|
{ $HDR$}
{**********************************************************************}
{ Unit archived using Team Coherence }
{ Team Coherence is Copyright 2002 by Quality Software Components }
{ }
{ For further information / comments, visit our WEB site at }
{ http://www.TeamCoherence.com }
{**********************************************************************}
{}
{ $Log: 11253: HashBox.pas
{
{ Rev 1.0 11/12/2002 09:18:10 PM JPMugaas
{ Initial check in. Import from FTP VC.
}
unit HashBox;
interface
uses
IndyBox,
IdHash, IdHashCRC, IdHashElf, IdHashMessageDigest;
const
MaxMemToLoad = 16777216; // 16MB
type
THashBox = class(TIndyBox)
public
procedure Test; override;
end;
implementation
uses
Classes,
IdGlobal,
SysUtils;
{ THashBox }
procedure THashBox.Test;
const
CHashTests = 6;
var
FHash16 : TIdHash16;
FHash32 : TIdHash32;
FHashMD2 : TIdHash128;
FHashMD4 : TIdHash128;
FHashMD5 : TIdHash128;
FHashElf : TidHashElf;
finddata: TSearchRec;
FS : TFileStream;
MS : TMemoryStream;
TS : TStream;
TestData : TStringList;
i : Integer;
H16 : Word;
H32 : LongWord;
H128 : T4x4LongWordRecord;
function ToHex : String;
var
T128 : T128BitRecord;
i : Integer;
begin
result := '';
Move(H128, T128, 16);
for i := 0 to 15 do
begin
result := result + IntToHex(T128[i], 2);
end;
end;
begin
FHash16 := TIdHashCRC16.Create;
FHash32 := TIdHashCRC32.Create;
FHashMD2 := TIdHashMessageDigest2.Create;
FHashMD4 := TIdHashMessageDigest4.Create;
FHashMD5 := TIdHashMessageDigest5.Create;
FHashElf := TIdHashElf.Create;
TestData := TStringList.Create;
i:= 0;
try
if FindFirst(GetDataDir + '*.ini', faAnyFile - faDirectory, finddata) = 0 then begin
repeat
inc(i);
Status('Test ' + IntToStr(i) + ': ' + finddata.Name);
TestData.LoadFromFile(GetDataDir + finddata.Name);
if TestData.Count < CHashTests then
begin
raise Exception.Create('Insufficient test results in .ini for tests');
end;
// Change the extension to .dat
FS := TFileStream.Create(GetDataDir+ChangeFileExt(finddata.Name, '.dat'), fmOpenRead or fmShareDenyNone);
TS := FS;
MS := TMemoryStream.Create;
if FS.Size <= MaxMemToLoad then
begin
MS.LoadFromStream(FS);
TS := MS;
end;
try
// CRC-16
H16 := FHash16.HashValue(TS);
Status('HashCRC16, expected: ' + TestData[0] + ', got: '
+ IntToHex(H16, 4));
Check(AnsiSameText(IntToHex(H16, 4), TestData[0]), 'Failed on HashCRC16.');
// CRC-32
TS.Seek(0, soFromBeginning);
H32 := FHash32.HashValue(TS);
Status('HashCRC32, expected: ' + TestData[1] + ', got: '
+ IntToHex(H32, 8));
Check(AnsiSameText(IntToHex(H32, 8), TestData[1]), 'Failed on HashCRC32.');
// MD2
TS.Seek(0, soFromBeginning);
H128 := FHashMD2.HashValue(TS);
Status('HashMD2, expected: ' + TestData[2] + ', got: '
+ ToHex);
Check(AnsiSameText(ToHex, TestData[2]), 'Failed on HashMD2.');
// MD4
TS.Seek(0, soFromBeginning);
H128 := FHashMD4.HashValue(TS);
Status('HashMD4, expected: ' + TestData[3] + ', got: '
+ ToHex);
Check(AnsiSameText(ToHex, TestData[3]), 'Failed on HashMD4.');
// MD5
TS.Seek(0, soFromBeginning);
H128 := FHashMD5.HashValue(TS);
Status('HashMD5, expected: ' + TestData[4] + ', got: '
+ ToHex);
Check(AnsiSameText(ToHex, TestData[4]), 'Failed on HashMD5.');
// Elf
TS.Seek(0, soFromBeginning);
H32 := FHashElf.HashValue(TS);
Status('HashElf, expected: ' + TestData[5] + ', got: '
+ IntToHex(H32, 8));
Check(AnsiSameText(IntToHex(H32, 8), TestData[5]), 'Failed on HashElf.');
finally
FreeAndNil(FS);
FreeAndNil(MS);
end;
until FindNext(finddata) <> 0;
FindClose(finddata);
end;
finally
FreeAndNil(TestData);
FreeAndNil(FHash16);
FreeAndNil(FHash32);
FreeAndNil(FHashMD2);
FreeAndNil(FHashMD4);
FreeAndNil(FHashMD5);
FreeAndNil(FHashElf);
end;
end;
initialization
TIndyBox.RegisterBox(THashBox, 'Hash', 'Misc');
end.
|
(*============================================================================
-----BEGIN PGP SIGNED MESSAGE-----
This code (c) 1994, 1997 Graham THE Ollis
GENERAL NOTES
=============
This is 16bit DOS TURBO PASCAL source code. It has been tested using
TURBO PASCAL 7.0. You will need AT LEAST version 5.0 to compile this
source code. You may need 7.0.
This is a generic pascal header for all my old pascal programs. Most of
these programs were written before I really got excited enough about 32bit
operating systems. In general this code dates back to 1994. Some of it
is important enough that I still work on it. For the most part though,
it's not the best code and it's probably the worst example of
documentation in all of computer science. oh well, you've been warned.
PGP NOTES
=========
This PGP signed message is provided in the hopes that it will prove useful
and informative. My name is Graham THE Ollis <ollisg@ns.arizona.edu> and my
public PGP key can be found by fingering my university account:
finger ollisg@u.arizona.edu
LEGAL NOTES
===========
You are free to use, modify and distribute this source code provided these
headers remain in tact. If you do make modifications to these programs,
i'd appreciate it if you documented your changes and leave some contact
information so that others can blame you and me, rather than just me.
If you maintain a anonymous ftp site or bbs feel free to archive this
stuff away. If your pressing CDs for commercial purposes again have fun.
It would be nice if you let me know about it though.
HOWEVER- there is no written or implied warranty. If you don't trust this
code then delete it NOW. I will in no way be held responsible for any
losses incurred by your using this software.
CONTACT INFORMATION
===================
You may contact me for just about anything relating to this code through
e-mail. Please put something in the subject line about the program you
are working with. The source file would be best in this case (e.g.
frag.pas, hexed.pas ... etc)
ollisg@ns.arizona.edu
ollisg@idea-bank.com
ollisg@lanl.gov
The first address is the most likely to work.
all right. that all said... HAVE FUN!
-----BEGIN PGP SIGNATURE-----
Version: 2.6.2
iQCVAwUBMv1UFoazF2irQff1AQFYNgQAhjiY/Dh3gSpk921FQznz4FOwqJtAIG6N
QTBdR/yQWrkwHGfPTw9v8LQHbjzl0jjYUDKR9t5KB7vzFjy9q3Y5lVHJaaUAU4Jh
e1abPhL70D/vfQU3Z0R+02zqhjfsfKkeowJvKNdlqEe1/kSCxme9mhJyaJ0CDdIA
40nefR18NrA=
=IQEZ
-----END PGP SIGNATURE-----
==============================================================================
| cfg.pas
| read config file for defaults.
|
| History:
| Date Author Comment
| ---- ------ -------
| -- --- 94 G. Ollis created and developed program
============================================================================*)
{$I-}
Unit CFG;
INTERFACE
Uses Crt;
Const
{Mouse Constants}
DefLeftButton=0;
DefRightButton=1;
DefCenterButton=2;
DefMousePresent=FALSE;
Var
LeftButton, {Mouse setup}
RightButton,
CenterButton,
SaveTextAttr:Byte;
MousePresent:Boolean;
Const
CFGFile='HEXED.CFG';
{++PROCEDURES++++++++++++++++++++++++++++++++++++++++++++++++++++++++++}
{++FUNCTIONS+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++}
Function HelpDir:String;
Function CheckOverflow(C:Char; P:Pointer):Boolean;
{++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++}
IMPLEMENTATION
Uses Dos,Ollis,CNT,VConvert,VOCTool,CMFTool;
Type
Exclusive=Array [1..10] Of Byte;
ExclusionType=Record
D:Array [1..20] Of Exclusive;
Num:Byte;
End;
Var
ExcludeReal:ExclusionType;
ExcludeSing:ExclusionType;
ExcludeDoub:ExclusionType;
ExcludeExte:ExclusionType;
ExcludeComp:ExclusionType;
{------------------------------------------------------------------------}
{FSplit}
Function HelpDir:String;
Var Path: PathStr; var Dir: DirStr; var Name: NameStr;
var Ext: ExtStr;
Begin
Path:=ParamStr(0);
FSplit(Path,Dir,Name,Ext);
If Dir[Length(Dir)]='\' Then
Delete(Dir,Length(Dir),1);
HelpDir:=Dir;
End;
{----------------------------------------------------------------------}
Function CheckOverflow(C:Char; P:Pointer):Boolean;
Var E2:^Exclusive; { file fragment}
E1:^ExclusionType; { exclude what? }
I:Integer;
Begin
Case UpCase(C) Of
'R' : E1:=@ExcludeReal;
'S' : E1:=@ExcludeSing;
'D' : E1:=@ExcludeDoub;
'X' : E1:=@ExcludeExte;
'C' : E1:=@ExcludeComp;
End;
CheckOverflow:=False;
E2:=P;
For I:=1 To E1^.Num Do
If ((E1^.D[I,1]=E2^[1]) Or (E1^.D[I,1]=0)) And
((E1^.D[I,2]=E2^[2]) Or (E1^.D[I,2]=0)) And
((E1^.D[I,3]=E2^[3]) Or (E1^.D[I,3]=0)) And
((E1^.D[I,4]=E2^[4]) Or (E1^.D[I,4]=0)) And
((E1^.D[I,5]=E2^[5]) Or (E1^.D[I,5]=0)) And
((E1^.D[I,6]=E2^[6]) Or (E1^.D[I,6]=0)) And
((E1^.D[I,7]=E2^[7]) Or (E1^.D[I,7]=0)) And
((E1^.D[I,8]=E2^[8]) Or (E1^.D[I,8]=0)) And
((E1^.D[I,9]=E2^[9]) Or (E1^.D[I,9]=0)) And
((E1^.D[I,10]=E2^[10]) Or (E1^.D[I,10]=0)) Then
Begin
CheckOverflow:=True;
Exit;
End;
End;
{----------------------------------------------------------------------}
Var
Buff:^String;
Function GetString(Var F:Text):String;
Var
S:String;
I:Integer;
Begin
If Buff^='' Then
Readln(F,Buff^);
I:=1;
S:='';
While (Buff^[I]<>' ') And (I<=Length(Buff^)) Do
Begin
S:=S+Buff^[I];
Inc(I);
End;
Delete(Buff^,1,I);
GetString:=S;
End;
{----------------------------------------------------------------------}
Function GetByte(Var F:TEXT):Byte;
Begin
GetByte:=StrToInt(GetString(F));
End;
{----------------------------------------------------------------------}
Function UpString(S:String):String;
Var I:Integer;
Begin
For I:=1 To Length(S) Do
S[I]:=UpCase(S[I]);
UpString:=S;
End;
{----------------------------------------------------------------------}
Procedure StOverflow(Var F:Text);
Var S:String; I:Integer;
Begin
S:=UpString(GetString(F));
If S='REAL' Then
If ExcludeReal.Num<19 Then
Begin
Inc(ExcludeReal.Num);
For I:=1 To 10 Do
ExcludeReal.D[ExcludeReal.Num,I]:=GetByte(F);
End
Else
Begin
Write('Too many real exclusions');
Repeat Until Readkey=#13;
Writeln('.');
End;
If S='SING' Then
If ExcludeSing.Num<19 Then
Begin
Inc(ExcludeSing.Num);
For I:=1 To 10 Do
ExcludeSing.D[ExcludeSing.Num,I]:=GetByte(F);
End
Else
Begin
Write('Too many single exclusions');
Repeat Until Readkey=#13;
Writeln('.');
End;
If S='DOUB' Then
If ExcludeDoub.Num<19 Then
Begin
Inc(ExcludeDoub.Num);
For I:=1 To 10 Do
ExcludeDoub.D[ExcludeDoub.Num,I]:=GetByte(F);
End
Else
Begin
Write('Too many Double exclusions');
Repeat Until Readkey=#13;
Writeln('.');
End;
If S='EXTE' Then
If ExcludeExte.Num<19 Then
Begin
Inc(ExcludeExte.Num);
For I:=1 To 10 Do
ExcludeExte.D[ExcludeExte.Num,I]:=GetByte(F);
End
Else
Begin
Write('Too many extended exclusions');
Repeat Until Readkey=#13;
Writeln('.');
End;
If S='COMP' Then
If ExcludeComp.Num<19 Then
Begin
Inc(ExcludeComp.Num);
For I:=1 To 10 Do
ExcludeComp.D[ExcludeComp.Num,I]:=GetByte(F);
End
Else
Begin
Write('Too many comp exclusions');
Repeat Until Readkey=#13;
Writeln('.');
End;
Buff^:='';
End;
{----------------------------------------------------------------------}
Procedure ReadCFGFile(FileName:String);
Var F:Text; S:String; Line:Integer;
Begin
LeftButton:=DefLeftButton;
RightButton:=DefRightButton;
CenterButton:=DefCenterButton;
MousePresent:=DefMousePresent;
ExcludeReal.Num:=0;
ExcludeSing.Num:=0;
ExcludeDoub.Num:=0;
ExcludeExte.Num:=0;
ExcludeComp.Num:=0;
Line:=1;
If HelpDir='' Then
Assign(F,FileName)
Else
Assign(F,HelpDir+'\'+FileName);
Reset(F);
If IOResult<>0 Then
Exit;
While Not EOF(F) Do
Begin
Repeat
S:=UpString(GetString(F));
Until (S<>'') Or (EOF(F));
If (S[1]=';') Then
Buff^:=''
Else If S='SET' Then
Begin
S:=UpString(GetString(F));
If S='OVERFLOW' Then
StOverflow(F)
Else If S='LFTBTN' Then
Begin
LeftButton:=GetByte(F);
Buff^:='';
End
Else If S='CNTBTN' Then
Begin
CenterButton:=GetByte(F);
Buff^:='';
End
Else If S='RTBTN' Then
Begin
RightButton:=GetByte(F);
Buff^:='';
End
Else
Begin
WriteContactMsg;
TextAttr:=LightGray;
Writeln('Set command not known line #',line);
Writeln('SET ',S);
Halt;
End;
End
Else If S='INIT' Then
Begin
S:=UpString(GetString(F));
If S='MOUSE' Then
Begin
If InitMC Then
Begin
MousePresent:=True;
ShowMC;
End;
End
Else If S='SB' Then
Begin
S:=UpString(GetString(F));
If S='DIGITAL' Then
InitVocSB
Else IF S='FM' Then
InitCMFSB
Else
Begin
WriteContactMsg;
TextAttr:=LightGray;
Writeln('sound blaster initalization unknown.');
Writeln('INIT SB ',S);
End;
End
Else
Begin
WriteContactMsg;
TextAttr:=LightGray;
Writeln('hardware initalization unknown.');
Writeln('INIT ',S);
Halt;
End;
Buff^:='';
End
Else
Begin
WriteContactMsg;
TextAttr:=LightGray;
Writeln('Configuration File error line #',line);
Writeln(S);
Halt;
End;
Line:=Line+1;
End;
Close(F);
End;
{======================================================================}
Begin
New(Buff);
Buff^:='';
ReadCFGFile(CFGFile);
Dispose(Buff);
End.
|
{ **************************************************************************** }
{ Adapted from CheckBox in }
{ }
{ Smart Mobile Studio - Runtime Library }
{ }
{ Copyright © 2012-2014 Optimale Systemer AS. }
{ }
{ **************************************************************************** }
{$R 'lib\radiobutton.css'}
unit RadioButton;
interface
uses
System.Types, SmartCL.System, SmartCL.Components, SmartCL.Controls.SimpleLabel;
type
TW3RadioCheckMark = class(TW3CustomControl)
protected
procedure setWidth(aValue: Integer); override;
procedure setHeight(aValue: Integer); override;
function makeElementTagObj: THandle; override;
procedure StyleTagObject; override; empty;
function getChecked: Boolean; virtual;
procedure setChecked(const aValue: Boolean); virtual;
published
property Checked: Boolean read getChecked write setChecked;
end;
TW3RadioButton = class(TW3CustomControl)
private
FLabel: TW3SimpleLabel;
FMark: TW3RadioCheckMark;
protected
function getCaption: String;
procedure setCaption(aValue: String);
function getChecked: Boolean;
procedure setChecked(aValue: Boolean);
function getEnabled: Boolean; override;
procedure setEnabled(aValue: Boolean); override;
procedure InitializeObject; override;
procedure FinalizeObject; override;
procedure Resize; override;
public
property Label: TW3SimpleLabel read FLabel;
property CheckMark: TW3RadioCheckMark read FMark;
published
property Caption: String read getCaption write setCaption;
property Checked: Boolean read getChecked write setChecked;
end;
implementation
{ **************************************************************************** }
{ TW3RadioCheckMark }
{ **************************************************************************** }
procedure TW3RadioCheckMark.setWidth(aValue: Integer);
begin
end;
procedure TW3RadioCheckMark.setHeight(aValue: Integer);
begin
end;
function TW3RadioCheckMark.getChecked: Boolean;
begin
Result := w3_getPropertyAsBool(Handle, 'checked');
end;
procedure TW3RadioCheckMark.setChecked(const aValue: Boolean);
begin
w3_setProperty(Handle, 'checked', aValue);
end;
function TW3RadioCheckMark.makeElementTagObj: THandle;
begin
Result := w3_createHtmlElement('input');
end;
{ **************************************************************************** }
{ TW3RadioButton }
{ **************************************************************************** }
procedure TW3RadioButton.InitializeObject;
begin
inherited;
FLabel := TW3SimpleLabel.Create(Self);
FLabel.Caption := 'Radio Button';
FLabel.Font.Size := 14;
FLabel.Handle.style.setProperty('margin-left', '1.8em');
FMark := TW3RadioCheckMark.Create(Self);
FMark.StyleClass := 'TW3RadioCheckMark';
w3_setProperty(FMark.Handle, 'type', 'radio');
FLabel.OnClick := procedure(Sender: TObject)
begin
if (FLabel.Enabled) then
if not Checked then
setChecked(true);
end;
FMark.OnClick := procedure(Sender: TObject)
begin
CSSClasses.RemoveByName('selected');
CSSClasses.Add('selected');
end;
end;
procedure TW3RadioButton.FinalizeObject;
begin
FMark.Free;
FLabel.Free;
inherited;
end;
function TW3RadioButton.getEnabled: Boolean;
begin
Result := FMark.Enabled;
end;
function TW3RadioButton.getChecked: Boolean;
begin
Result := FMark.Checked;
end;
procedure TW3RadioButton.setChecked(aValue: Boolean);
begin
FMark.Checked := aValue;
CSSClasses.RemoveByName('selected');
if aValue then
CSSClasses.Add('selected');
end;
procedure TW3RadioButton.setEnabled(aValue: Boolean);
begin
FMark.Enabled := aValue;
FLabel.Enabled := aValue;
end;
function TW3RadioButton.getCaption: String;
begin
Result := FLabel.Caption;
end;
procedure TW3RadioButton.setCaption(aValue: String);
begin
FLabel.Caption := aValue;
end;
procedure TW3RadioButton.Resize;
var
dx, dy: Integer;
begin
inherited;
dy := (ClientHeight div 2) - (FMark.Height div 2);
//FMark.MoveTo(0,dy);
dx := FMark.Left + FMark.Width + 1;
FLabel.SetBounds(dx, 0, ClientWidth - dx, ClientHeight);
end;
end.
|
{ $HDR$}
{**********************************************************************}
{ Unit archived using Team Coherence }
{ Team Coherence is Copyright 2002 by Quality Software Components }
{ }
{ For further information / comments, visit our WEB site at }
{ http://www.TeamCoherence.com }
{**********************************************************************}
{}
{ $Log: 22276: SaveToLoadFromFileTests.pas
{
{ Rev 1.1 28/07/2003 19:30:02 CCostelloe
{ Added tests for base64, quoted-printable and default encoding. Added check 0
{ for message body text. Incorporated '.' tests to ensure that the
{ end-of-message marker CRLF.CRLF is not confused with inline '.'s.
}
{
{ Rev 1.0 26/07/2003 13:34:52 CCostelloe
{ Test to show bug with attachments being saved base64 encoded while Content
{ Transfer Encoding set to 7bit.
}
unit SaveToLoadFromFileTests;
{This was written to demonstrate a bug in TIdMessage and hopefully check for it
if it ever creeps in again.
The attachment is written out with:
Content-Transfer-Encoding: 7bit
...but the attachment is actually encoded as base64 - you can verify this by
running the test, wait for the ShowMessage dialog, manually edit the file
it displays the name of (change the "7bit" to "base64"), and it will pass
check 6 but not check 7.
The real bug is that SaveToFile should have left the attachment content
unencoded.
Ciaran Costelloe, 26th July 2003.
CC2: Added tests for base64, quoted-printable and default encoding. Added
check 0 for message body text. Incorporated '.' tests to ensure that the
end-of-message marker CRLF.CRLF is not confused with inline '.'s.
}
interface
uses
Dialogs,
Classes,
IndyBox;
type
TSaveToLoadFromFileTests = class (TIndyBox)
public
procedure Test; override;
procedure ATest(AContentTransferEncoding: string);
end;
implementation
uses
IdGlobal,
IdMessage,
SysUtils, IdAttachmentFile, IdAttachmentMemory, IdText;
const
ContentID: string = '<73829274893.90238490.hkjsdhfsk>';
{ TExtraHeadersBox }
procedure TSaveToLoadFromFileTests.Test;
begin
ATest('base64');
ATest(''); {"Default" encoding}
ATest('quoted-printable');
ATest('7bit');
end;
procedure TSaveToLoadFromFileTests.ATest(AContentTransferEncoding: string);
var
Msg: TIdMessage;
Att: TIdAttachmentMemory;
Att2: TIdAttachmentFile;
LTempFilename: string;
AttText: string;
MsgText: string;
sTemp: string;
TheStrings: TStringList;
begin
sTemp := AContentTransferEncoding; if sTemp = '' then sTemp := 'default';
ShowMessage('Starting test for '+sTemp+' encoding...');
TheStrings := TStringList.Create;
Msg := TIdMessage.Create(nil);
MsgText := 'This is test message text.';
Msg.Body.Add(MsgText);
//Att := TIdAttachmentFile.Create(Msg.MessageParts, GetDataDir+'test.bmp');
AttText := 'This is a test attachment. This is deliberately a long line to ensure that the generated encoded lines go beyond 80 characters so that their line-breaking is tested.'#13#10'.This starts with a period'#13#10'.'#13#10'Last line only had a period.';
Att := TIdAttachmentMemory.Create(Msg.MessageParts, AttText);
try
Status('Creating message');
Att.ContentID := ContentID;
Att.FileName := 'test.txt';
Att.ContentTransfer := AContentTransferEncoding;
LTempFilename := MakeTempFilename;
//Msg.SaveToFile(GetTempDir()+'test.msg');
Msg.SaveToFile(LTempFilename);
Status('Message saved to file '+LTempFilename);
ShowMessage('Message saved to file '+LTempFilename+'. You may wish to view this to see if the intermediate file looks OK.');
finally
Msg.Free;
end;
Msg := TIdMessage.Create(nil);
try
Status('Loading message');
//Msg.LoadFromFile(GetTempDir()+'test.msg');
Msg.LoadFromFile(LTempFilename);
sTemp := Msg.Body.Strings[0];
Check(sTemp = MsgText, 'Check 0: Message body text >'+MsgText+'< changed to >'+sTemp+'<');
Check(Msg.MessageParts.Count = 2, 'Check 1: Wrong messagepart count ('+IntToStr(Msg.MessageParts.Count)+')!');
Check(Msg.MessageParts.Items[0] is TIdText, 'Check 2: Wrong type of attachment in #1');
Check(Msg.MessageParts.Items[1] is TIdAttachmentFile, 'Check 3: Wrong type of attachment in #2');
Att2 := TIdAttachmentFile(Msg.MessageParts.Items[1]);
Check(Att2.FileName = 'test.txt', 'Check 4: Filename of Attachment lost');
Check(Att2.ContentID = ContentID, 'Check 5: Content-ID lost/garbled!');
TheStrings.LoadFromFile(Att2.StoredPathName);
sTemp := TheStrings.Strings[0];
Check(sTemp = 'This is a test attachment. This is deliberately a long line to ensure that the generated encoded lines go beyond 80 characters so that their line-breaking is tested.',
'Check 6a: Attachment text >'+'This is a test attachment. This is deliberately a long line to ensure that the generated encoded lines go beyond 80 characters so that their line-breaking is tested.'+'< changed to >'+sTemp+'<');
sTemp := TheStrings.Strings[1];
Check(sTemp = '.This starts with a period',
'Check 6b: Attachment text >'+'.This starts with a period'+'< changed to >'+sTemp+'<');
sTemp := TheStrings.Strings[2];
Check(sTemp = '.',
'Check 6c: Attachment text >'+'.'+'< changed to >'+sTemp+'<');
sTemp := TheStrings.Strings[3];
Check(sTemp = 'Last line only had a period.',
'Check 6d: Attachment text >'+'Last line only had a period.'+'< changed to >'+sTemp+'<');
if AContentTransferEncoding <> '' then begin
{Note: We don't check encoding type if AContentTransferEncoding is '' because
we don't care what encoding SaveToFile chose. We do in the other cases, because
we specifically requested a certain encoding type.}
Check(Att2.ContentTransfer = AContentTransferEncoding, 'Check 7: Attachment Content Transfer Encoding changed from '+AContentTransferEncoding+' to '+Att2.ContentTransfer);
end;
finally
Msg.Free;
end;
sTemp := AContentTransferEncoding; if sTemp = '' then sTemp := 'default';
ShowMessage('Successfully completed test for '+sTemp+' encoding!');
end;
initialization
TIndyBox.RegisterBox(TSaveToLoadFromFileTests, 'ExtraHeaders', 'Message');
end.
|
{******************************************************************************}
{ }
{ Indy (Internet Direct) - Internet Protocols Simplified }
{ }
{ https://www.indyproject.org/ }
{ https://gitter.im/IndySockets/Indy }
{ }
{******************************************************************************}
{ }
{ This file is part of the Indy (Internet Direct) project, and is offered }
{ under the dual-licensing agreement described on the Indy website. }
{ (https://www.indyproject.org/license/) }
{ }
{ Copyright: }
{ (c) 1993-2020, Chad Z. Hower and the Indy Pit Crew. All rights reserved. }
{ }
{******************************************************************************}
{ }
{ Originally written by: Fabian S. Biehn }
{ fbiehn@aagon.com (German & English) }
{ }
{ Contributers: }
{ Here could be your name }
{ }
{******************************************************************************}
unit IdOpenSSLHeaders_cmserr;
interface
// Headers for OpenSSL 1.1.1
// cmserr.h
{$i IdCompilerDefines.inc}
uses
IdCTypes,
IdGlobal,
IdOpenSSLConsts;
const
//
// CMS function codes.
//
CMS_F_CHECK_CONTENT = 99;
CMS_F_CMS_ADD0_CERT = 164;
CMS_F_CMS_ADD0_RECIPIENT_KEY = 100;
CMS_F_CMS_ADD0_RECIPIENT_PASSWORD = 165;
CMS_F_CMS_ADD1_RECEIPTREQUEST = 158;
CMS_F_CMS_ADD1_RECIPIENT_CERT = 101;
CMS_F_CMS_ADD1_SIGNER = 102;
CMS_F_CMS_ADD1_SIGNINGTIME = 103;
CMS_F_CMS_COMPRESS = 104;
CMS_F_CMS_COMPRESSEDDATA_CREATE = 105;
CMS_F_CMS_COMPRESSEDDATA_INIT_BIO = 106;
CMS_F_CMS_COPY_CONTENT = 107;
CMS_F_CMS_COPY_MESSAGEDIGEST = 108;
CMS_F_CMS_DATA = 109;
CMS_F_CMS_DATAFINAL = 110;
CMS_F_CMS_DATAINIT = 111;
CMS_F_CMS_DECRYPT = 112;
CMS_F_CMS_DECRYPT_SET1_KEY = 113;
CMS_F_CMS_DECRYPT_SET1_PASSWORD = 166;
CMS_F_CMS_DECRYPT_SET1_PKEY = 114;
CMS_F_CMS_DIGESTALGORITHM_FIND_CTX = 115;
CMS_F_CMS_DIGESTALGORITHM_INIT_BIO = 116;
CMS_F_CMS_DIGESTEDDATA_DO_FINAL = 117;
CMS_F_CMS_DIGEST_VERIFY = 118;
CMS_F_CMS_ENCODE_RECEIPT = 161;
CMS_F_CMS_ENCRYPT = 119;
CMS_F_CMS_ENCRYPTEDCONTENT_INIT = 179;
CMS_F_CMS_ENCRYPTEDCONTENT_INIT_BIO = 120;
CMS_F_CMS_ENCRYPTEDDATA_DECRYPT = 121;
CMS_F_CMS_ENCRYPTEDDATA_ENCRYPT = 122;
CMS_F_CMS_ENCRYPTEDDATA_SET1_KEY = 123;
CMS_F_CMS_ENVELOPEDDATA_CREATE = 124;
CMS_F_CMS_ENVELOPEDDATA_INIT_BIO = 125;
CMS_F_CMS_ENVELOPED_DATA_INIT = 126;
CMS_F_CMS_ENV_ASN1_CTRL = 171;
CMS_F_CMS_FINAL = 127;
CMS_F_CMS_GET0_CERTIFICATE_CHOICES = 128;
CMS_F_CMS_GET0_CONTENT = 129;
CMS_F_CMS_GET0_ECONTENT_TYPE = 130;
CMS_F_CMS_GET0_ENVELOPED = 131;
CMS_F_CMS_GET0_REVOCATION_CHOICES = 132;
CMS_F_CMS_GET0_SIGNED = 133;
CMS_F_CMS_MSGSIGDIGEST_ADD1 = 162;
CMS_F_CMS_RECEIPTREQUEST_CREATE0 = 159;
CMS_F_CMS_RECEIPT_VERIFY = 160;
CMS_F_CMS_RECIPIENTINFO_DECRYPT = 134;
CMS_F_CMS_RECIPIENTINFO_ENCRYPT = 169;
CMS_F_CMS_RECIPIENTINFO_KARI_ENCRYPT = 178;
CMS_F_CMS_RECIPIENTINFO_KARI_GET0_ALG = 175;
CMS_F_CMS_RECIPIENTINFO_KARI_GET0_ORIG_ID = 173;
CMS_F_CMS_RECIPIENTINFO_KARI_GET0_REKS = 172;
CMS_F_CMS_RECIPIENTINFO_KARI_ORIG_ID_CMP = 174;
CMS_F_CMS_RECIPIENTINFO_KEKRI_DECRYPT = 135;
CMS_F_CMS_RECIPIENTINFO_KEKRI_ENCRYPT = 136;
CMS_F_CMS_RECIPIENTINFO_KEKRI_GET0_ID = 137;
CMS_F_CMS_RECIPIENTINFO_KEKRI_ID_CMP = 138;
CMS_F_CMS_RECIPIENTINFO_KTRI_CERT_CMP = 139;
CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT = 140;
CMS_F_CMS_RECIPIENTINFO_KTRI_ENCRYPT = 141;
CMS_F_CMS_RECIPIENTINFO_KTRI_GET0_ALGS = 142;
CMS_F_CMS_RECIPIENTINFO_KTRI_GET0_SIGNER_ID = 143;
CMS_F_CMS_RECIPIENTINFO_PWRI_CRYPT = 167;
CMS_F_CMS_RECIPIENTINFO_SET0_KEY = 144;
CMS_F_CMS_RECIPIENTINFO_SET0_PASSWORD = 168;
CMS_F_CMS_RECIPIENTINFO_SET0_PKEY = 145;
CMS_F_CMS_SD_ASN1_CTRL = 170;
CMS_F_CMS_SET1_IAS = 176;
CMS_F_CMS_SET1_KEYID = 177;
CMS_F_CMS_SET1_SIGNERIDENTIFIER = 146;
CMS_F_CMS_SET_DETACHED = 147;
CMS_F_CMS_SIGN = 148;
CMS_F_CMS_SIGNED_DATA_INIT = 149;
CMS_F_CMS_SIGNERINFO_CONTENT_SIGN = 150;
CMS_F_CMS_SIGNERINFO_SIGN = 151;
CMS_F_CMS_SIGNERINFO_VERIFY = 152;
CMS_F_CMS_SIGNERINFO_VERIFY_CERT = 153;
CMS_F_CMS_SIGNERINFO_VERIFY_CONTENT = 154;
CMS_F_CMS_SIGN_RECEIPT = 163;
CMS_F_CMS_SI_CHECK_ATTRIBUTES = 183;
CMS_F_CMS_STREAM = 155;
CMS_F_CMS_UNCOMPRESS = 156;
CMS_F_CMS_VERIFY = 157;
CMS_F_KEK_UNWRAP_KEY = 180;
//
// CMS reason codes.
//
CMS_R_ADD_SIGNER_ERROR = 99;
CMS_R_ATTRIBUTE_ERROR = 161;
CMS_R_CERTIFICATE_ALREADY_PRESENT = 175;
CMS_R_CERTIFICATE_HAS_NO_KEYID = 160;
CMS_R_CERTIFICATE_VERIFY_ERROR = 100;
CMS_R_CIPHER_INITIALISATION_ERROR = 101;
CMS_R_CIPHER_PARAMETER_INITIALISATION_ERROR = 102;
CMS_R_CMS_DATAFINAL_ERROR = 103;
CMS_R_CMS_LIB = 104;
CMS_R_CONTENTIDENTIFIER_MISMATCH = 170;
CMS_R_CONTENT_NOT_FOUND = 105;
CMS_R_CONTENT_TYPE_MISMATCH = 171;
CMS_R_CONTENT_TYPE_NOT_COMPRESSED_DATA = 106;
CMS_R_CONTENT_TYPE_NOT_ENVELOPED_DATA = 107;
CMS_R_CONTENT_TYPE_NOT_SIGNED_DATA = 108;
CMS_R_CONTENT_VERIFY_ERROR = 109;
CMS_R_CTRL_ERROR = 110;
CMS_R_CTRL_FAILURE = 111;
CMS_R_DECRYPT_ERROR = 112;
CMS_R_ERROR_GETTING_PUBLIC_KEY = 113;
CMS_R_ERROR_READING_MESSAGEDIGEST_ATTRIBUTE = 114;
CMS_R_ERROR_SETTING_KEY = 115;
CMS_R_ERROR_SETTING_RECIPIENTINFO = 116;
CMS_R_INVALID_ENCRYPTED_KEY_LENGTH = 117;
CMS_R_INVALID_KEY_ENCRYPTION_PARAMETER = 176;
CMS_R_INVALID_KEY_LENGTH = 118;
CMS_R_MD_BIO_INIT_ERROR = 119;
CMS_R_MESSAGEDIGEST_ATTRIBUTE_WRONG_LENGTH = 120;
CMS_R_MESSAGEDIGEST_WRONG_LENGTH = 121;
CMS_R_MSGSIGDIGEST_ERROR = 172;
CMS_R_MSGSIGDIGEST_VERIFICATION_FAILURE = 162;
CMS_R_MSGSIGDIGEST_WRONG_LENGTH = 163;
CMS_R_NEED_ONE_SIGNER = 164;
CMS_R_NOT_A_SIGNED_RECEIPT = 165;
CMS_R_NOT_ENCRYPTED_DATA = 122;
CMS_R_NOT_KEK = 123;
CMS_R_NOT_KEY_AGREEMENT = 181;
CMS_R_NOT_KEY_TRANSPORT = 124;
CMS_R_NOT_PWRI = 177;
CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE = 125;
CMS_R_NO_CIPHER = 126;
CMS_R_NO_CONTENT = 127;
CMS_R_NO_CONTENT_TYPE = 173;
CMS_R_NO_DEFAULT_DIGEST = 128;
CMS_R_NO_DIGEST_SET = 129;
CMS_R_NO_KEY = 130;
CMS_R_NO_KEY_OR_CERT = 174;
CMS_R_NO_MATCHING_DIGEST = 131;
CMS_R_NO_MATCHING_RECIPIENT = 132;
CMS_R_NO_MATCHING_SIGNATURE = 166;
CMS_R_NO_MSGSIGDIGEST = 167;
CMS_R_NO_PASSWORD = 178;
CMS_R_NO_PRIVATE_KEY = 133;
CMS_R_NO_PUBLIC_KEY = 134;
CMS_R_NO_RECEIPT_REQUEST = 168;
CMS_R_NO_SIGNERS = 135;
CMS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE = 136;
CMS_R_RECEIPT_DECODE_ERROR = 169;
CMS_R_RECIPIENT_ERROR = 137;
CMS_R_SIGNER_CERTIFICATE_NOT_FOUND = 138;
CMS_R_SIGNFINAL_ERROR = 139;
CMS_R_SMIME_TEXT_ERROR = 140;
CMS_R_STORE_INIT_ERROR = 141;
CMS_R_TYPE_NOT_COMPRESSED_DATA = 142;
CMS_R_TYPE_NOT_DATA = 143;
CMS_R_TYPE_NOT_DIGESTED_DATA = 144;
CMS_R_TYPE_NOT_ENCRYPTED_DATA = 145;
CMS_R_TYPE_NOT_ENVELOPED_DATA = 146;
CMS_R_UNABLE_TO_FINALIZE_CONTEXT = 147;
CMS_R_UNKNOWN_CIPHER = 148;
CMS_R_UNKNOWN_DIGEST_ALGORITHM = 149;
CMS_R_UNKNOWN_ID = 150;
CMS_R_UNSUPPORTED_COMPRESSION_ALGORITHM = 151;
CMS_R_UNSUPPORTED_CONTENT_TYPE = 152;
CMS_R_UNSUPPORTED_KEK_ALGORITHM = 153;
CMS_R_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM = 179;
CMS_R_UNSUPPORTED_RECIPIENTINFO_TYPE = 155;
CMS_R_UNSUPPORTED_RECIPIENT_TYPE = 154;
CMS_R_UNSUPPORTED_TYPE = 156;
CMS_R_UNWRAP_ERROR = 157;
CMS_R_UNWRAP_FAILURE = 180;
CMS_R_VERIFICATION_FAILURE = 158;
CMS_R_WRAP_ERROR = 159;
var
function ERR_load_CMS_strings: TIdC_INT;
implementation
end.
|
unit FormMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ImgList, Winapi.ShellAPI, IniFiles,
System.ImageList, FileCtrl;
type
TPaths = record
x264_8b, x264_10b, x265_8b, x265_10b, x265_12b, avs4x264mod, avs4x265, dgavcdec, mkvtoolnix, ffmpeg: string;
end;
TfrmMain = class(TForm)
edtInputFile: TLabeledEdit;
edtOutputFolder: TLabeledEdit;
btnOpenInput: TButton;
ilMain: TImageList;
btnOpenOutput: TButton;
rgEncoder: TRadioGroup;
edtOutputName: TLabeledEdit;
btnAutoName: TButton;
btnEncode: TButton;
mmoLog: TMemo;
grActions: TGroupBox;
chkIndex: TCheckBox;
chkEncode: TCheckBox;
chkMerge: TCheckBox;
chkShot: TCheckBox;
edtShift: TEdit;
chkRun: TCheckBox;
dlgFile: TOpenDialog;
mmoEncoderString: TMemo;
mmoAviSynth: TMemo;
lblCommandline: TLabel;
mmoBatch: TMemo;
mmoAvs: TMemo;
lblAviSynth: TLabel;
mmoShotFrames: TMemo;
lblScreenFrames: TLabel;
procedure FormCreate(Sender: TObject);
procedure btnEncodeClick(Sender: TObject);
procedure btnOpenOutputClick(Sender: TObject);
procedure btnAutoNameClick(Sender: TObject);
procedure btnOpenInputClick(Sender: TObject);
private
{ Private declarations }
Paths: TPaths;
procedure ReadOptions;
procedure CheckApps;
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
{$R *.dfm}
{ TfrmMain }
procedure TfrmMain.FormCreate(Sender: TObject);
begin
ReadOptions;
end;
procedure TfrmMain.ReadOptions;
var
IniFile: TIniFile;
begin
IniFile := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'paths.ini');
with IniFile do
begin
Paths.x264_8b := ReadString('paths', 'x264_8b', '');
Paths.x264_10b := ReadString('paths', 'x264_10b', '');
Paths.x265_8b := ReadString('paths', 'x265_8b', '');
Paths.x265_10b := ReadString('paths', 'x265_10b', '');
Paths.x265_12b := ReadString('paths', 'x265_12b', '');
Paths.avs4x264mod := ReadString('paths', 'avs4x264mod', '');
Paths.avs4x265 := ReadString('paths', 'avs4x265', '');
Paths.dgavcdec := ReadString('paths', 'dgavcdec', '');
Paths.mkvtoolnix := ReadString('paths', 'mkvtoolnix', '');
Paths.ffmpeg := ReadString('paths', 'ffmpeg', '');
end;
FreeAndNil(IniFile);
end;
procedure TfrmMain.btnEncodeClick(Sender: TObject);
const
Frames: array[0..19] of Integer = (31, 110, 131, 155, 242, 310, 314, 326, 355, 412, 653, 729, 748, 926, 1015, 1054, 1095, 1134, 1137, 1194);
var
InFile: string;
OutFolder: string;
OutName: string;
EncoderAvail: boolean;
AvsLine: string;
Frame: Integer;
Error: string;
begin
Error := '';
if FileExists(edtInputFile.Text) then
begin
if DirectoryExists(edtOutputFolder.Text) then
begin
InFile := edtInputFile.Text;
OutFolder := edtOutputFolder.Text;
OutName := edtOutputName.Text;
mmoBatch.Clear;
mmoAvs.Clear;
if (chkIndex.Checked) and (Error = '') then
begin
if FileExists(Paths.dgavcdec) then
begin
//ShellExecute(0, 'Open', PChar(ExtractFilePath(Application.ExeName) + 'DDS.exe'), nil, nil, SW_SHOW);
mmoBatch.Lines.Add(#34 + Paths.dgavcdec + #34 +' -i ' + #34 + InFile + #34 + ' -o ' + #34 + OutFolder + OutName + '.dga' + #34 + ' -e');
InFile := OutFolder + OutName + '.dga';
end
else
Error := 'DGAVCDec not found';
end;
if (chkEncode.Checked) and (Error = '') then
begin
case rgEncoder.ItemIndex of
0: EncoderAvail := FileExists(Paths.x264_8b) and FileExists(Paths.avs4x264mod);
1: EncoderAvail := FileExists(Paths.x264_10b) and FileExists(Paths.avs4x264mod);
2: EncoderAvail := FileExists(Paths.x265_8b) and FileExists(Paths.avs4x265);
3: EncoderAvail := FileExists(Paths.x265_10b) and FileExists(Paths.avs4x265);
4: EncoderAvail := FileExists(Paths.x265_12b) and FileExists(Paths.avs4x265);
end;
if EncoderAvail then
begin
case rgEncoder.ItemIndex of
0: AvsLine := #34 + Paths.avs4x264mod + #34 + ' --x264-binary ' + #34 + Paths.x264_8b + #34;
1: AvsLine := #34 + Paths.avs4x264mod + #34 + ' --x264-binary ' + #34 + Paths.x264_10b + #34;
2: AvsLine := #34 + Paths.avs4x265 + #34 + ' --x265-binary ' + #34 + Paths.x265_8b + #34;
3: AvsLine := #34 + Paths.avs4x265 + #34 + ' --x265-binary ' + #34 + Paths.x265_10b + #34;
4: AvsLine := #34 + Paths.avs4x265 + #34 + ' --x265-binary ' + #34 + Paths.x265_12b + #34;
end;
mmoBatch.Lines.Add(AvsLine + #32 + mmoEncoderString.Lines[0] + ' --output ' + #34 + OutFolder + OutName + '.mkv' + #34 + #32 + #34 + OutFolder + OutName + '.avs' + #34);
mmoAvs.Lines.Add('AVCSource(' + #34 + InFile + #34 + ')');
mmoAvs.Lines.Add(mmoAviSynth.Text);
//mmoAvs.Lines.Add('ConvertToYV12(matrix="rec709")');
mmoAvs.Lines.SaveToFile(OutFolder + OutName + '.avs');
InFile := OutFolder + OutName + '.mkv';
end
else
Error := 'Encoder "' + rgEncoder.Items[rgEncoder.ItemIndex] + '" not found';
end;
if (chkMerge.Checked) and (Error = '') then
begin
if FileExists(Paths.mkvtoolnix) then
begin
mmoBatch.Lines.Add(#34 + Paths.mkvtoolnix + #34 + ' --output ' + #34 + OutFolder + OutName + '.mkv' + #34 + ' --language 0:und ( ' + #34 + InFile + #34 + ' )');
InFile := OutFolder + OutName + '.mkv';
end
else
Error := 'MKVToolNix not found';
end;
if (chkShot.Checked) and (Error = '') then
begin
if FileExists(Paths.ffmpeg) then
begin
for Frame := Low(Frames) to High(Frames) do
mmoBatch.Lines.Add(#34 + Paths.ffmpeg + #34 + ' -i ' + #34 + InFile + #34 + ' -vf ' + #34 + 'select=gte(n\,' + IntToStr(Frames[Frame] + StrToInt(edtShift.Text)) + ')' + #34 + ' -vframes 1 ' + #34 + OutFolder + IntToStr(Frames[Frame]) + '.' + OutName + '.png' + #34);
end
else
Error := 'FFmpeg not found';
end;
mmoBatch.Lines.Add('pause');
mmoBatch.Lines.SaveToFile(OutFolder + OutName + '.bat');
//mmoLog.Text := mmoBatch.Text;
if Error = '' then
begin
mmoLog.Lines.Add('[DONE:] ' + 'Avisynth script ' + OutName + '.avs' + ' created');
mmoLog.Lines.Add('[DONE:] ' + 'Batch file ' + OutName + '.bat' + ' created');
if chkRun.Checked then
begin
ShellExecute(0, 'Open', PChar(OutFolder + OutName + '.bat'), nil, nil, SW_SHOW);
mmoLog.Lines.Add('[DONE:] ' + 'Batch file ' + OutName + '.bat' + ' executed');
end;
end
else
mmoLog.Lines.Add('[ERROR:] ' + Error + '!');
end
else
Error := 'Output folder not exist';
end
else
Error := 'Input file not exist';
end;
procedure TfrmMain.btnOpenInputClick(Sender: TObject);
begin
if DirectoryExists(ExtractFilePath(edtInputFile.Text)) then
dlgFile.InitialDir := ExtractFilePath(edtInputFile.Text);
if dlgFile.Execute() then
begin
edtInputFile.Text := dlgFile.FileName;
end;
end;
procedure TfrmMain.btnOpenOutputClick(Sender: TObject);
var
Dir: string;
begin
if DirectoryExists(edtOutputFolder.Text) then
Dir := edtOutputFolder.Text
else
Dir := '';
if SelectDirectory('Select output folder', '', Dir, [sdNewUI, sdNewFolder]) then
edtOutputFolder.Text := IncludeTrailingPathDelimiter(Dir);
end;
procedure TfrmMain.btnAutoNameClick(Sender: TObject);
begin
ShowMessage('');
end;
procedure TfrmMain.CheckApps;
begin
//
end;
end.
|
unit UPrefAppAutoUpdate;
{ ClickForms Application }
{ Bradford Technologies, Inc. }
{ All Rights Reserved }
{ Source Code Copyrighted © 1998-2011 by Bradford Technologies, Inc. }
interface
uses
Classes,
Controls,
ExtCtrls,
Forms,
StdCtrls,
UContainer,
UGlobals;
type
TPrefAutoUpdateFrame = class(TFrame)
chkEnableAutoUpdates: TCheckBox;
pnlTitle: TPanel;
private
FApplied_EnableAutomaticUpdates: Boolean;
public
constructor CreateFrame(AOwner: TComponent; ADoc: TContainer);
procedure LoadPrefs;
procedure SavePrefs;
procedure ApplyPreferences;
end;
implementation
uses
UAutoUpdateForm,
UMain;
{$R *.dfm}
constructor TPrefAutoUpdateFrame.CreateFrame(AOwner: TComponent; ADoc: TContainer);
begin
inherited Create(AOwner);
LoadPrefs;
end;
procedure TPrefAutoUpdateFrame.LoadPrefs;
begin
FApplied_EnableAutomaticUpdates := appPref_EnableAutomaticUpdates;
chkEnableAutoUpdates.Checked := FApplied_EnableAutomaticUpdates;
end;
procedure TPrefAutoUpdateFrame.SavePrefs;
begin
appPref_EnableAutomaticUpdates := chkEnableAutoUpdates.Checked;
ApplyPreferences;
end;
procedure TPrefAutoUpdateFrame.ApplyPreferences;
begin
if (FApplied_EnableAutomaticUpdates <> chkEnableAutoUpdates.Checked) then
begin
FApplied_EnableAutomaticUpdates := chkEnableAutoUpdates.Checked;
if FApplied_EnableAutomaticUpdates then
begin
TAutoUpdateForm.Updater.OnUpdatesChecked := Main.ShowAvailableUpdates;
TAutoUpdateForm.Updater.CheckForUpdates(True);
end
else
TAutoUpdateForm.Updater.Reset;
end;
end;
end.
|
unit Main;
interface
uses
CTmscorlib,
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
editSource: TEdit;
memoOutput: TMemo;
editPassword: TEdit;
butnEncrypt: TButton;
Label1: TLabel;
Label2: TLabel;
procedure butnEncryptClick(Sender: TObject);
private
public
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.butnEncryptClick(Sender: TObject);
// Loosely translated from C# example at:
// http://www.codeproject.com/KB/security/DotNetCrypto.aspx
var
xBytes: ByteArray;
xPDBBytes: ByteArray;
xPDB: PasswordDeriveBytes;
xCS: CryptoStream;
xMS: MemoryStream;
xAlg: Rijndael;
xEncrypted: ByteArray;
begin
xBytes := Encoding.Unicode.GetBytes(editSource.Text); try
//TODO: Allow transfer from a Delphi array, and pass an open array
xPDBBytes := ByteArray.Create(13); try
xPDBBytes[0] := $49;
xPDBBytes[1] := $76;
xPDBBytes[2] := $61;
xPDBBytes[3] := $6e;
xPDBBytes[4] := $20;
xPDBBytes[5] := $4d;
xPDBBytes[6] := $65;
xPDBBytes[7] := $64;
xPDBBytes[8] := $76;
xPDBBytes[9] := $65;
xPDBBytes[10] := $64;
xPDBBytes[11] := $65;
xPDBBytes[12] := $76;
xPDB := PasswordDeriveBytes.Create(editPassword.Text, xPDBBytes); try
xMS := MemoryStream.Create(); try
xAlg := Rijndael.Create1(); try
xAlg.Key := xPDB.GetBytes(32);
xAlg.IV := xPDB.GetBytes(16);
//TODO: Document why we have to cast xMS
//and why in the future it will go away
xCS := CryptoStream.Create(Stream(xMS), xAlg.CreateEncryptor()
, CryptoStreamMode.Write); try
xCS.Write(xBytes, 0, xBytes.Length);
xCS.Close();
finally xCS.Free; end;
finally xAlg.Free; end;
xEncrypted := xMS.ToArray(); try
memoOutput.Lines.Text := Convert.ToBase64String(xEncrypted);
finally xEncrypted.Free; end;
finally xMS.Free; end;
finally xPDB.Free; end;
finally xPDBBytes.Free; end;
finally xBytes.Free; end;
end;
end.
|
unit SendTest;
interface
uses dbTest, dbMovementTest, ObjectTest;
type
TSendTest = class (TdbMovementTestNew)
published
procedure ProcedureLoad; override;
procedure Test; override;
end;
TSend = class(TMovementTest)
private
protected
function InsertDefault: integer; override;
public
function InsertUpdateMovementSend(Id: Integer; InvNumber: String;
OperDate: TDateTime; UnitFromId, UnitToId: Integer): integer;
constructor Create; override;
end;
implementation
uses UtilConst, UnitsTest, dbObjectTest, SysUtils,
Db, TestFramework, GoodsTest;
{ TSend }
constructor TSend.Create;
begin
inherited;
spInsertUpdate := 'gpInsertUpdate_Movement_Send';
spSelect := 'gpSelect_Movement_Send';
spGet := 'gpGet_Movement_Send';
end;
function TSend.InsertDefault: integer;
var Id: Integer;
InvNumber: String;
OperDate: TDateTime;
UnitID: Integer;
begin
Id:=0;
InvNumber:='1';
OperDate:= Date;
UnitId := TUnit.Create.GetDefault;
result := InsertUpdateMovementSend(Id, InvNumber, OperDate, UnitId, UnitId);
end;
function TSend.InsertUpdateMovementSend(Id: Integer; InvNumber: String; OperDate: TDateTime;
UnitFromId, UnitToId: Integer):Integer;
begin
FParams.Clear;
FParams.AddParam('ioId', ftInteger, ptInputOutput, Id);
FParams.AddParam('inInvNumber', ftString, ptInput, InvNumber);
FParams.AddParam('inOperDate', ftDateTime, ptInput, OperDate);
FParams.AddParam('inFromId', ftInteger, ptInput, UnitFromId);
FParams.AddParam('inToId', ftInteger, ptInput, UnitToId);
result := InsertUpdate(FParams);
end;
{ TSendTest }
procedure TSendTest.ProcedureLoad;
begin
ScriptDirectory := LocalProcedurePath + 'Movement\Send\';
inherited;
end;
procedure TSendTest.Test;
var
MovementSend: TSend;
Id: Integer;
begin
MovementSend := TSend.Create;
// создание документа
Id := MovementSend.InsertDefault;
try
// редактирование
finally
// удаление
DeleteMovement(Id);
end;
end;
{ TSendItem }
initialization
TestFramework.RegisterTest('Документы', TSendTest.Suite);
end.
|
unit CadastroTanque;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.ToolWin, Vcl.StdCtrls, Util, Tanque, TanqueBO;
type
TFormCadastroTanque = class(TForm)
ToolBar: TToolBar;
ToolButtonNovo: TToolButton;
ToolButton01: TToolButton;
ToolButtonSalvar: TToolButton;
ToolButtonCancelar: TToolButton;
ToolButton02: TToolButton;
ToolButtonPesquisar: TToolButton;
ToolButton03: TToolButton;
ToolButtonExcluir: TToolButton;
LabelCodigo: TLabel;
EditCodigo: TEdit;
LabelDescricao: TLabel;
EditDescricao: TEdit;
StatusBar: TStatusBar;
LabelTipoConbustivel: TLabel;
ComboBoxTipo: TComboBox;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure FormShow(Sender: TObject);
procedure ToolButtonNovoClick(Sender: TObject);
procedure ToolButtonSalvarClick(Sender: TObject);
procedure ToolButtonCancelarClick(Sender: TObject);
procedure ToolButtonPesquisarClick(Sender: TObject);
procedure ToolButtonExcluirClick(Sender: TObject);
private
UltimoIdVisualizado :Integer;
procedure ExibirUltimoRegistro;
procedure ExibirRegistro(Tanque: TTanque);
procedure SalvarTanque;
function ValidarGravacao:Boolean;
public
{ Public declarations }
end;
var
FormCadastroTanque: TFormCadastroTanque;
implementation
{$R *.dfm}
uses ConsultaPadrao, Principal;
procedure TFormCadastroTanque.ExibirRegistro(Tanque: TTanque);
begin
try
if (Tanque <> nil) then
begin
UltimoIdVisualizado := Tanque.Id;
EditCodigo.Text := IntToStr(Tanque.Id);
EditDescricao.Text := Tanque.Descricao;
case (Tanque.Tipo) of
Gasolina : ComboBoxTipo.ItemIndex := 1;
OleoDiesel : ComboBoxTipo.ItemIndex := 2;
end;
end
else
begin
ToolButtonNovo.Click();
end;
except on E: Exception do
begin
TUtil.Mensagem(e.Message);
end;
end;
end;
procedure TFormCadastroTanque.ExibirUltimoRegistro;
var
TanqueBO: TTanqueBO;
Tanque: TTanque;
begin
try
TanqueBO := TTanqueBO.Create();
Tanque := TanqueBO.UltimoTanque();
ExibirRegistro(Tanque);
FreeAndNil(Tanque);
FreeAndNil(TanqueBO);
except on E: Exception do
begin
TUtil.Mensagem(e.Message);
end;
end;
end;
procedure TFormCadastroTanque.FormClose(Sender: TObject; var Action: TCloseAction);
begin
try
Action := caFree;
except on E: Exception do
begin
TUtil.Mensagem(e.Message);
end;
end;
end;
procedure TFormCadastroTanque.FormDestroy(Sender: TObject);
begin
try
FormCadastroTanque := nil;
except on E: Exception do
begin
TUtil.Mensagem(e.Message);
end;
end;
end;
procedure TFormCadastroTanque.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
try
case (Key) of
VK_F2 : ToolButtonNovo.Click();
VK_F3 : ToolButtonSalvar.Click();
VK_F4 : ToolButtonCancelar.Click();
VK_F5 : ToolButtonPesquisar.Click();
VK_F6 : ToolButtonExcluir.Click();
VK_ESCAPE : Close;
end;
except on E: Exception do
begin
TUtil.Mensagem(e.Message);
end;
end;
end;
procedure TFormCadastroTanque.FormShow(Sender: TObject);
begin
try
ExibirUltimoRegistro();
except on E: Exception do
begin
TUtil.Mensagem(e.Message);
end;
end;
end;
procedure TFormCadastroTanque.SalvarTanque;
var
TanqueBO: TTanqueBO;
Tanque: TTanque;
begin
try
Tanque := TTanque.Create;
if (Trim(EditCodigo.Text) = '') then
begin
Tanque.Id := 0;
end
else
begin
Tanque.Id := StrToInt(Trim(EditCodigo.Text));
end;
Tanque.Descricao := Trim(EditDescricao.Text);
case (ComboBoxTipo.ItemIndex) of
1 : Tanque.Tipo := Gasolina;
2 : Tanque.Tipo := OleoDiesel;
end;
TanqueBO := TTanqueBO.Create;
TanqueBO.Salvar(Tanque);
FreeAndNil(TanqueBO);
FreeAndNil(Tanque);
except on E: Exception do
begin
TUtil.Mensagem(e.Message);
end;
end;
end;
procedure TFormCadastroTanque.ToolButtonCancelarClick(Sender: TObject);
var
TanqueBO: TTanqueBO;
Tanque: TTanque;
begin
try
TanqueBO := TTanqueBO.Create();
Tanque := TanqueBO.ObterTanquePorId(UltimoIdVisualizado);
ExibirRegistro(Tanque);
FreeAndNil(Tanque);
FreeAndNil(TanqueBO);
except on E: Exception do
begin
TUtil.Mensagem(e.Message);
end;
end;
end;
procedure TFormCadastroTanque.ToolButtonExcluirClick(Sender: TObject);
var
TanqueBO: TTanqueBO;
Tanque: TTanque;
begin
try
if (Trim(EditCodigo.Text) = '') then
begin
TUtil.Mensagem('Selecione um tanque para poder realizar a exclusão');
Exit;
end;
if not(TUtil.Confirmacao('Tem certeza que deseja excluir o tanque?')) then
begin
Exit;
end;
TanqueBO := TTanqueBO.Create();
Tanque := TTanque.Create();
Tanque.Id := StrToInt(Trim(EditCodigo.Text));
TanqueBO.Excluir(Tanque);
FreeAndNil(Tanque);
FreeAndNil(TanqueBO);
ExibirUltimoRegistro();
TUtil.Mensagem('Tanque excluido com sucesso.');
except on E: Exception do
begin
if (Pos('FK',UpperCase(E.Message)) > 0) then
begin
TUtil.Mensagem('O tanque não pode ser excluído pois o mesmo possui referencias.');
end
else
begin
TUtil.Mensagem(e.Message);
end;
end;
end;
end;
procedure TFormCadastroTanque.ToolButtonNovoClick(Sender: TObject);
begin
try
EditCodigo.Clear();
EditDescricao.Clear();
ComboBoxTipo.ItemIndex := 0;
except on E: Exception do
begin
TUtil.Mensagem(e.Message);
end;
end;
end;
procedure TFormCadastroTanque.ToolButtonPesquisarClick(Sender: TObject);
var
TanqueBO: TTanqueBO;
Tanque: TTanque;
begin
try
if (FormConsultaPadrao = nil) then
begin
Application.CreateForm(TFormConsultaPadrao, FormConsultaPadrao);
end;
FormConsultaPadrao.TipoConsulta := ConsultaTanque;
FormConsultaPadrao.ShowModal();
if (Trim(IdSelecionado) <> '') then
begin
TanqueBO := TTanqueBO.Create();
Tanque := TanqueBO.ObterTanquePorId(StrToInt(IdSelecionado));
ExibirRegistro(Tanque);
FreeAndNil(Tanque);
FreeAndNil(TanqueBO);
end;
except on E: Exception do
begin
TUtil.Mensagem(e.Message);
end;
end;
end;
procedure TFormCadastroTanque.ToolButtonSalvarClick(Sender: TObject);
begin
try
if not(ValidarGravacao()) then
begin
Exit;
end;
SalvarTanque();
if (Trim(EditCodigo.Text) = '') then
begin
ExibirUltimoRegistro();
end;
TUtil.Mensagem('Tanque gravado com sucesso.');
except on E: Exception do
begin
TUtil.Mensagem(e.Message);
end;
end;
end;
function TFormCadastroTanque.ValidarGravacao: Boolean;
begin
try
Result := False;
if (Trim(EditDescricao.Text) = '') then
begin
TUtil.Mensagem('Informe a descrição do tanque.');
EditDescricao.SetFocus;
Exit;
end;
if (ComboBoxTipo.ItemIndex = 0) then
begin
TUtil.Mensagem('Selecione o tipo de combustível do tanque.');
ComboBoxTipo.SetFocus;
Exit;
end;
Result := True;
except on E: Exception do
begin
TUtil.Mensagem(e.Message);
end;
end;
end;
end.
|
unit httpDll_TLB;
// ************************************************************************ //
// WARNING
// -------
// The types declared in this file were generated from data read from a
// Type Library. If this type library is explicitly or indirectly (via
// another type library referring to this type library) re-imported, or the
// 'Refresh' command of the Type Library Editor activated while editing the
// Type Library, the contents of this file will be regenerated and all
// manual modifications will be lost.
// ************************************************************************ //
// PASTLWTR : 1.2
// File generated on 2016/10/7 16:58:58 from Type Library described below.
// ************************************************************************ //
// Type Lib: D:\TynooProject\DephiProjects\sdk²âÊÔ¹¤¾ßdelphi-Huawei\httpDll.tlb (1)
// LIBID: {37A9865D-0B4A-442C-A699-8B7A12329664}
// LCID: 0
// Helpfile:
// HelpString:
// DepndLst:
// (1) v2.0 stdole, (C:\Windows\SysWOW64\stdole2.tlb)
// (2) v2.4 mscorlib, (C:\Windows\Microsoft.NET\Framework\v4.0.30319\mscorlib.tlb)
// Errors:
// Error creating palette bitmap of (ThttpDllClass) : Server mscoree.dll contains no icons
// ************************************************************************ //
// *************************************************************************//
// NOTE:
// Items guarded by $IFDEF_LIVE_SERVER_AT_DESIGN_TIME are used by properties
// which return objects that may need to be explicitly created via a function
// call prior to any access via the property. These items have been disabled
// in order to prevent accidental use from within the object inspector. You
// may enable them by defining LIVE_SERVER_AT_DESIGN_TIME or by selectively
// removing them from the $IFDEF blocks. However, such items must still be
// programmatically created via a method of the appropriate CoClass before
// they can be used.
{$TYPEDADDRESS OFF} // Unit must be compiled without type-checked pointers.
{$WARN SYMBOL_PLATFORM OFF}
{$WRITEABLECONST ON}
{$VARPROPSETTER ON}
interface
uses Windows, ActiveX, Classes, Graphics, mscorlib_TLB, OleServer, StdVCL, Variants;
// *********************************************************************//
// GUIDS declared in the TypeLibrary. Following prefixes are used:
// Type Libraries : LIBID_xxxx
// CoClasses : CLASS_xxxx
// DISPInterfaces : DIID_xxxx
// Non-DISP interfaces: IID_xxxx
// *********************************************************************//
const
// TypeLibrary Major and minor versions
httpDllMajorVersion = 1;
httpDllMinorVersion = 0;
LIBID_httpDll: TGUID = '{37A9865D-0B4A-442C-A699-8B7A12329664}';
IID_httpDllInterface: TGUID = '{CBB21C05-47D8-3A57-A9A9-3016EC822445}';
CLASS_httpDllClass: TGUID = '{0D5778C2-0656-361D-8FA3-AD8BA06FF61A}';
type
// *********************************************************************//
// Forward declaration of types defined in TypeLibrary
// *********************************************************************//
httpDllInterface = interface;
httpDllInterfaceDisp = dispinterface;
// *********************************************************************//
// Declaration of CoClasses defined in Type Library
// (NOTE: Here we map each CoClass to its Default Interface)
// *********************************************************************//
httpDllClass = httpDllInterface;
// *********************************************************************//
// Interface: httpDllInterface
// Flags: (4416) Dual OleAutomation Dispatchable
// GUID: {CBB21C05-47D8-3A57-A9A9-3016EC822445}
// *********************************************************************//
httpDllInterface = interface(IDispatch)
['{CBB21C05-47D8-3A57-A9A9-3016EC822445}']
function HttpPost(const url: WideString; const data: WideString): WideString; safecall;
function HttpGet(const url: WideString; const data: WideString): WideString; safecall;
end;
// *********************************************************************//
// DispIntf: httpDllInterfaceDisp
// Flags: (4416) Dual OleAutomation Dispatchable
// GUID: {CBB21C05-47D8-3A57-A9A9-3016EC822445}
// *********************************************************************//
httpDllInterfaceDisp = dispinterface
['{CBB21C05-47D8-3A57-A9A9-3016EC822445}']
function HttpPost(const url: WideString; const data: WideString): WideString; dispid 1610743808;
function HttpGet(const url: WideString; const data: WideString): WideString; dispid 1610743809;
end;
// *********************************************************************//
// The Class CohttpDllClass provides a Create and CreateRemote method to
// create instances of the default interface httpDllInterface exposed by
// the CoClass httpDllClass. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CohttpDllClass = class
class function Create: httpDllInterface;
class function CreateRemote(const MachineName: string): httpDllInterface;
end;
// *********************************************************************//
// OLE Server Proxy class declaration
// Server Object : ThttpDllClass
// Help String :
// Default Interface: httpDllInterface
// Def. Intf. DISP? : No
// Event Interface:
// TypeFlags : (2) CanCreate
// *********************************************************************//
{$IFDEF LIVE_SERVER_AT_DESIGN_TIME}
ThttpDllClassProperties = class;
{$ENDIF}
ThttpDllClass = class(TOleServer)
private
FIntf: httpDllInterface;
{$IFDEF LIVE_SERVER_AT_DESIGN_TIME}
FProps: ThttpDllClassProperties;
function GetServerProperties: ThttpDllClassProperties;
{$ENDIF}
function GetDefaultInterface: httpDllInterface;
protected
procedure InitServerData; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Connect; override;
procedure ConnectTo(svrIntf: httpDllInterface);
procedure Disconnect; override;
function HttpPost(const url: WideString; const data: WideString): WideString;
function HttpGet(const url: WideString; const data: WideString): WideString;
property DefaultInterface: httpDllInterface read GetDefaultInterface;
published
{$IFDEF LIVE_SERVER_AT_DESIGN_TIME}
property Server: ThttpDllClassProperties read GetServerProperties;
{$ENDIF}
end;
{$IFDEF LIVE_SERVER_AT_DESIGN_TIME}
// *********************************************************************//
// OLE Server Properties Proxy Class
// Server Object : ThttpDllClass
// (This object is used by the IDE's Property Inspector to allow editing
// of the properties of this server)
// *********************************************************************//
ThttpDllClassProperties = class(TPersistent)
private
FServer: ThttpDllClass;
function GetDefaultInterface: httpDllInterface;
constructor Create(AServer: ThttpDllClass);
protected
public
property DefaultInterface: httpDllInterface read GetDefaultInterface;
published
end;
{$ENDIF}
procedure Register;
resourcestring
dtlServerPage = 'ActiveX';
dtlOcxPage = 'ActiveX';
implementation
uses ComObj;
class function CohttpDllClass.Create: httpDllInterface;
begin
Result := CreateComObject(CLASS_httpDllClass) as httpDllInterface;
end;
class function CohttpDllClass.CreateRemote(const MachineName: string): httpDllInterface;
begin
Result := CreateRemoteComObject(MachineName, CLASS_httpDllClass) as httpDllInterface;
end;
procedure ThttpDllClass.InitServerData;
const
CServerData: TServerData = (
ClassID: '{0D5778C2-0656-361D-8FA3-AD8BA06FF61A}';
IntfIID: '{CBB21C05-47D8-3A57-A9A9-3016EC822445}';
EventIID: '';
LicenseKey: nil;
Version: 500);
begin
ServerData := @CServerData;
end;
procedure ThttpDllClass.Connect;
var
punk: IUnknown;
begin
if FIntf = nil then
begin
punk := GetServer;
Fintf := punk as httpDllInterface;
end;
end;
procedure ThttpDllClass.ConnectTo(svrIntf: httpDllInterface);
begin
Disconnect;
FIntf := svrIntf;
end;
procedure ThttpDllClass.DisConnect;
begin
if Fintf <> nil then
begin
FIntf := nil;
end;
end;
function ThttpDllClass.GetDefaultInterface: httpDllInterface;
begin
if FIntf = nil then
Connect;
Assert(FIntf <> nil, 'DefaultInterface is NULL. Component is not connected to Server. You must call ''Connect'' or ''ConnectTo'' before this operation');
Result := FIntf;
end;
constructor ThttpDllClass.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
{$IFDEF LIVE_SERVER_AT_DESIGN_TIME}
FProps := ThttpDllClassProperties.Create(Self);
{$ENDIF}
end;
destructor ThttpDllClass.Destroy;
begin
{$IFDEF LIVE_SERVER_AT_DESIGN_TIME}
FProps.Free;
{$ENDIF}
inherited Destroy;
end;
{$IFDEF LIVE_SERVER_AT_DESIGN_TIME}
function ThttpDllClass.GetServerProperties: ThttpDllClassProperties;
begin
Result := FProps;
end;
{$ENDIF}
function ThttpDllClass.HttpPost(const url: WideString; const data: WideString): WideString;
begin
Result := DefaultInterface.HttpPost(url, data);
end;
function ThttpDllClass.HttpGet(const url: WideString; const data: WideString): WideString;
begin
Result := DefaultInterface.HttpGet(url, data);
end;
{$IFDEF LIVE_SERVER_AT_DESIGN_TIME}
constructor ThttpDllClassProperties.Create(AServer: ThttpDllClass);
begin
inherited Create;
FServer := AServer;
end;
function ThttpDllClassProperties.GetDefaultInterface: httpDllInterface;
begin
Result := FServer.DefaultInterface;
end;
{$ENDIF}
procedure Register;
begin
RegisterComponents(dtlServerPage, [ThttpDllClass]);
end;
end.
|
{
Функции регистрации объектов источников данных
Версия: 0.0.4.1
}
unit reg_data_ctrl;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,
obj_proto, dictionary;
{
Функция создания объекта контроллера данных по имени типа
ВНИМАНИЕ! После создания нового типа контроллера данных необходимо
прописать блок создания объекта по наименованию типа.
@param oParent Родительский объект
@param sTypeName Наименование типа источника/контроллера данных. Прописывается в INI файле в секции контроллера данных параметр 'type'
@param Properties Словарь свойств
@return Созданный объект. Необходимо для использования сделать преобразование типа
}
function CreateRegDataCtrl(oParent: TObject; sTypeName: AnsiString; Properties: TStrDictionary=nil): TICObjectProto;
{
Функция создания объекта контроллера данных по имени типа
ВНИМАНИЕ! После создания нового типа контроллера данных необходимо
прописать блок создания объекта по наименованию типа.
@param oParent Родительский объект
@param sTypeName Наименование типа источника/контроллера данных. Прописывается в INI файле в секции контроллера данных параметр 'type'
@param Args Массив свойств
@return Созданный объект. Необходимо для использования сделать преобразование типа
}
function CreateRegDataCtrlArgs(oParent: TObject; sTypeName: AnsiString; const aArgs: Array Of Const): TICObjectProto;
implementation
uses
log,
// Компоненты - источники данных
opc_da_node, opc_hda_node, opc_wt_hda_node,
opc_server_node; // Поддержка старого типа узла (для совместимости)
{
Функция создания объекта контроллера данных по имени типа.
ВНИМАНИЕ! После создания нового типа контроллера данных необходимо
прописать блок создания объекта по наименованию типа.
@param sTypeName Наименование типа. Прописывается в INI файле в секции контроллера данных параметр 'type'
}
function CreateRegDataCtrl(oParent: TObject; sTypeName: AnsiString; Properties: TStrDictionary): TICObjectProto;
begin
if sTypeName = opc_da_node.OPC_DA_NODE_TYPE then
begin
{ Создание и инициализация OPC DA сервера }
Result := opc_da_node.TICOPCDANode.Create;
end
else if sTypeName = opc_hda_node.OPC_HDA_NODE_TYPE then
begin
{ Создание и инициализация OPC DA сервера }
Result := opc_hda_node.TICOPCHDANode.Create;
end
else if sTypeName = opc_wt_hda_node.OPC_WT_HDA_NODE_TYPE then
begin
{ Создание и инициализация OPC DA сервера }
Result := opc_wt_hda_node.TICWtOPCHDANode.Create;
end
else if sTypeName = opc_server_node.OPC_SRV_NODE_TYPE then
begin
{ Создание и инициализация OPC сервера }
Result := opc_server_node.TICOPCServerNode.Create;
end
else
begin
log.WarningMsgFmt('Не поддерживаемый тип объекта контроллера данных <%s>', [sTypeName]);
Result := nil;
end;
if Result <> nil then
begin
if oParent <> nil then
Result.SetParent(oParent);
if Properties <> nil then
Result.SetProperties(Properties);
end;
end;
{
Функция создания объекта контроллера данных по имени типа.
ВНИМАНИЕ! После создания нового типа контроллера данных необходимо
прописать блок создания объекта по наименованию типа.
@param sTypeName Наименование типа. Прописывается в INI файле в секции контроллера данных параметр 'type'
}
function CreateRegDataCtrlArgs(oParent: TObject; sTypeName: AnsiString; const aArgs: Array Of Const): TICObjectProto;
begin
if sTypeName = opc_da_node.OPC_DA_NODE_TYPE then
begin
{ Создание и инициализация OPC DA сервера }
Result := opc_da_node.TICOPCDANode.Create;
end
else if sTypeName = opc_hda_node.OPC_HDA_NODE_TYPE then
begin
{ Создание и инициализация OPC HDA сервера }
Result := opc_hda_node.TICOPCHDANode.Create;
end
else if sTypeName = opc_wt_hda_node.OPC_WT_HDA_NODE_TYPE then
begin
{ Создание и инициализация OPC HDA сервера }
Result := opc_wt_hda_node.TICWtOPCHDANode.Create;
end
else if sTypeName = opc_server_node.OPC_SRV_NODE_TYPE then
begin
{ Создание и инициализация OPC сервера }
Result := opc_server_node.TICOPCServerNode.Create;
end
else
Result := nil;
if Result = nil then
begin
log.WarningMsgFmt('Не поддерживаемый тип объекта контроллера данных <%s>', [sTypeName]);
end
else
begin
if oParent <> nil then
Result.SetParent(oParent);
Result.SetPropertiesArray(aArgs);
end;
end;
end.
|
unit DW.OSDevice.Win;
{*******************************************************}
{ }
{ Kastri Free }
{ }
{ DelphiWorlds Cross-Platform Library }
{ }
{*******************************************************}
{$I DW.GlobalDefines.inc}
interface
uses
// DW
DW.FileVersionInfo.Win;
type
/// <remarks>
/// DO NOT ADD ANY FMX UNITS TO THESE FUNCTIONS
/// </remarks>
TPlatformOSDevice = class(TObject)
private
class var FFileVersionInfo: TFileVersionInfo;
class destructor DestroyClass;
class function GetFileVersionInfo: TFileVersionInfo; static;
public
class function GetDeviceName: string; static;
class function GetPackageBuild: string; static;
class function GetPackageID: string; static;
class function GetPackageVersion: string; static;
class function GetUniqueDeviceID: string; static;
class function IsTouchDevice: Boolean; static;
end;
implementation
uses
// RTL
System.SysUtils, System.Win.Registry,
// Windows
Winapi.Windows;
const
cMicrosoftCryptographyKey = 'SOFTWARE\Microsoft\Cryptography';
cMachineGuidValueName = 'MachineGuid';
{ TPlatformOSDevice }
class destructor TPlatformOSDevice.DestroyClass;
begin
FFileVersionInfo.Free;
end;
class function TPlatformOSDevice.GetDeviceName: string;
var
LComputerName: array[0..MAX_COMPUTERNAME_LENGTH] of Char;
LSize: DWORD;
begin
LSize := Length(LComputerName);
if GetComputerName(LComputerName, LSize) then
SetString(Result, LComputerName, LSize)
else
Result := '';
end;
class function TPlatformOSDevice.GetFileVersionInfo: TFileVersionInfo;
begin
if FFileVersionInfo = nil then
FFileVersionInfo := TFileVersionInfo.Create(GetModuleName(HInstance));
Result := FFileVersionInfo;
end;
class function TPlatformOSDevice.GetPackageID: string;
begin
Result := GetFileVersionInfo.InternalName;
end;
class function TPlatformOSDevice.GetPackageVersion: string;
var
LVersion: TLongVersion;
begin
LVersion := GetFileVersionInfo.FileLongVersion;
Result := Format('%d.%d.%d', [LVersion.All[2], LVersion.All[1], LVersion.All[4]]);
end;
class function TPlatformOSDevice.GetPackageBuild: string;
begin
Result := GetFileVersionInfo.FileLongVersion.All[3].ToString;
end;
class function TPlatformOSDevice.GetUniqueDeviceID: string;
var
LRegistry: TRegistry;
LAccess: Cardinal;
begin
// **** BEWARE!!!! ****
// VM's that are clones will have identical IDs.
Result := '';
LAccess := KEY_READ;
if TOSVersion.Architecture = TOSVersion.TArchitecture.arIntelX86 then
LAccess := LAccess or KEY_WOW64_32KEY
else
LAccess := LAccess or KEY_WOW64_64KEY;
LRegistry := TRegistry.Create(LAccess);
try
LRegistry.RootKey := HKEY_LOCAL_MACHINE;
if LRegistry.OpenKey(cMicrosoftCryptographyKey, False) then
Result := LRegistry.ReadString(cMachineGuidValueName);
finally
LRegistry.Free;
end;
end;
class function TPlatformOSDevice.IsTouchDevice: Boolean;
var
LValue: Integer;
begin
LValue := GetSystemMetrics(SM_DIGITIZER);
Result := ((LValue and NID_READY) = NID_READY) and (((LValue and NID_MULTI_INPUT) = NID_MULTI_INPUT));
end;
end.
|
program fib (input, output) ;
function fibRek (inZahl : integer) : integer ;
begin
if inZahl = 0 then
fibRek := 0
else
if inZahl = 1 then
fibRek := 1
else
fibRek := fibRek(inZahl - 1) + fibRek(inZahl - 2)
end;
begin
write(fibRek(10))
end.
|
unit View.UserEdit;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, View.TemplateEdit, Data.DB,
JvComponentBase, JvFormPlacement, Vcl.StdCtrls, Vcl.ExtCtrls, JvExControls,
JvDBLookup, Vcl.Mask, Vcl.DBCtrls,
JvExMask, JvToolEdit, JvDBControls, Vcl.Buttons,
Vcl.Grids, Vcl.DBGrids, JvExDBGrids, JvDBGrid, Vcl.ComCtrls,
Spring.Data.ObjectDataset,
Model.LanguageDictionary,
Model.ProSu.Interfaces,
Model.ProSu.Provider,
Model.Declarations,
Model.FormDeclarations;
type
TUserEditForm = class(TTemplateEdit)
labelUsername: TLabel;
labelPassword: TLabel;
labelUserGuid: TLabel;
labelDocPassword: TLabel;
labelCompanyId: TLabel;
labelLocationId: TLabel;
labelMobilePhone: TLabel;
labelEmail: TLabel;
edUsername: TDBEdit;
edPassword: TDBEdit;
edDocPassword: TDBEdit;
edCompanyId: TJvDBLookupCombo;
edLocationId: TJvDBLookupCombo;
edMobilePhone: TDBEdit;
edEmail: TDBEdit;
edUserGuid: TJvDBComboEdit;
PageControl1: TPageControl;
tabGroups: TTabSheet;
tabRoles: TTabSheet;
tabPermissions: TTabSheet;
Panel1: TPanel;
JvDBGrid1: TJvDBGrid;
JvDBGrid2: TJvDBGrid;
Panel3: TPanel;
Splitter1: TSplitter;
btnAddGroup: TSpeedButton;
btnDeleteGroup: TSpeedButton;
labelGroups: TLabel;
labelGroupsOfUser: TLabel;
JvDBGrid3: TJvDBGrid;
Panel4: TPanel;
btnAddRole: TSpeedButton;
btnDeleteRole: TSpeedButton;
JvDBGrid4: TJvDBGrid;
Panel5: TPanel;
labelRoles: TLabel;
labelRolesOfUser: TLabel;
grd: TJvDBGrid;
Panel6: TPanel;
btnAddPermission: TSpeedButton;
btnDeletePermission: TSpeedButton;
JvDBGrid6: TJvDBGrid;
Panel7: TPanel;
labelPermissions: TLabel;
labelPermissionsOfUser: TLabel;
dsCompany: TDataSource;
dsLocation: TDataSource;
dsGroupsSource: TDataSource;
dsRolesSource: TDataSource;
dsPermissionsSource: TDataSource;
dsGroupsTarget: TDataSource;
dsRolesTarget: TDataSource;
dsPermissionsTarget: TDataSource;
Splitter2: TSplitter;
Splitter3: TSplitter;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure edUserGuidButtonClick(Sender: TObject);
procedure btnAddGroupClick(Sender: TObject);
procedure btnDeleteGroupClick(Sender: TObject);
procedure btnAddRoleClick(Sender: TObject);
procedure btnDeleteRoleClick(Sender: TObject);
procedure btnAddPermissionClick(Sender: TObject);
procedure btnDeletePermissionClick(Sender: TObject);
procedure edCompanyIdChange(Sender: TObject);
private
fCompanyDataset : TObjectDataset;
fLocationDataset : TObjectDataset;
fGroupsTargetDS, fGroupsSourceDS : TObjectDataset;
fRolesTargetDS, fRolesSourceDS : TObjectDataset;
fPermissionsTargetDS, fPermissionsSourceDS : TObjectDataset;
procedure EnableSourceDS(aSourceDS: TDataset; aId: Integer; aIdField: String);
procedure DisableTargetDS(aTargetDS : TDataset);
procedure AddTargetDisableSourceDS(aSourceDS, aTargetDS: TDataset;
aId: Integer; aIdField, aNameField, aManagerField, aIsUserField, aRUGField : String);
protected
procedure FormLoaded; override;
class function RequiredPermission(cmd: TBrowseFormCommand) : string; override;
procedure AfterPost(DataSet: TDataSet); override;
public
end;
var
UserEditForm: TUserEditForm;
implementation
uses
Spring.Collections,
Spring.Persistence.Mapping.Attributes,
MainDM,
Spring.Persistence.Criteria.Interfaces,
Spring.Persistence.Criteria.Restrictions,
Spring.Persistence.Criteria.OrderBy,
Model.MosObjectDataset,
Spring.Persistence.Core.Interfaces,
Model.Interfaces,
Model.GroupUser,
Model.RoleUserGroup,
Model.RoleUserGroupPermission;
{$R *.dfm}
procedure TUserEditForm.AfterPost(DataSet: TDataSet);
var
agumdl : IGroupUserModelInterface;
aRugmdl : IRoleUserGroupModelInterface;
aRugpmdl : IRoleUserGroupPermissionModelInterface;
begin
agumdl := CreateGroupUserModelClass;
agumdl.UpdateGroupUserList(DataSource1.DataSet.FieldByName('UserId').AsInteger, -1, fGroupsTargetDS); //.DataList as IList<TGroupUser>);
aRugmdl := CreateRoleUserGroupModelClass;
aRugmdl.UpdateRoleUserGroupList(-1, DataSource1.DataSet.FieldByName('UserId').AsInteger, -1, fRolesTargetDS.DataList as IList<TRoleUserGroup>);
aRugpmdl := CreateRoleUserGroupPermissionModelClass;
aRugpmdl.UpdateRoleUserGroupList(-1, DataSource1.DataSet.FieldByName('UserId').AsInteger, -1, -1, fPermissionsTargetDS.DataList as IList<TRoleUserGroupPermission>);
end;
procedure TUserEditForm.EnableSourceDS(aSourceDS : TDataset; aId : Integer; aIdField : String);
var
prefiltered : boolean;
begin
aSourceDS.DisableControls;
prefiltered := fRolesSourceDS.Filtered;
try
aSourceDS.Filtered := false;
if aSourceDS.Locate(aIdField, IntToStr(aId), []) then
begin
aSourceDS.Edit;
aSourceDS.FieldByName('IsDeleted').AsBoolean := False;
aSourceDS.Post;
end;
finally
aSourceDS.Filtered := prefiltered;
aSourceDS.EnableControls;
aSourceDS.Locate(aIdField, IntToStr(aId), []);
end;
end;
procedure TUserEditForm.DisableTargetDS(aTargetDS : TDataset);
begin
aTargetDS.Edit;
try
aTargetDS.FindField('IsDeleted').AsBoolean := True;
aTargetDS.Post;
except
on e:Exception do
begin
aTargetDS.Cancel;
ShowMessage(e.Message);
end;
end;
if not aTargetDS.Filtered then
begin
aTargetDS.Filter := 'IsDeleted = 0 ';
aTargetDS.Filtered := True;
end;
end;
procedure TUserEditForm.AddTargetDisableSourceDS(aSourceDS : TDataset; aTargetDS : TDataset;
aId : Integer; aIdField, aNameField, aManagerField, aIsUserField, aRUGField : String);
var
prefiltered : boolean;
begin
if aSourceDS.RecordCount<0 then
Exit;
aSourceDS.DisableControls;
prefiltered := aSourceDS.Filtered;
aSourceDS.Filtered := False;
try
if not aSourceDS.Locate(aIdField, IntToStr(aId), []) then
raise Exception.Create(MessageDictionary.GetMessage('SSeriousUnknownError'));
if aTargetDS.Locate(aIdField, IntToStr(aId), []) then
begin
aTargetDS.Edit;
aTargetDS.FieldByName('IsDeleted').AsBoolean := False;
aTargetDS.Post;
end
else
begin
aTargetDS.Append;
aTargetDS.FieldByName(aIdField).AsInteger := aSourceDS.FieldByName(aIdField).AsInteger;
aTargetDS.FieldByName('UserId').AsInteger := DataSource1.DataSet.FieldByName('UserId').AsInteger;
if aIsUserField<>'' then
aTargetDS.FieldByName(aIsUserField).AsBoolean := True;
if aRUGField<>'' then
aTargetDS.FieldByName(aRUGField).AsInteger := 2;
if aManagerField<>'' then
aTargetDS.FieldByName(aManagerField).AsBoolean := False;
aTargetDS.FieldByName(aNameField).AsString := aSourceDS.FieldByName(aNameField).AsString;
aTargetDS.Post;
end;
aSourceDS.Edit;
aSourceDS.FieldByName('IsDeleted').AsBoolean := True;
aSourceDS.Post;
aSourceDS.Filter := 'IsDeleted = 0 ';
aSourceDS.Filtered := True;
finally
aSourceDS.Filtered := prefiltered;
aSourceDS.EnableControls;
end;
end;
procedure TUserEditForm.btnAddGroupClick(Sender: TObject);
begin
if fGroupsSourceDS.RecordCount<=0 then
Exit;
AddTargetDisableSourceDS(fGroupsSourceDS, fGroupsTargetDS, fGroupsSourceDS.FieldByName('GroupId').AsInteger,
'GroupId', 'GroupName', 'GroupManager', '', '');
end;
procedure TUserEditForm.btnAddPermissionClick(Sender: TObject);
//var
//prefiltered : boolean;
begin
if fPermissionsSourceDS.RecordCount<=0 then
Exit;
AddTargetDisableSourceDS(fPermissionsSourceDS, fPermissionsTargetDS, fPermissionsSourceDS.FieldByName('PermissionId').AsInteger,
'PermissionId', 'PermissionName', '', '', 'RUG');
end;
procedure TUserEditForm.btnAddRoleClick(Sender: TObject);
var
prefiltered : boolean;
begin
if fRolesSourceDS.RecordCount<=0 then
Exit;
AddTargetDisableSourceDS(fRolesSourceDS, fRolesTargetDS, fRolesSourceDS.FieldByName('RoleId').AsInteger,
'RoleId', 'RoleName', '', 'IsUser', '');
end;
procedure TUserEditForm.btnDeleteGroupClick(Sender: TObject);
begin
if fGroupsTargetDS.RecordCount<=0 then
Exit;
EnableSourceDS(fGroupsSourceDS, fGroupsTargetDS.FieldByName('GroupId').AsInteger, 'GroupId');
DisableTargetDS(fGroupsTargetDS);
end;
procedure TUserEditForm.btnDeletePermissionClick(Sender: TObject);
begin
if fPermissionsTargetDS.RecordCount<=0 then
Exit;
EnableSourceDS(fPermissionsSourceDS, fPermissionsTargetDS.FieldByName('PermissionId').AsInteger, 'PermissionId');
DisableTargetDS(fPermissionsTargetDS);
end;
procedure TUserEditForm.btnDeleteRoleClick(Sender: TObject);
begin
if fRolesTargetDS.RecordCount<=0 then
Exit;
EnableSourceDS(fRolesSourceDS,fRolesTargetDS.FieldByName('RoleId').AsInteger, 'RoleId');
DisableTargetDS(fRolesTargetDS);
end;
procedure TUserEditForm.edCompanyIdChange(Sender: TObject);
begin
if DataSource1.DataSet.FieldByName('CompanyId').IsNull then
begin
fLocationDataset.Filter := '';
fLocationDataset.Filtered := False;
end
else
begin
fLocationDataset.Filter := 'CompanyId='+DataSource1.DataSet.FieldByName('CompanyId').AsString;
fLocationDataset.Filtered := True;
end;
end;
procedure TUserEditForm.edUserGuidButtonClick(Sender: TObject);
var
guid : TGUID;
begin
CreateGUID(guid);
edUserGuid.Text := GUIDToString(guid);
end;
procedure TUserEditForm.FormCreate(Sender: TObject);
begin
inherited;
Caption := ComponentDictionary.GetText(Self.ClassName, 'Caption');
labelUsername.Caption := ComponentDictionary.GetText(ClassName, 'labelUsername.Caption');
labelPassword.Caption := ComponentDictionary.GetText(ClassName, 'labelPassword.Caption');
labelUserGuid.Caption := ComponentDictionary.GetText(ClassName, 'labelUserGuid.Caption');
labelDocPassword.Caption := ComponentDictionary.GetText(ClassName, 'labelDocPassword.Caption');
labelCompanyId.Caption := ComponentDictionary.GetText(ClassName, 'labelCompanyId.Caption');
labelLocationId.Caption := ComponentDictionary.GetText(ClassName, 'labelLocationId.Caption');
labelMobilePhone.Caption := ComponentDictionary.GetText(ClassName, 'labelMobilePhone.Caption');
labelEmail.Caption := ComponentDictionary.GetText(ClassName, 'labelEmail.Caption');
tabGroups.Caption := ComponentDictionary.GetText(ClassName, 'tabGroups.Caption');
tabRoles.Caption := ComponentDictionary.GetText(ClassName, 'tabRoles.Caption');
tabPermissions.Caption := ComponentDictionary.GetText(ClassName, 'tabPermissions.Caption');
end;
procedure TUserEditForm.FormDestroy(Sender: TObject);
begin
inherited;
fCompanyDataset.Free;
fLocationDataset.Free;
end;
procedure TUserEditForm.FormLoaded;
var
//il : IList<TGroupUserExt>;
aGuMdl : IGroupUserModelInterface;
aRugMdl : IRoleUserGroupModelInterface;
aRugPMdl : IRoleUserGroupPermissionModelInterface;
//aGroupModel : IGroupModelInterface;
UId : Integer;
begin
fCompanyDataset := TObjectDataset.Create(self);
fCompanyDataset.DataList := DMMain.Session.CreateCriteria<TCompany>.Add(Restrictions.NotEq('IsDeleted', -1)).ToList as IObjectList;
fCompanyDataset.Open;
dsCompany.DataSet := fCompanyDataset;
fLocationDataset := TObjectDataset.Create(self);
fLocationDataset .DataList := DMMain.Session.CreateCriteria<TLocation>.Add(Restrictions.NotEq('IsDeleted', -1)).ToList as IObjectList;
dsLocation.DataSet := fLocationDataset ;
fLocationDataset .Open;
edCompanyIdChange(nil);
if DataSource1.DataSet.State=dsInsert then
UId := -1
else
UId := DataSource1.DataSet.FieldByName('UserId').AsInteger;
fGroupsTargetDS := TObjectDataset.Create(self);
fGroupsTargetDS.DataList := DMMain.Session.CreateCriteria<TGroupUserExt>.Add(Restrictions.Eq('UserId', UId))
.Add(Restrictions.NotEq('IsDeleted', -1)).ToList as IObjectList;
{DMMain.Session.GetList<TGroupUserExt>('select GU.*, G.GroupName as GroupName from GroupUser as GU '+
'left join [Group] as G on (G.GroupId=GU.GroupId) '+
'where GU.UserId='+DataSource1.DataSet.FieldByName('UserId').AsString+' and GU.IsDeleted<>-1', []) as IObjectList;
}
dsGroupsTarget.Dataset := fGroupsTargetDS;
fGroupsTargetDS.Open;
fGroupsSourceDS := TObjectDataset.Create(self);
fGroupsSourceDS.DataList := DMMain.Session.CreateCriteria<TGroup>.Add(Restrictions.NotEq('IsDeleted', -1)).ToList as IObjectList;
dsGroupsSource.Dataset := fGroupsSourceDS;
fGroupsSourceDS.Open;
agumdl := CreateGroupUserModelClass;
if agumdl.GetDifference('Group', fGroupsSourceDS, 'Group', fGroupsTargetDS) then
begin
fGroupsSourceDS.Filter := 'IsDeleted = 0';
fGroupsSourceDS.Filtered := True;
end;
fGroupsSourceDS.First;
//==========================================================================
fRolesSourceDS := TObjectDataset.Create(self);
fRolesSourceDS.DataList := DMMain.Session.CreateCriteria<TRole>.Add(Restrictions.Eq('CompanyId', DMMain.Company.CompanyId))
.Add(Restrictions.NotEq('IsDeleted', -1)).ToList as IObjectList;
dsRolesSource.DataSet := fRolesSourceDS;
fRolesSourceDS.Open;
fRolesTargetDS := TObjectDataset.Create(self);
fRolesTargetDS.DataList := //DMMain.Session.GetList<TRoleUserGroup>.Add(Restrictions.Eq())
DMMain.Session.GetList<TRoleUserGroupExt>('select RUG.*, R.[RoleName] as [RoleName] from RoleUserGroup as RUG '+
'left join [Role] as R on (R.RoleId=RUG.RoleId) '+
'where RUG.UserId='+IntToStr(UId), []) as IObjectList;
dsRolesTarget.DataSet := fRolesTargetDS;
fRolesTargetDS.Open;
aRugMdl := CreateRoleUserGroupModelClass;
if aRugMdl.GetDifference('Role', fRolesSourceDS, 'Role', fRolesTargetDS) then
begin
fRolesSourceDS.Filter := 'IsDeleted = 0';
fRolesSourceDS.Filtered := True;
end;
fRolesSourceDS.First;
//=======================================================================
fPermissionsSourceDS := TObjectDataSet.Create(self);
fPermissionsSourceDS.DataList := DMMain.Session.CreateCriteria<TPermission>.Add(Restrictions.NotEq('IsDeleted', -1)).ToList as IObjectList;
dsPermissionsSource.DataSet := fPermissionsSourceDS;
fPermissionsSourceDS.Open;
fPermissionsTargetDS := TObjectDataSet.Create(self);
fPermissionsTargetDS.DataList := DMMain.Session.GetList<TRoleUserGroupPermissionExt>('Select RUGP.*, P.[PermissionName] as PermissionName from RoleUserGroupPermission as RUGP '+
'left join [Permission] as P on (P.PermissionId=RUGP.PermissionId) '+
'where RUGP.UserId='+IntToStr(UId), []) as IObjectList;
dsPermissionsTarget.DataSet := fPermissionsTargetDS;
fPermissionsTargetDS.Open;
aRugPMdl := CreateRoleUserGroupPermissionModelClass;
if aRugPMdl.GetDifference('Permission', fPermissionsSourceDS, 'Permission', fPermissionsTargetDS) then
begin
fPermissionsSourceDS.Filter := 'IsDeleted = 0';
fPermissionsSourceDS.Filtered := True;
end;
fPermissionsSourceDS.First;
end;
class function TUserEditForm.RequiredPermission(
cmd: TBrowseFormCommand): string;
begin
Result := '>????<';
case cmd of
efcmdAdd: Result := '102';
efcmdEdit: Result := '103';
efcmdDelete: Result := '104';
efcmdViewDetail: Result := '105';
end;
end;
end.
|
unit metadata;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, db, sqldb, DBGrids, Dialogs;
type
strings = array of string;
TColumnInfo = record
ColumnName: string;
ColumnCaption: string;
Reference: boolean;
ReferenceTable: string;
ReferenceName: string;
Size: integer;
FieldType: TFieldType;
end;
TColumnInfos = array of TColumnInfo;
TTableInfo = class
ColumnInfos: TColumnInfos;
TableCaption: string;
TableName: string;
constructor Create (aCaption, aName: string);
function GetColumnCaption: strings;
procedure SendQuery (SQLQuery: TSQLQuery);
procedure Show (SQLQuery: TSQLQuery; DBGrid: TDBGrid);
function CreateQuery: string;
//function GetTableName (aColumnName): string;
procedure SetCaptions (DBGrid: TDBGrid);
function AddColumn (aName, aCaption, aReferenceColumn: string;
aSize: integer; aFieldType: TFieldType):TTableInfo;
end;
//TTableInfos =
TListOfTable = class
TableInfos: array of TTableInfo;
constructor Create();
function AddTable (aCaption, aName: string): TTableInfo;
function GetTableCaption: strings;
end;
implementation
constructor TTableInfo.Create (aCaption, aName: string);
begin
TableCaption := aCaption;
TableName := aName;
end;
function TTableInfo.AddColumn(aName, aCaption, aReferenceColumn: string;
aSize: integer; aFieldType: TFieldType): TTableInfo;
begin
SetLength (ColumnInfos, length (ColumnInfos) + 1);
with ColumnInfos[high (ColumnInfos)] do begin
ColumnName := aName;
ColumnCaption := aCaption;
if (aReferenceColumn <> '') then Reference := true;
if (Reference) then begin
ReferenceName := aReferenceColumn;
ReferenceTable := Copy (aName, 1, length (aName) - 3) + 's';
end;
Size := aSize;
FieldType := aFieldType;
end;
Result := self;
end;
function TListOfTable.AddTable (aCaption, aName: string): TTableInfo;
begin
Result := TTableInfo.Create (aCaption, aName);
SetLength (TableInfos, length (TableInfos) + 1);
TableInfos[high (TableInfos)] := Result;
end;
constructor TListOfTable.Create ();
begin
AddTable ('Преподаватели', 'Professors').
AddColumn ('Name', 'Преподаватель', '', 200, ftString);
AddTable ('Предметы', 'Subjects').
AddColumn ('Name', 'Предмет', '', 400, ftString);
AddTable ('Кабинеты', 'Rooms').
AddColumn ('Name', 'Кабинет', '', 100, ftString).
AddColumn ('Room_size', 'Вместимость', '', 200, ftInteger);
AddTable ('Группы', 'Groups').
AddColumn ('Name', 'Группа', '', 100, ftString).
AddColumn ('Group_size', 'Количество человек', '', 100, ftInteger);
AddTable ('Расписание', 'Schedule_items').
AddColumn ('Professor_id', 'Преподаватель', 'Name', 200, ftString).
AddColumn ('Subject_id', 'Предмет', 'Name', 400, ftString).
AddColumn ('Subject_type_id', 'Тип', 'Name', 30, ftString).
AddColumn ('Room_id', 'Кабинет', 'Name', 100, ftString).
AddColumn ('Group_id', 'Группа', 'Name', 100, ftString).
AddColumn ('Day_id', 'День недели', 'Name', 100, ftDate);
end;
function TTableInfo.GetColumnCaption: strings;
var
i: integer;
begin
SetLength (Result, length (ColumnInfos));
for i := 0 to high (ColumnInfos) do
Result[i] := ColumnInfos[i].ColumnCaption;
end;
function TListOfTable.GetTableCaption: strings;
var
i: integer;
begin
SetLength (Result, length (TableInfos));
for i := 0 to high (TableInfos) do
Result[i] := TableInfos[i].TableCaption;
end;
procedure TTableInfo.SendQuery (SQLQuery: TSQLQuery);
begin
SQLQuery.Close;
SQLQuery.Params.Clear;
SQLQuery.SQL.Text := CreateQuery;
SQLQuery.Open;
end;
{function TTableInfo.GetTableName (aColumnName): string;
begin
end; }
function TTableInfo.CreateQuery: string;
var
i: integer;
begin
Result := 'Select ';
for i := 0 to High(ColumnInfos) do begin
if ColumnInfos[i].Reference then
Result += ColumnInfos[i].ReferenceTable + '.' + ColumnInfos[i].ReferenceName
else
Result += TableName + '.' + ColumnInfos[i].ColumnName + ' ';
if i < High(ColumnInfos) then Result += ', ';
end;
Result += ' From ' + TableName;
for i := 0 to High(ColumnInfos) do begin
if not ColumnInfos[i].Reference then continue;
Result += ' inner join ';
Result += ColumnInfos[i].ReferenceTable;
Result += ' on ' + TableName + '.' + ColumnInfos[i].ColumnName + ' = ' + ColumnInfos[i].ReferenceTable + '.ID';
end;
Result += ';';
//ShowMessage (Result);
end;
procedure TTableInfo.SetCaptions (DBGrid: TDBGrid);
var
i: Integer;
begin
for i := 0 to high(ColumnInfos) do begin
DBGrid.Columns[i].Title.Caption := ColumnInfos[i].ColumnCaption;
DBGrid.Columns[i].Width := ColumnInfos[i].Size;
end;
end;
procedure TTableInfo.Show(SQLQuery: TSQLQuery; DBGrid: TDBGrid);
begin
SendQuery(SQLQuery);
SetCaptions(DBGrid);
end;
end.
|
unit frameBuscaGrupo;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, Vcl.Mask, RxToolEdit, RxCurrEdit, Grupo;
type
TbuscaGrupo = class(TFrame)
StaticText1: TStaticText;
StaticText2: TStaticText;
edtCodigo: TCurrencyEdit;
btnBusca: TBitBtn;
edtGrupo: TEdit;
procedure edtGrupoEnter(Sender: TObject);
procedure btnBuscaClick(Sender: TObject);
procedure edtCodigoChange(Sender: TObject);
procedure edtCodigoExit(Sender: TObject);
private
Fcodigo :Integer;
FExecutarAposBuscar: TNotifyEvent;
FExecutarAposLimpar: TNotifyEvent;
FGrupo :TGrupo;
procedure buscaGrupo;
function selecionaGrupo :String;
procedure setaGrupo;
private
procedure SetGrupo (const Value: TGrupo);
procedure Setcodigo (const Value: Integer);
procedure SetExecutarAposBuscar(const Value: TNotifyEvent);
procedure SetExecutarAposLimpar(const Value: TNotifyEvent);
public
procedure limpa;
property Grupo :TGrupo read FGrupo write SetGrupo;
property codigo :Integer read Fcodigo write Setcodigo;
public
property ExecutarAposBuscar :TNotifyEvent read FExecutarAposBuscar write SetExecutarAposBuscar;
property ExecutarAposLimpar :TNotifyEvent read FExecutarAposLimpar write SetExecutarAposLimpar;
end;
implementation
uses uPesquisaSimples, Repositorio, FabricaRepositorio;
{$R *.dfm}
{ TbuscaGrupo }
procedure TbuscaGrupo.btnBuscaClick(Sender: TObject);
begin
selecionaGrupo;
end;
procedure TbuscaGrupo.buscaGrupo;
begin
setaGrupo;
if not assigned( FGrupo ) then
selecionaGrupo;
end;
procedure TbuscaGrupo.edtCodigoChange(Sender: TObject);
begin
edtGrupo.Clear;
if (self.edtCodigo.AsInteger <= 0) then
self.limpa;
end;
procedure TbuscaGrupo.edtCodigoExit(Sender: TObject);
begin
if edtCodigo.AsInteger > 0 then
buscaGrupo;
end;
procedure TbuscaGrupo.edtGrupoEnter(Sender: TObject);
begin
if not Assigned(FGrupo) or (FGrupo.Codigo <= 0) then
btnBusca.Click;
keybd_event(VK_RETURN, 0, 0, 0);
end;
procedure TbuscaGrupo.limpa;
begin
Fcodigo := 0;
edtCodigo.Clear;
edtGrupo.Clear;
if assigned(FGrupo) then
FreeAndNil(FGrupo);
if Assigned(FExecutarAposLimpar) then
self.FExecutarAposLimpar(self);
end;
function TbuscaGrupo.selecionaGrupo: String;
begin
Result := '';
frmPesquisaSimples := TFrmPesquisaSimples.Create(Self,'Select codigo, descricao grupo from grupos',
'CODIGO', 'Selecione o usuário desejado...');
if frmPesquisaSimples.ShowModal = mrOk then begin
Result := frmPesquisaSimples.cds_retorno.Fields[0].AsString;
edtCodigo.Text := Result;
setaGrupo;
end;
frmPesquisaSimples.Release;
end;
procedure TbuscaGrupo.setaGrupo;
var
RepUsuario :TRepositorio;
begin
RepUsuario := TFabricaRepositorio.GetRepositorio(TGrupo.ClassName);
FGrupo := TGrupo(RepUsuario.Get(edtCodigo.AsInteger));
if Assigned(FGrupo) then begin
edtCodigo.Value := FGrupo.Codigo;
edtGrupo.Text := FGrupo.descricao;
self.Fcodigo := FGrupo.codigo;
edtGrupo.SetFocus;
if Assigned(FGrupo) and Assigned(FExecutarAposBuscar) then
self.FExecutarAposBuscar(FGrupo);
end
else limpa;
end;
procedure TbuscaGrupo.Setcodigo(const Value: Integer);
begin
Fcodigo := value;
edtCodigo.AsInteger := value;
setaGrupo;
end;
procedure TbuscaGrupo.SetExecutarAposBuscar(const Value: TNotifyEvent);
begin
FExecutarAposBuscar := Value;
end;
procedure TbuscaGrupo.SetExecutarAposLimpar(const Value: TNotifyEvent);
begin
FExecutarAposLimpar := Value;
end;
procedure TbuscaGrupo.SetGrupo(const Value: TGrupo);
begin
self.FGrupo := value;
end;
end.
|
unit Unit1;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Objects, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
FMX.Controls.Presentation, FMX.StdCtrls;
type
TmyRectangle = class(Trectangle)
protected
procedure DoBeginUpdate; override;
procedure DoEndUpdate; override;
end;
TForm1 = class(TForm)
Start: TButton;
MasterControl: TRectangle;
Text1: TText;
Text2: TText;
Text3: TText;
procedure StartClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
var LBeginUpdateCount: integer;
LEndUpdateCount: integer;
procedure TForm1.StartClick(Sender: TObject);
begin
//create a LChildControl
var LChildControl := TMyRectangle.create(nil);
LChildControl.Align := TAlignLayout.Client;
LChildControl.Fill.Color := TalphaColorRec.Yellow;
//create a LGrandChildControl as child of LChildControl
Var LGrandChildControl := TRectangle.create(LChildControl);
LGrandChildControl.Align := TAlignLayout.Client;
LGrandChildControl.Fill.Color := TalphaColorRec.red;
LGrandChildControl.Parent := LChildControl;
//create a LGrandGrandChildControl as child of LGrandChildControl
Var LGrandGrandChildControl := TRectangle.create(LGrandChildControl);
LGrandGrandChildControl.Align := TAlignLayout.Client;
LGrandGrandChildControl.Fill.Color := TalphaColorRec.blue;
LGrandGrandChildControl.Parent := LGrandChildControl;
MasterControl.BeginUpdate;
try
LChildControl.Parent := MasterControl;
Showmessage(
'If everything is ok, all IsUpdating must be equal to true: ' + #13#10 +
#13#10 +
'MasterControl.IsUpdating: ' + boolToStr(MasterControl.IsUpdating, true) + #13#10 +
'ChildControl.IsUpdating: ' + boolToStr(LChildControl.IsUpdating, true) + #13#10 +
'GrandChildControl.IsUpdating: ' + boolToStr(LGrandChildControl.IsUpdating, true) + #13#10 +
'GrandGrandChildControl.IsUpdating: ' + boolToStr(LGrandGrandChildControl.IsUpdating, true) + #13#10);
finally
MasterControl.EndUpdate;
end;
Showmessage('If everything is ok, DoBeginUpdate = DoEndUpdate = 1' + #13#10 +
#13#10 +
'Control.DoBeginUpdate was called: '+inttostr(LBeginUpdateCount)+' times' + #13#10 +
'GrandChildControl.DoEndUpdate was called: '+inttostr(LEndUpdateCount)+' times');
Showmessage('Try now to rename _FMX.Controls.pas to FMX.Controls.pas and run again');
end;
{ TmyControl }
procedure TmyRectangle.DoBeginUpdate;
begin
inherited;
inc(LBeginUpdateCount);
end;
procedure TmyRectangle.DoEndUpdate;
begin
inherited;
inc(LEndUpdateCount);
end;
end.
|
{***************************************************************************}
{ }
{ DUnitX }
{ }
{ Copyright (C) 2017 Vincent Parrett }
{ }
{ vincent@finalbuilder.com }
{ http://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ 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 DUnitX.Tests.IoC;
{$I ..\Source\DUnitX.inc}
interface
uses
DUnitX.TestFramework,
DUnitX.IoC;
type
{$M+}
IFoo = interface
['{FA01B68C-0D64-4251-91C6-F38617A56B33}']
procedure Bar;
end;
{$M+}
ISingleton = interface
['{615BDB28-13D0-4CAF-B84A-3C77B479B9AE}']
function HowMany : integer;
end;
TDUnitX_IoCTests = class
private
FContainer : TDUnitXIoC;
public
[SetupFixture]
procedure Setup;
[TearDownFixture]
procedure TearDownFixture;
{$IFDEF DELPHI_XE_UP}
[Test]
procedure Test_Implementation_Non_Singleton;
[Test]
procedure Test_Implementation_Singleton;
{$ENDIF}
[Test]
procedure Test_Activator_Non_Singleton;
[Test]
procedure Test_Activator_Singleton;
end;
implementation
type
TFoo = class(TInterfacedObject,IFoo)
protected
procedure Bar;
end;
procedure TDUnitX_IoCTests.Setup;
begin
FContainer := TDUnitXIoC.Create;
FContainer.RegisterType<IFoo>(
function : IFoo
begin
result := TFoo.Create;
end);
{$IFDEF DELPHI_XE_UP}
//NOTE: DUnitX.IoC has details on why this is only available for XE up.
FContainer.RegisterType<IFoo,TFoo>('test');
{$ENDIF}
//singletons
FContainer.RegisterType<IFoo>(true,
function : IFoo
begin
result := TFoo.Create;
end,
'activator_singleton');
{$IFDEF DELPHI_XE_UP}
//NOTE: DUnitX.IoC has details on why this is only available for XE up.
FContainer.RegisterType<IFoo,TFoo>(true,'impl_singleton');
{$ENDIF}
end;
procedure TDUnitX_IoCTests.TearDownFixture;
begin
FContainer.Free;
end;
procedure TDUnitX_IoCTests.Test_Activator_Non_Singleton;
var
foo1 : IFoo;
foo2 : IFoo;
begin
foo1 := FContainer.Resolve<IFoo>();
foo2 := FContainer.Resolve<IFoo>();
Assert.AreNotSame(foo1,foo2);
end;
procedure TDUnitX_IoCTests.Test_Activator_Singleton;
var
foo1 : IFoo;
foo2 : IFoo;
begin
foo1 := FContainer.Resolve<IFoo>('activator_singleton');
foo2 := FContainer.Resolve<IFoo>('activator_singleton');
Assert.AreSame(foo1,foo2);
{$IFDEF DELPHI_XE_UP}
//NOTE: DUnitX.IoC has details on why this is only available for XE up.
foo1 := FContainer.Resolve<IFoo>('impl_singleton');
Assert.AreNotSame(foo1,foo2);
{$ENDIF}
end;
{$IFDEF DELPHI_XE_UP}
//NOTE: DUnitX.IoC has details on why this is only available for XE up.
procedure TDUnitX_IoCTests.Test_Implementation_Non_Singleton;
var
foo1 : IFoo;
foo2 : IFoo;
begin
foo1 := FContainer.Resolve<IFoo>('test');
foo2 := FContainer.Resolve<IFoo>('test');
Assert.AreNotSame(foo1,foo2);
end;
procedure TDUnitX_IoCTests.Test_Implementation_Singleton;
var
foo1 : IFoo;
foo2 : IFoo;
begin
foo1 := FContainer.Resolve<IFoo>('impl_singleton');
foo2 := FContainer.Resolve<IFoo>('impl_singleton');
Assert.AreSame(foo1,foo2);
end;
{$ENDIF}
procedure TFoo.Bar;
begin
Write('Bar');
end;
initialization
TDUnitX.RegisterTestFixture(TDUnitX_IoCTests);
end.
|
unit uTCPSockets;
{$mode objfpc}{$H+}
interface
uses
Classes,SysUtils, Math, Synsock, Blcksock, FileUtil;
const
Timeout = 6000;
TunnelTimeout = 60000;
PingTimeoutClient = 30000;
PingTimeoutServer = 300000;
type
TProxyType = (ptNone, ptHTML, ptSocks4, ptSocks5);
TProxy = record
FProxyType: TProxyType;
FProxyIP: String;
FProxyPort: String;
FProxyUser: String;
FProxyPass: String;
end;
TExtendedInfo = record
FLocalIP: String;
FLocalPort: Integer;
FRemoteIP: String;
FRemotePort: Integer;
FRemoteHost: String;
end;
TConnection = class
FIP: String;
FHost: String;
FPort: String;
FUser: String;
FPass: String;
FProxy: TProxy;
FExtendedInfo: TExtendedInfo;
FUniqueID: Integer;
FDateTime: TDateTime;
FData: Pointer;
end;
{ TTask }
TTask = class(TObject)
FName: String;
FMsg: String;
FileName: String;
FParams: array of String;
FMS: TMemoryStream;
FSL: TStringList;
end;
{ TTaskList }
TTaskList = class
FTaskList: TList;
FTaskCS: TRTLCriticalSection;
public
constructor Create;
destructor Destroy; override;
public
function AddTask(AName: String; AMsg: String; AParams: array of String; AMS: TMemoryStream = nil; AFileName: String = ''): Integer;
procedure DeleteTask(AIndex: Integer);
public
property TaskList: TList read FTaskList;
end;
{ TTaskQueue }
TStreamingType = (stDownload, stUpload);
TOnQueueRecv = procedure(AQueueType: Integer; AMsg: String; AParams: TStringArray; AMS: TMemoryStream; AFileName: String = '') of Object;
TOnQueueProgress = procedure(AStreamingType: TStreamingType; ACnt, ATotCnt: Int64; ASpeed, ARemaining: LongInt) of Object;
TTaskQueue = class(TObject)
private
FQueueType: Integer;
FMsg: String;
FParams: array of String;
FMS: TMemoryStream;
FFileName: String;
FStreamingType: TStreamingType;
FCnt: Int64;
FTotCnt: Int64;
FSpeed: LongInt;
FRemaining: LongInt;
FOnQueueRecv: TOnQueueRecv;
FOnQueueProgress: TOnQueueProgress;
procedure DoQueueRecv;
procedure DoQueueProgress;
public
constructor Create; virtual;
destructor Destroy; override;
procedure QueueRecv;
procedure QueueProgress;
public
property OnQueueRecv: TOnQueueRecv read FOnQueueRecv write FOnQueueRecv;
property OnQueueProgress: TOnQueueProgress read FOnQueueProgress write FOnQueueProgress;
end;
TTCPBase = class;
{ TBaseThread }
TBaseType = (btClient, btServer, btServer_AcceptedClient);
TBaseThread = class(TThread)
private
FBaseType: TBaseType;
FInternalMsg: String;
FTCPBase: TTCPBase;
FBlockSocket: TTCPBlockSocket;
FUniqueID: Integer;
FConnection: TConnection;
FNeedToBreak: Boolean;
FDisconnected: Boolean;
function GetUniqueID: Integer;
procedure CopyConnection(ASrc, ADst: TConnection);
procedure SyncError;
procedure SyncInternalMessage;
procedure DoError(AErrMsg: String; AErrCode: Integer);
procedure DoInternalMessage(AMsg: String);
public
constructor Create(ATCPBase: TTCPBase);
destructor Destroy; override;
end;
{ TClientThread }
TClientType = (ctMain, ctWorker);
TClientThread = class(TBaseThread)
private
FUseProxy: Boolean;
FClientType: TClientType;
FOldCnt: Int64;
FTick: QWord;
FTaskList: TTaskList;
FBusy: Boolean;
FLastPing: QWord;
procedure SetupProxy;
procedure SyncConnect;
procedure SyncDisconnect;
procedure QueueProgress(AStreamingType: TStreamingType; ACnt, ATotCnt: Int64; ASpeed, ARemaining: LongInt);
procedure QueueRecv(AQueueType: Integer; AMsg: String; AParams: TStringArray; AMS: TMemoryStream; AFileName: String = '');
procedure DoConnect;
procedure DoDisconnect;
procedure DoProgress(AStreamingType: TStreamingType; ACnt, ATotCnt: Int64);
procedure DoRecv(AQueueType: Integer; AMsg: String; AParams: TStringArray; AMS: TMemoryStream; AFileName: String = '');
procedure AcquireList(out AList: TList);
procedure FreeList(AList: TList);
function AddDirSeparator(const Path: String): String;
function GetDownloadDir(const APath: String): String;
function ProcessTask(ATask: TTask): Boolean;
function GetExtendedConnectionInfo: Boolean;
function SendMessage(AMsg: String; AParams: array of String): Boolean;
function RecvMessage(ATimeOut: Integer; out AMsgTyp: Integer; out AMsg: String; out AParams: TStringArray): Boolean;
function SendStream(AMS: TMemoryStream): Boolean;
function RecvStream(AMS: TMemoryStream): Boolean;
function SendFile(AFileName: String): Boolean;
function RecvFile(AFileName: String; ASize: Int64): Boolean;
protected
procedure Execute; override;
public
constructor Create(ATCPBase: TTCPBase); overload;
constructor Create(ATCPBase: TTCPBase; ASocket: TSocket); overload;
destructor Destroy; override;
end;
{ TServerThread }
TServerThread = class(TBaseThread)
private
function DoLogin(ACT: TClientThread): Boolean;
protected
procedure Execute; override;
public
constructor Create(ATCPBase: TTCPBase);
destructor Destroy; override;
end;
{ TTCPBase }
TOnConnect = procedure(Sender: TObject; AConnection: TConnection) of Object;
TOnDisconnect = procedure(Sender: TObject; AConnection: TConnection; AByUser: Boolean) of Object;
TOnError = procedure(Sender: TObject; AErrMsg: string; AErrCode: Integer; AConnection: TConnection) of Object;
TOnInternalMessage = procedure(Sender: TObject; AMsg: string) of Object;
TOnProgress = procedure(Sender: TObject; AStreamingType: TStreamingType; ACnt, ATotCnt: Int64; ASpeed, ARemaining: LongInt; AConnection: TConnection) of Object;
TOnRecvMessage = procedure(Sender: TObject; AMsg: String; AParams: TStringArray; AConnection: TConnection) of Object;
TOnRecvStream = procedure(Sender: TObject; AMsg: String; AParams: TStringArray; AMS: TMemoryStream; AConnection: TConnection) of Object;
TOnRecvFile = procedure(Sender: TObject; AMsg: String; AParams: TStringArray; AFileName: String; AConnection: TConnection) of Object;
TTCPBaseType = (tcpClient, tcpServer);
TTCPBase = class
private
FTCP_CS: TRTLCriticalSection;
FThreadList: TThreadList;
FTCPBaseType: TTCPBaseType;
FUniqueID: Integer;
FActiveOrConnected: Boolean;
FErrMsg: String;
FErrCode: Integer;
FCompress: Boolean;
FDownloadDirectory: String;
FHideInternalMessages: Boolean;
FHideErrorMessages: Boolean;
FIgnoreMessage: Boolean;
FOnConnect: TOnConnect;
FOnDisconnect: TOnDisconnect;
FOnError: TOnError;
FOnInternalMessage: TOnInternalMessage;
FOnProgress: TOnProgress;
FOnRecvMessage: TOnRecvMessage;
FOnRecvStream: TOnRecvStream;
FOnRecvFile: TOnRecvFile;
function FindThread(const AUniqueID: Integer): TBaseThread;
function IsMessageInvalid(const AMsg: String): Boolean;
public
constructor Create; virtual;
destructor Destroy; override;
public
function SendMessage(AMsg: String; AParams: array of String; const AUniqueID: Integer = 0): Boolean;
function SendStream(AMsg: String; AParams: array of String; AMS: TMemoryStream; const AUniqueID: Integer = 0): Boolean;
function SendFile(AMsg: String; AParams: array of String; AFileName: String; const AUniqueID: Integer = 0): Boolean;
public
property ErrMsg: String read FErrMsg;
property ErrCode: Integer read FErrCode;
property OnConnect: TOnConnect read FOnConnect write FOnConnect;
property OnDisconnect: TOnDisconnect read FOnDisconnect write FOnDisconnect;
property OnError: TOnError read FOnError write FOnError;
property OnInternalMessage: TOnInternalMessage read FOnInternalMessage write FOnInternalMessage;
property OnProgress: TOnProgress read FOnProgress write FOnProgress;
property OnRecvMessage: TOnRecvMessage read FOnRecvMessage write FOnRecvMessage;
property OnRecvStream: TOnRecvStream read FOnRecvStream write FOnRecvStream;
property OnRecvFile: TOnRecvFile read FOnRecvFile write FOnRecvFile;
end;
{ TTCPClient }
TTCPClient = class(TTCPBase)
private
FByUser: Boolean;
procedure Cleanup;
procedure Remove(AThread: TBaseThread);
function DoConnect(ACT: TClientThread): Boolean;
function DoLogin(ACT: TClientThread): Integer;
public
constructor Create; override;
destructor Destroy; override;
procedure Connect(const AConnection: TConnection);
procedure Disconnect(const AByUser: Boolean);
public
property Connected: Boolean read FActiveOrConnected;
property DownloadDirectory: String read FDownloadDirectory write FDownloadDirectory;
property HideInternalMessages: Boolean read FHideInternalMessages write FHideInternalMessages;
property HideErrorMessages: Boolean read FHideErrorMessages write FHideErrorMessages;
end;
{ TTCPServer }
TTCPServer = class(TTCPBase)
private
FUserList: TStringList;
procedure Cleanup;
procedure Remove(AThread: TBaseThread);
function FindUser(AUserName: String): Integer;
public
constructor Create; override;
destructor Destroy; override;
procedure Start(ABindConnection: TConnection);
procedure Stop;
procedure DisconnectClient(AUniqueID: Integer);
function IsClientConnected(AUniqueID: Integer): Boolean;
public
property Active: Boolean read FActiveOrConnected;
property DownloadDirectory: String read FDownloadDirectory write FDownloadDirectory;
property HideInternalMessages: Boolean read FHideInternalMessages write FHideInternalMessages;
property HideErrorMessages: Boolean read FHideErrorMessages write FHideErrorMessages;
end;
implementation
uses uTCPCryptoCompression, uTCPFunctions, uTCPConst;
constructor TTaskList.Create;
begin
InitCriticalSection(FTaskCS);
FTaskList := TList.Create;
end;
destructor TTaskList.Destroy;
var
I: Integer;
begin
for I := FTaskList.Count - 1 downto 0 do
DeleteTask(I);
FTaskList.Clear;
FTaskList.Free;
DoneCriticalsection(FTaskCS);
inherited Destroy;
end;
function TTaskList.AddTask(AName: String; AMsg: String; AParams: array of String;
AMS: TMemoryStream; AFileName: String = ''): Integer;
var
Task: TTask;
I: Integer;
begin
Result := -1;
Task := TTask.Create;
Task.FName := AName;
Task.FMsg := AMsg;
if Length(AParams) > 0 then
begin
SetLength(Task.FParams, Length(AParams));
for I := Low(AParams) to High(AParams) do
Task.FParams[I] := AParams[I];
end;
if AMS <> nil then
Task.FMS := AMS;
Task.FileName := AFileName;
Result := FTaskList.Add(Task);
end;
procedure TTaskList.DeleteTask(AIndex: Integer);
var
Task: TTask;
begin
Task := TTask(FTaskList.Items[AIndex]);
if Task <> nil then
begin
Task.FParams := nil;
if Assigned(Task.FMS) then
Task.FMS.Free;
if Assigned(Task.FSL) then
Task.FSL.Free;
Task.Free;
end;
FTaskList.Delete(AIndex);
end;
constructor TTaskQueue.Create;
begin
inherited Create;
FMS := TMemoryStream.Create;
end;
destructor TTaskQueue.Destroy;
begin
FMS.Free;
inherited Destroy;
end;
procedure TTaskQueue.DoQueueRecv;
begin
try
if Assigned(FOnQueueRecv) then
FOnQueueRecv(FQueueType, FMsg, FParams, FMS, FFileName);
finally
Free;
end;
end;
procedure TTaskQueue.DoQueueProgress;
begin
try
if Assigned(FOnQueueProgress) then
FOnQueueProgress(FStreamingType, FCnt, FTotCnt, FSpeed, FRemaining);
finally
Free;
end;
end;
procedure TTaskQueue.QueueRecv;
begin
try
TThread.Queue(nil, @DoQueueRecv);
except
Free;
end;
end;
procedure TTaskQueue.QueueProgress;
begin
try
TThread.Queue(nil, @DoQueueProgress);
except
Free;
end;
end;
constructor TBaseThread.Create(ATCPBase: TTCPBase);
begin
inherited Create(True);
FTCPBase := ATCPBase;
FUniqueID := GetUniqueID;
FConnection := TConnection.Create;
FBlockSocket := TTCPBlockSocket.Create;
FBlockSocket.Family := SF_Any;
FBlockSocket.RaiseExcept := False;
end;
destructor TBaseThread.Destroy;
begin
FBlockSocket.Free;
FConnection.Free;
inherited Destroy;
end;
function TBaseThread.GetUniqueID: Integer;
begin
EnterCriticalSection(FTCPBase.FTCP_CS);
try
Inc(FTCPBase.FUniqueID);
Result := FTCPBase.FUniqueID;
finally
LeaveCriticalSection(FTCPBase.FTCP_CS);
end;
end;
procedure TBaseThread.CopyConnection(ASrc, ADst: TConnection);
begin
with ADst do
begin
FIP := ASrc.FIP;
FHost := ASrc.FHost;
FPort := ASrc.FPort;
FUser := ASrc.FUser;
FPass := ASrc.FPass;
FProxy.FProxyType := ASrc.FProxy.FProxyType;
FProxy.FProxyIP := ASrc.FProxy.FProxyIP;
FProxy.FProxyPort := ASrc.FProxy.FProxyPort;
FProxy.FProxyUser := ASrc.FProxy.FProxyUser;
FProxy.FProxyPass := ASrc.FProxy.FProxyPass;
end;
end;
procedure TBaseThread.SyncError;
begin
if Assigned(FTCPBase.FOnError) then
FTCPBase.FOnError(Self, FTCPBase.FErrMsg, FTCPBase.FErrCode, FConnection);
end;
procedure TBaseThread.SyncInternalMessage;
begin
if Assigned(FTCPBase.FOnInternalMessage) then
FTCPBase.FOnInternalMessage(Self, FInternalMsg);
end;
procedure TBaseThread.DoInternalMessage(AMsg: String);
begin
if (FTCPBase.FActiveOrConnected) and (not FTCPBase.FHideInternalMessages) and (not FTCPBase.FIgnoreMessage) and (not Terminated) then
begin
FInternalMsg := AMsg;
Synchronize(@SyncInternalMessage);
end;
end;
procedure TBaseThread.DoError(AErrMsg: String; AErrCode: Integer);
begin
if (FTCPBase.FActiveOrConnected) and (not FTCPBase.FHideErrorMessages) and (not Terminated) then
begin
FTCPBase.FErrMsg := AErrMsg;
FTCPBase.FErrCode := AErrCode;
Synchronize(@SyncError);
end;
end;
constructor TClientThread.Create(ATCPBase: TTCPBase);
begin
inherited Create(ATCPBase);
//meu
FTaskList := TTaskList.Create;
FBaseType := btClient;
FDisconnected := False;
FOldCnt := 0;
FTick := GetTickCount64;
end;
constructor TClientThread.Create(ATCPBase: TTCPBase; ASocket: TSocket);
begin
inherited Create(ATCPBase);
FTaskList := TTaskList.Create;
FBaseType := btServer_AcceptedClient;
FBlockSocket.Socket := ASocket;
FDisconnected := False;
FOldCnt := 0;
FTick := GetTickCount64;
end;
destructor TClientThread.Destroy;
begin
inherited Destroy;
FTaskList.Free;
end;
procedure TClientThread.SetupProxy;
begin
with FConnection.FProxy do
begin
case FProxyType of
ptHTML:
begin
FBlockSocket.HTTPTunnelIP := FProxyIP;
FBlockSocket.HTTPTunnelPort := FProxyPort;
FBlockSocket.HTTPTunnelUser := FProxyUser;
FBlockSocket.HTTPTunnelPass := FProxyPass;
FBlockSocket.HTTPTunnelTimeout := TunnelTimeout;
end;
ptSocks4, ptSocks5:
begin
if FProxyType = ptSocks4 then
FBlockSocket.SocksType := ST_Socks4
else
FBlockSocket.SocksType := ST_Socks5;
FBlockSocket.SocksIP:= FProxyIP;
FBlockSocket.SocksPort := FProxyPort;
FBlockSocket.SocksUsername := FProxyUser;
FBlockSocket.SocksPassword := FProxyPass;
FBlockSocket.SocksTimeout := TunnelTimeout;
end;
ptNone:
begin
FBlockSocket.HTTPTunnelIP := '';
FBlockSocket.SocksIP := '';
end;
end;
end;
end;
procedure TClientThread.SyncConnect;
begin
if Assigned(FTCPBase.FOnConnect) then
FTCPBase.FOnConnect(Self, FConnection);
end;
procedure TClientThread.SyncDisconnect;
begin
case FBaseType of
btClient:
TTCPClient(FTCPBase).Remove(Self);
btServer, btServer_AcceptedClient:
TTCPServer(FTCPBase).Remove(Self);
end;
end;
procedure TClientThread.QueueProgress(AStreamingType: TStreamingType; ACnt, ATotCnt: Int64; ASpeed, ARemaining: LongInt);
begin
if Assigned(FTCPBase.FOnProgress) then
FTCPBase.FOnProgress(Self, AStreamingType, ACnt, ATotCnt, ASpeed, ARemaining, FConnection);
end;
procedure TClientThread.DoConnect;
begin
if (FTCPBase.FActiveOrConnected) and (not Terminated) then
Synchronize(@SyncConnect);
end;
procedure TClientThread.DoDisconnect;
begin
if (FTCPBase.FActiveOrConnected) and (not Terminated) then
Queue(@SyncDisconnect)
end;
procedure TClientThread.QueueRecv(AQueueType: Integer; AMsg: String;
AParams: TStringArray; AMS: TMemoryStream; AFileName: String = '');
begin
if (FTCPBase.FActiveOrConnected) and (not Terminated) then
case AQueueType of
0: if Assigned(FTCPBase.FOnRecvMessage) then
FTCPBase.FOnRecvMessage(Self, AMsg, AParams, FConnection);
1: if Assigned(FTCPBase.FOnRecvStream) then
FTCPBase.FOnRecvStream(Self, AMsg, AParams, AMS, FConnection);
2: if Assigned(FTCPBase.FOnRecvFile) then
FTCPBase.FOnRecvFile(Self, AMsg, AParams, AFileName, FConnection);
end;
end;
procedure TClientThread.DoRecv(AQueueType: Integer; AMsg: String; AParams: TStringArray;
AMS: TMemoryStream; AFileName: String = '');
var
TaskQueue: TTaskQueue;
begin
if (FTCPBase.FActiveOrConnected) and (not Terminated) and (not FNeedToBreak) then
begin
TaskQueue := TTaskQueue.Create;
TaskQueue.FQueueType := AQueueType;
TaskQueue.FMsg := AMsg;
TaskQueue.FParams := AParams;
SetLength(TaskQueue.FParams, Length(AParams));
if AMS <> nil then
TaskQueue.FMS.CopyFrom(AMS, AMS.Size);
if AFileName <> '' then
TaskQueue.FFileName := AFileName;
TaskQueue.OnQueueRecv := @QueueRecv;
TaskQueue.QueueRecv;
end;
end;
procedure TClientThread.DoProgress(AStreamingType: TStreamingType; ACnt, ATotCnt: Int64);
var
ElapsedSec: Single;
Speed: LongInt;
Remaining: LongInt;
Tick: QWord;
Diff: QWord;
TaskQueue: TTaskQueue;
begin
if (FTCPBase.FActiveOrConnected) and (not Terminated) then
begin
Tick := GetTickCount64;
Diff := Tick - FTick;
ElapsedSec := Diff/1000;
if (CompareValue(ElapsedSec, 0.50) = 1) or (ACnt >= ATotCnt) then
begin
Speed := Round((ACnt - FOldCnt)/ElapsedSec);
if Speed < 0 then
Speed := 0;
FTick := Tick;
FOldCnt := ACnt;
if Speed > 0 then
Remaining := Round((ATotCnt - ACnt)/Speed);
TaskQueue := TTaskQueue.Create;
TaskQueue.FStreamingType := AStreamingType;
TaskQueue.FCnt := ACnt;
TaskQueue.FTotCnt := ATotCnt;
TaskQueue.FSpeed := Speed;
TaskQueue.FRemaining := Remaining;
TaskQueue.OnQueueProgress := @QueueProgress;
TaskQueue.QueueProgress;
end;
end;
end;
function TClientThread.GetExtendedConnectionInfo: Boolean;
begin
Result := True;
FBlockSocket.GetSins;
if FBlockSocket.LastError <> 0 then
begin
Result := False;
DoError(FBlockSocket.LastErrorDesc, FBlockSocket.LastError);
Exit;
end;
with FConnection.FExtendedInfo do
begin
FLocalIP := FBlockSocket.GetLocalSinIP;
FLocalPort := FBlockSocket.GetLocalSinPort;
FRemoteIP := FBlockSocket.GetRemoteSinIP;
FRemotePort := FBlockSocket.GetRemoteSinPort;
FRemoteHost := FBlockSocket.ResolveIPToName(FRemoteIP);
end;
end;
function TClientThread.SendMessage(AMsg: String; AParams: array of String): Boolean;
var
I: Integer;
Msg: String;
begin
Result := False;
if not FTCPBase.FActiveOrConnected then
Exit;
Msg := AMsg;
if Length(AParams) > 0 then
begin
AMsg := AMsg + ':';
for I := Low(AParams) to High(AParams) do
AMsg := AMsg + AParams[I] + ',';
end;
AMsg := Encrypt(FConnection.FPort, AMsg);
FBlockSocket.SendString(AMsg);
Result := FBlockSocket.LastError = 0;
Delete(Msg, 1, 1);
FTCPBase.FIgnoreMessage := (Msg = 'BROADCASTSCREEN') or (Msg = 'PING');
if Result then
DoInternalMessage(Format(rsMessageSent, [Msg, FConnection.FExtendedInfo.FRemoteIP]))
else
DoError(Format(rsMessageSentError, [Msg]) + FBlockSocket.LastErrorDesc, FBlockSocket.LastError);
end;
function TClientThread.RecvMessage(ATimeOut: Integer; out AMsgTyp: Integer;
out AMsg: String; out AParams: TStringArray): Boolean;
var
Str: String;
P: Integer;
Len: Integer;
begin
Result := True;
AMsg := '';
AMsgTyp := -1;
AParams := nil;
Str := FBlockSocket.RecvPacket(ATimeOut);
if (FBlockSocket.LastError > 0) and (FBlockSocket.LastError <> WSAETIMEDOUT) then
begin
Result := False;
DoError(FBlockSocket.LastErrorDesc, FBlockSocket.LastError);
Exit;
end;
if Trim(Str) <> '' then
begin
Str := Decrypt(FConnection.FPort, Str);
P := Pos(':', Str);
if P > 0 then
begin
AMsg := Trim(System.Copy(Str, 1, P - 1));
System.Delete(Str, 1, P);
repeat
P := Pos(',', Str);
if P > 0 then
begin
Len := Length(AParams);
SetLength(AParams, Len + 1);
AParams[Len] := System.Copy(Str, 1, P - 1);
System.Delete(Str, 1, P);
end;
until (P = 0) or (Str = '') ;
end
else
AMsg := Trim(Str);
AMsgTyp := StrToIntDef(AMsg[1], -1);
if (not AMsgTyp in [0..3]) then
begin
DoError(rsInvalidMessage , 0);
Result := False;
Exit;
end;
Delete(AMsg, 1, 1);
FTCPBase.FIgnoreMessage := (AMsg = 'BROADCASTSCREEN') or (AMsg = 'PING');
DoInternalMessage(Format(rsMessageRecv, [AMsg, FConnection.FExtendedInfo.FRemoteIP]));
end;
end;
function TClientThread.SendStream(AMS: TMemoryStream): Boolean;
var
ReadCnt: LongInt;
Cnt: Int64;
Buffer: Pointer;
Ms: TMemoryStream;
MsComp: TMemoryStream;
Msg: String;
CompRate: Single;
begin
Result := False;
if not FTCPBase.FActiveOrConnected then
Exit;
if FBlockSocket.LastError > 0 then
begin
DoError(Format(rsStreamSentError, [FConnection.FExtendedInfo.FRemoteIP]) + FBlockSocket.LastErrorDesc, FBlockSocket.LastError);
Exit;
end;
FOldCnt := 0;
MS := TMemoryStream.Create;
try
AMS.Position := 0;
MSComp := TMemoryStream.Create;
try
GetMem(Buffer, FBlockSocket.SendMaxChunk);
try
Cnt := 0;
repeat
if FNeedToBreak then
Break;
Msg := FBlockSocket.RecvPacket(50000);
if (FBlockSocket.LastError > 0) or (Msg = 'DONE') or (Msg <> 'NEXT') then
Break;
ReadCnt := AMS.Read(Buffer^, FBlockSocket.SendMaxChunk);
if (ReadCnt > 0) then
begin
MS.Clear;
MS.Write(Buffer^, ReadCnt);
MS.Position := 0;
if FTCPBase.FCompress and CompressStream(Ms, MsComp, clBestCompression, CompRate) then
FBlockSocket.SendStream(MSComp)
else
FBlockSocket.SendStream(MS);
if (FBlockSocket.LastError > 0) and (FBlockSocket.LastError <> WSAETIMEDOUT) then
Break;
if (FBlockSocket.LastError = 0) and (FTCPBase.FActiveOrConnected) then
begin
Cnt := Cnt + MS.Size;
DoProgress(stUpload, Cnt, AMS.Size);
end;
end;
until (ReadCnt = 0) or (Cnt > AMS.Size);
Result := FBlockSocket.LastError = 0;
if Result then
DoInternalMessage(Format(rsStreamSent, [FormatSize(AMS.Size), FConnection.FExtendedInfo.FRemoteIP]))
else
DoError(Format(rsStreamSentError, [FConnection.FExtendedInfo.FRemoteIP]) + FBlockSocket.LastErrorDesc, FBlockSocket.LastError);
finally
FreeMem(Buffer);
end;
finally
MsComp.Free;
end;
finally
MS.Free;
end;
end;
function TClientThread.RecvStream(AMS: TMemoryStream): Boolean;
var
Cnt: Int64;
MS: TMemoryStream;
MSDecomp: TMemoryStream;
begin
Result := False;
if not FTCPBase.FActiveOrConnected then
Exit;
MS := TMemoryStream.Create;
try
Cnt := 0;
MSDecomp := TMemoryStream.Create;
try
repeat
if FNeedToBreak then
Break;
FBlockSocket.SendString('NEXT');
MS.Clear;
FBlockSocket.RecvStream(Ms, 5000);
if (FBlockSocket.LastError > 0) and (FBlockSocket.LastError <> WSAETIMEDOUT) then
Break;
if (MS.Size > 0) and (FBlockSocket.LastError = 0) and (FTCPBase.FActiveOrConnected) then
begin
MS.Position := 0;
if FTCPBase.FCompress and DecompressStream(MS, MSDecomp) then
begin
AMS.CopyFrom(MSDecomp, MSDecomp.Size);
Cnt := Cnt + MSDecomp.Size;
DoProgress(stDownload, Cnt, AMS.Size);
end
else
begin
AMS.CopyFrom(MS, MS.Size);
Cnt := Cnt + MS.Size;
DoProgress(stDownload, Cnt, AMS.Size);
end;
end;
until (Cnt >= AMS.Size);
FBlockSocket.SendString('DONE');
Result := FBlockSocket.LastError = 0;
if Result then
begin
DoInternalMessage(Format(rsStreamRecv, [FormatSize(AMS.Size), FConnection.FExtendedInfo.FRemoteIP]));
AMS.Position := 0
end
else
DoError(Format(rsStreamRecvError, [FConnection.FExtendedInfo.FRemoteIP]) + FBlockSocket.LastErrorDesc, FBlockSocket.LastError);
finally
MSDecomp.Free;
end;
finally
MS.Free;
end
end;
function TClientThread.SendFile(AFileName: String): Boolean;
var
ReadCnt: LongInt;
Cnt: Int64;
Buffer: Pointer;
MS: TMemoryStream;
MSComp: TMemoryStream;
FS: TFileStream;
Msg: String;
CompRate: Single;
begin
Result := False;
if not FTCPBase.FActiveOrConnected then
Exit;
if FBlockSocket.LastError > 0 then
begin
DoError(Format(rsFileSentError, [FConnection.FExtendedInfo.FRemoteIP]) + FBlockSocket.LastErrorDesc, FBlockSocket.LastError);
Exit;
end;
try
FS := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite);
try
FS.Position := 0;
GetMem(Buffer, FBlockSocket.SendMaxChunk);
try
Cnt := 0;
MS := TMemoryStream.Create;
try
MSComp := TMemoryStream.Create;
try
repeat
if FNeedToBreak then
Break;
Msg := FBlockSocket.RecvPacket(50000);
if (FBlockSocket.LastError > 0) or (Msg = 'DONE') or (Msg <> 'NEXT') then
Break;
ReadCnt := FS.Read(Buffer^, FBlockSocket.SendMaxChunk);
if (ReadCnt > 0) then
begin
MS.Clear;
MS.Write(Buffer^, ReadCnt);
MS.Position := 0;
if FTCPBase.FCompress and CompressStream(Ms, MsComp, clBestCompression, CompRate) then
FBlockSocket.SendStream(MSComp)
else
FBlockSocket.SendStream(MS);
if (FBlockSocket.LastError > 0) and (FBlockSocket.LastError <> WSAETIMEDOUT) then
Break;
if (FBlockSocket.LastError = 0) and (FTCPBase.FActiveOrConnected) then
begin
Cnt := Cnt + MS.Size;
DoProgress(stUpload, Cnt, FS.Size);
end;
end;
until (ReadCnt = 0) or (Cnt > FS.Size);
Result := FBlockSocket.LastError = 0;
if Result then
DoInternalMessage(Format(rsFileSent, [FormatSize(FS.Size), FConnection.FExtendedInfo.FRemoteIP]))
else
DoError(Format(rsFileSentError, [FConnection.FExtendedInfo.FRemoteIP]) + FBlockSocket.LastErrorDesc, FBlockSocket.LastError);
finally
MSComp.Free;
end;
finally
MS.Free;
end;
finally
FreeMem(Buffer);
end;
finally
FS.Free;
end;
except
on E: Exception do
DoError(Format(rsFileSentError, [FConnection.FExtendedInfo.FRemoteIP]) + E.Message, 0);
end
end;
function TClientThread.RecvFile(AFileName: String; ASize: Int64): Boolean;
var
Cnt: Int64;
MS: TMemoryStream;
MSDecomp: TMemoryStream;
FS: TFileStream;
begin
Result := False;
if not FTCPBase.FActiveOrConnected then
Exit;
try
FS := TFileStream.Create(AFileName, fmCreate or fmOpenReadWrite or fmShareDenyWrite);
try
MS := TMemoryStream.Create;
try
Cnt := 0;
MSDecomp := TMemoryStream.Create;
try
repeat
if FNeedToBreak then
Break;
FBlockSocket.SendString('NEXT');
MS.Clear;
FBlockSocket.RecvStream(MS, 5000);
if (FBlockSocket.LastError > 0) and (FBlockSocket.LastError <> WSAETIMEDOUT) then
Break;
if (MS.Size > 0) and (FBlockSocket.LastError = 0) and (FTCPBase.FActiveOrConnected) then
begin
MS.Position := 0;
if FTCPBase.FCompress and DecompressStream(MS, MSDecomp) then
begin
FS.CopyFrom(MsDecomp, MSDecomp.Size);
Cnt := Cnt + MSDecomp.Size;
DoProgress(stDownload, Cnt, ASize);
end
else
begin
FS.CopyFrom(MS, MS.Size);
Cnt := Cnt + MS.Size;
DoProgress(stDownload, Cnt, ASize);
end;
end;
until (Cnt >= ASize);
FBlockSocket.SendString('DONE');
Result := FBlockSocket.LastError = 0;
if Result then
DoInternalMessage(Format(rsFileRecv, [FormatSize(ASize), FConnection.FExtendedInfo.FRemoteIP]))
else
DoError(Format(rsFileRecvError, [FConnection.FExtendedInfo.FRemoteIP]) + FBlockSocket.LastErrorDesc, FBlockSocket.LastError);
finally
MSDecomp.Free;
end;
finally
MS.Free;
end
finally
FS.Free;
end;
except
on E: Exception do
DoError(Format(rsFileRecvError, [FConnection.FExtendedInfo.FRemoteIP]) + E.Message, 0);
end
end;
function TClientThread.ProcessTask(ATask: TTask): Boolean;
begin
case ATask.FName of
'MESSAGE':
begin
ATask.FMsg := '0' + ATask.FMsg;
Result := SendMessage(ATask.FMsg, ATask.FParams);
end;
'STREAM':
begin
ATask.FMsg := '1' + ATask.FMsg;
SetLength(ATask.FParams, Length(ATask.FParams) + 1);
ATask.FParams[Length(ATask.FParams) - 1] := IntToStr(ATask.FMS.Size);
Result := SendMessage(ATask.FMsg, ATask.FParams);
if Result then
Result := SendStream(ATask.FMS);
end;
'FILE':
begin
ATask.FMsg := '2' + ATask.FMsg;
SetLength(ATask.FParams, Length(ATask.FParams) + 2);
ATask.FParams[Length(ATask.FParams) - 2] := IntToStr(FileSize(ATask.FileName));
ATask.FParams[Length(ATask.FParams) - 1] := ExtractFileName(ATask.FileName);
Result := SendMessage(ATask.FMsg, ATask.FParams);
if Result then
Result := SendFile(ATask.FileName);
end;
end;
end;
procedure TClientThread.AcquireList(out AList: TList);
var
I: Integer;
begin
AList := TList.Create;
EnterCriticalSection(FTaskList.FTaskCS);
try
for I := FTaskList.TaskList.Count - 1 downto 0 do
begin
AList.Add(TTask(FTaskList.TaskList.Items[I]));
FTaskList.TaskList.Delete(I);
end;
finally
LeaveCriticalSection(FTaskList. FTaskCS);
end;
end;
procedure TClientThread.FreeList(AList: TList);
var
I: Integer;
Task: TTask;
begin
for I := AList.Count - 1 downto 0 do
begin
Task := TTask(AList.Items[I]);
if Task <> nil then
begin
Task.FParams := nil;
if Assigned(Task.FMS) then
Task.FMS.Free;
if Assigned(Task.FSL) then
Task.FSL.Free;
Task.Free;
end;
AList.Delete(I);
end;
AList.Free;
end;
function TClientThread.AddDirSeparator(const Path: String): String;
begin
if (Trim(Path) <> '') and (not (Path[Length(Path)] in AllowDirectorySeparators)) then
Result := Path + PathDelim
else
Result := Path;
end;
function TClientThread.GetDownloadDir(const APath: String): String;
begin
if Trim(APath) = '' then
begin
Result := AddDirSeparator(GetUserDir) + 'Downloads';
Exit;
end;
Result := AddDirSeparator(APath);
if not DirectoryExists(Result) then
begin
if not CreateDir(Result) then
Result := AddDirSeparator(GetUserDir) + 'Downloads';
end
end;
procedure TClientThread.Execute;
var
Msg: String;
MsgTyp: Integer;
Params: TStringArray;
Size: Int64;
MS: TMemoryStream;
I: Integer;
FileName: String;
Path: String;
TmpTaskList: TList;
FCurPing: QWord;
begin
FLastPing := GetTickCount64;
while not Terminated do
begin
if (not FBusy) and (FTaskList.TaskList.Count > 0) and (not FNeedToBreak) then
begin
FBusy := True;
try
AcquireList(TmpTaskList);
try
for I := TmpTaskList.Count - 1 downto 0 do
begin
if FNeedToBreak then
Break;
if ProcessTask(TTask(TmpTaskList[I])) then
FLastPing := GetTickCount64;
end;
finally
FreeList(TmpTaskList);
end;
finally
FBusy := False;
end;
end;
if not RecvMessage(500, MsgTyp, Msg, Params) then
begin
DoDisconnect;
Break;
end;
case MsgTyp of
0: begin
FLastPing := GetTickCount64;
if not FTCPBase.FIgnoreMessage then
DoRecv(0, Msg, Params, nil);
end;
1: begin
FLastPing := GetTickCount64;
Size := StrToInt64Def(Params[Length(Params) - 1], -1);
if Size > 0 then
begin
SetLength(Params, Length(Params) - 1);
MS := TMemoryStream.Create;
try
MS.SetSize(Size);
MS.Position := 0;
if RecvStream(MS) then
DoRecv(1, Msg, Params, MS);
finally
MS.Free;
end;
end
end;
2: begin
FLastPing := GetTickCount64;
Size := StrToInt64Def(Params[Length(Params) - 2], -1);
FileName := Params[Length(Params) - 1];
SetLength(Params, Length(Params) - 2);
if Size > 0 then
begin
Path := AddDirSeparator(GetDownloadDir(FTCPBase.FDownloadDirectory));
if DirectoryExists(Path) then
begin
Path := Path + FConnection.FUser + '_' + FileName;
if RecvFile(Path, Size) then
DoRecv(2, Msg, Params, nil, Path)
end
else
DoError(rsInvalidDirectory, 0);
end
else
FileCreate(Params[0] + Params[1]);
end;
end;
if (FTCPBase.FTCPBaseType = tcpServer) then
begin
FCurPing := GetTickCount64;
if (FCurPing - FLastPing > PingTimeoutServer) then
begin
DoDisconnect;
Break;
end;
end
else if (FTCPBase.FTCPBaseType = tcpClient) then
begin
FCurPing := GetTickCount64;
if (FTaskList.TaskList.Count = 0) and (FCurPing - FLastPing > PingTimeoutClient) then
FTaskList.AddTask('MESSAGE', 'PING', [], nil, '');
end;
end;
FDisconnected := True;
while not Terminated do
Sleep(100);
end;
constructor TServerThread.Create(ATCPBase: TTCPBase);
begin
inherited Create(ATCPBase);
FBaseType := btServer;
end;
destructor TServerThread.Destroy;
begin
inherited Destroy;
end;
function TServerThread.DoLogin(ACT: TClientThread): Boolean;
var
Msg: String;
MsgTyp: Integer;
Params: TStringArray;
UserID: Integer;
begin
Result := False;
if ACT.RecvMessage(Timeout, MsgTyp, Msg, Params) then
begin
if Length(Params) < 3 then
Exit;
if (MsgTyp = 0) and (Msg = 'LOGIN') and (Length(Params) >= 2) and (Params[0] = ACT.FConnection.FPass) then
begin
if Trim(Params[1]) = '' then
Params[1] := 'anonymous';
UserID := TTCPServer(FTCPBase).FindUser(Params[1]);
if UserID = -1 then
begin
Result := True;
TTCPServer(FTCPBase).FUserList.Add(Params[1]);
ACT.FConnection.FUser := Params[1];
ACT.SendMessage('0LOGINREPLY', ['SUCCESS']);
ACT.DoConnect;
end
else
begin
ACT.SendMessage('0LOGINREPLY', ['FAILEDDUPLICATE']);
DoInternalMessage(Format(rsConnectionRejectedDuplicate, [ACT.FConnection.FExtendedInfo.FRemoteIP + '(' + ACT.FConnection.FExtendedInfo.FRemoteHost + ')']));
end;
end
else
begin
ACT.SendMessage('0LOGINREPLY', ['FAILEDINVALID']);
DoInternalMessage(Format(rsConnectionRejectedInvalid, [ACT.FConnection.FExtendedInfo.FRemoteIP + '(' + ACT.FConnection.FExtendedInfo.FRemoteHost + ')']));
end;
end;
end;
procedure TServerThread.Execute;
var
CT: TClientThread;
Socket: TSocket;
begin
while not Terminated do
begin
if FTCPBase.FActiveOrConnected and FBlockSocket.CanRead(1000) then
begin
Socket := FBlockSocket.Accept;
if FBlockSocket.LastError = 0 then
begin
CT := TClientThread.Create(FTCPBase, Socket);
CT.CopyConnection(FConnection, CT.FConnection);
CT.FConnection.FUniqueID := CT.FUniqueID;
CT.FConnection.FDateTime := Now;
if CT.GetExtendedConnectionInfo then
begin
if DoLogin(CT) then
begin
FTCPBase.FThreadList.Add(CT);
CT.Start;
end
else
begin
CT.Free;
CT := nil;
end;
end
else
DoError(FBlockSocket.LastErrorDesc, FBlockSocket.LastError);
end
else
DoError(FBlockSocket.LastErrorDesc, FBlockSocket.LastError);
end;
end;
end;
constructor TTCPBase.Create;
begin
InitCriticalSection(FTCP_CS);
FThreadList := TThreadList.Create;
FUniqueID := -1;
end;
destructor TTCPBase.Destroy;
begin
FThreadList.Free;
DoneCriticalsection(FTCP_CS);
inherited Destroy;
end;
function TTCPBase.FindThread(const AUniqueID: Integer): TBaseThread;
var
List: TList;
I: Integer;
begin
Result := nil;
List := FThreadList.LockList;
try
for I := 0 to List.Count - 1 do
begin
if (TBaseThread(List.Items[I]).FUniqueID = AUniqueID) then
begin
Result := TBaseThread(List.Items[I]);
Break;
end;
end;
finally
FThreadList.UnlockList;
end;
end;
function TTCPBase.IsMessageInvalid(const AMsg: String): Boolean;
begin
Result := False;
if Trim(AMsg) = '' then
Exit;
Result := AMsg[1] in ['0', '1', '2', '3'];
if Result then
raise Exception.Create('Messages cannot begin with "0", "1", "2" or "3"');
end;
function TTCPBase.SendMessage(AMsg: String; AParams: array of String;
const AUniqueID: Integer = 0): Boolean;
var
CT: TClientThread;
begin
Result := False;
if IsMessageInvalid(AMsg) then
Exit;
if FActiveOrConnected then
begin
case FTCPBaseType of
tcpClient: CT := TClientThread(TTCPClient(Self).FindThread(AUniqueID));
tcpServer: CT := TClientThread(TTCPServer(Self).FindThread(AUniqueID));
end;
if CT <> nil then
Result := CT.FTaskList.AddTask('MESSAGE', AMsg, AParams) <> -1;
end
end;
function TTCPBase.SendStream(AMsg: String; AParams: array of String;
AMS: TMemoryStream; const AUniqueID: Integer = 0): Boolean;
var
CT: TClientThread;
begin
Result := False;
if IsMessageInvalid(AMsg) then
Exit;
if FActiveOrConnected then
begin
case FTCPBaseType of
tcpClient: CT := TClientThread(TTCPClient(Self).FindThread(AUniqueID));
tcpServer: CT := TClientThread(TTCPServer(Self).FindThread(AUniqueID));
end;
if CT <> nil then
begin
if AMS.Size = 0 then
CT.DoError('Stream size is zero.', 0)
else
Result := CT.FTaskList.AddTask('STREAM', AMsg, AParams, AMS) <> -1;
end;
end;
end;
function TTCPBase.SendFile(AMsg: String; AParams: array of String;
AFileName: String; const AUniqueID: Integer): Boolean;
var
CT: TClientThread;
begin
if IsMessageInvalid(AMsg) then
Exit;
if FActiveOrConnected then
begin
case FTCPBaseType of
tcpClient: CT := TClientThread(TTCPClient(Self).FindThread(AUniqueID));
tcpServer: CT := TClientThread(TTCPServer(Self).FindThread(AUniqueID));
end;
if CT <> nil then
begin
if not FileExists(AFileName) then
CT.DoError('File does not exists.', 0)
else
Result := CT.FTaskList.AddTask('FILE', AMsg, AParams, nil, AFileName) <> -1;
end;
end;
end;
constructor TTCPClient.Create;
begin
inherited Create;
FActiveOrConnected := False;
FTCPBaseType := tcpClient;
end;
destructor TTCPClient.Destroy;
begin
Disconnect(False);
inherited Destroy;
end;
procedure TTCPClient.Remove(AThread: TBaseThread);
var
List: TList;
begin
case TClientThread(AThread).FClientType of
ctWorker:
begin
List := FThreadList.LockList;
try
List.Remove(AThread);
TClientThread(AThread).FNeedToBreak := True;
TClientThread(AThread).FBlockSocket.CloseSocket;
TClientThread(AThread).FDisconnected := True;
TClientThread(AThread).Terminate;
TClientThread(AThread).WaitFor;
TClientThread(AThread).Free;
AThread := nil;
finally
FThreadList.UnlockList;
end;
end;
ctMain:
Disconnect(False);
end;
end;
function TTCPClient.DoConnect(ACT: TClientThread): Boolean;
begin
Result := False;
ACT.FBlockSocket.Connect(ACT.FConnection.FIP, ACT.FConnection.FPort);
if ACT.FUseProxy then
begin
if (ACT.FConnection.FProxy.FProxyType = ptSocks5) or (ACT.FConnection.FProxy.FProxyType = ptSocks4) then
begin
if ACT.FBlockSocket.LastError = 0 then
begin
ACT.FBlockSocket.RecvPacket(TunnelTimeout);
Result := (ACT.FBlockSocket.LastError = 0) or ((ACT.FBlockSocket.LastError > 0) and (ACT.FBlockSocket.LastError = WSAETIMEDOUT));
end;
end
else
Result := (ACT.FBlockSocket.LastError = 0);
end
else
Result := (ACT.FBlockSocket.LastError = 0);
if Result then
Result := ACT.GetExtendedConnectionInfo;
end;
function TTCPClient.DoLogin(ACT: TClientThread): Integer;
var
Msg: String;
MsgTyp: Integer;
Params: TStringArray;
begin
Result := 0;
ACT.SendMessage('0LOGIN', [ACT.FConnection.FPass, ACT.FConnection.FUser, IntToStr(Ord(ACT.FClientType))]);
if (ACT.FBlockSocket.LastError > 0) then
Exit;
if ACT.RecvMessage(TimeOut, MsgTyp, Msg, Params) then
begin
Result := 1;
if (MsgTyp = 0) and (Msg = 'LOGINREPLY') then
begin
if (Params[0] = 'FAILEDINVALID') then
Result := 1
else if (Params[0] = 'FAILEDDUPLICATE') then
Result := 2
else if (Params[0] = 'SUCCESS') then
Result := 3
end;
end;
end;
procedure TTCPClient.Connect(const AConnection: TConnection);
var
Login: Integer;
CT: TClientThread;
begin
CT := TClientThread.Create(self);
CT.FClientType := ctMain;
CT.CopyConnection(AConnection, CT.FConnection);
CT.FUniqueID := 0;
CT.FConnection.FUniqueID := 0;
CT.FUseProxy := AConnection.FProxy.FProxyType <> ptNone;
if CT.FUseProxy then
CT.SetupProxy;
if DoConnect(CT) then
begin
FActiveOrConnected := True;
Login := DoLogin(CT);
case Login of
0: begin
FErrMsg := CT.FBlockSocket.LastErrorDesc;
FErrCode := CT.FBlockSocket.LastError;
FActiveOrConnected := False;
end;
1: begin
FErrMsg := rsInvalidUserNameOrPassword;
FErrCode := 10013;
FActiveOrConnected := False;
end;
2: begin
FErrMsg := rsInvalidDuplicateUser;
FErrCode := 10013;
FActiveOrConnected := False;
end;
3: begin
CT.DoConnect;
FThreadList.Add(CT);
CT.Start;
Exit;
end;
end;
end
else
begin
FErrMsg := CT.FBlockSocket.LastErrorDesc;
FErrCode := CT.FBlockSocket.LastError;
FActiveOrConnected := False;
end;
if Assigned(FOnError) then
FOnError(Self, FErrMsg, FErrCode, CT.FConnection);
CT.FBlockSocket.CloseSocket;
CT.Free;
CT := nil;
end;
procedure TTCPClient.Cleanup;
var
List: TList;
I: Integer;
Thread: TBaseThread;
begin
List := FThreadList.LockList;
try
for I := List.Count - 1 downto 0 do
begin
Thread := TBaseThread(List.Items[I]);
if Thread = nil then
Continue;
if (Thread.FBaseType = btClient) and (TClientThread(Thread).FClientType = ctMain) then
if Assigned(FOnDisconnect) then
FOnDisconnect(Self, TClientThread(Thread).FConnection, FByUser);
Thread.FNeedToBreak := True;
Thread.FBlockSocket.CloseSocket;
Thread.FDisconnected := True;
Thread.Terminate;
Thread.WaitFor;
Thread.Free;
Thread := nil;
end;
finally
FThreadList.UnlockList;
end;
FThreadList.Clear;
end;
procedure TTCPClient.Disconnect(const AByUser: Boolean);
begin
FByUser := AByUser;
FActiveOrConnected := False;
Cleanup;
end;
constructor TTCPServer.Create;
begin
inherited Create;
FActiveOrConnected := False;
FTCPBaseType := tcpServer;
FUserList := TStringList.Create;
end;
destructor TTCPServer.Destroy;
begin
FUserList.Clear;
FUserList.Free;
Stop;
inherited Destroy;
end;
procedure TTCPServer.Remove(AThread: TBaseThread);
var
List: TList;
UserID: Integer;
begin
case TBaseThread(AThread).FBaseType of
btServer_AcceptedClient:
begin
if Assigned(FOnDisconnect) then
FOnDisconnect(Self, TClientThread(AThread).FConnection, False);
List := FThreadList.LockList;
try
List.Remove(AThread);
UserID := FindUser(TClientThread(AThread).FConnection.FUser);
if UserID <> -1 then
FUserList.Delete(UserID);
TClientThread(AThread).FNeedToBreak := True;
TClientThread(AThread).FBlockSocket.CloseSocket;
TClientThread(AThread).FDisconnected := True;
TClientThread(AThread).Terminate;
TClientThread(AThread).WaitFor;
TClientThread(AThread).Free;
AThread := nil;
finally
FThreadList.UnlockList;
end;
end;
btServer:
Stop;
else
Exit;
end;
end;
function TTCPServer.FindUser(AUserName: String): Integer;
var
I: Integer;
begin
Result := -1;
for I := 0 to FUserList.Count - 1 do
begin
if UpperCase(FUserList.Strings[I]) = UpperCase(AUserName) then
begin
Result := I;
Break;
end;
end;
end;
procedure TTCPServer.DisconnectClient(AUniqueID: Integer);
var
List: TList;
I: Integer;
begin
List := FThreadList.LockList;
try
for I := List.Count - 1 downto 0 do
if TBaseThread(List.Items[I]).FUniqueID = AUniqueID then
begin
Remove(TBaseThread(List.Items[I]));
Break;
end;
finally
FThreadList.UnlockList;
end;
end;
function TTCPServer.IsClientConnected(AUniqueID: Integer): Boolean;
var
Thread: TBaseThread;
begin
Thread := FindThread(AUniqueID);
Result := (Thread <> nil) and (not Thread.FDisconnected);
end;
procedure TTCPServer.Start(ABindConnection: TConnection);
var
ST: TServerThread;
begin
ST := TServerThread.Create(Self);
with ST.FBlockSocket do
begin
ST.CopyConnection(ABindConnection, ST.FConnection);
ST.FUniqueID := 0;
CreateSocket;
SetLinger(True, 10000);
Bind(ST.FConnection.FIP, ST.FConnection.FPort);
Listen;
FActiveOrConnected := True;
if LastError = 0 then
begin
FThreadList.Add(ST);
ST.Start;
end
else
begin
ST.DoError(ST.FBlockSocket.LastErrorDesc, ST.FBlockSocket.LastError);
ST.Free;
FActiveOrConnected := False;
end;
end;
end;
procedure TTCPServer.Cleanup;
var
List: TList;
I: Integer;
Thread: TBaseThread;
begin
List := FThreadList.LockList;
try
for I := List.Count - 1 downto 0 do
begin
Thread := TBaseThread(List.Items[I]);
if Thread = nil then
Continue;
if (Thread.FBaseType = btServer_AcceptedClient) then
if Assigned(FOnDisconnect) then
FOnDisconnect(Self, TClientThread(Thread).FConnection, False);
Thread.FNeedToBreak := True;
Thread.FBlockSocket.CloseSocket;
Thread.FDisconnected := True;
Thread.Terminate;
Thread.WaitFor;
Thread.Free;
Thread := nil;
end;
finally
FThreadList.UnlockList;
end;
FThreadList.Clear;
end;
procedure TTCPServer.Stop;
begin
if FActiveOrConnected then
begin
FActiveOrConnected := False;
Cleanup;
end;
end;
end.
|
unit FrmMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TForm2 = class(TForm)
edtNome: TEdit;
Label1: TLabel;
edtIdade: TEdit;
Label2: TLabel;
edtTelefone: TEdit;
Label3: TLabel;
edtEmail: TEdit;
Label4: TLabel;
edtCPF: TEdit;
Label5: TLabel;
Label10: TLabel;
edtCEP: TEdit;
btnCadastrar: TButton;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
Label9: TLabel;
edtLogradouro: TEdit;
edtBairro: TEdit;
edtCidade: TEdit;
edtComplemento: TEdit;
Label11: TLabel;
edtNumero: TEdit;
Label12: TLabel;
edtUF: TEdit;
Label13: TLabel;
edtPais: TEdit;
btnBuscarCep: TButton;
procedure btnBuscarCepClick(Sender: TObject);
procedure btnCadastrarClick(Sender: TObject);
procedure enviarEamil(msg:String);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form2: TForm2;
implementation
{$R *.dfm}
uses
UnAPICep, //--CEP
IdSMTP, IdSSLOpenSSL, IdMessage, IdText, IdAttachmentFile,
IdExplicitTLSClientServerBase, //--Email
XMLDoc, Xml.XMLIntf; //-- XML
procedure TForm2.btnBuscarCepClick(Sender: TObject);
var
cep : TAPICep;
begin
try
try
cep := TAPICep.Create(edtCep.Text);
if (cep.RespCode = 200 ) then
begin
edtLogradouro.Text := cep.Logradouro;
edtBairro.Text := cep.Bairro;
edtComplemento.Text := cep.Complemento;
edtCidade.Text := cep.Localidade;
edtUF.Text := cep.UF;
edtPais.Text := 'Brasil';
end else begin
if (cep.RespCode = 400) then showMessage('CEP inválido ou não encontrado');
//-- if 500, 0, etc...
end;
except
on e: Exception do begin
showmessage('Erro ao consultar o cep'+#13#10+e.Message);
end;
end;
finally
FreeAndNil(cep);
end;
end;
procedure TForm2.btnCadastrarClick(Sender: TObject);
var
Doc: IXMLDocument;
cadastro: IXMLNode;
begin
Doc := NewXMLDocument;
cadastro := Doc.AddChild('Cadastro');
cadastro.Attributes['id'] := 'eec0-47de-91bc-98e2d69d75cd';
cadastro.AddChild('nome' ).Text := edtNome.Text;
cadastro.AddChild('idade' ).Text := edtIdade.Text;
cadastro.AddChild('cpf' ).Text := edtCPF.Text;
cadastro.AddChild('telefone' ).Text := edtTelefone.Text;
cadastro.AddChild('email' ).Text := edtEmail.Text;
cadastro.AddChild('logradouro' ).Text := edtLogradouro.Text;
cadastro.AddChild('cep' ).Text := edtCEP.Text;
cadastro.AddChild('numero' ).Text := edtNumero.Text;
cadastro.AddChild('complemento').Text := edtComplemento.Text;
cadastro.AddChild('bairro' ).Text := edtBairro.Text;
cadastro.AddChild('cidade' ).Text := edtCidade.Text;
cadastro.AddChild('uf' ).Text := edtUF.Text;
cadastro.AddChild('pais' ).Text := edtPais.Text;
enviarEamil(Doc.XML.Text);
end;
procedure TForm2.enviarEamil(msg: String);
var
IdSSLIOHandlerSocket: TIdSSLIOHandlerSocketOpenSSL;
IdSMTP: TIdSMTP;
IdMessage: TIdMessage;
IdText: TIdText;
sAnexo: string;
begin
IdSSLIOHandlerSocket := TIdSSLIOHandlerSocketOpenSSL.Create(Self);
IdSMTP := TIdSMTP.Create(Self);
IdMessage := TIdMessage.Create(Self);
try
// Configuração do protocolo SSL (TIdSSLIOHandlerSocketOpenSSL)
IdSSLIOHandlerSocket.SSLOptions.Method := sslvSSLv23;
IdSSLIOHandlerSocket.SSLOptions.Mode := sslmClient;
// Configuração do servidor SMTP (TIdSMTP)
IdSMTP.IOHandler := IdSSLIOHandlerSocket;
IdSMTP.UseTLS := utUseImplicitTLS;
IdSMTP.AuthType := satDefault;
IdSMTP.Port := 465;
IdSMTP.Host := 'smtp.gmail.com';
IdSMTP.Username := 'usuario@gmail.com';
IdSMTP.Password := 'senha';
// Configuração da mensagem (TIdMessage)
IdMessage.From.Address := 'remetente@gmail.com';
IdMessage.From.Name := 'Nome do Remetente';
IdMessage.ReplyTo.EMailAddresses := IdMessage.From.Address;
IdMessage.Recipients.Add.Text := 'destinatario1@email.com';
IdMessage.Recipients.Add.Text := 'destinatario2@email.com'; // opcional
IdMessage.Recipients.Add.Text := 'destinatario3@email.com'; // opcional
IdMessage.Subject := 'Assunto do e-mail';
IdMessage.Encoding := meMIME;
// Configuração do corpo do email (TIdText)
IdText := TIdText.Create(IdMessage.MessageParts);
IdText.Body.Add(msg); // corpo do email
IdText.ContentType := 'text/plain; charset=iso-8859-1';
// Opcional - Anexo da mensagem (TIdAttachmentFile)
sAnexo := 'C:\Anexo.pdf';
if FileExists(sAnexo) then
begin
TIdAttachmentFile.Create(IdMessage.MessageParts, sAnexo);
end;
// Conexão e autenticação
try
IdSMTP.Connect;
IdSMTP.Authenticate;
except
on E:Exception do
begin
MessageDlg('Erro na conexão ou autenticação: ' +
E.Message, mtWarning, [mbOK], 0);
Exit;
end;
end;
// Envio da mensagem
try
IdSMTP.Send(IdMessage);
MessageDlg('Mensagem enviada com sucesso!', mtInformation, [mbOK], 0);
except
On E:Exception do
begin
MessageDlg('Erro ao enviar a mensagem: ' +
E.Message, mtWarning, [mbOK], 0);
end;
end;
finally
IdSMTP.Disconnect;
UnLoadOpenSSLLibrary;
FreeAndNil(IdMessage);
FreeAndNil(IdSSLIOHandlerSocket);
FreeAndNil(IdSMTP);
end;
end;
end.
|
unit AqDrop.Core.Helpers.TRttiObject;
interface
uses
System.Rtti,
System.SysUtils,
AqDrop.Core.Collections.Intf;
type
TAqRttiObjectHelper = class helper for TRttiObject
strict private
procedure ForEachAttribute<T: TCustomAttribute>(const pProcessing: TFunc<T, Boolean>);
public
function GetAttribute<T: TCustomAttribute>(out pAttribute: T; const pOccurrence: UInt32 = 0): Boolean;
function GetAttributes<T: TCustomAttribute>(out pAttributes: IAqResultList<T>): Boolean; overload;
function HasAttribute<T: TCustomAttribute>: Boolean;
end;
implementation
uses
AqDrop.Core.Helpers.TArray,
AqDrop.Core.Collections;
{ TAqRttiObjectHelper }
function TAqRttiObjectHelper.GetAttribute<T>(out pAttribute: T; const pOccurrence: UInt32): Boolean;
var
lResult: Boolean;
lAttribute: T;
lOccurrence: UInt32;
begin
lResult := False;
lOccurrence := pOccurrence;
ForEachAttribute<T>(
function(pAttribute: T): Boolean
begin
lResult := lOccurrence = 0;
if lResult then
begin
lAttribute := pAttribute;
end else begin
Dec(lOccurrence);
end;
Result := not lResult;
end);
Result := lResult;
if Result then
begin
pAttribute := lAttribute;
end;
end;
function TAqRttiObjectHelper.GetAttributes<T>(out pAttributes: IAqResultList<T>): Boolean;
var
lResult: Boolean;
lList: TAqResultList<T>;
begin
lResult := False;
lList := nil;
try
ForEachAttribute<T>(
function(pProcessingAttribute: T): Boolean
begin
Result := True;
if not lResult then
begin
lList := TAqResultList<T>.Create;
end;
lResult := True;
lList.Add(pProcessingAttribute);
end);
except
lList.Free;
raise;
end;
Result := lResult;
if Result then
begin
pAttributes := lList;
end;
end;
function TAqRttiObjectHelper.HasAttribute<T>: Boolean;
var
lAttribute: T;
begin
Result := GetAttribute<T>(lAttribute);
end;
procedure TAqRttiObjectHelper.ForEachAttribute<T>(const pProcessing: TFunc<T, Boolean>);
begin
TAqArray<TCustomAttribute>.ForIn(GetAttributes,
function(pItem: TCustomAttribute): Boolean
begin
Result := not pItem.InheritsFrom(T) or pProcessing(T(pItem));
end);
end;
end.
|
unit PolynomsStek;
interface
uses
polynoms;
procedure initStek();
procedure push(const P : TPolynom); // кладём
function pop() : TPolynom; //вынимаем
function numbersPolynoms : integer;
implementation
type
PStek = record
PArray : array of TPolynom;
position : integer;
length : integer;
end;
var
stek : PStek;
procedure initStek();
begin
stek.position := -1;
stek.length := 10;
setlength(stek.PArray, stek.length);
end;
procedure expansion();
begin
inc(stek.position);
if stek.position >= stek.length then begin
stek.length := stek.length * 2;
setlength(stek.PArray, stek.length);
end;
end;
procedure push(const P : TPolynom); // кладём
begin
expansion();
CopyPolynoms(stek.PArray[stek.position], P);
end;
function pop() : TPolynom; //вынимаем
begin
CopyPolynoms(result, stek.PArray[stek.position]);
disposePolynom(stek.PArray[stek.position]);
stek.position := stek.position - 1;
end;
function numbersPolynoms : integer;
begin
result := stek.position + 1;
end;
end.
|
unit IdHMACSHA1;
interface
uses
IdHash, IdHashSHA1, IdHMAC, IdGlobal, IdObjs, IdSys;
type
TIdHMACSHA1 = class(TIdHMAC)
private
FHashSHA1: TIdHashSHA1;
protected
procedure InitHash; override;
function InternalHashValue(const ABuffer: TIdBytes) : TIdBytes; override;
end;
implementation
{ TIdHMACSHA1 }
procedure TIdHMACSHA1.InitHash;
begin
inherited;
FHashSHA1 := TIdHashSHA1.Create;
FHash := FHashSHA1;
FHashSize := 20;
FBlockSize := 64;
FHashName := 'SHA1';
end;
function TIdHMACSHA1.InternalHashValue(const ABuffer: TIdBytes): TIdBytes;
var
TempStream: TIdMemoryStream;
TempResult: T5x4LongWordRecord;
TempBuff: TIdBytes;
begin
TempStream := TIdMemoryStream.Create;
try
WriteTIdBytesToStream(TempStream, ABuffer);
TempStream.Position := 0;
TempResult := FHashSHA1.HashValue(TempStream);
SetLength(TempBuff, 4);
SetLength(Result, FHashSize);
TempBuff := ToBytes(TempResult[0]);
CopyTIdBytes(TempBuff, 0, Result, 0, 4);
TempBuff := ToBytes(TempResult[1]);
CopyTIdBytes(TempBuff, 0, Result, 4, 4);
TempBuff := ToBytes(TempResult[2]);
CopyTIdBytes(TempBuff, 0, Result, 8, 4);
TempBuff := ToBytes(TempResult[3]);
CopyTIdBytes(TempBuff, 0, Result, 12, 4);
TempBuff := ToBytes(TempResult[4]);
CopyTIdBytes(TempBuff, 0, Result, 16, 4);
finally
Sys.FreeAndNil(TempStream);
end;
end;
initialization
TIdHMACSHA1.Create.Destroy;
end.
|
unit qCDK103types;
interface
uses Classes,SysUtils;
const
////////// данные константы используются для описания свойств классов-помощников
ndxMilliseconds=0; ndxMinutes=1;
ndxRES1=2; ndxIV=3;
ndxHours=4; RES2=5;
ndxSU=6;
ndxDayOfMonth=7; ndxDayOfWeek=8;
ndxMonth=9; ndxYear=10;
ndxRES4=11;
ndxTP=12; ndxTM=13; ndxTEST=14; ndxOTEV=15;
ndxFCV=100; ndxFCB=101; ndxPRM=102; ndxRES=103;
ndxDFC=100; ndxACD=101;
//////////
////////// константы ошибок, дополняют список в uConnections
iecePosAck=100; // положительное подтверждение
ieceNegAck=101; // отрицательное подтверждение
ieceBroadCast=102; // широковещательная посылка
ieceUserData=108; // есть пользовательские данные
ieceNoUserData=109; // нет пользовательских данных
ieceChannelState=111; // состояние канала связи
ieceServiceUnavailable=114; // сервис не доступен
ieceServiceUnimplemented=115; // сервис не реализован
ieceControlFunctionCode=-100; // код функции неизвестен (или не реализован в данной версии протокола)
ieceLinkControlField=-101; // ожидается поле управления
ieceLinkAddress=-102; // ожидается адрес устройства
ieceTypeIdentification=-103; // ожидается идентификатор типа
ieceTypeIdentificationUnknown=-104; // идентификатор типа неизвестен (или не реализован в данной версии протокола)
ieceVariableStructureQualifier=-105;// ожидается классификатор переменной стуктуры (7.2.2)
ieceCauseOfTransmission=-106; // ожидается причина передачи COT (7.2.3)
ieceASDUAddress=-107; // ожидается ASDU адрес (7.2.4)
ieceFunctionType=-108; // ожидается тип функции FUN (7.2.5.1)
ieceInformationNumber=-109; // ожидается номер информации INF (7.2.5.2)
ieceCP56Time2a=-115; // ожидается время типа CP56Time2a (7.2.6.29)
ieceSCN=-116; // ожидается номер сканирования SCN (7.2.6.21)
ieceDCO=-117; // ожидается значение двухпозиционной команды DCO (7.2.6.4)
// ieceDCOinvalid=29; // неверное значение двухпозиционной команды DCO (7.2.6.4)
ieceRII=-119; // ожидается идентификатор возвращаемой информации RII (7.2.6.19)
ieceTOO=-120; // ожидается тип приказа TOO (7.2.6.26)
ieceTOV=-121; // ожидается тип аварийных значений TOV (7.2.6.27)
ieceFAN=-122; // ожидается номер повреждения FAN (7.2.6.6)
ieceACC=-123; // ожидается номер канала ACC (7.2.6.1)
ieceDPI=-124; // ожидается двухэлементная информация DPI (7.2.6.5)
ieceCP32Time2a=-125; // ожидается время типа CP32Time2a (7.2.6.28)
ieceSIN=-126; // ожидается значение дополнительной информации SIN (7.2.6.23)
ieceRET=-127; // ожидается относительное время RET (7.2.6.15)
ieceMEA=-128; // ожидается значение измеряемой величины MEA (7.2.6.8)
ieceSCL=-129; // ожидается расстояние до места короткого замыкания (7.2.6.20)
ieceCOL=-130; // ожидается уровень совместимости COL (7.2.6.3)
ieceASC=-131; // ожидается символ идентификации ASC (7.2.6.2)
ieceSoftwareID=-132; // ожидается байт внутреннего идентификатора программного обеспечения
ieceSOF=-133; // ожидается состояние повреждения SOF (7.2.6.24)
ieceNullByte=-134; // ожидается байт со значением 0
ieceNOF=-135; // ожидается номер повреждения сети NOF (7.2.6.12)
ieceNOC=-136; // ожидается число каналов NOC (7.2.6.10)
ieceNOE=-137; // ожидается число элементов информации в канале NOE (7.2.6.11)
ieceINT=-138; // ожидается интервал между элементами в канале INT (7.2.6.7)
ieceRPV=-139; // ожидается номинальное первичное значение RPV (7.2.6.17)
ieceRSV=-140; // ожидается номинальное вторичное значение RSV (7.2.6.18)
ieceRFA=-141; // ожидается масштабный коэффициент RFA (7.2.6.16)
ieceNOT=-142; // ожидается число меток NOT (7.2.6.13)
ieceTAP=-143; // ожидается положение метки TAP (7.2.6.25)
ieceNDV=-144; // ожидается число аварийных значений NDV (7.2.6.14)
ieceNFE=-145; // ожидается номер первого элемента информации NFE (7.2.6.9)
ieceSDV=-146; // ожидается одиночное аварийное значение SDV (7.2.6.22)
lwIEC103ErrorsCount=49;
IEC103ErrorsInfos:array[0..lwIEC103ErrorsCount-1]of TIdentMapEntry=(
(Value:iecePosAck; Name:'100 - положительное подтверждение'),
(Value:ieceNegAck; Name:'101 - отрицательное подтверждение'),
(Value:ieceBroadCast; Name:'102 - широковещательная посылка'),
(Value:ieceUserData; Name:'108 - есть пользовательские данные'),
(Value:ieceNoUserData; Name:'109 - нет пользовательских данных'),
(Value:ieceChannelState; Name:'111 - состояние канала связи'),
(Value:ieceServiceUnavailable; Name:'114 - сервис не доступен'),
(Value:ieceServiceUnimplemented; Name:'115 - сервис не реализован'),
(Value:ieceControlFunctionCode; Name:'-100 - код функции неизвестен (или не реализован в данной версии протокола)'),
(Value:ieceLinkControlField; Name:'-101 - ожидается поле управления'),
(Value:ieceLinkAddress; Name:'-102 - ожидается адрес устройства'),
(Value:ieceTypeIdentification; Name:'-103 - ожидается идентификатор типа'),
(Value:ieceTypeIdentificationUnknown; Name:'-104 - идентификатор типа неизвестен (или не реализован в данной версии протокола)'),
(Value:ieceVariableStructureQualifier; Name:'-105 - ожидается классификатор переменной стуктуры (7.2.2)'),
(Value:ieceCauseOfTransmission; Name:'-106 - ожидается причина передачи COT (7.2.3)'),
(Value:ieceASDUAddress; Name:'-107 - ожидается ASDU адрес (7.2.4)'),
(Value:ieceFunctionType; Name:'-108 - ожидается тип функции FUN (7.2.5.1)'),
(Value:ieceInformationNumber; Name:'-109 - ожидается номер информации INF (7.2.5.2)'),
(Value:ieceCP56Time2a; Name:'-115 - ожидается время типа CP56Time2a (7.2.6.29)'),
(Value:ieceSCN; Name:'-116 - ожидается номер сканирования SCN (7.2.6.21)'),
(Value:ieceDCO; Name:'-117 - ожидается значение двухпозиционной команды DCO (7.2.6.4)'),
(Value:ieceRII; Name:'-119 - ожидается идентификатор возвращаемой информации RII (7.2.6.19)'),
(Value:ieceTOO; Name:'-120 - ожидается тип приказа TOO (7.2.6.26)'),
(Value:ieceTOV; Name:'-121 - ожидается тип аварийных значений TOV (7.2.6.27)'),
(Value:ieceFAN; Name:'-122 - ожидается номер повреждения FAN (7.2.6.6)'),
(Value:ieceACC; Name:'-123 - ожидается номер канала ACC (7.2.6.1)'),
(Value:ieceDPI; Name:'-124 - ожидается двухэлементная информация DPI (7.2.6.5)'),
(Value:ieceCP32Time2a; Name:'-125 - ожидается время типа CP32Time2a (7.2.6.28)'),
(Value:ieceSIN; Name:'-136 - ожидается значение дополнительной информации SIN (7.2.6.23)'),
(Value:ieceRET; Name:'-127 - ожидается относительное время RET (7.2.6.15)'),
(Value:ieceMEA; Name:'-128 - ожидается значение измеряемой величины MEA (7.2.6.8)'),
(Value:ieceSCL; Name:'-129 - ожидается расстояние до места короткого замыкания (7.2.6.20)'),
(Value:ieceCOL; Name:'-130 - ожидается уровень совместимости COL (7.2.6.3)'),
(Value:ieceASC; Name:'-131 - ожидается символ идентификации ASC (7.2.6.2)'),
(Value:ieceSoftwareID; Name:'-132 - ожидается байт внутреннего идентификатора программного обеспечения'),
(Value:ieceSOF; Name:'-133 - ожидается состояние повреждения SOF (7.2.6.24)'),
(Value:ieceNullByte; Name:'-134 - ожидается байт со значением 0'),
(Value:ieceNOF; Name:'-135 - ожидается номер повреждения сети NOF (7.2.6.12)'),
(Value:ieceNOC; Name:'-136 - ожидается число каналов NOC (7.2.6.10)'),
(Value:ieceNOE; Name:'-137 - ожидается число элементов информации в канале NOE (7.2.6.11)'),
(Value:ieceINT; Name:'-138 - ожидается интервал между элементами в канале INT (7.2.6.7)'),
(Value:ieceRPV; Name:'-139 - ожидается номинальное первичное значение RPV (7.2.6.17)'),
(Value:ieceRSV; Name:'-140 - ожидается номинальное вторичное значение RSV (7.2.6.18)'),
(Value:ieceRFA; Name:'-141 - ожидается масштабный коэффициент RFA (7.2.6.16)'),
(Value:ieceNOT; Name:'-142 - ожидается число меток NOT (7.2.6.13)'),
(Value:ieceTAP; Name:'-143 - ожидается положение метки TAP (7.2.6.25)'),
(Value:ieceNDV; Name:'-144 - ожидается число аварийных значений NDV (7.2.6.14)'),
(Value:ieceNFE; Name:'-145 - ожидается номер первого элемента информации NFE (7.2.6.9)'),
(Value:ieceSDV; Name:'-146 - ожидается одиночное аварийное значение SDV (7.2.6.22)')
);
////////// описание поля управления
iUnused=7;
{
Link Control Field - поле управления
MSB LSB
7 6 5 4 3..0
RES PRM FCB FCV Код_функции
RES - резерв
PRM = 1 - для управляющего (control direction), первичная станция, сообщение от первичной станции к вторичной
FCB - бит счёта кадров, чередующиеся 0 и 1 при последовательных передачах ПОСЫЛКА/ПОДТВЕРЖДЕНИЕ или ЗАПРОС/ОТВЕТ
если ожидаемый ответ отсутствует или искажается, то ПОСЫЛКА/ПОДТВЕРЖДЕНИЕ или ЗАПРОС/ОТВЕТ повторяется с тем же FCB
при команде сброса бит FCB всегда равен 0, а после приёма этой команды вторичная станция всегда ожидает следующий кадр
от первичной станции с FCV, равным 1, чтобы установить FCB=1
FCV - законность бита счёта кадров:
0 - изменение бита FCB неверно, 1 - верно
Для процедуры ПОСЫЛКА/БЕЗ ОТВЕТА при циркулярных сообщениях и т.п. процедур, в которых не контролируются потери и дублирование
сообщений, бит FCB не меняется, а нарушения указываются обнулением бита FCV
MSB LSB
7 6 5 4 3..0
RES PRM ACD DFC Код_функции
PRM = 0 - для управляемого (monitor direction), вторичная станция, сообщение от вторичной станции к первичной
DFC - контроль потока данных:
0 - приём сообщений возможен, 1 - приём сообщений невозможен из-за переполнения буфера
ACD - бит требования запроса данных:
0 - нет данных класса 1 на передачу, 1 - есть
}
////////// тип кадра Frame Type
// для первичной
ft1SendAck=0; // ПОСЫЛКА/ПОДТВЕРЖДЕНИЕ
ft1Req=1; // ЗАПРОС БЕЗ ОТВЕТА
ft1ReqRes=2; // ЗАПРОС/ОТВЕТ
// для вторичной
ft2Ack=3; // ПОДТВЕРЖДЕНИЕ, acknowledge
ft2Res=4; // ОТВЕТ, response
// должны вызывать исключение
ftReserved=5; // резерв
ftNotUsed=6; // не используется
////////// константы кодов функций управления Function Code
// для первичной
fc1ResetCommUnit=0;
fc1UserSend=3; fc1UserBroadcast=4;
fc1ResetFCB=7; fc1ChannelState=9;
fc1Class1=10; fc1Class2=11;
// для вторичной
fc2PosAck=0; fc2NegAck=1;
fc2UserData=8; fc2NoUserData=9;
fc2ChannelState=11;
fc2ServiceUnavailable=14; fc2ServiceUnimplemented=15;
////////// константы ASDU Type Identification
// для первичной
ti1TimeSynchronization=6; // синхронизация времени
ti1GeneralInterrogation=7; // общий опрос
ti1GenericInfo=10; // групповая информация
ti1GeneralCommand=20; // общая команда
ti1GenericCommand=21; // групповая команда
ti1FaultOrder=24; // приказ передачи данных о нарушениях (выбор нарушения, запрос/отмена передачи меток и данных аналоговых каналов)
ti1FaultAcknowledge=25; // подтверждение передачи данных о нарушениях - положительное или отрицательное
// для вторичной
ti2TimeTag=1; // сообщение с меткой времени
ti2RelativeTimeTag=2; // сообщение с меткой относительного времени
ti2MeasuredValues1=3; // измеряемые величины, набор типа 1
ti2ShortCircuitLocation=4; // место короткого замыкания
ti2IdentificationInfo=5; // идентификационная информация
ti2TimeSynchronization=6; // синхронизация времени
ti2GeneralInterrogationTermination=8; // завершение общего опроса
ti2MeasuredValues2=9; // измеряемые величины, набор типа 2
ti2GenericInfo=10; // групповая информация
ti2GenericIdentifier=11; // групповой идентификатор
ti2FaultsList=23; // список зарегистрированных нарушений
ti2FaultDataReady=26; // готовность к передаче данных о нарушениях
ti2FaultChannelReady=27; // готовность к передаче данных аналогового канала
ti2FaultTagsReady=28; // готовность к передаче меток
ti2FaultTagsTransmission=29; // передача меток
ti2FaultValuesTransmission=30; // передача аварийных значений
ti2FaultTransmissionTermination=31; // завершение передачи данных о нарушениях
////////// константы причины передачи Cause Of Transmission
// для первичной
cot1TimeSynchronization=8; // синхронизация времени
cot1GeneralInterrogation=9; // инициализация общего опроса
cot1GeneralCommand=20; // общая команда
cot1FaultTransmission=31; // передача данных о нарушениях
cot1GenericWriteCommand=40; // групповая команда записи
cot1GenericReadCommand=41; // групповая команда чтения
// для вторичной
cot2Sporadic=1; // спорадическая
cot2Cyclic=2; // циклическая
cot2ResetFCB=3; // сброс бита счёта кадров FCB
cot2ResetCommUnit=4; // сброс подсистемы связи CU
cot2StartRestart=5; // старт/рестарт
cot2PowerOn=6; // включение питания
cot2TestMode=7; // тестовый режим
cot2TimeSynchronization=8; // синхронизация времени
cot2GeneralInterrogation=9; // общий опрос
cot2GeneralInterrogationTermination=10; // завершение общего опроса
cot2LocalOperation=11; // местная операция
cot2RemoteOperation=12; // удалённая операция
cot2GeneralCommandPosAck=20; // положительное подтверждение команды
cot2GeneralCommandNegAck=21; // отрицательное подтверждение команды
cot2FaultDataTransmission=31; // передача данных о неисправностях
cot2GenericWriteCommandPosAck=40; // положительное подтверждение групповой команды записи
cot2GenericWriteCommandNegAck=41; // отрицательное подтверждение групповой команды записи
cot2GenericReadCommandValid=42; // ответ правильными данными на групповую команду чтения
cot2GenericReadCommandNotValid=43; // ответ на групповую команду чтения данными, среди которых могут быть неправильные
cot2GenericWriteAck=44; // подтверждение групповой записи
////////// константы типа приказа для нарушений
// для первичной
// для ASDU24
too1FaultSelect=1; // выбор повреждения
too1FaultDataRequest=2; // запрос данных о нарушениях
too1FaultDataAbort=3; // преждевременное прекращение данных о нарушениях
too1FaultChannelRequest=8; // запрос канала
too1FaultChannelAbort=9; // преждевременное прекращение канала
too1FaultTagsRequest=16; // запрос меток
too1FaultTagsAbort=17; // преждевременное прекращение меток
too1FaultsListRequest=24; // запрос списка зарегистрированных нарушений
// для ASDU25
too1FaultDataSuccess=64; // данные о нарушениях переданы успешно (положительно)
too1FaultDataFailed=65; // данные о нарушениях переданы неуспешно (отрицательно)
too1FaultChannelSucces=66; // передача канала успешна (положительно)
too1FaultChannelFailed=67; // передача канала неуспешна (отрицательно)
too1FaultTagsSuccess=68; // метки переданы успешно (положительно)
too1FaultTagsFailed=69; // метки переданы неуспешно (отрицательно)
// для вторичной
// для ASDU31
too2FaultDataEnd=32; // окончание передачи данных о нарушениях без преждевременного прекращения
too2FaultDataSystemAbort=33; // окончание передачи данных о нарушениях с преждевременным прекращением системой управления
too2FaultDataDeviceAbort=34; // окончание передачи данных о нарушениях с преждевременным прекращением устройством защиты
too2FaultChannelEnd=35; // окончание передачи канала без преждевременного прекращения
too2FaultChannelSystemAbort=36; // окончание передачи канала с преждевременным прекращением системой управления
too2FaultChannelDeviceAbort=37; // окончание передачи канала с преждевременным прекращением устройством защиты
too2FaultTagsEnd=38; // окончание передачи меток без преждевременного прекращения
too2FaultTagsSystemAbort=39; // окончание передачи меток с преждевременным прекращением системой управления
too2FaultTagsDeviceAbort=40; // окончание передачи меток с преждевременным прекращением устройством защиты
////////// константы типа аварийных значений
tovInstantaneousValues=1;
type
FCinfo=packed record
_fc:integer; // код функции управления
_ft:integer; // тип кадра
_fcv:byte; // значение бита FCV для этого кода, неизвестно (7) для _ft равного ftReserved и ftNotUsed
_sDecription:PAnsiChar; // назначение функционального кода
end;
const
FCinfos1:array[0..15]of FCinfo=( // все коды для первичной станции
(_fc: fc1ResetCommUnit; _ft:ft1SendAck; _fcv: 0; _sDecription:'сброс удалённого канала'),
(_fc: 1; _ft:ftNotUsed; _fcv: 0; _sDecription:'сброс процесса пользователя'),
(_fc: 2; _ft:ftReserved; _fcv: iUnused; _sDecription:'резерв для балансной процедуры передачи'),
(_fc: fc1UserSend; _ft:ft1SendAck; _fcv: 1; _sDecription:'пользовательские данные, подтверждение'),
(_fc: fc1UserBroadcast; _ft:ft1Req; _fcv: 0; _sDecription:'пользовательские данные, без ответа'),
(_fc: 5; _ft:ftReserved; _fcv: iUnused; _sDecription:'резерв'),
(_fc: 6; _ft:ftReserved; _fcv: iUnused; _sDecription:'резерв для использования по согласованию'),
(_fc: fc1ResetFCB; _ft:ft1SendAck; _fcv: 0; _sDecription:'сброс FCB'),
(_fc: 8; _ft:ftNotUsed; _fcv: 0; _sDecription:'запрос доступа'),
(_fc: fc1ChannelState; _ft:ft1ReqRes; _fcv: 0; _sDecription:'запрос о состоянии канала связи'),
(_fc: fc1Class1; _ft:ft1ReqRes; _fcv: 1; _sDecription:'запрос данных класса 1'),
(_fc: fc1Class2; _ft:ft1ReqRes; _fcv: 1; _sDecription:'запрос данных класса 2'),
(_fc: 12; _ft:ftReserved; _fcv: iUnused; _sDecription:'резерв'),
(_fc: 13; _ft:ftReserved; _fcv: iUnused; _sDecription:'резерв'),
(_fc: 14; _ft:ftReserved; _fcv: iUnused; _sDecription:'резерв для использования по согласованию'),
(_fc: 15; _ft:ftReserved; _fcv: iUnused; _sDecription:'резерв для использования по согласованию')
);
FCinfos2:array[0..15]of FCinfo=( // все коды для вторичной станции, _fcv не используется
(_fc: fc2PosAck; _ft:ft2Ack; _fcv: iUnused; _sDecription:'положительная квитанция'),
(_fc: fc2NegAck; _ft:ft2Ack; _fcv: iUnused; _sDecription:'отрицательная квитанция'),
(_fc: 2; _ft:ftReserved; _fcv: iUnused; _sDecription:'резерв'),
(_fc: 3; _ft:ftReserved; _fcv: iUnused; _sDecription:'резерв'),
(_fc: 4; _ft:ftReserved; _fcv: iUnused; _sDecription:'резерв'),
(_fc: 5; _ft:ftReserved; _fcv: iUnused; _sDecription:'резерв'),
(_fc: 6; _ft:ftReserved; _fcv: iUnused; _sDecription:'резерв для использования по согласованию'),
(_fc: 7; _ft:ftReserved; _fcv: iUnused; _sDecription:'резерв для использования по согласованию'),
(_fc: fc2UserData; _ft:ft2Res; _fcv: iUnused; _sDecription:'пользовательские данные присутствуют'),
(_fc: fc2NoUserData; _ft:ft2Res; _fcv: iUnused; _sDecription:'пользовательские данные отсутствуют, отрицательная квитанция'),
(_fc: 10; _ft:ftReserved; _fcv: iUnused; _sDecription:'резерв'),
(_fc: fc2ChannelState; _ft:ft2Res; _fcv: iUnused; _sDecription:'состояние канала связи или запрос доступа'),
(_fc: 12; _ft:ftReserved; _fcv: iUnused; _sDecription:'резерв'),
(_fc: 13; _ft:ftReserved; _fcv: iUnused; _sDecription:'резерв для использования по согласованию'),
(_fc: fc2ServiceUnavailable; _ft:ft2Res; _fcv: iUnused; _sDecription:'сервисные услуги не работают, есть неисправность'), // бит FCB должен поменяться
(_fc: fc2ServiceUnimplemented; _ft:ft2Res; _fcv: iUnused; _sDecription:'сервисные услуги не предусмотрены') // бит FCB должен поменяться
);
TIinfos1:array[0..6]of TIdentMapEntry=(
(Value: ti1TimeSynchronization; Name: 'синхронизация времени'),
(Value: ti1GeneralInterrogation; Name: 'общий опрос'),
(Value: ti1GenericInfo; Name: 'групповая информация'),
(Value: ti1GeneralCommand; Name: 'общая команда'),
(Value: ti1GenericCommand; Name: 'групповая команда'),
(Value: ti1FaultOrder; Name: 'приказ передачи данных о нарушениях (выбор нарушения, запрос/отмена передачи меток и данных аналоговых каналов)'),
(Value: ti1FaultAcknowledge; Name: 'подтверждение передачи данных о нарушениях (положительное или отрицательное)')
);
TIinfos2:array[0..16]of TIdentMapEntry=(
(Value: ti2TimeTag; Name: 'сообщение с меткой времени'),
(Value: ti2RelativeTimeTag; Name: 'сообщение с меткой относительного времени'),
(Value: ti2MeasuredValues1; Name: 'измеряемые величины, набор типа 1'),
(Value: ti2ShortCircuitLocation; Name: 'место короткого замыкания'),
(Value: ti2IdentificationInfo; Name: 'идентификационная информация'),
(Value: ti2TimeSynchronization; Name: 'синхронизация времени'),
(Value: ti2GeneralInterrogationTermination; Name: 'завершение общего опроса'),
(Value: ti2MeasuredValues2; Name: 'измеряемые величины, набор типа 2'),
(Value: ti2GenericInfo; Name: 'групповая информация'),
(Value: ti2GenericIdentifier; Name: 'групповой идентификатор'),
(Value: ti2FaultsList; Name: 'список зарегистрированных нарушений'),
(Value: ti2FaultDataReady; Name: 'готовность к передаче данных о нарушениях'),
(Value: ti2FaultChannelReady; Name: 'готовность к передаче данных аналогового канала'),
(Value: ti2FaultTagsReady; Name: 'готовность к передаче меток'),
(Value: ti2FaultTagsTransmission; Name: 'передача аварийных значений'),
(Value: ti2FaultValuesTransmission; Name: 'передача меток'),
(Value: ti2FaultTransmissionTermination; Name: 'завершение передачи данных о нарушениях')
);
COTinfos1:array[0..5]of TIdentMapEntry=(
(Value: cot1TimeSynchronization; Name: 'синхронизация времени'),
(Value: cot1GeneralInterrogation; Name: 'инициализация общего опроса'),
(Value: cot1GeneralCommand; Name: 'общая команда'),
(Value: cot1FaultTransmission; Name: 'передача данных о нарушениях'),
(Value: cot1GenericWriteCommand; Name: 'групповая команда записи'),
(Value: cot1GenericReadCommand; Name: 'групповая команда чтения')
);
COTinfos2:array[0..19]of TIdentMapEntry=(
(Value: cot2Sporadic; Name: 'спорадическая'),
(Value: cot2Cyclic; Name: 'циклическая'),
(Value: cot2ResetFCB; Name: 'сброс бита счёта кадров FCB'),
(Value: cot2ResetCommUnit; Name: 'сброс подсистемы связи CU'),
(Value: cot2StartRestart; Name: 'старт/рестарт'),
(Value: cot2PowerOn; Name: 'включение питания'),
(Value: cot2TestMode; Name: 'тестовый режим'),
(Value: cot2TimeSynchronization; Name: 'синхронизация времени'),
(Value: cot2GeneralInterrogation; Name: 'общий опрос'),
(Value: cot2GeneralInterrogationTermination; Name: 'завершение общего опроса'),
(Value: cot2LocalOperation; Name: 'местная операция'),
(Value: cot2RemoteOperation; Name: 'удалённая операция'),
(Value: cot2GeneralCommandPosAck; Name: 'положительное подтверждение команды'),
(Value: cot2GeneralCommandNegAck; Name: 'отрицательное подтверждение команды'),
(Value: cot2FaultDataTransmission; Name: 'передача данных о неисправностях'),
(Value: cot2GenericWriteCommandPosAck; Name: 'положительное подтверждение групповой команды записи'),
(Value: cot2GenericWriteCommandNegAck; Name: 'отрицательное подтверждение групповой команды записи'),
(Value: cot2GenericReadCommandValid; Name: 'ответ правильными данными на групповую команду чтения'),
(Value: cot2GenericReadCommandNotValid; Name: 'ответ на групповую команду чтения данными, среди которых могут быть неправильные'),
(Value: cot2GenericWriteAck; Name: 'подтверждение групповой записи')
);
TOOinfos1:array[0..13]of TIdentMapEntry=(
// для ASDU24
(Value: too1FaultSelect; Name: 'выбор повреждения'),
(Value: too1FaultDataRequest; Name: 'запрос данных о нарушениях'),
(Value: too1FaultDataAbort; Name: 'преждевременное прекращение данных о нарушениях'),
(Value: too1FaultChannelRequest; Name: 'запрос канала'),
(Value: too1FaultChannelAbort; Name: 'преждевременное прекращение канала'),
(Value: too1FaultTagsRequest; Name: 'запрос меток'),
(Value: too1FaultTagsAbort; Name: 'преждевременное прекращение меток'),
(Value: too1FaultsListRequest; Name: 'запрос списка зарегистрированных нарушений'),
// для ASDU25
(Value: too1FaultDataSuccess; Name: 'данные о нарушениях переданы успешно (положительно)'),
(Value: too1FaultDataFailed; Name: 'данные о нарушениях переданы неуспешно (отрицательно)'),
(Value: too1FaultChannelSucces; Name: 'передача канала успешна (положительно)'),
(Value: too1FaultChannelFailed; Name: 'передача канала неуспешна (отрицательно)'),
(Value: too1FaultTagsSuccess; Name: 'метки переданы успешно (положительно)'),
(Value: too1FaultTagsFailed; Name: 'метки переданы неуспешно (отрицательно)')
);
TOOinfos2:array[0..8]of TIdentMapEntry=(
// для ASDU31
(Value: too2FaultDataEnd; Name: 'окончание передачи данных о нарушениях без преждевременного прекращения'),
(Value: too2FaultDataSystemAbort; Name: 'окончание передачи данных о нарушениях с преждевременным прекращением системой управления'),
(Value: too2FaultDataDeviceAbort; Name: 'окончание передачи данных о нарушениях с преждевременным прекращением устройством защиты'),
(Value: too2FaultChannelEnd; Name: 'окончание передачи канала без преждевременного прекращения'),
(Value: too2FaultChannelSystemAbort; Name: 'окончание передачи канала с преждевременным прекращением системой управления'),
(Value: too2FaultChannelDeviceAbort; Name: 'окончание передачи канала с преждевременным прекращением устройством защиты'),
(Value: too2FaultTagsEnd; Name: 'окончание передачи меток без преждевременного прекращения'),
(Value: too2FaultTagsSystemAbort; Name: 'окончание передачи меток с преждевременным прекращением системой управления'),
(Value: too2FaultTagsDeviceAbort; Name: 'окончание передачи меток с преждевременным прекращением устройством защиты')
);
type
////////// типы IEC
tagBIT=0..1; // 1битная информация
tag1BIT=tagBIT; // 1битная информация
tag2BIT=0..3; // 2битная информация
tag4BIT=0..15; // 4битная информация
// 7.2.6.1 Текущий канал
// ACC:=UI8[1..8]<1..255>
// байт указывает текущий канал, который должен обрабатываться при передаче данных о нарушениях, где
// 0 - глобальный, используется только в ASDU 24, 25 и 31, если данные канала не должны передаваться
// 1..8 - Ia, Ib, Ic, In, Vae, Vbe, Vce, Ven
// 9..63 - резерв для дальнейших совместимых определений
// 64..255 - резерв для частного использования
tagACC=byte;
// 7.2.6.2 Символ ASCII
// ASC:=UI8[1..8]<ASCII 8битный код>
tagASC=AnsiChar;
// 7.2.6.3 Уровень совместимости
// COL:=UI8[1..8]<0..255>
// Уровень совместимости устройства защиты, основанного на требованиях стандарта,
// равен 2 - без использования групповых услуг, 3 - с использованием групповых услуг
tagCOL=byte;
// 7.2.6.4 Двухпозиционная команда
// DCO:=UI[1..2]<0..3>
// 0 - не используется, 1 - ОТКЛ, 2 - ВКЛ, 3 - не используется
tagDCO=0..3;
// 7.2.6.5 Двухэлементная информация
// DPI:=UI[1..2]<0..3>
// 0 - не используется, 1 - ОТКЛ, 2 - ВКЛ, 3 - не используется
tagDPI=0..3;
// 7.2.6.6 Номер повреждения
// FAN:=UI16[1..16]<1..65535>
// Номер повреждения используется для опознавания события, связанного с функциями защиты, например, сигнал запуска от устройства
// защиты увеличивает номер повреждения. Это значит, что последовательность с неуспешным АПВ будет регистрироваться как два отдельных
// повреждения со своими номерами. Номер повреждения не нужно ни сбрасывать, ни предварительно устанавливать.
tagFAN=word;
// 7.2.6.7 Интервал между элементами информации
// INT:=UI16[1..16]<1..65535>
// Интервал сбора одиночных элементов информации должен быть одинаковым для всех данных о нарушениях. Указывается в микросекундах.
tagINT=word;
// 7.2.6.8 Измеряемая величина с описателем качества
// MEA:=CP16{OV,ER,RES,MVAL}, где
// OV:=BS1[1]<0..1> 0 - нет переполнения, 1 - переполнение
// ER:=BS1[2]<0..1> 0 - MVAL правильное значение, 1 - MVAL неправильное значение
// RES:=BS1[3]<0..1> не используется, всегда 0
// MVAL:=F13[4..16]<-1..+1-2**(-12)>
// В случае переполнения MVAL устанавливается его максимальное положительное или отрицательное значение в дополнение к OV:=1.
// Максимальное значение MVAL должно быть +-1.2 или +-2.4 номинального.
// Другие форматы и диапазоны могут использоваться с групповыми услугами.
tagMEA=word; // для доступа к битам использовать TMEA(@varMEA).OV, TMEA(@varMEA).ER
PtagMEA=^tagMEA; // указатель на тип tagMEA
// 7.2.6.9 Номер первого элемента информации в ASDU
// NFE:=UI16[1..16]<0..65535>
// Все одиночные значения данных о нарушении в канале (файле) имеют последовательные номера и передаются однородными частями.
// В составе ASDU они передаются с последовательно возрастающими номерами. Для того, чтобы иметь возможность правильно восстановить файл,
// указывается номер первого аварийного значения (первого элемента информации) в ASDU
tagNFE=word;
// 7.2.6.10 Число каналов
// NOC:=UI8[1..8]<0..255>
// Этот байт показывает число аналоговых каналов набора передаваемых данных, готовых к передаче.
tagNOC=byte;
// 7.2.6.11 Число элементов информации в канале
// NOE:=UI16[1..16]<1..65535>
// Все каналы содерждат одинаковое число элементов информации.
// Это число передаётся в ASDU26 "готовность к передаче данных о нарушениях" и справедливо для всех каналов.
tagNOE=word;
// 7.2.6.12 Номер повреждения сети
// NOF:=UI16[1..16]<1..65535>
// Повреждение сети, например, короткое замыкание, может вызвать несколько аварийных событий с отключением и последующим АПВ,
// каждое из которых идентифицируется увеличением номера повреждения FAN. В этом случае номер повреждения сети остаётся неизменным,
// общим для этих событий. Номер повреждения сети не требуется ни сбрасывать, ни предварительно устанавливать.
tagNOF=word;
// 7.2.6.13 Число меток
// NOT:=UI8[1..8]<0..255>
// Этот байт показывает число меток, передаваемых в ASDU29
tagNOT=byte;
// 7.2.6.14 Число аварийных значений в ASDU30
// NDV:=UI8[1..8]<0..255>
tagNDV=byte;
// 7.2.6.15 Относительное время
// RET:=UI16[1..16]<1..65535>
// Относительное время устанавливается в 0 в начале короткого замыкания. Оно указывает время в мс от запуска устройства защиты до текущего момента.
tagRET=word;
// 7.2.6.16 Масштабный коэффициент
// RFA:=R32.23 {мантисса, порядок, знак}
// Значения аварийных данных передаются как относительные значения в формате чисел с фиксированной запятой.
// Масштабный коэффициент показывает соотношение между относительными и вторичными значениями.
//
// относительное значение
// Масштабный коэффициент RFA = _________________________
// вторичное значение
//
// Первичное значение равно вторичному значению, умноженному на отношение номинального первичного значения
// к номинальному вторичному значению:
//
// номинальное первичное значение относительное значение номинальное первичное значение
// Первичное значение = вторичное значение X ___________________________________ = _________________________ X __________________________________
// номинальное вторичное значение масштабный коэффициент номинальное вторичное значение
//
tagRFA=Single;
// 7.2.6.17 Номинальное первичное значение
// RPV:=R32.23 {мантисса, порядок, знак}
tagRPV=Single;
// 7.2.6.18 Номинальное вторичное значение
// RPV:=R32.23 {мантисса, порядок, знак}
tagRSV=Single;
// 7.2.6.20 Расстояние до места короткого замыкания
// SCL:=R32.23 {мантисса, порядок, знак}
// Расстояние до места короткого замыкания представляется в форме реактивного сопротивления, приведённого к первичным значениям. Оно выражается в омах.
tagSCL=Single;
// 7.2.6.21 Номер опроса
// SCN:=UI8[1..8]<0..255>
tagSCN=byte;
// 7.2.6.22 Одиночное аварийное значение
// SDV:=F16[1..16]<-1+1-2**(-15)>
tagSDV=SmallInt;
// 7.2.6.23 Дополнительная информация
// SIN:=UI8[1..8]<0.255>
// Дополнительная информация используется следующим образом:
// Причина передачи SIN
// общий опрос НОМЕР ОПРОСА ASDU, инициирующего GI
// положительное или отрицательное подтверждение команды ИДЕНТИФИКАТОР ВОЗВРАЩАЕМОЙ ИНФОРМАЦИИ командного сообщения
// другая несущественно
tagSIN=byte;
// 7.2.6.24 Состояние повреждения
// SOF:=BS8{TP,TM,TEST,OTEV,RES}, где
// TP:=BS1[1], 0 - регистрация повреждения без отключения, 1 - с отключением
// TM:=BS1[2], 0 - данные о нарушении, ожидающие передачи, 1 - передаваемые в данный момент
// TEST:=BS1[3], 0 - данные о нарушении, регистрируемые в рабочем режиме, 1 - в тестовом
// OTEV:=BS1[4], 0 - регистрация данных о нарушении, инициируемая запуском защиты, 1 - другими событиями
// RES:=BS4[5..8] - не используется
tagSOF=byte;
PtagSOF=^tagSOF;
// 7.2.6.25 Положение метки
// TAP:=UI16[1..16]<1..65535>
// Эти два байта показывают положение метки внутри набора данных о нарушении. Это число есть расстояние метки от первого
// элемента в наборе данных о нарушении, закодированное как число элементов информации по модулю 65536. Положение первой
// метки равно нулю.
tagTAP=word;
// 7.2.6.26 Тип приказа
// TOO:=UI8[1..8]<0..255>
// ASDU24 (приказ о передаче данных о нарушениях) - <1..31>,
// ASDU32 (окончание передачи данных о нарушениях) - <32..63>,
// ASDU25 (подтверждение передачи данных о нарушениях) - <64..95>
//
// 1: выбор подтверждения; 2: запрос данных о нарушениях; 3: преждевременное прекращение данных о нарушениях;
// 4..7: резерв
// 8: запрос канала; 9: преждевременное прекращение канала;
// 10..15: резерв
// 16: запрос меток; 17: преждевременное прекращение меток
// 18..23: резерв
// 24: запрос списка зарегистрированных нарушений
// 25..31: резерв
//
// 32: окончание передачи данных о нарушениях без преждевременного прекращения
// 33: окончание передачи данных о нарушениях с преждевременным прекращением системой управления
// 34: окончание передачи данных о нарушениях с преждевременным прекращением устройством защиты
// 35: окончание передачи канала без преждевременного прекращения
// 36: окончание передачи канала с преждевременным прекращением системой управления
// 37: окончание передачи канала с преждевременным прекращением устройством защиты
// 38: окончание передачи меток без преждевременного прекращения
// 39: окончание передачи меток с преждевременным прекращением системой управления
// 40: окончание передачи меток с преждевременным прекращением устройством защиты
// 41..63: резерв
//
// 64: данные о нарушениях переданы успешно (положительно)
// 65: данные о нарушениях переданы безуспешно (отрицательно)
// 66: передача канала успешна (положительно)
// 67: передача канала неуспешна (отрицательно)
// 68: метки переданы успешно (положительно)
// 69: метки переданы неуспешно (отрицательно)
// 70..255: резерв
tagTOO=byte;
// 7.2.6.27 Тип аварийных значений
// TOV:=UI8[1..8]<0..255>
// 0 - не используется, 1 - мгновенные значения, 2..255 - не используется
tagTOV=byte;
// 7.2.6.28 Четыре байта времени в двоичном коде
// CP32Time2a:=CP{Миллисекунды,Минуты,RES1,Недостоверное значение,Часы,RES2,Летнее время}
// Используется для метки времени
tagCP32Time2a=LongWord;
PtagCP32Time2a=^tagCP32Time2a;
// 7.2.6.29 Семь байт времени в двоичном коде
// CP56Time2a:=CP56{Миллисекунды,Минуты,RES,Недостоверное значение,Часы,RES2,Летнее время,День месяца,День недели,Месяц,RES4,Год,RES4}
// Этот формат определён в МЭК 60870-5-4, подпункт 6.8. Он используется для синхронизации часов и в списке зарегистрированных данных о нарушениях.
// День недели устанавливают числами от 1 до 7, если используется, где 1 означает понедельник, при неиспользовании он устанавливается в ноль.
// Когда этот формат используется групповыми услугами, он может быть сокращён отбрасыванием старших байтов. DataSize определяет фактическое число байт.
tagCP56Time2a=array[0..6]of byte;
PtagCP56Time2a=^tagCP56Time2a;
TrInformationObject1=packed record // ASDU1, для вторичной
_FunctionType:byte; // тип функции
_InformationNumber:byte; // номер информации
_DPI:tagDPI; // двухэлементная информация
_Time32:tagCP32Time2a; // метка времени
_SIN:tagSIN; // дополнительная информация
end;
TrInformationObject2=packed record // ASDU2, для вторичной
_FunctionType:byte; // тип функции
_InformationNumber:byte; // номер информации
_DPI:tagDPI; // двухэлементная информация
_RET:tagRET; // относительное время, для общего опроса не существенно
_FAN:tagFAN; // номер повреждения, для общего опроса не существенно
_Time32:tagCP32Time2a; // метка времени
_SIN:tagSIN; // дополнительная информация
end;
TrInformationObject3=packed record // ASDU3, для вторичной
_FunctionType:byte; // тип функции
_InformationNumber:byte; // номер информации
_MEA:array[0..255]of tagMEA; // массив измеряемых величин с описателем качества, количество величин - _VSQ and 0x7F
end;
TrInformationObject4=packed record // ASDU4, для вторичной
_FunctionType:byte; // тип функции
_InformationNumber:byte; // номер информации
_SCL:tagSCL; // расстояние до места короткого замыкания
_RET:tagRET; // относительное время
_FAN:tagFAN; // номер повреждения
_Time32:tagCP32Time2a; // метка времени
end;
TrInformationObject5=packed record // ASDU5, для вторичной
_FunctionType:byte; // тип функции
_InformationNumber:byte; // номер информации
// 2 при cot2ResetFCB, 3 при cot2ResetCommUnit, 4 при cot2StartRestart=5, 5 при cot2PowerOn
_COL:tagCOL; // уровень совместимости
_Vendor:array[0..7]of tagASC; // производитель
_SoftwareID:longword; // идентификатор программного обеспечения (4 байта)
end;
TrInformationObject6=packed record // ASDU6, для первичной и вторичной
_FunctionType:byte; // тип функции = 255
_InformationNumber:byte; // номер информации = 0
_Time56:tagCP56Time2a; // время
end;
TrInformationObject7=packed record // ASDU7, для первичной
_FunctionType:byte; // тип функции = 255
_InformationNumber:byte; // номер информации = 0
_SCN:tagSCN; // номер опроса
end;
TrInformationObject8=packed record // ASDU8, для вторичной
_FunctionType:byte; // тип функции = 255
_InformationNumber:byte; // номер информации = 0
_SCN:tagSCN; // номер опроса, берётся из команды инициализации GI
end;
TrInformationObject9=packed record // ASDU9, для вторичной
_FunctionType:byte; // тип функции
_InformationNumber:byte; // номер информации
_MEA:array[0..255]of tagMEA; // массив измеряемых величин с описателем качества, количество величин - _VSQ and 0x7F
end;
TrFanInfo=packed record // описание повреждения для ASDU 23
_FAN:tagFAN; // номер повреждения
_SOF:tagSOF; // состояние повреждения
_Time56:tagCP56Time2a; // время
end;
TrInformationObject23=packed record // ASDU 23, для вторичной
_FunctionType:byte; // тип функции
_InformationNumber:byte; // номер информации, не используется и равен 0
_FanInfo:array[0..255]of TrFanInfo; // массив описаний повреждения
end;
TrInformationObject24=packed record // ASDU24, для первичной
_FunctionType:byte; // тип функции
_InformationNumber:byte; // номер информации, не используется и равен 0
_TOO:tagTOO; // тип приказа
_TOV:tagTOV; // тип аварийных значений, определено только tovInstantaneousValues=1
_FAN:tagFAN; // номер повреждения
_ACC:tagACC; // текущий канал данных
end;
TrInformationObject25=packed record // ASDU25, для первичной
_FunctionType:byte; // тип функции
_InformationNumber:byte; // номер информации, не используется и равен 0
_TOO:tagTOO; // тип приказа
_TOV:tagTOV; // тип аварийных значений, определено только tovInstantaneousValues=1
_FAN:tagFAN; // номер повреждения
_ACC:tagACC; // текущий канал данных
end;
TrInformationObject26=packed record // ASDU26, для вторичной
_FunctionType:byte; // тип функции
_InformationNumber:byte; // номер информации, не используется и равен 0
_NotUsed:byte; // не используется и равен 0
_TOV:tagTOV; // тип аварийных значений, определено только tovInstantaneousValues=1
_FAN:tagFAN; // номер повреждения
_NOF:tagNOF; // номер повреждения сети
_NOC:tagNOC; // число каналов
_NOE:tagNOE; // число элементов информации в канале
_INT:tagINT; // интервал между элементами информации в мкс
_Time32:tagCP32Time2a; // метка времени первой зарегистрированной информации
end;
TrInformationObject27=packed record // ASDU27, для вторичной
_FunctionType:byte; // тип функции
_InformationNumber:byte; // номер информации, не используется и равен 0
_NotUsed:byte; // не используется и равен 0
_TOV:tagTOV; // тип аварийных значений, определено только tovInstantaneousValues=1
_FAN:tagFAN; // номер повреждения
_ACC:tagACC; // текущий канал данных
_RPV:tagRPV; // номинальное первичное значение
_RSV:tagRSV; // номинальное вторичное значение
_RFA:tagRFA; // масштабный коэффициент
end;
TrInformationObject28=packed record // ASDU28, для вторичной
_FunctionType:byte; // тип функции
_InformationNumber:byte; // номер информации, не используется и равен 0
_NotUsed1:byte; // не используется и равен 0
_NotUsed2:byte; // не используется и равен 0
_FAN:tagFAN; // номер повреждения
end;
TrTagInfo=packed record // описание метки для ASDU29
_FunctionType:byte; // тип функции
_InformationNumber:byte; // номер информации
_DPI:tagDPI; // состояние метки
end;
TrInformationObject29=packed record // ASDU29, для вторичной
_FunctionType:byte; // тип функции
_InformationNumber:byte; // номер информации, не используется и равен 0
_FAN:tagFAN; // номер повреждения
_NOT:tagNOT; // число меток в этом ASDU
_TAP:tagTAP; // положение метки
_Tags:array[0..255]of TrTagInfo; // массив меток
end;
TrInformationObject30=packed record // ASDU30, для вторичной
_FunctionType:byte; // тип функции
_InformationNumber:byte; // номер информации, не используется и равен 0
_NotUsed:byte; // не используется и равен 0
_TOV:tagTOV; // тип аварийных значений, определено только tovInstantaneousValues=1
_FAN:tagFAN; // номер повреждения
_ACC:tagACC; // текущий канал данных
_NDV:tagNDV; // число аварийных значений в этом ASDU
_NFE:tagNFE; // номер первого элемента в этом ASDU
_SDVs:array[0..255]of tagSDV; // массив аварийных значений
end;
TrInformationObject31=packed record // ASDU31, для вторичной
_FunctionType:byte; // тип функции
_InformationNumber:byte; // номер информации, не используется и равен 0
_TOO:tagTOO; // тип приказа
_TOV:tagTOV; // тип аварийных значений, определено только tovInstantaneousValues=1
_FAN:tagFAN; // номер повреждения
_ACC:tagACC; // текущий канал данных
end;
TrDataUnitIdentifier=packed record
_TypeID:byte; // идентификатор типа Type Identification
_VSQ:byte; // классификатор переменной структуры Variable Structure Qualifier
_COT:byte; // причина передачи Cause Of Transmission
_ASDUAddress:byte; // общий адрес ASDU
end;
TASDU=packed record // Application Service Data Unit
// Data Unit Identifier
DUI:TrDataUnitIdentifier;
// Information Object
case integer of
0: (FunctionType:byte; {тип функции} InformationNumber:byte {номер информации});
1: (IO1:TrInformationObject1); // для вторичной станции
2: (IO2:TrInformationObject2); // для вторичной станции
3: (IO3:TrInformationObject3); // для вторичной станции
4: (IO4:TrInformationObject4); // для вторичной станции
5: (IO5:TrInformationObject5); // для вторичной станции
6: (IO6:TrInformationObject6); // для первичной и вторичной станции - синхронизация
7: (IO7:TrInformationObject7); // для первичной станции - инициализация общего опроса
8: (IO8:TrInformationObject8); // для вторичной станции - окончание общего опроса
9: (IO9:TrInformationObject9); // для вторичной станции -
23: (IO23:TrInformationObject23); // для вторичной станции - список нарушений
24: (IO24:TrInformationObject24); // для первичной станции - приказ для нарушений
25: (IO25:TrInformationObject25); // для первичной станции - подтверждение передачи данных о нарушениях
26: (IO26:TrInformationObject26); // для вторичной станции - готовность к передаче данных о нарушениях
27: (IO27:TrInformationObject27); // для вторичной станции - готовность к передаче канала
28: (IO28:TrInformationObject28); // для вторичной станции - готовность к передаче меток
29: (IO29:TrInformationObject29); // для вторичной станции - передача меток
30: (IO30:TrInformationObject30); // для вторичной станции - передача аварийных значений
31: (IO31:TrInformationObject31); // для вторичной станции - завершение передачи меток, данных канала, данных нарушения
end;
PLDU=^TLDU;
TLDU=packed record // Link Data Unit
_LCF:byte; // поле управления LinkControlField
_LinkAddress:byte; // адресс процесса связи
_asdu:TASDU; // ASDU
end;
EIEC103Types=class(Exception);
TLinkControlField1=class // для первичной станции, использовать так TLinkControlField1(PByte).DFC
private
function GetBit(const ndx:integer):tagBIT;
function GetFunctionCode:tag4BIT;
procedure SetBit(const ndx:integer; const bit:tagBIT);
procedure SetFunctionCode(const fc:tag4BIT);
public
property FunctionCode:tag4BIT read GetFunctionCode write SetFunctionCode;
property FCV:tagBIT index ndxFCV read GetBit write SetBit;
property FCB:tagBIT index ndxFCB read GetBit write SetBit;
property PRM:tagBIT index ndxPRM read GetBit write SetBit;
property RES:tagBIT index ndxRES read GetBit write SetBit;
end;
TLinkControlField2=class // для вторичной станции, использовать так TLinkControlField2(PByte).DFC
private
function GetBit(const ndx:integer):tagBIT;
function GetFunctionCode:tag4BIT;
procedure SetBit(const ndx:integer; const bit:tagBIT);
procedure SetFunctionCode(const fc:tag4BIT);
public
property FunctionCode:tag4BIT read GetFunctionCode write SetFunctionCode;
property DFC:tagBIT index ndxDFC read GetBit write SetBit;
property ACD:tagBIT index ndxACD read GetBit write SetBit;
property PRM:tagBIT index ndxPRM read GetBit write SetBit;
property RES:tagBIT index ndxRES read GetBit write SetBit;
end;
TSOF=class // класс-помощник для типа tagSOF, использовать так - TSOF(PtagSOF).OTEV
private
function GetBit(const ndx:integer):tagBIT;
function GetRes:tag4BIT;
procedure SetBit(const ndx:integer; const bit:tagBIT);
procedure SetRes(const value:tag4BIT);
public
property TP:tagBIT index ndxTP read GetBit write SetBit; // регистрация повреждения с отключением или без
property TM:tagBIT index ndxTM read GetBit write SetBit; // данные о нарушении ожидающие передачи или передаваемые в настоящий момент
property TEST:tagBIT index ndxTEST read GetBit write SetBit; // данные о нарушении, регистрируемые в тестовом или рабочем режиме
property OTEV:tagBIT index ndxOTEV read GetBit write SetBit; // регистрация данных о нарушении, инициируемая запуском защиты или другими событиями
property RES:tag4BIT read GetRes write SetRes; // не используется
end;
TCP32Time2a=class // класс-помощник для типа tagCP32Time2a, использовать так - TCP32Time2a(PtagCP32Time2a).SU
protected
function GetBit(const ndx:integer):tagBIT;
function GetRES2:tag2BIT;
function GetWord(const ndx:integer):word;
procedure SetBit(const ndx:integer; const Value:tagBIT);
procedure SetRES2(const res2:tag2BIT);
procedure SetWord(const ndx:integer; const Value:word);
public
property Milliseconds:word index ndxMilliseconds read GetWord write SetWord; // миллисекунды 0..59999
property Minutes:word index ndxMinutes read GetWord write SetWord; // минуты 0..59
property RES1:tagBIT index ndxRES1 read GetBit write SetBit; // резерв 1
property IV:tagBIT index ndxIV read GetBit write SetBit; // недействительное значение
property Hours:word index ndxHours read GetWord write SetWord; // часы 0..23
property RES2:tag2BIT read GetRES2 write SetRES2; // резерв 2
property SU:tagBIT index ndxSU read GetBit write SetBit;
end;
TCP56Time2a=class // класс-помощник для типа tagCP56Time2a, использовать так - TCP56Time2a(PtagCP56Time2a).SU
protected
function GetBit(const ndx:integer):tagBIT;
function GetRES2:tag2BIT;
function GetRES3:tag4BIT;
function GetWord(const ndx:integer):word;
procedure SetBit(const ndx:integer; const Value:tagBIT);
procedure SetRES2(const res2:tag2BIT);
procedure SetRES3(const Value:tag4BIT);
procedure SetWord(const ndx:integer; const Value:word);
public
property Milliseconds:word index ndxMilliseconds read GetWord write SetWord; // миллисекунды 0..59999
property Minutes:word index ndxMinutes read GetWord write SetWord; // минуты 0..59
property RES1:tagBIT index ndxRES1 read GetBit write SetBit; // резерв 1
property IV:tagBIT index ndxIV read GetBit write SetBit; // недействительное значение
property Hours:word index ndxHours read GetWord write SetWord; // часы 0..23
property RES2:tag2BIT read GetRES2 write SetRES2; // резерв 2
property SU:tagBIT index ndxSU read GetBit write SetBit;
property DayOfMonth:word index ndxDayOfMonth read GetWord write SetWord; // день месяца 1..31
property DayOfWeek:word index ndxDayOfWeek read GetWord write SetWord; // день недели 1..7
property Month:word index ndxMonth read GetWord write SetWord; // месяц 1..12
property RES3:tag4BIT read GetRES3 write SetRES3; // резерв 3
property Year:word index ndxYear read GetWord write SetWord; // год 0..99
property RES4:tagBIT index ndxRES4 read getBit write SetBit; // резерв 4
end;
TMEA=class // класс-помощник для типа tagMEA, использовать так - TMEA(PtagMEA).OV:=1
private
function GetER:tagBIT;
function GetMVAL:Single;
function GetOV:tagBIT;
function GetRES:tagBIT;
procedure SetER(const er:tagBIT);
procedure SetMVAL(const mval:Single);
procedure SetOV(const ov:tagBIT);
procedure SetRES(const res:tagBIT);
public
property OV:tagBIT read GetOV write SetOV; // признак переполнения
property ER:tagBIT read GetER write SetER; // признак правильности MVAL
property RES:tagBIT read GetRES write SetRES; // резервный бит
property MVAL:Single read GetMVAL write SetMVAL; // значение в диапазоне -1..+1-2**(-12)
end;
function CP32Time2aToStr(time32:tagCP32Time2a):AnsiString; // время tagCP32Time2a в виде строки
function CP56Time2aToStr(time56:tagCP56Time2a):AnsiString; // время tagCP56Time2a в виде строки
function LinkControlField(const ui8:byte):byte; // поле управления на основе бита PRM: бит RES,FCB/ACD не меняется,
// FCV устанавливается для первичного, а DFC не меняется
function LinkControlField1(const ui8:byte):byte; // поле управления для первичной станции, PRM в 1
function LinkControlField2(const ui8:byte):byte; // поле управления для вторичной станции, PRM в 0
function FunctionCode1ToString(const fc:byte):AnsiString; // сервисный код функции в текст для первичного
function FunctionCode2ToString(const fc:byte):AnsiString; // сервисный код функции в текст для вторичного
function TypeIdentification1ToString(const ti:byte):AnsiString; // тип ASDU в текст для первичного
function TypeIdentification2ToString(const ti:byte):AnsiString; // тип ASDU в текст для вторичного
function CauseOfTransmission1ToString(const cot:byte):AnsiString; // причина передачи в текст для первичного
function CauseOfTransmission2ToString(const cot:byte):AnsiString; // причина передачи в текст для первичного
implementation
uses Windows;
{$BOOLEVAL OFF}
{$RANGECHECKS OFF}
{$OVERFLOWCHECKS OFF}
const arrSU:array[Boolean]of AnsiString=('',' SU'); arrIV:array[Boolean]of AnsiString=('',' IV');
procedure DoException(s:AnsiString); begin raise EIEC103Types.Create(s); end;
function CP32Time2aToStr(time32:tagCP32Time2a):AnsiString; begin
with TCP32Time2a(@time32)do Result:=Format('%.2d:%.2d:%.2d.%.3d%s%s',[Hours,Minutes,
Milliseconds div 1000,Milliseconds mod 1000,arrSU[SU=1],arrIV[IV=1]]);
end;
function CP56Time2aToStr(time56:tagCP56Time2a):AnsiString; var w:word; st:TSystemTime; begin
GetSystemTime(st); w:=(st.wYear div 1000)*1000;
with TCP56Time2a(@time56)do Result:=Format('%.4d.%.2d.%.2d %s',[w+Year,Month,DayOfMonth,CP32Time2aToStr(PtagCP32Time2a(@time56)^)]);
end;
function LinkControlField(const ui8:byte):byte; var fc:FCinfo; // поле управления на основе бита PRM: бит RES,FCB/ACD не меняется,
begin Result:=ui8; // FCV устанавливается для первичного, а DFC не меняется
if(ui8 and$40)<>0then begin // первичная станция
fc:=FCinfos1[ui8 and$0F]; if fc._fcv<>iUnused then Result:=(Result and not$10)or(fc._fcv shl 4);
end else fc:=FCinfos2[ui8 and$0F]; // вторичная станция
if fc._ft=ftReserved then DoException(Format('сервисная функция %d для PRM=%d зарезервирована, в МЭК 60870-5-103 не используется',[fc._fc,ui8 and$40]))
else if fc._ft=ftNotUsed then DoException(Format('сервисная функция %d для PRM=%d в МЭК 60870-5-103 не используется',[fc._fc,ui8 and$40]));
end;
function LinkControlField1(const ui8:byte):byte; // поле управления для первичной станции, PRM в 1
begin Result:=LinkControlField(ui8 or$40); end;
function LinkControlField2(const ui8:byte):byte; // поле управления для вторичной станции, PRM в 0
begin Result:=LinkControlField(ui8 and not$40); end;
function FunctionCode1ToString(const fc:byte):AnsiString; // сервисный код функции в текст для первичного
begin Result:='0x'+IntToHex(fc and$0F,2)+' - '+FCinfos1[fc and$0F]._sDecription; end;
function FunctionCode2ToString(const fc:byte):AnsiString; // сервисный код функции в текст для вторичного
begin Result:='0x'+IntToHex(fc and$0F,2)+' - '+FCinfos2[fc and$0F]._sDecription; end;
function TypeIdentification1ToString(const ti:byte):AnsiString; var s:AnsiString; begin // тип ASDU в текст для первичного
if not IntToIdent(ti,s,TIinfos1)then
if((ti)=0)or(ti>31)then s:='для специального применения (частный диапазон)'
else s:='зарезервировано для будущих совместных применений';
Result:='0x'+IntToHex(ti,2)+' - '+s;
end;
function TypeIdentification2ToString(const ti:byte):AnsiString; var s:AnsiString; begin // тип ASDU в текст для вторичного
if not IntToIdent(ti,s,TIinfos2)then
if((ti)=0)or(ti>31)then s:='для специального применения (частный диапазон)'
else s:='зарезервировано для будущих совместных применений';
Result:='0x'+IntToHex(ti,2)+' - '+s;
end;
function CauseOfTransmission1ToString(const cot:byte):AnsiString; var s:AnsiString; begin // причина передачи в текст для первичного
if not IntToIdent(cot,s,COTinfos1)then
if(cot>63)then s:='для специального применения (частный диапазон)'
else s:='зарезервировано для будущих совместных применений';
Result:='0x'+IntToHex(cot,2)+' - '+s;
end;
function CauseOfTransmission2ToString(const cot:byte):AnsiString; var s:AnsiString; begin // причина передачи в текст для первичного
if not IntToIdent(cot,s,COTinfos2)then
if(cot>63)then s:='для специального применения (частный диапазон)'
else s:='зарезервировано для будущих совместных применений';
Result:='0x'+IntToHex(cot,2)+' - '+s;
end;
{ TLinkControlField1 }
function TLinkControlField1.GetBit(const ndx:integer):tagBIT; begin
case ndx of
ndxFCV: Result:=tagBIT((PByte(Self)^shr 4)and$01);
ndxFCB: Result:=tagBIT((PByte(Self)^shr 5)and$01);
ndxPRM: Result:=tagBIT((PByte(Self)^shr 6)and$01);
ndxRES: Result:=tagBIT((PByte(Self)^shr 7)and$01);
else Result:=0; end;
end;
function TLinkControlField1.GetFunctionCode:tag4BIT;
begin Result:=tag4BIT(PByte(Self)^and$0F); end;
procedure TLinkControlField1.SetBit(const ndx:integer; const bit:tagBIT); begin
case ndx of
ndxFCV: PByte(Self)^:=(PByte(Self)^and not$10)or(bit shl 4);
ndxFCB: PByte(Self)^:=(PByte(Self)^and not$20)or(bit shl 5);
ndxPRM: PByte(Self)^:=(PByte(Self)^and not$40)or(1 shl 6);
ndxRES: PByte(Self)^:=(PByte(Self)^and not$80)or(bit shl 7);
end;
end;
procedure TLinkControlField1.SetFunctionCode(const fc:tag4BIT);
begin PByte(Self)^:=(PByte(Self)^and not$0F)or fc; end;
{ TLinkControlField2 }
function TLinkControlField2.GetBit(const ndx:integer):tagBIT; begin
case ndx of
ndxDFC: Result:=tagBIT((PByte(Self)^shr 4)and$01);
ndxACD: Result:=tagBIT((PByte(Self)^shr 5)and$01);
ndxPRM: Result:=tagBIT((PByte(Self)^shr 6)and$01);
ndxRES: Result:=tagBIT((PByte(Self)^shr 7)and$01);
else Result:=0; end;
end;
function TLinkControlField2.GetFunctionCode:tag4BIT;
begin Result:=tag4BIT(PByte(Self)^and$0F); end;
procedure TLinkControlField2.SetBit(const ndx:integer; const bit:tagBIT); begin
case ndx of
ndxDFC: PByte(Self)^:=(PByte(Self)^and not$10)or(bit shl 4);
ndxACD: PByte(Self)^:=(PByte(Self)^and not$20)or(bit shl 5);
ndxPRM: PByte(Self)^:=(PByte(Self)^and not$40)or(1 shl 6);
ndxRES: PByte(Self)^:=(PByte(Self)^and not$80)or(bit shl 7);
end;
end;
procedure TLinkControlField2.SetFunctionCode(const fc:tag4BIT);
begin PByte(Self)^:=(PByte(Self)^and not$0F)or fc; end;
{ TSOF }
function TSOF.GetBit(const ndx:integer):tagBIT; begin
case ndx of
ndxTP: Result:=tagBIT(PtagSOF(Self)^and$01);
ndxTM: Result:=tagBIT((PtagSOF(Self)^shr 1)and$01);
ndxTEST: Result:=tagBIT((PtagSOF(Self)^shr 2)and$01);
ndxOTEV: Result:=tagBIT((PtagSOF(Self)^shr 3)and$01);
else Result:=0; end;
end;
function TSOF.GetRes: tag4BIT;
begin Result:=tag4BIT(PtagSOF(Self)^shr 4); end;
procedure TSOF.SetBit(const ndx:integer; const bit:tagBIT); begin
case ndx of
ndxTP: PtagSOF(Self)^:=tagSOF((PtagSOF(Self)^and not$01)or(bit));
ndxTM: PtagSOF(Self)^:=tagSOF((PtagSOF(Self)^and not$02)or(bit shl 1));
ndxTEST: PtagSOF(Self)^:=tagSOF((PtagSOF(Self)^and not$04)or(bit shl 2));
ndxOTEV: PtagSOF(Self)^:=tagSOF((PtagSOF(Self)^and not$08)or(bit shl 3));
end;
end;
procedure TSOF.SetRes(const value:tag4BIT);
begin PtagSOF(Self)^:=tagSOF((PtagSOF(Self)^and$0F)and(value shl 4)); end;
{ TCP32Time2a }
function TCP32Time2a.GetBit(const ndx:integer):tagBIT; begin
case ndx of
ndxRES1: Result:=tagBIT((PtagCP32Time2a(Self)^shr 22)and$01);
ndxIV: Result:=tagBIT((PtagCP32Time2a(Self)^shr 23)and$01);
ndxSU: Result:=tagBIT((PtagCP32Time2a(Self)^shr 31)and$01);
else Result:=0; end;
end;
function TCP32Time2a.GetRES2:tag2BIT;
begin Result:=tag2BIT((PtagCP32Time2a(Self)^shr 29)and$03); end;
function TCP32Time2a.GetWord(const ndx:integer):word; begin
case ndx of
ndxMilliseconds: Result:=word(PtagCP32Time2a(Self)^);
ndxMinutes: Result:=word((PtagCP32Time2a(Self)^shr 16)and$3F);
ndxHours: Result:=word((PtagCP32Time2a(Self)^shr 24)and$1F);
else Result:=0; end;
end;
procedure TCP32Time2a.SetBit(const ndx:integer; const Value:tagBIT); begin
case ndx of
ndxRES1: PtagCP32Time2a(Self)^:=tagCP32Time2a((PtagCP32Time2a(Self)^and not$00400000)or(Value shl 22));
ndxIV: PtagCP32Time2a(Self)^:=tagCP32Time2a((PtagCP32Time2a(Self)^and not$00800000)or(Value shl 23));
ndxSU: PtagCP32Time2a(Self)^:=tagCP32Time2a((PtagCP32Time2a(Self)^and not$80000000)or(Value shl 31));
end;
end;
procedure TCP32Time2a.SetRES2(const res2:tag2BIT);
begin PtagCP32Time2a(Self)^:=tagCP32Time2a((PtagCP32Time2a(Self)^and not$60000000)or(res2 shl 29)); end;
procedure TCP32Time2a.SetWord(const ndx:integer; const Value:word); begin
case ndx of
ndxMilliseconds: begin if Value>59999then IV:=1;
PtagCP32Time2a(Self)^:=tagCP32Time2a((PtagCP32Time2a(Self)^and not$FFFF)or(Value));
end;
ndxMinutes: begin if Value>59then IV:=1;
PtagCP32Time2a(Self)^:=tagCP32Time2a((PtagCP32Time2a(Self)^and not$3F0000)or((Value and$3F)shl 16));
end;
ndxHours: begin if Value>23then IV:=1;
PtagCP32Time2a(Self)^:=tagCP32Time2a((PtagCP32Time2a(Self)^and not$1F000000)or((Value and$1F)shl 24));
end;
end;
end;
{ TCP56Time2a }
function TCP56Time2a.GetBit(const ndx:integer):tagBIT; begin
case ndx of
ndxRES1: Result:=tagBIT((PtagCP32Time2a(Self)^shr 22)and$01);
ndxIV: Result:=tagBIT((PtagCP32Time2a(Self)^shr 23)and$01);
ndxSU: Result:=tagBIT((PtagCP32Time2a(Self)^shr 31)and$01);
ndxRES4: Result:=tagBIT((PtagCP56Time2a(Self)^[6]shl 7)and$01);
else Result:=0; end;
end;
function TCP56Time2a.GetRES2:tag2BIT;
begin Result:=tag2BIT((PtagCP32Time2a(Self)^shr 29)and$03); end;
function TCP56Time2a.GetRES3:tag4BIT;
begin Result:=tag4BIT((PtagCP56Time2a(Self)^[5]shr 4)and$0F); end;
function TCP56Time2a.GetWord(const ndx:integer):word; begin
case ndx of
ndxMilliseconds: Result:=word(PtagCP32Time2a(Self)^);
ndxMinutes: Result:=word((PtagCP32Time2a(Self)^shr 16)and$3F);
ndxHours: Result:=word((PtagCP32Time2a(Self)^shr 24)and$1F);
ndxDayOfMonth: Result:=word(PtagCP56Time2a(Self)^[4]and$1F);
ndxDayOfWeek: Result:=word((PtagCP56Time2a(Self)^[4]shr 5)and$07);
ndxMonth: Result:=word(PtagCP56Time2a(Self)^[5]and$0F);
ndxYear: Result:=word(PtagCP56Time2a(Self)^[6]and$7F);
else Result:=0; end;
end;
procedure TCP56Time2a.SetBit(const ndx:integer; const Value:tagBIT); begin
case ndx of
ndxRES1: PtagCP32Time2a(Self)^:=tagCP32Time2a((PtagCP32Time2a(Self)^and not$00400000)or(Value shl 22));
ndxIV: PtagCP32Time2a(Self)^:=tagCP32Time2a((PtagCP32Time2a(Self)^and not$00800000)or(Value shl 23));
ndxSU: PtagCP32Time2a(Self)^:=tagCP32Time2a((PtagCP32Time2a(Self)^and not$80000000)or(Value shl 31));
ndxRES4: PtagCP56Time2a(Self)^[6]:=(PtagCP56Time2a(Self)^[6]and$7F)or(Value shl 7)
end;
end;
procedure TCP56Time2a.SetRES2(const res2:tag2BIT);
begin PtagCP32Time2a(Self)^:=tagCP32Time2a((PtagCP32Time2a(Self)^and not$60000000)or(res2 shl 29)); end;
procedure TCP56Time2a.SetRES3(const Value:tag4BIT);
begin PtagCP56Time2a(Self)^[5]:=(PtagCP56Time2a(Self)^[5]and$F0)or(Value shl 4); end;
procedure TCP56Time2a.SetWord(const ndx:integer; const Value:word); begin
case ndx of
ndxMilliseconds: begin if Value>59999then IV:=1;
PtagCP32Time2a(Self)^:=tagCP32Time2a((PtagCP32Time2a(Self)^and not$FFFF)or(Value));
end;
ndxMinutes: begin if Value>59then IV:=1;
PtagCP32Time2a(Self)^:=tagCP32Time2a((PtagCP32Time2a(Self)^and not$3F0000)or((Value and$3F)shl 16));
end;
ndxHours: begin if Value>23then IV:=1;
PtagCP32Time2a(Self)^:=tagCP32Time2a((PtagCP32Time2a(Self)^and not$1F000000)or((Value and$1F)shl 24));
end;
ndxDayOfMonth: begin if(Value=0)or(Value>31)then IV:=1;
PtagCP56Time2a(Self)^[4]:=(PtagCP56Time2a(Self)^[4]and byte(not$1F))or(Value and$1F);
end;
ndxDayOfWeek: begin if(Value>7)then IV:=1;
PtagCP56Time2a(Self)^[4]:=(PtagCP56Time2a(Self)^[4]and byte(not$E0))or((Value and$07)shl 5);
end;
ndxMonth: begin if(Value=0)or(Value>12)then IV:=1;
PtagCP56Time2a(Self)^[5]:=(PtagCP56Time2a(Self)^[5]and byte(not$0F))or(Value and$0F);
end;
ndxYear: begin
PtagCP56Time2a(Self)^[6]:=(PtagCP56Time2a(Self)^[6]and byte(not$7F))or(Value mod 100);
end;
end;
end;
{ TMEA }
function TMEA.GetER:tagBIT;
begin Result:=tagBIT((PtagMEA(Self)^shr 1)and$01); end;
function TMEA.GetMVAL:Single;
begin Result:=(SmallInt(PtagMEA(Self)^))/$8000; end;
function TMEA.GetOV:tagBIT;
begin Result:=tagBIT(PtagMEA(Self)^and$01); end;
function TMEA.GetRES:tagBIT;
begin Result:=tagBIT((PtagMEA(Self)^shr 2)and$01); end;
procedure TMEA.SetER(const er:tagBIT);
begin PtagMEA(Self)^:=tagMEA((PtagMEA(Self)^and not$02)or(er shl 1)); end;
procedure TMEA.SetMVAL(const mval:Single); var s:single; begin
if mval<-1then begin s:=-1; OV:=1; end
else if mval>=1then begin s:=1-0.000244140625; OV:=1; end
else begin s:=mval; OV:=0; end;
PtagMEA(Self)^:=tagMEA((PtagMEA(Self)^and $07)or(Round(s*$1000)shl 3));
end;
procedure TMEA.SetOV(const ov:tagBIT);
begin PtagMEA(Self)^:=tagMEA((PtagMEA(Self)^and not$01)or(ov)); end;
procedure TMEA.SetRES(const res:tagBIT);
begin PtagMEA(Self)^:=tagMEA((PtagMEA(Self)^and not$08)or(res shl 2)); end;
end.
|
unit UUADPropSubjAddr;
{ ClickForms Application }
{ Bradford Technologies, Inc. }
{ All Rights Reserved }
{ Source Code Copyrighted © 1998-2011 by Bradford Technologies, Inc. }
//Used to enter the subject property address
interface
uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls,
Buttons, Dialogs, UCell, UUADUtils, UContainer, UEditor, UGlobals,
UStatus, UForms;
type
TdlgUADPropSubjAddr = class(TAdvancedForm)
bbtnCancel: TBitBtn;
bbtnOK: TBitBtn;
lblState: TLabel;
cbState: TComboBox;
lblZipCode: TLabel;
edtZipCode: TEdit;
edtZipPlus4: TEdit;
lblUnitNum: TLabel;
edtUnitNum: TEdit;
lblStreetAddr: TLabel;
edtStreetAddr: TEdit;
lblCity: TLabel;
edtCity: TEdit;
bbtnHelp: TBitBtn;
bbtnClear: TBitBtn;
lblZipSep: TLabel;
procedure FormShow(Sender: TObject);
procedure bbtnHelpClick(Sender: TObject);
procedure bbtnOKClick(Sender: TObject);
procedure edtZipCodeKeyPress(Sender: TObject; var Key: Char);
procedure edtZipPlus4KeyPress(Sender: TObject; var Key: Char);
procedure bbtnClearClick(Sender: TObject);
procedure cbStateKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
FUnitCell, FAddr1Cell, FCityCell, FStCell, FZipCell: TBaseCell;
IsUnitAddr: Boolean;
public
{ Public declarations }
FCell: TBaseCell;
PriFormReqUnit: Boolean;
procedure Clear;
procedure SaveToCell;
end;
var
dlgUADPropSubjAddr: TdlgUADPropSubjAddr;
implementation
{$R *.dfm}
uses
UPage,
UAppraisalIDs,
UStrings;
procedure TdlgUADPropSubjAddr.FormShow(Sender: TObject);
var
Page: TDocPage;
begin
Page := FCell.ParentPage as TDocPage;
if FCell.UID.FormID = 794 then // Supplemental REO 2008
begin
FAddr1Cell := Page.GetCellByXID(3970);
IsUnitAddr := False;
FCityCell := Page.GetCellByXID(3971);
FStCell := Page.GetCellByXID(3972);
FZipCell := Page.GetCellByXID(3973);
end
else if FCell.UID.FormID = 683 then // Supplemental REO
begin
FAddr1Cell := Page.GetCellByXID(1790);
IsUnitAddr := False;
FCityCell := Page.GetCellByXID(1791);
FStCell := Page.GetCellByXID(1792);
FZipCell := Page.GetCellByXID(1793);
end
else if FCell.UID.FormID = 850 then // FNMA1004MC
begin
FAddr1Cell := Page.GetCellByXID(2758);
IsUnitAddr := False;
FCityCell := Page.GetCellByXID(2759);
FStCell := Page.GetCellByXID(2760);
FZipCell := Page.GetCellByXID(2761);
end
else
begin
FAddr1Cell := Page.GetCellByXID(46);
FUnitCell := Page.GetCellByXID(2141);
IsUnitAddr := (FUnitCell <> nil) and PriFormReqUnit;
FCityCell := Page.GetCellByXID(47);
FStCell := Page.GetCellByXID(48);
FZipCell := Page.GetCellByXID(49);
end;
edtStreetAddr.Text := FAddr1Cell.Text;
if IsUnitAddr then
edtUnitNum.Text := FUnitCell.Text;
edtCity.Text := FCityCell.Text;
cbState.ItemIndex := cbState.Items.IndexOf(FStCell.Text);
edtZipCode.Text := Copy(FZipCell.Text, 1, 5);
edtZipPlus4.Text := Copy(FZipCell.Text, 7, 4);
edtUnitNum.Visible := IsUnitAddr;
lblUnitNum.Visible := IsUnitAddr;
edtStreetAddr.SetFocus;
end;
procedure TdlgUADPropSubjAddr.bbtnHelpClick(Sender: TObject);
begin
ShowUADHelp('FILE_HELP_UAD_PROPERTY_ADDRESS', Caption);
end;
procedure TdlgUADPropSubjAddr.bbtnOKClick(Sender: TObject);
begin
if Trim(edtStreetAddr.Text) = '' then
begin
ShowAlert(atWarnAlert, msgUADValidStreet);
edtStreetAddr.SetFocus;
Exit;
end;
if IsUnitAddr and
(Trim(edtUnitNum.Text) = '') then
begin
ShowAlert(atWarnAlert, msgUADValidUnitNo);
edtUnitNum.SetFocus;
Exit;
end;
if Trim(edtCity.Text) = '' then
begin
ShowAlert(atWarnAlert, msgUADValidCity);
edtCity.SetFocus;
Exit;
end;
//user needs to be able to type in state. easier than clicking list
if (cbState.text = '') or (length(cbState.text) = 1) or (POS(cbState.text, cbState.Items.Text)= 0) then
begin
ShowAlert(atWarnAlert, msgValidState);
cbState.SetFocus;
Exit;
end;
if (Trim(edtZipCode.Text) = '') or (Length(edtZipCode.Text) < 5) or
(StrToInt(edtZipCode.Text) <= 0) then
begin
ShowAlert(atWarnAlert, msgValidZipCode);
edtZipCode.SetFocus;
Exit;
end;
if Length(Trim(edtZipPlus4.Text)) > 0 then
if (Length(edtZipPlus4.Text) < 4) or (StrToInt(edtZipPlus4.Text) = 0) then
begin
ShowAlert(atWarnAlert, msgValidZipPlus);
edtZipPlus4.SetFocus;
Exit;
end;
SaveToCell;
ModalResult := mrOK;
end;
procedure TdlgUADPropSubjAddr.edtZipCodeKeyPress(Sender: TObject;
var Key: Char);
begin
Key := PositiveNumKey(Key);
end;
procedure TdlgUADPropSubjAddr.edtZipPlus4KeyPress(Sender: TObject;
var Key: Char);
begin
Key := PositiveNumKey(Key);
end;
procedure TdlgUADPropSubjAddr.cbStateKeyPress(Sender: TObject;
var Key: Char);
begin
Key := GetAlphaKey(Key);
end;
procedure TdlgUADPropSubjAddr.Clear;
begin
edtStreetAddr.Text := '';
edtUnitNum.Text := '';
edtCity.Text := '';
cbState.ItemIndex := -1;
edtZipCode.Text := '';
edtZipPlus4.Text := '';
end;
procedure TdlgUADPropSubjAddr.SaveToCell;
var
ZipText: String;
begin
// Remove any legacy data - no longer used
FAddr1Cell.GSEData := '';
// Save the cleared or valid address
SetDisplayUADText(FAddr1Cell, edtStreetAddr.Text);
if IsUnitAddr then
SetDisplayUADText(FUnitCell, edtUnitNum.Text);
SetDisplayUADText(FCityCell, edtCity.Text);
SetDisplayUADText(FStCell, cbState.Text);
if Trim(edtZipPlus4.Text) <> '' then
ZipText := edtZipCode.Text + '-' + edtZipPlus4.Text
else
ZipText := edtZipCode.Text;
SetDisplayUADText(FZipCell, ZipText);
end;
procedure TdlgUADPropSubjAddr.bbtnClearClick(Sender: TObject);
begin
if WarnOK2Continue(msgUAGClearDialog) then
begin
Clear;
SaveToCell;
ModalResult := mrOK;
end;
end;
end.
|
{ $HDR$}
{**********************************************************************}
{ Unit archived using Team Coherence }
{ Team Coherence is Copyright 2002 by Quality Software Components }
{ }
{ For further information / comments, visit our WEB site at }
{ http://www.TeamCoherence.com }
{**********************************************************************}
{}
{ $Log: 22776: FTPListTests.pas
{
{ Rev 1.6 10/3/2003 05:47:54 PM JPMugaas
{ OS/2 tests.
}
{
{ Rev 1.5 9/28/2003 03:38:54 PM JPMugaas
{ Fixed a bad test case.
}
{
{ Rev 1.4 9/28/2003 03:03:22 AM JPMugaas
{ Added tests for nonstandard Unix dates.
}
{
{ Rev 1.3 9/27/2003 10:44:58 PM JPMugaas
{ Added a test for MS-DOS formats.
}
{
{ Rev 1.2 9/3/2003 07:36:16 PM JPMugaas
{ More parsing test cases.
}
{
{ Rev 1.1 9/3/2003 04:01:14 AM JPMugaas
{ Added some preliminary tests.
}
{
{ Rev 1.0 9/2/2003 02:27:46 AM JPMugaas
{ Skeliton for new FTP list test. The test is in development now.
}
unit FTPListTests;
interface
uses
SysUtils, Classes, BXBubble, BXCategory;
type
TFTPTestItem = class(TObject)
protected
FTestItem : String;
FFoundParser : String;
FExpectedParser : String;
//note that the Unix servers can normally only report either a year
//or a time. This can cause ambiguity because the year is interpretted
//according to the current or previous year if the date has passed or arrived. But
//because we can't know the local time zone, there can be a 24 hour window
//of time. E.g. Sept 8 10:00am 2003 can be interpretted as either Sept 8 10:00am 2003 or
//Sept 8, 2002 if in the window of Sept 7 10:00am or Sept 9 10:00am.
//Otherwise, a date such as Sept 8: 10:00am can be interpretted differently at different
//times of the year (when the window period has passed - 2002 or before the window 2003.
FEvaluateTime : Boolean;
FEvaluateYear : Boolean;
//Note that with the BSD -T switch, a time can be returned with seconds
FFoundYear, FFoundMonth, FFoundDay, FFoundHour, FFoundMin, FFoundSec : Word;
FExpectedYear, FExpectedMonth, FExpectedDay, FExpectedHour, FExpectedMin, FExpectedSec : Word;
FFoundOwner : String;
FExpectedOwner : String;
FFoundGroup : String;
FExpectedGroup : String;
FFoundFileName : String;
FExpectedFileName : String;
FFoundFileSize : Integer;
FExpectedFileSize : Integer;
public
procedure Clear;
property TestItem : String read FTestItem write FTestItem;
property FoundParser : String read FFoundParser write FFoundParser;
property ExpectedParser : String read FExpectedParser write FExpectedParser;
property EvaluateTime : Boolean read FEvaluateTime write FEvaluateTime;
property EvaluateYear : Boolean read FEvaluateYear write FEvaluateYear;
//Note that with the BSD -T switch, a time can be returned with seconds
property FoundYear : Word read FFoundYear write FFoundYear;
property FoundMonth : Word read FFoundMonth write FFoundMonth;
property FoundDay : Word read FFoundDay write FFoundDay;
property FoundHour : Word read FFoundHour write FFoundHour;
property FoundMin : Word read FFoundMin write FFoundMin;
property FoundSec : Word read FFoundSec write FFoundSec;
property ExpectedYear : Word read FExpectedYear write FExpectedYear;
property ExpectedMonth : Word read FExpectedMonth write FExpectedMonth;
property ExpectedDay : Word read FExpectedDay write FExpectedDay;
property ExpectedHour : Word read FExpectedHour write FExpectedHour;
property ExpectedMin : Word read FExpectedMin write FExpectedMin;
property ExpectedSec : Word read FExpectedSec write FExpectedSec;
property FoundOwner : String read FFoundOwner write FFoundOwner;
property ExpectedOwner : String read FExpectedOwner write FExpectedOwner;
property FoundGroup : String read FFoundGroup write FFoundGroup;
property ExpectedGroup : String read FExpectedGroup write FExpectedGroup;
property FoundFileName : String read FFoundFileName write FFoundFileName;
property ExpectedFileName : String read FExpectedFileName write FExpectedFileName;
property FoundFileSize : Integer read FFoundFileSize write FFoundFileSize;
property ExpectedFileSize : Integer read FExpectedFileSize write FExpectedFileSize;
end;
TdmFTPListTest = class(TDataModule)
bxUnixLSandSimilar: TBXBubble;
bxWin32IISForms: TBXBubble;
bxSterlingComTests: TBXBubble;
bxOS2Test: TBXBubble;
procedure bxUnixLSandSimilarTest(Sender: TBXBubble);
procedure bxWin32IISFormsTest(Sender: TBXBubble);
procedure bxSterlingComTestsTest(Sender: TBXBubble);
procedure bxOS2TestTest(Sender: TBXBubble);
private
{ Private declarations }
protected
procedure ReportItem(AItem : TFTPTestItem);
//this is for MS-DOS (Win32 style Dir lists where there's no
//owner or group and where the time and date are supplied
procedure TestItem(
ATestItem,
AExpectedParser,
AExpectedFileName : String;
AExpectedFileSize : Integer;
AExpectedYear,
AExpectedMonth,
AExpectedDay,
AExpectedHour,
AExpectedMin,
AExpectedSec : Word); overload;
//for FreeBSD -T /bin/ls variation and Novell Netware Print Services for Unix (NFS Namespace)
procedure TestItem(
ATestItem,
AExpectedParser,
AExpectedOwner,
AExpectedGroup,
AExpectedFileName : String;
AExpectedFileSize : Integer;
AExpectedYear,
AExpectedMonth,
AExpectedDay,
AExpectedHour,
AExpectedMin,
AExpectedSec : Word); overload;
//for /bin/ls with a date within 6 monthes
procedure TestItem(
ATestItem,
AExpectedParser,
AExpectedOwner,
AExpectedGroup,
AExpectedFileName : String;
AExpectedFileSize : Integer;
AExpectedMonth,
AExpectedDay,
AExpectedHour,
AExpectedMin,
AExpectedSec : Word); overload;
//for /bin/ls with a date greater than 6 monthes
procedure TestItem(
ATestItem,
AExpectedParser,
AExpectedOwner,
AExpectedGroup,
AExpectedFileName : String;
AExpectedFileSize : Integer;
AExpectedYear,
AExpectedMonth,
AExpectedDay : Word); overload;
public
{ Public declarations }
end;
var
dmFTPListTest: TdmFTPListTest;
implementation
uses IdCoreGlobal, IdAllFTPListParsers, IdFTPList, IdFTPListParseNovellNetwarePSU,
IdFTPListParseUnix,
IdFTPListParseBase, IdFTPListParseWindowsNT, IdFTPListParseStercomUnixEnt,
IdFTPListParseStercomOS390Exp, IdFTPListParseOS2;
{$R *.dfm}
procedure TdmFTPListTest.bxUnixLSandSimilarTest(Sender: TBXBubble);
begin
//drwxrwxrwx 1 user group 0 Mar 3 04:49:59 2003 upload
//FreeBSD /bin/ls -T format
TestItem('drwxrwxrwx 1 user group 0 Mar 3 04:49:59 2003 upload',
UNIX,
'user',
'group',
'upload',
0,
2003,
3,
3,
4,
49,
59
);
//-rw------- 1 root wheel 512 Oct 14, 99 8:45 pm deleted.sav
//Novell Netware Print Services for Unix FTP Deamon
TestItem('-rw------- 1 root wheel 512 Oct 14, 99 8:45 pm deleted.sav',
NOVELLNETWAREPSU + 'NFS Namespace',
'root',
'wheel',
'deleted.sav',
512,
1999,
10,
14,
20,
45,
0);
//Normal Unix item with time
TestItem('drwxrwxrwx 1 owner group 0 Sep 23 21:58 drdos',
UNIX,
'owner',
'group',
'drdos',
0,
9,
23,
21,
58,
0);
//drwxr-xr-x 4 ftpuser ftpusers 512 Jul 23 2001 about
//Normal Unix item with year
TestItem('drwxr-xr-x 4 ftpuser ftpusers 512 Jul 23 2001 about',
UNIX,
'ftpuser',
'ftpusers',
'about',
512,
2001,
7,
23);
// -rw------- 1 strauss staff DK adams 39 Feb 18 11:23 file2
// Unitree with Time
TestItem('-rw------- 1 strauss staff DK adams 39 Feb 18 11:23 file2',
UNITREE,
'strauss',
'staff',
'file2',
39,
2,
18,
11,
23,
0);
//Unitree with Date
TestItem('drwxr-xr-x 2 se2nl g664 DK common 8192 Dec 29 1993 encytemp (Empty)',
UNITREE,
'se2nl',
'g664',
'encytemp (Empty)',
8192,
1993,
12,
29);
TestItem('drwxr-xr-x 2 root 110 4096 Sep 27 2000 oracle',
UNIX,
'root',
'110',
'oracle',
4096,
2000,
9,
27);
TestItem('-r--r--r-- 1 0 1 351 Aug 8 2000 Welcome',
UNIX,
'0',
'1',
'Welcome',
351,
2000,
8,
8);
//-go switches
TestItem('-r--r--r-- 1 351 Aug 8 2000 Welcome',
UNIX,
'',
'',
'Welcome',
351,
2000,
8,
8 );
//-g switch
TestItem('-r--r--r-- 1 1 351 Aug 8 2000 Welcome',
UNIX,
'',
'1',
'Welcome',
351,
2000,
8,
8);
TestItem('-r--r--r-- 1 0 351 Aug 8 2000 Welcome',
UNIX,
'',
'0', //really the owner but for coding, it's the group because
//you can't desinguish a group and owner with one value and on
//a server, you can't make an API call.
'Welcome',
351,
2000,
8,
8);
//-i switch
TestItem(' 33025 -r--r--r-- 1 root other 351 Aug 8 2000 Welcome',
UNIX,
'root',
'other',
'Welcome',
351,
2000,
8,
8);
//-s switch
TestItem(' 16 -r--r--r-- 1 root other 351 Aug 8 2000 Welcome',
UNIX,
'root',
'other',
'Welcome',
351,
2000,
8,
8);
//-is switches
TestItem(' 33025 16 -r--r--r-- 1 root other 351 Aug 8 2000 Welcome',
UNIX,
'root',
'other',
'Welcome',
351,
2000,
8,
8);
TestItem('1008201 33 -rw-r--r-- 1 204 wheel 32871 Mar 4 16:45:27 1999 nl-ftp',
UNIX,
'204',
'wheel',
'nl-ftp',
32871,
1999,
3,
4,
16,
45,
27);
//char devices
TestItem('crw-rw-rw- 1 0 1 11, 42 Aug 8 2000 tcp',
UNIX,
'0',
'1',
'tcp',
0,
2000,
8,
8);
TestItem('crw-rw-rw- 1 0 1 105, 1 Aug 8 2000 ticotsord',
UNIX,
'0',
'1',
'ticotsord',
0,
2000,
8,
8);
// a /bin/ls form with a ACL.
TestItem('drwx------+ 7 Administ mkpasswd 86016 Feb 9 18:04 bin',
UNIX,
'Administ',
'mkpasswd',
'bin',
86016,
2,
9,
18,
4,
0);
//Note that this is problematic and I doubt we can ever fix for this one without
//introducing other problems.
{ TestItem('-rw-r--r-- 1 J. Peter Mugaas None 862979 Apr 8 2002 kftp.exe',
UNIX,
'J. Peter Mugaas',
'None',
'kftp.exe',
862979,
2002,
4,
8); }
//taken from remarks in the FileZilla GNU Source-code - note that non of that
//code is used at all
// /* Some listings with uncommon date/time format: */
// "-rw-r--r-- 1 root other 531 09-26 2000 README2",
TestItem('-rw-r--r-- 1 root other 531 09-26 2000 README2',
UNIX,
'root',
'other',
'README2',
531,
2000,
9,
26);
// "-rw-r--r-- 1 root other 531 09-26 13:45 README3",
TestItem('-rw-r--r-- 1 root other 531 09-26 13:45 README3',
UNIX,
'root',
'other',
'README3',
531,
9,
26,
13,
45,
0);
// "-rw-r--r-- 1 root other 531 2005-06-07 21:22 README4
TestItem('-rw-r--r-- 1 root other 531 2005-06-07 21:22 README4',
UNIX,
'root',
'other',
'README4',
2005,
6,
7,
21,
22,
0);
TestItem('---------- 1 owner group 1803128 Jul 10 10:18 ls-lR.Z',
UNIX,
'owner',
'group',
'ls-lR.Z',
1803128,
7,
10,
10,
18,
0);
TestItem('d--------- 1 owner group 0 May 9 19:45 Softlib',
UNIX,
'owner',
'group',
'Softlib',
0,
5,
9,
19,
45,
0);
// CONNECT:Enterprise for UNIX login ok,
TestItem('-r--r--r-- 1 connect 3444 910368 Sep 24 16:36 c3957010.zip.001',
UNIX,
'connect',
'3444',
'c3957010.zip.001',
910368,
9,
24,
16,
36,
0);
TestItem('-r--r--r-- 1 connect 2755 6669222 Sep 26 08:11 3963338.fix.000',
UNIX,
'connect',
'2755',
'3963338.fix.000',
6669222,
9,
26,
8,
11,
0);
TestItem('-r--r--r-- 1 connect 3188 6669222 Sep 26 13:12 c3963338.zip',
UNIX,
'connect',
'3188',
'c3963338.zip',
6669222,
9,
26,
13,
12,
0);
end;
procedure TdmFTPListTest.ReportItem(AItem: TFTPTestItem);
var LStatus : String;
begin
bxUnixLSandSimilar.Status('Item: ');
bxUnixLSandSimilar.Status(AItem.TestItem);
//filename
LStatus :=
'Obtained File name: '+ AItem.FoundFileName + EOL +'Expected name: '+AItem.ExpectedFileName ;
bxUnixLSandSimilar.Status(LStatus);
bxUnixLSandSimilar.Check(AItem.FoundFileName=AItem.ExpectedFileName, LSTatus);
//parserID
LStatus := 'Obtained Parser ID: '+ AItem.FoundParser +EOL+
'Expected Parser ID: '+ AItem.ExpectedParser;
bxUnixLSandSimilar.Status(LStatus);
bxUnixLSandSimilar.Check(AItem.FoundFileName=AItem.ExpectedFileName,LStatus);
//Owner
LStatus := 'Obtained Owner: '+ AItem.FoundOwner +EOL+'Expected Owner: '+ AItem.ExpectedOwner;
bxUnixLSandSimilar.Status(LStatus);
bxUnixLSandSimilar.Check(AItem.FoundOwner =AItem.ExpectedOwner, LStatus );
//Group
LStatus :='Obtained Group: '+ AItem.FoundGroup +EOL+'Expected Group: '+ AItem.ExpectedGroup;
bxUnixLSandSimilar.Status(LStatus);
bxUnixLSandSimilar.Check(AItem.FoundGroup =AItem.ExpectedGroup,LStatus );
//Date
// Year - note that this may skipped in some cases as explained above
if AItem.FEvaluateYear then
begin
LStatus := 'Obtained Year: '+ IntToStr(AItem.FFoundYear ) +EOL+'Expected Year: '+ IntToStr(AItem.ExpectedYear );
bxUnixLSandSimilar.Status(LStatus);
bxUnixLSandSimilar.Check(AItem.FoundYear =AItem.ExpectedYear,LStatus );
end;
//month
LStatus := 'Obtained Month: '+ IntToStr(AItem.FoundMonth) +EOL+'Expected Month: '+ IntToStr(AItem.ExpectedMonth);
bxUnixLSandSimilar.Status(LStatus);
bxUnixLSandSimilar.Check(AItem.FoundMonth =AItem.ExpectedMonth,LStatus );
//day
LStatus :='Obtained Day: '+ IntToStr(AItem.FoundDay) +EOL+'Expected Day: '+ IntToStr(AItem.ExpectedDay);
bxUnixLSandSimilar.Status(LStatus);
bxUnixLSandSimilar.Check(AItem.FoundDay =AItem.ExpectedDay,LStatus );
//time
if AItem.EvaluateTime then
begin
//Hour
LStatus := 'Obtained Hour: '+ IntToStr(AItem.FoundHour) +EOL+'Expected Hour: '+ IntToStr(AItem.ExpectedHour);
bxUnixLSandSimilar.Status(LStatus);
bxUnixLSandSimilar.Check(AItem.FoundHour =AItem.ExpectedHour, LStatus );
//Minute
LStatus := 'Obtained Minute: '+ IntToStr(AItem.FoundMin) +EOL+'Expected Minute: '+ IntToStr(AItem.ExpectedMin);
bxUnixLSandSimilar.Status(LStatus);
bxUnixLSandSimilar.Check(AItem.FoundMin =AItem.ExpectedMin, LStatus);
//Sec
LStatus := 'Obtained Second: '+ IntToStr(AItem.FoundSec) +EOL+'Expected Second: '+ IntToStr(AItem.ExpectedSec);
bxUnixLSandSimilar.Status(LStatus);
bxUnixLSandSimilar.Check(AItem.FoundSec =AItem.ExpectedSec, LStatus );
end;
//Size
LStatus := 'Obtained Size: '+ IntToStr(AItem.FoundFileSize ) +EOL+'Expected Size: '+ IntToStr(AItem.ExpectedFileSize ) ;
bxUnixLSandSimilar.Status(LStatus);
bxUnixLSandSimilar.Check(AItem.FoundSec =AItem.ExpectedSec, LStatus );
end;
{ TFTPTestItem }
procedure TFTPTestItem.Clear;
begin
FTestItem := '';
FFoundParser := '';
FExpectedParser := '';
//note that the Unix servers can normally only report either a year
//or a time. This can cause ambiguity because the year is interpretted
//according to the current or previous year if the date has passed or arrived. But
//because we can't know the local time zone, there can be a 24 hour window
//of time. E.g. Sept 8 10:00am 2003 can be interpretted as either Sept 8 10:00am 2003 or
//Sept 8, 2002 if in the window of Sept 7 10:00am or Sept 9 10:00am.
//Otherwise, a date such as Sept 8: 10:00am can be interpretted differently at different
//times of the year (when the window period has passed - 2002 or before the window 2003.
FEvaluateTime := True;
FEvaluateYear := True;
//Note that with the BSD -T switch, a time can be returned with seconds
FFoundYear := 0;
FExpectedYear := 0;
FFoundMonth := 0;
FFoundDay := 0;
FFoundHour := 0;
FFoundMin := 0;
FFoundSec := 0;
FExpectedMonth := 0;
FExpectedDay := 0;
FExpectedHour := 0;
FExpectedMin := 0;
FExpectedSec := 0;
FFoundOwner := '';
FExpectedOwner := '';
FFoundGroup := '';
FExpectedGroup := '';
FFoundFileName := '';
FExpectedFileName := '';
FFoundFileSize := 0;
FExpectedFileSize := 0;
end;
procedure TdmFTPListTest.TestItem(ATestItem, AExpectedParser,
AExpectedFileName: String; AExpectedFileSize: Integer; AExpectedYear,
AExpectedMonth, AExpectedDay, AExpectedHour, AExpectedMin,
AExpectedSec: Word);
begin
TestItem(ATestItem,AExpectedParser,'','',AExpectedFileName,AExpectedFileSize,AExpectedYear,AExpectedMonth,AExpectedDay,AExpectedHour,AExpectedMin,AExpectedSec);
end;
procedure TdmFTPListTest.TestItem(ATestItem, AExpectedParser,
AExpectedOwner, AExpectedGroup, AExpectedFileName: String;
AExpectedFileSize: Integer; AExpectedYear, AExpectedMonth, AExpectedDay,
AExpectedHour, AExpectedMin, AExpectedSec: Word);
var LT : TFTPTestItem;
LDir : TStrings;
LDirItems : TIdFTPListItems;
LFormat : String;
LFTPDir : TFTPTestItem;
LI : TIdFTPListItem;
LDummy : Word;
begin
LT := TFTPTestItem.Create;
try
LDir := TStringList.Create;
LDirItems := TIdFTPListItems.Create;
LDir.Add(ATestItem);
LFTPDir := TFTPTestItem.Create;
LFTPDir.TestItem := ATestItem;
CheckListParse(LDir,LDirItems,LFormat);
LFTPDir.EvaluateYear := True;
LFTPDir.EvaluateTime := True;
LFTPDir.FoundParser := LFormat;
LFTPDir.ExpectedParser := AExpectedParser;
if LDirItems.Count <> 1 then
begin
raise Exception.Create('Only 1 item from the parser is expected');
end
else
begin
LI := LDirItems[0];
end;
DecodeDate( LI.ModifiedDate,LFTPDir.FFoundYear,LFTPDir.FFoundMonth,LFTPDir.FFoundDay);
DecodeTime( LI.ModifiedDate,LFTPDir.FFoundHour,LFTPDir.FFoundMin,LFTPDir.FFoundSec,LDummy);
LFTPDir.FoundOwner := LI.OwnerName;
LFTPDir.FoundGroup := LI.GroupName;
LFTPDir.FoundFileName := LI.FileName;
LFTPDir.FoundFileSize := LI.Size;
LFTPDir.ExpectedYear := AExpectedYear;
LFTPDir.ExpectedMonth := AExpectedMonth;
LFTPDir.ExpectedDay := AExpectedDay;
LFTPDir.ExpectedHour := AExpectedHour;
LFTPDir.ExpectedMin := AExpectedMin;
LFTPDir.ExpectedSec := AExpectedSec;
LFTPDir.ExpectedOwner := AExpectedOwner;
LFTPDir.ExpectedGroup := AExpectedGroup;
LFTPDir.ExpectedFileName := AExpectedFileName;
LFTPDir.ExpectedFileSize := AExpectedFileSize;
ReportItem(LFTPDir);
finally
FreeAndNil(LFTPDir);
FreeAndNil(LDirItems);
FreeAndNil(LDir);
FreeAndNil(LT);
end;
end;
procedure TdmFTPListTest.TestItem(ATestItem, AExpectedParser,
AExpectedOwner, AExpectedGroup, AExpectedFileName: String;
AExpectedFileSize: Integer; AExpectedMonth, AExpectedDay, AExpectedHour,
AExpectedMin, AExpectedSec: Word);
var LT : TFTPTestItem;
LDir : TStrings;
LDirItems : TIdFTPListItems;
LFormat : String;
LFTPDir : TFTPTestItem;
LI : TIdFTPListItem;
LDummy : Word;
begin
LT := TFTPTestItem.Create;
try
LDir := TStringList.Create;
LDirItems := TIdFTPListItems.Create;
LDir.Add(ATestItem);
LFTPDir := TFTPTestItem.Create;
LFTPDir.TestItem := ATestItem;
CheckListParse(LDir,LDirItems,LFormat);
LFTPDir.EvaluateYear := False;
LFTPDir.EvaluateTime := True;
LFTPDir.FoundParser := LFormat;
LFTPDir.ExpectedParser := AExpectedParser;
if LDirItems.Count <> 1 then
begin
raise Exception.Create('Only 1 item from the parser is expected');
end
else
begin
LI := LDirItems[0];
end;
DecodeDate( LI.ModifiedDate,LFTPDir.FFoundYear,LFTPDir.FFoundMonth,LFTPDir.FFoundDay);
DecodeTime( LI.ModifiedDate,LFTPDir.FFoundHour,LFTPDir.FFoundMin,LFTPDir.FFoundSec,LDummy);
LFTPDir.FoundOwner := LI.OwnerName;
LFTPDir.FoundGroup := LI.GroupName;
LFTPDir.FoundFileName := LI.FileName;
LFTPDir.FoundFileSize := LI.Size;
LFTPDir.ExpectedMonth := AExpectedMonth;
LFTPDir.ExpectedDay := AExpectedDay;
LFTPDir.ExpectedHour := AExpectedHour;
LFTPDir.ExpectedMin := AExpectedMin;
LFTPDir.ExpectedSec := AExpectedSec;
LFTPDir.ExpectedOwner := AExpectedOwner;
LFTPDir.ExpectedGroup := AExpectedGroup;
LFTPDir.ExpectedFileName := AExpectedFileName;
LFTPDir.ExpectedFileSize := AExpectedFileSize;
ReportItem(LFTPDir);
finally
FreeAndNil(LFTPDir);
FreeAndNil(LDirItems);
FreeAndNil(LDir);
FreeAndNil(LT);
end;
end;
procedure TdmFTPListTest.TestItem(ATestItem, AExpectedParser,
AExpectedOwner, AExpectedGroup, AExpectedFileName: String;
AExpectedFileSize: Integer; AExpectedYear, AExpectedMonth, AExpectedDay : Word);
var LT : TFTPTestItem;
LDir : TStrings;
LDirItems : TIdFTPListItems;
LFormat : String;
LFTPDir : TFTPTestItem;
LI : TIdFTPListItem;
LDummy : Word;
begin
LT := TFTPTestItem.Create;
try
LDir := TStringList.Create;
LDirItems := TIdFTPListItems.Create;
LDir.Add(ATestItem);
LFTPDir := TFTPTestItem.Create;
LFTPDir.TestItem := ATestItem;
CheckListParse(LDir,LDirItems,LFormat);
LFTPDir.EvaluateYear := True;
LFTPDir.EvaluateTime := False;
LFTPDir.FoundParser := LFormat;
LFTPDir.ExpectedParser := AExpectedParser;
if LDirItems.Count <> 1 then
begin
raise Exception.Create('Only 1 item from the parser is expected');
end
else
begin
LI := LDirItems[0];
end;
DecodeDate( LI.ModifiedDate,LFTPDir.FFoundYear,LFTPDir.FFoundMonth,LFTPDir.FFoundDay);
DecodeTime( LI.ModifiedDate,LFTPDir.FFoundHour,LFTPDir.FFoundMin,LFTPDir.FFoundSec,LDummy);
LFTPDir.FoundOwner := LI.OwnerName;
LFTPDir.FoundGroup := LI.GroupName;
LFTPDir.FoundFileName := LI.FileName;
LFTPDir.FoundFileSize := LI.Size;
LFTPDir.ExpectedYear := AExpectedYear;
LFTPDir.ExpectedMonth := AExpectedMonth;
LFTPDir.ExpectedDay := AExpectedDay;
LFTPDir.ExpectedOwner := AExpectedOwner;
LFTPDir.ExpectedGroup := AExpectedGroup;
LFTPDir.ExpectedFileName := AExpectedFileName;
LFTPDir.ExpectedFileSize := AExpectedFileSize;
ReportItem(LFTPDir);
finally
FreeAndNil(LFTPDir);
FreeAndNil(LDirItems);
FreeAndNil(LDir);
FreeAndNil(LT);
end;
end;
procedure TdmFTPListTest.bxWin32IISFormsTest(Sender: TBXBubble);
begin
{Note that these were taken from comments in the FileZilla source-code.
Note that no GNU source-code from that program was used in source-code.
}
//04-27-00 09:09PM <DIR> DOS dir 1
TestItem(
'04-27-00 09:09PM <DIR> DOS dir 1',
WINNTID,
'DOS dir 1',
0,
2000,
4,
27,
21,
9,
0);
//04-14-00 03:47PM 589 DOS file 1
// procedure TestItem(
// ATestItem,
// AExpectedParser,
// AExpectedFileName : String;
// AExpectedFileSize : Integer;
// AExpectedYear,
// AExpectedMonth,
// AExpectedDay,
// AExpectedHour,
// AExpectedMin,
// AExpectedSec : Word); overload;
//Microsoft IIS using Unix format
TestItem(
'04-14-00 03:47PM 589 DOS file 1',
WINNTID,
'DOS file 1',
589,
2000,
4,
14,
15,
47,
0);
//2002-09-02 18:48 <DIR> DOS dir 2
TestItem(
'2002-09-02 18:48 <DIR> DOS dir 2',
WINNTID,
'DOS dir 2',
0,
2002,
9,
2,
18,
48,
0);
//2002-09-02 19:06 9,730 DOS file 2
TestItem(
'2002-09-02 19:06 9,730 DOS file 2',
WINNTID,
'DOS file 2',
9730,
2002,
9,
2,
19,
6,
0);
end;
procedure TdmFTPListTest.bxSterlingComTestsTest(Sender: TBXBubble);
begin
TestItem(
'-C--E-----FTP B QUA1I1 18128 41 Aug 12 13:56 QUADTEST',
STIRCOMUNIX,
'QUA1I1',
'',
'QUADTEST',
41,
8,
12,
13,
56,
0);
TestItem(
'-C--E-----FTP A QUA1I1 18128 41 Aug 12 13:56 QUADTEST2',
STIRCOMUNIX,
'QUA1I1',
'',
'QUADTEST2',
41,
8,
12,
13,
56,
0);
TestItem(
'-ARTE-----TCP A cbeodm 22159 629629 Aug 06 05:47 PSEUDOFILENAME',
STIRCOMUNIX,
'cbeodm',
'',
'PSEUDOFILENAME',
629629,
8,
6,
5,
47,
0);
TestItem(
'solution 00003444 00910368 <c3957010.zip.001> 030924-1636 A R TCP BIN',
STIRCOMUNIXNS,
'solution',
'',
'c3957010.zip.001',
00910368,
2003,
9,
24,
16,
36,
0);
TestItem('solution 00003048 00007341 <POST1202.P1182069.R>+ 030926-0832 A RT TCP ASC',
STIRCOMUNIXNS,
'solution',
'',
'POST1202.P1182069.R', //filename was truncated by the dir format
00007341,
2003,
9,
26,
8,
32,
0);
{
From:
"Connect:Enterprise® UNIX Remote User’s Guide Version 2.1 " Copyright
1999, 2002, 2003 Sterling Commerce, Inc.
==
-C--E-----FTP A steve 2 41 Sep 02 13:47 test.c
-SR--M------- A steve 1 369 Sep 02 13:47 <<ACTIVITY LOG>>
Total number of batches listed: 2
==
}
TestItem('-C--E-----FTP A steve 2 41 Sep 02 13:47 test.c',
STIRCOMUNIX,
'steve',
'',
'test.c',
41,
9,
2,
13,
47,
0);
TestItem('-SR--M------- A steve 1 369 Sep 02 13:47 <<ACTIVITY LOG>>',
STIRCOMUNIX,
'steve',
'',
'<<ACTIVITY LOG>>',
369,
9,
2,
13,
47,
0);
{The proper parser is incapable of returning a date}
TestItem('d - - - - - - - steve',
STIRCOMUNIXROOT,
'',
'',
'steve',
0,
12,
30,
0,
0,
0);
{Sterling Commerce Express for OS/390 tests}
TestItem('-D 2 T VB 00244 18000 FTPGDG!PSR$TST.GDG.TSTGDG0(+01)',
STIRCOMEXPOS390,
'',
'',
'FTPGDG!PSR$TST.GDG.TSTGDG0(+01)',
0,
12,
30,
0,
0,
0);
TestItem('-D 2 * VB 00244 27800 FTPV!PSR$TST.A.VVV.&REQNUMB',
STIRCOMEXPOS390,
'',
'',
'FTPV!PSR$TST.A.VVV.&REQNUMB',
0,
12,
30,
0,
0,
0);
TestItem('-F 1 R - - - FTPVAL1!PSR$TST.A.VVV',
STIRCOMEXPOS390,
'',
'',
'FTPVAL1!PSR$TST.A.VVV',
0,
12,
30,
0,
0,
0);
end;
procedure TdmFTPListTest.bxOS2TestTest(Sender: TBXBubble);
{ From: Jakarta Apache project's test suite.
" 0 DIR 12-30-97 12:32 jbrekke",
" 0 DIR 11-25-97 09:42 junk",
" 0 DIR 05-12-97 16:44 LANGUAGE",
" 0 DIR 05-19-97 12:56 local",
" 0 DIR 05-12-97 16:52 Maintenance Desktop",
" 0 DIR 05-13-97 10:49 MPTN",
"587823 RSA DIR 01-08-97 13:58 OS2KRNL",
" 33280 A 02-09-97 13:49 OS2LDR",
" 0 DIR 11-28-97 09:42 PC",
"149473 A 11-17-98 16:07 POPUPLOG.OS2",
" 0 DIR 05-12-97 16:44 PSFONTS"
}
begin
{note that some of servers are probably NOT Y2K complient}
TestItem(
' 0 DIR 12-30-97 12:32 jbrekke',
OS2PARSER,
'jbrekke',
0,
1997,
12,
30,
12,
32,
0);
TestItem(
' 73098 A 04-06-97 15:15 ds0.internic.net1996052434624.txt',
OS2PARSER,
'ds0.internic.net1996052434624.txt',
73098,
1997,
4,
6,
15,
15,
0);
{
taken from the FileZilla source-code comments
" 0 DIR 05-12-97 16:44 PSFONTS"
"36611 A 04-23-103 10:57 OS2 test1.file"
" 1123 A 07-14-99 12:37 OS2 test2.file"
" 0 DIR 02-11-103 16:15 OS2 test1.dir"
" 1123 DIR A 10-05-100 23:38 OS2 test2.dir"
}
TestItem(
' 0 DIR 05-12-97 16:44 PSFONTS',
OS2PARSER,
'PSFONTS',
0,
1997,
5,
12,
16,
44,
0);
TestItem(
'36611 A 04-23-103 10:57 OS2 test1.file',
OS2PARSER,
'OS2 test1.file',
36611,
2003,
4,
23,
10,
57,
0);
TestItem(
' 1123 A 07-14-99 12:37 OS2 test2.file',
OS2PARSER,
'OS2 test2.file',
1123,
1999,
7,
14,
12,
37,
0);
TestItem(
' 0 DIR 02-11-103 16:15 OS2 test1.dir',
OS2PARSER,
'OS2 test1.dir',
0,
2003,
2,
11,
16,
15,
0);
TestItem(
' 1123 DIR A 10-05-100 23:38 OS2 test2.dir',
OS2PARSER,
'OS2 test2.dir',
1123,
2000,
10,
5,
23,
38,
0);
end;
end.
|
//************************************************************************
//
// Program Name : AT Library
// Platform(s) : Android, iOS, Linux, MacOS, Windows
// Framework : Console, FMX, VCL
//
// Filename : AT.Config.Storage.XML.pas
// Date Created : 01-AUG-2014
// Author : Matthew Vesperman
//
// Description:
//
// XML config storage class.
//
// Revision History:
//
// v1.00 : Initial version
// v1.10 : Added DeleteSection method
//
//************************************************************************
//
// COPYRIGHT © 2014 Angelic Technology
// ALL RIGHTS RESERVED WORLDWIDE
//
//************************************************************************
/// <summary>
/// XML file based configuration storage class.
/// </summary>
unit AT.Config.Storage.XML;
interface
uses
System.Classes, AT.Config.Storage.Custom, System.SysUtils, OXmlPDOM,
AT.Config.Storage.Intf;
type
TATConfigXMLStorage = class(TATCustomConfigStorage,
ICfgStgDelete, ICfgStgQuery, ICfgStgRead, ICfgStgWrite)
strict private
FFileName: TFileName;
FXMLDoc: IXMLDocument;
FXMLRoot: PXMLNode;
strict protected
function CreateNewConfig(const sFileName: TFileName): Boolean; virtual;
function GetEntry(const sSection, sEntry: String; var AEntry: PXMLNode; const
AutoCreate: Boolean = True): Boolean; virtual;
function GetSection(const sSection: String; var ASection: PXMLNode; const
AutoCreate: Boolean = True): Boolean; virtual;
function HasEntry(const sSection: String; const sEntry: String): Boolean;
virtual;
function HasSection(const sSection: String): Boolean; virtual;
function LoadConfig(const sFileName: TFileName): Boolean; virtual;
function ReadValue(const sSection: String; sEntry: String; var AValue:
String): Boolean; virtual;
procedure ReloadConfig; virtual;
function SaveConfig: Boolean; virtual;
procedure WriteValue(const sSection: String; const sEntry: String; const
sValue: String); virtual;
public
constructor Create; overload; override;
constructor Create(const sFileName: TFileName); overload; virtual;
destructor Destroy; override;
procedure DeleteEntry(const sSection: String; const sEntry: String);
override;
procedure DeleteSection(const sSection: String); override;
function ReadBoolean(const sSection: String; const sEntry: String; const
bDefault: Boolean): Boolean; override;
function ReadCurrency(const sSection: String; const sEntry: String; const
cDefault: Currency): Currency; override;
function ReadDate(const sSection: String; const sEntry: String; const
dtDefault: TDateTime): TDateTime; override;
function ReadDateTime(const sSection: String; const sEntry: String; const
dtDefault: TDateTime): TDateTime; override;
function ReadDouble(const sSection: String; const sEntry: String; const
rDefault: Double): Double; override;
function ReadInteger(const sSection: String; const sEntry: String; const
iDefault: Integer): Integer; override;
function ReadString(const sSection, sEntry, sDefault: String): string; override;
function ReadTime(const sSection: String; const sEntry: String; const
dtDefault: TDateTime): TDateTime; override;
procedure WriteBoolean(const sSection: String; const sEntry: String; const
bValue: Boolean); override;
procedure WriteCurrency(const sSection: String; const sEntry: String; const
cValue: Currency); override;
procedure WriteDate(const sSection: String; const sEntry: String; const
dtValue: TDateTime); override;
procedure WriteDateTime(const sSection: String; const sEntry: String; const
dtValue: TDateTime); override;
procedure WriteDouble(const sSection: String; const sEntry: String; const
rValue: Double); override;
procedure WriteInteger(const sSection: String; const sEntry: String; const
iValue: Integer); override;
procedure WriteString(const sSection: String; const sEntry: String; const
sValue: String); override;
procedure WriteTime(const sSection: String; const sEntry: String; const
dtValue: TDateTime); override;
published
property FileName: TFileName read FFileName write FFileName;
end;
implementation
uses
OXmlUtils, AT.Validate, AT.XPlatform;
const
cCfgCRLF = #13#10;
cCfgRootNode = 'configuration';
cCfgLastMod = 'last-modified';
cCfgPlatform = 'platform';
cCfgFramework = 'framework';
cCfgHostName = 'hostname';
cCfgOSUser = 'os-user';
cCFGSectNode = 'section';
cCfgEntrNode = 'entry';
cCfgAttrKey = 'key';
cCfgAttrValue = 'value';
cCfgTrueValue = 'True';
cCfgFalseValue = 'False';
resourcestring
resCfgHdrComnt1 =
'**********************************************************************************';
resCfgHdrComnt2 =
' UNLESS INSTRUCTED TO DO SO, DO NOT MAKE ANY MANUAL CHANGES TO THIS FILE. ';
resCfgHdrComnt3 =
' DOING SO CAN MAKE YOUR SOFTWARE RUN INCORRECTLY, OR COULD EVEN MAKE IT UNUSABLE. ';
resCfgHdrComnt4 =
' IF YOU MAKE MANUAL CHANGES YOU DO SO AT YOUR OWN RISK! ';
resCfgHdrComnt5 =
'**********************************************************************************';
{
***************************** TATConfigXMLStorage ******************************
}
constructor TATConfigXMLStorage.Create;
begin
inherited Create;
end;
constructor TATConfigXMLStorage.Create(const sFileName: TFileName);
begin
Self.Create;
Self.FileName := sFileName;
FXMLDoc := CreateXMLDoc(cCfgRootNode, True);
FXMLDoc.WhiteSpaceHandling := wsTrim;
FXMLDoc.WriterSettings.IndentType := itIndent;
FXMLDoc.WriterSettings.LineBreak := lbCRLF;
if (FileExists(Self.FileName)) then
begin
LoadConfig(Self.FileName);
end
else
begin
CreateNewConfig(Self.FileName);
end;
end;
destructor TATConfigXMLStorage.Destroy;
begin
SaveConfig;
inherited Destroy;
end;
function TATConfigXMLStorage.CreateNewConfig(const sFileName: TFileName):
Boolean;
var
ANode: PXMLNode;
begin
Result := False;
if (Assigned(FXMLDoc)) then
begin
Self.FFileName := sFileName;
FXMLRoot := FXMLDoc.DocumentElement;
ANode := FXMLDoc.CreateComment(resCfgHdrComnt1);
FXMLRoot.AppendChild(ANode);
ANode := FXMLDoc.CreateComment(resCfgHdrComnt2);
FXMLRoot.AppendChild(ANode);
ANode := FXMLDoc.CreateComment(resCfgHdrComnt3);
FXMLRoot.AppendChild(ANode);
ANode := FXMLDoc.CreateComment(resCfgHdrComnt4);
FXMLRoot.AppendChild(ANode);
ANode := FXMLDoc.CreateComment(resCfgHdrComnt5);
FXMLRoot.AppendChild(ANode);
Self.SaveConfig;
end;
end;
procedure TATConfigXMLStorage.DeleteEntry(const sSection: String; const sEntry:
String);
var
BOk : Boolean;
AEntry: PXMLNode;
begin
BOk := GetEntry(sSection, sEntry, AEntry);
if (BOk) then
begin
AEntry.DeleteSelf;
Self.SaveConfig;
Self.ReloadConfig;
end;
end;
procedure TATConfigXMLStorage.DeleteSection(const sSection: String);
var
BOk : Boolean;
ASection: PXMLNode;
begin
BOk := GetSection(sSection, ASection);
if (BOk) then
begin
ASection.DeleteSelf;
Self.SaveConfig;
Self.ReloadConfig;
end;
end;
function TATConfigXMLStorage.GetEntry(const sSection, sEntry: String; var
AEntry: PXMLNode; const AutoCreate: Boolean = True): Boolean;
var
ASection: PXMLNode;
ANode : PXMLNode;
AAttr : PXMLNode;
begin
AEntry := NIL;
if (GetSection(sSection, ASection)) then
begin
ANode := NIL;
while (ASection.GetNextChild(ANode)) do
begin
if ((ANode.NodeType = ntElement) AND (ANode.NodeName = cCfgEntrNode))
then
begin
AAttr := NIL;
while (ANode.GetNextAttribute(AAttr)) do
begin
if ((AAttr.NodeName = cCfgAttrKey) AND
(AAttr.NodeValue = sEntry)) then
begin
AEntry := ANode;
Break;
end;
end;
end;
if (Assigned(AEntry)) then
Break;
end;
if (AutoCreate AND (NOT Assigned(AEntry)) ) then
begin
AEntry := ASection.AddChild(cCfgEntrNode);
AEntry.AddAttribute(cCfgAttrKey, sEntry);
end;
end;
Result := (Assigned(AEntry));
end;
function TATConfigXMLStorage.GetSection(const sSection: String; var ASection:
PXMLNode; const AutoCreate: Boolean = True): Boolean;
var
ANode: PXMLNode;
AAttr: PXMLNode;
begin
ASection := NIL;
if (Assigned(FXMLRoot)) then
begin
ANode := NIL;
while (FXMLRoot.GetNextChild(ANode)) do
begin
if ((ANode.NodeType = ntElement) AND (ANode.NodeName = cCFGSectNode))
then
begin
AAttr := NIL;
while (ANode.GetNextAttribute(AAttr)) do
begin
if ((AAttr.NodeName = cCfgAttrKey) AND
(AAttr.NodeValue = sSection)) then
begin
ASection := ANode;
Break;
end;
end;
end;
if (Assigned(ASection)) then
Break;
end;
if ( AutoCreate AND (NOT Assigned(ASection)) ) then
begin
ASection := FXMLRoot.AddChild(cCFGSectNode);
ASection.AddAttribute(cCfgAttrKey, sSection);
end;
end;
Result := (Assigned(ASection));
end;
function TATConfigXMLStorage.HasEntry(const sSection: String; const sEntry:
String): Boolean;
var
AEntry: PXMLNode;
begin
Result := Self.GetEntry(sSection, sEntry, AEntry);
end;
function TATConfigXMLStorage.HasSection(const sSection: String): Boolean;
var
ASection: PXMLNode;
begin
Result := Self.GetSection(sSection, ASection, False);
end;
function TATConfigXMLStorage.LoadConfig(const sFileName: TFileName): Boolean;
begin
Result := False;
if (Assigned(FXMLDoc)) then
begin
FFileName := sFileName;
FXMLDoc.Clear(True);
FXMLDoc.LoadFromFile(Self.FileName);
FXMLRoot := FXMLDoc.DocumentElement;
Result := True;
end;
end;
function TATConfigXMLStorage.ReadBoolean(const sSection: String; const sEntry:
String; const bDefault: Boolean): Boolean;
var
sValue: String;
begin
if (ReadValue(sSection, sEntry, sValue)) then
begin
if (IsStrBoolean(sValue)) then
begin
Result := IsStrBooleanTrue(sValue);
end
else
begin
Result := bDefault;
end;
end
else
begin
Result := bDefault;
end;
end;
function TATConfigXMLStorage.ReadCurrency(const sSection: String; const sEntry:
String; const cDefault: Currency): Currency;
var
sValue: String;
begin
if (ReadValue(sSection, sEntry, sValue)) then
begin
if (IsStrCurrency(sValue)) then
begin
Result := StrToCurr(sValue);
end
else
begin
Result := cDefault;
end;
end
else
begin
Result := cDefault;
end;
end;
function TATConfigXMLStorage.ReadDate(const sSection: String; const sEntry:
String; const dtDefault: TDateTime): TDateTime;
var
sValue: String;
begin
if (ReadValue(sSection, sEntry, sValue)) then
begin
if (IsStrDate(sValue)) then
begin
Result := StrToDate(sValue);
end
else
begin
Result := dtDefault;
end;
end
else
begin
Result := dtDefault;
end;
end;
function TATConfigXMLStorage.ReadDateTime(const sSection: String; const sEntry:
String; const dtDefault: TDateTime): TDateTime;
var
sValue: String;
begin
if (ReadValue(sSection, sEntry, sValue)) then
begin
if (IsStrDateTime(sValue)) then
begin
Result := StrToDateTime(sValue);
end
else
begin
Result := dtDefault;
end;
end
else
begin
Result := dtDefault;
end;
end;
function TATConfigXMLStorage.ReadDouble(const sSection: String; const sEntry:
String; const rDefault: Double): Double;
var
sValue: String;
begin
if (ReadValue(sSection, sEntry, sValue)) then
begin
if (IsStrReal(sValue)) then
begin
Result := StrToFloat(sValue);
end
else
begin
Result := rDefault;
end;
end
else
begin
Result := rDefault;
end;
end;
function TATConfigXMLStorage.ReadInteger(const sSection: String; const sEntry:
String; const iDefault: Integer): Integer;
var
rValue: Double;
sValue: String;
begin
if (ReadValue(sSection, sEntry, sValue)) then
begin
if (IsStrInteger(sValue)) then
begin
Result := StrToInt(sValue);
end
else if (IsStrReal(sValue)) then
begin
rValue := StrToFloat(sValue);
Result := Trunc(rValue);
end
else
begin
Result := iDefault;
end;
end
else
begin
Result := iDefault;
end;
end;
function TATConfigXMLStorage.ReadString(const sSection, sEntry, sDefault:
String): string;
var
sValue: String;
begin
sValue := sDefault;
if (ReadValue(sSection, sEntry, sValue)) then
begin
Result := sValue;
end
else
begin
Result := sDefault;
end;
end;
function TATConfigXMLStorage.ReadTime(const sSection: String; const sEntry:
String; const dtDefault: TDateTime): TDateTime;
var
sValue: String;
begin
if (ReadValue(sSection, sEntry, sValue)) then
begin
if (IsStrTime(sValue)) then
begin
Result := StrToTime(sValue);
end
else
begin
Result := dtDefault;
end;
end
else
begin
Result := dtDefault;
end;
end;
function TATConfigXMLStorage.ReadValue(const sSection: String; sEntry: String;
var AValue: String): Boolean;
var
AEntry: PXMLNode;
begin
ReloadConfig;
Result := GetEntry(sSection, sEntry, AEntry);
if (Result) then
begin
Result := AEntry.HasAttribute(cCfgAttrValue);
if (Result) then
AValue := AEntry.Attributes[cCfgAttrValue];
end;
end;
procedure TATConfigXMLStorage.ReloadConfig;
begin
Self.LoadConfig(Self.FileName);
end;
function TATConfigXMLStorage.SaveConfig: Boolean;
var
ADT : TDateTime;
SDT : String;
AArch: TATAppArchitecture;
sArch: string;
AFwk: TATAppFramework;
sFwk: string;
sHostName: String;
sOSUser: String;
begin
Result := False;
if (Assigned(FXMLDoc)) then
begin
ADT := Now;
SDT := DateTimeToStr(ADT);
FXMLRoot.Attributes[cCfgLastMod] := SDT;
{$IF Defined(ISAPI_APP)}
sArch := 'ISAPI Module';
{$ELSE}
AArch := AT.XPlatform.GetAppArchitecture;
case AArch of
archUnknown: sArch := '';
archMacOS32: sArch := 'OSX32';
archMacOS64: sArch := 'OSX64';
archAndroid: sArch := 'Android';
archIOS: sArch := 'iOS';
archWin32: sArch := 'Win32';
archWin64: sArch := 'Win64';
end;
{$ENDIF}
AFwk := AT.XPlatform.GetFrameworkType;
case AFwk of
fwkNone : sFwk := 'None';
fwkVCL : sFwk := 'VCL';
fwkFMX : sFwk := 'FireMonkey';
fwkIW14: sFwk := 'IntraWeb';
end;
sHostName := AT.XPlatform.GetComputerName;
sOSUser := AT.XPlatform.GetOSUserName;
FXMLRoot.Attributes[cCfgPlatform] := sArch;
FXMLRoot.Attributes[cCfgFramework] := sFwk;
FXMLRoot.Attributes[cCfgHostName] := sHostName;
FXMLRoot.Attributes[cCfgOSUser] := sOSUser;
FXMLDoc.SaveToFile(Self.FileName);
Result := True;
end;
end;
procedure TATConfigXMLStorage.WriteBoolean(const sSection: String; const
sEntry: String; const bValue: Boolean);
var
sValue: String;
begin
if (bValue) then
sValue := cCfgTrueValue
else
sValue := cCfgFalseValue;
WriteValue(sSection, sEntry, sValue);
end;
procedure TATConfigXMLStorage.WriteCurrency(const sSection: String; const
sEntry: String; const cValue: Currency);
var
sValue: String;
begin
sValue := CurrToStr(cValue);
WriteValue(sSection, sEntry, sValue);
end;
procedure TATConfigXMLStorage.WriteDate(const sSection: String; const sEntry:
String; const dtValue: TDateTime);
var
sValue: String;
begin
sValue := DateToStr(dtValue);
WriteValue(sSection, sEntry, sValue);
end;
procedure TATConfigXMLStorage.WriteDateTime(const sSection: String; const
sEntry: String; const dtValue: TDateTime);
var
sValue: String;
begin
sValue := DateTimeToStr(dtValue);
WriteValue(sSection, sEntry, sValue);
end;
procedure TATConfigXMLStorage.WriteDouble(const sSection: String; const sEntry:
String; const rValue: Double);
var
sValue: String;
begin
sValue := FloatToStr(rValue);
WriteValue(sSection, sEntry, sValue);
end;
procedure TATConfigXMLStorage.WriteInteger(const sSection: String; const
sEntry: String; const iValue: Integer);
var
sValue: String;
begin
sValue := IntToStr(iValue);
WriteValue(sSection, sEntry, sValue);
end;
procedure TATConfigXMLStorage.WriteString(const sSection: String; const sEntry:
String; const sValue: String);
begin
WriteValue(sSection, sEntry, sValue);
end;
procedure TATConfigXMLStorage.WriteTime(const sSection: String; const sEntry:
String; const dtValue: TDateTime);
var
sValue: String;
begin
sValue := TimeToStr(dtValue);
WriteValue(sSection, sEntry, sValue);
end;
procedure TATConfigXMLStorage.WriteValue(const sSection: String; const sEntry:
String; const sValue: String);
var
BOk : Boolean;
AEntry: PXMLNode;
begin
BOk := GetEntry(sSection, sEntry, AEntry);
if (BOk) then
begin
AEntry.Attributes[cCfgAttrValue] := sValue;
Self.SaveConfig;
Self.ReloadConfig;
end;
end;
initialization
RegisterClass(TATConfigXMLStorage);
end.
|
unit VTIDEEditors;
{$mode objfpc}{$H+}
interface
uses
ComponentEditors, PropEdits, VirtualTrees;
type
// The usual trick to make a protected property accessible in the ShowCollectionEditor call below.
TVirtualTreeCast = class(TBaseVirtualTree);
{ TVirtualTreeEditor }
TVirtualTreeEditor = class(TComponentEditor)
public
procedure Edit; override;
function GetVerbCount: Integer; override;
function GetVerb(Index: Integer): string; override;
procedure ExecuteVerb(Index: Integer); override;
end;
TLazVirtualTreeEditor = class(TVirtualTreeEditor);
implementation
{ TVirtualTreeEditor }
procedure TVirtualTreeEditor.Edit;
var
Tree: TVirtualTreeCast;
begin
Tree := TVirtualTreeCast(GetComponent);
TCollectionPropertyEditor.ShowCollectionEditor(Tree.Header.Columns, Tree, 'Columns');
end;
function TVirtualTreeEditor.GetVerbCount: Integer;
begin
Result := 1;
end;
function TVirtualTreeEditor.GetVerb(Index: Integer): string;
begin
case Index of
0: Result := 'Edit Columns...';
end;
end;
procedure TVirtualTreeEditor.ExecuteVerb(Index: Integer);
begin
case Index of
0: Edit;
end;
end;
end.
|
unit _fmMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.Menus, Vcl.AppEvnts,
Vcl.ComCtrls, Vcl.StdCtrls, JvExStdCtrls, JvEdit, System.IOUtils,
System.DateUtils, System.Types, JdcGlobal, System.StrUtils, System.ZLib;
type
TfmMain = class(TForm)
Label1: TLabel;
procedure FormCreate(Sender: TObject);
private
FDebug: boolean;
FSubFolder: boolean;
FBackUpFolder: string;
procedure PrintLog(AValue: string);
procedure CheckDir(APath: string; ADateTime: TDateTime);
procedure CheckFile(MyFile: string; ADateTime: TDateTime);
public
{ Public declarations }
end;
var
fmMain: TfmMain;
implementation
{$R *.dfm}
uses Global, Option;
procedure TfmMain.FormCreate(Sender: TObject);
var
DateTime: TDateTime;
begin
try
try
TGlobal.Obj.ExeName := Application.ExeName;
TOption.Obj.Year := TOption.Obj.Year;
TOption.Obj.Month := TOption.Obj.Month;
TOption.Obj.Day := TOption.Obj.Day;
TOption.Obj.Hour := TOption.Obj.Hour;
TOption.Obj.Minute := TOption.Obj.Minute;
TOption.Obj.Second := TOption.Obj.Second;
TOption.Obj.Backup := TOption.Obj.Backup;
TOption.Obj.SubDir := TOption.Obj.SubDir;
TOption.Obj.Debug := TOption.Obj.Debug;
TOption.Obj.SearchPattern := TOption.Obj.SearchPattern;
if (TOption.Obj.Year + TOption.Obj.Month + TOption.Obj.Day +
TOption.Obj.Hour + TOption.Obj.Minute + TOption.Obj.Second) = 0 then
Exit;
DateTime := now;
DateTime := IncYear(DateTime, -1 * TOption.Obj.Year);
DateTime := IncMonth(DateTime, -1 * TOption.Obj.Month);
DateTime := IncDay(DateTime, -1 * TOption.Obj.Day);
DateTime := IncHour(DateTime, -1 * TOption.Obj.Hour);
DateTime := IncMinute(DateTime, -1 * TOption.Obj.Minute);
DateTime := IncSecond(DateTime, -1 * TOption.Obj.Second);
FDebug := TOption.Obj.Debug;
FSubFolder := TOption.Obj.SubDir;
FBackUpFolder := TOption.Obj.Backup;
CheckDir(ExtractFilePath(TGlobal.Obj.ExeName), DateTime);
except
on E: Exception do
PrintLog('Error - ' + E.Message);
end;
finally
Application.Terminate;
end;
end;
procedure TfmMain.PrintLog(AValue: string);
begin
JdcGlobal.PrintLog(ChangeFileExt(TGlobal.Obj.ExeName, '.log'), AValue);
end;
procedure TfmMain.CheckDir(APath: string; ADateTime: TDateTime);
var
Files: TStringDynArray;
MyDir, MyFile: String;
tmp: string;
begin
if not TDirectory.Exists(APath) then
raise Exception.Create('Not exist. ' + APath);
if (FBackUpFolder <> '') and StartsText(FBackUpFolder, APath) then
Exit;
for MyDir in TDirectory.GetDirectories(APath) do
begin
CheckDir(MyDir, ADateTime);
end;
tmp := ChangeFileExt(ExtractFileName(TGlobal.Obj.ExeName), '');
for MyFile in TDirectory.GetFiles(APath, TOption.Obj.SearchPattern) do
begin
if StartsText(tmp, ExtractFileName(MyFile)) then
Continue;
CheckFile(MyFile, ADateTime);
Sleep(1);
end;
Files := TDirectory.GetFiles(APath, '*', TSearchOption.soAllDirectories);
if Length(Files) = 0 then
TDirectory.Delete(APath, True);
end;
procedure TfmMain.CheckFile(MyFile: string; ADateTime: TDateTime);
var
WriteTime: TDateTime;
BackUpPath: String;
begin
WriteTime := TFile.GetLastWriteTime(MyFile);
if FDebug then
PrintLog(MyFile + '\ Time : ' + DateTimeToStr(WriteTime) + ', Check Time : '
+ DateTimeToStr(ADateTime));
if WriteTime < ADateTime then
begin
try
try
if FBackUpFolder = '' then
Exit;
if FSubFolder then
BackUpPath := FBackUpFolder + '\' + FormatDateTime('YYYYMM',
WriteTime) + '\' + FormatDateTime('DD', WriteTime)
else
BackUpPath := FBackUpFolder;
TDirectory.CreateDirectory(BackUpPath);
BackUpPath := BackUpPath + '\' + ExtractFileName(MyFile);
TFile.Copy(MyFile, BackUpPath, True);
except
on E: Exception do
begin
PrintLog(BackUpPath + ', ' + E.Message);
end;
end;
finally
if TFile.Exists(MyFile) then
TFile.Delete(MyFile);
end;
end;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.