
QuickLib는 Delphi/Firemonkey (Windows, Linux, Android, OSX & IOS) 및 FPC (Windows & Linux) 라이브러리가 흥미롭고 빠르게 구현하는 기능을 포함하고 응용 프로그램 개발을 단순화하고 CrossPlatform 지원을 제공하고 생산성을 향상시킵니다. Delphi XE8 -Delphi 12 아테네 지원.
Github 에서이 프로젝트를 "별"하십시오! 비용은 비용이 들지만 코드를 참조하는 데 도움이됩니다. 
이 프로젝트가 유용하다고 생각되면 기부를 고려하십시오.
기능 영역 :
주요 단위 설명 :
업데이트 :
동일한 코드 단순화 디버그 작업으로 콘솔 앱을 콘솔 모드 또는 서비스 모드로 실행하도록 허용하십시오.
if not AppService.IsRunningAsService then
begin
...your code running as console
end
else
begin
AppService.ServiceName := ' MyService ' ;
AppService.DisplayName := ' MyServicesvc ' ;
// you can pass an anonymous method to events
AppService.OnStart := procedure
begin
...your start code
end ;
AppService.OnExecute := YourExecuteFunction;
AppService.OnStop := YourStopFunction;
AppService.CheckParams;
end ;Azure 및 Amazon Cloud Storage로 Blob 반복을 단순화합니다.
// connect to a Azure blobstorage
QuickAzure := TQuickAzure.Create(AzureAccountName,AzureAccountKey);
// download a blob file to a stream
done := QuickAzure.GetBlob( ' MyContainer ' , ' MyFile.jpg ' ,ResponseInfo,MyStream);
// check if exists a folder
found := ExistFolder( ' MyContainer ' , ' /Public/Documents/Personal ' );
// list blobs starting with a pattern (recursively or not)
for azBlob in ListBlobs( ' MyContainer ' , ' /Public/Documents ' ,Recursive,ResponseInfo) do
begin
if azBlob.Size > 1000 then Showmessage(azBlob. Name );
end ;CIDR 및 IP 범위 기능.
// convert ip string to integer
IPv4ToInt( ' 192.168.1.10 ' );
// get first and last ip of a subnet scope
GetIpRange( ' 192.168.100.0 ' , ' 255.255.255.0 ' ,LowIp,HighIP);개발자의 일상에서 자주 필요한 기능.
// coverts UTC time TDateTime to Local date time
UTCToLocalTime(MyUTCTime);
// generate a 10 char length random password with alfanumeric and signs.
RandomPassword( 10 ,[pfIncludeNumbers,pfIncludeSigns]);
// Capitalize every word of a phrase
CapitalizeAll( ' the grey fox ' ); // returns "The Grey Fox"
// Simple TCounter and TTimeCounter for loops
counter := TCounter;
counter.Init( 200 );
timecounter : TTimeCounter;
timecounter.Init( 10000 );
while true do
begin
Inc(n);
{ your procedural process here }
// every 200 steps writes to console
if counter.Check then writeln(Format( ' Processed %d entries ' ,[n]));
// every 10 seconds writes to console
if timecounter.Check then writeln( ' Im working... ' );
end ;크로노 미터 및 벤치 마크 코드는 간단합니다.
// get elapsed time execution of a code part
Chrono := TChronometer.Create(False);
Chrono.Start;
...code you need benchmark
Chrono.Stop;
// shows elapsed time in LongTime format (2 hour(s) and 10 minute(s))
Showmessage(Chrono.TimeElapsed(True));
// shows elapsed time in ShortTime format (02:10:00)
Showmessage(Chrono.TimeElapsed(False));
// get benchmak info of a process
Chrono := TChronoBenchMark.Create;
Chrono.TotalProcess := 100000 ;
for i := 1 to 10000 do
begin
{ your process here }
Chrono.CurrentProcess := i;
// shows estimated time your process will take in x hour(s), x minute(s) x second(s) format
writeln(Chrono.EstimatedTime(True));
// shows speed: num items per second processed of your process
writeln(Format( ' Items processed %d/sec ' ,[Chrono.Speed]));
end ;
writeln(Chrono.ElapsedTime(False)); // shows total time elapsed in 00:00:00 format 색상 등으로 콘솔에 로그 메시지를 작성하십시오 ...
// define which level of output needed
Console.Verbose := LOG_DEBUG;
// writes line to console in red color
cout( ' Error x ' ,etError);
// writes formatted line in green color
coutFmt( ' Proccess %s finished ' ,[ProccesName],etSuccess);
// writes integer
cout( 12348 );
// Connect a QuickLog and write to disk and screen with one line of code (with independent verbose levels)
MyQuickLog := TQuickLog.Create;
MyQuickLog.Verbose := LOG_ALL;
Console.Verbose := LOG_ONLYERRORS;
Console.Log := MyQuickLog;장황 레벨과 매일 또는 최대 공간 회전으로 디스크 또는 메모리에 로그를 작성하십시오.
// write a header on start with info as running path, appname, debugmode, user, etc...
Log.ShowHeader := True;
// sets log with rotation at 20MB
Log.SetLog( ' .mylog.log ' ,False, 20 );
// write an error message
Log.Add( ' Error x ' ,etError);
// write formatted error message
Log.Add( ' Error is %s ' ,[ErrorStr],etError);구성을 JSON 또는 YAML 파일 또는 Windows 레지스트리 키로로드/저장하십시오. TappConfigjson, TappConfigyaml 또는 TappConfigReistry에서 Descend 클래스를 만들고 추가 된 속성이로드/저장됩니다. 파일 구성을 감지 할 때 파일 구성을 다시로드 할 수 있습니다.
// create a class heritage
TMyConfig = class (TAppConfigJson)
private
fName : string;
fSurname : string;
fStatus : Integer;
published
property Name : string read fName write fName;
property SurName : string read fSurname write fSurname;
property Status : Integer read fStatus write fStatus;
end ;
// create your config to json file
// Add Quick.Config.Json to your uses
MyConfig := TMyConfig.Create( ' Config.json ' );
MyConfig.Provider.CreateIfNotExists := True;
MyConfig.Provider.ReloadIfFileModified := True;
MyConfig. Name := ' John ' ;
MyConfig.Surname := ' Smith ' ;
// load
MyConfig.Load;
// save
MyConfig.Save;
// create your config to Windows Registry
// Add Quick.Config.Registry to your uses
MyConfig := TMyConfig.Create;
// Define Registry as HKEY_CURRENT_USERSoftwareMyApp
MyConfig.HRoot := HKEY_CURRENT_USER;
MyConfig.MainKey := ' MyApp ' ;
MyConfig. Name := ' John ' ;
MyConfig.Surname := ' Smith ' ;
// load
MyConfig.Load;
// save
MyConfig.Save;
// Create a custom Config with no default provider
TMyConfig = class (TAppConfig)
...your properties
end ;
MyConfig := TMyConfig.Create(TAppConfigJsonProvider.Create( ' .config.json ' );
변경 사항에 대한 파일을 모니터링하고 이벤트를 던집니다.
FileMonitor.Filename := ' .myfile.txt ' ;
// check file changes every 2 seconds
FileMonitor.Interval := 2000 ;
// watch for deleted or modified file events
FileMonitor.Notifies := [mnFileModified, mnFileDeleted)];
FileMonitor.OnFileChange := MyFileChangeFunction;
FileMonitor.Enabled := True;JSON 객체와 함께 작업하기위한 util.
// When unit declared in uses, a TObject Helper allows all your objects to be loaded or saved to/from json string
MyObject.FromJson := jsonstring;
MyString := MyObject.ToJson;
// You can clone simple objects with clone function
MyObject1.Clone(MyObject2);두 개의 코드 줄이있는 이메일을 보내십시오.
// Send email
SMTP := TSMTP.Create( ' mail.domain.com ' , 25 ,False);
SMTP.SendMail( ' [email protected] ' , ' [email protected] ' , ' Email subject ' , ' My message body ' );
// You can define more advanced options
SMTP.SenderName := ' John ' ;
SMTP.From := ' [email protected] ' ;
SMTP.Recipient := ' [email protected],[email protected] ' ;
SMTP.Subject := ' Email subject ' ;
SMTP.AddBodyFromFile := ' .body.html ' ;
SMTP.CC := ' [email protected] ' ;
SMTP.BCC := ' [email protected] ' ;
SMTP.Attachments.Add( ' .notes.txt ' );
SMTP.SendMail;스레드 안전 수업.
TTHREADEDQUEUECS : 중요한 섹션이있는 TthreadedDeque의 버전.
tthreadobjectList : 스레드 안전 객체 목록.
tthreadedqueuelist : 스레드 안전 큐 목록. 자가 활동 및 임계 섹션.
tanonymousthread : 익명의 실행을 정의하는 익명의 스레드를 만듭니다. 코드가 UI를 업데이트 해야하는 경우 execute_sync 및 onterminate_sync 메소드를 사용하십시오.
// simple anonymousthread
TAnonymousThread.Execute(
procedure
var
i : Integer;
begin
for i := 0 to 10 do cout( ' Working %d ' ,[i],etTrace);
cout( ' executed thread ' ,etSuccess);
end )
.OnTerminate(
procedure
begin
cout( ' terminated thread ' ,etSuccess);
cout( ' PRESS <ENTER> TO EXIT ' ,etInfo);
end )
.Start;Truntask : 결함 및 재시험 제어 정책이있는 자동 단일 작업 스레드를 시작하십시오. 매개 변수를 전달하여 코드로 만들 수 있습니다.
TRunTask.Execute(
procedure(task : ITask)
var
stream : TStringStream;
response : IHttpRequestResponse;
begin
stream := TStringStream.Create;
try
response := TJsonHttpClient(task[ ' httpclient ' ].AsObject).Get(task[ ' url ' ]);
task.Result := response.StatusCode;
if response.StatusCode <> 200 then raise Exception.Create(response.StatusText);
finally
stream.Free;
end ;
end )
.SetParameter( ' httpclient ' ,(TJsonHttpClient.Create),True)
.SetParameter( ' url ' , ' https://mydomain.com/testfile ' )
.WaitAndRetry( 5 , 250 , 2 )
.OnRetry(
procedure(task : ITask; aException : Exception; var vStopRetries : Boolean)
begin
// if error 404 don't try to retry request
if task.Result = 404 then vStopRetries := True;
end )
.OnException(
procedure(task : ITask; aException : Exception)
begin
coutFmt( ' Exception downloading (Error: %s / StatusCode: %d)... ' ,[aException.Message,task.Result.AsInteger],etError);
end )
.OnTerminated(
procedure(task : ITask)
begin
if task.Done then coutFmt( ' Download "%s" finished ok ' ,[task[ ' url ' ].AsString],etSuccess)
else coutFmt( ' Download "%s" failed after %d retries ' ,[task[ ' url ' ].AsString,task.NumRetries],etError);
end )
.Run;Tbackgroundstasks : 결함 및 재시도 제어 정책을 가진 동시 작업자 수를 허용하는 백그라운드에서 작업을 시작합니다. 코드가 UI를 업데이트 해야하는 경우 addtask_sync 및 onterminate_sync 메소드를 사용하십시오.
backgroundtasks := TBackgroundTasks.Create( 10 );
for i := 1 to 100 do
begin
mytask := TMyTask.Create;
mytask.Id := i;
mytask. Name := ' Task ' + i.ToString;
backgroundtasks.AddTask([mytask],False,
procedure(task : ITask)
begin
cout( ' task %d started ' ,[TMyTask(task.Param[ 0 ].AsObject).Id],etDebug);
TMyTask(task.Param[ 0 ].AsObject).DoJob;
end
).WaitAndRetry([ 250 , 2000 , 10000 ])
).OnException(
procedure(task : ITask; aException : Exception)
begin
cout( ' task %d failed (%s) ' ,[TMyTask(task.Param[ 0 ].AsObject).Id,aException.Message],etError);
end
).OnTerminated(
procedure(task : ITask)
begin
cout( ' task %d finished ' ,[TMyTask(task.Param[ 0 ].AsObject).Id],etDebug);
TMyTask(task.Param[ 0 ].AsObject).Free;
end
).Run;
end ;
backgroundtasks.Start;Tscheduledtasks : 타이머 대안. 시작 시간, 반복 옵션 및 만료 날짜 및 실패 및 재시험 제어 정책으로 작업을 할당 할 수 있습니다. 코드가 UI를 업데이트 해야하는 경우 addtask_sync, onterminate_sync 및 onexpired_sync를 사용하십시오. 실행, 예외, 종료 및 만료 이벤트에 익명의 방법을 할당 할 수 있습니다.
myjob := TMyJob.Create;
myjob. Name := Format( ' Run at %s and repeat every 1 second until %s ' ,[DateTimeToStr(ScheduledDate),DateTimeToStr(ExpirationDate)]);
scheduledtasks.AddTask( ' Task1 ' ,[myjob],True,
procedure(task : ITask)
begin
cout( ' task "%s" started ' ,[TMyTask(task.Param[ 0 ]). Name ],etDebug);
TMyJob(task.Param[ 0 ]).DoJob;
end
).OnException(
procedure(task : ITask; aException : Exception)
begin
cout( ' task "%s" failed (%s) ' ,[TMyJob(task.Param[ 0 ]). Name ,aException.Message],etError);
end
).OnTerminated(
procedure(task : ITask)
begin
cout( ' task "%s" finished ' ,[TMyJob(task.Param[ 0 ]). Name ],etDebug);
end
).OnExpired(
procedure(task : ITask)
begin
cout( ' task "%s" expired ' ,[TMyJob(task.Param[ 0 ]). Name ],etWarning);
end
).StartAt(ScheduledDate
).RepeatEvery( 1 ,TTimeMeasure.tmSeconds,ExpirationDate);
scheduledtasks.Start;최대 회수를 정의하고, 회복과 회로 중단 메카 니즘 사이의 대기 시간을 정의하는 실패 및 재 시정 정책을 관리합니다.
Windows 프로세스를 관리합니다.
// kill explorer process
KillProcess( ' explorer.exe ' );
// determine if an application is running
if IsProcessRunning( ' explorer.exe ' ) then Showmessage( ' Explorer is running! ' );
// get username who is running an exe
writeln( ' Explorer.exe open by: ' + GetProcessUser( ' explorer.exe ' );
// gets handle of a window with a 20 seconds timeout
if FindWindowTimeout( ' MainWindow ' , 20 ) then writeln( ' Window detected ' );Windows 서비스를 관리합니다.
// detect if a service is installed
if not ServiceIsPresent( ' localhost ' , ' MySvc ' ) then raise Exception.Create( ' Service not installed! ' );
// Start a service
ServiceStart( ' localhost ' , ' MySvc ' );
// Uninstall a service
ServiceUninstall( ' MySvc ' );문자열 형식.
// Format bytes to MB, GB, TB...
FormatBytes( 50000 ) // shows 50KB
FormatBytes( 90000000 ) // shows 90MB /json 텍스트에서 객체를 직렬화합니다. 공개 또는 게시 된 것이 처리 될지 정의 할 수 있습니다 (Delphi, FPC RTTI 만 게시 된 속성을 지원합니다).
json := ' {"name":"Peter","age":30} ' ;
serializer := TJsonSerializer.Create(TSerializeLevel.slPublishedProperty);
try
serializer.JsonToObject(user,json);
finally
serializer.Free;
end ;한 클래스에서 다른 클래스로의지도 필드. 사용자 정의 매핑이 다른 필드 및 사용자 정의 매핑 절차와 일치하도록 허용하여 필드를 수동으로 캐스팅/변환합니다.
// Map values from User1 to User2
TMapper<TUser2>.Map(User);
// Map custom mappings
AutoMapper := TAutoMapper<TUser,TUser2>.Create;
// option1: you can define auto map different named properties
AutoMapper.CustomMapping.AddMap( ' Cash ' , ' Money ' );
AutoMapper.CustomMapping.AddMap( ' Id ' , ' IdUser ' );
// option2: you can decide to modify each property manually or allow to auto someones
AutoMapper.OnDoMapping := procedure( const aSrcObj : TUser; const aTargetName : string; out Value : TFlexValue)
begin
if aTargetName = ' Money ' then Value := aSrcObj.Cash * 2
else if aTargetName = ' IdUser ' then Value := aSrcObj.Id;
end ;
// option3: you can modify some properties after automapping done
AutoMapper.OnAfterMapping := procedure( const aSrcObj : TUser; aTgtObj : TUser2)
begin
aTgtObj.Money := aSrcObj.Cash * 2 ;
aTgtObj.IdUser := aSrcObj.Id;
end ;
User2 := AutoMapper.Map(User);JSON 직렬화 및 매핑 함수가 포함 된 DTO 클래스로 사용됩니다.
type
TUser = class (TJsonRecord)
private
fName : string;
fAge : Integer;
published
property Name : string read fName write fName;
property Age : Integer read fAge write fAge;
end ;
var
user, user2 : TUser;
begin
user := TUser.Create;
// show as json string
Writeln(user.ToJson);
// mapping to other class
user.Mapto(User2);
Writeln(user2.ToJson);
// load from file
user.LoadFromFile( ' .user.json ' );
// save to file
user2.SaveToFile( ' .user2.json ' );
end ;인덱싱 또는 검색 기능이있는 목록이 향상되었습니다.
var
users : TIndexedObjectList<TUser>;
begin
users := TIndexedObjectList<TUser>.Create(True);
// create index by property "Name"
users.Indexes.Add( ' Name ' , ' Name ' ,TClassField.cfProperty);
// create index by private field "Id"
users.Indexes.Add( ' Id ' , ' fId ' ,TClassField.cfField);
// get user by "Name" index
writeln(users.Get( ' Name ' , ' Peter ' ).SurName);
end ;FlexValue는 모든 데이터 유형을 저장하고 통합 연산자 및 자동 비용으로 다른 클래스로 패스를 허용합니다.
var
value : TFlexValue;
str : string;
num : Integer;
begin
value := ' hello ' ;
str := value ;
value := 123 ;
num := value ;
end ;개선 된 배열.
txarray : tlist와 같은 메소드가있는 배열.
var
users : TXArray<TUser>;
begin
users.Add(User);
if users.Count:= TIndexedObjectList<TUser>.Create(True);
// create index by property "Name"
users.Indexes.Add( ' Name ' , ' Name ' ,TClassField.cfProperty);
// create index by private field "Id"
users.Indexes.Add( ' Id ' , ' fId ' ,TClassField.cfField);
// get user by "Name" index
writeln(users.Get( ' Name ' , ' Peter ' ).SurName);
end ;tflexarray : 다른 값 유형을 동일한 배열로 저장할 수있는 것보다 tlist와 같은 메소드가있는 배열.
var
flexarray : TFlexArray;
begin
flexarray.Add( 10 );
flexarray.Add( ' Hello ' );
user := TUser.Create;
try
user. Name := ' Joe ' ;
flexarray.Add(user);
cout( ' Integer Item = %d ' ,[flexarray[ 0 ].AsInteger],etInfo);
cout( ' String Item = %s ' ,[flexarray[ 1 ].AsString],etInfo);
cout( ' Record Item = %s ' ,[TUser(flexarray[ 2 ]). Name ],etInfo);
finally
user.Free;
end ;
end ;TflexPairArray : 다른 값 유형을 동일한 배열에 저장할 수있는 것보다 tlist와 같은 메소드가있는 배열 및 항목 이름으로 검색합니다.
var
flexarray : TFlexPairArray;
begin
flexarray.Add( ' onenumber ' , 10 );
flexarray.Add( ' other ' , ' Hello boy! ' );
user := TUser.Create;
try
user. Name := ' Joe ' ;
flexarray.Add( ' myuser ' ,user);
cout( ' Integer Item = %d ' ,[flexarray.GetValue( ' onenumber ' ).AsInteger],etInfo);
cout( ' String Item = %s ' ,[flexarray.GetValue( ' other ' ).AsString],etInfo);
cout( ' Record Item = %s ' ,[TUser(flexarray.GetValue( ' myuser ' )). Name ],etInfo);
finally
user.Free;
end ;
end ;YAML 객체 구조.
tyamlobject : Yaml 객체는 yamlvalue 쌍의 배열입니다.
// create Yaml object from yaml text
yamlobj.ParseYamlValue(aYaml)
// add a pair
yamlobj.AddPair( ' Name ' , ' Mike ' );
// display as yaml structure
Writeln(yamlobj.ToYaml);Tyamlarray : 물체 또는 스칼라의 배열.
yamlarray.AddElement(TYamlPair.Create( ' Age ' , 30 ));
yamlobj.AddPair( ' myarray ' ,yamlarray);TyamlPair : 이름 값 쌍. 값은 물체, 배열 또는 스칼라 일 수 있습니다.
n := yamlobj.GetPair( ' Name ' ). Value as TYamlInteger;/yaml에서 객체를 직렬화/사형화하십시오.
// Serialize
text := YamlSerializer.ObjectToYaml(obj);
// Deserialize
YamlSerializer.YamlToObject(obj,yamltext);표현식을 사용하여 객체 속성 또는 단일 값을 평가합니다.
if TExpressionParser.Validate(user,( ' (Age > 30) AND (Dept.Name = "Financial") ' ) then
begin
// do something
end ;
if TExpressionParser.Validate(user,( ' (20 > 30) OR (5 > 3) ' ) then
begin
// do something
end ;LINQ를 TOBJECTLIST, TLIST, TARRAY 및 TXARRAY에 쿼리하여 SQL 구문과 같은 Complex별로 선택하여 목록을 통해 업데이트 및 주문합니다. Clauses는 네임 스페이스를 사용하여 중첩 특성을 결정합니다. LINQ는 속성 배열로 요소를 검색 할 수 있습니다. 이제 Tarray 도우미를 포함하여 정기적 인 표현식으로 배열에 추가, 제거 및 검색을 포함합니다.
// Select multi conditional
for user in TLinq<TUser>.From(userslist).Where( ' (Name = ?) OR (SurName = ?) OR (SurName = ?) ' ,[ ' Peter ' , ' Smith ' , ' Huan ' ]).Select do
begin
// do something
end ;
// Select like and update field
TLinq<TUser>.From(userlist).Where( ' SurName Like ? ' ,[ ' %son ' ]).SelectFirst. Name := ' Robert ' ;
// Select top and Order by field
for user in TLinq<TUser>.From(userlist).Where( ' Age > ? ' ,[ 18 ]).SelectTop( 10 ).OrderBy( ' Name ' ) do
begin
// do something
end ;
// update fields by conditional
TLinq<TUser>.From(userlist).Where( ' Name = ? ' ,[ ' Peter ' ]).Update([ ' Name ' ],[ ' Joe ' ]);
// count results
numusers := TLinq<TUser>.From(userlist).Where( ' (Age > ?) AND (Age < ?) ' ,[ 30 , 40 ]).Count;Tcustomhttpserver는 Httprequest 및 Httpresponse 구현을 갖춘 간단한 인터페이스 httpserver입니다. 사용자 정의 오류 페이지에서 사용자 정의 페이지 및 동적 오류 페이지를 반환 할 수 있습니다. thttpserver는 Indyhttpserver 구현이지만 직접 정의 할 수 있습니다.
TMyHttpServer = class (THttpServer)
public
procedure ProcessRequest (aRequest: IHttpRequest; aResponse: IHttpResponse); override;
end ;
procedure TMyHttpServer.ProcessRequest (aRequest: IHttpRequest; aResponse: IHttpResponse);
begin
aResponse.ContentText := ' Hello world! ' ;
end ;만료 시간으로 객체 또는 문자열을 캐시 하여이 정보를 매번 생성하지 않으려면 (데이터베이스 쿼리, 정보를 계산하기 어려운 등). tmemoryCache를 사용하면 객체와 문자열을 캐시 할 수 있습니다. 일반 버전 tmemoryCache를 사용하면 정의 된 유형 만 캐시 할 수 있습니다.
// create MemoryCache with 10 seconds purge interval
cache := TMemoryCache.Create( 10 );
// create MemoryCache for a type
cache := TMemoryCache<TMyObj>.Create; // set string to cache without expiration
cache.SetValue( ' mystring ' , ' hello world ' );
// set string to cache with expiration to 10 seconds
cache.SetValue( ' mystring ' , ' this cache will expire in 10 seconds ' ;
// set object to cache
cache.SetValue( ' Obj1 ' ,valueobj); // get string query result
cache.GetValue( ' Query12 ' );
// get integer
cache.TryGetValue<Integer>( ' number ' ,valueint);
// get object
cache.TryGetValue( ' Obj1 ' ,valueobj);removeValue : 캐시에서 객체를 제거합니다.
캐시 엔진 제공 업체 :
tcacheserializerjson : json을 사용하여 캐시 데이터를 시리얼링합니다.
tcachecompressorgzip : GZIP를 사용하여 캐시 데이터를 압축합니다.
tcachecompressorlzo : lzo를 사용하여 캐시 데이터를 압축합니다.
// create MemoryCache with 20 seconds purge interval and compression with LZO engine
cache := TMemoryCache.Create( 10 , nil ,TCacheCompressorLZO.Create);Control Manager의 역전을 사용하면 Interfaced O Instanced Object 또는 Autoince -in Autoinject를 생성자 클래스에서 자동으로 내릴 수 있습니다.
의존성 주입을 관리하기위한 컨테이너를 만듭니다.
iocContainer := TIocContainer.Create;등록 유형 :
주입하기 전에 유형을 등록해야합니다. 유형은 일시적인 싱글 톤으로 등록 할 수 있습니다. 싱글 톤 : 수명주기는 글로벌 변수와 유사한 모든 주사의 단일 인스턴스가됩니다. 과도 : 수명주기는 각 주입 당 하나의 인스턴스가됩니다. 과도로 컨테이너에 인터페이스 유형을 등록하십시오.
iocContainer.RegisterType<IMultService,TMultService>.AsTransient;인터페이스 유형을 싱글 톤으로 등록하고 건설 위임 :
iocContainer.RegisterType<ISumService,TSumService>.AsSingleTon.DelegateTo(
function : TSumService
begin
Result := TSumService.Create;
end
);인스턴스 등록 :
명명 된 인스턴스 객체를 일시적으로 위임, 구성 위임으로 등록하십시오.
iocContainer.RegisterInstance<TDivideService>( ' one ' ).AsTransient.DelegateTo(
function : TDivideService
begin
Result := TDivideService.Create(True);
end
);등록 옵션 :
등록 IOPTIONS (싱글 톤 만) :
iocContainer.RegisterOptions<TMyOptions>(MyOptions);유형 해결 :
ABTRESTORY : 종속성 주입으로 모든 Creation Method 매개 변수를 해결하려는 클래스를 만듭니다.
MyClass := iocContainer.AbstractFactory<TMyBaseClass>(TMyClass);인터페이스 종속성 해결 :
multservice := iocContainer.Resolve<IMultService>;
result := multservice.Mult( 2 , 4 );인스턴스 해결 :
이름이 지정된 인스턴스 종속성을 해결하십시오.
divideservice := iocContainer.Resolve<TDivideService>( ' other ' );
result := divideservice.Divide( 100 , 2 );인터페이스 인스턴스는 자동으로 해제되지만 인스턴스 종속성은 싱글 톤으로 정의 된 경우에만 해제되며 과도 인스턴스는 코드에 의해 파괴됩니다.
섹션을 클래스로 정의하고 단일 파일 설정으로 저장합니다. DotNet 옵션과 유사하게 작동합니다. 옵션 파일은 JSON 또는 YAML 형식으로 가능합니다.
옵션 클래스를 정의하십시오. 옵션 클래스를 정의하십시오. 소유권에서 상속 된 옵션 클래스를 정의하면 게시 된 모든 속성이로드/저장됩니다. JSONSERIALIZER 및 변경시 다시로드 옵션 컨테이너를 만듭니다.
Options := TOptionsContainer.Create( ' .options.conf ' ,TJsonOptionsSerializer.Create,True);컨테이너 옵션에 섹션을 추가하십시오.
Options.AddSection<TLoggingOptions>( ' Logging ' )옵션 구성 :
섹션 이름을 정의하여 파일에 저장하고 구성 기본 설정을 위임하고 값을 확인할 수 있습니다.
Options.AddSection<TLoggingOptions>( ' Logging ' ).ConfigureOptions(
procedure(aOptions : TLoggingOptions)
begin
aOptions.Path := ' C: ' ;
end
).ValidateOptions;옵션 유효성 검증 :
유효성 검사 옵션을 사용하면 옵션 설정이 정의 된 범위간에 설정되어 있는지 확인할 수 있습니다. 이 유효성 검사는 이전에 지정된 사용자 지정 속성이 귀하의 Toptions 클래스의 속성에 필요합니다.
TLoggingOptions = class (TOptions)
private
fPath : string;
published
[Required, StringLength( 255 , ' Path too long ' )]
property Path : string read fPath write fPath;
[Range( 0.0 , 5.2 )]
property Level : Double read fLevel write fLevel;
end ;옵션 사용 : 옵션 섹션을 검색하려면 :
LoggingOptions := Options.GetSection<TLoggingOptions>;
LoggginOptions.Path := ' C:Path ' ;IOPTIONS 사용 : IOPTIONS는 종속성 주입 가능한 인터페이스입니다. IOCCONCONTAINER.REGISTEROPTIONS에 등록하여 생성자 방법에 주입 할 수 있습니다.
UIOptions := Options.GetSectionInterface<TUIOptions>. Value ;
UIOptions.WindowColor := clBlue;로드/저장 옵션 :
파일 설정에서로드 옵션 :
options.Load;파일 설정에 옵션 저장 :
options.Save;ReloadonChanged 매개 변수로 컨테이너 생성을 정의하면 파일 설정이 변경 될 때마다 구성이 다시로드됩니다. 다시로드 할시기를 제어 해야하는 경우 이벤트를들을 수 있습니다.
Options.OnFileModified := procedure
begin
cout('Detected config file modification!',etWarning);
end;
연결 풀, 스레드 또는 데이터베이스 연결, HTTP 클라이언트 등과 같은 리소스 소비를 피하기 위해 제어 할 객체 정의 ...
HTTP 클라이언트 풀 만들기 :
pool := TObjectPool<THTTPClient>.Create( 5 , 5000 ,procedure( var aInstance : THTTPClient)
begin
aInstance := THTTPClient.Create;
aInstante.UserAgent := ' MyAgent ' ;
end );수영장에서 물체 가져 오기 :
httpcli := pool.Get.Item;
statuscode := httpcli.Get( ' https://www.mydomain.com ' ).StatusCode;LINQ 지원을 상속받은 인터페이스 목록 및 ObjectList를 정의합니다.
myarray := [ ' Joe ' , ' Mat ' , ' Lee ' ];
// search for regex match
cout( ' Search for regex match ' ,ccYellow);
for name in myarray.Where( ' e$ ' ,True).Select do
begin
cout( ' User %s ends with "e" ' ,[ name ],etInfo);
end ;user := ListObj.Where( ' Profile.Name = ? ' ,[ ' Lee ' ]).SelectFirst;항목 배열에 대한 표현 검색 :
users := ListObj.Where( ' Roles CONTAINS ? ' ,[ ' SuperAdmin ' ]).Select;술어 검색 :
user := ListObj.Where(function(aUser : TUser) : Boolean
begin
Result := aUser. Name .StartsWith( ' J ' );
end ).SelectFirst;
if user <> nil then cout( ' %s starts with J letter ' ,[user. Name ],etInfo);허용 된 더 많은 기능을 보려면 Quick.linq 섹션을 참조하십시오.
문자열 템플릿 사전 또는 대표 기능을 사용하여 대체합니다. 인용 된 토큰 숯을 지정할 수 있습니다.
사전 전달 교체 :
dict := TDictionary<string,string>.Create;
dict.Add( ' User ' , ' John ' );
dict.Add( ' Age ' , ' 20 ' );
dict.Add( ' SurName ' , ' Peterson ' );
mytemplate := ' User {{User}} {{SurName}} are {{Age}} years old. ' ;
template := TStringTemplate.Create( ' {{ ' , ' }} ' ,dict);
Result := template.Replace(mytemplate);대표 기능으로 교체하십시오.
mytemplate := ' User {{User}} {{SurName}} are {{Age}} years old. ' ;
template := TStringTemplate.Create( ' {{ ' , ' }} ' ,function( const aToken : string) : string
begin
if token = ' User ' then Result := ' John '
else if token = ' Surname ' then Result := ' Peterson '
else if token = ' Age ' then Result := ' 20 ' ;
end );
Result := template.Replace(mytemplate);디버그 UTIL을 확인하고 실적을 확인하고 입력 및 종료 메소드 체크 포인트를 구하십시오. 디버그 컴파일러 지시문으로 정의하여 앱이 디버그 모드에서 컴파일 될 때만 활성화되도록하십시오. 콘솔에서 앱은 기본적으로 콘솔을 사용합니다. 로거를 전달하여 출력 할 수 있습니다.
TDebugUtils.SetLogger(ilogger);코드의 일부를 추적하십시오.
function TCalculator.Subs (a, b: Int64): Int64;
begin
{ $IFDEF DEBUG }
TDebugger.Trace(Self,Format( ' Substract %d - %d ' ,[a,b]));
{ $ENDIF }
Result := a - b;
// simulate working for 200ms
Sleep( 200 );
end ;
// Returns:
// 29-06-2020 23:31:41.391 [TRACE] TCalculator -> Substract 30 - 12포인트에서 종료 기능으로 처리 시간을 계산합니다.
function TCalculator.Sum (a, b: Int64): Int64;
begin
{ $IFDEF DEBUG }
TDebugger.TimeIt(Self, ' Sum ' ,Format( ' Sum %d + %d ' ,[a,b]));
{ $ENDIF }
Result := a + b;
// simulate working for 1 seconds
Sleep( 1000 );
end ;
// Returns:
// 29-06-2020 22:58:45.808 [CHRONO] TCalculator.Sum -> Sum 100 + 50 = 1,00s포인트마다 처리 시간을 계산하고 기능을 종료합니다.
function TCalculator.Divide (a, b: Int64): Double;
begin
{ $IFDEF DEBUG }
var crono := TDebugger.TimeIt(Self, ' Divide ' ,Format( ' Divide %d / %d ' ,[a,b]));
{ $ENDIF }
Result := a / b;
// simulate working for 500ms
Sleep( 500 );
{ $IFDEF DEBUG }
crono.BreakPoint( ' Only divide ' );
{ $ENDIF }
// simulate working for 1 second
Sleep( 1000 );
{ $IFDEF DEBUG }
crono.BreakPoint( ' Only Sleep ' );
{ $ENDIF }
end ;
// Returns:
// 29-06-2020 23:25:46.223 [CHRONO] TCalculator.Divide -> First point = 500,18ms
// 29-06-2020 23:25:47.224 [CHRONO] TCalculator.Divide -> Second point = 1,00s
// 29-06-2020 23:25:47.225 [CHRONO] TCalculator.Divide -> Divide 10 / 2 = 1,50s기능을 입력하고 종료 할 때 알림을 받고 시간을 보내십시오.
function TCalculator.Mult (a, b: Int64): Int64;
begin
{ $IFDEF DEBUG }
TDebugger.Enter(Self, ' Mult ' ).TimeIt;
{ $ENDIF }
Result := a * b;
// simulate working for 2 seconds
Sleep( 2000 );
end ;
// Returns:
// 29-06-2020 22:58:45.808 [ENTER] >> TCalculator.Mult
// 29-06-2020 22:58:47.810 [EXIT] >> TCalculator.Mult in 2,00s CommandLine 매개 변수로 작업하는 것은 CommandLine 확장자를 사용하는 것이 쉽습니다. tparameters 또는 tserviceparameters (QuickAppServices로 작업하는 경우)에서 상속 된 클래스를 게시 한 속성으로 가능한 인수로 정의하십시오.
uses
Quick.Parameters;
type
TCommand = (Copy, Move, Remove);
TMyMode = (mdAdd, mdSelect, mdRemove);
[CommandDescription( ' Simple console application example with Quick.Parameters ' )]
TMyParameter = class (TParameters)
private
fCommand : TCommand;
fHost : string;
fPort : Integer;
fRetries : Integer;
fUseTCP : Boolean;
fConfigFile: string;
fSilent: Boolean;
fMyMode: TMyMode;
fLogErrorsConsole: Boolean;
fLogErrors: Boolean;
fShowReport: Boolean;
published
[ParamCommand( 1 )]
[ParamRequired]
[ParamHelp( ' Command action. ' , ' command-action ' )]
property Command : TCommand read fCommand write fCommand;
[ParamName( ' HostName ' ),ParamRequired]
[ParamHelp( ' Define host to connect. ' , ' host ' )]
property Host : string read fHost write fHost;
[ParamName( ' Port ' , ' p ' )]
[ParamValueIsNextParam]
[ParamHelp( ' Define Port to connect (default 80) ' , ' port ' )]
property Port : Integer read fPort write fPort;
[ParamHelp( ' Number of max retries. ' )]
property Retries : Integer read fRetries write fRetries;
[ParamHelp( ' Path to config. ' , ' path ' )]
[ParamName( ' Config-file ' )]
property ConfigFile : String read fConfigFile write fConfigFile;
[ParamHelp( ' Silent mode. ' )]
property Silent : Boolean read fSilent write fSilent;
[ParamHelp( ' Modes (mdAdd, mdSelect, mdRemove) ' )]
property Mode : TMyMode read fMyMode write fMyMode;
end ;
Param 사용 :
params := TMyParameter.Create;-HELP로 EXE를 호출하면 문서가 나타납니다. 스위치 또는 값을 확인 해야하는 경우 다음과 같은 작업을 수행 할 수 있습니다.
if params.Port = 0 then ...
if params.Silent then ...QuickParameters는 사용자 정의 속성을 사용하여 특수 매개 변수 조건을 정의합니다.
CommandDescription : 도움말 문서에서 응용 프로그램을 설명하기 위해 텍스트를 정의합니다.
ParamCommand (Number) : 단일 매개 변수에 대한 정적 위치를 CommandLine으로 정의합니다.
paramname (이름, 별칭) : 매개 변수의 다른 이름을 정의합니다. 클래스 속성에 허용되지 않는 특수 문자 (파일-이름 또는 config.file)를 사용할 수 있습니다. 선택적 별명 인수는 대안 (일반적으로 짧은 이름) 매개 변수 이름을 정의합니다.
Paramhelp (helptext, valuename) : 사용 섹션에서 명령 선의 도움말 텍스트 및 값 이름을 정의합니다.
Paramswitchchar (sign) : 스위치 또는 매개 변수를 나타내는 문자열 또는 숯을 정의합니다. 정의되지 않으면 이중 대시 (-)가 기본적으로 사용됩니다.
paramvalueseparator (sign) : string 또는 char를 value (filename = config.json)과 분리하기 위해 문자열 또는 char를 정의합니다. 정의되지 않으면 기본적으로 동일 부호 (=)가 사용됩니다.
ParamValueisNextParam : 값이없는 값이없는 매개 변수를 정의합니다 (filename c : config.ini)
paramrequired : 필요에 따라 매개 변수를 정의합니다. Param을 찾지 못하면 예외가 제기됩니다.
QuickParameter는 자동으로 값 유형을 확인합니다. 매개 변수 값을 정수로 정의하고 알파 너머를 통과하면 예외가 제기됩니다.
도움말 사용자 정의 : ColorizeHelp로 자신의 색상 사용자 정의를 정의 할 수 있습니다. 사용 가능한 속성은 사용자 정의 색상을 사용합니다. 그렇지 않으면 B/W가 사용됩니다.
Parameters.ColorizeHelp.Enabled := True;
Parameters.ColorizeHelp.CommandName := ccCyan;
Parameters.ColorizeHelp.CommandUsage := ccBlue;매개 변수가 헬프 매개 변수를 감지하면 도움말 문서가 표시됩니다.
Parameters.showHelp : 자동으로 생성 된 도움말 문서를 보여줍니다.
Parameters v.1.0
Usage: Parameters <command-action> <--HostName=<host>> [--Port <port>] [--Retries=<value>]
[--Config-file=<path>] [--UseTCP] [--Silent] [--Mode=<value>]
[--ShowReport] [--Help]
Simple console application example with Quick.Parameters
Arguments:
Command Command action.
--HostName Define host to connect.
--Port, -p Define Port to connect (default 80)
--Retries Number of max retries.
--Config-file Path to config.
--UseTCP Use TCP connection if present.
--Silent Silent mode.
--Mode Modes (mdAdd, mdSelect, mdRemove)
--Help, -h Show this documentation
일반적으로 사용되는 검증.
유창한 스타일의 사전 및 사후 조건 검증. 조건. 요청은 일부 작업을 수행하기 전에 조건에 대한 변수를 평가합니다. 조건. 잠재력은 일부 작업을 수행 한 후 조건에 대한 변수 결과를 평가합니다.
Condition.Requires(num, " num " )
.IsInRange( 1 , 10 , ' value for num is out of range ' ); // throws custom error if not in range
.IsNotGreater( 50 ); // throws ArgumentException if not equal to 128
Condition.Requires(myobj, " myobj " )
.WithExceptionOnFailure(EMyException) // throws specific exception on failure
.IsNotNull() // throws ArgumentNullException if null
.Evaluate(myobj.id > 10 ); // myobj.id must be greater than 10
Condition.Requires(text, " text " )
.IsNotEmpty() // throws ArgumentNullException if empty
.StartsWith( " <html> " ) // throws ArgumentException if not starts with <html>
.EndsWith( " </html> " ) // throws ArgumentException if not ends with </html>
.IsNotLowerCase // thows ArgumentException if not lowercase
.Evaluate(text.Contains( " sometxt " ) or test.Contains( ' othertxt ' )); // throws ArgumentException if not evaluates델파이를 배우거나 기술을 향상시키고 싶습니까? LEARNDELPHI.org