text
stringlengths
14
6.51M
unit UUngetStream; (* Copyright (c) 2001,2002 Twiddle <hetareprog@hotmail.com> *) interface uses Classes, StrUtils; type (* seek不可でもungetcの機能が使えるストリーム *) TUngetStream = class(TStream) protected FStream: TStream; ungets: string; public constructor Create(stream: TStream); destructor Destroy; override; procedure Unget(c: Char); function Read(var Buffer; Count: Longint): Longint; override; function Write(const Buffer; Count: Longint): Longint; override; end; (*=======================================================*) implementation (*=======================================================*) constructor TUngetStream.Create(stream: TStream); begin FStream := stream; end; destructor TUngetStream.Destroy; begin inherited; end; procedure TUngetStream.Unget(c: Char); begin ungets := ungets + c; end; function TUngetStream.Read(var Buffer; Count: Longint): Longint; var ptr: PByte; len: integer; begin ptr := @Buffer; result := 0; while (result < Count) do begin len := length(ungets); if 0 < len then begin ptr^ := Ord(ungets[len]); SetLength(ungets, len-1); Inc(ptr); Inc(result); end else begin Inc(result, FStream.Read(ptr^, Count - result)); break; end; end; end; function TUngetStream.Write(const Buffer; Count: Longint): Longint; begin result := inherited Write(Buffer, Count); end; end.
unit Ntapi.NtSecApi; { This module defines types and functions for working with auditing policies and logon sessions. } interface {$MINENUMSIZE 4} uses Ntapi.ntdef, Ntapi.WinNt, Ntapi.ntseapi, DelphiApi.Reflection; const secur32 = 'secur32.dll'; // SDK::NTSecAPI.h - auditing options POLICY_AUDIT_EVENT_UNCHANGED = $0; POLICY_AUDIT_EVENT_SUCCESS = $1; POLICY_AUDIT_EVENT_FAILURE = $2; POLICY_AUDIT_EVENT_NONE = $4; // SDK::NTSecAPI.h - user audit overrides PER_USER_POLICY_UNCHANGED = $00; PER_USER_AUDIT_SUCCESS_INCLUDE = $01; PER_USER_AUDIT_SUCCESS_EXCLUDE = $02; PER_USER_AUDIT_FAILURE_INCLUDE = $04; PER_USER_AUDIT_FAILURE_EXCLUDE = $08; PER_USER_AUDIT_NONE = $10; // SDK::NTSecAPI.h - logon flags LOGON_GUEST = $01; LOGON_NOENCRYPTION = $02; LOGON_CACHED_ACCOUNT = $04; LOGON_USED_LM_PASSWORD = $08; LOGON_EXTRA_SIDS = $20; LOGON_SUBAUTH_SESSION_KEY = $40; LOGON_SERVER_TRUST_ACCOUNT = $80; LOGON_NTLMV2_ENABLED = $100; LOGON_RESOURCE_GROUPS = $200; LOGON_PROFILE_PATH_RETURNED = $400; LOGON_NT_V2 = $800; LOGON_LM_V2 = $1000; LOGON_NTLM_V2 = $2000; LOGON_OPTIMIZED = $4000; LOGON_WINLOGON = $8000; LOGON_PKINIT = $10000; LOGON_NO_OPTIMIZED = $20000; LOGON_NO_ELEVATION = $40000; LOGON_MANAGED_SERVICE = $80000; NEGOSSP_NAME_A = AnsiString('Negotiate'); // SDK::NTSecAPI.h MSV1_0_PACKAGE_NAME = AnsiString('MICROSOFT_AUTHENTICATION_PACKAGE_V1_0'); // SDK::NTSecAPI.h MICROSOFT_KERBEROS_NAME_A = AnsiString('Kerberos'); type TLsaHandle = THandle; TLsaOperationalMode = Cardinal; [SDKName('LSA_STRING')] TLsaAnsiString = TNtAnsiString; PLsaAnsiString = PNtAnsiString; [SDKName('LSA_UNICODE_STRING')] TLsaUnicodeString = TNtUnicodeString; PLsaUnicodeString = PNtUnicodeString; TLuidArray = TAnysizeArray<TLuid>; PLuidArray = ^TLuidArray; TGuidArray = TAnysizeArray<TGuid>; PGuidArray = ^TGuidArray; [SubEnum($7, POLICY_AUDIT_EVENT_UNCHANGED, 'Unchanged')] [FlagName(POLICY_AUDIT_EVENT_SUCCESS, 'Success')] [FlagName(POLICY_AUDIT_EVENT_FAILURE, 'Failure')] [FlagName(POLICY_AUDIT_EVENT_NONE, 'None')] TAuditEventPolicy = type Cardinal; [SubEnum($1F, PER_USER_POLICY_UNCHANGED, 'Unchanged')] [FlagName(PER_USER_AUDIT_SUCCESS_INCLUDE, 'Include Success')] [FlagName(PER_USER_AUDIT_SUCCESS_EXCLUDE, 'Exclude Success')] [FlagName(PER_USER_AUDIT_FAILURE_INCLUDE, 'Include Failure')] [FlagName(PER_USER_AUDIT_FAILURE_EXCLUDE, 'Exclude Failure')] [FlagName(PER_USER_AUDIT_NONE, 'None')] TAuditEventPolicyOverride = type Cardinal; // SDK::NTSecAPI.h [SDKName('SECURITY_LOGON_TYPE')] [NamingStyle(nsCamelCase, 'LogonType')] TSecurityLogonType = ( LogonTypeSystem = 0, LogonTypeReserved = 1, LogonTypeInteractive = 2, LogonTypeNetwork = 3, LogonTypeBatch = 4, LogonTypeService = 5, LogonTypeProxy = 6, LogonTypeUnlock = 7, LogonTypeNetworkCleartext = 8, LogonTypeNewCredentials = 9, LogonTypeRemoteInteractive = 10, LogonTypeCachedInteractive = 11, LogonTypeCachedRemoteInteractive = 12, LogonTypeCachedUnlock = 13 ); // SDK::NTSecAPI.h [SDKName('LSA_LAST_INTER_LOGON_INFO')] TLsaLastInterLogonInfo = record LastSuccessfulLogon: TLargeInteger; LastFailedLogon: TLargeInteger; FailedAttemptsSinceLastSuccessfulLogon: Cardinal; end; PLsaLastInterLogonInfo = ^TLsaLastInterLogonInfo; [FlagName(LOGON_GUEST, 'Guest')] [FlagName(LOGON_NOENCRYPTION, 'No Encryption')] [FlagName(LOGON_CACHED_ACCOUNT, 'Cached Account')] [FlagName(LOGON_USED_LM_PASSWORD, 'Used LM Password')] [FlagName(LOGON_EXTRA_SIDS, 'Extra SIDs')] [FlagName(LOGON_SUBAUTH_SESSION_KEY, 'Sub-auth Session Key')] [FlagName(LOGON_SERVER_TRUST_ACCOUNT, 'Server Trust Account')] [FlagName(LOGON_NTLMV2_ENABLED, 'NTLMv2 Enabled')] [FlagName(LOGON_RESOURCE_GROUPS, 'Resource Groups')] [FlagName(LOGON_PROFILE_PATH_RETURNED, 'Profile Path Returned')] [FlagName(LOGON_NT_V2, 'NTv2')] [FlagName(LOGON_LM_V2, 'LMv2')] [FlagName(LOGON_NTLM_V2, 'NTLMv2')] [FlagName(LOGON_OPTIMIZED, 'Optimized')] [FlagName(LOGON_WINLOGON, 'Winlogon')] [FlagName(LOGON_PKINIT, 'PKINIT')] [FlagName(LOGON_NO_OPTIMIZED, 'Not Optimized')] [FlagName(LOGON_NO_ELEVATION, 'No Elevation')] [FlagName(LOGON_MANAGED_SERVICE, 'Managed Service')] TLogonFlags = type Cardinal; // SDK::NTSecAPI.h [SDKName('SECURITY_LOGON_SESSION_DATA')] TSecurityLogonSessionData = record [Bytes, Unlisted] Size: Cardinal; LogonID: TLuid; UserName: TLsaUnicodeString; LogonDomain: TLsaUnicodeString; AuthenticationPackage: TLsaUnicodeString; LogonType: TSecurityLogonType; Session: TSessionId; SID: PSid; LogonTime: TLargeInteger; LogonServer: TLsaUnicodeString; DNSDomainName: TLsaUnicodeString; UPN: TLsaUnicodeString; UserFlags: TLogonFlags; [Aggregate] LastLogonInfo: TLsaLastInterLogonInfo; LogonScript: TLsaUnicodeString; ProfilePath: TLsaUnicodeString; HomeDirectory: TLsaUnicodeString; HomeDirectoryDrive: TLsaUnicodeString; LogoffTime: TLargeInteger; KickoffTime: TLargeInteger; PasswordLastSet: TLargeInteger; PasswordCanChange: TLargeInteger; PasswordMustChange: TLargeInteger; end; PSecurityLogonSessionData = ^TSecurityLogonSessionData; // SDK::NTSecAPI.h [SDKName('KERB_LOGON_SUBMIT_TYPE')] [NamingStyle(nsCamelCase, 'Kerb'), Range(2)] TKerbLogonSubmitType = ( KerbInvalid = 0, KerbReserved = 1, KerbInteractiveLogon = 2, KerbSmartCardLogon = 6, KerbWorkstationUnlockLogon = 7, KerbSmartCardUnlockLogon = 8, KerbProxyLogon = 9, KerbTicketLogon = 10, KerbTicketUnlockLogon = 11, KerbS4ULogon = 12, KerbCertificateLogon = 13, KerbCertificateS4ULogon = 14, KerbCertificateUnlockLogon = 15 ); // SDK::NTSecAPI.h [SDKName('KERB_S4U_LOGON')] TKerbS4ULogon = record MessageType: TKerbLogonSubmitType; [Hex] Flags: Cardinal; ClientUPN: TLsaUnicodeString; ClientRealm: TLsaUnicodeString; end; PKerbS4ULogon = ^TKerbS4ULogon; TSidArray = TAnysizeArray<PSid>; PSidArray = ^TSidArray; // SDK::NTSecAPI.h [SDKName('POLICY_AUDIT_SID_ARRAY')] TPolicyAuditSidArray = record [Counter] UsersCount: Cardinal; UserSIDArray: PSidArray; end; PPolicyAuditSidArray = ^TPolicyAuditSidArray; // SDK::NTSecAPI.h [SDKName('AUDIT_POLICY_INFORMATION')] TAuditPolicyInformation = record AuditSubcategoryGUID: TGuid; AuditingInformation: Cardinal; AuditCategoryGUID: TGuid; end; PAuditPolicyInformation = ^TAuditPolicyInformation; TAuditPolicyInformationArray = TAnysizeArray<TAuditPolicyInformation>; PAuditPolicyInformationArray = ^TAuditPolicyInformationArray; // SDK::NTSecAPI.h [RequiredPrivilege(SE_TCB_PRIVILEGE, rpAlways)] function LsaRegisterLogonProcess( [in] const LogonProcessName: TLsaAnsiString; [out, ReleaseWith('LsaDeregisterLogonProcess')] out LsaHandle: TLsaHandle; [out] out SecurityMode: TLsaOperationalMode ): NTSTATUS; stdcall; external secur32; // SDK::NTSecAPI.h [RequiredPrivilege(SE_TCB_PRIVILEGE, rpSometimes)] function LsaLogonUser( [in] LsaHandle: TLsaHandle; [in] const OriginName: TLsaAnsiString; [in] LogonType: TSecurityLogonType; [in] AuthenticationPackage: Cardinal; [in, ReadsFrom] AuthenticationInformation: Pointer; [in, NumberOfBytes] AuthenticationInformationLength: Cardinal; [in, opt] LocalGroups: PTokenGroups; [in] const SourceContext: TTokenSource; [out, ReleaseWith('LsaFreeReturnBuffer')] out ProfileBuffer: Pointer; [out] out ProfileBufferLength: Cardinal; [out] out LogonId: TLogonId; [out, ReleaseWith('NtClose')] out hToken: THandle; [out] out Quotas: TQuotaLimits; [out] out SubStatus: NTSTATUS ): NTSTATUS; stdcall; external secur32; // SDK::NTSecAPI.h function LsaLookupAuthenticationPackage( [in] LsaHandle: TLsaHandle; [in] const PackageName: TLsaAnsiString; [out] out AuthenticationPackage: Cardinal ): NTSTATUS; stdcall; external secur32; // SDK::NTSecAPI.h function LsaFreeReturnBuffer( [in] Buffer: Pointer ): NTSTATUS; stdcall; external secur32; // SDK::NTSecAPI.h function LsaDeregisterLogonProcess( [in] LsaHandle: TLsaHandle ): NTSTATUS; stdcall; external secur32; // SDK::NTSecAPI.h function LsaConnectUntrusted( [out, ReleaseWith('LsaDeregisterLogonProcess')] out LsaHandle: TLsaHandle ): NTSTATUS; stdcall; external secur32; // SDK::NTSecAPI.h function LsaEnumerateLogonSessions( [out, NumberOfElements] out LogonSessionCount: Integer; [out, ReleaseWith('LsaFreeReturnBuffer')] out LogonSessionList: PLuidArray ): NTSTATUS; stdcall; external secur32; // SDK::NTSecAPI.h function LsaGetLogonSessionData( [in] const [ref] LogonId: TLogonId; [out, ReleaseWith('LsaFreeReturnBuffer')] out LogonSessionData: PSecurityLogonSessionData ): NTSTATUS; stdcall; external secur32; // SDK::NTSecAPI.h [SetsLastError] [RequiredPrivilege(SE_SECURITY_PRIVILEGE, rpAlways)] function AuditSetSystemPolicy( [in, ReadsFrom] const AuditPolicy: TArray<TAuditPolicyInformation>; [in, NumberOfElements] PolicyCount: Cardinal ): Boolean; stdcall; external advapi32; // SDK::NTSecAPI.h [SetsLastError] [RequiredPrivilege(SE_SECURITY_PRIVILEGE, rpAlways)] function AuditSetPerUserPolicy( [in] Sid: PSid; [in, ReadsFrom] const AuditPolicy: TArray<TAuditPolicyInformation>; [in, NumberOfBytes] PolicyCount: Cardinal ): Boolean; stdcall; external advapi32; // SDK::NTSecAPI.h [SetsLastError] [RequiredPrivilege(SE_SECURITY_PRIVILEGE, rpWithExceptions)] function AuditQuerySystemPolicy( [in, ReadsFrom] const SubCategoryGuids: TArray<TGuid>; [in, NumberOfElements] PolicyCount: Cardinal; [out, ReleaseWith('AuditFree')] out AuditPolicy: PAuditPolicyInformationArray ): Boolean; stdcall; external advapi32; // SDK::NTSecAPI.h [SetsLastError] [RequiredPrivilege(SE_SECURITY_PRIVILEGE, rpWithExceptions)] function AuditQueryPerUserPolicy( [in] Sid: PSid; [in, ReadsFrom] const SubCategoryGuids: TArray<TGuid>; [in, NumberOfElements] PolicyCount: Cardinal; [out, ReleaseWith('AuditFree')] out AuditPolicy: PAuditPolicyInformationArray ): Boolean; stdcall; external advapi32; // SDK::NTSecAPI.h [SetsLastError] function AuditEnumeratePerUserPolicy( [out, ReleaseWith('AuditFree')] out AuditSidArray: PPolicyAuditSidArray ): Boolean; stdcall; external advapi32; // SDK::NTSecAPI.h [SetsLastError] function AuditEnumerateCategories( [out, ReleaseWith('AuditFree')] out AuditCategoriesArray: PGuidArray; out CountReturned: Cardinal ): Boolean; stdcall; external advapi32; // SDK::NTSecAPI.h [SetsLastError] function AuditEnumerateSubCategories( [in, opt] AuditCategoryGuid: PGuid; [in] RetrieveAllSubCategories: Boolean; [out, ReleaseWith('AuditFree')] out AuditSubCategoriesArray: PGuidArray; [out, NumberOfElements] out CountReturned: Cardinal ): Boolean; stdcall; external advapi32; // SDK::NTSecAPI.h [SetsLastError] function AuditLookupCategoryNameW( [in] const AuditCategoryGuid: TGuid; [out, ReleaseWith('AuditFree')] out CategoryName: PWideChar ): Boolean; stdcall; external advapi32; // SDK::NTSecAPI.h [SetsLastError] function AuditLookupSubCategoryNameW( [in] const AuditSubCategoryGuid: TGuid; [out, ReleaseWith('AuditFree')] out SubCategoryName: PWideChar ): Boolean; stdcall; external advapi32; // SDK::NTSecAPI.h [SetsLastError] procedure AuditFree( [in] Buffer: Pointer ); stdcall; external advapi32; implementation {$BOOLEVAL OFF} {$IFOPT R+}{$DEFINE R+}{$ENDIF} {$IFOPT Q+}{$DEFINE Q+}{$ENDIF} end.
{***************************************************************************} { } { DUnitX } { } { Copyright (C) 2017 Vincent Parrett } { } { vincent@finalbuilder.com } { http://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DUnitX.Tests.Example; interface {$I ..\Source\DUnitX.inc} uses DUnitX.TestFramework, {$IFDEF USE_NS} System.SysUtils; {$ELSE} SysUtils; {$ENDIF} type {$M+} [TestFixture('ExampleFixture1')] [Category('examples')] TMyExampleTests = class public //Run the same test with mulitiple parameters. //ideally we would like to implement this using //[TestCase('Case 1',[1,3,4])] //but the delphi compiler will not accept arrays of //TValue as parameters to attributes, so we have to use //a string constant.. the attribute will split the string //and attempt to convert the values to the parameters of the //test method. //TODO: Add named params so that certain params can be passed and others are defaulted. //TODO: Add TestCase where the params are over and under the actually name to pass. //TODO: Make sure that each test case is passed and run only once, currently run multiple times. Actually its X*X times where X is the number of test cases in the fixture. [Test] [TestCase('Case 1','1,2')] [TestCase('Case 2','3,4')] [TestCase('Case 3','5,6')] procedure TestOne(param1 : integer; param2 : integer); [TestCase('Case 3','Blah,1')] procedure AnotherTestMethod(const a : string; const b : integer); [Test] [TestCase('Date, space, time', '1988-10-21 17:44:23.456')] [TestCase('Date, T, time', '1988-10-21T17:44:23.456')] [TestCase('Date, T, time, Z', '1988-10-21T17:44:23.456Z')] [TestCase('Date, T, time, offset (1)', '1988-10-21T17:44:23.456+02:30')] [TestCase('Date, T, time, offset (2)', '1988-10-21T17:44:23.456+0230')] procedure TestDateTimeArgument(dateTime: TDateTime); [Test] [TestCase('Just date', '1988-10-21')] procedure TestDateArgument(const date: TDate); [Test] [TestCase('time with ms', '17:44:23.456')] [TestCase('time without ms', '17:44:23')] procedure TestTimeArgument(time: TTime); [Test] [Category('Bar,foo')] procedure TestTwo; [Test] [Category('Bar,foo')] procedure TestTwoOne; [Test] [MaxTime(1000)] procedure TestMaxTime; //Disabled test [Test(false)] procedure DontCallMe; [Test] [Ignore('I was told to ignore me')] procedure IgnoreMe; [WillRaise(EOutOfMemory)] procedure FailMe; [WillRaise(EHeapException, exDescendant)] procedure FailMeToo; [WillRaise(Exception, exDescendant)] procedure FailAny; [WillRaise(EOutOfMemory)] [Ignore('I am not behaving as I should')] procedure IgnoreMeCauseImWrong; [Setup] procedure Setup; [TearDown] procedure TearDown; published [Category('blah')] procedure TestMeAnyway; [Ignore('I was told to ignore me anyway')] procedure IgnoreMeAnyway; end; [TestFixture] TExampleFixture2 = class private FPublished_Procedures_Are_Included_As_Tests_Called : Boolean; public [Setup] procedure SetupFixture; [Teardown] procedure TearDownFixture; destructor Destroy;override; published procedure Published_Procedures_Are_Included_As_Tests; end; [TestFixture] TExampleFixture3 = class private FSetupCalled : boolean; public // Testing constructor/destructor as fixture setup/teardown // Delphi 2010 does support calling of constructor {$IFDEF DELPHI_XE_UP} constructor Create; {$ELSE} procedure AfterConstruction; override; {$ENDIF} destructor Destroy;override; [SetupFixture] procedure SetupFixture; published procedure ATest; end; implementation uses DUnitX.DUnitCompatibility, DUnitX.Exceptions, System.Diagnostics, {$IFDEF USE_NS} System.DateUtils; {$ELSE} Diagnostics, DateUtils; {$ENDIF} procedure TMyExampleTests.DontCallMe; begin TDUnitX.CurrentRunner.Status('DontCallMe called'); raise Exception.Create('DontCallMe was called!!!!'); end; procedure TMyExampleTests.FailAny; begin Abort; end; procedure TMyExampleTests.FailMe; begin OutOfMemoryError; end; procedure TMyExampleTests.FailMeToo; begin OutOfMemoryError; end; procedure TMyExampleTests.IgnoreMe; begin Assert.IsTrue(false,'I should not have been called!'); end; procedure TMyExampleTests.IgnoreMeAnyway; begin Assert.IsTrue(false,'I should not have been called!'); end; procedure TMyExampleTests.IgnoreMeCauseImWrong; begin Abort; end; procedure TMyExampleTests.Setup; begin TDUnitX.CurrentRunner.Status('Setup called'); end; procedure TMyExampleTests.TearDown; begin TDUnitX.CurrentRunner.Status('TearDown called'); end; procedure TMyExampleTests.AnotherTestMethod(const a: string; const b: integer); begin TDUnitX.CurrentRunner.Status(Format('TestCaseBlah called with %s %d',[a,b])); Assert.Pass; end; procedure TMyExampleTests.TestDateArgument(const date: TDate); var expected: TDate; begin expected := EncodeDate(1988, 10, 21); Assert.IsTrue( SameDate(expected, date) ); end; procedure TMyExampleTests.TestDateTimeArgument(dateTime: TDateTime); var expected: TDateTime; begin dateTime := RecodeMilliSecond(dateTime, 000); expected := EncodeDateTime(1988, 10, 21, 17, 44, 23, 000); Assert.IsTrue( SameDateTime(expected, dateTime) ); end; procedure TMyExampleTests.TestMaxTime; var elapsedTime : Int64; stopwatch : TStopWatch; begin stopwatch := TStopWatch.Create; stopwatch.Reset; stopwatch.Start; try repeat //Give some time back to the system to process the test. Sleep(20); elapsedTime := stopwatch.ElapsedMilliseconds; until (elapsedTime >= 2000); Assert.Fail('Timeout did not work'); except on e : ETimedOut do begin Assert.Pass('timed out as expected'); end; end; end; procedure TMyExampleTests.TestMeAnyway; begin TDUnitX.CurrentRunner.Status('TestMeAnyway called'); Assert.Pass; end; procedure TMyExampleTests.TestOne(param1 : integer; param2 : integer); begin TDUnitX.CurrentRunner.Status(Format('TestOnce called with %d %d',[param1,param2])); Assert.Pass; end; procedure TMyExampleTests.TestTimeArgument(time: TTime); var expected: TTime; begin time := RecodeMilliSecond(time, 0); expected := EncodeTime(17, 44, 23, 000); Assert.IsTrue( SameTime(expected, time) ); end; procedure TMyExampleTests.TestTwo; var x : TMyExampleTests; begin TDUnitX.CurrentRunner.Status('TestTwo called'); x := TMyExampleTests.Create; //CheckIs(x,TObject); //DUnit compatibility. TDUnitX.CurrentRunner.Status('hello world'); Assert.IsTrue(x is TObject); /// a bit pointless since it's strongly typed. x.Free; end; procedure TMyExampleTests.TestTwoOne; var x : TMyExampleTests; begin TDUnitX.CurrentRunner.Status('TestTwo called'); x := TMyExampleTests.Create; //CheckIs(x,TObject); //DUnit compatibility. TDUnitX.CurrentRunner.Status('hello world'); Assert.IsTrue(x is TObject); /// a bit pointless since it's strongly typed. x.Free; end; destructor TExampleFixture2.Destroy; begin //Empty inherited; end; procedure TExampleFixture2.Published_Procedures_Are_Included_As_Tests; begin FPublished_Procedures_Are_Included_As_Tests_Called := True; Assert.Pass; end; procedure TExampleFixture2.SetupFixture; begin TDUnitX.CurrentRunner.Log('Setting up...'); FPublished_Procedures_Are_Included_As_Tests_Called := False; end; procedure TExampleFixture2.TearDownFixture; begin TDUnitX.CurrentRunner.Log('Tearing down'); Assert.IsTrue(FPublished_Procedures_Are_Included_As_Tests_Called); end; procedure TExampleFixture3.ATest; begin Assert.IsTrue(FSetupCalled); end; {$IFDEF DELPHI_XE_UP} constructor TExampleFixture3.Create; {$ELSE} procedure TExampleFixture3.AfterConstruction; {$ENDIF} begin FSetupCalled := True; end; destructor TExampleFixture3.Destroy; begin //Empty inherited; end; procedure TExampleFixture3.SetupFixture; begin Assert.IsTrue(False,'I should not be called!'); end; initialization //I was hoping to use RTTI to discover the TestFixture classes, however unlike .NET //if we don't touch the class somehow then the linker will remove //the class from the resulting exe. //We could just do this: //TMyExampleTests.ClassName; //TExampleFixture2.ClassName; //which is enough to make the compiler link the classes into the exe, but that seems a //bit redundent so I guess we'll just use manual registration. If you use the //{$STRONGLINKTYPES ON} compiler directive then it will link the TestFixtures in and you //can use RTTI. The downside to that is the resulting exe will potentially much larger. //Not sure which version {$STRONGLINKTYPES ON} was introduced so we'll allow RTTI and //manual registration for now. //Register the test fixtures TDUnitX.RegisterTestFixture(TMyExampleTests); TDUnitX.RegisterTestFixture(TExampleFixture2); TDUnitX.RegisterTestFixture(TExampleFixture3); end.
unit RepositorioKit; interface uses DB, Auditoria, Repositorio; type TRepositorioKit = 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 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 ExecutaDepoisDeSalvar (Objeto :TObject); 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, Kit, FabricaRepositorio, Produto_Kit; { TRepositorioKit } procedure TRepositorioKit.ExecutaDepoisDeSalvar(Objeto: TObject); var Kit :TKit; repositorio :TRepositorio; ProdutoKit :TProduto_Kit; begin try repositorio := nil; Kit := (Objeto as TKit); repositorio := TFabricaRepositorio.GetRepositorio(TProduto_kit.ClassName); if assigned(Kit.ProdutosKit) then begin for ProdutoKit in Kit.ProdutosKit do begin ProdutoKit.codigo_kit := Kit.codigo; repositorio.Salvar( ProdutoKit ); end; end; finally FreeAndNil(repositorio); end; end; function TRepositorioKit.Get(Dataset: TDataSet): TObject; var Kit :TKit; begin Kit:= TKit.Create; Kit.codigo := self.FQuery.FieldByName('codigo').AsInteger; Kit.descricao := self.FQuery.FieldByName('descricao').AsString; result := Kit; end; function TRepositorioKit.GetIdentificador(Objeto: TObject): Variant; begin result := TKit(Objeto).Codigo; end; function TRepositorioKit.GetNomeDaTabela: String; begin result := 'KITS'; end; function TRepositorioKit.GetRepositorio: TRepositorio; begin result := TRepositorioKit.Create; end; function TRepositorioKit.IsInsercao(Objeto: TObject): Boolean; begin result := (TKit(Objeto).Codigo <= 0); end; procedure TRepositorioKit.SetCamposAlterados(Auditoria :TAuditoria; AntigoObjeto, Objeto :TObject); var KitAntigo :TKit; KitNovo :TKit; begin KitAntigo := (AntigoObjeto as TKit); KitNovo := (Objeto as TKit); if (KitAntigo.descricao <> KitNovo.descricao) then Auditoria.AdicionaCampoAlterado('descricao', KitAntigo.descricao, KitNovo.descricao); end; procedure TRepositorioKit.SetCamposExcluidos(Auditoria :TAuditoria; Objeto :TObject); var Kit :TKit; begin Kit := (Objeto as TKit); Auditoria.AdicionaCampoExcluido('codigo' , IntToStr(Kit.codigo)); Auditoria.AdicionaCampoExcluido('descricao', Kit.descricao); end; procedure TRepositorioKit.SetCamposIncluidos(Auditoria :TAuditoria; Objeto :TObject); var Kit :TKit; begin Kit := (Objeto as TKit); Auditoria.AdicionaCampoIncluido('codigo' , IntToStr(Kit.codigo)); Auditoria.AdicionaCampoIncluido('descricao', Kit.descricao); end; procedure TRepositorioKit.SetIdentificador(Objeto: TObject; Identificador: Variant); begin TKit(Objeto).Codigo := Integer(Identificador); end; procedure TRepositorioKit.SetParametros(Objeto: TObject); var Kit :TKit; begin Kit := (Objeto as TKit); self.FQuery.ParamByName('codigo').AsInteger := Kit.codigo; self.FQuery.ParamByName('descricao').AsString := Kit.descricao; end; function TRepositorioKit.SQLGet: String; begin result := 'select * from KITS where codigo = :ncod'; end; function TRepositorioKit.SQLGetAll: String; begin result := 'select * from KITS'; end; function TRepositorioKit.SQLGetExiste(campo: String): String; begin result := 'select '+ campo +' from KITS where '+ campo +' = :ncampo'; end; function TRepositorioKit.SQLRemover: String; begin result := ' delete from KITS where codigo = :codigo '; end; function TRepositorioKit.SQLSalvar: String; begin result := 'update or insert into KITS (CODIGO ,DESCRICAO) '+ ' values ( :CODIGO , :DESCRICAO) '; end; end.
unit uPrincipal; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, rtti, uPessoa; type TForm1 = class(TForm) btnGetMethod: TBitBtn; btngetField: TBitBtn; betGetProperty: TBitBtn; btnGetPropertyValues: TBitBtn; btnSetValues: TBitBtn; btnMethodTypes: TBitBtn; BtninvocaMetodo: TBitBtn; btnValidar: TBitBtn; btnTabelaCampo: TBitBtn; Memo1: TMemo; procedure btnGetMethodClick(Sender: TObject); procedure btngetFieldClick(Sender: TObject); procedure betGetPropertyClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.betGetPropertyClick(Sender: TObject); var VCtx: TRttiContext; VType: TRttiType; VProp: TRttiProperty; begin Memo1.Lines.Clear; VCtx := TRttiContext.Create.Create; try VType := VCtx.GetType(TPessoa); for VProp in VType.GetProperties do begin Memo1.Lines.Add(VProp.Name) end; finally VCtx.Free; end; end; procedure TForm1.btngetFieldClick(Sender: TObject); var VCtx: TRttiContext; VType: TRttiType; VField: TRttiField; begin VCtx := TRttiContext.Create.Create; try VType := VCtx.GetType(TPessoa); for VField in VType.GetFields do begin Memo1.Lines.Clear; Memo1.Lines.Add(VField.Name) end; finally VCtx.Free; end; end; procedure TForm1.btnGetMethodClick(Sender: TObject); var VCtx: TRttiContext; VTypes : TRttiType; VMet: TRttiMethod; begin VCtx := TRttiContext.Create; try VTypes := VCtx.GetType(TPessoa); for VMet in VTypes.GetMethods do begin Memo1.Lines.Add(VMet.Name); end; finally VCtx.Free; end; end; end.
unit ReciptHelperU; interface uses System.Classes, System.SysUtils, System.StrUtils ,System.Generics.Collections, System.UIConsts, System.UITypes, FMX.StdCtrls, FMX.Controls.Presentation, FMX.Ani, FMX.Layouts, FMX.Graphics, FMX.Objects, FMX.Types, FMX.Effects, FMX.ImgList, ItemsU, DataMU; Const rhPickAnimationTime = 0.5; rhNotSelectedColor = '#FFE0E0E0'; rhSelectedColor = claLime; type TReciptPanel = class private ReciptRect: TRectangle; LbHeading: TLabel; FRecipt: TRecipt; ItemGrid: TGridLayout; ItemRect: TRectangle; Image: TGlyph; FIsSelected: Boolean; FOwnerPanel: TGridLayout; // function CreateBtn(aOwner: TComponent): TButton; function CreateLabel(aOwner: TComponent): TLabel; function CreateItemRect(aOwner: TComponent): TRectangle; Function CreateImg(aOwner: TComponent): TGlyph; function CreateAnimation(aOwner: TComponent; ToColor: TAlphaColor): TColorAnimation; procedure ReciptBtnClick; procedure IsClicked(sender: TObject); procedure OnStateChange(IsSelected: Boolean); protected public procedure CreateOnScreen(const aRecipt: TRecipt); property Recipt: TRecipt Read FRecipt Write FRecipt; property IsSelected: Boolean Read FIsSelected Write FIsSelected; property OwnerPanel: TGridLayout Read FOwnerPanel Write FOwnerPanel; property GridLayout: TGridLayout Read ItemGrid Write ItemGrid; published end; TReciptPanellist = class(TObjectList<TReciptPanel>) private protected public constructor Create; procedure SetSelectedRecipt(const ReciptId: integer); published end; var CurrentReciptpanels: TReciptPanellist; implementation { TReciptPanel } //function TReciptPanel.CreateBtn(aOwner: TComponent): TButton; //begin // Result:= TButton.Create(aOwner); // with Result // do begin // Parent:= aOwner; // OnClick:= self.ReciptBtnClick; // Text:= ''; // end; //end; function TReciptPanel.CreateLabel(aOwner: TComponent): TLabel; begin Result:= TLabel.Create(aOwner); with Result do begin Parent:= aOwner as TFmxObject; Opacity:= 0.7; TextSettings.Font.Style:=[TFontStyle.fsBold]; TextAlign:= TTextAlign.Center; HitTest:= False; end; end; procedure TReciptPanel.CreateOnScreen(const aRecipt: TRecipt); begin ReciptRect:= TRectangle.Create(OwnerPanel); Recipt:= aRecipt; OwnerPanel.AddObject(ReciptRect); With ReciptRect do begin Parent:= OwnerPanel; Padding.Top:= 5; // Padding.Bottom:= 5; // Padding.Left:= 5; // Padding.Right:= 5; Align:= TAlignLayout.Client; OnClick:=Self.IsClicked; end; // SelectedEffect:= TGlowEffect.Create(ReciptRect); // SelectedEffect.GlowColor:=claLime; // SelectedEffect.Enabled:= True; // ReciptRect.AddObject(SelectedEffect); ItemGrid:= TGridLayout.Create(ReciptRect); ReciptRect.AddObject(ItemGrid); with ItemGrid do begin Parent:=ReciptRect; Align:= TAlignLayout.Bottom; Height:= ReciptRect.Height/2; ItemHeight:=Height; ItemWidth:= Width/Recipt.InputCount; end; if Recipt.FirstItemId>0 then begin ItemRect:=CreateItemRect(ItemGrid); LbHeading:= CreateLabel(ItemRect); LbHeading.Align:= TAlignLayout.Top; LbHeading.Text:= Recipt.InputItem1.Name + ' : ' + Recipt.FirstItemQuantity.ToString; Image:= CreateImg(ItemRect); Image.ImageIndex:= Recipt.InputItem1.ImageIndex; end; if Recipt.SecondItemId>0 then begin ItemRect:=CreateItemRect(ItemGrid); LbHeading:= CreateLabel(ItemRect); LbHeading.Align:= TAlignLayout.Top; LbHeading.Text:= Recipt.InputItem2.Name + ' : ' + Recipt.SecondItemQuantity.ToString; Image:= CreateImg(ItemRect); Image.ImageIndex:= Recipt.InputItem2.ImageIndex; end; if Recipt.ThirdItemId>0 then begin ItemRect:= CreateItemRect(ItemGrid); LbHeading:= CreateLabel(ItemRect); LbHeading.Align:= TAlignLayout.Top; LbHeading.Text:= Recipt.InputItem3.Name + ' : ' + Recipt.ThirdItemQuantity.ToString; Image:= CreateImg(ItemRect); Image.ImageIndex:= Recipt.InputItem3.ImageIndex; end; if Recipt.FourthItemId>0 then begin ItemRect:= CreateItemRect(ItemGrid); LbHeading:= CreateLabel(ItemRect); LbHeading.Align:= TAlignLayout.Top; LbHeading.Text:= Recipt.InputItem4.Name + ' : ' + Recipt.FourthItemQuantity.ToString; Image:= CreateImg(ItemRect); Image.ImageIndex:= Recipt.InputItem4.ImageIndex; end; if Recipt.FifthItemId>0 then begin ItemRect:= CreateItemRect(ItemGrid); LbHeading:= CreateLabel(ItemRect); LbHeading.Align:= TAlignLayout.Top; LbHeading.Text:= Recipt.InputItem5.Name + ' : ' + Recipt.FifthItemQuantity.ToString; Image:= CreateImg(ItemRect); Image.ImageIndex:= Recipt.InputItem5.ImageIndex; end; if Recipt.sixthItemId>0 then begin ItemRect:= CreateItemRect(ItemGrid); LbHeading:= CreateLabel(ItemRect); LbHeading.Align:= TAlignLayout.Top; LbHeading.Text:= Recipt.InputItem6.Name + ' : ' + Recipt.SixthItemQuantity.ToString; Image:= CreateImg(ItemRect); Image.ImageIndex:= Recipt.InputItem6.ImageIndex; end; end; function TReciptPanel.CreateAnimation(aOwner: TComponent; ToColor: TAlphaColor): TColorAnimation; begin Result:=TColorAnimation.Create(aOwner); with Result do begin Parent:=aOwner as TFmxObject; PropertyName:='Fill.Color'; StartFromCurrent:=True; StopValue:=ToColor; Duration:=rhPickAnimationTime; Start; end; end; function TReciptPanel.CreateImg(aOwner: TComponent): TGlyph; begin Result:= TGlyph.Create(aOwner); with Result do begin Parent:= aOwner as TFmxObject; Images:=DataM.ImgListItems; Align:= TAlignLayout.Client; HitTest:= False; end; end; function TReciptPanel.CreateItemRect(aOwner: TComponent): TRectangle; begin Result:= TRectangle.Create(aOwner); with Result do begin Parent:= aOwner as TFmxObject; Opacity:= 0.8; HitTest:= False; end; end; procedure TReciptPanel.Isclicked(sender: TObject); begin if IsSelected = True then OnStateChange(False) else begin OnStateChange(True); CurrentReciptpanels.SetSelectedRecipt(Self.Recipt.Id); end; end; procedure TReciptPanel.ReciptBtnClick; begin end; procedure TReciptPanel.OnStateChange(IsSelected: Boolean); begin if Self.IsSelected <> IsSelected then begin if Self.IsSelected = true then begin CreateAnimation(Self.ReciptRect,StringToAlphaColor(rhNotSelectedColor)); Self.IsSelected:= False; end else begin CreateAnimation(Self.ReciptRect,rhSelectedColor); Self.IsSelected:= True; end; end; end; { TReciptPanellist } constructor TReciptPanellist.Create; begin inherited; end; procedure TReciptPanellist.SetSelectedRecipt(const ReciptId: integer); var ReciptPanel: TReciptPanel; begin for ReciptPanel in Self do begin if ReciptPanel.Recipt.Id <> ReciptId then begin if ReciptPanel.IsSelected then ReciptPanel.OnStateChange(False); end; end; end; end.
unit Menus.View.Produtos; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Layouts, System.Rtti, FMX.Grid.Style, FMX.ScrollBox, FMX.Grid, Data.DB, Data.Bind.EngExt, Fmx.Bind.DBEngExt, Fmx.Bind.Grid, System.Bindings.Outputs, Fmx.Bind.Editors, Data.Bind.Components, Data.Bind.Grid, Data.Bind.DBScope, Menus.Controller.Entity.Interfaces, FMX.Edit, Menus.Controller.Interfaces, Menus.Controller.Facade; type TFrmProduto = class(TForm) Label1: TLabel; ToolBar1: TToolBar; Layout1: TLayout; dsListaDados: TDataSource; StringGrid1: TStringGrid; BindSourceDB1: TBindSourceDB; BindingsList1: TBindingsList; LinkGridToDataSourceBindSourceDB1: TLinkGridToDataSource; Layout2: TLayout; EditCodigo: TEdit; EditDescricao: TEdit; Button1: TButton; Button2: TButton; Button3: TButton; Button4: TButton; procedure FormCreate(Sender: TObject); procedure dsListaDadosDataChange(Sender: TObject; Field: TField); procedure Button2Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button3Click(Sender: TObject); private { Private declarations } FEntity : iControllerEntity; procedure PreencherDados; public { Public declarations } end; var FrmProduto: TFrmProduto; implementation {$R *.fmx} procedure TFrmProduto.Button1Click(Sender: TObject); begin dsListaDados.DataSet.Append; end; procedure TFrmProduto.Button2Click(Sender: TObject); begin dsListaDados.DataSet.Edit; end; procedure TFrmProduto.Button3Click(Sender: TObject); begin dsListaDados.DataSet.Delete; end; procedure TFrmProduto.Button4Click(Sender: TObject); begin PreencherDados; dsListaDados.DataSet.Post; end; procedure TFrmProduto.dsListaDadosDataChange(Sender: TObject; Field: TField); begin EditCodigo.Text := dsListaDados.DataSet.FieldByName('id').AsString; EditDescricao.Text := dsListaDados.DataSet.FieldByName('descricao').AsString; end; procedure TFrmProduto.FormCreate(Sender: TObject); begin FEntity := TControllerFacade.New.Entity.Entity.Produto.Lista(dsListaDados); TControllerFacade.New.Menu.ListBox.Produtos(Layout1).Exibir; //TControllerListaBoxFactory.New.Produtos(Layout1).Exibir; //FEntity.Lista(dsListaDados); end; procedure TFrmProduto.PreencherDados; begin dsListaDados.DataSet.FieldByName('id').Value := EditCodigo.Text; dsListaDados.DataSet.FieldByName('descricao').Value := EditDescricao.Text; end; initialization RegisterFmxClasses([TFrmProduto]); end.
unit SignTable; interface type (* * Знак полинома в точке: -, 0 или + *) TValueSign = (vsMinus, vsZero, vsPlus); (* * Столбец таблицы знаков полиномов * Next - указатель на столбец, стоящий спарва следующим за данным * Column - значения столбца * ВНИМАНИЕ: Ячейки этого массива нумеруются с нуля *) PSignTableColumn = ^TSignTableColumn; TSignTableColumn = record Next : PSignTableColumn; Column : array of byte; end; (* * Таблица знаков полиномов * Height - высота таблицы * FirstColumn - указатель на первый (самый левый) столбец таблицы * Все столюцы таблицы должны иметь выоту Height *) TSignTable = record Height : Integer; FirstColumn : PSignTableColumn; end; procedure InsertColumn(var table : TSignTable; const insertAfter : PSignTableColumn); procedure InitTable( Var Table : TsignTable; TableHeight : integer); procedure NextColumn(var Current : PSignTableColumn); function GetItem(const GColumn : PsignTableColumn; NumberInColumn : integer) : TValueSign; procedure WriteItem(var WColumn : PsignTableColumn; NumberInColumn : integer; Value : TValueSign); procedure EasyWrite(var WColumn : PsignTableColumn; NumberInColumn : integer; Value : integer); function EasyGet(const GColumn : PsignTableColumn; NumberInColumn : integer) : integer; // EasyWrite и EasyGet отличаются от WriteItem и GetItem тем, что всместо констант // типа TValueSign у них в качестве третьего параметра целое число, которе лежит в // диапазоне от -1 до 1 (исключительно для удобства) implementation /////////////////////////////////////////////////////////////////////// function GetSignFromByte(const count : integer; const OurByte : byte) : TValueSign; var TwoBits : Byte; begin TwoBits := OurByte shl ((count - 1) * 2); TwoBits := twobits shr 6; case twobits of 0 : result := vsZero; 1 : result := vsPlus; 3 : result := vsMinus; end; end; procedure PutSignToByte(const count : integer; const Value : TValueSign; var OurByte : byte); var TwoBits : Byte; Mask : Byte; begin case Value of vsZero : TwoBits := 0; vsPlus : TwoBits := 1; vsMinus : TwoBits := 3; end; TwoBits := TwoBits shl ((4 - count) * 2); Mask := 3 shl ((4 - count) * 2); Mask := not Mask; OurByte := OurByte and Mask; OurByte := OurByte + Twobits; end; ///////////////////////////////////////////////////////////////////////// procedure insertColumn(var table : TSignTable; const insertAfter : PSignTableColumn); var i : PSignTableColumn; begin new(i); setlength(i.column, (Table.Height div 4) + 1); i.next := insertAfter.Next; insertAfter.Next := i; end; procedure InitTable( Var Table : TsignTable; TableHeight : integer); begin Table.Height := TableHeight; new(Table.FirstColumn); new(Table.FirstColumn^.Next); setlength(Table.FirstColumn^.Column, (Table.Height div 4) + 1); setlength(Table.FirstColumn^.Next^.Column, (Table.Height div 4) + 1); Table.FirstColumn^.Next^.Next := Nil; end; procedure NextColumn( var Current : PSignTableColumn); var i : PSignTableColumn; begin i := Current^.Next; Current := i; end; function GetItem (const GColumn : PsignTableColumn; NumberInColumn : integer) : TValueSign; begin result := GetSignFromByte((NumberInColumn mod 4) + 1, GColumn^.Column[(NumberInColumn div 4) ]); end; procedure WriteItem(var WColumn : PsignTableColumn; NumberInColumn : integer; Value : TValueSign); begin PutSignToByte((NumberInColumn mod 4) + 1, Value, WColumn^.Column[(NumberInColumn div 4) ]); end; procedure EasyWrite(var WColumn : PsignTableColumn; NumberInColumn : integer; Value : integer); begin if NumberInColumn < 0 then writeln('fatal error'); case Value of -1 : WriteItem(WColumn, NumberInColumn, vsMinus); 0 : WriteItem(WColumn, NumberInColumn, vsZero); 1 : WriteItem(WColumn, NumberInColumn, vsPlus); end;{case} end;{Easywrite} function EasyGet(const GColumn : PsignTableColumn; NumberInColumn : integer) : integer; begin if NumberInColumn < 0 then writeln('fatal error?'); case GetItem(GColumn, NumberInColumn) of vsMinus : result := -1; vsZero : result := 0; vsPlus : result := 1; end;{case} end; end.
unit DefaultValueTests; interface uses DUnitX.TestFramework, DelphiJSON, System.Generics.Collections; type [DJSerializable] TTestClass = class public [DJValue('str')] [DJRequired(false)] [DJDefaultValue('Hello World')] [DJDefaultOnNilAttribute] str: String; [DJValue('b')] [DJRequired(false)] [DJDefaultValue(true)] b: Boolean; [DJValue('i')] [DJRequired(false)] [DJDefaultValue(156)] i: Integer; [DJValue('s')] [DJRequired(false)] [DJDefaultValue(single(0.56))] s: single; end; TCustomListGenerator = class(DJDefaultValueCreatorAttribute < TList < String >> ) public function Generator: TList<String>; override; end; [DJSerializable] TAnother = class public [DJValue('messages')] [DJRequired(false)] [TCustomListGenerator] [DJDefaultOnNilAttribute] messages: TList<String>; end; [TestFixture] TDefaultValueTests = class(TObject) public [Test] procedure Test1; [Test] procedure Test2; [Test] procedure TestGenerator; [Test] procedure TestGenerator2; [Test] procedure TestDefaultOnNil1; [Test] procedure TestDefaultOnNil2; end; implementation function Generator: TObject; begin Result := TList<String>.Create(); (Result as TList<String>).Add('Wow'); end; { TDefaultValueTests } procedure TDefaultValueTests.Test1; const res = '{}'; var tmp: TTestClass; begin tmp := DelphiJSON<TTestClass>.Deserialize(res); Assert.AreEqual('Hello World', tmp.str); Assert.AreEqual(true, tmp.b); Assert.AreEqual(156, tmp.i); Assert.AreEqual(single(0.56), tmp.s); tmp.Free; end; procedure TDefaultValueTests.Test2; const res = '{ "str": "Bye Bye!", "s": 123.123 }'; var tmp: TTestClass; begin tmp := DelphiJSON<TTestClass>.Deserialize(res); Assert.AreEqual('Bye Bye!', tmp.str); Assert.AreEqual(true, tmp.b); Assert.AreEqual(156, tmp.i); Assert.AreEqual(single(123.123), tmp.s); tmp.Free; end; procedure TDefaultValueTests.TestDefaultOnNil1; const res = '{ "str": null, "s": 123.123 }'; var tmp: TTestClass; begin tmp := DelphiJSON<TTestClass>.Deserialize(res); Assert.AreEqual('Hello World', tmp.str); Assert.AreEqual(true, tmp.b); Assert.AreEqual(156, tmp.i); Assert.AreEqual(single(123.123), tmp.s); tmp.Free; end; procedure TDefaultValueTests.TestDefaultOnNil2; const res = '{ "messages": null }'; var tmp: TAnother; begin tmp := DelphiJSON<TAnother>.Deserialize(res); Assert.IsNotNull(tmp.messages); Assert.AreEqual(1, tmp.messages.Count); Assert.AreEqual('Yeah!', tmp.messages[0]); tmp.messages.Free; tmp.Free; end; procedure TDefaultValueTests.TestGenerator; const res = '{}'; var tmp: TAnother; begin tmp := DelphiJSON<TAnother>.Deserialize(res); Assert.IsNotNull(tmp.messages); Assert.AreEqual(1, tmp.messages.Count); Assert.AreEqual('Yeah!', tmp.messages[0]); tmp.messages.Free; tmp.Free; end; procedure TDefaultValueTests.TestGenerator2; const res = '{ "messages": ["abc", "def"] }'; var tmp: TAnother; begin tmp := DelphiJSON<TAnother>.Deserialize(res); Assert.IsNotNull(tmp.messages); Assert.AreEqual(2, tmp.messages.Count); Assert.AreEqual('abc', tmp.messages[0]); Assert.AreEqual('def', tmp.messages[1]); tmp.messages.Free; tmp.Free; end; { TEmptyListGenerator } function TCustomListGenerator.Generator: TList<String>; begin Result := TList<String>.Create; Result.Add('Yeah!'); end; initialization TDUnitX.RegisterTestFixture(TDefaultValueTests); end.
unit MapServer; interface uses IdHTTPServer, IdContext, IdCustomHTTPServer, windows, Classes, Sysutils, System.Generics.Collections; type TUploadStream = class(TMemoryStream) private FAdress: string; FStartTime: TDateTime; FOnDestroy: TNotifyEvent; function getProgress: double; function getSpeed: double; public constructor Create; destructor Destroy; override; property Progress: double read getProgress; property Address: string read FAdress write FAdress; property Speed: double read getSpeed; function Read(var Buffer; Count: integer): integer; override; property OnDestroy: TNotifyEvent read FOnDestroy write FOnDestroy; end; IMapKeeper = interface function GetMap(ServReq: string; var MapName: string): TUploadStream; end; TMapServer = class private FPort: Word; Server: TIdHTTPServer; FIsActive: boolean; FConnections: integer; FUploads: TObjectList<TUploadStream>; FMapKeeper: IMapKeeper; procedure Disconnect(AContext: TIdContext); procedure Connect(AContext: TIdContext); procedure CommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); procedure UploadFinish(Sender: TObject); class procedure getPage404(Stream: TStream); public constructor Create(const MapKeeper: IMapKeeper); destructor Destroy; override; procedure Run; procedure Stop; procedure Restart; property Port: Word read FPort write FPort; property Connections: integer read FConnections; property CurrentUploads: TObjectList<TUploadStream> read FUploads; end; implementation uses IdURI; { TUploadStream } constructor TUploadStream.Create; begin FStartTime := 0; end; destructor TUploadStream.Destroy; begin if Assigned(FOnDestroy) then FOnDestroy(self); inherited; end; function TUploadStream.getProgress: double; begin if (Assigned(self)) and (Size > 0) then result := Position * 100 / Size else result := 100; end; function TUploadStream.getSpeed: double; begin if FStartTime = 0 then result := 0 else result := Position / 1024 / ((now - FStartTime) * 60 * 60 * 24); end; function TUploadStream.Read(var Buffer; Count: integer): integer; begin result := inherited read(Buffer, Count); if FStartTime = 0 then FStartTime := now; end; { TMapServer } constructor TMapServer.Create(const MapKeeper: IMapKeeper); begin FMapKeeper := MapKeeper; FIsActive := false; FConnections := 0; FUploads := TObjectList<TUploadStream>.Create(false); end; destructor TMapServer.Destroy; begin Stop; FUploads.Free; FMapKeeper := nil; inherited; end; procedure TMapServer.CommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); var Stream: TUploadStream; m_stream: TMemoryStream; req, MapName: string; begin try AResponseInfo.Server := 'osu!share by Vladimir, North, Vodka, Bears'; req := ARequestInfo.Document; delete(req, 1, 1); if req = 'ping' then begin AResponseInfo.ContentType := 'text/plain'; AResponseInfo.ContentText := 'pong'; exit; end; req := StringReplace(req, '.osz', '', [rfReplaceAll]); Stream := FMapKeeper.GetMap(req, MapName); if Assigned(Stream) then begin Stream.Address := ARequestInfo.RemoteIP; Stream.OnDestroy := UploadFinish; TThread.Synchronize(TThread.CurrentThread, procedure begin FUploads.Add(Stream); end); MapName := TIdURI.ParamsEncode(MapName); AResponseInfo.ContentType := 'application/octet-stream'; AResponseInfo.CustomHeaders.Values['Content-disposition'] := Format('attachment; filename="%s.osz";', [MapName]); AResponseInfo.ContentText := ''; AResponseInfo.ContentLength := Stream.Size; AResponseInfo.ContentStream := Stream; // тут нельзя разрушить stream.Free; его порушит сам серв end else begin m_stream := TMemoryStream.Create; getPage404(m_stream); AResponseInfo.ContentType := 'text/html'; AResponseInfo.ResponseNo := 404; AResponseInfo.ContentLength := m_stream.Size; AResponseInfo.ContentStream := m_stream; // тут нельзя разрушить m_stream.Free; его порушит сам серв exit; end; except end; end; procedure TMapServer.Connect(AContext: TIdContext); begin InterlockedIncrement(FConnections); end; procedure TMapServer.Disconnect(AContext: TIdContext); begin InterlockedDecrement(FConnections); end; class procedure TMapServer.getPage404(Stream: TStream); var RS: TResourceStream; begin RS := TResourceStream.Create(HInstance, // your app or DLL instance handle '404page', // string containing resource name RT_RCDATA); try Stream.CopyFrom(RS, RS.Size) finally FreeAndNil(RS); end; end; procedure TMapServer.Restart; begin Stop; Run; end; procedure TMapServer.Run; begin if not FIsActive then begin Server := TIdHTTPServer.Create(nil); Server.OnConnect := Connect; Server.OnDisconnect := Disconnect; Server.OnCommandGet := CommandGet; Server.DefaultPort := Port; Server.ListenQueue := 50; Server.Active := true; FIsActive := true; end; end; procedure TMapServer.Stop; begin if FIsActive then begin Server.Active := false; Server.Free; FIsActive := false; FConnections := 0; end; end; procedure TMapServer.UploadFinish(Sender: TObject); begin TThread.Synchronize(TThread.CurrentThread, procedure begin FUploads.Extract(Sender as TUploadStream); end); end; end.
unit Builder.Concretes.Builder.Car; interface uses Builder.Interfaces.IBuilder, Builder.Interfaces.IEngine, Builder.Interfaces.IGPS, Builder.Interfaces.ITripComputer; // The Concrete Builder classes follow the Builder interface and provide // specific implementations of the building steps. Your program may have // several variations of Builders, implemented differently. // A classe concreta do Builder segue as assinaturas na Interface e provê // implementações especificas dos passos de criação. // Seu software pode ter diferentes variações de Builders, implementados de forma diferente. type TCar = class(TInterfacedObject, IBuilder) private FEngine: IEngine; FGPS: IGPS; FSeats: Integer; FTripComputer: ITripComputer; FEntityName: string; public function GetDescription: string; // Concrete Builders are supposed to provide their own methods for // retrieving results. That's because various types of builders may // create entirely different products that don't follow the same // interface. Therefore, such methods cannot be declared in the base // Builder interface (at least in a statically typed programming // language). // // Usually, after returning the end result to the client, a builder // instance is expected to be ready to start producing another product. // That's why it's a usual practice to call the reset method at the end // of the `GetProduct` method body. However, this behavior is not // mandatory, and you can make your builders wait for an explicit reset // call from the client code before disposing of the previous result. //Builders concretos disponibilizam seus métodos para se recuperar um produto como resultado. //Isto porque vários tipos de builders podem criar produtos totalmente diferentes que não seguem //a mesma interface. Portanto, esses métodos não podem ser declarados na mesma Interface base // (a não ser que você não esteja em uma linguagem de programação fortemente tipada). //Geralmente, depois de retornar o resultado para o Client, uma instancia de Builder //deve estar pronta para começar o processo de produção de um novo produto. //Isso é o porque de geralmente chamar o metodo Reset(New) em seguida de um GetResult (GetProduct) //De qualquer forma este comportamento não é obrigatório e você pode fazer limpar o seu Builder da mémoria //instanciando um novo objeto explicitamente function GetResult: IBuilder; // All production steps work with the same product instance. // Todos passos de produção funcionam com a mesma instancia de produto function SetSeats(ANumberOfSeats: Integer): IBuilder; function SetEngine(AEngine: IEngine): IBuilder; function SetTripComputer(ATripComputer: ITripComputer): IBuilder; function SetGPS(AGPS: IGPS): IBuilder; function SetEntityName(Const AValue: string): IBuilder; // A fresh builder instance should contain a blank product object, which // is used in further assembly. // Um nova instancia deve conter um produto limpo, que em seguida // será usado para uma nova montagem de produto class function New: TCar; end; implementation uses Builder.ProductParts.GPS, Builder.ProductParts.TripComputer, System.Classes, System.SysUtils; { TCar } function TCar.GetDescription: string; var oList: TStringList; begin oList := TStringList.Create; try oList.Add('Modelo do carro: ' + FEntityName); oList.Add(''); oList.Add(' Número de Acentos: ' + FSeats.ToString); if Assigned(FEngine) then oList.Add(' Potência Motor: ' + FEngine.GetPotency) else oList.Add(' Potência Motor: Não Informado'); if Assigned(FGPS) then oList.Add(' Modelo GPS: ' + FGPS.GetModel) else oList.Add(' Modelo GPS: Não Informado'); if Assigned(FTripComputer) then oList.Add(' Computador de bordo: ' + FTripComputer.GetModel) else oList.Add(' Computador de bordo: Não Informado'); Result := oList.Text; finally FreeAndNil(oList); end; end; function TCar.GetResult: IBuilder; begin Result := Self; end; class function TCar.New: TCar; begin Result := Self.Create; end; function TCar.SetSeats(ANumberOfSeats: Integer): IBuilder; begin Result := Self; FSeats := ANumberOfSeats; end; function TCar.SetEngine(AEngine: IEngine): IBuilder; begin Result := Self; FEngine := AEngine; end; function TCar.SetEntityName(const AValue: string): IBuilder; begin Result := Self; FEntityName := AValue; end; function TCar.SetGPS(AGPS: IGPS): IBuilder; begin Result := Self; FGPS := AGPS end; function TCar.SetTripComputer(ATripComputer: ITripComputer): IBuilder; begin Result := Self; FTripComputer := ATripComputer; end; end.
unit GpEasing; // Easing functions: http://www.timotheegroleau.com/Flash/experiments/easing_function_generator.htm // Robert Penner, Tweening: http://robertpenner.com/easing/penner_chapter7_tweening.pdf interface uses System.SysUtils; type IEasing = interface ['{97B451B6-FBAB-45DE-9979-7A740CDC3AFA}'] procedure Complete; end; { IEasing } Easing = class class function InOutCubic(start, stop: integer; duration_ms, tick_ms: integer; updater: TProc<integer>): IEasing; static; class function InOutQuintic(start, stop: integer; duration_ms, tick_ms: integer; updater: TProc<integer>): IEasing; static; class function Linear(start, stop: integer; duration_ms, tick_ms: integer; updater: TProc<integer>): IEasing; static; end; { Easing } implementation uses Vcl.ExtCtrls, DSiWin32; type TEasing = class(TInterfacedObject, IEasing) strict private FDuration_ms: integer; FEasingFunc : TFunc<integer, integer>; FStartValue : integer; FStopValue : integer; FStart_ms : int64; FTick_ms : integer; FTimer : TTimer; FUpdater : TProc<integer>; FValueDiff : integer; strict protected function InOutCubicEasing(delta_ms: integer): integer; function InOutQuinticEasing(delta_ms: integer): integer; function LinearEasing(delta_ms: integer): integer; procedure StartTimer; procedure UpdateValue(sender: TObject); public destructor Destroy; override; procedure Complete; procedure InOutCubic; procedure InOutQuintic; procedure Linear; property Duration_ms: integer read FDuration_ms write FDuration_ms; property StartValue: integer read FStartValue write FStartValue; property StopValue: integer read FStopValue write FStopValue; property Tick_ms: integer read FTick_ms write FTick_ms; property Updater: TProc<integer> read FUpdater write FUpdater; end; { TEasing } { Easing } function CreateEasing(start, stop, duration_ms, tick_ms: integer; updater: TProc<integer>): IEasing; var easing: TEasing; begin Result := TEasing.Create; easing := TEasing(Result); easing.StartValue := start; easing.StopValue := stop; easing.Duration_ms := duration_ms; easing.Tick_ms := tick_ms; easing.Updater := updater; end; { CreateEasing } class function Easing.InOutCubic(start, stop: integer; duration_ms, tick_ms: integer; updater: TProc<integer>): IEasing; begin Result := CreateEasing(start, stop, duration_ms, tick_ms, updater); TEasing(Result).InOutCubic; end; { Easing.InOutCubic } class function Easing.InOutQuintic(start, stop: integer; duration_ms, tick_ms: integer; updater: TProc<integer>): IEasing; begin Result := CreateEasing(start, stop, duration_ms, tick_ms, updater); TEasing(Result).InOutQuintic; end; class function Easing.Linear(start, stop, duration_ms, tick_ms: integer; updater: TProc<integer>): IEasing; begin Result := CreateEasing(start, stop, duration_ms, tick_ms, updater); TEasing(Result).Linear; end; { Easing } { TEasing } destructor TEasing.Destroy; begin FreeAndNil(FTimer); inherited; end; { TEasing } procedure TEasing.Complete; begin updater(StopValue); FTimer := nil; end; { TEasing.Complete } procedure TEasing.InOutCubic; begin FEasingFunc := InOutCubicEasing; StartTimer; end; { TEasing.InOutCubic } function TEasing.InOutCubicEasing(delta_ms: integer): integer; var t : real; ts: real; begin t := delta_ms/Duration_ms; ts := t*t; Result := FStartValue + Round(FValueDiff * (-2 * ts * t + 3 * ts)); end; { TEasing.InOutCubicEasing } procedure TEasing.InOutQuintic; begin FEasingFunc := InOutQuinticEasing; StartTimer; end; { TEasing.InOutQuintic } function TEasing.InOutQuinticEasing(delta_ms: integer): integer; var t: real; begin t := delta_ms/Duration_ms; Result := FStartValue + Round(FValueDiff * t * t * t * t); end; procedure TEasing.Linear; begin FEasingFunc := LinearEasing; StartTimer; end; { TEasing.Linear } function TEasing.LinearEasing(delta_ms: integer): integer; begin Result := FStartValue + Round(FValueDiff / Duration_ms * delta_ms); end; { TEasing.LinearEasing } procedure TEasing.StartTimer; begin FValueDiff := FStopValue - FStartValue; FTimer := TTimer.Create(nil); FTimer.Interval := Tick_ms; FTimer.OnTimer := UpdateValue; FStart_ms := DSiTimeGetTime64; end; { TEasing.StartTimer } procedure TEasing.UpdateValue(sender: TObject); var delta_ms: int64; newValue: integer; begin delta_ms := DSiElapsedTime64(FStart_ms); if delta_ms >= Duration_ms then newValue := StopValue else newValue := FEasingFunc(delta_ms); updater(newValue); if newValue = StopValue then FTimer.Enabled := false; end; { TEasing.UpdateValue } end.
unit uFmxPhysicsDemo; interface uses System.Types, System.Generics.Collections, FMX.Types, FMX.Controls, FMX.Graphics, uSimulationFmxCtrls; type TFmxPhysicsDemo = class private FCtrls: TList<TControl>; FTimer: TTimer; FSimCtrls: TSimulationFmxCtrls; FOffsetX: Double; FOffsetY: Double; FScaleX: Double; FScaleY: Double; FScreenWidth, FScreenHeight: Double; procedure SetIsRunning(const Value: boolean); procedure DoOnTimer(Sender: TObject); function GetIsRunning: boolean; procedure CtrlToBox(ctrlPos: TPointF; ctrlWidth, ctrlHeight: Single; var worldPosX, worldPosY, worldHalfWidth, worldHalfHeight: Single); public constructor Create; destructor Destroy; override; procedure AddControl(ctrl: TControl); procedure AddScreenSize(width, height: Double); procedure Start; procedure Stop; property IsRunning: boolean read GetIsRunning write SetIsRunning; end; implementation uses Box2D.Common, Box2D.Dynamics, uFmxControlHelper; { TFmxPhysicsDemo } constructor TFmxPhysicsDemo.Create; begin FScaleX := 10; FScaleY := 10; FOffsetX:= 0; FOffsetY:= 0; FScreenWidth := 640; // default form width FScreenHeight := 480; // default form height FTimer := TTimer.Create(nil); FTimer.Enabled := False; FTimer.Interval := 15; FTimer.OnTimer := DoOnTimer; FSimCtrls := TSimulationFmxCtrls.Create; FCtrls := TList<TControl>.Create; end; destructor TFmxPhysicsDemo.Destroy; begin Stop; FCtrls.Free; FSimCtrls.Free; FTimer.Free; inherited; end; procedure TFmxPhysicsDemo.DoOnTimer(Sender: TObject); var i: integer; ctrl: TControl; body: b2BodyWrapper; bodyPos: b2Vec2; angle: Single; ctrlCentre: TPointF; begin FSimCtrls.DoStep; for i := 0 to FCtrls.Count-1 do begin ctrl := FCtrls.Items[i]; body.FHandle := ctrl.Tag; bodyPos := body.GetPosition^; angle := body.GetAngle; ctrlCentre.X := bodyPos.x * FScaleX + FScreenWidth/2; ctrlCentre.Y := FScreenHeight/2 - bodyPos.y * FScaleY; ctrl.Position.X := ctrlCentre.X - ctrl.Width/2; ctrl.Position.Y := ctrlCentre.Y - ctrl.Height/2; ctrl.SetRotation(-angle * 180 / pi); end; end; function TFmxPhysicsDemo.GetIsRunning: boolean; begin Result := FTimer.Enabled; end; procedure TFmxPhysicsDemo.SetIsRunning(const Value: boolean); begin if Value <> IsRunning then FTimer.Enabled := Value; end; procedure TFmxPhysicsDemo.Start; begin IsRunning := True; end; procedure TFmxPhysicsDemo.Stop; begin IsRunning := False; end; procedure TFmxPhysicsDemo.AddScreenSize(width, height: Double); const ht = 0.5; // half of boudary box thickness, in world scale var hw, hh: Double; begin FScreenWidth := width; FScreenHeight := height; hw := width / FScaleX / 2; hh := height / FScaleY / 2; FSimCtrls.AddBoundaryBox(0, -hh-ht, hw+ht, ht); // bottom FSimCtrls.AddBoundaryBox(0, hh+ht, hw+ht, ht); // top FSimCtrls.AddBoundaryBox(-hw-ht, 0, ht, hh); // left FSimCtrls.AddBoundaryBox(hw+ht, 0, ht, hh); // right end; procedure TFmxPhysicsDemo.AddControl(ctrl: TControl); var x,y,hw,hh: Single; handle: b2BodyHandle; begin FCtrls.Add(ctrl); CtrlToBox(ctrl.Position.Point, ctrl.Width, ctrl.Height, x, y, hw, hh); handle := FSimCtrls.AddDynamicBox(x, y, hw, hh, ctrl); ctrl.Tag := handle; end; procedure TFmxPhysicsDemo.CtrlToBox(ctrlPos: TPointF; ctrlWidth, ctrlHeight: Single; var worldPosX, worldPosY, worldHalfWidth, worldHalfHeight: Single); var ctrlCentre: TPointF; begin worldHalfWidth := ctrlWidth / FScaleX / 2; worldHalfHeight := ctrlHeight / FScaleY / 2; ctrlCentre.X := ctrlPos.X + ctrlWidth / 2; ctrlCentre.Y := ctrlPos.Y + ctrlHeight / 2; worldPosX := (ctrlCentre.X - FScreenWidth/2) / FScaleX; worldPosY := (-ctrlCentre.Y + FScreenHeight/2) / FScaleY; end; end.
unit Classe.ExecutorTh; interface uses System.SysUtils, System.Classes, System.Generics.Collections; type TMetodo = class private FExecutar: TProc; FRetornoOk: TProc; FRetornoErro: TProc; public constructor Create(const pExecutar, pRetornoOk, pRetornoErro: TProc); property Executar: TProc read FExecutar write FExecutar; property RetornoOk: TProc read FRetornoOk write FRetornoOk; property RetornoErro: TProc read FRetornoErro write FRetornoErro; end; TListaMetodos = class(TList<TMetodo>); TThreadExecutor = class(TThread) protected procedure Execute; override; public constructor Create; end; TExecutor = class private class var FListaMetodos: TListaMetodos; FTh: TThreadExecutor; public class destructor Destroy; class function GetListaMetodos: TListaMetodos; class procedure AddMetodo(pMetodo: TMetodo); end; implementation { TMetodo } constructor TMetodo.Create(const pExecutar, pRetornoOk, pRetornoErro: TProc); begin FExecutar := pExecutar; FRetornoOk := pRetornoOk; FRetornoErro := pRetornoErro; end; { TExcutor } class procedure TExecutor.AddMetodo(pMetodo: TMetodo); begin if not Assigned(FTh) then begin FTh := TThreadExecutor.Create; end; GetListaMetodos.Add(pMetodo); end; class destructor TExecutor.Destroy; begin FListaMetodos.Free; end; class function TExecutor.GetListaMetodos: TListaMetodos; begin if not Assigned(FListaMetodos) then begin FListaMetodos := TListaMetodos.Create; end; Result := FListaMetodos; end; { TThreadExecutor } constructor TThreadExecutor.Create; begin FreeOnTerminate := True; inherited Create(False); end; procedure TThreadExecutor.Execute; var lMetodo: TMetodo; begin while not Terminated do begin lMetodo := nil; if TExecutor.GetListaMetodos.Count > 0 then begin lMetodo := TExecutor.GetListaMetodos.First; TExecutor.GetListaMetodos.Remove(lMetodo); end; if Assigned(lMetodo) then begin try if Assigned(lMetodo.FExecutar) then begin lMetodo.FExecutar(); end; if Assigned(lMetodo.FRetornoOk) then begin lMetodo.FRetornoOk(); end; except on E: Exception do begin if Assigned(lMetodo.FRetornoErro) then begin lMetodo.FRetornoErro(); end; end; end; lMetodo.Free; end; Sleep(100); end; end; end.
//Unit created based on http://docs.transifex.com/api/ unit uTransifexAPI; interface uses System.SysUtils, IdSSLOpenSSL, IdHTTP, Data.DBXJSON; type TransifexException = class(Exception); TransifexContent = string; TTransifexProject = class private FSlug: string; FName: string; FDescription: string; FSourceLanguageCode: string; FIsPrivate: Boolean; procedure SetName(const Value: string); procedure SetSlug(const Value: string); function RemoveUnavailableChars(Desc: string): string; public constructor Create; property Slug: string read FSlug write SetSlug; property Name: string read FName write SetName; property Description: string read FDescription write FDescription; property SourceLanguageCode: string read FSourceLanguageCode write FSourceLanguageCode; property IsPrivate: Boolean read FIsPrivate write FIsPrivate; function ConvertToJson: TJSONObject; end; TTransifexAPI = class(TObject) private FUserName: string; FUserPassword: string; FHttpComunication: TIdHTTP; FIOHandler: TIdSSLIOHandlerSocketOpenSSL; function ConfigureLogin: Boolean; procedure CreateHttpComunication; procedure DestroyHttpComunication; public constructor Create; destructor Destroy; function CreateNewProject(Project: TTransifexProject): string; function GetProjects: TransifexContent; function GetProject(Slug: string; out ProjectDetails: string): Boolean; property UserName: string read FUserName write FUserName; property UserPassword: string read FUserPassword write FUserPassword; end; implementation uses System.Classes, REST.Json; const TRANSIFEX_API_ADDR = 'https://www.transifex.com/api/2/'; COMUN_GET_PROJECTS = 'https://www.transifex.com/api/2/projects'; COMUN_POST_CREATE_PROJECTS = 'https://www.transifex.com/api/2/projects/'; COMUN_GET_PROJECT = 'https://www.transifex.com/api/2/project/%s/?details'; { TTransifexAPI } function TTransifexAPI.ConfigureLogin: Boolean; begin Result := False; if FUserName = '' then raise TransifexException.Create('User name is not setted.'); if FUserPassword = '' then raise TransifexException.Create('Password is not setted.'); FHttpComunication.Request.Username := FUserName; FHttpComunication.Request.Password := FUserPassword; FHttpComunication.Request.BasicAuthentication := True; Result := True; end; constructor TTransifexAPI.Create; begin CreateHttpComunication; end; procedure TTransifexAPI.CreateHttpComunication; begin FHttpComunication := TIdHTTP.Create(nil); FIOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil); FHttpComunication.IOHandler := FIOHandler; FHttpComunication.Request.ContentType := 'application/json' end; function TTransifexAPI.CreateNewProject(Project: TTransifexProject): string; var ContentToSend: TStringStream; Json: TJSONObject; Response: TStringStream; begin if not ConfigureLogin then Exit; Json := Project.ConvertToJson; ContentToSend := TStringStream.Create(Json.ToString); Response := TStringStream.Create; try FHttpComunication.Post(COMUN_POST_CREATE_PROJECTS, ContentToSend, Response); Result := Response.DataString; finally ContentToSend.Free; Response.Free; end; end; destructor TTransifexAPI.Destroy; begin DestroyHttpComunication; end; procedure TTransifexAPI.DestroyHttpComunication; begin FIOHandler.Free; FHttpComunication.Free; end; function TTransifexAPI.GetProject(Slug: string; out ProjectDetails: string): Boolean; var Response: TStringStream; begin Result := False; if not ConfigureLogin then Exit; Response := TStringStream.Create; try FHttpComunication.Get(Format(COMUN_GET_PROJECT, [Slug]), Response); ProjectDetails := Response.DataString; finally Response.Free; end; end; function TTransifexAPI.GetProjects: TransifexContent; var Response: TStringStream; begin Result := ''; if not ConfigureLogin then Exit; Response := TStringStream.Create; try FHttpComunication.Get(COMUN_GET_PROJECTS, Response); Result := Response.DataString; finally Response.Free; end; end; { TTransifexProject } function TTransifexProject.ConvertToJson: TJSONObject; var TrueJson: TJSONTrue; FalseJson: TJSONFalse; begin Result := TJSONObject.Create; Result.AddPair('slug', FSlug); Result.AddPair('name', FName); Result.AddPair('source_language_code', FSourceLanguageCode); Result.AddPair('description', FDescription); if FIsPrivate then begin TrueJson := TJSONTrue.Create; Result.AddPair('private', TrueJson); end else begin FalseJson := TJSONFalse.Create; Result.AddPair('private', FalseJson); end; end; constructor TTransifexProject.Create; begin FIsPrivate := True; end; function TTransifexProject.RemoveUnavailableChars(Desc: string): string; begin Desc := Trim(Desc); Desc := StringReplace(Desc, ' ', '', [rfReplaceAll]); end; procedure TTransifexProject.SetName(const Value: string); begin FName := RemoveUnavailableChars(Value); end; procedure TTransifexProject.SetSlug(const Value: string); begin FSlug := RemoveUnavailableChars(Value); end; end.
unit TestQuestionsInterview; interface uses TestFramework, QuestionsInterview, System.SysUtils; type TestTSampleInterview = class(TTestCase) strict private FSampleInterview: TSampleInterview; public procedure SetUp; override; procedure TearDown; override; published procedure TestIsOdd; end; implementation procedure TestTSampleInterview.SetUp; begin FSampleInterview := TSampleInterview.Create; end; procedure TestTSampleInterview.TearDown; begin FSampleInterview.Free; FSampleInterview := nil; end; procedure TestTSampleInterview.TestIsOdd; begin CheckTrue(TSampleInterview.IsOdd(5),'Testando se 5 é negativo'); end; initialization RegisterTest(TestTSampleInterview.Suite); end.
program ControleAcademico; {$MODE OBJFPC} uses SysUtils, DisciplinaModel in 'DisciplinaModel.pas', AlunoModel in 'AlunoModel.pas', AlunoGerenciador in 'AlunoGerenciador.pas', CursoGerenciador in 'CursoGerenciador.pas', CursoModel in 'CursoModel.pas', MatriculaModel in 'MatriculaModel.pas', MatriculaGerenciador in 'MatriculaGerenciador.pas', DisciplinaGerenciador in 'DisciplinaGerenciador.pas'; var opcao:integer; var dg:TDisciplinaGerenciador; alun:TAlunoGerenciador; cur: TCursoGerenciador; mat: TMatriculaGerenciador; begin try dg := TDisciplinaGerenciador.Create; alun := TAlunoGerenciador.Create; cur := TCursoGerenciador.Create; mat := TMatriculaGerenciador.Create; repeat Writeln('Escolha uma opção'); Writeln('1 - Gerenciar Disciplinas'); Writeln('2 - Gerenciar Aluno'); Writeln('3 - Gerenciar Cursos'); Writeln('4 - Gerenciar Matricula'); Writeln('0 - Sair'); Readln(opcao); case opcao of 1: dg.gerenciar; 2: alun.gerenciar; 3: cur.gerenciar; 4: mat.gerenciar; end; until opcao = 0; except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; end.
// ****************************************************************** // // Program Name : AT Library // Platform(s) : Android, iOS, Linux, MacOS, Windows // Framework : Console, FMX, VCL // // Filename : AT.DataType.Convert.pas // Date Created : 22-Nov-2020 // Author : Matthew Vesperman // // Description: // // Contains routines to convert data types. // // Revision History: // // v1.00 : Initial version // // ****************************************************************** // // COPYRIGHT © 2020 - PRESENT Angelic Technology // ALL RIGHTS RESERVED WORLDWIDE // // ****************************************************************** /// <summary> /// Contains routines to convert data types. /// </summary> unit AT.DataType.Convert; interface /// <summary> /// Converts an Currency value to a Extended (Floating-Point) /// value. /// </summary> function CurrToExtended(Value: Currency): Extended; /// <summary> /// Converts an Extended (Floating-Point) value to a Currency /// value. /// </summary> function ExtendedToCurr(Value: Extended): Currency; implementation function CurrToExtended(Value: Currency): Extended; var AValue: Variant; begin AValue := Value; Result := AValue; end; function ExtendedToCurr(Value: Extended): Currency; var AValue: Variant; begin AValue := Value; Result := AValue; end; 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 testcase.cwThreading.MessageParameter; {$ifdef fpc} {$mode delphiunicode} {$endif} {$M+} interface uses cwTest , cwTest.Standard , cwThreading ; type TTestMessageParameter = class(TTestCase) private published procedure ImplicitParameterToNativeuint; procedure ExplicitParameterToNativeuint; procedure ImplicitParameterToPointer; procedure ExplicitParameterToPointer; procedure ImplicitNativeuintToParameter; procedure ExplicitNativeuintToParameter; procedure ImplicitPointerToParameter; procedure ExplicitPointerToParameter; procedure EqualNativeuintAndParameter; procedure EqualParameterAndNativeuint; procedure NotEqualNativeuintAndParameter; procedure NotEqualParameterAndNativeuint; procedure EqualPointerAndParameter; procedure EqualParameterAndPointer; procedure NotEqualPointerAndParameter; procedure NotEqualParameterAndPointer; procedure EqualParameterAndParameter; procedure NotEqualParameterAndParameter; end; implementation const cTestNativeuintValue = 5; cTestPointerValue: pointer = pointer($00FF); { TTestMessageParameter } procedure TTestMessageParameter.ImplicitParameterToNativeuint; var param: TMessageParameter; nInt: nativeuint; begin // Arrange: param.Param := cTestNativeuintValue; // Act: nInt := param; // Assert: TTest.Expect(nativeuint(cTestNativeuintValue),nInt); end; procedure TTestMessageParameter.ExplicitParameterToNativeuint; var param: TMessageParameter; nInt: nativeuint; begin // Arrange: param.Param := cTestNativeuintValue; // Act: nInt := nativeuint(param); // Assert: TTest.Expect(nativeuint(cTestNativeuintValue),nInt); end; procedure TTestMessageParameter.ImplicitParameterToPointer; var param: TMessageParameter; ptr: pointer; begin // Arrange: {$hints off} param.Param := nativeuint( cTestPointerValue ); {$hints on} // Act: ptr := param; // Assert: {$hints off} TTest.Expect(nativeuint(cTestPointerValue),nativeuint(ptr)); {$hints on} end; procedure TTestMessageParameter.ExplicitParameterToPointer; var param: TMessageParameter; ptr: pointer; begin // Arrange: {$hints off} param.Param := nativeuint( cTestPointerValue ); {$hints on} // Act: ptr := pointer( param ); // Assert: {$hints off} TTest.Expect(nativeuint(cTestPointerValue),nativeuint(ptr)); {$hints on} end; procedure TTestMessageParameter.ImplicitNativeuintToParameter; var nInt: nativeuint; param: TMessageParameter; begin // Arrange: nInt := cTestNativeuintValue; // Act: param := nInt; // Assert: TTest.Expect(nativeuint(cTestNativeuintValue),param.Param); end; procedure TTestMessageParameter.ExplicitNativeuintToParameter; var nInt: nativeuint; param: TMessageParameter; begin // Arrange: nInt := cTestNativeuintValue; // Act: param := TMessageParameter( nInt ); // Assert: TTest.Expect(nativeuint(cTestNativeuintValue),param.Param); end; procedure TTestMessageParameter.ImplicitPointerToParameter; var ptr: pointer; param: TMessageParameter; begin // Arrange: ptr := cTestPointerValue; // Act: param := ptr; // Assert: {$hints off} TTest.Expect(nativeuint(cTestPointerValue),param.Param); {$hints on} end; procedure TTestMessageParameter.ExplicitPointerToParameter; var ptr: pointer; param: TMessageParameter; begin // Arrange: ptr := cTestPointerValue; // Act: param := TMessageParameter( ptr ); // Assert: {$hints off} TTest.Expect(nativeuint(cTestPointerValue),param.Param); {$hints on} end; procedure TTestMessageParameter.EqualNativeuintAndParameter; var srcnInt: nativeuint; b: boolean; param: TMessageParameter; begin // Arrange: srcnInt := cTestNativeuintValue; param := srcnInt; // Act: b := srcnInt = param; // Assert: TTest.IsTrue(b); end; procedure TTestMessageParameter.EqualParameterAndNativeuint; var srcnInt: nativeuint; b: boolean; param: TMessageParameter; begin // Arrange: srcnInt := cTestNativeuintValue; param := srcnInt; // Act: b := param = srcnInt; // Assert: TTest.IsTrue(b); end; procedure TTestMessageParameter.NotEqualNativeuintAndParameter; var srcnInt: nativeuint; b: boolean; param: TMessageParameter; begin // Arrange: srcnInt := succ(cTestNativeuintValue); param := cTestNativeuintValue; // Act: b := srcnInt <> param; // Assert: TTest.IsTrue(b); end; procedure TTestMessageParameter.NotEqualParameterAndNativeuint; var srcnInt: nativeuint; b: boolean; param: TMessageParameter; begin // Arrange: srcnInt := succ(cTestNativeuintValue); param := cTestNativeuintValue; // Act: b := param <> srcnInt; // Assert: TTest.IsTrue(b); end; procedure TTestMessageParameter.EqualPointerAndParameter; var ptr: pointer; b: boolean; param: TMessageParameter; begin // Arrange: ptr := cTestPointerValue; param := cTestPointerValue; // Act: b := ptr = param; // Assert: TTest.IsTrue(b); end; procedure TTestMessageParameter.EqualParameterAndPointer; var ptr: pointer; b: boolean; param: TMessageParameter; begin // Arrange: ptr := cTestPointerValue; param := cTestPointerValue; // Act: b := param = ptr; // Assert: TTest.IsTrue(b); end; procedure TTestMessageParameter.NotEqualPointerAndParameter; var ptr: pointer; b: boolean; param: TMessageParameter; begin // Arrange: ptr := cTestPointerValue; inc(ptr); param := cTestPointerValue; // Act: b := ptr <> param; // Assert: TTest.IsTrue(b); end; procedure TTestMessageParameter.NotEqualParameterAndPointer; var ptr: pointer; b: boolean; param: TMessageParameter; begin // Arrange: ptr := cTestPointerValue; inc(ptr); param := cTestPointerValue; // Act: b := param <> ptr; // Assert: TTest.IsTrue(b); end; procedure TTestMessageParameter.EqualParameterAndParameter; var b: boolean; paramA: TMessageParameter; paramB: TMessageParameter; begin // Arrange: paramA := cTestPointerValue; paramB := cTestPointerValue; // Act: b := paramA = ParamB; // Assert: TTest.IsTrue(b); end; procedure TTestMessageParameter.NotEqualParameterAndParameter; var b: boolean; paramA: TMessageParameter; paramB: TMessageParameter; begin // Arrange: paramA := succ(cTestNativeuintValue); paramB := cTestPointerValue; // Act: b := paramA <> ParamB; // Assert: TTest.IsTrue(b); end; initialization TestSuite.RegisterTestCase(TTestMessageParameter); end.
unit Pessoa; interface uses SysUtils, Endereco, Contnrs, generics.Collections; type TPessoa = class private FCodigo :Integer; FRazao :String; FNomeFantasia :String; FPessoa :String; FTipo :String; FCPF_CNPJ :String; FRG_IE :String; FDtCadastro :TDateTime; FFone1 :String; FFone2 :String; FFax :String; FEmail :String; FObservacao :String; FEnderecos :TObjectList<TEndereco>; FBloqueado: String; FMotivoBloq: String; procedure SetCodigo (const value :Integer); procedure SetRazao (const value :String); procedure SetPessoa (const value :String); procedure SetTipo (const value :String); procedure SetCPF_CNPJ (const value :String); procedure SetRG_IE (const value :String); procedure SetDtCadastro (const value :TDateTime); procedure SetFone1 (const value :String); procedure SetFone2 (const value :String); procedure SetFax (const value :String); procedure SetEmail (const value :String); procedure SetObservacao (const value :String); public function GetIsPessoaJuridica :Boolean; function GetIsPessoaFisica :Boolean; function GetEnderecos :TObjectList<TEndereco>; public constructor Create; destructor Destroy; override; public property Codigo :Integer read FCodigo write SetCodigo; property Razao :String read FRazao write SetRazao; property NomeFantasia :String read FNomeFantasia write FNomeFantasia; property Pessoa :String read FPessoa write SetPessoa; property Tipo :String read FTipo write SetTipo; property CPF_CNPJ :String read FCPF_CNPJ write SetCPF_CNPJ; property RG_IE :String read FRG_IE write SetRG_IE; property DtCadastro :TDateTime read FDtCadastro write SetDtCadastro; property Fone1 :String read FFone1 write SetFone1; property Fone2 :String read FFone2 write SetFone2; property Fax :String read FFax write SetFax; property Email :String read FEmail write SetEmail; property Observacao :String read FObservacao write SetObservacao; property Bloqueado :String read FBloqueado write FBloqueado; property MotivoBloq :String read FMotivoBloq write FMotivoBloq; public property Enderecos :TObjectList<TEndereco> read GetEnderecos; property IsPessoaJuridica :Boolean read GetIsPessoaJuridica; property IsPessoaFisica :Boolean read GetIsPessoaFisica; end; implementation uses Repositorio, FabricaRepositorio, Especificacao, EspecificacaoEnderecoComPessoaIgualA; { TPessoa } constructor TPessoa.Create; begin self.FEnderecos := TObjectList<TEndereco>.Create(true); end; destructor TPessoa.Destroy; begin FreeAndNil(self.FEnderecos); inherited; end; function TPessoa.GetEnderecos: TObjectList<TEndereco>; var Repositorio :TRepositorio; Especificacao :TEspecificacao; begin if not Assigned(self.FEnderecos) or ((Assigned(self.FEnderecos))and(FEnderecos.Count = 0)) then begin Repositorio := nil; Especificacao := nil; try Especificacao := TEspecificacaoEnderecoComPessoaIgualA.Create(self); Repositorio := TFabricaRepositorio.GetRepositorio(TEndereco.ClassName); self.FEnderecos := Repositorio.GetListaPorEspecificacao<TEndereco>(Especificacao); finally FreeAndNil(Especificacao); FreeAndNil(Repositorio); end; end; result := self.FEnderecos; end; function TPessoa.GetIsPessoaFisica: Boolean; begin result := (not self.IsPessoaJuridica); end; function TPessoa.GetIsPessoaJuridica: Boolean; begin result := (Trim(self.FPessoa) = 'J'); end; procedure TPessoa.SetCodigo(const value: Integer); begin self.FCodigo := value; end; procedure TPessoa.SetCPF_CNPJ(const value: String); begin self.FCPF_CNPJ := value; end; procedure TPessoa.SetDtCadastro(const value: TDateTime); begin self.FDtCadastro := value; end; procedure TPessoa.SetEmail(const value: String); begin self.FEmail := LowerCase(value); end; procedure TPessoa.SetFax(const value: String); begin self.FFax := value; end; procedure TPessoa.SetFone1(const value: String); begin self.FFone1 := value; end; procedure TPessoa.SetFone2(const value: String); begin self.FFone2 := value; end; procedure TPessoa.SetObservacao(const value: String); begin self.FObservacao := value; end; procedure TPessoa.SetPessoa(const value: String); begin self.FPessoa := value; end; procedure TPessoa.SetRazao(const value: String); begin self.FRazao := value; end; procedure TPessoa.SetRG_IE(const value: String); begin self.FRG_IE := value; end; procedure TPessoa.SetTipo(const value: String); begin self.FTipo := value; end; end.
unit SimpBmp; // %SimpBmp : 包装Windows的Bitmap,功能比TBitmap简单,速度快 (***** Code Written By Huang YanLai *****) interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms; type TSimpleBitmapImage = class(TSharedImage) private FHandle: HBITMAP; // DDB or DIB handle, used for drawing FPalette: HPALETTE; FOwn : boolean; FBitmap : tagBITMAP; protected procedure FreeHandle; override; public destructor Destroy; override; end; // %TSimpleBitmap : 包装Windows的Bitmap,功能比TBitmap简单,速度快 TSimpleBitmap = class(TGraphic) private FImage : TSimpleBitmapImage; FOldBitmap : HBitmap; FOldPalette : HPalette; FMemDC : HDC; function GetHandle: THandle; function GetOwnHandle: boolean; procedure SetHandle(const Value: THandle); procedure SetOwnHandle(const Value: boolean); procedure CreateNew; protected function GetEmpty: Boolean; override; // return the width/height of bitmap function GetHeight: Integer; override; function GetWidth: Integer; override; procedure SetHeight(Value: Integer); override; function GetTransparent: boolean; override; procedure SetTransparent(Value: Boolean); override; procedure SetWidth(Value: Integer); override; function GetPalette: HPALETTE; override; procedure SetPalette(Value: HPALETTE); override; public constructor Create; override; Destructor Destroy;override; procedure Assign(Source: TPersistent); override; procedure Clear; procedure Draw(ACanvas: TCanvas; const Rect: TRect); override; property Handle : THandle read GetHandle Write SetHandle; procedure LoadFromStream(Stream: TStream); override; procedure SaveToStream(Stream: TStream); override; procedure LoadFromClipboardFormat(AFormat: Word; AData: THandle; APalette: HPALETTE); override; procedure SaveToClipboardFormat(var AFormat: Word; var AData: THandle; var APalette: HPALETTE); override; property OwnHandle : boolean read GetOwnHandle Write SetOwnHandle; property MemDC : HDC read FMemDC; // before draw the bitmap, call GetmemDC to return the memDC that contain the bitmap function GetMemDC: HDC; // after draw the bitmap call ReleaseMemDC to release the memDC procedure ReleaseMemDC; published end; implementation procedure InvalidOperation(const Str: string); near; begin raise EInvalidGraphicOperation.Create(Str); end; { TSimpleBitmapImage } destructor TSimpleBitmapImage.Destroy; begin FreeHandle; inherited Destroy; end; procedure TSimpleBitmapImage.FreeHandle; begin if FOwn then begin DeleteObject(FHandle); if FPalette<>SystemPalette16 then DeleteObject(FPalette); FHandle:=0; FPalette:=0; end; end; { TSimpleBitmap } constructor TSimpleBitmap.Create; begin Inherited Create; FImage := TSimpleBitmapImage.Create; FImage.Reference; end; destructor TSimpleBitmap.Destroy; begin FImage.Release; inherited Destroy; end; procedure TSimpleBitmap.Assign(Source: TPersistent); begin if (Source = nil) or (Source is TSimpleBitmap) then begin //EnterCriticalSection(BitmapImageLock); try if Source <> nil then begin TSimpleBitmap(Source).FImage.Reference; FImage.Release; FImage := TSimpleBitmap(Source).FImage; end else begin CreateNew; end; finally //LeaveCriticalSection(BitmapImageLock); end; Changed(Self); end else inherited Assign(Source); end; procedure TSimpleBitmap.Clear; begin CreateNew; end; procedure TSimpleBitmap.Draw(ACanvas: TCanvas; const Rect: TRect); var OldPalette: HPalette; RestorePalette: Boolean; begin with Rect, FImage do begin //ACanvas.RequiredState(csAllValid); //PaletteNeeded; OldPalette := 0; RestorePalette := False; if FPalette <> 0 then begin OldPalette := SelectPalette(ACanvas.Handle, FPalette, True); RealizePalette(ACanvas.Handle); RestorePalette := True; end; try //Canvas.RequiredState(csAllValid); //MemDC := GetMemDC; GetMemDC; //SelectObject(MemDC,FHandle); if FBitmap.bmBitsPixel=1 then SetStretchBltMode(ACanvas.Handle,STRETCH_ORSCANS) else SetStretchBltMode(ACanvas.Handle,STRETCH_DELETESCANS); StretchBlt(ACanvas.Handle, Left, Top, Right - Left, Bottom - Top, MemDC, 0, 0, Width,Height, ACanvas.CopyMode); finally //DeleteDC(MemDC); ReleaseMemDC; if RestorePalette then SelectPalette(ACanvas.Handle, OldPalette, True); end; end; end; function TSimpleBitmap.GetEmpty: Boolean; begin result:=FImage.FHandle=0; end; function TSimpleBitmap.GetHandle: THandle; begin result := FImage.FHandle; end; function TSimpleBitmap.GetPalette: HPALETTE; begin result := FImage.FPalette; end; function TSimpleBitmap.GetHeight: Integer; begin result := FImage.FBitmap.bmHeight; end; function TSimpleBitmap.GetWidth: Integer; begin result := FImage.FBitmap.bmWidth; end; function TSimpleBitmap.GetTransparent: boolean; begin result := false; end; procedure TSimpleBitmap.LoadFromClipboardFormat(AFormat: Word; AData: THandle; APalette: HPALETTE); begin end; procedure TSimpleBitmap.SaveToClipboardFormat(var AFormat: Word; var AData: THandle; var APalette: HPALETTE); begin end; procedure TSimpleBitmap.LoadFromStream(Stream: TStream); var WorkBitmap : TBitmap; begin WorkBitmap := TBitmap.Create; try WorkBitmap.LoadFromStream(Stream); {FImage.FHandle := WorkBitmap.Handle; FImage.FPalette := WorkBitmap.Palette;} Handle := WorkBitmap.Handle; Palette := WorkBitmap.Palette; WorkBitmap.ReleaseHandle; WorkBitmap.ReleasePalette; OwnHandle := true; finally WorkBitmap.free; end; end; procedure TSimpleBitmap.SaveToStream(Stream: TStream); var WorkBitmap : TBitmap; begin WorkBitmap := TBitmap.Create; try WorkBitmap.Handle := FImage.FHandle; WorkBitmap.Palette := FImage.FPalette; WorkBitmap.SaveToStream(Stream); WorkBitmap.ReleaseHandle; WorkBitmap.ReleasePalette; finally WorkBitmap.free; end; end; procedure TSimpleBitmap.SetHandle(const Value: THandle); begin if FImage.FHandle <> Value then begin // set to FImage if FImage.RefCount > 1 then CreateNew; FImage.FHandle := Value; // get bitmap info FillChar(FImage.FBitmap, sizeof(FImage.FBitmap), 0); if Value <> 0 then GetObject(Value, SizeOf(FImage.FBitmap), @FImage.FBitmap); Changed(Self); end; end; procedure TSimpleBitmap.SetPalette(Value: HPALETTE); begin if FImage.FPalette <> Value then begin FImage.FPalette := Value; Changed(Self); end; end; function TSimpleBitmap.GetOwnHandle: boolean; begin result := FImage.FOwn; end; procedure TSimpleBitmap.SetOwnHandle(const Value: boolean); begin FImage.FOwn := value; end; procedure TSimpleBitmap.SetTransparent(Value: Boolean); begin end; procedure TSimpleBitmap.SetWidth(Value: Integer); begin InvalidOperation('SetWidth'); end; procedure TSimpleBitmap.SetHeight(Value: Integer); begin InvalidOperation('SetHeight'); end; procedure TSimpleBitmap.CreateNew; begin if FImage.RefCount=1 then begin FImage.FreeHandle; end else begin // release FImage.Release; // create new FImage := TSimpleBitmapImage.Create; FImage.Reference; end; end; function TSimpleBitmap.GetMemDC: HDC; begin ReleaseMemDC; FMemDC:=CreateCompatibleDC(0); result:=FMemDC; if FImage.FHandle <> 0 then FOldBitmap := SelectObject(FMemDC, FImage.FHandle) else FOldBitmap := 0; if FImage.FPalette <> 0 then begin FOldPalette := SelectPalette(FMemDC, FImage.FPalette, True); RealizePalette(FMemDC); end else FOldPalette := 0; end; procedure TSimpleBitmap.ReleaseMemDC; begin if FMemDC <> 0 then begin if FOldBitmap <> 0 then SelectObject(FMemDC, FOldBitmap); if FOldPalette <> 0 then SelectPalette(FMemDC, FOldPalette, True); DeleteDC(FMemDC); FMemDC:=0; FOldBitmap := 0; FOldPalette := 0; end; end; end.
///* // * android-plugin-api-for-locale https://github.com/twofortyfouram/android-plugin-api-for-locale // * Copyright 2014 two forty four a.m. LLC // * // * 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 twofortyfouram.Locale.API; interface type (** * Contains Intent constants necessary for interacting with the plug-in API for Locale. *) TIntent = class abstract sealed // abstract + sealed => prevents instantiation public const // /** // * <p>{@code Intent} action sent by the host to create or // * edit a plug-in condition. When the host sends this {@code Intent}, it // * will be explicit (i.e. sent directly to the package and class of the plug-in's // * {@code Activity}).</p> // * <p>The {@code Intent} MAY contain // * {@link #EXTRA_BUNDLE} and {@link #EXTRA_STRING_BLURB} that was previously set by the {@code // * Activity} result of ACTION_EDIT_CONDITION.</p> // * <p>There SHOULD be only one {@code Activity} per APK that implements this // * {@code Intent}. If a single APK wishes to export multiple plug-ins, it // * MAY implement multiple Activity instances that implement this // * {@code Intent}, however there must only be a single // * {@link #ACTION_QUERY_CONDITION} receiver. In such a scenario, it is the // * responsibility of the Activity to store enough data in // * {@link #EXTRA_BUNDLE} to allow this receiver to disambiguate which // * "plug-in" is being queried. To avoid user confusion, it is recommended // * that only a single plug-in be implemented per APK.</p> // * // * @see Intent#EXTRA_BUNDLE // * @see Intent#EXTRA_STRING_BREADCRUMB // */ ACTION_EDIT_CONDITION: string = 'com.twofortyfouram.locale.intent.action.EDIT_CONDITION'; //$NON-NLS-1$ // /** // * <p>Ordered {@code Intent} action broadcast by the host to query // * a plug-in condition. When the host broadcasts this {@code Intent}, it will // * be explicit (i.e. directly to the package and class of the plug-in's // * {@code BroadcastReceiver}).</p> // * <p>The {@code Intent} MUST contain a // * {@link #EXTRA_BUNDLE} that was previously set by the {@code Activity} // * result of {@link #ACTION_EDIT_CONDITION}. // * </p> // * <p> // * Since this is an ordered broadcast, the plug-in's receiver MUST set an // * appropriate result code from {@link #RESULT_CONDITION_SATISFIED}, // * {@link #RESULT_CONDITION_UNSATISFIED}, or // * {@link #RESULT_CONDITION_UNKNOWN}.</p> // * <p> // * There MUST be only one {@code BroadcastReceiver} per APK that implements // * an Intent-filter for this action. // * </p> // * // * @see Intent#EXTRA_BUNDLE // * @see Intent#RESULT_CONDITION_SATISFIED // * @see Intent#RESULT_CONDITION_UNSATISFIED // * @see Intent#RESULT_CONDITION_UNKNOWN // */ ACTION_QUERY_CONDITION: string = 'com.twofortyfouram.locale.intent.action.QUERY_CONDITION'; //$NON-NLS-1$ // /** // * <p> // * {@code Intent} action sent by the host to create or // * edit a plug-in setting. When the host sends this {@code Intent}, it // * will be sent explicit (i.e. sent directly to the package and class of the plug-in's // * {@code Activity}).</p> // * <p>The {@code Intent} MAY contain a {@link #EXTRA_BUNDLE} and {@link // * #EXTRA_STRING_BLURB} // * that was previously set by the {@code Activity} result of // * ACTION_EDIT_SETTING.</p> // * <p> // * There SHOULD be only one {@code Activity} per APK that implements this // * {@code Intent}. If a single APK wishes to export multiple plug-ins, it // * MAY implement multiple Activity instances that implement this // * {@code Intent}, however there must only be a single // * {@link #ACTION_FIRE_SETTING} receiver. In such a scenario, it is the // * responsibility of the Activity to store enough data in // * {@link #EXTRA_BUNDLE} to allow this receiver to disambiguate which // * "plug-in" is being fired. To avoid user confusion, it is recommended that // * only a single plug-in be implemented per APK. // * </p> // * // * @see Intent#EXTRA_BUNDLE // * @see Intent#EXTRA_STRING_BREADCRUMB // */ ACTION_EDIT_SETTING: string = 'com.twofortyfouram.locale.intent.action.EDIT_SETTING'; //$NON-NLS-1$ // /** // * <p> // * {@code Intent} action broadcast by the host to fire a // * plug-in setting. When the host broadcasts this {@code Intent}, it will be // * explicit (i.e. sent directly to the package and class of the plug-in's // * {@code BroadcastReceiver}).</p> // * <p>The {@code Intent} MUST contain a // * {@link #EXTRA_BUNDLE} that was previously set by the {@code Activity} // * result of {@link #ACTION_EDIT_SETTING}.</p> // * <p> // * There MUST be only one {@code BroadcastReceiver} per APK that implements // * an Intent-filter for this action. // * // * @see Intent#EXTRA_BUNDLE // */ ACTION_FIRE_SETTING: string = 'com.twofortyfouram.locale.intent.action.FIRE_SETTING'; //$NON-NLS-1$ // /** // * <p>Implicit broadcast {@code Intent} action to notify the host(s) that a plug-in // * condition is requesting a query it via // * {@link #ACTION_QUERY_CONDITION}. This merely serves as a hint to the host // * that a condition wants to be queried. There is no guarantee as to when or // * if the plug-in will be queried after this action is broadcast. If // * the host does not respond to the plug-in condition after a // * ACTION_REQUEST_QUERY Intent is sent, the plug-in SHOULD shut // * itself down and stop requesting requeries. A lack of response from the host // * indicates that the host is not currently interested in this plug-in. When // * the host becomes interested in the plug-in again, the host will send // * {@link #ACTION_QUERY_CONDITION}.</p> // * <p> // * The extra {@link #EXTRA_STRING_ACTIVITY_CLASS_NAME} MUST be included, otherwise the host will // * ignore this {@code Intent}. // * </p> // * <p> // * Plug-in conditions SHOULD NOT use this unless there is some sort of // * asynchronous event that has occurred, such as a broadcast {@code Intent} // * being received by the plug-in. Plug-ins SHOULD NOT periodically request a // * requery as a way of implementing polling behavior. // * </p> // * <p> // * Hosts MAY throttle plug-ins that request queries too frequently. // * </p> // * // * @see Intent#EXTRA_STRING_ACTIVITY_CLASS_NAME // */ ACTION_REQUEST_QUERY: string = 'com.twofortyfouram.locale.intent.action.REQUEST_QUERY'; //$NON-NLS-1$ // /** // * <p> // * Type: {@code String}. // * </p> // * <p> // * Maps to a {@code String} that represents the {@code Activity} bread crumb // * path. // * </p> // */ EXTRA_STRING_BREADCRUMB: string = 'com.twofortyfouram.locale.intent.extra.BREADCRUMB'; //$NON-NLS-1$ // /** // * <p> // * Type: {@code String}. // * </p> // * <p> // * Maps to a {@code String} that represents a blurb. This is returned as an // * {@code Activity} result extra from the Activity started with {@link #ACTION_EDIT_CONDITION} // * or // * {@link #ACTION_EDIT_SETTING}. // * </p> // * <p> // * The blurb is a concise description displayed to the user of what the // * plug-in is configured to do. // * </p> // */ EXTRA_STRING_BLURB: string = 'com.twofortyfouram.locale.intent.extra.BLURB'; //$NON-NLS-1$ // /** // * <p> // * Type: {@code Bundle}. // * <p> // * Maps to a {@code Bundle} that contains all of a plug-in's extras to later be used when // * querying or firing the plug-in. // * </p> // * <p> // * Plug-ins MUST NOT store {@link Parcelable} objects in this {@code Bundle} // * , because {@code Parcelable} is not a long-term storage format.</p> // * <p> // * Plug-ins MUST NOT store any serializable object that is not exposed by // * the Android SDK. Plug-ins SHOULD NOT store any serializable object that is not available // * across all Android API levels that the plug-in supports. Doing could cause previously saved // * plug-ins to fail during backup and restore. // * </p> // * <p> // * When the Bundle is serialized by the host, the maximum size of the serialized Bundle MUST be // * less than 25 kilobytes (base-10). While the serialization mechanism used by the host is // * opaque to the plug-in, in general plug-ins should just make their Bundle reasonably compact. // * In Android, Intent extras are limited to about 500 kilobytes, although the exact // * size is not specified by the Android public API. If an Intent exceeds that size, the extras // * will be silently dropped by Android. In Android 4.4 KitKat, the maximum amount of data that // * can be written to a ContentProvider during a ContentProviderOperation was reduced to // * less than 300 kilobytes. The maximum bundle size here was chosen to allow several large // * plug-ins to be added to a single batch of operations before overflow occurs. // * </p> // * <p>If a plug-in needs to store large amounts of data, the plug-in should consider // * implementing its own internal storage mechanism. The Bundle can then contain a small token // * that the plug-in uses as a lookup key in its own internal storage mechanism.</p> // */ EXTRA_BUNDLE: string = 'com.twofortyfouram.locale.intent.extra.BUNDLE'; //$NON-NLS-1$ // /** // * <p> // * Type: {@code String}. // * </p> // * <p> // * Maps to a {@code String} that is the fully qualified class name of a plug-in's // * {@code Activity}. // * </p> // * // * @see Intent#ACTION_REQUEST_QUERY // */ EXTRA_STRING_ACTIVITY_CLASS_NAME: string = 'com.twofortyfouram.locale.intent.extra.ACTIVITY'; // $NON-NLS-1$ // /** // * // * Ordered broadcast result code indicating that a plug-in condition's state // * is satisfied (true). // * // * @see Intent#ACTION_QUERY_CONDITION // */ RESULT_CONDITION_SATISFIED: Integer = 16; // /** // * Ordered broadcast result code indicating that a plug-in condition's state // * is not satisfied (false). // * // * @see Intent#ACTION_QUERY_CONDITION // */ RESULT_CONDITION_UNSATISFIED: Integer = 17; // /** // * <p> // * Ordered broadcast result code indicating that a plug-in condition's state // * is unknown (neither true nor false). // * </p> // * <p> // * If a condition returns UNKNOWN, then the host will use the last known // * return value on a best-effort basis. Best-effort means that the host may // * not persist known values forever (e.g. last known values could // * hypothetically be cleared after a device reboot or a restart of the // * host's process. If there is no last known return value, then unknown is // * treated as not satisfied (false). // * </p> // * <p> // * The purpose of an UNKNOWN result is to allow a plug-in condition more // * than 10 seconds to process a query. A {@code BroadcastReceiver} MUST // * return within 10 seconds, otherwise it will be killed by Android. A // * plug-in that needs more than 10 seconds might initially return // * RESULT_CONDITION_UNKNOWN, subsequently request a requery, and // * then return either {@link #RESULT_CONDITION_SATISFIED} or // * {@link #RESULT_CONDITION_UNSATISFIED}. // * </p> // * // * @see Intent#ACTION_QUERY_CONDITION // */ RESULT_CONDITION_UNKNOWN: Integer = 18; end; implementation 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} /// <summary> /// The standard implementation of cwTest. /// </summary> unit cwTest.Standard; {$ifdef fpc}{$mode delphiunicode}{$endif} interface uses cwTest ; /// <summary> /// Returns the singleton instance of ITestSuite which may be used to /// register and execute test cases. /// </summary> function TestSuite(): ITestSuite; type /// <summary> /// Provides utility methods for checking the results of operations /// performed during testing. For example, in order to fail a test you may /// call TTest.Fail( ' &lt;reason string&gt; '); from within the test /// procedure. /// </summary> TTest = record /// <summary> /// Causes the test to fail with the provided reason string. /// </summary> class procedure Fail( const ReasonString: string ); static; /// <summary> /// If the boolean value passed in is not TRUE, the test will /// fail. If a reason string is provided in the optional parameter it /// will be given as the reason for failure, otherwise a generic /// 'Expected True' message is used. /// </summary> class procedure IsTrue( const Value: boolean; const ReasonString: string = '' ); static; /// <summary> /// If the boolean value passed in is not FALSE, the test will /// fail. If a reason string is provided in the optional parameter it /// will be given as the reason for failure, otherwise a generic /// 'Expected False' message is used. /// </summary> class procedure IsFalse( const Value: boolean; const ReasonString: string = '' ); static; /// <summary> /// Compares the expected value to the got value and fails the test if the /// two values do not match. There are many overloads of this method for /// comparison of different types. Each overload has the same two parameters /// except for those which compare floating-points, which add a third parameter /// to indicate the level of precision to be used in the comparison. /// </summary> class procedure Expect( const ExpectedValue: string; const GotValue: string ); overload; static; /// <exclude/> class procedure Expect( const ExpectedValue: char; const GotValue: char ); overload; static; /// <exclude/> class procedure Expect( const ExpectedValue: boolean; const GotValue: boolean ); overload; static; /// <exclude/> class procedure Expect( const ExpectedValue: uint8; const GotValue: uint8 ); overload; static; /// <exclude/> class procedure Expect( const ExpectedValue: uint16; const GotValue: uint16 ); overload; static; /// <exclude/> class procedure Expect( const ExpectedValue: uint32; const GotValue: uint32 ); overload; static; /// <exclude/> class procedure Expect( const ExpectedValue: uint64; const GotValue: uint64 ); overload; static; /// <exclude/> class procedure Expect( const ExpectedValue: int8; const GotValue: int8 ); overload; static; /// <exclude/> class procedure Expect( const ExpectedValue: int16; const GotValue: int16 ); overload; static; /// <exclude/> class procedure Expect( const ExpectedValue: int32; const GotValue: int32 ); overload; static; /// <exclude/> class procedure Expect( const ExpectedValue: int64; const GotValue: int64 ); overload; static; /// <exclude/> class procedure Expect( const ExpectedValue: single; const GotValue: single; const precision: single = 0.0001 ); overload; static; /// <exclude/> class procedure Expect( const ExpectedValue: double; const GotValue: double; const precision: double = 0.0001 ); overload; static; /// <exclude/> class procedure Compare( const SourceData: pointer; const TargetData: pointer; const ByteCount: nativeuint; const FailMessage: string = '' ); static; end; /// <summary> /// A factory record for creating instances of ITestReport using the /// standard console implementation. <br />(Test results are printed to the /// console) /// </summary> TConsoleReport = record /// <summary> /// Factory method for creating instances of ITestReport, to appear as a /// constructor and may be used in place of a constructor for the console /// implementation. /// </summary> class function Create: ITestReport; static; end; implementation uses sysutils //[RTL] for Format() {$ifdef fpc} , cwTest.TestSuite.Fpc {$else} , cwTest.TestSuite.Delphi {$endif} , cwTest.TestReport.Console ; const cExpected = 'Expected %s but got %s'; var SingletonTestSuite: ITestSuite = nil; function TestSuite(): ITestSuite; begin if not assigned(SingletonTestSuite) then begin SingletonTestSuite := TTestSuite.Create; end; Result := SingletonTestSuite; end; { TConsoleReport } class function TConsoleReport.Create: ITestReport; begin Result := TStandardConsoleReport.Create; end; { TTest } class procedure TTest.Fail(const ReasonString: string); begin raise {$ifdef fpc} EFailedTest.Create(AnsiString(ReasonString)); {$else} EFailedTest.Create(ReasonString); {$endif} end; class procedure TTest.IsTrue(const Value: boolean; const ReasonString: string); begin if Value then begin exit; end; if ReasonString='' then begin Fail('Expected True.'); end else begin Fail(ReasonString); end; end; class procedure TTest.IsFalse(const Value: boolean; const ReasonString: string); begin if not Value then begin exit; end; if ReasonString='' then begin Fail('Expected False.'); end else begin Fail(ReasonString); end; end; class procedure TTest.Expect(const ExpectedValue: string; const GotValue: string); begin if ExpectedValue=GotValue then begin exit; end; Fail( string(Format(cExpected,[ExpectedValue,GotValue])) ); end; class procedure TTest.Expect(const ExpectedValue: char; const GotValue: char); begin if ExpectedValue=GotValue then begin exit; end; Fail( string(Format(cExpected,[ExpectedValue,GotValue])) ); end; class procedure TTest.Expect(const ExpectedValue: boolean; const GotValue: boolean); var strExpected: string; strGot: string; begin if ExpectedValue=GotValue then begin exit; end; if ExpectedValue then begin strExpected := 'True'; end else begin strExpected := 'False'; end; if GotValue then begin strGot := 'True'; end else begin strGot := 'False'; end; Fail( string(Format(cExpected,[strExpected,strGot])) ); end; class procedure TTest.Expect(const ExpectedValue: uint8; const GotValue: uint8); begin if ExpectedValue=GotValue then begin exit; end; Fail( string(Format(cExpected,[ExpectedValue.ToString,GotValue.ToString])) ); end; class procedure TTest.Expect(const ExpectedValue: uint16; const GotValue: uint16); begin if ExpectedValue=GotValue then begin exit; end; Fail( string(Format(cExpected,[ExpectedValue.ToString,GotValue.ToString])) ); end; class procedure TTest.Expect(const ExpectedValue: uint32; const GotValue: uint32); begin if ExpectedValue=GotValue then begin exit; end; Fail( string(Format(cExpected,[ExpectedValue.ToString,GotValue.ToString])) ); end; class procedure TTest.Expect(const ExpectedValue: uint64; const GotValue: uint64); begin if ExpectedValue=GotValue then begin exit; end; Fail( string(Format(cExpected,[ExpectedValue.ToString,GotValue.ToString])) ); end; class procedure TTest.Expect(const ExpectedValue: int8; const GotValue: int8); begin if ExpectedValue=GotValue then begin exit; end; Fail( string(Format(cExpected,[ExpectedValue.ToString,GotValue.ToString])) ); end; class procedure TTest.Expect(const ExpectedValue: int16; const GotValue: int16); begin if ExpectedValue=GotValue then begin exit; end; Fail( string(Format(cExpected,[ExpectedValue.ToString,GotValue.ToString])) ); end; class procedure TTest.Expect(const ExpectedValue: int32; const GotValue: int32); begin if ExpectedValue=GotValue then begin exit; end; Fail( string(Format(cExpected,[ExpectedValue.ToString,GotValue.ToString])) ); end; class procedure TTest.Expect(const ExpectedValue: int64; const GotValue: int64); begin if ExpectedValue=GotValue then begin exit; end; Fail( string(Format(cExpected,[ExpectedValue.ToString,GotValue.ToString])) ); end; class procedure TTest.Expect(const ExpectedValue: single; const GotValue: single; const precision: single); begin if (GotValue>=(ExpectedValue-Precision)) and (GotValue<=(ExpectedValue+Precision)) then begin exit; end; Fail( string(Format(cExpected,[ExpectedValue.ToString,GotValue.ToString])) ); end; class procedure TTest.Expect(const ExpectedValue: double; const GotValue: double; const precision: double); begin if (GotValue>=(ExpectedValue-Precision)) and (GotValue<=(ExpectedValue+Precision)) then begin exit; end; Fail( string(Format(cExpected,[ExpectedValue.ToString,GotValue.ToString])) ); end; class procedure TTest.Compare(const SourceData: pointer; const TargetData: pointer; const ByteCount: nativeuint; const FailMessage: string); var Counter: nativeuint; ptrSource: ^uint8; ptrTarget: ^uint8; begin Counter := ByteCount; ptrSource := SourceData; ptrTarget := TargetData; while Counter>0 do begin if ptrSource^<>ptrTarget^ then begin Fail(FailMessage); exit; end; inc(ptrSource); inc(ptrTarget); dec(Counter); end; end; initialization SingletonTestSuite := nil; finalization SingletonTestSuite := nil; end.
(* Copyright (c) 2011-2014, 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.Async; interface uses Classes, DSharp.Core.Threading, SysUtils; type Async = record private fTask: ITask; public class operator Implicit(const value: TProc): Async; procedure Await; procedure Cancel; end; Async<T> = record private fTask: ITask<T>; public class operator Implicit(const value: TFunc<T>): Async<T>; class operator Implicit(const value: Async<T>): T; function Await: T; procedure Cancel; end; TAsync = class(TTask) public procedure Wait; override; end; TAsync<T> = class(TTask<T>) public procedure Wait; override; end; function AsyncCanceled: Boolean; procedure Delay(milliseconds: Integer); procedure Synchronize(const proc: TProc); procedure WaitFor(const thread: TThread); implementation uses Forms, Windows; {$BOOLEVAL OFF} function AsyncCanceled: Boolean; begin Result := (TThread.CurrentThread.ThreadID <> MainThreadID) and TThread.CheckTerminated; end; procedure Delay(milliseconds: Integer); var ticks: Cardinal; event: THandle; begin event := CreateEvent(nil, False, False, nil); try ticks := GetTickCount + Cardinal(milliseconds); while (milliseconds > 0) and (MsgWaitForMultipleObjects(1, event, False, milliseconds, QS_ALLINPUT) <> WAIT_TIMEOUT) do begin Application.ProcessMessages; milliseconds := ticks - GetTickCount; end; finally CloseHandle(event); end; end; procedure Synchronize(const proc: TProc); begin if TThread.CurrentThread.ThreadID <> MainThreadID then TThread.Synchronize(TThread.CurrentThread, TThreadProcedure(proc)) else proc; end; procedure WaitFor(const thread: TThread); var handles: array[0..1] of THandle; begin handles[0] := thread.Handle; if GetCurrentThreadId = MainThreadID then begin handles[1] := SyncEvent; repeat case MsgWaitForMultipleObjects(2, handles, False, INFINITE, QS_ALLINPUT) of WAIT_OBJECT_0 + 1: CheckSynchronize; WAIT_OBJECT_0 + 2: Application.ProcessMessages; end; until thread.Finished; end else WaitForSingleObject(handles[0], INFINITE); end; { Async } procedure Async.Await; begin if Assigned(fTask) then fTask.Wait; end; procedure Async.Cancel; begin if Assigned(fTask) then fTask.Cancel; end; class operator Async.Implicit(const value: TProc): Async; begin Result.fTask := TAsync.Create(value); Result.fTask.Start; end; { Async<T> } function Async<T>.Await: T; begin if Assigned(fTask) then Result := fTask.Result else Result := Default(T); end; procedure Async<T>.Cancel; begin if Assigned(fTask) then fTask.Cancel; end; class operator Async<T>.Implicit(const value: TFunc<T>): Async<T>; begin Result.fTask := TAsync<T>.Create(value); Result.fTask.Start; end; class operator Async<T>.Implicit(const value: Async<T>): T; begin Result := value.Await; end; { TAsync } procedure TAsync.Wait; begin WaitFor(FWorker); FWorker.RaiseException; end; { TAsync<T> } procedure TAsync<T>.Wait; begin WaitFor(FWorker); FWorker.RaiseException; end; end.
unit md52; {------------------------------------------------------------------------------} { Esta classe separa a criacao do hash. Como muitos estavam tendo problema, resolvi ver o fonte do tissnet para ver como a ANS calculava. Estas funcoes fazem o parse no arquivo gerado e pega somente os valores das tags. É assim que o tissnet busca a string para geracao do hash. A única funcao a ser usada aqui, é a GeraHash que recebe como parâmetro a msg gerada e retorna o código hash dela. Dai e so atribuir a tag da seguinte forma: Ex: Msg.Epilogo.Hash := TMD5.GeraHash(Msg.OwnerDocument); Tambem tem funcao para verificacao do hash. Vai servir para quando a operadora ou prestador receber uma mensagem. Lembrem-se que nenhuma das pontas envia a mensagem necessariamente pelo tissnet, o qual faz a validacao. Para chamar a funcao, faca assim: Ex: if TMD5.isHashOK(Msg.OwnerDocument) then } {------------------------------------------------------------------------------} interface uses Windows, SysUtils, XMLDoc, XMLIntf; type TMD5 = class(TObject) private function MD5Hash(Buffer: string): string; function obterCabecalho(Root: IXMLNode): IXMLNode; function obterCorpo(Root: IXMLNode): IXMLNode; function obterSubNode(pNode: IXMLNode; NodeName: string): IXMLNode; function obterAtributosConcatenados(Node: IXMLNode): string; function obterEpilogo(XMLDoc: IXMLDocument): String; public class function GeraHash(XMLDoc: IXMLDocument): string; class function isHashOK(XMLDoc: IXMLDocument): boolean; end; implementation uses Md5tiss, U_Ciphertiss; { TMD5 } class function TMD5.GeraHash(XMLDoc: IXMLDocument): string; var S: string; Classe: TMD5; begin try Classe := TMD5.Create; S := Classe.obterAtributosConcatenados(Classe.obterCabecalho(XMLDoc.DocumentElement)) + Classe.obterAtributosConcatenados(Classe.obterCorpo(XMLDoc.DocumentElement)); Result := Classe.MD5Hash(S); finally Classe.Free; end; end; class function TMD5.isHashOK(XMLDoc: IXMLDocument): boolean; Var HashOK, HashMsg: String; Valor: Boolean; Md5: TMD5; begin try HashOk := TMD5.GeraHash(XmlDoc); Md5:= TMd5.Create; HashMsg := Md5.obterEpilogo(XMLDoc); Valor := HashOK = HashMsg; finally Md5.Free; Result := Valor; end; end; // Hash usando algoritmo MD5 com o componente DcpCrypt - http://www.cityinthesky.co.uk/ function TMD5.MD5Hash(Buffer: string): string; var MD5_Hash: TDCP_MD5tiss; Hash: array[0..15] of byte; //31 Temp: string; f: Byte; begin for f := 0 to 15 do Hash[f] := 0; Buffer := Trim(Buffer); MD5_Hash := TDCP_MD5tiss.Create(nil); MD5_Hash.Init; MD5_Hash.UpdateStr(Buffer); MD5_Hash.Final(Hash); for f := 0 to 15 do Temp := Temp + IntToHex(Hash[f], 2); Result := Copy(Temp, 1, 32); MD5_Hash.Burn; MD5_Hash.Free; end; function TMD5.obterAtributosConcatenados(Node: IXMLNode): string; var S: string; I: Integer; ChildNode: IXMLNode; NodeList: IXMLNodeList; begin if Node.HasChildNodes then begin NodeList := Node.ChildNodes; for I := 0 to NodeList.Count - 1 do begin ChildNode := NodeList.Nodes[I]; S := S + obterAtributosConcatenados(ChildNode); end; end else S := Trim(Node.Text); Result := S; end; function TMD5.obterCabecalho(Root: IXMLNode): IXMLNode; begin Result := obterSubNode(Root, 'cabecalho'); end; function TMD5.obterCorpo(Root: IXMLNode): IXMLNode; var Node: IXMLNode; begin Node := obterSubNode(Root, 'operadoraParaPrestador'); if (Node = nil) then Node := obterSubNode(Root, 'prestadorParaOperadora'); Result := Node; end; function TMD5.obterEpilogo(XMLDoc: IXMLDocument): String; Var Node: IXMLNode; begin Node := obterSubNode(XmlDoc.DocumentElement, 'epilogo'); Result := Node.ChildNodes['hash'].Text; end; function TMD5.obterSubNode(pNode: IXMLNode; NodeName: string): IXMLNode; var Node: IXMLNode; I: Integer; begin try for I := 0 to pNode.ChildNodes.Count - 1 do begin Node := pNode.ChildNodes.Nodes[I]; try if (Node.LocalName = NodeName) then break; except end; end; if (Node.LocalName = NodeName) then Result := Node else Result := nil; except Result := nil; end; end; end.
unit Container; // %Container : 载体 (***** Code Written By Huang YanLai *****) interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls,CMUtils, ComWriUtils; type // %TContainer : 载体 TContainer = class(TCustomPanel) private { Private declarations } FOnCreate: TNotifyEvent; FOnDestroy: TNotifyEvent; FDesigned: boolean; procedure LoadWhenCreate; procedure SetDesigned(const Value: boolean); protected { Protected declarations } procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override; // %IsAloneDesign : 返回是否是TContainer的子类,这个子类安装到Delphi的设计环境中 function IsAloneDesign: boolean; procedure DelphiDesignedComponent(ADesigned : boolean); public { Public declarations } property Designed : boolean read FDesigned write SetDesigned; constructor Create(AOwner: TComponent); override; constructor CreateWithParent(AOwner : TComponent; AParent : TWinControl); virtual; destructor Destroy; override; property Align; published { Published declarations } property OnCreate: TNotifyEvent read FOnCreate write FOnCreate ; property OnDestroy: TNotifyEvent read FOnDestroy write FOnDestroy ; // not publish "Align" property Alignment; property BevelInner; property BevelOuter; property BevelWidth; property BorderWidth; property BorderStyle; property DragCursor; property DragMode; property Enabled; property FullRepaint; property Caption; property Color; property Ctl3D; property Font; property Locked; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property Visible; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnResize; property OnStartDrag; end; TContainerClass = class of TContainer; { how to use TContainerProxy. (I) create in design time (1) in design time a) new a container and design it b) place a ContainerProxy on a form, set its ContainerClassName. (2) in runtime , it will automatically load the container. (II) create in run time In run time, create a ContainerProxy. a) set its ContainerClassName and call loadbyClassname or b) loadbyClassname(MyContainerClassName) or c) create my container and assign it to container property. } // %TContainerProxy : 在设计时代表TContainer的位置大小 TContainerProxy = class(TPanel) private FContainer : TContainer; FContainerClassName : string; procedure SetContainer(value : TContainer); protected procedure Loaded; override; public //OwnContainer : boolean; constructor Create(AOwner: TComponent); override; destructor Destroy; override; // if you set Container, OwnContainer=false { if s='' use ContainerClassName. if successful ContainerClassName:=s and OwnContainer=true } procedure LoadbyClassname(const s:string); procedure ReleaseContainer; published property ContainerClassName : string read FContainerClassName write FContainerClassName; property Container : TContainer read FContainer write SetContainer; end; EInvalidClassName = class(Exception); implementation uses Consts,MsgFilters {$ifdef Ver140} ,RTLConsts {$endif} ; constructor TContainer.Create(AOwner: TComponent); begin Inherited Create(AOwner); LoadWhenCreate; FDesigned := false; if IsAloneDesign then begin ControlStyle := ControlStyle - [csAcceptsControls]; DelphiDesignedComponent(false); Designed := true; end; end; constructor TContainer.CreateWithParent(AOwner: TComponent; AParent: TWinControl); begin inherited Create(AOwner); Parent := AParent; LoadWhenCreate; end; procedure TContainer.LoadWhenCreate; begin ControlStyle := ControlStyle - [csSetCaption]; // when design time // if TContainer as an component not as an form, // owner is not TApplication if (ClassType <> TContainer) and (not (csDesigning in ComponentState) //or (Owner=nil) or not (Owner is TApplication) or IsAloneDesign ) then begin if not InitInheritedComponent(Self, TContainer) then raise EResNotFound.CreateFmt(SResNotFound, [ClassName]); try if Assigned(FOnCreate) then FOnCreate(Self); except Application.HandleException(Self); end; end; end; destructor TContainer.Destroy; begin if Assigned(FOnDestroy) then try FOnDestroy(Self); except Application.HandleException(Self); end; inherited Destroy; end; function TContainer.IsAloneDesign: boolean; begin {result := (csDesigning in ComponentState) and ((Owner=nil) or not (Owner is TApplication));} result := (csDesigning in ComponentState) and (Owner is TCustomForm); {if result then ShowMessage('Alone') else ShowMessage('Not Alone');} end; procedure TContainer.GetChildren(Proc: TGetChildProc; Root: TComponent); begin inherited GetChildren(Proc, Root); CommonGetChildren(Self,Proc,Root); end; procedure TContainer.SetDesigned(const Value: boolean); begin if FDesigned<>Value then begin FDesigned := Value; InstallMouseTrans(self,Value); end; end; type TComponentAccess = class(TComponent); procedure TContainer.DelphiDesignedComponent(ADesigned: boolean); var I: Integer; begin for I := 0 to ComponentCount - 1 do TComponentAccess(Components[I]).SetDesigning(ADesigned); end; // TContainerProxy constructor TContainerProxy.Create(AOwner: TComponent); begin inherited Create(AOwner); FContainer := nil; FContainerClassName := ''; //OwnContainer := false; RegisterRefProp(self,'Container'); end; destructor TContainerProxy.Destroy; begin //ReleaseContainer; inherited destroy; end; procedure TContainerProxy.SetContainer(value : TContainer); begin if value<>FContainer then begin ReleaseContainer; FContainer := value; if (FContainer<>nil) then if not (csDesigning in ComponentState) then begin FContainer.align := alClient; { insertControl(FContainer); This call may bring a error when program terminate because : if FContainer is created by self, FContainer.parent is self, and FContainer has already been inserted, therefore, this call will insert it again! } FContainer.parent := self; end else FContainerClassName:= value.className; //OwnContainer := false; referTo(value); end; end; procedure TContainerProxy.LoadbyClassname(const s:string); var AClass : TContainerClass; LoadClassName : string; begin if (s='') then LoadClassName:=ContainerClassName else LoadClassName:=s; if LoadClassName='' then exit; AClass := TContainerClass(GetClass(LoadClassName)); if AClass=nil then raise EInvalidClassName.create('Invalid Class Name!(Maybe unregister)'); //Container := AClass.create(self); Container := AClass.CreateWithParent(self,self); //OwnContainer := true; ContainerClassName := LoadClassName; end; procedure TContainerProxy.Loaded; begin inherited loaded; if not (csdesigning in ComponentState) and (FContainer=nil) then LoadbyClassname(''); end; procedure TContainerProxy.ReleaseContainer; begin //if OwnContainer and (FContainer<>nil) if (FContainer<>nil) and (FContainer.owner=self) then begin //OwnContainer := false; if not (csDestroying in FContainer.componentState) then FContainer.free; FContainer := nil; end; end; end.
{ Una cadena de tiendas de indumentaria posee un archivo maestro no ordenado con la información correspondiente a las prendas que se encuentran a la venta. De cada prenda se registra: cod_prenda, descripción, colores, tipo_prenda, stock y precio_unitario. Ante un eventual cambio de temporada, se deben actualizar las prendas a la venta. Para ello reciben un archivo conteniendo: cod_prenda de las prendas que quedarán obsoletas. Deberá implementar un procedimiento que reciba ambos archivos y realice la baja lógica de las prendas, para ello deberá modificar el stock de la prenda correspondiente a valor negativo. } program untitled; const corte = 0; type prenda = record cod_prenda: integer; //desc: string[50]; //colores: string[50]; //tipo_prenda: string[50]; stock: integer; precio_unitario: real; end; cod = integer; maestro = file of prenda; archivo = file of cod; //codigos de achivos //---------------------------------------------------------------------- procedure leerPrenda(var p: prenda); begin with p do begin write('* Código de prenda: '); readln(cod_prenda); if(cod_prenda <> corte) then begin write('* Stock: '); readln(stock); write('* Precio unitario: '); readln(precio_unitario); writeln(); end; end; End; //---------------------------------------------------------------------- procedure generarMaestro(); var a: maestro; p: prenda; begin writeln('============ GENERANDO MAESTRO =============='); assign(a, 'archivoDePrendas'); rewrite(a); leerPrenda(p); while(p.cod_prenda <> corte) do begin write(a,p); leerPrenda(p); end; close(a); End; procedure generarArchivo(); var a: archivo; n: cod; begin writeln('============ GENERANDO DETALLE =============='); assign(a, 'archivoDeCodigos'); rewrite(a); write('* Código de la prenda: '); readln(n); writeln(); while (n <> corte) do begin write(a,n); write('* Código de la prenda; '); readln(n); writeln(); end; close(a); End; //---------------------------------------------------------------------- BEGIN generarMaestro(); generarArchivo(); END.
{******************************************************************************* 作者: dmzn@163.com 2012-02-03 描述: 业务常量定义 备注: *.所有In/Out数据,最好带有TBWDataBase基数据,且位于第一个元素. *******************************************************************************} unit UBusinessConst; interface uses Classes, SysUtils, UBusinessPacker, ULibFun, USysDB; const {*channel type*} cBus_Channel_Connection = $0002; cBus_Channel_Business = $0005; {*query field define*} cQF_Bill = $0001; {*business command*} cBC_GetSerialNO = $0001; //获取串行编号 cBC_ServerNow = $0002; //服务器当前时间 cBC_IsSystemExpired = $0003; //系统是否已过期 cBC_IsTruckValid = $0004; //车牌是否有效 cBC_UserLogin = $0005; //用户登录 cBC_UserLogOut = $0006; //用户注销 cBC_GetCardUsed = $0007; //获取卡片类型 cBC_GetCustomerMoney = $0010; //获取客户可用金 cBC_GetZhiKaMoney = $0011; //获取纸卡可用金 cBC_SaveTruckInfo = $0013; //保存车辆信息 cBC_GetStockBatcode = $0014; //获取物料批次 cBC_GetTruckPoundData = $0015; //获取车辆称重数据 cBC_SaveTruckPoundData = $0016; //保存车辆称重数据 cBC_SaveStockBatcode = $0017; //保存物料批次 cBC_GetOrderFHValue = $0018; //获取订单发货量 cBC_GetOrderGYValue = $0019; //获取订单供应量 cBC_SyncME25 = $0100; //同步发货单到榜单 cBC_SyncME03 = $0101; //同步供应到磅单 cBC_GetSQLQueryOrder = $0102; //查询订单语句 cBC_GetSQLQueryCustomer = $0103; //查询客户语句 cBC_GetSQLQueryDispatch = $0104; //查询调拨订单 cBC_SyncDuanDao = $0105; //同步短倒 cBC_SaveBills = $0020; //保存交货单列表 cBC_DeleteBill = $0021; //删除交货单 cBC_ModifyBillTruck = $0022; //修改车牌号 cBC_SaleAdjust = $0023; //销售调拨 cBC_SaveBillCard = $0024; //绑定交货单磁卡 cBC_LogoffCard = $0025; //注销磁卡 cBC_DeleteOrder = $0026; //删除入厂明细 cBC_GetPostBills = $0030; //获取岗位交货单 cBC_SavePostBills = $0031; //保存岗位交货单 cBC_SaveBillNew = $0032; //生成基础交货单 cBC_DeleteBillNew = $0033; //删除基础交货单 cBC_SaveBillNewCard = $0034; //绑定基础单磁卡 cBC_LogoffCardNew = $0035; //注销磁卡 cBC_SaveBillFromNew = $0036; //根据基础单据生成交货单 cBC_ChangeDispatchMode = $0053; //切换调度模式 cBC_GetPoundCard = $0054; //获取磅站卡号 cBC_GetQueueData = $0055; //获取队列数据 cBC_PrintCode = $0056; cBC_PrintFixCode = $0057; //喷码 cBC_PrinterEnable = $0058; //喷码机启停 cBC_PrinterChinaEnable = $0059; //喷码机启停 cBC_JSStart = $0060; cBC_JSStop = $0061; cBC_JSPause = $0062; cBC_JSGetStatus = $0063; cBC_SaveCountData = $0064; //保存计数结果 cBC_RemoteExecSQL = $0065; cBC_IsTunnelOK = $0075; cBC_TunnelOC = $0076; cBC_GetSQLQueryWeixin = $0081; //获取微信信息查询语句 cBC_SaveWeixinAccount = $0082; //保存微信账户 cBC_DelWeixinAccount = $0083; //删除微信账户 cBC_GetWeiXinReport = $0084; //获取微信报表 cBC_GetWeiXinQueue = $0085; //获取微信报表 cBC_GetTruckPValue = $0091; //获取车辆预置皮重 cBC_SaveTruckPValue = $0092; //保存车辆预置皮重 cBC_GetPoundBaseValue = $0093; //获取地磅表头跳动基数 type PWorkerQueryFieldData = ^TWorkerQueryFieldData; TWorkerQueryFieldData = record FBase : TBWDataBase; FType : Integer; //类型 FData : string; //数据 end; PWorkerBusinessCommand = ^TWorkerBusinessCommand; TWorkerBusinessCommand = record FBase : TBWDataBase; FCommand : Integer; //命令 FData : string; //数据 FExtParam : string; //参数 end; TPoundStationData = record FStation : string; //磅站标识 FValue : Double; //皮重 FDate : TDateTime; //称重日期 FOperator : string; //操作员 end; PLadingBillItem = ^TLadingBillItem; TLadingBillItem = record FID : string; //交货单号 FZhiKa : string; //纸卡编号 FCusID : string; //客户编号 FCusName : string; //客户名称 FTruck : string; //车牌号码 FType : string; //品种类型 FStockNo : string; //品种编号 FStockName : string; //品种名称 FValue : Double; //提货量 FPrice : Double; //提货单价 FCard : string; //磁卡号 FIsVIP : string; //通道类型 FStatus : string; //当前状态 FNextStatus : string; //下一状态 FPData : TPoundStationData; //称皮 FMData : TPoundStationData; //称毛 FFactory : string; //工厂编号 FOrigin : string; //来源,矿点 FPModel : string; //称重模式 FPType : string; //业务类型 FPoundID : string; //称重记录 FSelected : Boolean; //选中状态 FLocked : Boolean; //锁定状态,更新预置皮重 FPreTruckP : Boolean; //预置皮重; FYSValid : string; //验收结果 FKZValue : Double; //扣杂量 FSeal : string; //批次号 FMemo : string; //备注 FExtID_1 : string; //额外编号 FExtID_2 : string; //额外编号 FCardUse : string; //卡片类型 FNCChanged : Boolean; //NC可用量变化 FChangeValue: Double; //NC 减少 end; TLadingBillItems = array of TLadingBillItem; //交货单列表 TWeiXinAccount = record FID : string; //微信ID FWXID : string; //微信开发者ID FWXName : string; //微信名称 FWXFact : string; //微信帐号所属工厂编码 FIsValid : string; //微信状态 FComment : string; //备注信息 FAttention: string; //关注者编号 FAttenType: string; //关注者类型 end; TPreTruckPItem = record FPreUse :Boolean; //使用预置 FPrePMan :string; //预置司磅 FPrePTime :TDateTime; //预置时间 FPrePValue :Double; //预置皮重 FMinPVal :Double; //历史最小皮重 FMaxPVal :Double; //历史最大皮重 FPValue :Double; //有效皮重 FPreTruck :string; //车牌号 end; procedure AnalyseBillItems(const nData: string; var nItems: TLadingBillItems); //解析由业务对象返回的交货单数据 function CombineBillItmes(const nItems: TLadingBillItems): string; //合并交货单数据为业务对象能处理的字符串 procedure AnalyseWXAccountItem(const nData: string; var nItem: TWeiXinAccount); //解析由业务对象返回的微信账户数据 function CombineWXAccountItem(const nItem: TWeiXinAccount): string; //合并微信账户数据为业务对象能处理的字符串 function CombinePreTruckItem(const nItem: TPreTruckPItem): string; //合并预置皮重数据为业务对象能处理的字符串 procedure AnalysePreTruckItem(const nData: string; var nItem: TPreTruckPItem); //解析由业务对象返回的预置皮重数据 resourcestring {*PBWDataBase.FParam*} sParam_NoHintOnError = 'NHE'; //不提示错误 {*plug module id*} sPlug_ModuleBus = '{DF261765-48DC-411D-B6F2-0B37B14E014E}'; //业务模块 sPlug_ModuleHD = '{B584DCD6-40E5-413C-B9F3-6DD75AEF1C62}'; //硬件守护 {*common function*} sSys_BasePacker = 'Sys_BasePacker'; //基本封包器 {*business mit function name*} sBus_ServiceStatus = 'Bus_ServiceStatus'; //服务状态 sBus_GetQueryField = 'Bus_GetQueryField'; //查询的字段 sBus_BusinessSaleBill = 'Bus_BusinessSaleBill'; //交货单相关 sBus_BusinessProvide = 'Bus_BusinessProvide'; //采购单相关 sBus_BusinessCommand = 'Bus_BusinessCommand'; //业务指令 sBus_HardwareCommand = 'Bus_HardwareCommand'; //硬件指令 sBus_BusinessDuanDao = 'Bus_BusinessDuanDao'; //短倒业务相关 {*client function name*} sCLI_ServiceStatus = 'CLI_ServiceStatus'; //服务状态 sCLI_GetQueryField = 'CLI_GetQueryField'; //查询的字段 sCLI_BusinessSaleBill = 'CLI_BusinessSaleBill'; //交货单业务 sCLI_BusinessProvide = 'CLI_BusinessProvide'; //采购单业务 sCLI_BusinessCommand = 'CLI_BusinessCommand'; //业务指令 sCLI_HardwareCommand = 'CLI_HardwareCommand'; //硬件指令 sCLI_BusinessDuanDao = 'CLI_BusinessDuanDao'; //短倒业务相关 implementation //Date: 2014-09-17 //Parm: 交货单数据;解析结果 //Desc: 解析nData为结构化列表数据 procedure AnalyseBillItems(const nData: string; var nItems: TLadingBillItems); var nStr: string; nIdx,nInt: Integer; nListA,nListB: TStrings; begin nListA := TStringList.Create; nListB := TStringList.Create; try nListA.Text := PackerDecodeStr(nData); //bill list nInt := 0; SetLength(nItems, nListA.Count); for nIdx:=0 to nListA.Count - 1 do begin nListB.Text := PackerDecodeStr(nListA[nIdx]); //bill item with nListB,nItems[nInt] do begin FID := Values['ID']; FZhiKa := Values['ZhiKa']; FCusID := Values['CusID']; FCusName := Values['CusName']; FTruck := Values['Truck']; FExtID_1 := Values['ExtID_1']; FExtID_2 := Values['ExtID_2']; FType := Values['Type']; FStockNo := Values['StockNo']; FStockName := Values['StockName']; FCard := Values['Card']; FIsVIP := Values['IsVIP']; FCardUse := Values['CType']; FStatus := Values['Status']; FNextStatus := Values['NextStatus']; FFactory := Values['Factory']; FOrigin := Values['Origin']; FPModel := Values['PModel']; FPType := Values['PType']; FPoundID := Values['PoundID']; FSelected := Values['Selected'] = sFlag_Yes; FLocked := Values['Locked'] = sFlag_Yes; FPreTruckP := Values['PreTruckP'] = sFlag_Yes; FNCChanged := Values['NCChanged'] = sFlag_Yes; with FPData do begin FStation := Values['PStation']; FDate := Str2DateTime(Values['PDate']); FOperator := Values['PMan']; nStr := Trim(Values['PValue']); if (nStr <> '') and IsNumber(nStr, True) then FPData.FValue := StrToFloat(nStr) else FPData.FValue := 0; end; with FMData do begin FStation := Values['MStation']; FDate := Str2DateTime(Values['MDate']); FOperator := Values['MMan']; nStr := Trim(Values['MValue']); if (nStr <> '') and IsNumber(nStr, True) then FMData.FValue := StrToFloat(nStr) else FMData.FValue := 0; end; nStr := Trim(Values['Value']); if (nStr <> '') and IsNumber(nStr, True) then FValue := StrToFloat(nStr) else FValue := 0; nStr := Trim(Values['Price']); if (nStr <> '') and IsNumber(nStr, True) then FPrice := StrToFloat(nStr) else FPrice := 0; nStr := Trim(Values['NCChangeValue']); if (nStr <> '') and IsNumber(nStr, True) then FChangeValue := StrToFloat(nStr) else FChangeValue := 0; nStr := Trim(Values['KZValue']); if (nStr <> '') and IsNumber(nStr, True) then FKZValue := StrToFloat(nStr) else FKZValue := 0; FYSValid:= Values['YSValid']; FMemo := Values['Memo']; FSeal := Values['Seal']; end; Inc(nInt); end; finally nListB.Free; nListA.Free; end; end; //Date: 2014-09-18 //Parm: 交货单列表 //Desc: 将nItems合并为业务对象能处理的 function CombineBillItmes(const nItems: TLadingBillItems): string; var nIdx: Integer; nListA,nListB: TStrings; begin nListA := TStringList.Create; nListB := TStringList.Create; try Result := ''; nListA.Clear; nListB.Clear; for nIdx:=Low(nItems) to High(nItems) do with nItems[nIdx] do begin if not FSelected then Continue; //ignored with nListB do begin Values['ID'] := FID; Values['ZhiKa'] := FZhiKa; Values['CusID'] := FCusID; Values['CusName'] := FCusName; Values['Truck'] := FTruck; Values['ExtID_1'] := FExtID_1; Values['ExtID_2'] := FExtID_2; Values['Type'] := FType; Values['StockNo'] := FStockNo; Values['StockName'] := FStockName; Values['Value'] := FloatToStr(FValue); Values['Price'] := FloatToStr(FPrice); Values['Card'] := FCard; Values['CType'] := FCardUse; Values['IsVIP'] := FIsVIP; Values['Status'] := FStatus; Values['NextStatus'] := FNextStatus; Values['Factory'] := FFactory; Values['Origin'] := FOrigin; Values['PModel'] := FPModel; Values['PType'] := FPType; Values['PoundID'] := FPoundID; with FPData do begin Values['PStation'] := FStation; Values['PValue'] := FloatToStr(FPData.FValue); Values['PDate'] := DateTime2Str(FDate); Values['PMan'] := FOperator; end; with FMData do begin Values['MStation'] := FStation; Values['MValue'] := FloatToStr(FMData.FValue); Values['MDate'] := DateTime2Str(FDate); Values['MMan'] := FOperator; end; if FSelected then Values['Selected'] := sFlag_Yes else Values['Selected'] := sFlag_No; if FLocked then Values['Locked'] := sFlag_Yes else Values['Locked'] := sFlag_No; if FPreTruckP then Values['PreTruckP'] := sFlag_Yes else Values['PreTruckP'] := sFlag_No; if FNCChanged then Values['NCChanged'] := sFlag_Yes else Values['NCChanged'] := sFlag_No; Values['NCChangeValue'] := FloatToStr(FChangeValue); Values['KZValue'] := FloatToStr(FKZValue); Values['YSValid'] := FYSValid; Values['Memo'] := FMemo; Values['Seal'] := FSeal; end; nListA.Add(PackerEncodeStr(nListB.Text)); //add bill end; Result := PackerEncodeStr(nListA.Text); //pack all finally nListB.Free; nListA.Free; end; end; //Date: 2015-04-17 //Parm: 微信帐号信息;解析结果 //Desc: 解析nData为结构化列表数据 procedure AnalyseWXAccountItem(const nData: string; var nItem: TWeiXinAccount); var nListA: TStrings; begin nListA := TStringList.Create; try nListA.Text := PackerDecodeStr(nData); with nListA, nItem do begin FID := Values['ID']; FWXID := Values['WXID']; FWXName := Values['WXName']; FWXFact := Values['WXFactory']; FIsValid := Values['IsValid']; FComment := Values['Comment']; FAttention:= Values['AttentionID']; FAttenType:= Values['AttentionTP']; end; finally nListA.Free; end; end; //Date: 2014-09-18 //Parm: 微信信息列表 //Desc: 将nItems合并为业务对象能处理的 function CombineWXAccountItem(const nItem: TWeiXinAccount): string; var nListA: TStrings; begin nListA := TStringList.Create; try Result := ''; nListA.Clear; with nListA, nItem do begin Values['ID'] := FID; Values['WXID'] := FWXID; Values['WXName'] := FWXName; Values['WXFactory'] := FWXFact; Values['IsValid'] := FIsValid; Values['Comment'] := FComment; Values['AttentionID']:= FAttention; Values['AttentionTP']:= FAttenType; end; Result := PackerEncodeStr(nListA.Text); //pack all finally nListA.Free; end; end; //Date: 2015-04-17 //Parm: 预置皮重信息;解析结果 //Desc: 解析nData为结构化列表数据 procedure AnalysePreTruckItem(const nData: string; var nItem: TPreTruckPItem); var nListA: TStrings; begin nListA := TStringList.Create; try nListA.Text := PackerDecodeStr(nData); with nListA, nItem do begin FPreUse := Values['FPreUse'] = sFlag_Yes; FPrePMan := Values['FPrePMan']; FPrePTime := Str2DateTime(Values['FPrePTime']); FPrePValue := StrToFloat(Values['FPrePValue']); FMinPVal := StrToFloat(Values['FMinPVal']); FMaxPVal := StrToFloat(Values['FMaxPVal']); FPValue := StrToFloat(Values['FPValue']); FPreTruck := Values['FPreTruck']; end; finally nListA.Free; end; end; //Date: 2014-09-18 //Parm: 微信信息列表 //Desc: 将nItems合并为业务对象能处理的 function CombinePreTruckItem(const nItem: TPreTruckPItem): string; var nListA: TStrings; nUse : string; begin nListA := TStringList.Create; try Result := ''; nListA.Clear; with nListA, nItem do begin if FPreUse then nUse := sFlag_Yes else nUse := sFlag_No; Values['FPreUse'] := nUse; Values['FPrePMan'] := FPrePMan; Values['FPrePTime'] := DateTime2Str(FPrePTime); Values['FPrePValue'] := FloatToStr(FPrePValue); Values['FMinPVal'] := FloatToStr(FMinPVal); Values['FMaxPVal'] := FloatToStr(FMaxPVal); Values['FPValue'] := FloatToStr(FPValue); Values['FPreTruck'] := FPreTruck; end; Result := PackerEncodeStr(nListA.Text); //pack all finally nListA.Free; end; end; end.
unit UCustomLists; interface uses Classes; type TCustomList = class(TStringList) public procedure AfterConstruction; override; procedure PopulateList; overload; virtual; abstract; class procedure PopulateList(const AList: TStrings); overload; end; TPostalCodeNameList = class(TCustomList) private procedure PopulateENC; procedure PopulateENU; public procedure PopulateList; override; end; TPostalCodeList = class(TCustomList) public procedure PopulateList; override; end; TPostalNameList = class(TCustomList) public procedure PopulateList; override; end; TTerritoryNameList = class(TPostalNameList) public procedure PopulateList; override; end; implementation uses Windows, SysUtils; // --- TCustomList ------------------------------------------------------------ procedure TCustomList.AfterConstruction; begin inherited; Duplicates := dupIgnore; CaseSensitive := false; PopulateList; end; class procedure TCustomList.PopulateList(const AList: TStrings); var list: TCustomList; begin if not Assigned(AList) then EInvalidPointer.Create('The parameter is invalid'); list := Create; try list.Sort; AList.Text := list.Text; finally FreeAndNil(list); end; end; // --- TPostalCodeNameList -------------------------------------------- procedure TPostalCodeNameList.PopulateList; var sLanguage: array [0..254] of Char; begin GetLocaleInfo(LOCALE_SYSTEM_DEFAULT, LOCALE_SABBREVLANGNAME, sLanguage, sizeof(sLanguage)); if (sLanguage = 'ENU') then PopulateENU else if (sLanguage = 'ENC') then PopulateENC else PopulateENU; end; procedure TPostalCodeNameList.PopulateENC; begin Values['AB'] := 'Alberta'; Values['BC'] := 'British Columbia'; Values['MB'] := 'Manatoba'; Values['NB'] := 'New Brunswick'; Values['NL'] := 'Newfoundland'; Values['NT'] := 'Northwest Territories'; Values['NS'] := 'Nova Scotia'; Values['NU'] := 'Nanavut'; Values['ON'] := 'Ontario'; Values['PE'] := 'Prince Edward Island'; Values['QC'] := 'Quebec'; Values['SK'] := 'Saskatchewan'; Values['YT'] := 'Yukon Territory'; end; procedure TPostalCodeNameList.PopulateENU; begin Values['AA'] := 'Armed Forces Americas'; Values['AE'] := 'Armed Forces Europe'; Values['AK'] := 'Alaska'; Values['AL'] := 'Alabama'; Values['AP'] := 'Armed Forces Pacific'; Values['AR'] := 'Arkansas'; Values['AS'] := 'American Samoa'; Values['AZ'] := 'Arizona'; Values['CA'] := 'California'; Values['CO'] := 'Colorado'; Values['CT'] := 'Connecticut'; Values['DC'] := 'District of Columbia'; Values['DE'] := 'Delaware'; Values['FL'] := 'Florida'; Values['FM'] := 'Federated States of Micronesia'; Values['GA'] := 'Georgia'; Values['GU'] := 'Guam'; Values['HI'] := 'Hawaii'; Values['IA'] := 'Iowa'; Values['ID'] := 'Idaho'; Values['IL'] := 'Illinois'; Values['IN'] := 'Indiana'; Values['KS'] := 'Kansas'; Values['KY'] := 'Kentucky'; Values['LA'] := 'Louisiana'; Values['MA'] := 'Massachusetts'; Values['MD'] := 'Maryland'; Values['ME'] := 'Maine'; Values['MH'] := 'Marshall Islands'; Values['MI'] := 'Michigan'; Values['MN'] := 'Minnesota'; Values['MO'] := 'Missouri'; Values['MS'] := 'Mississippi'; Values['MT'] := 'Montana'; Values['NC'] := 'North Carolina'; Values['ND'] := 'North Dakota'; Values['NE'] := 'Nebraska'; Values['NH'] := 'New Hampshire'; Values['NJ'] := 'New Jersey'; Values['NM'] := 'New Mexico'; Values['NP'] := 'Northern Mariana Islands'; Values['NV'] := 'Nevada'; Values['NY'] := 'New York'; Values['OH'] := 'Ohio'; Values['OK'] := 'Oklahoma'; Values['OR'] := 'Oregon'; Values['PA'] := 'Pennsylvania'; Values['PR'] := 'Puerto Rico'; Values['PW'] := 'Palau'; Values['RI'] := 'Rhode Island'; Values['SC'] := 'South Carolina'; Values['SD'] := 'South Dakota'; Values['TN'] := 'Tennessee'; Values['TX'] := 'Texas'; Values['UT'] := 'Utah'; Values['VA'] := 'Virginia'; Values['VI'] := 'Virgin Islands'; Values['VT'] := 'Vermont'; Values['WA'] := 'Washington'; Values['WI'] := 'Wisconsin'; Values['WV'] := 'West Virginia'; Values['WY'] := 'Wyoming'; end; // --- TPostalCodeList ------------------------------------------------ procedure TPostalCodeList.PopulateList; var index: integer; list: TPostalCodeNameList; begin list := TPostalCodeNameList.Create; try for index := 0 to list.Count - 1 do Add(list.Names[index]); finally FreeAndNil(list); end; end; // --- TPostalNameList -------------------------------------------------------- procedure TPostalNameList.PopulateList; var index: integer; list: TPostalCodeNameList; begin list := TPostalCodeNameList.Create; try for index := 0 to list.Count - 1 do Add(list.ValueFromIndex[index]); finally FreeAndNil(list); end; end; // --- TTerritoryNameList ----------------------------------------------------- procedure TTerritoryNameList.PopulateList; begin inherited; if (IndexOf('Armed Forces Americas') <> -1) then Delete(IndexOf('Armed Forces Americas')); if (IndexOf('Armed Forces Europe') <> -1) then Delete(IndexOf('Armed Forces Europe')); if (IndexOf('Armed Forces Pacific') <> -1) then Delete(IndexOf('Armed Forces Pacific')); end; end.
unit BaseWinFile; interface uses Windows, Types, Sysutils, BaseFile; type TWinFileData = record FileHandle: THandle; FileMapHandle: THandle; FileMapRootView: Pointer; FileSizeLow: DWORD; end; TWinFile = class(TBaseFile) protected fWinFileData: TWinFileData; function GetFileSize: DWORD; override; procedure SetFileSize(const Value: DWORD); override; public constructor Create; virtual; destructor Destroy; override; function OpenFile(AFileUrl: WideString; AForceOpen: Boolean): Boolean; override; procedure CloseFile; override; function OpenFileMap: Pointer; procedure CloseFileMap; procedure ReadTest(); procedure WriteTest(); property FileHandle: THandle read fWinFileData.FileHandle; end; implementation // //uses // UtilsLog; { TWinFile } constructor TWinFile.Create; begin FillChar(fWinFileData, SizeOf(fWinFileData), 0); end; destructor TWinFile.Destroy; begin CloseFile; inherited; end; function TWinFile.OpenFile(AFileUrl: WideString; AForceOpen: Boolean): Boolean; var tmpFlags: DWORD; tmpCreation: DWORD; begin tmpFlags := Windows.FILE_ATTRIBUTE_NORMAL; tmpCreation := Windows.OPEN_EXISTING; if AForceOpen then begin if not FileExists(AFileUrl) then begin tmpCreation := Windows.CREATE_NEW; end; end; fWinFileData.FileHandle := Windows.CreateFileW(PWideChar(AFileUrl), Windows.GENERIC_ALL, Windows.FILE_SHARE_READ or Windows.FILE_SHARE_WRITE or Windows.FILE_SHARE_DELETE, nil, tmpCreation, tmpFlags, 0); //Log('BaseWinFile.pas', 'TWinFile.OpenFile Handle:' + IntToStr(fWinFileData.FileHandle)); Result := (fWinFileData.FileHandle <> 0) and (fWinFileData.FileHandle <> Windows.INVALID_HANDLE_VALUE); if Result then begin fWinFileData.FileSizeLow := Windows.GetFileSize(fWinFileData.FileHandle, nil); end else begin // 5 if ERROR_ACCESS_DENIED = Windows.GetLastError then begin // NTFS 的文件访问权限问题 end; //Log('BaseWinFile.pas', 'TWinFile.OpenFile Fail:' + IntToStr(Windows.GetLastError)); end; end; procedure TWinFile.CloseFile; begin CloseFileMap; if (0 <> fWinFileData.FileHandle) and (INVALID_HANDLE_VALUE <> fWinFileData.FileHandle) then begin if Windows.CloseHandle(fWinFileData.FileHandle) then begin fWinFileData.FileHandle := 0; end; end; inherited; end; function TWinFile.OpenFileMap: Pointer; begin fWinFileData.FileMapHandle := Windows.CreateFileMapping(fWinFileData.FileHandle, nil, Windows.PAGE_READWRITE, 0, 0, nil); if fWinFileData.FileMapHandle <> 0 then begin // OpenFileMapping fWinFileData.FileMapRootView := Windows.MapViewOfFile(fWinFileData.FileMapHandle, Windows.FILE_MAP_ALL_ACCESS, 0, 0, 0); // fWinFileData.FileMapRootView := MapViewOfFileEx( // fWinFileData.FileMapHandle, //hFileMappingObject: THandle; // Windows.FILE_MAP_ALL_ACCESS, //dwDesiredAccess, // 0, //dwFileOffsetHigh, // 0, //dwFileOffsetLow, // 0, //dwNumberOfBytesToMap: DWORD; // nil //lpBaseAddress: Pointer // ); end; Result := fWinFileData.FileMapRootView; end; procedure TWinFile.CloseFileMap; begin if nil <> fWinFileData.FileMapRootView then begin UnMapViewOfFile(fWinFileData.FileMapRootView); fWinFileData.FileMapRootView := nil; end; if 0 <> fWinFileData.FileMapHandle then begin Windows.CloseHandle(fWinFileData.FileMapHandle); fWinFileData.FileMapHandle := 0; end; end; procedure TWinFile.SetFileSize(const Value: DWORD); begin if fWinFileData.FileSizeLow <> Value then begin if 0 < Value then begin Windows.SetFilePointer(fWinFileData.FileHandle, Value, nil, FILE_BEGIN); Windows.SetEndOfFile(fWinFileData.FileHandle); Windows.SetFilePointer(fWinFileData.FileHandle, 0, nil, FILE_BEGIN); fWinFileData.FileSizeLow := Value; end; end; end; function TWinFile.GetFileSize: DWORD; begin Result := fWinFileData.FileSizeLow; end; procedure Proc_ReadCompletion(); stdcall; begin end; procedure Proc_WriteCompletion(); stdcall; begin end; procedure TWinFile.ReadTest(); var tmpBytesRead: Cardinal; tmpBytesReaded: Cardinal; tmpOverlap: TOverlapped; tmpError: DWORD; tmpReadedBuffer: array[0..4 * 1024 - 1] of AnsiChar; begin tmpBytesRead := 0; tmpBytesReaded := 0; if Windows.ReadFile(fWinFileData.FileHandle, tmpReadedBuffer, tmpBytesRead, tmpBytesReaded, @tmpOverlap) then begin end else begin tmpError := Windows.GetLastError(); case tmpError of ERROR_HANDLE_EOF: begin end; ERROR_IO_PENDING: begin if Windows.GetOverlappedResult(fWinFileData.FileHandle, tmpOverlap, tmpBytesReaded, false) then begin end else begin end; end; end; end; // ReadFileEx 与 ReadFile相似 // 只是它只能用于异步读操作,并包含了一个完整的回调 if Windows.ReadFileEx(fWinFileData.FileHandle, @tmpReadedBuffer, tmpBytesRead, @tmpOverlap, @Proc_ReadCompletion) then begin end; end; procedure TWinFile.WriteTest(); var tmpBytesWrite: Cardinal; tmpBytesWritten: Cardinal; tmpOverlap: TOverlapped; tmpWriteBuffer: array[0..4 * 1024 - 1] of AnsiChar; begin tmpBytesWrite := 0; if Windows.WriteFile(fWinFileData.FileHandle, tmpWriteBuffer, tmpBytesWrite, tmpBytesWritten, @tmpOverlap) then begin end; if Windows.WriteFileEx(fWinFileData.FileHandle, @tmpWriteBuffer, tmpBytesWrite, tmpOverlap, @Proc_WriteCompletion) then begin end; end; end.
unit USBIO_I; interface uses Windows; {*********************************************************************** * Module: usbio_i.h * Long name: USBIO Driver Interface * Description: Defines the interface (API) of the USBIO driver * * Runtime Env.: Win32 * Author(s): Guenter Hildebrandt, Thomas Fröhlich * Company: Thesycon GmbH, Ilmenau *********************************************************************** } // // Define the API version number. // This will be incremented if changes are made. // // Applications should check if the driver supports the // required API version using IOCTL_USBIO_GET_DRIVER_INFO. // // current API version: 2.01 const USBIO_API_VERSION = DWORD($0230); // build in (default) GUID for the interface const USBIO_IID_STR = '{325ddf96-938c-11d3-9e34-0080c82727f4}'; USBIO_IID_STR_W : widestring = USBIO_IID_STR; USBIO_IID : TGUID = USBIO_IID_STR; type USHORT = word; // // Error Codes // const USBIO_ERR_SUCCESS = DWORD($00000000); USBIO_ERR_CRC = DWORD($E0000001); USBIO_ERR_BTSTUFF = DWORD($E0000002); USBIO_ERR_DATA_TOGGLE_MISMATCH = DWORD($E0000003); USBIO_ERR_STALL_PID = DWORD($E0000004); USBIO_ERR_DEV_NOT_RESPONDING = DWORD($E0000005); USBIO_ERR_PID_CHECK_FAILURE = DWORD($E0000006); USBIO_ERR_UNEXPECTED_PID = DWORD($E0000007); USBIO_ERR_DATA_OVERRUN = DWORD($E0000008); USBIO_ERR_DATA_UNDERRUN = DWORD($E0000009); USBIO_ERR_RESERVED1 = DWORD($E000000A); USBIO_ERR_RESERVED2 = DWORD($E000000B); USBIO_ERR_BUFFER_OVERRUN = DWORD($E000000C); USBIO_ERR_BUFFER_UNDERRUN = DWORD($E000000D); USBIO_ERR_NOT_ACCESSED = DWORD($E000000F); USBIO_ERR_FIFO = DWORD($E0000010); USBIO_ERR_ENDPOINT_HALTED = DWORD($E0000030); USBIO_ERR_NO_MEMORY = DWORD($E0000100); USBIO_ERR_INVALID_URB_FUNCTION = DWORD($E0000200); USBIO_ERR_INVALID_PARAMETER = DWORD($E0000300); USBIO_ERR_ERROR_BUSY = DWORD($E0000400); USBIO_ERR_REQUEST_FAILED = DWORD($E0000500); USBIO_ERR_INVALID_PIPE_HANDLE = DWORD($E0000600); USBIO_ERR_NO_BANDWIDTH = DWORD($E0000700); USBIO_ERR_INTERNAL_HC_ERROR = DWORD($E0000800); USBIO_ERR_ERROR_SHORT_TRANSFER = DWORD($E0000900); USBIO_ERR_BAD_START_FRAME = DWORD($E0000A00); USBIO_ERR_ISOCH_REQUEST_FAILED = DWORD($E0000B00); USBIO_ERR_FRAME_CONTROL_OWNED = DWORD($E0000C00); USBIO_ERR_FRAME_CONTROL_NOT_OWNED = DWORD($E0000D00); USBIO_ERR_INSUFFICIENT_RESOURCES = DWORD($E8001000); USBIO_ERR_SET_CONFIG_FAILED = DWORD($E0002000); USBIO_ERR_USBD_BUFFER_TOO_SMALL = DWORD($E0003000); USBIO_ERR_USBD_INTERFACE_NOT_FOUND = DWORD($E0004000); USBIO_ERR_INVALID_PIPE_FLAGS = DWORD($E0005000); USBIO_ERR_USBD_TIMEOUT = DWORD($E0006000); USBIO_ERR_DEVICE_GONE = DWORD($E0007000); USBIO_ERR_STATUS_NOT_MAPPED = DWORD($E0008000); USBIO_ERR_CANCELED = DWORD($E0010000); USBIO_ERR_ISO_NOT_ACCESSED_BY_HW = DWORD($E0020000); USBIO_ERR_ISO_TD_ERROR = DWORD($E0030000); USBIO_ERR_ISO_NA_LATE_USBPORT = DWORD($E0040000); USBIO_ERR_ISO_NOT_ACCESSED_LATE = DWORD($E0050000); USBIO_ERR_FAILED = DWORD($E0001000); USBIO_ERR_INVALID_INBUFFER = DWORD($E0001001); USBIO_ERR_INVALID_OUTBUFFER = DWORD($E0001002); USBIO_ERR_OUT_OF_MEMORY = DWORD($E0001003); USBIO_ERR_PENDING_REQUESTS = DWORD($E0001004); USBIO_ERR_ALREADY_CONFIGURED = DWORD($E0001005); USBIO_ERR_NOT_CONFIGURED = DWORD($E0001006); USBIO_ERR_OPEN_PIPES = DWORD($E0001007); USBIO_ERR_ALREADY_BOUND = DWORD($E0001008); USBIO_ERR_NOT_BOUND = DWORD($E0001009); USBIO_ERR_DEVICE_NOT_PRESENT = DWORD($E000100A); USBIO_ERR_CONTROL_NOT_SUPPORTED = DWORD($E000100B); USBIO_ERR_TIMEOUT = DWORD($E000100C); USBIO_ERR_INVALID_RECIPIENT = DWORD($E000100D); USBIO_ERR_INVALID_TYPE = DWORD($E000100E); USBIO_ERR_INVALID_IOCTL = DWORD($E000100F); USBIO_ERR_INVALID_DIRECTION = DWORD($E0001010); USBIO_ERR_TOO_MUCH_ISO_PACKETS = DWORD($E0001011); USBIO_ERR_POOL_EMPTY = DWORD($E0001012); USBIO_ERR_PIPE_NOT_FOUND = DWORD($E0001013); USBIO_ERR_INVALID_ISO_PACKET = DWORD($E0001014); USBIO_ERR_OUT_OF_ADDRESS_SPACE = DWORD($E0001015); USBIO_ERR_INTERFACE_NOT_FOUND = DWORD($E0001016); USBIO_ERR_INVALID_DEVICE_STATE = DWORD($E0001017); USBIO_ERR_INVALID_PARAM = DWORD($E0001018); USBIO_ERR_DEMO_EXPIRED = DWORD($E0001019); USBIO_ERR_INVALID_POWER_STATE = DWORD($E000101A); USBIO_ERR_POWER_DOWN = DWORD($E000101B); USBIO_ERR_VERSION_MISMATCH = DWORD($E000101C); USBIO_ERR_SET_CONFIGURATION_FAILED = DWORD($E000101D); USBIO_ERR_ADDITIONAL_EVENT_SIGNALLED = DWORD($E000101E); USBIO_ERR_INVALID_PROCESS = DWORD($E000101F); USBIO_ERR_DEVICE_ACQUIRED = DWORD($E0001020); USBIO_ERR_DEVICE_OPENED = DWORD($E0001021); USBIO_ERR_VID_RESTRICTION = DWORD($E0001080); USBIO_ERR_ISO_RESTRICTION = DWORD($E0001081); USBIO_ERR_BULK_RESTRICTION = DWORD($E0001082); USBIO_ERR_EP0_RESTRICTION = DWORD($E0001083); USBIO_ERR_PIPE_RESTRICTION = DWORD($E0001084); USBIO_ERR_PIPE_SIZE_RESTRICTION = DWORD($E0001085); USBIO_ERR_CONTROL_RESTRICTION = DWORD($E0001086); USBIO_ERR_INTERRUPT_RESTRICTION = DWORD($E0001087); USBIO_ERR_DEVICE_NOT_FOUND = DWORD($E0001100); USBIO_ERR_DEVICE_NOT_OPEN = DWORD($E0001102); USBIO_ERR_NO_SUCH_DEVICE_INSTANCE = DWORD($E0001104); USBIO_ERR_INVALID_FUNCTION_PARAM = DWORD($E0001105); // // IOCTL codes. // Note that function codes 0-2047 are reserved for Microsoft, and // 2048-4095 are reserved for customers. // IOCTL_USBIO_GET_DESCRIPTOR = DWORD($80942006); IOCTL_USBIO_SET_DESCRIPTOR = DWORD($80942009); IOCTL_USBIO_SET_FEATURE = DWORD($8094200C); IOCTL_USBIO_CLEAR_FEATURE = DWORD($80942010); IOCTL_USBIO_GET_STATUS = DWORD($80942014); IOCTL_USBIO_GET_CONFIGURATION = DWORD($80942018); IOCTL_USBIO_GET_INTERFACE = DWORD($8094201C); IOCTL_USBIO_STORE_CONFIG_DESCRIPTOR = DWORD($80942020); IOCTL_USBIO_SET_CONFIGURATION = DWORD($80942024); IOCTL_USBIO_UNCONFIGURE_DEVICE = DWORD($80942028); IOCTL_USBIO_SET_INTERFACE = DWORD($8094202C); IOCTL_USBIO_CLASS_OR_VENDOR_IN_REQUEST = DWORD($80942032); IOCTL_USBIO_CLASS_OR_VENDOR_OUT_REQUEST = DWORD($80942035); IOCTL_USBIO_GET_DEVICE_PARAMETERS = DWORD($8094203C); IOCTL_USBIO_SET_DEVICE_PARAMETERS = DWORD($80942040); IOCTL_USBIO_GET_CONFIGURATION_INFO = DWORD($80942050); IOCTL_USBIO_RESET_DEVICE = DWORD($80942054); IOCTL_USBIO_GET_CURRENT_FRAME_NUMBER = DWORD($80942058); IOCTL_USBIO_SET_DEVICE_POWER_STATE = DWORD($8094205C); IOCTL_USBIO_GET_DEVICE_POWER_STATE = DWORD($80942060); IOCTL_USBIO_GET_BANDWIDTH_INFO = DWORD($80942064); IOCTL_USBIO_GET_DEVICE_INFO = DWORD($80942068); IOCTL_USBIO_GET_DRIVER_INFO = DWORD($8094206C); IOCTL_USBIO_CYCLE_PORT = DWORD($80942070); IOCTL_USBIO_BIND_PIPE = DWORD($80942078); IOCTL_USBIO_UNBIND_PIPE = DWORD($8094207C); IOCTL_USBIO_RESET_PIPE = DWORD($80942080); IOCTL_USBIO_ABORT_PIPE = DWORD($80942084); IOCTL_USBIO_GET_PIPE_PARAMETERS = DWORD($8094208C); IOCTL_USBIO_SET_PIPE_PARAMETERS = DWORD($80942090); IOCTL_USBIO_SETUP_PIPE_STATISTICS = DWORD($80942094); IOCTL_USBIO_QUERY_PIPE_STATISTICS = DWORD($80942098); IOCTL_USBIO_PIPE_CONTROL_TRANSFER_IN = DWORD($809420A2); IOCTL_USBIO_PIPE_CONTROL_TRANSFER_OUT= DWORD($809420A5); IOCTL_USBIO_ACQUIRE_DEVICE = DWORD($809420C8); IOCTL_USBIO_RELEASE_DEVICE = DWORD($809420CC); USBIO_RESET_DEVICE_ON_CLOSE = DWORD($00000001); USBIO_UNCONFIGURE_ON_CLOSE = DWORD($00000002); USBIO_ENABLE_REMOTE_WAKEUP = DWORD($00000004); USBIO_SHORT_TRANSFER_OK = DWORD($00010000); USBIO_START_TRANSFER_ASAP = DWORD($00020000); USBIO_MAX_INTERFACES = DWORD(32); USBIO_MAX_PIPES = DWORD(32); {$MINENUMSIZE 4} // enum type constants should be longwords type USBIO_PIPE_TYPE = ( PipeTypeControl, PipeTypeIsochronous, PipeTypeBulk, PipeTypeInterrupt); type USBIO_REQUEST_RECIPIENT = ( RecipientDevice, RecipientInterface, RecipientEndpoint, RecipientOther); type USBIO_REQUEST_TYPE = ( UsbioRequestDummy_0, // =0 RequestTypeClass, RequestTypeVendor); type USBIO_DEVICE_POWER_STATE = ( DevicePowerStateD0, DevicePowerStateD1, DevicePowerStateD2, DevicePowerStateD3); type USBIO_BANDWIDTH_INFO = packed record TotalBandwidth : ULONG; ConsumedBandwidth : ULONG; reserved1 : ULONG; reserved2 : ULONG; end; PUSBIO_BANDWIDTH_INFO = ^USBIO_BANDWIDTH_INFO; type USBIO_DEVICE_INFO = packed record Flags : ULONG; reserved1 : ULONG; reserved2 : ULONG; reserved3 : ULONG; end; PUSBIO_DEVICE_INFO = ^USBIO_DEVICE_INFO; const USBIO_DEVICE_INFOFLAG_HIGH_SPEED : longword = $00100000; type USBIO_DESCRIPTOR_REQUEST = packed record Recipient : USBIO_REQUEST_RECIPIENT; DescriptorType : UCHAR; DescriptorIndex : UCHAR; LanguageId : USHORT; end; PUSBIO_DESCRIPTOR_REQUEST = ^USBIO_DESCRIPTOR_REQUEST; type USBIO_FEATURE_REQUEST = packed record Recipient : USBIO_REQUEST_RECIPIENT; FeatureSelector : USHORT; Index : USHORT; end; PUSBIO_FEATURE_REQUEST = ^USBIO_FEATURE_REQUEST; type USBIO_STATUS_REQUEST = packed record Recipient : USBIO_REQUEST_RECIPIENT; Index : USHORT; end; PUSBIO_STATUS_REQUEST = ^USBIO_STATUS_REQUEST; type USBIO_STATUS_REQUEST_DATA = packed record Status : USHORT; end; PUSBIO_STATUS_REQUEST_DATA = ^USBIO_STATUS_REQUEST_DATA; type USBIO_GET_CONFIGURATION_DATA = packed record ConfigurationValue : UCHAR; end; PUSBIO_GET_CONFIGURATION_DATA = ^USBIO_GET_CONFIGURATION_DATA; type USBIO_GET_INTERFACE = packed record _Interface : USHORT; //in c++ Interface end; PUSBIO_GET_INTERFACE = ^USBIO_GET_INTERFACE; type USBIO_GET_INTERFACE_DATA = packed record AlternateSetting : UCHAR; end; PUSBIO_GET_INTERFACE_DATA = ^USBIO_GET_INTERFACE_DATA; type USBIO_INTERFACE_SETTING = packed record InterfaceIndex : USHORT; AlternateSettingIndex : USHORT; MaximumTransferSize : ULONG; end; PUSBIO_INTERFACE_SETTING = ^USBIO_INTERFACE_SETTING; type USBIO_SET_CONFIGURATION = packed record ConfigurationIndex : USHORT; NbOfInterfaces : USHORT; InterfaceList : array[0..(USBIO_MAX_INTERFACES-1)] of USBIO_INTERFACE_SETTING; end; PUSBIO_SET_CONFIGURATION = ^USBIO_SET_CONFIGURATION; type USBIO_CLASS_OR_VENDOR_REQUEST = packed record Flags : ULONG; _Type : USBIO_REQUEST_TYPE; Recipient : USBIO_REQUEST_RECIPIENT; RequestTypeReservedBits : UCHAR; Request : UCHAR; Value : USHORT; Index : USHORT; end; PUSBIO_CLASS_OR_VENDOR_REQUEST = ^USBIO_CLASS_OR_VENDOR_REQUEST; type USBIO_DEVICE_PARAMETERS = packed record Options : ULONG; RequestTimeout : ULONG; end; PUSBIO_DEVICE_PARAMETERS = ^USBIO_DEVICE_PARAMETERS; type USBIO_INTERFACE_CONFIGURATION_INFO = packed record InterfaceNumber : UCHAR; AlternateSetting : UCHAR; _Class : UCHAR; SubClass : UCHAR; Protocol : UCHAR; NumberOfPipes : UCHAR; reserved1 : UCHAR; reserved2 : UCHAR; end; PUSBIO_INTERFACE_CONFIGURATION_INFO = ^USBIO_INTERFACE_CONFIGURATION_INFO; type USBIO_PIPE_CONFIGURATION_INFO = packed record PipeType : USBIO_PIPE_TYPE; MaximumTransferSize : ULONG; MaximumPacketSize : USHORT; EndpointAddress : UCHAR; Interval : UCHAR; InterfaceNumber : UCHAR; reserved1 : UCHAR; reserved2 : UCHAR; reserved3 : UCHAR; end; PUSBIO_PIPE_CONFIGURATION_INFO = ^USBIO_PIPE_CONFIGURATION_INFO; type USBIO_CONFIGURATION_INFO = packed record NbOfInterfaces : ULONG; NbOfPipes : ULONG; InterfaceInfo : Array[0..USBIO_MAX_INTERFACES-1] of USBIO_INTERFACE_CONFIGURATION_INFO; PipeInfo : Array[0..USBIO_MAX_PIPES-1] of USBIO_PIPE_CONFIGURATION_INFO; end; PUSBIO_CONFIGURATION_INFO = ^USBIO_CONFIGURATION_INFO; type USBIO_FRAME_NUMBER = packed record FrameNumber : ULONG; end; PUSBIO_FRAME_NUMBER = ^USBIO_FRAME_NUMBER; type USBIO_DEVICE_POWER = packed record DevicePowerState : USBIO_DEVICE_POWER_STATE; end; PUSBIO_DEVICE_POWER = ^USBIO_DEVICE_POWER; type USBIO_DRIVER_INFO = packed record APIVersion : USHORT; DriverVersion : USHORT; DriverBuildNumber : ULONG; Flags : ULONG; end; PUSBIO_DRIVER_INFO = ^USBIO_DRIVER_INFO; const USBIO_INFOFLAG_CHECKED_BUILD : longword = $00000010; USBIO_INFOFLAG_DEMO_VERSION : longword = $00000020; type USBIO_BIND_PIPE = packed record EndpointAddress : UCHAR; end; PUSBIO_BIND_PIPE = ^USBIO_BIND_PIPE; type USBIO_PIPE_PARAMETERS = packed record Flags : ULONG; end; PUSBIO_PIPE_PARAMETERS = ^USBIO_PIPE_PARAMETERS; type USBIO_SETUP_PIPE_STATISTICS = packed record AveragingInterval : ULONG; reserved1 : ULONG; reserved2 : ULONG; end; PUSBIO_SETUP_PIPE_STATISTICS = ^USBIO_SETUP_PIPE_STATISTICS; type USBIO_QUERY_PIPE_STATISTICS = packed record Flags : ULONG; end; PUSBIO_QUERY_PIPE_STATISTICS = ^USBIO_QUERY_PIPE_STATISTICS; const USBIO_QPS_FLAG_RESET_BYTES_TRANSFERRED : longword = $00000001; USBIO_QPS_FLAG_RESET_REQUESTS_SUCCEEDED : longword = $00000002; USBIO_QPS_FLAG_RESET_REQUESTS_FAILED : longword = $00000004; USBIO_QPS_FLAG_RESET_ALL_COUNTERS : longword = $00000007; type USBIO_PIPE_STATISTICS = packed record ActualAveragingInterval : ULONG; AverageRate : ULONG; BytesTransferred_L : ULONG; BytesTransferred_H : ULONG; RequestsSucceeded : ULONG; RequestsFailed : ULONG; reserved1 : ULONG; reserved2 : ULONG; end; PUSBIO_PIPE_STATISTICS = ^USBIO_PIPE_STATISTICS; type USBIO_PIPE_CONTROL_TRANSFER = packed record Flags : ULONG; SetupPacket : Array[0..8-1] of UCHAR; end; PUSBIO_PIPE_CONTROL_TRANSFER = ^USBIO_PIPE_CONTROL_TRANSFER; // // Isochronous Transfers // // The data buffer passed to ReadFile/WriteFile must contain a // predefined header that describes the size and location of the // packets to be transferred. The USBIO_ISO_TRANSFER_HEADER consists // of a fixed size part USBIO_ISO_TRANSFER and a variable size array // of USBIO_ISO_PACKET descriptors. // type USBIO_ISO_TRANSFER = packed record NumberOfPackets : ULONG; Flags : ULONG; StartFrame : ULONG; ErrorCount : ULONG; end; PUSBIO_ISO_TRANSFER = ^USBIO_ISO_TRANSFER; type USBIO_ISO_PACKET = packed record Offset : ULONG; Length : ULONG; Status : ULONG; end; PUSBIO_ISO_PACKET = ^USBIO_ISO_PACKET; type USBIO_ISO_TRANSFER_HEADER = packed record IsoTransfer : USBIO_ISO_TRANSFER; IsoPacket : Array[0..1-1] of USBIO_ISO_PACKET; end; PUSBIO_ISO_TRANSFER_HEADER = ^USBIO_ISO_TRANSFER_HEADER; // // Define the device type value. Note that values used by Microsoft // are in the range 0-32767, and 32768-65535 are reserved for use // by customers. // const FILE_DEVICE_USBIO = DWORD($8094); const _USBIO_IOCTL_BASE = DWORD($800); implementation end.
unit DirFindNodes; interface uses Classes, ComCtrls, DirFindWorker; type TDirFindTreeNode=class(TTreeNode)//abstract public function ProgressText:string; virtual; procedure DoDblClick; virtual; end; TDirFinderNodeProgress=procedure(Sender:TObject; const PrgTxt:string) of object; TDirFinderNode=class(TDirFindTreeNode) private FDirFinder:TDirFinder; FRootPath,FFiles,FNotFiles,FPattern,FProgressText:string; FIgnoreCase,FMultiLine:boolean; FCountMatches:TDirFinderCountMatches; FTotalFilesFound:integer; FTotalFinds:array of integer; FOnProgress:TDirFinderNodeProgress; FOnStoreValues:TNotifyEvent; public procedure Start(const Folder,Files,NotFiles,Pattern:string; IgnoreCase,MultiLine:boolean;CountMatches:TDirFinderCountMatches; OnStoreValues:TNotifyEvent); procedure FinderNotify(nm:TDirFinderNotifyMessage; const msg:string;const vals:array of integer); destructor Destroy; override; procedure Abort; procedure Refresh; function ReplaceAll(const ReplaceWith:WideString):integer; property OnProgress:TDirFinderNodeProgress read FOnProgress write FOnProgress; property Pattern:string read FPattern; property RootPath:string read FRootPath; property FindFiles:string read FFiles; property FindNotFiles:string read FNotFiles; function ProgressText:string; override; function IsFinding:boolean; function AllFilePaths:string; end; TDirFindFolderNode=class(TDirFindTreeNode) private FMatchingFiles,FFolders:integer; FMatches:array of integer; procedure IncMatches(const vals:array of integer); public FolderName:string; procedure AfterConstruction; override; procedure SetPrioFolder; function FolderPath:string; function ProgressText:string; override; end; TDirFindMatchNode=class(TDirFindTreeNode) private FFilePath:string; FLines:integer; FMatchingLinesLoaded:boolean; public procedure AfterConstruction; override; function ProgressText:string; override; procedure DoDblClick; override; property FilePath:string read FFilePath; property Lines:integer read FLines; end; TDirFindLineNode=class(TDirFindTreeNode) private FLineNumber,FIndentLevel:integer; procedure UpdateIcons; public procedure DoDblClick; override; property LineNumber:integer read FLineNumber; end; var DirFindNextNodeClass:TTreeNodeClass; IndentLevelTabSize:integer; implementation uses SysUtils, VBScript_RegExp_55_TLB; const NodeTextSeparator=#$95;//' '; NodeTextProgress='...'; NodeTextMatchCount=#$B7;//':'; NodeTextSubMatchCount=' \'; iiFolder=0; iiFolderWorking=1; iiFile=2; iiFolderGray=3; iiError=4; iiLineMatch=5; iiFileMulti=6;//..6+7 iiLineMatchMulti=14;//..14+7 iiLine=22; iiLineNeighboursLoaded=23; function IndentLevel(var w:WideString):integer; var i,j,k,l:integer; x:WideString; y:boolean; begin i:=1; j:=1; Result:=0; x:=w; y:=true; l:=Length(x); k:=l; while i<=l do begin if x[i]=#9 then begin if j+IndentLevelTabSize>=k then begin inc(k,$100); SetLength(w,k); end; w[j]:=#32; inc(j); while ((j-1) mod IndentLevelTabSize)<>0 do begin w[j]:=#32; inc(j); end; if y then Result:=j-1; end else begin if y then if x[i]=#32 then inc(Result) else y:=false; if j=k then begin inc(k,$100); SetLength(w,k); end; w[j]:=x[i]; inc(j); end; inc(i); end; SetLength(w,j-1); end; { TDirFindTreeNode } procedure TDirFindTreeNode.DoDblClick; begin // end; function TDirFindTreeNode.ProgressText: string; begin Result:=Text;//inheritants don't need to call inherited end; { TDirFinderNode } destructor TDirFinderNode.Destroy; begin if FDirFinder<>nil then FDirFinder.Terminate; inherited; end; procedure TDirFinderNode.FinderNotify(nm: TDirFinderNotifyMessage; const msg: string; const vals: array of integer); var tn:TTreeNode; procedure FindNode(IsFile:boolean); var tn1:TTreeNode; i,j,k:integer; s:string; begin tn:=Self; i:=Length(FRootPath)+2; while (i<=Length(msg)) do begin j:=i; while (j<=Length(msg)) and (msg[j]<>'\') do inc(j); if IsFile and (j>Length(msg)) then begin s:=Copy(msg,i,j-i); tn1:=tn.getFirstChild; while (tn1<>nil) and (tn1 is TDirFindFolderNode) do tn1:=tn1.getNextSibling; while (tn1<>nil) and (CompareText(tn1.Text,s)<0) do tn1:=tn1.getNextSibling; //assert doesn't exist already, only one FindNode(true) call case FCountMatches of ncMatches: s:=s+NodeTextSeparator+IntToStr(vals[0]);//assert(Length(vals)=1) ncSubMatches: if Length(vals)>0 then if Length(vals)>3 then begin s:=s+NodeTextSeparator+IntToStr(vals[0]); for k:=1 to Length(vals)-1 do s:=s+NodeTextSubMatchCount+IntToStr(k)+'='+IntToStr(vals[k]); end else begin s:=s+NodeTextSeparator+IntToStr(vals[0]); for k:=1 to Length(vals)-1 do s:=s+NodeTextMatchCount+IntToStr(vals[k]); end; end; DirFindNextNodeClass:=TDirFindMatchNode; if tn1=nil then tn1:=Owner.AddChild(tn,s) else tn1:=Owner.Insert(tn1,s); (tn1 as TDirFindMatchNode).FFilePath:=msg; end else begin s:='\'+Copy(msg,i,j-i); tn1:=tn.getFirstChild; while (tn1<>nil) and (tn1 is TDirFindFolderNode) and (CompareText((tn1 as TDirFindFolderNode).FolderName,s)<0) do tn1:=tn1.getNextSibling; if (tn1=nil) or not(tn1 is TDirFindFolderNode) or ((tn1 as TDirFindFolderNode).FolderName<>s) then begin DirFindNextNodeClass:=TDirFindFolderNode; if tn1=nil then tn1:=Owner.AddChild(tn,s+NodeTextProgress) else tn1:=Owner.Insert(tn1,s+NodeTextProgress); (tn1 as TDirFindFolderNode).FolderName:=s; if tn<>Self then inc((tn as TDirFindFolderNode).FFolders); end; end; i:=j+1; tn:=tn1; end; end; var tn1:TTreeNode; s1:string; k,l:integer; begin case nm of nmDone: begin FDirFinder:=nil; if ImageIndex<>iiFolderGray then //see nmError below begin ImageIndex:=iiFolder; SelectedIndex:=iiFolder; end; case FCountMatches of ncFiles: s1:=IntToStr(FTotalFinds[0]); ncMatches://assert(Length(FTotalFinds)=1) s1:=IntToStr(FTotalFilesFound)+NodeTextMatchCount+IntToStr(FTotalFinds[0]); ncSubMatches: begin s1:=IntToStr(FTotalFilesFound); if Length(FTotalFinds)>3 then begin s1:=s1+NodeTextMatchCount+IntToStr(FTotalFinds[0]); for k:=1 to Length(FTotalFinds)-1 do s1:=s1+NodeTextSubMatchCount+IntToStr(k)+'='+IntToStr(FTotalFinds[k]); end else for k:=0 to Length(FTotalFinds)-1 do s1:=s1+NodeTextMatchCount+IntToStr(FTotalFinds[k]); end; end; FProgressText:=FRootPath+NodeTextSeparator+s1+NodeTextSeparator+ FPattern+NodeTextSeparator+FFiles+NodeTextSeparator+FNotFiles; Text:=FProgressText; if @FOnProgress<>nil then FOnProgress(Self,FProgressText); if (@FOnStoreValues<>nil) and (FTotalFilesFound<>0) then FOnStoreValues(Self); end; nmError: begin DirFindNextNodeClass:=TTreeNode;//TDirFindErrorNode? ImageIndex:=iiFolderGray; SelectedIndex:=iiFolderGray; tn:=Owner.AddChild(Self,msg); tn.ImageIndex:=iiError; tn.SelectedIndex:=iiError; end; nmFolderFound: begin FindNode(false); tn.ImageIndex:=iiFolderWorking; tn.SelectedIndex:=iiFolderWorking; end; nmProgress: begin FProgressText:=NodeTextProgress+msg; if @FOnProgress<>nil then FOnProgress(Self,FProgressText); end; nmFolderDone: begin FindNode(false); while tn<>Self do begin if tn.Count=0 then begin tn1:=tn.Parent; tn.Delete; tn:=tn1; end else if (tn as TDirFindFolderNode).FFolders=0 then begin tn.ImageIndex:=iiFolder; tn.SelectedIndex:=iiFolder; tn:=tn.Parent; end else tn:=Self; if tn<>Self then dec((tn as TDirFindFolderNode).FFolders); end; end; nmMatchFound: begin FindNode(true); tn.ImageIndex:=iiFile; tn.SelectedIndex:=iiFile; inc(FTotalFilesFound); k:=Length(FTotalFinds); l:=Length(vals); if k<l then begin SetLength(FTotalFinds,l); while k<l do begin FTotalFinds[k]:=0; inc(k); end; end; for k:=0 to l-1 do inc(FTotalFinds[k],vals[k]); tn:=tn.Parent; while (tn<>nil) and (tn<>Self) do begin (tn as TDirFindFolderNode).IncMatches(vals); tn:=tn.Parent; end; end; end; end; procedure TDirFinderNode.Start(const Folder, Files, NotFiles, Pattern: string; IgnoreCase, MultiLine: boolean; CountMatches: TDirFinderCountMatches; OnStoreValues: TNotifyEvent); var i:integer; begin //assert called once, short after add/create FRootPath:=Folder; FFiles:=Files; FNotFiles:=NotFiles; FPattern:=Pattern; FIgnoreCase:=IgnoreCase; FMultiLine:=MultiLine; FCountMatches:=CountMatches; FProgressText:=NodeTextProgress+Folder; FOnStoreValues:=OnStoreValues; i:=Length(FRootPath); if (i<>0) and (FRootPath[i]='\') then SetLength(FRootPath,i-1); FDirFinder:=nil; Refresh; end; procedure TDirFinderNode.Refresh; begin if FDirFinder<>nil then FDirFinder.Terminate; DeleteChildren; ImageIndex:=iiFolderWorking; SelectedIndex:=iiFolderWorking; FTotalFilesFound:=0; SetLength(FTotalFinds,1); FTotalFinds[0]:=0; Text:=FRootPath+NodeTextSeparator+NodeTextProgress+NodeTextSeparator+ FPattern+NodeTextSeparator+FFiles+NodeTextSeparator+FNotFiles; FDirFinder:=TDirFinder.Create(FRootPath,FFiles,FNotFiles,FPattern, FIgnoreCase,FMultiLine,FCountMatches,FinderNotify); //assert notifies nmDone when done end; procedure TDirFinderNode.Abort; begin if FDirFinder<>nil then begin FDirFinder.Terminate; FinderNotify(nmError,'Aborted by user',[]); FinderNotify(nmDone,'',[-1]); end; end; function TDirFinderNode.ProgressText: string; begin Result:=FProgressText; end; function TDirFinderNode.IsFinding: boolean; begin Result:=FDirFinder<>nil; end; function TDirFinderNode.ReplaceAll(const ReplaceWith: WideString): integer; var re:RegExp; tn,tnLast:TTreeNode; enc:TFileEncoding; fn:string; s:RawByteString; w:WideString; f:TFileStream; const BOMUtf16=#$FF#$FE; BOMUtf8=#$EF#$BB#$BF; begin //assert FDirFinder=nil, checked so by caller re:=CoRegExp.Create; re.Pattern:=FPattern; re.IgnoreCase:=FIgnoreCase; re.Multiline:=FMultiLine; re.Global:=true; Result:=0; Owner.BeginUpdate; try tn:=Self.getFirstChild; tnLast:=Self.getNextSibling; while (tn<>tnLast) do begin if (tn is TDirFindMatchNode) then begin if tn.Count<>0 then tn.DeleteChildren;//reset any matching lines shown fn:=(tn as TDirFindMatchNode).FilePath; w:=re.Replace(FileAsWideString(fn,enc),ReplaceWith); f:=TFileStream.Create(fn,fmCreate); try case enc of feUtf16: begin f.Write(BOMUtf16[1],2); f.Write(w[1],Length(w)*2); end; feUtf8: begin s:=UTF8Encode(w); f.Write(BOMUtf8[1],3); f.Write(s[1],Length(s)); end; else//feUnknown begin s:=AnsiString(w); f.Write(s[1],Length(s)); end; end; finally f.Free; end; inc(Result); end; tn:=tn.GetNext; end; finally Owner.EndUpdate; end; end; function TDirFinderNode.AllFilePaths: string; var n,n1:TTreeNode; begin Result:=''; n1:=getNextSibling; n:=Self; while n<>n1 do begin if n is TDirFindMatchNode then Result:=Result+(n as TDirFindMatchNode).FilePath+#13#10; n:=n.GetNext; end; end; { TDirFindFolderNode } procedure TDirFindFolderNode.AfterConstruction; begin inherited; FMatches:=nil;//SetLength(FMatches,0); FFolders:=0; end; procedure TDirFindFolderNode.IncMatches(const vals:array of integer); var k,l:integer; s:string; begin inc(FMatchingFiles); k:=Length(FMatches); l:=Length(vals); if k<l then begin SetLength(FMatches,l); while k<l do begin FMatches[k]:=0; inc(k); end; end; for k:=0 to l-1 do inc(FMatches[k],vals[k]); //case FCountMatches of if (Length(FMatches)=0) or ((Length(FMatches)=1) and (FMatches[0]=FMatchingFiles)) then s:=FolderName+NodeTextSeparator+IntToStr(FMatchingFiles) else begin s:=FolderName+NodeTextSeparator+IntToStr(FMatchingFiles); if Length(FMatches)>3 then begin s:=s+NodeTextMatchCount+IntToStr(FMatches[0]); for k:=1 to l-1 do s:=s+NodeTextSubMatchCount+IntToStr(k)+'='+IntToStr(FMatches[k]); end else for k:=0 to l-1 do s:=s+NodeTextMatchCount+IntToStr(FMatches[k]); end; Text:=s; end; function TDirFindFolderNode.ProgressText: string; begin Result:=FolderPath; end; function TDirFindFolderNode.FolderPath: string; var tn:TTreeNode; begin tn:=Self; Result:=''; while tn is TDirFindFolderNode do begin Result:=(tn as TDirFindFolderNode).FolderName+Result; tn:=tn.Parent; end; Result:=(tn as TDirFinderNode).RootPath+Result;//+NodeTextSeparator+IntToStr? end; procedure TDirFindFolderNode.SetPrioFolder; var tn:TTreeNode; s:string; begin tn:=Self; s:=''; while (tn<>nil) and (tn is TDirFindFolderNode) do begin s:=(tn as TDirFindFolderNode).FolderName+s; tn:=tn.Parent; end; if (tn as TDirFinderNode).FDirFinder<>nil then (tn as TDirFinderNode).FDirFinder.PrioFolder:=s; end; { TDirFindMatchNode } procedure TDirFindMatchNode.AfterConstruction; begin inherited; //FFilePath:=//? see where created FMatchingLinesLoaded:=false; FLines:=-1;//see DoDblClick end; function TDirFindMatchNode.ProgressText: string; begin Result:=FFilePath;//TODO: file size? last modified date? end; procedure TDirFindMatchNode.DoDblClick; var re:RegExp; mc:MatchCollection; m1:Match; i,j,l,k,m,n:integer; w,w1:WideString; tn:TTreeNode; enc:TFileEncoding; begin if not(FMatchingLinesLoaded) then begin w:=FileAsWideString(FilePath,enc); tn:=Self; while not(tn is TDirFinderNode) do tn:=tn.Parent; re:=CoRegExp.Create; re.Pattern:=(tn as TDirFinderNode).FPattern; re.IgnoreCase:=(tn as TDirFinderNode).FIgnoreCase; re.Multiline:=(tn as TDirFinderNode).FMultiLine; re.Global:=true; mc:=re.Execute(w) as MatchCollection; //first match n:=0; if mc.Count=0 then m1:=nil else m1:=mc.Item[0] as Match; DirFindNextNodeClass:=TDirFindLineNode; Owner.BeginUpdate; try i:=1; k:=1; l:=Length(w); while i<=l do begin j:=i; while (j<=l) and (w[j]<>#13) and (w[j]<>#10) do inc(j); if (m1<>nil) and (m1.FirstIndex>=i-1) and (m1.FirstIndex<j-1) then begin //show line w1:=Copy(w,i,j-i);//TODO: expand tabs m:=IndentLevel(w1); tn:=Owner.AddChild(Self,Format('%.6d',[k])+NodeTextSeparator+w1); tn.ImageIndex:=iiLineMatch; tn.SelectedIndex:=iiLineMatch; (tn as TDirFindLineNode).FLineNumber:=k; (tn as TDirFindLineNode).FIndentLevel:=m; //next match while (m1<>nil) and (m1.FirstIndex<j-1) do begin inc(n); if mc.Count=n then m1:=nil else m1:=mc.Item[n] as Match; end; end; if (j<l) and (w[j]=#13) and (w[j+1]=#10) then inc(j); i:=j+1; inc(k); end; FLines:=k-1;//for TDirFindLineNode.DoDblClick iiLineNeighboursLoaded Expand(false); finally Owner.EndUpdate; end; FMatchingLinesLoaded:=true; end; end; { TDirFindLineNode } procedure TDirFindLineNode.DoDblClick; const IndentSeekMax=128; var i,j,k,l,m:integer; w,w1:WideString; tn:TTreeNode; s:string; MaxLineIndentLevel:array[0..IndentSeekMax-1] of record LineNumber,IndentLevel:integer; LineText:WideString; end; procedure AddLine; begin tn:=Self; if (k<FLineNumber) then while (tn<>nil) and ((tn as TDirFindLineNode).FLineNumber>k) do tn:=tn.getPrevSibling else while (tn<>nil) and ((tn as TDirFindLineNode).FLineNumber<k) do tn:=tn.getNextSibling; if (tn=nil) or ((tn as TDirFindLineNode).FLineNumber<>k) then begin s:=Format('%.6d',[k])+NodeTextSeparator+w1; if k<FLineNumber then if tn=nil then tn:=Owner.AddChildFirst(Self.parent,s) else tn:=Owner.Insert(tn.getNextSibling,s) else if tn=nil then tn:=Owner.AddChild(Parent,s) else tn:=Owner.Insert(tn,s); tn.ImageIndex:=iiLine; tn.SelectedIndex:=iiLine; (tn as TDirFindLineNode).FLineNumber:=k; (tn as TDirFindLineNode).FIndentLevel:=m; end; end; var enc:TFileEncoding; begin for i:=0 to IndentSeekMax-1 do MaxLineIndentLevel[i].LineNumber:=-1; w:=FileAsWideString((Parent as TDirFindMatchNode).FilePath,enc); tn:=Self; while not(tn is TDirFinderNode) do tn:=tn.Parent; DirFindNextNodeClass:=TDirFindLineNode; Owner.BeginUpdate; try //find lines i:=1; k:=1; l:=Length(w); while i<=l do begin j:=i; while (j<=l) and (w[j]<>#13) and (w[j]<>#10) do inc(j); w1:=Copy(w,i,j-i);//TODO: expand tabs m:=IndentLevel(w1); if (k<FLineNumber) and (i<>j) then begin if (m<FIndentLevel) and (m<IndentSeekMax) then begin MaxLineIndentLevel[m].LineNumber:=k; MaxLineIndentLevel[m].IndentLevel:=m; MaxLineIndentLevel[m].LineText:=w1; end; end; if ((k>=FLineNumber-5) and (k<FLineNumber)) or ((k>FLineNumber) and (k<=FLineNumber+5)) then AddLine; if (j<l) and (w[j]=#13) and (w[j+1]=#10) then inc(j); i:=j+1; inc(k); if k>FLineNumber+5 then i:=l+1;//skip remainder end; //lines of lower indent i:=0; j:=-1; while (i<FIndentLevel) and (i<IndentSeekMax) do begin if MaxLineIndentLevel[i].LineNumber>j then begin j:=MaxLineIndentLevel[i].LineNumber; m:=MaxLineIndentLevel[i].IndentLevel; w1:=MaxLineIndentLevel[i].LineText; k:=j; AddLine; end; inc(i); end; UpdateIcons; Expand(false); finally Owner.EndUpdate; end; end; procedure TDirFindLineNode.UpdateIcons; var tn0,tn1,tn2:TDirFindLineNode; ml:integer; begin ml:=(Parent as TDirFindMatchNode).Lines; tn0:=nil; tn1:=Self.Parent.getFirstChild as TDirFindLineNode; tn2:=(tn1.getNextSibling) as TDirFindLineNode; while tn1<>nil do begin if (tn1.ImageIndex=iiLine) and (((tn0=nil) and (tn1.LineNumber=1)) or ((tn0<>nil) and (tn0.LineNumber=tn1.LineNumber-1))) and (((tn2=nil) and (tn1.LineNumber>=ml)) or (((tn2<>nil) and (tn2.LineNumber=tn1.LineNumber+1)))) then begin tn1.ImageIndex:=iiLineNeighboursLoaded; tn1.SelectedIndex:=iiLineNeighboursLoaded; end; tn0:=tn1; tn1:=tn2; if tn2<>nil then tn2:=(tn2.getNextSibling) as TDirFindLineNode; end; end; initialization IndentLevelTabSize:=4;//default end.
unit HTMLColors; interface {$I mxs.inc} uses SysUtils, Windows, Graphics; function ColorToHex(Color: TColor): string; function GetWebSafe(C: TColor): TColor; implementation //------------------------------------------------------------------------------ //converts a TColor value to a hex value function ColorToHex(Color: TColor): string; begin if Color <> $0 then Result := IntToHex(GetRValue(Color), 2) + IntToHex(GetGValue(Color), 2) + IntToHex(GetBValue(Color), 2) else Result := '000000'; end; //------------------------------------------------------------------------------ //returns the closest web safe color to the one given function GetWebSafe(C: TColor): TColor; begin result := C; //Result := RGB(WS[GetRValue(C)], WS[GetGValue(C)], WS[GetBValue(C)]); end; //------------------------------------------------------------------------------ end.
unit CFOPCorrespondente; interface uses SysUtils, Contnrs; type TCFOPCorrespondente = class private Fcod_CFOP_Saida: integer; Fcod_CFOP_Entrada: integer; Fcodigo: integer; Fcfop_saida: String; Fcfop_entrada: String; procedure Setcod_CFOP_Entrada(const Value: integer); procedure Setcod_CFOP_Saida(const Value: integer); procedure Setcodigo(const Value: integer); procedure Setcfop_entrada(const Value: String); procedure Setcfop_saida(const Value: String); public property codigo :integer read Fcodigo write Setcodigo; property cod_CFOP_Saida :integer read Fcod_CFOP_Saida write Setcod_CFOP_Saida; property cfop_saida :String read Fcfop_saida write Setcfop_saida; property cod_CFOP_Entrada :integer read Fcod_CFOP_Entrada write Setcod_CFOP_Entrada; property cfop_entrada :String read Fcfop_entrada write Setcfop_entrada; end; implementation { TCFOPCorrespondente } procedure TCFOPCorrespondente.Setcod_CFOP_Entrada(const Value: integer); begin Fcod_CFOP_Entrada := Value; end; procedure TCFOPCorrespondente.Setcod_CFOP_Saida(const Value: integer); begin Fcod_CFOP_Saida := Value; end; procedure TCFOPCorrespondente.Setcodigo(const Value: integer); begin Fcodigo := Value; end; procedure TCFOPCorrespondente.Setcfop_entrada(const Value: String); begin Fcfop_entrada := Value; end; procedure TCFOPCorrespondente.Setcfop_saida(const Value: String); begin Fcfop_saida := Value; end; end.
unit uDataSetConvertJson; interface uses System.SysUtils, System.Classes, Data.DB, System.json; type TDataSetConvertJson = class private { Private declarations } class function toJson(const dataSet: TDataSet; jsonObj: TJSONObject; logs: TStrings = nil ): string; overload; public { Public declarations } class function convert(const dataSet: TDataSet; const useData: boolean; logs: TStrings = nil ): string; overload; end; implementation class function TDataSetConvertJson.toJson(const dataSet: TDataSet; jsonObj: TJSONObject; logs: TStrings): string; {ftUnknown, ftString, ftSmallint, ftInteger, ftWord, // 0..4 ftBoolean, ftFloat, ftCurrency, ftBCD, ftDate, ftTime, ftDateTime, // 5..11 ftBytes, ftVarBytes, ftAutoInc, ftBlob, ftMemo, ftGraphic, ftFmtMemo, // 12..18 ftParadoxOle, ftDBaseOle, ftTypedBinary, ftCursor, ftFixedChar, ftWideString, // 19..24 ftLargeint, ftADT, ftArray, ftReference, ftDataSet, ftOraBlob, ftOraClob, // 25..31 ftVariant, ftInterface, ftIDispatch, ftGuid, ftTimeStamp, ftFMTBcd, // 32..37 ftFixedWideChar, ftWideMemo, ftOraTimeStamp, ftOraInterval, // 38..41 ftLongWord, ftShortint, ftByte, ftExtended, ftConnection, ftParams, ftStream, //42..48 ftTimeStampOffset, ftObject, ftSingle} //0: string, 1:number, 2: datetime; {function isNumber(const ft: TFieldType): TJSONValue; begin if ft in [ftString] then begin end else if ft in [] then begin end; end;} function getJsonVal(const fld: TField): TJSONValue; var fieldName: string; dt: TFieldType; begin fieldName := fld.FieldName; dt := fld.DataType; if dt in [ftString, ftMemo, ftFmtMemo, ftFixedChar, ftWideString, ftFixedWideChar, ftWideMemo] then begin Result := TJSONString.Create(fld.value); end else if dt in [ftSmallint, ftInteger, ftWord, ftBytes, ftVarBytes, ftAutoInc, ftLargeint, ftLongWord, ftShortint, ftByte] then begin Result := TJSONNumber.Create(fld.AsLargeInt); end else if dt in [ftFloat, ftCurrency, ftBCD, ftADT, ftSingle] then begin Result := TJSONNumber.Create(fld.value); end else if dt in [ftDate, ftTime, ftDateTime, ftTimeStamp] then begin Result := TJSONString.Create( formatDateTime('yyyy-mm-dd hh:nn:ss', fld.value)); end else begin Result := TJSONString.Create(fld.value); end; end; procedure rowToJson(jsonObj: TJSONObject); var J: integer; fld: TField; begin for J := 0 to dataSet.FieldCount - 1 do begin //jsonVal.AddPair() fld := dataSet.Fields[J]; if assigned(logs) then begin logs.Add(fld.FieldName + ': ' + IntToStr( Integer(fld.DataType) ) ); end; if fld.IsNull then begin jsonObj.AddPair(fld.FieldName, TJSONNull.Create); continue; end; jsonObj.AddPair(fld.FieldName, getJsonVal(fld)); end; end; procedure rowsToJson(jsonObj: TJSONObject); var jsonArr: TJSONArray; jo: TJSONObject; begin jsonArr := TJSONArray.Create(); try dataSet.First; while not dataSet.Eof do begin jo := TJSONObject.Create; rowToJson(jo); jsonArr.AddElement(jo); dataSet.Next; end; jsonObj.AddPair('data', jsonArr); finally //jsonArr.Free; end; end; begin if dataSet.RecordCount=1 then begin rowToJson(jsonObj); end else begin rowsToJson(jsonObj); end; end; class function TDataSetConvertJson.convert(const dataSet: TDataSet; const useData: boolean; logs: TStrings): string; function getData(const jsonData: TJSONObject): TJSONObject; var jsonObj: TJSONObject; begin jsonObj := TJSONObject.Create; jsonObj.AddPair('state', TJSONNumber.Create(0)); jsonObj.AddPair('msg', TJSONString.Create('')); jsonObj.AddPair('data', jsonData); Result := jsonObj; end; var jsonObj: TJSONObject; begin if dataSet.Active = false then begin exit; end; jsonObj := TJSONObject.Create; try toJson(dataSet, jsonObj, logs); if useData then begin Result := getData(jsonObj).ToString; end else begin Result := jsonObj.ToString; end; finally jsonObj.Free; end; 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 ContentBuffer; interface uses FileUnit, OutputStream, InputStream; type TContentBuffer = class private outputStream : TOutputStream; size : integer; tempFile : TFile; opened : boolean; procedure open(); // function append(const bytes) : TContentBuffer; overload; procedure close(); public constructor Create; overload; constructor Create(ext : string); overload; destructor Destroy; override; function getSize() : Integer; function getInputStream() : TInputStream; function getNonDeleteingInputStream() : TInputStream; function getOutputStream() : TOutputStream; function getFile() : TFile; procedure delete(); function append(value : string) : TContentBuffer; overload; function getContent() : string; end; implementation uses FileInputStream, FileOutputStream, classes, FileUtil; type TDeleteFileInputStream = class(TFileInputStream) public tempFile : TFile; procedure close(); override; end; procedure TDeleteFileInputStream.close(); begin inherited close(); tempFile.delete(); end; constructor TContentBuffer.Create(ext : string); begin inherited Create; tempFile := TFile.createTempFile('FitNesse-', ext); end; constructor TContentBuffer.Create(); begin Create('.tmp'); end; destructor TContentBuffer.Destroy(); begin delete(); inherited Destroy; end; procedure TContentBuffer.open(); begin if (not opened) then begin outputStream := TFileOutputStream.Create(tempFile, true); opened := true; end; end; function TContentBuffer.append(value : string) : TContentBuffer; //var // bytes : byte; begin // bytes:=value.getBytes('UTF-8'); //TODO result := append(value); open(); Inc(size, Length(value)); outputStream.write(value); result := self; end; { function TContentBuffer.append(const bytes): TContentBuffer; begin open(); Inc(size, Length(bytes)); outputStream.write(bytes); result := self; end; } procedure TContentBuffer.close(); begin if (opened) then begin outputStream.close(); opened := false; end; end; function TContentBuffer.getContent() : string; begin close(); result := TFileUtil.getFileContent(tempFile.FileName); end; function TContentBuffer.getSize() : Integer; begin close(); result := size; end; function TContentBuffer.getInputStream() : TInputStream; begin close(); Result := TDeleteFileInputStream.Create(tempFile); end; function TContentBuffer.getNonDeleteingInputStream() : TInputStream; begin close(); Result := TFileInputStream.Create(tempFile); end; function TContentBuffer.getOutputStream() : TOutputStream; begin result := outputStream; end; function TContentBuffer.getFile() : TFile; begin result := tempFile; end; procedure TContentBuffer.delete(); begin tempFile.delete(); end; end.
program OhmsLaw(input, output); uses wincrt; var ConvertTo : integer; Input1, Input2 : real; function Amps(Volts, Ohms : real) : real; begin Amps := Volts / Ohms; end; function Volts(Amps, Ohms : real) : real; begin Volts := Amps * Ohms; end; function Ohms(Amps, Volts : real) : real; begin Ohms := Amps * Volts; end; begin writeln('What unit would you like to convert to?'); writeln; writeln('1) Amps'); writeln('2) Volts'); writeln('3) Ohms'); readln(ConvertTo); clrscr; {Get the two inputs} Case ConvertTo of 1: writeln('Enter the Volts, and Ohms'); 2: writeln('Enter the Ampts, and Ohms'); 3: writeln('Enter your Amps, and Volts'); end; readln(Input1, Input2); clrscr; {Print output} Case ConvertTo of 1: writeln(Amps(Input1, Input2):1:2); 2: writeln(Volts(Input1, Input2):1:2); 3: writeln(Ohms(Input1, Input2):1:2); end; readln; donewincrt; end. {Ohm's Law} {Kaleb Haslam}
unit uMainForm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.ListView.Types, FMX.ListView.Appearances, FMX.ListView.Adapters.Base, FMX.TabControl, System.Actions, FMX.ActnList, FMX.StdCtrls, FMX.ListView, FMX.Edit, FMX.Layouts, FMX.ListBox, FMX.Objects, FMX.Controls.Presentation, Data.Bind.EngExt, FMX.Bind.DBEngExt, System.Rtti, System.Bindings.Outputs, FMX.Bind.GenData, Data.Bind.GenData, Data.Bind.Components, Data.Bind.ObjectScope, FMX.Bind.Editors, FMX.Ani, Data.Bind.DBScope; type TMainForm = class(TForm) ToolBar1: TToolBar; imgLogo: TImage; Label1: TLabel; TabControl1: TTabControl; tabLogin: TTabItem; LayoutLogin: TLayout; edtPassword: TEdit; PasswordEditButton1: TPasswordEditButton; edtUsername: TEdit; ClearEditButton1: TClearEditButton; tabCases: TTabItem; StyleBook1: TStyleBook; ActionList1: TActionList; actLogin: TAction; NextTabAction1: TNextTabAction; PreviousTabAction1: TPreviousTabAction; lstCases: TListView; RectAnimation1: TRectAnimation; tabDetails: TTabItem; lstDetails: TListBox; StatusBar1: TStatusBar; labelLoggedInUser: TLabel; butGoBack: TSpeedButton; BindSourceDB1: TBindSourceDB; BindingsList1: TBindingsList; LinkFillControlToField1: TLinkFillControlToField; edtServerIP: TEdit; ClearEditButton2: TClearEditButton; butLogin: TButton; procedure actLoginExecute(Sender: TObject); procedure edtUsernameChangeTracking(Sender: TObject); procedure edtPasswordChangeTracking(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); procedure FormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); procedure FormShow(Sender: TObject); procedure lstCasesUpdateObjects(const Sender: TObject; const AItem: TListViewItem); procedure lstCasesItemClickEx(const Sender: TObject; ItemIndex: Integer; const LocalClickPos: TPointF; const ItemObject: TListItemDrawable); procedure edtServerIPChangeTracking(Sender: TObject); private { Private declarations } procedure BuildDetailScreen; public { Public declarations } end; var MainForm: TMainForm; implementation {$R *.fmx} {$R *.LgXhdpiPh.fmx ANDROID} {$R *.iPhone55in.fmx IOS} uses FMX.VirtualKeyboard, FMX.Platform, FMX.DialogService, uMainDM; procedure TMainForm.actLoginExecute(Sender: TObject); begin MainDM.ServerIP := edtServerIP.Text; MainDM.UserName := edtUsername.Text; MainDM.Password := edtPassword.Text; try LayoutLogin.Enabled := False; if MainDM.UserLogin then begin MainDM.LoadSFCases; NextTabAction1.ExecuteTarget(nil); labelLoggedInUser.Text := 'User: ' + edtUsername.Text; end else begin edtPassword.SetFocus; edtPassword.Text := ''; labelLoggedInUser.Text := 'Invalid user/pass combination!'; end; finally LayoutLogin.Enabled := True; end; end; procedure TMainForm.BuildDetailScreen; var i: Integer; ListBoxEdit: TEdit; ListBoxItem: TListBoxItem; ListBoxGroupHeader: TListBoxGroupHeader; begin lstDetails.BeginUpdate; try lstDetails.Items.Clear; ListBoxGroupHeader := TListBoxGroupHeader.Create(lstDetails); ListBoxGroupHeader.Text := 'Case Details'; lstDetails.AddObject(ListBoxGroupHeader); for i := 0 to MainDM.CaseMemTable.Fields.Count - 1 do begin ListBoxItem := TListBoxItem.Create(lstDetails); ListBoxItem.ItemData.Text := MainDM.CaseMemTable.Fields[i].FieldName; ListBoxEdit := TEdit.Create(ListBoxItem); ListBoxEdit.Align := TAlignLayout.VertCenter; ListBoxEdit.Margins.Left := 180; ListBoxEdit.Margins.Right := 05; ListBoxEdit.Font.Size := 10; ListBoxEdit.StyledSettings := ListBoxEdit.StyledSettings - [TStyledSetting.Size]; ListBoxEdit.Text := MainDM.CaseMemTable.Fields[i].AsString; ListBoxEdit.ReadOnly := True; ListBoxItem.AddObject(ListBoxEdit); lstDetails.AddObject(ListBoxItem); end; finally lstDetails.EndUpdate; end; end; procedure TMainForm.edtPasswordChangeTracking(Sender: TObject); begin actLogin.Enabled := (edtUsername.Text.Length >= 3) and (edtPassword.Text.Length >= 3) and (edtServerIP.Text.Length >= 3); end; procedure TMainForm.edtServerIPChangeTracking(Sender: TObject); begin actLogin.Enabled := (edtUsername.Text.Length >= 3) and (edtPassword.Text.Length >= 3) and (edtServerIP.Text.Length >= 3); end; procedure TMainForm.edtUsernameChangeTracking(Sender: TObject); begin actLogin.Enabled := (edtUsername.Text.Length >= 3) and (edtPassword.Text.Length >= 3) and (edtServerIP.Text.Length >= 3); end; procedure TMainForm.FormKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin if Key = vkReturn then begin Key := vkTab; KeyDown(Key, KeyChar, Shift); end; end; procedure TMainForm.FormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); var FService: IFMXVirtualKeyboardService; begin if Key = vkHardwareBack then begin TPlatformServices.Current.SupportsPlatformService (IFMXVirtualKeyboardService, IInterface(FService)); if (FService <> nil) and (TVirtualKeyboardState.Visible in FService.VirtualKeyBoardState) then begin // do nothing... end else begin if TabControl1.TabIndex = 0 then begin Key := 0; TDialogService.MessageDialog('Close the application?', TMsgDlgType.mtConfirmation, [TMsgDlgBtn.mbNo, TMsgDlgBtn.mbYes], TMsgDlgBtn.mbYes, 0, procedure(const AResult: TModalResult) begin case AResult of mrYES: begin Application.Terminate; end; end; end); end else begin Key := 0; PreviousTabAction1.ExecuteTarget(Self); end; end; end; end; procedure TMainForm.FormShow(Sender: TObject); begin edtUsername.Text := MainDM.UserName; edtServerIP.Text := MainDM.ServerIP; TabControl1.ActiveTab := tabLogin; {$IFDEF ANDROID} butGoBack.Visible := False; {$ENDIF} end; procedure TMainForm.lstCasesItemClickEx(const Sender: TObject; ItemIndex: Integer; const LocalClickPos: TPointF; const ItemObject: TListItemDrawable); begin if ItemObject.Name = 'butDetails' then begin BuildDetailScreen; NextTabAction1.ExecuteTarget(nil); end; end; procedure TMainForm.lstCasesUpdateObjects(const Sender: TObject; const AItem: TListViewItem); var UsedSpace: Single; AvailableWidth: Single; Drawable: TListItemText; begin if TListView(Sender).EditMode = False then begin AvailableWidth := TListView(Sender).Width - TListView(Sender) .ItemSpaces.Left - TListView(Sender).ItemSpaces.Right - 15; Drawable := TListItemText(AItem.View.FindDrawable('butDetails')); Drawable.PlaceOffset.X := AvailableWidth - Drawable.Width; AvailableWidth := AvailableWidth - Drawable.Width + 5; Drawable := TListItemText(AItem.View.FindDrawable('txtSubject')); Drawable.Width := AvailableWidth; Drawable.PlaceOffset.X := 0; Drawable := TListItemText(AItem.View.FindDrawable('txtPriority')); Drawable.Width := ((AvailableWidth - 15) / 4); Drawable.PlaceOffset.X := AvailableWidth - Drawable.Width; UsedSpace := Drawable.Width + 5; Drawable := TListItemText(AItem.View.FindDrawable('txtUpdated')); Drawable.Width := ((AvailableWidth - 15) / 4); Drawable.PlaceOffset.X := AvailableWidth - Drawable.Width - UsedSpace; UsedSpace := UsedSpace + Drawable.Width + 5; Drawable := TListItemText(AItem.View.FindDrawable('txtCreated')); Drawable.Width := ((AvailableWidth - 15) / 4); Drawable.PlaceOffset.X := AvailableWidth - Drawable.Width - UsedSpace; UsedSpace := UsedSpace + Drawable.Width + 5; Drawable := TListItemText(AItem.View.FindDrawable('txtCaseNumber')); Drawable.Width := ((AvailableWidth - 15) / 4); Drawable.PlaceOffset.X := AvailableWidth - Drawable.Width - UsedSpace; end; end; end.
unit UXMLSub; (* Copyright (c) 2001,2002 Twiddle <hetareprog@hotmail.com> *) (* 自分が書いたのを読むだけなので、あくまで簡易 *) interface uses Classes, StrUtils, UUngetStream; type (*-------------------------------------------------------*) TXMLElementType = (xmleELEMENT, xmleTEXT, xmleENTITY); TXMLElement = class(TList) protected function GetItems(index: integer): TXMLElement; procedure SetItems(index: integer; elem: TXMLElement); public elementType: TXMLElementType; text: string; attrib: TStringList; constructor Create(elmType: TXMLElementType; name: string); destructor Destroy; override; procedure Clear; override; property Items[index:integer]: TXMLElement read GetItems write SetItems; default; end; (*-------------------------------------------------------*) TXMLDoc = class(TXMLElement) protected // FElements: TList; public constructor Create; destructor Destroy; override; procedure Clear; override; procedure LoadFromStream(stream: TStream); end; function XMLQuoteEncode(const str: string): string; (*=======================================================*) implementation (*=======================================================*) const TokenChars = ['0'..'9','A'..'Z',':','a'..'z','_','!','-']; function XMLQuoteEncode(const str: string): string; var i: integer; begin result := ''; for i := 1 to length(str) do begin case str[i] of '"': result := result + '&quot;'; '&': result := result + '&amp;'; else result := result + str[i]; end; end; end; (*=======================================================*) constructor TXMLElement.Create(elmType: TXMLElementType; name: string); begin inherited Create; elementType := elmType; text := name; attrib := TStringList.Create; end; destructor TXMLElement.Destroy; begin Clear; attrib.Free; inherited; end; procedure TXMLElement.Clear; var i: Integer; begin for i := 0 to Count -1 do TXMLElement(Items[i]).Free; inherited; end; function TXMLELement.GetItems(index: integer): TXMLElement; begin result := inherited Items[index]; end; procedure TXMLELement.SetItems(index: integer; elem: TXMLElement); begin inherited Items[index] := elem; end; (*=======================================================*) constructor TXMLDoc.Create; begin inherited Create(xmleELEMENT, ''); // FElements := TList.Create; end; destructor TXMLDoc.Destroy; begin Clear; inherited; end; procedure TXMLDoc.Clear; begin // FElements.Clear; inherited; end; procedure TXMLDoc.LoadFromStream(stream: TStream); var input: TUngetStream; text: string; el: TXMLElement; c: Char; function GetChar: Char; var buf: Char; begin input.ReadBuffer(buf, 1); result := buf; end; procedure FlushText(elem: TXMLElement); begin if (0 < length(text)) then begin elem.Add(TXMLElement.Create(xmleTEXT, text)); text := ''; end; end; function GetName: string; begin result := ''; while true do begin c := GetChar; if c in TokenChars then result := result + c else begin input.Unget(c); break; end; // case c of // '0'..'9','A'..'Z',':','a'..'z','_','!','-': result := result + c; // else begin input.Unget(c); break; end; // end; end; end; procedure SkipSpaces; begin while true do begin c := GetChar; if not (c in [#0..#$20]) then begin input.Unget(c); break; end; end; end; procedure SkipComment; var s: string; begin s := ''; while length(s) < 3 do s := s + GetChar; while true do begin if s = '-->' then exit; s := Copy(s, 1, 2) + GetChar; end; end; function GetEntity: string; begin result := ''; while true do begin c := GetChar; case c of #$0..#$20,';': break; else result := result + c; end; end; if result = 'quot' then result := '"' else if result = 'amp' then result := '&' else result := '&' + result + c; end; function GetValue: string; begin result := ''; c := GetChar; if c = '"' then begin while true do begin c := GetChar; case c of '"': break; '&': result := result + GetEntity; else result := result + c; end; end; end else begin result := c; while true do begin c := GetChar; case c of #0..#$20: break; '>': begin input.Unget(c); break; end; else result := result + c; end; end; end; end; procedure GetAttribute(elem: TXMLElement); var name, value: string; begin name := GetName; SkipSpaces; c := GetChar; if c <> '=' then begin input.Unget(c); exit; end; value := GetValue; elem.attrib.Add(name + '=' + value); end; procedure Parse(elem: TXMLElement); forward; function ParseTag(elem: TXMLElement): boolean; var return: boolean; begin result := false; (* 終了タグ? *) c := GetChar; if c = '/' then result := true else input.Unget(c); return := result; text := GetName; if AnsiStartsStr('!--', text) then begin text := ''; SkipComment; exit; end; if not result then begin el := TXMLElement.Create(xmleELEMENT, text); elem.Add(el); end; text := ''; (* タグ内の処理 *) while true do begin SkipSpaces; c := GetChar; case c of '/': return := true; '>': break; else if c in TokenChars then begin input.Unget(c); GetAttribute(el); end; end; end; if not return then Parse(el); end; procedure ParseEntity(elem: TXMLElement); var name: String; begin while true do begin try c := GetChar; except break; end; case c of #$0..#$20,';': break; else name := name + c; end; end; if (0 < length(name)) then begin elem.Add(TXMLElement.Create(xmleENTITY, name)); end; end; procedure Parse(elem: TXMLElement); begin while true do begin try c := GetChar; except FlushText(elem); break; end; case c of '<': begin FlushText(elem); if ParseTag(elem) then exit; end; '&': begin FlushText(elem); ParseEntity(elem); end; else begin text := text + c; end; end; end; end; begin input := TUngetStream.Create(stream); Parse(self); input.Free; 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_obj_mac; interface // Headers for OpenSSL 1.1.1 // obj_mac.h {$i IdCompilerDefines.inc} const SN_undef = AnsiString('UNDEF'); LN_undef = AnsiString('undefined'); NID_undef = 0; SN_itu_t = AnsiString('ITU-T'); LN_itu_t = AnsiString('itu-t'); NID_itu_t = 645; NID_ccitt = 404; SN_iso = AnsiString('ISO'); LN_iso = AnsiString('iso'); NID_iso = 181; SN_joint_iso_itu_t = AnsiString('JOINT-ISO-ITU-T'); LN_joint_iso_itu_t = AnsiString('joint-iso-itu-t'); NID_joint_iso_itu_t = 646; NID_joint_iso_ccitt = 393; SN_member_body = AnsiString('member-body'); LN_member_body = AnsiString('ISO Member Body'); NID_member_body = 182; SN_identified_organization = AnsiString('identified-organization'); NID_identified_organization = 676; SN_hmac_md5 = AnsiString('HMAC-MD5'); LN_hmac_md5 = AnsiString('hmac-md5'); NID_hmac_md5 = 780; SN_hmac_sha1 = AnsiString('HMAC-SHA1'); LN_hmac_sha1 = AnsiString('hmac-sha1'); NID_hmac_sha1 = 781; SN_x509ExtAdmission = AnsiString('x509ExtAdmission'); LN_x509ExtAdmission = AnsiString('Professional Information or basis for Admission'); NID_x509ExtAdmission = 1093; SN_certicom_arc = AnsiString('certicom-arc'); NID_certicom_arc = 677; SN_ieee = AnsiString('ieee'); NID_ieee = 1170; SN_ieee_siswg = AnsiString('ieee-siswg'); LN_ieee_siswg = AnsiString('IEEE Security in Storage Working Group'); NID_ieee_siswg = 1171; SN_international_organizations = AnsiString('international-organizations'); LN_international_organizations = AnsiString('International Organizations'); NID_international_organizations = 647; SN_wap = AnsiString('wap'); NID_wap = 678; SN_wap_wsg = AnsiString('wap-wsg'); NID_wap_wsg = 679; SN_selected_attribute_types = AnsiString('selected-attribute-types'); LN_selected_attribute_types = AnsiString('Selected Attribute Types'); NID_selected_attribute_types = 394; SN_clearance = AnsiString('clearance'); NID_clearance = 395; SN_ISO_US = AnsiString('ISO-US'); LN_ISO_US = AnsiString('ISO US Member Body'); NID_ISO_US = 183; SN_X9_57 = AnsiString('X9-57'); LN_X9_57 = AnsiString('X9.57'); NID_X9_57 = 184; SN_X9cm = AnsiString('X9cm'); LN_X9cm = AnsiString('X9.57 CM ?'); NID_X9cm = 185; SN_ISO_CN = AnsiString('ISO-CN'); LN_ISO_CN = AnsiString('ISO CN Member Body'); NID_ISO_CN = 1140; SN_oscca = AnsiString('oscca'); NID_oscca = 1141; SN_sm_scheme = AnsiString('sm-scheme'); NID_sm_scheme = 1142; SN_dsa = AnsiString('DSA'); LN_dsa = AnsiString('dsaEncryption'); NID_dsa = 116; SN_dsaWithSHA1 = AnsiString('DSA-SHA1'); LN_dsaWithSHA1 = AnsiString('dsaWithSHA1'); NID_dsaWithSHA1 = 113; SN_ansi_X9_62 = AnsiString('ansi-X9-62'); LN_ansi_X9_62 = AnsiString('ANSI X9.62'); NID_ansi_X9_62 = 405; SN_X9_62_prime_field = AnsiString('prime-field'); NID_X9_62_prime_field = 406; SN_X9_62_characteristic_two_field = AnsiString('characteristic-two-field'); NID_X9_62_characteristic_two_field = 407; SN_X9_62_id_characteristic_two_basis = AnsiString('id-characteristic-two-basis'); NID_X9_62_id_characteristic_two_basis = 680; SN_X9_62_onBasis = AnsiString('onBasis'); NID_X9_62_onBasis = 681; SN_X9_62_tpBasis = AnsiString('tpBasis'); NID_X9_62_tpBasis = 682; SN_X9_62_ppBasis = AnsiString('ppBasis'); NID_X9_62_ppBasis = 683; SN_X9_62_id_ecPublicKey = AnsiString('id-ecPublicKey'); NID_X9_62_id_ecPublicKey = 408; SN_X9_62_c2pnb163v1 = AnsiString('c2pnb163v1'); NID_X9_62_c2pnb163v1 = 684; SN_X9_62_c2pnb163v2 = AnsiString('c2pnb163v2'); NID_X9_62_c2pnb163v2 = 685; SN_X9_62_c2pnb163v3 = AnsiString('c2pnb163v3'); NID_X9_62_c2pnb163v3 = 686; SN_X9_62_c2pnb176v1 = AnsiString('c2pnb176v1'); NID_X9_62_c2pnb176v1 = 687; SN_X9_62_c2tnb191v1 = AnsiString('c2tnb191v1'); NID_X9_62_c2tnb191v1 = 688; SN_X9_62_c2tnb191v2 = AnsiString('c2tnb191v2'); NID_X9_62_c2tnb191v2 = 689; SN_X9_62_c2tnb191v3 = AnsiString('c2tnb191v3'); NID_X9_62_c2tnb191v3 = 690; SN_X9_62_c2onb191v4 = AnsiString('c2onb191v4'); NID_X9_62_c2onb191v4 = 691; SN_X9_62_c2onb191v5 = AnsiString('c2onb191v5'); NID_X9_62_c2onb191v5 = 692; SN_X9_62_c2pnb208w1 = AnsiString('c2pnb208w1'); NID_X9_62_c2pnb208w1 = 693; SN_X9_62_c2tnb239v1 = AnsiString('c2tnb239v1'); NID_X9_62_c2tnb239v1 = 694; SN_X9_62_c2tnb239v2 = AnsiString('c2tnb239v2'); NID_X9_62_c2tnb239v2 = 695; SN_X9_62_c2tnb239v3 = AnsiString('c2tnb239v3'); NID_X9_62_c2tnb239v3 = 696; SN_X9_62_c2onb239v4 = AnsiString('c2onb239v4'); NID_X9_62_c2onb239v4 = 697; SN_X9_62_c2onb239v5 = AnsiString('c2onb239v5'); NID_X9_62_c2onb239v5 = 698; SN_X9_62_c2pnb272w1 = AnsiString('c2pnb272w1'); NID_X9_62_c2pnb272w1 = 699; SN_X9_62_c2pnb304w1 = AnsiString('c2pnb304w1'); NID_X9_62_c2pnb304w1 = 700; SN_X9_62_c2tnb359v1 = AnsiString('c2tnb359v1'); NID_X9_62_c2tnb359v1 = 701; SN_X9_62_c2pnb368w1 = AnsiString('c2pnb368w1'); NID_X9_62_c2pnb368w1 = 702; SN_X9_62_c2tnb431r1 = AnsiString('c2tnb431r1'); NID_X9_62_c2tnb431r1 = 703; SN_X9_62_prime192v1 = AnsiString('prime192v1'); NID_X9_62_prime192v1 = 409; SN_X9_62_prime192v2 = AnsiString('prime192v2'); NID_X9_62_prime192v2 = 410; SN_X9_62_prime192v3 = AnsiString('prime192v3'); NID_X9_62_prime192v3 = 411; SN_X9_62_prime239v1 = AnsiString('prime239v1'); NID_X9_62_prime239v1 = 412; SN_X9_62_prime239v2 = AnsiString('prime239v2'); NID_X9_62_prime239v2 = 413; SN_X9_62_prime239v3 = AnsiString('prime239v3'); NID_X9_62_prime239v3 = 414; SN_X9_62_prime256v1 = AnsiString('prime256v1'); NID_X9_62_prime256v1 = 415; SN_ecdsa_with_SHA1 = AnsiString('ecdsa-with-SHA1'); NID_ecdsa_with_SHA1 = 416; SN_ecdsa_with_Recommended = AnsiString('ecdsa-with-Recommended'); NID_ecdsa_with_Recommended = 791; SN_ecdsa_with_Specified = AnsiString('ecdsa-with-Specified'); NID_ecdsa_with_Specified = 792; SN_ecdsa_with_SHA224 = AnsiString('ecdsa-with-SHA224'); NID_ecdsa_with_SHA224 = 793; SN_ecdsa_with_SHA256 = AnsiString('ecdsa-with-SHA256'); NID_ecdsa_with_SHA256 = 794; SN_ecdsa_with_SHA384 = AnsiString('ecdsa-with-SHA384'); NID_ecdsa_with_SHA384 = 795; SN_ecdsa_with_SHA512 = AnsiString('ecdsa-with-SHA512'); NID_ecdsa_with_SHA512 = 796; SN_secp112r1 = AnsiString('secp112r1'); NID_secp112r1 = 704; SN_secp112r2 = AnsiString('secp112r2'); NID_secp112r2 = 705; SN_secp128r1 = AnsiString('secp128r1'); NID_secp128r1 = 706; SN_secp128r2 = AnsiString('secp128r2'); NID_secp128r2 = 707; SN_secp160k1 = AnsiString('secp160k1'); NID_secp160k1 = 708; SN_secp160r1 = AnsiString('secp160r1'); NID_secp160r1 = 709; SN_secp160r2 = AnsiString('secp160r2'); NID_secp160r2 = 710; SN_secp192k1 = AnsiString('secp192k1'); NID_secp192k1 = 711; SN_secp224k1 = AnsiString('secp224k1'); NID_secp224k1 = 712; SN_secp224r1 = AnsiString('secp224r1'); NID_secp224r1 = 713; SN_secp256k1 = AnsiString('secp256k1'); NID_secp256k1 = 714; SN_secp384r1 = AnsiString('secp384r1'); NID_secp384r1 = 715; SN_secp521r1 = AnsiString('secp521r1'); NID_secp521r1 = 716; SN_sect113r1 = AnsiString('sect113r1'); NID_sect113r1 = 717; SN_sect113r2 = AnsiString('sect113r2'); NID_sect113r2 = 718; SN_sect131r1 = AnsiString('sect131r1'); NID_sect131r1 = 719; SN_sect131r2 = AnsiString('sect131r2'); NID_sect131r2 = 720; SN_sect163k1 = AnsiString('sect163k1'); NID_sect163k1 = 721; SN_sect163r1 = AnsiString('sect163r1'); NID_sect163r1 = 722; SN_sect163r2 = AnsiString('sect163r2'); NID_sect163r2 = 723; SN_sect193r1 = AnsiString('sect193r1'); NID_sect193r1 = 724; SN_sect193r2 = AnsiString('sect193r2'); NID_sect193r2 = 725; SN_sect233k1 = AnsiString('sect233k1'); NID_sect233k1 = 726; SN_sect233r1 = AnsiString('sect233r1'); NID_sect233r1 = 727; SN_sect239k1 = AnsiString('sect239k1'); NID_sect239k1 = 728; SN_sect283k1 = AnsiString('sect283k1'); NID_sect283k1 = 729; SN_sect283r1 = AnsiString('sect283r1'); NID_sect283r1 = 730; SN_sect409k1 = AnsiString('sect409k1'); NID_sect409k1 = 731; SN_sect409r1 = AnsiString('sect409r1'); NID_sect409r1 = 732; SN_sect571k1 = AnsiString('sect571k1'); NID_sect571k1 = 733; SN_sect571r1 = AnsiString('sect571r1'); NID_sect571r1 = 734; SN_wap_wsg_idm_ecid_wtls1 = AnsiString('wap-wsg-idm-ecid-wtls1'); NID_wap_wsg_idm_ecid_wtls1 = 735; SN_wap_wsg_idm_ecid_wtls3 = AnsiString('wap-wsg-idm-ecid-wtls3'); NID_wap_wsg_idm_ecid_wtls3 = 736; SN_wap_wsg_idm_ecid_wtls4 = AnsiString('wap-wsg-idm-ecid-wtls4'); NID_wap_wsg_idm_ecid_wtls4 = 737; SN_wap_wsg_idm_ecid_wtls5 = AnsiString('wap-wsg-idm-ecid-wtls5'); NID_wap_wsg_idm_ecid_wtls5 = 738; SN_wap_wsg_idm_ecid_wtls6 = AnsiString('wap-wsg-idm-ecid-wtls6'); NID_wap_wsg_idm_ecid_wtls6 = 739; SN_wap_wsg_idm_ecid_wtls7 = AnsiString('wap-wsg-idm-ecid-wtls7'); NID_wap_wsg_idm_ecid_wtls7 = 740; SN_wap_wsg_idm_ecid_wtls8 = AnsiString('wap-wsg-idm-ecid-wtls8'); NID_wap_wsg_idm_ecid_wtls8 = 741; SN_wap_wsg_idm_ecid_wtls9 = AnsiString('wap-wsg-idm-ecid-wtls9'); NID_wap_wsg_idm_ecid_wtls9 = 742; SN_wap_wsg_idm_ecid_wtls10 = AnsiString('wap-wsg-idm-ecid-wtls10'); NID_wap_wsg_idm_ecid_wtls10 = 743; SN_wap_wsg_idm_ecid_wtls11 = AnsiString('wap-wsg-idm-ecid-wtls11'); NID_wap_wsg_idm_ecid_wtls11 = 744; SN_wap_wsg_idm_ecid_wtls12 = AnsiString('wap-wsg-idm-ecid-wtls12'); NID_wap_wsg_idm_ecid_wtls12 = 745; SN_cast5_cbc = AnsiString('CAST5-CBC'); LN_cast5_cbc = AnsiString('cast5-cbc'); NID_cast5_cbc = 108; SN_cast5_ecb = AnsiString('CAST5-ECB'); LN_cast5_ecb = AnsiString('cast5-ecb'); NID_cast5_ecb = 109; SN_cast5_cfb64 = AnsiString('CAST5-CFB'); LN_cast5_cfb64 = AnsiString('cast5-cfb'); NID_cast5_cfb64 = 110; SN_cast5_ofb64 = AnsiString('CAST5-OFB'); LN_cast5_ofb64 = AnsiString('cast5-ofb'); NID_cast5_ofb64 = 111; LN_pbeWithMD5AndCast5_CBC = AnsiString('pbeWithMD5AndCast5CBC'); NID_pbeWithMD5AndCast5_CBC = 112; SN_id_PasswordBasedMAC = AnsiString('id-PasswordBasedMAC'); LN_id_PasswordBasedMAC = AnsiString('password based MAC'); NID_id_PasswordBasedMAC = 782; SN_id_DHBasedMac = AnsiString('id-DHBasedMac'); LN_id_DHBasedMac = AnsiString('Diffie-Hellman based MAC'); NID_id_DHBasedMac = 783; SN_rsadsi = AnsiString('rsadsi'); LN_rsadsi = AnsiString('RSA Data Security; Inc.'); NID_rsadsi = 1; SN_pkcs = AnsiString('pkcs'); LN_pkcs = AnsiString('RSA Data Security; Inc. PKCS'); NID_pkcs = 2; SN_pkcs1 = AnsiString('pkcs1'); NID_pkcs1 = 186; LN_rsaEncryption = AnsiString('rsaEncryption'); NID_rsaEncryption = 6; SN_md2WithRSAEncryption = AnsiString('RSA-MD2'); LN_md2WithRSAEncryption = AnsiString('md2WithRSAEncryption'); NID_md2WithRSAEncryption = 7; SN_md4WithRSAEncryption = AnsiString('RSA-MD4'); LN_md4WithRSAEncryption = AnsiString('md4WithRSAEncryption'); NID_md4WithRSAEncryption = 396; SN_md5WithRSAEncryption = AnsiString('RSA-MD5'); LN_md5WithRSAEncryption = AnsiString('md5WithRSAEncryption'); NID_md5WithRSAEncryption = 8; SN_sha1WithRSAEncryption = AnsiString('RSA-SHA1'); LN_sha1WithRSAEncryption = AnsiString('sha1WithRSAEncryption'); NID_sha1WithRSAEncryption = 65; SN_rsaesOaep = AnsiString('RSAES-OAEP'); LN_rsaesOaep = AnsiString('rsaesOaep'); NID_rsaesOaep = 919; SN_mgf1 = AnsiString('MGF1'); LN_mgf1 = AnsiString('mgf1'); NID_mgf1 = 911; SN_pSpecified = AnsiString('PSPECIFIED'); LN_pSpecified = AnsiString('pSpecified'); NID_pSpecified = 935; SN_rsassaPss = AnsiString('RSASSA-PSS'); LN_rsassaPss = AnsiString('rsassaPss'); NID_rsassaPss = 912; SN_sha256WithRSAEncryption = AnsiString('RSA-SHA256'); LN_sha256WithRSAEncryption = AnsiString('sha256WithRSAEncryption'); NID_sha256WithRSAEncryption = 668; SN_sha384WithRSAEncryption = AnsiString('RSA-SHA384'); LN_sha384WithRSAEncryption = AnsiString('sha384WithRSAEncryption'); NID_sha384WithRSAEncryption = 669; SN_sha512WithRSAEncryption = AnsiString('RSA-SHA512'); LN_sha512WithRSAEncryption = AnsiString('sha512WithRSAEncryption'); NID_sha512WithRSAEncryption = 670; SN_sha224WithRSAEncryption = AnsiString('RSA-SHA224'); LN_sha224WithRSAEncryption = AnsiString('sha224WithRSAEncryption'); NID_sha224WithRSAEncryption = 671; SN_sha512_224WithRSAEncryption = AnsiString('RSA-SHA512/224'); LN_sha512_224WithRSAEncryption = AnsiString('sha512-224WithRSAEncryption'); NID_sha512_224WithRSAEncryption = 1145; SN_sha512_256WithRSAEncryption = AnsiString('RSA-SHA512/256'); LN_sha512_256WithRSAEncryption = AnsiString('sha512-256WithRSAEncryption'); NID_sha512_256WithRSAEncryption = 1146; SN_pkcs3 = AnsiString('pkcs3'); NID_pkcs3 = 27; LN_dhKeyAgreement = AnsiString('dhKeyAgreement'); NID_dhKeyAgreement = 28; SN_pkcs5 = AnsiString('pkcs5'); NID_pkcs5 = 187; SN_pbeWithMD2AndDES_CBC = AnsiString('PBE-MD2-DES'); LN_pbeWithMD2AndDES_CBC = AnsiString('pbeWithMD2AndDES-CBC'); NID_pbeWithMD2AndDES_CBC = 9; SN_pbeWithMD5AndDES_CBC = AnsiString('PBE-MD5-DES'); LN_pbeWithMD5AndDES_CBC = AnsiString('pbeWithMD5AndDES-CBC'); NID_pbeWithMD5AndDES_CBC = 10; SN_pbeWithMD2AndRC2_CBC = AnsiString('PBE-MD2-RC2-64'); LN_pbeWithMD2AndRC2_CBC = AnsiString('pbeWithMD2AndRC2-CBC'); NID_pbeWithMD2AndRC2_CBC = 168; SN_pbeWithMD5AndRC2_CBC = AnsiString('PBE-MD5-RC2-64'); LN_pbeWithMD5AndRC2_CBC = AnsiString('pbeWithMD5AndRC2-CBC'); NID_pbeWithMD5AndRC2_CBC = 169; SN_pbeWithSHA1AndDES_CBC = AnsiString('PBE-SHA1-DES'); LN_pbeWithSHA1AndDES_CBC = AnsiString('pbeWithSHA1AndDES-CBC'); NID_pbeWithSHA1AndDES_CBC = 170; SN_pbeWithSHA1AndRC2_CBC = AnsiString('PBE-SHA1-RC2-64'); LN_pbeWithSHA1AndRC2_CBC = AnsiString('pbeWithSHA1AndRC2-CBC'); NID_pbeWithSHA1AndRC2_CBC = 68; LN_id_pbkdf2 = AnsiString('PBKDF2'); NID_id_pbkdf2 = 69; LN_pbes2 = AnsiString('PBES2'); NID_pbes2 = 161; LN_pbmac1 = AnsiString('PBMAC1'); NID_pbmac1 = 162; SN_pkcs7 = AnsiString('pkcs7'); NID_pkcs7 = 20; LN_pkcs7_data = AnsiString('pkcs7-data'); NID_pkcs7_data = 21; LN_pkcs7_signed = AnsiString('pkcs7-signedData'); NID_pkcs7_signed = 22; LN_pkcs7_enveloped = AnsiString('pkcs7-envelopedData'); NID_pkcs7_enveloped = 23; LN_pkcs7_signedAndEnveloped = AnsiString('pkcs7-signedAndEnvelopedData'); NID_pkcs7_signedAndEnveloped = 24; LN_pkcs7_digest = AnsiString('pkcs7-digestData'); NID_pkcs7_digest = 25; LN_pkcs7_encrypted = AnsiString('pkcs7-encryptedData'); NID_pkcs7_encrypted = 26; SN_pkcs9 = AnsiString('pkcs9'); NID_pkcs9 = 47; LN_pkcs9_emailAddress = AnsiString('emailAddress'); NID_pkcs9_emailAddress = 48; LN_pkcs9_unstructuredName = AnsiString('unstructuredName'); NID_pkcs9_unstructuredName = 49; LN_pkcs9_contentType = AnsiString('contentType'); NID_pkcs9_contentType = 50; LN_pkcs9_messageDigest = AnsiString('messageDigest'); NID_pkcs9_messageDigest = 51; LN_pkcs9_signingTime = AnsiString('signingTime'); NID_pkcs9_signingTime = 52; LN_pkcs9_countersignature = AnsiString('countersignature'); NID_pkcs9_countersignature = 53; LN_pkcs9_challengePassword = AnsiString('challengePassword'); NID_pkcs9_challengePassword = 54; LN_pkcs9_unstructuredAddress = AnsiString('unstructuredAddress'); NID_pkcs9_unstructuredAddress = 55; LN_pkcs9_extCertAttributes = AnsiString('extendedCertificateAttributes'); NID_pkcs9_extCertAttributes = 56; SN_ext_req = AnsiString('extReq'); LN_ext_req = AnsiString('Extension Request'); NID_ext_req = 172; SN_SMIMECapabilities = AnsiString('SMIME-CAPS'); LN_SMIMECapabilities = AnsiString('S/MIME Capabilities'); NID_SMIMECapabilities = 167; SN_SMIME = AnsiString('SMIME'); LN_SMIME = AnsiString('S/MIME'); NID_SMIME = 188; SN_id_smime_mod = AnsiString('id-smime-mod'); NID_id_smime_mod = 189; SN_id_smime_ct = AnsiString('id-smime-ct'); NID_id_smime_ct = 190; SN_id_smime_aa = AnsiString('id-smime-aa'); NID_id_smime_aa = 191; SN_id_smime_alg = AnsiString('id-smime-alg'); NID_id_smime_alg = 192; SN_id_smime_cd = AnsiString('id-smime-cd'); NID_id_smime_cd = 193; SN_id_smime_spq = AnsiString('id-smime-spq'); NID_id_smime_spq = 194; SN_id_smime_cti = AnsiString('id-smime-cti'); NID_id_smime_cti = 195; SN_id_smime_mod_cms = AnsiString('id-smime-mod-cms'); NID_id_smime_mod_cms = 196; SN_id_smime_mod_ess = AnsiString('id-smime-mod-ess'); NID_id_smime_mod_ess = 197; SN_id_smime_mod_oid = AnsiString('id-smime-mod-oid'); NID_id_smime_mod_oid = 198; SN_id_smime_mod_msg_v3 = AnsiString('id-smime-mod-msg-v3'); NID_id_smime_mod_msg_v3 = 199; SN_id_smime_mod_ets_eSignature_88 = AnsiString('id-smime-mod-ets-eSignature-88'); NID_id_smime_mod_ets_eSignature_88 = 200; SN_id_smime_mod_ets_eSignature_97 = AnsiString('id-smime-mod-ets-eSignature-97'); NID_id_smime_mod_ets_eSignature_97 = 201; SN_id_smime_mod_ets_eSigPolicy_88 = AnsiString('id-smime-mod-ets-eSigPolicy-88'); NID_id_smime_mod_ets_eSigPolicy_88 = 202; SN_id_smime_mod_ets_eSigPolicy_97 = AnsiString('id-smime-mod-ets-eSigPolicy-97'); NID_id_smime_mod_ets_eSigPolicy_97 = 203; SN_id_smime_ct_receipt = AnsiString('id-smime-ct-receipt'); NID_id_smime_ct_receipt = 204; SN_id_smime_ct_authData = AnsiString('id-smime-ct-authData'); NID_id_smime_ct_authData = 205; SN_id_smime_ct_publishCert = AnsiString('id-smime-ct-publishCert'); NID_id_smime_ct_publishCert = 206; SN_id_smime_ct_TSTInfo = AnsiString('id-smime-ct-TSTInfo'); NID_id_smime_ct_TSTInfo = 207; SN_id_smime_ct_TDTInfo = AnsiString('id-smime-ct-TDTInfo'); NID_id_smime_ct_TDTInfo = 208; SN_id_smime_ct_contentInfo = AnsiString('id-smime-ct-contentInfo'); NID_id_smime_ct_contentInfo = 209; SN_id_smime_ct_DVCSRequestData = AnsiString('id-smime-ct-DVCSRequestData'); NID_id_smime_ct_DVCSRequestData = 210; SN_id_smime_ct_DVCSResponseData = AnsiString('id-smime-ct-DVCSResponseData'); NID_id_smime_ct_DVCSResponseData = 211; SN_id_smime_ct_compressedData = AnsiString('id-smime-ct-compressedData'); NID_id_smime_ct_compressedData = 786; SN_id_smime_ct_contentCollection = AnsiString('id-smime-ct-contentCollection'); NID_id_smime_ct_contentCollection = 1058; SN_id_smime_ct_authEnvelopedData = AnsiString('id-smime-ct-authEnvelopedData'); NID_id_smime_ct_authEnvelopedData = 1059; SN_id_ct_asciiTextWithCRLF = AnsiString('id-ct-asciiTextWithCRLF'); NID_id_ct_asciiTextWithCRLF = 787; SN_id_ct_xml = AnsiString('id-ct-xml'); NID_id_ct_xml = 1060; SN_id_smime_aa_receiptRequest = AnsiString('id-smime-aa-receiptRequest'); NID_id_smime_aa_receiptRequest = 212; SN_id_smime_aa_securityLabel = AnsiString('id-smime-aa-securityLabel'); NID_id_smime_aa_securityLabel = 213; SN_id_smime_aa_mlExpandHistory = AnsiString('id-smime-aa-mlExpandHistory'); NID_id_smime_aa_mlExpandHistory = 214; SN_id_smime_aa_contentHint = AnsiString('id-smime-aa-contentHint'); NID_id_smime_aa_contentHint = 215; SN_id_smime_aa_msgSigDigest = AnsiString('id-smime-aa-msgSigDigest'); NID_id_smime_aa_msgSigDigest = 216; SN_id_smime_aa_encapContentType = AnsiString('id-smime-aa-encapContentType'); NID_id_smime_aa_encapContentType = 217; SN_id_smime_aa_contentIdentifier = AnsiString('id-smime-aa-contentIdentifier'); NID_id_smime_aa_contentIdentifier = 218; SN_id_smime_aa_macValue = AnsiString('id-smime-aa-macValue'); NID_id_smime_aa_macValue = 219; SN_id_smime_aa_equivalentLabels = AnsiString('id-smime-aa-equivalentLabels'); NID_id_smime_aa_equivalentLabels = 220; SN_id_smime_aa_contentReference = AnsiString('id-smime-aa-contentReference'); NID_id_smime_aa_contentReference = 221; SN_id_smime_aa_encrypKeyPref = AnsiString('id-smime-aa-encrypKeyPref'); NID_id_smime_aa_encrypKeyPref = 222; SN_id_smime_aa_signingCertificate = AnsiString('id-smime-aa-signingCertificate'); NID_id_smime_aa_signingCertificate = 223; SN_id_smime_aa_smimeEncryptCerts = AnsiString('id-smime-aa-smimeEncryptCerts'); NID_id_smime_aa_smimeEncryptCerts = 224; SN_id_smime_aa_timeStampToken = AnsiString('id-smime-aa-timeStampToken'); NID_id_smime_aa_timeStampToken = 225; SN_id_smime_aa_ets_sigPolicyId = AnsiString('id-smime-aa-ets-sigPolicyId'); NID_id_smime_aa_ets_sigPolicyId = 226; SN_id_smime_aa_ets_commitmentType = AnsiString('id-smime-aa-ets-commitmentType'); NID_id_smime_aa_ets_commitmentType = 227; SN_id_smime_aa_ets_signerLocation = AnsiString('id-smime-aa-ets-signerLocation'); NID_id_smime_aa_ets_signerLocation = 228; SN_id_smime_aa_ets_signerAttr = AnsiString('id-smime-aa-ets-signerAttr'); NID_id_smime_aa_ets_signerAttr = 229; SN_id_smime_aa_ets_otherSigCert = AnsiString('id-smime-aa-ets-otherSigCert'); NID_id_smime_aa_ets_otherSigCert = 230; SN_id_smime_aa_ets_contentTimestamp = AnsiString('id-smime-aa-ets-contentTimestamp'); NID_id_smime_aa_ets_contentTimestamp = 231; SN_id_smime_aa_ets_CertificateRefs = AnsiString('id-smime-aa-ets-CertificateRefs'); NID_id_smime_aa_ets_CertificateRefs = 232; SN_id_smime_aa_ets_RevocationRefs = AnsiString('id-smime-aa-ets-RevocationRefs'); NID_id_smime_aa_ets_RevocationRefs = 233; SN_id_smime_aa_ets_certValues = AnsiString('id-smime-aa-ets-certValues'); NID_id_smime_aa_ets_certValues = 234; SN_id_smime_aa_ets_revocationValues = AnsiString('id-smime-aa-ets-revocationValues'); NID_id_smime_aa_ets_revocationValues = 235; SN_id_smime_aa_ets_escTimeStamp = AnsiString('id-smime-aa-ets-escTimeStamp'); NID_id_smime_aa_ets_escTimeStamp = 236; SN_id_smime_aa_ets_certCRLTimestamp = AnsiString('id-smime-aa-ets-certCRLTimestamp'); NID_id_smime_aa_ets_certCRLTimestamp = 237; SN_id_smime_aa_ets_archiveTimeStamp = AnsiString('id-smime-aa-ets-archiveTimeStamp'); NID_id_smime_aa_ets_archiveTimeStamp = 238; SN_id_smime_aa_signatureType = AnsiString('id-smime-aa-signatureType'); NID_id_smime_aa_signatureType = 239; SN_id_smime_aa_dvcs_dvc = AnsiString('id-smime-aa-dvcs-dvc'); NID_id_smime_aa_dvcs_dvc = 240; SN_id_smime_aa_signingCertificateV2 = AnsiString('id-smime-aa-signingCertificateV2'); NID_id_smime_aa_signingCertificateV2 = 1086; SN_id_smime_alg_ESDHwith3DES = AnsiString('id-smime-alg-ESDHwith3DES'); NID_id_smime_alg_ESDHwith3DES = 241; SN_id_smime_alg_ESDHwithRC2 = AnsiString('id-smime-alg-ESDHwithRC2'); NID_id_smime_alg_ESDHwithRC2 = 242; SN_id_smime_alg_3DESwrap = AnsiString('id-smime-alg-3DESwrap'); NID_id_smime_alg_3DESwrap = 243; SN_id_smime_alg_RC2wrap = AnsiString('id-smime-alg-RC2wrap'); NID_id_smime_alg_RC2wrap = 244; SN_id_smime_alg_ESDH = AnsiString('id-smime-alg-ESDH'); NID_id_smime_alg_ESDH = 245; SN_id_smime_alg_CMS3DESwrap = AnsiString('id-smime-alg-CMS3DESwrap'); NID_id_smime_alg_CMS3DESwrap = 246; SN_id_smime_alg_CMSRC2wrap = AnsiString('id-smime-alg-CMSRC2wrap'); NID_id_smime_alg_CMSRC2wrap = 247; SN_id_alg_PWRI_KEK = AnsiString('id-alg-PWRI-KEK'); NID_id_alg_PWRI_KEK = 893; SN_id_smime_cd_ldap = AnsiString('id-smime-cd-ldap'); NID_id_smime_cd_ldap = 248; SN_id_smime_spq_ets_sqt_uri = AnsiString('id-smime-spq-ets-sqt-uri'); NID_id_smime_spq_ets_sqt_uri = 249; SN_id_smime_spq_ets_sqt_unotice = AnsiString('id-smime-spq-ets-sqt-unotice'); NID_id_smime_spq_ets_sqt_unotice = 250; SN_id_smime_cti_ets_proofOfOrigin = AnsiString('id-smime-cti-ets-proofOfOrigin'); NID_id_smime_cti_ets_proofOfOrigin = 251; SN_id_smime_cti_ets_proofOfReceipt = AnsiString('id-smime-cti-ets-proofOfReceipt'); NID_id_smime_cti_ets_proofOfReceipt = 252; SN_id_smime_cti_ets_proofOfDelivery = AnsiString('id-smime-cti-ets-proofOfDelivery'); NID_id_smime_cti_ets_proofOfDelivery = 253; SN_id_smime_cti_ets_proofOfSender = AnsiString('id-smime-cti-ets-proofOfSender'); NID_id_smime_cti_ets_proofOfSender = 254; SN_id_smime_cti_ets_proofOfApproval = AnsiString('id-smime-cti-ets-proofOfApproval'); NID_id_smime_cti_ets_proofOfApproval = 255; SN_id_smime_cti_ets_proofOfCreation = AnsiString('id-smime-cti-ets-proofOfCreation'); NID_id_smime_cti_ets_proofOfCreation = 256; LN_friendlyName = AnsiString('friendlyName'); NID_friendlyName = 156; LN_localKeyID = AnsiString('localKeyID'); NID_localKeyID = 157; SN_ms_csp_name = AnsiString('CSPName'); LN_ms_csp_name = AnsiString('Microsoft CSP Name'); NID_ms_csp_name = 417; SN_LocalKeySet = AnsiString('LocalKeySet'); LN_LocalKeySet = AnsiString('Microsoft Local Key set'); NID_LocalKeySet = 856; LN_x509Certificate = AnsiString('x509Certificate'); NID_x509Certificate = 158; LN_sdsiCertificate = AnsiString('sdsiCertificate'); NID_sdsiCertificate = 159; LN_x509Crl = AnsiString('x509Crl'); NID_x509Crl = 160; SN_pbe_WithSHA1And128BitRC4 = AnsiString('PBE-SHA1-RC4-128'); LN_pbe_WithSHA1And128BitRC4 = AnsiString('pbeWithSHA1And128BitRC4'); NID_pbe_WithSHA1And128BitRC4 = 144; SN_pbe_WithSHA1And40BitRC4 = AnsiString('PBE-SHA1-RC4-40'); LN_pbe_WithSHA1And40BitRC4 = AnsiString('pbeWithSHA1And40BitRC4'); NID_pbe_WithSHA1And40BitRC4 = 145; SN_pbe_WithSHA1And3_Key_TripleDES_CBC = AnsiString('PBE-SHA1-3DES'); LN_pbe_WithSHA1And3_Key_TripleDES_CBC = AnsiString('pbeWithSHA1And3-KeyTripleDES-CBC'); NID_pbe_WithSHA1And3_Key_TripleDES_CBC = 146; SN_pbe_WithSHA1And2_Key_TripleDES_CBC = AnsiString('PBE-SHA1-2DES'); LN_pbe_WithSHA1And2_Key_TripleDES_CBC = AnsiString('pbeWithSHA1And2-KeyTripleDES-CBC'); NID_pbe_WithSHA1And2_Key_TripleDES_CBC = 147; SN_pbe_WithSHA1And128BitRC2_CBC = AnsiString('PBE-SHA1-RC2-128'); LN_pbe_WithSHA1And128BitRC2_CBC = AnsiString('pbeWithSHA1And128BitRC2-CBC'); NID_pbe_WithSHA1And128BitRC2_CBC = 148; SN_pbe_WithSHA1And40BitRC2_CBC = AnsiString('PBE-SHA1-RC2-40'); LN_pbe_WithSHA1And40BitRC2_CBC = AnsiString('pbeWithSHA1And40BitRC2-CBC'); NID_pbe_WithSHA1And40BitRC2_CBC = 149; LN_keyBag = AnsiString('keyBag'); NID_keyBag = 150; LN_pkcs8ShroudedKeyBag = AnsiString('pkcs8ShroudedKeyBag'); NID_pkcs8ShroudedKeyBag = 151; LN_certBag = AnsiString('certBag'); NID_certBag = 152; LN_crlBag = AnsiString('crlBag'); NID_crlBag = 153; LN_secretBag = AnsiString('secretBag'); NID_secretBag = 154; LN_safeContentsBag = AnsiString('safeContentsBag'); NID_safeContentsBag = 155; SN_md2 = AnsiString('MD2'); LN_md2 = AnsiString('md2'); NID_md2 = 3; SN_md4 = AnsiString('MD4'); LN_md4 = AnsiString('md4'); NID_md4 = 257; SN_md5 = AnsiString('MD5'); LN_md5 = AnsiString('md5'); NID_md5 = 4; SN_md5_sha1 = AnsiString('MD5-SHA1'); LN_md5_sha1 = AnsiString('md5-sha1'); NID_md5_sha1 = 114; LN_hmacWithMD5 = AnsiString('hmacWithMD5'); NID_hmacWithMD5 = 797; LN_hmacWithSHA1 = AnsiString('hmacWithSHA1'); NID_hmacWithSHA1 = 163; SN_sm2 = AnsiString('SM2'); LN_sm2 = AnsiString('sm2'); NID_sm2 = 1172; SN_sm3 = AnsiString('SM3'); LN_sm3 = AnsiString('sm3'); NID_sm3 = 1143; SN_sm3WithRSAEncryption = AnsiString('RSA-SM3'); LN_sm3WithRSAEncryption = AnsiString('sm3WithRSAEncryption'); NID_sm3WithRSAEncryption = 1144; LN_hmacWithSHA224 = AnsiString('hmacWithSHA224'); NID_hmacWithSHA224 = 798; LN_hmacWithSHA256 = AnsiString('hmacWithSHA256'); NID_hmacWithSHA256 = 799; LN_hmacWithSHA384 = AnsiString('hmacWithSHA384'); NID_hmacWithSHA384 = 800; LN_hmacWithSHA512 = AnsiString('hmacWithSHA512'); NID_hmacWithSHA512 = 801; LN_hmacWithSHA512_224 = AnsiString('hmacWithSHA512-224'); NID_hmacWithSHA512_224 = 1193; LN_hmacWithSHA512_256 = AnsiString('hmacWithSHA512-256'); NID_hmacWithSHA512_256 = 1194; SN_rc2_cbc = AnsiString('RC2-CBC'); LN_rc2_cbc = AnsiString('rc2-cbc'); NID_rc2_cbc = 37; SN_rc2_ecb = AnsiString('RC2-ECB'); LN_rc2_ecb = AnsiString('rc2-ecb'); NID_rc2_ecb = 38; SN_rc2_cfb64 = AnsiString('RC2-CFB'); LN_rc2_cfb64 = AnsiString('rc2-cfb'); NID_rc2_cfb64 = 39; SN_rc2_ofb64 = AnsiString('RC2-OFB'); LN_rc2_ofb64 = AnsiString('rc2-ofb'); NID_rc2_ofb64 = 40; SN_rc2_40_cbc = AnsiString('RC2-40-CBC'); LN_rc2_40_cbc = AnsiString('rc2-40-cbc'); NID_rc2_40_cbc = 98; SN_rc2_64_cbc = AnsiString('RC2-64-CBC'); LN_rc2_64_cbc = AnsiString('rc2-64-cbc'); NID_rc2_64_cbc = 166; SN_rc4 = AnsiString('RC4'); LN_rc4 = AnsiString('rc4'); NID_rc4 = 5; SN_rc4_40 = AnsiString('RC4-40'); LN_rc4_40 = AnsiString('rc4-40'); NID_rc4_40 = 97; SN_des_ede3_cbc = AnsiString('DES-EDE3-CBC'); LN_des_ede3_cbc = AnsiString('des-ede3-cbc'); NID_des_ede3_cbc = 44; SN_rc5_cbc = AnsiString('RC5-CBC'); LN_rc5_cbc = AnsiString('rc5-cbc'); NID_rc5_cbc = 120; SN_rc5_ecb = AnsiString('RC5-ECB'); LN_rc5_ecb = AnsiString('rc5-ecb'); NID_rc5_ecb = 121; SN_rc5_cfb64 = AnsiString('RC5-CFB'); LN_rc5_cfb64 = AnsiString('rc5-cfb'); NID_rc5_cfb64 = 122; SN_rc5_ofb64 = AnsiString('RC5-OFB'); LN_rc5_ofb64 = AnsiString('rc5-ofb'); NID_rc5_ofb64 = 123; SN_ms_ext_req = AnsiString('msExtReq'); LN_ms_ext_req = AnsiString('Microsoft Extension Request'); NID_ms_ext_req = 171; SN_ms_code_ind = AnsiString('msCodeInd'); LN_ms_code_ind = AnsiString('Microsoft Individual Code Signing'); NID_ms_code_ind = 134; SN_ms_code_com = AnsiString('msCodeCom'); LN_ms_code_com = AnsiString('Microsoft Commercial Code Signing'); NID_ms_code_com = 135; SN_ms_ctl_sign = AnsiString('msCTLSign'); LN_ms_ctl_sign = AnsiString('Microsoft Trust List Signing'); NID_ms_ctl_sign = 136; SN_ms_sgc = AnsiString('msSGC'); LN_ms_sgc = AnsiString('Microsoft Server Gated Crypto'); NID_ms_sgc = 137; SN_ms_efs = AnsiString('msEFS'); LN_ms_efs = AnsiString('Microsoft Encrypted File System'); NID_ms_efs = 138; SN_ms_smartcard_login = AnsiString('msSmartcardLogin'); LN_ms_smartcard_login = AnsiString('Microsoft Smartcard Login'); NID_ms_smartcard_login = 648; SN_ms_upn = AnsiString('msUPN'); LN_ms_upn = AnsiString('Microsoft User Principal Name'); NID_ms_upn = 649; SN_idea_cbc = AnsiString('IDEA-CBC'); LN_idea_cbc = AnsiString('idea-cbc'); NID_idea_cbc = 34; SN_idea_ecb = AnsiString('IDEA-ECB'); LN_idea_ecb = AnsiString('idea-ecb'); NID_idea_ecb = 36; SN_idea_cfb64 = AnsiString('IDEA-CFB'); LN_idea_cfb64 = AnsiString('idea-cfb'); NID_idea_cfb64 = 35; SN_idea_ofb64 = AnsiString('IDEA-OFB'); LN_idea_ofb64 = AnsiString('idea-ofb'); NID_idea_ofb64 = 46; SN_bf_cbc = AnsiString('BF-CBC'); LN_bf_cbc = AnsiString('bf-cbc'); NID_bf_cbc = 91; SN_bf_ecb = AnsiString('BF-ECB'); LN_bf_ecb = AnsiString('bf-ecb'); NID_bf_ecb = 92; SN_bf_cfb64 = AnsiString('BF-CFB'); LN_bf_cfb64 = AnsiString('bf-cfb'); NID_bf_cfb64 = 93; SN_bf_ofb64 = AnsiString('BF-OFB'); LN_bf_ofb64 = AnsiString('bf-ofb'); NID_bf_ofb64 = 94; SN_id_pkix = AnsiString('PKIX'); NID_id_pkix = 127; SN_id_pkix_mod = AnsiString('id-pkix-mod'); NID_id_pkix_mod = 258; SN_id_pe = AnsiString('id-pe'); NID_id_pe = 175; SN_id_qt = AnsiString('id-qt'); NID_id_qt = 259; SN_id_kp = AnsiString('id-kp'); NID_id_kp = 128; SN_id_it = AnsiString('id-it'); NID_id_it = 260; SN_id_pkip = AnsiString('id-pkip'); NID_id_pkip = 261; SN_id_alg = AnsiString('id-alg'); NID_id_alg = 262; SN_id_cmc = AnsiString('id-cmc'); NID_id_cmc = 263; SN_id_on = AnsiString('id-on'); NID_id_on = 264; SN_id_pda = AnsiString('id-pda'); NID_id_pda = 265; SN_id_aca = AnsiString('id-aca'); NID_id_aca = 266; SN_id_qcs = AnsiString('id-qcs'); NID_id_qcs = 267; SN_id_cct = AnsiString('id-cct'); NID_id_cct = 268; SN_id_ppl = AnsiString('id-ppl'); NID_id_ppl = 662; SN_id_ad = AnsiString('id-ad'); NID_id_ad = 176; SN_id_pkix1_explicit_88 = AnsiString('id-pkix1-explicit-88'); NID_id_pkix1_explicit_88 = 269; SN_id_pkix1_implicit_88 = AnsiString('id-pkix1-implicit-88'); NID_id_pkix1_implicit_88 = 270; SN_id_pkix1_explicit_93 = AnsiString('id-pkix1-explicit-93'); NID_id_pkix1_explicit_93 = 271; SN_id_pkix1_implicit_93 = AnsiString('id-pkix1-implicit-93'); NID_id_pkix1_implicit_93 = 272; SN_id_mod_crmf = AnsiString('id-mod-crmf'); NID_id_mod_crmf = 273; SN_id_mod_cmc = AnsiString('id-mod-cmc'); NID_id_mod_cmc = 274; SN_id_mod_kea_profile_88 = AnsiString('id-mod-kea-profile-88'); NID_id_mod_kea_profile_88 = 275; SN_id_mod_kea_profile_93 = AnsiString('id-mod-kea-profile-93'); NID_id_mod_kea_profile_93 = 276; SN_id_mod_cmp = AnsiString('id-mod-cmp'); NID_id_mod_cmp = 277; SN_id_mod_qualified_cert_88 = AnsiString('id-mod-qualified-cert-88'); NID_id_mod_qualified_cert_88 = 278; SN_id_mod_qualified_cert_93 = AnsiString('id-mod-qualified-cert-93'); NID_id_mod_qualified_cert_93 = 279; SN_id_mod_attribute_cert = AnsiString('id-mod-attribute-cert'); NID_id_mod_attribute_cert = 280; SN_id_mod_timestamp_protocol = AnsiString('id-mod-timestamp-protocol'); NID_id_mod_timestamp_protocol = 281; SN_id_mod_ocsp = AnsiString('id-mod-ocsp'); NID_id_mod_ocsp = 282; SN_id_mod_dvcs = AnsiString('id-mod-dvcs'); NID_id_mod_dvcs = 283; SN_id_mod_cmp2000 = AnsiString('id-mod-cmp2000'); NID_id_mod_cmp2000 = 284; SN_info_access = AnsiString('authorityInfoAccess'); LN_info_access = AnsiString('Authority Information Access'); NID_info_access = 177; SN_biometricInfo = AnsiString('biometricInfo'); LN_biometricInfo = AnsiString('Biometric Info'); NID_biometricInfo = 285; SN_qcStatements = AnsiString('qcStatements'); NID_qcStatements = 286; SN_ac_auditEntity = AnsiString('ac-auditEntity'); NID_ac_auditEntity = 287; SN_ac_targeting = AnsiString('ac-targeting'); NID_ac_targeting = 288; SN_aaControls = AnsiString('aaControls'); NID_aaControls = 289; SN_sbgp_ipAddrBlock = AnsiString('sbgp-ipAddrBlock'); NID_sbgp_ipAddrBlock = 290; SN_sbgp_autonomousSysNum = AnsiString('sbgp-autonomousSysNum'); NID_sbgp_autonomousSysNum = 291; SN_sbgp_routerIdentifier = AnsiString('sbgp-routerIdentifier'); NID_sbgp_routerIdentifier = 292; SN_ac_proxying = AnsiString('ac-proxying'); NID_ac_proxying = 397; SN_sinfo_access = AnsiString('subjectInfoAccess'); LN_sinfo_access = AnsiString('Subject Information Access'); NID_sinfo_access = 398; SN_proxyCertInfo = AnsiString('proxyCertInfo'); LN_proxyCertInfo = AnsiString('Proxy Certificate Information'); NID_proxyCertInfo = 663; SN_tlsfeature = AnsiString('tlsfeature'); LN_tlsfeature = AnsiString('TLS Feature'); NID_tlsfeature = 1020; SN_id_qt_cps = AnsiString('id-qt-cps'); LN_id_qt_cps = AnsiString('Policy Qualifier CPS'); NID_id_qt_cps = 164; SN_id_qt_unotice = AnsiString('id-qt-unotice'); LN_id_qt_unotice = AnsiString('Policy Qualifier User Notice'); NID_id_qt_unotice = 165; SN_textNotice = AnsiString('textNotice'); NID_textNotice = 293; SN_server_auth = AnsiString('serverAuth'); LN_server_auth = AnsiString('TLS Web Server Authentication'); NID_server_auth = 129; SN_client_auth = AnsiString('clientAuth'); LN_client_auth = AnsiString('TLS Web Client Authentication'); NID_client_auth = 130; SN_code_sign = AnsiString('codeSigning'); LN_code_sign = AnsiString('Code Signing'); NID_code_sign = 131; SN_email_protect = AnsiString('emailProtection'); LN_email_protect = AnsiString('E-mail Protection'); NID_email_protect = 132; SN_ipsecEndSystem = AnsiString('ipsecEndSystem'); LN_ipsecEndSystem = AnsiString('IPSec End System'); NID_ipsecEndSystem = 294; SN_ipsecTunnel = AnsiString('ipsecTunnel'); LN_ipsecTunnel = AnsiString('IPSec Tunnel'); NID_ipsecTunnel = 295; SN_ipsecUser = AnsiString('ipsecUser'); LN_ipsecUser = AnsiString('IPSec User'); NID_ipsecUser = 296; SN_time_stamp = AnsiString('timeStamping'); LN_time_stamp = AnsiString('Time Stamping'); NID_time_stamp = 133; SN_OCSP_sign = AnsiString('OCSPSigning'); LN_OCSP_sign = AnsiString('OCSP Signing'); NID_OCSP_sign = 180; SN_dvcs = AnsiString('DVCS'); LN_dvcs = AnsiString('dvcs'); NID_dvcs = 297; SN_ipsec_IKE = AnsiString('ipsecIKE'); LN_ipsec_IKE = AnsiString('ipsec Internet Key Exchange'); NID_ipsec_IKE = 1022; SN_capwapAC = AnsiString('capwapAC'); LN_capwapAC = AnsiString('Ctrl/provision WAP Access'); NID_capwapAC = 1023; SN_capwapWTP = AnsiString('capwapWTP'); LN_capwapWTP = AnsiString('Ctrl/Provision WAP Termination'); NID_capwapWTP = 1024; SN_sshClient = AnsiString('secureShellClient'); LN_sshClient = AnsiString('SSH Client'); NID_sshClient = 1025; SN_sshServer = AnsiString('secureShellServer'); LN_sshServer = AnsiString('SSH Server'); NID_sshServer = 1026; SN_sendRouter = AnsiString('sendRouter'); LN_sendRouter = AnsiString('Send Router'); NID_sendRouter = 1027; SN_sendProxiedRouter = AnsiString('sendProxiedRouter'); LN_sendProxiedRouter = AnsiString('Send Proxied Router'); NID_sendProxiedRouter = 1028; SN_sendOwner = AnsiString('sendOwner'); LN_sendOwner = AnsiString('Send Owner'); NID_sendOwner = 1029; SN_sendProxiedOwner = AnsiString('sendProxiedOwner'); LN_sendProxiedOwner = AnsiString('Send Proxied Owner'); NID_sendProxiedOwner = 1030; SN_cmcCA = AnsiString('cmcCA'); LN_cmcCA = AnsiString('CMC Certificate Authority'); NID_cmcCA = 1131; SN_cmcRA = AnsiString('cmcRA'); LN_cmcRA = AnsiString('CMC Registration Authority'); NID_cmcRA = 1132; SN_id_it_caProtEncCert = AnsiString('id-it-caProtEncCert'); NID_id_it_caProtEncCert = 298; SN_id_it_signKeyPairTypes = AnsiString('id-it-signKeyPairTypes'); NID_id_it_signKeyPairTypes = 299; SN_id_it_encKeyPairTypes = AnsiString('id-it-encKeyPairTypes'); NID_id_it_encKeyPairTypes = 300; SN_id_it_preferredSymmAlg = AnsiString('id-it-preferredSymmAlg'); NID_id_it_preferredSymmAlg = 301; SN_id_it_caKeyUpdateInfo = AnsiString('id-it-caKeyUpdateInfo'); NID_id_it_caKeyUpdateInfo = 302; SN_id_it_currentCRL = AnsiString('id-it-currentCRL'); NID_id_it_currentCRL = 303; SN_id_it_unsupportedOIDs = AnsiString('id-it-unsupportedOIDs'); NID_id_it_unsupportedOIDs = 304; SN_id_it_subscriptionRequest = AnsiString('id-it-subscriptionRequest'); NID_id_it_subscriptionRequest = 305; SN_id_it_subscriptionResponse = AnsiString('id-it-subscriptionResponse'); NID_id_it_subscriptionResponse = 306; SN_id_it_keyPairParamReq = AnsiString('id-it-keyPairParamReq'); NID_id_it_keyPairParamReq = 307; SN_id_it_keyPairParamRep = AnsiString('id-it-keyPairParamRep'); NID_id_it_keyPairParamRep = 308; SN_id_it_revPassphrase = AnsiString('id-it-revPassphrase'); NID_id_it_revPassphrase = 309; SN_id_it_implicitConfirm = AnsiString('id-it-implicitConfirm'); NID_id_it_implicitConfirm = 310; SN_id_it_confirmWaitTime = AnsiString('id-it-confirmWaitTime'); NID_id_it_confirmWaitTime = 311; SN_id_it_origPKIMessage = AnsiString('id-it-origPKIMessage'); NID_id_it_origPKIMessage = 312; SN_id_it_suppLangTags = AnsiString('id-it-suppLangTags'); NID_id_it_suppLangTags = 784; SN_id_regCtrl = AnsiString('id-regCtrl'); NID_id_regCtrl = 313; SN_id_regInfo = AnsiString('id-regInfo'); NID_id_regInfo = 314; SN_id_regCtrl_regToken = AnsiString('id-regCtrl-regToken'); NID_id_regCtrl_regToken = 315; SN_id_regCtrl_authenticator = AnsiString('id-regCtrl-authenticator'); NID_id_regCtrl_authenticator = 316; SN_id_regCtrl_pkiPublicationInfo = AnsiString('id-regCtrl-pkiPublicationInfo'); NID_id_regCtrl_pkiPublicationInfo = 317; SN_id_regCtrl_pkiArchiveOptions = AnsiString('id-regCtrl-pkiArchiveOptions'); NID_id_regCtrl_pkiArchiveOptions = 318; SN_id_regCtrl_oldCertID = AnsiString('id-regCtrl-oldCertID'); NID_id_regCtrl_oldCertID = 319; SN_id_regCtrl_protocolEncrKey = AnsiString('id-regCtrl-protocolEncrKey'); NID_id_regCtrl_protocolEncrKey = 320; SN_id_regInfo_utf8Pairs = AnsiString('id-regInfo-utf8Pairs'); NID_id_regInfo_utf8Pairs = 321; SN_id_regInfo_certReq = AnsiString('id-regInfo-certReq'); NID_id_regInfo_certReq = 322; SN_id_alg_des40 = AnsiString('id-alg-des40'); NID_id_alg_des40 = 323; SN_id_alg_noSignature = AnsiString('id-alg-noSignature'); NID_id_alg_noSignature = 324; SN_id_alg_dh_sig_hmac_sha1 = AnsiString('id-alg-dh-sig-hmac-sha1'); NID_id_alg_dh_sig_hmac_sha1 = 325; SN_id_alg_dh_pop = AnsiString('id-alg-dh-pop'); NID_id_alg_dh_pop = 326; SN_id_cmc_statusInfo = AnsiString('id-cmc-statusInfo'); NID_id_cmc_statusInfo = 327; SN_id_cmc_identification = AnsiString('id-cmc-identification'); NID_id_cmc_identification = 328; SN_id_cmc_identityProof = AnsiString('id-cmc-identityProof'); NID_id_cmc_identityProof = 329; SN_id_cmc_dataReturn = AnsiString('id-cmc-dataReturn'); NID_id_cmc_dataReturn = 330; SN_id_cmc_transactionId = AnsiString('id-cmc-transactionId'); NID_id_cmc_transactionId = 331; SN_id_cmc_senderNonce = AnsiString('id-cmc-senderNonce'); NID_id_cmc_senderNonce = 332; SN_id_cmc_recipientNonce = AnsiString('id-cmc-recipientNonce'); NID_id_cmc_recipientNonce = 333; SN_id_cmc_addExtensions = AnsiString('id-cmc-addExtensions'); NID_id_cmc_addExtensions = 334; SN_id_cmc_encryptedPOP = AnsiString('id-cmc-encryptedPOP'); NID_id_cmc_encryptedPOP = 335; SN_id_cmc_decryptedPOP = AnsiString('id-cmc-decryptedPOP'); NID_id_cmc_decryptedPOP = 336; SN_id_cmc_lraPOPWitness = AnsiString('id-cmc-lraPOPWitness'); NID_id_cmc_lraPOPWitness = 337; SN_id_cmc_getCert = AnsiString('id-cmc-getCert'); NID_id_cmc_getCert = 338; SN_id_cmc_getCRL = AnsiString('id-cmc-getCRL'); NID_id_cmc_getCRL = 339; SN_id_cmc_revokeRequest = AnsiString('id-cmc-revokeRequest'); NID_id_cmc_revokeRequest = 340; SN_id_cmc_regInfo = AnsiString('id-cmc-regInfo'); NID_id_cmc_regInfo = 341; SN_id_cmc_responseInfo = AnsiString('id-cmc-responseInfo'); NID_id_cmc_responseInfo = 342; SN_id_cmc_queryPending = AnsiString('id-cmc-queryPending'); NID_id_cmc_queryPending = 343; SN_id_cmc_popLinkRandom = AnsiString('id-cmc-popLinkRandom'); NID_id_cmc_popLinkRandom = 344; SN_id_cmc_popLinkWitness = AnsiString('id-cmc-popLinkWitness'); NID_id_cmc_popLinkWitness = 345; SN_id_cmc_confirmCertAcceptance = AnsiString('id-cmc-confirmCertAcceptance'); NID_id_cmc_confirmCertAcceptance = 346; SN_id_on_personalData = AnsiString('id-on-personalData'); NID_id_on_personalData = 347; SN_id_on_permanentIdentifier = AnsiString('id-on-permanentIdentifier'); LN_id_on_permanentIdentifier = AnsiString('Permanent Identifier'); NID_id_on_permanentIdentifier = 858; SN_id_pda_dateOfBirth = AnsiString('id-pda-dateOfBirth'); NID_id_pda_dateOfBirth = 348; SN_id_pda_placeOfBirth = AnsiString('id-pda-placeOfBirth'); NID_id_pda_placeOfBirth = 349; SN_id_pda_gender = AnsiString('id-pda-gender'); NID_id_pda_gender = 351; SN_id_pda_countryOfCitizenship = AnsiString('id-pda-countryOfCitizenship'); NID_id_pda_countryOfCitizenship = 352; SN_id_pda_countryOfResidence = AnsiString('id-pda-countryOfResidence'); NID_id_pda_countryOfResidence = 353; SN_id_aca_authenticationInfo = AnsiString('id-aca-authenticationInfo'); NID_id_aca_authenticationInfo = 354; SN_id_aca_accessIdentity = AnsiString('id-aca-accessIdentity'); NID_id_aca_accessIdentity = 355; SN_id_aca_chargingIdentity = AnsiString('id-aca-chargingIdentity'); NID_id_aca_chargingIdentity = 356; SN_id_aca_group = AnsiString('id-aca-group'); NID_id_aca_group = 357; SN_id_aca_role = AnsiString('id-aca-role'); NID_id_aca_role = 358; SN_id_aca_encAttrs = AnsiString('id-aca-encAttrs'); NID_id_aca_encAttrs = 399; SN_id_qcs_pkixQCSyntax_v1 = AnsiString('id-qcs-pkixQCSyntax-v1'); NID_id_qcs_pkixQCSyntax_v1 = 359; SN_id_cct_crs = AnsiString('id-cct-crs'); NID_id_cct_crs = 360; SN_id_cct_PKIData = AnsiString('id-cct-PKIData'); NID_id_cct_PKIData = 361; SN_id_cct_PKIResponse = AnsiString('id-cct-PKIResponse'); NID_id_cct_PKIResponse = 362; SN_id_ppl_anyLanguage = AnsiString('id-ppl-anyLanguage'); LN_id_ppl_anyLanguage = AnsiString('Any language'); NID_id_ppl_anyLanguage = 664; SN_id_ppl_inheritAll = AnsiString('id-ppl-inheritAll'); LN_id_ppl_inheritAll = AnsiString('Inherit all'); NID_id_ppl_inheritAll = 665; SN_Independent = AnsiString('id-ppl-independent'); LN_Independent = AnsiString('Independent'); NID_Independent = 667; SN_ad_OCSP = AnsiString('OCSP'); LN_ad_OCSP = AnsiString('OCSP'); NID_ad_OCSP = 178; SN_ad_ca_issuers = AnsiString('caIssuers'); LN_ad_ca_issuers = AnsiString('CA Issuers'); NID_ad_ca_issuers = 179; SN_ad_timeStamping = AnsiString('ad_timestamping'); LN_ad_timeStamping = AnsiString('AD Time Stamping'); NID_ad_timeStamping = 363; SN_ad_dvcs = AnsiString('AD_DVCS'); LN_ad_dvcs = AnsiString('ad dvcs'); NID_ad_dvcs = 364; SN_caRepository = AnsiString('caRepository'); LN_caRepository = AnsiString('CA Repository'); NID_caRepository = 785; SN_id_pkix_OCSP_basic = AnsiString('basicOCSPResponse'); LN_id_pkix_OCSP_basic = AnsiString('Basic OCSP Response'); NID_id_pkix_OCSP_basic = 365; SN_id_pkix_OCSP_Nonce = AnsiString('Nonce'); LN_id_pkix_OCSP_Nonce = AnsiString('OCSP Nonce'); NID_id_pkix_OCSP_Nonce = 366; SN_id_pkix_OCSP_CrlID = AnsiString('CrlID'); LN_id_pkix_OCSP_CrlID = AnsiString('OCSP CRL ID'); NID_id_pkix_OCSP_CrlID = 367; SN_id_pkix_OCSP_acceptableResponses = AnsiString('acceptableResponses'); LN_id_pkix_OCSP_acceptableResponses = AnsiString('Acceptable OCSP Responses'); NID_id_pkix_OCSP_acceptableResponses = 368; SN_id_pkix_OCSP_noCheck = AnsiString('noCheck'); LN_id_pkix_OCSP_noCheck = AnsiString('OCSP No Check'); NID_id_pkix_OCSP_noCheck = 369; SN_id_pkix_OCSP_archiveCutoff = AnsiString('archiveCutoff'); LN_id_pkix_OCSP_archiveCutoff = AnsiString('OCSP Archive Cutoff'); NID_id_pkix_OCSP_archiveCutoff = 370; SN_id_pkix_OCSP_serviceLocator = AnsiString('serviceLocator'); LN_id_pkix_OCSP_serviceLocator = AnsiString('OCSP Service Locator'); NID_id_pkix_OCSP_serviceLocator = 371; SN_id_pkix_OCSP_extendedStatus = AnsiString('extendedStatus'); LN_id_pkix_OCSP_extendedStatus = AnsiString('Extended OCSP Status'); NID_id_pkix_OCSP_extendedStatus = 372; SN_id_pkix_OCSP_valid = AnsiString('valid'); NID_id_pkix_OCSP_valid = 373; SN_id_pkix_OCSP_path = AnsiString('path'); NID_id_pkix_OCSP_path = 374; SN_id_pkix_OCSP_trustRoot = AnsiString('trustRoot'); LN_id_pkix_OCSP_trustRoot = AnsiString('Trust Root'); NID_id_pkix_OCSP_trustRoot = 375; SN_algorithm = AnsiString('algorithm'); LN_algorithm = AnsiString('algorithm'); NID_algorithm = 376; SN_md5WithRSA = AnsiString('RSA-NP-MD5'); LN_md5WithRSA = AnsiString('md5WithRSA'); NID_md5WithRSA = 104; SN_des_ecb = AnsiString('DES-ECB'); LN_des_ecb = AnsiString('des-ecb'); NID_des_ecb = 29; SN_des_cbc = AnsiString('DES-CBC'); LN_des_cbc = AnsiString('des-cbc'); NID_des_cbc = 31; SN_des_ofb64 = AnsiString('DES-OFB'); LN_des_ofb64 = AnsiString('des-ofb'); NID_des_ofb64 = 45; SN_des_cfb64 = AnsiString('DES-CFB'); LN_des_cfb64 = AnsiString('des-cfb'); NID_des_cfb64 = 30; SN_rsaSignature = AnsiString('rsaSignature'); NID_rsaSignature = 377; SN_dsa_2 = AnsiString('DSA-old'); LN_dsa_2 = AnsiString('dsaEncryption-old'); NID_dsa_2 = 67; SN_dsaWithSHA = AnsiString('DSA-SHA'); LN_dsaWithSHA = AnsiString('dsaWithSHA'); NID_dsaWithSHA = 66; SN_shaWithRSAEncryption = AnsiString('RSA-SHA'); LN_shaWithRSAEncryption = AnsiString('shaWithRSAEncryption'); NID_shaWithRSAEncryption = 42; SN_des_ede_ecb = AnsiString('DES-EDE'); LN_des_ede_ecb = AnsiString('des-ede'); NID_des_ede_ecb = 32; SN_des_ede3_ecb = AnsiString('DES-EDE3'); LN_des_ede3_ecb = AnsiString('des-ede3'); NID_des_ede3_ecb = 33; SN_des_ede_cbc = AnsiString('DES-EDE-CBC'); LN_des_ede_cbc = AnsiString('des-ede-cbc'); NID_des_ede_cbc = 43; SN_des_ede_cfb64 = AnsiString('DES-EDE-CFB'); LN_des_ede_cfb64 = AnsiString('des-ede-cfb'); NID_des_ede_cfb64 = 60; SN_des_ede3_cfb64 = AnsiString('DES-EDE3-CFB'); LN_des_ede3_cfb64 = AnsiString('des-ede3-cfb'); NID_des_ede3_cfb64 = 61; SN_des_ede_ofb64 = AnsiString('DES-EDE-OFB'); LN_des_ede_ofb64 = AnsiString('des-ede-ofb'); NID_des_ede_ofb64 = 62; SN_des_ede3_ofb64 = AnsiString('DES-EDE3-OFB'); LN_des_ede3_ofb64 = AnsiString('des-ede3-ofb'); NID_des_ede3_ofb64 = 63; SN_desx_cbc = AnsiString('DESX-CBC'); LN_desx_cbc = AnsiString('desx-cbc'); NID_desx_cbc = 80; SN_sha = AnsiString('SHA'); LN_sha = AnsiString('sha'); NID_sha = 41; SN_sha1 = AnsiString('SHA1'); LN_sha1 = AnsiString('sha1'); NID_sha1 = 64; SN_dsaWithSHA1_2 = AnsiString('DSA-SHA1-old'); LN_dsaWithSHA1_2 = AnsiString('dsaWithSHA1-old'); NID_dsaWithSHA1_2 = 70; SN_sha1WithRSA = AnsiString('RSA-SHA1-2'); LN_sha1WithRSA = AnsiString('sha1WithRSA'); NID_sha1WithRSA = 115; SN_ripemd160 = AnsiString('RIPEMD160'); LN_ripemd160 = AnsiString('ripemd160'); NID_ripemd160 = 117; SN_ripemd160WithRSA = AnsiString('RSA-RIPEMD160'); LN_ripemd160WithRSA = AnsiString('ripemd160WithRSA'); NID_ripemd160WithRSA = 119; SN_blake2b512 = AnsiString('BLAKE2b512'); LN_blake2b512 = AnsiString('blake2b512'); NID_blake2b512 = 1056; SN_blake2s256 = AnsiString('BLAKE2s256'); LN_blake2s256 = AnsiString('blake2s256'); NID_blake2s256 = 1057; SN_sxnet = AnsiString('SXNetID'); LN_sxnet = AnsiString('Strong Extranet ID'); NID_sxnet = 143; SN_X500 = AnsiString('X500'); LN_X500 = AnsiString('directory services(X.500)'); NID_X500 = 11; SN_X509 = AnsiString('X509'); NID_X509 = 12; SN_commonName = AnsiString('CN'); LN_commonName = AnsiString('commonName'); NID_commonName = 13; SN_surname = AnsiString('SN'); LN_surname = AnsiString('surname'); NID_surname = 100; LN_serialNumber = AnsiString('serialNumber'); NID_serialNumber = 105; SN_countryName = AnsiString('C'); LN_countryName = AnsiString('countryName'); NID_countryName = 14; SN_localityName = AnsiString('L'); LN_localityName = AnsiString('localityName'); NID_localityName = 15; SN_stateOrProvinceName = AnsiString('ST'); LN_stateOrProvinceName = AnsiString('stateOrProvinceName'); NID_stateOrProvinceName = 16; SN_streetAddress = AnsiString('street'); LN_streetAddress = AnsiString('streetAddress'); NID_streetAddress = 660; SN_organizationName = AnsiString('O'); LN_organizationName = AnsiString('organizationName'); NID_organizationName = 17; SN_organizationalUnitName = AnsiString('OU'); LN_organizationalUnitName = AnsiString('organizationalUnitName'); NID_organizationalUnitName = 18; SN_title = AnsiString('title'); LN_title = AnsiString('title'); NID_title = 106; LN_description = AnsiString('description'); NID_description = 107; LN_searchGuide = AnsiString('searchGuide'); NID_searchGuide = 859; LN_businessCategory = AnsiString('businessCategory'); NID_businessCategory = 860; LN_postalAddress = AnsiString('postalAddress'); NID_postalAddress = 861; LN_postalCode = AnsiString('postalCode'); NID_postalCode = 661; LN_postOfficeBox = AnsiString('postOfficeBox'); NID_postOfficeBox = 862; LN_physicalDeliveryOfficeName = AnsiString('physicalDeliveryOfficeName'); NID_physicalDeliveryOfficeName = 863; LN_telephoneNumber = AnsiString('telephoneNumber'); NID_telephoneNumber = 864; LN_telexNumber = AnsiString('telexNumber'); NID_telexNumber = 865; LN_teletexTerminalIdentifier = AnsiString('teletexTerminalIdentifier'); NID_teletexTerminalIdentifier = 866; LN_facsimileTelephoneNumber = AnsiString('facsimileTelephoneNumber'); NID_facsimileTelephoneNumber = 867; LN_x121Address = AnsiString('x121Address'); NID_x121Address = 868; LN_internationaliSDNNumber = AnsiString('internationaliSDNNumber'); NID_internationaliSDNNumber = 869; LN_registeredAddress = AnsiString('registeredAddress'); NID_registeredAddress = 870; LN_destinationIndicator = AnsiString('destinationIndicator'); NID_destinationIndicator = 871; LN_preferredDeliveryMethod = AnsiString('preferredDeliveryMethod'); NID_preferredDeliveryMethod = 872; LN_presentationAddress = AnsiString('presentationAddress'); NID_presentationAddress = 873; LN_supportedApplicationContext = AnsiString('supportedApplicationContext'); NID_supportedApplicationContext = 874; SN_member = AnsiString('member'); NID_member = 875; SN_owner = AnsiString('owner'); NID_owner = 876; LN_roleOccupant = AnsiString('roleOccupant'); NID_roleOccupant = 877; SN_seeAlso = AnsiString('seeAlso'); NID_seeAlso = 878; LN_userPassword = AnsiString('userPassword'); NID_userPassword = 879; LN_userCertificate = AnsiString('userCertificate'); NID_userCertificate = 880; LN_cACertificate = AnsiString('cACertificate'); NID_cACertificate = 881; LN_authorityRevocationList = AnsiString('authorityRevocationList'); NID_authorityRevocationList = 882; LN_certificateRevocationList = AnsiString('certificateRevocationList'); NID_certificateRevocationList = 883; LN_crossCertificatePair = AnsiString('crossCertificatePair'); NID_crossCertificatePair = 884; SN_name = AnsiString('name'); LN_name = AnsiString('name'); NID_name = 173; SN_givenName = AnsiString('GN'); LN_givenName = AnsiString('givenName'); NID_givenName = 99; SN_initials = AnsiString('initials'); LN_initials = AnsiString('initials'); NID_initials = 101; LN_generationQualifier = AnsiString('generationQualifier'); NID_generationQualifier = 509; LN_x500UniqueIdentifier = AnsiString('x500UniqueIdentifier'); NID_x500UniqueIdentifier = 503; SN_dnQualifier = AnsiString('dnQualifier'); LN_dnQualifier = AnsiString('dnQualifier'); NID_dnQualifier = 174; LN_enhancedSearchGuide = AnsiString('enhancedSearchGuide'); NID_enhancedSearchGuide = 885; LN_protocolInformation = AnsiString('protocolInformation'); NID_protocolInformation = 886; LN_distinguishedName = AnsiString('distinguishedName'); NID_distinguishedName = 887; LN_uniqueMember = AnsiString('uniqueMember'); NID_uniqueMember = 888; LN_houseIdentifier = AnsiString('houseIdentifier'); NID_houseIdentifier = 889; LN_supportedAlgorithms = AnsiString('supportedAlgorithms'); NID_supportedAlgorithms = 890; LN_deltaRevocationList = AnsiString('deltaRevocationList'); NID_deltaRevocationList = 891; SN_dmdName = AnsiString('dmdName'); NID_dmdName = 892; LN_pseudonym = AnsiString('pseudonym'); NID_pseudonym = 510; SN_role = AnsiString('role'); LN_role = AnsiString('role'); NID_role = 400; LN_organizationIdentifier = AnsiString('organizationIdentifier'); NID_organizationIdentifier = 1089; SN_countryCode3c = AnsiString('c3'); LN_countryCode3c = AnsiString('countryCode3c'); NID_countryCode3c = 1090; SN_countryCode3n = AnsiString('n3'); LN_countryCode3n = AnsiString('countryCode3n'); NID_countryCode3n = 1091; LN_dnsName = AnsiString('dnsName'); NID_dnsName = 1092; SN_X500algorithms = AnsiString('X500algorithms'); LN_X500algorithms = AnsiString('directory services - algorithms'); NID_X500algorithms = 378; SN_rsa = AnsiString('RSA'); LN_rsa = AnsiString('rsa'); NID_rsa = 19; SN_mdc2WithRSA = AnsiString('RSA-MDC2'); LN_mdc2WithRSA = AnsiString('mdc2WithRSA'); NID_mdc2WithRSA = 96; SN_mdc2 = AnsiString('MDC2'); LN_mdc2 = AnsiString('mdc2'); NID_mdc2 = 95; SN_id_ce = AnsiString('id-ce'); NID_id_ce = 81; SN_subject_directory_attributes = AnsiString('subjectDirectoryAttributes'); LN_subject_directory_attributes = AnsiString('X509v3 Subject Directory Attributes'); NID_subject_directory_attributes = 769; SN_subject_key_identifier = AnsiString('subjectKeyIdentifier'); LN_subject_key_identifier = AnsiString('X509v3 Subject Key Identifier'); NID_subject_key_identifier = 82; SN_key_usage = AnsiString('keyUsage'); LN_key_usage = AnsiString('X509v3 Key Usage'); NID_key_usage = 83; SN_private_key_usage_period = AnsiString('privateKeyUsagePeriod'); LN_private_key_usage_period = AnsiString('X509v3 Private Key Usage Period'); NID_private_key_usage_period = 84; SN_subject_alt_name = AnsiString('subjectAltName'); LN_subject_alt_name = AnsiString('X509v3 Subject Alternative Name'); NID_subject_alt_name = 85; SN_issuer_alt_name = AnsiString('issuerAltName'); LN_issuer_alt_name = AnsiString('X509v3 Issuer Alternative Name'); NID_issuer_alt_name = 86; SN_basic_constraints = AnsiString('basicConstraints'); LN_basic_constraints = AnsiString('X509v3 Basic Constraints'); NID_basic_constraints = 87; SN_crl_number = AnsiString('crlNumber'); LN_crl_number = AnsiString('X509v3 CRL Number'); NID_crl_number = 88; SN_crl_reason = AnsiString('CRLReason'); LN_crl_reason = AnsiString('X509v3 CRL Reason Code'); NID_crl_reason = 141; SN_invalidity_date = AnsiString('invalidityDate'); LN_invalidity_date = AnsiString('Invalidity Date'); NID_invalidity_date = 142; SN_delta_crl = AnsiString('deltaCRL'); LN_delta_crl = AnsiString('X509v3 Delta CRL Indicator'); NID_delta_crl = 140; SN_issuing_distribution_point = AnsiString('issuingDistributionPoint'); LN_issuing_distribution_point = AnsiString('X509v3 Issuing Distribution Point'); NID_issuing_distribution_point = 770; SN_certificate_issuer = AnsiString('certificateIssuer'); LN_certificate_issuer = AnsiString('X509v3 Certificate Issuer'); NID_certificate_issuer = 771; SN_name_constraints = AnsiString('nameConstraints'); LN_name_constraints = AnsiString('X509v3 Name Constraints'); NID_name_constraints = 666; SN_crl_distribution_points = AnsiString('crlDistributionPoints'); LN_crl_distribution_points = AnsiString('X509v3 CRL Distribution Points'); NID_crl_distribution_points = 103; SN_certificate_policies = AnsiString('certificatePolicies'); LN_certificate_policies = AnsiString('X509v3 Certificate Policies'); NID_certificate_policies = 89; SN_any_policy = AnsiString('anyPolicy'); LN_any_policy = AnsiString('X509v3 Any Policy'); NID_any_policy = 746; SN_policy_mappings = AnsiString('policyMappings'); LN_policy_mappings = AnsiString('X509v3 Policy Mappings'); NID_policy_mappings = 747; SN_authority_key_identifier = AnsiString('authorityKeyIdentifier'); LN_authority_key_identifier = AnsiString('X509v3 Authority Key Identifier'); NID_authority_key_identifier = 90; SN_policy_constraints = AnsiString('policyConstraints'); LN_policy_constraints = AnsiString('X509v3 Policy Constraints'); NID_policy_constraints = 401; SN_ext_key_usage = AnsiString('extendedKeyUsage'); LN_ext_key_usage = AnsiString('X509v3 Extended Key Usage'); NID_ext_key_usage = 126; SN_freshest_crl = AnsiString('freshestCRL'); LN_freshest_crl = AnsiString('X509v3 Freshest CRL'); NID_freshest_crl = 857; SN_inhibit_any_policy = AnsiString('inhibitAnyPolicy'); LN_inhibit_any_policy = AnsiString('X509v3 Inhibit Any Policy'); NID_inhibit_any_policy = 748; SN_target_information = AnsiString('targetInformation'); LN_target_information = AnsiString('X509v3 AC Targeting'); NID_target_information = 402; SN_no_rev_avail = AnsiString('noRevAvail'); LN_no_rev_avail = AnsiString('X509v3 No Revocation Available'); NID_no_rev_avail = 403; SN_anyExtendedKeyUsage = AnsiString('anyExtendedKeyUsage'); LN_anyExtendedKeyUsage = AnsiString('Any Extended Key Usage'); NID_anyExtendedKeyUsage = 910; SN_netscape = AnsiString('Netscape'); LN_netscape = AnsiString('Netscape Communications Corp.'); NID_netscape = 57; SN_netscape_cert_extension = AnsiString('nsCertExt'); LN_netscape_cert_extension = AnsiString('Netscape Certificate Extension'); NID_netscape_cert_extension = 58; SN_netscape_data_type = AnsiString('nsDataType'); LN_netscape_data_type = AnsiString('Netscape Data Type'); NID_netscape_data_type = 59; SN_netscape_cert_type = AnsiString('nsCertType'); LN_netscape_cert_type = AnsiString('Netscape Cert Type'); NID_netscape_cert_type = 71; SN_netscape_base_url = AnsiString('nsBaseUrl'); LN_netscape_base_url = AnsiString('Netscape Base Url'); NID_netscape_base_url = 72; SN_netscape_revocation_url = AnsiString('nsRevocationUrl'); LN_netscape_revocation_url = AnsiString('Netscape Revocation Url'); NID_netscape_revocation_url = 73; SN_netscape_ca_revocation_url = AnsiString('nsCaRevocationUrl'); LN_netscape_ca_revocation_url = AnsiString('Netscape CA Revocation Url'); NID_netscape_ca_revocation_url = 74; SN_netscape_renewal_url = AnsiString('nsRenewalUrl'); LN_netscape_renewal_url = AnsiString('Netscape Renewal Url'); NID_netscape_renewal_url = 75; SN_netscape_ca_policy_url = AnsiString('nsCaPolicyUrl'); LN_netscape_ca_policy_url = AnsiString('Netscape CA Policy Url'); NID_netscape_ca_policy_url = 76; SN_netscape_ssl_server_name = AnsiString('nsSslServerName'); LN_netscape_ssl_server_name = AnsiString('Netscape Server: SSl Name'); NID_netscape_ssl_server_name = 77; SN_netscape_comment = AnsiString('nsComment'); LN_netscape_comment = AnsiString('Netscape Comment'); NID_netscape_comment = 78; SN_netscape_cert_sequence = AnsiString('nsCertSequence'); LN_netscape_cert_sequence = AnsiString('Netscape Certificate Sequence'); NID_netscape_cert_sequence = 79; SN_ns_sgc = AnsiString('nsSGC'); LN_ns_sgc = AnsiString('Netscape Server Gated Crypto'); NID_ns_sgc = 139; SN_org = AnsiString('ORG'); LN_org = AnsiString('org'); NID_org = 379; SN_dod = AnsiString('DOD'); LN_dod = AnsiString('dod'); NID_dod = 380; SN_iana = AnsiString('IANA'); LN_iana = AnsiString('iana'); NID_iana = 381; SN_Directory = AnsiString('directory'); LN_Directory = AnsiString('Directory'); NID_Directory = 382; SN_Management = AnsiString('mgmt'); LN_Management = AnsiString('Management'); NID_Management = 383; SN_Experimental = AnsiString('experimental'); LN_Experimental = AnsiString('Experimental'); NID_Experimental = 384; SN_Private = AnsiString('private'); LN_Private = AnsiString('Private'); NID_Private = 385; SN_Security = AnsiString('security'); LN_Security = AnsiString('Security'); NID_Security = 386; SN_SNMPv2 = AnsiString('snmpv2'); LN_SNMPv2 = AnsiString('SNMPv2'); NID_SNMPv2 = 387; LN_Mail = AnsiString('Mail'); NID_Mail = 388; SN_Enterprises = AnsiString('enterprises'); LN_Enterprises = AnsiString('Enterprises'); NID_Enterprises = 389; SN_dcObject = AnsiString('dcobject'); LN_dcObject = AnsiString('dcObject'); NID_dcObject = 390; SN_mime_mhs = AnsiString('mime-mhs'); LN_mime_mhs = AnsiString('MIME MHS'); NID_mime_mhs = 504; SN_mime_mhs_headings = AnsiString('mime-mhs-headings'); LN_mime_mhs_headings = AnsiString('mime-mhs-headings'); NID_mime_mhs_headings = 505; SN_mime_mhs_bodies = AnsiString('mime-mhs-bodies'); LN_mime_mhs_bodies = AnsiString('mime-mhs-bodies'); NID_mime_mhs_bodies = 506; SN_id_hex_partial_message = AnsiString('id-hex-partial-message'); LN_id_hex_partial_message = AnsiString('id-hex-partial-message'); NID_id_hex_partial_message = 507; SN_id_hex_multipart_message = AnsiString('id-hex-multipart-message'); LN_id_hex_multipart_message = AnsiString('id-hex-multipart-message'); NID_id_hex_multipart_message = 508; SN_zlib_compression = AnsiString('ZLIB'); LN_zlib_compression = AnsiString('zlib compression'); NID_zlib_compression = 125; SN_aes_128_ecb = AnsiString('AES-128-ECB'); LN_aes_128_ecb = AnsiString('aes-128-ecb'); NID_aes_128_ecb = 418; SN_aes_128_cbc = AnsiString('AES-128-CBC'); LN_aes_128_cbc = AnsiString('aes-128-cbc'); NID_aes_128_cbc = 419; SN_aes_128_ofb128 = AnsiString('AES-128-OFB'); LN_aes_128_ofb128 = AnsiString('aes-128-ofb'); NID_aes_128_ofb128 = 420; SN_aes_128_cfb128 = AnsiString('AES-128-CFB'); LN_aes_128_cfb128 = AnsiString('aes-128-cfb'); NID_aes_128_cfb128 = 421; SN_id_aes128_wrap = AnsiString('id-aes128-wrap'); NID_id_aes128_wrap = 788; SN_aes_128_gcm = AnsiString('id-aes128-GCM'); LN_aes_128_gcm = AnsiString('aes-128-gcm'); NID_aes_128_gcm = 895; SN_aes_128_ccm = AnsiString('id-aes128-CCM'); LN_aes_128_ccm = AnsiString('aes-128-ccm'); NID_aes_128_ccm = 896; SN_id_aes128_wrap_pad = AnsiString('id-aes128-wrap-pad'); NID_id_aes128_wrap_pad = 897; SN_aes_192_ecb = AnsiString('AES-192-ECB'); LN_aes_192_ecb = AnsiString('aes-192-ecb'); NID_aes_192_ecb = 422; SN_aes_192_cbc = AnsiString('AES-192-CBC'); LN_aes_192_cbc = AnsiString('aes-192-cbc'); NID_aes_192_cbc = 423; SN_aes_192_ofb128 = AnsiString('AES-192-OFB'); LN_aes_192_ofb128 = AnsiString('aes-192-ofb'); NID_aes_192_ofb128 = 424; SN_aes_192_cfb128 = AnsiString('AES-192-CFB'); LN_aes_192_cfb128 = AnsiString('aes-192-cfb'); NID_aes_192_cfb128 = 425; SN_id_aes192_wrap = AnsiString('id-aes192-wrap'); NID_id_aes192_wrap = 789; SN_aes_192_gcm = AnsiString('id-aes192-GCM'); LN_aes_192_gcm = AnsiString('aes-192-gcm'); NID_aes_192_gcm = 898; SN_aes_192_ccm = AnsiString('id-aes192-CCM'); LN_aes_192_ccm = AnsiString('aes-192-ccm'); NID_aes_192_ccm = 899; SN_id_aes192_wrap_pad = AnsiString('id-aes192-wrap-pad'); NID_id_aes192_wrap_pad = 900; SN_aes_256_ecb = AnsiString('AES-256-ECB'); LN_aes_256_ecb = AnsiString('aes-256-ecb'); NID_aes_256_ecb = 426; SN_aes_256_cbc = AnsiString('AES-256-CBC'); LN_aes_256_cbc = AnsiString('aes-256-cbc'); NID_aes_256_cbc = 427; SN_aes_256_ofb128 = AnsiString('AES-256-OFB'); LN_aes_256_ofb128 = AnsiString('aes-256-ofb'); NID_aes_256_ofb128 = 428; SN_aes_256_cfb128 = AnsiString('AES-256-CFB'); LN_aes_256_cfb128 = AnsiString('aes-256-cfb'); NID_aes_256_cfb128 = 429; SN_id_aes256_wrap = AnsiString('id-aes256-wrap'); NID_id_aes256_wrap = 790; SN_aes_256_gcm = AnsiString('id-aes256-GCM'); LN_aes_256_gcm = AnsiString('aes-256-gcm'); NID_aes_256_gcm = 901; SN_aes_256_ccm = AnsiString('id-aes256-CCM'); LN_aes_256_ccm = AnsiString('aes-256-ccm'); NID_aes_256_ccm = 902; SN_id_aes256_wrap_pad = AnsiString('id-aes256-wrap-pad'); NID_id_aes256_wrap_pad = 903; SN_aes_128_xts = AnsiString('AES-128-XTS'); LN_aes_128_xts = AnsiString('aes-128-xts'); NID_aes_128_xts = 913; SN_aes_256_xts = AnsiString('AES-256-XTS'); LN_aes_256_xts = AnsiString('aes-256-xts'); NID_aes_256_xts = 914; SN_aes_128_cfb1 = AnsiString('AES-128-CFB1'); LN_aes_128_cfb1 = AnsiString('aes-128-cfb1'); NID_aes_128_cfb1 = 650; SN_aes_192_cfb1 = AnsiString('AES-192-CFB1'); LN_aes_192_cfb1 = AnsiString('aes-192-cfb1'); NID_aes_192_cfb1 = 651; SN_aes_256_cfb1 = AnsiString('AES-256-CFB1'); LN_aes_256_cfb1 = AnsiString('aes-256-cfb1'); NID_aes_256_cfb1 = 652; SN_aes_128_cfb8 = AnsiString('AES-128-CFB8'); LN_aes_128_cfb8 = AnsiString('aes-128-cfb8'); NID_aes_128_cfb8 = 653; SN_aes_192_cfb8 = AnsiString('AES-192-CFB8'); LN_aes_192_cfb8 = AnsiString('aes-192-cfb8'); NID_aes_192_cfb8 = 654; SN_aes_256_cfb8 = AnsiString('AES-256-CFB8'); LN_aes_256_cfb8 = AnsiString('aes-256-cfb8'); NID_aes_256_cfb8 = 655; SN_aes_128_ctr = AnsiString('AES-128-CTR'); LN_aes_128_ctr = AnsiString('aes-128-ctr'); NID_aes_128_ctr = 904; SN_aes_192_ctr = AnsiString('AES-192-CTR'); LN_aes_192_ctr = AnsiString('aes-192-ctr'); NID_aes_192_ctr = 905; SN_aes_256_ctr = AnsiString('AES-256-CTR'); LN_aes_256_ctr = AnsiString('aes-256-ctr'); NID_aes_256_ctr = 906; SN_aes_128_ocb = AnsiString('AES-128-OCB'); LN_aes_128_ocb = AnsiString('aes-128-ocb'); NID_aes_128_ocb = 958; SN_aes_192_ocb = AnsiString('AES-192-OCB'); LN_aes_192_ocb = AnsiString('aes-192-ocb'); NID_aes_192_ocb = 959; SN_aes_256_ocb = AnsiString('AES-256-OCB'); LN_aes_256_ocb = AnsiString('aes-256-ocb'); NID_aes_256_ocb = 960; SN_des_cfb1 = AnsiString('DES-CFB1'); LN_des_cfb1 = AnsiString('des-cfb1'); NID_des_cfb1 = 656; SN_des_cfb8 = AnsiString('DES-CFB8'); LN_des_cfb8 = AnsiString('des-cfb8'); NID_des_cfb8 = 657; SN_des_ede3_cfb1 = AnsiString('DES-EDE3-CFB1'); LN_des_ede3_cfb1 = AnsiString('des-ede3-cfb1'); NID_des_ede3_cfb1 = 658; SN_des_ede3_cfb8 = AnsiString('DES-EDE3-CFB8'); LN_des_ede3_cfb8 = AnsiString('des-ede3-cfb8'); NID_des_ede3_cfb8 = 659; SN_sha256 = AnsiString('SHA256'); LN_sha256 = AnsiString('sha256'); NID_sha256 = 672; SN_sha384 = AnsiString('SHA384'); LN_sha384 = AnsiString('sha384'); NID_sha384 = 673; SN_sha512 = AnsiString('SHA512'); LN_sha512 = AnsiString('sha512'); NID_sha512 = 674; SN_sha224 = AnsiString('SHA224'); LN_sha224 = AnsiString('sha224'); NID_sha224 = 675; SN_sha512_224 = AnsiString('SHA512-224'); LN_sha512_224 = AnsiString('sha512-224'); NID_sha512_224 = 1094; SN_sha512_256 = AnsiString('SHA512-256'); LN_sha512_256 = AnsiString('sha512-256'); NID_sha512_256 = 1095; SN_sha3_224 = AnsiString('SHA3-224'); LN_sha3_224 = AnsiString('sha3-224'); NID_sha3_224 = 1096; SN_sha3_256 = AnsiString('SHA3-256'); LN_sha3_256 = AnsiString('sha3-256'); NID_sha3_256 = 1097; SN_sha3_384 = AnsiString('SHA3-384'); LN_sha3_384 = AnsiString('sha3-384'); NID_sha3_384 = 1098; SN_sha3_512 = AnsiString('SHA3-512'); LN_sha3_512 = AnsiString('sha3-512'); NID_sha3_512 = 1099; SN_shake128 = AnsiString('SHAKE128'); LN_shake128 = AnsiString('shake128'); NID_shake128 = 1100; SN_shake256 = AnsiString('SHAKE256'); LN_shake256 = AnsiString('shake256'); NID_shake256 = 1101; SN_hmac_sha3_224 = AnsiString('id-hmacWithSHA3-224'); LN_hmac_sha3_224 = AnsiString('hmac-sha3-224'); NID_hmac_sha3_224 = 1102; SN_hmac_sha3_256 = AnsiString('id-hmacWithSHA3-256'); LN_hmac_sha3_256 = AnsiString('hmac-sha3-256'); NID_hmac_sha3_256 = 1103; SN_hmac_sha3_384 = AnsiString('id-hmacWithSHA3-384'); LN_hmac_sha3_384 = AnsiString('hmac-sha3-384'); NID_hmac_sha3_384 = 1104; SN_hmac_sha3_512 = AnsiString('id-hmacWithSHA3-512'); LN_hmac_sha3_512 = AnsiString('hmac-sha3-512'); NID_hmac_sha3_512 = 1105; SN_dsa_with_SHA224 = AnsiString('dsa_with_SHA224'); NID_dsa_with_SHA224 = 802; SN_dsa_with_SHA256 = AnsiString('dsa_with_SHA256'); NID_dsa_with_SHA256 = 803; SN_dsa_with_SHA384 = AnsiString('id-dsa-with-sha384'); LN_dsa_with_SHA384 = AnsiString('dsa_with_SHA384'); NID_dsa_with_SHA384 = 1106; SN_dsa_with_SHA512 = AnsiString('id-dsa-with-sha512'); LN_dsa_with_SHA512 = AnsiString('dsa_with_SHA512'); NID_dsa_with_SHA512 = 1107; SN_dsa_with_SHA3_224 = AnsiString('id-dsa-with-sha3-224'); LN_dsa_with_SHA3_224 = AnsiString('dsa_with_SHA3-224'); NID_dsa_with_SHA3_224 = 1108; SN_dsa_with_SHA3_256 = AnsiString('id-dsa-with-sha3-256'); LN_dsa_with_SHA3_256 = AnsiString('dsa_with_SHA3-256'); NID_dsa_with_SHA3_256 = 1109; SN_dsa_with_SHA3_384 = AnsiString('id-dsa-with-sha3-384'); LN_dsa_with_SHA3_384 = AnsiString('dsa_with_SHA3-384'); NID_dsa_with_SHA3_384 = 1110; SN_dsa_with_SHA3_512 = AnsiString('id-dsa-with-sha3-512'); LN_dsa_with_SHA3_512 = AnsiString('dsa_with_SHA3-512'); NID_dsa_with_SHA3_512 = 1111; SN_ecdsa_with_SHA3_224 = AnsiString('id-ecdsa-with-sha3-224'); LN_ecdsa_with_SHA3_224 = AnsiString('ecdsa_with_SHA3-224'); NID_ecdsa_with_SHA3_224 = 1112; SN_ecdsa_with_SHA3_256 = AnsiString('id-ecdsa-with-sha3-256'); LN_ecdsa_with_SHA3_256 = AnsiString('ecdsa_with_SHA3-256'); NID_ecdsa_with_SHA3_256 = 1113; SN_ecdsa_with_SHA3_384 = AnsiString('id-ecdsa-with-sha3-384'); LN_ecdsa_with_SHA3_384 = AnsiString('ecdsa_with_SHA3-384'); NID_ecdsa_with_SHA3_384 = 1114; SN_ecdsa_with_SHA3_512 = AnsiString('id-ecdsa-with-sha3-512'); LN_ecdsa_with_SHA3_512 = AnsiString('ecdsa_with_SHA3-512'); NID_ecdsa_with_SHA3_512 = 1115; SN_RSA_SHA3_224 = AnsiString('id-rsassa-pkcs1-v1_5-with-sha3-224'); LN_RSA_SHA3_224 = AnsiString('RSA-SHA3-224'); NID_RSA_SHA3_224 = 1116; SN_RSA_SHA3_256 = AnsiString('id-rsassa-pkcs1-v1_5-with-sha3-256'); LN_RSA_SHA3_256 = AnsiString('RSA-SHA3-256'); NID_RSA_SHA3_256 = 1117; SN_RSA_SHA3_384 = AnsiString('id-rsassa-pkcs1-v1_5-with-sha3-384'); LN_RSA_SHA3_384 = AnsiString('RSA-SHA3-384'); NID_RSA_SHA3_384 = 1118; SN_RSA_SHA3_512 = AnsiString('id-rsassa-pkcs1-v1_5-with-sha3-512'); LN_RSA_SHA3_512 = AnsiString('RSA-SHA3-512'); NID_RSA_SHA3_512 = 1119; SN_hold_instruction_code = AnsiString('holdInstructionCode'); LN_hold_instruction_code = AnsiString('Hold Instruction Code'); NID_hold_instruction_code = 430; SN_hold_instruction_none = AnsiString('holdInstructionNone'); LN_hold_instruction_none = AnsiString('Hold Instruction None'); NID_hold_instruction_none = 431; SN_hold_instruction_call_issuer = AnsiString('holdInstructionCallIssuer'); LN_hold_instruction_call_issuer = AnsiString('Hold Instruction Call Issuer'); NID_hold_instruction_call_issuer = 432; SN_hold_instruction_reject = AnsiString('holdInstructionReject'); LN_hold_instruction_reject = AnsiString('Hold Instruction Reject'); NID_hold_instruction_reject = 433; SN_data = AnsiString('data'); NID_data = 434; SN_pss = AnsiString('pss'); NID_pss = 435; SN_ucl = AnsiString('ucl'); NID_ucl = 436; SN_pilot = AnsiString('pilot'); NID_pilot = 437; LN_pilotAttributeType = AnsiString('pilotAttributeType'); NID_pilotAttributeType = 438; LN_pilotAttributeSyntax = AnsiString('pilotAttributeSyntax'); NID_pilotAttributeSyntax = 439; LN_pilotObjectClass = AnsiString('pilotObjectClass'); NID_pilotObjectClass = 440; LN_pilotGroups = AnsiString('pilotGroups'); NID_pilotGroups = 441; LN_iA5StringSyntax = AnsiString('iA5StringSyntax'); NID_iA5StringSyntax = 442; LN_caseIgnoreIA5StringSyntax = AnsiString('caseIgnoreIA5StringSyntax'); NID_caseIgnoreIA5StringSyntax = 443; LN_pilotObject = AnsiString('pilotObject'); NID_pilotObject = 444; LN_pilotPerson = AnsiString('pilotPerson'); NID_pilotPerson = 445; SN_account = AnsiString('account'); NID_account = 446; SN_document = AnsiString('document'); NID_document = 447; SN_room = AnsiString('room'); NID_room = 448; LN_documentSeries = AnsiString('documentSeries'); NID_documentSeries = 449; SN_Domain = AnsiString('domain'); LN_Domain = AnsiString('Domain'); NID_Domain = 392; LN_rFC822localPart = AnsiString('rFC822localPart'); NID_rFC822localPart = 450; LN_dNSDomain = AnsiString('dNSDomain'); NID_dNSDomain = 451; LN_domainRelatedObject = AnsiString('domainRelatedObject'); NID_domainRelatedObject = 452; LN_friendlyCountry = AnsiString('friendlyCountry'); NID_friendlyCountry = 453; LN_simpleSecurityObject = AnsiString('simpleSecurityObject'); NID_simpleSecurityObject = 454; LN_pilotOrganization = AnsiString('pilotOrganization'); NID_pilotOrganization = 455; LN_pilotDSA = AnsiString('pilotDSA'); NID_pilotDSA = 456; LN_qualityLabelledData = AnsiString('qualityLabelledData'); NID_qualityLabelledData = 457; SN_userId = AnsiString('UID'); LN_userId = AnsiString('userId'); NID_userId = 458; LN_textEncodedORAddress = AnsiString('textEncodedORAddress'); NID_textEncodedORAddress = 459; SN_rfc822Mailbox = AnsiString('mail'); LN_rfc822Mailbox = AnsiString('rfc822Mailbox'); NID_rfc822Mailbox = 460; SN_info = AnsiString('info'); NID_info = 461; LN_favouriteDrink = AnsiString('favouriteDrink'); NID_favouriteDrink = 462; LN_roomNumber = AnsiString('roomNumber'); NID_roomNumber = 463; SN_photo = AnsiString('photo'); NID_photo = 464; LN_userClass = AnsiString('userClass'); NID_userClass = 465; SN_host = AnsiString('host'); NID_host = 466; SN_manager = AnsiString('manager'); NID_manager = 467; LN_documentIdentifier = AnsiString('documentIdentifier'); NID_documentIdentifier = 468; LN_documentTitle = AnsiString('documentTitle'); NID_documentTitle = 469; LN_documentVersion = AnsiString('documentVersion'); NID_documentVersion = 470; LN_documentAuthor = AnsiString('documentAuthor'); NID_documentAuthor = 471; LN_documentLocation = AnsiString('documentLocation'); NID_documentLocation = 472; LN_homeTelephoneNumber = AnsiString('homeTelephoneNumber'); NID_homeTelephoneNumber = 473; SN_secretary = AnsiString('secretary'); NID_secretary = 474; LN_otherMailbox = AnsiString('otherMailbox'); NID_otherMailbox = 475; LN_lastModifiedTime = AnsiString('lastModifiedTime'); NID_lastModifiedTime = 476; LN_lastModifiedBy = AnsiString('lastModifiedBy'); NID_lastModifiedBy = 477; SN_domainComponent = AnsiString('DC'); LN_domainComponent = AnsiString('domainComponent'); NID_domainComponent = 391; LN_aRecord = AnsiString('aRecord'); NID_aRecord = 478; LN_pilotAttributeType27 = AnsiString('pilotAttributeType27'); NID_pilotAttributeType27 = 479; LN_mXRecord = AnsiString('mXRecord'); NID_mXRecord = 480; LN_nSRecord = AnsiString('nSRecord'); NID_nSRecord = 481; LN_sOARecord = AnsiString('sOARecord'); NID_sOARecord = 482; LN_cNAMERecord = AnsiString('cNAMERecord'); NID_cNAMERecord = 483; LN_associatedDomain = AnsiString('associatedDomain'); NID_associatedDomain = 484; LN_associatedName = AnsiString('associatedName'); NID_associatedName = 485; LN_homePostalAddress = AnsiString('homePostalAddress'); NID_homePostalAddress = 486; LN_personalTitle = AnsiString('personalTitle'); NID_personalTitle = 487; LN_mobileTelephoneNumber = AnsiString('mobileTelephoneNumber'); NID_mobileTelephoneNumber = 488; LN_pagerTelephoneNumber = AnsiString('pagerTelephoneNumber'); NID_pagerTelephoneNumber = 489; LN_friendlyCountryName = AnsiString('friendlyCountryName'); NID_friendlyCountryName = 490; SN_uniqueIdentifier = AnsiString('uid'); LN_uniqueIdentifier = AnsiString('uniqueIdentifier'); NID_uniqueIdentifier = 102; LN_organizationalStatus = AnsiString('organizationalStatus'); NID_organizationalStatus = 491; LN_janetMailbox = AnsiString('janetMailbox'); NID_janetMailbox = 492; LN_mailPreferenceOption = AnsiString('mailPreferenceOption'); NID_mailPreferenceOption = 493; LN_buildingName = AnsiString('buildingName'); NID_buildingName = 494; LN_dSAQuality = AnsiString('dSAQuality'); NID_dSAQuality = 495; LN_singleLevelQuality = AnsiString('singleLevelQuality'); NID_singleLevelQuality = 496; LN_subtreeMinimumQuality = AnsiString('subtreeMinimumQuality'); NID_subtreeMinimumQuality = 497; LN_subtreeMaximumQuality = AnsiString('subtreeMaximumQuality'); NID_subtreeMaximumQuality = 498; LN_personalSignature = AnsiString('personalSignature'); NID_personalSignature = 499; LN_dITRedirect = AnsiString('dITRedirect'); NID_dITRedirect = 500; SN_audio = AnsiString('audio'); NID_audio = 501; LN_documentPublisher = AnsiString('documentPublisher'); NID_documentPublisher = 502; SN_id_set = AnsiString('id-set'); LN_id_set = AnsiString('Secure Electronic Transactions'); NID_id_set = 512; SN_set_ctype = AnsiString('set-ctype'); LN_set_ctype = AnsiString('content types'); NID_set_ctype = 513; SN_set_msgExt = AnsiString('set-msgExt'); LN_set_msgExt = AnsiString('message extensions'); NID_set_msgExt = 514; SN_set_attr = AnsiString('set-attr'); NID_set_attr = 515; SN_set_policy = AnsiString('set-policy'); NID_set_policy = 516; SN_set_certExt = AnsiString('set-certExt'); LN_set_certExt = AnsiString('certificate extensions'); NID_set_certExt = 517; SN_set_brand = AnsiString('set-brand'); NID_set_brand = 518; SN_setct_PANData = AnsiString('setct-PANData'); NID_setct_PANData = 519; SN_setct_PANToken = AnsiString('setct-PANToken'); NID_setct_PANToken = 520; SN_setct_PANOnly = AnsiString('setct-PANOnly'); NID_setct_PANOnly = 521; SN_setct_OIData = AnsiString('setct-OIData'); NID_setct_OIData = 522; SN_setct_PI = AnsiString('setct-PI'); NID_setct_PI = 523; SN_setct_PIData = AnsiString('setct-PIData'); NID_setct_PIData = 524; SN_setct_PIDataUnsigned = AnsiString('setct-PIDataUnsigned'); NID_setct_PIDataUnsigned = 525; SN_setct_HODInput = AnsiString('setct-HODInput'); NID_setct_HODInput = 526; SN_setct_AuthResBaggage = AnsiString('setct-AuthResBaggage'); NID_setct_AuthResBaggage = 527; SN_setct_AuthRevReqBaggage = AnsiString('setct-AuthRevReqBaggage'); NID_setct_AuthRevReqBaggage = 528; SN_setct_AuthRevResBaggage = AnsiString('setct-AuthRevResBaggage'); NID_setct_AuthRevResBaggage = 529; SN_setct_CapTokenSeq = AnsiString('setct-CapTokenSeq'); NID_setct_CapTokenSeq = 530; SN_setct_PInitResData = AnsiString('setct-PInitResData'); NID_setct_PInitResData = 531; SN_setct_PI_TBS = AnsiString('setct-PI-TBS'); NID_setct_PI_TBS = 532; SN_setct_PResData = AnsiString('setct-PResData'); NID_setct_PResData = 533; SN_setct_AuthReqTBS = AnsiString('setct-AuthReqTBS'); NID_setct_AuthReqTBS = 534; SN_setct_AuthResTBS = AnsiString('setct-AuthResTBS'); NID_setct_AuthResTBS = 535; SN_setct_AuthResTBSX = AnsiString('setct-AuthResTBSX'); NID_setct_AuthResTBSX = 536; SN_setct_AuthTokenTBS = AnsiString('setct-AuthTokenTBS'); NID_setct_AuthTokenTBS = 537; SN_setct_CapTokenData = AnsiString('setct-CapTokenData'); NID_setct_CapTokenData = 538; SN_setct_CapTokenTBS = AnsiString('setct-CapTokenTBS'); NID_setct_CapTokenTBS = 539; SN_setct_AcqCardCodeMsg = AnsiString('setct-AcqCardCodeMsg'); NID_setct_AcqCardCodeMsg = 540; SN_setct_AuthRevReqTBS = AnsiString('setct-AuthRevReqTBS'); NID_setct_AuthRevReqTBS = 541; SN_setct_AuthRevResData = AnsiString('setct-AuthRevResData'); NID_setct_AuthRevResData = 542; SN_setct_AuthRevResTBS = AnsiString('setct-AuthRevResTBS'); NID_setct_AuthRevResTBS = 543; SN_setct_CapReqTBS = AnsiString('setct-CapReqTBS'); NID_setct_CapReqTBS = 544; SN_setct_CapReqTBSX = AnsiString('setct-CapReqTBSX'); NID_setct_CapReqTBSX = 545; SN_setct_CapResData = AnsiString('setct-CapResData'); NID_setct_CapResData = 546; SN_setct_CapRevReqTBS = AnsiString('setct-CapRevReqTBS'); NID_setct_CapRevReqTBS = 547; SN_setct_CapRevReqTBSX = AnsiString('setct-CapRevReqTBSX'); NID_setct_CapRevReqTBSX = 548; SN_setct_CapRevResData = AnsiString('setct-CapRevResData'); NID_setct_CapRevResData = 549; SN_setct_CredReqTBS = AnsiString('setct-CredReqTBS'); NID_setct_CredReqTBS = 550; SN_setct_CredReqTBSX = AnsiString('setct-CredReqTBSX'); NID_setct_CredReqTBSX = 551; SN_setct_CredResData = AnsiString('setct-CredResData'); NID_setct_CredResData = 552; SN_setct_CredRevReqTBS = AnsiString('setct-CredRevReqTBS'); NID_setct_CredRevReqTBS = 553; SN_setct_CredRevReqTBSX = AnsiString('setct-CredRevReqTBSX'); NID_setct_CredRevReqTBSX = 554; SN_setct_CredRevResData = AnsiString('setct-CredRevResData'); NID_setct_CredRevResData = 555; SN_setct_PCertReqData = AnsiString('setct-PCertReqData'); NID_setct_PCertReqData = 556; SN_setct_PCertResTBS = AnsiString('setct-PCertResTBS'); NID_setct_PCertResTBS = 557; SN_setct_BatchAdminReqData = AnsiString('setct-BatchAdminReqData'); NID_setct_BatchAdminReqData = 558; SN_setct_BatchAdminResData = AnsiString('setct-BatchAdminResData'); NID_setct_BatchAdminResData = 559; SN_setct_CardCInitResTBS = AnsiString('setct-CardCInitResTBS'); NID_setct_CardCInitResTBS = 560; SN_setct_MeAqCInitResTBS = AnsiString('setct-MeAqCInitResTBS'); NID_setct_MeAqCInitResTBS = 561; SN_setct_RegFormResTBS = AnsiString('setct-RegFormResTBS'); NID_setct_RegFormResTBS = 562; SN_setct_CertReqData = AnsiString('setct-CertReqData'); NID_setct_CertReqData = 563; SN_setct_CertReqTBS = AnsiString('setct-CertReqTBS'); NID_setct_CertReqTBS = 564; SN_setct_CertResData = AnsiString('setct-CertResData'); NID_setct_CertResData = 565; SN_setct_CertInqReqTBS = AnsiString('setct-CertInqReqTBS'); NID_setct_CertInqReqTBS = 566; SN_setct_ErrorTBS = AnsiString('setct-ErrorTBS'); NID_setct_ErrorTBS = 567; SN_setct_PIDualSignedTBE = AnsiString('setct-PIDualSignedTBE'); NID_setct_PIDualSignedTBE = 568; SN_setct_PIUnsignedTBE = AnsiString('setct-PIUnsignedTBE'); NID_setct_PIUnsignedTBE = 569; SN_setct_AuthReqTBE = AnsiString('setct-AuthReqTBE'); NID_setct_AuthReqTBE = 570; SN_setct_AuthResTBE = AnsiString('setct-AuthResTBE'); NID_setct_AuthResTBE = 571; SN_setct_AuthResTBEX = AnsiString('setct-AuthResTBEX'); NID_setct_AuthResTBEX = 572; SN_setct_AuthTokenTBE = AnsiString('setct-AuthTokenTBE'); NID_setct_AuthTokenTBE = 573; SN_setct_CapTokenTBE = AnsiString('setct-CapTokenTBE'); NID_setct_CapTokenTBE = 574; SN_setct_CapTokenTBEX = AnsiString('setct-CapTokenTBEX'); NID_setct_CapTokenTBEX = 575; SN_setct_AcqCardCodeMsgTBE = AnsiString('setct-AcqCardCodeMsgTBE'); NID_setct_AcqCardCodeMsgTBE = 576; SN_setct_AuthRevReqTBE = AnsiString('setct-AuthRevReqTBE'); NID_setct_AuthRevReqTBE = 577; SN_setct_AuthRevResTBE = AnsiString('setct-AuthRevResTBE'); NID_setct_AuthRevResTBE = 578; SN_setct_AuthRevResTBEB = AnsiString('setct-AuthRevResTBEB'); NID_setct_AuthRevResTBEB = 579; SN_setct_CapReqTBE = AnsiString('setct-CapReqTBE'); NID_setct_CapReqTBE = 580; SN_setct_CapReqTBEX = AnsiString('setct-CapReqTBEX'); NID_setct_CapReqTBEX = 581; SN_setct_CapResTBE = AnsiString('setct-CapResTBE'); NID_setct_CapResTBE = 582; SN_setct_CapRevReqTBE = AnsiString('setct-CapRevReqTBE'); NID_setct_CapRevReqTBE = 583; SN_setct_CapRevReqTBEX = AnsiString('setct-CapRevReqTBEX'); NID_setct_CapRevReqTBEX = 584; SN_setct_CapRevResTBE = AnsiString('setct-CapRevResTBE'); NID_setct_CapRevResTBE = 585; SN_setct_CredReqTBE = AnsiString('setct-CredReqTBE'); NID_setct_CredReqTBE = 586; SN_setct_CredReqTBEX = AnsiString('setct-CredReqTBEX'); NID_setct_CredReqTBEX = 587; SN_setct_CredResTBE = AnsiString('setct-CredResTBE'); NID_setct_CredResTBE = 588; SN_setct_CredRevReqTBE = AnsiString('setct-CredRevReqTBE'); NID_setct_CredRevReqTBE = 589; SN_setct_CredRevReqTBEX = AnsiString('setct-CredRevReqTBEX'); NID_setct_CredRevReqTBEX = 590; SN_setct_CredRevResTBE = AnsiString('setct-CredRevResTBE'); NID_setct_CredRevResTBE = 591; SN_setct_BatchAdminReqTBE = AnsiString('setct-BatchAdminReqTBE'); NID_setct_BatchAdminReqTBE = 592; SN_setct_BatchAdminResTBE = AnsiString('setct-BatchAdminResTBE'); NID_setct_BatchAdminResTBE = 593; SN_setct_RegFormReqTBE = AnsiString('setct-RegFormReqTBE'); NID_setct_RegFormReqTBE = 594; SN_setct_CertReqTBE = AnsiString('setct-CertReqTBE'); NID_setct_CertReqTBE = 595; SN_setct_CertReqTBEX = AnsiString('setct-CertReqTBEX'); NID_setct_CertReqTBEX = 596; SN_setct_CertResTBE = AnsiString('setct-CertResTBE'); NID_setct_CertResTBE = 597; SN_setct_CRLNotificationTBS = AnsiString('setct-CRLNotificationTBS'); NID_setct_CRLNotificationTBS = 598; SN_setct_CRLNotificationResTBS = AnsiString('setct-CRLNotificationResTBS'); NID_setct_CRLNotificationResTBS = 599; SN_setct_BCIDistributionTBS = AnsiString('setct-BCIDistributionTBS'); NID_setct_BCIDistributionTBS = 600; SN_setext_genCrypt = AnsiString('setext-genCrypt'); LN_setext_genCrypt = AnsiString('generic cryptogram'); NID_setext_genCrypt = 601; SN_setext_miAuth = AnsiString('setext-miAuth'); LN_setext_miAuth = AnsiString('merchant initiated auth'); NID_setext_miAuth = 602; SN_setext_pinSecure = AnsiString('setext-pinSecure'); NID_setext_pinSecure = 603; SN_setext_pinAny = AnsiString('setext-pinAny'); NID_setext_pinAny = 604; SN_setext_track2 = AnsiString('setext-track2'); NID_setext_track2 = 605; SN_setext_cv = AnsiString('setext-cv'); LN_setext_cv = AnsiString('additional verification'); NID_setext_cv = 606; SN_set_policy_root = AnsiString('set-policy-root'); NID_set_policy_root = 607; SN_setCext_hashedRoot = AnsiString('setCext-hashedRoot'); NID_setCext_hashedRoot = 608; SN_setCext_certType = AnsiString('setCext-certType'); NID_setCext_certType = 609; SN_setCext_merchData = AnsiString('setCext-merchData'); NID_setCext_merchData = 610; SN_setCext_cCertRequired = AnsiString('setCext-cCertRequired'); NID_setCext_cCertRequired = 611; SN_setCext_tunneling = AnsiString('setCext-tunneling'); NID_setCext_tunneling = 612; SN_setCext_setExt = AnsiString('setCext-setExt'); NID_setCext_setExt = 613; SN_setCext_setQualf = AnsiString('setCext-setQualf'); NID_setCext_setQualf = 614; SN_setCext_PGWYcapabilities = AnsiString('setCext-PGWYcapabilities'); NID_setCext_PGWYcapabilities = 615; SN_setCext_TokenIdentifier = AnsiString('setCext-TokenIdentifier'); NID_setCext_TokenIdentifier = 616; SN_setCext_Track2Data = AnsiString('setCext-Track2Data'); NID_setCext_Track2Data = 617; SN_setCext_TokenType = AnsiString('setCext-TokenType'); NID_setCext_TokenType = 618; SN_setCext_IssuerCapabilities = AnsiString('setCext-IssuerCapabilities'); NID_setCext_IssuerCapabilities = 619; SN_setAttr_Cert = AnsiString('setAttr-Cert'); NID_setAttr_Cert = 620; SN_setAttr_PGWYcap = AnsiString('setAttr-PGWYcap'); LN_setAttr_PGWYcap = AnsiString('payment gateway capabilities'); NID_setAttr_PGWYcap = 621; SN_setAttr_TokenType = AnsiString('setAttr-TokenType'); NID_setAttr_TokenType = 622; SN_setAttr_IssCap = AnsiString('setAttr-IssCap'); LN_setAttr_IssCap = AnsiString('issuer capabilities'); NID_setAttr_IssCap = 623; SN_set_rootKeyThumb = AnsiString('set-rootKeyThumb'); NID_set_rootKeyThumb = 624; SN_set_addPolicy = AnsiString('set-addPolicy'); NID_set_addPolicy = 625; SN_setAttr_Token_EMV = AnsiString('setAttr-Token-EMV'); NID_setAttr_Token_EMV = 626; SN_setAttr_Token_B0Prime = AnsiString('setAttr-Token-B0Prime'); NID_setAttr_Token_B0Prime = 627; SN_setAttr_IssCap_CVM = AnsiString('setAttr-IssCap-CVM'); NID_setAttr_IssCap_CVM = 628; SN_setAttr_IssCap_T2 = AnsiString('setAttr-IssCap-T2'); NID_setAttr_IssCap_T2 = 629; SN_setAttr_IssCap_Sig = AnsiString('setAttr-IssCap-Sig'); NID_setAttr_IssCap_Sig = 630; SN_setAttr_GenCryptgrm = AnsiString('setAttr-GenCryptgrm'); LN_setAttr_GenCryptgrm = AnsiString('generate cryptogram'); NID_setAttr_GenCryptgrm = 631; SN_setAttr_T2Enc = AnsiString('setAttr-T2Enc'); LN_setAttr_T2Enc = AnsiString('encrypted track 2'); NID_setAttr_T2Enc = 632; SN_setAttr_T2cleartxt = AnsiString('setAttr-T2cleartxt'); LN_setAttr_T2cleartxt = AnsiString('cleartext track 2'); NID_setAttr_T2cleartxt = 633; SN_setAttr_TokICCsig = AnsiString('setAttr-TokICCsig'); LN_setAttr_TokICCsig = AnsiString('ICC or token signature'); NID_setAttr_TokICCsig = 634; SN_setAttr_SecDevSig = AnsiString('setAttr-SecDevSig'); LN_setAttr_SecDevSig = AnsiString('secure device signature'); NID_setAttr_SecDevSig = 635; SN_set_brand_IATA_ATA = AnsiString('set-brand-IATA-ATA'); NID_set_brand_IATA_ATA = 636; SN_set_brand_Diners = AnsiString('set-brand-Diners'); NID_set_brand_Diners = 637; SN_set_brand_AmericanExpress = AnsiString('set-brand-AmericanExpress'); NID_set_brand_AmericanExpress = 638; SN_set_brand_JCB = AnsiString('set-brand-JCB'); NID_set_brand_JCB = 639; SN_set_brand_Visa = AnsiString('set-brand-Visa'); NID_set_brand_Visa = 640; SN_set_brand_MasterCard = AnsiString('set-brand-MasterCard'); NID_set_brand_MasterCard = 641; SN_set_brand_Novus = AnsiString('set-brand-Novus'); NID_set_brand_Novus = 642; SN_des_cdmf = AnsiString('DES-CDMF'); LN_des_cdmf = AnsiString('des-cdmf'); NID_des_cdmf = 643; SN_rsaOAEPEncryptionSET = AnsiString('rsaOAEPEncryptionSET'); NID_rsaOAEPEncryptionSET = 644; SN_ipsec3 = AnsiString('Oakley-EC2N-3'); LN_ipsec3 = AnsiString('ipsec3'); NID_ipsec3 = 749; SN_ipsec4 = AnsiString('Oakley-EC2N-4'); LN_ipsec4 = AnsiString('ipsec4'); NID_ipsec4 = 750; SN_whirlpool = AnsiString('whirlpool'); NID_whirlpool = 804; SN_cryptopro = AnsiString('cryptopro'); NID_cryptopro = 805; SN_cryptocom = AnsiString('cryptocom'); NID_cryptocom = 806; SN_id_tc26 = AnsiString('id-tc26'); NID_id_tc26 = 974; SN_id_GostR3411_94_with_GostR3410_2001 = AnsiString('id-GostR3411-94-with-GostR3410-2001'); LN_id_GostR3411_94_with_GostR3410_2001 = AnsiString('GOST R 34.11-94 with GOST R 34.10-2001'); NID_id_GostR3411_94_with_GostR3410_2001 = 807; SN_id_GostR3411_94_with_GostR3410_94 = AnsiString('id-GostR3411-94-with-GostR3410-94'); LN_id_GostR3411_94_with_GostR3410_94 = AnsiString('GOST R 34.11-94 with GOST R 34.10-94'); NID_id_GostR3411_94_with_GostR3410_94 = 808; SN_id_GostR3411_94 = AnsiString('md_gost94'); LN_id_GostR3411_94 = AnsiString('GOST R 34.11-94'); NID_id_GostR3411_94 = 809; SN_id_HMACGostR3411_94 = AnsiString('id-HMACGostR3411-94'); LN_id_HMACGostR3411_94 = AnsiString('HMAC GOST 34.11-94'); NID_id_HMACGostR3411_94 = 810; SN_id_GostR3410_2001 = AnsiString('gost2001'); LN_id_GostR3410_2001 = AnsiString('GOST R 34.10-2001'); NID_id_GostR3410_2001 = 811; SN_id_GostR3410_94 = AnsiString('gost94'); LN_id_GostR3410_94 = AnsiString('GOST R 34.10-94'); NID_id_GostR3410_94 = 812; SN_id_Gost28147_89 = AnsiString('gost89'); LN_id_Gost28147_89 = AnsiString('GOST 28147-89'); NID_id_Gost28147_89 = 813; SN_gost89_cnt = AnsiString('gost89-cnt'); NID_gost89_cnt = 814; SN_gost89_cnt_12 = AnsiString('gost89-cnt-12'); NID_gost89_cnt_12 = 975; SN_gost89_cbc = AnsiString('gost89-cbc'); NID_gost89_cbc = 1009; SN_gost89_ecb = AnsiString('gost89-ecb'); NID_gost89_ecb = 1010; SN_gost89_ctr = AnsiString('gost89-ctr'); NID_gost89_ctr = 1011; SN_id_Gost28147_89_MAC = AnsiString('gost-mac'); LN_id_Gost28147_89_MAC = AnsiString('GOST 28147-89 MAC'); NID_id_Gost28147_89_MAC = 815; SN_gost_mac_12 = AnsiString('gost-mac-12'); NID_gost_mac_12 = 976; SN_id_GostR3411_94_prf = AnsiString('prf-gostr3411-94'); LN_id_GostR3411_94_prf = AnsiString('GOST R 34.11-94 PRF'); NID_id_GostR3411_94_prf = 816; SN_id_GostR3410_2001DH = AnsiString('id-GostR3410-2001DH'); LN_id_GostR3410_2001DH = AnsiString('GOST R 34.10-2001 DH'); NID_id_GostR3410_2001DH = 817; SN_id_GostR3410_94DH = AnsiString('id-GostR3410-94DH'); LN_id_GostR3410_94DH = AnsiString('GOST R 34.10-94 DH'); NID_id_GostR3410_94DH = 818; SN_id_Gost28147_89_CryptoPro_KeyMeshing = AnsiString('id-Gost28147-89-CryptoPro-KeyMeshing'); NID_id_Gost28147_89_CryptoPro_KeyMeshing = 819; SN_id_Gost28147_89_None_KeyMeshing = AnsiString('id-Gost28147-89-None-KeyMeshing'); NID_id_Gost28147_89_None_KeyMeshing = 820; SN_id_GostR3411_94_TestParamSet = AnsiString('id-GostR3411-94-TestParamSet'); NID_id_GostR3411_94_TestParamSet = 821; SN_id_GostR3411_94_CryptoProParamSet = AnsiString('id-GostR3411-94-CryptoProParamSet'); NID_id_GostR3411_94_CryptoProParamSet = 822; SN_id_Gost28147_89_TestParamSet = AnsiString('id-Gost28147-89-TestParamSet'); NID_id_Gost28147_89_TestParamSet = 823; SN_id_Gost28147_89_CryptoPro_A_ParamSet = AnsiString('id-Gost28147-89-CryptoPro-A-ParamSet'); NID_id_Gost28147_89_CryptoPro_A_ParamSet = 824; SN_id_Gost28147_89_CryptoPro_B_ParamSet = AnsiString('id-Gost28147-89-CryptoPro-B-ParamSet'); NID_id_Gost28147_89_CryptoPro_B_ParamSet = 825; SN_id_Gost28147_89_CryptoPro_C_ParamSet = AnsiString('id-Gost28147-89-CryptoPro-C-ParamSet'); NID_id_Gost28147_89_CryptoPro_C_ParamSet = 826; SN_id_Gost28147_89_CryptoPro_D_ParamSet = AnsiString('id-Gost28147-89-CryptoPro-D-ParamSet'); NID_id_Gost28147_89_CryptoPro_D_ParamSet = 827; SN_id_Gost28147_89_CryptoPro_Oscar_1_1_ParamSet = AnsiString('id-Gost28147-89-CryptoPro-Oscar-1-1-ParamSet'); NID_id_Gost28147_89_CryptoPro_Oscar_1_1_ParamSet = 828; SN_id_Gost28147_89_CryptoPro_Oscar_1_0_ParamSet = AnsiString('id-Gost28147-89-CryptoPro-Oscar-1-0-ParamSet'); NID_id_Gost28147_89_CryptoPro_Oscar_1_0_ParamSet = 829; SN_id_Gost28147_89_CryptoPro_RIC_1_ParamSet = AnsiString('id-Gost28147-89-CryptoPro-RIC-1-ParamSet'); NID_id_Gost28147_89_CryptoPro_RIC_1_ParamSet = 830; SN_id_GostR3410_94_TestParamSet = AnsiString('id-GostR3410-94-TestParamSet'); NID_id_GostR3410_94_TestParamSet = 831; SN_id_GostR3410_94_CryptoPro_A_ParamSet = AnsiString('id-GostR3410-94-CryptoPro-A-ParamSet'); NID_id_GostR3410_94_CryptoPro_A_ParamSet = 832; SN_id_GostR3410_94_CryptoPro_B_ParamSet = AnsiString('id-GostR3410-94-CryptoPro-B-ParamSet'); NID_id_GostR3410_94_CryptoPro_B_ParamSet = 833; SN_id_GostR3410_94_CryptoPro_C_ParamSet = AnsiString('id-GostR3410-94-CryptoPro-C-ParamSet'); NID_id_GostR3410_94_CryptoPro_C_ParamSet = 834; SN_id_GostR3410_94_CryptoPro_D_ParamSet = AnsiString('id-GostR3410-94-CryptoPro-D-ParamSet'); NID_id_GostR3410_94_CryptoPro_D_ParamSet = 835; SN_id_GostR3410_94_CryptoPro_XchA_ParamSet = AnsiString('id-GostR3410-94-CryptoPro-XchA-ParamSet'); NID_id_GostR3410_94_CryptoPro_XchA_ParamSet = 836; SN_id_GostR3410_94_CryptoPro_XchB_ParamSet = AnsiString('id-GostR3410-94-CryptoPro-XchB-ParamSet'); NID_id_GostR3410_94_CryptoPro_XchB_ParamSet = 837; SN_id_GostR3410_94_CryptoPro_XchC_ParamSet = AnsiString('id-GostR3410-94-CryptoPro-XchC-ParamSet'); NID_id_GostR3410_94_CryptoPro_XchC_ParamSet = 838; SN_id_GostR3410_2001_TestParamSet = AnsiString('id-GostR3410-2001-TestParamSet'); NID_id_GostR3410_2001_TestParamSet = 839; SN_id_GostR3410_2001_CryptoPro_A_ParamSet = AnsiString('id-GostR3410-2001-CryptoPro-A-ParamSet'); NID_id_GostR3410_2001_CryptoPro_A_ParamSet = 840; SN_id_GostR3410_2001_CryptoPro_B_ParamSet = AnsiString('id-GostR3410-2001-CryptoPro-B-ParamSet'); NID_id_GostR3410_2001_CryptoPro_B_ParamSet = 841; SN_id_GostR3410_2001_CryptoPro_C_ParamSet = AnsiString('id-GostR3410-2001-CryptoPro-C-ParamSet'); NID_id_GostR3410_2001_CryptoPro_C_ParamSet = 842; SN_id_GostR3410_2001_CryptoPro_XchA_ParamSet = AnsiString('id-GostR3410-2001-CryptoPro-XchA-ParamSet'); NID_id_GostR3410_2001_CryptoPro_XchA_ParamSet = 843; SN_id_GostR3410_2001_CryptoPro_XchB_ParamSet = AnsiString('id-GostR3410-2001-CryptoPro-XchB-ParamSet'); NID_id_GostR3410_2001_CryptoPro_XchB_ParamSet = 844; SN_id_GostR3410_94_a = AnsiString('id-GostR3410-94-a'); NID_id_GostR3410_94_a = 845; SN_id_GostR3410_94_aBis = AnsiString('id-GostR3410-94-aBis'); NID_id_GostR3410_94_aBis = 846; SN_id_GostR3410_94_b = AnsiString('id-GostR3410-94-b'); NID_id_GostR3410_94_b = 847; SN_id_GostR3410_94_bBis = AnsiString('id-GostR3410-94-bBis'); NID_id_GostR3410_94_bBis = 848; SN_id_Gost28147_89_cc = AnsiString('id-Gost28147-89-cc'); LN_id_Gost28147_89_cc = AnsiString('GOST 28147-89 Cryptocom ParamSet'); NID_id_Gost28147_89_cc = 849; SN_id_GostR3410_94_cc = AnsiString('gost94cc'); LN_id_GostR3410_94_cc = AnsiString('GOST 34.10-94 Cryptocom'); NID_id_GostR3410_94_cc = 850; SN_id_GostR3410_2001_cc = AnsiString('gost2001cc'); LN_id_GostR3410_2001_cc = AnsiString('GOST 34.10-2001 Cryptocom'); NID_id_GostR3410_2001_cc = 851; SN_id_GostR3411_94_with_GostR3410_94_cc = AnsiString('id-GostR3411-94-with-GostR3410-94-cc'); LN_id_GostR3411_94_with_GostR3410_94_cc = AnsiString('GOST R 34.11-94 with GOST R 34.10-94 Cryptocom'); NID_id_GostR3411_94_with_GostR3410_94_cc = 852; SN_id_GostR3411_94_with_GostR3410_2001_cc = AnsiString('id-GostR3411-94-with-GostR3410-2001-cc'); LN_id_GostR3411_94_with_GostR3410_2001_cc = AnsiString('GOST R 34.11-94 with GOST R 34.10-2001 Cryptocom'); NID_id_GostR3411_94_with_GostR3410_2001_cc = 853; SN_id_GostR3410_2001_ParamSet_cc = AnsiString('id-GostR3410-2001-ParamSet-cc'); LN_id_GostR3410_2001_ParamSet_cc = AnsiString('GOST R 3410-2001 Parameter Set Cryptocom'); NID_id_GostR3410_2001_ParamSet_cc = 854; SN_id_tc26_algorithms = AnsiString('id-tc26-algorithms'); NID_id_tc26_algorithms = 977; SN_id_tc26_sign = AnsiString('id-tc26-sign'); NID_id_tc26_sign = 978; SN_id_GostR3410_2012_256 = AnsiString('gost2012_256'); LN_id_GostR3410_2012_256 = AnsiString('GOST R 34.10-2012 with 256 bit modulus'); NID_id_GostR3410_2012_256 = 979; SN_id_GostR3410_2012_512 = AnsiString('gost2012_512'); LN_id_GostR3410_2012_512 = AnsiString('GOST R 34.10-2012 with 512 bit modulus'); NID_id_GostR3410_2012_512 = 980; SN_id_tc26_digest = AnsiString('id-tc26-digest'); NID_id_tc26_digest = 981; SN_id_GostR3411_2012_256 = AnsiString('md_gost12_256'); LN_id_GostR3411_2012_256 = AnsiString('GOST R 34.11-2012 with 256 bit hash'); NID_id_GostR3411_2012_256 = 982; SN_id_GostR3411_2012_512 = AnsiString('md_gost12_512'); LN_id_GostR3411_2012_512 = AnsiString('GOST R 34.11-2012 with 512 bit hash'); NID_id_GostR3411_2012_512 = 983; SN_id_tc26_signwithdigest = AnsiString('id-tc26-signwithdigest'); NID_id_tc26_signwithdigest = 984; SN_id_tc26_signwithdigest_gost3410_2012_256 = AnsiString('id-tc26-signwithdigest-gost3410-2012-256'); LN_id_tc26_signwithdigest_gost3410_2012_256 = AnsiString('GOST R 34.10-2012 with GOST R 34.11-2012(256 bit)'); NID_id_tc26_signwithdigest_gost3410_2012_256 = 985; SN_id_tc26_signwithdigest_gost3410_2012_512 = AnsiString('id-tc26-signwithdigest-gost3410-2012-512'); LN_id_tc26_signwithdigest_gost3410_2012_512 = AnsiString('GOST R 34.10-2012 with GOST R 34.11-2012(512 bit)'); NID_id_tc26_signwithdigest_gost3410_2012_512 = 986; SN_id_tc26_mac = AnsiString('id-tc26-mac'); NID_id_tc26_mac = 987; SN_id_tc26_hmac_gost_3411_2012_256 = AnsiString('id-tc26-hmac-gost-3411-2012-256'); LN_id_tc26_hmac_gost_3411_2012_256 = AnsiString('HMAC GOST 34.11-2012 256 bit'); NID_id_tc26_hmac_gost_3411_2012_256 = 988; SN_id_tc26_hmac_gost_3411_2012_512 = AnsiString('id-tc26-hmac-gost-3411-2012-512'); LN_id_tc26_hmac_gost_3411_2012_512 = AnsiString('HMAC GOST 34.11-2012 512 bit'); NID_id_tc26_hmac_gost_3411_2012_512 = 989; SN_id_tc26_cipher = AnsiString('id-tc26-cipher'); NID_id_tc26_cipher = 990; SN_id_tc26_cipher_gostr3412_2015_magma = AnsiString('id-tc26-cipher-gostr3412-2015-magma'); NID_id_tc26_cipher_gostr3412_2015_magma = 1173; SN_id_tc26_cipher_gostr3412_2015_magma_ctracpkm = AnsiString('id-tc26-cipher-gostr3412-2015-magma-ctracpkm'); NID_id_tc26_cipher_gostr3412_2015_magma_ctracpkm = 1174; SN_id_tc26_cipher_gostr3412_2015_magma_ctracpkm_omac = AnsiString('id-tc26-cipher-gostr3412-2015-magma-ctracpkm-omac'); NID_id_tc26_cipher_gostr3412_2015_magma_ctracpkm_omac = 1175; SN_id_tc26_cipher_gostr3412_2015_kuznyechik = AnsiString('id-tc26-cipher-gostr3412-2015-kuznyechik'); NID_id_tc26_cipher_gostr3412_2015_kuznyechik = 1176; SN_id_tc26_cipher_gostr3412_2015_kuznyechik_ctracpkm = AnsiString('id-tc26-cipher-gostr3412-2015-kuznyechik-ctracpkm'); NID_id_tc26_cipher_gostr3412_2015_kuznyechik_ctracpkm = 1177; SN_id_tc26_cipher_gostr3412_2015_kuznyechik_ctracpkm_omac = AnsiString('id-tc26-cipher-gostr3412-2015-kuznyechik-ctracpkm-omac'); NID_id_tc26_cipher_gostr3412_2015_kuznyechik_ctracpkm_omac = 1178; SN_id_tc26_agreement = AnsiString('id-tc26-agreement'); NID_id_tc26_agreement = 991; SN_id_tc26_agreement_gost_3410_2012_256 = AnsiString('id-tc26-agreement-gost-3410-2012-256'); NID_id_tc26_agreement_gost_3410_2012_256 = 992; SN_id_tc26_agreement_gost_3410_2012_512 = AnsiString('id-tc26-agreement-gost-3410-2012-512'); NID_id_tc26_agreement_gost_3410_2012_512 = 993; SN_id_tc26_wrap = AnsiString('id-tc26-wrap'); NID_id_tc26_wrap = 1179; SN_id_tc26_wrap_gostr3412_2015_magma = AnsiString('id-tc26-wrap-gostr3412-2015-magma'); NID_id_tc26_wrap_gostr3412_2015_magma = 1180; SN_id_tc26_wrap_gostr3412_2015_magma_kexp15 = AnsiString('id-tc26-wrap-gostr3412-2015-magma-kexp15'); NID_id_tc26_wrap_gostr3412_2015_magma_kexp15 = 1181; SN_id_tc26_wrap_gostr3412_2015_kuznyechik = AnsiString('id-tc26-wrap-gostr3412-2015-kuznyechik'); NID_id_tc26_wrap_gostr3412_2015_kuznyechik = 1182; SN_id_tc26_wrap_gostr3412_2015_kuznyechik_kexp15 = AnsiString('id-tc26-wrap-gostr3412-2015-kuznyechik-kexp15'); NID_id_tc26_wrap_gostr3412_2015_kuznyechik_kexp15 = 1183; SN_id_tc26_constants = AnsiString('id-tc26-constants'); NID_id_tc26_constants = 994; SN_id_tc26_sign_constants = AnsiString('id-tc26-sign-constants'); NID_id_tc26_sign_constants = 995; SN_id_tc26_gost_3410_2012_256_constants = AnsiString('id-tc26-gost-3410-2012-256-constants'); NID_id_tc26_gost_3410_2012_256_constants = 1147; SN_id_tc26_gost_3410_2012_256_paramSetA = AnsiString('id-tc26-gost-3410-2012-256-paramSetA'); LN_id_tc26_gost_3410_2012_256_paramSetA = AnsiString('GOST R 34.10-2012(256 bit)ParamSet A'); NID_id_tc26_gost_3410_2012_256_paramSetA = 1148; SN_id_tc26_gost_3410_2012_256_paramSetB = AnsiString('id-tc26-gost-3410-2012-256-paramSetB'); LN_id_tc26_gost_3410_2012_256_paramSetB = AnsiString('GOST R 34.10-2012(256 bit)ParamSet B'); NID_id_tc26_gost_3410_2012_256_paramSetB = 1184; SN_id_tc26_gost_3410_2012_256_paramSetC = AnsiString('id-tc26-gost-3410-2012-256-paramSetC'); LN_id_tc26_gost_3410_2012_256_paramSetC = AnsiString('GOST R 34.10-2012(256 bit)ParamSet C'); NID_id_tc26_gost_3410_2012_256_paramSetC = 1185; SN_id_tc26_gost_3410_2012_256_paramSetD = AnsiString('id-tc26-gost-3410-2012-256-paramSetD'); LN_id_tc26_gost_3410_2012_256_paramSetD = AnsiString('GOST R 34.10-2012(256 bit)ParamSet D'); NID_id_tc26_gost_3410_2012_256_paramSetD = 1186; SN_id_tc26_gost_3410_2012_512_constants = AnsiString('id-tc26-gost-3410-2012-512-constants'); NID_id_tc26_gost_3410_2012_512_constants = 996; SN_id_tc26_gost_3410_2012_512_paramSetTest = AnsiString('id-tc26-gost-3410-2012-512-paramSetTest'); LN_id_tc26_gost_3410_2012_512_paramSetTest = AnsiString('GOST R 34.10-2012(512 bit)testing parameter set'); NID_id_tc26_gost_3410_2012_512_paramSetTest = 997; SN_id_tc26_gost_3410_2012_512_paramSetA = AnsiString('id-tc26-gost-3410-2012-512-paramSetA'); LN_id_tc26_gost_3410_2012_512_paramSetA = AnsiString('GOST R 34.10-2012(512 bit)ParamSet A'); NID_id_tc26_gost_3410_2012_512_paramSetA = 998; SN_id_tc26_gost_3410_2012_512_paramSetB = AnsiString('id-tc26-gost-3410-2012-512-paramSetB'); LN_id_tc26_gost_3410_2012_512_paramSetB = AnsiString('GOST R 34.10-2012(512 bit)ParamSet B'); NID_id_tc26_gost_3410_2012_512_paramSetB = 999; SN_id_tc26_gost_3410_2012_512_paramSetC = AnsiString('id-tc26-gost-3410-2012-512-paramSetC'); LN_id_tc26_gost_3410_2012_512_paramSetC = AnsiString('GOST R 34.10-2012(512 bit)ParamSet C'); NID_id_tc26_gost_3410_2012_512_paramSetC = 1149; SN_id_tc26_digest_constants = AnsiString('id-tc26-digest-constants'); NID_id_tc26_digest_constants = 1000; SN_id_tc26_cipher_constants = AnsiString('id-tc26-cipher-constants'); NID_id_tc26_cipher_constants = 1001; SN_id_tc26_gost_28147_constants = AnsiString('id-tc26-gost-28147-constants'); NID_id_tc26_gost_28147_constants = 1002; SN_id_tc26_gost_28147_param_Z = AnsiString('id-tc26-gost-28147-param-Z'); LN_id_tc26_gost_28147_param_Z = AnsiString('GOST 28147-89 TC26 parameter set'); NID_id_tc26_gost_28147_param_Z = 1003; SN_INN = AnsiString('INN'); LN_INN = AnsiString('INN'); NID_INN = 1004; SN_OGRN = AnsiString('OGRN'); LN_OGRN = AnsiString('OGRN'); NID_OGRN = 1005; SN_SNILS = AnsiString('SNILS'); LN_SNILS = AnsiString('SNILS'); NID_SNILS = 1006; SN_subjectSignTool = AnsiString('subjectSignTool'); LN_subjectSignTool = AnsiString('Signing Tool of Subject'); NID_subjectSignTool = 1007; SN_issuerSignTool = AnsiString('issuerSignTool'); LN_issuerSignTool = AnsiString('Signing Tool of Issuer'); NID_issuerSignTool = 1008; SN_grasshopper_ecb = AnsiString('grasshopper-ecb'); NID_grasshopper_ecb = 1012; SN_grasshopper_ctr = AnsiString('grasshopper-ctr'); NID_grasshopper_ctr = 1013; SN_grasshopper_ofb = AnsiString('grasshopper-ofb'); NID_grasshopper_ofb = 1014; SN_grasshopper_cbc = AnsiString('grasshopper-cbc'); NID_grasshopper_cbc = 1015; SN_grasshopper_cfb = AnsiString('grasshopper-cfb'); NID_grasshopper_cfb = 1016; SN_grasshopper_mac = AnsiString('grasshopper-mac'); NID_grasshopper_mac = 1017; SN_magma_ecb = AnsiString('magma-ecb'); NID_magma_ecb = 1187; SN_magma_ctr = AnsiString('magma-ctr'); NID_magma_ctr = 1188; SN_magma_ofb = AnsiString('magma-ofb'); NID_magma_ofb = 1189; SN_magma_cbc = AnsiString('magma-cbc'); NID_magma_cbc = 1190; SN_magma_cfb = AnsiString('magma-cfb'); NID_magma_cfb = 1191; SN_magma_mac = AnsiString('magma-mac'); NID_magma_mac = 1192; SN_camellia_128_cbc = AnsiString('CAMELLIA-128-CBC'); LN_camellia_128_cbc = AnsiString('camellia-128-cbc'); NID_camellia_128_cbc = 751; SN_camellia_192_cbc = AnsiString('CAMELLIA-192-CBC'); LN_camellia_192_cbc = AnsiString('camellia-192-cbc'); NID_camellia_192_cbc = 752; SN_camellia_256_cbc = AnsiString('CAMELLIA-256-CBC'); LN_camellia_256_cbc = AnsiString('camellia-256-cbc'); NID_camellia_256_cbc = 753; SN_id_camellia128_wrap = AnsiString('id-camellia128-wrap'); NID_id_camellia128_wrap = 907; SN_id_camellia192_wrap = AnsiString('id-camellia192-wrap'); NID_id_camellia192_wrap = 908; SN_id_camellia256_wrap = AnsiString('id-camellia256-wrap'); NID_id_camellia256_wrap = 909; SN_camellia_128_ecb = AnsiString('CAMELLIA-128-ECB'); LN_camellia_128_ecb = AnsiString('camellia-128-ecb'); NID_camellia_128_ecb = 754; SN_camellia_128_ofb128 = AnsiString('CAMELLIA-128-OFB'); LN_camellia_128_ofb128 = AnsiString('camellia-128-ofb'); NID_camellia_128_ofb128 = 766; SN_camellia_128_cfb128 = AnsiString('CAMELLIA-128-CFB'); LN_camellia_128_cfb128 = AnsiString('camellia-128-cfb'); NID_camellia_128_cfb128 = 757; SN_camellia_128_gcm = AnsiString('CAMELLIA-128-GCM'); LN_camellia_128_gcm = AnsiString('camellia-128-gcm'); NID_camellia_128_gcm = 961; SN_camellia_128_ccm = AnsiString('CAMELLIA-128-CCM'); LN_camellia_128_ccm = AnsiString('camellia-128-ccm'); NID_camellia_128_ccm = 962; SN_camellia_128_ctr = AnsiString('CAMELLIA-128-CTR'); LN_camellia_128_ctr = AnsiString('camellia-128-ctr'); NID_camellia_128_ctr = 963; SN_camellia_128_cmac = AnsiString('CAMELLIA-128-CMAC'); LN_camellia_128_cmac = AnsiString('camellia-128-cmac'); NID_camellia_128_cmac = 964; SN_camellia_192_ecb = AnsiString('CAMELLIA-192-ECB'); LN_camellia_192_ecb = AnsiString('camellia-192-ecb'); NID_camellia_192_ecb = 755; SN_camellia_192_ofb128 = AnsiString('CAMELLIA-192-OFB'); LN_camellia_192_ofb128 = AnsiString('camellia-192-ofb'); NID_camellia_192_ofb128 = 767; SN_camellia_192_cfb128 = AnsiString('CAMELLIA-192-CFB'); LN_camellia_192_cfb128 = AnsiString('camellia-192-cfb'); NID_camellia_192_cfb128 = 758; SN_camellia_192_gcm = AnsiString('CAMELLIA-192-GCM'); LN_camellia_192_gcm = AnsiString('camellia-192-gcm'); NID_camellia_192_gcm = 965; SN_camellia_192_ccm = AnsiString('CAMELLIA-192-CCM'); LN_camellia_192_ccm = AnsiString('camellia-192-ccm'); NID_camellia_192_ccm = 966; SN_camellia_192_ctr = AnsiString('CAMELLIA-192-CTR'); LN_camellia_192_ctr = AnsiString('camellia-192-ctr'); NID_camellia_192_ctr = 967; SN_camellia_192_cmac = AnsiString('CAMELLIA-192-CMAC'); LN_camellia_192_cmac = AnsiString('camellia-192-cmac'); NID_camellia_192_cmac = 968; SN_camellia_256_ecb = AnsiString('CAMELLIA-256-ECB'); LN_camellia_256_ecb = AnsiString('camellia-256-ecb'); NID_camellia_256_ecb = 756; SN_camellia_256_ofb128 = AnsiString('CAMELLIA-256-OFB'); LN_camellia_256_ofb128 = AnsiString('camellia-256-ofb'); NID_camellia_256_ofb128 = 768; SN_camellia_256_cfb128 = AnsiString('CAMELLIA-256-CFB'); LN_camellia_256_cfb128 = AnsiString('camellia-256-cfb'); NID_camellia_256_cfb128 = 759; SN_camellia_256_gcm = AnsiString('CAMELLIA-256-GCM'); LN_camellia_256_gcm = AnsiString('camellia-256-gcm'); NID_camellia_256_gcm = 969; SN_camellia_256_ccm = AnsiString('CAMELLIA-256-CCM'); LN_camellia_256_ccm = AnsiString('camellia-256-ccm'); NID_camellia_256_ccm = 970; SN_camellia_256_ctr = AnsiString('CAMELLIA-256-CTR'); LN_camellia_256_ctr = AnsiString('camellia-256-ctr'); NID_camellia_256_ctr = 971; SN_camellia_256_cmac = AnsiString('CAMELLIA-256-CMAC'); LN_camellia_256_cmac = AnsiString('camellia-256-cmac'); NID_camellia_256_cmac = 972; SN_camellia_128_cfb1 = AnsiString('CAMELLIA-128-CFB1'); LN_camellia_128_cfb1 = AnsiString('camellia-128-cfb1'); NID_camellia_128_cfb1 = 760; SN_camellia_192_cfb1 = AnsiString('CAMELLIA-192-CFB1'); LN_camellia_192_cfb1 = AnsiString('camellia-192-cfb1'); NID_camellia_192_cfb1 = 761; SN_camellia_256_cfb1 = AnsiString('CAMELLIA-256-CFB1'); LN_camellia_256_cfb1 = AnsiString('camellia-256-cfb1'); NID_camellia_256_cfb1 = 762; SN_camellia_128_cfb8 = AnsiString('CAMELLIA-128-CFB8'); LN_camellia_128_cfb8 = AnsiString('camellia-128-cfb8'); NID_camellia_128_cfb8 = 763; SN_camellia_192_cfb8 = AnsiString('CAMELLIA-192-CFB8'); LN_camellia_192_cfb8 = AnsiString('camellia-192-cfb8'); NID_camellia_192_cfb8 = 764; SN_camellia_256_cfb8 = AnsiString('CAMELLIA-256-CFB8'); LN_camellia_256_cfb8 = AnsiString('camellia-256-cfb8'); NID_camellia_256_cfb8 = 765; SN_aria_128_ecb = AnsiString('ARIA-128-ECB'); LN_aria_128_ecb = AnsiString('aria-128-ecb'); NID_aria_128_ecb = 1065; SN_aria_128_cbc = AnsiString('ARIA-128-CBC'); LN_aria_128_cbc = AnsiString('aria-128-cbc'); NID_aria_128_cbc = 1066; SN_aria_128_cfb128 = AnsiString('ARIA-128-CFB'); LN_aria_128_cfb128 = AnsiString('aria-128-cfb'); NID_aria_128_cfb128 = 1067; SN_aria_128_ofb128 = AnsiString('ARIA-128-OFB'); LN_aria_128_ofb128 = AnsiString('aria-128-ofb'); NID_aria_128_ofb128 = 1068; SN_aria_128_ctr = AnsiString('ARIA-128-CTR'); LN_aria_128_ctr = AnsiString('aria-128-ctr'); NID_aria_128_ctr = 1069; SN_aria_192_ecb = AnsiString('ARIA-192-ECB'); LN_aria_192_ecb = AnsiString('aria-192-ecb'); NID_aria_192_ecb = 1070; SN_aria_192_cbc = AnsiString('ARIA-192-CBC'); LN_aria_192_cbc = AnsiString('aria-192-cbc'); NID_aria_192_cbc = 1071; SN_aria_192_cfb128 = AnsiString('ARIA-192-CFB'); LN_aria_192_cfb128 = AnsiString('aria-192-cfb'); NID_aria_192_cfb128 = 1072; SN_aria_192_ofb128 = AnsiString('ARIA-192-OFB'); LN_aria_192_ofb128 = AnsiString('aria-192-ofb'); NID_aria_192_ofb128 = 1073; SN_aria_192_ctr = AnsiString('ARIA-192-CTR'); LN_aria_192_ctr = AnsiString('aria-192-ctr'); NID_aria_192_ctr = 1074; SN_aria_256_ecb = AnsiString('ARIA-256-ECB'); LN_aria_256_ecb = AnsiString('aria-256-ecb'); NID_aria_256_ecb = 1075; SN_aria_256_cbc = AnsiString('ARIA-256-CBC'); LN_aria_256_cbc = AnsiString('aria-256-cbc'); NID_aria_256_cbc = 1076; SN_aria_256_cfb128 = AnsiString('ARIA-256-CFB'); LN_aria_256_cfb128 = AnsiString('aria-256-cfb'); NID_aria_256_cfb128 = 1077; SN_aria_256_ofb128 = AnsiString('ARIA-256-OFB'); LN_aria_256_ofb128 = AnsiString('aria-256-ofb'); NID_aria_256_ofb128 = 1078; SN_aria_256_ctr = AnsiString('ARIA-256-CTR'); LN_aria_256_ctr = AnsiString('aria-256-ctr'); NID_aria_256_ctr = 1079; SN_aria_128_cfb1 = AnsiString('ARIA-128-CFB1'); LN_aria_128_cfb1 = AnsiString('aria-128-cfb1'); NID_aria_128_cfb1 = 1080; SN_aria_192_cfb1 = AnsiString('ARIA-192-CFB1'); LN_aria_192_cfb1 = AnsiString('aria-192-cfb1'); NID_aria_192_cfb1 = 1081; SN_aria_256_cfb1 = AnsiString('ARIA-256-CFB1'); LN_aria_256_cfb1 = AnsiString('aria-256-cfb1'); NID_aria_256_cfb1 = 1082; SN_aria_128_cfb8 = AnsiString('ARIA-128-CFB8'); LN_aria_128_cfb8 = AnsiString('aria-128-cfb8'); NID_aria_128_cfb8 = 1083; SN_aria_192_cfb8 = AnsiString('ARIA-192-CFB8'); LN_aria_192_cfb8 = AnsiString('aria-192-cfb8'); NID_aria_192_cfb8 = 1084; SN_aria_256_cfb8 = AnsiString('ARIA-256-CFB8'); LN_aria_256_cfb8 = AnsiString('aria-256-cfb8'); NID_aria_256_cfb8 = 1085; SN_aria_128_ccm = AnsiString('ARIA-128-CCM'); LN_aria_128_ccm = AnsiString('aria-128-ccm'); NID_aria_128_ccm = 1120; SN_aria_192_ccm = AnsiString('ARIA-192-CCM'); LN_aria_192_ccm = AnsiString('aria-192-ccm'); NID_aria_192_ccm = 1121; SN_aria_256_ccm = AnsiString('ARIA-256-CCM'); LN_aria_256_ccm = AnsiString('aria-256-ccm'); NID_aria_256_ccm = 1122; SN_aria_128_gcm = AnsiString('ARIA-128-GCM'); LN_aria_128_gcm = AnsiString('aria-128-gcm'); NID_aria_128_gcm = 1123; SN_aria_192_gcm = AnsiString('ARIA-192-GCM'); LN_aria_192_gcm = AnsiString('aria-192-gcm'); NID_aria_192_gcm = 1124; SN_aria_256_gcm = AnsiString('ARIA-256-GCM'); LN_aria_256_gcm = AnsiString('aria-256-gcm'); NID_aria_256_gcm = 1125; SN_kisa = AnsiString('KISA'); LN_kisa = AnsiString('kisa'); NID_kisa = 773; SN_seed_ecb = AnsiString('SEED-ECB'); LN_seed_ecb = AnsiString('seed-ecb'); NID_seed_ecb = 776; SN_seed_cbc = AnsiString('SEED-CBC'); LN_seed_cbc = AnsiString('seed-cbc'); NID_seed_cbc = 777; SN_seed_cfb128 = AnsiString('SEED-CFB'); LN_seed_cfb128 = AnsiString('seed-cfb'); NID_seed_cfb128 = 779; SN_seed_ofb128 = AnsiString('SEED-OFB'); LN_seed_ofb128 = AnsiString('seed-ofb'); NID_seed_ofb128 = 778; SN_sm4_ecb = AnsiString('SM4-ECB'); LN_sm4_ecb = AnsiString('sm4-ecb'); NID_sm4_ecb = 1133; SN_sm4_cbc = AnsiString('SM4-CBC'); LN_sm4_cbc = AnsiString('sm4-cbc'); NID_sm4_cbc = 1134; SN_sm4_ofb128 = AnsiString('SM4-OFB'); LN_sm4_ofb128 = AnsiString('sm4-ofb'); NID_sm4_ofb128 = 1135; SN_sm4_cfb128 = AnsiString('SM4-CFB'); LN_sm4_cfb128 = AnsiString('sm4-cfb'); NID_sm4_cfb128 = 1137; SN_sm4_cfb1 = AnsiString('SM4-CFB1'); LN_sm4_cfb1 = AnsiString('sm4-cfb1'); NID_sm4_cfb1 = 1136; SN_sm4_cfb8 = AnsiString('SM4-CFB8'); LN_sm4_cfb8 = AnsiString('sm4-cfb8'); NID_sm4_cfb8 = 1138; SN_sm4_ctr = AnsiString('SM4-CTR'); LN_sm4_ctr = AnsiString('sm4-ctr'); NID_sm4_ctr = 1139; SN_hmac = AnsiString('HMAC'); LN_hmac = AnsiString('hmac'); NID_hmac = 855; SN_cmac = AnsiString('CMAC'); LN_cmac = AnsiString('cmac'); NID_cmac = 894; SN_rc4_hmac_md5 = AnsiString('RC4-HMAC-MD5'); LN_rc4_hmac_md5 = AnsiString('rc4-hmac-md5'); NID_rc4_hmac_md5 = 915; SN_aes_128_cbc_hmac_sha1 = AnsiString('AES-128-CBC-HMAC-SHA1'); LN_aes_128_cbc_hmac_sha1 = AnsiString('aes-128-cbc-hmac-sha1'); NID_aes_128_cbc_hmac_sha1 = 916; SN_aes_192_cbc_hmac_sha1 = AnsiString('AES-192-CBC-HMAC-SHA1'); LN_aes_192_cbc_hmac_sha1 = AnsiString('aes-192-cbc-hmac-sha1'); NID_aes_192_cbc_hmac_sha1 = 917; SN_aes_256_cbc_hmac_sha1 = AnsiString('AES-256-CBC-HMAC-SHA1'); LN_aes_256_cbc_hmac_sha1 = AnsiString('aes-256-cbc-hmac-sha1'); NID_aes_256_cbc_hmac_sha1 = 918; SN_aes_128_cbc_hmac_sha256 = AnsiString('AES-128-CBC-HMAC-SHA256'); LN_aes_128_cbc_hmac_sha256 = AnsiString('aes-128-cbc-hmac-sha256'); NID_aes_128_cbc_hmac_sha256 = 948; SN_aes_192_cbc_hmac_sha256 = AnsiString('AES-192-CBC-HMAC-SHA256'); LN_aes_192_cbc_hmac_sha256 = AnsiString('aes-192-cbc-hmac-sha256'); NID_aes_192_cbc_hmac_sha256 = 949; SN_aes_256_cbc_hmac_sha256 = AnsiString('AES-256-CBC-HMAC-SHA256'); LN_aes_256_cbc_hmac_sha256 = AnsiString('aes-256-cbc-hmac-sha256'); NID_aes_256_cbc_hmac_sha256 = 950; SN_chacha20_poly1305 = AnsiString('ChaCha20-Poly1305'); LN_chacha20_poly1305 = AnsiString('chacha20-poly1305'); NID_chacha20_poly1305 = 1018; SN_chacha20 = AnsiString('ChaCha20'); LN_chacha20 = AnsiString('chacha20'); NID_chacha20 = 1019; SN_dhpublicnumber = AnsiString('dhpublicnumber'); LN_dhpublicnumber = AnsiString('X9.42 DH'); NID_dhpublicnumber = 920; SN_brainpoolP160r1 = AnsiString('brainpoolP160r1'); NID_brainpoolP160r1 = 921; SN_brainpoolP160t1 = AnsiString('brainpoolP160t1'); NID_brainpoolP160t1 = 922; SN_brainpoolP192r1 = AnsiString('brainpoolP192r1'); NID_brainpoolP192r1 = 923; SN_brainpoolP192t1 = AnsiString('brainpoolP192t1'); NID_brainpoolP192t1 = 924; SN_brainpoolP224r1 = AnsiString('brainpoolP224r1'); NID_brainpoolP224r1 = 925; SN_brainpoolP224t1 = AnsiString('brainpoolP224t1'); NID_brainpoolP224t1 = 926; SN_brainpoolP256r1 = AnsiString('brainpoolP256r1'); NID_brainpoolP256r1 = 927; SN_brainpoolP256t1 = AnsiString('brainpoolP256t1'); NID_brainpoolP256t1 = 928; SN_brainpoolP320r1 = AnsiString('brainpoolP320r1'); NID_brainpoolP320r1 = 929; SN_brainpoolP320t1 = AnsiString('brainpoolP320t1'); NID_brainpoolP320t1 = 930; SN_brainpoolP384r1 = AnsiString('brainpoolP384r1'); NID_brainpoolP384r1 = 931; SN_brainpoolP384t1 = AnsiString('brainpoolP384t1'); NID_brainpoolP384t1 = 932; SN_brainpoolP512r1 = AnsiString('brainpoolP512r1'); NID_brainpoolP512r1 = 933; SN_brainpoolP512t1 = AnsiString('brainpoolP512t1'); NID_brainpoolP512t1 = 934; SN_dhSinglePass_stdDH_sha1kdf_scheme = AnsiString('dhSinglePass-stdDH-sha1kdf-scheme'); NID_dhSinglePass_stdDH_sha1kdf_scheme = 936; SN_dhSinglePass_stdDH_sha224kdf_scheme = AnsiString('dhSinglePass-stdDH-sha224kdf-scheme'); NID_dhSinglePass_stdDH_sha224kdf_scheme = 937; SN_dhSinglePass_stdDH_sha256kdf_scheme = AnsiString('dhSinglePass-stdDH-sha256kdf-scheme'); NID_dhSinglePass_stdDH_sha256kdf_scheme = 938; SN_dhSinglePass_stdDH_sha384kdf_scheme = AnsiString('dhSinglePass-stdDH-sha384kdf-scheme'); NID_dhSinglePass_stdDH_sha384kdf_scheme = 939; SN_dhSinglePass_stdDH_sha512kdf_scheme = AnsiString('dhSinglePass-stdDH-sha512kdf-scheme'); NID_dhSinglePass_stdDH_sha512kdf_scheme = 940; SN_dhSinglePass_cofactorDH_sha1kdf_scheme = AnsiString('dhSinglePass-cofactorDH-sha1kdf-scheme'); NID_dhSinglePass_cofactorDH_sha1kdf_scheme = 941; SN_dhSinglePass_cofactorDH_sha224kdf_scheme = AnsiString('dhSinglePass-cofactorDH-sha224kdf-scheme'); NID_dhSinglePass_cofactorDH_sha224kdf_scheme = 942; SN_dhSinglePass_cofactorDH_sha256kdf_scheme = AnsiString('dhSinglePass-cofactorDH-sha256kdf-scheme'); NID_dhSinglePass_cofactorDH_sha256kdf_scheme = 943; SN_dhSinglePass_cofactorDH_sha384kdf_scheme = AnsiString('dhSinglePass-cofactorDH-sha384kdf-scheme'); NID_dhSinglePass_cofactorDH_sha384kdf_scheme = 944; SN_dhSinglePass_cofactorDH_sha512kdf_scheme = AnsiString('dhSinglePass-cofactorDH-sha512kdf-scheme'); NID_dhSinglePass_cofactorDH_sha512kdf_scheme = 945; SN_dh_std_kdf = AnsiString('dh-std-kdf'); NID_dh_std_kdf = 946; SN_dh_cofactor_kdf = AnsiString('dh-cofactor-kdf'); NID_dh_cofactor_kdf = 947; SN_ct_precert_scts = AnsiString('ct_precert_scts'); LN_ct_precert_scts = AnsiString('CT Precertificate SCTs'); NID_ct_precert_scts = 951; SN_ct_precert_poison = AnsiString('ct_precert_poison'); LN_ct_precert_poison = AnsiString('CT Precertificate Poison'); NID_ct_precert_poison = 952; SN_ct_precert_signer = AnsiString('ct_precert_signer'); LN_ct_precert_signer = AnsiString('CT Precertificate Signer'); NID_ct_precert_signer = 953; SN_ct_cert_scts = AnsiString('ct_cert_scts'); LN_ct_cert_scts = AnsiString('CT Certificate SCTs'); NID_ct_cert_scts = 954; SN_jurisdictionLocalityName = AnsiString('jurisdictionL'); LN_jurisdictionLocalityName = AnsiString('jurisdictionLocalityName'); NID_jurisdictionLocalityName = 955; SN_jurisdictionStateOrProvinceName = AnsiString('jurisdictionST'); LN_jurisdictionStateOrProvinceName = AnsiString('jurisdictionStateOrProvinceName'); NID_jurisdictionStateOrProvinceName = 956; SN_jurisdictionCountryName = AnsiString('jurisdictionC'); LN_jurisdictionCountryName = AnsiString('jurisdictionCountryName'); NID_jurisdictionCountryName = 957; SN_id_scrypt = AnsiString('id-scrypt'); LN_id_scrypt = AnsiString('scrypt'); NID_id_scrypt = 973; SN_tls1_prf = AnsiString('TLS1-PRF'); LN_tls1_prf = AnsiString('tls1-prf'); NID_tls1_prf = 1021; SN_hkdf = AnsiString('HKDF'); LN_hkdf = AnsiString('hkdf'); NID_hkdf = 1036; SN_id_pkinit = AnsiString('id-pkinit'); NID_id_pkinit = 1031; SN_pkInitClientAuth = AnsiString('pkInitClientAuth'); LN_pkInitClientAuth = AnsiString('PKINIT Client Auth'); NID_pkInitClientAuth = 1032; SN_pkInitKDC = AnsiString('pkInitKDC'); LN_pkInitKDC = AnsiString('Signing KDC Response'); NID_pkInitKDC = 1033; SN_X25519 = AnsiString('X25519'); NID_X25519 = 1034; SN_X448 = AnsiString('X448'); NID_X448 = 1035; SN_ED25519 = AnsiString('ED25519'); NID_ED25519 = 1087; SN_ED448 = AnsiString('ED448'); NID_ED448 = 1088; SN_kx_rsa = AnsiString('KxRSA'); LN_kx_rsa = AnsiString('kx-rsa'); NID_kx_rsa = 1037; SN_kx_ecdhe = AnsiString('KxECDHE'); LN_kx_ecdhe = AnsiString('kx-ecdhe'); NID_kx_ecdhe = 1038; SN_kx_dhe = AnsiString('KxDHE'); LN_kx_dhe = AnsiString('kx-dhe'); NID_kx_dhe = 1039; SN_kx_ecdhe_psk = AnsiString('KxECDHE-PSK'); LN_kx_ecdhe_psk = AnsiString('kx-ecdhe-psk'); NID_kx_ecdhe_psk = 1040; SN_kx_dhe_psk = AnsiString('KxDHE-PSK'); LN_kx_dhe_psk = AnsiString('kx-dhe-psk'); NID_kx_dhe_psk = 1041; SN_kx_rsa_psk = AnsiString('KxRSA_PSK'); LN_kx_rsa_psk = AnsiString('kx-rsa-psk'); NID_kx_rsa_psk = 1042; SN_kx_psk = AnsiString('KxPSK'); LN_kx_psk = AnsiString('kx-psk'); NID_kx_psk = 1043; SN_kx_srp = AnsiString('KxSRP'); LN_kx_srp = AnsiString('kx-srp'); NID_kx_srp = 1044; SN_kx_gost = AnsiString('KxGOST'); LN_kx_gost = AnsiString('kx-gost'); NID_kx_gost = 1045; SN_kx_any = AnsiString('KxANY'); LN_kx_any = AnsiString('kx-any'); NID_kx_any = 1063; SN_auth_rsa = AnsiString('AuthRSA'); LN_auth_rsa = AnsiString('auth-rsa'); NID_auth_rsa = 1046; SN_auth_ecdsa = AnsiString('AuthECDSA'); LN_auth_ecdsa = AnsiString('auth-ecdsa'); NID_auth_ecdsa = 1047; SN_auth_psk = AnsiString('AuthPSK'); LN_auth_psk = AnsiString('auth-psk'); NID_auth_psk = 1048; SN_auth_dss = AnsiString('AuthDSS'); LN_auth_dss = AnsiString('auth-dss'); NID_auth_dss = 1049; SN_auth_gost01 = AnsiString('AuthGOST01'); LN_auth_gost01 = AnsiString('auth-gost01'); NID_auth_gost01 = 1050; SN_auth_gost12 = AnsiString('AuthGOST12'); LN_auth_gost12 = AnsiString('auth-gost12'); NID_auth_gost12 = 1051; SN_auth_srp = AnsiString('AuthSRP'); LN_auth_srp = AnsiString('auth-srp'); NID_auth_srp = 1052; SN_auth_null = AnsiString('AuthNULL'); LN_auth_null = AnsiString('auth-null'); NID_auth_null = 1053; SN_auth_any = AnsiString('AuthANY'); LN_auth_any = AnsiString('auth-any'); NID_auth_any = 1064; SN_poly1305 = AnsiString('Poly1305'); LN_poly1305 = AnsiString('poly1305'); NID_poly1305 = 1061; SN_siphash = AnsiString('SipHash'); LN_siphash = AnsiString('siphash'); NID_siphash = 1062; SN_ffdhe2048 = AnsiString('ffdhe2048'); NID_ffdhe2048 = 1126; SN_ffdhe3072 = AnsiString('ffdhe3072'); NID_ffdhe3072 = 1127; SN_ffdhe4096 = AnsiString('ffdhe4096'); NID_ffdhe4096 = 1128; SN_ffdhe6144 = AnsiString('ffdhe6144'); NID_ffdhe6144 = 1129; SN_ffdhe8192 = AnsiString('ffdhe8192'); NID_ffdhe8192 = 1130; SN_ISO_UA = AnsiString('ISO-UA'); NID_ISO_UA = 1150; SN_ua_pki = AnsiString('ua-pki'); NID_ua_pki = 1151; SN_dstu28147 = AnsiString('dstu28147'); LN_dstu28147 = AnsiString('DSTU Gost 28147-2009'); NID_dstu28147 = 1152; SN_dstu28147_ofb = AnsiString('dstu28147-ofb'); LN_dstu28147_ofb = AnsiString('DSTU Gost 28147-2009 OFB mode'); NID_dstu28147_ofb = 1153; SN_dstu28147_cfb = AnsiString('dstu28147-cfb'); LN_dstu28147_cfb = AnsiString('DSTU Gost 28147-2009 CFB mode'); NID_dstu28147_cfb = 1154; SN_dstu28147_wrap = AnsiString('dstu28147-wrap'); LN_dstu28147_wrap = AnsiString('DSTU Gost 28147-2009 key wrap'); NID_dstu28147_wrap = 1155; SN_hmacWithDstu34311 = AnsiString('hmacWithDstu34311'); LN_hmacWithDstu34311 = AnsiString('HMAC DSTU Gost 34311-95'); NID_hmacWithDstu34311 = 1156; SN_dstu34311 = AnsiString('dstu34311'); LN_dstu34311 = AnsiString('DSTU Gost 34311-95'); NID_dstu34311 = 1157; SN_dstu4145le = AnsiString('dstu4145le'); LN_dstu4145le = AnsiString('DSTU 4145-2002 little endian'); NID_dstu4145le = 1158; SN_dstu4145be = AnsiString('dstu4145be'); LN_dstu4145be = AnsiString('DSTU 4145-2002 big endian'); NID_dstu4145be = 1159; SN_uacurve0 = AnsiString('uacurve0'); LN_uacurve0 = AnsiString('DSTU curve 0'); NID_uacurve0 = 1160; SN_uacurve1 = AnsiString('uacurve1'); LN_uacurve1 = AnsiString('DSTU curve 1'); NID_uacurve1 = 1161; SN_uacurve2 = AnsiString('uacurve2'); LN_uacurve2 = AnsiString('DSTU curve 2'); NID_uacurve2 = 1162; SN_uacurve3 = AnsiString('uacurve3'); LN_uacurve3 = AnsiString('DSTU curve 3'); NID_uacurve3 = 1163; SN_uacurve4 = AnsiString('uacurve4'); LN_uacurve4 = AnsiString('DSTU curve 4'); NID_uacurve4 = 1164; SN_uacurve5 = AnsiString('uacurve5'); LN_uacurve5 = AnsiString('DSTU curve 5'); NID_uacurve5 = 1165; SN_uacurve6 = AnsiString('uacurve6'); LN_uacurve6 = AnsiString('DSTU curve 6'); NID_uacurve6 = 1166; SN_uacurve7 = AnsiString('uacurve7'); LN_uacurve7 = AnsiString('DSTU curve 7'); NID_uacurve7 = 1167; SN_uacurve8 = AnsiString('uacurve8'); LN_uacurve8 = AnsiString('DSTU curve 8'); NID_uacurve8 = 1168; SN_uacurve9 = AnsiString('uacurve9'); LN_uacurve9 = AnsiString('DSTU curve 9'); NID_uacurve9 = 1169; implementation end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons; type TParallel = class; TForm1 = class(TForm) Button1: TButton; Button2: TButton; Memo1: TMemo; Button3: TButton; BitBtn1: TBitBtn; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure BitBtn1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; TParallel = class public Fa:word; //поле хранящее ширину Fb:word; //поле хранящее длину Fc:word; //поле хранящее высоту procedure Init (a,b,c: word); function Volume: word; //метод-функция //возвращающая объем procedure Show; end; //конец описания класса var Form1: TForm1; Par1:TParallel; Par:array [1..5] of TParallel; x:word=0; y:word=0; z:word=0; implementation {$R *.dfm} { TParallel } procedure TParallel.Init(a, b, c: word); begin Fa:=a; Fb:=b; Fc:=c; end; procedure TParallel.Show; begin ShowMessage('Объем параллелепипеда равен' + IntToStr(Volume)+#10#13 + 'Ширина-Поле Fa='+IntToStr(Fa)+#10#13 + 'Длина-Поле Fb='+IntToStr(Fb)+#10#13 + 'Высота-Поле Fc='+IntToStr(Fc)+#10#13); end; function TParallel.Volume: word; begin result:=Fa*Fb*Fc; end; procedure TForm1.BitBtn1Click(Sender: TObject); begin close; end; procedure TForm1.Button1Click(Sender: TObject); begin x:=x+1; y:=y+1; z:=z+1; Par1:=TParallel.Create; Par[x]:=Par1; Par1.Init(x,y,z); Par1.Show; Memo1.Lines.Add('Адрес в памяти объекта, содержащий в Par1, равен' +IntToStr (integer(Par1))); end; procedure TForm1.Button2Click(Sender: TObject); begin if Par1 = nil then Form1.Caption:='Объекта в памяти нет' else Form1.Caption:='Объект существует в памяти'; end; procedure TForm1.Button3Click(Sender: TObject); var i:integer; begin for i := 1 to 5 do Memo1.Lines.Add(('Адрес объекта с номером ' +IntToStr(i)+ ' равен ' +IntToStr (integer(Par[i])) + ' Поле Fa= ' +IntToStr(Par[i].Fa))); end; end.
unit AT.FMX.Layouts; interface uses System.SysUtils, System.Classes, FMX.Types, FMX.Controls; const pidATPlatforms = pidWin32 OR pidWin64 OR pidOSX32 OR pidiOSSimulator32 OR pidiOSSimulator64 OR pidiOSDevice32 OR pidiOSDevice64 OR pidAndroid32Arm OR pidAndroid64Arm OR pidLinux64; type [ComponentPlatformsAttribute(pidATPlatforms)] TATListLayout = class(TControl) strict private FVerticalGap: Single; procedure SetVerticalGap(const Value: Single); private FAutoSize: Boolean; procedure SetAutoSize(const Value: Boolean); protected procedure DoRealign; override; procedure DoAddObject(const AObject: TFmxObject); override; procedure DoRemoveObject(const AObject: TFmxObject); override; public constructor Create(AOwner: TComponent); override; published property Align; property Anchors; property AutoSize: Boolean read FAutoSize write SetAutoSize default True; property ClipChildren; property ClipParent; property Cursor; property DragMode; property EnableDragHighlight; property Enabled; property Locked; property Height; property HitTest; property Margins; property Opacity; property Padding; property PopupMenu; property Position; property RotationAngle; property RotationCenter; property Scale; property TouchTargetExpansion; property VerticalGap: Single read FVerticalGap write SetVerticalGap; property Visible; property Width; property OnApplyStyleLookup; property OnDragEnter; property OnDragLeave; property OnDragOver; property OnDragDrop; property OnDragEnd; property OnClick; property OnDblClick; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnMouseWheel; property OnMouseEnter; property OnMouseLeave; property OnPainting; property OnPaint; property OnResize; end; implementation uses AT.GarbageCollector; { TATListLayout } constructor TATListLayout.Create(AOwner: TComponent); begin inherited Create(AOwner); FAutoSize := True; end; procedure TATListLayout.DoAddObject(const AObject: TFmxObject); begin inherited; Realign; end; procedure TATListLayout.DoRealign; var AGC : IATGarbageCollector; Control : TControl; NextY, StdWidth: Single; ASpacingHgt : Single; ANewHeight : Single; ACtlHeight : Single; begin if (ControlsCount = 0) then Exit; FDisableAlign := True; TATGC.Cleanup( procedure begin FDisableAlign := False; end, AGC); if (AutoSize) then begin ASpacingHgt := (ControlsCount - 1) * VerticalGap; ANewHeight := 0 + Padding.Top + Padding.Bottom + ASpacingHgt; end else ANewHeight := Height; NextY := Margins.Top; StdWidth := Width - Margins.Left - Margins.Right; for Control in Controls do begin if (Control.Visible) then begin NextY := NextY + Control.Padding.Top; Control.SetBounds(Margins.Left + Control.Padding.Left, NextY, StdWidth - Control.Padding.Right - Control.Padding.Left, Control.Height); NextY := NextY + Control.Height + Control.Padding.Bottom + VerticalGap; if (AutoSize) then begin ACtlHeight := Control.Margins.Top + Control.Height + Control.Margins.Bottom; ANewHeight := ANewHeight + ACtlHeight; end; end; end; Height := ANewHeight; end; procedure TATListLayout.DoRemoveObject(const AObject: TFmxObject); begin inherited; Realign; end; procedure TATListLayout.SetAutoSize(const Value: Boolean); begin FAutoSize := Value; Realign; end; procedure TATListLayout.SetVerticalGap(const Value: Single); begin if Value = FVerticalGap then Exit; FVerticalGap := Value; Realign; end; initialization RegisterClass(TATListLayout); end.
unit IdHeaderCoderUTF; interface {$i IdCompilerDefines.inc} uses IdGlobal, IdHeaderCoderBase; type TIdHeaderCoderUTF = class(TIdHeaderCoder) public class function Decode(const ACharSet, AData: String): String; override; class function Encode(const ACharSet, AData: String): String; override; class function CanHandle(const ACharSet: String): Boolean; override; end; implementation class function TIdHeaderCoderUTF.Decode(const ACharSet, AData: String): String; var LEncoding: TIdTextEncoding; LBytes: TIdBytes; begin Result := ''; LBytes := nil; if TextIsSame(ACharSet, 'UTF-7') then begin {do not localize} LEncoding := TIdTextEncoding.UTF7; end else if TextIsSame(ACharSet, 'UTF-8') then begin {do not localize} LEncoding := TIdTextEncoding.UTF8; end else begin Exit; end; {$IFDEF DOTNET_OR_UNICODESTRING} // RLebeau 1/27/09: do not use the same Encoding class to decode the input // string to bytes and then decode the bytes to a string. Doing so will // undo what TIdTextEncoding.Convert() does, effectively making this class // behave the same as TIdHeaderCoderPlain. The output of this class needs // to be a string that contains codeunits in the UTF-16 range, not // codeunits that have been converted back to the input encoding... LBytes := Indy8BitEncoding.GetBytes(AData); {$ELSE} // RLebeau 2/12/09: Not using TIdTextEncoding.GetBytes() here. Although // the input string (should) contain the correct values, the conversion // performed by the RTL when assigning an AnsiString to the WideString // parameter can change characters!! Just assign the input characters // directly to the buffer to avoid that... if AData <> '' then begin LBytes := RawToBytes(PChar(AData)^, Length(AData)); end; {$ENDIF} LBytes := TIdTextEncoding.Convert( LEncoding, TIdTextEncoding.Unicode, LBytes); Result := TIdTextEncoding.Unicode.GetString(LBytes, 0, Length(LBytes)); end; class function TIdHeaderCoderUTF.Encode(const ACharSet, AData: String): String; var LBytes: TIdBytes; LEncoding: TIdTextEncoding; begin Result := ''; LBytes := nil; if TextIsSame(ACharSet, 'UTF-7') then begin {do not localize} LEncoding := TIdTextEncoding.UTF7; end else if TextIsSame(ACharSet, 'UTF-8') then begin {do not localize} LEncoding := TIdTextEncoding.UTF8; end else begin Exit; end; LBytes := TIdTextEncoding.Convert( TIdTextEncoding.Unicode, LEncoding, TIdTextEncoding.Unicode.GetBytes(AData)); {$IFDEF DOTNET_OR_UNICODESTRING} // RLebeau 1/27/09: do not use the same Encoding class to encode the input // string to bytes and then encode the bytes to a string. Doing so will // undo what TIdTextEncoding.Convert() does, effectively making this class // behave the same as TIdHeaderCoderPlain. The output of this class needs // to be a string that contains codeunits in the UTF-7/8 Ansi range, not // codeunits that have been converted back to UTF-16... Result := Indy8BitEncoding.GetString(LBytes, 0, Length(LBytes)); {$ELSE} // RLebeau 2/12/09: Not using TIdTextEncoding.GetString() here. Although // the encoded bytes contain the correct values, the conversion performed // by the RTL when assigning a WideString to the AnsiString Result can // lose characters!! Just assign the encoded bytes directly to the Result // to avoid that... SetString(Result, PAnsiChar(LBytes), Length(LBytes)); {$ENDIF} end; class function TIdHeaderCoderUTF.CanHandle(const ACharSet: String): Boolean; begin Result := PosInStrArray(ACharSet, ['UTF-7', 'UTF-8'], False) > -1; {do not localize} end; initialization RegisterHeaderCoder(TIdHeaderCoderUTF); finalization UnregisterHeaderCoder(TIdHeaderCoderUTF); end.
unit Report_GeneralMovementGoods; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, AncestorEnum, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxPCdxBarPopupMenu, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, Data.DB, cxDBData, Vcl.Menus, dsdAddOn, dxBarExtItems, dxBar, cxClasses, dsdDB, Datasnap.DBClient, dsdAction, Vcl.ActnList, cxPropertiesStore, cxGridLevel, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxPC, cxContainer, cxTextEdit, cxLabel, cxCurrencyEdit, cxButtonEdit, Vcl.DBActns, cxMaskEdit, Vcl.ExtCtrls, dxBarBuiltInMenu, cxNavigator, Vcl.StdCtrls, cxButtons, dxSkinsCore, dxSkinsDefaultPainters, dxSkinscxPCPainter, dxSkinsdxBarPainter, Vcl.ComCtrls, dxCore, cxDateUtils, cxDropDownEdit, cxCalendar, cxGridBandedTableView, cxGridDBBandedTableView, ChoicePeriod, dsdGuides, cxCheckBox; type TReport_GeneralMovementGoodsForm = class(TAncestorEnumForm) edCodeSearch: TcxTextEdit; cxLabel1: TcxLabel; ChoiceGoodsForm: TOpenChoiceForm; UpdateDataSet: TdsdUpdateDataSet; actSetGoodsLink: TdsdExecStoredProc; bbGoodsPriceListLink: TdxBarButton; mactChoiceGoodsForm: TMultiAction; actRefreshSearch: TdsdExecStoredProc; Panel1: TPanel; actDeleteLink: TdsdExecStoredProc; actRefreshSearch2: TdsdExecStoredProc; cxLabel3: TcxLabel; cxLabel2: TcxLabel; edGoodsSearch: TcxTextEdit; cxLabel4: TcxLabel; dxBarButton1: TdxBarButton; FormParams: TdsdFormParams; cxGridDBBandedTableView1: TcxGridDBBandedTableView; GoodsCode: TcxGridDBBandedColumn; UnitName: TcxGridDBBandedColumn; SummaSale: TcxGridDBBandedColumn; SummaIncome: TcxGridDBBandedColumn; AmountIncome: TcxGridDBBandedColumn; SummaProfit: TcxGridDBBandedColumn; Remains: TcxGridDBBandedColumn; RemainsSum: TcxGridDBBandedColumn; ceUnit: TcxButtonEdit; cxLabel5: TcxLabel; cxLabel6: TcxLabel; deStart: TcxDateEdit; cxLabel7: TcxLabel; deEnd: TcxDateEdit; GuidesUnit: TdsdGuides; PeriodChoice: TPeriodChoice; AmountSale: TcxGridDBBandedColumn; actGridToExcelReport: TdsdGridToExcel; bbGridToExcelReport: TdxBarButton; GoodsName: TcxGridDBBandedColumn; ExecuteDialog: TExecuteDialog; bbExecuteDialog: TdxBarButton; RefreshDispatcher: TRefreshDispatcher; edGoods: TcxButtonEdit; cxLabel8: TcxLabel; GuidesGoods: TdsdGuides; cbTabletki: TcxCheckBox; cbMobile: TcxCheckBox; cbNeBoley: TcxCheckBox; SummChangePercent: TcxGridDBBandedColumn; private { Private declarations } public { Public declarations } end; implementation {$R *.dfm} initialization RegisterClass(TReport_GeneralMovementGoodsForm); end.
unit ALTestRtti; interface uses System.Classes, System.Diagnostics, System.Types, Alcinoe.Common, Alcinoe.RTTI, Alcinoe.StringUtils, DUnitX.TestFramework; {$RTTI EXPLICIT METHODS([vcPublic, vcPublished]) FIELDS([vcPublic, vcPublished]) PROPERTIES([vcProtected, vcPublic, vcPublished])} type [TestFixture] TALTestRtti = class strict private fStopWatchAlcinoe: TStopwatch; fStopWatchDELPHI: TStopwatch; procedure CheckExecutionTime(const ARatio: single = 1.2); public [Setup] procedure Setup; //[TearDown] //procedure TearDown; [Test] procedure TestALRttiAutoInit; procedure onClick(Sender: TObject); end; TAlign = (alNone, alTop, alBottom, alLeft, alRight, alClient, alCustom); TAlignSet = set of TAlign; TALAutoInitChildObject = class; TALAutoInitObject = class(TObject) private FDateTimeValue2: TDateTime; FAlignValues2: TAlignSet; FInt64Value2: Int64; FSingleValue2: Single; FStringValue2: String; FAlignValue2: TAlign; FStringList2: TStringList; FAnsiStringValue2: ansiString; FOnclick2: TnotifyEvent; FDoubleValue2: Double; FCharValue2: Char; FChildObject2: TALAutoInitChildObject; FBooleanValue2: Boolean; FInt32Value2: Int32; FAnsiCharValue2: ansiChar; fOwner2: TALTestRtti; fOwner3: TALTestRtti; FDateTimeValue3: TDateTime; FAlignValues3: TAlignSet; FInt64Value3: Int64; FSingleValue3: Single; FStringValue3: String; FAlignValue3: TAlign; FStringList3: TStringList; FChildObject3: TALAutoInitChildObject; FAnsiStringValue3: ansiString; FOnclick3: TnotifyEvent; FDoubleValue3: Double; FCharValue3: Char; FBooleanValue3: Boolean; FInt32Value3: Int32; FAnsiCharValue3: ansiChar; procedure SetAlignValue2(const Value: TAlign); procedure SetAlignValues2(const Value: TAlignSet); procedure SetAnsiCharValue2(const Value: ansiChar); procedure SetAnsiStringValue2(const Value: ansiString); procedure SetBooleanValue2(const Value: Boolean); procedure SetCharValue2(const Value: Char); procedure SeTALAutoInitChildObject2(const Value: TALAutoInitChildObject); procedure SetDateTimeValue2(const Value: TDateTime); procedure SetDoubleValue2(const Value: Double); procedure SetInt32Value2(const Value: Int32); procedure SetInt64Value2(const Value: Int64); procedure SetOnclick2(const Value: TnotifyEvent); procedure SetSingleValue2(const Value: Single); procedure SetStringList2(const Value: TStringList); procedure SetStringValue2(const Value: String); function GetOwner2: TALTestRtti; public AutoInit: Boolean; Owner: TALTestRtti; property Owner2: TALTestRtti read GetOwner2; property Owner3: TALTestRtti read fOwner3; public //---- //auto init of member fields //---- [TALInit('B')] CharValue: Char; [TALInit('e')] AnsiCharValue: ansiChar; [TALInit('abcdefg')] StringValue: String; [TALInit('abcdefg')] AnsiStringValue: ansiString; [TALInit('64')] Int64Value: Int64; [TALInit('32')] Int32Value: Int32; [TALInit('3.14159265359')] SingleValue: Single; [TALInit('3.14159265359')] DoubleValue: Double; [TALInit('now')] DateTimeValue: TDateTime; [TALInit('true')] BooleanValue: Boolean; [TALInit('alRight')] AlignValue: TAlign; [TALInit('[alTop,alRight,alClient]')] AlignValues: TAlignSet; [TALInit('QuoteChar:A;NameValueSeparator:B;Options:[soStrictDelimiter, soWriteBOM]')] StringList: TStringList; [TALInit('Owner.OnClick')] Onclick: TnotifyEvent; [TALInit('left:50;right:75')] Rect: TRect; [TALInit('')] ChildObject: TALAutoInitChildObject; public //---- //auto init of property fields with setter //---- [TALInit('B')] property CharValue2: Char read FCharValue2 write SetCharValue2; [TALInit('e')] property AnsiCharValue2: ansiChar read FAnsiCharValue2 write SetAnsiCharValue2; [TALInit('abcdefg')] property StringValue2: String read FStringValue2 write SetStringValue2; [TALInit('abcdefg')] property AnsiStringValue2: ansiString read FAnsiStringValue2 write SetAnsiStringValue2; [TALInit('64')] property Int64Value2: Int64 read FInt64Value2 write SetInt64Value2; [TALInit('32')] property Int32Value2: Int32 read FInt32Value2 write SetInt32Value2; [TALInit('3.14159265359')] property SingleValue2: Single read FSingleValue2 write SetSingleValue2; [TALInit('3.14159265359')] property DoubleValue2: Double read FDoubleValue2 write SetDoubleValue2; [TALInit('now')] property DateTimeValue2: TDateTime read FDateTimeValue2 write SetDateTimeValue2; [TALInit('true')] property BooleanValue2: Boolean read FBooleanValue2 write SetBooleanValue2; [TALInit('alRight')] property AlignValue2: TAlign read FAlignValue2 write SetAlignValue2; [TALInit('[alTop,alRight,alClient]')] property AlignValues2: TAlignSet read FAlignValues2 write SetAlignValues2; [TALInit('QuoteChar:A;NameValueSeparator:B;Options:[soStrictDelimiter, soWriteBOM]')] property StringList2: TStringList read FStringList2 write SetStringList2; [TALInit('Owner2.OnClick')] property Onclick2: TnotifyEvent read FOnclick2 write SetOnclick2; [TALInit('')] property ChildObject2: TALAutoInitChildObject read FChildObject2 write SeTALAutoInitChildObject2; public //---- //auto init of property fields without setter //---- [TALInit('B')] property CharValue3: Char read FCharValue3 write fCharValue3; [TALInit('e')] property AnsiCharValue3: ansiChar read FAnsiCharValue3 write fAnsiCharValue3; [TALInit('abcdefg')] property StringValue3: String read FStringValue3 write fStringValue3; [TALInit('abcdefg')] property AnsiStringValue3: ansiString read FAnsiStringValue3 write fAnsiStringValue3; [TALInit('64')] property Int64Value3: Int64 read FInt64Value3 write fInt64Value3; [TALInit('32')] property Int32Value3: Int32 read FInt32Value3 write fInt32Value3; [TALInit('3.14159265359')] property SingleValue3: Single read FSingleValue3 write fSingleValue3; [TALInit('3.14159265359')] property DoubleValue3: Double read FDoubleValue3 write fDoubleValue3; [TALInit('now')] property DateTimeValue3: TDateTime read FDateTimeValue3 write fDateTimeValue3; [TALInit('true')] property BooleanValue3: Boolean read FBooleanValue3 write fBooleanValue3; [TALInit('alRight')] property AlignValue3: TAlign read FAlignValue3 write fAlignValue3; [TALInit('[alTop,alRight,alClient]')] property AlignValues3: TAlignSet read FAlignValues3 write fAlignValues3; [TALInit('QuoteChar:A;NameValueSeparator:B;Options:[soStrictDelimiter, soWriteBOM]')] property StringList3: TStringList read FStringList3 write fStringList3; [TALInit('Owner2.OnClick')] property Onclick3: TnotifyEvent read FOnclick3 write FOnclick3; [TALInit('')] property ChildObject3: TALAutoInitChildObject read FChildObject3 write fChildObject3; public constructor Create(const aOwner: TALTestRtti; const AAutoInit: Boolean); virtual; destructor Destroy; override; End; [TALInit('BooleanValue3:false;Int32Value:52')] TALAutoInitObject2 = class(TALAutoInitObject) private public [TALInit('alLeft')] property AlignValue2; public constructor Create(const aOwner: TALTestRtti; const AAutoInit: Boolean); override; End; [TALInit('Int32Value:75')] TALAutoInitObject3 = class(TALAutoInitObject2) private public [TALInit('altop')] property AlignValue2; public constructor Create(const aOwner: TALTestRtti; const AAutoInit: Boolean); override; End; TALAutoInitChildObject = class(TObject) private fOwner: TALAutoInitObject; public constructor Create(const aOwner: TALAutoInitObject); virtual; End; implementation uses system.SysUtils, system.DateUtils, System.Math; {**************************} procedure TALTestRtti.Setup; begin fStopWatchAlcinoe := TStopwatch.Create; fStopWatchDELPHI := TStopwatch.Create; end; {*******************************************************************} procedure TALTestRtti.CheckExecutionTime(const ARatio: single = 1.2); begin {$IF defined(debug) or defined(Win32)} //In debug we have overflow checking and range checking so that mean //that the execution time will be much slower that the Delphi RTL so skip it //In Win32 we remove all ASM (fastcode heritage) than the delphi RTL have //so we will be othen much more slower than the Delphi RTL Writeln(ALFormatW('CheckExecutionTime Skipped - %0.0f ms for Alcinoe vs %0.0f ms for Delphi (%0.1fx faster)', [fStopWatchAlcinoe.Elapsed.TotalMilliseconds, fStopWatchDELPHI.Elapsed.TotalMilliseconds, fStopWatchDELPHI.Elapsed.TotalMilliseconds / fStopWatchAlcinoe.Elapsed.TotalMilliseconds], ALDefaultFormatSettingsW)); {$ELSE} if fStopWatchAlcinoe.Elapsed.TotalMilliseconds > fStopWatchDELPHI.Elapsed.TotalMilliseconds * ARatio then Assert.Fail(ALFormatW('Time too long (%0.0f ms for Alcinoe vs %0.0f ms for Delphi)', [fStopWatchAlcinoe.Elapsed.TotalMilliseconds, fStopWatchDELPHI.Elapsed.TotalMilliseconds], ALDefaultFormatSettingsW)) else //https://github.com/VSoftTechnologies/DUnitX/issues/319 Writeln(ALFormatW('%0.0f ms for Alcinoe vs %0.0f ms for Delphi (%0.1fx faster)', [fStopWatchAlcinoe.Elapsed.TotalMilliseconds, fStopWatchDELPHI.Elapsed.TotalMilliseconds, fStopWatchDELPHI.Elapsed.TotalMilliseconds / fStopWatchAlcinoe.Elapsed.TotalMilliseconds], ALDefaultFormatSettingsW)); {$ENDIF} end; {***************************************} procedure TALTestRtti.TestALRttiAutoInit; begin //-- for var I := 0 to 100000 do begin fStopWatchAlcinoe.Start; {-} var LAutoInitObject := TALAutoInitObject.create(self, True); LAutoInitObject.Free; var LAutoInitObject2 := TALAutoInitObject2.create(self, True); LAutoInitObject2.Free; var LAutoInitObject3 := TALAutoInitObject3.create(self, True); LAutoInitObject3.Free; fStopWatchAlcinoe.Stop; end; //-- for var I := 0 to 100000 do begin fStopWatchDelphi.Start; {-} var LAutoInitObject := TALAutoInitObject.create(self, false); LAutoInitObject.Free; var LAutoInitObject2 := TALAutoInitObject2.create(self, false); LAutoInitObject2.Free; var LAutoInitObject3 := TALAutoInitObject3.create(self, false); LAutoInitObject3.Free; fStopWatchDelphi.Stop; end; //-- CheckExecutionTime(1.20{ARatio}); end; {*********************************************} procedure TALTestRtti.onClick(Sender: TObject); begin //nothing to do here end; {****************************************************************************************} constructor TALAutoInitObject.create(const aOwner: TALTestRtti; const AAutoInit: Boolean); begin Owner := aOwner; FOwner2 := aOwner; FOwner3 := aOwner; AutoInit := AAutoInit; if AAutoInit then ALRttiInitializeInstance(self) else begin CharValue := 'B'; AnsiCharValue := 'e'; StringValue := 'abcdefg'; AnsiStringValue := 'abcdefg'; Int64Value := 64; Int32Value := 32; SingleValue := 3.14159265359; DoubleValue := 3.14159265359; DateTimeValue := now; BooleanValue := true; AlignValue := TAlign.alRight; AlignValues := [alTop,alRight,alClient]; StringList:= TStringList.create; StringList.QuoteChar:='A'; StringList.NameValueSeparator := 'B'; StringList.Options := [soStrictDelimiter, soWriteBOM]; Onclick := Owner.OnClick; Rect.left := 50; Rect.right := 75; ChildObject := TALAutoInitChildObject.create(self); //---- CharValue2 := 'B'; AnsiCharValue2 := 'e'; StringValue2 := 'abcdefg'; AnsiStringValue2 := 'abcdefg'; Int64Value2 := 64; Int32Value2 := 32; SingleValue2 := 3.14159265359; DoubleValue2 := 3.14159265359; DateTimeValue2 := now; BooleanValue2 := true; AlignValue2 := TAlign.alRight; AlignValues2 := [alTop,alRight,alClient]; StringList2 := TStringList.create; StringList2.QuoteChar:='A'; StringList2.NameValueSeparator := 'B'; StringList2.Options := [soStrictDelimiter, soWriteBOM]; Onclick2 := Owner.OnClick; ChildObject2 := TALAutoInitChildObject.create(self); //---- CharValue3 := 'B'; AnsiCharValue3 := 'e'; StringValue3 := 'abcdefg'; AnsiStringValue3 := 'abcdefg'; Int64Value3 := 64; Int32Value3 := 32; SingleValue3 := 3.14159265359; DoubleValue3 := 3.14159265359; DateTimeValue3 := now; BooleanValue3 := true; AlignValue3 := TAlign.alRight; AlignValues3 := [alTop,alRight,alClient]; StringList3 := TStringList.create; StringList3.QuoteChar:='A'; StringList3.NameValueSeparator := 'B'; StringList3.Options := [soStrictDelimiter, soWriteBOM]; Onclick3 := Owner.OnClick; ChildObject3 := TALAutoInitChildObject.create(self); end; //-- if self.ClassType = TALAutoInitObject then begin if CharValue <> 'B' then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if AnsiCharValue <> 'e' then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if StringValue <> 'abcdefg' then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if AnsiStringValue <> 'abcdefg' then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if Int64Value <> 64 then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if Int32Value <> 32 then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if Not SameValue(SingleValue, single(3.14159265359)) then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if Not SameValue(DoubleValue, 3.14159265359) then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if Not SameDate(DateTimeValue, now) then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if BooleanValue <> true then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if AlignValue <> TAlign.alRight then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if AlignValues <> [alTop,alRight,alClient] then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if StringList.classname <> 'TStringList' then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if StringList.QuoteChar<>'A' then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if StringList.NameValueSeparator <> 'B' then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if StringList.Options <> [soStrictDelimiter, soWriteBOM] then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); Onclick(self); if Rect.left <> 50 then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if Rect.right <> 75 then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if ChildObject.classname <> 'TALAutoInitChildObject' then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); //---- if CharValue2 <> 'B' then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if AnsiCharValue2 <> 'e' then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if StringValue2 <> 'abcdefg' then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if AnsiStringValue2 <> 'abcdefg' then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if Int64Value2 <> 64 then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if Int32Value2 <> 32 then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if Not SameValue(SingleValue2, single(3.14159265359)) then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if Not SameValue(DoubleValue2, 3.14159265359) then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if Not SameDate(DateTimeValue2, now) then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if BooleanValue2 <> true then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if AlignValue2 <> TAlign.alRight then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if AlignValues2 <> [alTop,alRight,alClient] then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if StringList2.classname <> 'TStringList' then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if StringList2.QuoteChar<>'A' then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if StringList2.NameValueSeparator <> 'B' then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if StringList2.Options <> [soStrictDelimiter, soWriteBOM] then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); Onclick2(self); if ChildObject2.classname <> 'TALAutoInitChildObject' then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); //---- if CharValue3 <> 'B' then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if AnsiCharValue3 <> 'e' then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if StringValue3 <> 'abcdefg' then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if AnsiStringValue3 <> 'abcdefg' then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if Int64Value3 <> 64 then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if Int32Value3 <> 32 then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if Not SameValue(SingleValue3, single(3.14159265359)) then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if Not SameValue(DoubleValue3, 3.14159265359) then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if Not SameDate(DateTimeValue3, now) then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if BooleanValue3 <> true then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if AlignValue3 <> TAlign.alRight then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if AlignValues3 <> [alTop,alRight,alClient] then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if StringList3.classname <> 'TStringList' then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if StringList3.QuoteChar<>'A' then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if StringList3.NameValueSeparator <> 'B' then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); if StringList3.Options <> [soStrictDelimiter, soWriteBOM] then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); Onclick3(self); if ChildObject3.classname <> 'TALAutoInitChildObject' then raise Exception.create('Error 3AC91D01-134D-4092-BAEC-D22217157CDE'); end; end; {***********************************} destructor TALAutoInitObject.Destroy; begin if AutoInit then ALRttiFinalizeInstance(self) else begin ALFreeandNil(StringList); ALFreeandNil(ChildObject); ALFreeandNil(StringList2); ALFreeandNil(ChildObject2); ALFreeandNil(StringList3); ALFreeandNil(ChildObject3); end; inherited; end; {************************************************} function TALAutoInitObject.GetOwner2: TALTestRtti; begin result := FOwner2; end; {**************************************************************} procedure TALAutoInitObject.SetAlignValue2(const Value: TAlign); begin FAlignValue2 := Value; end; {******************************************************************} procedure TALAutoInitObject.SetAlignValues2(const Value: TAlignSet); begin FAlignValues2 := Value; end; {*******************************************************************} procedure TALAutoInitObject.SetAnsiCharValue2(const Value: ansiChar); begin FAnsiCharValue2 := Value; end; {***********************************************************************} procedure TALAutoInitObject.SetAnsiStringValue2(const Value: ansiString); begin FAnsiStringValue2 := Value; end; {*****************************************************************} procedure TALAutoInitObject.SetBooleanValue2(const Value: Boolean); begin FBooleanValue2 := Value; end; {***********************************************************} procedure TALAutoInitObject.SetCharValue2(const Value: Char); begin FCharValue2 := Value; end; {*****************************************************************************************} procedure TALAutoInitObject.SeTALAutoInitChildObject2(const Value: TALAutoInitChildObject); begin FChildObject2 := Value; end; {********************************************************************} procedure TALAutoInitObject.SetDateTimeValue2(const Value: TDateTime); begin FDateTimeValue2 := Value; end; {***************************************************************} procedure TALAutoInitObject.SetDoubleValue2(const Value: Double); begin FDoubleValue2 := Value; end; {*************************************************************} procedure TALAutoInitObject.SetInt32Value2(const Value: Int32); begin FInt32Value2 := Value; end; {*************************************************************} procedure TALAutoInitObject.SetInt64Value2(const Value: Int64); begin FInt64Value2 := Value; end; {*****************************************************************} procedure TALAutoInitObject.SetOnclick2(const Value: TnotifyEvent); begin FOnclick2 := Value; end; {***************************************************************} procedure TALAutoInitObject.SetSingleValue2(const Value: Single); begin FSingleValue2 := Value; end; {*******************************************************************} procedure TALAutoInitObject.SetStringList2(const Value: TStringList); begin FStringList2 := Value; end; {***************************************************************} procedure TALAutoInitObject.SetStringValue2(const Value: String); begin FStringValue2 := Value; end; {*****************************************************************************************} constructor TALAutoInitObject2.Create(const aOwner: TALTestRtti; const AAutoInit: Boolean); begin inherited create(aOwner, AAutoInit); if not AAutoInit then begin AlignValue2 := TAlign.alLeft; BooleanValue3 := false; Int32Value := 52; end; //-- if self.ClassType = TALAutoInitObject2 then begin if AlignValue2 <> TAlign.alLeft then raise Exception.create('Error D09DA31D-11BF-4404-BF0A-92D38B82D23D'); if BooleanValue3 <> false then raise Exception.create('Error D09DA31D-11BF-4404-BF0A-92D38B82D23D'); if Int32Value <> 52 then raise Exception.create('Error D09DA31D-11BF-4404-BF0A-92D38B82D23D'); end; end; {*****************************************************************************************} constructor TALAutoInitObject3.Create(const aOwner: TALTestRtti; const AAutoInit: Boolean); begin inherited create(aOwner, AAutoInit); if not AAutoInit then begin AlignValue2 := ALTop; Int32Value := 75; end; //-- if self.ClassType = TALAutoInitObject3 then begin if AlignValue2 <> altop then raise Exception.create('Error D09DA31D-11BF-4404-BF0A-92D38B82D23D'); if Int32Value <> 75 then raise Exception.create('Error D09DA31D-11BF-4404-BF0A-92D38B82D23D'); end; end; {*************************************************************************} constructor TALAutoInitChildObject.Create(const aOwner: TALAutoInitObject); begin if aOwner = nil then raise Exception.Create('Error CCD0F741-D468-4CD1-A94F-9E5F8F680643'); fOwner := aOwner; end; initialization ALRttiInitialization( ['ALTestRtti.*', 'DUnitX.TestFramework.TLogLevel', 'System.AnsiChar', 'System.AnsiString', 'System.Boolean', 'System.Byte', 'System.Cardinal', 'System.Char', 'System.Classes.IInterfaceList', 'System.Classes.IStringsAdapter', 'System.Classes.TAsyncConstArrayFunctionEvent', 'System.Classes.TAsyncConstArrayProc', 'System.Classes.TAsyncConstArrayProcedureEvent', 'System.Classes.TAsyncFunctionEvent', 'System.Classes.TAsyncProcedureEvent', 'System.Classes.TBasicAction', 'System.Classes.TBasicActionLink', 'System.Classes.TComponent', 'System.Classes.TComponentEnumerator', 'System.Classes.TComponentName', 'System.Classes.TComponentState', 'System.Classes.TComponentStyle', 'System.Classes.TGetDeltaStreamsEvent', 'System.Classes.TNotifyEvent', 'System.Classes.TObservers', 'System.Classes.TObservers.TCanObserveEvent', 'System.Classes.TObservers.TObserverAddedEvent', 'System.Classes.TOperation', 'System.Classes.TPersistent', 'System.Classes.TSeekOrigin', 'System.Classes.TStream', 'System.Classes.TStringItemList', 'System.Classes.TStringList', 'System.Classes.TStringList.TOverridden', 'System.Classes.TStringListSortCompare', 'System.Classes.TStrings', 'System.Classes.TStringsEnumerator', 'System.Classes.TStringsOptions', 'System.Double', 'System.Extended', 'System.Generics.Collections.TCollectionNotifyEvent<System.Classes.IInterfaceList>', 'System.Generics.Collections.TCollectionNotifyEvent<System.Classes.TBasicActionLink>', 'System.Generics.Collections.TCollectionNotifyEvent<System.Classes.TComponent>', 'System.Generics.Collections.TCollectionNotifyEvent<System.Integer>', 'System.Generics.Collections.TDictionary<System.Integer,System.Classes.IInterfaceList>', 'System.Generics.Collections.TDictionary<System.Integer,System.Classes.IInterfaceList>.TItemArray', 'System.Generics.Collections.TDictionary<System.Integer,System.Classes.IInterfaceList>.TKeyCollection', 'System.Generics.Collections.TDictionary<System.Integer,System.Classes.IInterfaceList>.TKeyEnumerator', 'System.Generics.Collections.TDictionary<System.Integer,System.Classes.IInterfaceList>.TPairEnumerator', 'System.Generics.Collections.TDictionary<System.Integer,System.Classes.IInterfaceList>.TValueCollection', 'System.Generics.Collections.TDictionary<System.Integer,System.Classes.IInterfaceList>.TValueEnumerator', 'System.Generics.Collections.TEnumerable<System.Classes.IInterfaceList>', 'System.Generics.Collections.TEnumerable<System.Classes.TBasicActionLink>', 'System.Generics.Collections.TEnumerable<System.Classes.TComponent>', 'System.Generics.Collections.TEnumerable<System.Generics.Collections.TPair<System.Integer,System.Classes.IInterfaceList>>', 'System.Generics.Collections.TEnumerable<System.Integer>', 'System.Generics.Collections.TEnumerator<System.Classes.IInterfaceList>', 'System.Generics.Collections.TEnumerator<System.Classes.TBasicActionLink>', 'System.Generics.Collections.TEnumerator<System.Classes.TComponent>', 'System.Generics.Collections.TEnumerator<System.Generics.Collections.TPair<System.Integer,System.Classes.IInterfaceList>>', 'System.Generics.Collections.TEnumerator<System.Integer>', 'System.Generics.Collections.TList<System.Classes.TBasicActionLink>', 'System.Generics.Collections.TList<System.Classes.TBasicActionLink>.ParrayofT', 'System.Generics.Collections.TList<System.Classes.TBasicActionLink>.TEmptyFunc', 'System.Generics.Collections.TList<System.Classes.TBasicActionLink>.TEnumerator', 'System.Generics.Collections.TList<System.Classes.TBasicActionLink>.arrayofT', 'System.Generics.Collections.TList<System.Classes.TComponent>', 'System.Generics.Collections.TList<System.Classes.TComponent>.ParrayofT', 'System.Generics.Collections.TList<System.Classes.TComponent>.TEmptyFunc', 'System.Generics.Collections.TList<System.Classes.TComponent>.TEnumerator', 'System.Generics.Collections.TList<System.Classes.TComponent>.arrayofT', 'System.Generics.Collections.TListHelper.TInternalCompareFunc', 'System.Generics.Collections.TListHelper.TInternalNotifyProc', 'System.Generics.Collections.TPair<System.Integer,System.Classes.IInterfaceList>', 'System.Generics.Defaults.IComparer<System.Classes.TBasicActionLink>', 'System.Generics.Defaults.IComparer<System.Classes.TComponent>', 'System.Generics.Defaults.IEqualityComparer<System.Integer>', 'System.HRESULT', 'System.IEnumerable', 'System.IEnumerable<System.Classes.TBasicActionLink>', 'System.IEnumerable<System.Classes.TComponent>', 'System.IInterface', 'System.Int64', 'System.Integer', 'System.NativeInt', 'System.PAnsiChar', 'System.PCurrency', 'System.PExtended', 'System.PInt64', 'System.PInterfaceEntry', 'System.PInterfaceTable', 'System.PResStringRec', 'System.PShortString', 'System.PVariant', 'System.PWideChar', 'System.Pointer', 'System.ShortInt', 'System.ShortString', 'System.Single', 'System.SmallInt', 'System.SysUtils.TEncoding', 'System.SysUtils.TProc', 'System.TArray<System.Byte>', 'System.TArray<System.Char>', 'System.TArray<System.Classes.IInterfaceList>', 'System.TArray<System.Classes.IInterfaceList>', 'System.TArray<System.Classes.TBasicActionLink>', 'System.TArray<System.Classes.TComponent>', 'System.TArray<System.Generics.Collections.TPair<System.Integer,System.Classes.IInterfaceList>>', 'System.TArray<System.Integer>', 'System.TArray<System.TObject>', 'System.TArray<System.string>', 'System.TClass', 'System.TDateTime', 'System.TExtended80Rec', 'System.TFloatSpecial', 'System.TGUID', 'System.TObject', 'System.TVarRec', 'System.Types.IAsyncResult', 'System.Types.TDirection', 'System.Types.TDuplicates', 'System.Types.TPoint', 'System.Types.TRect', 'System.Types.TSmallPoint', 'System.Types.TSplitRectType', 'System.UInt64', 'System.Word', 'System.string'], []); finalization ALRttiFinalization; end.
unit QueryEditor; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, DsgnIntf, DbTables, DBLists, DB, EditorForm, QueryDialog; procedure Register; implementation { TQueryDialogProperty } type TQueryDialogProperty = class(TPropertyEditor) public procedure Edit; override; function GetValue: string; override; function GetAttributes: TPropertyAttributes; override; end; procedure TQueryDialogProperty.Edit; var i : integer; EditForm : TfrmDisplayEditor; begin with GetComponent(0) as TQueryDialog do begin if TransTable.Count > 0 then begin EditForm := TfrmDisplayEditor.Create(Application); EditForm.InternalList := TList.Create; for i := 0 to TransTable.Count-1 do begin EditForm.InternalList.Add(TFieldInfo.Create); TFieldInfo(EditForm.InternalList.Items[i]).FieldName := TransTable.Items[i].FieldName; TFieldInfo(EditForm.InternalList.Items[i]).DisplayName := TransTable.Items[i].DisplayName; TFieldInfo(EditForm.InternalList.Items[i]).FieldType := TransTable.Items[i].FieldType; TFieldInfo(EditForm.InternalList.Items[i]).PickList := TStringList.Create; TFieldInfo(EditForm.InternalList.Items[i]).PickList.Assign( TransTable.Items[i].PickList); end; EditForm.grdName.RowCount := TransTable.Count+1; if EditForm.ShowModal=mrOK then begin Designer.Modified; for i := 0 to TransTable.Count-1 do begin TransTable.Items[i].FieldName:= TFieldInfo(EditForm.InternalList.Items[i]).FieldName; TransTable.Items[i].DisplayName:= TFieldInfo(EditForm.InternalList.Items[i]).DisplayName; TransTable.Items[i].FieldType:= TFieldInfo(EditForm.InternalList.Items[i]).FieldType; TransTable.Items[i].PickList.Assign( TFieldInfo(EditForm.InternalList.Items[i]).PickList); end; end; for i := 0 to EditForm.InternalList.Count-1 do begin TFieldInfo(EditForm.InternalList.Items[i]).PickList.Free; TFieldInfo(EditForm.InternalList.Items[i]).Free; end; EditForm.InternalList.Free; EditForm.Free; end; end; end; function TQueryDialogProperty.GetValue: string; begin Result := '[DisplayName]'; end; function TQueryDialogProperty.GetAttributes: TPropertyAttributes; begin Result := [paDialog,paReadOnly]; end; { TQueryDialogEditor} type TQueryDialogEditor = class(TComponentEditor) procedure Edit; override; procedure ExecuteVerb(Index: Integer); override; function GetVerb(Index: Integer): string; override; function GetVerbCount: Integer; override; end; function TQueryDialogEditor.GetVerbCount: Integer; begin Result := 1; end; function TQueryDialogEditor.GetVerb(index: Integer): string; begin case index of 0: Result := 'DisplayCaption Editor'; end; end; procedure TQueryDialogEditor.ExecuteVerb (index: integer); var i : integer; EditForm : TfrmDisplayEditor; begin case index of 0: begin with Component as TQueryDialog do begin if TransTable.Count > 0 then begin EditForm := TfrmDisplayEditor.Create(Application); EditForm.InternalList := TList.Create; for i := 0 to TransTable.Count-1 do begin EditForm.InternalList.Add(TFieldInfo.Create); TFieldInfo(EditForm.InternalList.Items[i]).FieldName := TransTable.Items[i].FieldName; TFieldInfo(EditForm.InternalList.Items[i]).DisplayName := TransTable.Items[i].DisplayName; TFieldInfo(EditForm.InternalList.Items[i]).FieldType := TransTable.Items[i].FieldType; TFieldInfo(EditForm.InternalList.Items[i]).PickList := TStringList.Create; TFieldInfo(EditForm.InternalList.Items[i]).PickList.Assign( TransTable.Items[i].PickList); end; EditForm.grdName.RowCount := TransTable.Count+1; if EditForm.ShowModal=mrOK then begin Designer.Modified; for i := 0 to TransTable.Count-1 do begin TransTable.Items[i].FieldName:= TFieldInfo(EditForm.InternalList.Items[i]).FieldName; TransTable.Items[i].DisplayName:= TFieldInfo(EditForm.InternalList.Items[i]).DisplayName; TransTable.Items[i].FieldType:= TFieldInfo(EditForm.InternalList.Items[i]).FieldType; TransTable.Items[i].PickList.Assign( TFieldInfo(EditForm.InternalList.Items[i]).PickList); end; end; for i := 0 to EditForm.InternalList.Count-1 do begin TFieldInfo(EditForm.InternalList.Items[i]).PickList.Free; TFieldInfo(EditForm.InternalList.Items[i]).Free; end; EditForm.InternalList.Free; end; end; end; end; end; procedure TQueryDialogEditor.Edit; begin ExecuteVerb(0); end; procedure Register; begin RegisterComponentEditor(TQueryDialog,TQueryDialogEditor); RegisterPropertyEditor(TypeInfo(TTransTable),TQueryDialog, 'TransTable', TQueryDialogProperty); end; end.
{**********************************************************************} { } { "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. } { } { Current maintainer: Christian-W. Budde } { } {**********************************************************************} unit MainUnit; interface {$I dws.inc} {-$DEFINE JS} {-$DEFINE LLVM} {-$DEFINE LLVM_EXECUTE} uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, Menus, StdActns, ActnList, ExtDlgs, ComCtrls, Types, SyncObjs, ImgList, dwsComp, dwsExprs, dwsSymbols, dwsErrors, dwsSuggestions, dwsRTTIConnector, dwsVCLGUIFunctions, dwsStrings, dwsUnitSymbols, {$IFDEF LLVM}dwsLLVMCodeGen, dwsLLVM, {$ENDIF} {$IFDEF JS}dwsJSCodeGen, {$ENDIF} SynEdit, SynEditHighlighter, SynHighlighterDWS, SynCompletionProposal, SynEditMiscClasses, SynEditSearch, SynEditOptionsDialog, SynEditPlugins, SynMacroRecorder; type TRescanThread = class(TThread) protected procedure Execute; override; end; TFrmBasic = class(TForm) AcnAutoCompile: TAction; AcnCodeGenJS: TAction; AcnCodeGenLLVM: TAction; AcnEditCopy: TEditCopy; AcnEditCut: TEditCut; AcnEditDelete: TEditDelete; AcnEditPaste: TEditPaste; AcnEditSelectAll: TEditSelectAll; AcnEditUndo: TEditUndo; AcnFileExit: TFileExit; AcnFileNew: TAction; AcnFileOpen: TFileOpen; AcnFileSaveScriptAs: TFileSaveAs; AcnFileScriptSave: TAction; AcnOptions: TAction; AcnScriptCompile: TAction; AcnSearchFind: TSearchFind; AcnUseRTTI: TAction; ActionList: TActionList; DelphiWebScript: TDelphiWebScript; dwsRTTIConnector: TdwsRTTIConnector; dwsUnitExternal: TdwsUnit; ListBoxCompiler: TListBox; ListBoxOutput: TListBox; MainMenu: TMainMenu; MnuCodeGen: TMenuItem; MnuCodeGenJS: TMenuItem; MnuCodeGenLLVM: TMenuItem; MnuEdit: TMenuItem; MnuEditCopy: TMenuItem; MnuEditCut: TMenuItem; MnuEditDelete: TMenuItem; MnuEditPaste: TMenuItem; MnuEditSaveAs: TMenuItem; MnuEditSearch: TMenuItem; MnuEditUndo: TMenuItem; MnuFile: TMenuItem; MnuFileNew: TMenuItem; MnuOptions: TMenuItem; MnuSaveMessagesAs: TMenuItem; MnuSaveOutputAs: TMenuItem; MnuScript: TMenuItem; MnuScriptAutomaticallyCompile: TMenuItem; MnuScriptCompile: TMenuItem; MnuScriptExit: TMenuItem; MnuScriptOpen: TMenuItem; MnuScriptUseRTTI: TMenuItem; MnuSearch: TMenuItem; MnuSelectAll: TMenuItem; N1: TMenuItem; N2: TMenuItem; N3: TMenuItem; N4: TMenuItem; N5: TMenuItem; PageControl: TPageControl; PopupMenuMessages: TPopupMenu; PopupMenuOutput: TPopupMenu; ProposalImages: TImageList; SplitterVertical: TSplitter; StatusBar: TStatusBar; SynCompletionProposal: TSynCompletionProposal; SynDWSSyn: TSynDWSSyn; SynEdit: TSynEdit; SynEditOptionsDialog: TSynEditOptionsDialog; SynEditSearch: TSynEditSearch; SynMacroRecorder: TSynMacroRecorder; SynParameters: TSynCompletionProposal; TabSheetCompiler: TTabSheet; TabSheetOutput: TTabSheet; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure AcnAutoCompileExecute(Sender: TObject); procedure AcnCodeGenLLVMExecute(Sender: TObject); procedure AcnFileNewExecute(Sender: TObject); procedure AcnFileOpenAccept(Sender: TObject); procedure AcnFileSaveScriptAsAccept(Sender: TObject); procedure AcnFileScriptSaveExecute(Sender: TObject); procedure AcnOptionsExecute(Sender: TObject); procedure AcnScriptCompileExecute(Sender: TObject); procedure AcnUseRTTIExecute(Sender: TObject); procedure MnuSaveMessagesAsClick(Sender: TObject); procedure MnuScriptExitClick(Sender: TObject); procedure SynCompletionProposalExecute(Kind: SynCompletionType; Sender: TObject; var CurrentInput: string; var x, y: Integer; var CanExecute: Boolean); procedure SynCompletionProposalPaintItem(Sender: TObject; Index: Integer; TargetCanvas: TCanvas; ItemRect: TRect; var CustomDraw: Boolean); procedure SynCompletionProposalShow(Sender: TObject); procedure SynEditChange(Sender: TObject); procedure SynEditGutterPaint(Sender: TObject; aLine, X, Y: Integer); procedure SynParametersExecute(Kind: SynCompletionType; Sender: TObject; var CurrentInput: string; var x, y: Integer; var CanExecute: Boolean); procedure AcnCodeGenJSExecute(Sender: TObject); private FRecentScriptName: TFileName; FRescanThread: TRescanThread; FCompiledProgram: IdwsProgram; FUnitRTTI: TdwsUnit; {$IFDEF LLVM} FLLVMCodeGen: TdwsLLVMCodeGen; FErrorLog: TFileStream; {$ENDIF} {$IFDEF JS} FJSCodeGen: TdwsJSCodeGen; {$ENDIF} FCriticalSection: TCriticalSection; FSyncEvent: TEvent; procedure SourceChanged; procedure DoGetSelfInstance(Info: TProgramInfo); public procedure CompileScript; procedure UpdateCompilerOutput; property SyncEvent: TEvent read FSyncEvent; end; var FrmBasic: TFrmBasic; implementation {$R *.dfm} uses Math, Registry, dwsUtils, dwsXPlatform; { TRescanThread } procedure TRescanThread.Execute; var SourceChanged: Boolean; begin SourceChanged := True; repeat if SourceChanged and (not Terminated) then begin FrmBasic.CompileScript; Sleep(100); end; SourceChanged := FrmBasic.SyncEvent.WaitFor(5000) = wrSignaled; until Terminated; end; { TFrmBasic } procedure TFrmBasic.FormCreate(Sender: TObject); begin FUnitRTTI := TdwsUnit.Create(nil); FUnitRTTI.UnitName := 'IDE'; FUnitRTTI.Script := DelphiWebScript; FUnitRTTI.Dependencies.Add(RTTI_UnitName); with FUnitRTTI.Functions.Add do begin Name := 'Self'; ResultType := 'RTTIVariant'; OnEval := DoGetSelfInstance; end; FCriticalSection := TCriticalSection.Create; FSyncEvent := TEvent.Create; FRescanThread := TRescanThread.Create; AcnCodeGenLLVM.Enabled := False; AcnCodeGenJS.Enabled := False; MnuCodeGenLLVM.Visible := False; MnuCodeGenJS.Visible := False; MnuCodeGen.Visible := False; {$IFDEF LLVM} FLLVMCodeGen := TdwsLLVMCodeGen.Create; FLLVMCodeGen.ModuleName := 'dws'; FLLVMCodeGen.Optimizations := loNone; FLLVMCodeGen.CustomOptimizationPasses := [cpPromoteMemoryToRegisterPass, cpCFGSimplificationPass, cpDeadStoreEliminationPass, cpInstructionCombiningPass, cpLoopDeletionPass, cpLoopIdiomPass, cpLoopRotatePass, cpLoopUnrollPass, cpLoopUnswitchPass, cpBasicAliasAnalysisPass, cpLoopVectorizePass, cpConstantMergePass, cpStripDeadPrototypesPass, cpStripSymbolsPass]; (* FLLVMCodeGen.CustomOptimizationPasses := [cpAggressiveDCEPass, cpCFGSimplificationPass, cpDeadStoreEliminationPass, cpGVNPass, cpIndVarSimplifyPass, cpInstructionCombiningPass, cpJumpThreadingPass, cpLICMPass, cpLoopDeletionPass, cpLoopIdiomPass, cpLoopRotatePass, cpLoopUnrollPass, cpLoopUnswitchPass, cpMemCpyOptPass, cpPromoteMemoryToRegisterPass, cpReassociatePass, cpSCCPPass, cpScalarReplAggregatesPass, cpScalarReplAggregatesPassSSA, cpSimplifyLibCallsPass, cpTailCallEliminationPass, cpConstantPropagationPass, cpDemoteMemoryToRegisterPass, cpVerifierPass, cpCorrelatedValuePropagationPass, cpEarlyCSEPass, cpLowerExpectIntrinsicPass, cpTypeBasedAliasAnalysisPass, cpBasicAliasAnalysisPass, cpBBVectorizePass, cpLoopVectorizePass, cpArgumentPromotionPass, cpConstantMergePass, cpDeadArgEliminationPass, cpFunctionAttrsPass, cpFunctionInliningPass, cpAlwaysInlinerPass, cpGlobalDCEPass, cpGlobalOptimizerPass, cpIPConstantPropagationPass, cpPruneEHPass, cpIPSCCPPass, cpStripDeadPrototypesPass, cpStripSymbolsPass]; *) // redirect std error and reload LLVM DLL FErrorLog := TFileStream.Create('Error.log', fmCreate or fmShareDenyWrite); SetStdHandle(STD_ERROR_HANDLE, FErrorLog.Handle); UnloadLLVM; LoadLLVM; MnuCodeGen.Visible := True; MnuCodeGenLLVM.Visible := True; AcnCodeGenLLVM.Enabled := True; {$ENDIF} {$IFDEF JS} FJSCodeGen := TdwsJSCodeGen.Create; MnuCodeGen.Visible := True; MnuCodeGenJS.Visible := True; AcnCodeGenJS.Enabled := True; {$ENDIF} end; procedure TFrmBasic.FormDestroy(Sender: TObject); begin {$IFDEF LLVM} FErrorLog.Free; FreeAndNil(FLLVMCodeGen); {$ENDIF} {$IFDEF JS} FreeAndNil(FJSCodeGen); {$ENDIF} if Assigned(FRescanThread) then begin FRescanThread.Terminate; FSyncEvent.SetEvent; FRescanThread.WaitFor; FreeAndNil(FRescanThread); end; FreeAndNil(FSyncEvent); FreeAndNil(FCriticalSection); FreeAndNil(FUnitRTTI); end; procedure TFrmBasic.FormShow(Sender: TObject); begin FRecentScriptName := ChangeFileExt(Application.ExeName, '.dws'); if FileExists(FRecentScriptName) then SynEdit.Lines.LoadFromFile(FRecentScriptName); with TRegistry.Create do try if OpenKey('Software\Graphics32\Interactive\', False) then begin SynEdit.CaretX := ReadInteger('CaretX'); SynEdit.CaretY := ReadInteger('CaretY'); end; CloseKey; finally Free; end; SourceChanged; end; procedure TFrmBasic.FormClose(Sender: TObject; var Action: TCloseAction); begin SynEdit.Lines.SaveToFile(FRecentScriptName); with TRegistry.Create do try OpenKey('Software\Graphics32\Interactive\', True); WriteInteger('CaretX', SynEdit.CaretX); WriteInteger('CaretY', SynEdit.CaretY); CloseKey; finally Free; end; end; procedure TFrmBasic.DoGetSelfInstance(Info: TProgramInfo); begin Info.ResultAsVariant := TdwsRTTIVariant.FromObject(Self); end; procedure TFrmBasic.CompileScript; begin FSyncEvent.ResetEvent; FCriticalSection.Enter; try FCompiledProgram := DelphiWebScript.Compile(SynEdit.Lines.Text); finally FCriticalSection.Leave; end; FRescanThread.Synchronize(UpdateCompilerOutput); end; procedure TFrmBasic.UpdateCompilerOutput; var ExecutedProgram: IdwsProgramExecution; begin if not Assigned(FCompiledProgram) then Exit; StatusBar.SimpleText := 'Compiled'; ListBoxCompiler.Items.Text := FCompiledProgram.Msgs.AsInfo; if ListBoxCompiler.Count = 0 then PageControl.ActivePage := TabSheetOutput else PageControl.ActivePage := TabSheetCompiler; ListBoxOutput.Items.Clear; if not Assigned(FCompiledProgram) then Exit; try ExecutedProgram := FCompiledProgram.Execute; ListBoxOutput.Items.Text := ExecutedProgram.Result.ToString; StatusBar.SimpleText := 'Executed'; except StatusBar.SimpleText := 'Error'; end; {$IFDEF LLVM} {$IFDEF DEBUG} // AcnCodeGenLLVM.Execute; {$ENDIF} {$ENDIF} end; procedure TFrmBasic.MnuSaveMessagesAsClick(Sender: TObject); begin with TOpenDialog.Create(Self) do try Filter := 'Text (*.txt)|*.txt'; if Execute then ListBoxOutput.Items.SaveToFile(FileName); finally Free; end; end; procedure TFrmBasic.MnuScriptExitClick(Sender: TObject); begin Close; end; procedure TFrmBasic.AcnAutoCompileExecute(Sender: TObject); begin if Assigned(FRescanThread) then begin FRescanThread.Terminate; FRescanThread.WaitFor; FreeAndNil(FRescanThread); end; if AcnAutoCompile.Checked then FRescanThread := TRescanThread.Create; end; procedure TFrmBasic.AcnCodeGenJSExecute(Sender: TObject); begin {$IFDEF JS} FJSCodeGen.CompileProgram(FCompiledProgram); SaveTextToUTF8File('dws.js', FJSCodeGen.CompiledOutput(FCompiledProgram)); {$ENDIF} end; procedure TFrmBasic.AcnCodeGenLLVMExecute(Sender: TObject); {$IFDEF LLVM} {$IFDEF LLVM_EXECUTE} var JIT: PLLVMExecutionEngine; Error: PAnsiChar; Fn: PLLVMValue; Args, Ret: PLLVMGenericValue; M: PLLVMModule; Target: PAnsiChar; {$ENDIF} {$ENDIF} begin {$IFDEF LLVM} FLLVMCodeGen.CompileProgram(FCompiledProgram); FLLVMCodeGen.PrintToFile('dws.ir'); // emit code LLVMInitializeX86Target; LLVMInitializeX86TargetInfo; LLVMInitializeX86TargetMC; LLVMInitializeX86AsmPrinter; LLVMInitializeX86AsmParser; LLVMInitializeX86Disassembler; FLLVMCodeGen.EmitToFile('dws.asm', LLVMAssemblyFile); {$IFDEF LLVM_EXECUTE} LLVMInitializeNativeTarget; LLVMLinkInJIT; if not LLVMCreateJITCompilerForModule(JIT, FLLVMCodeGen.Module.Handle, 0, Error) then try if not LLVMFindFunction(JIT, 'main', Fn) then begin Ret := LLVMRunFunction(JIT, Fn, 0, Args); LLVMDisposeGenericValue(Ret); end; // savely remove module from execution engine LLVMRemoveModule(JIT, FLLVMCodeGen.Module.Handle, M, Error); finally LLVMDisposeExecutionEngine(JIT); end else begin raise Exception.Create(Error); LLVMDisposeMessage(Error); end; {$ENDIF} {$ENDIF} end; procedure TFrmBasic.AcnFileNewExecute(Sender: TObject); begin SynEdit.Clear; end; procedure TFrmBasic.AcnFileOpenAccept(Sender: TObject); begin SynEdit.Lines.LoadFromFile(AcnFileOpen.Dialog.Filename); end; procedure TFrmBasic.AcnFileSaveScriptAsAccept(Sender: TObject); begin SynEdit.Lines.SaveToFile(AcnFileSaveScriptAs.Dialog.Filename); end; procedure TFrmBasic.AcnFileScriptSaveExecute(Sender: TObject); begin SynEdit.Lines.SaveToFile(FRecentScriptName); end; procedure TFrmBasic.AcnOptionsExecute(Sender: TObject); var SynEditorOptionsContainer: TSynEditorOptionsContainer; begin SynEditorOptionsContainer := TSynEditorOptionsContainer.Create(nil); SynEditorOptionsContainer.Assign(SynEdit); SynEditOptionsDialog.Execute(SynEditorOptionsContainer); SynEdit.Assign(SynEditorOptionsContainer); end; procedure TFrmBasic.AcnScriptCompileExecute(Sender: TObject); begin if not Assigned(FRescanThread) then CompileScript; end; procedure TFrmBasic.AcnUseRTTIExecute(Sender: TObject); begin if AcnUseRTTI.Checked then FUnitRTTI.Script := DelphiWebScript else FUnitRTTI.Script := nil; SourceChanged; end; procedure TFrmBasic.SourceChanged; begin FSyncEvent.SetEvent; end; procedure TFrmBasic.SynCompletionProposalExecute(Kind: SynCompletionType; Sender: TObject; var CurrentInput: string; var x, y: Integer; var CanExecute: Boolean); var SuggestionIndex: Integer; Proposal: TSynCompletionProposal; SourceFile: TSourceFile; ScriptPos: TScriptPos; Suggestions: IdwsSuggestions; begin CanExecute := False; Assert(Sender is TSynCompletionProposal); // check the proposal type Proposal := TSynCompletionProposal(Sender); Proposal.InsertList.Clear; Proposal.ItemList.Clear; if Assigned(Proposal.Form) then begin Proposal.Form.DoubleBuffered := True; Proposal.Resizeable := True; Proposal.Form.Resizeable := True; Proposal.Form.BorderStyle := bsSizeToolWin; end; // use this handler only in case the kind is set to ctCode! Assert(Kind = ctCode); // ok, get the compiled "program" from DWS if Assigned(FCompiledProgram) then begin SourceFile := TSourceFile.Create; try SourceFile.Code := SynEdit.Lines.Text; ScriptPos := TScriptPos.Create(SourceFile, SynEdit.CaretX, SynEdit.CaretY); finally SourceFile.Free; end; Suggestions := TDWSSuggestions.Create(FCompiledProgram, ScriptPos, [soNoReservedWords]); // now populate the suggestion box for SuggestionIndex := 0 to Suggestions.Count - 1 do begin Proposal.ItemList.AddObject(Suggestions.Caption[SuggestionIndex], TObject(Suggestions.Category[SuggestionIndex])); Proposal.InsertList.Add(Suggestions.Code[SuggestionIndex]); end; end; CanExecute := True; end; procedure TFrmBasic.SynParametersExecute(Kind: SynCompletionType; Sender: TObject; var CurrentInput: string; var x, y: Integer; var CanExecute: Boolean); procedure GetParameterInfosForCursor(const AProgram: IdwsProgram; Col, Line: Integer; var ParameterInfos: TStrings; InfoPosition: Integer = 0); procedure ParamsToInfo(const AParams: TParamsSymbolTable); var y: Integer; ParamsStr: string; begin ParamsStr := ''; if (AParams <> nil) and (AParams.Count > 0) then begin if InfoPosition >= AParams.Count then Exit; ParamsStr := '"' + AParams[0].Description + ';"'; for y := 1 to AParams.Count - 1 do ParamsStr := ParamsStr + ',"' + AParams[y].Description + ';"'; end else if InfoPosition > 0 then Exit; if (ParameterInfos.IndexOf(ParamsStr) < 0) then ParameterInfos.Add(ParamsStr); end; var Overloads : TFuncSymbolList; procedure CollectMethodOverloads(methSym : TMethodSymbol); var Member: TSymbol; Struct: TCompositeTypeSymbol; LastOverloaded: TMethodSymbol; begin LastOverloaded := methSym; Struct := methSym.StructSymbol; repeat for Member in Struct.Members do begin if not UnicodeSameText(Member.Name, methSym.Name) then Continue; if not (Member is TMethodSymbol) then Continue; LastOverloaded := TMethodSymbol(Member); if not Overloads.ContainsChildMethodOf(LastOverloaded) then Overloads.Add(LastOverloaded); end; Struct := Struct.Parent; until (Struct = nil) or not LastOverloaded.IsOverloaded; end; var ItemIndex: Integer; FuncSymbol: TFuncSymbol; SymbolDictionary: TdwsSymbolDictionary; Symbol, TestSymbol: TSymbol; begin // make sure the string list is present Assert(Assigned(ParameterInfos)); // ensure a compiled program is assigned if not Assigned(AProgram) then Exit; SymbolDictionary := AProgram.SymbolDictionary; Symbol := SymbolDictionary.FindSymbolAtPosition(Col, Line, MSG_MainModule); if (Symbol is TSourceMethodSymbol) then begin Overloads := TFuncSymbolList.Create; try CollectMethodOverloads(TSourceMethodSymbol(Symbol)); for ItemIndex := 0 to Overloads.Count - 1 do begin FuncSymbol := Overloads[ItemIndex]; ParamsToInfo(FuncSymbol.Params); end; finally Overloads.Free; end; end else if (Symbol is TFuncSymbol) then begin ParamsToInfo(TFuncSymbol(Symbol).Params); if TFuncSymbol(Symbol).IsOverloaded then begin for ItemIndex := 0 to SymbolDictionary.Count - 1 do begin TestSymbol := SymbolDictionary.Items[ItemIndex].Symbol; if (TestSymbol.ClassType = Symbol.ClassType) and SameText(TFuncSymbol(TestSymbol).Name, TFuncSymbol(Symbol).Name) and (TestSymbol <> Symbol) then ParamsToInfo(TFuncSymbol(TestSymbol).Params); end; end end; // check if no parameters at all is an option, if so: replace and move to top ItemIndex := ParameterInfos.IndexOf(''); if ItemIndex >= 0 then begin ParameterInfos.Delete(ItemIndex); ParameterInfos.Insert(0, '"<no parameters required>"'); end; end; var LineText: String; Proposal: TSynCompletionProposal; LocLine: string; TmpX: Integer; TmpLocation, StartX, ParenCounter: Integer; ParameterInfoList: TStrings; begin CanExecute := False; Assert(Kind = ctParams); // check the proposal type if Sender is TSynCompletionProposal then begin Proposal := TSynCompletionProposal(Sender); Proposal.InsertList.Clear; Proposal.ItemList.Clear; ParameterInfoList := TStrings(Proposal.ItemList); // get current line LineText := SynEdit.LineText; with TSynCompletionProposal(Sender).Editor do begin // get current compiled program if not Assigned(FCompiledProgram) then Exit; LocLine := LineText; //go back from the cursor and find the first open paren TmpX := CaretX; if TmpX > Length(LocLine) then TmpX := Length(LocLine) else Dec(TmpX); TmpLocation := 0; while (TmpX > 0) and not CanExecute do begin if LocLine[TmpX] = ',' then begin Inc(TmpLocation); Dec(TmpX); end else if LocLine[TmpX] = ')' then begin // we found a close, go till it's opening paren ParenCounter := 1; Dec(TmpX); while (TmpX > 0) and (ParenCounter > 0) do begin if LocLine[TmpX] = ')' then Inc(ParenCounter) else if LocLine[TmpX] = '(' then Dec(ParenCounter); Dec(TmpX); end; if TmpX > 0 then Dec(TmpX); // eat the open paren end else if LocLine[TmpX] = '(' then begin // we have a valid open paren, lets see what the word before it is StartX := TmpX; while (TmpX > 0) and not IsIdentChar(LocLine[TmpX])do Dec(TmpX); if TmpX > 0 then begin while (TmpX > 0) and IsIdentChar(LocLine[TmpX]) do Dec(TmpX); Inc(TmpX); GetParameterInfosForCursor(FCompiledProgram, TmpX, SynEdit.CaretY, ParameterInfoList, TmpLocation); CanExecute := ParameterInfoList.Count > 0; if not CanExecute then begin TmpX := StartX; Dec(TmpX); end else TSynCompletionProposal(Sender).Form.CurrentIndex := TmpLocation; end; end else Dec(TmpX) end; end; end; end; procedure TFrmBasic.SynCompletionProposalPaintItem(Sender: TObject; Index: Integer; TargetCanvas: TCanvas; ItemRect: TRect; var CustomDraw: Boolean); var Offset: TPoint; ItemName, ItemHighlight: string; ImageIndex: Integer; begin inherited; if Assigned(SynCompletionProposal.Images) then begin TargetCanvas.FillRect(ItemRect); ImageIndex := -1; case TdwsSuggestionCategory(SynCompletionProposal.ItemList.Objects[index]) of scFunction, scProcedure: ImageIndex := 0; scConstructor, scDestructor, scMethod: ImageIndex := 1; scProperty: ImageIndex := 2; scType, scRecord, scInterface: ImageIndex := 3; scClass: ImageIndex := 4; scUnit: ImageIndex := 5; scReservedWord: ImageIndex := 6; end; if ImageIndex >= 0 then SynCompletionProposal.Images.Draw(TargetCanvas, ItemRect.Left, ItemRect.Top, ImageIndex); Offset.X := ItemRect.Left + 18; Offset.Y := ItemRect.Top; ItemHighlight := SynCompletionProposal.InsertList[index]; ItemName := SynCompletionProposal.ItemList[index]; TargetCanvas.Font.Style := TargetCanvas.Font.Style + [fsBold]; TargetCanvas.TextOut(Offset.X, Offset.Y, ItemHighlight); Delete(ItemName, 1, Length(ItemHighlight)); Inc(Offset.X, TargetCanvas.TextWidth(ItemHighlight)); TargetCanvas.Font.Style := TargetCanvas.Font.Style - [fsBold]; TargetCanvas.TextOut(Offset.X, Offset.Y, ItemName); CustomDraw := True; end; end; procedure TFrmBasic.SynCompletionProposalShow(Sender: TObject); var CompletionProposalForm: TSynBaseCompletionProposalForm; begin inherited; if (Sender <> nil) and (Sender is TSynBaseCompletionProposalForm) then begin CompletionProposalForm := TSynBaseCompletionProposalForm(Sender); try CompletionProposalForm.DoubleBuffered := True; if CompletionProposalForm.Height > 300 then CompletionProposalForm.Height := 300 except on Exception do; end; end; end; procedure TFrmBasic.SynEditChange(Sender: TObject); begin SourceChanged; end; procedure TFrmBasic.SynEditGutterPaint(Sender: TObject; ALine, X, Y: Integer); var StrLineNumber: string; LineNumberRect: TRect; GutterWidth, Offset: Integer; OldFont: TFont; begin with TSynEdit(Sender), Canvas do begin Brush.Style := bsClear; GutterWidth := Gutter.Width - 5; if (ALine = 1) or (ALine = CaretY) or ((ALine mod 10) = 0) then begin StrLineNumber := IntToStr(ALine); LineNumberRect := Rect(x, y, GutterWidth, y + LineHeight); OldFont := TFont.Create; try OldFont.Assign(Canvas.Font); Canvas.Font := Gutter.Font; Canvas.TextRect(LineNumberRect, StrLineNumber, [tfVerticalCenter, tfSingleLine, tfRight]); Canvas.Font := OldFont; finally OldFont.Free; end; end else begin Canvas.Pen.Color := Gutter.Font.Color; if (ALine mod 5) = 0 then Offset := 5 else Offset := 2; Inc(y, LineHeight div 2); Canvas.MoveTo(GutterWidth - Offset, y); Canvas.LineTo(GutterWidth, y); end; end; end; end.
{*******************************************************} { } { Delphi FireDAC Framework } { FireDAC PostgreSQL API } { } { Copyright(c) 2004-2013 Embarcadero Technologies, Inc. } { } {*******************************************************} {$I FireDAC.inc} unit FireDAC.Phys.PGCli; interface uses FireDAC.Stan.Intf; const // Base PostgreSQL datatypes SQL_BOOL = 16; SQL_BYTEA = 17; SQL_CHAR = 18; // Internal SQL_NAME = 19; // Internal SQL_INT8 = 20; SQL_INT2 = 21; SQL_INT2VECTOR = 22; // Internal SQL_INT4 = 23; SQL_REGPROC = 24; SQL_TEXT = 25; SQL_OID = 26; // Internal SQL_TID = 27; SQL_XID = 28; SQL_CID = 29; // Internal SQL_OIDVECTOR = 30; // Internal SQL_XML = 142; SQL_SMGR = 210; SQL_POINT = 600; SQL_LSEG = 601; SQL_PATH = 602; SQL_BOX = 603; SQL_POLYGON = 604; SQL_LINE = 628; SQL_CIDR = 650; // Internal SQL_FLOAT4 = 700; SQL_FLOAT8 = 701; SQL_ABSTIME = 702; SQL_RELTIME = 703; SQL_TINTERVAL = 704; SQL_UNKNOWN = 705; // Internal SQL_CIRCLE = 718; SQL_CASH = 790; SQL_MACADDR = 829; // Internal SQL_INET = 869; // Internal SQL_ACLITEM = 1033; SQL_BPCHAR = 1042; SQL_VARCHAR = 1043; SQL_DATE = 1082; SQL_TIME = 1083; SQL_TIMESTAMP = 1114; SQL_TIMESTAMPTZ = 1184; SQL_INTERVAL = 1186; SQL_TIMETZ = 1266; SQL_BIT = 1560; SQL_VARBIT = 1562; SQL_NUMERIC = 1700; SQL_REFCURSOR = 1790; SQL_REGPROCEDURE = 2202; SQL_REGOPER = 2203; SQL_REGOPERATOR = 2204; SQL_REGCLASS = 2205; SQL_REGTYPE = 2206; SQL_CSTRING = 2275; SQL_ANY = 2276; SQL_VOID = 2278; // Internal SQL_UUID = 2950; // connection status constants CONNECTION_OK = 0; CONNECTION_BAD = 1; CONNECTION_STARTED = 2; CONNECTION_MADE = 3; CONNECTION_AWAITING_RESPONSE = 4; CONNECTION_AUTH_OK = 5; CONNECTION_SETENV = 6; CONNECTION_SSL_STARTUP = 7; CONNECTION_NEEDED = 8; // exec status constants PGRES_EMPTY_QUERY = 0; PGRES_COMMAND_OK = 1; PGRES_TUPLES_OK = 2; PGRES_COPY_OUT = 3; PGRES_COPY_IN = 4; PGRES_BAD_RESPONSE = 5; PGRES_NONFATAL_ERROR = 6; PGRES_FATAL_ERROR = 7; // error fields, copied from postgres_ext.h PG_DIAG_SEVERITY = Ord('S'); PG_DIAG_SQLSTATE = Ord('C'); PG_DIAG_MESSAGE_PRIMARY = Ord('M'); PG_DIAG_MESSAGE_DETAIL = Ord('D'); PG_DIAG_MESSAGE_HINT = Ord('H'); PG_DIAG_STATEMENT_POSITION = Ord('P'); PG_DIAG_INTERNAL_POSITION = Ord('p'); PG_DIAG_INTERNAL_QUERY = Ord('q'); PG_DIAG_CONTEXT = Ord('W'); PG_DIAG_SOURCE_FILE = Ord('F'); PG_DIAG_SOURCE_LINE = Ord('L'); PG_DIAG_SOURCE_FUNCTION = Ord('R'); // PGTransactionStatusType PQTRANS_IDLE = 0; // connection idle PQTRANS_ACTIVE = 1; // command in progress PQTRANS_INTRANS = 2; // idle, within transaction block PQTRANS_INERROR = 3; // idle, within failed transaction PQTRANS_UNKNOWN = 4; // cannot determine status // Attribute numbers for the system-defined attributes // Source: src\include\access\htup.h SelfItemPointerAttributeNumber = -1; ObjectIdAttributeNumber = -2; MinTransactionIdAttributeNumber = -3; MinCommandIdAttributeNumber = -4; MaxTransactionIdAttributeNumber = -5; MaxCommandIdAttributeNumber = -6; TableOidAttributeNumber = -7; // other POSTGRES_EPOCH_JDATE = 2451545; NAMEMAXLEN = 64; InvalidOid = 0; VARHDRSZ = 4; NULL_LEN = -1; type PGConn = Pointer; PPGConn = Pointer; // Internal pqlib structure pgresAttValue = record len: Integer; value: PFDAnsiString; end; PPGresAttValue = ^pgresAttValue; PPPGresAttValue = ^PPGresAttValue; // Internal pqlib structure pg_result = record ntups: Integer; numAttributes: Integer; attDescs: Pointer; tuples: PPPGresAttValue; // each PGresTuple is an array of PGresAttValue's // .......... end; PGresult = pg_result; PPGresult = ^PGresult; PGcancel = Pointer; PPGcancel = Pointer; Oid = LongWord; POid = ^Oid; Tid = array[0..5] of Byte; PTid = ^Tid; PQConninfoOptions = record keyword: PFDAnsiString; // The keyword of the option envvar: PFDAnsiString; // Fallback environment variable name compiled: PFDAnsiString; // Fallback compiled in default value val: PFDAnsiString; // Option's current value, or NULL lbl: PFDAnsiString; // Label for field in connect dialog dispchar: PFDAnsiString; // Character to display for this field in a // connect dialog. Values are: "" Display // entered value as is "*" Password field - // hide value "D" Debug option - don't show // by default dispsize: integer; // Field size in characters for dialog end; PPQconninfoOption = ^PQConninfoOptions; PGnotify = record relname: PFDAnsiString; // notification condition name be_pid: Integer; // process ID of notifying server process extra: PFDAnsiString; // notification parameter end; PPGnotify = ^PGnotify; // Notice Processing TPQnoticeReceiver = procedure(arg: Pointer; res: PPGresult); cdecl; TPQnoticeProcessor = procedure(arg: Pointer; msg: PFDAnsiString); cdecl; {$IFDEF FireDAC_PGSQL_STATIC} {$L crypt.obj} // {$L dirent.obj} // {$L dirmod.obj} {$L encnames.obj} {$L fe-auth.obj} {$L fe-connect.obj} {$L fe-exec.obj} {$L fe-lobj.obj} {$L fe-misc.obj} {$L fe-print.obj} {$L fe-protocol2.obj} {$L fe-protocol3.obj} {$L fe-secure.obj} {$L getaddrinfo.obj} {$L inet_aton.obj} {$L ip.obj} {$L md5.obj} {$L noblock.obj} {$L open.obj} {$L pgsleep.obj} {$L pgstrcasecmp.obj} {$L pqexpbuffer.obj} {$L pqsignal.obj} {$L pthread-win32.obj} {$L snprintf.obj} {$L strlcpy.obj} {$L thread.obj} {$L wchar.obj} {$L win32.obj} {$L win32error.obj} // Database Connection Control Functions function PQconnectdb(ConnInfo: PFDAnsiString): PPGconn; cdecl; external; // function PQsetdbLogin(Host, Port, Options, Tty, Db, User, Passwd: PFDAnsiString): PPGconn; cdecl; external; function PQconndefaults: PPQconninfoOption; cdecl; external; procedure PQfinish(conn: PPGconn); cdecl; external; procedure PQreset(conn: PPGconn); cdecl; external; // Connection Status Functions function PQdb(conn: PPGconn): PFDAnsiString; cdecl; external; function PQuser(conn: PPGconn): PFDAnsiString; cdecl; external; function PQpass(conn: PPGconn): PFDAnsiString; cdecl; external; function PQhost(conn: PPGconn): PFDAnsiString; cdecl; external; function PQport(conn: PPGconn): PFDAnsiString; cdecl; external; function PQtty(conn: PPGconn): PFDAnsiString; cdecl; external; function PQoptions(conn: PPGconn): PFDAnsiString; cdecl; external; function PQstatus(conn: PPGconn): Integer; cdecl; external; function PQparameterStatus(conn: PGconn; ParamName: PFDAnsiString): PFDAnsiString; cdecl; external; function PQtransactionStatus(conn: PGconn): Integer; cdecl; external; function PQserverVersion(conn: PPGconn): Integer; cdecl; external; function PQprotocolVersion(conn: PPGconn): Integer; cdecl; external; function PQsetClientEncoding(conn: PPGconn; encoding: PFDAnsiString): Integer; cdecl; external; function PQclientEncoding(conn: PPGconn): Integer; cdecl; external; function pg_encoding_to_char(encoding_id: Integer): PFDAnsiString; cdecl; external; function PQerrorMessage(conn: PPGconn): PByte; cdecl; external; function PQbackendPID(conn: PPGconn): Integer; cdecl; external; // SSL *_PQgetssl(const PGconn *conn); // Command Execution Functions function PQexec(conn: PPGconn; command: PByte): PPGresult; cdecl; external; function PQexecParams(conn: PPGconn; command: PByte; nParams: integer; paramTypes: PInteger; ParamValues: Pointer; paramLengths: PInteger; paramFormats: Integer; resultFormat: Integer): PPGresult; cdecl; external; function PQprepare(conn: PPGconn; stmtName: PFDAnsiString; query: PByte; nParams: Integer; ParamTypes: POid): PPGresult; cdecl; external; function PQexecPrepared(conn: PPGconn; stmtName: PFDAnsiString; nParams: Integer; paramValues: Pointer; paramLengths: PInteger; paramFormats: PInteger; resultFormat: Integer): PPGresult; cdecl; external; function PQdescribePrepared(conn: PPGconn; stmtName: PFDAnsiString): PPGresult; cdecl; external; function PQdescribePortal(conn: PPGconn; portalName: PFDAnsiString): PPGresult; cdecl; external; function PQresultStatus(res: PPGresult): Integer; cdecl; external; function PQresultErrorMessage(res: PPGresult): PByte; cdecl; external; function PQresultErrorField(res: PPGResult; fieldcode: integer): PByte; cdecl; external; procedure PQclear(res: PPGresult); cdecl; external; function PQmakeEmptyPGresult(conn: PPGconn; status: Integer): PPGresult; cdecl; external; function PQntuples(res: PPGresult): Integer; cdecl; external; function PQnfields(res: PPGresult): Integer; cdecl; external; function PQfname(res: PPGresult; field_num: Integer): PByte; cdecl; external; function PQfnumber(res: PPGresult; field_name: PByte): Integer; cdecl; external; function PQftable(res: PPGresult; column_number: Integer): Oid; cdecl; external; function PQftablecol(res: PPGresult; column_number: Integer): Integer; cdecl; external; function PQfformat(res: PPGresult; column_number: Integer): Integer; cdecl; external; function PQftype(res: PPGresult; field_num: Integer): Oid; cdecl; external; function PQfmod(res: PPGresult; field_num: Integer): Integer; cdecl; external; function PQfsize(res: PPGresult; field_num: Integer): Integer; cdecl; external; function PQbinaryTuples(res: PPGresult): Integer; cdecl; external; function PQgetvalue(res: PPGresult; row_number, column_number: Integer): PByte; cdecl; external; function PQgetisnull(res: PPGresult; tup_num, field_num: Integer): Integer; cdecl; external; function PQgetlength(res: PPGresult; tup_num, field_num: Integer): Integer; cdecl; external; function PQnparams(res: PPGresult): Integer; cdecl; external; function PQparamtype(res: PPGresult; param_number: Integer): Oid; cdecl; external; function PQcmdStatus(res: PPGresult): PFDAnsiString; cdecl; external; function PQoidValue(res: PPGresult): Oid; cdecl; external; function PQoidStatus(res: PPGresult): PFDAnsiString; cdecl; external; function PQcmdTuples(res: PPGresult): PFDAnsiString; cdecl; external; // Notice Processing function PQsetNoticeReceiver(conn: PPGconn; proc: TPQnoticeReceiver; arg: Pointer): TPQnoticeReceiver; cdecl; external; function PQsetNoticeProcessor(conn: PPGconn; proc: TPQnoticeProcessor; arg: Pointer): TPQnoticeProcessor; cdecl; external; // Cancelling Queries in Progress function PQgetCancel(conn: PPGconn): PPGcancel; cdecl; external; procedure PQfreeCancel(cancel: PPGcancel); cdecl; external; function PQcancel(cancel: PPGcancel; errbuf: PFDAnsiString; errbufsize: Integer): Integer; cdecl; external; // Large Objects support function lo_creat(conn: PPGconn; mode: Integer): Oid; cdecl; external; function lo_open(conn: PPGconn; objoid: Oid; mode: Integer): Integer; cdecl; external; function lo_write(conn: PPGconn; fd: Integer; buf: Pointer; len: Integer): Integer; cdecl; external; function lo_read(conn: PPGconn; fd: Integer; buf: Pointer; len: Integer): Integer; cdecl; external; function lo_lseek(conn: PPGconn; fd: Integer; offset: Integer; whence: Integer): Integer; cdecl; external; function lo_tell(conn: PPGconn; fd: Integer): Integer; cdecl; external; function lo_close(conn: PPGconn; fd: Integer): Integer; cdecl; external; function lo_unlink(conn: PPGconn; objoid: Oid): Integer; cdecl; external; function PQgetResult(conn: PPGconn): PPGresult; cdecl; external; // Functions Associated with the COPY Command function PQputCopyData(conn: PPGconn; buffer: Pointer; nbytes: Integer): Integer; cdecl; external; function PQputCopyEnd(conn: PPGconn; errormsg: Pointer): Integer; cdecl; external; // Async notifications // Check after: prepare, execute, describe, isbusy, getresult, putcopydata function PQnotifies(conn: PPGconn): PPGnotify; cdecl; external; procedure PQfreemem(ptr: Pointer); cdecl; external; function PQconsumeInput(conn: PPGconn): Integer; cdecl; external; function PQsocket(conn: PPGconn): Integer; cdecl; external; {$ENDIF} type // Database Connection Control Functions TPQconnectdb = function(ConnInfo: PFDAnsiString): PPGconn; cdecl; // TPQsetdbLogin = function(Host, Port, Options, Tty, Db, User, Passwd: PFDAnsiString): PPGconn; cdecl; TPQconndefaults = function: PPQconninfoOption; cdecl; TPQfinish = procedure(conn: PPGconn); cdecl; TPQreset = procedure(conn: PPGconn); cdecl; // Connection Status Functions TPQdb = function(conn: PPGconn): PFDAnsiString; cdecl; TPQuser = function(conn: PPGconn): PFDAnsiString; cdecl; TPQpass = function(conn: PPGconn): PFDAnsiString; cdecl; TPQhost = function(conn: PPGconn): PFDAnsiString; cdecl; TPQport = function(conn: PPGconn): PFDAnsiString; cdecl; TPQtty = function(conn: PPGconn): PFDAnsiString; cdecl; TPQoptions = function(conn: PPGconn): PFDAnsiString; cdecl; TPQstatus = function(conn: PPGconn): Integer; cdecl; TPQparameterStatus = function(conn: PGconn; ParamName: PFDAnsiString): PFDAnsiString; cdecl; TPQtransactionStatus = function(conn: PGconn): Integer; cdecl; TPQserverVersion = function(conn: PPGconn): Integer; cdecl; TPQprotocolVersion = function(conn: PPGconn): Integer; cdecl; TPQsetClientEncoding = function(conn: PPGconn; encoding: PFDAnsiString): Integer; cdecl; TPQclientEncoding = function(conn: PPGconn): Integer; cdecl; Tpg_encoding_to_char = function(encoding_id: Integer): PFDAnsiString; cdecl; TPQerrorMessage = function(conn: PPGconn): PByte; cdecl; TPQbackendPID = function(conn: PPGconn): Integer; cdecl; // SSL *PQgetssl(const PGconn *conn); // Command Execution Functions TPQexec = function(conn: PPGconn; command: PByte): PPGresult; cdecl; TPQexecParams = function(conn: PPGconn; command: PByte; nParams: integer; paramTypes: PInteger; ParamValues: Pointer; paramLengths: PInteger; paramFormats: PInteger; resultFormat: Integer): PPGresult; cdecl; TPQprepare = function(conn: PPGconn; stmtName: PFDAnsiString; query: PByte; nParams: Integer; ParamTypes: POid): PPGresult; cdecl; TPQexecPrepared = function(conn: PPGconn; stmtName: PFDAnsiString; nParams: Integer; paramValues: Pointer; paramLengths: PInteger; paramFormats: PInteger; resultFormat: Integer): PPGresult; cdecl; TPQdescribePrepared = function(conn: PPGconn; stmtName: PFDAnsiString): PPGresult; cdecl; TPQdescribePortal = function(conn: PPGconn; portalName: PFDAnsiString): PPGresult; cdecl; TPQresultStatus = function(res: PPGresult): Integer; cdecl; TPQresultErrorMessage = function(res: PPGresult): PByte; cdecl; TPQresultErrorField = function(res: PPGResult; fieldcode: integer): PByte; cdecl; TPQclear = procedure(res: PPGresult); cdecl; TPQmakeEmptyPGresult = function(conn: PPGconn; status: Integer): PPGresult; cdecl; TPQntuples = function(res: PPGresult): Integer; cdecl; TPQnfields = function(res: PPGresult): Integer; cdecl; TPQfname = function(res: PPGresult; field_num: Integer): PByte; cdecl; TPQfnumber = function(res: PPGresult; field_name: PByte): Integer; cdecl; TPQftable = function(res: PPGresult; column_number: Integer): Oid; cdecl; TPQftablecol = function(res: PPGresult; column_number: Integer): Integer; cdecl; TPQfformat = function(res: PPGresult; column_number: Integer): Integer; cdecl; TPQftype = function(res: PPGresult; field_num: Integer): Oid; cdecl; TPQfmod = function(res: PPGresult; field_num: Integer): Integer; cdecl; TPQfsize = function(res: PPGresult; field_num: Integer): Integer; cdecl; TPQbinaryTuples = function(res: PPGresult): Integer; cdecl; TPQgetvalue = function(res: PPGresult; row_number, column_number: Integer): PByte; cdecl; TPQgetisnull = function(res: PPGresult; tup_num, field_num: Integer): Integer; cdecl; TPQgetlength = function(res: PPGresult; tup_num, field_num: Integer): Integer; cdecl; TPQnparams = function(res: PPGresult): Integer; cdecl; TPQparamtype = function(res: PPGresult; param_number: Integer): Oid; cdecl; TPQcmdStatus = function(res: PPGresult): PFDAnsiString; cdecl; TPQoidValue = function(res: PPGresult): Oid; cdecl; TPQoidStatus = function(res: PPGresult): PFDAnsiString; cdecl; TPQcmdTuples = function(res: PPGresult): PFDAnsiString; cdecl; // Notice Processing TPQsetNoticeReceiver = function(conn: PPGconn; proc: TPQnoticeReceiver; arg: Pointer): TPQnoticeReceiver; cdecl; TPQsetNoticeProcessor = function(conn: PPGconn; proc: TPQnoticeProcessor; arg: Pointer): TPQnoticeProcessor; cdecl; // Cancelling Queries in Progress TPQgetCancel = function(conn: PPGconn): PPGcancel; cdecl; TPQfreeCancel = procedure(cancel: PPGcancel); cdecl; TPQcancel = function(cancel: PPGcancel; errbuf: PFDAnsiString; errbufsize: Integer): Integer; cdecl; // Large Objects support Tlo_creat = function(conn: PPGconn; mode: Integer): Oid; cdecl; Tlo_open = function(conn: PPGconn; objoid: Oid; mode: Integer): Integer; cdecl; Tlo_write = function(conn: PPGconn; fd: Integer; buf: Pointer; len: Integer): Integer; cdecl; Tlo_read = function(conn: PPGconn; fd: Integer; buf: Pointer; len: Integer): Integer; cdecl; Tlo_lseek = function(conn: PPGconn; fd: Integer; offset: Integer; whence: Integer): Integer; cdecl; Tlo_tell = function(conn: PPGconn; fd: Integer): Integer; cdecl; Tlo_close = function(conn: PPGconn; fd: Integer): Integer; cdecl; Tlo_unlink = function(conn: PPGconn; objoid: Oid): Integer; cdecl; TPQgetResult = function(conn: PPGconn): PPGresult; cdecl; // Functions Associated with the COPY Command TPQputCopyData = function(conn: PPGconn; buffer: Pointer; nbytes: Integer): Integer; cdecl; TPQputCopyEnd = function(conn: PPGconn; errormsg: Pointer): Integer; cdecl; // Async notifications // Check after: prepare, execute, describe, isbusy, getresult, putcopydata TPQnotifies = function(conn: PPGconn): PPGnotify; cdecl; TPQfreemem = procedure(ptr: Pointer); cdecl; TPQconsumeInput = function(conn: PPGconn): Integer; cdecl; TPQsocket = function(conn: PPGconn): Integer; cdecl; // Functions mentioned below are not used in FireDAC PostgreSQL driver // Asynchronous Command Processing // PQsendQuery // PQsendQueryParams // PQsendPrepare // PQsendQueryPrepared // PQsendDescribePrepared // PQsendDescribePortal // PQgetResult // PQconsumeInput // PQisBusy // PQsetnonblocking // PQisnonblocking // PQflush // The Fast-Path Interface // PQfn implementation {$IFDEF FireDAC_PGSQL_STATIC} uses Winapi.Windows, Winapi.WinSock, System.ShlObj, FireDAC.Stan.CRTL; {$ENDIF} end.
unit EnvelopeFunctionsFrame; { ------------------------------------------------------------------------------ } interface { ------------------------------------------------------------------------------ } uses Windows, Messages, SysUtils, Variants, Classes, StrUtils, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, ExtCtrls, EUSignCP, EUSignCPOwnUI, Certificates; { ------------------------------------------------------------------------------ } type PEUBinaryItems = ^TEUBinaryItems; TEUBinaryItems = record Items: PPByte; ItemsSizes: PCardinal; Count: Cardinal; end; { ------------------------------------------------------------------------------ } type TEnvelopeFunctionsFrame = class(TFrame) SettingsPanel: TPanel; SettingsLabel: TLabel; SettingsUnderlineImage: TImage; AddSignCheckBox: TCheckBox; EncryptDataPanel: TPanel; SignDataUnderlineImage: TImage; DataLabel: TLabel; EncryptDataLabel: TLabel; EncryptDataTitleLabel: TLabel; EncryptDataButton: TButton; DecryptDataButton: TButton; EncryptedDataRichEdit: TRichEdit; EncryptDataEdit: TEdit; EncryptFilePanel: TPanel; SignFileUnderlineImage: TImage; EncryptFileLabel: TLabel; EncryptedFileLabel: TLabel; EncryptFileTitleLabel: TLabel; EncryptFileButton: TButton; DecryptFileButton: TButton; EncryptFileEdit: TEdit; ChooseEncryptFileButton: TButton; EncryptedFileEdit: TEdit; ChooseEncryptedFileButton: TButton; TestPanel: TPanel; TestEncryptionLabel: TLabel; FullDataTestButton: TButton; FullFileTestButton: TButton; TargetFileOpenDialog: TOpenDialog; DecryptedDataLabel: TLabel; DecryptedDataEdit: TEdit; DecryptedFileLabel: TLabel; DecryptedFileEdit: TEdit; ChooseDecryptedFileButton: TButton; MultiEnvelopCheckBox: TCheckBox; UseDynamycKeysCheckBox: TCheckBox; AppendCertCheckBox: TCheckBox; RecipientsCertsFromFileCheckBox: TCheckBox; procedure EncryptDataButtonClick(Sender: TObject); procedure DecryptDataButtonClick(Sender: TObject); procedure ChooseEncryptedFileButtonClick(Sender: TObject); procedure ChooseEncryptFileButtonClick(Sender: TObject); procedure EncryptFileButtonClick(Sender: TObject); procedure DecryptFileButtonClick(Sender: TObject); procedure FullDataTestButtonClick(Sender: TObject); procedure FullFileTestButtonClick(Sender: TObject); procedure ChooseDecryptedFileButtonClick(Sender: TObject); procedure UseDynamycKeysCheckBoxClick(Sender: TObject); procedure AddSignCheckBoxClick(Sender: TObject); private CPInterface: PEUSignCP; UseOwnUI: Boolean; procedure ChangeControlsState(Enabled: Boolean); procedure ClearAllData(); function GetOwnCertificateForEnvelop(Info: PPEUCertInfoEx): Cardinal; function ChooseCertificatesInfoForEncryption(OnlyOne: Boolean; CertsInfo: PEUCertificatesUniqueInfo): Cardinal; function ChooseCertificatesFromFile(OnlyOne: Boolean; Certificates: PEUBinaryItems): Cardinal; function EncryptData(CertsInfo: PEUCertificatesUniqueInfo; Data: PByte; DataLength: Cardinal; EnvelopedString: PPAnsiChar): Cardinal; function DynamicEncryptData(CertsInfo: PEUCertificatesUniqueInfo; Data: PByte; DataLength: Cardinal; EnvelopedString: PPAnsiChar): Cardinal; function EncryptDataToRecipients(Data: PByte; DataLength: Cardinal; EnvelopedString: PPAnsiChar): Cardinal; function EncryptFile(CertsInfo: PEUCertificatesUniqueInfo; TargetFile, EncryptedFileName: PAnsiChar) : Cardinal; function DynamicEncryptFile(CertsInfo: PEUCertificatesUniqueInfo; TargetFile, EncryptedFileName: PAnsiChar) : Cardinal; function EncryptFileToRecipients(TargetFile, EncryptedFileName: PAnsiChar) : Cardinal; public procedure Initialize(CPInterface: PEUSignCP; UseOwnUI: Boolean); procedure Deinitialize(); procedure WillShow(); end; { ------------------------------------------------------------------------------ } implementation { ------------------------------------------------------------------------------ } {$R *.dfm} { ============================================================================== } function AllocBinaryItems(Count: Cardinal; Items: PEUBinaryItems): Boolean; begin Items.Count := 0; Items.Items := nil; Items.ItemsSizes := nil; AllocBinaryItems := False; Items.Items := AllocMem(Count * SizeOf(PByte)); if (Items.Items = nil) then Exit; Items.ItemsSizes := AllocMem(Count * SizeOf(Cardinal)); if (Items.ItemsSizes = nil) then begin FreeMem(Items.Items); Items.Items := nil; Exit; end; Items.Count := Count; AllocBinaryItems := True; end; { ------------------------------------------------------------------------------ } procedure FreeBinaryItems(Items: PEUBinaryItems); var Index: Integer; CurItemDataPointer: PPByte; begin if (Items.Count = 0) then Exit; if (Items.ItemsSizes <> nil) then begin FreeMem(Items.ItemsSizes); Items.ItemsSizes := nil; end; if (Items.Items <> nil) then begin CurItemDataPointer := Items.Items; for Index := 0 to (Items.Count - 1) do begin if (CurItemDataPointer^ <> nil) then begin FreeMemory(CurItemDataPointer^); CurItemDataPointer^ := nil; end; CurItemDataPointer := Pointer(Cardinal( Pointer(CurItemDataPointer)) + SizeOf(PByte)); end; FreeMem(Items.Items); Items.Items := nil; end; Items.Count := 0; end; { ------------------------------------------------------------------------------ } function CreateBinaryItems(Count: Cardinal; var ItemsData: array of PByte; ItemsDataSizes: array of Cardinal; var Items: PEUBinaryItems): Boolean; var Index: Integer; CurItemDataPointer: PPByte; CurItemDataSizePointer: PCardinal; begin CreateBinaryItems := False; if (Length(ItemsData) <> Length(ItemsDataSizes)) then Exit; if (not AllocBinaryItems(Count, Items)) then Exit; CurItemDataPointer := Items.Items; CurItemDataSizePointer := Items.ItemsSizes; for Index := 0 to High(ItemsData) do begin CurItemDataPointer^ := GetMemory(ItemsDataSizes[Index] * SizeOf(Byte)); if (CurItemDataPointer^ = nil) then begin FreeBinaryItems(Items); Exit; end; CopyMemory(CurItemDataPointer^, ItemsData[Index], ItemsDataSizes[Index]); CurItemDataSizePointer^ := ItemsDataSizes[Index]; CurItemDataPointer := Pointer(Cardinal( Pointer(CurItemDataPointer)) + SizeOf(PByte)); CurItemDataSizePointer := Pointer(Cardinal( Pointer(CurItemDataSizePointer)) + SizeOf(Cardinal)); end; CreateBinaryItems := True; end; { ============================================================================== } procedure TEnvelopeFunctionsFrame.ChangeControlsState(Enabled: Boolean); var EncryptWithDynamicKey: Boolean; begin if (CPInterface <> nil) then begin UseDynamycKeysCheckBox.Enabled := CPInterface.IsInitialized(); end else begin UseDynamycKeysCheckBox.Enabled := False; end; EncryptWithDynamicKey := ((UseDynamycKeysCheckBox.Enabled and UseDynamycKeysCheckBox.Checked) or Enabled); AddSignCheckBox.Enabled := Enabled; RecipientsCertsFromFileCheckBox.Enabled := EncryptWithDynamicKey; AppendCertCheckBox.Enabled := (Enabled and AddSignCheckBox.Checked and UseDynamycKeysCheckBox.Checked); MultiEnvelopCheckBox.Enabled := EncryptWithDynamicKey; EncryptDataButton.Enabled := EncryptWithDynamicKey; DecryptDataButton.Enabled := Enabled; EncryptedDataRichEdit.Enabled := EncryptWithDynamicKey; EncryptDataEdit.Enabled := EncryptWithDynamicKey; EncryptFileButton.Enabled := EncryptWithDynamicKey; DecryptFileButton.Enabled := Enabled; EncryptFileEdit.Enabled := EncryptWithDynamicKey; ChooseEncryptFileButton.Enabled := EncryptWithDynamicKey; EncryptedFileEdit.Enabled := EncryptWithDynamicKey; ChooseEncryptedFileButton.Enabled := Enabled; FullDataTestButton.Enabled := Enabled; FullFileTestButton.Enabled := Enabled; DecryptedDataEdit.Enabled := Enabled; DecryptedFileEdit.Enabled := Enabled; ChooseDecryptedFileButton.Enabled := Enabled; end; { ------------------------------------------------------------------------------ } procedure TEnvelopeFunctionsFrame.Initialize(CPInterface: PEUSignCP; UseOwnUI: Boolean); begin self.CPInterface := CPInterface; self.UseOwnUI := UseOwnUI; ChangeControlsState(False); end; { ------------------------------------------------------------------------------ } procedure TEnvelopeFunctionsFrame.Deinitialize(); begin ClearAllData(); ChangeControlsState(False); self.CPInterface := nil; self.UseOwnUI := false; end; { ------------------------------------------------------------------------------ } procedure TEnvelopeFunctionsFrame.WillShow(); var Enabled: LongBool; begin Enabled := ((CPInterface <> nil) and CPInterface.IsInitialized and CPInterface.IsPrivateKeyReaded()); ChangeControlsState(Enabled); end; { ============================================================================== } procedure TEnvelopeFunctionsFrame.ClearAllData(); begin AddSignCheckBox.Checked := False; MultiEnvelopCheckBox.Checked := False; AppendCertCheckBox.Checked := False; RecipientsCertsFromFileCheckBox.Checked := False; if (CPInterface <> nil) then begin if (not CPInterface.IsInitialized) then UseDynamycKeysCheckBox.Checked := False; end else begin UseDynamycKeysCheckBox.Checked := False; end; EncryptFileEdit.Text := ''; EncryptedFileEdit.Text := ''; DecryptedFileEdit.Text := ''; EncryptDataEdit.Text := ''; EncryptedDataRichEdit.Text := ''; DecryptedDataEdit.Text := ''; end; { ============================================================================== } procedure TEnvelopeFunctionsFrame.AddSignCheckBoxClick(Sender: TObject); begin AppendCertCheckBox.Enabled := (AddSignCheckBox.Checked and UseDynamycKeysCheckBox.Checked); end; { ------------------------------------------------------------------------------ } procedure TEnvelopeFunctionsFrame.UseDynamycKeysCheckBoxClick(Sender: TObject); begin WillShow(); end; { ============================================================================== } function TEnvelopeFunctionsFrame.ChooseCertificatesInfoForEncryption( OnlyOne: Boolean; CertsInfo: PEUCertificatesUniqueInfo): Cardinal; var Info: PEUCertInfoEx; ReceiversCertificates: PEUCertificates; Index: Integer; Error: Cardinal; begin if UseOwnUI then begin if OnlyOne then begin if (not EUShowCertificates(WindowHandle, '', CPInterface, 'Сертифікати користувачів-отримувачів', CertTypeEndUser, @Info, EU_CERT_KEY_TYPE_DSTU4145, EU_KEY_USAGE_KEY_AGREEMENT)) then begin ChooseCertificatesInfoForEncryption := EU_ERROR_CANCELED_BY_GUI; Exit; end; SetLength(CertsInfo.Issuers, 1); SetLength(CertsInfo.Serials, 1); CertsInfo.Issuers[0] := Info.Issuer; CertsInfo.Serials[0] := Info.Serial; CPInterface.FreeCertificateInfoEx(Info); end else begin if (not EUSelectCertificates(WindowHandle, '', CPInterface, 'Сертифікати користувачів-отримувачів', CertTypeEndUser, CertsInfo, EU_CERT_KEY_TYPE_DSTU4145, EU_KEY_USAGE_KEY_AGREEMENT)) then begin ChooseCertificatesInfoForEncryption := EU_ERROR_CANCELED_BY_GUI; Exit; end; end; end else begin Error := CPInterface.GetReceiversCertificates(@ReceiversCertificates); if (Error <> EU_ERROR_NONE) then begin ChooseCertificatesInfoForEncryption := Error; Exit; end; if (ReceiversCertificates.Count < 1) then begin CPInterface.FreeReceiversCertificates(ReceiversCertificates); ChooseCertificatesInfoForEncryption := EU_ERROR_CANCELED_BY_GUI; Exit; end; if OnlyOne then begin Info := ReceiversCertificates.Certificates[0]; SetLength(CertsInfo.Issuers, 1); SetLength(CertsInfo.Serials, 1); CertsInfo.Issuers[0] := Info.Issuer; CertsInfo.Serials[0] := Info.Serial; end else begin SetLength(CertsInfo.Issuers, ReceiversCertificates.Count); SetLength(CertsInfo.Serials, ReceiversCertificates.Count); for Index := 0 to High(ReceiversCertificates.Certificates) do begin Info := ReceiversCertificates.Certificates[Index]; CertsInfo.Issuers[Index] := Info.Issuer; CertsInfo.Serials[Index] := Info.Serial; end; end; CPInterface.FreeReceiversCertificates(ReceiversCertificates); end; ChooseCertificatesInfoForEncryption := EU_ERROR_NONE; end; { ------------------------------------------------------------------------------ } function TEnvelopeFunctionsFrame.ChooseCertificatesFromFile(OnlyOne: Boolean; Certificates: PEUBinaryItems): Cardinal; var FileName: AnsiString; FileStream: TFileStream; CertificatesData: array of PByte; CertificatesDataLength: array of Cardinal; CertificatesCount: Cardinal; CertData: PByte; CertDataSize: Int64; MBResult: Integer; begin SetLength(CertificatesData, 0); SetLength(CertificatesDataLength, 0); CertificatesCount := 0; while True do begin TargetFileOpenDialog.Title := 'Оберіть файл з сертифікатом'; TargetFileOpenDialog.Filter := 'Файли з сертифікатами (*.cer)|*.cer'; if (not TargetFileOpenDialog.Execute()) then begin ChooseCertificatesFromFile := EU_ERROR_CANCELED_BY_GUI; Exit; end; FileName := AnsiString(TargetFileOpenDialog.FileName); if (FileName = '') then begin ChooseCertificatesFromFile := EU_ERROR_CANCELED_BY_GUI; Exit; end; FileStream := nil; try FileStream := TFileStream.Create(FileName, fmOpenRead); FileStream.Seek(0, soBeginning); CertDataSize := FileStream.Size; CertData := GetMemory(CertDataSize); FileStream.Read(CertData^, CertDataSize); CertificatesCount := CertificatesCount + 1; SetLength(CertificatesData, CertificatesCount); SetLength(CertificatesDataLength, CertificatesCount); CertificatesData[High(CertificatesData)] := CertData; CertificatesDataLength[High(CertificatesDataLength)] := CertDataSize; FileStream.Destroy; Except if (FileStream <> nil) then FileStream.Destroy; for CertData in CertificatesData do FreeMemory(CertData); ChooseCertificatesFromFile := EU_ERROR_UNKNOWN; Exit; end; if OnlyOne then Break; MBResult := MessageBoxA(Handle, 'Обрати наступний сетрифікат одержувача?', 'Повідомлення оператору', MB_YESNO or MB_ICONQUESTION); if (MBResult = IDNO) then Break; end; if (not (CreateBinaryItems(CertificatesCount, CertificatesData, CertificatesDataLength, Certificates))) then begin ChooseCertificatesFromFile := EU_ERROR_MEMORY_ALLOCATION; for CertData in CertificatesData do FreeMemory(CertData); Exit; end; for CertData in CertificatesData do FreeMemory(CertData); ChooseCertificatesFromFile := EU_ERROR_NONE; end; { ============================================================================== } function TEnvelopeFunctionsFrame.EncryptData( CertsInfo: PEUCertificatesUniqueInfo; Data: PByte; DataLength: Cardinal; EnvelopedString: PPAnsiChar): Cardinal; var UseSign: LongBool; Issuers: PAnsiChar; Serials: PAnsiChar; Error: Cardinal; begin UseSign := (AddSignCheckBox.Checked and AddSignCheckBox.Enabled); if MultiEnvelopCheckBox.Checked then begin Issuers := nil; Serials := nil; Error := EU_ERROR_MEMORY_ALLOCATION; if (EUStringArrayToPAnsiChar(CertsInfo.Issuers, @Issuers) and EUStringArrayToPAnsiChar(CertsInfo.Serials, @Serials)) then begin Error := CPInterface.EnvelopDataEx(Issuers, Serials, UseSign, Data, DataLength, @EnvelopedString, nil, nil); end; if (Issuers <> nil) then FreeMem(Issuers); if (Serials <> nil) then FreeMem(Serials); if (Error <> EU_ERROR_NONE) then begin EncryptData := Error; Exit; end; end else begin Error := CPInterface.EnvelopData(PAnsiChar(CertsInfo.Issuers[0]), PAnsiChar(CertsInfo.Serials[0]), UseSign, Data, DataLength, @EnvelopedString, nil, nil); if (Error <> EU_ERROR_NONE) then begin EncryptData := Error; Exit; end; end; EncryptData := EU_ERROR_NONE; end; { ------------------------------------------------------------------------------ } function TEnvelopeFunctionsFrame.DynamicEncryptData( CertsInfo: PEUCertificatesUniqueInfo; Data: PByte; DataLength: Cardinal; EnvelopedString: PPAnsiChar): Cardinal; var UseSign: LongBool; AppendCert: LongBool; Issuers: PAnsiChar; Serials: PAnsiChar; Error: Cardinal; begin Issuers := nil; Serials := nil; if (not EUStringArrayToPAnsiChar(CertsInfo.Issuers, @Issuers)) then begin DynamicEncryptData := EU_ERROR_MEMORY_ALLOCATION; Exit; end; if (not EUStringArrayToPAnsiChar(CertsInfo.Serials, @Serials)) then begin FreeMem(Issuers); DynamicEncryptData := EU_ERROR_MEMORY_ALLOCATION; Exit; end; UseSign := (AddSignCheckBox.Checked and AddSignCheckBox.Enabled); AppendCert := (AppendCertCheckBox.Checked and AppendCertCheckBox.Enabled); Error := CPInterface.EnvelopDataExWithDynamicKey(Issuers, Serials, UseSign, AppendCert, Data, DataLength, EnvelopedString, nil, nil); if (Error <> EU_ERROR_NONE) then begin FreeMem(Issuers); FreeMem(Serials); DynamicEncryptData := Error; Exit; end; FreeMem(Issuers); FreeMem(Serials); DynamicEncryptData := EU_ERROR_NONE; end; { ------------------------------------------------------------------------------ } function TEnvelopeFunctionsFrame.EncryptDataToRecipients(Data: PByte; DataLength: Cardinal; EnvelopedString: PPAnsiChar): Cardinal; var UseSign: LongBool; AppendCert: LongBool; RecipientsCerts: TEUBinaryItems; Error: Cardinal; begin UseSign := (AddSignCheckBox.Checked and AddSignCheckBox.Enabled); AppendCert := (AppendCertCheckBox.Checked and AppendCertCheckBox.Enabled); Error := ChooseCertificatesFromFile((not MultiEnvelopCheckBox.Checked), @RecipientsCerts); if (Error <> EU_ERROR_NONE) then begin EncryptDataToRecipients := Error; Exit; end; if (RecipientsCerts.Count < 1) then begin EncryptDataToRecipients := EU_ERROR_CANCELED_BY_GUI; Exit; end; if UseDynamycKeysCheckBox.Checked then begin Error := CPInterface.EnvelopDataToRecipientsWithDynamicKey( RecipientsCerts.Count, RecipientsCerts.Items, RecipientsCerts.ItemsSizes, UseSign, AppendCert, Data, DataLength, EnvelopedString, nil, nil); end else begin Error := CPInterface.EnvelopDataToRecipients(RecipientsCerts.Count, @RecipientsCerts.Items, @RecipientsCerts.ItemsSizes, UseSign, Data, DataLength, EnvelopedString, nil, nil); end; if (Error <> EU_ERROR_NONE) then begin FreeBinaryItems(@RecipientsCerts); EncryptDataToRecipients := Error; Exit; end; FreeBinaryItems(@RecipientsCerts); EncryptDataToRecipients := EU_ERROR_NONE; end; { ------------------------------------------------------------------------------ } procedure TEnvelopeFunctionsFrame.EncryptDataButtonClick(Sender: TObject); var DataString: WideString; DataStringLength: Cardinal; EnvelopedString: PAnsiChar; CertsInfo: TEUCertificatesUniqueInfo; Error: Cardinal; begin if (not CPInterface.IsPrivateKeyReaded() and (not UseDynamycKeysCheckBox.Checked)) then begin MessageBoxA(Handle, 'Особистий ключ не зчитано', 'Повідомлення оператору', MB_ICONERROR); Exit; end; DataString := WideString(EncryptDataEdit.Text); if (Length(DataString) > 0) then begin DataStringLength := (Length(DataString) + 1) * 2; end else DataStringLength := 0; EncryptedDataRichEdit.Text := ''; DecryptedDataEdit.Text := ''; if (RecipientsCertsFromFileCheckBox.Checked and RecipientsCertsFromFileCheckBox.Enabled) then begin Error := EncryptDataToRecipients(PByte(DataString), DataStringLength, @EnvelopedString); end else begin Error := ChooseCertificatesInfoForEncryption(not MultiEnvelopCheckBox.Checked, @CertsInfo); if (Error <> EU_ERROR_NONE) then begin if (Error <> EU_ERROR_CANCELED_BY_GUI) then EUShowError(Handle, Error); Exit; end; if UseDynamycKeysCheckBox.Checked then begin Error := DynamicEncryptData(@CertsInfo, PByte(DataString), DataStringLength, @EnvelopedString); end else begin Error := DynamicEncryptData(@CertsInfo, PByte(DataString), DataStringLength, @EnvelopedString); end; end; if (Error <> EU_ERROR_NONE) then begin if (Error <> EU_ERROR_CANCELED_BY_GUI) then EUShowError(Handle, Error); Exit; end; EncryptedDataRichEdit.Text := string(EnvelopedString); CPInterface.FreeMemory(PByte(EnvelopedString)); end; { ------------------------------------------------------------------------------ } procedure TEnvelopeFunctionsFrame.DecryptDataButtonClick(Sender: TObject); var Error: Cardinal; EnvelopInfo: TEUEnvelopInfo; Data: PByte; DataLength: Cardinal; AnsiSignStringing: AnsiString; begin if (not CPInterface.IsPrivateKeyReaded()) then begin MessageBoxA(Handle, 'Особистий ключ не зчитано', 'Повідомлення оператору', MB_ICONERROR); Exit; end; DataLength := 0; Data := nil; AnsiSignStringing := AnsiString(EncryptedDataRichEdit.Text); DecryptedDataEdit.Text := ''; Error := CPInterface.DevelopData(PAnsiChar(AnsiSignStringing), nil, 0, @Data, @DataLength, @EnvelopInfo); if (Error <> EU_ERROR_NONE) then begin EUShowError(Handle, Error); Exit; end; if (EnvelopInfo.Filled) then begin if UseOwnUI then begin EUSignCPOwnUI.EUShowSignInfo(WindowHandle, '', @EnvelopInfo, EnvelopInfo.bTime, True, True); end else CPInterface.ShowSenderInfo(@EnvelopInfo); end; if (DataLength > 0) then DecryptedDataEdit.Text := String(PWideChar(Data)); CPInterface.FreeSenderInfo(@EnvelopInfo); CPInterface.FreeMemory(Data); end; { ============================================================================== } procedure TEnvelopeFunctionsFrame.ChooseEncryptFileButtonClick(Sender: TObject); begin TargetFileOpenDialog.Title := 'Оберіть файл для зашифрування'; TargetFileOpenDialog.FileName := ''; TargetFileOpenDialog.Filter := ''; if (not TargetFileOpenDialog.Execute(Handle)) then Exit; EncryptFileEdit.Text := TargetFileOpenDialog.FileName; end; { ------------------------------------------------------------------------------ } function TEnvelopeFunctionsFrame.EncryptFile( CertsInfo: PEUCertificatesUniqueInfo; TargetFile, EncryptedFileName: PAnsiChar) : Cardinal; var UseSign: LongBool; Issuers: PAnsiChar; Serials: PAnsiChar; Error: Cardinal; begin UseSign := (AddSignCheckBox.Checked and AddSignCheckBox.Enabled); if MultiEnvelopCheckBox.Checked then begin Issuers := nil; Serials := nil; Error := EU_ERROR_MEMORY_ALLOCATION; if (EUStringArrayToPAnsiChar(CertsInfo.Issuers, @Issuers) and EUStringArrayToPAnsiChar(CertsInfo.Serials, @Serials)) then begin Error := CPInterface.EnvelopFileEx(Issuers, Serials, UseSign, PAnsiChar(TargetFile), PAnsiChar(EncryptedFileName)); end; if (Issuers <> nil) then FreeMem(Issuers); if (Serials <> nil) then FreeMem(Serials); end else begin Error := CPInterface.EnvelopFile(PAnsiChar(CertsInfo.Issuers[0]), PAnsiChar(CertsInfo.Serials[0]), UseSign, PAnsiChar(TargetFile), PAnsiChar(EncryptedFileName)); end; EncryptFile := Error; end; { ------------------------------------------------------------------------------ } function TEnvelopeFunctionsFrame.DynamicEncryptFile( CertsInfo: PEUCertificatesUniqueInfo; TargetFile, EncryptedFileName: PAnsiChar): Cardinal; var UseSign: LongBool; AppendCert: LongBool; Issuers: PAnsiChar; Serials: PAnsiChar; Error: Cardinal; begin Issuers := nil; Serials := nil; if (not EUStringArrayToPAnsiChar(CertsInfo.Issuers, @Issuers)) then begin DynamicEncryptFile := EU_ERROR_MEMORY_ALLOCATION; Exit; end; if (not EUStringArrayToPAnsiChar(CertsInfo.Serials, @Serials)) then begin FreeMem(Issuers); DynamicEncryptFile := EU_ERROR_MEMORY_ALLOCATION; Exit; end; UseSign := (AddSignCheckBox.Checked and AddSignCheckBox.Enabled); AppendCert := (AppendCertCheckBox.Checked and AppendCertCheckBox.Enabled); Error := CPInterface.EnvelopFileExWithDynamicKey(Issuers, Serials, UseSign, AppendCert, TargetFile, EncryptedFileName); if (Error <> EU_ERROR_NONE) then begin FreeMem(Issuers); FreeMem(Serials); DynamicEncryptFile := Error; Exit; end; FreeMem(Issuers); FreeMem(Serials); DynamicEncryptFile := EU_ERROR_NONE; end; { ------------------------------------------------------------------------------ } function TEnvelopeFunctionsFrame.EncryptFileToRecipients(TargetFile, EncryptedFileName: PAnsiChar) : Cardinal; var UseSign: LongBool; AppendCert: LongBool; RecipientsCerts: TEUBinaryItems; Error: Cardinal; begin Error := ChooseCertificatesFromFile((not MultiEnvelopCheckBox.Checked), @RecipientsCerts); if (Error <> EU_ERROR_NONE) then begin EncryptFileToRecipients := Error; Exit; end; if (RecipientsCerts.Count < 1) then begin EncryptFileToRecipients := EU_ERROR_CANCELED_BY_GUI; Exit; end; UseSign := (AddSignCheckBox.Checked and AddSignCheckBox.Enabled); AppendCert := (AppendCertCheckBox.Checked and AppendCertCheckBox.Enabled); if UseDynamycKeysCheckBox.Checked then begin Error := CPInterface.EnvelopFileToRecipientsWithDynamicKey( RecipientsCerts.Count, RecipientsCerts.Items, @RecipientsCerts.ItemsSizes, UseSign, AppendCert, TargetFile, EncryptedFileName); end else begin Error := CPInterface.EnvelopFileToRecipients(RecipientsCerts.Count, @RecipientsCerts.Items, @RecipientsCerts.ItemsSizes, UseSign, TargetFile, EncryptedFileName); end; if (Error <> EU_ERROR_NONE) then begin FreeBinaryItems(@RecipientsCerts); EncryptFileToRecipients := Error; Exit; end; FreeBinaryItems(@RecipientsCerts); EncryptFileToRecipients := EU_ERROR_NONE; end; { ------------------------------------------------------------------------------ } procedure TEnvelopeFunctionsFrame.EncryptFileButtonClick(Sender: TObject); var TargetFile: AnsiString; EncryptedFileName: AnsiString; CertsInfo: TEUCertificatesUniqueInfo; Error: Cardinal; begin if ((not CPInterface.IsPrivateKeyReaded()) and (not UseDynamycKeysCheckBox.Checked)) then begin MessageBoxA(Handle, 'Особистий ключ не зчитано', 'Повідомлення оператору', MB_ICONERROR); Exit; end; if (Length(EncryptFileEdit.Text) = 0) then begin MessageBoxA(Handle, 'Файл для зашифрування не обрано', 'Повідомлення оператору', MB_ICONERROR); Exit; end; TargetFile := AnsiString(EncryptFileEdit.Text); if (EncryptedFileEdit.Text <> '') then begin EncryptedFileName := AnsiString(EncryptedFileEdit.Text); end else EncryptedFileName := TargetFile + '.p7e'; DecryptedFileEdit.Text := ''; if (RecipientsCertsFromFileCheckBox.Checked and RecipientsCertsFromFileCheckBox.Enabled) then begin Error := EncryptFileToRecipients(PAnsiChar(TargetFile), PAnsiChar(EncryptedFileName)) end else begin Error := ChooseCertificatesInfoForEncryption( not MultiEnvelopCheckBox.Checked, @CertsInfo); if (Error <> EU_ERROR_NONE) then begin if (Error <> EU_ERROR_CANCELED_BY_GUI) then EUShowError(Handle, Error); Exit; end; if UseDynamycKeysCheckBox.Checked then begin Error := DynamicEncryptFile(@CertsInfo, PAnsiChar(TargetFile), PAnsiChar(EncryptedFileName)); end else begin Error := EncryptFile(@CertsInfo, PAnsiChar(TargetFile), PAnsiChar(EncryptedFileName)); end; end; if (Error <> EU_ERROR_NONE) then begin if (Error <> EU_ERROR_CANCELED_BY_GUI) then EUShowError(Handle, Error); Exit; end; EncryptedFileEdit.Text := EncryptedFileName; MessageBox(Handle, 'Файл успішно зашифрованно', 'Повідомлення оператору', MB_ICONINFORMATION); end; { ------------------------------------------------------------------------------ } procedure TEnvelopeFunctionsFrame.ChooseEncryptedFileButtonClick(Sender: TObject); begin TargetFileOpenDialog.Title := 'Оберіть зашифрований файл'; TargetFileOpenDialog.FileName := ''; TargetFileOpenDialog.Filter := ''; if (not TargetFileOpenDialog.Execute(Handle)) then Exit; EncryptedFileEdit.Text := TargetFileOpenDialog.FileName; end; { ------------------------------------------------------------------------------ } procedure TEnvelopeFunctionsFrame.ChooseDecryptedFileButtonClick( Sender: TObject); begin TargetFileOpenDialog.Title := 'Оберіть файл'; TargetFileOpenDialog.FileName := ''; TargetFileOpenDialog.Filter := ''; if (not TargetFileOpenDialog.Execute(Handle)) then Exit; DecryptedFileEdit.Text := TargetFileOpenDialog.FileName; end; { ------------------------------------------------------------------------------ } procedure TEnvelopeFunctionsFrame.DecryptFileButtonClick(Sender: TObject); var Error: Cardinal; EnvelopInfo: TEUEnvelopInfo; TargetFile: AnsiString; DecryptedFile: AnsiString; begin if (not CPInterface.IsPrivateKeyReaded()) then begin MessageBoxA(Handle, 'Особистий ключ не зчитано', 'Повідомлення оператору', MB_ICONERROR); Exit; end; if (Length(EncryptedFileEdit.Text) = 0) then begin MessageBoxA(Handle, 'Файл для розшифрування (*.p7e) не обрано', 'Повідомлення оператору', MB_ICONERROR); Exit; end; TargetFile := AnsiString(EncryptedFileEdit.Text); if (DecryptedFileEdit.Text <> '') then begin DecryptedFile := AnsiString(DecryptedFileEdit.Text); end else DecryptedFile := LeftStr(TargetFile, Length(TargetFile) - 4); Error := CPInterface.DevelopFile(PAnsiChar(TargetFile), PAnsiChar(DecryptedFile), @EnvelopInfo); if (Error <> EU_ERROR_NONE) then begin EUShowError(Handle, Error); Exit; end; if(EnvelopInfo.Filled) then begin if UseOwnUI then begin EUSignCPOwnUI.EUShowSignInfo(WindowHandle, '', @EnvelopInfo, EnvelopInfo.bTime, True, True); end else CPInterface.ShowSenderInfo(@EnvelopInfo); end; DecryptedFileEdit.Text := DecryptedFile; CPInterface.FreeSenderInfo(@EnvelopInfo); MessageBox(Handle, 'Файл успішно розшифрованно', 'Повідомлення оператору', MB_ICONINFORMATION); end; { ============================================================================== } function TEnvelopeFunctionsFrame.GetOwnCertificateForEnvelop (Info: PPEUCertInfoEx): Cardinal; var Index: Cardinal; begin Index := 0; while True do begin Result := CPInterface.EnumOwnCertificates(Index, Info); if (Result <> EU_ERROR_NONE) then Exit; if (Info^.PublicKeyType = EU_CERT_KEY_TYPE_DSTU4145) and ((Info^.KeyUsageType and EU_KEY_USAGE_KEY_AGREEMENT)= EU_KEY_USAGE_KEY_AGREEMENT) then begin Exit; end; Index := Index + 1; CPInterface.FreeCertificateInfoEx(Info^); end; end; { ------------------------------------------------------------------------------ } procedure TEnvelopeFunctionsFrame.FullDataTestButtonClick(Sender: TObject); var Data, EnvData, DevData: PByte; DataSize, EnvDataSize, DevDataSize, Error: Cardinal; EnvDataString: PAnsiChar; EnvelopInfo: TEUEnvelopInfo; Index: Integer; Info: PEUCertInfoEx; Issuer, Serial: AnsiString; begin if (not CPInterface.IsPrivateKeyReaded()) then begin MessageBoxA(Handle, 'Особистий ключ не зчитано', 'Повідомлення оператору', MB_ICONERROR); Exit; end; Error := GetOwnCertificateForEnvelop(@Info); if (Error <> EU_ERROR_NONE) then begin EUShowError(Handle, Error); Exit; end; Issuer := Info.Issuer; Serial := Info.Serial; CPInterface.FreeCertificateInfoEx(Info); DataSize := $00800000; Data := GetMemory(DataSize); if (Data = nil) then begin MessageBoxA(Handle, 'Недостатньо ресурсів для завершення операції', 'Повідомлення оператору', MB_ICONERROR); Exit; end; for Index := 0 to (DataSize - 1) do {$if CompilerVersion > 19} Data[Index] := Index; {$else} PByte(Cardinal(Data) + Index)^ := Index; {$ifend} Error := CPInterface.EnvelopData(PAnsiChar(Issuer), PAnsiChar(Serial), False, Data, DataSize, nil, @EnvData, @EnvDataSize); if (Error <> EU_ERROR_NONE) then begin FreeMemory(Data); EUShowError(Handle, Error); Exit; end; Error := CPInterface.DevelopData(nil, EnvData, EnvDataSize, @DevData, @DevDataSize, @EnvelopInfo); if (Error <> EU_ERROR_NONE) then begin FreeMemory(Data); CPInterface.FreeMemory(EnvData); EUShowError(Handle, Error); Exit; end; if UseOwnUI then begin EUShowSignInfo(WindowHandle, '', @EnvelopInfo, False, True, True); end else CPInterface.ShowSignInfo(@EnvelopInfo); if (DevDataSize <> DataSize) or (not CompareMem(Data, DevData, DataSize)) then begin FreeMemory(Data); CPInterface.FreeMemory(EnvData); CPInterface.FreeMemory(DevData); CPInterface.FreeSignInfo(@EnvelopInfo); MessageBoxA(Handle, 'Виникла помилка при тестуванні: дані не співпадають', 'Повідомлення оператору', MB_ICONERROR); Exit; end; CPInterface.FreeMemory(EnvData); CPInterface.FreeMemory(DevData); CPInterface.FreeSignInfo(@EnvelopInfo); Error := CPInterface.EnvelopData(PAnsiChar(Issuer), PAnsiChar(Serial), True, Data, DataSize, nil, @EnvData, @EnvDataSize); if (Error <> EU_ERROR_NONE) then begin FreeMemory(Data); EUShowError(Handle, Error); Exit; end; Error := CPInterface.DevelopData(nil, EnvData, EnvDataSize, @DevData, @DevDataSize, @EnvelopInfo); if (Error <> EU_ERROR_NONE) then begin FreeMemory(Data); CPInterface.FreeMemory(EnvData); EUShowError(Handle, Error); Exit; end; if UseOwnUI then begin EUShowSignInfo(WindowHandle, '', @EnvelopInfo, True, False, True); end else CPInterface.ShowSignInfo(@EnvelopInfo); if (DevDataSize <> DataSize) or (not CompareMem(Data, DevData, DataSize)) then begin FreeMemory(Data); CPInterface.FreeMemory(EnvData); CPInterface.FreeMemory(DevData); CPInterface.FreeSignInfo(@EnvelopInfo); MessageBoxA(Handle, 'Виникла помилка при тестуванні: дані не співпадають', 'Повідомлення оператору', MB_ICONERROR); Exit; end; CPInterface.FreeMemory(EnvData); CPInterface.FreeMemory(DevData); CPInterface.FreeSignInfo(@EnvelopInfo); Error := CPInterface.EnvelopData(PAnsiChar(Issuer), PAnsiChar(Serial), False, Data, DataSize, @EnvDataString, nil, nil); if (Error <> EU_ERROR_NONE) then begin FreeMemory(Data); EUShowError(Handle, Error); Exit; end; Error := CPInterface.DevelopData(EnvDataString, nil, 0, @DevData, @DevDataSize, @EnvelopInfo); if (Error <> EU_ERROR_NONE) then begin FreeMemory(Data); CPInterface.FreeMemory(PByte(EnvDataString)); EUShowError(Handle, Error); Exit; end; if UseOwnUI then begin EUShowSignInfo(WindowHandle, '', @EnvelopInfo, False, True, True); end else CPInterface.ShowSignInfo(@EnvelopInfo); if (DevDataSize <> DataSize) or (not CompareMem(Data, DevData, DataSize)) then begin FreeMemory(Data); CPInterface.FreeMemory(PByte(EnvDataString)); CPInterface.FreeMemory(DevData); CPInterface.FreeSignInfo(@EnvelopInfo); MessageBoxA(Handle, 'Виникла помилка при тестуванні: дані не співпадають', 'Повідомлення оператору', MB_ICONERROR); Exit; end; CPInterface.FreeMemory(PByte(EnvDataString)); CPInterface.FreeMemory(DevData); CPInterface.FreeSignInfo(@EnvelopInfo); Error := CPInterface.EnvelopData(PAnsiChar(Issuer), PAnsiChar(Serial), True, Data, DataSize, @EnvDataString, nil, nil); if (Error <> EU_ERROR_NONE) then begin FreeMemory(Data); EUShowError(Handle, Error); Exit; end; Error := CPInterface.DevelopData(EnvDataString, nil, 0, @DevData, @DevDataSize, @EnvelopInfo); if (Error <> EU_ERROR_NONE) then begin FreeMemory(Data); CPInterface.FreeMemory(PByte(EnvDataString)); EUShowError(Handle, Error); Exit; end; if UseOwnUI then begin EUShowSignInfo(WindowHandle, '', @EnvelopInfo, True, True, True); end else CPInterface.ShowSignInfo(@EnvelopInfo); if (DevDataSize <> DataSize) or (not CompareMem(Data, DevData, DataSize)) then begin FreeMemory(Data); CPInterface.FreeMemory(PByte(EnvDataString)); CPInterface.FreeMemory(DevData); CPInterface.FreeSignInfo(@EnvelopInfo); MessageBoxA(Handle, 'Виникла помилка при тестуванні: дані не співпадають', 'Повідомлення оператору', MB_ICONERROR); Exit; end; CPInterface.FreeMemory(PByte(EnvDataString)); CPInterface.FreeMemory(DevData); CPInterface.FreeSignInfo(@EnvelopInfo); MessageBoxA(Handle, 'Тестування виконано успішно', 'Повідомлення оператору', MB_ICONINFORMATION); end; { ------------------------------------------------------------------------------ } procedure TEnvelopeFunctionsFrame.FullFileTestButtonClick(Sender: TObject); var FileName, EnvFileName, DevFileName: AnsiString; Error: Cardinal; EnvelopInfo: TEUEnvelopInfo; Info: PEUCertInfoEx; Issuer, Serial: AnsiString; begin if (not CPInterface.IsPrivateKeyReaded()) then begin MessageBoxA(Handle, 'Особистий ключ не зчитано', 'Повідомлення оператору', MB_ICONERROR); Exit; end; TargetFileOpenDialog.Title := 'Оберіть файл для тестування'; if (not TargetFileOpenDialog.Execute()) then Exit; FileName := TargetFileOpenDialog.FileName; if (Length(FileName) = 0) then begin MessageBoxA(Handle, 'Файл для тестування шифрування файлів не обрано', 'Повідомлення оператору', MB_ICONERROR); Exit; end; EnvFileName := FileName + '.p7e'; DevFileName := LeftStr(FileName, Length(FileName) - 8) + '.new' + RightStr(FileName, 4); Error := GetOwnCertificateForEnvelop(@Info); if (Error <> EU_ERROR_NONE) then begin if Error = EU_WARNING_END_OF_ENUM then begin MessageBoxA(Handle, 'Зашифрування даних на ключі користувача не можливо', 'Повідомлення оператору', MB_ICONERROR); end else EUShowError(Handle, Error); Exit; end; Issuer := Info.Issuer; Serial := Info.Serial; CPInterface.FreeCertificateInfoEx(Info); Error := CPInterface.EnvelopFile(PAnsiChar(Issuer), PAnsiChar(Serial), False, PAnsiChar(FileName), PAnsiChar(EnvFileName)); if (Error <> EU_ERROR_NONE) then begin EUShowError(Handle, Error); Exit; end; Error := CPInterface.DevelopFile(PAnsiChar(EnvFileName), PAnsiChar(DevFileName), @EnvelopInfo); if (Error <> EU_ERROR_NONE) then begin EUShowError(Handle, Error); Exit; end; if UseOwnUI then begin EUSignCPOwnUI.EUShowSignInfo(WindowHandle, '', @EnvelopInfo, EnvelopInfo.bTime, True, True); end else CPInterface.ShowSenderInfo(@EnvelopInfo); CPInterface.FreeSignInfo(@EnvelopInfo); Error := CPInterface.EnvelopFile(PAnsiChar(Issuer), PAnsiChar(Serial), True, PAnsiChar(FileName), PAnsiChar(EnvFileName)); if (Error <> EU_ERROR_NONE) then begin EUShowError(Handle, Error); Exit; end; Error := CPInterface.DevelopFile(PAnsiChar(EnvFileName), PAnsiChar(DevFileName), @EnvelopInfo); if (Error <> EU_ERROR_NONE) then begin EUShowError(Handle, Error); Exit; end; if UseOwnUI then begin EUSignCPOwnUI.EUShowSignInfo(WindowHandle, '', @EnvelopInfo, EnvelopInfo.bTime, True, True); end else CPInterface.ShowSenderInfo(@EnvelopInfo); CPInterface.FreeSignInfo(@EnvelopInfo); MessageBoxA(Handle, 'Тестування виконано успішно', 'Повідомлення оператору', MB_ICONINFORMATION); end; { ============================================================================== } end.
unit SPDialog; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, AncestorDialog, Vcl.ActnList, dsdAction, cxClasses, cxPropertiesStore, dsdAddOn, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, Vcl.Menus, Vcl.StdCtrls, cxButtons, cxTextEdit, Vcl.ExtCtrls, dsdGuides, dsdDB, cxMaskEdit, cxButtonEdit, AncestorBase, dxSkinsCore, dxSkinsDefaultPainters, Vcl.ComCtrls, dxCore, cxDateUtils, cxDropDownEdit, cxCalendar, cxLabel, dxSkinBlack, dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy, dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMoneyTwins, dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus, dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008, dxSkinTheAsphaltWorld, dxSkinValentine, dxSkinVS2010, dxSkinWhiteprint, dxSkinXmas2008Blue, System.Actions; type TSPDialogForm = class(TAncestorDialogForm) cePartnerMedical: TcxButtonEdit; PartnerMedicalGuides: TdsdGuides; Label1: TLabel; Label2: TLabel; cxLabel13: TcxLabel; edOperDateSP: TcxDateEdit; cxLabel14: TcxLabel; edInvNumberSP: TcxTextEdit; cxLabel17: TcxLabel; edAmbulance: TcxTextEdit; edMedicSP: TcxButtonEdit; MedicSPGuides: TdsdGuides; Label3: TLabel; edSPKind: TcxButtonEdit; SPKindGuides: TdsdGuides; spGet_SPKind_def: TdsdStoredProc; bbSP_Prior: TcxButton; spGet_SP_Prior: TdsdStoredProc; Panel1: TPanel; Panel2: TPanel; cxLabel22: TcxLabel; cxLabel23: TcxLabel; cxLabel24: TcxLabel; cxLabel25: TcxLabel; cxLabel26: TcxLabel; edMemberSP: TcxButtonEdit; edPassport: TcxTextEdit; edInn: TcxTextEdit; edAddress: TcxTextEdit; GuidesMemberSP: TdsdGuides; edGroupMemberSP: TcxTextEdit; spSelect_Object_MemberSP: TdsdStoredProc; spGet_Movement_InvNumberSP: TdsdStoredProc; procedure bbOkClick(Sender: TObject); procedure DiscountExternalGuidesAfterChoice(Sender: TObject); procedure bbSP_PriorClick(Sender: TObject); procedure edSPKindPropertiesChange(Sender: TObject); procedure cePartnerMedicalPropertiesChange(Sender: TObject); private { Private declarations } FHelsiID : string; FHelsiIDList : string; FHelsiName : string; FHelsiDenUnit : string; FHelsiQty : currency; FHelsiDate : TDateTime; FProgramId : string; FProgramName : string; FPartialPrescription : Boolean; FSkipDispenseSign : Boolean; public function DiscountDialogExecute(var APartnerMedicalId, ASPKindId: Integer; var APartnerMedicalName, AAmbulance, AMedicSP, AInvNumberSP, ASPKindName: String; var AOperDateSP : TDateTime; var ASPTax : Currency; var AMemberSPID: Integer; var AMemberSPName: String; var AHelsiID, AHelsiIDList, AHelsiName, AHelsiDenUnit : string; var AHelsiQty : currency; var AHelsiProgramId, AHelsiProgramName : String; var AHelsiPartialPrescription, AHelsiSkipDispenseSign : Boolean; var AisPaperRecipeSP : Boolean): boolean; function CheckInvNumberSP(ASPKind : integer; ANumber : string) : boolean; end; implementation {$R *.dfm} uses IniUtils, DiscountService, RegularExpressions, MainCash2, Helsi, LikiDniproeHealth; function TSPDialogForm.CheckInvNumberSP(ASPKind : integer; ANumber : string) : boolean; var Res: TArray<string>; I, J : Integer; bCheck : boolean; begin Result := False; if (MainCashForm.UnitConfigCDS.FieldByName('Helsi_IdSP').AsInteger = 0) or (MainCashForm.UnitConfigCDS.FieldByName('Helsi_IdSP').AsInteger <> ASPKind) then begin if Length(ANumber) <> 19 then begin ShowMessage ('Ошибка.<Номер рецепта> должен содержать 19 символов...'); exit; end; Res := TRegEx.Split(ANumber, '-'); if High(Res) <> 3 then begin ShowMessage ('Ошибка.<Номер рецепта> должен содержать 4 блока по 4 символа разделенных символом "-" ...'); exit; end; for I := 0 to High(Res) do begin if Length(Res[I]) <> 4 then begin ShowMessage ('Ошибка.<Номер рецепта> должен содержать 4 блока по 4 символа разделенных символом "-"...'); exit; end; for J := 1 to 4 do if not (Res[I][J] in ['0'..'9','A'..'Z']) then begin ShowMessage ('Ошибка.<Номер рецепта> должен содержать только цыфры и большие буквы латинского алфовита...'); exit; end; end; //Сначала ищем в текущем ДБФ bCheck := MainCash2.MainCashForm.pCheck_InvNumberSP (ASPKind, ANumber); if bCheck then begin ShowMessage ('Ошибка.<Номер рецепта> уже использован. Повторное использование запрещено...'); exit; end; if spGet_Movement_InvNumberSP.Execute = '' then begin if spGet_Movement_InvNumberSP.ParamByName('outIsExists').Value then begin ShowMessage ('Ошибка.<Номер рецепта> уже использован. Повторное использование запрещено...'); Exit; end; end else Exit; Result := True; end else begin if MainCash2.MainCashForm.UnitConfigCDS.FieldByName('eHealthApi').AsInteger = 1 then begin Result := GetHelsiReceipt(ANumber, FHelsiID, FHelsiIDList, FHelsiName, FHelsiDenUnit, FHelsiQty, FHelsiDate, FProgramId, FProgramName, FPartialPrescription, FSkipDispenseSign); end else if MainCash2.MainCashForm.UnitConfigCDS.FieldByName('eHealthApi').AsInteger = 2 then begin Result := GetLikiDniproeHealthReceipt(ANumber, FHelsiID, FHelsiIDList, FHelsiName, FHelsiQty, FHelsiDate); end; end; end; procedure TSPDialogForm.bbOkClick(Sender: TObject); var Key :Integer; begin try StrToDate(edOperDateSP.Text) except ActiveControl:=edOperDateSP; ShowMessage ('Ошибка.Значение <Дата рецепта> не определено'); ModalResult:=mrNone; // не надо закрывать exit; end; if StrToDate(edOperDateSP.Text) < NOW - 30 then begin ActiveControl:=edOperDateSP; ShowMessage ('Ошибка.Значение <Дата рецепта> не может быть раньше чем <'+DateToStr(NOW - 30)+'>'); ModalResult:=mrNone; // не надо закрывать exit; end; if StrToDate(edOperDateSP.Text) > NOW then begin ActiveControl:=edOperDateSP; ShowMessage ('Ошибка.Значение <Дата рецепта> не может быть позже чем <'+DateToStr(NOW)+'>'); ModalResult:=mrNone; // не надо закрывать exit; end; if trim (edInvNumberSP.Text) = '' then begin ActiveControl:=edInvNumberSP; ShowMessage ('Ошибка.Значение <Номер рецепта> не определено'); ModalResult:=mrNone; // не надо закрывать exit; end; // 23.01.2018 - «№ амбулатории» - убрать эту ячейку , она не нужна {if trim (edAmbulance.Text) = '' then begin ActiveControl:=edAmbulance; ShowMessage ('Ошибка.Значение <№ амбулатории> не определено'); ModalResult:=mrNone; // не надо закрывать exit; end;} // try Key:= SPKindGuides.Params.ParamByName('Key').Value; except Key:= 0;end; if Key = 0 then begin ActiveControl:=edSPKind; ShowMessage ('Внимание.Значение <Вид соц.проекта> не установлено.'); ModalResult:=mrNone; // не надо закрывать exit; end; if not Panel2.Visible and (Length(edInvNumberSP.Text) > 15) and not CheckInvNumberSP(Key, edInvNumberSP.Text) then begin ActiveControl:=edInvNumberSP; ModalResult:=mrNone; // не надо закрывать exit; end; if Panel2.Visible then begin if trim (edMedicSP.Text) = '' then begin ActiveControl:=edMedicSP; ShowMessage ('Ошибка.Значение <ФИО врача> не определено'); ModalResult:=mrNone; // не надо закрывать exit; end; // try Key:= GuidesMemberSP.Params.ParamByName('Key').Value; except Key:= 0;end; if Key = 0 then begin ActiveControl:=edMemberSP; ShowMessage ('Внимание.Значение <ФИО пациента> не установлено.'); ModalResult:=mrNone; // не надо закрывать exit; end; try Key:= PartnerMedicalGuides.Params.ParamByName('Key').Value; except Key:= 0;end; if Key = 0 then begin ActiveControl:=cePartnerMedical; ShowMessage ('Внимание.Значение <Медицинское учреждение> не установлено.'); ModalResult:=mrOk; // ??? может не надо закрывать end else ModalResult:=mrOk; end else if (Length(trim (edInvNumberSP.Text)) <= 15) and (SPKindGuides.Params.ParamByName('Key').Value = 4823009) then begin if trim (edMedicSP.Text) = '' then begin ActiveControl:=edMedicSP; ShowMessage ('Ошибка.Значение <ФИО врача> не определено'); ModalResult:=mrNone; // не надо закрывать exit; end else ModalResult:=mrOk; end // а здесь уже все ОК else ModalResult:=mrOk; end; procedure TSPDialogForm.bbSP_PriorClick(Sender: TObject); var APartnerMedicalId: Integer; APartnerMedicalName, AMedicSP : String; AOperDateSP : TDateTime; begin ActiveControl:= edInvNumberSP; // if PartnerMedicalGuides.Params.ParamByName('Key').Value <> 0 then begin ShowMessage ('Ошибка.Медицинское учреждение уже заполнено.Необходимо сначала обнулить значение'); exit; end; if edMedicSP.Text <> '' then begin ShowMessage ('Ошибка.ФИО врача уже заполнено.Необходимо сначала обнулить значение'); exit; end; // //Сначала ищем в текущем ДБФ MainCash2.MainCashForm.pGet_OldSP (APartnerMedicalId, APartnerMedicalName, AMedicSP, AOperDateSP); //если не нашли - попробуем в базе if APartnerMedicalId = 0 then begin spGet_SP_Prior.Execute; if spGet_SP_Prior.ParamByName('outPartnerMedicalId').Value = 0 then ShowMessage('Данные для заполнения не найдены') else begin PartnerMedicalGuides.Params.ParamByName('Key').Value := spGet_SP_Prior.ParamByName('outPartnerMedicalId').Value; PartnerMedicalGuides.Params.ParamByName('TextValue').Value:= spGet_SP_Prior.ParamByName('outPartnerMedicalName').Value; cePartnerMedical.Text:= spGet_SP_Prior.ParamByName('outPartnerMedicalName').Value; edMedicSP.Text := spGet_SP_Prior.ParamByName('outMedicSPName').Value; //вернуть через строчку, т.к. с TDateTime - ошибка AOperDateSP := StrToDate(spGet_SP_Prior.ParamByName('outOperDateSP').Value); edOperDateSP.Date := AOperDateSP; end end else begin PartnerMedicalGuides.Params.ParamByName('Key').Value := APartnerMedicalId; PartnerMedicalGuides.Params.ParamByName('TextValue').Value:= APartnerMedicalName; cePartnerMedical.Text:= APartnerMedicalName; edMedicSP.Text:= AMedicSP; edOperDateSP.Date:= AOperDateSP; end; end; procedure TSPDialogForm.cePartnerMedicalPropertiesChange(Sender: TObject); begin inherited; if PartnerMedicalGuides.Params.ParamByName('Key').Value <> 0 then GuidesMemberSP.DisableGuidesOpen := False else GuidesMemberSP.DisableGuidesOpen := True; end; function TSPDialogForm.DiscountDialogExecute(var APartnerMedicalId, ASPKindId: Integer; var APartnerMedicalName, AAmbulance, AMedicSP, AInvNumberSP, ASPKindName: String; var AOperDateSP : TDateTime; var ASPTax : Currency; var AMemberSPID: Integer; var AMemberSPName: String; var AHelsiID, AHelsiIDList, AHelsiName, AHelsiDenUnit : string; var AHelsiQty : currency; var AHelsiProgramId, AHelsiProgramName : String; var AHelsiPartialPrescription, AHelsiSkipDispenseSign : Boolean; var AisPaperRecipeSP : Boolean): boolean; Begin FHelsiID := ''; FHelsiIDList := ''; FHelsiName := ''; FHelsiDenUnit := ''; AHelsiProgramId := ''; AHelsiProgramName := ''; AHelsiPartialPrescription := False; AisPaperRecipeSP := False; edAmbulance.Text:= AAmbulance; edMedicSP.Text:= AMedicSP; edInvNumberSP.Text:= AInvNumberSP; edOperDateSP.Text:= DateToStr(aOperDateSP); edSPKind.Text:= AInvNumberSP; FormParams.ParamByName('MasterUnitId').Value :=IniUtils.gUnitId; FormParams.ParamByName('MasterUnitName').Value:=IniUtils.gUnitName; // PartnerMedicalGuides.Params.ParamByName('Key').Value := APartnerMedicalId; PartnerMedicalGuides.Params.ParamByName('TextValue').Value:= ''; if APartnerMedicalId > 0 then begin cePartnerMedical.Text:= APartnerMedicalName; PartnerMedicalGuides.Params.ParamByName('TextValue').Value:= APartnerMedicalName; end; // SPKindGuides.Params.ParamByName('Key').Value := ASPKindId; SPKindGuides.Params.ParamByName('TextValue').Value:= ''; SPKindGuides.Params.ParamByName('Tax').Value:= ASPTax; //FormParams.ParamByName('SPTax').Value:=ASPTax; if ASPKindId > 0 then begin edSPKind.Text:= ASPKindName; SPKindGuides.Params.ParamByName('TextValue').Value:= ASPKindName; end else begin spGet_SPKind_def.Execute; SPKindGuides.Params.ParamByName('Tax').Value:= 0 end; if AMemberSPID <> 0 then begin GuidesMemberSP.Params.ParamByName('Key').Value := AMemberSPID; try spSelect_Object_MemberSP.Execute; except end; end; GuidesMemberSP.DisableGuidesOpen := True; cePartnerMedicalPropertiesChange(Nil); edSPKindPropertiesChange(Nil); // Result := ShowModal = mrOK; // if Result then begin try APartnerMedicalId := PartnerMedicalGuides.Params.ParamByName('Key').Value; except APartnerMedicalId := 0; PartnerMedicalGuides.Params.ParamByName('Key').Value:= 0; end; APartnerMedicalName := PartnerMedicalGuides.Params.ParamByName('TextValue').Value; AAmbulance:= trim (edAmbulance.Text); AMedicSP:= trim (edMedicSP.Text); AInvNumberSP:= trim (edInvNumberSP.Text); AOperDateSP:= StrToDate (edOperDateSP.Text); try ASPKindId := SPKindGuides.Params.ParamByName('Key').Value; except ASPKindId := 0; SPKindGuides.Params.ParamByName('Key').Value:= 0; end; ASPKindName := SPKindGuides.Params.ParamByName('TextValue').Value; ASPTax := SPKindGuides.Params.ParamByName('Tax').Value; if Panel2.Visible then begin AMemberSPID := GuidesMemberSP.Params.ParamByName('Key').Value; AMemberSPName := GuidesMemberSP.Params.ParamByName('TextValue').Value; if edGroupMemberSP.Text <> '' then AMemberSPName := AMemberSPName + ' / ' + edGroupMemberSP.Text end else begin AMemberSPID := 0; AMemberSPName :='' end; if (MainCashForm.UnitConfigCDS.FieldByName('Helsi_IdSP').AsInteger <> 0) and (MainCashForm.UnitConfigCDS.FieldByName('Helsi_IdSP').AsInteger = ASPKindId) then begin AHelsiID := FHelsiID; AHelsiIDList := FHelsiIDList; AHelsiName := FHelsiName; AHelsiDenUnit := FHelsiDenUnit; AHelsiQty := FHelsiQty; AHelsiProgramId := FProgramId; AHelsiProgramName := FProgramName; AHelsiPartialPrescription := FPartialPrescription; AHelsiSkipDispenseSign := FSkipDispenseSign; AisPaperRecipeSP := Length(AInvNumberSP) <= 15; end else begin AHelsiID := ''; AHelsiName := ''; AHelsiDenUnit := ''; AHelsiQty := 0; AHelsiProgramId := ''; AHelsiProgramName := ''; AHelsiPartialPrescription := False; AisPaperRecipeSP := False; AHelsiSkipDispenseSign := False; end; end else begin APartnerMedicalId := 0; APartnerMedicalName := ''; AAmbulance := ''; AMedicSP := ''; AInvNumberSP := ''; ASPTax := 0; ASPKindId := 0; ASPKindName := ''; AMemberSPID := 0; AMemberSPName := ''; AHelsiID := ''; AHelsiName := ''; AHelsiDenUnit := ''; AHelsiQty := 0; AHelsiProgramId := ''; AHelsiProgramName := ''; AHelsiPartialPrescription := False; AisPaperRecipeSP := False; AHelsiSkipDispenseSign := False; end; end; procedure TSPDialogForm.DiscountExternalGuidesAfterChoice(Sender: TObject); begin ActiveControl:= cePartnerMedical; inherited; end; procedure TSPDialogForm.edSPKindPropertiesChange(Sender: TObject); begin inherited; if SPKindGuides.Params.ParamByName('Key').Value <> '' then begin Panel2.Visible := (SPKindGuides.Params.ParamByName('Key').Value = 4823010); if SPKindGuides.Params.ParamByName('Key').Value = 4823009 then begin PartnerMedicalGuides.Params.ParamByName('Key').Value := 0; PartnerMedicalGuides.Params.ParamByName('TextValue').Value:= ''; MedicSPGuides.FormNameParam.Value := 'TMedicSP_PaperRecipeForm'; edMedicSP.Properties.ReadOnly := False; end else begin MedicSPGuides.FormNameParam.Value := 'TMedicSP_ObjectForm'; edMedicSP.Properties.ReadOnly := True; end; end else Panel2.Visible := False; end; End.
unit ExemploSemOCP; interface type TCliente = class public procedure SelecionarPrimeirosClientes(const ABancoDados: string); end; implementation uses FireDAC.Comp.Client; { TCliente } procedure TCliente.SelecionarPrimeirosClientes(const ABancoDados: string); var Query: TFDQuery; begin Query := TFDQuery.Create(nil); try if ABancoDados = 'Oracle' then Query.Open('SELECT * FROM Clientes WHERE rownum <= 100') else if ABancoDados = 'Firebird' then Query.Open('SELECT FIRST 100 * FROM CLIENTES') else if ABancoDados = 'SQL Server' then Query.Open('SELECT TOP 100 * FROM CLIENTES') else if ABancoDados = 'PostgreSQL' then Query.Open('SELECT * FROM CLIENTES LIMIT 100'); { ... } finally Query.Free; end; end; end.
(* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * 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 mozilla.org. * * The Initial Developer of the Original Code is * Netscape Communications Corpotation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Takanori Itou <necottie@nesitive.net> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** *) unit nsNetUtil; interface uses nsXPCOM, nsConsts, nsTypes, nsGeckoStrings; function NS_GetIOService: nsIIOService; function NS_NewURI(const spec: nsAUTF8String; const charset: AnsiString=''; baseURI: nsIURI=nil; ioService: nsIIOService=nil): nsIURI; overload; function NS_NewURI(const spec: UTF8String; baseURI: nsIURI=nil; ioService: nsIIOService=nil): nsIURI; overload; function NS_NewFileURI(spec: nsIFile; ioService: nsIIOService=nil): nsIURI; function NS_NewChannel(uri: nsIURI; ioService: nsIIOService=nil; loadGroup: nsILoadGroup=nil; callbacks: nsIInterfaceRequestor=nil; loadFlags: Longword=NS_IREQUEST_LOAD_NORMAL): nsIChannel; function NS_OpenURI(uri: nsIURI; ioService: nsIIOService=nil; loadGroup: nsILoadGroup=nil; callbacks: nsIInterfaceRequestor=nil; loadFlags: Longword=NS_IREQUEST_LOAD_NORMAL): nsIInputStream; overload; procedure NS_OpenURI(listener: nsIStreamListener; context: nsISupports; uri: nsIURI; ioService: nsIIOService=nil; loadGroup: nsILoadGroup=nil; callbacks: nsIInterfaceRequestor=nil; loadFlags: Longword=NS_IREQUEST_LOAD_NORMAL); overload; procedure NS_MakeAbsoluteURI(uri: nsAUTF8String; const spec: nsAUTF8String; baseURI: nsIURI; ioService: nsIIOService=nil); overload; function NS_MakeAbsoluteURI(const spec: UTF8String; baseURI: nsIURI; ioService: nsIIOService=nil): UTF8String; overload; function NS_NewLoadGroup(obs: nsIRequestObserver): nsILoadGroup; function NS_NewURI(const spec: nsAString; const charset: AnsiString=''; baseURI: nsIURI=nil; ioService: nsIIOService=nil): nsIURI; overload; procedure NS_MakeAbsoluteURI(uri: nsAString; const spec: nsAString; baseURI: nsIURI; ioService: nsIIOService=nil); overload; resourcestring SNewURIError = 'Cannot create instance of nsIURI by URI ''%s.'' '; SConversationError = 'Cannot convert strings between UTF8 and UTF16.'; SNewFileURIError = 'Cannot create instance of nsIURI by file ''%s.'''; SNewChannelError = 'Cannot create instance of nsIChannel.'; SOpenURIError = 'Cannot open URI ''%s.'' '; SMakeAbsoluteURIError = 'Cannot make the absolute URI.'; SNewLoadGroupError = 'Cannot create instance of nsILoadGroup.'; implementation uses nsXPCOMGlue, nsError, nsInit; function NS_GetIOService: nsIIOService; const kIOServiceCID:TGUID = '{9ac9e770-18bc-11d3-9337-00104ba0fd40}'; begin NS_GetService(kIOServiceCID, nsIIOService, Result); end; function EnsureIOService(ios: nsIIOService): nsIIOService; begin if not Assigned(ios) then begin Result := NS_GetIOService; end else begin Result := ios; end; end; function NS_NewURI(const spec: nsAUTF8String; const charset: AnsiString; baseURI: nsIURI; ioService: nsIIOService): nsIURI; var charsetPtr: PAnsiChar; grip: nsIIOService; str: IInterfacedUTF8String; begin if Length(charset)>0 then charsetPtr := PAnsiChar(charset) else charsetPtr := nil; grip := EnsureIOService(ioService); try Result := grip.NewURI(spec, charsetPtr, baseURI); except str := RelateUTF8String(spec); raise EGeckoError.CreateResFmt(PResStringRec(@SNewURIError), [str.ToString]); end; end; function NS_NewURI(const spec: nsAString; const charset: AnsiString; baseURI: nsIURI; ioService: nsIIOService): nsIURI; var spec2: IInterfacedUTF8String; rv: nsresult; begin spec2 := NewUTF8String; rv := NS_UTF16ToCString(spec, NS_ENCODING_UTF8, spec2.AUTF8String); if NS_FAILED(rv) then raise EGeckoError.CreateRes(PResStringRec(@SConversationError)); Result := NS_NewURI(spec2.AUTF8String, charset, baseURI, ioService); end; function NS_NewURI(const spec: UTF8String; baseURI: nsIURI; ioService: nsIIOService): nsIURI; var spec2: IInterfacedUTF8String; begin spec2 := NewUTF8String(spec); Result := NS_NewURI(spec2.AUTF8String, '', baseURI, ioService); end; function NS_NewFileURI(spec: nsIFile; ioService: nsIIOService): nsIURI; var grip: nsIIOService; str: IInterfacedUTF8String; begin grip := EnsureIOService(ioService); if Assigned(grip) then try Result := grip.NewFileURI(spec); except str := NewUTF8String; spec.GetNativePath(str.AUTF8String); raise EGeckoError.CreateResFmt(PResStringRec(@SNewFileURIError), [str.ToString]); end; end; function NS_NewChannel(uri: nsIURI; ioService: nsIIOService; loadGroup: nsILoadGroup; callbacks: nsIInterfaceRequestor; loadFlags: Longword): nsIChannel; var grip: nsIIOService; chan: nsIChannel; begin grip := EnsureIOService(ioService); try chan := grip.NewChannelFromURI(uri); if Assigned(loadGroup) then chan.SetLoadGroup(loadGroup); if Assigned(callbacks) then chan.SetNotificationCallbacks(callbacks); if loadFlags <> NS_IREQUEST_LOAD_NORMAL then chan.SetLoadFlags(loadFlags); Result := chan; except raise EGeckoError.CreateRes(PResStringRec(@SNewChannelError)); end; end; function NS_OpenURI(uri: nsIURI; ioService: nsIIOService; loadGroup: nsILoadGroup; callbacks: nsIInterfaceRequestor; loadFlags: Longword): nsIInputStream; var channel: nsIChannel; st: nsIInputStream; str: IInterfacedCString; begin try channel := NS_NewChannel(uri, ioService, loadGroup, callbacks, loadFlags); st := channel.Open; Result := st; except str := NewCString; uri.GetSpec(str.ACString); raise EGeckoError.CreateResFmt(PResStringRec(@SOpenURIError), [str.ToString]); end; end; procedure NS_OpenURI(listener: nsIStreamListener; context: nsISupports; uri: nsIURI; ioService: nsIIOService; loadGroup: nsILoadGroup; callbacks: nsIInterfaceRequestor; loadFlags: Longword); var channel: nsIChannel; str: IInterfacedCString; begin try channel := NS_NewChannel(uri, ioService, loadGroup, callbacks, loadFlags); channel.AsyncOpen(listener, context); except str := NewCString; uri.GetSpec(str.ACString); raise EGeckoError.CreateResFmt(PResStringRec(@SOpenURIError), [str.ToString]); end; end; procedure NS_MakeAbsoluteURI(uri: nsAUTF8String; const spec: nsAUTF8String; baseURI: nsIURI; ioService: nsIIOService); var uri2, spec2: IInterfacedUTF8String; begin uri2 := RelateUTF8String(uri); spec2 := RelateUTF8String(spec); if not Assigned(baseURI) then begin uri2.Assign(spec2); end else if uri2.Length()>0 then try baseURI.Resolve(spec2.AUTF8String, uri2.AUTF8String); except raise EGeckoError.CreateRes(PResStringRec(@SMakeAbsoluteURIError)); end else raise EGeckoError.CreateRes(PResStringRec(@SMakeAbsoluteURIError)); end; procedure NS_MakeAbsoluteURI(uri: nsAString; const spec: nsAString; baseURI: nsIURI; ioService: nsIIOService=nil); var uri2, spec2: IInterfacedString; buf1, buf2: IInterfacedUTF8String; rv: nsresult; begin uri2 := RelateString(uri); spec2 := RelateString(spec); buf1 := NewUTF8String; buf2 := NewUTF8String; if not Assigned(baseURI) then begin uri2.Assign(spec2); end else try if uri2.Length()=0 then baseURI.GetSpec(buf1.AUTF8String) else begin NS_UTF16ToCString(spec,NS_ENCODING_UTF8,buf2.AUTF8String); baseURI.Resolve(buf2.AUTF8String, buf1.AUTF8String); end; rv := NS_CStringToUTF16(buf1.AUTF8String, NS_ENCODING_UTF8, uri); if NS_FAILED(rv) then raise EGeckoError.CreateRes(PResStringRec(@SConversationError)); except on EGeckoError do raise else raise EGeckoError.CreateRes(PResStringRec(@SMakeAbsoluteURIError)); end; end; function NS_MakeAbsoluteURI(const spec: UTF8String; baseURI: nsIURI; ioService: nsIIOService): UTF8String; var uri2, spec2: IInterfacedUTF8String; begin uri2 := NewUTF8String(); spec2 := NewUTF8String(spec); NS_MakeAbsoluteURI(uri2.AUTF8String, spec2.AUTF8String, baseURI, ioService); Result := uri2.ToString; end; function NS_NewLoadGroup(obs: nsIRequestObserver): nsILoadGroup; const kLoadGroupCID: TGUID = '{e1c61582-2a84-11d3-8cce-0060b0fc14a3}'; var group: nsILoadGroup; begin try NS_CreateInstance(kLoadGroupCID,nsILoadGroup,group); group.SetGroupObserver(obs); Result := group; except raise EGeckoError.CreateRes(PResStringRec(@SNewLoadGroupError)); end; end; end.
unit UCardinalList; interface uses Classes; type TCardinalList = class(TObject) protected FList:TList; function GetItems(Index: Integer): Cardinal; procedure SetItems(Index: Integer; const Value: Cardinal); function GetCount: Integer; procedure SetCount(const Value: Integer); function GetCapacity: Integer; procedure SetCapacity(const Value: Integer); public constructor Create; destructor Destroy;override; function Add(Item:Cardinal):Integer; property Items[Index:Integer]:Cardinal read GetItems write SetItems;default; procedure Clear; virtual; procedure Delete(Index: Integer); procedure Exchange(Index1, Index2: Integer); function IndexOf(Item: Cardinal): Integer; procedure Insert(Index: Integer; Item: Cardinal); procedure Move(CurIndex, NewIndex: Integer); property Count: Integer read GetCount write SetCount; property Capacity: Integer read GetCapacity write SetCapacity; end; implementation { TCardinalList } constructor TCardinalList.Create; begin FList:=TList.Create; end; destructor TCardinalList.Destroy; begin FList.Free; inherited Destroy; end; function TCardinalList.Add(Item: Cardinal): Integer; begin Result:=FList.Add(Pointer(Item)); end; procedure TCardinalList.Clear; begin FList.Clear; end; procedure TCardinalList.Delete(Index: Integer); begin FList.Delete(Index); end; procedure TCardinalList.Exchange(Index1, Index2: Integer); begin FList.Exchange(Index1, Index2); end; function TCardinalList.GetCount: Integer; begin Result:=FList.Count; end; function TCardinalList.GetCapacity: Integer; begin Result:=FList.Capacity; end; function TCardinalList.IndexOf(Item: Cardinal): Integer; begin Result:=FList.IndexOf(Pointer(Item)); end; procedure TCardinalList.Insert(Index: Integer; Item: Cardinal); begin FList.Insert(Index,Pointer(Item)); end; procedure TCardinalList.Move(CurIndex, NewIndex: Integer); begin FList.Move(CurIndex, NewIndex); end; procedure TCardinalList.SetCount(const Value: Integer); begin FList.Count:=Value; end; procedure TCardinalList.SetCapacity(const Value: Integer); begin FList.Capacity:=Value; end; function TCardinalList.GetItems(Index: Integer): Cardinal; begin Result:=Cardinal(FList[Index]); end; procedure TCardinalList.SetItems(Index: Integer; const Value: Cardinal); begin FList[Index]:=pointer(Value); end; end.
namespace Beta; uses Foundation; type NSDate_Helpers = extension class (NSDate) private const SECOND = 1; const MINUTE = 60 * SECOND; const HOUR = 60 * MINUTE; const DAY = 24 * HOUR; const MONTH = 30 * DAY; public method relativeDateString: String; begin var lNow := NSDate.date; var lDelta := lNow.timeIntervalSinceDate(self); var lCalendar := NSCalendar.currentCalendar; var lUnits := (NSCalendarUnit.NSYearCalendarUnit or NSCalendarUnit.NSMonthCalendarUnit or NSCalendarUnit.NSDayCalendarUnit or NSCalendarUnit.NSHourCalendarUnit or NSCalendarUnit.NSMinuteCalendarUnit or NSCalendarUnit.NSSecondCalendarUnit); var lComponents := lCalendar.components(lUnits) fromDate(self) toDate(lNow) options(0); {if (lDelta < 0) then result := '!n the future!' else if (lDelta < 1 * MINUTE) then result := if (lComponents.second = 1) then 'One second ago' else NSString.stringWithFormat('%d seconds ago', lComponents.second) as NSString else if (lDelta < 2 * MINUTE) then result := 'a minute ago' else if (lDelta < 45 * MINUTE) then result := NSString.stringWithFormat('%d minutes ago', lComponents.minute) else if (lDelta < 90 * MINUTE) then result := 'an hour ago' else if (lDelta < 24 * HOUR) then result := NSString.stringWithFormat('%d hours ago', lComponents.hour)} if (lDelta < 24 * HOUR) then result := NSString.stringWithFormat('today') else if (lDelta < 48 * HOUR) then result := 'yesterday' else if (lDelta < 30 * DAY) then result := NSString.stringWithFormat('%ld days ago', lComponents.day) else if (lDelta < 12 * MONTH) then result := if (lComponents.month <= 1) then 'one month ago' else NSString.stringWithFormat('%ld months ago', lComponents.month) as NSString else result := if (lComponents.year <= 1) then 'one year ago' else NSString.stringWithFormat('%ld years ago', lComponents.year) as NSString; end; end; end.
unit DialogFormUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, MinMaxFormUnit, StdCtrls, ComCtrls, ExtCtrls, CheckLst, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Menus, cxButtons, dxSkinsCore, dxSkinsDefaultPainters; type TInteractMode = (imView, imEditing); TBlockingPanel = class(TPanel) private constructor Create(AOwner: TComponent); end; TDialogForm = class(TMinMaxForm) btnOK: TcxButton; btnCancel: TcxButton; procedure btnOKClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); private { Private declarations } procedure SetEnabledChildEditControlsByInteractMode( ParentControl: TWinControl ); overload; procedure SetEnabledBlockedControlsByInteractMode; procedure SetEnabledBlockedControlByInteractMode( Control: TControl ); function GetCancelButtonCaption: String; function GetOKButtonCaption: String; procedure SetCancelButtonCaption(const Value: String); procedure SetOKButtonCaption(const Value: String); function GetCancelButtonVisible: Boolean; procedure SetCancelButtonVisible(const Value: Boolean); protected FHorzDistanceBetweenOKAndCancelButton: Integer; FInteractMode: TInteractMode; FBlockingControlList: TList; procedure Init(const ACaption: String = ''; const AInteractMode: TInteractMode = imEditing); procedure DefaultOKButtonClickedHandle; virtual; procedure OnOKButtonClicked; virtual; procedure OnCancelButtonClicked; virtual; procedure SetEnabledChildEditControlsByInteractMode; overload; virtual; procedure SetEnabledChildEditControlByInteractMode( Control: TControl); virtual; procedure InitMinMaxSize; virtual; procedure SetInteractMode(const AInteractMode: TInteractMode); procedure OnComboBoxInput(Sender: TObject; var Key: Char); public { Public declarations } destructor Destroy; override; constructor Create(AOwner: TComponent); overload; override; constructor Create(AOwner: TComponent; const ACaption: String); overload; constructor Create(AOwner: TComponent; const AInteractMode: TInteractMode; const ACaption: String = ''); overload; published property OKButtonCaption: String read GetOKButtonCaption write SetOKButtonCaption; property CancelButtonVisible: Boolean read GetCancelButtonVisible write SetCancelButtonVisible; property CancelButtonCaption: String read GetCancelButtonCaption write SetCancelButtonCaption; property InteractMode: TInteractMode read FInteractMode write SetInteractMode; end; var DialogForm: TDialogForm; implementation uses AuxCollectionFunctionsUnit; {$R *.dfm} { TDialogForm } constructor TDialogForm.Create(AOwner: TComponent; const ACaption: String); begin FBlockingControlList := TList.Create; inherited Create(AOwner); Init(ACaption); end; constructor TDialogForm.Create(AOwner: TComponent; const AInteractMode: TInteractMode; const ACaption: String); begin FBlockingControlList := TList.Create; inherited Create(AOwner); Init(ACaption, AInteractMode); end; constructor TDialogForm.Create(AOwner: TComponent); begin FBlockingControlList := TList.Create; inherited; Init; end; procedure TDialogForm.btnCancelClick(Sender: TObject); begin OnCancelButtonClicked; end; procedure TDialogForm.btnOKClick(Sender: TObject); begin if FInteractMode <> imView then OnOKButtonClicked else DefaultOKButtonClickedHandle; end; procedure TDialogForm.DefaultOKButtonClickedHandle; begin ModalResult := mrOK; if fsModal in Self.FormState then CloseModal else Close; end; destructor TDialogForm.Destroy; begin FreeAndNil(FBlockingControlList); inherited; end; function TDialogForm.GetCancelButtonCaption: String; begin Result := btnCancel.Caption; end; function TDialogForm.GetCancelButtonVisible: Boolean; begin Result := btnCancel.Visible; end; function TDialogForm.GetOKButtonCaption: String; begin Result := btnOK.Caption; end; procedure TDialogForm.Init(const ACaption: String; const AInteractMode: TInteractMode); begin Caption := ACaption; FHorzDistanceBetweenOKAndCancelButton := btnCancel.Left - btnOK.Left - btnOK.Width; InitMinMaxSize; InteractMode := AInteractMode; end; procedure TDialogForm.InitMinMaxSize; begin FMinWidth := Width; FMinHeight := Height; end; procedure TDialogForm.OnCancelButtonClicked; begin ModalResult := mrCancel; Close; end; procedure TDialogForm.OnComboBoxInput(Sender: TObject; var Key: Char); begin Key := chr(0); end; procedure TDialogForm.OnOKButtonClicked; begin DefaultOKButtonClickedHandle; end; procedure TDialogForm.SetCancelButtonCaption(const Value: String); begin btnCancel.Caption := Value; end; procedure TDialogForm.SetCancelButtonVisible(const Value: Boolean); begin btnCancel.Visible := Value; if Value then btnOK.Left := btnCancel.Left - 12 - btnOK.Width else btnOK.Left := btnCancel.Left; end; procedure TDialogForm.SetEnabledBlockedControlByInteractMode( Control: TControl); var BlockingPanel: TPanel; begin if Control is TBlockingPanel then begin BlockingPanel := Control as TBlockingPanel; BlockingPanel.Controls[0].Parent := BlockingPanel.Parent; BlockingPanel.Controls[0].Left := BlockingPanel.Left; BlockingPanel.Controls[0].Top := BlockingPanel.Top; FreeAndNil(BlockingPanel); Exit; end; with TControl(Control) do begin if FInteractMode = imView then begin BlockingPanel := TBlockingPanel.Create(Control.Parent); BlockingPanel.Parent := Control.Parent; BlockingPanel.SetBounds(Left, Top, Width, Height); BlockingPanel.BevelOuter := bvNone; BlockingPanel.Anchors := Anchors; Control.Left := 0; Control.Top := 0; Control.Parent := BlockingPanel; BlockingPanel.Enabled := False; end end; end; procedure TDialogForm.SetEnabledBlockedControlsByInteractMode; var BlockedControl: TControl; I: Integer; begin for I := 0 to FBlockingControlList.Count - 1 do begin BlockedControl := TControl(FBlockingControlList[I]); SetEnabledBlockedControlByInteractMode(BlockedControl); end; end; procedure TDialogForm.SetEnabledChildEditControlByInteractMode( Control: TControl); var LEnabled: Boolean; BlockingPanel: TPanel; begin LEnabled := FInteractMode = imEditing; if Control is TCustomEdit then TEdit(Control).ReadOnly := not LEnabled else if Control is TComboBox then begin with TComboBox(Control) do begin if LEnabled then begin Style := csDropDownList; OnKeyPress := nil; end else begin Style := csSimple; OnKeyPress := OnComboBoxInput; end; end; end else if (Control is TDateTimePicker) or (Control is TCheckBox) or (Control is TCheckListBox) or (Control is TBlockingPanel) then begin FBlockingControlList.Add(Control); end else Control.Enabled := LEnabled; end; procedure TDialogForm.SetEnabledChildEditControlsByInteractMode( ParentControl: TWinControl); var I: Integer; begin for I := 0 to ParentControl.ControlCount - 1 do begin if (ParentControl.Controls[I] is TLabel) or (ParentControl.Controls[I] = btnOK) or (ParentControl.Controls[I] = btnCancel) or ((ParentControl.Controls[I] is TBlockingPanel) and (FInteractMode = imEditing)) then Continue; if (ParentControl.Controls[I] is TGroupBox) or (ParentControl.Controls[I] is TPanel) then begin SetEnabledChildEditControlsByInteractMode( ParentControl.Controls[I] as TWinControl ); end else SetEnabledChildEditControlByInteractMode(ParentControl.Controls[I]); end; end; procedure TDialogForm.SetEnabledChildEditControlsByInteractMode; begin SetEnabledChildEditControlsByInteractMode(Self); SetEnabledBlockedControlsByInteractMode; FBlockingControlList.Clear; if FInteractMode = imView then begin btnOK.Left := btnCancel.Left + (btnCancel.Width - btnOK.Width); btnCancel.Visible := False; end else begin btnOK.Left := btnCancel.Left - btnOK.Width - FHorzDistanceBetweenOKAndCancelButton; btnCancel.Visible := True; end; end; procedure TDialogForm.SetInteractMode(const AInteractMode: TInteractMode); begin FInteractMode := AInteractMode; SetEnabledChildEditControlsByInteractMode; end; procedure TDialogForm.SetOKButtonCaption(const Value: String); begin btnOK.Caption := Value; end; { TBlockingPanel } constructor TBlockingPanel.Create(AOwner: TComponent); begin inherited; end; end.
///* // * android-plugin-client-sdk-for-locale https://github.com/twofortyfouram/android-plugin-client-sdk-for-locale // * Copyright 2014 two forty four a.m. LLC // * // * 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 twofortyfouram.Locale.SDK.Client.Receiver.AbstractPluginSettingReceiver; interface //import android.app.Activity; //import android.content.ComponentName; //import android.content.Context; //import android.content.Intent; //import android.os.Build; //import android.os.Bundle; //import android.support.annotation.NonNull; // //import com.twofortyfouram.log.Lumberjack; //import com.twofortyfouram.spackle.AndroidSdkVersion; //import com.twofortyfouram.spackle.bundle.BundleScrubber; // ///** // * <p>Abstract superclass for a plug-in setting BroadcastReceiver implementation.</p> // * <p>The plug-in receiver lifecycle is as follows:</p> // * <ol> // * <li>{@link #onReceive(android.content.Context, android.content.Intent)} is called by the Android // * frameworks. // * onReceive() will verify that the Intent is valid. If the Intent is invalid, the receiver // * returns // * immediately. If the Intent appears to be valid, then the lifecycle continues.</li> // * <li>{@link #isBundleValid(android.os.Bundle)} is called to determine whether {@link // * com.twofortyfouram.locale.api.Intent#EXTRA_BUNDLE EXTRA_BUNDLE} is valid. If the Bundle is // * invalid, then the // * receiver returns immediately. If the bundle is valid, then the lifecycle continues.</li> // * <li>{@link #isAsync()} is called to determine whether the remaining work should be performed on // * a // * background thread.</li> // * <li>{@link #firePluginSetting(android.content.Context, android.os.Bundle)} is called to trigger // * the plug-in setting's action.</li> // * </ol> // * <p> // * Implementations of this BroadcastReceiver must be registered in the Android // * Manifest with an Intent filter for // * {@link com.twofortyfouram.locale.api.Intent#ACTION_FIRE_SETTING ACTION_FIRE_SETTING}. The // * BroadcastReceiver must be exported, enabled, and cannot have permissions // * enforced on it. // * </p> // */ //public abstract class AbstractPluginSettingReceiver extends AbstractAsyncReceiver { // // /* // * The multiple return statements in this method are a little gross, but the // * alternative of nested if statements is even worse :/ // */ // @Override // public final void onReceive(final Context context, final Intent intent) { // if (BundleScrubber.scrub(intent)) { // return; // } // Lumberjack.v("Received %s", intent); //$NON-NLS-1$ // // /* // * Note: It is OK if a host sends an ordered broadcast for plug-in // * settings. Such a behavior would allow the host to optionally block until the // * plug-in setting finishes. // */ // // if (!com.twofortyfouram.locale.api.Intent.ACTION_FIRE_SETTING.equals(intent.getAction())) { // Lumberjack // .e("Intent action is not %s", // com.twofortyfouram.locale.api.Intent.ACTION_FIRE_SETTING); //$NON-NLS-1$ // return; // } // // /* // * Ignore implicit intents, because they are not valid. It would be // * meaningless if ALL plug-in setting BroadcastReceivers installed were // * asked to handle queries not intended for them. Ideally this // * implementation here would also explicitly assert the class name as // * well, but then the unit tests would have trouble. In the end, // * asserting the package is probably good enough. // */ // if (!context.getPackageName().equals(intent.getPackage()) // && !new ComponentName(context, this.getClass().getName()).equals(intent // .getComponent())) { // Lumberjack.e("Intent is not explicit"); //$NON-NLS-1$ // return; // } // // final Bundle bundle = intent // .getBundleExtra(com.twofortyfouram.locale.api.Intent.EXTRA_BUNDLE); // if (BundleScrubber.scrub(intent)) { // return; // } // // if (null == bundle) { // Lumberjack.e("%s is missing", // com.twofortyfouram.locale.api.Intent.EXTRA_BUNDLE); //$NON-NLS-1$ // return; // } // // if (!isBundleValid(bundle)) { // Lumberjack.e("%s is invalid", // com.twofortyfouram.locale.api.Intent.EXTRA_BUNDLE); //$NON-NLS-1$ // return; // } // // if (isAsync() && AndroidSdkVersion.isAtLeastSdk(Build.VERSION_CODES.HONEYCOMB)) { // final AsyncCallback callback = new AsyncCallback() { // // @NonNull // private final Context mContext = context; // // @NonNull // private final Bundle mBundle = bundle; // // @Override // public int runAsync() { // firePluginSetting(mContext, mBundle); // return Activity.RESULT_OK; // } // // }; // // goAsyncWithCallback(callback, isOrderedBroadcast()); // } else { // firePluginSetting(context, bundle); // } // } // // /** // * <p>Gives the plug-in receiver an opportunity to validate the Bundle, to // * ensure that a malicious application isn't attempting to pass // * an invalid Bundle.</p> // * <p> // * This method will be called on the BroadcastReceiver's Looper (normatively the main thread) // * </p> // * // * @param bundle The plug-in's Bundle previously returned by the edit // * Activity. {@code bundle} should not be mutated by this method. // * @return true if {@code bundle} appears to be valid. false if {@code bundle} appears to be // * invalid. // */ // protected abstract boolean isBundleValid(@NonNull final Bundle bundle); // // /** // * Configures the receiver whether it should process the Intent in a // * background thread. Plug-ins should return true if their // * {@link #firePluginSetting(android.content.Context, android.os.Bundle)} method performs any // * sort of disk IO (ContentProvider query, reading SharedPreferences, etc.). // * or other work that may be slow. // * <p> // * Asynchronous BroadcastReceivers are not supported prior to Honeycomb, so // * with older platforms broadcasts will always be processed on the BroadcastReceiver's Looper // * (which for Manifest registered receivers will be the main thread). // * // * @return True if the receiver should process the Intent in a background // * thread. False if the plug-in should process the Intent on the // * BroadcastReceiver's Looper (normatively the main thread). // */ // protected abstract boolean isAsync(); // // /** // * If {@link #isAsync()} returns true, this method will be called on a // * background thread. If {@link #isAsync()} returns false, this method will // * be called on the main thread. Regardless of which thread this method is // * called on, this method MUST return within 10 seconds per the requirements // * for BroadcastReceivers. // * // * @param context BroadcastReceiver context. // * @param bundle The plug-in's Bundle previously returned by the edit // * Activity. // */ // protected abstract void firePluginSetting(@NonNull final Context context, // @NonNull final Bundle bundle); //} implementation end.
unit DBAIntf; {********************************************** Kingstar Delphi Library Copyright (C) Kingstar Corporation <Unit>DBAIntf <What>定义了访问数据源的抽象接口 <Written By> Huang YanLai (黄燕来) <History> **********************************************} { IDBAccess is a basic data access interface for internal usage. I recommend : The implements of IHDataset and other interfaces should be based on IDBAccess. } interface uses SysUtils,Listeners,classes; type //TTriState = (tsUnknown,tsFalse,tsTrue); // 支持的字段数据类型 TDBFieldType = (ftInteger,ftFloat,ftCurrency,ftChar,ftDatetime,ftBinary,ftOther); // 对数据类型的补充 TDBFieldOption = (foFixedChar); TDBFieldOptions = set of TDBFieldOption; { <Class>TDBFieldDef <What>定义数据字段属性的类 <Properties> FieldIndex - 字段在结果集中的索引(从左到右),从1开始编号。 FieldName - 字段名称 DisplayName - 字段显示名称 FieldType - 字段数据类型; FieldSize - 原始字段大小(bytes) RawType - 原始字段数据类型,由驱动程序提供 Options - 对数据类型的补充; isOnlyDate - 如果是日期时间类型,是否仅包括日期部分 isOnlyTime - 如果是日期时间类型,是否仅包括时间部分 autoTrim - 是否自动去掉字符类型右边的空格 <Methods> - <Event> - } TDBFieldDef = class private FisOnlyDate: boolean; FisOnlyTime: boolean; FautoTrim: boolean; procedure SetIsOnlyDate(const Value: boolean); procedure SetIsOnlyTime(const Value: boolean); public FieldIndex : Integer; // indexed from 1 FieldName : String; DisplayName : String; FieldType : TDBFieldType; FieldSize : Integer; // the raw data size RawType : Integer; // the raw data type defined by the database driver Options : TDBFieldOptions; property isOnlyDate : boolean read FisOnlyDate write SetIsOnlyDate; property isOnlyTime : boolean read FisOnlyTime write SetIsOnlyTime; property autoTrim : boolean read FautoTrim write FautoTrim default true; constructor Create; procedure assign(source : TDBFieldDef); virtual; end; //TDataReadMode = (rmRaw,rmChar); { <Class>EDBAccessError <What>数据源访问错误 <Properties> - <Methods> - <Event> - } EDBAccessError = class(Exception); { <Class>EDBUnsupported <What>调用了驱动程序不支持的操作 <Properties> - <Methods> - <Event> - } EDBUnsupported = class(EDBAccessError); { <Class>EDBNoDataset <What>返回无结果集 <Properties> - <Methods> - <Event> - } EDBNoDataset = class(EDBAccessError); { <Class>EInvalidDatabase <What>无效的数据库 <Properties> - <Methods> - <Event> - } EInvalidDatabase = class(Exception); { <Enum>TDBState <What>IDBAccess状态 <Item> dsNotReady - 未连接 dsReady - 准备好执行新命令 dsBusy - 正在处理命令(读取返回数据未完) } TDBState =(dsNotReady,dsReady,dsBusy); // 远过程调用(RPC)参数类型 TDBParamMode=(pmUnknown,pmInput,pmOutput,pmInputOutput); { <Enum>TDBResponseType <What>数据源返回响应的类型 <Item> rtNone - 无 rtDataset - 结果集 rtReturnValue - 返回值 rtOutputValue - RPC 输出参数 rtError - 错误 rtMessage - 文本信息 } TDBResponseType=(rtNone,rtDataset, rtReturnValue, rtOutputValue, rtError, rtMessage); { <Enum>TDBEventType <What>IDBAccess触发的事件类型 <Item> etOpened - 打开连接 etClosed - 关闭连接 etBeforeExec - 在执行命令以前 etAfterExec - 在执行命令以后 etGone2NextResponse - 处理到下一个响应 etFinished - 所有返回的响应处理完 etDestroy - 实例被删除 } TDBEventType = (etOpened,etClosed,etBeforeExec,etAfterExec,etGone2NextResponse,etFinished,etDestroy); { <Class>TDBEvent <What>IDBAccess触发的事件对象 <Properties> EventType - 事件类型 <Methods> - <Event> - } TDBEvent = class(TObjectEvent) public EventType : TDBEventType; end; { <Interface>IDBAccess <What>访问数据源的抽象接口 <Properties> - <Methods> - } IDBAccess = interface ['{FFAD05C0-8CA8-11D3-AAFA-00C0268E6AE8}'] // 0) 公共方法,打开/关闭数据源连接,以及获得连接状态 procedure open; procedure close; function state : TDBState; function Ready : Boolean; function CmdCount:Integer; // 0.1) 处理数据源响应的标准步骤 function nextResponse: TDBResponseType; function curResponseType: TDBResponseType; procedure finished; function get_isMessageNotified:boolean; procedure set_isMessageNotified(value:boolean); // 0.2) 支持Listener的方法,让外界可以知道内部发生的时间。通过IListener传递的是TDBEvent对象 procedure addListener(Listener : IListener); procedure removeListener(Listener : IListener); // 0.3) 在标准数据类型(TDBFieldType)和数据源的原始数据类型之间进行的转换方法 // raw data (base on database driver) to standard data type ( TDBFieldType ) // return standard data size function rawDataToStd(rawType : Integer; rawBuffer : pointer; rawSize : Integer; stdType : TDBFieldType; stdBuffer:pointer; stdSize:Integer):Integer; function stdDataToRaw(rawType : Integer; rawBuffer : pointer; rawSize : Integer; stdType : TDBFieldType; stdBuffer:pointer; stdSize:Integer):Integer; // 0.4) 获得实现该接口的对象的实例 function getImplement : TObject; // 1) 通过SQL文本对数据源进行访问的方法 function GetSQLText : String; procedure SetSQLText(const Value:String); property SQLText : String read GetSQLText write SetSQLText; function GetExtraSQLText : String; procedure SetExtraSQLText(const Value:String); property ExtraSQLText : String read GetExtraSQLText write SetExtraSQLText; procedure exec; procedure execSQL(const ASQLText : String); // 2) 处理返回结果集的方法 // 2.1) 浏览结果集 //function hasDataset:TTriState; function nextRow : Boolean; function eof : Boolean; // 2.2) 获得字段的定义 function fieldCount : Integer; function fieldName(index : Integer) : string; function fieldType(index : Integer) : Integer; //rawtype function fieldSize(index : Integer) : Integer; function fieldDataLen(index : Integer) : Integer; procedure getFieldDef(index : Integer; FieldDef : TDBFieldDef); // 2.3) 读取字段的值 function readData(index : Integer; dataType: TDBFieldType; buffer : pointer; buffersize : Integer) : Integer; function readData2(FieldDef : TDBFieldDef; buffer : pointer; buffersize : Integer) : Integer; function readRawData(index : Integer; buffer : pointer; buffersize : Integer) : Integer; function isNull(index:Integer): Boolean; // extend data read for data results function fieldAsInteger(index:Integer): Integer; function fieldAsFloat(index:Integer): Double; function fieldAsDateTime(index:Integer): TDateTime; function fieldAsString(index:Integer): String; function fieldAsCurrency(index:Integer): Currency; // 2.4) 获取SQLServer, Sybase的COMPUTE字段信息的方法(在其他的驱动中不支持这种访问) // Returns the number of COMPUTE clauses in the current set of results function cumputeClauseCount : Integer; // if isSupportCompute=false, nextRow will skip compute rows. default is false function GetisSupportCompute : Boolean; procedure setisSupportCompute(value : Boolean); property isSupportCompute : Boolean read GetisSupportCompute write setisSupportCompute; function isThisACumputeRow : Boolean; function ComputeFieldCount : Integer; function ComputeFieldType(index : Integer) : Integer; function ComputeFieldSize(index : Integer) : Integer; function ComputeFieldDataLen(index : Integer) : Integer; procedure getComputeFieldDef(index : Integer; FieldDef : TDBFieldDef); function readComputeData(index : Integer; dataType: TDBFieldType; buffer : pointer; buffersize : Integer) : Integer; function readComputeData2(FieldDef : TDBFieldDef; buffer : pointer; buffersize : Integer) : Integer; function readRawComputeData(index : Integer; buffer : pointer; buffersize : Integer) : Integer; function computeIsNull(index : Integer): boolean; // 3) 获取输出参数信息 //procedure ReachOutputs; //function hasOutput: TTriState; function outputCount : Integer; procedure getOutputDef(index : Integer; FieldDef : TDBFieldDef); function readOutput(index : Integer; dataType: TDBFieldType; buffer : pointer; buffersize : Integer) : Integer; function readOutput2(FieldDef : TDBFieldDef; buffer : pointer; buffersize : Integer) : Integer; function readRawOutput(index : Integer; buffer : pointer; buffersize : Integer) : Integer; function outputIsNull(index : Integer): boolean; // 4) 获取返回参数信息 //procedure ReachReturn; //function hasReturn: TTriState; function readReturn(buffer : pointer; buffersize : Integer) : Integer; function returnValue : Integer; // 5) 通过RPC(例如存储过程)对数据源进行访问的方法 procedure initRPC(rpcname : String; flags : Integer); // if value=nil, it is a null value procedure setRPCParam(name : String; mode : TDBParamMode; datatype : TDBFieldType; size : Integer; length : Integer; value : pointer; rawType : Integer); procedure execRPC; // 6) 获得数据源返回的信息 procedure getMessage(msg : TStrings); function MessageText : string; // 7) 获得数据源返回的意外 function getError : EDBAccessError; end; const // 标准数据长度 StdDataSize : array[TDBFieldType] of Integer = (sizeof(Integer),sizeof(Double),Sizeof(Currency),0,Sizeof(TDatetime),0,0); implementation uses safeCode; { TDBFieldDef } procedure TDBFieldDef.assign(source: TDBFieldDef); begin FieldIndex := source.FieldIndex; FieldName := source.FieldName; DisplayName := source.DisplayName; FieldType := source.FieldType; FieldSize := source.FieldSize; RawType := source.RawType; FisOnlyDate := source.FisOnlyDate; FisOnlyTime := source.FisOnlyTime; end; constructor TDBFieldDef.Create; begin FieldIndex := 0; FieldName := ''; DisplayName := ''; FieldType := ftOther; FieldSize := 0; RawType := 0; FisOnlyDate := false; FisOnlyTime := false; Options := []; FautoTrim := true; end; procedure TDBFieldDef.SetIsOnlyDate(const Value: boolean); begin if FieldType<>ftDatetime then begin FisOnlyDate := false; FisOnlyTime := false; end else begin FisOnlyDate := Value; if FisOnlyDate then FisOnlyTime := false; end; end; procedure TDBFieldDef.SetIsOnlyTime(const Value: boolean); begin if FieldType<>ftDatetime then begin FisOnlyDate := false; FisOnlyTime := false; end else begin FisOnlyTime := Value; if FisOnlyTime then FisOnlyDate := false; end; end; end.
unit YOTM.Form.OverlayTime; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, YOTM.Form, HGM.Button, Vcl.StdCtrls, Vcl.ExtCtrls, HGM.Controls.PanelExt; type TChangeActive = procedure(Sender:TObject; State:Boolean) of object; TFormTimeOverlay = class(TFormCustom) LabelTime: TLabel; ButtonFlatSwitch: TButtonFlat; procedure FormCreate(Sender: TObject); procedure ButtonFlatSwitchClick(Sender: TObject); procedure LabelCaptionMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); private FActiveWork: Boolean; FTime: string; FCallback: TChangeActive; procedure SetActiveWork(const Value: Boolean); procedure SetTime(const Value: string); procedure SetCallback(const Value: TChangeActive); { Private declarations } public property Time:string read FTime write SetTime; property ActiveWork:Boolean read FActiveWork write SetActiveWork; procedure SetActivateLow(Value:Boolean); procedure Stop; procedure Resume; property Callback:TChangeActive read FCallback write SetCallback; end; var FormTimeOverlay: TFormTimeOverlay; implementation {$R *.dfm} procedure TFormTimeOverlay.ButtonFlatSwitchClick(Sender: TObject); begin ActiveWork:=not ActiveWork; end; procedure TFormTimeOverlay.FormCreate(Sender: TObject); begin inherited; Top:=Screen.WorkAreaRect.Bottom - ClientHeight - 5; Left:=Screen.WorkAreaRect.Right - ClientWidth - 5; end; procedure TFormTimeOverlay.LabelCaptionMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin DragBarTop.DoDrag; end; procedure TFormTimeOverlay.Stop; begin ActiveWork:=False; end; procedure TFormTimeOverlay.Resume; begin ActiveWork:=True; end; procedure TFormTimeOverlay.SetActivateLow(Value: Boolean); begin FActiveWork := Value; case Value of True: ButtonFlatSwitch.ImageIndex:=28; False:ButtonFlatSwitch.ImageIndex:=27; end; end; procedure TFormTimeOverlay.SetActiveWork(const Value: Boolean); begin if FActiveWork = Value then Exit; SetActivateLow(Value); if Assigned(FCallback) then FCallback(Self, FActiveWork); end; procedure TFormTimeOverlay.SetCallback(const Value: TChangeActive); begin FCallback := Value; end; procedure TFormTimeOverlay.SetTime(const Value: string); begin FTime := Value; LabelTime.Caption:=FTime; end; end.
unit DisplayProcessorU; interface uses Graphics, Types, Classes, ExtCtrls, Contnrs, ShapesU; type /// Класът, който ще бъде използван при управляване на дисплейната система. TDisplayProcessor = class protected fShapeList : TObjectList; public /// Списък с всички елементи формиращи изображението. property ShapeList : TObjectList read fShapeList write fShapeList; constructor Create; procedure ReDraw(Sender : TObject; grfx : TCanvas); procedure Draw(grfx : TCanvas);virtual; procedure DrawShape(grfx: TCanvas; item: TShapes); end; implementation { TDisplayProcessor } /// Конструктор constructor TDisplayProcessor.Create; begin ShapeList := TObjectList.Create; end; /// Прерисува всички елементи в ShapeList върху grfx procedure TDisplayProcessor.ReDraw(Sender: TObject; grfx: TCanvas); begin Draw(grfx); end; /// Визуализация. /// Обхождане на всички елементи в списъка и извикване на визуализиращия им метод. /// grfx - Къде да се извърши визуализацията. procedure TDisplayProcessor.Draw(grfx: TCanvas); var i : Integer; begin for i := 0 to ShapeList.Count - 1 do begin DrawShape(grfx, ShapeList.Items[i] as TShapes); end; end; /// Визуализира даден елемент от изображението. /// grfx - Къде да се извърши визуализацията. /// item - Елемент за визуализиране. procedure TDisplayProcessor.DrawShape(grfx: TCanvas; item: TShapes); begin item.DrawSelf(grfx); end; end.
unit DIOTA.IotaAPIImpl; interface uses System.Classes, Generics.Collections, DIOTA.IotaAPI, DIOTA.IotaAPICoreImpl, DIOTA.IotaLocalPow, DIOTA.Pow.ICurl, DIOTA.Model.Bundle, DIOTA.Model.Transaction, DIOTA.Model.Input, DIOTA.Model.Transfer, DIOTA.Dto.Response.GetNewAddressesResponse, DIOTA.Dto.Response.GetTransfersResponse, DIOTA.Dto.Response.BroadcastTransactionsResponse, DIOTA.Dto.Response.GetBalancesAndFormatResponse, DIOTA.Dto.Response.GetBundleResponse, DIOTA.Dto.Response.GetAccountDataResponse, DIOTA.Dto.Response.ReplayBundleResponse, DIOTA.Dto.Response.GetInclusionStatesResponse, DIOTA.Dto.Response.SendTransferResponse; type TIotaAPI = class(TIotaAPICore, IIotaAPI) private FCustomCurl: ICurl; function IsAboveMaxDepth(AAttachmentTimestamp: Int64): Boolean; public constructor Create(ABuilder: IIotaAPIBuilder); reintroduce; virtual; function GetNewAddress(const ASeed: String; const ASecurity: Integer; AIndex: Integer; AChecksum: Boolean; ATotal: Integer; AReturnAll: Boolean): TGetNewAddressesResponse; deprecated; function GetNextAvailableAddress(ASeed: String; ASecurity: Integer; AChecksum: Boolean): TGetNewAddressesResponse; overload; function GetNextAvailableAddress(ASeed: String; ASecurity: Integer; AChecksum: Boolean; AIndex: Integer): TGetNewAddressesResponse; overload; function GenerateNewAddresses(ASeed: String; ASecurity: Integer; AChecksum: Boolean; AAmount: Integer): TGetNewAddressesResponse; overload; function GenerateNewAddresses(ASeed: String; ASecurity: Integer; AChecksum: Boolean; AIndex: Integer; AAmount: Integer): TGetNewAddressesResponse; overload; function GenerateNewAddresses(ASeed: String; ASecurity: Integer; AChecksum: Boolean; AIndex: Integer; AAmount: Integer; AAddSpendAddresses: Boolean): TGetNewAddressesResponse; overload; function GetAddressesUnchecked(ASeed: String; ASecurity: Integer; AChecksum: Boolean; AIndex: Integer; AAmount: Integer): TGetNewAddressesResponse; function GetTransfers(ASeed: String; ASecurity: Integer; AStart: Integer; AEnd: Integer; AInclusionStates: Boolean): TGetTransfersResponse; function BundlesFromAddresses(AAddresses: TStrings; AInclusionStates: Boolean): TArray<IBundle>; function StoreAndBroadcast(ATrytes: TStrings): TBroadcastTransactionsResponse; function SendTrytes(ATrytes: TStrings; ADepth: Integer; AMinWeightMagnitude: Integer; AReference: String): TList<ITransaction>; function FindTransactionsObjectsByHashes(AHashes: TStrings): TList<ITransaction>; function FindTransactionObjectsByAddresses(AAddresses: TStrings): TList<ITransaction>; function FindTransactionObjectsByTag(ATags: TStrings): TList<ITransaction>; function FindTransactionObjectsByApprovees(AApprovees: TStrings): TList<ITransaction>; function FindTransactionObjectsByBundle(ABundles: TStrings): TList<ITransaction>; function PrepareTransfers(ASeed: String; ASecurity: Integer; ATransfers: TList<ITransfer>; ARemainder: String; AInputs: TList<IInput>; ATips: TList<ITransaction>; AValidateInputs: Boolean): TStringList; function GetInputs(ASeed: String; ASecurity: Integer; AStart: Integer; AEnd: Integer; AThreshold: Int64; const ATips: TStrings): TGetBalancesAndFormatResponse; function GetBalanceAndFormat(AAddresses: TStrings; ATips: TStrings; AThreshold: Int64; AStart: Integer; ASecurity: Integer): TGetBalancesAndFormatResponse; function GetBundle(ATransaction: String): TGetBundleResponse; function GetAccountData(ASeed: String; ASecurity: Integer; AIndex: Integer; AChecksum: Boolean; ATotal: Integer; AReturnAll: Boolean; AStart: Integer; AEnd: Integer; AInclusionStates: Boolean; AThreshold: Int64): TGetAccountDataResponse; function CheckWereAddressSpentFrom(AAddresses: TStrings): TArray<Boolean>; overload; function CheckWereAddressSpentFrom(AAddress: String): Boolean; overload; function ReplayBundle(ATailTransactionHash: String; ADepth: Integer; AMinWeightMagnitude: Integer; AReference: String): TReplayBundleResponse; function GetLatestInclusion(AHashes: TStrings): TGetInclusionStatesResponse; function SendTransfer(ASeed: String; ASecurity: Integer; ADepth: Integer; AMinWeightMagnitude: Integer; ATransfers: TList<ITransfer>; AInputs: TList<IInput>; ARemainderAddress: String; AValidateInputs: Boolean; AValidateInputAddresses: Boolean; ATips: TList<ITransaction>): TSendTransferResponse; function TraverseBundle(ATrunkTx: String; ABundleHash: String; ABundle: IBundle): IBundle; function InitiateTransfer(ASecuritySum: Integer; AInputAddress: String; ARemainderAddress: String; const ATransfers: TList<ITransfer>): TList<ITransaction>; overload; function InitiateTransfer(ASecuritySum: Integer; AInputAddress: String; ARemainderAddress: String; const ATransfers: TList<ITransfer>; ATips: TList<ITransaction>): TList<ITransaction>; overload; function InitiateTransfer(ASecuritySum: Integer; AInputAddress: String; ARemainderAddress: String; ATransfers: TList<ITransfer>; ATestMode: Boolean): TList<ITransaction>; overload; function InitiateTransfer(ASecuritySum: Integer; AInputAddress: String; ARemainderAddress: String; ATransfers: TList<ITransfer>; ATips: TList<ITransaction>; ATestMode: Boolean): TList<ITransaction>; overload; procedure ValidateTransfersAddresses(ASeed: String; ASecurity: Integer; ATrytes: TStrings); function AddRemainder(ASeed: String; ASecurity: Integer; AInputs: TList<IInput>; ABundle: IBundle; ATag: String; ATotalValue: Int64; ARemainderAddress: String; ASignatureFragments: TStrings): TStringList; function IsPromotable(ATail: ITransaction): Boolean; overload; function IsPromotable(ATail: String): Boolean; overload; function PromoteTransaction(ATail: String; ADepth: Integer; AMinWeightMagnitude: Integer; ABundle: IBundle): TList<ITransaction>; end; TIotaAPIBuilder = class(TIotaAPICoreBuilder, IIotaAPIBuilder) private FCustomCurl: ICurl; public constructor Create; virtual; function Protocol(AProtocol: String): IIotaAPIBuilder; function Host(AHost: String): IIotaAPIBuilder; function Port(APort: Integer): IIotaAPIBuilder; function Timeout(ATimeout: Integer): IIotaAPIBuilder; function LocalPow(ALocalPow: IIotaLocalPow): IIotaAPIBuilder; function WithCustomCurl(ACurl: ICurl): IIotaAPIBuilder; function Build: IIotaAPI; function GetCustomCurl: ICurl; end; implementation uses System.SysUtils, System.Math, System.DateUtils, System.Threading, DIOTA.Pow.SpongeFactory, DIOTA.Utils.Constants, DIOTA.Utils.InputValidator, DIOTA.Utils.BundleValidator, DIOTA.Utils.IotaAPIUtils, DIOTA.Utils.Checksum, DIOTA.Dto.Response.FindTransactionsResponse, DIOTA.Dto.Response.GetTransactionsToApproveResponse, DIOTA.Dto.Response.AttachToTangleResponse, DIOTA.Dto.Response.GetTrytesResponse, DIOTA.Dto.Response.GetBalancesResponse, DIOTA.Dto.Response.WereAddressesSpentFromResponse, DIOTA.Dto.Response.GetNodeInfoResponse, DIOTA.Dto.Response.CheckConsistencyResponse; { TIotaAPIBuilder } constructor TIotaAPIBuilder.Create; begin FCustomCurl := TSpongeFactory.Create(TSpongeFactory.Mode.KERL); FTimeout := 5000; end; function TIotaAPIBuilder.Protocol(AProtocol: String): IIotaAPIBuilder; begin Result := inherited Protocol(AProtocol) as IIotaAPIBuilder; end; function TIotaAPIBuilder.Host(AHost: String): IIotaAPIBuilder; begin Result := inherited Host(AHost) as IIotaAPIBuilder; end; function TIotaAPIBuilder.Port(APort: Integer): IIotaAPIBuilder; begin Result := inherited Port(APort) as IIotaAPIBuilder; end; function TIotaAPIBuilder.Timeout(ATimeout: Integer): IIotaAPIBuilder; begin Result := inherited Timeout(ATimeout) as IIotaAPIBuilder; end; function TIotaAPIBuilder.LocalPow(ALocalPow: IIotaLocalPow): IIotaAPIBuilder; begin Result := inherited LocalPow(ALocalPow) as IIotaAPIBuilder; end; function TIotaAPIBuilder.WithCustomCurl(ACurl: ICurl): IIotaAPIBuilder; begin FCustomCurl := ACurl; Result := Self; end; function TIotaAPIBuilder.Build: IIotaAPI; begin Result := TIotaAPI.Create(Self); end; function TIotaAPIBuilder.GetCustomCurl: ICurl; begin Result := FCustomCurl; end; { TIotaAPI } constructor TIotaAPI.Create(ABuilder: IIotaAPIBuilder); begin inherited Create(ABuilder); FCustomCurl := ABuilder.GetCustomCurl; end; function TIotaAPI.GetNewAddress(const ASeed: String; const ASecurity: Integer; AIndex: Integer; AChecksum: Boolean; ATotal: Integer; AReturnAll: Boolean): TGetNewAddressesResponse; begin // If total number of addresses to generate is supplied, simply generate // and return the list of all addresses if ATotal <> 0 then Result := GetAddressesUnchecked(ASeed, ASecurity, AChecksum, AIndex, ATotal) else // If !returnAll return only the last address that was generated Result := GenerateNewAddresses(ASeed, ASecurity, AChecksum, AIndex, 1, AReturnAll); end; function TIotaAPI.GetNextAvailableAddress(ASeed: String; ASecurity: Integer; AChecksum: Boolean): TGetNewAddressesResponse; begin Result := GenerateNewAddresses(ASeed, ASecurity, AChecksum, 0, 1, False); end; function TIotaAPI.GetNextAvailableAddress(ASeed: String; ASecurity: Integer; AChecksum: Boolean; AIndex: Integer): TGetNewAddressesResponse; begin Result := GenerateNewAddresses(ASeed, ASecurity, AChecksum, AIndex, 1, False); end; function TIotaAPI.GenerateNewAddresses(ASeed: String; ASecurity: Integer; AChecksum: Boolean; AAmount: Integer): TGetNewAddressesResponse; begin Result := GenerateNewAddresses(ASeed, ASecurity, AChecksum, 0, AAmount, False); end; function TIotaAPI.GenerateNewAddresses(ASeed: String; ASecurity: Integer; AChecksum: Boolean; AIndex, AAmount: Integer): TGetNewAddressesResponse; begin Result := GenerateNewAddresses(ASeed, ASecurity, AChecksum, 0, AAmount, False); end; function TIotaAPI.GenerateNewAddresses(ASeed: String; ASecurity: Integer; AChecksum: Boolean; AIndex, AAmount: Integer; AAddSpendAddresses: Boolean): TGetNewAddressesResponse; var AllAddresses: TStringList; i: Integer; ANumUnspentFound: Integer; ANewAddressList: TStringList; ANewAddress: String; AResponse: TFindTransactionsResponse; begin if not TInputValidator.IsValidSeed(ASeed) then raise Exception.Create(INVALID_SEED_INPUT_ERROR); if not TInputValidator.IsValidSecurityLevel(ASecurity) then raise Exception.Create(INVALID_SECURITY_LEVEL_INPUT_ERROR); if (AIndex + AAmount) < 0 then raise Exception.Create(INVALID_INPUT_ERROR); AllAddresses := TStringList.Create; ANewAddressList := TStringList.Create; try ANumUnspentFound := 0; i := AIndex; while ANumUnspentFound < AAmount do begin ANewAddress := TIotaAPIUtils.NewAddress(ASeed, ASecurity, i, AChecksum, FCustomCurl.Clone); if AChecksum then ANewAddressList.Text := ANewAddress else ANewAddressList.Text := TChecksum.AddChecksum(ANewAddress); AResponse := FindTransactionsByAddresses(ANewAddressList); try if AResponse.HashesCount = 0 then begin //Unspent address, if we ask for 0, we dont need to add it if AAmount <> 0 then AllAddresses.Add(ANewAddress); Inc(ANumUnspentFound); end else if AAddSpendAddresses then //Spend address, were interested anyways AllAddresses.Add(ANewAddress); finally AResponse.Free; end; Inc(i); end; Result := TGetNewAddressesResponse.Create(AllAddresses.ToStringArray); finally ANewAddressList.Free; AllAddresses.Free; end; end; function TIotaAPI.GetAddressesUnchecked(ASeed: String; ASecurity: Integer; AChecksum: Boolean; AIndex, AAmount: Integer): TGetNewAddressesResponse; var AllAddresses: TStringList; i: Integer; begin if not TInputValidator.IsValidSeed(ASeed) then raise Exception.Create(INVALID_SEED_INPUT_ERROR); AllAddresses := TStringList.Create; try for i := AIndex to AIndex + AAmount - 1 do AllAddresses.Add(TIOTAAPIUtils.NewAddress(ASeed, ASecurity, i, AChecksum, FCustomCurl.Clone)); Result := TGetNewAddressesResponse.Create(AllAddresses.ToStringArray); finally AllAddresses.Free; end; end; function TIotaAPI.GetTransfers(ASeed: String; ASecurity, AStart, AEnd: Integer; AInclusionStates: Boolean): TGetTransfersResponse; var AGnr: TGetNewAddressesResponse; ABundles: TArray<IBundle>; AAddressesList: TStringList; begin // validate seed if not TInputValidator.IsValidSeed(ASeed) then raise Exception.Create(INVALID_SEED_INPUT_ERROR); if (AStart < 0) or (AStart > AEnd) or (AEnd > (AStart + 500)) then raise Exception.Create(INVALID_INPUT_ERROR); if not TInputValidator.IsValidSecurityLevel(ASecurity) then raise Exception.Create(INVALID_SECURITY_LEVEL_INPUT_ERROR); AGnr := GetNewAddress(ASeed, ASecurity, AStart, True, AEnd, True); if Assigned(AGnr) and (AGnr.AddressesCount > 0) then begin AAddressesList := AGnr.AddressesList; try ABundles := BundlesFromAddresses(AAddressesList, AInclusionStates); finally AAddressesList.Free; end; Result := TGetTransfersResponse.Create(ABundles); end else Result := TGetTransfersResponse.Create([]); end; function TIotaAPI.BundlesFromAddresses(AAddresses: TStrings; AInclusionStates: Boolean): TArray<IBundle>; var ATrxs: TList<ITransaction>; ATailTransactions: TStringList; ANonTailBundleHashes: TStringList; ATrx: ITransaction; ABundleObjects: TList<ITransaction>; AThreadFinalBundles: TThreadList<IBundle>; AFinalBundles: TList<IBundle>; AGisr: TGetInclusionStatesResponse; AFinalInclusionStates: TGetInclusionStatesResponse; j: Integer; begin ATailTransactions := TStringList.Create; ANonTailBundleHashes := TStringList.Create; AThreadFinalBundles := TThreadList<IBundle>.Create; try ATrxs := FindTransactionObjectsByAddresses(AAddresses); try for ATrx in ATrxs do // Sort tail and nonTails if ATrx.CurrentIndex = 0 then ATailTransactions.Add(ATrx.Hash) else if ANonTailBundleHashes.IndexOf(ATrx.Bundle) < 0 then ANonTailBundleHashes.Add(ATrx.Bundle); finally ATrxs.Free; end; ABundleObjects := FindTransactionObjectsByBundle(ANonTailBundleHashes); try for ATrx in ABundleObjects do // Sort tail and nonTails if (ATrx.CurrentIndex = 0) and (ATailTransactions.IndexOf(ATrx.Hash) < 0) then ATailTransactions.Add(ATrx.Hash); finally ABundleObjects.Free; end; // If inclusionStates, get the confirmation status // of the tail transactions, and thus the bundles AGisr := nil; if (ATailTransactions.Count > 0) and AInclusionStates then begin AGisr := GetLatestInclusion(ATailTransactions); if (not Assigned(AGisr)) or (AGisr.StatesCount = 0) then raise Exception.Create(GET_INCLUSION_STATE_RESPONSE_ERROR); end; AFinalInclusionStates := AGisr; TParallel.For(0, ATailTransactions.Count - 1, procedure(i: Integer) var ABundleResponse: TGetBundleResponse; AGbr: IBundle; ABundleList: TList<ITransaction>; AThisInclusion: Boolean; ATransaction: ITransaction; begin //try ABundleResponse := GetBundle(ATailTransactions[i]); ABundleList := ABundleResponse.TransactionsList; try with TBundleBuilder.Create do begin AGbr := SetTransactions(ABundleList.ToArray).Build; Free; end; if AGbr.Transactions.Count > 0 then begin if AInclusionStates then begin if Assigned(AFinalInclusionStates) then AThisInclusion := AFinalInclusionStates.States[i] else AThisInclusion := False; for ATransaction in AGbr.Transactions do ATransaction.SetPersistence(AThisInclusion); end; AThreadFinalBundles.Add(AGbr); end; finally ABundleList.Free; ABundleResponse.Free; end; //except //log.warn(Constants.GET_BUNDLE_RESPONSE_ERROR); //end; end); AFinalBundles := AThreadFinalBundles.LockList; try AFinalBundles.Sort; SetLength(Result, AFinalBundles.Count); for j := 0 to AFinalBundles.Count - 1 do with TBundleBuilder.Create do begin Result[j] := SetTransactions(AFinalBundles[j].Transactions.ToArray).Build; Free; end; finally AThreadFinalBundles.UnLockList; end; finally ATailTransactions.Free; ANonTailBundleHashes.Free; AThreadFinalBundles.Free; end; end; function TIotaAPI.StoreAndBroadcast(ATrytes: TStrings): TBroadcastTransactionsResponse; begin if not TInputValidator.IsArrayOfAttachedTrytes(ATrytes.ToStringArray) then raise Exception.Create(INVALID_TRYTES_INPUT_ERROR); StoreTransactions(ATrytes).Free; Result := BroadcastTransactions(ATrytes); end; function TIotaAPI.SendTrytes(ATrytes: TStrings; ADepth, AMinWeightMagnitude: Integer; AReference: String): TList<ITransaction>; var ATxs: TGetTransactionsToApproveResponse; ARes: TAttachToTangleResponse; AResTrytes: TStringList; i: Integer; AResSB: TBroadcastTransactionsResponse; begin Result := TList<ITransaction>.Create; ATxs := GetTransactionsToApprove(ADepth, AReference); try // attach to tangle - do pow ARes := AttachToTangle(ATxs.TrunkTransaction, ATxs.BranchTransaction, AMinWeightMagnitude, ATrytes); AResTrytes := ARes.TrytesList; try AResSB := StoreAndBroadcast(AResTrytes); try for i := 0 to ARes.TrytesCount - 1 do with TTransactionBuilder.Create do try Result.Add(FromTrytes(ARes.Trytes[i]).Build); finally Free; end; finally AResSB.Free; end; finally AResTrytes.Free; ARes.Free; end; finally ATxs.Free; end; end; function TIotaAPI.FindTransactionsObjectsByHashes(AHashes: TStrings): TList<ITransaction>; var ATrytesResponse: TGetTrytesResponse; i: Integer; begin if not TInputValidator.IsArrayOfHashes(AHashes.ToStringArray) then raise Exception.Create(INVALID_HASHES_INPUT_ERROR); ATrytesResponse := GetTrytes(AHashes); try Result := TList<ITransaction>.Create; for i := 0 to ATrytesResponse.TrytesCount - 1 do with TTransactionBuilder.Create do try Result.Add(FromTrytes(ATrytesResponse.Trytes[i]).Build); finally Free; end; finally ATrytesResponse.Free; end; end; function TIotaAPI.FindTransactionObjectsByAddresses(AAddresses: TStrings): TList<ITransaction>; var AFtr: TFindTransactionsResponse; AHashesList: TStringList; begin AFtr := FindTransactionsByAddresses(AAddresses); try if (not Assigned(AFtr)) or (AFtr.HashesCount = 0) then Result := TList<ITransaction>.Create else // get the transaction objects of the transactions begin AHashesList := AFtr.HashesList; try Result := FindTransactionsObjectsByHashes(AHashesList); finally AHashesList.Free; end; end; finally AFtr.Free; end; end; function TIotaAPI.FindTransactionObjectsByTag(ATags: TStrings): TList<ITransaction>; var AFtr: TFindTransactionsResponse; AHashesList: TStringList; begin AFtr := FindTransactionsByDigests(ATags); try if (not Assigned(AFtr)) or (AFtr.HashesCount = 0) then Result := TList<ITransaction>.Create else // get the transaction objects of the transactions begin AHashesList := AFtr.HashesList; try Result := FindTransactionsObjectsByHashes(AHashesList); finally AHashesList.Free; end; end; finally AFtr.Free; end; end; function TIotaAPI.FindTransactionObjectsByApprovees(AApprovees: TStrings): TList<ITransaction>; var AFtr: TFindTransactionsResponse; AHashesList: TStringList; begin AFtr := FindTransactionsByApprovees(AApprovees); try if (not Assigned(AFtr)) or (AFtr.HashesCount = 0) then Result := TList<ITransaction>.Create else // get the transaction objects of the transactions begin AHashesList := AFtr.HashesList; try Result := FindTransactionsObjectsByHashes(AHashesList); finally AHashesList.Free; end; end; finally AFtr.Free; end; end; function TIotaAPI.FindTransactionObjectsByBundle(ABundles: TStrings): TList<ITransaction>; var AFtr: TFindTransactionsResponse; AHashesList: TStringList; begin AFtr := FindTransactionsByBundles(ABundles); try if (not Assigned(AFtr)) or (AFtr.HashesCount = 0) then Result := TList<ITransaction>.Create else // get the transaction objects of the transactions begin AHashesList := AFtr.HashesList; try Result := FindTransactionsObjectsByHashes(AHashesList); finally AHashesList.Free; end; end; finally AFtr.Free; end; end; function TIotaAPI.PrepareTransfers(ASeed: String; ASecurity: Integer; ATransfers: TList<ITransfer>; ARemainder: String; AInputs: TList<IInput>; ATips: TList<ITransaction>; AValidateInputs: Boolean): TStringList; var ABundle: IBundle; ASignatureFragments: TStringList; ATotalValue: Int64; ATag: String; ATransfer: ITransfer; ASignatureMessageLength: Integer; AMsgCopy: String; AFragment: String; ATimestamp: Int64; ANewInputs: TGetBalancesAndFormatResponse; AInputsList: TList<IInput>; AInputsAddresses: TStringList; AInput: IInput; ATipHashes: TStringList; ATrx: ITransaction; ABalancesResponse: TGetBalancesResponse; ABalances: TArray<Int64>; AConfirmedInputs: TList<IInput>; ATotalBalance: Int64; i: Integer; AThisBalance: Int64; ABundleTrytes: TList<String>; begin // validate seed if not TInputValidator.IsValidSeed(ASeed) then raise Exception.Create(INVALID_SEED_INPUT_ERROR); if not TInputValidator.IsValidSecurityLevel(ASecurity) then raise Exception.Create(INVALID_SECURITY_LEVEL_INPUT_ERROR); if (ARemainder <> '') and (not TInputValidator.CheckAddress(ARemainder)) then raise Exception.Create(INVALID_ADDRESSES_INPUT_ERROR); // Input validation of transfers object if not TInputValidator.IsTransfersCollectionValid(ATransfers) then raise Exception.Create(INVALID_TRANSFERS_INPUT_ERROR); if Assigned(AInputs) and (not TInputValidator.AreValidInputsList(AInputs)) then raise Exception.Create(INVALID_ADDRESSES_INPUT_ERROR); Result := nil; // Create a new bundle ABundle := TBundleBuilder.CreateBundle; ASignatureFragments := TStringList.Create; try ATotalValue := 0; ATag := ''; // Iterate over all transfers, get totalValue // and prepare the signatureFragments, message and tag for ATransfer in ATransfers do begin // remove the checksum of the address ATransfer.Address := TChecksum.RemoveChecksum(ATransfer.Address); ASignatureMessageLength := 1; // If message longer than 2187 trytes, increase signatureMessageLength (add 2nd transaction) if Length(ATransfer.Message) > MESSAGE_LENGTH then begin // Get total length, message / maxLength (2187 trytes) ASignatureMessageLength := ASignatureMessageLength + Floor(Length(ATransfer.Message) / MESSAGE_LENGTH); AMsgCopy := ATransfer.Message; // While there is still a message, copy it while AMsgCopy <> '' do begin AFragment := Copy(AMsgCopy, 1, MESSAGE_LENGTH); AMsgCopy := Copy(AMsgCopy, MESSAGE_LENGTH + 1, Length(AMsgCopy)); // Pad remainder of fragment AFragment := AFragment.PadRight(MESSAGE_LENGTH, '9'); ASignatureFragments.Add(AFragment); end; end else begin // Else, get single fragment with 2187 of 9's trytes AFragment := ATransfer.Message; if Length(AFragment) < MESSAGE_LENGTH then AFragment := AFragment.PadRight(MESSAGE_LENGTH, '9'); ASignatureFragments.Add(AFragment); end; ATag := ATransfer.Tag; // pad for required 27 tryte length if Length(ATag) < TAG_LENGTH then ATag := ATag.PadRight(TAG_LENGTH, '9'); // get current timestamp in seconds ATimestamp := DateTimeToUnix(TTimeZone.Local.ToUniversalTime(Now));//SecondsBetween(, 0); // Add first entry to the bundle ABundle.AddEntry(ASignatureMessageLength, ATransfer.Address, ATransfer.Value, ATag, ATimestamp); // Sum up total value ATotalValue := ATotalValue + ATransfer.Value; end; // Get inputs if we are sending tokens if ATotalValue <> 0 then begin for ATransfer in ATransfers do if not TInputValidator.HasTrailingZeroTrit(ATransfer.Address) then raise Exception.Create(INVALID_ADDRESSES_INPUT_ERROR); // Case 1: user provided inputs // Validate the inputs by calling getBalances if Assigned(AInputs) and (AInputs.Count > 0) then begin if not AValidateInputs then begin Result := AddRemainder(ASeed, ASecurity, AInputs, ABundle, ATag, ATotalValue, ARemainder, ASignatureFragments); Exit; end; // Get list of addresses of the provided inputs AInputsAddresses := TStringList.Create; try for AInput in AInputs do AInputsAddresses.Add(AInput.Address); if Assigned(ATips) then begin ATipHashes := TStringList.Create; try for ATrx in ATips do ATipHashes.Add(ATrx.Hash); finally ATipHashes.Free; end; end else ATipHashes := nil; ABalancesResponse := GetBalances(100, AInputsAddresses, ATipHashes); AConfirmedInputs := TList<IInput>.Create; try ABalances := ABalancesResponse.BalancesArray; ATotalBalance := 0; for i := 0 to High(ABalances) do begin AThisBalance := ABalances[i]; // If input has balance, add it to confirmedInputs if AThisBalance > 0 then begin ATotalBalance := ATotalBalance + AThisBalance; AInputs[i].Balance := AThisBalance; AConfirmedInputs.Add(AInputs[i]); // if we've already reached the intended input value, break out of loop if ATotalBalance >= ATotalValue then Break; end; end; // Return not enough balance error if ATotalValue > ATotalBalance then raise Exception.Create(NOT_ENOUGH_BALANCE_ERROR); Result := AddRemainder(ASeed, ASecurity, AConfirmedInputs, ABundle, ATag, ATotalValue, ARemainder, ASignatureFragments); finally AConfirmedInputs.Free; ABalancesResponse.Free; end; finally AInputsAddresses.Free; end; end else // Case 2: Get inputs deterministically // // If no inputs provided, derive the addresses from the seed and // confirm that the inputs exceed the threshold begin ANewInputs := GetInputs(ASeed, ASecurity, 0, 0, ATotalValue, nil); AInputsList := ANewInputs.InputsList; try // If inputs with enough balance Result := AddRemainder(ASeed, ASecurity, AInputsList, ABundle, ATag, ATotalValue, ARemainder, ASignatureFragments); finally AInputsList.Free; ANewInputs.Free; end; end; end else begin // If no input required, don't sign and simply finalize the bundle ABundle.Finalize(FCustomCurl.Clone); ABundle.AddTrytes(ASignatureFragments); ABundleTrytes := TList<String>.Create; try for ATrx in ABundle.Transactions do ABundleTrytes.Add(ATrx.ToTrytes); ABundleTrytes.Reverse; Result := TStringList.Create; for i := 0 to ABundleTrytes.Count - 1 do Result.Add(ABundleTrytes[i]); finally ABundleTrytes.Free; end; end; finally ASignatureFragments.Free; end; end; function TIotaAPI.GetInputs(ASeed: String; ASecurity, AStart, AEnd: Integer; AThreshold: Int64; const ATips: TStrings): TGetBalancesAndFormatResponse; var AAllAddresses: TStringList; i: Integer; AAddress: String; ARes: TGetNewAddressesResponse; AResAddresses: TStringList; begin // validate the seed if not TInputValidator.IsValidSeed(ASeed) then raise Exception.Create(INVALID_SEED_INPUT_ERROR); if not TInputValidator.IsValidSecurityLevel(ASecurity) then raise Exception.Create(INVALID_SECURITY_LEVEL_INPUT_ERROR); // If start value bigger than end, return error // or if difference between end and start is bigger than 500 keys if (AStart < 0) or (AStart > AEnd) or (AEnd > (AStart + 500)) then raise Exception.Create(INVALID_INPUT_ERROR); // Case 1: start and end // // If start and end is defined by the user, simply iterate through the keys // and call getBalances if AEnd <> 0 then begin AAllAddresses := TStringList.Create; try for i := AStart to AEnd - 1 do begin AAddress := TIotaAPIUtils.NewAddress(ASeed, ASecurity, i, True, FCustomCurl.Clone); AAllAddresses.Add(AAddress); end; Result := GetBalanceAndFormat(AAllAddresses, ATips, AThreshold, AStart, ASecurity); finally AAllAddresses.Free; end; end else // Case 2: iterate till threshold or till end // // Either start from index: 0 or start (if defined) until threshold is reached. // Calls getNewAddress and deterministically generates and returns all addresses // We then do getBalance, format the output and return it begin ARes := GenerateNewAddresses(ASeed, ASecurity, True, AStart, AThreshold, True); AResAddresses := ARes.AddressesList; try Result := GetBalanceAndFormat(AResAddresses, ATips, AThreshold, AStart, ASecurity); finally AResAddresses.Free; ARes.Free; end; end; end; function TIotaAPI.GetBalanceAndFormat(AAddresses, ATips: TStrings; AThreshold: Int64; AStart, ASecurity: Integer): TGetBalancesAndFormatResponse; var ARes: TGetBalancesResponse; ABalances: TList<Int64>; AThresholdReached: Boolean; ATotalBalance: Int64; AInputs: TList<IInput>; i: Integer; ABalance: Int64; begin if not TInputValidator.IsValidSecurityLevel(ASecurity) then raise Exception.Create(INVALID_SECURITY_LEVEL_INPUT_ERROR); ARes := GetBalances(100, AAddresses, ATips); ABalances := ARes.BalancesList; try // If threshold defined, keep track of whether reached or not // else set default to true AThresholdReached := AThreshold = 0; ATotalBalance := 0; AInputs := TList<IInput>.Create; try for i := 0 to AAddresses.Count - 1 do begin ABalance := ABalances[i]; if ABalance > 0 then begin AInputs.Add(TInputBuilder.CreateInput(AAddresses[i], ABalance, AStart + i, ASecurity)); // Increase totalBalance of all aggregated inputs ATotalBalance := ATotalBalance + ABalance; if (not AThresholdReached) and (ATotalBalance >= AThreshold) then begin AThresholdReached := True; Break; end; end; end; if AThresholdReached then Result := TGetBalancesAndFormatResponse.Create(AInputs.ToArray, ATotalBalance) else begin Result := nil; raise Exception.Create(NOT_ENOUGH_BALANCE_ERROR); end; finally AInputs.Free; end; finally ABalances.Free; ARes.Free; end; end; function TIotaAPI.GetBundle(ATransaction: String): TGetBundleResponse; var ABundle: IBundle; begin if not TInputValidator.isHash(ATransaction) then raise Exception.Create(INVALID_HASHES_INPUT_ERROR); ABundle := TraverseBundle(ATransaction, '', TBundleBuilder.CreateBundle); if not Assigned(ABundle) then raise Exception.Create(INVALID_BUNDLE_ERROR); if not TBundleValidator.IsBundle(ABundle) then raise Exception.Create(INVALID_BUNDLE_ERROR); Result := TGetBundleResponse.Create(ABundle.Transactions.ToArray); end; function TIotaAPI.GetAccountData(ASeed: String; ASecurity, AIndex: Integer; AChecksum: Boolean; ATotal: Integer; AReturnAll: Boolean; AStart, AEnd: Integer; AInclusionStates: Boolean; AThreshold: Int64): TGetAccountDataResponse; var AGna: TGetNewAddressesResponse; AGtr: TGetTransfersResponse; AGbr: TGetBalancesAndFormatResponse; begin if not TInputValidator.IsValidSecurityLevel(ASecurity) then raise Exception.Create(INVALID_SECURITY_LEVEL_INPUT_ERROR); if (AStart < 0) or (AStart > AEnd) or (AEnd > (AStart + 1000)) then raise Exception.Create(INVALID_INPUT_ERROR); AGna := GetNewAddress(ASeed, ASecurity, AIndex, AChecksum, ATotal, AReturnAll); AGtr := GetTransfers(ASeed, ASecurity, AStart, AEnd, AInclusionStates); AGbr := GetInputs(ASeed, ASecurity, AStart, AEnd, AThreshold, nil); try Result := TGetAccountDataResponse.Create(AGna.AddressesArray, AGtr.TransfersArray, AGbr.InputsArray, AGbr.TotalBalance); finally AGbr.Free; AGtr.Free; AGna.Free; end; end; function TIotaAPI.CheckWereAddressSpentFrom(AAddresses: TStrings): TArray<Boolean>; var ARes: TWereAddressesSpentFromResponse; begin ARes := WereAddressesSpentFrom(AAddresses); try Result := ARes.StatesArray; finally ARes.Free; end; end; function TIotaAPI.CheckWereAddressSpentFrom(AAddress: String): Boolean; var ASpentAddresses: TStringList; begin ASpentAddresses := TStringList.Create; try ASpentAddresses.Add(AAddress); Result := CheckWereAddressSpentFrom(ASpentAddresses)[0]; finally ASpentAddresses.Free; end; end; function TIotaAPI.ReplayBundle(ATailTransactionHash: String; ADepth, AMinWeightMagnitude: Integer; AReference: String): TReplayBundleResponse; var i: Integer; ABundleResponse: TGetBundleResponse; ABundleTrytesList: TList<String>; ATransactionsList: TList<ITransaction>; ATrx: ITransaction; ATrxs: TList<ITransaction>; ABundleTrytes: TStringList; ASuccessful: TArray<Boolean>; ARes: TFindTransactionsResponse; ABundleList: TStringList; begin if not TInputValidator.IsHash(ATailTransactionHash) then raise Exception.Create(INVALID_TAIL_HASH_INPUT_ERROR); ABundleTrytesList := TList<String>.Create; try ABundleResponse := GetBundle(ATailTransactionHash); ATransactionsList := ABundleResponse.TransactionsList; try for ATrx in ATransactionsList do ABundleTrytesList.Add(ATrx.ToTrytes); ABundleTrytesList.Reverse; ABundleTrytes := TStringList.Create; try for i := 0 to ABundleTrytesList.Count - 1 do ABundleTrytes.Add(ABundleTrytesList[i]); ATrxs := SendTrytes(ABundleTrytes, ADepth, AMinWeightMagnitude, AReference); try SetLength(ASuccessful, ATrxs.Count); for i := 0 to ATrxs.Count - 1 do begin ABundleList := TStringList.Create; ABundleList.Add(ATrxs[i].Bundle); ARes := FindTransactionsByBundles(ABundleList); try ASuccessful[i] := ARes.HashesCount > 0; finally ARes.Free; ABundleList.Free; end; end; finally ATrxs.Free; end; Result := TReplayBundleResponse.Create(ASuccessful); finally ABundleTrytes.Free; end; finally ATransactionsList.Free; ABundleResponse.Free; end; finally ABundleTrytesList.Free; end; end; function TIotaAPI.GetLatestInclusion(AHashes: TStrings): TGetInclusionStatesResponse; var AGetNodeInfoResponse: TGetNodeInfoResponse; ALatestMilestone: TStringList; begin AGetNodeInfoResponse := GetNodeInfo; ALatestMilestone := TStringList.Create; try ALatestMilestone.Add(AGetNodeInfoResponse.LatestSolidSubtangleMilestone); Result := GetInclusionStates(AHashes, ALatestMilestone); finally ALatestMilestone.Free; AGetNodeInfoResponse.Free; end; end; function TIotaAPI.SendTransfer(ASeed: String; ASecurity, ADepth, AMinWeightMagnitude: Integer; ATransfers: TList<ITransfer>; AInputs: TList<IInput>; ARemainderAddress: String; AValidateInputs, AValidateInputAddresses: Boolean; ATips: TList<ITransaction>): TSendTransferResponse; var ATrytes: TStringList; AReference: String; ATrxs: TList<ITransaction>; ASuccessful: TArray<Boolean>; i: Integer; ARes: TFindTransactionsResponse; ABundleList: TStringList; begin ATrytes := PrepareTransfers(ASeed, ASecurity, ATransfers, ARemainderAddress, AInputs, ATips, AValidateInputs); try if AValidateInputAddresses then ValidateTransfersAddresses(ASeed, ASecurity, ATrytes); if Assigned(ATips) and (ATips.Count > 0) then AReference := ATips[0].Hash else AReference := ''; ATrxs := SendTrytes(ATrytes, ADepth, AMinWeightMagnitude, AReference); try SetLength(ASuccessful, ATrxs.Count); for i := 0 to ATrxs.Count - 1 do begin ABundleList := TStringList.Create; try ABundleList.Add(ATrxs[i].Bundle); ARes := FindTransactionsByBundles(ABundleList); try ASuccessful[i] := ARes.HashesCount > 0; finally ARes.Free; end; finally ABundleList.Free; end; end; Result := TSendTransferResponse.Create(ATrxs.ToArray, ASuccessful); finally ATrxs.Free; end; finally ATrytes.Free; end; end; function TIotaAPI.TraverseBundle(ATrunkTx, ABundleHash: String; ABundle: IBundle): IBundle; var AGtr: TGetTrytesResponse; AHashes: TStringList; ATrx: ITransaction; AHash: String; ANewTrunkTx: String; begin Result := nil; AHash := ABundleHash; AHashes := TStringList.Create; try AHashes.Add(ATrunkTx); AGtr := GetTrytes(AHashes); if Assigned(AGtr) then try if AGtr.TrytesCount = 0 then raise Exception.Create(INVALID_BUNDLE_ERROR); with TTransactionBuilder.Create do try ATrx := FromTrytes(AGtr.Trytes[0]).Build; finally Free; end; if ATrx.Bundle = '' then raise Exception.Create(INVALID_TRYTES_INPUT_ERROR); // If first transaction to search is not a tail, return error if (AHash = '') and (ATrx.CurrentIndex <> 0) then raise Exception.Create(INVALID_TAIL_HASH_INPUT_ERROR); // If no bundle hash, define it if AHash = '' then AHash := ATrx.Bundle; // If different bundle hash, return with bundle if AHash <> ATrx.Bundle then Result := ABundle else // If only one bundle element, return if (ATrx.LastIndex = 0) and (ATrx.CurrentIndex = 0) then Result := TBundleBuilder.CreateBundle([ATrx]) else begin // Define new trunkTransaction for search ANewTrunkTx := ATrx.TrunkTransaction; // Add transaction object to bundle ABundle.Transactions.Add(ATrx); // Continue traversing with new trunkTx Result := TraverseBundle(ANewTrunkTx, AHash, ABundle); end; finally AGtr.Free; end else raise Exception.Create(GET_TRYTES_RESPONSE_ERROR); finally AHashes.Free; end; end; function TIotaAPI.InitiateTransfer(ASecuritySum: Integer; AInputAddress, ARemainderAddress: String; const ATransfers: TList<ITransfer>): TList<ITransaction>; begin Result := InitiateTransfer(ASecuritySum, AInputAddress, ARemainderAddress, ATransfers, nil, False); end; function TIotaAPI.InitiateTransfer(ASecuritySum: Integer; AInputAddress, ARemainderAddress: String; const ATransfers: TList<ITransfer>; ATips: TList<ITransaction>): TList<ITransaction>; begin Result := InitiateTransfer(ASecuritySum, AInputAddress, ARemainderAddress, ATransfers, ATips, False); end; function TIotaAPI.InitiateTransfer(ASecuritySum: Integer; AInputAddress, ARemainderAddress: String; ATransfers: TList<ITransfer>; ATestMode: Boolean): TList<ITransaction>; begin Result := InitiateTransfer(ASecuritySum, AInputAddress, ARemainderAddress, ATransfers, nil, ATestMode); end; function TIotaAPI.InitiateTransfer(ASecuritySum: Integer; AInputAddress, ARemainderAddress: String; ATransfers: TList<ITransfer>; ATips: TList<ITransaction>; ATestMode: Boolean): TList<ITransaction>; var ABundle: IBundle; ATotalValue: Int64; ASignatureFragments: TStringList; ATag: String; ATransfer: ITransfer; ASignatureMessageLength: Integer; AMsgCopy: String; AFragment: String; ATimestamp: Int64; ATipHashes: TStringList; ABalancesResponse: TGetBalancesResponse; ATx: ITransaction; AInputAddressList: TStringList; ATotalBalance: Int64; i: Integer; begin if ASecuritySum < MIN_SECURITY_LEVEL then raise Exception.Create(INVALID_SECURITY_LEVEL_INPUT_ERROR); // validate input address if not TInputValidator.IsAddress(AInputAddress) then raise Exception.Create(INVALID_ADDRESSES_INPUT_ERROR); // validate remainder address if (ARemainderAddress <> '') and (not TInputValidator.IsAddress(ARemainderAddress)) then raise Exception.Create(INVALID_ADDRESSES_INPUT_ERROR); // Input validation of transfers object if not TInputValidator.IsTransfersCollectionValid(ATransfers) then raise Exception.Create(INVALID_TRANSFERS_INPUT_ERROR); // Create a new bundle ABundle := TBundleBuilder.CreateBundle; ASignatureFragments := TStringList.Create; try ATotalValue := 0; ATag := ''; // Iterate over all transfers, get totalValue // and prepare the signatureFragments, message and tag for ATransfer in ATransfers do begin // remove the checksum of the address ATransfer.Address := TChecksum.RemoveChecksum(ATransfer.Address); ASignatureMessageLength := 1; // If message longer than 2187 trytes, increase signatureMessageLength (add next transaction) if Length(ATransfer.Message) > MESSAGE_LENGTH then begin // Get total length, message / maxLength (2187 trytes) ASignatureMessageLength := ASignatureMessageLength + Floor(Length(ATransfer.Message) / MESSAGE_LENGTH); AMsgCopy := ATransfer.Message; // While there is still a message, copy it while AMsgCopy <> '' do begin AFragment := Copy(AMsgCopy, 1, MESSAGE_LENGTH); AMsgCopy := Copy(AMsgCopy, MESSAGE_LENGTH + 1, Length(AMsgCopy)); // Pad remainder of fragment AFragment := AFragment.PadRight(MESSAGE_LENGTH, '9'); ASignatureFragments.Add(AFragment); end; end else begin // Else, get single fragment with 2187 of 9's trytes AFragment := ATransfer.Message; if Length(ATransfer.Message) < MESSAGE_LENGTH then AFragment := AFragment.PadRight(MESSAGE_LENGTH, '9'); end; ATag := ATransfer.Tag; // pad for required 27 tryte length if Length(ATransfer.Tag) < TAG_LENGTH then ATag := ATag.PadRight(TAG_LENGTH, '9'); // get current timestamp in seconds ATimestamp := DateTimeToUnix(TTimeZone.Local.ToUniversalTime(Now)); // Add first entry to the bundle ABundle.AddEntry(ASignatureMessageLength, ATransfer.Address, ATransfer.Value, ATag, ATimestamp); // Sum up total value ATotalValue := ATotalValue + ATransfer.Value; end; // Get inputs if we are sending tokens if ATotalValue <> 0 then begin for ATransfer in ATransfers do if not TInputValidator.HasTrailingZeroTrit(ATransfer.Address) then raise Exception.Create(INVALID_ADDRESSES_INPUT_ERROR); AInputAddressList := TStringList.Create; try AInputAddressList.Add(AInputAddress); if Assigned(ATips) then begin ATipHashes := TStringList.Create; try for ATx in ATips do ATipHashes.Add(ATx.Hash); ABalancesResponse := GetBalances(100, AInputAddressList, ATipHashes); finally ATipHashes.Free; end end else ABalancesResponse := GetBalances(100, AInputAddressList, nil); finally AInputAddressList.Free; end; ATotalBalance := 0; try for i := 0 to ABalancesResponse.BalancesCount - 1 do ATotalBalance := ATotalBalance + ABalancesResponse.Balances[i]; finally ABalancesResponse.Free; end; // get current timestamp in seconds ATimestamp := DateTimeToUnix(TTimeZone.Local.ToUniversalTime(Now)); // bypass the balance checks during unit testing //TODO: remove this uglyness if ATestMode then ATotalBalance := ATotalBalance + 1000; if ATotalBalance > 0 then // Add input as bundle entry // Only a single entry, signatures will be added later ABundle.AddEntry(ASecuritySum, TChecksum.RemoveChecksum(AInputAddress), -ATotalBalance, ATag, ATimestamp); // Return not enough balance error if ATotalValue > ATotalBalance then raise Exception.Create(NOT_ENOUGH_BALANCE_ERROR); // If there is a remainder value // Add extra output to send remaining funds to if ATotalBalance > ATotalValue then begin // Remainder bundle entry if necessary if ARemainderAddress = '' then raise Exception.Create(NO_REMAINDER_ADDRESS_ERROR); ABundle.AddEntry(1, ARemainderAddress, ATotalBalance - ATotalValue, ATag, ATimestamp); end; ABundle.Finalize(TSpongeFactory.Create(TSpongeFactory.Mode.CURLP81)); ABundle.AddTrytes(ASignatureFragments); Result := TList<ITransaction>.Create; for i := 0 to ABundle.Transactions.Count - 1 do Result.Add(ABundle.Transactions[i]); end else raise Exception.Create(INVALID_VALUE_TRANSFER_ERROR); finally ASignatureFragments.Free; end; end; procedure TIotaAPI.ValidateTransfersAddresses(ASeed: String; ASecurity: Integer; ATrytes: TStrings); var ATrxStr: String; ATransaction: ITransaction; AInputTransactions: TList<ITransaction>; AAddresses: TStringList; AInputAddresses: TStringList; ARes: TFindTransactionsResponse; AHashes: TStringList; ATransactions: TList<ITransaction>; AGna: TGetNewAddressesResponse; AGbr: TGetBalancesAndFormatResponse; AInput: IInput; AGnaAddresses: TStringList; begin AInputTransactions := TList<ITransaction>.Create; AAddresses := TStringList.Create; AInputAddresses := TStringList.Create; try for ATrxStr in ATrytes do begin with TTransactionBuilder.Create do try ATransaction := FromTrytes(ATrxStr).Build; finally Free; end; AAddresses.Add(TChecksum.AddChecksum(ATransaction.Address)); AInputTransactions.Add(ATransaction); end; ARes := FindTransactionsByAddresses(AAddresses); try if ARes.HashesCount > 0 then begin AHashes := ARes.HashesList; try ATransactions := FindTransactionsObjectsByHashes(AHashes); try AGna := GenerateNewAddresses(ASeed, ASecurity, True, 0, 0, False); AGnaAddresses := AGna.AddressesList; try AGbr := GeTInputs(ASeed, ASecurity, 0, 0, 0, nil); try for AInput in AGbr.InputsArray do AInputAddresses.Add(TChecksum.AddChecksum(AInput.Address)); //check if send to input for ATransaction in AInputTransactions do if ATransaction.Value > 0 then if AInputAddresses.IndexOf(ATransaction.Address) >= 0 then raise Exception.Create(SEND_TO_INPUTS_ERROR) else if not TInputValidator.HasTrailingZeroTrit(ATransaction.Address) then raise Exception.Create(INVALID_ADDRESSES_INPUT_ERROR); for ATransaction in ATransactions do begin //check if destination address is already in use if (ATransaction.Value < 0) and (AInputAddresses.IndexOf(ATransaction.Address) < 0) then raise Exception.Create(SENDING_TO_USED_ADDRESS_ERROR); //check if key reuse if (ATransaction.Value < 0) and (AGnaAddresses.IndexOf(ATransaction.Address) >= 0) then raise Exception.Create(PRIVATE_KEY_REUSE_ERROR); end; finally AGbr.Free; end; finally AGnaAddresses.Free; AGna.Free; end; finally ATransactions.Free; end; finally AHashes.Free; end; end; finally ARes.Free; end; finally AInputTransactions.Free; AAddresses.Free; AInputAddresses.Free; end; end; function TIotaAPI.AddRemainder(ASeed: String; ASecurity: Integer; AInputs: TList<IInput>; ABundle: IBundle; ATag: String; ATotalValue: Int64; ARemainderAddress: String; ASignatureFragments: TStrings): TStringList; var ATotalTransferValue: Int64; i: Integer; AThisBalance: Int64; ATimestamp: Int64; ARemainder: Int64; ARes: TGetNewAddressesResponse; begin // validate seed if not TInputValidator.IsValidSeed(ASeed) then raise Exception.Create(INVALID_SEED_INPUT_ERROR); if (ARemainderAddress <> '') and (not TInputValidator.CheckAddress(ARemainderAddress)) then raise Exception.Create(INVALID_ADDRESSES_INPUT_ERROR); if not TInputValidator.IsValidSecurityLevel(ASecurity) then raise Exception.Create(INVALID_SECURITY_LEVEL_INPUT_ERROR); if not TInputValidator.AreValidInputsList(AInputs) then raise Exception.Create(INVALID_INPUT_ERROR); ATotalTransferValue := ATotalValue; for i := 0 to AInputs.Count - 1 do begin AThisBalance := AInputs[i].Balance; ATimestamp := DateTimeToUnix(TTimeZone.Local.ToUniversalTime(Now)); // Add input as bundle entry ABundle.AddEntry(ASecurity, TChecksum.RemoveChecksum(AInputs[i].Address), -AThisBalance, ATag, ATimestamp); // If there is a remainder value // Add extra output to send remaining funds to if AThisBalance >= ATotalTransferValue then begin ARemainder := AThisBalance - ATotalTransferValue; // If user has provided remainder address // Use it to send remaining funds to if (ARemainder > 0) and (ARemainderAddress <> '') then // Remainder bundle entry ABundle.AddEntry(1, TChecksum.RemoveChecksum(ARemainderAddress), ARemainder, ATag, ATimestamp) else if ARemainder > 0 then // Generate a new Address by calling getNewAddress begin ARes := GetNextAvailableAddress(ASeed, ASecurity, False); // Remainder bundle entry ABundle.AddEntry(1, ARes.Addresses[0], ARemainder, ATag, ATimestamp); end; // Final function for signing inputs Result := TIotaAPIUtils.SignInputsAndReturn(ASeed, AInputs, ABundle, ASignatureFragments, FCustomCurl.Clone); Exit; end else // If multiple inputs provided, subtract the totalTransferValue by // the inputs balance ATotalTransferValue := ATotalTransferValue - AThisBalance; end; raise Exception.Create(NOT_ENOUGH_BALANCE_ERROR); end; function TIotaAPI.IsPromotable(ATail: ITransaction): Boolean; var AConsistencyResponse: TCheckConsistencyResponse; ALowerBound: Int64; ATails: TStringList; begin ALowerBound := ATail.AttachmentTimestamp; ATails := TStringList.Create; try ATails.Add(ATail.Hash); AConsistencyResponse := CheckConsistency(ATails); try Result := AConsistencyResponse.State and IsAboveMaxDepth(ALowerBound); finally AConsistencyResponse.Free; end; finally ATails.Free; end; end; function TIotaAPI.IsPromotable(ATail: String): Boolean; var ATransaction: TGetTrytesResponse; AHashes: TStringList; ATrx: ITransaction; begin Result := False; AHashes := TStringList.Create; try AHashes.Add(ATail); ATransaction := GetTrytes(AHashes); try if ATransaction.TrytesCount = 0 then raise Exception.Create(TRANSACTION_NOT_FOUND); with TTransactionBuilder.Create do try ATrx := FromTrytes(ATransaction.Trytes[0]).Build; finally Free; end; Result := IsPromotable(ATrx); finally ATransaction.Free; end; finally AHashes.Free; end; end; function TIotaAPI.IsAboveMaxDepth(AAttachmentTimestamp: Int64): Boolean; begin // Check against future timestamps Result := (AAttachmentTimestamp < DateTimeToUnix(TTimeZone.Local.ToUniversalTime(Now))) and { * Check if transaction wasn't issued before last 6 milestones * Without a coo, technically there is no limit for promotion on the network. * But old transactions are less likely to be selected in tipselection * This means that the higher maxdepth, the lower the use of promoting is. * 6 was picked by means of "observing" nodes for their most popular depth, and 6 was the "edge" of popularity. * * Milestones are being issued every ~2mins * * The 11 is calculated like this: * 6 milestones is the limit, so 5 milestones are used, each 2 minutes each totaling 10 minutes. * Add 1 minute delay for propagating through the network of nodes. * * That's why its 11 and not 10 or 12 (*60*1000) } ((DateTimeToUnix(TTimeZone.Local.ToUniversalTime(Now)) - AAttachmentTimestamp) < 11 * 60 * 1000); end; function TIotaAPI.PromoteTransaction(ATail: String; ADepth, AMinWeightMagnitude: Integer; ABundle: IBundle): TList<ITransaction>; var AConsistencyResponse: TCheckConsistencyResponse; ATransactionsToApprove: TGetTransactionsToApproveResponse; ARes: TAttachToTangleResponse; ATrytes: TStringList; ATrx: ITransaction; ATrytesList: TStringList; i: Integer; ATails: TStringList; begin if (not Assigned(ABundle)) or (ABundle.Transactions.Count = 0) then raise Exception.Create(EMPTY_BUNDLE_ERROR); if ADepth < 0 then raise Exception.Create(INVALID_DEPTH_ERROR); if AMinWeightMagnitude <= 0 then raise Exception.Create(INVALID_WEIGHT_MAGNITUDE_ERROR); ATails := TStringList.Create; try ATails.Add(ATail); AConsistencyResponse := CheckConsistency(ATails); try if not AConsistencyResponse.State then raise Exception.Create(AConsistencyResponse.Info); finally AConsistencyResponse.Free; end; finally ATails.Free; end; ATransactionsToApprove := GetTransactionsToApprove(ADepth, ATail); ATrytes := TStringList.Create; try for ATrx in ABundle.Transactions do ATrytes.Add(ATrx.ToTrytes); ARes := AttachToTangle(ATransactionsToApprove.TrunkTransaction, ATransactionsToApprove.BranchTransaction, AMinWeightMagnitude, ATrytes); ATrytesList := ARes.TrytesList; try try StoreAndBroadcast(ATrytesList).Free; except Result := TList<ITransaction>.Create; Exit; end; finally ATrytesList.Free; ARes.Free; end; Result := TList<ITransaction>.Create; for i := 0 to ARes.TrytesCount - 1 do begin with TTransactionBuilder.Create do try ATrx := FromTrytes(ARes.Trytes[i]).Build; finally Free; end; Result.Add(ATrx); end; finally ATrytes.Free; ATransactionsToApprove.Free; end; 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. // unit FixtureTests; interface uses TestFrameWork, Fixture, classes, sysUtils, windows, Parse; type T2dArrayOfString = array of array of string; TStringArray = array of string; TFixtureTests = class(TTestCase) private class function makeFixtureTable(table : T2dArrayOfString) : string; public class function executeFixture(table : T2dArrayOfString) : TParse; published procedure TestdoTablesPass; procedure TestdoTablesFail; procedure TestdoTablesException; procedure TestdoTablesIgnore; procedure TestCheck; procedure testEmptyCounts; procedure testTally; procedure testRuntime; // procedure testRunTimeOneSec; procedure testFixctureCounts; procedure testCreate; end; {$METHODINFO ON} TFixtureOne = class(TFixture) end; FixtureTwo = class(TFixture) end; TheThirdFixture = class(TFixture) end; {$METHODINFO OFF} implementation uses Runtime, Counts, FitFailureException; type PassFixture = class(TFixture) public procedure doTable(tables : TParse); override; end; FailFixture = class(TFixture) public procedure doTable(tables : TParse); override; end; IgnoreFixture = class(TFixture) public procedure doTable(tables : TParse); override; end; ExceptionFixture = class(TFixture) public procedure doTable(tables : TParse); override; end; TTestObject = class public Field : Integer; constructor Create; end; procedure TFixtureTests.testEmptyCounts; var theCounts : TCounts; begin theCounts := TCounts.Create; checkEquals('0 right, 0 wrong, 0 ignored, 0 exceptions', theCounts.toString); theCounts.Free; end; procedure TFixtureTests.testFixctureCounts; var theFixture : TFixture; begin theFixture := TFixture.create; checkEquals('0 right, 0 wrong, 0 ignored, 0 exceptions', theFixture.counts.toString); end; procedure TFixtureTests.testRuntime; var theRT : TRuntime; begin theRT := TRuntime.Create; theRT.Start := getTickCount; checkEquals('0:00.00', theRT.toString); theRT.Free; end; { procedure TFixtureTests.testRunTimeOneSec; var theRT : TRuntime; begin theRT := TRuntime.Create; theRT.Start := getTickCount; Sleep(1000); check((theRT.elapsed > 500) and (theRT.Elapsed < 1500)); theRT.Free; end; } procedure TFixtureTests.testTally; var theCounts, source : TCounts; begin theCounts := TCounts.Create; source := TCounts.Create; source.right := 5; source.wrong := 5; source.ignores := 5; source.exceptions := 5; theCounts.tally(source); checkEquals(5, theCounts.right); checkEquals(5, theCounts.wrong); checkEquals(5, theCounts.ignores); checkEquals(5, theCounts.exceptions); theCounts.Free; end; procedure TFixtureTests.TestCheck; begin end; procedure TFixtureTests.testCreate; var instance : TTestObject; theClass : TClass; begin theClass := TTestObject; instance := TTestObject(theClass.NewInstance); try CheckEquals(0, instance.Field); finally instance.FreeInstance; end; end; procedure TFixtureTests.TestdoTablesPass; var theFixture : TFixture; theTable : TParse; passFixture : string; begin passFixture := '<table><tr><td>PassFixture</td></tr></table>'; theTable := TParse.Create(passFixture); theFixture := TFixture.Create; theFixture.doTables(theTable); check(pos('"pass"', theTable.Tag) > 0, 'Class pass was not found ' + theTable.tag); checkEquals(1, theFixture.Counts.right); end; { FixtureTests } procedure TFixtureTests.TestdoTablesFail; var theFixture : TFixture; theTable : TParse; passFixture : string; begin passFixture := '<table><tr><td>FailFixture</td></tr></table>'; theTable := TParse.Create(passFixture); theFixture := TFixture.Create; theFixture.doTables(theTable); check(pos(' class="fail"', theTable.Tag) > 0, 'Class fail was not found ' + theTable.tag); checkEquals(1, theFixture.Counts.wrong); check(pos('test failed', theTable.text) > 0, 'failure message not found'); end; procedure TFixtureTests.TestdoTablesException; var fixture : TFixture; table : TParse; passFixture : string; begin passFixture := '<table><tr><td>ExceptionFixture</td></tr></table>'; table := TParse.Create(passFixture); fixture := TFixture.Create; fixture.doTables(table); check(pos('Test exception from Exception Fixture', table.body) > 0, 'Exception message was not found ' + table.body); check(pos('class="error"', table.Tag) > 0, 'class error was not found ' + table.tag); checkEquals(1, fixture.Counts.exceptions); end; procedure TFixtureTests.TestdoTablesIgnore; var theFixture : TFixture; theTable : TParse; passFixture : string; begin passFixture := '<table><tr><td>IgnoreFixture</td></tr></table>'; theTable := TParse.Create(passFixture); theFixture := TFixture.Create; theFixture.doTables(theTable); check(pos(' class="ignore"', theTable.Tag) > 0, 'class ignore was not found ' + theTable.tag); checkEquals(1, theFixture.Counts.ignores); end; class function TFixtureTests.executeFixture(table : T2dArrayOfString) : TParse; var pageString : string; page : TParse; fixture : TFixture; begin pageString := makeFixtureTable(table); page := TParse.Create(pageString); fixture := TFixture.Create(); fixture.doTables(page); fixture.Free; result := page; end; class function TFixtureTests.makeFixtureTable(table : T2dArrayOfString) : string; var buf : string; ri : Integer; ci : Integer; cell : string; begin buf := ''; buf := buf + '<table>'#10; for ri := Low(table) to High(table) do begin buf := buf + ' <tr>'; for ci := Low(table[ri]) to High(table[ri]) do begin cell := table[ri][ci]; buf := buf + '<td>' + cell + '</td>'; end; buf := buf + '</tr>'#10; end; buf := buf + '</table>'#10; result := buf; end; { PassFixture } procedure PassFixture.doTable(tables : TParse); begin right(tables); end; { FailFixture } procedure FailFixture.doTable(tables : TParse); begin wrong(tables, 'test failed'); end; { PassFixture } procedure IgnoreFixture.doTable(tables : TParse); begin ignore(tables); end; { PassFixture } procedure ExceptionFixture.doTable(tables : TParse); var e : Exception; begin e := TFitFailureException.create('Test exception from Exception Fixture'); doException(tables, e); end; constructor TTestObject.Create; begin inherited; Field := 11; end; initialization registerTest(TFixtureTests.Suite); classes.RegisterClass(PassFixture); classes.RegisterClass(failFixture); classes.RegisterClass(IgnoreFixture); classes.RegisterClass(ExceptionFixture); classes.RegisterClass(TFixtureOne); classes.RegisterClass(FixtureTwo); classes.RegisterClass(TheThirdFixture); end.
unit MessagingServiceCommonObjects; interface uses IGetSelfUnit, MessagingServiceUnit, SysUtils, Classes; type TCommonMessageMember = class (TInterfacedObject, IMessageMember) protected FIdentifier: Variant; FDisplayName: String; public constructor Create; function GetIdentifier: Variant; procedure SetIdentifier(const Value: Variant); function GetDisplayName: String; procedure SetDisplayName(const Value: String); property Identifier: Variant read GetIdentifier write SetIdentifier; property DisplayName: String read GetDisplayName write SetDisplayName; end; TCommonMessageMembers = class (TAbstractMessageMembers) protected function CreateMessageMemberInstance: IMessageMember; override; end; TCommonMessage = class (TInterfacedObject, IMessage) protected FName: String; FContent: TStringList; FSender: IMessageMember; FReceivers: IMessageMembers; FAttachments: IMessageAttachments; public constructor Create; function GetSelf: TObject; function GetName: String; procedure SetName(const Value: String); function GetContent: TStrings; procedure SetContent(const Value: TStrings); procedure SetContentAsText(const Text: String); function GetSender: IMessageMember; function GetReceivers: IMessageMembers; function GetAttachments: IMessageAttachments; property Name: String read GetName write SetName; property Content: TStrings read GetContent write SetContent; property Sender: IMessageMember read GetSender; property Receivers: IMessageMembers read GetReceivers; property Attachments: IMessageAttachments read GetAttachments; end; TCommonMessages = class (TAbstractMessages) protected function CreateMessageInstance: IMessage; override; public constructor Create; override; end; TCommonMessageAttachment = class (TInterfacedObject, IMessageAttachment) protected FFilePath: String; public function GetFilePath: String; procedure SetFilePath(const FilePath: String); property FilePath: String read GetFilePath write SetFilePath; end; TCommonMessageAttachments = class (TAbstractMessageAttachments) protected function CreateMessageAttachmentInstance: IMessageAttachment; override; end; implementation uses Variants; { TCommonMessageMember } constructor TCommonMessageMember.Create; begin inherited; FIdentifier := Null; end; function TCommonMessageMember.GetDisplayName: String; begin Result := FDisplayName; end; function TCommonMessageMember.GetIdentifier: Variant; begin Result := FIdentifier; end; procedure TCommonMessageMember.SetDisplayName(const Value: String); begin FDisplayName := Value; end; procedure TCommonMessageMember.SetIdentifier(const Value: Variant); begin FIdentifier := Value; end; { TCommonMessageMembers } function TCommonMessageMembers.CreateMessageMemberInstance: IMessageMember; begin Result := TCommonMessageMember.Create; end; { TCommonMessage } constructor TCommonMessage.Create; begin inherited; FContent := TStringList.Create; FSender := TCommonMessageMember.Create; FReceivers := TCommonMessageMembers.Create; FAttachments := TCommonMessageAttachments.Create; end; function TCommonMessage.GetAttachments: IMessageAttachments; begin Result := FAttachments; end; function TCommonMessage.GetContent: TStrings; begin Result := FContent; end; function TCommonMessage.GetName: String; begin Result := FName; end; function TCommonMessage.GetReceivers: IMessageMembers; begin Result := FReceivers; end; function TCommonMessage.GetSelf: TObject; begin Result := Self; end; function TCommonMessage.GetSender: IMessageMember; begin Result := FSender; end; procedure TCommonMessage.SetContent(const Value: TStrings); begin FContent.Assign(Value); end; procedure TCommonMessage.SetContentAsText(const Text: String); begin FContent.Text := Text; end; procedure TCommonMessage.SetName(const Value: String); begin FName := Value; end; { TCommonMessageAttachment } function TCommonMessageAttachment.GetFilePath: String; begin Result := FFilePath; end; procedure TCommonMessageAttachment.SetFilePath(const FilePath: String); begin FFilePath := FilePath; end; { TCommonMessageAttachments } function TCommonMessageAttachments.CreateMessageAttachmentInstance: IMessageAttachment; begin Result := TCommonMessageAttachment.Create; end; { TCommonMessages } constructor TCommonMessages.Create; begin inherited; end; function TCommonMessages.CreateMessageInstance: IMessage; begin Result := TCommonMessage.Create; end; end.
unit Exemplo7_6; interface uses Exemplo7, Exemplo7_2, Exemplo7_3; type TGerenciadorFichaHelper = class helper for TGerenciadorFicha procedure ExportarParaArquivo(pTipoFicha: TTipoFicha; pNomeArquivo: string); class procedure CriarExportarDestruir(lFicha: TFichaUsuario; pTipoFicha: TTipoFicha; pNomeArquivo: string); end; implementation { TGerenciadorFichaHelper } class procedure TGerenciadorFichaHelper.CriarExportarDestruir(lFicha: TFichaUsuario; pTipoFicha: TTipoFicha; pNomeArquivo: string); var lGerenciadorFicha : TGerenciadorFicha; begin lGerenciadorFicha := TGerenciadorFicha.Create(lFicha); try lGerenciadorFicha.Exportar(TExportaFichaUsuarioFactory.ObterExportador(pTipoFicha),pNomeArquivo); finally lGerenciadorFicha.Free; end; end; procedure TGerenciadorFichaHelper.ExportarParaArquivo(pTipoFicha: TTipoFicha; pNomeArquivo: string); begin Exportar(TExportaFichaUsuarioFactory.ObterExportador(pTipoFicha),pNomeArquivo); end; end.
unit UPrefFAppPhotoInbox; { ClickForms Application } { Bradford Technologies, Inc. } { All Rights Reserved } { Source Code Copyrighted © 1998-2011 by Bradford Technologies, Inc. } { This is the Frame that contains the Application Photo Inbox Preferences} interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, RzShellDialogs, StdCtrls, RzButton, RzRadChk, ExtCtrls, UContainer; type TPrefAppPhotoInbox = class(TFrame) cbxWatchPhotos: TRzCheckBox; edtPathNewPhotosInbox: TEdit; cbxWPhotoInsert: TCheckBox; cbxWPhoto2Catalog: TCheckBox; btnBrowsePhotoWatchFolder: TButton; SelectFolderDialog: TRzSelectFolderDialog; Panel1: TPanel; StaticText1: TStaticText; procedure btnBrowsePhotoWatchFolderClick(Sender: TObject); procedure cbxWatchPhotosClick(Sender: TObject); private FDoc: TContainer; public constructor CreateFrame(AOwner: TComponent; ADoc: TContainer); procedure LoadPrefs; //loads in the prefs from the app procedure SavePrefs; //saves the changes procedure InitPhotoWatchFolder; procedure SavePhotoWatchFolder; function FolderWatcherSetupOK: Boolean; end; implementation uses UGlobals, UInit, UFileUtils, UStatus, UFolderSelect, UDirMonitor, UWatchFolders; {$R *.dfm} constructor TPrefAppPhotoInbox.CreateFrame(AOwner: TComponent; ADoc: TContainer); begin inherited Create(AOwner); FDoc := ADoc; LoadPrefs; end; procedure TPrefAppPhotoInbox.LoadPrefs; begin //Display watch folder settings InitPhotoWatchFolder; end; procedure TPrefAppPhotoInbox.SavePrefs; begin //capture watch folder settings SavePhotoWatchFolder; end; procedure TPrefAppPhotoInbox.btnBrowsePhotoWatchFolderClick(Sender: TObject); begin edtPathNewPhotosInbox.text := SelectOneFolder('Select the New Photos folder to watch', appPref_DirNewPhotosInbox); end; procedure TPrefAppPhotoInbox.cbxWatchPhotosClick(Sender: TObject); begin edtPathNewPhotosInbox.Enabled := cbxWatchPhotos.checked; btnBrowsePhotoWatchFolder.Enabled := cbxWatchPhotos.checked; cbxWPhotoInsert.Enabled := cbxWatchPhotos.checked; cbxWPhoto2Catalog.Enabled := cbxWatchPhotos.checked; end; procedure TPrefAppPhotoInbox.InitPhotoWatchFolder; begin if appPref_WatchPhotosInbox then cbxWatchPhotos.InitState(cbChecked) else cbxWatchPhotos.InitState(cbUnchecked); edtPathNewPhotosInbox.Text := appPref_DirNewPhotosInbox; cbxWPhotoInsert.Checked := appPref_AutoPhotoInsert2Cell; cbxWPhoto2Catalog.Checked := appPref_AutoPhoto2Catalog; edtPathNewPhotosInbox.Enabled := appPref_WatchPhotosInbox; btnBrowsePhotoWatchFolder.Enabled := appPref_WatchPhotosInbox; cbxWPhotoInsert.Enabled := appPref_WatchPhotosInbox; cbxWPhoto2Catalog.Enabled := appPref_WatchPhotosInbox; end; //this is called after dialog exists procedure TPrefAppPhotoInbox.SavePhotoWatchFolder; var fWatcher: TDirMonitor; turnedOnMsg: Integer; watcherSetup: Boolean; begin watcherSetup := False; turnedOnMsg := 0; appPref_AutoPhotoInsert2Cell := cbxWPhotoInsert.checked; appPref_AutoPhoto2Catalog := cbxWPhoto2Catalog.checked; //check if there was a change in the Watch Folder settings if (appPref_WatchPhotosInbox <> cbxWatchPhotos.checked) or (compareText(edtPathNewPhotosInbox.Text, appPref_DirNewPhotosInbox)<>0) then begin //user turned watching on or off if (appPref_WatchPhotosInbox <> cbxWatchPhotos.checked) then if cbxWatchPhotos.checked then //user wants a watcher begin fWatcher := FolderWatchers.Watcher[mtInboxPhotos]; //get one if not assigned(fWatcher) then fWatcher := FolderWatchers.CreateWatcher(mtInboxPhotos, ''); if DirectoryExists(edtPathNewPhotosInbox.Text) then //check for valid folder begin fWatcher.DirectoryToWatch := edtPathNewPhotosInbox.Text; fWatcher.active := True; //restart watcherSetup := True; turnedOnMsg := 1; end; end else begin fWatcher := FolderWatchers.Watcher[mtInboxPhotos]; //get one fWatcher.active := False; turnedOnMsg := 2; end; //if user wants to watch and they changed folders if not watcherSetup then if cbxWatchPhotos.checked and (compareText(edtPathNewPhotosInbox.Text, appPref_DirNewPhotosInbox)<>0) then if DirectoryExists(edtPathNewPhotosInbox.Text) then begin fWatcher := FolderWatchers.Watcher[mtInboxPhotos]; //while debugging if not assigned(fWatcher) then fWatcher := FolderWatchers.CreateWatcher(mtInboxPhotos, ''); fWatcher.active := False; //stop the monitoring to reset fWatcher.DirectoryToWatch := edtPathNewPhotosInbox.Text; fWatcher.active := True; //restart turnedOnMsg := 3; end; case turnedOnMsg of 1: ShowNotice('Monitoring '+ ExtractFileName(edtPathNewPhotosInbox.Text) + ' for new photos is now active.'); 2: ShowNotice('Monitoring '+ ExtractFileName(edtPathNewPhotosInbox.Text) + ' for new photos has been deactivated.'); 3: ShowNotice('The folder to watch for new photos has been changed to '+ ExtractFileName(edtPathNewPhotosInbox.Text) + ' and is now being monitored.'); end; end; //save the new settings appPref_WatchPhotosInbox := cbxWatchPhotos.checked; appPref_DirNewPhotosInbox := edtPathNewPhotosInbox.Text; //uncheck watcher setting if we don't have a valid folder to watch if not DirectoryExists(appPref_DirNewPhotosInbox) then appPref_WatchPhotosInbox := False; end; function TPrefAppPhotoInbox.FolderWatcherSetupOK: Boolean; begin result := True; if cbxWatchPhotos.checked and not DirectoryExists(edtPathNewPhotosInbox.Text) then begin ShowAlert(atWarnAlert, 'You have not specified a valid Photo Inbox folder to watch.'); //PrefPages.ActivePage := InBoxFolders; result := False; end; 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: 23.07.2021 14:40:17 unit IdOpenSSLHeaders_pem; interface // Headers for OpenSSL 1.1.1 // pem.h {$i IdCompilerDefines.inc} uses Classes, IdCTypes, IdGlobal, IdOpenSSLConsts, IdOpenSSLHeaders_ec, IdOpenSSLHeaders_ossl_typ, IdOpenSSLHeaders_pkcs7, IdOpenSSLHeaders_x509; type EVP_CIPHER_INFO = type Pointer; PEVP_CIPHER_INFO = ^EVP_CIPHER_INFO; const PEM_BUFSIZE = 1024; PEM_STRING_X509_OLD = AnsiString('X509 CERTIFICATE'); PEM_STRING_X509 = AnsiString('CERTIFICATE'); PEM_STRING_X509_TRUSTED = AnsiString('TRUSTED CERTIFICATE'); PEM_STRING_X509_REQ_OLD = AnsiString('NEW CERTIFICATE REQUEST'); PEM_STRING_X509_REQ = AnsiString('CERTIFICATE REQUEST'); PEM_STRING_X509_CRL = AnsiString('X509 CRL'); PEM_STRING_EVP_PKEY = AnsiString('ANY PRIVATE KEY'); PEM_STRING_PUBLIC = AnsiString('PUBLIC KEY'); PEM_STRING_RSA = AnsiString('RSA PRIVATE KEY'); PEM_STRING_RSA_PUBLIC = AnsiString('RSA PUBLIC KEY'); PEM_STRING_DSA = AnsiString('DSA PRIVATE KEY'); PEM_STRING_DSA_PUBLIC = AnsiString('DSA PUBLIC KEY'); PEM_STRING_PKCS7 = AnsiString('PKCS7'); PEM_STRING_PKCS7_SIGNED = AnsiString('PKCS #7 SIGNED DATA'); PEM_STRING_PKCS8 = AnsiString('ENCRYPTED PRIVATE KEY'); PEM_STRING_PKCS8INF = AnsiString('PRIVATE KEY'); PEM_STRING_DHPARAMS = AnsiString('DH PARAMETERS'); PEM_STRING_DHXPARAMS = AnsiString('X9.42 DH PARAMETERS'); PEM_STRING_SSL_SESSION = AnsiString('SSL SESSION PARAMETERS'); PEM_STRING_DSAPARAMS = AnsiString('DSA PARAMETERS'); PEM_STRING_ECDSA_PUBLIC = AnsiString('ECDSA PUBLIC KEY'); PEM_STRING_ECPARAMETERS = AnsiString('EC PARAMETERS'); PEM_STRING_ECPRIVATEKEY = AnsiString('EC PRIVATE KEY'); PEM_STRING_PARAMETERS = AnsiString('PARAMETERS'); PEM_STRING_CMS = AnsiString('CMS'); PEM_TYPE_ENCRYPTED = 10; PEM_TYPE_MIC_ONLY = 20; PEM_TYPE_MIC_CLEAR = 30; PEM_TYPE_CLEAR = 40; PEM_FLAG_SECURE = $1; PEM_FLAG_EAY_COMPATIBLE = $2; PEM_FLAG_ONLY_B64 = $4; type pem_password_cb = function(buf: PIdAnsiChar; size: TIdC_INT; rwflag: TIdC_INT; userdata: Pointer): TIdC_INT; cdecl; procedure Load(const ADllHandle: TIdLibHandle; const AFailed: TStringList); procedure UnLoad; var PEM_get_EVP_CIPHER_INFO: function(header: PIdAnsiChar; cipher: PEVP_CIPHER_INFO): TIdC_INT cdecl = nil; PEM_do_header: function(cipher: PEVP_CIPHER_INFO; data: PByte; len: PIdC_LONG; callback: pem_password_cb; u: Pointer): TIdC_INT cdecl = nil; PEM_read_bio: function(bp: PBIO; name: PPIdAnsiChar; header: PPIdAnsiChar; data: PPByte; len: PIdC_LONG): TIdC_INT cdecl = nil; PEM_read_bio_ex: function(bp: PBIO; name: PPIdAnsiChar; header: PPIdAnsiChar; data: PPByte; len: PIdC_LONG; flags: TIdC_UINT): TIdC_INT cdecl = nil; PEM_bytes_read_bio_secmem: function(pdata: PPByte; plen: PIdC_LONG; pnm: PPIdAnsiChar; const name: PIdAnsiChar; bp: PBIO; cb: pem_password_cb; u: Pointer): TIdC_INT cdecl = nil; PEM_write_bio: function(bp: PBIO; const name: PIdAnsiChar; const hdr: PIdAnsiChar; const data: PByte; len: TIdC_LONG): TIdC_INT cdecl = nil; PEM_bytes_read_bio: function(pdata: PPByte; plen: PIdC_LONG; pnm: PPIdAnsiChar; const name: PIdAnsiChar; bp: PBIO; cb: pem_password_cb; u: Pointer): TIdC_INT cdecl = nil; PEM_ASN1_read_bio: function(d2i: d2i_of_void; const name: PIdAnsiChar; bp: PBIO; x: PPointer; cb: pem_password_cb; u: Pointer): Pointer cdecl = nil; PEM_ASN1_write_bio: function(i2d: i2d_of_void; const name: PIdAnsiChar; bp: PBIO; x: Pointer; const enc: PEVP_CIPHER; kstr: PByte; klen: TIdC_INT; cb: pem_password_cb; u: Pointer): TIdC_INT cdecl = nil; //function PEM_X509_INFO_read_bio(bp: PBIO; sk: PSTACK_OF_X509_INFO; cb: pem_password_cb; u: Pointer): PSTACK_OF_X509_INFO; PEM_X509_INFO_write_bio: function(bp: PBIO; xi: PX509_INFO; enc: PEVP_CIPHER; kstr: PByte; klen: TIdC_INT; cd: pem_password_cb; u: Pointer): TIdC_INT cdecl = nil; PEM_SignInit: function(ctx: PEVP_MD_CTX; type_: PEVP_MD): TIdC_INT cdecl = nil; PEM_SignUpdate: function(ctx: PEVP_MD_CTX; d: PByte; cnt: Byte): TIdC_INT cdecl = nil; PEM_SignFinal: function(ctx: PEVP_MD_CTX; sigret: PByte; siglen: PIdC_UINT; pkey: PEVP_PKEY): TIdC_INT cdecl = nil; (* The default pem_password_cb that's used internally *) PEM_def_callback: function(buf: PIdAnsiChar; num: TIdC_INT; rwflag: TIdC_INT; userdata: Pointer): TIdC_INT cdecl = nil; PEM_proc_type: procedure(buf: PIdAnsiChar; type_: TIdC_INT) cdecl = nil; PEM_dek_info: procedure(buf: PIdAnsiChar; const type_: PIdAnsiChar; len: TIdC_INT; str: PIdAnsiChar) cdecl = nil; PEM_read_bio_X509: function(bp: PBIO; x: PPX509; cb: pem_password_cb; u: Pointer): PX509 cdecl = nil; PEM_write_bio_X509: function(bp: PBIO; x: PX509): TIdC_INT cdecl = nil; PEM_read_bio_X509_AUX: function(bp: PBIO; x: PPX509; cb: pem_password_cb; u: Pointer): PX509 cdecl = nil; PEM_write_bio_X509_AUX: function(bp: PBIO; x: PX509): TIdC_INT cdecl = nil; PEM_read_bio_X509_REQ: function(bp: PBIO; x: PPX509_REQ; cb: pem_password_cb; u: Pointer): PX509_REQ cdecl = nil; PEM_write_bio_X509_REQ: function(bp: PBIO; x: PX509_REQ): TIdC_INT cdecl = nil; PEM_write_bio_X509_REQ_NEW: function(bp: PBIO; x: PX509_REQ): TIdC_INT cdecl = nil; PEM_read_bio_X509_CRL: function(bp: PBIO; x: PPX509_CRL; cb: pem_password_cb; u: Pointer): PX509_CRL cdecl = nil; PEM_write_bio_X509_CRL: function(bp: PBIO; x: PX509_CRL): TIdC_INT cdecl = nil; PEM_read_bio_PKCS7: function(bp: PBIO; x: PPPKCS7; cb: pem_password_cb; u: Pointer): PPKCS7 cdecl = nil; PEM_write_bio_PKCS7: function(bp: PBIO; x: PPKCS7): TIdC_INT cdecl = nil; // function PEM_read_bio_NETSCAPE_CERT_SEQUENCE(bp: PBIO; x: PPNETSCAPE_CERT_SEQUENCE; cb: pem_password_cb; u: Pointer): PNETSCAPE_CERT_SEQUENCE; // function PEM_write_bio_NETSCAPE_CERT_SEQUENCE(bp: PBIO; x: PNETSCAPE_CERT_SEQUENCE): TIdC_INT; PEM_read_bio_PKCS8: function(bp: PBIO; x: PPX509_SIG; cb: pem_password_cb; u: Pointer): PX509_SIG cdecl = nil; PEM_write_bio_PKCS8: function(bp: PBIO; x: PX509_SIG): TIdC_INT cdecl = nil; PEM_read_bio_PKCS8_PRIV_KEY_INFO: function(bp: PBIO; x: PPPKCS8_PRIV_KEY_INFO; cb: pem_password_cb; u: Pointer): PPKCS8_PRIV_KEY_INFO cdecl = nil; PEM_write_bio_PKCS8_PRIV_KEY_INFO: function(bp: PBIO; x: PPKCS8_PRIV_KEY_INFO): TIdC_INT cdecl = nil; // RSA PEM_read_bio_RSAPrivateKey: function(bp: PBIO; x: PPRSA; cb: pem_password_cb; u: Pointer): PRSA cdecl = nil; PEM_write_bio_RSAPrivateKey: function(bp: PBIO; x: PRSA; const enc: PEVP_CIPHER; kstr: PByte; klen: TIdC_INT; cb: pem_password_cb; u: Pointer): TIdC_INT cdecl = nil; PEM_read_bio_RSAPublicKey: function(bp: PBIO; x: PPRSA; cb: pem_password_cb; u: Pointer): PRSA cdecl = nil; PEM_write_bio_RSAPublicKey: function(bp: PBIO; const x: PRSA): TIdC_INT cdecl = nil; PEM_read_bio_RSA_PUBKEY: function(bp: PBIO; x: PPRSA; cb: pem_password_cb; u: Pointer): PRSA cdecl = nil; PEM_write_bio_RSA_PUBKEY: function(bp: PBIO; x: PRSA): TIdC_INT cdecl = nil; // ~RSA // DSA PEM_read_bio_DSAPrivateKey: function(bp: PBIO; x: PPDSA; cb: pem_password_cb; u: Pointer): PDSA cdecl = nil; PEM_write_bio_DSAPrivateKey: function(bp: PBIO; x: PDSA; const enc: PEVP_CIPHER; kstr: PByte; klen: TIdC_INT; cb: pem_password_cb; u: Pointer): TIdC_INT cdecl = nil; PEM_read_bio_DSA_PUBKEY: function(bp: PBIO; x: PPDSA; cb: pem_password_cb; u: Pointer): PDSA cdecl = nil; PEM_write_bio_DSA_PUBKEY: function(bp: PBIO; x: PDSA): TIdC_INT cdecl = nil; PEM_read_bio_DSAparams: function(bp: PBIO; x: PPDSA; cb: pem_password_cb; u: Pointer): PDSA cdecl = nil; PEM_write_bio_DSAparams: function(bp: PBIO; const x: PDSA): TIdC_INT cdecl = nil; // ~DSA // EC PEM_read_bio_ECPKParameters: function(bp: PBIO; x: PPEC_GROUP; cb: pem_password_cb; u: Pointer): PEC_GROUP cdecl = nil; PEM_write_bio_ECPKParameters: function(bp: PBIO; const x: PEC_GROUP): TIdC_INT cdecl = nil; PEM_read_bio_ECPrivateKey: function(bp: PBIO; x: PPEC_KEY; cb: pem_password_cb; u: Pointer): PEC_KEY cdecl = nil; PEM_write_bio_ECPrivateKey: function(bp: PBIO; x: PEC_KEY; const enc: PEVP_CIPHER; kstr: PByte; klen: TIdC_INT; cb: pem_password_cb; u: Pointer): TIdC_INT cdecl = nil; PEM_read_bio_EC_PUBKEY: function(bp: PBIO; x: PPEC_KEY; cb: pem_password_cb; u: Pointer): PEC_KEY cdecl = nil; PEM_write_bio_EC_PUBKEY: function(bp: PBIO; x: PEC_KEY): TIdC_INT cdecl = nil; // ~EC // DH PEM_read_bio_DHparams: function(bp: PBIO; x: PPDH; cb: pem_password_cb; u: Pointer): PDH cdecl = nil; PEM_write_bio_DHparams: function(bp: PBIO; const x: PDH): TIdC_INT cdecl = nil; PEM_write_bio_DHxparams: function(bp: PBIO; const x: PDH): TIdC_INT cdecl = nil; // ~DH PEM_read_bio_PrivateKey: function(bp: PBIO; x: PPEVP_PKEY; cb: pem_password_cb; u: Pointer): PEVP_PKEY cdecl = nil; PEM_write_bio_PrivateKey: function(bp: PBIO; x: PEVP_PKEY; const enc: PEVP_CIPHER; kstr: PByte; klen: TIdC_INT; cb: pem_password_cb; u: Pointer): TIdC_INT cdecl = nil; PEM_read_bio_PUBKEY: function(bp: PBIO; x: PPEVP_PKEY; cb: pem_password_cb; u: Pointer): PEVP_PKEY cdecl = nil; PEM_write_bio_PUBKEY: function(bp: PBIO; x: PEVP_PKEY): TIdC_INT cdecl = nil; PEM_write_bio_PrivateKey_traditional: function(bp: PBIO; x: PEVP_PKEY; const enc: PEVP_CIPHER; kstr: PByte; klen: TIdC_INT; cb: pem_password_cb; u: Pointer): TIdC_INT cdecl = nil; PEM_write_bio_PKCS8PrivateKey_nid: function(bp: PBIO; x: PEVP_PKEY; nid: TIdC_INT; kstr: PIdAnsiChar; klen: TIdC_INT; cb: pem_password_cb; u: Pointer): TIdC_INT cdecl = nil; PEM_write_bio_PKCS8PrivateKey: function(bp: PBIO; x: PEVP_PKEY_METHOD; const enc: PEVP_CIPHER; kstr: PIdAnsiChar; klen: TIdC_INT; cb: pem_password_cb; u: Pointer): TIdC_INT cdecl = nil; i2d_PKCS8PrivateKey_bio: function(bp: PBIO; x: PEVP_PKEY; const enc: PEVP_CIPHER_CTX; kstr: PIdAnsiChar; klen: TIdC_INT; cb: pem_password_cb; u: Pointer): TIdC_INT cdecl = nil; i2d_PKCS8PrivateKey_nid_bio: function(bp: PBIO; x: PEVP_PKEY; nid: TIdC_INT; kstr: PIdAnsiChar; klen: TIdC_INT; cb: pem_password_cb; u: Pointer): TIdC_INT cdecl = nil; d2i_PKCS8PrivateKey_bio: function(bp: PBIO; x: PPEVP_PKEY_CTX; cb: pem_password_cb; u: Pointer): PEVP_PKEY cdecl = nil; PEM_read_bio_Parameters: function(bp: PBIO; x: PPEVP_PKEY): PEVP_PKEY cdecl = nil; PEM_write_bio_Parameters: function(bp: PBIO; x: PEVP_PKEY): TIdC_INT cdecl = nil; b2i_PrivateKey: function(const in_: PPByte; length: TIdC_LONG): PEVP_PKEY cdecl = nil; b2i_PublicKey: function(const in_: PPByte; length: TIdC_LONG): PEVP_PKEY cdecl = nil; b2i_PrivateKey_bio: function(in_: PBIO): PEVP_PKEY cdecl = nil; b2i_PublicKey_bio: function(in_: PBIO): PEVP_PKEY cdecl = nil; i2b_PrivateKey_bio: function(out_: PBIO; pk: PEVP_PKEY): TIdC_INT cdecl = nil; i2b_PublicKey_bio: function(out_: PBIO; pk: PEVP_PKEY): TIdC_INT cdecl = nil; b2i_PVK_bio: function(in_: PBIO; cb: pem_password_cb; u: Pointer): PEVP_PKEY cdecl = nil; i2b_PVK_bio: function(out_: PBIO; pk: PEVP_PKEY; enclevel: TIdC_INT; cb: pem_password_cb; u: Pointer): TIdC_INT cdecl = nil; implementation procedure Load(const ADllHandle: TIdLibHandle; const AFailed: TStringList); function LoadFunction(const AMethodName: string; const AFailed: TStringList): Pointer; begin Result := LoadLibFunction(ADllHandle, AMethodName); if not Assigned(Result) then AFailed.Add(AMethodName); end; begin PEM_get_EVP_CIPHER_INFO := LoadFunction('PEM_get_EVP_CIPHER_INFO', AFailed); PEM_do_header := LoadFunction('PEM_do_header', AFailed); PEM_read_bio := LoadFunction('PEM_read_bio', AFailed); PEM_read_bio_ex := LoadFunction('PEM_read_bio_ex', AFailed); PEM_bytes_read_bio_secmem := LoadFunction('PEM_bytes_read_bio_secmem', AFailed); PEM_write_bio := LoadFunction('PEM_write_bio', AFailed); PEM_bytes_read_bio := LoadFunction('PEM_bytes_read_bio', AFailed); PEM_ASN1_read_bio := LoadFunction('PEM_ASN1_read_bio', AFailed); PEM_ASN1_write_bio := LoadFunction('PEM_ASN1_write_bio', AFailed); PEM_X509_INFO_write_bio := LoadFunction('PEM_X509_INFO_write_bio', AFailed); PEM_SignInit := LoadFunction('PEM_SignInit', AFailed); PEM_SignUpdate := LoadFunction('PEM_SignUpdate', AFailed); PEM_SignFinal := LoadFunction('PEM_SignFinal', AFailed); PEM_def_callback := LoadFunction('PEM_def_callback', AFailed); PEM_proc_type := LoadFunction('PEM_proc_type', AFailed); PEM_dek_info := LoadFunction('PEM_dek_info', AFailed); PEM_read_bio_X509 := LoadFunction('PEM_read_bio_X509', AFailed); PEM_write_bio_X509 := LoadFunction('PEM_write_bio_X509', AFailed); PEM_read_bio_X509_AUX := LoadFunction('PEM_read_bio_X509_AUX', AFailed); PEM_write_bio_X509_AUX := LoadFunction('PEM_write_bio_X509_AUX', AFailed); PEM_read_bio_X509_REQ := LoadFunction('PEM_read_bio_X509_REQ', AFailed); PEM_write_bio_X509_REQ := LoadFunction('PEM_write_bio_X509_REQ', AFailed); PEM_write_bio_X509_REQ_NEW := LoadFunction('PEM_write_bio_X509_REQ_NEW', AFailed); PEM_read_bio_X509_CRL := LoadFunction('PEM_read_bio_X509_CRL', AFailed); PEM_write_bio_X509_CRL := LoadFunction('PEM_write_bio_X509_CRL', AFailed); PEM_read_bio_PKCS7 := LoadFunction('PEM_read_bio_PKCS7', AFailed); PEM_write_bio_PKCS7 := LoadFunction('PEM_write_bio_PKCS7', AFailed); PEM_read_bio_PKCS8 := LoadFunction('PEM_read_bio_PKCS8', AFailed); PEM_write_bio_PKCS8 := LoadFunction('PEM_write_bio_PKCS8', AFailed); PEM_read_bio_PKCS8_PRIV_KEY_INFO := LoadFunction('PEM_read_bio_PKCS8_PRIV_KEY_INFO', AFailed); PEM_write_bio_PKCS8_PRIV_KEY_INFO := LoadFunction('PEM_write_bio_PKCS8_PRIV_KEY_INFO', AFailed); PEM_read_bio_RSAPrivateKey := LoadFunction('PEM_read_bio_RSAPrivateKey', AFailed); PEM_write_bio_RSAPrivateKey := LoadFunction('PEM_write_bio_RSAPrivateKey', AFailed); PEM_read_bio_RSAPublicKey := LoadFunction('PEM_read_bio_RSAPublicKey', AFailed); PEM_write_bio_RSAPublicKey := LoadFunction('PEM_write_bio_RSAPublicKey', AFailed); PEM_read_bio_RSA_PUBKEY := LoadFunction('PEM_read_bio_RSA_PUBKEY', AFailed); PEM_write_bio_RSA_PUBKEY := LoadFunction('PEM_write_bio_RSA_PUBKEY', AFailed); PEM_read_bio_DSAPrivateKey := LoadFunction('PEM_read_bio_DSAPrivateKey', AFailed); PEM_write_bio_DSAPrivateKey := LoadFunction('PEM_write_bio_DSAPrivateKey', AFailed); PEM_read_bio_DSA_PUBKEY := LoadFunction('PEM_read_bio_DSA_PUBKEY', AFailed); PEM_write_bio_DSA_PUBKEY := LoadFunction('PEM_write_bio_DSA_PUBKEY', AFailed); PEM_read_bio_DSAparams := LoadFunction('PEM_read_bio_DSAparams', AFailed); PEM_write_bio_DSAparams := LoadFunction('PEM_write_bio_DSAparams', AFailed); PEM_read_bio_ECPKParameters := LoadFunction('PEM_read_bio_ECPKParameters', AFailed); PEM_write_bio_ECPKParameters := LoadFunction('PEM_write_bio_ECPKParameters', AFailed); PEM_read_bio_ECPrivateKey := LoadFunction('PEM_read_bio_ECPrivateKey', AFailed); PEM_write_bio_ECPrivateKey := LoadFunction('PEM_write_bio_ECPrivateKey', AFailed); PEM_read_bio_EC_PUBKEY := LoadFunction('PEM_read_bio_EC_PUBKEY', AFailed); PEM_write_bio_EC_PUBKEY := LoadFunction('PEM_write_bio_EC_PUBKEY', AFailed); PEM_read_bio_DHparams := LoadFunction('PEM_read_bio_DHparams', AFailed); PEM_write_bio_DHparams := LoadFunction('PEM_write_bio_DHparams', AFailed); PEM_write_bio_DHxparams := LoadFunction('PEM_write_bio_DHxparams', AFailed); PEM_read_bio_PrivateKey := LoadFunction('PEM_read_bio_PrivateKey', AFailed); PEM_write_bio_PrivateKey := LoadFunction('PEM_write_bio_PrivateKey', AFailed); PEM_read_bio_PUBKEY := LoadFunction('PEM_read_bio_PUBKEY', AFailed); PEM_write_bio_PUBKEY := LoadFunction('PEM_write_bio_PUBKEY', AFailed); PEM_write_bio_PrivateKey_traditional := LoadFunction('PEM_write_bio_PrivateKey_traditional', AFailed); PEM_write_bio_PKCS8PrivateKey_nid := LoadFunction('PEM_write_bio_PKCS8PrivateKey_nid', AFailed); PEM_write_bio_PKCS8PrivateKey := LoadFunction('PEM_write_bio_PKCS8PrivateKey', AFailed); i2d_PKCS8PrivateKey_bio := LoadFunction('i2d_PKCS8PrivateKey_bio', AFailed); i2d_PKCS8PrivateKey_nid_bio := LoadFunction('i2d_PKCS8PrivateKey_nid_bio', AFailed); d2i_PKCS8PrivateKey_bio := LoadFunction('d2i_PKCS8PrivateKey_bio', AFailed); PEM_read_bio_Parameters := LoadFunction('PEM_read_bio_Parameters', AFailed); PEM_write_bio_Parameters := LoadFunction('PEM_write_bio_Parameters', AFailed); b2i_PrivateKey := LoadFunction('b2i_PrivateKey', AFailed); b2i_PublicKey := LoadFunction('b2i_PublicKey', AFailed); b2i_PrivateKey_bio := LoadFunction('b2i_PrivateKey_bio', AFailed); b2i_PublicKey_bio := LoadFunction('b2i_PublicKey_bio', AFailed); i2b_PrivateKey_bio := LoadFunction('i2b_PrivateKey_bio', AFailed); i2b_PublicKey_bio := LoadFunction('i2b_PublicKey_bio', AFailed); b2i_PVK_bio := LoadFunction('b2i_PVK_bio', AFailed); i2b_PVK_bio := LoadFunction('i2b_PVK_bio', AFailed); end; procedure UnLoad; begin PEM_get_EVP_CIPHER_INFO := nil; PEM_do_header := nil; PEM_read_bio := nil; PEM_read_bio_ex := nil; PEM_bytes_read_bio_secmem := nil; PEM_write_bio := nil; PEM_bytes_read_bio := nil; PEM_ASN1_read_bio := nil; PEM_ASN1_write_bio := nil; PEM_X509_INFO_write_bio := nil; PEM_SignInit := nil; PEM_SignUpdate := nil; PEM_SignFinal := nil; PEM_def_callback := nil; PEM_proc_type := nil; PEM_dek_info := nil; PEM_read_bio_X509 := nil; PEM_write_bio_X509 := nil; PEM_read_bio_X509_AUX := nil; PEM_write_bio_X509_AUX := nil; PEM_read_bio_X509_REQ := nil; PEM_write_bio_X509_REQ := nil; PEM_write_bio_X509_REQ_NEW := nil; PEM_read_bio_X509_CRL := nil; PEM_write_bio_X509_CRL := nil; PEM_read_bio_PKCS7 := nil; PEM_write_bio_PKCS7 := nil; PEM_read_bio_PKCS8 := nil; PEM_write_bio_PKCS8 := nil; PEM_read_bio_PKCS8_PRIV_KEY_INFO := nil; PEM_write_bio_PKCS8_PRIV_KEY_INFO := nil; PEM_read_bio_RSAPrivateKey := nil; PEM_write_bio_RSAPrivateKey := nil; PEM_read_bio_RSAPublicKey := nil; PEM_write_bio_RSAPublicKey := nil; PEM_read_bio_RSA_PUBKEY := nil; PEM_write_bio_RSA_PUBKEY := nil; PEM_read_bio_DSAPrivateKey := nil; PEM_write_bio_DSAPrivateKey := nil; PEM_read_bio_DSA_PUBKEY := nil; PEM_write_bio_DSA_PUBKEY := nil; PEM_read_bio_DSAparams := nil; PEM_write_bio_DSAparams := nil; PEM_read_bio_ECPKParameters := nil; PEM_write_bio_ECPKParameters := nil; PEM_read_bio_ECPrivateKey := nil; PEM_write_bio_ECPrivateKey := nil; PEM_read_bio_EC_PUBKEY := nil; PEM_write_bio_EC_PUBKEY := nil; PEM_read_bio_DHparams := nil; PEM_write_bio_DHparams := nil; PEM_write_bio_DHxparams := nil; PEM_read_bio_PrivateKey := nil; PEM_write_bio_PrivateKey := nil; PEM_read_bio_PUBKEY := nil; PEM_write_bio_PUBKEY := nil; PEM_write_bio_PrivateKey_traditional := nil; PEM_write_bio_PKCS8PrivateKey_nid := nil; PEM_write_bio_PKCS8PrivateKey := nil; i2d_PKCS8PrivateKey_bio := nil; i2d_PKCS8PrivateKey_nid_bio := nil; d2i_PKCS8PrivateKey_bio := nil; PEM_read_bio_Parameters := nil; PEM_write_bio_Parameters := nil; b2i_PrivateKey := nil; b2i_PublicKey := nil; b2i_PrivateKey_bio := nil; b2i_PublicKey_bio := nil; i2b_PrivateKey_bio := nil; i2b_PublicKey_bio := nil; b2i_PVK_bio := nil; i2b_PVK_bio := nil; end; end.
unit ETL.Component.Extract.Files; interface uses ETL.Component.Extract, ETL.Form.Edit.Extract, ETL.Form.Edit.Extract.Files, ETL.Form.Grid, ETL.FileProject.Interfaces; type TCompFiles = class(TCompExtract) strict private FFormEdit: TFoEditFiles; // FConnections: TObjectList<TFDConnection>; function GetInstanceFormEdit: TFoEditExtract; override; strict protected function GetScript: string; override; procedure setScript(const AScript: string); override; procedure RefreshGrid(var AFormGrid: TFoGrid); override; end; implementation uses System.SysUtils, FireDAC.Comp.Client, Generics.Collections; { TCompQuery } procedure TCompFiles.RefreshGrid(var AFormGrid: TFoGrid); var i: Integer; begin inherited; AFormGrid.tv.DataController.RecordCount := 0; // AFormGrid.tv.Bands.Clear; AFormGrid.tv.ClearItems; end; function TCompFiles.GetInstanceFormEdit: TFoEditExtract; begin if not Assigned(FFormEdit) then begin FFormEdit := TFoEditFiles.New(Self); FFormEdit.OnChange := OnFormEditChange; end; Result := FFormEdit; end; const SEPARATE_FILES_CHAR = '|'; function TCompFiles.GetScript: string; var i: Integer; begin Result := ''; if Assigned(FFormEdit) then begin Result := FFormEdit.EdPath.Text + SEPARATE_FILES_CHAR + FFormEdit.EdFilter.Text + SEPARATE_FILES_CHAR; if FFormEdit.CbSubDir.Checked then Result := Result + '1' else Result := Result + '0' end; end; procedure TCompFiles.setScript(const AScript: string); var s: string; i: Integer; begin i := Pos(SEPARATE_FILES_CHAR, AScript); TFoEditFiles(GetInstanceFormEdit).EdPath.Text := Copy(AScript, 1, i - 1); s := Copy(AScript, i + 1); i := Pos(SEPARATE_FILES_CHAR, s); FFormEdit.EdFilter.Text := Copy(s, 1, i - 1); FFormEdit.CbSubDir.Checked := Copy(s, i + 1) = '1'; end; end.
(* Name: UfrmDebugStatus_Deadkeys Copyright: Copyright (C) SIL International. Documentation: Description: Create Date: 14 Sep 2006 Modified Date: 16 Jan 2009 Authors: mcdurdin Related Files: Dependencies: Bugs: Todo: Notes: History: 14 Sep 2006 - mcdurdin - Initial version 16 Jan 2009 - mcdurdin - I1699 - Fix crash in debugger when debugging deadkeys *) unit UfrmDebugStatus_Deadkeys; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, DebugListBox, debugging, debugdeadkeys, UfrmDebugStatus_Child; type TfrmDebugStatus_DeadKeys = class(TfrmDebugStatus_Child) lbDeadkeys: TDebugListBox; procedure lbDeadkeysClick(Sender: TObject); private { Deadkey functions } procedure ClearDeadKeys; public procedure UpdateDeadkeyDisplay(deadkeys: TList); procedure DeselectDeadkeys; end; implementation uses UfrmDebugStatus; {$R *.dfm} procedure TfrmDebugStatus_DeadKeys.ClearDeadKeys; begin lbDeadkeys.Clear; end; procedure TfrmDebugStatus_DeadKeys.DeselectDeadkeys; begin lbDeadkeys.ItemIndex := -1; lbDeadkeysClick(lbDeadkeys); end; procedure TfrmDebugStatus_DeadKeys.lbDeadkeysClick(Sender: TObject); begin if lbDeadKeys.ItemIndex < 0 then DebugForm.SelectDeadKey(nil) else DebugForm.SelectDeadKey(lbDeadKeys.Items.Objects[lbDeadKeys.ItemIndex] as TDeadKeyInfo); end; procedure TfrmDebugStatus_DeadKeys.UpdateDeadkeyDisplay(deadkeys: TList); var i: Integer; begin ClearDeadKeys; for i := 0 to deadkeys.Count - 1 do with TDeadKeyInfo(deadkeys[i]) do lbDeadkeys.Items.AddObject('deadkey('+Deadkey.Name+') ('+IntToStr(Position)+')', TDeadKeyInfo(deadkeys[i])); end; end.
unit uDMCdata; interface uses System.SysUtils, System.Classes, 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.CDataGoogleDrive, FireDAC.Phys.CDataGoogleDriveDef, FireDAC.FMXUI.Wait, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.Client, Data.DB, FireDAC.Comp.DataSet, FMX.Dialogs, FMX.Types,System.Generics.Collections, uCDataGDriveTypes; type TdmCdata = class(TDataModule, IGDrive, IGDFile) fdGDriveCon: TFDConnection; fqFiles: TFDQuery; fqTemp: TFDQuery; spCreateFolder: TFDStoredProc; spUploadFile: TFDStoredProc; spDownloadFile: TFDStoredProc; fqRead: TFDQuery; fqSearch: TFDQuery; fqInsert: TFDQuery; fqUpdate: TFDQuery; fqDelete: TFDQuery; fqPermissions: TFDQuery; procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); procedure fdGDriveConAfterConnect(Sender: TObject); private { Private declarations } FRootPath: GDPath; FCurPath: GDPath; FPath: TStack<GDPath>; procedure SetRootPath(const Value: GDPath); function GetRootPath: GDPath; public { Public declarations } property RootPath: GDPath read FRootPath write SetRootPath; property CurPath: GDPath read FCurPath write FCurPath; function PathToStr: string; procedure GetFolderFileList(FolderId:TFileId); { IGDrive = interface } procedure Connect; function UploadFile(name:string; description: string; FolderId: TFileID; localfile: string): TFileID; function DownloadFile(FileId: TFileID; fName,FileFormat: string; localfile: string; Overwrite:Boolean): boolean; function CreateFolder(name:string; description: string; FolderId: TFileID):TFileId; procedure Search(name:string); procedure SearchType(typenm:string); procedure SearchDate(StartDate, EndDate: TDatetime); function GetTablesList: TStringList; function InFolder(fileId:TFileId): GDPath; procedure JumpUp; procedure JumpTo(newFolder: GDPath); overload; procedure JumpTo(id:TFileId;name:string); overload; procedure JumpToRoot; { IGDFile = interface } function ReadGDFile(id:TFileId; out Buffer:TGDFileRec):boolean; function InsertGDFile(Buffer:TGDFileRec):TFileId; function UpdateGDFile(Buffer:TGDFileRec):boolean; function DeleteGDFile(id:TFileId): boolean; end; TMyDataset = TFDDataset; _GDFileRec = TGDFileRec; _GDPath = GDPath; function IsColumnHere(ds: TFDDataset; fName: string): Boolean; var dmCdata: TdmCdata; implementation {%CLASSGROUP 'FMX.Controls.TControl'} {$R *.dfm} function IsColumnHere(ds: TFDDataset; fName: string): Boolean; begin Result := False; if ds.FieldDefs.IndexOf(fName) > -1 then Result := True; end; { TdmCdata } function TdmCdata.GetTablesList: TStringList; begin Result := TStringList.Create; fdGDriveCon.GetTableNames('', '', '', Result); end; procedure TdmCdata.Connect; begin {todo 2 : if OAuthToken<>'' then begin fdGDriveCon.Params.Values['OAuthAuthorizeToken']:=OAuthToken; end; } fdGDriveCon.Connected := True; // moved to AfterConnected Event end; function TdmCdata.CreateFolder(name, description: string; FolderId: TFileID): TFileId; begin spCreateFolder.ParamByName('Name').AsString := name; spCreateFolder.ParamByName('Parents').AsString := String(FolderID); if description <> '' then spUploadFile.ParamByName('Description').AsString := description; spCreateFolder.ExecProc; end; procedure TdmCdata.DataModuleCreate(Sender: TObject); begin FPath:= TStack<GDPath>.Create; // FRootPath: GDPath; // FCurPath: GDPath; end; procedure TdmCdata.DataModuleDestroy(Sender: TObject); begin FPath.Free; end; function TdmCdata.DeleteGDFile(id: TFileId): boolean; begin fqDelete.ParamByName('fId').AsString:=string(id); try fqDelete.ExecSQL; Result:=True; except Result:=False; end; end; function TdmCdata.DownloadFile(FileId: TFileID; fName, FileFormat, localfile: string; Overwrite: Boolean): boolean; begin Result := False; spDownloadFile.ParamByName('LocalFile').AsString := localfile; spDownloadFile.ParamByName('Id').AsString := String(FileId); spDownloadFile.ParamByName('FileFormat').AsString := FileFormat; if Overwrite then spDownloadFile.ParamByName('Overwrite').AsString := 'true' else spDownloadFile.ParamByName('Overwrite').AsString := 'false'; spDownloadFile.ExecProc; Result := (spDownloadFile.ParamByName('success').AsString = 'true'); end; procedure TdmCdata.fdGDriveConAfterConnect(Sender: TObject); begin FRootPath := GetRootPath; JumpToRoot; end; procedure TdmCdata.GetFolderFileList(FolderId: TFileId); begin fqfiles.Close; fqFiles.ParamByName('pId').AsString:=FolderID; fqFiles.Open; end; function TdmCdata.GetRootPath: GDPath; var tsql: string; begin tsql := 'select ParentIds from Files where Query='' ''''root'''' in parents'' limit 1'; fqTemp.Open(tsql); if not fqTemp.Eof then begin Result.FolderID:= TFileId(fqTemp.FieldByName('ParentIds').AsString); Result.FolderName:='My Drive'; Result.ParentID:=''; end; fqTemp.Close; end; function TdmCdata.InFolder(fileId: TFileId): GDPath; var tsql: string; begin tsql := 'select F.Id, F.Name, F.ParentIds from Files S, Folders F where S.Id=''' + fileId + ''' and F.Id = S.parentIds limit 1'; fqTemp.Open(tsql); if not fqTemp.Eof then begin Result.FolderID := TFileId(fqTemp.FieldByName('Id').AsString); Result.FolderName := TFileId(fqTemp.FieldByName('name').AsString); Result.ParentID := TFileId(fqTemp.FieldByName('ParentIds').AsString); end; fqTemp.Close; end; function TdmCdata.InsertGDFile(Buffer: TGDFileRec): TFileId; begin Result:=''; fqInsert.ParamByName('Name').AsString:=Buffer.Name; fqInsert.ParamByName('Description').AsString:=Buffer.Description; fqInsert.ParamByName('MIME').AsString:=Buffer.MIMEType; fqInsert.ParamByName('Starred').AsBoolean:=Buffer.Starred; fqInsert.ExecSQL; Result:= Buffer.ParentIds; end; procedure TdmCdata.JumpTo(newFolder: GDPath); begin // tsql:='select * from Files where ''' + string(folderId) +''' in (parentids)'; // tsql := tsql + ' and Trashed = ''False'' order by Folder Desc'; // fqFiles.Open(tsql); // fqfiles.Close; // fqFiles.ParamByName('pId').AsString:=newFolder.FolderID; // fqFiles.Open; GetFolderFileList(newFolder.FolderID); FPath.Push(FCurPath); FCurPath:=newFolder; end; procedure TdmCdata.JumpTo(id: TFileId; name: string); var bpath:GDPath; begin bpath.FolderID:=id; bpath.FolderName:=name; bpath.ParentID:=FCurPath.FolderID; JumpTo(bpath); end; procedure TdmCdata.JumpToRoot; begin JumpTo(FRootPath); FPath.Clear; end; procedure TdmCdata.JumpUp; var tgtFolder: GDPath; begin if FPath.Count > 0 then begin tgtFolder:=FPath.Pop; fqfiles.Close; fqFiles.ParamByName('pId').AsString:=tgtFolder.FolderID; fqFiles.Open; FCurPath:=tgtFolder; end; end; function TdmCdata.PathToStr: string; var spart: string; //spart: GDPath; inarray: TArray<GDPath>; i: Integer; begin Result:=''; inarray:=FPath.ToArray; for i:=FPath.Count-1 downto 0 do begin spart := inarray[i].FolderName; Result := spart + '\' + Result; end; Result:=Result + FCurPath.FolderName; end; function TdmCdata.ReadGDFile(id: TFileId; out Buffer: TGDFileRec): boolean; begin fqRead.ParamByName('Id').AsString:=string(id); Result:=False; fqRead.Open; try if fqRead.RecordCount > 0 then begin Result:=True; //if fqRead.Fields['id'] <> nil then Buffer.Id := fqRead.FieldByName('Id').AsString; Buffer.Name := fqRead.FieldByName('Name').AsString; Buffer.Description := fqRead.FieldByName('Description').AsString; Buffer.Extension := fqRead.FieldByName('Extension').AsString; Buffer.MIMEType := fqRead.FieldByName('MIMEType').AsString; Buffer.CreatedTime := fqRead.FieldByName('CreatedTime').AsDateTime; Buffer.ModifiedTime := fqRead.FieldByName('ModifiedTime').AsDateTime; Buffer.Size := fqRead.FieldByName('Size').AsInteger; Buffer.OwnerName := fqRead.FieldByName('OwnerName').AsString; Buffer.OwnerEmail := fqRead.FieldByName('OwnerEmail').AsString; Buffer.Folder := fqRead.FieldByName('Folder').AsBoolean; Buffer.Starred := fqRead.FieldByName('Starred').AsBoolean; Buffer.Hidden := fqRead.FieldByName('Hidden').AsBoolean; Buffer.Trashed := fqRead.FieldByName('Trashed').AsBoolean; Buffer.Viewed := fqRead.FieldByName('Viewed').AsBoolean; Buffer.ParentIds := fqRead.FieldByName('ParentIds').AsString; Buffer.ChildIds := fqRead.FieldByName('ChildIds').AsString; Buffer.ChildLinks := fqRead.FieldByName('ChildLinks').AsString; end; finally fqRead.Close; end; // todo 1 : Add File Permissions reading end; procedure TdmCdata.Search(name: string); begin if Pos('%',name) > 1 then fqSearch.Open('select * from Files where Name Like '''+name+'''') else fqSearch.Open('select * from Files where Name = '''+name+''''); end; procedure TdmCdata.SearchDate(StartDate, EndDate: TDatetime); begin //todo 1 : check dates validity fqSearch.Open('select Name, ModifiedTime, Starred, OwnerName from Files where ModifiedTime > ' + DateToStr(StartDate)+' and ModifiedTime < ' + DateToStr(EndDate)); end; procedure TdmCdata.SearchType(typenm: string); var ltype, sqlfrom: string; begin //application/pdf ltype:= typenm.ToLower; if ltype = 'folders' then sqlfrom := ' from Folders' else if ltype = 'photos' then sqlfrom := ' from Photos' else if ltype = 'sheets' then sqlfrom := ' from Sheets' else if (ltype = 'docs') or (ltype = 'pdf')then sqlfrom := ' from Docs' else if ltype = 'videos' then sqlfrom := ' from Videos' else if ltype = 'trashed' then sqlfrom := ' from Files where Trashed = ''True''' else exit; fqSearch.Open('select Id,Name,ModifiedTime,Starred,OwnerName ' + sqlfrom); end; procedure TdmCdata.SetRootPath(const Value: GDPath); begin FRootPath := Value; end; function TdmCdata.UpdateGDFile(Buffer: TGDFileRec): boolean; begin fqUpdate.ParamByName('Id').AsString:=Buffer.Id; fqUpdate.ParamByName('Name').AsString:=Buffer.Name; fqUpdate.ParamByName('Description').AsString:=Buffer.Description; fqUpdate.ParamByName('MIME').AsString:=Buffer.MIMEType; fqUpdate.ParamByName('Starred').asBoolean:=Buffer.Starred; try fqUpdate.ExecSQL; Result:=True; except Result:=False; end; end; function TdmCdata.UploadFile(name, description: string; FolderId: TFileID; localfile: string): TFileID; begin spUploadFile.ParamByName('LocalFile').AsString := localfile; spUploadFile.ParamByName('Name').AsString := name; //ExtractFileName(localfile); spUploadFile.ParamByName('Parents').AsString := String(FolderID); if description <> '' then spUploadFile.ParamByName('Description').AsString := description; spUploadFile.ExecProc; end; end.
unit AErenderLauncher.Localization; interface uses System.Types, System.Character, System.Variants, System.IOUtils, System.SysUtils, System.Classes, System.JSON; type /// I didn't use it anywhere, but I'll leave it here /// Maybe this will come useful someday TLanguageCode = record const EN: Cardinal = 0; RU: Cardinal = 1; JP: Cardinal = 2; end; (* Main Menu values *) MainMenuText = record LauncherMenu, FileMenu, EditMenu, HelpMenu, RecentProjects, ImportConfiguration, ExportConfiguration, Close, CloseDarwin, OutputModuleEditor, Settings, Documentation, About: String end; (* Main Form *) MainFormText = record MainMenu: MainMenuText; ProjectFile, OutputFile, OpenSaveProjectButton, DarwinDialogTip, DarwinDialogOpen, DarwinDialogSaveNameField, DarwinDialogSave, OutputModulePreset, ConfigureOutputModules, RenderSettings, ConfigureRenderSettings, Properties, MissingFiles, Sound, Threaded, Custom, CustomPropHint, CacheUsageLimit, MemUsage, Unlimited, SingleComp, MultiComp, SingleRener, SplitRender, CompNameHint, MultiCompGridHeader, StartFrame, EndFrame, EndFrameHint, Calculate, Launch, NewVersionAvailable, Download: String end; (* Settings Form *) SettingsFormText = record LauncherSettings, RenderEnginePath, DefaultProjectsDirectory, DefaultOutputDirectory, UserInterface, Style, Language, LangChange, InterfaceScale, Behaviour, OnRenderStart, DoNothing, MinimizeLauncher, CloseLauncher, HandleAerender, DeleteTemporary: String; end; (* Import Form *) ImportFormText = record ImportAEProject, ProjectPath, Compositions, CompositonProperties, Name, Resolution, Framerate, RangeStart, RangeEnd, ImportProperties, PrepareForSplitRendering, SelectAll, DeselectAll, Import: String; end; (* Output Modules Editor Form *) OutputModuleFormText = record OutputModulePresetConfigurator, Imported, OutputModule, OutputModulePrompt, OutputFileNameStructure, OutputFileNamePrompt, ProjectTab, CompositionTab, CompositionTimeTab, ImageTab, DateTab, Save, Cancel, CloseDialog: String; end; (* About Form *) AboutFormText = record AErenderLauncher, CreatedBy, Description, FromRussiaWithLove, FFMPEG, FFMPEGNotFound, Copyright: String; end; RenderingFormText = record RenderingProgress, HandleDisabled, QueueIsEmpty, TotalProgress, TimeElapsed, AbortRendering, WaitingForAerender, Rendering, RenderingError, RenderingFinished: String; end; ErrorText = record MemoryValueInvalid, CacheValueInvalid, CalculateFrameError, CalculateUnknownError, ConfigCorrupted, aerenderInvalid, aerenderUndetectable, errorsOccured, aerenderIsEmpty, projectIsEmpty, outputIsEmpty, compositionIsEmpty, multiCompIsEmpty, tooManyThreads, isCurrentlyRendering, IncompatibleFile: String; end; LauncherText = record Language, Author, Completion: String; MainForm: MainFormText; SettingsForm: SettingsFormText; ImportForm: ImportFormText; OutputModuleConfiguratorForm: OutputModuleFormText; AboutForm: AboutFormText; RenderingForm: RenderingFormText; Errors: ErrorText; Result: Integer; /// <summary> /// Creates AErender Launcher Language data from specified .aerlang JSON file. /// </summary> constructor InitFromFile(Path: String); constructor InitFromStringList(StringList: TStringList); constructor InitFromResourceStream(Stream: TResourceStream); /// <summary> /// Parses .aerlang JSON file /// </summary function ParseJSONLanguage(const LanguageData: TJsonValue): LauncherText; end; implementation function LauncherText.ParseJSONLanguage(const LanguageData: TJsonValue): LauncherText; begin {$REGION ' Language Data '} Result.Language := LanguageData.P['language'].Value; Result.Author := LanguageData.P['author'].Value; Result.Completion := LanguageData.P['completion'].Value; {$ENDREGION} {$REGION ' Main Form Text '} {$REGION ' Menubar Text '} Result.MainForm.MainMenu.LauncherMenu := LanguageData.P['LauncherText'].P['MainFormText'].P['MainMenuText'].P['LauncherMenu'].Value; Result.MainForm.MainMenu.FileMenu := LanguageData.P['LauncherText'].P['MainFormText'].P['MainMenuText'].P['FileMenu'].Value; Result.MainForm.MainMenu.EditMenu := LanguageData.P['LauncherText'].P['MainFormText'].P['MainMenuText'].P['EditMenu'].Value; Result.MainForm.MainMenu.HelpMenu := LanguageData.P['LauncherText'].P['MainFormText'].P['MainMenuText'].P['HelpMenu'].Value; Result.MainForm.MainMenu.RecentProjects := LanguageData.P['LauncherText'].P['MainFormText'].P['MainMenuText'].P['RecentProjects'].Value; Result.MainForm.MainMenu.ImportConfiguration := LanguageData.P['LauncherText'].P['MainFormText'].P['MainMenuText'].P['ImportConfiguration'].Value; Result.MainForm.MainMenu.ExportConfiguration := LanguageData.P['LauncherText'].P['MainFormText'].P['MainMenuText'].P['ExportConfiguration'].Value; Result.MainForm.MainMenu.Close := LanguageData.P['LauncherText'].P['MainFormText'].P['MainMenuText'].P['Close'].Value; Result.MainForm.MainMenu.CloseDarwin := LanguageData.P['LauncherText'].P['MainFormText'].P['MainMenuText'].P['CloseDarwin'].Value; Result.MainForm.MainMenu.OutputModuleEditor := LanguageData.P['LauncherText'].P['MainFormText'].P['MainMenuText'].P['OutputModuleEditor'].Value; Result.MainForm.MainMenu.Settings := LanguageData.P['LauncherText'].P['MainFormText'].P['MainMenuText'].P['Settings'].Value; Result.MainForm.MainMenu.Documentation := LanguageData.P['LauncherText'].P['MainFormText'].P['MainMenuText'].P['Documentation'].Value; Result.MainForm.MainMenu.About := LanguageData.P['LauncherText'].P['MainFormText'].P['MainMenuText'].P['About'].Value; {$ENDREGION ' Menubar Text '} Result.MainForm.OutputFile := LanguageData.P['LauncherText'].P['MainFormText'].P['OutputFile'].Value; Result.MainForm.ProjectFile := LanguageData.P['LauncherText'].P['MainFormText'].P['ProjectFile'].Value; Result.MainForm.OpenSaveProjectButton := LanguageData.P['LauncherText'].P['MainFormText'].P['OpenSaveProjectButton'].Value; Result.MainForm.DarwinDialogTip := LanguageData.P['LauncherText'].P['MainFormText'].P['DarwinDialogTip'].Value; Result.MainForm.DarwinDialogOpen := LanguageData.P['LauncherText'].P['MainFormText'].P['DarwinDialogOpen'].Value; Result.MainForm.DarwinDialogSaveNameField := LanguageData.P['LauncherText'].P['MainFormText'].P['DarwinDialogSaveNameField'].Value; Result.MainForm.DarwinDialogSave := LanguageData.P['LauncherText'].P['MainFormText'].P['DarwinDialogSave'].Value; Result.MainForm.OutputModulePreset := LanguageData.P['LauncherText'].P['MainFormText'].P['OutputModulePreset'].Value; Result.MainForm.ConfigureOutputModules := LanguageData.P['LauncherText'].P['MainFormText'].P['ConfigureOutputModules'].Value; Result.MainForm.RenderSettings := LanguageData.P['LauncherText'].P['MainFormText'].P['RenderSettings'].Value; Result.MainForm.ConfigureRenderSettings := LanguageData.P['LauncherText'].P['MainFormText'].P['ConfigureRenderSettings'].Value; Result.MainForm.Properties := LanguageData.P['LauncherText'].P['MainFormText'].P['Properties'].Value; Result.MainForm.MissingFiles := LanguageData.P['LauncherText'].P['MainFormText'].P['MissingFiles'].Value; Result.MainForm.Sound := LanguageData.P['LauncherText'].P['MainFormText'].P['Sound'].Value; Result.MainForm.Threaded := LanguageData.P['LauncherText'].P['MainFormText'].P['Threaded'].Value; Result.MainForm.Custom := LanguageData.P['LauncherText'].P['MainFormText'].P['Custom'].Value; Result.MainForm.CustomPropHint := LanguageData.P['LauncherText'].P['MainFormText'].P['CustomPropHint'].Value; Result.MainForm.CacheUsageLimit := LanguageData.P['LauncherText'].P['MainFormText'].P['CacheUsageLimit'].Value; Result.MainForm.MemUsage := LanguageData.P['LauncherText'].P['MainFormText'].P['MemUsage'].Value; Result.MainForm.Unlimited := LanguageData.P['LauncherText'].P['MainFormText'].P['Unlimited'].Value; Result.MainForm.SingleComp := LanguageData.P['LauncherText'].P['MainFormText'].P['SingleComp'].Value; Result.MainForm.MultiComp := LanguageData.P['LauncherText'].P['MainFormText'].P['MultiComp'].Value; Result.MainForm.SingleRener := LanguageData.P['LauncherText'].P['MainFormText'].P['SingleRener'].Value; Result.MainForm.SplitRender := LanguageData.P['LauncherText'].P['MainFormText'].P['SplitRender'].Value; Result.MainForm.CompNameHint := LanguageData.P['LauncherText'].P['MainFormText'].P['CompNameHint'].Value; Result.MainForm.MultiCompGridHeader := LanguageData.P['LauncherText'].P['MainFormText'].P['MultiCompGridHeader'].Value; Result.MainForm.StartFrame := LanguageData.P['LauncherText'].P['MainFormText'].P['StartFrame'].Value; Result.MainForm.EndFrame := LanguageData.P['LauncherText'].P['MainFormText'].P['EndFrame'].Value; Result.MainForm.EndFrameHint := LanguageData.P['LauncherText'].P['MainFormText'].P['EndFrameHint'].Value; Result.MainForm.Calculate := LanguageData.P['LauncherText'].P['MainFormText'].P['Calculate'].Value; Result.MainForm.Launch := LanguageData.P['LauncherText'].P['MainFormText'].P['Launch'].Value; Result.MainForm.NewVersionAvailable := LanguageData.P['LauncherText'].P['MainFormText'].P['NewVersionAvailable'].Value; Result.MainForm.Download := LanguageData.P['LauncherText'].P['MainFormText'].P['Download'].Value; {$ENDREGION} {$REGION ' Settings Form Text '} Result.SettingsForm.LauncherSettings := LanguageData.P['LauncherText'].P['SettingsFormText'].P['LauncherSettings'].Value; Result.SettingsForm.RenderEnginePath := LanguageData.P['LauncherText'].P['SettingsFormText'].P['RenderEnginePath'].Value; Result.SettingsForm.DefaultProjectsDirectory := LanguageData.P['LauncherText'].P['SettingsFormText'].P['DefaultProjectsDirectory'].Value; Result.SettingsForm.DefaultOutputDirectory := LanguageData.P['LauncherText'].P['SettingsFormText'].P['DefaultOutputDirectory'].Value; Result.SettingsForm.UserInterface := LanguageData.P['LauncherText'].P['SettingsFormText'].P['UserInterface'].Value; Result.SettingsForm.Style := LanguageData.P['LauncherText'].P['SettingsFormText'].P['Style'].Value; Result.SettingsForm.Language := LanguageData.P['LauncherText'].P['SettingsFormText'].P['Language'].Value; Result.SettingsForm.LangChange := LanguageData.P['LauncherText'].P['SettingsFormText'].P['LangChange'].Value; Result.SettingsForm.InterfaceScale := LanguageData.P['LauncherText'].P['SettingsFormText'].P['InterfaceScale'].Value; Result.SettingsForm.Behaviour := LanguageData.P['LauncherText'].P['SettingsFormText'].P['Behaviour'].Value; Result.SettingsForm.OnRenderStart := LanguageData.P['LauncherText'].P['SettingsFormText'].P['OnRenderStart'].Value; Result.SettingsForm.DoNothing := LanguageData.P['LauncherText'].P['SettingsFormText'].P['DoNothing'].Value; Result.SettingsForm.MinimizeLauncher := LanguageData.P['LauncherText'].P['SettingsFormText'].P['MinimizeLauncher'].Value; Result.SettingsForm.CloseLauncher := LanguageData.P['LauncherText'].P['SettingsFormText'].P['CloseLauncher'].Value; Result.SettingsForm.HandleAerender := LanguageData.P['LauncherText'].P['SettingsFormText'].P['HandleAerender'].Value; Result.SettingsForm.DeleteTemporary := LanguageData.P['LauncherText'].P['SettingsFormText'].P['DeleteTemporary'].Value; {$ENDREGION} {$REGION ' Import Form Text '} Result.ImportForm.ImportAEProject := LanguageData.P['LauncherText'].P['ImportFormText'].P['ImportAEProject'].Value; Result.ImportForm.ProjectPath := LanguageData.P['LauncherText'].P['ImportFormText'].P['ProjectPath'].Value; Result.ImportForm.Compositions := LanguageData.P['LauncherText'].P['ImportFormText'].P['Compositions'].Value; Result.ImportForm.CompositonProperties := LanguageData.P['LauncherText'].P['ImportFormText'].P['CompositionProperties'].Value; Result.ImportForm.Name := LanguageData.P['LauncherText'].P['ImportFormText'].P['Name'].Value; Result.ImportForm.Resolution := LanguageData.P['LauncherText'].P['ImportFormText'].P['Resolution'].Value; Result.ImportForm.Framerate := LanguageData.P['LauncherText'].P['ImportFormText'].P['Framerate'].Value; Result.ImportForm.RangeStart := LanguageData.P['LauncherText'].P['ImportFormText'].P['RangeStart'].Value; Result.ImportForm.RangeEnd := LanguageData.P['LauncherText'].P['ImportFormText'].P['RangeEnd'].Value; Result.ImportForm.ImportProperties := LanguageData.P['LauncherText'].P['ImportFormText'].P['ImportProperties'].Value; Result.ImportForm.PrepareForSplitRendering := LanguageData.P['LauncherText'].P['ImportFormText'].P['PrepareForSplitRendering'].Value; Result.ImportForm.SelectAll := LanguageData.P['LauncherText'].P['ImportFormText'].P['SelectAll'].Value; Result.ImportForm.DeselectAll := LanguageData.P['LauncherText'].P['ImportFormText'].P['DeselectAll'].Value; Result.ImportForm.Import := LanguageData.P['LauncherText'].P['ImportFormText'].P['Import'].Value; {$ENDREGION} {$REGION ' Output Module Configurator Form Text '} Result.OutputModuleConfiguratorForm.OutputModulePresetConfigurator := LanguageData.P['LauncherText'].P['OutputModuleFormText'].P['OutputModulePresetConfigurator'].Value; Result.OutputModuleConfiguratorForm.OutputModule := LanguageData.P['LauncherText'].P['OutputModuleFormText'].P['OutputModule'].Value; Result.OutputModuleConfiguratorForm.OutputModulePrompt := LanguageData.P['LauncherText'].P['OutputModuleFormText'].P['OutputModulePrompt'].Value; Result.OutputModuleConfiguratorForm.OutputFileNameStructure := LanguageData.P['LauncherText'].P['OutputModuleFormText'].P['OutputFileNameStructure'].Value; Result.OutputModuleConfiguratorForm.OutputFileNamePrompt := LanguageData.P['LauncherText'].P['OutputModuleFormText'].P['OutputFileNamePrompt'].Value; Result.OutputModuleConfiguratorForm.Imported := LanguageData.P['LauncherText'].P['OutputModuleFormText'].P['Imported'].Value; Result.OutputModuleConfiguratorForm.ProjectTab := LanguageData.P['LauncherText'].P['OutputModuleFormText'].P['ProjectTab'].Value; Result.OutputModuleConfiguratorForm.CompositionTab := LanguageData.P['LauncherText'].P['OutputModuleFormText'].P['CompositionTab'].Value; Result.OutputModuleConfiguratorForm.CompositionTimeTab := LanguageData.P['LauncherText'].P['OutputModuleFormText'].P['CompositionTimeTab'].Value; Result.OutputModuleConfiguratorForm.ImageTab := LanguageData.P['LauncherText'].P['OutputModuleFormText'].P['ImageTab'].Value; Result.OutputModuleConfiguratorForm.DateTab := LanguageData.P['LauncherText'].P['OutputModuleFormText'].P['DateTab'].Value; Result.OutputModuleConfiguratorForm.Save := LanguageData.P['LauncherText'].P['OutputModuleFormText'].P['Save'].Value; Result.OutputModuleConfiguratorForm.Cancel := LanguageData.P['LauncherText'].P['OutputModuleFormText'].P['Cancel'].Value; Result.OutputModuleConfiguratorForm.CloseDialog := LanguageData.P['LauncherText'].P['OutputModuleFormText'].P['CloseDialog'].Value; {$ENDREGION} {$REGION ' Rendering Form Text '} Result.RenderingForm.RenderingProgress := LanguageData.P['LauncherText'].P['RenderingFormText'].P['RenderingProgress'].Value; Result.RenderingForm.HandleDisabled := LanguageData.P['LauncherText'].P['RenderingFormText'].P['HandleDisabled'].Value; Result.RenderingForm.QueueIsEmpty := LanguageData.P['LauncherText'].P['RenderingFormText'].P['QueueIsEmpty'].Value; Result.RenderingForm.TotalProgress := LanguageData.P['LauncherText'].P['RenderingFormText'].P['TotalProgress'].Value; Result.RenderingForm.TimeElapsed := LanguageData.P['LauncherText'].P['RenderingFormText'].P['TimeElapsed'].Value; Result.RenderingForm.AbortRendering := LanguageData.P['LauncherText'].P['RenderingFormText'].P['AbortRendering'].Value; Result.RenderingForm.WaitingForAerender := LanguageData.P['LauncherText'].P['RenderingFormText'].P['WaitingForAerender'].Value; Result.RenderingForm.Rendering := LanguageData.P['LauncherText'].P['RenderingFormText'].P['Rendering'].Value; Result.RenderingForm.RenderingError := LanguageData.P['LauncherText'].P['RenderingFormText'].P['RenderingError'].Value; Result.RenderingForm.RenderingFinished := LanguageData.P['LauncherText'].P['RenderingFormText'].P['RenderingFinished'].Value; {$ENDREGION} {$REGION ' About Form Text '} Result.AboutForm.AErenderLauncher := LanguageData.P['LauncherText'].P['AboutFormText'].P['AErenderLauncher'].Value; Result.AboutForm.CreatedBy := LanguageData.P['LauncherText'].P['AboutFormText'].P['CreatedBy'].Value; Result.AboutForm.Description := LanguageData.P['LauncherText'].P['AboutFormText'].P['Description'].Value; Result.AboutForm.FromRussiaWithLove := LanguageData.P['LauncherText'].P['AboutFormText'].P['FromRussiaWithLove'].Value; Result.AboutForm.FFMPEG := LanguageData.P['LauncherText'].P['AboutFormText'].P['FFMPEG'].Value; Result.AboutForm.FFMPEGNotFound := LanguageData.P['LauncherText'].P['AboutFormText'].P['FFMPEGNotFound'].Value; Result.AboutForm.Copyright := LanguageData.P['LauncherText'].P['AboutFormText'].P['Copyright'].Value; {$ENDREGION} {$REGION ' Errors Text '} Result.Errors.MemoryValueInvalid := LanguageData.P['LauncherText'].P['ErrorText'].P['MemoryValueInvalid'].Value; Result.Errors.CacheValueInvalid := LanguageData.P['LauncherText'].P['ErrorText'].P['CacheValueInvalid'].Value; Result.Errors.CalculateFrameError := LanguageData.P['LauncherText'].P['ErrorText'].P['CalculateFrameError'].Value; Result.Errors.CalculateUnknownError := LanguageData.P['LauncherText'].P['ErrorText'].P['CalculateUnknownError'].Value; Result.Errors.ConfigCorrupted := LanguageData.P['LauncherText'].P['ErrorText'].P['ConfigCorrupted'].Value; Result.Errors.aerenderInvalid := LanguageData.P['LauncherText'].P['ErrorText'].P['aerenderInvalid'].Value; Result.Errors.aerenderUndetectable := LanguageData.P['LauncherText'].P['ErrorText'].P['aerenderUndetectable'].Value; Result.Errors.errorsOccured := LanguageData.P['LauncherText'].P['ErrorText'].P['errorsOccured'].Value; Result.Errors.aerenderIsEmpty := LanguageData.P['LauncherText'].P['ErrorText'].P['aerenderIsEmpty'].Value; Result.Errors.projectIsEmpty := LanguageData.P['LauncherText'].P['ErrorText'].P['projectIsEmpty'].Value; Result.Errors.outputIsEmpty := LanguageData.P['LauncherText'].P['ErrorText'].P['outputIsEmpty'].Value; Result.Errors.compositionIsEmpty := LanguageData.P['LauncherText'].P['ErrorText'].P['compositionIsEmpty'].Value; Result.Errors.multiCompIsEmpty := LanguageData.P['LauncherText'].P['ErrorText'].P['multiCompIsEmpty'].Value; Result.Errors.tooManyThreads := LanguageData.P['LauncherText'].P['ErrorText'].P['tooManyThreads'].Value; Result.Errors.isCurrentlyRendering := LanguageData.P['LauncherText'].P['ErrorText'].P['isCurrentlyRendering'].Value; Result.Errors.IncompatibleFile := LanguageData.P['LauncherText'].P['ErrorText'].P['IncompatibleFile'].Value; {$ENDREGION} end; constructor LauncherText.InitFromFile(Path: String); var LanguageString: WideString; LanguageData: TJsonValue; begin try LanguageString := TFile.ReadAllText(Path, TEncoding.UTF8); LanguageData := TJSONObject.ParseJSONValue(LanguageString); Self := ParseJSONLanguage(LanguageData); Self.Result := 0; except on Exception do Self.Result := -1; end; end; constructor LauncherText.InitFromStringList(StringList: TStringList); var LanguageData: TJsonValue; begin try LanguageData := TJSONObject.ParseJSONValue(StringList.Text); Self := ParseJSONLanguage(LanguageData); Self.Result := 0; except on Exception do Self.Result := -1; end; end; constructor LauncherText.InitFromResourceStream(Stream: TResourceStream); var LanguageSource: TStringList; LanguageData: TJsonValue; begin try LanguageSource := TStringList.Create; LanguageSource.LoadFromStream(Stream, TEncoding.UTF8); LanguageData := TJSONObject.ParseJSONValue(LanguageSource.Text); Self := ParseJSONLanguage(LanguageData); Self.Result := 0; except on Exception do Self.Result := -1; end; end; end.
unit BaseFrontForm_Unit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, FrontData_Unit, AdvAppStyler, AdvPanel, AdvPageControl, ExtCtrls, Front_DataBase_Unit, AdvSmoothButton, FrontLog_Unit; type TBaseFrontForm = class(TForm) AdvFormStyler: TAdvFormStyler; protected FLogManager: TLogManager; FFrontBase: TFrontBase; FIsActionRun: Boolean; public procedure AfterConstruction; override; property FrontBase: TFrontBase read FFrontBase write FFrontBase; property LogManager: TLogManager read FLogManager write FLogManager; property IsActionRun: Boolean read FIsActionRun write FIsActionRun; end; var BaseFrontForm: TBaseFrontForm; implementation {$R *.dfm} { TBaseFrontForm } procedure TBaseFrontForm.AfterConstruction; var I : Integer; begin inherited; FIsActionRun := False; Color := FrontData.PanelColorTo; AdvFormStyler.Style := GetFrontStyle; for I := 0 to ComponentCount - 1 do begin if (Components[I] is TAdvPanel) then begin TAdvPanel(Components[I]).Styler := FrontData.FrontPanelStyler; TAdvPanel(Components[I]).Buffered := False; TAdvPanel(Components[I]).BevelOuter := bvNone; end else if (Components[I] is TPanel) then TPanel(Components[I]).Color := FrontData.PanelColorTo else if (Components[I] is TAdvTabSheet) then begin TAdvTabSheet(Components[I]).Color := FrontData.PanelColor; TAdvTabSheet(Components[I]).ColorTo := FrontData.PanelColorTo; end else if (Components[I] is TAdvSmoothButton) then SetButtonStyle(TAdvSmoothButton(Components[I])) else if (Components[I] is TGridPanel) or (Components[I] is TScrollBox) then TPanel(Components[I]).Color := FrontData.PanelColor else if (Components[I] is TAdvPageControl) then TAdvPageControl(Components[I]).TabBackGroundColor := FrontData.PanelColor; end; BorderIcons := []; BorderStyle := bsSingle; end; end.
unit DtDBTimeEdit; {$MODE Delphi} interface uses LCLIntf, LCLType, LMessages, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, MaskEdit, DB, DBCtrls; type { TDtDBTimeEdit } TDtDBTimeEdit = class(TDBEdit) private FDataLink: TFieldDataLink; procedure UpdateData(Sender: TObject); protected procedure KeyDown(var Key: word; Shift: TShiftState); override; procedure KeyPress(var Key: char); override; property CustomEditMask; property EditMask; //events public constructor Create(AOwner: TComponent); override; published end; procedure Register; implementation procedure Register; begin RegisterComponents('Mis Componentes', [TDtDBTimeEdit]); end; procedure TDtDBTimeEdit.UpdateData(Sender: TObject); var s: string; begin if (Text = ' : ') or (Trim(Text) = '') then FDataLink.Field.Value := Null else begin //Si pone 1 solo dígito de la hora, lo coloco en su lugar s:=Text; if (Length(Text)>=2) and (Text[1]<>'') and (Text[2]=#32) then begin s:=Text; s[2]:=s[1]; s[1]:='0'; Text:=s; end; //Completo con ceros si por si lo dejó en blanco Text := StringReplace(Text, ' ', '0', [rfReplaceAll]); ValidateEdit; if Int(FDataLink.Field.AsDateTime) = 0 then FDataLink.Field.AsDateTime := 2 {NullDate} + Frac(StrToTime(Text)) else FDataLink.Field.AsDateTime := Int(FDataLink.Field.AsDateTime) + Frac(StrToTime(Text)); end; end; procedure TDtDBTimeEdit.KeyDown(var Key: word; Shift: TShiftState); begin if (Key = VK_DELETE) or ((Key = VK_INSERT) and (ssShift in Shift)) then begin FDataLink.Edit; if Key = VK_DELETE then begin FDatalink.Field.Value := Null; Key := VK_UNKNOWN; end; end; inherited KeyDown(Key, Shift); end; procedure TDtDBTimeEdit.KeyPress(var Key: char); {begin inherited KeyPress(Key); if (Key in [#32..#255]) and (FDataLink.Field <> nil) and not FDataLink.Field.IsValidChar(Key) then begin Beep; Key := #0; end; case Key of ^H, ^V, ^X, #32..#255: FDataLink.Edit; #27: begin FDataLink.Reset; SelectAll; Key := #0; end; end; end; } var ss: integer; begin // inherited KeyPress(Key); if (Key in [#32..#255]) and (FDataLink.Field <> nil) and not FDataLink.Field.IsValidChar(Key) then begin Beep; Key := #0; end; case Key of ^H, ^V, ^X, #32..#255: FDataLink.Edit; //#27: //begin // FDataLink.Reset; // SelectAll; // Key := #0; //end; end; ss := selstart; if ss <= 7 then sellength := 1; if ss = 0 then begin if not (key in ['0'..'2']) then key := #0; end else if ss = 1 then begin if not ((EditText[1] in ['0'..'1']) and (key in ['0'..'9'])) and not ((EditText[1] = '2') and (key in ['0'..'3'])) then key := #0; end else if ss = 2 then begin if not (key in [':']) then key := ':'; end else if ss = 3 then begin if not (key in ['0'..'5']) then key := #0; end else if ss = 4 then begin if not (key in ['0'..'9']) then key := #0; end else if ss = 5 then begin if not (key in [':']) then key := ':'; end else if ss = 6 then begin if not (key in ['0'..'5']) then key := #0; end else if ss = 7 then begin if not (key in ['0'..'9']) then key := #0; end else if ss >= 8 then begin key := #0; end; if key <> #0 then inherited KeyPress(key) else Beep; end; constructor TDtDBTimeEdit.Create(AOwner: TComponent); begin inherited Create(AOwner); FDataLink := TFieldDataLink(Perform(CM_GETDATALINK, 0, 0)); FDataLink.OnUpdateData := UpdateData; CustomEditMask := True; EditMask := '##:##;1;_'; end; end.
unit users; interface const USERSFILE_ = 'data/users' ; type userTree = ^tree ; userFields = record nick : String [ 8 ] ; password : String [ 8 ] end ; tree = record nick : String [ 8 ] ; password : String [ 8 ] ; low : userTree ; big : userTree end ; usersFile = file of userFields ; function createUserNode ( var newNode: userTree; userData: userFields ): boolean; procedure insertUserNode ( var _tree, _userNode: userTree ); procedure loadUsers ( var users: userTree ); function userExists ( users: userTree; nick: String ): userTree; procedure saveUser ( users: userTree ); procedure showUsers ( users: userTree ); function passwordAccepted ( user: userTree; password: String ): Boolean; procedure deleteUser ( var currentUser: userTree ); implementation procedure openUsersFile ( var _file: usersFile; _fileName: String; var error: Boolean ); begin error := false; assign ( _file, _fileName ); {$I-} reset ( _file ); {$I+} if ( ioResult <> 0 ) then error := true; end; function createUserNode ( var newNode: userTree; userData: userFields ): boolean; begin createUserNode := false; new ( newNode ); if ( newNode <> nil ) then begin createUserNode := true; with newNode^ do begin nick := userData.nick; password := userData.password; big := nil; low := nil; end; end; end; procedure insertUserNode ( var _tree, _userNode: userTree ); begin if ( _tree = nil ) then _tree := _userNode else if ( _tree^.nick <= _userNode^.nick ) then insertUserNode ( _tree^.big, _userNode ) else insertUserNode ( _tree^.low, _userNode ); end; procedure createTreeFromFile ( var _tree: userTree; var _file: usersFile ); var Information :userFields ; userNode :userTree ; begin while not eof ( _file ) do begin read ( _file, Information ); if ( createUserNode ( userNode, Information ) ) then insertUserNode ( _tree, userNode ); end; end; procedure loadUsers ( var users: userTree ); var error : boolean ; usersStored :usersFile ; begin users := nil; openUsersFile ( usersStored, USERSFILE_, error ); if ( error ) then begin close(usersStored); rewrite(usersStored); end; createTreeFromFile ( users, usersStored ); close ( usersStored ); end; function userExists ( users: userTree; nick: String ): userTree; begin if ( users <> nil ) then begin if ( users^.nick < nick ) then userExists := userExists ( users^.big, nick ); if ( users^.nick > nick ) then userExists := userExists ( users^.low, nick ); if ( users^.nick = nick ) then userExists := users; end else userExists := nil; end; procedure saveUserInformationFromTree ( var usersStore: usersFile; var node: userTree ); var newUser :userFields ; begin with newUser do begin nick := node^.nick; password := node^.password; end; write ( usersStore, newUser ); end; procedure getUsersNode ( users: userTree; var usersStore: usersFile ); begin if ( users <> nil ) then begin getUsersNode ( users^.low, usersStore ); saveUserInformationFromTree ( usersStore, users ); getUsersNode ( users^.big, usersStore ); end; end; procedure saveUser ( users: userTree ); var usersStore :usersFile ; error :Boolean ; begin openUsersFile ( usersStore, USERSFILE_, error ); close ( usersStore ); rewrite ( usersStore );{HABÍA UN IF} rewrite ( usersStore ); getUsersNode ( users, usersStore ); end; procedure showUsers ( users: userTree ); begin if ( users <> nil ) then begin showUsers ( users^.low ); writeln ( users^.nick ); showUsers ( users^.big ); end; end; function passwordAccepted ( user: userTree; password: String ): Boolean; begin passwordAccepted := true; if ( user^.password <> password ) then passwordAccepted := false; end; procedure shiftTree ( var currentUser: userTree; direction: String ); begin if ( direction = 'low' ) then begin if ( currentUser^.low^.low = nil ) then begin currentUser^.nick := currentUser^.low^.nick; currentUser^.password := currentUser^.low^.nick; currentUser^.low := nil; end else begin currentUser^.nick := currentUser^.low^.nick; currentUser^.password := currentUser^.low^.nick; shiftTree ( currentUser^.low, direction ); end; end else begin if ( currentUser^.big^.big = nil ) then begin currentUser^.nick := currentUser^.big^.nick; currentUser^.password := currentUser^.big^.nick; currentUser^.big := nil; end else begin currentUser^.nick := currentUser^.big^.nick; currentUser^.password := currentUser^.big^.nick; shiftTree ( currentUser^.big, direction ); end; end; end; procedure deleteUser ( var currentUser: userTree ); begin if ( currentUser <> nil) then if ( currentUser^.low <> nil ) or ( currentUser^.big <> nil ) then if ( currentUser^.low <> nil ) then shiftTree ( currentUser, 'low' ) else shiftTree ( currentUser, 'big' ) else currentUser := nil; end; end.
unit dbCreateStructureTest; interface uses TestFramework, ZConnection, ZDataset, dbTest; type TdbCreateStructureTest = class (TdbTest) protected // подготавливаем данные для тестирования procedure SetUp; override; published procedure CreateDataBase; procedure CreateType; procedure CreateObject; procedure CreateObjectGoodsItem; procedure CreateObjectPartionGoods; procedure CreateObjectGoodsPrint; procedure CreateContainer; procedure CreateObjectCost; procedure CreateFunctionsForIndex; procedure CreateMovement; procedure CreateMovementItem; procedure CreateMovementItemContainer; procedure CreateHistory; procedure CreateProtocol; procedure CreatePeriodClose; procedure CreateLoad; procedure UpdateStructure; // procedure CreateIndexes; // пустой скрипт end; var CreateStructurePath: string = '..\DATABASE\Boutique\STRUCTURE\'; implementation { TdbCreateStructureTest } uses zLibUtil, System.SysUtils; const StructurePath = '..\DATABASE\Boutique\STRUCTURE\'; FunctionsPath = '..\DATABASE\Boutique\FUNCTION\'; UpdateStructurePath = '..\DATABASE\Boutique\UPDATESTRUCTURE\'; procedure TdbCreateStructureTest.CreateContainer; begin ExecFile(StructurePath + 'Container\ContainerDesc.sql', ZQuery); ExecFile(StructurePath + 'Container\Container.sql', ZQuery); ExecFile(StructurePath + 'Container\ContainerLinkObjectDesc.sql', ZQuery); ExecFile(StructurePath + 'Container\ContainerLinkObject.sql', ZQuery); end; procedure TdbCreateStructureTest.CreateDataBase; begin ZConnection.Connected := false; ZConnection.Database := 'postgres'; ZConnection.Connected := true; if FileExists(CreateStructurePath + 'real_DROP_andCreate_Database = YES.txt') then begin try // Если база существует, то сначала надо ее удалить // ExecFile(CreateStructurePath + 'KIllSession.sql', ZQuery); // ExecFile(CreateStructurePath + 'DropDataBase.sql', ZQuery); except end; // ExecFile(CreateStructurePath + 'CreateDataBase.sql', ZQuery); end else raise Exception.Create('Нельзя real_DROP_andCreate_Database '); end; procedure TdbCreateStructureTest.CreateFunctionsForIndex; begin ExecFile(FunctionsPath + 'zfConvert_StringToNumber.sql', ZQuery); end; procedure TdbCreateStructureTest.CreateHistory; begin ExecFile(StructurePath + 'ObjectHistory\ObjectHistoryDesc.sql', ZQuery); ExecFile(StructurePath + 'ObjectHistory\ObjectHistory.sql', ZQuery); ExecFile(StructurePath + 'ObjectHistory\ObjectHistoryStringDesc.sql', ZQuery); ExecFile(StructurePath + 'ObjectHistory\ObjectHistoryString.sql', ZQuery); ExecFile(StructurePath + 'ObjectHistory\ObjectHistoryFloatDesc.sql', ZQuery); ExecFile(StructurePath + 'ObjectHistory\ObjectHistoryFloat.sql', ZQuery); ExecFile(StructurePath + 'ObjectHistory\ObjectHistoryDateDesc.sql', ZQuery); ExecFile(StructurePath + 'ObjectHistory\ObjectHistoryDate.sql', ZQuery); ExecFile(StructurePath + 'ObjectHistory\ObjectHistoryLinkDesc.sql', ZQuery); ExecFile(StructurePath + 'ObjectHistory\ObjectHistoryLink.sql', ZQuery); end; //procedure TdbCreateStructureTest.CreateIndexes; //begin // DirectoryLoad(StructurePath + 'INDEX\'); //end; procedure TdbCreateStructureTest.CreateLoad; begin DirectoryLoad(CreateStructurePath + 'Load\'); end; procedure TdbCreateStructureTest.CreateMovement; begin ExecFile(StructurePath + 'Movement\MovementDesc.sql', ZQuery); ExecFile(StructurePath + 'Movement\Movement.sql', ZQuery); ExecFile(StructurePath + 'Movement\MovementLinkObjectDesc.sql', ZQuery); ExecFile(StructurePath + 'Movement\MovementLinkObject.sql', ZQuery); ExecFile(StructurePath + 'Movement\MovementFloatDesc.sql', ZQuery); ExecFile(StructurePath + 'Movement\MovementFloat.sql', ZQuery); ExecFile(StructurePath + 'Movement\MovementBlobDesc.sql', ZQuery); ExecFile(StructurePath + 'Movement\MovementBlob.sql', ZQuery); ExecFile(StructurePath + 'Movement\MovementBooleanDesc.sql', ZQuery); ExecFile(StructurePath + 'Movement\MovementBoolean.sql', ZQuery); ExecFile(StructurePath + 'Movement\MovementDateDesc.sql', ZQuery); ExecFile(StructurePath + 'Movement\MovementDate.sql', ZQuery); ExecFile(StructurePath + 'Movement\MovementStringDesc.sql', ZQuery); ExecFile(StructurePath + 'Movement\MovementString.sql', ZQuery); ExecFile(StructurePath + 'Movement\MovementLinkMovementDesc.sql', ZQuery); ExecFile(StructurePath + 'Movement\MovementLinkMovement.sql', ZQuery); end; procedure TdbCreateStructureTest.CreateMovementItem; begin ExecFile(StructurePath + 'MovementItem\MovementItemDesc.sql', ZQuery); ExecFile(StructurePath + 'MovementItem\MovementItem.sql', ZQuery); ExecFile(StructurePath + 'MovementItem\MovementItemLinkObjectDesc.sql', ZQuery); ExecFile(StructurePath + 'MovementItem\MovementItemLinkObject.sql', ZQuery); ExecFile(StructurePath + 'MovementItem\MovementItemFloatDesc.sql', ZQuery); ExecFile(StructurePath + 'MovementItem\MovementItemFloat.sql', ZQuery); ExecFile(StructurePath + 'MovementItem\MovementItemBooleanDesc.sql', ZQuery); ExecFile(StructurePath + 'MovementItem\MovementItemBoolean.sql', ZQuery); ExecFile(StructurePath + 'MovementItem\MovementItemDateDesc.sql', ZQuery); ExecFile(StructurePath + 'MovementItem\MovementItemDate.sql', ZQuery); ExecFile(StructurePath + 'MovementItem\MovementItemStringDesc.sql',ZQuery); ExecFile(StructurePath + 'MovementItem\MovementItemString.sql', ZQuery); end; procedure TdbCreateStructureTest.CreateMovementItemContainer; begin ExecFile(StructurePath + 'MovementItemContainer\MovementItemContainerDesc.sql', ZQuery); ExecFile(StructurePath + 'MovementItemContainer\MovementItemContainer.sql', ZQuery); end; procedure TdbCreateStructureTest.CreateObject; begin ExecFile(StructurePath + 'Object\ObjectDesc.sql', ZQuery); ExecFile(StructurePath + 'Object\Object.sql', ZQuery); ExecFile(StructurePath + 'Object\ObjectStringDesc.sql', ZQuery); ExecFile(StructurePath + 'Object\ObjectString.sql', ZQuery); ExecFile(StructurePath + 'Object\ObjectFloatDesc.sql', ZQuery); ExecFile(StructurePath + 'Object\ObjectFloat.sql', ZQuery); ExecFile(StructurePath + 'Object\ObjectDateDesc.sql', ZQuery); ExecFile(StructurePath + 'Object\ObjectDate.sql', ZQuery); ExecFile(StructurePath + 'Object\ObjectBLOBDesc.sql', ZQuery); ExecFile(StructurePath + 'Object\ObjectBLOB.sql', ZQuery); ExecFile(StructurePath + 'Object\ObjectBooleanDesc.sql', ZQuery); ExecFile(StructurePath + 'Object\ObjectBoolean.sql', ZQuery); ExecFile(StructurePath + 'Object\ObjectLinkDesc.sql', ZQuery); ExecFile(StructurePath + 'Object\ObjectLink.sql', ZQuery); end; procedure TdbCreateStructureTest.CreateObjectCost; begin ExecFile(StructurePath + 'ObjectCost\ObjectCostDesc.sql', ZQuery); ExecFile(StructurePath + 'ObjectCost\ObjectCostLinkDesc.sql', ZQuery); ExecFile(StructurePath + 'ObjectCost\ObjectCostLink.sql', ZQuery); ExecFile(StructurePath + 'ObjectCost\ContainerObjectCost.sql', ZQuery); ExecFile(StructurePath + 'ObjectCost\HistoryCost.sql', ZQuery); ExecFile(StructurePath + 'ObjectCost\ObjectCostSEQUENCE.sql', ZQuery); end; procedure TdbCreateStructureTest.CreateObjectGoodsItem; begin ExecFile(StructurePath + 'ObjectGoodsItem - !!!\ObjectGoodsItem.sql', ZQuery); end; procedure TdbCreateStructureTest.CreateObjectPartionGoods; begin ExecFile(StructurePath + 'ObjectPartionGoods - !!!\ObjectPartionGoods.sql', ZQuery); end; procedure TdbCreateStructureTest.CreateObjectGoodsPrint; begin ExecFile(StructurePath + 'ObjectGoodsPrint - !!!\ObjectGoodsPrint.sql', ZQuery); end; procedure TdbCreateStructureTest.CreatePeriodClose; begin ExecFile(StructurePath + 'PeriodClose\PeriodClose.sql', ZQuery); end; procedure TdbCreateStructureTest.CreateProtocol; begin DirectoryLoad(StructurePath + 'Protocol\'); end; procedure TdbCreateStructureTest.CreateType; begin ExecFile(StructurePath + 'Type\CreateType.sql', ZQuery); end; procedure TdbCreateStructureTest.SetUp; begin ZConnection := TConnectionFactory.GetConnection; try ZConnection.Connected := true; except end; ZQuery := TZQuery.Create(nil); ZQuery.Connection := ZConnection; end; procedure TdbCreateStructureTest.UpdateStructure; begin if FileExists(CreateStructurePath + 'real_DROP_andCreate_Database = YES.txt') then DirectoryLoad(UpdateStructurePath) else raise Exception.Create('Нельзя real_UpdateStructure_Database '); end; initialization // TestFramework.RegisterTest('Создание базы', TdbCreateStructureTest.Suite); end.
unit UMathUntitleds; { ClickForms Application } { Bradford Technologies, Inc. } { All Rights Reserved } { Source Code Copyrighted © 1998-2006 by Bradford Technologies, Inc. } interface uses UGlobals, UContainer; // This file handles the generic pages where the user defines the title. // Such as Untitled Exhibits, Untitled Comments, etc. // Each page has only one 1 rountine. It takes the text from the title and // makes it the page title, the form manager title and the title in Table // of Contents. const fmNTComtLtr = 96; //Comment Untitled Letter Size fmNTComtLgl = 97; //Comment Untitled Legal Size fmNTComtWSign = 124; //Comment Untitled With Signature fmNTMapLgl = 114; //Map Untitled Legal Size fmNTMapLtr = 115; //Map Untitled Letter Size fmNTPhoto3X5 = 308; //Photo Untitled 3 x 5 fmNTPhoto4X6 = 318; //Photo Untitled 4 x 6 fmNTPhoto6 = 324; //Photo Untitled 6 photos fmNTPhoto15 = 325; //Photo Untitled 15 photos fmNTPhoto12Lgl = 326; //Photo Untitled 12 on legal size fmNTPhoto12Ltr = 327; //Photo Untitled 12 on letter size fmNTPhotoVert = 328; //Photo Untitled vertical images fmNTExhibit595 = 595; //Exhibit fmNTExhibit596 = 596; //Exhibit fmNTExhibit597 = 597; //Exhibit fmNTExhibit598 = 598; //Exhibit fmNTExhibit725 = 725; //Exhibit w/comments fmNTExhibit726 = 726; //Exhibit w/comments fmNTExhibit727 = 727; //Exhibit w/comments fmNTExhibit728 = 728; //Exhibit w/comments fmNTPhotoVertical3 = 303; //Photo Untitled (3) Vertical fmNTPhotoVertical6 = 339; //Photo Untitled (6) Vertical fmNTPhotoMixed1 = 305; //Photo Untitled Mixed #1 fmNTPhotoMixed2 = 313; //Photo Untitled Mixed #2 fmNTPhotoMixed3 = 315; //Photo Untitled Mixed #3 fmNTPhotoMixed4 = 329; //Photo Untitled Mixed #4 function ProcessForm0096Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; function ProcessForm0097Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; function ProcessForm0124Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; function ProcessForm0114Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; function ProcessForm0115Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; function ProcessForm0308Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; function ProcessForm0318Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; function ProcessForm0324Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; function ProcessForm0325Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; function ProcessForm0326Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; function ProcessForm0327Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; function ProcessForm0328Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; function ProcessForm0595Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; function ProcessForm0596Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; function ProcessForm0597Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; function ProcessForm0598Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; function ProcessForm0725Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; function ProcessForm0726Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; function ProcessForm0727Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; function ProcessForm0728Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; function ProcessForm0303Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; function ProcessForm0339Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; function ProcessForm0305Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; function ProcessForm0313Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; function ProcessForm0315Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; function ProcessForm0329Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; implementation uses Dialogs, SysUtils, Math, UUtil1, UStatus, UBase, UForm, UPage, UCell, UMath, UStrings; function ProcessForm0096Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; begin if Cmd > 0 then repeat case Cmd of 1: cmd := SetPageTitleBarName(doc, CX); else Cmd := 0; end; until Cmd = 0; result := 0; end; function ProcessForm0097Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; begin if Cmd > 0 then repeat case Cmd of 1: cmd := SetPageTitleBarName(doc, CX); else Cmd := 0; end; until Cmd = 0; result := 0; end; function ProcessForm0124Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; begin if Cmd > 0 then repeat case Cmd of 1: cmd := SetPageTitleBarName(doc, CX); else Cmd := 0; end; until Cmd = 0; result := 0; end; function ProcessForm0114Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; begin if Cmd > 0 then repeat case Cmd of 1: cmd := SetPageTitleBarName(doc, CX); else Cmd := 0; end; until Cmd = 0; result := 0; end; function ProcessForm0115Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; begin if Cmd > 0 then repeat case Cmd of 1: cmd := SetPageTitleBarName(doc, CX); else Cmd := 0; end; until Cmd = 0; result := 0; end; function ProcessForm0308Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; begin if Cmd > 0 then repeat case Cmd of 1: cmd := SetPageTitleBarName(doc, CX); else Cmd := 0; end; until Cmd = 0; result := 0; end; function ProcessForm0318Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; begin if Cmd > 0 then repeat case Cmd of 1: cmd := SetPageTitleBarName(doc, CX); else Cmd := 0; end; until Cmd = 0; result := 0; end; function ProcessForm0324Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; begin if Cmd > 0 then repeat case Cmd of 1: cmd := SetPageTitleBarName(doc, CX); else Cmd := 0; end; until Cmd = 0; result := 0; end; function ProcessForm0325Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; begin if Cmd > 0 then repeat case Cmd of 1: cmd := SetPageTitleBarName(doc, CX); else Cmd := 0; end; until Cmd = 0; result := 0; end; function ProcessForm0326Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; begin if Cmd > 0 then repeat case Cmd of 1: cmd := SetPageTitleBarName(doc, CX); else Cmd := 0; end; until Cmd = 0; result := 0; end; function ProcessForm0327Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; begin if Cmd > 0 then repeat case Cmd of 1: cmd := SetPageTitleBarName(doc, CX); else Cmd := 0; end; until Cmd = 0; result := 0; end; function ProcessForm0328Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; begin if Cmd > 0 then repeat case Cmd of 1: cmd := SetPageTitleBarName(doc, CX); else Cmd := 0; end; until Cmd = 0; result := 0; end; function ProcessForm0595Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; begin if Cmd > 0 then repeat case Cmd of 1: cmd := SetPageTitleBarName(doc, CX); else Cmd := 0; end; until Cmd = 0; result := 0; end; function ProcessForm0596Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; begin if Cmd > 0 then repeat case Cmd of 1: cmd := SetPageTitleBarName(doc, CX); else Cmd := 0; end; until Cmd = 0; result := 0; end; function ProcessForm0597Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; begin if Cmd > 0 then repeat case Cmd of 1: cmd := SetPageTitleBarName(doc, CX); else Cmd := 0; end; until Cmd = 0; result := 0; end; function ProcessForm0598Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; begin if Cmd > 0 then repeat case Cmd of 1: cmd := SetPageTitleBarName(doc, CX); else Cmd := 0; end; until Cmd = 0; result := 0; end; function ProcessForm0725Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; begin if Cmd > 0 then repeat case Cmd of 1: cmd := SetPageTitleBarName(doc, CX); else Cmd := 0; end; until Cmd = 0; result := 0; end; function ProcessForm0726Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; begin if Cmd > 0 then repeat case Cmd of 1: cmd := SetPageTitleBarName(doc, CX); else Cmd := 0; end; until Cmd = 0; result := 0; end; function ProcessForm0727Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; begin if Cmd > 0 then repeat case Cmd of 1: cmd := SetPageTitleBarName(doc, CX); else Cmd := 0; end; until Cmd = 0; result := 0; end; function ProcessForm0728Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; begin if Cmd > 0 then repeat case Cmd of 1: cmd := SetPageTitleBarName(doc, CX); else Cmd := 0; end; until Cmd = 0; result := 0; end; function ProcessForm0303Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; begin if Cmd > 0 then repeat case Cmd of 1: cmd := SetPageTitleBarName(doc, CX); else Cmd := 0; end; until Cmd = 0; result := 0; end; function ProcessForm0339Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; begin if Cmd > 0 then repeat case Cmd of 1: cmd := SetPageTitleBarName(doc, CX); else Cmd := 0; end; until Cmd = 0; result := 0; end; function ProcessForm0305Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; begin if Cmd > 0 then repeat case Cmd of 1: cmd := SetPageTitleBarName(doc, CX); else Cmd := 0; end; until Cmd = 0; result := 0; end; function ProcessForm0313Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; begin if Cmd > 0 then repeat case Cmd of 1: cmd := SetPageTitleBarName(doc, CX); else Cmd := 0; end; until Cmd = 0; result := 0; end; function ProcessForm0315Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; begin if Cmd > 0 then repeat case Cmd of 1: cmd := SetPageTitleBarName(doc, CX); else Cmd := 0; end; until Cmd = 0; result := 0; end; function ProcessForm0329Math(doc: TContainer; Cmd: Integer; CX: CellUID): Integer; begin if Cmd > 0 then repeat case Cmd of 1: cmd := SetPageTitleBarName(doc, CX); else Cmd := 0; end; until Cmd = 0; result := 0; end; end.
unit fRecoveringConnection; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, 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.PG, FireDAC.Phys.PGDef, FireDAC.VCLUI.Wait, Data.DB, FireDAC.Comp.Client, Vcl.ExtCtrls, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Phys.FB, FireDAC.Phys.FBDef; type TFrmRecoveringConnection = class(TForm) memLog: TMemo; Connection: TFDConnection; panTest: TPanel; chcAutoReconnect: TCheckBox; btnPing: TButton; panConnection: TPanel; btnConnect: TButton; btnDisconnect: TButton; procedure btnConnectClick(Sender: TObject); procedure btnDisconnectClick(Sender: TObject); procedure ConnectionAfterConnect(Sender: TObject); procedure ConnectionAfterDisconnect(Sender: TObject); procedure ConnectionLost(Sender: TObject); procedure ConnectionRestored(Sender: TObject); procedure ConnectionRecover(ASender, AInitiator: TObject; AException: Exception; var AAction: TFDPhysConnectionRecoverAction); procedure btnPingClick(Sender: TObject); procedure ConnectionBeforeConnect(Sender: TObject); private procedure SetLog(ALog: String); { Private declarations } public { Public declarations } end; var FrmRecoveringConnection: TFrmRecoveringConnection; implementation {$R *.dfm} procedure TFrmRecoveringConnection.btnConnectClick(Sender: TObject); begin Connection.Connected := True; end; procedure TFrmRecoveringConnection.btnDisconnectClick(Sender: TObject); begin Connection.Connected := False; end; procedure TFrmRecoveringConnection.btnPingClick(Sender: TObject); begin SetLog('Ping Iniciado'); Connection.Ping; SetLog('Ping Finalizado'); SetLog(EmptyStr); end; procedure TFrmRecoveringConnection.ConnectionBeforeConnect(Sender: TObject); begin Connection.ResourceOptions.AutoReconnect := chcAutoReconnect.Checked; end; procedure TFrmRecoveringConnection.ConnectionAfterConnect(Sender: TObject); begin SetLog('Connected'); end; procedure TFrmRecoveringConnection.ConnectionAfterDisconnect(Sender: TObject); begin SetLog('Disconnected'); end; procedure TFrmRecoveringConnection.ConnectionLost(Sender: TObject); begin SetLog('Connection Losted'); end; procedure TFrmRecoveringConnection.ConnectionRecover(ASender, AInitiator: TObject; AException: Exception; var AAction: TFDPhysConnectionRecoverAction); begin SetLog('Connection Recovering'); end; procedure TFrmRecoveringConnection.ConnectionRestored(Sender: TObject); begin SetLog('Connection Restored'); end; procedure TFrmRecoveringConnection.SetLog(ALog: String); var Line: String; begin if ALog <> EmptyStr then Line := DateTimeToStr(Now) + ' - '; memLog.Lines.Add(Line + ALog); end; end.
unit mathutils; interface uses types; function diff (const a,b:TPoint) :TPoint; function sum (const a,b:TPoint) :TPoint; function vector (const a,b:TPoint) :TPoint; function mult (const a:TPoint; x:Single):TPoint; function dot(const a,b:TPoint) :Single; function cross(const a,b:TPoint) :Single; function rotate(const a:TPoint; angle:Single):TPoint; function average(const rect:TRect):TPoint; implementation function diff (const a,b:TPoint) :TPoint; begin Result:=Point(a.x-b.x,a.y-b.y); end; function sum (const a,b:TPoint) :TPoint; begin Result:=Point(a.x+b.x,a.y+b.y); end; function vector (const a,b:TPoint) :TPoint; begin result:=diff(b,a); end; function mult (const a:TPoint; x:Single):TPoint; begin Result:= Point(Round(a.x*x),Round(a.y*x)); end; function dot(const a,b:TPoint) :Single; begin result:=a.x*b.x+a.y*b.y; end; function cross(const a,b:TPoint) :Single; begin Result:=a.x*b.y-a.y*b.x; end; function rotate(const a:TPoint; angle:Single):TPoint; begin angle:= angle/180*pi; result.x:= Round(a.x*cos(-angle)-a.y*sin(-angle)); result.y:= Round(a.x*sin(-angle)+a.y*cos(-angle)); end; function average(const rect:TRect):TPoint; begin Result:=Point((rect.left+rect.right)div 2, (rect.top+rect.bottom)div 2) end; end.
unit ClientesForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, Vcl.ComCtrls, ClienteIntf, ClienteMVPIntf, Cliente, ClientePresenter, Generics.Collections, ClienteM, System.UITypes, Utils; type TFormClientes = class(TForm, IClienteView) Label1: TLabel; edNome: TEdit; btAdicionar: TBitBtn; Label2: TLabel; lvClientes: TListView; Label3: TLabel; Label4: TLabel; procedure btAdicionarClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure lvClientesKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure lvClientesDblClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure lvClientesData(Sender: TObject; Item: TListItem); procedure FormShow(Sender: TObject); private { Private declarations } FCliente: TCliente; FClientes: TList<TCliente>; FPresenter: Pointer; Estado: TEstados; procedure ListarClientes; procedure AtualizaBtn; function NomePreenchido: Boolean; protected function GetCliente: TCliente; procedure SetCliente(Value: TCliente); function GetPresenter: IClientePresenter; procedure SetPresenter(const Value: IClientePresenter); public { Public declarations } property Cliente: TCliente read GetCliente write SetCliente; property Presenter: IClientePresenter read GetPresenter write SetPresenter; function ShowView: TModalResult; end; var FormClientes: TFormClientes; implementation {$R *.dfm} { TfrmClientes } procedure TFormClientes.AtualizaBtn; begin if (Inserindo in Estado) then btAdicionar.Caption := 'Adicionar' else btAdicionar.Caption := 'Atualizar'; end; procedure TFormClientes.btAdicionarClick(Sender: TObject); begin if NomePreenchido then begin if (Inserindo in Estado) then begin FCliente := TCliente.Create; Cliente.Nome := Trim(edNome.Text); Presenter.Add; end else begin Cliente.Nome := Trim(edNome.Text); Presenter.Update; end; ListarClientes; Estado := [Inserindo]; end; edNome.Text := ''; edNome.SetFocus; AtualizaBtn; end; procedure TFormClientes.FormCreate(Sender: TObject); begin Estado := [Inserindo]; FCliente := TCliente.Create; end; procedure TFormClientes.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Key = VK_RETURN) then begin Key := 0; SelectNext(ActiveControl, True, True); end else if (Key = VK_ESCAPE) then Close; end; procedure TFormClientes.FormShow(Sender: TObject); begin ListarClientes; end; function TFormClientes.GetCliente: TCliente; begin Result := FCliente; end; function TFormClientes.GetPresenter: IClientePresenter; begin Result := IClientePresenter(FPresenter); end; procedure TFormClientes.ListarClientes; begin FClientes := Presenter.ListAll; lvClientes.Items.Count := FClientes.Count; end; procedure TFormClientes.SetCliente(Value: TCliente); begin FCliente := Value; end; procedure TFormClientes.SetPresenter(const Value: IClientePresenter); begin FPresenter := Pointer(Value); end; function TFormClientes.ShowView: TModalResult; begin Result := Self.ShowModal; end; procedure TFormClientes.lvClientesData(Sender: TObject; Item: TListItem); var Cli: TCliente; begin Cli := FClientes[Item.Index]; Item.Caption := Cli.Id.ToString; Item.SubItems.Add(Cli.Nome); end; procedure TFormClientes.lvClientesDblClick(Sender: TObject); var Cli: TCliente; begin if (lvClientes.Items.Count = 0) then Exit; Cli := TCliente.Create; Cli.Id := StrToInt(lvClientes.Items[lvClientes.ItemIndex].Caption); Cli.Nome := lvClientes.Items[lvClientes.ItemIndex].SubItems[0]; Cliente := Cli; Presenter.Get; edNome.Text := Cliente.Nome; Estado := [Editando]; AtualizaBtn; end; procedure TFormClientes.lvClientesKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var Cli: TCliente; begin if ((ssCtrl in Shift) and (Key = VK_DELETE)) then if (MessageDlg('Confirma a exclusão?', mtConfirmation, [mbYes, mbNo], 0) = mrYes) then begin Cli := TCliente.Create; Cli.Id := StrToInt(lvClientes.Items[lvClientes.ItemIndex].Caption); Cliente := Cli; Presenter.Delete; ListarClientes; end; end; function TFormClientes.NomePreenchido: Boolean; begin Result := False; if Length(Trim(edNome.Text)) < 3 then begin MessageDlg('O Nome precisa ter mais de 3 caracteres.', mtWarning, [mbOk], 0); Exit; end; Result := True; end; end.
unit DUnitX.Tests.CategoryParser; interface uses DUnitX.TestFrameWork, DUnitX.Filters, DUnitX.CategoryExpression; type [TestFixture] TCategoryParseTests = class public [Test] procedure EmptyStringReturnsEmptyFilter; [Test] procedure CanParseSimpleCategory; [Test] procedure CanParseCompoundCategory; [Test] procedure CanParseExcludedCategories; [Test] procedure CanParseMultipleCategoriesWithAnd; [Test] procedure CanParseMultipleAlternatives; [Test] procedure PrecedenceTest; [Test] procedure PrecedenceTestWithParentheses; [Test] procedure OrAndMinusCombined; [Test] procedure PlusAndMinusCombined; end; implementation { TCategoryParseTests } procedure TCategoryParseTests.CanParseCompoundCategory; var filter : ITestFilter; catFilter : ICategoryFilter; begin filter := TCategoryExpression.CreateFilter('One , Two; Three,Four'); catFilter := filter as ICategoryFilter; Assert.AreEqual(catFilter.Categories[0],'One'); Assert.AreEqual(catFilter.Categories[1],'Two'); Assert.AreEqual(catFilter.Categories[2],'Three'); Assert.AreEqual(catFilter.Categories[3],'Four'); end; procedure TCategoryParseTests.CanParseExcludedCategories; var filter : ITestFilter; catFilter : ICategoryFilter; notFilter : INotFilter; begin filter := TCategoryExpression.CreateFilter('-One,Two,Three'); notFilter := filter as INotFilter; Assert.IsNotNull(notFilter); catFilter := notFilter.BaseFilter as ICategoryFilter; Assert.IsNotNull(catFilter); Assert.AreEqual(catFilter.Categories[0],'One'); Assert.AreEqual(catFilter.Categories[1],'Two'); Assert.AreEqual(catFilter.Categories[2],'Three'); end; procedure TCategoryParseTests.CanParseMultipleAlternatives; var filter : ITestFilter; orFilter : IOrFilter; catFilter : ICategoryFilter; begin filter := TCategoryExpression.CreateFilter('One|Two|Three'); orFilter := filter as IOrFilter; Assert.IsNotNull(orFilter); Assert.AreEqual(orFilter.Filters.Count,3); catFilter := orFilter.Filters[0] as ICategoryFilter; Assert.IsNotNull(catFilter); Assert.AreEqual(catFilter.Categories[0],'One'); catFilter := orFilter.Filters[1] as ICategoryFilter; Assert.IsNotNull(catFilter); Assert.AreEqual(catFilter.Categories[0],'Two'); catFilter := orFilter.Filters[2] as ICategoryFilter; Assert.IsNotNull(catFilter); Assert.AreEqual(catFilter.Categories[0],'Three'); end; procedure TCategoryParseTests.CanParseMultipleCategoriesWithAnd; var filter : ITestFilter; catFilter : ICategoryFilter; andFilter : IAndFilter; begin filter := TCategoryExpression.CreateFilter('One + Two+Three'); andFilter := filter as IAndFilter; Assert.IsNotNull(andFilter); Assert.AreEqual(andFilter.Filters.Count,3); catFilter := andFilter.Filters[0] as ICategoryFilter; Assert.IsNotNull(catFilter); Assert.AreEqual(catFilter.Categories[0],'One'); catFilter := andFilter.Filters[1] as ICategoryFilter; Assert.IsNotNull(catFilter); Assert.AreEqual(catFilter.Categories[0],'Two'); catFilter := andFilter.Filters[2] as ICategoryFilter; Assert.IsNotNull(catFilter); Assert.AreEqual(catFilter.Categories[0],'Three'); end; procedure TCategoryParseTests.CanParseSimpleCategory; var filter : ITestFilter; catFilter : ICategoryFilter; begin filter := TCategoryExpression.CreateFilter('Data'); catFilter := filter as ICategoryFilter; Assert.AreEqual(catFilter.Categories[0],'Data'); end; procedure TCategoryParseTests.EmptyStringReturnsEmptyFilter; var filter : ITestFilter; begin filter := TCategoryExpression.CreateFilter(''); Assert.IsNotNull(filter); Assert.IsTrue(filter.IsEmpty); end; procedure TCategoryParseTests.OrAndMinusCombined; var filter : ITestFilter; orFilter : IOrFilter; andFilter : IAndFilter; begin filter := TCategoryExpression.CreateFilter('A|B-C-D|E'); orFilter := filter as IOrFilter; Assert.IsNotNull(orFilter); Assert.AreEqual(orFilter.Filters.Count,3); andFilter := orFilter.Filters[1] as IAndFilter; Assert.IsNotNull(andFilter); Assert.AreEqual(andFilter.Filters.Count,3); Assert.Implements<ICategoryFilter>(andFilter.Filters[0]); Assert.Implements<INotFilter>(andFilter.Filters[1]); Assert.Implements<INotFilter>(andFilter.Filters[2]); end; procedure TCategoryParseTests.PlusAndMinusCombined; var filter : ITestFilter; andFilter : IAndFilter; begin filter := TCategoryExpression.CreateFilter('A+B-C-D+E'); andFilter := filter as IAndFilter; Assert.IsNotNull(andFilter); Assert.AreEqual(andFilter.Filters.Count,5); Assert.Implements<ICategoryFilter>(andFilter.Filters[0]); Assert.Implements<ICategoryFilter>(andFilter.Filters[1]); Assert.Implements<INotFilter>(andFilter.Filters[2]); Assert.Implements<INotFilter>(andFilter.Filters[3]); Assert.Implements<ICategoryFilter>(andFilter.Filters[4]); end; procedure TCategoryParseTests.PrecedenceTest; var filter : ITestFilter; orFilter : IOrFilter; andFilter : IAndFilter; catFilter : ICategoryFilter; notFilter : INotFilter; begin filter := TCategoryExpression.CreateFilter('A + B | C + -D,E,F'); orFilter := filter as IorFilter; Assert.IsNotNull(orFilter); andFilter := orFilter.Filters[0] as IAndFilter; Assert.IsNotNull(andFilter); catFilter := andFilter.Filters[0] as ICategoryFilter; Assert.AreEqual(catFilter.Categories[0],'A'); catFilter := andFilter.Filters[1] as ICategoryFilter; Assert.AreEqual(catFilter.Categories[0],'B'); andFilter := orFilter.Filters[1] as IAndFilter; Assert.IsNotNull(andFilter); catFilter := andFilter.Filters[0] as ICategoryFilter; Assert.AreEqual(catFilter.Categories[0],'C'); notFilter := andFilter.Filters[1] as INotFilter; Assert.IsNotNull(notFilter); catFilter := notFilter.BaseFilter as ICategoryFilter; Assert.IsNotNull(catFilter); Assert.AreEqual(catFilter.Categories[0],'D'); Assert.AreEqual(catFilter.Categories[1],'E'); Assert.AreEqual(catFilter.Categories[2],'F'); end; procedure TCategoryParseTests.PrecedenceTestWithParentheses; var filter : ITestFilter; orFilter : IOrFilter; andFilter : IAndFilter; catFilter : ICategoryFilter; notFilter : INotFilter; begin filter := TCategoryExpression.CreateFilter('A + (B | C) - D,E,F'); andFilter := filter as IAndFilter; Assert.IsNotNull(andFilter); Assert.AreEqual(andFilter.Filters.Count,3); catFilter := andFilter.Filters[0] as ICategoryFilter; Assert.AreEqual(catFilter.Categories[0],'A'); orFilter := andFilter.Filters[1] as IOrFilter; Assert.IsNotNull(orFilter); catFilter := orFilter.Filters[0] as ICategoryFilter; Assert.AreEqual(catFilter.Categories[0],'B'); catFilter := orFilter.Filters[1] as ICategoryFilter; Assert.AreEqual(catFilter.Categories[0],'C'); notFilter := andFilter.Filters[2] as INotFilter; Assert.IsNotNull(notFilter); catFilter := notFilter.BaseFilter as ICategoryFilter; Assert.AreEqual(catFilter.Categories[0],'D'); Assert.AreEqual(catFilter.Categories[1],'E'); Assert.AreEqual(catFilter.Categories[2],'F'); end; initialization TDUnitX.RegisterTestFixture(TCategoryParseTests); end.
{ Структура данных "Запись адресной книги". Поля записи: Name - Имя Phone - Телефон CelluarPhone - Сотовый телефон BirthDate - Дата рождения Email - Адрес электронной почты ICQ - Номер ICQ } type AddressBookEntry = record Name : String[80]; { Имя } Phone : String[80]; { Телефон } CelluarPhone : String[80]; { Сотовый телефон } BirthDate : TDateTime; { Дата рождения } Email : String[80]; { Адрес электронной почты } ICQ : Integer; { Номер ICQ } end;
{ Copyright (C) 2012-2013 Matthias Bolte <matthias@tinkerforge.com> Redistribution and use in source and binary forms of this file, with or without modification, are permitted. See the Creative Commons Zero (CC0 1.0) License for more details. } unit Device; {$ifdef FPC}{$mode OBJFPC}{$H+}{$endif} interface uses {$ifdef UNIX}CThreads,{$endif} SyncObjs, SysUtils, Base58, BlockingQueue, LEConverter, DeviceBase; const DEVICE_RESPONSE_EXPECTED_INVALID_FUNCTION_ID = 0; DEVICE_RESPONSE_EXPECTED_ALWAYS_TRUE = 1; { Getter } DEVICE_RESPONSE_EXPECTED_ALWAYS_FALSE = 2; { Callback } DEVICE_RESPONSE_EXPECTED_TRUE = 3; { Setter } DEVICE_RESPONSE_EXPECTED_FALSE = 4; { Setter, default } type { TDevice } TCallbackWrapper = procedure(const packet: TByteArray) of object; TVersionNumber = array [0..2] of byte; TDevice = class(TDeviceBase) private requestMutex: TCriticalSection; public uid_: longword; ipcon: TObject; apiVersion: TVersionNumber; expectedResponseFunctionID: byte; { protected by requestMutex } expectedResponseSequenceNumber: byte; { protected by requestMutex } responseQueue: TBlockingQueue; responseExpected: array [0..255] of byte; callbackWrappers: array [0..255] of TCallbackWrapper; /// <summary> /// Creates the device objectwith the unique device ID *uid* and adds /// it to the IPConnection *ipcon*. /// </summary> constructor Create(const uid__: string; ipcon_: TObject); /// <summary> /// Removes the device object from its IPConnection and destroys it. /// The device object cannot be used anymore afterwards. /// </summary> destructor Destroy; override; /// <summary> /// Returns the API version (major, minor, revision) of the bindings for /// this device. /// </summary> function GetAPIVersion: TVersionNumber; virtual; /// <summary> /// Returns the response expected flag for the function specified by the /// *functionId* parameter. It is *true* if the function is expected to /// send a response, *false* otherwise. /// /// For getter functions this is enabled by default and cannot be disabled, /// because those functions will always send a response. For callback /// configuration functions it is enabled by default too, but can be /// disabled via the setResponseExpected function. For setter functions it /// is disabled by default and can be enabled. /// /// Enabling the response expected flag for a setter function allows to /// detect timeouts and other error conditions calls of this setter as /// well. The device will then send a response for this purpose. If this /// flag is disabled for a setter function then no response is send and /// errors are silently ignored, because they cannot be detected. /// </summary> function GetResponseExpected(const functionId: byte): boolean; virtual; /// <summary> /// Changes the response expected flag of the function specified by /// the function ID parameter. This flag can only be changed for setter /// (default value: *false*) and callback configuration functions /// (default value: *true*). For getter functions it is always enabled /// and callbacks it is always disabled. /// /// Enabling the response expected flag for a setter function allows to /// detect timeouts and other error conditions calls of this setter as /// well. The device will then send a response for this purpose. If this /// flag is disabled for a setter function then no response is send and /// errors are silently ignored, because they cannot be detected. /// </summary> procedure SetResponseExpected(const functionId: byte; const responseExpected_: boolean); virtual; /// <summary> /// Changes the response expected flag for all setter and callback /// configuration functions of this device at once. /// </summary> procedure SetResponseExpectedAll(const responseExpected_: boolean); virtual; procedure GetIdentity(out uid: string; out connectedUid: string; out position: char; out hardwareVersion: TVersionNumber; out firmwareVersion: TVersionNumber; out deviceIdentifier: word); virtual; abstract; { Internal } function SendRequest(const request: TByteArray): TByteArray; end; { TDeviceTable } TUIDArray = array of longword; TDeviceArray = array of TDevice; TDeviceTable = class private mutex: TCriticalSection; uids: TUIDArray; devices: TDeviceArray; public constructor Create; destructor Destroy; override; procedure Insert(const uid: longword; const device: TDevice); procedure Remove(const uid: longword); function Get(const uid: longword): TDevice; end; implementation uses IPConnection; { TDevice } constructor TDevice.Create(const uid__: string; ipcon_: TObject); var longUid: uint64; value1, value2, i: longint; begin inherited Create; longUid := Base58Decode(uid__); if (longUid > $FFFFFFFF) then begin { Convert from 64bit to 32bit } value1 := longUid and $FFFFFFFF; value2 := longword((longUid shr 32) and $FFFFFFFF); uid_ := (value1 and $00000FFF); uid_ := uid_ or ((value1 and longword($0F000000)) shr 12); uid_ := uid_ or ((value2 and longword($0000003F)) shl 16); uid_ := uid_ or ((value2 and longword($000F0000)) shl 6); uid_ := uid_ or ((value2 and longword($3F000000)) shl 2); end else begin uid_ := longUid and $FFFFFFFF; end; ipcon := ipcon_; apiVersion[0] := 0; apiVersion[1] := 0; apiVersion[2] := 0; expectedResponseFunctionID := 0; expectedResponseSequenceNumber := 0; requestMutex := TCriticalSection.Create; responseQueue := TBlockingQueue.Create; for i := 0 to Length(responseExpected) - 1 do begin responseExpected[i] := DEVICE_RESPONSE_EXPECTED_INVALID_FUNCTION_ID; end; responseExpected[IPCON_FUNCTION_ENUMERATE] := DEVICE_RESPONSE_EXPECTED_ALWAYS_FALSE; responseExpected[IPCON_CALLBACK_ENUMERATE] := DEVICE_RESPONSE_EXPECTED_ALWAYS_FALSE; (ipcon as TIPConnection).devices.Insert(uid_, self); end; destructor TDevice.Destroy; begin (ipcon as TIPConnection).devices.Remove(uid_); requestMutex.Destroy; responseQueue.Destroy; inherited Destroy; end; function TDevice.GetAPIVersion: TVersionNumber; begin result := apiVersion; end; function TDevice.GetResponseExpected(const functionID: byte): boolean; var flag: byte; begin flag := responseExpected[functionID]; if (flag = DEVICE_RESPONSE_EXPECTED_INVALID_FUNCTION_ID) then begin raise Exception.Create('Invalid function ID ' + IntToStr(functionID)); end; if ((flag = DEVICE_RESPONSE_EXPECTED_ALWAYS_TRUE) or (flag = DEVICE_RESPONSE_EXPECTED_TRUE)) then begin result := true; end else begin result := false; end; end; procedure TDevice.SetResponseExpected(const functionID: byte; const responseExpected_: boolean); var flag: byte; begin flag := responseExpected[functionID]; if (flag = DEVICE_RESPONSE_EXPECTED_INVALID_FUNCTION_ID) then begin raise Exception.Create('Invalid function ID ' + IntToStr(functionID)); end; if ((flag = DEVICE_RESPONSE_EXPECTED_ALWAYS_TRUE) or (flag = DEVICE_RESPONSE_EXPECTED_ALWAYS_FALSE)) then begin raise Exception.Create('Response Expected flag cannot be changed for function ID ' + IntToStr(functionID)); end; if (responseExpected_) then begin responseExpected[functionID] := DEVICE_RESPONSE_EXPECTED_TRUE; end else begin responseExpected[functionID] := DEVICE_RESPONSE_EXPECTED_FALSE; end; end; procedure TDevice.SetResponseExpectedAll(const responseExpected_: boolean); var flag: byte; i: longint; begin if (responseExpected_) then begin flag := DEVICE_RESPONSE_EXPECTED_TRUE; end else begin flag := DEVICE_RESPONSE_EXPECTED_FALSE; end; for i := 0 to Length(responseExpected) - 1 do begin if ((responseExpected[i] = DEVICE_RESPONSE_EXPECTED_TRUE) or (responseExpected[i] = DEVICE_RESPONSE_EXPECTED_FALSE)) then begin responseExpected[i] := flag; end; end; end; function TDevice.SendRequest(const request: TByteArray): TByteArray; var ipcon_: TIPConnection; kind, errorCode, functionID: byte; begin SetLength(result, 0); ipcon_ := ipcon as TIPConnection; if (GetResponseExpectedFromData(request)) then begin functionID := GetFunctionIDFromData(request); requestMutex.Acquire; try expectedResponseFunctionID := functionID; expectedResponseSequenceNumber := GetSequenceNumberFromData(request); try ipcon_.SendRequest(request); while true do begin if (not responseQueue.Dequeue(kind, result, ipcon_.timeout)) then begin raise ETimeoutException.Create('Did not receive response in time for function ID ' + IntToStr(functionID)); end; if ((expectedResponseFunctionID = GetFunctionIDFromData(result)) and (expectedResponseSequenceNumber = GetSequenceNumberFromData(result))) then begin { Ignore old responses that arrived after the timeout expired, but before setting expectedResponseFunctionID and expectedResponseSequenceNumber back to 0 } break; end; end; finally expectedResponseFunctionID := 0; expectedResponseSequenceNumber := 0; end; finally requestMutex.Release; end; errorCode := GetErrorCodeFromData(result); if (errorCode = 0) then begin { No error } end else begin if (errorCode = 1) then begin raise ENotSupportedException.Create('Got invalid parameter for function ID ' + IntToStr(functionID)); end else if (errorCode = 2) then begin raise ENotSupportedException.Create('Function ID ' + IntToStr(functionID) + ' is not supported'); end else begin raise ENotSupportedException.Create('Function ID ' + IntToStr(functionID) + ' returned an unknown error'); end; end; end else begin ipcon_.SendRequest(request); end; end; { TDeviceTable } constructor TDeviceTable.Create; begin mutex := TCriticalSection.Create; SetLength(uids, 0); SetLength(devices, 0); end; destructor TDeviceTable.Destroy; begin SetLength(uids, 0); SetLength(devices, 0); mutex.Destroy; inherited Destroy; end; procedure TDeviceTable.Insert(const uid: longword; const device: TDevice); var len: longint; i: longint; begin len := Length(uids); for i := 0 to len - 1 do begin if (uids[i] = uid) then begin devices[i] := device; exit; end; end; SetLength(uids, len + 1); SetLength(devices, len + 1); uids[len] := uid; devices[len] := device; end; procedure TDeviceTable.Remove(const uid: longword); var len: longint; i: longint; k: longint; begin len := Length(uids); for i := 0 to len - 1 do begin if (uids[i] = uid) then begin for k := i + 1 to len - 1 do begin uids[k - 1] := uids[k]; devices[k - 1] := devices[k]; end; SetLength(uids, len - 1); SetLength(devices, len - 1); exit; end; end; end; function TDeviceTable.Get(const uid: longword): TDevice; var len: longint; i: longint; begin result := nil; len := Length(uids); for i := 0 to len - 1 do begin if (uids[i] = uid) then begin result := devices[i]; exit; end; end; end; end.
unit KM_GUIMenuReplays; {$I KaM_Remake.inc} interface uses SysUtils, Controls, Math, KM_Utils, KM_Controls, KM_Saves, KM_InterfaceDefaults, KM_Minimap; type TKMMenuReplays = class private fOnPageChange: TGUIEventText; fSaves: TKMSavesCollection; fMinimap: TKMMinimap; fLastSaveCRC: Cardinal; //CRC of selected save procedure Replays_ListClick(Sender: TObject); procedure Replay_TypeChange(Sender: TObject); procedure Replays_ScanUpdate(Sender: TObject); procedure Replays_SortUpdate(Sender: TObject); procedure Replays_RefreshList(aJumpToSelected:Boolean); procedure Replays_Sort(aIndex: Integer); procedure Replays_Play(Sender: TObject); procedure BackClick(Sender: TObject); procedure DeleteClick(Sender: TObject); procedure DeleteConfirm(aVisible: Boolean); protected Panel_Replays:TKMPanel; Radio_Replays_Type:TKMRadioGroup; ColumnBox_Replays: TKMColumnBox; Button_ReplaysPlay: TKMButton; Button_ReplaysBack:TKMButton; MinimapView_Replay: TKMMinimapView; Button_Delete, Button_DeleteConfirm, Button_DeleteCancel: TKMButton; Label_DeleteConfirm: TKMLabel; public constructor Create(aParent: TKMPanel; aOnPageChange: TGUIEventText); destructor Destroy; override; procedure Show; procedure UpdateState; end; implementation uses KM_ResTexts, KM_GameApp, KM_RenderUI, KM_ResFonts; { TKMGUIMenuReplays } constructor TKMMenuReplays.Create(aParent: TKMPanel; aOnPageChange: TGUIEventText); begin inherited Create; fOnPageChange := aOnPageChange; fSaves := TKMSavesCollection.Create; fMinimap := TKMMinimap.Create(False, True); Panel_Replays := TKMPanel.Create(aParent, 0, 0, aParent.Width, aParent.Height); Panel_Replays.AnchorsStretch; TKMLabel.Create(Panel_Replays, aParent.Width div 2, 50, gResTexts[TX_MENU_LOAD_LIST], fnt_Outline, taCenter); TKMBevel.Create(Panel_Replays, 22, 86, 770, 50); Radio_Replays_Type := TKMRadioGroup.Create(Panel_Replays,30,94,300,40,fnt_Grey); Radio_Replays_Type.ItemIndex := 0; Radio_Replays_Type.Add(gResTexts[TX_MENU_MAPED_SPMAPS]); Radio_Replays_Type.Add(gResTexts[TX_MENU_MAPED_MPMAPS]); Radio_Replays_Type.OnChange := Replay_TypeChange; ColumnBox_Replays := TKMColumnBox.Create(Panel_Replays, 22, 150, 770, 425, fnt_Metal, bsMenu); ColumnBox_Replays.SetColumns(fnt_Outline, [gResTexts[TX_MENU_LOAD_FILE], gResTexts[TX_MENU_LOAD_DATE], gResTexts[TX_MENU_LOAD_DESCRIPTION]], [0, 250, 430]); ColumnBox_Replays.Anchors := [anLeft,anTop,anBottom]; ColumnBox_Replays.SearchColumn := 0; ColumnBox_Replays.OnChange := Replays_ListClick; ColumnBox_Replays.OnColumnClick := Replays_Sort; ColumnBox_Replays.OnDoubleClick := Replays_Play; with TKMBevel.Create(Panel_Replays, 805, 290, 199, 199) do Anchors := [anLeft]; MinimapView_Replay := TKMMinimapView.Create(Panel_Replays,809,294,191,191); MinimapView_Replay.Anchors := [anLeft]; Button_ReplaysBack := TKMButton.Create(Panel_Replays, 337, 700, 350, 30, gResTexts[TX_MENU_BACK], bsMenu); Button_ReplaysBack.Anchors := [anLeft,anBottom]; Button_ReplaysBack.OnClick := BackClick; Button_ReplaysPlay := TKMButton.Create(Panel_Replays, 337, 590, 350, 30, gResTexts[TX_MENU_VIEW_REPLAY], bsMenu); Button_ReplaysPlay.Anchors := [anLeft,anBottom]; Button_ReplaysPlay.OnClick := Replays_Play; Button_Delete := TKMButton.Create(Panel_Replays, 337, 624, 350, 30, gResTexts[TX_MENU_REPLAY_DELETE], bsMenu); Button_Delete.Anchors := [anLeft,anBottom]; Button_Delete.OnClick := DeleteClick; Label_DeleteConfirm := TKMLabel.Create(Panel_Replays, aParent.Width div 2, 634, gResTexts[TX_MENU_REPLAY_DELETE_CONFIRM], fnt_Outline, taCenter); Label_DeleteConfirm.Anchors := [anLeft,anBottom]; Label_DeleteConfirm.Hide; Button_DeleteConfirm := TKMButton.Create(Panel_Replays, 337, 660, 170, 30, gResTexts[TX_MENU_LOAD_DELETE_DELETE], bsMenu); Button_DeleteConfirm.Anchors := [anLeft,anBottom]; Button_DeleteConfirm.OnClick := DeleteClick; Button_DeleteConfirm.Hide; Button_DeleteCancel := TKMButton.Create(Panel_Replays, 517, 660, 170, 30, gResTexts[TX_MENU_LOAD_DELETE_CANCEL], bsMenu); Button_DeleteCancel.Anchors := [anLeft,anBottom]; Button_DeleteCancel.OnClick := DeleteClick; Button_DeleteCancel.Hide; end; destructor TKMMenuReplays.Destroy; begin fSaves.Free; fMinimap.Free; inherited; end; procedure TKMMenuReplays.Replays_ListClick(Sender: TObject); var ID: Integer; begin fSaves.Lock; ID := ColumnBox_Replays.ItemIndex; Button_ReplaysPlay.Enabled := InRange(ID, 0, fSaves.Count-1) and fSaves[ID].IsValid and fSaves[ID].IsReplayValid; Button_Delete.Enabled := InRange(ID, 0, fSaves.Count-1); if Sender = ColumnBox_Replays then DeleteConfirm(False); if InRange(ID, 0, fSaves.Count-1) then fLastSaveCRC := fSaves[ID].CRC else fLastSaveCRC := 0; MinimapView_Replay.Hide; //Hide by default, then show it if we load the map successfully if Button_ReplaysPlay.Enabled and fSaves[ID].LoadMinimap(fMinimap) then begin MinimapView_Replay.SetMinimap(fMinimap); MinimapView_Replay.Show; end; fSaves.Unlock; end; procedure TKMMenuReplays.Replay_TypeChange(Sender: TObject); begin fSaves.TerminateScan; fLastSaveCRC := 0; ColumnBox_Replays.Clear; Replays_ListClick(nil); fSaves.Refresh(Replays_ScanUpdate, (Radio_Replays_Type.ItemIndex = 1)); DeleteConfirm(False); end; procedure TKMMenuReplays.Replays_ScanUpdate(Sender: TObject); begin Replays_RefreshList(False); //Don't jump to selected with each scan update end; procedure TKMMenuReplays.Replays_SortUpdate(Sender: TObject); begin Replays_RefreshList(True); //After sorting jump to the selected item end; procedure TKMMenuReplays.Replays_RefreshList(aJumpToSelected: Boolean); var I, PrevTop: Integer; begin PrevTop := ColumnBox_Replays.TopIndex; ColumnBox_Replays.Clear; fSaves.Lock; try for I := 0 to fSaves.Count - 1 do ColumnBox_Replays.AddItem(MakeListRow( [fSaves[I].FileName, fSaves[i].Info.GetSaveTimestamp, fSaves[I].Info.GetTitleWithTime], [$FFFFFFFF, $FFFFFFFF, $FFFFFFFF])); for I := 0 to fSaves.Count - 1 do if (fSaves[I].CRC = fLastSaveCRC) then ColumnBox_Replays.ItemIndex := I; finally fSaves.Unlock; end; ColumnBox_Replays.TopIndex := PrevTop; if aJumpToSelected and (ColumnBox_Replays.ItemIndex <> -1) and not InRange(ColumnBox_Replays.ItemIndex - ColumnBox_Replays.TopIndex, 0, ColumnBox_Replays.GetVisibleRows-1) then if ColumnBox_Replays.ItemIndex < ColumnBox_Replays.TopIndex then ColumnBox_Replays.TopIndex := ColumnBox_Replays.ItemIndex else if ColumnBox_Replays.ItemIndex > ColumnBox_Replays.TopIndex + ColumnBox_Replays.GetVisibleRows - 1 then ColumnBox_Replays.TopIndex := ColumnBox_Replays.ItemIndex - ColumnBox_Replays.GetVisibleRows + 1; end; procedure TKMMenuReplays.Replays_Sort(aIndex: Integer); begin case ColumnBox_Replays.SortIndex of //Sorting by filename goes A..Z by default 0: if ColumnBox_Replays.SortDirection = sdDown then fSaves.Sort(smByFileNameDesc, Replays_SortUpdate) else fSaves.Sort(smByFileNameAsc, Replays_SortUpdate); //Sorting by description goes Old..New by default 1: if ColumnBox_Replays.SortDirection = sdDown then fSaves.Sort(smByDateDesc, Replays_SortUpdate) else fSaves.Sort(smByDateAsc, Replays_SortUpdate); //Sorting by description goes A..Z by default 2: if ColumnBox_Replays.SortDirection = sdDown then fSaves.Sort(smByDescriptionDesc, Replays_SortUpdate) else fSaves.Sort(smByDescriptionAsc, Replays_SortUpdate); end; end; procedure TKMMenuReplays.Replays_Play(Sender: TObject); var ID: Integer; begin if not Button_ReplaysPlay.Enabled then exit; //This is also called by double clicking ID := ColumnBox_Replays.ItemIndex; if not InRange(ID, 0, fSaves.Count-1) then Exit; fSaves.TerminateScan; //stop scan as it is no longer needed fGameApp.NewReplay(fSaves[ID].Path + fSaves[ID].FileName + '.bas'); end; procedure TKMMenuReplays.BackClick(Sender: TObject); begin //Scan should be terminated, it is no longer needed fSaves.TerminateScan; fOnPageChange(gpMainMenu); end; procedure TKMMenuReplays.DeleteConfirm(aVisible: Boolean); begin Label_DeleteConfirm.Visible := aVisible; Button_DeleteConfirm.Visible := aVisible; Button_DeleteCancel.Visible := aVisible; Button_Delete.Visible := not aVisible; end; procedure TKMMenuReplays.DeleteClick(Sender: TObject); var OldSelection: Integer; begin if ColumnBox_Replays.ItemIndex = -1 then Exit; if Sender = Button_Delete then DeleteConfirm(True); if (Sender = Button_DeleteConfirm) or (Sender = Button_DeleteCancel) then DeleteConfirm(False); //Delete the save if Sender = Button_DeleteConfirm then begin OldSelection := ColumnBox_Replays.ItemIndex; fSaves.DeleteSave(ColumnBox_Replays.ItemIndex); Replays_RefreshList(False); if ColumnBox_Replays.RowCount > 0 then ColumnBox_Replays.ItemIndex := EnsureRange(OldSelection, 0, ColumnBox_Replays.RowCount - 1) else ColumnBox_Replays.ItemIndex := -1; Replays_ListClick(ColumnBox_Replays); end; end; procedure TKMMenuReplays.Show; begin //Copy/Pasted from SwitchPage for now (needed that for ResultsMP BackClick) //Probably needs some cleanup when we have GUIMenuReplays fLastSaveCRC := 0; Radio_Replays_Type.ItemIndex := 0; //we always show SP replays on start Replay_TypeChange(nil); //Select SP as this will refresh everything Replays_Sort(ColumnBox_Replays.SortIndex); //Apply sorting from last time we were on this page Panel_Replays.Show; end; procedure TKMMenuReplays.UpdateState; begin fSaves.UpdateState; end; end.
unit GoodsToExpirationDate; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxPCdxBarPopupMenu, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, Data.DB, cxDBData, Vcl.Menus, dsdAddOn, dxBarExtItems, dxBar, cxClasses, dsdDB, Datasnap.DBClient, dsdAction, Vcl.ActnList, cxPropertiesStore, cxGridLevel, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxPC, dxSkinsCore, dxSkinsDefaultPainters, dxSkinscxPCPainter, dxSkinsdxBarPainter, cxContainer, Vcl.ComCtrls, dxCore, cxDateUtils, cxTextEdit, cxLabel, cxMaskEdit, cxDropDownEdit, cxCalendar, Vcl.ExtCtrls, cxCurrencyEdit, AncestorBase; type TGoodsToExpirationDateForm = class(TAncestorBaseForm) ListGoodsGrid: TcxGrid; ListGoodsGridDBTableView: TcxGridDBTableView; colGoodsCode: TcxGridDBColumn; colGoodsName: TcxGridDBColumn; colAmout: TcxGridDBColumn; colExpirationDate: TcxGridDBColumn; ListGoodsGridLevel: TcxGridLevel; ListGoodsDS: TDataSource; ListGoodsCDS: TClientDataSet; procedure colGoodsCodeGetDataText(Sender: TcxCustomGridTableItem; ARecordIndex: Integer; var AText: string); procedure colGoodsNameGetDataText(Sender: TcxCustomGridTableItem; ARecordIndex: Integer; var AText: string); private { Private declarations } FGoodsCode: Integer; FGoodsName: String; public { Public declarations } function GoodsToExpirationDateExecute(AId, AGoodsCode: Integer; AGoodsName: String): boolean; end; implementation {$R *.dfm} uses LocalWorkUnit, CommonData, MainCash2; procedure TGoodsToExpirationDateForm.colGoodsCodeGetDataText( Sender: TcxCustomGridTableItem; ARecordIndex: Integer; var AText: string); begin AText := IntToStr(FGoodsCode); end; procedure TGoodsToExpirationDateForm.colGoodsNameGetDataText( Sender: TcxCustomGridTableItem; ARecordIndex: Integer; var AText: string); begin AText := FGoodsName; end; function TGoodsToExpirationDateForm.GoodsToExpirationDateExecute(AId, AGoodsCode: Integer; AGoodsName: String): boolean; begin FGoodsCode := AGoodsCode; FGoodsName := AGoodsName; WaitForSingleObject(MutexGoodsExpirationDate, INFINITE); try if FileExists(GoodsExpirationDate_lcl) then LoadLocalData(ListGoodsCDS, GoodsExpirationDate_lcl); if not ListGoodsCDS.Active then ListGoodsCDS.Open; finally ReleaseMutex(MutexGoodsExpirationDate); end; ListGoodsCDS.Filter := 'Id = ' + IntToStr(AId); ListGoodsCDS.Filtered := True; Result := ShowModal = mrOK; end; end.
unit RepositorioNotaFiscal; interface uses DB, NotaFiscal, Repositorio, Dialogs; type TRepositorioNotaFiscal = 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 CondicaoSQLGetAll :String; override; function SQLGetAll :String; override; function SQLRemover :String; override; protected function IsInsercao(Objeto :TObject) :Boolean; override; protected procedure SetParametros (Objeto :TObject ); override; procedure SetIdentificador(Objeto :TObject; Identificador :Variant); override; protected procedure ExecutaDepoisDeSalvar (Objeto :TObject); override; private procedure salva_itens_produtos(notaFiscal :TNotaFiscal); end; implementation uses TipoSerie, TipoFrete, SysUtils, FabricaRepositorio, ItemNotaFiscal, LocalEntregaNotaFiscal, VolumesNotaFiscal, ObservacaoNotaFiscal, Funcoes, TotaisNotaFiscal, LoteNFe, NFe, RepositorioItemAvulso, ItemAvulso, Math, StrUtils; { TRepositorioNotaFiscal } function TRepositorioNotaFiscal.CondicaoSQLGetAll: String; begin result := ' WHERE data_saida between '+FIdentificador; end; procedure TRepositorioNotaFiscal.ExecutaDepoisDeSalvar(Objeto: TObject); var NotaFiscal :TNotaFiscal; begin NotaFiscal := (Objeto as TNotaFiscal); salva_itens_produtos(NotaFiscal) end; function TRepositorioNotaFiscal.Get(Dataset: TDataSet): TObject; begin result := TNotaFiscal.CriarParaRepositorio(Dataset.FieldByName('codigo').AsInteger, Dataset.FieldByName('numero_nota_fiscal').AsInteger, Dataset.FieldByName('codigo_natureza').AsInteger, Dataset.FieldByName('serie').AsString, Dataset.FieldByName('codigo_emitente').AsInteger, Dataset.FieldByName('codigo_destinatario').AsInteger, Dataset.FieldByName('codigo_fpagto').AsInteger, Dataset.FieldByName('data_emissao').AsDateTime, Dataset.FieldByName('data_saida').AsDateTime, Dataset.FieldByName('codigo_transportadora').AsInteger, Dataset.FieldByName('tipo_frete').AsInteger, Dataset.FieldByName('entrada_saida').AsString, Dataset.FieldByName('finalidade').AsString, Dataset.FieldByName('nfe_referenciada').AsString, Dataset.FieldByName('entrou_estoque').AsString, Dataset.FieldByName('nota_importacao').AsString = 'S'); end; function TRepositorioNotaFiscal.GetIdentificador(Objeto: TObject): Variant; begin result := TNotaFiscal(Objeto).CodigoNotaFiscal; end; function TRepositorioNotaFiscal.GetNomeDaTabela: String; begin result := 'notas_fiscais'; end; function TRepositorioNotaFiscal.GetRepositorio: TRepositorio; begin result := TRepositorioNotaFiscal.Create; end; function TRepositorioNotaFiscal.IsInsercao(Objeto: TObject): Boolean; begin result := (TNotaFiscal(Objeto).CodigoNotaFiscal <= 0); end; procedure TRepositorioNotaFiscal.salva_itens_produtos(notaFiscal: TNotaFiscal); var RepItens :TRepositorio; RepPedFat :TRepositorio; RepItensAvulsos :TRepositorio; RepLocalEntrega :TRepositorio; RepVolumes :TRepositorio; RepObservacoes :TRepositorio; RepTotais :TRepositorio; RepLoteNFe :TRepositorio; RepNFe :TRepositorio; nX :Integer; codigo_item :Integer; begin RepItens := nil; RepPedFat := nil; RepLocalEntrega := nil; RepVolumes := nil; RepObservacoes := nil; RepTotais := nil; RepLoteNFe := nil; RepNFe := nil; try { Itens } RepItens := TFabricaRepositorio.GetRepositorio(TItemNotaFiscal.ClassName); for nX := 0 to (NotaFiscal.Itens.Count-1) do begin if Assigned(self.FAtualizarTela) then self.FAtualizarTela; TItemNotaFiscal(NotaFiscal.Itens[nX]).CarregarImpostos; end; for nX := 0 to (NotaFiscal.Itens.Count-1) do begin if Assigned(self.FAtualizarTela) then self.FAtualizarTela; {codigo_item := StrToIntDef( Campo_por_campo('ITENS_NOTAS_FISCAIS','CODIGO','CODIGO_NOTA_FISCAL', IntToStr(notaFiscal.CodigoNotaFiscal), 'CODIGO_PRODUTO',IntToStr(TItemNotaFiscal(NotaFiscal.Itens[nX]).Produto.Codigo)), 0); TItemNotaFiscal(NotaFiscal.Itens[nX]).Codigo := codigo_item; } TItemNotaFiscal(NotaFiscal.Itens[nX]).CodigoNotaFiscal := notaFiscal.CodigoNotaFiscal; RepItens.Salvar(NotaFiscal.Itens[nX]); end; { Volumes } if Assigned(self.FAtualizarTela) then self.FAtualizarTela; if assigned(NotaFiscal.Volumes) and (NotaFiscal.Volumes.Especie <> '') then begin RepVolumes := TFabricaRepositorio.GetRepositorio(TVolumesNotaFiscal.ClassName); NotaFiscal.Volumes.CodigoNotaFiscal := notaFiscal.CodigoNotaFiscal; RepVolumes.Remover(NotaFiscal.Volumes); RepVolumes.Salvar(NotaFiscal.Volumes); end; { Observações } if Assigned(self.FAtualizarTela) then self.FAtualizarTela; RepObservacoes := TFabricaRepositorio.GetRepositorio(TObservacaoNotaFiscal.ClassName); notaFiscal.Observacoes.CodigoNotaFiscal := notaFiscal.CodigoNotaFiscal; RepObservacoes.Remover(NotaFiscal.Observacoes); RepObservacoes.Salvar(NotaFiscal.Observacoes); { Totais } // if Assigned(self.FAtualizarTela) then // self.FAtualizarTela; RepTotais := TFabricaRepositorio.GetRepositorio(TTotaisNotaFiscal.ClassName); //notaFiscal.Totais.CodigoNotaFiscal := notaFiscal.CodigoNotaFiscal; RepTotais.Remover(NotaFiscal.Totais); RepTotais.Salvar(NotaFiscal.Totais); { Itens Avulsos } RepItensAvulsos := TFabricaRepositorio.GetRepositorio(TItemAvulso.ClassName); if Assigned(NotaFiscal.ItensAvulsos) and Assigned(self.FAtualizarTela) then self.FAtualizarTela; RepItensAvulsos.RemoverPorIdentificador(NotaFiscal.CodigoNotaFiscal); if Assigned(NotaFiscal.ItensAvulsos) then begin for nX := 0 to (NotaFiscal.ItensAvulsos.Count-1) do begin if Assigned(self.FAtualizarTela) then self.FAtualizarTela; TItemAvulso(NotaFiscal.ItensAvulsos[nX]).CodigoNotaFiscal := notaFiscal.CodigoNotaFiscal; RepItensAvulsos.Salvar(NotaFiscal.ItensAvulsos[nX]); end; end; { LoteNFe } if Assigned(NotaFiscal.Lote) then begin if Assigned(self.FAtualizarTela) then self.FAtualizarTela; RepLoteNFe := TFabricaRepositorio.GetRepositorio(TLoteNFe.ClassName); NotaFiscal.Lote.CodigoNotaFiscal := notaFiscal.CodigoNotaFiscal; RepLoteNFe.Salvar(NotaFiscal.Lote); end; { NFe } if Assigned(NotaFiscal.NFe) then begin if Assigned(self.FAtualizarTela) then self.FAtualizarTela; RepNFe := TFabricaRepositorio.GetRepositorio(TNFe.ClassName); NotaFiscal.NFe.CodigoNotaFiscal := notaFiscal.CodigoNotaFiscal; RepNFe.Remover(NotaFiscal.NFe); RepNFe.Salvar(NotaFiscal.NFe); end; finally FreeAndNil(RepPedFat); FreeAndNil(RepItens); FreeAndNil(RepLocalEntrega); FreeAndNil(RepVolumes); FreeAndNil(RepObservacoes); FreeAndNil(RepTotais); FreeAndNil(RepLoteNFe); FreeAndNil(RepNFe); end; end; procedure TRepositorioNotaFiscal.SetIdentificador(Objeto: TObject; Identificador: Variant); begin TNotaFiscal(Objeto).CodigoNotaFiscal := Integer(Identificador); end; procedure TRepositorioNotaFiscal.SetParametros(Objeto: TObject); var obj :TNotaFiscal; begin obj := (Objeto as TNotaFiscal); if (obj.CodigoNotaFiscal > 0) then inherited SetParametro('codigo', obj.CodigoNotaFiscal) else inherited LimpaParametro('codigo'); inherited SetParametro('numero_nota_fiscal', Obj.NumeroNotaFiscal); inherited SetParametro('codigo_natureza', obj.CFOP.Codigo); inherited SetParametro('serie', Obj.Serie); inherited SetParametro('codigo_emitente', obj.Emitente.Codigo); inherited SetParametro('codigo_destinatario', obj.Destinatario.Codigo); if assigned( obj.FormaPagamento ) then inherited SetParametro('codigo_fpagto', obj.FormaPagamento.Codigo) else inherited SetParametro('codigo_fpagto', 1); //uma qualquer apenas para passar (impor. xml entrada) inherited SetParametro('data_emissao', obj.DataEmissao); inherited SetParametro('data_saida', obj.DataSaida); if assigned(obj.Transportadora) then inherited SetParametro('codigo_transportadora', obj.Transportadora.Codigo); inherited SetParametro('tipo_frete', TTipoFreteUtilitario.DeEnumeradoParaInteiro(obj.TipoFrete)); inherited SetParametro('entrada_saida', obj.Entrada_saida ); inherited SetParametro('finalidade', obj.Finalidade ); inherited SetParametro('nfe_referenciada', obj.NFe_referenciada ); inherited SetParametro('entrou_estoque', obj.EntrouEstoque ); inherited SetParametro('nota_importacao', IfThen(obj.notaDeImportacao, 'S', '') ); end; function TRepositorioNotaFiscal.SQLGet: String; begin result := ' select * from ' + self.GetNomeDaTabela + ' where codigo = :codigo '; end; function TRepositorioNotaFiscal.SQLGetAll: String; begin result := ' select * from ' + self.GetNomeDaTabela + IfThen(FIdentificador = '','', CondicaoSQLGetAll) +' order by codigo'; end; function TRepositorioNotaFiscal.SQLRemover: String; begin result := 'delete from ' + self.GetNomeDaTabela + ' where codigo = :codigo '; end; function TRepositorioNotaFiscal.SQLSalvar: String; begin result := ' update or insert into ' + self.GetNomeDaTabela + ' (codigo, numero_nota_fiscal, codigo_natureza, serie, codigo_emitente, codigo_destinatario, codigo_fpagto, data_emissao, '+ ' data_saida, codigo_transportadora, tipo_frete, entrada_saida, finalidade, nfe_referenciada, entrou_estoque, nota_importacao) '+ ' values (:codigo, :numero_nota_fiscal, :codigo_natureza, :serie, :codigo_emitente, :codigo_destinatario, :codigo_fpagto, :data_emissao, '+ ' :data_saida, :codigo_transportadora, :tipo_frete, :entrada_saida, :finalidade, :nfe_referenciada, :entrou_estoque, :nota_importacao) '; end; end.
unit ClipbrdGraphic; interface uses Editor, Graphics, Project, Windows; type TveRuler = ( ruNone, ruNumber, ruLetterNumber ); // ******************************************************* // ARTMAKER PUTS BITMAPPED BOARD IMAGE TO CLIPBOARD // ******************************************************* type TveClipboarder = class protected FEditor : TveEditor; FRulers : TveRuler; FPixelsPerCell : integer; TopRulerHeight : integer; LeftRulerWidth : integer; RulerTextHeight : integer; Project : TveProject; procedure PaintToCanvas( Canvas : TCanvas; Project : TveProject; Area : TRect ); public // property BorderWidth : integer; // property BorderColor : TColor; property Rulers : TveRuler read FRulers write FRulers; property PixelsPerCell : integer read FPixelsPerCell write FPixelsPerCell; property Editor : TveEditor read FEditor write FEditor; procedure CopyToClipboard; // constructor Create; end; implementation uses Clipbrd, Outlines, Classes, Painter, BoardPainter, SysUtils; const FBorder = 0; FGap = 1; { constructor TveArtMaker.Create; begin end; } function IntToLetter( i : integer ) : string; begin // show single character A..Z if i < 26 then begin result := char( Ord('A') + (i mod 26) ); end // show AA..ZZ else begin result := char( Ord('A') + (i div 26) -1 ) + char( Ord('A') + (i mod 26) ); end; end; procedure TveClipboarder.PaintToCanvas( Canvas : TCanvas; Project : TveProject; Area : TRect ); var i : integer; Item : TveBoardItem; CellX1, CellY1, CellX2, CellY2 : integer; ScreenX1, ScreenY1, ScreenX2, ScreenY2 : integer; BoardPainter : TbrBoardPainter; Painter : TvePainter; LeftTopRulerValue, RightTopRulerValue : integer; Text : string; TextX, TextY : integer; TextSize : TSize; begin // move origin so correct part of graphic is included in rect if Editor.SelectionValid then begin SetWindowOrgEx( Canvas.Handle, ( FPixelsPerCell * Editor.SelectedRect.Left ) - LeftRulerWidth, ( FPixelsPerCell * Editor.SelectedRect.Top ) - TopRulerHeight, nil ); end else begin SetWindowOrgEx( Canvas.Handle, - LeftRulerWidth, - TopRulerHeight, nil ); end; // visible screen area in cell coords. Part of this rectangle of cells // may be partly hidden, but all should be drawn CellX1 := (Area.Left ) div FPixelsPerCell; CellY1 := (Area.Top ) div FPixelsPerCell; // ... CellX2 needs to be 1 more otherwise not entire visible area drawn CellX2 := 1+ (Area.Right) div FPixelsPerCell; CellY2 := (Area.Bottom) div FPixelsPerCell; // (ScreenX1, ScreenY1) and ( ScreenX2, ScreenY2) define rectangle we need // to draw inside. Units are pixels : ie canvas coords. Even though part // of this rectangle may be outside the visible rectangle "Rect", we use // this rectangle because its top left coords start exactly at top left of // a cell - and we have to draw integral cells. ScreenX1 := CellX1 * FPixelsPerCell; ScreenY1 := CellY1 * FPixelsPerCell; ScreenX2 := CellX2 * FPixelsPerCell; ScreenY2 := CellY2 * FPixelsPerCell; // BoardPainter object draws board, holes and strips BoardPainter := TbrBoardPainter.Create; try BoardPainter.PixelsPerCell := FPixelsPerCell; BoardPainter.BoardColor := Editor.BoardColor; BoardPainter.StripColor := Editor.StripColor; BoardPainter.Paint( Canvas, Project.Board ); finally BoardPainter.Free; end; // draw BoardItems Painter := TvePainter.Create; try Painter.Border := FBorder; Painter.Gap := FGap; Painter.PixelsPerCell := FPixelsPerCell; Painter.TextDisplay := Editor.TextDisplay; Painter.LeadStyle := Editor.LeadStyle; Painter.LineWidth := Editor.ComponentLineWidth; Painter.BodyColor := Editor.BodyColor; Painter.PinColor := Editor.PinColor; Painter.SmallTextWidth := PixelsPerCell2CharWidth( FPixelsPerCell, tsSmall ); Painter.SmallTextHeight := PixelsPerCell2CharHeight( FPixelsPerCell, tsSmall ); Painter.LargeTextWidth := PixelsPerCell2CharWidth( FPixelsPerCell, tsLarge ); Painter.LargeTextHeight := PixelsPerCell2CharHeight( FPixelsPerCell, tsLarge ); //... draw BoardItems into TvePainter for i := 0 to Project.BoardItemCount -1 do begin Item := TveBoardItem(Project.BoardItems[i]); Item.Outline.Paint( Item, Painter ); end; Painter.PaintNormal( Canvas ); finally Painter.Free; end; if FRulers <> ruNone then begin // move coords back to 0,0 at top, left SetWindowOrgEx( Canvas.Handle, 0, 0 , nil ); // erase ruler areas where component outlines were drawn Canvas.Brush.Color := Editor.BoardColor; //.. lefthand ruler Canvas.FillRect( Classes.Rect( 0, 0, LeftRulerWidth, TopRulerHeight + ScreenY2 - ScreenY1 )); //.. top ruler Canvas.FillRect( Classes.Rect( LeftRulerWidth, 0, LeftRulerWidth + ScreenX2 - ScreenX1, TopRulerHeight )); if Editor.SelectionValid then begin LeftTopRulerValue := Editor.SelectedRect.Top; RightTopRulerValue := Editor.SelectedRect.Left; end else begin LeftTopRulerValue := 0; RightTopRulerValue := 0; end; // write in ruler text Canvas.Font.Color := clBlack; Canvas.Font.Name := 'CourierNew'; Canvas.Font.Height := (13 * FPixelsPerCell) div 16; // Painter.PaintNormal had side effect of leaving text alignment set // to TA_CENTER - ie. horizontally centered, but written below the y // ccord, ie. not centered in both x and y. All following code works // with this alignment. //.. lefthand ruler always shows numbers TextX := (3 * LeftRulerWidth) div 4; // TextY := FTopRulerWidth + (FPixelsPerCell div 2) - (Canvas.Font.Height div 2); // same as above with less rounding error : TextY := TopRulerHeight + ((FPixelsPerCell - Canvas.Font.Height ) div 2); for i := LeftTopRulerValue to LeftTopRulerValue + CellY2 - CellY1 do begin Text := IntToStr(i mod 100); GetTextExtentPoint32( Canvas.Handle, pChar(Text), length(Text), TextSize ); Canvas.TextOut( TextX - (TextSize.cx div 2), TextY, Text ); // Canvas.TextOut( TextX - (Canvas.TextWidth(Text) div 2), TextY, IntToStr(i mod 100) ); Inc( TextY, FPixelsPerCell ); end; // if top ruler shows numbers if FRulers = ruNumber then begin //.. Top ruler TextX := LeftRulerWidth + (FPixelsPerCell div 2); TextY := FPixelsPerCell div 4; for i := RightTopRulerValue to RightTopRulerValue + CellX2 - CellX1 do begin Text := IntToStr(i mod 100); Canvas.TextOut( TextX, TextY, Text ); Inc( TextX, FPixelsPerCell ); end; end // else top ruler shows letters else if FRulers = ruLetterNumber then begin //.. Top ruler TextX := LeftRulerWidth + (FPixelsPerCell div 2); TextY := FPixelsPerCell div 4; for i := RightTopRulerValue to RightTopRulerValue + CellX2 - CellX1 do begin Text := IntToLetter(i); Canvas.TextOut( TextX, TextY, Text ); Inc( TextX, FPixelsPerCell ); end; end; end; end; procedure TveClipboarder.CopyToClipBoard; var Bitmap : Graphics.TBitmap; Canvas : TCanvas; begin Project := FEditor.Project; Bitmap := Graphics.TBitmap.Create; try Canvas := Bitmap.Canvas; // calculate size of rulers if FRulers <> ruNone then begin RulerTextHeight := (PixelsPerCell * 9) div 12; TopRulerHeight := PixelsPerCell; LeftRulerWidth := (PixelsPerCell * 15) div 12; end else begin RulerTextHeight := 0; TopRulerHeight := 0; LeftRulerWidth := 0; end; // if a valid mouse selection if Editor.SelectionValid then begin Bitmap.Width := (FPixelsPerCell * (Editor.SelectedRect.Right - Editor.SelectedRect.Left)) + LeftRulerWidth; Bitmap.Height := (FPixelsPerCell * (Editor.SelectedRect.Bottom - Editor.SelectedRect.Top)) + TopRulerHeight; end // else copy the whole graphic else begin Bitmap.Width := (FPixelsPerCell * Project.BoardWidth) + LeftRulerWidth; Bitmap.Height := (FPixelsPerCell * Project.BoardHeight) + TopRulerHeight; end; PaintToCanvas( Canvas, Project, Rect( 0, 0, FPixelsPerCell * Project.BoardWidth, FPixelsPerCell * Project.BoardHeight ) ); // send Bitmap to clipboard ClipBoard.Assign( Bitmap ); finally Bitmap.Free; end end; end.
unit ScriptEngine; interface uses SysUtils, Classes, uPSComponent, uPSRuntime, upSUtils, ScriptObject, dmThreadDataModule, Contnrs; type EScriptEngine = class(Exception); EStopScript = class(EScriptEngine); TPSPluginClass = class of TPSPlugin; TScriptEngine = class(TObject) private FCode, FCompiledCode: string; Compiled, LoadedCompiledCode: boolean; FMessages: TStrings; FRootObjects, FFunctions: TStringList; oldOnCompile, oldOnExecute: TPSEvent; FStopped: boolean; plugins: TObjectList; function GetCode: string; function GetCol(i: integer): integer; function GetRow(i: integer): integer; function GetExecuteErrorMsg: string; function GetExecuteErrorCol: integer; function GetExecuteErrorRow: integer; function GetExecuteErrorPosition: integer; function GetHasExceptionError: boolean; function GetExceptionMsg: string; function GetExceptionObj: string; function GetCompiledCode: string; procedure SetCompiledCode(const Value: string); procedure OnAfterExecuteStop(Sender: TPSScript); protected PSScript: TPSScriptDebugger; procedure OnExecute(Sender: TPSScript); virtual; procedure OnCompile(Sender: TPSScript); virtual; procedure SetCode(const Value: string); virtual; procedure RegisterPlugin(const pluginClass: TPSPluginClass; const scriptClass: TScriptObjectClass); procedure RegisterFunction(Ptr: Pointer; const Decl: string); procedure RegisterScriptRootClass(const name: string; const scriptObject: TScriptObject); public constructor Create; virtual; destructor Destroy; override; procedure ReloadCode; procedure RaiseException; procedure Stop; function Compile: boolean; virtual; function Execute: boolean; virtual; function GetVariableBoolean(const varName: string): boolean; function GetVariableString(const varName: string): string; function GetVariableCurrency(const varName: string): currency; function GetVariableInteger(const varName: string): integer; function IsCompiled: boolean; function IsLoadedCompiledCode: Boolean; property ExecuteErrorMsg: string read GetExecuteErrorMsg; property ExecuteErrorCol: integer read GetExecuteErrorCol; property ExecuteErrorRow: integer read GetExecuteErrorRow; property ExecuteErrorPosition: integer read GetExecuteErrorPosition; property CompiledCode: string read GetCompiledCode write SetCompiledCode; property Code: string read GetCode write SetCode; property Messages: TStrings read FMessages; property ColMessage[i: integer]: integer read GetCol; property RowMessage[i: integer]: integer read GetRow; property HasExceptionError: boolean read GetHasExceptionError; property ExceptionMsg: string read GetExceptionMsg; property ExceptionObj: string read GetExceptionObj; property RootObjects: TStringList read FRootObjects; property Functions: TStringList read FFunctions; property Stopped: boolean read FStopped; end; implementation uses UtilException; var FHasExceptionError: boolean; FExceptionMsg: string; FExceptionObj: string; FExceptionStack: string; procedure OnException(Sender: TPSExec; ExError: TPSError; const ExParam: tbtstring; ExObject: TObject; ProcNo, Position: Cardinal); begin FHasExceptionError := ExError = erException; if FHasExceptionError then begin FExceptionObj := ExObject.ClassName; FExceptionMsg := ExParam; FExceptionStack := GetStackTraceString; end; end; { TScriptEngine } function TScriptEngine.Compile: boolean; var i: integer; begin Messages.Clear; if Code = '' then Compiled := true else begin Compiled := PSScript.Compile; for i := 0 to PSScript.CompilerMessageCount -1 do begin Messages.Add(PSScript.CompilerMessages[i].MessageToString); end; if Compiled then begin LoadedCompiledCode := false; FCompiledCode := CompiledCode; end; end; result := Compiled; end; constructor TScriptEngine.Create; begin inherited; PSScript := TPSScriptDebugger.Create(nil); plugins := TObjectList.Create(true); FRootObjects := TStringList.Create; FFunctions := TStringList.Create; FMessages := TStringList.Create; PSScript.Exec.OnException := OnException; oldOnCompile := PSScript.OnCompile; PSScript.OnCompile := OnCompile; oldOnExecute := PSScript.OnExecute; PSScript.OnExecute := OnExecute; Compiled := false; end; destructor TScriptEngine.Destroy; begin plugins.Free; FFunctions.Free; FMessages.Free; FRootObjects.Free; PSScript.Free; inherited; end; function TScriptEngine.Execute: boolean; begin FStopped := false; FHasExceptionError := false; FExceptionMsg := ''; FExceptionObj := ''; if LoadedCompiledCode then PSScript.SetCompiled(CompiledCode) else PSScript.Compile; result := PSScript.Execute; if FStopped then raise EStopScript.Create(''); end; function TScriptEngine.GetCode: string; begin result := PSScript.Script.Text; end; function TScriptEngine.GetCol(i: integer): integer; begin result := PSScript.CompilerMessages[i].Col; end; function TScriptEngine.GetCompiledCode: string; begin result := FCompiledCode; if result = '' then begin PSScript.GetCompiled(result); if result <> '' then FCompiledCode := result; end; end; function TScriptEngine.GetExceptionMsg: string; begin result := FExceptionMsg; end; function TScriptEngine.GetExceptionObj: string; begin result := FExceptionObj; end; function TScriptEngine.GetExecuteErrorCol: integer; begin result := PSSCript.ExecErrorCol; end; function TScriptEngine.GetExecuteErrorMsg: string; begin result := PSScript.ExecErrorToString; end; function TScriptEngine.GetExecuteErrorPosition: integer; begin result := PSScript.ExecErrorPosition; end; function TScriptEngine.GetExecuteErrorRow: integer; begin result := PSSCript.ExecErrorRow; end; function TScriptEngine.GetHasExceptionError: boolean; begin result := FHasExceptionError; end; function TScriptEngine.GetRow(i: integer): integer; begin result := PSScript.CompilerMessages[i].Row; end; function TScriptEngine.GetVariableBoolean(const varName: string): boolean; begin result := VGetUInt(PSScript.GetVariable(varName)) <> 0; end; function TScriptEngine.GetVariableCurrency(const varName: string): currency; begin result := VGetCurrency(PSScript.GetVariable(varName)); end; function TScriptEngine.GetVariableInteger(const varName: string): integer; begin result := VGetInt(PSScript.GetVariable(varName)); end; function TScriptEngine.GetVariableString(const varName: string): string; begin result := VGetString(PSScript.GetVariable(varName)); end; function TScriptEngine.IsCompiled: boolean; begin result := Compiled; end; function TScriptEngine.IsLoadedCompiledCode: Boolean; begin result := LoadedCompiledCode; end; procedure TScriptEngine.OnAfterExecuteStop(Sender: TPSScript); begin // Si se llama a Stop, para detener el script la única manera de hacerlo // es en el evento OnRunLine llamar contínuamente a Stop. Cuando acaba el // script debemos quitar el evento, sino si se ejecuta otro script estaría // asignado el evento y solo empezar pararía Sender.Exec.OnRunLine := nil; PSScript.OnAfterExecute := nil; end; procedure TScriptEngine.OnCompile(Sender: TPSScript); var i: integer; obj: TScriptObject; begin for i := 0 to rootObjects.Count - 1 do begin obj := rootObjects.Objects[i] as TScriptObject; Sender.AddRegisteredVariable(rootObjects[i], obj.ScriptInstance.ClassName); end; for i := 0 to Functions.Count - 1 do begin Sender.AddFunction(Pointer(Functions.Objects[i]), Functions[i]); end; if Assigned(oldOnCompile) then oldOnCompile(Sender); end; procedure TScriptEngine.OnExecute(Sender: TPSScript); var i: integer; obj: TScriptObject; begin for i := 0 to rootObjects.Count - 1 do begin obj := rootObjects.Objects[i] as TScriptObject; Sender.SetVarToInstance(rootObjects[i], obj.ScriptInstance); end; if Assigned(oldOnExecute) then oldOnExecute(Sender); end; procedure TScriptEngine.RaiseException; begin if FHasExceptionError then raise EScriptEngine.Create(FExceptionObj + ':' + sLineBreak + FExceptionMsg + sLineBreak + FExceptionStack); end; procedure TScriptEngine.RegisterFunction(Ptr: Pointer; const Decl: string); begin Functions.AddObject(Decl, Ptr); end; procedure TScriptEngine.RegisterPlugin(const pluginClass: TPSPluginClass; const scriptClass: TScriptObjectClass); var plugin: TPSPlugin; begin plugin := pluginClass.Create(nil); plugins.Add(plugin); TPSPluginItem(PSScript.Plugins.Add).Plugin := plugin; RegisterClass(scriptClass); end; procedure TScriptEngine.RegisterScriptRootClass(const name: string; const scriptObject: TScriptObject); begin FRootObjects.AddObject(name, scriptObject); end; procedure TScriptEngine.ReloadCode; begin SetCode(FCode); end; procedure TScriptEngine.SetCode(const Value: string); begin FCode := Value; PSScript.Script.Text := Value; Compiled := false; end; procedure TScriptEngine.SetCompiledCode(const Value: string); begin FCompiledCode := Value; LoadedCompiledCode := Value <> ''; if LoadedCompiledCode then PSScript.SetCompiled(Value); end; procedure OnRunLine(Sender: TPSExec); begin Sender.Stop; end; procedure TScriptEngine.Stop; begin FStopped := true; if PSScript.Running then begin PSScript.OnAfterExecute := OnAfterExecuteStop; // Para detener el script la única manera de hacerlo // es en el evento OnRunLine llamar contínuamente a Stop. PSScript.Exec.OnRunLine := OnRunLine; end; end; end.
{$mode objfpc} {$modeswitch objectivec1} {$modeswitch cblocks} unit AppDelegate; interface uses CocoaAll; type TAppDelegate = objcclass(NSObject, NSApplicationDelegateProtocol) private window: NSWindow; public procedure applicationDidFinishLaunching(notification: NSNotification); message 'applicationDidFinishLaunching:'; procedure newWindow(sender: id); message 'newWindow:'; end; implementation type TCustomWindowController = objcclass (NSWindowController, NSWindowDelegateProtocol) procedure clickedButton(sender: id); message 'clickedButton:'; procedure windowDidLoad; override; { NSWindowDelegateProtocol } procedure windowWillClose (notification: NSNotification); message 'windowWillClose:'; end; type NSAlertCompletionBlock = reference to procedure(response: NSModalResponse); cdecl; procedure AlertCompleted(response: NSModalResponse); begin writeln('response: ', response); end; procedure TCustomWindowController.clickedButton(sender: id); var completionHandler: NSAlertCompletionBlock; alert: NSAlert; begin completionHandler := @AlertCompleted; alert := NSAlert.alloc.init; alert.setMessageText(NSSTR('Clicked!')); alert.setInformativeText(NSSTR('more information...')); alert.addButtonWithTitle(NSSTR('Ok')); alert.beginSheetModalForWindow_completionHandler(window, OpaqueCBlock(completionHandler)); end; procedure TCustomWindowController.windowWillClose (notification: NSNotification); begin { we get NSWindowDelegate messages because the windows delegate is set to the controller } writeln('window will close'); end; procedure TCustomWindowController.windowDidLoad; begin window.setTitle(NSSTR(HexStr(self))); end; procedure TAppDelegate.newWindow(sender: id); var controller: TCustomWindowController; begin controller := TCustomWindowController.alloc.initWithWindowNibName(NSSTR('TCustomWindowController')); if assigned(controller) then controller.showWindow(nil); end; procedure TAppDelegate.applicationDidFinishLaunching(notification : NSNotification); begin newWindow(nil); end; 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, cxImageComboBox, cxNavigator, System.JSON, cxDataControllerConditionalFormattingRulesManagerDialog, ZStoredProcedure, dxDateRanges, REST.Types, REST.Client, Data.Bind.Components, Data.Bind.ObjectScope; type TMainForm = class(TForm) ZConnection1: TZConnection; Timer1: TTimer; Panel2: TPanel; btnAll: TButton; btnLoadeEchangeRates: TButton; spExchangeRates: TZStoredProc; Panel3: TPanel; cxGrid1: TcxGrid; cxGridDBTableView4: TcxGridDBTableView; UnitId: TcxGridDBColumn; UnitName: TcxGridDBColumn; UnitSerialNumber: TcxGridDBColumn; cxGridLevel4: TcxGridLevel; dsUnit: TDataSource; qryUnit: TZQuery; RESTRequest: TRESTRequest; RESTResponse: TRESTResponse; RESTClient: TRESTClient; procedure FormCreate(Sender: TObject); procedure btnLoadeEchangeRatesClick(Sender: TObject); procedure btnAllClick(Sender: TObject); procedure Timer1Timer(Sender: TObject); private { Private declarations } APIUser: String; APIPassword: String; 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 if Pos('----', AMessage) > 0 then Writeln(F, AMessage) else Writeln(F,FormatDateTime('YYYY.MM.DD hh:mm:ss',now) + ' - ' + AMessage); finally CloseFile(F); end; except end; end; procedure TMainForm.btnAllClick(Sender: TObject); begin Add_Log('-----------------'); Add_Log('Запуск процессов загрузки.'#13#10); btnLoadeEchangeRatesClick(Sender); end; procedure TMainForm.btnLoadeEchangeRatesClick(Sender: TObject); var jValue : TJSONValue; JSONA: TJSONArray; I : Integer; begin Add_Log('Получение курса доллара.'); RESTClient.BaseURL := 'https://api.privatbank.ua/p24api/pubinfo?json&exchange&coursid=11'; RESTClient.ContentType := 'application/json'; RESTRequest.ClearBody; RESTRequest.Method := TRESTRequestMethod.rmGET; RESTRequest.Resource := ''; // required parameters RESTRequest.Params.Clear; try RESTRequest.Execute; if RESTResponse.ContentType = 'application/json' then begin JSONA := RESTResponse.JSONValue.GetValue<TJSONArray>; for I := 0 to JSONA.Count - 1 do begin jValue := JSONA.Items[I]; if (jValue.FindValue('ccy').Value = 'USD') and (jValue.FindValue('base_ccy').Value = 'UAH') then begin spExchangeRates.ParamByName('inOperDate').Value := Date; spExchangeRates.ParamByName('inExchange').Value := Ceil(StrToCurr(StringReplace(jValue.FindValue('sale').Value, '.', FormatSettings.DecimalSeparator, [rfReplaceAll]))); spExchangeRates.ParamByName('inSession').Value := '3'; spExchangeRates.ExecProc; Break; end; end; end else Add_Log('Ошибка загрузки курса: '#13#10 + RESTResponse.Content); except on E: Exception do Begin Add_Log('Ошибка загрузки курса: '#13#10 + E.Message); Exit; End; end; end; procedure TMainForm.FormCreate(Sender: TObject); var Ini: TIniFile; begin Ini := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'LoadingDataFarmacy.ini'); try ZConnection1.Database := Ini.ReadString('Connect', 'DataBase', 'farmacy'); Ini.WriteString('Connect', 'DataBase', ZConnection1.Database); ZConnection1.HostName := Ini.ReadString('Connect', 'HostName', '172.17.2.5'); Ini.WriteString('Connect', 'HostName', ZConnection1.HostName); ZConnection1.User := Ini.ReadString('Connect', 'User', 'postgres'); Ini.WriteString('Connect', 'User', ZConnection1.User); ZConnection1.Password := Ini.ReadString('Connect', 'Password', 'eej9oponahT4gah3'); Ini.WriteString('Connect', 'Password', ZConnection1.Password); finally Ini.free; end; ZConnection1.LibraryLocation := ExtractFilePath(Application.ExeName) + 'libpq.dll'; try ZConnection1.Connect; except on E:Exception do begin Application.ShowMainForm := False; Add_Log(E.Message); Timer1.Enabled := true; Exit; end; end; // if ZConnection1.Connected then // begin // qryUnit.Close; // try // qryUnit.Open; // except // on E: Exception do // begin // Add_Log(E.Message); // ZConnection1.Disconnect; // end; // end; // end; if ZConnection1.Connected then begin if not ((ParamCount >= 1) and (CompareText(ParamStr(1), 'manual') = 0)) then begin Application.ShowMainForm := False; btnAll.Enabled := false; btnLoadeEchangeRates.Enabled := false; btnLoadeEchangeRates.Enabled := false; Timer1.Enabled := true; end; end else begin Application.ShowMainForm := False; Timer1.Enabled := true; Exit; end; end; procedure TMainForm.Timer1Timer(Sender: TObject); begin try Timer1.Enabled := False; btnAllClick(Sender); finally Close; end; end; end.
unit ImpressaoAbastecimentos; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.ToolWin, Vcl.StdCtrls, Data.SqlExpr, Data.DB; type TFormImpressaoAbastecimentos = class(TForm) LabelDataInicial: TLabel; ToolBar: TToolBar; ToolButtonLimpar: TToolButton; ToolButtonSeparator01: TToolButton; ToolButtonImprimir: TToolButton; DateTimePickerDataInicial: TDateTimePicker; StatusBar: TStatusBar; LabelDataFinal: TLabel; DateTimePickerDataFinal: TDateTimePicker; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormShow(Sender: TObject); procedure ToolButtonLimparClick(Sender: TObject); procedure ToolButtonImprimirClick(Sender: TObject); private function ValidaImpressao:Boolean; public { Public declarations } end; var FormImpressaoAbastecimentos: TFormImpressaoAbastecimentos; implementation {$R *.dfm} uses Principal, Util, ImpressaoAbastecimentosa; procedure TFormImpressaoAbastecimentos.FormClose(Sender: TObject; var Action: TCloseAction); begin try Action := caFree; except on E: Exception do begin TUtil.Mensagem(e.Message); end; end; end; procedure TFormImpressaoAbastecimentos.FormDestroy(Sender: TObject); begin try FormImpressaoAbastecimentos := nil; except on E: Exception do begin TUtil.Mensagem(e.Message); end; end; end; procedure TFormImpressaoAbastecimentos.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin try case (Key) of VK_F2 : ToolButtonLimpar.Click(); VK_F7 : ToolButtonImprimir.Click(); VK_ESCAPE : Close; end; except on E: Exception do begin TUtil.Mensagem(e.Message); end; end; end; procedure TFormImpressaoAbastecimentos.FormShow(Sender: TObject); begin try ToolButtonLimpar.Click(); except on E: Exception do begin TUtil.Mensagem(e.Message); end; end; end; procedure TFormImpressaoAbastecimentos.ToolButtonImprimirClick(Sender: TObject); var Query: TSQLQuery; DataSource: TDataSource; begin try if not(ValidaImpressao()) then begin Exit; end; TUtil.CriarQuery(Query); DataSource := TDataSource.Create(Self); DataSource.DataSet := Query; Query.SQL.Add('SELECT b.Descricao AS Bomba'); Query.SQL.Add(' ,a.Data AS DataAbastecimento'); Query.SQL.Add(' ,t.Descricao AS Tanque'); Query.SQL.Add(' ,a.Valor'); Query.SQL.Add(' FROM Abastecimento a'); Query.SQL.Add(' INNER JOIN Bomba b'); Query.SQL.Add(' ON a.BombaId = b.Id'); Query.SQL.Add(' INNER JOIN Tanque t'); Query.SQL.Add(' ON b.TanqueId = t.Id'); Query.SQL.Add(' WHERE Data >= '''+FormatDateTime('yyyy-mm-dd',DateTimePickerDataInicial.Date)+''''); Query.SQL.Add(' AND Data <= '''+FormatDateTime('yyyy-mm-dd',DateTimePickerDataFinal.Date)+''''); Query.SQL.Add(' ORDER BY b.Descricao'); Query.Open(); if (Query.IsEmpty) then begin TUtil.Mensagem('Não existem abastecimentos para serem impressos nesse período.'); TUtil.DestruirQuery(Query); Exit; end; if (FormImpressaoAbastecimentosa = nil) then begin Application.CreateForm(TFormImpressaoAbastecimentosa, FormImpressaoAbastecimentosa); end; FormImpressaoAbastecimentosa.RLReportAbastecimentoBombas.DataSource := DataSource; FormImpressaoAbastecimentosa.Query := Query; FormImpressaoAbastecimentosa.RLReportAbastecimentoBombas.Preview(); Application.RemoveComponent(FormImpressaoAbastecimentosa); FormImpressaoAbastecimentosa.Destroy; FormImpressaoAbastecimentosa := nil; FreeAndNil(DataSource); TUtil.DestruirQuery(Query); except on E: Exception do begin TUtil.Mensagem(e.Message); end; end; end; procedure TFormImpressaoAbastecimentos.ToolButtonLimparClick(Sender: TObject); begin try DateTimePickerDataInicial.Date := Date(); DateTimePickerDataFinal.Date := Date(); DateTimePickerDataInicial.SetFocus(); except on E: Exception do begin TUtil.Mensagem(e.Message); end; end; end; function TFormImpressaoAbastecimentos.ValidaImpressao: Boolean; begin try Result := False; if (DateTimePickerDataInicial.Date > DateTimePickerDataFinal.Date) then begin TUtil.Mensagem('A data inicial não pode ser maior que a data final.'); Exit; end; Result := True; except on E: Exception do begin raise Exception.Create(E.Message); end; end; end; end.
unit rMasks; interface uses System.SysUtils; type EMaskException = class(Exception); TMask = class private type TMaskSet = array of WideChar; PMaskSet = ^TMaskSet; TMaskStates = (msLiteral, msAny, msSet); TMaskState = record SkipTo: Boolean; case State: TMaskStates of msLiteral: (Literal: WideChar); msAny: (); msSet: ( Negate: Boolean; CharSet: PMaskSet); end; private FMaskStates: array of TMaskState; protected function CharInSet(const Char: WideChar; const List: TMaskSet): Boolean; procedure CharAdd(const Char: WideChar; var List: TMaskSet); function InitMaskStates(const Mask: string): Integer; procedure DoneMaskStates; function MatchesMaskStates(const Filename: string): Boolean; public constructor Create(const MaskValue: string); destructor Destroy; override; function Matches(const Filename: string): Boolean; end; function MatchesMask(const Filename, Mask: string): Boolean; implementation uses System.RTLConsts, Dialogs; const MaxCards = 255; function TMask.CharInSet(const Char: WideChar; const List: TMaskSet): Boolean; var i: Integer; begin Result := False; if Length(List) > 0 then begin for i := Low(List) to High(List) do begin if List[i] = Char then begin Result := True; Exit; end; end; end; end; procedure TMask.CharAdd(const Char: WideChar; var List: TMaskSet); begin if not CharInSet(Char, List) then begin SetLength(List, Length(List) + 1); List[High(List)] := Char; end; end; function TMask.InitMaskStates(const Mask: string): Integer; var I: Integer; SkipTo: Boolean; Literal: WideChar; P: PWideChar; Negate: Boolean; CharSet: TMaskSet; Cards: Integer; procedure InvalidMask; begin raise EMaskException.CreateResFmt(@SInvalidMask, [Mask, P - PWideChar(Mask) + 1]); end; procedure Reset; begin SkipTo := False; Negate := False; CharSet := []; end; procedure WriteScan(MaskState: TMaskStates); begin if I <= High(FMaskStates) then begin if SkipTo then begin Inc(Cards); if Cards > MaxCards then InvalidMask; end; FMaskStates[I].SkipTo := SkipTo; FMaskStates[I].State := MaskState; case MaskState of msLiteral: FMaskStates[I].Literal := Literal; msSet: begin FMaskStates[I].Negate := Negate; New(FMaskStates[I].CharSet); SetLength(FMaskStates[I].CharSet^, 0); FMaskStates[I].CharSet^ := CharSet; end; end; end; Inc(I); Reset; end; procedure ScanSet; var LastChar: WideChar; C: WideChar; begin Inc(P); if P^ = '!' then begin Negate := True; Inc(P); end; LastChar := #0; while not CharInSet(P^, [#0, ']']) do begin case P^ of '-': if LastChar = #0 then InvalidMask else begin Inc(P); for C := LastChar to P^ do CharAdd(C, CharSet); end; else LastChar := P^; CharAdd(LastChar, CharSet); end; Inc(P); end; if (P^ <> ']') or (Length(CharSet) = 0) then InvalidMask; WriteScan(msSet); end; begin P := PWideChar(Mask); I := 0; Cards := 0; Reset; while P^ <> #0 do begin case P^ of '*': SkipTo := True; '?': if not SkipTo then WriteScan(msAny); '[': ScanSet; else Literal := P^; WriteScan(msLiteral); end; Inc(P); end; Literal := #0; WriteScan(msLiteral); Result := I; end; function TMask.MatchesMaskStates(const Filename: string): Boolean; type TStackRec = record sP: PWideChar; sI: Integer; end; var T: Integer; S: array of TStackRec; I: Integer; P: PWideChar; procedure Push(P: PWideChar; I: Integer); begin S[T].sP := P; S[T].sI := I; Inc(T); end; function Pop(var P: PWideChar; var I: Integer): Boolean; begin if T = 0 then Result := False else begin Dec(T); P := S[T].sP; I := S[T].sI; Result := True; end; end; function Matches(P: PWideChar; Start: Integer): Boolean; var I: Integer; begin Result := False; for I := Start to High(FMaskStates) do begin if FMaskStates[I].SkipTo then begin case FMaskStates[I].State of msLiteral: while (P^ <> #0) and (P^ <> FMaskStates[I].Literal) do Inc(P); msSet: while (P^ <> #0) and not (FMaskStates[I].Negate xor CharInSet(P^, FMaskStates[I].CharSet^)) do Inc(P); end; if P^ <> #0 then Push(@P, I); end; case FMaskStates[I].State of msLiteral: if P^ <> FMaskStates[I].Literal then Exit; msSet: if not (FMaskStates[I].Negate xor CharInSet(P^, FMaskStates[I].CharSet^)) then Exit; msAny: if P^ = #0 then begin Result := False; Exit; end; end; Inc(P); end; Result := True; end; begin SetLength(S, MaxCards); Result := True; T := 0; P := PWideChar(Filename); I := Low(FMaskStates); repeat if Matches(P, I) then Exit; until not Pop(P, I); Result := False; end; procedure TMask.DoneMaskStates; var I: Integer; begin for I := Low(FMaskStates) to High(FMaskStates) do if FMaskStates[I].State = msSet then begin SetLength(FMaskStates[I].CharSet^, 0); Dispose(FMaskStates[I].CharSet); end; end; constructor TMask.Create(const MaskValue: string); var Size: Integer; begin SetLength(FMaskStates, 1); Size := InitMaskStates(MaskValue); DoneMaskStates; SetLength(FMaskStates, Size); InitMaskStates(MaskValue); end; destructor TMask.Destroy; begin DoneMaskStates; SetLength(FMaskStates, 0); end; function TMask.Matches(const Filename: string): Boolean; begin Result := MatchesMaskStates(Filename); end; function MatchesMask(const Filename, Mask: string): Boolean; var CMask: TMask; begin CMask := TMask.Create(UpperCase(Mask, loUserLocale)); try Result := CMask.Matches(UpperCase(Filename, loUserLocale)); finally CMask.Free; end; end; end.
unit UPlayer; interface uses UArcher; type TPlayer = class(TArcher) public ExtraArchers : array of TArcher; procedure UpdateInformation(origX, origY, currX, currY : float); override; procedure Fire(); override; procedure UpdateY(newPos : float); end; implementation procedure TPlayer.UpdateInformation(origX, origY, currX, currY : float); begin inherited(origX, origY, currX, currY); // Update information for the extra archers for var i := 0 to High(ExtraArchers) do begin ExtraArchers[i].UpdateInformation(origX, origY, currX, currY); // Set the archer's ability to shoot to that of the player if not ExtraArchers[i].CanShoot = CanShoot then begin ExtraArchers[i].CanShoot := CanShoot; end; end; end; procedure TPlayer.Fire(); begin // Make extra archers also fire if the player can if CanShoot then begin for var i := 0 to High(ExtraArchers) do begin ExtraArchers[i].Fire(); end; end; // Then fire the player inherited(); end; procedure TPlayer.UpdateY(newPos : float); var posChange : float; begin // Get the change in y position posChange := Y - newPos; // Update the player's and extra archer's y position Y -= posChange; for var i := 0 to High(ExtraArchers) do begin ExtraArchers[i].Y -= posChange; end; end; end.
unit unCadUsuarioAlteraSenha; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, DB, ZAbstractRODataset, PerlRegEx, ZAbstractDataset, ZDataset, ComCtrls, StrUtils, pngimage, AdvAppStyler, AdvEdit, AdvOfficeButtons, AdvGlowButton, AdvPanel, unUsuario; type TfmCadUsuarioAlteraSenha = class(TForm) FormStyler: TAdvFormStyler; PanelBotoes: TAdvPanel; BitBtnFechar: TAdvGlowButton; BitBtnAlterarSenha: TAdvGlowButton; PanelCentral: TAdvPanel; CheckBoxEnviarEmail: TAdvOfficeCheckBox; CheckBoxSenhaComplexa: TAdvOfficeCheckBox; EditSenhaAtual: TAdvEdit; EditSenhaConfirmacao: TAdvEdit; EditSenhaNova: TAdvEdit; LabelDicaSenha: TLabel; LabelNovaSenha: TLabel; LabelRedigite: TLabel; LabelSenhaAtual: TLabel; LabelUsuario: TLabel; MemoDicaSenha: TMemo; procedure BitBtnFecharClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure BitBtnAlterarSenhaClick(Sender: TObject); procedure EditSenhaNovaKeyPress(Sender: TObject; var Key: Char); procedure EditSenhaAtualExit(Sender: TObject); procedure EditSenhaNovaExit(Sender: TObject); procedure EditSenhaConfirmacaoExit(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormResize(Sender: TObject); private { Private declarations } //pWindowsNetAPI: NET_API_STATUS; pId: TGUID; ppreValidacao: TPerlRegEx; pUsuario: TUsuario; pstrSenhaAnterior: string; procedure obtemInformacoesUsuario; function validaCadastro: boolean; public { Public declarations } end; var fmCadUsuarioAlteraSenha: TfmCadUsuarioAlteraSenha; const cRegExp = '(?=^[A-Z])(?=^[!-~]{8,}$)(?=.*[a-z])(?=.*[A-Z])(?=.*[^A-Za-z0-9])(?=^.*[^\s].*$)(?=.*[\d]).*$'; cCaractesEspeciaisProibidos = ['ç','Ç','~','^','´','`','¨','â','Â','à','À','ã', 'Ã','é','É','ê','Ê','è','È','í','Í','î','Î','ì', 'Ì','æ','Æ','ô','ò','û','ù','ø','£','Ø','ƒ','á', 'Á','ó','ú','ñ','Ñ','ª','º','¿','®','½','¼','Ó', 'ß','Ô','Ò','õ','Õ','µ','þ','Ú','Û','Ù','ý','Ý']; cValidaEMail = '\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b'; implementation uses unPrincipal, undmPrincipal, undmEstilo; {$R *.dfm} procedure TfmCadUsuarioAlteraSenha.BitBtnAlterarSenhaClick(Sender: TObject); var vEmail: string; vRetorno: integer; begin try vRetorno := 0; BitBtnAlterarSenha.Enabled := false; // Valida se a nova senha está ok. // Valida a força da Senha; if not validaCadastro then Exit; try try with pUsuario do begin Codigo := fmPrincipal.CodigoUsuarioLogado; Senha := fmPrincipal.fnGeral.criptografaSenha(EditSenhaNova.Text); DicaSenha := MemoDicaSenha.Lines.Text; vRetorno := atualizaSenhaUsuario; end; if vRetorno <> 0 then begin fmPrincipal.SenhaComplexa := CheckBoxSenhaComplexa.Checked; fmPrincipal.apresentaResultadoCadastro('Senha de acesso atualizada com sucesso.'); end else begin fmPrincipal.apresentaResultadoCadastro('Não foi possível atualizar a senha de acesso.'); Exit; end; if CheckBoxEnviarEmail.Checked = true then begin vEmail := '<div align="left">'+ 'Prezado '+fmPrincipal.LoginUsuarioLogado+','+ '</div>'+ '<br>'+ '<div align="left">'+ 'Sua senha de acesso foi alterada em '+FormatDateTime('dd/mm/yyy hh:nn:ss',Now())+'.'+ '<br>'+ 'A sua nova senha de acesso é: "'+EditSenhaNova.Text+'".'+ '<br>'+ 'A dica da sua nova senha de acesso é: "'+MemoDicaSenha.Lines.Text+'".'+ '</div>'; fmPrincipal.enviaEmail('Alteração de senha de acesso', fmPrincipal.EmailUsuarioLogado, EmptyStr, EmptyStr, vEmail); end; fmPrincipal.pLogSistema.Debug('O usuário ' + fmPrincipal.LoginUsuarioLogado + ' atualizou sua senha de acesso.'); finally if vRetorno <> 0 then begin fmPrincipal.SenhaUsuarioLogado := EditSenhaNova.Text; EditSenhaAtual.Enabled := false; EditSenhaNova.Enabled := false; MemoDicaSenha.Enabled := false; CheckBoxEnviarEmail.Enabled := false; BitBtnAlterarSenha.Enabled := false; end; end; except on E: exception do fmPrincipal.manipulaExcecoes(Sender,E); end; finally BitBtnAlterarSenha.Enabled := false; end; end; procedure TfmCadUsuarioAlteraSenha.BitBtnFecharClick(Sender: TObject); begin Close; end; procedure TfmCadUsuarioAlteraSenha.EditSenhaAtualExit(Sender: TObject); begin if Trim(EditSenhaAtual.Text) = EmptyStr then Exit; if fmPrincipal.SenhaUsuarioLogado <> EditSenhaAtual.Text then begin fmPrincipal.apresentaResultadoCadastro('A senha informada não confere com a senha atual do usuário.'); EditSenhaAtual.SetFocus; end; end; procedure TfmCadUsuarioAlteraSenha.EditSenhaConfirmacaoExit(Sender: TObject); begin if Trim(EditSenhaConfirmacao.Text) = EmptyStr then Exit; if AnsiUpperCase(EditSenhaConfirmacao.Text) <> AnsiUpperCase(EditSenhaNova.Text) then begin fmPrincipal.apresentaResultadoCadastro('A senha de confirmação precisa ser igual a senha nova informada.'); EditSenhaConfirmacao.SetFocus; Exit; end; BitBtnAlterarSenha.Enabled := true; end; procedure TfmCadUsuarioAlteraSenha.EditSenhaNovaExit(Sender: TObject); begin if Trim(EditSenhaNova.Text) = EmptyStr then Exit; if AnsiUpperCase(EditSenhaAtual.Text) = AnsiUpperCase(EditSenhaNova.Text) then begin fmPrincipal.apresentaResultadoCadastro('A senha nova precisa ser diferente da senha atual.'); EditSenhaNova.SetFocus; end else begin EditSenhaConfirmacao.Enabled := true; EditSenhaConfirmacao.SetFocus; end; end; procedure TfmCadUsuarioAlteraSenha.EditSenhaNovaKeyPress(Sender: TObject; var Key: Char); begin if (CharInSet(Key,cCaractesEspeciaisProibidos)) or (Key = '''') Then begin fmPrincipal.apresentaResultadoCadastro('Este caractere especial não pode ser utilizado na nova senha de acesso,'+ ' favor utilizar outro caractere especial.'); Key := #0; end; end; procedure TfmCadUsuarioAlteraSenha.FormCreate(Sender: TObject); var i: integer; begin try CreateGUID(pId); Color := Self.Color; FormStyler.AutoThemeAdapt := false; ppreValidacao := TPerlRegEx.Create; pUsuario := TUsuario.Create; LabelUsuario.Caption := 'Usuário: ' + fmPrincipal.LoginUsuarioLogado; CheckBoxSenhaComplexa.Checked := fmPrincipal.SenhaComplexa; CheckBoxEnviarEmail.Checked := true; for i := Self.ComponentCount -1 downto 0 do if (Self.Components[i] is TAdvOfficeCheckBox) then (Self.Components[i] as TAdvOfficeCheckBox).Themed := true; obtemInformacoesUsuario; FormResize(Sender); except on E: Exception do begin fmPrincipal.manipulaExcecoes(Sender,E); Close; end; end; end; procedure TfmCadUsuarioAlteraSenha.FormDestroy(Sender: TObject); begin FreeAndNil(ppreValidacao); FreeAndNil(pUsuario); end; procedure TfmCadUsuarioAlteraSenha.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then Exit; end; procedure TfmCadUsuarioAlteraSenha.FormResize(Sender: TObject); begin BitBtnFechar.Left := PanelBotoes.Width - BitBtnFechar.Width - fmPrincipal.EspacamentoFinalBotao; BitBtnAlterarSenha.Left := BitBtnFechar.Left - BitBtnAlterarSenha.Width - fmPrincipal.EspacamentoEntreBotoes; end; procedure TfmCadUsuarioAlteraSenha.obtemInformacoesUsuario; var vQuery: TZQuery; begin fmPrincipal.pLogSistema.Debug('O usuário solicitou a informação da dica da senha.'); vQuery := pUsuario.lista; try with vQuery do begin SQL.Add('WHERE NMLOGIN = ' + QuotedStr(fmPrincipal.LoginUsuarioLogado)); dmPrincipal.executaConsulta(vQuery); if RecordCount > 0 then begin MemoDicaSenha.Lines.Text := FieldByName('DEDICASENHA').AsString; pstrSenhaAnterior := FieldByName('DESENHANTERIOR').AsString; end; end; finally vQuery.Active := false; FreeAndNil(vQuery); end; end; function TfmCadUsuarioAlteraSenha.validaCadastro: boolean; var vMensagem: TStringList; vSenha: string; begin vMensagem := TStringList.Create; // Para a Senha Atual. if fmPrincipal.SenhaUsuarioLogado <> EditSenhaAtual.Text then begin vMensagem.Add('- A senha informada não confere com a senha atual do usuário.'); end; if AnsiUpperCase(EditSenhaAtual.Text) = AnsiUpperCase(EditSenhaNova.Text) then vMensagem.Add('- A senha nova precisa ser diferente da senha atual.'); vSenha := fmPrincipal.fnGeral.criptografaSenha(EditSenhaNova.Text); if vSenha = pstrSenhaAnterior then vMensagem.Add('- A senha nova precisa ser diferente da última senha utilizada pelo usuário.'); // Se for definido que vai validar a complexidade das senha, executa o processo abaixo. if CheckBoxSenhaComplexa.Checked = true then begin // Para a Senha Atual. with ppreValidacao do begin RegEx := cRegExp; Subject := UTF8String(EditSenhaNova.Text); if not Match then vMensagem.Add( 'A nova senha informada não respeita os requisitos mínimos para uma senha forte e segura.'+#13+#10+ 'Requisitos:'+#13+#10+ '- Iniciar com letra maiúscula;'+#13+#10+ '- Possuir no mínimo ter 8 caracteres;'+#13+#10+ '- Possuir no mínimo 1 letra minúscula;'+#13+#10+ '- Possuir no mínimo 1 caracter especial;'+#13+#10+ '- Possuir no mínimo 1 número;'+#13+#10+ '- Não possuir espaços em branco.'+#13+#10+ 'Favor revisar a senha informada.'); end; end; Result := (vMensagem.Count = 0); if vMensagem.Count > 0 then begin MessageBox(fmPrincipal.Handle, PWideChar('A alteração da sua senha não poderá ser executada devido as seguintes pendências:'+#13#10+ vMensagem.Text+ 'Por favor, revise os pontos de pendência identificados.'), cTituloMensagemErro, MB_OK or MB_ICONERROR); EditSenhaAtual.Clear; EditSenhaNova.Clear; EditSenhaConfirmacao.Clear; EditSenhaConfirmacao.Enabled := false; BitBtnAlterarSenha.Enabled := false; ActiveControl := EditSenhaAtual; end; end; end.
unit CatParamList; interface uses Classes, CatParam, ADODB; type TCatParamList = class(TList) private function Get(Index: Integer): TCatParam; procedure Put(Index: Integer; const Value: TCatParam); public Letters: string; procedure Clear; override; procedure Fill(Con: TADOConnection); function FindCat(Letter: Char): TCatParam; function AbbrCat(Letter: Char): string; function ValTypeCat(Letter: Char): Integer; property Items[Index: Integer]: TCatParam read Get write Put; default; end; implementation uses SysUtils, CatField; { TCatParamList } function TCatParamList.AbbrCat(Letter: Char): string; var x: TCatParam; begin x:=FindCat(Letter); if x <> nil then Result:=x.Abbr else Result:='N'; end; procedure TCatParamList.Clear; var i: Integer; begin for i:=0 to Count-1 do Items[i].Free; inherited; end; procedure TCatParamList.Fill(Con: TADOConnection); var Cat: TCatParam; QCat, QFld: TADOQuery; begin Clear; QCat:=TADOQuery.Create(nil); QCat.Connection:=Con; QCat.SQL.Text:='select Abbr, Letter, Comment, DTable, id, InRTDB, InFormul from OICat'; QFld:=TADOQuery.Create(nil); QFld.Connection:=Con; QFld.SQL.Text:='select NnField, RTNameField, RTSizeField, RTTypeField '+ 'from oitype where oicat=:oicat order by NnField'; Letters:=''; QCat.Open; while not QCat.EOF do begin Cat:=TCatParam.Create; Cat.Letter:=QCat.FieldByName('Letter').AsString[1]; Cat.Name:=QCat.FieldByName('Comment').AsString; Cat.Abbr:=TrimRight(QCat.FieldByName('Abbr').AsString); Cat.Size:=0; Cat.DTable:=not QCat.FieldByName('DTable').IsNull; Cat.InRTDB:=QCat.FieldByName('InRTDB').AsBoolean; Cat.InFrml:=QCat.FieldByName('InFormul').AsBoolean; if Cat.DTable then begin QFld.Close; QFld.Parameters[0].Value:=QCat.FieldByName('ID').AsInteger; QFld.Open; while not QFld.EOF do begin Cat.Add(TCatField.Create(Trim(QFld.FieldByName('RTNameField').AsString), QFld.FieldByName('RTTypeField').AsInteger, QFld.FieldByName('RTSizeField').AsInteger)); Cat.Size:=Cat.Size+QFld.FieldByName('RTSizeField').AsInteger; QFld.Next; end; QFld.Close; end; Add(Cat); Letters:=Letters+Cat.Letter; QCat.Next; end; QCat.Free; QFld.Free; end; function TCatParamList.FindCat(Letter: Char): TCatParam; var i: Integer; begin Result:=nil; for i:=0 to Count-1 do if Items[i].Letter = Letter then begin Result:=Items[i]; Break; end; end; function TCatParamList.Get(Index: Integer): TCatParam; begin Result:=TCatParam(inherited Get(Index)); end; procedure TCatParamList.Put(Index: Integer; const Value: TCatParam); begin inherited Put(Index, Value); end; function TCatParamList.ValTypeCat(Letter: Char): Integer; var x: TCatParam; i: Integer; begin Result:=0; x:=FindCat(Letter); if x <> nil then for i:=0 to x.Count-1 do if x[i].Name = 'value' then begin Result:=x[i].RType; Break; end; end; end.
unit MainFrm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Layouts, FMX.Controls.Presentation, FMX.StdCtrls, FMX.ScrollBox, FMX.Memo, DW.NFC; type TfrmMain = class(TForm) ButtonsLayout: TLayout; StartButton: TButton; LogMemo: TMemo; procedure StartButtonClick(Sender: TObject); private FNFCReader: TNFCReader; procedure NFCReaderDetectedNDEFsHandler(Sender: TObject; const AMessages: TNFCMessages); procedure NFCReaderErrorHandler(Sender: TObject; const AError: string); public constructor Create(AOwner: TComponent); override; end; var frmMain: TfrmMain; implementation {$R *.fmx} uses DW.OSLog; const cNFCMessagePayload = 'Payload - id: %s, payload: %s'; { TForm1 } constructor TfrmMain.Create(AOwner: TComponent); begin inherited; FNFCReader := TNFCReader.Create; FNFCReader.OnDetectedNDEFs := NFCReaderDetectedNDEFsHandler; FNFCReader.OnError := NFCReaderErrorHandler; FNFCReader.AlertMessage := 'Hold an NFC tag near the phone..'; end; procedure TfrmMain.NFCReaderDetectedNDEFsHandler(Sender: TObject; const AMessages: TNFCMessages); var I, J: Integer; LPayload: TNFCPayload; begin for I := 0 to Length(AMessages) - 1 do begin for J := 0 to Length(AMessages[I].Payloads) - 1 do begin LPayload := AMessages[I].Payloads[J]; LogMemo.Lines.Add(Format(cNFCMessagePayload, [LPayload.Identifier, LPayload.Payload])) end; end; end; procedure TfrmMain.NFCReaderErrorHandler(Sender: TObject; const AError: string); begin if not FNFCReader.IsActive then StartButton.Text := 'Start'; LogMemo.Lines.Add('Error: ' + AError); end; procedure TfrmMain.StartButtonClick(Sender: TObject); begin if FNFCReader.IsActive then begin FNFCReader.EndSession; StartButton.Text := 'Start'; end else begin FNFCReader.BeginSession; StartButton.Text := 'Stop'; end; end; end.
unit ImpRibbon; // Ribbon Control MDI patch component // by Jeehoon Imp Park // // Originally from Ribbon patch file of Georgi Panayotov, http://www.ada-soft.bg/downloads/ribbon.patch interface uses Classes, Controls, Windows, Forms, Messages, Ribbon, RibbonStyleActnCtrls; type TMdiSysButtonKind = (mbkMDIMinimize, mbkMDIRestore, mbkMDIClose); TImpRibbon = class; // MDI Buttons TRibbonMDIButton = class(TOffice2007Button) private FOwnerRibbon: TImpRibbon; FButtonKind: TMdiSysButtonKind; protected procedure DrawImage; override; procedure Click; override; public constructor Create(AOwner: TComponent); override; end; TRibbonMDIButtons = class(TObject) private FMinimizeItem: TRibbonMDIButton; FRestoreItem: TRibbonMDIButton; FCloseItem: TRibbonMDIButton; FButtonsWidth: Integer; FRibbon: TImpRibbon; FButtonsHeight: Integer; FRect: TRect; procedure InvalidateToolbar; procedure UpdateState(W: HWND; Maximized: Boolean); procedure SetRect(const Value: TRect); public constructor Create(AOwner: TImpRibbon); destructor Destroy; override; property ButtonsWidth: Integer read FButtonsWidth; property ButtonsHeight: Integer read FButtonsHeight; property BoundsRect: TRect read FRect write SetRect; end; TImpRibbon = class(TRibbon) private FParentForm: TCustomForm; FRibbonMDIButtons: TRibbonMDIButtons; FOldDefWndProc: Pointer; procedure ClientWndProc(var Message: TMessage); protected function GetHelpButtonRect: TRect; override; function GetMDIButtonsRect: TRect; virtual; procedure InvalidateSubTitleButtons; virtual; procedure SetParent(AParent: TWinControl); override; procedure Resize; override; procedure CreateWnd; override; procedure DestroyWnd; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; implementation uses SysUtils, Dialogs; { TImpRibbon } constructor TImpRibbon.Create(AOwner: TComponent); begin inherited Create(AOwner); FRibbonMDIButtons := nil; end; destructor TImpRibbon.Destroy; begin if Assigned(FRibbonMDIButtons) then FreeAndNil(FRibbonMDIButtons); inherited Destroy; end; procedure TImpRibbon.CreateWnd; begin inherited CreateWnd; FOldDefWndProc := Pointer(SetWindowLong(TForm(FParentForm).ClientHandle, GWL_WNDPROC, LongInt(classes.MakeObjectInstance(ClientWndProc)))); end; procedure TImpRibbon.DestroyWnd; begin SetWindowLong(TForm(FParentForm).ClientHandle, GWL_WNDPROC, LongInt(FOldDefWndProc)); inherited DestroyWnd; end; procedure TImpRibbon.ClientWndProc(var Message: TMessage); var I: Integer; begin if (TForm(FParentForm).FormStyle=fsMDIForm) then case Message.Msg of WM_MDIRESTORE, WM_MDIMAXIMIZE, WM_SIZE, WM_MDIDESTROY: if Assigned(self.ApplicationMenu.Menu) then for I := 1 to self.ApplicationMenu.Menu.ControlCount - 1 do self.ApplicationMenu.Menu.Controls[I].Visible := False; end; with Message do Result := CallWindowProc(FOldDefWndProc, TForm(FParentForm).ClientHandle, Msg, wParam, lParam); end; function TImpRibbon.GetHelpButtonRect: TRect; var MBWidth, LTopPos, HelpButtonWidth, HelpButtonHeight: Integer; begin Result := inherited GetHelpButtonRect; if ShowHelpButton then begin HelpButtonWidth := Result.Right - Result.Left; HelpButtonHeight := Result.Bottom - Result.Top; LTopPos := Result.Top; if Assigned(FRibbonMDIButtons) then MBWidth := FRibbonMDIButtons.ButtonsWidth else MBWidth := 0; if BiDiMode = bdLeftToRight then Result := Rect(Width - HelpButtonWidth - MBWidth, LTopPos, Width - MBWidth, LTopPos + HelpButtonHeight) else Result := Rect(0 + MBWidth, LTopPos, HelpButtonWidth + MBWidth, LTopPos + HelpButtonHeight); end; end; function TImpRibbon.GetMDIButtonsRect: TRect; var LTopPos: Integer; begin if Assigned(FRibbonMDIButtons) then begin LTopPos := GetRibbonMetric(rmCaption) + 1; if BiDiMode = bdLeftToRight then Result := Rect(Width - FRibbonMDIButtons.ButtonsWidth, LTopPos, Width, LTopPos + FRibbonMDIButtons.ButtonsHeight) else Result := Rect(0, LTopPos, FRibbonMDIButtons.ButtonsWidth, LTopPos + FRibbonMDIButtons.ButtonsHeight); end else Result := Rect(0, 0, 0, 0); end; procedure TImpRibbon.InvalidateSubTitleButtons; var I: Integer; begin if Assigned(FRibbonMDIButtons) then FRibbonMDIButtons.BoundsRect := GetMDIButtonsRect; if ShowHelpButton then begin for I := 0 to ControlCount - 1 do if Controls[I].ClassName = 'THelpButton' then THelpButton(Controls[I]).BoundsRect := GetHelpButtonRect; end; end; procedure TImpRibbon.Resize; begin inherited Resize; if Assigned(FRibbonMDIButtons) then FRibbonMDIButtons.BoundsRect := GetMDIButtonsRect; end; procedure TImpRibbon.SetParent(AParent: TWinControl); begin if Parent = AParent then exit; if Assigned(AParent) then FParentForm := GetParentForm(AParent) else FParentForm := nil; inherited SetParent(AParent); if not Assigned(AParent) then exit; if not(csDesigning in ComponentState) and not(csDestroying in ComponentState) then begin if Assigned(FParentForm) and (TForm(FParentForm).FormStyle = fsMDIForm) then begin if not Assigned(FRibbonMDIButtons) then begin FRibbonMDIButtons := TRibbonMDIButtons.Create(self); FRibbonMDIButtons.BoundsRect := GetMDIButtonsRect; end; end else if Assigned(FRibbonMDIButtons) then FreeAndNil(FRibbonMDIButtons); end; end; { TRibbonMDIButtons } var CBTHookHandle: HHOOK; RibbonMDIButtonsList: TList; function AddToList(var List: TList; Item: TObject): Boolean; { Returns True if Item didn't already exist in the list } begin if List = nil then List := TList.Create; Result := List.IndexOf(Item) = -1; if Result then List.Add(Item); end; procedure RemoveFromList(var List: TList; Item: TObject); begin if Assigned(List) then begin List.Remove(Item); if List.Count = 0 then begin List.Free; List := nil; end; end; end; function WindowIsMDIChild(W: HWND): Boolean; var I: Integer; MainForm, ChildForm: TForm; begin MainForm := Application.MainForm; if Assigned(MainForm) then for I := 0 to MainForm.MDIChildCount - 1 do begin ChildForm := MainForm.MDIChildren[I]; if ChildForm.HandleAllocated and (ChildForm.Handle = W) then begin Result := True; Exit; end; end; Result := False; end; function CBTHook(Code: Integer; WParam: WParam; LParam: LParam): LRESULT; stdcall; var Maximizing: Boolean; WindowPlacement: TWindowPlacement; I: Integer; begin case Code of HCBT_SETFOCUS: begin if WindowIsMDIChild(HWND(WParam)) and Assigned(RibbonMDIButtonsList) then begin for I := 0 to RibbonMDIButtonsList.Count - 1 do TRibbonMDIButtons(RibbonMDIButtonsList[I]).InvalidateToolbar; end; end; HCBT_MINMAX: begin if WindowIsMDIChild(HWND(WParam)) and Assigned(RibbonMDIButtonsList) and (LParam in [SW_SHOWNORMAL, SW_SHOWMAXIMIZED, SW_MINIMIZE, SW_RESTORE]) then begin Maximizing := (LParam = SW_MAXIMIZE); if (LParam = SW_RESTORE) and not IsZoomed(HWND(WParam)) then begin WindowPlacement.length := SizeOf(WindowPlacement); GetWindowPlacement(HWND(WParam), @WindowPlacement); Maximizing := (WindowPlacement.flags and WPF_RESTORETOMAXIMIZED <> 0); end; for I := 0 to RibbonMDIButtonsList.Count - 1 do TRibbonMDIButtons(RibbonMDIButtonsList[I]).UpdateState(HWND(WParam), Maximizing); end; end; HCBT_DESTROYWND: begin if WindowIsMDIChild(HWND(WParam)) and Assigned(RibbonMDIButtonsList) then for I := 0 to RibbonMDIButtonsList.Count - 1 do TRibbonMDIButtons(RibbonMDIButtonsList[I]).UpdateState(HWND(WParam), False); end; end; Result := CallNextHookEx(CBTHookHandle, Code, WParam, LParam); end; constructor TRibbonMDIButtons.Create(AOwner: TImpRibbon); begin FRibbon := AOwner; FMinimizeItem := TRibbonMDIButton.Create(AOwner); FRestoreItem := TRibbonMDIButton.Create(AOwner); FCloseItem := TRibbonMDIButton.Create(AOwner); FMinimizeItem.FButtonKind := mbkMDIMinimize; FRestoreItem.FButtonKind := mbkMDIRestore; FCloseItem.FButtonKind := mbkMDIClose; UpdateState(0, False); AddToList(RibbonMDIButtonsList, self); if CBTHookHandle = 0 then CBTHookHandle := SetWindowsHookEx(WH_CBT, CBTHook, 0, GetCurrentThreadId); end; destructor TRibbonMDIButtons.Destroy; begin RemoveFromList(RibbonMDIButtonsList, self); if (CBTHookHandle <> 0) then begin UnhookWindowsHookEx(CBTHookHandle); CBTHookHandle := 0; end; FreeAndNil(FMinimizeItem); FreeAndNil(FRestoreItem); FreeAndNil(FCloseItem); inherited Destroy; end; procedure TRibbonMDIButtons.InvalidateToolbar; begin FRibbon.InvalidateSubTitleButtons; end; procedure TRibbonMDIButtons.SetRect(const Value: TRect); var W, h: Integer; begin FRect := Value; if FMinimizeItem.Visible then begin W := FMinimizeItem.Width; // (Value.Right - Value.Left) div 3; h := FMinimizeItem.Height; if FRibbon.BiDiMode = bdLeftToRight then begin FMinimizeItem.BoundsRect := Rect(FRect.Left, FRect.Top, FRect.Left + W, FRect.Top + h); FRestoreItem.BoundsRect := Rect(FRect.Left + W, FRect.Top, FRect.Right - W, FRect.Top + h); FCloseItem.BoundsRect := Rect(FRect.Right - W, FRect.Top, FRect.Right, FRect.Top + h); end else begin FCloseItem.BoundsRect := Rect(FRect.Left, FRect.Top, FRect.Left + W, FRect.Top + h); FRestoreItem.BoundsRect := Rect(FRect.Left + W, FRect.Top, FRect.Right - W, FRect.Top + h); FMinimizeItem.BoundsRect := Rect(FRect.Right - W, FRect.Top, FRect.Right, FRect.Top + h); end; end; end; procedure TRibbonMDIButtons.UpdateState(W: HWND; Maximized: Boolean); var HasMaxChild, VisibilityChanged: Boolean; procedure UpdateVisibleEnabled(const Button: TOffice2007Button; const AEnabled: Boolean); begin if (Button.Visible <> HasMaxChild) or (Button.Enabled <> AEnabled) then begin Button.Visible := HasMaxChild; Button.Enabled := AEnabled; VisibilityChanged := True; end; end; var MainForm, ActiveMDIChild, ChildForm: TForm; I: Integer; begin HasMaxChild := False; MainForm := Application.MainForm; ActiveMDIChild := nil; if Assigned(MainForm) then begin for I := 0 to MainForm.MDIChildCount - 1 do begin ChildForm := MainForm.MDIChildren[I]; if ChildForm.HandleAllocated and (((ChildForm.Handle = W) and Maximized) or ((ChildForm.Handle <> W) and IsZoomed(ChildForm.Handle))) then begin HasMaxChild := True; Break; end; end; ActiveMDIChild := MainForm.ActiveMDIChild; end; VisibilityChanged := False; UpdateVisibleEnabled(FMinimizeItem, (ActiveMDIChild = nil) or (GetWindowLong(ActiveMDIChild.Handle, GWL_STYLE) and WS_MINIMIZEBOX <> 0)); UpdateVisibleEnabled(FRestoreItem, True); UpdateVisibleEnabled(FCloseItem, True); if VisibilityChanged then begin if HasMaxChild then FButtonsWidth := FMinimizeItem.Width * 3 else FButtonsWidth := 0; InvalidateToolbar; end; if Assigned(FRibbon.ApplicationMenu.Menu) then for I := 1 to FRibbon.ApplicationMenu.Menu.ControlCount - 1 do FRibbon.ApplicationMenu.Menu.Controls[I].Visible := False; end; { TRibbonMDIButton } constructor TRibbonMDIButton.Create(AOwner: TComponent); begin inherited Create(AOwner); FOwnerRibbon := nil; if AOwner is TImpRibbon then FOwnerRibbon := TImpRibbon(AOwner); Visible := False; Parent := FOwnerRibbon; end; procedure TRibbonMDIButton.Click; var ChildForm: TForm; dwSysCommand: dword; begin if Assigned(FOwnerRibbon.FParentForm) then begin ChildForm := TForm(FOwnerRibbon.FParentForm).ActiveMDIChild; if Assigned(ChildForm) then begin case FButtonKind of mbkMDIMinimize: dwSysCommand := SC_MINIMIZE; mbkMDIRestore: dwSysCommand := SC_RESTORE; mbkMDIClose: dwSysCommand := SC_CLOSE; end; SendMessage(ChildForm.Handle, WM_SYSCOMMAND, dwSysCommand, GetMessagePos); end; end; end; procedure TRibbonMDIButton.DrawImage; var SkinForm: TSkinForm; begin case FButtonKind of mbkMDIMinimize: SkinForm := sfMinimize; mbkMDIRestore: SkinForm := sfRestore; mbkMDIClose: SkinForm := sfClose; end; RibbonStyle.DrawElement(SkinForm, Canvas, ClientRect, -1); end; end.
unit ProdutoHasMateria; interface uses SysUtils, Contnrs, MateriaPrima, Produto; type TProdutoHasMateria = class private Fcodigo_materia: integer; Fcodigo_produto: integer; Fcodigo: integer; FMateriaPrima :TMateriaPrima; FProduto: TProduto; procedure Setcodigo(const Value: integer); procedure Setcodigo_materia(const Value: integer); procedure Setcodigo_produto(const Value: integer); procedure Setproduto(const Value: TProduto); function GetMateriaPrima :TMateriaPrima; function GetProduto :TProduto; public property codigo :integer read Fcodigo write Setcodigo; property codigo_produto :integer read Fcodigo_produto write Setcodigo_produto; property codigo_materia :integer read Fcodigo_materia write Setcodigo_materia; property materia_prima :TMateriaPrima read GetMateriaPrima; property produto :TProduto read GetProduto write Setproduto; end; implementation uses repositorio, fabricaRepositorio; { TProdutoHasMateria } function TProdutoHasMateria.GetMateriaPrima: TMateriaPrima; var Repositorio :TRepositorio; begin Repositorio := nil; try if not Assigned(self.FMateriaPrima) then begin Repositorio := TFabricaRepositorio.GetRepositorio(TMateriaPrima.ClassName); self.FMateriaPrima := TMateriaPrima( Repositorio.Get(self.Fcodigo_materia) ); end; result := self.FMateriaPrima; finally FreeAndNil(Repositorio); end; end; function TProdutoHasMateria.GetProduto: TProduto; var Repositorio :TRepositorio; begin Repositorio := nil; try if not Assigned(self.FProduto) then begin Repositorio := TFabricaRepositorio.GetRepositorio(TProduto.ClassName); self.FProduto := TProduto( Repositorio.Get(self.Fcodigo_produto) ); end; result := self.FProduto; finally FreeAndNil(Repositorio); end; end; procedure TProdutoHasMateria.Setcodigo(const Value: integer); begin Fcodigo := Value; end; procedure TProdutoHasMateria.Setcodigo_materia(const Value: integer); begin Fcodigo_materia := Value; end; procedure TProdutoHasMateria.Setcodigo_produto(const Value: integer); begin Fcodigo_produto := Value; end; procedure TProdutoHasMateria.Setproduto(const Value: TProduto); begin Fproduto := Value; end; end.
{ Invokable interface ISynchroWS } unit SynchroWSIntf; interface uses InvokeRegistry, Types, XSBuiltIns, CommunicationObj; type ISynchroWS = interface(IInvokable) ['{C05DD55B-1CDC-4A72-9055-5FA92CBE0459}'] procedure Set_Pulso_Largo; safecall; procedure Set_Pulso_Corto(PRF_Rate: TxDualPulseEnum); safecall; function Get_Frecuencia: Integer; safecall; function Get_Pulse: TxPulseEnum; safecall; function Get_PRF_Rate: TxDualPulseEnum; safecall; end; implementation initialization InvRegistry.RegisterInterface(TypeInfo(ISynchroWS)); end.
unit ImportGroupTest; interface uses dbTest, dbObjectTest, ObjectTest; type TImportGroupTest = class (TdbObjectTestNew) published procedure ProcedureLoad; override; procedure Test; override; end; TImportGroupObjectTest = class(TObjectTest) function InsertDefault: integer; override; public function InsertUpdateImportGroup(const Id: integer; Name: string): integer; constructor Create; override; end; implementation uses DB, UtilConst, TestFramework, SysUtils, ExternalLoad; { TdbUnitTest } procedure TImportGroupTest.ProcedureLoad; begin ScriptDirectory := ProcedurePath + 'OBJECTS\ImportGroup\'; inherited; end; procedure TImportGroupTest.Test; var Id: integer; RecordCount: Integer; ObjectTest: TImportGroupObjectTest; begin ObjectTest := TImportGroupObjectTest.Create; // Получим список RecordCount := ObjectTest.GetDataSet.RecordCount; // Вставка Типа импорта Id := ObjectTest.InsertDefault; try // Получим список ролей Check(ObjectTest.GetDataSet.RecordCount = (RecordCount + 1), 'Количество записей не изменилось'); finally ObjectTest.Delete(Id); end; end; { TImportGroupTest } constructor TImportGroupObjectTest.Create; begin inherited Create; spInsertUpdate := 'gpInsertUpdate_Object_ImportGroup'; spSelect := 'gpSelect_Object_ImportGroup'; spGet := 'gpGet_Object_ImportGroup'; end; function TImportGroupObjectTest.InsertDefault: integer; begin result := InsertUpdateImportGroup(0, 'Загрузка прихода'); inherited; end; function TImportGroupObjectTest.InsertUpdateImportGroup(const Id: integer; Name: string): integer; begin FParams.Clear; FParams.AddParam('ioId', ftInteger, ptInputOutput, Id); FParams.AddParam('inName', ftString, ptInput, Name); result := InsertUpdate(FParams); end; initialization TestFramework.RegisterTest('Объекты', TImportGroupTest.Suite); end.
{***********************************************************} { Exemplo de lançamento de nota fiscal orientado a objetos, } { com banco de dados Oracle } { Reinaldo Silveira - reinaldopsilveira@gmail.com } { Franca/SP - set/2019 } {***********************************************************} unit U_Produto; interface uses U_BaseControl, System.SysUtils, Data.DB, Vcl.Controls; type TTipoBusca = (tbID, tbDescricao); TProduto = class(TBaseControl) private FPRODUTO_ID: Integer; FPRECO: Double; FDESCRICAO: String; FUNIDADE: String; procedure SetDESCRICAO(const Value: String); procedure SetPRECO(const Value: Double); procedure SetPRODUTO_ID(const Value: Integer); procedure SetUNIDADE(const Value: String); { private declarations } protected { protected declarations } public { public declarations } property PRODUTO_ID: Integer read FPRODUTO_ID write SetPRODUTO_ID; property DESCRICAO: String read FDESCRICAO write SetDESCRICAO; property UNIDADE: String read FUNIDADE write SetUNIDADE; property PRECO: Double read FPRECO write SetPRECO; function BuscaDados(pBusca: Variant; pBuscarPor: TTipoBusca): Boolean; function Pesquisa(pPesq: String = ''): Boolean; end; implementation { TProduto } uses U_Pesquisa; function TProduto.BuscaDados(pBusca: Variant; pBuscarPor: TTipoBusca): Boolean; begin Query.Close; Query.SQL.Clear; Query.SQL.Add('select PRODUTO_ID, '); Query.SQL.Add(' DESCRICAO, '); Query.SQL.Add(' UNIDADE, '); Query.SQL.Add(' PRECO '); Query.SQL.Add('from TB_PRODUTO '); case pBuscarPor of tbID : Query.SQL.Add(Format('where PRODUTO_ID = %d', [Integer(pBusca)])); tbDescricao: Query.SQL.Add(Format('where DESCRICAO = %s', [QuotedStr(pBusca)])); end; Query.Open; Result := not Query.IsEmpty; FPRODUTO_ID := Query.Fields[0].AsInteger; FDESCRICAO := Query.Fields[1].AsString; FUNIDADE := Query.Fields[2].AsString; FPRECO := Query.Fields[3].AsFloat; end; function TProduto.Pesquisa(pPesq: String): Boolean; begin if not Assigned(F_Pesquisa) then F_Pesquisa := TF_Pesquisa.Create(Self); try F_Pesquisa.Caption := 'Pesquisa de Produtos'; F_Pesquisa.SQL_BASE := 'select PRODUTO_ID as "Código", DESCRICAO as "Descrição" from TB_PRODUTO'; F_Pesquisa.SQL_WHERE := 'where DESCRICAO like %s'; F_Pesquisa.SQL_ORDER := 'order by DESCRICAO'; F_Pesquisa.edtPesquisa.Text := pPesq; F_Pesquisa.ShowModal; Result := F_Pesquisa.ModalResult = mrOk; if Result then Result := BuscaDados(F_Pesquisa.ID, tbID); finally FreeAndNil(F_Pesquisa); end; end; procedure TProduto.SetDESCRICAO(const Value: String); begin FDESCRICAO := Value; end; procedure TProduto.SetPRECO(const Value: Double); begin FPRECO := Value; end; procedure TProduto.SetPRODUTO_ID(const Value: Integer); begin FPRODUTO_ID := Value; end; procedure TProduto.SetUNIDADE(const Value: String); begin FUNIDADE := Value; end; end.
unit Tasker.Plugin.Helper; interface type THelper = class {strict} private //// ---------------------------------- HELPER FUNCTIONS -------------------------------- // // // private static Object getBundleValueSafe( Bundle b, String key, Class<?> expectedClass, String funcName ) { // Object value = null; // // if ( b != null ) { // if ( b.containsKey( key ) ) { // Object obj = b.get( key ); // if ( obj == null ) // Log.w( TAG, funcName + ": " + key + ": null value" ); // else if ( obj.getClass() != expectedClass ) // Log.w( TAG, funcName + ": " + key + ": expected " + expectedClass.getClass().getName() + ", got " + obj.getClass().getName() ); // else // value = obj; // } // } // return value; // } // // private static Object getExtraValueSafe( Intent i, String key, Class<?> expectedClass, String funcName ) { // return ( i.hasExtra( key ) ) ? // getBundleValueSafe( i.getExtras(), key, expectedClass, funcName ) : // null; // } // // function hostSupports({extrasFromHost: Bundle;} capabilityFlag: Integer): Boolean; static; // function variableNameIsLocal(varName: string): Boolean; static; public // public static int getPackageVersionCode( PackageManager pm, String packageName ) { // // int code = -1; // // if ( pm != null ) { // try { // PackageInfo pi = pm.getPackageInfo( packageName, 0 ); // if ( pi != null ) // code = pi.versionCode; // } // catch ( Exception e ) { // Log.e( TAG, "getPackageVersionCode: exception getting package info" ); // } // } // // return code; // } // // private static String [] getStringArrayFromBundleString( Bundle bundle, String key, String funcName ) { // // String spec = (String) getBundleValueSafe( bundle, key, String.class, funcName ); // // String [] toReturn = null; // // if ( spec != null ) // toReturn = spec.split( " " ); // // return toReturn; // } // // private static void addStringArrayToBundleAsString( String [] toAdd, Bundle bundle, String key, String callerName ) { // // StringBuilder builder = new StringBuilder(); // // if ( toAdd != null ) { // // for ( String keyName : toAdd ) { // // if ( keyName.contains( " " ) ) // Log.w( TAG, callerName + ": ignoring bad keyName containing space: " + keyName ); // else { // if ( builder.length() > 0 ) // builder.append( ' ' ); // // builder.append( keyName ); // } // // if ( builder.length() > 0 ) // bundle.putString( key, builder.toString() ); // } // } // } // // // state tracking for random number sequence // private static int [] lastRandomsSeen = null; // private static int randomInsertPointer = 0; // private static SecureRandom sr = null; // // * Generate a sequence of secure random positive integers which is guaranteed not to repeat // * in the last 100 calls to this function. // * // * @return a random positive integer // */ // public static int getPositiveNonRepeatingRandomInteger() { // // // initialize on first call // if ( sr == null ) { // sr = new SecureRandom(); // lastRandomsSeen = new int[RANDOM_HISTORY_SIZE]; // // for ( int x = 0; x < lastRandomsSeen.length; x++ ) // lastRandomsSeen[x] = -1; // } // // int toReturn; // do { // // pick a number // toReturn = sr.nextInt( Integer.MAX_VALUE ); // // // check we havn't see it recently // for ( int seen : lastRandomsSeen ) { // if ( seen == toReturn ) { // toReturn = -1; // break; // } // } // } // while ( toReturn == -1 ); // // // update history // lastRandomsSeen[randomInsertPointer] = toReturn; // randomInsertPointer = ( randomInsertPointer + 1 ) % lastRandomsSeen.length; // // return toReturn; // } end; implementation { THelper } uses System.SysUtils; //function THelper.hostSupports(capabilityFlag: Integer): Boolean; //var // Flags: Integer; //begin //// flags := Integer( getBundleValueSafe( extrasFromHost, EXTRA_HOST_CAPABILITIES, Integer.class, "hostSupports" )); //// Result := (Flags != null) and ((flags and capabilityFlag) > 0); //end; // //function THelper.variableNameIsLocal(varName: string): Boolean; //var // digitCount, length: Integer; //begin // digitCount := 0; // length := varName.Length; // // Result := True; // //// for ( int x = 0; x < length; x++ ) { //// char ch = varName.charAt( x ); //// //// if ( Character.isUpperCase( ch ) ) //// return false; //// else if ( Character.isDigit( ch ) ) //// digitCount++; //// } // // if digitCount = (varName.Length - 1) then // Result := False; //end; end.
unit UCheckWin; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, UzLogConst, UzLogGlobal, UzLogQSO; type TCheckWin = class(TForm) Panel1: TPanel; Button3: TButton; ListBox: TListBox; StayOnTop: TCheckBox; procedure Button3Click(Sender: TObject); procedure StayOnTopClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); protected FFontSize: Integer; function GetFontSize(): Integer; virtual; procedure SetFontSize(v: Integer); virtual; private { Private declarations } public { Public declarations } ListCWandPh : boolean; BandRow : array[b19..HiBand] of Integer; procedure ResetListBox; procedure Renew(aQSO : TQSO); virtual; property FontSize: Integer read GetFontSize write SetFontSize; end; implementation uses Main; {$R *.DFM} procedure TCheckWin.Button3Click(Sender: TObject); begin Close; end; procedure TCheckWin.StayOnTopClick(Sender: TObject); begin If StayOnTop.Checked then FormStyle := fsStayOnTop else FormStyle := fsNormal; end; procedure TCheckWin.ResetListBox; var B: TBand; i: Integer; hh: Integer; begin i := 0; for B := b19 to HiBand do begin if (MainForm.BandMenu.Items[ord(B)].Enabled) and (MainForm.BandMenu.Items[ord(B)].Visible) then begin BandRow[B] := i; inc(i); end else BandRow[B] := -1; end; hh := Abs(ListBox.Font.Height) + 2; if ListCWandPh then begin ClientHeight := (hh * 2) * (i) + Panel1.Height + 8; end else begin ClientHeight := hh * (i) + Panel1.Height + 8; end; ListBox.Items.Clear; if ListCWandPh then begin for B := b19 to HiBand do begin if BandRow[B] >= 0 then begin ListBox.Items.Add(FillRight(MHzString[B], 5) + ' CW'); ListBox.Items.Add(FillRight(MHzString[B], 5) + ' Ph'); end; end; end else begin for B := b19 to HiBand do begin if BandRow[B] >= 0 then ListBox.Items.Add(MHzString[B]); end; end; end; procedure TCheckWin.Renew(aQSO: TQSO); begin end; procedure TCheckWin.FormShow(Sender: TObject); begin MainForm.AddTaskbar(Handle); ResetListBox; Renew(Main.CurrentQSO); end; procedure TCheckWin.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_ESCAPE: MainForm.SetLastFocus(); end; end; procedure TCheckWin.FormClose(Sender: TObject; var Action: TCloseAction); begin MainForm.DelTaskbar(Handle); end; procedure TCheckWin.FormCreate(Sender: TObject); begin ListBox.Font.Name := dmZLogGlobal.Settings.FBaseFontName; ListCWandPh := False; end; function TCheckWin.GetFontSize(): Integer; begin Result := FFontSize; end; procedure TCheckWin.SetFontSize(v: Integer); begin FFontSize := v; ListBox.Font.Size := v; ResetListBox(); end; end.