text
stringlengths
14
6.51M
unit UPrescricao; interface uses UEntidade , UFuncionario , UCliente , UMedicamento; type TPrescricao = class(TENTIDADE) public FUNCIONARIO : TFUNCIONARIO; CLIENTE : TCLIENTE; MEDICAMENTO : TMEDICAMENTO; DESCRICAO : String; DATA_HORA_PRESCRITA : TDateTime; DATA_HORA_VENCIMENTO : TDate; constructor Create; override; destructor Destroy; override; end; const TBL_PRESCRICAO = 'PRESCRICAO'; FLD_PRESCRICAO_COD_FUNCIONARIO = 'COD_FUNCIONARIO'; FLD_PRESCRICAO_COD_CLIENTE = 'COD_CLIENTE'; FLD_PRESCRICAO_COD_MEDICAMENTO = 'COD_MEDICAMENTO'; FLD_PRESCRICAO_DESCRICAO = 'DESCRICAO'; FLD_PRESCRICAO_DATA_HORA_PRESCRITA = 'DATA_HORA_PRESCRITA'; FLD_PRESCRICAO_DATA_HORA_VENCIMENTO = 'DATA_VENCIMENTO'; resourcestring STR_PRESCRICAO = 'Prescricao'; implementation uses SysUtils , Dialogs ; { TPrescricao } constructor TPrescricao.Create; begin inherited; FUNCIONARIO := TFUNCIONARIO.Create; CLIENTE := TCliente.Create; MEDICAMENTO := TMEDICAMENTO.Create; end; destructor TPrescricao.Destroy; begin FreeAndNil(FUNCIONARIO); FreeAndNil(CLIENTE); FreeAndNil(MEDICAMENTO); inherited; end; end.
unit Alcinoe.AndroidApi.AndroidX; interface // Java Type Delphi Type // boolean Boolean // byte ShortInt // char WideChar // double Double // float Single // int Integer // long Int64 // short SmallInt // void N/A uses Androidapi.JNI.Widget, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.Util, Androidapi.JNIBridge, Androidapi.JNI.Net, Androidapi.JNI.JavaTypes; type {*********************************} JLocalBroadcastManager = interface; JLifecycleOwner = interface; Jlifecycle_Observer = interface; JLiveData = interface; JMutableLiveData = interface; JPreferenceManager = interface; {*************************************************************************} //https://developer.android.com/reference/androidx/lifecycle/LifecycleOwner JLifecycleOwnerClass = interface(IJavaClass) ['{4A72E007-665C-4E9A-BF6A-3997CC4C55FB}'] end; [JavaSignature('androidx/lifecycle/LifecycleOwner')] JLifecycleOwner = interface(IJavaInstance) ['{4ECDBBFC-2F20-471F-912E-BE96CA23E96E}'] end; TJLifecycleOwner = class(TJavaGenericImport<JLifecycleOwnerClass, JLifecycleOwner>) end; {****************************************************************************************************} //https://developer.android.com/reference/androidx/localbroadcastmanager/content/LocalBroadcastManager JLocalBroadcastManagerClass = interface(JObjectClass) ['{03179F7E-C439-4369-93CC-AA2BADC54398}'] {class} function getInstance(context: JContext): JLocalBroadcastManager; cdecl; deprecated; end; [JavaSignature('androidx/localbroadcastmanager/content/LocalBroadcastManager')] JLocalBroadcastManager = interface(JObject) ['{6C255CD6-D94E-40BC-A758-EC4965A40725}'] procedure registerReceiver(receiver: JBroadcastReceiver; filter: JIntentFilter); cdecl; deprecated; function sendBroadcast(intent: JIntent): Boolean; cdecl; deprecated; procedure sendBroadcastSync(intent: JIntent); cdecl; deprecated; procedure unregisterReceiver(receiver: JBroadcastReceiver); cdecl; deprecated; end; TJLocalBroadcastManager = class(TJavaGenericImport<JLocalBroadcastManagerClass, JLocalBroadcastManager>) end; {*******************************************************************} //https://developer.android.com/reference/androidx/lifecycle/Observer Jlifecycle_ObserverClass = interface(IJavaClass) ['{4AF7ACEE-58A0-4FED-BE07-21162B9AA120}'] end; [JavaSignature('androidx/lifecycle/Observer')] Jlifecycle_Observer = interface(IJavaInstance) ['{A78847B9-5FDD-4E82-86A0-4D026F433099}'] procedure onChanged(t: JObject); cdecl; end; TJlifecycle_Observer = class(TJavaGenericImport<Jlifecycle_ObserverClass, Jlifecycle_Observer>) end; {*******************************************************************} //https://developer.android.com/reference/androidx/lifecycle/LiveData JLiveDataClass = interface(JObjectClass) ['{57738F7E-F789-4911-90D1-9C8E14720CC0}'] end; [JavaSignature('androidx/lifecycle/LiveData')] JLiveData = interface(JObject) ['{520539FF-2147-4B43-8287-23E12551B616}'] function getValue: JObject; cdecl; function hasActiveObservers: Boolean; cdecl; function hasObservers: Boolean; cdecl; procedure observe(owner: JLifecycleOwner; observer: Jlifecycle_Observer); cdecl; procedure observeForever(observer: Jlifecycle_Observer); cdecl; procedure postValue(value: JObject); cdecl; procedure removeObserver(observer: Jlifecycle_Observer); cdecl; procedure removeObservers(owner: JLifecycleOwner); cdecl; procedure setValue(value: JObject); cdecl; end; TJLiveData = class(TJavaGenericImport<JLiveDataClass, JLiveData>) end; {**************************************************************************} //https://developer.android.com/reference/androidx/lifecycle/MutableLiveData JMutableLiveDataClass = interface(JLiveDataClass) ['{F28C102C-51C2-4048-8FCC-9AB9EA939938}'] end; [JavaSignature('androidx/lifecycle/MutableLiveData')] JMutableLiveData = interface(JLiveData) ['{597E7685-0F91-4384-A153-818DD5436B5D}'] end; TJMutableLiveData = class(TJavaGenericImport<JMutableLiveDataClass, JMutableLiveData>) end; {*****************************************************************************} //https://developer.android.com/reference/androidx/preference/PreferenceManager JPreferenceManagerClass = interface(JObjectClass) ['{2BCBB8F6-B5EE-441E-B01B-5F7E37A783B5}'] {class} function getDefaultSharedPreferences(context: JContext): JSharedPreferences; cdecl; end; [JavaSignature('androidx/preference/PreferenceManager')] JPreferenceManager = interface(JObject) ['{62FC9030-B469-461B-98AD-C5E3F9AAACBA}'] end; TJPreferenceManager = class(TJavaGenericImport<JPreferenceManagerClass, JPreferenceManager>) end; implementation {**********************} procedure RegisterTypes; begin TRegTypes.RegisterType('Alcinoe.AndroidApi.AndroidX.JLocalBroadcastManager', TypeInfo(Alcinoe.AndroidApi.AndroidX.JLocalBroadcastManager)); TRegTypes.RegisterType('Alcinoe.AndroidApi.AndroidX.JLifecycleOwner', TypeInfo(Alcinoe.AndroidApi.AndroidX.JLifecycleOwner)); TRegTypes.RegisterType('Alcinoe.AndroidApi.AndroidX.Jlifecycle_Observer', TypeInfo(Alcinoe.AndroidApi.AndroidX.Jlifecycle_Observer)); TRegTypes.RegisterType('Alcinoe.AndroidApi.AndroidX.JLiveData', TypeInfo(Alcinoe.AndroidApi.AndroidX.JLiveData)); TRegTypes.RegisterType('Alcinoe.AndroidApi.AndroidX.JMutableLiveData', TypeInfo(Alcinoe.AndroidApi.AndroidX.JMutableLiveData)); TRegTypes.RegisterType('Alcinoe.AndroidApi.AndroidX.JPreferenceManager', TypeInfo(Alcinoe.AndroidApi.AndroidX.JPreferenceManager)); end; initialization RegisterTypes; end.
program TirArc; type tab=array[1..20] of string; (* Le type du tableau qui va contenir les noms des joueurs*) bull=array[1..20] of integer; (* Le type du tableau qui va contenir les scores des joueurs*) var A:tab; N:integer; (* La fonction alpha qui sert à verifier que les noms saisies sont composés de lettres et de espaces*) function Alpha(s:string) : boolean; var i:integer; begin Alpha:=true; if length(s)>30 then Alpha:=false; for i:=1 to length(s) do begin if not((s[i] in ['a'..'z']) or (s[i] in ['A'..'Z']) or (s[i]=' ')) then Alpha:=false; end; end; (* La procedure saisieEssai qui sert à remplir le tableau A par les noms des joueurs*) procedure saisieNoms(var tableau:tab; var n:integer); var i:integer; begin for i:=1 to n do begin repeat writeln('Donner le nom du joueur numéro ', i, ' :'); readln(tableau[i]); until(Alpha(tableau[i])) end; end; (* La procedure Score qui sert à remplir un tableau de scores (bulletin) puis à trier le tableau A par ordre décroissant des scores*) procedure Score(var tableau:tab; var n:integer); var i,j,k:integer; (* compteurs et variables auxilières*) bulletin:bull; s:string; (* variable auxilière *) begin for i:=1 to n do begin bulletin[i]:=0; for j:=1 to 3 do begin repeat writeln('Donner le résultat de l''essai numéro ', j,' du joueur numéro ', i, ' (', tableau[i],'):'); readln(k); until((-1<k) and (k<11)); bulletin[i]:=bulletin[i]+k; end; end; for i:=1 to n do begin writeln(bulletin[i], tableau[i]); end; for i:=1 to n do begin for j:=i to n do begin (* Ici le tableau bulletin est trié et le tableau tableau le suit afin qu'il reste une correspondance entre les noms et les score à un indice donné i. *) if bulletin[j]>bulletin[i] then begin k:=bulletin[i]; bulletin[i]:=bulletin[j]; bulletin[j]:=k; s:=tableau[i]; tableau[i]:=tableau[j]; tableau[j]:=s; end; end; writeln(tableau[i], ' avec un score de ', bulletin[i]); end; end; begin repeat writeln('Donner le nombre de joueurs :'); readln(N); until(N in [2..20]); writeln('***********************'); writeln(); saisieNoms(A,N); writeln('***********************'); writeln(); Score(A,N); end.
unit NotaInutilizada; interface uses SysUtils, Contnrs; type TNotaInutilizada = class private Fcodigo :Integer; Fmodelo :String; Fserie :String; Finicio :Integer; Ffim :Integer; Fjustificativa :String; public property codigo :Integer read Fcodigo write Fcodigo; property modelo :String read Fmodelo write Fmodelo; property serie :String read Fserie write Fserie; property inicio :Integer read Finicio write Finicio; property fim :Integer read Ffim write Ffim; property justificativa :String read Fjustificativa write Fjustificativa; end; implementation { TNotaInutilizada } end.
unit RTXCNotetipsActiveXContainerLib_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. // ************************************************************************ // // $Rev: 52393 $ // File generated on 2014/11/14 14:07:45 from Type Library described below. // ************************************************************************ // // Type Lib: {62B4856D-8644-4DFE-B8BD-AA4C7EAD8AF0} // LIBID: // LCID: 0 // Helpfile: // HelpString: // DepndLst: // (1) v2.0 stdole, (C:\Windows\SysWOW64\stdole2.tlb) // (2) v4.0 StdVCL, (stdvcl40.dll) // SYS_KIND: SYS_WIN32 // ************************************************************************ // {$TYPEDADDRESS OFF} // Unit must be compiled without type-checked pointers. {$WARN SYMBOL_PLATFORM OFF} {$WRITEABLECONST ON} {$VARPROPSETTER ON} {$ALIGN 4} interface uses Winapi.Windows, System.Classes, System.Variants, System.Win.StdVCL, Vcl.Graphics, Vcl.OleCtrls, Winapi.ActiveX; // *********************************************************************// // 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 RTXCNotetipsActiveXContainerLibMajorVersion = 1; RTXCNotetipsActiveXContainerLibMinorVersion = 0; LIBID_RTXCNotetipsActiveXContainerLib: TGUID = '{62B4856D-8644-4DFE-B8BD-AA4C7EAD8AF0}'; IID_ITRXCNotetipsActiveXContainer: TGUID = '{B071104F-13CD-4E53-97EF-148C177D7F40}'; DIID_ITRXCNotetipsActiveXContainerEvents: TGUID = '{BD2F42B1-6BF1-486E-8A9A-B2F19E7FD438}'; CLASS_TRXCNotetipsActiveXContainer: TGUID = '{C2678E0F-AB4D-4E49-B9E5-629EBB788998}'; type // *********************************************************************// // Forward declaration of types defined in TypeLibrary // *********************************************************************// ITRXCNotetipsActiveXContainer = interface; ITRXCNotetipsActiveXContainerDisp = dispinterface; ITRXCNotetipsActiveXContainerEvents = dispinterface; // *********************************************************************// // Declaration of CoClasses defined in Type Library // (NOTE: Here we map each CoClass to its Default Interface) // *********************************************************************// TRXCNotetipsActiveXContainer = ITRXCNotetipsActiveXContainer; // *********************************************************************// // Interface: ITRXCNotetipsActiveXContainer // Flags: (4416) Dual OleAutomation Dispatchable // GUID: {B071104F-13CD-4E53-97EF-148C177D7F40} // *********************************************************************// ITRXCNotetipsActiveXContainer = interface(IDispatch) ['{B071104F-13CD-4E53-97EF-148C177D7F40}'] end; // *********************************************************************// // DispIntf: ITRXCNotetipsActiveXContainerDisp // Flags: (4416) Dual OleAutomation Dispatchable // GUID: {B071104F-13CD-4E53-97EF-148C177D7F40} // *********************************************************************// ITRXCNotetipsActiveXContainerDisp = dispinterface ['{B071104F-13CD-4E53-97EF-148C177D7F40}'] end; // *********************************************************************// // DispIntf: ITRXCNotetipsActiveXContainerEvents // Flags: (0) // GUID: {BD2F42B1-6BF1-486E-8A9A-B2F19E7FD438} // *********************************************************************// ITRXCNotetipsActiveXContainerEvents = dispinterface ['{BD2F42B1-6BF1-486E-8A9A-B2F19E7FD438}'] end; implementation uses System.Win.ComObj; end.
/////////////////////////////////////////////////////////////////////////// // Project: CW // Program: helpu.pas // Language: Object Pascal - Delphi ver 3.0 // Support: David Fahey // Date: 01Oct97 // Purpose: This code displays a simple (non-standard) help window. // History: 01Oct97 Initial coding DAF // Notes: None /////////////////////////////////////////////////////////////////////////// unit helpu; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls; type THelp = class(TForm) HelpText: TRichEdit; private { Private declarations } public { Public declarations } end; var Help: THelp; implementation {$R *.DFM} end.
// ************************************************************************ // // The types declared in this file were generated from data read from the // WSDL File described below: // WSDL : http://localhost:8888/wsdl/IDRX_AFC_WS // Version : 1.0 // (5/6/2011 11:23:32 PM - 1.33.2.5) // ************************************************************************ // unit DRX_AFC_WS; interface uses InvokeRegistry, SOAPHTTPClient, Types, XSBuiltIns; type // ************************************************************************ // // The following types, referred to in the WSDL document are not being represented // in this file. They are either aliases[@] of other types represented or were referred // to but never[!] declared in the document. The types from the latter category // typically map to predefined/known XML or Borland types; however, they could also // indicate incorrect WSDL documents that failed to declare or import a schema type. // ************************************************************************ // // !:boolean - "http://www.w3.org/2001/XMLSchema" // !:long - "http://www.w3.org/2001/XMLSchema" // !:double - "http://www.w3.org/2001/XMLSchema" // ************************************************************************ // // Namespace : urn:DRX_AFC_WS-IDRX_AFC_WS // soapAction: urn:DRX_AFC_WS-IDRX_AFC_WS#%operationName% // transport : http://schemas.xmlsoap.org/soap/http // style : rpc // binding : IDRX_AFC_WSbinding // service : IDRX_AFC_WSservice // port : IDRX_AFC_WSPort // URL : http://localhost:8888/soap/IDRX_AFC_WS // ************************************************************************ // IDRX_AFC_WS = interface(IInvokable) ['{33A3143C-2820-24A6-C116-9F6BBB2CE244}'] procedure Set_STALO_Output(const state: Boolean); stdcall; function Get_STALO_Output: Boolean; stdcall; function Get_Frequency: Int64; stdcall; procedure Set_Frequency(const value: Int64); stdcall; function Get_Power: Double; stdcall; procedure Set_Power(const value: Double); stdcall; function Get_Temperature: Double; stdcall; procedure Set_AFCChangesInhibited(const value: Boolean); stdcall; function Get_Settling: Boolean; stdcall; function Get_NCOFrequency: Int64; stdcall; procedure Set_NCOFrequency(const value: Int64); stdcall; end; function GetIDRX_AFC_WS(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): IDRX_AFC_WS; implementation function GetIDRX_AFC_WS(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): IDRX_AFC_WS; const defWSDL = 'http://localhost:8888/wsdl/IDRX_AFC_WS'; defURL = 'http://localhost:8888/soap/IDRX_AFC_WS'; defSvc = 'IDRX_AFC_WSservice'; defPrt = 'IDRX_AFC_WSPort'; var RIO: THTTPRIO; begin Result := nil; if (Addr = '') then begin if UseWSDL then Addr := defWSDL else Addr := defURL; end; if HTTPRIO = nil then RIO := THTTPRIO.Create(nil) else RIO := HTTPRIO; try Result := (RIO as IDRX_AFC_WS); if UseWSDL then begin RIO.WSDLLocation := Addr; RIO.Service := defSvc; RIO.Port := defPrt; end else RIO.URL := Addr; finally if (Result = nil) and (HTTPRIO = nil) then RIO.Free; end; end; initialization InvRegistry.RegisterInterface(TypeInfo(IDRX_AFC_WS), 'urn:DRX_AFC_WS-IDRX_AFC_WS', ''); InvRegistry.RegisterDefaultSOAPAction(TypeInfo(IDRX_AFC_WS), 'urn:DRX_AFC_WS-IDRX_AFC_WS#%operationName%'); end.
unit UAMC_UserValidationComment; { ClickForms Application } { Bradford Technologies, Inc. } { All Rights Reserved } { Source Code Copyrighted © 1998-2012 by Bradford Technologies, Inc. } interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Buttons, Mask, UForms, RzButton, RzRadChk; type TAMCUserValidationCmnt = class(TAdvancedForm) Panel1: TPanel; lblCharsRemaining: TLabel; meCharBal: TMaskEdit; lblMandatory: TLabel; bbtnOK: TBitBtn; bbtnCancel: TBitBtn; Panel2: TPanel; lblCommentDesc: TLabel; mmDescr: TMemo; lblAppraiserComment: TLabel; rbRespYes: TRzRadioButton; rbRespNo: TRzRadioButton; mmComment: TMemo; procedure bbtnOKClick(Sender: TObject); procedure mmCommentChange(Sender: TObject); procedure FormShow(Sender: TObject); procedure OKBtnChk; procedure SetRspCategory; procedure rbRespYesClick(Sender: TObject); procedure rbRespNoClick(Sender: TObject); private { Private declarations } procedure AdjustDPISettings; public { Public declarations } ServiceName, Question, Response, RspReqYN, RspCmntReqd: String; end; var AMCUserValidationCmnt: TAMCUserValidationCmnt; RspCategory: Integer; implementation {$R *.dfm} uses UStatus; procedure TAMCUserValidationCmnt.bbtnOKClick(Sender: TObject); begin modalResult := mrOK; end; procedure TAMCUserValidationCmnt.mmCommentChange(Sender: TObject); begin meCharBal.Text := IntToStr(mmComment.MaxLength - Length(mmComment.Text)); OKBtnChk; end; procedure TAMCUserValidationCmnt.FormShow(Sender: TObject); function BuildRspCategory(ReqYN, CmntReqd: String): Integer; begin if ReqYN = 'Y' then Result := 0 else Result := 5; if CmntReqd = 'Y' then Result := Result + 1 else if CmntReqd = 'N' then Result := Result + 2 else if CmntReqd = 'Always' then Result := Result + 3 else if CmntReqd = 'Never' then Result := Result + 4 else Result := Result + 5; end; begin Caption := ServiceName + ' Question or Message Response'; mmDescr.Lines.Text := Question; meCharBal.Text := IntToStr(mmComment.MaxLength); rbRespYes.Checked := False; rbRespYes.Font.Color := clRed; rbRespNo.Checked := False; rbRespNo.Font.Color := clRed; if RspReqYN = 'N' then begin rbRespYes.Visible := False; rbRespNo.Visible := False; end else if Length(Response) >= 2 then if Copy(Response, 1, 2) = 'Y;' then begin Response := Copy(Response, 3, Length(Response)); rbRespYes.Checked := True; end else if Copy(Response, 1, 2) = 'N;' then begin Response := Copy(Response, 3, Length(Response)); rbRespNo.Checked := True; end; if Length(Response) > mmComment.MaxLength then mmComment.Text := Copy(Response, 1, mmComment.MaxLength) else mmComment.Text := Response; RspCategory := BuildRspCategory(RspReqYN, RspCmntReqd); SetRspCategory; AdjustDPISettings; OKBtnChk; Refresh; mmComment.SetFocus; end; procedure TAMCUserValidationCmnt.AdjustDPISettings; begin Panel1.Align := alBottom; Panel1.Width := self.Width; bbtnCancel.Left := Panel1.Width - bbtnCancel.width - 50; bbtnOK.Left := bbtnCancel.Left - bbtnOK.Width - 60; end; procedure TAMCUserValidationCmnt.OKBtnChk; begin case RspCategory of 1: begin bbtnOK.Enabled := (rbRespYes.Checked or rbRespNo.Checked); if rbRespYes.Checked and (Length(mmComment.Text) = 0) then bbtnOK.Enabled := False; end; 2: begin bbtnOK.Enabled := (rbRespYes.Checked or rbRespNo.Checked); if rbRespNo.Checked and (Length(mmComment.Text) = 0) then bbtnOK.Enabled := False; end; 3: bbtnOK.Enabled := (Length(mmComment.Text) > 0) and (rbRespYes.Checked or rbRespNo.Checked); 4,5: bbtnOK.Enabled := (rbRespYes.Checked or rbRespNo.Checked); 8: bbtnOK.Enabled := (Length(mmComment.Text) > 0); else bbtnOK.Enabled := True; end; end; procedure TAMCUserValidationCmnt.SetRspCategory; begin mmComment.Visible := True; case RspCategory of 1: if rbRespYes.Checked then lblAppraiserComment.Font.Color := clRed else lblAppraiserComment.Font.Color := clWindowText; 2: if rbRespNo.Checked then lblAppraiserComment.Font.Color := clRed else lblAppraiserComment.Font.Color := clWindowText; 3,6,8: lblAppraiserComment.Font.Color := clRed; else lblAppraiserComment.Font.Color := clWindowText; end; end; procedure TAMCUserValidationCmnt.rbRespYesClick(Sender: TObject); begin SetRspCategory; OKBtnChk; end; procedure TAMCUserValidationCmnt.rbRespNoClick(Sender: TObject); begin SetRspCategory; OKBtnChk; end; end.
{ Copyright (c) 2014 Daniele Teti, Daniele Spinetti, bit Time Software (daniele.teti@gmail.com). All rights reserved. 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 CommonsU; {$SCOPEDENUMS ON} interface uses Cromis.Multitouch.Custom, Androidapi.JNI.JavaTypes; const MACCAR1 = '00:13:EF:D6:67:0D'; // daniele teti MACCAR2 = '00:24:94:D0:24:62'; // daniele spinetti type TControlState = (csForwardStop = 0, csForward = 1, csBackStop = 2, csBack = 3, csLeftStop = 4, csLeft = 5, csRightStop = 6, csRight = 7); TControlsStates = set of TControlState; TTouchPoints = array of TTouchPoint; function DoConnect(MACAddress: String; out istream: JInputstream; out ostream: JOutputStream): Boolean; implementation uses Androidapi.Helpers, Androidapi.JNI.BluetoothAdapter, Android.JNI.Toast, System.SysUtils; function DoConnect(MACAddress: String; out istream: JInputstream; out ostream: JOutputStream): Boolean; var uid: JUUID; targetMAC: string; Adapter: JBluetoothAdapter; remoteDevice: JBluetoothDevice; Sock: JBluetoothSocket; begin uid := TJUUID.JavaClass.fromString (stringtojstring('00001101-0000-1000-8000-00805F9B34FB')); targetMAC := MACAddress; Adapter := TJBluetoothAdapter.JavaClass.getDefaultAdapter; remoteDevice := Adapter.getRemoteDevice(stringtojstring(targetMAC)); Toast('Connecting to ' + targetMAC); Sock := remoteDevice.createRfcommSocketToServiceRecord(uid); try Sock.connect; except Toast('Could not create service record!'); Exit(False); end; if not Sock.isConnected then begin Toast('Failed to connect to ' + targetMAC + '! Try again...'); Exit(False); end; Toast('Connected!'); ostream := Sock.getOutputStream; // record io streams istream := Sock.getInputStream; // Application.ProcessMessages; ostream.write(ord(255)); // ostream.write(ord(255)); // get device id (nur Chitanda) Sleep(200); Result := True; end; end.
unit RussianPoker; interface uses PokerCards; type costArray = array[c2..cAce] of byte; russianCombo = array[wAK..wAKplus] of byte; { возвращает кобинацию Русского покера для набора карт (до 6 шт.) } function russianCombination(c: cards) : russianCombo; { возвращает саму старшую комбинаци Русского покера } function combRus2Simple(cmb: russianCombo) : Byte; { возваращает количетсво денег за данный намор комбинаций Русского покера } function russianMoney(cmb: russianCombo; changeN: Byte) : Integer; { переводит массив карт в массив повторений их достоинств } function Cards2CostArray(c: cards) : costArray; { проверяет наличие Туза, Короля } procedure hasAK(ca: costArray; var combos: russianCombo); { проверяет наличие простых комбинаций } procedure hasSimple(ca: costArray; var combos: russianCombo); { проверяет наличие стритов } procedure hasStreet(ca: costArray; var combos: russianCombo); { проверяет наличие флеша } procedure hasFlash(c: cards; var combos: russianCombo); { уточняет, что стрит именно одной масти } procedure hasStreetFlash(c: cards; var combos: russianCombo); { возвращает комбинацию обычного покера (сделана по мотивам алгоритма Р.П.) } function simpleCombination(c: cards; var costs: costArray; useCosts: Boolean = False) : Byte; { возвращает комбинацию обычного покера для 6 карт } function simple6Combination(c: cards; var costs: costArray; useCosts: Boolean = False) : Byte; function hasSimple_smp(ca: costArray; var combos: russianCombo) : Boolean; function hasStreet_smp(ca: costArray; var combos: russianCombo) : Boolean; function hasFlash_smp(c: cards; var combos: russianCombo) : Boolean; function hasAK_smp(ca: costArray) : Boolean; function MajorComb(cards1, cards2: cards; combo: Byte) : Shortint; function wConst2Str(w: Byte): string; implementation uses Math; {==================================================== RUSSIAN COMBINATION } function russianCombination(c: cards) : russianCombo; var cmb: russianCombo; costs: costArray; begin FillChar(cmb, SizeOf(cmb), 0); costs := Cards2CostArray(c); hasAK(costs, cmb); hasSimple(costs, cmb); hasFlash(c, cmb); hasStreet(costs, cmb); { доп. проверка на то, что все карты стрита одной масти } if (cmb[wStreet]>0) and (cmb[wFlash]>0) then hasStreetFlash(c, cmb); //result := cmb; exit; //debug version FillChar(result, SizeOf(result), 0); { 2 топовые комбинации } if cmb[wRoyalFlash]=1 then begin { Royal Flash } result[wRoyalFlash] := 1; { Royal Flash + Street Flash } if cmb[wStreetFlash]>0 then result[wStreetFlash] := 1; if cmb[wFlash]>0 then result[wFlash] := 1; if cmb[wStreet]>0 then result[wStreet] := 1; Exit; end; {все одноцветные стриты} if cmb[wStreetFlash]>0 then begin { Street Flash } result[wStreetFlash] := cmb[wStreetFlash]; { Street Flash + Street Flash } //if (cmb[wStreet]=2) and (cmb[wFlash]=2) then Inc(result[wStreetFlash]); { Street Flash + Street } if cmb[wStreet]>0 then begin result[wStreet] := 1; Exit; end; { Street Flash + Flash } if cmb[wFlash]>0 then begin result[wFlash] := 1; Exit; end; { Street Flash + AK } if cmb[wAK]=1 then result[wAKplus] := 1; Exit; end; {==================================== Обработка уличных комбинаций ===} if (cmb[wStreet]>0) or (cmb[wFlash]>0) then begin { Street & Flash } if (cmb[wStreet]>0) and (cmb[wFlash]>0) then begin result[wStreet] := 1; result[wFlash] := 1; Exit; end; { Street + TK } if (cmb[wStreet]=1) and (cmb[wAK]=1) {& исключить случай разномастного 10ВДКТ} and (costs[c2]>0) and (costs[c3]>0) then begin result[wStreet] := 1; result[wAKplus] := 1; Exit; end; { Street & Street + Street} if (cmb[wStreet]>0) then begin result[wStreet] := cmb[wStreet]; Exit; end; { Flash + AK } if (cmb[wFlash]=1) and (cmb[wAK]=1) then begin result[wFlash] := 1; result[wAKplus] := 1; Exit; end; if (cmb[wFlash]=1) and (cmb[wPair]=1) then begin result[wFlash]:=1; result[wPair]:=1; Exit; end; { Flash & Flash + Flash } if cmb[wFlash]>0 then begin result[wFlash] := cmb[wFlash]; Exit; end; {==================================== Обработка прямых комбинаций ===} end else begin { Care + Full House } if (cmb[wCare]=1) and (cmb[wPair]=1) then begin result[wCare] := 1; result[wFullHouse] := 1; Exit; end; { Care + AK } if (cmb[wCare]=1) and (cmb[wAK]=1) then begin result[wCare] := 1; result[wAKplus] := 1; Exit; end; { Care } if (cmb[wCare]=1) then begin result[wCare] := 1; Exit; end; { Full House + Full House } if (cmb[wTriple]=2) then begin result[wFullHouse] := 2; Exit; end; { Full House + TK } if (cmb[wTriple]=1) and (cmb[wPair]=1) and (cmb[wAK]=1) // & исключение случая ТТТКК: and ( (costs[cAce]=1) or (costs[cKing]=1) ) then begin result[wFullHouse] := 1; result[wAKplus] := 1; Exit; end; { Full House } if (cmb[wTriple]=1) and (cmb[wPair]=1) then begin result[wFullHouse] := 1; Exit; end; { Triple + AK } if (cmb[wTriple]=1) and (cmb[wAK]=1) then begin result[wTriple] := 1; result[wAKplus] := 1; Exit; end; { Triple } if (cmb[wTriple]=1) then begin result[wTriple] := 1; Exit; end; { 2Pair + 2Pair } if (cmb[wPair]=3) then begin result[w2Pair] := 2; Exit; end; { 2Pair + AK } // & исключение случая ТТКК: if (cmb[wPair]=2) and (cmb[wAK]=1) and ( (costs[cAce]=1) or (costs[cKing]=1) ) then begin result[w2Pair] := 1; result[wAKplus] := 1; Exit; end; { 2Pair } if (cmb[wPair]=2) then begin result[w2Pair] := 1; Exit; end; { Pair + AK } if (cmb[wPair]=1) and (cmb[wAK]=1) then begin result[wPair] := 1; result[wAKplus] := 1; Exit; end; result := cmb // обработка Пары, Туз-Король и Нет игры end; end; function russianMoney(cmb: russianCombo; changeN: Byte) : Integer; var i: Byte; begin result := 0; for i:=wAK to wAKplus do Inc(result,cmb[i]*winCoefRUS[i, changeN]); if result=0 then result := winCoefRUS[wNoGame, changeN]; end; {==================================================== SIMPLE COMBINATION } function simpleCombination(c: cards; var costs: costArray; useCosts: Boolean = False) : Byte; var cmb: russianCombo; flash, street: Boolean; begin result := wNoGame; FillChar(cmb, SizeOf(cmb), 0); c[6] := NOCARD; if not useCosts then costs := Cards2CostArray(c); if hasSimple_smp(costs,cmb) then begin if cmb[wCare]=1 then begin result:=wCare; Exit; end; if (cmb[wTriple]=1) and (cmb[wPair]=1) then begin result:=wFullHouse; Exit; end; if cmb[wTriple]=1 then begin result:=wTriple; Exit; end; if cmb[wPair]=2 then begin result:=w2Pair; Exit; end; if cmb[wPair]=1 then begin result:=wPair; Exit; end; end; flash := hasFlash_smp(c, cmb); street := hasStreet_smp(costs, cmb); if flash or street then begin if flash and street then begin result := wStreetFlash; if cmb[wRoyalFlash]=1 then result:=wRoyalFlash; end else begin if flash then result:=wFlash; if street then result:=wStreet; end; Exit; end; if hasAK_smp(costs) then result := wAK; end; function simple6Combination(c: cards; var costs: costArray; useCosts: Boolean = False) : Byte; var cmb: russianCombo; begin result := wNoGame; FillChar(cmb, SizeOf(cmb), 0); if not useCosts then costs := Cards2CostArray(c); hasAK(costs, cmb); hasSimple(costs, cmb); hasFlash(c, cmb); hasStreet(costs, cmb); { доп. проверка на то, что все карты стрита одной масти } if (cmb[wStreet]>0) and (cmb[wFlash]>0) then begin hasStreetFlash(c, cmb); if cmb[wRoyalFlash]>0 then begin result:=wRoyalFlash; Exit; end; if cmb[wStreetFlash]>0 then begin result:=wStreetFlash; Exit; end; end; {==================================== Обработка уличных комбинаций ===} if (cmb[wStreet]>0) or (cmb[wFlash]>0) then begin if cmb[wFlash]>0 then begin result:=wFlash; Exit; end; if cmb[wStreet]>0 then begin result:=wStreet; Exit; end; {==================================== Обработка прямых комбинаций ===} end else begin if cmb[wCare]>0 then begin result:=wCare; Exit; end; if (cmb[wTriple]=2) or ((cmb[wTriple]>0) and (cmb[wPair]>0)) then begin result:=wFullHouse; Exit; end; if cmb[wTriple]>0 then begin result:=wTriple; Exit; end; if cmb[wPair]>=2 then begin result:=w2Pair; Exit; end; if cmb[wPair]=1 then begin result:=wPair; Exit; end; if cmb[wAK]>0 then begin result:=wAK; Exit; end; end; end; {==================================================== CARDS TO COSTARRAY } function Cards2CostArray(c: cards) : costArray; var i: Byte; begin FillChar(result, SizeOf(result), 0); for i:=1 to 6 do if c[i] in ISCARD then Inc(result[GetCost(c[i])]); end; {==================================================== HAS ACE-KING } procedure hasAK(ca: costArray; var combos: russianCombo); begin if ((ca[cAce]>0) and (ca[cKing]>0)) then combos[wAK]:=1 else combos[wAK]:=0; end; {==================================================== HAS SIMPLE } procedure hasSimple(ca: costArray; var combos: russianCombo); var i: Byte; begin for i:=c2 to cAce do case ca[i] of 2: Inc(combos[wPair]); 3: Inc(combos[wTriple]); 4: Inc(combos[wCare]); end; end; {==================================================== HAS STREET } { устанавливает wStreet и/или wRoyalFlash} procedure hasStreet(ca: costArray; var combos: russianCombo); var i, sameCount, sameStart, sameSum: Byte; begin sameCount := 0; sameStart := 0; sameSum := 0; if ca[cAce]>0 then begin Inc(sameCount); sameStart := cAce; sameSum := sameSum + ca[cAce]; end; for i:=c2 to cAce do if ca[i]>0 then begin if sameCount=0 then sameStart:=i; Inc(sameCount); sameSum := sameSum + ca[i]; end else begin if sameCount >= 5 then break; sameCount:=0; sameStart:=0; sameSum :=0; end; if sameCount >= 5 then begin combos[wStreet] := sameSum-4; // 1 или 2 стрита if (sameStart + sameCount - 1 = cAce) { если кончается на тузе } and (combos[wFlash]>0) then { и есть флэш } combos[wRoyalFlash] := 1; { - значит подозрение на Royal } end; end; {==================================================== HAS FLASH } { устанавливает wFlash } procedure hasFlash(c: cards; var combos: russianCombo); var i,m: Byte; mArr: array [mCrosses..mPeaks] of Byte; maxCount: Byte; begin FillChar(mArr, SizeOf(mArr), 0); maxCount := 0; for i:=1 to Length(c) do if c[i] in ISCARD then begin m := GetMast(c[i]); Inc(mArr[m]); if mArr[m]>maxCount then maxCount := mArr[m]; end; if maxCount>=5 then combos[wFlash] := maxCount-4; //1 или 2 флеша end; {==================================================== HAS STREET FLASH } { устанавливает wRoyalFlash и/или wStreetFlash } procedure hasStreetFlash(c: cards; var combos: russianCombo); var i,j: Byte; flash: cards; cmb: russianCombo; costs: costArray; begin j := 1; ClearCards(flash); for i:=1 to Length(c) do if ThisMastCount(GetMast(c[i]),c)>=5 then begin flash[j] := c[i]; Inc(j); end; if j>5 then begin FillChar(cmb, SizeOf(cmb), 0); cmb[wFlash] := j-5; costs := Cards2CostArray(flash); hasStreet(costs,cmb); combos[wRoyalFlash] := cmb[wRoyalFlash]; if cmb[wStreet] > 0 then begin combos[wStreetFlash] := cmb[wStreet]-cmb[wRoyalFlash]; Dec(combos[wStreet], combos[wStreetFlash]+combos[wRoyalFlash]); Dec(combos[wFlash], combos[wStreetFlash]+combos[wRoyalFlash]); //combos[wStreet] := 0; //combos[wFlash] := cmb[wStreet]; end; end; end; { Возвращает максимальную комбинацию или нет игры } function combRus2Simple(cmb: russianCombo) : Byte; var i: Byte; begin result := wNoGame; for i:=wRoyalFlash downto wAK do if cmb[i]>0 then begin result:=i; Exit; end; end; function wConst2Str(w: Byte): string; begin case w of wNoGame: result := 'NOGAME'; wAK: result := 'AK'; wPair: result := 'PAIR'; w2Pair: result := '2PAIR'; wTriple: result := 'TRIPLE'; wStreet: result := 'STREET'; wFlash: result := 'FLASH'; wFullHouse: result := 'FULLHOUSE'; wCare: result := 'CARE'; wStreetFlash: result := 'STRFLASH'; wRoyalFlash: result := 'ROYFLASH'; end; end; {==================================================== HAS SIMPLE for simple} function hasSimple_smp(ca: costArray; var combos: russianCombo) : Boolean; var i: Byte; begin result := False; for i:=c2 to cAce do case ca[i] of 2: begin Inc(combos[wPair]); result:=True; end; 3: begin Inc(combos[wTriple]); result:=True; end; 4: begin Inc(combos[wCare]); result:=True; end; end; end; {==================================================== HAS STREET for simple } function hasStreet_smp(ca: costArray; var combos: russianCombo) : Boolean; var i, count: Byte; begin result := False; count := 0; if (ca[cAce]>0) and (ca[c2]>0) then Inc(count); for i:=c2 to cAce do if ca[i]>0 then begin if count<5 then Inc(count) else Break; end else begin if count>0 then Break; end; if count = 5 then begin result := True; combos[wStreet] := 1; if ca[c10]+ca[cAce]=2 then { если есть десятка и есть туз } combos[wRoyalFlash] := 1;{ - значит подозрение на Royal } end; end; {==================================================== HAS FLASH for simple } function hasFlash_smp(c: cards; var combos: russianCombo) : Boolean; var i,m: Byte; begin m := GetMast(c[1]); result:=True; for i:=2 to 5 do if GetMast(c[i])<>m then begin result:=False; Break; end; if result then combos[wFlash] := 1; end; {==================================================== HAS ACE-KING for simple } function hasAK_smp(ca: costArray) : Boolean; begin if ((ca[cAce]>0) and (ca[cKing]>0)) then result:=True else result:=False; end; function MajorComb(cards1, cards2: cards; combo: Byte) : Shortint; var costs1, costs2: costArray; i: Byte; signs: array [1..4] of Shortint; begin MajorComb:=0; costs1:=Cards2CostArray(cards1); costs2:=Cards2CostArray(cards2); if combo in wSTREETGROUP then begin for i:=cKing downto c2 do if (costs1[i]>0) and (costs2[i]>0) then begin MajorComb := 0; if costs1[i+1]>0 then MajorComb := 1; if costs2[i+1]>0 then MajorComb := -1; Break; end end else if combo=wFlash then begin for i:=cAce downto c2 do if costs1[i]<>costs2[i] then begin MajorComb := Sign(costs1[i]-costs2[i]); Break; end end else begin FillChar(signs, SizeOf(signs), 0); for i:=cAce downto c2 do begin if costs2[i]<>costs1[i] then begin if (costs1[i]>0) and (signs[costs1[i]]=0) then signs[costs1[i]]:=1; if (costs2[i]>0) and (signs[costs2[i]]=0) then signs[costs2[i]]:=-1; end; end; for i:=4 downto 1 do if signs[i]<>0 then begin MajorComb:=signs[i]; Break; end; end; end; (* {==================================== Обработка уличных комбинаций ===} if (cmb[wStreet]>0) or (cmb[wFlash]>0) then begin { доп. проверка на то, что все карты стрита одной масти } hasStreetFlash(c, cmb); if cmb[wRoyalFlash]=1 then begin { Royal Flash + Street Flash } if (cmb[wFlash]=2) and (cmb[wStreet]=2) then begin result[wRoyalFlash] := 1; result[wStreetFlash] := 1; Exit; end; { Royal Flash } result[wRoyalFlash] := 1; Exit; end; {все одноцветные стриты} if cmb[wStreetFlash]=1 then begin { Street Flash + Street Flash } if (cmb[wStreet]=2) and (cmb[wFlash]=2) then begin result[wStreetFlash] := 2; Exit; end; { Street Flash + Street } if (cmb[wStreet]=2) and (cmb[wFlash]=1) then begin result[wStreetFlash] := 1; result[wStreet] := 1; Exit; end; { Street Flash + Flash } if (cmb[wStreet]=1) and (cmb[wFlash]=2) then begin result[wStreetFlash] := 1; result[wFlash] := 1; Exit; end; { Street Flash + AK } if (cmb[wStreet]=1) and (cmb[wFlash]=1) and (cmb[wAK]=1) then begin result[wStreetFlash] := 1; result[wAK] := 1; Exit; end; { Street Flash } result[wStreetFlash] := 1; Exit; end; { Street + TK } if (cmb[wStreet]=1) and (cmb[wAK]=1) {& исключить случай разномастного 10ВДКТ} and (costs[c2]>0) and (costs[c3]>0) then begin result[wStreet] := 1; result[wAK] := 1; Exit; end; { Street & Street + Street} if (cmb[wStreet]>0) then begin result[wStreet] := cmb[wStreet]; Exit; end; { Flash & Flash + Flash } if (cmb[wFlash]>0) then begin result[wFlash] := cmb[wFlash]; Exit; end; {==================================== Обработка прямых комбинаций ===} end else begin { Care + Full House } if (cmb[wCare]=1) and (cmb[wPair]=1) then begin result[wCare] := 1; result[wFullHouse] := 1; Exit; end; { Care + AK } if (cmb[wCare]=1) and (cmb[wAK]=1) then begin result[wCare] := 1; result[wAK] := 1; Exit; end; { Care } if (cmb[wCare]=1) then begin result[wCare] := 1; Exit; end; { Full House + Full House } if (cmb[wTriple]=2) then begin result[wFullHouse] := 2; Exit; end; { Full House + TK } if (cmb[wTriple]=1) and (cmb[wPair]=1) and (cmb[wAK]=1) // & исключение случая ТТТКК: and ( (costs[cAce]=1) or (costs[cKing]=1) ) then begin result[wFullHouse] := 1; result[wAK] := 1; Exit; end; { Full House } if (cmb[wTriple]=1) and (cmb[wPair]=1) then begin result[wFullHouse] := 1; Exit; end; { Triple + AK } if (cmb[wTriple]=1) and (cmb[wAK]=1) then begin result[wTriple] := 1; result[wAK] := 1; Exit; end; { Triple } if (cmb[wTriple]=1) then begin result[wTriple] := 1; Exit; end; { 2Pair + AK } if (cmb[wPair]=2) and (cmb[wAK]=1) then begin result[w2Pair] := 1; result[wAK] := 1; Exit; end; { 2Pair } if (cmb[wPair]=2) then begin result[w2Pair] := 1; Exit; end; { Pair + AK } if (cmb[wPair]=1) and (cmb[wAK]=1) then begin result[wPair] := 1; result[wAK] := 1; Exit; end; result := cmb // обработка Пары, Туз-Король и Нет игры end; {==================================================== HAS STREET FLASH } procedure hasStreetFlash(c: cards; var combos: russianCombo); var i,i0, mast: Byte; flag1, flag2: Boolean; begin {отсортировать карты по убыванию достоинства} c := CostSort(c); {проверка с какой карты начинается стрит} if GetCost(c[1])-GetCost(c[2])=1 then begin {доп. проверка на равность масти первых двух карт} if GetMast(c[1])=GetMast(c[2]) then i0:=1 else i0:=2; end else i0:=2; flag1 := True; // надежда mast := GetMast(c[i0]); for i:=i0+1 to i0+4 do if GetMast(c[i])<>mast then begin flag1 := False; Break; end; { если не наудено при такой сортировке, попробуем отсортировать в виде К5432Т } if not flag1 then begin c := SortByCost(c); if GetCost(c[1])-GetCost(c[2])=1 then begin if GetMast(c[1])=GetMast(c[2]) then i0:=1 else i0:=2; end else i0:=2; flag2 := True; mast := GetMast(c[i0]); for i:=i0+1 to i0+4 do if GetMast(c[i])<>mast then begin flag2 := False; Break; end; end; {найдено 5 карт одной масти} if flag1 then begin combos[wStreetFlash] := 1; Exit; end else if flag2 then begin combos[wStreetFlash] := 1; end; if combos[wRoyalFlash]=1 then combos[wRoyalFlash] := 0; end; *) end.
unit cbclasses; interface uses W3System, w3components, w3label, w3image, w3panel, w3styles, w3Graphics, w3application, w3memo, qtxUtils, qtxlabel, qtxScrollController, qtxEffects; type TCBGlyphButton = Class(TW3CustomControl) private FGlyph: TW3CustomControl; FCaption: TQTXLabel; protected procedure Resize;override; public Property Glyph:TW3CustomControl read FGlyph; Property Text:TQTXLabel read FCaption; Procedure InitializeObject;Override; Procedure FinalizeObject;Override; End; TCBDialogInfo = Class(TObject) private FBlocker: TW3BlockBox; FBox: TW3Panel; FCancel: TCBGlyphButton; FPost: TCBGlyphButton; FEditor: TW3Memo; FTitle: TQTXLabel; public property Editor:TW3Memo read FEditor; Property BackgroundBlocker:TW3BlockBox read FBlocker; Property Panel:TW3Panel read FBox; property CancelButton:TCBGlyphButton read FCancel; Property PostButton:TCBGlyphButton read FPost; Constructor Create;virtual; Destructor Destroy;Override; End; TCBNotifierPlack = Class(TObject) private FBox: TW3Panel; public Property Box:TW3Panel read FBox; procedure Show; Constructor Create(AOwner:TW3CustomControl);virtual; Destructor Destroy;Override; End; //TCBProfileHeader = Class(TW3CustomControl) //End; TCBPanel = Class(TW3CustomControl) protected class function supportAdjustment: Boolean; override; class function DisplayMode : String; override; End; TCBNewsItem = Class(TW3CustomControl) private FImage: TW3Image; FTitle: TQTXLabel; FTimeInfo: TQTXLabel; FText: TQTXLabel; FUrl: String; Procedure HandleTextChange(sender:TObject); protected Procedure Resize;Override; public procedure InitializeObject;Override; Procedure FinalizeObject;Override; public class var Index:Integer; Property URL:String read FUrl write FUrl; Property Image:TW3Image read FImage; Property Title:TQTXLabel read FTitle; Property TimeInfo:TQTXLabel read FTimeInfo; Property Text:TQTXLabel read FText; Procedure StyleTagObject;override; End; TCaseBookList = Class(TQTXScrollWindow) protected procedure InitializeObject;Override; End; implementation //############################################################################ // TCBPanel //############################################################################ class function TCBPanel.supportAdjustment:Boolean; Begin result:=true; end; class function TCBPanel.DisplayMode:String; Begin result:='inline';//inherited displaymode; end; //############################################################################ // TCaseBookList //############################################################################ Procedure TCaseBookList.InitializeObject; Begin inherited; //TQTXTools.ExecuteOnElementReady(Handle, procedure () Handle.readyExecute( procedure () Begin resize; end); end; //############################################################################# // TCBGlyphButton //############################################################################# Procedure TCBGlyphButton.InitializeObject; Begin inherited; FGlyph:=TW3CustomControl.Create(self); FGlyph.setSize(16,16); FGlyph.handle.style['background']:='transparent'; FGlyph.Handle.style['text-align']:='center'; Handle.style['border-style']:='solid'; Handle.style['border-width']:='1px'; Handle.style['border-color']:='#CECECE'; FGlyph.handle.style['color']:='#AFAFAF'; FCaption:=TQTXLabel.Create(self); FCaption.handle.style['background']:='transparent'; FCaption.Autosize:=false; FCaption.Height:=18; FCaption.Width:=40; FCaption.Caption:=''; //TQTXTools.ExecuteOnElementReady(Handle, procedure () Handle.readyExecute( procedure () Begin LayoutChildren; end); end; Procedure TCBGlyphButton.FinalizeObject; Begin FGlyph.free; FCaption.free; inherited; end; procedure TCBGlyphButton.Resize; var dx: Integer; dy: Integer; mText: String; xx: Integer; Begin inherited; if FGlyph.handle.ready then begin mText:=trim(FCaption.Caption); if mText.Length>0 then Begin dy:=(clientHeight div 2) - (FGlyph.Height div 2); FGlyph.MoveTo(1,dy); end else Begin dx:=(ClientWidth div 2) - (FGlyph.width div 2); dy:=(clientHeight div 2) - (FGlyph.Height div 2); FGlyph.MoveTo(dx,dy); FCaption.moveto(-FCaption.Width,-FCaption.Height); exit; end; end; if FCaption.handle.ready then begin xx:=FGlyph.left + FGlyph.Width; dy:=(clientheight div 2) - (FCaption.height div 2); dx:=((clientWidth-xx) div 2) - (FCaption.width div 2); inc(dx,xx); FCaption.setBounds(dx,dy,FCaption.Width,FCaption.height); end; end; //############################################################################# // TCBNewsItem //############################################################################# procedure TCBNewsItem.InitializeObject; Begin inherited; FImage:=TW3Image.Create(self); FTitle:=TQTXLabel.Create(self); Handle.style['border-style']:='solid'; Handle.style['border-width']:='1px'; Handle.style['border-color']:='#cccccc'; handle.style['background']:='#FFFFFF'; FTimeInfo:=TQTXLabel.Create(self); FTimeInfo.Font.size:=12; FTimeInfo.font.Color:=clGrey; FTimeInfo.Caption:='Smart Pascal wrote at ' + TimeToStr(now); FText:=TQTXLabel.Create(self); FText.font.size:=14; FText.Autosize:=False; FText.OnChanged:=HandleTextChange; //FText.Font.Color:=RGBToColor($55,$55,$55); (* FText.Handle.style['border-style']:='solid'; FText.Handle.style['border-width']:='1px'; FText.Handle.style['border-color']:='#cccccc'; *) Handle.ReadyExecute( procedure () //TQTXTools.ExecuteOnElementReady(Handle, procedure () Begin Resize; end); end; Procedure TCBNewsItem.FinalizeObject; Begin FImage.free; FTitle.free; FTimeInfo.free; Ftext.free; inherited; end; Procedure TCBNewsItem.StyleTagObject; begin inherited; //Handle.style['border-radius']:='8px'; background.fromColor(clWhite); end; Procedure TCBNewsItem.HandleTextChange(sender:TObject); Begin beginupdate; try FText.height:=FText.MeasureTextFixed(FText.caption).tmHeight; self.height:=FText.top + FText.height + 6; finally EndUpdate; end; end; Procedure TCBNewsItem.Resize; Begin inherited; if handle.ready then //if TQTXTools.getHandleReady(self.handle) then begin FImage.setbounds(4,4,36,36); FTitle.setBounds(44,4,clientwidth-(44 + 4),22); FTimeInfo.setBounds(44,24,clientwidth-(44 + 4),16); FText.left:=4; FText.top:=44+8; FText.width:=clientWidth-8; //FText.height:=FText.MeasureTextFixed(FText.caption).tmHeight; (* This will cause one immediate resize *) //self.height:=FText.top + FText.height + 6; end; end; //############################################################################# // TCBNotifierPlack //############################################################################# Constructor TCBNotifierPlack.Create(AOwner:TW3CustomControl); const CNT_Width = 280; CNT_Height = 100; Begin inherited Create; FBox:=TW3Panel.Create(aOwner); FBox.visible:=False; FBox.setBounds( (AOwner.ClientWidth div 2) - (CNT_WIDTH div 2), //(AOwner.clientHeight - CNT_HEIGHT), AOwner.ClientHeight + CNT_HEIGHT, CNT_WIDTH, CNT_HEIGHT); FBox.OnMouseTouchClick:=Procedure (Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer) Begin FBox.fxFadeOut(0.3, procedure () begin FBox.free; end); end; end; Destructor TCBNotifierPlack.Destroy; Begin FBox.free; inherited; end; procedure TCBNotifierPlack.Show; Begin FBox.fxFadeIn(0.5, procedure () begin FBox.fxMoveTo(FBox.Left, (TW3CustomControl(FBox.Parent).ClientHeight div 2) - FBox.Height div 2, 0.6, procedure () begin TQTXRuntime.DelayedDispatch( procedure () Begin FBox.fxFadeOut(0.3, procedure () begin self.free; end); end, 1000 * 8); end); end); end; //############################################################################# // TCBDialogInfo //############################################################################# Constructor TCBDialogInfo.Create; var dx: Integer; dy: Integer; wd: Integer; Begin inherited Create; FBlocker := TW3BlockBox.Create(Application.Display); FBlocker.SetBounds(0,0,Application.Display.Width,Application.Display.Height); FBlocker.BringToFront; FBox:=TW3Panel.Create(FBlocker); FBox.SetBounds(10,20,300,280); FBox.moveTo((application.display.clientwidth div 2) - FBox.width div 2, (application.display.clientHeight div 2) - FBox.height div 2); FEditor:=TW3Memo.Create(FBox); FEditor.SetBounds(10,40,FBox.ClientWidth-20,(FBox.ClientHeight-20) - 80); FTitle:=TQTXLabel.Create(FBox); FTitle.MoveTo(10,10); FTitle.Caption:='Add new post'; dy:=FBox.ClientHeight-40; wd:=((FBox.ClientWidth - 40) div 2) - 20; Fpost:=TCBGlyphButton.Create(FBox); Fpost.setBounds(10,dy,wd,26); FPost.text.Autosize:=False; FPost.text.height:=16; FPost.Text.Caption:='Post'; FPost.glyph.innerHTML:='<i class="fa fa-bolt fa-2x">'; FPost.LayoutChildren; FPost.Glyph.height:=26; dx:=(FBox.ClientWidth - 10) - wd; FCancel:=TCBGlyphButton.Create(FBox); FCancel.setBounds(dx,dy,wd,26); FCancel.text.Autosize:=False; FCancel.text.height:=16; FCancel.text.caption:='Cancel'; FCancel.glyph.innerHTML:='<i class="fa fa-times fa-2x">'; FCancel.LayoutChildren; FCancel.Glyph.height:=26; FCancel.OnMouseTouchRelease:=Procedure (Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer) Begin FBox.fxZoomOut(0.3, procedure () Begin self.free; end); end; FBox.fxZoomIn(0.3); end; Destructor TCBDialogInfo.Destroy; Begin FPost.free; FTitle.free; FEditor.free; FBox.free; FBlocker.free; inherited; end; end.
// Fit4Delphi Copyright (C) 2008. Sabre Inc. // This program 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 program 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. // // You should have received a copy of the GNU General Public License along with this program; // if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // Ported to Delphi by Michal Wojcik. {$H+} unit Field; interface uses Fixture, TypInfo; type TField = class private FFieldName : string; FFieldType : TTypeKind; function getFieldType : TTypeKind; function getFieldName : string; public function get(theInstance : TObject) : variant; procedure doSet(theInstance : TFixture; const theValue : variant); property FieldName : string read getFieldName; property FieldType : TTypeKind read getFieldType; constructor Create(theClass : TClass; const aFld : string); overload; constructor Create(const theName : string; theType : TTypeKind); overload; end; implementation { TField } constructor TField.Create(const theName : string; theType : TTypeKind); begin FFieldName := theName; FFieldType := theType; end; constructor TField.Create(theClass : TClass; const aFld : string); var thePropInfo : PPropInfo; begin {$IFDEF UNICODE} thePropInfo := GetPropInfo( theClass.classInfo, aFld, [tkUnknown, tkInteger, tkChar, tkEnumeration, tkFloat, tkString, tkSet, tkClass, tkMethod, tkWChar, tkLString, tkWString, tkUString, tkVariant, tkArray, tkRecord, tkInterface, tkInt64, tkDynArray ] ); {$ELSE} thePropInfo := GetPropInfo( theClass.classInfo, aFld, [tkUnknown, tkInteger, tkChar, tkEnumeration, tkFloat, tkString, tkSet, tkClass, tkMethod, tkWChar, tkLString, tkWString, tkVariant, tkArray, tkRecord, tkInterface, tkInt64, tkDynArray ] ); {$ENDIF} self.Create(aFld, thePropInfo.PropType^.Kind); end; procedure TField.doSet(theInstance : TFixture; const theValue : variant); begin SetPropValue(theInstance, FieldName, theValue); end; function TField.get(theInstance : TObject) : variant; begin result := GetPropValue(theInstance, FieldName); end; function TField.getFieldName : string; begin result := FFieldName; end; function TField.getFieldType : TTypeKind; begin result := FFieldType; end; end.
unit Counting; interface uses SysUtils, Naturals, Rationals, sToPolynom, Polynoms; function CountInTRational(const p : Tpolynom; const x : TRationalnumber) : TRationalnumber; function power(const a : TRationalNumber; const b : integer) : TRationalnumber; function RoundToNat(const a : TRationalNumber) : TNaturalNumber; function RoundToInt(const a : TRationalNumber) : integer; implementation function power(const a : TRationalNumber; const b : integer) : TRationalnumber; var i : integer; help : TRationalNumber; begin result := a; for i := 1 to b - 1 do begin rationals.mult(help, result, a); result := help; end; if b = 0 then begin result.Sign := nsPlus; result.Numerator := strtonatural('0001'); result.Denominator := strtonatural('0001'); end; end; function CountInTRational(const p : Tpolynom; const x : TRationalnumber) : TRationalnumber; var i : integer; help1, help2 : TRationalNumber; begin result := polynoms.initzero()^; for i := 0 to length(p) - 1 do begin rationals.mult(help1, p[i]^, power(x, i)); rationals.add(help2, result, help1); result := help2; end; end; function RoundToNat(const a : TRationalNumber) : TNaturalNumber; var b : TrationalNumber; help1, help2 : TNaturalNumber; begin b := a; naturals.divide(result, help1, a.numerator, a.denominator); end; function RoundToInt(const a : TRationalNumber) : integer; begin result := RoundToNat(a)[0]; end; end.
program visiblewindow; {$IFNDEF HASAMIGA} {$FATAL This source is compatible with Amiga, AROS and MorphOS only !} {$ENDIF} { Project : visiblewindow Source : RKRM } {* ** open a window on the visible part of a screen, with the window as large ** as the visible part of the screen. It is assumed that the visible part ** of the screen is OSCAN_TEXT, which how the user has set their preferences. *} {$MODE OBJFPC}{$H+}{$HINTS ON} {$UNITPATH ../../../Base/CHelpers} {$UNITPATH ../../../Base/Trinity} Uses Exec, AGraphics, Intuition, utility, {$IFDEF AMIGA} SystemVarTags, {$ENDIF} CHelpers, Trinity; const {* Minimum window width and height: ** These values should really be calculated dynamically given the size ** of the font and the window borders. Here, to keep the example simple ** they are hard-coded values. *} MIN_WINDOW_WIDTH = (100); MIN_WINDOW_HEIGHT = (50); {* minimum and maximum calculations...Note that each argument is ** evaluated twice (don't use max(a++,foo(c))). *} function max(a: LongInt; b: LongInt): LongInt; inline; begin if ( (a) > (b) ) then max := (a) else max := (b); end; function min(a: LongInt; b: LongInt): LOngInt; inline; begin if ( (a) <= (b) ) then min := (a) else min := (b); end; procedure fullScreen; forward; procedure handle_window_events(win: PWindow); forward; {* ** open all the libraries and run the code. Cleanup when done. *} procedure Main(argc: integer; argv: PPChar); begin //* these calls are only valid if we have Intuition version 37 or greater */ {$IFNDEF HASAMIGA} if SetAndTest(GfxBase, OpenLibrary('graphics.library', 37)) then {$ENDIF} begin {$IFDEF MORPHOS} if SetAndTest(IntuitionBase, OpenLibrary('intuition.library', 37)) then {$ENDIF} begin fullScreen; {$IFDEF MORPHOS} CloseLibrary(PLibrary(IntuitionBase)); {$ENDIF} end; {$IFNDEF HASAMIGA} CloseLibrary(GfxBase); {$ENDIF} end; end; {* ** Open a window on the default public screen, then leave it open until the ** user selects the close gadget. The window is full-sized, positioned in the ** currently visible OSCAN_TEXT area. *} procedure fullScreen; var test_window : PWindow; pub_screen : PScreen; rect : TRectangle; screen_modeID : ULONG; width, height, left, top : LONG; begin left := 0; //* set some reasonable defaults for left, top, width and height. */ top := 0; //* we'll pick up the real values with the call to QueryOverscan(). */ width := 640; height := 200; //* get a lock on the default public screen */ if (nil <> SetAndGet(pub_screen, LockPubScreen(nil))) then begin {* this technique returns the text overscan rectangle of the screen that we ** are opening on. If you really need the actual value set into the display ** clip of the screen, use the VideoControl() command of the graphics library ** to return a copy of the ViewPortExtra structure. See the Graphics ** library chapter and Autodocs for more details. ** ** GetVPModeID() is a graphics call... *} screen_modeID := GetVPModeID(@pub_screen^.ViewPort); if (screen_modeID <> ULONG(INVALID_ID)) then begin if (QueryOverscan(screen_modeID, @rect, OSCAN_TEXT) <> 0) then begin //* make sure window coordinates are positive or zero */ left := max(0, -pub_screen^.LeftEdge); top := max(0, -pub_screen^.TopEdge); //* get width and height from size of display clip */ width := rect.MaxX - rect.MinX + 1; height := rect.MaxY - rect.MinY + 1; //* adjust height for pulled-down screen (only show visible part) */ if (pub_screen^.TopEdge > 0) then height := height - pub_screen^.TopEdge; //* insure that window fits on screen */ height := min(height, pub_screen^.Height); width := min(width, pub_screen^.Width); //* make sure window is at least minimum size */ width := max(width, MIN_WINDOW_WIDTH); height := max(height, MIN_WINDOW_HEIGHT); end; end; //* open the window on the public screen */ test_window := OpenWindowTags(nil, [ TAG_(WA_Left) , left, TAG_(WA_Width) , width, TAG_(WA_Top) , top, TAG_(WA_Height) , height, TAG_(WA_CloseGadget) , TAG_(TRUE), TAG_(WA_IDCMP) , IDCMP_CLOSEWINDOW, TAG_(WA_PubScreen) , TAG_(pub_screen), TAG_END ]); {* unlock the screen. The window now acts as a lock on the screen, ** and we do not need the screen after the window has been closed. *} UnlockPubScreen(nil, pub_screen); {* if we have a valid window open, run the rest of the ** program, then clean up when done. *} if assigned(test_window) then begin handle_window_events(test_window); CloseWindow(test_window); end; end; end; {* ** Wait for the user to select the close gadget. *} procedure handle_window_events(win: PWindow); var msg : PIntuiMessage; done : Boolean = FALSE; begin while not(done) do begin {* we only have one signal bit, so we do not have to check which ** bit(s) broke the Wait() (i.e. the return value of Wait) *} Wait(1 shl win^.UserPort^.mp_SigBit); while ( not(done) and SetAndTest(msg, PIntuiMessage(GetMsg(win^.UserPort)))) do begin //* use a case statement if looking for multiple event types */ if (msg^.IClass = IDCMP_CLOSEWINDOW) then done := TRUE; ReplyMsg(PMessage(msg)); end; end; end; begin Main(ArgC, ArgV); end.
unit IdTestCoder3to4; interface uses IdCoder3to4, IdObjs, IdSys, IdGlobal, IdCoderBinHex4, IdTest; type TTestIdCoder3to4 = class(TIdTest) published procedure TestCoder; end; implementation procedure TTestIdCoder3to4.TestCoder; var aCoder: TIdEncoder3to4; aStream: TIdMemoryStream; s:string; begin aStream := TIdMemoryStream.Create; aCoder := TIdEncoderBinHex4.Create(nil); try WriteStringToStream(AStream, 'abc'); AStream.Position := 0; s := aCoder.Encode(aStream, aStream.Size); Assert(s = 'B@*M', s); finally Sys.FreeAndNil(aStream); Sys.FreeAndNil(aCoder); end; end; initialization TIdTest.RegisterTest(TTestIdCoder3to4); end.
// ************************************************************************ // // The types declared in this file were generated from data read from the // WSDL File described below: // WSDL : http://webservices.bradfordsoftware.com/WSFidelity/FidelityService.asmx?wsdl // Encoding : utf-8 // Version : 1.0 // (3/21/2007 5:19:16 PM - 1.33.2.5) // ************************************************************************ // unit FidelityService; interface uses InvokeRegistry, SOAPHTTPClient, Types, XSBuiltIns; type // ************************************************************************ // // The following types, referred to in the WSDL document are not being represented // in this file. They are either aliases[@] of other types represented or were referred // to but never[!] declared in the document. The types from the latter category // typically map to predefined/known XML or Borland types; however, they could also // indicate incorrect WSDL documents that failed to declare or import a schema type. // ************************************************************************ // // !:int - "http://www.w3.org/2001/XMLSchema" // !:string - "http://www.w3.org/2001/XMLSchema" FISRequestRec = class; { "http://tempuri.org/" } Location = class; { "http://BradfordTechnologies.SiteXData.com/BradfordTechnologies/" } AssessmentInfo = class; { "http://BradfordTechnologies.SiteXData.com/BradfordTechnologies/" } LegalDescriptionInfo = class; { "http://BradfordTechnologies.SiteXData.com/BradfordTechnologies/" } Transfer = class; { "http://BradfordTechnologies.SiteXData.com/BradfordTechnologies/" } PriorSale = class; { "http://BradfordTechnologies.SiteXData.com/BradfordTechnologies/" } ComparableSale = class; { "http://BradfordTechnologies.SiteXData.com/BradfordTechnologies/" } ReportResult = class; { "http://BradfordTechnologies.SiteXData.com/BradfordTechnologies/" } BradfordTechnologiesResult = class; { "http://BradfordTechnologies.SiteXData.com/BradfordTechnologies/" } // ************************************************************************ // // Namespace : http://tempuri.org/ // ************************************************************************ // FISRequestRec = class(TRemotable) private FszAPN: WideString; FszFIPS: WideString; FszAddress: WideString; FszCity: WideString; FszState: WideString; FszZip: WideString; FszRequestType: WideString; published property szAPN: WideString read FszAPN write FszAPN; property szFIPS: WideString read FszFIPS write FszFIPS; property szAddress: WideString read FszAddress write FszAddress; property szCity: WideString read FszCity write FszCity; property szState: WideString read FszState write FszState; property szZip: WideString read FszZip write FszZip; property szRequestType: WideString read FszRequestType write FszRequestType; end; // ************************************************************************ // // Namespace : http://BradfordTechnologies.SiteXData.com/BradfordTechnologies/ // ************************************************************************ // Location = class(TRemotable) private FFIPS: WideString; FAPN: WideString; FUnitType: WideString; FUnitNumber: WideString; FAddress: WideString; FCity: WideString; FState: WideString; FZip: WideString; FZip4: WideString; published property FIPS: WideString read FFIPS write FFIPS; property APN: WideString read FAPN write FAPN; property UnitType: WideString read FUnitType write FUnitType; property UnitNumber: WideString read FUnitNumber write FUnitNumber; property Address: WideString read FAddress write FAddress; property City: WideString read FCity write FCity; property State: WideString read FState write FState; property Zip: WideString read FZip write FZip; property Zip4: WideString read FZip4 write FZip4; end; ArrayOfLocation = array of Location; { "http://BradfordTechnologies.SiteXData.com/BradfordTechnologies/" } // ************************************************************************ // // Namespace : http://BradfordTechnologies.SiteXData.com/BradfordTechnologies/ // ************************************************************************ // AssessmentInfo = class(TRemotable) private FSiteAddress: WideString; FSiteUnitType: WideString; FSiteUnit: WideString; FSiteCity: WideString; FSiteState: WideString; FSiteZip: WideString; FSiteZip4: WideString; FAPN: WideString; FCensusTract: WideString; FUseCodeDescription: WideString; FZoning: WideString; FOwnerName: WideString; FOwnerMailUnitType: WideString; FOwnerMailUnit: WideString; FOwnerMailAddress: WideString; FOwnerMailCity: WideString; FOwnerMailState: WideString; FOwnerMailZip: WideString; FOwnerMailZip4: WideString; FAssessedLandValue: WideString; FAssessedImprovement: WideString; FTotalAssessedValue: WideString; FMarketLandValue: WideString; FMarketImprovementValue: WideString; FTotalMarketValue: WideString; FTaxRateCodeArea: WideString; FTaxAmount: WideString; FTaxDelinquentYear: WideString; FHomeOwnerExemption: WideString; FLotNumber: WideString; FLandLot: WideString; FBlock: WideString; FSection: WideString; FDistrict: WideString; FUnit_: WideString; FCityMuniTwp: WideString; FSubdivisionName: WideString; FPhaseNumber: WideString; FTractNumber: WideString; FSecTwpRngMer: WideString; FLegalBriefDescription: WideString; FMapRef: WideString; FLotSize: WideString; FLotSizeUnits: WideString; FBuildingArea: WideString; FYearBuilt: WideString; FNumBuildings: WideString; FNumUnits: WideString; FBedrooms: WideString; FBaths: WideString; FTotalRooms: WideString; FGarageType: WideString; FGarageNumCars: WideString; FPool: WideString; FFirePlace: WideString; FImprovedPercentage: WideString; FTaxStatus: WideString; FHousingTract: WideString; published property SiteAddress: WideString read FSiteAddress write FSiteAddress; property SiteUnitType: WideString read FSiteUnitType write FSiteUnitType; property SiteUnit: WideString read FSiteUnit write FSiteUnit; property SiteCity: WideString read FSiteCity write FSiteCity; property SiteState: WideString read FSiteState write FSiteState; property SiteZip: WideString read FSiteZip write FSiteZip; property SiteZip4: WideString read FSiteZip4 write FSiteZip4; property APN: WideString read FAPN write FAPN; property CensusTract: WideString read FCensusTract write FCensusTract; property UseCodeDescription: WideString read FUseCodeDescription write FUseCodeDescription; property Zoning: WideString read FZoning write FZoning; property OwnerName: WideString read FOwnerName write FOwnerName; property OwnerMailUnitType: WideString read FOwnerMailUnitType write FOwnerMailUnitType; property OwnerMailUnit: WideString read FOwnerMailUnit write FOwnerMailUnit; property OwnerMailAddress: WideString read FOwnerMailAddress write FOwnerMailAddress; property OwnerMailCity: WideString read FOwnerMailCity write FOwnerMailCity; property OwnerMailState: WideString read FOwnerMailState write FOwnerMailState; property OwnerMailZip: WideString read FOwnerMailZip write FOwnerMailZip; property OwnerMailZip4: WideString read FOwnerMailZip4 write FOwnerMailZip4; property AssessedLandValue: WideString read FAssessedLandValue write FAssessedLandValue; property AssessedImprovement: WideString read FAssessedImprovement write FAssessedImprovement; property TotalAssessedValue: WideString read FTotalAssessedValue write FTotalAssessedValue; property MarketLandValue: WideString read FMarketLandValue write FMarketLandValue; property MarketImprovementValue: WideString read FMarketImprovementValue write FMarketImprovementValue; property TotalMarketValue: WideString read FTotalMarketValue write FTotalMarketValue; property TaxRateCodeArea: WideString read FTaxRateCodeArea write FTaxRateCodeArea; property TaxAmount: WideString read FTaxAmount write FTaxAmount; property TaxDelinquentYear: WideString read FTaxDelinquentYear write FTaxDelinquentYear; property HomeOwnerExemption: WideString read FHomeOwnerExemption write FHomeOwnerExemption; property LotNumber: WideString read FLotNumber write FLotNumber; property LandLot: WideString read FLandLot write FLandLot; property Block: WideString read FBlock write FBlock; property Section: WideString read FSection write FSection; property District: WideString read FDistrict write FDistrict; property Unit_: WideString read FUnit_ write FUnit_; property CityMuniTwp: WideString read FCityMuniTwp write FCityMuniTwp; property SubdivisionName: WideString read FSubdivisionName write FSubdivisionName; property PhaseNumber: WideString read FPhaseNumber write FPhaseNumber; property TractNumber: WideString read FTractNumber write FTractNumber; property SecTwpRngMer: WideString read FSecTwpRngMer write FSecTwpRngMer; property LegalBriefDescription: WideString read FLegalBriefDescription write FLegalBriefDescription; property MapRef: WideString read FMapRef write FMapRef; property LotSize: WideString read FLotSize write FLotSize; property LotSizeUnits: WideString read FLotSizeUnits write FLotSizeUnits; property BuildingArea: WideString read FBuildingArea write FBuildingArea; property YearBuilt: WideString read FYearBuilt write FYearBuilt; property NumBuildings: WideString read FNumBuildings write FNumBuildings; property NumUnits: WideString read FNumUnits write FNumUnits; property Bedrooms: WideString read FBedrooms write FBedrooms; property Baths: WideString read FBaths write FBaths; property TotalRooms: WideString read FTotalRooms write FTotalRooms; property GarageType: WideString read FGarageType write FGarageType; property GarageNumCars: WideString read FGarageNumCars write FGarageNumCars; property Pool: WideString read FPool write FPool; property FirePlace: WideString read FFirePlace write FFirePlace; property ImprovedPercentage: WideString read FImprovedPercentage write FImprovedPercentage; property TaxStatus: WideString read FTaxStatus write FTaxStatus; property HousingTract: WideString read FHousingTract write FHousingTract; end; // ************************************************************************ // // Namespace : http://BradfordTechnologies.SiteXData.com/BradfordTechnologies/ // ************************************************************************ // LegalDescriptionInfo = class(TRemotable) private FLotCode: WideString; FLotNumber: WideString; FBlock: WideString; FSection: WideString; FDistrict: WideString; FSubdivision: WideString; FTractNumber: WideString; FPhaseNumber: WideString; FUnit_: WideString; FLandLot: WideString; FMapRef: WideString; FSecTwnshipRange: WideString; FLegalBriefDescription: WideString; FCityMuniTwp: WideString; published property LotCode: WideString read FLotCode write FLotCode; property LotNumber: WideString read FLotNumber write FLotNumber; property Block: WideString read FBlock write FBlock; property Section: WideString read FSection write FSection; property District: WideString read FDistrict write FDistrict; property Subdivision: WideString read FSubdivision write FSubdivision; property TractNumber: WideString read FTractNumber write FTractNumber; property PhaseNumber: WideString read FPhaseNumber write FPhaseNumber; property Unit_: WideString read FUnit_ write FUnit_; property LandLot: WideString read FLandLot write FLandLot; property MapRef: WideString read FMapRef write FMapRef; property SecTwnshipRange: WideString read FSecTwnshipRange write FSecTwnshipRange; property LegalBriefDescription: WideString read FLegalBriefDescription write FLegalBriefDescription; property CityMuniTwp: WideString read FCityMuniTwp write FCityMuniTwp; end; // ************************************************************************ // // Namespace : http://BradfordTechnologies.SiteXData.com/BradfordTechnologies/ // ************************************************************************ // Transfer = class(TRemotable) private FTypeCD: WideString; FRecordingDate: WideString; FDocumentNumber: WideString; FDocumentType: WideString; FDocumentTypeCode: WideString; FBook: WideString; FPage: WideString; FMultiAPN: WideString; FLoan1DueDate: WideString; FLoan1Amount: WideString; FLoan1Type: WideString; FMortDoc: WideString; FLenderName: WideString; FLenderType: WideString; FTypeFinancing: WideString; FLoan1Rate: WideString; FLoan2Amount: WideString; FBuyerName: WideString; FBuyerMailCareOfName: WideString; FBuyerMailUnit: WideString; FBuyerMailUnitType: WideString; FBuyerMailAddress: WideString; FBuyerMailCity: WideString; FBuyerMailState: WideString; FBuyerMailZip: WideString; FBuyerMailZip4: WideString; FBuyerVesting: WideString; FBuyerID: WideString; FSellerName: WideString; FSellerID: WideString; FSalePrice: WideString; FSalePriceCode: WideString; FSaleType: WideString; FLegalDescriptionInfo: LegalDescriptionInfo; public destructor Destroy; override; published property TypeCD: WideString read FTypeCD write FTypeCD; property RecordingDate: WideString read FRecordingDate write FRecordingDate; property DocumentNumber: WideString read FDocumentNumber write FDocumentNumber; property DocumentType: WideString read FDocumentType write FDocumentType; property DocumentTypeCode: WideString read FDocumentTypeCode write FDocumentTypeCode; property Book: WideString read FBook write FBook; property Page: WideString read FPage write FPage; property MultiAPN: WideString read FMultiAPN write FMultiAPN; property Loan1DueDate: WideString read FLoan1DueDate write FLoan1DueDate; property Loan1Amount: WideString read FLoan1Amount write FLoan1Amount; property Loan1Type: WideString read FLoan1Type write FLoan1Type; property MortDoc: WideString read FMortDoc write FMortDoc; property LenderName: WideString read FLenderName write FLenderName; property LenderType: WideString read FLenderType write FLenderType; property TypeFinancing: WideString read FTypeFinancing write FTypeFinancing; property Loan1Rate: WideString read FLoan1Rate write FLoan1Rate; property Loan2Amount: WideString read FLoan2Amount write FLoan2Amount; property BuyerName: WideString read FBuyerName write FBuyerName; property BuyerMailCareOfName: WideString read FBuyerMailCareOfName write FBuyerMailCareOfName; property BuyerMailUnit: WideString read FBuyerMailUnit write FBuyerMailUnit; property BuyerMailUnitType: WideString read FBuyerMailUnitType write FBuyerMailUnitType; property BuyerMailAddress: WideString read FBuyerMailAddress write FBuyerMailAddress; property BuyerMailCity: WideString read FBuyerMailCity write FBuyerMailCity; property BuyerMailState: WideString read FBuyerMailState write FBuyerMailState; property BuyerMailZip: WideString read FBuyerMailZip write FBuyerMailZip; property BuyerMailZip4: WideString read FBuyerMailZip4 write FBuyerMailZip4; property BuyerVesting: WideString read FBuyerVesting write FBuyerVesting; property BuyerID: WideString read FBuyerID write FBuyerID; property SellerName: WideString read FSellerName write FSellerName; property SellerID: WideString read FSellerID write FSellerID; property SalePrice: WideString read FSalePrice write FSalePrice; property SalePriceCode: WideString read FSalePriceCode write FSalePriceCode; property SaleType: WideString read FSaleType write FSaleType; property LegalDescriptionInfo: LegalDescriptionInfo read FLegalDescriptionInfo write FLegalDescriptionInfo; end; ArrayOfTransfer = array of Transfer; { "http://BradfordTechnologies.SiteXData.com/BradfordTechnologies/" } // ************************************************************************ // // Namespace : http://BradfordTechnologies.SiteXData.com/BradfordTechnologies/ // ************************************************************************ // PriorSale = class(TRemotable) private FBuyer1FirstName: WideString; FBuyer1LastName: WideString; FBuyer2FirstName: WideString; FBuyer2LastName: WideString; FSeller1FirstName: WideString; FSeller1LastName: WideString; FSeller2FirstName: WideString; FSeller2LastName: WideString; FRecordingDate: WideString; FSalePrice: WideString; published property Buyer1FirstName: WideString read FBuyer1FirstName write FBuyer1FirstName; property Buyer1LastName: WideString read FBuyer1LastName write FBuyer1LastName; property Buyer2FirstName: WideString read FBuyer2FirstName write FBuyer2FirstName; property Buyer2LastName: WideString read FBuyer2LastName write FBuyer2LastName; property Seller1FirstName: WideString read FSeller1FirstName write FSeller1FirstName; property Seller1LastName: WideString read FSeller1LastName write FSeller1LastName; property Seller2FirstName: WideString read FSeller2FirstName write FSeller2FirstName; property Seller2LastName: WideString read FSeller2LastName write FSeller2LastName; property RecordingDate: WideString read FRecordingDate write FRecordingDate; property SalePrice: WideString read FSalePrice write FSalePrice; end; ArrayOfPriorSale = array of PriorSale; { "http://BradfordTechnologies.SiteXData.com/BradfordTechnologies/" } // ************************************************************************ // // Namespace : http://BradfordTechnologies.SiteXData.com/BradfordTechnologies/ // ************************************************************************ // ComparableSale = class(TRemotable) private FProximity: WideString; FSiteAddress: WideString; FSiteUnit: WideString; FSiteUnitType: WideString; FSiteCity: WideString; FSiteState: WideString; FSiteZip: WideString; FSiteZip4: WideString; FRecordingDate: WideString; FPriceCode: WideString; FSalePrice: WideString; FAssessmentValue: WideString; FPricePerSQFT: WideString; FBuildingArea: WideString; FTotalRooms: WideString; FBedrooms: WideString; FBaths: WideString; FYearBuilt: WideString; FLotSize: WideString; FPool: WideString; FAPN: WideString; FDocumentNumber: WideString; FDocumentType: WideString; FUseCodeDescription: WideString; FLotCode: WideString; FLotNumber: WideString; FBlock: WideString; FSection: WideString; FDistrict: WideString; FLandLot: WideString; FUnit_: WideString; FCityMuniTwp: WideString; FSubdivisionName: WideString; FPhaseNumber: WideString; FTractNumber: WideString; FLegalBriefDescription: WideString; FSecTwpRngMer: WideString; FMapRef: WideString; FBuyer1FName: WideString; FBuyer1LName: WideString; FBuyer2FName: WideString; FBuyer2LName: WideString; FSeller1FName: WideString; FSeller1LName: WideString; FSeller2FName: WideString; FSeller2LName: WideString; FLenderName: WideString; FLoan1Amount: WideString; FLatitude: WideString; FLongitude: WideString; FPriorSales: ArrayOfPriorSale; public destructor Destroy; override; published property Proximity: WideString read FProximity write FProximity; property SiteAddress: WideString read FSiteAddress write FSiteAddress; property SiteUnit: WideString read FSiteUnit write FSiteUnit; property SiteUnitType: WideString read FSiteUnitType write FSiteUnitType; property SiteCity: WideString read FSiteCity write FSiteCity; property SiteState: WideString read FSiteState write FSiteState; property SiteZip: WideString read FSiteZip write FSiteZip; property SiteZip4: WideString read FSiteZip4 write FSiteZip4; property RecordingDate: WideString read FRecordingDate write FRecordingDate; property PriceCode: WideString read FPriceCode write FPriceCode; property SalePrice: WideString read FSalePrice write FSalePrice; property AssessmentValue: WideString read FAssessmentValue write FAssessmentValue; property PricePerSQFT: WideString read FPricePerSQFT write FPricePerSQFT; property BuildingArea: WideString read FBuildingArea write FBuildingArea; property TotalRooms: WideString read FTotalRooms write FTotalRooms; property Bedrooms: WideString read FBedrooms write FBedrooms; property Baths: WideString read FBaths write FBaths; property YearBuilt: WideString read FYearBuilt write FYearBuilt; property LotSize: WideString read FLotSize write FLotSize; property Pool: WideString read FPool write FPool; property APN: WideString read FAPN write FAPN; property DocumentNumber: WideString read FDocumentNumber write FDocumentNumber; property DocumentType: WideString read FDocumentType write FDocumentType; property UseCodeDescription: WideString read FUseCodeDescription write FUseCodeDescription; property LotCode: WideString read FLotCode write FLotCode; property LotNumber: WideString read FLotNumber write FLotNumber; property Block: WideString read FBlock write FBlock; property Section: WideString read FSection write FSection; property District: WideString read FDistrict write FDistrict; property LandLot: WideString read FLandLot write FLandLot; property Unit_: WideString read FUnit_ write FUnit_; property CityMuniTwp: WideString read FCityMuniTwp write FCityMuniTwp; property SubdivisionName: WideString read FSubdivisionName write FSubdivisionName; property PhaseNumber: WideString read FPhaseNumber write FPhaseNumber; property TractNumber: WideString read FTractNumber write FTractNumber; property LegalBriefDescription: WideString read FLegalBriefDescription write FLegalBriefDescription; property SecTwpRngMer: WideString read FSecTwpRngMer write FSecTwpRngMer; property MapRef: WideString read FMapRef write FMapRef; property Buyer1FName: WideString read FBuyer1FName write FBuyer1FName; property Buyer1LName: WideString read FBuyer1LName write FBuyer1LName; property Buyer2FName: WideString read FBuyer2FName write FBuyer2FName; property Buyer2LName: WideString read FBuyer2LName write FBuyer2LName; property Seller1FName: WideString read FSeller1FName write FSeller1FName; property Seller1LName: WideString read FSeller1LName write FSeller1LName; property Seller2FName: WideString read FSeller2FName write FSeller2FName; property Seller2LName: WideString read FSeller2LName write FSeller2LName; property LenderName: WideString read FLenderName write FLenderName; property Loan1Amount: WideString read FLoan1Amount write FLoan1Amount; property Latitude: WideString read FLatitude write FLatitude; property Longitude: WideString read FLongitude write FLongitude; property PriorSales: ArrayOfPriorSale read FPriorSales write FPriorSales; end; ArrayOfComparableSale = array of ComparableSale; { "http://BradfordTechnologies.SiteXData.com/BradfordTechnologies/" } // ************************************************************************ // // Namespace : http://BradfordTechnologies.SiteXData.com/BradfordTechnologies/ // ************************************************************************ // ReportResult = class(TRemotable) private FAssessmentInfo: AssessmentInfo; FTransferHistory: ArrayOfTransfer; FComparableSales: ArrayOfComparableSale; public destructor Destroy; override; published property AssessmentInfo: AssessmentInfo read FAssessmentInfo write FAssessmentInfo; property TransferHistory: ArrayOfTransfer read FTransferHistory write FTransferHistory; property ComparableSales: ArrayOfComparableSale read FComparableSales write FComparableSales; end; // ************************************************************************ // // Namespace : http://BradfordTechnologies.SiteXData.com/BradfordTechnologies/ // ************************************************************************ // BradfordTechnologiesResult = class(TRemotable) private FMatchCode: Integer; FMessage: WideString; FLocations: ArrayOfLocation; FReportResult: ReportResult; public destructor Destroy; override; published property MatchCode: Integer read FMatchCode write FMatchCode; property Message: WideString read FMessage write FMessage; property Locations: ArrayOfLocation read FLocations write FLocations; property ReportResult: ReportResult read FReportResult write FReportResult; end; // ************************************************************************ // // Namespace : http://tempuri.org/ // soapAction: http://tempuri.org/GetFISDataFromField // transport : http://schemas.xmlsoap.org/soap/http // style : document // binding : FidelityServiceSoap // service : FidelityService // port : FidelityServiceSoap // URL : http://webservices.bradfordsoftware.com/WSFidelity/FidelityService.asmx // ************************************************************************ // FidelityServiceSoap = interface(IInvokable) ['{CCAA8690-87EC-4F92-27CA-48C98B22309A}'] procedure GetFISDataFromField(const iCustID: Integer; const szPassword: WideString; const oFISRequest: FISRequestRec; out GetFISDataFromFieldResult: BradfordTechnologiesResult; out iMsgCode: Integer; out sMsgText: WideString); stdcall; end; function GetFidelityServiceSoap(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): FidelityServiceSoap; implementation function GetFidelityServiceSoap(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): FidelityServiceSoap; const defWSDL = 'http://webservices.bradfordsoftware.com/WSFidelity/FidelityService.asmx?wsdl'; defURL = 'http://webservices.bradfordsoftware.com/WSFidelity/FidelityService.asmx'; defSvc = 'FidelityService'; defPrt = 'FidelityServiceSoap'; var RIO: THTTPRIO; begin Result := nil; if (Addr = '') then begin if UseWSDL then Addr := defWSDL else Addr := defURL; end; if HTTPRIO = nil then RIO := THTTPRIO.Create(nil) else RIO := HTTPRIO; try Result := (RIO as FidelityServiceSoap); if UseWSDL then begin RIO.WSDLLocation := Addr; RIO.Service := defSvc; RIO.Port := defPrt; end else RIO.URL := Addr; finally if (Result = nil) and (HTTPRIO = nil) then RIO.Free; end; end; destructor Transfer.Destroy; begin if Assigned(FLegalDescriptionInfo) then FLegalDescriptionInfo.Free; inherited Destroy; end; destructor ComparableSale.Destroy; var I: Integer; begin for I := 0 to Length(FPriorSales)-1 do if Assigned(FPriorSales[I]) then FPriorSales[I].Free; SetLength(FPriorSales, 0); inherited Destroy; end; destructor ReportResult.Destroy; var I: Integer; begin for I := 0 to Length(FTransferHistory)-1 do if Assigned(FTransferHistory[I]) then FTransferHistory[I].Free; SetLength(FTransferHistory, 0); for I := 0 to Length(FComparableSales)-1 do if Assigned(FComparableSales[I]) then FComparableSales[I].Free; SetLength(FComparableSales, 0); if Assigned(FAssessmentInfo) then FAssessmentInfo.Free; inherited Destroy; end; destructor BradfordTechnologiesResult.Destroy; var I: Integer; begin for I := 0 to Length(FLocations)-1 do if Assigned(FLocations[I]) then FLocations[I].Free; SetLength(FLocations, 0); if Assigned(FReportResult) then FReportResult.Free; inherited Destroy; end; initialization InvRegistry.RegisterInterface(TypeInfo(FidelityServiceSoap), 'http://tempuri.org/', 'utf-8'); InvRegistry.RegisterDefaultSOAPAction(TypeInfo(FidelityServiceSoap), 'http://tempuri.org/GetFISDataFromField'); InvRegistry.RegisterInvokeOptions(TypeInfo(FidelityServiceSoap), ioDocument); RemClassRegistry.RegisterXSClass(FISRequestRec, 'http://tempuri.org/', 'FISRequestRec'); RemClassRegistry.RegisterXSClass(Location, 'http://BradfordTechnologies.SiteXData.com/BradfordTechnologies/', 'Location'); RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfLocation), 'http://BradfordTechnologies.SiteXData.com/BradfordTechnologies/', 'ArrayOfLocation'); RemClassRegistry.RegisterXSClass(AssessmentInfo, 'http://BradfordTechnologies.SiteXData.com/BradfordTechnologies/', 'AssessmentInfo'); RemClassRegistry.RegisterExternalPropName(TypeInfo(AssessmentInfo), 'Unit_', 'Unit'); RemClassRegistry.RegisterXSClass(LegalDescriptionInfo, 'http://BradfordTechnologies.SiteXData.com/BradfordTechnologies/', 'LegalDescriptionInfo'); RemClassRegistry.RegisterExternalPropName(TypeInfo(LegalDescriptionInfo), 'Unit_', 'Unit'); RemClassRegistry.RegisterXSClass(Transfer, 'http://BradfordTechnologies.SiteXData.com/BradfordTechnologies/', 'Transfer'); RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfTransfer), 'http://BradfordTechnologies.SiteXData.com/BradfordTechnologies/', 'ArrayOfTransfer'); RemClassRegistry.RegisterXSClass(PriorSale, 'http://BradfordTechnologies.SiteXData.com/BradfordTechnologies/', 'PriorSale'); RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfPriorSale), 'http://BradfordTechnologies.SiteXData.com/BradfordTechnologies/', 'ArrayOfPriorSale'); RemClassRegistry.RegisterXSClass(ComparableSale, 'http://BradfordTechnologies.SiteXData.com/BradfordTechnologies/', 'ComparableSale'); RemClassRegistry.RegisterExternalPropName(TypeInfo(ComparableSale), 'Unit_', 'Unit'); RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfComparableSale), 'http://BradfordTechnologies.SiteXData.com/BradfordTechnologies/', 'ArrayOfComparableSale'); RemClassRegistry.RegisterXSClass(ReportResult, 'http://BradfordTechnologies.SiteXData.com/BradfordTechnologies/', 'ReportResult'); RemClassRegistry.RegisterXSClass(BradfordTechnologiesResult, 'http://BradfordTechnologies.SiteXData.com/BradfordTechnologies/', 'BradfordTechnologiesResult'); end.
unit UGraphs; interface uses Graphics, Types; type TGraphPoint = class x,y : Single; id : Integer; FText : String; Width, Height: Single; private FSelected : Boolean; procedure SetText(const Value: String); published public constructor Create;overload; constructor Create(AID: Integer; AX, AY: Single; AText : String);overload; procedure Paint(ACanvas : TCanvas); function HitTest(AX,AY : Single) : Boolean; function GetMaxX : Integer; function GetMaxY : Integer; property Text: String read FText write SetText; function MouseDown(mp : TPoint): Boolean; function MouseMove(newmp: TPoint): Boolean; function MouseUp(): Boolean; end; TGraphLink = class A,B : TGraphPoint; constructor Create(AA,AB : TGraphPoint); procedure Paint (ACanvas : TCanvas); end; var gMousePos : TPoint; implementation { TGraphPoint } constructor TGraphPoint.Create(AID : Integer; AX, AY: Single; AText : String); begin Create; X := AX; Y := AY; ID := AID; Text := AText; end; constructor TGraphPoint.Create; begin inherited Create; FSelected := false; Text := ''; end; function TGraphPoint.GetMaxX: Integer; begin Result := Round(X) + 100; end; function TGraphPoint.GetMaxY: Integer; begin Result := Round(Y) + 50; end; function TGraphPoint.HitTest(AX, AY: Single): Boolean; begin Result := PtInRect(Bounds(Round(X-Width / 2), Round(Y - Height / 2), Round(Width), Round(Height)), Point(Round(AX), Round(AY))); end; function TGraphPoint.MouseDown(mp: TPoint): Boolean; begin if HitTest(mp.X, mp.Y) then begin Result := True; FSelected := True; gMousePos := mp; end else begin Result:= False; end; end; function TGraphPoint.MouseMove(newmp: TPoint): Boolean; begin Result := FSelected; if FSelected then begin X := X + newmp.X - gMousePos.X; Y := Y + newmp.Y - gMousePos.Y; gMousePos := newmp; end; end; function TGraphPoint.MouseUp: Boolean; begin Result := False; FSelected := false; end; function RGB (r,g,b: Byte) : TColor; begin Result := r shl 16 or g shl 8 or b end; procedure TGraphPoint.Paint(ACanvas : TCanvas); var W,H : Integer; begin W := ACanvas.TextWidth(Text)+2; H := ACanvas.TextHeight(Text)+2; ACanvas.Brush.Color := RGB(200,200,200); ACanvas.Pen.Style := psSolid; ACanvas.Rectangle(Bounds(Round (X)-W div 2, Round (Y) - H div 2, W, H)); ACanvas.TextOut(Round (X)-W div 2+1, Round (Y) - H div 2+1, Text); Width := W; Height := H; end; procedure TGraphPoint.SetText(const Value: String); begin FText := Value; Width := 10*length(text); Height := 20; end; { TGraphLink } constructor TGraphLink.Create(AA, AB: TGraphPoint); begin A := AA; B := AB; end; procedure TGraphLink.Paint(ACanvas: TCanvas); begin ACanvas.Pen.Color := clNavy; ACanvas.Pen.Style := psSolid; ACanvas.MoveTo(Round(A.X), Round(A.Y)); ACanvas.LineTo(Round(B.X), Round(B.Y)); end; end.
unit UExportApprPortXML2; { ClickForms Application } { Bradford Technologies, Inc. } { All Rights Reserved } { Source Code Copyrighted © 1998-2011 by Bradford Technologies, Inc. } { this the unit that creates the AIready XML and loads it to the FNC Enveloper } interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, xmldom, XMLIntf, msxmldom, XMLDoc, ComCtrls, StdCtrls, FastXML_TLB, ENVUPD_TLB, UForms; const ApprWorldSubDir = 'AppraisalWorld'; AISubDir = 'AIReady'; MapsSubDir = 'AppraisalWorld\AIReady\Maps'; FNCToolDir = 'AppraisalWorld\AIReady\FNC Uploader'; ImgDLLdir = 'Tools\Imaging'; tmpEnvFileName = 'latestEnvFile.env'; strVendor = 'Bradford Technologies'; strVersion = '4.5'; // appraisal port compliance version CLKPathKeyName = 'Path'; envpUpExe = 'envupd.exe'; envUplWndTitle = 'ENVUPD'; envUplWndClass = 'TApplication'; formListFName = 'FormList.txt'; imgMapFName = 'arImages.txt'; geocodeMapFileName = 'arGeocodes.txt'; addendaMapFName = 'Addenda.txt'; tagForminfo = 'FORMINFO'; tagAddendums = 'ADDENDUMS'; pathAddendums = '\ADDENDUMS'; pathRoot = '\'; arPrefix = 'ar'; strForm = ' Form'; strSignature = 'signature'; checkBoxMark = 'X'; strOn = 'On'; strOff = 'Off'; strMoveTo = 'MOVETO'; strMainForm = 'MAINFORM'; cmdOpen = 'Open'; airImgTypes = 18; jpegType = 'JPEG'; jpgExt = '.jpg'; emfExt = '.emf'; commaDelim = ','; SpaceDelim = ' '; //addendum Fiellds strAddendNum = 'NUM'; strAddendName = 'NAME'; straddendValue = 'VALUE'; strAdditComment = 'Additional Comment'; //address fields strCity = 'City'; strStreet = 'Street'; strState = 'State'; strZip = 'Zip'; strCompany = 'Company'; strPhone = 'Phone'; strUnit = 'Unit'; //cell Types strClRegular = 'Regular'; strClCheckBox = 'Ch'; strClAlternCheckBox = 'MCh'; strClFullAddress = 'FullAddress'; strClCityStateZip = 'CityStateZip'; strClFormNum = 'Formnum'; strClFormVersion = 'FormVersion'; strClVendor = 'Vendor'; strClVersion = 'Version'; strClDocID = 'DocID'; strClcompNum = 'CompNum'; strSeqNum = 'NUM'; strClSignature = 'Signature'; strClExtraCompComm = 'ExtraCompComment'; strClMerge = 'Merge'; strClAddAttrib = 'AddAttrib'; strClMoveToMainForm = 'MoveToMainForm'; strClUADVersion = 'UADVersion'; strClUnitCityStateZip = 'UnitCityStateZip'; strClPredefinedText = 'PredefinedText'; //Limits maxComps = 12; maxAddSubjPhotos = 3; maxListingPhotos = 9; maxAddPhotos = 99; maxPlatMaps = 5; maxLocationMaps = 5; maxAddMaps = 50; maxSketches = 5; //Image XML fields fldImgFileName = 'FileName'; fldImgFileType = 'FileType'; fldImgName = 'Name'; fldImgTitle = 'Title'; fldImgDescr1 = 'ImgDescr1'; fldImgDescrNum1 = 'ImgDescrNum1'; fldImgDescr2 = 'ImgDescr2'; fldImgDescrNum2 = 'ImgDescrNum2'; fldImgDescr3 = 'ImgDescr3'; fldImgDescrNum3 = 'ImgDescrNum3'; fldImgNum = 'NUM'; fldImgCompNum = 'COMPNUM'; //error messages strCantCompl = #13#10 + 'The AIReady conversion cannot be completed.'; errWrongCmdLine = 'There is an error in calling %s. ' + strCantCompl; errCantFindMaps = 'Cannot find the AIReady utility files. ' + strCantCompl; errCantFindSrcFile = 'Cannot find the source file %s. ' + strCantCompl; errWrongSrcXML = 'There is an error in the export package %s. ' + strCantCompl; errCantFindSrcPack = 'Cannot find the export package %s. ' + strCantCompl; errNoAiReadyForm = 'Cannot find the AIReady Form corresponding %s'; errWrongMapFile = 'There is an error in the map file %s. ' + strCantCompl; errCantConvForm = 'Cannot convert the file %s. ' + strCantCompl; errCantFindUploader = 'Cannot find the FNC Uploader. ' + strCantcompl; errCantFindMap = 'Cannot find the mapping file %s ' + strCantcompl; errCantConvToJpg = 'Cannot convert the image %s to JPG ' + strCantcompl; errCantOpenUpl = 'Cannot open the FNC Uploader. ' + strCantcompl; errCantFindForm = 'Cannot find the form %s'; msgContConv = 'The form %s cannot be converted to AIReady format.' + #13#10 + 'Do you want to continue the conversion?'; type DataType = (Text,FileName); FormType = (frmRegular,frmSketch,frmExtraComps,frmMap,frmPhoto,frmComment); PageType = (pgRegular,pgExtraTableOfContent,pgExtraComps,pgExtraListing,pgExtraRental, pgSketch,pgPlatMap,pgLocationMap,pgFloodMap,pgExhibit,pgPhotosComps, pgPhotosListing,pgPhotosRental,pgPhotosSubject,pgPhotosSubjectExtra, pgMapListing,pgMapRental,pgMapOther,pgPhotosUntitled,pgComments); ImageType = (imgGeneral,imgSubjectFront,imgSubjectRear,imgSubjectStreet,imgPhotoTop, imgPhotoMiddle,imgPhotoBottom,imgMap,imgMetafile,imgGeneric1,imgGeneric2, imgGeneric3,imgGeneric4,imgGeneric5,imgGeneric6,imgGeneric7,imgInspectPhoto1,imgInspectPhoto2); AiReadyImageType = (UNKNOWN,SUBJECTFRONTVIEW,SUBJECTREARVIEW,SUBJECTSTREETVIEW, SUBJECTADDITIONAL,COMPPHOTO,LISTINGCOMPPHOTO,ADDITIONALPHOTO,PLATMAP,LOCATIONMAP, FLOODMAP,ADDITIONALMAP,FLOORPLAN,sgnAPPRAISER,sgnSUPAPPRAISER, sgnSUPERVISOR,sgnREVAPPRAISER,sgnREVAPPRAISER2, GENERICPHOTO, INSPECTPHOTO); PhotoLocation = (locUnknown,locPhotoTop,locPhotoMiddle,locPhotoBottom); CellType = (clRegular, clCheckBox, clAlternCheckBox,clFullAddress,clCityStateZip, clExtraCompComm,clFormNum,clFormVersion,clVendor,clVersion,clDocID,clCompNum, clPredefinedText, clMerge,clAddAttrib,clMoveToMainForm,clSignature,clUADVersion,clUnitCityStateZip, clSeqNum); airFileType = (MainForm, AddendumForm,ImageFile); airFormRec = record frmName: String; frmVersion: String; end; subStrArr = Array of String; fileRec = record fltype: airFileType; frmName: String; xmlObj: TXMLDOM; Path, Descr, key: String; end; imgFileRec = record imgType: AiReadyImageType; key,flDescr: String; end; imgRec = record imgType: string; param: Integer; path,key,flDescr,name,title,descr1,descr2,descr3,imgFormat: String; end; imgMapRec = record imgType: String; fldType: String; param: Integer; attr,xmlPath: String; end; addendMapRec = record fldName, attr, xmlPath1,xmlPath2: String; end; mapRec = record clNo: Integer; clType: CellType; param,attr,xmlPath: String; end; cellRecord = record cellNo,cellID: Integer; dtType: DataType; cellText: String; end; geocodeMapRec = record compNo: Integer; propType, field,xPath: String; end; TExportApprPortXML = class(TObject) CLKDir: String; mapsDir: String; FNCDir: String; XMLSrcDir: String; mainFormID: Integer; airMainForm: String; filesToAdd: Array of fileRec; FRptName: String; curForm: String; curFormVersion: String; curFormUADVersion: String; curExtraCompSet: Integer; curAddSubjPhoto: Integer; curAddPhoto: Integer; curListingPhoto: Integer; curPlatMap: Integer; curLocMap: Integer; curAddMap: Integer; curSketch: Integer; fXmlMainForm: TXMLDOM; FXMLSrc: TXMLDocument; FXMLPackagePath: String; FSaveENV: Boolean; FENVFilePath: string; FMISMOXMLPath: String; private envUP: TPackage ; procedure InitConverter; function CreateAiReadyXML:Boolean; function CreateEnvelope:Boolean; function ConvertForm(fXmlObj: TXMLDOM;frmNode: IXMLNode): Boolean; function GetAirForm(fmID: Integer): airFormRec; function GetSignatures(rtNode: IXMLNode): Boolean; function ConvertSketches(fXML:TXMLDOM;rtNode: IXMLNode): Boolean; function ConvertImages(fXML:TXMLDOM;rtNode: IXMLNode): Boolean; function ConvertComments(fXML:TXMLDOM;rtNode: IXMLNode): Boolean; function GetFormType(frmNode: IXMLNODE): FormType; function GetFormUADVersion(frmNode: IXMLNode): String; function CreateAirXmlFileName(formName: String): String; function WriteSpecAttributes(fXML: TXMLDOM; mfile: String): Boolean; function WriteAirXML(fXML:TXMLDOM; srcF,mapF: String): Boolean; procedure WriteImage(img: imgRec;fXML:TXMLDOM); procedure WriteSignature(fXML: TXMLDOM; airsignType,clfSignType: String); procedure WriteCityStateZip(fXML: TXMLDOM;mpList: TStringList; clRec: CellRecord); function GetAirImgType(pgType: PageType; imType: ImageType; var imgPos: Integer): AiReadyImageType; function FitImgRec(imType: aiReadyImagetype;var curImg: ImgRec;imgNode: IXMLNode): Boolean; function GetXml(curForm: String; var bNew: Boolean): TXMLDOM; procedure WriteUnitCityStateZip(fXML: TXMLDOM;mpList: TStringList; clRec: CellRecord;StreetNumber:String); //handle unit/city/state/zip function ConvertGeocodes(fXML:TXMLDOM;rtNode: IXMLNode): Boolean; procedure AddMismoXml(envUP: TPackage); public constructor Create; destructor Destroy; override; function StartConversion:Boolean; property ExportPath: String read FXMLPackagePath write FXMLPackagePath; property SaveENV: Boolean read FSaveENV write FSaveENV; property ENVFilePath: String read FENVFilePath write FENVFilePath; end; function CreateAppraisalPortXML(XMLPackagePath: String; bSaveEnv: Boolean = false): Boolean; implementation uses Registry, JPEG, ShellAPI, StrUtils, UGlobals, UXMLConst, UStatus, UUtilConvert2JPG, Dll96v1, UUtil1, UUtil2; const AirImages: Array[1..airImgTypes] of ImgFileRec = ((imgType: SUBJECTFRONTVIEW; key: 'SUBJECTFRONTVIEW'; flDescr: 'Front View'), (imgType: SUBJECTREARVIEW; key: 'SUBJECTREARVIEW'; flDescr: 'Rear View'), (imgType: SUBJECTSTREETVIEW; key: 'SUBJECTSTREETVIEW'; flDescr: 'Street View'), (imgType: SUBJECTADDITIONAL; key: 'SUBJECTADDITIONAL'; flDescr: 'Subject Photo'), (imgType: COMPPHOTO; key: 'COMPPHOTO'; flDescr: 'Photo Comps'), (imgType: LISTINGCOMPPHOTO; key: 'LISTINGCOMPPHOTO'; flDescr: 'Photo Listings'), (imgType: ADDITIONALPHOTO; key: 'ADDITIONALPHOTO'; flDescr: 'Additional Photo'), (imgType: PLATMAP; key: 'PLATMAP'; flDescr: 'Plat Map'), (imgType: LOCATIONMAP; key: 'LOCATIONMAP'; flDescr: 'Location Map'), (imgType: FLOODMAP; key: 'ADDITIONALMAP'; flDescr: 'Flood Map'), (imgType: ADDITIONALMAP; key: 'ADDITIONALMAP'; flDescr: 'Additional Map'), (imgType: FLOORPLAN; key: 'FLOORPLAN'; flDescr: 'Sketcher page'), (imgType: sgnAPPRAISER; key: 'APPRAISERSIGNATURE'; flDescr: 'Appraiser Signature'), (imgType: sgnSUPAPPRAISER; key: 'SUPAPPRAISERSIGNATURE'; flDescr: 'SupAppraiser Signature'), (imgType: sgnRevAppraiser; key: 'REVAPPRAISERSIGNATURE'; flDescr: 'RevAppraiser Signature'), (imgType: sgnRevAppraiser2; key: 'REVAPPRAISER2SIGNATURE'; flDescr: 'RevAppraiser2 Signature'), (imgType: GenericPhoto; key: 'GENERICPHOTO'; flDescr: 'Generic Photo'), (imgType: INSPECTPHOTO; key: 'INSPECTPHOTO'; flDescr: 'Inspection Photo')); function GetImageType(strImageType: String): ImageType; Forward; function GetPageType(strPageType: String): PageType; Forward; function GetCellType(strCellType: String): CellType; Forward; function GetMapFileName(fID, pg: Integer; cmpSet: Integer = 0): String; Forward; function GetMapRec(mapStr: String): MapRec; Forward; function GetMapRecByCellNo(mpList: TStringList;cl: Integer): MapRec; Forward; function GetCellRec(srcRec: String): cellRecord; Forward; function GetPhotoLocation(strPhotoLocation: String): PhotoLocation; Forward; function GetImgMapRec(imgMapStr: String): imgMapRec; Forward; function GetAddendMapRec(addMapRec: String): addendMapRec; Forward; function ParseCityStateZip(srcStr: String): subStrArr; Forward; function GetMainFormID(ApprWorldDir: String;frmStr: String): Integer; Forward; procedure GetImgFileInfo(tp: AiReadyImageType; clfPageType: String; var curImg: imgRec); Forward; procedure WriteGeneralFields(fXml: TXMLDOM); Forward; function ParseUnitCityStateZip(srcStr, StreetNumber: String): subStrArr; Forward; function ParsePropType(clfPropType: string; var compNo: Integer): string; Forward; function GetGeocodeMapRec(srcRec: String): geocodeMapRec; Forward; //Main procedure to create the process and convert dialog //need to replace with Processing Thread function CreateAppraisalPortXML(XMLPackagePath: String; bSaveEnv: Boolean = false):Boolean; var ExpAP: TExportApprPortXML; begin ExpAP := TExportApprPortXML.Create; result := True; try try ExpAP.FXMLPackagePath := XMLPackagePath; ExpAP.FMISMOXMLPath := IncludeTrailingPathDelimiter(ExtractFileDir(XMLPackagePath)) + arMismoXml; ExpAP.SaveENV := bSaveEnv; //default is upload result := ExpAP.StartConversion; except ShowAlert(atWarnAlert, 'Problems were encountered exporting to AppraisalPort.'); end; finally ExpAP.Free; end; end; { TExportApprPortXML } constructor TExportApprPortXML.Create; begin inherited; FXMLPackagePath := ''; FSaveENV := False; FENVFilePath := ''; envUP := nil; end; destructor TExportApprPortXML.Destroy; begin if assigned(FXMLSrc) then FXMLSrc.Free; filesToAdd := nil; if assigned(envUP) then envUP.Disconnect; //forced disconnecction from Ole Server end; function TExportApprPortXML.StartConversion:Boolean; begin result := True; try InitConverter; result := CreateAiReadyXML; if result then result := CreateEnvelope; except on E:Exception do begin if length(E.Message) > 0 then ShowAlert(atWarnAlert, E.Message); result := False; end; end; end; procedure TExportApprPortXML.InitConverter; var // reg: TRegistry; rpType: String; ExportXMLPath: String; begin //get source XML, comes in as second parameter - {not anymore} ExportXMLPath := FXMLPackagePath; if not FileExists(ExportXMLPath) then raise Exception.CreateFmt(errCantfindSrcPack,[ExportXMLPath]); FXMLSrc := TXMLDocument.Create(application); FXMLSrc.DOMVendor := GetDomVendor('MSXML'); FXMLSrc.FileName := ExportXMLPath; FXMLSrc.Active := True; XMLSrcDir := ExtractFileDir(ExportXMLPath); mapsDir := IncludeTrailingPathDelimiter(appPref_DirAppraisalWorld) + 'AIReady\Maps'; FNCDir := IncludeTrailingPathDelimiter(appPref_DirAppraisalWorld) + 'AIReady\FNC Uploader'; // mapsDir := IncludeTrailingPathDelimiter(CLKDir) + MapsSubDir; // FNCDir := IncludeTrailingPathDelimiter(CLKDir) + FNCToolDir; (* //get map directory mapsDir := ''; reg := TRegistry.Create; try reg.RootKey := HKEY_LOCAL_MACHINE; if reg.OpenKey(LocMachClickFormBaseSection, False) then CLKDir := ExtractFileDir(reg.ReadString(CLKPathKeyName)); if DirectoryExists(CLKDir) then begin mapsDir := IncludeTrailingPathDelimiter(CLKDir) + MapsSubDir; FNCDir := IncludeTrailingPathDelimiter(CLKDir) + FNCToolDir; DLLPATHNAME := IncludeTrailingPathDelimiter(CLKDir) + ImgDLLdir; end; finally reg.free; end; *) //make sure folders are there if not DirectoryExists(mapsDir) then raise Exception.Create(errCantFindMaps); if not DirectoryExists(FNCDir) then raise Exception.Create(errCantFindUploader); //get main form rpType := FXMLSrc.DocumentElement.attributes[tagReportType]; FRptName := FXMLSrc.DocumentElement.attributes[tagName]; mainFormID := GetMainFormID(IncludeTrailingPathDelimiter(appPref_DirAppraisalWorld), rpType); if MainFormID < 1 then raise Exception.CreateFmt(errWrongSrcXML, [FRptName]); airMainForm := GetAirForm(mainFormID).frmName; if length(airMainForm) = 0 then raise Exception.CreateFmt(errWrongSrcXML, [FRptName]); end; function TExportApprPortXML.CreateAiReadyXML:Boolean; var fXMLmain,fXMLadd: TXMLDOM; formsNode,formNode: IXMLNode; nForms: Integer; frm: Integer; frmType: FormType; airFrm: airFormRec; frmID: Integer; bNewForm: Boolean; indx: Integer; xmlText: TStringList; fPath: String; frmNamePos: Integer; begin result := True; fXMLMain := TXMLDOM.Create(screen.ActiveForm); fXMlMainForm := fXMLMain; // Global object we need it to handle Appraiser Certificate info fXMLMain.NewXML(tagFormInfo); formsNode := FXMLSrc.DocumentElement.ChildNodes.FindNode(tagForms); if not assigned(formsNode) then begin raise Exception.CreateFmt(errWrongSrcXML, [FRptName]); result := False; end; curExtraCompSet := 0; curAddSubjPhoto := 0; curListingPhoto := 0; curAddPhoto := 0; curPlatMap := 0; curLocMap := 0; curAddMap := 0; curSketch := 0; //make the main Form nForms := formsNode.ChildNodes.Count; for frm := 0 to nForms - 1 do begin formNode := formsNode.ChildNodes[frm]; if formNode.Attributes[tagFormID] = mainFormID then break end; if frm >= nForms then //did not find the main form begin raise Exception.CreateFmt(errWrongSrcXML, [FRptName]); result := False; end; //convert main form and images if not GetSignatures(FXMLSrc.DocumentElement) then begin raise Exception.CreateFmt(errWrongSrcXML, [FRptName]); result := False; end; airFrm := GetAirForm(mainFormID); curForm := airFrm.frmName; frmNamePos := Pos(strMoveTo,curForm); if frmNamePos = 1 then //get real Form Name curForm := Copy(curForm,length(strMoveTo) + 1,length(curForm)); curFormVersion := airFrm.frmVersion; curFormUADVersion := GetFormUADVersion(formNode); if not ( ConvertForm(fXMLmain,formNode) and ConvertComments(fXMLmain,FXMLSrc.DocumentElement) and ConvertSketches(fXMLmain,FXMLSrc.DocumentElement) and ConvertImages(fXMLmain,FXMLSrc.DocumentElement) and //get report level images (photo pages) ConvertImages(fXMLmain,formNode) and ConvertGeocodes(fXMLmain,FXMLSrc.DocumentElement)) then //get form level images begin raise Exception.CreateFmt(errWrongSrcXML, [FRptName]); //unspecific exception result := False; end; //add the main form to the list setLength(filesToAdd,length(filesToAdd) + 1); indx := length(filesToAdd) - 1; filesToAdd[indx].frmName := curForm; filesToAdd[indx].xmlObj := fXMLMain; filesToAdd[indx].fltype := Mainform; // make the addendum forms for frm := 0 to nForms - 1 do begin curExtraCompSet := 0; formNode := formsNode.ChildNodes[frm]; frmID := formNode.Attributes[tagFormID]; if frmID = mainFormID then continue; //we already handled it airFrm := GetAirForm(frmID); curForm := airFrm.frmName; curFormVersion := airFrm.frmVersion; frmType := GetFormType(formNode); case frmType of frmSketch, frmPhoto, frmMap, frmComment: continue; //we already added it to main Form frmExtraComps: begin curForm := airMainForm; if not ConvertForm(fXMLmain,formNode) then ;// just skip the form //raise Exception.CreateFmt(errWrongSrcXML, [FRptName]); //unspecific exception end; frmRegular: begin fXmlAdd := GetXml(curForm,bNewForm); if ( ConvertForm(fXmlAdd,FormNode) and ConvertImages(fXMLAdd,formNode)) then if bNewForm then // add the new form to list begin setLength(filesToAdd,length(filesToAdd) + 1); indx := length(filesToAdd) - 1; filesToAdd[indx].frmName := curForm; filesToAdd[indx].xmlObj := fXMLAdd; filesToAdd[indx].fltype := AddendumForm; end; end; end; end; WriteGeneralFields(fXMLmain); //create files for the main form for indx := 0 to length(FilesToAdd) - 1 do begin if FilesToAdd[indx].fltype = ImageFile then continue; // the file already created xmlText := TStringList.Create; with FilesToAdd[indx] do try xmlText.Text := xmlObj.XML; fPath := IncludeTrailingPathDelimiter(XMLSrcDir) + CreateAirXmlFileName(frmName); xmlText.SaveToFile(fPath); Path := fPath; Descr := frmName + strForm; finally xmlText.Free; xmlObj.Free; end; end; end; function TExportApprPortXML.CreateEnvelope:Boolean; var rec: Integer; flRec: fileRec; //envUP: TPackage; //moved to class member envupPath: String; cmdLine: String; startInfo: STARTUPINFO; procInfo: PROCESS_INFORMATION; mainFrmName: String; begin result := True; //create uploader envupPath := IncludeTrailingPathDelimiter(FNCDir) + envpUpExe; if not FileExists(envupPath) then begin raise Exception.Create(errCantFindUploader); result := False; end; //open ENVUPD cmdLine := '"' + envupPath + '"'; FillChar(startInfo,sizeof(startInfo),0); startInfo.cb := sizeof(startInfo); if not CreateProcess(nil,PChar(cmdLine),nil,nil,False,NORMAL_PRIORITY_CLASS,nil,nil,startInfo,procInfo) then begin raise Exception.Create(errCantOpenUpl); result := False; end; WaitForInputIdle(procInfo.hProcess, INFINITE); //wait 10 seconds or until ready envUp := TPackage.Create(screen.activeform); if SaveENV then envUp.HideSend; //hide the Send button //envUP.ShowMainForm; envUp.HideOnClose; if Length(filesToAdd) < 1 then exit; //add images for rec := 0 to length(filesToAdd) -1 do begin flRec := filesToAdd[rec]; if flRec.fltype = imageFile then envUp.AddImage(flRec.Path,flRec.Descr,flRec.key) end; //add Mismo XML //AddMismoXML(envUP); //add the main form for rec := 0 to length(filesToAdd) -1 do begin flRec := filesToAdd[rec]; if flRec.fltype = mainForm then begin mainFrmName := flRec.frmName; envUp.AddMainForm(flRec.Path,flRec.Descr); end; end; // then the addendum forms for rec := 0 to length(filesToAdd) -1 do begin flRec := filesToAdd[rec]; if flRec.fltype = addendumForm then envUp.AddAddendumForm(flRec.Path,flRec.Descr); end; AddMismoXML(envUP); envUP.ShowMainForm; //do we need to save the ENV file (ie not uploading) if SaveENV then begin ENVFilePath := IncludeTrailingPathDelimiter(appPref_DirExports) + tmpEnvFileName; if FileExists(ENVFilePath) then deletefile(ENVFilePath); envUP.Pack(ENVFilePath,''); //write the file here end; end; function TExportApprPortXML.ConvertForm(fXmlObj: TXMLDOM;frmNode: IXMLNode): Boolean; var frmID: Integer; srcF, mapF: String; pgNode: IXMLNode; pg,Pgs: Integer; frmType: FormType; begin frmId := frmNode.Attributes[tagFormID]; frmType := GetFormType(frmNode); Pgs := frmNode.ChildNodes[tagPages].Attributes[tagCount]; result := True; for pg := 0 to Pgs - 1 do begin if not result then exit; pgNode := frmNode.ChildNodes[tagPages].ChildNodes[pg]; if frmType = frmExtraComps then curExtraCompSet := pgNode.Attributes[tagCompsSet]; //get source srcF := pgNode.Text; if not FileExists(IncludeTrailingPathDelimiter(XMLSrcDir) + srcF) then raise Exception.CreateFmt(errCantfindSrcFile, [srcF]); //get map file mapF := GetMapFileName(frmID,pg + 1,curExtraCompSet); if not FileExists(IncludeTrailingPathDelimiter(mapsDir) + mapF) then begin //do not raise exception, just skip the form result := False; exit; end; if not WriteSpecAttributes(fXmlObj,IncludeTrailingPathDelimiter(mapsDir) + mapF) then raise Exception.CreateFmt(errWrongMapFile, [mapF]); if not WriteAirXML(fXMLobj,IncludeTrailingPathDelimiter(XMLSrcDir) + srcF, IncludeTrailingPathDelimiter(mapsDir) + mapF) then raise Exception.CreateFmt(errCantConvForm, [srcF]); result := True; curExtraCompSet := 0; end; end; function TExportApprPortXML.GetairForm(fmID: Integer): airFormRec; var frmList: TStringList; mapPath: String; recIndex: Integer; recStr: String; tabPos: integer; begin frmList := nil; result.frmName := ''; result.frmVersion := ''; mapPath := IncludeTrailingPathDelimiter(mapsDir) + formListFName; if not FileExists(mapPath) then exit; try frmList := TStringList.Create; frmList.Sorted := True; frmList.CaseSensitive := False; frmList.LoadFromFile(mapPath); frmList.Find(IntToStr(fmID),recIndex); if recIndex < frmList.Count then begin recStr := frmList.Strings[recIndex]; tabPos := Pos(tab,recStr); if (tabPos = 0) or (compareText(Copy(recStr,1,tabPos - 1),IntToStr(fmID)) <> 0) then exit; recStr := Copy(recStr,tabPos + 1,length(recStr)); tabPos := Pos(tab,recStr); if tabPos = 0 then exit; result.frmName := Copy(recStr,1,tabPos - 1); result.frmVersion := Copy(recStr,tabPos + 1,length(recStr)); end; finally if assigned(frmList) then frmList.Free; end; end; procedure TExportApprPortXML.WriteSignature(fXML: TXMLDOM; airsignType,clfSignType: String); var fl,nFiles: Integer; imgSigRec: ImgRec; imType: Integer; begin imgSigRec.path := ''; //do we have the signature nFiles := length(FilesToAdd); for fl := 0 to nFiles - 1 do if CompareText(clfSigntype,FilesToAdd[fl].key) = 0 then break; if fl = nFiles then exit; if not FileExists(FilesToAdd[fl].Path) then //it never happens exit; imgSigRec.path := FilesToAdd[fl].Path; if CompareText(ExtractFileExt(imgSigRec.path),jpgExt) <> 0 then exit; // it never happens .ClickForms save the signatures in JPG format. imgSigRec.imgFormat := jpegType; //find airSignType for imtype := 1 to airImgTypes do if CompareText(airImages[imType].key,airsignType) = 0 then break; if imType > airImgTypes then exit; imgsigRec.imgType := airImages[imType].key; imgSigRec.flDescr := airImages[imType].flDescr; imgSigRec.param := 0; WriteImage(imgSigRec,fXML); end; function TExportApprPortXML.GetSignatures(rtNode: IXMLNode): Boolean; var sign,nSigns: Integer; nd,nNodes: Integer; signNode: IXMLNode; flRec: fileRec; sgnPath: String; begin nNodes := rtNode.ChildNodes.Count; for nd := 0 to nNodes - 1 do if CompareText(rtNode.ChildNodes[nd].NodeName,tagSignatures) = 0 then break; if nd = nNodes then begin result := True; //it is OK, just no signatures exit; end; nSigns := rtNode.ChildNodes[nd].Attributes[tagCount]; if nSigns > 0 then //check Images map file if not FileExists(IncludeTrailingPathDelimiter(mapsDir) + imgMapFName) then begin raise Exception.CreateFmt(errCantFindMap, [imgMapFName]); result := False; end; for sign := 0 to nSigns - 1 do begin signNode := rtNode.ChildNodes[tagSignatures].ChildNodes[sign]; sgnPath := IncludeTrailingPathDelimiter(XMLSrcDir) + signNode.Text; if not FileExists(sgnPath) then raise Exception.CreateFmt(errCantFindSrcFile, [signNode.Text]); if CompareText(ExtractFileExt(sgnPath),jpgExt) <> 0 then if not ConvertToJpg(sgnPath) then begin raise Exception.CreateFmt(errCantConvToJpg, [sgnPath]); result := false; end; //add Images to File list flRec.fltype := ImageFile; flRec.Path := sgnPath; flRec.Descr := signNode.Attributes[tagSignatureType] + ' ' + strSignature; flRec.key := signNode.Attributes[tagSignatureType]; setLength(filesToAdd,length(filesToAdd) + 1); filesToAdd[length(filesToAdd) - 1] := flRec; end; result := True; end; function TExportApprPortXML.ConvertSketches(fXML:TXMLDOM;rtNode: IXMLNode): Boolean; var curNode,skNode: IXMLNode; nd,nNodes: Integer; sktch, nSketches: Integer; imType: aiReadyImageType; curImg: ImgRec; flRec: FileRec; begin nNodes := rtNode.ChildNodes.Count; for nd := 0 to nNodes - 1 do if CompareText(rtNode.ChildNodes[nd].NodeName,tagFloorplans) = 0 then break; if nd = nNodes then begin result := True; //it is OK, just no sketches, no sketch data file exit; end; curNode := rtNode.ChildNodes[nd]; //node Floorplans nNodes := curNode.ChildNodes.Count; for nd := 0 to nNodes - 1 do if CompareText(curNode.ChildNodes[nd].NodeName,tagSketches) = 0 then break; if (nNodes = 0) or (nd = nNodes) then begin result := True; //it is OK, just no sketches exit; end; curNode := curNode.ChildNodes[nd]; nSKetches := curNode.Attributes[tagCount]; if nSketches > 0 then //check Images map file if not FileExists(IncludeTrailingPathDelimiter(mapsDir) + imgMapFName) then raise Exception.CreateFmt(errCantFindMap, [imgMapFName]); for sktch := 0 to nSketches - 1 do begin if sktch >= maxSketches then break; skNode := curNode.ChildNodes[sktch]; curImg.path := IncludeTrailingPathDelimiter(XMLSrcDir) + skNode.Text; if not FileExists(curImg.path) then raise Exception.CreateFmt(errCantFindSrcFile, [skNode.Text]); if CompareText(ExtractFileExt(curImg.path),jpgExt) <> 0 then if not ConvertToJpg(curImg.Path) then raise Exception.CreateFmt(errCantConvToJpg,[curImg.path]); curImg.imgFormat := jpegType; imType := FLOORPLAN; GetImgFileInfo(imType,'', curImg); curImg.key := curImg.imgType; curImg.param := sktch + 1; if sktch > 0 then curImg.key := curImg.key + IntToStr(sktch + 1); WriteImage(curImg,fXML); //add Images to File list flRec.fltype := ImageFile; flRec.Path := curImg.path; flRec.Descr := curImg.flDescr; flRec.key := curImg.key; setLength(filesToAdd,length(filesToAdd) + 1); filesToAdd[length(filesToAdd) - 1] := flRec; end; result := True; end; function TExportApprPortXML.ConvertImages(fXML:TXMLDOM;rtNode: IXMLNode): Boolean; var img,nImgs: Integer; imgNode: IXMLNode; curImg: imgRec; imType: aiReadyImageType; flRec: fileRec; nd,nNodes: Integer; imgPos: Integer; clfPageType, clfImgType: String; begin nNodes := rtNode.ChildNodes.Count; for nd := 0 to nNodes - 1 do if CompareText(rtNode.ChildNodes[nd].NodeName,tagImages) = 0 then break; if nd = nNodes then begin result := True; //it is OK, just no images exit; end; nImgs := rtNode.ChildNodes[tagImages].Attributes[tagCount]; if nImgs > 0 then //check Images map file if not FileExists(IncludeTrailingPathDelimiter(mapsDir) + imgMapFName) then raise Exception.CreateFmt(errCantFindMap,[imgMapFName]); for img := 0 to nImgs - 1 do begin imgNode := rtNode.ChildNodes[tagImages].ChildNodes[img]; curImg.path := IncludeTrailingPathDelimiter(XMLSrcDir) + imgNode.Text; if not FileExists(curImg.path) then raise Exception.CreateFmt(errCantFindSrcFile,[imgNode.Text]); //AiReady recognizes only jpg Format if CompareText(ExtractFileExt(curImg.path),jpgExt) <> 0 then if not ConvertToJpg(curImg.path) then raise Exception.CreateFmt(errCantConvToJpg,[curImg.path]); curImg.imgFormat := jpegType; clfPageType := imgNode.Attributes[tagPageType]; clfImgType := imgNode.Attributes[tagImagetype]; imType := GetAirImgType(GetPageType(clfPageType), GetImageType(clfImgType), imgPos); if imType = Unknown then continue; curImg.param := 0; //default if imgPos > 0 then curImg.param := imgPos; GetImgFileInfo(imType,clfPageType,curImg); //curImg.descr := imgNode.Attributes[tagPageType]; curImg.descr1 := ''; curImg.descr2 := ''; curImg.descr3 := ''; if imType = LISTINGCOMPPHOTO then //AiReady Listing Photos do not have titles begin // we will add it in FitImgRec to the descr1 field if imgNode.HasAttribute(tagImgTextLine1) then curImg.descr2 := imgNode.Attributes[tagImgTextLine1]; if imgNode.HasAttribute(tagImgTextLine2) then curImg.descr3 := imgNode.Attributes[tagImgTextLine2]; end else begin if imgNode.HasAttribute(tagImgTextLine1) then curImg.descr1 := imgNode.Attributes[tagImgTextLine1]; if imgNode.HasAttribute(tagImgTextLine2) then curImg.descr2 := imgNode.Attributes[tagImgTextLine2]; end; if not FitImgRec(imType,curImg,imgNode) then continue; WriteImage(curImg,fXML); //add Images to File list flRec.fltype := ImageFile; flRec.Path := curImg.path; if CompareText(clfPageType,pgTypePageImage) = 0 then flRec.Descr := clfImgType else flRec.Descr := curImg.flDescr; flRec.key := curImg.key; setLength(filesToAdd,length(filesToAdd) + 1); filesToAdd[length(filesToAdd) - 1] := flRec; end; result := True; end; function TExportApprPortXML.ConvertComments(fXML:TXMLDOM;rtNode: IXMLNode): Boolean; var cmnt,nCmnts: Integer; nd,nNodes: Integer; cmntNode: IXMLNode; strm: TFileStream; buff: PChar; mapList: TStringList; rec: Integer; mapRec: addendMapRec; strValue: String; strXmlPath: String; root: Variant; begin buff := nil; root := fXml.RootElement; nNodes := rtNode.ChildNodes.Count; for nd := 0 to nNodes - 1 do begin if CompareText(rtNode.ChildNodes[nd].NodeName,tagComments) = 0 then break; end; if nd = nNodes then begin result := True; //it is OK, just no comments exit; end; nCmnts := rtNode.ChildNodes[nd].Attributes[tagCount]; if nCmnts > 0 then //check addendums map file if not FileExists(IncludeTrailingPathDelimiter(mapsDir) + addendaMapFName) then raise Exception.CreateFmt(errCantFindMap,[addendaMapFName]); mapList := TStringList.Create; try mapList.LoadFromFile(IncludeTrailingPathDelimiter(mapsDir) + addendaMapFName); for cmnt := 0 to nCmnts - 1 do begin cmntNode := rtNode.ChildNodes[nd].ChildNodes[cmnt]; if not FileExists(IncludeTrailingPathDelimiter(XMLSrcDir) + cmntNode.Text) then continue; strm := TFileStream.Create(IncludeTrailingPathDelimiter(XMLSrcDir) + cmntNode.Text,fmOpenRead); try GetMem(buff,strm.Size + 1); FillChar(buff^,strm.Size + 1,0); strm.ReadBuffer(buff^,strm.Size); for rec:= 0 to mapList.Count - 1 do begin mapRec := GetAddendMapRec(mapList[rec]); strValue := ''; strXmlPath := ''; if CompareText(mapRec.fldName,strAddendNum) = 0 then begin strValue := IntToStr(cmnt + 1); strXmlPath := mapRec.xmlPath1; end; if CompareText(mapRec.fldName,strAddendName) = 0 then begin strValue := strAdditComment + ' ' + IntToStr(cmnt+ 1); strXmlPath := mapRec.xmlPath1 + ':' + IntToStr(cmnt) + mapRec.xmlPath2; end; if CompareText(mapRec.fldName,strAddendValue) = 0 then begin strValue := String(buff); strXmlPath := mapRec.xmlPath1 + ':' + IntToStr(cmnt) + mapRec.xmlPath2; end; if length(strValue) > 0 then fXml.Write(root,strXmlPath,mapRec.attr,strValue); end; finally FreeMem(buff); strm.Free; end; end; result := True; finally mapList.Free; end; end; function TExportApprPortXML.GetFormType(frmNode: IXMLNode): FormType; var Page1Type: PageType; strPage1Type: String; begin strPage1Type := frmNode.ChildNodes[tagPages].ChildNodes[0].attributes[tagPageType]; page1Type := GetPageType(strPage1Type); case Page1Type of pgExtraComps,pgExtraListing,pgExtraRental: result := frmExtraComps; pgSketch: result := frmSketch; pgPlatMap,pgLocationMap,pgFloodMap, pgExhibit, pgMapListing,pgMapRental: result := frmMap; pgPhotosComps,pgPhotosListing,pgPhotosRental, pgPhotosSubject,pgPhotosSubjectExtra, pgPhotosUntitled: result := frmPhoto; pgComments: result := frmComment; else result := frmRegular; end; end; function TExportApprPortXML.GetFormUADVersion(frmNode: IXMLNode): String; begin if frmNode.HasAttribute(tagUADVersion) then Result := frmNode.Attributes[tagUADVersion] else Result := ''; end; function TExportApprPortXML.CreateAirXmlFileName(formName: String): String; var fName: String; begin fName := arPrefix + formName; while FileExists(IncludeTrailingPathDelimiter(XMLSrcDir) + fName + xmlExt) do fName := fName + '_'; result := fName + xmlExt; end; function TExportApprPortXML.WriteSpecAttributes(fXML: TXMLDOM; mFile: String): Boolean; var mapList: TStringList; rec: Integer; mpRec: MapRec; root: Variant; begin root := fXML.RootElement; mapList := TStringList.Create; try mapList.Sorted := True; mapList.LoadFromFile(mFile); result := True; for rec := 0 to mapList.Count -1 do begin mpRec := GetMapRec(MapList.Strings[rec]); if mpRec.clNo > 0 then break; if mpRec.clType = clRegular then continue; case mpRec.clType of clVendor: if (length(mpRec.xmlPath) > 0) and (length(strVendor) > 0) then fXML.Write(root,mpRec.xmlPath,mpRec.attr,strVendor); clVersion: if (length(mpRec.xmlPath) > 0) and (length(strVersion) > 0) then fXML.Write(root,mpRec.xmlPath,mpRec.attr,strVersion); clFormNum: if (length(mpRec.xmlPath) > 0) and (length(curForm) > 0) then fXML.Write(root,mpRec.xmlPath,mpRec.attr,curForm); clFormVersion: if (length(mpRec.xmlPath) > 0) and (length(curFormVersion) > 0) then fXML.Write(root,mpRec.xmlPath,mpRec.attr,curFormVersion); clDocID: ; clCompNum: if (length(mpRec.xmlPath) > 0) and (length(mpRec.param) > 0) then fXML.Write(root,mpRec.xmlPath,mpRec.attr,mpRec.param); clSeqNum: if (length(mpRec.xmlPath) > 0) and (length(mpRec.param) > 0) then fXML.Write(root,mpRec.xmlPath,mpRec.attr,mpRec.param); clAddAttrib: if (length(mpRec.xmlPath) > 0) and (length(mpRec.param) > 0) then fXML.Write(root,mpRec.xmlPath,mpRec.attr,mpRec.param); clPredefinedText: if (length(mpRec.xmlPath) > 0) and (length(mpRec.param) > 0) then fXML.Write(root,mpRec.xmlPath,mpRec.attr,mpRec.param); clSignature: WriteSignature(fXML,mpRec.param,mpRec.attr); clUADVersion: if (curFormUADVersion <> '') then fXML.Write(root,mpRec.xmlPath,mpRec.attr,curFormUADVersion); end; end; finally mapList.Clear; end; end; function TExportApprPortXML.WriteAirXML(fXML: TXMLDOM; srcF,mapF: String): Boolean; var srcList,MapList: TStringList; rec: Integer; srcRec: CellRecord; mpRec: MapRec; strValue,TmpStr,StreetNumber: String; root: Variant; rootMain: Variant; begin srcList := TStringList.Create; srcList.Sorted := True; //by cell # mapList := TStringList.Create; mapList.Sorted := true; root := fXML.RootElement; rootMain := fXmlMainForm.RootElement; StreetNumber :=''; try srcList.LoadFromFile(srcF); mapList.LoadFromFile(mapF); for rec := 0 to srcList.Count - 1 do begin srcRec := GetCellRec(srcList.Strings[rec]); if (srcRec.cellNo = 0) or (length(srcRec.cellText) = 0) then continue; mpRec := GetMapRecByCellno(mapList,srcRec.cellNo); if length(mpRec.xmlPath) = 0 then continue; case mpRec.clType of clCheckBox: if CompareText(Trim(srcRec.cellText),CheckboxMark) = 0 then fXml.Write(root,mpRec.xmlPath,mpRec.attr,strOn) else fXml.Write(root,mpRec.xmlPath,mpRec.attr,strOff); clAlternCheckBox: if CompareText(Trim(srcRec.cellText),CheckboxMark) = 0 then begin //### - what was the problem being solved?? // 102711 JWyatt Implement in version 7.5.8 // see if the path & its value already exist strValue := fXml.ReadValue(root,mpRec.xmlPath); if strValue = '' then begin // path & its value do not exist so set it if there's no attribute // otherwise see if we have it in the attribute if mpRec.attr = '' then strValue := mpRec.param else begin strValue := fXml.Read(root,mpRec.xmlPath,mpRec.attr); if strValue = '' then strValue := mpRec.param else strValue := strValue + ',' + mpRec.param; end; end else strValue := strValue + ',' + mpRec.param; fXml.Write(root,mpRec.xmlPath,mpRec.attr,strValue); end; clExtraCompComm: begin if curExtraCompSet > 0 then mpRec.xmlPath := mpRec.xmlPath + IntToStr(curExtraCompSet); fXML.Write(root,mpRec.xmlPath,mpRec.attr,srcRec.cellText); end; clCityStateZip: WriteCityStateZip(fXml,mapList,srcRec); clMerge: case StrToIntDef(mpRec.param,0) of 1: //the first cell strValue := srcRec.cellText; 2: //the middle cells strValue := strValue + ' ' + srcRec.cellText; 3: //the last cell begin strValue := strValue + ' ' + srcRec.cellText; fXML.Write(root,mpRec.xmlPath,mpRec.attr,strValue); end; 0: //must not happens fXML.Write(root,mpRec.xmlPath,mpRec.attr,strValue); end; clMoveToMainForm: fXmlMainForm.Write(rootMain,mpRec.xmlPath,mpRec.attr,srcRec.cellText); clRegular: begin //need to get the address street # for unitcitystatezip to use if pos('\ADDR\STREET',UpperCase(mpRec.xmlPath))>0 then begin TmpStr := srcRec.CellText; StreetNumber := popStr(TmpStr, SpaceDelim); end; fXML.Write(root,mpRec.xmlPath,mpRec.attr,srcRec.cellText); end; clUnitCityStateZip: //handle new cell type: unitcitystatezip WriteUnitCityStateZip(fXml,mapList,srcRec,StreetNumber); end; end; result := true; finally srcList.Clear; mapList.Clear; end; end; function TExportApprPortXML.GetAirImgType(pgType: PageType; imType: ImageType; var imgPos: Integer): AiReadyImagetype; begin result := GENERICPHOTO; imgPos := -1; case pgType of pgPhotosSubjectExtra: if curAddSubjPhoto < MaxAddSubjPhotos then result := SUBJECTADDITIONAL else result := ADDITIONALPHOTO; pgPhotosComps: result := COMPPHOTO; pgPhotosListing: if curListingPhoto < maxListingPhotos then result := LISTINGCOMPPHOTO else result := ADDITIONALPHOTO; pgPhotosRental, pgPhotosUntitled: result := ADDITIONALPHOTO; pgPlatMap: if curPlatMap < maxPlatMaps then result := PLATMAP else result := ADDITIONALMAP; pgLocationMap: if curLocMap < maxLocationMaps then result := LOCATIONMAP else result := ADDITIONALMAP; pgFloodMap: result := FLOODMAP; pgMapListing, pgMapRental, pgExhibit,pgMapOther: result := ADDITIONALMAP; pgSketch: result := FLOORPLAN; else case imType of imgSubjectFront: result := SUBJECTFRONTVIEW; imgSubjectRear: result := SUBJECTREARVIEW; imgSubjectStreet: result := SUBJECTSTREETVIEW; imgInspectPhoto1: begin result := INSPECTPHOTO; imgPos := 1; end; imgInspectPhoto2: begin result := INSPECTPHOTO; imgPos := 2; end; imgGeneric1: imgPos := 1; imgGeneric2: imgPos := 2; imgGeneric3: imgPos := 3; imgGeneric4: imgPos := 4; imgGeneric5: imgPos := 5; imgGeneric6: imgPos := 6; imgGeneric7: imgPos := 7; end; end; end; function TExportApprPortXML.FitImgRec(imType: aiReadyImagetype;var curImg: ImgRec;imgNode: IXMLNode): Boolean; var compsSet,imgLoc,compsNo :Integer; begin result := False; curImg.key := curImg.imgType; //default curImg.title := ''; case imType of SUBJECTADDITIONAL: begin inc(curAddSubjPhoto); if curAddSubjPhoto > maxAddSubjPhotos then exit; curImg.param := curAddSubjPhoto; curImg.Key := curImg.Key + IntToStr(curAddSubjPhoto); curImg.flDescr := curImg.flDescr + ' ' + IntTostr(curAddSubjPhoto); end; PLATMAP: begin inc(curPlatMap); if curPlatMap > maxPlatMaps then exit; curImg.param := curPlatMap; if curPlatMap > 1 then begin curImg.key := curImg.key + IntToStr(curPlatMap); curImg.flDescr := curImg.flDescr + ' ' + IntToStr(curPlatMap); end; end; LOCATIONMAP: begin inc(curLocMap); if curLocMap > maxLocationMaps then exit; curImg.param := curLocMap; if curLocMap > 1 then begin curImg.key := curImg.key + IntToStr(curLocMap); curImg.flDescr := curImg.flDescr + ' ' + IntToStr(curLocMap); end; end; COMPPHOTO: begin compsSet := imgNode.Attributes[tagCompsSet]; imgLoc := Ord(GetPhotoLocation(imgNode.Attributes[tagImageType])); if imgLoc < 1 then raise Exception.CreateFmt(errWrongSrcXML,['??']); //wrong error msg compsNo := (compsSet - 1) * 3 + imgLoc; if compsNo > maxComps then exit; curImg.param := compsNo; curImg.key := curImg.key + IntToStr(compsNo); curImg.flDescr := curImg.flDescr + ' ' + IntToStr(compsNo); end; LISTINGCOMPPHOTO: begin inc(curListingPhoto); if curListingPhoto > maxListingPhotos then exit; compsSet := imgNode.Attributes[tagCompsSet]; imgLoc := Ord(GetPhotoLocation(imgNode.Attributes[tagImageType])); if imgLoc < 1 then raise Exception.CreateFmt(errWrongSrcXML,['??']); //wrong error msg compsNo := (compsSet - 1) * 3 + imgLoc; curImg.param := compsNo; curImg.Key := curImg.Key + IntToStr(compsNo); curImg.flDescr := curImg.flDescr + ' ' + IntToStr(compsNo); curImg.descr1 := 'Comparable Listing # ' + IntToStr(compsNo); end; ADDITIONALPHOTO: begin inc(curAddPhoto); if curAddPhoto > maxAddPhotos then exit; curImg.param := curaddPhoto; curImg.key := curImg.key + IntToStr(curAddPhoto); curImg.flDescr := curImg.flDescr + ' ' + IntToStr(curaddPhoto); end; GENERICPHOTO: begin //we already defined param for generic photo curImg.key := curImg.key + IntToStr(curImg.param); curImg.flDescr := curImg.flDescr + ' ' + IntToStr(curImg.param); end; FLOODMAP,ADDITIONALMAP: begin inc(curAddMap); if curAddMap > maxAddMaps then exit; curImg.param := curAddMap; curImg.key := curImg.key + IntToStr(curaddMap); curImg.flDescr := curImg.flDescr + ' ' + InttoStr(curAddMap); end; end; result := True; end; procedure TExportApprPortXML.WriteImage(img: imgRec;fXML: TXMLDOM); var mapList: TStringList; rec,indx: Integer; mpRec: ImgMapRec; root: Variant; xmlPath: String; begin mapList := TStringList.Create; mapList.Sorted := True; try mapList.LoadFromFile(IncludeTrailingPathDelimiter(mapsDir) + imgMapFName); mapList.Find(img.imgType,indx); mpRec := GetImgMapRec(mapList[indx]); if (indx >= mapList.Count) or (CompareText(img.imgType,mprec.imgType) <> 0) then exit; //did not find the image type root := fXML.RootElement; for rec := indx to mapList.Count - 1 do begin mpRec := GetImgMapRec(mapList[rec]); if CompareText(img.imgType,mpRec.imgType) <> 0 then break; if img.param > 0 then xmlPath := Format(mpRec.xmlPath,[img.param - 1]) else xmlPath := mpRec.xmlPath; if (length(mpRec.fldType) = 0) or (length(mpRec.xmlPath) = 0) then continue; //write XML if CompareText(mpRec.fldType,fldImgFileName) = 0 then fXML.Write(root,xmlPath,mpRec.attr,ExtractFileName(img.path)); if CompareText(mpRec.fldType,fldImgFileType) = 0 then fXML.Write(root,xmlPath,mpRec.attr,img.imgFormat); if CompareText(mpRec.fldType,fldImgNum) = 0 then fXML.Write(root,xmlPath,mpRec.attr,IntToStr(img.param)); if CompareText(mpRec.fldType,fldImgCompNum) = 0 then fXML.Write(root,xmlPath,mpRec.attr,IntToStr(img.param)); if CompareText(mpRec.fldType,fldImgDescr1) = 0 then if length(img.descr1) > 0 then fXML.Write(root,xmlPath,mpRec.attr,img.descr1); if CompareText(mpRec.fldType,fldImgDescrNum1) = 0 then if length(img.descr1) > 0 then fXML.Write(root,xmlPath,mpRec.attr,'1'); if CompareText(mpRec.fldType,fldImgDescr2) = 0 then if length(img.descr2) > 0 then fXML.Write(root,xmlPath,mpRec.attr,img.descr2); if CompareText(mpRec.fldType,fldImgDescrNum2) = 0 then if length(img.descr2) > 0 then fXML.Write(root,xmlPath,mpRec.attr,'2'); if CompareText(mpRec.fldType,fldImgDescr3) = 0 then if length(img.descr3) > 0 then fXML.Write(root,xmlPath,mpRec.attr,img.descr3); if CompareText(mpRec.fldType,fldImgDescrNum3) = 0 then if length(img.descr3) > 0 then fXML.Write(root,xmlPath,mpRec.attr,'3'); {if CompareText(mpRec.fldType,fldImgName) = 0 then if length(img.descr) > 0 then //for now the same as description fXML.Write(root,mpRec.xmlPath,mpRec.attr,img.descr); if CompareText(mpRec.fldType,fldImgTitle) = 0 then if length(img.descr) > 0 then //for now the same as description fXML.Write(root,mpRec.xmlPath,mpRec.attr,img.descr); } end; finally mapList.Clear; end; end; procedure TExportApprPortXML.WriteCityStateZip(fXML: TXMLDOM;mpList: TStringList; clRec: CellRecord); var subStrs: SubStrArr; str,nStrs: Integer; indx: Integer; mpRec: MapRec; strValue: String; root: Variant; begin subStrs := nil; if length(clRec.cellText) = 0 then exit; mpList.Find(IntToStr(clRec.cellNo),indx); if indx >= mpList.Count then //never happens exit; root := fXML.RootElement; try subStrs := ParseCityStateZip(clRec.cellText); while indx < mpList.Count do begin mpRec := GetMapRec(mpList[indx]); inc(indx); if mpRec.clNo <> clRec.cellNo then break; //that is it strValue := ''; if CompareText(mpRec.param,strCity) = 0 then strValue := subStrs[0]; if CompareText(mpRec.param,strState) = 0 then strValue := subStrs[1]; if CompareText(mpRec.param,strZip) = 0 then strValue := subStrs[2]; if length(strValue) > 0 then fXml.Write(root,mpRec.xmlPath,mpRec.attr,strValue); end; finally nStrs := Length(subStrs); for str := 0 to nStrs - 1 do SetLength(subStrs[str],0); subStrs := nil; end; end; procedure TExportApprPortXML.WriteUnitCityStateZip(fXML: TXMLDOM;mpList: TStringList; clRec: CellRecord; StreetNumber:String); var subStrs: SubStrArr; str,nStrs: Integer; indx: Integer; mpRec: MapRec; strValue: String; root: Variant; begin subStrs := nil; if length(clRec.cellText) = 0 then exit; mpList.Find(IntToStr(clRec.cellNo),indx); if indx >= mpList.Count then //never happens exit; root := fXML.RootElement; try subStrs := ParseUnitCityStateZip(clRec.cellText,StreetNumber); while indx < mpList.Count do begin mpRec := GetMapRec(mpList[indx]); inc(indx); if mpRec.clNo <> clRec.cellNo then break; //that is it strValue := ''; if CompareText(mpRec.param,strUnit) = 0 then strValue := subStrs[0]; if CompareText(mpRec.param,strCity) = 0 then strValue := subStrs[1]; if CompareText(mpRec.param,strState) = 0 then strValue := subStrs[2]; if CompareText(mpRec.param,strZip) = 0 then strValue := subStrs[3]; if length(strValue) > 0 then fXml.Write(root,mpRec.xmlPath,mpRec.attr,strValue); end; finally nStrs := Length(subStrs); for str := 0 to nStrs - 1 do SetLength(subStrs[str],0); subStrs := nil; end; end; function TExportApprPortXML.GetXML(curForm: String; var bNew: Boolean): TXMLDOM; var frmPos: Integer; rec,nRec: Integer; baseForm: String; begin result := nil; bNew := False; frmPos := Pos(strMoveTo,curForm); if frmPos = 1 then //may be it is additional form begin baseForm := Copy(curForm,length(strMoveTo) + 1,length(curForm)); if CompareText(baseForm,strMainForm) = 0 then result := fXmlMainForm // it is part of the main form else begin nRec := length(filesToAdd); for rec := 0 to nRec - 1 do if CompareText(baseForm,filesToAdd[rec].frmName) = 0 then break; if rec < nRec then // it is the part of some already added form result := filesToAdd[rec].xmlObj; end; end; if not assigned(result) then //add the new form begin result := TXMLDOM.Create(Screen.ActiveForm); result.NewXML(TagformInfo); bNew := True; end; end; function TExportApprPortXML.ConvertGeocodes(fXML:TXMLDOM;rtNode: IXMLNode): Boolean; var nodeGeocodes: IXMLNode; recIndex, mapIndex: Integer; propType: String; compNo: Integer; geocodeMap: TStringList; geocodeMapPath: string; geocodeRec: geocodeMapRec; fldValue, xPath: String; begin result := true; //some reports do not have Geocodes. It is OK, not error if rtNode.HasChildNodes then nodeGeocodes := rtNode.ChildNodes.FindNode(tagGeocodes) else exit; if not assigned(nodeGeocodes) then exit; if not nodeGeocodes.HasChildNodes then exit; geocodeMapPath := IncludeTrailingPathDelimiter(appPref_DirAppraisalWorld) + 'AIReady\Maps\' + geocodeMapFileName; if not FileExists(geocodeMapPath) then exit; geocodeMap := TStringList.Create; try geocodeMap.Sorted := true; geocodeMap.LoadFromFile(geocodeMapPath); for recIndex := 0 to nodeGeocodes.ChildNodes.Count - 1 do with nodeGeocodes.ChildNodes[recIndex] do begin if not HasAttribute(tagCompType) then continue; propType := ParsePropType(Attributes[tagCompType],compNo); geocodeMap.Find(propType,mapIndex); if mapIndex < geocodeMap.Count then for mapIndex := mapIndex to geocodeMap.Count - 1 do begin geocodeRec := getGeocodeMapRec(geoCodeMap[mapIndex]); if CompareText(propType,geocodeRec.propType) <> 0 then break; if length(geocodeRec.xPath) = 0 then exit; if not assigned(childNodes.FindNode(geocodeRec.field)) then continue; fldValue := ChildValues[geocodeRec.field]; xPath := format(geocodeRec.xPath,[compNo - 1]); fXML.Write(fXML.RootElement,xPath,'',fldValue); end; end; finally geocodeMap.Free; end; end; procedure TExportApprPortXML.AddMismoXml(envUP: TPackage); var fPath: String; xmlDoc: TXMLDocument; xmlNode: IXMLNode; mismoVer, reportType: String; params: String; begin mismoVer := ''; reportType := ''; fPath := FMismoXMLPath; if not FileExists(fPath) then exit; xmlDoc := TXMLDocument.Create(application); xmlDoc.DOMVendor := GetDomVendor('MSXML'); try xmldoc.LoadFromFile(fPath); xmlNode := xmlDoc.DocumentElement; if xmlNode.HasAttribute(fldNameMismoVers) then mismoVer := xmlNode.Attributes[fldNameMismoVers]; reportType := 'MISMO XML';//mainForm + ' Form'; params := fldNameType + '=' + fldValeType + #13#10 + ' ' + fldNameDocType + '=' + fldValueDoctype + #13#10 + fldNameMismoVers + '=' + mismoVer; envUP.AddFile(fPath,reporttype,params); except end; end; function GetCellType(strCellType: String): CellType; begin result := clRegular; if CompareText(strClCheckBox, strCellType) = 0 then result := clCheckBox; if CompareText(strclAlternCheckBox, strCellType) = 0 then result := clAlternCheckBox; if CompareText(strClFullAddress, strCellType) = 0 then result := clFullAddress; if CompareText(strClCityStateZip, strCellType) = 0 then result := clCityStateZip; if CompareText(strClFormNum, strCellType) = 0 then result := clFormNum; if CompareText(strClFormVersion, strCellType) = 0 then result := clFormVersion; if CompareText(strClVendor, strCellType) = 0 then result := clVendor; if CompareText(strClVersion, strCellType) = 0 then result := clVersion; if CompareText(strClDocID, strCellType) = 0 then result := clDocID; if CompareText(strClCompNum, strCellType) = 0 then result := clCompNum; if CompareText(strClExtraCompComm, strCellType) = 0 then result := clExtraCompComm; if CompareText(strClMerge, strCellType) = 0 then result := clMerge; if CompareText(strClAddAttrib, strCellType) = 0 then result := clAddAttrib; if CompareText(strClMoveToMainForm, strCellType) = 0 then result := clMoveToMainForm; if CompareText(strClSignature, strCellType) = 0 then result := clSignature; if CompareText(strClUADVersion, strCellType) = 0 then result := clUADVersion; if CompareText(strClUnitCityStateZip, strCellType) = 0 then result := clUnitCityStateZip; if CompareText(strSeqNum, strCellType) = 0 then result := clSeqNum; if CompareText(strClPredefinedText, strCellType) = 0 then result := clPredefinedText; end; function GetPageType(strPageType: String): PageType; begin result := pgRegular; if CompareText(pgTypeExtraTableOfContent,strPageType) = 0 then result := pgExtraTableOfContent; if CompareText(pgTypeExtraComps,strPageType) = 0 then result := pgExtraComps; if CompareText(pgTypeExtraListing,strPageType) = 0 then result := pgExtraListing; if CompareText(pgTypeExtraRental,strPageType) = 0 then result := pgExtraRental; if CompareText(pgTypeSketch,strPageType) = 0 then result := pgSketch; if CompareText(pgTypePlatMap,strPageType) = 0 then result := pgPlatMap; if CompareText(pgTypeLocationMap,strPageType) = 0 then result := pgLocationMap; if CompareText(pgTypeFloodMap,strPageType) = 0 then result := pgFloodMap; if (CompareText(pgTypeExhibit,strPageType) = 0) or (CompareText(pgTypePageImage, strPageType) = 0) then result := pgExhibit; if CompareText(pgTypePhotosComps,strPageType) = 0 then result := pgPhotosComps; if CompareText(pgTypePhotosListing,strPageType) = 0 then result := pgPhotosListing; if CompareText(pgTypePhotosRental,strPageType) = 0 then result := pgPhotosRental; if CompareText(pgTypePhotosSubject,strPageType) = 0 then result := pgPhotosSubject; if CompareText(pgTypePhotosSubjectExtra,strPageType) = 0 then result := pgPhotosSubjectExtra; if CompareText(pgTypeMapListing,strPageType) = 0 then result := pgMapListing; if CompareText(pgTypeMapRental,strPageType) = 0 then result := pgMapRental; if CompareText(pgTypePhotosUntitled,strPageType) = 0 then result := pgPhotosUntitled; if CompareText(pgTypeComments,strPageType) = 0 then result := pgComments; if CompareText(pgTypeMapOther,strPageType) = 0 then result := pgMapOther; end; function GetImageType(strImageType: String): ImageType; begin result := imgGeneral; if CompareText(imgTypeSubjectFront,strImageType) = 0 then result := imgSubjectFront; if CompareText(imgTypeSubjectRear,strImageType) = 0 then result := imgSubjectRear; if CompareText(imgTypeSubjectStreet,strImageType) = 0 then result := imgSubjectStreet; if CompareText(imgTypePhotoTop,strImageType) = 0 then result := imgPhotoTop; if CompareText(imgTypePhotoMiddle,strImageType) = 0 then result := imgPhotoMiddle; if CompareText(imgTypePhotoBottom,strImageType) = 0 then result := imgPhotoBottom; if CompareText(imgTypeMap,strImageType) = 0 then result := imgMap; if CompareText(imgTypeMetafile,strImageType) = 0 then result := imgMetafile; if CompareText(imgTypeGeneric1,strImageType) = 0 then result := imgGeneric1; if CompareText(imgTypeGeneric2,strImageType) = 0 then result := imgGeneric2; if CompareText(imgTypeGeneric3,strImageType) = 0 then result := imgGeneric3; if CompareText(imgTypeGeneric4,strImageType) = 0 then result := imgGeneric4; if CompareText(imgTypeGeneric5,strImageType) = 0 then result := imgGeneric5; if CompareText(imgTypeGeneric6,strImageType) = 0 then result := imgGeneric6; if CompareText(imgTypeGeneric7,strImageType) = 0 then result := imgGeneric7; if CompareText(imgTypeInspectPhoto1,strImageType) = 0 then result := imgInspectPhoto1; if CompareText(imgTypeInspectPhoto2,strImageType) = 0 then result := imgInspectPhoto2; end; function GetMapFileName(fID, pg: Integer; cmpSet: Integer = 0): String; var flName: String; begin flName := Format(arPrefix + '%4d%d',[fID,pg]); flName := StringReplace(flName,space,zero,[rfReplaceAll]); if cmpSet > 0 then flName := flName + '_' + IntToStr(cmpSet); result := flName + textFileExt; end; function GetMapRecByCellNo(mpList: TStringList;cl: Integer): MapRec; var mpRec: MapRec; indx: Integer; begin result.xmlPath := ''; result.clNo := 0; result.param := ''; result.clType := clRegular; result.attr := ''; mpList.Find(IntToStr(cl),indx); if indx < mpList.Count then mpRec := GetMapRec(MpList.Strings[indx]); if mpRec.clNo = cl then result := mpRec; end; function GetMapRec(mapStr: String): MapRec; var curStr: String; tabPos: Integer; begin result.xmlPath := ''; result.clNo := 0; result.param := ''; result.clType := clRegular; result.attr := ''; curStr := mapStr; tabPos := Pos(tab,curStr); if tabPos = 0 then exit; result.clNo := StrToIntDef(Copy(curStr,1,tabPos - 1),0); curStr := Copy(curStr,tabPos + 1,length(curStr)); tabPos := Pos(tab,curStr); if tabPos = 0 then exit; result.clType := GetCellType(Copy(curStr,1,tabPos - 1)); curStr := Copy(curStr,tabPos + 1,length(curStr)); tabPos := Pos(tab,curStr); if tabPos = 0 then exit; result.param := Copy(curStr,1,tabPos - 1); curStr := Copy(curStr,tabPos + 1,length(curStr)); tabPos := Pos(tab,curStr); if tabPos = 0 then exit; result.attr := Copy(curStr,1,tabPos - 1); curStr := Copy(curStr,tabPos + 1,length(curStr)); result.xmlPath := curStr; end; function GetCellRec(srcRec: String): cellRecord; var curStr: String; delimPos: Integer; begin curStr := srcRec; result.cellNo := 0; result.cellID := 0; result.cellText := ''; delimPos := Pos(tab,curStr); if delimPos = 0 then exit; result.cellNo := StrToIntDef(Copy(curStr,1,delimPos - 1),0); curStr := Copy(curStr,delimPos + 1,length(curStr)); delimPos := Pos(tab,curStr); if delimPos = 0 then exit; result.cellID := StrToIntDef(Copy(curStr,1,delimPos - 1),0); curStr := Copy(curStr,delimPos + 1,length(curStr)); delimPos := Pos(tab,curStr); if delimPos = 0 then exit; if CompareText(dataTypeFile,Copy(curStr,1,delimPos - 1)) = 0 then result.dtType := FileName else result.dtType := Text; curStr := Copy(curStr,delimPos + 1,length(curStr)); result.cellText := StringReplace(curStr,CRReplacement,CR,[rfReplaceAll]); end; procedure GetImgFileInfo(tp: AiReadyImageType; clfPageType: String; var curImg: imgRec); var rec: Integer; begin curImg.imgType := ''; curImg.flDescr:= ''; for rec := 1 to airImgTypes do if AirImages[rec].imgType = tp then begin curImg.imgType := AirImages[rec].key; if tp = GENERICPHOTO then curImg.flDescr := clfPageType + ' ' + AirImages[rec].flDescr else curImg.flDescr := AirImages[rec].flDescr; break; end; end; function GetPhotoLocation(strPhotoLocation: String): PhotoLocation; begin result := locUnknown; if CompareText(imgTypePhotoTop,strPhotoLocation) = 0 then result := locPhotoTop; if CompareText(imgTypePhotoMiddle,strPhotoLocation) = 0 then result := locPhotoMiddle; if CompareText(imgTypePhotoBottom,strPhotoLocation) = 0 then result := locPhotoBottom; end; function GetImgMapRec(imgMapStr: String): imgMapRec; var curStr: String; tabPos: Integer; begin curStr := imgMapStr; result.imgType := ''; result.fldType := ''; result.param := 0; result.attr := ''; result.xmlPath := ''; tabPos := Pos(tab,curStr); if tabPos = 0 then exit; result.imgType := Copy(curStr,1,tabPos - 1); curStr := Copy(curStr,tabPos + 1,length(curStr)); tabPos := Pos(tab,curStr); if tabPos = 0 then exit; result.fldType := Copy(curStr,1,tabPos - 1); curStr := Copy(curStr,tabPos + 1,length(curStr)); tabPos := Pos(tab,curStr); if tabPos = 0 then exit; result.param := StrToIntDef(Copy(curStr,1,tabPos - 1),0); curStr := Copy(curStr,tabPos + 1,length(curStr)); tabPos := Pos(tab,curStr); if tabPos = 0 then exit; result.attr := Copy(curStr,1,tabPos - 1); curStr := Copy(curStr,tabPos + 1,length(curStr)); result.xmlPath := curStr; end; procedure WriteGeneralFields(fXml: TXMLDOM); var strValue: String; root: Variant; begin root := fXml.RootElement; //case No for ADDENDUMS strValue := fXml.Read(root,pathRoot,tagCaseNo); if (length(strValue) > 0) and assigned(fXml.GetNodeX(root,pathAddendums)) then fXml.Write(root,pathAddendums,tagCaseNo,strValue); end; function ParseCityStateZip(srcStr: String): subStrArr; var delimPos: Integer; curStr: String; begin setLength(result,3); curStr := srcStr; //city delimPos := Pos(commaDelim,curStr); if delimPos = 0 then begin result[0] := curStr; exit; end else begin result[0] := copy(curStr,1,delimPos - 1); curStr := TrimLeft(Copy(curStr,delimPos + 1, length(curStr))); //###JB - Let figure out a better way. 090211 JWyatt Add check for 2nd comma which indicates that the address // is formatted in UAD style: unit,city,state,zip. In this case we need // to skip past the unit number to capture the city, state & zip. delimPos := Pos(commaDelim,curStr); if delimPos > 0 then begin result[0] := copy(curStr,1,delimPos - 1); curStr := TrimLeft(Copy(curStr,delimPos + 1, length(curStr))); end; end; //state delimPos := Pos(SpaceDelim,curStr); if delimPos = 0 then begin result[1] := curStr; exit; end else begin result[1] := copy(curStr,1,delimPos - 1); curStr := TrimLeft(Copy(curStr,delimPos + 1, length(curStr))); end; //zip result[2] := curStr; end; function GetAddendMapRec(addMapRec: String): addendMapRec; var curStr: String; tabPos: Integer; begin curStr := addMapRec; result.fldName := ''; result.attr := ''; result.xmlPath1 := ''; result.xmlPath2 := ''; tabPos := Pos(tab,curStr); if tabPos = 0 then exit; result.fldName := Copy(curStr,1,tabPos - 1); curStr := Copy(curStr,tabPos + 1,length(curStr)); tabPos := Pos(tab,curStr); if tabPos = 0 then exit; result.attr := Copy(curStr,1,tabPos - 1); curStr := Copy(curStr,tabPos + 1,length(curStr)); tabPos := Pos(tab,curStr); if tabPos = 0 then exit; result.xmlPath1 := Copy(curStr,1,tabPos - 1); curStr := Copy(curStr,tabPos + 1,length(curStr)); result.xmlPath2 := curStr; end; function GetMainFormID(ApprWorldDir: String; frmStr: String): Integer; function GetMainFormRecord(formStr: String): recMainForm; var delimPos: Integer; begin result.name := ''; delimPos := Pos(tab,formStr); if delimPos = 0 then exit; result.id := StrToIntDef(Copy(formStr,1,delimPos - 1),0); result.name := Copy(formStr,delimPos + 1,length(formStr)); end; var mainFrm: Integer; nMainForms: Integer; mainFrmList: TStringList; mainFrmListPath: String; frmRec: recMainForm; begin result := 0; mainFrmListPath := IncludeTrailingPathDelimiter(ApprWorldDir) + ClFMainFormList; if not FileExists(mainFrmListPath) then exit; mainFrmList := TStringList.Create; try mainFrmList.Sorted := False; //keep the original order mainFrmList.LoadFromFile(mainFrmListPath); nMainForms := mainFrmList.Count; for mainFrm := 0 to nMainForms - 1 do begin frmRec := GetMainFormRecord(mainFrmList.Strings[mainFrm]); if compareText(frmStr,frmRec.name) = 0 then begin result := frmRec.id; break; end; end; finally mainFrmList.Free; end; end; function ParseUnitCityStateZip(srcStr, StreetNumber: String): subStrArr; const spaceDelim = ' '; var curStr,aStr,aUnitNumber: String; isUnit: Boolean; idx : Integer; begin setLength(result,length(srcStr)); curStr := srcStr; idx := pos(commaDelim, curStr); if idx > 0 then begin aStr := copy(curStr, idx+1, length(curStr)); isUnit := pos(commaDelim, aStr) > 0; end else //we only have unit number begin result[0] := curStr; exit; end; if isUnit then begin //it's unit,city,state zip aUnitNumber := popStr(curStr, commaDelim); //unit # result[1] := popStr(curStr, commaDelim); //City result[2] := copy(Trim(curStr),1, 2); //state, only need 2 chars for state result[3] := copy(Trim(curStr),4,length(curStr)); //the rest is zip //For UnitNumber, we need to write out: UnitNumber, City, State zip result[0] := Format('%s, %s, %s %s',[aUnitNumber, result[1], result[2],result[3]]); end else //only city,state and zip begin aUnitNumber := StreetNumber; result[1] := popStr(curStr, commaDelim); //City result[2] := copy(Trim(curStr),1, 2); //state, only need 2 chars for state result[3] := copy(Trim(curStr),4,length(curStr)); //the rest is zip //For UnitNumber, we need to write out: UnitNumber, City, State zip result[0] := Format('%s, %s, %s %s',[aUnitNumber, result[1], result[2],result[3]]); end; end; function ParsePropType(clfPropType: string; var compNo: Integer): string; var lastCharPos: Integer; begin result := ''; compNo := 0; if length(clfPropType) = 0 then exit; lastCharPos := length(clfPropType); while lastCharPos > 0 do if isDigitOnly(clfPropType[lastCharPos]) then dec(lastCharPos) else break; if lastCharPos = 0 then exit; result := copy(clfPropType,1,lastCharPos); if lastCharPos < length(clfPropType) then compNo := StrToIntDef(copy(clfPropType,lastCharPos + 1, length(clfPropType) - lastCharPos),0); end; function GetGeocodeMapRec(srcRec: String): geocodeMapRec; const delim = #09; //tab var startPos, endPos, len: Integer; begin with result do begin propType := ''; field := ''; xPath := ''; len := length(srcRec); startPos := 1; endPos := Pos(delim,srcRec) -1; if endPos = 0 then exit; propType := Trim(Copy(srcRec,startPos, endPos - startPos + 1)); startPos := endPos + 2; if StartPos >= len then exit; endPos := PosEx(delim,srcRec, startPos) - 1; if endPos = startPos then exit; field := Trim(Copy(srcRec,startPos, endPos - startPos + 1)); startPos := endPos + 2; if startPos >= len then exit; xPath := Trim(copy(srcRec,startPos,len - startPos + 1)); end; end; end.
unit FinkOkWsTimbrado; // ************************************************************************ // // The types declared in this file were generated from data read from the // WSDL File described below: // WSDL : http://demo-facturacion.finkok.com/servicios/soap/stamp.wsdl // Encoding : UTF-8 // Version : 1.0 // (11/25/2013 1:07:55 PM - 1.33.2.5) // ************************************************************************ // // ************************************************************************ // // The types declared in this file were generated from data read from the // WSDL File described below: // WSDL : http://demo-facturacion.finkok.com/servicios/soap/cancel.wsdl // Encoding : UTF-8 // Version : 1.0 // (11/25/2013 1:11:58 PM - 1.33.2.5) // ************************************************************************ // // ************************************************************************ // // The types declared in this file were generated from data read from the // WSDL File described below: // WSDL : http://demo-facturacion.finkok.com/servicios/soap/registration.wsdl // Encoding : UTF-8 // Version : 1.0 // (11/26/2013 10:04:30 AM - 1.33.2.5) // ************************************************************************ // interface uses InvokeRegistry, SOAPHTTPClient, Types, XSBuiltIns; type // ************************************************************************ // // The following types, referred to in the WSDL document are not being represented // in this file. They are either aliases[@] of other types represented or were referred // to but never[!] declared in the document. The types from the latter category // typically map to predefined/known XML or Borland types; however, they could also // indicate incorrect WSDL documents that failed to declare or import a schema type. // ************************************************************************ // // !:string - "http://www.w3.org/2001/XMLSchema" // !:base64Binary - "http://www.w3.org/2001/XMLSchema" /// usados para timbrar QueryPendingResult = class; { "apps.services.soap.core.views" } //timbrar y cancelar Incidencia = class; { "apps.services.soap.core.views" } TFinkOkRespuestaTimbrado = class; { "apps.services.soap.core.views" } // usados para cancelar UUIDS = class; { "apps.services.soap.core.views" } Folio = class; { "apps.services.soap.core.views" } CancelaCFDResult = class; { "apps.services.soap.core.views" } ReceiptResult = class; { "apps.services.soap.core.views" } // usados para registrar nuevo rfc IFinkOkRespuestaRegistro = class; { "apps.services.soap.core.views" } stringArray = array of WideString; { "http://facturacion.finkok.com/cancellation" } // ************************************************************************ // // Namespace : apps.services.soap.core.views // ************************************************************************ // QueryPendingResult = class(TRemotable) private Fstatus: WideString; Fxml: WideString; Fuuid: WideString; Fuuid_status: WideString; Fnext_attempt: WideString; Fattempts: WideString; Ferror: WideString; Fdate: WideString; published property status: WideString read Fstatus write Fstatus; property xml: WideString read Fxml write Fxml; property uuid: WideString read Fuuid write Fuuid; property uuid_status: WideString read Fuuid_status write Fuuid_status; property next_attempt: WideString read Fnext_attempt write Fnext_attempt; property attempts: WideString read Fattempts write Fattempts; property error: WideString read Ferror write Ferror; property date: WideString read Fdate write Fdate; end; // ************************************************************************ // // Namespace : apps.services.soap.core.views // ************************************************************************ // Incidencia = class(TRemotable) private FIdIncidencia: WideString; FUuid: WideString; FCodigoError: WideString; FWorkProcessId: WideString; FMensajeIncidencia: WideString; FRfcEmisor: WideString; FNoCertificadoPac: WideString; FFechaRegistro: WideString; published property IdIncidencia: WideString read FIdIncidencia write FIdIncidencia; property Uuid: WideString read FUuid write FUuid; property CodigoError: WideString read FCodigoError write FCodigoError; property WorkProcessId: WideString read FWorkProcessId write FWorkProcessId; property MensajeIncidencia: WideString read FMensajeIncidencia write FMensajeIncidencia; property RfcEmisor: WideString read FRfcEmisor write FRfcEmisor; property NoCertificadoPac: WideString read FNoCertificadoPac write FNoCertificadoPac; property FechaRegistro: WideString read FFechaRegistro write FFechaRegistro; end; IncidenciaArray = array of Incidencia; { "apps.services.soap.core.views" } // ************************************************************************ // // Namespace : apps.services.soap.core.views // ************************************************************************ // TFinkOkRespuestaTimbrado = class(TRemotable) private Fxml: WideString; FUUID: WideString; Ffaultstring: WideString; FFecha: WideString; FCodEstatus: WideString; Ffaultcode: WideString; FSatSeal: WideString; FIncidencias: IncidenciaArray; FNoCertificadoSAT: WideString; public destructor Destroy; override; published property xml: WideString read Fxml write Fxml; property UUID: WideString read FUUID write FUUID; property faultstring: WideString read Ffaultstring write Ffaultstring; property Fecha: WideString read FFecha write FFecha; property CodEstatus: WideString read FCodEstatus write FCodEstatus; property faultcode: WideString read Ffaultcode write Ffaultcode; property SatSeal: WideString read FSatSeal write FSatSeal; property Incidencias: IncidenciaArray read FIncidencias write FIncidencias; property NoCertificadoSAT: WideString read FNoCertificadoSAT write FNoCertificadoSAT; end; // ************************************************************************ // // Namespace : apps.services.soap.core.views // ************************************************************************ // UUIDS = class(TRemotable) private Fuuids: stringArray; // constructor Create; overload; published property uuids: stringArray read Fuuids write Fuuids; end; // ************************************************************************ // // Namespace : apps.services.soap.core.views // ************************************************************************ // Folio = class(TRemotable) private FEstatusUUID: WideString; FUUID: WideString; published property EstatusUUID: WideString read FEstatusUUID write FEstatusUUID; property UUID: WideString read FUUID write FUUID; end; FolioArray = array of Folio; { "apps.services.soap.core.views" } // ************************************************************************ // // Namespace : apps.services.soap.core.views // ************************************************************************ // CancelaCFDResult = class(TRemotable) private FFolios: FolioArray; FAcuse: WideString; FFecha: WideString; FRfcEmisor: WideString; FCodEstatus: WideString; public destructor Destroy; override; published property Folios: FolioArray read FFolios write FFolios; property Acuse: WideString read FAcuse write FAcuse; property Fecha: WideString read FFecha write FFecha; property RfcEmisor: WideString read FRfcEmisor write FRfcEmisor; property CodEstatus: WideString read FCodEstatus write FCodEstatus; end; // ************************************************************************ // // Namespace : apps.services.soap.core.views // ************************************************************************ // ReceiptResult = class(TRemotable) private Fuuid: WideString; Fsuccess: Boolean; Freceipt: WideString; Ftaxpayer_id: WideString; Ferror: WideString; Fdate: WideString; published property uuid: WideString read Fuuid write Fuuid; property success: Boolean read Fsuccess write Fsuccess; property receipt: WideString read Freceipt write Freceipt; property taxpayer_id: WideString read Ftaxpayer_id write Ftaxpayer_id; property error: WideString read Ferror write Ferror; property date: WideString read Fdate write Fdate; end; // ************************************************************************ // // Namespace : apps.services.soap.core.views // ************************************************************************ // IFinkOkRespuestaRegistro = class(TRemotable) private Fmessage: WideString; Fsuccess: Boolean; published property message: WideString read Fmessage write Fmessage; property success: Boolean read Fsuccess write Fsuccess; end; // ************************************************************************ // // Namespace : http://facturacion.finkok.com/stamp // soapAction: %operationName% // transport : http://schemas.xmlsoap.org/soap/http // style : document // binding : Application // service : StampSOAP // port : Application // URL : http://demo-facturacion.finkok.com/servicios/soap/stamp // ************************************************************************ // IFinkOkServicioTimbrado = interface(IInvokable) ['{0AA07360-97A0-C6DA-8BD0-6C56DCAE7D6F}'] function stamp(const xml: TByteDynArray; const username: WideString; const password: WideString): TFinkOkRespuestaTimbrado; stdcall; function stamped(const xml: TByteDynArray; const username: WideString; const password: WideString): TFinkOkRespuestaTimbrado; stdcall; function quick_stamp(const xml: TByteDynArray; const username: WideString; const password: WideString): TFinkOkRespuestaTimbrado; stdcall; function query_pending(const username: WideString; const password: WideString; const uuid: WideString): QueryPendingResult; stdcall; end; // ************************************************************************ // // Namespace : http://facturacion.finkok.com/cancel // soapAction: %operationName% // transport : http://schemas.xmlsoap.org/soap/http // style : document // binding : Aplicacion // service : CancelSOAP // port : Aplicacion // URL : http://demo-facturacion.finkok.com/servicios/soap/cancel // ************************************************************************ // IFinkOkCancelaTimbrado = interface(IInvokable) ['{A50B2847-80CB-1437-9E24-A9C18DE43316}'] function cancel(const UUIDS: UUIDS; const username: WideString; const password: WideString; const taxpayer_id: WideString; const cer: TByteDynArray; const key: TByteDynArray; const store_pending: Boolean): CancelaCFDResult; stdcall; function query_pending_cancellation(const username: WideString; const password: WideString; const uuid: WideString): QueryPendingResult; stdcall; function get_receipt(const username: WideString; const password: WideString; const taxpayer_id: WideString; const uuid: WideString; const type_: WideString): ReceiptResult; stdcall; function out_cancel(const xml: TByteDynArray; const username: WideString; const password: WideString; const taxpayer_id: WideString; const cer: TByteDynArray; const key: TByteDynArray; const store_pending: Boolean): CancelaCFDResult; stdcall; end; // ************************************************************************ // // Namespace : http://facturacion.finkok.com/registration // soapAction: %operationName% // transport : http://schemas.xmlsoap.org/soap/http // style : document // binding : Aplicacion // service : RegistrationSOAP // port : Aplicacion // URL : http://demo-facturacion.finkok.com/servicios/soap/registration // ************************************************************************ // IFinkOkAltaCliente = interface(IInvokable) ['{8E23E329-6B09-E96E-D30F-4E0B79723D1D}'] function edit(const reseller_username: WideString; const reseller_password: WideString; const taxpayer_id: WideString; const status: WideString): IFinkOkRespuestaRegistro; stdcall; function add(const reseller_username: WideString; const reseller_password: WideString; const taxpayer_id: WideString; const coupon: WideString; const added: WideString): IFinkOkRespuestaRegistro; stdcall; function delete(const reseller_username: WideString; const reseller_password: WideString; const taxpayer_id: WideString): IFinkOkRespuestaRegistro; stdcall; end; function GetFinkOkTimbrado(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): IFinkOkServicioTimbrado; function GetFinkOkCancelar(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): IFinkOkCancelaTimbrado; function GetFinkOkCliente(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): IFinkOkAltaCliente; implementation function GetFinkOkTimbrado(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): IFinkOkServicioTimbrado; const defWSDL = 'http://demo-facturacion.finkok.com/servicios/soap/stamp.wsdl'; defURL = 'http://demo-facturacion.finkok.com/servicios/soap/stamp'; defSvc = 'StampSOAP'; defPrt = 'Application'; var RIO: THTTPRIO; begin Result := nil; if (Addr = '') then begin if UseWSDL then Addr := defWSDL else Addr := defURL; end; if HTTPRIO = nil then RIO := THTTPRIO.Create(nil) else RIO := HTTPRIO; try Result := (RIO as IFinkOkServicioTimbrado); if UseWSDL then begin RIO.WSDLLocation := Addr; RIO.Service := defSvc; RIO.Port := defPrt; end else RIO.URL := Addr; finally if (Result = nil) and (HTTPRIO = nil) then RIO.Free; end; end; function GetFinkOkCancelar(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): IFinkOkCancelaTimbrado; const defWSDL = 'http://demo-facturacion.finkok.com/servicios/soap/cancel.wsdl'; defURL = 'http://demo-facturacion.finkok.com/servicios/soap/cancel'; defSvc = 'CancelSOAP'; defPrt = 'Aplicacion'; var RIO: THTTPRIO; begin Result := nil; if (Addr = '') then begin if UseWSDL then Addr := defWSDL else Addr := defURL; end; if HTTPRIO = nil then RIO := THTTPRIO.Create(nil) else RIO := HTTPRIO; try Result := (RIO as IFinkOkCancelaTimbrado); if UseWSDL then begin RIO.WSDLLocation := Addr; RIO.Service := defSvc; RIO.Port := defPrt; end else RIO.URL := Addr; finally if (Result = nil) and (HTTPRIO = nil) then RIO.Free; end; end; function GetFinkOkCliente(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): IFinkOkAltaCliente; const defWSDL = 'http://demo-facturacion.finkok.com/servicios/soap/registration.wsdl'; defURL = 'http://demo-facturacion.finkok.com/servicios/soap/registration'; defSvc = 'RegistrationSOAP'; defPrt = 'Aplicacion'; var RIO: THTTPRIO; begin Result := nil; if (Addr = '') then begin if UseWSDL then Addr := defWSDL else Addr := defURL; end; if HTTPRIO = nil then RIO := THTTPRIO.Create(nil) else RIO := HTTPRIO; try Result := (RIO as IFinkOkAltaCliente); if UseWSDL then begin RIO.WSDLLocation := Addr; RIO.Service := defSvc; RIO.Port := defPrt; end else RIO.URL := Addr; finally if (Result = nil) and (HTTPRIO = nil) then RIO.Free; end; end; destructor TFinkOkRespuestaTimbrado.Destroy; var I: Integer; begin for I := 0 to Length(FIncidencias)-1 do if Assigned(FIncidencias[I]) then FIncidencias[I].Free; SetLength(FIncidencias, 0); inherited Destroy; end; destructor CancelaCFDResult.Destroy; var I: Integer; begin for I := 0 to Length(FFolios)-1 do if Assigned(FFolios[I]) then FFolios[I].Free; SetLength(FFolios, 0); inherited Destroy; end; initialization InvRegistry.RegisterInterface(TypeInfo(IFinkOkServicioTimbrado), 'http://facturacion.finkok.com/stamp', 'UTF-8'); InvRegistry.RegisterDefaultSOAPAction(TypeInfo(IFinkOkServicioTimbrado), '%operationName%'); InvRegistry.RegisterInvokeOptions(TypeInfo(IFinkOkServicioTimbrado), ioDocument); RemClassRegistry.RegisterXSClass(QueryPendingResult, 'apps.services.soap.core.views', 'QueryPendingResult'); RemClassRegistry.RegisterXSClass(Incidencia, 'apps.services.soap.core.views', 'Incidencia'); RemClassRegistry.RegisterXSInfo(TypeInfo(IncidenciaArray), 'apps.services.soap.core.views', 'IncidenciaArray'); RemClassRegistry.RegisterXSClass(TFinkOkRespuestaTimbrado, 'apps.services.soap.core.views', 'AcuseRecepcionCFDI'); /// registro las que son para cancelar InvRegistry.RegisterInterface(TypeInfo(IFinkOkCancelaTimbrado), 'http://facturacion.finkok.com/cancel', 'UTF-8'); InvRegistry.RegisterDefaultSOAPAction(TypeInfo(IFinkOkCancelaTimbrado), '%operationName%'); InvRegistry.RegisterInvokeOptions(TypeInfo(IFinkOkCancelaTimbrado), ioDocument); InvRegistry.RegisterExternalParamName(TypeInfo(IFinkOkCancelaTimbrado), 'get_receipt', 'type_', 'type'); RemClassRegistry.RegisterXSInfo(TypeInfo(stringArray), 'http://facturacion.finkok.com/cancellation', 'stringArray'); RemClassRegistry.RegisterXSClass(UUIDS, 'apps.services.soap.core.views', 'UUIDS'); RemClassRegistry.RegisterXSClass(Folio, 'apps.services.soap.core.views', 'Folio'); RemClassRegistry.RegisterXSInfo(TypeInfo(FolioArray), 'apps.services.soap.core.views', 'FolioArray'); RemClassRegistry.RegisterXSClass(CancelaCFDResult, 'apps.services.soap.core.views', 'CancelaCFDResult'); RemClassRegistry.RegisterXSClass(ReceiptResult, 'apps.services.soap.core.views', 'ReceiptResult'); // registro las que son para dar de alta Clientes (RFC) InvRegistry.RegisterInterface(TypeInfo(IFinkOkAltaCliente), 'http://facturacion.finkok.com/registration', 'UTF-8'); InvRegistry.RegisterDefaultSOAPAction(TypeInfo(IFinkOkAltaCliente), '%operationName%'); InvRegistry.RegisterInvokeOptions(TypeInfo(IFinkOkAltaCliente), ioDocument); RemClassRegistry.RegisterXSClass(IFinkOkRespuestaRegistro, 'apps.services.soap.core.views', 'RegistrationResult'); end.
unit ImportDialogs; interface uses System.SysUtils, System.Classes, Winapi.Windows, Vcl.Controls, Settings; function ShowSelectDatasource(ParentHandle: HWND; var SelectedIndex: Integer):Boolean; function ShowSettingMySQL(ParentHandle: HWND; var MySQLSetting:TMySQLSetting):Boolean; function ShowSettingPostgreSQL(ParentHandle: HWND; var PgSQLSetting:TPostgreSQLSetting):Boolean; implementation uses FormSelectDatasource, FormSettingMySQL, FormSettingPostgreSQL; function ShowSelectDatasource(ParentHandle: HWND; var SelectedIndex: Integer):Boolean; var F: TFrmSelectDataSource; Executed: Boolean; begin Executed:=False; SelectedIndex:=-1; F:=TFrmSelectDataSource.CreateParented(ParentHandle); try F.setSelectedIndex(0); if F.ShowModal = mrOK then begin SelectedIndex:=F.getSelectedIndex; Executed:=True; end; finally FreeAndNil(F); Result:=Executed; end; end; function ShowSettingMySQL(ParentHandle: HWND; var MySQLSetting: TMySQLSetting):Boolean; var F: TFrmSettingMySQL; Executed: Boolean; begin Executed:=False; F:=TFrmSettingMySQL.CreateParented(ParentHandle); try F.setSetting(MySQLSetting); if F.ShowModal = mrOK then begin F.getSetting(MySQLSetting); Executed:=True; end; finally FreeAndNil(F); Result:=Executed; end; end; function ShowSettingPostgreSQL(ParentHandle: HWND; var PgSQLSetting:TPostgreSQLSetting):Boolean; var F: TFrmSettingPostgreSQL; Executed: Boolean; begin Executed:=False; F:=TFrmSettingPostgreSQL.CreateParented(ParentHandle); try F.setSetting(PgSQLSetting); if F.ShowModal = mrOK then begin F.getSetting(PgSQLSetting); Executed:=True; end; finally FreeAndNil(F); Result:=Executed; end; end; end.
unit IdTestHMACMD5; //examples are from http://www.ietf.org/rfc/rfc2202.txt interface uses IdHMACMD5, IdObjs, IdTest, IdSys, IdGlobal; type TIdTestHMACMD5 = class(TIdTest) private FHash: TIdHMACMD5; protected procedure SetUp; override; procedure TearDown; override; public function GenerateByteArray(AValue: Byte; ACount: Integer) : TIdBytes; published procedure TestIETF1; procedure TestIETF2; procedure TestIETF3; procedure TestIETF4; procedure TestIETF5; procedure TestIETF6; procedure TestIETF7; end; implementation procedure TIdTestHMACMD5.SetUp; begin inherited; FHash:=TIdHMACMD5.Create; end; procedure TIdTestHMACMD5.TearDown; begin Sys.FreeAndNil(fhash); inherited; end; function TIdTestHMACMD5.GenerateByteArray(AValue: Byte; ACount: Integer): TIdBytes; var I: Integer; TempBuffer: TIdBytes; begin SetLength(TempBuffer, ACount); for I := 0 to ACount - 1 do begin TempBuffer[I] := AValue; end; Result := TempBuffer; SetLength(TempBuffer, 0); end; // actual tests procedure TIdTestHMACMD5.TestIETF1; var LByteArray: TIdBytes; begin FHash.Key := GenerateByteArray($0B, 16); LByteArray := ToBytes('Hi There'); LByteArray := FHash.HashValue(LByteArray); Assert(Sys.LowerCase(ToHex(LByteArray)) = '9294727a3638bb1c13f48ef8158bfc9d'); end; procedure TIdTestHMACMD5.TestIETF2; var LByteArray: TIdBytes; begin //FHash:=TIdHMACMD5.Create; FHash.Key := ToBytes('Jefe'); LByteArray := ToBytes('what do ya want for nothing?'); LByteArray := FHash.HashValue(LByteArray); Assert(Sys.LowerCase(ToHex(LByteArray)) = '750c783e6ab0b503eaa86e310a5db738'); SetLength(LByteArray, 0); //Sys.FreeAndNil(FHash); end; procedure TIdTestHMACMD5.TestIETF3; var LByteArray: TIdBytes; begin FHash.Key := GenerateByteArray($aa, 16); LByteArray := GenerateByteArray($DD, 50); LByteArray := FHash.HashValue(LByteArray); Assert(Sys.LowerCase(ToHex(LByteArray)) = '56be34521d144c88dbb8c733f0e8b3f6'); end; procedure TIdTestHMACMD5.TestIETF4; var LByteArray: TIdBytes; begin SetLength(LByteArray, 25); LByteArray[0] := $01; LByteArray[1] := $02; LByteArray[2] := $03; LByteArray[3] := $04; LByteArray[4] := $05; LByteArray[5] := $06; LByteArray[6] := $07; LByteArray[7] := $08; LByteArray[8] := $09; LByteArray[9] := $0A; LByteArray[10] := $0B; LByteArray[11] := $0C; LByteArray[12] := $0D; LByteArray[13] := $0E; LByteArray[14] := $0F; LByteArray[15] := $10; LByteArray[16] := $11; LByteArray[17] := $12; LByteArray[18] := $13; LByteArray[19] := $14; LByteArray[20] := $15; LByteArray[21] := $16; LByteArray[22] := $17; LByteArray[23] := $18; LByteArray[24] := $19; FHash.Key := LByteArray; LByteArray := GenerateByteArray($CD, 50); LByteArray := FHash.HashValue(LByteArray); Assert(Sys.LowerCase(ToHex(LByteArray)) = '697eaf0aca3a3aea3a75164746ffaa79'); end; procedure TIdTestHMACMD5.TestIETF5; var LByteArray: TIdBytes; begin FHash.Key := GenerateByteArray($0C, 16); LByteArray := ToBytes('Test With Truncation'); LByteArray := FHash.HashValue(LByteArray); Assert(Sys.LowerCase(ToHex(LByteArray)) = '56461ef2342edc00f9bab995690efd4c'); LByteArray := ToBytes('Test With Truncation'); LByteArray := FHash.HashValue(LByteArray, 12); Assert(Sys.LowerCase(ToHex(LByteArray)) = '56461ef2342edc00f9bab995'); end; procedure TIdTestHMACMD5.TestIETF6; var LByteArray: TIdBytes; begin FHash.Key := GenerateByteArray($AA, 80); LByteArray := ToBytes('Test Using Larger Than Block-Size Key - Hash Key First'); LByteArray := FHash.HashValue(LByteArray); Assert(Sys.LowerCase(ToHex(LByteArray)) = '6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd'); end; procedure TIdTestHMACMD5.TestIETF7; var LByteArray: TIdBytes; begin FHash.Key := GenerateByteArray($AA, 80); LByteArray := ToBytes('Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data'); LByteArray := FHash.HashValue(LByteArray); Assert(Sys.LowerCase(ToHex(LByteArray)) = '6f630fad67cda0ee1fb1f562db3aa53e'); end; initialization TIdTest.RegisterTest(TIdTestHMACMD5); end.
unit Principal; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Menus, Vcl.ComCtrls, Data.DBXFirebird, Data.DB, Data.SqlExpr, Vcl.ImgList; type TFormPrincipal = class(TForm) StatusBar: TStatusBar; MainMenu: TMainMenu; MenuItemMovimentos: TMenuItem; MenuItemAbastecimeto: TMenuItem; MenuItemRelatorios: TMenuItem; MenuItemRelatoriosAbastecimentoPorBomba: TMenuItem; Conexao: TSQLConnection; ImageList: TImageList; MenuItemCadastros: TMenuItem; MenuItemCadastrosConfiguracoes: TMenuItem; MenuItemCadastrosTanques: TMenuItem; MenuItemCadastrosBombas: TMenuItem; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure MenuItemAbastecimetoClick(Sender: TObject); procedure MenuItemRelatoriosAbastecimentoPorBombaClick(Sender: TObject); procedure MenuItemCadastrosConfiguracoesClick(Sender: TObject); procedure MenuItemCadastrosTanquesClick(Sender: TObject); procedure MenuItemCadastrosBombasClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var FormPrincipal: TFormPrincipal; IdSelecionado: String; DescricaoSelecionada: String; implementation {$R *.dfm} uses Util, ConsultaBomba, ImpressaoAbastecimentosa, ImpressaoAbastecimentos, CadastroConfiguracoes, CadastroTanque, CadastroBomba; procedure TFormPrincipal.FormCreate(Sender: TObject); begin try TUtil.ConectarBanco(Conexao); StatusBar.Panels[0].Text := 'Data: ' + FormatDateTime('dd/mm/yyyy',Date); except on E: Exception do begin TUtil.Mensagem(e.Message); Application.Terminate(); end; end; end; procedure TFormPrincipal.FormDestroy(Sender: TObject); begin Conexao.Connected := False; end; procedure TFormPrincipal.MenuItemAbastecimetoClick(Sender: TObject); begin if (FormConsultaBomba = nil) then begin Application.CreateForm(TFormConsultaBomba, FormConsultaBomba); end; FormConsultaBomba.Show(); end; procedure TFormPrincipal.MenuItemCadastrosBombasClick(Sender: TObject); begin if (FormCadastroBomba = nil) then begin Application.CreateForm(TFormCadastroBomba, FormCadastroBomba); end; FormCadastroBomba.Show(); end; procedure TFormPrincipal.MenuItemCadastrosConfiguracoesClick(Sender: TObject); begin if (FormCadastroConfiguracoes = nil) then begin Application.CreateForm(TFormCadastroConfiguracoes, FormCadastroConfiguracoes); end; FormCadastroConfiguracoes.ShowModal(); end; procedure TFormPrincipal.MenuItemCadastrosTanquesClick(Sender: TObject); begin if (FormCadastroTanque = nil) then begin Application.CreateForm(TFormCadastroTanque, FormCadastroTanque); end; FormCadastroTanque.Show(); end; procedure TFormPrincipal.MenuItemRelatoriosAbastecimentoPorBombaClick(Sender: TObject); begin if (FormImpressaoAbastecimentos = nil) then begin Application.CreateForm(TFormImpressaoAbastecimentos, FormImpressaoAbastecimentos); end; FormImpressaoAbastecimentos.Show(); end; 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----- ============================================================================== | wtd.pas | "write type data" or byte identification unit. handy for finding | that magic cookie your looking for! | | History: | Date Author Comment | ---- ------ ------- | -- --- 94 G. Ollis created and developed program ============================================================================*) {$I-,N+,E+} Unit WTD; INTERFACE Uses Header; {++PROCEDURES++++++++++++++++++++++++++++++++++++++++++++++++++++++++++} Procedure WriteTypeData(Var B:Byte; D:DataType); {++FUNCTIONS+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++} {++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++} IMPLEMENTATION Uses ViewU,CRT,CFG,FUTIL,VConvert,Res,Dos; Type WordPointer=^Word; {------------------------------------------------------------------------} Function GetVOCBlock(Var D:DataType; Var blkLen:LongInt):LongInt; Var X:LongInt; L:LongInt; FN:String; Begin D.X:=D.X+1; If D.X+D.offset>D.EOF Then Begin GetVOCBlock:=-1; Exit; End; X:=GetFileWord(D.stream,20)+1; CheckIOError('getting data .voc offset',100); While X<=ImageSize Do Begin If X<D.EOF Then L:=GetFileLong(D.stream,X); CheckIOError(' getting blklen from .voc file',100); L:=(L And $FFFFFF)+4; If X<=D.X+D.offset Then Begin GetVOCBlock:=X; blkLen:=L-4; End; If X>D.X+D.offset Then Exit; X:=X+L; End; GetVOCBlock:=-1; End; {------------------------------------------------------------------------} Function GetMaxPattern(Var D:DataType):LongInt; Var I:Word; Max:Byte; B:Byte; Begin Max:=0; If D.BFT=9 Then B:=GetFileByte(D.stream,$3B6) Else If D.BFT=10 Then B:=GetFileByte(D.stream,$1D6); If B=0 Then Begin GetMaxPattern:=0; Exit; End; If D.BFT=9 Then Begin For I:=0 To B-1 Do If GetFileByte(D.stream,$3B8+I)>Max Then Max:=GetFileByte(D.stream,$3B8+I) End Else For I:=0 To B-1 Do If GetFileByte(D.stream,$1D8+I)>Max Then Max:=GetFileByte(D.stream,$1D8+I); GetMaxPattern:=Max; End; {----------------------------------------------------------------------} Function GetTime(L:LongInt):String; Var DT:DateTime; Answer:String; Begin UnPackTime(L,DT); Answer:=IntToStr(DT.Hour,0)+':'+IntToStr(DT.Min,2)+':'+IntToStr(DT.Sec,2)+' '; Answer:=Answer+IntToStr(DT.Day,0)+' '; Case DT.Month Of 1 : Answer:=Answer+'Jan '; 2 : Answer:=Answer+'Feb '; 3 : Answer:=Answer+'Mar '; 4 : Answer:=Answer+'Apr '; 5 : Answer:=Answer+'May '; 6 : Answer:=Answer+'Jun '; 7 : Answer:=Answer+'Jul '; 8 : Answer:=Answer+'Aug '; 9 : Answer:=Answer+'Sep '; 10: Answer:=Answer+'Oct '; 11: Answer:=Answer+'Nov '; 12: Answer:=Answer+'Dec '; End; Answer:=Answer+IntToStr(DT.Year,0); GetTime:=Answer; End; {----------------------------------------------------------------------} Procedure WriteTypeData(Var B:Byte; D:DataType); Var P:^MultType; CmfHead:CMFHeadType; CMFPoint:^CMFHeadType; L,blkLen:LongInt; BT:Byte; Begin If AltMode=StdMode Then Begin P:=@B; If (D.X>=$FFFF-20) Then P:=@D.D^[$FFFF-20]; GotoXY(1,6); TextAttr:=ICFG.Lolight; Write('Shortint '); TextAttr:=ICFG.Numbers; Write(P^.S:12); TextAttr:=ICFG.Lolight; Write(' Integer '); TextAttr:=ICFG.Numbers; Write(P^.I:10); TextAttr:=ICFG.Lolight; Write(' LongInteger '); TextAttr:=ICFG.Numbers; Writeln(P^.L:16); TextAttr:=ICFG.Lolight; Write('Real '); TextAttr:=ICFG.Numbers; If CheckOverflow('R',@D.D^[D.X]) Then Write('Overflow':12) Else Write(P^.R:12); TextAttr:=ICFG.Lolight; Write(' Single '); TextAttr:=ICFG.Numbers; If CheckOverflow('S',@D.D^[D.X]) Then Write('Overflow':10) Else Write(P^.R:9); TextAttr:=ICFG.Lolight; Write(' Double '); TextAttr:=ICFG.Numbers; If CheckOverflow('D',@D.D^[D.X]) Then Writeln('Overflow':16) Else Writeln(P^.D:16); TextAttr:=ICFG.Lolight; Write('Extended '); TextAttr:=ICFG.Numbers; If CheckOverflow('X',@D.D^[D.X]) Then Write('Overflow':20) Else Write(P^.E:20); TextAttr:=ICFG.Lolight; Write(' Comp '); TextAttr:=ICFG.Numbers; IF CheckOverflow('C',@D.D^[D.X]) Then Writeln('Overflow':20) Else Writeln(P^.C:20); End; If (AltMode=Byte4Mode) Or (AltMode=ThirdView) Then Begin Window(1,Resolution-1,80,Resolution-1); {24} {24} TextAttr:=Blue * $10 or White; End; TextAttr:=ICFG.Highlight; ClrEol; If (D.BFT=1) Then Case AltMode Of 0 : Write('Primary View Mode'); 1 : Write('Secondary View Mode Press Ctrl and Shift for more commands'); 2 : Write('Third View Mode'); Else Write('Unknown View Mode'); End Else If (D.BFT=3) Then Begin If (D.X mod 3)=0 Then Write('BLUE '); If (D.X mod 3)=1 Then Write('RED '); If (D.X mod 3)=2 Then Write('GREEN '); Write(((D.X-1) div 3):4); Write(' (BYTE)'); End Else If D.BFT=2 Then Begin Case D.X+D.offset Of 1 : Write('MANUFACTURER should be $A0 (BYTE) '); 2 : Write('VERSION (0=2.5,2=2.8,3=2.8,5=3.0+) (BYTE) '); 3 : Write('ENCODING should be $01 (BYTE) '); 4 : Write('BITS_PER_PIXEL size of pixels (BYTE) '); 5,6 : Write('XMIN image origin (INTEGER) '); 7,8 : Write('YMIN image origin (INTEGER) '); 9,10 : Write('XMAX image dimensions (INTEGER) '); 11,12 : Write('YMAX image dimensions (INTEGER) '); 13,14 : Write('HRES resolution valuse (INTEGER) '); 15,16 : Write('VRES resolution valuse (INTEGER) '); 65 : Write('RESERVED (BYTE) '); 66 : Write('COLOR_PLAINS (BYTE) '); 67,68 : Write('BYTES_PER_LINE (INTEGER) '); 69,70 : Write('PALETTE_TYPE (1=Greay scale, 2=color) (INTEGER)'); End; If (D.X+D.offset>16) And (D.X+D.offset<=16+48) Then Write('EGA_PALETTE (ARRAY [1..48] OF BYTE) ') Else If (D.X+D.offset>70) And (D.X+D.offset<70+58) Then Write('FILLER space for future expansion (BYTE) ') Else If (D.X+D.offset>=D.EOF-256*3+1) Then Begin If (D.D^[D.EOF-D.offset-256*3]=$0C) Then Write('VGA_PALETTE (ARRAY [1..255*3] OF BYTE) ') Else Write('IMAGE_DATA ... (...) '); End Else If (D.X+D.offset=D.EOF-256*3) And (D.D^[D.X]=$0C) Then Write('BEGINNING_OF_PALETTE should be $0C (BYTE) ') Else If (D.X+D.offset>70+58) And (D.X+D.offset<D.EOF-256*3) Then Write('IMAGE_DATA ... (...) '); End Else If (D.BFT=4) Then Begin Case D.X+D.offset-1 Of 0,1,2,3 : Write('FILE_ID should be ''CTMF'' (ARRAY [0..3] OF CHAR) '); 4,5 : Write('VERSION we support 1.10 (2 BYTES) '); 6,7 : Write('INSTRUMENT_OFFSET where are the instruments (WORD) '); 8,9 : Write('MUSIC_OFFSET where is the music block (WORD) '); $A,$B : Write('TICKS_PER_QUARTER_NOTE one beat (WORD) '); $C,$D : Write('CLOCK_TICKS_PER_SECOND Timmer 0 frequency in Hz (WORD) '); $E,$F : Write('OFFSET_MUSIC_TITLE offset of title in bytes (0 no title) (WORD)'); $10,$11 : Write('OFFSET_COMPOSER_NAME 0 if no composer name (WORD) '); $12,$13 : Write('OFFSET_REMARKS 0 if no remarks (WORD) '); $24,$25 : Write('NUMBER_INSTRUMENTS given to fm driver (WORD) '); $26,$27 : Write('BASIC_TEMPO main tempo used in the music (WORD) '); End; D.X:=D.X-1; If (D.X+D.offset>=$14) And (D.X+D.offset<=$23) Then Write('CHANNEL_IN_USE_TABLE which of 16 channels is used (16 BYTE) '); If (D.X+D.offset>$27) Then Begin If D.offset<>0 Then Begin Seek(D.stream,0); BlockRead(D.stream,CMFHead,SizeOf(CMFHead)); End Else Begin CmfPoint:=@D.D^; CMFHead:=CMFPoint^; End; If (D.X+D.offset>CMFHead.InstrumentOffset-1) And (D.X+D.offset<(CMFHead.InstrumentOffset+CMFHead.NumInstruments*16)) Then Begin Write('INSTRUMENT_BLOCK sbi fields (ARRAY [1..x,1..16] OF BYTE)'); Write((D.X+D.offset-CMFHead.InstrumentOffset) div 16,',',(D.X+D.offset-CMFHead.InstrumentOffset) mod 16, ' '); End Else If (D.X+D.offset>CMFHead.MusicOffset) Then Write('MUSIC_BLOCK smf format (bunch of bytes) ') Else Write('UNIDENTIFIED BYTE '); End; End Else If D.BFT=5 Then Begin D.X:=D.X-1; Case D.X+D.offset Of 0,1,2,3 : Write('FILE_ID should be ''SBI''#26 (ARRAY [0..3] OF CHAR) '); $24 : Write('MODULATOR_SOUND_CHARACTERISTIC (BYTE) '); $25 : Write('CARRIER_SOUND_CHARACTERISTIC (BYTE) '); $26 : Write('MODULATOR_SCALING/OUTPUT_LEVEL (BYTE) '); $27 : Write('CARRIER_SCALING/OUTPUT_LEVEL (BYTE) '); $28 : Write('MODULATOR_ATTACK/DECAY (BYTE) '); $29 : Write('CARRIER ATTACK/DECAY (BYTE) '); $2A : Write('MODULATOR_SUSTAIN_LEVEL/RELESE_RATE (BYTE) '); $2B : Write('CARRIER_SUSTAIN_LEVEL/RELEASE_RATE (BYTE) '); $2C : Write('MODULATOR_WAVE_SELECT (BYTE) '); $2D : Write('CARRIER_WAVE_SELECT (BYTE) '); $2E : Write('FEEDBACK/CONNECTION (BYTE) '); End; If (D.X+D.offset>=4) And (D.X+D.offset<=$23) Then Write('INSTRUMENT NAME all zero if none ($4-$23 null term string)') Else If (D.X+D.offset>=$2F) And (D.X+D.offset<=$33) Then Write('RESERVED FOR FUTURE USE empty filler ') Else If (D.X+D.offset>$2E) Then Write('UNIDENTIFIED BYTE '); End Else If D.BFT=6 Then Begin ClrEol; D.X:=D.X-1; If D.X+D.offset<6 Then Write('GIF signature string. should be "GIF87a" or "GIF89a"'); Case D.X+D.offset Of $6,$7 : Write('SCREEN_WIDTH size of x (WORD)'); $8,$9 : Write('SCREEN_DEPTH size of y (WORD)'); $A : Begin Write('FLAGS ',(1 shl ((D.D^[11] And 7)+1)),' colors '); If (D.D^[11] And $80)=$80 Then Write('global palette ') Else Write('no global palette '); Write('(BYTE)'); End; $B : Write('BACKGROUND pal[BACKGROUND]=bk color (BYTE)'); $C : Write('ASPECT safe to ignore (89a only) (BYTE)'); End; If (D.X+D.offset<781) And (D.X+D.offset>$C) And ((GetFileByte(D.stream,13) And $80)=$80) Then Write('global palette table') Else If (D.X+D.offset>$C) And (D.X+D.offset<D.EOF) Then Write('image data') Else If (D.X+D.offset>$C) Then Write('unidentified byte'); End Else If D.BFT=7 Then Begin D.X:=D.X-1; ClrEol; If (D.X+D.offset<=$13) Then Write('FILE_TYPE_DESCRIPTION should be ''Creative Voice File''#$1A (ARRAY [$13] OF CHAR)'); Case D.X+D.offset Of $14,$15 : Write('OFFSET_OF_DATA_BLOCK position in file (WORD)'); $16,$17 : Write('FORMAT_VERSION current version 1.10 (WORD)'); $18,$19 : Write('FILE_ID_CODE should be $1129 (WORD)'); End; If D.X+D.offset>GetFileWord(D.stream,20)-1 Then Begin L:=GetVOCBlock(D,blkLen); BT:=GetFileByte(D.stream,L-1); If IOResult<>0 Then BT:=0; Case BT Of 0 : Write('Terminator EOF blk '); 1 : Write('Voice data blk '); 2 : Write('Voice continuation blk '); 3 : Write('Silence blk '); 4 : Write('Marker blk '); 5 : Write('ASCII text blk '); 6 : Write('Repeat loop blk '); 7 : Write('End repeat loop blk '); 8 : Write('Extended blk '); 9 : Write('New voice data blk '); End; If BT>9 Then Write('Unknown blk '); If BT=D.X+D.offset Then Write('block determiner'); If (BT<>0) And (D.X+D.offset>L) And (D.X+D.offset<L+4) Then Write('24-bit BLKLEN ',blkLen); If (D.X+D.offset=L+4) And (BT=1) Then Write('TC - time constant (BYTE)'); If (D.X+D.offset=L+5) And (BT=1) Then Write('PACK - packing methoud for sub blk (BYTE)'); If ((D.X+D.offset>L+5) And (BT=1)) Or ((D.X+D.offset>L+3) And (BT=2)) Or ((D.X+D.offset>L+15) And (BT=9)) Then Write('VOICE DATA'); If ((D.X+D.offset=L+4) Or (D.X+D.offset=L+5)) And (BT=3) Then Write('PERIOD - length of silence (WORD)'); If (D.X+D.offset=L+6) And (BT=3) Then Write('TC - time constant (BYTE)'); If ((D.X+D.offset=L+4) Or (D.X+D.offset=L+5)) And (BT=4) Then Write('MARKER - marker number (WORD)'); If (D.X+D.offset>L+4) And (BT=5) Then Write('ASCII_DATA - null terminated'); If ((D.X+D.offset=L+4) Or (D.X+D.offset=L+5)) And (BT=6) Then Write('COUNT - number of loops $FFFF endless loop (WORD)'); If ((D.X+D.offset=L+4) Or (D.X+D.offset=L+5)) And (BT=8) Then Write('TC - time constant (WORD)'); If (D.X+D.offset=L+6) And (BT=8) Then Write('PACK - packing methoud for sub blk (BYTE)'); If (D.X+D.offset=L+7) And (BT=8) Then Write('MODE - mono or stero (0m,1s) (BYTE)'); If (D.X+D.offset>=L+4) And (D.X+D.offset<=L+7) And (BT=9) Then Write('SAMPLES_PER_SEC - sampling freq (LONGWORD)'); If (D.X+D.offset=L+8) And (BT=9) Then Write('BITS_PER_SAMPLE - bps after compressiong (BYTE)'); If (D.X+D.offset=L+9) And (BT=9) Then Write('CHANNELS - 1=mono 2=stereo (BYTE)'); If ((D.X+D.offset=L+10) Or (D.X+D.offset=L+11)) And (BT=9) Then Write('FORMAT_TAG - see other source (WORD)'); IF (D.X+D.offset>=L+12) And (D.X+D.offset<=L+15) And (BT=9) Then Write('RESERVED - for future use (ARRAY [0..3] OF BYTE)'); If L=-1 Then Begin GotoXY(1,WhereY); ClrEol; Write('blk not found '); End; End; End Else If D.BFT=8 Then Begin ClrEol; Case (D.X+D.offset) Of $1,$2 : Write('ID should be $0001 for IMG (rvWORD)'); $3,$4 : Write('HEADER_WORDS number of words in header, should be 8 or 9 (rvWORD)'); $5,$6 : Write('IMAGE_PLANES number of grey level plains, shoult be 1 for monochrome (rvWORD)'); $7,$8 : Write('PATTERN_LENGTH usually 1 (rvWORD)'); $9,$A : Write('PIXEL_WIDTH (rvWORD)'); $B,$C : Write('PIXEL_DEPTH (rvWORD)'); $D,$E : Write('LINE_WIDTH (rvWORD)'); $F,$10 : Write('IMAGE_DEPTH (rvWORD)'); End; If ((D.X+D.offset=$11) Or (D.X+D.offset=$12)) Then Begin If (D.D^[$4]=$9) Then Write('EXTRA (OPTIONAL) (rvWORD)') Else Write('IMAGE_DATA (...)'); End Else If D.X+D.offset>$12 Then Write('IMAGE_DATA (...)'); End Else If D.BFT=9 Then Begin Dec(D.X); If (D.offset+D.X<$14) Then Write('SONG_NAME null terminated string') Else If (D.offset+D.X<$3B6) Then Begin Write('INSTRUMENT'); Write((D.offset+D.X-$14) div 30); L:=D.offset+D.X-$14-((D.offset+D.X-$14) div 30)*30; If L<22 Then Write('_NAME null terminated string') Else If L<23 Then Write('_LENGTH ',Swap(D.D^[D.X+1]):6,' $', Word2Str(Swap(D.D^[D.X+1])),'(rvWORD)') Else If L<24 Then Write('_LENGTH ',Swap(D.D^[D.X]):6,' $', Word2Str(Swap(D.D^[D.X])),'(rvWORD)') Else If L<25 Then Write('_FINETUNE') Else If L<26 Then Write('_LOUDNESS 0-64 (BYTE)') Else If L<27 Then Write('_REPEATLOOP ',Swap(D.D^[D.X+1]):6,' $', Word2Str(Swap(D.D^[D.X+1])),' (rvWORD)') Else If L<28 Then Write('_REPEATLOOP ',Swap(D.D^[D.X]):6,' $', Word2Str(Swap(D.D^[D.X])),' (rvWORD)') Else If L<29 Then Write('_REPEATLENGTH ',Swap(D.D^[D.X+1]):6,' $', Word2Str(Swap(D.D^[D.X+1])),' (rvWORD)') Else If L<30 Then Write('_REPEATLENGTH ',Swap(D.D^[D.X]):6,' $', Word2Str(Swap(D.D^[D.X])),' (rvWORD)') Else Write('_unidentified'); End Else If (D.offset+D.X<$3B7) Then Write('SONG_LENGTH #patterns played (BYTE)') Else If (D.offset+D.X<$3B8) Then Write('SONG_CIAASPEED important for Amiga. usually 127 $7F (BYTE)') Else If (D.offset+D.X<$438) Then Write('SONG_ARRANGEMENT max:',GetMaxPattern(D):4,' $',Byte2Str(GetMaxPattern(D)), ' playback order (ARRAY [0..127] OF BYTE)') Else If (D.offset+D.X<$43C) Then Write('SONG_ID "M.K." or "FLT4" for MOD31 (ARRAY [0..3] OF CHAR)') Else If (D.offset+D.X<$43C+(GetMaxPattern(D)+1)*1024) Then Begin Write('PATTERN',((D.offset+D.X)-$43C) div 1024,'_NOTE', ((D.offset+D.X)-($43C+(((D.offset+D.X)-$43C) div 1024)*1024)) div 4,' '); Case (((D.offset+D.X)-($43C+(((D.offset+D.X)-$43C) div 1024)*1024)) mod 4) Of 0 : Write('high bits of instrument numbers (LONGWORD)'); 1 : Write('12bit pitch (LONGWORD)'); 2 : Write('low bits of instrument number (LONGWORD)'); 3 : Write('12bit effect argument (LONGWORD)'); End; End Else Write('INSTRUMENT_DATA (...)'); For L:=WhereX To 79 Do Write(' '); Inc(D.X); End (* MOD15 *) Else If D.BFT=10 Then Begin Dec(D.X); If (D.X+D.offset<$14) Then Write('SONG_NAME null terminated string') Else If (D.X+D.offset<$1D6) Then Begin Write('INSTRUMENT'); Write((D.offset+D.X-$14) div 30); L:=D.offset+D.X-$14-((D.offset+D.X-$14) div 30)*30; If L<22 Then Write('_NAME null terminated string') Else If L<23 Then Write('_LENGTH ',Swap(D.D^[D.X+1]):6,' $', Word2Str(Swap(D.D^[D.X+1])),'(rvWORD)') Else If L<24 Then Write('_LENGTH ',Swap(D.D^[D.X]):6,' $', Word2Str(Swap(D.D^[D.X])),'(rvWORD)') Else If L<25 Then Write('_FINETUNE') Else If L<26 Then Write('_LOUDNESS 0-64 (BYTE)') Else If L<27 Then Write('_REPEATLOOP ',Swap(D.D^[D.X+1]):6,' $', Word2Str(Swap(D.D^[D.X+1])),' (rvWORD)') Else If L<28 Then Write('_REPEATLOOP ',Swap(D.D^[D.X]):6,' $', Word2Str(Swap(D.D^[D.X])),' (rvWORD)') Else If L<29 Then Write('_REPEATLENGTH ',Swap(D.D^[D.X+1]):6,' $', Word2Str(Swap(D.D^[D.X+1])),' (rvWORD)') Else If L<30 Then Write('_REPEATLENGTH ',Swap(D.D^[D.X]):6,' $', Word2Str(Swap(D.D^[D.X])),' (rvWORD)') Else Write('_unidentified'); End Else If (D.X+D.offset<$1D7) Then Write('SONG_LENGTH #patterns played (BYTE)') Else If (D.X+D.offset<$1D8) Then Write('SONG_CIAASPEED important for Amiga. usually 127 $7F (BYTE)') Else If (D.X+D.offset<$258) Then Write('SONG_ARRANGEMENT max:',GetMaxPattern(D):4,' $', Byte2Str(GetMaxPattern(D)),' playback order (ARRAY [0..127] OF BYTE)') Else If (D.X+D.offset<$258+(GetMaxPattern(D)+1)*1024) Then Begin Write('PATTERN',((D.offset+D.X)-$258) div 1024,'_NOTE', ((D.offset+D.X)-($258+(((D.offset+D.X)-$258) div 1024)*1024)) div 4,' '); Case (((D.offset+D.X)-($258+(((D.offset+D.X)-$258) div 1024)*1024)) mod 4) Of 0 : Write('high bits of instrument numbers (LONGWORD)'); 1 : Write('12bit pitch (LONGWORD)'); 2 : Write('low bits of instrument number (LONGWORD)'); 3 : Write('12bit effect argument (LONGWORD)'); End; End Else Write('INSTRUMENT_DATA (...)'); Inc(D.X); End (* IBK *) Else If D.BFT=11 Then Begin If D.X+D.offset<$5 Then Write('FILEID ASCII string "IBK"#$1A (ARRAY [0..3] OF CHAR)') Else IF D.X+D.offset<$805 Then Begin Write('INSTRUMENT',(D.X+D.offset-5) div $10); Case (D.X+D.offset-5) mod $10 Of $0 : Write('_MODULATORE_SOUND_CHARACTERISTIC (BYTE)'); $1 : Write('_CARRIER_SOUND_CHARACTERISTIC (BYTE)'); $2 : Write('_MODULATOR_SCALING/OUTPUT_LEVEL (BYTE)'); $3 : Write('_CARRIOR_SCALING/OUTPUT_LEVEL (BYTE)'); $4 : Write('_MODULATOR_ATTACK/DELAY (BYTE)'); $5 : Write('_CARRIOR_ATTACK/DELAY (BYTE)'); $6 : Write('_MODULATOR_SUSTAIN_LEVEL/RELEASE_RATE (BYTE)'); $7 : Write('_CARRIER_SUSTAIN_LEVEL/RELEASE_RATE (BYTE)'); $8 : Write('_MODULATOR_WAVE_SELECT (BYTE)'); $9 : Write('_CARRIER_WAVE_SELECT (BYTE)'); $A : Write('_FEEDBACK/CONNECTION (BYTE)'); $B,$C,$D,$E,$F : Write('_RESERVED for future update (ARRAY [0..4] OF BYTE)'); End; End Else If D.X+D.offset<$C85 Then Write('NAME',(D.X+D.offset-$805) div 9, ' null terminated string (ARRAY [0..8] OF CHAR)') Else Write('unidentified byte'); End Else If D.BFT=12 Then Begin Dec(D.X); Case D.X Of 0,1,2,3 : Write('LENGTH of file in bytes (LONGINT)'); 4,5 : Write('MAGIC identifier should by $AF11 (WORD)'); 6,7 : Write('FRAMES # of frames in FLI (WORD)'); 8,9 : Write('WIDTH number of pixels per row should be 320 (WORD)'); 10,11 : Write('HEIGHT number of pixels per colum should be 200 (WORD)'); 12,13 : Write('DEPTH number of bits per pixel should be 8 (WORD)'); 14,15 : Write('FLAGS must be 0 (WORD)'); 16,17 : Write('SPEED number of video ticks between frames (WORD)'); 18,19,20,21,22,23,24,25 : Write('NEXT/FRIT set to 0 (2*LONGINT)'); End; If (D.X>25) And (D.X<26+102) Then Write('EXPAND all zeros -- for future enhancement'); If (D.X>26+102) Then Write('unidentified byte'); Inc(D.X); End Else If D.BFT=13 Then Begin If D.X+D.offset> (D.FragOffset + 1) Then Writeln('DATA (...)') Else Begin Case D.X+D.offset Of 1,2,3 : Write('FileID should be ''FRG'' (ARRAY [1..3] OF CHAR)'); 5 : Write('INDEX (WORD) ',D.D^[D.X]); 6,7,8,9 : Write('TIME Packed Time of Compression (LONGWORD) ',GetTime(LongInt((@D.D^[6])^))); 10,11,12,13 : Write('OFFSET where the file should be put in the destination file (LONGWORD) ', LongInt((@D.D^[10])^)); 14,15,16,17 : Write('TOTAL_SIZE size of original file (LONGWORD) ',LongInt((@D.D^[14])^)); End; If D.X+D.offset=4 Then Begin If D.D^[D.X]=0 Then Write('VERSION_NUMBER corresponds with UN/FRAG v2.04 (BYTE)') Else If D.D^[D.X]=1 Then Write('VERSION_NUMBER corresponds with UN/FRAG v2.05 (BYTE)') Else If D.D^[D.X]=2 Then Write('VERSION_NUMBER corresponds with UN/FRAG v3.00 (BYTE)') Else Write('VERSION_NUMBER unknown version (BYTE)'); End Else If (D.X+D.offset>17) And (D.X+D.offset<31) Then Write('SOURCE_FILE_NAME (STRING[12])') Else If (D.X+D.offset>30) And (D.X+D.offset<33) Then Write('HEADER_SIZE (WORD)') Else If (D.X+D.offset=33) Then Write('FRAG_MODE 0=specific size 1=variable size (BYTE)') Else If (D.X+D.offset>33) And (D.X+D.offset<38) Then Write('FRAG_SIZE estimated size of each fragment (LONG)') Else If (D.X+D.offset=37) And (D.X+D.offset=38) Then Write('UNIX_MODE octal permission ', Octal2Permission(D.D^[37]), ' (WORD)') Else If (D.X+D.offset>38) And (D.X+D.offset<43) Then Write('UNIX_UID user ID on unix (LONG)') Else If (D.X+D.offset>42) And (D.X+D.offset<47) Then Write('UNIX_GID group ID on unix (LONG)') Else If (D.X+D.offset>46) And (D.X+D.offset<51) Then Write('FILE_NAME pointer to a perl scaler filename (LONG)') Else If (D.X+D.offset>50) And (D.X+D.offset<55) Then Write('FILE_NAME length of string (LONG)') Else If D.X+D.offset>37 Then Write('perl scaler representing file name'); End; End Else If D.BFT=14 Then Begin Dec(D.X); If D.X+D.offset<2 Then Case Word(WordPointer(D.D)^) Of $5A4D : Write('SIGNATURE .exe file (2 BYTEs)'); $4D5A : Write('SIGNATURE .com file (2 BYTEs)'); Else Write('SINGNATURE .??? file (2 BYTEs)'); End Else If D.X+D.offset<$1C Then Case D.X+D.offset Of $02,$03 : Write('number of bytes in last 512-byte page of executable (WORD)'); $04,$05 : Write('total number of 512-byte pages in executable (WORD)'); $06,$07 : Write('number of relocation entries (WORD)'); $08,$09 : Write('header size in paragraphs (WORD)'); $0A,$0B : Write('minimum paragraphs to allocate in addition to exe''s size (WORD)'); $0C,$0D : Write('maximum paragraphs to allocate in addition to exe''s size (WORD)'); $0E,$0F : Write('initial SS relative to start of executable (WORD)'); $10,$11 : Write('initial SP (WORD)'); $12,$13 : Write('checksum (WORD)'); $14,$15, $16,$17 : Write('initial CS:IP relative to start of executable (DWORD)'); $18,$19 : Write('offset within header of relocation table (WORD)'); $1A,$1B : Write('overlay number (WORD)'); End Else If (D.X+D.offset>=D.ED.OffRlc) And (D.X+D.offset<D.ED.OffRlc+D.ED.NumRlc*4) Then Write('relocation table #',(D.X+D.offset-D.ED.OffRlc) div 4,' (DWORD)') Else If D.X+D.offset<D.ED.HeadSize Then Begin If D.ED.Tp=0 Then Else If D.ED.Tp=1 Then Begin Write('[new exe] '); If D.X+D.offset<$40 Then Case D.X+D.offset Of $1C,$1D,$1E,$1F : Write('???? (4 BYTEs)'); $20,$21 : Write('behavior bits (WORD)'); {*} $3C,$3D,$3E,$3F : Write('offset of new executable (DWORD)'); Else Write('reserved for additional behavior info (26 BYTEs)'); End; End Else If D.ED.Tp=2 Then Begin Write('[Borland TLINK] '); Case D.X+D.offset Of $1C : Write('apparently always $01 (BYTE)'); $1D : Write('apparently always $00 (BYTE)'); $1E : Write('SIGNATURE2 should be $FB (BYTE)'); $1F : Write('VERSION ',((D.D^[D.X+1] And $F0) shr 4)+1,'.',(D.D^[D.X+1] And $F),' (BYTE)'); $20 : Write('apparently always $72 (v2.0) or $6A (v3.0+)'); $21 : Write('apparently always $6A (v2.0) or $72 (v3.0+)'); End; End Else If D.ED.Tp=3 Then Begin Write('[ARJ Self-extracting archive] '); If (D.X+D.offset>=$1C) And (D.X+D.offset<=$1F) Then Write('SIGNATURE2 should be "RJSX" (ARRAY [1..4] OF CHAR)'); End Else If D.ED.Tp=4 Then Begin Write('[LZEXE 0.90 compressed exe] '); If (D.X+D.offset>=$1C) And (D.X+D.offset<=$1F) Then Write('SIGNATURE2 should be "LZ09" (ARRAY [1..4] OF CHAR)'); End Else If D.ED.Tp=5 Then Begin Write('[LZEXE 0.91 compressed exe] '); If (D.X+D.offset>=$1C) And (D.X+D.offset<=$1F) Then Write('SIGNATURE2 should be "LZ91" (ARRAY [1..4] OF CHAR)'); End Else If D.ED.Tp=9 Then Begin Write('[TopSpeed C 3.0 CRUNCH compressed file] '); If (D.X+D.offset>=$1C) And (D.X+D.offset<=$1F) Then Write('$01A0001 (DWORD)'); If (D.X+D.offset>=$20) And (D.X+D.offset<=$21) Then Write('$1565 (WORD)'); End Else If D.ED.Tp=10 Then Begin Write('[PKARCK 3.5 SFA] '); If (D.X+D.offset>=$1C) And (D.X+D.offset<=$1F) Then Write('$00020001 (DWORD)'); If (D.X+D.offset>=$20) And (D.X+D.offset<=$21) Then Write('$0700 (WORD)'); End Else If D.ED.Tp=11 Then Begin Write('[BSA (Soviet archiver) SFA] '); Case D.X+D.offset Of $1C,$1D : Write('$000F (WORD)'); $1E : Write('$A7 (BYTE)'); End; End; End; Inc(D.X); End Else Write(' '); End; {======================================================================} End.
{ ID:because3 PROG:agrinet LANG:PASCAL } program agrinet; type date=record len,x,y:longint; end; var n,total:longint; a:array [1..10000] of date; f:array [1..100] of longint; procedure qsort(l,r:longint); var i,j,tmp:longint; t:date; begin i:=l; j:=r; tmp:=a[random(r-l+1)+l].len; while i<=j do begin while a[i].len<tmp do inc(i); while a[j].len>tmp do dec(j); if i<=j then begin t:=a[i]; a[i]:=a[j]; a[j]:=t; inc(i); dec(j); end; end; if i<r then qsort(i,r); if j>l then qsort(l,j); end; function getf(x:longint):longint; begin if f[x]=x then exit(x) else begin f[x]:=getf(f[x]); exit(f[x]); end; end; procedure union(x,y:longint); begin x:=getf(x); y:=getf(y); f[x]:=y; end; function min(a,b:longint):longint; begin if a>b then exit(b) else exit(a); end; function max(a,b:longint):longint; begin if a>b then exit(a) else exit(b); end; procedure init; var i,j:longint; begin readln(n); total:=0; for i:=1 to n do for j:=1 to n do begin inc(total); read(a[total].len); a[total].x:=i; a[total].y:=j; end; qsort(1,total); for i:=1 to n do f[i]:=i; end; procedure work; var count,i:longint; begin count:=0;i:=0;total:=0; while count<n-1 do begin inc(i); with a[i] do if getf(x)<>getf(y) then begin union(x,y); inc(total,len); inc(count); end; end; writeln(total); end; procedure print; begin end; BEGIN assign(input,'agrinet.in'); reset(input); assign(output,'agrinet.out'); rewrite(output); init; work; print; close(input); close(output); END.
{ $OmniXML: OmniXML/OmniXML_LookupTables.pas,v 1.2 2005/12/01 19:27:06 mremec Exp $ } (******************************************************************************* * 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 OmniXML_LookupTables.pas * * * * The Initial Developer of the Original Code is Miha Remec * * http://www.MihaRemec.com/ * * * * Contributor(s): Erik Berry <eb@techie.com> * *******************************************************************************) unit OmniXML_LookupTables; interface {$I OmniXML.inc} {$IFDEF OmniXML_DXE4_UP} {$ZEROBASEDSTRINGS OFF} {$ENDIF} var XMLCharLookupTable: array of Byte; implementation type TRLEItem = record Val: Byte; Len: Smallint; end; const RLEArray: array [0..612] of TRLEItem = ( (Val: $00; Len: 9;), (Val: $40; Len: 2;), (Val: $00; Len: 2;), (Val: $40; Len: 1;), (Val: $00; Len: 18;), (Val: $40; Len: 13;), (Val: $C0; Len: 2;), (Val: $40; Len: 1;), (Val: $C4; Len: 10;), (Val: $C0; Len: 1;), (Val: $40; Len: 6;), (Val: $D1; Len: 26;), (Val: $40; Len: 4;), (Val: $C0; Len: 1;), (Val: $40; Len: 1;), (Val: $D1; Len: 26;), (Val: $40; Len: 60;), (Val: $E0; Len: 1;), (Val: $40; Len: 8;), (Val: $D1; Len: 23;), (Val: $40; Len: 1;), (Val: $D1; Len: 31;), (Val: $40; Len: 1;), (Val: $D1; Len: 58;), (Val: $40; Len: 2;), (Val: $D1; Len: 11;), (Val: $40; Len: 2;), (Val: $D1; Len: 8;), (Val: $40; Len: 1;), (Val: $D1; Len: 53;), (Val: $40; Len: 1;), (Val: $D1; Len: 68;), (Val: $40; Len: 9;), (Val: $D1; Len: 36;), (Val: $40; Len: 3;), (Val: $D1; Len: 2;), (Val: $40; Len: 4;), (Val: $D1; Len: 30;), (Val: $40; Len: 56;), (Val: $D1; Len: 89;), (Val: $40; Len: 18;), (Val: $D1; Len: 7;), (Val: $40; Len: 14;), (Val: $E0; Len: 2;), (Val: $40; Len: 46;), (Val: $C2; Len: 70;), (Val: $40; Len: 26;), (Val: $C2; Len: 2;), (Val: $40; Len: 36;), (Val: $D1; Len: 1;), (Val: $E0; Len: 1;), (Val: $D1; Len: 3;), (Val: $40; Len: 1;), (Val: $D1; Len: 1;), (Val: $40; Len: 1;), (Val: $D1; Len: 20;), (Val: $40; Len: 1;), (Val: $D1; Len: 44;), (Val: $40; Len: 1;), (Val: $D1; Len: 7;), (Val: $40; Len: 3;), (Val: $D1; Len: 1;), (Val: $40; Len: 1;), (Val: $D1; Len: 1;), (Val: $40; Len: 1;), (Val: $D1; Len: 1;), (Val: $40; Len: 1;), (Val: $D1; Len: 1;), (Val: $40; Len: 1;), (Val: $D1; Len: 18;), (Val: $40; Len: 13;), (Val: $D1; Len: 12;), (Val: $40; Len: 1;), (Val: $D1; Len: 66;), (Val: $40; Len: 1;), (Val: $D1; Len: 12;), (Val: $40; Len: 1;), (Val: $D1; Len: 36;), (Val: $40; Len: 1;), (Val: $C2; Len: 4;), (Val: $40; Len: 9;), (Val: $D1; Len: 53;), (Val: $40; Len: 2;), (Val: $D1; Len: 2;), (Val: $40; Len: 2;), (Val: $D1; Len: 2;), (Val: $40; Len: 3;), (Val: $D1; Len: 28;), (Val: $40; Len: 2;), (Val: $D1; Len: 8;), (Val: $40; Len: 2;), (Val: $D1; Len: 2;), (Val: $40; Len: 55;), (Val: $D1; Len: 38;), (Val: $40; Len: 2;), (Val: $D1; Len: 1;), (Val: $40; Len: 7;), (Val: $D1; Len: 38;), (Val: $40; Len: 10;), (Val: $C2; Len: 17;), (Val: $40; Len: 1;), (Val: $C2; Len: 23;), (Val: $40; Len: 1;), (Val: $C2; Len: 3;), (Val: $40; Len: 1;), (Val: $C2; Len: 1;), (Val: $40; Len: 1;), (Val: $C2; Len: 2;), (Val: $40; Len: 1;), (Val: $C2; Len: 1;), (Val: $40; Len: 11;), (Val: $D1; Len: 27;), (Val: $40; Len: 5;), (Val: $D1; Len: 3;), (Val: $40; Len: 46;), (Val: $D1; Len: 26;), (Val: $40; Len: 5;), (Val: $E0; Len: 1;), (Val: $D1; Len: 10;), (Val: $C2; Len: 8;), (Val: $40; Len: 13;), (Val: $C4; Len: 10;), (Val: $40; Len: 6;), (Val: $C2; Len: 1;), (Val: $D1; Len: 71;), (Val: $40; Len: 2;), (Val: $D1; Len: 5;), (Val: $40; Len: 1;), (Val: $D1; Len: 15;), (Val: $40; Len: 1;), (Val: $D1; Len: 4;), (Val: $40; Len: 1;), (Val: $D1; Len: 1;), (Val: $C2; Len: 15;), (Val: $D1; Len: 2;), (Val: $C2; Len: 2;), (Val: $40; Len: 1;), (Val: $C2; Len: 4;), (Val: $40; Len: 2;), (Val: $C4; Len: 10;), (Val: $40; Len: 519;), (Val: $C2; Len: 3;), (Val: $40; Len: 1;), (Val: $D1; Len: 53;), (Val: $40; Len: 2;), (Val: $C2; Len: 1;), (Val: $D1; Len: 1;), (Val: $C2; Len: 16;), (Val: $40; Len: 3;), (Val: $C2; Len: 4;), (Val: $40; Len: 3;), (Val: $D1; Len: 10;), (Val: $C2; Len: 2;), (Val: $40; Len: 2;), (Val: $C4; Len: 10;), (Val: $40; Len: 17;), (Val: $C2; Len: 3;), (Val: $40; Len: 1;), (Val: $D1; Len: 8;), (Val: $40; Len: 2;), (Val: $D1; Len: 2;), (Val: $40; Len: 2;), (Val: $D1; Len: 22;), (Val: $40; Len: 1;), (Val: $D1; Len: 7;), (Val: $40; Len: 1;), (Val: $D1; Len: 1;), (Val: $40; Len: 3;), (Val: $D1; Len: 4;), (Val: $40; Len: 2;), (Val: $C2; Len: 1;), (Val: $40; Len: 1;), (Val: $C2; Len: 7;), (Val: $40; Len: 2;), (Val: $C2; Len: 2;), (Val: $40; Len: 2;), (Val: $C2; Len: 3;), (Val: $40; Len: 9;), (Val: $C2; Len: 1;), (Val: $40; Len: 4;), (Val: $D1; Len: 2;), (Val: $40; Len: 1;), (Val: $D1; Len: 3;), (Val: $C2; Len: 2;), (Val: $40; Len: 2;), (Val: $C4; Len: 10;), (Val: $D1; Len: 2;), (Val: $40; Len: 16;), (Val: $C2; Len: 1;), (Val: $40; Len: 2;), (Val: $D1; Len: 6;), (Val: $40; Len: 4;), (Val: $D1; Len: 2;), (Val: $40; Len: 2;), (Val: $D1; Len: 22;), (Val: $40; Len: 1;), (Val: $D1; Len: 7;), (Val: $40; Len: 1;), (Val: $D1; Len: 2;), (Val: $40; Len: 1;), (Val: $D1; Len: 2;), (Val: $40; Len: 1;), (Val: $D1; Len: 2;), (Val: $40; Len: 2;), (Val: $C2; Len: 1;), (Val: $40; Len: 1;), (Val: $C2; Len: 5;), (Val: $40; Len: 4;), (Val: $C2; Len: 2;), (Val: $40; Len: 2;), (Val: $C2; Len: 3;), (Val: $40; Len: 11;), (Val: $D1; Len: 4;), (Val: $40; Len: 1;), (Val: $D1; Len: 1;), (Val: $40; Len: 7;), (Val: $C4; Len: 10;), (Val: $C2; Len: 2;), (Val: $D1; Len: 3;), (Val: $40; Len: 12;), (Val: $C2; Len: 3;), (Val: $40; Len: 1;), (Val: $D1; Len: 7;), (Val: $40; Len: 1;), (Val: $D1; Len: 1;), (Val: $40; Len: 1;), (Val: $D1; Len: 3;), (Val: $40; Len: 1;), (Val: $D1; Len: 22;), (Val: $40; Len: 1;), (Val: $D1; Len: 7;), (Val: $40; Len: 1;), (Val: $D1; Len: 2;), (Val: $40; Len: 1;), (Val: $D1; Len: 5;), (Val: $40; Len: 2;), (Val: $C2; Len: 1;), (Val: $D1; Len: 1;), (Val: $C2; Len: 8;), (Val: $40; Len: 1;), (Val: $C2; Len: 3;), (Val: $40; Len: 1;), (Val: $C2; Len: 3;), (Val: $40; Len: 18;), (Val: $D1; Len: 1;), (Val: $40; Len: 5;), (Val: $C4; Len: 10;), (Val: $40; Len: 17;), (Val: $C2; Len: 3;), (Val: $40; Len: 1;), (Val: $D1; Len: 8;), (Val: $40; Len: 2;), (Val: $D1; Len: 2;), (Val: $40; Len: 2;), (Val: $D1; Len: 22;), (Val: $40; Len: 1;), (Val: $D1; Len: 7;), (Val: $40; Len: 1;), (Val: $D1; Len: 2;), (Val: $40; Len: 2;), (Val: $D1; Len: 4;), (Val: $40; Len: 2;), (Val: $C2; Len: 1;), (Val: $D1; Len: 1;), (Val: $C2; Len: 6;), (Val: $40; Len: 3;), (Val: $C2; Len: 2;), (Val: $40; Len: 2;), (Val: $C2; Len: 3;), (Val: $40; Len: 8;), (Val: $C2; Len: 2;), (Val: $40; Len: 4;), (Val: $D1; Len: 2;), (Val: $40; Len: 1;), (Val: $D1; Len: 3;), (Val: $40; Len: 4;), (Val: $C4; Len: 10;), (Val: $40; Len: 18;), (Val: $C2; Len: 2;), (Val: $40; Len: 1;), (Val: $D1; Len: 6;), (Val: $40; Len: 3;), (Val: $D1; Len: 3;), (Val: $40; Len: 1;), (Val: $D1; Len: 4;), (Val: $40; Len: 3;), (Val: $D1; Len: 2;), (Val: $40; Len: 1;), (Val: $D1; Len: 1;), (Val: $40; Len: 1;), (Val: $D1; Len: 2;), (Val: $40; Len: 3;), (Val: $D1; Len: 2;), (Val: $40; Len: 3;), (Val: $D1; Len: 3;), (Val: $40; Len: 3;), (Val: $D1; Len: 8;), (Val: $40; Len: 1;), (Val: $D1; Len: 3;), (Val: $40; Len: 4;), (Val: $C2; Len: 5;), (Val: $40; Len: 3;), (Val: $C2; Len: 3;), (Val: $40; Len: 1;), (Val: $C2; Len: 4;), (Val: $40; Len: 9;), (Val: $C2; Len: 1;), (Val: $40; Len: 15;), (Val: $C4; Len: 9;), (Val: $40; Len: 17;), (Val: $C2; Len: 3;), (Val: $40; Len: 1;), (Val: $D1; Len: 8;), (Val: $40; Len: 1;), (Val: $D1; Len: 3;), (Val: $40; Len: 1;), (Val: $D1; Len: 23;), (Val: $40; Len: 1;), (Val: $D1; Len: 10;), (Val: $40; Len: 1;), (Val: $D1; Len: 5;), (Val: $40; Len: 4;), (Val: $C2; Len: 7;), (Val: $40; Len: 1;), (Val: $C2; Len: 3;), (Val: $40; Len: 1;), (Val: $C2; Len: 4;), (Val: $40; Len: 7;), (Val: $C2; Len: 2;), (Val: $40; Len: 9;), (Val: $D1; Len: 2;), (Val: $40; Len: 4;), (Val: $C4; Len: 10;), (Val: $40; Len: 18;), (Val: $C2; Len: 2;), (Val: $40; Len: 1;), (Val: $D1; Len: 8;), (Val: $40; Len: 1;), (Val: $D1; Len: 3;), (Val: $40; Len: 1;), (Val: $D1; Len: 23;), (Val: $40; Len: 1;), (Val: $D1; Len: 10;), (Val: $40; Len: 1;), (Val: $D1; Len: 5;), (Val: $40; Len: 4;), (Val: $C2; Len: 7;), (Val: $40; Len: 1;), (Val: $C2; Len: 3;), (Val: $40; Len: 1;), (Val: $C2; Len: 4;), (Val: $40; Len: 7;), (Val: $C2; Len: 2;), (Val: $40; Len: 7;), (Val: $D1; Len: 1;), (Val: $40; Len: 1;), (Val: $D1; Len: 2;), (Val: $40; Len: 4;), (Val: $C4; Len: 10;), (Val: $40; Len: 18;), (Val: $C2; Len: 2;), (Val: $40; Len: 1;), (Val: $D1; Len: 8;), (Val: $40; Len: 1;), (Val: $D1; Len: 3;), (Val: $40; Len: 1;), (Val: $D1; Len: 23;), (Val: $40; Len: 1;), (Val: $D1; Len: 16;), (Val: $40; Len: 4;), (Val: $C2; Len: 6;), (Val: $40; Len: 2;), (Val: $C2; Len: 3;), (Val: $40; Len: 1;), (Val: $C2; Len: 4;), (Val: $40; Len: 9;), (Val: $C2; Len: 1;), (Val: $40; Len: 8;), (Val: $D1; Len: 2;), (Val: $40; Len: 4;), (Val: $C4; Len: 10;), (Val: $40; Len: 145;), (Val: $D1; Len: 46;), (Val: $40; Len: 1;), (Val: $D1; Len: 1;), (Val: $C2; Len: 1;), (Val: $D1; Len: 2;), (Val: $C2; Len: 7;), (Val: $40; Len: 5;), (Val: $D1; Len: 6;), (Val: $E0; Len: 1;), (Val: $C2; Len: 8;), (Val: $40; Len: 1;), (Val: $C4; Len: 10;), (Val: $40; Len: 39;), (Val: $D1; Len: 2;), (Val: $40; Len: 1;), (Val: $D1; Len: 1;), (Val: $40; Len: 2;), (Val: $D1; Len: 2;), (Val: $40; Len: 1;), (Val: $D1; Len: 1;), (Val: $40; Len: 2;), (Val: $D1; Len: 1;), (Val: $40; Len: 6;), (Val: $D1; Len: 4;), (Val: $40; Len: 1;), (Val: $D1; Len: 7;), (Val: $40; Len: 1;), (Val: $D1; Len: 3;), (Val: $40; Len: 1;), (Val: $D1; Len: 1;), (Val: $40; Len: 1;), (Val: $D1; Len: 1;), (Val: $40; Len: 2;), (Val: $D1; Len: 2;), (Val: $40; Len: 1;), (Val: $D1; Len: 2;), (Val: $40; Len: 1;), (Val: $D1; Len: 1;), (Val: $C2; Len: 1;), (Val: $D1; Len: 2;), (Val: $C2; Len: 6;), (Val: $40; Len: 1;), (Val: $C2; Len: 2;), (Val: $D1; Len: 1;), (Val: $40; Len: 2;), (Val: $D1; Len: 5;), (Val: $40; Len: 1;), (Val: $E0; Len: 1;), (Val: $40; Len: 1;), (Val: $C2; Len: 6;), (Val: $40; Len: 2;), (Val: $C4; Len: 10;), (Val: $40; Len: 62;), (Val: $C2; Len: 2;), (Val: $40; Len: 6;), (Val: $C4; Len: 10;), (Val: $40; Len: 11;), (Val: $C2; Len: 1;), (Val: $40; Len: 1;), (Val: $C2; Len: 1;), (Val: $40; Len: 1;), (Val: $C2; Len: 1;), (Val: $40; Len: 4;), (Val: $C2; Len: 2;), (Val: $D1; Len: 8;), (Val: $40; Len: 1;), (Val: $D1; Len: 33;), (Val: $40; Len: 7;), (Val: $C2; Len: 20;), (Val: $40; Len: 1;), (Val: $C2; Len: 6;), (Val: $40; Len: 4;), (Val: $C2; Len: 6;), (Val: $40; Len: 1;), (Val: $C2; Len: 1;), (Val: $40; Len: 1;), (Val: $C2; Len: 21;), (Val: $40; Len: 3;), (Val: $C2; Len: 7;), (Val: $40; Len: 1;), (Val: $C2; Len: 1;), (Val: $40; Len: 230;), (Val: $D1; Len: 38;), (Val: $40; Len: 10;), (Val: $D1; Len: 39;), (Val: $40; Len: 9;), (Val: $D1; Len: 1;), (Val: $40; Len: 1;), (Val: $D1; Len: 2;), (Val: $40; Len: 1;), (Val: $D1; Len: 3;), (Val: $40; Len: 1;), (Val: $D1; Len: 1;), (Val: $40; Len: 1;), (Val: $D1; Len: 2;), (Val: $40; Len: 1;), (Val: $D1; Len: 5;), (Val: $40; Len: 41;), (Val: $D1; Len: 1;), (Val: $40; Len: 1;), (Val: $D1; Len: 1;), (Val: $40; Len: 1;), (Val: $D1; Len: 1;), (Val: $40; Len: 11;), (Val: $D1; Len: 1;), (Val: $40; Len: 1;), (Val: $D1; Len: 1;), (Val: $40; Len: 1;), (Val: $D1; Len: 1;), (Val: $40; Len: 3;), (Val: $D1; Len: 2;), (Val: $40; Len: 3;), (Val: $D1; Len: 1;), (Val: $40; Len: 5;), (Val: $D1; Len: 3;), (Val: $40; Len: 1;), (Val: $D1; Len: 1;), (Val: $40; Len: 1;), (Val: $D1; Len: 1;), (Val: $40; Len: 1;), (Val: $D1; Len: 1;), (Val: $40; Len: 1;), (Val: $D1; Len: 1;), (Val: $40; Len: 3;), (Val: $D1; Len: 2;), (Val: $40; Len: 3;), (Val: $D1; Len: 2;), (Val: $40; Len: 1;), (Val: $D1; Len: 1;), (Val: $40; Len: 40;), (Val: $D1; Len: 1;), (Val: $40; Len: 9;), (Val: $D1; Len: 1;), (Val: $40; Len: 2;), (Val: $D1; Len: 1;), (Val: $40; Len: 2;), (Val: $D1; Len: 2;), (Val: $40; Len: 7;), (Val: $D1; Len: 2;), (Val: $40; Len: 1;), (Val: $D1; Len: 1;), (Val: $40; Len: 1;), (Val: $D1; Len: 7;), (Val: $40; Len: 40;), (Val: $D1; Len: 1;), (Val: $40; Len: 4;), (Val: $D1; Len: 1;), (Val: $40; Len: 8;), (Val: $D1; Len: 1;), (Val: $40; Len: 3078;), (Val: $D1; Len: 156;), (Val: $40; Len: 4;), (Val: $D1; Len: 90;), (Val: $40; Len: 6;), (Val: $D1; Len: 22;), (Val: $40; Len: 2;), (Val: $D1; Len: 6;), (Val: $40; Len: 2;), (Val: $D1; Len: 38;), (Val: $40; Len: 2;), (Val: $D1; Len: 6;), (Val: $40; Len: 2;), (Val: $D1; Len: 8;), (Val: $40; Len: 1;), (Val: $D1; Len: 1;), (Val: $40; Len: 1;), (Val: $D1; Len: 1;), (Val: $40; Len: 1;), (Val: $D1; Len: 1;), (Val: $40; Len: 1;), (Val: $D1; Len: 31;), (Val: $40; Len: 2;), (Val: $D1; Len: 53;), (Val: $40; Len: 1;), (Val: $D1; Len: 7;), (Val: $40; Len: 1;), (Val: $D1; Len: 1;), (Val: $40; Len: 3;), (Val: $D1; Len: 3;), (Val: $40; Len: 1;), (Val: $D1; Len: 7;), (Val: $40; Len: 3;), (Val: $D1; Len: 4;), (Val: $40; Len: 2;), (Val: $D1; Len: 6;), (Val: $40; Len: 4;), (Val: $D1; Len: 13;), (Val: $40; Len: 5;), (Val: $D1; Len: 3;), (Val: $40; Len: 1;), (Val: $D1; Len: 7;), (Val: $40; Len: 211;), (Val: $C2; Len: 13;), (Val: $40; Len: 4;), (Val: $C2; Len: 1;), (Val: $40; Len: 68;), (Val: $D1; Len: 1;), (Val: $40; Len: 3;), (Val: $D1; Len: 2;), (Val: $40; Len: 2;), (Val: $D1; Len: 1;), (Val: $40; Len: 81;), (Val: $D1; Len: 3;), (Val: $40; Len: 3714;), (Val: $E0; Len: 1;), (Val: $40; Len: 1;), (Val: $D8; Len: 1;), (Val: $40; Len: 25;), (Val: $D8; Len: 9;), (Val: $C2; Len: 6;), (Val: $40; Len: 1;), (Val: $E0; Len: 5;), (Val: $40; Len: 11;), (Val: $D1; Len: 84;), (Val: $40; Len: 4;), (Val: $C2; Len: 2;), (Val: $40; Len: 2;), (Val: $E0; Len: 2;), (Val: $40; Len: 2;), (Val: $D1; Len: 90;), (Val: $40; Len: 1;), (Val: $E0; Len: 3;), (Val: $40; Len: 6;), (Val: $D1; Len: 40;), (Val: $40; Len: 7379;), (Val: $D8; Len: 20902;), (Val: $40; Len: 3162;), (Val: $D1; Len: 11172;), (Val: $40; Len: 92;), (Val: $00; Len: 2048;), (Val: $40; Len: 8190;) ); procedure InitializeCharLookupTable; var i, j: Integer; Value: Byte; Length: Smallint; TablePos: Integer; begin SetLength(XMLCharLookupTable, 65536); TablePos := 0; for i := Low(RLEArray) to High(RLEArray) do begin Value := RLEArray[i].Val; Length := RLEArray[i].Len; for j := 0 to Length - 1 do begin XMLCharLookupTable[TablePos] := Value; Inc(TablePos); end; end; end; initialization InitializeCharLookupTable; end.
unit ByteToStructEbk3; interface uses EBK3HeadStruct, ChapterListStruct, blockStruct, ChapterHeadModelStruct, DynDataStruct, Util, System.SysUtils, System.Types; type TByteToStructEbk3 = class private class function GetBytes(length: Integer; var offset: Integer; buff: TArray<Byte>): TArray<Byte>; static; class function GetInt16(length: Integer; var offset: Integer; buff: TArray<Byte>): Integer; static; class function GetInt32(length: Integer; var offset: Integer; buff: TArray<Byte>): Cardinal; static; public function GetBlockFileList(buffs: TArray<Byte>): TChapterListStruct; function GetBlockStruct(buffs: TArray<Byte>): TblockStruct; function GetChapterHeadModelStruct(buffs: TArray<Byte>): TChapterHeadModelStruct; function GetDynDataStruct(buffs: TArray<Byte>): TDynDataStruct; function GetHeadStruct(buffs: TArray<Byte>): TEBK3HeadStruct; end; implementation class function TByteToStructEbk3.GetBytes(length: Integer; var offset: Integer; buff: TArray<Byte>): TArray<Byte>; var buffer: TArray<Byte>; begin SetLength(buffer, length); TUtil.ArrayCopy(buff[0], offset, buffer[0], 0, length); Inc(offset, length); Result := buffer; end; class function TByteToStructEbk3.GetInt16(length: Integer; var offset: Integer; buff: TArray<Byte>): Integer; var buffer: TArray<Byte>; begin SetLength(buffer, length); TUtil.ArrayCopy(buff[0], offset, buffer[0], 0, length); Inc(offset, length); Result := TBitConverter.InTo<Int16>(buffer); end; class function TByteToStructEbk3.GetInt32(length: Integer; var offset: Integer; buff: TArray<Byte>): Cardinal; var buffer: TArray<Byte>; begin SetLength(buffer, length); TUtil.ArrayCopy(buff[0], offset, buffer[0], 0, length); Inc(offset, length); Result := TBitConverter.InTo<Int32>(buffer); end; function TByteToStructEbk3.GetBlockFileList(buffs: TArray<System.Byte>): TChapterListStruct; var struct2: TChapterListStruct; offset: Integer; begin offset := 0; struct2.chapter_name_length7 := TByteToStructEbk3.GetInt32(4, offset, buffs); struct2.chapter_index1 := TByteToStructEbk3.GetInt32(4, offset, buffs); struct2.chapter_level2 := TByteToStructEbk3.GetInt16(2, offset, buffs); struct2.chapter_data_type3 := TByteToStructEbk3.GetInt16(2, offset, buffs); struct2.chapter_data_block_offset4 := TByteToStructEbk3.GetInt32(4, offset, buffs); struct2.chapter_content_decompresss_offset5 := TByteToStructEbk3.GetInt32(4, offset, buffs); struct2.chapter_content_decompress_length6 := TByteToStructEbk3.GetInt32(4, offset, buffs); Result := struct2; end; function TByteToStructEbk3.GetBlockStruct(buffs: TArray<System.Byte>): TblockStruct; var struct2: TblockStruct; offset: Integer; begin offset := 0; struct2.header_key := TByteToStructEbk3.GetInt32(4, offset, buffs); struct2.header_length := TByteToStructEbk3.GetInt32(4, offset, buffs); struct2.decode_key := TByteToStructEbk3.GetInt32(4, offset, buffs); Result := struct2; end; function TByteToStructEbk3.GetChapterHeadModelStruct(buffs: TArray<System.Byte>): TChapterHeadModelStruct; var struct2: TChapterHeadModelStruct; offset: Integer; begin offset := 0; struct2.chapter_count := TByteToStructEbk3.GetInt32(4, offset, buffs); struct2.chapter_name_header_length := TByteToStructEbk3.GetInt32(4, offset, buffs); Result := struct2; end; function TByteToStructEbk3.GetDynDataStruct(buffs: TArray<System.Byte>): TDynDataStruct; var struct2: TDynDataStruct; offset: Integer; begin offset := 0; struct2.dyn_data_length := TByteToStructEbk3.GetInt32(4, offset, buffs); struct2.book_id := TByteToStructEbk3.GetInt32(4, offset, buffs); struct2.chapter_list_offset := TByteToStructEbk3.GetInt32(4, offset, buffs); struct2.chapter_list_length := TByteToStructEbk3.GetInt32(4, offset, buffs); Result := struct2; end; function TByteToStructEbk3.GetHeadStruct(buffs: TArray<System.Byte>): TEBK3HeadStruct; var struct2: TEBK3HeadStruct; offset: Integer; begin offset := 0; struct2 := TEBK3HeadStruct.Create; struct2.identifier := TByteToStructEbk3.GetBytes(4, offset, buffs); struct2.header_key := TByteToStructEbk3.GetInt32(4, offset, buffs); struct2.header_length := TByteToStructEbk3.GetInt32(4, offset, buffs); struct2.decode_key := TByteToStructEbk3.GetInt32(4, offset, buffs); Result := struct2; end; end.
unit ReceiptsAnal; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, LikeList, cxGridCustomPopupMenu, cxGridPopupMenu, DB, dxBar, FIBDataSet, pFIBDataSet, FIBDatabase, pFIBDatabase, cxSplitter, cxContainer, cxEdit, cxTextEdit, cxMemo, cxDBEdit, StdCtrls, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, ExtCtrls, cxInplaceContainer, cxTL, cxDBTL, cxTLData, cxLabel, cxMaskEdit, cxDropDownEdit, cxCalendar; type TfrmReceiptsAnal = class(TfrmLikeList) tlGroups: TcxDBTreeList; tlGroupsNAME: TcxDBTreeListColumn; tlGroupsID: TcxDBTreeListColumn; tlGroupsPARENT_ID: TcxDBTreeListColumn; cxSplitter2: TcxSplitter; fibdsGoodsServices: TpFIBDataSet; dsGoodsServices: TDataSource; fibdsGoodsServicesID: TFIBIntegerField; fibdsGoodsServicesPARENT_ID: TFIBIntegerField; fibdsGoodsServicesNAME: TFIBStringField; fibdsGoodsServicesCOMMENTS: TFIBStringField; fibdsGoodsServicesAMOUNT: TFIBFloatField; fibdsGoodsServicesNAME_WITH_AMOUNT: TFIBStringField; Panel3: TPanel; cxLabel12: TcxLabel; cxLabel1: TcxLabel; deStart: TcxDateEdit; deStop: TcxDateEdit; fibdsMainListNAME: TFIBStringField; fibdsMainListDEPARTMENT_ID: TFIBIntegerField; fibdsMainListQUANTITY: TFIBBCDField; fibdsMainListAMOUNT: TFIBFloatField; tvMainListNAME: TcxGridDBColumn; tvMainListDEPARTMENT_ID: TcxGridDBColumn; tvMainListQUANTITY: TcxGridDBColumn; tvMainListAMOUNT: TcxGridDBColumn; procedure OpenAll; override; procedure fibdsGoodsServicesCalcFields(DataSet: TDataSet); procedure FormCreate(Sender: TObject); procedure fibdsGoodsServicesBeforeOpen(DataSet: TDataSet); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure cxSplitter2AfterClose(Sender: TObject); procedure cxSplitter2AfterOpen(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmReceiptsAnal: TfrmReceiptsAnal; implementation uses DM; var DMTagIncreased: Boolean = False; {$R *.dfm} procedure TfrmReceiptsAnal.OpenAll; begin inherited; If Not(frmDM.trMain.InTransaction) then frmDM.trMain.StartTransaction; frmDM.fibdsDepartments.Open; If Not(DMTagIncreased) then Begin DMTagIncreased := True; frmDM.fibdsDepartments.Tag := Succ(frmDM.fibdsDepartments.Tag) End; If (cxSplitter2.State=ssOpened) then Begin fibdsGoodsServices.ReopenLocate('ID'); tlGroups.FullExpand End; fibdsMainList.FullRefresh end; procedure TfrmReceiptsAnal.fibdsGoodsServicesCalcFields(DataSet: TDataSet); begin fibdsGoodsServicesNAME_WITH_AMOUNT.Value := fibdsGoodsServicesNAME.AsString+' ('+FormatFloat('#,##0.00р',fibdsGoodsServicesAMOUNT.AsFloat)+'.)' end; procedure TfrmReceiptsAnal.FormCreate(Sender: TObject); var D, M, Y: Word; begin FName := 'Анализ квитанций'; inherited; DecodeDate(Date, Y, M, D); If (M > 1) then Begin deStart.Date := EncodeDate(Y, M-1, 1); deStop.Date := EncodeDate(Y, M, 1)-1; End else Begin deStart.Date := EncodeDate(Y-1, 12, 1); deStop.Date := EncodeDate(Y, M, 1)-1; End end; procedure TfrmReceiptsAnal.fibdsGoodsServicesBeforeOpen(DataSet: TDataSet); begin TpFIBDataSet(DataSet).ParamByName('START').AsDate := deStart.Date; TpFIBDataSet(DataSet).ParamByName('STOP').AsDate := deStop.Date end; procedure TfrmReceiptsAnal.FormClose(Sender: TObject; var Action: TCloseAction); begin If (frmDM.fibdsDepartments.Tag=1) then frmDM.fibdsDepartments.Close else frmDM.fibdsDepartments.Tag := Pred(frmDM.fibdsDepartments.Tag); inherited end; procedure TfrmReceiptsAnal.cxSplitter2AfterClose(Sender: TObject); begin fibdsMainList.Close; fibdsMainList.SelectSQL[4] := ''; fibdsMainList.DataSource := nil; OpenAll end; procedure TfrmReceiptsAnal.cxSplitter2AfterOpen(Sender: TObject); begin fibdsMainList.Close; fibdsMainList.SelectSQL[4] := 'and (GS.PARENT_ID=:ID)'; fibdsMainList.DataSource := dsGoodsServices; OpenAll end; end.
//*************************************************************************** // // 名称:RTXC.EventSink.pas // 工具:RAD Studio XE6 // 日期:2014/11/8 15:11:42 // 作者:ying32 // QQ :396506155 // MSN :ying_32@live.cn // E-mail:yuanfen3287@vip.qq.com // Website:http://www.ying32.com // //--------------------------------------------------------------------------- // // 备注: // // //*************************************************************************** unit RTXC.EventSink; {$WARN SYMBOL_PLATFORM OFF} interface uses ActiveX, ComObj, Variants, RTXCAPILib_TLB, RTXCModulEinterfaceLib_TLB, RTX.Common; type { TRTXCModuleSiteEventsSink } TRTXCModuleSiteEventsSink = class(TEventSink) public type TOnDataReceivedEvent = procedure(const Key: WideString) of object; TOnViewDataEvent = procedure(const Key: WideString) of object; TOnSendDataResultEvent = procedure(Result: RTXC_MODULE_SEND_DATA_RESULT; Extra: OleVariant) of object; private FOnDataReceived: TOnDataReceivedEvent; FOnViewData: TOnViewDataEvent; FOnSendDataResult: TOnSendDataResultEvent; protected procedure InvokeEvent(DispID: TDispID; var Params: TOleVariantArray); override; public constructor Create(AController: IUnknown); overload; public property OnDataReceived: TOnDataReceivedEvent read FOnDataReceived write FOnDataReceived; property OnViewData: TOnViewDataEvent read FOnViewData write FOnViewData; property OnSendDataResult: TOnSendDataResultEvent read FOnSendDataResult write FOnSendDataResult; end; { TRTXCRootEventsSink } TRTXCRootEventsSink = class(TEventSink) public type TOnLoginResultEvent = procedure(Result: RTXC_LOGIN_RESULT) of object; TOnMyPresenceChangeEvent = procedure(Result: RTXC_RESULT; RTXPresence: RTX_PRESENCE) of object; TOnLogoutResultEvent = procedure(Result: RTXC_RESULT) of object; TOnAccountChangeEvent = procedure of object; TOnPackageComeEvent = procedure(Reserved: Integer) of object; TOnModifyPasswordEvent = procedure(Result: RTXC_MODIFY_PWD_RESULT) of object; TOnMsgCountChangeEvent = procedure(Count: Integer; Forbid: WordBool; const Identifier: WideString; const Key: WideString; const Sender: WideString) of object; TOnExitAppEvent = procedure(const pData: IRTXCData; var pbCanExit: WordBool) of object; private FOnLoginResult: TOnLoginResultEvent; FOnMyPresenceChange: TOnMyPresenceChangeEvent; FOnLogoutResult: TOnLogoutResultEvent; FOnAccountChange: TOnAccountChangeEvent; FOnPackageCome: TOnPackageComeEvent; FOnModifyPassword: TOnModifyPasswordEvent; FOnMsgCountChange: TOnMsgCountChangeEvent; FOnExitApp: TOnExitAppEvent; protected procedure InvokeEvent(DispID: TDispID; var Params: TOleVariantArray); override; public constructor Create(AController: IUnknown); overload; public property OnLoginResult: TOnLoginResultEvent read FOnLoginResult write FOnLoginResult; property OnMyPresenceChange: TOnMyPresenceChangeEvent read FOnMyPresenceChange write FOnMyPresenceChange; property OnLogoutResult: TOnLogoutResultEvent read FOnLogoutResult write FOnLogoutResult; property OnAccountChange: TOnAccountChangeEvent read FOnAccountChange write FOnAccountChange; property OnPackageCome: TOnPackageComeEvent read FOnPackageCome write FOnPackageCome; property OnModifyPassword: TOnModifyPasswordEvent read FOnModifyPassword write FOnModifyPassword; property OnMsgCountChange: TOnMsgCountChangeEvent read FOnMsgCountChange write FOnMsgCountChange; property OnExitApp: TOnExitAppEvent read FOnExitApp write FOnExitApp; end; { TRTXCPresenceEventsSink } TRTXCPresenceEventsSink = class(TEventSink) public type TOnPresenceChangeEvent = procedure(const Account: WideString; RTXPresence: RTX_PRESENCE) of object; private FOnPresenceChange: TOnPresenceChangeEvent; protected procedure InvokeEvent(DispID: TDispID; var Params: TOleVariantArray); override; public constructor Create(AController: IUnknown); overload; public property OnPresenceChange: TOnPresenceChangeEvent read FOnPresenceChange write FOnPresenceChange; end; { TRTXCExStateEventsSink } TRTXCExStateEventsSink = class(TEventSink) public type TOnExStateChangeEvent = procedure(const bstrAccount: WideString; const bstrExStateName: WideString; lExState: Integer) of object; private FOnExStateChange: TOnExStateChangeEvent; protected procedure InvokeEvent(DispID: TDispID; var Params: TOleVariantArray); override; public constructor Create(AController: IUnknown); overload; public property OnExStateChange: TOnExStateChangeEvent read FOnExStateChange write FOnExStateChange; end; { TRTXOrgEventsSink } TRTXOrgEventsSink = class(TEventSink) public type TLClickEvent = procedure(Val: OleVariant; nType: Integer) of object; private FLClickEvent: TLClickEvent; protected procedure InvokeEvent(DispID: TDispID; var Params: TOleVariantArray); override; public constructor Create(AController: IUnknown); overload; public property LClickEvent: TLClickEvent read FLClickEvent write FLClickEvent; end; { TRTXCLicenseEventsSink } TRTXCLicenseEventsSink = class(TEventSink) public type TOnConfigChangedEvent = procedure(IsSucceed: WordBool; const Name: WideString; Val: OleVariant) of object; private FOnConfigChanged: TOnConfigChangedEvent; protected procedure InvokeEvent(DispID: TDispID; var Params: TOleVariantArray); override; public constructor Create(AController: IUnknown); overload; public property OnConfigChanged: TOnConfigChangedEvent read FOnConfigChanged write FOnConfigChanged; end; { TRTXCMDSessionEventsSink } // TEvent = procedure() of object; TRTXCMDSessionEventsSink = class(TEventSink) public type TOnAddParticipantCompleteEvent = procedure(const Participant: WideString; nResult: Integer) of object; TOnConnectCompleteEvent = procedure(const Participant: WideString; nResult: Integer) of object; TOnParticipantChangeEvent = procedure(const Participant: WideString) of object; TOnDisConnectEvent = procedure(const Participant: WideString) of object; TOnByeEvent = procedure(const Participant: WideString) of object; TOnRecvDataEvent = procedure(const Participant: WideString; Data: OleVariant) of object; TOnKickoutEvent = procedure(const Participant: WideString) of object; private FOnAddParticipantComplete: TOnAddParticipantCompleteEvent; FOnConnectComplete: TOnConnectCompleteEvent; FOnParticipantChange: TOnParticipantChangeEvent; FOnDisConnect: TOnDisConnectEvent; FOnBye: TOnByeEvent; FOnRecvData: TOnRecvDataEvent; FOnKickout: TOnKickoutEvent; protected procedure InvokeEvent(DispID: TDispID; var Params: TOleVariantArray); override; public constructor Create(AController: IUnknown); overload; public property OnAddParticipantComplete: TOnAddParticipantCompleteEvent read FOnAddParticipantComplete write FOnAddParticipantComplete; property OnConnectComplete: TOnConnectCompleteEvent read FOnConnectComplete write FOnConnectComplete; property OnParticipantChange: TOnParticipantChangeEvent read FOnParticipantChange write FOnParticipantChange; property OnDisConnect: TOnDisConnectEvent read FOnDisConnect write FOnDisConnect; property OnBye: TOnByeEvent read FOnBye write FOnBye; property OnRecvData: TOnRecvDataEvent read FOnRecvData write FOnRecvData; property OnKickout: TOnKickoutEvent read FOnKickout write FOnKickout; end; { TRTXCMDSessionManagerEventsSink } TRTXCMDSessionManagerEventsSink = class(TEventSink) public type TOnInviteEvent = procedure(const Session: IRTXCMDSession; const VerifyString: WideString) of object; TOnCancelEvent = procedure(const Session: IRTXCMDSession) of object; private FOnInvite: TOnInviteEvent; FOnCancel: TOnCancelEvent; protected procedure InvokeEvent(DispID: TDispID; var Params: TOleVariantArray); override; public constructor Create(AController: IUnknown); overload; public property OnInvite: TOnInviteEvent read FOnInvite write FOnInvite; property OnCancel: TOnCancelEvent read FOnCancel write FOnCancel; end; { TRTXCMFCSupportEventsSink } TRTXCMFCSupportEventsSink = class(TEventSink) public type // OnPreTranslateMessage(MSGPointer: Integer): WordBool 需再考虑更改的 TOnPreTranslateMessageEvent = procedure(MSGPointer: Integer) of object; TOnIdleEvent = procedure(Count: Integer) of object; private FOnPreTranslateMessage: TOnPreTranslateMessageEvent; FOnIdle: TOnIdleEvent; protected procedure InvokeEvent(DispID: TDispID; var Params: TOleVariantArray); override; public constructor Create(AController: IUnknown); overload; public property OnPreTranslateMessage: TOnPreTranslateMessageEvent read FOnPreTranslateMessage write FOnPreTranslateMessage; property OnIdle: TOnIdleEvent read FOnIdle write FOnIdle; end; { TRTXCExtBuddyManagerEventsSink } TRTXCExtBuddyManagerEventsSink = class(TEventSink) public type TOnExtBuddyChangeEvent = procedure(const RTXCExtBuddy: IRTXCExtBuddy) of object; TOnAddNewExtBuddyEvent = procedure(const Account: WideString) of object; private FOnExtBuddyChange: TOnExtBuddyChangeEvent; FOnAddNewExtBuddy: TOnAddNewExtBuddyEvent; protected procedure InvokeEvent(DispID: TDispID; var Params: TOleVariantArray); override; public constructor Create(AController: IUnknown); overload; public property OnExtBuddyChange: TOnExtBuddyChangeEvent read FOnExtBuddyChange write FOnExtBuddyChange; property OnAddNewExtBuddy: TOnAddNewExtBuddyEvent read FOnAddNewExtBuddy write FOnAddNewExtBuddy; end; { TRTXCRTXBuddyManagerEventsSink } TRTXCRTXBuddyManagerEventsSink = class(TEventSink) public type TOnBuddyProfileChangeEvent = procedure(const RTXCRTXBuddy: IRTXCRTXBuddy) of object; TOnQueryExistenceEvent = procedure(const Account: WideString; Existence: WordBool) of object; private FOnBuddyProfileChange: TOnBuddyProfileChangeEvent; FOnQueryExistence: TOnQueryExistenceEvent; protected procedure InvokeEvent(DispID: TDispID; var Params: TOleVariantArray); override; public constructor Create(AController: IUnknown); overload; public property OnBuddyProfileChange: TOnBuddyProfileChangeEvent read FOnBuddyProfileChange write FOnBuddyProfileChange; property OnQueryExistence: TOnQueryExistenceEvent read FOnQueryExistence write FOnQueryExistence; end; { TRTXCRTXBuddyEventsSink } TRTXCRTXBuddyEventsSink = class(TEventSink) public type TOnModifyProfileEvent = procedure(Success: WordBool) of object; private FOnModifyProfile: TOnModifyProfileEvent; protected procedure InvokeEvent(DispID: TDispID; var Params: TOleVariantArray); override; public constructor Create(AController: IUnknown); overload; public property OnModifyProfile: TOnModifyProfileEvent read FOnModifyProfile write FOnModifyProfile; end; { TRTXCSessionManagerEventsSink } TRTXCSessionManagerEventsSink = class(TEventSink) public type TOnQuerySessionInfoCompleteEvent = procedure(const Session: IRTXCSession; Cookie: Integer) of object; TOnSessionAddEvent = procedure(const Session: IRTXCSession) of object; TOnRequestInitiatorEvent = procedure(const Session: IRTXCSession; const Participant: WideString) of object; TOnRegisterSessionEvent = procedure(const Session: IRTXCSession) of object; private FOnQuerySessionInfoComplete: TOnQuerySessionInfoCompleteEvent; FOnSessionAdd: TOnSessionAddEvent; FOnRequestInitiator: TOnRequestInitiatorEvent; FOnRegisterSession: TOnRegisterSessionEvent; protected procedure InvokeEvent(DispID: TDispID; var Params: TOleVariantArray); override; public constructor Create(AController: IUnknown); overload; public property OnQuerySessionInfoComplete: TOnQuerySessionInfoCompleteEvent read FOnQuerySessionInfoComplete write FOnQuerySessionInfoComplete; property OnSessionAdd: TOnSessionAddEvent read FOnSessionAdd write FOnSessionAdd; property OnRequestInitiator: TOnRequestInitiatorEvent read FOnRequestInitiator write FOnRequestInitiator; property OnRegisterSession: TOnRegisterSessionEvent read FOnRegisterSession write FOnRegisterSession; end; { TRTXCSessionEventsSink } TRTXCSessionEventsSink = class(TEventSink) public type TOnParticipantChangeEvent = procedure(const Participant: WideString) of object; TOnTopicChangeEvent = procedure(const Topic: WideString) of object; TOnMessageCountChangeEvent = procedure(MsgCount: Integer) of object; TOnRequestInitiatorEvent = procedure(const Participant: WideString) of object; TOnRequestInitiatorCompleteEvent = procedure(nResult: Integer) of object; TOnInitiatorChangeEvent = procedure(const Initiator: WideString) of object; TOnStateChangeEvent = procedure(State: RTXC_SESSION_STATE) of object; TOnParticipantChangeStateEvent = procedure(const Participant: WideString; State: RTXC_SESSION_STATE) of object; private FOnParticipantChange: TOnParticipantChangeEvent; FOnTopicChange: TOnTopicChangeEvent; FOnMessageCountChange: TOnMessageCountChangeEvent; FOnRequestInitiator: TOnRequestInitiatorEvent; FOnRequestInitiatorComplete: TOnRequestInitiatorCompleteEvent; FOnInitiatorChange: TOnInitiatorChangeEvent; FOnStateChange: TOnStateChangeEvent; FOnParticipantChangeState: TOnParticipantChangeStateEvent; protected procedure InvokeEvent(DispID: TDispID; var Params: TOleVariantArray); override; public constructor Create(AController: IUnknown); overload; public property OnParticipantChange: TOnParticipantChangeEvent read FOnParticipantChange write FOnParticipantChange; property OnTopicChange: TOnTopicChangeEvent read FOnTopicChange write FOnTopicChange; property OnMessageCountChange: TOnMessageCountChangeEvent read FOnMessageCountChange write FOnMessageCountChange; property OnRequestInitiator: TOnRequestInitiatorEvent read FOnRequestInitiator write FOnRequestInitiator; property OnRequestInitiatorComplete: TOnRequestInitiatorCompleteEvent read FOnRequestInitiatorComplete write FOnRequestInitiatorComplete; property OnInitiatorChange: TOnInitiatorChangeEvent read FOnInitiatorChange write FOnInitiatorChange; property OnStateChange: TOnStateChangeEvent read FOnStateChange write FOnStateChange; property OnParticipantChangeState: TOnParticipantChangeStateEvent read FOnParticipantChangeState write FOnParticipantChangeState; end; { TRTXCRTXGroupManagerEventsSink } TRTXCRTXGroupManagerEventsSink = class(TEventSink) public type TOnGroupChangeEvent = procedure(const RTXCRTXGroup: IRTXCRTXGroup) of object; TOnGroupAddEvent = procedure(const RTXCRTXGroup: IRTXCRTXGroup) of object; TOnGroupRemoveEvent = procedure(const RTXCRTXGroup: IRTXCRTXGroup) of object; TOnBuddyAddEvent = procedure(const RTXCRTXGroup: IRTXCRTXGroup; const RTXCRTXBuddy: IRTXCRTXBuddy) of object; TOnBuddyRemoveEvent = procedure(const RTXCRTXGroup: IRTXCRTXGroup; const RTXCRTXBuddy: IRTXCRTXBuddy) of object; private FOnGroupChange: TOnGroupChangeEvent; FOnGroupAdd: TOnGroupAddEvent; FOnGroupRemove: TOnGroupRemoveEvent; FOnBuddyAdd: TOnBuddyAddEvent; FOnBuddyRemove: TOnBuddyRemoveEvent; protected procedure InvokeEvent(DispID: TDispID; var Params: TOleVariantArray); override; public constructor Create(AController: IUnknown); overload; public property OnGroupChange: TOnGroupChangeEvent read FOnGroupChange write FOnGroupChange; property OnGroupAdd: TOnGroupAddEvent read FOnGroupAdd write FOnGroupAdd; property OnGroupRemove: TOnGroupRemoveEvent read FOnGroupRemove write FOnGroupRemove; property OnBuddyAdd: TOnBuddyAddEvent read FOnBuddyAdd write FOnBuddyAdd; property OnBuddyRemove: TOnBuddyRemoveEvent read FOnBuddyRemove write FOnBuddyRemove; end; { TRTXCExtGroupManagerEventsSink } TRTXCExtGroupManagerEventsSink = class(TEventSink) public type TOnGroupChangeEvent = procedure(const RTXCRTXGroup: IRTXCRTXGroup) of object; TOnGroupAddEvent = procedure(const RTXCRTXGroup: IRTXCRTXGroup) of object; TOnGroupRemoveEvent = procedure(const RTXCRTXGroup: IRTXCRTXGroup) of object; TOnBuddyAddEvent = procedure(const RTXCRTXGroup: IRTXCRTXGroup; const RTXCRTXBuddy: IRTXCRTXBuddy) of object; TOnBuddyRemoveEvent = procedure(const RTXCRTXGroup: IRTXCRTXGroup; const RTXCRTXBuddy: IRTXCRTXBuddy) of object; private FOnGroupChange: TOnGroupChangeEvent; FOnGroupAdd: TOnGroupAddEvent; FOnGroupRemove: TOnGroupRemoveEvent; FOnBuddyAdd: TOnBuddyAddEvent; FOnBuddyRemove: TOnBuddyRemoveEvent; protected procedure InvokeEvent(DispID: TDispID; var Params: TOleVariantArray); override; public constructor Create(AController: IUnknown); overload; public property OnGroupChange: TOnGroupChangeEvent read FOnGroupChange write FOnGroupChange; property OnGroupAdd: TOnGroupAddEvent read FOnGroupAdd write FOnGroupAdd; property OnGroupRemove: TOnGroupRemoveEvent read FOnGroupRemove write FOnGroupRemove; property OnBuddyAdd: TOnBuddyAddEvent read FOnBuddyAdd write FOnBuddyAdd; property OnBuddyRemove: TOnBuddyRemoveEvent read FOnBuddyRemove write FOnBuddyRemove; end; implementation { TRTXCModuleSiteEventsSink } constructor TRTXCModuleSiteEventsSink.Create(AController: IInterface); begin inherited Create(AController, _IRTXCModuleSiteEvents); end; procedure TRTXCModuleSiteEventsSink.InvokeEvent(DispID: TDispID; var Params: TOleVariantArray); begin case DispID of -1: Exit; 1 : if Assigned(FOnDataReceived) then FOnDataReceived(Params[0]); 2 : if Assigned(FOnViewData) then FOnViewData(Params[0]); 3 : if Assigned(FOnSendDataResult) then FOnSendDataResult(Params[0], Params[1]); end; end; { TRTXCRootEventsSink } constructor TRTXCRootEventsSink.Create(AController: IInterface); begin inherited Create(AController, _IRTXCRootEvents); end; procedure TRTXCRootEventsSink.InvokeEvent(DispID: TDispID; var Params: TOleVariantArray); var LCanExit: WordBool; begin case DispID of -1: Exit; 1 : if Assigned(FOnLoginResult) then FOnLoginResult(Params[0]); 2 : if Assigned(FOnMyPresenceChange) then FOnMyPresenceChange(Params[0], Params[1]); 3 : if Assigned(FOnLogoutResult) then FOnLogoutResult(Params[0]); 4 : if Assigned(FOnAccountChange) then FOnAccountChange(); 5 : if Assigned(FOnPackageCome) then FOnPackageCome(Params[0]); 6 : if Assigned(FOnModifyPassword) then FOnModifyPassword(Params[0]); 7 : if Assigned(FOnMsgCountChange) then FOnMsgCountChange(Params[0], Params[1], Params[2], Params[4], Params[5]); 8 : if Assigned(FOnExitApp) then begin LCanExit := Params[1]; FOnExitApp(IRTXCData(TVarData(VarAsType(Params[0], varDispatch)).VDispatch), LCanExit); Params[1] := LCanExit; end; end; end; { TRTXCPresenceEventsSink } constructor TRTXCPresenceEventsSink.Create(AController: IInterface); begin inherited Create(AController, _IRTXCPresenceEvents); end; procedure TRTXCPresenceEventsSink.InvokeEvent(DispID: TDispID; var Params: TOleVariantArray); begin case DispID of -1 : Exit; 1 : if Assigned(FOnPresenceChange) then FOnPresenceChange(Params[0], Params[1]); end; end; { TRTXCExStateEventsSink } constructor TRTXCExStateEventsSink.Create(AController: IInterface); begin inherited Create(AController, _IRTXCExStateEvents); end; procedure TRTXCExStateEventsSink.InvokeEvent(DispID: TDispID; var Params: TOleVariantArray); begin case DispID of -1 : Exit; 1 : if Assigned(FOnExStateChange) then FOnExStateChange(Params[0], Params[1], Params[2]); end; end; { TRTXOrgEventsSink } constructor TRTXOrgEventsSink.Create(AController: IInterface); begin inherited Create(AController, _DRTXOrgEvents); end; procedure TRTXOrgEventsSink.InvokeEvent(DispID: TDispID; var Params: TOleVariantArray); begin case DispID of -1 : Exit; 1 : if Assigned(FLClickEvent) then FLClickEvent(Params[0], Params[1]); end; end; { TRTXCLicenseEventsSink } constructor TRTXCLicenseEventsSink.Create(AController: IInterface); begin inherited Create(AController, _IRTXCLicenseEvents); end; procedure TRTXCLicenseEventsSink.InvokeEvent(DispID: TDispID; var Params: TOleVariantArray); begin case DispID of -1 : Exit; 1 : if Assigned(FOnConfigChanged) then FOnConfigChanged(Params[0], Params[1], Params[2]); end; end; { TRTXCMDSessionEventsSink } constructor TRTXCMDSessionEventsSink.Create(AController: IInterface); begin inherited Create(AController, _IRTXCMDSessionEvents); end; procedure TRTXCMDSessionEventsSink.InvokeEvent(DispID: TDispID; var Params: TOleVariantArray); begin case DispID of -1 : Exit; 1 : if Assigned(FOnAddParticipantComplete) then FOnAddParticipantComplete(Params[0], Params[1]); 2 : if Assigned(FOnConnectComplete) then FOnConnectComplete(Params[0], Params[1]); 3 : if Assigned(FOnParticipantChange) then FOnParticipantChange(Params[0]); 4 : if Assigned(FOnDisConnect) then FOnDisConnect(Params[0]); 5 : if Assigned(FOnBye) then FOnBye(Params[0]); 6 : if Assigned(FOnRecvData) then FOnRecvData(Params[0], Params[1]); 7 : if Assigned(FOnKickout) then FOnKickout(Params[0]); end; end; { TRTXCMDSessionManagerEventsSink } constructor TRTXCMDSessionManagerEventsSink.Create(AController: IInterface); begin inherited Create(AController, _IRTXCMDSessionManagerEvents); end; procedure TRTXCMDSessionManagerEventsSink.InvokeEvent(DispID: TDispID; var Params: TOleVariantArray); begin case DispID of -1 : Exit; 1 : if Assigned(FOnInvite) then FOnInvite(IRTXCMDSession(TVarData(VarAsType(Params[0], varDispatch)).VDispatch), Params[1]); 2 : if Assigned(FOnCancel) then FOnCancel(IRTXCMDSession(TVarData(VarAsType(Params[0], varDispatch)).VDispatch)); end; end; { TRTXCMFCSupportEventsSink } constructor TRTXCMFCSupportEventsSink.Create(AController: IInterface); begin inherited Create(AController, _IRTXCMFCSupportEvents); end; procedure TRTXCMFCSupportEventsSink.InvokeEvent(DispID: TDispID; var Params: TOleVariantArray); begin case DispID of -1 : Exit; 1 : if Assigned(FOnPreTranslateMessage) then FOnPreTranslateMessage(Params[0]); 2 : if Assigned(FOnIdle) then FOnIdle(Params[0]); end; end; { TRTXCExtBuddyManagerEventsSink } constructor TRTXCExtBuddyManagerEventsSink.Create(AController: IInterface); begin inherited Create(AController, _IRTXCExtBuddyManagerEvents); end; procedure TRTXCExtBuddyManagerEventsSink.InvokeEvent(DispID: TDispID; var Params: TOleVariantArray); begin case DispID of -1 : Exit; 1 : if Assigned(FOnExtBuddyChange) then FOnExtBuddyChange(IRTXCExtBuddy(TVarData(VarAsType(Params[0], varDispatch)).VDispatch)); 2 : if Assigned(FOnAddNewExtBuddy) then FOnAddNewExtBuddy(Params[0]); end; end; { TRTXCRTXBuddyManagerEventsSink } constructor TRTXCRTXBuddyManagerEventsSink.Create(AController: IInterface); begin inherited Create(AController, _IRTXCRTXBuddyManagerEvents); end; procedure TRTXCRTXBuddyManagerEventsSink.InvokeEvent(DispID: TDispID; var Params: TOleVariantArray); begin case DispID of -1 : Exit; 1 : if Assigned(FOnBuddyProfileChange) then FOnBuddyProfileChange(IRTXCRTXBuddy(TVarData(VarAsType(Params[0], varDispatch)).VDispatch)); 2 : if Assigned(FOnQueryExistence) then FOnQueryExistence(Params[0], Params[1]); end; end; { TRTXCRTXBuddyEventsSink } constructor TRTXCRTXBuddyEventsSink.Create(AController: IInterface); begin inherited Create(AController, _IRTXCRTXBuddyEvents); end; procedure TRTXCRTXBuddyEventsSink.InvokeEvent(DispID: TDispID; var Params: TOleVariantArray); begin case DispID of -1 : Exit; 1 : if Assigned(FOnModifyProfile) then FOnModifyProfile(Params[0]); end; end; { TRTXCSessionManagerEventsSink } constructor TRTXCSessionManagerEventsSink.Create(AController: IInterface); begin inherited Create(AController, _IRTXCSessionManagerEvents); end; procedure TRTXCSessionManagerEventsSink.InvokeEvent(DispID: TDispID; var Params: TOleVariantArray); begin case DispID of -1 : Exit; 1 : if Assigned(FOnQuerySessionInfoComplete) then FOnQuerySessionInfoComplete(IRTXCSession(TVarData(VarAsType(Params[0], varDispatch)).VDispatch), Params[1]); 2 : if Assigned(FOnSessionAdd) then FOnSessionAdd(IRTXCSession(TVarData(VarAsType(Params[0], varDispatch)).VDispatch)); 3 : if Assigned(FOnRequestInitiator) then FOnRequestInitiator(IRTXCSession(TVarData(VarAsType(Params[0], varDispatch)).VDispatch), Params[1]); 4 : if Assigned(FOnRegisterSession) then FOnRegisterSession(IRTXCSession(TVarData(VarAsType(Params[0], varDispatch)).VDispatch)); end; end; { TRTXCSessionEventsSink } constructor TRTXCSessionEventsSink.Create(AController: IInterface); begin inherited Create(AController, _IRTXCSessionEvents); end; procedure TRTXCSessionEventsSink.InvokeEvent(DispID: TDispID; var Params: TOleVariantArray); begin case DispID of -1 : Exit; 1 : if Assigned(FOnParticipantChange) then FOnParticipantChange(Params[0]); 2 : if Assigned(FOnTopicChange) then FOnTopicChange(Params[0]); 3 : if Assigned(FOnMessageCountChange) then FOnMessageCountChange(Params[0]); 4 : if Assigned(FOnRequestInitiator) then FOnRequestInitiator(Params[0]); 5 : if Assigned(FOnRequestInitiatorComplete) then FOnRequestInitiatorComplete(Params[0]); 6 : if Assigned(FOnInitiatorChange) then FOnInitiatorChange(Params[0]); 7 : if Assigned(FOnStateChange) then FOnStateChange(Params[0]); 8 : if Assigned(FOnParticipantChangeState) then FOnParticipantChangeState(Params[0], Params[1]); end; end; { TRTXCRTXGroupManagerEventsSink } constructor TRTXCRTXGroupManagerEventsSink.Create(AController: IInterface); begin inherited Create(AController, _IRTXCRTXGroupManagerEvents); end; procedure TRTXCRTXGroupManagerEventsSink.InvokeEvent(DispID: TDispID; var Params: TOleVariantArray); begin case DispID of -1 : Exit; 1 : if Assigned(FOnGroupChange) then FOnGroupChange(IRTXCRTXGroup(TVarData(VarAsType(Params[0], varDispatch)).VDispatch)); 2 : if Assigned(FOnGroupAdd) then FOnGroupAdd(IRTXCRTXGroup(TVarData(VarAsType(Params[0], varDispatch)).VDispatch)); 3 : if Assigned(FOnGroupRemove) then FOnGroupRemove(IRTXCRTXGroup(TVarData(VarAsType(Params[0], varDispatch)).VDispatch)); 4 : if Assigned(FOnBuddyAdd) then FOnBuddyAdd(IRTXCRTXGroup(TVarData(VarAsType(Params[0], varDispatch)).VDispatch), IRTXCRTXBuddy(TVarData(VarAsType(Params[1], varDispatch)).VDispatch)); 5 : if Assigned(FOnBuddyRemove) then FOnBuddyRemove(IRTXCRTXGroup(TVarData(VarAsType(Params[0], varDispatch)).VDispatch), IRTXCRTXBuddy(TVarData(VarAsType(Params[1], varDispatch)).VDispatch)); end; end; { TRTXCExtGroupManagerEventsSink } constructor TRTXCExtGroupManagerEventsSink.Create(AController: IInterface); begin inherited Create(AController, _IRTXCExtGroupManagerEvents); end; procedure TRTXCExtGroupManagerEventsSink.InvokeEvent(DispID: TDispID; var Params: TOleVariantArray); begin case DispID of -1 : Exit; 1 : if Assigned(FOnGroupChange) then FOnGroupChange(IRTXCRTXGroup(TVarData(VarAsType(Params[0], varDispatch)).VDispatch)); 2 : if Assigned(FOnGroupAdd) then FOnGroupAdd(IRTXCRTXGroup(TVarData(VarAsType(Params[0], varDispatch)).VDispatch)); 3 : if Assigned(FOnGroupRemove) then FOnGroupRemove(IRTXCRTXGroup(TVarData(VarAsType(Params[0], varDispatch)).VDispatch)); 4 : if Assigned(FOnBuddyAdd) then FOnBuddyAdd(IRTXCRTXGroup(TVarData(VarAsType(Params[0], varDispatch)).VDispatch), IRTXCRTXBuddy(TVarData(VarAsType(Params[1], varDispatch)).VDispatch)); 5 : if Assigned(FOnBuddyRemove) then FOnBuddyRemove(IRTXCRTXGroup(TVarData(VarAsType(Params[0], varDispatch)).VDispatch), IRTXCRTXBuddy(TVarData(VarAsType(Params[1], varDispatch)).VDispatch)); end; end; end.
unit SimThyrMain; { SimThyr Project } { (c) J. W. Dietrich, 1994 - 2011 } { (c) Ludwig Maximilian University of Munich 1995 - 2002 } { (c) Ruhr University of Bochum 2005 - 2011 } { This unit provides global GUI functions, toolbar and menubar handling } { Source code released under the BSD License } {$mode objfpc}{$H+}{$R+} interface uses Classes, SysUtils, FileUtil, LResources, Forms, Controls, Graphics, Dialogs, Grids, ExtCtrls, StdActns, StdCtrls, LCLType, Menus, ActnList, SimThyrTypes, SimThyrServices, LaunchDialog, ShowIPS, Simulator, Printers, ComCtrls, LCLIntf, ExtDlgs, SimThyrLog, SimThyrPlot, AboutDialog, ShowAboutModel, StructureParameters, SimThyrPrediction, ScenarioHandler, HandlePreferences, HandleNotifier, LCLProc, LazHelpHTML; type { TSimThyrToolbar } TSimThyrToolbar = class(TForm) ActionList1: TActionList; ApplicationProperties1: TApplicationProperties; CloseMenuItem: TMenuItem; CopyMenuItem: TMenuItem; CutMenuItem: TMenuItem; Divider_1_1: TMenuItem; Divider_2_1: TMenuItem; EditCopy1: TEditCopy; EditCut1: TEditCut; EditDelete1: TEditDelete; EditMenu: TMenuItem; EditPaste1: TEditPaste; EditUndo1: TEditUndo; FileMenu: TMenuItem; IdleTimer1: TIdleTimer; ImageList1: TImageList; MacAboutItem: TMenuItem; AppleMenu: TMenuItem; MacPreferencesItem: TMenuItem; MainMenu1: TMainMenu; HelpMenu: TMenuItem; HelpItem: TMenuItem; Divider_5_1: TMenuItem; Divider_1_3: TMenuItem; Divider_1_2: TMenuItem; AboutModelItem: TMenuItem; Divider_3_2: TMenuItem; ChangeParItem: TMenuItem; IPSItem: TMenuItem; LogItem: TMenuItem; IPSItem2: TMenuItem; SavePictureDialog1: TSavePictureDialog; WinPreferencesItem: TMenuItem; Divider_2_2: TMenuItem; PredictionItem: TMenuItem; PlotItem: TMenuItem; WindowMenu: TMenuItem; PauseItem: TMenuItem; StopItem: TMenuItem; Divider_3_1: TMenuItem; RunItem: TMenuItem; SimulationMenu: TMenuItem; PrintItem: TMenuItem; PageSetupItem: TMenuItem; SaveItem: TMenuItem; QuitMenuItem: TMenuItem; ToolBar1: TToolBar; NewToolButton: TToolButton; OpenToolButton: TToolButton; SaveToolButton: TToolButton; SaveAsToolButton: TToolButton; ToolButton1: TToolButton; PrefsToolButton: TToolButton; ParametersToolButton: TToolButton; RunToolButton: TToolButton; PauseToolButton: TToolButton; StopToolButton: TToolButton; ToolButton2: TToolButton; ToolButton3: TToolButton; ToolButton4: TToolButton; UndoToolButton: TToolButton; CutToolButton: TToolButton; CopyToolButton: TToolButton; PasteToolButton: TToolButton; PrintToolButton: TToolButton; ToolButton9: TToolButton; WinAboutItem: TMenuItem; OnlineInfo: TMenuItem; Divider_0_1: TMenuItem; Divider_0_2: TMenuItem; DeleteMenuItem: TMenuItem; NewMenuItem: TMenuItem; OpenDialog1: TOpenDialog; OpenMenuItem: TMenuItem; PasteMenuItem: TMenuItem; SaveAsItem: TMenuItem; SaveDialog1: TSaveDialog; UndoMenuItem: TMenuItem; procedure AboutModelItemClick(Sender: TObject); procedure CloseMenuItemClick(Sender: TObject); procedure CopyMenuItemClick(Sender: TObject); procedure FormActivate(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure HandleIdle(Sender: TObject; var Done: Boolean); procedure HelpItemClick(Sender: TObject); procedure IdleTimer1Timer(Sender: TObject); procedure IPSItemClick(Sender: TObject); procedure LogItemClick(Sender: TObject); procedure OnlineInfoClick(Sender: TObject); procedure OpenToolButtonClick(Sender: TObject); procedure PageSetupItemClick(Sender: TObject); procedure ParametersToolButtonClick(Sender: TObject); procedure PauseToolButtonClick(Sender: TObject); procedure PlotItemClick(Sender: TObject); procedure PredictionItemClick(Sender: TObject); procedure QuitMenuItemClick(Sender: TObject); procedure RunItemClick(Sender: TObject); procedure SaveAsToolButtonClick(Sender: TObject); procedure SaveToolButtonClick(Sender: TObject); procedure StopToolButtonClick(Sender: TObject); procedure ToolBar1Click(Sender: TObject); procedure NewToolButtonClick(Sender: TObject); procedure PrefsToolButtonClick(Sender: TObject); procedure PrintToolButtonClick(Sender: TObject); procedure UndoMenuItemClick(Sender: TObject); procedure AboutItemClick(Sender: TObject); private { private declarations } public { public declarations } end; tInterfaceLanguage = (English, German); var SimThyrToolbar: TSimThyrToolbar; gInterfaceLanguage: tInterfaceLanguage; j, gIdleCounter: integer; implementation { TSimThyrToolbar } procedure AdaptMenus; var modifierKey: TShiftState; begin {$IFDEF LCLcarbon} modifierKey := [ssMeta]; SimThyrToolbar.WinAboutItem.Visible := false; SimThyrToolbar.Divider_5_1.Visible := false; SimThyrToolbar.Divider_2_2.Visible := false; SimThyrToolbar.Divider_2_2.Visible := false; SimThyrToolbar.WinPreferencesItem.Visible := false; SimThyrToolbar.AppleMenu.Visible := true; {$ELSE} modifierKey := [ssCtrl]; SimThyrToolbar.WinAboutItem.Visible := true; SimThyrToolbar.Divider_5_1.Visible := true; SimThyrToolbar.Divider_2_2.Visible := true; SimThyrToolbar.WinPreferencesItem.Visible := true; SimThyrToolbar.AppleMenu.Visible := false; {$ENDIF} SimThyrToolbar.NewMenuItem.ShortCut:=ShortCut(VK_N, modifierKey); SimThyrToolbar.OpenMenuItem.ShortCut:=ShortCut(VK_O, modifierKey); SimThyrToolbar.CloseMenuItem.ShortCut:=ShortCut(VK_W, modifierKey); SimThyrToolbar.SaveItem.ShortCut:=ShortCut(VK_S, modifierKey); SimThyrToolbar.PrintItem.ShortCut:=ShortCut(VK_P, modifierKey); SimThyrToolbar.QuitMenuItem.ShortCut:=ShortCut(VK_Q, modifierKey); SimThyrToolbar.UndoMenuItem.ShortCut:=ShortCut(VK_Z, modifierKey); SimThyrToolbar.CutMenuItem.ShortCut:=ShortCut(VK_X, modifierKey); SimThyrToolbar.CopyMenuItem.ShortCut:=ShortCut(VK_C, modifierKey); SimThyrToolbar.PasteMenuItem.ShortCut:=ShortCut(VK_V, modifierKey); SimThyrToolbar.RunItem.ShortCut:=ShortCut(VK_R, modifierKey); end; procedure AdaptLanguages; begin if gInterfaceLanguage = English then begin ; end else begin ; end; AdaptMenus; end; procedure TSimThyrToolbar.FormCreate(Sender: TObject); begin AdaptLanguages; gIdleCounter := 0; end; procedure TSimThyrToolbar.FormShow(Sender: TObject); begin if (SimulationSettings <> nil) and showSettingsAtStartup then begin SimulationSettings.ShowOnTop; SimulationSettings.SetFocus; end; end; procedure TSimThyrToolbar.HandleIdle(Sender: TObject; var Done: Boolean); begin if simready then begin {$IFDEF LCLcarbon} SimThyrLogWindow.ValuesGrid.BeginUpdate; SimThyrLogWindow.ValuesGrid.EndUpdate(true); {$ENDIF} if gIdleCounter < 2 then begin SimThyrToolbar.SendToBack; SimulationSettings.ShowOnTop; SimulationSettings.SetFocus; gIdleCounter := gIdleCounter + 1; end; application.ProcessMessages; end else; end; procedure TSimThyrToolbar.HelpItemClick(Sender: TObject); begin OpenURL(HELP_URL); end; procedure TSimThyrToolbar.IdleTimer1Timer(Sender: TObject); begin if simready then begin {$IFDEF LCLcarbon} SimThyrLogWindow.ValuesGrid.BeginUpdate; SimThyrLogWindow.ValuesGrid.EndUpdate(true); {$ENDIF} application.ProcessMessages; Notice.Hide; end; end; procedure TSimThyrToolbar.FormActivate(Sender: TObject); begin if (SimulationSettings <> nil) and gStartup and showSettingsAtStartup then begin SimulationSettings.ShowOnTop; SimulationSettings.SetFocus; end; if gStartup then gStartup := false; end; procedure TSimThyrToolbar.CloseMenuItemClick(Sender: TObject); var theForm: TForm; begin theForm := Screen.ActiveForm; {if (simready and theForm = SimThyrLogWindow) then SimThread.free;} theForm.Close; end; procedure TSimThyrToolbar.AboutModelItemClick(Sender: TObject); begin AboutModelForm.Show; end; procedure TSimThyrToolbar.CopyMenuItemClick(Sender: TObject); var theForm: TForm; begin theForm := Screen.ActiveForm; if theForm = SimThyrLogWindow then SimThyrLogWindow.CopyCells else if theForm = IPSForm then IPSForm.CopyImage else if theForm = ValuesPlot then ValuesPlot.CopyChart(Sender) else ActionList1.Actions[2].Execute; end; procedure TSimThyrToolbar.IPSItemClick(Sender: TObject); begin IPSForm.Show; end; procedure TSimThyrToolbar.LogItemClick(Sender: TObject); begin SimThyrLogWindow.Show; end; procedure TSimThyrToolbar.OnlineInfoClick(Sender: TObject); begin OpenURL(BASE_URL); end; procedure TSimThyrToolbar.OpenToolButtonClick(Sender: TObject); var theFile: File of Byte; fileData: Array of Byte; theString, theFileName: String; theSize: Int64; i: integer; begin OpenDialog1.FilterIndex := 2; if OpenDialog1.Execute then begin theFileName := OpenDialog1.FileName; case OpenDialog1.FilterIndex of 1: bell; 2: ReadScenario(theFileName); end; {AssignFile(theFile, theFileName); FileMode := 0; {$i-} Reset(theFile); {$i+} if IOResult <> 0 then begin bell; exit ; end else begin } {StatusBar1.SimpleText := StatusStringReading; theSize := FileSize(theFileName); SetLength(fileData, theSize) ; BlockRead(theFile, fileData[0], theSize) ;} {CloseFile(theFile) ;} {FileContent := AnsiString(fileData); PreviewPanel.text := FileContent; StatusBar1.SimpleText := StatusStringDataRead; } {end;} end; end; procedure TSimThyrToolbar.PageSetupItemClick(Sender: TObject); begin ShowImplementationMessage; end; procedure TSimThyrToolbar.ParametersToolButtonClick(Sender: TObject); begin StructureParametersDlg.HandleStrucPars; end; procedure TSimThyrToolbar.PauseToolButtonClick(Sender: TObject); begin if haltsim then SimThread.Restart else SimThread.Pause; end; procedure TSimThyrToolbar.PlotItemClick(Sender: TObject); begin ValuesPlot.Show; end; procedure TSimThyrToolbar.PredictionItemClick(Sender: TObject); begin Prediction.Show; end; procedure TSimThyrToolbar.QuitMenuItemClick(Sender: TObject); begin {SavePreferences;} if SimThread <> nil then SimThread.Terminate; application.Terminate; end; procedure TSimThyrToolbar.RunItemClick(Sender: TObject); begin if simready = true then SimulationSettings.ShowOnTop else if haltsim then SimThread.Restart else bell; end; procedure TSimThyrToolbar.SaveAsToolButtonClick(Sender: TObject); begin ShowImplementationMessage; end; procedure TSimThyrToolbar.SaveToolButtonClick(Sender: TObject); var theForm: TForm; theDelimiter: Char; theFileName: String; begin theForm := Screen.ActiveForm; if theForm = IPSForm then begin if SavePictureDialog1.Execute then try theFileName := SavePictureDialog1.FileName; IPSForm.Image1.Picture.SaveToFile(theFileName); finally ; end; end else begin if theForm = SimThyrToolbar then SaveDialog1.FilterIndex := 4 else if theForm = SimThyrLogWindow then SaveDialog1.FilterIndex := 1; if SaveDialog1.Execute then begin theFileName := SaveDialog1.FileName; case SaveDialog1.FilterIndex of 1: theDelimiter := kTab; 2: if DecimalSeparator = ',' then theDelimiter := ';' else theDelimiter := ','; 3: theDelimiter := 'd'; 4: theDelimiter := ' '; end; case SaveDialog1.FilterIndex of 1..3: SimThyrLogWindow.SaveGrid(theFileName, theDelimiter); 4: SaveScenario(theFilename); end; end; end; end; procedure TSimThyrToolbar.StopToolButtonClick(Sender: TObject); begin haltsim := true; graphready := false; nmax := 0; if SimThread <> nil then begin SimThread.WaitFor; {ensure that simulation thread has completed last cycle} SimThread.Terminate; end; SetBaseVariables; SetLength(gResultMatrix, 0, 9); SimThyrLogWindow.InitGrid; ClearPrediction; DrawPlot(true); end; procedure TSimThyrToolbar.ToolBar1Click(Sender: TObject); begin end; procedure TSimThyrToolbar.NewToolButtonClick(Sender: TObject); begin ShowImplementationMessage; end; procedure TSimThyrToolbar.PrefsToolButtonClick(Sender: TObject); begin PreferencesDialog.ShowPreferences; end; procedure TSimThyrToolbar.PrintToolButtonClick(Sender: TObject); var theForm: TForm; begin theForm := Screen.ActiveForm; if theForm = ValuesPlot then ValuesPlot.PrintChart(Sender) else ShowImplementationMessage; end; procedure TSimThyrToolbar.UndoMenuItemClick(Sender: TObject); begin end; procedure TSimThyrToolbar.AboutItemClick(Sender: TObject); begin AboutWindow.ShowAbout; end; initialization {$I simthyrmain.lrs} gParameterLabel[i_pos] := 'i'; gParameterLabel[t_pos] := 'Time'; gParameterLabel[TSH_pos] := 'Portal TRH'; gParameterLabel[pTSH_pos] := 'Pituitary TSH'; gParameterLabel[TSH_pos] := 'Serum TSH'; gParameterLabel[TT4_pos] := 'Serum total T4'; gParameterLabel[FT4_pos] := 'Serum free T4'; gParameterLabel[TT3_pos] := 'Serum total T3'; gParameterLabel[FT3_pos] := 'Serum free T3'; gParameterLabel[cT3_pos] := 'Central T3'; for j := i_pos to cT3_pos do gParameterFactor[j] := 1; end.
Program TugasBesar_TransKalimantan; uses crt,sysutils; type pesanpesawat=record tnama:string; tasal:string; ttujuan:string; tpulangpergi:string; ttglberangkat:string; ttglpulang:string; tjumlahpenumpang:integer; tharga:integer; ttotal:integer; end; type pesantravel=record tnama:string; tasal:string; ttujuan:string; ttglberangkat:string; tjumlahpenumpang:integer; tharga:integer; ttotal:integer; end; type user=record tnama:string; tuser:string; tpass:string; tpesanpesawat:array[1..50] of pesanpesawat; tpesantravel:array[1..50] of pesantravel; ttotalpesan:integer; end; type pesawatadmin=record tnomor:integer; tnama:string; tharga:longint; tsisatiket:longint; end; type traveladmin=record tnomor:integer; tnama:string; tplat:string; tharga:longint; tsisatiket:longint; end; var arruser:array[1..50] of user; arrpesawat:array[1..50] of pesawatadmin; arrtravel:array[1..50] of traveladmin; jumlahuser:integer; i,j:integer; pesan:string; sisapesawat1,sisapesawat2,sisapesawat3,sisatravel1,sisatravel2,sisatravel3:integer; totpesawat,tottravel:integer; procedure pesawat_admin; label pesawatadmin; var menu:integer; y,i,j,x,z:integer; nama:string; harga,sisa:longint; nomor:integer; edit:integer; nmedit:string; nmredit:integer; hedit,sedit:longint; begin pesawatadmin: clrscr; gotoxy(45,5);write('================================'); gotoxy(45,6);write(' T R A N S K A L I M A N T A N '); gotoxy(45,7);write('================================'); gotoxy(10,9);write('Selamat Datang, Admin :)'); gotoxy(53,9);write ('+--------------+'); gotoxy(53,10);write('| DATA PESAWAT |'); gotoxy(53,11);write('+--------------+'); gotoxy(53,13);write('[1] JUMLAH PESAWAT'); gotoxy(53,14);write('[2] INPUT DATA PESAWAT'); gotoxy(53,15);write('[3] EDIT DATA PESAWAT'); gotoxy(53,17);write('[0] KEMBALI'); gotoxy(53,19);write('Silakan pilih menu : ');readln(menu); while (menu<>1) and (menu<>2) and (menu<>3) and (menu<>0) do begin goto pesawatadmin; end; case menu of 1:begin gotoxy(45,21);write('Jumlah Pesawat : ',totpesawat); y:=2; for i:=1 to totpesawat do begin gotoxy(45,21+y);write('Nomor Pesawat : ',arrpesawat[i].tnomor); gotoxy(45,22+y);write('Nama Pesawat : ',arrpesawat[i].tnama); gotoxy(45,23+y);write('Harga Tiket : ',arrpesawat[i].tharga); gotoxy(45,24+y);write('Sisa Tiket : ',arrpesawat[i].tsisatiket); y:=y+5; end; readln; goto pesawatadmin; end; 2:begin gotoxy(45,21);write('Nomor Pesawat : ');readln(nomor); z:=1; while (z<=totpesawat) and (nomor<>arrpesawat[z].tnomor) do begin z:=z+1; end; if nomor=arrpesawat[z].tnomor then begin gotoxy(45,23);write('Nomor Pesawat Sudah Terdaftar, Nomor Tidak Boleh Sama');readln; goto pesawatadmin; end else begin gotoxy(45,22);write('Nama Pesawat : ');readln(nama); if nama='' then begin gotoxy(45,24);write('Nama pesawat tidak boleh kosong.');readln; goto pesawatadmin; end; gotoxy(45,23);write('Harga Tiket : ');readln(harga); gotoxy(45,24);write('Sisa Tiket : ');readln(sisa); arrpesawat[totpesawat+ 1].tnomor:=nomor; arrpesawat[totpesawat+1].tnama:=nama; arrpesawat[totpesawat+1].tharga:=harga; arrpesawat[totpesawat+1].tsisatiket:=sisa; totpesawat:=totpesawat+1; gotoxy(45,26);write('Data Pesawat sudah disimpan.');readln; end; goto pesawatadmin; end; 3:begin gotoxy(45,21);write('Masukkan Nomor Pesawat : ');readln(nmredit); x:=1; while (x<=totpesawat) and (nmredit<>arrpesawat[x].tnomor) do begin x:=x+1; end; if nmredit=arrpesawat[x].tnomor then begin gotoxy(45,22);write('[1] Nama Pesawat : ',arrpesawat[x].tnama); gotoxy(45,23);write('[2] Harga Tiket : ',arrpesawat[x].tharga); gotoxy(45,24);write('[3] Sisa Tiket : ',arrpesawat[x].tsisatiket); gotoxy(45,26);write('Pilih nomor yang ingin di-edit : ');readln(edit); case edit of 1:begin gotoxy(46,28);write('Nama Pesawat Baru : ');readln(nmedit); arrpesawat[x].tnama:=nmedit; gotoxy(46,30);write('Data baru sudah disimpan.');readln; x:=0; end; 2:begin gotoxy(46,28);write('Harga Tiket Pesawat Baru : ');readln(hedit); arrpesawat[x].tharga:=hedit; gotoxy(46,30);write('Data baru sudah disimpan.');readln; x:=0; end; 3:begin gotoxy(46,28);write('Sisa Tiket Pesawat : ');readln(sedit); arrpesawat[x].tsisatiket:=sedit; gotoxy(46,30);write('Data baru sudah disimpan.');readln; x:=0; end; end; end else begin gotoxy(45,23);write('Nomor Pesawat Tidak Ditemukan.');readln; goto pesawatadmin; end; goto pesawatadmin; end; 0:begin exit; end; end; readln; exit; end; procedure travel_admin; label traveladmin; var menu:integer; y,i,j,x,z:integer; nama,plat:string; harga,sisa:longint; nomor:integer; edit:integer; nmedit,pedit:string; nmredit:integer; hedit,sedit:longint; begin traveladmin: clrscr; gotoxy(45,5);write('================================'); gotoxy(45,6);write(' T R A N S K A L I M A N T A N '); gotoxy(45,7);write('================================'); gotoxy(10,9);write('Selamat Datang, Admin :)'); gotoxy(53,9);write ('+-------------+'); gotoxy(53,10);write('| DATA TRAVEL |'); gotoxy(53,11);write('+-------------+'); gotoxy(53,13);write('[1] JUMLAH TRAVEL'); gotoxy(53,14);write('[2] INPUT DATA TRAVEL'); gotoxy(53,15);write('[3] EDIT DATA TRAVEL'); gotoxy(53,17);write('[0] KEMBALI'); gotoxy(53,19);write('Silakan pilih menu : ');readln(menu); while (menu<>1) and (menu<>2) and (menu<>3) and (menu<>0) do begin goto traveladmin; end; case menu of 1:begin gotoxy(45,21);write('Jumlah Travel : ',tottravel); y:=2; for i:=1 to tottravel do begin gotoxy(45,21+y);write('Nomor Travel : ',arrtravel[i].tnomor); gotoxy(45,22+y);write('Nama Travel : ',arrtravel[i].tnama); gotoxy(45,23+y);write('Plat Travel : ',arrtravel[i].tplat); gotoxy(45,24+y);write('Harga Tiket : ',arrtravel[i].tharga); gotoxy(45,25+y);write('Sisa Tiket : ',arrtravel[i].tsisatiket); y:=y+7; end; readln; goto traveladmin; end; 2:begin gotoxy(45,21);write('Nomor Travel : ');readln(nomor); z:=1; while (z<=tottravel) and (nomor<>arrtravel[z].tnomor) do begin z:=z+1; end; if nomor=arrtravel[z].tnomor then begin gotoxy(45,23);write('Nomor Travel Sudah Terdaftar, Nomor Tidak Boleh Sama.');readln; goto traveladmin; end else begin gotoxy(45,22);write('Nama Travel : ');readln(nama); if nama='' then begin gotoxy(45,24);write('Nama travel tidak boleh kosong.');readln; goto traveladmin; end; gotoxy(45,23);write('Plat Travel : ');readln(plat); if plat='' then begin gotoxy(45,25);write('Plat travel tidak boleh kosong.');readln; goto traveladmin; end; gotoxy(45,24);write('Harga Tiket : ');readln(harga); gotoxy(45,25);write('Sisa Tiket : ');readln(sisa); arrtravel[tottravel+1].tnomor:=nomor; arrtravel[tottravel+1].tnama:=nama; arrtravel[tottravel+1].tplat:=plat; arrtravel[tottravel+1].tharga:=harga; arrtravel[tottravel+1].tsisatiket:=sisa; tottravel:=tottravel+1; gotoxy(45,27);write('Data Travel sudah disimpan.');readln; end; goto traveladmin; end; 3:begin gotoxy(45,21);write('Masukkan Nomor Travel : ');readln(nmredit); x:=1; while (x<=tottravel) and (nmredit<>arrtravel[x].tnomor) do begin x:=x+1; end; if nmredit=arrtravel[x].tnomor then begin gotoxy(45,22);write('[1] Nama Travel : ',arrtravel[x].tnama); gotoxy(45,23);write('[2] Plat Travel : ',arrtravel[x].tplat); gotoxy(45,24);write('[3] Harga Tiket : ',arrtravel[x].tharga); gotoxy(45,25);write('[4] Sisa Tiket : ',arrtravel[x].tsisatiket); gotoxy(45,27);write('Pilih nomor yang ingin di-edit : ');readln(edit); case edit of 1:begin gotoxy(46,29);write('Nama Travel Baru : ');readln(nmedit); arrtravel[x].tnama:=nmedit; gotoxy(46,31);write('Data baru sudah disimpan.');readln; x:=0; end; 2:begin gotoxy(46,29);write('Plat Travel Baru : ');readln(pedit); arrtravel[x].tplat:=pedit; gotoxy(46,31);write('Data baru sudah disimpan.');readln; x:=0; end; 3:begin gotoxy(46,29);write('Harga Tiket Travel Baru : ');readln(hedit); arrtravel[x].tharga:=hedit; gotoxy(46,31);write('Data baru sudah disimpan.');readln; x:=0; end; 4:begin gotoxy(46,29);write('Sisa Tiket Travel : ');readln(sedit); arrtravel[x].tsisatiket:=sedit; gotoxy(46,31);write('Data baru sudah disimpan.');readln; x:=0; end; end; end else begin gotoxy(45,23);write('Nomor Travel Tidak Ditemukan.');readln; goto traveladmin; end; goto traveladmin; end; 0:begin exit; end; end; readln; exit; end; procedure pesawat_user(idx:integer;a:string); begin clrscr; gotoxy(45,5);write('================================'); gotoxy(45,6);write(' T R A N S K A L I M A N T A N '); gotoxy(45,7);write('================================'); gotoxy(10,9);write('Selamat Datang, ',a); gotoxy(53,9);write ('+---------------+'); gotoxy(53,10);write('| TIKET PESAWAT |'); gotoxy(53,11);write('+---------------+'); readln; exit; end; procedure travel_user(idx:integer;a:string); begin clrscr; gotoxy(45,5);write('================================'); gotoxy(45,6);write(' T R A N S K A L I M A N T A N '); gotoxy(45,7);write('================================'); gotoxy(10,9);write('Selamat Datang, ',a); gotoxy(53,9);write ('+--------------+'); gotoxy(53,10);write('| TIKET TRAVEL |'); gotoxy(53,11);write('+--------------+'); readln; exit; end; procedure riwayat_user(idx:integer;a:string); begin clrscr; gotoxy(45,5);write('================================'); gotoxy(45,6);write(' T R A N S K A L I M A N T A N '); gotoxy(45,7);write('================================'); gotoxy(10,9);write('Selamat Datang, ',a); gotoxy(55,9);write ('+---------+'); gotoxy(55,10);write('| RIWAYAT |'); gotoxy(55,11);write('+---------+'); readln; exit; end; procedure login;forward; procedure awal;forward; procedure menu_user(user:integer); label menuuser; var menu:integer; logout:string; begin menuuser: clrscr; gotoxy(45,5);write('================================'); gotoxy(45,6);write(' T R A N S K A L I M A N T A N '); gotoxy(45,7);write('================================'); gotoxy(10,9);write('Selamat Datang, ',arruser[user].tnama,' :)'); gotoxy(54,9);write ('+-------------+'); gotoxy(54,10);write('| MENU USER |'); gotoxy(54,11);write('+-------------+'); gotoxy(50,13);write('[1] TIKET PESAWAT'); gotoxy(50,14);write('[2] TIKET TRAVEL'); gotoxy(50,15);write('[3] RIWAYAT'); gotoxy(50,17);write('[0] LOGOUT'); gotoxy(50,19);write('Silakan Pilih Menu : ');readln(menu); while (menu<>1) and (menu<>2) and (menu<>3) and (menu<>0) do begin goto menuuser; end; case menu of 1:begin pesawat_user(user,arruser[user].tnama); goto menuuser; end; 2:begin travel_user(user,arruser[user].tnama); goto menuuser; end; 3:begin riwayat_user(user,arruser[user].tnama); goto menuuser; end; 0:begin gotoxy(45,21);write('Apakah Anda Ingin Logout? (Y/N) : ');readln(logout); if (logout='Y') or (logout='y') then begin awal; exit; end else if (logout='N') or (logout='n') then begin goto menuuser; end else begin gotoxy(55,23);write('Inputan Salah.');readln; goto menuuser; end; end; end; end; procedure menu_admin; var duser:integer; menu:integer; y:integer; kata1,kata2,kalimat:string; logout:string; begin clrscr; gotoxy(45,5);write('================================'); gotoxy(45,6);write(' T R A N S K A L I M A N T A N '); gotoxy(45,7);write('================================'); gotoxy(10,9);write('Selamat Datang, Admin :)'); gotoxy(55,9);write ('+------------+'); gotoxy(55,10);write('| MENU ADMIN |'); gotoxy(55,11);write('+------------+'); gotoxy(50,13);write('[1] DATA USER'); gotoxy(50,14);write('[2] DATA PESAWAT'); gotoxy(50,15);write('[3] DATA TRAVEL'); gotoxy(50,17);write('[0] LOGOUT'); gotoxy(50,19);write('Silakan Pilih Menu : ');readln(menu); while (menu<>1) and (menu<>2) and (menu<>3) and (menu<>0) do begin menu_admin; end; case menu of 1:begin gotoxy(45,21);write('Jumlah User : ',jumlahuser); y:=2; for duser:=1 to jumlahuser do begin gotoxy(45,21+y);write('Nama : ',arruser[duser].tnama); gotoxy(45,22+y);write('Username : ',arruser[duser].tuser); y:=y+3; end; readln; menu_admin; end; 2:begin pesawat_admin; menu_admin; end; 3:begin travel_admin; menu_admin; end; 0:begin gotoxy(45,21);write('Apakah Anda Ingin Logout? (Y/N) : ');readln(logout); if (logout='Y') or (logout='y') then begin awal; exit; end else if (logout='N') or (logout='n') then begin menu_admin; end else begin gotoxy(55,23);write('Inputan Salah.');readln; menu_admin end; end; end; end; procedure login; var akun:string; nama,userbaru,passbaru,user,pass:string; i,j:integer; begin clrscr; gotoxy(45,5);write('================================'); gotoxy(45,6);write(' T R A N S K A L I M A N T A N '); gotoxy(45,7);write('================================'); gotoxy(45,9);write('Sudah Punya Akun? [y/n] : ');readln(akun); while (akun<>'y') and (akun<>'n') and (akun<>'Y') and (akun<>'N') do begin login; end; if akun='y' then begin gotoxy(45,11);write('Username : ');readln(user); if user='' then begin gotoxy(45,13);write('Username Tidak Boleh Kosong.');readln; login; end else if (user='admin') or (user='Admin') then begin gotoxy(45,12);write('Password : ');readln(pass); if (pass='admin') or (pass='Admin') then begin menu_admin; exit; end else begin gotoxy(45,14);write('Password Admin Salah.');readln; login; end; end else begin i:=1; while (i<=jumlahuser) and (user<>arruser[i].tuser) do begin i:=i+1; end; if user=arruser[i].tuser then begin gotoxy(45,12);write('Password : ');readln(pass); if pass='' then begin gotoxy(45,14);write('Password Tidak Boleh Kosong.');readln; login; end else if pass=arruser[i].tpass then begin menu_user(i); end else begin gotoxy(45,14);write('Password Salah.');readln; login; end; end else begin gotoxy(45,13);write('Username Tidak Terdaftar.');readln; login; end; end; end else if akun='n' then begin gotoxy(45,11);write('================'); gotoxy(45,12);write('DAFTAR AKUN BARU'); gotoxy(45,13);write('================'); gotoxy(45,15);write('Nama : ');readln(nama); if nama='' then begin gotoxy(45,17);write('Nama Tidak Boleh Kosong.');readln; login; end else begin gotoxy(45,16);write('Username : ');readln(userbaru); if userbaru='' then begin gotoxy(45,18);write('Username Tidak Boleh Kosong.');readln; login; end else begin j:=1; while (j<=jumlahuser) and (userbaru<>arruser[j].tuser) do begin j:=j+1; end; if userbaru=arruser[j].tuser then begin gotoxy(45,18);write('Username Sudah Digunakan, Gunakan Username Lain.');readln; login; end else begin gotoxy(45,17);write('Password : ');readln(passbaru); if passbaru='' then begin gotoxy(45,19);write('Password Tidak Boleh Kosong.');readln; login; end else begin arruser[jumlahuser+1].tnama:=nama; arruser[jumlahuser+1].tuser:=userbaru; arruser[jumlahuser+1].tpass:=passbaru; jumlahuser:=jumlahuser+1; gotoxy(45,19);write('Selamat Anda Berhasil Terdaftar, Silakan Login.');readln; login; end; end; end; end; end; end; procedure awal; var menu:longint; keluar:char; ch:char; begin clrscr; gotoxy(45,5);write('================================'); gotoxy(45,6);write(' T R A N S K A L I M A N T A N '); gotoxy(45,7);write('================================'); gotoxy(50,13);write('[L] LOGIN'); gotoxy(50,15);write('[ESC] EXIT'); repeat ch:=readkey; until (ch=#108) or (ch=#027); write(ch); case ch of #108:login; #027:begin gotoxy(45,20);write('Anda Yakin Ingin Keluar? (Y/N)'); repeat keluar:=readkey; until (keluar=#121) or (keluar=#110); write(keluar); case keluar of #121:halt(1); #110:awal; end; end; end; end; begin clrscr; awal; end.
{ ClickFORMS (C) Copyright 1998 - 2010, Bradford Technologies, Inc. All Rights Reserved. Purpose: A control to display a generated image of a document page. } unit UControlPageImage; interface uses Windows, Classes, Controls, ExtCtrls, Graphics, Messages, Types, UContainer, UGlobals; type /// summary: Displays an image of a document page. TPageImage = class(TImage) private FDocument: TContainer; FMargins: TRect; FMouseInControl: Boolean; FPageUID: PageUID; FScale: Double; procedure DrawActiveCell(const Canvas: TCanvas); procedure GenerateImage; procedure SetDocument(const Value: TContainer); procedure SetPageUID(const Value: PageUID); procedure SetScale(const Value: Double); protected procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER; procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE; procedure Paint; override; public constructor Create(AOwner: TComponent); override; procedure Update; override; published property Document: TContainer read FDocument write SetDocument; property Margins: TRect read FMargins write FMargins; property PageUID: PageUID read FPageUID write SetPageUID; property Scale: Double read FScale write SetScale; end; procedure Register; implementation uses EurekaLog, Forms, Dialogs, SysUtils, UCell, UEditor, UPage, UUtil1; type /// summary: Grants access to the control canvas of a TImage control. /// remarks: TImage unwittingly blocks access to the TGraphicControl canvas. TGraphicControlFriend = class(TGraphicControl) end; // --- Unit ------------------------------------------------------------------ procedure Register; begin RegisterComponents('Bradford', [TPageImage]); end; // --- TPageImage ------------------------------------------------------------ constructor TPageImage.Create(AOwner: TComponent); begin FMargins := Rect(10, 10, 10, 10); // designer margins FScale := 1; inherited; end; /// summary: Draws the active cell and cell editor. procedure TPageImage.DrawActiveCell(const Canvas: TCanvas); var Cell: TBaseCell; DataBoundCell: TDataBoundCell; Index: Integer; begin if Assigned(FDocument.docActiveCell) then begin Cell := nil; // the active cell is on this page if TPageUID.IsEqual(FPageUID, TPageUID.Create(FDocument.docActiveCell.ParentDataPage as TDocPage)) then begin Cell := FDocument.docActiveCell end // the active cell is data bound to a cell on this page, making it also active else if (FDocument.docActiveCell is TDataBoundCell) then begin DataBoundCell := FDocument.docActiveCell as TDataBoundCell; for Index := 0 to DataBoundCell.DataLinkCount - 1 do if TPageUID.IsEqual(FPageUID, TPageUID.Create(DataBoundCell.DataLinks[Index].ParentDataPage as TDocPage)) then Cell := DataBoundCell.DataLinks[Index]; end; // draw the active cell if Assigned(Cell) then Cell.DrawZoom(Canvas, cNormScale, Screen.PixelsPerInch, True); end; end; /// summary: Generates an image graphic of the page. procedure TPageImage.GenerateImage; var Bitmap: TBitmap; Dest: TRect; Page: TDocPage; Viewport: TRect; begin Bitmap := TBitmap.Create; try if TPageUID.IsValid(FPageUID, FDocument) then begin // set pixel format to save on memory Bitmap.PixelFormat := pf16bit; // calculate page size with margins Page := FDocument.docForm[FPageUID.FormIdx].frmPage[FPageUID.PageIdx]; Viewport := Rect(0, 0, Page.pgDesc.PgWidth, Page.pgDesc.PgHeight); // width & height Viewport := ScaleRect(Viewport, cNormScale, Screen.PixelsPerInch); // scale to 96 dpi Viewport := Rect(0, 0, Viewport.Right + cMarginWidth, Viewport.Bottom + cTitleHeight); // add margins // generate bitmap image of page Bitmap.Width := Viewport.Right - Viewport.Left; Bitmap.Height := Viewport.Bottom - Viewport.Top; Page.pgDisplay.PgBody.DrawInView(Bitmap.Canvas, Viewport, Screen.PixelsPerInch); // get rid of the margins Dest := Rect(-cMarginWidth, -cTitleHeight, Viewport.Right - cMarginWidth, Viewport.Bottom - cTitleHeight); Bitmap.Canvas.CopyRect(Dest, Bitmap.Canvas, Viewport); Bitmap.Width := Bitmap.Width - cMarginWidth; Bitmap.Height := Bitmap.Height - cTitleHeight; // draw current cell if its on this page DrawActiveCell(Bitmap.Canvas); // apply scaling if (FScale <> 1) then begin Viewport := Rect(0, 0, Bitmap.Width, Bitmap.Height); Dest := Rect(Viewport.Left, Viewport.Top, Trunc(Viewport.Right * FScale), Trunc(Viewport.Bottom * FScale)); //SetStretchBltMode(Bitmap.Canvas.Handle, STRETCH_DELETESCANS); // low quality but faster SetStretchBltMode(Bitmap.Canvas.Handle, HALFTONE); // high quality but slower Bitmap.Canvas.CopyRect(Dest, Bitmap.Canvas, Viewport); Bitmap.Width := Dest.Right - Dest.Left; Bitmap.Height := Dest.Bottom - Dest.Top; end; end; // assign the graphic Picture.Graphic := Bitmap; except on E: EOutOfMemory do ShowMessage('Due to memory constraints, not all of the pages could be shown.'); on E: Exception do ShowMessage(E.Message); end; FreeAndNil(Bitmap); end; /// summary: Sets the document from which the image will be generated. procedure TPageImage.SetDocument(const Value: TContainer); begin FPageUID := TPageUID.Null; FDocument := Value; Update; end; /// summary: Sets the page from which the image will be generated. procedure TPageImage.SetPageUID(const Value: PageUID); var Page: TDocPage; begin FPageUID := Value; if TPageUID.IsValid(FPageUID, FDocument) then begin Page := TPageUID.GetPage(FPageUID, FDocument); Hint := Page.FPgTitleName; ShowHint := True; end; Update; end; /// summary: Sets the scale of the generated image. procedure TPageImage.SetScale(const Value: Double); begin if (FScale <> Value) then begin FScale := Value; Update; end; end; /// summary: Invalidates the control when the mouse enters. procedure TPageImage.CMMouseEnter(var Message: TMessage); begin inherited; if not FMouseInControl and Enabled then begin FMouseInControl := True; Invalidate; end; end; /// summary: Invalidates the control when the mouse leaves. procedure TPageImage.CMMouseLeave(var Message: TMessage); begin inherited; if FMouseInControl and Enabled then begin FMouseInControl := False; Invalidate; end; end; /// summary: Paints the image with a mouse hover effect when the mouse is overtop. procedure TPageImage.Paint; var ControlCanvas: TCanvas; begin inherited; if (FMouseInControl) and Enabled then begin // TImage unwittingly blocks access to the TGraphicControl.Canvas. // (Technically an unsafe typecast, but therein lies the secret) ControlCanvas := TGraphicControlFriend(Self).Canvas; ControlCanvas.Pen.Width := 3; ControlCanvas.Pen.Style := psSolid; ControlCanvas.Pen.Color := clHotLight; ControlCanvas.Brush.Style := bsClear; ControlCanvas.Rectangle(0, 0, Width, Height); end; end; /// summary: Updates the displayed image. procedure TPageImage.Update; begin GenerateImage; inherited; end; initialization EurekaLog.SetCustomErrorMessage(TTextCell, @TTextCell.DoSetText, @TTextCell.CheckTextOverflow, ''); EurekaLog.SetCustomErrorMessage(TMLnTextCell, @TMLnTextCell.DoSetText, @TMLnTextCell.CheckTextOverflow, ''); EurekaLog.SetCustomErrorMessage(TGridCell, @TGridCell.DoSetText, @TGridCell.CheckTextOverflow, ''); end.
unit BankTest; interface uses dbTest, dbObjectTest, ObjectTest; type TBankTest = class (TdbObjectTestNew) published procedure ProcedureLoad; override; procedure Test; override; end; TBank = class(TObjectTest) function InsertDefault: integer; override; public function InsertUpdateBank(const Id, Code: Integer; Name, MFO, SWIFT, IBAN: string; JuridicalId: integer): integer; constructor Create; override; end; implementation uses DB, UtilConst, TestFramework, SysUtils, JuridicalTest; { TBankTest } procedure TBankTest.ProcedureLoad; begin ScriptDirectory := ProcedurePath + 'OBJECTS\Bank\'; inherited; end; procedure TBankTest.Test; var Id: integer; RecordCount: Integer; ObjectTest: TBank; begin ObjectTest := TBank.Create; // Проверили выполнение Get для 0 записи ObjectTest.GetRecord(0); // Получим список RecordCount := ObjectTest.GetDataSet.RecordCount; // Вставка Банка Id := ObjectTest.InsertDefault; try // Получение данных о банке with ObjectTest.GetRecord(Id) do Check((FieldByName('Name').AsString = 'Банк'), 'Не сходятся данные Id = ' + FieldByName('id').AsString); finally ObjectTest.Delete(Id); end; end; {TBank} constructor TBank.Create; begin inherited; spInsertUpdate := 'gpInsertUpdate_Object_Bank'; spSelect := 'gpSelect_Object_Bank'; spGet := 'gpGet_Object_Bank'; end; function TBank.InsertDefault: integer; var JuridicalId: Integer; begin JuridicalId := TJuridical.Create.GetDefault; result := InsertUpdateBank(0, -1, 'Банк', 'МФО', 'SWIFT', 'IBAN', JuridicalId); inherited; end; function TBank.InsertUpdateBank; begin FParams.Clear; FParams.AddParam('ioId', ftInteger, ptInputOutput, Id); FParams.AddParam('inCode', ftInteger, ptInput, Code); FParams.AddParam('inName', ftString, ptInput, Name); FParams.AddParam('inMFO', ftString, ptInput, MFO); FParams.AddParam('inSWIFT', ftString, ptInput, SWIFT); FParams.AddParam('inIBAN', ftString, ptInput, IBAN); FParams.AddParam('inJuridicalId', ftInteger, ptInput, JuridicalId); result := InsertUpdate(FParams); end; initialization TestFramework.RegisterTest('Объекты', TBankTest.Suite); end.
unit AddRandBytesUnit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls; type TFormRandomBytes = class(TForm) lblFile: TLabel; edtFile: TEdit; btnBrowse: TButton; lblCount: TLabel; edtByteCount: TEdit; udCount: TUpDown; chkRandom: TCheckBox; btnSave: TButton; dlgOpen: TOpenDialog; procedure btnBrowseClick(Sender: TObject); procedure btnSaveClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var FormRandomBytes: TFormRandomBytes; implementation {$R *.DFM} procedure TFormRandomBytes.btnBrowseClick(Sender: TObject); begin if dlgOpen.Execute then edtFile.Text := dlgOpen.FileName; end; procedure TFormRandomBytes.btnSaveClick(Sender: TObject); var I: Integer; F: TFileStream; B: Byte; begin F := TFileStream.Create(edtFile.Text, fmOpenWrite); try F.Seek(0, soFromEnd); if chkRandom.Checked then Randomize else B := 0; Screen.Cursor := crHourGlass; for I := 1 to udCount.Position do begin if chkRandom.Checked then B := Trunc(Random * 256); F.WriteBuffer(B, SizeOf(Byte)); end; finally Screen.Cursor := crDefault; F.Free; end; Application.MessageBox('Save Success.', 'Hint', MB_OK + MB_ICONINFORMATION); end; procedure TFormRandomBytes.FormCreate(Sender: TObject); begin Application.Title := Caption; end; end.
unit AbstractFactory.Interfaces.IAbstractFactory; interface uses AbstractFactory.Interfaces.IAbstractProductA, AbstractFactory.Interfaces.IAbstractProductB; // The Abstract Factory interface declares a set of methods that return // different abstract products. These products are called a family and are // related by a high-level theme or concept. Products of one family are // usually able to collaborate among themselves. A family of products may // have several variants, but the products of one variant are incompatible // with products of another. // A interface Abstract Factory declara um conjunto de métodos que retorna diferentes // tipos de produtos abstratos. // Estes produtos são chamados de familia e são relacionados em uma camada superior // Produtos da mesma familia são frequentemente capazes de colaborar entre si. // Uma familia de produtos pode ter muitas variações, mas os produtos de uma variação é incompativel // com os produtos de uma outra. type IAbstractFactory = interface ['{54F6B347-C70C-40DC-B3D5-37E49C2A4095}'] function CreateProductA: IAbstractProductA; function CreateProductB: IAbstractProductB; end; implementation end.
{***************************************************************************} { } { Delphi.Mocks } { } { Copyright (C) 2011 Vincent Parrett } { } { 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 Delphi.Mocks.Proxy.TypeInfo; interface uses System.Rtti, System.SysUtils, System.Generics.Collections, System.TypInfo, Delphi.Mocks, Delphi.Mocks.Proxy, Delphi.Mocks.WeakReference, Delphi.Mocks.Interfaces, Delphi.Mocks.Behavior; type TProxy = class(TWeakReferencedObject, IWeakReferenceableObject, IInterface, IProxy, IVerify) private FTypeInfo : PTypeInfo; FParentProxy : IWeakReference<IProxy>; FInterfaceProxies : TDictionary<TGUID, IProxy>; FAllowRedefineBehaviorDefinitions : Boolean; FVirtualInterface : IProxyVirtualInterface; FName : string; FMethodData : TDictionary<string, IMethodData>; FBehaviorMustBeDefined : Boolean; FSetupMode : TSetupMode; //behavior setup FNextBehavior : TBehaviorType; FReturnValue : TValue; FNextFunc : TExecuteFunc; FExceptClass : ExceptClass; FExceptionMessage : string; //expectation setup FNextExpectation : TExpectationType; FTimes : Cardinal; FBetween : array[0..1] of Cardinal; FIsStubOnly : boolean; FQueryingInterface : boolean; FQueryingInternalInterface : boolean; FAutoMocker : IAutoMock; protected type TProxyVirtualInterface = class(TVirtualInterface, IInterface, IProxyVirtualInterface) private FProxy : IWeakReference<IProxy>; function SupportsIInterface: Boolean; protected //IProxyVirtualInterface function QueryProxy(const IID: TGUID; out Obj : IProxy) : HRESULT; function QueryInterfaceWithOwner(const IID: TGUID; out Obj; const ACheckOwner : Boolean): HRESULT; overload; function QueryInterfaceWithOwner(const IID: TGUID; const ACheckOwner : Boolean): HRESULT; overload; function _AddRef: Integer; override; stdcall; function _Release: Integer; override; stdcall; public procedure AfterConstruction; override; //TVirtualInterface overrides constructor Create(const AProxy : IProxy; const AInterface: Pointer; const InvokeEvent: TVirtualInterfaceInvokeEvent); function QueryInterface(const IID: TGUID; out Obj): HRESULT; override; stdcall; end; protected procedure SetParentProxy(const AProxy : IProxy); function SupportsIInterface: Boolean; function QueryImplementedInterface(const IID: TGUID; out Obj): HRESULT; stdcall; function QueryInterface(const IID: TGUID; out Obj): HRESULT; virtual; stdcall; function _AddRef: Integer; override; stdcall; function _Release: Integer; override; stdcall; //IProxy function ProxyInterface : IInterface; function ProxySupports(const Instance: IInterface; const IID: TGUID) : boolean; virtual; function ProxyFromType(const ATypeInfo : PTypeInfo) : IProxy; virtual; procedure AddImplement(const AProxy : IProxy; const ATypeInfo : PTypeInfo); virtual; procedure DoInvoke(Method: TRttiMethod; const Args: TArray<TValue>; out Result: TValue); procedure SetBehaviorMustBeDefined(const AValue : Boolean); //IVerify procedure Verify(const message : string = ''); procedure VerifyAll(const message : string = ''); procedure ResetCalls; function CheckExpectations: string; function GetMethodData(const AMethodName : string; const ATypeName: string) : IMethodData; overload; procedure ClearSetupState; public procedure AfterConstruction; override; constructor Create(const ATypeInfo : PTypeInfo; const AAutoMocker : IAutoMock = nil; const AIsStubOnly : boolean = false); virtual; destructor Destroy; override; end; implementation uses Delphi.Mocks.Utils, Delphi.Mocks.When, Delphi.Mocks.MethodData, Delphi.Mocks.ParamMatcher; {TProxy} procedure TProxy.AddImplement(const AProxy: IProxy; const ATypeInfo : PTypeInfo); begin if FInterfaceProxies.ContainsKey(GetTypeData(ATypeInfo).Guid) then raise EMockProxyAlreadyImplemented.Create('The mock already implements ' + ATypeInfo.NameStr); FInterfaceProxies.Add(GetTypeData(ATypeInfo).Guid, AProxy); AProxy.SetParentProxy(Self); end; // //procedure TProxy.After(const AMethodName, AAfterMethodName: string); //begin // raise Exception.Create('Not implemented'); //end; // //function TProxy.After(const AMethodName: string): IWhen<T>; //begin // raise Exception.Create('Not implemented'); //end; // //procedure TProxy.AtLeast(const AMethodName: string; const times: Cardinal); //var // methodData : IMethodData; //begin // pInfo := TypeInfo(T); // methodData := GetMethodData(AMethodName,pInfo.NameStr); // Assert(methodData <> nil); // methodData.AtLeast(times); // ClearSetupState; //end; // //function TProxy.AtLeast(const times: Cardinal): IWhen<T>; //begin // FSetupMode := TSetupMode.Expectation; // FNextExpectation := TExpectationType.AtLeastWhen; // FTimes := times; // result := TWhen<T>.Create(Self.Proxy); //end; // //procedure TProxy.AtLeastOnce(const AMethodName: string); //var // methodData : IMethodData; //begin // pInfo := TypeInfo(T); // methodData := GetMethodData(AMethodName,pInfo.NameStr); // Assert(methodData <> nil); // methodData.AtLeastOnce; // ClearSetupState; //end; // //function TProxy.AtLeastOnce: IWhen<T>; //begin // FSetupMode := TSetupMode.Expectation; // FNextExpectation := TExpectationType.AtLeastOnceWhen; // FTimes := 1; // result := TWhen<T>.Create(Self.Proxy); //end; // //procedure TProxy.AtMost(const AMethodName: string; const times: Cardinal); //var // methodData : IMethodData; //begin // pInfo := TypeInfo(T); // methodData := GetMethodData(AMethodName,pInfo.NameStr); // Assert(methodData <> nil); // methodData.AtMost(times); // ClearSetupState; //end; // //function TProxy.AtMost(const times: Cardinal): IWhen<T>; //begin // FSetupMode := TSetupMode.Expectation; // FNextExpectation := TExpectationType.AtMostWhen; // FTimes := times; // result := TWhen<T>.Create(Self.Proxy); //end; // //procedure TProxy.Before(const AMethodName, ABeforeMethodName: string); //begin // raise Exception.Create('not implemented'); //end; // //function TProxy.Before(const AMethodName: string): IWhen<T>; //begin // raise Exception.Create('not implemented'); //end; // //procedure TProxy.Between(const AMethodName: string; const a, b: Cardinal); //var // methodData : IMethodData; //begin // pInfo := TypeInfo(T); // methodData := GetMethodData(AMethodName,pInfo.NameStr); // Assert(methodData <> nil); // methodData.Between(a,b); // ClearSetupState; //end; // //function TProxy.Between(const a, b: Cardinal): IWhen<T>; //begin // FSetupMode := TSetupMode.Expectation; // FNextExpectation := TExpectationType.BetweenWhen; // FBetween[0] := a; // FBetween[1] := b; // result := TWhen<T>.Create(Self.Proxy); // //end; procedure TProxy.AfterConstruction; begin inherited; end; function TProxy.CheckExpectations: string; var methodData : IMethodData; report : string; begin Result := ''; for methodData in FMethodData.Values do begin report := ''; if not methodData.Verify(report) then begin if Result <> '' then Result := Result + #13#10; Result := Result + report ; end; end; end; procedure TProxy.ClearSetupState; begin FSetupMode := TSetupMode.None; FReturnValue := TValue.Empty; FExceptClass := nil; FNextFunc := nil; end; constructor TProxy.Create(const ATypeInfo : PTypeInfo; const AAutoMocker : IAutoMock; const AIsStubOnly : boolean); var selfProxy : IProxy; begin inherited Create; FName := ATypeInfo.NameStr; FAutoMocker := AAutoMocker; FParentProxy := nil; FVirtualInterface := nil; FSetupMode := TSetupMode.None; FBehaviorMustBeDefined := False; FMethodData := TDictionary<string,IMethodData>.Create; FIsStubOnly := AIsStubOnly; FInterfaceProxies := TDictionary<TGUID, IProxy>.Create; FTypeInfo := ATypeInfo; case FTypeInfo.Kind of //Create our proxy interface object, which will implement our interface T tkInterface : begin selfProxy := Self; FVirtualInterface := TProxyVirtualInterface.Create(selfProxy, FTypeInfo, Self.DoInvoke); end; end; end; destructor TProxy.Destroy; begin FVirtualInterface := nil; FMethodData.Clear; FMethodData.Free; FInterfaceProxies.Clear; FInterfaceProxies.Free; FParentProxy := nil; inherited; end; procedure TProxy.DoInvoke(Method: TRttiMethod; const Args: TArray<TValue>; out Result: TValue); var methodData : IMethodData; pInfo : PTypeInfo; matchers : TArray<IMatcher>; begin pInfo := FTypeInfo; case FSetupMode of TSetupMode.None: begin //record actual behavior methodData := GetMethodData(method.Name,pInfo.NameStr); Assert(methodData <> nil); methodData.RecordHit(Args,Method.ReturnType,Method,Result); end; TSetupMode.Behavior: begin try matchers := TMatcherFactory.GetMatchers; if Length(matchers) > 0 then if Length(matchers) < Length(Args) -1 then raise EMockSetupException.Create('Setup called with Matchers but on on all parameters : ' + Method.Name); //record desired behavior //first see if we know about this method methodData := GetMethodData(method.Name,pInfo.NameStr); Assert(methodData <> nil); case FNextBehavior of TBehaviorType.WillReturn: begin case Method.MethodKind of mkProcedure, mkDestructor, mkClassProcedure, mkClassDestructor, mkSafeProcedure : raise EMockSetupException.CreateFmt('Setup.WillReturn called on [%s] method [%s] which does not have a return value.', [MethodKindToStr(Method.MethodKind), Method.Name]); //Method kinds which have a return value. mkFunction, mkConstructor, mkClassFunction, mkClassConstructor, mkOperatorOverload, mkSafeFunction: ; end; //We don't test for the return type being valid as XE5 and below have a RTTI bug which does not return //a return type for function which reference their own class/interface. Even when RTTI is specified on //the declaration and forward declaration. if (FReturnValue.IsEmpty) then raise EMockSetupException.CreateFmt('Setup.WillReturn call on method [%s] was not passed a return value.', [Method.Name]); methodData.WillReturnWhen(Args, FReturnValue, matchers); end; TBehaviorType.WillRaise: begin methodData.WillRaiseAlways(FExceptClass,FExceptionMessage); end; TBehaviorType.WillExecuteWhen : begin methodData.WillExecuteWhen(FNextFunc,Args, matchers); end; end; finally ClearSetupState; end; end; TSetupMode.Expectation: begin try //record expectations //first see if we know about this method methodData := GetMethodData(method.Name,pInfo.NameStr); Assert(methodData <> nil); matchers := TMatcherFactory.GetMatchers; case FNextExpectation of OnceWhen : methodData.OnceWhen(Args, matchers); NeverWhen : methodData.NeverWhen(Args, matchers) ; AtLeastOnceWhen : methodData.AtLeastOnceWhen(Args, matchers); AtLeastWhen : methodData.AtLeastWhen(FTimes,args, matchers); AtMostOnceWhen : methodData.AtLeastOnceWhen(Args, matchers); AtMostWhen : methodData.AtMostWhen(FTimes,args, matchers); BetweenWhen : methodData.BetweenWhen(FBetween[0],FBetween[1],Args, matchers) ; ExactlyWhen : methodData.ExactlyWhen(FTimes,Args, matchers); BeforeWhen : raise exception.Create('not implemented') ; AfterWhen : raise exception.Create('not implemented'); end; finally ClearSetupState; end; end; end; end; //procedure TProxy.Exactly(const AMethodName: string; const times: Cardinal); //var // methodData : IMethodData; //begin // methodData := GetMethodData(AMethodName, FTypeInfo.NameStr); // Assert(methodData <> nil); // methodData.Exactly(times); // ClearSetupState; //end; // //function TProxy.GetBehaviorMustBeDefined: boolean; //begin // Result := FBehaviorMustBeDefined; //end; function TProxy.GetMethodData(const AMethodName: string; const ATypeName: string): IMethodData; var methodName : string; setupParams: TSetupMethodDataParameters; begin methodName := LowerCase(AMethodName); if FMethodData.TryGetValue(methodName,Result) then exit; setupParams := TSetupMethodDataParameters.Create(FIsStubOnly, FBehaviorMustBeDefined, FAllowRedefineBehaviorDefinitions); {$IFNDEF NEXTGEN} Result := TMethodData.Create(string(FTypeInfo.Name), AMethodName, setupParams, FAutoMocker); {$ELSE} Result := TMethodData.Create(FTypeInfo.NameFld.ToString, AMethodName, setupParams, FAutoMocker); {$ENDIF} FMethodData.Add(methodName,Result); end; function TProxy.QueryImplementedInterface(const IID: TGUID; out Obj): HRESULT; var virtualProxy : IProxy; begin Result := E_NOINTERFACE; if FQueryingInternalInterface then Exit; FQueryingInternalInterface := True; try //Otherwise look in the list of interface proxies that might have been implemented if (FInterfaceProxies.ContainsKey(IID)) then begin virtualProxy := FInterfaceProxies.Items[IID]; Result := virtualProxy.ProxyInterface.QueryInterface(IID, Obj); if result = S_OK then Exit; end; {$Message 'TODO: Need to query the parent, but exclude ourselves and any other children which have already been called.'} //Call the parent. if FParentProxy <> nil then Result := FParentProxy.Data.QueryInterface(IID, obj); finally FQueryingInternalInterface := False; end; end; //procedure TProxy.Never(const AMethodName: string); //var // methodData : IMethodData; //begin // pInfo := TypeInfo(T); // methodData := GetMethodData(AMethodName, pInfo.NameStr); // Assert(methodData <> nil); // methodData.Never; // ClearSetupState; //end; // //function TProxy.Never: IWhen<T>; //begin // FSetupMode := TSetupMode.Expectation; // FNextExpectation := TExpectationType.NeverWhen; // result := TWhen<T>.Create(Self.Proxy); //end; // //function TProxy.Once: IWhen<T>; //begin // FSetupMode := TSetupMode.Expectation; // FNextExpectation := TExpectationType.OnceWhen; // result := TWhen<T>.Create(Self.Proxy); //end; // //procedure TProxy.Once(const AMethodName: string); //var // methodData : IMethodData; //begin // methodData := GetMethodData(AMethodName,pInfo.NameStr); // Assert(methodData <> nil); // methodData.Once; // ClearSetupState; //end; //function TProxy.Proxy: TObject; //var // virtualProxy : IInterface; //begin // if FVirtualInterface = nil then // raise EMockNoProxyException.CreateFmt('Error casting to interface [%s], proxy does not appear to implememnt T', [FTypeInfo.NameStr]); // // if FVirtualInterface.QueryInterface(GetTypeData(FTypeInfo).Guid, result) <> 0 then // raise EMockNoProxyException.CreateFmt('Error casting to interface, proxy does not appear to implememnt T', [FTypeInfo.NameStr]); //end; function TProxy.QueryInterface(const IID: TGUID; out Obj): HRESULT; begin Result := E_NOINTERFACE; //If we are already querying this interface, leave. if FQueryingInterface then Exit; FQueryingInterface := True; try //The interface requested might be one of this classes interfaces. E.g. IProxy Result := inherited QueryInterface(IID, Obj); //If we have found the interface then return it. if Result = S_OK then Exit; finally FQueryingInterface := False; end; end; procedure TProxy.ResetCalls; var methodData : IMethodData; begin for methodData in FMethodData.Values do begin methodData.ResetCalls; end; end; procedure TProxy.SetBehaviorMustBeDefined(const AValue: boolean); begin FBehaviorMustBeDefined := AValue; end; procedure TProxy.SetParentProxy(const AProxy : IProxy); begin FParentProxy := TWeakReference<IProxy>.Create(AProxy); end; function TProxy.SupportsIInterface: Boolean; begin Result := (FParentProxy = nil); end; function TProxy.ProxyFromType(const ATypeInfo: PTypeInfo): IProxy; var interfaceID : TGUID; begin //Get the GUID of the type the proxy needs to support interfaceID := GetTypeData(ATypeInfo).Guid; //If we support the passed in type then return ourselves. if ProxySupports(FVirtualInterface, interfaceID) then begin Result := Self; Exit; end; //Are our children the proxy for this type? if FInterfaceProxies.ContainsKey(interfaceID) then begin //Remember that the virtual interface will be of the passed in type, therefore //return its proxy. Result := FInterfaceProxies.Items[interfaceID].ProxyFromType(ATypeInfo); Exit; end; raise EMockNoProxyException.CreateFmt('Error - No Proxy of type [%s] was found.', [ATypeInfo.NameStr]); end; function TProxy.ProxySupports(const Instance: IInterface; const IID: TGUID): boolean; begin //We support the proxy if we have a virtual interface, which supports the passed in //interface. As the virtual interface is built to support mulitple interfaces we //need to ask it not check the other implementations. Result := (FVirtualInterface <> nil) and Supports(FVirtualInterface, IID, False); end; function TProxy.ProxyInterface: IInterface; begin if FVirtualInterface = nil then raise EMockNoProxyException.CreateFmt('Error casting to interface [%s], proxy does not appear to implememnt T', [FTypeInfo.NameStr]); if FVirtualInterface.QueryInterface(GetTypeData(FTypeInfo).Guid, result) <> 0 then raise EMockNoProxyException.CreateFmt('Error casting to interface [%s], proxy does not appear to implememnt T', [FTypeInfo.NameStr]); end; procedure TProxy.Verify(const message: string); var msg : string; begin msg := CheckExpectations; if msg <> '' then raise EMockVerificationException.Create(message + #13#10 + msg); end; //function TProxy.WillExecute(const func: TExecuteFunc): IWhen<T>; //begin // FSetupMode := TSetupMode.Behavior; // FNextBehavior := TBehaviorType.WillExecuteWhen; // FNextFunc := func; // result := TWhen<T>.Create(Self.Proxy); //end; // //procedure TProxy.WillExecute(const AMethodName: string; const func: TExecuteFunc); //var // methodData : IMethodData; // pInfo : PTypeInfo; //begin // //actually record the behaviour here! // pInfo := TypeInfo(T); // methodData := GetMethodData(AMethodName,pInfo.NameStr); // Assert(methodData <> nil); // methodData.WillExecute(func); // ClearSetupState; //end; // //function TProxy.WillRaise(const exceptionClass: ExceptClass;const message : string): IWhen<T>; //begin // FSetupMode := TSetupMode.Behavior; // FNextBehavior := TBehaviorType.WillRaise; // FExceptClass := exceptionClass; // FExceptionMessage := message; // result := TWhen<T>.Create(Self.Proxy); //end; // //procedure TProxy.WillRaise(const AMethodName: string; const exceptionClass: ExceptClass;const message : string); //var // methodData : IMethodData; // pInfo : PTypeInfo; //begin // //actually record the behaviour here! // pInfo := TypeInfo(T); // methodData := GetMethodData(AMethodName, pInfo.NameStr); // Assert(methodData <> nil); // methodData.WillRaiseAlways(exceptionClass,message); // ClearSetupState; //end; // //function TProxy.WillReturn(const value: TValue): IWhen<T>; //begin // FSetupMode := TSetupMode.Behavior; // FReturnValue := value; // FNextBehavior := TBehaviorType.WillReturn; // result := TWhen<T>.Create(Self.Proxy); //end; // //procedure TProxy.WillReturnDefault(const AMethodName : string; const value : TValue); //var // methodData : IMethodData; // pInfo : PTypeInfo; //begin // //actually record the behaviour here! // pInfo := TypeInfo(T); // methodData := GetMethodData(AMethodName,pInfo.NameStr); // Assert(methodData <> nil); // methodData.WillReturnDefault(value); // ClearSetupState; //end; function TProxy._AddRef: Integer; begin result := inherited; end; function TProxy._Release: Integer; begin result := inherited; end; { TProxy.TProxyVirtualInterface } procedure TProxy.TProxyVirtualInterface.AfterConstruction; begin inherited; end; constructor TProxy.TProxyVirtualInterface.Create(const AProxy : IProxy; const AInterface: Pointer; const InvokeEvent: TVirtualInterfaceInvokeEvent); begin //Create a weak reference to our owner proxy. This is the proxy who implements //all the mocking interfaces required to setup, and verify us. FProxy := TWeakReference<IProxy>.Create(AProxy); inherited Create(Ainterface, InvokeEvent); end; function TProxy.TProxyVirtualInterface.QueryInterface(const IID: TGUID; out Obj): HRESULT; begin //The default query interface will ask the owner for the implementing virtual //interface for the type being queried for. This allows a virtual interface of //IInterfaceOne to support IInterfaceTwo when asked. Use this when looking for //the implementing virtual interface, use QueryProxy when looking for the //owning proxy of the implemented type. Result := QueryInterfaceWithOwner(IID, Obj, True); end; function TProxy.TProxyVirtualInterface.QueryInterfaceWithOwner(const IID: TGUID; out Obj; const ACheckOwner: Boolean): HRESULT; begin //See if we support the passed in interface. if IsEqualGUID(IID, IInterface) and not SupportsIInterface then Result := E_NOINTERFACE else Result := inherited QueryInterface(IID, Obj); //If we don't support the interface, then we need to look to our owner to see //who does implement it. This allows for a single proxy to implement multiple //interfaces at once. if (ACheckOwner) and (Result <> 0) then begin if FProxy <> nil then Result := FProxy.Data.QueryImplementedInterface(IID, Obj); end; end; function TProxy.TProxyVirtualInterface.QueryInterfaceWithOwner(const IID: TGUID; const ACheckOwner: Boolean): HRESULT; var dud : IInterface; begin Result := QueryInterfaceWithOwner(IID, dud, ACheckOwner); end; function TProxy.TProxyVirtualInterface.QueryProxy(const IID: TGUID; out Obj : IProxy): HRESULT; begin Result := E_NOINTERFACE; //If this virtual proxy (and only this virtual proxy) supports the passed in //interface, return the proxy who owns us. if QueryInterfaceWithOwner(IID, Obj, False) <> 0 then Result := FProxy.QueryInterface(IProxy, Obj); end; function TProxy.TProxyVirtualInterface.SupportsIInterface: Boolean; begin if FProxy <> nil then Result := FProxy.Data.SupportsIInterface else Result := True; end; function TProxy.TProxyVirtualInterface._AddRef: Integer; begin result := inherited; end; function TProxy.TProxyVirtualInterface._Release: Integer; begin result := inherited; end; procedure TProxy.VerifyAll(const message: string); var proxy : IProxy; interfaceV : IVerify; begin //Verify ourselves. Verify(message); //Now verify all our children. for proxy in FInterfaceProxies.Values.ToArray do if Supports(proxy, IVerify, interfaceV) then interfaceV.Verify(message); end; end.
unit _TaskFrame; interface uses _ClickToEditFrame, _EditableTimeFrame, Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Buttons; type TTaskFrame = class(TFrame) private { Private declarations } FTaskNumber: Integer; public { Public declarations } published TaskPanel: TPanel; StartBtn: TSpeedButton; StopBtn: TSpeedButton; DeleteButton: TSpeedButton; TaskName: TClickToEdit; TaskTime: TEditableTime; KeyLabel: TLabel; procedure StartBtnClick(Sender: TObject); procedure DeleteButtonClick(Sender: TObject); procedure StopBtnClick(Sender: TObject); procedure SetTaskNumber(NewTaskNumber: Integer); property TaskNumber: Integer read FTaskNumber write SetTaskNumber; end; implementation uses Main; {$R *.dfm} procedure TTaskFrame.SetTaskNumber(NewTaskNumber: Integer); begin // Set the internal field FTaskNumber := NewTaskNumber; // Display as a number, or as a letter (tasks 10..35 are A..Z) If (NewTaskNumber < 10) Or (NewTaskNumber > 35) Then KeyLabel.Caption := IntToStr(NewTaskNumber) Else KeyLabel.Caption := Chr(NewTaskNumber - 10 + Ord('A')); end; procedure TTaskFrame.StartBtnClick(Sender: TObject); begin MainForm.SetActiveTask(Self.TaskNumber); end; procedure TTaskFrame.StopBtnClick(Sender: TObject); begin MainForm.SetActiveTask(-1); end; procedure TTaskFrame.DeleteButtonClick(Sender: TObject); begin MainForm.DeleteTask(Self.TaskNumber); end; end.
unit depscan.MainForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Menus, Depscan.Db, Vcl.ComCtrls; type TMainForm = class(TForm) MainMenu: TMainMenu; File1: TMenuItem; miNewScan: TMenuItem; miOpenDb: TMenuItem; N1: TMenuItem; miExit: TMenuItem; SaveDialog: TSaveDialog; OpenDialog: TOpenDialog; miCloseDb: TMenuItem; lbImages: TListBox; edtQuickfilter: TEdit; pcImageDetails: TPageControl; tsExports: TTabSheet; tsImports: TTabSheet; tsClients: TTabSheet; lbExports: TListBox; lbImports: TListBox; lbClients: TListBox; procedure miExitClick(Sender: TObject); procedure miNewScanClick(Sender: TObject); procedure miOpenDbClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure miCloseDbClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure edtQuickfilterChange(Sender: TObject); procedure lbImagesClick(Sender: TObject); protected FDb: TDepscanDb; FSelectedImage: TImageId; procedure ReloadImages; procedure SetSelectedImage(const AValue: TImageId); function LbGetSelectedImage: TImageId; procedure LbSetSelectedImage(const AValue: TImageId); procedure ReloadDetails; procedure ReloadExports; procedure ReloadImports; procedure ReloadClients; public procedure Refresh; property SelectedImage: TImageId read FSelectedImage write SetSelectedImage; end; var MainForm: TMainForm; implementation uses UITypes, UniStrUtils, SystemUtils, FilenameUtils, depscan.ScanSetup, depscan.ScanProgress; {$R *.dfm} resourcestring sConfirmDbOverwrite = 'File already exists. Do you want to overwrite it?'; procedure TMainForm.FormDestroy(Sender: TObject); begin if FDb <> nil then FreeAndNil(FDb); end; procedure TMainForm.FormShow(Sender: TObject); begin FSelectedImage := 0; Refresh; end; procedure TMainForm.miNewScanClick(Sender: TObject); var NewDb: TDepscanDb; begin if not IsPositiveResult(ScanSetupForm.ShowModal) then exit; if not SaveDialog.Execute then exit; if FileExists(SaveDialog.Filename) then begin if MessageBox(Self.Handle, PChar(sConfirmDbOverwrite), PChar(self.Caption), MB_ICONQUESTION + MB_YESNO) <> ID_YES then exit; DeleteFile(SaveDialog.Filename); end; ScanProgressForm.Folders.Assign(ScanSetupForm.mmFolders.Lines); ScanProgressForm.Exts.Assign(ScanSetupForm.mmExts.Lines); NewDb := ScanProgressForm.ModalCreateDb(SaveDialog.Filename); if NewDb <> nil then begin if FDb <> nil then FreeAndNil(FDb); FDb := NewDb; end; Refresh; end; procedure TMainForm.miOpenDbClick(Sender: TObject); var NewDb: TDepscanDb; begin if not OpenDialog.Execute then exit; NewDb := TDepscanDb.Create(OpenDialog.Filename); if FDb <> nil then FreeAndNil(FDb); FDb := NewDb; Refresh; end; procedure TMainForm.miCloseDbClick(Sender: TObject); begin if FDb <> nil then FreeAndNil(FDb); Refresh; end; procedure TMainForm.miExitClick(Sender: TObject); begin Close; end; procedure TMainForm.Refresh; begin miCloseDb.Enabled := FDb <> nil; ReloadImages; ReloadDetails; end; procedure TMainForm.edtQuickfilterChange(Sender: TObject); begin ReloadImages; end; procedure TMainForm.ReloadImages; var AImages: TDepImageList; data: TDepImageData; oldImageId: TImageId; begin oldImageId := LbGetSelectedImage; if FDb = nil then begin lbImages.Clear; exit; end; AImages := TDepImageList.Create; try if edtQuickFilter.Text <> '' then FDb.FindImages(edtQuickfilter.Text, AImages) else FDb.GetAllImages(AImages); lbImages.Items.BeginUpdate; try lbImages.Clear; //clear in update to prevent flicker for data in AImages do lbImages.Items.AddObject(data.name, TObject(data.id)); finally lbImages.Items.EndUpdate; end; finally FreeAndNil(AImages); end; LbSetSelectedImage(oldImageId); end; procedure TMainForm.lbImagesClick(Sender: TObject); begin SelectedImage := LbGetSelectedImage; end; function TMainForm.LbGetSelectedImage: TImageId; begin if lbImages.ItemIndex < 0 then Result := -1 else Result := TImageId(lbImages.Items.Objects[lbImages.ItemIndex]); end; procedure TMainForm.LbSetSelectedImage(const AValue: TImageId); var i: integer; begin for i := 0 to lbImages.Count-1 do if TImageId(lbImages.Items.Objects[i]) = AValue then begin lbImages.ItemIndex := i; exit; end; lbImages.ItemIndex := -1; end; procedure TMainForm.SetSelectedImage(const AValue: TImageId); begin if FSelectedImage = AValue then exit; FSelectedImage := AValue; ReloadDetails; end; procedure TMainForm.ReloadDetails; begin ReloadExports; ReloadImports; ReloadClients; end; procedure TMainForm.ReloadExports; var list: TDepExportList; data: TDepExportData; begin lbExports.Clear; if (FDb = nil) or (SelectedImage < 0) then exit; list := TDepExportList.Create; lbExports.Items.BeginUpdate; try FDb.GetExports(SelectedImage, list); for data in list do if data.name <> '' then lbExports.Items.Add(data.name + ' ('+ IntToStr(data.ord) + ')') else lbExports.Items.Add(IntToStr(data.ord)); finally lbExports.Items.EndUpdate; FreeAndNil(list); end; end; procedure TMainForm.ReloadImports; var list: TDepImportList; data: TDepImportData; begin lbImports.Clear; if (FDb = nil) or (SelectedImage < 0) then exit; list := TDepImportList.Create; lbImports.Items.BeginUpdate; try FDb.GetImports(SelectedImage, list); for data in list do if data.name <> '' then lbImports.Items.Add(data.libname + '@' + data.name) else lbImports.Items.Add(data.libname + '@' + IntToStr(data.ord)); finally lbImports.Items.EndUpdate; FreeAndNil(list); end; end; procedure TMainForm.ReloadClients; var list: TDepCallerList; data: TDepCallerData; begin lbClients.Clear; if (FDb = nil) or (SelectedImage < 0) then exit; list := TDepCallerList.Create; lbClients.Items.BeginUpdate; try FDb.GetCallers(SelectedImage, list); for data in list do if data.name <> '' then lbClients.Items.Add(FDb.GetImageName(data.image) + '@' + data.name) else lbClients.Items.Add(FDb.GetImageName(data.image) + '@' + IntToStr(data.ord)); finally lbClients.Items.EndUpdate; FreeAndNil(list); end; end; 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----- ============================================================================== | mousein.pas | handle the mouse input. supposed to be like keyin is to the keyboard, | but last time i tested it, didn't work. *sigh* | | History: | Date Author Comment | ---- ------ ------- | -- --- 94 G. Ollis created and developed program ============================================================================*) {$I-} Unit MouseIN; INTERFACE Uses Header; {++PROCEDURES++++++++++++++++++++++++++++++++++++++++++++++++++++++++++} Procedure MInput(Var D:DataType; Var hp:HelpPointer; wb:Byte); {++FUNCTIONS+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++} {++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++} IMPLEMENTATION Uses Ollis,CFG,CRT,OutCRT,UModify,BinED,Help,KeyIn; {----------------------------------------------------------------------} Procedure MInput(Var D:DataType; Var hp:HelpPointer; wb:Byte); Var X,Y:Integer; First:Boolean; Begin HideMC; X:=GetMouseX div 8+1; Y:=GetMouseY div 8+1; First:=True; If (wb=LeftButton) And (Y>0) And (Y<4) And (X<76) Then Repeat If First Then Begin Delay(75); First:=False; End; X:=GetMouseX div 8+1; Y:=GetMouseY div 8+1; Delay(15); D.X:=D.X+(X div 3)-12; DefaultOutPut; Until MouseButtonReleased(LeftButton); If wb=RightButton Then If (D.X+(X div 3)-12>=1) And (D.X+(X div 3)-12<D.EOF) And (Y<4) Then If (Y=1) Or (Y=2) Then HexModify(D.D^[D.X+(X div 3)-12],D.X+(X div 3)-12,D) Else CharModify(D.D^[D.X+(X div 3)-12],D.X+(X div 3)-12,D); If wb=CenterButton Then If (D.X+(X div 3)-12>=1) And (D.X+(X div 3)-12<ImageSize-1) And (Y<4) Then BinaryEditor(D.D^[D.X+(X div 3)-12],D); If (hp<>Nil) And (wb=LeftButton) And (Y=11) Then Repeat hp^.Y:=hp^.Y-1; If hp^.Y<1 Then hp^.Y:=1; WriteHelp(hp); Delay(25); Until MouseButtonReleased(LeftButton); If (hp<>Nil) And (wb=LeftButton) And (Y=24) Then Repeat hp^.Y:=hp^.Y+1; If hp^.Y>MaxHelp-12 Then hp^.Y:=MaxHelp-12; WriteHelp(hp); Delay(25); Until MouseButtonReleased(LeftButton); If (wb=LeftButton) And (Y=5) Then Begin C1:=' '; Commands(D,hp); C1:=#0; End; If (wb=LeftButton) And (Y>=6) And (Y<=9) Then Begin C1:='P'; Commands(D,hp); C1:=#0; End; If (wb=RightButton) And (Y>=6) And (Y<=9) Then Begin C1:='D'; Commands(D,hp); C1:=#0; End; If (wb=RightButton) And (Y=5) Then Begin C1:=#13; Commands(D,hp); C1:=#0; End; If (wb=CenterButton) And (Y=5) Then Begin C1:='A'; Commands(D,hp); C1:=#0; End; ShowMC; DefaultOutPut; End; {======================================================================} End.
{*****************************************************************************} { BindAPI } { Copyright (C) 2020 Paolo Morandotti } { Unit plBindAPI.BinderElement } {*****************************************************************************} { } {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.BinderElement; interface uses {$IFDEF FPC} Rtti, Generics.Collections, Generics.Defaults, Classes, {$ELSE} System.Rtti, System.Generics.Collections, System.Generics.Defaults, System.Classes, {$ENDIF} plBindAPI.Types; type TplRTTIMemberBind = class private function FirstLeaf(var pathLeafs: string): string; procedure SetRecordFieldValue(Sender: TObject; AOwner, AField: TRTTIField; AValue: TValue); overload; procedure SetRecordFieldValue(Sender: TObject; AOwner: TRttiProperty; AField: TRTTIField; AValue: TValue); overload; function GetRecordFieldValue(Sender: TObject; AOwner: TRttiProperty; AField: TRTTIField): TValue; overload; function GetRecordFieldValue(Sender: TObject; AOwner, AField: TRTTIField): TValue; overload; private FCalculatedValue: TplBridgeFunction; FElement: TObject; FElementPath: string; FEnabled: Boolean; FValue: TValue; function AreEqual(Left, Right: TValue): Boolean; function GetPathValue(ARoot: TObject; var APath: string): TValue; function GetRecordPathValue(ARoot: TObject; var APath: string): TValue; function GetValue: TValue; function InternalCastTo(const AType: TTypeKind; AValue: TValue): TValue; procedure SetValue(Value: TValue); virtual; procedure SetPathValue(ARoot: TObject; var APath: string; AValue: TValue); procedure SetRecordPathValue(ARoot: TObject; var APath: string; AValue: TValue); public constructor Create(AObject: TObject; const APropertyPath: string; AFunction: TplBridgeFunction = nil); property Element: TObject read FElement; property Enabled: Boolean read FEnabled write FEnabled; property PropertyPath: string read FElementPath; property Value: TValue read FValue write SetValue; function ValueChanged: boolean; function IsEqualTo(AStructure: TplRTTIMemberBind) : Boolean; end; TplPropertyBind = class(TplRTTIMemberBind) end; TPlParKeyComparer = class(TEqualityComparer<TplPropertyBind>) function Equals(const Left, Right: TplPropertyBind): Boolean; override; function GetHashCode(const Value: TplPropertyBind): Integer; override; end; implementation uses System.TypInfo, System.Hash, System.SysUtils, System.StrUtils, System.Math; {TplRTTIMemberBind} function TplRTTIMemberBind.AreEqual(Left, Right: TValue): Boolean; var i: Integer; pLeft, pRight: Pointer; begin If Left.IsOrdinal then Result := Left.AsOrdinal = Right.AsOrdinal else if Left.TypeInfo.Kind = tkSet then Result := SameText(Left.ToString(), Right.ToString()) else if Left.TypeInfo = System.TypeInfo(Single) then Result := SameValue(Left.AsType<Single>(), Right.AsType<Single>()) else if Left.TypeInfo = System.TypeInfo(Double) then Result := SameValue(Left.AsType<Double>(), Right.AsType<Double>()) else if Left.Kind in [tkChar, tkString, tkWChar, tkLString, tkWString, tkUString] then Result := Left.AsString = Right.AsString else if Left.IsClass and Right.IsClass then Result := Left.AsClass = Right.AsClass else if Left.IsObject then Result := Left.AsObject = Right.AsObject else if Left.IsArray then begin Result := Left.GetArrayLength = Right.GetArrayLength; for i := 0 to Left.GetArrayLength - 1 do Result := Result and AreEqual(Left.GetArrayElement(i), Right.GetArrayElement(i)); end else if (Left.Kind = tkPointer) or (Left.TypeInfo = Right.TypeInfo) then begin pLeft := nil; pRight := nil; Left.ExtractRawDataNoCopy(pLeft); Right.ExtractRawDataNoCopy(pRight); Result := pLeft = pRight; end else if Left.TypeInfo = System.TypeInfo(Variant) then Result := Left.AsVariant = Right.AsVariant else if Left.TypeInfo = System.TypeInfo(TGUID) then Result := IsEqualGuid( Left.AsType<TGUID>, Right.AsType<TGUID> ) else Result := False; end; constructor TplRTTIMemberBind.Create(AObject: TObject; const APropertyPath: string; AFunction: TplBridgeFunction); begin // Basic test. We should provide more test to verifiy if property exists, etc. if not Assigned(AObject) then raise Exception.Create('AObject not assgined'); if APropertyPath = '' then raise Exception.Create('PropertyPath not set'); FEnabled := True; FCalculatedValue := AFunction; FElementPath := APropertyPath; FElement := AObject; FValue := GetValue; end; function TplRTTIMemberBind.FirstLeaf(var pathLeafs: string): string; var dot: string; i: Integer; leafs: TArray<string>; begin if pathLeafs <> '' then begin leafs := pathLeafs.Split(['.']); Result := leafs[0]; dot := ''; pathLeafs := ''; for i := 1 to High(leafs) do begin pathLeafs := pathLeafs + dot + leafs[i]; dot := '.'; end; end else Result := ''; end; {Get record value when a is a field of a property} function TplRTTIMemberBind.GetRecordFieldValue(Sender: TObject; AOwner: TRttiProperty; AField: TRTTIField): TValue; var MyPointer: Pointer; begin MyPointer := TRttiInstanceProperty(AOwner).PropInfo^.GetProc; Result := AField.GetValue(PByte(Sender) + Smallint(MyPointer)); end; function TplRTTIMemberBind.GetPathValue(ARoot: TObject; var APath: string): TValue; var currentRoot: TObject; leafName: string; myContext: TRttiContext; myField: TRttiField; myPath: string; myProp: TRttiProperty; propertyInfo: PPropInfo; begin currentRoot := ARoot; myProp := nil; myField := nil; myPath := APath; while myPath <> '' do begin leafName := FirstLeaf(myPath); // 1) localizza la prima foglia, sia prop o field myField := myContext.GetType(currentRoot.ClassType).GetField(leafName); if not Assigned(myField) then myProp := myContext.GetType(currentRoot.ClassType).GetProperty(leafName); // 2) esamina se il nodo è un oggetto o un record, o se non si deve fare // nulla perché abbiamo raggiunto la fine del path e abbiamo quindi // estratto lo RTTImembr finale if myPath <> '' then begin // Caso A: abbiamo a che fare con un oggetto if Assigned(myField) then begin myProp := nil; if myField.FieldType.IsRecord then begin // trasferisce il controllo alla procedura apposita myPath := leafName + '.' + IfThen(myPath <> '', '.' + myPath, ''); Result := GetRecordPathValue(currentRoot, myPath); Exit; end else if myField.FieldType.isInstance then currentRoot := myField.GetValue(currentRoot).AsObject; end else if Assigned(myProp) then begin if myProp.PropertyType.IsRecord then begin // trasferisce il controllo alla procedura apposita myPath := leafName + IfThen(myPath <> '', '.' + myPath, ''); Result := GetRecordPathValue(currentRoot, myPath); Exit; end else if (myProp.PropertyType.isInstance) then currentRoot := myProp.GetValue(currentRoot).AsObject; end else raise Exception.Create(FElementPath + ' is not a path to property or field.'); // leafName := FirstLeaf(myPath); end; end; // 3) con l'ultimo nodo e la proprietà da impostare, si esegue l'operazione appropriata if Assigned(myField) then case myField.FieldType.TypeKind of tkClass: Result := myField.GetValue(currentRoot).AsObject else Result := myField.GetValue(currentRoot); end else if Assigned(myProp) then case myProp.PropertyType.TypeKind of tkClass: begin propertyInfo := (myProp as TRttiInstanceProperty).PropInfo; Result := GetObjectProp(currentRoot, propertyInfo); end else Result := myProp.GetValue(currentRoot); end else raise Exception.Create(FElementPath + ' is not a path to property or field.'); end; function TplRTTIMemberBind.GetRecordFieldValue(Sender: TObject; AOwner, AField: TRTTIField): TValue; begin Result := AField.GetValue(PByte(Sender) + AOwner.Offset); end; function TplRTTIMemberBind.GetRecordPathValue(ARoot: TObject; var APath: string): TValue; var myContext: TRttiContext; myField: TRttiField; myFieldRoot: TRttiField; myRecField: TRttiField; myProp: TRttiProperty; myPropRoot: TRttiProperty; myPath: string; leafName: string; begin myPropRoot := nil; myProp := nil; myPath := APath; leafName := FirstLeaf(myPath); // 1) localizza il record, sia prop o field myField := myContext.GetType(ARoot.ClassType).GetField(leafName); myFieldRoot := myField; if not Assigned(myField) then begin myProp := myContext.GetType(ARoot.ClassType).GetProperty(leafName); myPropRoot := myProp; end; // scorre le prop interne. La prima volta potrebbe passare da myProp, poi // solo da myField while myPath.Contains('.') do begin leafName := FirstLeaf(myPath); if Assigned(myField) then myField := myField.FieldType.GetField(leafName) else myField := myProp.PropertyType.GetField(leafName); end; if Assigned(myField) then myRecField := myField.FieldType.GetField(myPath) else myRecField := myProp.PropertyType.GetField(myPath); try if Assigned(myFieldRoot) then Result := GetRecordFieldValue(ARoot, myFieldRoot, myRecField) else Result := GetRecordFieldValue(ARoot, myPropRoot, myRecField); except on e: Exception do raise Exception.Create('Error on setting ' + APath + ': ' + e.Message); end; end; function TplRTTIMemberBind.GetValue: TValue; var path: string; begin path := FElementPath; Result := GetPathValue(FElement, path); end; function TplRTTIMemberBind.InternalCastTo(const AType: TTypeKind; AValue: TValue): TValue; begin case AType of tkInteger: case AValue.Kind of tkString, tkLString, tkWString, tkWChar, tkUString: Result := StrToInt(AValue.AsString); tkFloat: Result := Trunc(AValue.AsType<Double>); end; tkInt64: case AValue.Kind of tkString, tkLString, tkWString, tkWChar, tkUString: Result := StrToInt64(AValue.AsString); tkFloat: Result := Trunc(AValue.AsType<Double>); end; tkFloat: case AValue.Kind of tkString, tkLString, tkWString, tkWChar, tkUString: Result := StrToFloat(AValue.AsString); end; tkString, tkLString, tkWString, tkWChar, tkUString: case AValue.Kind of tkString, tkLString, tkWString, tkWChar, tkUString: Result := AValue.AsString; tkFloat: Result := FloatToStr(AValue.AsType<Double>); tkInteger: Result := IntToStr(AValue.AsInteger); tkInt64: Result := IntToStr(AValue.AsInt64); end else Result := AValue; end; end; function TplRTTIMemberBind.IsEqualTo(AStructure: TplRTTIMemberBind): Boolean; begin Result := (Self.Element = AStructure.Element) and (Self.PropertyPath = AStructure.PropertyPath); end; {TplRTTIMemberBind} {Set record value when a is a field of a property} procedure TplRTTIMemberBind.SetPathValue(ARoot: TObject; var APath: string; AValue: TValue); var currentRoot: TObject; leafName: string; myContext: TRttiContext; myField: TRttiField; myPath: string; myProp: TRttiProperty; propertyInfo: PPropInfo; begin if not FEnabled then Exit; if Assigned(FCalculatedValue) then FValue := FCalculatedValue(AValue, FValue) else FValue := AValue; currentRoot := ARoot; myField := nil; myProp := nil; myPath := APath; while myPath <> '' do begin leafName := FirstLeaf(myPath); // 1) localizza la prima foglia, sia prop o field myField := myContext.GetType(currentRoot.ClassType).GetField(leafName); if not Assigned(myField) then begin myProp := myContext.GetType(currentRoot.ClassType).GetProperty(leafName); end; if myPath <> '' then begin // 2) esamina se il nodo è un oggetto o un record // Caso A: abbiamo a che fare con un oggetto if Assigned(myField) then begin myProp := nil; if myField.FieldType.IsRecord then begin // trasferisce il controllo alla procedura apposita myPath := leafName + '.' + IfThen(myPath <> '', '.' + myPath, ''); SetRecordPathValue(currentRoot, myPath, FValue); Exit; end else if myField.FieldType.isInstance then currentRoot := myField.GetValue(currentRoot).AsObject else if myPath = '' then Break; end else if Assigned(myProp) then begin if myProp.PropertyType.IsRecord then begin // trasferisce il controllo alla procedura apposita myPath := leafName + IfThen(myPath <> '', '.' + myPath, ''); SetRecordPathValue(currentRoot, myPath, FValue); Exit; end else if myProp.PropertyType.isInstance then currentRoot := myProp.GetValue(currentRoot).AsObject else if myPath = '' then Break; end else raise Exception.Create(FElementPath + ' is not a path to property or field.'); end; end; // 3) con l'ultimo nodo e la proprietà da impostare, si esegue l'operazione appropriata if Assigned(myField) then begin if (myField.FieldType.TypeKind <> FValue.Kind) then FValue := InternalCastTo(myField.FieldType.TypeKind, FValue); case myField.FieldType.TypeKind of tkClass: myField.SetValue(currentRoot, TObject(FValue.AsObject)) else myField.SetValue(currentRoot, FValue); end; end else if Assigned(myProp) then begin if (myProp.PropertyType.TypeKind <> FValue.Kind) then FValue := InternalCastTo(myProp.propertyType.TypeKind, FValue); case myProp.PropertyType.TypeKind of tkClass: begin propertyInfo := (myProp as TRttiInstanceProperty).PropInfo; SetObjectProp(currentRoot, propertyInfo, FValue.AsObject); end else myProp.SetValue(currentRoot, FValue); end; end else raise Exception.Create(FElementPath + ' is not a path to property or field.'); end; procedure TplRTTIMemberBind.SetRecordFieldValue(Sender: TObject; AOwner: TRttiProperty; AField: TRTTIField; AValue: TValue); var MyPointer: Pointer; begin if (AField.FieldType.TypeKind <> AValue.Kind) then AValue := InternalCastTo(AField.FieldType.TypeKind, FValue); MyPointer := TRttiInstanceProperty(AOwner).PropInfo^.GetProc; AField.SetValue(PByte(Sender) + Smallint(MyPointer), AValue); end; {Set record value when a is a field of a field} procedure TplRTTIMemberBind.SetRecordFieldValue(Sender: TObject; AOwner, AField: TRTTIField; AValue: TValue); begin if (AField.FieldType.TypeKind <> AValue.Kind) then AValue := InternalCastTo(AField.FieldType.TypeKind, FValue); AField.SetValue(PByte(Sender) + AOwner.Offset, AValue); end; procedure TplRTTIMemberBind.SetRecordPathValue(ARoot: TObject; var APath: string; AValue: TValue); var myContext: TRttiContext; myField: TRttiField; myFieldRoot: TRttiField; myRecField: TRttiField; myProp: TRttiProperty; myPropRoot: TRttiProperty; myPath: string; leafName: string; begin myPropRoot := nil; myProp := nil; myPath := APath; leafName := FirstLeaf(myPath); // 1) localizza il record, sia prop o field myField := myContext.GetType(ARoot.ClassType).GetField(leafName); myFieldRoot := myField; if not Assigned(myField) then begin myProp := myContext.GetType(ARoot.ClassType).GetProperty(leafName); myPropRoot := myProp; end; // scorre le prop interne. La prima volta potrebbe passare da myProp, poi // solo da myField while myPath.Contains('.') do begin leafName := FirstLeaf(myPath); if Assigned(myField) then myField := myField.FieldType.GetField(leafName) else myField := myProp.PropertyType.GetField(leafName); end; if Assigned(myField) then myRecField := myField.FieldType.GetField(myPath) else myRecField := myProp.PropertyType.GetField(myPath); try if Assigned(myFieldRoot) then SetRecordFieldValue(ARoot, myFieldRoot, myRecField, AValue) else SetRecordFieldValue(ARoot, myPropRoot, myRecField, AValue); except on e: Exception do raise Exception.Create('Error on setting ' + APath + ': ' + e.Message); end; end; procedure TplRTTIMemberBind.SetValue(Value: TValue); var path: string; begin path := FElementPath; SetPathValue(FElement, path, Value); //was: QuickLib.RTTI.TRTTI.SetPathValue(FElement, FElementPath, FValue); end; function TplRTTIMemberBind.ValueChanged: boolean; var newValue: TValue; begin if FEnabled and Assigned(FElement) then try newValue := GetValue; Result := not AreEqual(newValue, FValue); //not newValue.Equals(FValue); if Result then FValue := newValue; except Result := False; FEnabled := False; end else Result := False; end; { TplFieldBind } { TPlParKeyComparer } function TPlParKeyComparer.Equals(const Left, Right: TplPropertyBind): Boolean; begin Result := (Left.Element = Right.Element) and (Left.PropertyPath = Right.PropertyPath); end; function TPlParKeyComparer.GetHashCode( const Value: TplPropertyBind): Integer; begin Result := THashBobJenkins.GetHashValue(PChar(Value.PropertyPath)^, Length(Value.PropertyPath) * SizeOf(Char), 0); end; end.
{***************************************************************} { Компонент для формирования диалоговых окон SmartDlg } { Copyright (c) 2012 - 2013 год . } { Тетенев Леонид Петрович, ltetenev@yandex.ru } { } {***************************************************************} unit RegSmartDlg; interface uses Windows, Classes, GridDlg, DlgExecute; type TSmartDlg = class(TCustomSmartDlg) published property Align; property Anchors; property BevelInner; property BevelOuter; property BevelWidth; property BevelKind; property Constraints; property Ctl3D; property ParentCtl3D; property Enabled; property ParentFont; property Font; property TabStop; property TabOrder; property Visible; property PopupMenu; property RowsList; property FormAutoHeight; property TabSet; property BorderStyle; property DividerPosition; property FolderFontColor; property FolderFontStyle; property LongTextHintTime; property LongEditHintTime; property AutoSelect; property DropDownCount; property TypeDialog; property OnShowDialog; property OnChangeRow; property OnSetEditText; property OnGetLookupList; property OnEditAcceptKey; property OnGetTabsTitle; property ReadOnly; // наследуемые события от TCustomControl и его родителей property OnContextPopup; property OnEnter; property OnExit; property OnResize; property OnKeyDown; property OnKeyPress; property OnKeyUp; end; TFillRows = class( TCustomFillRows ) published property SmartDialog; property OnGetDataBaseParam; property OnGetRowsListParam; property OnAfterFillRowList; property OnFilterGetHistory; property OnFillBetweenMenu; property OnGetLookupFieldValue; end; procedure Register; implementation procedure Register; begin RegisterComponents('DLG', [ TSmartDlg, TFillRows ]); end; end.
unit ServerMethodsUnit1; interface uses System.SysUtils, System.Classes, System.Json, Datasnap.DSServer, Datasnap.DSAuth, DataSnap.DSProviderDataModuleAdapter, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.IB, Data.DB, FireDAC.Comp.Client, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Phys.IBDef, FireDAC.VCLUI.Wait, MVCFramework.Serializer.JSON, MVCFramework.Serializer.Commons; type {$METHODINFO ON} TServerMethods1 = class(TDataModule) FDConnection1: TFDConnection; FDQuery1: TFDQuery; procedure DataModuleCreate(Sender: TObject); private FSerializer: TMVCJSONSerializer; { Private declarations } public { Public declarations } function EchoString(Value: string): string; function ReverseString(Value: string): string; function GetEmployees: TJSONArray; end; {$METHODINFO OFF} implementation {$R *.dfm} uses System.StrUtils, MVCFramework.DataSet.Utils; procedure TServerMethods1.DataModuleCreate(Sender: TObject); begin FSerializer := TMVCJSONSerializer.Create; end; function TServerMethods1.EchoString(Value: string): string; begin Result := Value; end; function TServerMethods1.GetEmployees: TJSONArray; var JObj: TJSONObject; begin FDQuery1.Open('SELECT * FROM PEOPLE'); Result := TJSONArray.Create; while not FDQuery1.Eof do begin JObj := TJSONObject.Create; FSerializer.DataSetToJSONObject(FDQuery1, JObj, TMVCNameCase.ncAsIs, []); Result.Add(JObj); FDQuery1.Next; end; FDQuery1.AsJSONArray; end; function TServerMethods1.ReverseString(Value: string): string; begin Result := System.StrUtils.ReverseString(Value); end; end.
{############################################################################### https://github.com/wendelb/DelphiOTP ###############################################################################} unit GoogleOTP; interface uses System.SysUtils, System.Math, System.DateUtils, IdGlobal, IdHMACSHA1; (* Test Case for the CalculateOTP function --------------------------------------- Init key: AAAAAAAAAAAAAAAAAAAA Timestamp: 1 BinCounter: 0000000000000001 (HEX-Representation) Hash: eeb00b0bcc864679ff2d8dd30bec495cb5f2ee9e (HEX-Representation) Offset: 14 Part 1: 73 Part 2: 92 Part 3: 181 Part 4: 242 One time password: 812658 Easy Display: Format('%.6d', [CalculateOTP(SECRET)]); *) function CalculateOTP(const Secret: String; const DateTime : TDateTime = 0; const Counter: Integer = -1): Integer; function ValidateTOPT(const Secret: String; const Token: Integer; const DateTime : TDateTime = 0; const WindowSize: Integer = 4): Boolean; function GenerateOTPSecret(len: Integer = -1): String; implementation Type OTPBytes = TIdBytes; const otpLength = 6; keyRegeneration = 30; SecretLengthDef = 20; ValidChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; function Base32Decode(const source: String): String; var UpperSource: String; p, i, l, n, j: Integer; begin UpperSource := UpperCase(source); l := Length(source); n := 0; j := 0; Result := ''; for i := 1 to l do begin n := n shl 5; // Move buffer left by 5 to make room p := Pos(UpperSource[i], ValidChars); if p >= 0 then n := n + (p - 1); // Add value into buffer j := j + 5; // Keep track of number of bits in buffer if (j >= 8) then begin j := j - 8; Result := Result + chr((n AND ($FF shl j)) shr j); end; end; end; function Base32Encode(source: string): string; var i: integer; nr: int64; begin result := ''; while length(source) > 0 do begin nr := 0; for i := 1 to 5 do begin nr := (nr shl 8); if length(source)>=i then nr := nr + byte(source[i]); end; for i := 7 downto 0 do if ((length(source)<2) and (i<6)) or ((length(source)<3) and (i<4)) or ((length(source)<4) and (i<3)) or ((length(source)<5) and (i<1)) then result := result + '=' else result := result + ValidChars[((nr shr (i*5)) and $1F)+1]; delete(source, 1, 5); end; end; /// <summary> /// Sign the Buffer with the given Key /// </summary> function HMACSHA1(const _Key: OTPBytes; const Buffer: OTPBytes): OTPBytes; begin with TIdHMACSHA1.Create do begin Key := _Key; Result := HashValue(Buffer); Free; end; end; /// <summary> /// Reverses TIdBytes (from low->high to high->low) /// </summary> function ReverseIdBytes(const inBytes: OTPBytes): OTPBytes; var i: Integer; begin //Result := []; SetLength(Result, Length(inBytes)); for i := Low(inBytes) to High(inBytes) do Result[High(inBytes) - i] := inBytes[i]; end; /// <summary> /// My own ToBytes function. Something in the original one isn't working as expected. /// </summary> function StrToIdBytes(const inString: String): OTPBytes; var ch: Char; i: Integer; begin //Result := []; SetLength(Result, Length(inString)); i := 0; for ch in inString do begin Result[i] := Ord(ch); inc(i); end; end; function CalculateOTP(const Secret: String; const DateTime : TDateTime = 0; const Counter: Integer = -1): Integer; var BinSecret: String; Hash: String; Offset: Integer; Part1, Part2, Part3, Part4: Integer; Key: Integer; Time: Integer; begin if Counter <> -1 then Time := Counter else if DateTime <> 0 then Time := DateTimeToUnix(DateTime) div keyRegeneration else Time := DateTimeToUnix(TTimeZone.Local.ToUniversalTime(Now)) div keyRegeneration; BinSecret := Base32Decode(Secret); Hash := BytesToStringRaw(HMACSHA1(StrToIdBytes(BinSecret), ReverseIdBytes(ToBytes(Int64(Time))))); Offset := (ord(Hash[20]) AND $0F) + 1; Part1 := (ord(Hash[Offset+0]) AND $7F); Part2 := (ord(Hash[Offset+1]) AND $FF); Part3 := (ord(Hash[Offset+2]) AND $FF); Part4 := (ord(Hash[Offset+3]) AND $FF); Key := (Part1 shl 24) OR (Part2 shl 16) OR (Part3 shl 8) OR (Part4); Result := Key mod Trunc(IntPower(10, otpLength)); end; function ValidateTOPT(const Secret: String; const Token: Integer; const DateTime : TDateTime = 0; const WindowSize: Integer = 4): Boolean; var TimeStamp: Integer; TestValue: Integer; begin Result := false; if DateTime <> 0 then TimeStamp := DateTimeToUnix(DateTime) div keyRegeneration else TimeStamp := DateTimeToUnix(TTimeZone.Local.ToUniversalTime(Now)) div keyRegeneration; for TestValue := Timestamp - WindowSize to TimeStamp + WindowSize do begin if (CalculateOTP(Secret, DateTime, TestValue) = Token) then Result := true; end; end; function GenerateOTPSecret(len: Integer = -1): String; var i : integer; ValCharLen : integer; begin Result := ''; ValCharLen := Length(ValidChars); if (len < 1) then len := SecretLengthDef; for i := 1 to len do begin Result := Result + copy(ValidChars, Random(ValCharLen) + 1, 1); end; Result := Base32Encode(Result); end; end.
{*******************************************************} { } { Delphi FireDAC Framework } { FireDAC InterBase driver } { } { Copyright(c) 2004-2013 Embarcadero Technologies, Inc. } { } {*******************************************************} {$I FireDAC.inc} {$IFDEF WIN32} {$HPPEMIT '#pragma link "FireDAC.Phys.IB.obj"'} {$ELSE} {$HPPEMIT '#pragma link "FireDAC.Phys.IB.o"'} {$ENDIF} unit FireDAC.Phys.IB; interface uses System.Classes, FireDAC.DatS, FireDAC.Phys, FireDAC.Phys.IBWrapper, FireDAC.Phys.IBBase; type TFDPhysIBDriverLink = class; TFDIBSDump = class; [ComponentPlatformsAttribute(pidWin32 or pidWin64 or pidOSX32 or pidiOSSimulator or pidiOSDevice or pidAndroid)] TFDPhysIBDriverLink = class(TFDPhysIBBaseDriverLink) protected function GetBaseDriverID: String; override; end; [ComponentPlatformsAttribute(pidWin32 or pidWin64 or pidOSX32 or pidiOSSimulator or pidiOSDevice or pidAndroid)] TFDIBSDump = class (TFDIBService) private FDatabase: String; FBackupFiles: TStrings; FOverwrite: Boolean; procedure SetBackupFiles(const AValue: TStrings); protected function CreateService(AEnv: TIBEnv): TIBService; override; procedure SetupService(AService: TIBService); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Dump; published property Database: String read FDatabase write FDatabase; property BackupFiles: TStrings read FBackupFiles write SetBackupFiles; property Overwrite: Boolean read FOverwrite write FOverwrite; end; {-------------------------------------------------------------------------------} implementation uses System.Variants, System.SysUtils, Data.DB, FireDAC.Stan.Intf, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.Stan.Option, FireDAC.Stan.Util, FireDAC.Stan.Consts, FireDAC.Phys.Intf, FireDAC.Phys.IBMeta, FireDAC.Phys.SQLGenerator, FireDAC.Phys.IBCli; type TFDPhysIBDriver = class; TFDPhysIBConnection = class; TFDPhysIBCommand = class; TFDPhysIBDriver = class(TFDPhysIBDriverBase) protected procedure InternalLoad; override; function InternalCreateConnection(AConnHost: TFDPhysConnectionHost): TFDPhysConnection; override; class function GetBaseDriverID: String; override; function GetConnParamCount(AKeys: TStrings): Integer; override; procedure GetConnParams(AKeys: TStrings; AIndex: Integer; var AName, AType, ADefVal, ACaption: String; var ALoginIndex: Integer); override; end; TFDPhysIBConnection = class(TFDPhysIBConnectionBase) protected function InternalCreateCommand: TFDPhysCommand; override; procedure BuildIBConnectParams(AParams: TStrings; const AConnectionDef: IFDStanConnectionDef); override; procedure InternalAnalyzeSession(AMessages: TStrings); override; end; TFDPhysIBCommand = class(TFDPhysIBCommandBase) private procedure DoExecuteIB2007Batch(ATimes, AOffset: Integer; var ACount: TFDCounter); protected procedure InternalExecute(ATimes, AOffset: Integer; var ACount: TFDCounter); override; procedure ProcessMetaColumn(ATable: TFDDatSTable; AFmtOpts: TFDFormatOptions; AColIndex: Integer; ARow: TFDDatSRow; ApInfo: PFDIBColInfoRec; ARowIndex: Integer); override; end; {-------------------------------------------------------------------------------} { TFDPhysIBDriverLink } {-------------------------------------------------------------------------------} function TFDPhysIBDriverLink.GetBaseDriverID: String; begin Result := S_FD_IBId; end; {-------------------------------------------------------------------------------} { TFDIBSDump } {-------------------------------------------------------------------------------} constructor TFDIBSDump.Create(AOwner: TComponent); begin inherited Create(AOwner); FBackupFiles := TFDStringList.Create; end; {-------------------------------------------------------------------------------} destructor TFDIBSDump.Destroy; begin FDFreeAndNil(FBackupFiles); inherited Destroy; end; {-------------------------------------------------------------------------------} procedure TFDIBSDump.SetBackupFiles(const AValue: TStrings); begin FBackupFiles.Assign(AValue); end; {-------------------------------------------------------------------------------} function TFDIBSDump.CreateService(AEnv: TIBEnv): TIBService; begin Result := TIBSDump.Create(AEnv, Self); end; {-------------------------------------------------------------------------------} procedure TFDIBSDump.SetupService(AService: TIBService); begin inherited SetupService(AService); TIBSDump(AService).DatabaseName := FDExpandStr(Database); TIBSDump(AService).BackupFiles := BackupFiles; FDExpandStrs(TIBSDump(AService).BackupFiles); TIBSDump(AService).Overwrite := Overwrite; end; {-------------------------------------------------------------------------------} procedure TFDIBSDump.Dump; begin Execute; end; {-------------------------------------------------------------------------------} { TFDPhysIBDriver } {-------------------------------------------------------------------------------} procedure TFDPhysIBDriver.InternalLoad; var sHome, sLib: String; begin sHome := ''; sLib := ''; GetVendorParams(sHome, sLib); FLib.LoadIB(sHome, sLib); end; {-------------------------------------------------------------------------------} function TFDPhysIBDriver.InternalCreateConnection( AConnHost: TFDPhysConnectionHost): TFDPhysConnection; begin Result := TFDPhysIBConnection.Create(Self, AConnHost); end; {-------------------------------------------------------------------------------} class function TFDPhysIBDriver.GetBaseDriverID: String; begin Result := S_FD_IBId; end; {-------------------------------------------------------------------------------} function TFDPhysIBDriver.GetConnParamCount(AKeys: TStrings): Integer; begin Result := inherited GetConnParamCount(AKeys) + 2; end; {-------------------------------------------------------------------------------} procedure TFDPhysIBDriver.GetConnParams(AKeys: TStrings; AIndex: Integer; var AName, AType, ADefVal, ACaption: String; var ALoginIndex: Integer); begin ALoginIndex := -1; if AIndex < inherited GetConnParamCount(AKeys) then begin inherited GetConnParams(AKeys, AIndex, AName, AType, ADefVal, ACaption, ALoginIndex); if AName = S_FD_ConnParam_Common_Database then AType := '@F:InterBase Database|*.gdb;*.ib'; end else begin case AIndex - inherited GetConnParamCount(AKeys) of 0: begin AName := S_FD_ConnParam_IBS_InstanceName; AType := '@S'; ADefVal := ''; end; 1: begin AName := S_FD_ConnParam_IBS_SEPassword; AType := '@P'; end; end; ACaption := AName; end; end; {-------------------------------------------------------------------------------} { TFDPhysIBConnection } {-------------------------------------------------------------------------------} function TFDPhysIBConnection.InternalCreateCommand: TFDPhysCommand; begin Result := TFDPhysIBCommand.Create(Self); end; {-------------------------------------------------------------------------------} procedure TFDPhysIBConnection.BuildIBConnectParams(AParams: TStrings; const AConnectionDef: IFDStanConnectionDef); begin inherited BuildIBConnectParams(AParams, AConnectionDef); if GetConnectionDef.HasValue(S_FD_ConnParam_IBS_InstanceName) then AParams.Add('instance_name=' + GetConnectionDef.AsString[S_FD_ConnParam_IBS_InstanceName]); if GetConnectionDef.HasValue(S_FD_ConnParam_IBS_SEPassword) then AParams.Add('sys_encrypt_password=' + GetConnectionDef.AsString[S_FD_ConnParam_IBS_SEPassword]); end; {-------------------------------------------------------------------------------} procedure TFDPhysIBConnection.InternalAnalyzeSession(AMessages: TStrings); begin inherited InternalAnalyzeSession(AMessages); // 3. Use driver to connect to IB server with gds32.dll if ServerBrand <> ibInterbase then AMessages.Add('Warning: Use InterBase driver to connect to InterBase'); if IBEnv.Lib.Brand <> ibInterbase then AMessages.Add('Warning: Use gds32.dll with InterBase driver '); end; {-------------------------------------------------------------------------------} { TFDPhysIBCommand } {-------------------------------------------------------------------------------} procedure TFDPhysIBCommand.DoExecuteIB2007Batch(ATimes, AOffset: Integer; var ACount: TFDCounter); var iBatchSize, iRows: LongWord; iCurTimes, iCurOffset, i: Integer; oResOpts: TFDResourceOptions; begin oResOpts := FOptions.ResourceOptions; // total size of XSQLVAR, which will be send to server in single packet iBatchSize := FStmt.MaximumBatchSize; if iBatchSize > LongWord(oResOpts.ArrayDMLSize) then iBatchSize := LongWord(oResOpts.ArrayDMLSize); // If block will have only single command or there are OUT params, then go // by standard route - execute command once for each param array item. if (iBatchSize <= 1) or (FStmt.OutVars.VarCount > 0) then begin DoExecute(ATimes, AOffset, ACount); Exit; end; iCurOffset := AOffset; iCurTimes := LongWord(AOffset) + iBatchSize; while iCurOffset < ATimes do begin if iCurTimes > ATimes then iCurTimes := ATimes; FStmt.InVars.RowCount := Word(iCurTimes - iCurOffset); SetParamValues(iCurTimes, iCurOffset); try try FStmt.ExecuteBatch; finally if FStmt <> nil then for i := 0 to FStmt.InVars.RowCount - 1 do begin iRows := FStmt.InVars.FRowsAffected[i]; if iRows = $FFFFFFFF then Break; if iRows > 0 then Inc(ACount); end; end; except on E: EIBNativeException do begin E.Errors[0].RowIndex := iCurOffset + ACount; raise; end; end; if FStmt.OutVars.VarCount > 0 then GetParamValues(iCurTimes, iCurOffset); FStmt.Close; Inc(iCurOffset, iBatchSize); Inc(iCurTimes, iBatchSize); end; end; {-------------------------------------------------------------------------------} procedure TFDPhysIBCommand.InternalExecute(ATimes, AOffset: Integer; var ACount: TFDCounter); begin CheckSPPrepared(skStoredProcNoCrs); CheckParamInfos; ACount := 0; if (ATimes - AOffset > 1) and (FStmt.Lib.Brand = ibInterbase) and (FStmt.Lib.Version >= ivIB110000) then DoExecuteIB2007Batch(ATimes, AOffset, ACount) else DoExecute(ATimes, AOffset, ACount); end; {-------------------------------------------------------------------------------} procedure TFDPhysIBCommand.ProcessMetaColumn(ATable: TFDDatSTable; AFmtOpts: TFDFormatOptions; AColIndex: Integer; ARow: TFDDatSRow; ApInfo: PFDIBColInfoRec; ARowIndex: Integer); var iVal: Integer; iSize: Longword; eIndexType: TFDPhysIndexKind; eTableType: TFDPhysTableKind; eScope: TFDPhysObjectScope; pBlob: PISCQuad; eDataType: TFDDataType; eRule: TFDPhysCascadeRuleKind; s: String; lUseBase: Boolean; procedure SetScope; begin if not ApInfo^.FVar.GetData(iVal, iSize) or (iVal = 0) then eScope := osMy else eScope := osSystem; ARow.SetData(AColIndex, Integer(eScope)); end; procedure SetDataType; begin if not ApInfo^.FVar.GetData(iVal, iSize) or (iVal = 0) then eDataType := dtUnknown else case iVal of 7: eDataType := dtInt16; 8: eDataType := dtInt32; 9: eDataType := dtInt64; 10: eDataType := dtSingle; 11: eDataType := dtDouble; 12: eDataType := dtDate; 13: eDataType := dtTime; 14: eDataType := dtAnsiString; 16: eDataType := dtInt64; 17: eDataType := dtBoolean; 27: eDataType := dtDouble; 35: eDataType := dtDateTimeStamp; 37: eDataType := dtAnsiString; 40: eDataType := dtAnsiString; 45: eDataType := dtBlob; 261: eDataType := dtMemo; else eDataType := dtUnknown; end; ARow.SetData(AColIndex, Integer(eDataType)); end; begin lUseBase := True; if (IBConnection.ServerBrand = ibInterbase) and (IBConnection.ServerVersion < ivIB070500) then case GetMetaInfoKind of mkIndexes: if AColIndex = 6 then begin if not ApInfo^.FVar.GetData(iVal, iSize) or (iVal = 0) then eIndexType := ikNonUnique else if (iVal = 1) and not VarIsNull(ARow.GetData(5)) then eIndexType := ikPrimaryKey else eIndexType := ikUnique; ARow.SetData(AColIndex, Integer(eIndexType)); lUseBase := False; end; mkTables: if AColIndex = 4 then begin if not ApInfo^.FVar.GetData(pBlob, iSize) then eTableType := tkTable else eTableType := tkView; ARow.SetData(AColIndex, Integer(eTableType)); lUseBase := False; end else if AColIndex = 5 then begin SetScope; lUseBase := False; end; mkTableFields: if AColIndex = 6 then begin SetDataType; lUseBase := False; end; mkForeignKeys: if (AColIndex = 8) or (AColIndex = 9) then begin s := ApInfo^.FVar.AsString; if CompareText('RESTRICT', s) = 0 then eRule := ckRestrict else if CompareText('CASCADE', s) = 0 then eRule := ckCascade else if CompareText('SET NULL', s) = 0 then eRule := ckSetNull else if CompareText('SET DEFAULT', s) = 0 then eRule := ckSetDefault else eRule := ckNone; ARow.SetData(AColIndex, Integer(eRule)); lUseBase := False; end; mkProcs: if AColIndex = 7 then begin SetScope; lUseBase := False; end; mkProcArgs: if AColIndex = 9 then begin SetDataType; lUseBase := False; end; mkGenerators: if AColIndex = 4 then begin SetScope; lUseBase := False; end; mkResultSetFields: if (AColIndex = 7) or (AColIndex = 8) then begin if not ApInfo^.FVar.GetData(pBlob, iSize) then iVal := 0 else iVal := 1; ARow.SetData(AColIndex, iVal); lUseBase := False; end; end; if lUseBase then inherited ProcessMetaColumn(ATable, AFmtOpts, AColIndex, ARow, ApInfo, ARowIndex); end; {-------------------------------------------------------------------------------} initialization FDPhysManager(); FDPhysManagerObj.RegisterDriverClass(TFDPhysIBDriver); end.
unit uFunctionalNumberClassifier; interface uses Spring.Collections , uNumberClassificationTypes ; type TFunctionalNumberClassifier = class public class function IsFactor(aNumber: integer; aPotentialFactor: integer): Boolean; static; class function Factors(aNumber: integer): IEnumerable<integer>; static; class function IsAbundant(aNumber: integer): boolean; static; class function IsDeficient(aNumber: integer): boolean; static; class function IsPerfect(aNumber: integer): boolean; static; end; function FunctionalNumberClassifier(aNumber: integer): TNumberClassification; implementation function FunctionalNumberClassifier(aNumber: integer): TNumberClassification; begin if TFunctionalNumberClassifier.IsPerfect(aNumber) then begin Result := Perfect end else begin if TFunctionalNumberClassifier.IsAbundant(aNumber) then begin Result := Abundant end else begin Result := Deficient; end; end; end; { TFunctionalNumberClassifier } class function TFunctionalNumberClassifier.Factors(aNumber: integer): IEnumerable<integer>; begin Result := TEnumerable.Range(1, aNumber).Where(function(const aInteger: integer): Boolean begin Result := IsFactor(aNumber, aInteger); end); end; class function TFunctionalNumberClassifier.IsFactor(aNumber, aPotentialFactor: integer): Boolean; begin Result := aNumber mod aPotentialFactor = 0; end; class function TFunctionalNumberClassifier.IsPerfect(aNumber: integer): boolean; begin Result := Factors(aNumber).Sum - aNumber = aNumber; end; class function TFunctionalNumberClassifier.IsAbundant(aNumber: integer): boolean; begin Result := Factors(aNumber).Sum - aNumber > aNumber; end; class function TFunctionalNumberClassifier.IsDeficient(aNumber: integer): boolean; begin Result := Factors(aNumber).Sum - aNumber < aNumber; end; end.
unit PromoManagerDialog; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ParentForm, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Vcl.Menus, Vcl.StdCtrls, cxButtons, cxControls, cxContainer, cxEdit, Vcl.ComCtrls, dxCore, cxDateUtils, ChoicePeriod, dsdGuides, cxDropDownEdit, cxCalendar, cxTextEdit, cxMaskEdit, cxButtonEdit, cxPropertiesStore, dsdAddOn, dsdDB, cxLabel, dxSkinsCore, dxSkinsDefaultPainters, cxCheckBox, cxCurrencyEdit, cxMemo, cxStyles, dxSkinscxPCPainter, cxCustomData, cxFilter, cxData, cxDataStorage, Data.DB, cxDBData, Datasnap.DBClient, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxGridCustomView, cxGrid, dsdAction, Vcl.ActnList; type TPromoManagerDialogForm = class(TParentForm) cxButton1: TcxButton; cxButton2: TcxButton; dsdUserSettingsStorageAddOn: TdsdUserSettingsStorageAddOn; cxPropertiesStore: TcxPropertiesStore; FormParams: TdsdFormParams; cxLabel1: TcxLabel; cxLabel5: TcxLabel; edPromoStateKindName: TcxTextEdit; MemoComment: TcxMemo; cxGridPromoStateKind: TcxGrid; cxGridDBTableViewPromoStateKind: TcxGridDBTableView; psOrd: TcxGridDBColumn; psisQuickly: TcxGridDBColumn; psPromoStateKindName: TcxGridDBColumn; psComment: TcxGridDBColumn; psInsertName: TcxGridDBColumn; psInsertDate: TcxGridDBColumn; psIsErased: TcxGridDBColumn; cxGridLevel4: TcxGridLevel; PromoStateKindDS: TDataSource; PromoStateKindDCS: TClientDataSet; dsdDBViewAddOnPromoStateKind: TdsdDBViewAddOn; spSelectMIPromoStateKind: TdsdStoredProc; ActionList: TActionList; actRefresh: TdsdDataSetRefresh; private { Private declarations } public { Public declarations } end; implementation {$R *.dfm} initialization RegisterClass(TPromoManagerDialogForm); end.
unit GraficoLineas; interface uses GraficoZoom, GR32, Graphics, Classes, LinePainter; type TGraficoLineas = class(TZoomGrafico) private LinePainter: TLinePainter; function GetColorLine: TColor; procedure SetColorLine(const Value: TColor); protected procedure PaintZoomGrafico(const iFrom, iTo: integer); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure ChangeColors; property ColorLine: TColor read GetColorLine write SetColorLine default clGreen; end; implementation uses Tipos; { TGraficoLineas } procedure TGraficoLineas.ChangeColors; begin InvalidateGrafico; end; constructor TGraficoLineas.Create(AOwner: TComponent); begin inherited Create(AOwner); LinePainter := TLinePainter.Create; LinePainter.Datos := Datos; LinePainter.Color := clGreen32; end; destructor TGraficoLineas.Destroy; begin LinePainter.Free; inherited; end; function TGraficoLineas.GetColorLine: TColor; begin result := WinColor(LinePainter.Color); end; procedure TGraficoLineas.PaintZoomGrafico(const iFrom, iTo: integer); begin LinePainter.Paint(Bitmap, iFrom, iTo); end; procedure TGraficoLineas.SetColorLine(const Value: TColor); begin LinePainter.Color := Color32(Value); InvalidateGrafico; end; end.
{******************************************************************************} { } { WiRL: RESTful Library for Delphi } { } { Copyright (c) 2015-2019 WiRL Team } { } { https://github.com/delphi-blocks/WiRL } { } {******************************************************************************} unit WiRL.WebServer.Resources; interface uses System.SysUtils, System.Classes, System.Generics.Collections, WiRL.Core.Attributes, WiRL.http.Accept.MediaType, WiRL.http.URL, WiRL.http.Response; type TFileSystemResource = class; WebAttribute = class(TCustomAttribute) public procedure ApplyToResource(const AResource: TFileSystemResource); virtual; end; RootFolderAttribute = class(WebAttribute) private FPath: string; FIncludeSubFolders: Boolean; public constructor Create(const APath: string; const AIncludeSubFolders: Boolean); procedure ApplyToResource(const AResource: TFileSystemResource); override; property IncludeSubFolders: Boolean read FIncludeSubFolders; property Path: string read FPath; end; ContentTypeForFileExt = class(WebAttribute) private FContentType: string; FFileExt: string; public constructor Create(const AContentType, AFileExt: string); procedure ApplyToResource(const AResource: TFileSystemResource); override; property ContentType: string read FContentType; property FileExt: string read FFileExt; end; WebFilterAttribute = class(WebAttribute) private FPattern: string; public constructor Create(const APattern: string = '*.*'); property Pattern: string read FPattern; end; IncludeAttribute = class(WebFilterAttribute) public procedure ApplyToResource(const AResource: TFileSystemResource); override; end; ExcludeAttribute = class(WebFilterAttribute) public procedure ApplyToResource(const AResource: TFileSystemResource); override; end; TFileSystemResource = class private FRootFolder: string; FIncludeSubFolders: Boolean; FContentTypesForExt: TDictionary<string, string>; FExclusionFilters: TStringList; FInclusionFilters: TStringList; FIndexFileNames: TStringList; protected [Context] URL: TWiRLURL; [Context] FResponse: TWiRLResponse; procedure Init; virtual; procedure InitContentTypesForExt; virtual; procedure InitIndexFileNames; virtual; function CheckFilters(const AString: string): Boolean; virtual; procedure ServeFileContent(const AFileName: string; const AResponse: TWiRLResponse); virtual; procedure ServeDirectoryContent(const ADirectory: string; const AResponse: TWiRLResponse); virtual; function DirectoryHasIndexFile(const ADirectory: string; out AIndexFullPath: string): Boolean; virtual; public constructor Create; virtual; destructor Destroy; override; [GET, Path('/{*}')] procedure GetContent; virtual; // PROPERTIES property RootFolder: string read FRootFolder write FRootFolder; property IncludeSubFolders: Boolean read FIncludeSubFolders write FIncludeSubFolders; property ContentTypesForExt: TDictionary<string, string> read FContentTypesForExt; property InclusionFilters: TStringList read FInclusionFilters; property ExclusionFilters: TStringList read FExclusionFilters; property IndexFileNames: TStringList read FIndexFileNames; end; function AtLeastOneMatch(const ASample: string; const AValues: TStringList): Boolean; implementation uses System.Types, System.IOUtils, System.Masks, System.StrUtils, WiRL.Core.Utils, WiRL.Rtti.Utils, WiRL.Core.Exceptions; function AtLeastOneMatch(const ASample: string; const AValues: TStringList): Boolean; var LIndex: Integer; begin Result := False; for LIndex := 0 to AValues.Count-1 do begin if MatchesMask(ASample, AValues[LIndex]) then begin Result := True; Break; end; end; end; { TFileSystemResource } function TFileSystemResource.CheckFilters(const AString: string): Boolean; begin if (ExclusionFilters.Count > 0) and AtLeastOneMatch(AString, ExclusionFilters) then begin Result := False; end else begin Result := (InclusionFilters.Count = 0) or AtLeastOneMatch(AString, InclusionFilters); end; end; constructor TFileSystemResource.Create; begin inherited Create; FRootFolder := ''; FIncludeSubFolders := False; FContentTypesForExt := TDictionary<string, string>.Create; FInclusionFilters := TStringList.Create; FExclusionFilters := TStringList.Create; FIndexFileNames := TStringList.Create; Init; end; destructor TFileSystemResource.Destroy; begin FIndexFileNames.Free; FExclusionFilters.Free; FInclusionFilters.Free; FContentTypesForExt.Free; inherited; end; function TFileSystemResource.DirectoryHasIndexFile(const ADirectory: string; out AIndexFullPath: string): Boolean; var LIndex: Integer; LIndexFileName: string; LIndexFullFileName: string; begin Result := False; for LIndex := 0 to IndexFileNames.Count-1 do begin LIndexFileName := IndexFileNames[LIndex]; LIndexFullFileName := TPath.Combine(ADirectory, LIndexFileName); if FileExists(LIndexFullFileName) then begin Result := True; AIndexFullPath := LIndexFullFileName; Break; end; end; end; procedure TFileSystemResource.GetContent; var LRelativePath: string; LFullPath: string; LIndexFileFullPath: string; begin FResponse.StatusCode := 404; LRelativePath := SmartConcat(URL.SubResourcesToArray, PathDelim); LFullPath := TPath.Combine(RootFolder, LRelativePath); if CheckFilters(LFullPath) then begin if FileExists(LFullPath) then ServeFileContent(LFullPath, FResponse) else if TDirectory.Exists(LFullPath) then begin if DirectoryHasIndexFile(LFullPath, LIndexFileFullPath) then ServeFileContent(LIndexFileFullPath, FResponse) else ServeDirectoryContent(LFullPath, FResponse); end; end; end; procedure TFileSystemResource.Init; begin InitContentTypesForExt; InitIndexFileNames; TRttiHelper.ForEachAttribute<WebAttribute>(Self, procedure (AAttrib: WebAttribute) begin AAttrib.ApplyToResource(Self); end ); end; procedure TFileSystemResource.InitContentTypesForExt; begin ContentTypesForExt.Add('.jpg', 'image/jpeg'); ContentTypesForExt.Add('.jpeg', 'image/jpeg'); ContentTypesForExt.Add('.png', 'image/png'); ContentTypesForExt.Add('.pdf', 'application/pdf'); ContentTypesForExt.Add('.htm', 'text/html'); ContentTypesForExt.Add('.html', 'text/html'); ContentTypesForExt.Add('.js', 'application/javascript'); ContentTypesForExt.Add('.css', 'text/css'); ContentTypesForExt.Add('.txt', 'text/plain'); end; procedure TFileSystemResource.InitIndexFileNames; begin IndexFileNames.Add('index.html'); IndexFileNames.Add('index.htm'); IndexFileNames.Add('default.html'); IndexFileNames.Add('default.htm'); end; procedure TFileSystemResource.ServeDirectoryContent(const ADirectory: string; const AResponse: TWiRLResponse); var LEntries: TStringDynArray; LIndex: Integer; LEntry: string; LEntryRelativePath: string; begin AResponse.StatusCode := 200; AResponse.ContentType := TMediaType.TEXT_HTML; AResponse.Content := '<html><body><ul>'; LEntries := TDirectory.GetFileSystemEntries(ADirectory); for LIndex := Low(LEntries) to High(LEntries) do begin LEntry := LEntries[LIndex]; if CheckFilters(LEntry) then begin LEntryRelativePath := ExtractRelativePath(RootFolder, LEntry); AResponse.Content := AResponse.Content + '<li>' + '<a href="' + LEntryRelativePath + '">' + LEntryRelativePath + '</a>' + IfThen(TDirectory.Exists(LEntry), ' (folder)') + '</li>'; end; end; AResponse.Content := AResponse.Content + '</ul></body></html>'; end; procedure TFileSystemResource.ServeFileContent(const AFileName: string; const AResponse: TWiRLResponse); var LFileExt: string; LContentType: string; begin LFileExt := ExtractFileExt(AFileName); AResponse.StatusCode := 200; AResponse.ContentStream := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyNone); if not ContentTypesForExt.TryGetValue(LFileExt, LContentType) then LContentType := TMediaType.APPLICATION_OCTET_STREAM; // default = binary AResponse.ContentType := LContentType; end; { RootFolderAttribute } procedure RootFolderAttribute.ApplyToResource( const AResource: TFileSystemResource); begin inherited; AResource.RootFolder := Path; AResource.IncludeSubFolders := IncludeSubFolders; end; constructor RootFolderAttribute.Create(const APath: string; const AIncludeSubFolders: Boolean); begin inherited Create; FPath := IncludeTrailingPathDelimiter(APath); FIncludeSubFolders := AIncludeSubFolders; end; { ContentTypeForFileExt } procedure ContentTypeForFileExt.ApplyToResource( const AResource: TFileSystemResource); begin inherited; AResource.ContentTypesForExt.Add(FFileExt, FContentType); end; constructor ContentTypeForFileExt.Create(const AContentType, AFileExt: string); begin inherited Create; FContentType := AContentType; FFileExt := AFileExt; end; { WebAttribute } procedure WebAttribute.ApplyToResource(const AResource: TFileSystemResource); begin end; { WebFilterAttribute } constructor WebFilterAttribute.Create(const APattern: string); begin inherited Create; FPattern := APattern; end; { IncludeAttribute } procedure IncludeAttribute.ApplyToResource(const AResource: TFileSystemResource); begin inherited; AResource.InclusionFilters.Add(Pattern); end; { ExcludeAttribute } procedure ExcludeAttribute.ApplyToResource(const AResource: TFileSystemResource); begin inherited; AResource.ExclusionFilters.Add(Pattern); end; end.
unit UDebuggerTests; interface uses Classes, SysUtils, Variants, {$ifdef Windows} ComObj, {$endif} dwsXPlatformTests, dwsComp, dwsCompiler, dwsExprs, dwsErrors, dwsUtils, dwsSymbols, dwsDebugger, dwsStrings; type TDebuggerTests = class (TTestCase) private FCompiler : TDelphiWebScript; FUnits : TdwsUnit; FDebugger : TdwsDebugger; FDebugEvalAtLine : Integer; FDebugEvalExpr : String; FDebugLastEvalResult : String; FDebugLastMessage : String; FDebugLastNotificationPos : TScriptPos; procedure DoCreateExternal(Info: TProgramInfo; var ExtObject: TObject); procedure DoCleanupExternal(externalObject : TObject); procedure DoGetValue(Info: TProgramInfo; ExtObject: TObject); procedure DoDebugEval(exec: TdwsExecution; expr: TExprBase); procedure DoDebugMessage(const msg : UnicodeString); procedure DoDebugExceptionNotification(const exceptObj : IInfo); public procedure SetUp; override; procedure TearDown; override; published procedure EvaluateSimpleTest; procedure EvaluateOutsideOfExec; procedure EvaluateContextTest; procedure EvaluateLocalVar; procedure ExecutableLines; procedure AttachToScript; procedure DebugMessage; procedure ExceptionNotification; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ type TTestObject = class private FField : String; public constructor Create(const value : String); end; // Create // constructor TTestObject.Create(const value : String); begin FField:=value; end; // ------------------ // ------------------ TDebuggerTests ------------------ // ------------------ // SetUp // procedure TDebuggerTests.SetUp; var cls : TdwsClass; cst : TdwsConstructor; meth : TdwsMethod; begin FCompiler:=TDelphiWebScript.Create(nil); FCompiler.Config.CompilerOptions:=[coContextMap, coAssertions]; FUnits:=TdwsUnit.Create(nil); FUnits.UnitName:='TestUnit'; FUnits.Script:=FCompiler; FDebugger:=TdwsDebugger.Create(nil); FDebugger.OnDebug:=DoDebugEval; FDebugger.OnDebugMessage:=DoDebugMessage; FDebugger.OnNotifyException:=DoDebugExceptionNotification; cls:=FUnits.Classes.Add; cls.Name:='TTestClass'; cls.OnCleanUp:=DoCleanupExternal; cst:=cls.Constructors.Add as TdwsConstructor; cst.Name:='Create'; cst.OnEval:=DoCreateExternal; meth:=cls.Methods.Add as TdwsMethod; meth.ResultType:='String'; meth.Name:='GetValue'; meth.OnEval:=DoGetValue; end; // TearDown // procedure TDebuggerTests.TearDown; begin FDebugger.Free; FUnits.Free; FCompiler.Free; end; // DoCreateExternal // procedure TDebuggerTests.DoCreateExternal(Info: TProgramInfo; var ExtObject: TObject); begin ExtObject:=TTestObject.Create('Hello'); end; // DoCleanupExternal // procedure TDebuggerTests.DoCleanupExternal(externalObject : TObject); begin externalObject.Free; end; // DoGetValue // procedure TDebuggerTests.DoGetValue(Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsString:=(ExtObject as TTestObject).FField; end; // DoDebugEval // procedure TDebuggerTests.DoDebugEval(exec: TdwsExecution; expr: TExprBase); var p : TScriptPos; begin p:=expr.ScriptPos; if p.Line=FDebugEvalAtLine then FDebugLastEvalResult:=FDebugger.EvaluateAsString(FDebugEvalExpr, @p); end; // DoDebugMessage // procedure TDebuggerTests.DoDebugMessage(const msg : UnicodeString); begin FDebugLastMessage:=msg; end; // DoDebugExceptionNotification // procedure TDebuggerTests.DoDebugExceptionNotification(const exceptObj : IInfo); var expr : TExprBase; begin if exceptObj<>nil then expr:=exceptObj.Exec.GetLastScriptErrorExpr else expr:=nil; if expr<>nil then FDebugLastNotificationPos:=expr.ScriptPos else FDebugLastNotificationPos:=cNullPos; end; // EvaluateSimpleTest // procedure TDebuggerTests.EvaluateSimpleTest; var prog : IdwsProgram; exec : IdwsProgramExecution; expr : IdwsEvaluateExpr; buf : UnicodeString; begin prog:=FCompiler.Compile('var i := 10;'); try exec:=prog.BeginNewExecution; try exec.RunProgram(0); CheckEquals(10, exec.Info.ValueAsInteger['i'], 'value of i'); expr:=TdwsCompiler.Evaluate(exec, 'i+i*10'); try CheckEquals(110, expr.Expression.EvalAsInteger(exec.ExecutionObject), 'i+i*10'); finally expr:=nil; end; expr:=TdwsCompiler.Evaluate(exec, 'StrToInt(''123'')'); try CheckEquals(123, expr.Expression.EvalAsInteger(exec.ExecutionObject), 'StrToInt(''123'')'); finally expr:=nil; end; expr:=TdwsCompiler.Evaluate(exec, 'i +* i'); try expr.Expression.EvalAsString(exec.ExecutionObject, buf); CheckEquals('Syntax Error: Expression expected [line: 1, column: 4]'#13#10, buf, 'i +* i'); finally expr:=nil; end; finally exec.EndProgram; exec:=nil; end; finally prog:=nil; end; end; // EvaluateOutsideOfExec // procedure TDebuggerTests.EvaluateOutsideOfExec; var expr : IdwsEvaluateExpr; begin expr:=TdwsCompiler.Evaluate(nil, 'StrToInt(''113'')+10'); try CheckEquals(123, expr.Expression.EvalAsInteger(expr.Execution.ExecutionObject), 'StrToInt(''113'')+10'); finally expr:=nil; end; end; // EvaluateContextTest // procedure TDebuggerTests.EvaluateContextTest; var prog : IdwsProgram; exec : IdwsProgramExecution; begin prog:=FCompiler.Compile( 'var i := 1;'#13#10 +'procedure Test;'#13#10 +'var i := 2;'#13#10 +'begin'#13#10 +'PrintLn(i);'#13#10 // line 5 +'end;'#13#10 +'Test;'); // line 7 try exec:=prog.CreateNewExecution; try FDebugEvalExpr:='i'; FDebugEvalAtLine:=5; FDebugLastEvalResult:=''; FDebugger.BeginDebug(exec); try CheckEquals('2', FDebugLastEvalResult, 'i at line 5'); finally FDebugger.EndDebug; end; FDebugEvalAtLine:=7; FDebugLastEvalResult:=''; FDebugger.BeginDebug(exec); try CheckEquals('1', FDebugLastEvalResult, 'i at line 7'); finally FDebugger.EndDebug; end; finally exec:=nil; end; finally prog:=nil; end; end; // EvaluateLocalVar // procedure TDebuggerTests.EvaluateLocalVar; var prog : IdwsProgram; exec : IdwsProgramExecution; begin prog:=FCompiler.Compile( 'for var i := 1 to 1 do'#13#10 +'PrintLn(i);'); try exec:=prog.CreateNewExecution; try FDebugEvalExpr:='i'; FDebugEvalAtLine:=2; FDebugLastEvalResult:=''; FDebugger.BeginDebug(exec); try CheckEquals('1', FDebugLastEvalResult, 'i at line 2'); finally FDebugger.EndDebug; end; finally exec:=nil; end; finally prog:=nil; end; end; // ExecutableLines // procedure TDebuggerTests.ExecutableLines; var prog : IdwsProgram; breakpointables : TdwsBreakpointableLines; function ReportBreakpointables : String; var i, j : Integer; lines : TBits; sourceNames : TStringList; begin Result:=''; sourceNames:=TStringList.Create; try breakpointables.Enumerate(sourceNames); sourceNames.Sort; for i:=0 to sourceNames.Count-1 do begin if i>0 then Result:=Result+#13#10; Result:=Result+sourceNames[i]+': '; lines:=sourceNames.Objects[i] as TBits; for j:=0 to lines.Size-1 do if lines[j] then Result:=Result+IntToStr(j)+','; end; finally sourceNames.Free; end; end; begin prog:=FCompiler.Compile( 'var i := 1;'#13#10 +'procedure Test;'#13#10 +'var i := 2;'#13#10 +'begin'#13#10 +'PrintLn(i);'#13#10 +'end;'#13#10 +'Test;'); CheckEquals('2'#13#10, prog.Execute.Result.ToString, 'Result 1'); breakpointables:=TdwsBreakpointableLines.Create(prog); CheckEquals('*MainModule*: 1,3,4,5,7,', ReportBreakpointables, 'Case 1'); breakpointables.Free; prog:=FCompiler.Compile( 'var i := 1;'#13#10 +'procedure Test;'#13#10 +'begin'#13#10 +'var i := 2;'#13#10 +'PrintLn(i);'#13#10 +'end;'#13#10 +'i:=i+1;'); CheckEquals('', prog.Execute.Result.ToString, 'Result 2'); breakpointables:=TdwsBreakpointableLines.Create(prog); CheckEquals('*MainModule*: 1,3,4,5,7,', ReportBreakpointables, 'Case 2'); breakpointables.Free; end; // AttachToScript // procedure TDebuggerTests.AttachToScript; var prog : IdwsProgram; exec : IdwsProgramExecution; begin prog:=FCompiler.Compile( 'var i : Integer;'#13#10 +'procedure Test;'#13#10 +'begin'#13#10 +'Print(Inc(i));'#13#10 +'end;'#13#10 +'Test;'); CheckEquals('', prog.Msgs.AsInfo, 'compile'); exec:=prog.BeginNewExecution; exec.RunProgram(0); try CheckEquals('1', exec.Result.ToString, 'run'); FDebugger.AttachDebug(exec); CheckEquals('1', FDebugger.EvaluateAsString('i'), 'eval after attach'); exec.Info.Func['Test'].Call; CheckEquals('2', FDebugger.EvaluateAsString('i'), 'eval after call'); CheckEquals('12', exec.Result.ToString, 'result after call'); FDebugger.DetachDebug; CheckEquals(DBG_NotDebugging, FDebugger.EvaluateAsString('i'), 'eval after detach'); exec.Info.Func['Test'].Call; CheckEquals('123', exec.Result.ToString, 'result after re-call'); finally exec.EndProgram; end; end; // DebugMessage // procedure TDebuggerTests.DebugMessage; var prog : IdwsProgram; exec : IdwsProgramExecution; begin prog:=FCompiler.Compile( 'OutputDebugString("hello");'); CheckEquals('', prog.Msgs.AsInfo, 'compile'); FDebugLastMessage:=''; exec:=prog.CreateNewExecution; FDebugger.BeginDebug(exec); FDebugger.EndDebug; CheckEquals('', exec.Msgs.AsInfo, 'exec'); CheckEquals('hello', FDebugLastMessage, 'msg'); end; // ExceptionNotification // procedure TDebuggerTests.ExceptionNotification; var prog : IdwsProgram; exec : IdwsProgramExecution; procedure RunExceptNotification(const source : String); begin prog:=FCompiler.Compile(source); CheckEquals('', prog.Msgs.AsInfo, 'compile '+source); FDebugLastNotificationPos:=cNullPos; exec:=prog.CreateNewExecution; FDebugger.BeginDebug(exec); FDebugger.EndDebug; end; begin RunExceptNotification('var i : Integer;'#13#10'raise Exception.Create("here");'); CheckEquals(' [line: 2, column: 31]', FDebugLastNotificationPos.AsInfo, '1'); RunExceptNotification('var i : Integer; Assert(False);'); CheckEquals(' [line: 1, column: 18]', FDebugLastNotificationPos.AsInfo, '2'); RunExceptNotification('var i : Integer;'#13#10'try i := i div i; except end;'); CheckEquals(' [line: 2, column: 12]', FDebugLastNotificationPos.AsInfo, '3'); RunExceptNotification('procedure Test;'#13#10'begin'#13#10'var i:=0;'#13#10'i := i div i;'#13#10'end;'#13#10'Test'); CheckEquals(' [line: 4, column: 8]', FDebugLastNotificationPos.AsInfo, '4'); end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ RegisterTest('DebuggerTests', TDebuggerTests); end.
unit MPI_Complex; interface type TComplex = record re, im : Extended; end; function Add_C(a, b : TComplex) : TComplex; function Sub_C(a, b : TComplex) : TComplex; function Mul_C(a, b : TComplex) : TComplex; function Div_C(a, b : TComplex) : TComplex; implementation function Add_C(a, b : TComplex) : TComplex; begin Result.re := a.re + b.re; Result.im := a.im + b.im; end; function Sub_C(a, b : TComplex) : TComplex; begin Result.re := a.re - b.re; Result.im := a.im - b.im; end; function Mul_C(a, b : TComplex) : TComplex; begin Result.re := a.re*b.re - a.im*b.im; Result.im := a.re*b.im + a.im*b.re; end; function Div_C(a, b : TComplex) : TComplex; begin Result.re := (a.re*b.re + a.im*b.im) / (b.re*b.re + b.im*b.im); Result.im := (a.im*b.re - a.re*b.im) / (b.re*b.re + b.im*b.im); end; end.
unit AqDrop.Core.Log; interface uses System.SysUtils, System.Classes, AqDrop.Core.Collections.Intf, AqDrop.Core.Observers.Intf, AqDrop.Core.Observers; type IAqLog<T> = interface(IAqObservable<T>) ['{E0E5390F-2145-4CD6-AE23-9C067BE6E253}'] function GetDefaultFormatMessage: string; procedure SetDefaultFormatMessage(const pValue: string); property DefaultFormatMessage: string read GetDefaultFormatMessage write SetDefaultFormatMessage; end; TAqLogMessage = class FDateTime: TDateTime; FSender: IAqLog<TAqLogMessage>; FMessage: string; public constructor Create(pSender: IAqLog<TAqLogMessage>; const pMessage: string); function GetDefaultFormatMessage: string; property DateTime: TDateTime read FDateTime; property Sender: IAqLog<TAqLogMessage> read FSender; property Message: string read FMessage; public const THREAD_ID_PLACE_HOLDER = '%thid'; end; TAqLog = class(TAqObservable<TAqLogMessage>, IAqObservable<TAqLogMessage>, IAqLog<TAqLogMessage>) strict private FDefaultFormatMesssage: string; FExecutionLevels: IAqDictionary<TThreadID, UInt32>; function IncrementExecutionLevel: UInt32; procedure DecrementExecutionLevel; function GetDefaultFormatMessage: string; procedure SetDefaultFormatMessage(const pValue: string); function GetExceptionMessage(const pException: Exception): string; class var FDefaultInstance: TAqLog; class function GetDefaultInstance: TAqLog; static; public constructor Create; class procedure InitializeDefaultInstance; class procedure ReleaseDefaultInstance; procedure Log(const pMessage: string); overload; procedure Log(const pFormat: string; const pParameters: array of const); overload; procedure Log(const pException: Exception); overload; inline; procedure LogExecution(const pDescription: string; const pMethod: TProc); class property DefaultInstance: TAqLog read GetDefaultInstance; end; implementation uses AqDrop.Core.Exceptions, AqDrop.Core.Helpers, AqDrop.Core.Helpers.Exception, AqDrop.Core.Collections; resourcestring StrExceptionLogFormat = 'Error: %s (%s)'; { TAqLogMessage } constructor TAqLogMessage.Create(pSender: IAqLog<TAqLogMessage>; const pMessage: string); begin FDateTime := Now; FSender := pSender; FMessage := pMessage; end; function TAqLogMessage.GetDefaultFormatMessage: string; var lFormat: string; begin lFormat := FormatDateTime(FSender.DefaultFormatMessage, FDateTime); if lFormat.Contains(THREAD_ID_PLACE_HOLDER, False) then begin lFormat := lFormat.Replace(THREAD_ID_PLACE_HOLDER, FormatFloat('000000', TThread.CurrentThread.ThreadID), [rfIgnoreCase]); end; Result := Format(lFormat, [FMessage]); end; { TAqLog } constructor TAqLog.Create; begin inherited Create(True); FDefaultFormatMesssage := 'hh:mm:ss:zzz ''' + TAqLogMessage.THREAD_ID_PLACE_HOLDER + ''' ''%s'''; FExecutionLevels := TAqDictionary<TThreadID, UInt32>.Create(TAqLockerType.lktMultiReaderExclusiveWriter); end; procedure TAqLog.DecrementExecutionLevel; var lExecutionLevel: UInt32; lThreadID: TThreadID; begin lThreadID := TThread.CurrentThread.ThreadID; FExecutionLevels.ExecuteLockedForWriting( procedure begin if not FExecutionLevels.TryGetValue(lThreadID, lExecutionLevel) or (lExecutionLevel = 0) then begin raise EAqInternal.Create('No execution level to decrement in log management.'); end; Dec(lExecutionLevel); FExecutionLevels.Items[lThreadID] := lExecutionLevel; end); end; function TAqLog.GetDefaultFormatMessage: string; begin Result := FDefaultFormatMesssage; end; class function TAqLog.GetDefaultInstance: TAqLog; begin InitializeDefaultInstance; Result := FDefaultInstance; end; function TAqLog.GetExceptionMessage(const pException: Exception): string; begin Result := Format(StrExceptionLogFormat, [ pException.Message, pException.QualifiedClassName]); if Assigned(pException.InnerException) then begin Result := Result + string.LineBreak + ' caused by ' + pException.InnerException.ConcatFullMessage(string.LineBreak + ' '); end; end; function TAqLog.IncrementExecutionLevel: UInt32; var lExecutionLevel: UInt32; lThreadID: TThreadID; begin lThreadID := TThread.CurrentThread.ThreadID; FExecutionLevels.ExecuteLockedForWriting( procedure begin if FExecutionLevels.TryGetValue(lThreadID, lExecutionLevel) then begin Inc(lExecutionLevel); end else begin lExecutionLevel := 1; end; FExecutionLevels.AddOrSetValue(lThreadID, lExecutionLevel); end); Result := lExecutionLevel; end; class procedure TAqLog.InitializeDefaultInstance; begin if not Assigned(FDefaultInstance) then begin FDefaultInstance := Self.Create; end; end; procedure TAqLog.Log(const pException: Exception); begin Log(GetExceptionMessage(pException)); end; procedure TAqLog.LogExecution(const pDescription: string; const pMethod: TProc); var lExecutionLevel: UInt32; procedure LogWithExecutionLevelMarker(pMessage: string); begin if lExecutionLevel > 0 then begin pMessage := string.Create('>', lExecutionLevel) + ' ' + pMessage; end; Log(pMessage); end; begin lExecutionLevel := IncrementExecutionLevel - 1; try LogWithExecutionLevelMarker('Starting ' + pDescription); try pMethod; except on E: Exception do begin LogWithExecutionLevelMarker('Error while running ' + pDescription + ' > ' + GetExceptionMessage(E)); raise; end; end; LogWithExecutionLevelMarker('Ending ' + pDescription); finally DecrementExecutionLevel; end; end; procedure TAqLog.Log(const pFormat: string; const pParameters: array of const); begin Log(Format(pFormat, pParameters)); end; procedure TAqLog.Log(const pMessage: string); var lMessage: TAqLogMessage; begin lMessage := TAqLogMessage.Create(Self, pMessage); try Notify(lMessage); finally lMessage.Free; end; end; class procedure TAqLog.ReleaseDefaultInstance; begin FreeAndNil(FDefaultInstance); end; procedure TAqLog.SetDefaultFormatMessage(const pValue: string); begin FDefaultFormatMesssage := pValue; end; initialization finalization TAqLog.ReleaseDefaultInstance; end.
UNIT Novell; {---------------------------------------------------------------------------} { } { This UNIT provides a method of obtaining Novell information from a user } { written program. This UNIT was tested on an IBM AT running DOS 4.0 & } { using Netware 2.15. The unit compiled cleanly under Turbo Pascal 6.0 } { } { Last Update: 8 Apr 91 } {---------------------------------------------------------------------------} { } { Any questions can be directed to: } { } { Mark Bramwell } { University of Western Ontario } { London, Ontario, N6A 3K7 } { } { Phone: 519-473-3618 [work] 519-473-3618 [home] } { } { Bitnet: mark@hamster.business.uwo.ca Packet: ve3pzr @ ve3gyq } { } { Anonymous FTP Server Internet Address: 129.100.22.100 } { } {---------------------------------------------------------------------------} { Any other Novell UNITS gladly accepted. } { mods February 1 1991, Ross Lazarus (rml@extro.ucc.su.AU.OZ) var retcodes in procedure getservername, get_broadcast_message, verify_object_password comments, password conversion to upper case, Seems to work fine on a Netware 3.00 and on 3.01 servers - } INTERFACE Uses Dos; Const Months : Array [1..12] of String[3] = ('JAN','FEB','MAR','APR','MAY','JUN', 'JUL','AUG','SEP','OCT','NOV','DEC'); HEXDIGITS : Array [0..15] of char = '0123456789ABCDEF'; VAR {----------------------------------------------------------------------} { The following values can be pulled from an user written application } { } { The programmer would first call GetServerInfo. } { Then he could writeln(serverinfo.name) to print the server name } {----------------------------------------------------------------------} ServerInfo : Record ReturnLength : Integer; Server : Packed Array [1..48] of Byte; NetwareVers : Byte; NetwareSubV : Byte; ConnectionMax : array [1..2] of byte; ConnectionUse : array [1..2] of byte; MaxConVol : array [1..2] of byte; {} OS_revision : byte; SFT_level : byte; TTS_level : byte; peak_used : array [1..2] of byte; accounting_version : byte; vap_version : byte; queuing_version : byte; print_server_version : byte; virtual_console_version : byte; security_restrictions_version : byte; Internetwork_version_version : byte; Undefined : Packed Array [1..60] of Byte; peak_connections_used : integer; Connections_max : integer; Connections_in_use : integer; Max_connected_volumes : integer; name : string; End; procedure GetConnectionInfo(var LogicalStationNo: integer; var name,hex_id:string; var conntype:integer; var datetime:string; var retcode:integer); { returns username and login date/time when you supply the station number. } procedure clear_connection(connection_number : integer; var retcode : integer); { kicks the workstation off the server} procedure GetHexID(var userid,hexid: string; var retcode: integer); { returns the novell hexid of an username when you supply the username. } procedure GetServerInfo; { returns various info of the default server } procedure GetUser( var _station: integer; var _username: string; var retcode:integer); { returns logged-in station username when you supply the station number. } procedure GetNode( var hex_addr: string; var retcode: integer); { returns your physical network node in hex. } procedure GetStation( var _station: integer; var retcode: integer); { returns the station number of your workstation } procedure GetServerName(var servername : string; var retcode : integer); { returns the name of the current server } procedure Send_Message_to_Username(username,message : string; var retcode: integer); { Sends a novell message to the userid's workstation } procedure Send_Message_to_Station(station:integer; message : string; var retcode: integer); { Sends a message to the workstation station # } procedure Get_Volume_Name(var volume_name: string; volume_number: integer; var retcode:integer); { Gets the Volume name from Novell network drive } { Example: SYS Note: default drive must be a } { network drive. } procedure get_realname(var userid:string; var realname:string; var retcode:integer); { You supply the userid, and it returns the realname as stored by syscon. } { Example: userid=mbramwel realname=Mark Bramwell } procedure get_broadcast_mode(var bmode:integer); procedure set_broadcast_mode(bmode:integer); procedure get_broadcast_message(var bmessage: string; var retcode : integer); procedure get_server_datetime(var _year,_month,_day,_hour,_min,_sec,_dow:integer); { pulls from the server the date, time and Day Of Week } procedure set_date_from_server; { pulls the date from the server and updates the workstation's clock } procedure set_time_from_server; { pulls the time from the server and updates the workstation's clock } procedure get_server_version(var _version : string); procedure open_message_pipe(var _connection, retcode : integer); procedure close_message_pipe(var _connection, retcode : integer); procedure check_message_pipe(var _connection, retcode : integer); procedure send_personal_message(var _connection : integer; var _message : string; var retcode : integer); procedure get_personal_message(var _connection : integer; var _message : string; var retcode : integer); procedure get_drive_connection_id(var drive_number, server_number : integer); {pass the drive number - it returns the server number if a network volume} procedure get_file_server_name(var server_number : integer; var server_name : string); procedure get_directory_path(var handle : integer; var pathname : string; var retcode : integer); procedure get_drive_handle_id(var drive_number, handle_number : integer); procedure set_preferred_connection_id(server_num : integer); procedure get_preferred_connection_id(var server_num : integer); procedure set_primary_connection_id(server_num : integer); procedure get_primary_connection_id(var server_num : integer); procedure get_default_connection_id(var server_num : integer); procedure Get_Internet_Address(station : integer; var net_number, node_addr, socket_number : string; var retcode : integer); procedure login_to_file_server(obj_type:integer; _name,_password : string;var retcode:integer); procedure logout; procedure logout_from_file_server(var id: integer); procedure down_file_server(flag:integer;var retcode : integer); procedure detach_from_file_server(var id,retcode:integer); procedure disable_file_server_login(var retcode : integer); procedure enable_file_server_login(var retcode : integer); procedure alloc_permanent_directory_handle(var _dir_handle : integer; var _drive_letter : string; var _dir_path_name : string; var _new_dir_handle : integer; var _effective_rights: byte; var _retcode : integer); procedure map(var drive_spec:string; var _rights:byte; var _retcode : integer); procedure scan_object(var last_object: longint; var search_object_type: integer; var search_object : string; var replyid : longint; var replytype : integer; var replyname : string; var replyflag : integer; var replysecurity : byte; var replyproperties : integer; var retcode : integer); procedure verify_object_password(var object_type:integer; var object_name,password : string; var retcode : integer); {--------------------------------------------------------------------------} { file locking routines } {-----------------------} procedure log_file(lock_directive:integer; log_filename: string; log_timeout:integer; var retcode:integer); procedure clear_file_set; procedure lock_file_set(lock_timeout:integer; var retcode:integer); procedure release_file_set; procedure release_file(log_filename: string; var retcode:integer); procedure clear_file(log_filename: string; var retcode:integer); {-----------------------------------------------------------------------------} procedure open_semaphore( _name:string; _initial_value:shortint; var _open_count:integer; var _handle:longint; var retcode:integer); procedure close_semaphore(var _handle:longint; var retcode:integer); procedure examine_semaphore(var _handle:longint; var _value:shortint; var _count, retcode:integer); procedure signal_semaphore(var _handle:longint; var retcode:integer); procedure wait_on_semaphore(var _handle:longint; _timeout:integer; var retcode:integer); {-----------------------------------------------------------------------------} IMPLEMENTATION const zero = '0'; var retcode : byte; { return code for all functions } procedure get_volume_name(var volume_name: string; volume_number: integer; var retcode:integer); { pulls volume names from default server. Use set_preferred_connection_id to set the default server. retcodes: 0=ok, 1=no volume assigned 98h= # out of range } VAR pcregs : Registers; count,count1 : integer; requestbuffer : record len : integer; func : byte; vol_num : byte; end; replybuffer : record len : integer; vol_length : byte; name : packed array [1..16] of byte; end; begin With pcregs do begin ah := $E2; ds := seg(requestbuffer); si := ofs(requestbuffer); es := seg(replybuffer); di := ofs(replybuffer); end; With requestbuffer do begin len := 2; func := 6; vol_num := volume_number; {passed from calling program} end; With replybuffer do begin len := 17; vol_length := 0; for count := 1 to 16 do name[count] := $00; end; msdos(pcregs); volume_name := ''; if replybuffer.vol_length > 0 then for count := 1 to replybuffer.vol_length do volume_name := volume_name + chr(replybuffer.name[count]); retcode := pcregs.al; end; procedure verify_object_password(var object_type:integer; var object_name,password : string; var retcode : integer); { for netware 3.xx remember to have previously (eg in the autoexec file ) set allow unencrypted passwords = on on the console, otherwise this call always fails ! Note that intruder lockout status is affected by this call ! Netware security isn't that stupid.... Passwords appear to need to be converted to upper case retcode apparent meaning as far as I can work out.... 0 verification of object_name/password combination 197 account disabled due to intrusion lockout 214 unencrypted password calls not allowed on this v3+ server 252 no such object_name on this server 255 failure to verify object_name/password combination } var regs : registers; request_buffer : record buffer_length : integer; subfunction : byte; obj_type : array [1..2] of byte; obj_name_length : byte; obj_name : array [1..47] of byte; password_length : byte; obj_password : array [1..127] of byte; end; reply_buffer : record buffer_length : integer; end; count : integer; begin With request_buffer do begin buffer_length := 179; subfunction := $3F; obj_type[1] := 0; obj_type[2] := object_type; obj_name_length := 47; for count := 1 to 47 do obj_name[count] := $00; for count := 1 to length(object_name) do obj_name[count] := ord(object_name[count]); password_length := length(password); for count := 1 to 127 do obj_password[count] := $00; if password_length > 0 then for count := 1 to password_length do obj_password[count] := ord(upcase(password[count])); end; With reply_buffer do buffer_length := 0; With regs do begin Ah := $E3; Ds := Seg(Request_Buffer); Si := Ofs(Request_Buffer); Es := Seg(Reply_Buffer); Di := Ofs(Reply_Buffer); End; msdos(regs); retcode := regs.al; end; { verify_object_password } procedure scan_object(var last_object: longint; var search_object_type: integer; var search_object : string; var replyid : longint; var replytype : integer; var replyname : string; var replyflag : integer; var replysecurity : byte; var replyproperties : integer; var retcode : integer); var regs : registers; request_buffer : record buffer_length : integer; subfunction : byte; last_seen : longint; search_type : array [1..2] of byte; name_length : byte; search_name : array [1..47] of byte; end; reply_buffer : record buffer_length : integer; object_id : longint; object_type : array [1..2] of byte; object_name : array [1..48] of byte; object_flag : byte; security : byte; properties : byte; end; count : integer; begin with request_buffer do begin buffer_length := 55; subfunction := $37; last_seen := last_object; if search_object_type = -1 then { -1 = wildcard } begin search_type[1] := $ff; search_type[2] := $ff; end else begin search_type[1] := 0; search_type[2] := search_object_type; end; name_length := length(search_object); for count := 1 to 47 do search_name[count] := $00; if name_length > 0 then for count := 1 to name_length do search_name[count] := ord(upcase(search_object[count])); end; With reply_buffer do begin buffer_length := 57; object_id:= 0; object_type[1] := 0; object_type[2] := 0; for count := 1 to 48 do object_name[count] := $00; object_flag := 0; security := 0; properties := 0; end; With Regs Do Begin Ah := $E3; Ds := Seg(Request_Buffer); Si := Ofs(Request_Buffer); Es := Seg(Reply_Buffer); Di := Ofs(Reply_Buffer); End; msdos(regs); retcode := regs.al; With reply_buffer do begin replyflag := object_flag; replyproperties := properties; replysecurity := security; replytype := object_type[2]; replyid := object_id; end; count := 1; replyname := ''; While (count <= 48) and (reply_buffer.Object_Name[count] <> 0) Do Begin replyName := replyname + Chr(reply_buffer.Object_name[count]); count := count + 1; End { while }; end; procedure alloc_permanent_directory_handle (var _dir_handle : integer; var _drive_letter : string; var _dir_path_name : string; var _new_dir_handle : integer; var _effective_rights: byte; var _retcode : integer); var regs : registers; request_buffer : record buffer_length : integer; subfunction : byte; dir_handle : byte; drive_letter : byte; dir_path_length : byte; dir_path_name : packed array [1..255] of byte; end; reply_buffer : record buffer_length : integer; new_dir_handle : byte; effective_rights : byte; end; count : integer; begin With request_buffer do begin buffer_length := 259; subfunction := $12; dir_handle := _dir_handle; drive_letter := ord(upcase(_drive_letter[1])); dir_path_length := length(_dir_path_name); for count := 1 to 255 do dir_path_name[count] := $0; if dir_path_length > 0 then for count := 1 to dir_path_length do dir_path_name[count] := ord(upcase(_dir_path_name[count])); end; With reply_buffer do begin buffer_length := 2; new_dir_handle := 0; effective_rights := 0; end; With Regs Do Begin Ah := $E2; Ds := Seg(Request_Buffer); Si := Ofs(Request_Buffer); Es := Seg(Reply_Buffer); Di := Ofs(Reply_Buffer); End; msdos(regs); _retcode := regs.al; _effective_rights := $0; _new_dir_handle := $0; if _retcode = 0 then begin _effective_rights := reply_buffer.effective_rights; _new_dir_handle := reply_buffer.new_dir_handle; end; end; procedure map(var drive_spec:string; var _rights:byte; var _retcode : integer); var dir_handle : integer; path_name : string; rights : byte; drive_number : integer; drive_letter : string; new_handle : integer; retcode : integer; begin {first thing is we strip leading and trailing blanks} while drive_spec[1]=' ' do drive_spec := copy(drive_spec,2,length(drive_spec)); while drive_spec[length(drive_spec)]=' ' do drive_spec := copy(drive_spec,1,length(drive_spec)-1); drive_number := ord(upcase(drive_spec[1]))-65; drive_letter := upcase(drive_spec[1]); path_name := copy(drive_spec,4,length(drive_spec)); get_drive_handle_id(drive_number,dir_handle); alloc_permanent_directory_handle(dir_handle,drive_letter,path_name,new_handle,rights,retcode); _retcode := retcode; _rights := rights; end; procedure down_file_server(flag:integer;var retcode : integer); var regs : registers; request_buffer : record buffer_length : integer; subfunction : byte; down_flag : byte; end; reply_buffer : record buffer_length : integer; end; begin With request_buffer do begin buffer_length := 2; subfunction := $D3; down_flag := flag; end; reply_buffer.buffer_length := 0; With Regs Do Begin Ah := $E3; Ds := Seg(Request_Buffer); Si := Ofs(Request_Buffer); Es := Seg(Reply_Buffer); Di := Ofs(Reply_Buffer); End; msdos(regs); retcode := regs.al; end; procedure set_preferred_connection_id(server_num : integer); var regs : registers; begin regs.ah := $F0; regs.al := $00; regs.dl := server_num; msdos(regs); end; procedure set_primary_connection_id(server_num : integer); var regs : registers; begin regs.ah := $F0; regs.al := $04; regs.dl := server_num; msdos(regs); end; procedure get_primary_connection_id(var server_num : integer); var regs : registers; begin regs.ah := $F0; regs.al := $05; msdos(regs); server_num := regs.al; end; procedure get_default_connection_id(var server_num : integer); var regs : registers; begin regs.ah := $F0; regs.al := $02; msdos(regs); server_num := regs.al; end; procedure get_preferred_connection_id(var server_num : integer); var regs : registers; begin regs.ah := $F0; regs.al := $02; msdos(regs); server_num := regs.al; end; procedure get_drive_connection_id(var drive_number, server_number : integer); var regs : registers; drive_table : array [1..32] of byte; count : integer; p : ^byte; begin regs.ah := $EF; regs.al := $02; msdos(regs); p := ptr(regs.es, regs.si); move(p^,drive_table,32); if ((drive_number < 0) or (drive_number > 32)) then drive_number := 1; server_number := drive_table[drive_number]; end; procedure get_drive_handle_id(var drive_number, handle_number : integer); var regs : registers; drive_table : array [1..32] of byte; count : integer; p : ^byte; begin regs.ah := $EF; regs.al := $00; msdos(regs); p := ptr(regs.es, regs.si); move(p^,drive_table,32); if ((drive_number < 0) or (drive_number > 32)) then drive_number := 1; handle_number := drive_table[drive_number]; end; procedure get_file_server_name(var server_number : integer; var server_name : string); var regs : registers; name_table : array [1..8*48] of byte; server : array [1..8] of string; count : integer; count2 : integer; p : ^byte; no_more : integer; begin regs.ah := $EF; regs.al := $04; msdos(regs); no_more := 0; p := ptr(regs.es, regs.si); move(p^,name_table,8*48); for count := 1 to 8 do server[count] := ''; for count := 0 to 7 do begin no_more := 0; for count2 := (count*48)+1 to (count*48)+48 do if name_table[count2] <> $00 then begin if no_more=0 then server[count+1] := server[count+1] + chr(name_table[count2]); end else no_more:=1; {scan until 00h is found} end; if ((server_number<1) or (server_number>8)) then server_number := 1; server_name := server[server_number]; end; procedure disable_file_server_login(var retcode : integer); var regs : registers; request_buffer : record buffer_length : integer; subfunction : byte end; reply_buffer : record buffer_length : integer; end; begin With Regs Do Begin Ah := $E3; Ds := Seg(Request_Buffer); Si := Ofs(Request_Buffer); Es := Seg(Reply_Buffer); Di := Ofs(Reply_Buffer); End; With request_buffer do begin buffer_length := 1; subfunction := $CB; end; reply_buffer.buffer_length := 0; msdos(regs); retcode := regs.al; end; procedure enable_file_server_login(var retcode : integer); var regs : registers; request_buffer : record buffer_length : integer; subfunction : byte end; reply_buffer : record buffer_length : integer; end; begin With Regs Do Begin Ah := $E3; Ds := Seg(Request_Buffer); Si := Ofs(Request_Buffer); Es := Seg(Reply_Buffer); Di := Ofs(Reply_Buffer); End; With request_buffer do begin buffer_length := 1; subfunction := $CC; end; reply_buffer.buffer_length := 0; msdos(regs); retcode := regs.al; end; procedure get_directory_path(var handle : integer; var pathname : string; var retcode : integer); var regs : registers; count : integer; request_buffer : record len : integer; subfunction : byte; dir_handle : byte; end; reply_buffer : record len : integer; path_len : byte; path_name : array [1..255] of byte; end; begin With Regs Do Begin Ah := $e2; Ds := Seg(Request_Buffer); Si := Ofs(Request_Buffer); Es := Seg(Reply_Buffer); Di := Ofs(Reply_Buffer); End; With request_buffer do begin len := 2; subfunction := $01; dir_handle := handle; end; With reply_buffer do begin len := 256; path_len := 0; for count := 1 to 255 do path_name[count] := $00; end; msdos(regs); retcode := regs.al; pathname := ''; if reply_buffer.path_len > 0 then for count := 1 to reply_buffer.path_len do pathname := pathname + chr(reply_buffer.path_name[count]); end; procedure detach_from_file_server(var id,retcode:integer); var regs : registers; begin regs.ah := $F1; regs.al := $01; regs.dl := id; msdos(regs); retcode := regs.al; end; procedure getstation( var _station: integer; var retcode: integer); VAR pcregs : Registers; begin pcregs.ah := $DC; MsDos( pcregs ); _station := pcregs.al; retcode := 0; end; procedure GetHexID( var userid,hexid: string; var retcode: integer); var reg : registers; i,x : integer; hex_id : string; requestbuffer : record len : integer; func : byte; conntype : packed array [1..2] of byte; name_len : byte; name : packed array [1..47] of char; end; replybuffer : record len : integer; uniqueid1: packed array [1..2] of byte; uniqueid2: packed array [1..2] of byte; conntype : word; name : packed array [1..48] of byte; end; begin reg.ah := $E3; requestbuffer.func := $35; reg.ds := seg(requestbuffer); reg.si := ofs(requestbuffer); reg.es := seg(replybuffer); reg.di := ofs(replybuffer); requestbuffer.len := 52; replybuffer.len := 55; requestbuffer.name_len := length(userid); for i := 1 to length(userid) do requestbuffer.name[i] := userid[i]; requestbuffer.conntype[2] := $1; requestbuffer.conntype[1] := $0; replybuffer.conntype := 1; msdos(reg); retcode := reg.al; { if retcode = $96 then writeln('Server out of memory'); if retcode = $EF then writeln('Invalid name'); if retcode = $F0 then writeln('Wildcard not allowed'); if retcode = $FC then writeln('No such object *',userid,'*'); if retcode = $FE then writeln('Server bindery locked'); if retcode = $FF then writeln('Bindery failure'); } hex_id := ''; if retcode = 0 then begin hex_id := hexdigits[replybuffer.uniqueid1[1] shr 4]; hex_id := hex_id + hexdigits[replybuffer.uniqueid1[1] and $0F]; hex_id := hex_id + hexdigits[replybuffer.uniqueid1[2] shr 4]; hex_id := hex_id + hexdigits[replybuffer.uniqueid1[2] and $0F]; hex_id := hex_id + hexdigits[replybuffer.uniqueid2[1] shr 4]; hex_id := hex_id + hexdigits[replybuffer.uniqueid2[1] and $0F]; hex_id := hex_id + hexdigits[replybuffer.uniqueid2[2] shr 4]; hex_id := hex_id + hexdigits[replybuffer.uniqueid2[2] and $0F]; { Now we chop off leading zeros } while hex_id[1] = '0' do hex_id := copy(hex_id,2,length(hex_id)); end; hexid := hex_id; end; Procedure GetConnectionInfo (Var LogicalStationNo: Integer; Var Name: String; Var HEX_ID: String; Var ConnType : Integer; Var DateTime : String; Var retcode:integer); Var Reg : Registers; I,X : Integer; RequestBuffer : Record PacketLength : Integer; FunctionVal : Byte; ConnectionNo : Byte; End; ReplyBuffer : Record ReturnLength : Integer; UniqueID1 : Packed Array [1..2] of byte; UniqueID2 : Packed Array [1..2] of byte; ConnType : Packed Array [1..2] of byte; ObjectName : Packed Array [1..48] of Byte; LoginTime : Packed Array [1..8] of Byte; End; Month : String[3]; Year, Day, Hour, Minute : String[2]; Begin With RequestBuffer Do Begin PacketLength := 2; FunctionVal := 22; { 22 = Get Station Info } ConnectionNo := LogicalStationNo; End; ReplyBuffer.ReturnLength := 62; With Reg Do Begin Ah := $e3; Ds := Seg(RequestBuffer); Si := Ofs(RequestBuffer); Es := Seg(ReplyBuffer); Di := Ofs(ReplyBuffer); End; MsDos(Reg); name := ''; hex_id := ''; conntype := 0; datetime := ''; If Reg.al = 0 Then Begin With ReplyBuffer Do Begin I := 1; While (I <= 48) and (ObjectName[I] <> 0) Do Begin Name[I] := Chr(Objectname[I]); I := I + 1; End { while }; Name[0] := Chr(I - 1); if name<>'' then begin Str(LoginTime[1]:2,Year); Month := Months[LoginTime[2]]; Str(LoginTime[3]:2,Day); Str(LoginTime[4]:2,Hour); Str(LoginTime[5]:2,Minute); If Day[1] = ' ' Then Day[1] := '0'; If Hour[1] = ' ' Then Hour[1] := '0'; If Minute[1] = ' ' Then Minute[1] := '0'; DateTime := Day+'-'+Month+'-'+Year+' ' + Hour + ':' + Minute; End; End { with }; End; retcode := reg.al; if name<>'' then begin hex_id := ''; hex_id := hexdigits[replybuffer.uniqueid1[1] shr 4]; hex_id := hex_id + hexdigits[replybuffer.uniqueid1[1] and $0F]; hex_id := hex_id + hexdigits[replybuffer.uniqueid1[2] shr 4]; hex_id := hex_id + hexdigits[replybuffer.uniqueid1[2] and $0F]; hex_id := hex_id + hexdigits[replybuffer.uniqueid2[1] shr 4]; hex_id := hex_id + hexdigits[replybuffer.uniqueid2[1] and $0F]; hex_id := hex_id + hexdigits[replybuffer.uniqueid2[2] shr 4]; hex_id := hex_id + hexdigits[replybuffer.uniqueid2[2] and $0F]; ConnType := replybuffer.conntype[2]; { Now we chop off leading zeros } while hex_id[1]='0' do hex_id := copy(hex_id,2,length(hex_id)); End; End { GetConnectInfo }; procedure login_to_file_server(obj_type:integer;_name,_password : string;var retcode:integer); var regs : registers; request_buffer : record B_length : integer; subfunction : byte; o_type : packed array [1..2] of byte; name_length : byte; obj_name : packed array [1..47] of byte; password_length : byte; password : packed array [1..27] of byte; end; reply_buffer : record R_length : integer; end; count : integer; begin With request_buffer do begin B_length := 79; subfunction := $14; o_type[1] := 0; o_type[2] := obj_type; for count := 1 to 47 do obj_name[count] := $0; for count := 1 to 27 do password[count] := $0; if length(_name) > 0 then for count := 1 to length(_name) do obj_name[count]:=ord(upcase(_name[count])); if length(_password) > 0 then for count := 1 to length(_password) do password[count]:=ord(upcase(_password[count])); {set to full length of field} name_length := 47; password_length := 27; end; With reply_buffer do begin R_length := 0; end; With Regs Do Begin Ah := $e3; Ds := Seg(Request_Buffer); Si := Ofs(Request_Buffer); Es := Seg(reply_buffer); Di := Ofs(reply_buffer); End; MsDos(Regs); retcode := regs.al end; procedure logout; {logout from all file servers} var regs : registers; begin regs.ah := $D7; msdos(regs); end; procedure logout_from_file_server(var id: integer); {logout from one file server} var regs : registers; begin regs.ah := $F1; regs.al := $02; regs.dl := id; msdos(regs); end; procedure send_message_to_username(username,message : string; var retcode: integer); VAR count1 : byte; userid : string; stationid : integer; ret_code : integer; begin ret_code := 1; for count1:= 1 to length(username) do username[count1]:=upcase(username[count1]); { Convert to upper case } getserverinfo; for count1:= 1 to serverinfo.connections_max do begin stationid := count1; getuser( stationid, userid, retcode); if userid = username then begin ret_code := 0; send_message_to_station(stationid, message, retcode); end; end; { end of count } retcode := ret_code; { retcode = 0 if sent, 1 if userid not found } end; { end of procedure } Procedure GetServerInfo; Var Reg : Registers; RequestBuffer : Record PacketLength : Integer; FunctionVal : Byte; End; I : Integer; Begin With RequestBuffer Do Begin PacketLength := 1; FunctionVal := 17; { 17 = Get Server Info } End; ServerInfo.ReturnLength := 128; With Reg Do Begin Ah := $e3; Ds := Seg(RequestBuffer); Si := Ofs(RequestBuffer); Es := Seg(ServerInfo); Di := Ofs(ServerInfo); End; MsDos(Reg); With serverinfo do begin connections_max := connectionmax[1]*256 + connectionmax[2]; connections_in_use := connectionuse[1]*256 + connectionuse[2]; max_connected_volumes := maxconvol[1]*256 + maxconvol[2]; peak_connections_used := peak_used[1]*256 + peak_used[2]; name := ''; i := 1; while ((server[i] <> 0) and (i<>48)) do begin name := name + chr(server[i]); i := i + 1; end; end; End; procedure GetServerName(var servername : string; var retcode : integer); {-----------------------------------------------------------------} { This routine returns the same as GetServerInfo. This routine } { was kept to maintain compatibility with the older novell unit. } {-----------------------------------------------------------------} begin getserverinfo; servername := serverinfo.name; retcode := 0; end; procedure send_message_to_station(station:integer; message : string; var retcode: integer); VAR pcregs : Registers; req_buffer : record buffer_len : integer; subfunction: byte; c_count : byte; c_list : byte; msg_length : byte; msg : packed array [1..55] of byte; end; rep_buffer : record buffer_len : integer; c_count : byte; r_list : byte; end; count1 : integer; begin if length(message) > 55 then message:=copy(message,1,55); With PCRegs do begin ah := $E1; ds:=seg(req_buffer); si:=ofs(req_buffer); es:=seg(rep_buffer); di:=ofs(rep_buffer); End; With req_buffer do begin buffer_len := 59; subfunction := 00; c_count := 1; c_list := station; for count1:= 1 to 55 do msg[count1]:= $00; { zero the buffer } msg_length := length(message); { message length } for count1:= 1 to length(message) do msg[count1]:=ord(message[count1]); End; With rep_buffer do begin buffer_len := 2; c_count := 1; r_list := 0; End; msdos( pcregs ); retcode:= rep_buffer.r_list; end; procedure getuser( var _station: integer; var _username: string; var retcode: integer); {This procedure provides a shorter method of obtaining just the USERID.} var gu_hexid : string; gu_conntype : integer; gu_datetime : string; begin getconnectioninfo(_station,_username,gu_hexid,gu_conntype,gu_datetime,retcode); end; PROCEDURE GetNode( var hex_addr: string; var retcode: integer ); { get the physical station address } Const Hex_Set :packed array[0..15] of char = '0123456789ABCDEF'; Var Regs :Registers; Begin { GetNode } {Get the physical address from the Network Card} Regs.Ah := $EE; MsDos(Regs); hex_addr := ''; hex_addr := hex_addr + hex_set[(regs.ch shr 4)]; hex_addr := hex_addr + hex_set[(regs.ch and $0f)]; hex_addr := hex_addr + hex_set[(regs.cl shr 4) ]; hex_addr := hex_addr + hex_set[(regs.cl and $0f)]; hex_addr := hex_addr + hex_set[(regs.bh shr 4)]; hex_addr := hex_addr + hex_set[(regs.bh and $0f)]; hex_addr := hex_addr + hex_set[(regs.bl shr 4)]; hex_addr := hex_addr + hex_set[(regs.bl and $0f)]; hex_addr := hex_addr + hex_set[(regs.ah shr 4)]; hex_addr := hex_addr + hex_set[(regs.ah and $0f)]; hex_addr := hex_addr + hex_set[(regs.al shr 4)]; hex_addr := hex_addr + hex_set[(regs.al and $0f)]; retcode := 0; End; { Getnode } PROCEDURE Get_Internet_Address(station : integer; var net_number, node_addr, socket_number : string; var retcode : integer); Const Hex_Set :packed array[0..15] of char = '0123456789ABCDEF'; Var Regs :Registers; Request_buffer : record length : integer; subfunction : byte; connection : byte; end; Reply_Buffer : record length : integer; network : array [1..4] of byte; node : array [1..6] of byte; socket : array [1..2] of byte; end; count : integer; _node_addr : string; _socket_number : string; _net_number : string; begin With Regs do begin ah := $E3; ds:=seg(request_buffer); si:=ofs(request_buffer); es:=seg(reply_buffer); di:=ofs(reply_buffer); End; With request_buffer do begin length := 2; subfunction := $13; connection := station; end; With reply_buffer do begin length := 12; for count := 1 to 4 do network[count] := 0; for count := 1 to 6 do node[count] := 0; for count := 1 to 2 do socket[count] := 0; end; msdos(regs); retcode := regs.al; _net_number := ''; _node_addr := ''; _socket_number := ''; if retcode = 0 then begin for count := 1 to 4 do begin _net_number := _net_number + hex_set[ (reply_buffer.network[count] shr 4) ]; _net_number := _net_number + hex_set[ (reply_buffer.network[count] and $0F) ]; end; for count := 1 to 6 do begin _node_addr := _node_addr + (hex_set[ (reply_buffer.node[count] shr 4) ]); _node_addr := _node_addr + (hex_set[ (reply_buffer.node[count] and $0F) ]); end; for count := 1 to 2 do begin _socket_number := _socket_number + (hex_set[ (reply_buffer.socket[count] shr 4) ]); _socket_number := _socket_number + (hex_set[ (reply_buffer.socket[count] and $0F) ]); end; end; {end of retcode=0} net_number := _net_number; node_addr := _node_addr; socket_number := _socket_number; end; procedure get_realname(var userid,realname:string; var retcode:integer); var requestbuffer : record buffer_length : array [1..2] of byte; subfunction : byte; object_type : array [1..2] of byte; object_length : byte; object_name : array [1..47] of byte; segment : byte; property_length : byte; property_name : array [1..14] of byte; end; replybuffer : record buffer_length : array [1..2] of byte; property_value : array [1..128] of byte; more_segments : byte; property_flags : byte; end; count : integer; id : string; Regs : registers; fullname : string; begin id := 'IDENTIFICATION'; With requestbuffer do begin buffer_length[2] := 0; buffer_length[1] := 69; subfunction := $3d; object_type[1]:= 0; object_type[2]:= 01; segment := 1; object_length := 47; property_length := length(id); for count := 1 to 47 do object_name[count] := $0; for count := 1 to length(userid) do object_name[count] := ord(userid[count]); for count := 1 to 14 do property_name[count] := $0; for count := 1 to length(id) do property_name[count] := ord(id[count]); end; With replybuffer do begin buffer_length[1] := 130; buffer_length[2] := 0; for count := 1 to 128 do property_value[count] := $0; more_segments := 1; property_flags := 0; end; With Regs do begin Ah := $e3; Ds := Seg(requestbuffer); Si := Ofs(requestbuffer); Es := Seg(replybuffer); Di := Ofs(replybuffer); end; MSDOS(Regs); retcode := Regs.al; fullname := ''; count := 1; repeat begin if replybuffer.property_value[count]<>0 then fullname := fullname + chr(replybuffer.property_value[count]); count := count + 1; end; until ((count=128) or (replybuffer.property_value[count]=0)); {if regs.al = $96 then writeln('server out of memory'); if regs.al = $ec then writeln('no such segment'); if regs.al = $f0 then writeln('wilcard not allowed'); if regs.al = $f1 then writeln('invalid bindery security'); if regs.al = $f9 then writeln('no property read priv'); if regs.al = $fb then writeln('no such property'); if regs.al = $fc then writeln('no such object');} if retcode=0 then realname := fullname else realname:=''; end; procedure get_broadcast_mode(var bmode:integer); var regs : registers; begin regs.ah := $de; regs.dl := $04; msdos(regs); bmode := regs.al; end; procedure set_broadcast_mode(bmode:integer); var regs : registers; begin if ((bmode > 3) or (bmode < 0)) then bmode := 0; regs.ah := $de; regs.dl := bmode; msdos(regs); bmode := regs.al; end; procedure get_broadcast_message(var bmessage: string; var retcode : integer); var regs : registers; requestbuffer : record bufferlength : array [1..2] of byte; subfunction : byte; end; replybuffer : record bufferlength : array [1..2] of byte; messagelength : byte; message : array [1..58] of byte; end; count : integer; begin With Requestbuffer do begin bufferlength[1] := 1; bufferlength[2] := 0; subfunction := 1; end; With replybuffer do begin bufferlength[1] := 59; bufferlength[2] := 0; messagelength := 0; end; for count := 1 to 58 do replybuffer.message[count] := $0; With Regs do begin Ah := $e1; Ds := Seg(requestbuffer); Si := Ofs(requestbuffer); Es := Seg(replybuffer); Di := Ofs(replybuffer); end; MSDOS(Regs); retcode := Regs.al; bmessage := ''; count := 0; if replybuffer.messagelength > 58 then replybuffer.messagelength := 58; if replybuffer.messagelength > 0 then for count := 1 to replybuffer.messagelength do bmessage := bmessage + chr(replybuffer.message[count]); { retcode = 0 if no message, 1 if message was retreived } if length(bmessage) = 0 then retcode := 1 else retcode := 0; end; procedure get_server_datetime(var _year,_month,_day,_hour,_min,_sec,_dow:integer); var replybuffer : record year : byte; month : byte; day : byte; hour : byte; minute : byte; second : byte; dow : byte; end; regs : registers; begin With Regs do begin Ah := $e7; Ds := Seg(replybuffer); Dx := Ofs(replybuffer); end; MSDOS(Regs); retcode := Regs.al; _year := replybuffer.year; _month := replybuffer.month; _day := replybuffer.day; _hour := replybuffer.hour; _min := replybuffer.minute; _sec := replybuffer.second; _dow := replybuffer.dow; end; procedure set_date_from_server; var replybuffer : record year : byte; month : byte; day : byte; hour : byte; minute : byte; second : byte; dow : byte; end; regs : registers; begin With Regs do begin Ah := $e7; Ds := Seg(replybuffer); Dx := Ofs(replybuffer); end; MSDOS(Regs); setdate(replybuffer.year+1900,replybuffer.month,replybuffer.day); end; procedure set_time_from_server; var replybuffer : record year : byte; month : byte; day : byte; hour : byte; minute : byte; second : byte; dow : byte; end; regs : registers; begin With Regs do begin Ah := $e7; Ds := Seg(replybuffer); Dx := Ofs(replybuffer); end; MSDOS(Regs); settime(replybuffer.hour,replybuffer.minute,replybuffer.second,0); end; procedure get_server_version(var _version : string); var regs : registers; count,x : integer; request_buffer : record buffer_length : integer; subfunction : byte; end; reply_buffer : record buffer_length : integer; stuff : array [1..512] of byte; end; strings : array [1..3] of string; begin With Regs do begin Ah := $e3; Ds := Seg(request_buffer); Si := Ofs(request_buffer); Es := Seg(reply_buffer); Di := Ofs(reply_buffer); end; With request_buffer do begin buffer_length := 1; subfunction := $c9; end; With reply_buffer do begin buffer_length := 512; for count := 1 to 512 do stuff[count] := $00; end; MSDOS(Regs); for count := 1 to 3 do strings[count] := ''; x := 1; With reply_buffer do begin for count := 1 to 256 do begin if stuff[count] <> $0 then begin if not ((stuff[count]=32) and (strings[x]='')) then strings[x] := strings[x] + chr(stuff[count]); end; if stuff[count] = $0 then if x <> 3 then x := x + 1; end; End; { end of with } _version := strings[2]; end; procedure open_message_pipe(var _connection, retcode : integer); var regs : registers; request_buffer : record buffer_length : integer; subfunction : byte; connection_count : byte; connection_list : byte; end; reply_buffer : record buffer_length : integer; connection_count : byte; result_list : byte; end; begin With Regs do begin Ah := $e1; Ds := Seg(request_buffer); Si := Ofs(request_buffer); Es := Seg(reply_buffer); Di := Ofs(reply_buffer); end; With request_buffer do begin buffer_length := 3; subfunction := $06; connection_count := $01; connection_list := _connection; end; With reply_buffer do begin buffer_length := 2; connection_count := 0; result_list := 0; end; MSDOS(Regs); retcode := reply_buffer.result_list; end; procedure close_message_pipe(var _connection, retcode : integer); var regs : registers; request_buffer : record buffer_length : integer; subfunction : byte; connection_count : byte; connection_list : byte; end; reply_buffer : record buffer_length : integer; connection_count : byte; result_list : byte; end; begin With Regs do begin Ah := $e1; Ds := Seg(request_buffer); Si := Ofs(request_buffer); Es := Seg(reply_buffer); Di := Ofs(reply_buffer); end; With request_buffer do begin buffer_length := 3; subfunction := $07; connection_count := $01; connection_list := _connection; end; With reply_buffer do begin buffer_length := 2; connection_count := 0; result_list := 0; end; MSDOS(Regs); retcode := reply_buffer.result_list; end; procedure check_message_pipe(var _connection, retcode : integer); var regs : registers; request_buffer : record buffer_length : integer; subfunction : byte; connection_count : byte; connection_list : byte; end; reply_buffer : record buffer_length : integer; connection_count : byte; result_list : byte; end; begin With Regs do begin Ah := $e1; Ds := Seg(request_buffer); Si := Ofs(request_buffer); Es := Seg(reply_buffer); Di := Ofs(reply_buffer); end; With request_buffer do begin buffer_length := 3; subfunction := $08; connection_count := $01; connection_list := _connection; end; With reply_buffer do begin buffer_length := 2; connection_count := 0; result_list := 0; end; MSDOS(Regs); retcode := reply_buffer.result_list; end; procedure send_personal_message(var _connection : integer; var _message : string; var retcode : integer); var regs : registers; count : integer; request_buffer : record buffer_length : integer; subfunction : byte; connection_count : byte; connection_list : byte; message_length : byte; message : array [1..126] of byte; end; reply_buffer : record buffer_length : integer; connection_count : byte; result_list : byte; end; begin With Regs do begin Ah := $e1; Ds := Seg(request_buffer); Si := Ofs(request_buffer); Es := Seg(reply_buffer); Di := Ofs(reply_buffer); end; With request_buffer do begin subfunction := $04; connection_count := $01; connection_list := _connection; message_length := length(_message); buffer_length := length(_message) + 4; for count := 1 to 126 do message[count] := $00; if message_length > 0 then for count := 1 to message_length do message[count] := ord(_message[count]); end; With reply_buffer do begin buffer_length := 2; connection_count := 0; result_list := 0; end; MSDOS(Regs); retcode := reply_buffer.result_list; end; procedure get_personal_message(var _connection : integer; var _message : string; var retcode : integer); var regs : registers; count : integer; request_buffer : record buffer_length : integer; subfunction : byte; end; reply_buffer : record buffer_length : integer; source_connection : byte; message_length : byte; message_buffer : array [1..126] of byte; end; begin With Regs do begin Ah := $e1; Ds := Seg(request_buffer); Si := Ofs(request_buffer); Es := Seg(reply_buffer); Di := Ofs(reply_buffer); end; With request_buffer do begin buffer_length := 1; subfunction := $05; end; With reply_buffer do begin buffer_length := 128; source_connection := 0; message_length := 0; for count := 1 to 126 do message_buffer[count] := $0; end; MSDOS(Regs); _connection := reply_buffer.source_connection; _message := ''; retcode := reply_buffer.message_length; if retcode > 0 then for count := 1 to retcode do _message := _message + chr(reply_buffer.message_buffer[count]); end; procedure log_file(lock_directive:integer; log_filename: string; log_timeout:integer; var retcode:integer); var regs : registers; begin With Regs do begin Ah := $eb; Ds := Seg(log_filename); Dx := Ofs(log_filename); BP := log_timeout; end; msdos(regs); retcode := regs.al; end; procedure release_file(log_filename: string; var retcode:integer); var regs : registers; begin With Regs do begin Ah := $ec; Ds := Seg(log_filename); Dx := Ofs(log_filename); end; msdos(regs); retcode := regs.al; end; procedure clear_file(log_filename: string; var retcode:integer); var regs : registers; begin With Regs do begin Ah := $ed; Ds := Seg(log_filename); Dx := Ofs(log_filename); end; msdos(regs); retcode := regs.al; end; procedure clear_file_set; var regs : registers; begin regs.Ah := $cf; msdos(regs); retcode := regs.al; end; procedure lock_file_set(lock_timeout:integer; var retcode:integer); var regs : registers; begin regs.ah := $CB; regs.bp := lock_timeout; msdos(regs); retcode := regs.al; end; procedure release_file_set; var regs : registers; begin regs.ah := $CD; msdos(regs); end; procedure open_semaphore( _name:string; _initial_value:shortint; var _open_count:integer; var _handle:longint; var retcode:integer); var regs : registers; s_name : array [1..129] of byte; count : integer; semaphore_handle : array [1..2] of word; begin if (_initial_value < 0) or (_initial_value > 127) then _initial_value := 0; for count := 1 to 129 do s_name[count] := $00; {zero buffer} if length(_name) > 127 then _name := copy(_name,1,127); {limit name length} if length(_name) > 0 then for count := 1 to length(_name) do s_name[count+1] := ord(_name[count]); s_name[1] := length(_name); regs.ah := $C5; regs.al := $00; move(_initial_value, regs.cl, 1); regs.ds := seg(s_name); regs.dx := ofs(s_name); msdos(regs); retcode := regs.al; _open_count := regs.bl; semaphore_handle[1]:=regs.cx; semaphore_handle[2]:=regs.dx; move(semaphore_handle,_handle,4); end; procedure close_semaphore(var _handle:longint; var retcode:integer); var regs : registers; semaphore_handle : array [1..2] of word; begin move(_handle,semaphore_handle,4); regs.ah := $C5; regs.al := $04; regs.cx := semaphore_handle[1]; regs.dx := semaphore_handle[2]; msdos(regs); retcode := regs.al; { 00h=successful FFh=Invalid handle} end; procedure examine_semaphore(var _handle:longint; var _value:shortint; var _count, retcode:integer); var regs : registers; semaphore_handle : array [1..2] of word; begin move(_handle,semaphore_handle,4); regs.ah := $C5; regs.al := $01; regs.cx := semaphore_handle[1]; regs.dx := semaphore_handle[2]; msdos(regs); retcode := regs.al; {00h=successful FFh=invalid handle} move(regs.cx, _value, 1); _count := regs.dl; end; procedure signal_semaphore(var _handle:longint; var retcode:integer); var regs : registers; semaphore_handle : array [1..2] of word; begin move(_handle,semaphore_handle,4); regs.ah := $C5; regs.al := $03; regs.cx := semaphore_handle[1]; regs.dx := semaphore_handle[2]; msdos(regs); retcode := regs.al; {00h=successful 01h=overflow value > 127 FFh=invalid handle} end; procedure wait_on_semaphore(var _handle:longint; _timeout:integer; var retcode:integer); var regs : registers; semaphore_handle : array [1..2] of word; begin move(_handle,semaphore_handle,4); regs.ah := $C5; regs.al := $02; regs.bp := _timeout; {units in 1/18 of second, 0 = no wait} regs.cx := semaphore_handle[1]; regs.dx := semaphore_handle[2]; msdos(regs); retcode := regs.al; {00h=successful FEh=timeout failure FFh=invalid handle} end; procedure clear_connection(connection_number : integer; var retcode : integer); var con_num : byte; regs : registers; request_buffer : record length : integer; subfunction : byte; con_num : byte; end; reply_buffer : record length : integer; end; begin with request_buffer do begin length := 4; con_num := connection_number; subfunction := $D2; end; reply_buffer.length := 0; with regs do begin Ah := $e3; Ds := Seg(request_buffer); Si := Ofs(request_buffer); Es := Seg(reply_buffer); Di := Ofs(reply_buffer); end; msdos(regs); retcode := regs.al; end; end. { end of unit novell }
unit PDBCustomStaffEdit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Mask, ToolEdit, PDateEdit,dbctrls,db,PNumEdit; type TPDBCustomStaffEdit = class(TEdit) private FBErn : string; FCustomStaffDataLink : TFieldDataLink; protected { Protected declarations } function GetDataField : string; function GetDataSource : TDataSource; function GetErn: string; function GetField : TField; function GetWholeErn: string; procedure ActiveChange(Sender : TObject); procedure CMExit(var Message : TCMExit); message CM_EXIT; procedure change; override; procedure DataChange(Sender : TObject); procedure SetDataField(Value : string); procedure SetDataSource(Value : TDataSource); procedure SetErn(Value : string); procedure SetWholeErn(Value : string); procedure UpdateData(Sender : TObject); public { Public declarations } Constructor Create(AOwner: TComponent) ; override; Destructor Destroy; override; property Field: TField read GetField; property WholeErn : string read GetWholeErn write SetWholeErn; published { Published declarations } property AutoSelect; property AutoSize; property BorderStyle; property CharCase; property Color; property Ctl3D; property DataField: string read GetDataField write SetDataField; property DataSource: TDataSource read GetDataSource write SetDataSource; property DragCursor; property DragMode; property Enabled; property Ern: string read GetErn write setErn; property Font; property HideSelection; property ImeMode; property ImeName; property MaxLength; property OEMConvert; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PasswordChar; property PopupMenu; property ReadOnly; property ShowHint; property TabOrder; property TabStop; property Text; property Visible; property OnChange; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; end; procedure Register; implementation constructor TPDBCustomStaffEdit.Create(AOwner : TComponent); begin inherited Create(AOwner); FCustomStaffDataLink := TFieldDataLink.Create ; FCustomStaffDataLink.Control := Self; FCustomStaffDataLink.OnDataChange := DataChange; FCustomStaffDataLink.OnUpDateData := UpdateData; FCustomStaffDataLink.OnActiveChange := ActiveChange; Font.Size := 9; Font.Name := 'ËÎÌå'; Enabled := False; end; destructor TPDBCustomStaffEdit.Destroy; begin FCustomStaffDataLink.Free; FCustomStaffDataLink := nil; inherited Destroy; end; procedure TPDBCustomStaffEdit.SetDataSource(Value : TDataSource); begin FCustomStaffDataLink.DataSource := Value; Enabled := FCustomStaffDataLink.Active and (FCustomStaffDataLink.Field <> nil) and (not FCustomStaffDataLink.Field.ReadOnly); Enabled := Enabled; end; procedure TPDBCustomStaffEdit.SetDataField(Value : string); begin try FCustomStaffDataLink.FieldName := Value; finally Enabled := FCustomStaffDataLink.Active and (FCustomStaffDataLink.Field <> nil) and (not FCustomStaffDataLink.Field.ReadOnly); Enabled := Enabled; end; end; procedure TPDBCustomStaffEdit.ActiveChange (Sender : TObject); begin Enabled := FCustomStaffDataLink.Active and (FCustomStaffDataLink.Field <> nil) and (not FCustomStaffDataLink.Field.ReadOnly); Enabled := Enabled; end; procedure TPDBCustomStaffEdit.UpdateData (Sender : TObject); begin if (FCustomStaffDataLink.Field <> nil)then begin FCustomStaffDataLink.Field.AsString := WholeErn; end; end; function TPDBCustomStaffEdit.GetErn : string; begin Result := Text; end; procedure TPDBCustomStaffEdit.SetErn(Value : string); begin if Text <> Value then Text := Value; end; function TPDBCustomStaffEdit.GetWholeErn: string; begin Result := FBErn + Text; end; procedure TPDBCustomStaffEdit.SetWholeErn(Value : string); begin FCustomStaffDataLink.Edit; FBErn := Value[1]+ Value[2]; text := pchar(pointer(integer(pointer(Value))+2)); FCustomStaffDataLink.Modified; end; procedure TPDBCustomStaffEdit.DataChange(sender : TObject); var temp : string; begin if (FCustomStaffDataLink.Field <> nil) then //and (FCustomStaffDataLink.Field is TDateField) then begin temp := FCustomStaffDataLink.Field.AsString; if temp <> '' then WholeErn := temp else begin FBErn := ''; text := ''; end end else begin FBErn := ''; text := ''; end; end; function TPDBCustomStaffEdit.GetDataField : string; begin Result := FCustomStaffDataLink.FieldName; end; function TPDBCustomStaffEdit.GetDataSource : TDataSource; begin Result := FCustomStaffDataLink.DataSource; end; function TPDBCustomStaffEdit.GetField : TField; begin Result := FCustomStaffDataLink.Field; end; procedure TPDBCustomStaffEdit.change; begin FCustomStaffDataLink.Modified; inherited change; end; procedure TPDBCustomStaffEdit.CMExit(var Message : TCMExit); begin {inherited; try FCustomStaffDataLink.UpdateRecord ; except SetFocus; raise; end;} try FCustomStaffDataLink.UpdateRecord; except SelectAll; SetFocus; raise; end; //SetFocused(False); //CheckCursor; DoExit; end; procedure Register; begin RegisterComponents('PosControl2', [TPDBCustomStaffEdit]); end; end.
unit ContactManager.Interfaces; interface uses Contact, DSharp.Aspects.Logging, DSharp.ComponentModel.Composition, DSharp.Core.Lazy, Spring.Collections; type [InheritedExport] [Logging] IContactDetailsViewModel = interface(IInvokable) ['{04FC1B4C-5B2A-4C41-BB84-39E69816F7D6}'] function GetContact: TContact; procedure SetContact(const Value: TContact); property Contact: TContact read GetContact write SetContact; end; [InheritedExport] [Logging] IContactsOverviewViewModel = interface(IInvokable) ['{15AC3244-E2BB-42BE-AB15-61C2DF87FEB8}'] function GetCanDeleteContact: Boolean; function GetCanEditContact: Boolean; function GetSelectedContact: TContact; procedure SetSelectedContact(const Value: TContact); procedure AddNewContact; procedure EditContact; procedure DeleteContact; property CanDeleteContact: Boolean read GetCanDeleteContact; property CanEditContact: Boolean read GetCanEditContact; property SelectedContact: TContact read GetSelectedContact write SetSelectedContact; end; implementation end.
{ mteFiles Tests Tests for functions in mteFiles } unit mteFilesTests; uses 'lib\mteBase', 'lib\mteFiles', 'lib\jvTest'; const mteTestVersion = '0.0.0.1'; mteTestFile1 = 'TestMTE-1.esp'; mteTestFile2 = 'TestMTE-2.esp'; mteTestFile3 = 'TestMTE-3.esp'; mteTestFile4 = 'TestMTE-4.esp'; expectedLoadOrder = 'Skyrim.esm'#44'TestMTE-1.esp'#44'TestMTE-2.esp'#44 'TestMTE-3.esp'#44'TestMTE-4.esp'; { mteVersionTest: Raises an exception if you're the testing suite is not built to target the version of mteFunctions the user is running. } procedure mteVersionTest; begin if mteVersion <> mteTestVersion then raise Exception.Create('mteFilesTests - These tests are meant to be '+ 'run on mteFunctions v'+mteTestVersion+', you are running '+ mteVersion+'. Testing terminated.'); end; procedure VerifyEnvironment; var i: Integer; f: IInterface; sl: TStringList; begin sl := TStringList.Create; try for i := 0 to FileCount -2 do begin f := FileByLoadOrder(i); sl.Add(GetFileName(f)); end; if sl.CommaText <> expectedLoadOrder then raise Exception.Create('To run these tests, your load order must be: '+expectedLoadOrder); finally sl.Free; end; end; { RemoveMasters: Helper method that removes the Master Files element from a file. } procedure RemoveMasters(filename: string); var fileHeader, f, masters: IInterface; begin f := FileByName(filename); fileHeader := GetFileHeader(f); masters := ElementByPath(fileHeader, 'Master Files'); if Assigned(masters) then Remove(masters); end; { TestMteFiles: Tests the functions in mteFiles using the jvTest framework. } procedure TestMteFiles; var bCaughtException: boolean; xEditVersion: string; fileHeader, f, rec: IInterface; iRestore, iActual: Integer; sRestore, sActual: string; lst: TList; sl, sl2: TStringList; begin (*** GetFileHeader Tests ***) Describe('GetFileHeader'); try // Test with file not assigned Describe('File not assigned'); try bCaughtException := false; try f := nil; GetFileHeader(f); except on x: Exception do begin bCaughtException := true; ExpectEqual(x.Message, 'GetFileHeader: Input file is not assigned', 'Should raise the correct exception'); end; end; Expect(bCaughtException, 'Should have raised an exception'); Pass; except on x: Exception do Fail(x); end; // Test with an element that isn't a file Describe('Element is not a file'); try bCaughtException := false; try f := FileByIndex(0); rec := RecordByIndex(f, 0); GetFileHeader(rec); except on x: Exception do begin bCaughtException := true; ExpectEqual(x.Message, 'GetFileHeader: Input element is not a file', 'Should raise the correct exception'); end; end; Expect(bCaughtException, 'Should have raised an exception'); Pass; except on x: Exception do Fail(x); end; // Test with a valid input file Describe('Valid input file'); try f := FileByIndex(0); Expect(Equals(GetFileHeader(f), ElementByIndex(f, 0)), 'Should return the file header'); Pass; except on x: Exception do Fail(x); end; // all tests passed? Pass; except on x: Exception do Fail(x); end; (*** GetNextObjectID Tests ***) Describe('GetNextObjectID'); try // Test with valid input file f := FileByIndex(0); fileHeader := ElementByIndex(f, 0); iActual := GetElementNativeValues(fileHeader, 'HEDR\Next Object ID'); ExpectEqual(GetNextObjectID(f), iActual, 'Should return the Next Object ID'); Pass; except on x: Exception do Fail(x); end; (*** SetNextObjectID Tests ***) Describe('SetNextObjectID'); iRestore := -1; try // Test with valid input file f := FileByName(mteTestFile1); fileHeader := ElementByIndex(f, 0); // store value so it can be resotred iRestore := GetElementNativeValues(fileHeader, 'HEDR\Next Object ID'); SetNextObjectID(f, 9999); iActual := GetElementNativeValues(fileHeader, 'HEDR\Next Object ID'); ExpectEqual(iActual, 9999, 'Should set the value of the Next Object ID element'); // restore value SetElementNativeValues(fileHeader, 'HEDR\Next Object ID', iRestore); Pass; except on x: Exception do begin // restore value if changed if Assigned(fileHeader) and (iRestore > -1) then SetElementNativeValues(fileHeader, 'HEDR\Next Object ID', iRestore); Fail(x); end; end; (*** GetAuthor Tests ***) Describe('GetAuthor'); try // Test with valid input file f := FileByIndex(0); fileHeader := ElementByIndex(f, 0); sActual := GetElementEditValues(fileHeader, 'CNAM - Author'); ExpectEqual(GetAuthor(f), sActual, 'Should return the author'); Pass; except on x: Exception do Fail(x); end; (*** SetAuthor Tests ***) Describe('SetAuthor'); sRestore := '-1'; try // Test with valid input file f := FileByName(mteTestFile1); fileHeader := ElementByIndex(f, 0); // store value so it can be resotred sRestore := GetElementEditValues(fileHeader, 'CNAM - Author'); SetAuthor(f, 'Testing123'); sActual := GetElementEditValues(fileHeader, 'CNAM - Author'); ExpectEqual(sActual, 'Testing123', 'Should set the value of the author element'); // restore value SetElementEditValues(fileHeader, 'CNAM - Author', sRestore); Pass; except on x: Exception do begin // restore value if changed if Assigned(fileHeader) and (sRestore <> '-1') then SetElementEditValues(fileHeader, 'CNAM - Author', sRestore); Fail(x); end; end; (*** GetDescription Tests ***) Describe('GetDescription'); try // Test with valid input file f := FileByIndex(0); fileHeader := ElementByIndex(f, 0); sActual := GetElementEditValues(fileHeader, 'SNAM - Description'); ExpectEqual(GetDescription(f), sActual, 'Should return the description'); Pass; except on x: Exception do Fail(x); end; (*** SetDescription Tests ***) Describe('SetDescription'); try // Test with valid input file f := FileByName(mteTestFile1); fileHeader := ElementByIndex(f, 0); // test description doesn't exist SetDescription(f, 'Testing123'); sActual := GetElementEditValues(fileHeader, 'SNAM - Description'); ExpectEqual(sActual, 'Testing123', 'Should create the description element with the correct value if it doesn''t exist'); // test description exists SetDescription(f, 'abcTesting'); sActual := GetElementEditValues(fileHeader, 'SNAM - Description'); ExpectEqual(sActual, 'abcTesting', 'Should set the value of the description element'); // tear down Remove(ElementByPath(fileHeader, 'SNAM - Description')); Pass; except on x: Exception do begin if Assigned(fileHeader) then Remove(ElementByPath(fileHeader, 'SNAM - Description')); Fail(x); end; end; (*** OverrideRecordCount Tests ***) Describe('OverrideRecordCount'); try // Test with file not assigned Describe('File not assigned'); try bCaughtException := false; try f := nil; OverrideRecordCount(f); except on x: Exception do begin bCaughtException := true; ExpectEqual(x.Message, 'OverrideRecordCount: Input file not assigned', 'Should raise the correct exception'); end; end; Expect(bCaughtException, 'Should have raised an exception'); Pass; except on x: Exception do Fail(x); end; // Test with valid input file Describe('Valid input file'); try f := FileByName(mteTestFile1); ExpectEqual(OverrideRecordCount(f), 6, 'Should return 6 for TestFileMTE.esp'); Pass; except on x: Exception do Fail(x); end; // all tests passed? Pass; except on x: Exception do Fail(x); end; (*** GetOverrideRecords Tests ***) Describe('GetOverrideRecords'); try // Test with file not assigned Describe('File not assigned'); try bCaughtException := false; try f := nil; GetOverrideRecords(f, lst); except on x: Exception do begin bCaughtException := true; ExpectEqual(x.Message, 'GetOverrideRecords: Input file not assigned', 'Should raise the correct exception'); end; end; Expect(bCaughtException, 'Should have raised an exception'); Pass; except on x: Exception do Fail(x); end; // Test with input list not assigned Describe('Input list not assigned'); try bCaughtException := false; lst := nil; try f := FileByName(mteTestFile1); GetOverrideRecords(f, lst); except on x: Exception do begin bCaughtException := true; ExpectEqual(x.Message, 'GetOverrideRecords: Input TList not assigned', 'Should raise the correct exception'); end; end; Expect(bCaughtException, 'Should have raised an exception'); Pass; except on x: Exception do Fail(x); end; // Test with valid inputs Describe('Valid inputs'); lst := TList.Create; try f := FileByName(mteTestFile1); GetOverrideRecords(f, lst); ExpectEqual(lst.Count, 6, 'Should have found 6 override records in TestFileMTE.esp'); rec := ObjectToElement(lst[0]); ExpectEqual(Name(rec), 'FirebrandWine "Firebrand Wine" [ALCH:0001895F]' , 'Should have found Firebrand Wine as first override'); Pass; except on x: Exception do Fail(x); end; lst.Free; // all tests passed? Pass; except on x: Exception do Fail(x); end; (*** AddFileToList Test ***) Describe('AddFileToList'); try // Test with file not assigned Describe('Input file not assigned'); try bCaughtException := false; try f := nil; AddFileToList(f, sl); except on x: Exception do begin bCaughtException := true; ExpectEqual(x.Message, 'AddFileToList: Input file is not assigned', 'Should raise the correct exception'); end; end; Expect(bCaughtException, 'Should have raised an exception'); Pass; except on x: Exception do Fail(x); end; // Test with stringlist not assigned Describe('Input stringlist not assigned'); try bCaughtException := false; sl := nil; try f := FileByIndex(0); AddFileToList(f, sl); except on x: Exception do begin bCaughtException := true; ExpectEqual(x.Message, 'AddFileToList: Input TStringList is not assigned', 'Should raise the correct exception'); end; end; Expect(bCaughtException, 'Should have raised an exception'); Pass; except on x: Exception do Fail(x); end; // Test with valid inputs Describe('Valid inputs'); sl := TStringList.Create; try f := FileByIndex(0); AddFileToList(f, sl); ExpectEqual(sl.Count, 1, 'Files list should have 1 item'); ExpectEqual(sl[0], GetFileName(f), 'First item should be Skyrim.esm'); ExpectEqual(Integer(sl.Objects[0]), 0, 'First item should have a load order of 0'); Pass; except on x: Exception do Fail(x); end; sl.Free; // Test with file added twice Describe('File added twice'); sl := TStringList.Create; try f := FileByIndex(0); AddFileToList(f, sl); AddFileToList(f, sl); ExpectEqual(sl.Count, 1, 'Files list should have 1 item'); ExpectEqual(sl[0], GetFileName(f), 'First item should be Skyrim.esm'); ExpectEqual(Integer(sl.Objects[0]), 0, 'First item should have a load order of 0'); Pass; except on x: Exception do Fail(x); end; sl.Free; // Test file with lower load order than existing item added Describe('File with lower load order added'); sl := TStringList.Create; try f := FileByName(mteTestFile1); AddFileToList(f, sl); f := FileByIndex(0); AddFileToList(f, sl); ExpectEqual(sl.Count, 2, 'Files list should have 2 items'); ExpectEqual(sl[0], GetFileName(f), 'First item should be Skyrim.esm'); ExpectEqual(sl[1], mteTestFile1, 'Second item should be '+mteTestFile1); ExpectEqual(Integer(sl.Objects[0]), 0, 'First item should have a load order of 0'); ExpectEqual(Integer(sl.Objects[1]), 1, 'Second item should have a load order of 1'); Pass; except on x: Exception do Fail(x); end; sl.Free; // Test file with higher load order than existing item added Describe('File with higher load order added'); sl := TStringList.Create; try f := FileByIndex(0); AddFileToList(f, sl); f := FileByName(mteTestFile1); AddFileToList(f, sl); f := FileByIndex(0); ExpectEqual(sl.Count, 2, 'Files list should have 2 items'); ExpectEqual(sl[0], GetFileName(f), 'First item should be Skyrim.esm'); ExpectEqual(sl[1], mteTestFile1, 'Second item should be '+mteTestFile1); ExpectEqual(Integer(sl.Objects[0]), 0, 'First item should have a load order of 0'); ExpectEqual(Integer(sl.Objects[1]), 1, 'Second item should have a load order of 1'); Pass; except on x: Exception do Fail(x); end; sl.Free; // Test three files Describe('Adding three files'); sl := TStringList.Create; try f := FileByName(mteTestFile1); AddFileToList(f, sl); f := FileByIndex(0); AddFileToList(f, sl); f := FileByName(mteTestFile2); AddFileToList(f, sl); f := FileByIndex(0); ExpectEqual(sl.Count, 3, 'Files list should have 2 items'); ExpectEqual(sl[0], GetFileName(f), 'First item should be Skyrim.esm'); ExpectEqual(sl[1], mteTestFile1, 'Second item should be '+mteTestFile1); ExpectEqual(sl[2], mteTestFile2, 'Third item should be '+mteTestFile2); ExpectEqual(Integer(sl.Objects[0]), 0, 'First item should have a load order of 0'); ExpectEqual(Integer(sl.Objects[1]), 1, 'Second item should have a load order of 1'); ExpectEqual(Integer(sl.Objects[2]), 2, 'Third item should have a load order of 2'); Pass; except on x: Exception do Fail(x); end; sl.Free; // all tests passed? Pass; except on x: Exception do Fail(x); end; (*** AddMastersToList Test ***) Describe('AddMastersToList'); try // Test with stringlist not assigned Describe('Input stringlist not assigned'); try bCaughtException := false; sl := nil; try f := FileByIndex(0); AddMastersToList(f, sl, true); except on x: Exception do begin bCaughtException := true; ExpectEqual(x.Message, 'AddMastersToList: Input TStringList not assigned', 'Should raise the correct exception'); end; end; Expect(bCaughtException, 'Should have raised an exception'); Pass; except on x: Exception do Fail(x); end; // Test with file that has no masters Describe('File has no masters'); sl := TStringList.Create; try f := nil; f := FileByIndex(0); AddMastersToList(f, sl, true); ExpectEqual(sl.Count, 0, 'Masters list should have 0 items'); Pass; except on x: Exception do Fail(x); end; sl.Free; // Test with file that has one master Describe('File has one master'); sl := TStringList.Create; try f := FileByName(mteTestFile1); AddMastersToList(f, sl, true); ExpectEqual(sl.Count, 1, 'Masters list should have 1 item'); ExpectEqual(sl[0], 'Skyrim.esm', 'First item should be Skyrim.esm'); Pass; except on x: Exception do Fail(x); end; sl.Free; // Test with file that has two masters Describe('File has two masters'); sl := TStringList.Create; try f := FileByName(mteTestFile2); AddMastersToList(f, sl, true); ExpectEqual(sl.Count, 2, 'Masters list should have 2 items'); ExpectEqual(sl[0], 'Skyrim.esm', 'First item should be Skyrim.esm'); ExpectEqual(sl[1], mteTestFile1, 'Second item should be '+mteTestFile1); Pass; except on x: Exception do Fail(x); end; sl.Free; // Test with masters from two files Describe('Masters from two files'); sl := TStringList.Create; try f := FileByName(mteTestFile1); AddMastersToList(f, sl, true); f := FileByName(mteTestFile2); AddMastersToList(f, sl, true); ExpectEqual(sl.Count, 2, 'Masters list should have 2 items'); ExpectEqual(sl[0], 'Skyrim.esm', 'First item should be Skyrim.esm'); ExpectEqual(sl[1], mteTestFile1, 'Second item should be '+mteTestFile1); Pass; except on x: Exception do Fail(x); end; sl.Free; // Test sorted = false Describe('Sorted = false'); sl := TStringList.Create; try f := FileByName(mteTestFile4); AddFileToList(f, sl); f := FileByName(mteTestFile2); AddMastersToList(f, sl, false); ExpectEqual(sl.Count, 3, 'Masters list should have 3 items'); ExpectEqual(sl[0], mteTestFile4, 'First item should be '+mteTestFile4); ExpectEqual(sl[1], 'Skyrim.esm', 'Second item should be Skyrim.esm'); ExpectEqual(sl[2], mteTestFile1, 'Third item should be '+mteTestFile1); Pass; except on x: Exception do Fail(x); end; sl.Free; // all tests passed? Pass; except on x: Exception do Fail(x); end; (*** AddMaster ***) Describe('AddMaster'); try // Test Master Files element doesn''t exist Describe('Master Files element doesn''t exist'); sl := TStringList.Create; try f := FileByName(mteTestFile4); AddMaster(f, FileByName(mteTestFile2)); AddMastersToList(f, sl, true); ExpectEqual(sl.Count, 1, 'Masters list should have 1 item'); ExpectEqual(sl[0], mteTestFile2, 'First item should be '+mteTestFile2); Pass; except on x: Exception do Fail(x); end; sl.Free; // Test with file that doesn't have the master Describe('File doesn''t have the master'); sl := TStringList.Create; try f := FileByName(mteTestFile4); AddMaster(f, FileByName(mteTestFile3)); AddMastersToList(f, sl, true); ExpectEqual(sl.Count, 2, 'Masters list should have 2 items'); ExpectEqual(sl[0], mteTestFile2, 'First item should be '+mteTestFile2); ExpectEqual(sl[1], mteTestFile3, 'Second item should be '+mteTestFile3); Pass; except on x: Exception do Fail(x); end; sl.Free; // Test with file that already has the master Describe('File already has the master'); sl := TStringList.Create; try f := FileByName(mteTestFile4); AddMaster(f, FileByName(mteTestFile3)); AddMastersToList(f, sl, true); ExpectEqual(sl.Count, 2, 'Masters list should have 3 items'); ExpectEqual(sl[0], mteTestFile2, 'First item should be '+mteTestFile2); ExpectEqual(sl[1], mteTestFile3, 'Second item should be '+mteTestFile3); Pass; except on x: Exception do Fail(x); end; sl.Free; // Test with file that has a master at a higher load order Describe('File has a master at a higher load order'); sl := TStringList.Create; try f := FileByName(mteTestFile4); AddMaster(f, FileByIndex(0)); AddMastersToList(f, sl, true); ExpectEqual(sl.Count, 3, 'Masters list should have 4 items'); ExpectEqual(sl[0], 'Skyrim.esm', 'First item should be Skyrim.esm'); ExpectEqual(sl[1], mteTestFile2, 'Second item should be '+mteTestFile2); ExpectEqual(sl[2], mteTestFile3, 'Third item should be '+mteTestFile3); Pass; except on x: Exception do Fail(x); end; sl.Free; // clean up RemoveMasters(mteTestFile4); // all tests passed Pass; except on x: Exception do Fail(x); end; (*** AddMastersToFile Test ***) Describe('AddMastersToFile'); try // Test with input file not assigned Describe('Input file not assigned'); try bCaughtException := false; try f := nil; AddMastersToFile(f, sl); except on x: Exception do begin bCaughtException := true; ExpectEqual(x.Message, 'AddMastersToFile: Input file not assigned', 'Should raise the correct exception'); end; end; Expect(bCaughtException, 'Should have raised an exception'); Pass; except on x: Exception do Fail(x); end; // Test with stringlist not assigned Describe('Input stringlist not assigned'); try bCaughtException := false; sl := nil; try f := FileByIndex(0); AddMastersToFile(f, sl); except on x: Exception do begin bCaughtException := true; ExpectEqual(x.Message, 'AddMastersToFile: Input TStringList not assigned', 'Should raise the correct exception'); end; end; Expect(bCaughtException, 'Should have raised an exception'); Pass; except on x: Exception do Fail(x); end; // Test with file that already had the masters Describe('File already has masters'); sl := TStringList.Create; sl2 := TStringList.Create; try f := FileByName(mteTestFile2); AddMastersToList(f, sl, true); AddMastersToFile(f, sl); AddMastersToList(f, sl2, true); ExpectEqual(sl.CommaText, sl2.CommaText, 'Masters should not be changed'); Pass; except on x: Exception do Fail(x); end; sl.Free; sl2.Free; // Test with file that has no masters Describe('File has no masters'); sl := TStringList.Create; sl2 := TStringList.Create; try f := FileByName(mteTestFile2); AddMastersToList(f, sl, true); f := FileByName(mteTestFile3); AddMastersToFile(f, sl); AddMastersToList(f, sl2, true); ExpectEqual(sl.CommaText, sl2.CommaText, 'Masters should be added correctly'); Pass; except on x: Exception do Fail(x); end; sl.Free; sl2.Free; // Test with file that has had masters added in same session Describe('File has had masters added in same session'); sl := TStringList.Create; sl2 := TStringList.Create; try f := FileByName(mteTestFile2); AddMastersToList(f, sl, true); f := FileByName(mteTestFile3); AddMastersToFile(f, sl); AddMastersToList(f, sl2, true); ExpectEqual(sl.CommaText, sl2.CommaText, 'Masters should be the same'); Pass; except on x: Exception do Fail(x); end; sl.Free; sl2.Free; // Test with file that has had masters manually removed Describe('File has had masters manually removed'); sl := TStringList.Create; sl2 := TStringList.Create; f := nil; try f := FileByName(mteTestFile2); AddMastersToList(f, sl, true); f := FileByName(mteTestFile3); fileHeader := GetFileHeader(f); Remove(ElementByPath(fileHeader, 'Master Files')); f := FileByName(mteTestFile3); AddMastersToFile(f, sl); f := FileByName(mteTestFile3); AddMastersToList(f, sl2, true); ExpectEqual(sl.CommaText, sl2.CommaText, 'Masters should be added correctly'); Pass; except on x: Exception do Fail(x); end; sl.Free; sl2.Free; // Test with file that has had masters manually removed and re-added in the same session Describe('File has had masters manually removed and re-added'); sl := TStringList.Create; sl2 := TStringList.Create; f := nil; try f := FileByName(mteTestFile2); AddMastersToList(f, sl, true); f := FileByName(mteTestFile3); fileHeader := GetFileHeader(f); AddMastersToFile(f, sl); AddMastersToList(f, sl2, true); ExpectEqual(sl.CommaText, sl2.CommaText, 'Masters should be the same'); Pass; except on x: Exception do Fail(x); end; sl.Free; sl2.Free; // Test adding masters out of order Describe('Adding masters out of order'); sl := TStringList.Create; sl2 := TStringList.Create; f := nil; try // construct initial list of masters // * Skyrim.esm // * TestMTE-1.esp // * TestMTE-3.esp f := FileByIndex(0); AddFileToList(f, sl); f := FileByName(mteTestFile1); AddFileToList(f, sl); f := FileByName(mteTestFile3); AddFileToList(f, sl); f := FileByName(mteTestFile4); // add initial masters to file AddMastersToFile(f, sl); // add TestMTE-2.esp to masters list f := FileByName(mteTestFile2); AddFileToList(f, sl); ExpectEqual(sl.CommaText, 'Skyrim.esm'#44'TestMTE-1.esp'#44'TestMTE-2.esp'#44 'TestMTE-3.esp', 'Should have the masters in the list in the correct order'); // add masters to TestMTE-4.esp f := FileByName(mteTestFile4); AddMastersToFile(f, sl); // get actual order of masters on TestMTE-4.esp AddMastersToList(f, sl2, false); ExpectEqual(sl.CommaText, sl2.CommaText, 'Masters on the file should be ordered correctly'); Pass; except on x: Exception do Fail(x); end; sl.Free; sl2.Free; // clean up RemoveMasters(mteTestFile3); RemoveMasters(mteTestFile4); // all tests passed? Pass; except on x: Exception do Fail(x); end; (*** RemoveMaster Test ***) Describe('RemoveMaster'); try // Test Master Files element doesn''t exist Describe('Master Files element doesn''t exist'); try f := FileByName(mteTestFile3); RemoveMaster(f, mteTestFile2); Expect(true, 'Should not throw an exception'); Pass; except on x: Exception do Fail(x); end; // Test master not present Describe('Master not present'); sl := TStringList.Create; sl2 := TStringList.Create; try f := FileByName(mteTestFile2); AddMastersToList(f, sl, true); RemoveMaster(f, mteTestFile2); AddMastersToList(f, sl2, true); ExpectEqual(sl.CommaText, sl2.CommaText, 'Should not change the file''s masters'); Pass; except on x: Exception do Fail(x); end; sl.Free; sl2.Free; // Test master present Describe('Master present'); sl := TStringList.Create; sl2 := TStringList.Create; try f := FileByName(mteTestFile2); AddMastersToList(f, sl, true); RemoveMaster(f, mteTestFile1); AddMastersToList(f, sl2, true); AddMaster(f, FileByName(mteTestFile1)); ExpectEqual(sl2.Count, 1, 'Should only have one master now'); ExpectEqual(sl2[0], 'Skyrim.esm', 'First master should be Skyrim.esm'); Pass; except on x: Exception do Fail(x); end; sl.Free; sl2.Free; // all tests passed? Pass; except on x: Exception do Fail(x); end; (*** RemoveMaster Test ***) Describe('AddLoadedFilesAsMasters'); try // Test with input file not assigned Describe('Input file not assigned'); try bCaughtException := false; try f := nil; AddLoadedFilesAsMasters(f); except on x: Exception do begin bCaughtException := true; ExpectEqual(x.Message, 'AddLoadedFilesAsMasters: Input file not assigned', 'Should raise the correct exception'); end; end; Expect(bCaughtException, 'Should have raised an exception'); Pass; except on x: Exception do Fail(x); end; // all tests passed? Pass; except on x: Exception do Fail(x); end; end; {******************************************************************************} { ENTRY POINTS Entry points for when the script is run in xEdit. - Initialize } {******************************************************************************} function Initialize: Integer; begin // don't perform tests if mteVersionTest fails mteVersionTest; VerifyEnvironment; jvtInitialize; // perform tests TestMteFiles; // finalize jvt jvtPrintReport; jvtFinalize; end; end.
unit UStrings; { ClickForms Application } { Bradford Technologies, Inc. } { All Rights Reserved } { Source Code Copyrighted © 1998-2011 by Bradford Technologies, Inc. } {$WARN SYMBOL_PLATFORM OFF} {$WARN UNIT_PLATFORM OFF} interface uses SysConst; resourcestring cADOProvider = 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source='; SupportedImageFormats = '*.jpg;*.jpeg;*.bmp;*.wmf;*.emf;*.png;*.gif;*.tif;*.tiff;*.tga;*.pcx;*.eps;*.pcd;*.dxf'; {For ImageLib} ImageLibFilter1 = 'All Supported Media Formats|*.BMP;*.CMS;*.GIF;*.JPG;*.JPEG;*.PCX;*.PNG;*.SCM;*.TIF;*.TIFF;*.PCD;*.EMF;*.WMF;*.TGA;*.WAV;*.MID;*.RMI;*.AVI;*.MOV;|Windows Bitmap (BMP)|*.BMP|Credit Message (CMS)|*.CMS|Compuserve Gif (GIF)|*.GIF'; ImageLibFilter2 = '|Jpeg (JPG,JPEG)|*.JPG;*.JPEG|PaintShop Pro (PCX)|*.PCX|Portable Graphics (PNG)|*.PNG|Scrolling Message (SCM)|*.SCM|Tagged Image (TIF,TIFF)|*.TIF|Kodak Photo CD (PCD)|*.PCD|Windows Metafile (WMF)|*.WMF|Enhanced Metafile (EMF) |*.EMF'; ImageLibFilter3 = '|Targe Image (TGA)|*.TGA|Wave Sound (WAV)|*.WAV|Midi Sound (MID)|*.MID|RMI Sound (RMI)|*.RMI|Video for Windows (AVI)|*.AVI|Apple Quicktime Video (MOV)|*.MOV'; errUnknownExt = 'The file extension was not recognized. Try adding a "clk" or "cft" extension to the file.'; errUnknownFileType = ' is an unknown file type and cannot be opened.'; errCannotOpenFile = 'Could not open the file '; errCannotCreateFile = 'Could not create the ClickFORMS file.'; errCannotCreateTemplate = 'Could not create the ClickFORMS Template file.'; errErrorOnWrite = 'An error occured while saving the report. This may be due to large images that have not been optimized. Please delete some images then go into the Image Editor to optimize all images.'; {errCannotSave = 'Could not save the contents of the report.';} errCannotSaveList = 'Could not save the list.'; errNotValidFile = 'This is not a valid file. Please select another one.'; errNotValidDB = 'This is not a valid database type.'; errCannotConnect2DB = 'Could not connect to the database.'; errDBExists = 'The requested Database currently exists. Please select another one.'; errCannotCreateDBDir = 'Could not create the Database directory.'; errCannotExport = 'Could not export the contents of the report.'; errCannotReadSpec = 'There was a problem reading the Report Specification.'; errCannotRead = 'There was a problem reading the file '; errNoPageResource = 'Can not find resource to convert page '; errOwnerFileDamaged = 'The Owner License file appears to be damaged.'; errCannotWriteLicense = 'The License file could not be written.'; errCannotReadLicense = 'The License file could not be read.'; errCannotPaste = 'There was not enough memory to perform the Paste operation.'; errCannotCopy = 'There was not enough memory to perform the Copy operation.'; errChkBoxGrpOR = 'The checkbox grouping is out of range.'; errDblClkLibFolder = 'This is not a ClickFORMS file. Make sure you double click on the file and not the folder.'; errFileNotVerified = 'Could not open this file. It is either the wrong type or it has been created by a newer version of ClickFORMS'; errPrinterProblem = 'There is a problem with the print driver. Please ensure your printer has been setup and configured correctly.'; errCompsConnection = 'There was a problem connecting to the Comps Database. Make sure it is located in the Databases folder.'; errOnCensusTract = 'A problem was encountered while accessing the Census Tract website.'; errOnFidelityData = 'A problem was encountered while working with the Fidelity Data Service.'; errOnFloodData = 'A problem was encountered while accessing the flood zoning data web service.'; errOnFloodMap = 'A problem was encountered while accessing the flood map data web service.'; errOnLocationMap = 'A problem was encountered while accessing the location map data web service.'; errOnBuildFax = 'A problem was encountered while accessing the BuildFax Permit History web service.'; errOnRelsMLSImport = 'A problem was encountered while accessing the RELS MLS Import service.'; errOnCostAnalysis = 'A problem was encountered while accessing the Cost Analysis data web service.'; errOnAWResults = 'A problem was encountered retrieving results from the AppraisalWorld web service.'; errOnAWResponse = 'A problem was encountered retrieving the response from the AppraisalWorld web service.'; errOnAreaSketch = 'A problem was encountered while accessing the AreaSketch web service.'; //Tool Error Msgs errCannotRunTool = 'Could not run %s'; errSketcherOpen = 'The Sketcher is already running.'; errSketcherExecute = 'There was an error starting the Sketcher.'; errTrackerFindCol = 'The specified column could not be found in the database.'; msgTrackerFind = 'Please input a search string.'; msgTrackerFindFail = 'Search string not found.'; msgNoUserName = 'You need to specify a contact name for the user. This is used for the name of the User''s license file.'; msgConnected2DBOK = 'Connected to the database successfully.'; msgSaveAsTemplate = 'Save As Template'; msgSaveConvertedAs = 'Save Converted File As:'; msgNeedsConverting = ' needs to be converted. Please specify where the new converted file is to be saved.'; msgNoRspForCell = 'No Responses for this cell'; msgBeOnline = 'This Help function requires you to be online. Do you want to continue?'; msgEnterValidName = 'You must enter a valid name to evaluate the software.'; msgThx4Evaluating = 'Thank you for evaluating our software. We hope you enjoy using it.'; msgThx4EvalPostName = ' for evaluating our software. We hope you enjoy using it.'; msgThxStudentLater = ' for using ClickFORMS. Be sure to register to gain access to free Property Location Maps.'; msgThxStudentRegister = ' for registering ClickFORMS For Students. You now have access to online Property Location Maps. We hope you enjoy using the software in your appraisal class.'; msgThxStudentExpired = 'Thank you for using ClickFORMS. This version has expired. If you would like to purchase the professional version, please call 800-622-8727 and ask for the Student Upgrade Package.'; msgStudentTampered = 'This student version of CickFORMS cannot be used any more.'; msgWant2SaveRegInfo = 'Do you want to save the changes to the Registration Information?'; msgWant2SaveRegInfoB = 'Do you want to save the changes to the Registration Information for %s?'; msgWrongUnlock = 'The Unlocking Number you entered does not correspond to the registration number. Please reenter it.'; msgInvalidOwner = 'The Software License Owner has not been validated for this version of the software. Please re-register.'; msgInvalidUser = 'The Software User has not been validated for this version of the software. Please re-register.'; msgNeedLicUserName = 'You must first enter a User Name before attempting to unlock the software.'; msgNeedUnlockNo = 'You must enter an Unlocking Number before attempting to unlock the software.'; msgNeedSerialNo = 'You must enter the Software Serial Number before attempting to unlock the software.'; msgInvalidSerialNo = 'The Software Serial Number is invalid. Please re-enter it.'; msgPopOrBroadcast = 'You just added a form with data! Do you want to EXPORT the common data from this form into the report or IMPORT the common data from the report into this form?'; msgNoEditRsps = 'The responses for this cell cannot be changed.'; msgAffixSignature = 'Affix Signature'; msgClearSignature = 'Clear Signature'; msgSaveFormats = 'The formatting on one or more forms has changed. Do you want to make this the default formatting when using these forms in the future?'; msgUpdateReportDB = 'An older version of the Reports database has been encountered. Do you want to update it?'; msgUpdateCompDB = 'An older version of the Comparables database has been encountered. Do you want to update it?'; msgUpdateClientDB = 'An older version of the Clients database has been encountered. Do you want to update it?'; msgShouldUpgradeCF = 'A new version of ClickFORMS is available. You should use this new version to produce reports. ' + 'Please download the latest update, or contact Bradford Technical Support for assistance.'; msgMustUpgradeCF = 'A new version of ClickFORMS is available. You must use this new version to produce reports. ' + 'Please download the latest update, or contact Bradford Technical Support for assistance.'; msgCantUseFlood = 'You are not a registered ClickFORMS user, so access to Flood Insights has been denied. If you would like to register ClickFORMS or subscribe to the Flood Insights service please call Bradford Technologies'' sales department at 1-800-622-8727.'; msgBadFloodMapAddr = 'The address is incomplete or one of the items does not conform to standards. Please check the address and make the required changes.'; msgAcceptOrder = 'You must accept or decline the apraisal order before closing the window. Please click on the Accept - Decline button located on the Order form.'; msgOrderNotAccepted = 'The appraisal order has not been accepted or declined. Are you sure you want to close the window? You can click on the Accept - Decline button located on the Order form to accept the order.'; msgRELSMessage = 'Click OK to obtain the results. Please correct the issues noted and validate again. You must pass validation prior to successful delivery.'; msgClickFORMSInitialWelcome = 'Welcome to ClickFORMS'; msgClickFORMSInitialMeno = 'If you have purchased a software license, please click Register to record this copy of ClickFORMS. If you want to evaluate ClickFORMS and experience the simplicity of sophisticated software please click the Evaluate button. Thank you.'; msgClickFORMSThankYou = 'Thank you for using ClickFORMS.'; msgClickFORMSThx4Evaluating = 'Thank you for evaluating ClickFORMS. We hope you are enjoying the software. To purchase a license, please login into AppraisalWorld.com or contact your account representative at 800-622-8727. Thanks for your interest in ClickFORMS.'; msgSoftwareInEvalMode = 'ClickFORMS is in evaluation mode. It is FULLY FUNCTIONAL. To continue using it after the evaluation period, please login into AppraisalWorld.com or contact your account representative at 800-622-8727 to purchase a subscription. Thank you.'; msgClickFORMSEvalExpiredTitle = 'ClickFORMS evaluation period has expired.'; msgClickFORMSEvalExpired = 'We hope you enjoyed using ClickFORMS. To continue using it, please login into AppraisalWorld.com or contact your account representative at 800-622-8727 to purchase a subscription.'; msgClickFORMSSubcripExpired = 'Please login into AppraisalWorld.com or contact your account representative at 800-622-8727 to renew your subscription.'; msgClickFORMSGeneralExpired = 'Please login into AppraisalWorld.com or contact your account representative at 800-622-8727 to purchase a ClickFORMS license. Thank you for your interest in using ClickFORMS.'; msgServiceGeneralMessage = 'Please login into AppraisalWorld.com or contact your account representative at 800-622-8727 to purchase.'; msgClickFORMSCanntValidate = 'Please connect to the Internet, then click the REGISTER button below to attempt to validate your Subscription.'; msgClickFORMSChkSubscription = 'ClickFORMS cannot connect to the server to check your subscription status. Please make sure you are connected to internet and your firewall is not blocking ClickFORMS.'; msgClickFORMSSubscription0Day = 'Your ClickFORMS subscription must be validated today. Please connect to the Internet and restart ClickFORMS so it can validate your subscription.'; msgClickFORMSSubscription1Day = 'Your ClickFORMS subscription must be validated by tomorrow. Please connect to the Internet and restart ClickFORMS so it can validate your subscription.'; msgClickFORMSSubscription3Day = 'Your ClickFORMS subscription must be validated within the next 3 days. Make sure you are connected to the Internet next time you start ClickFORMS.'; msgClickFORMSSubscription5Day = 'Your ClickFORMS subscription must be validated within the next 5 days. Make sure you are connected to the Internet next time you start ClickFORMS.'; msgClickFORMSSubscription10Day = 'Your ClickFORMS subscription must be validated within the next 10 days. Make sure you are connected to the Internet next time you start ClickFORMS.'; msgClickFORMSSubscription14Day = 'Your ClickFORMS subscription must be validated within the next two weeks. Make sure you are connected to the Internet next time you start ClickFORMS.'; msgFindNotFound = 'The search string %s was not found.'; msgReplNotFound = 'The search string %s was not found or could not be replaced.'; msgFindReplFinishied = 'ClickForms has finished searching the document.'; msgReplAllOccur = '%d occurence(s) have been replaced.'; msgSuggestionSent = 'Your suggestion has been sent directly to the ClickFORMS developers. Thanks for helping us improve ClickFORMS'; msgTechSupport = 'Thank you for your request. An email has been sent to our technical support department.You should receive an answer within 24 hours.'; msgToolBoxFileNotSupported = 'This Appraisers ToolBox file is not supported in ClickFORMS.'; //recogniziable extensions //.uad and uat are used for TBX USPAP2002 - a mistake //When adding file types, inc consts in UFileGlobals extClickForms = '.clk.cft'; extOldClkForms = '.uad.udt.u2d.u2t.bfd.bft.brd.brt.cmd.cmt.chd.cht.ccd.cct.c2d.c2t.cpd.cpt.cqd.cqt.crd.crt.dsd.tst.rad.rat.dpd.tpt' + '.dvd.tvt.egd.egt.uhd.uht.bkd.bkt.erd.ert.rod.rot.ucd.uct.spd.spt.mhd.mht' + //uad.uat. '.e5d.e5t.e6d.e6t.e7d.e7t.ead.eat.cod.cot.emd.emt.e2d.e2t.red.ret.41d.41t.42d.42t.fid.fit.fcd.fct.fld.flt.s5d.s5t' + '.f2d.f2t.ied.iet.1fd.1ft.2fd.2ft.3fd.3ft.5fd.5ft.9fd.9ft.0fd.0ft.11d.11t.12d.12t.14d.14t.15d.15t.16d.16t.l3d.l3t' + '.grd.grt.frd.frt.nhd.nht.hid.hit.hod.hot.idd.itt.ird.irt.iod.iot.kad.kat.lnd.lnt.lvd.lvt.mbd.mbt.nad.nat.ntd.ntt' + '.nkd.nkt.nwd.nwt.nyd.nyt.oid.oit.okd.okt.eqd.eqt.lod.lot.5ad.5at.5bd.5bt.4rd.4rt.7ad.7at.7bd.7bt.rrd.rrt' + '.cvd.cvt.rxd.rxt.ard.art.rsd.rst.rmd.rmt.rvd.rvt.rpd.rpt.rcd.rct.rtd.rtt.rfd.rft.rud.rut.s5d.s5t.s6d.s6t.s7d.s7t' + '.s9d.s9t.ssd.sst.sad.sat.rid.rit.s2d.s2t.sfd.sft.sud.sut.tbd.tbt.ucd.uct.spd.spt.upd.upt.usp.uspt'; //if attemp to read these files, a notice is given that they are nolonger supported extOldClkFormsExtinct = '.usd.ust.sld.slt.skd.skt'; // software update msgMaintenanceExpired = 'Your Software maintenance plan has expired.' + sLineBreak + 'Please call Bradford Technologies at (800) 622-8727 to renew your maintenance plan and ' + 'receive the latest software updates.'; //Mercury message Mercury_WarnTriesMsg ='Your Mercury Network Connection trial allows you to transfer "%d" Mercury Orders into ClickFORMS. If you are at the Gold Membership level, '+ 'call your sales representative or visit the AppraisalWorld store to purchase after the trial.'; Mercury_WarnPurchaseMsg ='The Mercury Network Connection is not part of your current ClickFORMS Membership. '+ 'Please call your sales representative at 800-622-8727 or visit the AppraisalWorld store.'; Mercury_WarnCallSalesMsg = 'The Mercury Network Connection is not part of your current ClickFORMS Membership. '+ 'Please call your sales representative at 800-622-8727 to upgrade.'; //Trial message Trial_WarnTriesMsg = 'You have %d Flood Maps to use with your trial. If you want to continue using this service, '+ 'call your sales representative or visit the AppraisalWorld store to purchase after the trial.'; Trial_WarnPurchaseMsg = 'You have used the maximum number of Flood Maps with your trial. '+ 'Please call your sales representative or visit the AppraisalWorld store to purchase'; // carry-over comments msgCommentsReferenceText = 'See comments - %s'; msgLinkWordProcessorPages = 'Would you like to link this Comments Page with the Comment Page above it? Linking allows text to flow between Comment Pages while typing.'; msgAppendWithoutSignatures = 'Appraiser signatures were not appended to this report. You will will need to sign this report again.'; // location maps msgSelectForm = 'A Location Map page already exists in the report. Do you want to place (INSERT) this map on that page, or do you want to ADD an additional map addendum with this map on it?'; msgMapConfirmReplace = 'Do you want to replace the selected map with the new map, or add an additional map addendum?'; msgMapPortalError = 'The map editor reported the following error:' + sLineBreak + '%s'; // pictometry msgPictometryConfirmReplace = 'Do you want to replace the existing Pictometry images with the new images, or add the images to a new addendum?'; // UAD Uniform Appraisal Dataset msgUADDisableFeatures = 'UAD Compliance OFF'; msgUADEnableFeatures = 'UAD Compliance ON'; msgUADDatabaseError = 'UAD Compliance features are unavailable because there is a problem reading the UAD database.'; msgUADEditComments = 'The comment text on this page can only be edited by the cells that originated them.'; msgUAGClearDialog = 'All data in this dialog will be cleared. Do you want to continue?'; msgUADUserNotLicensed = ' is not licensed for UAD Compliance Services. These services need to be purchased.'; msgUADValidStreet = 'A street number and name must be entered.'; msgUADValidUnitNo = 'A unit number must be entered.'; msgUADValidCity = 'A city must be entered.'; msgValidState = 'A valid state abbreviation must be selected.'; msgValidZipCode = 'A valid five digit zip code must be entered.'; msgValidZipPlus = 'The zip plus four code must be blank or four non-zero digits.'; msgOK2ApplyUAD = 'This is a Non-UAD Compliant report. Do you want to apply the UAD Compliant rules.'; msgUADNotLicensed = 'You are not licensed for the UAD Compliance Service. It will be turned off for this report.'; UADCountTypeList = '0|1|2|3|4|5|6|7|8|9|'; UADSalesTypeList = 'REO sale|Short sale|Court Ordered sale|Estate sale|Relocation sale|Non-Arms Length sale|Arms Length sale|'; UADInfluenceList = 'Neutral|Beneficial|Adverse|'; // 091211 JWyatt View factors realinged to match the dialog. // UADViewFactorList = 'Pastoral View|Woods View|Water View|Park View|Golf Course View|City View Skyline View|Mountain View|Residential View|City Street View|Industrial View|Power Lines|Limited Sight|Other|'; UADViewFactorList = 'Residential View|Water View|Golf Course View|Park View|Pastoral View|Woods View|City View Skyline View|Mountain View|City Street View|Industrial View|Power Lines|Limited Sight|Other|'; UADLocFactorList = 'Residential|Industrial|Commercial|Busy Road|Water Front|Golf Course|Adjacent to Park|Adjacent to Powerlines|Landfill|Public Transportation|Other|'; UADImproveTypList = 'Not Updated|Updated|Remodeled|'; UADWhenTypList = 'Less then 1 yr ago|1 - 5 yrs ago|6 - 10 yrs ago|11 - 15 yrs ago|Unknown|'; UADConditionList = 'C1|C2|C3|C4|C5|C6|'; UADQualityList = 'Q1|Q2|Q3|Q4|Q5|Q6|'; UADStoryTypList = '1.00|1.50|2.00|2.50|3.00|'; UADListDateTypList = 'Price Change|Contract|Current|Expired|Settled|Withdrawn|'; UADUnkFinAssistance = 'There is a financial assistance amount that is unknown.'; UADFinanceTypList = 'None|FHA|VA|Convential|Cash|Seller|Rural housing|Other|'; UADUnknownAbbr = 'Unk|'; errOnUSPostal = 'A problem was enocuntered while accessing the US Postal Service website.'; msgInterNetNotConnected = 'There was a problem connecting to AppraisalWorld. ' + 'Please make sure you are connected to Internet and your firewall is not ' + 'blocking ClickFORMS from accessing the internet.'; msgNotAWMember = 'You''re not an AppraisalWorld member yet. Please visit the AppraisalWorld home page to register.'; //**** Service warning message //warning message for Time based service expired ServiceWarning_TimebasedWhenExpired = 'The service you requested has expired. '+ 'Please visit the AppraisalWorld store to renew this service.'; ServiceWarning_NotAvailable ='This service is not part of your Membership. '+ 'Please visit the AppraisalWorld store or call your sales representative to purchase.'; //warning message for Unit based service expired ServiceWarning_NoUnitsOrExipred = 'The service you requested has expired or you do not have enough credits. '+ 'Please visit the AppraisalWorld store to renew or purchase additional credits.'; //github #518: ServiceWarning_UnitBasedWhenExipred = 'There are 0 units left in the service you requested. Please visit the AppraisalWorld store to purchase additional units.'; //warning message for unit based service when units is down to a certain limits. ServiceWarning_UnitBasedB4Expired = 'The %s service will expire in %d days or you are down to %d %s left. '+ 'Please visit the AppraisalWorld store to purchase more credits.'; //warning message for Time based service Before expiration ServiceWarning_TimeBasedB4Expired = 'Your %s will expire in %d days. '+ 'Please visit the AppraisalWorld store to renew this service.'; //warning message for Time based service Before expiration ServiceWarning_TimeBasedhasExpired = 'Your %s are down to %d %s left. '+ 'Please visit the AppraisalWorld store to renew this service.'; // msgMobileInspectionMemberShipWarning = 'Thank you for interesting in Inspect-a-Lot. Your current AppraisalWorld membership level does not quality for upload privileges. '+ // 'Please contact your account representative at 800-622-8727 to upgrade your membership.'; msgMobileInspectionMemberShipWarning = 'Your current AppraisalWorld membership level does not allow you upload privileges. '+ 'Please contact your account representative at 800-622-8727 to upgrade your membership.'; msgServiceNotAvaible = 'The service that you requested is not available.'; implementation end.
unit CashOperationTest; interface uses dbTest, dbMovementTest, DB, ObjectTest; type TCashOperationTest = class (TdbMovementTestNew) published procedure ProcedureLoad; override; procedure Test; override; end; TCashOperation = class(TMovementTest) private function InsertDefault: integer; override; protected procedure SetDataSetParam; override; public function InsertUpdateCashOperation(const Id: integer; InvNumber: String; OperDate: TDateTime; Amount: Double; Comment: string; CashId, ObjectId, ContractId, InfoMoneyId, UnitId: integer): integer; constructor Create; override; function GetRecord(Id: integer): TDataSet; override; end; implementation uses UtilConst, JuridicalTest, dbObjectTest, SysUtils, TestFramework, DBClient, dsdDB, CashTest, dbObjectMeatTest, InfoMoneyTest; { TIncomeCashJuridical } constructor TCashOperation.Create; begin inherited; spInsertUpdate := 'gpInsertUpdate_Movement_Cash'; spSelect := 'gpSelect_Movement_Cash'; spGet := 'gpGet_Movement_Cash'; spCompleteProcedure := 'gpComplete_Movement_Cash'; end; function TCashOperation.GetRecord(Id: integer): TDataSet; begin with FdsdStoredProc do begin DataSets.Add.DataSet := TClientDataSet.Create(nil); StoredProcName := spGet; OutputType := otDataSet; Params.Clear; Params.AddParam('ioId', ftInteger, ptInputOutput, Id); Params.AddParam('inOperDate', ftDateTime, ptInput, Date); Execute; result := DataSets[0].DataSet; end; end; function TCashOperation.InsertDefault: integer; var Id: Integer; InvNumber: String; OperDate: TDateTime; Amount: Double; CashId, ObjectId, PaidKindId, InfoMoneyId, ContractId, UnitId, PositionId: Integer; AccrualsDate: TDateTime; begin Id:=0; InvNumber:='1'; OperDate:= Date; // Выбираем кассу CashId := TCash.Create.GetDefault; // Выбираем Юр лицо ObjectId := TJuridical.Create.GetDefault; PaidKindId := 0; ContractId := 0; InfoMoneyId := 0; with TInfoMoney.Create.GetDataSet do begin if Locate('Code', '10103', []) then InfoMoneyId := FieldByName('Id').AsInteger; end; UnitId := 0; Amount := 265.68; // PositionId := 0; AccrualsDate := Date; result := InsertUpdateCashOperation(Id, InvNumber, OperDate, Amount, 'Это комментарий', CashId, ObjectId, ContractId, InfoMoneyId, UnitId); ; end; function TCashOperation.InsertUpdateCashOperation(const Id: integer; InvNumber: String; OperDate: TDateTime; Amount: Double; Comment: string; CashId, ObjectId, ContractId, InfoMoneyId, UnitId: 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('inAmountIn', ftFloat, ptInput, Amount); FParams.AddParam('inAmountOut', ftFloat, ptInput, 0); FParams.AddParam('inComment', ftString, ptInput, Comment); FParams.AddParam('inCashId', ftInteger, ptInput, CashId); FParams.AddParam('inObjectId', ftInteger, ptInput, ObjectId); FParams.AddParam('inContractId', ftInteger, ptInput, ContractId); FParams.AddParam('inInfoMoneyId', ftInteger, ptInput, InfoMoneyId); FParams.AddParam('inUnitId', ftInteger, ptInput, UnitId); result := InsertUpdate(FParams); end; procedure TCashOperation.SetDataSetParam; begin inherited; FParams.AddParam('inCashId', ftInteger, ptInput, 0); end; { TIncomeCashJuridicalTest } procedure TCashOperationTest.ProcedureLoad; begin ScriptDirectory := ProcedurePath + 'Movement\Cash\'; inherited; ScriptDirectory := ProcedurePath + 'MovementItemContainer\Cash\'; inherited; end; procedure TCashOperationTest.Test; var MovementCashOperation: TCashOperation; Id, RecordCount: Integer; StoredProc: TdsdStoredProc; AccountAmount, AccountAmountTwo: double; begin inherited; AccountAmount := 0; AccountAmountTwo := 0; // Создаем объект документ MovementCashOperation := TCashOperation.Create; RecordCount := MovementCashOperation.GetDataSet.RecordCount; // Проверяем остаток по счету кассы StoredProc := TdsdStoredProc.Create(nil); StoredProc.Params.AddParam('inStartDate', ftDateTime, ptInput, Date); StoredProc.Params.AddParam('inEndDate', ftDateTime, ptInput, TDateTime(Date)); StoredProc.StoredProcName := 'gpReport_Balance'; StoredProc.DataSet := TClientDataSet.Create(nil); StoredProc.OutputType := otDataSet; StoredProc.Execute; with StoredProc.DataSet do begin if Locate('AccountCode', '40201', []) then AccountAmount := FieldByName('AmountDebetEnd').AsFloat + FieldByName('AmountKreditEnd').AsFloat end; // создание документа и проведение Id := MovementCashOperation.InsertDefault; MovementCashOperation.GetRecord(Id); try StoredProc.Execute; with StoredProc.DataSet do begin if Locate('AccountCode', '40201', []) then AccountAmountTwo := FieldByName('AmountDebetEnd').AsFloat - FieldByName('AmountKreditEnd').AsFloat; end; Check(abs(AccountAmount - (AccountAmountTwo - 265.68)) < 0.01, 'Провелось не правильно. Было ' + FloatToStr(AccountAmount) + ' стало ' + FloatToStr(AccountAmountTwo)); finally // распроведение MovementCashOperation.DocumentUnComplete(Id); StoredProc.Free; end; end; initialization TestFramework.RegisterTest('Документы', TCashOperationTest.Suite); end.
{$ifdef license} (* Copyright 2020 ChapmanWorld LLC ( https://chapmanworld.com ) Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *) {$endif} unit cwCollections.Stack.Standard; {$ifdef fpc} {$mode delphiunicode} {$endif} interface uses cwCollections ; type TStandardStack<T> = class( TInterfacedObject, IReadOnlyStack<T>, IStack<T> ) private fItems: array of T; fCount: nativeuint; fCapacity: nativeuint; fGranularity: nativeuint; fPruned: boolean; private //- IReadOnlyStack -// function Pull: T; function getAsReadOnly: IReadOnlyStack<T>; private //- IStack<T> -// procedure Push( const Item: T ); public constructor Create( const Granularity: nativeuint = 0; const IsPruned: boolean = false ); reintroduce; destructor Destroy; override; end; implementation constructor TStandardStack<T>.Create( const Granularity: nativeuint; const IsPruned: boolean ); const cDefaultGranularity = 32; begin inherited Create; //- Determine memory usage granularity. if Granularity>0 then begin fGranularity := Granularity; end else begin fGranularity := cDefaultGranularity; //-default granularity end; fPruned := IsPruned; fCapacity := 0; fCount := 0; SetLength( fItems, fCapacity ); end; destructor TStandardStack<T>.Destroy; begin SetLength( fItems, 0 ); inherited; end; function TStandardStack<T>.Pull: T; begin Result := Default(T); if fCount>0 then begin Result := fItems[pred(fCount)]; fItems[pred(fCount)] := Default(T); dec(fCount); if fPruned then begin if fCount<(fCapacity-fGranularity) then begin fCapacity := fCapacity - fGranularity; SetLength( fItems, fCapacity ); end; end; end; end; procedure TStandardStack<T>.Push( const Item: T ); begin //- Test that there is sufficient memory to add the item. if (fCount=fCapacity) then begin fCapacity := fCapacity + fGranularity; SetLength( fItems, fCapacity ); end; //- Add the item fItems[fCount] := Item; inc(fCount); end; function TStandardStack<T>.getAsReadOnly: IReadOnlyStack<T>; begin Result := Self as IReadOnlyStack<T>; end; end.
unit FormCalculadora; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Buttons, Vcl.StdCtrls; type TCalculadora = class(TForm) Sete: TSpeedButton; Oito: TSpeedButton; Nove: TSpeedButton; Multiplicar: TSpeedButton; Quatro: TSpeedButton; Cinco: TSpeedButton; Seis: TSpeedButton; Menos: TSpeedButton; Um: TSpeedButton; Dois: TSpeedButton; Tres: TSpeedButton; Igual: TSpeedButton; Ponto: TSpeedButton; Zero: TSpeedButton; Mais: TSpeedButton; Limpar: TSpeedButton; Percent: TSpeedButton; Dividir: TSpeedButton; edtVisor: TEdit; procedure UmClick(Sender: TObject); procedure DoisClick(Sender: TObject); procedure TresClick(Sender: TObject); procedure QuatroClick(Sender: TObject); procedure CincoClick(Sender: TObject); procedure SeisClick(Sender: TObject); procedure SeteClick(Sender: TObject); procedure OitoClick(Sender: TObject); procedure NoveClick(Sender: TObject); procedure MaisClick(Sender: TObject); procedure MenosClick(Sender: TObject); procedure DividirClick(Sender: TObject); procedure MultiplicarClick(Sender: TObject); procedure PontoClick(Sender: TObject); procedure LimparClick(Sender: TObject); procedure IgualClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure ZeroClick(Sender: TObject); private { Private declarations } public end; var Calculadora: TCalculadora; valor1: real; valor2: real; funcao: integer; implementation {$R *.dfm} procedure TCalculadora.CincoClick(Sender: TObject); begin edtVisor.Text := edtVisor.Text + (Sender as TSpeedButton).Caption end; procedure TCalculadora.DoisClick(Sender: TObject); begin edtVisor.Text := edtVisor.Text + (Sender as TSpeedButton).Caption end; procedure TCalculadora.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_NUMPAD1 then Um.Click; if Key = VK_NUMPAD2 then Dois.Click; if Key = VK_NUMPAD3 then Tres.Click; if Key = VK_NUMPAD4 then Quatro.Click; if Key = VK_NUMPAD5 then Cinco.Click; if Key = VK_NUMPAD6 then Seis.Click; if Key = VK_NUMPAD7 then Sete.Click; if Key = VK_NUMPAD8 then Oito.Click; if Key = VK_NUMPAD9 then Nove.Click; if Key = VK_NUMPAD0 then Zero.Click; if Key = VK_ADD then Mais.Click; if Key = VK_SUBTRACT then Menos.Click; if Key = VK_MULTIPLY then Multiplicar.Click; if Key = VK_DIVIDE then Dividir.Click; if Key = VK_RETURN then Igual.Click; if Key = VK_DECIMAL then Ponto.Click; if Key = VK_DELETE then Limpar.Click; end; procedure TCalculadora.FormShow(Sender: TObject); begin valor1 := 0; valor2 := 0; end; procedure TCalculadora.IgualClick(Sender: TObject); var soma: real; begin valor2 := StrToFloat(edtVisor.Text); case (funcao) of 1: begin soma := valor1 + valor2; edtVisor.Text := floattostr(soma); end; 2: begin soma := valor1 - valor2; edtVisor.Text := floattostr(soma); end; 3: begin soma := valor1 * valor2; edtVisor.Text := floattostr(soma); end; 4: begin if (valor2 <> 0) then begin soma := valor1 / valor2; edtVisor.Text := floattostr(soma); end else begin // SHowMessage('Divisão por zero!!'); edtVisor.Text := 'Divisão por zero!'; end end end; end; procedure TCalculadora.LimparClick(Sender: TObject); begin edtVisor.Text := ''; end; procedure TCalculadora.MaisClick(Sender: TObject); begin valor1 := StrToFloat(edtVisor.Text); edtVisor.Text := ''; funcao := 1; end; procedure TCalculadora.MenosClick(Sender: TObject); begin valor1 := StrToFloat(edtVisor.Text); edtVisor.Text := ''; funcao := 2; end; procedure TCalculadora.MultiplicarClick(Sender: TObject); begin valor1 := StrToFloat(edtVisor.Text); edtVisor.Text := ''; funcao := 3; end; procedure TCalculadora.DividirClick(Sender: TObject); begin valor1 := StrToFloat(edtVisor.Text); edtVisor.Text := ''; funcao := 4; end; procedure TCalculadora.PontoClick(Sender: TObject); begin valor1 := StrToFloat(edtVisor.Text); if pos(',', edtVisor.Text) = 0 then begin edtVisor.Text := edtVisor.Text + ','; end; end; procedure TCalculadora.NoveClick(Sender: TObject); begin edtVisor.Text := edtVisor.Text + (Sender as TSpeedButton).Caption end; procedure TCalculadora.OitoClick(Sender: TObject); begin edtVisor.Text := edtVisor.Text + (Sender as TSpeedButton).Caption end; procedure TCalculadora.QuatroClick(Sender: TObject); begin edtVisor.Text := edtVisor.Text + (Sender as TSpeedButton).Caption end; procedure TCalculadora.SeisClick(Sender: TObject); begin edtVisor.Text := edtVisor.Text + (Sender as TSpeedButton).Caption end; procedure TCalculadora.SeteClick(Sender: TObject); begin edtVisor.Text := edtVisor.Text + (Sender as TSpeedButton).Caption end; procedure TCalculadora.TresClick(Sender: TObject); begin edtVisor.Text := edtVisor.Text + (Sender as TSpeedButton).Caption end; procedure TCalculadora.UmClick(Sender: TObject); begin edtVisor.Text := edtVisor.Text + (Sender as TSpeedButton).Caption end; procedure TCalculadora.ZeroClick(Sender: TObject); begin edtVisor.Text := edtVisor.Text + (Sender as TSpeedButton).Caption end; end.
// see ISC_license.txt {$I genLL.inc} unit SimpleParser; interface uses Runtime, SimpleLexer; type TSimpleParser = class(TParser) public procedure pars_program; procedure pars_variable; procedure pars_method; procedure pars_block; procedure pars_expr; procedure pars_statement; end; implementation procedure TSimpleParser.pars_program; var LA1: integer; begin repeat LA1 := LA(1); if LA1 = LEX_KEY_INT then pars_variable() else if LA1 = LEX_KEY_METHOD then break else begin // also EOF is error ErrorP('error in program'); ConsumeToType(LEX_SEMI); Consume(); // SEMI or EOF end; until false; repeat pars_method(); until LA(1) = LEX_EOF; end; procedure TSimpleParser.pars_variable(); var LA1: integer; begin Match(LEX_KEY_INT); Match(LEX_ID); LA1 := LA(1); if LA1 = LEX_ASSIGN then begin Match(LEX_ASSIGN); pars_expr; end; Match(LEX_SEMI); end; procedure TSimpleParser.pars_method; begin Match(LEX_KEY_METHOD); Match(LEX_ID); Match(LEX_LPAREN); Match(LEX_RPAREN); pars_block(); end; procedure TSimpleParser.pars_block; begin Match(LEX_LCURLY); while LA(1) = LEX_KEY_INT do pars_variable(); repeat pars_statement(); until LA(1) = LEX_RCURLY; Match(LEX_RCURLY); end; procedure TSimpleParser.pars_statement; var LA1: integer; begin LA1 := LA(1); case LA1 of LEX_ID: begin Match(LEX_ID); Match(LEX_ASSIGN); pars_expr; Match(LEX_SEMI); end; LEX_KEY_RETURN: begin Match(LEX_KEY_RETURN); pars_expr; Match(LEX_SEMI); end; LEX_LCURLY: pars_block(); else ErrorP(''); end; end; procedure TSimpleParser.pars_expr; var LA1: integer; begin LA1 := LA(1); case LA1 of LEX_ID: Match(LEX_ID); LEX_INT: Match(LEX_INT); else ErrorP(''); end; end; end.
{----------------------------------------------------------------------------- Unit Name: DUParams Author: Sebastian Hütter Date: 2006-08-01 Purpose: Simple acces to command line parameters in the form paramname=paramvalue History: 2006-08-01 initial release -----------------------------------------------------------------------------} unit DUParams; interface uses SysUtils, Classes, Windows; type TParamList = class(TStringList) protected function Get(Index: Integer): string; override; end; var ParamList:TParamList; ParamAlias:TStringList; procedure RebuildParamList; function GetPrmValue(Index:integer):string; overload; function GetPrmValue(Name:string):string; overload; function ParamExists(Name:string):boolean; function CatParams(First,Last:integer; Quote:boolean=false):string; implementation { TParamList } function TParamList.Get(Index: Integer): string; begin if (Index < 0) or (Index >= Count) then Result:= '' else Result := inherited Get(Index); end; function GetPrmValue(Index:integer):string; begin Result:= ParamList.ValueFromIndex[Index]; end; function GetPrmValue(Name:string):string; begin Result:= ParamList.Values[Name]; end; function ParamExists(Name:string):boolean; begin Result:= (ParamList.IndexOfName(Name)>-1) or (ParamList.IndexOf(Name)>-1); end; function CatParams(First,Last:integer; Quote:boolean=false):string; var i:integer; begin if Quote then begin Result:= '"'+ParamStr(First)+'"'; for i:= First+1 to Last do Result:= Result+' "'+ParamStr(i)+'"'; end else begin Result:= ParamStr(First); for i:= First+1 to Last do Result:= Result+' '+ParamStr(i); end; end; procedure BuildParamList; var i:integer; s,n,v:string; begin for i:= 1 to ParamCount do begin s:= ParamStr(i); n:= copy(s,1,pos('=',s)-1); v:= copy(s,pos('=',s)+1,maxint); if n='' then s:= v else s:= n+'='+v; ParamList.Add(s); end; end; procedure RebuildParamList; begin ParamList.Clear; BuildParamList; end; initialization ParamList:= TParamList.Create; ParamAlias:= TStringList.Create; BuildParamList; finalization ParamList.Free; ParamAlias.Free; end.
Program MeasureText; {$IFNDEF HASAMIGA} {$FATAL This source is compatible with Amiga, AROS and MorphOS only !} {$ENDIF} { Project : MeasureText Source : RKRM } {* ** The following example, measuretext.c, opens a window on the default ** public screen and renders the contents of an ASCII file into the ** window. It uses TextFit() to measure how much of a line of text will ** fit across the window. If the entire line doesn't fit, measuretext ** will wrap the remainder of the line into the rows that follow. This ** example makes use of an ASL font requester, letting the user choose ** the font, style, size, drawing mode, and color. *} {$MODE OBJFPC}{$H+}{$HINTS ON} {$UNITPATH ../../../Base/CHelpers} {$UNITPATH ../../../Base/Trinity} {$IFDEF AMIGA} {$UNITPATH ../../../Sys/Amiga} {$ENDIF} {$IFDEF AROS} {$UNITPATH ../../../Sys/AROS} {$ENDIF} {$IFDEF MORPHOS} {$UNITPATH ../../../Sys/MorphOS} {$ENDIF} Uses Exec, AmigaDOS, AGraphics, Intuition, DiskFont, ASL, Utility, {$IFDEF AMIGA} systemvartags, {$ENDIF} CHelpers, Trinity; const BUFSIZE = 32768; vers : PChar = #0'$VER: MeasureText 37.1'; Var buffer : array[0..Pred(BUFSIZE)] of UBYTE; myfile : BPTR; wtbarheight : UWORD; fr : PFontRequester; myfont : PTextFont; w : PWindow; myrp : PRastPort; mytask : PTask; procedure MainLoop; forward; procedure EOP; forward; procedure Main(argc: integer; argv: PPCHar); var myta : TTextAttr; begin if (argc = 2) then begin if SetAndTest(myfile, DOSOpen(argv[1], MODE_OLDFILE)) then //* Open the file to print out. */ begin {$IF DEFINED(MORPHOS) or DEFINED(AMIGA)} if SetAndTest(DiskfontBase, OpenLibrary('diskfont.library', 37)) then //* Open the libraries. */ {$ENDIF} begin {$IF DEFINED(MORPHOS)} if SetAndTest(IntuitionBase, OpenLibrary('intuition.library', 37)) then {$ENDIF} begin {$IF DEFINED(MORPHOS) or DEFINED(AMIGA)} if SetAndTest(GfxBase, OpenLibrary('graphics.library', 37)) then {$ENDIF} begin {$IF DEFINED(MORPHOS) or DEFINED(AMIGA)} if SetAndTest(AslBase, OpenLibrary('asl.library', 37)) then {$ENDIF} begin if SetAndTest(fr, PFontRequester(AllocAslRequestTags(ASL_FontRequest, //* Open an ASL font requester */ [ //* Supply initial values for requester */ { ASL_FontName , PChar('topaz.font'), ASL_FontHeight , 11, ASL_FontStyles , FSF_BOLD or FSF_ITALIC, ASL_FrontPen , $01, ASL_BackPen , $00, } TAG_(ASLFO_InitialName) , TAG_(PChar('topaz.font')), TAG_(ASLFO_InitialSize) , 11, TAG_(ASLFO_InitialStyle) , FSF_BOLD or FSF_ITALIC, TAG_(ASLFO_InitialFrontPen) , $01, TAG_(ASLFO_InitialBackPen) , $00, //* Give us all the gadgetry */ // ASL_FuncFlags, FONF_FRONTCOLOR or FONF_BACKCOLOR or FONF_DRAWMODE or FONF_STYLES, TAG_(ASLFO_Flags) , FOF_DOFRONTPEN or FOF_DOBACKPEN or FOF_DODRAWMODE or FOF_DOSTYLE, TAG_DONE ]))) then begin //* Pop up the requester */ if (AslRequest(fr, nil)) then begin myta.ta_Name := fr^.fo_Attr.ta_Name; //* extract the font and */ myta.ta_YSize := fr^.fo_Attr.ta_YSize; //* display attributes */ myta.ta_Style := fr^.fo_Attr.ta_Style; //* from the FontRequest */ myta.ta_Flags := fr^.fo_Attr.ta_Flags; //* structure. */ if SetAndTest(myfont, OpenDiskFont(@myta)) then begin if SetAndTEst(w, OpenWindowTags(nil, [ TAG_(WA_SizeGadget) , TAG_(TRUE), TAG_(WA_MinWidth) , 200, TAG_(WA_MinHeight) , 200, TAG_(WA_DragBar) , TAG_(TRUE), TAG_(WA_DepthGadget), TAG_(TRUE), TAG_(WA_Title) , TAG_(argv[1]), TAG_DONE ])) then begin myrp := w^.RPort; //* figure out where the baseline of the uppermost line should be. */ wtbarheight := w^.WScreen^.BarHeight + myfont^.tf_Baseline + 2; //* Set the font and add software styling to the text if I asked for it */ //* in OpenFont() and didn't get it. Because most Amiga fonts do not */ //* have styling built into them (with the exception of the CG outline */ //* fonts), if the user selected some kind of styling for the text, it */ //* will to be added algorithmically by calling SetSoftStyle(). */ SetFont(myrp, myfont); SetSoftStyle(myrp, myta.ta_Style xor myfont^.tf_Style, (FSF_BOLD or FSF_UNDERLINED or FSF_ITALIC)); SetDrMd(myrp, fr^.fo_DrawMode); SetAPen(myrp, fr^.fo_FrontPen); SetBPen(myrp, fr^.fo_BackPen); GfxMove(myrp, w^.WScreen^.WBorLeft, wtbarheight); mytask := FindTask(nil); MainLoop(); DOSDelay(25); //* short delay to give user a chance to */ CloseWindow(w); //* see the text before it goes away. */ end; CloseFont(myfont); end; end else WriteLn('Request Cancelled'); FreeAslRequest(fr); end; {$IF DEFINED(MORPHOS) or DEFINED(AMIGA)} CloseLibrary(AslBase); {$ENDIF} end; {$IF DEFINED(MORPHOS) or DEFINED(AMIGA)} CloseLibrary(GfxBase); {$ENDIF} end; {$IF DEFINED(MORPHOS)} CloseLibrary(IntuitionBase); {$ENDIF} end; {$IF DEFINED(MORPHOS) or DEFINED(AMIGA)} CloseLibrary(DiskfontBase); {$ENDIF} end; DOSClose(myfile); end; end else WriteLn('template: MeasureText <file name>'); end; procedure MainLoop; var resulttextent : TTextExtent; fit, actual, count, printable, crrts: LONG; aok : Boolean = TRUE; begin while (( SetAndGet(actual, DOSRead(myfile, @buffer, BUFSIZE)) > 0) and aok) do //* while there's something to */ begin //* read, fill the buffer. */ count := 0; while (count < actual) do begin crrts := 0; while ( ( (buffer[count] < myfont^.tf_LoChar) or //* skip non-printable characters, but */ (buffer[count] > myfont^.tf_HiChar) ) and //* account for newline characters. */ (count < actual) ) do begin if (buffer[count] = 12) then inc(crrts); //* is this character a newline? if it is, bump */ inc(count); //* up the newline count. */ end; if (crrts > 0) then //* if there where any newlines, be sure to display them. */ begin GfxMove(myrp, w^.BorderLeft, myrp^.cp_y + (crrts * (myfont^.tf_YSize + 1))); EOP; //* did we go past the end of the page? */ end; printable := count; while ( (buffer[printable] >= myfont^.tf_LoChar) and //* find the next non-printables */ (buffer[printable] <= myfont^.tf_HiChar) and (printable < actual) ) do begin inc(printable); end; //* print the string of printable characters wrapping */ while (count < printable) do //* lines to the beginning of the next line as needed. */ begin //* how many characters in the current string of printable characters will fit */ //* between the rastport's current X position and the edge of the window? */ fit := TextFit( myrp, @(buffer[count]), (printable - count), @resulttextent, nil, 1, (w^.Width - (myrp^.cp_x + w^.BorderLeft + w^.BorderRight)), myfont^.tf_YSize + 1 ); if ( fit = 0 ) then begin //* nothing else fits on this line, need to wrap to the next line. */ GfxMove(myrp, w^.BorderLeft, myrp^.cp_y + myfont^.tf_YSize + 1); end else begin GfxText(myrp, @(buffer[count]), fit); count := count + fit; end; EOP; end; if (mytask^.tc_SigRecvd and SIGBREAKF_CTRL_C <> 0) then //* did the user hit CTRL-C (the shell */ begin //* window has to receive the CTRL-C)? */ aok := FALSE; WriteLn('Ctrl-C Break'); count := BUFSIZE + 1; end; end; end; if (actual < 0) then WriteLn('Error while reading'); end; procedure EOP; begin if (myrp^.cp_y > (w^.Height - (w^.BorderBottom + 2))) then //* If we reached page bottom, clear the */ begin //* rastport and move back to the top. */ DOSDelay(25); SetAPen(myrp, 0); RectFill(myrp, LONG(w^.BorderLeft), LONG(w^.BorderTop), w^.Width - (w^.BorderRight + 1), w^.Height - (w^.BorderBottom + 1) ); SetAPen(myrp, 1); GfxMove(myrp, w^.BorderLeft + 1, wtbarheight); SetAPen(myrp, fr^.fo_FrontPen); end; end; begin Main(ArgC, ArgV); end.
unit win_data_math; interface { Returns min./max. value of A, B and C } function Min(const A, B, C: Integer): Integer; overload; {$IFDEF USEINLINING} inline; {$ENDIF} function Max(const A, B, C: Integer): Integer; overload; {$IFDEF USEINLINING} inline; {$ENDIF} implementation function Min(const A, B, C: Integer): Integer; {$IFDEF USENATIVECODE} begin if A < B then Result := A else Result := B; if C < Result then Result := C; {$ELSE} {$IFDEF FPC} assembler; nostackframe; {$ENDIF} asm {$IFDEF TARGET_x64} MOV RAX,RCX MOV RCX,R8 {$ENDIF} CMP EDX,EAX CMOVL EAX,EDX CMP ECX,EAX CMOVL EAX,ECX {$ENDIF} end; function Max(const A, B, C: Integer): Integer; {$IFDEF USENATIVECODE} begin if A > B then Result := A else Result := B; if C > Result then Result := C; {$ELSE} {$IFDEF FPC} assembler; nostackframe; {$ENDIF} asm {$IFDEF TARGET_x64} MOV RAX,RCX MOV RCX,R8 {$ENDIF} CMP EDX,EAX CMOVG EAX,EDX CMP ECX,EAX CMOVG EAX,ECX {$ENDIF} end; end.
program serial_boot; {$mode objfpc}{$H+} {$IFDEF WINDOWS} {$APPTYPE Console} {$ENDIF} uses {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} Classes, SysUtils, CustApp { you can add units after this }, synaser; const DefaultSpeed = 19200; DefaultCOM = 'COM1'; DefaultEeprom = 0; type { TSerialBoot } TSerialBoot = class(TCustomApplication) private FComPort : String; FFileName : TFilename; FSpeed : Cardinal; FVerbose : Boolean; FEeprom : integer; FSerialConnection : TBlockSerial; protected procedure DoRun; override; public constructor Create(TheOwner: TComponent); override; destructor Destroy; override; procedure WriteHelp; virtual; function SetMandatoryParams : Boolean; virtual; procedure SetSeconderyParams; virtual; procedure OpenCom(const ACom : String); virtual; procedure CloseCom; virtual; published property ComPort : String read FComPort write FComPort; property Eeprom : integer read FEeprom write FEeprom; property FileName : TFilename read FFileName write FFileName; property Speed : Cardinal read FSpeed write FSpeed; property Verbose : Boolean read FVerbose write FVerbose; end; { TSerialBoot } procedure TSerialBoot.DoRun; var ErrorMsg : String; begin // quick check parameters ErrorMsg:=CheckOptions('h','help'); if ErrorMsg<>'' then begin ShowException(Exception.Create(ErrorMsg)); Terminate; Exit; end; // parse parameters FComPort := DefaultCOM; FSpeed := DefaultSpeed; FEeprom := DefaultEeprom; SetSeconderyParams; if HasOption('h','help') or (not SetMandatoryParams) then begin WriteHelp; Terminate; Exit; end; { add your program here } // stop program loop Terminate; end; constructor TSerialBoot.Create(TheOwner: TComponent); begin inherited Create(TheOwner); StopOnException:=True; end; destructor TSerialBoot.Destroy; begin inherited Destroy; end; procedure TSerialBoot.WriteHelp; begin { add your help code here } writeln('Usage: ',ExeName,' -h'); end; function TSerialBoot.SetMandatoryParams : Boolean; begin Result := False; if HasOption('f', 'file') then begin FFileName := GetOptionValue('f', 'file'); Result := True; end; end; procedure TSerialBoot.SetSeconderyParams; begin if HasOption('c', 'com') then begin FComPort := GetOptionValue('c', 'com'); end; if HasOption('s', 'speed') then begin try FSpeed := StrToInt(GetOptionValue('s', 'speed')); except on E:Exception do begin writeln(StdErr, 'Invalid Speed value: ', E.Message); Terminate; Exit; end end; end; if HasOption('e', 'eprom') then begin try FEeprom := StrToInt(GetOptionValue('e', 'eprom')); except on E:Exception do begin writeln(StdErr,'Invalid EPROM value : ', E.Message); Terminate; Exit; end; end; end; FVerbose := HasOption('v'); end; procedure TSerialBoot.CloseCom; begin if Assigned(FSerialConnection) then begin FSerialConnection.CloseSocket; FreeAndNil(FSerialConnection); end; end; procedure TSerialBoot.OpenCom ( const ACom : String ) ; begin CloseCom; FSerialConnection := TBlockSerial.Create; FSerialConnection.Connect(ACom); // Connect to the port FSerialConnection.Config(FSpeed, // Speed 8, // Number of bits to use (8 - A full Byte) 'N', // parity (no parity) 1, // Stop bits False, // softflow off (I think) False // hardflow off (I think) ); FSerialConnection.Purge; // Clean buffers end; var Application: TSerialBoot; {$IFDEF WINDOWS}{$R serial_boot.rc}{$ENDIF} begin Application:=TSerialBoot.Create(nil); Application.Title:='Serial Boot'; Application.Run; Application.Free; end.
unit Data.Mock.Book; interface uses System.Classes, System.SysUtils, Data.DB, FireDAC.Comp.Client; function CreateMockTableBook(AOwner: TComponent): TFDMemTable; implementation function CreateMockTableBook(AOwner: TComponent): TFDMemTable; var ds: TFDMemTable; begin ds := TFDMemTable.Create(AOwner); with ds do begin FieldDefs.Add('ISBN', ftWideString, 20); FieldDefs.Add('Title', ftWideString, 100); FieldDefs.Add('Authors', ftWideString, 100); FieldDefs.Add('Status', ftWideString, 15); FieldDefs.Add('ReleseDate', ftDate); FieldDefs.Add('Pages', ftInteger); with FieldDefs.AddFieldDef do begin Name := 'Price'; DataType := ftBCD; Precision := 12; Size := 2; end; FieldDefs.Add('Currency', ftWideString, 10); FieldDefs.Add('Imported', ftDateTime); FieldDefs.Add('Description', ftWideString, 2000); CreateDataSet; end; with ds do begin Append; FieldByName('ISBN').Value := '978-0201633610'; FieldByName('Title').Value := 'Design Patterns: Elements of Reusable Object-Oriented Software'; FieldByName('Authors').Value := 'Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides'; FieldByName('Status').Value := 'on-shelf'; FieldByName('ReleseDate').Value := EncodeDate(1994,11,1); FieldByName('Pages').Value := 395; FieldByName('Price').Value := 54.9; FieldByName('Currency').Value := 'USD'; FieldByName('Imported').Value := EncodeDate(2017,6,30); FieldByName('Description').Value := 'Modern classic in the literature of object-oriented development. Off'+ 'ering timeless and elegant solutions to common problems in software '+ 'design. It describes 23 patterns for object creation, composing them'+ ', and coordinating control flow between them.'; Post; end; with ds do begin Append; FieldByName('ISBN').Value := '978-0201485677'; FieldByName('Title').Value := 'Refactoring: Improving the Design of Existing Code'; FieldByName('Authors').Value := 'Martin Fowler, Kent Beck, John Brant, William Opdyke, Don Roberts'; FieldByName('Status').Value := 'on-shelf'; FieldByName('ReleseDate').Value := EncodeDate(1999,7,1); FieldByName('Pages').Value := 464; FieldByName('Price').Value := 52.98; FieldByName('Currency').Value := 'USD'; FieldByName('Imported').Value := EncodeDate(2017,7,9); FieldByName('Description').Value := 'Book shows how refactoring can make object-oriented code simpler and'+ ' easier to maintain. Provides a catalog of tips for improving code.'; Post; end; with ds do begin Append; FieldByName('ISBN').Value := '978-0131177055'; FieldByName('Title').Value := 'Working Effectively with Legacy Code'; FieldByName('Authors').Value := 'Michael Feathers'; FieldByName('Status').Value := 'on-shelf'; FieldByName('ReleseDate').Value := EncodeDate(2004,10,1); FieldByName('Pages').Value := 464; FieldByName('Price').Value := 52.69; FieldByName('Currency').Value := 'USD'; FieldByName('Imported').Value := EncodeDate(2017,8,7); FieldByName('Description').Value := 'This book describes a set of disciplines, concepts, and attitudes th'+ 'at you will carry with you for the rest of your career and that will'+ ' help you to turn systems that gradually degrade into systems that g'+ 'radually improve.'; Post; Append; FieldByName('ISBN').Value := '978-0321127426'; FieldByName('Title').Value := 'Patterns of Enterprise Application Architecture'; FieldByName('Authors').Value := 'Martin Fowler'; FieldByName('Status').Value := 'avaliable'; FieldByName('ReleseDate').Value := EncodeDate(2002,11,1); FieldByName('Pages').Value := 560; FieldByName('Price').Value := 55.99; FieldByName('Currency').Value := 'USD'; FieldByName('Imported').Value := EncodeDate(2017,8,20); FieldByName('Description').Value := 'This book is written in direct response to the stiff challenges that'+ ' face enterprise application developers. Author distills over forty '+ 'recurring solutions into patterns. Indispensable handbook of solutio'+ 'ns that are applicable to any enterprise application platform.'; Post; Append; FieldByName('ISBN').Value := '978-1849689121'; FieldByName('Title').Value := 'Applied Architecture Patterns on the Microsoft Platform (Second Edit'+ 'ion)'; FieldByName('Authors').Value := 'Andre Dovgal, Dmitri Olechko, Gregor Noriskin'; FieldByName('Status').Value := 'avaliable'; FieldByName('ReleseDate').Value := EncodeDate(2014,7,1); FieldByName('Pages').Value := 456; FieldByName('Price').Value := 23.24; FieldByName('Currency').Value := 'EUR'; FieldByName('Imported').Value := EncodeDate(2017,9,18); FieldByName('Description').Value := 'Work with various Microsoft technologies using Applied Architecture '+ 'Patterns'; Post; Append; FieldByName('ISBN').Value := '978-0735619678'; FieldByName('Title').Value := 'Code Complete: A Practical Handbook of Software Construction'; FieldByName('Authors').Value := 'Steve McConnell'; FieldByName('Status').Value := 'avaliable'; FieldByName('ReleseDate').Value := EncodeDate(2004,6,1); FieldByName('Pages').Value := 960; FieldByName('Price').Value := 40.97; FieldByName('Currency').Value := 'USD'; FieldByName('Imported').Value := EncodeDate(2017,9,18); FieldByName('Description').Value := 'Author synthesizes the most effective techniques and must-know princ'+ 'iples into clear, pragmatic book which will inform and stimulate you'+ 'r thinking and help you build the highest quality software'; Post; Append; FieldByName('ISBN').Value := '978-0132350884'; FieldByName('Title').Value := 'Clean Code: A Handbook of Agile Software Craftsmanship'; FieldByName('Authors').Value := 'Robert C. Martin'; FieldByName('Status').Value := 'on-shelf'; FieldByName('ReleseDate').Value := EncodeDate(2008,8,1); FieldByName('Pages').Value := 464; FieldByName('Price').Value := 47.49; FieldByName('Currency').Value := 'USD'; FieldByName('Imported').Value := EncodeDate(2017,9,19); FieldByName('Description').Value := 'Best agile practices of cleaning code “on the fly” that will instill'+ ' within you the values of a software craftsman and make you a better'+ ' programmer—but only if you work at it.'; Post; Append; FieldByName('ISBN').Value := '978-1941266106'; FieldByName('Title').Value := 'More Coding in Delphi'; FieldByName('Authors').Value := 'Nick Hodges'; FieldByName('Status').Value := 'on-shelf'; FieldByName('ReleseDate').Value := EncodeDate(2015,12,1); FieldByName('Pages').Value := 246; FieldByName('Price').Value := 25.99; FieldByName('Currency').Value := 'USD'; FieldByName('Imported').Value := EncodeDate(2017,10,1); FieldByName('Description').Value := 'Picks up where previous "Coding in Delphi" left of, continuing to il'+ 'lustrate good, sound coding techniques including design patterns and'+ ' principles'; Post; Append; FieldByName('ISBN').Value := '978-1941266038'; FieldByName('Title').Value := 'Coding in Delphi'; FieldByName('Authors').Value := 'Nick Hodges'; FieldByName('Status').Value := 'on-shelf'; FieldByName('ReleseDate').Value := EncodeDate(2014,4,1); FieldByName('Pages').Value := 236; FieldByName('Price').Value := 24.99; FieldByName('Currency').Value := 'USD'; FieldByName('Imported').Value := EncodeDate(2017,10,5); FieldByName('Description').Value := 'All about writing Delphi code. It''s just about how to use the langu'+ 'age in the most effective way to write clean, testable, maintainable'+ ' Delphi code'; Post; Append; FieldByName('ISBN').Value := '978-1785287428'; FieldByName('Title').Value := 'Delphi Cookbook - Second Edition'; FieldByName('Authors').Value := 'Daniele Teti'; FieldByName('Status').Value := 'avaliable'; FieldByName('ReleseDate').Value := EncodeDate(2016,6,1); FieldByName('Pages').Value := 470; FieldByName('Price').Value := 30.13; FieldByName('Currency').Value := 'EUR'; FieldByName('Imported').Value := EncodeDate(2017,10,18); FieldByName('Description').Value := 'Over 60 hands-on recipes to help you master the power of Delphi for '+ 'cross-platform and mobile development on multiple platforms'; Post; Append; FieldByName('ISBN').Value := '978-1786466150'; FieldByName('Title').Value := '.NET Design Patterns'; FieldByName('Authors').Value := 'Praseed Pai, Shine Xavier'; FieldByName('Status').Value := 'avaliable'; FieldByName('ReleseDate').Value := EncodeDate(2017,1,1); FieldByName('Pages').Value := 314; FieldByName('Price').Value := 26.69; FieldByName('Currency').Value := 'EUR'; FieldByName('Imported').Value := EncodeDate(2017,10,27); FieldByName('Description').Value := 'Explore the world of .NET design patterns and bring the benefits tha'+ 't the right patterns can offer to your toolkit today'; Post; Append; FieldByName('ISBN').Value := '978-1786460165'; FieldByName('Title').Value := 'Expert Delphi'; FieldByName('Authors').Value := 'Paweł Głowacki'; FieldByName('Status').Value := 'avaliable'; FieldByName('ReleseDate').Value := EncodeDate(2017,6,1); FieldByName('Pages').Value := 506; FieldByName('Price').Value := 32.71; FieldByName('Currency').Value := 'EUR'; FieldByName('Imported').Value := EncodeDate(2017,12,12); FieldByName('Description').Value := 'Become a developer superhero and build stunning cross-platform apps '+ 'with Delphi'; Post; Append; FieldByName('ISBN').Value := '978-1546391272'; FieldByName('Title').Value := 'Delphi in Depth: FireDAC'; FieldByName('Authors').Value := 'Cary Jensen Ph.D'; FieldByName('Status').Value := 'avaliable'; FieldByName('ReleseDate').Value := EncodeDate(2017,5,1); FieldByName('Pages').Value := 556; FieldByName('Price').Value := 52.43; FieldByName('Currency').Value := 'EUR'; FieldByName('Imported').Value := EncodeDate(2017,12,21); FieldByName('Description').Value := 'Learn how to connect to a wide variety of databases, optimize your c'+ 'onnection configurations, the power of persisted datasets, create fl'+ 'exible queries using macros and FireDAC scalar functions, achieve bl'+ 'azing performance with Array DML, Master the art of cached updates'; Post; Append; FieldByName('ISBN').Value := '978-1941266229'; FieldByName('Title').Value := 'Dependency Injection In Delphi'; FieldByName('Authors').Value := 'Nick Hodges'; FieldByName('Status').Value := 'avaliable'; FieldByName('ReleseDate').Value := EncodeDate(2017,2,1); FieldByName('Pages').Value := 132; FieldByName('Price').Value := 18.18; FieldByName('Currency').Value := 'USD'; FieldByName('Imported').Value := EncodeDate(2017,12,23); FieldByName('Description').Value := 'Covers Dependency Injection, you''ll learn about Constructor Injecti'+ 'on, Property Injection, and Method Injection and about the right and'+ ' wrong way to use it'; Post; Append; FieldByName('ISBN').Value := '978-1788625456'; FieldByName('Title').Value := 'Delphi High Performance'; FieldByName('Authors').Value := 'Primož Gabrijelčič'; FieldByName('Status').Value := 'avaliable'; FieldByName('ReleseDate').Value := EncodeDate(2018,2,1); FieldByName('Pages').Value := 336; FieldByName('Price').Value := 25.83; FieldByName('Currency').Value := 'EUR'; FieldByName('Imported').Value := EncodeDate(2017,12,30); FieldByName('Description').Value := 'Build fast, scalable, and high performing applications with Delphi'; Post; Append; FieldByName('ISBN').Value := '978-1788621304'; FieldByName('Title').Value := 'Delphi Cookbook - Third Edition'; FieldByName('Authors').Value := 'Daniele Spinetti, Daniele Teti'; FieldByName('Status').Value := 'avaliable'; FieldByName('ReleseDate').Value := EncodeDate(2018,7,1); FieldByName('Pages').Value := 668; FieldByName('Price').Value := 30.13; FieldByName('Currency').Value := 'EUR'; FieldByName('Imported').Value := EncodeDate(2018,3,24); FieldByName('Description').Value := 'Quickly learn and employ practical recipes for developing real-world'+ ', cross-platform applications using Delphi'; Post; Append; FieldByName('ISBN').Value := '978-1788625258'; FieldByName('Title').Value := 'Hands-On Design Patterns with C# and .NET Core'; FieldByName('Authors').Value := 'Gaurav Aroraa, Jeffrey Chilberto'; FieldByName('Status').Value := 'cooming-soon'; FieldByName('ReleseDate').Value := EncodeDate(1899,12,30); FieldByName('Pages').Value := 437; FieldByName('Price').Value := 25.83; FieldByName('Currency').Value := 'EUR'; FieldByName('Imported').Value := EncodeDate(2019,2,16)+EncodeTime(22,20,16,493); FieldByName('Description').Value := 'Build effective applications in C# and .NET Core by using proven pro'+ 'gramming practices and design techniques.'; Post; Append; FieldByName('ISBN').Value := '978-1788624176'; FieldByName('Title').Value := 'Delphi GUI Programming with FireMonkey'; FieldByName('Authors').Value := 'Andrea Magni'; FieldByName('Status').Value := 'cooming-soon'; FieldByName('ReleseDate').Value := EncodeDate(1899,12,30); FieldByName('Pages').Value := 437; FieldByName('Price').Value := 29.27; FieldByName('Currency').Value := 'EUR'; FieldByName('Imported').Value := EncodeDate(2019,2,16)+EncodeTime(22,20,16,496); FieldByName('Description').Value := 'Master the techniques to build interesting cross platform GUI applic'+ 'ations with FMX'; Post; Append; FieldByName('ISBN').Value := '978-1789343243'; FieldByName('Title').Value := 'Hands-On Design Patterns with Delphi'; FieldByName('Authors').Value := 'Primož Gabrijelčič'; FieldByName('Status').Value := 'on-shelf'; FieldByName('ReleseDate').Value := EncodeDate(2019,2,27); FieldByName('Pages').Value := 476; FieldByName('Price').Value := 35.99; FieldByName('Currency').Value := 'EUR'; FieldByName('Imported').Value := EncodeDate(2019,2,16)+EncodeTime(22,20,16,497); FieldByName('Description').Value := 'Build scalable projects via exploring design patterns in Delphi'; Post; Append; FieldByName('ISBN').Value := '978-1788834094'; FieldByName('Title').Value := 'Hands-On Domain Driven Design with .NET'; FieldByName('Authors').Value := 'Alexey Zimarev'; FieldByName('Status').Value := 'avaliable'; FieldByName('ReleseDate').Value := EncodeDate(2019,4,29); FieldByName('Pages').Value := 446; FieldByName('Price').Value := 31.99; FieldByName('Currency').Value := 'EUR'; FieldByName('Imported').Value := EncodeDate(2019,2,16)+EncodeTime(22,20,16,498); FieldByName('Description').Value := 'Learn to solve complex business problems by understanding users bett'+ 'er, finding the right problem to solve, and building lean event-driv'+ 'en systems to give your customers what they really want.'; Post; end; Result := ds; end; end.
unit Interf.SearchStringCache; interface uses System.Classes; type ISearchStringCache = interface ['{4819D4F0-383A-401A-B2A4-80286ABA5D1D}'] function GetMatch(const SearchString: string; out FoundList: TStringList): Boolean; function AddItemOnCache(const SearchString: string; var FoundList: TStringList): Boolean; end; implementation end.
unit SOPReaderUnit; interface uses Windows, Classes, SysUtils, ComObj, Variants, CommUtils, Excel2000, DateUtils; type TSOPProj = class; TSOPCol = class; TSOPLine = class; TSOPReader = class private FFile: string; ExcelApp, WorkBook: Variant; FLogEvent: TLogEvent; FHaveArea: Boolean; procedure Open; procedure Log(const str: string); function GetProjCount: Integer; function GetProjs(i: Integer): TSOPProj; public FProjYear: TStringList; FProjs: TStringList; constructor Create(slProjYear: TStringList; const sfile: string; aLogEvent: TLogEvent = nil); destructor Destroy; override; procedure Clear; function GetProj(const sName: string): TSOPProj; procedure GetNumberList(slFGNumber: TStringList); procedure GetDateList(sldate: TStringList); procedure GetMonthList(slMonth: TStringList); function GetDemand(const snumber: string; dt1: TDateTime): TSOPCol; procedure GetDemands(const snumber: string; dt1, dtMemand: TDateTime; lstDemand: TList); function GetDemandQty(const snumber: string; dt1: TDateTime): Double; function GetDemandSum(dt1: TDateTime; const snumber: string): Double; property ProjCount: Integer read GetProjCount; property Projs[i: Integer]: TSOPProj read GetProjs; property HaveArea: Boolean read FHaveArea; property sFile: string read FFile; end; TSOPProj = class private function GetLineCount: Integer; function GetLines(i: Integer): TSOPLine; public FName: string; FList: TStringList; slMonths: TStringList; constructor Create(const sproj: string); destructor Destroy; override; procedure Clear; function GetLine(const sVer, sNumber, sColor, sCap: string): TSOPLine; procedure GetVerList(sl: TStringList); procedure GetCapList(sl: TStringList); function GetSumVer(const sver: string; dt: TDateTime): Double; function GetSumCap(const scap: string; dt: TDateTime): Double; function GetSumColor(const scolor: string; dt: TDateTime): Double; function GetSumAll(dt: TDateTime): Double; function GetNumberQty(const sNumber, sver, scolor, scap: string; dt: TDateTime): Double; procedure GetDateList(sl: TStringList); procedure GetColorList(sl: TStringList); property LineCount: Integer read GetLineCount; property Lines[i: Integer]: TSOPLine read GetLines; end; TSOPLine = class private function GetDateCount: Integer; function GetDates(i: Integer): TSOPCol; public sDate: string; sProj: string; sFG: string; sPkg: string; sStdVer: string; sVer: string; //制式 sNumber: string; // 物料编码 sColor: string; //颜色 sCap: string; //容量 sMRPArea: string; FList: TStringList; FCalc: Boolean; constructor Create; destructor Destroy; override; procedure Clear; procedure Add( const sMonth, sWeek, sDate: string; dt1, dt2: TDateTime; iQty: Integer ); overload; procedure Add( const sMonth, sWeek, sDate: string; dt1, dt2: TDateTime; iQty_sop, iQty_mps: Integer ); overload; procedure Insert(idx: Integer; const sMonth, sWeek, sDate: string; dt1, dt2: TDateTime; iQty_sop, iQty_mps: Integer ); function GetCol(const sDate: string): TSOPCol; function DateIdx(const dt1: TDateTime): Integer; property DateCount: Integer read GetDateCount; property Dates[i: Integer]: TSOPCol read GetDates; end; TSOPCol = class public sMonth: string; sWeek: string; sDate: string; dt1: TDateTime; dt2: TDateTime; iQty: Double; iQty_Left: Double; // 历史遗留需求 iQty_sop: Double; iQty_mps: Double; iQty_ok: Double; // 可齐套数量 iQty_calc: Double; // 齐套分析,已计算数量 icol: Integer; sShortageICItem: string; procedure AddShortageICItem(const smsg: string); function DemandQty: Double; end; implementation type TSopColHead = packed record sdate: string; dt1: TDateTime; dt2: TDateTime; icol: Integer; end; PSopColHead = ^TSopColHead; { TSOPProj } constructor TSOPProj.Create(const sproj: string); begin FName := sproj; FList := TStringList.Create; slMonths := TStringList.Create; end; destructor TSOPProj.Destroy; begin Clear; FList.Free; slMonths.Free; inherited; end; procedure TSOPProj.Clear; var i: Integer; iweek: Integer; aSOPLine: TSOPLine; slweek: TStringList; aSopColHeadPtr: PSopColHead; begin for i := 0 to slMonths.Count - 1 do begin slweek := TStringList(slMonths.Objects[i]); for iweek := 0 to slweek.Count - 1 do begin aSopColHeadPtr := PSopColHead(slweek.Objects[iweek]); Dispose(aSopColHeadPtr); end; slweek.Free; end; slMonths.Clear; for i := 0 to FList.Count - 1 do begin aSOPLine := TSOPLine(FList.Objects[i]); aSOPLine.Free; end; FList.Clear; end; function TSOPProj.GetLineCount: Integer; begin Result := FList.Count; end; function TSOPProj.GetLines(i: Integer): TSOPLine; begin Result := TSOPLine(FList.Objects[i]); end; function TSOPProj.GetLine(const sVer, sNumber, sColor, sCap: string): TSOPLine; var i: Integer; aSOPLine: TSOPLine; begin Result := nil; for i := 0 to FList.Count - 1 do begin aSOPLine := TSOPLine(FList.Objects[i]); if (aSOPLine.sVer = sVer) and (aSOPLine.sNumber = sNumber) and (aSOPLine.sColor = sColor) and (aSOPLine.sCap = sCap) then begin Result := aSOPLine; Break; end; end; end; procedure TSOPProj.GetVerList(sl: TStringList); var iLine: Integer; aSOPLine: TSOPLine; begin for iLine := 0 to self.LineCount - 1 do begin aSOPLine := self.Lines[iLine]; if sl.IndexOf( aSOPLine.sVer ) < 0 then begin sl.Add(aSOPLine.sVer); end; end; end; procedure TSOPProj.GetCapList(sl: TStringList); var iLine: Integer; aSOPLine: TSOPLine; begin for iLine := 0 to self.LineCount - 1 do begin aSOPLine := self.Lines[iLine]; if sl.IndexOf( aSOPLine.sCap ) < 0 then begin sl.Add(aSOPLine.sCap); end; end; end; procedure TSOPProj.GetColorList(sl: TStringList); var iLine: Integer; aSOPLine: TSOPLine; begin for iLine := 0 to self.LineCount - 1 do begin aSOPLine := self.Lines[iLine]; if sl.IndexOf( aSOPLine.sColor ) < 0 then begin sl.Add(aSOPLine.sColor); end; end; end; function TSOPProj.GetSumVer(const sver: string; dt: TDateTime): Double; var iLine: Integer; aSOPLine: TSOPLine; idate: Integer; aSOPCol: TSOPCol; begin Result := 0; for iLine := 0 to self.LineCount - 1 do begin aSOPLine := self.Lines[iLine]; if aSOPLine.sVer <> sver then Continue; for idate := 0 to aSOPLine.DateCount - 1 do begin aSOPCol := aSOPLine.Dates[idate]; if DoubleE(aSOPCol.dt1, dt) then begin Result := Result + aSOPCol.iQty; Break; end; end; end; end; function TSOPProj.GetSumCap(const scap: string; dt: TDateTime): Double; var iLine: Integer; aSOPLine: TSOPLine; idate: Integer; aSOPCol: TSOPCol; begin Result := 0; for iLine := 0 to self.LineCount - 1 do begin aSOPLine := self.Lines[iLine]; if aSOPLine.sCap <> scap then Continue; for idate := 0 to aSOPLine.DateCount - 1 do begin aSOPCol := aSOPLine.Dates[idate]; if DoubleE(aSOPCol.dt1, dt) then begin Result := Result + aSOPCol.iQty; Break; end; end; end; end; function TSOPProj.GetSumColor(const scolor: string; dt: TDateTime): Double; var iLine: Integer; aSOPLine: TSOPLine; idate: Integer; aSOPCol: TSOPCol; begin Result := 0; for iLine := 0 to self.LineCount - 1 do begin aSOPLine := self.Lines[iLine]; if aSOPLine.sColor <> scolor then Continue; for idate := 0 to aSOPLine.DateCount - 1 do begin aSOPCol := aSOPLine.Dates[idate]; if DoubleE(aSOPCol.dt1, dt) then begin Result := Result + aSOPCol.iQty; Break; end; end; end; end; function TSOPProj.GetSumAll(dt: TDateTime): Double; var iLine: Integer; aSOPLine: TSOPLine; idate: Integer; aSOPCol: TSOPCol; begin Result := 0; for iLine := 0 to self.LineCount - 1 do begin aSOPLine := self.Lines[iLine]; for idate := 0 to aSOPLine.DateCount - 1 do begin aSOPCol := aSOPLine.Dates[idate]; if DoubleE(aSOPCol.dt1, dt) then begin Result := Result + aSOPCol.iQty; Break; end; end; end; end; function TSOPProj.GetNumberQty(const sNumber, sver, scolor, scap: string; dt: TDateTime): Double; var iLine: Integer; aSOPLine: TSOPLine; idate: Integer; aSOPCol: TSOPCol; begin Result := 0; for iLine := 0 to self.LineCount - 1 do begin aSOPLine := self.Lines[iLine]; // 编码为空,比较 制式、颜色、容量 if (Trim(sNumber) = '') and (Trim(aSOPLine.sNumber) = '') then begin if (aSOPLine.sVer <> sver) or (aSOPLine.sColor <> scolor) or (aSOPLine.sCap <> scap) then Continue; end else if (aSOPLine.sNumber <> sNumber) then Continue; for idate := 0 to aSOPLine.DateCount - 1 do begin aSOPCol := aSOPLine.Dates[idate]; if DoubleE(aSOPCol.dt1, dt) then begin Result := Result + aSOPCol.iQty; Break; end; end; end; end; procedure TSOPProj.GetDateList(sl: TStringList); var iLine: Integer; aSOPLine: TSOPLine; idate: Integer; aSOPCol: TSOPCol; aSOPColNew: TSOPCol; begin for iLine := 0 to self.LineCount - 1 do begin aSOPLine := self.Lines[iLine]; for idate := 0 to aSOPLine.DateCount - 1 do begin aSOPCol := aSOPLine.Dates[idate]; aSOPColNew := TSOPCol.Create; aSOPColNew.sMonth := aSOPCol.sMonth; aSOPColNew.sWeek := aSOPCol.sWeek; aSOPColNew.sDate := aSOPCol.sDate; aSOPColNew.dt1 := aSOPCol.dt1; sl.AddObject(aSOPColNew.sDate, aSOPColNew); end; Break; end; end; { TSOPLine } constructor TSOPLine.Create; begin FList := TStringList.Create; FCalc := False; end; destructor TSOPLine.Destroy; begin Clear; FList.Free; end; procedure TSOPLine.Clear; var i: Integer; aSOPCol: TSOPCol; begin for i := 0 to FList.Count - 1 do begin aSOPCol := TSOPCol(FList.Objects[i]); aSOPCol.Free; end; FList.Clear; end; function TSOPLine.GetDateCount: Integer; begin Result := FList.Count; end; function TSOPLine.GetDates(i: Integer): TSOPCol; begin Result := TSOPCol(FList.Objects[i]); end; procedure TSOPLine.Add( const sMonth, sWeek, sDate: string; dt1, dt2: TDateTime; iQty: Integer ); var aSOPCol: TSOPCol; begin aSOPCol := TSOPCol.Create; aSOPCol.sMonth := sMonth; aSOPCol.sWeek := sWeek; aSOPCol.sDate := sDate; aSOPCol.iQty := iQty; aSOPCol.dt1 := dt1; aSOPCol.dt2 := dt2; FList.AddObject(sDate, aSOPCol); end; procedure TSOPLine.Add( const sMonth, sWeek, sDate: string; dt1, dt2: TDateTime; iQty_sop, iQty_mps: Integer ); var aSOPCol: TSOPCol; begin aSOPCol := TSOPCol.Create; aSOPCol.sMonth := sMonth; aSOPCol.sWeek := sWeek; aSOPCol.sDate := sDate; aSOPCol.dt1 := dt1; aSOPCol.dt2 := dt2; aSOPCol.iQty_sop := iQty_sop; aSOPCol.iQty_mps := iQty_mps; FList.AddObject(sDate, aSOPCol); end; procedure TSOPLine.Insert(idx: Integer; const sMonth, sWeek, sDate: string; dt1, dt2: TDateTime; iQty_sop, iQty_mps: Integer ); var aSOPCol: TSOPCol; begin aSOPCol := TSOPCol.Create; aSOPCol.sMonth := sMonth; aSOPCol.sWeek := sWeek; aSOPCol.sDate := sDate; aSOPCol.dt1 := dt1; aSOPCol.dt2 := dt2; aSOPCol.iQty_sop := iQty_sop; aSOPCol.iQty_mps := iQty_mps; FList.InsertObject(idx, sDate, aSOPCol); end; function TSOPLine.GetCol(const sDate: string): TSOPCol; var i: Integer; aSOPCol: TSOPCol; begin Result := nil; for i := 0 to FList.Count - 1 do begin aSOPCol := TSOPCol(FList.Objects[i]); if aSOPCol.sDate = sDate then begin Result := aSOPCol; Break; end; end; end; function TSOPLine.DateIdx(const dt1: TDateTime): Integer; var i: Integer; aSOPCol: TSOPCol; begin Result := -1; for i := 0 to FList.Count - 1 do begin aSOPCol := TSOPCol(FList.Objects[i]); if FormatDateTime('yyyy-MM-dd', aSOPCol.dt1) = FormatDateTime('yyyy-MM-dd', dt1) then begin Result := i; Break; end; end; end; { TSOPReader } constructor TSOPReader.Create(slProjYear: TStringList; const sfile: string; aLogEvent: TLogEvent = nil); begin FFile := sfile; FLogEvent := aLogEvent; FProjYear := slProjYear; FProjs := TStringList.Create; Open; end; destructor TSOPReader.Destroy; begin Clear; FProjs.Free; inherited; end; procedure TSOPReader.Clear; var i: Integer; aSOPProj: TSOPProj; begin for i := 0 to FProjs.Count - 1 do begin aSOPProj := TSOPProj(FProjs.Objects[i]); aSOPProj.Free; end; FProjs.Clear; end; function TSOPReader.GetProj(const sName: string): TSOPProj; var i: Integer; aSOPProj: TSOPProj; begin Result := nil; for i := 0 to FProjs.Count - 1 do begin aSOPProj := TSOPProj(FProjs.Objects[i]); if aSOPProj.FName = sName then begin Result := aSOPProj; Break; end; end; end; procedure TSOPReader.GetNumberList(slFGNumber: TStringList); var iproj: Integer; aSOPProj: TSOPProj; iline: Integer; aSOPLine: TSOPLine; begin for iproj := 0 to self.FProjs.Count - 1 do begin aSOPProj := TSOPProj(FProjs.Objects[iproj]); for iline := 0 to aSOPProj.FList.Count - 1 do begin aSOPLine := TSOPLine(aSOPProj.FList.Objects[iline]); if slFGNumber.IndexOf(aSOPLine.sNumber) >= 0 then Continue; slFGNumber.Add(aSOPLine.sNumber); end; end; end; procedure TSOPReader.GetDateList(sldate: TStringList); function IndexOfDate(dt1: TDateTime): Integer; var iCount: Integer; aSOPCol: TSOPCol; begin Result := -1; for iCount := 0 to sldate.Count - 1 do begin aSOPCol := TSOPCol(sldate.Objects[iCount]); if dt1 = aSOPCol.dt1 then begin Result := iCount; Break; end; end; end; var iproj: Integer; aSOPProj: TSOPProj; iline: Integer; aSOPLine: TSOPLine; idate: Integer; aSOPCol: TSOPCol; aSOPColNew: TSOPCol; begin for iproj := 0 to self.FProjs.Count - 1 do begin aSOPProj := TSOPProj(FProjs.Objects[iproj]); for iline := 0 to aSOPProj.FList.Count - 1 do begin aSOPLine := TSOPLine(aSOPProj.FList.Objects[iline]); for idate := 0 to aSOPLine.FList.Count - 1 do begin aSOPCol := TSOPCol(aSOPLine.FList.Objects[idate]); if IndexOfDate(aSOPCol.dt1) >= 0 then Continue; aSOPColNew := TSOPCol.Create; aSOPColNew.sMonth := aSOPCol.sMonth; aSOPColNew.sWeek := aSOPCol.sWeek; aSOPColNew.sDate := aSOPCol.sDate; aSOPColNew.dt1 := aSOPCol.dt1; aSOPColNew.dt2 := aSOPCol.dt2; sldate.AddObject(aSOPColNew.sDate, aSOPColNew); end; Break; end; end; end; function StringListSortCompare_month(List: TStringList; Index1, Index2: Integer): Integer; var dt1, dt2: TDateTime; begin dt1 := myStrToDateTime(List[Index1]); dt2 := myStrToDateTime(List[Index2]); if DoubleG(dt1, dt2) then Result := 1 else if DoubleE(dt1, dt2) then Result := 0 else Result := -1; end; procedure TSOPReader.GetMonthList(slMonth: TStringList); var iproj: Integer; aSOPProj: TSOPProj; iline: Integer; aSOPLine: TSOPLine; idate: Integer; aSOPCol: TSOPCol; aSOPColNew: TSOPCol; sdt: string; begin slMonth.Clear; for iproj := 0 to self.FProjs.Count - 1 do begin aSOPProj := TSOPProj(FProjs.Objects[iproj]); for iline := 0 to aSOPProj.FList.Count - 1 do begin aSOPLine := TSOPLine(aSOPProj.FList.Objects[iline]); for idate := 0 to aSOPLine.FList.Count - 1 do begin aSOPCol := TSOPCol(aSOPLine.FList.Objects[idate]); sdt := FormatDateTime('yyyy-MM', aSOPCol.dt1) + '-01'; if slMonth.IndexOf(sdt) >= 0 then Continue; slMonth.Add(sdt); end; Break; end; end; slMonth.CustomSort(StringListSortCompare_month); end; function TSOPReader.GetDemand(const snumber: string; dt1: TDateTime): TSOPCol; var iproj: Integer; aSOPProj: TSOPProj; iline: Integer; aSOPLine: TSOPLine; idate: Integer; aSOPCol: TSOPCol; begin Result := nil; for iproj := 0 to self.FProjs.Count - 1 do begin aSOPProj := TSOPProj(FProjs.Objects[iproj]); for iline := 0 to aSOPProj.FList.Count - 1 do begin aSOPLine := TSOPLine(aSOPProj.FList.Objects[iline]); if aSOPLine.sNumber <> snumber then Continue; for idate := 0 to aSOPLine.FList.Count - 1 do begin aSOPCol := TSOPCol(aSOPLine.FList.Objects[idate]); if aSOPCol.dt1 <> dt1 then Continue; Result := aSOPCol; Break; end; Break; end; if Result <> nil then Break; end; end; procedure TSOPReader.GetDemands(const snumber: string; dt1, dtMemand: TDateTime; lstDemand: TList); var iproj: Integer; aSOPProj: TSOPProj; iline: Integer; aSOPLine: TSOPLine; idate: Integer; aSOPCol: TSOPCol; aSOPCol_last: TSOPCol; begin lstDemand.Clear; for iproj := 0 to self.FProjs.Count - 1 do begin aSOPProj := TSOPProj(FProjs.Objects[iproj]); for iline := 0 to aSOPProj.FList.Count - 1 do begin aSOPLine := TSOPLine(aSOPProj.FList.Objects[iline]); if aSOPLine.sNumber <> snumber then Continue; for idate := 0 to aSOPLine.FList.Count - 1 do begin aSOPCol := TSOPCol(aSOPLine.FList.Objects[idate]); if aSOPCol.dt1 <> dt1 then Continue; if idate > 0 then begin aSOPCol_last := TSOPCol(aSOPLine.FList.Objects[idate - 1]); if aSOPCol_last.dt1 >= dtMemand then begin aSOPCol.iQty_Left := aSOPCol_last.DemandQty - aSOPCol_last.iQty_ok; // 上一日期为满足数量 end; end; lstDemand.Add(aSOPCol); Break; end; end; end; end; function TSOPReader.GetDemandQty(const snumber: string; dt1: TDateTime): Double; var aSOPCol: TSOPCol; begin aSOPCol := GetDemand(snumber, dt1); if aSOPCol = nil then Result := 0 else Result := aSOPCol.iQty; end; function TSOPReader.GetDemandSum(dt1: TDateTime; const snumber: string): Double; var iproj: Integer; aSOPProj: TSOPProj; iline: Integer; aSOPLine: TSOPLine; idate: Integer; aSOPCol: TSOPCol; bFound: Boolean; begin Result := 0; bFound := False; for iproj := 0 to self.FProjs.Count - 1 do begin aSOPProj := TSOPProj(FProjs.Objects[iproj]); for iline := 0 to aSOPProj.FList.Count - 1 do begin aSOPLine := TSOPLine(aSOPProj.FList.Objects[iline]); if aSOPLine.sNumber <> snumber then Continue; bFound := True; for idate := 0 to aSOPLine.FList.Count - 1 do begin aSOPCol := TSOPCol(aSOPLine.FList.Objects[idate]); if aSOPCol.dt1 < dt1 then Continue; Result := Result + aSOPCol.iQty; end; Break; end; if bFound then Break; end; end; function TSOPReader.GetProjCount: Integer; begin Result := FProjs.Count; end; function TSOPReader.GetProjs(i: Integer): TSOPProj; begin Result := TSOPProj(FProjs.Objects[i]); end; procedure TSOPReader.Log(const str: string); begin if Assigned(FLogEvent) then FLogEvent(str); end; function CheckSopCol(const sdate: string): Boolean; var s: string; idx: Integer; begin Result := False; s := sdate; idx := Pos('/', s); if idx <= 0 then Exit; s := Copy(s, idx + 1, Length(s)); idx := Pos('-', s); if idx <= 0 then Exit; s := Copy(s, idx + 1, Length(s)); idx := Pos('/', s); if idx <= 0 then Exit; s := Copy(s, idx + 1, Length(s)); if Length(s) > 2 then Exit; Result := True; end; procedure MoveActOut(ExcelApp: Variant; icolDate1: Integer; const syear: string); var icol: Integer; irow: Integer; s: string; icolActOut: Integer; sFirstWeek: string; sweek: string; icolCut: Integer; s1, s2, s3, s4, s5: string; dt: TDateTime; begin icolActOut := 0; irow := 1; for icol := 5 to 1000 do begin s := ExcelApp.Cells[irow, icol].Value; if s = '实际出货' then begin icolActOut := icol; Break; end; s1 := ExcelApp.Cells[irow, icol].Value; s2 := ExcelApp.Cells[irow, icol + 1].Value; s3 := ExcelApp.Cells[irow, icol + 2].Value; s4 := ExcelApp.Cells[irow, icol + 3].Value; s5 := ExcelApp.Cells[irow, icol + 4].Value; s := s1 + s2 + s3 + s4 + s5; if s = '' then Break; end; if icolActOut = 0 then Exit; sFirstWeek := ExcelApp.Cells[2, icolDate1]; icolCut := 0; for icol := icolActOut to icolActOut + 10 do begin if not IsCellMerged(ExcelApp, 1, icolActOut, 1, icol) then Break; sweek := ExcelApp.Cells[2, icol]; if sweek = sFirstWeek then begin icolCut := icol - 1; Break; end; end; if icolCut < icolActOut then Exit; ExcelApp.Cells[1, icolActOut].UnMerge; ExcelApp.Columns[GetRef(icolActOut) + ':' + GetRef(icolCut)].Select; ExcelApp.Selection.Cut; ExcelApp.Columns[GetRef(icolDate1) + ':' + GetRef(icolDate1)].Select; ExcelApp.Selection.Insert (Shift:=xlToRight); for icol := icolDate1 to icolDate1 + icolCut - icolActOut do begin s := ExcelApp.Cells[2, icol].Value; s := Copy(s, 1, Pos('-', s) - 1); s := syear + '-' + StringReplace(s, '/', '-', [rfReplaceAll]); dt := myStrToDateTime(s); ExcelApp.Cells[1, icol].Value := 'WK' + IntToStr(WeekOfTheYear(dt)); end; end; function GetStartYear(ExcelApp: Variant; icolDate1: Integer): string; var icol: Integer; irow: Integer; s: string; s1, s2, s3, s4, s5: string; v: variant; dt: TDateTime; syear: string; begin syear := ''; irow := 1; for icol := icolDate1 to 500 do begin v := ExcelApp.Cells[irow, icol].Value; if VarIsType(v, varDate) then // 标准日期格式 begin dt := v; syear := FormatDateTime('yyyy', dt); Break; end else begin s := v; // 格式中有年度 if Pos('年', s) > 0 then begin syear := Copy(s, 1, 4); Break; end; end; s1 := ExcelApp.Cells[irow, icol].Value; s2 := ExcelApp.Cells[irow, icol + 1].Value; s3 := ExcelApp.Cells[irow, icol + 2].Value; s4 := ExcelApp.Cells[irow, icol + 3].Value; s5 := ExcelApp.Cells[irow, icol + 4].Value; s := s1 + s2 + s3 + s4 + s5; if s = '' then Break; end; Result := syear; end; procedure TSOPReader.Open; var iSheetCount, iSheet: Integer; sSheet: string; sproj: string; stitle1, stitle2, stitle3, stitle4, stitle5, stitle6, stitle7, stitle8, stitle9: string; stitle4x, stitle8x: string; stitle5x, stitle9x: string; irow, icol: Integer; icol1: Integer; smonth: string; sweek: string; sdate: string; irow1: Integer; icolDate1: Integer; icolMRPArea: Integer; icolVer: Integer; //制式 icolNumber: Integer; // 物料编码 icolColor: Integer; //颜色 icolCap: Integer; //容量 icolProj: Integer; icolFG: Integer; icolPkg: Integer; icolStdVer: Integer; sVer: string; //制式 sNumber: string; // 物料编码 sColor: string; //颜色 sCap: string; //容量 v: Variant; iQty: Integer; slWeeks: TStringList; iMonth: Integer; iWeek: Integer; aSOPLine: TSOPLine; aSOPProj: TSOPProj; iProj: Integer; aSopColHeadPtr: PSopColHead; dt0: TDateTime; syear: string; sdt1, sdt2: string; dt1, dt2: TDateTime; idx: Integer; s: string; begin Clear; icolDate1 := 0; ExcelApp := CreateOleObject('Excel.Application' ); ExcelApp.Visible := False; ExcelApp.Caption := '应用程序调用 Microsoft Excel'; try WorkBook := ExcelApp.WorkBooks.Open(FFile); FHaveArea := False; try iSheetCount := ExcelApp.Sheets.Count; for iSheet := 1 to iSheetCount do begin if not ExcelApp.Sheets[iSheet].Visible then Continue; ExcelApp.Sheets[iSheet].Activate; sSheet := ExcelApp.Sheets[iSheet].Name; ExcelApp.Columns[1].ColumnWidth := 2; ExcelApp.Columns[2].ColumnWidth := 18; ExcelApp.Columns[3].ColumnWidth := 10; irow := 1; stitle1 := ExcelApp.Cells[irow, 1].Value; stitle2 := ExcelApp.Cells[irow, 2].Value; stitle3 := ExcelApp.Cells[irow, 3].Value; stitle4 := ExcelApp.Cells[irow, 4].Value; stitle5 := ExcelApp.Cells[irow, 5].Value; stitle6 := ExcelApp.Cells[irow, 6].Value; stitle7 := ExcelApp.Cells[irow, 7].Value; stitle8 := ExcelApp.Cells[irow, 8].Value; stitle9 := ExcelApp.Cells[irow, 9].Value; stitle4x := stitle1 + stitle2 + stitle3 + stitle4; stitle8x := stitle1 + stitle2 + stitle3 + stitle4 + stitle5 + stitle6 + stitle7 + stitle8; stitle5x := stitle1 + stitle2 + stitle3 + stitle4 + stitle5; stitle9x := stitle1 + stitle2 + stitle3 + stitle4 + stitle5 + stitle6 + stitle7 + stitle8 + stitle9; if stitle4x = '制式物料编码颜色容量' then begin FHaveArea := False; icolVer := 1; // Integer; //制式 icolNumber := 2; // Integer; // 物料编码 icolColor := 3; // Integer; //颜色 icolCap := 4; // Integer; //容量 icolDate1 := 5; end else if stitle8x = '项目整机/裸机包装标准制式制式物料编码颜色容量' then begin FHaveArea := False; icolProj := 1; icolFG := 2; icolPkg := 3; icolStdVer := 4; icolVer := 5; // Integer; //制式 icolNumber := 6; // Integer; // 物料编码 icolColor := 7; // Integer; //颜色 icolCap := 8; // Integer; //容量 icolDate1 := 9; end else if (stitle5x = 'MRP区域制式物料编码颜色容量') or (stitle5x = 'MRP范围制式物料编码颜色容量') then begin FHaveArea := True; icolMRPArea := 1; icolVer := 2; // Integer; //制式 icolNumber := 3; // Integer; // 物料编码 icolColor := 4; // Integer; //颜色 icolCap := 5; // Integer; //容量 icolDate1 := 6; end else if (stitle9x = '项目整机/裸机包装标准制式MRP区域制式物料编码颜色容量') or (stitle9x = '项目整机/裸机包装标准制式MRP范围制式物料编码颜色容量') then begin FHaveArea := True; icolProj := 1; icolFG := 2; icolPkg := 3; icolStdVer := 4; icolMRPArea := 5; icolVer := 6; // Integer; //制式 icolNumber := 7; // Integer; // 物料编码 icolColor := 8; // Integer; //颜色 icolCap := 9; // Integer; //容量 icolDate1 := 10; end else begin Log(sSheet + ' 不是SOP格式'); Continue; end; sproj := sSheet; if Pos(' ', sSheet) > 0 then begin sproj := Copy(sSheet, 1, Pos(' ', sSheet) - 1); end; if (FProjYear <> nil) and (FProjYear.Count > 0) and (FProjYear.IndexOfName(sproj) < 0) then begin Log(sSheet + ' 没有项目开始年度'); Continue; end; syear := GetStartYear(ExcelApp, icolDate1); if syear = '' then begin // 文件格式中获取不到年份, 从配置获取 if FProjYear = nil then begin syear := inttostr(yearof(now)) end else begin syear := FProjYear.Values[sproj]; syear := Trim(syear); if syear = '' then begin syear := inttostr(yearof(now)); end; end; end; MoveActOut(ExcelApp, icolDate1, syear); aSOPProj := TSOPProj.Create(sproj); FProjs.AddObject(sproj, aSOPProj); irow := 1; icol := icolDate1; sweek := ExcelApp.Cells[irow, icol].Value; sdate := ExcelApp.Cells[irow + 1, icol].Value; icol1 := icol; dt0 := 0; slWeeks := TStringList.Create; while Trim(sweek + sdate) <> '' do begin if IsCellMerged(ExcelApp, irow, icol, irow + 1, icol) and (icol > icol1) then begin smonth := ExcelApp.Cells[irow, icol].Value; if slWeeks.Count > 0 then begin aSOPProj.slMonths.AddObject(smonth, slWeeks); slWeeks := TStringList.Create; end; icol := icol + 1; sweek := ExcelApp.Cells[irow, icol].Value; sdate := ExcelApp.Cells[irow + 1, icol].Value; // v := ExcelApp.Cells[irow + 1, icol].Value; // if VarIsType(v, varDate) then // begin // sdate := FormatDateTime('MM/dd-MM/dd', v); // end // else sdate := v; Continue; end; if not CheckSopCol(sdate) then begin icol := icol + 1; sweek := ExcelApp.Cells[irow, icol].Value; sdate := ExcelApp.Cells[irow + 1, icol].Value; Continue; end; aSopColHeadPtr := New(PSopColHead); aSopColHeadPtr^.sdate := sdate; aSopColHeadPtr^.icol := icol; idx := Pos('-', sdate); if idx > 0 then begin sdt1 := Copy(sdate, 1, idx - 1); sdt2 := Copy(sdate, idx + 1, Length(sdate) - idx) end else begin sdt1 := sdate; sdt2 := sdate; end; sdt1 := StringReplace(sdt1, '/', '-', [rfReplaceAll]); sdt2 := StringReplace(sdt2, '/', '-', [rfReplaceAll]); dt1 := myStrToDateTime(syear + '-' + sdt1); dt2 := myStrToDateTime(syear + '-' + sdt2); if dt0 > dt1 then begin syear := IntToStr(StrToInt(syear) + 1); dt1 := myStrToDateTime(syear + '-' + sdt1); dt2 := myStrToDateTime(syear + '-' + sdt2); end; dt0 := dt1; aSopColHeadPtr^.dt1 := dt1; aSopColHeadPtr^.dt2 := dt2; slWeeks.AddObject(sweek + '=' + sdate, TObject(aSopColHeadPtr)); icol := icol + 1; sweek := ExcelApp.Cells[irow, icol].Value; sdate := ExcelApp.Cells[irow + 1, icol].Value; end; if slWeeks.Count > 0 then begin aSOPProj.slMonths.AddObject(smonth, slWeeks); end else slWeeks.Free; irow := 3; irow1 := 0; while not IsCellMerged(ExcelApp, irow, icolNumber, irow, icolCap) do begin if (irow1 = 0) or not IsCellMerged(ExcelApp, irow1, icolVer, irow, icolVer) then begin irow1 := irow; sVer := ExcelApp.Cells[irow, icolVer].Value; end; sNumber := ExcelApp.Cells[irow, icolNumber].Value; sColor := ExcelApp.Cells[irow, icolColor].Value; sCap := ExcelApp.Cells[irow, icolCap].Value; sNumber := Trim(sNumber); if {(sVer = '') and} (sNumber = '') and (sColor = '') and (sCap = '') then begin Log('结束'); Break; end; aSOPLine := TSOPLine.Create; aSOPProj.FList.AddObject(sNumber, aSOPLine); if (icolVer = 5) or (icolVer = 6) then begin aSOPLine.sProj := ExcelApp.Cells[irow, 1].Value; aSOPLine.sFG := ExcelApp.Cells[irow, 2].Value; aSOPLine.sPkg := ExcelApp.Cells[irow, 3].Value; aSOPLine.sStdVer := ExcelApp.Cells[irow, 4].Value; end; aSOPLine.sVer := sVer; aSOPLine.sNumber := sNumber; aSOPLine.sColor := sColor; aSOPLine.sCap := sCap; if FHaveArea then begin aSOPLine.sMRPArea := ExcelApp.Cells[irow, icolMRPArea].Value; end; for iMonth := 0 to aSOPProj.slMonths.Count - 1 do begin slWeeks := TStringList(aSOPProj.slMonths.Objects[iMonth]); for iWeek := 0 to slWeeks.Count - 1 do begin aSopColHeadPtr := PSopColHead( slWeeks.Objects[iWeek] ); v := ExcelApp.Cells[irow, aSopColHeadPtr^.icol].Value; if VarIsNumeric(v) then begin iQty := v; end else begin s := v; iQty := StrToIntDef(s, 0); end; aSOPLine.Add(aSOPProj.slMonths[iMonth], slWeeks.Names[iWeek], slWeeks.ValueFromIndex[iWeek], aSopColHeadPtr^.dt1, aSopColHeadPtr^.dt2, iQty); end; end; irow := irow + 1; end; end; finally ExcelApp.ActiveWorkBook.Saved := True; //新加的,设置已经保存 WorkBook.Close; end; finally ExcelApp.Visible := True; ExcelApp.Quit; end; end; { TSOPCol } procedure TSOPCol.AddShortageICItem(const smsg: string); begin if sShortageICItem <> '' then sShortageICItem := sShortageICItem + #13#10''; sShortageICItem := sShortageICItem + smsg; end; function TSOPCol.DemandQty: Double; begin Result := iQty + iQty_Left; end; end.
unit fExportLevel; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, BCData; type TfrmExportLevel = class(TForm) txtOutputFileName: TEdit; cmdExport: TButton; lblFilename: TLabel; cmdBrowse: TButton; cbPhase: TComboBox; lblPhase: TLabel; SaveDialog: TSaveDialog; cmdCancel: TButton; procedure cmdExportClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure cmdBrowseClick(Sender: TObject); private _BattleCityROM : TBattleCityROM; procedure ExportFile(pFilename: String); { Private declarations } public { Public declarations } constructor Create(AOwner: TComponent; ROMData: TBattleCityROM); end; var frmExportLevel: TfrmExportLevel; implementation {$R *.dfm} uses uGlobals; procedure TfrmExportLevel.ExportFile(pFilename : String); var LevelFile : TMemoryStream; TempBuf : Byte; i,x : Integer; begin { TODO : Disabled Code } {LevelFile := TMemoryStream.Create; try // Write the header. TempBuf := $42; LevelFile.Write(TempBuf,1); TempBuf := $43; LevelFile.Write(TempBuf,1); TempBuf := $44; LevelFile.Write(TempBuf,1); TempBuf := $41; LevelFile.Write(TempBuf,1); TempBuf := $54; LevelFile.Write(TempBuf,1); TempBuf := $41; LevelFile.Write(TempBuf,1); // Now write the actual level data For I := 0 To 12 do begin For X := 0 To 6 do begin TempBuf := BattleCityROM.ROM[LevelLoc[cbPhase.ItemIndex] + (I * 7) + X]; LevelFile.Write(TempBuf,1); end; end; // Now write the enemy data for i := 0 to 3 do begin TempBuf := BattleCityROM.ROM[EnemyLoc[cbPhase.ItemIndex] + I]; LevelFile.Write(TempBuf,1); end; // Now write the enemy amount data for i := 0 to 3 do begin TempBuf := BattleCityROM.ROM[EnemyNumbersLoc[cbPhase.ItemIndex] + I]; LevelFile.Write(TempBuf,1); end; LevelFile.SaveToFile(pFilename); finally FreeAndNil(LevelFile); end;} end; procedure TfrmExportLevel.cmdExportClick(Sender: TObject); begin ExportFile(txtOutputFilename.text); MessageDlg('Quarrel has successfully exported the level.', mtInformation, [mbOK], 0); end; constructor TfrmExportLevel.Create(AOwner: TComponent; ROMData: TBattleCityROM); begin end; procedure TfrmExportLevel.FormShow(Sender: TObject); var I : Integer; begin { TODO : Disabled Code } { for i := 0 to NumberOfLevels - 1 do cbPhase.Items.Add('Level ' + IntToStr(i+1)); cbPhase.ItemIndex := 0;} end; procedure TfrmExportLevel.cmdBrowseClick(Sender: TObject); begin if SaveDialog.Execute then begin txtOutputFilename.Text := SaveDialog.Filename; txtOutputFilename.SelStart := length(txtOutputFilename.Text); end; end; end.
unit uAsyncIo; interface uses Windows, Messages, Classes, SysUtils; type PAsync = ^TAsync; TAsync = record AsyncEvents : array [ 0 .. 1 ] of THandle; Overlapped : TOverlapped; end; EAsync = class( Exception ) private FWinCode : Integer; public constructor Create( AWinCode : Integer ); property WinCode : Integer read FWinCode write FWinCode; end; TOpAsync = ( opAsyncRead, opAsyncWrite, opAsyncIo ); function WriteAsync( hWrite : THandle; const Buffer; Count : Integer; TimeOut : DWord; AsyncEvent : THandle = 0 ) : Integer; function ReadAsync( hRead : THandle; var Buffer; Count : Integer; TimeOut : DWord; AsyncEvent : THandle = 0 ) : Integer; function DeviceIoControlAsync( hDevice : THandle; dwIoControlCode : DWord; const lpInBuffer; nInBufferSize : DWord; var lpOutBuffer; nOutBufferSize : DWord; TimeOut : DWord; AsyncEvent : THandle = 0 ) : Integer; implementation { EAsync } // raise EAsync.Create( GetLastError() ); constructor EAsync.Create( AWinCode : Integer ); begin FWinCode := AWinCode; inherited CreateFmt( ' (Windows Error Code: %d)', [ AWinCode ] ); end; // ----------------------------------------------------------------------------- // initialization of PAsync variables used in Asynchronous calls // ----------------------------------------------------------------------------- procedure InitAsync( var AsyncPtr : PAsync ); begin New( AsyncPtr ); // Dispose(AsyncPtr) in DoneAsync() with AsyncPtr^ do begin FillChar( Overlapped, SizeOf( TOverlapped ), 0 ); // the function creates a manual-reset event object, // which requires the use of the ResetEvent function // to set the event state to nonsignaled. Overlapped.hEvent := CreateEvent( nil, True, FALSE, nil ); // IoCompleteRequest() set the event state to signaled. // After Asynchronous IoComplete AsyncEvents[ 0 ] := Overlapped.hEvent; // CloseHandle(Overlapped.hEvent) in DoneAsync() end; end; // ----------------------------------------------------------------------------- // clean-up of PAsync variable // ----------------------------------------------------------------------------- procedure DoneAsync( var AsyncPtr : PAsync ); begin CloseHandle( AsyncPtr^.Overlapped.hEvent ); Dispose( AsyncPtr ); AsyncPtr := nil; end; // ----------------------------------------------------------------------------- // perform Asynchronous io operation // ----------------------------------------------------------------------------- function DoAsync( OpAsync : TOpAsync; hAsync : THandle; TimeOut : DWord; dwIoControlCode : DWord; const lpInBuffer; nInBufferSize : DWord; var lpOutBuffer; nOutBufferSize : DWord; AsyncEvent : THandle ) : Integer; var dwWait : DWord; dwError : DWord; Async : TAsync; AsyncPtr : PAsync; BytesTrans : DWord; AsyncResult : Boolean; OverLappedResult : Boolean; DoCancelIo : Boolean; begin Result := -1; if hAsync <> INVALID_HANDLE_VALUE then begin AsyncPtr := @Async; with AsyncPtr^ do begin FillChar( Overlapped, SizeOf( TOverlapped ), 0 ); // the function creates a manual-reset event object, // which requires the use of the ResetEvent function // to set the event state to nonsignaled. Overlapped.hEvent := CreateEvent( nil, True, FALSE, nil ); // IoCompleteRequest() set the event state to signaled. // After Asynchronous IoComplete AsyncEvents[ 0 ] := Overlapped.hEvent; // CloseHandle(Overlapped.hEvent) in DoneAsync() AsyncEvents[ 1 ] := AsyncEvent; end; DoCancelIo := FALSE; BytesTrans := 0; try AsyncResult := FALSE; // Sends a control code directly to a specified device driver, // causing the corresponding device to perform the corresponding operation. // If the operation completes successfully, the return value is nonzero. // For overlapped operations, DeviceIoControl returns immediately, // and the event object is signaled when the operation has been completed. // If the operation fails or is pending, the return value is zero. if OpAsync = opAsyncIo then AsyncResult := DeviceIoControl( hAsync, dwIoControlCode, @lpInBuffer, nInBufferSize, @lpOutBuffer, nOutBufferSize, BytesTrans, @AsyncPtr^.Overlapped ) else if OpAsync = opAsyncRead then AsyncResult := ReadFile( hAsync, lpOutBuffer, nOutBufferSize, BytesTrans, @AsyncPtr^.Overlapped ) else if OpAsync = opAsyncWrite then AsyncResult := WriteFile( hAsync, lpInBuffer, nInBufferSize, BytesTrans, @AsyncPtr^.Overlapped ); // Io/Read/Write from/to device completed, done. if AsyncResult then Exit( BytesTrans ); dwError := GetLastError( ); // ERROR_ACCESS_DENIED : // if a device is disconnected while you still have the handle open // // ERROR_BAD_COMMAND : // if a device is connected but command is not supported // // ERROR_HANDLE_EOF : // we're reached the end of the file // during the call to ReadFile // code to handle that if dwError <> ERROR_IO_PENDING then Exit( -1 ); // Retrieves the results of an overlapped operation on the specified file, // named pipe, or communications device. To specify a timeout interval or // wait on an alertable thread, use GetOverlappedResultEx. // lpNumberOfBytesTransferred A pointer to a variable that receives the number // of bytes that were actually transferred by a read or write operation. // bWait : TRUE, and the Internal member of the lpOverlapped structure is // STATUS_PENDING, the function does not return until // the operation has been completed. // bWait : FALSE and the operation is still pending, the function returns FALSE // and the GetLastError function returns ERROR_IO_INCOMPLETE. // If the function succeeds, the return value is nonzero. // If the function fails, the return value is zero. // To get extended error information, call GetLastError. // A pending operation is indicated when the function that started the operation // returns FALSE, and the GetLastError function returns ERROR_IO_PENDING. // When an I/O operation is pending, the function that started the operation // resets the hEvent member of the OVERLAPPED structure to the nonsignaled state. // Then when the pending operation has been completed, // the system sets the event object to the signaled state. // // Waits until one or all of the specified objects are // in the signaled state or the time-out interval elapses. // DWORD WINAPI WaitForMultipleObjects( // __in DWORD nCount, // __in const HANDLE *lpHandles, // __in BOOL bWaitAll, // __in DWORD dwMilliseconds); // // Retrieves the results of an overlapped operation on the specified file, // named pipe, or communications device. // BOOL WINAPI GetOverlappedResult( // __in HANDLE hFile, // __in LPOVERLAPPED lpOverlapped, // __out LPDWORD lpNumberOfBytesTransferred, // __in BOOL bWait); // // asynchronous i/o is still in progress, do something else for a while // IoCompleteRequest() set the event state to signaled After IoComplete if AsyncEvent <> 0 then dwWait := WaitForMultipleObjects( 2, @AsyncPtr^.AsyncEvents[ 0 ], FALSE, TimeOut ) else dwWait := WaitForSingleObject( AsyncPtr^.AsyncEvents[ 0 ], TimeOut ); // Closing a handle while the handle is being waited on can cause undefined behaviour. // INVALID_HANDLE_VALUE // If you lack the SYNCHRONIZE privilege on the object, then you cannot wait. if dwWait = WAIT_FAILED then begin Exit( -1 ); end; if dwWait = WAIT_TIMEOUT then begin DoCancelIo := True; Exit( -1 ); end; // Only when AsyncEvent <> 0 if dwWait = ( WAIT_OBJECT_0 + 1 ) then begin ResetEvent( AsyncPtr^.AsyncEvents[ 1 ] ); DoCancelIo := True; Exit( -1 ); end; if dwWait = ( WAIT_OBJECT_0 + 0 ) then begin GetOverlappedResult( hAsync, AsyncPtr^.Overlapped, BytesTrans, FALSE ); // the manual-reset event object, which requires the use of // the ResetEvent function to set the event state to nonsignaled. ResetEvent( AsyncPtr^.AsyncEvents[ 0 ] ); Exit( BytesTrans ); // has read/written from/to device end; finally { http://blogs.msdn.com/b/oldnewthing/archive/2011/02/02/10123392.aspx } if DoCancelIo then begin { One of the cardinal rules of the OVERLAPPED structure is the OVERLAPPED structure must remain valid until the I/O completes. The reason is that the OVERLAPPED structure is manipulated by address rather than by value. The word complete here has a specific technical meaning. It doesn't mean "must remain valid until you are no longer interested in the result of the I/O." It means that the structure must remain valid until the I/O subsystem has signaled that the I/O operation is finally over, that there is nothing left to do, it has passed on: You have an ex-I/O operation. Note that an I/O operation can complete successfully, or it can complete unsuccessfully. Completion is not the same as success. } { Submit I/O cancellation to device driver } CancelIo( hAsync ); { when an I/O operation completes : It updates the OVERLAPPED structure with the results of the I/O operation, and notifies whoever wanted to be notified that the I/O is finished. } { I/O cancellation submitted to device driver, Wait IO Canceled before CloseHandle } WaitForSingleObject( AsyncPtr^.AsyncEvents[ 0 ], INFINITE ); ResetEvent( AsyncPtr^.AsyncEvents[ 0 ] ); end; CloseHandle( AsyncPtr^.AsyncEvents[ 0 ] ); AsyncPtr := nil; end; end; end; function ReadAsync( hRead : THandle; var Buffer; Count : Integer; TimeOut : DWord; AsyncEvent : THandle ) : Integer; var LBuffer : Integer; LCount : Integer; begin Result := DoAsync( opAsyncRead, hRead, TimeOut, 0, LBuffer, LCount, Buffer, Count, AsyncEvent ); end; function WriteAsync( hWrite : THandle; const Buffer; Count : Integer; TimeOut : DWord; AsyncEvent : THandle ) : Integer; var LBuffer : Integer; LCount : Integer; begin Result := DoAsync( opAsyncWrite, hWrite, TimeOut, 0, Buffer, Count, LBuffer, LCount, AsyncEvent ); end; (* BOOL WINAPI DeviceIoControl( _In_ HANDLE hDevice, _In_ DWORD dwIoControlCode, _In_opt_ LPVOID lpInBuffer, _In_ DWORD nInBufferSize, _Out_opt_ LPVOID lpOutBuffer, _In_ DWORD nOutBufferSize, _Out_opt_ LPDWORD lpBytesReturned, _Inout_opt_ LPOVERLAPPED lpOverlapped ); *) function DeviceIoControlAsync( hDevice : THandle; dwIoControlCode : DWord; const lpInBuffer; nInBufferSize : DWord; var lpOutBuffer; nOutBufferSize : DWord; TimeOut : DWord; AsyncEvent : THandle ) : Integer; begin Result := DoAsync( opAsyncWrite, hDevice, TimeOut, dwIoControlCode, lpInBuffer, nInBufferSize, lpOutBuffer, nOutBufferSize, AsyncEvent ); end; end.
// Need RECORD_AUDIO Permission unit android.speech.SpeechRecognizer; interface {$IFDEF ANDROID} uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, Androidapi.JNI.Os, Androidapi.JNI.GraphicsContentViewText; type JSpeechRecognizer = interface; JRecognitionListener = interface; JRecognizerIntent = interface; JSpeechRecognizerClass = interface(JObjectClass) ['{88580157-3372-4534-A141-96E730D15BE0}'] function _GetCONFIDENCE_SCORES : JString; cdecl; // A: $19 function _GetERROR_AUDIO : Integer; cdecl; // A: $19 function _GetERROR_CLIENT : Integer; cdecl; // A: $19 function _GetERROR_INSUFFICIENT_PERMISSIONS : Integer; cdecl; // A: $19 function _GetERROR_NETWORK : Integer; cdecl; // A: $19 function _GetERROR_NETWORK_TIMEOUT : Integer; cdecl; // A: $19 function _GetERROR_NO_MATCH : Integer; cdecl; // A: $19 function _GetERROR_RECOGNIZER_BUSY : Integer; cdecl; // A: $19 function _GetERROR_SERVER : Integer; cdecl; // A: $19 function _GetERROR_SPEECH_TIMEOUT : Integer; cdecl; // A: $19 function _GetRESULTS_RECOGNITION : JString; cdecl; // A: $19 function createSpeechRecognizer(context : JContext) : JSpeechRecognizer; cdecl; overload;// (Landroid/content/Context;)Landroid/speech/SpeechRecognizer; A: $9 function createSpeechRecognizer(context : JContext; serviceComponent : JComponentName) : JSpeechRecognizer; cdecl; overload;// (Landroid/content/Context;Landroid/content/ComponentName;)Landroid/speech/SpeechRecognizer; A: $9 function isRecognitionAvailable(context : JContext) : boolean; cdecl; // (Landroid/content/Context;)Z A: $9 procedure cancel ; cdecl; // ()V A: $1 procedure destroy ; cdecl; // ()V A: $1 procedure setRecognitionListener(listener : JRecognitionListener) ; cdecl; // (Landroid/speech/RecognitionListener;)V A: $1 procedure startListening(recognizerIntent : JIntent) ; cdecl; // (Landroid/content/Intent;)V A: $1 procedure stopListening ; cdecl; // ()V A: $1 property CONFIDENCE_SCORES : JString read _GetCONFIDENCE_SCORES; // Ljava/lang/String; A: $19 property ERROR_AUDIO : Integer read _GetERROR_AUDIO; // I A: $19 property ERROR_CLIENT : Integer read _GetERROR_CLIENT; // I A: $19 property ERROR_INSUFFICIENT_PERMISSIONS : Integer read _GetERROR_INSUFFICIENT_PERMISSIONS;// I A: $19 property ERROR_NETWORK : Integer read _GetERROR_NETWORK; // I A: $19 property ERROR_NETWORK_TIMEOUT : Integer read _GetERROR_NETWORK_TIMEOUT; // I A: $19 property ERROR_NO_MATCH : Integer read _GetERROR_NO_MATCH; // I A: $19 property ERROR_RECOGNIZER_BUSY : Integer read _GetERROR_RECOGNIZER_BUSY; // I A: $19 property ERROR_SERVER : Integer read _GetERROR_SERVER; // I A: $19 property ERROR_SPEECH_TIMEOUT : Integer read _GetERROR_SPEECH_TIMEOUT; // I A: $19 property RESULTS_RECOGNITION : JString read _GetRESULTS_RECOGNITION; // Ljava/lang/String; A: $19 end; [JavaSignature('android/speech/SpeechRecognizer')] JSpeechRecognizer = interface(JObject) ['{F76A683F-F90D-489E-A9B6-D167ED3C7658}'] procedure cancel ; cdecl; // ()V A: $1 procedure destroy ; cdecl; // ()V A: $1 procedure setRecognitionListener(listener : JRecognitionListener) ; cdecl; // (Landroid/speech/RecognitionListener;)V A: $1 procedure startListening(recognizerIntent : JIntent) ; cdecl; // (Landroid/content/Intent;)V A: $1 procedure stopListening ; cdecl; // ()V A: $1 end; TJSpeechRecognizer = class(TJavaGenericImport<JSpeechRecognizerClass, JSpeechRecognizer>) end; JRecognitionListenerClass = interface(JObjectClass) ['{2D6FFE3E-233C-4DC9-819C-22C9BEF470A1}'] procedure onBeginningOfSpeech ; cdecl; // ()V A: $401 procedure onBufferReceived(TJavaArrayByteparam0 : TJavaArray<Byte>) ; cdecl;// ([B)V A: $401 procedure onEndOfSpeech ; cdecl; // ()V A: $401 procedure onError(Integerparam0 : Integer) ; cdecl; // (I)V A: $401 procedure onEvent(Integerparam0 : Integer; JBundleparam1 : JBundle) ; cdecl;// (ILandroid/os/Bundle;)V A: $401 procedure onPartialResults(JBundleparam0 : JBundle) ; cdecl; // (Landroid/os/Bundle;)V A: $401 procedure onReadyForSpeech(JBundleparam0 : JBundle) ; cdecl; // (Landroid/os/Bundle;)V A: $401 procedure onResults(JBundleparam0 : JBundle) ; cdecl; // (Landroid/os/Bundle;)V A: $401 procedure onRmsChanged(Singleparam0 : Single) ; cdecl; // (F)V A: $401 end; [JavaSignature('android/speech/RecognitionListener')] JRecognitionListener = interface(JObject) ['{E636176D-E6C2-405C-94C1-CC08701DFFAA}'] procedure onBeginningOfSpeech ; cdecl; // ()V A: $401 procedure onBufferReceived(TJavaArrayByteparam0 : TJavaArray<Byte>) ; cdecl;// ([B)V A: $401 procedure onEndOfSpeech ; cdecl; // ()V A: $401 procedure onError(Integerparam0 : Integer) ; cdecl; // (I)V A: $401 procedure onEvent(Integerparam0 : Integer; JBundleparam1 : JBundle) ; cdecl;// (ILandroid/os/Bundle;)V A: $401 procedure onPartialResults(JBundleparam0 : JBundle) ; cdecl; // (Landroid/os/Bundle;)V A: $401 procedure onReadyForSpeech(JBundleparam0 : JBundle) ; cdecl; // (Landroid/os/Bundle;)V A: $401 procedure onResults(JBundleparam0 : JBundle) ; cdecl; // (Landroid/os/Bundle;)V A: $401 procedure onRmsChanged(Singleparam0 : Single) ; cdecl; // (F)V A: $401 end; TJRecognitionListener = class(TJavaGenericImport<JRecognitionListenerClass, JRecognitionListener>) end; JRecognizerIntentClass = interface(JObjectClass) ['{028F22D9-0B41-4DA7-8C4C-4E1E07E40DF0}'] function _GetACTION_GET_LANGUAGE_DETAILS : JString; cdecl; // A: $19 function _GetACTION_RECOGNIZE_SPEECH : JString; cdecl; // A: $19 function _GetACTION_VOICE_SEARCH_HANDS_FREE : JString; cdecl; // A: $19 function _GetACTION_WEB_SEARCH : JString; cdecl; // A: $19 function _GetDETAILS_META_DATA : JString; cdecl; // A: $19 function _GetEXTRA_CALLING_PACKAGE : JString; cdecl; // A: $19 function _GetEXTRA_CONFIDENCE_SCORES : JString; cdecl; // A: $19 function _GetEXTRA_LANGUAGE : JString; cdecl; // A: $19 function _GetEXTRA_LANGUAGE_MODEL : JString; cdecl; // A: $19 function _GetEXTRA_LANGUAGE_PREFERENCE : JString; cdecl; // A: $19 function _GetEXTRA_MAX_RESULTS : JString; cdecl; // A: $19 function _GetEXTRA_ONLY_RETURN_LANGUAGE_PREFERENCE : JString; cdecl; // A: $19 function _GetEXTRA_ORIGIN : JString; cdecl; // A: $19 function _GetEXTRA_PARTIAL_RESULTS : JString; cdecl; // A: $19 function _GetEXTRA_PROMPT : JString; cdecl; // A: $19 function _GetEXTRA_RESULTS : JString; cdecl; // A: $19 function _GetEXTRA_RESULTS_PENDINGINTENT : JString; cdecl; // A: $19 function _GetEXTRA_RESULTS_PENDINGINTENT_BUNDLE : JString; cdecl; // A: $19 function _GetEXTRA_SECURE : JString; cdecl; // A: $19 function _GetEXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS : JString; cdecl;// A: $19 function _GetEXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS : JString; cdecl; // A: $19 function _GetEXTRA_SPEECH_INPUT_POSSIBLY_COMPLETE_SILENCE_LENGTH_MILLIS : JString; cdecl;// A: $19 function _GetEXTRA_SUPPORTED_LANGUAGES : JString; cdecl; // A: $19 function _GetEXTRA_WEB_SEARCH_ONLY : JString; cdecl; // A: $19 function _GetLANGUAGE_MODEL_FREE_FORM : JString; cdecl; // A: $19 function _GetLANGUAGE_MODEL_WEB_SEARCH : JString; cdecl; // A: $19 function _GetRESULT_AUDIO_ERROR : Integer; cdecl; // A: $19 function _GetRESULT_CLIENT_ERROR : Integer; cdecl; // A: $19 function _GetRESULT_NETWORK_ERROR : Integer; cdecl; // A: $19 function _GetRESULT_NO_MATCH : Integer; cdecl; // A: $19 function _GetRESULT_SERVER_ERROR : Integer; cdecl; // A: $19 function getVoiceDetailsIntent(context : JContext) : JIntent; cdecl; // (Landroid/content/Context;)Landroid/content/Intent; A: $19 property ACTION_GET_LANGUAGE_DETAILS : JString read _GetACTION_GET_LANGUAGE_DETAILS;// Ljava/lang/String; A: $19 property ACTION_RECOGNIZE_SPEECH : JString read _GetACTION_RECOGNIZE_SPEECH;// Ljava/lang/String; A: $19 property ACTION_VOICE_SEARCH_HANDS_FREE : JString read _GetACTION_VOICE_SEARCH_HANDS_FREE;// Ljava/lang/String; A: $19 property ACTION_WEB_SEARCH : JString read _GetACTION_WEB_SEARCH; // Ljava/lang/String; A: $19 property DETAILS_META_DATA : JString read _GetDETAILS_META_DATA; // Ljava/lang/String; A: $19 property EXTRA_CALLING_PACKAGE : JString read _GetEXTRA_CALLING_PACKAGE; // Ljava/lang/String; A: $19 property EXTRA_CONFIDENCE_SCORES : JString read _GetEXTRA_CONFIDENCE_SCORES;// Ljava/lang/String; A: $19 property EXTRA_LANGUAGE : JString read _GetEXTRA_LANGUAGE; // Ljava/lang/String; A: $19 property EXTRA_LANGUAGE_MODEL : JString read _GetEXTRA_LANGUAGE_MODEL; // Ljava/lang/String; A: $19 property EXTRA_LANGUAGE_PREFERENCE : JString read _GetEXTRA_LANGUAGE_PREFERENCE;// Ljava/lang/String; A: $19 property EXTRA_MAX_RESULTS : JString read _GetEXTRA_MAX_RESULTS; // Ljava/lang/String; A: $19 property EXTRA_ONLY_RETURN_LANGUAGE_PREFERENCE : JString read _GetEXTRA_ONLY_RETURN_LANGUAGE_PREFERENCE;// Ljava/lang/String; A: $19 property EXTRA_ORIGIN : JString read _GetEXTRA_ORIGIN; // Ljava/lang/String; A: $19 property EXTRA_PARTIAL_RESULTS : JString read _GetEXTRA_PARTIAL_RESULTS; // Ljava/lang/String; A: $19 property EXTRA_PROMPT : JString read _GetEXTRA_PROMPT; // Ljava/lang/String; A: $19 property EXTRA_RESULTS : JString read _GetEXTRA_RESULTS; // Ljava/lang/String; A: $19 property EXTRA_RESULTS_PENDINGINTENT : JString read _GetEXTRA_RESULTS_PENDINGINTENT;// Ljava/lang/String; A: $19 property EXTRA_RESULTS_PENDINGINTENT_BUNDLE : JString read _GetEXTRA_RESULTS_PENDINGINTENT_BUNDLE;// Ljava/lang/String; A: $19 property EXTRA_SECURE : JString read _GetEXTRA_SECURE; // Ljava/lang/String; A: $19 property EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS : JString read _GetEXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS;// Ljava/lang/String; A: $19 property EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS : JString read _GetEXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS;// Ljava/lang/String; A: $19 property EXTRA_SPEECH_INPUT_POSSIBLY_COMPLETE_SILENCE_LENGTH_MILLIS : JString read _GetEXTRA_SPEECH_INPUT_POSSIBLY_COMPLETE_SILENCE_LENGTH_MILLIS;// Ljava/lang/String; A: $19 property EXTRA_SUPPORTED_LANGUAGES : JString read _GetEXTRA_SUPPORTED_LANGUAGES;// Ljava/lang/String; A: $19 property EXTRA_WEB_SEARCH_ONLY : JString read _GetEXTRA_WEB_SEARCH_ONLY; // Ljava/lang/String; A: $19 property LANGUAGE_MODEL_FREE_FORM : JString read _GetLANGUAGE_MODEL_FREE_FORM;// Ljava/lang/String; A: $19 property LANGUAGE_MODEL_WEB_SEARCH : JString read _GetLANGUAGE_MODEL_WEB_SEARCH;// Ljava/lang/String; A: $19 property RESULT_AUDIO_ERROR : Integer read _GetRESULT_AUDIO_ERROR; // I A: $19 property RESULT_CLIENT_ERROR : Integer read _GetRESULT_CLIENT_ERROR; // I A: $19 property RESULT_NETWORK_ERROR : Integer read _GetRESULT_NETWORK_ERROR; // I A: $19 property RESULT_NO_MATCH : Integer read _GetRESULT_NO_MATCH; // I A: $19 property RESULT_SERVER_ERROR : Integer read _GetRESULT_SERVER_ERROR; // I A: $19 end; [JavaSignature('android/speech/RecognizerIntent')] JRecognizerIntent = interface(JObject) ['{FE722411-65FA-4B52-A721-37330C246156}'] end; TJRecognizerIntent = class(TJavaGenericImport<JRecognizerIntentClass, JRecognizerIntent>) end; const TJRecognizerIntentEXTRA_CALLING_PACKAGE = 'calling_package'; TJRecognizerIntentACTION_RECOGNIZE_SPEECH = 'android.speech.action.RECOGNIZE_SPEECH'; TJRecognizerIntentACTION_WEB_SEARCH = 'android.speech.action.WEB_SEARCH'; TJRecognizerIntentACTION_VOICE_SEARCH_HANDS_FREE = 'android.speech.action.VOICE_SEARCH_HANDS_FREE'; TJRecognizerIntentEXTRA_SECURE = 'android.speech.extras.EXTRA_SECURE'; TJRecognizerIntentEXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS = 'android.speech.extras.SPEECH_INPUT_MINIMUM_LENGTH_MILLIS'; TJRecognizerIntentEXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS = 'android.speech.extras.SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS'; TJRecognizerIntentEXTRA_SPEECH_INPUT_POSSIBLY_COMPLETE_SILENCE_LENGTH_MILLIS = 'android.speech.extras.SPEECH_INPUT_POSSIBLY_COMPLETE_SILENCE_LENGTH_MILLIS'; TJRecognizerIntentEXTRA_LANGUAGE_MODEL = 'android.speech.extra.LANGUAGE_MODEL'; TJRecognizerIntentLANGUAGE_MODEL_FREE_FORM = 'free_form'; TJRecognizerIntentLANGUAGE_MODEL_WEB_SEARCH = 'web_search'; TJRecognizerIntentEXTRA_PROMPT = 'android.speech.extra.PROMPT'; TJRecognizerIntentEXTRA_LANGUAGE = 'android.speech.extra.LANGUAGE'; TJRecognizerIntentEXTRA_ORIGIN = 'android.speech.extra.ORIGIN'; TJRecognizerIntentEXTRA_MAX_RESULTS = 'android.speech.extra.MAX_RESULTS'; TJRecognizerIntentEXTRA_WEB_SEARCH_ONLY = 'android.speech.extra.WEB_SEARCH_ONLY'; TJRecognizerIntentEXTRA_PARTIAL_RESULTS = 'android.speech.extra.PARTIAL_RESULTS'; TJRecognizerIntentEXTRA_RESULTS_PENDINGINTENT = 'android.speech.extra.RESULTS_PENDINGINTENT'; TJRecognizerIntentEXTRA_RESULTS_PENDINGINTENT_BUNDLE = 'android.speech.extra.RESULTS_PENDINGINTENT_BUNDLE'; TJRecognizerIntentRESULT_NO_MATCH = 1; TJRecognizerIntentRESULT_CLIENT_ERROR = 2; TJRecognizerIntentRESULT_SERVER_ERROR = 3; TJRecognizerIntentRESULT_NETWORK_ERROR = 4; TJRecognizerIntentRESULT_AUDIO_ERROR = 5; TJRecognizerIntentEXTRA_RESULTS = 'android.speech.extra.RESULTS'; TJRecognizerIntentEXTRA_CONFIDENCE_SCORES = 'android.speech.extra.CONFIDENCE_SCORES'; TJRecognizerIntentDETAILS_META_DATA = 'android.speech.DETAILS'; TJRecognizerIntentACTION_GET_LANGUAGE_DETAILS = 'android.speech.action.GET_LANGUAGE_DETAILS'; TJRecognizerIntentEXTRA_ONLY_RETURN_LANGUAGE_PREFERENCE = 'android.speech.extra.ONLY_RETURN_LANGUAGE_PREFERENCE'; TJRecognizerIntentEXTRA_LANGUAGE_PREFERENCE = 'android.speech.extra.LANGUAGE_PREFERENCE'; TJRecognizerIntentEXTRA_SUPPORTED_LANGUAGES = 'android.speech.extra.SUPPORTED_LANGUAGES'; TJSpeechRecognizerRESULTS_RECOGNITION = 'results_recognition'; TJSpeechRecognizerCONFIDENCE_SCORES = 'confidence_scores'; TJSpeechRecognizerERROR_NETWORK_TIMEOUT = 1; TJSpeechRecognizerERROR_NETWORK = 2; TJSpeechRecognizerERROR_AUDIO = 3; TJSpeechRecognizerERROR_SERVER = 4; TJSpeechRecognizerERROR_CLIENT = 5; TJSpeechRecognizerERROR_SPEECH_TIMEOUT = 6; TJSpeechRecognizerERROR_NO_MATCH = 7; TJSpeechRecognizerERROR_RECOGNIZER_BUSY = 8; TJSpeechRecognizerERROR_INSUFFICIENT_PERMISSIONS = 9; {$ENDIF} implementation end.
unit DataModulo; interface uses VarSYS, Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, DataModuloTemplate, Db, DBTables, RxQuery, DBLists; type TDM = class(TDMTemplate) SQLUsuarios: TQuery; SQLUsuariosUSUAICOD: TIntegerField; SQLUsuariosUSUAA60LOGIN: TStringField; SQLUsuariosUSUAA5SENHA: TStringField; SQLConfigCrediario: TQuery; SQLConfigCrediarioCFCRN2PERCJURATRAS: TBCDField; SQLConfigCrediarioCFCRN2PERCMULATRAS: TBCDField; SQLConfigCrediarioCFCRINRODIASTOLJUR: TIntegerField; SQLConfigCrediarioCFCRINRODIASTOLMUL: TIntegerField; SQLConfigCrediarioCFCRN2PERCADIANT: TBCDField; SQLConfigCrediarioCFCRINRODIASADIANT: TIntegerField; SQLConfigCrediarioCFCRINRODIACARTA1A: TIntegerField; SQLConfigCrediarioCFCRINRODIACARTA2A: TIntegerField; SQLConfigCrediarioCFCRINRODIACARTA3A: TIntegerField; SQLConfigCrediarioCFCRA255PATHCART1A: TStringField; SQLConfigCrediarioCFCRA255PATHCART2A: TStringField; SQLConfigCrediarioCFCRA255PATHCART3A: TStringField; SQLConfigCrediarioCFCRCCONSMOTBLOQ: TStringField; SQLConfigCrediarioCFCRCCONSCARTAVISO: TStringField; SQLConfigCrediarioCFCRA255PATHRELSPC: TStringField; SQLConfigCrediarioCFCRA255PATHAUTDEP: TStringField; SQLConfigGeral: TQuery; SQLConfigGeralCFGEIEMPPADRAO: TIntegerField; SQLConfigGeralEmpresaPadraoCalcField: TStringField; SQLEmpresa: TRxQuery; SQLConfigVenda: TRxQuery; SQLConfigVendaOPESICODCANCTROCA: TIntegerField; SQLConfigVendaOPESICODTROCA: TIntegerField; SQLConfigVendaOPESICODCUPOM: TIntegerField; SQLConfigVendaOPESICODCANCCUPOM: TIntegerField; SQLConfigVendaOPESICODNF: TIntegerField; SQLConfigVendaOPESICODCANCNF: TIntegerField; SQLConfigVendaOPESICODRETORNO: TIntegerField; SQLProdutoSaldo: TRxQuery; SQLProdutoSaldoEMPRICOD: TIntegerField; SQLProdutoSaldoPRODICOD: TIntegerField; SQLProdutoSaldoPSLDN3QTDE: TBCDField; SQLProdutoFilho: TRxQuery; DSSQLProduto: TDataSource; SQLProduto: TRxQuery; SQLConfigConta: TRxQuery; SQLConfigContaCFGCINIVEL1: TBCDField; SQLConfigContaCFGCNIVEIS: TIntegerField; SQLConfigContaCFGCINIVEL2: TBCDField; SQLConfigContaCFGCINIVEL3: TBCDField; SQLConfigContaCFGCINIVEL4: TBCDField; SQLConfigContaCFGCINIVEL5: TBCDField; SQLConfigContaCFGCINIVEL6: TBCDField; SQLConfigContaCFGCINIVEL7: TBCDField; SQLConfigContaCFGCINIVEL8: TBCDField; SQLConfigContaCFGCINIVEL9: TBCDField; SQLConfigContaCFGCINIVEL10: TBCDField; SQLConfigContaCFGCA30MASCARA: TStringField; SQLConfigContaPENDENTE: TStringField; SQLConfigContaREGISTRO: TDateTimeField; DSSQLConfigConta: TDataSource; UpdateSQLConfigConta: TUpdateSQL; SQLPlanodeContas: TRxQuery; SQLPlanodeContasPLCTA15COD: TStringField; SQLPlanodeContasPLCTICODREDUZ: TIntegerField; SQLPlanodeContasPLCTINIVEL: TIntegerField; SQLPlanodeContasPLCTA15CODPAI: TStringField; SQLPlanodeContasPLCTA30CODEDIT: TStringField; SQLPlanodeContasPLCTA60DESCR: TStringField; SQLPlanodeContasPLCTCANALSINT: TStringField; SQLPlanodeContasPLCTCTIPOSALDO: TStringField; SQLPlanodeContasPENDENTE: TStringField; SQLPlanodeContasREGISTRO: TDateTimeField; DSSQLPlanodeContas: TDataSource; UpDateSQLPlanodeContas: TUpdateSQL; SQLConta: TRxQuery; SQLContaPLCTA15COD: TStringField; SQLContaPLCTICODREDUZ: TIntegerField; SQLContaPLCTINIVEL: TIntegerField; SQLContaPLCTA15CODPAI: TStringField; SQLContaPLCTA30CODEDIT: TStringField; SQLContaPLCTA60DESCR: TStringField; SQLContaPLCTCANALSINT: TStringField; SQLContaPLCTCTIPOSALDO: TStringField; SQLContaPENDENTE: TStringField; SQLContaREGISTRO: TDateTimeField; SQLConfigGeralCFGEA255PATHREPORT: TStringField; SQLConfigCrediarioCFCRINRODIACARTA4A: TIntegerField; SQLConfigCrediarioCFCRN2PERCTAXACOBR: TBCDField; SQLPreco: TRxQuery; SQLProdutoOrdemPesquisa: TRxQuery; SQLProdutoOrdemPesquisaPDOPIORDEM: TIntegerField; SQLProdutoOrdemPesquisaPDOPA30CAMPO: TStringField; SQLConfigVendaCFVECFAZVENDCONSIG: TStringField; SQLTerminalAtivo: TRxQuery; SQLTerminalAtivoTERMICOD: TIntegerField; SQLTerminalAtivoTERMA60DESCR: TStringField; SQLTerminalAtivoTERMCINFDADOSCLICP: TStringField; SQLTerminalAtivoTERMA60IMPAUTORIZCOM: TStringField; SQLTerminalAtivoTERMA60IMPFICHACLI: TStringField; SQLConfigVendaCFVECTIPOLIMCRED: TStringField; SQLConfigVendaCFVEN3MAXLIMCRED: TBCDField; SQLConfigVendaCFVEN2PERCLIMCRED: TBCDField; SQLConfigGeralCFGECATUSALDODIA: TStringField; SQLConfigVendaCFVECSUBDEBNOLIMITE: TStringField; SQLConfigVendaCFVEINROCASASDEC: TIntegerField; SQLConfigVendaCFVECFARREDVLRVEND: TStringField; SQLConfigCrediarioCFCRA254PATHMALADIRETA: TStringField; SQLConfigVendaCFVECTESTALIMTCRED: TStringField; SQLParcelas: TRxQuery; SQLCliente: TRxQuery; SQLConfigFinanceiro: TRxQuery; SQLConfigFinanceiroOPTEICODPAGAR: TIntegerField; SQLConfigFinanceiroOPBCICODPAGAR: TIntegerField; SQLConfigFinanceiroNUMEICODPAGAR: TIntegerField; SQLConfigFinanceiroCTCRICODPAGAR: TIntegerField; SQLConfigFinanceiroALINICODPAGAR: TIntegerField; SQLConfigFinanceiroCGFIA254HISTPAGAR: TStringField; SQLConfigFinanceiroOPTEICODRECEBER: TIntegerField; SQLConfigFinanceiroOPBCICODRECEBER: TIntegerField; SQLConfigFinanceiroNUMEICODRECEBER: TIntegerField; SQLConfigFinanceiroCGFIA254HISTRECEBE: TStringField; SQLConfigFinanceiroALINICODRECEBER: TIntegerField; SQLConfigFinanceiroPORTICODRECEBER: TIntegerField; SQLConfigFinanceiroCGFIUSATESOURARIA: TStringField; SQLConfigGeralCFGEA255EXEDUPLICATA: TStringField; SQLTeleEntrega: TRxQuery; SQLTeleEntregaTELEA13ID: TStringField; SQLTeleEntregaEMPRICOD: TIntegerField; SQLTeleEntregaTERMICOD: TIntegerField; SQLTeleEntregaTELEICOD: TIntegerField; SQLTeleEntregaCUPOA13ID: TStringField; SQLTeleEntregaNOFIA13ID: TStringField; SQLTeleEntregaPDVDA13ID: TStringField; SQLTeleEntregaTELEDENTRPREV: TDateTimeField; SQLTeleEntregaTELEDENTRPREV1: TDateTimeField; SQLTeleEntregaTELEDENTRPREV2: TDateTimeField; SQLTeleEntregaTELEDENTRREAL: TDateTimeField; SQLTeleEntregaTELEA60SOLICITANTE: TStringField; SQLTeleEntregaTELEA60ENTRPARANOME: TStringField; SQLTeleEntregaTELEA60ENTRPARAEND: TStringField; SQLTeleEntregaTELEA60ENTRPARABAI: TStringField; SQLTeleEntregaTELEA60ENTRPARACID: TStringField; SQLTeleEntregaTELEA2ENTRPARAUF: TStringField; SQLTeleEntregaTELEA15ENTRPARAFONE: TStringField; SQLTeleEntregaTELEA60RECPORNOME: TStringField; SQLTeleEntregaTELEADREC: TDateTimeField; SQLTeleEntregaTELEA1016MENSG: TMemoField; SQLTeleEntregaPENDENTE: TStringField; SQLTeleEntregaREGISTRO: TDateTimeField; UpdateSQLTeleEntrega: TUpdateSQL; SQLUsuariosUSUACUSERMASTER: TStringField; SQLConfigVendaCFVECRENDCONJNOLIM: TStringField; SQLEmpresaEMPRICOD: TIntegerField; SQLEmpresaEMPRA60RAZAOSOC: TStringField; SQLEmpresaEMPRA60NOMEFANT: TStringField; SQLEmpresaEMPRCMATRIZFILIAL: TStringField; SQLEmpresaEMPRA20FONE: TStringField; SQLEmpresaEMPRA20FAX: TStringField; SQLEmpresaEMPRA60END: TStringField; SQLEmpresaEMPRA60BAI: TStringField; SQLEmpresaEMPRA60CID: TStringField; SQLEmpresaEMPRA2UF: TStringField; SQLEmpresaEMPRA8CEP: TStringField; SQLEmpresaEMPRCFISJURID: TStringField; SQLEmpresaEMPRA14CGC: TStringField; SQLEmpresaEMPRA20IE: TStringField; SQLEmpresaEMPRA11CPF: TStringField; SQLEmpresaEMPRA10RG: TStringField; SQLEmpresaEMPRA60EMAIL: TStringField; SQLEmpresaEMPRA60URL: TStringField; SQLEmpresaPENDENTE: TStringField; SQLEmpresaREGISTRO: TDateTimeField; SQLEmpresaEMPRA100INFSPC: TStringField; SQLTerminalAtivoTERMA60IMPPEDIDO: TStringField; TblTicketPreVendaCab: TTable; TblTicketPreVendaCabTicketNumero: TStringField; TblTicketPreVendaCabVendedor: TStringField; TblTicketPreVendaCabPlano: TStringField; TblTicketPreVendaCabCliente: TStringField; TblTicketPreVendaCabFoneCliente: TStringField; TblTicketPreVendaCabTotalNominal: TFloatField; TblTicketPreVendaCabTaxaCrediario: TFloatField; TblTicketPreVendaCabAcrescimo: TFloatField; TblTicketPreVendaCabDesconto: TFloatField; TblTicketPreVendaCabTotalGeral: TFloatField; TblTicketPreVendaCabNomeEmpresa: TStringField; TblTicketPreVendaCabFoneEmpresa: TStringField; TblTicketPreVendaCabNroCreditCard: TStringField; TblTicketPreVendaCabNumerarioPagto: TStringField; TblTicketPreVendaCabMensagem: TStringField; TblTicketPreVendaCabDataEntrega: TStringField; TblTicketPreVendaCabTipoVenda: TStringField; TblTicketPreVendaCabPessoaRecebeNome: TStringField; TblTicketPreVendaCabPessoaRecebeEnder: TStringField; TblTicketPreVendaCabPessoaRecebeBai: TStringField; TblTicketPreVendaCabPessoaRecebeCid: TStringField; TblTicketPreVendaCabPessoaRecebeUF: TStringField; TblTicketPreVendaCabPessoaRecebeFone: TStringField; TblTicketPreVendaCabMensagem2: TMemoField; TblTicketPreVendaItem: TTable; TblTicketPreVendaItemCodigo: TIntegerField; TblTicketPreVendaItemDescricao: TStringField; TblTicketPreVendaItemQuantidade: TFloatField; TblTicketPreVendaItemValorUnitario: TFloatField; TblTicketPreVendaItemValorTotal: TFloatField; TblTicketPreVendaItemDesconto: TFloatField; TblTicketPreVendaItemMarca: TStringField; TblTicketPreVendaItemReferencia: TStringField; SQLEmpresaEMPRA15CODEAN: TStringField; SQLEmpresaEMPRBLOGOTIPO: TBlobField; SQLConfigVendaCFVECINFDADOVENDA: TStringField; TblTicketPreVendaCabDataEmissao: TDateField; SQLConfigFinanceiroCGFICINFPLCTBXSIMP: TStringField; SQLTeleEntregaTPVDICOD: TIntegerField; SQLTeleEntregaFUNCA13ID: TStringField; SQLTeleEntregaTELEA30OCASIAO: TStringField; SQLConfigTransportadora: TRxQuery; SQLConfigTransportadoraCFTROPFUICODCREDITO: TIntegerField; SQLConfigTransportadoraOPFUA60DESCRCREDITO: TStringField; SQLConfigTransportadoraCFTROPFUICODDEBITO: TIntegerField; SQLConfigTransportadoraOPFUA60DESCRDEBITO: TStringField; SQLConfigFinanceiroOPBCICODESTORNOCRD: TIntegerField; SQLConfigFinanceiroOPTEICODESTORNOCRD: TIntegerField; SQLConfigFinanceiroOPBCICODESTORNODEB: TIntegerField; SQLConfigFinanceiroOPTEICODESTORNODEB: TIntegerField; procedure DataModuleCreate(Sender: TObject); procedure SQLConfigContaBeforeEdit(DataSet: TDataSet); procedure SQLConfigContaBeforePost(DataSet: TDataSet); procedure SQLConfigContaNewRecord(DataSet: TDataSet); procedure SQLPlanodeContasBeforeInsert(DataSet: TDataSet); procedure SQLPlanodeContasBeforePost(DataSet: TDataSet); procedure SQLPlanodeContasNewRecord(DataSet: TDataSet); private { Private declarations } public { Public declarations } TemClienteDiferente : Boolean; GrupoAtual, SubGrupoAtual : Integer; end; var DM: TDM; implementation {$R *.DFM} procedure TDM.DataModuleCreate(Sender: TObject); begin inherited; SQLUsuarios.Open ; SQLConfigCrediario.Open ; SQLConfigGeral.Open ; SQLConta.Open ; SQLConfigConta.Open ; SQLPlanodeContas.Open ; SQLConfigFinanceiro.Open; SQLConfigVenda.Open; end; procedure TDM.SQLConfigContaBeforeEdit(DataSet: TDataSet); Var Existe:Boolean; begin SQLTemplate.SQL.Text:='Select Count(*) as CONTAS From PLANODECONTAS'; SQLTemplate.Open; Existe := SQLTemplate.FindField('CONTAS').asInteger > 0; SQLTemplate.Close; If Existe Then Begin ShowMessage('A estrutura do Plano de Contas não pode ser alterada se já existirem Contas!'); Abort; End; inherited; end; procedure TDM.SQLConfigContaBeforePost(DataSet: TDataSet); Var Soma,NumGraus,Teste,NivelGraus:Integer; Mascara:String; begin inherited; If DataSet.State = dsInsert Then Begin Soma:=SQLConfigContaCFGCINIVEL1.asInteger+ SQLConfigContaCFGCINIVEL2.asInteger+ SQLConfigContaCFGCINIVEL3.asInteger+ SQLConfigContaCFGCINIVEL4.asInteger+ SQLConfigContaCFGCINIVEL5.asInteger+ SQLConfigContaCFGCINIVEL6.asInteger+ SQLConfigContaCFGCINIVEL7.asInteger+ SQLConfigContaCFGCINIVEL8.asInteger+ SQLConfigContaCFGCINIVEL9.asInteger+ SQLConfigContaCFGCINIVEL10.AsInteger; If Soma>15 Then Begin Application.Messagebox('A soma dos Graus deve ser no máximo 15.','GVDASA Informa',MB_Ok+MB_IconInformation); SysUtils.Abort; End; Mascara:=''; For NumGraus:=1 to SQLConfigContaCFGCNIVEIS.asInteger Do Begin If (NumGraus>1) Then Mascara:=Mascara+'.'; Teste:=1; Teste:=SQLConfigConta.FieldByName('CFGCINIVEL'+IntToStr(NumGraus)).AsInteger; For NivelGraus:=1 to Teste Do Mascara:=Mascara+'_'; End; SQLConfigContaCFGCA30MASCARA.asString:=Mascara; End; DataSet.FindField('REGISTRO').AsDateTime := Now ; DataSet.FindField('PENDENTE').AsString := 'S' ; end; procedure TDM.SQLConfigContaNewRecord(DataSet: TDataSet); var I:Integer; begin inherited; DataSet.FieldByName('CFGCNIVEIS').Value:=1; for I:= 1 to 10 do DataSet.FieldByName('CFGCINIVEL'+IntToStr(I)).Value:=1; end; procedure TDM.SQLPlanodeContasBeforeInsert(DataSet: TDataSet); begin inherited; If DM.SQLPlanodeContas.Active Then DM.SQLPlanodeContas.Close; DM.SQLPlanodeContas.MacroByName('MFiltro').asString:=DM.SQLPlanodeContas.Fields[0].FieldName + ' IS NULL'; DM.SQLPlanodeContas.Open; end; procedure TDM.SQLPlanodeContasBeforePost(DataSet: TDataSet); begin inherited; DataSet.FindField('REGISTRO').AsDateTime := Now ; DataSet.FindField('PENDENTE').AsString := 'S' ; end; procedure TDM.SQLPlanodeContasNewRecord(DataSet: TDataSet); begin inherited; DataSet.FieldByName('PLCTCANALSINT').Value := 'S'; DataSet.FieldByName('PLCTCTIPOSALDO').Value := 'A'; end; end.
unit VirtualTreeviewSample.Templates; interface uses DSharp.Core.DataTemplates; type TFolderTemplate = class(TDataTemplate) public function GetItem(const Item: TObject; const Index: Integer): TObject; override; function GetItemCount(const Item: TObject): Integer; override; function GetText(const Item: TObject; const ColumnIndex: Integer): string; override; function GetTemplateDataClass: TClass; override; end; TFileTemplate = class(TDataTemplate) public function GetText(const Item: TObject; const ColumnIndex: Integer): string; override; function GetTemplateDataClass: TClass; override; end; implementation { TFolderTemplate } function TFolderTemplate.GetItem(const Item: TObject; const Index: Integer): TObject; begin Result := TFolder(Item).Files[Index]; end; function TFolderTemplate.GetItemCount(const Item: TObject): Integer; begin Result := TFolder(Item).Files.Count; // containing subfolders in that list as well end; function TFolderTemplate.GetTemplateDataClass: TClass; begin Result := TFolder; end; function TFolderTemplate.GetText(const Item: TObject; const ColumnIndex: Integer): string; begin case ColumnIndex of 0: Result := TFolder(Item).Name; end; end; { TFileTemplate } function TFileTemplate.GetTemplateDataClass: TClass; begin Result := TFile; end; function TFileTemplate.GetText(const Item: TObject; const ColumnIndex: Integer): string; begin case ColumnIndex of 0: Result := TFile(Item).Name; 1: Result := DateTimeToStr(TFile(Item).ChangeDate); 2: Result := IntToStr(TFile(Item).Size); end; end; end.
unit V_Historico_Produtos_03; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, Mask; type TVHistoricoProdutos03 = class(TForm) GroupBox1: TGroupBox; Label1: TLabel; Label2: TLabel; editCodigo: TEdit; editDescricao: TEdit; GroupBox2: TGroupBox; cbEstado: TComboBox; cbCidade: TComboBox; cbBairro: TComboBox; edtDataInicial: TMaskEdit; edtDataFinal: TMaskEdit; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; Panel1: TPanel; btnFiltrar: TBitBtn; btnSair: TBitBtn; Tipo_Historico: TEdit; Label8: TLabel; editReferencia: TEdit; procedure FormShow(Sender: TObject); procedure cbEstadoSelect(Sender: TObject); procedure btnSairClick(Sender: TObject); procedure cbCidadeSelect(Sender: TObject); procedure btnFiltrarClick(Sender: TObject); procedure edtDataInicialKeyPress(Sender: TObject; var Key: Char); procedure edtDataFinalKeyPress(Sender: TObject; var Key: Char); procedure cbEstadoKeyPress(Sender: TObject; var Key: Char); procedure cbCidadeKeyPress(Sender: TObject; var Key: Char); procedure cbBairroKeyPress(Sender: TObject; var Key: Char); private procedure Carrega_Combo_Estado(); procedure Carrega_Combo_Cidade(); procedure Carrega_Combo_Bairro(); { Private declarations } public { Public declarations } end; var VHistoricoProdutos03: TVHistoricoProdutos03; implementation uses Conexao_BD, Rotinas_Gerais, V_Historico_Produtos_01, V_Historico_Clientes_02, V_Historico_Clientes_03; {$R *.dfm} procedure TVHistoricoProdutos03.Carrega_Combo_Estado; var Comando_SQL: String; begin Ampulheta(); Comando_SQL := 'Select * from fb_clientes '; Comando_SQL := Comando_SQL + 'Group By fb_cliente_estado '; Comando_SQL := Comando_SQL + 'Order By fb_cliente_estado'; ConexaoBD.SQL_FB_Clientes.Close; ConexaoBD.SQL_FB_Clientes.SQL.Clear; ConexaoBD.SQL_FB_Clientes.SQL.Add(Comando_SQL); ConexaoBD.SQL_FB_Clientes.Open; cbEstado.Items.Clear; cbEstado.Items.Add('- Todos -'); While ConexaoBD.SQL_FB_Clientes.Eof = False Do Begin cbEstado.Items.Add(Trim(ConexaoBD.SQL_FB_Clientesfb_cliente_estado.Text)); ConexaoBD.SQL_FB_Clientes.Next; End; cbEstado.ItemIndex := 0; ConexaoBD.SQL_FB_Clientes.Close; Seta(); end; procedure TVHistoricoProdutos03.Carrega_Combo_Cidade; var Comando_SQL: String; begin Ampulheta(); If Trim(cbEstado.Text) <> '- Todos -' Then Begin Comando_SQL := 'Select * from fb_clientes '; Comando_SQL := Comando_SQL + 'Where fb_cliente_estado ='+#39+Trim(cbEstado.Text)+#39; Comando_SQL := Comando_SQL + 'Group By fb_cliente_cidade '; Comando_SQL := Comando_SQL + 'Order By fb_cliente_cidade'; ConexaoBD.SQL_FB_Clientes.Close; ConexaoBD.SQL_FB_Clientes.SQL.Clear; ConexaoBD.SQL_FB_Clientes.SQL.Add(Comando_SQL); ConexaoBD.SQL_FB_Clientes.Open; cbCidade.Items.Clear; cbCidade.Items.Add('- - - - - - - - - - Todas - - - - - - - - - -'); While ConexaoBD.SQL_FB_Clientes.Eof = False Do Begin cbCidade.Items.Add(Trim(ConexaoBD.SQL_FB_Clientesfb_cliente_cidade.Text)); ConexaoBD.SQL_FB_Clientes.Next; End; cbCidade.ItemIndex := 0; ConexaoBD.SQL_FB_Clientes.Close; End Else Begin cbCidade.Items.Clear; cbCidade.Items.Add('- - - - - - - - - - Todas - - - - - - - - - -'); cbCidade.ItemIndex := 0; End; Seta(); end; procedure TVHistoricoProdutos03.Carrega_Combo_Bairro; var Comando_SQL: String; begin Ampulheta(); If Trim(cbCidade.Text) <> '- - - - - - - - - - Todas - - - - - - - - - -' Then Begin Comando_SQL := 'Select * from fb_clientes '; Comando_SQL := Comando_SQL + 'Where (fb_cliente_estado ='+#39+Trim(cbEstado.Text)+#39+') '; Comando_SQL := Comando_SQL + 'And (fb_cliente_cidade ='+#39+Trim(cbCidade.Text)+#39+')'; Comando_SQL := Comando_SQL + 'Group By fb_cliente_bairro '; Comando_SQL := Comando_SQL + 'Order By fb_cliente_bairro'; ConexaoBD.SQL_FB_Clientes.Close; ConexaoBD.SQL_FB_Clientes.SQL.Clear; ConexaoBD.SQL_FB_Clientes.SQL.Add(Comando_SQL); ConexaoBD.SQL_FB_Clientes.Open; cbBairro.Items.Clear; cbBairro.Items.Add('- - - - - - - - - - Todos - - - - - - - - - -'); While ConexaoBD.SQL_FB_Clientes.Eof = False Do Begin cbBairro.Items.Add(Trim(ConexaoBD.SQL_FB_Clientesfb_cliente_bairro.Text)); ConexaoBD.SQL_FB_Clientes.Next; End; cbBairro.ItemIndex := 0; ConexaoBD.SQL_FB_Clientes.Close; End Else Begin cbBairro.Items.Clear; cbBairro.Items.Add('- - - - - - - - - - Todos - - - - - - - - - -'); cbBairro.ItemIndex := 0; End; Seta(); end; procedure TVHistoricoProdutos03.FormShow(Sender: TObject); begin edtDataInicial.Text := DateToStr(Date()); edtDataFinal.Text := DateToStr(Date()); Carrega_Combo_Estado(); end; procedure TVHistoricoProdutos03.cbEstadoSelect(Sender: TObject); begin Carrega_Combo_Cidade(); end; procedure TVHistoricoProdutos03.btnSairClick(Sender: TObject); begin VHistoricoProdutos03.Close; end; procedure TVHistoricoProdutos03.cbCidadeSelect(Sender: TObject); begin Carrega_Combo_Bairro(); end; procedure TVHistoricoProdutos03.btnFiltrarClick(Sender: TObject); begin IF Trim(edtDataInicial.Text) = '/ /' Then Begin MSG_Erro('Antes de proseguir preencha os campos de período...'); edtDataInicial.SetFocus; End Else IF Trim(edtDataFinal.Text) = '/ /' Then Begin MSG_Erro('Antes de proseguir preencha os campos de período...'); edtDataFinal.SetFocus; End Else IF StrToDate(edtDataFinal.Text) < StrToDate(edtDataInicial.Text) Then Begin MSG_Erro('A data de início do Período não pode ser '+#13+'maior que a data de termino.'); edtDataInicial.SetFocus; End Else Begin If Trim(Tipo_Historico.Text) = 'Historico_Produtos' Then Begin Application.CreateForm(TVHistoricoProdutos01,VHistoricoProdutos01); VHistoricoProdutos01.editReferencia.Text := Trim(editReferencia.Text); VHistoricoProdutos01.editCodigo.Text := Trim(editCodigo.Text); VHistoricoProdutos01.editDescricao.Text := Trim(editDescricao.Text); VHistoricoProdutos01.edtDataInicial.Text := Trim(edtDataInicial.Text); VHistoricoProdutos01.edtDataFinal.Text := Trim(edtDataFinal.Text); VHistoricoProdutos01.edtEstado.Text := Trim(cbEstado.Text); VHistoricoProdutos01.edtCidade.Text := Trim(cbCidade.Text); VHistoricoProdutos01.edtBairro.Text := Trim(cbBairro.Text); VHistoricoProdutos01.ShowModal; VHistoricoProdutos01.Destroy; End Else Begin Application.CreateForm(TVHistoricoClientes03,VHistoricoClientes03); VHistoricoClientes03.editReferencia.Text := Trim(editReferencia.Text); VHistoricoClientes03.editCodigo.Text := Trim(editCodigo.Text); VHistoricoClientes03.editDescricao.Text := Trim(editDescricao.Text); VHistoricoClientes03.edtDataInicial.Text := Trim(edtDataInicial.Text); VHistoricoClientes03.edtDataFinal.Text := Trim(edtDataFinal.Text); VHistoricoClientes03.edtEstado.Text := Trim(cbEstado.Text); VHistoricoClientes03.edtCidade.Text := Trim(cbCidade.Text); VHistoricoClientes03.edtBairro.Text := Trim(cbBairro.Text); VHistoricoClientes03.ShowModal; VHistoricoClientes03.Destroy; End; End; end; procedure TVHistoricoProdutos03.edtDataInicialKeyPress(Sender: TObject; var Key: Char); begin If Key = #13 Then Begin Key := #0; Perform(WM_NEXTDLGCTL, 0, 0); End; end; procedure TVHistoricoProdutos03.edtDataFinalKeyPress(Sender: TObject; var Key: Char); begin If Key = #13 Then Begin Key := #0; Perform(WM_NEXTDLGCTL, 0, 0); End; end; procedure TVHistoricoProdutos03.cbEstadoKeyPress(Sender: TObject; var Key: Char); begin If Key = #13 Then Begin Key := #0; Perform(WM_NEXTDLGCTL, 0, 0); End; end; procedure TVHistoricoProdutos03.cbCidadeKeyPress(Sender: TObject; var Key: Char); begin If Key = #13 Then Begin Key := #0; Perform(WM_NEXTDLGCTL, 0, 0); End; end; procedure TVHistoricoProdutos03.cbBairroKeyPress(Sender: TObject; var Key: Char); begin If Key = #13 Then Begin Key := #0; Perform(WM_NEXTDLGCTL, 0, 0); End; end; end.
(***************************************************************************) (* *) (* AtomTape v1.1 (c) by Wouter Ras, Delft, November - December 1997 *) (* ---------------------------------------------------------------- *) (* *) (* This source code may be distributed freely within the following *) (* restrictions *) (* 1. You may not charge for this program or for any part of it. *) (* 2. This copyright message may not be removed from it. *) (* 3. You may use sections of code from this program in your applications, *) (* but you must acknowledge its use. I'd appreciate it if you'd let me *) (* know, i.e. send me a copy of your work. *) (* *) (* Please report any problems, questions, comments to me at this address: *) (* avio@casema.net *) (* *) (* The latest version of the emulator can be downloaded from my Atom-page: *) (* http://www.casema.net/~avio/atom.htm *) (* *) (***************************************************************************) {$r-} PROGRAM ATOMTAPE; USES CRT,HEXA; CONST SILENCE = $80; SILENCEMIN = $7C; SILENCEMAX = $84; MAXWAVE1 = +12; MINWAVE0 = +16; MAXWAVE0 = +24; VOCHEADER : ARRAY[$00..$13] OF CHAR = 'Creative Voice File'+#$1a; TYPE TAPESPEEDTYPE = (SCOS,FCOS); BUFTYPE = ARRAY[$0000..$FFF8] OF BYTE; ATMHEADERREC = RECORD ATOMNAME : ARRAY[$00..$0F] OF BYTE; STARTADDRESS : WORD; EXECADDRESS : WORD; DATASIZE : WORD; END; VAR TAPESPEED : TAPESPEEDTYPE; HEADER : ARRAY[$00..$FF] OF BYTE; READBUF : ^BUFTYPE; WRITEBUF : ^BUFTYPE; SOURCEFILE : STRING; DESTFILE : STRING; FROMF : FILE; TOF : FILE; NOMOREDATA : BOOLEAN; P1 : LONGINT; P2 : LONGINT; ABSRP : LONGINT; RELRP : WORD; RP : WORD; WP : WORD; HP : BYTE; NR : WORD; LASTBLOCK : BOOLEAN; ATMHEADER : ATMHEADERREC; FIRSTWAVEDOWN: BOOLEAN; PROCEDURE TERMINATE; VAR CH:CHAR; BEGIN CLOSE (FROMF); CLOSE (TOF); ERASE (TOF); WRITELN ('Program aborted.'); WHILE KEYPRESSED DO CH := READKEY; HALT; END; PROCEDURE GETBYTE (VAR B:BYTE); BEGIN IF NOMOREDATA THEN EXIT; B := READBUF^[RP]; INC (RP); IF RP >= NR THEN BEGIN INC (ABSRP,RP); BLOCKREAD (FROMF,READBUF^,SIZEOF(BUFTYPE),NR); IF NR=0 THEN NOMOREDATA := TRUE; RP := $0000; END; END; PROCEDURE STOREBYTE (B:BYTE); VAR I:BYTE; W:WORD; BEGIN WRITEBUF^[WP] := B; INC (WP); IF WP >= SIZEOF(BUFTYPE) THEN BEGIN BLOCKWRITE (TOF,WRITEBUF^,WP); INC (ATMHEADER.DATASIZE,WP); WP := $0000; END; END; PROCEDURE SETSTART; VAR B:BYTE; BEGIN IF FIRSTWAVEDOWN THEN BEGIN REPEAT GETBYTE (B); IF NOMOREDATA THEN EXIT; UNTIL B > SILENCEMAX; REPEAT GETBYTE (B); IF NOMOREDATA THEN EXIT; UNTIL B < SILENCE; END ELSE BEGIN REPEAT GETBYTE (B); IF NOMOREDATA THEN EXIT; UNTIL B < SILENCEMIN; REPEAT GETBYTE (B); IF NOMOREDATA THEN EXIT; UNTIL B > SILENCE; END; END; PROCEDURE SEEKENDOFWAVE; VAR B:BYTE; BEGIN IF FIRSTWAVEDOWN THEN BEGIN REPEAT GETBYTE (B); IF NOMOREDATA THEN EXIT; UNTIL B > SILENCE; REPEAT GETBYTE (B); IF NOMOREDATA THEN EXIT; UNTIL B < SILENCE; END ELSE BEGIN REPEAT GETBYTE (B); IF NOMOREDATA THEN EXIT; UNTIL B < SILENCE; REPEAT GETBYTE (B); IF NOMOREDATA THEN EXIT; UNTIL B > SILENCE; END; END; PROCEDURE READONEBYTEFROMVOC (FIRSTWAVEDONE:BOOLEAN; VAR B:BYTE); VAR DATABITS:ARRAY[0..9] OF BYTE; S:STRING[16]; I:BYTE; A:BYTE; BEGIN I := 0; DATABITS[0] := 0; S := ''; IF TAPESPEED = SCOS THEN BEGIN IF FIRSTWAVEDONE THEN S := '00'; END ELSE BEGIN IF FIRSTWAVEDONE THEN I := 1; END; WHILE I <= 9 DO BEGIN P1 := P2; SEEKENDOFWAVE; IF NOMOREDATA THEN EXIT; P2 := ABSRP + LONGINT(RP); IF P2-P1 <= MAXWAVE1 THEN BEGIN S := S + '1'; END ELSE IF P2-P1 >= MINWAVE0 THEN BEGIN S := S + '00'; END ELSE BEGIN GOTOXY (1,WHEREY); WRITELN ('Error: Misformed wave pattern at position ',HEXL(P1),'h.'); TERMINATE; END; IF ((TAPESPEED = FCOS) AND (S='00')) OR ((TAPESPEED = SCOS) AND (S='00000000')) THEN BEGIN DATABITS[I] := 0; INC (I); S := ''; END ELSE IF ((TAPESPEED = FCOS) AND (S='11')) OR ((TAPESPEED = SCOS) AND (S='11111111')) THEN BEGIN DATABITS[I] := 1; INC (I); S := ''; END; IF ((TAPESPEED = FCOS) AND (LENGTH(S) > 2)) OR ((TAPESPEED = SCOS) AND (LENGTH(S) > 8)) THEN BEGIN GOTOXY (1,WHEREY); WRITELN ('Error: Misformed wave pattern at position ',HEXL(P1),'h.'); TERMINATE; END; END; P1 := P2; SEEKENDOFWAVE; {---stopbit always has one extra wave---} IF NOMOREDATA THEN EXIT; P2 := ABSRP + LONGINT(RP); IF DATABITS[0] <> $00 THEN BEGIN GOTOXY (1,WHEREY); WRITELN ('Error: No startbit (0) found at position ',HEXL(P1),'h.'); TERMINATE; END; IF DATABITS[9] <> $01 THEN BEGIN GOTOXY (1,WHEREY); WRITELN ('Error: No stopbit (1) found at position ',HEXL(P1),'h.'); TERMINATE; END; B := $00; A := $01; FOR I := 1 TO 8 DO BEGIN IF DATABITS[I] <> $00 THEN B := B OR A; A := (A SHL 1) AND $FF; END; IF KEYPRESSED THEN BEGIN GOTOXY (1,WHEREY); CLREOL; WRITELN ('User break.'); TERMINATE; END; END; PROCEDURE INPUTSTRING (LENGTE:BYTE;VAR S:STRING); LABEL 1; VAR CH,DH:CHAR; N,P:BYTE; XC,YC:BYTE; T:STRING; BEGIN T := ''; 1:S := T; XC := WHEREX; YC := WHEREY; P := SUCC(LENGTH(S)); REPEAT WHILE LENGTH(S) < LENGTE DO S := S + '_'; INLINE ($B8/$00/$01/$B9/$07/$26/$CD/$10); {---hidecursor---} GOTOXY (XC,YC); WRITE (S); GOTOXY (XC+PRED(P),YC); INLINE ($B8/$00/$01/$B9/$06/$05/$CD/$10); {---showcursor---} CH := READKEY; IF CH=#0 THEN BEGIN DH := READKEY; IF (DH=#75) AND (P>1) THEN DEC(P); IF (DH=#77) AND (P<=LENGTE) THEN INC(P); IF (DH=#83) AND (P<=LENGTE) THEN BEGIN DELETE (S,P,1); S := S + '_'; END; IF (DH=#$75) AND (P<=LENGTE) THEN BEGIN FOR N := P TO LENGTE DO S[N] := '_'; END; IF DH=#$47 THEN P := 1; IF DH=#$4F THEN BEGIN P := SUCC(LENGTE); WHILE S[PRED(P)]='_' DO DEC(P); END; END; IF (CH=#8) AND (P>1) THEN BEGIN DELETE (S,PRED(P),1); S := S + '_'; DEC(P); END; IF (CH>=' ') AND (P<=LENGTE) Then BEGIN DELETE (S,LENGTH(S),1); INSERT (CH,S,P); INC (P); END; IF CH=#27 THEN BEGIN WRITELN; WRITELN; WRITELN ('User break.'); HALT; END; UNTIL (CH=#13); WHILE S[LENGTH(S)] = '_' DO DELETE (S,LENGTH(S),1); IF S='' THEN GOTO 1; GOTOXY (XC,YC); WRITE (S); CLREOL; END; PROCEDURE CREATETEMPFILE; LABEL 1; VAR TOF:FILE; BLOCKSIZE:LONGINT; BLOCK01POS:LONGINT; TOTALSIZE:LONGINT; AANTAL:WORD; BEGIN WRITE ('File consists of more than one datablocks. Restructuring file...'); SEEK (FROMF,0); ASSIGN (TOF,'$ATMTEMP.TMP'); REWRITE (TOF,1); {---header---} BLOCKREAD (FROMF,READBUF^,$1A,NR); BLOCKWRITE (TOF,READBUF^,$1A); {---data (including block 8)---} BLOCKREAD (FROMF,READBUF^,$04,NR); WHILE (READBUF^[$00] > $02) AND (READBUF^[$00] <> $08) DO BEGIN BLOCKSIZE := LONGINT(READBUF^[$01]) + (LONGINT(READBUF^[$02]) SHL 8) + (LONGINT(READBUF^[$03]) SHL 16); SEEK (FROMF,FILEPOS(FROMF)+BLOCKSIZE); BLOCKREAD (FROMF,READBUF^,$04,NR); END; IF READBUF^[$00] = $08 THEN BEGIN BLOCKWRITE (TOF,READBUF^,$04); BLOCKSIZE := LONGINT(READBUF^[$01]) + (LONGINT(READBUF^[$02]) SHL 8) + (LONGINT(READBUF^[$03]) SHL 16); BLOCKREAD (FROMF,READBUF^,BLOCKSIZE,NR); BLOCKWRITE (TOF,READBUF^,NR); BLOCKREAD (FROMF,READBUF^,$04,NR); END; IF READBUF^[$00] = $01 THEN BEGIN BLOCK01POS := FILESIZE(TOF); TOTALSIZE := $02; BLOCKWRITE (TOF,READBUF^,$04); BLOCKSIZE := LONGINT(READBUF^[$01]) + (LONGINT(READBUF^[$02]) SHL 8) + (LONGINT(READBUF^[$03]) SHL 16); BLOCKREAD (FROMF,READBUF^,$02,NR); BLOCKWRITE (TOF,READBUF^,$02); DEC (BLOCKSIZE,$02); END ELSE BEGIN CLOSE (FROMF); CLOSE (TOF); ERASE (TOF); WRITELN ('Error: No information about samplerate etc. encountered.'); HALT; END; {---rest of data; block 8 ignored---} 1:WHILE BLOCKSIZE > 0 DO BEGIN AANTAL := SIZEOF(BUFTYPE); IF AANTAL > BLOCKSIZE THEN AANTAL := BLOCKSIZE; INC (TOTALSIZE,AANTAL); BLOCKREAD (FROMF,READBUF^,AANTAL,NR); BLOCKWRITE (TOF,READBUF^,NR); DEC (BLOCKSIZE,NR); END; BLOCKREAD (FROMF,READBUF^,$04,NR); IF READBUF^[$00] = $01 THEN BEGIN BLOCKSIZE := LONGINT(READBUF^[$01]) + (LONGINT(READBUF^[$02]) SHL 8) + (LONGINT(READBUF^[$03]) SHL 16); SEEK (FROMF,FILEPOS(FROMF)+$02); DEC (BLOCKSIZE,$02); END; IF READBUF^[$00] = $02 THEN BEGIN BLOCKSIZE := LONGINT(READBUF^[$01]) + (LONGINT(READBUF^[$02]) SHL 8) + (LONGINT(READBUF^[$03]) SHL 16); END; IF READBUF^[$00] <> $00 THEN GOTO 1; BLOCKWRITE (TOF,READBUF^,$01); SEEK (TOF,SUCC(BLOCK01POS)); BLOCKWRITE (TOF,TOTALSIZE,$03); CLOSE (FROMF); CLOSE (TOF); ERASE (FROMF); RENAME (TOF,SOURCEFILE); WRITELN; ASSIGN (FROMF,SOURCEFILE); RESET (FROMF,1); END; {===[main]==================================================================} LABEL 1,2,3; VAR CH : CHAR; DH : CHAR; W : WORD; B : BYTE; I : BYTE; CHKSUM : BYTE; EERSTE : BOOLEAN; NUMBYTES : WORD; SR : WORD; BLOCKSIZE : LONGINT; BEGIN GETMEM (READBUF,SIZEOF(BUFTYPE)); GETMEM (WRITEBUF,SIZEOF(BUFTYPE)); CLRSCR; WRITELN ('AtomTape v1.1 (c) Wouter Ras, Delft, November-December 1997'); WRITELN; WRITELN; WRITE ('Name of VOC-file (without extension) ? '); INPUTSTRING (30,SOURCEFILE); FOR I := 1 TO LENGTH(SOURCEFILE) DO SOURCEFILE[I] := UPCASE(SOURCEFILE[I]); DESTFILE := SOURCEFILE + '.ATM'; SOURCEFILE := SOURCEFILE + '.VOC'; WRITELN; WRITELN; ASSIGN (FROMF,SOURCEFILE); {$i-} RESET (FROMF,1); {$i+} IF IORESULT <> 0 THEN BEGIN WRITELN ('Source file (',SOURCEFILE,') not found.'); HALT; END; WRITE ('Is it a 300 bps (slow) or 1200 bps (fast) file [S/F] ? F',#8); WHILE KEYPRESSED DO CH := READKEY; REPEAT CH := UPCASE(READKEY); IF CH=#0 THEN DH := READKEY; IF CH=#27 THEN BEGIN WRITELN; WRITELN; WRITELN ('User break.'); CLOSE (FROMF); HALT; END; IF CH=#13 THEN CH := 'F'; UNTIL (CH='F') OR (CH='S'); WRITELN (CH); WRITELN; WRITELN; IF CH='S' THEN TAPESPEED := SCOS ELSE TAPESPEED := FCOS; FOR I := $00 TO $0F DO ATMHEADER.ATOMNAME[I] := $00; ATMHEADER.DATASIZE := 0; 3:BLOCKREAD (FROMF,READBUF^,SIZEOF(BUFTYPE),NR); FOR I := $00 TO $13 DO BEGIN IF READBUF^[I] <> ORD(VOCHEADER[I]) THEN BEGIN WRITELN ('This is not a valid VOC-file.'); CLOSE (FROMF); HALT; END; END; RP := $001A; WHILE (READBUF^[RP] <> $01) AND (READBUF^[RP] <> $08) DO BEGIN IF READBUF^[RP] = $02 THEN BEGIN WRITELN ('No information about samplerate etc. encountered.'); CLOSE (FROMF); HALT; END; IF (READBUF^[RP] >= $03) AND (READBUF^[RP] <=07) THEN BEGIN BLOCKSIZE := LONGINT(READBUF^[RP+$01]) + (LONGINT(READBUF^[RP+$02]) SHL 8) + (LONGINT(READBUF^[RP+$03]) SHL 16); INC (RP,BLOCKSIZE+$04); END; END; IF READBUF^[RP] = $08 THEN BEGIN SR := READBUF^[RP+$04] + SWAP(WORD(READBUF^[RP+$05])); IF (SR < $D2A7-$80) OR (SR > $D2A7+$80) THEN BEGIN WRITELN ('Wrong samplerate. It should be 22050 Hz.'); CLOSE (FROMF); HALT; END; IF (READBUF^[RP+$06] <> $00) OR (READBUF^[RP+$07] <> $00) THEN BEGIN WRITELN ('File must be 8-bits sample mono recorded.'); CLOSE (FROMF); HALT; END; RP := $0022; BLOCKSIZE := LONGINT(READBUF^[RP+$01]) + (LONGINT(READBUF^[RP+$02]) SHL 8) + (LONGINT(READBUF^[RP+$03]) SHL 16); IF BLOCKSIZE <> FILESIZE(FROMF)-(RP+$04)-$01 THEN BEGIN CREATETEMPFILE; GOTO 3; END; RP := $0028; END ELSE BEGIN IF READBUF^[RP] = $01 THEN BEGIN BLOCKSIZE := LONGINT(READBUF^[RP+$01]) + (LONGINT(READBUF^[RP+$02]) SHL 8) + (LONGINT(READBUF^[RP+$03]) SHL 16); IF BLOCKSIZE <> FILESIZE(FROMF)-(RP+$04)-$01 THEN BEGIN CREATETEMPFILE; GOTO 3; END; IF (READBUF^[RP+$04] < $D2) OR (READBUF^[RP+$04] > $D3) THEN BEGIN WRITELN ('Wrong samplerate. It should be 22050 Hz.'); CLOSE (FROMF); HALT; END; IF READBUF^[RP+$05] <> $00 THEN BEGIN WRITELN ('File must be 8-bits sample mono recorded.'); CLOSE (FROMF); HALT; END; RP := $0020; END ELSE BEGIN WRITELN ('Unrecognised VOC-block. Only blocktypes 1 and 8 are allowed.'); CLOSE (FROMF); HALT; END; END; ABSRP := RP; NOMOREDATA := FALSE; ASSIGN (TOF,DESTFILE); REWRITE (TOF,1); BLOCKWRITE (TOF,ATMHEADER,SIZEOF(ATMHEADER)); WP := $0000; WRITELN ('Analyzing VOC-file:'); WRITELN; WRITELN ('Atom filename Strt End Exec Nr'); WRITELN ('--------------- ---- ---- ---- --'); 2:FIRSTWAVEDOWN := TRUE; {---searching for header---} WRITE ('Searching header...'); SETSTART; IF NOMOREDATA THEN GOTO 1; P2 := ABSRP + LONGINT(RP); REPEAT P1 := P2; SEEKENDOFWAVE; IF NOMOREDATA THEN GOTO 1; P2 := ABSRP + LONGINT(RP); UNTIL (P2-P1 > MAXWAVE1) AND (P2-P1 <= MAXWAVE0); IF P2-P1 < MINWAVE0 THEN {swap wavestart} BEGIN FIRSTWAVEDOWN := FALSE; SEEKENDOFWAVE; IF NOMOREDATA THEN GOTO 1; P2 := ABSRP + LONGINT(RP); END; {---read header---} GOTOXY (1,WHEREY); WRITE ('Reading header...'); CLREOL; HP := 0; EERSTE := TRUE; CHKSUM := 0; REPEAT INC(MEM[$B800:2*80*25]); READONEBYTEFROMVOC (EERSTE,B); EERSTE := FALSE; IF NOMOREDATA THEN GOTO 1; HEADER[HP] := B; CHKSUM := LO(CHKSUM + B); INC (HP); UNTIL (HP >= $0D) AND (HEADER[HP-$09] = $0D); GOTOXY (1,WHEREY); IF (HEADER[$00] <> ORD('*')) OR (HEADER[$01] <> ORD('*')) OR (HEADER[$02] <> ORD('*')) OR (HEADER[$03] <> ORD('*')) THEN BEGIN WRITELN ('Error: Blockheader corrupted.'); TERMINATE; END; I := $04; WHILE HEADER[I] <> $0D DO BEGIN WRITE (CHR(HEADER[I])); ATMHEADER.ATOMNAME[I-$04] := HEADER[I]; INC (I); END; INC (I); WHILE WHEREX < 17 DO WRITE (' '); W := HEADER[I+$07] + (WORD(HEADER[I+$06]) SHL 8); IF HEADER[I+$02] = $00 THEN ATMHEADER.STARTADDRESS := W; WRITE (HEXW(W),' '); NUMBYTES := SUCC(WORD(HEADER[I+$03])); INC (W,PRED(NUMBYTES)); WRITE (HEXW(W),' '); W := HEADER[I+$05] + (WORD(HEADER[I+$04]) SHL 8); IF HEADER[I+$02] = $00 THEN ATMHEADER.EXECADDRESS := W; WRITE (HEXW(W),' '); W := HEADER[I+$02]; WRITELN (HEX(W)); W := HEADER[I]; IF W AND $80 = $00 THEN LASTBLOCK := TRUE ELSE LASTBLOCK := FALSE; {---searching datablock---} WRITE ('Searching datablock...'); REPEAT P1 := P2; SEEKENDOFWAVE; IF NOMOREDATA THEN EXIT; P2 := ABSRP + LONGINT(RP); UNTIL P2-P1 <= MAXWAVE1; REPEAT P1 := P2; SEEKENDOFWAVE; IF NOMOREDATA THEN EXIT; P2 := ABSRP + LONGINT(RP); UNTIL (P2-P1 > MAXWAVE1) AND (P2-P1 <= MAXWAVE0); {---read datablock---} GOTOXY (1,WHEREY); WRITE ('Reading datablock...'); CLREOL; EERSTE := TRUE; FOR W := 1 TO NUMBYTES DO BEGIN INC(MEM[$B800:2*80*25]); READONEBYTEFROMVOC (EERSTE,B); EERSTE := FALSE; IF NOMOREDATA THEN GOTO 1; STOREBYTE (B); CHKSUM := LO(CHKSUM + B); END; READONEBYTEFROMVOC (FALSE,B); {---checksum---} GOTOXY (1,WHEREY); CLREOL; IF B <> CHKSUM THEN BEGIN WRITELN ('Checksum error: ',HEX(CHKSUM),'h should be ',HEX(B),'h.'); TERMINATE; END; IF NOT LASTBLOCK THEN GOTO 2; 1:BLOCKWRITE (TOF,WRITEBUF^,WP); INC (ATMHEADER.DATASIZE,WP); CLOSE (FROMF); CLOSE (TOF); RESET (TOF,1); BLOCKWRITE (TOF,ATMHEADER,SIZEOF(ATMHEADER)); CLOSE (TOF); WHILE KEYPRESSED DO CH := READKEY; IF NOT LASTBLOCK THEN BEGIN GOTOXY (1,WHEREY); WRITELN ('Alert: File might be incomplete.'); END ELSE BEGIN WRITELN ('Ready.'); END; END.
unit WiRL.Tests.Framework.ContentNegotiation; interface uses System.SysUtils, DUnitX.TestFramework, WiRL.Core.Application, WiRL.Core.Attributes, WiRL.Core.Resource, WiRL.Core.Registry, WiRL.Core.Engine, WiRL.Core.Context, WiRL.http.Server, WiRL.http.Response, WiRL.http.Request, WiRL.http.Accept.MediaType, WiRL.Tests.Mock.MessageBodyXML, WiRL.Tests.Mock.Server; type [TestFixture] TTestContentNegotiation = class(TObject) private FServer: TWiRLServer; FRequest: TWiRLTestRequest; FResponse: TWiRLTestResponse; public [Setup] procedure Setup; [TearDown] procedure TearDown; [Test] procedure TestMainWithoutAccept; [Test] procedure TestMainWithAccept; [Test] procedure TestMainWithAcceptFail; [Test] procedure TestSimpleObjectJson; [Test] procedure TestSimpleObjectXml; [Test] procedure TestSimpleObjectFixedXml; [Test] procedure TestTextPlainWithCharset; [Test] procedure TestTextPlainWithoutCharset; end; TSimpleObject = class Value: Integer; end; [Path('/coneg')] TContentNegotiationResource = class private [CONTEXT] FResponse: TWiRLResponse; public [GET] [Produces(TMediaType.TEXT_PLAIN + TMediaType.WITH_CHARSET_UTF8)] function TextPlainUTF8(): string; [GET] [Produces(TMediaType.APPLICATION_XML)] [Produces(TMediaType.APPLICATION_JSON)] function GetObject(): TSimpleObject; [GET] [Path('/xml')] [Produces(TMediaType.APPLICATION_XML)] function GetObjectXml(): TSimpleObject; [GET] [Path('/text-nocharset')] [Produces(TMediaType.TEXT_PLAIN)] function TextPlain(): string; end; implementation { TTestContentNegotiation } procedure TTestContentNegotiation.Setup; begin FServer := TWiRLServer.Create(nil); // Engine configuration FServer.AddEngine<TWiRLEngine>('/rest') .SetEngineName('WiRL Test Demo') .AddApplication('/app') .SetSystemApp(True) .SetAppName('Test Application') .SetResources(['*']) .SetFilters(['*']); if not FServer.Active then FServer.Active := True; FRequest := TWiRLTestRequest.Create; FResponse := TWiRLTestResponse.Create; end; procedure TTestContentNegotiation.TearDown; begin FServer.Free; FRequest.Free; FResponse.Free; end; procedure TTestContentNegotiation.TestMainWithAccept; begin FRequest.Method := 'GET'; FRequest.Url := 'http://localhost:1234/rest/app/coneg'; FRequest.Accept := TMediaType.TEXT_PLAIN + TMediaType.WITH_CHARSET_UTF8; FServer.HandleRequest(FRequest, FResponse); Assert.AreEqual(200, FResponse.StatusCode); Assert.AreEqual(TMediaType.TEXT_PLAIN + TMediaType.WITH_CHARSET_UTF8, FResponse.ContentType); end; procedure TTestContentNegotiation.TestMainWithAcceptFail; begin FRequest.Method := 'GET'; FRequest.Url := 'http://localhost:1234/rest/app/coneg'; FRequest.Accept := TMediaType.TEXT_CSV; FServer.HandleRequest(FRequest, FResponse); Assert.AreEqual(404, FResponse.StatusCode); end; procedure TTestContentNegotiation.TestMainWithoutAccept; begin FRequest.Method := 'GET'; FRequest.Url := 'http://localhost:1234/rest/app/coneg'; FServer.HandleRequest(FRequest, FResponse); Assert.AreEqual(200, FResponse.StatusCode); Assert.AreEqual('ciaoà€', FResponse.Content); Assert.AreEqual(TMediaType.TEXT_PLAIN + TMediaType.WITH_CHARSET_UTF8, FResponse.ContentType); Assert.AreEqual('TextPlainUTF8', FResponse.HeaderFields['X-Resource-Name']); end; procedure TTestContentNegotiation.TestSimpleObjectFixedXml; begin FRequest.Method := 'GET'; FRequest.Url := 'http://localhost:1234/rest/app/coneg/xml'; //FRequest.Accept := TMediaType.TEXT_XML; FServer.HandleRequest(FRequest, FResponse); Assert.AreEqual(200, FResponse.StatusCode); Assert.AreEqual('GetObjectXml', FResponse.HeaderFields['X-Resource-Name']); Assert.AreEqual(TMediaType.APPLICATION_XML, FResponse.ContentType); end; procedure TTestContentNegotiation.TestSimpleObjectJson; begin FRequest.Method := 'GET'; FRequest.Url := 'http://localhost:1234/rest/app/coneg'; FRequest.Accept := TMediaType.APPLICATION_JSON; FServer.HandleRequest(FRequest, FResponse); Assert.AreEqual(200, FResponse.StatusCode); Assert.AreEqual(TMediaType.APPLICATION_JSON, FResponse.ContentType); end; procedure TTestContentNegotiation.TestSimpleObjectXml; begin FRequest.Method := 'GET'; FRequest.Url := 'http://localhost:1234/rest/app/coneg'; FRequest.Accept := TMediaType.APPLICATION_XML; FServer.HandleRequest(FRequest, FResponse); Assert.AreEqual(200, FResponse.StatusCode); Assert.AreEqual(TMediaType.APPLICATION_XML, FResponse.ContentType); end; procedure TTestContentNegotiation.TestTextPlainWithCharset; begin FRequest.Method := 'GET'; FRequest.Url := 'http://localhost:1234/rest/app/coneg'; FRequest.Accept := TMediaType.TEXT_PLAIN; FServer.HandleRequest(FRequest, FResponse); Assert.AreEqual(200, FResponse.StatusCode); Assert.AreEqual(TMediaType.TEXT_PLAIN + TMediaType.WITH_CHARSET_UTF8, FResponse.ContentType); end; procedure TTestContentNegotiation.TestTextPlainWithoutCharset; begin FRequest.Method := 'GET'; FRequest.Url := 'http://localhost:1234/rest/app/coneg/text-nocharset'; FRequest.Accept := TMediaType.TEXT_PLAIN; FServer.HandleRequest(FRequest, FResponse); Assert.AreEqual(200, FResponse.StatusCode); Assert.AreEqual(TMediaType.TEXT_PLAIN, FResponse.ContentType); Assert.AreEqual('TextPlain', FResponse.HeaderFields['X-Resource-Name']); // Warning: if you doesn't specify the content type with the // "Produces" attribute the default is ANSI. Assert.AreEqual('ciaoù', TEncoding.ANSI.GetString(FResponse.RawContent)); end; { TContentNegotiationResource } function TContentNegotiationResource.GetObject: TSimpleObject; begin FResponse.HeaderFields['X-Resource-Name'] := 'GetObject'; Result := TSimpleObject.Create; Result.Value := 12; end; function TContentNegotiationResource.GetObjectXml: TSimpleObject; begin FResponse.HeaderFields['X-Resource-Name'] := 'GetObjectXml'; Result := TSimpleObject.Create; Result.Value := 12; end; function TContentNegotiationResource.TextPlain: string; begin FResponse.HeaderFields['X-Resource-Name'] := 'TextPlain'; Result := 'ciaoù'; end; function TContentNegotiationResource.TextPlainUTF8: string; begin FResponse.HeaderFields['X-Resource-Name'] := 'TextPlainUTF8'; Result := 'ciaoà€'; end; initialization TDUnitX.RegisterTestFixture(TTestContentNegotiation); TWiRLResourceRegistry.Instance.RegisterResource<TContentNegotiationResource>; end.
unit uF3_startSimulasi; interface uses uP1_tipeBentukan, uP2_pesan, uF4_stopSimulasi, uF5_beliBahan, uF6_OlahBahan, uF7_jualOlahan, uF8_jualResep, uF9_makan, uF10_istirahat, uF11_tidur, uF12_lihatStatistik, uF13_lihatInventori, uF14_lihatResep, uF15_cariResep, uF16_tambahResep, uF17_upgradeInventori; procedure mainStartSimulasi(ID : integer; var dataBahanMentah : tabelBahanMentah; var dataBahanOlahan : tabelBahanOlahan; var dataResep : tabelResep; var dataSimulasi : tabelSimulasi; var dataInventoriBahanMentah: tabelBahanMentah; var dataInventoriBahanOlahan: tabelBahanOlahan); {memberikan prompt kepada user untuk memasukkan perintah dan melaksanakan perintah tersebut} function lelah(dataSimulasi : tabelSimulasi; ID : integer):boolean; {memberikan nilai true dan sebuah pesan kesalahan apabila dataSimulasi.itemKe[ID].jumlahEnergi <=0} procedure hapusKosong(var BM : tabelBahanMentah;var BO : tabelBahanOlahan); {Menghapus bahan mentah dan olahan yang habis} implementation procedure mainStartSimulasi(ID : integer; var dataBahanMentah : tabelBahanMentah; var dataBahanOlahan : tabelBahanOlahan; var dataResep : tabelResep; var dataSimulasi : tabelSimulasi; var dataInventoriBahanMentah: tabelBahanMentah; var dataInventoriBahanOlahan: tabelBahanOlahan); {memberikan prompt kepada user untuk memasukkan perintah dan melaksanakan perintah tersebut} {KAMUS LOKAL} var stopSimulasi: boolean; perintah : string; jmlMakan : integer; jmlIstirahat: integer; bahanYangDibeli : string; kuantitasBahanYangDibeli : integer; {ALGORITMA LOKAL} begin dataSimulasi.itemKe[ID].jumlahEnergi := 10; dataSimulasi.itemKe[ID].jumlahHariHidup := 1; dataSimulasi.itemKe[ID].jumlahDuit := 100000; dataInventoriBahanOlahan.banyakItem := 0; jmlMakan := 0; jmlIstirahat := 0; tampilkanMenu('startSimulasi'); repeat {inisialisasi} stopSimulasi := false; dataSimulasi.itemKe[ID].isTidur := false; {antarmuka} writeln('--------------------------------------------------'); writeln('Selamat pagi!, hari ini tanggal: ',dataSimulasi.itemKe[ID].tanggalSimulasi.hari,'/',dataSimulasi.itemKe[ID].tanggalSimulasi.bulan,'/',dataSimulasi.itemKe[ID].tanggalSimulasi.tahun); writeln('Sisa Energi : ', dataSimulasi.itemKe[ID].jumlahEnergi); writeln('Sisa Uang : ', dataSimulasi.itemKe[ID].jumlahDuit); writeln('Jumlah Makan : ', jmlMakan); writeln('Jumlah Istirahat: ', jmlIstirahat); writeln('--------------------------------------------------'); write('>> '); readln(perintah); case (perintah) of 'stopSimulasi' : mainStopSimulasi(stopSimulasi); 'lihatStatistik' : mainLihatStatistik(ID, dataSimulasi); 'lihatInventori' : mainLihatInventori(dataInventoriBahanMentah, dataInventoriBahanOlahan); 'lihatResep' : mainLihatResep(ID, dataResep); 'cariResep' : mainCariResep(ID, dataResep); 'tambahResep' : mainTambahResep(ID, dataBahanMentah, dataBahanOlahan, dataResep, dataSimulasi, dataInventoriBahanMentah); 'upgradeInventori' : mainUpgradeInventori(ID, dataSimulasi); 'makan' : mainMakan(jmlMakan, dataSimulasi.itemKe[ID].jumlahEnergi); 'istirahat' : mainIstirahat(jmlIstirahat, dataSimulasi.itemKe[ID].jumlahEnergi); 'tidur' : mainTidur(dataBahanMentah, dataSimulasi, dataInventoriBahanMentah, dataInventoriBahanOlahan, ID, jmlMakan, jmlIstirahat); 'beliBahan' : if (lelah(dataSimulasi,ID)) then mainTidur(dataBahanMentah, dataSimulasi, dataInventoriBahanMentah, dataInventoriBahanOlahan,ID,jmlMakan,jmlIstirahat) else begin write('Nama bahan: '); readln(bahanYangDibeli); write('Kuantitas: '); readln(kuantitasBahanYangDibeli); mainBeliBahan(bahanYangDibeli, kuantitasBahanYangDibeli, ID, dataBahanMentah, dataSimulasi, dataInventoriBahanMentah); end; 'olahBahan' : if (lelah(dataSimulasi,ID)) then mainTidur(dataBahanMentah, dataSimulasi, dataInventoriBahanMentah, dataInventoriBahanOlahan,ID,jmlMakan,jmlIstirahat) else mainOlahBahan(ID,dataInventoriBahanMentah,dataBahanOlahan,dataSimulasi,dataInventoriBahanOlahan); 'jualOlahan' : if (lelah(dataSimulasi,ID)) then mainTidur(dataBahanMentah, dataSimulasi, dataInventoriBahanMentah, dataInventoriBahanOlahan,ID,jmlMakan,jmlIstirahat) else mainJualOlahan(ID,dataInventoriBahanOlahan,dataSimulasi); 'jualResep' : if (lelah(dataSimulasi,ID)) then mainTidur(dataBahanMentah, dataSimulasi, dataInventoriBahanMentah, dataInventoriBahanOlahan,ID,jmlMakan,jmlIstirahat) else mainJualResep(ID, dataInventoriBahanMentah, dataInventoriBahanOlahan, dataResep, dataSimulasi); end; {asumsi : perintah selalu valid} hapusKosong(dataInventoriBahanMentah,dataInventoriBahanOlahan); until (stopSimulasi) or (dataSimulasi.itemKe[ID].jumlahHariHidup>10); end; function lelah(dataSimulasi : tabelSimulasi; ID : integer):boolean; {memberikan nilai true dan pesan kesalahan apabila dataSimulasi.itemKe[ID].jumlahEnergi <=0} begin if (dataSimulasi.itemKe[ID].jumlahEnergi <= 0) then begin writeln('Anda kelelahan, silahkan tidur'); lelah:= true end else lelah:= false; end; procedure hapusKosong(var BM : tabelBahanMentah;var BO : tabelBahanOlahan); {Menghapus bahan mentah dan olahan yang habis} var i, j : integer; begin for i:=1 to BM.banyakItem do begin if BM.itemKe[i].jumlahTersedia<=0 then begin for j:=i to (BM.banyakItem-1) do BM.itemKe[j]:=BM.itemKe[j+1]; BM.itemKe[BM.banyakItem].nama:=''; dec(BO.banyakItem); end; end; for i:=1 to BO.banyakItem do begin if BO.itemKe[i].jumlahTersedia<=0 then begin for j:=i to (BO.banyakItem-1) do BO.itemKe[j]:=BO.itemKe[j+1]; BO.itemKe[BO.banyakItem].nama:=''; dec(BO.banyakItem); end; end; end; end.
{ Sobre o autor: Guinther Pauli Delphi Certified Professional - 3,5,6,7,2005,2006,Delphi Web,Kylix,XE Microsoft Certified Professional - MCP,MCAD,MCSD.NET,MCTS,MCPD (C#, ASP.NET, Arquitetura) Colaborador Editorial Revistas .net Magazine e ClubeDelphi MVP (Most Valuable Professional) - Embarcadero Technologies - US http://gpauli.com http://www.facebook.com/guintherpauli http://www.twitter.com/guintherpauli http://br.linkedin.com/in/guintherpauli } unit uFramework; interface type // Memento Memento = class private _state: string; public constructor Create(state: string); property State: string read _state; end; // Originator Pessoa = class private _state: string; public property State: string read _state write _state; public function CreateMemento(): Memento; public procedure setMemento(memento: Memento); end; // Caretaker Caretaker = class private _memento: Memento; public property Memento: Memento read _memento write _memento; end; implementation // Pessoa function Pessoa.CreateMemento(): Memento; begin result := Memento.Create(_state); end; procedure Pessoa.setMemento(memento: Memento); begin WriteLn('Restaurando o estado...'); State := memento.State; end; constructor Memento.Create(state: string); begin self._state := state; end; end.
{*************************************************** * * Module: usbspec.h * Long name: USB Specification 1.0 * Description: * * Runtime Env.: * Author(s): Guenter Hildebrandt, Thomas Fröhlich * Company: Thesycon GmbH, Ilmenau ***************************************************} unit USBSPEC; interface uses Windows; type USHORT = word; // // descriptor types // const USB_DEVICE_DESCRIPTOR_TYPE = DWORD($01); USB_CONFIGURATION_DESCRIPTOR_TYPE = DWORD($02); USB_STRING_DESCRIPTOR_TYPE = DWORD($03); USB_INTERFACE_DESCRIPTOR_TYPE = DWORD($04); USB_ENDPOINT_DESCRIPTOR_TYPE = DWORD($05); USB_HID_DESCRIPTOR_TYPE = DWORD($21); type USB_DEVICE_DESCRIPTOR = packed record bLength : UCHAR; bDescriptorType : UCHAR; bcdUSB : USHORT; bDeviceClass : UCHAR; bDeviceSubClass : UCHAR; bDeviceProtocol : UCHAR; bMaxPacketSize0 : UCHAR; idVendor : USHORT; idProduct : USHORT; bcdDevice : USHORT; iManufacturer : UCHAR; iProduct : UCHAR; iSerialNumber : UCHAR; bNumConfigurations : UCHAR; end {_USB_DEVICE_DESCRIPTOR}; PUSB_DEVICE_DESCRIPTOR = ^USB_DEVICE_DESCRIPTOR; type USB_CONFIGURATION_DESCRIPTOR = packed record bLength : UCHAR; bDescriptorType : UCHAR; wTotalLength : USHORT; bNumInterfaces : UCHAR; bConfigurationValue : UCHAR; iConfiguration : UCHAR; bmAttributes : UCHAR; MaxPower : UCHAR; end {_USB_CONFIGURATION_DESCRIPTOR}; PUSB_CONFIGURATION_DESCRIPTOR = ^USB_CONFIGURATION_DESCRIPTOR; type USB_INTERFACE_DESCRIPTOR = packed record bLength : UCHAR; bDescriptorType : UCHAR; bInterfaceNumber : UCHAR; bAlternateSetting : UCHAR; bNumEndpoints : UCHAR; bInterfaceClass : UCHAR; bInterfaceSubClass : UCHAR; bInterfaceProtocol : UCHAR; iInterface : UCHAR; end {_USB_INTERFACE_DESCRIPTOR}; PUSB_INTERFACE_DESCRIPTOR = ^USB_INTERFACE_DESCRIPTOR; type USB_ENDPOINT_DESCRIPTOR = packed record bLength : UCHAR; bDescriptorType : UCHAR; bEndpointAddress : UCHAR; bmAttributes : UCHAR; wMaxPacketSize : USHORT; bInterval : UCHAR; end {_USB_ENDPOINT_DESCRIPTOR}; PUSB_ENDPOINT_DESCRIPTOR = ^USB_ENDPOINT_DESCRIPTOR; type USB_STRING_DESCRIPTOR = packed record bLength : UCHAR; bDescriptorType : UCHAR; bString : Array[0..126] of WCHAR; end {_USB_STRING_DESCRIPTOR}; PUSB_STRING_DESCRIPTOR = ^USB_STRING_DESCRIPTOR; type USB_HID_DESCRIPTOR = packed record bLength : UCHAR; bDescriptorType : UCHAR; bcdHID : USHORT; bCountryCode : UCHAR; bNumDescriptors : UCHAR; bDescriptorType1 : UCHAR; wDescriptorLength1 : USHORT; end {_USB_HID_DESCRIPTOR}; PUSB_HID_DESCRIPTOR = ^USB_HID_DESCRIPTOR; type USB_COMMON_DESCRIPTOR = packed record bLength : UCHAR; bDescriptorType : UCHAR; end {_USB_COMMON_DESCRIPTOR}; PUSB_COMMON_DESCRIPTOR = ^USB_COMMON_DESCRIPTOR; // // Audio Descriptors // const AUDIO_CS_INTERFACE_TYPE = DWORD($24); AUDIO_CS_ENDPOINT_TYPE = DWORD($25); AUDIO_CS_SUBTYPE_HEADER = DWORD($01); AUDIO_CS_SUBTYPE_INPUT_TERMINAL = DWORD($02); AUDIO_CS_SUBTYPE_OUTPUT_TERMINAL = DWORD($03); //AUDIO_CS_SUBTYPE_MIXER_UNIT = DWORD($04); //AUDIO_CS_SUBTYPE_SELECTOR_UNIT = DWORD($05); AUDIO_CS_SUBTYPE_FEATUR_UNIT = DWORD($06); AUDIO_CS_SUBTYPE_PROCESSING_UNIT = DWORD($07); AUDIO_CS_SUBTYPE_EXTENSION_UNIT = DWORD($08); type AUDIO_COMMON_INTERFACE_DESCRIPTOR = packed record bLength : UCHAR; bDescriptorType : UCHAR; bDescriptorSubtypeType : UCHAR; end {_AUDIO_COMMON_INTERFACE_DESCRIPTOR}; PAUDIO_COMMON_INTERFACE_DESCRIPTOR = ^AUDIO_COMMON_INTERFACE_DESCRIPTOR; type AUDIO_INTERFACE_HEADER_DESCRIPTOR = packed record bcdADC : USHORT; bTotalLength : USHORT; blnCollection : UCHAR; /// baInterfaceNr : UCHAR; end {_AUDIO_INTERFACE_HEADER_DESCRIPTOR}; PAUDIO_INTERFACE_HEADER_DESCRIPTOR = ^AUDIO_INTERFACE_HEADER_DESCRIPTOR; type AUDIO_INTERFACE_INPUT_TERMINAL_DESCRIPTOR = packed record bTerminalId : UCHAR; wTerminalType : USHORT; bAssocTerminal : UCHAR; bNrChannels : UCHAR; wChannelConfig : USHORT; iChannelNames : UCHAR; iTerminal : UCHAR; end {_AUDIO_INTERFACE_INPUT_TERMINAL_DESCRIPTOR}; PAUDIO_INTERFACE_INPUT_TERMINAL_DESCRIPTOR = ^AUDIO_INTERFACE_INPUT_TERMINAL_DESCRIPTOR; type AUDIO_INTERFACE_OUTPUT_TERMINAL_DESCRIPTOR = packed record bTerminalId : UCHAR; wTerminalType : USHORT; bAssocTerminal : UCHAR; bSourceID : UCHAR; iTerminal : UCHAR; end {_AUDIO_INTERFACE_OUTPUT_TERMINAL_DESCRIPTOR}; PAUDIO_INTERFACE_OUTPUT_TERMINAL_DESCRIPTOR = ^AUDIO_INTERFACE_OUTPUT_TERMINAL_DESCRIPTOR; type AUDIO_INTERFACE_FEATURE_UNIT_DESCRIPTOR = packed record bUnitID : UCHAR; bSourceID : UCHAR; bControlSize : UCHAR; // bmaControls : UCHAR; end {_AUDIO_INTERFACE_FEATURE_UNIT_DESCRIPTOR}; PAUDIO_INTERFACE_FEATURE_UNIT_DESCRIPTOR = ^AUDIO_INTERFACE_FEATURE_UNIT_DESCRIPTOR; type AUDIO_INTERFACE_AS_GENERAL_DESCRIPTOR = packed record bTerminalLink : UCHAR; bDelay : UCHAR; wFormatTag : USHORT; end {_AUDIO_INTERFACE_AS_GENERAL_DESCRIPTOR}; PAUDIO_INTERFACE_AS_GENERAL_DESCRIPTOR = ^AUDIO_INTERFACE_AS_GENERAL_DESCRIPTOR; type AUDIO_FORMAT_TYPE_I_DESCRIPTOR = packed record bFormatType : UCHAR; bNrChannels : UCHAR; bSubframeSize : UCHAR; bBitResolution : UCHAR; bSamFreqType : UCHAR; end {_AUDIO_FORMAT_TYPE_I_DESCRIPTOR}; PAUDIO_FORMAT_TYPE_I_DESCRIPTOR = ^AUDIO_FORMAT_TYPE_I_DESCRIPTOR; type AUDIO_CS_ENDPOINT_DESCRIPTOR = packed record bLength : UCHAR; bDescriptorType : UCHAR; bDescriptorSubtypeType : UCHAR; bmAttributes : UCHAR; bLockDelayUnits : UCHAR; wLockDelay : USHORT; end {_AUDIO_CS_ENDPOINT_DESCRIPTOR}; PAUDIO_CS_ENDPOINT_DESCRIPTOR = ^AUDIO_CS_ENDPOINT_DESCRIPTOR; implementation end.
unit BasicTypes; {$mode objfpc}{$H+} { ----- interface ------------------------------------------------------------------------------------------------- } interface uses Classes, SysUtils, zglHeader, Registry, Windows; { ----- global constants ------------------------------------------------------------------------------------------ } const SPRITE_SIZE_X = 40; SPRITE_SIZE_Y = 40; const RESOLUTION_X = SPRITE_SIZE_X * 15 + 360; RESOLUTION_Y = SPRITE_SIZE_Y * 15; const FRAME_SIZE_X = 100; FRAME_SIZE_Y = 100; { ----- global types ---------------------------------------------------------------------------------------------- } type TAppState = (asMenu, asGameStarted, asGamePaused); type TControlsSettings = record Up: UInt16; Down: Int16; Left: Int16; Right: Int16; PutBomb: Int16; Detonate: Int16; end; type TScreenSettings = record FullScreen: Boolean; Stretch: Boolean; end; { ----- classes --------------------------------------------------------------------------------------------------- } type TSettings = class private FControlsSettings: TControlsSettings; FScreenSettings: TScreenSettings; private function LoadFromFile() : Boolean; procedure LoadDefaults(); procedure SaveToFile(); public constructor Create(); destructor Destroy(); override; public property ControlsSettings : TControlsSettings read FControlsSettings write FControlsSettings; property ScreenSettings : TScreenSettings read FScreenSettings write FScreenSettings; end; { ----- global variables ------------------------------------------------------------------------------------------ } var ConfigPath : String; DataPath : String; { ----- global procedures & functions ----------------------------------------------------------------------------- } procedure SetPath(); procedure SetScreenSettings(AFullScreen, AStretch: Boolean); { ----- end interface --------------------------------------------------------------------------------------------- } implementation { ----- TSettings class ----------------------------------------------------------------------------------- } constructor TSettings.Create(); begin inherited Create; if not LoadFromFile then LoadDefaults; end; destructor TSettings.Destroy(); begin SaveToFile; inherited Destroy; end; function TSettings.LoadFromFile() : Boolean; var ConfigFile: TFileStream; begin Result := False; if FileExists(ConfigPath + 'config.cfg') then begin ConfigFile := TFileStream.Create(ConfigPath + 'config.cfg', fmOpenRead); try ConfigFile.ReadBuffer(FControlsSettings, SizeOf(FControlsSettings)); ConfigFile.ReadBuffer(FScreenSettings, SizeOf(FScreenSettings)); finally ConfigFile.Free(); end; Result := True; end; end; procedure TSettings.LoadDefaults(); begin FControlsSettings.Up := K_UP; FControlsSettings.Down := K_DOWN; FControlsSettings.Left := K_LEFT; FControlsSettings.Right := K_RIGHT; FControlsSettings.PutBomb := K_SPACE; FControlsSettings.Detonate := K_B; FScreenSettings.FullScreen := False; FScreenSettings.Stretch := False; end; procedure TSettings.SaveToFile(); var ConfigFile: TFileStream; begin ConfigFile := TFileStream.Create(ConfigPath + 'config.cfg', fmCreate); try ConfigFile.WriteBuffer(FControlsSettings, SizeOf(FControlsSettings)); ConfigFile.WriteBuffer(FScreenSettings, SizeOf(FScreenSettings)); finally ConfigFile.Free(); end; end; { ----- global procedures & functions ----------------------------------------------------------------------------- } procedure SetPath(); var Registry : TRegistry; begin Registry := TRegistry.Create(); try Registry.RootKey := HKEY_LOCAL_MACHINE; if Registry.OpenKey('SOFTWARE\Bomberman', true) then try if Registry.ValueExists('Path') then DataPath := Registry.ReadString('Path') else begin MessageBox(0, 'Missing registry key. Please reinstall game', 'Error!', MB_OK); Halt(2); end; finally Registry.CloseKey(); end else begin MessageBox(0, 'Missing registry value. Please reinstall game', 'Error!', MB_OK); Halt(1); end; finally Registry.Free(); end; if DirectoryExists(DataPath) then SetCurrentDir(DataPath) else begin MessageBox(0, 'Failed to set correct working path. Please reinstall game', 'Error!', MB_OK); Halt(3); end; ConfigPath := SysUtils.GetEnvironmentVariable('appdata') + '\Bomberman\'; if not DirectoryExists(ConfigPath) then if not CreateDir(ConfigPath) then begin MessageBox(0, 'Failed to set correct path to configuration file. Please reinstall game', 'Error!', MB_OK); Halt(4); end; end; procedure SetScreenSettings(AFullScreen, AStretch: Boolean); begin if AFullScreen and not AStretch then begin zgl_Enable(CORRECT_RESOLUTION); scr_CorrectResolution(RESOLUTION_X, RESOLUTION_Y); scr_SetOptions(zgl_Get(DESKTOP_WIDTH), zgl_Get(DESKTOP_HEIGHT), REFRESH_MAXIMUM, True, False); end // fullscreen bez czarnych pasów. else if AFullScreen and AStretch then begin zgl_Enable(CORRECT_RESOLUTION); zgl_Disable(CORRECT_WIDTH); zgl_Disable(CORRECT_HEIGHT); scr_CorrectResolution(RESOLUTION_X, RESOLUTION_Y); scr_SetOptions(zgl_Get(DESKTOP_WIDTH), zgl_Get(DESKTOP_HEIGHT), REFRESH_MAXIMUM, True, False); end else // okno begin zgl_Disable(CORRECT_RESOLUTION); scr_SetOptions(RESOLUTION_X, RESOLUTION_Y, REFRESH_MAXIMUM, False, False); end; end; { ----- end implementation----------------------------------------------------------------------------------------- } end.
unit MemStream; INTERFACE uses SysUtils; type tMemoryStream=object length: LongWord; size: LongWord; base: pointer; position: LongWord; procedure Seek(absolute:LongWord); procedure Skip(cnt:Word); procedure Read(var buf; cnt:Word); function ReadPtr(cnt:Word):pointer; function ReadByte:byte; function ReadWord(cnt:byte): LongWord; procedure Trunc; procedure Append; function Tell:LongWord; procedure Write(const buf; cnt:word); procedure WriteByte(v:byte); procedure WriteWord(v:LongWord; cnt:byte); procedure Init(ibuf:pointer; ilen,isize:LongWord); procedure Init(isize:LongWord); function WRBuf:pointer; function WRBufLen:LongWord; procedure WREnd(used:LongWord); function RDBuf:pointer; function RDBufLen:LongWord; procedure RDEnd(used:LongWord); end; type eInvalidMemStreamAccess=class(Exception) {no details jet} end; IMPLEMENTATION procedure tMemoryStream.Seek(absolute:LongWord); begin if absolute>size then raise eInvalidMemStreamAccess.Create('Seek out of bounds'); position:=absolute; end; procedure tMemoryStream.Skip(cnt:Word); begin Seek(position+cnt); end; procedure tMemoryStream.Read(var buf; cnt:Word); begin if (position+cnt)>length then raise eInvalidMemStreamAccess.Create('Read out of bounds'); Move((base+position)^,buf,cnt); position:=position+cnt; end; function tMemoryStream.ReadPtr(cnt:Word):pointer; begin result:=base+position; skip(cnt); end; function tMemoryStream.ReadByte:byte; begin Read(result, 1); end; function tMemoryStream.ReadWord(cnt:byte): LongWord; {$IFDEF ENDIAN_LITTLE} var tm:packed array [0..3] of byte; var i:byte; begin FillChar(tm,4,0); if (position+cnt)>length then raise eInvalidMemStreamAccess.Create('Read out of bounds'); for i:=cnt-1 downto 0 do begin tm[i]:=byte((base+position)^); inc(position); end; {$ELSE} begin Read(tm[4-cnt],cnt); {$ENDIF} ReadWord:=LongWord(pointer(@tm)^); end; procedure tMemoryStream.Trunc; begin length:=position; end; procedure tMemoryStream.Append; begin position:=length; end; function tMemoryStream.Tell:LongWord; begin Tell:=position; end; procedure tMemoryStream.Write(const buf; cnt:word); begin if (position+cnt)>size then raise eInvalidMemStreamAccess.Create('Write out of bounds'); Move(buf,(base+position)^,cnt); position:=position+cnt; if position>length then length:=position; end; procedure tMemoryStream.WriteByte(v:byte); begin Write(v,1); end; procedure tMemoryStream.WriteWord(v:LongWord; cnt:byte); var tm:packed array [0..3] of byte absolute v; var i:byte; begin {$IFDEF ENDIAN_LITTLE} if (position+cnt)>size then raise eInvalidMemStreamAccess.Create('Write out of bounds'); for i:=cnt-1 downto 0 do begin byte((base+position)^):=tm[i]; inc(position); end; if position>length then length:=position; {$ELSE} Write(tm[4-cnt],cnt); {$ENDIF} end; procedure tMemoryStream.Init(ibuf:pointer; ilen,isize:LongWord); begin base:=ibuf; length:=ilen; size:=isize; seek(0); end; procedure tMemoryStream.Init(isize:LongWord); begin Init(GetMem(isize),0,isize); end; function tMemoryStream.WRBuf:pointer; begin result:=base+position end; function tMemoryStream.WRBufLen:LongWord; begin result:=size-position end; procedure tMemoryStream.WREnd(used:LongWord); begin RDEnd(used); if position>length then length:=position end; function tMemoryStream.RDBuf:pointer; begin result:=base+position end; function tMemoryStream.RDBufLen:LongWord; begin result:=length-position end; procedure tMemoryStream.RDEnd(used:LongWord); begin skip(used) end; END.
unit Zip; interface uses Windows; const ZIP_HANDLE = 1; ZIP_FILENAME = 2; ZIP_MEMORY = 3; ZR_OK = $00000000; // nb. the pseudo-code zr-recent is never returned, ZR_RECENT = $00000001; // but can be passed to FormatZipMessage. // The following come from general system stuff (e.g. files not openable) ZR_GENMASK = $0000FF00; ZR_NODUPH = $00000100; // couldn't duplicate the handle ZR_NOFILE = $00000200; // couldn't create/open the file ZR_NOALLOC = $00000300; // failed to allocate some resource ZR_WRITE = $00000400; // a general error writing to the file ZR_NOTFOUND = $00000500; // couldn't find that file in the zip ZR_MORE = $00000600; // there's still more data to be unzipped ZR_CORRUPT = $00000700; // the zipfile is corrupt or not a zipfile ZR_READ = $00000800; // a general error reading the file // The following come from mistakes on the part of the caller ZR_CALLERMASK = $00FF0000; ZR_ARGS = $00010000; // general mistake with the arguments ZR_NOTMMAP = $00020000; // tried to ZipGetMemory, but that only works on mmap zipfiles, which yours wasn't ZR_MEMSIZE = $00030000; // the memory size is too small ZR_FAILED = $00040000; // the thing was already failed when you called this function ZR_ENDED = $00050000; // the zip creation has already been closed ZR_MISSIZE = $00060000; // the indicated input file size turned out mistaken ZR_PARTIALUNZ = $00070000; // the file had already been partially unzipped ZR_ZMODE = $00080000; // tried to mix creating/opening a zip // The following come from bugs within the zip library itself ZR_BUGMASK = $FF000000; ZR_NOTINITED = $01000000; // initialisation didn't work ZR_SEEK = $02000000; // trying to seek in an unseekable file ZR_NOCHANGE = $04000000; // changed its mind on storage, but not allowed ZR_FLATE = $05000000; // an internal error in the de/inflation code type HZIP = LongWord; ZIPENTRY = record index: integer; name: array [0..MAX_PATH - 1] of char; attr: DWORD; atime, ctime, mtime: FILETIME; comp_size, unc_size: LongInt; end; function ZOpen(const z; len: DWORD; flags: DWORD): HZIP; stdcall; { ZOpen - opens a zip file and returns a handle with which you can subssequently examine its contents. You can open a zip file from: file handle ZOpen(hfile, 0, ZIP_HANDLE); file name ZOpen('zip.zip', 0, ZIP_FILENAME); memory block ZOpen(buf, buflen, ZIP_MEMORY); } function ZGetItem(hz: HZIP; index: integer; var ze: ZIPENTRY): DWORD; stdcall; { ZGetItem - call this to get information about an item in the zip. If index is -1 it returns information about the whole zipfile (and in particular ze.index returns the number of index items). Note: the item might be a directory (ze.attr & FILE_ATTRIBUTE_DIRECTORY) } function ZFindItem(hz: HZIP; const name: PChar; ic: boolean; var index: integer; var ze: ZIPENTRY): DWORD; stdcall; { ZFindItem - finds an item by name. ic means 'insensitive to case'. It returns the index of the item, and returns information about it. If nothing was found, then index is set to -1 and the function returns an error code. } function ZUnzipItem(hz: HZIP; index: integer; var z; len: DWORD; flags: DWORD): DWORD; stdcall; { ZUnzipItem - given an index to an item, unzips it. You can unzip to: file handle UnzipItem(hz, i, hfile, 0, ZIP_HANDLE); file name UnzipItem(hz, i, ze.name, 0, ZIP_FILENAME); memory block UnzipItem(hz, i, buf,buflen, ZIP_MEMORY); Note: zip files are normally stored with relative pathnames. If you unzip with ZIP_FILENAME a relative pathname then the item gets created relative to the current directory - it first ensures that all necessary subdirectories have been created. Also, the item may itself be a directory. If you unzip a directory with ZIP_FILENAME, then the directory gets created. If you unzip it to a handle or a memory block, then nothing gets created and it emits 0 bytes. } function ZClose(hz: HZIP): DWORD; stdcall; { ZClose - the zip handle must be closed with this function. } implementation const zipdll = 'popmm.dll'; function ZOpen; external zipdll name 'ZOpen'; function ZGetItem; external zipdll name 'ZGetItem'; function ZFindItem; external zipdll name 'ZFindItem'; function ZUnzipItem; external zipdll name 'ZUnzipItem'; function ZClose; external zipdll name 'ZClose'; end.
unit PDBNormalDateEdit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Mask, ToolEdit, PDateEdit,dbctrls,db; type TPDBNormalDateEdit = class(TPDateEdit) private FDataLink : TFieldDataLink; protected { Protected declarations } function AcceptPopup(var Value: Variant): Boolean; override; function GetField : TField; function GetDataField : string; function GetDataSource : TDataSource; procedure ActiveChange(Sender : TObject); procedure CMExit(var Message : TCMExit); message CM_EXIT; procedure DataChange(Sender : TObject); procedure SetDataField(Value : string); procedure SetDataSource(Value : TDataSource); procedure UpdateData(Sender : TObject); public { Public declarations } Constructor Create(AOwner: TComponent) ; override; Destructor Destroy; override; property Field: TField read GetField; published { Published declarations } property DataField: string read GetDataField write SetDataField; property DataSource: TDataSource read GetDataSource write SetDataSource; end; procedure Register; implementation constructor TPDBNormalDateEdit.Create(AOwner : TComponent); begin inherited Create(AOwner); FDataLink := TFieldDataLink.Create ; FDataLink.Control := Self; FDataLink.OnDataChange := DataChange; FDataLink.OnUpDateData := UpdateData; FDataLink.OnActiveChange := ActiveChange; Enabled := True; end; destructor TPDBNormalDateEdit.Destroy; begin FDataLink.Free; FDataLink := nil; inherited Destroy; end; procedure TPDBNormalDateEdit.SetDataSource(Value : TDataSource); begin FDataLink.DataSource := Value; // Enabled := FDataLink.Active and (FDataLink.Field <> nil) and (not FDataLink.Field.ReadOnly); end; procedure TPDBNormalDateEdit.SetDataField(Value : string); begin try FDataLink.FieldName := Value; finally // Enabled := FDataLink.Active and (FDataLink.Field <> nil) and (not FDataLink.Field.ReadOnly); end; end; procedure TPDBNormalDateEdit.ActiveChange (Sender : TObject); begin // Enabled := FDataLink.Active and (FDataLink.Field <> nil) and (not FDataLink.Field.ReadOnly); end; procedure TPDBNormalDateEdit.UpdateData (Sender : TObject); var ok : Boolean; date : TDateTime; begin ok := True; try date := StrToDate(text); except ok := False; end; if (FDataLink.Field <> nil) and ok then// and (FDataLink.Field is TDateField) then FDataLink.Field.AsString := text; end; procedure TPDBNormalDateEdit.DataChange(sender : TObject); begin if (FDataLink.Field <> nil) then //and (FDataLink.Field is TDateField) then text := FDataLink.Field.AsString else text := ''; end; function TPDBNormalDateEdit.GetDataField : string; begin Result := FDataLink.FieldName; end; function TPDBNormalDateEdit.GetDataSource : TDataSource; begin Result := FDataLink.DataSource; end; function TPDBNormalDateEdit.GetField : TField; begin Result := FDataLink.Field; end; function TPDBNormalDateEdit.AcceptPopup(var Value: Variant): Boolean; begin FDataLink.Edit; Result := inherited AcceptPopup(Value); FDataLink.Modified; end; procedure TPDBNormalDateEdit.CMExit(var Message : TCMExit); begin try FDataLink.UpdateRecord ; //UpdateData; except SetFocus; raise; end; inherited; end; procedure Register; begin RegisterComponents('Poscontrol2', [TPDBNormalDateEdit]); end; end.
unit SendMovementItemTest; interface uses dbTest, ObjectTest; type TSendMovementItemTest = class(TdbTest) protected //procedure SetUp; override; published // загрузка процедура из определенной директории procedure ProcedureLoad; override; procedure Test; override; end; TSendMovementItem = class(TMovementItemTest) private function InsertDefault: integer; override; protected procedure SetDataSetParam; override; public function InsertUpdateMovementItemSend (Id, MovementId, GoodsId: Integer; Amount: double): integer; constructor Create; override; end; implementation uses UtilConst, Db, SysUtils, dbMovementTest, UnitsTest, Storage, Authentication, TestFramework, CommonData, dbObjectTest, Variants, SendTest, IncomeMovementItemTest; { TSendMovementItemTest } procedure TSendMovementItemTest.Test; var MovementItemSend: TSendMovementItem; Id: Integer; begin exit; MovementItemSend := TSendMovementItem.Create; Id := MovementItemSend.InsertDefault; // создание документа try // редактирование finally // удаление MovementItemSend.Delete(Id); end; end; procedure TSendMovementItemTest.ProcedureLoad; begin ScriptDirectory := LocalProcedurePath + 'Movement\Send\'; inherited; ScriptDirectory := LocalProcedurePath + 'MovementItem\Send\'; inherited; ScriptDirectory := LocalProcedurePath + 'MovementItemContainer\Send\'; inherited; end; { TSendMovementItem } constructor TSendMovementItem.Create; begin inherited; spInsertUpdate := 'gpInsertUpdate_MovementItem_Send'; spSelect := 'gpSelect_MovementItem_Send'; // spGet := 'gpGet_MovementItem_Send'; end; procedure TSendMovementItem.SetDataSetParam; begin inherited; FParams.AddParam('inMovementId', ftInteger, ptInput, TSend.Create.GetDefault); FParams.AddParam('inShowAll', ftBoolean, ptInput, true); FParams.AddParam('inIsErased', ftBoolean, ptInput, False); end; function TSendMovementItem.InsertDefault: integer; var Id, MovementId, GoodsId, PartionGoodsId: Integer; Amount, Price: double; begin Id:=0; MovementId := TSend.Create.GetDefault; With TIncomeMovementItem.Create.GetDataSet DO Begin GoodsId := FieldByName('GoodsId').asInteger; Amount := FieldBYName('Amount').asFloat; End; result := InsertUpdateMovementItemSend(Id, MovementId, GoodsId, Amount); end; function TSendMovementItem.InsertUpdateMovementItemSend (Id, MovementId, GoodsId: Integer; Amount: double): integer; begin FParams.Clear; FParams.AddParam('ioId', ftInteger, ptInputOutput, Id); FParams.AddParam('inMovementId', ftInteger, ptInput, MovementId); FParams.AddParam('inGoodsId', ftInteger, ptInput, GoodsId); FParams.AddParam('inAmount', ftFloat, ptInput, Amount); result := InsertUpdate(FParams); end; initialization TestFramework.RegisterTest('Строки Документов', TSendMovementItemTest.Suite); end.
unit TelegAPI.Utils.Json; interface uses System.Json; type TBaseJsonClass = class of TBaseJson; TBaseJson = class(TInterfacedObject) private protected FJSON: TJSONObject; FJsonRaw: string; //for debbuger function ReadToClass<T: class, constructor>(const AKey: string): T; function ReadToSimpleType<T>(const AKey: string): T; function ReadToDateTime(const AKey: string): TDateTime; function ReadToArray<TI: IInterface>(TgClass: TBaseJsonClass; const AKey: string): TArray<TI>; procedure Write(const AKey, AValue: string); procedure SetJson(const AJson: string); public function AsJson: string; class function FromJson(const AJson: string): TBaseJson; class function GetTgClass: TBaseJsonClass; virtual; // abstract; class procedure UnSupported; constructor Create(const AJson: string); virtual; destructor Destroy; override; end; TJsonUtils = class class function ArrayToJString<T: class>(LArray: TArray<T>): string; class function ObjectToJString(AObj: TObject): string; class function FileToObject<T: class, constructor>(const AFileName: string): T; class procedure ObjectToFile(AObj: TObject; const AFileName: string); end; TJSONValueHelper = class helper for TJSONValue strict private private function GetS(const APath: string): string; procedure SetS(const APath, AValue: string); public property S[const APath: string]: string read GetS write SetS; end; implementation uses REST.Json, System.DateUtils, System.IOUtils, System.SysUtils, System.TypInfo; { TJSONValueHelper } type TJSONStringHack = class(TJSONString); function TJSONValueHelper.GetS(const APath: string): string; begin if (not Self.TryGetValue<string>(APath, Result)) then Result := string.Empty; end; procedure TJSONValueHelper.SetS(const APath, AValue: string); var LValue: TJSONValue; begin LValue := Self.FindValue(APath); if (LValue is TJSONString) then begin TJSONStringHack(LValue).FStrBuffer.Clear(); TJSONStringHack(LValue).FStrBuffer.Append(AValue); end; end; { TJsonUtils } class function TJsonUtils.ArrayToJString<T>(LArray: TArray<T>): string; var I: Integer; begin Result := '['; for I := Low(LArray) to High(LArray) do if Assigned(LArray[I]) then begin Result := Result + TJson.ObjectToJsonString(LArray[I]); if I <> High(LArray) then Result := Result + ','; end; Result := Result + ']'; Result := Result.Replace('"inline_keyboard":null', '', [rfReplaceAll]); // какашечка end; class function TJsonUtils.FileToObject<T>(const AFileName: string): T; var LContent: string; begin Result := nil; if TFile.Exists(AFileName) then begin LContent := TFile.ReadAllText(AFileName, TEncoding.UTF8); Result := TJson.JsonToObject<T>(LContent); end; end; class procedure TJsonUtils.ObjectToFile(AObj: TObject; const AFileName: string); var LContent: string; begin LContent := ObjectToJString(AObj); TFile.WriteAllText(AFileName, LContent, TEncoding.UTF8); end; class function TJsonUtils.ObjectToJString(AObj: TObject): string; begin // IF DELPHI_VERSION < TOKIO if Assigned(AObj) then Result := TJson.ObjectToJsonString(AObj) else Result := 'null'; end; { TBaseJson } function TBaseJson.AsJson: string; begin if Assigned(FJSON) then Result := FJSON.ToJSON else Result := ''; end; constructor TBaseJson.Create(const AJson: string); begin inherited Create; SetJson(AJson); end; function TBaseJson.ReadToArray<TI>(TgClass: TBaseJsonClass; const AKey: string): TArray<TI>; var LJsonArray: TJSONArray; I: Integer; GUID: TGUID; begin // stage 1: type checking // cache value fot further use GUID := GetTypeData(TypeInfo(TI))^.GUID; // check for TI interface support if TgClass.GetInterfaceEntry(GUID) = nil then raise Exception.Create('GetArrayFromMethod: unsupported interface for ' + TgClass.ClassName); // stage 2: proceed data LJsonArray := FJSON.GetValue(AKey) as TJSONArray; if (not Assigned(LJsonArray)) or LJsonArray.Null then Exit(nil); SetLength(Result, LJsonArray.Count); for I := 0 to High(Result) do begin TgClass.GetTgClass.Create(LJsonArray.Items[I].ToString).GetInterface(GUID, Result[I]); end; end; function TBaseJson.ReadToClass<T>(const AKey: string): T; var LValue: string; LObj: TJSONValue; begin Result := nil; LObj := FJSON.GetValue(AKey); if Assigned(LObj) and (not LObj.Null) then begin {$IFDEF USE_INDY} // Директива не совсем подходит. Это в случае если используется старая версия ИДЕ LValue := LObj.ToString; {$ELSE} LValue := LObj.ToJSON; {$ENDIF} Result := TBaseJsonClass(T).Create(LValue) as T; end end; destructor TBaseJson.Destroy; begin FJSON.Free; inherited; end; class function TBaseJson.FromJson(const AJson: string): TBaseJson; begin if AJson.IsEmpty then Result := nil else Result := TBaseJson.Create(AJson); end; class function TBaseJson.GetTgClass: TBaseJsonClass; begin Result := Self; end; function TBaseJson.ReadToDateTime(const AKey: string): TDateTime; var LValue: Int64; begin Result := 0; if FJSON.TryGetValue<Int64>(AKey, LValue) then Result := UnixToDateTime(LValue, False); end; function TBaseJson.ReadToSimpleType<T>(const AKey: string): T; begin if (not Assigned(FJSON)) or (not FJSON.TryGetValue<T>(AKey, Result)) then Result := Default(T); end; procedure TBaseJson.SetJson(const AJson: string); begin FJsonRaw := AJson; if FJsonRaw.IsEmpty then Exit; if Assigned(FJSON) then FreeAndNil(FJSON); FJSON := TJSONObject.ParseJSONValue(AJson) as TJSONObject; end; class procedure TBaseJson.UnSupported; begin raise Exception.Create('Telegram method not supported in TelegaPi Library. Sorry.'); end; procedure TBaseJson.Write(const AKey, AValue: string); var JoX: TJSONPair; begin JoX := FJSON.GetValue<TJSONPair>(AKey); if Assigned(JoX.JsonValue) then JoX.JsonValue.Free; JoX.JsonValue := TJSONString.Create(AValue); end; end.
unit MensagemForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls; type TFormMensagem = class(TForm) panel: TPanel; procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private FTipoAto: string; FProtocolo: string; procedure SetProtocolo(const Value: string); procedure SetTipoAto(const Value: string); public property Protocolo: string read FProtocolo write SetProtocolo; property TipoAto: string read FTipoAto write SetTipoAto; end; var FormMensagem: TFormMensagem; implementation {$R *.dfm} { TFormMensagem } procedure TFormMensagem.FormClose(Sender: TObject; var Action: TCloseAction); begin panel.Caption := EmptyStr; end; procedure TFormMensagem.FormShow(Sender: TObject); begin panel.Caption := Format('Aguarde! Processando protocolo %s com tipo de ato %s...', [Protocolo, TipoAto]); end; procedure TFormMensagem.SetProtocolo(const Value: string); begin FProtocolo := Value; end; procedure TFormMensagem.SetTipoAto(const Value: string); begin FTipoAto := Value; end; end.
unit DBUtils; interface uses Db, DBTables,Bde,DBConsts, BDEConst,DBCommon; function CreateParamDesc(SP : TStoredProc; DefaultInput : boolean = false): boolean; implementation function CreateParamDesc(SP : TStoredProc; DefaultInput : boolean = false):boolean; var Desc: SPParamDesc; Cursor: HDBICur; Buffer: DBISPNAME; ParamName: string; ParamDataType: TFieldType; db : TDatabase; r : integer; begin AnsiToNative(sp.DBLocale, sp.StoredProcName, Buffer, SizeOf(Buffer)-1); db := sp.OpenDatabase; if db=nil then begin result:=false; exit; end; r := DbiOpenSPParamList(db.Handle, Buffer, False, sp.OverLoad, Cursor); result := r=0; if result then try SP.Params.Clear; while DbiGetNextRecord(Cursor, dbiNOLOCK, @Desc, nil) = 0 do with Desc do begin NativeToAnsi(sp.DBLocale, szName, ParamName); if (TParamType(eParamType) = ptResult) and (ParamName = '') then ParamName := SResultName; if uFldType < MAXLOGFLDTYPES then ParamDataType := DataTypeMap[uFldType] else ParamDataType := ftUnknown; if (uFldType = fldFLOAT) and (uSubType = fldstMONEY) then ParamDataType := ftCurrency; with TParam(sp.Params.Add) do begin ParamType := TParamType(eParamType); DataType := ParamDataType; Name := ParamName; if DefaultInput and (ParamType=ptUnknown) then ParamType := ptInput; end; end; //SetServerParams; finally DbiCloseCursor(Cursor); end; end; end.
unit RepositorioQuantidadePorValidade; interface uses DB, Auditoria, Repositorio; type TRepositorioQuantidadePorValidade = class(TRepositorio) protected function Get (Dataset :TDataSet) :TObject; overload; override; function GetNomeDaTabela :String; override; function GetIdentificador(Objeto :TObject) :Variant; override; function GetRepositorio :TRepositorio; override; protected function SQLGet :String; override; function SQLSalvar :String; override; function SQLGetAll :String; override; function CondicaoSQLGetAll :String; override; function SQLRemover :String; override; function SQLGetExiste(campo: String): String; override; protected function IsInsercao(Objeto :TObject) :Boolean; override; protected procedure SetParametros (Objeto :TObject ); override; procedure SetIdentificador(Objeto :TObject; Identificador :Variant); override; protected procedure SetCamposIncluidos(Auditoria :TAuditoria; Objeto :TObject); override; procedure SetCamposAlterados(Auditoria :TAuditoria; AntigoObjeto, Objeto :TObject); override; procedure SetCamposExcluidos(Auditoria :TAuditoria; Objeto :TObject); override; end; implementation uses SysUtils, QuantidadePorValidade, System.StrUtils; { TRepositorioQuantidadePorValidade } function TRepositorioQuantidadePorValidade.CondicaoSQLGetAll: String; begin result := ' WHERE '+FIdentificador; end; function TRepositorioQuantidadePorValidade.Get(Dataset: TDataSet): TObject; var QuantidadePorValidade :TQuantidadePorValidade; begin QuantidadePorValidade:= TQuantidadePorValidade.Create; QuantidadePorValidade.codigo := self.FQuery.FieldByName('codigo').AsInteger; QuantidadePorValidade.codigo_item := self.FQuery.FieldByName('codigo_item').AsInteger; QuantidadePorValidade.codigo_validade := self.FQuery.FieldByName('codigo_validade').AsInteger; QuantidadePorValidade.quantidade := self.FQuery.FieldByName('quantidade').AsFloat; result := QuantidadePorValidade; end; function TRepositorioQuantidadePorValidade.GetIdentificador(Objeto: TObject): Variant; begin result := TQuantidadePorValidade(Objeto).Codigo; end; function TRepositorioQuantidadePorValidade.GetNomeDaTabela: String; begin result := 'QTD_ITEM_POR_VALIDADE'; end; function TRepositorioQuantidadePorValidade.GetRepositorio: TRepositorio; begin result := TRepositorioQuantidadePorValidade.Create; end; function TRepositorioQuantidadePorValidade.IsInsercao(Objeto: TObject): Boolean; begin result := (TQuantidadePorValidade(Objeto).Codigo <= 0); end; procedure TRepositorioQuantidadePorValidade.SetCamposAlterados(Auditoria :TAuditoria; AntigoObjeto, Objeto :TObject); var QuantidadePorValidadeAntigo :TQuantidadePorValidade; QuantidadePorValidadeNovo :TQuantidadePorValidade; begin QuantidadePorValidadeAntigo := (AntigoObjeto as TQuantidadePorValidade); QuantidadePorValidadeNovo := (Objeto as TQuantidadePorValidade); if (QuantidadePorValidadeAntigo.codigo_item <> QuantidadePorValidadeNovo.codigo_item) then Auditoria.AdicionaCampoAlterado('codigo_item', IntToStr(QuantidadePorValidadeAntigo.codigo_item), IntToStr(QuantidadePorValidadeNovo.codigo_item)); if (QuantidadePorValidadeAntigo.codigo_validade <> QuantidadePorValidadeNovo.codigo_validade) then Auditoria.AdicionaCampoAlterado('codigo_validade', IntToStr(QuantidadePorValidadeAntigo.codigo_validade), IntToStr(QuantidadePorValidadeNovo.codigo_validade)); if (QuantidadePorValidadeAntigo.quantidade <> QuantidadePorValidadeNovo.quantidade) then Auditoria.AdicionaCampoAlterado('quantidade', FloatToStr(QuantidadePorValidadeAntigo.quantidade), FloatToStr(QuantidadePorValidadeNovo.quantidade)); end; procedure TRepositorioQuantidadePorValidade.SetCamposExcluidos(Auditoria :TAuditoria; Objeto :TObject); var QuantidadePorValidade :TQuantidadePorValidade; begin QuantidadePorValidade := (Objeto as TQuantidadePorValidade); Auditoria.AdicionaCampoExcluido('codigo' , IntToStr(QuantidadePorValidade.codigo)); Auditoria.AdicionaCampoExcluido('codigo_item' , IntToStr(QuantidadePorValidade.codigo_item)); Auditoria.AdicionaCampoExcluido('codigo_validade', IntToStr(QuantidadePorValidade.codigo_validade)); Auditoria.AdicionaCampoExcluido('quantidade' , FloatToStr(QuantidadePorValidade.quantidade)); end; procedure TRepositorioQuantidadePorValidade.SetCamposIncluidos(Auditoria :TAuditoria; Objeto :TObject); var QuantidadePorValidade :TQuantidadePorValidade; begin QuantidadePorValidade := (Objeto as TQuantidadePorValidade); Auditoria.AdicionaCampoIncluido('codigo' , IntToStr(QuantidadePorValidade.codigo)); Auditoria.AdicionaCampoIncluido('codigo_item' , IntToStr(QuantidadePorValidade.codigo_item)); Auditoria.AdicionaCampoIncluido('codigo_validade', IntToStr(QuantidadePorValidade.codigo_validade)); Auditoria.AdicionaCampoIncluido('quantidade' , FloatToStr(QuantidadePorValidade.quantidade)); end; procedure TRepositorioQuantidadePorValidade.SetIdentificador(Objeto: TObject; Identificador: Variant); begin TQuantidadePorValidade(Objeto).Codigo := Integer(Identificador); end; procedure TRepositorioQuantidadePorValidade.SetParametros(Objeto: TObject); var QuantidadePorValidade :TQuantidadePorValidade; begin QuantidadePorValidade := (Objeto as TQuantidadePorValidade); self.FQuery.ParamByName('codigo').AsInteger := QuantidadePorValidade.codigo; self.FQuery.ParamByName('codigo_item').AsInteger := QuantidadePorValidade.codigo_item; self.FQuery.ParamByName('codigo_validade').AsInteger := QuantidadePorValidade.codigo_validade; self.FQuery.ParamByName('quantidade').AsFloat := QuantidadePorValidade.quantidade; end; function TRepositorioQuantidadePorValidade.SQLGet: String; begin result := 'select * from QTD_ITEM_POR_VALIDADE where codigo = :ncod'; end; function TRepositorioQuantidadePorValidade.SQLGetAll: String; begin result := 'select * from QTD_ITEM_POR_VALIDADE '+ IfThen(FIdentificador = '','', CondicaoSQLGetAll); end; function TRepositorioQuantidadePorValidade.SQLGetExiste(campo: String): String; begin result := 'select '+ campo +' from QTD_ITEM_POR_VALIDADE where '+ campo +' = :ncampo'; end; function TRepositorioQuantidadePorValidade.SQLRemover: String; begin result := ' delete from QTD_ITEM_POR_VALIDADE where codigo = :codigo '; end; function TRepositorioQuantidadePorValidade.SQLSalvar: String; begin result := 'update or insert into QTD_ITEM_POR_VALIDADE (CODIGO ,CODIGO_ITEM ,CODIGO_VALIDADE ,QUANTIDADE) '+ ' values ( :CODIGO , :CODIGO_ITEM , :CODIGO_VALIDADE , :QUANTIDADE) '; end; end.
unit UCC_TrendAnalyzer; { ClickForms Application } { Bradford Technologies, Inc. } { All Rights Reserved } { Source Code Copyrighted 1998-2015 by Bradford Technologies, Inc.} { this unit is for performing the same analysis as is required for the 1004MC} { it creates arrays of sales and listing in various time periods and determines} { the min, max, average, median of each and then performs market analysis to } { plot trends of the market.} { Period and Timeline Structure } { The most recent period will be the last one in the list of periods} { The End date of a period will be the most recent, The Begin date will be the } { start of the period: for instance Begin Date 1/1/15, End Date would be 1/31/15} { NOTE: Since a property can be a sale in one period and a listing in a another} { period, the dataPts in the sales and listing lists are clones of the } { actual dataPts stored in the TrendAnalyzer Object} interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Contnrs; const //Listing Status lsUnknown = 0; lsSold = 1; lsActive = 2; lsPending = 3; lsExpired = 4; lsWithDrwn = 5; // ckSale = 1; // ckList = 2; //number of periods tp12MonthPeriods = 1; tpQuarterPeriods = 2; tp1004MCPeriods = 3; //trend IDs ttSalePrice = 1; ttListPrice = 2; ttTotalSales = 3; ttTotalListings = 4; ttPricePerSqft = 5; //only for sales ttAbsorptionRate = 6; ttMonthsSupply = 7; ttSalesDOM = 8; ttListingDOM = 9; ttSaleToListRatio = 10; //trend period interval tdNone = 0; tdLast3Months = 1; tdLast6Months = 2; tdLast12Months = 3; type ArrayOf12Reals = array[1..12] of Real; TDataPt = class(TObject) private FTestID: Integer; FStatus: Integer; //status of listing (sold, active, pending, withdrawn, etc) FStatDate: TDateTime; //if sold then sold date. otherwise its status date FPrice: Integer; //if sold, then sold price. Otherwise its listing price on status date FListDate: TDateTime; //original listing date (or status date) FListPrice: Integer; //original listing price FStoLRatio: Real; //sales to list ratio - only for sold and pending FDOM: Integer; //sale date - list date or statusDate - list date FBeds: Integer; // FGLA: Integer; //gross living area FPrPerGLA: Real; //price depends on status (sale or listing) FPrPerBed: Real; public procedure Assign(Source: TDataPt); property TestID: Integer read FTestID write FTestID; property Status: Integer read FStatus write FStatus; property StatDate: TDateTime read FStatDate write FStatDate; property Price: Integer read FPrice write FPrice; property ListDate: TDateTime read FListDate write FListDate; //original listing date (status date) property ListPrice: Integer read FListPrice write FListPrice; //original listing price property Sale2ListRatio: Real read FStoLRatio write FStoLRatio; //sales to list ratio property DOM: Integer read FDOM write FDOM; property GLA: Integer read FGLA write FGLA; property Beds: Integer read FBeds write FBeds; property PricePerGLA: Real read FPrPerGLA write FPrPerGLA; property PricePerBed: Real read FPrPerBed write FPrPerBed; end; TDataPtList = class(TObjectList) private FMinGLA: Integer; FMaxGLA: Integer; FAvgGLA: Integer; FMedGLA: Integer; FMinPrice: Integer; FMaxPrice: Integer; FAvgPrice: Integer; FMedPrice: Integer; FMinDOM: Integer; FMaxDOM: Integer; FAvgDOM: Integer; FMedDOM: Integer; FMinPrPerGLA: Real; FMaxPrPerGLA: Real; FAvgPrPerGLA: Real; FMedPrPerGLA: Real; FMinS2LRatio: Real; FMaxS2LRatio: Real; FAvgS2LRatio: Real; FMedS2LRatio: Real; FMedTimeAdjPcnt: Real; FAvgTimeAdjPcnt: Real; procedure AnalyzeGLA; procedure AnalyzePrice; procedure AnalyzeDOM; procedure AnalyzePrPerGLA; procedure AnalyzeS2LRatio; function SumGLA: Integer; function SumPrice: Integer; function SumDOM: Integer; function SumPrPerGLA: Real; function SumSale2ListRatio: Real; function GetDataPt(Index: Integer): TDataPt; procedure SetDataPt(Index: Integer; const Value: TDataPt); function CalcMedianDOM: Integer; function CalcMedianPrice: Integer; function CalcMedianPrPerGLA: Real; function CalcMedianGLA: Integer; function CalcMedianS2LRatio: Real; public procedure Analyze; procedure QuickSortOnGLA(startLo, startHi: Integer); procedure QuickSortOnPrice(startLo, startHi: Integer); procedure QuickSortOnDOM(startLo, startHi: Integer); procedure QuickSortOnPricePerGLA(startLo, startHi: Integer); procedure QuickSortOnS2LRatio(startLo, startHi: Integer); property MinGLA: Integer read FMinGLA write FMinGLA; property MaxGLA: Integer read FMaxGLA write FMaxGLA; property AvgGLA: Integer read FAvgGLA write FAvgGLA; property MedianGLA: Integer read FMedGLA write FMedGLA; property MinPrice: Integer read FMinPrice write FMinPrice; property MaxPrice: Integer read FMaxPrice write FMaxPrice; property AvgPrice: Integer read FAvgPrice write FAvgPrice; property MedianPrice: Integer read FMedPrice write FMedPrice; property MinDOM: Integer read FMinDOM write FMinDOM; property MaxDOM: Integer read FMaxDOM write FMaxDOM; property AvgDOM: Integer read FAvgDOM write FAvgDOM; property MedianDOM: Integer read FMedDOM write FMedDOM; property MinPrPerGLA: Real read FMinPrPerGLA write FMinPrPerGLA; property MaxPrPerGLA: Real read FMaxPrPerGLA write FMaxPrPerGLA; property AvgPrPerGLA: Real read FAvgPrPerGLA write FAvgPrPerGLA; property MedianPrPerGLA: Real read FMedPrPerGLA write FMedPrPerGLA; property MinSaleToListRatio: Real read FMinS2LRatio write FMinS2LRatio; property MaxSaleToListRatio: Real read FMaxS2LRatio write FMaxS2LRatio; property AvgSaleToListRatio: Real read FAvgS2LRatio write FAvgS2LRatio; property MedianSaleToListRatio: Real read FMedS2LRatio write FMedS2LRatio; property MedianTimeAdjPercent: Real read FMedTimeAdjPcnt write FMedTimeAdjPcnt; property AvgTimeAdjPercent: Real read FAvgTimeAdjPcnt write FAvgTimeAdjPcnt; property DataPt[Index: Integer]: TDataPt read GetDataPt write SetDataPt; default; end; TSales = Class(TDataPtList); TListings = class(TDataPtList); TTimePeriod = class(TObject) private FMoInPeriod: Integer; //Months in this period FBeginDate: TDateTime; FEndDate: TDateTime; FAbsorbRate: Real; //absorption Rate (sales/months in period) FMosSupply: Real; //Months supply (active listing/absorption rate) FSales: TSales; FListings: TListings; public Constructor Create; Destructor Destroy; override; procedure Analyze; property BeginDate: TDateTime read FBeginDate write FBeginDate; property EndDate: TDateTime read FEndDate write FEndDate; property Sales: TSales read FSales write FSales; property Listings: TListings read FListings write FListings; property MonthsInPeriod: Integer read FMoInPeriod write FMoInPeriod; property AbsorptionRate: Real read FAbsorbRate write FAbsorbRate; property MonthsSupply: Real read FMosSupply write FMosSupply; end; TTimePeriodList = class(TObjectList) private function GetTimePeriod(Index: Integer): TTimePeriod; procedure SetTimePeriod(Index: Integer; const Value: TTimePeriod); public procedure Analyze; property Period[Index: Integer]: TTimePeriod read GetTimePeriod write SetTimePeriod; default; end; TTrendLine = class(TObject) TrendID: Integer; //trend type identifier (total sales, sale price, etc) PeriodTyp: Integer; //3 mos, 6 mos, 12 mos X1, X2: Integer; //end points of the trend line (x1,y1) (x2,y2) Y1, y2: Real; AConst: Real; //y-intercept of the line Velocity: Real; //slope of the line or rate of change X1Act, X2Act: Real; //actual end point values PctChgActual: Real; //actual percent change between start and end of trend interval X1Trend, X2Trend: Real; //caluclated end point values PctChgTrend: Real; //calculated change between start and end of trend interval end; TTrendLineList = class(TObjectList) private function GetTrendLine(Index: Integer): TTrendLine; procedure SetTrendLine(Index: Integer; const Value: TTrendLine); public function GetTrendLineByID(ATendID, ATrendPeriod: Integer): TTrendLine; function GetTrendVelocityByID(ATendID, ATrendPeriod: Integer): Real; function GetTrendPercentChangeByID(ATendID, ATrendPeriod: Integer): Real; function GetTrendRateOfChangeStrByID(ATendID, ATrendPeriod: Integer): String; function GetTrendPercentChangeStrByID(ATendID, ATrendPeriod: Integer): String; property Trend[Index: Integer]: TTrendLine read GetTrendLine write SetTrendLine; default; end; TTrendAnalyzer = class(TObject) private FDataPts: TDataPtList; FPeriods: TTimePeriodList; FTrends: TTrendLineList; FPeriodType: Integer; //12mo, quarterly, 1004MC periods FStartDate: TDateTime; FTrendInterval: Integer; //last 3mos, last 6mos, last 12mos FHas12PeriodData: Boolean; FPendingAsSold: Boolean; FActiveListingOnly: Boolean; procedure Build1004MCPeriodList; procedure Build12MonthPeriodList; procedure Build4QuarterPeriodList; procedure BuildTimePeriodList; procedure LoadSalesAndListingsToPeriods; procedure AddSalesToTimePeriods(ADataPt: TDataPt); procedure AddListingsToTimePeriods(ADataPt: TDataPt); function CalcTrendLine(ATrendID, ATrendPeriod: Integer; const Y: ArrayOf12Reals): TTrendLine; procedure CalcTotalSalesTrendLines; procedure CalcTotalListingsTrendLines; procedure CalcSalePriceTrendLines; procedure CalcListingPriceTrendLines; procedure CalcListingDOMTrendLines; procedure CalcSalesDOMTrendLines; procedure CalcSalePricePerSqftTrendLines; procedure CalcAbsorptionRateTrendLines; procedure CalcMonthsSupplyTrendLines; procedure CalcSaleToListRatioTrendLines; public Constructor Create; Destructor Destroy; override; procedure Analyze; procedure CalcAllTrendLines; procedure CalcPeriodTimeAdjustments; function EmptySalesListingPrice: Boolean; property PendingAsSold: Boolean read FPendingAsSold write FPendingAsSold; property ActiveListingOnly: Boolean read FActiveListingOnly write FActiveListingOnly; property Has12PeriodData: Boolean read FHas12PeriodData write FHas12PeriodData; property TrendStartDate: TDateTime read FStartDate write FStartDate; property TrendInterval: Integer read FTrendInterval write FTrendInterval; property PeriodType: Integer read FPeriodType write FPeriodType; property DataPts: TDataPtList read FDataPts write FDataPts; property Periods: TTimePeriodList read FPeriods write FPeriods; property Trends: TTrendLineList read FTrends write FTrends; end; implementation uses DateUtils, TPMath, Math; { TDataPt } procedure TDataPt.Assign(Source: TDataPt); begin FTestID := Source.FTestID; FStatus := Source.FStatus; FStatDate := Source.FStatDate; FPrice := Source.FPrice; FListDate := Source.FListDate; FListPrice := Source.FListPrice; FStoLRatio := Source.FStoLRatio; FDOM := Source.FDOM; FBeds := Source.FBeds; FGLA := Source.FGLA; FPrPerGLA := Source.FPrPerGLA; FPrPerBed := Source.FPrPerBed; end; { TDataPtList } function TDataPtList.GetDataPt(Index: Integer): TDataPt; begin result := TDataPt(inherited Items[index]); end; procedure TDataPtList.SetDataPt(Index: Integer; const Value: TDataPt); begin inherited Insert(Index, Value); end; //start = 0 to count-1 procedure TDataPtList.QuickSortOnGLA(startLo, startHi: Integer); var Lo, Hi, pivotGLA: Integer; begin repeat Lo := startLo; Hi := startHi; pivotGLA := DataPt[(Lo + Hi) div 2].GLA; repeat while DataPt[Lo].GLA < pivotGLA do Inc(Lo); while DataPt[Hi].GLA > pivotGLA do Dec(Hi); if Lo <= Hi then begin Exchange(Lo, Hi); Inc(Lo); Dec(Hi); end; until Lo > Hi; if startLo < Hi then QuickSortOnGLA(startLo, Hi); startLo := Lo; until Lo >= startHi; end; procedure TDataPtList.QuickSortOnPrice(startLo, startHi: Integer); var Lo, Hi, pivotPrice: Integer; begin repeat Lo := startLo; Hi := startHi; pivotPrice := DataPt[(Lo + Hi) div 2].Price; repeat while DataPt[Lo].Price < pivotPrice do Inc(Lo); while DataPt[Hi].Price > pivotPrice do Dec(Hi); if Lo <= Hi then begin Exchange(Lo, Hi); Inc(Lo); Dec(Hi); end; until Lo > Hi; if startLo < Hi then QuickSortOnPrice(startLo, Hi); startLo := Lo; until Lo >= startHi; end; procedure TDataPtList.QuickSortOnDOM(startLo, startHi: Integer); var Lo, Hi, pivotDOM: Integer; begin repeat Lo := startLo; Hi := startHi; pivotDOM := DataPt[(Lo + Hi) div 2].DOM; repeat while DataPt[Lo].DOM < pivotDOM do Inc(Lo); while DataPt[Hi].DOM > pivotDOM do Dec(Hi); if Lo <= Hi then begin Exchange(Lo, Hi); Inc(Lo); Dec(Hi); end; until Lo > Hi; if startLo < Hi then QuickSortOnDOM(startLo, Hi); startLo := Lo; until Lo >= startHi; end; procedure TDataPtList.QuickSortOnPricePerGLA(startLo, startHi: Integer); var Lo, Hi: Integer; pivotPPGLA: Real; begin repeat Lo := startLo; Hi := startHi; pivotPPGLA := DataPt[(Lo + Hi) div 2].FPrPerGLA; repeat while DataPt[Lo].FPrPerGLA < pivotPPGLA do Inc(Lo); while DataPt[Hi].FPrPerGLA > pivotPPGLA do Dec(Hi); if Lo <= Hi then begin Exchange(Lo, Hi); Inc(Lo); Dec(Hi); end; until Lo > Hi; if startLo < Hi then QuickSortOnPricePerGLA(startLo, Hi); startLo := Lo; until Lo >= startHi; end; procedure TDataPtList.QuickSortOnS2LRatio(startLo, startHi: Integer); var Lo, Hi: Integer; pivotS2LRatio: Real; begin repeat Lo := startLo; Hi := startHi; pivotS2LRatio := DataPt[(Lo + Hi) div 2].FStoLRatio; repeat while DataPt[Lo].FStoLRatio < pivotS2LRatio do Inc(Lo); while DataPt[Hi].FStoLRatio > pivotS2LRatio do Dec(Hi); if Lo <= Hi then begin Exchange(Lo, Hi); Inc(Lo); Dec(Hi); end; until Lo > Hi; if startLo < Hi then QuickSortOnS2LRatio(startLo, Hi); startLo := Lo; until Lo >= startHi; end; procedure TDataPtList.Analyze; begin if count > 0 then begin AnalyzeGLA; AnalyzePrice; AnalyzeDOM; AnalyzeS2LRatio; AnalyzePrPerGLA; end; end; function TDataPtList.CalcMedianGLA: Integer; var i: Integer; isEven: Boolean; num1, num2: Integer; begin isEven := Count Mod 2 = 0; if isEven then begin i:= trunc(Count/2); num1 := DataPt[i-1].FGLA; num2 := DataPt[i].FGLA; FMedGLA := round((num1+num2)/2); end else begin i:= Round(Count/2); FMedGLA := DataPt[i].FGLA; end; result := FMedGLA; end; procedure TDataPtList.AnalyzeGLA; var ASum: Integer; // debugStr: String; // j: Integer; begin (* debugStr := ''; for j := 0 to count -1 do debugStr := debugStr + IntToStr(DataPt[j].GLA) + ', '; showMessage(debugStr); *) if count > 0 then begin QuickSortOnGLA(0, count-1); FMinGLA := DataPt[0].GLA; FMaxGLA := DataPt[count-1].GLA; ASum := SumGLA; FAvgGLA := Round(ASum/Count); FMedGLA := CalcMedianGLA; end; (* debugStr := ''; for j := 0 to count -1 do debugStr := debugStr + IntToStr(DataPt[j].GLA) + ', '; debugStr := debugStr + 'MED: ' + IntToStr(FMedGLA); showMessage(debugStr); *) end; function TDataPtList.CalcMedianPrice: Integer; var i: Integer; isEven: Boolean; num1, num2: Integer; begin isEven := Count Mod 2 = 0; if isEven then begin i:= trunc(Count/2); num1 := DataPt[i-1].FPrice; num2 := DataPt[i].FPrice; FMedPrice := round((num1+num2)/2); end else begin i:= Round(Count/2); FMedPrice := DataPt[i].FPrice; end; result := FMedPrice; end; procedure TDataPtList.AnalyzePrice; var ASum: Integer; begin if count > 0 then begin QuickSortOnPrice(0, Count-1); FMinPrice := DataPt[0].Price; FMaxPrice := DataPt[count-1].Price; ASum := SumPrice; FAvgPrice := Round(ASum/Count); FMedPrice := CalcMedianPrice; end; end; function TDataPtList.CalcMedianDOM: Integer; var i: Integer; isEven: Boolean; num1, num2: Integer; begin isEven := Count Mod 2 = 0; if isEven then begin i:= trunc(Count/2); num1 := DataPt[i-1].FDOM; num2 := DataPt[i].FDOM; FMedDOM := round((num1+num2)/2); end else begin i:= Round(Count/2); FMedDOM := DataPt[i].FDOM; end; result := FMedDOM; end; procedure TDataPtList.AnalyzeDOM; var ASum: Integer; //i: Integer; // debugStr: String; begin if count > 0 then begin QuickSortOnDOM(0, count-1); FMinDOM := DataPt[0].DOM; FMaxDOM := DataPt[count-1].DOM; ASum := SumDOM; FAvgDOM := Round(ASum/Count); FMedDOM := calcMedianDOM; end; (* debugStr := ''; for i := 0 to count -1 do debugStr := debugStr + IntToStr(DataPt[i].DOM) + ', '; debugStr := debugStr + 'MED: j=' + IntToStr(j) + ', ' + IntToStr(FMedDOM); showMessage('DOM: ' + debugStr); *) end; function TDataPtList.CalcMedianPrPerGLA: Real; var i: Integer; isEven: Boolean; num1, num2: Real; begin isEven := Count Mod 2 = 0; if isEven then begin i:= trunc(Count/2); num1 := DataPt[i-1].PricePerGLA; num2 := DataPt[i].PricePerGLA; FMedPrPerGLA := (num1+num2)/2; end else begin i:= Round(Count/2); FMedPrPerGLA := DataPt[i].PricePerGLA; end; result := FMedPrPerGLA; end; procedure TDataPtList.AnalyzePrPerGLA; var ASum: Real; begin if count > 0 then begin QuickSortOnPricePerGLA(0, count-1); FMinPrPerGLA := DataPt[0].PricePerGLA; FMaxPrPerGLA := DataPt[count-1].PricePerGLA; ASum := SumPrPerGLA; FAvgPrPerGLA := ASum/Count; FMedPrPerGLA := CalcMedianPrPerGLA; end; end; function TDataPtList.CalcMedianS2LRatio: Real; var i: Integer; isEven: Boolean; num1, num2: real; begin isEven := Count Mod 2 = 0; if isEven then begin i:= trunc(Count/2); num1 := DataPt[i-1].Sale2ListRatio; num2 := DataPt[i].Sale2ListRatio; FAvgS2LRatio := round((num1+num2)/2); end else begin i:= Round(Count/2); FAvgS2LRatio := DataPt[i].Sale2ListRatio; end; result := FAvgS2LRatio; end; procedure TDataPtList.AnalyzeS2LRatio; var ASum: Real; // j: Integer; begin if count > 0 then begin QuickSortOnS2LRatio(0, count-1); FMinS2LRatio := DataPt[0].Sale2ListRatio; FMaxS2LRatio := DataPt[count-1].Sale2ListRatio; ASum := SumSale2ListRatio; FAvgS2LRatio := ASum/Count; // j:= Round(Count/2); // FMedS2LRatio := DataPt[j].Sale2ListRatio; FMedS2LRatio := CalcMedianS2LRatio; end; end; function TDataPtList.SumGLA: Integer; var i: Integer; begin result := 0; for i := 0 to count-1 do result := result + DataPt[i].GLA; end; function TDataPtList.SumPrice: Integer; var i: Integer; begin result := 0; for i := 0 to count-1 do result := result + DataPt[i].Price; end; function TDataPtList.SumDOM: Integer; var i: Integer; begin result := 0; for i := 0 to count-1 do result := result + DataPt[i].DOM; end; function TDataPtList.SumPrPerGLA: Real; var i: Integer; begin result := 0; for i := 0 to count-1 do result := result + DataPt[i].PricePerGLA; end; function TDataPtList.SumSale2ListRatio: Real; var i: Integer; begin result := 0; for i := 0 to count-1 do result := result + DataPt[i].Sale2ListRatio; end; { TTimePeriod } constructor TTimePeriod.Create; begin inherited; FSales := TSales.Create(True); FListings := TListings.Create(True); end; destructor TTimePeriod.Destroy; begin if assigned(FSales) then FSales.free; if assigned(FListings) then FListings.free; inherited; end; procedure TTimePeriod.Analyze; begin Sales.Analyze; Listings.Analyze; //do calculations FAbsorbRate := FSales.Count / FMoInPeriod; //absorption Rate (sales/months in period) FMosSupply := 0; if FAbsorbRate > 0 then FMosSupply := FListings.Count / FAbsorbRate; //Months supply (active listing/absorption rate) end; { TTimePeriodList } function TTimePeriodList.GetTimePeriod(Index: Integer): TTimePeriod; begin result := TTimePeriod(inherited Items[index]); end; procedure TTimePeriodList.SetTimePeriod(Index: Integer; const Value: TTimePeriod); begin inherited Insert(Index, Value); end; procedure TTimePeriodList.Analyze; var i: Integer; begin for i := 0 to count -1 do Period[i].Analyze; end; { TTrendAnalyzer } constructor TTrendAnalyzer.Create; begin inherited; FStartDate := Now; FPendingAsSold := False; FActiveListingOnly := True; FHas12PeriodData := False; FTrendInterval := tdLast3Months; FDataPts := TDataPtList.Create(True); //it owns the data points FPeriods := TTimePeriodList.Create(True); //it owns the period objects FTrends := TTrendLineList.Create(True); //it owns the trend line objects end; destructor TTrendAnalyzer.Destroy; begin if assigned(FDataPts) then FDataPts.free; if assigned(FPeriods) then FPeriods.free; if assigned(FTrends) then FTrends.free; inherited; end; //check function TTrendAnalyzer.EmptySalesListingPrice: Boolean; var i, dpCount, cnt: Integer; begin result := False; cnt := 0; if FDataPts.Count = 0 then exit; dpCount := FDataPts.Count; for i:= 0 to FDataPts.Count - 1 do begin if FDataPts[i].FPrice = 0 then inc(cnt); end; if cnt = dpCount then result := True; end; procedure TTrendAnalyzer.BuildTimePeriodList; begin if assigned(FPeriods) then FPeriods.Clear; case FPeriodType of tp12MonthPeriods: Build12MonthPeriodList; tpQuarterPeriods: Build4QuarterPeriodList; tp1004MCPeriods: Build1004MCPeriodList; else Build1004MCPeriodList; end; end; procedure TTrendAnalyzer.Build1004MCPeriodList; var APeriod: TTimePeriod; startDate, endDate: TDateTime; begin //current to 3 months endDate := TrendStartDate; startDate := incDay(incMonth(endDate,-3),1); APeriod := TTimePeriod.Create; APeriod.BeginDate := startDate; APeriod.EndDate := endDate; APeriod.FMoInPeriod := Round(MonthSpan(endDate, startDate)); Periods.Add(APeriod); //4-6 months endDate := incMonth(TrendStartDate, - 3); startDate := incDay(incMonth(endDate,-3),1); APeriod := TTimePeriod.Create; APeriod.BeginDate := startDate; APeriod.EndDate := endDate; APeriod.FMoInPeriod := Round(MonthSpan(endDate, startDate)); Periods.Insert(0, APeriod); //12-7 momths endDate := incMonth(TrendStartDate, - 6); startDate := incDay(incMonth(endDate,-6),1); APeriod := TTimePeriod.Create; APeriod.BeginDate := startDate; APeriod.EndDate := endDate; APeriod.FMoInPeriod := Round(MonthSpan(endDate, startDate)); Periods.Insert(0, APeriod); end; procedure TTrendAnalyzer.Build12MonthPeriodList; var i: Integer; startDate, endDate: TDateTime; APeriod: TTimePeriod; begin for i := 1 to 12 do begin endDate := incMonth(TrendStartDate, -(i-1)*1); startDate := incDay(incMonth(endDate, -1), 1); APeriod := TTimePeriod.Create; APeriod.BeginDate := startDate; APeriod.EndDate := endDate; APeriod.FMoInPeriod := Round(MonthSpan(endDate, startDate)); Periods.Insert(0, APeriod); end; end; procedure TTrendAnalyzer.Build4QuarterPeriodList; var i: Integer; startDate, endDate: TDateTime; APeriod: TTimePeriod; begin for i := 1 to 4 do begin endDate := incMonth(TrendStartDate, -(i-1)*3); startDate := incDay(incMonth(endDate,-3),1); APeriod := TTimePeriod.Create; APeriod.BeginDate := startDate; APeriod.EndDate := endDate; APeriod.FMoInPeriod := Round(MonthSpan(endDate, startDate)); Periods.Insert(0, APeriod); end; end; procedure TTrendAnalyzer.CalcPeriodTimeAdjustments; var curMedSalePrice: Integer; curAvgSalePrice: Integer; p, numPs: Integer; begin numPs := Periods.Count; if numPs > 0 then begin curMedSalePrice := Periods[numPs-1].Sales.MedianPrice; curAvgSalePrice := Periods[numPs-1].Sales.AvgPrice; for p := 0 to numPs-1 do begin if curMedSalePrice > 0 then Periods[p].Sales.MedianTimeAdjPercent := ((curMedSalePrice - Periods[p].Sales.MedianPrice)/curMedSalePrice)* 100; if curAvgSalePrice > 0 then Periods[p].Sales.AvgTimeAdjPercent := ((curAvgSalePrice - Periods[p].Sales.AvgPrice)/curAvgSalePrice)* 100; end; end; end; function TTrendAnalyzer.CalcTrendLine(ATrendID, ATrendPeriod: Integer; const Y: ArrayOf12Reals): TTrendLine; const Alpha = 0.05; { Significance level } var XX, YY : PVector; { Data } Ycalc : PVector; { Computed Y values } B : PVector; { Regression parameters } V : PMatrix; { Variance-covariance matrix } //Test : TRegTest; { Statistical tests } //Tc : Float; { Critical t value } //Fc : Float; { Critical F value } I, N, Xn, X1, X2: Integer; VStart, VEnd: Real; begin result := TTrendLine.Create; case ATrendPeriod of tdLast3Months: begin N := 3; //sample size X1 := 10; X2 := 12; end; tdLast6Months: begin N := 6; X1 := 7; X2 := 12; end; tdLast12Months: begin N := 12; X1 := 1; X2 := 12; end; else begin N := 12; X1 := 1; X2 := 12; end; end; //allocate space for vectors and matrix DimVector(XX, N); DimVector(YY, N); DimVector(Ycalc, N); DimVector(B, 1); DimMatrix(V, 1, 1); try Xn := X1; for I := 1 to N do begin XX^[I] := I; //evenly spaced interval YY^[I] := Y[Xn]; Xn := Xn + 1; end; LinFit(XX, YY, 1, N, B, V); //Perform regression by standard method for I := 1 to N do Ycalc^[I] := B^[0] + B^[1] * XX^[I]; //Compute predicted Y values result.TrendID := ATrendID; result.PeriodTyp := ATrendPeriod; //3 mos, 6 mos, 12 mos result.X1 := X1; result.Y1 := Ycalc^[1]; result.Y2 := Ycalc^[N]; result.X2 := X2; result.AConst := B^[0]; //the line (y-intercept) result.Velocity := B^[1]; //slope of the line (* { Update variance-covariance matrix and compute statistical tests } RegTest(YY, Ycalc, 1, N, V, 0, 1, Test); { Compute Student's t and Snedecor's F } Tc := InvStudent(N - 2, 1 - 0.5 * Alpha); Fc := InvSnedecor(1, N - 2, 1 - Alpha); *) //calc the percent change using actual values result.X1Act := Y[X1]; //remember values for commentary result.X2Act := Y[X2]; if Y[X1] <> 0 then result.PctChgActual := (Y[X2] - Y[X1])/Y[X1] * 100 else result.PctChgActual := Y[X2]; //calc the percent change using the trend line values // VStart := B^[0] + B^[1] * X1; //y = a + b*x // VEnd := B^[0] + B^[1] * X2; VStart := result.Y1; //remember values for commentary VEnd := result.Y2; if VStart <> 0 then result.PctChgTrend := (VEnd - VStart)/VStart * 100 else result.PctChgTrend := VEnd; finally DelVector(XX, N); DelVector(YY, N); DelVector(Ycalc, N); DelVector(B, 1); DelMatrix(V, 1, 1); end; end; procedure TTrendAnalyzer.CalcTotalSalesTrendLines; var YValue: ArrayOf12Reals; i: Integer; begin for i := 1 to 12 do YValue[i] := Periods[i-1].Sales.Count; Trends.Add(CalcTrendLine(ttTotalSales, tdLast3Months, YValue)); Trends.Add(CalcTrendLine(ttTotalSales, tdLast6Months, YValue)); Trends.Add(CalcTrendLine(ttTotalSales, tdLast12Months, YValue)); end; procedure TTrendAnalyzer.CalcTotalListingsTrendLines; var YValue: ArrayOf12Reals; i: Integer; begin for i := 1 to 12 do YValue[i] := Periods[i-1].Listings.Count; Trends.Add(CalcTrendLine(ttTotalListings, tdLast3Months, YValue)); Trends.Add(CalcTrendLine(ttTotalListings, tdLast6Months, YValue)); Trends.Add(CalcTrendLine(ttTotalListings, tdLast12Months, YValue)); end; procedure TTrendAnalyzer.CalcSalePriceTrendLines; var YValue: ArrayOf12Reals; i: Integer; begin for i := 1 to 12 do YValue[i] := Periods[i-1].Sales.MedianPrice; Trends.Add(CalcTrendLine(ttSalePrice, tdLast3Months, YValue)); Trends.Add(CalcTrendLine(ttSalePrice, tdLast6Months, YValue)); Trends.Add(CalcTrendLine(ttSalePrice, tdLast12Months, YValue)); end; procedure TTrendAnalyzer.CalcAbsorptionRateTrendLines; var YValue: ArrayOf12Reals; i: Integer; begin for i := 1 to 12 do YValue[i] := Periods[i-1].AbsorptionRate; Trends.Add(CalcTrendLine(ttAbsorptionRate, tdLast3Months, YValue)); Trends.Add(CalcTrendLine(ttAbsorptionRate, tdLast6Months, YValue)); Trends.Add(CalcTrendLine(ttAbsorptionRate, tdLast12Months, YValue)); end; procedure TTrendAnalyzer.CalcMonthsSupplyTrendLines; var YValue: ArrayOf12Reals; i: Integer; begin for i := 1 to 12 do YValue[i] := Periods[i-1].MonthsSupply; Trends.Add(CalcTrendLine(ttMonthsSupply, tdLast3Months, YValue)); Trends.Add(CalcTrendLine(ttMonthsSupply, tdLast6Months, YValue)); Trends.Add(CalcTrendLine(ttMonthsSupply, tdLast12Months, YValue)); end; procedure TTrendAnalyzer.CalcListingPriceTrendLines; var YValue: ArrayOf12Reals; i: Integer; begin for i := 1 to 12 do YValue[i] := Periods[i-1].Listings.MedianPrice; Trends.Add(CalcTrendLine(ttListPrice, tdLast3Months, YValue)); Trends.Add(CalcTrendLine(ttListPrice, tdLast6Months, YValue)); Trends.Add(CalcTrendLine(ttListPrice, tdLast12Months, YValue)); end; procedure TTrendAnalyzer.CalcSalePricePerSqftTrendLines; var YValue: ArrayOf12Reals; i: Integer; begin for i := 1 to 12 do YValue[i] := Periods[i-1].Sales.MedianPrPerGLA; Trends.Add(CalcTrendLine(ttPricePerSqft, tdLast3Months, YValue)); Trends.Add(CalcTrendLine(ttPricePerSqft, tdLast6Months, YValue)); Trends.Add(CalcTrendLine(ttPricePerSqft, tdLast12Months, YValue)); end; procedure TTrendAnalyzer.CalcSalesDOMTrendLines; var YValue: ArrayOf12Reals; i: Integer; begin for i := 12 downto 1 do YValue[i] := Periods[i-1].Sales.MedianDOM; Trends.Add(CalcTrendLine(ttSalesDOM, tdLast3Months, YValue)); Trends.Add(CalcTrendLine(ttSalesDOM, tdLast6Months, YValue)); Trends.Add(CalcTrendLine(ttSalesDOM, tdLast12Months, YValue)); end; procedure TTrendAnalyzer.CalcListingDOMTrendLines; var YValue: ArrayOf12Reals; i: Integer; begin for i := 12 downto 1 do YValue[i] := Periods[i-1].Listings.MedianDOM; Trends.Add(CalcTrendLine(ttListingDOM, tdLast3Months, YValue)); Trends.Add(CalcTrendLine(ttListingDOM, tdLast6Months, YValue)); Trends.Add(CalcTrendLine(ttListingDOM, tdLast12Months, YValue)); end; procedure TTrendAnalyzer.CalcSaleToListRatioTrendLines; var YValue: ArrayOf12Reals; i: Integer; begin for i := 12 downto 1 do YValue[i] := Periods[i-1].Sales.MedianSaleToListRatio; Trends.Add(CalcTrendLine(ttSaleToListRatio, tdLast3Months, YValue)); Trends.Add(CalcTrendLine(ttSaleToListRatio, tdLast6Months, YValue)); Trends.Add(CalcTrendLine(ttSaleToListRatio, tdLast12Months, YValue)); end; procedure TTrendAnalyzer.CalcAllTrendLines; begin Trends.Clear; //get rid of the previous results if FHas12PeriodData then begin CalcTotalSalesTrendLines; CalcTotalListingsTrendLines; CalcSalePriceTrendLines; CalcListingPriceTrendLines; CalcSalesDOMTrendLines; CalcListingDOMTrendLines; CalcSalePricePerSqftTrendLines; CalcAbsorptionRateTrendLines; CalcMonthsSupplyTrendLines; CalcSaleToListRatioTrendLines; end; end; procedure TTrendAnalyzer.Analyze; begin Periods.Clear; //delete any prevous periods from the list BuildTimePeriodList; LoadSalesAndListingsToPeriods; Periods.Analyze; //perform analysis on sales and listings CalcPeriodTimeAdjustments; //must be done AFTER periods.analyze //this flag to let TrendLines do calculations & display on chart FHas12PeriodData := (tp12MonthPeriods = FPeriodType); //we analyzed 12 periods of data end; procedure TTrendAnalyzer.LoadSalesAndListingsToPeriods; var i, numPts: Integer; ADataPt: TDataPt; begin numPts := DataPts.count -1; for i := 0 to numPts do begin ADataPt := DataPts[i]; //assign the sales to the sale list if ADataPt.Status = lsSold then AddSalesToTimePeriods(ADataPt); //assign the listings to the listing list, check for pending as sold if PendingAsSold and (ADataPt.Status = lsPending) then AddSalesToTimePeriods(ADataPt) else begin //For Active Listings Only: include active and sold // if ActiveListingOnly and ((ADataPt.Status = lsActive) or (ADataPt.Status = lsSold)) then // AddListingsToTimePeriods(ADataPt) //Include all // else if not ActiveListingOnly then AddListingsToTimePeriods(ADataPt); end; end; end; procedure TTrendAnalyzer.AddSalesToTimePeriods(ADataPt: TDataPt); var p, numPs: Integer; APeriod: TTimePeriod; ASale: TDataPt; begin numPs := Periods.Count -1; for p := 0 to numPs do begin APeriod := Periods[p]; if (APeriod.BeginDate <= ADataPt.StatDate) and (ADataPt.StatDate <= APeriod.EndDate) then begin ASale := TDataPt.Create; ASale.Assign(ADataPt); APeriod.Sales.Add(ASale); break; end; end; end; procedure TTrendAnalyzer.AddListingsToTimePeriods(ADataPt: TDataPt); var p, numPs: Integer; APeriod: TTimePeriod; AListing: TDataPt; //an active listing begin numPs := Periods.Count -1; for p := 0 to numPs do begin APeriod := Periods[p]; //test the data EndDate in each period if (ADataPt.ListDate <= APeriod.EndDate) and (ADataPt.StatDate >= APeriod.EndDate) then begin //found an active listing at this period's END boundary AListing := TDataPt.Create; AListing.Assign(ADataPt); AListing.DOM := DaysBetween(APeriod.EndDate, AListing.ListDate); APeriod.Listings.Add(AListing); end; end; end; { TTrendLineList } function TTrendLineList.GetTrendLine(Index: Integer): TTrendLine; begin result := TTrendLine(inherited Items[index]); end; procedure TTrendLineList.SetTrendLine(Index: Integer; const Value: TTrendLine); begin inherited Insert(Index, Value); end; function TTrendLineList.GetTrendLineByID(ATendID, ATrendPeriod: Integer): TTrendLine; var t: Integer; ATrend: TTrendLine; begin result := nil; for t := 0 to Count-1 do begin ATrend := Trend[t]; if (ATrend.TrendID = ATendID) and (ATrend.PeriodTyp = ATrendPeriod) then begin result := ATrend; break; end; end; end; function TTrendLineList.GetTrendVelocityByID(ATendID, ATrendPeriod: Integer): Real; var ATrendLine: TTrendLine; begin result := 0; ATrendLine := GetTrendLineByID(ATendID, ATrendPeriod); if assigned(ATrendLine) then result := ATrendLine.Velocity; end; function TTrendLineList.GetTrendPercentChangeByID(ATendID, ATrendPeriod: Integer): Real; var ATrendLine: TTrendLine; begin result := 0; ATrendLine := GetTrendLineByID(ATendID, ATrendPeriod); if assigned(ATrendLine) then result := ATrendLine.PctChgTrend; //could use Actual percent change end; function TTrendLineList.GetTrendRateOfChangeStrByID(ATendID, ATrendPeriod: Integer): String; var velocity: Real; changeStr: String; (* function SignOfStr(AChange: Real): String; begin case Sign(AChange) of 1: result := '+ '; 0: result := ''; -1: result := ''; end; end; *) begin changeStr := ''; velocity := GetTrendVelocityByID(ATendID, ATrendPeriod); case ATendID of ttSalePrice: changeStr := FloatToStr(RoundTo(velocity, 0)) + '/mo'; //FloatToStr(velocity); //SignOfStr(RoundTo(velocity, 0)) + ttListPrice: changeStr := FloatToStr(RoundTo(velocity, 0)) + '/mo'; //FloatToStr(velocity); //SignOfStr(RoundTo(velocity, 0)) + ttTotalSales: changeStr := FloatToStr(RoundTo(velocity, -1)) + '/mo'; //FloatToStr(velocity); //SignOfStr(RoundTo(velocity, 1)) + ttTotalListings: changeStr := FloatToStr(RoundTo(velocity, -1)) + '/mo'; //FloatToStr(velocity); //SignOfStr(RoundTo(velocity, 1)) + ttPricePerSqft: changeStr := FloatToStr(RoundTo(velocity, -2)) + '/mo'; //FloatToStr(velocity); //SignOfStr(RoundTo(velocity, 2)) + ttAbsorptionRate: changeStr := FloatToStr(RoundTo(velocity, -1)) + '/mo'; //FloatToStr(velocity); //SignOfStr(RoundTo(velocity, 2)) + ttMonthsSupply: changeStr := FloatToStr(RoundTo(velocity, -1)) + '/mo'; //FloatToStr(velocity); //SignOfStr(RoundTo(velocity, 1)) + ttSalesDOM: changeStr := FloatToStr(RoundTo(velocity, -1)) + '/mo'; //FloatToStr(velocity); //SignOfStr(RoundTo(velocity, 0)) + ttListingDOM: changeStr := FloatToStr(RoundTo(velocity, -1)) + '/mo'; //FloatToStr(velocity); //SignOfStr(RoundTo(velocity, 0)) + ttSaleToListRatio: changeStr := FloatToStr(RoundTo(velocity, -2)) + '/mo'; //FloatToStr(velocity); //SignOfStr(RoundTo(velocity, 2)) + end; result := changeStr; end; function TTrendLineList.GetTrendPercentChangeStrByID(ATendID, ATrendPeriod: Integer): String; var Percent: Real; percentStr: String; function GetSpecialRounding(APercent: Real): Real; begin if abs(APercent) > 25 then result := RoundTo(Percent, 0) else result := RoundTo(Percent, -1); end; begin percentStr := ''; Percent := GetTrendPercentChangeByID(ATendID, ATrendPeriod); case ATendID of ttSalePrice: percentStr := FloatToStr(GetSpecialRounding(Percent)) + '%'; ttListPrice: percentStr := FloatToStr(GetSpecialRounding(Percent)) + '%'; ttTotalSales: percentStr := FloatToStr(GetSpecialRounding(Percent)) + '%'; ttTotalListings: percentStr := FloatToStr(GetSpecialRounding(Percent)) + '%'; ttPricePerSqft: percentStr := FloatToStr(GetSpecialRounding(Percent)) + '%'; ttAbsorptionRate: percentStr := FloatToStr(GetSpecialRounding(Percent)) + '%'; ttMonthsSupply: percentStr := FloatToStr(GetSpecialRounding(Percent)) + '%'; ttSalesDOM: percentStr := FloatToStr(GetSpecialRounding(Percent)) + '%'; ttListingDOM: percentStr := FloatToStr(GetSpecialRounding(Percent)) + '%'; ttSaleToListRatio: percentStr := FloatToStr(GetSpecialRounding(Percent)) + '%'; end; result := percentStr; end; end.
{ **************************************************************************** } { } { Unit testing Framework for SmartPascal and DWScript } { } { Copyright (c) Eric Grange, Creative IT. All rights reserved. } { Licensed to Optimale Systemer AS. } { } { **************************************************************************** } unit TestFramework; interface type TestStatus = enum (NotRun, Running, Failed, Passed); TAbstractTestCase = class; ITestListener = interface procedure BeginTest(test : TAbstractTestCase); procedure EndTest(test : TAbstractTestCase); procedure Failed(test : TAbstractTestCase; msg : String); end; TAbstractTestCase = class private FListener : ITestListener; protected property Listener : ITestListener read FListener; public constructor Create; virtual; empty; property Name : String; property Disabled : Boolean; property Enabled : Boolean read (not Disabled) write (Disabled:=not Value); property Status : TestStatus; property Failed : Boolean read (Status=TestStatus.Failed); property Passed : Boolean read (Status=TestStatus.Passed); property BeginTime : Float; property EndTime : Float; property Elapsed : Float read (EndTime-BeginTime); property NbChecks : Integer; procedure Run(listener : ITestListener); procedure DoRun; virtual; empty; procedure Setup; virtual; empty; procedure Teardown; virtual; empty; property ActiveTest : TAbstractTestCase; procedure Pass; procedure Fail(msg : String); overload; procedure Fail(fmt : String; const args : array of const; msg : String); overload; procedure Check(v : Boolean; msg : String = ''); overload; procedure Equal(expected, actual : Integer; msg : String = ''); overload; procedure Equal(expected, actual : Float; msg : String = ''); overload; procedure Equal(expected, actual : String; msg : String = ''); overload; procedure Equal(expected, actual : Boolean; msg : String = ''); overload; procedure Equal(expected, actual : TObject; msg : String = ''); overload; procedure CheckNoException(proc : procedure; msg : String); end; TAbstractTestCases = array of TAbstractTestCase; TAbstractTestCaseClass = class of TAbstractTestCase; TTestSuite = class (TAbstractTestCase) private FTests : TAbstractTestCases; protected public property Tests : TAbstractTestCases read FTests; procedure Add(test : TAbstractTestCase); procedure DoRun; override; end; TTestCase = class (TTestSuite) public constructor Create; override; end; TTestFrameWork = static class private class var vSuites : TTestSuite; public class procedure Register(const suiteName : String; aTest : TAbstractTestCaseClass); class property Suites[idx : Integer] : TTestSuite read (vSuites.Tests[idx] as TTestSuite); class property Count : Integer read (vSuites.Tests.Count); class procedure Run(listener : ITestListener); end; TMethodTestCase = class (TAbstractTestCase) private FCase : TTestCase; FMethod : RTTIMethodAttribute; public procedure DoRun; override; end; ETestFailure = class(Exception); implementation uses W3C.Console; (* ═══════════════════════════════════════════════════════ TAbstractTestCase ═══════════════════════════════════════════════════════*) procedure TAbstractTestCase.Run(listener: ITestListener); begin FListener:=listener; listener.BeginTest(Self); NbChecks:=0; Status:=TestStatus.Running; ActiveTest:=Self; try CheckNoException(Setup, 'Setup failed'); DoRun; if (NbChecks=0) and not Failed then begin Status:=TestStatus.Failed; listener.Failed(Self, 'No checks'); end; CheckNoException(Teardown, 'Teardown failed'); except on E : ETestFailure do ; on E : Exception do begin Status:=TestStatus.Failed; listener.Failed(Self, E.ClassName+': '+E.Message); end; end; if Status=TestStatus.Running then Status:=TestStatus.Passed; listener.EndTest(Self); FListener:=nil; end; procedure TAbstractTestCase.Pass; begin NbChecks:=NbChecks+1; end; procedure TAbstractTestCase.Fail(msg: String); begin NbChecks:=NbChecks+1; ActiveTest.Status:=TestStatus.Failed; FListener.Failed(ActiveTest, msg); raise ETestFailure.Create(msg); end; procedure TAbstractTestCase.Fail(fmt: String; const args: array of const; msg: String); begin if msg='' then Fail(Format(fmt, args)) else Fail(Format(fmt, args)+', '+msg); end; procedure TAbstractTestCase.Check(v: Boolean; msg: String = ''); begin if v then Pass else Fail(msg); end; procedure TAbstractTestCase.Equal(expected, actual: Integer; msg: String = ''); begin if expected=actual then Pass else Fail('%d expected but got %d', [expected, actual], msg); end; procedure TAbstractTestCase.Equal(expected, actual: Float; msg: String = ''); begin if expected=actual then Pass else Fail('%f expected but got %f', [expected, actual], msg); end; procedure TAbstractTestCase.Equal(expected, actual: String; msg: String = ''); begin if expected=actual then Pass else Fail('<%s> expected but got <%s>', [expected, actual], msg); end; procedure TAbstractTestCase.Equal(expected, actual: Boolean; msg: String = ''); begin if expected=actual then Pass else Fail( BoolToStr(expected)+' expected but got '+BoolToStr(actual) +if msg<>'' then (', '+msg)); end; procedure TAbstractTestCase.Equal(expected, actual: TObject; msg: String = ''); begin if expected=actual then Pass else Fail('Object mismatch', [], msg); end; procedure TAbstractTestCase.CheckNoException(proc: procedure; msg: String); begin try proc(); Pass; except on E : Exception do Fail('%s: %s', [E.ClassName, E.Message], msg); end; end; (* ═══════════════════════════════════════════════════════ TTestSuite ═══════════════════════════════════════════════════════*) procedure TTestSuite.Add(test: TAbstractTestCase); begin FTests.Add(test); end; procedure TTestSuite.DoRun; var test : TAbstractTestCase; begin try for test in FTests do begin if test.Disabled then continue; ActiveTest:=test; test.Run(Listener); if test.Failed then Status:=TestStatus.Failed; end; finally ActiveTest:=Self; end; end; (* ═══════════════════════════════════════════════════════ TTestFrameWork ═══════════════════════════════════════════════════════*) class procedure TTestFrameWork.Register(const suiteName: String; aTest: TAbstractTestCaseClass); begin if not Assigned(vSuites) then begin vSuites:=TTestSuite.Create; vSuites.Name:='TestFramework'; end; var suite : TTestSuite; for var i := 0 to vSuites.Tests.Count-1 do begin if vSuites.Tests[i].Name = 'suiteName' then begin suite := vSuites.Tests[i] as TTestSuite; break; end; end; if suite = nil then begin suite := TTestSuite.Create; suite.Name := suiteName; vSuites.Add(suite); end; var test := aTest.Create; test.Name := aTest.ClassName; suite.Add(test); end; class procedure TTestFrameWork.Run(listener: ITestListener); begin if Assigned(vSuites) then vSuites.Run(listener); end; (* ═══════════════════════════════════════════════════════ TTestFrameWork ═══════════════════════════════════════════════════════*) constructor TTestCase.Create; begin var rtti := RTTIRawAttributes; var typeID := TypeOf(ClassType); for var i:=Low(rtti) to High(rtti) do begin var attrib := rtti[i]; if (variant(attrib).T.ID = variant(typeID).ID) and (attrib.A.ClassType = RTTIMethodAttribute) then begin var test := TMethodTestCase.Create; test.FMethod := RTTIMethodAttribute(attrib.A); test.FCase := Self; test.Name := test.FMethod.Name; //console.log(test.Name); Add(test); end; end; end; (* ═══════════════════════════════════════════════════════ TMethodTestCase ═══════════════════════════════════════════════════════*) procedure TMethodTestCase.DoRun; begin FMethod.Call(FCase, []); end; end.
// ************************************************************************ // // The types declared in this file were generated from data read from the // WSDL File described below: // WSDL : http://10.0.0.43/WSClfPictometry/PictometryService.asmx?WSDL // >Import : http://10.0.0.43/WSClfPictometry/PictometryService.asmx?WSDL:0 // Encoding : utf-8 // Version : 1.0 // (11/13/2014 12:06:11 PM - - $Rev: 10138 $) // ************************************************************************ // unit PictometryService; interface uses InvokeRegistry, SOAPHTTPClient, Types, XSBuiltIns; const IS_OPTN = $0001; IS_REF = $0080; type // ************************************************************************ // // The following types, referred to in the WSDL document are not being represented // in this file. They are either aliases[@] of other types represented or were referred // to but never[!] declared in the document. The types from the latter category // typically map to predefined/known XML or Borland types; however, they could also // indicate incorrect WSDL documents that failed to declare or import a schema type. // ************************************************************************ // // !:string - "http://www.w3.org/2001/XMLSchema"[Gbl] // !:int - "http://www.w3.org/2001/XMLSchema"[Gbl] // !:base64Binary - "http://www.w3.org/2001/XMLSchema"[Gbl] PictometryAddress = class; { "http://bradfordsoftware.com/"[GblCplx] } PictometrySearchModifiers = class; { "http://bradfordsoftware.com/"[GblCplx] } PictometryMaps = class; { "http://bradfordsoftware.com/"[GblCplx] } UserCredentials = class; { "http://bradfordsoftware.com/"[Hdr][GblCplx] } UserCredentials2 = class; { "http://bradfordsoftware.com/"[Hdr][GblElm] } // ************************************************************************ // // XML : PictometryAddress, global, <complexType> // Namespace : http://bradfordsoftware.com/ // ************************************************************************ // PictometryAddress = class(TRemotable) private FstreetAddress: WideString; FstreetAddress_Specified: boolean; Fcity: WideString; Fcity_Specified: boolean; Fstate: WideString; Fstate_Specified: boolean; Fzip: WideString; Fzip_Specified: boolean; procedure SetstreetAddress(Index: Integer; const AWideString: WideString); function streetAddress_Specified(Index: Integer): boolean; procedure Setcity(Index: Integer; const AWideString: WideString); function city_Specified(Index: Integer): boolean; procedure Setstate(Index: Integer; const AWideString: WideString); function state_Specified(Index: Integer): boolean; procedure Setzip(Index: Integer; const AWideString: WideString); function zip_Specified(Index: Integer): boolean; published property streetAddress: WideString Index (IS_OPTN) read FstreetAddress write SetstreetAddress stored streetAddress_Specified; property city: WideString Index (IS_OPTN) read Fcity write Setcity stored city_Specified; property state: WideString Index (IS_OPTN) read Fstate write Setstate stored state_Specified; property zip: WideString Index (IS_OPTN) read Fzip write Setzip stored zip_Specified; end; // ************************************************************************ // // XML : PictometrySearchModifiers, global, <complexType> // Namespace : http://bradfordsoftware.com/ // ************************************************************************ // PictometrySearchModifiers = class(TRemotable) private FMapWidth: Integer; FMapHeight: Integer; FMapQuality: Integer; published property MapWidth: Integer read FMapWidth write FMapWidth; property MapHeight: Integer read FMapHeight write FMapHeight; property MapQuality: Integer read FMapQuality write FMapQuality; end; // ************************************************************************ // // XML : PictometryMaps, global, <complexType> // Namespace : http://bradfordsoftware.com/ // ************************************************************************ // PictometryMaps = class(TRemotable) private FNorthView: TByteDynArray; FNorthView_Specified: boolean; FEastView: TByteDynArray; FEastView_Specified: boolean; FSouthView: TByteDynArray; FSouthView_Specified: boolean; FWestView: TByteDynArray; FWestView_Specified: boolean; FOrthogonalView: TByteDynArray; FOrthogonalView_Specified: boolean; procedure SetNorthView(Index: Integer; const ATByteDynArray: TByteDynArray); function NorthView_Specified(Index: Integer): boolean; procedure SetEastView(Index: Integer; const ATByteDynArray: TByteDynArray); function EastView_Specified(Index: Integer): boolean; procedure SetSouthView(Index: Integer; const ATByteDynArray: TByteDynArray); function SouthView_Specified(Index: Integer): boolean; procedure SetWestView(Index: Integer; const ATByteDynArray: TByteDynArray); function WestView_Specified(Index: Integer): boolean; procedure SetOrthogonalView(Index: Integer; const ATByteDynArray: TByteDynArray); function OrthogonalView_Specified(Index: Integer): boolean; published property NorthView: TByteDynArray Index (IS_OPTN) read FNorthView write SetNorthView stored NorthView_Specified; property EastView: TByteDynArray Index (IS_OPTN) read FEastView write SetEastView stored EastView_Specified; property SouthView: TByteDynArray Index (IS_OPTN) read FSouthView write SetSouthView stored SouthView_Specified; property WestView: TByteDynArray Index (IS_OPTN) read FWestView write SetWestView stored WestView_Specified; property OrthogonalView: TByteDynArray Index (IS_OPTN) read FOrthogonalView write SetOrthogonalView stored OrthogonalView_Specified; end; // ************************************************************************ // // XML : UserCredentials, global, <complexType> // Namespace : http://bradfordsoftware.com/ // Info : Header // ************************************************************************ // UserCredentials = class(TSOAPHeader) private FCustID: WideString; FCustID_Specified: boolean; FPassword: WideString; FPassword_Specified: boolean; procedure SetCustID(Index: Integer; const AWideString: WideString); function CustID_Specified(Index: Integer): boolean; procedure SetPassword(Index: Integer; const AWideString: WideString); function Password_Specified(Index: Integer): boolean; published property CustID: WideString Index (IS_OPTN) read FCustID write SetCustID stored CustID_Specified; property Password: WideString Index (IS_OPTN) read FPassword write SetPassword stored Password_Specified; end; // ************************************************************************ // // XML : UserCredentials, global, <element> // Namespace : http://bradfordsoftware.com/ // Info : Header // ************************************************************************ // UserCredentials2 = class(UserCredentials) private published end; // ************************************************************************ // // Namespace : http://bradfordsoftware.com/ // soapAction: http://bradfordsoftware.com/SearchByAddress // transport : http://schemas.xmlsoap.org/soap/http // style : document // binding : PictometryServiceSoap // service : PictometryService // port : PictometryServiceSoap // URL : http://10.0.0.43/WSClfPictometry/PictometryService.asmx // ************************************************************************ // PictometryServiceSoap = interface(IInvokable) ['{8B1AEEE3-BFFA-C30B-EA78-7358EDDB2E5B}'] // Headers: UserCredentials:pIn function SearchByAddress(const ipAddress: PictometryAddress; const ipSearchModifiers: PictometrySearchModifiers): PictometryMaps; stdcall; end; function GetPictometryServiceSoap(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): PictometryServiceSoap; implementation uses SysUtils; function GetPictometryServiceSoap(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): PictometryServiceSoap; const defWSDL = 'http://10.0.0.43/WSClfPictometry/PictometryService.asmx?WSDL'; defURL = 'http://10.0.0.43/WSClfPictometry/PictometryService.asmx'; defSvc = 'PictometryService'; defPrt = 'PictometryServiceSoap'; var RIO: THTTPRIO; begin Result := nil; if (Addr = '') then begin if UseWSDL then Addr := defWSDL else Addr := defURL; end; if HTTPRIO = nil then RIO := THTTPRIO.Create(nil) else RIO := HTTPRIO; try Result := (RIO as PictometryServiceSoap); if UseWSDL then begin RIO.WSDLLocation := Addr; RIO.Service := defSvc; RIO.Port := defPrt; end else RIO.URL := Addr; finally if (Result = nil) and (HTTPRIO = nil) then RIO.Free; end; end; procedure PictometryAddress.SetstreetAddress(Index: Integer; const AWideString: WideString); begin FstreetAddress := AWideString; FstreetAddress_Specified := True; end; function PictometryAddress.streetAddress_Specified(Index: Integer): boolean; begin Result := FstreetAddress_Specified; end; procedure PictometryAddress.Setcity(Index: Integer; const AWideString: WideString); begin Fcity := AWideString; Fcity_Specified := True; end; function PictometryAddress.city_Specified(Index: Integer): boolean; begin Result := Fcity_Specified; end; procedure PictometryAddress.Setstate(Index: Integer; const AWideString: WideString); begin Fstate := AWideString; Fstate_Specified := True; end; function PictometryAddress.state_Specified(Index: Integer): boolean; begin Result := Fstate_Specified; end; procedure PictometryAddress.Setzip(Index: Integer; const AWideString: WideString); begin Fzip := AWideString; Fzip_Specified := True; end; function PictometryAddress.zip_Specified(Index: Integer): boolean; begin Result := Fzip_Specified; end; procedure PictometryMaps.SetNorthView(Index: Integer; const ATByteDynArray: TByteDynArray); begin FNorthView := ATByteDynArray; FNorthView_Specified := True; end; function PictometryMaps.NorthView_Specified(Index: Integer): boolean; begin Result := FNorthView_Specified; end; procedure PictometryMaps.SetEastView(Index: Integer; const ATByteDynArray: TByteDynArray); begin FEastView := ATByteDynArray; FEastView_Specified := True; end; function PictometryMaps.EastView_Specified(Index: Integer): boolean; begin Result := FEastView_Specified; end; procedure PictometryMaps.SetSouthView(Index: Integer; const ATByteDynArray: TByteDynArray); begin FSouthView := ATByteDynArray; FSouthView_Specified := True; end; function PictometryMaps.SouthView_Specified(Index: Integer): boolean; begin Result := FSouthView_Specified; end; procedure PictometryMaps.SetWestView(Index: Integer; const ATByteDynArray: TByteDynArray); begin FWestView := ATByteDynArray; FWestView_Specified := True; end; function PictometryMaps.WestView_Specified(Index: Integer): boolean; begin Result := FWestView_Specified; end; procedure PictometryMaps.SetOrthogonalView(Index: Integer; const ATByteDynArray: TByteDynArray); begin FOrthogonalView := ATByteDynArray; FOrthogonalView_Specified := True; end; function PictometryMaps.OrthogonalView_Specified(Index: Integer): boolean; begin Result := FOrthogonalView_Specified; end; procedure UserCredentials.SetCustID(Index: Integer; const AWideString: WideString); begin FCustID := AWideString; FCustID_Specified := True; end; function UserCredentials.CustID_Specified(Index: Integer): boolean; begin Result := FCustID_Specified; end; procedure UserCredentials.SetPassword(Index: Integer; const AWideString: WideString); begin FPassword := AWideString; FPassword_Specified := True; end; function UserCredentials.Password_Specified(Index: Integer): boolean; begin Result := FPassword_Specified; end; initialization InvRegistry.RegisterInterface(TypeInfo(PictometryServiceSoap), 'http://bradfordsoftware.com/', 'utf-8'); InvRegistry.RegisterDefaultSOAPAction(TypeInfo(PictometryServiceSoap), 'http://bradfordsoftware.com/SearchByAddress'); InvRegistry.RegisterInvokeOptions(TypeInfo(PictometryServiceSoap), ioDocument); InvRegistry.RegisterHeaderClass(TypeInfo(PictometryServiceSoap), UserCredentials2, 'UserCredentials', 'http://bradfordsoftware.com/'); RemClassRegistry.RegisterXSClass(PictometryAddress, 'http://bradfordsoftware.com/', 'PictometryAddress'); RemClassRegistry.RegisterXSClass(PictometrySearchModifiers, 'http://bradfordsoftware.com/', 'PictometrySearchModifiers'); RemClassRegistry.RegisterXSClass(PictometryMaps, 'http://bradfordsoftware.com/', 'PictometryMaps'); RemClassRegistry.RegisterXSClass(UserCredentials, 'http://bradfordsoftware.com/', 'UserCredentials'); RemClassRegistry.RegisterXSClass(UserCredentials2, 'http://bradfordsoftware.com/', 'UserCredentials2', 'UserCredentials'); end.
unit TarFTP.Factory; interface uses SysUtils, TarFTP.Interfaces; type TFactory = class(TInterfacedObject, IFactory) public { IFactory } function CreateArchiver : IArchiver; function CreateFtpSender : IFtpSender; function CreateTask : ITask; end; implementation uses TarFTP.Archiver, TarFTP.FtpSender, TarFTP.Tasks; { TFactory } function TFactory.CreateArchiver: IArchiver; begin Result := TTarArchiver.Create; end; function TFactory.CreateFtpSender: IFtpSender; begin Result := TFtpSender.Create; end; function TFactory.CreateTask: ITask; begin Result := TThreadedTask.Create; end; 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 } { } {******************************************************************************} // This File is auto generated! // Any change to this file should be made in the // corresponding unit in the folder "intermediate"! // Generation date: 28.10.2020 15:24:33 unit IdOpenSSLHeaders_pkcs7err; interface // Headers for OpenSSL 1.1.1 // pkcs7err.h {$i IdCompilerDefines.inc} uses IdCTypes, IdGlobal, IdOpenSSLConsts; const (* * PKCS7 function codes. *) PKCS7_F_DO_PKCS7_SIGNED_ATTRIB = 136; PKCS7_F_PKCS7_ADD0_ATTRIB_SIGNING_TIME = 135; PKCS7_F_PKCS7_ADD_ATTRIB_SMIMECAP = 118; PKCS7_F_PKCS7_ADD_CERTIFICATE = 100; PKCS7_F_PKCS7_ADD_CRL = 101; PKCS7_F_PKCS7_ADD_RECIPIENT_INFO = 102; PKCS7_F_PKCS7_ADD_SIGNATURE = 131; PKCS7_F_PKCS7_ADD_SIGNER = 103; PKCS7_F_PKCS7_BIO_ADD_DIGEST = 125; PKCS7_F_PKCS7_COPY_EXISTING_DIGEST = 138; PKCS7_F_PKCS7_CTRL = 104; PKCS7_F_PKCS7_DATADECODE = 112; PKCS7_F_PKCS7_DATAFINAL = 128; PKCS7_F_PKCS7_DATAINIT = 105; PKCS7_F_PKCS7_DATAVERIFY = 107; PKCS7_F_PKCS7_DECRYPT = 114; PKCS7_F_PKCS7_DECRYPT_RINFO = 133; PKCS7_F_PKCS7_ENCODE_RINFO = 132; PKCS7_F_PKCS7_ENCRYPT = 115; PKCS7_F_PKCS7_FINAL = 134; PKCS7_F_PKCS7_FIND_DIGEST = 127; PKCS7_F_PKCS7_GET0_SIGNERS = 124; PKCS7_F_PKCS7_RECIP_INFO_SET = 130; PKCS7_F_PKCS7_SET_CIPHER = 108; PKCS7_F_PKCS7_SET_CONTENT = 109; PKCS7_F_PKCS7_SET_DIGEST = 126; PKCS7_F_PKCS7_SET_TYPE = 110; PKCS7_F_PKCS7_SIGN = 116; PKCS7_F_PKCS7_SIGNATUREVERIFY = 113; PKCS7_F_PKCS7_SIGNER_INFO_SET = 129; PKCS7_F_PKCS7_SIGNER_INFO_SIGN = 139; PKCS7_F_PKCS7_SIGN_ADD_SIGNER = 137; PKCS7_F_PKCS7_SIMPLE_SMIMECAP = 119; PKCS7_F_PKCS7_VERIFY = 117; (* * PKCS7 reason codes. *) PKCS7_R_CERTIFICATE_VERIFY_ERROR = 117; PKCS7_R_CIPHER_HAS_NO_OBJECT_IDENTIFIER = 144; PKCS7_R_CIPHER_NOT_INITIALIZED = 116; PKCS7_R_CONTENT_AND_DATA_PRESENT = 118; PKCS7_R_CTRL_ERROR = 152; PKCS7_R_DECRYPT_ERROR = 119; PKCS7_R_DIGEST_FAILURE = 101; PKCS7_R_ENCRYPTION_CTRL_FAILURE = 149; PKCS7_R_ENCRYPTION_NOT_SUPPORTED_FOR_THIS_KEY_TYPE = 150; PKCS7_R_ERROR_ADDING_RECIPIENT = 120; PKCS7_R_ERROR_SETTING_CIPHER = 121; PKCS7_R_INVALID_NULL_POINTER = 143; PKCS7_R_INVALID_SIGNED_DATA_TYPE = 155; PKCS7_R_NO_CONTENT = 122; PKCS7_R_NO_DEFAULT_DIGEST = 151; PKCS7_R_NO_MATCHING_DIGEST_TYPE_FOUND = 154; PKCS7_R_NO_RECIPIENT_MATCHES_CERTIFICATE = 115; PKCS7_R_NO_SIGNATURES_ON_DATA = 123; PKCS7_R_NO_SIGNERS = 142; PKCS7_R_OPERATION_NOT_SUPPORTED_ON_THIS_TYPE = 104; PKCS7_R_PKCS7_ADD_SIGNATURE_ERROR = 124; PKCS7_R_PKCS7_ADD_SIGNER_ERROR = 153; PKCS7_R_PKCS7_DATASIGN = 145; PKCS7_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE = 127; PKCS7_R_SIGNATURE_FAILURE = 105; PKCS7_R_SIGNER_CERTIFICATE_NOT_FOUND = 128; PKCS7_R_SIGNING_CTRL_FAILURE = 147; PKCS7_R_SIGNING_NOT_SUPPORTED_FOR_THIS_KEY_TYPE = 148; PKCS7_R_SMIME_TEXT_ERROR = 129; PKCS7_R_UNABLE_TO_FIND_CERTIFICATE = 106; PKCS7_R_UNABLE_TO_FIND_MEM_BIO = 107; PKCS7_R_UNABLE_TO_FIND_MESSAGE_DIGEST = 108; PKCS7_R_UNKNOWN_DIGEST_TYPE = 109; PKCS7_R_UNKNOWN_OPERATION = 110; PKCS7_R_UNSUPPORTED_CIPHER_TYPE = 111; PKCS7_R_UNSUPPORTED_CONTENT_TYPE = 112; PKCS7_R_WRONG_CONTENT_TYPE = 113; PKCS7_R_WRONG_PKCS7_TYPE = 114; function ERR_load_PKCS7_strings: TIdC_INT cdecl; external CLibCrypto; implementation end.
unit Menus.Controller.ListBox.Clientes; interface uses Menus.Controller.ListBox.Interfaces, System.Classes; type TControllerListBoxClientes = class(TInterfacedObject, iControllerListBoxMenu) private FContainer: TComponent; public constructor Create(Container: TComponent); destructor Destroy; override; class function New(Container: TComponent): iControllerListBoxMenu; procedure Exibir; end; implementation uses Menus.Controller.ListaBox.Factory, Menus.Controller.ListaBox.Itens.Factory; { TControllerListBoxClientes } constructor TControllerListBoxClientes.Create(Container: TComponent); begin FContainer := Container; end; destructor TControllerListBoxClientes.Destroy; begin inherited; end; procedure TControllerListBoxClientes.Exibir; begin TControllerListaBoxFactory.New .Default(FContainer) .AddItem(TControllerListaBoxItensFactory.New.Produto.Show) .Exibir; end; class function TControllerListBoxClientes.New( Container: TComponent): iControllerListBoxMenu; begin Result := Self.Create(Container); end; end.
unit UFrameMakeCard; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UFrameBase, ExtCtrls, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxLabel, jpeg, Buttons, StdCtrls; type TfFrameMakeCard = class(TfFrameBase) PanelClient: TPanel; BtnOK: TSpeedButton; LabelCusName: TcxLabel; LabelOrder: TcxLabel; LabelTruck: TcxLabel; LabelStockName: TcxLabel; LabelTon: TcxLabel; LabelMemo: TcxLabel; procedure BtnOKClick(Sender: TObject); private { Private declarations } FListA, FListB, FListC: TStrings; //列表信息 procedure InitUIData(nOrderInfo: string = ''); //初始化信息 public { Public declarations } procedure OnCreateFrame; override; procedure OnDestroyFrame; override; procedure OnShowFrame; override; class function FrameID: integer; override; function DealCommand(Sender: TObject; const nCmd: Integer; const nParamA: Pointer; const nParamB: Integer): Integer; override; {*处理命令*} end; var fFrameMakeCard: TfFrameMakeCard; implementation {$R *.dfm} uses ULibFun, USysLoger, UDataModule, UMgrControl, USelfHelpConst, USysBusiness, UMgrK720Reader, USysDB, UBase64; //------------------------------------------------------------------------------ //Desc: 记录日志 procedure WriteLog(const nEvent: string); begin gSysLoger.AddLog(TfFrameMakeCard, '网上订单制卡', nEvent); end; class function TfFrameMakeCard.FrameID: Integer; begin Result := cFI_FrameMakeCard; end; function TfFrameMakeCard.DealCommand(Sender: TObject; const nCmd: Integer; const nParamA: Pointer; const nParamB: Integer): Integer; begin Result := 0; if nCmd = cCmd_FrameQuit then begin Close; end else if nCmd = cCmd_MakeCard then begin if not Assigned(nParamA) then Exit; InitUIData(PFrameCommandParam(nParamA).FParamA); end; end; procedure TfFrameMakeCard.OnCreateFrame; begin DoubleBuffered := True; FListA := TStringList.Create; FListB := TStringList.Create; FListC := TStringList.Create; end; procedure TfFrameMakeCard.OnDestroyFrame; begin FListA.Free; FListB.Free; FListC.Free; end; procedure TfFrameMakeCard.OnShowFrame; begin end; procedure TfFrameMakeCard.InitUIData(nOrderInfo: string); begin if nOrderInfo = '' then begin ShowMsg('无订单信息', sHint); gTimeCounter := 0; Exit; end; FListA.Text := nOrderInfo; with FListA do begin LabelOrder.Caption := '订单编号:' + Values['OrderNO']; LabelCusName.Caption := '客户名称:' + Values['CusName']; LabelStockName.Caption := '物料名称:' + Values['StockName']; LabelTruck.Caption := '车牌号码:' + Values['Truck']; LabelTon.Caption := '订单数量:' + Values['Value']; LabelMemo.Caption := '备注信息:' + Values['SendArea']; end; gTimeCounter := 30; end; procedure TfFrameMakeCard.BtnOKClick(Sender: TObject); var nMsg, nStr, nCard: string; nIdx: Integer; nRet: Boolean; begin inherited; if ShopOrderHasUsed(FListA.Values['WebShopID']) then begin nMsg := '订单号[ %s ]已使用,请重选订单号.'; nMsg := Format(nMsg, [FListA.Values['WebShopID']]); ShowMsg(nMsg, sHint); Exit; end; for nIdx:=0 to 3 do if gMgrK720Reader.ReadCard(nCard) then Break else Sleep(500); //连续三次读卡,成功则退出。 if nCard = '' then begin nMsg := '卡箱异常,请查看是否有卡.'; ShowMsg(nMsg, sWarn); Exit; end; nCard := gMgrK720Reader.ParseCardNO(nCard); WriteLog('读取到卡片: ' + nCard); //解析卡片 nStr := GetCardUsed(nCard); if (nStr = sFlag_Sale) or (nStr = sFlag_SaleNew) then LogoutBillCard(nCard); //销售业务注销卡片,其它业务则无需注销 if FListA.Values['OrderType'] = sFlag_Sale then begin with FListB do begin Clear; Values['Orders'] := EncodeBase64(FListA.Values['Orders']); Values['Value'] := FListA.Values['Value']; //订单量 Values['Truck'] := FListA.Values['Truck']; Values['Lading'] := sFlag_TiHuo; Values['IsVIP'] := sFlag_TypeCommon; Values['Pack'] := FListA.Values['StockType']; Values['BuDan'] := sFlag_No; Values['CusID'] := FListA.Values['CusID']; Values['CusName'] := FListA.Values['CusName']; Values['Brand'] := FListA.Values['Brand']; Values['StockArea'] := FListA.Values['StockArea']; end; nStr := SaveBill(EncodeBase64(FListB.Text)); //call mit bus nRet := nStr <> ''; if not nRet then begin nMsg := '生成提货单信息失败,请联系管理员尝试手工制卡.'; ShowMsg(nMsg, sHint); Exit; end; nRet := SaveBillCard(nStr, nCard); SaveShopOrderIn(FListA.Values['WebShopID'], nStr); end else if FListA.Values['OrderType'] = sFlag_Provide then begin with FListB do begin Clear; Values['Order'] := FListA.Values['OrderNO']; Values['Origin'] := FListA.Values['Origin']; Values['Truck'] := FListA.Values['Truck']; Values['ProID'] := FListA.Values['CusID']; Values['ProName'] := FListA.Values['CusName']; Values['StockNO'] := FListA.Values['StockNO']; Values['StockName'] := FListA.Values['StockName']; Values['Value'] := FListA.Values['Value']; Values['Card'] := nCard; Values['Memo'] := FListA.Values['Data']; Values['CardType'] := sFlag_ProvCardL; Values['TruckBack'] := sFlag_No; Values['TruckPre'] := sFlag_No; Values['Muilti'] := sFlag_No; end; nStr := SaveCardProvie(EncodeBase64(FListB.Text)); //call mit bus nRet := nStr <> ''; SaveShopOrderIn(FListA.Values['WebShopID'], nStr); end else nRet := False; if not nRet then begin nMsg := '办理磁卡失败,请重试.'; ShowMsg(nMsg, sHint); Exit; end; for nIdx := 0 to 3 do begin nRet := gMgrK720Reader.SendReaderCmd('FC0'); if nRet then Break; Sleep(500); end; //发卡 if nRet then begin nMsg := '微信订单[ %s ]发卡成功,卡号[ %s ],请收好您的卡片'; nMsg := Format(nMsg, [FListA.Values['WebID'], nCard]); WriteLog(nMsg); ShowMsg(nMsg,sWarn); end else begin gMgrK720Reader.RecycleCard; nMsg := '微信订单[ %s ],卡号[ %s ]关联订单失败,请到开票窗口重新关联.'; nMsg := Format(nMsg, [FListA.Values['WebID'], nCard]); WriteLog(nMsg); ShowMsg(nMsg,sWarn); end; gTimeCounter := 0; end; initialization gControlManager.RegCtrl(TfFrameMakeCard, TfFrameMakeCard.FrameID); end.
unit MainUnit; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, System.Win.ComObj, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGridExportLink, cxGraphics, Math, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxSkinsCore, System.RegularExpressions, dxSkinsDefaultPainters, dxSkinscxPCPainter, cxPCdxBarPopupMenu, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, Data.DB, cxDBData, cxContainer, Vcl.ComCtrls, dxCore, cxSpinEdit, Vcl.StdCtrls, cxLabel, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, Vcl.ExtCtrls, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxGridCustomView, cxGrid, cxPC, ZAbstractRODataset, ZAbstractDataset, ZDataset, ZAbstractConnection, ZConnection, IniFiles, IdMessage, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdExplicitTLSClientServerBase, IdMessageClient, IdSMTPBase, IdSMTP, Vcl.ActnList, IdText, IdSSLOpenSSL, IdGlobal, strUtils, IdAttachmentFile, IdFTP, cxCurrencyEdit, cxCheckBox, Vcl.Menus, DateUtils, cxButtonEdit, ZLibExGZ; type TMainForm = class(TForm) ZConnection: TZConnection; Timer1: TTimer; qryMaker: TZQuery; dsMaker: TDataSource; qryMailParam: TZQuery; Panel2: TPanel; btnAll: TButton; qryReport_Upload: TZQuery; dsReport_Upload: TDataSource; qrySetDateSend: TZQuery; Memo: TMemo; ZQuery: TZQuery; ZQueryTable: TZQuery; procedure FormCreate(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure btnAllClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } public { Public declarations } procedure Add_Log(AMessage:String); end; var MainForm: TMainForm; implementation {$R *.dfm} procedure TMainForm.Add_Log(AMessage: String); var F: TextFile; begin try AssignFile(F,ChangeFileExt(Application.ExeName,'.log')); if not fileExists(ChangeFileExt(Application.ExeName,'.log')) then Rewrite(F) else Append(F); try Writeln(F,FormatDateTime('YYYY.MM.DD hh:mm:ss',now) + ' - ' + AMessage); Memo.Lines.Add(FormatDateTime('YYYY.MM.DD hh:mm:ss',now) + ' - ' + AMessage); finally CloseFile(F); end; except end; end; procedure TMainForm.btnAllClick(Sender: TObject); function lVACUUM (lStr : String): Boolean; begin try Application.ProcessMessages; ZQuery.Sql.Clear;; ZQuery.Sql.Add (lStr); ZQuery.ExecSql; Add_Log(lStr); Application.ProcessMessages; Sleep(500); except on E: Exception do Add_Log(E.Message); end; end; begin try try if not ((CompareText(ParamStr(1), 'analyze') = 0) or (CompareText(ParamStr(2), 'analyze') = 0) or (CompareText(ParamStr(3), 'analyze') = 0)) then begin // Add_Log('start all VACUUM'); // // Container // lVACUUM ('VACUUM FULL Container'); // lVACUUM ('VACUUM ANALYZE Container'); // CashSessionSnapShot - !!! 180 MIN !!! lVACUUM ('delete from CashSessionSnapShot WHERE CashSessionId IN (select Id from CashSession WHERE lastConnect < CURRENT_TIMESTAMP - INTERVAL ' + chr(39) + '180 MIN' + chr(39) + ')'); lVACUUM ('delete from CashSession WHERE Id NOT IN (SELECT DISTINCT CashSessionId FROM CashSessionSnapShot) AND lastConnect < CURRENT_TIMESTAMP - INTERVAL ' + chr(39) + '180 MIN' + chr(39)); // lVACUUM ('VACUUM FULL CashSession'); // lVACUUM ('VACUUM ANALYZE CashSession'); // lVACUUM ('VACUUM FULL CashSessionSnapShot'); // lVACUUM ('VACUUM ANALYZE CashSessionSnapShot'); // LoadPriceList + LoadPriceListItem // lVACUUM ('VACUUM FULL LoadPriceList'); // lVACUUM ('VACUUM ANALYZE LoadPriceList'); // lVACUUM ('VACUUM FULL LoadPriceListItem'); // lVACUUM ('VACUUM ANALYZE LoadPriceListItem'); // System - FULL // lVACUUM ('VACUUM FULL pg_catalog.pg_statistic'); // lVACUUM ('VACUUM FULL pg_catalog.pg_attribute'); // lVACUUM ('VACUUM FULL pg_catalog.pg_class'); // lVACUUM ('VACUUM FULL pg_catalog.pg_type'); // lVACUUM ('VACUUM FULL pg_catalog.pg_depend'); // lVACUUM ('VACUUM FULL pg_catalog.pg_shdepend'); // lVACUUM ('VACUUM FULL pg_catalog.pg_index'); // lVACUUM ('VACUUM FULL pg_catalog.pg_attrdef'); // lVACUUM ('VACUUM FULL pg_catalog.pg_proc'); // System - ANALYZE lVACUUM ('VACUUM ANALYZE pg_catalog.pg_statistic'); lVACUUM ('VACUUM ANALYZE pg_catalog.pg_attribute'); lVACUUM ('VACUUM ANALYZE pg_catalog.pg_class'); lVACUUM ('VACUUM ANALYZE pg_catalog.pg_type'); lVACUUM ('VACUUM ANALYZE pg_catalog.pg_depend'); lVACUUM ('VACUUM ANALYZE pg_catalog.pg_shdepend'); lVACUUM ('VACUUM ANALYZE pg_catalog.pg_index'); lVACUUM ('VACUUM ANALYZE pg_catalog.pg_attrdef'); lVACUUM ('VACUUM ANALYZE pg_catalog.pg_proc'); // // !!!main!!! try ZQueryTable.Open; ZQueryTable.First; while not ZQueryTable.Eof do begin lVACUUM ('VACUUM ANALYZE ' + ZQueryTable.FieldByName('table_name').AsString); ZQueryTable.Next; if HourOf(Now) >= 7 then Exit; end; finally // // Add_Log('end all VACUUM'); end; end else begin if HourOf(Now) < 7 then Exit; // Add_Log('start all ANALYZE'); // // System - ANALYZE lVACUUM ('VACUUM ANALYZE pg_catalog.pg_statistic'); lVACUUM ('VACUUM ANALYZE pg_catalog.pg_attribute'); lVACUUM ('VACUUM ANALYZE pg_catalog.pg_class'); lVACUUM ('VACUUM ANALYZE pg_catalog.pg_type'); lVACUUM ('VACUUM ANALYZE pg_catalog.pg_depend'); lVACUUM ('VACUUM ANALYZE pg_catalog.pg_shdepend'); lVACUUM ('VACUUM ANALYZE pg_catalog.pg_index'); lVACUUM ('VACUUM ANALYZE pg_catalog.pg_attrdef'); lVACUUM ('VACUUM ANALYZE pg_catalog.pg_proc'); ZQueryTable.Open; ZQueryTable.First; while not ZQueryTable.Eof do begin lVACUUM ('ANALYZE ' + ZQueryTable.FieldByName('table_name').AsString); ZQueryTable.Next; end; // // Add_Log('end all ANALYZE'); end; except on E: Exception do Add_Log(E.Message); end; finally ZConnection.Connected := false; ZQuery.Free; ZConnection.Free; end; end; procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TMainForm.FormCreate(Sender: TObject); var Ini: TIniFile; begin Ini := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'ExecuteVACUM.ini'); try ZConnection.Database := Ini.ReadString('Connect', 'DataBase', 'farmacy'); Ini.WriteString('Connect', 'DataBase', ZConnection.Database); ZConnection.HostName := Ini.ReadString('Connect', 'HostName', '172.17.2.5'); Ini.WriteString('Connect', 'HostName', ZConnection.HostName); ZConnection.User := Ini.ReadString('Connect', 'User', 'postgres'); Ini.WriteString('Connect', 'User', ZConnection.User); ZConnection.Password := Ini.ReadString('Connect', 'Password', 'eej9oponahT4gah3'); Ini.WriteString('Connect', 'Password', ZConnection.Password); finally Ini.free; end; ZConnection.LibraryLocation := ExtractFilePath(Application.ExeName) + 'libpq.dll'; try ZConnection.Connect; except on E:Exception do begin Add_Log(E.Message); ZConnection.Disconnect; Timer1.Enabled := true; Exit; end; end; if ZConnection.Connected then begin if not ((ParamCount >= 1) and (CompareText(ParamStr(1), 'manual') = 0)) then begin btnAll.Enabled := false; Timer1.Enabled := true; end; end; end; procedure TMainForm.Timer1Timer(Sender: TObject); begin try timer1.Enabled := False; if ZConnection.Connected then btnAllClick(nil); finally Close; end; end; end.
unit PhysicsParticles; interface Uses dglOpenGL, PhysicsArifm; Type TParticle = class public PreviousPosition, Position: TVector3; ForceAccumulator: TVector3; Velocity: TVector3; Acceleration: TVector3; Mass: Float; Radius: Float; Texture: GLUInt; Constructor Create (const InitialPosition, InitialVelocity, InitialForce: TVector3; const ParticleTexture: GLUInt; const ParticleMass, ParticleRadius: Float); Procedure ClearForceAccumulator; Function GetMass: Float; Function GetInvMass: Float; Procedure AddForce (const Force: TVector3); Procedure Draw; Procedure Integrate (const DeltaTime: Float); end; TParticles = array of TParticle; implementation {############################################################################################################### TParticle - класс, описывающий материальную частицу ###############################################################################################################} Constructor TParticle.Create(const InitialPosition: TVector3; const InitialVelocity: TVector3; const InitialForce: TVector3; const ParticleTexture: Cardinal; const ParticleMass, ParticleRadius: Float); begin inherited Create; Position := V3AddScaledVector (InitialPosition, InitialVelocity, 0.01); PreviousPosition := InitialPosition; Velocity := InitialVelocity; Mass := ParticleMass; ForceAccumulator := InitialForce; Acceleration := V3 (0); Texture := ParticleTexture; Radius := ParticleRadius; end; Procedure TParticle.ClearForceAccumulator; begin ForceAccumulator := V3 (0); end; Function TParticle.GetMass: Float; begin Result := Mass; end; Function TParticle.GetInvMass: Float; begin Result := 1 / Mass; end; Procedure TParticle.AddForce(const Force: TVector3); begin ForceAccumulator := V3Add (ForceAccumulator, Force); end; Procedure TParticle.Draw; Var QuadricObj: PGLUQuadricObj; begin QuadricObj := gluNewQuadric; //Разрешаем наложение текстуры на трёхмерный объект gluQuadricTexture (QuadricObj, TRUE); //Устанавливаем тип рисования объекта - заполнение gluQuadricDrawStyle (QuadricObj, GL_FILL); glBindTexture (GL_TEXTURE_2D, Texture); glPushMatrix; glTranslateF (Position.X, Position.Y, Position.Z); gluSphere (QuadricObj, Radius, 10, 10); glPopMatrix; //Удаляем объект gluDeleteQuadric (QuadricObj); end; Procedure TParticle.Integrate (const DeltaTime: Float); begin //Сохраним текущую позицию частицы PreviousPosition := Position; {//Рассчитаем новую позицию частицы Position := V3AddScaledVector (V3Add (Position, V3Sub (Position, PreviousPosition)), ForceAccumulator, Sqr (DeltaTime)/Mass); //Сохраним текущую позицию в предыдущую} Acceleration := V3Div (ForceAccumulator, Mass); Velocity := V3AddScaledVector (Velocity, Acceleration, DeltaTime); Position := V3AddScaledVector (Position, Velocity, DeltaTime); ClearForceAccumulator; end; end.
unit URepositorioMedicamento; interface uses UMedicamento , UEntidade , URepositorioDB , SqlExpr ; type TRepositorioMedicamento = class(TRepositorioDB<TMEDICAMENTO>) protected procedure AtribuiDBParaEntidade(const coMEDICAMENTO: TMEDICAMENTO); override; procedure AtribuiEntidadeParaDB(const coMEDICAMENTO: TMEDICAMENTO; const coSQLQuery: TSQLQuery); override; public constructor Create; function RetornaClienteCodigo(const csCodigo: Integer): TMEDICAMENTO; end; implementation uses UDM , SysUtils , UUtilitarios ; const CNT_SELECT_NOME = 'select * from medicamento where codigo = :codigo'; { TRepositorioMedicamento } procedure TRepositorioMedicamento.AtribuiDBParaEntidade( const coMEDICAMENTO: TMEDICAMENTO); begin inherited; with dmProway.SQLSelect do begin coMEDICAMENTO.PRINCIPIO_ATIVO := FieldByName(FLD_MEDICAMENTO_PRINCIPIO_ATIVO).AsString; coMEDICAMENTO.CNPJ := FieldByName(FLD_MEDICAMENTO_CNPJ).AsString; coMEDICAMENTO.LABORATORIO := FieldByName(FLD_MEDICAMENTO_LABORATORIO).AsString; coMEDICAMENTO.CODGREM := FieldByName(FLD_MEDICAMENTO_CODGREM).AsString; coMEDICAMENTO.EAN := FieldByName(FLD_MEDICAMENTO_EAN).AsString; coMEDICAMENTO.NOME := FieldByName(FLD_MEDICAMENTO_NOME).AsString; coMEDICAMENTO.APRESENTACAO := FieldByName(FLD_MEDICAMENTO_APRESENTACAO).AsString; coMEDICAMENTO.PRECOFAB := FieldByName(FLD_MEDICAMENTO_PRECOFAB).AsString; coMEDICAMENTO.PRECOCOMERCIAL := FieldByName(FLD_MEDICAMENTO_PRECOCOMERCIAL).AsString; coMEDICAMENTO.RESTRICAOHOSPITALAR:= FieldByName(FLD_MEDICAMENTO_RESTRICAOHOSPITALAR).AsString; end; end; procedure TRepositorioMedicamento.AtribuiEntidadeParaDB( const coMEDICAMENTO: TMEDICAMENTO; const coSQLQuery: TSQLQuery); begin inherited; with coSQLQuery do begin FieldByName(FLD_MEDICAMENTO_PRINCIPIO_ATIVO) .AsString := coMEDICAMENTO.PRINCIPIO_ATIVO; FieldByName(FLD_MEDICAMENTO_CNPJ) .AsString := coMEDICAMENTO.CNPJ; FieldByName(FLD_MEDICAMENTO_LABORATORIO) .AsString := coMEDICAMENTO.LABORATORIO; FieldByName(FLD_MEDICAMENTO_CODGREM) .AsString := coMEDICAMENTO.CODGREM; FieldByName(FLD_MEDICAMENTO_EAN) .AsString := coMEDICAMENTO.EAN; FieldByName(FLD_MEDICAMENTO_NOME) .AsString := coMEDICAMENTO.NOME; FieldByName(FLD_MEDICAMENTO_APRESENTACAO) .AsString := coMEDICAMENTO.APRESENTACAO; FieldByName(FLD_MEDICAMENTO_PRECOFAB) .AsString := coMEDICAMENTO.PRECOFAB; FieldByName(FLD_MEDICAMENTO_PRECOCOMERCIAL) .AsString := coMEDICAMENTO.PRECOCOMERCIAL; FieldByName(FLD_MEDICAMENTO_RESTRICAOHOSPITALAR).AsString := coMEDICAMENTO.RESTRICAOHOSPITALAR; end; end; constructor TRepositorioMedicamento.Create; begin inherited Create(TMEDICAMENTO, TBL_MEDICAMENTO, FLD_ENTIDADE_CODIGO, STR_MEDICAMENTO); end; function TRepositorioMedicamento.RetornaClienteCodigo( const csCodigo: Integer): TMEDICAMENTO; begin dmProway.SQLSelect.Close; dmProway.SQLSelect.CommandText := CNT_SELECT_NOME; dmProway.SQLSelect.ParamByName('codigo').AsInteger := csCodigo; dmProway.SQLSelect.Open; Result := Nil; if not dmProway.SQLSelect.Eof then begin Result := TMEDICAMENTO(FEntidadeClasse.Create); AtribuiDBParaEntidade(Result); end; end; end.
(* Copyright (c) 2011, Stefan Glienke All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of this library nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *) unit DSharp.Core.DataConversion.Default; interface uses DSharp.Core.DataConversion, TypInfo; type TDefaultConverter = class(TValueConverter) private FSourceType: PTypeInfo; FTargetType: PTypeInfo; public constructor Create(ASourceType, ATargetType: PTypeInfo); function Convert(const Value: TValue): TValue; override; function ConvertBack(const Value: TValue): TValue; override; end; implementation uses DSharp.Core.Reflection; { TDefaultConverter } constructor TDefaultConverter.Create(ASourceType, ATargetType: PTypeInfo); begin FSourceType := ASourceType; FTargetType := ATargetType; end; function TDefaultConverter.Convert(const Value: TValue): TValue; begin Value.TryConvert(FTargetType, Result); end; function TDefaultConverter.ConvertBack(const Value: TValue): TValue; begin Value.TryConvert(FSourceType, Result); end; end.
unit Form1; //{$R 'lib\aes.js'} //{$R 'https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js'} interface uses uCryptoJS, W3C.TypedArray, W3C.Cryptography, System.Diagnostics, SynCrossPlatformCrypto, SmartCL.System, SmartCL.Graphics, SmartCL.Components, SmartCL.Forms, SmartCL.Fonts, SmartCL.Borders, SmartCL.Application, SmartCL.Controls.Label, SmartCL.Controls.Button, SmartCL.Controls.EditBox, SmartCL.Controls.Combobox; type JOptions = class(JObject) class var mode := cryptoJS.mode.CBC; class var padding := cryptoJS.pad.Pkcs7; end; type TForm1 = class(TW3Form) procedure GenerateUUID1Click(Sender: TObject); procedure GenerateUUID2Click(Sender: TObject); procedure ComboBox1Changed(Sender: TObject); procedure W3Button1Click(Sender: TObject); procedure btndecryptClick(Sender: TObject); procedure btnEncrptClick(Sender: TObject); private {$I 'Form1:intf'} op : JOptions; json: JCipherParams; _keySizeInBits: integer; procedure genPassphrase; protected procedure InitializeForm; override; procedure InitializeObject; override; procedure Resize; override; end; implementation { TForm1 } function GenerateUUID:string; // The procedure to generate a version 4 UUID is as follows: // 1. Generate 16 random bytes (=128 bits) // 2. Adjust certain bits according to RFC 4122 section 4.4 as follows: // a. set the four most significant bits of the 7th byte to 0100'B, so the high nibble is '4' // b. set the two most significant bits of the 9th byte to 10'B, so the high nibble will be one of '8', '9', 'A', or 'B'. // 3. Convert the adjusted bytes to 32 hexadecimal digits // 4. Add four hyphen '-' characters to obtain blocks of 8, 4, 4, 4 and 12 hex digits // 5. Output the resulting 36-character string "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" var d0, d1, d2, d3: integer; begin d0 := Integer(Now + PerformanceTimer.Now) + Trunc(Random * $ffffffff); d1 := d0 + Trunc(Random * $ffffffff); d2 := d1 + Trunc(Random * $ffffffff); d3 := d2 + Trunc(Random * $ffffffff); d1 := (d1 and $ff0fffff) or $00400000; d2 := (d2 and $ffffff3f) or $00000080; Result := IntToHex(d0 and $ff, 2) + IntToHex((d0 shr 8) and $ff, 2) + IntToHex((d0 shr 16) and $ff, 2) + IntToHex((d0 shr 24) and $ff, 2) + '-' + IntToHex(d1 and $ff, 2) + IntToHex((d1 shr 8) and $ff, 2) + '-' + IntToHex((d1 shr 16) and $ff, 2) + IntToHex((d1 shr 24) and $ff, 2) + '-' + IntToHex(d2 and $ff, 2) + IntToHex((d2 shr 8) and $ff, 2) + '-' + IntToHex((d2 shr 16) and $ff, 2) + IntToHex((d2 shr 24) and $ff, 2) + IntToHex(d3 and $ff, 2) + IntToHex((d3 shr 8) and $ff, 2) + IntToHex((d3 shr 16) and $ff, 2) + IntToHex((d3 shr 24) and $ff, 2); end; function GenerateUUIDNew: string; // The procedure to generate a version 4 UUID is as follows: // 1. Generate 16 random bytes (=128 bits) // 2. Adjust certain bits according to RFC 4122 section 4.4 as follows: // a. set the four most significant bits of the 7th byte to 0100'B, so the high nibble is '4' // b. set the two most significant bits of the 9th byte to 10'B, so the high nibble will be one of '8', '9', 'A', or 'B'. // 3. Convert the adjusted bytes to 32 hexadecimal digits // 4. Add four hyphen '-' characters to obtain blocks of 8, 4, 4, 4 and 12 hex digits // 5. Output the resulting 36-character string "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" var data: JUint8Array; begin data := JUint8Array.Create(16); JCrypto.getRandomValues(data); data[6] := (data[6] and $0f) or $40; data[8] := (data[8] and $3f) or $80; Result := IntToHex(data[0], 2) + IntToHex(data[1], 2) + IntToHex(data[2], 2) + IntToHex(data[3], 2) + '-' + IntToHex(data[4], 2) + IntToHex(data[5], 2) + '-' + IntToHex(data[6], 2) + IntToHex(data[7], 2) + '-' + IntToHex(data[8], 2) + IntToHex(data[9], 2) + '-' + IntToHex(data[10], 2) + IntToHex(data[11], 2) + IntToHex(data[12], 2) + IntToHex(data[13], 2) + IntToHex(data[14], 2) + IntToHex(data[15], 2); end; procedure TForm1.btnEncrptClick(Sender: TObject); begin /*** encrypt */ json := CryptoJS.AES.encrypt(edit1.text, "Secret Passphrase", op); edit2.Text := json.ciphertext.toString(CryptoJS.enc.Base64); end; procedure TForm1.btndecryptClick(Sender: TObject); begin /*** decrypt */ var decrypt := CryptoJS.AES.decrypt(json, "Secret Passphrase", op); edit3.Text := decrypt.toString(CryptoJS.enc.Utf8); end; function parseInt(s: string; radix: integer = 0): integer;external; function troncaNum(c, a: variant): variant; begin var b := c.toString(); result := b.substring(0, a) end; function getHash(c, e: variant): variant; begin var d : variant; var b = parseInt(e); if (b = 128) then begin d := SHA256(c); var a = 128 / 4; d := troncaNum(d, a) end else begin if (b = 192) then begin d := SHA256(c); var a = 192 / 4; d := troncaNum(d, a) end else begin if (b = 256) then begin d := SHA256(c) end; end; end; result := d; end; function randomPassphrase(c: variant): variant; begin try var d = (RandomInt(10000)); var b = getHash(d, c); result := b except on E : Exception do result := -1 end; end; procedure TForm1.W3Button1Click(Sender: TObject); begin genPassphrase; end; procedure TForm1.GenerateUUID2Click(Sender: TObject); begin EditUI2.Text := GenerateUUIDNew; end; procedure TForm1.GenerateUUID1Click(Sender: TObject); begin EditUI1.Text := GenerateUUID; end; procedure TForm1.genPassphrase; begin _keySizeInBits := StrToInt( ComboBox1.Items[ComboBox1.SelectedIndex] ); //192; var a = randomPassphrase(_keySizeInBits); keysize.Text := a; end; procedure TForm1.ComboBox1Changed(Sender: TObject); begin WriteLn(ComboBox1.Items[ComboBox1.SelectedIndex]); end; procedure TForm1.InitializeForm; begin inherited; // this is a good place to initialize components end; procedure TForm1.InitializeObject; begin inherited; {$I 'Form1:impl'} op := new JOptions; ComboBox1.Add('128'); ComboBox1.Add('192'); ComboBox1.Add('256'); end; procedure TForm1.Resize; begin inherited; end; initialization Forms.RegisterForm({$I %FILE%}, TForm1); end.
unit MyMatrix; { матричные преобразования разработчик: Макаров М.М. дата создания: 24 февраля 2005 } interface uses Math; type TVector3 = Array[0..2] of Extended; TVector4 = Array[0..3] of Extended; TMatrixArray = Array of TVector4; TMyMatrix = class public hsize:Integer; arr:TMatrixArray; constructor Create; destructor Destroy;override; procedure AddLine(a,b,c,d:Extended);overload; procedure AddLine(a:TVector4);overload; procedure Clear; procedure MultMatrix(m:TMyMatrix); procedure RotateX(angle:Extended); procedure RotateY(angle:Extended); procedure RotateZ(angle:Extended); procedure Scale(x,y,z:Extended); procedure MirrorX; procedure MirrorY; procedure MirrorZ; procedure Translate(x,y,z:Extended); procedure LoadIdentity; function GetX(line:Integer):Extended; function GetY(line:Integer):Extended; function GetZ(line:Integer):Extended; procedure FrustumProjection(l,r,b,t,n,f:Extended); procedure OrthoProjection(l,r,b,t,n,f:Extended); procedure ParallelProjectionXY(z0:Extended); procedure ParallelProjectionXZ(y0:Extended); procedure ParallelProjectionYZ(x0:Extended); procedure Perspective(fovy,aspect,znear,zfar:Extended); procedure LookAt(eyex,eyey,eyez, centerx,centery,centerz, upx,upy,upz:Extended); procedure Normalize(var v:TVector3); procedure Cross(v1,v2:TVector3; var r:TVector3); procedure Transpose; procedure Copy(m:TMyMatrix); procedure Sort; end; implementation constructor TMyMatrix.Create; {конструктор} begin Clear; end; destructor TMyMatrix.Destroy; {деструктор} begin Clear; Inherited Destroy; end; procedure TMyMatrix.AddLine(a,b,c,d:Extended); {добавить строку в матрицу} begin inc(hsize); SetLength(arr,hsize); arr[hsize-1,0]:=a; arr[hsize-1,1]:=b; arr[hsize-1,2]:=c; arr[hsize-1,3]:=d; end; procedure TMyMatrix.AddLine(a:TVector4); {добавить строку в матрицу} var i:Integer; begin inc(hsize); SetLength(arr,hsize); for i:=0 to 3 do arr[hsize-1,i]:=a[i]; end; procedure TMyMatrix.Clear; {очистить массив} begin hsize:=0; Finalize(arr); end; procedure TMyMatrix.MultMatrix(m:TMyMatrix); {перемножение матриц} var i,j:Integer; tmp:TMatrixArray; begin if m.hsize=4 then begin SetLength(tmp,hsize); for i:=0 to hsize-1 do for j:=0 to 3 do tmp[i,j]:=arr[i,j]; for i:=0 to hsize-1 do for j:=0 to 3 do arr[i,j]:=tmp[i,0]*m.arr[0,j]+ tmp[i,1]*m.arr[1,j]+ tmp[i,2]*m.arr[2,j]+ tmp[i,3]*m.arr[3,j]; Finalize(tmp); end; end; procedure TMyMatrix.RotateX(angle:Extended); {вращение вокруг оси X} var tmp:TMyMatrix; begin tmp:=TMyMatrix.Create; tmp.AddLine(1,0,0,0); tmp.AddLine(0,cos(DegToRad(angle)),sin(DegToRad(angle)),0); tmp.AddLine(0,-sin(DegToRad(angle)),cos(DegToRad(angle)),0); tmp.AddLine(0,0,0,1); MultMatrix(tmp); tmp.Destroy; end; procedure TMyMatrix.RotateY(angle:Extended); {вращение вокруг оси Y} var tmp:TMyMatrix; begin tmp:=TMyMatrix.Create; tmp.AddLine(cos(DegToRad(angle)),0,-sin(DegToRad(angle)),0); tmp.AddLine(0,1,0,0); tmp.AddLine(sin(DegToRad(angle)),0,cos(DegToRad(angle)),0); tmp.AddLine(0,0,0,1); MultMatrix(tmp); tmp.Destroy; end; procedure TMyMatrix.RotateZ(angle:Extended); {вращение вокруг оси Z} var tmp:TMyMatrix; begin tmp:=TMyMatrix.Create; tmp.AddLine(cos(DegToRad(angle)),sin(DegToRad(angle)),0,0); tmp.AddLine(-sin(DegToRad(angle)),cos(DegToRad(angle)),0,0); tmp.AddLine(0,0,1,0); tmp.AddLine(0,0,0,1); MultMatrix(tmp); tmp.Destroy; end; procedure TMyMatrix.Scale(x,y,z:Extended); {масштабирование} var tmp:TMyMatrix; begin tmp:=TMyMatrix.Create; tmp.AddLine(x,0,0,0); tmp.AddLine(0,y,0,0); tmp.AddLine(0,0,z,0); tmp.AddLine(0,0,0,1); MultMatrix(tmp); tmp.Destroy; end; procedure TMyMatrix.MirrorX; {отражение по оси X} var tmp:TMyMatrix; begin tmp:=TMyMatrix.Create; tmp.AddLine(-1,0,0,0); tmp.AddLine(0,1,0,0); tmp.AddLine(0,0,1,0); tmp.AddLine(0,0,0,1); MultMatrix(tmp); tmp.Destroy; end; procedure TMyMatrix.MirrorY; {отражение по оси Y} var tmp:TMyMatrix; begin tmp:=TMyMatrix.Create; tmp.AddLine(1,0,0,0); tmp.AddLine(0,-1,0,0); tmp.AddLine(0,0,1,0); tmp.AddLine(0,0,0,1); MultMatrix(tmp); tmp.Destroy; end; procedure TMyMatrix.MirrorZ; {отражение по оси Z} var tmp:TMyMatrix; begin tmp:=TMyMatrix.Create; tmp.AddLine(1,0,0,0); tmp.AddLine(0,1,0,0); tmp.AddLine(0,0,-1,0); tmp.AddLine(0,0,0,1); MultMatrix(tmp); tmp.Destroy; end; procedure TMyMatrix.Translate(x,y,z:Extended); {перенос на вектор (x,y,z)} var tmp:TMyMatrix; begin tmp:=TMyMatrix.Create; tmp.AddLine(1,0,0,0); tmp.AddLine(0,1,0,0); tmp.AddLine(0,0,1,0); tmp.AddLine(x,y,z,1); MultMatrix(tmp); tmp.Destroy; end; procedure TMyMatrix.LoadIdentity; {единичная матрица} begin Clear; AddLine(1,0,0,0); AddLine(0,1,0,0); AddLine(0,0,1,0); AddLine(0,0,0,1); end; function TMyMatrix.GetX(line:Integer):Extended; {взять координату X} begin Result:=999999; if line<=hsize then Result:=arr[line-1,0]/arr[line-1,3]; end; function TMyMatrix.GetY(line:Integer):Extended; {взять координату Y} begin Result:=999999; if line<=hsize then Result:=arr[line-1,1]/arr[line-1,3]; end; function TMyMatrix.GetZ(line:Integer):Extended; {взять координату Z} begin Result:=999999; if line<=hsize then Result:=arr[line-1,2]/arr[line-1,3]; end; procedure TMyMatrix.Transpose; {транспонирование матрицы 4x4} var i,j:Integer; tmp:TMatrixArray; begin if hsize=4 then begin SetLength(tmp,4); for i:=0 to 3 do for j:=0 to 3 do tmp[i,j]:=arr[i,j]; for i:=0 to 3 do for j:=0 to 3 do arr[i,j]:=tmp[j,i]; end; end; procedure TMyMatrix.FrustumProjection(l,r,b,t,n,f:Extended); {перспективная проекция} var tmp:TMyMatrix; begin tmp:=TMyMatrix.Create; tmp.AddLine(2*n/(r-l),0,0,0); tmp.AddLine(0,2*n/(t-b),0,0); tmp.AddLine((r+l)/(r-l),(t+b)/(t-b),-(f+n)/(f-n),-1); tmp.AddLine(0,0,-2*f*n/(f-n),0); MultMatrix(tmp); tmp.Destroy; end; procedure TMyMatrix.OrthoProjection(l,r,b,t,n,f:Extended); {ортогональная проекция} var tmp:TMyMatrix; begin tmp:=TMyMatrix.Create; tmp.AddLine(2/(r-l),0,0,0); tmp.AddLine(0,2/(t-b),0,0); tmp.AddLine(0,0,-2/(f-n),0); tmp.AddLine((r+l)/(r-l),(t+b)/(t-b),(f+n)/(f-n),1); MultMatrix(tmp); tmp.Destroy; end; procedure TMyMatrix.ParallelProjectionXY(z0:Extended); {параллельная проекция в плоскость xy} var tmp:TMyMatrix; begin tmp:=TMyMatrix.Create; tmp.AddLine(1,0,0,0); tmp.AddLine(0,1,0,0); tmp.AddLine(0,0,0,0); tmp.AddLine(0,0,z0,1); MultMatrix(tmp); tmp.Destroy; end; procedure TMyMatrix.ParallelProjectionXZ(y0:Extended); {параллельная проекция в плоскость xz} var tmp:TMyMatrix; begin tmp:=TMyMatrix.Create; tmp.AddLine(1,0,0,0); tmp.AddLine(0,0,0,0); tmp.AddLine(0,0,1,0); tmp.AddLine(0,y0,0,1); MultMatrix(tmp); tmp.Destroy; end; procedure TMyMatrix.ParallelProjectionYZ(x0:Extended); {параллельная проекция в плоскость yz} var tmp:TMyMatrix; begin tmp:=TMyMatrix.Create; tmp.AddLine(0,0,0,0); tmp.AddLine(0,1,0,0); tmp.AddLine(0,0,1,0); tmp.AddLine(x0,0,0,1); MultMatrix(tmp); tmp.Destroy; end; procedure TMyMatrix.Perspective(fovy,aspect,znear,zfar:Extended); {перспективная проекция} var tmp:TMyMatrix; cotangent, radians, sine, deltaZ:Extended; begin radians:=(fovy/2)*pi/180; sine:=sin(radians); cotangent:=cos(radians)/sine; deltaZ:=zFar-zNear; tmp:=TMyMatrix.Create; tmp.AddLine(cotangent/aspect,0,0,0); tmp.AddLine(0,cotangent,0,0); tmp.AddLine(0,0,-(zFar+zNear)/deltaZ,-1); tmp.AddLine(0,0,-2*zNear*zFar/deltaZ,0); MultMatrix(tmp); tmp.Destroy; end; procedure TMyMatrix.Normalize(var v:TVector3); {нормализация вектора} var r:Extended; begin r:=sqrt(sqr(v[0])+sqr(v[1])+sqr(v[2])); if r<>0 then begin v[0]:=v[0]/r; v[1]:=v[1]/r; v[2]:=v[2]/r; end; end; procedure TMyMatrix.Cross(v1,v2:TVector3; var r:TVector3); {векторное произведение} begin r[0]:=v1[1]*v2[2]-v1[2]*v2[1]; r[1]:=v1[2]*v2[0]-v1[0]*v2[2]; r[2]:=v1[0]*v2[1]-v1[1]*v2[0]; end; procedure TMyMatrix.LookAt(eyex,eyey,eyez, centerx,centery,centerz, upx,upy,upz:Extended); {позиционирование камеры} var fwd,side,up:TVector3; tmp:TMyMatrix; begin fwd[0]:=centerx-eyex; fwd[1]:=centery-eyey; fwd[2]:=centerz-eyez; up[0]:=upx; up[1]:=upy; up[2]:=upz; Normalize(fwd); Cross(fwd,up,side); Normalize(side); Cross(side,fwd,up); tmp:=TMyMatrix.Create; tmp.AddLine(side[0],up[0],-fwd[0],0); tmp.AddLine(side[1],up[1],-fwd[1],0); tmp.AddLine(side[2],up[2],-fwd[2],0); tmp.AddLine(0,0,0,1); MultMatrix(tmp); Translate(-eyex,-eyey,-eyez); tmp.Destroy; end; procedure TMyMatrix.Copy(m:TMyMatrix); var i,j:Integer; begin if hsize>0 then begin SetLength(m.arr,hsize); for i:=0 to hsize-1 do for j:=0 to 3 do m.arr[i,j]:=arr[i,j]; m.hsize:=hsize; end; end; procedure TMyMatrix.Sort; var tmp1,tmp2,tmp3:TVector4; j:Integer; f:Boolean; begin f:=True; while f do begin f:=False; for j:=0 to hsize-4 do begin if j mod 3 = 0 then if (arr[j,2]+arr[j+1,2]+arr[j+2,2])<(arr[j+3,2]+arr[j+4,2]+arr[j+5,2]) then begin tmp1:=arr[j]; tmp2:=arr[j+1]; tmp3:=arr[j+2]; arr[j]:=arr[j+3]; arr[j+1]:=arr[j+4]; arr[j+2]:=arr[j+5]; arr[j+3]:=tmp1; arr[j+4]:=tmp2; arr[j+5]:=tmp3; f:=True; end; end; end; end; end.
{******************************************************************************} { } { WiRL: RESTful Library for Delphi } { } { Copyright (c) 2015-2019 WiRL Team } { } { https://github.com/delphi-blocks/WiRL } { } {******************************************************************************} unit WiRL.http.Response; interface uses System.SysUtils, System.Classes, WiRL.Http.Core, WiRL.http.Cookie, WiRL.http.Accept.MediaType; type TWiRLResponse = class private FCookie: TWiRLCookies; FMediaType: TMediaType; FHeaderFields: TWiRLHeaderList; FHasContentLength: Boolean; function GetContentType: string; procedure SetContentType(const Value: string); function GetDate: TDateTime; procedure SetDate(const Value: TDateTime); function GetExpires: TDateTime; procedure SetExpires(const Value: TDateTime); function GetLastModified: TDateTime; procedure SetLastModified(const Value: TDateTime); function GetContentMediaType: TMediaType; function GetContentLength: Int64; procedure SetContentLength(const Value: Int64); function GetConnection: string; procedure SetConnection(const Value: string); function GetRawContent: TBytes; procedure SetRawContent(const Value: TBytes); function GetContentEncoding: string; procedure SetContentEncoding(const Value: string); function GetAllow: string; procedure SetAllow(const Value: string); function GetServer: string; procedure SetServer(const Value: string); function GetWWWAuthenticate: string; procedure SetWWWAuthenticate(const Value: string); function GetLocation: string; procedure SetLocation(const Value: string); function GetContentLanguage: string; procedure SetContentLanguage(const Value: string); function GetCookies: TWiRLCookies; protected function IsUnknownResponseCode: Boolean; virtual; function GetHeaderFields: TWiRLHeaderList; function GetContent: string; virtual; abstract; function GetContentStream: TStream; virtual; abstract; procedure SetContent(const Value: string); virtual; abstract; procedure SetContentStream(const Value: TStream); virtual; abstract; function GetStatusCode: Integer; virtual; abstract; procedure SetStatusCode(const Value: Integer); virtual; abstract; function GetReasonString: string; virtual; abstract; procedure SetReasonString(const Value: string); virtual; abstract; public procedure SendHeaders; virtual; abstract; destructor Destroy; override; procedure FromWiRLStatus(AStatus: TWiRLHttpStatus); procedure Redirect(ACode: Integer; const ALocation: string); procedure SetNonStandardReasonString(const AValue: string); property HasContentLength: Boolean read FHasContentLength; property Date: TDateTime read GetDate write SetDate; property Expires: TDateTime read GetExpires write SetExpires; property LastModified: TDateTime read GetLastModified write SetLastModified; property Content: string read GetContent write SetContent; property ContentEncoding: string read GetContentEncoding write SetContentEncoding; property ContentLanguage: string read GetContentLanguage write SetContentLanguage; property ContentStream: TStream read GetContentStream write SetContentStream; property StatusCode: Integer read GetStatusCode write SetStatusCode; property ReasonString: string read GetReasonString write SetReasonString; property ContentType: string read GetContentType write SetContentType; property ContentLength: Int64 read GetContentLength write SetContentLength; property HeaderFields: TWiRLHeaderList read GetHeaderFields; property ContentMediaType: TMediaType read GetContentMediaType; property Connection: string read GetConnection write SetConnection; property RawContent: TBytes read GetRawContent write SetRawContent; property Allow: string read GetAllow write SetAllow; property Server: string read GetServer write SetServer; property WWWAuthenticate: string read GetWWWAuthenticate write SetWWWAuthenticate; property Location: string read GetLocation write SetLocation; property Cookies: TWiRLCookies read GetCookies; end; implementation uses IdGlobal, IdGlobalProtocols; { TWiRLResponse } destructor TWiRLResponse.Destroy; begin FHeaderFields.Free; FMediaType.Free; FCookie.Free; inherited; end; procedure TWiRLResponse.FromWiRLStatus(AStatus: TWiRLHttpStatus); begin StatusCode := AStatus.Code; if not AStatus.Reason.IsEmpty then ReasonString := AStatus.Reason; if not AStatus.Location.IsEmpty then Location := AStatus.Location; end; function TWiRLResponse.GetAllow: string; begin Result := HeaderFields.Values['Allow']; end; function TWiRLResponse.GetConnection: string; begin Result := HeaderFields.Values['Connection']; end; function TWiRLResponse.GetContentEncoding: string; begin Result := HeaderFields.Values['Content-Encoding']; end; function TWiRLResponse.GetContentLanguage: string; begin Result := HeaderFields.Values['Content-Language']; end; function TWiRLResponse.GetContentLength: Int64; begin Result := StrToInt64Def(HeaderFields.Values['Content-Length'], -1); end; function TWiRLResponse.GetContentMediaType: TMediaType; begin if not Assigned(FMediaType) then FMediaType := TMediaType.Create(ContentType); Result := FMediaType; end; function TWiRLResponse.GetContentType: string; begin Result := HeaderFields.Values['Content-Type']; end; function TWiRLResponse.GetCookies: TWiRLCookies; begin if not Assigned(FCookie) then FCookie := TWiRLCookies.Create; Result := FCookie; end; function TWiRLResponse.GetDate: TDateTime; var LValue: string; begin LValue := HeaderFields.Values['Date']; if LValue = '' then Result := Now else Result := GMTToLocalDateTime(LValue); end; function TWiRLResponse.GetExpires: TDateTime; var LValue: string; begin LValue := HeaderFields.Values['Expires']; if LValue = '' then Result := 0 else Result := GMTToLocalDateTime(LValue); end; function TWiRLResponse.GetHeaderFields: TWiRLHeaderList; begin if not Assigned(FHeaderFields) then FHeaderFields := TWiRLHeaderList.Create; Result := FHeaderFields; end; function TWiRLResponse.GetLastModified: TDateTime; var LValue: string; begin LValue := HeaderFields.Values['Last-Modified']; if LValue = '' then Result := 0 else Result := GMTToLocalDateTime(LValue); end; function TWiRLResponse.GetLocation: string; begin Result := HeaderFields.Values['Location']; end; function TWiRLResponse.GetRawContent: TBytes; begin if (GetContentStream <> nil) and (GetContentStream.Size > 0) then begin GetContentStream.Position := 0; SetLength(Result, GetContentStream.Size); GetContentStream.ReadBuffer(Result[0], GetContentStream.Size); end; end; function TWiRLResponse.GetServer: string; begin Result := HeaderFields.Values['Server']; end; function TWiRLResponse.IsUnknownResponseCode: Boolean; begin Result := False; end; function TWiRLResponse.GetWWWAuthenticate: string; begin Result := HeaderFields.Values['WWW-Authenticate']; end; procedure TWiRLResponse.Redirect(ACode: Integer; const ALocation: string); begin Assert((ACode >= 300) and (ACode < 400), 'Redirect code must be of 300 class'); StatusCode := ACode; Location := ALocation; end; procedure TWiRLResponse.SetAllow(const Value: string); begin HeaderFields.Values['Allow'] := Value; end; procedure TWiRLResponse.SetConnection(const Value: string); begin HeaderFields.Values['Connection'] := Value; end; procedure TWiRLResponse.SetContentEncoding(const Value: string); begin HeaderFields.Values['Content-Encoding'] := Value; end; procedure TWiRLResponse.SetContentLanguage(const Value: string); begin HeaderFields.Values['Content-Language'] := Value; end; procedure TWiRLResponse.SetContentLength(const Value: Int64); begin FHasContentLength := True; HeaderFields.Values['Content-Length'] := IntToStr(Value); end; procedure TWiRLResponse.SetContentType(const Value: string); begin HeaderFields.Values['Content-Type'] := Value; end; procedure TWiRLResponse.SetDate(const Value: TDateTime); begin HeaderFields.Values['Date'] := LocalDateTimeToHttpStr(Value); end; procedure TWiRLResponse.SetExpires(const Value: TDateTime); begin if Value = 0 then HeaderFields.Values['Expires'] := '' else HeaderFields.Values['Expires'] := LocalDateTimeToHttpStr(Value); end; procedure TWiRLResponse.SetLastModified(const Value: TDateTime); begin if Value = 0 then HeaderFields.Values['Last-Modified'] := '' else HeaderFields.Values['Last-Modified'] := LocalDateTimeToHttpStr(Value); end; procedure TWiRLResponse.SetLocation(const Value: string); begin HeaderFields.Values['Location'] := Value; end; procedure TWiRLResponse.SetNonStandardReasonString(const AValue: string); begin if (ReasonString = '') or IsUnknownResponseCode then ReasonString := Avalue; end; procedure TWiRLResponse.SetRawContent(const Value: TBytes); var LStream: TStream; begin LStream := TBytesStream.Create(Value); ContentStream := LStream; end; procedure TWiRLResponse.SetServer(const Value: string); begin HeaderFields.Values['Server'] := Value; end; procedure TWiRLResponse.SetWWWAuthenticate(const Value: string); begin HeaderFields.Values['WWW-Authenticate'] := Value; end; end.