text stringlengths 14 6.51M |
|---|
{
this file is part of Ares
Aresgalaxy ( http://aresgalaxy.sourceforge.net )
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., 675 Mass Ave, Cambridge, MA 02139, USA.
}
{
Description:
load/save filelists from/to disk
}
unit helper_library_db;
interface
uses
ares_types,classes2,classes,{tntwindows,}windows,sysutils;
function set_NEWtrusted_metas:boolean;
procedure set_trusted_metas; // in synchro da scrivi su form1
procedure get_trusted_metas;
procedure get_cached_metas;
function already_in_DBTOWRITE(hash_sha1:string; crcsha1:word):boolean;
function find_trusted_file(hash_sha1:string; crcsha1:word):precord_file_trusted;
procedure set_cached_metas;
function find_cached_file(hash_sha1:string; crcsha1:word):precord_file_library;
procedure DBFiles_free;
procedure DBTrustedFiles_free;
function DB_everseen(path:string; fsize:int64):precord_file_library;
procedure DB_TOWRITE_free;
procedure assign_trusted_metas(pfile:precord_file_library);
procedure init_cached_dbs;
var
DB_TRUSTED:array[0..255] of pointer;
DB_CACHED:array[0..255] of pointer;
DB_TOWRITE:array[0..255] of pointer;
implementation
uses
helper_diskio,vars_global,helper_strings,helper_crypt,
vars_localiz,helper_datetime,{helper_visual_library,}
const_ares,helper_mimetypes,helper_ICH;
procedure init_cached_dbs;
var
i:integer;
begin
for i:=0 to 255 do DB_TOWRITE[i]:=nil;
for i:=0 to 255 do DB_CACHED[i]:=nil;
for i:=0 to 255 do DB_TRUSTED[i]:=nil;
end;
procedure assign_trusted_metas(pfile:precord_file_library);
var
pfiletrust:precord_file_trusted;
begin
try
pfile^.corrupt:=False; //default settings
pfile^.shared:=true;
pfiletrust:=find_trusted_file(pfile^.hash_sha1,pfile^.crcsha1);
if pfiletrust=nil then exit;
with pfile^ do begin
if pfile^.amime=ARES_MIME_SOFTWARe then begin
title:=trim(copy(pfiletrust^.title,1,length(pfiletrust^.title)));
artist:=trim(copy(pfiletrust^.artist,1,length(Pfiletrust^.artist)));
album:=trim(copy(pfiletrust^.album,1,length(pfiletrust^.album)));
end else begin
title:=copy(pfiletrust^.title,1,length(pfiletrust^.title));
artist:=copy(pfiletrust^.artist,1,length(pfiletrust^.artist));
album:=copy(pfiletrust^.album,1,length(pfiletrust^.album));
end;
category:=copy(pfiletrust^.category,1,length(pfiletrust^.category));
language:=copy(pfiletrust^.language,1,length(pfiletrust^.language));
comment:=copy(pfiletrust^.comment,1,length(pfiletrust^.comment));
url:=copy(pfiletrust^.url,1,length(pfiletrust^.url));
year:=copy(pfiletrust^.year,1,length(pfiletrust^.year));
filedate:=pfiletrust^.filedate;
corrupt:=pfiletrust^.corrupt;
shared:=pfiletrust^.shared;
end;
except
end;
end;
procedure DB_TOWRITE_free;
var
pfile,next_pfile:precord_file_library;
i:integer;
begin
try
for i:=0 to 255 do begin
if DB_TOWRITE[i]=nil then continue;
pfile:=DB_TOWRITE[i];
while (pfile<>nil) do begin
next_pfile:=pfile^.next;
// reset_pfile_strings(pfile);
FreeMem(pfile,sizeof(record_file_library));
if next_pfile=nil then break;
pfile:=next_pfile;
end;
DB_TOWRITE[i]:=nil;
end;
except
end;
end;
function DB_everseen(path:string; fsize:int64):precord_file_library;
var
i:integer;
pfile:precord_file_library;
lopath:string;
begin
result:=nil;
lopath:=lowercase(path);
try
for i:=0 to 255 do begin
if DB_CACHED[i]=nil then continue;
pfile:=DB_CACHED[i];
while (pfile<>nil) do begin
if pfile^.fsize<>fsize then begin
pfile:=pfile^.next;
continue;
end;
if lowercase(pfile^.path)<>lopath then begin
pfile:=pfile^.next;
continue;
end;
if length(pfile^.hash_sha1)<>20 then begin
pfile:=pfile^.next;
continue;
end;
result:=pfile;
exit;
end;
end;
except
end;
end;
procedure DBTrustedFiles_free;
var
pfiletrusted,thenext:precord_file_trusted;
i:integer;
begin
try
for i:=0 to 255 do begin
if DB_TRUSTED[i]=nil then continue;
pfiletrusted:=DB_TRUSTED[i];
while (pfiletrusted<>nil) do begin
thenext:=pfiletrusted^.next;
// reset_pfile_trusted_strings(pfiletrusted);
FreeMem(pfiletrusted,sizeof(record_file_trusted));
if thenext=nil then break;
pfiletrusted:=thenext;
end;
DB_TRUSTED[i]:=nil;
end;
except
end;
end;
procedure DBFiles_free;
var
i:integer;
pfile,next_pfile:precord_file_library;
begin
try
for i:=0 to 255 do begin
if DB_CACHED[i]=nil then continue;
pfile:=DB_CACHED[i];
while (pfile<>nil) do begin
next_pfile:=pfile^.next;
// reset_pfile_strings(pfile);
FreeMem(pfile,sizeof(record_file_library));
if next_pfile=nil then break;
pfile:=next_pfile;
end;
DB_CACHED[i]:=nil;
end;
except
end;
end;
function find_cached_file(hash_sha1:string; crcsha1:word):precord_file_library;
begin
result:=nil;
if DB_CACHED[ord(hash_sha1[1])]=nil then exit;
result:=DB_CACHED[ord(hash_sha1[1])];
while (result<>nil) do begin
if result^.crcsha1=crcsha1 then
if result^.hash_sha1=hash_sha1 then exit;
result:=result^.next;
end;
end;
function Tnt_CreateDirectoryW(lpPathName: PWideChar;
lpSecurityAttributes: PSecurityAttributes): BOOL;
var Win32PlatformIsUnicode : boolean;
begin
Win32PlatformIsUnicode := (Win32Platform = VER_PLATFORM_WIN32_NT);
if Win32PlatformIsUnicode then
Result := CreateDirectoryW{TNT-ALLOW CreateDirectoryW}(lpPathName, lpSecurityAttributes)
else
Result := CreateDirectoryA{TNT-ALLOW CreateDirectoryA}(PAnsiChar(AnsiString(lpPathName)), lpSecurityAttributes);
end;
procedure set_cached_metas;
var
pfile:precord_file_library;
i:integer;
str_detail,str:string;
stream:thandlestream;
buffer:array[0..4095] of char;
begin
Tnt_CreateDirectoryW(pwidechar(data_path+'\Data'),nil);
stream:=Myfileopen(data_path+'\Data\ShareL.dat',ARES_CREATE_ALWAYSAND_WRITETHROUGH);
if stream=nil then exit;
stream.size:=0;
//2963 diventa 1.04
str:='__ARESDB1.04L_';
move(str[1],buffer,length(str));
stream.write(buffer,length(str));
//FlushFileBuffers(stream.handle);
str:='';
try
for i:=0 to 255 do begin
if DB_TOWRITE[i]=nil then continue;
pfile:=DB_TOWRITE[i];
while (pfile<>nil) do begin
if length(pfile^.hash_sha1)<>20 then begin //only corrected files
pfile:=pfile^.next;
continue;
end;
str_detail:=chr(1)+int_2_word_string(length(pfile^.path))+pfile^.path+
chr(2)+int_2_word_string(length(pfile^.title))+pfile^.title+
chr(3)+int_2_word_string(length(pfile^.artist))+pfile^.artist+
chr(4)+int_2_word_string(length(pfile^.album))+pfile^.album+
chr(5)+int_2_word_string(length(pfile^.category))+pfile^.category+
chr(6)+int_2_word_string(length(pfile^.year))+pfile^.year+
chr(7)+int_2_word_string(length(pfile^.vidinfo))+pfile^.vidinfo+
chr(8)+int_2_word_string(length(pfile^.language))+pfile^.language+
chr(9)+int_2_word_string(length(pfile^.url))+pfile^.url+
chr(10)+int_2_word_string(length(pfile^.comment))+pfile^.comment+
chr(18)+int_2_word_string(length(pfile^.hash_of_phash))+pfile^.hash_of_phash;//2963
if pfile^.corrupt then str_detail:=str_detail+chr(17)+chr(20)+CHRNULL+pfile^.hash_sha1;
str:=str+
e67(pfile^.hash_sha1+
chr(pfile^.amime)+
int_2_dword_string(0)+
int_2_qword_string(pfile^.fsize)+
int_2_dword_string(pfile^.param1)+
int_2_dword_string(pfile^.param2)+
int_2_dword_string(pfile^.param3)+
int_2_word_string(length(str_detail)),13871)+
e67(str_detail,13872); //crypt
if length(str)>2500 then begin
move(str[1],buffer,length(str));
stream.write(buffer,length(str));
//FlushFileBuffers(stream.handle);
str:='';
end;
pfile:=pfile^.next;
end;
end;
except
end;
if length(str)>0 then begin
move(str[1],buffer,length(str));
stream.write(buffer,length(str));
//FlushFileBuffers(stream.handle);
str:='';
end;
FreeHandleStream(stream);
end;
function find_trusted_file(hash_sha1:string; crcsha1:word):precord_file_trusted;
begin
result:=nil;
if length(hash_sha1)<>20 then exit;
if DB_TRUSTED[ord(hash_sha1[1])]=nil then exit;
result:=DB_TRUSTED[ord(hash_sha1[1])];
while (result<>nil) do begin
if result^.crcsha1=crcsha1 then
if result^.hash_sha1=hash_sha1 then exit;//FOUND!
result:=result^.next;
end;
end;
function already_in_DBTOWRITE(hash_sha1:string; crcsha1:word):boolean;
var
pfile:precord_file_library;
begin
result:=False;
if DB_TOWRITE[ord(hash_sha1[1])]=nil then exit;
pfile:=DB_TOWRITE[ord(hash_sha1[1])];
while (pfile<>nil) do begin
if pfile^.crcsha1=crcsha1 then
if pfile^.hash_sha1=hash_sha1 then begin
result:=true;
exit;
end;
pfile:=pfile^.next;
end;
end;
procedure get_cached_metas;
var
stream:thandlestream;
buffer,buffer2:array[0..2047] of byte;
letti:integer;
lun:word;
pfile,last_pfile:precord_file_library;
fsize:int64;
param1,param2,param3:integer;
str_detail,str_temp:string;
mime,fkind:byte;
i,hi:integer;
b:word;
crcsha1:word;
hash_sha1:string;
begin
for i:=0 to 255 do DB_CACHED[i]:=nil;
stream:=MyFileOpen(data_path+'\data\ShareL.dat',ARES_READONLY_BUT_SEQUENTIAL);
if stream=nil then exit;
letti:=stream.read(buffer,14);
if letti<14 then begin
FreeHandleStream(Stream);
sleep(5);
exit;
end;
setlength(hash_sha1,14);
move(buffer,hash_sha1[1],14);
if hash_sha1<>'__ARESDB1.04L_' then begin
FreeHandleStream(Stream);
exit;
end;
try
while stream.position<stream.size do begin
letti:=stream.read(buffer,47);
if letti<47 then break;
if stream.position>=stream.size then break;
move(buffer,buffer2,47);
b:=13871;
for hi := 0 to 46 do begin
buffer2[hI] := buffer[hI] xor (b shr 8);
b := (buffer[hI] + b) * 23219 + 36126;
end;
move(buffer2,buffer,47);
setlength(hash_sha1,20);
move(buffer,hash_sha1[1],20);
crcsha1:=crcstring(hash_sha1);
mime:=buffer[20];
setlength(str_temp,26);
move(buffer[21],str_temp[1],26);
fsize:=chars_2_Qword(copy(str_temp,5,8));
param1:=chars_2_dword(copy(str_temp,13,4));
param2:=chars_2_dword(copy(str_temp,17,4));
param3:=chars_2_dword(copy(str_temp,21,4));
move(str_temp[25],lun,2);
if lun=0 then continue; //empty ?
if lun>2048 then break;//(???)
letti:=stream.read(buffer,lun); //leggiamo strdetail
if lun>letti then break; //corrotto?
if fsize>ICH_MIN_FILESIZE then
if ICH_find_phash_index(hash_sha1,crcsha1)=nil then continue; //must have partial hashes too
pfile:=find_cached_file(hash_sha1,crcsha1);
if pfile=nil then begin
pfile:=AllocMem(sizeof(recorD_file_library));
if DB_CACHED[ord(hash_sha1[1])]=nil then pfile^.next:=nil
else begin
last_pfile:=DB_CACHED[ord(hash_sha1[1])];
pfile^.next:=last_pfile;
end;
DB_CACHED[ord(hash_sha1[1])]:=pfile;
end;
// reset_pfile_strings(pfile);
pfile^.hash_sha1:=hash_sha1; //20 bytes!
pfile^.crcsha1:=crcsha1;
pfile^.filedate:=0;
pfile^.amime:=mime;
pfile^.fsize:=fsize;
pfile^.shared:=true;
pfile^.param1:=param1;
pfile^.param2:=param2;
pfile^.param3:=param3;
pfile^.shared:=true;
pfile^.mediatype:=mediatype_to_str(pfile^.amime);
pfile^.corrupt:=false;
move(buffer,buffer2,lun);
b:=13872;
for hi := 0 to lun-1 do begin
buffer2[hI] := buffer[hI] xor (b shr 8);
b := (buffer[hI] + b) * 23219 + 36126;
end;
move(buffer2,buffer,lun);
setlength(str_detail,lun);
move(buffer,str_detail[1],lun);
for i:=0 to 14 do begin
if length(str_detail)<3 then break;
fkind:=ord(str_detail[1]);
move(str_detail[2],lun,2);
delete(str_detail,1,3);
case fkind of
1:begin
pfile^.path:=copy(str_detail,1,lun);
end;
2:pfile^.title:=copy(str_detail,1,lun);
3:pfile^.artist:=copy(str_detail,1,lun);
4:pfile^.album:=copy(str_detail,1,lun);
5:pfile^.category:=copy(str_detail,1,lun);
6:pfile^.year:=copy(str_detail,1,lun);
7:pfile^.vidinfo:=copy(str_detail,1,lun);
8:pfile^.language:=copy(str_detail,1,lun);
9:pfile^.url:=copy(str_detail,1,lun);
10:pfile^.comment:=copy(str_detail,1,lun);
17:pfile^.corrupt:=true;
18:pfile^.hash_of_phash:=copy(str_detail,1,lun);
end;
delete(str_detail,1,lun);
end; //for params...
pfile^.ext:=lowercase(extractfileext(pfile^.path));
//check overflows...........
if length(pfile^.title)>MAX_LENGTH_TITLE then delete(pfile^.title,MAX_LENGTH_TITLE,length(pfile^.title));
if length(pfile^.artist)>MAX_LENGTH_FIELDS then delete(pfile^.artist,MAX_LENGTH_FIELDS,length(pfile^.artist));
if length(pfile^.album)>MAX_LENGTH_FIELDS then delete(pfile^.album,MAX_LENGTH_FIELDS,length(pfile^.album));
if length(pfile^.category)>MAX_LENGTH_FIELDS then delete(pfile^.category,MAX_LENGTH_FIELDS,length(pfile^.category));
if length(pfile^.language)>MAX_LENGTH_FIELDS then delete(pfile^.language,MAX_LENGTH_FIELDS,length(pfile^.language));
if length(pfile^.year)>MAX_LENGTH_FIELDS then delete(pfile^.year,MAX_LENGTH_FIELDS,length(pfile^.year));
if length(pfile^.comment)>MAX_LENGTH_COMMENT then delete(pfile^.comment,MAX_LENGTH_COMMENT,length(pfile^.comment));
if length(pfile^.url)>MAX_LENGTH_URL then delete(pfile^.url,MAX_LENGTH_URL,length(pfile^.url));
if pfile^.amime=ARES_MIME_SOFTWARE then begin //hack to eliminate exe trailing spaces bug
pfile^.title:=trim(pfile^.title);
pfile^.artist:=trim(pfile^.artist);
pfile^.album:=trim(pfile^.album);
end;
////////////////////////////////////
end;
except
end;
FreeHandleStream(Stream);
sleep(5);
end;
procedure get_trusted_metas;
var
stream:thandlestream;
buffer,buffer2:array[0..2047] of byte;
letti:integer;
lun,b:word;
pfiletrusted,LastPfileTrusted:precord_file_trusted;
str_detail,str_temp:string;
tipo:byte;
i,hi:integer;
shared:boolean;
crcsha1:word;
hash_sha1,tempStr:string;
begin
DBTrustedFiles_Free;
//for i:=0 to 255 do DB_TRUSTED[i]:=nil;
stream:=MyFileOpen(data_path+'\data\ShareH.dat',ARES_READONLY_BUT_SEQUENTIAL);
if stream=nil then exit;
//////////////////////////////// is it encrypted???
letti:=stream.read(buffer,14);
if letti<14 then begin
FreeHandleStream(Stream);
sleep(5);
exit;
end;
setlength(hash_sha1,14);
move(buffer,hash_sha1[1],14);
if hash_sha1<>'__ARESDB1.02H_' then begin
FreeHandleStream(Stream);
exit;
end;
//////////////////////////////////////////////////////
try
while stream.position<stream.size do begin
str_temp:='';
letti:=stream.read(buffer,23);
if letti<23 then break;
if stream.position>=stream.size-1 then break;//non c'è più nulla qui!
//////////////////decrypt
move(buffer,buffer2,23); //copiamo in buffer2
b:=13871; //header 1 content 2
for hi := 0 to 22 do begin
buffer2[hI] := buffer[hI] xor (b shr 8);
b := (buffer[hI] + b) * 23219 + 36126;
end;
move(buffer2,buffer,23); //rimettiamo in buffer
setlength(hash_sha1,20); //attenzione ora ho sha1 prima avevo md5+dword num scaricati (2941+)
move(buffer,hash_sha1[1],20); //copy hash
crcsha1:=crcstring(hash_sha1);
setlength(str_temp,7);
move(buffer[20],str_temp[1],3);
shared:=(ord(str_temp[1])=1);
move(str_temp[2],lun,2);
if lun=0 then continue;//boh non c'è title o altro...
if lun>1024 then break;
letti:=stream.read(buffer,lun); //read str detail
if lun>letti then break; //file finito non ho letto abbastanza?
pfiletrusted:=find_trusted_file(hash_sha1,crcsha1);
if pfiletrusted=nil then begin
pfiletrusted:=AllocMem(sizeof(record_file_trusted));
if DB_TRUSTED[ord(hash_sha1[1])]=nil then pfiletrusted^.next:=nil
else begin
Lastpfiletrusted:=DB_TRUSTED[ord(hash_sha1[1])];
pfiletrusted^.next:=Lastpfiletrusted;
end;
DB_TRUSTED[ord(hash_sha1[1])]:=pfiletrusted;
end;
// reset_pfile_trusted_strings(pfiletrusted);
pfiletrusted^.hash_sha1:=hash_sha1;
pfiletrusted^.filedate:=0; //se non ha data non lo facciamo comparire nei recent...
pfiletrusted^.crcsha1:=crcsha1;
pfiletrusted^.shared:=shared;
pfiletrusted^.corrupt:=false; //di default non è corrotto
/////////decrypt
move(buffer,buffer2,lun); //copiamo in buffer2
b:=13872; //2 mentre header ha 1
for hi := 0 to lun-1 do begin
buffer2[hI] := buffer[hI] xor (b shr 8);
b := (buffer[hI] + b) * 23219 + 36126;
end;
move(buffer2,buffer,lun); //rimettiamo in buffer
setlength(str_detail,lun);
move(buffer,str_detail[1],lun);
for i:=0 to 11 do begin
if length(str_detail)<3 then break;
tipo:=ord(str_detail[1]);
move(str_detail[2],lun,2);
delete(str_detail,1,3);
tempStr:=copy(str_detail,1,lun);
case tipo of
2:pfiletrusted^.title:=tempStr;
3:pfiletrusted^.artist:=tempStr;
4:pfiletrusted^.album:=tempStr;
5:pfiletrusted^.category:=tempStr;
6:pfiletrusted^.year:=tempStr;
8:pfiletrusted^.language:=tempStr;
9:pfiletrusted^.url:=tempStr;
10:pfiletrusted^.comment:=tempStr;
11:pfiletrusted^.filedate:=UnixToDelphiDateTime(chars_2_dword(tempStr));
17:begin
pfiletrusted^.corrupt:=true;
end;
end;
tempStr:='';
delete(str_detail,1,lun);
end; //fine for
//check overflows...........
if length(pfiletrusted^.title)>MAX_LENGTH_TITLE then delete(pfiletrusted^.title,MAX_LENGTH_TITLE,length(pfiletrusted^.title));
if length(pfiletrusted^.artist)>MAX_LENGTH_FIELDS then delete(pfiletrusted^.artist,MAX_LENGTH_FIELDS,length(pfiletrusted^.artist));
if length(pfiletrusted^.album)>MAX_LENGTH_FIELDS then delete(pfiletrusted^.album,MAX_LENGTH_FIELDS,length(pfiletrusted^.album));
if length(pfiletrusted^.category)>MAX_LENGTH_FIELDS then delete(pfiletrusted^.category,MAX_LENGTH_FIELDS,length(pfiletrusted^.category));
if length(pfiletrusted^.language)>MAX_LENGTH_FIELDS then delete(pfiletrusted^.language,MAX_LENGTH_FIELDS,length(pfiletrusted^.language));
if length(pfiletrusted^.year)>MAX_LENGTH_FIELDS then delete(pfiletrusted^.year,MAX_LENGTH_FIELDS,length(pfiletrusted^.year));
if length(pfiletrusted^.comment)>MAX_LENGTH_COMMENT then delete(pfiletrusted^.comment,MAX_LENGTH_COMMENT,length(pfiletrusted^.comment));
if length(pfiletrusted^.url)>MAX_LENGTH_URL then delete(pfiletrusted^.url,MAX_LENGTH_URL,length(pfiletrusted^.url));
////////////////////////////////////
end; //while
except
end;
FreeHandleStream(Stream);
str_detail:='';
str_temp:='';
hash_sha1:='';
sleep(5);
end;
procedure set_trusted_metas; // in synchro da scrivi su form1
var
i:integer;
pfiletrusted:precord_file_trusted;
str_detail,str:string;
stream:thandlestream;
buffer:array[0..4095] of char;
begin
Tnt_CreateDirectoryW(pwidechar(data_path+'\Data'),nil);
stream:=Myfileopen(data_path+'\Data\ShareH.dat',ARES_CREATE_ALWAYSAND_WRITETHROUGH);
if stream=nil then exit;
stream.size:=0;//tronchiamo file (cancellazione) dobbiamo riscrivere da zero
str:='__ARESDB1.02H_'; //centrambi riptati!
move(str[1],buffer,length(str));
stream.write(buffer,length(str));
FlushFileBuffers(stream.handle);//boh
str:='';
try
for i:=0 to 255 do begin
if DB_TRUSTED[i]=nil then continue;
pfiletrusted:=DB_TRUSTED[i];
while (pfiletrusted<>nil) do begin
if length(pfiletrusted^.hash_sha1)<>20 then begin
pfiletrusted:=pfiletrusted^.next;
continue; //evitiamo corruzione
end;
if lowercase(pfiletrusted^.artist)=GetLangStringA(STR_UNKNOW_LOWER) then pfiletrusted^.artist:='';
if lowercase(pfiletrusted^.category)=GetLangStringA(STR_UNKNOW_LOWER) then pfiletrusted^.category:='';
if lowercase(pfiletrusted^.album)=GetLangStringA(STR_UNKNOW_LOWER) then pfiletrusted^.album:='';
str_detail:=chr(2)+int_2_word_string(length(pfiletrusted^.title))+pfiletrusted^.title+
chr(3)+int_2_word_string(length(pfiletrusted^.artist))+pfiletrusted^.artist+
chr(4)+int_2_word_string(length(pfiletrusted^.album))+pfiletrusted^.album+
chr(5)+int_2_word_string(length(pfiletrusted^.category))+pfiletrusted^.category+
chr(6)+int_2_word_string(length(pfiletrusted^.year))+pfiletrusted^.year+
chr(8)+int_2_word_string(length(pfiletrusted^.language))+pfiletrusted^.language+
chr(9)+int_2_word_string(length(pfiletrusted^.url))+pfiletrusted^.url+
chr(10)+int_2_word_string(length(pfiletrusted^.comment))+pfiletrusted^.comment;
if trunc(pfiletrusted^.filedate)<>0 then str_detail:=str_detail+chr(11)+chr(4)+CHRNULL+int_2_dword_string(DelphiDateTimeToUnix(pfiletrusted^.filedate));
if pfiletrusted^.corrupt then str_detail:=str_detail+chr(17)+chr(20)+CHRNULL+pfiletrusted^.hash_sha1;
str:=str+
e67(pfiletrusted^.hash_sha1+//pfile^.requested_total)+
chr(integer(pfiletrusted^.shared))+
int_2_word_string(length(str_detail)),13871)+
e67(str_detail,13872); //criptiamo
if length(str)>2500 then begin
move(str[1],buffer,length(str));
stream.write(buffer,length(str));
//FlushFileBuffers(stream.handle);
str:='';
end;
pfiletrusted:=pfiletrusted^.next;
end;//while
end; //for per DB_TRUSTED count
if length(str)>0 then begin
move(str[1],buffer,length(str));
stream.write(buffer,length(str));
//FlushFileBuffers(stream.handle);
end;
except
end;
FreeHandleStream(Stream);
end;
function set_newtrusted_metas:boolean; //chiamato in chiusura e riapertura thread_share
var //aggiunge in coda file su trusted
i:integer;
pfile:precord_file_library;
stream,stream2:thandlestream;
str_detail,str:string;
str_detail2,str2:string;
buffer:array[0..1023] of char;
buffer2:array[0..2047] of char;
begin
result:=false;
Tnt_CreateDirectoryW(pwidechar(data_path+'\data'),nil);
if not helper_diskio.FileExists(data_path+'\data\ShareH.dat') then stream:=Myfileopen(data_path+'\data\ShareH.dat',ARES_CREATE_ALWAYSAND_WRITETHROUGH)
else stream:=Myfileopen(data_path+'\data\ShareH.dat',ARES_WRITEEXISTING_WRITETHROUGH); //open to append existing
if stream<>nil then begin
stream.seek(0,sofromend);
if stream.position=0 then begin //primo file, mettiamo header cript nuovo
str:='__ARESDB1.02H_';
move(str[1],buffer,length(str));
stream.write(buffer,length(str));
FlushFileBuffers(stream.handle);//boh
end;
end;
if not helper_diskio.FileExists(data_path+'\data\ShareL.dat') then stream2:=Myfileopen(data_path+'\data\ShareL.dat',ARES_CREATE_ALWAYSAND_WRITETHROUGH)
else stream2:=Myfileopen(data_path+'\data\ShareL.dat',ARES_WRITEEXISTING_WRITETHROUGH); //open to append existing
if stream2<>nil then begin //handle al file di settings
stream2.seek(0,sofromend);
if stream2.position=0 then begin //secondo file, mettiamo header cript nuovo //2963 diventa chr 52 (1.04L)
str:='__ARESDB1.04L_';
move(str[1],buffer,length(str));
stream2.write(buffer,length(str));
FlushFileBuffers(stream2.handle);//boh
end;
end;
if stream2=nil then
if stream=nil then exit;
try
for i:=0 to lista_shared.count-1 do begin
pfile:=lista_shared[i];
if not pfile^.write_to_disk then continue;
if length(pfile^.hash_sha1)<>20 then continue; //woah
result:=true;
pfile^.write_to_disk:=false;
if lowercase(pfile^.artist)=GetLangStringA(STR_UNKNOW_LOWER) then pfile^.artist:='';
if lowercase(pfile^.category)=GetLangStringA(STR_UNKNOW_LOWER) then pfile^.category:='';
if lowercase(pfile^.album)=GetLangStringA(STR_UNKNOW_LOWER) then pfile^.album:='';
str_detail:=chr(2)+int_2_word_string(length(pfile^.title))+pfile^.title+
chr(3)+int_2_word_string(length(pfile^.artist))+pfile^.artist+
chr(4)+int_2_word_string(length(pfile^.album))+pfile^.album+
chr(5)+int_2_word_string(length(pfile^.category))+pfile^.category+
chr(6)+int_2_word_string(length(pfile^.year))+pfile^.year+
chr(8)+int_2_word_string(length(pfile^.language))+pfile^.language+
chr(9)+int_2_word_string(length(pfile^.url))+pfile^.url+
chr(10)+int_2_word_string(length(pfile^.comment))+pfile^.comment;
if trunc(pfile^.filedate)<>0 then str_detail:=str_detail+chr(11)+chr(4)+CHRNULL+int_2_dword_string(DelphiDateTimeToUnix(pfile^.filedate));
if pfile^.corrupt then str_detail:=str_detail+chr(17)+chr(20)+CHRNULL+pfile^.hash_sha1;
str_detail2:=chr(1)+int_2_word_string(length(pfile^.path))+pfile^.path+
chr(2)+int_2_word_string(length(pfile^.title))+pfile^.title+
chr(3)+int_2_word_string(length(pfile^.artist))+pfile^.artist+
chr(4)+int_2_word_string(length(pfile^.album))+pfile^.album+
chr(5)+int_2_word_string(length(pfile^.category))+pfile^.category+
chr(6)+int_2_word_string(length(pfile^.year))+pfile^.year+
chr(7)+int_2_word_string(length(pfile^.vidinfo))+pfile^.vidinfo+
chr(8)+int_2_word_string(length(pfile^.language))+pfile^.language+
chr(9)+int_2_word_string(length(pfile^.url))+pfile^.url+
chr(10)+int_2_word_string(length(pfile^.comment))+pfile^.comment+
chr(18)+int_2_word_string(length(pfile^.hash_of_phash))+pfile^.hash_of_phash;
if pfile^.corrupt then str_detail2:=str_detail2+chr(17)+chr(20)+CHRNULL+pfile^.hash_sha1;
str:=e67(pfile^.hash_sha1+
chr(integer(pfile^.shared))+
int_2_word_string(length(str_detail)),13871)+
e67(str_detail,13872);
if stream<>nil then begin
move(str[1],buffer,length(str));
stream.write(buffer,length(str));
FlushFileBuffers(stream.handle);//boh
end;
str2:=e67(pfile^.hash_sha1+
chr(pfile^.amime)+
int_2_dword_string(0)+
int_2_Qword_string(pfile^.fsize)+
int_2_dword_string(pfile^.param1)+
int_2_dword_string(pfile^.param2)+
int_2_dword_string(pfile^.param3)+
int_2_word_string(length(str_detail2)),13871)+
e67(str_detail2,13872);
if stream2<>nil then begin
move(str2[1],buffer2,length(str2));
stream2.write(buffer2,length(str2));
FlushFileBuffers(stream2.handle);
end;
end;
except
end;
if stream<>nil then FreeHandleStream(Stream);
if stream2<>nil then FreeHandleStream(Stream2);
end;
end.
|
unit utils_redis;
interface
uses
utils_DValue, SysUtils, diocp.core.rawWinSocket, diocp.winapi.winsock2, Classes, utils_rawPackage,
utils_async, utils.strings, SysConst;
const
MAX_LEN = 10240;
type
TRedisCommand = class(TObject)
private
FRawPackage: TRawPackage;
FCommand: String;
FData: TDValue;
FDecodeFlag: Integer;
FDecodeArgs: Integer;
FDecodeCurrentIndex: Integer;
FDecodeCurrentParamLength: Integer;
FDecodeLength: Integer;
FLastCmdString: String;
FResponseMessage: String;
// 用单行回复,回复的第一个字节将是“+”
// 错误消息,回复的第一个字节将是“-”
// 整型数字,回复的第一个字节将是“:”
// 批量回复,回复的第一个字节将是“$”
// 多个批量回复,回复的第一个字节将是“*”
FDecodeTypeChr: Char;
FDecodePackTypeChr: Char;
FLastResponseIntValue: Integer;
/// <summary>
/// * 多行
/// </summary>
/// <returns> 0, 需要更多的数据, 1: 完整, -1:错误</returns>
function InputBufferForMultiResponse(pvBuf: Byte): Integer;
function InputBufferForTypeChar(pvBuf: Byte): Char;
function InputBufferForDefaultStr(pvBuf: Byte): Integer;
procedure ConfigStartAndEndBytes(pvStart, pvEnd: string);
public
function InputBufferForDecode(pvBuf: Byte): Integer;
constructor Create;
destructor Destroy; override;
property Command: String read FCommand write FCommand;
property Data: TDValue read FData;
property ResponseMessage: String read FResponseMessage;
property LastResponseIntValue: Integer read FLastResponseIntValue write
FLastResponseIntValue;
procedure Clear;
procedure MakeSubscribe(pvSubscribeArgs: array of string);
procedure MakePublish(pvChannel:String; pvMessage:String);
procedure MakeHSET(pvKey, pvField, pvValue:String);
function ExtractSubscribeMessage: String;
end;
TRedisClient = class(TObject)
private
FActive: Boolean;
FRawSocket: TRawSocket;
FStream: TMemoryStream;
FHost: String;
FPort: Integer;
public
constructor Create;
destructor Destroy; override;
procedure Connect;
procedure Close;
function SendCMD(pvRedisCMD: TRedisCommand): Integer;
function RecvCMD(pvRedisCMD: TRedisCommand): Integer;
function ReceiveLength: Integer;
procedure ExecuteCMD(pvRedisCMD:TRedisCommand);
procedure CheckRecvResult(pvSocketResult: Integer);
property Active: Boolean read FActive;
property Host: String read FHost write FHost;
property Port: Integer read FPort write FPort;
end;
function utils_redis_tester: string;
implementation
resourcestring
STRING_E_RECV_ZERO = '服务端主动断开关闭';
STRING_E_TIMEOUT = '服务端响应超时';
{$IFDEF POSIX}
{$ELSE}
// <2007版本的Windows平台使用
// SOSError = 'System Error. Code: %d.'+sLineBreak+'%s';
procedure RaiseLastOSErrorException(LastError: Integer);
var // 高版本的 SOSError带3个参数
Error: EOSError;
begin
if LastError <> 0 then
Error := EOSError.CreateResFmt(@SOSError, [LastError,
SysErrorMessage(LastError)])
else
Error := EOSError.CreateRes(@SUnkOSError);
Error.ErrorCode := LastError;
raise Error;
end;
{$ENDIF}
function utils_redis_tester: string;
var
lvRedisCmd: TRedisCommand;
lvRedisClient: TRedisClient;
begin
lvRedisClient := TRedisClient.Create;
lvRedisCmd := TRedisCommand.Create;
lvRedisClient.Host := '127.0.0.1';
lvRedisClient.Port := 6379;
lvRedisClient.Connect;
lvRedisCmd.MakeSubscribe(['tester', 'news']);
lvRedisClient.SendCMD(lvRedisCmd);
lvRedisCmd.Clear;
if lvRedisClient.RecvCMD(lvRedisCmd) = -1 then
begin
RaiseLastOSError;
end;
lvRedisCmd.Clear;
if lvRedisClient.RecvCMD(lvRedisCmd) = -1 then
begin
RaiseLastOSError;
end;
Result := lvRedisCmd.ResponseMessage;
end;
constructor TRedisCommand.Create;
begin
inherited Create;
FData := TDValue.Create();
SetPackageMaxLength(@FRawPackage, MAX_LEN);
end;
destructor TRedisCommand.Destroy;
begin
FData.Free;
inherited Destroy;
end;
procedure TRedisCommand.MakeSubscribe(pvSubscribeArgs: array of string);
var
i:Integer;
begin
Clear;
Command := 'subscribe';
Data.Clear;
for i := Low(pvSubscribeArgs) to High(pvSubscribeArgs) do
begin
Data.Add.AsString := pvSubscribeArgs[i];
end;
//Data.Add.AsString := pvSubscribeArgs;
end;
procedure TRedisCommand.Clear;
begin
FData.Clear;
ResetPacakge(@FRawPackage);
FDecodePackTypeChr := Char(0);
FDecodeTypeChr := Char(0);
FDecodeCurrentIndex := 0;
FDecodeCurrentParamLength := 0;
end;
procedure TRedisCommand.ConfigStartAndEndBytes(pvStart, pvEnd: string);
var
lvBytes: TBytes;
r: Integer;
begin
SetLength(lvBytes, 128);
r := StringToBytes(pvStart, lvBytes);
SetPackageStartBytes(@FRawPackage, lvBytes, 0, r);
r := StringToBytes(pvEnd, lvBytes);
SetPackageEndBytes(@FRawPackage, lvBytes, 0, r);
end;
function TRedisCommand.ExtractSubscribeMessage: String;
begin
Result := '';
if LowerCase(FCommand) = 'message' then
begin
if FData.Count > 1 then
Result := FData[1].AsString;
end;
end;
function TRedisCommand.InputBufferForDecode(pvBuf: Byte): Integer;
var
lvBytes: TBytes;
l: Integer;
begin
if FDecodePackTypeChr = Char(0) then
begin
// 用单行回复,回复的第一个字节将是“+”
// 错误消息,回复的第一个字节将是“-”
// 整型数字,回复的第一个字节将是“:”
// 批量回复,回复的第一个字节将是“$”
// 多个批量回复,回复的第一个字节将是“*”
FDecodePackTypeChr := InputBufferForTypeChar(pvBuf);
end;
if FDecodePackTypeChr = '*' then
begin
l := InputBufferForMultiResponse(pvBuf);
if l = -1 then
begin
ResetPacakge(@FRawPackage);
FDecodeFlag := 0;
Result := -1;
Exit;
end;
Result := l;
Exit;
end
else if FDecodePackTypeChr in ['+', '-', ':'] then
begin // + 单行回复
if FDecodeTypeChr = Char(0) then
begin
FDecodeTypeChr := FDecodePackTypeChr;
ResetPacakge(@FRawPackage);
ConfigStartAndEndBytes(FDecodeTypeChr, sLineBreak);
end;
l := InputBuffer(@FRawPackage, pvBuf);
if l = 1 then
begin
if FDecodeTypeChr = ':' then
begin
FLastResponseIntValue := StrToInt(FLastCmdString);
end;
FResponseMessage := Utf8BytesToString(FRawPackage.FRawBytes, 1);
Result := 1;
ResetPacakge(@FRawPackage);
Exit;
end;
end;
Result := 0;
end;
function TRedisCommand.InputBufferForMultiResponse(pvBuf: Byte): Integer;
var
r: Integer;
s: String;
function InnerCheckResponse(pvByteIndex:Integer):Integer;
begin
if FDecodeCurrentIndex = 0 then
begin
FLastCmdString := Trim(BytesToString(FRawPackage.FRawBytes, pvByteIndex));
FCommand := FLastCmdString;
end
else
begin
FLastCmdString := Trim(Utf8BytesToString(FRawPackage.FRawBytes, pvByteIndex));
FData.Add.AsString := FLastCmdString;
end;
Inc(FDecodeCurrentIndex);
if FDecodeCurrentIndex = FDecodeArgs then
begin
Result := 1;
end else
begin
Result := 0;
end;
end;
begin
if (FDecodeCurrentParamLength = 0) and (FDecodeTypeChr = Char(0)) then
begin
FDecodeTypeChr := Char(pvBuf);
if FDecodeTypeChr = '*' then
begin
ResetPacakge(@FRawPackage);
ConfigStartAndEndBytes('*', sLineBreak);
end
else if FDecodeTypeChr = '$' then
begin
ResetPacakge(@FRawPackage);
ConfigStartAndEndBytes('$', sLineBreak);
end
else if FDecodeTypeChr = ':' then
begin
ResetPacakge(@FRawPackage);
ConfigStartAndEndBytes(':', sLineBreak);
end
else if FDecodeTypeChr = '+' then
begin
ResetPacakge(@FRawPackage);
ConfigStartAndEndBytes('+', sLineBreak);
end
else if FDecodeTypeChr = '-' then
begin
ResetPacakge(@FRawPackage);
ConfigStartAndEndBytes('-', sLineBreak);
end
else
begin
Result := -1;
Exit;
end;
end;
if FDecodeTypeChr = '*' then
begin
Result := InputBufferForDefaultStr(pvBuf);
if Result = 1 then
begin
FDecodeArgs := StrToInt(FLastCmdString);
FDecodeCurrentIndex := 0;
ResetPacakge(@FRawPackage); //
FDecodeTypeChr := Char(0);
Result := 0;
end;
end
else if FDecodeTypeChr = '$' then
begin
Result := InputBufferForDefaultStr(pvBuf);
if Result = 1 then
begin
//
FDecodeCurrentParamLength := StrToInt(FLastCmdString) + 2;
FDecodeTypeChr := Char(0);
ResetPacakge(@FRawPackage); //
Result := 0;
end;
end
else if FDecodeCurrentParamLength > 0 then
begin
if FRawPackage.FRawLength <= FDecodeCurrentParamLength then
begin
FRawPackage.FRawBytes[FRawPackage.FRawLength] := pvBuf;
Inc(FRawPackage.FRawLength);
end;
if FRawPackage.FRawLength = FDecodeCurrentParamLength then
begin
if InnerCheckResponse(0) = 1 then
begin
FDecodeCurrentParamLength := 0;
ResetPacakge(@FRawPackage); // 准备接收参数
Result := 1;
Exit;
end;
FDecodeCurrentParamLength := 0;
ResetPacakge(@FRawPackage); // 准备接收参数
end;
Result := 0;
end
else if FDecodeTypeChr = ':' then
begin
Result := InputBufferForDefaultStr(pvBuf);
if Result = 1 then
begin
Result := InnerCheckResponse(1);
FLastResponseIntValue := StrToInt(FLastCmdString);
if Result = 1 then
begin
ResetPacakge(@FRawPackage); //
FDecodeTypeChr := Char(0);
Result := 1;
Exit;
end;
Result := 0;
end;
end;
end;
function TRedisCommand.InputBufferForDefaultStr(pvBuf: Byte): Integer;
begin
Result := InputBuffer(@FRawPackage, pvBuf);
if Result = 1 then
begin
FLastCmdString := Trim(BytesToString(FRawPackage.FRawBytes, 1));
end;
end;
function TRedisCommand.InputBufferForTypeChar(pvBuf: Byte): Char;
begin
Result := Char(pvBuf);
if not(Result in ['*', '$', '+', '-', ':']) then
begin
Result := Char(0);
end;
end;
procedure TRedisCommand.MakeHSET(pvKey, pvField, pvValue:String);
begin
Clear;
Command := 'HSET';
Data.Clear;
Data.Add.AsString := pvKey;
Data.Add.AsString := pvField;
Data.Add.AsString := pvValue;
end;
procedure TRedisCommand.MakePublish(pvChannel:String; pvMessage:String);
begin
// Clear;
// Command := 'subscribe';
// Data.Clear;
//
// for i := Low(pvSubscribeArgs) to High(pvSubscribeArgs) do
// begin
// Data.Add.AsString := pvSubscribeArgs[i];
// end;
end;
constructor TRedisClient.Create;
begin
inherited Create;
FRawSocket := TRawSocket.Create();
FStream := TMemoryStream.Create;
end;
destructor TRedisClient.Destroy;
begin
FreeAndNil(FRawSocket);
FStream.Free;
inherited Destroy;
end;
procedure TRedisClient.CheckRecvResult(pvSocketResult: Integer);
var
lvErrorCode:Integer;
begin
if pvSocketResult = -2 then
begin
self.Close;
raise Exception.Create(STRING_E_TIMEOUT);
end;
{$IFDEF POSIX}
if (pvSocketResult = -1) or (pvSocketResult = 0) then
begin
try
RaiseLastOSError;
except
FRawSocket.Close;
raise;
end;
end;
{$ELSE}
if (pvSocketResult = SOCKET_ERROR) then
begin
lvErrorCode := GetLastError;
FRawSocket.Close; // 出现异常后断开连接
{$if CompilerVersion < 23}
RaiseLastOSErrorException(lvErrorCode);
{$ELSE}
RaiseLastOSError(lvErrorCode);
{$ifend}
end;
{$ENDIF}
end;
procedure TRedisClient.Connect;
begin
FRawSocket.CreateTcpSocket;
if not FRawSocket.Connect(FHost, FPort) then
begin
RaiseLastOSError;
end;
FActive := True;
end;
procedure TRedisClient.Close;
begin
FRawSocket.Close;
FActive := False;
end;
procedure TRedisClient.ExecuteCMD(pvRedisCMD:TRedisCommand);
var
r:Integer;
begin
SendCMD(pvRedisCMD);
pvRedisCMD.Clear;
r := RecvCMD(pvRedisCMD);
CheckRecvResult(r);
end;
function TRedisClient.ReceiveLength: Integer;
begin
Result := FRawSocket.ReceiveLength;
end;
function TRedisClient.RecvCMD(pvRedisCMD: TRedisCommand): Integer;
var
lvData: Byte;
lvRecvBuff: AnsiString;
begin
while True do
begin
SetLength(lvRecvBuff, 1024);
// l := FRawSocket.RecvBuf(PAnsiChar(lvRecvBuff)^, 1024);
Result := FRawSocket.RecvBuf(lvData, 1);
if Result <= 0 then
begin
Break;
end
else
begin
Result := pvRedisCMD.InputBufferForDecode(lvData);
if Result = 1 then
begin
Break;
end;
end;
end;
end;
function TRedisClient.SendCMD(pvRedisCMD: TRedisCommand): Integer;
var
lvData, lvArgCmd: String;
lvEndBytes: array [0 .. 1] of Byte;
lvBytes, lvArgBytes: TBytes;
l, l2, i: Integer;
lvItem: TDValue;
begin
lvEndBytes[0] := 13;
lvEndBytes[1] := 10;
FStream.Clear;
SetLength(lvBytes, 1024);
SetLength(lvArgBytes, 1024);;
// arg num
lvData := Format('*%d' + sLineBreak, [pvRedisCMD.Data.Count + 1]);
l := StringToUtf8Bytes(lvData, lvBytes);
FStream.Write(lvBytes[0], l);
// cmd
lvData := pvRedisCMD.Command;
l := StringToUtf8Bytes(lvData, lvBytes);
lvArgCmd := Format('$%d%s', [l, sLineBreak]);
l2 := StringToUtf8Bytes(lvArgCmd, lvArgBytes);
// len
FStream.Write(lvArgBytes[0], l2);
// cmd
FStream.Write(lvBytes[0], l);
FStream.Write(lvEndBytes[0], 2);
for i := 0 to pvRedisCMD.Data.Count - 1 do
begin
lvItem := pvRedisCMD.Data[i];
// arg[i];
lvData := lvItem.AsString;
l := StringToUtf8Bytes(lvData, lvBytes);
lvArgCmd := Format('$%d%s', [l, sLineBreak]);
l2 := StringToUtf8Bytes(lvArgCmd, lvArgBytes);
// len
FStream.Write(lvArgBytes[0], l2);
// cmd
FStream.Write(lvBytes[0], l);
FStream.Write(lvEndBytes[0], 2);
end;
Result := FRawSocket.SendBuf(FStream.Memory^, FStream.Size);
end;
end.
|
unit ComponentsQuery;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf,
FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet,
FireDAC.Comp.Client, Vcl.StdCtrls, {Sequence,} ApplyQueryFrame,
BaseComponentsQuery, DSWrap, CustomComponentsQuery;
type
TComponentsW = class(TCustomComponentsW)
protected
procedure AddNewValue(const AIDParentComponent: Integer;
const AValue: string);
public
procedure LocateOrAppend(const AIDParentComponent: Integer;
const AValue: string);
end;
TQueryComponents = class(TQueryBaseComponents)
private
function GetComponentsW: TComponentsW;
{ Private declarations }
protected
function CreateDSWrap: TDSWrap; override;
public
constructor Create(AOwner: TComponent); override;
property ComponentsW: TComponentsW read GetComponentsW;
{ Public declarations }
end;
implementation
uses NotifyEvents, RepositoryDataModule, DBRecordHolder;
{$R *.dfm}
{ TfrmQueryComponentsDetail }
constructor TQueryComponents.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
DetailParameterName := 'vProductCategoryId';
end;
function TQueryComponents.CreateDSWrap: TDSWrap;
begin
Result := TComponentsW.Create(FDQuery);
end;
function TQueryComponents.GetComponentsW: TComponentsW;
begin
Result := W as TComponentsW;
end;
procedure TComponentsW.AddNewValue(const AIDParentComponent: Integer;
const AValue: string);
begin
// Добавляем дочерний компонент
TryAppend;
ParentProductID.F.AsInteger := AIDParentComponent;
Value.F.AsString := AValue;
TryPost;
end;
procedure TComponentsW.LocateOrAppend(const AIDParentComponent: Integer;
const AValue: string);
begin
// Ещем дочерний компонент
if not FDDataSet.LocateEx(Format('%s;%s', [ParentProductID.FieldName,
Value.FieldName]), VarArrayOf([AIDParentComponent, AValue]),
[lxoCaseInsensitive]) then
AddNewValue(AIDParentComponent, AValue);
end;
end.
|
{*******************************************************}
{ }
{ Delphi VCL Extensions (RX) }
{ }
{ Copyright (c) 1997 Master-Bank }
{ }
{ Patched by Polaris Software }
{ Patched by Jouni Airaksinen }
{*******************************************************}
unit RxColors;
{$C PRELOAD}
{$I RX.INC}
{$DEFINE RX_COLOR_APPENDED}
interface
uses Classes, Controls, Graphics, Forms, RxVCLUtils;
function RxIdentToColor(const Ident: string; var Color: TColor): Boolean;
function RxColorToString(Color: TColor): string;
function RxStringToColor(S: string): TColor;
procedure RxGetColorValues(Proc: TGetStrProc);
const
clInfoBk16 = TColor($02E1FFFF);
clNone16 = TColor($02FFFFFF);
{ Added colors }
clWavePale = TColor($00D0D0D0); { selected tab }
clWaveDarkGray = TColor($00505050); { borders }
clWaveGray = TColor($00A0A0A0); { menus, unselected tabs }
clWaveLightGray = TColor($00BCBCBC); { gray button }
clWaveBeige = TColor($00B4C4C4); { button face }
clWaveBrightBeige = TColor($00BFFFFF); { selected text }
clWaveLightBeige = TColor($00D8E8E8); { hotkey }
clWaveCyan = TColor($00C4B4C4); { button face }
clWaveBrightCyan = TColor($00FFBFFF); { selected text }
clWaveLightCyan = TColor($00E8D8E8); { hotkey }
clWaveGreen = TColor($00B8B8BA); { button face }
clWaveBrightGreen = TColor($00CFCFFF); { selected text }
clWaveLightGreen = TColor($00DCDCE8); { hotkey }
clWaveViolet = TColor($02C4B8C2); { button face }
clWaveBrightViolet = TColor($02FFCFCF); { selected text }
clWaveLightViolet = TColor($02E8DCDC); { hotkey }
{ Standard Encarta & FlatStyle Color Constants }
clRxDarkBlue = TColor($00996633);
clRxBlue = TColor($00CF9030);
clRxLightBlue = TColor($00CFB78F);
clRxDarkRed = TColor($00302794);
clRxRed = TColor($005F58B0);
clRxLightRed = TColor($006963B6);
clRxDarkGreen = TColor($00385937);
clRxGreen = TColor($00518150);
clRxLightGreen = TColor($0093CAB1);
clRxDarkYellow = TColor($004EB6CF);
clRxYellow = TColor($0057D1FF);
clRxLightYellow = TColor($00B3F8FF);
clRxDarkBrown = TColor($00394D4D);
clRxBrown = TColor($00555E66);
clRxLightBrown = TColor($00829AA2);
clRxDarkKhaki = TColor($00D3D3D3);
clRxKhaki = TColor($00C8D7D7);
clRxLightKhaki = TColor($00E0E9EF);
{ added standard named html colors }
clHtmBlack = TColor($00000000);
clHtmGray0 = TColor($00170515);
clHtmGray18 = TColor($00170525);
clHtmGray21 = TColor($00171B2B);
clHtmGray23 = TColor($00172230);
clHtmGray24 = TColor($00262230);
clHtmGray25 = TColor($00262834);
clHtmGray26 = TColor($002C2834);
clHtmGray27 = TColor($002C2D38);
clHtmGray28 = TColor($0031313B);
clHtmGray29 = TColor($0035353E);
clHtmGray30 = TColor($00393841);
clHtmGray31 = TColor($003C3841);
clHtmGray32 = TColor($003F3E46);
clHtmGray34 = TColor($0044434A);
clHtmGray35 = TColor($0046464C);
clHtmGray36 = TColor($0048484E);
clHtmGray37 = TColor($004B4A50);
clHtmGray38 = TColor($004F4E54);
clHtmGray39 = TColor($00515056);
clHtmGray40 = TColor($00545459);
clHtmGray41 = TColor($0058585C);
clHtmGray42 = TColor($00595A5F);
clHtmGray43 = TColor($005D5D62);
clHtmGray44 = TColor($00606064);
clHtmGray45 = TColor($00626366);
clHtmGray46 = TColor($00656569);
clHtmGray47 = TColor($0068696D);
clHtmGray48 = TColor($006B6A6E);
clHtmGray49 = TColor($006D6E72);
clHtmGray50 = TColor($00707174);
clHtmGray = TColor($006E6F73);
clHtmSlateGray4 = TColor($007E6D61);
clHtmSlateGray = TColor($00837365);
clHtmLightSteelBlue4 = TColor($007E6D64);
clHtmLightSlateGray = TColor($008D7B6D);
clHtmCadetBlue4 = TColor($007E784C);
clHtmDarkSlateGray4 = TColor($007E7D4C);
clHtmThistle4 = TColor($007E6D80);
clHtmMediumSlateBlue = TColor($00805A5E);
clHtmMediumPurple4 = TColor($007E384E);
clHtmMidnightBlue = TColor($00541B15);
clHtmDarkSlateBlue = TColor($0056382B);
clHtmDarkSlateGray = TColor($003C3825);
clHtmDimGray = TColor($00413E46);
clHtmCornflowerBlue = TColor($008D1B15);
clHtmRoyalBlue4 = TColor($007E3115);
clHtmSlateBlue4 = TColor($007E2D34);
clHtmRoyalBlue = TColor($00DE602B);
clHtmRoyalBlue1 = TColor($00FF6E30);
clHtmRoyalBlue2 = TColor($00EC652B);
clHtmRoyalBlue3 = TColor($00C75425);
clHtmDeepSkyBlue = TColor($00FFB93B);
clHtmDeepSkyBlue2 = TColor($00ECAC38);
clHtmSlateBlue = TColor($00C77E35);
clHtmDeepSkyBlue3 = TColor($00C79030);
clHtmDeepSkyBlue4 = TColor($007E5825);
clHtmDodgerBlue = TColor($00FF8915);
clHtmDodgerBlue2 = TColor($00EC7D15);
clHtmDodgerBlue3 = TColor($00C76915);
clHtmDodgerBlue4 = TColor($007E3E15);
clHtmSteelBlue4 = TColor($007E542B);
clHtmSteelBlue = TColor($00A06348);
clHtmSlateBlue2 = TColor($00EC6069);
clHtmViolet = TColor($00C9388D);
clHtmMediumPurple3 = TColor($00C75D7A);
clHtmMediumPurple = TColor($00D76784);
clHtmMediumPurple2 = TColor($00EC7291);
clHtmMediumPurple1 = TColor($00FF7B9E);
clHtmLightSteelBlue = TColor($00CE8F72);
clHtmSteelBlue3 = TColor($00C78A48);
clHtmSteelBlue2 = TColor($00ECA556);
clHtmSteelBlue1 = TColor($00FFB35C);
clHtmSkyBlue3 = TColor($00C79E65);
clHtmSkyBlue4 = TColor($007E6241);
clHtmSlateBlue3 = TColor($00A17C73);
clHtmSlateGray3 = TColor($00C7AF98);
clHtmVioletRed = TColor($008A35F6);
clHtmVioletRed1 = TColor($008A35F6);
clHtmVioletRed2 = TColor($007F31E4);
clHtmDeepPink = TColor($008728F5);
clHtmDeepPink2 = TColor($007C28E4);
clHtmDeepPink3 = TColor($006722C1);
clHtmDeepPink4 = TColor($003F057D);
clHtmMediumVioletRed = TColor($006B22CA);
clHtmVioletRed3 = TColor($006928C1);
clHtmFirebrick = TColor($00170580);
clHtmVioletRed4 = TColor($0041057D);
clHtmMaroon4 = TColor($0052057D);
clHtmMaroon = TColor($00410581);
clHtmMaroon3 = TColor($008322C1);
clHtmMaroon2 = TColor($009D31E3);
clHtmMaroon1 = TColor($00AA35F5);
clHtmMagenta = TColor($00FF00FF);
clHtmMagenta1 = TColor($00FF33F4);
clHtmMagenta2 = TColor($00EC38E2);
clHtmMagenta3 = TColor($00C731C0);
clHtmMediumOrchid = TColor($00B548B0);
clHtmMediumOrchid1 = TColor($00FF62D4);
clHtmMediumOrchid2 = TColor($00EC5AC4);
clHtmMediumOrchid3 = TColor($00C74AA7);
clHtmMediumOrchid4 = TColor($007E286A);
clHtmPurple = TColor($00EF358E);
clHtmPurple1 = TColor($00FF3B89);
clHtmPurple2 = TColor($00EC387F);
clHtmPurple3 = TColor($00C72D6C);
clHtmPurple4 = TColor($007E1B46);
clHtmDarkOrchid4 = TColor($007E1B57);
clHtmDarkOrchid = TColor($007E1B7D);
clHtmDarkViolet = TColor($00CE2D84);
clHtmDarkOrchid3 = TColor($00C7318B);
clHtmDarkOrchid2 = TColor($00EC3BA2);
clHtmDarkOrchid1 = TColor($00FF41B0);
clHtmPlum4 = TColor($007E587E);
clHtmPaleVioletRed = TColor($008765D1);
clHtmPaleVioletRed1 = TColor($00A178F7);
clHtmPaleVioletRed2 = TColor($00946EE5);
clHtmPaleVioletRed3 = TColor($007C5AC2);
clHtmPaleVioletRed4 = TColor($004D357E);
clHtmPlum = TColor($008F3BB9);
clHtmPlum1 = TColor($00FFB7F9);
clHtmPlum2 = TColor($00ECA9E6);
clHtmPlum3 = TColor($00C78EC3);
clHtmThistle = TColor($00D3B9D2);
clHtmThistle3 = TColor($00C7AEC6);
clHtmLavenderBlush2 = TColor($00E2DDEB);
clHtmLavenderBlush3 = TColor($00BEBBC8);
clHtmThistle2 = TColor($00ECCFE9);
clHtmThistle1 = TColor($00FFDFFC);
clHtmLavender = TColor($00FAE4E3);
clHtmLavenderBlush = TColor($00F4EEFD);
clHtmLightSteelBlue1 = TColor($00FFDEC6);
clHtmLightBlue = TColor($00FFDFAD);
clHtmLightBlue1 = TColor($00FFEDBD);
clHtmLightCyan = TColor($00FFFFE0);
clHtmSlateGray1 = TColor($00FFDFC2);
clHtmSlateGray2 = TColor($00ECCFB4);
clHtmLightSteelBlue2 = TColor($00ECCEB7);
clHtmTurquoise1 = TColor($00FFF352);
clHtmCyan = TColor($00FFFF00);
clHtmCyan1 = TColor($00FFFE57);
clHtmCyan2 = TColor($00ECEB50);
clHtmTurquoise2 = TColor($00ECE24E);
clHtmMediumTurquoise = TColor($00CDCC48);
clHtmTurquoise = TColor($00DBC643);
clHtmDarkSlateGray1 = TColor($00FFFE9A);
clHtmDarkSlateGray2 = TColor($00ECEB8E);
clHtmDarkSlateGray3 = TColor($00C7C778);
clHtmCyan3 = TColor($00C7C746);
clHtmTurquoise3 = TColor($00C7BF43);
clHtmCadetBlue3 = TColor($00C7BF77);
clHtmPaleTurquoise3 = TColor($00C7C792);
clHtmLightBlue2 = TColor($00ECDCAF);
clHtmDarkTurquoise = TColor($009C9C3B);
clHtmCyan4 = TColor($007E7D30);
clHtmLightSeaGreen = TColor($009FA93E);
clHtmLightSkyBlue = TColor($00FACA82);
clHtmLightSkyBlue2 = TColor($00ECCFA0);
clHtmLightSkyBlue3 = TColor($00C7AF87);
clHtmSkyBlue = TColor($00FFCA82);
clHtmSkyBlue2 = TColor($00ECBA79);
clHtmLightSkyBlue4 = TColor($007E6D56);
clHtmSkyBlue5 = TColor($00FF9866);
clHtmLightSlateBlue = TColor($00FF6A73);
clHtmLightCyan2 = TColor($00ECECCF);
clHtmLightCyan3 = TColor($00C7C7AF);
clHtmLightCyan4 = TColor($007D7D71);
clHtmLightBlue3 = TColor($00C7B995);
clHtmLightBlue4 = TColor($007E765E);
clHtmPaleTurquoise4 = TColor($007E7D5E);
clHtmDarkSeaGreen4 = TColor($00587C61);
clHtmMediumAquamarine =TColor($00818734);
clHtmMediumSeaGreen = TColor($00546730);
clHtmSeaGreen = TColor($0075894E);
clHtmDarkGreen = TColor($00174125);
clHtmSeaGreen4 = TColor($00447C38);
clHtmForestGreen = TColor($0058924E);
clHtmMediumForestGreen = TColor($00357234);
clHtmSpringGreen4 = TColor($002C7C34);
clHtmDarkOliveGreen4 = TColor($00267C66);
clHtmChartreuse4 = TColor($00177C43);
clHtmGreen4 = TColor($00177C34);
clHtmMediumSpringGreen = TColor($00178034);
clHtmSpringGreen = TColor($002CA04A);
clHtmLimeGreen = TColor($0017A341);
clHtmDarkSeaGreen = TColor($0081B38B);
clHtmDarkSeaGreen3 = TColor($008EC699);
clHtmGreen3 = TColor($0017C44C);
clHtmChartreuse3 = TColor($0017C46C);
clHtmYellowGreen = TColor($0017D052);
clHtmSpringGreen3 = TColor($0052C54C);
clHtmSeaGreen3 = TColor($0071C554);
clHtmSpringGreen2 = TColor($0064E957);
clHtmSpringGreen1 = TColor($006EFB5E);
clHtmSeaGreen2 = TColor($0086E964);
clHtmSeaGreen1 = TColor($0092FB6A);
clHtmDarkSeaGreen2 = TColor($00AAEAB5);
clHtmDarkSeaGreen1 = TColor($00B8FDC3);
clHtmGreen = TColor($0000FF00);
clHtmLawnGreen = TColor($0017F787);
clHtmGreen1 = TColor($0017FB5F);
clHtmGreen2 = TColor($0017E859);
clHtmChartreuse2 = TColor($0017E87F);
clHtmChartreuse = TColor($0017FB8A);
clHtmGreenYellow = TColor($0017FBB1);
clHtmDarkOliveGreen1 = TColor($005DFBCC);
clHtmDarkOliveGreen2 = TColor($0054E9BC);
clHtmDarkOliveGreen3 = TColor($0044C5A0);
clHtmYellow = TColor($0000FFFF);
clHtmYellow1 = TColor($0017FCFF);
clHtmKhaki1 = TColor($0080F3FF);
clHtmKhaki2 = TColor($0075E2ED);
clHtmGoldenrod = TColor($0074DAED);
clHtmGold2 = TColor($0017C1EA);
clHtmGold1 = TColor($0017D0FD);
clHtmGoldenrod1 = TColor($0017B9FB);
clHtmGoldenrod2 = TColor($0017ABE9);
clHtmGold = TColor($0017A0D4);
clHtmGold3 = TColor($0017A3C7);
clHtmGoldenrod3 = TColor($00178EC6);
clHtmDarkGoldenrod = TColor($001778AF);
clHtmKhaki = TColor($006EA9AD);
clHtmKhaki3 = TColor($0062BEC9);
clHtmKhaki4 = TColor($00397882);
clHtmDarkGoldenrod1 = TColor($0017B1FB);
clHtmDarkGoldenrod2 = TColor($0017A3E8);
clHtmDarkGoldenrod3 = TColor($001789C5);
clHtmSienna1 = TColor($003174F8);
clHtmSienna2 = TColor($002C6CE6);
clHtmDarkOrange = TColor($001780F8);
clHtmDarkOrange1 = TColor($001772F8);
clHtmDarkOrange2 = TColor($001767E5);
clHtmDarkOrange3 = TColor($001756C3);
clHtmSienna3 = TColor($001758C3);
clHtmSienna = TColor($0017418A);
clHtmSienna4 = TColor($0017357E);
clHtmIndianRed4 = TColor($0017227E);
clHtmDarkOrange4 = TColor($0017317E);
clHtmSalmon4 = TColor($0017387E);
clHtmDarkGoldenrod4 = TColor($0017527F);
clHtmGold4 = TColor($00176580);
clHtmGoldenrod4 = TColor($00175880);
clHtmLightSalmon4 = TColor($002C467F);
clHtmChocolate = TColor($00175AC8);
clHtmCoral3 = TColor($002C4AC3);
clHtmCoral2 = TColor($003C5BE5);
clHtmCoral = TColor($004165F7);
clHtmDarkSalmon = TColor($006B8BE1);
clHtmSalmon1 = TColor($005881F8);
clHtmSalmon2 = TColor($005174E6);
clHtmSalmon3 = TColor($004162C3);
clHtmLightSalmon3 = TColor($005174C4);
clHtmLightSalmon2 = TColor($00618AE7);
clHtmLightSalmon = TColor($006B96F9);
clHtmSandyBrown = TColor($004D9AEE);
clHtmHotPink = TColor($00AB60F6);
clHtmHotPink1 = TColor($00AB65F6);
clHtmHotPink2 = TColor($009D5EE4);
clHtmHotPink3 = TColor($008352C2);
clHtmHotPink4 = TColor($0052227D);
clHtmLightCoral = TColor($007174E7);
clHtmIndianRed1 = TColor($00595DF7);
clHtmIndianRed2 = TColor($005154E5);
clHtmIndianRed3 = TColor($004146C2);
clHtmRed = TColor($000000FF);
clHtmRed1 = TColor($001722F6);
clHtmRed2 = TColor($00171BE4);
clHtmFirebrick1 = TColor($001728F6);
clHtmFirebrick2 = TColor($001722E4);
clHtmFirebrick3 = TColor($00171BC1);
clHtmPink = TColor($00BEAFFA);
clHtmRosyBrown1 = TColor($00B9BBFB);
clHtmRosyBrown2 = TColor($00AAADE8);
clHtmPink2 = TColor($00B0A1E7);
clHtmLightPink = TColor($00BAAFFA);
clHtmLightPink1 = TColor($00B0A7F9);
clHtmLightPink2 = TColor($00A399E7);
clHtmPink3 = TColor($009387C4);
clHtmRosyBrown3 = TColor($008E90C5);
clHtmRosyBrown = TColor($008184B3);
clHtmLightPink3 = TColor($008981C4);
clHtmRosyBrown4 = TColor($00585A7F);
clHtmLightPink4 = TColor($00524E7F);
clHtmPink4 = TColor($005D527F);
clHtmLavenderBlush4 = TColor($00797681);
clHtmLightGoldenrod4 =TColor($00397381);
clHtmLemonChiffon4 = TColor($00607B82);
clHtmLemonChiffon3 = TColor($0099C2C9);
clHtmLightGoldenrod3 =TColor($0060B5C8);
clHtmLightGolden2 = TColor($0072D6EC);
clHtmLightGoldenrod = TColor($0072D8EC);
clHtmLightGoldenrod1 =TColor($007CE8FF);
clHtmLemonChiffon2 = TColor($00B6E5EC);
clHtmLemonChiffon = TColor($00C6F8FF);
clHtmLightGoldenrodYellow = TColor($00CCF8FA);
clCosmicLatte = TColor($00FFF8E7);
implementation
uses
{$IFDEF RX_D5}Windows, {$ENDIF}SysUtils; // Polaris
type
TColorEntry = record
Value: TColor;
Name: PChar;
end;
const
ColorCount = 3{$IFDEF RX_COLOR_APPENDED} + 34 + 295 + 1{$ENDIF};
Colors: array[0..ColorCount - 1] of TColorEntry = (
(Value: clCream; Name: 'clCream'),
(Value: clMoneyGreen; Name: 'clMoneyGreen'),
(Value: clSkyBlue; Name: 'clSkyBlue')
{$IFDEF RX_COLOR_APPENDED},
{ added colors }
(Value: clWavePale; Name: 'clWavePale'),
(Value: clWaveDarkGray; Name: 'clWaveDarkGray'),
(Value: clWaveGray; Name: 'clWaveGray'),
(Value: clWaveLightGray; Name: 'clWaveLightGray'),
(Value: clWaveBeige; Name: 'clWaveBeige'),
(Value: clWaveBrightBeige; Name: 'clWaveBrightBeige'),
(Value: clWaveLightBeige; Name: 'clWaveLightBeige'),
(Value: clWaveCyan; Name: 'clWaveCyan'),
(Value: clWaveBrightCyan; Name: 'clWaveBrightCyan'),
(Value: clWaveLightCyan; Name: 'clWaveLightCyan'),
(Value: clWaveGreen; Name: 'clWaveGreen'),
(Value: clWaveBrightGreen; Name: 'clWaveBrightGreen'),
(Value: clWaveLightGreen; Name: 'clWaveLightGreen'),
(Value: clWaveViolet; Name: 'clWaveViolet'),
(Value: clWaveBrightViolet; Name: 'clWaveBrightViolet'),
(Value: clWaveLightViolet; Name: 'clWaveLightViolet'),
{ Standard Encarta & FlatStyle Color Constants }
(Value: clRxDarkBlue; Name: 'clRxDarkBlue'),
(Value: clRxBlue; Name: 'clRxBlue'),
(Value: clRxLightBlue; Name: 'clRxLightBlue'),
(Value: clRxDarkRed; Name: 'clRxDarkRed'),
(Value: clRxRed; Name: 'clRxRed'),
(Value: clRxLightRed; Name: 'clRxLightRed'),
(Value: clRxDarkGreen; Name: 'clRxDarkGreen'),
(Value: clRxGreen; Name: 'clRxGreen'),
(Value: clRxLightGreen; Name: 'clRxLightGreen'),
(Value: clRxDarkYellow; Name: 'clRxDarkYellow'),
(Value: clRxYellow; Name: 'clRxYellow'),
(Value: clRxLightYellow; Name: 'clRxLightYellow'),
(Value: clRxDarkBrown; Name: 'clRxDarkBrown'),
(Value: clRxBrown; Name: 'clRxBrown'),
(Value: clRxLightBrown; Name: 'clRxLightBrown'),
(Value: clRxDarkKhaki; Name: 'clRxDarkKhaki'),
(Value: clRxKhaki; Name: 'clRxKhaki'),
(Value: clRxLightKhaki; Name: 'clRxLightKhaki'),
{ added standard named html colors }
(Value: clHtmBlack; Name: 'clHtmBlack'),
(Value: clHtmGray0; Name: 'clHtmGray0'),
(Value: clHtmGray18; Name: 'clHtmGray18'),
(Value: clHtmGray21; Name: 'clHtmGray21'),
(Value: clHtmGray23; Name: 'clHtmGray23'),
(Value: clHtmGray24; Name: 'clHtmGray24'),
(Value: clHtmGray25; Name: 'clHtmGray25'),
(Value: clHtmGray26; Name: 'clHtmGray26'),
(Value: clHtmGray27; Name: 'clHtmGray27'),
(Value: clHtmGray28; Name: 'clHtmGray28'),
(Value: clHtmGray29; Name: 'clHtmGray29'),
(Value: clHtmGray30; Name: 'clHtmGray30'),
(Value: clHtmGray31; Name: 'clHtmGray31'),
(Value: clHtmGray32; Name: 'clHtmGray32'),
(Value: clHtmGray34; Name: 'clHtmGray34'),
(Value: clHtmGray35; Name: 'clHtmGray35'),
(Value: clHtmGray36; Name: 'clHtmGray36'),
(Value: clHtmGray37; Name: 'clHtmGray37'),
(Value: clHtmGray38; Name: 'clHtmGray38'),
(Value: clHtmGray39; Name: 'clHtmGray39'),
(Value: clHtmGray40; Name: 'clHtmGray40'),
(Value: clHtmGray41; Name: 'clHtmGray41'),
(Value: clHtmGray42; Name: 'clHtmGray42'),
(Value: clHtmGray43; Name: 'clHtmGray43'),
(Value: clHtmGray44; Name: 'clHtmGray44'),
(Value: clHtmGray45; Name: 'clHtmGray45'),
(Value: clHtmGray46; Name: 'clHtmGray46'),
(Value: clHtmGray47; Name: 'clHtmGray47'),
(Value: clHtmGray48; Name: 'clHtmGray48'),
(Value: clHtmGray49; Name: 'clHtmGray49'),
(Value: clHtmGray50; Name: 'clHtmGray50'),
(Value: clHtmGray; Name: 'clHtmGray'),
(Value: clHtmSlateGray4; Name: 'clHtmSlateGray4'),
(Value: clHtmSlateGray; Name: 'clHtmSlateGray'),
(Value: clHtmLightSteelBlue4; Name: 'clHtmLightSteelBlue4'),
(Value: clHtmLightSlateGray; Name: 'clHtmLightSlateGray'),
(Value: clHtmCadetBlue4; Name: 'clHtmCadetBlue4'),
(Value: clHtmDarkSlateGray4; Name: 'clHtmDarkSlateGray4'),
(Value: clHtmThistle4; Name: 'clHtmThistle4'),
(Value: clHtmMediumSlateBlue; Name: 'clHtmMediumSlateBlue'),
(Value: clHtmMediumPurple4; Name: 'clHtmMediumPurple4'),
(Value: clHtmMidnightBlue; Name: 'clHtmMidnightBlue'),
(Value: clHtmDarkSlateBlue; Name: 'clHtmDarkSlateBlue'),
(Value: clHtmDarkSlateGray; Name: 'clHtmDarkSlateGray'),
(Value: clHtmDimGray; Name: 'clHtmDimGray'),
(Value: clHtmCornflowerBlue; Name: 'clHtmCornflowerBlue'),
(Value: clHtmRoyalBlue4; Name: 'clHtmRoyalBlue4'),
(Value: clHtmSlateBlue4; Name: 'clHtmSlateBlue4'),
(Value: clHtmRoyalBlue; Name: 'clHtmRoyalBlue'),
(Value: clHtmRoyalBlue1; Name: 'clHtmRoyalBlue1'),
(Value: clHtmRoyalBlue2; Name: 'clHtmRoyalBlue2'),
(Value: clHtmRoyalBlue3; Name: 'clHtmRoyalBlue3'),
(Value: clHtmDeepSkyBlue; Name: 'clHtmDeepSkyBlue'),
(Value: clHtmDeepSkyBlue2; Name: 'clHtmDeepSkyBlue2'),
(Value: clHtmSlateBlue; Name: 'clHtmSlateBlue'),
(Value: clHtmDeepSkyBlue3; Name: 'clHtmDeepSkyBlue3'),
(Value: clHtmDeepSkyBlue4; Name: 'clHtmDeepSkyBlue4'),
(Value: clHtmDodgerBlue; Name: 'clHtmDodgerBlue'),
(Value: clHtmDodgerBlue2; Name: 'clHtmDodgerBlue2'),
(Value: clHtmDodgerBlue3; Name: 'clHtmDodgerBlue3'),
(Value: clHtmDodgerBlue4; Name: 'clHtmDodgerBlue4'),
(Value: clHtmSteelBlue4; Name: 'clHtmSteelBlue4'),
(Value: clHtmSteelBlue; Name: 'clHtmSteelBlue'),
(Value: clHtmSlateBlue2; Name: 'clHtmSlateBlue2'),
(Value: clHtmViolet; Name: 'clHtmViolet'),
(Value: clHtmMediumPurple3; Name: 'clHtmMediumPurple3'),
(Value: clHtmMediumPurple; Name: 'clHtmMediumPurple'),
(Value: clHtmMediumPurple2; Name: 'clHtmMediumPurple2'),
(Value: clHtmMediumPurple1; Name: 'clHtmMediumPurple1'),
(Value: clHtmLightSteelBlue; Name: 'clHtmLightSteelBlue'),
(Value: clHtmSteelBlue3; Name: 'clHtmSteelBlue3'),
(Value: clHtmSteelBlue2; Name: 'clHtmSteelBlue2'),
(Value: clHtmSteelBlue1; Name: 'clHtmSteelBlue1'),
(Value: clHtmSkyBlue3; Name: 'clHtmSkyBlue3'),
(Value: clHtmSkyBlue4; Name: 'clHtmSkyBlue4'),
(Value: clHtmSlateBlue3; Name: 'clHtmSlateBlue3'),
(Value: clHtmSlateGray3; Name: 'clHtmSlateGray3'),
(Value: clHtmVioletRed; Name: 'clHtmVioletRed'),
(Value: clHtmVioletRed1; Name: 'clHtmVioletRed1'),
(Value: clHtmVioletRed2; Name: 'clHtmVioletRed2'),
(Value: clHtmDeepPink; Name: 'clHtmDeepPink'),
(Value: clHtmDeepPink2; Name: 'clHtmDeepPink2'),
(Value: clHtmDeepPink3; Name: 'clHtmDeepPink3'),
(Value: clHtmDeepPink4; Name: 'clHtmDeepPink4'),
(Value: clHtmMediumVioletRed; Name: 'clHtmMediumVioletRed'),
(Value: clHtmVioletRed3; Name: 'clHtmVioletRed3'),
(Value: clHtmFirebrick; Name: 'clHtmFirebrick'),
(Value: clHtmVioletRed4; Name: 'clHtmVioletRed4'),
(Value: clHtmMaroon4; Name: 'clHtmMaroon4'),
(Value: clHtmMaroon; Name: 'clHtmMaroon'),
(Value: clHtmMaroon3; Name: 'clHtmMaroon3'),
(Value: clHtmMaroon2; Name: 'clHtmMaroon2'),
(Value: clHtmMaroon1; Name: 'clHtmMaroon1'),
(Value: clHtmMagenta; Name: 'clHtmMagenta'),
(Value: clHtmMagenta1; Name: 'clHtmMagenta1'),
(Value: clHtmMagenta2; Name: 'clHtmMagenta2'),
(Value: clHtmMagenta3; Name: 'clHtmMagenta3'),
(Value: clHtmMediumOrchid; Name: 'clHtmMediumOrchid'),
(Value: clHtmMediumOrchid1; Name: 'clHtmMediumOrchid1'),
(Value: clHtmMediumOrchid2; Name: 'clHtmMediumOrchid2'),
(Value: clHtmMediumOrchid3; Name: 'clHtmMediumOrchid3'),
(Value: clHtmMediumOrchid4; Name: 'clHtmMediumOrchid4'),
(Value: clHtmPurple; Name: 'clHtmPurple'),
(Value: clHtmPurple1; Name: 'clHtmPurple1'),
(Value: clHtmPurple2; Name: 'clHtmPurple2'),
(Value: clHtmPurple3; Name: 'clHtmPurple3'),
(Value: clHtmPurple4; Name: 'clHtmPurple4'),
(Value: clHtmDarkOrchid4; Name: 'clHtmDarkOrchid4'),
(Value: clHtmDarkOrchid; Name: 'clHtmDarkOrchid'),
(Value: clHtmDarkViolet; Name: 'clHtmDarkViolet'),
(Value: clHtmDarkOrchid3; Name: 'clHtmDarkOrchid3'),
(Value: clHtmDarkOrchid2; Name: 'clHtmDarkOrchid2'),
(Value: clHtmDarkOrchid1; Name: 'clHtmDarkOrchid1'),
(Value: clHtmPlum4; Name: 'clHtmPlum4'),
(Value: clHtmPaleVioletRed; Name: 'clHtmPaleVioletRed'),
(Value: clHtmPaleVioletRed1; Name: 'clHtmPaleVioletRed1'),
(Value: clHtmPaleVioletRed2; Name: 'clHtmPaleVioletRed2'),
(Value: clHtmPaleVioletRed3; Name: 'clHtmPaleVioletRed3'),
(Value: clHtmPaleVioletRed4; Name: 'clHtmPaleVioletRed4'),
(Value: clHtmPlum; Name: 'clHtmPlum'),
(Value: clHtmPlum1; Name: 'clHtmPlum1'),
(Value: clHtmPlum2; Name: 'clHtmPlum2'),
(Value: clHtmPlum3; Name: 'clHtmPlum3'),
(Value: clHtmThistle; Name: 'clHtmThistle'),
(Value: clHtmThistle3; Name: 'clHtmThistle3'),
(Value: clHtmLavenderBlush2; Name: 'clHtmLavenderBlush2'),
(Value: clHtmLavenderBlush3; Name: 'clHtmLavenderBlush3'),
(Value: clHtmThistle2; Name: 'clHtmThistle2'),
(Value: clHtmThistle1; Name: 'clHtmThistle1'),
(Value: clHtmLavender; Name: 'clHtmLavender'),
(Value: clHtmLavenderBlush; Name: 'clHtmLavenderBlush'),
(Value: clHtmLightSteelBlue1; Name: 'clHtmLightSteelBlue1'),
(Value: clHtmLightBlue; Name: 'clHtmLightBlue'),
(Value: clHtmLightBlue1; Name: 'clHtmLightBlue1'),
(Value: clHtmLightCyan; Name: 'clHtmLightCyan'),
(Value: clHtmSlateGray1; Name: 'clHtmSlateGray1'),
(Value: clHtmSlateGray2; Name: 'clHtmSlateGray2'),
(Value: clHtmLightSteelBlue2; Name: 'clHtmLightSteelBlue2'),
(Value: clHtmTurquoise1; Name: 'clHtmTurquoise1'),
(Value: clHtmCyan; Name: 'clHtmCyan'),
(Value: clHtmCyan1; Name: 'clHtmCyan1'),
(Value: clHtmCyan2; Name: 'clHtmCyan2'),
(Value: clHtmTurquoise2; Name: 'clHtmTurquoise2'),
(Value: clHtmMediumTurquoise; Name: 'clHtmMediumTurquoise'),
(Value: clHtmTurquoise; Name: 'clHtmTurquoise'),
(Value: clHtmDarkSlateGray1; Name: 'clHtmDarkSlateGray1'),
(Value: clHtmDarkSlateGray2; Name: 'clHtmDarkSlateGray2'),
(Value: clHtmDarkSlateGray3; Name: 'clHtmDarkSlateGray3'),
(Value: clHtmCyan3; Name: 'clHtmCyan3'),
(Value: clHtmTurquoise3; Name: 'clHtmTurquoise3'),
(Value: clHtmCadetBlue3; Name: 'clHtmCadetBlue3'),
(Value: clHtmPaleTurquoise3; Name: 'clHtmPaleTurquoise3'),
(Value: clHtmLightBlue2; Name: 'clHtmLightBlue2'),
(Value: clHtmDarkTurquoise; Name: 'clHtmDarkTurquoise'),
(Value: clHtmCyan4; Name: 'clHtmCyan4'),
(Value: clHtmLightSeaGreen; Name: 'clHtmLightSeaGreen'),
(Value: clHtmLightSkyBlue; Name: 'clHtmLightSkyBlue'),
(Value: clHtmLightSkyBlue2; Name: 'clHtmLightSkyBlue2'),
(Value: clHtmLightSkyBlue3; Name: 'clHtmLightSkyBlue3'),
(Value: clHtmSkyBlue; Name: 'clHtmSkyBlue'),
(Value: clHtmSkyBlue2; Name: 'clHtmSkyBlue2'),
(Value: clHtmLightSkyBlue4; Name: 'clHtmLightSkyBlue4'),
(Value: clHtmSkyBlue5; Name: 'clHtmSkyBlue5'),
(Value: clHtmLightSlateBlue; Name: 'clHtmLightSlateBlue'),
(Value: clHtmLightCyan2; Name: 'clHtmLightCyan2'),
(Value: clHtmLightCyan3; Name: 'clHtmLightCyan3'),
(Value: clHtmLightCyan4; Name: 'clHtmLightCyan4'),
(Value: clHtmLightBlue3; Name: 'clHtmLightBlue3'),
(Value: clHtmLightBlue4; Name: 'clHtmLightBlue4'),
(Value: clHtmPaleTurquoise4; Name: 'clHtmPaleTurquoise4'),
(Value: clHtmDarkSeaGreen4; Name: 'clHtmDarkSeaGreen4'),
(Value: clHtmMediumAquamarine; Name: 'clHtmMediumAquamarine'),
(Value: clHtmMediumSeaGreen; Name: 'clHtmMediumSeaGreen'),
(Value: clHtmSeaGreen; Name: 'clHtmSeaGreen'),
(Value: clHtmDarkGreen; Name: 'clHtmDarkGreen'),
(Value: clHtmSeaGreen4; Name: 'clHtmSeaGreen4'),
(Value: clHtmForestGreen; Name: 'clHtmForestGreen'),
(Value: clHtmMediumForestGreen; Name: 'clHtmMediumForestGreen'),
(Value: clHtmSpringGreen4; Name: 'clHtmSpringGreen4'),
(Value: clHtmDarkOliveGreen4; Name: 'clHtmDarkOliveGreen4'),
(Value: clHtmChartreuse4; Name: 'clHtmChartreuse4'),
(Value: clHtmGreen4; Name: 'clHtmGreen4'),
(Value: clHtmMediumSpringGreen; Name: 'clHtmMediumSpringGreen'),
(Value: clHtmSpringGreen; Name: 'clHtmSpringGreen'),
(Value: clHtmLimeGreen; Name: 'clHtmLimeGreen'),
(Value: clHtmDarkSeaGreen; Name: 'clHtmDarkSeaGreen'),
(Value: clHtmDarkSeaGreen3; Name: 'clHtmDarkSeaGreen3'),
(Value: clHtmGreen3; Name: 'clHtmGreen3'),
(Value: clHtmChartreuse3; Name: 'clHtmChartreuse3'),
(Value: clHtmYellowGreen; Name: 'clHtmYellowGreen'),
(Value: clHtmSpringGreen3; Name: 'clHtmSpringGreen3'),
(Value: clHtmSeaGreen3; Name: 'clHtmSeaGreen3'),
(Value: clHtmSpringGreen2; Name: 'clHtmSpringGreen2'),
(Value: clHtmSpringGreen1; Name: 'clHtmSpringGreen1'),
(Value: clHtmSeaGreen2; Name: 'clHtmSeaGreen2'),
(Value: clHtmSeaGreen1; Name: 'clHtmSeaGreen1'),
(Value: clHtmDarkSeaGreen2; Name: 'clHtmDarkSeaGreen2'),
(Value: clHtmDarkSeaGreen1; Name: 'clHtmDarkSeaGreen1'),
(Value: clHtmGreen; Name: 'clHtmGreen'),
(Value: clHtmLawnGreen; Name: 'clHtmLawnGreen'),
(Value: clHtmGreen1; Name: 'clHtmGreen1'),
(Value: clHtmGreen2; Name: 'clHtmGreen2'),
(Value: clHtmChartreuse2; Name: 'clHtmChartreuse2'),
(Value: clHtmChartreuse; Name: 'clHtmChartreuse'),
(Value: clHtmGreenYellow; Name: 'clHtmGreenYellow'),
(Value: clHtmDarkOliveGreen1; Name: 'clHtmDarkOliveGreen1'),
(Value: clHtmDarkOliveGreen2; Name: 'clHtmDarkOliveGreen2'),
(Value: clHtmDarkOliveGreen3; Name: 'clHtmDarkOliveGreen3'),
(Value: clHtmYellow; Name: 'clHtmYellow'),
(Value: clHtmYellow1; Name: 'clHtmYellow1'),
(Value: clHtmKhaki1; Name: 'clHtmKhaki1'),
(Value: clHtmKhaki2; Name: 'clHtmKhaki2'),
(Value: clHtmGoldenrod; Name: 'clHtmGoldenrod'),
(Value: clHtmGold2; Name: 'clHtmGold2'),
(Value: clHtmGold1; Name: 'clHtmGold1'),
(Value: clHtmGoldenrod1; Name: 'clHtmGoldenrod1'),
(Value: clHtmGoldenrod2; Name: 'clHtmGoldenrod2'),
(Value: clHtmGold; Name: 'clHtmGold'),
(Value: clHtmGold3; Name: 'clHtmGold3'),
(Value: clHtmGoldenrod3; Name: 'clHtmGoldenrod3'),
(Value: clHtmDarkGoldenrod; Name: 'clHtmDarkGoldenrod'),
(Value: clHtmKhaki; Name: 'clHtmKhaki'),
(Value: clHtmKhaki3; Name: 'clHtmKhaki3'),
(Value: clHtmKhaki4; Name: 'clHtmKhaki4'),
(Value: clHtmDarkGoldenrod1; Name: 'clHtmDarkGoldenrod1'),
(Value: clHtmDarkGoldenrod2; Name: 'clHtmDarkGoldenrod2'),
(Value: clHtmDarkGoldenrod3; Name: 'clHtmDarkGoldenrod3'),
(Value: clHtmSienna1; Name: 'clHtmSienna1'),
(Value: clHtmSienna2; Name: 'clHtmSienna2'),
(Value: clHtmDarkOrange; Name: 'clHtmDarkOrange'),
(Value: clHtmDarkOrange1; Name: 'clHtmDarkOrange1'),
(Value: clHtmDarkOrange2; Name: 'clHtmDarkOrange2'),
(Value: clHtmDarkOrange3; Name: 'clHtmDarkOrange3'),
(Value: clHtmSienna3; Name: 'clHtmSienna3'),
(Value: clHtmSienna; Name: 'clHtmSienna'),
(Value: clHtmSienna4; Name: 'clHtmSienna4'),
(Value: clHtmIndianRed4; Name: 'clHtmIndianRed4'),
(Value: clHtmDarkOrange4; Name: 'clHtmDarkOrange4'),
(Value: clHtmSalmon4; Name: 'clHtmSalmon4'),
(Value: clHtmDarkGoldenrod4; Name: 'clHtmDarkGoldenrod4'),
(Value: clHtmGold4; Name: 'clHtmGold4'),
(Value: clHtmGoldenrod4; Name: 'clHtmGoldenrod4'),
(Value: clHtmLightSalmon4; Name: 'clHtmLightSalmon4'),
(Value: clHtmChocolate; Name: 'clHtmChocolate'),
(Value: clHtmCoral3; Name: 'clHtmCoral3'),
(Value: clHtmCoral2; Name: 'clHtmCoral2'),
(Value: clHtmCoral; Name: 'clHtmCoral'),
(Value: clHtmDarkSalmon; Name: 'clHtmDarkSalmon'),
(Value: clHtmSalmon1; Name: 'clHtmSalmon1'),
(Value: clHtmSalmon2; Name: 'clHtmSalmon2'),
(Value: clHtmSalmon3; Name: 'clHtmSalmon3'),
(Value: clHtmLightSalmon3; Name: 'clHtmLightSalmon3'),
(Value: clHtmLightSalmon2; Name: 'clHtmLightSalmon2'),
(Value: clHtmLightSalmon; Name: 'clHtmLightSalmon'),
(Value: clHtmSandyBrown; Name: 'clHtmSandyBrown'),
(Value: clHtmHotPink; Name: 'clHtmHotPink'),
(Value: clHtmHotPink1; Name: 'clHtmHotPink1'),
(Value: clHtmHotPink2; Name: 'clHtmHotPink2'),
(Value: clHtmHotPink3; Name: 'clHtmHotPink3'),
(Value: clHtmHotPink4; Name: 'clHtmHotPink4'),
(Value: clHtmLightCoral; Name: 'clHtmLightCoral'),
(Value: clHtmIndianRed1; Name: 'clHtmIndianRed1'),
(Value: clHtmIndianRed2; Name: 'clHtmIndianRed2'),
(Value: clHtmIndianRed3; Name: 'clHtmIndianRed3'),
(Value: clHtmRed; Name: 'clHtmRed'),
(Value: clHtmRed1; Name: 'clHtmRed1'),
(Value: clHtmRed2; Name: 'clHtmRed2'),
(Value: clHtmFirebrick1; Name: 'clHtmFirebrick1'),
(Value: clHtmFirebrick2; Name: 'clHtmFirebrick2'),
(Value: clHtmFirebrick3; Name: 'clHtmFirebrick3'),
(Value: clHtmPink; Name: 'clHtmPink'),
(Value: clHtmRosyBrown1; Name: 'clHtmRosyBrown1'),
(Value: clHtmRosyBrown2; Name: 'clHtmRosyBrown2'),
(Value: clHtmPink2; Name: 'clHtmPink2'),
(Value: clHtmLightPink; Name: 'clHtmLightPink'),
(Value: clHtmLightPink1; Name: 'clHtmLightPink1'),
(Value: clHtmLightPink2; Name: 'clHtmLightPink2'),
(Value: clHtmPink3; Name: 'clHtmPink3'),
(Value: clHtmRosyBrown3; Name: 'clHtmRosyBrown3'),
(Value: clHtmRosyBrown; Name: 'clHtmRosyBrown'),
(Value: clHtmLightPink3; Name: 'clHtmLightPink3'),
(Value: clHtmRosyBrown4; Name: 'clHtmRosyBrown4'),
(Value: clHtmLightPink4; Name: 'clHtmLightPink4'),
(Value: clHtmPink4; Name: 'clHtmPink4'),
(Value: clHtmLavenderBlush4; Name: 'clHtmLavenderBlush4'),
(Value: clHtmLightGoldenrod4; Name: 'clHtmLightGoldenrod4'),
(Value: clHtmLemonChiffon4; Name: 'clHtmLemonChiffon4'),
(Value: clHtmLemonChiffon3; Name: 'clHtmLemonChiffon3'),
(Value: clHtmLightGoldenrod3; Name: 'clHtmLightGoldenrod3'),
(Value: clHtmLightGolden2; Name: 'clHtmLightGolden2'),
(Value: clHtmLightGoldenrod; Name: 'clHtmLightGoldenrod'),
(Value: clHtmLightGoldenrod1; Name: 'clHtmLightGoldenrod1'),
(Value: clHtmLemonChiffon2; Name: 'clHtmLemonChiffon2'),
(Value: clHtmLemonChiffon; Name: 'clHtmLemonChiffon'),
(Value: clHtmLightGoldenrodYellow; Name: 'clHtmLightGoldenrodYellow'),
(Value: clCosmicLatte; Name: 'clCosmicLatte')
{$ENDIF}
);
function RxColorToString(Color: TColor): string;
var
I: Integer;
begin
if not ColorToIdent(Color, Result) then
begin
for I := Low(Colors) to High(Colors) do
if Colors[I].Value = Color then
begin
Result := Colors[I].Name;
Exit;
end;
Result := Format('$%.8x', [Color]);
end;
end;
function RxIdentToColor(const Ident: string; var Color: TColor): Boolean;
var
I: Integer;
begin
{own colors}
for I := Low(Colors) to High(Colors) do
if AnsiCompareText(Colors[I].Name, Ident) = 0 then
begin
Color := Colors[I].Value;
Result := True;
Exit;
end;
{systems colors}
Result := IdentToColor(Ident, Integer(Color));
end;
function RxStringToColor(S: string): TColor;
begin
if not RxIdentToColor(S, Result) then
try
Result := StringToColor(S);
except
Result := clNone;
end;
end;
procedure RxGetColorValues(Proc: TGetStrProc);
var
I: Integer;
begin
GetColorValues(Proc);
for I := Low(Colors) to High(Colors) do
Proc(StrPas(Colors[I].Name));
end;
end.
|
{
ID: a2peter1
PROG: cowtour
LANG: PASCAL
}
{$B-,I-,Q-,R-,S-}
const
problem = 'cowtour';
MaxN = 150;
oo = 1 shl 30;
var
ch : char;
sol,t : real;
N,S,i,j : longint;
farth,fcp : array[0..MaxN] of real;
X,Y,comp : array[0..MaxN] of longint;
mat : array[0..MaxN,0..MaxN] of boolean;
procedure dfs(i: longint);
var j : longint;
begin
comp[i] := S;
for j := 1 to N do
if mat[i,j] and (comp[j] = 0) then dfs(j);
end;{dfs}
function dist(i,j: longint): real;
begin
dist := sqrt(sqr(X[i] - X[j]) + sqr(Y[i] - Y[j]));
end;{dist}
function max3(a,b,c: real): real;
var tmp : real;
begin
if a > b then tmp := a else tmp := b;
if c > tmp then tmp := c;
max3 := tmp;
end;{max3}
begin
assign(input,problem + '.in'); reset(input);
assign(output,problem + '.out'); rewrite(output);
readln(N);
for i := 1 to N
do readln(X[i],Y[i]);
for i := 1 to N do
begin
for j := 1 to N do
begin
read(ch);
mat[i,j] := (ch = '1');
end;{for}
readln;
end;{for}
for i := 1 to N do
if comp[i] = 0 then
begin
inc(S); dfs(i);
end;{then}
for i := 1 to N do
for j := 1 to N do
if (comp[j] = comp[i]) and (dist(i,j) > farth[i])
then farth[i] := dist(i,j);
for i := 1 to S do
for j := 1 to N do
if (comp[j] = i) and (farth[j] > fcp[i])
then fcp[i] := farth[j];
sol := oo;
for i := 1 to N do
for j := 1 to N do
if (i <> j) and (comp[i] <> comp[j]) then
begin
t := max3(fcp[comp[i]],fcp[comp[j]],farth[i] + farth[j] + dist(i,j));
if t < sol then sol := t;
end;{then}
writeln(sol:0:6);
close(output);
end.{main}
|
unit TestFileConverter;
{(*}
(*------------------------------------------------------------------------------
Delphi Code formatter source code
The Original Code is TestFileConverter.pas, released December 2005.
The Initial Developer of the Original Code is Anthony Steele.
Portions created by Anthony Steele are Copyright (C) 2001 Anthony Steele.
All Rights Reserved.
Contributor(s): Anthony Steele.
The contents of this file are subject to the Mozilla Public License Version 1.1
(the "License"). you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.mozilla.org/NPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied.
See the License for the specific language governing rights and limitations
under the License.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 or later (the "GPL")
See http://www.gnu.org/licenses/gpl.html
------------------------------------------------------------------------------*)
{*)}
{$I JcfGlobal.inc}
interface
{
AFS 16 December 2005
I introduced a bug in FileConverter in v 2.16
My bad for not having test cases that would have caught it
So, here they are }
uses
SysUtils,
TestFramework,
FileConverter;
type
TTestFileConverter = class(TTestCase)
private
fcFileCoverter: TFileConverter;
fsFileName: string;
fsBackFileName: string;
fsOutFileName: string;
protected
procedure SetUp; override;
procedure TearDown; override;
public
published
procedure TestInPlace;
procedure TestInPlaceWithBackup;
procedure TestSeparateOutput;
end;
implementation
uses
Windows,
JclFileUtils, JcfStringUtils,
ConvertTypes;
const
// a unit that needs formatting
UNIT_TEXT = 'unit TestUnit; interface implementation uses SysUtils; const aConst = 3; end.';
function TimesEqual(const prFileTime1, prFileTime2: TFileTime): boolean;
begin
Result := (prFileTime1.dwLowDateTime = prFileTime2.dwLowDateTime) and
(prFileTime1.dwHighDateTime = prFileTime2.dwHighDateTime);
end;
procedure TTestFileConverter.SetUp;
var
lsBaseFileName: string;
begin
inherited;
fcFileCoverter := TFileConverter.Create;
fcFileCoverter.SourceMode := fmSingleFile;
fcFileCoverter.YesAll := True;
// write the unit text to a file
lsBaseFileName := PathGetTempPath + 'JcfTempUnit.';
fsFileName := lsBaseFileName + 'pas';
fsBackFileName := lsBaseFileName + 'bak';
fsOutFileName := lsBaseFileName + 'out';
if FileExists(fsFileName) then
SysUtils.DeleteFile(fsFileName);
if FileExists(fsBackFileName) then
SysUtils.DeleteFile(fsBackFileName);
if FileExists(fsOutFileName) then
SysUtils.DeleteFile(fsOutFileName);
StringToFile(fsFileName, UNIT_TEXT);
fcFileCoverter.Input := fsFileName;
end;
procedure TTestFileConverter.TearDown;
begin
inherited;
FreeAndNil(fcFileCoverter);
if FileExists(fsFileName) then
SysUtils.DeleteFile(fsFileName);
if FileExists(fsBackFileName) then
SysUtils.DeleteFile(fsBackFileName);
if FileExists(fsOutFileName) then
SysUtils.DeleteFile(fsOutFileName);
end;
procedure TTestFileConverter.TestInPlace;
var
lrFileTime1, lrFileTime2: TFileTime;
begin
fcFileCoverter.BackupMode := cmInPlace;
fcFileCoverter.Convert;
Check(FileExists(fsFileName));
{ file is now formatted, so formatting it again should have no effect
File time should not be updated }
lrFileTime1 := GetFileLastWrite(fsFileName);
fcFileCoverter.Convert;
Check(FileExists(fsFileName));
Check(not FileExists(fsBackFileName));
Check(not FileExists(fsOutFileName));
lrFileTime2 := GetFileLastWrite(fsFileName);
Check(TimesEqual(lrFileTime1, lrFileTime2));
end;
procedure TTestFileConverter.TestInPlaceWithBackup;
var
lrFileTime1, lrFileTime2: TFileTime;
begin
fcFileCoverter.BackupMode := cmInPlaceWithBackup;
fcFileCoverter.Convert;
Check(FileExists(fsFileName));
Check(FileExists(fsBackFileName));
Check(not FileExists(fsOutFileName));
// try again on the formatted file
lrFileTime1 := GetFileLastWrite(fsFileName);
fcFileCoverter.Convert;
Check(FileExists(fsFileName));
Check(FileExists(fsBackFileName));
Check(not FileExists(fsOutFileName));
lrFileTime2 := GetFileLastWrite(fsFileName);
Check(TimesEqual(lrFileTime1, lrFileTime2));
end;
procedure TTestFileConverter.TestSeparateOutput;
begin
fcFileCoverter.BackupMode := cmSeparateOutput;
fcFileCoverter.Convert;
Check(FileExists(fsFileName));
Check(FileExists(fsOutFileName));
Check(not FileExists(fsBackFileName));
// move out to original and try again on the formatted file
SysUtils.DeleteFile(fsFileName);
RenameFile(fsOutFileName, fsFileName);
fcFileCoverter.Convert;
Check(FileExists(fsFileName));
Check(FileExists(fsOutFileName));
Check(not FileExists(fsBackFileName));
end;
initialization
TestFramework.RegisterTest('Processes', TTestFileConverter.Suite);
end.
|
{ @exclude }
unit rtcEditors;
{$INCLUDE rtcDefs.inc}
interface
uses
{$IFDEF IDE_6up}
DesignIntf, DesignEditors, TypInfo,
{$ELSE}
DsgnIntf, TypInfo,
{$ENDIF}
Consts,
Classes;
type
TRtcSimpleAddStringList = class(TStringList)
public
procedure SimpleAdd(const s: string);
end;
TRtcInterfacedComponentProperty = class(TComponentProperty)
public
function GetIID: TGUID; virtual; abstract;
procedure GetValues(Proc: TGetStrProc); override;
procedure SetValue(const Value: string); override;
end;
implementation
procedure TRtcSimpleAddStringList.SimpleAdd(const s: string);
begin
Add(s);
end;
procedure TRtcInterfacedComponentProperty.GetValues(Proc: TGetStrProc);
var
sl : TRtcSimpleAddStringList;
i : Integer;
Component : TComponent;
Unknown : IUnknown;
begin
sl := TRtcSimpleAddStringList.Create;
try
inherited GetValues(sl.SimpleAdd);
for i := 0 to Pred(sl.Count) do
begin
Component := Designer.GetComponent(sl[i]);
if Assigned(Component) and Component.GetInterface(GetIID, Unknown) then
Proc(sl[i]);
Unknown := nil;
end;
finally
sl.Free;
end;
end;
procedure TRtcInterfacedComponentProperty.SetValue(const Value: string);
var
Component : TComponent;
Unknown : IUnknown;
begin
inherited SetValue(Value);
{$IFDEF DCC6OrLater}
Component := GetComponentReference;
{$ELSE}
Component := TComponent(GetOrdValue);
{$ENDIF}
if Assigned(Component) then
begin
if Component.GetInterface(GetIID, Unknown) then
begin
Unknown := nil;
Exit;
end;
inherited SetValue('');
raise EPropertyError.Create('Invalid property value');
end;
end;
end. |
unit xElecPoint;
interface
uses SysUtils, Classes;
const
/// <summary>
/// 无效权值
/// </summary>
C_WEIGHT_VALUE_INVALID = 9999;
type
/// <summary>
/// 权值类
/// </summary>
TWeightValue = class
private
FWID: Integer;
FWValue: Integer;
public
constructor Create;
/// <summary>
/// 权值大小(相同ID,权值大的往权值小的地方流)
/// </summary>
property WValue : Integer read FWValue write FWValue;
/// <summary>
/// 权值ID (只有相同权值才有比较权值大小的意义)
/// </summary>
property WID : Integer read FWID write FWID;
/// <summary>
/// 清除权值
/// </summary>
procedure ClearWValue;
end;
type
/// <summary>
/// 电的点对象
/// </summary>
TElecPoint = class
private
FOwner: TObject;
FAngle: Double;
FValue: Double;
FPointName: string;
FPointSN: string;
FOnChange: TNotifyEvent;
FIsLowPoint: Boolean;
FIsVolRoot: Boolean;
FIsHighPoint: Boolean;
FWValueList: TStringList;
procedure SetValue(const Value: Double);
procedure SetAngle(const Value: Double);
procedure Changed;
function GetTWeightValue(nWID : Integer): TWeightValue;
public
constructor Create;
destructor Destroy; override;
/// <summary>
/// 所有者
/// </summary>
property Owner : TObject read FOwner write FOwner;
/// <summary>
/// 点编号
/// </summary>
property PointSN : string read FPointSN write FPointSN;
/// <summary>
/// 向量点名称
/// </summary>
property PointName : string read FPointName write FPointName;
/// <summary>
/// 角度 水平向右为0度 竖直向上为90度
/// </summary>
property Angle : Double read FAngle write SetAngle;
/// <summary>
/// 向量值
/// </summary>
property Value : Double read FValue write SetValue;
/// <summary>
/// 清空值
/// </summary>
procedure ClearValue;
/// <summary>
/// 清除权值
/// </summary>
procedure ClearWValue;
/// <summary>
/// 权值列表
/// </summary>
property WValueList : TStringList read FWValueList write FWValueList;
/// <summary>
/// 根据权值ID获取权值对象(没有回自动创建)
/// </summary>
property WeightValue[nWID:Integer] : TWeightValue read GetTWeightValue;
/// <summary>
/// 是否是电流的低端或者是地线
/// </summary>
property IsLowPoint : Boolean read FIsLowPoint write FIsLowPoint;
/// <summary>
/// 是否是电流高端(在权值大于零的情况可以传递电流值)
/// </summary>
property IsHighPoint : Boolean read FIsHighPoint write FIsHighPoint;
/// <summary>
/// 是否是电压源
/// </summary>
property IsVolRoot : Boolean read FIsVolRoot write FIsVolRoot;
/// <summary>
/// 改变事件
/// </summary>
property OnChange : TNotifyEvent read FOnChange write FOnChange;
/// <summary>
/// 值赋值
/// </summary>
procedure AssignValue(APoint : TElecPoint);
end;
implementation
{ TElecPoint }
procedure TElecPoint.AssignValue(APoint: TElecPoint);
begin
if Assigned(APoint) then
begin
Angle := APoint.Angle;
Value := APoint.Value;
end;
end;
procedure TElecPoint.Changed;
begin
if Assigned(FOnChange) then
FOnChange(Self);
end;
procedure TElecPoint.ClearValue;
begin
FAngle := 0;
FValue := 0;
end;
procedure TElecPoint.ClearWValue;
var
i : Integer;
begin
for i := 0 to FWValueList.Count - 1 do
begin
FWValueList.Objects[i].Free;
end;
FWValueList.Clear;
end;
constructor TElecPoint.Create;
begin
FWValueList := TStringList.Create;
FAngle := 0;
FValue := 0;
FPointName:= '';
FPointSN:= '';
FIsLowPoint:= False;
FIsVolRoot := False;
FIsHighPoint := False;
end;
destructor TElecPoint.Destroy;
begin
ClearWValue;
FWValueList.Free;
inherited;
end;
function TElecPoint.GetTWeightValue(nWID: Integer): TWeightValue;
var
nIndex : Integer;
begin
nIndex := FWValueList.IndexOf(IntToStr(nWID));
if nIndex = -1 then
begin
Result := TWeightValue.Create;
Result.WID := nWID;
FWValueList.AddObject(IntToStr(nWID), Result);
end
else
begin
Result := TWeightValue(FWValueList.Objects[nIndex]);
end;
end;
procedure TElecPoint.SetAngle(const Value: Double);
begin
if Abs(FAngle - Value) > 0.001 then
begin
FAngle := Value;
Changed;
end;
end;
procedure TElecPoint.SetValue(const Value: Double);
begin
if Abs(FValue - Value) > 0.001 then
begin
FValue := Value;
Changed;
end;
end;
{ TWeightValue }
procedure TWeightValue.ClearWValue;
begin
FWID := C_WEIGHT_VALUE_INVALID;
FWValue := C_WEIGHT_VALUE_INVALID;
end;
constructor TWeightValue.Create;
begin
ClearWValue;
end;
end.
|
unit fOrdersVerify;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
fAutoSz, StdCtrls, ORFn, ORCtrls, ExtCtrls, VA508AccessibilityManager;
type
TfrmVerifyOrders = class(TfrmAutoSz)
Panel1: TPanel;
lblVerify: TLabel;
lstOrders: TCaptionListBox;
Panel2: TPanel;
lblESCode: TLabel;
txtESCode: TCaptionEdit;
cmdOK: TButton;
cmdCancel: TButton;
procedure FormCreate(Sender: TObject);
procedure cmdOKClick(Sender: TObject);
procedure cmdCancelClick(Sender: TObject);
procedure lstOrdersMeasureItem(Control: TWinControl; Index: Integer;
var AHeight: Integer);
procedure lstOrdersDrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
procedure Panel1Resize(Sender: TObject);
private
OKPressed: Boolean;
ESCode: string;
end;
function ExecuteVerifyOrders(SelectedList: TList; ChartReview: Boolean): Boolean;
implementation
{$R *.DFM}
uses XWBHash, rCore, rOrders, System.UITypes, VAUtils;
const
TX_CHART_REVIEW = 'The following orders will be marked as reviewed -';
function ExecuteVerifyOrders(SelectedList: TList; ChartReview: Boolean): Boolean;
var
frmVerifyOrders: TfrmVerifyOrders;
i: Integer;
begin
Result := False;
if SelectedList.Count = 0 then Exit;
frmVerifyOrders := TfrmVerifyOrders.Create(Application);
try
ResizeFormToFont(TForm(frmVerifyOrders));
if ChartReview then
begin
frmVerifyOrders.lblVerify.Caption := TX_CHART_REVIEW;
frmVerifyOrders.Caption := 'Chart Review';
end;
with SelectedList do for i := 0 to Count - 1 do
frmVerifyOrders.lstOrders.Items.Add(TOrder(Items[i]).Text);
frmVerifyOrders.ShowModal;
if frmVerifyOrders.OKPressed then
begin
with SelectedList do for i := 0 to Count - 1 do
begin
if ChartReview
then VerifyOrderChartReview(TOrder(Items[i]), frmVerifyOrders.ESCode)
else VerifyOrder(TOrder(Items[i]), frmVerifyOrders.ESCode);
end;
Result := True;
end;
finally
frmVerifyOrders.Release;
with SelectedList do for i := 0 to Count - 1 do UnlockOrder(TOrder(Items[i]).ID);
end;
end;
procedure TfrmVerifyOrders.FormCreate(Sender: TObject);
begin
inherited;
OKPressed := False;
end;
procedure TfrmVerifyOrders.cmdOKClick(Sender: TObject);
const
TX_NO_CODE = 'An electronic signature code must be entered to verify orders.';
TC_NO_CODE = 'Electronic Signature Code Required';
TX_BAD_CODE = 'The electronic signature code entered is not valid.';
TC_BAD_CODE = 'Invalid Electronic Signature Code';
begin
inherited;
if Length(txtESCode.Text) = 0 then
begin
InfoBox(TX_NO_CODE, TC_NO_CODE, MB_OK);
Exit;
end;
if not ValidESCode(txtESCode.Text) then
begin
InfoBox(TX_BAD_CODE, TC_BAD_CODE, MB_OK);
txtESCode.SetFocus;
txtESCode.SelectAll;
Exit;
end;
ESCode := Encrypt(txtESCode.Text);
OKPressed := True;
Close;
end;
procedure TfrmVerifyOrders.cmdCancelClick(Sender: TObject);
begin
inherited;
Close;
end;
procedure TfrmVerifyOrders.lstOrdersMeasureItem(Control: TWinControl;
Index: Integer; var AHeight: Integer);
var
x: string;
ARect: TRect;
begin
inherited;
with lstOrders do if Index < Items.Count then
begin
ARect := ItemRect(Index);
Canvas.FillRect(ARect);
x := FilteredString(Items[Index]);
AHeight := WrappedTextHeightByFont(Canvas, Font, x, ARect);
if AHeight < 13 then AHeight := 15;
end;
end;
procedure TfrmVerifyOrders.lstOrdersDrawItem(Control: TWinControl;
Index: Integer; Rect: TRect; State: TOwnerDrawState);
var
x: string;
ARect: TRect;
SaveColor: TColor;
begin
inherited;
with lstOrders do
begin
ARect := Rect;
ARect.Left := ARect.Left + 2;
Canvas.FillRect(ARect);
Canvas.Pen.Color := Get508CompliantColor(clSilver);
SaveColor := Canvas.Brush.Color;
Canvas.MoveTo(ARect.Left, ARect.Bottom - 1);
Canvas.LineTo(ARect.Right, ARect.Bottom - 1);
if Index < Items.Count then
begin
x := FilteredString(Items[Index]);
DrawText(Canvas.Handle, PChar(x), Length(x), ARect, DT_LEFT or DT_NOPREFIX or DT_WORDBREAK);
Canvas.Brush.Color := SaveColor;
ARect.Right := ARect.Right + 4;
end;
end;
end;
procedure TfrmVerifyOrders.Panel1Resize(Sender: TObject);
begin
inherited;
lstOrders.Invalidate;
end;
end.
|
unit gui_benri;
// 説 明:面倒な手続きをユニットにまとめたもの
// 作 者:クジラ飛行机(web@kujirahand.com)
// 公開日:2001/10/21
interface
uses
SysUtils, Classes, Forms, Windows, ShellApi, ComObj, ActiveX, ShlObj, Registry;
function AppPath: string;
function MsgYesNo(msg: string): Boolean; overload;
function MsgYesNo(msg,cap: string): Boolean; overload;
function MsgYesNoCancel(msg: string): Integer; overload;
function MsgYesNoCancel(msg,cap: string): Integer; overload;
procedure ShowWarn(msg,cap: string);//警告ダイアログを表示
procedure ShowInfo(msg,cap: string);//情報ダイアログを表示
{Windowsフォルダを得る}
function WinDir:string;
{Systemフォルダを得る}
function SysDir:string;
{Tempフォルダを得る}
function TempDir:string;
{デスクトップフォルダを得る}
function DesktopDir:string;
{特殊フォルダを得る}
function GetSpecialFolder(const loc:Word): string;
function SendToDir:string;
function StartUpDir:string;
function StartMenuDir:string;
function MyDocumentDir:string;
function GomibakoDir:string;
function FavoritesDir:string;
function ProgramsDir:string;
{オリジナル一時ファイル名の取得(dirnameを省略で、TempDirを参照)}
function getOriginalFileName(dirname, header: string): string;
{ショートカットを作成する}
function CreateShortCut(Name, Target, Arg, WorkDir: string; State: TWindowState): Boolean;
function StrToDateDef(const StrDate, DefDate: string): TDateTime;
{chkDayが、baseDay以降なら、True を返す}
function DateAfter(const baseDay, chkDay: TDateTime): Boolean;
function makeShortcut(FilePath, Description, WorkDir: string): Boolean;
function makeShortcutDesktop(FilePath, Description, WorkDir: string): Boolean;
{サブフォルダまで一気にコピーする}
function SHFileCopy(const Sorce, Dest: string): Boolean;
function SHFileDelete(const Sorce: string): Boolean;
function SHFileMove(const Sorce, Dest: string): Boolean;
function SHFileRename(const Sorce, Dest: string): Boolean;
{Windows の XCopy.exe を使って、一気にコピー}
procedure XCopy(const Sorce, Dest: string);
{ファイルに任意の文字列を書きこむ}
function WriteTextFile(const fname, str:string):Boolean;
function ReadTextFile(const fname:string; var str:string):Boolean;
{ソフトを起動する}
function RunApp(const fname: String): Boolean;
function OpenApp(const fname: string): Integer;
function RunAppAndWait(const fname: string): Boolean;
{ディレクトリの選択:右下に表示されないバージョン:OwnerHandleを、フォームのものにする}
function SelectDirectoryEx(const Caption: string; const Root: WideString;
out Directory: string; OwnerHandle: THandle): Boolean;
{長いファイル名を得る}
function ShortToLongFileName(ShortName: String):String;
{Windowsのバージョンを文字列で列挙}
function getWinVersion: string;
implementation
function OpenApp(const fname: string): Integer;
begin
Result := ShellExecute(0, 'open', PChar(fname),'','',SW_SHOW);
end;
function RunAppAndWait(const fname: string): Boolean;
var
SI :TStartupInfo;
PI :TProcessInformation;
begin
GetStartupInfo(SI);
try
if not CreateProcess(nil, PChar(fname), nil,nil,False, 0, nil, nil,
SI, PI) then raise Exception.Create('Error!');
while WaitForSingleObject(PI.hProcess, 0) = WAIT_TIMEOUT do
Application.ProcessMessages; // プロセス終了まで待機する
Result := True;
except
Result := False;
end;
end;
function getWinVersion: string;
var
//s: string;
major,minor: LongInt;
Info: TOSVersionInfo;
begin
Info.dwOSVersionInfoSize := SizeOf(Info);
GetVersionEx(Info);
Major := Info.dwMajorVersion ;
Minor := Info.dwMinorVersion ;
case major of
4://95/98/ME/NT
begin
if Info.dwPlatformId = VER_PLATFORM_WIN32_WINDOWS then
begin
case Minor of
0 :Result := 'Windows 95';
10:Result := 'Windows 98';
90:Result := 'Windows Me';
end;
end else
if Info.dwPlatformId = VER_PLATFORM_WIN32_NT then
begin
Result := 'Windows NT 4.0';
end;
end;
3://NT 3.51
begin
Result := 'Windows NT 3.51';
end;
5://2000/XP/.NET Server
begin
case Minor of
0: Result := 'Windows 2000';
1: Result := 'Windows XP';
end;
end;
else begin
Result := '不明 Version = '+ IntToStr(GetVersion);
end;
end;
{上手く動かない
s := string(PChar(@Info.szCSDVersion[1]));
if s<>'' then
begin
Result := Result + s;
end;}
end;
function ShortToLongFileName(ShortName: String):String;
var
SearchRec: TSearchRec;
begin
result:= '';
// フルパス化
ShortName:= ExpandFileName(ShortName);
// 長い名前に変換(ディレクトリも)
while LastDelimiter('\', ShortName) >= 3 do begin
if FindFirst(ShortName, faAnyFile, SearchRec) = 0 then
try
result := '\' + SearchRec.Name + result;
finally
// 見つかったときだけ Close -> [Delphi-ML:17508] を参照
Sysutils.FindClose(SearchRec);
end
else
// ファイルが見つからなければそのまま
result := '\' + ExtractFileName(ShortName) + result;
ShortName := ExtractFilePath(ShortName);
SetLength(ShortName, Length(ShortName)-1); // 最後の '\' を削除
end;
result := ShortName + result;
end;
{オリジナル一時ファイル名の取得}
function getOriginalFileName(dirname, header: string): string;
var
i: Integer;
fname,s,ext: string;
begin
if dirname='' then dirname := TempDir;
i := 1;
s := header;
ext := ExtractFileExt(header);
s := Copy(s,1, Length(s)-Length(ext));
if Copy(dirname,Length(dirname),1)<>'\' then dirname := dirname + '\';
while True do
begin
fname := dirname + s + IntToStr(i) + ext;
if FileExists(fname) = False then
begin
Result := fname; Break;
end;
Inc(i);
end;
end;
function SelectDirectoryEx(const Caption: string; const Root: WideString;
out Directory: string; OwnerHandle: THandle): Boolean;
var
WindowList: Pointer;
BrowseInfo: TBrowseInfo;
Buffer: PChar;
RootItemIDList, ItemIDList: PItemIDList;
ShellMalloc: IMalloc;
IDesktopFolder: IShellFolder;
Eaten, Flags: LongWord;
s: string;
begin
Result := False;
Directory := '';
FillChar(BrowseInfo, SizeOf(BrowseInfo), 0);
if (ShGetMalloc(ShellMalloc) = S_OK) and (ShellMalloc <> nil) then
begin
Buffer := ShellMalloc.Alloc(MAX_PATH);
s := GetCurrentDir ;
StrCopy(Buffer, PChar(s));
try
RootItemIDList := nil;
if Root <> '' then
begin
SHGetDesktopFolder(IDesktopFolder);
IDesktopFolder.ParseDisplayName(Application.Handle, nil,
POleStr(Root), Eaten, RootItemIDList, Flags);
end;
with BrowseInfo do
begin
hwndOwner := OwnerHandle;
pidlRoot := RootItemIDList;
pszDisplayName := Buffer;
lpszTitle := PChar(Caption);
ulFlags := BIF_RETURNONLYFSDIRS;
end;
WindowList := DisableTaskWindows(0);
try
ItemIDList := ShBrowseForFolder(BrowseInfo);
finally
EnableTaskWindows(WindowList);
end;
Result := ItemIDList <> nil;
if Result then
begin
ShGetPathFromIDList(ItemIDList, Buffer);
ShellMalloc.Free(ItemIDList);
Directory := Buffer;
end;
finally
ShellMalloc.Free(Buffer);
end;
end;
end;
{ソフトを起動する}
function RunApp(const fname: String): Boolean;
var
retCode: Integer;
begin
retCode := WinExec(PChar(fname), SW_SHOW);
if retCode > 31 then
begin
Result:= True;
end else
begin
Result :=False;
end;
end;
{chkDayが、baseDay以降(その日を含む)なら、True を返す}
function DateAfter(const baseDay, chkDay: TDateTime): Boolean;
var
y1,m1,d1, y2,m2,d2: Word;
v1, v2: DWORD;
begin
Result := False;
DecodeDate(baseDay, y1, m1, d1);
DecodeDate(chkDay, y2, m2, d2);
v1 := y1*365 + m1*12 + d1;
v2 := y2*365 + m2*12 + d2;
if v1 <= v2 then Result := True;
end;
{Windowsフォルダを得る}
function WinDir:string;
var
TempWin:array[0..MAX_PATH] of Char;
begin
GetWindowsDirectory(TempWin,MAX_PATH);
Result:=StrPas(TempWin);
if Copy(Result,Length(Result),1)<>'\' then Result := Result + '\';
end;
{Systemフォルダを得る}
function SysDir:string;
var
TempSys:array[0..MAX_PATH] of Char;
begin
GetSystemDirectory(TempSys,MAX_PATH);
Result:=StrPas(TempSys);
if Copy(Result,Length(Result),1)<>'\' then Result := Result + '\';
end;
{Tempフォルダを得る}
function TempDir:string;
var
TempTmp:array[0..MAX_PATH] of Char;
begin
GetTemppath(MAX_PATH,TempTmp);
Result:=StrPas(TempTmp);
if Copy(Result,Length(Result),1)<>'\' then Result := Result + '\';
end;
function GetSpecialFolder(const loc:Word): string;
var
PathID: PItemIDList;
Path : array[0..MAX_PATH] of char;
begin
SHGetSpecialFolderLocation(Application.Handle, loc, PathID);
SHGetPathFromIDList(PathID, Path);
Result := string(Path);
if Copy(Result, Length(Result),1)<>'\' then
Result := Result + '\';
end;
function DesktopDir:string;
begin
Result := GetSpecialFolder(CSIDL_DESKTOPDIRECTORY);
end;
function SendToDir:string;
begin
Result := GetSpecialFolder(CSIDL_SENDTO);
end;
function StartUpDir:string;
begin
Result := GetSpecialFolder(CSIDL_STARTUP);
end;
function ProgramsDir:string;
begin
Result := GetSpecialFolder(CSIDL_PROGRAMS);
end;
function StartMenuDir:string;
begin
Result := GetSpecialFolder(CSIDL_STARTMENU);
end;
function MyDocumentDir:string;
begin
Result := GetSpecialFolder(CSIDL_PERSONAL);
end;
function GomibakoDir:string;
begin
Result := GetSpecialFolder(CSIDL_BITBUCKET);
end;
function FavoritesDir: string;
begin
Result := GetSpecialFolder(CSIDL_FAVORITES);
end;
function CreateShortCut(Name, Target, Arg, WorkDir: string; State: TWindowState): Boolean;
var
IU: IUnknown;
W: PWideChar;
const
ShowCmd: array[TWindowState] of Integer =
(SW_SHOWNORMAL, SW_MINIMIZE, SW_MAXIMIZE);
begin
Result := False;
try
IU := CreateComObject(CLSID_ShellLink);
with IU as IShellLink do begin
if SetPath(PChar(Target)) <> NOERROR then Abort;
if SetArguments(PChar(Arg)) <> NOERROR then Abort;
if SetWorkingDirectory(PChar(WorkDir)) <> NOERROR then Abort;
if SetShowCmd(ShowCmd[State]) <> NOERROR then Abort
end;
W := PWChar(WideString(Name));
if (IU as IPersistFile).Save(W, False) <> S_OK then Abort;
Result := True
except
end
end;
function AppPath: string;
begin
result := ExtractFilePath( ParamStr(0) );
end;
function MsgYesNo(msg: string): Boolean;
var
i: Integer;
begin
i := MessageBox(Application.Handle,PChar(msg), PChar(Application.Title), MB_YESNO + MB_ICONQUESTION);
if i=IDYES then
Result := True
else
Result := False;
end;
function MsgYesNo(msg,cap: string): Boolean; overload;
var
i: Integer;
begin
i := MessageBox(Application.Handle,PChar(msg),
PChar(cap), MB_YESNO + MB_ICONQUESTION);
if i=IDYES then
Result := True
else
Result := False;
end;
function MsgYesNoCancel(msg: string): Integer;
begin
Result := MessageBox(Application.Handle,PChar(msg), PChar(Application.Title), MB_YESNOCANCEL + MB_ICONQUESTION);
end;
function MsgYesNoCancel(msg,cap: string): Integer; overload;
begin
Result := MessageBox(Application.Handle,PChar(msg), PChar(cap), MB_YESNOCANCEL + MB_ICONQUESTION);
end;
procedure ShowWarn(msg,cap: string);//警告ダイアログを表示
begin
if cap='' then cap := Application.Title ;
MessageBox(
Application.Handle,
PChar(msg),
PChar(cap),
MB_ICONWARNING or MB_OK);
end;
procedure ShowInfo(msg,cap: string);//情報ダイアログを表示
begin
if cap='' then cap := Application.Title ;
MessageBox(
Application.Handle,
PChar(msg),
PChar(cap),
MB_ICONINFORMATION or MB_OK);
end;
function StrToDateDef(const StrDate, DefDate: string): TDateTime;
begin
if StrDate='' then
begin
Result := StrToDate(DefDate);
Exit;
end;
try
Result := StrToDate(StrDate);
except
try
Result := StrToDate(DefDate);
except
Result := Date;
end;
end;
end;
function makeShortcut(FilePath, Description, WorkDir: string): Boolean;
var
AnObj: IUnknown;
ShLink: IShellLink;
PFile: IPersistFile;
Reg: TRegIniFile;
WFilename: WideString ;
begin
try
AnObj := CreateComObject(CLSID_ShellLink) as IShellLink;
ShLink := AnObj as IShellLink;
PFile := ShLink as IPersistFile;
ShLink.SetPath (PChar(FilePath));
ShLink.SetDescription(PChar(Description));
ShLink.SetWorkingDirectory(PChar(WorkDir));
//save Desktop
Reg := TRegIniFile.Create(
'Software\MicroSoft\Windows\CurrentVersion\Explorer');
WFilename := Reg.ReadString('Shell Folders','Desktop','')+
'\' + Description + '.lnk';
Reg.Free ;
PFile.Save(PWChar(WFilename), False);
//save StartMenu
Reg := TRegIniFile.Create(
'Software\MicroSoft\Windows\CurrentVersion\Explorer');
WFilename := Reg.ReadString('Shell Folders','Start Menu','')+
'\' + Description + '.lnk';
Reg.Free ;
PFile.Save(PWChar(WFilename), False);
except
Result := False; Exit;
end;
Result := True;
end;
function makeShortcutDesktop(FilePath, Description, WorkDir: string): Boolean;
var
AnObj: IUnknown;
ShLink: IShellLink;
PFile: IPersistFile;
Reg: TRegIniFile;
WFilename: WideString ;
begin
try
AnObj := CreateComObject(CLSID_ShellLink) as IShellLink;
ShLink := AnObj as IShellLink;
PFile := ShLink as IPersistFile;
ShLink.SetPath (PChar(FilePath));
ShLink.SetDescription(PChar(Description));
ShLink.SetWorkingDirectory(PChar(WorkDir));
//save Desktop
Reg := TRegIniFile.Create(
'Software\MicroSoft\Windows\CurrentVersion\Explorer');
WFilename := Reg.ReadString('Shell Folders','Desktop','')+
'\' + Description + '.lnk';
Reg.Free ;
PFile.Save(PWChar(WFilename), False);
except
Result := False; Exit;
end;
Result := True;
end;
function SHFileCopy(const Sorce, Dest: string): Boolean;
var
foStruct: TSHFileOpStruct;
begin
Result := False;
if (Sorce='')or(Dest='') then Exit;
with foStruct do
begin
wnd:=Application.Handle;
wFunc:=FO_COPY; //フラグ(コピーの場合はFO_COPY)
pFrom:=PChar(Sorce+#0#0); //するフォルダ
pTo:=PChar(Dest+#0#0);
fFlags:=FOF_SILENT or FOF_NOCONFIRMATION or FOF_MULTIDESTFILES ; //ダイアログ非表示
fAnyOperationsAborted:=False;
hNameMappings:=nil;
lpszProgressTitle:=nil;
end;
Result := (SHFileOperation(foStruct)=0);
end;
function SHFileDelete(const Sorce: string): Boolean;
var
foStruct: TSHFileOpStruct;
begin
with foStruct do
begin
wnd:=Application.Handle;
wFunc:=FO_DELETE; //フラグ(コピーの場合はFO_COPY)
pFrom:=PChar(Sorce+#0#0); //するフォルダ
pTo:=Nil;
fFlags:=FOF_SILENT or FOF_NOCONFIRMATION or FOF_ALLOWUNDO or FOF_MULTIDESTFILES; //ダイアログ非表示
{fAnyOperationsAborted:=False;
hNameMappings:=nil;
lpszProgressTitle:=nil;}
end;
Result := (SHFileOperation(foStruct)=0);
(*
//FileOpの初期化
//複数ファイルをごみ箱へ削除
with FileOp do
begin
Wnd := Handle;
wFunc := FO_DELETE;
pFrom := PChar( FNames);
pTo := Nil;
fFlags := FOF_ALLOWUNDO;
end;
SHFileOperation( FileOp);
*)
end;
function SHFileMove(const Sorce, Dest: string): Boolean;
var
foStruct: TSHFileOpStruct;
begin
with foStruct do
begin
wnd:=Application.Handle;
wFunc:=FO_MOVE; //フラグ(コピーの場合はFO_COPY)
pFrom:=PChar(Sorce+#0#0); //するフォルダ
pTo:=PChar(Dest + #0#0);
fFlags:=FOF_NOCONFIRMATION or FOF_ALLOWUNDO; //ダイアログ非表示
fAnyOperationsAborted:=False;
hNameMappings:=nil;
lpszProgressTitle:=nil;
end;
Result := (SHFileOperation(foStruct)=0);
end;
//なんだか、コピーされてしまうようですよ・・・要調査
function SHFileRename(const Sorce, Dest: string): Boolean;
var
foStruct: TSHFileOpStruct;
begin
with foStruct do
begin
wnd:=Application.Handle;
wFunc:=FO_RENAME; //フラグ(コピーの場合はFO_COPY)
pFrom:=PChar(Sorce+#0#0); //するフォルダ
pTo:=PChar(Dest + #0#0);
fFlags:=FOF_SILENT or FOF_NOCONFIRMATION or FOF_MULTIDESTFILES or FOF_ALLOWUNDO; //ダイアログ非表示
fAnyOperationsAborted:=False;
hNameMappings:=nil;
lpszProgressTitle:=nil;
end;
Result := (SHFileOperation(foStruct)=0);
end;
{Windows の XCopy.exe を使って、一気にコピー}
procedure XCopy(const Sorce, Dest: string);
var s:string;
begin
s := 'XCOPY.EXE "'+Sorce+'" "'+dest+'" /E';
WinExec(PChar(s),SW_NORMAL);
end;
{ファイルに任意の文字列を書きこむ}
function WriteTextFile(const fname, str:string):Boolean;
var
s: TStringList;
begin
Result := True;
s := TStringList.Create;
try
try
s.Text := str;
s.SaveToFile(fname);
except
Result := False;
end;
finally
s.Free;
end;
end;
function ReadTextFile(const fname:string; var str:string):Boolean;
var
s: TMemoryStream;
begin
Result := True;
s := TMemoryStream.Create;
try
try
s.LoadFromFile(fname);
if s.Size=0 then Exit;
SetLength(str, s.Size);
s.Position := 0;
s.Read(str[1], s.Size);
except
Result := False;
end;
finally
s.Free;
end;
end;
end.
|
unit TestCondReturns;
interface
uses
Dialogs;
implementation
function DoTestCondReturns: Boolean;
var
foo, bar: boolean;
begin
if foo then
begin
{$IFDEF DEBUG}
MessageDlg('Foo!',
mtInformation, [mbOK], 0);
{$ENDIF}
Result := True;
bar := False;
end;
end;
end. |
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC Informix driver }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
{$HPPEMIT LINKUNIT}
unit FireDAC.Phys.Infx;
interface
uses
System.Classes,
FireDAC.Stan.Intf, FireDAC.Stan.Error, FireDAC.Stan.Option,
FireDAC.Phys, FireDAC.Phys.ODBCCli, FireDAC.Phys.ODBCWrapper, FireDAC.Phys.ODBCBase;
type
TFDInfxError = class;
EInfxNativeException = class;
TFDPhysInfxDriverLink = class;
/// <summary> The TFDInfxError object is a container for the information
/// pertaining to one Informix database error, warning, or message. One
/// or more TFDInfxError objects are included in the Errors property of
/// the EInfxNativeException object. Compared to TFDODBCNativeError, the
/// TFDInfxError class also comprises error attributes specific to the Informix. </summary>
TFDInfxError = class(TFDODBCNativeError)
private
FISAMError: Integer;
protected
procedure Assign(ASrc: TFDDBError); override;
procedure LoadFromStorage(const AStorage: IFDStanStorage); override;
procedure SaveToStorage(const AStorage: IFDStanStorage); override;
public
/// <summary> Returns a secondary error number called the ISAM error, which
/// may be generated in addition to the normal SQL error number. The ISAM
/// error gives additional information about why the SQL error occurred. </summary>
property ISAMError: Integer read FISAMError;
end;
/// <summary> EInfxNativeException class representing a Informix driver exception.
/// Use this class to handle Informix driver specific exception. </summary>
EInfxNativeException = class(EODBCNativeException)
private
function GetErrors(AIndex: Integer): TFDInfxError;
protected
function GetErrorClass: TFDDBErrorClass; override;
public
constructor Create(AStatus: SQLReturn; AOwner: TODBCHandle); override;
function AppendError(AHandle: TODBCHandle; ARecNum: SQLSmallint;
const ASQLState: String; ANativeError: SQLInteger; const ADiagMessage,
AResultMessage, ACommandText, AObject: String;
AKind: TFDCommandExceptionKind; ACmdOffset, ARowIndex: Integer): TFDDBError; override;
/// <summary> Use the Errors property to get access to an error item from
/// the collection of errors, associated with this exception object. </summary>
property Errors[Index: Integer]: TFDInfxError read GetErrors; default;
end;
[ComponentPlatformsAttribute(pfidWindows)]
TFDPhysInfxDriverLink = class(TFDPhysODBCBaseDriverLink)
protected
function GetBaseDriverID: String; override;
public
procedure GetServers(AList: TStrings);
end;
{-------------------------------------------------------------------------------}
implementation
uses
System.SysUtils, System.Variants, Data.DB,
{$IFDEF MSWINDOWS}
Winapi.Windows, System.Win.Registry,
{$ENDIF}
{$IFDEF POSIX}
System.IniFiles,
{$ENDIF}
FireDAC.Stan.Consts, FireDAC.Stan.Util, FireDAC.Stan.Param,
FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.Phys.SQLGenerator, FireDAC.Phys.InfxMeta,
FireDAC.Phys.InfxDef;
type
TFDPhysInfxDriver = class;
TFDPhysInfxConnection = class;
TFDPhysInfxCommand = class;
TFDPhysInfxEventAlerter_DBMS_ALERT = class;
IFDPhysInfxDriver = interface
['{A52C2247-E07C-4BEB-821B-6DF097828ED2}']
// public
procedure GetServers(AList: TStrings);
end;
TFDPhysInfxDriver = class(TFDPhysODBCDriverBase, IFDPhysInfxDriver)
protected
class function GetBaseDriverID: String; override;
class function GetBaseDriverDesc: String; override;
class function GetRDBMSKind: TFDRDBMSKind; override;
class function GetConnectionDefParamsClass: TFDConnectionDefParamsClass; override;
procedure InternalLoad; override;
function InternalCreateConnection(AConnHost: TFDPhysConnectionHost): TFDPhysConnection; override;
procedure GetODBCConnectStringKeywords(AKeywords: TStrings); override;
function GetConnParams(AKeys: TStrings; AParams: TFDDatSTable): TFDDatSTable; override;
// IFDPhysInfxDriver
procedure GetServers(AList: TStrings);
public
function BuildODBCConnectString(const AConnectionDef: IFDStanConnectionDef): String; override;
end;
TFDPhysInfxConnection = class(TFDPhysODBCConnectionBase)
private
FServerVersion: TFDVersion;
FTxSupported: Boolean;
FWaitLock: Boolean;
protected
function InternalCreateCommand: TFDPhysCommand; override;
function InternalCreateEvent(const AEventKind: String): TFDPhysEventAlerter; override;
function InternalCreateCommandGenerator(const ACommand:
IFDPhysCommand): TFDPhysCommandGenerator; override;
function InternalCreateMetadata: TObject; override;
procedure GetStrsMaxSizes(AStrDataType: SQLSmallint; AFixedLen: Boolean;
out ACharSize, AByteSize: Integer); override;
function GetExceptionClass: EODBCNativeExceptionClass; override;
procedure InternalConnect; override;
end;
TFDPhysInfxCommand = class(TFDPhysODBCCommand)
private
procedure UpdateWaitLock;
protected
procedure InternalExecute(ATimes, AOffset: Integer; var ACount: TFDCounter); override;
function InternalOpen(var ACount: TFDCounter): Boolean; override;
end;
TFDPhysInfxEventAlerter_DBMS_ALERT = class(TFDPhysEventAlerter)
private
FWaitConnection: IFDPhysConnection;
FWaitCommand: IFDPhysCommand;
FWaitThread: TThread;
FSignalCommand: IFDPhysCommand;
protected
// TFDPhysEventAlerter
procedure DoFired;
procedure InternalAllocHandle; override;
procedure InternalReleaseHandle; override;
procedure InternalRegister; override;
procedure InternalHandle(AEventMessage: TFDPhysEventMessage); override;
procedure InternalAbortJob; override;
procedure InternalUnregister; override;
procedure InternalSignal(const AEvent: String; const AArgument: Variant); override;
end;
{-------------------------------------------------------------------------------}
{ TFDInfxError }
{-------------------------------------------------------------------------------}
procedure TFDInfxError.Assign(ASrc: TFDDBError);
begin
inherited Assign(ASrc);
if ASrc is TFDInfxError then
FISAMError := TFDInfxError(ASrc).FISAMError;
end;
{-------------------------------------------------------------------------------}
procedure TFDInfxError.LoadFromStorage(const AStorage: IFDStanStorage);
begin
inherited LoadFromStorage(AStorage);
FISAMError := AStorage.ReadInteger('ISAMError', 0);
end;
{-------------------------------------------------------------------------------}
procedure TFDInfxError.SaveToStorage(const AStorage: IFDStanStorage);
begin
inherited SaveToStorage(AStorage);
AStorage.WriteInteger('ISAMError', ISAMError, 0);
end;
{-------------------------------------------------------------------------------}
{ EInfxNativeException }
{-------------------------------------------------------------------------------}
constructor EInfxNativeException.Create(AStatus: SQLReturn;
AOwner: TODBCHandle);
begin
inherited Create(AStatus, AOwner);
if (ErrorCode = SQL_ERROR) and (Kind = ekOther) then
Errors[0].Kind := ekServerGone;
end;
{-------------------------------------------------------------------------------}
function EInfxNativeException.AppendError(AHandle: TODBCHandle;
ARecNum: SQLSmallint; const ASQLState: String; ANativeError: SQLInteger;
const ADiagMessage, AResultMessage, ACommandText, AObject: String;
AKind: TFDCommandExceptionKind; ACmdOffset, ARowIndex: Integer): TFDDBError;
var
sObj: String;
oStmt: TODBCStatementBase;
iISAMError: SQLInteger;
procedure ExtractObjName;
var
i1, i2: Integer;
begin
// first (xxxx) - object name
i1 := Pos('(', ADiagMessage);
if i1 <> 0 then begin
i2 := Pos(')', ADiagMessage, i1 + 1);
if i2 <> 0 then
sObj := Copy(ADiagMessage, i1 + 1, i2 - i1 - 1);
end;
end;
begin
// ekUserPwdExpired
// ekUserPwdWillExpire
// ekNoDataFound
// ekTooManyRows
// ekArrExecMalfunc
// ekInvalidParams
// ekServerOutput
sObj := AObject;
// many Informix errors have object names
ExtractObjName;
iISAMError := 0;
if AHandle is TODBCStatementBase then begin
oStmt := TODBCStatementBase(AHandle);
try
oStmt.IgnoreErrors := True;
iISAMError := oStmt.DIAG_INFX_ISAM_ERROR[ARecNum];
finally
oStmt.IgnoreErrors := False;
end;
end;
case ANativeError of
-951,
-952,
-11302,
-11033:
AKind := ekUserPwdInvalid;
-206,
-8300,
-674,
-9404,
-319,
-19804,
-9992,
-218,
-634,
-9628,
-329:
AKind := ekObjNotExists;
-268:
AKind := ekUKViolated;
-691,
-692:
AKind := ekFKViolated;
-233,
-244,
-245,
-246,
-263,
-378:
AKind := ekRecordLocked;
-271:
if iISAMError = -113 then
AKind := ekRecordLocked;
-908,
-11020,
-25580:
AKind := ekServerGone;
-11010:
AKind := ekCmdAborted;
end;
Result := inherited AppendError(AHandle, ARecNum, ASQLState, ANativeError,
ADiagMessage, AResultMessage, ACommandText, sObj, AKind, ACmdOffset, ARowIndex);
TFDInfxError(Result).FISAMError := iISAMError;
end;
{-------------------------------------------------------------------------------}
function EInfxNativeException.GetErrorClass: TFDDBErrorClass;
begin
Result := TFDInfxError;
end;
{-------------------------------------------------------------------------------}
function EInfxNativeException.GetErrors(AIndex: Integer): TFDInfxError;
begin
Result := inherited Errors[AIndex] as TFDInfxError;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysInfxDriverLink }
{-------------------------------------------------------------------------------}
function TFDPhysInfxDriverLink.GetBaseDriverID: String;
begin
Result := S_FD_InfxId;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysInfxDriverLink.GetServers(AList: TStrings);
var
oDrv: IFDPhysInfxDriver;
begin
if FDPhysManager.State = dmsInactive then
FDPhysManager.Open;
DriverIntf.Employ;
try
Supports(DriverIntf, IFDPhysInfxDriver, oDrv);
oDrv.GetServers(AList);
finally
oDrv := nil;
DriverIntf.Vacate;
end;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysInfxDriver }
{-------------------------------------------------------------------------------}
class function TFDPhysInfxDriver.GetBaseDriverID: String;
begin
Result := S_FD_InfxId;
end;
{-------------------------------------------------------------------------------}
class function TFDPhysInfxDriver.GetBaseDriverDesc: String;
begin
Result := 'Informix';
end;
{-------------------------------------------------------------------------------}
class function TFDPhysInfxDriver.GetRDBMSKind: TFDRDBMSKind;
begin
Result := TFDRDBMSKinds.Informix;
end;
{-------------------------------------------------------------------------------}
class function TFDPhysInfxDriver.GetConnectionDefParamsClass: TFDConnectionDefParamsClass;
begin
Result := TFDPhysInfxConnectionDefParams;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysInfxDriver.InternalLoad;
begin
ODBCAdvanced := 'CURB=1;DLMT=y';
inherited InternalLoad;
if ODBCDriver = '' then
ODBCDriver := FindBestDriver(
[{$IF DEFINED(POSIX) OR DEFINED(FireDAC_32)} 'IBM INFORMIX ODBC DRIVER' {$ENDIF}
{$IF DEFINED(MSWINDOWS) AND DEFINED(FireDAC_64)} 'IBM INFORMIX ODBC DRIVER (64-bit)' {$ENDIF}]);
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxDriver.InternalCreateConnection(
AConnHost: TFDPhysConnectionHost): TFDPhysConnection;
begin
Result := TFDPhysInfxConnection.Create(Self, AConnHost);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysInfxDriver.GetODBCConnectStringKeywords(AKeywords: TStrings);
begin
inherited GetODBCConnectStringKeywords(AKeywords);
AKeywords.Add(S_FD_ConnParam_Common_Server + '=SRVR');
AKeywords.Add(S_FD_ConnParam_Common_Database);
AKeywords.Add(S_FD_ConnParam_Common_CharacterSet + '=CLOC');
AKeywords.Add(S_FD_ConnParam_Infx_DBCharacterSet + '=DLOC');
AKeywords.Add(S_FD_ConnParam_Infx_ReadTimeout + '=RECVTIMEOUT');
AKeywords.Add(S_FD_ConnParam_Infx_WriteTimeout + '=SENDTIMEOUT');
AKeywords.Add('=CURB');
AKeywords.Add('=HOST');
AKeywords.Add('=SERV');
AKeywords.Add('=PRO');
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxDriver.BuildODBCConnectString(const AConnectionDef: IFDStanConnectionDef): String;
var
s: String;
begin
Result := inherited BuildODBCConnectString(AConnectionDef);
if AConnectionDef.HasValue(S_FD_ConnParam_Infx_StringFormat) then begin
s := AConnectionDef.AsString[S_FD_ConnParam_Infx_StringFormat];
if CompareText(s, S_FD_ANSI) = 0 then
Result := Result + ';RCWC=0'
else if CompareText(s, S_FD_Unicode) = 0 then
Result := Result + ';RCWC=1';
end;
if not AConnectionDef.HasValue(S_FD_ConnParam_Infx_DBCharacterSet) then
Result := Result + ';SDLOC=1';
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxDriver.GetConnParams(AKeys: TStrings; AParams: TFDDatSTable): TFDDatSTable;
var
oView: TFDDatSView;
oList: TFDStringList;
s: String;
begin
Result := inherited GetConnParams(AKeys, AParams);
oView := Result.Select('Name=''' + S_FD_ConnParam_Common_Database + '''');
if oView.Rows.Count = 1 then begin
oView.Rows[0].BeginEdit;
oView.Rows[0].SetValues('LoginIndex', 4);
oView.Rows[0].EndEdit;
end;
oList := TFDStringList.Create(#0, ';');
try
GetServers(oList);
s := oList.DelimitedText;
if s = '' then
s := '@S';
finally
FDFree(oList);
end;
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_Server, s, '', S_FD_ConnParam_Common_Server, 3]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_CharacterSet, '@S', '', S_FD_ConnParam_Common_CharacterSet, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Infx_DBCharacterSet, '@S', '', S_FD_ConnParam_Infx_DBCharacterSet, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Infx_StringFormat, S_FD_Unicode + ';' + S_FD_ANSI, S_FD_ANSI, S_FD_ConnParam_Infx_StringFormat, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Infx_ReadTimeout, '@I', '', S_FD_ConnParam_Infx_ReadTimeout, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Infx_WriteTimeout, '@I', '', S_FD_ConnParam_Infx_WriteTimeout, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Infx_TxSupported, S_FD_Yes + ';' + S_FD_No + ';' + S_FD_Choose, S_FD_Yes, S_FD_ConnParam_Infx_TxSupported, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Infx_TxRetainLocks, '@Y', S_FD_Yes, S_FD_ConnParam_Infx_TxRetainLocks, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Infx_TxLastCommitted, '@Y', S_FD_Yes, S_FD_ConnParam_Infx_TxLastCommitted, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_MetaDefCatalog, '@S', '', S_FD_ConnParam_Common_MetaDefCatalog, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_MetaDefSchema, '@S', '', S_FD_ConnParam_Common_MetaDefSchema, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_MetaCurCatalog, '@S', '', S_FD_ConnParam_Common_MetaCurCatalog, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_MetaCurSchema, '@S', '', S_FD_ConnParam_Common_MetaCurSchema, -1]);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysInfxDriver.GetServers(AList: TStrings);
{$IFDEF MSWINDOWS}
var
oReg: TRegistry;
{$ENDIF}
begin
{$IFDEF MSWINDOWS}
oReg := TRegistry.Create;
AList.BeginUpdate;
try
oReg.RootKey := HKEY_LOCAL_MACHINE;
if oReg.OpenKey('SOFTWARE\Informix\SqlHosts', False) then
oReg.GetKeyNames(AList)
else
AList.Clear;
finally
AList.EndUpdate;
FDFree(oReg);
end;
{$ENDIF}
{$IFDEF POSIX}
AList.Clear;
{$ENDIF}
end;
{-------------------------------------------------------------------------------}
{ TFDPhysInfxConnection }
{-------------------------------------------------------------------------------}
function TFDPhysInfxConnection.InternalCreateCommand: TFDPhysCommand;
begin
Result := TFDPhysInfxCommand.Create(Self);
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxConnection.InternalCreateEvent(const AEventKind: String): TFDPhysEventAlerter;
begin
if CompareText(AEventKind, S_FD_EventKind_Infx_DBMS_ALERT) = 0 then
Result := TFDPhysInfxEventAlerter_DBMS_ALERT.Create(Self, AEventKind)
else
Result := nil;
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxConnection.InternalCreateCommandGenerator(
const ACommand: IFDPhysCommand): TFDPhysCommandGenerator;
begin
if ACommand <> nil then
Result := TFDPhysInfxCommandGenerator.Create(ACommand)
else
Result := TFDPhysInfxCommandGenerator.Create(Self);
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxConnection.InternalCreateMetadata: TObject;
var
iSrvVer, iClntVer: TFDVersion;
oParams: TFDPhysInfxConnectionDefParams;
begin
GetVersions(iSrvVer, iClntVer);
oParams := ConnectionDef.Params as TFDPhysInfxConnectionDefParams;
Result := TFDPhysInfxMetadata.Create(Self, FServerVersion, iClntVer, GetKeywords,
oParams.StringFormat = sfUnicode, FTxSupported);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysInfxConnection.GetStrsMaxSizes(AStrDataType: SQLSmallint;
AFixedLen: Boolean; out ACharSize, AByteSize: Integer);
begin
// char - 32767
// varchar - 255
// nchar - 32767
// nvarchar - 255
// lvarchar - 32739
case AStrDataType of
SQL_C_CHAR,
SQL_C_BINARY:
begin
AByteSize := 32739;
ACharSize := AByteSize;
end;
SQL_C_WCHAR:
begin
AByteSize := 32739;
ACharSize := AByteSize div SizeOf(SQLWChar);
end;
else
FDCapabilityNotSupported(Self, [S_FD_LPhys, S_FD_InfxId]);
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxConnection.GetExceptionClass: EODBCNativeExceptionClass;
begin
Result := EInfxNativeException;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysInfxConnection.InternalConnect;
var
oPars: TFDPhysInfxConnectionDefParams;
oStmt: TODBCCommandStatement;
oCol: TODBCColumn;
pData: SQLPointer;
iSize: SQLLen;
begin
inherited InternalConnect;
oPars := TFDPhysInfxConnectionDefParams(ConnectionDef.Params);
// Informix ODBC return wrong info by SQL_DBMS_VER
oStmt := TODBCCommandStatement.Create(ODBCConnection, Self);
try
oStmt.Open(1, 'SELECT FIRST 1 dbinfo(''version'', ''full'') FROM systables');
oCol := oStmt.AddCol(1, SQL_VARCHAR, SQL_C_WCHAR, 255);
oStmt.Fetch(1);
FServerVersion := FDVerStr2Int(oCol.AsStrings[0]);
finally
FDFree(oStmt);
end;
FTxSupported := True;
if oPars.TxSupported = tsChoose then begin
oStmt := TODBCCommandStatement.Create(ODBCConnection, Self);
try
oStmt.Open(1, 'SELECT a.is_logging FROM sysmaster:sysdatabases a ' +
'WHERE LOWER(a.name) = ''' + LowerCase(oPars.Database) + '''');
oCol := oStmt.AddCol(1, SQL_INTEGER, SQL_C_SLONG);
oStmt.Fetch(1);
if oCol.GetData(0, pData, iSize, True) then
FTxSupported := PSQLInteger(pData)^ <> 0;
finally
FDFree(oStmt);
end;
end
else
FTxSupported := oPars.TxSupported = tsYes;
if (InternalGetSharedCliHandle() = nil) and FTxSupported then begin
if oPars.TxRetainLocks then
InternalExecuteDirect('SET ENVIRONMENT RETAINUPDATELOCKS ''ALL''', nil);
if (FServerVersion >= ivInfx1110) and oPars.TxLastCommitted then
InternalExecuteDirect('SET ENVIRONMENT USELASTCOMMITTED ''COMMITTED READ''', nil);
end;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysInfxCommand }
{-------------------------------------------------------------------------------}
procedure TFDPhysInfxCommand.UpdateWaitLock;
var
s: String;
begin
TFDPhysInfxConnection(ODBCConnection).FWaitLock := FOptions.UpdateOptions.LockWait;
if TFDPhysInfxConnection(ODBCConnection).FWaitLock then
s := 'SET LOCK MODE TO WAIT 60'
else
s := 'SET LOCK MODE TO NOT WAIT';
TFDPhysInfxConnection(ODBCConnection).InternalExecuteDirect(s, nil);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysInfxCommand.InternalExecute(ATimes, AOffset: Integer;
var ACount: TFDCounter);
begin
if FOptions.UpdateOptions.LockWait <> TFDPhysInfxConnection(ODBCConnection).FWaitLock then
UpdateWaitLock;
inherited InternalExecute(ATimes, AOffset, ACount);
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxCommand.InternalOpen(var ACount: TFDCounter): Boolean;
begin
if FOptions.UpdateOptions.LockWait <> TFDPhysInfxConnection(ODBCConnection).FWaitLock then
UpdateWaitLock;
Result := inherited InternalOpen(ACount);
end;
{-------------------------------------------------------------------------------}
{ TFDPhysInfxEventThread }
{-------------------------------------------------------------------------------}
type
TFDPhysInfxEventThread = class(TThread)
private
[weak] FAlerter: TFDPhysInfxEventAlerter_DBMS_ALERT;
protected
procedure Execute; override;
public
constructor Create(AAlerter: TFDPhysInfxEventAlerter_DBMS_ALERT);
destructor Destroy; override;
end;
{-------------------------------------------------------------------------------}
constructor TFDPhysInfxEventThread.Create(AAlerter: TFDPhysInfxEventAlerter_DBMS_ALERT);
begin
inherited Create(False);
FAlerter := AAlerter;
FreeOnTerminate := True;
end;
{-------------------------------------------------------------------------------}
destructor TFDPhysInfxEventThread.Destroy;
begin
FAlerter.FWaitThread := nil;
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysInfxEventThread.Execute;
begin
while not Terminated and FAlerter.IsRunning do
try
FAlerter.FWaitCommand.Execute();
if not Terminated then
FAlerter.DoFired;
except
on E: EFDDBEngineException do
if E.Kind <> ekCmdAborted then begin
Terminate;
FAlerter.AbortJob;
end;
end;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysInfxEventMessage_DBMS_ALERT }
{-------------------------------------------------------------------------------}
type
TFDPhysInfxEventMessage_DBMS_ALERT = class(TFDPhysEventMessage)
private
FName,
FMessage: String;
public
constructor Create(const AName, AMessage: String);
end;
{-------------------------------------------------------------------------------}
constructor TFDPhysInfxEventMessage_DBMS_ALERT.Create(const AName, AMessage: String);
begin
inherited Create;
FName := AName;
FMessage := AMessage;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysInfxEventAlerter_DBMS_ALERT }
{-------------------------------------------------------------------------------}
const
C_WakeUpEvent = C_FD_SysNamePrefix + 'WAKEUP';
procedure TFDPhysInfxEventAlerter_DBMS_ALERT.InternalAllocHandle;
begin
FWaitConnection := GetConnection.Clone;
if FWaitConnection.State = csDisconnected then
FWaitConnection.Open;
FWaitConnection.CreateCommand(FWaitCommand);
SetupCommand(FWaitCommand);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysInfxEventAlerter_DBMS_ALERT.InternalReleaseHandle;
begin
FSignalCommand := nil;
FWaitCommand := nil;
FWaitConnection := nil;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysInfxEventAlerter_DBMS_ALERT.InternalRegister;
var
i: Integer;
oPar: TFDParam;
begin
FWaitCommand.CommandText := 'EXECUTE PROCEDURE DBMS_ALERT_REGISTER(:name)';
oPar := FWaitCommand.Params[0];
oPar.ParamType := ptInput;
oPar.DataType := ftString;
oPar.Size := 128;
FWaitCommand.Prepare();
FWaitCommand.Params[0].AsString := C_WakeUpEvent;
FWaitCommand.Execute();
for i := 0 to GetNames().Count - 1 do begin
FWaitCommand.Params[0].AsString := Trim(GetNames()[i]);
FWaitCommand.Execute();
end;
FWaitCommand.CommandText := 'EXECUTE PROCEDURE DBMS_ALERT_WAITANY(:name, :message, :status, :timeout)';
oPar := FWaitCommand.Params[0];
oPar.ParamType := ptOutput;
oPar.DataType := ftString;
oPar.Size := 128;
oPar := FWaitCommand.Params[1];
oPar.ParamType := ptOutput;
oPar.DataType := ftString;
oPar.Size := 32672;
oPar := FWaitCommand.Params[2];
oPar.ParamType := ptOutput;
oPar.DataType := ftInteger;
oPar := FWaitCommand.Params[3];
oPar.ParamType := ptInput;
oPar.DataType := ftInteger;
oPar.AsInteger := 86400;
FWaitCommand.Prepare();
FWaitThread := TFDPhysInfxEventThread.Create(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysInfxEventAlerter_DBMS_ALERT.DoFired;
begin
if (FWaitCommand.Params[2].AsInteger = 0) and
(CompareText(FWaitCommand.Params[0].AsString, C_WakeUpEvent) <> 0) then
FMsgThread.EnqueueMsg(TFDPhysInfxEventMessage_DBMS_ALERT.Create(
FWaitCommand.Params[0].AsString, FWaitCommand.Params[1].AsString));
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysInfxEventAlerter_DBMS_ALERT.InternalHandle(AEventMessage: TFDPhysEventMessage);
var
oMsg: TFDPhysInfxEventMessage_DBMS_ALERT;
begin
oMsg := TFDPhysInfxEventMessage_DBMS_ALERT(AEventMessage);
InternalHandleEvent(oMsg.FName, oMsg.FMessage);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysInfxEventAlerter_DBMS_ALERT.InternalAbortJob;
begin
if FWaitThread <> nil then begin
FWaitThread.Terminate;
InternalSignal(C_WakeUpEvent, Null);
FWaitCommand.AbortJob(True);
while (FWaitThread <> nil) and (FWaitThread.ThreadID <> TThread.Current.ThreadID) do
Sleep(1);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysInfxEventAlerter_DBMS_ALERT.InternalUnregister;
var
i: Integer;
oPar: TFDParam;
begin
FWaitThread := nil;
if FWaitCommand <> nil then
try
FWaitCommand.CommandText := 'EXECUTE PROCEDURE DBMS_ALERT_REMOVE(:name)';
oPar := FWaitCommand.Params[0];
oPar.ParamType := ptInput;
oPar.DataType := ftString;
oPar.Size := 128;
FWaitCommand.Prepare();
FWaitCommand.Params[0].AsString := C_WakeUpEvent;
FWaitCommand.Execute();
for i := 0 to GetNames().Count - 1 do begin
FWaitCommand.Params[0].AsString := Trim(GetNames()[i]);
FWaitCommand.Execute();
end;
except
// hide exception
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysInfxEventAlerter_DBMS_ALERT.InternalSignal(const AEvent: String;
const AArgument: Variant);
var
oPar: TFDParam;
begin
if FSignalCommand = nil then begin
GetConnection.CreateCommand(FSignalCommand);
SetupCommand(FSignalCommand);
FSignalCommand.CommandText := 'EXECUTE PROCEDURE DBMS_ALERT_SIGNAL(:name, :message)';
oPar := FSignalCommand.Params[0];
oPar.DataType := ftString;
oPar.Size := 128;
oPar := FSignalCommand.Params[1];
oPar.DataType := ftString;
oPar.Size := 32672;
FSignalCommand.Prepare();
end;
FSignalCommand.Params[0].AsString := AEvent;
FSignalCommand.Params[1].AsString := VarToStr(AArgument);
FSignalCommand.Execute();
end;
{-------------------------------------------------------------------------------}
function InfxNativeExceptionLoad(const AStorage: IFDStanStorage): TObject;
begin
Result := EInfxNativeException.Create;
EInfxNativeException(Result).LoadFromStorage(AStorage);
end;
{-------------------------------------------------------------------------------}
initialization
FDRegisterDriverClass(TFDPhysInfxDriver);
FDStorageManager().RegisterClass(EInfxNativeException, 'InfxNativeException',
@InfxNativeExceptionLoad, @FDExceptionSave);
finalization
FDUnregisterDriverClass(TFDPhysInfxDriver);
end.
|
unit URepositorioCoren;
interface
uses
UCoren
, UEntidade
, URepositorioDB
, SqlExpr
;
type
TRepositorioCoren = class(TRepositorioDB<TCoren>)
private
public
constructor Create;
//destructor Destroy; override;
procedure AtribuiDBParaEntidade(const coCOREN: TCoren); override;
procedure AtribuiEntidadeParaDB(const coCOREN: TCoren;
const coSQLQuery: TSQLQuery); override;
end;
implementation
uses
UDM
, SysUtils
, StrUtils
;
{ TRepositorioCoren }
constructor TRepositorioCoren.Create;
begin
inherited Create(TCoren, TBL_Coren, FLD_ENTIDADE_ID, STR_Coren);
end;
procedure TRepositorioCoren.AtribuiDBParaEntidade(const coCoren: TCoren);
begin
inherited;
with FSQLSelect do
begin
{coAGENTE. := FieldByName(FLD_AGENTE_NOME).AsString ;
coAGENTE.NOME := FieldByName(FLD_NOME).AsString ;
coAGENTE.ESPECIFICACAO := FieldByName(FLD_ESPECIFICACAO).AsString;
coAGENTE.DATA_NASC := FieldByName(FLD_DATA_NASC).AsDateTime; }
end;
end;
procedure TRepositorioCOREN.AtribuiEntidadeParaDB(const coCOREN: TCOREN;
const coSQLQuery: TSQLQuery);
begin
inherited;
with coSQLQuery do
begin
ParamByName(FLD_COREN).AsString := coCOREN.COREN;
ParamByName(FLD_NOME).AsString := coCOREN.NOME;
ParamByName(FLD_ESPECIFICACAO).AsString := coCOREN.ESPECIFICACAO ;
ParamByName(FLD_DATA_NASC).AsDate := coCOREN.DATA_NASC ;
end;
end;
end.
|
unit FC.StockChart.UnitTask.BB.AdjustWidthDialog;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Contnrs,
Dialogs, BaseUtils,SystemService, ufmDialogClose_B, ufmDialog_B, ActnList, StdCtrls, ExtendControls, ExtCtrls, Spin,
StockChart.Definitions,StockChart.Definitions.Units, FC.Definitions, DB, Grids, DBGrids, MultiSelectDBGrid,
ColumnSortDBGrid, EditDBGrid, MemoryDS, ComCtrls;
type
TfmAdjustWidthDialog = class(TfmDialogClose_B)
buAdjust: TButton;
taReport: TMemoryDataSet;
DataSource1: TDataSource;
grReport: TEditDBGrid;
taReportPeriod: TIntegerField;
taReportDeviations: TFloatField;
taReportProfit: TFloatField;
taReportNumber: TIntegerField;
Label1: TLabel;
laBestValue: TLabel;
Label2: TLabel;
edJitter: TExtendSpinEdit;
Label3: TLabel;
pbProgress: TProgressBar;
procedure buAdjustClick(Sender: TObject);
private
FIndicator: ISCIndicatorBB;
function Iterate:double;
procedure Adjust;
public
class procedure Run(const aIndicator: ISCIndicatorBB);
constructor Create(aOwner: TComponent); override;
destructor Destroy; override;
end;
implementation
uses Math;
type
TDirection = (dNone,dUp,dDown);
{$R *.dfm}
{ TfmAdjustWidthDialog }
function TfmAdjustWidthDialog.Iterate: double;
var
i: integer;
aSumm : double;
aInputData: ISCInputDataCollection;
aTop,aBottom: TSCRealNumber;
aCurrentDirection: TDirection;
aPrevValue : TSCRealNumber;
aJitter: TSCRealNumber;
aDelta : TSCRealNumber;
begin
aInputData:=FIndicator.GetInputData;
aCurrentDirection:=dNone;
aPrevValue:=0;
aSumm:=0;
aJitter:=FIndicator.GetInputData.PointToPrice(edJitter.Value);
//Проверка левая, нужна только для того, чтобы обратиться к последнему значению
//и тем самым сразу расчитать весь диапазон. Небольшая оптимизация
if IsNan(FIndicator.GetValue(aInputData.Count-1)) then
raise EAlgoError.Create;
for i:=FIndicator.GetFirstValidValueIndex to aInputData.Count-1 do
begin
aBottom:=FIndicator.GetInputData.RoundPrice(FIndicator.GetBottomLine(i));
//Пересечение нижней границы
if aInputData.DirectGetItem_DataLow(i)<=aBottom then
begin
case aCurrentDirection of
dNone: ;
//Уже отталкивлись от границы и опять от нее отталкиваемся
dUp: begin
aDelta:= (aBottom-aPrevValue);
if abs(aDelta)>aJitter then
aSumm:=aSumm+aDelta;
end;
dDown: begin
aSumm:=aSumm+(aPrevValue-aBottom);
end;
end;
aCurrentDirection:=dUp;
aPrevValue:=aBottom;
continue;
end;
aTop:=FIndicator.GetInputData.RoundPrice(FIndicator.GetTopLine(i));
//Пересечение верхней границы
if aInputData.DirectGetItem_DataHigh(i)>=aTop then
begin
case aCurrentDirection of
dNone: ;
dUp: begin
aSumm:=aSumm+(aTop-aPrevValue);
end;
//Уже отталкивлись от границы и опять от нее отталкиваемся
dDown: begin
aDelta:=(aPrevValue-aTop);
if abs(aDelta)>aJitter then
aSumm:=aSumm+aDelta;
end;
end;
aCurrentDirection:=dDown;
aPrevValue:=aTop;
continue;
end;
end;
result:=aSumm
end;
procedure TfmAdjustWidthDialog.Adjust;
var
i,j: Integer;
aBestPeriod: integer;
aBestDeviation,aBestValue: double;
begin
TWaitCursor.SetUntilIdle;
aBestValue:=0;
aBestPeriod:=21;
aBestDeviation:=2;
taReport.DisableControls;
try
taReport.EmptyTable;
taReport.Open;
pbProgress.Max:=100-21;
pbProgress.Position:=0;
pbProgress.Visible:=true;
j:=0;
for i := 21 to 100 do
begin
FIndicator.SetPeriod(i);
FIndicator.SetDeviation(1.5);
while FIndicator.GetDeviation<4 do
begin
inc(j);
taReport.Append;
taReport['Number']:=j;
taReport['Period']:=i;
taReport['Deviations']:=FIndicator.GetDeviation;
taReport['Profit']:=FIndicator.GetInputData.PriceToPoint(Iterate);
if aBestValue<taReport['Profit'] then
begin
aBestValue:=taReport['Profit'];
aBestPeriod:=i;
aBestDeviation:=FIndicator.GetDeviation;
end;
taReport.Post;
FIndicator.SetDeviation(FIndicator.GetDeviation+0.1);
end;
pbProgress.StepIt;
end;
finally
grReport.RefreshSort;
pbProgress.Visible:=false;
taReport.EnableControls;
end;
FIndicator.SetPeriod(aBestPeriod);
FIndicator.SetDeviation(aBestDeviation);
laBestValue.Caption:=IntToStr(aBestPeriod)+', '+FormatCurr('0,.00', aBestDeviation);
end;
procedure TfmAdjustWidthDialog.buAdjustClick(Sender: TObject);
begin
inherited;
Adjust;
end;
constructor TfmAdjustWidthDialog.Create(aOwner: TComponent);
begin
inherited;
end;
destructor TfmAdjustWidthDialog.Destroy;
begin
inherited;
end;
class procedure TfmAdjustWidthDialog.Run(const aIndicator: ISCIndicatorBB);
begin
with TfmAdjustWidthDialog.Create(nil) do
try
FIndicator:=aIndicator;
ShowModal;
finally
Free;
end;
end;
end.
|
unit GrafTool;
interface
uses Graph;
PROCEDURE MakePolyCircle(x,y,radius,numpoints);
CONST
maxpoints = 50;
TYPE
Poly := ARRAY[0..49] OF PointType;
VAR
PolyCircle := Poly;
BEGIN
radsqrd := radius * radius;
halfpoints := numpoints div 2;
scale := radius / numpoints;
startX := x - scale / 2;
FOR point := 0 TO halfpoints DO
BEGIN
Xpt := StartX + scale * point;
Ypt := sqrt((Xpt-x) * (Xpt-x) + radsqrd);
PolyCircle[point].X := round(Xpt);
PolyCircle[point].Y := round(y - Ypt);
PolyCircle[numpoints - point].X := round(Xpt);
PolyCircle[numpoints - point].Y := round(y - Ypt);
|
unit UFUserRegister;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls,
Vcl.Imaging.pngimage, UIRegisterController;
type
TFUserRegister = class(TForm)
pnlBackground: TPanel;
lblUsername: TLabel;
edtUsername: TEdit;
edtName: TEdit;
lblName: TLabel;
edtPassword: TEdit;
lblPassword: TLabel;
Label4: TLabel;
lblConfirmPassword: TLabel;
cbActive: TCheckBox;
edtConfirmPassword: TEdit;
pnlDividerTitle: TPanel;
lblTitle: TLabel;
imgTitle: TImage;
Panel1: TPanel;
btnSave: TButton;
btnCancel: TButton;
procedure btnSaveClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
private
{ Private declarations }
FController : IRegisterController;
function GetUsername: string;
procedure SetUsername(Value: string);
function GetName: string;
procedure SetName(Value: string);
function GetPassword: string;
procedure SetPassword(Value: string);
function GetConfirmPassword: string;
procedure SetConfirmPassword(Value: string);
function GetActive: boolean;
procedure SetActive(Value: boolean);
procedure SetController(Value: IRegisterController);
public
{ Public declarations }
property Username: string read GetUsername write SetUsername;
property Name: string read GetName write SetName;
property Password: string read GetPassword write SetPassword;
property ConfirmPassword: string read GetConfirmPassword write SetConfirmPassword;
property Active: boolean read GetActive write SetActive;
property Controller: IRegisterController write SetController;
procedure ShowMsgError(Msg: string);
end;
var
FUserRegister: TFUserRegister;
implementation
{$R *.dfm}
{ TFUserRegister }
procedure TFUserRegister.btnCancelClick(Sender: TObject);
begin
FController.RegisterClose;
end;
procedure TFUserRegister.btnSaveClick(Sender: TObject);
begin
FController.RegisterSave;
end;
function TFUserRegister.GetActive: boolean;
begin
Result := cbActive.Checked;
end;
function TFUserRegister.GetConfirmPassword: string;
begin
Result := edtConfirmPassword.Text;
end;
function TFUserRegister.GetName: string;
begin
Result := edtName.Text;
end;
function TFUserRegister.GetPassword: string;
begin
Result := edtPassword.Text;
end;
function TFUserRegister.GetUsername: string;
begin
Result := edtUsername.Text;
end;
procedure TFUserRegister.SetActive(Value: boolean);
begin
cbActive.Checked := Value;
end;
procedure TFUserRegister.SetConfirmPassword(Value: string);
begin
edtConfirmPassword.Text := Value;
end;
procedure TFUserRegister.SetController(Value: IRegisterController);
begin
FController := Value;
end;
procedure TFUserRegister.SetName(Value: string);
begin
edtName.Text := Value;
end;
procedure TFUserRegister.SetPassword(Value: string);
begin
edtPassword.Text := Value;
end;
procedure TFUserRegister.SetUsername(Value: string);
begin
edtUsername.Text := Value;
end;
procedure TFUserRegister.ShowMsgError(Msg: string);
begin
MessageDlg(Msg,mtError,mbOKCancel,0);
end;
end.
|
{*********************************************}
{ TeeBI Software Library }
{ Importing data from TComponent }
{ Copyright (c) 2015-2017 by Steema Software }
{ All Rights Reserved }
{*********************************************}
unit BI.Store.Component;
interface
{
This unit declares the TComponentImporter class.
TComponentImporter is used to import data from any TComponent into a
TDataItem.
For example, we can import contents from a TStrings:
BIGrid1.Data := TComponentImporter.From(Self, Memo1.Lines)
Supported component classes (and derived classes):
- Any TComponent that has a TStrings or TStringList property
- TXMLDocument
- TDataSet
- TField
- TDataSource
- TCustomConnection (FireDAC, any other database library, etc)
- TBaseDataImporter
- Any TComponent that has a TDataSource property
- Any TComponent class supported by a "plugin":
Available plugin classes:
- TControlImporter (see VCLBI.Component and FMXBI.Component units)
This class is also internally used by editor dialogs to allow selecting any
control or component to import its data
}
uses
{System.}Classes,
{$IFNDEF FPC}
System.Generics.Collections,
{$ENDIF}
{Data.}DB, BI.DataItem, BI.Persist;
type
TComponentImporterClass=class of TComponentImporter;
{$IFNDEF FPC}
{$IF CompilerVersion>=23}
[ComponentPlatformsAttribute(pidWin32 or pidWin64 or pidOSX32
{$IF CompilerVersion>=25}or pidiOSSimulator or pidiOSDevice{$ENDIF}
{$IF CompilerVersion>=26}or pidAndroid{$ENDIF}
{$IF CompilerVersion>=29}or pidiOSDevice64{$ENDIF}
)]
{$ENDIF}
{$ENDIF}
TComponentImporter=class(TBaseDataImporter)
private
{$IFDEF AUTOREFCOUNT}[weak]{$ENDIF}
FSource : TComponent;
IDataLink : TDataLink;
IDataSource : TDataSource;
ILoading : Boolean;
class function IgnoreError(const Sender:TObject; const Error:String):Boolean;
procedure SetSource(const Value: TComponent);
class function TryFromStrings(const ASource:TComponent):TDataItem;
protected
function DoImport(const AComponent: TComponent):TDataItem; virtual;
procedure GetItems(const AData:TDataItem); override;
class function GuessFrom(const AStrings:TStrings):TDataItem; overload; static;
class function GuessFrom(const AString:String):TDataItem; overload; static;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure Load(const AData:TDataItem; const Children:Boolean); override;
class function StringsOf(const ASource:TComponent):TStrings; virtual;
public
class var
Plugins : TList{$IFNDEF FPC}<TComponentImporterClass>{$ENDIF};
Destructor Destroy; override;
procedure Refresh;
class function DataOf(const AComponent:TComponent):TDataItem; virtual;
class function DataOfProvider(const AData:TDataItem):TDataItem; static;
class function From(const AOwner,AComponent:TComponent): TDataItem; overload; static;
class function From(const AOwner,AComponent:TComponent; const AOrigin:String): TDataItem; overload; static;
class function IsSupported(const AComponent:TComponent):Boolean; static;
class function Origin(const AComponent:TComponent; const AData:TDataItem):String; static;
class function ProviderOf(const AData:TDataItem):TComponent; static;
class function Supports(const AComponent:TComponent):Boolean; virtual;
class function TryLoadOrigin(const AOwner,AProvider:TComponent; var AOrigin:String):TDataItem; static;
published
property Source:TComponent read FSource write SetSource;
end;
implementation
|
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 1024,0,0}
{
by Behdad Esfahbod
Algorithmic Problems Book
April '2000
Problem 171 O(N3) BellmanFord Alg.
}
program
TransferInWeightedGraph;
const
MaxN = 100;
var
N, M : Integer;
G : array [0 .. MaxN, 0 .. MaxN] of Longint;
S : array [0 .. MaxN] of Longint;
NoSol : Boolean;
I, J, K, L : Integer;
procedure ReadInput;
begin
FillChar(G, SizeOf(G), 1);
Assign(Input, 'input.txt');
Reset(Input);
Readln(N, M);
for I := 1 to M do
begin
Readln(J, K, L);
G[K, J] := L - 1;
end;
Close(Input);
end;
procedure WriteOutput;
begin
Assign(Output, 'output.txt');
Rewrite(Output);
if NoSol then
Writeln('NO SOLUTION')
else
for I := 1 to N do
if S[I] <> 0 then
Writeln(I, ' ', -S[I]);
Close(Output);
end;
procedure BellmanFord;
begin
FillChar(S, SizeOf(S), 1);
for I := 1 to N do
G[0, I] := 0;
S[0] := 0;
for K := 0 to N do
begin
NoSol := False;
for I := 0 to N do
for J := 0 to N do
if S[I] > S[J] + G[J, I] then
begin
S[I] := S[J] + G[J, I];
NoSol := True;
end;
end;
end;
begin
ReadInput;
BellmanFord;
WriteOutput;
end.
|
{********************************************}
{ TeeChart Pro Charting Library }
{ Average Function editor }
{ Copyright (c) 2002-2004 by David Berneda }
{ All Rights Reserved }
{********************************************}
unit TeeAvgFuncEditor;
{$I TeeDefs.inc}
interface
uses
{$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
SysUtils, Classes,
{$IFDEF CLX}
QGraphics, QControls, QForms, QDialogs, QStdCtrls,
{$ELSE}
Graphics, Controls, Forms, Dialogs, StdCtrls,
{$ENDIF}
TeeEdiPeri, TeCanvas;
type
TAverageFuncEditor = class(TTeeFunctionEditor)
CBNulls: TCheckBox;
procedure CBNullsClick(Sender: TObject);
private
{ Private declarations }
protected
procedure ApplyFormChanges; override;
procedure SetFunction; override;
public
{ Public declarations }
end;
implementation
{$IFNDEF CLX}
{$R *.dfm}
{$ELSE}
{$R *.xfm}
{$ENDIF}
uses TeeFunci;
{ TAverageFuncEditor }
procedure TAverageFuncEditor.ApplyFormChanges;
begin
inherited;
TAverageTeeFunction(IFunction).IncludeNulls:=CBNulls.Checked;
end;
procedure TAverageFuncEditor.SetFunction;
begin
inherited;
CBNulls.Checked:=TAverageTeeFunction(IFunction).IncludeNulls;
end;
procedure TAverageFuncEditor.CBNullsClick(Sender: TObject);
begin
EnableApply;
end;
initialization
RegisterClass(TAverageFuncEditor);
end.
|
unit RealSizeUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, Generics.Collections;
type
TRealSizeForm = class(TForm)
RealSizePaintBox: TPaintBox;
procedure FormShow(Sender: TObject);
procedure RealSizePaintBoxPaint(Sender: TObject);
private
{ Private declarations }
function OffsetCoordinate(A: Integer): Integer;
public
{ Public declarations }
end;
var
RealSizeForm: TRealSizeForm;
implementation
{$R *.dfm}
uses MainUnit;
procedure TRealSizeForm.FormShow(Sender: TObject);
begin
ClientWidth := 2 * MainForm.FPixelsPerQuadrantSide + 1;
ClientHeight := 2 * MainForm.FPixelsPerQuadrantSide + 1;
end;
procedure TRealSizeForm.RealSizePaintBoxPaint(Sender: TObject);
var
InnerItem: TPair<Integer, TColor>;
OuterItem: TPair<Integer, TDictionary<Integer, TColor>>;
begin
// ** clearing canvas ** //
RealSizePaintBox.Canvas.Pen.Style := psClear;
RealSizePaintBox.Canvas.Brush.Color := MainUnit.BLANK_COLOR;
RealSizePaintBox.Canvas.Rectangle(0, 0, RealSizePaintBox.Width, RealSizePaintBox.Height);
RealSizePaintBox.Canvas.Pen.Style := psSolid;
// ** filling pixels ** //
for OuterItem in MainForm.FPixels do
for InnerItem in OuterItem.Value do
RealSizePaintBox.Canvas.Pixels[OffsetCoordinate(OuterItem.Key) + 1, OffsetCoordinate(InnerItem.Key) + 1] := InnerItem.Value;
end;
function TRealSizeForm.OffsetCoordinate(A: Integer): Integer;
begin
Result := A;
if MainForm.FCenterOrigin then
Result := Result + RealSizePaintBox.Width div 2;
end;
end.
|
unit nexUrls;
interface
uses Sysutils, Classes, idHttp, md5, SyncObjs, ExtCtrls, Windows;
type
TnexUrlsRefresh = class ( TThread )
protected
procedure Execute; override;
procedure Get;
public
ResOk : Boolean;
ResString : String;
constructor Create;
end;
TnexUrls = class ( TStringList )
private
FDef : TStrings;
FForce : TStrings;
FCS : TCriticalSection;
FTimer : TTimer;
FOnRefresh: TNotifyEvent;
FRefreshTh : TnexUrlsRefresh;
FKeepRefreshing : Boolean;
function GetOnRefresh: TNotifyEvent;
procedure SetOnRefresh(const Value: TNotifyEvent);
function _Values(aName: String): String;
function GetTextStr: String;
procedure SetTextStr(const Value: String);
procedure OnTimer(Sender: TObject);
procedure OnRefreshTerminate(Sender: TObject);
public
function Url(aNome: String; aParams: String = ''; aAddLang: Boolean = True): String;
function CustomUrl(aNome, aSufix, aParams: String; aAddLang: Boolean): String;
procedure Refresh;
constructor Create;
destructor Destroy; override;
procedure SetString(aValue: String);
procedure KeepRefreshing;
function SkyWidth(aScreenWidth: Integer): Integer;
function AppTimeMS: Cardinal;
function AppRetryMS: Cardinal;
function TTLms: Cardinal;
function AsString: String;
property Text: String
read GetTextStr write SetTextStr;
property OnRefresh: TNotifyEvent
read GetOnRefresh write SetOnRefresh;
end;
function AddParamUrl(aUrl, aParams: String): String;
var
gUrls : TnexUrls;
implementation
uses
ncDebug, uNexTransResourceStrings_PT;
threadvar
gUrlUsada : String;
{ TnexUrls }
const
salt = '>LKHASDIUywefd7kdsf_)(*!@Tkjhasfdkxzxxx7777!38213zxc%nbv';
maxnexttry = 30 * 60 * 1000;
incnexttry = 5000;
function TnexUrls.AppRetryMS: Cardinal;
const
minuto = 60 * 1000;
hora = 60 * minuto;
begin
Result := StrToIntDef(_Values('app_time'), 5) * minuto;
if (Result < (5*minuto)) or (Result > (24*hora)) then
Result := 5*minuto;
end;
function TnexUrls.AppTimeMS: Cardinal;
const
minuto = 60 * 1000;
hora = 60 * minuto;
begin
Result := StrToIntDef(_Values('app_time'), 60) * minuto;
if (Result < (5*minuto)) or (Result > (24*hora)) then
Result := hora;
end;
function TnexUrls.AsString: String;
begin
FCS.Enter;
try
Result := Text;
finally
FCS.Leave;
end;
end;
function ForceFName: String;
begin
Result := ExtractFilePath(ParamStr(0))+'forceurl.ini';
end;
constructor TnexUrls.Create;
begin
inherited;
FKeepRefreshing := False;
FTimer := TTimer.Create(nil);
FTimer.OnTimer := OnTimer;
FTimer.Enabled := False;
FRefreshTh := nil;
FForce := TStringList.Create;
if FileExists(ForceFName) then
FForce.LoadFromFile(ForceFName);
FDef := TStringList.Create;
FDef.Values['contas_app'] := 'http://contas.nextar.com.br/contas/app';
FDef.Values['contas_app_admin'] := 'http://contas.nextar.com.br/contas/app';
FDef.Values['contas_app_server'] := 'http://contas.nextar.com.br/contas/app';
FDef.Values['contas_finalizatrial'] := 'http://contas.nextar.com.br/contas/finalizatrial';
FDef.Values['contas_infoplanos'] := 'http://contas.nextar.com.br/contas/infoplanos/';
FDef.Values['info_server'] := 'http://contas2.nextar.com.br/contas/info/server';
FDef.Values['contas_obteminfocampanha'] := 'http://contas.nextar.com.br/contas/obteminfocampanha';
FDef.Values['contas_obtemchaveseg'] := 'http://contas.nextar.com.br/contas/obtemchaveseg';
FDef.Values['contas_corrigiremail'] := 'http://contas.nextar.com.br/contas/corrigiremail';
FDef.Values['contas_criarcontabasica'] := 'http://contas.nextar.com.br/contas/criarcontabasica';
FDef.Values['contas_ativar'] := 'http://contas.nextar.com.br/contas/ativar';
FDef.Values['contas_esquecisenha'] := 'http://contas.nextar.com.br/contas/esquecisenha';
FDef.Values['contas_reenviaconfirmacao'] := 'http://contas.nextar.com.br/contas/reenviaconfirmacao';
FDef.Values['contas_obtemregistro'] := 'http://contas.nextar.com.br/contas/obtemregistro';
FDef.Values['contas_transferir'] := 'http://contas.nextar.com.br/contas/transferir';
FDef.Values['contas_abriuadmin'] := 'http://contas.nextar.com.br/contas/abriuadmin';
FDef.Values['contas_assinar'] := 'http://contas.nextar.com.br/contas/assinar';
FDef.Values['contas_confirmartrial'] := 'http://contas.nextar.com.br/contas/confirmartrial';
FDef.Values['contas_upgradetrial'] := 'http://contas.nextar.com.br/contas/upgradetrial';
FDef.Values['contas_dataupgradeplano'] := 'http://contas.nextar.com.br/contas/dataupgradeplano';
FDef.Values['contas_fazupgradeplano'] := 'http://contas.nextar.com.br/contas/fazupgradeplano';
FDef.Values['pag_suporte_free'] := 'http://docs.nextar.com.br/969cfbfe34910c2c0da218709437b2d4';
FDef.Values['pag_suporte_pro'] := 'http://docs.nextar.com.br/9fff1a8208287c95a378997d1083aeca';
FDef.Values['pag_suporte_premium'] := 'http://docs.nextar.com.br/1c8ab77f89947c4c9f44056cd3e9cdfd';
FDef.Values['contas_setflags'] := 'http://contas.nextar.com.br/contas/setflags';
FDef.Values['contas_getflags'] := 'http://contas.nextar.com.br/contas/getflags';
FDef.Values['contas_cep'] := 'http://contas.nextar.com.br/cep';
FDef.Values['kapi_registro'] := 'http://contas.nextar.com.br/kite/registro';
FDef.Values['kapi_token'] := 'http://contas.nextar.com.br/kite/token';
FDef.Values['kapi_consultaip'] := 'http://contas.nextar.com.br/kite/consultaip';
FDef.Values['kapi_employeepass'] := 'http://contas.nextar.com.br/kite/profile/employeepass';
FDef.Values['kapi_emailcaixa'] := 'http://contas.nextar.com.br/kite/emailcaixa';
FDef.Values['track'] := 'http://contas.nextar.com.br/track';
FDef.Values['nexmsg'] := 'http://contas.nextar.com.br/nexmsgs';
FDef.Values['nextabs'] := 'http://contas.nextar.com.br/nextabs';
FDef.Values['autoconninfo'] := 'http://contas.nextar.com.br/autoconninfo';
FDef.Values['dbapi_setup'] := 'http://contas.nextar.com.br/dbapi/setup';
FDef.Values['scnt'] := 'http://contas.nextar.com.br/scnt';
FDef.Values['mailer'] := 'http://contas.nextar.com.br/mailer';
FDef.Values['img_botao'] := 'http://botao.nextar.com';
FDef.Values['ad_toolbar'] := 'http://ads.nexcafe.com.br/toolbar';
FDef.Values['ad_sky'] := 'http://ads.nexcafe.com.br/sky';
FDef.Values['ad_home'] := 'http://ads.nexcafe.com.br/open';
FDef.Values['ttl'] := '60';
FDef.Values['app_time'] := '60';
FDef.Values['app_retry'] := '5';
FDef.Values['nexapp_cards'] := 'http://api.app.nextar.com/cards';
FDef.Values['nexapp_products'] := 'http://api.app.nextar.com/products';
FDef.Values['nexapp_reset'] := 'http://api.app.nextar.com/reset';
FDef.Values['cloudbk'] := 'http://cloud.nextar.com/backup';
FCS := TCriticalSection.Create;
FOnRefresh := nil;
end;
function TnexUrls.CustomUrl(aNome, aSufix, aParams: String;
aAddLang: Boolean): String;
begin
Result := FForce.Values[aNome];
if Result='' then begin
Result := _Values(aNome);
if Result='' then begin
Refresh;
Result := _Values(aNome);
end;
if Result='' then
Result := FDef.Values[aNome];
end;
if aSufix>'' then begin
if Copy(Result, Length(Result), 1)<>'/' then Result := Result + '/';
Result := Result + aSufix;
end;
if aAddLang then
if Pos('lang=', aParams)<1 then begin
if aParams>'' then aParams := aParams + '&';
aParams := aParams + 'lang='+SLingua;
end;
Result := AddParamUrl(Result, aParams);
DebugMsg(Self, 'Url: '+Result);
gUrlUsada := Result;
end;
destructor TnexUrls.Destroy;
begin
FTimer.Free;
FDef.Free;
FCS.Free;
FForce.Free;
inherited;
end;
function TnexUrls.GetOnRefresh: TNotifyEvent;
begin
FCS.Enter;
try
Result := FOnRefresh;
finally
FCS.Leave;
end;
end;
function TnexUrls.GetTextStr: String;
begin
Result := inherited Text;
end;
procedure TnexUrls.KeepRefreshing;
begin
FKeepRefreshing := True;
Refresh;
end;
procedure TnexUrls.OnRefreshTerminate(Sender: TObject);
var
ResOk: Boolean;
ResString : String;
begin
ResOk := FRefreshTh.ResOk;
ResString := FRefreshTh.ResString;
FRefreshTh := nil;
if ResOk then begin
DebugMsg(Self, 'OnRefreshTerminate - ResOk');
SetString(ResString);
if FKeepRefreshing then begin
FTimer.Interval := TTLms;
FTimer.Enabled := True;
end;
if Assigned(FOnRefresh) then FOnRefresh(Self);
end else
begin
DebugMsg(Self, 'OnRefreshTerminate - Falhou');
FTimer.Interval := 5000;
FTimer.Enabled := True;
end;
end;
procedure TnexUrls.OnTimer(Sender: TObject);
begin
FTimer.Enabled := False;
Refresh;
end;
procedure TnexUrls.Refresh;
begin
if Assigned(FRefreshTh) then Exit;
FRefreshTh := TnexUrlsRefresh.Create;
FRefreshTh.OnTerminate := OnRefreshTerminate;
FREfreshTh.Resume;
end;
procedure TnexUrls.SetOnRefresh(const Value: TNotifyEvent);
begin
FCS.Enter;
try
FOnRefresh := Value;
finally
FCS.Leave;
end;
end;
procedure TnexUrls.SetString(aValue: String);
begin
FCS.Enter;
try
Text := aValue;
finally
FCS.Leave;
end;
end;
procedure TnexUrls.SetTextStr(const Value: String);
begin
inherited Text := Value;
end;
type
TSkyWidth = record
swScreen : Integer;
swWidth : Integer;
end;
function StrToSkyWidth(S: String; var SW: TSkyWidth): Boolean;
var P: Integer;
begin
Result := False;
P := Pos('=', S);
if P<2 then Exit;
sw.swScreen := StrToIntDef(Copy(S, 1, P-1), 0);
sw.swWidth := StrToIntDef(Copy(S, P+1, 4), 0);
Result := (sw.swScreen>0) and (sw.swWidth>0) and (sw.swWidth<sw.swScreen);
end;
function TnexUrls.SkyWidth(aScreenWidth: Integer): Integer;
var
S : String;
P : Integer;
sw : TskyWidth;
begin
Result := 160;
S := _Values('skysizemap');
if S='' then Exit;
repeat
P := Pos('(', S);
if P>0 then begin
System.Delete(S, 1, P);
P := Pos(')', S);
if P>0 then begin
if StrToSkyWidth(Copy(S, 1, P-1), sw) then
if aScreenWidth<=sw.swScreen then begin
Result := sw.swWidth;
Exit;
end;
System.Delete(S, 1, P);
end;
end;
until (P<1);
end;
function TnexUrls.TTLms: Cardinal;
const
minuto = 60 * 1000;
hora = 60 * minuto;
begin
Result := StrToIntDef(_Values('ttl'), 60) * minuto;
if (Result < (5*minuto)) or (Result>(24*hora))then
Result := hora;
DebugMsg(Self, 'TTLms: '+IntToStr(Result));
end;
function AddParamUrl(aUrl, aParams: String): String;
begin
Result := aUrl;
if aParams='' then Exit;
if Pos('?', Result)<1 then begin
if Copy(Result, Length(Result), 1)<>'/' then
Result := Result + '/';
Result := Result + '?';
end else
Result := Result + '&';
Result := Result + aParams;
end;
function TnexUrls.Url(aNome: String; aParams: String = ''; aAddLang: Boolean = True): String;
begin
Result := CustomUrl(aNome, '', aParams, aAddLang);
{ Result := FForce.Values[aNome];
if Result='' then begin
Result := _Values(aNome);
if Result='' then begin
Refresh;
Result := _Values(aNome);
end;
if Result='' then
Result := FDef.Values[aNome];
end;
if aAddLang then
if Pos('lang=', aParams)<1 then begin
if aParams>'' then aParams := aParams + '&';
aParams := aParams + 'lang='+SLingua;
end;
Result := AddParamUrl(Result, aParams);
DebugMsg(Self, 'Url: '+Result);
gUrlUsada := Result; }
end;
function TnexUrls._Values(aName: String): String;
begin
FCS.Enter;
try
Result := Values[aName];
finally
FCS.Leave;
end;
end;
{ TnexUrlsRefresh }
constructor TnexUrlsRefresh.Create;
begin
inherited Create(True);
ResOk := False;
ResString := '';
FreeOnTerminate := True;
end;
procedure TnexUrlsRefresh.Execute;
var NextTry : Cardinal;
begin
NextTry := 0;
ResOk := False;
repeat
try
if GetTickCount>=NextTry then begin
Get;
NextTry := GetTickCount + 10000;
end;
Sleep(10);
except
On E: Exception do DebugEx(Self, 'Execute', E);
end;
until ResOk or Terminated;
end;
procedure TnexUrlsRefresh.Get;
var h: TidHttp; sl: TStrings; S: String;
begin
H := TidHttp.Create(nil);
try
ResOk := False;
H.HandleRedirects := True;
sl := TStringList.Create;
try
try
sl.Text := H.Get('http://setup.contas.nextar.com.br/?random='+IntToStr(Random(999999)));
DebugMsg(Self, 'Get - ' + sl.Text);
except
on E: Exception do begin
DebugEx(Self, 'Get - '+sl.Text, E);
Exit;
end;
end;
S := sl.Values['chave'];
if S='' then Exit;
sl.Delete(sl.IndexOfName('chave'));
if not sameText(S, getmd5str(sl.Text+salt)) then
begin
DebugMsg(Self, 'Get - Chave Invalida: '+S+' - Chave servidor: '+getmd5str(sl.Text+salt));
Exit;
end;
ResOk := True;
ResString := sl.Text;
finally
sl.Free;
end;
finally
H.Free;
end;
end;
initialization
gUrls := TnexUrls.Create;
finalization
gUrls.Free;
end.
|
unit chrome_common;
{$mode delphi}{$H+}
{$I vrode.inc}
interface
uses
Classes, SysUtils, variants,
vr_utils, vr_types, //vrUtilsPlus,
uCEFTypes, uCEFInterfaces, uCEFv8Value, uCEFValue,
uCEFListValue;
type
Pustring = ^ustring;
const
MSG_CMD: ustring = 'cmd';
MSG_EVENT: ustring = 'event';
{ Commands }
CMD_FUNC_EXEC = 1; //First param: function name
CMD_POST_JSON_STRING = 2;
{ Events }
EVENT_JSON_RECEIVED = 1;
function GetObjectKeyValueObj(const AObj: ICefv8Value; const AKey: ustring; out AResult: ICefv8Value): Boolean;
function GetObjectKeyValueStr(const AObj: ICefv8Value; const AKey: ustring; out S: ustring): Boolean;
function GetObjectKeyValueStrDef(const AObj: ICefv8Value; const AKey: ustring;
const ADefault: ustring = ''): ustring;
function GetObjectKeyValueInt(const AObj: ICefv8Value; const AKey: ustring; out I: Integer): Boolean;
function GetObjectKeyValueIntDef(const AObj: ICefv8Value; const AKey: ustring;
const ADefault: Integer = 0): Integer;
function FindFunction(const ACtx: ICefv8Context; const AName: ustring; out AFunc: ICefv8Value): Boolean;
function CefValueToCefv8Value(const AValue: ICefValue): ICefv8Value;
function Cefv8ValueToCefValue(const AValue: ICefv8Value): ICefValue;
function CefListValueToCefv8ValueArray(const AList: ICefListValue; const AFromIndex: Integer = 0): TCefv8ValueArray;
function CefListValueToStringArray(const AList: ICefListValue; const AFromIndex: Integer = 0): TStringArray;
function CefListValueToByteArray(const AList: ICefListValue; const AFromIndex: Integer = 0): TByteDynArray;
procedure AddCefv8ValueToCefListValue(const AValue: ICefv8Value; const AList: ICefListValue; const AIndex: Integer);
function VarsToCefListValue(const AVars: array of const): ICefListValue;
procedure AddVarToCefListValue(const AList: ICefListValue; AIndex: Integer; constref AVar: TVarRec);
var
ChromeInitialized: Boolean = False;
OnAfterGlobalCEFAppCreate: TProcedure = nil;
implementation
function GetObjectKeyValueObj(const AObj: ICefv8Value; const AKey: ustring; out
AResult: ICefv8Value): Boolean;
begin
Result := False;
if not AObj.IsObject then Exit;
AResult := AObj.GetValueByKey(AKey);
Result := AResult.IsObject;
if not Result then
AResult := nil;
end;
function GetObjectKeyValueStr(const AObj: ICefv8Value; const AKey: ustring; out S: ustring): Boolean;
var
val: ICefv8Value;
begin
Result := False;
if not AObj.IsObject then Exit;
val := AObj.GetValueByKey(AKey);
if (val = nil) or not val.IsString then Exit;
Result := True;
S := val.GetStringValue;
end;
function GetObjectKeyValueStrDef(const AObj: ICefv8Value; const AKey: ustring;
const ADefault: ustring): ustring;
begin
if not GetObjectKeyValueStr(AObj, AKey, Result) then
Result := ADefault;
end;
function GetObjectKeyValueInt(const AObj: ICefv8Value; const AKey: ustring; out I: Integer): Boolean;
var
val: ICefv8Value;
begin
Result := False;
if not AObj.IsObject then Exit;
val := AObj.GetValueByKey(AKey);
if (val = nil) or not val.IsInt then Exit;
Result := True;
I := val.GetIntValue;
end;
function GetObjectKeyValueIntDef(const AObj: ICefv8Value; const AKey: ustring;
const ADefault: Integer): Integer;
begin
if not GetObjectKeyValueInt(AObj, AKey, Result) then
Result := ADefault;
end;
function FindFunction(const ACtx: ICefv8Context; const AName: ustring; out AFunc: ICefv8Value): Boolean;
var
err: ICefV8Exception = nil;
begin
Result := (ACtx <> nil) and ACtx.Eval(AName, '', 0, AFunc{%H-}, err) and
AFunc.IsFunction;
if not Result then
AFunc := nil;
end;
function CefValueToCefv8Value(const AValue: ICefValue): ICefv8Value;
begin
if (AValue = nil) or not AValue.IsValid then
begin
Result := TCefv8ValueRef.NewUndefined;
Exit;
end;
try
case AValue.GetType of
VTYPE_NULL: Result := TCefv8ValueRef.NewNull;
VTYPE_BOOL: Result := TCefv8ValueRef.NewBool(AValue.GetBool);
VTYPE_INT: Result := TCefv8ValueRef.NewInt(AValue.GetInt);
VTYPE_DOUBLE: Result := TCefv8ValueRef.NewDouble(AValue.GetDouble);
VTYPE_STRING: Result := TCefv8ValueRef.NewString(AValue.GetString);
//VTYPE_BINARY: Result := TCefv8ValueRef.NewBool(AValue.GetBool);
//VTYPE_DICTIONARY: Result := TCefv8ValueRef.NewBool(AValue.GetBool);
//VTYPE_LIST: Result := TCefv8ValueRef.NewBool(AValue.GetBool);
//VTYPE_INVALID: ;
else
Result := TCefv8ValueRef.NewUndefined;
end;
except
Result := TCefv8ValueRef.NewUndefined;
end;
end;
function Cefv8ValueToCefValue(const AValue: ICefv8Value): ICefValue;
var
lst: ICefListValue;
i: Integer;
begin
Result := TCefValueRef.New;
if (AValue = nil) or not AValue.IsValid then
Exit;
if AValue.IsString then
Result.SetString(AValue.GetStringValue)
else if AValue.IsInt then
Result.SetInt(AValue.GetIntValue)
else if AValue.IsBool then
Result.SetBool(Integer(AValue.GetBoolValue))
else if AValue.IsNull then
Result.SetNull
else if AValue.IsDouble then
Result.SetDouble(AValue.GetDoubleValue)
else if AValue.IsArray then
begin
//if List,Dictionary in List may be ERROR on exit upper stack function
//use AddCefv8ValueToCefListValue()
lst := TCefListValueRef.New;
Result.SetList(lst);
for i := 0 to AValue.GetArrayLength - 1 do
lst.SetValue(i, Cefv8ValueToCefValue(AValue.GetValueByIndex(i)));
end;
//else if AValue.IsObject then; //ToDo lst.SetDictionary();
end;
function CefListValueToCefv8ValueArray(const AList: ICefListValue;
const AFromIndex: Integer): TCefv8ValueArray;
var
i: Integer;
begin
if (AList = nil) or not AList.IsValid then
begin
SetLength(Result, 0);
Exit;
end;
SetLength(Result, AList.GetSize - AFromIndex);
for i := 0 to Length(Result) - 1 do
Result[i] := CefValueToCefv8Value(AList.GetValue(i + AFromIndex));
end;
function CefListValueToStringArray(const AList: ICefListValue;
const AFromIndex: Integer): TStringArray;
var
i: Integer;
LenArr: NativeUInt;
begin
SetLength(Result , 0);
if (AList = nil) or not AList.IsValid then
Exit;
LenArr := AList.GetSize - AFromIndex;
if LenArr <= 0 then Exit;
SetLength(Result, LenArr);
for i := 0 to LenArr - 1 do
Result[i] := utf_16To8(AList.GetString(AFromIndex + i));
end;
function CefListValueToByteArray(const AList: ICefListValue;
const AFromIndex: Integer): TByteDynArray;
var
i: Integer;
LenArr: NativeUInt;
begin
SetLength(Result , 0);
if (AList = nil) or not AList.IsValid then
Exit;
LenArr := AList.GetSize - AFromIndex;
if LenArr <= 0 then Exit;
SetLength(Result, LenArr);
for i := 0 to LenArr - 1 do
Result[i] := AList.GetInt(AFromIndex + i);
end;
procedure AddCefv8ValueToCefListValue(const AValue: ICefv8Value;
const AList: ICefListValue; const AIndex: Integer);
var
i: Integer;
begin
if (AValue = nil) or not AValue.IsValid or
(AList = nil) or not AList.IsValid then
Exit;
if AValue.IsArray then
begin
for i := 0 to AValue.GetArrayLength - 1 do
AList.SetValue(AIndex + i, Cefv8ValueToCefValue(AValue.GetValueByIndex(i)));
end
else if AValue.IsObject then
begin
//Todo
end
else
AList.SetValue(AIndex, Cefv8ValueToCefValue(AValue));
end;
function VarsToCefListValue(const AVars: array of const): ICefListValue;
var
i: Integer;
begin
Result := TCefListValueRef.New;
for i := 0 to Length(AVars) - 1 do
AddVarToCefListValue(Result, i, AVars[i]);
end;
procedure AddVarToCefListValue(const AList: ICefListValue; AIndex: Integer;
constref AVar: TVarRec);
begin
case AVar.VType of
vtInteger: AList.SetInt(AIndex, AVar.VInteger);
vtBoolean: AList.SetBool(AIndex, AVar.VBoolean);
vtAnsiString: AList.SetString(AIndex, UTF8Decode(AnsiString(AVar.VAnsiString)));
vtUnicodeString: AList.SetString(AIndex, ustring(AVar.VUnicodeString));
vtWideString: AList.SetString(AIndex, WideString(AVar.VWideString));
else
AList.SetNull(AIndex);
end;
end;
end.
|
(*
Name: KPInstallVisualKeyboard
Copyright: Copyright (C) SIL International.
Documentation:
Description:
Create Date: 3 May 2011
Modified Date: 3 Feb 2015
Authors: mcdurdin
Related Files:
Dependencies:
Bugs:
Todo:
Notes:
History: 03 May 2011 - mcdurdin - I2890 - Record diagnostic data when encountering registry errors
03 Feb 2015 - mcdurdin - I4574 - V9.0 - If any files are read-only, they need the read-only flag removed on install
*)
unit KPInstallVisualKeyboard;
interface
uses
kpbase;
type
TKPInstallVisualKeyboard = class(TKPBase)
public
procedure Execute(FileName, KeyboardName: string);
end;
implementation
uses
Windows,
Classes,
SysUtils,
ErrorControlledRegistry,
RegistryKeys,
KeymanErrorCodes,
utilkeyman,
utildir,
VisualKeyboard,
Variants;
procedure TKPInstallVisualKeyboard.Execute(FileName, KeyboardName: string);
var
SDest: string;
FIsAdmin: Boolean;
begin
with TVisualKeyboard.Create do
try
LoadFromFile(FileName);
if KeyboardName = '' then
KeyboardName := Header.AssociatedKeyboard;
if KeyboardInstalled(KeyboardName, FIsAdmin) then
begin
with TRegistryErrorControlled.Create do // I2890
try
if FIsAdmin
then RootKey := HKEY_LOCAL_MACHINE
else RootKey := HKEY_CURRENT_USER;
if OpenKey(GetRegistryKeyboardInstallKey(KeyboardName), True) then
begin
if not ValueExists(SRegValue_KeymanFile) then Exit;
SDest := ExtractFilePath(ReadString(SRegValue_KeymanFile));
if ValueExists(SRegValue_VisualKeyboard) then
DeleteFileCleanAttr(SDest + ExtractFileName(ReadString(SRegValue_VisualKeyboard))); // I4574
WriteString(SRegValue_VisualKeyboard, SDest + ExtractFileName(FileName));
if not CopyFileCleanAttr(PChar(FileName), PChar(SDest + ExtractFileName(FileName)), False) then // I4574
begin
DeleteValue(SRegValue_VisualKeyboard);
ErrorFmt(KMN_E_VisualKeyboard_Install_CouldNotInstall, VarArrayOf([FileName]));
end;
end
else
ErrorFmt(KMN_E_VisualKeyboard_Install_CouldNotInstall, VarArrayOf([FileName]));
finally
Free;
end;
end
else
ErrorFmt(KMN_E_VisualKeyboard_Install_KeyboardNotInstalled, VarArrayOf([FileName, KeyboardName]));
finally
Free;
end;
Context.Control.AutoApplyKeyman;
end;
end.
|
{ Copyright (C) 1998-2011, written by Mike Shkolnik, Scalabium Software
E-Mail: mshkolnik@scalabium
WEB: http://www.scalabium.com
Const strings for localization
freeware SMComponent library
}
unit SMCnst;
interface
{Traditional Chinese strings}
const
strMessage = '列印...';
strSaveChanges = '你真的要在資料庫伺服器上儲存變更?';
strErrSaveChanges = '無法儲存資料,請檢查伺服器連接或驗證資訊.';
strDeleteWarning = '你真的要刪除資料表 %s?';
strEmptyWarning = '你真的要清空資料表 %s?';
const
PopUpCaption: array [0..24] of string =
('增加記錄',
'插入紀錄',
'編輯記錄',
'刪除記錄',
'-',
'列印 ...',
'匯出 ...',
'過濾 ...',
'搜尋 ...',
'-',
'儲存變更',
'取消變更',
'更新畫面',
'-',
'選取/不選取 記錄',
'選取 記錄',
'選取全部記錄',
'-',
'取消選取記錄',
'取消選取全部記錄',
'-',
'儲存欄位安排',
'取回欄位安排',
'-',
'設定...');
const //for TSMSetDBGridDialog
SgbTitle = '標題 ';
SgbData = ' 資料 ';
STitleCaption = ' 標題:';
STitleAlignment = '對齊:';
STitleColor = '背景:';
STitleFont = '字形:';
SWidth = '寬度:';
SWidthFix = '字元';
SAlignLeft = '左';
SAlignRight = '右';
SAlignCenter = '置中';
const //for TSMDBFilterDialog
strEqual = '相等';
strNonEqual = '不相等';
strNonMore = '不大於';
strNonLess = '不小於';
strLessThan = '少於';
strLargeThan = '大於';
strExist = '空白';
strNonExist = '非空白';
strIn = '於列表中';
strBetween = '之間';
strLike = '類似';
strOR = '或';
strAND = '且';
strField = '欄位';
strCondition = '條件';
strValue = '值';
strAddCondition = ' 定義附加條件:';
strSelection = ' 由下一個條件選擇記錄:';
strAddToList = '添加到列表';
strEditInList = '編輯列表';
strDeleteFromList = '從列表中刪除';
strTemplate = '過濾樣版對話框';
strFLoadFrom = '載入,由...';
strFSaveAs = '另存..';
strFDescription = '描述';
strFFileName = '檔名';
strFCreate = '建立: %s';
strFModify = '修改: %s';
strFProtect = '保護覆寫';
strFProtectErr = '檔案受到保護!';
const //for SMDBNavigator
SFirstRecord = '第一筆記錄';
SPriorRecord = '上一筆記錄';
SNextRecord = '下一筆記錄';
SLastRecord = '最後一筆記錄';
SInsertRecord = '插入記錄';
SCopyRecord = '複製記錄';
SDeleteRecord = '刪除記錄';
SEditRecord = '編輯記錄';
SFilterRecord = '過濾條件';
SFindRecord = '搜索記錄';
SPrintRecord = '列印記錄';
SExportRecord = '匯出記錄';
SImportRecord = '匯入記錄';
SPostEdit = '儲存變更';
SCancelEdit = '取消變更';
SRefreshRecord = '更新資料';
SChoice = '選擇記錄';
SClear = '清除選取記錄';
SDeleteRecordQuestion = '刪除記錄?';
SDeleteMultipleRecordsQuestion = '你真的要刪除選定的記錄?';
SRecordNotFound = '記錄未找到';
SFirstName = '第一';
SPriorName = '上一個';
SNextName = '下一個';
SLastName = '最後';
SInsertName = '插入';
SCopyName = '複製';
SDeleteName = '刪除';
SEditName = '編輯';
SFilterName = '過濾';
SFindName = '搜尋';
SPrintName = '列印';
SExportName = '匯出';
SImportName = '匯入';
SPostName = '儲存';
SCancelName = '取消';
SRefreshName = '更新';
SChoiceName = '選擇';
SClearName = '清除';
SBtnOk = '&確認';
SBtnCancel = '&取消';
SBtnLoad = '載入';
SBtnSave = '儲存';
SBtnCopy = '複製';
SBtnPaste = '貼上';
SBtnClear = '清除';
SRecNo = '記錄.';
SRecOf = ' 於 ';
const //for EditTyped
etValidNumber = '有效數字';
etValidInteger = '有效的整數';
etValidDateTime = '有效日期/時間';
etValidDate = '有效日期';
etValidTime = '有效時間';
etValid = '有效';
etIsNot = '是不是一個';
etOutOfRange = '數值 %s 超出範圍 %s..%s';
SApplyAll = '全部套用';
SNoDataToDisplay = '<沒有資料可以顯示>';
SPrevYear = '前一年';
SPrevMonth = '前一個月';
SNextMonth = '下一個月';
SNextYear = '下一年';
implementation
end.
|
unit Vigilante.Controller.Build.Impl;
interface
uses
System.SysUtils, Vigilante.Controller.Build, Vigilante.DataSet.Build,
Vigilante.Build.Model, Vigilante.View.URLDialog,
Vigilante.Controller.Base.Impl, Module.ValueObject.URL,
Module.DataSet.VigilanteBase, Vigilante.Controller.Mediator;
type
TBuildController = class(TControllerBase<IBuildModel>, IBuildController)
private
FDataSet: TBuildDataSet;
FMediator: IControllerMediator;
procedure SalvarDadosBuild;
procedure CarregarDadosDoBuild;
protected
function GetDataSet: TBuildDataSet;
procedure SetDataSet(const ADataSet: TBuildDataSet);
function GetDataSetInterno: TVigilanteDataSetBase<IBuildModel>; override;
public
constructor Create(const AMediator: IControllerMediator);
destructor Destroy; override;
procedure AdicionarOuAtualizar(const ABuild: IBuildModel);
procedure BuscarAtualizacoes; override;
procedure TransformarEmCompilacao(const AID: TGUID);
property DataSet: TBuildDataSet read GetDataSet;
end;
implementation
uses
System.Classes, System.Threading, Data.DB, ContainerDI,
Vigilante.Build.Observer.Impl, Vigilante.Build.Observer,
Vigilante.Build.Service, Vigilante.Module.GerenciadorDeArquivoDataSet;
constructor TBuildController.Create(const AMediator: IControllerMediator);
begin
FDataSet := TBuildDataSet.Create(nil);
CarregarDadosDoBuild;
FMediator := AMediator;
FMediator.AdicionarController(Self, tcBuild);
end;
destructor TBuildController.Destroy;
begin
SalvarDadosBuild;
FreeAndNil(FDataSet);
FMediator.RemoverController(tcBuild);
inherited;
end;
procedure TBuildController.CarregarDadosDoBuild;
var
_gerenciadorArquivosDataSet: IGerenciadorDeArquivoDataSet;
begin
_gerenciadorArquivosDataSet := CDI.Resolve<IGerenciadorDeArquivoDataSet>
([DataSet]);
if not _gerenciadorArquivosDataSet.CarregarArquivo(QualifiedClassName) then
DataSet.CreateDataSet;
end;
procedure TBuildController.SalvarDadosBuild;
var
_gerenciadorArquivosDataSet: IGerenciadorDeArquivoDataSet;
begin
_gerenciadorArquivosDataSet := CDI.Resolve<IGerenciadorDeArquivoDataSet>
([DataSet]);
_gerenciadorArquivosDataSet.SalvarArquivo(QualifiedClassName);
end;
procedure TBuildController.AdicionarOuAtualizar(const ABuild: IBuildModel);
begin
DataSet.Importar(ABuild);
end;
procedure TBuildController.BuscarAtualizacoes;
var
_service: IBuildService;
_dataTemp: TBuildDataSet;
_buildOriginal: IBuildModel;
_build: IBuildModel;
begin
inherited;
if DataSet.IsEmpty then
Exit;
if DataSet.State in dsEditModes then
Exit;
_dataTemp := TBuildDataSet.Create(nil);
try
_dataTemp.CloneCursor(DataSet);
_dataTemp.ApenasAtualizaveis();
_dataTemp.First;
while not _dataTemp.Eof do
begin
_service := CDI.Resolve<IBuildService>;
_buildOriginal := _dataTemp.ExportarRegistro;
_build := _service.AtualizarBuild(_buildOriginal);
if not Assigned(_build) then
Exit;
if not _buildOriginal.Equals(_build) then
_dataTemp.Importar(_build);
_dataTemp.Next;
end;
finally
FreeAndNil(_dataTemp);
end;
end;
function TBuildController.GetDataSet: TBuildDataSet;
begin
Result := FDataSet;
end;
function TBuildController.GetDataSetInterno: TVigilanteDataSetBase<IBuildModel>;
begin
Result := GetDataSet;
end;
procedure TBuildController.SetDataSet(const ADataSet: TBuildDataSet);
begin
FDataSet := ADataSet;
end;
procedure TBuildController.TransformarEmCompilacao(const AID: TGUID);
var
_urlBuild: string;
_numeroCompilacao: integer;
_urlCompilacao: string;
_url: IURL;
begin
if not DataSet.LocalizarPorID(AID) then
Exit;
_urlBuild := DataSet.URL;
_numeroCompilacao := DataSet.UltimoBuild;
_urlCompilacao := Format('%s/%d', [_urlBuild, _numeroCompilacao]);
_url := CDI.Resolve<IURL>([_urlCompilacao]);
FMediator.AdicionarURL(tcCompilacao, _url);
end;
end.
|
program cch;
(*************************************************************************
DESCRIPTION : Console demo for CRC/HASH
REQUIREMENTS : TP5-7, D1-D7/D9-D10/D12/D17-D18, FPC, VP
EXTERNAL DATA : ---
MEMORY USAGE : ---
DISPLAY MODUS : ---
REFERENCES : ---
Version Date Author Modification
------- -------- ------- ------------------------------------------
0.10 18.03.02 we D3 demo for DLL
0.20 06.05.03 we with units (no DLL), for TP5.5/6/7, D1-D6, FPC
0.30 12.09.03 we with Adler32, CRC64
0.40 05.10.03 we STD.INC, TP5.0
0.50 24.10.03 we speedups
0.60 30.11.03 we SHA384/512
0.62 02.01.04 we SHA224
0.63 11.04.04 we D7, BP7 WIN/DPMI
0.64 04.01.05 we recompiled to fix SHA512/384 bug
0.65 22.05.05 we $I-, ShareDenyNone for BIT32
0.70 22.05.05 we Options
0.71 02.12.05 we Bugfix: no confusing NOSHAxxx-defines
0.72 11.12.05 we Whirlpool
0.73 22.01.06 we New hash units
0.74 01.02.06 we RIPEMD-160
0.75 05.04.06 we CRC24
0.76 11.05.06 we Print "not found" for nonzero findfirst
0.77 21.01.07 we Bugfix Whirlpool
0.78 10.02.07 we Without filesize
0.79 21.02.07 we MD4, ED2K
0.80 24.02.07 we eDonkey AND eMule
0.81 30.09.07 we Bug fix SHA512/384 for file sizes above 512MB
0.81.1 03.10.07 we Run self tests with -t
0.81.2 15.11.08 we BTypes, str255, BString
0.82 21.07.09 we D12 fixes
0.83 11.03.12 we SHA512/224, SHA512/256
0.84 26.12.12 we D17 and 64-bit adjustments
0.85 12.08.15 we SHA3 algorithms
0.86 18.05.17 we Blake2s
0.87 03.11.17 we Blake2b
0.88 24.11.17 we Blake2b for VER5X
**************************************************************************)
(*-------------------------------------------------------------------------
(C) Copyright 2002-2017 Wolfgang Ehrhardt
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from
the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software in
a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
----------------------------------------------------------------------------*)
{$i STD.INC}
{$ifdef BIT16}
{$ifdef DPMI}
{$M $1000}
{$else}
{$M $4000,0,655360}
{$endif}
{$endif}
{$I-,V-}
{$ifndef FPC}
{$B-,N-}
{$endif}
{$undef UseDOS}
{Check if we can use DOS unit}
{$ifdef MSDOS}
{$define UseDOS} {includes FPC Go32V2!}
{$endif}
{$ifdef DPMI}
{$define UseDOS}
{$endif}
{$ifdef VirtualPascal}
{$define UseDOS}
{$endif}
{$ifndef UseDOS}
{$ifdef VER70}
{BP7Win}
{$define UseWinDOS}
{$x+}
{$endif}
{$ifdef VER15}
{$define UseWinDOS}
{$x+}
{$endif}
{$endif}
{$ifdef APPCONS}
{$apptype console}
{$endif}
uses
{$ifdef WINCRT}
WinCRT,
{$endif}
{$ifdef UseWinDOS}
WinDOS, Strings, {BP7Win}
{$else}
{$ifdef UseDOS}
DOS,
{$else}
{$ifdef UNIT_SCOPE}
System.SysUtils,
{$else}
SysUtils,
{$endif}
{$endif}
{$endif}
CRC16, CRC24, CRC32, Adler32, CRC64, hash, MD5, RMD160,
SHA1, SHA256, SHA224, SHA384, SHA512, SHA5_224, SHA5_256,
SHA3_224, SHA3_256, SHA3_384, SHA3_512,
Whirl512,MD4,ED2K,Blaks224, Blaks256, Blakb384, Blakb512,
BTypes, mem_util;
const
CCH_Version = '0.88';
{$ifdef J_OPT}
{$J+}
{$endif}
const
Base64: boolean = false;
LSB1 : boolean = false;
{$ifdef UseWinDOS}
var
buf: array[1..$6800] of byte; {BP7Win: data segment too large!!}
{$else}
{$ifdef VER80}
var
buf: array[1..$4800] of byte; {D1: data segment too large!!}
{$else}
var
buf: array[1..$A000] of byte;
{$endif}
{$endif}
{---------------------------------------------------------------------------}
procedure Process1File({$ifdef CONST} const {$endif} FName: str255);
{-Process a single file}
var
{$ifdef MSDOS}
n: word;
{$else}
{$ifdef BIT16}
n: word;
{$else}
n: longint;
{$endif}
{$endif}
CRC16: word;
CRC24: longint; pgpsig: TPGPDigest;
CRC32: longint;
Adler: longint;
CRC64: TCRC64;
RMD160Context : THashContext; RMD160Digest: TRMD160Digest;
SHA1Context : THashContext; SHA1Digest: TSHA1Digest;
SHA256Context : THashContext; SHA256Digest: TSHA256Digest;
ED2KContext : TED2KContext; ED2KRes: TED2KResult;
MD4Context : THashContext; MD4Digest: TMD4Digest;
MD5Context : THashContext; MD5Digest: TMD5Digest;
SHA224Context : THashContext; SHA224Digest: TSHA224Digest;
SHA384Context : THashContext; SHA384Digest: TSHA384Digest;
SHA512Context : THashContext; SHA512Digest: TSHA512Digest;
WhirlContext : THashContext; WhirlDigest: TWhirlDigest;
SHA5_224Context: THashContext; SHA5_224Digest: TSHA5_224Digest;
SHA5_256Context: THashContext; SHA5_256Digest: TSHA5_256Digest;
SHA3_224Context: THashContext; SHA3_224Digest: TSHA3_224Digest;
SHA3_256Context: THashContext; SHA3_256Digest: TSHA3_256Digest;
SHA3_384Context: THashContext; SHA3_384Digest: TSHA3_384Digest;
SHA3_512Context: THashContext; SHA3_512Digest: TSHA3_512Digest;
Blaks_224Context: THashContext; Blaks_224Digest: TBlake2S_224Digest;
Blaks_256Context: THashContext; Blaks_256Digest: TBlake2S_256Digest;
Blakb_384Context: THashContext; Blakb_384Digest: TBlake2B_384Digest;
Blakb_512Context: THashContext; Blakb_512Digest: TBlake2B_512Digest;
f: file;
{----------------------------------------------------------------------}
function RB(A: longint): longint;
{-rotate byte of longint}
begin
RB := (A shr 24) or ((A shr 8) and $FF00) or ((A shl 8) and $FF0000) or (A shl 24);
end;
{----------------------------------------------------------------------}
function OutStr(psrc: pointer; L: integer): BString;
{-Format string as hex or base64}
begin
if Base64 then OutStr := Base64Str(psrc, L)
else OutStr := HexStr(psrc, L)
end;
begin
{$ifdef bit32}
{ShareDenyNone to avoid error if redirected output is processed}
FileMode := $40;
{$else}
FileMode := $0;
{$endif}
writeln(Fname);
system.assign(f,{$ifdef D12Plus} string {$endif}(FName));
system.reset(f,1);
if IOresult<>0 then begin
writeln('*** could not be opened');
exit;
end;
RMD160Init(RMD160Context);
SHA1Init(SHA1Context);
SHA256Init(SHA256Context);
SHA224Init(SHA224Context);
SHA384Init(SHA384Context);
SHA512Init(SHA512Context);
SHA5_224Init(SHA5_224Context);
SHA5_256Init(SHA5_256Context);
SHA3_224Init(SHA3_224Context);
SHA3_256Init(SHA3_256Context);
SHA3_384Init(SHA3_384Context);
SHA3_512Init(SHA3_512Context);
Blaks224Init(Blaks_224Context);
Blaks256Init(Blaks_256Context);
Blakb384Init(Blakb_384Context);
Blakb512Init(Blakb_512Context);
Whirl_Init(WhirlContext);
ED2K_Init(ED2KContext);
MD4Init(MD4Context);
MD5Init(MD5Context);
CRC16Init(CRC16);
CRC24Init(CRC24);
CRC32Init(CRC32);
Adler32Init(adler);
CRC64Init(CRC64);
repeat
blockread(f,buf,sizeof(buf),n);
if IOResult<>0 then begin
writeln('*** read error');
{$ifdef CONST}
break;
{$else}
{Trick V5.5/6.0, no break for VER < 7}
n := 0;
{$endif}
end;
if n<>0 then begin
RMD160Update(RMD160Context,@buf,n);
SHA1Update(SHA1Context,@buf,n);
ED2K_Update(ED2KContext,@buf,n);
MD4Update(MD4Context,@buf,n);
MD5Update(MD5Context,@buf,n);
Adler32Update(adler,@buf,n);
CRC16Update(CRC16,@buf,n);
CRC24Update(CRC24,@buf,n);
CRC32Update(CRC32,@buf,n);
CRC64Update(CRC64,@buf,n);
SHA224Update(SHA224Context,@buf,n);
SHA256Update(SHA256Context,@buf,n);
SHA384Update(SHA384Context,@buf,n);
SHA512Update(SHA512Context,@buf,n);
SHA5_224Update(SHA5_224Context,@buf,n);
SHA5_256Update(SHA5_256Context,@buf,n);
Whirl_Update(WhirlContext,@buf,n);
SHA3_224Update(SHA3_224Context,@buf,n);
SHA3_256Update(SHA3_256Context,@buf,n);
SHA3_384Update(SHA3_384Context,@buf,n);
SHA3_512Update(SHA3_512Context,@buf,n);
Blaks224Update(Blaks_224Context,@buf,n);
Blaks256Update(Blaks_256Context,@buf,n);
Blakb384Update(Blakb_384Context,@buf,n);
Blakb512Update(Blakb_512Context,@buf,n);
end;
until n<>sizeof(buf);
system.close(f);
n := IOResult;
RMD160Final(RMD160Context,RMD160Digest);
SHA1Final(SHA1Context,SHA1Digest);
ED2K_Final(ED2KContext,ED2KRes);
MD4Final(MD4Context,MD4Digest);
MD5Final(MD5Context,MD5Digest);
CRC16Final(CRC16);
CRC24Final(CRC24);
CRC32Final(CRC32);
Adler32Final(adler);
CRC64Final(CRC64);
SHA224Final(SHA224Context,SHA224Digest);
SHA256Final(SHA256Context,SHA256Digest);
SHA384Final(SHA384Context,SHA384Digest);
SHA512Final(SHA512Context,SHA512Digest);
SHA5_224Final(SHA5_224Context,SHA5_224Digest);
SHA5_256Final(SHA5_256Context,SHA5_256Digest);
Whirl_Final(WhirlContext,WhirlDigest);
SHA3_224Final(SHA3_224Context,SHA3_224Digest);
SHA3_256Final(SHA3_256Context,SHA3_256Digest);
SHA3_384Final(SHA3_384Context,SHA3_384Digest);
SHA3_512Final(SHA3_512Context,SHA3_512Digest);
Blaks224Final(Blaks_224Context,Blaks_224Digest);
Blaks256Final(Blaks_256Context,Blaks_256Digest);
Blakb384Final(Blakb_384Context,Blakb_384Digest);
Blakb512Final(Blakb_512Context,Blakb_512Digest);
if (not LSB1) and (not Base64) then begin
{swap bytes: display shall look like word / longint}
{but HexStr constructs LSB first}
CRC16 := swap(CRC16);
CRC32 := RB(CRC32);
Adler := RB(Adler);
end;
Long2PGP(CRC24, pgpsig);
writeln(' CRC16: '+OutStr(@CRC16, sizeof(CRC16)));
{special case 3 byte CRC24 use CRC24 variable or pgpsig}
if LSB1 then writeln(' CRC24: '+OutStr(@CRC24, 3))
else writeln(' CRC24: '+OutStr(@pgpsig, 3));
writeln(' CRC32: '+OutStr(@CRC32, sizeof(CRC32)));
writeln(' Adler32: '+OutStr(@adler, sizeof(adler)));
writeln(' CRC64: '+OutStr(@CRC64, sizeof(CRC64)));
writeln(' eDonkey: '+OutStr(@ED2KRes.eDonkey, sizeof(ED2KRes.eDonkey)));
if ED2KRes.differ then begin
writeln(' eMule: '+OutStr(@ED2KRes.eMule, sizeof(ED2KRes.eMule)));
end;
writeln(' MD4: '+OutStr(@MD4Digest, sizeof(MD4Digest)));
writeln(' MD5: '+OutStr(@MD5Digest, sizeof(MD5Digest)));
writeln(' RIPEMD160: '+OutStr(@RMD160Digest, sizeof(RMD160Digest)));
writeln(' SHA1: '+OutStr(@SHA1Digest, sizeof(SHA1Digest)));
writeln(' SHA224: '+OutStr(@SHA224Digest, sizeof(SHA224Digest)));
writeln(' SHA256: '+OutStr(@SHA256Digest, sizeof(SHA256Digest)));
writeln(' SHA384: '+OutStr(@SHA384Digest, sizeof(SHA384Digest)));
writeln(' SHA512: '+OutStr(@SHA512Digest, sizeof(SHA512Digest)));
writeln(' SHA512/224: '+OutStr(@SHA5_224Digest,sizeof(SHA5_224Digest)));
writeln(' SHA512/256: '+OutStr(@SHA5_256Digest,sizeof(SHA5_256Digest)));
writeln(' Whirlpool: '+OutStr(@WhirlDigest, sizeof(WhirlDigest)));
writeln(' SHA3-224: '+OutStr(@SHA3_224Digest, sizeof(SHA3_224Digest)));
writeln(' SHA3-256: '+OutStr(@SHA3_256Digest, sizeof(SHA3_256Digest)));
writeln(' SHA3-384: '+OutStr(@SHA3_384Digest, sizeof(SHA3_384Digest)));
writeln(' SHA3-512: '+OutStr(@SHA3_512Digest, sizeof(SHA3_512Digest)));
writeln('Blake2s-224: '+OutStr(@Blaks_224Digest, sizeof(Blaks_224Digest)));
writeln('Blake2s-256: '+OutStr(@Blaks_256Digest, sizeof(Blaks_256Digest)));
writeln('Blake2b-384: '+OutStr(@Blakb_384Digest, sizeof(Blakb_384Digest)));
writeln('Blake2b-512: '+OutStr(@Blakb_512Digest, sizeof(Blakb_512Digest)));
writeln;
end;
{$ifdef UseWinDOS}
{---------------------------------------------------------------------------}
procedure ProcessFile({$ifdef CONST} const {$endif} s: str255);
{-Process one cmd line paramater, wildcards allowed}
var
SR: TSearchRec;
Path: array[0..sizeof(str255)+1] of Char8;
base: array[0..fsDirectory] of Char8;
Name: array[0..fsFileName] of Char8;
Ext: array[0..fsExtension] of Char8;
begin
StrPCopy(Path,s);
FileSplit(Path,base,name,ext);
FindFirst(Path, faAnyFile, SR);
if DosError<>0 then writeln('*** not found: ',s);
while DosError=0 do begin
if SR.Attr and (faVolumeID or faDirectory) = 0 then begin
Process1File(StrPas(Base)+StrPas(SR.Name));
end;
FindNext(SR);
end;
end;
{$else}
{$ifdef UseDOS}
{---------------------------------------------------------------------------}
procedure ProcessFile({$ifdef CONST} const {$endif} s: str255);
{-Process one cmd line parameter, wildcards allowed}
var
SR: SearchRec;
n: namestr;
e: extstr;
base: str255;
begin
FSplit(s,base,n,e);
FindFirst(s, AnyFile, SR);
if DosError<>0 then writeln('*** not found: ',s);
while DosError=0 do begin
if SR.Attr and (VolumeID or Directory) = 0 then begin
Process1File(Base+SR.Name);
end;
FindNext(SR);
end;
end;
{$else}
{$ifdef D12Plus}
{---------------------------------------------------------------------------}
procedure ProcessFile(const s: string);
{-Process one cmd line parameter, wildcards allowed}
var
SR: TSearchRec;
FR: integer;
base: string;
begin
Base := ExtractFilePath(s);
FR := FindFirst(s, faAnyFile, SR);
if FR<>0 then writeln('*** not found: ',s);
while FR=0 do begin
if SR.Attr and (faVolumeID or faDirectory) = 0 then begin
Process1File(str255(Base+SR.Name));
end;
FR := FindNext(SR);
end;
FindClose(SR);
end;
{$else}
{---------------------------------------------------------------------------}
procedure ProcessFile(const s: str255);
{-Process one cmd line parameter, wildcards allowed}
var
SR: TSearchRec;
FR: integer;
base: str255;
begin
Base := ExtractFilePath(s);
FR := FindFirst(s, faAnyFile, SR);
if FR<>0 then writeln('*** not found: ',s);
while FR=0 do begin
{$ifdef FPC}
{suppress warnings for faVolumeID}
{$WARN SYMBOL_DEPRECATED OFF}
{$WARN SYMBOL_PLATFORM OFF}
{$endif}
if SR.Attr and (faVolumeID or faDirectory) = 0 then begin
Process1File(Base+SR.Name);
end;
FR := FindNext(SR);
end;
FindClose(SR);
end;
{$endif}
{$endif}
{$endif}
{---------------------------------------------------------------------------}
procedure Selftests;
{-Self test of all check sum algorithms}
procedure report(aname: str255; passed: boolean);
begin
writeln(' ',aname, ' self test passed: ',passed);
end;
begin
report('CRC16 ', CRC16SelfTest );
report('CRC24 ', CRC24SelfTest );
report('CRC32 ', CRC32SelfTest );
report('Adler32 ', Adler32SelfTest );
report('CRC64 ', CRC64SelfTest );
report('eDonkey ', ED2K_SelfTest );
report('MD4 ', MD4SelfTest );
report('MD5 ', MD5SelfTest );
report('RIPEMD160 ', RMD160SelfTest );
report('SHA1 ', SHA1SelfTest );
report('SHA224 ', SHA224SelfTest );
report('SHA256 ', SHA256SelfTest );
report('SHA384 ', SHA384SelfTest );
report('SHA512 ', SHA512SelfTest );
report('SHA512/224 ', SHA5_224SelfTest);
report('SHA512/256 ', SHA5_256SelfTest);
report('Whirlpool ', Whirl_SelfTest );
report('SHA3-224 ', SHA3_224SelfTest);
report('SHA3-256 ', SHA3_256SelfTest);
report('SHA3-384 ', SHA3_384SelfTest);
report('SHA3-512 ', SHA3_512SelfTest);
report('Blake2s-224', Blaks224SelfTest);
report('Blake2s-256', Blaks256SelfTest);
report('Blake2b-384', Blakb384SelfTest);
report('Blake2b-512', Blakb512SelfTest);
end;
{---------------------------------------------------------------------------}
procedure usage;
begin
writeln('Usage: CCH [arg1] ... [argN]');
writeln(' args may be file specs (wildcards allowed) or options');
writeln(' -b: display results in Base64');
writeln(' -h: display in hex (default)');
writeln(' -u: display in HEX');
writeln(' -l: display CRC16/24/32,Adler LSB first');
writeln(' -t: run self tests of algorithms');
writeln(' -m: display CRC16/24/32,Adler MSB first (default)');
writeln(' -?: this help');
halt;
end;
{---------------------------------------------------------------------------}
var
i,k,n: integer;
{$ifdef D12Plus}
s: string;
{$else}
s: string[2];
{$endif}
begin
writeln('CCH V', CCH_Version, ' - Calculate CRC/Hash (c) 2002-2017 W.Ehrhardt');
n := 0;
for i:=1 to Paramcount do begin
s := Paramstr(i);
for k:=1 to length(s) do s[k] := upcase(s[k]);
if s='-B' then Base64 := true
else if s='-T' then begin
Selftests;
inc(n);
end
else if s='-H'then begin
Base64 := false;
HexUpper := false;
end
else if s='-U'then begin
Base64 := false;
HexUpper := true;
end
else if s='-L'then LSB1 := true
else if s='-M'then LSB1 := false
else if s[1]='-'then usage
else begin
ProcessFile(paramstr(i));
inc(n);
end;
end;
if n=0 then usage;
end.
|
{-----------------------------------------------------------------------------
Unit Name: DelphiSettingRegistry
Author: Erwien Saputra
This software and source code are distributed on an as is basis, without
warranty of any kind, either express or implied.
This file can be redistributed, modified if you keep this header.
Copyright © Erwien Saputra 2005 All Rights Reserved.
Purpose: Encapsulates all interaction with the Registry.
History:
01/19/05 - Initial creation.
02/20/05 - Fixed a bug when a key was missing on one treeview and exist at
another, and that node is expanded, the treeview with missing key
will expand the root node.
-----------------------------------------------------------------------------}
unit DelphiSettingRegistry;
interface
uses
Classes, Registry, SysUtils, IntfObserver, Subject;
type
IDelphiSettingRegistry = interface;
TOnNodeChanged = procedure (const Sender : IDelphiSettingRegistry;
const CurrentPath : string;
const RefreshCurrentPath : boolean) of object;
TOnValueNamesChanged = procedure (const Sender : IDelphiSettingRegistry;
const CurrentPath : string;
const Names : TStrings);
TStringArray = array of string;
//This interface will provide all necessary functionalities to open a setting.
//Setting path is the full registry key to the Delphi Custom Setting.
//This interface provides the ability to have selection, change the selection,
//add a new key, delete existing key, and get children keys of a sub-key.
IDelphiSettingRegistry = interface
['{B910A6AD-9BEB-4540-A17B-4D099E7B7AE9}']
function GetSettingPath : string;
function GetCurrentPath : string;
function GetParent (APath : string) : string;
function SetCurrentPath (const APath : string) : boolean;
procedure GetChild (const APath : string; out StringArray : TStringArray);
procedure OpenSetting (const SettingPath : string);
function DeleteCurrentKey : string;
procedure AddKey (const RelativePath : string);
property SettingPath : string read GetSettingPath;
property CurrentPath : string read GetcurrentPath;
end;
TDelphiSettingRegistry = class (TInterfacedObject, IDelphiSettingRegistry,
ISubject)
private
FSettingPath : string;
FReg : TRegistry;
FCurrentIndex : integer;
FValueNames : TStringList;
FSubject : ISubject;
protected
function GetSettingPath : string;
function GetCurrentPath : string;
function SetCurrentPath (const APath : string) : boolean;
function GetParent (APath : string) : string;
procedure GetChild (const APath : string; out StringArray : TStringArray);
procedure OpenSetting (const SettingPath : string);
function DeleteCurrentKey : string;
procedure AddKey (const RelativePath : string);
property Subject : ISubject read FSubject implements ISubject;
public
constructor Create (const APath : string = '');
destructor Destroy; override;
end;
function GetLastDelimiterIndex (const AValue : string): integer; forward;
function GetFirstDelimiterIndex (const AValue : string): integer; forward;
implementation
uses
Contnrs;
const
NO_CURRENT = -2;
ROOT = -1;
DELIMITER = '\';
function GetLastDelimiterIndex (const AValue : string): integer;
begin
Result := LastDelimiter (DELIMITER, AValue);
if Result > 1 then
if AValue [Result - 1] = DELIMITER then
Result := GetLastDelimiterIndex (Copy (AValue, 1, Result - 2));
end;
function GetFirstDelimiterIndex (const AValue : string): integer;
var
ValueLength : integer;
begin
ValueLength := Length (AValue);
Result := Pos (DELIMITER, AValue);
if Result < ValueLength then
if AValue[Result + 1] = DELIMITER then
Result := GetFirstDelimiterIndex (
Copy (AValue, Result + 1, ValueLength - (Result + 1)));
end;
{ TDelphiSettingKeys }
constructor TDelphiSettingRegistry.Create(const APath: string = '');
begin
inherited Create;
FReg := TRegistry.Create;
FValueNames := TStringList.Create;
FCurrentIndex := NO_CURRENT;
FSubject := TSubject.Create (self);
if SameText (Trim (APath), EmptyStr) = false then
OpenSetting (APath);
end;
destructor TDelphiSettingRegistry.Destroy;
begin
FReg.Free;
FValueNames.Free;
FSubject.Enabled := false;
FSubject := nil;
inherited;
end;
function TDelphiSettingRegistry.GetSettingPath: string;
begin
Result := FSettingPath;
end;
procedure TDelphiSettingRegistry.OpenSetting(const SettingPath: string);
begin
FSettingPath := ExcludeTrailingBackslash (SettingPath);
//It is important to include backslash at the beginning. The path is always a
//full path under HKCU. Without backslash in the beginning, Regedit.OpenKey
//may try to open a sub key under the current key.
if SameText (FSettingPath[1], '\') = false then
FSettingPath := '\' + FSettingPath;
if FReg.OpenKey(FSettingPath, false) = false then
raise Exception.Create (FSettingPath + ' does not exist.');
FSubject.Notify;
end;
//Return the current path, start it with a backslash.
function TDelphiSettingRegistry.GetCurrentPath: string;
begin
Result := '\' + IncludeTrailingBackslash (FReg.CurrentPath);
end;
//Open the current path. Any update to the selection will notify the subscriber
//of this class.
function TDelphiSettingRegistry.SetCurrentPath (const APath: string) : boolean;
begin
Result := FReg.OpenKey (APath, false);
if (Result = true) then
FSubject.Notify;
end;
//Add a key. Relative Path is the path relative to the SettingPath. This method
//does not add any values or sub-keys.
procedure TDelphiSettingRegistry.AddKey(const RelativePath: string);
var
CorrectedPath : string;
begin
CorrectedPath := FSettingPath + '\' + ExcludeTrailingBackslash (RelativePath);
if FReg.KeyExists (CorrectedPath) = true then
Exit;
if FReg.CreateKey (CorrectedPath) = false then
raise Exception.Create('Cannot Create ' + CorrectedPath);
FReg.OpenKey (CorrectedPath, false);
//Notify all observer.
FSubject.Notify;
end;
//Delete the current key. After deleting a key, this method does not broadcast
//messages to the subscriber. When a key is deleted, the selection is changed
//to the parent path of the deleted node (probably I should change it to nil).
//If this action notifies all subscribers it will move all TreeView selection.
//It looked weird.
function TDelphiSettingRegistry.DeleteCurrentKey : string;
var
ParentPath : string;
begin
if FReg.DeleteKey (GetCurrentPath) = false then
raise Exception.Create ('Failed to delete ' + GetCurrentPath);
ParentPath := self.GetParent (GetCurrentPath);
Result := self.GetCurrentPath;
SetCurrentPath (ParentPath);
end;
procedure TDelphiSettingRegistry.GetChild(const APath: string;
out StringArray: TStringArray);
var
CurrentPath : string;
List : TStringList;
Loop : integer;
begin
CurrentPath := self.GetCurrentPath;
List := TStringList.Create;
try
if FReg.OpenKey (APath, false) = false then
raise Exception.Create ('Error opening ' + APath);
FReg.GetKeyNames(List);
SetLength (StringArray, List.Count);
for Loop := 0 to List.Count - 1 do
StringArray[Loop] := List[Loop];
finally
//Assign the CurrentPath directly to the FReg to prevent OnNodeChanged from
//firing.
FReg.OpenKey (CurrentPath, false);
List.Free;
end;
end;
function TDelphiSettingRegistry.GetParent(APath: string): string;
begin
APath := ExcludeTrailingBackslash (APath);
Result := Copy (APath, 1, GetLastDelimiterIndex (APath) - 1);
end;
end.
|
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 1024,0,0}
{
by Behdad Esfahbod
Algorithmic Problems Book
April '2000
Problem 162 Dfs Method O(N2)
}
program
SerialParallelCircuit;
const
MaxN = 100 + 1;
MaxE = 3 * MaxN div 2 + 1;
var
N, E, S, T : Integer;
G : array [1 .. MaxN, 1 .. 3] of Integer;
R : array [1 .. MaxN, 1 .. MaxN] of Real;
D : array [1 .. MaxN] of Integer;
Stack : array [1 .. MaxE] of record
Sr, Tr, Md, V1, V2, V3, V4 : Integer;
end;
StNum : Integer;
IsTerm : array [1 .. MaxN] of Boolean;
Mark : array [1 .. MaxN] of Integer;
DfsN : Integer;
I, J, K, P, Q : Integer;
procedure NoSolution;
begin
Assign(Output, 'output.txt');
Rewrite(Output);
Writeln('Is not serial-parallel');
Close(Output);
Halt;
end;
procedure WriteAnswer;
begin
Assign(Output, 'output.txt');
Rewrite(Output);
Writeln('Is serial-parallel');
Writeln(R[S, T] : 0 : 2);
Close(Output);
Halt;
end;
procedure ReadInput;
begin
Assign(Input, 'input.txt');
Reset(Input);
Readln(N, E, S, T);
for I := 1 to E do
begin
Readln(P, Q);
Inc(D[P]);
Inc(D[Q]);
if (D[P] > 3) or (D[Q] > 3) then
NoSolution;
G[P, D[P]] := Q;
G[Q, D[Q]] := P;
end;
for I := 1 to N do
if (D[I] = 1) and not (I in [S, T]) then
NoSolution;
if (D[S] = 3) or (D[T] = 3) then
NoSolution;
Close(Input);
end;
function Min (A, B : Integer) : Integer;
begin
if A <= B then Min := A else Min := B;
end;
var
CE1, CE2, NTerm : Integer; {Cut Edge Vertices}
function Dfs (V, P : Integer) : Integer;
var
I, J, K : Integer;
begin
Inc(DfsN);
Mark[V] := DfsN;
K := Mark[V];
for I := 1 to D[V] do
if Mark[G[V, I]] = 0 then
begin
if IsTerm[G[V, I]] then
NTerm := G[V, I];
J := Dfs(G[V, I], V);
K := Min(K, J);
if J > Mark[V] then
begin
CE1 := V;
CE2 := G[V, I];
end;
end
else
if G[V, I] <> P then
K := Min(K, Mark[G[V, I]]);
Dfs := K;
end;
procedure Delete (I, J : Integer);
var
K : Integer;
begin
for K := 1 to D[I] - 1 do
if G[I, K] = J then
begin
G[I, K] := G[I, D[I]];
Break;
end;
Dec(D[I]);
end;
var
Flag : Boolean;
procedure SetTerm (I : Integer);
begin
if IsTerm[I] then
NoSolution;
IsTerm[I] := True;
end;
procedure CalcResistants;
var
J, K : Real;
begin
for I := StNum downto 1 do
with Stack[I] do
begin
case Md of
0: R[Sr, Tr] := 1;
1: R[Sr, Tr] := 1 + R[V1, Tr];
2: R[Sr, Tr] := R[Sr, V1] + R[V2, Tr];
4:
begin
J := R[V1, V3] + R[V1, V4];
K := R[V2, V3] + R[V2, V4];
R[Sr, Tr] := J * K / (J + K);
end;
end;
R[Tr, Sr] := R[Sr, Tr];
end;
end;
procedure Solve;
begin
SetTerm(S);
SetTerm(T);
DfsN := 0;
Dfs(S, 0);
if Mark[T] = 0 then
NoSolution;
repeat
Flag := True;
for I := 1 to N do
if IsTerm[I] then
if D[I] > 1 then
begin
CE1 := 0;
DfsN := 0;
FillChar(Mark, SizeOf(Mark), 0);
Dfs(I, 0);
if CE1 = 0 then
begin
Inc(StNum);
with Stack[StNum] do
begin
Sr := I;
Tr := NTerm;
Md := 4;
V1 := G[I, 1];
V2 := G[I, 2];
V3 := G[NTerm, 1];
V4 := G[NTerm, 2];
end;
SetTerm(G[I, 1]);
SetTerm(G[I, 2]);
SetTerm(G[NTerm, 1]);
SetTerm(G[NTerm, 2]);
Delete(G[I, 1], I);
Delete(G[I, 2], I);
Delete(G[NTerm, 1], NTerm);
Delete(G[NTerm, 2], NTerm);
Dec(E, 4);
IsTerm[I] := False;
IsTerm[NTerm] := False;
Flag := False;
end
else
begin
Inc(StNum);
with Stack[StNum] do
begin
Sr := I;
Tr := NTerm;
Md := 2;
V1 := CE1;
V2 := CE2;
end;
SetTerm(CE1);
SetTerm(CE2);
Delete(CE1, CE2);
Delete(CE2, CE1);
Flag := False;
Dec(E);
end;
end
else
begin
Inc(StNum);
DfsN := 0;
FillChar(Mark, SizeOf(Mark), 0);
Dfs(I, 0);
with Stack[StNum] do
begin
Sr := I;
Tr := NTerm;
Md := 0;
end;
if IsTerm[G[I, 1]] xor (D[G[I, 1]] = 1) then
NoSolution;
IsTerm[I] := False;
IsTerm[G[I, 1]] := False;
Delete(G[I, 1], I);
Delete(I, G[I, 1]);
Dec(E);
if D[G[I, 1]] > 1 then
NoSolution;
if D[G[I, 1]] > 0 then
begin
if IsTerm[G[G[I, 1], 1]] then
NoSolution;
with Stack[StNum] do
begin
Md := 1;
V1 := G[G[I, 1], 1];
end;
Delete(G[I, 1], G[G[I, 1], 1]);
Delete(G[G[I, 1], 1], G[I, 1]);
if D[G[G[I, 1], 1]] = 0 then
NoSolution;
SetTerm(G[G[I, 1], 1]);
Dec(E);
end;
end;
until Flag;
if E <> 0 then
NoSolution;
CalcResistants;
end;
begin
ReadInput;
Solve;
WriteAnswer;
end.
|
unit SendKeys;
//SendKeys
//--------
//
// Easy Method :
//
// SendKeysTo(Window Title text, key codes)
//
// This sets focus to window with specified window text and sends
// it given key codes.
//
// e.g. to close Delphi :
//
// SendKeysTo('Delphi 2.0',SK_ALT_DN + 'F' + 'x' + SK_ALT_UP);
//
// Copyright 1997, 1998 MJT Net Ltd
// info@mjtnet.com
// www.mjtnet.com
//
// This source code is given as is. The author is not responsible for any
// possible damage done due to the use of this code. The component can
// be freely used and compiled in any application. The source code
// remains the property of the author and may not be distributed, sold,
// quoted or otherwise, without written consent from MJT Net Ltd.
interface
uses
Windows, Messages, Classes, Forms, SysUtils, Dialogs;
const
SK_BKSP = #8;
SK_TAB = #9;
SK_ENTER = #13;
SK_ESC = #27;
SK_F1 = #228;
SK_F2 = #229;
SK_F3 = #230;
SK_F4 = #231;
SK_F5 = #232;
SK_F6 = #233;
SK_F7 = #234;
SK_F8 = #235;
SK_F9 = #236;
SK_F10 = #237;
SK_F11 = #238;
SK_F12 = #239;
SK_HOME = #240;
SK_END = #241;
SK_UP = #242;
SK_DOWN = #243;
SK_LEFT = #244;
SK_RIGHT = #245;
SK_PGUP = #246;
SK_PGDN = #247;
SK_INS = #248;
SK_DEL = #249;
SK_SHIFT_DN = #250;
SK_SHIFT_UP = #251;
SK_CTRL_DN = #252;
SK_CTRL_UP = #253;
SK_ALT_DN = #254;
SK_ALT_UP = #255;
type
TSendKeys = class(TComponent)
private
{ Private declarations }
protected
{ Protected declarations }
public
{ Public declarations }
//constructor Create(AOwner: TComponent);override;
function HandleFromTitle(const titletext: string): hWnd;
procedure SendKeys(const text: String);
procedure MakeWindowActive(whandle: hWnd);
procedure SendKeysTo(Titletext:string; const text :string);
published
{ Published declarations }
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Samples', [TSendKeys]);
end;
//Create
//constructor TSendKeys.Create(aOwner: TComponent);
//begin
// inherited Create(aOwner);
// MessageDlg('SendKeys is Shareware, Please see the file registration.txt for registration details.',mtinformation,[mbok],0);
//end;
//HandleFromTitle
//---------------
function TSendKeys.HandleFromTitle(const titletext: string): hWnd;
var
strbuf: Array[0..255] of Char;
begin
result := FindWindow(PChar(0),StrPCopy(strbuf,titletext));
end;
//MakeWindowActive
//----------------
procedure TSendKeys.MakeWindowActive(whandle: hWnd);
begin
if IsIconic(whandle) then
ShowWindow(whandle,SW_RESTORE)
else
SetForegroundwindow(whandle);
end;
//SendKeys
//--------
procedure TSendKeys.SendKeys(const text: String);
var
i: Integer;
shift: Boolean;
vk,scancode: Word;
ch: Char;
c,s: Byte;
const
vk_keys: Array[0..9] of Byte =
(VK_HOME,VK_END,VK_UP,VK_DOWN,VK_LEFT,
VK_RIGHT,VK_PRIOR,VK_NEXT,VK_INSERT,
VK_DELETE);
vk_shft: Array[0..2] of Byte =
(VK_SHIFT,VK_CONTROL,VK_MENU);
flags: Array[false..true] of Integer =
(KEYEVENTF_KEYUP, 0);
begin
shift := false;
for i := 1 to Length(text) do
begin
ch := text[i];
if ch >= #250 then
begin
s := Ord(ch) - 250;
shift := not Odd(s);
c := vk_shft[s shr 1];
scancode := MapVirtualKey(c,0);
Keybd_Event(c,scancode,flags[shift],0);
end else
begin
vk := 0;
if ch >= #240 then
c := vk_keys[Ord(ch) - 240]
else if ch >= #228 then
c := Ord(ch) - 116
else if ch < #32 then
c := Ord(ch)
else
begin
vk := VkKeyScan(ch);
c := LoByte(vk);
end;
scancode := MapVirtualKey(c,0);
//if not shift and (Hi(vk) > 0) then
//Keybd_Event(VK_SHIFT,$2A,0,0);
if (not shift) and ((hi(vk) and $01)>0) then
keybd_event(VK_Shift,0,0,0);
if (not shift) and ((hi(vk) and $02)>0) then
keybd_event(VK_Control,0,0,0);
if (not shift) and ((hi(vk) and $04)>0) then
keybd_event(VK_Menu,0,0,0);
Keybd_Event(c,scancode,0,0);
Keybd_Event(c,scancode,KEYEVENTF_KEYUP,0);
//if not shift and (Hi(vk) > 0) then
// Keybd_Event(VK_SHIFT,$2A,KEYEVENTF_KEYUP,0);
if (not shift) and ((hi(vk) and $04)>0) then
keybd_event(VK_Menu,0,KEYEVENTF_KEYUP,0);
if (not shift) and ((hi(vk) and $02)>0) then
keybd_event(VK_Control,0,KEYEVENTF_KEYUP,0);
if (not shift) and ((hi(vk) and $01)>0) then
keybd_event(VK_Shift,0,KEYEVENTF_KEYUP,0);
end;
Application.ProcessMessages;
end;
end;
//SendKeysTo
//---------
procedure TSendKeys.SendKeysTo(Titletext:string; const text :string);
Var
h: hWnd;
begin
h := HandleFromTitle(Titletext);
MakeWindowActive(h);
SendKeys(text);
end;
end.
|
unit UDPBindingStorage;
interface
uses Windows, Classes, Threads.ReqSpecDevTemplate, IdSocketHandle, IdUDPServer, SysUtils, GMGlobals;
type
TUDPBindingAndThread = class(TCollectionItem)
public
thread: TRequestSpecDevices;
binding: TIdSocketHandle;
end;
TUDPBindingsAndThreads = class(TCollection)
private
synch: TMultiReadExclusiveWriteSynchronizer;
FUdpSrv: TIdUDPServer;
function CheckBinding(binding: TIdSocketHandle): bool;
public
function ByBinding(ABinding: TIdSocketHandle): TRequestSpecDevices;
function ByThread(AThread: TThread): TIdSocketHandle;
procedure RemoveThread(AThread: TThread);
procedure ClearByIdObj(id_obj: int; AThreadClass: TRequestSpecDevicesClass);
procedure PrepareToShutDown();
constructor Create(AUdpSrv: TIdUDPServer);
destructor Destroy; override;
end;
implementation
{ TUDPBindingsAndThreads }
function TUDPBindingsAndThreads.ByBinding(ABinding: TIdSocketHandle): TRequestSpecDevices;
var i: int;
r: TUDPBindingAndThread;
begin
Result := nil;
synch.BeginRead();
try
for i := Count - 1 downto 0 do
begin
r := TUDPBindingAndThread(Items[i]);
if r.binding = ABinding then
begin
Result := r.thread;
Exit;
end;
end;
finally
synch.EndRead();
end;
end;
function TUDPBindingsAndThreads.ByThread(AThread: TThread): TIdSocketHandle;
var i, n: int;
r: TUDPBindingAndThread;
begin
n := -1;
Result := nil;
synch.BeginRead();
try
for i := Count - 1 downto 0 do
begin
r := TUDPBindingAndThread(Items[i]);
if r.thread = AThread then
begin
n := i;
break;
end;
end;
finally
synch.EndRead();
end;
if n < 0 then Exit;
// проверим отпавшие соединения
r := TUDPBindingAndThread(Items[n]);
if CheckBinding(r.binding) then
begin
Result := r.binding;
end
else
begin
synch.BeginWrite();
try
Delete(n);
finally
synch.EndWrite();
end;
Result := ByThread(AThread);
end;
end;
procedure TUDPBindingsAndThreads.ClearByIdObj(id_obj: int; AThreadClass: TRequestSpecDevicesClass);
var i: int;
r: TUDPBindingAndThread;
begin
synch.BeginWrite();
try
for i := Count - 1 downto 0 do
begin
r := TUDPBindingAndThread(Items[i]);
if (r.thread is AThreadClass) and (r.thread.ID_Obj =id_obj) then
begin
Delete(i);
end
else
begin
if not CheckBinding(r.binding) then
begin
Delete(i);
end;
end;
end;
finally
synch.EndWrite();
end;
end;
constructor TUDPBindingsAndThreads.Create(AUdpSrv: TIdUDPServer);
begin
inherited Create(TUDPBindingAndThread);
synch := TMultiReadExclusiveWriteSynchronizer.Create();
FUdpSrv := AUdpSrv;
end;
destructor TUDPBindingsAndThreads.Destroy;
begin
synch.Free();
inherited;
end;
procedure TUDPBindingsAndThreads.PrepareToShutDown;
var i: int;
r: TUDPBindingAndThread;
begin
synch.BeginWrite();
try
for i := Count - 1 downto 0 do
begin
r := TUDPBindingAndThread(Items[i]);
r.binding := nil;
end;
finally
synch.EndWrite();
end;
end;
procedure TUDPBindingsAndThreads.RemoveThread(AThread: TThread);
var i: int;
r: TUDPBindingAndThread;
begin
synch.BeginWrite();
try
for i := Count - 1 downto 0 do
begin
r := TUDPBindingAndThread(Items[i]);
if r.thread = AThread then
begin
Delete(i);
break;
end;
end;
finally
synch.EndWrite();
end;
end;
function TUDPBindingsAndThreads.CheckBinding(binding: TIdSocketHandle): bool;
var i: int;
begin
Result := false;
synch.BeginRead();
try
for i := 0 to FUdpSrv.Bindings.Count - 1 do
if FUdpSrv.Bindings[i] = binding then
begin
Result := true;
break;
end;
finally
synch.EndRead();
end;
end;
end.
|
{$I NEX.INC}
unit ncDMCaixa;
{
ResourceString: Dario 12/03/13
}
interface
uses
SysUtils, Classes, DB, nxdb, kbmMemTable, nxllTransport,
nxptBasePooledTransport, nxtwWinsockTransport, nxsdServerEngine,
nxreRemoteServerEngine, nxllComponent, frxClass, frxDBSet, frxExportPDF,
uLogs, uNexTransResourceStrings_PT;
type
{TDadosCaixa = record
dcID : Integer;
dcAbertura : TDateTime;
dcFechamento : TDateTime;
dcSaldoInicial : Currency;
dcUsuario : String;
end;}
TDadosResFin = record
drfQtd : Integer;
drfValor : Currency;
end;
TdmCaixa = class(TDataModule)
nxSession: TnxSession;
nxDB: TnxDatabase;
nxRSE: TnxRemoteServerEngine;
nxTCPIP: TnxWinsockTransport;
dsQVC: TDataSource;
qVC: TnxQuery;
tProd: TnxTable;
tProdDescricao: TStringField;
tME: TnxTable;
mtEst: TkbmMemTable;
mtEstSaldoInicial: TFloatField;
mtEstEntradas: TFloatField;
mtEstCompras: TFloatField;
mtEstSaidas: TFloatField;
mtEstVendas: TFloatField;
mtEstValorVendas: TCurrencyField;
mtEstDescricao: TStringField;
mtEstSaldoFinal: TFloatField;
mtEstLucro: TCurrencyField;
dsTot: TDataSource;
dsEst: TDataSource;
mtTot: TkbmMemTable;
mtTotItem: TIntegerField;
mtTotDescricao: TStringField;
mtTotValor: TCurrencyField;
tProdID: TAutoIncField;
mtEstID: TIntegerField;
tProdCustoUnitario: TCurrencyField;
tProdNaoControlaEstoque: TBooleanField;
qRFFat: TnxQuery;
qDesc: TnxQuery;
qCanc: TnxQuery;
tCli: TnxTable;
qVCCategoria: TStringField;
qVCTotal: TCurrencyField;
qVCDesconto: TCurrencyField;
qVCTotFinal: TCurrencyField;
tMEID: TAutoIncField;
tMETran: TIntegerField;
tMEProduto: TIntegerField;
tMEQuant: TFloatField;
tMEUnitario: TCurrencyField;
tMETotal: TCurrencyField;
tMECustoU: TCurrencyField;
tMEItem: TWordField;
tMEDesconto: TCurrencyField;
tMEPago: TCurrencyField;
tMEPagoPost: TCurrencyField;
tMEDescPost: TCurrencyField;
tMEDataHora: TDateTimeField;
tMEEntrada: TBooleanField;
tMECancelado: TBooleanField;
tMEEstoqueAnt: TFloatField;
tMECliente: TIntegerField;
tMECaixa: TIntegerField;
tMECategoria: TStringField;
tMENaoControlaEstoque: TBooleanField;
tMEITran: TIntegerField;
tMETipoTran: TWordField;
tMESessao: TIntegerField;
tMESaldoFinal: TFloatField;
tCaixa: TnxTable;
tCaixaID: TAutoIncField;
tCaixaAberto: TBooleanField;
tCaixaUsuario: TStringField;
tCaixaAbertura: TDateTimeField;
tCaixaFechamento: TDateTimeField;
tCaixaTotalFinal: TCurrencyField;
tCaixaDescontos: TCurrencyField;
tCaixaCancelamentos: TCurrencyField;
tCaixaSaldoAnt: TCurrencyField;
tCaixaObs: TMemoField;
qFecha: TnxQuery;
qFechaCancelado: TBooleanField;
qFechaTipo: TWordField;
qFechaTotal: TCurrencyField;
qFechaDesconto: TCurrencyField;
qFechaPago: TCurrencyField;
qFechaDebito: TCurrencyField;
PDFexp: TfrxPDFExport;
frdbCaixa: TfrxDBDataset;
frdbTot: TfrxDBDataset;
tCriar: TnxTable;
tCriarID: TAutoIncField;
tCriarTipo: TIntegerField;
tCriarParametros: TMemoField;
tCriarDestino: TMemoField;
qVCQuant: TFloatField;
tCaixaSangria: TCurrencyField;
tCaixaSupr: TCurrencyField;
tCaixaReproc: TDateTimeField;
qCorr: TnxQuery;
qCorr2: TnxQuery;
tTran: TnxTable;
tTranID: TAutoIncField;
tTranDataHora: TDateTimeField;
tTranCliente: TIntegerField;
tTranTipo: TWordField;
tTranFunc: TStringField;
tTranTotal: TCurrencyField;
tTranDesconto: TCurrencyField;
tTranPago: TCurrencyField;
tTranObs: TMemoField;
tTranCancelado: TBooleanField;
tTranCanceladoPor: TStringField;
tTranCanceladoEm: TDateTimeField;
tTranCaixa: TIntegerField;
tTranMaq: TWordField;
tTranNomeCliente: TStringField;
tTranSessao: TIntegerField;
tTranDescr: TStringField;
tTranDebito: TCurrencyField;
tTranQtdTempo: TFloatField;
tTranCredValor: TBooleanField;
tITran: TnxTable;
tITranID: TAutoIncField;
tITranTran: TIntegerField;
tITranCaixa: TIntegerField;
tITranDataHora: TDateTimeField;
tITranTipoTran: TWordField;
tITranTipoItem: TWordField;
tITranSubTipo: TWordField;
tITranItemID: TIntegerField;
tITranSubItemID: TIntegerField;
tITranItemPos: TWordField;
tITranTotal: TCurrencyField;
tITranDesconto: TCurrencyField;
tITranPago: TCurrencyField;
tITranCancelado: TBooleanField;
tITranSessao: TIntegerField;
tITranDebito: TCurrencyField;
mtEstFidResg: TFloatField;
tMEFidResgate: TBooleanField;
tMEFidPontos: TFloatField;
tCaixaEstSessoesQtd: TIntegerField;
tCaixaEstSessoesTempo: TFloatField;
tCaixaEstUrls: TIntegerField;
tCaixaEstSyncOk: TBooleanField;
tCaixaEstBuscasEng: TMemoField;
tCaixaEstRes: TMemoField;
qCancQuant: TLargeintField;
qCancTotal: TCurrencyField;
qDescQuant: TLargeintField;
qDescTotal: TCurrencyField;
tCaixaSaldoF: TCurrencyField;
tCaixaQuebra: TCurrencyField;
frdbEst: TfrxDBDataset;
mtEstEntradasTot: TFloatField;
frdbTran: TfrxDBDataset;
tRepProd: TnxTable;
tRepProdID: TAutoIncField;
tRepProdCodigo: TStringField;
tRepProdDescricao: TStringField;
tRepProdUnid: TStringField;
tRepProdPreco: TCurrencyField;
tRepProdObs: TnxMemoField;
tRepProdImagem: TGraphicField;
tRepProdCategoria: TStringField;
tRepProdFornecedor: TIntegerField;
tRepProdSubCateg: TStringField;
tRepProdEstoqueAtual: TFloatField;
tRepProdCustoUnitario: TCurrencyField;
tRepProdEstoqueACE: TFloatField;
tRepProdEstoqueACS: TFloatField;
tRepProdPodeAlterarPreco: TBooleanField;
tRepProdNaoControlaEstoque: TBooleanField;
tRepProdEstoqueMin: TFloatField;
tRepProdEstoqueMax: TFloatField;
tRepProdAbaixoMin: TBooleanField;
tRepProdAbaixoMinDesde: TDateTimeField;
tRepProdEstoqueRepor: TFloatField;
tRepProdFidelidade: TBooleanField;
tRepProdFidPontos: TIntegerField;
frdbProd: TfrxDBDataset;
qRepTran: TnxQuery;
qRepTranID: TIntegerField;
qRepTranDataHora: TDateTimeField;
qRepTranCliente: TIntegerField;
qRepTranTipo: TWordField;
qRepTranFunc: TStringField;
qRepTranTotal: TCurrencyField;
qRepTranDesconto: TCurrencyField;
qRepTranTotLiq: TCurrencyField;
qRepTranPago: TCurrencyField;
qRepTranDebito: TCurrencyField;
qRepTranObs: TnxMemoField;
qRepTranCancelado: TBooleanField;
qRepTranCanceladoPor: TStringField;
qRepTranCanceladoEm: TDateTimeField;
qRepTranCaixa: TIntegerField;
qRepTranMaq: TWordField;
qRepTranNomeCliente: TStringField;
qRepTranSessao: TIntegerField;
qRepTranDescr: TStringField;
qRepTranQtdTempo: TFloatField;
qRepTranCredValor: TBooleanField;
qRepTranFidResgate: TBooleanField;
qRepTranNomeTipo: TStringField;
qRepTranCancFid: TStringField;
tCaixaIDLivre: TStringField;
tUsuario: TnxTable;
tUsuarioUsername: TStringField;
tUsuarioNome: TStringField;
tUsuarioAdmin: TBooleanField;
repCaixa: TfrxReport;
tCaixaNomeLoja: TStringField;
qPagEsp: TnxQuery;
qPagEspTotalF: TCurrencyField;
qPagEspTotalValor: TCurrencyField;
qPagEspTotalTroco: TCurrencyField;
qPagEspEspecie: TWordField;
tEsp: TnxTable;
tEspID: TWordField;
tEspNome: TStringField;
tEspImg: TWordField;
qPagEspNomeEspecie: TStringField;
qPagEspImg: TWordField;
qPagEspObs: TStringField;
dsPagEsp: TDataSource;
frdbPagEsp: TfrxDBDataset;
qFechaTroco: TCurrencyField;
qRFPag: TnxQuery;
qRFPagCredito: TCurrencyField;
qRFPagDebito: TCurrencyField;
qRFPagTipo: TWordField;
qRFPagQtd: TLargeintField;
qRFPagCreditoUsado: TCurrencyField;
qRFPagPago: TCurrencyField;
qRFFatTipo: TWordField;
qRFFatQtd: TLargeintField;
qRFFatTotLiq: TCurrencyField;
mtRF1: TkbmMemTable;
mtRF1Item: TIntegerField;
mtRF1Descricao: TStringField;
mtRF1Total: TCurrencyField;
dsRF1: TDataSource;
mtRF2: TkbmMemTable;
mtRF2Item: TIntegerField;
mtRF2Descricao: TStringField;
mtRF2Total: TCurrencyField;
dsRF2: TDataSource;
mtRF3: TkbmMemTable;
mtRF3Item: TIntegerField;
mtRF3Descricao: TStringField;
mtRF3Total: TCurrencyField;
dsRF3: TDataSource;
dbRF1: TfrxDBDataset;
dbRF2: TfrxDBDataset;
dbRF3: TfrxDBDataset;
mtRF1Bold: TBooleanField;
mtRF1Cor: TIntegerField;
mtRF2Bold: TBooleanField;
mtRF2Cor: TIntegerField;
mtRF3Bold: TBooleanField;
mtRF3Cor: TIntegerField;
mtObs: TkbmMemTable;
mtObsObs: TMemoField;
dbObs: TfrxDBDataset;
qRFPagTroco: TCurrencyField;
procedure qVCCalcFields(DataSet: TDataSet);
procedure tMECalcFields(DataSet: TDataSet);
procedure DataModuleCreate(Sender: TObject);
procedure mtEstCalcFields(DataSet: TDataSet);
procedure repCaixaBeforePrint(Sender: TfrxReportComponent);
procedure qRepTranCalcFields(DataSet: TDataSet);
procedure tCaixaCalcFields(DataSet: TDataSet);
procedure qPagEspCalcFields(DataSet: TDataSet);
procedure mtRF1CalcFields(DataSet: TDataSet);
procedure mtRF2CalcFields(DataSet: TDataSet);
procedure mtRF3CalcFields(DataSet: TDataSet);
private
{ Private declarations }
procedure AddItemRF(aItem: Integer; aDescr: String; aValor: Currency; aAddZero: Boolean = True);
public
drf : Array[1..16] of TDadosResFin;
CaixaI,
CaixaF: Integer;
TemSupSan : Boolean;
FImpTran : Boolean;
TotalTroco : Currency;
procedure AbreConn;
function AbreCaixa(aFunc: String; aSaldo: Currency; aManterSaldo: Boolean; var aNumCx: Integer): Integer;
function FechaCaixa(aFunc: String; aSaldo: Currency; aNumCx: Integer; aReproc: Boolean): Integer;
function Processa(aID: Integer; aPeriodo: Boolean; aDataI, aDataF: TDateTime): Currency;
procedure ExportaCaixa(aID: Integer; aArquivo: String);
procedure ExportaCaixaKite(aID: Integer; aArquivo: String; slPar: tStrings);
{ Public declarations }
end;
var
dmCaixa: TdmCaixa;
const
irfFaturamento = 1;
irfDebitado = 2;
irfCredUsado = 3;
irfDescontos = 4;
irfCancelamentos = 5;
irfVendasRec = 6;
irfDebPagos = 7;
irfTrocoCred = 8;
irfTotalRec = 9;
irfSaldoInicial = 10;
irfTotalRec2 = 11;
irfDinAdd = 12;
irfDinRem = 13;
irfSaldoFinal = 14;
irfSaldoInformado = 15;
irfQuebraCaixa = 16;
implementation
uses
ncClassesBase, ncErros, Graphics, ncDebug;
// START resource string wizard section
{$R *.dfm}
resourcestring
rsValorOriginal = 'Valor Original';
rsTroco = 'Troco';
function InitTran(aDB: TnxDatabase;
const aTables : array of TnxTable;
aWith : Boolean): Boolean;
var I : Integer;
begin
Result := False;
if aDB.InTransaction then Exit; I := 10;
while I > 0 do begin
try
if aWith then
aDB.StartTransactionWith(aTables)
else
aDB.StartTransaction;
I := 0;
except
Dec(I);
Random(500);
end
end;
Result := True;
end;
function TdmCaixa.AbreCaixa(aFunc: String; aSaldo: Currency; aManterSaldo: Boolean; var aNumCx: Integer): Integer;
var SaldoAnt: Currency;
begin
tCaixa.Active := True;
tTran.IndexName := 'IID'; // do not localize
tTran.Open;
tITran.Open;
InitTran(nxDB, [tCaixa, tTran, tITran], True);
try
tCaixa.IndexName := 'IAberto'; // do not localize
try
if tCaixa.FindKey([True]) then begin
nxDB.Rollback;
Result := ncerrJaTemCaixaAberto;
Exit;
end;
finally
tCaixa.IndexName := 'IID'; // do not localize
end;
if aManterSaldo then begin
if tCaixa.IsEmpty then
SaldoAnt := 0
else begin
tCaixa.Last;
SaldoAnt := tCaixaTotalFinal.Value + tCaixaSaldoAnt.Value + tCaixaSupr.Value - tCaixaSangria.Value;
end;
end else
SaldoAnt := aSaldo;
tCaixa.Insert;
tCaixaAbertura.Value := Now;
tCaixaAberto.Value := True;
tCaixaUsuario.Value := aFunc;
if aManterSaldo or gConfig.PedirSaldoI then
tCaixaSaldoAnt.Value := SaldoAnt;
tCaixaEstSyncOk.Value := False;
tCaixa.Post;
aNumCx := tCaixaID.Value;
Result := 0;
nxDB.Commit;
except
on e: exception do begin
nxDB.Rollback;
Result := ncerrExcecaoNaoTratada_TdmCaixa_AbreCaixa;
glog.LogCriticalException(self,Result, e);
end;
end;
end;
procedure TdmCaixa.AbreConn;
begin
nxDB.AliasPath := '';
nxDB.AliasName := 'NexCafe'; // do not localize
nxDB.Active := True;
tCli.Open;
tME.Open;
tProd.Open;
tCaixa.Open;
tCriar.Open;
end;
procedure TdmCaixa.AddItemRF(aItem: Integer; aDescr: String; aValor: Currency; aAddZero: Boolean = True);
begin
if (aValor<0.01) and (not aAddZero) then Exit;
mtTot.Append;
mtTotDescricao.Value := aDescr;
if aItem<>99 then
mtTotValor.Value := aValor;
mtTotItem.Value := aItem;
mtTot.Post;
if (aItem<>99) then
case aItem of
irfFaturamento..irfCancelamentos: begin
mtRF1.Append;
mtRF1Descricao.Value := aDescr;
mtRF1Total.Value := aValor;
mtRF1Item.Value := aItem;
mtRF1.Post
end;
irfVendasRec..irfTotalRec: begin
mtRF2.Append;
mtRF2Descricao.Value := aDescr;
mtRF2Total.Value := aValor;
mtRF2Item.Value := aItem;
mtRF2.Post
end;
irfSaldoInicial..irfQuebraCaixa: begin
mtRF3.Append;
mtRF3Descricao.Value := aDescr;
mtRF3Total.Value := aValor;
mtRF3Item.Value := aItem;
mtRF3.Post
end;
end;
end;
procedure TdmCaixa.DataModuleCreate(Sender: TObject);
begin
nxTCPIP.Port := 17200;
TemSupSan := False;
FImpTran := False;
TotalTroco := 0;
end;
procedure TdmCaixa.ExportaCaixa(aID: Integer; aArquivo: String);
begin
ExportaCaixaKite(aID, aArquivo, nil);
end;
procedure TdmCaixa.ExportaCaixaKite(aID: Integer; aArquivo: String;
slPar: tStrings);
var sIdent: String;
begin
DebugMsg('TdmCaixa.ExportaCaixa - aID: ' + IntToStr(aID) + ' - aArquivo: ' + aArquivo); // do not localize
Processa(aID, False, 0, 0);
DebugMsg('TdmCaixa.ExportaCaixa - 2'); // do not localize
tUsuario.Active := True;
if slPar<>nil then begin
slPar.Add('timestamp_de_abertura='+formatDateTime('YYYY-MM-DD HH:NN:SS', tCaixaAbertura.Value)); // do not localize
slPar.Add('timestamp_de_fechamento='+formatDateTime('YYYY-MM-DD HH:NN:SS', tCaixaFechamento.Value)); // do not localize
slPar.Add('username_funcionario='+tCaixaUsuario.Value); // do not localize
slPar.Add('numero_do_caxa='+tCaixaID.AsString); // do not localize
slPar.Add('conta_da_loja='+gConfig.Conta); // do not localize
if tUsuario.FindKey([tCaixaUsuario.Value]) then
slPar.Add('nome_funcionario='+tUsuarioNome.Value) else // do not localize
slPar.Add('nome_funcionario='); // do not localize
if Trim(gConfig.EmailIdent)>'' then
sIdent:= gConfig.EmailIdent + ' - ' else
sIdent:= '';
slPar.Add('subject='+sIdent+'Caixa n.' + tCaixaID.AsString+ // do not localize
' - ' + tCaixaAbertura.AsString +
' a ' + tCaixaFechamento.AsString);
end;
pdfExp.FileName := aArquivo;
DebugMsg('TdmCaixa.ExportaCaixa - 3'); // do not localize
pdfExp.DefaultPath := '';
DebugMsg('TdmCaixa.ExportaCaixa - 4'); // do not localize
repCaixa.PrepareReport;
DebugMsg('TdmCaixa.ExportaCaixa - 5'); // do not localize
repCaixa.Export(PDFexp);
DebugMsg('TdmCaixa.ExportaCaixa - 6'); // do not localize
end;
function TdmCaixa.FechaCaixa(aFunc: String; aSaldo: Currency; aNumCx: Integer; aReproc: Boolean): Integer;
var
SAnt: Currency;
SL : TStrings;
begin
InitTran(nxDB, [], False);
try
tCaixa.IndexName := 'IID'; // do not localize
if not tCaixa.FindKey([aNumCx]) then begin
nxDB.Rollback;
Result := ncerrItemInexistente;
Exit;
end;
SAnt := 0;
if aReproc then begin
if tCaixaAberto.Value then begin
nxDB.Rollback;
Raise ENexCafe.Create(SncDMCaixa_OReprocessamentoDeCaixaSóPodeSer);
end;
if gConfig.ManterSaldoCaixa then begin
tCaixa.Prior;
if (tCaixaID.Value < aNumCx) then
if not tCaixaSaldoF.IsNull then
SAnt := tCaixaSaldoF.Value else
SAnt := tCaixaTotalFinal.Value + tCaixaSaldoAnt.Value + tCaixaSupr.Value - tCaixaSangria.Value;
tCaixa.FindKey([aNumCx]);
end else
SAnt := tCaixaSaldoAnt.Value;
end else
if not tCaixaAberto.Value then begin
nxDB.Rollback;
Result := ncerrCaixaJaFoiFechado;
Exit;
end;
if aReproc then begin
qCorr.Active := False;
qCorr.ParamByName('Caixa').AsInteger := aNumCx; // do not localize
qCorr.ExecSQL;
qCorr2.Active := False;
qCorr2.SQL.Text := 'update itran '+ // do not localize
'set caixa = ' + IntToStr(aNumCx) + // do not localize
' where tran in (select id from tran where caixa = ' + IntToStr(aNumCx) +')'; // do not localize
qCorr2.ExecSQL;
qCorr2.Active := False;
qCorr2.SQL.Text := 'update movest '+ // do not localize
'set caixa = ' + IntToStr(aNumCx) + // do not localize
' where tran in (select id from tran where caixa = ' + IntToStr(aNumCx) +')'; // do not localize
qCorr2.ExecSQL;
end;
qFecha.ParamByName('Caixa').AsInteger := aNumCx; // do not localize
qFecha.Active := True;
tCaixa.Edit;
tCaixaCancelamentos.Value := 0;
tCaixaDescontos.Value := 0;
tCaixaTotalFinal.Value := 0;
tCaixaSangria.Value := 0;
tCaixaSupr.Value := 0;
if aReproc then
tCaixaSaldoAnt.Value := SAnt;
while not qFecha.Eof do begin
if qFechaCancelado.Value then
tCaixaCancelamentos.Value := tCaixaCancelamentos.Value + qFechaTotal.Value
else
case qFechaTipo.Value of
trCaixaEnt : tCaixaSupr.Value := tCaixaSupr.Value + qFechaTotal.Value;
trCaixaSai : tCaixaSangria.Value := tCaixaSangria.Value + qFechaTotal.Value;
trEstCompra,
trEstSaida,
trEstEntrada,
trCorrDataCx : ;
else
tCaixaTotalFinal.Value := tCaixaTotalFinal.Value + (qFechaPago.Value-qFechaTroco.Value);
end;
tCaixaDescontos.Value := tCaixaDescontos.Value + qFechaDesconto.Value;
qFecha.Next;
end;
tCaixaAberto.Value := False;
if aReproc then
tCaixaReproc.Value := Now else
tCaixaFechamento.Value := Now;
tCaixaEstSyncOk.Value := True;
if gConfig.PedirSaldoF then begin
if (not aReproc) then
tCaixaSaldoF.Value := aSaldo;
tCaixaQuebra.Value :=
tCaixaSaldoF.Value -
(tCaixaTotalFinal.Value + tCaixaSaldoAnt.Value + tCaixaSupr.Value - tCaixaSangria.Value);
end;
tCaixa.Post;
Result := 0;
nxDB.Commit;
except
on e: exception do begin
nxDB.Rollback;
Result := ncerrExcecaoNaoTratada_TdmCaixa_FechaCaixa;
glog.LogCriticalException(self,Result, e);
end;
end;
end;
procedure TdmCaixa.mtEstCalcFields(DataSet: TDataSet);
begin
mtEstEntradasTot.Value := mtEstEntradas.Value + mtEstCompras.Value;
end;
function GetCor(aItem: Integer): TColor;
begin
case aItem of
irfCancelamentos, irfDescontos, irfQuebraCaixa : Result := clRed;
irfSaldoFinal, irfSaldoInformado : Result := clBlue;
else
Result := clBlack;
end;
end;
function GetBold(aItem: Integer): Boolean;
begin
case aItem of
irfTotalRec,
irfSaldoFinal,
irfSaldoInformado,
irfQuebraCaixa,
irfFaturamento : Result := True;
else
Result := False;
end;
end;
procedure TdmCaixa.mtRF1CalcFields(DataSet: TDataSet);
begin
mtRF1Bold.Value := GetBold(mtRF1Item.Value);
mtRF1Cor.Value := GetCor(mtRF1Item.Value);
end;
procedure TdmCaixa.mtRF2CalcFields(DataSet: TDataSet);
begin
mtRF2Bold.Value := GetBold(mtRF2Item.Value);
mtRF2Cor.Value := GetCor(mtRF2Item.Value);
end;
procedure TdmCaixa.mtRF3CalcFields(DataSet: TDataSet);
begin
mtRF3Bold.Value := GetBold(mtRF3Item.Value);
mtRF3Cor.Value := GetCor(mtRF3Item.Value);
end;
function V2Casas(C: Currency): Currency;
begin
Result := Int(C * 100) / 100;
end;
function TdmCaixa.Processa(aID: Integer; aPeriodo: Boolean; aDataI, aDataF: TDateTime): Currency;
var
Q: TnxQuery;
I, Num, IDCli : Integer;
CustoU, TotFinal, PercDesc, Desc, DescT : Double;
S: String;
Incluir: Boolean;
PagDet, PagReg : Integer;
ValorI : Currency;
qItem: Integer;
begin
Fillchar(DRF, SizeOf(DRF), 0);
Result := 0;
CaixaI := 0;
CaixaF := 0;
mtRF1.EmptyTable;
mtRF2.EmptyTable;
mtRF3.EmptyTable;
mtObs.Active := False;
mtObs.Active := True;
qVC.Active := False;
qDesc.Active := False;
qCanc.Active := False;
qRFFat.Active := False;
qRFPag.Active := False;
// qCliValor.Active := False;
mtEst.Active := False;
mtEst.Active := True;
mtTot.Active := False;
mtTot.Active := True;
FillChar(drf, SizeOf(drf), 0);
Num := aID;
if aPeriodo then begin
Q := TnxQuery.Create(Self);
try
Q.Database := nxDB;
Q.SQL.Add('SELECT MIN(ID) as CaixaI, MAX(ID) as CaixaF FROM CAIXA'); // do not localize
Q.SQL.Add('WHERE (Abertura >= TIMESTAMP ' + QuotedStr(FormatDateTime('yyyy-mm-dd hh:mm:ss', aDataI))+') AND ' + // do not localize
' (Abertura < TIMESTAMP ' + QuotedStr(FormatDateTime('yyyy-mm-dd hh:mm:ss', aDataF+1))+') AND (Aberto = False)'); // do not localize
Q.Open;
CaixaI := Q.FieldByName('CaixaI').AsInteger; // do not localize
CaixaF := Q.FieldByName('CaixaF').AsInteger; // do not localize
finally
Q.Free;
end;
end;
if Num > 0 then begin
tCaixa.Locate('ID', Num, []); // do not localize
CaixaI := Num;
CaixaF := Num;
if Trim(tCaixaObs.Value)>'' then begin
mtObs.Append;
mtObsObs.Value := tCaixaObs.Value;
mtObs.Post;
end;
end;
tRepProd.Open;
tRepProd.SetRange([True], [True]);
qRepTran.Active := False;
qRepTran.SQL.Text := 'select * from Tran'; // do not localize
if gConfig.cce(cceTransacoesCanc) then
S := '(Cancelado=True)' else // do not localize
S := '';
if gConfig.cce(cceTransacoesDesc) then
if S>'' then
S := '(Cancelado=True) or (Desconto>0)' else // do not localize
S := '(Desconto>0)'; // do not localize
if gConfig.cce(cceTransacoesObs) then
if S>'' then
S := S + ' or (Trim(Obs)>'+QuotedStr('')+')' else // do not localize
S := '(Trim(Obs)>'+QuotedStr('')+')'; // do not localize
if (gConfig.EmailEnviarCaixa) and (S>'') then begin
FImpTran := True;
S := 'where (Caixa='+IntToStr(CaixaI)+') and ('+S+') order by ID'; // do not localize
qRepTran.SQL.Text := 'select * from Tran ' + S; // do not localize
qRepTran.Open;
end else begin
// qRepTran.Open;
FImpTran := False;
end;
qCanc.ParamByName('CaixaI').AsInteger := CaixaI; // do not localize
qCanc.ParamByName('CaixaF').AsInteger := CaixaF; // do not localize
qCanc.Active := True;
qDesc.ParamByName('CaixaI').AsInteger := CaixaI; // do not localize
qDesc.ParamByName('CaixaF').AsInteger := CaixaF; // do not localize
qDesc.Active := True;
qVC.ParamByName('CaixaI').AsInteger := CaixaI; // do not localize
qVC.ParamByName('CaixaF').AsInteger := CaixaF; // do not localize
qVC.Active := True;
qPagEsp.Active := False;
qPagEsp.Params[0].AsInteger := CaixaI;
qPagEsp.Params[1].AsInteger := CaixaF;
qPagEsp.Active := True;
qPagEsp.First;
TotalTroco := 0;
while not qPagEsp.Eof do begin
TotalTroco := TotalTroco + qPagEspTotalTroco.Value;
qPagEsp.Next;
end;
qPagEsp.First;
qRFFat.ParamByName('CaixaI').AsInteger := CaixaI; // do not localize
qRFFat.ParamByName('CaixaF').AsInteger := CaixaF; // do not localize
qRFFat.Active := True;
qRFFat.First;
qRFPag.ParamByName('CaixaI').AsInteger := CaixaI; // do not localize
qRFPag.ParamByName('CaixaF').AsInteger := CaixaF; // do not localize
qRFPag.Active := True;
qRFPag.First;
while not qRFFat.Eof do begin
case qRFFatTipo.Value of
trEstVenda, trEstVendaWeb : begin
drf[irfFaturamento].drfQtd := drf[irfFaturamento].drfQtd + qRFFatQtd.Value;
drf[irfFaturamento].drfValor := drf[irfFaturamento].drfValor + qRFFatTotLiq.Value;
end;
trCaixaEnt : begin
drf[irfDinAdd].drfQtd := qRFFatQtd.Value;
drf[irfDinAdd].drfValor := qRFFatTotLiq.Value;
end;
trCaixaSai : begin
drf[irfDinRem].drfQtd := qRFFatQtd.Value;
drf[irfDinRem].drfValor := qRFFatTotLiq.Value;
end;
end;
qRFFat.Next;
end;
while not qRFPag.Eof do begin
case qRFPagTipo.Value of
trEstVenda,
trEstVendaWeb : drf[irfVendasRec].drfValor := drf[irfVendasRec].drfValor + (qRFPagPago.Value - qRFPagTroco.Value - qRFPagCredito.Value);
trPagDebito : begin
drf[irfDebPagos].drfQtd := qRFPagQtd.Value;
drf[irfDebPagos].drfValor := qRFPagPago.Value;
end;
end;
drf[irfTrocoCred].drfValor := drf[irfTrocoCred].drfValor + qRFPagCredito.Value;
drf[irfDebitado].drfValor := drf[irfDebitado].drfValor + qRFPagDebito.Value;
drf[irfCredUsado].drfValor := drf[irfCredUsado].drfValor + qRFPagCreditoUsado.Value;
qRFPag.Next;
end;
dsEst.Dataset := nil;
try
tProd.First;
while not tProd.Eof do begin
tME.SetRange([tProdID.Value, CaixaI], [tProdID.Value, CaixaF]);
if not (tME.Eof and tME.Bof) then begin
mtEst.Append;
mtEstID.Value := tProdID.Value;
mtEstDescricao.Value := tProdDescricao.Value;
mtEstSaldoInicial.Value := tMEEstoqueAnt.Value;
tME.First;
while not tME.Eof do begin
case tMETipoTran.Value of
trEstCompra : mtEstCompras.Value := mtEstCompras.Value + tMEQuant.Value;
trEstEntrada : mtEstEntradas.Value := mtEstEntradas.Value + tMEQuant.Value;
trEstSaida : mtEstSaidas.Value := mtEstSaidas.Value + tMEQuant.Value;
else
if tMEFidResgate.Value then begin
mtEstFidResg.Value := mtEstFidResg.Value + tMEQuant.Value;
end else begin
mtEstVendas.Value := mtEstVendas.Value + tMEQuant.Value;
mtEstValorVendas.Value := mtEstValorVendas.Value + tMETotal.Value - tMEDesconto.Value;
CustoU := tMECustoU.Value;
if (CustoU < 0.00009) then
CustoU := tProdCustoUnitario.Value;
mtEstLucro.Value := mtEstLucro.Value + (tMETotal.Value - (CustoU * tMEQuant.Value) - tMEDesconto.Value);
end;
end;
tME.Next;
end;
mtEstSaldoFinal.Value := tMESaldoFinal.Value;
mtEst.Post;
end;
tProd.Next;
end;
finally
dsEst.Dataset := mtEst;
end;
PagDet := 0;
PagReg := 0;
ValorI := 0;
mtTot.Open;
mtTot.EmptyTable;
drf[irfTotalRec].drfValor := drf[irfVendasRec].drfValor +
drf[irfDebPagos].drfValor +
drf[irfTrocoCred].drfValor;
drf[irfTotalRec2].drfValor := drf[irfTotalRec].drfValor;
if not aPeriodo then
drf[irfSaldoFinal].drfValor := drf[irfTotalRec].drfValor +
tCaixaSaldoAnt.Value +
drf[irfDinAdd].drfValor -
drf[irfDinRem].drfValor;
AddItemRF(irfFaturamento, SncDMCaixa_Faturamento, drf[irfFaturamento].drfValor);
AddItemRF(99, '', 0);
AddItemRF(irfDebitado, SncDMCaixa_Debitado, drf[irfDebitado].drfValor, False);
AddItemRF(irfCredUsado, SncDMCaixa_CredUsado, drf[irfCredUsado].drfValor, False);
AddItemRF(irfDescontos, SncDMCaixa_Descontos, qDescTotal.Value, False);
AddItemRF(irfCancelamentos, SncDMCaixa_Cancelamentos, qCancTotal.Value, False);
AddItemRF(99, '', 0);
AddItemRF(99, SncDMCaixa_ValoresRecebidos, 0);
AddItemRF(irfVendasRec, SncDMCaixa_Vendas, drf[irfVendasRec].drfValor);
AddItemRF(irfDebPagos, SncDMCaixa_DebPagos, drf[irfDebPagos].drfValor, False);
AddItemRF(irfTrocoCred, SncDMCaixa_TrocoCreditado, drf[irfTrocoCred].drfValor, false);
AddItemRF(irfTotalRec, SncDMCaixa_TotalRec, drf[irfTotalRec].drfValor);
AddItemRF(99, '', 0);
if not aPeriodo then AddItemRF(99, SncDMCaixa_SaldoCaixa, 0);
if not aPeriodo then AddItemRF(irfSaldoInicial, SncDMCaixa_SaldoInicial, tCaixaSaldoAnt.Value);
if not aPeriodo then AddItemRF(irfTotalRec2, SncDMCaixa_ValoresRecebidos, drf[irfTotalRec2].drfValor);
AddItemRF(irfDinAdd, '+ '+SncDMCaixa_DinheiroAdicionado, drf[irfDinAdd].drfValor, false);
AddItemRF(irfDinRem, '- '+SncDMCaixa_DinheiroRetirado, drf[irfDinRem].drfValor, false);
if (not aPeriodo) then begin
AddItemRF(irfSaldoFinal, SncDMCaixa_SaldoFinal, drf[irfSaldoFinal].drfValor);
if (not tCaixaAberto.Value) and gConfig.PedirSaldoF then begin
AddItemRF(irfSaldoInformado, SncDMCaixa_SaldoInformado, tCaixaSaldoF.Value);
AddItemRF(irfQuebraCaixa, SncDMCaixa_QuebraDeCaixa, tCaixaQuebra.Value, False);
end;
end;
Result := drf[irfSaldoFinal].drfValor;
end;
procedure TdmCaixa.qPagEspCalcFields(DataSet: TDataSet);
begin
if (qPagEspEspecie.Value=1) then begin
qPagEspTotalF.Value := qPagEspTotalValor.Value - TotalTroco;
qPagEspObs.Value := rsValorOriginal + '=' + CurrencyToStr(qPagEspTotalValor.Value) + ' - ' +
rsTroco + '=' + CurrencyToStr(TotalTroco);
end else
qPagEspTotalF.Value := qPagEspTotalValor.Value;
end;
procedure TdmCaixa.qRepTranCalcFields(DataSet: TDataSet);
const BoolStr : Array[Boolean] of String[3] = ('Não', 'Sim');
begin
if qRepTranTipo.Value in [trInicioSessao..trAjustaFid] then
qRepTranNomeTipo.Value := StTipoTransacao[qRepTranTipo.Value];
qRepTranCancFid.Value := BoolStr[qRepTranCancelado.Value] + ' / ' + BoolStr[qRepTranFidResgate.Value];
end;
procedure TdmCaixa.qVCCalcFields(DataSet: TDataSet);
begin
qVCTotFinal.Value := qVCTotal.Value - qVCDesconto.Value;
end;
procedure TdmCaixa.repCaixaBeforePrint(Sender: TfrxReportComponent);
begin
if SameText(Sender.Name, 'srTran') then // do not localize
Sender.Visible := FImpTran;
if SameText(Sender.Name, 'srImpressoes') then // do not localize
Sender.Visible := gConfig.cce(cceImpressoes);
if SameText(Sender.Name, 'srMovEstoque') then // do not localize
Sender.Visible := gConfig.cce(cceMovEstoque);
if SameText(Sender.Name, 'srResumoFin') then // do not localize
Sender.Visible := gConfig.cce(cceResumoFin);
if SameText(Sender.Name, 'srEstoqueAbaixoMin') then // do not localize
Sender.Visible := gConfig.cce(cceEstoqueAbaixoMin);
if SameText(Sender.Name, 'srPagEsp') then // do not localize
Sender.Visible := gConfig.cce(ccePagEsp);
if SameText(Sender.Name, 'Footer2') then // do not localize
Sender.Visible := (Trim(tCaixaObs.Value)>'');
end;
procedure TdmCaixa.tCaixaCalcFields(DataSet: TDataSet);
begin
tCaixaNomeLoja.Value := gConfig.EmailIdent;
end;
procedure TdmCaixa.tMECalcFields(DataSet: TDataSet);
begin
if tMENaoControlaEstoque.Value then
tMESaldoFinal.Value := 0 else
if tMECancelado.Value then
tMESaldoFinal.Value := tMEEstoqueAnt.Value
else
if tMEEntrada.Value then
tMESaldoFinal.Value := tMEEstoqueAnt.Value + tMEQuant.Value else
tMESaldoFinal.Value := tMEEstoqueAnt.Value - tMEQuant.Value;
end;
end.
|
(* PatternMatching: MM, 2020-03-18 *)
(* ------ *)
(* SImple pattern matching algorithms for strings *)
(* ========================================================================= *)
PROGRAM PatternMatching;
TYPE PatternMatcher = FUNCTION(s, p: STRING): INTEGER;
VAR charComps: INTEGER;
PROCEDURE Init;
BEGIN (* Init *)
charComps := 0;
END; (* Init *)
PROCEDURE WriteCharComps;
BEGIN (* WriteCharComps *)
Write(charComps);
END; (* WriteCharComps *)
FUNCTION Equals(a, b: CHAR): BOOLEAN;
BEGIN (* Equals *)
Inc(charComps);
Equals := a = b;
END; (* Equals *)
FUNCTION BruteSearchLR1(s, p: STRING): INTEGER;
VAR sLen, pLen: INTEGER;
i, j: INTEGER;
BEGIN (* BruteSearchLR1 *)
sLen := Length(s);
pLen := Length(p);
IF (pLen = 0) OR (sLen = 0) OR (pLen > sLen) THEN BEGIN
BruteSearchLR1 := 0;
END ELSE BEGIN
i := 1;
REPEAT
j := 1;
WHILE ((j <= pLen) AND (Equals(p[j], s[i + j - 1]))) DO BEGIN
Inc(j);
END; (* WHILE *)
Inc(i);
UNTIL ((j > pLen) OR (i > sLen - pLen + 1)); (* REPEAT *)
IF (j > pLen) THEN BEGIN
BruteSearchLR1 := i - 1;
END ELSE BEGIN
BruteSearchLR1 := 0;
END; (* IF *)
END; (* IF *)
END; (* BruteSearchLR1 *)
FUNCTION BruteSearchLR2(s, p: STRING): INTEGER;
VAR sLen, pLen: INTEGER;
i, j: INTEGER;
BEGIN (* BruteSearchLR2 *)
sLen := Length(s);
pLen := Length(p);
IF (pLen = 0) OR (sLen = 0) OR (pLen > sLen) THEN BEGIN
BruteSearchLR2 := 0;
END ELSE BEGIN
i := 1;
j := 1;
REPEAT
IF (Equals(s[i], p[j])) THEN BEGIN
Inc(i);
Inc(j);
END ELSE BEGIN
i := i - j + 2;
j := 1;
END; (* IF *)
UNTIL ((j > pLen) OR (i > sLen)); (* REPEAT *)
IF (j > pLen) THEN BEGIN
BruteSearchLR2 := i - pLen;
END ELSE BEGIN
BruteSearchLR2 := 0;
END; (* IF *)
END; (* IF *)
END; (* BruteSearchLR1 *)
FUNCTION BruteSearchRL(s, p: STRING): INTEGER;
VAR sLen, pLen: INTEGER;
i, j: INTEGER;
BEGIN (* BruteSearchRL *)
sLen := Length(s);
pLen := Length(p);
IF (pLen = 0) OR (sLen = 0) OR (pLen > sLen) THEN BEGIN
BruteSearchRL := 0;
END ELSE BEGIN
i := pLen;
j := pLen;
REPEAT
IF (Equals(s[i], p[j])) THEN BEGIN
Dec(i);
Dec(j);
END ELSE BEGIN
i := i + pLen - j + 1;
j := pLen;
END; (* IF *)
UNTIL ((j < 1) OR (i > sLen)); (* REPEAT *)
IF (j < 1) THEN
BruteSearchRL := i + 1
ELSE
BruteSearchRL := 0;
END; (* IF *)
END; (* BruteSearchRL *)
FUNCTION KnutMorrisPratt1(s, p: STRING): INTEGER;
VAR next: ARRAY[1..255] OF INTEGER;
sLen, pLen: INTEGER;
i, j: INTEGER;
PROCEDURE InitNext;
BEGIN (* InitNext *)
i := 1;
j := 0;
next[1] := 0;
WHILE (i < pLen) DO BEGIN
IF ((j = 0) OR Equals(p[i], p[j])) THEN BEGIN
Inc(i);
Inc(j);
next[i] := j;
END ELSE BEGIN
j := next[j];
END; (* IF *)
END; (* WHILE *)
END; (* InitNext *)
BEGIN (* KnutMorrisPratt1 *)
sLen := Length(s);
pLen := Length(p);
IF (pLen = 0) OR (sLen = 0) OR (pLen > sLen) THEN BEGIN
KnutMorrisPratt1 := 0;
END ELSE BEGIN
InitNext;
i := 1;
j := 1;
REPEAT
IF (j = 0) OR (Equals(s[i], p[j])) THEN BEGIN
Inc(i);
Inc(j);
END ELSE BEGIN
j := next[j];
END; (* IF *)
UNTIL ((j > pLen) OR (i > sLen)); (* REPEAT *)
IF (j > pLen) THEN BEGIN
KnutMorrisPratt1 := i - pLen;
END ELSE BEGIN
KnutMorrisPratt1 := 0;
END; (* IF *)
END; (* IF *)
END; (* KnutMorrisPratt2 *)
FUNCTION KnutMorrisPratt2(s, p: STRING): INTEGER;
VAR next: ARRAY[1..255] OF INTEGER;
sLen, pLen: INTEGER;
i, j: INTEGER;
PROCEDURE InitNext;
BEGIN (* InitNext *)
i := 1;
j := 0;
next[1] := 0;
WHILE (i < pLen) DO BEGIN
IF ((j = 0) OR Equals(p[i], p[j])) THEN BEGIN
Inc(i);
Inc(j);
IF (NOT Equals(p[i], p[j])) THEN
next[i] := j
ELSE
next[i] := next[j];
END ELSE BEGIN
j := next[j];
END; (* IF *)
END; (* WHILE *)
END; (* InitNext *)
BEGIN (* KnutMorrisPratt1 *)
sLen := Length(s);
pLen := Length(p);
IF (pLen = 0) OR (sLen = 0) OR (pLen > sLen) THEN BEGIN
KnutMorrisPratt2 := 0;
END ELSE BEGIN
InitNext;
i := 1;
j := 1;
REPEAT
IF (j = 0) OR (Equals(s[i], p[j])) THEN BEGIN
Inc(i);
Inc(j);
END ELSE BEGIN
j := next[j];
END; (* IF *)
UNTIL ((j > pLen) OR (i > sLen)); (* REPEAT *)
IF (j > pLen) THEN BEGIN
KnutMorrisPratt2 := i - pLen;
END ELSE BEGIN
KnutMorrisPratt2 := 0;
END; (* IF *)
END; (* IF *)
END; (* KnutMorrisPratt2 *)
FUNCTION BoyerMoore(s, p: STRING): INTEGER;
VAR skip: ARRAY[CHAR] OF INTEGER;
sLen, pLen: INTEGER;
i, j: INTEGER;
PROCEDURE InitSkip;
VAR ch: CHAR;
i: INTEGER;
BEGIN (* InitSkip *)
FOR ch := Low(skip) TO High(skip) DO BEGIN
skip[ch] := pLen;
END;(* FOR *)
FOR i := 1 TO pLen DO BEGIN
skip[p[i]] := pLen - i;
END; (* FOR *)
END; (* InitSkip *)
BEGIN (* BoyerMoore *)
sLen := Length(s);
pLen := Length(p);
InitSkip;
IF (pLen = 0) OR (sLen = 0) OR (pLen > sLen) THEN BEGIN
BoyerMoore := 0;
END ELSE BEGIN
i := pLen;
j := pLen;
REPEAT
IF (Equals(s[i], p[j])) THEN BEGIN
Dec(i);
Dec(j);
END ELSE BEGIN
IF (pLen - j + 1 > skip[s[i]]) THEN
i := i + pLen - j + 1
ELSE
i := i + skip[s[i]];
j := pLen;
END; (* IF *)
UNTIL ((j < 1) OR (i > sLen)); (* REPEAT *)
IF (j < 1) THEN
BoyerMoore := i + 1
ELSE
BoyerMoore := 0;
END; (* IF *)
END; (* BoyerMoore *)
FUNCTION RabinKarp(s, p: STRING): INTEGER;
CONST
B = 256; (* base of strings interpreted as number *)
Q = 8355967; (* large prime number *)
VAR sLen, pLen: INTEGER;
hp, hs: LONGINT; (* Hash of p, Hash of s *)
b_m: LONGINT; (* = B ^ (pLen - 1) *)
i, j, k: INTEGER;
BEGIN (* RabinKarp *)
sLen := Length(s);
pLen := Length(p);
IF (pLen = 0) OR (sLen = 0) OR (pLen > sLen) THEN BEGIN
RabinKarp := 0;
END ELSE BEGIN
b_m := 1;
FOR i := 1 TO pLen - 1 DO BEGIN
b_m := (b_m * B) MOD Q;
END; (* FOR *)
hp := 0;
hs := 0;
FOR i := 1 TO pLen DO BEGIN
hp := (hp * B + Ord(p[i])) MOD Q;
hs := (hs * B + Ord(s[i])) MOD Q;
END; (* FOR *)
i := 1;
j := 1;
WHILE ((i <= (sLen - pLen + 1)) AND (j <= pLen)) DO BEGIN
IF (hp = hs) THEN BEGIN
j := 1;
k := i;
WHILE ((j <= pLen) AND (Equals(s[k], p[j]))) DO BEGIN
Inc(j);
Inc(k);
END; (* WHILE *)
END; (* IF *)
hs := (hs + B * Q - Ord(s[i]) * b_m) MOD Q;
hs := (hs * B) MOD Q;
hs := (hs + Ord(s[i + plen])) MOD Q;
Inc(i);
END; (* WHILE *)
IF (j > pLen) THEN
RabinKarp := i - 1
ELSE
RabinKarp := 0;
END; (* IF *)
END; (* RabinKarp *)
PROCEDURE TestPatternMatcher(pm: PatternMatcher; pmName: STRING; s, p: STRING);
BEGIN (* TestPatternMatcher *)
Init;
Write(pmName, ': ', pm(s, p), ', comparisons: ');
WriteCharComps;
WriteLn();
END; (* TestPatternMatcher *)
var s, p: STRING;
BEGIN (* PatternMatching *)
REPEAT
Write('Enter s > ');
ReadLn(s);
Write('Enter p > ');
ReadLn(p);
TestPatternMatcher(BruteSearchLR1, 'BruteSearchLR1', s, p);
TestPatternMatcher(BruteSearchLR2, 'BruteSearchLR2', s, p);
TestPatternMatcher(BruteSearchRL, 'BruteSearchRL', s, p);
TestPatternMatcher(KnutMorrisPratt1, 'KMP1', s, p);
TestPatternMatcher(KnutMorrisPratt2, 'KMP2', s, p);
TestPatternMatcher(BoyerMoore, 'BoyerMoore', s, p);
TestPatternMatcher(RabinKarp, 'RabinKarp', s, p);
UNTIL (s = ''); (* REPEAT *)
END. (* PatternMatching *) |
unit UFrmReturnBill;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, UFrmBill, dxSkinsCore, dxSkinsdxBarPainter, dxSkinsDefaultPainters,
dxBar, cxClasses, ImgList, cxGraphics, Grids, AdvObj, BaseGrid, AdvGrid,
ExtCtrls, StdCtrls, cxControls, cxLookAndFeels, cxLookAndFeelPainters,
cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxButtonEdit, cxDropDownEdit,
cxCalendar, DB,
uDataRecord, DBClient, UFrameClient, UFrameStock;
type
TFrmReturnBill = class(TFrmBill)
lbl1: TLabel;
lbl2: TLabel;
edtWorker: TcxButtonEdit;
lbl6: TLabel;
edtRemark: TcxTextEdit;
lbl4: TLabel;
edtBillCode: TcxTextEdit;
lbl5: TLabel;
edtBillDate: TcxDateEdit;
CdsTemp: TClientDataSet;
lbl3: TLabel;
FrameStock1: TFrameStock;
FrameClient1: TFrameClient;
procedure advstrngrd1CanEditCell(Sender: TObject; ARow, ACol: Integer;
var CanEdit: Boolean);
procedure advstrngrd1GetAlignment(Sender: TObject; ARow, ACol: Integer;
var HAlign: TAlignment; var VAlign: TVAlignment);
procedure advstrngrd1GetEditorType(Sender: TObject; ACol, ARow: Integer;
var AEditor: TEditorType);
procedure FormShow(Sender: TObject);
procedure advstrngrd1KeyPress(Sender: TObject; var Key: Char);
procedure FormDestroy(Sender: TObject);
procedure edtWorkerKeyPress(Sender: TObject; var Key: Char);
procedure edtRemarkKeyPress(Sender: TObject; var Key: Char);
procedure edtBillCodeKeyPress(Sender: TObject; var Key: Char);
procedure edtBillDateKeyPress(Sender: TObject; var Key: Char);
procedure BtnSaveClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure BtnCancelClick(Sender: TObject);
procedure BtnAddLineClick(Sender: TObject);
procedure BtnInsertLineClick(Sender: TObject);
procedure BtnDelLineClick(Sender: TObject);
procedure advstrngrd1CellsChanged(Sender: TObject; R: TRect);
procedure FrameClient1edtClientKeyPress(Sender: TObject; var Key: Char);
procedure FrameStock1edtStockKeyPress(Sender: TObject; var Key: Char);
private
function GetBillCode: string;
function DoBeforeSaveBill: Boolean;
procedure DoSaveNoteInData;
procedure DoSelectGoods;
function DoCheckGoodsStock: Boolean;
procedure InitForm;
procedure AutoCalculate;
procedure SetLineNo;
function CheckGoodsCanReturn: Boolean;
public
end;
var
FrmNoteIn: TFrmReturnBill;
implementation
uses dxForms, UMsgBox, uSysObj, UDBAccess, UPubFunLib,
UFrmClientSelect, UFrmStockSelect, UFrmGoodsSelect, UDmBillBase;
{$R *.dfm}
procedure TFrmReturnBill.DoSelectGoods;
procedure SetClientValue(DataSet: TDataSet);
var
lRow: Integer;
begin
lRow := advstrngrd1.Row;
with advstrngrd1, DataSet do
begin
Cells[1, lRow] := FindField('GoodsID').AsString;
Cells[2, lRow] := FindField('GoodsName').AsString;
Cells[3, lRow] := FindField('GoodsType').AsString;
Cells[4, lRow] := FindField('GoodsUnit').AsString;
if Trim(Cells[5, lRow]) = '' then
Cells[5, lRow] := '1';
Cells[6, lRow] := FindField('GoodsPrice').AsString;
Cells[8, lRow] := FindField('Guid').AsString;
AutoCalculate;
end;
end;
begin
if not Assigned(FrmGoodsSelect) then
FrmGoodsSelect := TFrmGoodsSelect.Create(nil);
with FrmGoodsSelect, DmBillBase do
begin
//DoDataFilter(Trim(FrameClient1.edtClient.Text));
if CdsGoods.Active and (CdsGoods.RecordCount = 1) then
begin
SetClientValue(CdsGoods);
end
else
begin
if ShowModal = mrOk then
begin
SetClientValue(CdsGoods);
end;
end;
end;
end;
procedure TFrmReturnBill.advstrngrd1CanEditCell(Sender: TObject; ARow,
ACol: Integer; var CanEdit: Boolean);
begin
inherited;
case ACol of
1: CanEdit := Trim(advstrngrd1.Cells[1, ARow - 1]) <> '';
5, 6: CanEdit := Trim(advstrngrd1.Cells[1, ARow]) <> '';
else
CanEdit := False;
end;
end;
procedure TFrmReturnBill.AutoCalculate;
var
I, lRowCount: Integer;
lNum: Double;
begin
lNum := 0;
lRowCount := advstrngrd1.RowCount;
for I := 1 to lRowCount - 2 do
lNum := lNum + StrToFloatDef(Trim(advstrngrd1.Cells[5, I]), 0);
advstrngrd1.Cells[5, lRowCount - 1] := FormatFloat('0.####', lNum);
end;
procedure TFrmReturnBill.BtnAddLineClick(Sender: TObject);
begin
inherited;
advstrngrd1.InsertRows(advstrngrd1.RowCount - 1, 1);
advstrngrd1.Row := advstrngrd1.RowCount - 2;
SetLineNo;
end;
procedure TFrmReturnBill.BtnCancelClick(Sender: TObject);
begin
InitForm;
end;
procedure TFrmReturnBill.BtnDelLineClick(Sender: TObject);
var
iRow: Integer;
begin
inherited;
iRow := advstrngrd1.Row;
if (iRow = 0) or (iRow = advstrngrd1.RowCount - 1) then Exit;
if (iRow = 1) and (advstrngrd1.RowCount = 3) then
advstrngrd1.Rows[1].Clear
else
begin
advstrngrd1.RemoveRows(iRow, 1);
if iRow = advstrngrd1.RowCount - 1 then
advstrngrd1.Row := advstrngrd1.RowCount - 2;
end;
SetLineNo;
AutoCalculate;
advstrngrd1.Repaint;
end;
procedure TFrmReturnBill.BtnInsertLineClick(Sender: TObject);
var
iRow: Integer;
begin
inherited;
iRow := advstrngrd1.Row;
if (iRow = 0) then Exit;
advstrngrd1.InsertRows(iRow, 1);
SetLineNo;
end;
procedure TFrmReturnBill.BtnSaveClick(Sender: TObject);
begin
DoSaveNoteInData;
end;
procedure TFrmReturnBill.FormCreate(Sender: TObject);
begin
inherited;
DmBillBase := TDmBillBase.Create(nil);
end;
procedure TFrmReturnBill.FormDestroy(Sender: TObject);
begin
FreeAndNil(DmBillBase);
inherited;
end;
procedure TFrmReturnBill.FormShow(Sender: TObject);
begin
inherited;
advstrngrd1.ColWidths[0] := 40;
advstrngrd1.ColWidths[1] := 100;
advstrngrd1.ColWidths[2] := 200;
advstrngrd1.ColWidths[3] := 100;
advstrngrd1.ColWidths[4] := 100;
advstrngrd1.ColWidths[5] := 100;
advstrngrd1.ColWidths[6] := 200;
advstrngrd1.HideColumns(7, 8);
InitForm;
SetLineNo;
if not DmBillBase.OpenDataSets then
begin
pnlTop.Enabled := False;
advstrngrd1.Enabled := False;
ShowMsg('读取初始化数据失败!');
end;
end;
procedure TFrmReturnBill.FrameClient1edtClientKeyPress(Sender: TObject;
var Key: Char);
begin
FrameClient1.edtClientKeyPress(Sender, Key);
if Key = #13 then
begin
if FrameClient1.gClientGuid <> '' then
edtWorker.SetFocus;
end;
end;
procedure TFrmReturnBill.FrameStock1edtStockKeyPress(Sender: TObject;
var Key: Char);
begin
FrameStock1.edtStockKeyPress(Sender, Key);
if Key = #13 then
begin
if FrameStock1.gStockGuid <> '' then
edtRemark.SetFocus;
end;
end;
function TFrmReturnBill.GetBillCode: string;
var
lStrSql: string;
begin
lStrSql := 'declare @MaxID varchar(3) '+
' declare @Prefix varchar(10) '+
' set @Prefix=''GH'' + replace(CONVERT(VARCHAR(10), getdate(), 120), ''-'', '''') '+
' select @MaxID = CONVERT(VARCHAR(3), isnull(max(substring(ID, 11, 3)), 0) + 1) from ReturnBillH '+
' where substring(ID, 1, 10)=@Prefix '+
' select @Prefix + REPLICATE(''0'', 3 - len(@MaxID)) + @MaxID';
Result := DBAccess.GetSQLStringValue(lStrSql);
if Result = '' then
begin
ShowMsg('归还单号生成失败!');
Exit;
end;
end;
procedure TFrmReturnBill.InitForm;
var
I: Integer;
begin
FrameClient1.edtClient.SetFocus;
edtBillCode.Text := GetBillCode;
edtBillDate.Date := Date;
FrameClient1.edtClient.Text := '';
FrameClient1.gClientGuid := '';
edtWorker.Text := Sys.WorkerInfo.WorkerName;
FrameStock1.edtStock.Text := '';
FrameStock1.gStockGuid := '';
edtRemark.Text := '';
for I := 1 to advstrngrd1.RowCount - 2 do
advstrngrd1.Rows[I].Clear;
advstrngrd1.Cells[5, advstrngrd1.RowCount - 1] := '';
end;
procedure TFrmReturnBill.SetLineNo;
var
I: Integer;
begin
for I := 1 to advstrngrd1.RowCount - 2 do
advstrngrd1.Cells[0, I] := IntToStr(I);
advstrngrd1.Cells[0, advstrngrd1.RowCount - 1] := '合计';
end;
procedure TFrmReturnBill.advstrngrd1CellsChanged(Sender: TObject; R: TRect);
var
lValue: Double;
ARow, ACol: Integer;
begin
inherited;
ARow := advstrngrd1.Row;
ACol := advstrngrd1.Col;
if not (ACol in [5]) then Exit;
case ACol of
5:
begin
lValue := StrToFloatDef(Trim(advstrngrd1.Cells[5, ARow]), 0);
advstrngrd1.Cells[5, ARow] := FormatFloat('0.####', lValue);
end;
end;
AutoCalculate;
end;
procedure TFrmReturnBill.advstrngrd1GetAlignment(Sender: TObject; ARow,
ACol: Integer; var HAlign: TAlignment; var VAlign: TVAlignment);
begin
inherited;
if ARow > 0 then
begin
if ACol in [0, 4] then
HAlign := taCenter
else
HAlign := taLeftJustify;
end;
end;
procedure TFrmReturnBill.advstrngrd1GetEditorType(Sender: TObject; ACol,
ARow: Integer; var AEditor: TEditorType);
begin
inherited;
case ACol of
5: AEditor := edFloat;
else
AEditor := edNormal;
end;
end;
const
// 获取用户某个产品的租赁数量,如果=0表示不存在租赁信息,一次不能归还当前产品
GetGoodsLeaseNumSQL = 'select isnull(sum(D.Num), 0) from LeaseBillH M '+
' inner join LeaseBillD D on D.LeaseID=M.ID '+
' inner join GoodsInfo G on G.Guid=D.GoodsGuid '+
' where M.ClientGuid=''%s'' and G.GoodsID=''%s''';
function TFrmReturnBill.CheckGoodsCanReturn: Boolean;
var
iRow: Integer;
lNum: Double;
lGoodsID: string;
lStrSql: string;
begin
Result := False;
if FrameClient1.gClientGuid = '' then
begin
FrameClient1.edtClient.SetFocus;
ShowMsg('请先选择归还单位!');
Exit;
end;
iRow := advstrngrd1.Row;
lGoodsID := Trim(advstrngrd1.Cells[1, iRow]);
if lGoodsID = '' then Exit;
with DmBillBase.CdsGoods do
begin
if not Active or IsEmpty then
begin
ShowMsg('获取商品信息失败!');
Exit;
end;
if not Locate('GoodsID', lGoodsID, [loCaseInsensitive]) then
begin
ShowMsg('未找到当前商品编号对应的商品信息!');
Exit;
end;
end;
lStrSql := Format(GetGoodsLeaseNumSQL, [FrameClient1.gClientGuid, lGoodsID]);
if not DBAccess.ReadDataSet(lStrSql, CdsTemp) then
begin
ShowMsg('获取当前商品编号对应的商品租赁信息失败!');
Exit;
end;
if not CdsTemp.Active or CdsTemp.IsEmpty then
begin
ShowMsg('未获取到当前商品编号对应的商品租赁信息!');
Exit;
end;
lNum := CdsTemp.Fields[0].AsFloat;
if lNum = 0 then
begin
ShowMsg('不存在需要归还的当前商品编号对应的商品信息!');
Exit;
end;
with advstrngrd1, DmBillBase.CdsGoods do
begin
Cells[2, iRow] := FindField('GoodsName').AsString;
Cells[3, iRow] := FindField('GoodsType').AsString;
Cells[4, iRow] := FindField('GoodsUnit').AsString;
Cells[5, iRow] := FloatToStr(lNum);
Cells[7, iRow] := FindField('Guid').AsString;
Cells[8, iRow] := FloatToStr(lNum);
end;
AutoCalculate;
Result := True;
end;
procedure TFrmReturnBill.advstrngrd1KeyPress(Sender: TObject; var Key: Char);
begin
inherited;
if Key = #13 then
begin
Key := #0;
case advstrngrd1.Col of
1:
begin
if not CheckGoodsCanReturn then
begin
advstrngrd1.Rows[advstrngrd1.Row].Clear;
advstrngrd1.Cells[0, advstrngrd1.Row] := IntToStr(advstrngrd1.Row);
advstrngrd1.EditorMode := True;
Exit;
end;
advstrngrd1.Col := advstrngrd1.Col + 4;
end;
2..5: advstrngrd1.Col := advstrngrd1.Col + 1;
6:
begin
advstrngrd1.Col := 1;
advstrngrd1.Row := advstrngrd1.Row + 1;
advstrngrd1.EditorMode := True;
end;
end;
end;
end;
procedure TFrmReturnBill.edtBillCodeKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then
edtBillDate.SetFocus;
end;
procedure TFrmReturnBill.edtBillDateKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then
begin
advstrngrd1.SetFocus;
advstrngrd1.Row := 1;
advstrngrd1.Col := 1;
advstrngrd1.EditorMode := True;
end;
end;
procedure TFrmReturnBill.edtRemarkKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then
edtBillCode.SetFocus;
end;
procedure TFrmReturnBill.edtWorkerKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then
FrameStock1.edtStock.SetFocus;
end;
function TFrmReturnBill.DoCheckGoodsStock: Boolean;
const
GetGoodsStockSQL = 'select * from GoodsStock where StockGuid=''%s''';
var
I: Integer;
lNum, lStockNum: Double;
lGoodsGuid, lGoodsName: string;
lStrSql: string;
begin
Result := False;
lStrSql := Format(GetGoodsStockSQL, [FrameStock1.gStockGuid]);
if not DBAccess.ReadDataSet(lStrSql, CdsTemp) then
begin
ShowMsg('获取商品库存信息失败!');
Exit;
end;
for I := 1 to advstrngrd1.RowCount - 2 do
begin
if Trim(advstrngrd1.Cells[1, I]) = '' then
Continue;
lGoodsName := advstrngrd1.Cells[2, I];
lGoodsGuid := advstrngrd1.Cells[8, I];
lNum := StrToFloatDef(advstrngrd1.Cells[5, I], 0);
if CdsTemp.Locate('GoodsGuid', lGoodsGuid, [loCaseInsensitive]) then
begin
lStockNum := CdsTemp.FindField('TotalNum').AsFloat;
if lNum > lStockNum then
begin
ShowMsg(Format('“%s”仓库的“%s”库存不足!', [Trim(FrameStock1.edtStock.Text), lGoodsName]));
Exit;
end;
end
else
begin
ShowMsg(Format('“%s”仓库未找到“%s”的库存信息!', [Trim(FrameStock1.edtStock.Text), lGoodsName]));
Exit;
end;
end;
Result := True;
end;
function TFrmReturnBill.DoBeforeSaveBill: Boolean;
var
I, iCount: Integer;
begin
Result := False;
if Trim(FrameClient1.edtClient.Text) = '' then
begin
FrameClient1.edtClient.SetFocus;
ShowMsg('归还单位不能为空!');
Exit;
end;
if Trim(edtWorker.Text) = '' then
begin
edtWorker.SetFocus;
ShowMsg('经手人不能为空!');
Exit;
end;
if Trim(FrameStock1.edtStock.Text) = '' then
begin
FrameStock1.edtStock.SetFocus;
ShowMsg('收货仓库不能为空!');
Exit;
end;
if Trim(edtBillCode.Text) = '' then
begin
edtBillCode.SetFocus;
ShowMsg('单据编号不能为空!');
Exit;
end;
if Trim(edtBillDate.Text) = '' then
begin
edtBillDate.SetFocus;
ShowMsg('归还日期不能为空!');
Exit;
end;
iCount := 0;
for I := 1 to advstrngrd1.RowCount - 2 do
begin
if Trim(advstrngrd1.Cells[1, I]) <> '' then
Inc(iCount);
end;
if iCount = 0 then
begin
ShowMsg('归还单明细信息至少需要包含一条完整信息!');
Exit;
end;
// 判断单号是否重复
iCount := DBAccess.GetSQLIntegerValue('select count(*) from ReturnBillH where ID=' + QuotedStr(edtBillCode.Text));
if iCount = -1 then
begin
ShowMsg('检查归还单号是否重复失败!');
Exit;
end;
if iCount > 0 then
begin
ShowMsg('归还单号重复!');
Exit;
end;
// 此处判断库存是否充足
if not DoCheckGoodsStock then Exit;
Result := True;
end;
procedure TFrmReturnBill.DoSaveNoteInData;
const
InsLeaseBillHSQL = 'insert into ReturnBillH(ID, LeaseDate, ClientGuid, StockGuid, '+
' TotalNum, CreateMan, CreateTime, IsAffirm, AffirmMan, AffirmTime, Remark)'+
' values(''%s'', ''%s'', ''%s'', ''%s'', %f, ''%s'', getdate(), '+
' 1, ''%s'', getdate(), ''%s'')';
InsLeaseBillDSQL = 'insert into ReturnBillD(Guid, LeaseID, Line, GoodsGuid, Num, '+
' Price, Remark) '+
' values(''%s'', ''%s'', %d, ''%s'', %f, %f, ''%s'')';
UpdGoodsStockSQL = 'update GoodsStock set TotalNum=isnull(TotalNum, 0) - %f '+
' where GoodsGuid=''%s'' and StockGuid=''%s''';
var
lStrSql: string;
lList: TStrings;
I: Integer;
lBillCode, lGoodsGuid, lGuid, lRemark: string;
lTNum, lNum, lPrice: Double;
begin
if not DoBeforeSaveBill then Exit;
lList := TStringList.Create;
try
lBillCode := Trim(edtBillCode.Text);
lTNum := 0;
// 增加明细表记录
for I := 1 to advstrngrd1.RowCount - 2 do
begin
if Trim(advstrngrd1.Cells[1, I]) <> '' then
begin
lGuid := CreateGuid;
lNum := StrToFloat(Trim(advstrngrd1.Cells[5, I]));
lRemark := Trim(advstrngrd1.Cells[6, I]);
lGoodsGuid := Trim(advstrngrd1.Cells[7, I]);
lStrSql := Format(InsLeaseBillDSQL, [lGuid, lBillCode, I,
lGoodsGuid, lNum, lPrice, lRemark]);
lList.Add(lStrSql);
lStrSql := Format(UpdGoodsStockSQL, [lNum, lGoodsGuid, FrameStock1.gStockGuid]);
lList.Add(lStrSql);
lTNum := lTNum + lNum;
end;
end;
lStrSql := Format(InsLeaseBillHSQL, [lBillCode, DateToStr(edtBillDate.Date),
FrameClient1.gClientGuid, FrameStock1.gStockGuid, lTNum, Sys.WorkerInfo.WorkerID,
Sys.WorkerInfo.WorkerID, Trim(edtRemark.Text)]);
lList.Add(lStrSql);
if not DBAccess.ExecuteBatchSQL(lList) then
begin
ShowMsg('归还单保存失败!');
Exit;
end;
Self.InitForm;
finally
lList.Free;
end;
end;
initialization
dxFormManager.RegisterForm(TFrmReturnBill);
end.
|
unit BillContentExportView;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, GridFrame, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, cxStyles, dxSkinsCore,
dxSkinsDefaultPainters, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit,
cxNavigator, dxDateRanges, Data.DB, cxDBData, dxBarBuiltInMenu,
cxGridCustomPopupMenu, cxGridPopupMenu, Vcl.Menus, System.Actions,
Vcl.ActnList, dxBar, cxClasses, Vcl.ComCtrls, cxGridLevel, cxGridCustomView,
cxGridCustomTableView, cxGridTableView, cxGridBandedTableView,
cxGridDBBandedTableView, cxGrid, BillContentExportQry;
type
TViewBillContentExport = class(TfrmGrid)
procedure cxGridDBBandedTableViewCustomDrawGroupCell
(Sender: TcxCustomGridTableView; ACanvas: TcxCanvas;
AViewInfo: TcxGridTableCellViewInfo; var ADone: Boolean);
private
procedure CreateBandForColumns(AColumnArr: TArray<TcxGridDBBandedColumn>;
ABandCaption: string); overload;
procedure CreateBandForColumn(AColumn: TcxGridDBBandedColumn); overload;
procedure CreateBandForColumn(const AFieldName: string); overload;
procedure CreateBandForColumns(AFieldNames: TArray<String>;
ABandCaption: string); overload;
function GetclBillTitle: TcxGridDBBandedColumn;
function GetclSumSaleR: TcxGridDBBandedColumn;
function GetclBillNumber: TcxGridDBBandedColumn;
function GetclValue: TcxGridDBBandedColumn;
function GetW: TBillContentExportW;
procedure SetW(const Value: TBillContentExportW);
{ Private declarations }
protected
procedure InitColumns(AView: TcxGridDBBandedTableView); override;
public
function Export(const AFileName: string): String;
property clBillTitle: TcxGridDBBandedColumn read GetclBillTitle;
property clSumSaleR: TcxGridDBBandedColumn read GetclSumSaleR;
property clBillNumber: TcxGridDBBandedColumn read GetclBillNumber;
property clValue: TcxGridDBBandedColumn read GetclValue;
property W: TBillContentExportW read GetW write SetW;
{ Public declarations }
end;
implementation
uses
cxGridExportLink, System.Generics.Collections, GridSort, System.IOUtils;
{$R *.dfm}
procedure TViewBillContentExport.CreateBandForColumns
(AColumnArr: TArray<TcxGridDBBandedColumn>; ABandCaption: string);
var
ABand: TcxGridBand;
AChildBand: TcxGridBand;
AColumn: TcxGridDBBandedColumn;
begin
ABand := MainView.Bands.Add;
ABand.Caption := ABandCaption;
for AColumn in AColumnArr do
begin
AChildBand := MainView.Bands.Add;
AChildBand.Position.BandIndex := ABand.Index;
AChildBand.Caption := AColumn.Caption;
AColumn.Position.BandIndex := AChildBand.Index;
end;
end;
procedure TViewBillContentExport.CreateBandForColumn
(AColumn: TcxGridDBBandedColumn);
var
ABand: TcxGridBand;
begin
Assert(AColumn <> nil);
ABand := MainView.Bands.Add;
ABand.Caption := AColumn.Caption;
AColumn.Position.BandIndex := ABand.Index;
end;
procedure TViewBillContentExport.CreateBandForColumn(const AFieldName: string);
begin
CreateBandForColumn(MainView.GetColumnByFieldName(AFieldName));
end;
procedure TViewBillContentExport.CreateBandForColumns
(AFieldNames: TArray<String>; ABandCaption: string);
var
AColumn: TcxGridDBBandedColumn;
AFieldName: string;
L: TList<TcxGridDBBandedColumn>;
begin
L := TList<TcxGridDBBandedColumn>.Create;
try
for AFieldName in AFieldNames do
begin
AColumn := MainView.GetColumnByFieldName(AFieldName);
Assert(AColumn <> nil);
L.Add(AColumn);
end;
CreateBandForColumns(L.ToArray, ABandCaption);
finally
FreeAndNil(L);
end;
end;
procedure TViewBillContentExport.cxGridDBBandedTableViewCustomDrawGroupCell
(Sender: TcxCustomGridTableView; ACanvas: TcxCanvas;
AViewInfo: TcxGridTableCellViewInfo; var ADone: Boolean);
var
ARect: TRect;
AText: string;
// i: Integer;
begin
inherited;
// Определяемся с тексом
AText := AViewInfo.GridRecord.DisplayTexts[0];
// i := AText.IndexOf('-');
// AText := AText.Substring(i + 1);
// Определяемся с границами ячейки
ARect := AViewInfo.Bounds;
ACanvas.FillRect(ARect);
ARect.Left := ARect.Left + 30;
ACanvas.DrawText(AText, ARect, cxAlignLeft);
ADone := True;
end;
function TViewBillContentExport.Export(const AFileName: string): String;
var
AFileExt: string;
begin
MainView.DataController.Groups.FullExpand;
MainView.ApplyBestFit;
AFileExt := 'xls';
Result := TPath.ChangeExtension(AFileName, AFileExt);
// Экспортируем в Excel
ExportGridToExcel(Result, cxGrid, True, True, True, AFileExt);
// ExportViewToExcel(MainView, 'C:\Electronics DB\test.xls');
end;
function TViewBillContentExport.GetclBillTitle: TcxGridDBBandedColumn;
begin
Result := MainView.GetColumnByFieldName(W.BillTitle.FieldName);
end;
function TViewBillContentExport.GetclSumSaleR: TcxGridDBBandedColumn;
begin
Result := MainView.GetColumnByFieldName(W.SumSaleR.FieldName);
end;
function TViewBillContentExport.GetclBillNumber: TcxGridDBBandedColumn;
begin
Result := MainView.GetColumnByFieldName(W.BillNumber.FieldName);
end;
function TViewBillContentExport.GetclValue: TcxGridDBBandedColumn;
begin
Result := MainView.GetColumnByFieldName(W.Value.FieldName);
end;
function TViewBillContentExport.GetW: TBillContentExportW;
begin
Result := DSWrap as TBillContentExportW;
end;
procedure TViewBillContentExport.InitColumns(AView: TcxGridDBBandedTableView);
begin
inherited;
clBillTitle.GroupIndex := 0;
clBillTitle.Caption := '';
CreateBandForColumn(W.Value.FieldName);
// clValue.Position.Band.FixedKind := fkLeft;
CreateBandForColumn(W.StoreHouse.FieldName);
CreateBandForColumn(W.Producer.FieldName);
CreateBandForColumn(W.DescriptionComponentName.FieldName);
CreateBandForColumn(W.Datasheet.FieldName);
CreateBandForColumn(W.Diagram.FieldName);
CreateBandForColumn(W.Drawing.FieldName);
CreateBandForColumn(W.Image.FieldName);
CreateBandForColumn(W.ReleaseDate.FieldName);
CreateBandForColumn(W.Amount.FieldName);
CreateBandForColumn(W.Packaging.FieldName);
CreateBandForColumns([W.PriceR2.FieldName, W.PriceD2.FieldName,
W.PriceE2.FieldName], 'Оптовая цена');
CreateBandForColumns([W.PriceR1.FieldName, W.PriceD1.FieldName,
W.PriceE1.FieldName], 'Розничная цена (за 1 шт.)');
CreateBandForColumns([W.PriceR.FieldName, W.PriceD.FieldName,
W.PriceE.FieldName], 'Закупочная цена (без НДС)');
CreateBandForColumns([W.OriginCountryCode.FieldName,
W.OriginCountry.FieldName], 'Страна происхождения');
CreateBandForColumn(W.BatchNumber.FieldName);
CreateBandForColumn(W.CustomsDeclarationNumber.FieldName);
CreateBandForColumns([W.Storage.FieldName, W.StoragePlace.FieldName],
'Место хранения');
CreateBandForColumn(W.Seller.FieldName);
CreateBandForColumn(W.DocumentNumber.FieldName);
CreateBandForColumn(W.Barcode.FieldName);
CreateBandForColumn(W.LoadDate.FieldName);
CreateBandForColumns([W.Dollar.FieldName, W.Euro.FieldName], 'Курсы валют');
CreateBandForColumn(W.SaleCount.FieldName);
CreateBandForColumns([W.SaleR.FieldName, W.SaleD.FieldName,
W.SaleE.FieldName], 'Стоимость');
CreateBandForColumns([clSumSaleR], 'Итого');
clSumSaleR.Options.CellMerging := True;
GridSort.Add(TSortVariant.Create(clBillNumber, [clBillNumber, clValue]));
ApplySort(MainView, clBillNumber);
end;
procedure TViewBillContentExport.SetW(const Value: TBillContentExportW);
begin
if DSWrap = Value then
Exit;
DSWrap := Value;
end;
end.
|
unit BaseGridDetail;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseDocked, Data.DB, Vcl.StdCtrls,
Vcl.Mask, RzEdit, RzTabs, Vcl.Grids, Vcl.DBGrids, RzDBGrid, RzLabel,
Vcl.ExtCtrls, RzPanel, RzButton, System.ImageList, Vcl.ImgList,
SaveIntf, NewIntf;
type
TfrmBaseGridDetail = class(TfrmBaseDocked,ISave,INew)
pnlList: TRzPanel;
grList: TRzDBGrid;
pnlSearch: TRzPanel;
Label1: TLabel;
edSearchKey: TRzEdit;
pnlDetail: TRzPanel;
pnlAdd: TRzPanel;
sbtnNew: TRzShapeButton;
procedure FormCreate(Sender: TObject);
procedure edSearchKeyChange(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure sbtnNewClick(Sender: TObject);
private
{ Private declarations }
protected
procedure SearchList; virtual; abstract;
procedure BindToObject; virtual; abstract;
function EntryIsValid: boolean; virtual; abstract;
function NewIsAllowed: boolean; virtual; abstract;
function EditIsAllowed: boolean; virtual; abstract;
public
{ Public declarations }
function Save: boolean; virtual;
procedure Cancel; virtual;
procedure New; virtual;
end;
implementation
{$R *.dfm}
uses
FormsUtil;
procedure TfrmBaseGridDetail.edSearchKeyChange(Sender: TObject);
begin
inherited;
SearchList;
end;
procedure TfrmBaseGridDetail.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
OpenDropdownDataSources(pnlDetail,false);
OpenGridDataSources(pnlList,false);
inherited;
end;
procedure TfrmBaseGridDetail.FormCreate(Sender: TObject);
begin
inherited;
OpenGridDataSources(pnlList);
end;
procedure TfrmBaseGridDetail.FormShow(Sender: TObject);
begin
inherited;
OpenDropdownDataSources(pnlDetail);
end;
function TfrmBaseGridDetail.Save: boolean;
begin
Result := false;
with grList.DataSource.DataSet do
begin
if State in [dsInsert,dsEdit] then
begin
BindToObject;
if EntryIsValid then
begin
grList.DataSource.DataSet.Post;
grList.Enabled := true;
Result := true;
end
end;
end;
end;
procedure TfrmBaseGridDetail.sbtnNewClick(Sender: TObject);
begin
New;
end;
procedure TfrmBaseGridDetail.Cancel;
begin
grList.DataSource.DataSet.Cancel;
grList.Enabled := true;
end;
procedure TfrmBaseGridDetail.New;
begin
if NewIsAllowed then
begin
grList.DataSource.DataSet.Append;
// disable the grid
grList.Enabled := false;
// focus the first control
grList.DataSource.DataSet.FieldByName(grList.Columns[0].FieldName).FocusControl;
end;
end;
end.
|
// Copyright 2021 Darian Miller, Licensed under Apache-2.0
// SPDX-License-Identifier: Apache-2.0
// More info: www.radprogrammer.com
unit radRTL.HOTP;
interface
uses
System.SysUtils;
type
EOTPException = class(Exception);
// "Password generated must be at least 6, but can be 7 or 8" digits in length (simply changes the MOD operation) (9-digit addition suggested in errata: https://www.rfc-editor.org/errata/eid2400)
TOTPLength = (SixDigits, SevenDigits, EightDigits);
THOTP = class
private const
ModTable: array [0 .. 2] of integer = (1000000, 10000000, 100000000); // 6,7,8 zeros matching OTP Length
FormatTable: array [0 .. 2] of string = ('%.6d', '%.7d', '%.8d'); // 6,7,8 string length (padded left with zeros)
RFCMinimumKeyLengthBytes = 16; // length of shared secret MUST be 128 bits (16 bytes)
public
/// <summary> HOTP: HMAC-Based One-Time Password Algorithm</summary>
class function GeneratePassword(const pBase32EncodedSecretKey:string; const pCounterValue:Int64; const pOutputLength:TOTPLength = TOTPLength.SixDigits):string; overload;
class function GeneratePassword(const pPlainTextSecretKey:TBytes; const pCounterValue:Int64; const pOutputLength:TOTPLength = TOTPLength.SixDigits):string; overload;
end;
resourcestring
sOTPKeyLengthTooShort = 'Key length must be at least 128bits';
implementation
uses
System.Hash,
radRTL.Base32Encoding,
radRTL.ByteArrayUtils;
class function THOTP.GeneratePassword(const pBase32EncodedSecretKey:string; const pCounterValue:Int64; const pOutputLength:TOTPLength = TOTPLength.SixDigits):string;
var
vEncodedKey:TBytes;
vDecodedKey:TBytes;
begin
vEncodedKey := TEncoding.UTF8.GetBytes(pBase32EncodedSecretKey); // assume secret was stored as UTF8 (prover and verifier must match)
vDecodedKey := TBase32.Decode(vEncodedKey);
Result := GeneratePassword(vDecodedKey, pCounterValue, pOutputLength);
end;
// https://datatracker.ietf.org/doc/html/rfc4226
class function THOTP.GeneratePassword(const pPlainTextSecretKey:TBytes; const pCounterValue:Int64; const pOutputLength:TOTPLength = TOTPLength.SixDigits):string;
var
vData:TBytes;
vHMAC:TBytes;
vOffset:integer;
vBinCode:integer;
vPinNumber:integer;
begin
if Length(pPlainTextSecretKey) < RFCMinimumKeyLengthBytes then
begin
// RFC minimum length required (Note: did not see this limitation in other implementations)
raise EOTPException.CreateRes(@sOTPKeyLengthTooShort);
end;
vData := ReverseByteArray(ConvertToByteArray(pCounterValue)); // RFC reference implmentation reversed order of CounterValue (movingFactor) bytes
vHMAC := THashSHA1.GetHMACAsBytes(vData, pPlainTextSecretKey); // SHA1 = 20 byte digest
// rfc notes: extract a 4-byte dynamic binary integer code from the HMAC result
vOffset := vHMAC[19] and $0F; // extract a random number 0 to 15 (from the value of the very last byte of the hash digest AND 0000-1111)
// 4 bytes extracted starting at this random offset (first bit intentionally zero'ed to avoid compatibility problems with signed vs unsigned MOD operations)
vBinCode := ((vHMAC[vOffset] and $7F) shl 24) // byte at offset AND 0111-1111 moved to first 8 bits of result
or (vHMAC[vOffset + 1] shl 16) or (vHMAC[vOffset + 2] shl 8) or vHMAC[vOffset + 3];
// trim 31-bit unsigned value to 6 to 8 digits in length
vPinNumber := vBinCode mod THOTP.ModTable[Ord(pOutputLength)];
// Format the 6 to 8 digit OTP result by padding left with zeros as needed
Result := Format(FormatTable[Ord(pOutputLength)], [vPinNumber]);
end;
end.
|
unit APesarCartucho;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios,
StdCtrls, Buttons, Mask, numericos, Componentes1, Localizacao, ExtCtrls,
PainelGradiente, UnToledo, DBKeyViolation, UnArgox, UnDadosProduto, Menus;
type
TFPesarCartucho = class(TFormularioPermissao)
PainelGradiente1: TPainelGradiente;
PanelColor1: TPanelColor;
PanelColor2: TPanelColor;
Localiza: TConsultaPadrao;
Label8: TLabel;
SpeedButton2: TSpeedButton;
LNomProduto: TLabel;
EProduto: TEditLocaliza;
EPeso: Tnumerico;
Label1: TLabel;
Label2: TLabel;
BPesar: TBitBtn;
BFechar: TBitBtn;
ESequencial: Tnumerico;
Label3: TLabel;
Label4: TLabel;
SpeedButton5: TSpeedButton;
Label10: TLabel;
ECelulaTrabalho: TEditLocaliza;
ValidaGravacao1: TValidaGravacao;
CCilindroNovo: TCheckBox;
BitBtn1: TBitBtn;
CChipNovo: TCheckBox;
PopupMenu1: TPopupMenu;
ReimprimirEtiqueta1: TMenuItem;
Label5: TLabel;
SpeedButton1: TSpeedButton;
Label6: TLabel;
EPo: TEditLocaliza;
Label7: TLabel;
SpeedButton3: TSpeedButton;
Label9: TLabel;
ECilindro: TEditLocaliza;
Label11: TLabel;
SpeedButton4: TSpeedButton;
Label12: TLabel;
EChip: TEditLocaliza;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BFecharClick(Sender: TObject);
procedure BPesarClick(Sender: TObject);
procedure ECelulaTrabalhoCadastrar(Sender: TObject);
procedure EProdutoChange(Sender: TObject);
procedure BitBtn1Click(Sender: TObject);
procedure EProdutoRetorno(Retorno1, Retorno2: String);
procedure ReimprimirEtiqueta1Click(Sender: TObject);
procedure CCilindroNovoClick(Sender: TObject);
procedure EPoRetorno(Retorno1, Retorno2: String);
procedure ECilindroRetorno(Retorno1, Retorno2: String);
procedure EChipRetorno(Retorno1, Retorno2: String);
procedure EPoSelect(Sender: TObject);
procedure ECilindroSelect(Sender: TObject);
procedure EChipSelect(Sender: TObject);
private
{ Private declarations }
VprSeqPo,
VprSeqCilindro,
VprSeqChip : INteger;
FunArgox : TRBFuncoesArgox;
FunArgox2 : TRBFuncoesArgox;
VprDProduto : TRBDProduto;
VprDCartucho : TRBDPesoCartucho;
procedure InicializaTela;
procedure CarDClasse;
procedure ImprimeEtiqueta(VpaReimprimir : Boolean);
public
{ Public declarations }
end;
var
FPesarCartucho: TFPesarCartucho;
implementation
uses APrincipal, ConstMsg, constantes, ACelulaTrabalho, Unprodutos;
{$R *.DFM}
{ ****************** Na criação do Formulário ******************************** }
procedure TFPesarCartucho.FormCreate(Sender: TObject);
var
VpfResultado : String;
begin
VprDCartucho := TRBDPesoCartucho.cria;
VprDProduto := TRBDProduto.cria;
VprDProduto.CodEmpresa := VARIA.CodigoEmpresa;
VprDProduto.CodEmpFil := Varia.CodigoEmpFil;
FunArgox := TRBFuncoesArgox.cria(Varia.PortaComunicacaoImpTermica);
if AbrePorta(VARIA.PortaComunicacaoBalanca,0,1,0)= cfalha then
aviso('ERRO NA ABERTURA DA PORTA!!!'#13'Não foi possível o programa se comunicar com a balança');
if varia.OperacaoEstoqueImpressaoEtiqueta = 0 then
aviso('OPERAÇÃO ESTOQUE IMPRESSAO ETIQUETA NÃO PREENCHIDO!!!'#13'É necessário preencher nas configurações do produto a operacao de estoque de impressão de etiqueta');
InicializaTela;
{ abre tabelas }
{ chamar a rotina de atualização de menus }
end;
{ ******************* Quando o formulario e fechado ************************** }
procedure TFPesarCartucho.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{ fecha tabelas }
{ chamar a rotina de atualização de menus }
VprDProduto.free;
// VprDCartucho.free;
FunArgox.Free;
Action := CaFree;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Ações Diversas
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
procedure TFPesarCartucho.InicializaTela;
begin
VprDCartucho.free;
VprDCartucho := TRBDPesoCartucho.cria;
EProduto.clear;
ECelulaTrabalho.clear;
EPeso.clear;
ESequencial.clear;
ValidaGravacao1.execute;
end;
{******************************************************************************}
procedure TFPesarCartucho.CarDClasse;
begin
VprDCartucho.free;
VprDCartucho := TRBDPesoCartucho.cria;
VprDCartucho.SeqCartucho := ESequencial.AsInteger;
VprDCartucho.SeqProduto := VprDProduto.SeqProduto;
VprDCartucho.SeqPo := VprSeqPo;
VprDCartucho.SeqCilindro := VprSeqCilindro;
VprDCartucho.SeqChip := VprSeqChip;
VprDCartucho.CodUsuario := varia.CodigoUsuario;
VprDCartucho.CodCelula := ECelulaTrabalho.AInteiro;
VprDCartucho.DatPeso :=now;
VprDCartucho.PesCartucho := EPeso.AsInteger;
VprDCartucho.CodProduto := VprDProduto.CodProduto;
VprDCartucho.NomProduto := VprDProduto.NomProduto;
VprDCartucho.CodReduzidoCartucho := VprDProduto.CodReduzidoCartucho;
VprDCartucho.IndCilindroNovo := CCilindroNovo.Checked;
VprDCartucho.IndChipNovo := CChipNovo.Checked;
VprDCartucho.DesTipoCartucho := VprDProduto.DesTipoCartucho;
VprDCartucho.QtdMLCartucho := VprDProduto.QtdMlCartucho;
if VprDProduto.CodCorCartucho <> 0 then
VprDCartucho.NomCorCartucho := FunProdutos.RNomeCor(IntToStr(VprDProduto.CodCorCartucho))
else
VprDCartucho.NomCorCartucho := '';
end;
{******************************************************************************}
procedure TFPesarCartucho.ImprimeEtiqueta(VpaReimprimir : Boolean);
var
VpfNomProduto : string;
VpfResultado : String;
begin
VpfResultado := '';
CarDClasse;
if not VpaReimprimir then
begin
VpfREsultado := FunProdutos.GravaPesoCartucho(VprDCartucho,VprDProduto );
end;
if VpfResultado = '' then
begin
if VprDProduto.CodReduzidoCartucho <> '' then
VpfNomProduto := EProduto.Text+'-'+VprDProduto.CodReduzidoCartucho
else
VpfNomProduto := EProduto.Text+'-'+LNomProduto.Caption;
FunArgox.ImprimeEtiqueta(VprDCartucho);
FunArgox.free;
FunArgox := TRBFuncoesArgox.cria(Varia.PortaComunicacaoImpTermica);
VprDCartucho := TRBDPesoCartucho.cria;
end
else
aviso(VpfResultado);
end;
{******************************************************************************}
procedure TFPesarCartucho.BFecharClick(Sender: TObject);
begin
close;
end;
{******************************************************************************}
procedure TFPesarCartucho.BPesarClick(Sender: TObject);
var
Peso: array[0..5]of Ansichar;
begin
if PegaPeso(1,Peso,pAnsichar('')) = cSucesso then
begin
EPeso.Text:=StrPas(Peso);
// EPeso.Text:='100';
ESequencial.AsInteger := FunProdutos.RSeqCartuchoDisponivel;
if VprDProduto.PesCartucho <> 0 then
begin
if EPeso.AsInteger < (VprDProduto.PesCartucho * 0.9) then
aviso('PESO DO CARTUCHO INFERIOR A 10%!!!!'#13'O peso ideal para esse cartucho é de '+IntToStr(VprDProduto.PesCartucho)+'g');
end;
ImprimeEtiqueta(false);
end
else
aviso('ERRO NA LEITURA!!!'#13'Ocorreu um erro na leitura do peso.');
end;
{******************************************************************************}
procedure TFPesarCartucho.ECelulaTrabalhoCadastrar(Sender: TObject);
begin
FCelulaTrabalho := tFCelulaTrabalho.CriarSDI(self,'',FPrincipal.VerificaPermisao('FCelulaTrabalho'));
FCelulaTrabalho.BotaoCadastrar1.Click;
FCelulaTrabalho.showmodal;
FCelulaTrabalho.free;
Localiza.AtualizaConsulta;
end;
{******************************************************************************}
procedure TFPesarCartucho.EProdutoChange(Sender: TObject);
begin
ValidaGravacao1.execute;
end;
{******************************************************************************}
procedure TFPesarCartucho.BitBtn1Click(Sender: TObject);
begin
FunArgox.VoltarEtiqueta;
end;
{******************************************************************************}
procedure TFPesarCartucho.EProdutoRetorno(Retorno1, Retorno2: String);
begin
if Retorno1 <> '' then
begin
VprDProduto.SeqProduto := StrToInt(Retorno1);
FunProdutos.CarDProduto(VprDProduto);
CCilindroNovo.Checked := VprDProduto.IndCilindroNovo;
CChipNovo.Checked := VprDProduto.IndChipNovo;
end;
end;
{******************************************************************************}
procedure TFPesarCartucho.ReimprimirEtiqueta1Click(Sender: TObject);
begin
ImprimeEtiqueta(true);
end;
{******************************************************************************}
procedure TFPesarCartucho.CCilindroNovoClick(Sender: TObject);
begin
// CCilindroNovo.Checked := VprDProduto.IndCilindroNovo;
end;
{******************************************************************************}
procedure TFPesarCartucho.EPoRetorno(Retorno1, Retorno2: String);
begin
if Retorno1 <> '' then
VprSeqPo := StrToInt(Retorno1)
else
VprSeqPo := 0;
end;
{******************************************************************************}
procedure TFPesarCartucho.ECilindroRetorno(Retorno1, Retorno2: String);
begin
if Retorno1 <> '' then
VprSeqCilindro := StrToInt(Retorno1)
else
VprSeqCilindro := 0;
end;
{******************************************************************************}
procedure TFPesarCartucho.EChipRetorno(Retorno1, Retorno2: String);
begin
if Retorno1 <> '' then
VprSeqChip := StrToInt(Retorno1)
else
VprSeqChip := 0;
end;
{******************************************************************************}
procedure TFPesarCartucho.EPoSelect(Sender: TObject);
begin
EPo.ASelectLocaliza.Text:= 'Select C_COD_PRO, C_NOM_PRO, I_SEQ_PRO from CADPRODUTOS'+
' Where C_NOM_PRO like ''@%'' '+
' and C_ATI_PRO = ''S'' '+
' AND C_COD_CLA LIKE '''+Varia.CodClassificacaoPoTinta+'%'' ';
EPo.ASelectValida.Text:= 'Select * from CADPRODUTOS'+
' Where C_COD_PRO = ''@'' and C_ATI_PRO = ''S'' '+
' AND C_COD_CLA LIKE '''+Varia.CodClassificacaoPoTinta+'%'' ';
end;
{******************************************************************************}
procedure TFPesarCartucho.ECilindroSelect(Sender: TObject);
begin
ECilindro.ASelectLocaliza.Text:= 'Select C_COD_PRO, C_NOM_PRO, I_SEQ_PRO from CADPRODUTOS'+
' Where C_NOM_PRO like ''@%'' '+
' and C_ATI_PRO = ''S'' '+
' AND C_COD_CLA LIKE '''+Varia.CodClassificacaoCilindro+'%'' ';
ECilindro.ASelectValida.Text:= 'Select * from CADPRODUTOS'+
' Where C_COD_PRO = ''@'' and C_ATI_PRO = ''S'''+
' AND C_COD_CLA LIKE '''+Varia.CodClassificacaoCilindro+'%'' ';
end;
{******************************************************************************}
procedure TFPesarCartucho.EChipSelect(Sender: TObject);
begin
EChip.ASelectLocaliza.Text:= 'Select C_COD_PRO, C_NOM_PRO, I_SEQ_PRO from CADPRODUTOS'+
' Where C_NOM_PRO like ''@%'' '+
' and C_ATI_PRO = ''S'' '+
' AND C_COD_CLA LIKE '''+Varia.CodClassificacaoChip+'%'' ';
EChip.ASelectValida.Text:= 'Select * from CADPRODUTOS'+
' Where C_COD_PRO = ''@'' and C_ATI_PRO = ''S'' '+
' AND C_COD_CLA LIKE '''+Varia.CodClassificacaoChip+'%'' ';
end;
Initialization
{ *************** Registra a classe para evitar duplicidade ****************** }
RegisterClasses([TFPesarCartucho]);
end.
|
unit UnitRepository;
interface
uses
SysUtils;
function GetUserFolder(UserId: string): string;
function GetDesktopFolder(UserId: string): string;
function GetWebcamFolder(UserId: string): string;
function GetMicrophoneFolder(UserId: string): string;
function GetKeyloggerFolder(UserId: string): string;
function GetPasswordsFolder(UserId: string): string;
function GetDownloadsFolder(UserId: string): string;
implementation
function GetUserFolder(UserId: string): string;
var
TmpStr: string;
begin
TmpStr := ExtractFilePath(ParamStr(0)) + 'Users';
if not DirectoryExists(TmpStr) then CreateDir(TmpStr);
TmpStr := TmpStr + '\' + UserId;
if not DirectoryExists(TmpStr) then CreateDir(TmpStr);
Result := TmpStr;
end;
function GetDesktopFolder(UserId: string): string;
var
TmpStr: string;
begin
TmpStr := GetUserFolder(UserId);
TmpStr := TmpStr + '\Desktop';
if not DirectoryExists(TmpStr) then CreateDir(TmpStr);
Result := TmpStr;
end;
function GetWebcamFolder(UserId: string): string;
var
TmpStr: string;
begin
TmpStr := GetUserFolder(UserId);
TmpStr := TmpStr + '\Webcam';
if not DirectoryExists(TmpStr) then CreateDir(TmpStr);
Result := TmpStr;
end;
function GetMicrophoneFolder(UserId: string): string;
var
TmpStr: string;
begin
TmpStr := GetUserFolder(UserId);
TmpStr := TmpStr + '\Microphone';
if not DirectoryExists(TmpStr) then CreateDir(TmpStr);
Result := TmpStr;
end;
function GetPasswordsFolder(UserId: string): string;
var
TmpStr: string;
begin
TmpStr := GetUserFolder(UserId);
TmpStr := TmpStr + '\Passwords';
if not DirectoryExists(TmpStr) then CreateDir(TmpStr);
Result := TmpStr;
end;
function GetKeyloggerFolder(UserId: string): string;
var
TmpStr: string;
begin
TmpStr := GetUserFolder(UserId);
TmpStr := TmpStr + '\Keylogger';
if not DirectoryExists(TmpStr) then CreateDir(TmpStr);
Result := TmpStr;
TmpStr := TmpStr + '\Offline keylogger';
if not DirectoryExists(TmpStr) then CreateDir(TmpStr);
end;
function GetDownloadsFolder(UserId: string): string;
var
TmpStr: string;
begin
TmpStr := GetUserFolder(UserId);
TmpStr := TmpStr + '\Downloads';
if not DirectoryExists(TmpStr) then CreateDir(TmpStr);
Result := TmpStr;
end;
end.
|
unit LandlordDetail;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BasePopupDetail, Vcl.StdCtrls, Vcl.Mask,
RzEdit, RzDBEdit, RzButton, RzTabs, RzLabel,
Vcl.Imaging.pngimage, Vcl.ExtCtrls, RzPanel;
type
TfrmLandlordDetail = class(TfrmBasePopupDetail)
edMiddle: TRzDBEdit;
edFirstname: TRzDBEdit;
edLastname: TRzDBEdit;
RzDBEdit11: TRzDBEdit;
RzDBEdit10: TRzDBEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
private
{ Private declarations }
public
{ Public declarations }
protected
procedure Save; override;
procedure Cancel; override;
procedure BindToObject; override;
function ValidEntry: boolean; override;
end;
var
frmLandlordDetail: TfrmLandlordDetail;
implementation
{$R *.dfm}
uses
EntitiesData, Landlord, IFinanceDialogs;
procedure TfrmLandlordDetail.BindToObject;
begin
inherited;
end;
procedure TfrmLandlordDetail.Cancel;
begin
inherited;
llord.Cancel;
end;
procedure TfrmLandlordDetail.Save;
begin
llord.Save;
end;
function TfrmLandlordDetail.ValidEntry: boolean;
var
error: string;
begin
if Trim(edLastname.Text) = '' then error := 'Please enter a lastname.'
else if Trim(edFirstname.Text) = '' then error := 'Please enter a firstname.';
Result := error = '';
if not Result then ShowErrorBox(error);
end;
end.
|
unit ClassNulovy;
interface
uses ExtCtrls, Windows, MojeTypy;
type TNulovy = class
protected
Image : TImage;
public
Hotovo : boolean;
NasielRiesenie : boolean;
Funkcia : TMojaFunkcia;
Stred : TPoint;
NakresliL, NakresliP : real;
PocitajL, PocitajP : real;
Presnost : real;
constructor Create( iLavy, iPravy : real; iImage : TImage );
destructor Destroy; override;
procedure NakresliFunkciu;
procedure RiesFunkciu;
procedure Krok; virtual; abstract;
end;
implementation
uses Graphics;
//==============================================================================
//==============================================================================
//
// Constructor
//
//==============================================================================
//==============================================================================
constructor TNulovy.Create( iLavy, iPravy : real; iImage : TImage );
begin
inherited Create;
Image := iImage;
Stred.X := Image.Width div 2;
Stred.Y := Image.Height div 2;
Hotovo := False;
end;
//==============================================================================
//==============================================================================
//
// Destructor
//
//==============================================================================
//==============================================================================
destructor TNulovy.Destroy;
begin
inherited;
end;
//==============================================================================
//==============================================================================
//
// I N T E R F A C E
//
//==============================================================================
//==============================================================================
procedure TNulovy.NakresliFunkciu;
var I : integer;
A, B : integer;
begin
A := Round( NakresliL );
B := Round( NakresliP );
if A < -Stred.X then A := -Stred.X;
if A > Stred.X then exit;
if B < -Stred.X then exit;
if B > Stred.X then B := Stred.X;
with Image.Canvas do
begin
Brush.Color := clBlack;
FillRect( Image.ClientRect );
Pen.Color := clGray;
MoveTo( 0 , Stred.Y );
LineTo( Image.Width , Stred.Y );
MoveTo( Stred.X , 0 );
LineTo( Stred.X , Image.Height );
Pen.Color := clYellow;
end;
Image.Canvas.MoveTo( Round( Stred.X + NakresliL ) , Round( Stred.Y - Funkcia( NakresliL ) ) );
for I := A+1 to B do
Image.Canvas.LineTo( Stred.X + I , Round( Stred.Y - Funkcia( I ) ) );
end;
procedure TNulovy.RiesFunkciu;
begin
while not Hotovo do Krok;
end;
end.
|
unit ufrmFeed;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
FMX.Header, FMX.Layouts,uDmPrincipal, FMX.Objects, FMX.Ani, FMX.ExtCtrls,
FMX.Effects, FMX.Edit, FMX.Controls.Presentation,uServico;
type
TfrmFeed = class(TForm)
VertScrollBoxFundo: TVertScrollBox;
pnlTitulo: TPanel;
lblTitulo: TLabel;
tmrAtualizaFeed: TTimer;
RetanguloMenu: TRectangle;
AniFloatMenu: TFloatAnimation;
ShadowEffect1: TShadowEffect;
imgMenu: TImage;
pnlPesquisa: TPanel;
imgPesquisar: TImage;
edtPesquisar: TEdit;
retanguloNovo: TRectangle;
ShadowEffect2: TShadowEffect;
imgNovo: TImage;
RetanguloFinalizar: TRectangle;
imgFinalizar: TImage;
spdNovo: TSpeedButton;
spdFinalizar: TSpeedButton;
spdCarregarMais: TSpeedButton;
imgLoading: TImage;
FloatAnimationRotacaoImg: TFloatAnimation;
procedure tmrAtualizaFeedTimer(Sender: TObject);
procedure SpeedButton1Click(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure spdNovoClick(Sender: TObject);
procedure imgMenuClick(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure lblFinalizarClick(Sender: TObject);
procedure imgFinalizarClick(Sender: TObject);
procedure VertScrollBoxFundoClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure imgNovoClick(Sender: TObject);
procedure spdFinalizarClick(Sender: TObject);
procedure imgPesquisarClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure spdCarregarMaisClick(Sender: TObject);
private
{ Private declarations }
procedure AbrirNoticia(Sender : TObject; PertenceAoUsuario:boolean);
procedure CriaNovaNoticia(var Servico :TServico);
procedure CriaComponentesNoticia(Servico: TServico; ParentPrincipal : TFmxObject);
procedure EventoClickPanelNoticia(Sender : TObject);
procedure FinalizarApp;
procedure AddNovaNoticia;
procedure AtualizarFeed;
procedure AtivarLoading;
procedure DesativarLoading;
var
{Componentes criados em tempo de execução}
nCallPnlNoticiaPrincipal : TCalloutPanel;
nPnlNoticiaTop,nPnlNoticiaMid ,nPnlNoticiaBot : TPanel;
nLineSeparador : TLine;
nlblCodigo,nlblDataHora,nlblAutorTit,nlblAutor,nlblDescricaoTit,nlblDescricao :TLabel;
ultIdFeed : Integer;
efeitoBlur : TBlurEffect;
public
{ Public declarations }
end;
var
frmFeed: TfrmFeed;
implementation
{$R *.fmx}
uses uFrmNoticia, FireDAC.Comp.Client ;
{ TfrmFeed }
procedure TfrmFeed.AbrirNoticia(Sender: TObject;PertenceAoUsuario:boolean);
var
DadosNoticia : TServico;
ListaServicos : TStringList;
lQryAcao : TFdQuery;
lQryServicos : TFdQuery;
CodNoticia : Integer;
i : Integer;
NomeComponente : String;
begin
{Pesquisar as informações da Notiícia}
NomeComponente := TFmxObject(Sender).Name;
CodNoticia := StrToInt(Copy(NomeComponente, pos('_',NomeComponente)+1,Length(NomeComponente)) );
DadosNoticia := TServico.Create;
ListaServicos := TStringList.Create;
lQryAcao := TFDQuery.Create(Self);
lQryAcao.Connection := dmPrincipal.SQLiteConn;
lQryServicos := TFDQuery.Create(Self);
lQryServicos.Connection := dmPrincipal.SQLiteConn;
if not Assigned(frmNoticia) then
begin
frmNoticia := TfrmNoticia.Create(Self);
end;
try
{Passar para o DadosNoticia os valores de suas variaveis publicas,
através da busca pelo código}
lQryAcao.SQL.Add(' SELECT ID ');
lQryAcao.SQL.Add(' ,COD_NOTICIA');
lQryAcao.SQL.Add(' ,AUTOR');
lQryAcao.SQL.Add(' ,DESCRICAO ');
lQryAcao.SQL.Add(' ,DT_POSTAGEM ');
lQryAcao.SQL.Add(' ,DT_CHEGADA ');
lQryAcao.SQL.Add(' ,DT_SAIDA ');
lQryAcao.SQL.Add(' ,EQUIPAMENTO ');
lQryAcao.SQL.Add(' ,OBSERVACAO ');
lQryAcao.SQL.Add(' ,CLIENTE ');
lQryAcao.SQL.Add('FROM NOTICIASFEED');
lQryAcao.SQL.Add('WHERE COD_NOTICIA = :COD_NOTICIA');
lQryAcao.ParamByName('COD_NOTICIA').AsInteger := CodNoticia;
lQryAcao.Open();
DadosNoticia.CodServico := lQryAcao.FieldByName('COD_NOTICIA').AsInteger;
DadosNoticia.dtChegada := lQryAcao.FieldByName('DT_CHEGADA').AsDateTime;
DadosNoticia.dtSaida := lQryAcao.FieldByName('DT_SAIDA').AsDateTime;
DadosNoticia.DescricaoRapida := lQryAcao.FieldByName('DESCRICAO').AsString;
DadosNoticia.Observacoes := lQryAcao.FieldByName('OBSERVACAO').AsString;
DadosNoticia.Autor := lQryAcao.FieldByName('AUTOR').AsString;
DadosNoticia.Cliente := lQryAcao.FieldByName('CLIENTE').AsString;
lQryServicos.SQL.Add('SELECT DESCRICAO');
lQryServicos.SQL.Add('FROM ACOESREALIZADAS');
lQryServicos.SQL.Add('WHERE COD_NOTICIA = :COD_NOTICIA');
lQryServicos.ParamByName('COD_NOTICIA').AsInteger := CodNoticia;
lQryServicos.Open();
lQryServicos.First;
while not lQryServicos.Eof do
begin
ListaServicos.Add(lQryServicos.FieldByName('DESCRICAO').AsString);
lQryServicos.Next;
end;
DadosNoticia.listaAcoesRealizadas.Text := ListaServicos.Text;
if PertenceAoUsuario then
begin
frmNoticia.HabilitaEdicao;
end
else
begin
frmNoticia.DesabilitaEdicao;
end;
frmNoticia.RecebeNoticia(DadosNoticia);
frmNoticia.Show;
finally
DadosNoticia.Free;
ListaServicos.Free;
lQryAcao.Free;
lQryServicos.Free;
end;
end;
procedure TfrmFeed.CriaComponentesNoticia(Servico: TServico; ParentPrincipal : TFmxObject);
var
i : Integer;
PosYAnterior : Single;
PosYMaior : Single;
begin
{Painel principal da noticia}
spdCarregarMais.Visible := False; {Sumir o botão de atualizar}
nCallPnlNoticiaPrincipal := TCalloutPanel.Create(ParentPrincipal);
nCallPnlNoticiaPrincipal.Opacity := 0;
nCallPnlNoticiaPrincipal.Parent := ParentPrincipal;
nCallPnlNoticiaPrincipal.Name := 'nCallPnlNoticiaPrincipal_' + IntToStr(Servico.CodServico);
PosYMaior := 0;
for i := 0 to ParentPrincipal.ComponentCount -1 do
begin
if (ParentPrincipal.Components[i] is TCalloutPanel) then
begin
if TCalloutPanel(ParentPrincipal.Components[i]).Position.Y > PosYMaior then
begin
PosYMaior := TCalloutPanel(ParentPrincipal.Components[i]).Position.Y;
end;
// if ParentPrincipal.Components[i].Name = nCallPnlNoticiaPrincipal.Name then
// begin
// PosYAnterior := TCalloutPanel(ParentPrincipal.Components[ParentPrincipal.ComponentCount - 1 ]).Position.Y;
// Break;
// end;
end;
end;
nCallPnlNoticiaPrincipal.Position.y := PosYMaior + 1;
nCallPnlNoticiaPrincipal.Align := TAlignLayout.Top;
nCallPnlNoticiaPrincipal.Height := 120;
// Tag = 1 : O autor da notícia é o usuário logado
// se éOAutor então
if UpperCase(Servico.Autor) = UpperCase(dmPrincipal.NomeUsuarioLogado) then
begin
nCallPnlNoticiaPrincipal.Tag := 1;
end
else
begin
nCallPnlNoticiaPrincipal.Tag := 0;
end;
{Reposicionar o botão de atualizar}
spdCarregarMais.Position.y := nCallPnlNoticiaPrincipal.Position.y + 10;
spdCarregarMais.Visible := True;
{Painel do meio da noticia}
nPnlNoticiaMid := TPanel.Create(nCallPnlNoticiaPrincipal);
nPnlNoticiaMid.Align := TAlignLayout.Top;
nPnlNoticiaMid.Height := 35;
nPnlNoticiaMid.Parent := nCallPnlNoticiaPrincipal;
nPnlNoticiaMid.Name := 'nPnlNoticiaMid_' + IntToStr(Servico.CodServico);
nPnlNoticiaMid.Position.x := 0;
nPnlNoticiaMid.Position.y := 46;
{conteúdo do painel do meio da noticia}
nlblAutorTit := TLabel.Create(nPnlNoticiaMid);
nlblAutorTit.Text := 'Autor:';
nlblAutorTit.Align := TAlignLayout.Left;
nlblAutorTit.Width := 49;
nlblAutorTit.Parent := nPnlNoticiaMid;
nlblAutorTit.Name := 'nlblAutorTit_' + intToStr(Servico.CodServico);
nlblAutorTit.Position.X := 0;
nlblAutorTit.Position.Y := 0;
nlblAutorTit.Font.Size := 14;
nlblAutorTit.StyledSettings := [TStyledSetting.Family,TStyledSetting.Style,TStyledSetting.FontColor];
{conteúdo do painel do meio da noticia}
nlblAutor := TLabel.Create(nPnlNoticiaMid);
nlblAutor.Text := Servico.Autor;
nlblAutor.Align := TAlignLayout.Left;
nlblAutor.Width := 209;
nlblAutor.Parent := nPnlNoticiaMid;
nlblAutor.Name := 'nlblAutor_' + intToStr(Servico.CodServico);
nlblAutor.Position.X := 49;
nlblAutor.Position.Y := 0;
nlblAutor.Font.Size := 14;
nlblAutor.Font.Style := [TFontStyle.fsBold];
nlblAutor.StyledSettings := [TStyledSetting.Family,TStyledSetting.FontColor];
{Painel inferuior da notícia}
nPnlNoticiaBot := TPanel.Create(nCallPnlNoticiaPrincipal);
nPnlNoticiaBot.Align := TAlignLayout.Top;
nPnlNoticiaBot.Height := 35;
nPnlNoticiaBot.Parent := nCallPnlNoticiaPrincipal;
nPnlNoticiaBot.Name := 'nPnlNoticiaBot_' + IntToStr(Servico.CodServico);
nPnlNoticiaBot.Position.x := 0;
nPnlNoticiaBot.Position.y := 81;
{conteúdo do painel inferuior da noticia}
nlblDescricaoTit := TLabel.Create(nPnlNoticiaBot);
nlblDescricaoTit.Text := 'Descrição:';
nlblDescricaoTit.Align := TAlignLayout.Left;
nlblDescricaoTit.Width := 73;
nlblDescricaoTit.Parent := nPnlNoticiaBot;
nlblDescricaoTit.Name := 'nlblDescricaoTit_' + intToStr(Servico.CodServico);
nlblDescricaoTit.Position.X := 0;
nlblDescricaoTit.Position.y := 0;
nlblDescricaoTit.Font.Size := 14;
nlblDescricaoTit.StyledSettings := [TStyledSetting.Family,TStyledSetting.Style,TStyledSetting.FontColor];
{conteúdo do painel inferuior da noticia}
nlblDescricao := TLabel.Create(nPnlNoticiaBot);
nlblDescricao.Text := Servico.DescricaoRapida;
nlblDescricao.Align := TAlignLayout.Left;
nlblDescricao.Width := 201;
nlblDescricao.Parent := nPnlNoticiaBot;
nlblDescricao.Name := 'nlblDescricao_' + intToStr(Servico.CodServico);
nlblDescricao.Position.X := 73;
nlblDescricao.Position.y := 0;
nlblDescricao.Font.Size := 14;
nlblDescricao.Font.Style := [TFontStyle.fsBold];
nlblDescricao.StyledSettings := [TStyledSetting.Family,TStyledSetting.FontColor] ;
{Painel superior da noticia}
nPnlNoticiaTop := TPanel.Create(nCallPnlNoticiaPrincipal);
nPnlNoticiaTop.Align := TAlignLayout.Top;
nPnlNoticiaTop.Height := 35;
nPnlNoticiaTop.Parent := nCallPnlNoticiaPrincipal;
nPnlNoticiaTop.Name := 'nPnlNoticiaTop_' + IntToStr(Servico.CodServico);
nPnlNoticiaTop.Position.x := 0;
nPnlNoticiaTop.Position.y := 11;
{conteúdo do painel superior da noticia}
nlblCodigo := TLabel.Create(nPnlNoticiaTop);
nlblCodigo.Text := intToStr(Servico.CodServico);
nlblCodigo.Align := TAlignLayout.Left;
nlblCodigo.Width := 65;
nlblCodigo.Parent := nPnlNoticiaTop;
nlblCodigo.Name := 'nlblCodigo_' + intToStr(Servico.CodServico);
nlblCodigo.Position.X := 0;
nlblCodigo.Position.Y := 0;
nlblCodigo.Font.Size := 14;
nlblCodigo.StyledSettings := [TStyledSetting.Family,TStyledSetting.Style];
nlblCodigo.TextAlign := TTextAlign.Center;
{Data da postagem}
nlblDataHora := TLabel.Create(nPnlNoticiaTop);
nlblDataHora.Text := DateToStr(Servico.dtPostagem);
nlblDataHora.Align := TAlignLayout.Left;
nlblDataHora.Width := 192;
nlblDataHora.Parent := nPnlNoticiaTop;
nlblDataHora.Name := 'nlblDataHora_' + intToStr(Servico.CodServico);
nlblDataHora.Position.X := 73;
nlblDataHora.Font.Size := 14;
nlblDataHora.StyledSettings := [TStyledSetting.Family];
nlblDataHora.Font.Style := [TFontStyle.fsBold];
{Linha separadora entre codigo e data}
nLineSeparador := TLine.Create(nPnlNoticiaTop);
nLineSeparador.Align := TAlignLayout.Left;
nLineSeparador.Height := 35;
nLineSeparador.LineType := TLineType.Left;
nLineSeparador.Stroke.Color := TAlphaColorRec.White;
nLineSeparador.Width := 8;
nLineSeparador.Parent := nPnlNoticiaTop;
nLineSeparador.Position.X := 65;
nPnlNoticiaTop.OnClick := EventoClickPanelNoticia;
nPnlNoticiaMid.OnClick := EventoClickPanelNoticia;
nPnlNoticiaBot.onclick := EventoClickPanelNoticia;
TAnimator.AnimateFloat(nCallPnlNoticiaPrincipal,'Opacity', 1.0, 1, TAnimationType.InOut, TInterpolationType.Linear);
end;
procedure TfrmFeed.CriaNovaNoticia(var Servico :TServico);
begin
{Faz pesquisa no Banco e preenche o objeto}
dmPrincipal.qryNoticiasFeed.ParamByName('ID').AsInteger := ultIdFeed -1;
dmPrincipal.qryNoticiasFeed.Open();
dmPrincipal.qryNoticiasFeed.First;
if dmPrincipal.qryNoticiasFeed.FieldByName('ID').AsInteger = ultIdFeed then
begin
Exit; //Não há mais Atualizações
end;
while not dmPrincipal.qryNoticiasFeed.eof do
begin
Servico.CodServico := dmPrincipal.qryNoticiasFeed.FieldByName('COD_NOTICIA').AsInteger;
Servico.DescricaoRapida := dmPrincipal.qryNoticiasFeed.FieldByName('DESCRICAO').AsString;
Servico.dtPostagem := dmPrincipal.qryNoticiasFeed.FieldByName('DT_POSTAGEM').AsDateTime;
Servico.Autor := dmPrincipal.qryNoticiasFeed.FieldByName('AUTOR').AsString;
try
CriaComponentesNoticia(Servico, VertScrollBoxFundo);
except
on E:Exception do
begin
ShowMessage('Falha ao carregar notícia. Mensagem :' + E.Message);
end;
end;
dmPrincipal.qryNoticiasFeed.Next;
end;
dmPrincipal.qryNoticiasFeed.Last;
ultIdFeed := dmPrincipal.qryNoticiasFeedID.AsInteger;
dmPrincipal.qryNoticiasFeed.Close;
end;
procedure TfrmFeed.EventoClickPanelNoticia(Sender: TObject);
var
PertenceAoUsuario : Boolean;
begin
RetanguloMenu.Height := 0;
PertenceAoUsuario := TPanel(Sender).Parent.Tag = 1;
AbrirNoticia(Sender,PertenceAoUsuario);
end;
procedure TfrmFeed.FinalizarApp;
begin
{$IFDEF WIN32}
if MessageDlg('Deseja realmente fechar a aplicação?',
TMsgDlgType.mtConfirmation,[TMsgDlgBtn.mbYes, TMsgDlgBtn.mbNo], 0, TMsgDlgBtn.mbNo) = mrYes then
{$ENDIF}
begin
Close;
end;
end;
procedure TfrmFeed.AddNovaNoticia;
begin
if not Assigned(frmNoticia) then
begin
frmNoticia := TfrmNoticia.Create(Self);
end;
frmNoticia.NovaNoticia;
frmNoticia.Show;
end;
procedure TfrmFeed.AtualizarFeed;
var
Servico : TServico;
begin
Try
Servico := TServico.Create;
CriaNovaNoticia(Servico);
Finally
Servico.Free;
End;
end;
procedure TfrmFeed.AtivarLoading;
begin
imgLoading.Visible := True;
FloatAnimationRotacaoImg.Enabled := True;
efeitoBlur := TBlurEffect.Create(VertScrollBoxFundo);
efeitoBlur.Softness := 0.3;
efeitoBlur.Parent := VertScrollBoxFundo;
efeitoBlur.Enabled := True;
// pnlTitulo.Visible := False;
end;
procedure TfrmFeed.DesativarLoading;
begin
imgLoading.Visible := False;
FloatAnimationRotacaoImg.Enabled := False;
efeitoBlur.Free;
// pnlTitulo.Visible := True;
end;
procedure TfrmFeed.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := TCloseAction.caFree;
frmFeed := nil;
Application.Terminate;
end;
procedure TfrmFeed.FormCreate(Sender: TObject);
begin
{Perguntar pro web service qual é o max id}
ultIdFeed := 100;
imgLoading.Visible := False;
end;
procedure TfrmFeed.FormResize(Sender: TObject);
begin
RetanguloMenu.Position.X := imgMenu.Position.X + imgMenu.Width - RetanguloMenu.Width;
end;
procedure TfrmFeed.FormShow(Sender: TObject);
begin
RetanguloMenu.Height := 0;
end;
procedure TfrmFeed.imgFinalizarClick(Sender: TObject);
begin
FinalizarApp;
end;
procedure TfrmFeed.imgMenuClick(Sender: TObject);
begin
RetanguloMenu.Position.X := imgMenu.Position.X + imgMenu.Width - RetanguloMenu.Width;
RetanguloMenu.BringToFront;
AniFloatMenu.Inverse := (RetanguloMenu.Height > 0);
AniFloatMenu.Enabled := True;
AniFloatMenu.Enabled := False;
end;
procedure TfrmFeed.imgNovoClick(Sender: TObject);
begin
AddNovaNoticia;
end;
procedure TfrmFeed.imgPesquisarClick(Sender: TObject);
var
i :Integer;
TextoDigitado : String;
TextoDoComponente : String;
begin
if not Trim(edtPesquisar.Text).IsEmpty then
begin
TextoDigitado := UpperCase(edtPesquisar.Text);
for i := 0 to VertScrollBoxFundo.ComponentCount - 1 do
begin
if VertScrollBoxFundo.Components[i] is TLabel then
begin
TextoDoComponente := UpperCase(TLabel(VertScrollBoxFundo.Components[i]).Text);
if TextoDigitado.Contains(TextoDigitado) then
begin
end;
end;
end;
end;
end;
procedure TfrmFeed.lblFinalizarClick(Sender: TObject);
begin
FinalizarApp;
end;
procedure TfrmFeed.spdCarregarMaisClick(Sender: TObject);
begin
AtivarLoading;
AtualizarFeed;
//DesativarLoading;
end;
procedure TfrmFeed.spdFinalizarClick(Sender: TObject);
begin
FinalizarApp;
end;
procedure TfrmFeed.spdNovoClick(Sender: TObject);
begin
AddNovaNoticia;
end;
procedure TfrmFeed.SpeedButton1Click(Sender: TObject);
var
Servico : TServico;
begin
dmPrincipal.SQLiteConn.ExecSQL('INSERT INTO NOTICIASFEED(COD_NOTICIA) VALUES(10)');
end;
procedure TfrmFeed.tmrAtualizaFeedTimer(Sender: TObject);
begin
//CriaNovaNoticia;
end;
procedure TfrmFeed.VertScrollBoxFundoClick(Sender: TObject);
begin
RetanguloMenu.Height := 0;
end;
end.
|
PROGRAM MARKS;
VAR
oral1, oral2, oral3, exam: INTEGER;
average: REAL;
BEGIN
WRITE ('Input the first oral grade : ');
READ (oral1);
WRITE ('Input the second oral grade : ');
READ (oral2);
WRITE ('Input the third oral grade : ');
READ (oral3);
WRITE ('Input your exam grade : ');
READ (exam);
average := (oral1 + oral2 + oral3 + exam + exam) / 5;
WRITE ('Your average grade is : ', average:0:2);
IF average>=10 THEN
WRITE (' you passed')
ELSE
WRITE (' you did not pass')
END. |
////////////////////////////////////////////
// Шаблонный класс для опроса приборов через пассивные конвертеры/модемы/порты
////////////////////////////////////////////
unit Threads.ReqSpecDevTemplate;
interface
uses Classes, Windows, SysUtils, GMGlobals, GMConst, ActiveX,
GMSqlQuery, GM485, GMGenerics, RequestList, Threads.Base, Connection.Base, Devices.ReqCreatorBase;
type
TRequestListBuilder = class
private
FObjType: int;
FID_Obj: int;
FAllowLowPriorityRequests: bool;
q: TGMSqlQuery;
FReqList: TRequestCollection;
ReqCreator: T485RequestCreator;
procedure FillReqDetails;
procedure AddRequestToSendBuf(ReqDetails: TRequestDetails);
procedure CreateQuery;
public
constructor Create(ObjType: int; ID_Obj: int = 0);
destructor Destroy; override;
procedure Build(lst: TRequestCollection);
end;
TRequestSpecDevices = class (TGMThread)
private
FObjType: int;
FID_Obj: int;
FReqID: int;
FConnectionObject: TConnectionObjectBase;
ReqListBuilder: TRequestListBuilder;
FReqList: TRequestCollection;
FCurrentRequest: TRequestDetails;
FLastReadUTime: UInt64;
procedure RequestDataFromCOM;
procedure RequestDataWithPriority(priority: TRequestPriority; count: int);
function CheckTerminated(): bool;
protected
procedure PostGBV(ReqDetails: TRequestDetails; bufRec: array of byte; cnt: int);
procedure BackGroungProc; virtual;
procedure LoadCommands(); overload;
procedure CycleProc();
procedure DoOneRequest(ri: TSpecDevReqListItem); virtual;
function ConfigurePort(ri: TSpecDevReqListItem): bool; virtual;
procedure FreePort(); virtual;
property CurrentRequest: TRequestDetails read FCurrentRequest;
function CheckGetAllData: bool; virtual;
procedure SafeExecute; override;
procedure CreateConnectionObject(connectionObjectClass: TConnectionObjectClass);
constructor Create(ObjType: int; ID_Obj: int = 0); overload;
public
property ObjType: int read FObjType;
property ID_Obj: int read FID_Obj;
property LastReadUTime: UInt64 read FLastReadUTime;
destructor Destroy; override;
property ConnectionObject: TConnectionObjectBase read FConnectionObject;
procedure AddRequest(reqDetails: TRequestDetails);
property RequestList: TRequestCollection read FReqList;
class procedure LoadCommands(ID_Obj, ID_Device, ID_Prm: int; AAddRequestToSendBuf: TGMAddRequestToSendBufProc); overload;
end;
TRequestSpecDevicesClass = class of TRequestSpecDevices;
TRequestDetailsHelper = record helper for TRequestDetails
public
procedure InitFromQuery(q: TGMSqlQuery);
end;
implementation
uses StrUtils, DB, GMBlockValues, ProgramLogFile, Math, Devices.Logica.SPT961, UsefulQueries, EsLogging;
constructor TRequestSpecDevices.Create(ObjType: int; ID_Obj: int = 0);
begin
inherited Create(false);
FObjType := ObjType;
FID_Obj := ID_Obj;
FReqID := 0;
FLastReadUTime := 0;
FReqList := TRequestCollection.Create();
ReqListBuilder := TRequestListBuilder.Create(ObjType, ID_Obj);
end;
procedure TRequestSpecDevices.CreateConnectionObject(connectionObjectClass: TConnectionObjectClass);
begin
if FConnectionObject <> nil then
TryFreeAndNil(FConnectionObject);
if connectionObjectClass <> nil then
begin
FConnectionObject := connectionObjectClass.Create();
FConnectionObject.CheckTerminated := CheckTerminated;
FConnectionObject.ExternalCheckGetAllData := CheckGetAllData;
end;
end;
destructor TRequestSpecDevices.Destroy;
begin
FReqList.Free();
ReqListBuilder.Free();
TryFreeAndNil(FConnectionObject);
inherited;
end;
procedure TRequestSpecDevices.PostGBV(ReqDetails: TRequestDetails; bufRec: array of byte; cnt: int);
var gbv: TGeomerBlockValues;
begin
gbv := TGeomerBlockValues.Create();
gbv.gbt := gbt485;
gbv.gmTime := NowGM();
gbv.ReqDetails := ReqDetails;
gbv.SetBufRec(bufRec, cnt);
GMPostMessage(WM_GEOMER_BLOCK, WPARAM(gbv), 0, DefaultLogger);
DefaultLogger.Debug('WM_GEOMER_BLOCK');
end;
procedure TRequestSpecDevices.DoOneRequest(ri: TSpecDevReqListItem);
var
ext: TPrepareRequestBufferInfo;
begin
if not ConfigurePort(ri) then
Exit;
try
FCurrentRequest := ri.ReqDetails;
ext.ReqID := FReqID;
ri.PrepareBuffer(ext);
FReqID := (FReqID + 1) and $FF;
WriteBuf(FConnectionObject.buffers.BufSend, 0, ri.ReqDetails.buf, ri.ReqDetails.BufCnt);
FConnectionObject.buffers.LengthSend := ri.ReqDetails.BufCnt;
if FConnectionObject.ExchangeBlockData(etSenRec) = ccrBytes then
begin
PostGBV(ri.ReqDetails, FConnectionObject.buffers.bufRec, FConnectionObject.buffers.NumberOfBytesRead);
FLastReadUTime := NowGM();
end;
finally
FreePort();
end;
end;
procedure TRequestSpecDevices.FreePort();
begin
FConnectionObject.FreePort();
end;
procedure TRequestSpecDevices.LoadCommands;
begin
LoadCommands(fID_Obj, 0, 0, AddRequest);
end;
procedure TRequestSpecDevices.RequestDataWithPriority(priority: TRequestPriority; count: int);
var i: int;
cnt: int;
begin
FReqList.SortByPriority();
cnt := 0;
for i := 0 to FReqList.Count - 1 do
begin
if Terminated then Exit;
if not FReqList[i].Processed and
((priority = rqprNone) or (FReqList[i].ReqDetails.Priority <= priority)) then
begin
DoOneRequest(FReqList[i]);
FReqList[i].Processed := true;
if count > 0 then
begin
inc(cnt);
if cnt >= count then break
end;
end;
end;
end;
procedure TRequestSpecDevices.RequestDataFromCOM();
begin
RequestDataWithPriority(rqprCurrents, 0);
end;
procedure TRequestSpecDevices.CycleProc();
begin
try
FReqList.ClearProcessed();
ReqListBuilder.Build(FReqList);
RequestDataFromCOM();
except
on e: Exception do
ProgramLog().AddException(ClassName() + '.SafeExecute - ' + e.Message);
end;
end;
procedure TRequestSpecDevices.AddRequest(reqDetails: TRequestDetails);
begin
FReqList.Add(reqDetails);
end;
class procedure TRequestSpecDevices.LoadCommands(ID_Obj, ID_Device, ID_Prm: int; AAddRequestToSendBuf: TGMAddRequestToSendBufProc);
begin
try
ReadFromQuery(
SqlText_LoadCommands(ID_Obj, ID_Device, ID_Prm),
procedure(q: TGMSqlQuery)
var
channelIds: TChannelIds;
reqCreator: ISmartPointer<T485RequestCreator>;
begin
channelIds := ChannelIdsFromQ(q);
reqCreator := TSmartPointer<T485RequestCreator>.Create(T485RequestCreator.Create(AAddRequestToSendBuf));
reqCreator.ReqDetails.InitFromQuery(q);
reqCreator.ReqDetails.Priority := rqprCommand;
reqCreator.ReqDetails.rqtp := rqtCommand;
if not reqCreator.SetChannelValue(channelIds, q.FieldByName('Value').AsFloat, q.FieldByName('TimeHold').AsInteger) then
SQLReq_SetCmdState(q.FieldByName('ID_Cmd').AsInteger, COMMAND_STATE_ERROR)
else
SQLReq_SetCmdState(q.FieldByName('ID_Cmd').AsInteger, COMMAND_STATE_EXECUTED)
end);
except
ProgramLog.AddException(ClassName() + '.LoadCommands');
end;
end;
procedure TRequestSpecDevices.BackGroungProc;
begin
FReqList.ClearProcessed();
LoadCommands();
RequestDataWithPriority(rqprCommand, 0);
RequestDataWithPriority(rqprNone, 5); // запрашиваем недозапрошенное в основном цикле
end;
procedure TRequestSpecDevices.SafeExecute;
var tLastReq: int64;
begin
CoInitialize(nil);
while not Terminated do
begin
tLastReq := GetTickCount();
CycleProc();
repeat // опрос раз в минуту
if Terminated then Exit;
BackGroungProc();
SleepThread(2000);
until Terminated or (Abs(tLastReq - GetTickCount()) >= COMDevicesRequestInterval * 1000);
end;
end;
function TRequestSpecDevices.CheckGetAllData: bool;
begin
Result := false;
case CurrentRequest.ID_DevType of
DEVTYPE_SPT_961: Result := LogicaSPT961_CheckCRC(FConnectionObject.buffers.BufRec, FConnectionObject.buffers.NumberOfBytesRead);
end;
end;
function TRequestSpecDevices.CheckTerminated: bool;
begin
Result := Terminated;
end;
function TRequestSpecDevices.ConfigurePort(ri: TSpecDevReqListItem): bool;
begin
FConnectionObject.WaitFirst := ri.ReqDetails.TimeOut;
Result := true;
end;
{ TRequestListBuilder }
procedure TRequestListBuilder.CreateQuery();
begin
CoInitialize(nil);
q := TGMSqlQuery.Create();
end;
constructor TRequestListBuilder.Create(ObjType: int; ID_Obj: int = 0);
begin
inherited Create();
FID_Obj := ID_Obj;
FObjType := ObjType;
CreateQuery();
ReqCreator := T485RequestCreator.Create(AddRequestToSendBuf);
end;
destructor TRequestListBuilder.Destroy;
begin
TryFreeAndNil(q);
TryFreeAndNil(ReqCreator);
inherited;
end;
procedure TRequestListBuilder.FillReqDetails();
begin
ReqCreator.ReqDetails.InitFromQuery(q);
end;
procedure TRequestListBuilder.AddRequestToSendBuf(ReqDetails: TRequestDetails);
begin
if FAllowLowPriorityRequests or (ReqDetails.Priority <= rqprCurrents) then
FReqList.Add(ReqDetails);
end;
procedure TRequestListBuilder.Build(lst: TRequestCollection);
var action: string;
begin
FReqList := lst;
FAllowLowPriorityRequests := FReqList.MaxPriority() <= rqprCurrents; // разрешаем опрос архивов, только когда старые заявки на архивы все обработаны
ProgramLog.AddMessage(ClassName() + '.ReadRequestListFromSQL');
try
q.SQL.Text := ' select * from Devices d join objects o on o.ID_Obj = d.ID_Obj join DevTypes dt on d.ID_DevType = dt.ID_DevType' +
' where (COALESCE(d.Number, 0) > 0 or (COALESCE(d.Number, 0) = 0 and AllowZeroNumber > 0))' +
' and d.ID_Devtype not in (' + SetOfIntCommaList(GeomerFamily) + ')' +
IfThen(FID_Obj > 0,
' and d.ID_Obj = ' + IntToStr(FID_Obj),
' and COALESCE(ObjType, 0) = ' + IntToStr(FObjType)) +
' and exists (select * from Params p where p.ID_Device = d.ID_Device and ID_PT > 0)';
action := 'OpenQuery ' + q.SQL.Text;
q.Open();
while not q.Eof do
begin
action := 'ReqDetails';
FillReqDetails();
action := 'AddDeviceToSendBuf';
ReqCreator.AddDeviceToSendBuf();
ProgramLog.AddMessage(ClassName() + '.ReadRequestListFromSQL object Found ID = ' + IntToStr(ReqCreator.ReqDetails.ID_Obj));
q.Next();
end;
q.Close();
except
on e: Exception do
ProgramLog().AddException(ClassName() + '.ReadRequestListFromSQL.' + action + ' - ' + e.Message);
end;
end;
{ TRequestDetailsHelper }
procedure TRequestDetailsHelper.InitFromQuery(q: TGMSqlQuery);
begin
Init();
Priority := rqprCurrents; // кому надо - поменяет по месту
N_Car := q.FieldByName('N_Car').AsInteger;
DevNumber := q.FieldByName('Number').AsInteger and $FF; // на всякий случай отрежем старшие байты
BaudRate := q.FieldByName('BaudRate').AsInteger;
IPPort := q.FieldByName('RemotePort').AsInteger;
IP := q.FieldByName('RemoteSrv').AsString;
Converter := q.FieldByName('Converter').AsInteger;
ID_Obj := q.FieldByName('ID_Obj').AsInteger;
ObjType := q.FieldByName('ObjType').AsInteger;
ID_Device := q.FieldByName('ID_Device').AsInteger;
ID_DevType := q.FieldByName('ID_DevType').AsInteger;
if q.Fields.FindField('ID_Prm') <> nil then
ID_Prm := q.FieldByName('ID_Prm').AsInteger;
end;
end.
|
unit IdFinger;
{*******************************************************}
{ }
{ Indy Finger Client TIdFinger }
{ }
{ Copyright (C) 2000 Winshoes Working Group }
{ Original author J. Peter Mugaas }
{ 2000-April-23 }
{ Based on RFC 1288 }
{ }
{*******************************************************}
{2000-April-30 J. Peter Mugaas
-adjusted CompleteQuery to permit recursive finger queries such
as "test@test.com@example.com". I had mistakenly assumed that
everything after the first @ was the host name.
-Added option for verbose output request from server - note that
many do not support this.}
interface
uses
Classes,
IdAssignedNumbers,
IdTCPClient;
type
TIdFinger = class(TIdTCPClient)
protected
FQuery: String;
FVerboseOutput: Boolean;
Procedure SetCompleteQuery(AQuery: String);
Function GetCompleteQuery: String;
public
constructor Create(AOwner: TComponent); override;
{This connects to a server, does the finger querry specified in the Query
property and returns the results of the querry}
function Finger: String;
published
{This is the querry to the server which you set with the Host Property}
Property Query: String read FQuery write FQuery;
{This is the complete querry such as "user@host"}
Property CompleteQuery: String read GetCompleteQuery write SetCompleteQuery;
{This indicates that the server should give more detailed information on
some systems. However, this will probably not work on many systems so it is
False by default}
Property VerboseOutput: Boolean read FVerboseOutPut write FVerboseOutPut
default False;
end;
implementation
uses
IdGlobal,
IdTCPConnection,
SysUtils;
{ TIdFinger }
constructor TIdFinger.Create(AOwner: TComponent);
begin
inherited;
Port := IdPORT_FINGER;
end;
{This is the method used for retreiving Finger Data which is returned in the
result}
function TIdFinger.Finger: String;
var QStr : String;
begin
QStr := FQuery;
if VerboseOutPut then
begin
QStr := QStr + '/W'; {Do not Localize}
end; //if VerboseOutPut then
Connect;
try
{Write querry}
Result := ''; {Do not Localize}
WriteLn(QStr);
{Read results}
Result := AllData;
finally
Disconnect;
end; // try..finally.
end;
function TIdFinger.GetCompleteQuery: String;
begin
Result := FQuery + '@' + Host; {Do not Localize}
end;
procedure TIdFinger.SetCompleteQuery(AQuery: String);
var p : Integer;
begin
p := RPos('@', AQuery, -1); {Do not Localize}
if (p <> 0) then begin
if ( p < Length ( AQuery ) ) then
begin
Host := Copy(AQuery, p + 1, Length ( AQuery ) );
end; // if ( p < Length ( AQuery ) ) then
FQuery := Copy(AQuery, 1, p - 1);
end //if (p <> 0) then begin
else
begin
FQuery := AQuery;
end; //else..if (p <> 0) then begin
end;
end.
|
{ Copyright (C) 1998-2011, written by Mike Shkolnik, Scalabium Software
E-Mail: mshkolnik@scalabium
WEB: http://www.scalabium.com
Const strings for localization : Portuguese(Standard)
freeware SMComponent library
}
unit SMCnst;
interface
{Translated by Fernando Dias (fernandodias@easygate.com.pt)
Last update: 25-Oct-2011}
const
strMessage = 'Imprimir...';
strSaveChanges = 'Pretende mesmo guardar as alterações na base de dados ?';
strErrSaveChanges = 'Não foi possível guardar os dados! Verifique a ligação ao servidor e a validação dos dados.';
strDeleteWarning = 'Pretende mesmo eliminar a tabela %s?';
strEmptyWarning = 'Pretende eliminar o conteúdo da tabela %s?';
const
PopUpCaption: array [0..24] of string =
('Acrescentar registo',
'Inserir registo',
'Editar registo',
'Apagar registo',
'-',
'Imprimir ...',
'Exportar ...',
'Filtrar ...',
'Procurar ...',
'-',
'Guardar alterações',
'Cancelar alterações',
'Refrescar',
'-',
'Marcar/Desmarcar registos',
'Marcar registo',
'Marcar todos',
'-',
'Desmarcar registo',
'Desmarcar todos',
'-',
'Guardar aspecto da coluna',
'Recuperar aspecto da coluna',
'-',
'Configuração...');
const //for TSMSetDBGridDialog
SgbTitle = ' Título ';
SgbData = ' Dados ';
STitleCaption = 'Rótulo:';
STitleAlignment = 'Alinhamento:';
STitleColor = 'Fundo:';
STitleFont = 'Letra:';
SWidth = 'Largura:';
SWidthFix = 'caracteres';
SAlignLeft = 'esquerda';
SAlignRight = 'direita';
SAlignCenter = 'centro';
const //for TSMDBFilterDialog
strEqual = 'igual';
strNonEqual = 'não igual';
strNonMore = 'não maior';
strNonLess = 'não menor';
strLessThan = 'menor que';
strLargeThan = 'maior que';
strExist = 'vazio';
strNonExist = 'não vazio';
strIn = 'na lista';
strBetween = 'entre';
strLike = 'como';
strOR = 'OU';
strAND = 'E';
strField = 'Campo';
strCondition = 'Condição';
strValue = 'Valor';
strAddCondition = ' Defina a condição adicional:';
strSelection = ' Seleccionar registos pela seguinte condição:';
strAddToList = 'Adicionar à lista';
strEditInList = 'Editar a lista';
strDeleteFromList = 'Apagar da lista';
strTemplate = 'Modelo de filtro';
strFLoadFrom = 'Ler de...';
strFSaveAs = 'Guardar como...';
strFDescription = 'Descrição';
strFFileName = 'Ficheiro';
strFCreate = 'Criado: %s';
strFModify = 'Modificado: %s';
strFProtect = 'Proteger para escrita';
strFProtectErr = 'Ficheiro está protegido!';
const //for SMDBNavigator
SFirstRecord = 'Primeiro registo';
SPriorRecord = 'Registo anterior';
SNextRecord = 'Próximo registo';
SLastRecord = 'Último registo';
SInsertRecord = 'Inserir registo';
SCopyRecord = 'Copiar registo';
SDeleteRecord = 'Apagar registo';
SEditRecord = 'Editar registo';
SFilterRecord = 'Filtrar';
SFindRecord = 'Procurar';
SPrintRecord = 'Imprimir';
SExportRecord = 'Exportar';
SImportRecord = 'Importar';
SPostEdit = 'Guardar alterações';
SCancelEdit = 'Cancelar alterações';
SRefreshRecord = 'Refrescar dados';
SChoice = 'Escolher registo';
SClear = 'Anular escolha de registo';
SDeleteRecordQuestion = 'Apagar registo?';
SDeleteMultipleRecordsQuestion = 'Pretende mesmo apagar os registos seleccionados?';
SRecordNotFound = 'Registo não encontrado';
SFirstName = 'Primeiro';
SPriorName = 'Anterior';
SNextName = 'Próximo';
SLastName = 'Último';
SInsertName = 'Inserir';
SCopyName = 'Copiar';
SDeleteName = 'Apagar';
SEditName = 'Editar';
SFilterName = 'Filtrar';
SFindName = 'Procurar';
SPrintName = 'Imprimir';
SExportName = 'Exportar';
SImportName = 'Importar';
SPostName = 'Guardar';
SCancelName = 'Cancelar';
SRefreshName = 'Refrescar';
SChoiceName = 'Escolher';
SClearName = 'Limpar';
SBtnOk = '&OK';
SBtnCancel = '&Cancelar';
SBtnLoad = 'Abrir';
SBtnSave = 'Guardar';
SBtnCopy = 'Copiar';
SBtnPaste = 'Colar';
SBtnClear = 'Limpar';
SRecNo = 'reg.';
SRecOf = ' de ';
const //for EditTyped
etValidNumber = 'numero válido';
etValidInteger = 'numero inteiro válido';
etValidDateTime = 'data/hora válida';
etValidDate = 'data válida';
etValidTime = 'hora válida';
etValid = 'válido';
etIsNot = 'não é um(a)';
etOutOfRange = 'Valor %s fora do intervalo %s..%s';
SApplyAll = 'Aplicar a todos';
SNoDataToDisplay = '<Sem dados para apresentar>';
SPrevYear = 'ano anterior';
SPrevMonth = 'mês anterior';
SNextMonth = 'mês seguinte';
SNextYear = 'ano seguinte';
implementation
end.
|
unit FLista;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uCtrlObject, FCadastroPai, uCadastroPaiClass,
Data.DB, Datasnap.DBClient, FCadastroMestreDet;
type
TfrmLista = class(TForm)
ds: TDataSource;
cds: TClientDataSet;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
protected
_Filtro : TFiltro;
_Ctrl : TControlObject;
_FrmCadastro : TfrmCadastroPai;
_FrmCadastroMestreDet : TfrmCadastroMestreDet;
_FrmReference: TfrmCadastroPaiClass;
_FrmReferenceMestreDet: TfrmCadastroMestreDetClass;
_Campos : TStringList;
procedure carregaGrid; virtual;
procedure Setup(Ctrl: TControlObject; formCadastro: TfrmCadastroPaiClass; bCarregaGrid: Boolean = True); virtual;
procedure SetupMestreDet(Ctrl: TControlObject; formCadastro: TfrmCadastroMestreDetClass); virtual;
{ Private declarations }
public
procedure criarCtrl; virtual;
procedure destruirCtrl; virtual;
constructor create(AOwner: TComponent; Filtro: TFiltro = nil);
{ Public declarations }
end;
var
frmLista: TfrmLista;
implementation
{$R *.dfm}
{ TfrmLista }
procedure TfrmLista.carregaGrid;
begin
cds.Data := _Ctrl.listaGrid(_Filtro);
end;
constructor TfrmLista.create(AOwner: TComponent; Filtro: TFiltro);
begin
inherited create(AOwner);
_Filtro := Filtro;
end;
procedure TfrmLista.criarCtrl;
begin
end;
procedure TfrmLista.destruirCtrl;
begin
end;
procedure TfrmLista.FormCreate(Sender: TObject);
begin
criarCtrl;
end;
procedure TfrmLista.FormDestroy(Sender: TObject);
begin
destruirCtrl;
end;
procedure TfrmLista.Setup(Ctrl: TControlObject; formCadastro: TfrmCadastroPaiClass; bCarregaGrid: Boolean = True);
begin
_FrmReference := formCadastro;
_Ctrl := Ctrl;
if bCarregaGrid then
carregaGrid;
end;
procedure TfrmLista.SetupMestreDet(Ctrl: TControlObject; formCadastro: TfrmCadastroMestreDetClass);
begin
_FrmReferenceMestreDet := formCadastro;
_Ctrl := Ctrl;
carregaGrid;
end;
end.
|
unit SpectrumStrings;
{$mode objfpc}{$H+}
interface
const
NL = LineEnding;
NL2 = LineEnding + LineEnding;
resourcestring
Action_Undo = 'Undo';
Action_Redo = 'Redo';
Dlg_DiagramTitleCaption = 'Diagram Title';
Dlg_DiagramTitlePrompt = 'Enter new diagram title:';
Dlg_GraphTitleCaption = 'Graph Title';
Dlg_GraphTitlePrompt = 'Enter new graph title:';
Dlg_OpenFolder = 'Add Graphs From Folder';
Dlg_OpenGraphs = 'Add Graphs';
Dlg_OpenTable = 'Add Table';
Err_FileNotFound = 'File "%s" not found.';
Err_FileTryNext = 'Try to open remaining files?';
Err_IllegalChar = 'Illegal symbol in input data (the data may be binary).';
Err_ReadData = 'Error while reading data from %s.';
Err_TooFewPoints = 'Too few points for plotting.';
Err_RSNoSetFile = 'Could not find the spectrum settings file (%s).';
Err_RSUnknownVersion = 'Could not automatically determine the version of spectrum file. ' + NL +
'Try to manually set on of predefined version numbers: 0 - Auto, 1 - FSE 40GHz, 2 - FSE 3GHz. ' + NL +
'(Parameter RSFileVersion in main section of program configuration file).';
Err_XYLengthsDiffer = 'Arrays of X and Y values must have equal length.';
Err_UnsupportedFile = 'It is not known how to read file "%s"';
Filter_All = 'All files|*.*';
Filter_AllCSV = 'All text data files (*.TXT;*.CSV;*.DAT)|*.TXT;*.CSV;*.DAT|';
Filter_CSV = 'Data files with separators (*.CSV)|*.CSV|';
Filter_Dag = 'Dagatron counter files (*.*)|*.*|';
Filter_DAT = 'Data files (*.DAT)|*.DAT|';
Filter_OO = 'Analyzer Ocean Optics HR2000 files (*.Scope)|*.scope|';
Filter_RAR = 'RAR archives';
Filter_RS = 'Analyzer Rohde&Schwarz files (*.TR1,2,3,4)|*.tr1;*.tr2;*.tr3;*.tr4|';
Filter_TXT = 'Text files (*.TXT)|*.TXT|';
Filter_ZIP = 'ZIP archives';
Plot_DefTitle = 'Diagram';
ParamErr_ZeroRange = 'Range can not be zero (Min = Max).';
ParamErr_WrongFloat = '%s is not valid number.';
ParamErr_WrongStep = 'Wrong step value: %g.' + NL2 +
'Step must be greater than zero but less than range between minimum and maximum (%g).';
Status_Modified = 'Modified';
Status_Graphs = 'Graphs';
Tooltab_DataTable = 'Data Table';
Undo_AddGraph = 'Append Graph';
Undo_DeleteGraph = 'Delete Graph';
Undo_DeleteGraphs = 'Delete Graphs';
Undo_Despike = 'Remove Spikes';
Undo_Flip = 'Flip Graphs';
Undo_FlipX = 'Flip Along X Axis';
Undo_FlipY = 'Flip Along Y Axis';
Undo_FormulaEdit = 'Edit Formula';
Undo_GraphMod = 'Change Graphs';
Undo_Inverse = 'Invert Graphs';
Undo_Normalize = 'Normalize Graphs';
Undo_Offset = 'Offset Graphs';
Undo_Scale = 'Scale Graphs';
Undo_SwapXY = 'Swap Axes';
Undo_TitleGraph = 'Rename Graph';
Undo_TitlePlot = 'Rename Diagram';
Undo_Trim = 'Trim Graphs';
implementation
end.
|
{$MODE OBJFPC} { -*- delphi -*- }
{$INCLUDE settings.inc}
program startgame;
uses
sysutils,
world,
exceptions;
// Command line argument: world file, players file, directory of first turn
// The first turn directory should not yet exist and will be created.
// The world JSON files have the following format:
{
Provinces: [ province, province, province, ... ],
}
// Each province is a JSON object with the following format:
{
Name: 'string...',
Neighbours: [ number, number, ... ], // province IDs
}
// Provinces are referenced by their position in the Provinces
// array, which we call their ID.
// The players JSON files have the following format:
{
Players: [ player, player, player, ... ],
}
// Each player is a JSON object with the following format:
{
Name: 'string...',
id: 'string', // 1-10 character string with only 'a' to 'z' characters
}
// This program outputs the same format of data as process-turn
// (qv), with the Turn field set to 1.
procedure StartGame(const ServerFile, PlayerFile, FirstTurnDir: AnsiString);
var
World: TPerilWorldCreator;
begin
if (DirectoryExists(FirstTurnDir)) then
raise Exception.Create('third argument is a directory that exists');
if (not CreateDir(FirstTurnDir)) then
raise Exception.Create('could not create directory for first turn');
World := TPerilWorldCreator.Create();
try
World.LoadData(ServerFile, [pdfProvinces]);
World.LoadData(PlayerFile, [pdfPlayers]);
if (World.PlayerCount < 2) then
raise Exception.Create('insufficent number of players specified');
if (World.PlayerCount > World.ProvinceCount) then
raise Exception.Create('too many players specified');
World.DistributePlayers();
World.RandomiseIDs();
World.SaveData(FirstTurnDir);
finally
World.Free();
end;
end;
begin
Randomize();
try
if (ParamCount() <> 3) then
raise Exception.Create('arguments must be <world-file> <player-file> <first-turn-directory>');
StartGame(ParamStr(1), ParamStr(2), ParamStr(3));
except
on E: Exception do
begin
{$IFDEF DEBUG}
ReportCurrentException();
{$ELSE}
Writeln('start-game: ', E.Message);
{$ENDIF}
ExitCode := 1;
end;
end;
end. |
unit ncErros;
{
ResourceString: Dario 12/03/13
}
interface
uses
SysUtils,
classes,
uNexTransResourceStrings_PT;
type
ENexCafe = class(Exception);
const
ncerrTipoClasseInvalido = 1;
ncerrItemInexistente = 3;
ncerrItemSemAlteracoes = 4;
ncerrInfoLoginInvalida = 5;
ncerrErroBD = 6;
ncerrClienteInvalido = 7;
ncerrItemJaExiste = 8;
ncerrAcessoEmAndamento = 9;
ncerrClienteJaAtivo = 10;
ncerrSemCreditoDisp = 11;
ncerrMaquinaInexistente = 12;
ncerrMaquinaJaConectada = 13;
ncerrTelaNaoDisponivel = 14;
ncerrMaquinaSemAcesso = 15;
ncerrEmModoDemo = 16;
ncerrNumMaxMaq = 17;
ncerrSemNovaVersao = 18;
ncerrErroSocket = 19;
ncerrMaqJaEstaManutencao = 20;
ncerrMaqNaoEstaManutencao = 21;
ncerrAcessoNaoPermitido = 22;
ncerrPassaporteEmUso = 23;
ncerrRGErrado = 24;
ncerrRGNaoCadastrado = 25;
ncerrCaixaFechado = 26;
ncerrClienteInativo = 27;
ncerrTransfAguardaPagto = 28;
ncerrLimiteManutUsuario = 29;
ncerrArqNaoEncontrado = 30;
ncerrFundoTemQueSerJPG = 31;
ncerrFundoTemQueSerJPGouGIF = 32;
ncerrClienteNaoEncontrado = 33;
ncerrMaqNaoLic = 34;
ncerrCaixaDiferente = 35;
ncerrImpossivelCancFimSessao = 36;
ncerrImpossivelCancPassaporteUsado = 37;
ncerrSemCreditoDispCanc = 38;
ncerrExisteTranPosterior = 39;
ncerrUsuarioInexistente = 40;
ncerrJaTemCaixaAberto = 41;
ncerrCaixaJaFoiFechado = 42;
ncerrAguardaPagto = 43;
ncerrMaqReservada = 44;
ncerrSaldoTempoInsuficiente = 45;
ncerrSenhaInvalida = 46;
ncerrLimiteDebitoExcedido = 47;
ncerrHorarioNaoPermitido = 48;
ncerrMaquinaEmManutencao = 49;
ncerrTransacaoSoPodeAlterarViaFimSessao = 50;
ncerrLoginNaoPermitidoLimDeb = 51;
ncerrProdutoSemSaldo = 52;
ncerrSaldoValorInsuficiente = 53;
ncerrAcessoAlteradoPorOutroUsuario = 54;
ncerrSessaoJaEncerrou = 55;
ncerrSaldoFidInsuficiente = 56;
ncerrFalhaTransfArq = 57;
ncerrConexaoPerdida = 58;
ncerrFalhaConexao = 59;
ncerrCliAvulsoBloqueado = 60;
ncerrCliSemDadosMinimos = 61;
ncerrTipoImpNaoExiste = 62;
ncerrLoginAvulsoNaoPerm = 63;
ncerrImpressaoPendente = 64;
ncerrFalhaDownloadInt = 65;
ncerrComandaInvalida = 66;
ncerrNFCeImpedeFecharCaixa = 67;
ncerrNFCeCancelarModoHomo = 68;
ncerrTranAlteradaOutroUsuario = 69;
ncerrExcecaoNaoTratada_TdmCaixa_AbreCaixa = 500;
ncerrExcecaoNaoTratada_TdmCaixa_FechaCaixa = 501;
ncerrExcecaoNaoTratada_TDM_ExcluiIME = 502;
ncerrExcecaoNaoTratada_TncServidor_ObtemStreamListaObj = 503;
ncerrExcecaoNaoTratada_TncServidor_EnviarMsg = 504;
ncerrExcecaoNaoTratada_TncServidor_FechaCaixa = 505;
ncerrExcecaoNaoTratada_TncServidor_DisableAD = 506;
ncerrExcecaoNaoTratada_TncServidor_AlteraSessao = 507;
ncerrExcecaoNaoTratada_TncServidor_DesativarFWSessao = 508;
ncerrExcecaoNaoTratada_TncServidor_DesktopSincronizado = 509;
ncerrExcecaoNaoTratada_TncServidor_AtualizaUsuarioBD = 510;
ncerrExcecaoNaoTratada_TncServidor_AtualizaConfigBD = 511;
ncerrExcecaoNaoTratada_TncServidor_AtualizaTarifaBD = 512;
ncerrExcecaoNaoTratada_TncServidor_AtualizaTipoAcessoBD = 513;
ncerrExcecaoNaoTratada_TncServidor_AtualizaTipoImpBD = 514;
ncerrExcecaoNaoTratada_TncServidor_SalvaCredTempo = 515;
ncerrExcecaoNaoTratada_TncServidor_SalvaDebito = 516;
ncerrExcecaoNaoTratada_TncServidor_SalvaDebTempo = 517;
ncerrExcecaoNaoTratada_TncServidor_SalvaImpressao = 518;
ncerrExcecaoNaoTratada_TncServidor_SalvaClientPages = 519;
ncerrExcecaoNaoTratada_TncServidor_SalvaLancExtra = 520;
ncerrExcecaoNaoTratada_TncServidor_SalvaLogAppUrl = 521;
ncerrExcecaoNaoTratada_TncServidor_SalvaMovEst = 522;
ncerrExcecaoNaoTratada_TncServidor_SalvaProcessos = 523;
ncerrExcecaoNaoTratada_TncServidor_AtualizaSessaoBD = 525;
ncerrExcecaoNaoTratada_TncServidor_AtualizaMaquinaBD = 526;
ncerrExcecaoNaoTratada_TncServidor_ApagaMsgCli = 527;
ncerrExcecaoNaoTratada_TncServidor_ApagaObj = 528;
ncerrExcecaoNaoTratada_TncServidor_LimpaFundo = 529;
ncerrExcecaoNaoTratada_TncServidor_ArqFundoEnviado = 530;
ncerrExcecaoNaoTratada_TncServidor_ObtemSitesBloqueados = 532;
ncerrExcecaoNaoTratada_TncServidor_ObtemStreamAvisos = 533;
ncerrExcecaoNaoTratada_TncServidor_ObtemStreamConfig = 534;
ncerrExcecaoNaoTratada_TncServidor_SalvaStreamObj = 535;
ncerrExcecaoNaoTratada_TncServidor_ShutdownMaq = 536;
ncerrExcecaoNaoTratada_TncServidor_SuporteRem = 537;
ncerrExcecaoNaoTratada_TncServidor_RefreshEspera = 538;
ncerrExcecaoNaoTratada_TncServidor_RefreshPrecos = 539;
ncerrExcecaoNaoTratada_TncServidor_ModoManutencao = 540;
ncerrExcecaoNaoTratada_TncServidor_PermitirDownload = 541;
ncerrExcecaoNaoTratada_TncServidor_CorrigeDataCaixa = 542;
ncerrExcecaoNaoTratada_TncServidor_Login = 543;
ncerrExcecaoNaoTratada_TncServidor_TransferirMaq = 544;
ncerrExcecaoNaoTratada_TncServidor_PararTempoMaq = 545;
ncerrExcecaoNaoTratada_TncServidor_AbreCaixa = 546;
ncerrExcecaoNaoTratada_TncServidor_AdicionaPassaporte = 547;
ncerrExcecaoNaoTratada_TncServidor_AjustaPontosFid = 548;
ncerrExcecaoNaoTratada_TncServidor_LoginMaq = 549;
ncerrExcecaoNaoTratada_TncServidor_PreLogoutMaq = 550;
ncerrExcecaoNaoTratada_TncServidor_CancelaTran = 551;
ncerrExcecaoNaoTratada_TncServidor_CancLogoutMaq = 552;
ncerrExcecaoNaoTratada_TncServidor_LogoutMaq = 553;
ncerrExcecaoNaoTratada_TncServidor_AtualizaEspecieBD = 554;
ncerrExcecaoNaoTratada_TncServidor_ZerarEstoque = 555;
ncerrExcecaoNaoTratada_GetCertificados = 556;
ncerrExcecaoNaoTratada_ReemitirNFCe = 557;
ncerrExcecaoNaoTratada_GeraXMLProt = 558;
ncerrExcecaoNaoTratada_ConsultarSAT = 559;
ncerrExcecaoNaoTratada_InutilizarNFCE = 560;
ncerrUltimo = ncerrExcecaoNaoTratada_InutilizarNFCE;
function StringErro(Erro: Integer): String;
implementation
// START resource string wizard section
// END resource string wizard section
function StringErro(Erro: Integer): String;
begin
case Erro of
ncerrTipoClasseInvalido :
Result := SncErros_TipoDeClasseInválido;
ncerrItemInexistente :
Result := SncErros_ItemInexistente;
ncerrItemSemAlteracoes :
Result := SncErros_ItemSemAlterações;
ncerrInfoLoginInvalida :
Result := SncErros_UsernameOuSenhaInválida;
ncerrErroBD :
Result := SncErros_ErroAcessandoBancoDeDadosDoServi;
ncerrClienteInvalido :
Result := SncErros_HandleDeClienteInválido;
ncerrItemJaExiste :
Result := SncErros_ItemRepetido;
ncerrAcessoEmAndamento :
Result := SncErros_OAcessoAnteriorDessaMáquinaAinda;
ncerrClienteJaAtivo :
Result := SncErros_JáExisteMáquinaSendoUsadaPorEsse;
ncerrSemCreditoDisp :
Result := SncErros_NãoHáCréditoDisponível;
ncerrMaquinaInexistente :
Result := SncErros_NúmeroDeMáquinaInexistente;
ncerrMaquinaJaConectada :
Result := SncErros_EstaMáquinaJáEstáConectada;
ncerrTelaNaoDisponivel :
Result := SncErros_TelaNãoDisponível;
ncerrMaquinaSemAcesso :
Result := SncErros_NãoExisteAcessoEmAndamentoNessaM;
ncerrEmModoDemo :
Result := SncErros_ONexCaféEstáSendoExecutadoEmModo;
ncerrNumMaxMaq :
Result := SncErros_LimiteDeMáquinasLicenciadasFoiAt;
ncerrSemNovaVersao :
Result := SncErros_NãoHáNovaVersãoDisponívelNoServi;
ncerrErroSocket :
Result := SncErros_ErroDeComunicaçãoTCPIP;
ncerrMaqJaEstaManutencao :
Result := SncErros_MáquinaEstáEmManutenção;
ncerrMaqNaoEstaManutencao :
Result := SncErros_MáquinaNãoEstáEmModoManutenção;
ncerrAcessoNaoPermitido :
Result := SncErros_VocêNãoPossuiDireitoDeExecutarEs;
ncerrPassaporteEmUso :
Result := SncErros_EsseCartãoDeTempoOuPassaporteJáE;
ncerrRGErrado :
Result := SncErros_ONúmeroDeRGInformadoEstáDiferent;
ncerrRGNaoCadastrado :
Result := SncErros_ParaUsarSuaContaéNecessárioCadas;
ncerrCaixaFechado :
Result := SncErros_ÉNecessárioAbrirUmCaixaParaReali;
ncerrClienteInativo :
Result := SncErros_EssaContaDeClienteEstáInativada;
ncerrTransfAguardaPagto :
Result := SncErros_NãoéPossívelTransferirUmAcessoQu;
ncerrLimiteManutUsuario :
Result := SncErros_LimiteMáximoDeMáquinasEmManutenç;
ncerrArqNaoEncontrado :
Result := SncErros_ArquivoNãoEncontrado;
ncerrFundoTemQueSerJPG :
Result := SncErros_OArquivoDeFundoParaáreaDeTrabalh;
ncerrFundoTemQueSerJPGouGIF :
Result := SncErros_OArquivoDeFundoParaATelaDeLoginT;
ncerrClienteNaoEncontrado :
Result := SncErros_ClienteNãoEncontrado;
ncerrMaqNaoLic :
Result := SncErros_SuaContaNexCaféNãoPermiteOUsoDes;
ncerrCaixaDiferente :
Result := SncErros_NãoéPossívelAlterarUmaTransaçãoQ;
ncerrImpossivelCancFimSessao :
Result := SncErros_NãoéPermitidoCancelarUmFimDeAces;
ncerrImpossivelCancPassaporteUsado :
Result := SncErros_NãoéPermitidoCancelarAVendaDeUmP;
ncerrSemCreditoDispCanc :
Result := SncErros_SemCréditoDisponívelParaCancelar;
ncerrExisteTranPosterior :
Result := SncErros_ExisteTransaçãoPosteriorAEssaQue;
ncerrUsuarioInexistente :
Result := SncErros_NomeDeUsuárioInexistente;
ncerrJaTemCaixaAberto :
Result := SncErros_JáExisteUmCaixaAberto;
ncerrCaixaJaFoiFechado :
Result := SncErros_EsteCaixaJáEstáFechado;
ncerrAguardaPagto :
Result := SncErros_ExistemItensAguardandoConfirmaçã;
ncerrMaqReservada :
Result := SncErros_EstaMáquinaEstáReservadaParaOutr;
ncerrSaldoTempoInsuficiente :
Result := SncErros_CréditoDeTempoAtualDoClienteNãoé;
ncerrSaldoValorInsuficiente :
Result := SncErros_OClienteNãoPossuiSaldoSuficiente;
ncerrSenhaInvalida :
Result := SncErros_SenhaInválida;
ncerrLimiteDebitoExcedido :
Result := SncErros_OLimiteMáximoDeDébitoPermitidoPa;
ncerrHorarioNaoPermitido :
Result := SncErros_ClienteNãoAutorizadoAUsarComputa;
ncerrMaquinaEmManutencao :
Result := SncErros_EssaMáquinaEstáEmManutençãoForaD;
ncerrTransacaoSoPodeAlterarViaFimSessao :
Result := SncErros_EssaTransaçãoNãoPodeSerAlteradaD+
SncErros_FaçaAAlteraçãoAtravésDaTelaDeFim;
ncerrLoginNaoPermitidoLimDeb :
Result := SncErros_LoginNãoPermitidoValorLimiteDeDé;
ncerrProdutoSemSaldo :
Result := SncErros_SaldoDeProdutoInsuficiente;
ncerrAcessoAlteradoPorOutroUsuario :
Result := SncErros_OAcessoFoiAlteradoAntesDeVocêSal;
ncerrSessaoJaEncerrou :
Result := SncErros_NãoéPossívelRealizarEssaOperação;
ncerrSaldoFidInsuficiente :
Result := SncErros_SaldoDePontosDoFidelidadeDoClien;
ncerrFalhaTransfArq :
Result := SncErros_FalhaNaTransferênciaDeArquivo;
ncerrConexaoPerdida :
Result := SncErros_AConexãoDeRedeComOServidorFoiPer;
ncerrFalhaConexao :
Result := SncErros_FalhaDeConexãoComOServidorNexCaf;
ncerrCliAvulsoBloqueado :
Result := SncErros_NãoéPossívelLiberarAcessoParaCli;
ncerrCliSemDadosMinimos :
Result := SncErros_OClienteNãoPossuiOsDadosCadastra;
ncerrTipoImpNaoExiste :
Result := SncErros_ÉNecessárioSelecionarUmTipoDeImp;
ncerrLoginAvulsoNaoPerm :
Result := SncErros_NãoéPermitidoOAcessoDeClienteSem;
ncerrImpressaoPendente :
Result := SncErros_NãoéPossívelEncerrarOAcessoPoisH;
ncerrFalhaDownloadInt :
Result := SncErros_FalhaDownloadInt;
ncerrComandaInvalida :
Result := '';
ncerrNFCeImpedeFecharCaixa :
Result := 'Existe NFC-e em situação que impede o fechamento de caixa (Ex: Em contingência, com erro ou com cancelamento em andamento)';
ncerrNFCeCancelarModoHomo :
Result := 'É necessário cancelar a venda feita em modo homologação para realizar essa operação';
ncerrTranAlteradaOutroUsuario :
Result := SncErros_TranAlteradaOutroUsuario;
ncerrExcecaoNaoTratada_TdmCaixa_AbreCaixa :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TdmCaixa_AbreCaixa;
ncerrExcecaoNaoTratada_TdmCaixa_FechaCaixa :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TdmCaixa_FechaCaixa;
ncerrExcecaoNaoTratada_TDM_ExcluiIME :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TDM_ExcluiIME;
ncerrExcecaoNaoTratada_TncServidor_ObtemStreamListaObj :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_ObtemStreamListaObj;
ncerrExcecaoNaoTratada_TncServidor_EnviarMsg :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_EnviarMsg;
ncerrExcecaoNaoTratada_TncServidor_FechaCaixa :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_FechaCaixa;
ncerrExcecaoNaoTratada_TncServidor_DisableAD :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_DisableAD;
ncerrExcecaoNaoTratada_TncServidor_AlteraSessao :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_AlteraSessao;
ncerrExcecaoNaoTratada_TncServidor_DesativarFWSessao :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_DesativarFWSessao;
ncerrExcecaoNaoTratada_TncServidor_DesktopSincronizado :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_DesktopSincronizado;
ncerrExcecaoNaoTratada_TncServidor_AtualizaUsuarioBD :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_AtualizaUsuarioBD;
ncerrExcecaoNaoTratada_TncServidor_AtualizaConfigBD :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_AtualizaConfigBD;
ncerrExcecaoNaoTratada_TncServidor_AtualizaTarifaBD :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_AtualizaTarifaBD;
ncerrExcecaoNaoTratada_TncServidor_AtualizaTipoAcessoBD :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_AtualizaTipoAcessoBD;
ncerrExcecaoNaoTratada_TncServidor_AtualizaTipoImpBD :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_AtualizaTipoImpBD;
ncerrExcecaoNaoTratada_TncServidor_SalvaCredTempo :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_SalvaCredTempo;
ncerrExcecaoNaoTratada_TncServidor_SalvaDebito :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_SalvaDebito;
ncerrExcecaoNaoTratada_TncServidor_SalvaDebTempo :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_SalvaDebTempo;
ncerrExcecaoNaoTratada_TncServidor_SalvaImpressao :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_SalvaImpressao;
ncerrExcecaoNaoTratada_TncServidor_SalvaClientPages :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_SalvaClientPages;
ncerrExcecaoNaoTratada_TncServidor_SalvaLancExtra :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_SalvaLancExtra ;
ncerrExcecaoNaoTratada_TncServidor_SalvaLogAppUrl :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_SalvaLogAppUrl;
ncerrExcecaoNaoTratada_TncServidor_SalvaMovEst :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_SalvaMovEst;
ncerrExcecaoNaoTratada_TncServidor_SalvaProcessos :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_SalvaProcessos;
ncerrExcecaoNaoTratada_TncServidor_AtualizaSessaoBD :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_AtualizaSessaoBD;
ncerrExcecaoNaoTratada_TncServidor_AtualizaMaquinaBD :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_AtualizaMaquinaBD;
ncerrExcecaoNaoTratada_TncServidor_ApagaMsgCli :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_ApagaMsgCli;
ncerrExcecaoNaoTratada_TncServidor_ApagaObj :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_ApagaObj;
ncerrExcecaoNaoTratada_TncServidor_LimpaFundo :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_LimpaFundo;
ncerrExcecaoNaoTratada_TncServidor_ArqFundoEnviado :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_ArqFundoEnviado;
ncerrExcecaoNaoTratada_TncServidor_ObtemSitesBloqueados :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_ObtemSitesBloqueados;
ncerrExcecaoNaoTratada_TncServidor_ObtemStreamAvisos :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_ObtemStreamAvisos;
ncerrExcecaoNaoTratada_TncServidor_ObtemStreamConfig :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_ObtemStreamConfig;
ncerrExcecaoNaoTratada_TncServidor_SalvaStreamObj :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_SalvaStreamObj;
ncerrExcecaoNaoTratada_TncServidor_ShutdownMaq :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_ShutdownMaq;
ncerrExcecaoNaoTratada_TncServidor_SuporteRem :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_SuporteRem;
ncerrExcecaoNaoTratada_TncServidor_RefreshEspera :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_RefreshEspera;
ncerrExcecaoNaoTratada_TncServidor_RefreshPrecos :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_RefreshPrecos;
ncerrExcecaoNaoTratada_TncServidor_ModoManutencao :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_ModoManutencao;
ncerrExcecaoNaoTratada_TncServidor_PermitirDownload :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_PermitirDownload;
ncerrExcecaoNaoTratada_TncServidor_CorrigeDataCaixa :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_CorrigeDataCaixa;
ncerrExcecaoNaoTratada_TncServidor_Login :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_Login;
ncerrExcecaoNaoTratada_TncServidor_TransferirMaq :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_TransferirMaq;
ncerrExcecaoNaoTratada_TncServidor_PararTempoMaq :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_PararTempoMaq;
ncerrExcecaoNaoTratada_TncServidor_AbreCaixa :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_AbreCaixa;
ncerrExcecaoNaoTratada_TncServidor_AdicionaPassaporte :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_AdicionaPassaporte;
ncerrExcecaoNaoTratada_TncServidor_AjustaPontosFid :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_AjustaPontosFid;
ncerrExcecaoNaoTratada_TncServidor_LoginMaq :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_LoginMaq;
ncerrExcecaoNaoTratada_TncServidor_PreLogoutMaq :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_PreLogoutMaq;
ncerrExcecaoNaoTratada_TncServidor_CancelaTran :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_CancelaTran;
ncerrExcecaoNaoTratada_TncServidor_CancLogoutMaq :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_CancLogoutMaq;
ncerrExcecaoNaoTratada_TncServidor_LogoutMaq :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_LogoutMaq;
ncerrExcecaoNaoTratada_TncServidor_AtualizaEspecieBD :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_AtuaizaEspecieBD;
ncerrExcecaoNaoTratada_TncServidor_ZerarEstoque :
Result := SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_ZerarEstoque;
ncerrExcecaoNaoTratada_GetCertificados :
Result := SncErros_ExcecaoNaoTratada_GetCertificados;
ncerrExcecaoNaoTratada_ReemitirNFCe :
Result := SncErros_ExcecaoNaoTratada_ReemitirNFCe;
ncerrExcecaoNaoTratada_GeraXMLProt :
Result := SncErros_ExcecaoNaoTratada_GeraXMLProt;
ncerrExcecaoNaoTratada_ConsultarSAT :
Result := SncErros_ExcecaoNaoTratada_ConsultarSAT;
ncerrExcecaoNaoTratada_InutilizarNFCE :
Result := SncErros_ExcecaoNaoTratada_InutilizarNFCE;
else
Result := '';
end;
end;
end.
|
unit QuestionInputFrame;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, TestClasses;
type
TfrmQuestionInput = class(TFrame)
PanelInputQuestion: TPanel;
lbQuestion: TLabel;
edQuestion: TLabeledEdit;
edNumber: TLabeledEdit;
private
function GetNumber: Integer;
function GetQuestion: String;
procedure SetNumber(const Value: Integer);
procedure SetQuestion(const Value: String);
function NullCheck: boolean;
function NumberNullCheck: boolean;
{ Private declarations }
public
{ Public declarations }
property Question : String read GetQuestion write SetQuestion;
property Number: Integer read GetNumber write SetNumber;
property IsNull: boolean read NullCheck;
property NumberIsNull: boolean read NumberNullCheck;
procedure ClearInput;
procedure Binding(Quiz: TQuiz);
procedure QuestionSet(NextNumber: Integer);
end;
implementation
{$R *.dfm}
{ TfrmQuestionInput }
procedure TfrmQuestionInput.Binding(Quiz: TQuiz);
begin
edNumber.Text := IntToStr(Quiz.QuizNumber);
edQuestion.Text := Quiz.Quiz;
end;
procedure TfrmQuestionInput.ClearInput;
begin
edNumber.Clear;
edQuestion.Clear;
end;
function TfrmQuestionInput.GetNumber: Integer;
begin
Result := StrToIntDef(edNumber.Text, 0);
end;
function TfrmQuestionInput.GetQuestion: String;
begin
Result := edQuestion.Text;
end;
function TfrmQuestionInput.NullCheck: boolean;
begin
Result := (edNumber.Text = '') or (edQuestion.Text = '');
end;
function TfrmQuestionInput.NumberNullCheck: boolean;
begin
Result := edNumber.Text = '';
end;
procedure TfrmQuestionInput.QuestionSet(NextNumber: Integer);
begin
edNumber.Text := IntToStr(NextNumber);
edQuestion.Clear;
end;
procedure TfrmQuestionInput.SetNumber(const Value: Integer);
begin
edNumber.Text := IntToStr(Value);
end;
procedure TfrmQuestionInput.SetQuestion(const Value: String);
begin
edQuestion.Text := Value;
end;
end.
|
program Sample;
var
A,B,C,D : Boolean;
begin
A := TRUE;
B := FALSE;
C := A or B;
D := A and B;
WriteLn('A = ',A);
WriteLn('B = ',B);
WriteLn('C = ',C);
WriteLn('D = ',D)
end.
|
unit SMCnst;
interface
{Chinese GB strings}
const
strMessage = '打印...';
strSaveChanges = '是否确认保存变更到数据库中?';
strErrSaveChanges = '保存失败, 请检查数据库连接.';
strDeleteWarning = '是否确认删除表 %s?';
strEmptyWarning = '是否确认清空表 %s?';
const
PopUpCaption: array [0..24] of string[33] = // I think "string" is better
('增加记录',
'插入记录',
'编辑记录',
'删除记录',
'-',
'打印...',
'导出...',
'过滤...',
'查找...',
'-',
'保存变更',
'放弃保存变更',
'刷新',
'-',
'记录选取',
'选取当前记录',
'全选',
'-',
'不选取当前记录',
'全不选',
'-',
'保存列布局',
'恢复列布局',
'-',
'设置...');
const //for TSMSetDBGridDialog
SgbTitle = ' 标题 ';
SgbData = ' 数据 ';
STitleCaption = '标题:';
STitleAlignment = '对齐:';
STitleColor = '背景:';
STitleFont = '字体:';
SWidth = '宽度:';
SWidthFix = '字符';
SAlignLeft = '左';
SAlignRight = '右';
SAlignCenter = '居中';
const //for TSMDBFilterDialog
strEqual = '等于';
strNonEqual = '不等于';
strNonMore = '不大于';
strNonLess = '不小于';
strLessThan = '小于';
strLargeThan = '大于';
strExist = '为空';
strNonExist = '不为空';
strIn = '在列表中';
strBetween = '在范围内';
strLike = '包含'; // 模糊匹配
strOR = '或者';
strAND = '并且';
strField = '字段';
strCondition = '条件';
strValue = '值';
strAddCondition = ' 定义额外条件:';
strSelection = ' 选择下一条件的记录:';
strAddToList = '添加到列表';
strEditInList = '编辑列表项';
strDeleteFromList = '从列表中删除';
strTemplate = '过滤模板对话框';
strFLoadFrom = '装载...';
strFSaveAs = '另存为..';
strFDescription = '描述';
strFFileName = '文件名';
strFCreate = '创建: %s';
strFModify = '修改: %s';
strFProtect = '重写保护';
strFProtectErr = '文件被保护!';
const //for SMDBNavigator
SFirstRecord = '第一条记录';
SPriorRecord = '上一条记录';
SNextRecord = '下一条记录';
SLastRecord = '最后一条记录';
SInsertRecord = '插入记录';
SCopyRecord = '复制记录';
SDeleteRecord = '删除记录';
SEditRecord = '编辑记录';
SFilterRecord = '过滤条件';
SFindRecord = '查找记录';
SPrintRecord = '打印记录';
SExportRecord = '导出记录';
SPostEdit = '保存变更';
SCancelEdit = '取消变更';
SRefreshRecord = '刷新数据';
SChoice = '选择一条记录';
SClear = '清除选择记录';
SDeleteRecordQuestion = '删除记录?';
SDeleteMultipleRecordsQuestion = '是否确认删除选取的记录?';
SRecordNotFound = '记录不存在';
SFirstName = '第一';
SPriorName = '上一';
SNextName = '下一';
SLastName = '最后';
SInsertName = '插入';
SCopyName = '复制';
SDeleteName = '删除';
SEditName = '编辑';
SFilterName = '过滤';
SFindName = '查找';
SPrintName = '打印';
SExportName = '导出';
SPostName = '保存';
SCancelName = '取消';
SRefreshName = '刷新';
SChoiceName = '选择';
SClearName = '清除'; //???
SBtnOk = '确定(&O)';
SBtnCancel = '取消(&C)';
SBtnLoad = '装载';
SBtnSave = '保存';
SBtnCopy = '复制';
SBtnPaste = '粘贴';
SBtnClear = '清除';
SRecNo = '记录 ';
SRecOf = ' 共 ';
const //for EditTyped
etValidNumber = '合法的数字';
etValidInteger = '合法的整数';
etValidDateTime = '合法的日期/时间';
etValidDate = '合法的日期';
etValidTime = '合法的时间';
etValid = '合法的';
etIsNot = '不是一个';
etOutOfRange = '值 %s 超出范围 %s..%s';
SApplyAll = '应用到所有';
implementation
end. |
unit PRFWK_Utilidades;
interface
uses PRFWK_Classe, Forms, SysUtils, StrUtils, IniFiles, Windows, Classes, Graphics;
type
TPRFWK_Utilidades = class(TPRFWK_Classe)
private
function replaceSubstring( stringAntiga, stringNova, s : string ) : string;
function extenso3em3( Numero : Word ) : string;
public
class function obterInstancia():TPRFWK_Utilidades;
function obterPastaProjeto():String;
function obterIniProjeto():String;
function obterConfiguracao(sessao: string; ident: string; padrao: string = ''): String;
function obterConfiguracaoAsBoolean(sessao: string; ident: string; padrao: boolean = true): Boolean;
procedure definirConfiguracao(sessao: string; ident: string; valor: string = '');
procedure definirConfiguracaoAsBoolean(sessao, ident:string; valor: Boolean);
function existeIniProjeto():Boolean;
procedure msgInf(texto:String);
procedure msgCrit(texto:String);
function msgPerg(texto:String):Boolean;
procedure msgAlerta(texto:String);
procedure criarForm(NomeForm: TFormClass);
function extenso( Numero : extended ) : string;
function diaSemana(Data: TDateTime): String;
function minutoParaHora(Minutos: Integer): String;
function horaParaMinuto(const s: string; const sep: string = ':'): Integer;
function formatarValorString(Valor:Extended; Precisao: Byte = 2):String;
procedure textoEntreTags( Const S: String; Tag1, Tag2: String; list:TStrings );
function uRLEncode(const S: string; const InQueryString: Boolean): string;
function dataValida(data: Variant; valorDoBanco: Boolean):String;
function obterDataNula(): String;
function converteDataAccess(data: String; incluiFuncao: Boolean = true):String;
function converteDataMysql(data: String):String;
function colorToString(const colColor: TColor; const revert: Boolean = false): string;
function stringToColor(sColor: string; const revert: Boolean = false): Cardinal;
published
end;
const
DATANULA = '01/01/1500';
var
instancia : TPRFWK_Utilidades;
implementation
{ TUtilidades }
{*
* Retorna uma configuração do arquivo de configuração do projeto
*}
function TPRFWK_Utilidades.obterConfiguracao(sessao: string; ident: string; padrao: string = ''): String;
var
lIni : TIniFile;
lTemp : String;
begin
lTemp := obterIniProjeto();
if existeIniProjeto() then
begin
try
lIni := TIniFile.Create(lTemp);
Result := lIni.ReadString(sessao, ident, padrao);
except
msgCrit('Erro ao tentar obter informação do arquivo de configurações.');
Result := '';
end;
end
else
begin
msgCrit('Arquivo de configuração não encontrado.');
end;
end;
{*
* Retorna true/false para uma configuração do arquivo de configuração do projeto
*}
function TPRFWK_Utilidades.obterConfiguracaoAsBoolean(sessao: string; ident: string; padrao: boolean = true): boolean;
var
lTemp : String;
lPadrao : String;
begin
try
if (padrao = true) then
lPadrao := '1'
else
lPadrao := '0';
lTemp := obterConfiguracao(sessao, ident, lPadrao);
if (Trim(lTemp) = '1') then
begin
Result := true;
end
else
begin
Result := false;
end;
except
msgCrit('Erro ao tentar obter informação do arquivo de configurações.');
Result := padrao;
end;
end;
{*
* Retorna o arquivo INI correspondente ao projeto atual
*}
function TPRFWK_Utilidades.obterIniProjeto: String;
begin
Result := obterPastaProjeto + 'config.ini';
end;
{*
* Retorna a instância da classe (Singleton)
*}
class function TPRFWK_Utilidades.obterInstancia(): TPRFWK_Utilidades;
begin
if instancia = nil then
instancia := TPRFWK_Utilidades.Create();
Result := instancia;
end;
{*
* Retorna se existe ou não o arquivo INI do projeto atual
*}
function TPRFWK_Utilidades.existeIniProjeto():Boolean;
begin
if FileExists(obterIniProjeto()) then
Result := true
else
Result := false;
end;
{*
* Retorna a pasta do projeto atual
*}
function TPRFWK_Utilidades.obterPastaProjeto: String;
var
lTemp : String;
begin
lTemp := ExtractFilePath( Application.ExeName );
lTemp := ReplaceStr(lTemp, '/', '\');
if (RightStr(lTemp,1) <> '\') then
lTemp := lTemp + '\';
Result := lTemp;
end;
{*
* Cria mensagem de informação
*}
procedure TPRFWK_Utilidades.msgInf(texto:String);
begin
MessageBox(Application.Handle, PChar(Texto), PChar('Mensagem'), $00000040);
end;
{*
* Cria mensagem de crítica
*}
procedure TPRFWK_Utilidades.msgCrit(texto:String);
begin
MessageBox(Application.Handle, PChar(Texto), PChar('Mensagem'), $00000010);
end;
{*
* Cria mensagem de alerta
*}
procedure TPRFWK_Utilidades.msgAlerta(texto:String);
begin
MessageBox(Application.Handle, PChar(Texto), PChar('Mensagem'), $00000030);
end;
{*
* Cria mensagem de pergunta
*}
function TPRFWK_Utilidades.msgPerg(texto:String):Boolean;
begin
if MessageBox(Application.Handle, PChar(Texto), PChar('Mensagem'), $00000024) = IDYES then
begin
Result:= True;
end
else
begin
Result:= False;
end;
end;
{*
* Cria form em runtime como modal
*}
procedure TPRFWK_Utilidades.criarForm(NomeForm: TFormClass);
begin
Try
TForm (NomeForm) := NomeForm.Create(Application);
if (TForm (NomeForm) <> nil) then
begin
TForm (NomeForm).ShowModal;
end;
Finally
FreeAndNil(NomeForm);
End;
end;
{*
* Substitui string
*}
function TPRFWK_Utilidades.replaceSubstring( stringAntiga, stringNova, s : string ) : string;
var p : word;
begin
repeat
p := Pos( stringAntiga, s );
if p > 0 then begin
Delete( s, p, Length( stringAntiga ) );
Insert( stringNova, s, p );
end;
until p = 0;
replaceSubstring := s;
end;
{*
* Esta é a função que gera os blocos de extenso que depois serão montados
*}
function TPRFWK_Utilidades.extenso3em3( Numero : Word ) : string;
const Valores : array[1..36] of word = ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
13, 14, 15, 16, 17, 18, 19, 20, 30, 40, 50, 60, 70, 80, 90,
100, 200, 300, 400, 500, 600, 700, 800, 900 );
Nomes : array[0..36] of string[12] = ( '', 'UM', 'DOIS', 'TRÊS', 'QUATRO',
'CINCO', 'SEIS', 'SETE', 'OITO', 'NOVE', 'DEZ', 'ONZE',
'DOZE', 'TREZE', 'QUATORZE', 'QUINZE', 'DEZESSEIS',
'DEZESSETE', 'DEZOITO', 'DEZENOVE', 'VINTE', 'TRINTA',
'QUARENTA', 'CINQÜENTA', 'SESSENTA', 'SETENTA', 'OITENTA',
'NOVENTA', 'CENTO', 'DUZENTOS', 'TREZENTOS', 'QUATROCENTOS',
'QUINHENTOS', 'SEISCENTOS', 'SETECENTOS', 'OITOCENTOS',
'NOVECENTOS' );
var i : byte;
Resposta : string;
Inteiro : word;
Resto : word;
begin
Inteiro := Numero;
Resposta := '';
for i := 36 downto 1 do begin
Resto := ( Inteiro div valores[i] ) * valores[i];
if ( Resto = valores[i] ) and ( Inteiro >= Resto ) then begin
Resposta := Resposta + Nomes[i] + ' E ';
Inteiro := Inteiro - Valores[i];
end;
end;
{ Corta o 'E' excedente do final da string }
extenso3em3 := Copy( Resposta, 1, Length( Resposta ) - 3 );
end;
{*
* Função que retorna o valor passado por parâmetro em extenso
*}
function TPRFWK_Utilidades.extenso( Numero : extended ) : string;
const NoSingular : array[1..6] of string = ( 'TRILHÃO', 'BILHÃO', 'MILHÃO', 'MIL',
'REAL', 'CENTAVO' );
NoPlural : array[1..6] of string = ( 'TRILHÕES', 'BILHÕES', 'MILHÕES', 'MIL',
'REAIS', 'CENTAVOS' );
{
Estas constantes facilitam o entendimento do código.
Como os valores de singular e plural são armazenados em um vetor,
cada posicao indica a grandeza do número armazenado (leia-se sempre
da esquerda para a direita).
}
CasaDosTrilhoes = 1;
CasaDosBilhoes = CasaDosTrilhoes + 1;
CasaDosMilhoes = CasaDosBilhoes + 1;
CasaDosMilhares = CasaDosMilhoes + 1;
CasaDasCentenas = CasaDosMilhares + 1;
CasaDosCentavos = CasaDasCentenas + 1;
var TrioAtual,
TrioPosterior : byte;
v : integer; { usada apenas com o Val }
Resposta : array[CasaDosTrilhoes..CasaDosCentavos] of string;
RespostaN : array[CasaDosTrilhoes..CasaDosCentavos] of word;
Plural : array[CasaDosTrilhoes..CasaDosCentavos] of boolean;
Inteiro : extended;
NumStr : string;
TriosUsados : set of CasaDosTrilhoes..CasaDosCentavos;
NumTriosInt : byte;
{ Para os não pascalistas de tradição, observe o uso de uma função
encapsulada na outra. }
function ProximoTrio( i : byte ) : byte;
begin
repeat
Inc( i );
until ( i in TriosUsados ) or ( i >= CasaDosCentavos );
ProximoTrio := i;
end;
begin
Inteiro := Int( Numero * 100 );
{ Inicializa os vetores }
for TrioAtual := CasaDosTrilhoes to CasaDosCentavos do begin
Resposta[TrioAtual] := '';
Plural[TrioAtual] := False;
end;
{
O número é quebrado em partes distintas, agrupadas de três em três casas:
centenas, milhares, milhões, bilhões e trilhões. A última parte (a sexta)
contém apenas os centavos, com duas casas
}
Str( Inteiro : 17 : 0, NumStr );
TrioAtual := 1;
Inteiro := Int( Inteiro / 100 ); { remove os centavos }
{ Preenche os espaços vazios com zeros para evitar erros de conversão }
while NumStr[TrioAtual] = ' ' do begin
NumStr[TrioAtual] := '0';
Inc( TrioAtual );
end;
{ Inicializa o conjunto como vazio }
TriosUsados := [];
NumTriosInt := 0; { Números de trios da parte inteira (sem os centavos) }
{ Este loop gera os extensos de cada parte do número }
for TrioAtual := CasaDosTrilhoes to CasaDosCentavos do begin
Val( Copy( NumStr, 3 * TrioAtual - 2, 3 ), RespostaN[TrioAtual], v );
if RespostaN[TrioAtual] <> 0 then begin
Resposta[TrioAtual] := Resposta[TrioAtual] +
extenso3em3( RespostaN[TrioAtual] );
TriosUsados := TriosUsados + [ TrioAtual ];
Inc( NumTriosInt );
if RespostaN[TrioAtual] > 1 then begin
Plural[TrioAtual] := True;
end;
end;
end;
if CasaDosCentavos in TriosUsados then
Dec( NumTriosInt );
{ Gerar a resposta propriamente dita }
NumStr := '';
{
Este trecho obriga que o nome da moeda seja sempre impresso no caso de
haver uma parte inteira, qualquer que seja o valor.
}
if (Resposta[CasaDasCentenas]='') and ( Inteiro > 0 ) then begin
Resposta[CasaDasCentenas] := ' ';
Plural[CasaDasCentenas] := True;
TriosUsados := TriosUsados + [ CasaDasCentenas ];
end;
{ Basta ser maior que um para que a palavra "real" seja escrita no plural }
if Inteiro > 1 then
Plural[CasaDasCentenas] := True;
{ Localiza o primeiro elemento }
TrioAtual := 0;
TrioPosterior := ProximoTrio( TrioAtual );
{ Localiza o segundo elemento }
TrioAtual := TrioPosterior;
TrioPosterior := ProximoTrio( TrioAtual );
{ Este loop vai percorrer apenas os trios preenchidos e saltar os vazios. }
while TrioAtual <= CasaDosCentavos do begin
{ se for apenas cem, não escrever 'cento' }
if Resposta[TrioAtual] = 'CENTO' then
Resposta[TrioAtual] := 'CEM';
{ Verifica se a resposta deve ser no plural ou no singular }
if Resposta[TrioAtual] <> '' then begin
NumStr := NumStr + Resposta[TrioAtual] + ' ';
if plural[TrioAtual] then
NumStr := NumStr + NoPlural[TrioAtual] + ' '
else
NumStr := NumStr + NoSingular[TrioAtual] + ' ';
{ Verifica a necessidade da particula 'e' para os números }
if ( TrioAtual < CasaDosCentavos ) and ( Resposta[TrioPosterior] <> '' )
and ( Resposta[TrioPosterior] <> ' ' ) then begin
{
Este trecho analisa diversos fatores e decide entre usar uma
vírgula ou um "E", em função de uma peculiaridade da língua. Veja
os exemplos para compreender:
- DOIS MIL, QUINHENTOS E CINQÜENTA REAIS
- DOIS MIL E QUINHENTOS REAIS
- DOIS MIL E UM REAIS
- TRÊS MIL E NOVENTA E CINCO REAIS
- QUATRO MIL, CENTO E UM REAIS
- UM MILHÃO E DUZENTOS MIL REAIS
- UM MILHÃO, DUZENTOS MIL E UM REAIS
- UM MILHÃO, OITOCENTOS E NOVENTA REAIS
Obs.: Fiz o máximo esforço pra que o extenso soasse o mais natural
possível em relação à lingua falada, mas se aparecer alguma
situação em que algo soe esquisito, peço a gentileza de me
avisar.
}
if ( TrioAtual < CasaDosCentavos ) and
( ( NumTriosInt = 2 ) or ( TrioAtual = CasaDosMilhares ) ) and
( ( RespostaN[TrioPosterior] <= 100 ) or
( RespostaN[TrioPosterior] mod 100 = 0 ) ) then
NumStr := NumStr + 'E '
else
NumStr := NumStr + ', ';
end;
end;
{ se for apenas trilhões, bilhões ou milhões, acrescenta o 'de' }
if ( NumTriosInt = 1 ) and ( Inteiro > 0 ) and ( TrioAtual <= CasaDosMilhoes ) then begin
NumStr := NumStr + ' DE ';
end;
{ se tiver centavos, acrescenta a partícula 'e', mas somente se houver
qualquer valor na parte inteira }
if ( TrioAtual = CasaDasCentenas ) and ( Resposta[CasaDosCentavos] <> '' )
and ( inteiro > 0 ) then begin
NumStr := Copy( NumStr, 1, Length( NumStr ) - 2 ) + ' E ';
end;
TrioAtual := ProximoTrio( TrioAtual );
TrioPosterior := ProximoTrio( TrioAtual );
end;
{ Eliminar algumas situações em que o extenso gera excessos de espaços
da resposta. Mero perfeccionismo... }
NumStr := ReplaceSubstring( ' ', ' ', NumStr );
NumStr := ReplaceSubstring( ' ,', ',', NumStr );
Extenso := NumStr;
end;
{*
* Função que retorna os textos entre as tags especificadas
*}
procedure TPRFWK_Utilidades.textoEntreTags( Const S: String; Tag1, Tag2: String; list:TStrings );
Var
pScan, pEnd, pTag1, pTag2: PChar;
foundText: String;
searchtext: String;
Begin
searchtext := Uppercase(S);
Tag1:= Uppercase( Tag1 );
Tag2:= Uppercase( Tag2 );
pTag1:= PChar(Tag1);
pTag2:= PChar(Tag2);
pScan:= PChar(searchtext);
Repeat
{ Search for next occurence of Tag1. }
pScan:= StrPos( pScan, pTag1 );
If pScan <> Nil Then Begin
{ Found one, hop over it, then search from that position
forward for the next occurence of Tag2. }
Inc(pScan, Length( Tag1 ));
pEnd := StrPos( pScan, pTag2 );
If pEnd <> Nil Then Begin
{ Found start and end tag, isolate text between,
add it to the list. We need to get the text from
the original S, however, since we want the un-uppercased
version!}
SetString( foundText, Pchar(S) + (pScan- PChar(searchtext) ), pEnd-pScan );
list.Add( foundText );
{ Continue next search after the found end tag. }
pScan := pEnd + Length(tag2);
End { If }
Else { Error, no end tag found for start tag, abort. }
pScan := Nil;
End; { If }
Until pScan = Nil;
End;
{*
* Função que faz o encode de uma url
*}
function TPRFWK_Utilidades.uRLEncode(const S: string; const InQueryString: Boolean): string;
var
Idx: Integer; // loops thru characters in string
begin
Result := '';
for Idx := 1 to Length(S) do
begin
case S[Idx] of
'A'..'Z', 'a'..'z', '0'..'9', '-', '_', '.':
Result := Result + S[Idx];
' ':
if InQueryString then
Result := Result + '+'
else
Result := Result + '%20';
else
Result := Result + '%' + SysUtils.IntToHex(Ord(S[Idx]), 2);
end;
end;
end;
{*
* Função que retorna o dia da semana em extenso
*}
function TPRFWK_Utilidades.diaSemana(Data: TDateTime): String;
{Retorna o dia da semana em Extenso de uma determinada data}
const
Dias : Array[1..7] of String[07] = ('DOMINGO', 'SEGUNDA', 'TERÇA','QUARTA','QUINTA', 'SEXTA','SÁBADO');
begin
Result := Dias[DayOfWeek(Data)];
end;
{*
* Função que retorna em formato de hora os minutos informados
*}
function TPRFWK_Utilidades.minutoParaHora(Minutos: Integer): String;
begin
Result := AnsiReplaceStr( format('%.2d:%.2d',[Minutos div 60,Minutos mod 60]) , '24:', '00:');
end;
{*
* Função que retorna em minutos a hora informada
*}
function TPRFWK_Utilidades.horaParaMinuto(const s: string; const sep: string = ':'): Integer;
var
h,m: shortstring;
p : integer;
_h,_m: integer;
begin
Result:= -1;
p:= Pos(sep,s);
if (p = 0) then
exit;
h:= copy(s,1,p-1);
m:= copy(s,p+1,length(s));
Result:= -2;
if TryStrToInt(h,_h) and TryStrToInt(m,_m) then
Result:= _h * 60 + _m;
end;
{*
* Função que formata um valor para o formato padrão do banco de dados
*}
function TPRFWK_Utilidades.formatarValorString(Valor:Extended; Precisao: Byte = 2):String;
begin
Result := ReplaceStr( CurrToStrF(Valor, ffNumber, 2), '.', '');
end;
{*
* Função que retorna uma data válida, verificando a data nula
*}
function TPRFWK_Utilidades.dataValida(data: Variant; valorDoBanco: Boolean):String;
var
dataTemp1: TDateTime;
dataTemp2: String;
begin
//verifica se é do banco ou não a data informada
if valorDoBanco = false then
begin
try
dataTemp1 := StrToDate(data);
Result := FormatDateTime('dd/mm/yyyy', dataTemp1);
except
Result := DATANULA;
end;
end
else
begin
try
dataTemp2 := FormatDateTime('dd/mm/yyyy', data);
if dataTemp2 = DATANULA then
Result := ''
else
Result := FormatDateTime('dd/mm/yyyy', data);
except
Result := '';
end;
end;
end;
{*
* Define uma configuração do arquivo de configuração do projeto
*}
procedure TPRFWK_Utilidades.definirConfiguracao(sessao, ident, valor: string);
var
lIni : TIniFile;
lTemp : String;
begin
lTemp := obterIniProjeto();
if existeIniProjeto() then
begin
try
lIni := TIniFile.Create(lTemp);
lIni.WriteString(sessao, ident, valor);
except
msgCrit('Erro ao tentar definir informação no arquivo de configurações.');
end;
end
else
begin
msgCrit('Arquivo de configuração não encontrado.');
end;
end;
{*
* Define uma configuração do arquivo de configuração do projeto como booleana
*}
procedure TPRFWK_Utilidades.definirConfiguracaoAsBoolean(sessao, ident:string; valor: Boolean);
var
lTemp : String;
begin
try
if (valor = true) then
lTemp := '1'
else
lTemp := '0';
definirConfiguracao(sessao, ident, lTemp);
except
msgCrit('Erro ao tentar definir informação no arquivo de configurações.');
end;
end;
{*
* Retorna a data nula
*}
function TPRFWK_Utilidades.obterDataNula(): String;
begin
Result := DATANULA;
end;
{*
* Retorna uma data no padrão MS-ACCESS
*}
function TPRFWK_Utilidades.converteDataAccess(data: String; incluiFuncao: Boolean = true):String;
var
dataTemp1: TDateTime;
dataTemp2: String;
begin
try
dataTemp1 := StrToDate(data);
if incluiFuncao = true then
dataTemp2 := dataTemp2 + 'DATESERIAL(';
dataTemp2 := dataTemp2 + FormatDateTime('yyyy , mm , dd', dataTemp1);
if incluiFuncao = true then
dataTemp2 := dataTemp2 + ')';
Result := dataTemp2;
except
Result := data;
end;
end;
{*
* Retorna uma data no padrão MYSQL
*}
function TPRFWK_Utilidades.converteDataMysql(data: String):String;
var
dataTemp1: TDateTime;
dataTemp2: String;
begin
try
dataTemp1 := StrToDate(data);
dataTemp2 := FormatDateTime('yyyy-mm-dd', dataTemp1);
Result := dataTemp2;
except
Result := data;
end;
end;
{*
* Converte uma color(TColor) para uma string em hexadecimal
*}
function TPRFWK_Utilidades.colorToString(const colColor: TColor; const revert: Boolean = false): string;
begin
if (revert = true) then
Result := '$' + IntToHex(GetBValue(colColor), 2) + IntToHex(GetGValue(colColor), 2) + IntToHex(GetRValue(colColor), 2)
else
Result := '$' + IntToHex(GetRValue(colColor), 2) + IntToHex(GetGValue(colColor), 2) + IntToHex(GetBValue(colColor), 2);
end;
{*
* Converte uma string em hexadecimal para color(TColor)
*}
function TPRFWK_Utilidades.stringToColor(sColor: string; const revert: Boolean = false): Cardinal;
begin
if (Copy(sColor, 1, 1) = '$') then
sColor := Copy(sColor, 2, 6);
if (revert = true) then
Result := RGB(StrToInt('$' + Copy(sColor, 5, 2)), StrToInt('$' + Copy(sColor, 3, 2)), StrToInt('$' + Copy(sColor, 1, 2)))
else
Result := RGB(StrToInt('$' + Copy(sColor, 1, 2)), StrToInt('$' + Copy(sColor, 3, 2)), StrToInt('$' + Copy(sColor, 5, 2)));
end;
end.
|
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, Spin,
ComCtrls, StdCtrls;
type
{ TForm1 }
TForm1 = class(TForm)
Button1: TButton;
Image1: TImage;
Panel1: TPanel;
SpinEdit1: TSpinEdit;
SpinEdit2: TSpinEdit;
Timer1: TTimer;
TrackBar1: TTrackBar;
TrackBar2: TTrackBar;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure TrackBar1Change(Sender: TObject);
procedure TrackBar2Change(Sender: TObject);
private
FRunning: boolean;
function SignalX: single;
function SignalY: single;
procedure Draw;
public
t: single;
Scale: TPoint;
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ TForm1 }
procedure TForm1.TrackBar1Change(Sender: TObject);
begin
Scale.x := TrackBar1.Position;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
if not FRunning then
begin
Button1.Caption := 'Stop';
Image1.Canvas.Brush.Color := clWhite;
Image1.Canvas.FillRect(Image1.ClientRect);
end
else
begin
Button1.Caption := 'Start';
t := 0;
end;
FRunning := not FRunning;
Timer1.Enabled := FRunning;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Scale := Point(TrackBar1.Position, TrackBar2.Position);
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
t := t + 0.05;
draw;
end;
procedure TForm1.TrackBar2Change(Sender: TObject);
begin
Scale.Y := TrackBar2.Position;
end;
procedure TForm1.Draw;
var
center: TPoint;
pt: TPoint;
begin
center := Point(Image1.Width div 2, Image1.Height div 2);
pt.X := center.X + Round(scale.X * signalX());
pt.Y := center.Y + Round(scale.Y * signalY());
Image1.Canvas.Brush.Color := clGreen;
Image1.Canvas.Rectangle(pt.X - 2, pt.Y - 2, pt.X + 2, pt.Y + 2);
end;
function TForm1.SignalX: single;
begin
Result := Sin(SpinEdit1.Value * t);
end;
function TForm1.SignalY: single;
begin
Result := Sin(SpinEdit2.Value * t);
end;
end.
|
unit uDMMoz;
interface
uses
SysUtils, Dialogs, Classes, Windows, LMDCustomComponent, LMDBaseController, LMDCustomContainer,
LMDGenericList, OleCtrls, MOZILLACONTROLLib_TLB, ActiveX;
type
TdmMoz = class(TDataModule)
glRoot: TLMDGenericList;
glComp: TLMDGenericList;
glDefaults_Pref: TLMDGenericList;
glGrepRefs: TLMDGenericList;
glIPC_Modules: TLMDGenericList;
glPlugins: TLMDGenericList;
glRes: TLMDGenericList;
glRes_Builtin: TLMDGenericList;
glRes_Dtd: TLMDGenericList;
glRes_entityTables: TLMDGenericList;
glRes_Fonts: TLMDGenericList;
glRes_Html: TLMDGenericList;
private
{ Private declarations }
procedure Extrai;
public
{ Public declarations }
end;
TThreadInstallMoz = class ( TThread )
protected
procedure Execute; override;
end;
procedure InstallMoz;
function CreateMoz(aOwner: TComponent; aParentWindow: HWND): TMozillaBrowser;
var
dmMoz: TdmMoz;
MozInstalled : Boolean = False;
implementation
uses ncShellStart, ncDebug;
{$R *.dfm}
{ TDataModule25 }
function CreateMoz(aOwner: TComponent; aParentWindow: HWND): TMozillaBrowser;
begin
Result := nil;
if MozInstalled then
try
Result := TMozillaBrowser.Create(aOwner);
Result.ParentWindow := aParentWindow;
except
on E: Exception do begin
DebugMsg('CreateMoz - Exception: ' + E.Message);
Result := nil;
end;
end;
end;
procedure TdmMoz.Extrai;
var
sBase, S: String;
T : Cardinal;
procedure ExtraiGL(GL : TLMDGenericList);
var I : Integer;
begin
for I := 0 to GL.Count - 1 do
with Gl.Items[I] do
try GL.Items[I].SaveToFile(S+FileName); except end;
end;
begin
T := GetTickCount;
sBase := ExtractFilePath(ParamStr(0));
sBase := sBase + 'moz\';
S := sBase;
if not DirectoryExists(S) then
MkDir(S);
ExtraiGL(glRoot);
S := sBase + 'components\';
if not DirectoryExists(S) then
MkDir(S);
ExtraiGL(glComp);
S := sBase + 'defaults\pref\';
if not DirectoryExists(S) then
ForceDirectories(S);
ExtraiGL(glDefaults_Pref);
S := sBase + 'greprefs\';
if not DirectoryExists(S) then
MkDir(S);
ExtraiGL(glGrepRefs);
S := sBase + 'ipc\modules\';
if not DirectoryExists(S) then
ForceDirectories(S);
ExtraiGL(glIPC_Modules);
S := sBase + 'plugins\';
if not DirectoryExists(S) then
MkDir(S);
ExtraiGL(glPlugins);
S := sBase + 'res\';
if not DirectoryExists(S) then
MkDir(S);
ExtraiGL(glRes);
S := sBase + 'res\builtin\';
if not DirectoryExists(S) then
ForceDirectories(S);
ExtraiGL(glRes_Builtin);
S := sBase + 'res\dtd\';
if not DirectoryExists(S) then
ForceDirectories(S);
ExtraiGL(glRes_DTD);
S := sBase + 'res\entityTables\';
if not DirectoryExists(S) then
ForceDirectories(S);
ExtraiGL(glRes_entityTables);
S := sBase + 'res\fonts\';
if not DirectoryExists(S) then
ForceDirectories(S);
ExtraiGL(glRes_fonts);
S := sBase + 'res\html\';
if not DirectoryExists(S) then
ForceDirectories(S);
ExtraiGL(glRes_html);
S := '/s ' + sBase + 'mozctlx.dll';
ShellStart('regsvr32', S);
end;
{ TThreadInstallMoz }
procedure TThreadInstallMoz.Execute;
var dm : TdmMoz;
begin
try
dm := TdmMoz.Create(nil);
try
dm.Extrai;
MozInstalled := True;
finally
dm.Free;
end;
except
end;
Free;
end;
procedure InstallMoz;
begin
if not MozInstalled then
TThreadInstallMoz.Create(False);
end;
Initialization
OleInitialize(nil);
Finalization
OleUninitialize;
end.
|
unit PascalCoin.Utils.Classes;
interface
uses System.Generics.Collections, System.Classes, System.SysUtils,
PascalCoin.Utils.Interfaces;
Type
TPascalCoinList<T> = class(TInterfacedObject, IPascalCoinList<T>)
private
FItems: TList<T>;
protected
function GetItem(const Index: Integer): T;
function Count: Integer;
function Add(Item: T): Integer;
procedure Delete(const Index: Integer);
procedure Clear;
public
constructor Create;
destructor Destroy; override;
end;
TPascalCoinTools = class(TInterfacedObject, IPascalCoinTools)
private
protected
function IsHexaString(const Value: string): Boolean;
function AccountNumberCheckSum(const Value: Cardinal): Integer;
function ValidAccountNumber(const Value: string): Boolean;
function SplitAccount(const Value: string; out AccountNumber: Cardinal;
out CheckSum: Integer): Boolean;
function ValidateAccountName(const Value: string): Boolean;
function UnixToLocalDate(const Value: Integer): TDateTime;
function StrToHex(const Value: string): string;
end;
implementation
uses System.DateUtils, clpConverters, clpEncoders;
{ TPascalCoinList<T> }
function TPascalCoinList<T>.Add(Item: T): Integer;
begin
result := FItems.Add(Item);
end;
procedure TPascalCoinList<T>.Clear;
begin
FItems.Clear;
end;
function TPascalCoinList<T>.Count: Integer;
begin
result := FItems.Count;
end;
constructor TPascalCoinList<T>.Create;
begin
inherited Create;
FItems := TList<T>.Create;
end;
procedure TPascalCoinList<T>.Delete(const Index: Integer);
begin
FItems.Delete(index);
end;
destructor TPascalCoinList<T>.Destroy;
begin
FItems.Free;
inherited;
end;
function TPascalCoinList<T>.GetItem(const Index: Integer): T;
begin
result := FItems[Index];
end;
{ TPascalCoinTools }
function TPascalCoinTools.AccountNumberCheckSum(const Value: Cardinal): Integer;
var
lVal: Int64;
begin
lVal := Value;
result := ((lVal * 101) MOD 89) + 10;
end;
function TPascalCoinTools.IsHexaString(const Value: string): Boolean;
var
i: Integer;
begin
result := true;
for i := Low(Value) to High(Value) do
if (NOT CharInSet(Value[i], ['0' .. '9'])) AND
(NOT CharInSet(Value[i], ['a' .. 'f'])) AND
(NOT CharInSet(Value[i], ['A' .. 'F'])) then
begin
result := false;
exit;
end;
end;
function TPascalCoinTools.SplitAccount(const Value: string;
out AccountNumber: Cardinal; out CheckSum: Integer): Boolean;
var
lVal: TArray<string>;
begin
if Value.IndexOf('-') > 0 then
begin
lVal := Value.Trim.Split(['-']);
AccountNumber := lVal[0].ToInt64;
CheckSum := lVal[1].ToInteger;
end
else
begin
AccountNumber := Value.ToInt64;
CheckSum := -1;
end;
end;
function TPascalCoinTools.StrToHex(const Value: string): string;
begin
result := THex.Encode(TConverters.ConvertStringToBytes(Value,
TEncoding.ANSI));
end;
function TPascalCoinTools.UnixToLocalDate(const Value: Integer): TDateTime;
begin
TTimeZone.Local.ToLocalTime(UnixToDateTime(Value));
end;
function TPascalCoinTools.ValidAccountNumber(const Value: string): Boolean;
var
lVal: TArray<string>;
lChk: Integer;
lAcct: Int64;
begin
result := false;
lVal := Value.Trim.Split(['-']);
if length(lVal) = 1 then
begin
if TryStrToInt64(lVal[0], lAcct) then
result := true;
end
else
begin
if TryStrToInt64(lVal[0], lAcct) then
begin
lChk := AccountNumberCheckSum(lVal[0].Trim.ToInt64);
result := lChk = lVal[1].Trim.ToInteger;
end;
end;
end;
function TPascalCoinTools.ValidateAccountName(const Value: string): Boolean;
var
i: Integer;
begin
result := true;
if Value = '' then
exit;
if Not CharInSet(Value.Chars[0], PascalCoinNameStart) then
exit(false);
if Value.length < 3 then
exit(false);
if Value.length > 64 then
exit(false);
for i := 0 to Value.length - 1 do
begin
if Not CharInSet(Value.Chars[i], PascalCoinEncoding) then
exit(false);
end;
end;
end.
|
CONST
CONNECT_MAX = 5;
DISCONNECT_MAX = 5;
COMMAND_MAX = 40;
RESPONSE_MAX = 10;
TYPE
LPSArrayType = ARRAY[0..RESPONSE_MAX] OF BYTE;
CommandStringType = STRING[COMMAND_MAX];
ResponseStringType = STRING[RESPONSE_MAX];
CfgRecordType = RECORD
command : CommandStringType;
response : ResponseStringType;
END;
VAR
configTimeout : INTEGER;
connectStrs : ARRAY [1..CONNECT_MAX] OF CfgRecordType;
disconnectStrs : ARRAY [1..DISCONNECT_MAX] OF CfgRecordType;
numConnectStrs,numDisconnectStrs : INTEGER;
modemTest : BOOLEAN;
PROCEDURE ReadConfigFile(VAR driveMap : INTEGER; VAR maxUser : BYTE);
CONST
cfgFileName = 'A:BACKUP.CFG';
CONNECT_MAX = 5;
DISCONNECT_MAX = 5;
TIMEOUT_DEFAULT = 5; { 1/10s of a second }
TAB = ^I;
TYPE
ExpectingType = (ANYTHING,CONNECT_OUT,DISCONNECT_OUT);
String80 = STRING[80];
VAR
cfgFile : TEXT;
line : STRING[80];
lng,result,lineNum,i : INTEGER;
break,ok : BOOLEAN;
expecting : ExpectingType;
PROCEDURE CfgError(errStr : String80; lineNum : INTEGER);
BEGIN
WriteLn('Error in line #',lineNum);
WriteLn(errStr);
Halt;
END;
BEGIN
numConnectStrs := 0;
numDisconnectStrs := 0;
configTimeout := TIMEOUT_DEFAULT;
modemTest := FALSE;
Assign(cfgFile,cfgFileName);
{$I-} Reset(cfgFile); {$I+}
IF IoResult = 0 THEN BEGIN
expecting := ANYTHING;
lineNum := 0;
WHILE NOT Eof(cfgFile) DO BEGIN
ReadLn(cfgFile,line);
lineNum := Succ(lineNum);
REPEAT
break := TRUE;
IF Length(line) > 0 THEN BEGIN
IF (line[1] = ' ') OR (line[1] = TAB) THEN BEGIN
line := Copy(line,2,80);
break := FALSE;
END;
END;
UNTIL Break;
lng := Length(line);
ok := FALSE;
IF lng > 0 THEN BEGIN
CASE expecting OF
ANYTHING:
BEGIN
IF lng > 8 THEN BEGIN
IF Copy(line,1,8) = 'Timeout:' THEN BEGIN
Val(Copy(line,9,5),configTimeout,result);
ok := result = 0;
END ELSE IF Copy(line,1,8) = 'MaxUser:' THEN BEGIN
Val(Copy(line,9,5),i,result);
maxUser := i;
ok := result = 0;
END;
END;
IF lng >= 9 THEN BEGIN
IF Copy(line,1,9) = 'ModemTest' THEN BEGIN
modemTest := TRUE;
ok := TRUE;
END ELSE IF Copy(line,1,9) = 'DriveMap:' THEN BEGIN
driveMap := 0;
FOR i := 10 TO Length(line) DO
IF line[i] in ['A'..'P'] THEN
driveMap := driveMap OR (1 SHL (Ord(line[i])-Ord('A')))
ELSE
CfgError('Bad drive letter in DriveMap', lineNum);
ok := TRUE;
END;
END;
IF lng > 10 THEN BEGIN
IF Copy(line,1,10) = 'ConnectIn:' THEN BEGIN
numConnectStrs := Succ(numConnectStrs);
IF numConnectStrs > CONNECT_MAX THEN BEGIN
Close(cfgFile);
CfgError('Too many connect strings', lineNum);
END;
connectStrs[numConnectStrs].Command := Copy(line,11,COMMAND_MAX);
expecting := CONNECT_OUT;
ok := TRUE;
END;
END;
IF lng > 13 THEN BEGIN
IF Copy(line,1,13) = 'DisconnectIn:' THEN BEGIN
numDisconnectStrs := Succ(numDisconnectStrs);
IF numDisconnectStrs > DISCONNECT_MAX THEN BEGIN
Close(cfgFile);
CfgError('Too many disconnect strings', lineNum);
END;
disconnectStrs[numDisconnectStrs].Command := Copy(line,14,COMMAND_MAX);
expecting := DISCONNECT_OUT;
ok := TRUE;
END;
END;
END;
CONNECT_OUT:
IF lng > 11 THEN BEGIN
IF Copy(line,1,11) = 'ConnectOut:' THEN BEGIN
connectStrs[numConnectStrs].Response := Copy(line,12,RESPONSE_MAX);
expecting := ANYTHING;
ok := TRUE;
END;
END;
DISCONNECT_OUT:
IF lng > 14 THEN BEGIN
IF Copy(line,1,14) = 'DisconnectOut:' THEN BEGIN
disconnectStrs[numDisconnectStrs].Response := Copy(line,15,RESPONSE_MAX);
expecting := ANYTHING;
ok := TRUE;
END;
END;
END;
IF NOT ok THEN BEGIN
WriteLn('Error in line #',lineNum);
WriteLn('Unexpected input: "',line,'"');
Close(cfgFile);
Halt;
END;
END;
END;
Close(cfgFile);
END;
END;
PROCEDURE computeLPSArray(pat : ResponseStringType; m : INTEGER; VAR lps : LPSArrayType);
VAR
len,i : INTEGER;
BEGIN
len := 0;
lps[0] := 0;
i := 1;
WHILE i < m DO BEGIN
IF pat[i+1] = pat[len+1] THEN BEGIN
len := Succ(len);
lps[i] := len;
i := Succ(i);
END ELSE BEGIN
IF len <> 0 THEN
len := lps[len-1]
ELSE BEGIN
lps[i] := 0;
i := Succ(i);
END;
END;
END;
END;
PROCEDURE SendCommand( cfgRecord : CfgRecordType );
CONST
CTRLC = ^C;
CR = ^M;
VAR
c : CHAR;
ticks,idx,lng : INTEGER;
responseSeen : BOOLEAN;
lps : LPSArrayType;
break : BOOLEAN;
BEGIN
lng := Length(cfgRecord.Response);
IF lng > 0 THEN
ComputeLpsArray(cfgRecord.Response, lng, lps);
Write(Aux,cfgRecord.Command,CR);
ticks := configTimeout * 50;
idx := 0;
responseSeen := lng = 0;
REPEAT
IF KeyPressed THEN BEGIN
Read(Kbd,c);
IF c = CTRLC THEN BEGIN
ticks := -1;
WriteLn('Abort #1');
END;
END ELSE IF ModemInReady THEN BEGIN
Read(Aux,c);
Write(c);
IF NOT responseSeen THEN BEGIN
break := FALSE;
REPEAT
IF cfgRecord.Response[idx+1] = c THEN BEGIN
idx := Succ(idx);
IF idx = lng THEN
responseSeen := TRUE;
break := TRUE;
END ELSE IF idx = 0 THEN
break := TRUE
ELSE
idx := lps[idx - 1]
UNTIL break;
END;
ticks := configTimeout * 50;
END ELSE IF responseSeen THEN BEGIN
ticks := Pred(ticks);
Delay(2);
END;
UNTIL ticks < 0;
END;
PROCEDURE ConnectRemote;
VAR
i : INTEGER;
BEGIN
IF modemTest THEN BEGIN
IF NOT IsOffline THEN BEGIN
WriteLn('Backup aborted: serial port is busy.');
Halt;
END;
END;
FOR i := 1 TO numConnectStrs DO
SendCommand(connectStrs[i]);
END;
PROCEDURE DisconnectRemote;
VAR
i : INTEGER;
BEGIN
FOR i := 1 TO numDisconnectStrs DO
SendCommand(disconnectStrs[i]);
END;
|
program khanHW3;
{ NAME: Camron Khan }
{ DATE: November 22, 2017 }
{ COURSE: CSC 540 - Graduate Research }
{ DESCRIPTION: This program simulates a 37-slot roulette table. It requires }
{ the number of requested spins and a target number to track. Upon }
{ completion the program generates data related to the doubles, triples, }
{ and even/odd runs, and it outputs this aggregated data to the console }
{ for the user. }
{ DATA: Below is sample data generated for HW3 (NOTE: All data is representing }
{ the number of spins, and the target number selected was 13). }
{ }
{ -------------- ------------ ------------- ----------- -------- ------- }
{ NUM SPINS AVG DBL FREQ AVG TRPL FREQ 1ST TGT DBL EVEN RUN ODD RUN }
{ -------------- ------------ ------------- ----------- -------- ------- }
{ 10,000 33.92 907.80 611 13 12 }
{ 1,000,000 35.76 1350.20 1674 19 16 }
{ 100,000,000 35.98 1376.50 2192 25 29 }
{ 10,000,000,000 35.99 1369.11 1212 33 30 }
uses sysutils;
const wheelLength = 37;
var i,
currentSpin,
resultN,
resultNMinusOne,
resultNMinusTwo,
targetNum : integer;
numSpins,
totalDoubles,
totalTriples,
totalSpinsBetweenDoubles,
totalSpinsBetweenTriples,
numSpinsSinceLastDouble,
numSpinsSinceLastTriple,
numSpinsForTargetDouble,
longestRunEvens,
longestRunOdds,
currentRunEvens,
currentRunOdds : qword;
procedure initializeVars();
begin
currentSpin := 0;
resultN := -1;
resultNMinusOne := -1;
resultNMinusTwo := -1;
targetNum := -1;
totalDoubles := 0;
totalTriples := 0;
totalSpinsBetweenDoubles := 0;
totalSpinsBetweenTriples := 0;
numSpinsSinceLastDouble := 0;
numSpinsSinceLastTriple := 0;
numSpinsForTargetDouble := 0;
longestRunEvens := 0;
longestRunOdds := 0;
currentRunEvens := 0;
currentRunOdds := 0;
end; {initializeVars}
procedure getUserInput();
{get user's desired number of spins and target number}
begin
WriteLn('--------------------');
WriteLn('WELCOME TO ROULETTE!');
WriteLn('--------------------');
repeat
write('Enter the number of spins: ');
readln(numSpins);
until numSpins > 0;
repeat
write('Select a number between 0 and 36: ');
readln(targetNum);
until (targetNum >= 0) and (targetNum <= 36);
WriteLn();
WriteLn();
end; {getUserInput}
procedure updateResults(val: integer);
{keep track of the last 3 spins to track doubles and triples spun}
begin
resultNMinusTwo := resultNMinusOne;
resultNMinusOne := resultN;
resultN := val;
end; {updateResults}
procedure evalTargetDoubles();
{evaluate if a double of the target number has been spun}
{tracks number of spins required to spin first double of target number}
begin
if ((resultN = targetNum) and (numSpinsForTargetDouble = 0)) then
numSpinsForTargetDouble := currentSpin;
end; {evalTargetDoubles}
procedure doublesSpun();
{increment counters for number of doubles and number of spins between doubles}
{reset counter tracking number of spins between doubles}
begin
evalTargetDoubles();
totalDoubles += 1;
totalSpinsBetweenDoubles += numSpinsSinceLastDouble;
numSpinsSinceLastDouble := 0;
end; {doublesSpun}
procedure doublesNotSpun();
{increment counter for number of spins between doubles}
begin
numSpinsSinceLastDouble += 1;
end; {doublesNotSpun}
procedure triplesSpun();
{increment counters for number of triples and number of spins between triples}
{reset counter tracking number of spins between triples}
begin
totalTriples += 1;
totalSpinsBetweenTriples += numSpinsSinceLastTriple;
numSpinsSinceLastTriple := 0;
end; {triplesSpun}
procedure triplesNotSpun();
{increment counter for number of spins between triples}
begin
numSpinsSinceLastTriple += 1;
end; {triplesNotSpun}
procedure doEvenRun();
{increment counter tracking evens run}
begin
currentRunEvens += 1;
end; {doEvenRun}
procedure doOddRun();
{increment counter tracking odds run}
begin
currentRunOdds += 1;
end; {doOddRun}
procedure endEvenRun();
{check if current even run is longer than longest previous even run}
{if so, update}
{reset even run counter}
begin
if (currentRunEvens > longestRunEvens) then
longestRunEvens := currentRunEvens;
currentRunEvens := 0;
end; {endEvenRun}
procedure endOddRun();
{check if current odd run is longer than longest previous odd run}
{if so, update}
{reset odd run counter}
begin
if (currentRunOdds > longestRunOdds) then
longestRunOdds := currentRunOdds;
currentRunOdds := 0;
end; {endOddRun}
procedure updateCountMetrics();
{monitor last three spins to determine doubles, triples, and even/odd runs}
begin
{check for double}
if (resultN = resultNMinusOne) then
doublesSpun()
else
doublesNotSpun();
{check for triple}
if ((resultN = resultNMinusOne) and (resultNMinusOne = resultNMinusTwo)) then
triplesSpun()
else
triplesNotSpun();
{check for even/odd runs}
if (resultN = 0) then
begin
endEvenRun();
endOddRun();
end;
if ((resultN mod 2) = 0) then
begin
doEvenRun();
endOddRun();
end
else
begin
doOddRun();
endEvenRun();
end;
end; {updateCountMetrics}
function calcAvg(total, n: integer): double;
{calculates the average given a total and number of observations}
{returns -1 if no observations}
begin
if (n > 0) then
calcAvg := total / n
else
calcAvg := -1;
end; {calcAvg}
procedure displayMetrics();
{send data to console}
var avgSpinsPerDoubles, avgSpinsPerTriples: double;
begin
{diplay general metrics}
writeln('-------');
writeln('GENERAL');
writeln('-------');
writeln('Total spins: ', currentSpin);
WriteLn();
WriteLn();
{display doubles metrics}
writeln('-------');
writeln('DOUBLES');
writeln('-------');
writeln('Total doubles: ', totalDoubles);
avgSpinsPerDoubles := calcAvg(totalSpinsBetweenDoubles, totalDoubles);
if (avgSpinsPerDoubles > 0) then
writeln('Average number of spins between doubles: ',
FormatFloat('0.00', avgSpinsPerDoubles));
WriteLn();
WriteLn();
{display triples metrics}
writeln('-------');
writeln('TRIPLES');
writeln('-------');
writeln('Total triples: ', totalTriples);
avgSpinsPerTriples := calcAvg(totalSpinsBetweenTriples, totalTriples);
if (avgSpinsPerTriples > 0) then
writeln('Average number of spins between triples: ',
FormatFloat('0.00', avgSpinsPerTriples));
WriteLn();
WriteLn();
{display target metrics}
writeln('------');
writeln('TARGET');
writeln('------');
if (numSpinsForTargetDouble > 0) then
writeln('Number of spins to hit doubles of number ', targetNum, ': ',
numSpinsForTargetDouble)
else
writeln('No doubles were spun of number ', targetNum);
WriteLn();
WriteLn();
{display even/odd metrics}
writeln('--------');
writeln('EVEN/ODD');
writeln('--------');
writeln('Longest evens run: ', longestRunEvens);
writeln('Longest odds run: ', longestRunOdds);
WriteLn();
WriteLn();
end; {displayMetrics}
procedure spinWheel();
{engine to simulate spinning of the roulette wheel}
{pseudorandomly generates a number between 0 and 36 inclusive}
{increments current spin counter}
var tempResult: integer;
begin
currentSpin += 1;
tempResult := Random(wheelLength);
updateResults(tempResult);
updateCountMetrics();
end; {spinWheel}
begin {main}
randomize;
initializeVars();
getUserInput();
for i := 1 to numSpins do
spinWheel();
displayMetrics();
writeln('Press ENTER to exit');
readln();
end. {main}
|
program quicksort;
type
list = array [0 .. 9] of char;
var
l: list;
i: integer;
procedure swap (i: ^char; j: ^char);
var
t: char;
begin
t := i^;
i^ := j^;
j^ := t
end;
procedure quick (l: ^list; a: integer; c: integer);
var
b: char;
i: integer;
j: integer;
t: char;
begin
if a < c then
begin
i := a;
j := c;
b := l^[a];
while i <= j do
begin
while l^[i] < b do i := i + 1;
while l^[j] > b do j := j - 1;
if (i <= j) then
begin
swap (^(l^[i]), ^(l^[j]));
i := i + 1;
j := j - 1
end
end;
quick (l, a, j);
quick (l, i, c)
end
end;
begin
l[0] := 'c';
l[1] := 'a';
l[2] := 'j';
l[3] := 'f';
l[4] := 'g';
l[5] := 'b';
l[6] := 'h';
l[7] := 'e';
l[8] := 'd';
l[9] := 'i';
for i := 0 to 9 do putch (l[i]);
putch (chr (10));
quick (^l, 0, 9);
for i := 0 to 9 do putch (l[i]);
putch (chr (10))
end.
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, FireDAC.UI.Intf, FireDAC.VCLUI.Wait,
FireDAC.Stan.Intf, FireDAC.Comp.UI, FBZabuuWaitCursor, FDZabuuReplicator,
Vcl.StdCtrls, Vcl.Menus;
type
TForm1 = class(TForm)
FDZabuuReplicator1: TFDZabuuReplicator;
FBZabuuWaitCursor1: TFBZabuuWaitCursor;
memoLog: TMemo;
btnStart: TButton;
btnStop: TButton;
MainMenu1: TMainMenu;
Acoes1: TMenuItem;
CriarEstruturadoReplicadro1: TMenuItem;
CriarEstruturadeReplicaons1: TMenuItem;
procedure CriarEstruturadoReplicadro1Click(Sender: TObject);
procedure FDZabuuReplicator1Log(Value: string);
procedure CriarEstruturadeReplicaons1Click(Sender: TObject);
procedure btnStartClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.btnStartClick(Sender: TObject);
begin
FDZabuuReplicator1.Replicate;
end;
procedure TForm1.CriarEstruturadeReplicaons1Click(Sender: TObject);
begin
FDZabuuReplicator1.ApplyMetadata;
end;
procedure TForm1.CriarEstruturadoReplicadro1Click(Sender: TObject);
begin
FDZabuuReplicator1.ApplyMetadataBankReplicator;
end;
procedure TForm1.FDZabuuReplicator1Log(Value: string);
begin
memoLog.lines.Add(value)
end;
end.
|
{ Program MAKE_DSPIC_INC [pic]
*
* Make the include file for each dsPIC processor that has a linker file, or
* for a single specific processor. The include file will contain definitions
* of symbols found in the linker file that meet the following criteria:
*
* 1 - The name starts with an alphabetic character.
*
* 2 - All alphabetic characters in the symbol are upper case.
*
* 3 - The symbol is assigned a literal integer constant.
*
* These symbols will be defined in the output file with .equiv statements.
* The symbol names in the output file will have the first character upper
* case, with all following aphabetic characters, if any, lower case.
*
* With the PIC command line option omitted, all linker files in the current
* dsPIC tools installation will be processed and an include file created for
* each of them.
*
* If the PIC command line option is provided, then only the file for that
* PIC will be created. PIC must be the model number without the preceeding
* "PIC". For example, "30F3013" and "24FJ256DA210". The PIC command line
* option is case-insensitive.
}
program make_dspic_inc;
%include 'base.ins.pas';
const
max_msg_args = 2; {max arguments we can pass to a message}
var
onlypic: {only create include file for this PIC}
%include '(cog)lib/string32.ins.pas';
npics: sys_int_machine_t; {number of PICs include file written for}
tnam: {scratch treename}
%include '(cog)lib/string_treename.ins.pas';
stat: sys_err_t; {completion status}
{
********************************************************************************
*
* Subroutine DO_DIR (DIR)
*
* Process all the linker files, if any, in the directory tree DIR. This
* routine calls itself recursively for any subdirectories.
*
* If the global string ONLYPIC is not empty, then only the include file for
* that PIC will be created.
*
* The global variable NPICS is incremented by 1 for each include file created.
}
procedure do_dir ( {process GLD files from one directory}
in dir: string_treename_t); {the directory to process .gld files from}
val_param; internal;
var
conn_dir: file_conn_t; {connection to the directory to scan}
conn_in: file_conn_t; {connection to linker input file}
conn_out: file_conn_t; {connection to output include file}
p: string_index_t; {parse index}
ii: sys_int_machine_t; {scratch integer and loop counter}
finfo: file_info_t; {info about directory entry}
radix: sys_int_machine_t; {radix of integer digits string}
ival: sys_int_max_t; {symbol integer value}
time: sys_clock_t; {scratch time descriptor}
c: char; {scratch character}
ibuf: string_var132_t; {one line input buffer}
obuf: string_var132_t; {one line output buffer}
tnam, tnam2: string_treename_t; {scratch treenames}
fnam: string_leafname_t; {current directory entry name}
gnam: string_leafname_t; {generic file name}
tk: string_var80_t; {scratch string or token}
name: string_var80_t; {symbol name}
sval: string_var80_t; {symbol's string value}
incdir: string_treename_t; {treename of directory containing .INC files}
incname: string_treename_t; {treename of include file for current linker file}
picname: string_var32_t; {upper case target PIC name, like "30F3013"}
picfam: string_var32_t; {lower case dsPIC family name, like 30f, 24h, etc}
msg_parm: {references arguments passed to a message}
array[1..max_msg_args] of sys_parm_msg_t;
stat: sys_err_t; {completion status}
label
loop_fnam, have_digit, loop_iline, have_ival, eof;
{
****************************************
*
* Local Subroutine WBUF
*
* Write the contents of OBUF to the output file as the next line and reset
* OBUF to empty.
}
procedure wbuf; {write OBUF to output file, clear OBUF}
var
stat: sys_err_t;
begin
file_write_text (obuf, conn_out, stat); {write the output line}
sys_error_abort (stat, '', '', nil, 0);
obuf.len := 0; {reset the output buffer to empty}
end;
{
****************************************
*
* Start of executable code of DO_DIR.
}
begin
ibuf.max := size_char(ibuf.str); {init local var strings}
obuf.max := size_char(obuf.str);
tnam.max := size_char(tnam.str);
tnam2.max := size_char(tnam2.str);
fnam.max := size_char(fnam.str);
gnam.max := size_char(gnam.str);
tk.max := size_char(tk.str);
name.max := size_char(name.str);
sval.max := size_char(sval.str);
incdir.max := size_char(incdir.str);
incname.max := size_char(incname.str);
picname.max := size_char(picname.str);
picfam.max := size_char(picfam.str);
{
* Open the directory for reading its entries.
}
file_open_read_dir (dir, conn_dir, stat);
sys_msg_parm_vstr (msg_parm[1], dir);
sys_error_abort (stat, 'pic', 'err_dspic_linkdir', msg_parm, 1);
{
* Read and process each directory entry. If the entry is a file name ending in
* ".gld", then process it as a linker file. If the entry is a directory then
* process it recursively.
}
loop_fnam: {back here each new linker files directory entry}
file_read_dir ( {get next linker files directory entry}
conn_dir, {connection to the directory}
[file_iflag_dtm_k, file_iflag_type_k], {info requested about this directory entry}
fnam, {returned directory entry name}
finfo, {info about this directory entry}
stat);
if file_eof(stat) then begin {hit end of directory ?}
file_close (conn_dir); {close the directory}
return; {all done}
end;
sys_error_abort (stat, '', '', nil, 0);
case finfo.ftype of
file_type_data_k: ; {fall thru to process files or links}
file_type_link_k: ;
file_type_dir_k: begin {this directory entry is a subdirectory}
string_copy (conn_dir.tnam, tnam); {make full subdirectory pathname}
string_append1 (tnam, '/');
string_append (tnam, fnam);
do_dir (tnam); {recursively process this subdirectory}
goto loop_fnam;
end;
otherwise
goto loop_fnam; {not a type we can handle, ignore this entry}
end;
if fnam.len < 5 then goto loop_fnam; {can't be at least x.gld file name ?}
string_substr ( {extract last 4 characters of file name}
fnam, {input string}
fnam.len - 3, {start index to extract from}
fnam.len, {end index to extract from}
gnam); {extracted string}
string_downcase (gnam);
if not string_equal (gnam, string_v('.gld')) {not a linker script file name ?}
then goto loop_fnam;
{
* This directory entry is a .gld file.
*
* Extract the PIC name in upper case into PICNAME. A example PIC name is
* 30F2010.
}
for ii := 1 to fnam.len do begin {scan generic name looking for first digit}
c := fnam.str[ii]; {fetch this character}
if (c >= '0') and (c <= '9') then goto have_digit;
end;
sys_msg_parm_vstr (msg_parm[1], fnam);
sys_message_parms ('pic', 'err_picname', msg_parm, 1);
goto loop_fnam;
have_digit: {II is index of first digit in generic input fnam}
string_substr (fnam, ii, fnam.len-4, picname); {extract the PIC name}
string_upcase (picname); {save PIC name all upper case}
{
* Skip this file if a specific PIC name was supplied and it does not match
* this file.
}
if onlypic.len > 0 then begin {only make file for specific PIC ?}
if not string_equal(picname, onlypic) then goto loop_fnam; {not the right PIC ?}
end;
{
* Make the PIC family name lower case in PICFAM. This is the family number
* followed by the first letter, like 24H and 33F.
}
for ii := 1 to picname.len do begin {scan looking for first non-digit of PIC name}
c := picname.str[ii]; {get this character}
if (c < '0') or (c > '9') then exit; {found first non-digit ?}
end;
ii := min(ii, picname.len); {make sure last char is within string}
string_substr (picname, 1, ii, picfam); {extract the PIC family designator}
string_downcase (picfam); {make final PIC family name in lower case}
{
* Set INCNAME to the full pathname of the corresponding Microchip include file
* for this PIC.
}
string_copy (conn_dir.tnam, tnam); {init to this directory name}
string_appends (tnam, '/../inc/'(0));
string_append (tnam, fnam);
tnam.len := tnam.len - 4; {remove .gld linker file name suffix}
string_appends (tnam, '.inc'(0));
string_treename (tnam, incname); {make full pathname of the include file}
if not file_exists (incname) {skip this GLD file if include file not exist}
then goto loop_fnam;
{
* Open this linker file for read on CONN_IN.
}
string_pathname_join (conn_dir.tnam, fnam, tnam2);
string_treename (tnam2, tnam); {make full treename of this linker file}
file_open_read_text (tnam, '.gld', conn_in, stat); {open linker file for read}
sys_error_abort (stat, '', '', nil, 0);
{
* Open the output file to create for this linker file.
}
file_open_write_text (conn_in.gnam, '.ins.dspic', conn_out, stat); {open output file}
sys_error_abort (stat, '', '', nil, 0);
time := sys_clock; {get time output file created}
writeln (conn_out.tnam.str:conn_out.tnam.len); {show name of output file being created}
{
* A linker script is open on CONN_IN, and the assembler include file to create from
* it is open on CONN_OUT.
}
obuf.len := 0; {init output buffer to empty}
string_appends (obuf, '; Derived from linker script "');
string_append (obuf, conn_in.tnam);
string_appends (obuf, '",');
wbuf;
string_appends (obuf, '; which was last changed at ');
sys_clock_str1 (finfo.modified, tk); {make linker file last modified date/time string}
string_append (obuf, tk);
string_append1 (obuf, '.');
wbuf;
string_appends (obuf, ';');
wbuf;
string_appends (obuf, '; Created by program MAKE_DSPIC_INC at ');
sys_clock_str1 (time, tk);
string_append (obuf, tk);
string_appends (obuf, ' on machine ');
sys_node_name (tk);
string_upcase (tk);
string_append (obuf, tk);
string_append1 (obuf, '.');
wbuf;
string_appends (obuf, ';');
wbuf;
string_appends (obuf, '/var new Picname string');
wbuf;
string_appends (obuf, '/set Picname "');
string_append (obuf, picname);
string_appends (obuf, '"');
wbuf;
string_appends (obuf, '.ifndef __');
string_append (obuf, picname);
wbuf;
string_appends (obuf, ' .equiv __');
string_append (obuf, picname);
string_appends (obuf, ', 1');
wbuf;
string_appends (obuf, ' .endif');
wbuf;
string_appends (obuf, '/include "');
string_append (obuf, incname);
string_appends (obuf, '"');
wbuf;
wbuf;
loop_iline: {back here each new linker file input line}
file_read_text (conn_in, ibuf, stat); {read next line from linker file}
if file_eof(stat) then goto eof; {end of file ?}
sys_error_abort (stat, '', '', nil, 0);
for ii := 1 to ibuf.len do begin {convert all control characters to spaces}
if ord(ibuf.str[ii]) < 32 then ibuf.str[ii] := ' ';
end;
string_unpad (ibuf); {truncate trailing spaces}
if ibuf.len <= 0 then goto loop_iline; {ignore blank lines}
p := 1; {init input line parse index}
{
* Get and validate the name of the symbol being defined. The symbol name
* converted to the format used in the output file will be left in NAME.
}
string_token_anyd ( {try to extract name symbol token before "="}
ibuf, {input string}
p, {parse index}
' =', 2, {list of delimiters}
1, {first N delimiters that may be repeated}
[string_tkopt_padsp_k], {strip leading/trailing blank padding around token}
name, {the extracted symbol name}
ii, {index of main ending delimiter}
stat);
if sys_error(stat) then goto loop_iline; {ignore line on parsing error}
if ii <> 2 then goto loop_iline; {token wasn't followed by equal sign ?}
if name.len <= 0 then goto loop_iline; {symbol name token is empty ?}
if (name.str[1] < 'A') or (name.str[1] > 'Z') {not start with upper case alphabetic char ?}
then goto loop_iline;
for ii := 2 to name.len do begin {scan remaining characters after the first}
if (name.str[ii] >= 'a') and (name.str[ii] <= 'z') {lower case alphabetic character ?}
then goto loop_iline;
name.str[ii] := string_downcase_char (name.str[ii]); {downcase to make output name}
end;
{
* Get the value being assinged to the symbol.
}
string_token_anyd ( {try to extract symbol value between "=" and ";"}
ibuf, {input string}
p, {parse index}
' ;', 2, {list of delimiters}
1, {first N delimiters that may be repeated}
[string_tkopt_padsp_k], {strip leading/trailing blank padding around token}
sval, {the extracted symbol value string}
ii, {index of main ending delimiter}
stat);
if sys_error(stat) then goto loop_iline; {ignore line on parsing error}
if ii <> 2 then goto loop_iline; {token wasn't followed by semicolon ?}
if sval.len <= 0 then goto loop_iline; {symbol value string is empty ?}
string_upcase (sval); {make value string all upper case}
if sval.str[1] <> '0' then begin {normal decimal integer ?}
string_t_int_max (sval, ival, stat);
if sys_error(stat) then goto loop_iline; {not a valid integer ?}
goto have_ival;
end;
case sval.str[2] of {what follows leading zero character ?}
'B': begin {binary}
radix := 2; {radix}
ii := 3; {start of integer index}
end;
'0', '1', '2', '3', '4', '5', '6', '7': begin {octal}
radix := 8; {radix}
ii := 2; {start of integer index}
end;
'X': begin {hexadecimal}
radix := 16; {radix}
ii := 3; {start of integer index}
end;
otherwise
goto loop_iline; {unexpected radix indicator, ignore line}
end;
if sval.len < ii then goto loop_iline; {string too short to be valid integer ?}
string_substr (sval, ii, sval.len, tk); {extract just the integer digits into TK}
string_t_int_max_base ( {convert digits string to integer value}
tk, {input string}
radix, {radix}
[string_ti_unsig_k], {convert digits as unsigned value}
ival, {resulting integer value}
stat);
if sys_error(stat) then goto loop_iline; {not a real integer value, ignore line ?}
have_ival: {symbol value is in IVAL}
{
* A valid symbol assignment was parsed from the current input line. The
* symbol name in output file format is in NAME, and its integer value is
* in IVAL.
*
* Now write the definition of this symbol to the output file.
}
string_appends (obuf, '.equiv ');
string_append (obuf, name);
string_appends (obuf, ', 0x');
string_f_int_max_base ( {make hexadecimal string of integer value}
tk, {output string}
ival, {input integer}
16, {radix}
0, {free form field width}
[string_fi_unsig_k], {assume input integer is unsigned}
stat);
sys_error_abort (stat, '', '', nil, 0);
string_append (obuf, tk);
wbuf; {write this line to the output file}
goto loop_iline; {back for next input file line}
eof: {end of linker input file encountered}
file_close (conn_in); {close the linker input file}
wbuf;
string_appends (obuf, '/include "lcase.ins.dspic"');
wbuf;
file_close (conn_out); {close the output file}
npics := npics + 1; {count one more include file created}
goto loop_fnam; {back to try next directory entry}
end;
{
********************************************************************************
*
* Start of main routine.
}
begin
string_cmline_init; {init for reading the command line}
string_cmline_token (onlypic, stat); {try to get single PIC to make file for}
if string_eos(stat)
then begin {end of command line}
onlypic.len := 0; {indicate make include file for all PICs}
end
else begin {got single PIC name or hard error}
sys_error_abort (stat, '', '', nil, 0); {abort on hard error}
string_upcase (onlypic); {command line arugment can be any case}
string_cmline_end_abort; {no more command line arguments allowed}
end
;
npics := 0; {init number of include files created}
string_vstring ( {set top of tree to search}
tnam, '(cog)extern/mplab/support16'(0), -1);
do_dir (tnam); {scan all linker files in the tree}
if onlypic.len > 0
then begin {creating file for a specific PIC only}
if npics <= 0 then begin {nothing created ?}
writeln ('No files found for the indicated PIC.');
sys_bomb;
end;
end
else begin {created files for all PICs}
writeln (npics, ' files created');
end
;
end.
|
unit DlgNameAddressUnit;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Mask, DBCtrls, Db, DBTables, Wwtable, Buttons, ToolWin,
ComCtrls, ExtCtrls;
type
TNameAddressDialogForm = class(TForm)
NameAddressGroupBox: TGroupBox;
Label11: TLabel;
Label12: TLabel;
Label13: TLabel;
Label14: TLabel;
Label15: TLabel;
SwisLabel: TLabel;
Label17: TLabel;
Label3: TLabel;
Label28: TLabel;
EditName1: TDBEdit;
EditName2: TDBEdit;
EditAddress: TDBEdit;
EditAddress2: TDBEdit;
EditStreet: TDBEdit;
EditCity: TDBEdit;
EditState: TDBEdit;
EditZip: TDBEdit;
EditZipPlus4: TDBEdit;
MainToolBar: TToolBar;
SaveButton: TSpeedButton;
CancelButton: TSpeedButton;
NameAddressTable: TwwTable;
NameAddressDataSource: TDataSource;
ButtonsStateTimer: TTimer;
lbl_PhoneNumber: TLabel;
edt_PhoneNumber: TDBEdit;
procedure SaveButtonClick(Sender: TObject);
procedure CancelButtonClick(Sender: TObject);
procedure ButtonsStateTimerTimer(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure EditZipPlus4Exit(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure edt_PhoneNumberExit(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
UnitName : String;
ShowPhoneNumber : Boolean;
Procedure InitializeForm(_SwisSBLKey : String;
_TableName : String;
_IndexName : String;
_RecordNumber : Integer;
_RecordNumberFieldName : String;
_EditMode : String;
_Title : String;
_ShowPhoneNumber : Boolean);
end;
var
NameAddressDialogForm : TNameAddressDialogForm;
implementation
{$R *.DFM}
uses DataAccessUnit, Utilitys, GlblCnst, WinUtils, GlblVars;
{=========================================================================}
Procedure TNameAddressDialogForm.ButtonsStateTimerTimer(Sender: TObject);
var
Enabled : Boolean;
begin
Enabled := NameAddressTable.Modified;
SaveButton.Enabled := Enabled;
CancelButton.Enabled := Enabled;
end; {ButtonsStateTimerTimer}
{=========================================================================}
Procedure TNameAddressDialogForm.InitializeForm(_SwisSBLKey : String;
_TableName : String;
_IndexName : String;
_RecordNumber : Integer;
_RecordNumberFieldName : String;
_EditMode : String;
_Title : String;
_ShowPhoneNumber : Boolean);
begin
UnitName := 'DlgNameAddressUnit';
with NameAddressTable do
try
If _Compare(_EditMode, emBrowse, coEqual)
then ReadOnly := True;
TableName := _TableName;
IndexName := _IndexName;
Open;
except
end;
If _Compare(_EditMode, [emBrowse, emEdit], coEqual)
then
begin
_Locate(NameAddressTable, [_SwisSBLKey, _RecordNumber], '', []);
If _Compare(_EditMode, emEdit, coEqual)
then NameAddressTable.Edit;
end
else _InsertRecord(NameAddressTable, ['SwisSBLKey', _RecordNumberFieldName],
[_SwisSBLKey, _RecordNumber], [irSuppressPost]);
Caption := _Title;
NameAddressGroupBox.Caption := ' ' + _Title + ' #' + IntToStr(_RecordNumber) + ': ';
ShowPhoneNumber := _ShowPhoneNumber;
If ShowPhoneNumber
then
begin
lbl_PhoneNumber.Visible := True;
edt_PhoneNumber.Visible := True;
edt_PhoneNumber.DataField := 'PhoneNumber';
end; {If ShowPhoneNumber}
ButtonsStateTimer.Enabled := True;
end; {InitializeForm}
{==========================================================}
Procedure TNameAddressDialogForm.FormKeyPress( Sender: TObject;
var Key: Char);
begin
If (Key = #13)
then
begin
Perform(WM_NEXTDLGCTL, 0, 0);
Key := #0;
end;
end; {FormKeyPress}
{==========================================================}
Procedure TNameAddressDialogForm.SaveButtonClick(Sender: TObject);
begin
try
NameAddressTable.Post;
ModalResult := mrOK;
except
SystemSupport(1, NameAddressTable, 'Error posting record.', UnitName, GlblErrorDlgBox);
end;
end; {SaveButtonClick}
{==========================================================}
Procedure TNameAddressDialogForm.CancelButtonClick(Sender: TObject);
begin
NameAddressTable.Cancel;
ModalResult := mrCancel;
end; {CancelButtonClick}
{=======================================================================}
Procedure TNameAddressDialogForm.EditZipPlus4Exit(Sender: TObject);
begin
If not ShowPhoneNumber
then Close;
end; {EditZipPlus4Exit}
{=======================================================================}
Procedure TNameAddressDialogForm.edt_PhoneNumberExit(Sender: TObject);
begin
Close;
end;
{=======================================================================}
Procedure TNameAddressDialogForm.FormCloseQuery( Sender: TObject;
var CanClose: Boolean);
var
Selection : Integer;
begin
CanClose := True;
If NameAddressTable.Modified
then
begin
Selection := MessageDlg('Do you want to save the changes?', mtConfirmation, [mbYes, mbNo, mbCancel], 0);
case Selection of
idYes : SaveButtonClick(Sender);
idNo : CancelButtonClick(Sender);
idCancel : CanClose := False;
end;
end; {If NameAddressTable.Modified}
end; {FormCloseQuery}
end.
|
unit uAccounting;
{$mode objfpc}{$H+}
interface
uses
SynCommons, mORMot, uForwardDeclaration;//Classes, SysUtils;
type
// 1
TSQLBudget = class(TSQLRecord)
private
fName: RawUTF8;
fBudgetType: TSQLBudgetTypeID;
fCustomTimePeriod: TSQLCustomTimePeriodID;
fComments: RawUTF8;
published
property Name: RawUTF8 read fName write fName;
property BudgetType: TSQLBudgetTypeID read fBudgetType write fBudgetType;
property CustomTimePeriod: TSQLCustomTimePeriodID read fCustomTimePeriod write fCustomTimePeriod;
property Comments: RawUTF8 read fComments write fComments;
end;
// 2
TSQLBudgetAttribute = class(TSQLRecord)
private
fBudget: TSQLBudgetID;
fAttrName: TSQLCostComponentTypeAttrID;
fAttrValue: RawUTF8;
fAttrDescription: RawUTF8;
published
property Budget: TSQLBudgetID read fBudget write fBudget;
property AttrName: TSQLCostComponentTypeAttrID read fAttrName write fAttrName;
property AttrValue: RawUTF8 read fAttrValue write fAttrValue;
property AttrDescription: RawUTF8 read fAttrDescription write fAttrDescription;
end;
// 3
TSQLBudgetItem = class(TSQLRecord)
private
fBudget: TSQLBudgetID;
fBudgetItemSeq: Integer;
fBudgetItemType: TSQLBudgetItemTypeID;
fAmount: Currency;
fPurpose: RawUTF8;
fJustification: RawUTF8;
published
property Budget: TSQLBudgetID read fBudget write fBudget;
property BudgetItemSeq: Integer read fBudgetItemSeq write fBudgetItemSeq;
property BudgetItemType: TSQLBudgetItemTypeID read fBudgetItemType write fBudgetItemType;
property Amount: Currency read fAmount write fAmount;
property Purpose: RawUTF8 read fPurpose write fPurpose;
property Justification: RawUTF8 read fJustification write fJustification;
end;
// 4
TSQLBudgetItemAttribute = class(TSQLRecord)
private
fBudget: TSQLBudgetID;
fBudgetItemSeq: Integer;
fAttrName: TSQLCostComponentTypeAttrID;
fAttrValue: RawUTF8;
fAttrDescription: RawUTF8;
published
property Budget: TSQLBudgetID read fBudget write fBudget;
property BudgetItemSeq: Integer read fBudgetItemSeq write fBudgetItemSeq;
property AttrName: TSQLCostComponentTypeAttrID read fAttrName write fAttrName;
property AttrValue: RawUTF8 read fAttrValue write fAttrValue;
property AttrDescription: RawUTF8 read fAttrDescription write fAttrDescription;
end;
// 5
TSQLBudgetItemType = class(TSQLRecord)
private
fEncode: RawUTF8;
fParentEncode: RawUTF8;
fParent: TSQLBudgetItemTypeID;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property ParentEncode: RawUTF8 read fParentEncode write fParentEncode;
property Parent: TSQLBudgetItemTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 6
TSQLBudgetItemTypeAttr = class(TSQLRecord)
private
fBudgetItemType: TSQLBudgetItemTypeID;
fAttrName: TSQLCostComponentTypeAttrID;
fAttrValue: RawUTF8;
fDescription: RawUTF8;
published
property BudgetItemType: TSQLBudgetItemTypeID read fBudgetItemType write fBudgetItemType;
property AttrName: TSQLCostComponentTypeAttrID read fAttrName write fAttrName;
property AttrValue: RawUTF8 read fAttrValue write fAttrValue;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 7
TSQLBudgetReview = class(TSQLRecord)
private
fBudget: TSQLBudgetID;
fParty: TSQLPartyID;
fBudgetReviewResultType: TSQLBudgetReviewResultTypeID;
fReviewDate: TDateTime;
published
property Budget: TSQLBudgetID read fBudget write fBudget;
property Party: TSQLPartyID read fParty write fParty;
property BudgetReviewResultType: TSQLBudgetReviewResultTypeID read fBudgetReviewResultType write fBudgetReviewResultType;
property ReviewDate: TDateTime read fReviewDate write fReviewDate;
end;
// 8
TSQLBudgetReviewResultType = class(TSQLRecord)
private
fEncode: RawUTF8;
fName: RawUTF8;
fDescription: RawUTF8;
fComments: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read fDescription write fDescription;
property Comments: RawUTF8 read fComments write fComments;
end;
// 9
TSQLBudgetRevision = class(TSQLRecord)
private
fBudget: TSQLBudgetID;
fRevisionSeq: Integer;
fDateRevised: TDateTime;
published
property Budget: TSQLBudgetID read fBudget write fBudget;
property RevisionSeq: Integer read fRevisionSeq write fRevisionSeq;
property DateRevised: TDateTime read fDateRevised write fDateRevised;
end;
// 10
TSQLBudgetRevisionImpact = class(TSQLRecord)
private
fBudget: TSQLBudgetID;
fBudgetItemSeq: Integer;
fRevisionSeq: Integer;
fRevisedAmount: Currency;
fAddDeleteFlag: TDateTime;
fRevisionReason: RawUTF8;
published
property Budget: TSQLBudgetID read fBudget write fBudget;
property BudgetItemSeq: Integer read fBudgetItemSeq write fBudgetItemSeq;
property RevisionSeq: Integer read fRevisionSeq write fRevisionSeq;
property RevisedAmount: Currency read fRevisedAmount write fRevisedAmount;
property AddDeleteFlag: TDateTime read fAddDeleteFlag write fAddDeleteFlag;
property RevisionReason: RawUTF8 read fRevisionReason write fRevisionReason;
end;
// 11
TSQLBudgetRole = class(TSQLRecord)
private
fBudget: TSQLBudgetID;
fParty: TSQLPartyID;
fRoleTypeId: Integer;
published
property Budget: TSQLBudgetID read fBudget write fBudget;
property Party: TSQLPartyID read fParty write fParty;
property RoleTypeId: Integer read fRoleTypeId write fRoleTypeId;
end;
// 12
TSQLBudgetScenario = class(TSQLRecord)
private
fName: RawUTF8;
fDescription: RawUTF8;
published
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 13
TSQLBudgetScenarioApplication = class(TSQLRecord)
private
fBudgetScenario: TSQLBudgetScenarioID;
fBudget: TSQLBudgetID;
fBudgetItemSeq: Integer;
fAmountChange: Currency;
fPercentageChange: Double;
published
property BudgetScenario: TSQLBudgetScenarioID read fBudgetScenario write fBudgetScenario;
property Budget: TSQLBudgetID read fBudget write fBudget;
property BudgetItemSeq: Integer read fBudgetItemSeq write fBudgetItemSeq;
property AmountChange: Currency read fAmountChange write fAmountChange;
property PercentageChange: Double read fPercentageChange write fPercentageChange;
end;
// 14
TSQLBudgetScenarioRule = class(TSQLRecord)
private
fBudgetScenario: TSQLBudgetScenarioID;
fBudgetItemType: TSQLBudgetItemTypeID;
fAmountChange: Currency;
fPercentageChange: Double;
published
property BudgetScenario: TSQLBudgetScenarioID read fBudgetScenario write fBudgetScenario;
property BudgetItemType: TSQLBudgetItemTypeID read fBudgetItemType write fBudgetItemType;
property AmountChange: Currency read fAmountChange write fAmountChange;
property PercentageChange: Double read fPercentageChange write fPercentageChange;
end;
// 15
TSQLBudgetStatus = class(TSQLRecord)
private
fBudget: TSQLBudgetID;
fStatus: TSQLStatusItemID;
fStatusDate: TDateTime;
fComments: RawUTF8;
fChangeByUserLogin: TSQLUserLoginID;
published
property Budget: TSQLBudgetID read fBudget write fBudget;
property Status: TSQLStatusItemID read fStatus write fStatus;
property StatusDate: TDateTime read fStatusDate write fStatusDate;
property Comments: RawUTF8 read fComments write fComments;
property ChangeByUserLogin: TSQLUserLoginID read fChangeByUserLogin write fChangeByUserLogin;
end;
// 16
TSQLBudgetType = class(TSQLRecord)
private
fEncode: RawUTF8;
fParentEncode: RawUTF8;
fParent: TSQLBudgetTypeID;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property ParentEncode: RawUTF8 read fParentEncode write fParentEncode;
property Parent: TSQLBudgetTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 17
TSQLBudgetTypeAttr = class(TSQLRecord)
private
fBudgetType: TSQLBudgetTypeID;
fAttrName: TSQLBudgetAttributeID;
fDescription: RawUTF8;
published
property BudgetType: TSQLBudgetTypeID read fBudgetType write fBudgetType;
property AttrName: TSQLBudgetAttributeID read fAttrName write fAttrName;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 18
TSQLFinAccount = class(TSQLRecord)
private
fFinAccountType: TSQLFinAccountTypeID;
fStatusId: Integer;
fFinAccountName: RawUTF8;
fFinAccountCode: RawUTF8;
fFinAccountPin: RawUTF8;
fCurrencyUom: TSQLUomID;
fOrganizationParty: TSQLPartyID;
fOwnerParty: TSQLPartyID;
fPostToGlAccount: TSQLGlAccountID;
fFromDate: TDateTime;
fThruDate: TDateTime;
fIsRefundable: Boolean;
fReplenishPayment: TSQLPaymentMethodID;
fReplenishLevel: Currency;
fActualBalance: Currency;
fAvailableBalance: Currency;
published
property FinAccountType: TSQLFinAccountTypeID read fFinAccountType write fFinAccountType;
property StatusId: Integer read fStatusId write fStatusId;
property FinAccountName: RawUTF8 read fFinAccountName write fFinAccountName;
property FinAccountCode: RawUTF8 read fFinAccountCode write fFinAccountCode;
property FinAccountPin: RawUTF8 read fFinAccountPin write fFinAccountPin;
property CurrencyUom: TSQLUomID read fCurrencyUom write fCurrencyUom;
property OrganizationParty: TSQLPartyID read fOrganizationParty write fOrganizationParty;
property OwnerParty: TSQLPartyID read fOwnerParty write fOwnerParty;
property PostToGlAccount: TSQLGlAccountID read fPostToGlAccount write fPostToGlAccount;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
property IsRefundable: Boolean read fIsRefundable write fIsRefundable;
property ReplenishPayment: TSQLPaymentMethodID read fReplenishPayment write fReplenishPayment;
property ReplenishLevel: Currency read fReplenishLevel write fReplenishLevel;
property ActualBalance: Currency read fActualBalance write fActualBalance;
property AvailableBalance: Currency read fAvailableBalance write fAvailableBalance;
end;
// 19
TSQLFinAccountAttribute = class(TSQLRecord)
private
fFinAccount: TSQLFinAccountID;
fAttrName: TSQLCostComponentTypeAttrID;
fAttrValue: RawUTF8;
fAttrDescription: RawUTF8;
published
property FinAccount: TSQLFinAccountID read fFinAccount write fFinAccount;
property AttrName: TSQLCostComponentTypeAttrID read fAttrName write fAttrName;
property AttrValue: RawUTF8 read fAttrValue write fAttrValue;
property AttrDescription: RawUTF8 read fAttrDescription write fAttrDescription;
end;
// 20
TSQLFinAccountAuth = class(TSQLRecord)
private
fFinAccount: TSQLFinAccountID;
fAmount: Currency;
fCurrencyUom: TSQLUomID;
fAuthorizationDate: TDateTime;
fFromDate: TDateTime;
fThruDate: TDateTime;
published
property FinAccount: TSQLFinAccountID read fFinAccount write fFinAccount;
property Amount: Currency read fAmount write fAmount;
property CurrencyUom: TSQLUomID read fCurrencyUom write fCurrencyUom;
property AuthorizationDate: TDateTime read fAuthorizationDate write fAuthorizationDate;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
end;
// 21
TSQLFinAccountRole = class(TSQLRecord)
private
fFinAccount: TSQLFinAccountID;
fParty: TSQLPartyID;
fRoleType: TSQLRoleTypeID;
fFromDate: TDateTime;
fThruDate: TDateTime;
published
property FinAccount: TSQLFinAccountID read fFinAccount write fFinAccount;
property Party: TSQLPartyID read fParty write fParty;
property RoleType: TSQLRoleTypeID read fRoleType write fRoleType;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
end;
// 22
TSQLFinAccountStatus = class(TSQLRecord)
private
fFinAccount: TSQLFinAccountID;
fStatus: TSQLStatusItemID;
fStatusDate: TDateTime;
fStatusEndDate: TDateTime;
fChangeByUserLogin: TSQLUserLoginID;
published
property FinAccount: TSQLFinAccountID read fFinAccount write fFinAccount;
property Status: TSQLStatusItemID read fStatus write fStatus;
property StatusDate: TDateTime read fStatusDate write fStatusDate;
property StatusEndDate: TDateTime read fStatusEndDate write fStatusEndDate;
property ChangeByUserLogin: TSQLUserLoginID read fChangeByUserLogin write fChangeByUserLogin;
end;
// 23
TSQLFinAccountTrans = class(TSQLRecord)
private
fFinAccountTransType: TSQLFinAccountTransTypeID;
fFinAccount: TSQLFinAccountID;
fParty: TSQLPartyID;
fGlReconciliation: TSQLGlReconciliationID;
fTransactionDate: TDateTime;
fEntryDate: TDateTime;
fAmount: Currency;
fPayment: TSQLPaymentID;
fOrderId: Integer;
fOrderItemSeqId: Integer;
fPerformedByParty: TSQLPartyID;
fReasonEnum: TSQLEnumerationID;
fComments: RawUTF8;
fStatus: TSQLStatusItemID;
published
property FinAccountTransType: TSQLFinAccountTransTypeID read fFinAccountTransType write fFinAccountTransType;
property FinAccount: TSQLFinAccountID read fFinAccount write fFinAccount;
property Party: TSQLPartyID read fParty write fParty;
property GlReconciliation: TSQLGlReconciliationID read fGlReconciliation write fGlReconciliation;
property TransactionDate: TDateTime read fTransactionDate write fTransactionDate;
property EntryDate: TDateTime read fEntryDate write fEntryDate;
property Amount: Currency read fAmount write fAmount;
property Payment: TSQLPaymentID read fPayment write fPayment;
property OrderId: Integer read fOrderId write fOrderId;
property OrderItemSeqId: Integer read fOrderItemSeqId write fOrderItemSeqId;
property PerformedByParty: TSQLPartyID read fPerformedByParty write fPerformedByParty;
property ReasonEnum: TSQLEnumerationID read fReasonEnum write fReasonEnum;
property Comments: RawUTF8 read fComments write fComments;
property Status: TSQLStatusItemID read fStatus write fStatus;
end;
// 24
TSQLFinAccountTransAttribute = class(TSQLRecord)
private
fFinAccountTrans: TSQLFinAccountTransID;
fAttrName: TSQLFinAccountTransTypeAttrID;
fAttrValue: RawUTF8;
fAttrDescription: RawUTF8;
published
property FinAccountTrans: TSQLFinAccountTransID read fFinAccountTrans write fFinAccountTrans;
property AttrName: TSQLFinAccountTransTypeAttrID read fAttrName write fAttrName;
property AttrValue: RawUTF8 read fAttrValue write fAttrValue;
property AttrDescription: RawUTF8 read fAttrDescription write fAttrDescription;
end;
// 25
TSQLFinAccountTransType = class(TSQLRecord)
private
fEncode: RawUTF8;
fParentEncode: RawUTF8;
fParent: TSQLFinAccountTransTypeID;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property ParentEncode: RawUTF8 read fParentEncode write fParentEncode;
property Parent: TSQLFinAccountTransTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 26
TSQLFinAccountTransTypeAttr = class(TSQLRecord)
private
fFinAccountTransType: TSQLFinAccountTransTypeID;
fAttrName: TSQLFinAccountTransAttributeID;
fDescription: RawUTF8;
published
property FinAccountTransType: TSQLFinAccountTransTypeID read fFinAccountTransType write fFinAccountTransType;
property AttrName: TSQLFinAccountTransAttributeID read fAttrName write fAttrName;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 27
TSQLFinAccountType = class(TSQLRecord)
private
fEncode: RawUTF8;
fParentEncode: RawUTF8;
fReplenishEnumEncode: RawUTF8;
fParent: TSQLFinAccountTypeID;
fReplenishEnum: TSQLEnumerationID;
fIsRefundable: Boolean;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property ParentEncode: RawUTF8 read fParentEncode write fParentEncode;
property ReplenishEnumEncode: RawUTF8 read fReplenishEnumEncode write fReplenishEnumEncode;
property Parent: TSQLFinAccountTypeID read fParent write fParent;
property ReplenishEnum: TSQLEnumerationID read fReplenishEnum write fReplenishEnum;
property IsRefundable: Boolean read fIsRefundable write fIsRefundable;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 28
TSQLFinAccountTypeAttr = class(TSQLRecord)
private
fFinAccountType: TSQLFinAccountTypeID;
fAttrName: TSQLCostComponentTypeAttrID;
fAttrValue: RawUTF8;
fDescription: RawUTF8;
published
property FinAccountType: TSQLFinAccountTypeID read fFinAccountType write fFinAccountType;
property AttrName: TSQLCostComponentTypeAttrID read fAttrName write fAttrName;
property AttrValue: RawUTF8 read fAttrValue write fAttrValue;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 29
TSQLFinAccountTypeGlAccount = class(TSQLRecord)
private
fFinAccountType: TSQLFinAccountTypeID;
fOrganizationParty: TSQLPartyID;
fGlAccount: TSQLGlAccountID;
published
property FinAccountType: TSQLFinAccountTypeID read fFinAccountType write fFinAccountType;
property OrganizationParty: TSQLPartyID read fOrganizationParty write fOrganizationParty;
property GlAccount: TSQLGlAccountID read fGlAccount write fGlAccount;
end;
// 30
TSQLFixedAsset = class(TSQLRecord)
private
fFixedAssetType: TSQLFixedAssetTypeID;
fParentFixedAsset: TSQLFixedAssetID;
fInstanceOfProduct: TSQLProductID;
fClassEnum: TSQLEnumerationID;
fParty: TSQLPartyID;
fRoleType: TSQLRoleTypeID;
fFixedAssetName: RawUTF8;
fAcquireOrder: TSQLOrderHeaderID;
fAcquireOrderItemSeq: Integer;
fDateAcquired: TDateTime;
fDateLastServiced: TDateTime;
fDateNextService: TDateTime;
fExpectedEndOfLife: TDateTime;
fActualEndOfLife: TDateTime;
fProductionCapacity: Double;
fUom: TSQLUomID;
fCalendar: TSQLTechDataCalendarID;
fSerialNumber: RawUTF8;
fLocatedAtFacility: TSQLFacilityID;
fLocatedAtLocationSeq: Integer;
fSalvageValue: Currency;
fDepreciation: Currency;
fPurchaseCost: Currency;
fPurchaseCostUom: TSQLUomID;
published
property FixedAssetType: TSQLFixedAssetTypeID read fFixedAssetType write fFixedAssetType;
property ParentFixedAsset: TSQLFixedAssetID read fParentFixedAsset write fParentFixedAsset;
property InstanceOfProduct: TSQLProductID read fInstanceOfProduct write fInstanceOfProduct;
property ClassEnum: TSQLEnumerationID read fClassEnum write fClassEnum;
property Party: TSQLPartyID read fParty write fParty;
property RoleType: TSQLRoleTypeID read fRoleType write fRoleType;
property FixedAssetName: RawUTF8 read fFixedAssetName write fFixedAssetName;
property AcquireOrder: TSQLOrderHeaderID read fAcquireOrder write fAcquireOrder;
property AcquireOrderItemSeq: Integer read fAcquireOrderItemSeq write fAcquireOrderItemSeq;
property DateAcquired: TDateTime read fDateAcquired write fDateAcquired;
property DateLastServiced: TDateTime read fDateLastServiced write fDateLastServiced;
property DateNextService: TDateTime read fDateNextService write fDateNextService;
property ExpectedEndOfLife: TDateTime read fExpectedEndOfLife write fExpectedEndOfLife;
property ActualEndOfLife: TDateTime read fActualEndOfLife write fActualEndOfLife;
property ProductionCapacity: Double read fProductionCapacity write fProductionCapacity;
property Uom: TSQLUomID read fUom write fUom;
property Calendar: TSQLTechDataCalendarID read fCalendar write fCalendar;
property SerialNumber: RawUTF8 read fSerialNumber write fSerialNumber;
property LocatedAtFacility: TSQLFacilityID read fLocatedAtFacility write fLocatedAtFacility;
property LocatedAtLocationSeq: Integer read fLocatedAtLocationSeq write fLocatedAtLocationSeq;
property SalvageValue: Currency read fSalvageValue write fSalvageValue;
property Depreciation: Currency read fDepreciation write fDepreciation;
property PurchaseCost: Currency read fPurchaseCost write fPurchaseCost;
property PurchaseCostUom: TSQLUomID read fPurchaseCostUom write fPurchaseCostUom;
end;
// 31
TSQLFixedAssetAttribute = class(TSQLRecord)
private
fFixedAsset: TSQLFixedAssetID;
fAttrName: TSQLFixedAssetTypeAttrID;
fAttrValue: RawUTF8;
fAttrDescription: RawUTF8;
published
property FixedAsset: TSQLFixedAssetID read fFixedAsset write fFixedAsset;
property AttrName: TSQLFixedAssetTypeAttrID read fAttrName write fAttrName;
property AttrValue: RawUTF8 read fAttrValue write fAttrValue;
property AttrDescription: RawUTF8 read fAttrDescription write fAttrDescription;
end;
// 32
TSQLFixedAssetDepMethod = class(TSQLRecord)
private
fDepreciationCustomMethod: TSQLCustomMethodID;
fFixedAsset: TSQLFixedAssetID;
fFromDate: TDateTime;
fThruDate: TDateTime;
published
property DepreciationCustomMethod: TSQLCustomMethodID read fDepreciationCustomMethod write fDepreciationCustomMethod;
property FixedAsset: TSQLFixedAssetID read fFixedAsset write fFixedAsset;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
end;
// 33
TSQLFixedAssetGeoPoint = class(TSQLRecord)
private
fFixedAsset: TSQLFixedAssetID;
fGeoPoint: TSQLGeoPointID;
fFromDate: TDateTime;
fThruDate: TDateTime;
published
property FixedAsset: TSQLFixedAssetID read fFixedAsset write fFixedAsset;
property GeoPoint: TSQLGeoPointID read fGeoPoint write fGeoPoint;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
end;
// 34
TSQLFixedAssetIdent = class(TSQLRecord)
private
fFixedAsset: TSQLFixedAssetID;
fFixedAssetIdentType: TSQLFixedAssetIdentTypeID;
fIdValue: RawUTF8;
published
property FixedAsset: TSQLFixedAssetID read fFixedAsset write fFixedAsset;
property FixedAssetIdentType: TSQLFixedAssetIdentTypeID read fFixedAssetIdentType write fFixedAssetIdentType;
property IdValue: RawUTF8 read fIdValue write fIdValue;
end;
// 35
TSQLFixedAssetIdentType = class(TSQLRecord)
private
fEncode: RawUTF8;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 36
TSQLFixedAssetMaint = class(TSQLRecord)
private
fFixedAsset: TSQLFixedAssetID;
fMaintHistSeq: Integer;
fStatus: TSQLStatusItemID;
fProductMaintType: TSQLProductMaintTypeID;
fProductMaintSeq: Integer;
fScheduleWorkEffort: TSQLWorkEffortID;
fIntervalQuantity: Double;
fIntervalUom: TSQLUomID;
fProductMeterType: TSQLProductMeterTypeID;
fPurchaseOrder: TSQLOrderHeaderID;
published
property FixedAsset: TSQLFixedAssetID read fFixedAsset write fFixedAsset;
property MaintHistSeq: Integer read fMaintHistSeq write fMaintHistSeq;
property Status: TSQLStatusItemID read fStatus write fStatus;
property ProductMaintType: TSQLProductMaintTypeID read fProductMaintType write fProductMaintType;
property ProductMaintSeq: Integer read fProductMaintSeq write fProductMaintSeq;
property ScheduleWorkEffort: TSQLWorkEffortID read fScheduleWorkEffort write fScheduleWorkEffort;
property IntervalQuantity: Double read fIntervalQuantity write fIntervalQuantity;
property IntervalUom: TSQLUomID read fIntervalUom write fIntervalUom;
property ProductMeterType: TSQLProductMeterTypeID read fProductMeterType write fProductMeterType;
property PurchaseOrder: TSQLOrderHeaderID read fPurchaseOrder write fPurchaseOrder;
end;
// 37
TSQLFixedAssetMeter = class(TSQLRecord)
private
fFixedAsset: TSQLFixedAssetID;
fProductMeterType: TSQLProductMeterTypeID;
fReadingDate: TDateTime;
fMeterValue: Double;
fReadingReasonEnum: Integer;
fMaintHistSeq: Integer;
fWorkEffort: Integer;
published
property FixedAsset: TSQLFixedAssetID read fFixedAsset write fFixedAsset;
property ProductMeterType: TSQLProductMeterTypeID read fProductMeterType write fProductMeterType;
property ReadingDate: TDateTime read fReadingDate write fReadingDate;
property MeterValue: Double read fMeterValue write fMeterValue;
property ReadingReasonEnum: Integer read fReadingReasonEnum write fReadingReasonEnum;
property MaintHistSeq: Integer read fMaintHistSeq write fMaintHistSeq;
property WorkEffort: Integer read fWorkEffort write fWorkEffort;
end;
// 38
TSQLFixedAssetProduct = class(TSQLRecord)
private
fFixedAsset: TSQLFixedAssetID;
fProduct: TSQLProductID;
fFixedAssetProductType: TSQLFixedAssetProductTypeID;
fFromDate: TDateTime;
fThruDate: TDateTime;
fSequenceNum: Integer;
fQuantity: Double;
fQuantityUom: TSQLUomID;
published
property FixedAsset: TSQLFixedAssetID read fFixedAsset write fFixedAsset;
property Product: TSQLProductID read fProduct write fProduct;
property FixedAssetProductType: TSQLFixedAssetProductTypeID read fFixedAssetProductType write fFixedAssetProductType;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
property SequenceNum: Integer read fSequenceNum write fSequenceNum;
property Quantity: Double read fQuantity write fQuantity;
property QuantityUom: TSQLUomID read fQuantityUom write fQuantityUom;
end;
// 39
TSQLFixedAssetProductType = class(TSQLRecord)
private
fEncode: RawUTF8;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 40
TSQLFixedAssetTypeGlAccount = class(TSQLRecord)
private
fFixedAssetType: TSQLFixedAssetTypeID;
fFixedAsset: TSQLFixedAssetID;
fOrganizationParty: TSQLPartyID;
fAssetGlAccount: TSQLGlAccountID;
fAccDepGlAccount: TSQLGlAccountID;
fDepGlAccount: TSQLGlAccountID;
fProfitGlAccount: TSQLGlAccountID;
fLossGlAccount: TSQLGlAccountID;
published
property FixedAssetType: TSQLFixedAssetTypeID read fFixedAssetType write fFixedAssetType;
property FixedAsset: TSQLFixedAssetID read fFixedAsset write fFixedAsset;
property OrganizationParty: TSQLPartyID read fOrganizationParty write fOrganizationParty;
property AssetGlAccount: TSQLGlAccountID read fAssetGlAccount write fAssetGlAccount;
property AccDepGlAccount: TSQLGlAccountID read fAccDepGlAccount write fAccDepGlAccount;
property DepGlAccount: TSQLGlAccountID read fDepGlAccount write fDepGlAccount;
property ProfitGlAccount: TSQLGlAccountID read fProfitGlAccount write fProfitGlAccount;
property LossGlAccount: TSQLGlAccountID read fLossGlAccount write fLossGlAccount;
end;
// 41
TSQLFixedAssetRegistration = class(TSQLRecord)
private
fFixedAsset: TSQLFixedAssetID;
fFromDate: TDateTime;
fThruDate: TDateTime;
fRegistrationDate: TDateTime;
fGovAgencyParty: TSQLPartyID;
fRegistrationNumber: RawUTF8;
fLicenseNumber: RawUTF8;
published
property FixedAsset: TSQLFixedAssetID read fFixedAsset write fFixedAsset;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
property RegistrationDate: TDateTime read fRegistrationDate write fRegistrationDate;
property GovAgencyParty: TSQLPartyID read fGovAgencyParty write fGovAgencyParty;
property RegistrationNumber: RawUTF8 read fRegistrationNumber write fRegistrationNumber;
property LicenseNumber: RawUTF8 read fLicenseNumber write fLicenseNumber;
end;
// 42
TSQLFixedAssetStdCost = class(TSQLRecord)
private
fFixedAsset: TSQLFixedAssetID;
fFixedAssetStdCostType: TSQLFixedAssetStdCostTypeID;
fFromDate: TDateTime;
fThruDate: TDateTime;
fAmountUom: TSQLUomID;
fAmount: Currency;
published
property FixedAsset: TSQLFixedAssetID read fFixedAsset write fFixedAsset;
property FixedAssetStdCostType: TSQLFixedAssetStdCostTypeID read fFixedAssetStdCostType write fFixedAssetStdCostType;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
property AmountUom: TSQLUomID read fAmountUom write fAmountUom;
property Amount: Currency read fAmount write fAmount;
end;
// 43
TSQLFixedAssetStdCostType = class(TSQLRecord)
private
fEncode: RawUTF8;
fParentEncode: RawUTF8;
fParent: TSQLFixedAssetStdCostTypeID;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property ParentEncode: RawUTF8 read fParentEncode write fParentEncode;
property Parent: TSQLFixedAssetStdCostTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 44
TSQLFixedAssetType = class(TSQLRecord)
private
fEncode: RawUTF8;
fParentEncode: RawUTF8;
fParent: TSQLFixedAssetTypeID;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property ParentEncode: RawUTF8 read fParentEncode write fParentEncode;
property Parent: TSQLFixedAssetTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 45
TSQLFixedAssetTypeAttr = class(TSQLRecord)
private
fFixedAssetType: TSQLFixedAssetTypeID;
fAttrName: TSQLCostComponentAttributeID;
fDescription: RawUTF8;
published
property FixedAssetType: TSQLFixedAssetTypeID read fFixedAssetType write fFixedAssetType;
property AttrName: TSQLCostComponentAttributeID read fAttrName write fAttrName;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 46
TSQLPartyFixedAssetAssignment = class(TSQLRecord)
private
fParty: TSQLPartyID;
fRoleType: TSQLRoleTypeID;
fFixedAsset: TSQLFixedAssetID;
fFromDate: TDateTime;
fThruDate: TDateTime;
fAllocatedDate: TDateTime;
fStatus: TSQLStatusItemID;
fComments: RawUTF8;
published
property Party: TSQLPartyID read fParty write fParty;
property RoleType: TSQLRoleTypeID read fRoleType write fRoleType;
property FixedAsset: TSQLFixedAssetID read fFixedAsset write fFixedAsset;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
property AllocatedDate: TDateTime read fAllocatedDate write fAllocatedDate;
property Status: TSQLStatusItemID read fStatus write fStatus;
property Comments: RawUTF8 read fComments write fComments;
end;
// 47
TSQLFixedAssetMaintOrder = class(TSQLRecord)
private
fFixedAsset: TSQLFixedAssetID;
fMaintHistSeq: Integer;
fOrderId: TSQLOrderHeaderID;
fOrderItemSeq: Integer;
published
property FixedAsset: TSQLFixedAssetID read fFixedAsset write fFixedAsset;
property MaintHistSeq: Integer read fMaintHistSeq write fMaintHistSeq;
property OrderId: TSQLOrderHeaderID read fOrderId write fOrderId;
property OrderItemSeq: Integer read fOrderItemSeq write fOrderItemSeq;
end;
// 48
TSQLAccommodationClass = class(TSQLRecord)
private
fParent: TSQLAccommodationClassID;
fName: RawUTF8;
FDescription: RawUTF8;
published
property Parent: TSQLAccommodationClassID read fParent write fParent;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 49
TSQLAccommodationSpot = class(TSQLRecord)
private
fAccommodationClass: TSQLAccommodationClassID;
fFixedAsset: TSQLFixedAssetID;
fNumberOfSpaces: Integer;
FDescription: RawUTF8;
published
property AccommodationClass: TSQLAccommodationClassID read fAccommodationClass write fAccommodationClass;
property FixedAsset: TSQLFixedAssetID read fFixedAsset write fFixedAsset;
property NumberOfSpaces: Integer read fNumberOfSpaces write fNumberOfSpaces;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 50
TSQLAccommodationMap = class(TSQLRecord)
private
fAccommodationClass: TSQLAccommodationClassID;
fFixedAsset: TSQLFixedAssetID;
fAccommodationMapType: TSQLAccommodationMapTypeID;
fNumberOfSpaces: Integer;
published
property AccommodationClass: TSQLAccommodationClassID read fAccommodationClass write fAccommodationClass;
property FixedAsset: TSQLFixedAssetID read fFixedAsset write fFixedAsset;
property AccommodationMapType: TSQLAccommodationMapTypeID read fAccommodationMapType write fAccommodationMapType;
property NumberOfSpaces: Integer read fNumberOfSpaces write fNumberOfSpaces;
end;
// 51
TSQLAccommodationMapType = class(TSQLRecord)
private
fName: RawUTF8;
FDescription: RawUTF8;
published
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 52
TSQLInvoice = class(TSQLRecord)
private
fInvoiceType: TSQLInvoiceTypeID;
fPartyIdFrom: TSQLPartyID;
fParty: TSQLPartyID;
fRoleType: TSQLRoleTypeID;
fStatus: TSQLStatusItemID;
fBillingAccount: TSQLBillingAccountID;
fContactMech: TSQLContactMechID;
fInvoiceDate: TDateTime;
fDueDate: TDateTime;
fPaidDate: TDateTime;
fInvoiceMessage: RawUTF8;
fReferenceNumber: RawUTF8;
fDescription: RawUTF8;
fCurrencyUom: TSQLUomID;
fRecurrenceInfo: TSQLRecurrenceInfoID;
published
property InvoiceType: TSQLInvoiceTypeID read fInvoiceType write fInvoiceType;
property PartyIdFrom: TSQLPartyID read fPartyIdFrom write fPartyIdFrom;
property Party: TSQLPartyID read fParty write fParty;
property RoleType: TSQLRoleTypeID read fRoleType write fRoleType;
property Status: TSQLStatusItemID read fStatus write fStatus;
property BillingAccount: TSQLBillingAccountID read fBillingAccount write fBillingAccount;
property ContactMech: TSQLContactMechID read fContactMech write fContactMech;
property InvoiceDate: TDateTime read fInvoiceDate write fInvoiceDate;
property DueDate: TDateTime read fDueDate write fDueDate;
property PaidDate: TDateTime read fPaidDate write fPaidDate;
property InvoiceMessage: RawUTF8 read fInvoiceMessage write fInvoiceMessage;
property ReferenceNumber: RawUTF8 read fReferenceNumber write fReferenceNumber;
property Description: RawUTF8 read fDescription write fDescription;
property CurrencyUom: TSQLUomID read fCurrencyUom write fCurrencyUom;
property RecurrenceInfo: TSQLRecurrenceInfoID read fRecurrenceInfo write fRecurrenceInfo;
end;
// 53
TSQLInvoiceAttribute = class(TSQLRecord)
private
fInvoice: TSQLInvoiceID;
fAttrName: TSQLCostComponentTypeAttrID;
fAttrValue: RawUTF8;
fAttrDescription: RawUTF8;
published
property Invoice: TSQLInvoiceID read fInvoice write fInvoice;
property AttrName: TSQLCostComponentTypeAttrID read fAttrName write fAttrName;
property AttrValue: RawUTF8 read fAttrValue write fAttrValue;
property AttrDescription: RawUTF8 read fAttrDescription write fAttrDescription;
end;
// 54
TSQLInvoiceContent = class(TSQLRecord)
private
fInvoice: TSQLInvoiceID;
fInvoiceContentType: TSQLInvoiceContentTypeID;
fContent: TSQLContentID;
fFromDate: TDateTime;
fThruDate: TDateTime;
published
property Invoice: TSQLInvoiceID read fInvoice write fInvoice;
property InvoiceContentType: TSQLInvoiceContentTypeID read fInvoiceContentType write fInvoiceContentType;
property Content: TSQLContentID read fContent write fContent;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
end;
// 55
TSQLInvoiceContentType = class(TSQLRecord)
private
fEncode: RawUTF8;
fParentEncode: RawUTF8;
fParent: TSQLInvoiceContentTypeID;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property ParentEncode: RawUTF8 read fParentEncode write fParentEncode;
property Parent: TSQLInvoiceContentTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 56
TSQLInvoiceContactMech = class(TSQLRecord)
private
fInvoice: TSQLInvoiceID;
fContactMechPurposeType: TSQLContactMechPurposeTypeID;
fContactMech: TSQLContactMechID;
published
property Invoice: TSQLInvoiceID read fInvoice write fInvoice;
property ContactMechPurposeType: TSQLContactMechPurposeTypeID read fContactMechPurposeType write fContactMechPurposeType;
property ContactMech: TSQLContactMechID read fContactMech write fContactMech;
end;
// 57
TSQLInvoiceItem = class(TSQLRecord)
private
fInvoice: TSQLInvoiceID;
fInvoiceItemSeq: Integer;
fInvoiceItemType: TSQLInvoiceItemTypeID;
fOverrideGlAccount: TSQLGlAccountID;
fOverrideOrgParty: TSQLPartyID;
fInventoryItem: TSQLInventoryItemID;
fProduct: TSQLProductID;
fProductFeature: TSQLProductFeatureID;
fParentInvoice: TSQLInvoiceItemID;
fParentInvoiceItemSeq: Integer;
fUom: TSQLUomID;
fTaxableFlag: Boolean;
fQuantity: Double;
fAmount: Currency;
fDescription: RawUTF8;
fTaxAuthParty: TSQLPartyID;
fTaxAuthGeo: TSQLGeoID;
fTaxAuthorityRateSeq: TSQLTaxAuthorityRateProductID;
fSalesOpportunity: TSQLSalesOpportunityID;
published
property Invoice: TSQLInvoiceID read fInvoice write fInvoice;
property InvoiceItemSeq: Integer read fInvoiceItemSeq write fInvoiceItemSeq;
property InvoiceItemType: TSQLInvoiceItemTypeID read fInvoiceItemType write fInvoiceItemType;
property OverrideGlAccount: TSQLGlAccountID read fOverrideGlAccount write fOverrideGlAccount;
property OverrideOrgParty: TSQLPartyID read fOverrideOrgParty write fOverrideOrgParty;
property InventoryItem: TSQLInventoryItemID read fInventoryItem write fInventoryItem;
property Product: TSQLProductID read fProduct write fProduct;
property ProductFeature: TSQLProductFeatureID read fProductFeature write fProductFeature;
property ParentInvoice: TSQLInvoiceItemID read fParentInvoice write fParentInvoice;
property ParentInvoiceItemSeq: Integer read fParentInvoiceItemSeq write fParentInvoiceItemSeq;
property Uom: TSQLUomID read fUom write fUom;
property TaxableFlag: Boolean read fTaxableFlag write fTaxableFlag;
property Quantity: Double read fQuantity write fQuantity;
property Amount: Currency read fAmount write fAmount;
property Description: RawUTF8 read fDescription write fDescription;
property TaxAuthParty: TSQLPartyID read fTaxAuthParty write fTaxAuthParty;
property TaxAuthGeo: TSQLGeoID read fTaxAuthGeo write fTaxAuthGeo;
property TaxAuthorityRateSeq: TSQLTaxAuthorityRateProductID read fTaxAuthorityRateSeq write fTaxAuthorityRateSeq;
property SalesOpportunity: TSQLSalesOpportunityID read fSalesOpportunity write fSalesOpportunity;
end;
// 58
TSQLInvoiceItemAssoc = class(TSQLRecord)
private
fInvoiceFrom: TSQLInvoiceItemID;
fInvoiceItemSeqFrom: Integer;
fInvoiceTo: TSQLInvoiceItemID;
fInvoiceItemSeqTo: Integer;
fInvoiceItemAssocType: TSQLInvoiceItemAssocTypeID;
fFromDate: TDateTime;
fThruDate: TDateTime;
fPartyFrom: TSQLPartyID;
fPartyTo: TSQLPartyID;
fQuantity: Double;
fAmount: Currency;
published
property InvoiceFrom: TSQLInvoiceItemID read fInvoiceFrom write fInvoiceFrom;
property InvoiceItemSeqFrom: Integer read fInvoiceItemSeqFrom write fInvoiceItemSeqFrom;
property InvoiceTo: TSQLInvoiceItemID read fInvoiceTo write fInvoiceTo;
property InvoiceItemSeqTo: Integer read fInvoiceItemSeqTo write fInvoiceItemSeqTo;
property InvoiceItemAssocType: TSQLInvoiceItemAssocTypeID read fInvoiceItemAssocType write fInvoiceItemAssocType;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
property PartyFrom: TSQLPartyID read fPartyFrom write fPartyFrom;
property PartyTo: TSQLPartyID read fPartyTo write fPartyTo;
property Quantity: Double read fQuantity write fQuantity;
property Amount: Currency read fAmount write fAmount;
end;
// 59
TSQLInvoiceItemAssocType = class(TSQLRecord)
private
fEncode: RawUTF8;
fParentEncode: RawUTF8;
fParent: TSQLInvoiceItemAssocTypeID;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property ParentEncode: RawUTF8 read fParentEncode write fParentEncode;
property Parent: TSQLInvoiceItemAssocTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 60
TSQLInvoiceItemAttribute = class(TSQLRecord)
private
fInvoice: TSQLInvoiceItemID;
fInvoiceItemSeq: Integer;
fAttrName: TSQLCostComponentTypeAttrID;
fAttrValue: RawUTF8;
fAttrDescription: RawUTF8;
published
property Invoice: TSQLInvoiceItemID read fInvoice write fInvoice;
property InvoiceItemSeq: Integer read fInvoiceItemSeq write fInvoiceItemSeq;
property AttrName: TSQLCostComponentTypeAttrID read fAttrName write fAttrName;
property AttrValue: RawUTF8 read fAttrValue write fAttrValue;
property AttrDescription: RawUTF8 read fAttrDescription write fAttrDescription;
end;
// 61
TSQLInvoiceItemType = class(TSQLRecord)
private
fEncode: RawUTF8;
fParentEncode: RawUTF8;
fDefaultGlAccountEncode: RawUTF8;
fInvoiceItemType: TSQLInvoiceItemTypeID;
fParent: TSQLInvoiceItemTypeID;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
fDefaultGlAccount: TSQLGlAccountID;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property ParentEncode: RawUTF8 read fParentEncode write fParentEncode;
property DefaultGlAccountEncode: RawUTF8 read fDefaultGlAccountEncode write fDefaultGlAccountEncode;
property InvoiceItemType: TSQLInvoiceItemTypeID read fInvoiceItemType write fInvoiceItemType;
property Parent: TSQLInvoiceItemTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
property DefaultGlAccount: TSQLGlAccountID read fDefaultGlAccount write fDefaultGlAccount;
end;
// 62
TSQLInvoiceItemTypeAttr = class(TSQLRecord)
private
fInvoiceItemType: TSQLInvoiceItemTypeID;
fAttrName: TSQLCostComponentTypeAttrID;
fDescription: RawUTF8;
published
property InvoiceItemType: TSQLInvoiceItemTypeID read fInvoiceItemType write fInvoiceItemType;
property AttrName: TSQLCostComponentTypeAttrID read fAttrName write fAttrName;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 63
TSQLInvoiceItemTypeGlAccount = class(TSQLRecord)
private
fInvoiceItemType: TSQLInvoiceItemTypeID;
fOrganizationParty: TSQLPartyID;
fGlAccount: TSQLGlAccountID;
published
property InvoiceItemType: TSQLInvoiceItemTypeID read fInvoiceItemType write fInvoiceItemType;
property OrganizationParty: TSQLPartyID read fOrganizationParty write fOrganizationParty;
property GlAccount: TSQLGlAccountID read fGlAccount write fGlAccount;
end;
// 64
TSQLInvoiceItemTypeMap = class(TSQLRecord)
private
fInvoiceTypeEncode: RawUTF8;
fInvoiceItemMapKey: RawUTF8;
fInvoiceItemTypeEncode: RawUTF8;
fInvoiceType: TSQLInvoiceTypeID;
fInvoiceItemType: TSQLInvoiceItemTypeID;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property InvoiceTypeEncode: RawUTF8 read fInvoiceTypeEncode write fInvoiceTypeEncode;
property InvoiceItemMapKey: RawUTF8 read fInvoiceItemMapKey write fInvoiceItemMapKey;
property InvoiceItemTypeEncode: RawUTF8 read fInvoiceItemTypeEncode write fInvoiceItemTypeEncode;
property InvoiceType: TSQLInvoiceTypeID read fInvoiceType write fInvoiceType;
property InvoiceItemType: TSQLInvoiceItemTypeID read fInvoiceItemType write fInvoiceItemType;
end;
// 65
TSQLInvoiceRole = class(TSQLRecord)
private
fInvoice: TSQLInvoiceID;
fParty: TSQLPartyID;
fRoleType: TSQLRoleTypeID;
fDatetimePerformed: TDateTime;
fPercentage: Double;
published
property Invoice: TSQLInvoiceID read fInvoice write fInvoice;
property Party: TSQLPartyID read fParty write fParty;
property RoleType: TSQLRoleTypeID read fRoleType write fRoleType;
property DatetimePerformed: TDateTime read fDatetimePerformed write fDatetimePerformed;
property Percentage: Double read fPercentage write fPercentage;
end;
// 66
TSQLInvoiceStatus = class(TSQLRecord)
private
fStatus: TSQLStatusItemID;
fInvoice: TSQLInvoiceID;
fStatusDate: TDateTime;
fChangeByUserLogin: TSQLUserLoginID;
published
property Status: TSQLStatusItemID read fStatus write fStatus;
property Invoice: TSQLInvoiceID read fInvoice write fInvoice;
property StatusDate: TDateTime read fStatusDate write fStatusDate;
property ChangeByUserLogin: TSQLUserLoginID read fChangeByUserLogin write fChangeByUserLogin;
end;
// 67
TSQLInvoiceTerm = class(TSQLRecord)
private
fTermType: TSQLTermTypeID;
fInvoice: TSQLInvoiceID;
fInvoiceItemSeq: Integer;
fTermValue: Currency;
fTermDays: Integer;
fTextValue: RawUTF8;
fDescription: RawUTF8;
fUom: TSQLUomID;
published
property TermType: TSQLTermTypeID read fTermType write fTermType;
property Invoice: TSQLInvoiceID read fInvoice write fInvoice;
property InvoiceItemSeq: Integer read fInvoiceItemSeq write fInvoiceItemSeq;
property TermValue: Currency read fTermValue write fTermValue;
property TermDays: Integer read fTermDays write fTermDays;
property TextValue: RawUTF8 read fTextValue write fTextValue;
property Description: RawUTF8 read fDescription write fDescription;
property Uom: TSQLUomID read fUom write fUom;
end;
// 68
TSQLInvoiceTermAttribute = class(TSQLRecord)
private
fInvoiceTerm: TSQLInvoiceTermID;
fAttrName: TSQLCostComponentTypeAttrID;
fAttrValue: RawUTF8;
fAttrDescription: RawUTF8;
published
property InvoiceTerm: TSQLInvoiceTermID read fInvoiceTerm write fInvoiceTerm;
property AttrName: TSQLCostComponentTypeAttrID read fAttrName write fAttrName;
property AttrValue: RawUTF8 read fAttrValue write fAttrValue;
property AttrDescription: RawUTF8 read fAttrDescription write fAttrDescription;
end;
// 69
TSQLInvoiceType = class(TSQLRecord)
private
fEncode: RawUTF8;
fParentEncode: RawUTF8;
fParent: TSQLInvoiceTypeID;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property ParentEncode: RawUTF8 read fParentEncode write fParentEncode;
property Parent: TSQLInvoiceTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 70
TSQLInvoiceTypeAttr = class(TSQLRecord)
private
fInvoiceType: TSQLInvoiceTypeID;
fAttrName: TSQLCostComponentTypeAttrID;
fDescription: RawUTF8;
published
property InvoiceType: TSQLInvoiceTypeID read fInvoiceType write fInvoiceType;
property AttrName: TSQLCostComponentTypeAttrID read fAttrName write fAttrName;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 71
TSQLInvoiceNote = class(TSQLRecord)
private
fInvoice: TSQLInvoiceID;
fNote: TSQLNoteDataID;
published
property Invoice: TSQLInvoiceID read fInvoice write fInvoice;
property Note: TSQLNoteDataID read fNote write fNote;
end;
// 72
TSQLAcctgTrans = class(TSQLRecord)
private
fAcctgTransType: TSQLAcctgTransTypeID;
fDescription: RawUTF8;
fTransactionDate: TDateTime;
fIsPosted: Boolean;
fPostedDate: TDateTime;
fScheduledPostingDate: TDateTime;
fGlJournal: TSQLGlJournalID;
fGlFiscalType: TSQLGlFiscalTypeID;
fVoucherRef: RawUTF8;
fVoucherDate: TDateTime;
fGroupStatus: TSQLStatusItemID;
fFixedAsset: TSQLFixedAssetID;
fInventoryItem: TSQLInventoryItemID;
fPhysicalInventory: TSQLPhysicalInventoryID;
fParty: TSQLPartyID;
fRoleType: TSQLRoleTypeID;
fInvoice: TSQLInvoiceID;
fPayment: TSQLPaymentID;
fFinAccountTrans: TSQLFinAccountTransID;
fShipment: TSQLShipmentID;
fReceipt: TSQLShipmentReceiptID;
fWorkEffort: TSQLWorkEffortID;
fTheirAcctgTrans: Integer;
fCreatedDate: TDateTime;
fCreatedByUserLogin: TSQLUserLoginID;
fLastModifiedDate: TDateTime;
fLastModifiedByUserLogin: TSQLUserLoginID;
published
property AcctgTransType: TSQLAcctgTransTypeID read fAcctgTransType write fAcctgTransType;
property Description: RawUTF8 read fDescription write fDescription;
property TransactionDate: TDateTime read fTransactionDate write fTransactionDate;
property IsPosted: Boolean read fIsPosted write fIsPosted;
property PostedDate: TDateTime read fPostedDate write fPostedDate;
property ScheduledPostingDate: TDateTime read fScheduledPostingDate write fScheduledPostingDate;
property GlJournal: TSQLGlJournalID read fGlJournal write fGlJournal;
property GlFiscalType: TSQLGlFiscalTypeID read fGlFiscalType write fGlFiscalType;
property VoucherRef: RawUTF8 read fVoucherRef write fVoucherRef;
property VoucherDate: TDateTime read fVoucherDate write fVoucherDate;
property GroupStatus: TSQLStatusItemID read fGroupStatus write fGroupStatus;
property FixedAsset: TSQLFixedAssetID read fFixedAsset write fFixedAsset;
property InventoryItem: TSQLInventoryItemID read fInventoryItem write fInventoryItem;
property PhysicalInventory: TSQLPhysicalInventoryID read fPhysicalInventory write fPhysicalInventory;
property Party: TSQLPartyID read fParty write fParty;
property RoleType: TSQLRoleTypeID read fRoleType write fRoleType;
property Invoice: TSQLInvoiceID read fInvoice write fInvoice;
property Payment: TSQLPaymentID read fPayment write fPayment;
property FinAccountTrans: TSQLFinAccountTransID read fFinAccountTrans write fFinAccountTrans;
property Shipment: TSQLShipmentID read fShipment write fShipment;
property Receipt: TSQLShipmentReceiptID read fReceipt write fReceipt;
property WorkEffort: TSQLWorkEffortID read fWorkEffort write fWorkEffort;
property TheirAcctgTrans: Integer read fTheirAcctgTrans write fTheirAcctgTrans;
property CreatedDate: TDateTime read fCreatedDate write fCreatedDate;
property CreatedByUserLogin: TSQLUserLoginID read fCreatedByUserLogin write fCreatedByUserLogin;
property LastModifiedDate: TDateTime read fLastModifiedDate write fLastModifiedDate;
property LastModifiedByUserLogin: TSQLUserLoginID read fLastModifiedByUserLogin write fLastModifiedByUserLogin;
end;
// 73
TSQLAcctgTransAttribute = class(TSQLRecord)
private
fAcctgTrans: TSQLAcctgTransID;
fAttrName: TSQLInventoryItemTypeAttrID;
fAttrValue: RawUTF8;
fAttrDescription: RawUTF8;
published
property AcctgTrans: TSQLAcctgTransID read fAcctgTrans write fAcctgTrans;
property AttrName: TSQLInventoryItemTypeAttrID read fAttrName write fAttrName;
property AttrValue: RawUTF8 read fAttrValue write fAttrValue;
property AttrDescription: RawUTF8 read fAttrDescription write fAttrDescription;
end;
// 74
TSQLAcctgTransEntry = class(TSQLRecord)
private
fAcctgTrans: TSQLAcctgTransID;
fAcctgTransEntrySeq: Integer;
fAcctgTransEntryType: TSQLAcctgTransEntryTypeID;
fDescription: RawUTF8;
fVoucherRef: RawUTF8;
fParty: TSQLPartyID;
fRoleType: TSQLRoleTypeID;
fTheirParty: TSQLPartyID;
fProduct: TSQLProductID;
fTheirProduct: TSQLProductID;
fInventoryItem: TSQLInventoryItemID;
fGlAccountType: TSQLGlAccountTypeID;
fGlAccount: TSQLGlAccountID;
fOrganizationParty: TSQLPartyID;
fAmount: Currency;
fCurrencyUom: TSQLUomID;
fOrigAmount: Currency;
fOrigCurrencyUom: TSQLUomID;
fDebitCreditFlag: Boolean;
fDueDate: TDateTime;
fGroupId: Integer;
fTax: Integer;
fReconcileStatus: TSQLStatusItemID;
fSettlementTerm: TSQLSettlementTermID;
fIsSummary: Boolean;
published
property AcctgTrans: TSQLAcctgTransID read fAcctgTrans write fAcctgTrans;
property AcctgTransEntrySeq: Integer read fAcctgTransEntrySeq write fAcctgTransEntrySeq;
property AcctgTransEntryType: TSQLAcctgTransEntryTypeID read fAcctgTransEntryType write fAcctgTransEntryType;
property Description: RawUTF8 read fDescription write fDescription;
property VoucherRef: RawUTF8 read fVoucherRef write fVoucherRef;
property Party: TSQLPartyID read fParty write fParty;
property RoleType: TSQLRoleTypeID read fRoleType write fRoleType;
property TheirParty: TSQLPartyID read fTheirParty write fTheirParty;
property Product: TSQLProductID read fProduct write fProduct;
property TheirProduct: TSQLProductID read fTheirProduct write fTheirProduct;
property InventoryItem: TSQLInventoryItemID read fInventoryItem write fInventoryItem;
property GlAccountType: TSQLGlAccountTypeID read fGlAccountType write fGlAccountType;
property GlAccount: TSQLGlAccountID read fGlAccount write fGlAccount;
property OrganizationParty: TSQLPartyID read fOrganizationParty write fOrganizationParty;
property Amount: Currency read fAmount write fAmount;
property CurrencyUom: TSQLUomID read fCurrencyUom write fCurrencyUom;
property OrigAmount: Currency read fOrigAmount write fOrigAmount;
property OrigCurrencyUom: TSQLUomID read fOrigCurrencyUom write fOrigCurrencyUom;
property DebitCreditFlag: Boolean read fDebitCreditFlag write fDebitCreditFlag;
property DueDate: TDateTime read fDueDate write fDueDate;
property GroupId: Integer read fGroupId write fGroupId;
property Tax: Integer read fTax write fTax;
property ReconcileStatus: TSQLStatusItemID read fReconcileStatus write fReconcileStatus;
property SettlementTerm: TSQLSettlementTermID read fSettlementTerm write fSettlementTerm;
property IsSummary: Boolean read fIsSummary write fIsSummary;
end;
// 75
TSQLAcctgTransEntryType = class(TSQLRecord)
private
fEncode: RawUTF8;
fParentEncode: RawUTF8;
fParent: TSQLAcctgTransEntryTypeID;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property ParentEncode: RawUTF8 read fParentEncode write fParentEncode;
property Parent: TSQLAcctgTransEntryTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 76
TSQLAcctgTransType = class(TSQLRecord)
private
fEncode: RawUTF8;
fParentEncode: RawUTF8;
fParent: TSQLAcctgTransTypeID;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property ParentEncode: RawUTF8 read fParentEncode write fParentEncode;
property Parent: TSQLAcctgTransTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 77
TSQLAcctgTransTypeAttr = class(TSQLRecord)
private
fAcctgTransType: TSQLAcctgTransTypeID;
fAttrName: TSQLAcctgTransAttributeID;
FDescription: RawUTF8;
published
property AcctgTransType: TSQLAcctgTransTypeID read fAcctgTransType write fAcctgTransType;
property AttrName: TSQLAcctgTransAttributeID read fAttrName write fAttrName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 78
TSQLGlAccount = class(TSQLRecord)
private
fGlAccountType: TSQLGlAccountTypeID;
fGlAccountClass: TSQLGlAccountClassID;
fGlResourceType: TSQLGlResourceTypeID;
fGlXbrlClass: TSQLGlXbrlClassID;
fParentGlAccount: TSQLGlAccountID;
fAccountCode: RawUTF8;
fAccountName: RawUTF8;
fDescription: RawUTF8;
fProduct: TSQLProductID;
fExternalId: Integer;
published
property GlAccountType: TSQLGlAccountTypeID read fGlAccountType write fGlAccountType;
property GlAccountClass: TSQLGlAccountClassID read fGlAccountClass write fGlAccountClass;
property GlResourceType: TSQLGlResourceTypeID read fGlResourceType write fGlResourceType;
property GlXbrlClass: TSQLGlXbrlClassID read fGlXbrlClass write fGlXbrlClass;
property ParentGlAccount: TSQLGlAccountID read fParentGlAccount write fParentGlAccount;
property AccountCode: RawUTF8 read fAccountCode write fAccountCode;
property AccountName: RawUTF8 read fAccountName write fAccountName;
property Description: RawUTF8 read fDescription write fDescription;
property Product: TSQLProductID read fProduct write fProduct;
property ExternalId: Integer read fExternalId write fExternalId;
end;
// 79
TSQLGlAccountClass = class(TSQLRecord)
private
fEncode: RawUTF8;
fParentEncode: RawUTF8;
fParent: TSQLGlAccountClassID;
fName: RawUTF8;
fDescription: RawUTF8;
fIsAssetClass: Boolean;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property ParentEncode: RawUTF8 read fParentEncode write fParentEncode;
property Parent: TSQLGlAccountClassID read fParent write fParent;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read fDescription write fDescription;
property IsAssetClass: Boolean read fIsAssetClass write fIsAssetClass;
end;
// 80
TSQLGlAccountGroup = class(TSQLRecord)
private
fEncode: RawUTF8;
fGlAccountGroupTypeEncode: RawUTF8;
fGlAccountGroupType: TSQLGlAccountGroupTypeID;
fDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property GlAccountGroupTypeEncode: RawUTF8 read fGlAccountGroupTypeEncode write fGlAccountGroupTypeEncode;
property GlAccountGroupType: TSQLGlAccountGroupTypeID read fGlAccountGroupType write fGlAccountGroupType;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 81
TSQLGlAccountGroupMember = class(TSQLRecord)
private
fGlAccount: TSQLGlAccountID;
fGlAccountGroupType: TSQLGlAccountGroupTypeID;
fGlAccountGroup: TSQLGlAccountGroupID;
published
property GlAccount: TSQLGlAccountID read fGlAccount write fGlAccount;
property GlAccountGroupType: TSQLGlAccountGroupTypeID read fGlAccountGroupType write fGlAccountGroupType;
property GlAccountGroup: TSQLGlAccountGroupID read fGlAccountGroup write fGlAccountGroup;
end;
// 82
TSQLGlAccountGroupType = class(TSQLRecord)
private
fEncode: RawUTF8;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 83
TSQLGlAccountHistory = class(TSQLRecord)
private
fGlAccount: TSQLGlAccountID;
fOrganizationParty: TSQLPartyID;
fCustomTimePeriod: TSQLCustomTimePeriodID;
fOpeningBalance: Currency;
fPostedDebits: Currency;
fPostedCredits: Currency;
fEndingBalance: Currency;
published
property GlAccount: TSQLGlAccountID read fGlAccount write fGlAccount;
property OrganizationParty: TSQLPartyID read fOrganizationParty write fOrganizationParty;
property CustomTimePeriod: TSQLCustomTimePeriodID read fCustomTimePeriod write fCustomTimePeriod;
property OpeningBalance: Currency read fOpeningBalance write fOpeningBalance;
property PostedDebits: Currency read fPostedDebits write fPostedDebits;
property PostedCredits: Currency read fPostedCredits write fPostedCredits;
property EndingBalance: Currency read fEndingBalance write fEndingBalance;
end;
// 84
TSQLGlAccountOrganization = class(TSQLRecord)
private
fGlAccount: TSQLGlAccountID;
fOrganizationParty: TSQLPartyID;
fRoleType: TSQLRoleTypeID;
fFromDate: TDateTime;
fThruDate: TDateTime;
published
property GlAccount: TSQLGlAccountID read fGlAccount write fGlAccount;
property OrganizationParty: TSQLPartyID read fOrganizationParty write fOrganizationParty;
property RoleType: TSQLRoleTypeID read fRoleType write fRoleType;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
end;
// 85
TSQLGlAccountRole = class(TSQLRecord)
private
fGlAccount: TSQLGlAccountID;
fParty: TSQLPartyID;
fRoleType: TSQLRoleTypeID;
fFromDate: TDateTime;
fThruDate: TDateTime;
published
property GlAccount: TSQLGlAccountID read fGlAccount write fGlAccount;
property Party: TSQLPartyID read fParty write fParty;
property RoleType: TSQLRoleTypeID read fRoleType write fRoleType;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
end;
// 86
TSQLGlAccountType = class(TSQLRecord)
private
fEncode: RawUTF8;
fParentEncode: RawUTF8;
fParent: TSQLGlAccountTypeID;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property ParentEncode: RawUTF8 read fParentEncode write fParentEncode;
property Parent: TSQLGlAccountTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 87
TSQLGlAccountTypeDefault = class(TSQLRecord)
private
fGlAccountType: TSQLGlAccountTypeID;
fOrganizationParty: TSQLPartyID;
fGlAccount: TSQLGlAccountID;
published
property GlAccountType: TSQLGlAccountTypeID read fGlAccountType write fGlAccountType;
property OrganizationParty: TSQLPartyID read fOrganizationParty write fOrganizationParty;
property GlAccount: TSQLGlAccountID read fGlAccount write fGlAccount;
end;
// 88
TSQLGlBudgetXref = class(TSQLRecord)
private
fGlAccount: TSQLGlAccountID;
fBudgetItemType: TSQLBudgetItemTypeID;
fFromDate: TDateTime;
fThruDate: TDateTime;
fAllocationPercentage: Double;
published
property GlAccount: TSQLGlAccountID read fGlAccount write fGlAccount;
property BudgetItemType: TSQLBudgetItemTypeID read fBudgetItemType write fBudgetItemType;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
property AllocationPercentage: Double read fAllocationPercentage write fAllocationPercentage;
end;
// 89
TSQLGlFiscalType = class(TSQLRecord)
private
fEncode: RawUTF8;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 90
TSQLGlJournal = class(TSQLRecord)
private
fGlJournalName: RawUTF8;
fOrganizationParty: TSQLPartyID;
fIsPosted: Boolean;
fPostedDate: TDateTime;
published
property GlJournalName: RawUTF8 read fGlJournalName write fGlJournalName;
property OrganizationParty: TSQLPartyID read fOrganizationParty write fOrganizationParty;
property IsPosted: Boolean read fIsPosted write fIsPosted;
property PostedDate: TDateTime read fPostedDate write fPostedDate;
end;
// 91
TSQLGlReconciliation = class(TSQLRecord)
private
fGlReconciliationName: RawUTF8;
FDescription: RawUTF8;
fCreatedDate: TDateTime;
fCreatedByUserLogin: TSQLUserLoginID;
fLastModifiedDate: TDateTime;
fLastModifiedByUserLogin: TSQLUserLoginID;
fGlAccount: TSQLGlAccountID;
fStatus: TSQLStatusItemID;
fOrganizationParty: TSQLPartyID;
fReconciledBalance: Currency;
fOpeningBalance: Currency;
fReconciledDate: TDateTime;
published
property GlReconciliationName: RawUTF8 read fGlReconciliationName write fGlReconciliationName;
property Description: RawUTF8 read FDescription write FDescription;
property CreatedDate: TDateTime read fCreatedDate write fCreatedDate;
property CreatedByUserLogin: TSQLUserLoginID read fCreatedByUserLogin write fCreatedByUserLogin;
property LastModifiedDate: TDateTime read fLastModifiedDate write fLastModifiedDate;
property LastModifiedByUserLogin: TSQLUserLoginID read fLastModifiedByUserLogin write fLastModifiedByUserLogin;
property GlAccount: TSQLGlAccountID read fGlAccount write fGlAccount;
property Status: TSQLStatusItemID read fStatus write fStatus;
property OrganizationParty: TSQLPartyID read fOrganizationParty write fOrganizationParty;
property ReconciledBalance: Currency read fReconciledBalance write fReconciledBalance;
property OpeningBalance: Currency read fOpeningBalance write fOpeningBalance;
property ReconciledDate: TDateTime read fReconciledDate write fReconciledDate;
end;
// 92
TSQLGlReconciliationEntry = class(TSQLRecord)
private
fGlReconciliation: TSQLGlReconciliationID;
fAcctgTrans: TSQLAcctgTransID;
fAcctgTransEntrySeq: Integer;
fReconciledAmount: Currency;
published
property GlReconciliation: TSQLGlReconciliationID read fGlReconciliation write fGlReconciliation;
property AcctgTrans: TSQLAcctgTransID read fAcctgTrans write fAcctgTrans;
property AcctgTransEntrySeq: Integer read fAcctgTransEntrySeq write fAcctgTransEntrySeq;
property ReconciledAmount: Currency read fReconciledAmount write fReconciledAmount;
end;
// 93
TSQLGlResourceType = class(TSQLRecord)
private
fEncode: RawUTF8;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 94
TSQLGlXbrlClass = class(TSQLRecord)
private
fEncode: RawUTF8;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 95
TSQLPartyAcctgPreference = class(TSQLRecord)
private
fParty: TSQLPartyID;
fFiscalYearStartMonth: Integer;
fFiscalYearStartDay: Integer;
fTaxForm: TSQLEnumerationID;
fCogsMethod: TSQLEnumerationID;
fBaseCurrencyUom: TSQLUomID;
fInvoiceSeqCustMeth: TSQLCustomMethodID;
fInvoiceIdPrefix: RawUTF8;
fLastInvoiceNumber: Integer;
fLastInvoiceRestartDate: TDateTime;
fUseInvoiceIdForReturns: Boolean;
fQuoteSeqCustMethId: TSQLCustomMethodID;
fQuoteIdPrefix: RawUTF8;
fLastQuoteNumber: Integer;
fOrderSeqCustMeth: TSQLCustomMethodID;
fOrderIdPrefix: RawUTF8;
fLastOrderNumber: Integer;
fRefundPaymentMethod: TSQLPaymentMethodID;
fErrorGlJournalId: TSQLGlJournalID;
published
property Party: TSQLPartyID read fParty write fParty;
property FiscalYearStartMonth: Integer read fFiscalYearStartMonth write fFiscalYearStartMonth;
property FiscalYearStartDay: Integer read fFiscalYearStartDay write fFiscalYearStartDay;
property TaxForm: TSQLEnumerationID read fTaxForm write fTaxForm;
property CogsMethod: TSQLEnumerationID read fCogsMethod write fCogsMethod;
property BaseCurrencyUom: TSQLUomID read fBaseCurrencyUom write fBaseCurrencyUom;
property InvoiceSeqCustMeth: TSQLCustomMethodID read fInvoiceSeqCustMeth write fInvoiceSeqCustMeth;
property InvoiceIdPrefix: RawUTF8 read fInvoiceIdPrefix write fInvoiceIdPrefix;
property LastInvoiceNumber: Integer read fLastInvoiceNumber write fLastInvoiceNumber;
property LastInvoiceRestartDate: TDateTime read fLastInvoiceRestartDate write fLastInvoiceRestartDate;
property UseInvoiceIdForReturns: Boolean read fUseInvoiceIdForReturns write fUseInvoiceIdForReturns;
property QuoteSeqCustMethId: TSQLCustomMethodID read fQuoteSeqCustMethId write fQuoteSeqCustMethId;
property QuoteIdPrefix: RawUTF8 read fQuoteIdPrefix write fQuoteIdPrefix;
property LastQuoteNumber: Integer read fLastQuoteNumber write fLastQuoteNumber;
property OrderSeqCustMeth: TSQLCustomMethodID read fOrderSeqCustMeth write fOrderSeqCustMeth;
property OrderIdPrefix: RawUTF8 read fOrderIdPrefix write fOrderIdPrefix;
property LastOrderNumber: Integer read fLastOrderNumber write fLastOrderNumber;
property RefundPaymentMethod: TSQLPaymentMethodID read fRefundPaymentMethod write fRefundPaymentMethod;
property ErrorGlJournalId: TSQLGlJournalID read fErrorGlJournalId write fErrorGlJournalId;
end;
// 96
TSQLProductAverageCost = class(TSQLRecord)
private
fProductAverageCostType: TSQLProductAverageCostTypeID;
fOrganizationParty: TSQLPartyID;
fProduct: TSQLProductID;
fFacility: TSQLFacilityID;
fFromDate: TDateTime;
fThruDate: TDateTime;
fAverageCost: Double;
published
property ProductAverageCostType: TSQLProductAverageCostTypeID read fProductAverageCostType write fProductAverageCostType;
property OrganizationParty: TSQLPartyID read fOrganizationParty write fOrganizationParty;
property Product: TSQLProductID read fProduct write fProduct;
property Facility: TSQLFacilityID read fFacility write fFacility;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
property AverageCost: Double read fAverageCost write fAverageCost;
end;
// 97
TSQLProductAverageCostType = class(TSQLRecord)
private
fEncode: RawUTF8;
fParentEncode: RawUTF8;
fParent: TSQLProductAverageCostTypeID;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property ParentEncode: RawUTF8 read fParentEncode write fParentEncode;
property Parent: TSQLProductAverageCostTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 98
TSQLSettlementTerm = class(TSQLRecord)
private
fEncode: RawUTF8;
fUomEncode: RawUTF8;
fTermName: RawUTF8;
fTermValue: Integer;
fUom: TSQLUomID;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property UomEncode: RawUTF8 read fUomEncode write fUomEncode;
property TermName: RawUTF8 read fTermName write fTermName;
property TermValue: Integer read fTermValue write fTermValue;
property Uom: TSQLUomID read fUom write fUom;
end;
// 99
TSQLVarianceReasonGlAccount = class(TSQLRecord)
private
fVarianceReason: TSQLVarianceReasonID;
fOrganizationParty: TSQLPartyID;
fGlAccountL: TSQLGlAccountID;
published
property VarianceReason: TSQLVarianceReasonID read fVarianceReason write fVarianceReason;
property OrganizationParty: TSQLPartyID read fOrganizationParty write fOrganizationParty;
property GlAccountL: TSQLGlAccountID read fGlAccountL write fGlAccountL;
end;
// 100
TSQLBillingAccount = class(TSQLRecord)
private
fAccountLimit: Currency;
fAccountCurrencyUom: TSQLUomID;
fContactMech: TSQLContactMechID;
fFromDate: TDateTime;
fThruDate: TDateTime;
fDescription: RawUTF8;
fExternalAccount: RawUTF8;
published
property AccountLimit: Currency read fAccountLimit write fAccountLimit;
property AccountCurrencyUom: TSQLUomID read fAccountCurrencyUom write fAccountCurrencyUom;
property ContactMech: TSQLContactMechID read fContactMech write fContactMech;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
property Description: RawUTF8 read fDescription write fDescription;
property ExternalAccount: RawUTF8 read fExternalAccount write fExternalAccount;
end;
// 101
TSQLBillingAccountRole = class(TSQLRecord)
private
fBillingAccount: TSQLBillingAccountID;
fParty: TSQLPartyID;
fRoleType: TSQLRoleTypeID;
fFromDate: TDateTime;
fThruDate: TDateTime;
published
property BillingAccount: TSQLBillingAccountID read fBillingAccount write fBillingAccount;
property Party: TSQLPartyID read fParty write fParty;
property RoleType: TSQLRoleTypeID read fRoleType write fRoleType;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
end;
// 102
TSQLBillingAccountTerm = class(TSQLRecord)
private
fBillingAccount: TSQLBillingAccountID;
fTermType: TSQLTermTypeID;
fTermValue: Currency;
fTermDays: Integer;
fUom: TSQLUomID;
published
property BillingAccount: TSQLBillingAccountID read fBillingAccount write fBillingAccount;
property TermType: TSQLTermTypeID read fTermType write fTermType;
property TermValue: Currency read fTermValue write fTermValue;
property TermDays: Integer read fTermDays write fTermDays;
property Uom: TSQLUomID read fUom write fUom;
end;
// 103
TSQLBillingAccountTermAttr = class(TSQLRecord)
private
fBillingAccountTerm: TSQLBillingAccountTermID;
fAttrName: TSQLTermTypeAttrID;
fAttrValue: RawUTF8;
published
property BillingAccountTerm: TSQLBillingAccountTermID read fBillingAccountTerm write fBillingAccountTerm;
property AttrName: TSQLTermTypeAttrID read fAttrName write fAttrName;
property AttrValue: RawUTF8 read fAttrValue write fAttrValue;
end;
// 104
TSQLCreditCard = class(TSQLRecord)
private
fPaymentMethod: TSQLPaymentMethodID;
fCardType: RawUTF8;
fCardNumber: RawUTF8;
fValidFromDate: TDateTime;
fExpireDate: TDateTime;
fIssueNumber: TDateTime;
fCompanyNameOnCard: RawUTF8;
fTitleOnCard: RawUTF8;
fFirstNameOnCard: RawUTF8;
fMiddleNameOnCard: RawUTF8;
fLastNameOnCard: RawUTF8;
fSuffixOnCard: RawUTF8;
fContactMech: TSQLContactMechID;
fConsecutiveFailedAuths: Integer;
fLastFailedAuthDate: TDateTime;
fConsecutiveFailedNsf: Integer;
fLastFailedNsfDate: TDateTime;
published
property PaymentMethod: TSQLPaymentMethodID read fPaymentMethod write fPaymentMethod;
property CardType: RawUTF8 read fCardType write fCardType;
property CardNumber: RawUTF8 read fCardNumber write fCardNumber;
property ValidFromDate: TDateTime read fValidFromDate write fValidFromDate;
property ExpireDate: TDateTime read fExpireDate write fExpireDate;
property IssueNumber: TDateTime read fIssueNumber write fIssueNumber;
property CompanyNameOnCard: RawUTF8 read fCompanyNameOnCard write fCompanyNameOnCard;
property TitleOnCard: RawUTF8 read fTitleOnCard write fTitleOnCard;
property FirstNameOnCard: RawUTF8 read fFirstNameOnCard write fFirstNameOnCard;
property MiddleNameOnCard: RawUTF8 read fMiddleNameOnCard write fMiddleNameOnCard;
property LastNameOnCard: RawUTF8 read fLastNameOnCard write fLastNameOnCard;
property SuffixOnCard: RawUTF8 read fSuffixOnCard write fSuffixOnCard;
property ContactMech: TSQLContactMechID read fContactMech write fContactMech;
property ConsecutiveFailedAuths: Integer read fConsecutiveFailedAuths write fConsecutiveFailedAuths;
property LastFailedAuthDate: TDateTime read fLastFailedAuthDate write fLastFailedAuthDate;
property ConsecutiveFailedNsf: Integer read fConsecutiveFailedNsf write fConsecutiveFailedNsf;
property LastFailedNsfDate: TDateTime read fLastFailedNsfDate write fLastFailedNsfDate;
end;
// 105
TSQLCreditCardTypeGlAccount = class(TSQLRecord)
private
fCardType: RawUTF8;
fOrganizationParty: TSQLPartyID;
fGlAccount: TSQLGlAccountID;
published
property CardType: RawUTF8 read fCardType write fCardType;
property OrganizationParty: TSQLPartyID read fOrganizationParty write fOrganizationParty;
property GlAccount: TSQLGlAccountID read fGlAccount write fGlAccount;
end;
// 106
TSQLDeduction = class(TSQLRecord)
private
fDeductionType: TSQLDeductionTypeID;
fPayment: TSQLPaymentID;
fAmount: Currency;
published
property DeductionType: TSQLDeductionTypeID read fDeductionType write fDeductionType;
property Payment: TSQLPaymentID read fPayment write fPayment;
property Amount: Currency read fAmount write fAmount;
end;
// 107
TSQLDeductionType = class(TSQLRecord)
private
fParent: TSQLDeductionTypeID;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
published
property Parent: TSQLDeductionTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 108
TSQLEftAccount = class(TSQLRecord)
private
fPaymentMethod: TSQLPaymentMethodID;
fBankName: RawUTF8;
fRoutingNumber: RawUTF8;
fAccountType: RawUTF8;
fAccountNumber: RawUTF8;
fNameOnAccount: RawUTF8;
fCompanyNameOnAccount: RawUTF8;
fContactMech: TSQLContactMechID;
fYearsAtBank: Integer;
published
property PaymentMethod: TSQLPaymentMethodID read fPaymentMethod write fPaymentMethod;
property BankName: RawUTF8 read fBankName write fBankName;
property RoutingNumber: RawUTF8 read fRoutingNumber write fRoutingNumber;
property AccountType: RawUTF8 read fAccountType write fAccountType;
property AccountNumber: RawUTF8 read fAccountNumber write fAccountNumber;
property NameOnAccount: RawUTF8 read fNameOnAccount write fNameOnAccount;
property CompanyNameOnAccount: RawUTF8 read fCompanyNameOnAccount write fCompanyNameOnAccount;
property ContactMech: TSQLContactMechID read fContactMech write fContactMech;
property YearsAtBank: Integer read fYearsAtBank write fYearsAtBank;
end;
// 109
TSQLCheckAccount = class(TSQLRecord)
private
fPaymentMethod: TSQLPaymentMethodID;
fBankName: RawUTF8;
fRoutingNumber: RawUTF8;
fAccountType: RawUTF8;
fAccountNumber: RawUTF8;
fNameOnAccount: RawUTF8;
fCompanyNameOnAccount: RawUTF8;
fContactMech: TSQLContactMechID;
fBranchCode: RawUTF8;
published
property PaymentMethod: TSQLPaymentMethodID read fPaymentMethod write fPaymentMethod;
property BankName: RawUTF8 read fBankName write fBankName;
property RoutingNumber: RawUTF8 read fRoutingNumber write fRoutingNumber;
property AccountType: RawUTF8 read fAccountType write fAccountType;
property AccountNumber: RawUTF8 read fAccountNumber write fAccountNumber;
property NameOnAccount: RawUTF8 read fNameOnAccount write fNameOnAccount;
property CompanyNameOnAccount: RawUTF8 read fCompanyNameOnAccount write fCompanyNameOnAccount;
property ContactMech: TSQLContactMechID read fContactMech write fContactMech;
property BranchCode: RawUTF8 read fBranchCode write fBranchCode;
end;
// 110
TSQLGiftCard = class(TSQLRecord)
private
fPaymentMethod: TSQLPaymentMethodID;
fCardNumber: RawUTF8;
fPinNumber: RawUTF8;
fExpireDate: TDateTime;
fContactMech: TSQLContactMechID;
published
property PaymentMethod: TSQLPaymentMethodID read fPaymentMethod write fPaymentMethod;
property CardNumber: RawUTF8 read fCardNumber write fCardNumber;
property PinNumber: RawUTF8 read fPinNumber write fPinNumber;
property ExpireDate: TDateTime read fExpireDate write fExpireDate;
property ContactMech: TSQLContactMechID read fContactMech write fContactMech;
end;
// 111
TSQLGiftCardFulfillment = class(TSQLRecord)
private
fTypeEnum: TSQLEnumerationID;
fMerchant: RawUTF8;
fParty: TSQLPartyID;
fOrderId: TSQLOrderHeaderID;
fOrderItemSeq: Integer;
fSurveyResponse: TSQLSurveyResponseID;
fCardNumber: RawUTF8;
fPinNumber: RawUTF8;
fAmount: Currency;
fResponseCode: RawUTF8;
fReferenceNum: RawUTF8;
fAuthCode: RawUTF8;
fFulfillmentDate: TDateTime;
published
property TypeEnum: TSQLEnumerationID read fTypeEnum write fTypeEnum;
property Merchant: RawUTF8 read fMerchant write fMerchant;
property Party: TSQLPartyID read fParty write fParty;
property OrderId: TSQLOrderHeaderID read fOrderId write fOrderId;
property OrderItemSeq: Integer read fOrderItemSeq write fOrderItemSeq;
property SurveyResponse: TSQLSurveyResponseID read fSurveyResponse write fSurveyResponse;
property CardNumber: RawUTF8 read fCardNumber write fCardNumber;
property PinNumber: RawUTF8 read fPinNumber write fPinNumber;
property Amount: Currency read fAmount write fAmount;
property ResponseCode: RawUTF8 read fResponseCode write fResponseCode;
property ReferenceNum: RawUTF8 read fReferenceNum write fReferenceNum;
property AuthCode: RawUTF8 read fAuthCode write fAuthCode;
property FulfillmentDate: TDateTime read fFulfillmentDate write fFulfillmentDate;
end;
// 112
TSQLPayment = class(TSQLRecord)
private
fPaymentType: TSQLPaymentTypeID;
fPaymentMethodType: TSQLPaymentMethodTypeID;
fPaymentMethod: TSQLPaymentMethodID;
fPaymentGatewayResponse: TSQLPaymentGatewayResponseID;
fPaymentPreference: TSQLOrderPaymentPreferenceID;
fPartyFrom: TSQLPartyID;
fPartyTo: TSQLPartyID;
fRoleTypeTo: TSQLRoleTypeID;
fStatus: TSQLStatusItemID;
fEffectiveDate: TDateTime;
fPaymentRefNum: RawUTF8;
fAmount: Currency;
fCurrencyUom: TSQLUomID;
fComments: RawUTF8;
fFinAccountTrans: TSQLFinAccountTransID;
fOverrideGlAccount: TSQLGlAccountID;
fActualCurrencyAmount: Currency;
fActualCurrencyUom: TSQLUomID;
published
property PaymentType: TSQLPaymentTypeID read fPaymentType write fPaymentType;
property PaymentMethodType: TSQLPaymentMethodTypeID read fPaymentMethodType write fPaymentMethodType;
property PaymentMethod: TSQLPaymentMethodID read fPaymentMethod write fPaymentMethod;
property PaymentGatewayResponse: TSQLPaymentGatewayResponseID read fPaymentGatewayResponse write fPaymentGatewayResponse;
property PaymentPreference: TSQLOrderPaymentPreferenceID read fPaymentPreference write fPaymentPreference;
property PartyFrom: TSQLPartyID read fPartyFrom write fPartyFrom;
property PartyTo: TSQLPartyID read fPartyTo write fPartyTo;
property RoleTypeTo: TSQLRoleTypeID read fRoleTypeTo write fRoleTypeTo;
property Status: TSQLStatusItemID read fStatus write fStatus;
property EffectiveDate: TDateTime read fEffectiveDate write fEffectiveDate;
property PaymentRefNum: RawUTF8 read fPaymentRefNum write fPaymentRefNum;
property Amount: Currency read fAmount write fAmount;
property CurrencyUom: TSQLUomID read fCurrencyUom write fCurrencyUom;
property Comments: RawUTF8 read fComments write fComments;
property FinAccountTrans: TSQLFinAccountTransID read fFinAccountTrans write fFinAccountTrans;
property OverrideGlAccount: TSQLGlAccountID read fOverrideGlAccount write fOverrideGlAccount;
property ActualCurrencyAmount: Currency read fActualCurrencyAmount write fActualCurrencyAmount;
property ActualCurrencyUom: TSQLUomID read fActualCurrencyUom write fActualCurrencyUom;
end;
// 113
TSQLPaymentApplication = class(TSQLRecord)
private
fPayment: TSQLPaymentID;
fInvoice: TSQLInvoiceID;
fInvoiceItemSeq: Integer;
fBillingAccount: TSQLBillingAccountID;
fOverrideGlAccount: TSQLGlAccountID;
fToPayment: TSQLPaymentID;
fTaxAuthGeo: TSQLGeoID;
fAmountApplied: Currency;
published
property Payment: TSQLPaymentID read fPayment write fPayment;
property Invoice: TSQLInvoiceID read fInvoice write fInvoice;
property InvoiceItemSeq: Integer read fInvoiceItemSeq write fInvoiceItemSeq;
property BillingAccount: TSQLBillingAccountID read fBillingAccount write fBillingAccount;
property OverrideGlAccount: TSQLGlAccountID read fOverrideGlAccount write fOverrideGlAccount;
property ToPayment: TSQLPaymentID read fToPayment write fToPayment;
property TaxAuthGeo: TSQLGeoID read fTaxAuthGeo write fTaxAuthGeo;
property AmountApplied: Currency read fAmountApplied write fAmountApplied;
end;
// 114
TSQLPaymentAttribute = class(TSQLRecord)
private
fPayment: TSQLPaymentID;
fAttrName: TSQLInventoryItemTypeAttrID;
fAttrValue: RawUTF8;
fAttrDescription: RawUTF8;
published
property Payment: TSQLPaymentID read fPayment write fPayment;
property AttrName: TSQLInventoryItemTypeAttrID read fAttrName write fAttrName;
property AttrValue: RawUTF8 read fAttrValue write fAttrValue;
property AttrDescription: RawUTF8 read fAttrDescription write fAttrDescription;
end;
// 115
TSQLPaymentBudgetAllocation = class(TSQLRecord)
private
fBudget: TSQLBudgetID;
fBudgetItemSeq: Integer;
fPayment: TSQLPaymentID;
fAmount: Currency;
published
property Budget: TSQLBudgetID read fBudget write fBudget;
property BudgetItemSeq: Integer read fBudgetItemSeq write fBudgetItemSeq;
property Payment: TSQLPaymentID read fPayment write fPayment;
property Amount: Currency read fAmount write fAmount;
end;
// 116
TSQLPaymentContent = class(TSQLRecord)
private
fPayment: TSQLPaymentID;
fPaymentContentType: TSQLPaymentContentTypeID;
fContent: TSQLContentID;
fFromDate: TDateTime;
fThruDate: TDateTime;
published
property Payment: TSQLPaymentID read fPayment write fPayment;
property PaymentContentType: TSQLPaymentContentTypeID read fPaymentContentType write fPaymentContentType;
property Content: TSQLContentID read fContent write fContent;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
end;
// 117
TSQLPaymentContentType = class(TSQLRecord)
private
fParent: TSQLPaymentContentTypeID;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
published
property Parent: TSQLPaymentContentTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 118
TSQLPaymentMethod = class(TSQLRecord)
private
fPaymentMethodType: TSQLPaymentMethodTypeID;
fParty: TSQLPartyID;
fGlAccount: TSQLGlAccountID;
fFinAccount: TSQLFinAccountID;
fDescription: RawUTF8;
fFromDate: TDateTime;
fThruDate: TDateTime;
published
property PaymentMethodType: TSQLPaymentMethodTypeID read fPaymentMethodType write fPaymentMethodType;
property Party: TSQLPartyID read fParty write fParty;
property GlAccount: TSQLGlAccountID read fGlAccount write fGlAccount;
property FinAccount: TSQLFinAccountID read fFinAccount write fFinAccount;
property Description: RawUTF8 read fDescription write fDescription;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
end;
// 119
TSQLPaymentMethodType = class(TSQLRecord)
private
fEncode: RawUTF8;
fName: RawUTF8;
FDescription: RawUTF8;
fDefaultGlAccount: TSQLGlAccountID;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
property DefaultGlAccount: TSQLGlAccountID read fDefaultGlAccount write fDefaultGlAccount;
end;
// 120
TSQLPaymentMethodTypeGlAccount = class(TSQLRecord)
private
fPaymentMethodType: TSQLPaymentMethodTypeID;
fOrganizationParty: TSQLPartyID;
fGlAccount: TSQLGlAccountID;
published
property PaymentMethodType: TSQLPaymentMethodTypeID read fPaymentMethodType write fPaymentMethodType;
property OrganizationParty: TSQLPartyID read fOrganizationParty write fOrganizationParty;
property GlAccount: TSQLGlAccountID read fGlAccount write fGlAccount;
end;
// 121
TSQLPaymentType = class(TSQLRecord)
private
fEncode: RawUTF8;
fParentEncode: RawUTF8;
fParent: TSQLPaymentTypeID;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property ParentEncode: RawUTF8 read fParentEncode write fParentEncode;
property Parent: TSQLPaymentTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 122
TSQLPaymentTypeAttr = class(TSQLRecord)
private
fPaymentType: TSQLPaymentTypeID;
fAttrName: TSQLInventoryItemTypeAttrID;
fDescription: RawUTF8;
published
property PaymentType: TSQLPaymentTypeID read fPaymentType write fPaymentType;
property AttrName: TSQLInventoryItemTypeAttrID read fAttrName write fAttrName;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 123
TSQLPaymentGlAccountTypeMap = class(TSQLRecord)
private
fPaymentType: TSQLPaymentTypeID;
fOrganizationParty: TSQLPartyID;
fGlAccountType: TSQLGlAccountTypeID;
published
property PaymentType: TSQLPaymentTypeID read fPaymentType write fPaymentType;
property OrganizationParty: TSQLPartyID read fOrganizationParty write fOrganizationParty;
property GlAccountType: TSQLGlAccountTypeID read fGlAccountType write fGlAccountType;
end;
// 124
TSQLPaymentGatewayConfigType = class(TSQLRecord)
private
fEncode: RawUTF8;
fParentEncode: RawUTF8;
fParent: TSQLPaymentGatewayConfigTypeID;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property ParentEncode: RawUTF8 read fParentEncode write fParentEncode;
property Parent: TSQLPaymentGatewayConfigTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 125
TSQLPaymentGatewayConfig = class(TSQLRecord)
private
fPaymentGatewayConfigType: TSQLPaymentGatewayConfigTypeID;
FDescription: RawUTF8;
published
property PaymentGatewayConfigType: TSQLPaymentGatewayConfigTypeID read fPaymentGatewayConfigType write fPaymentGatewayConfigType;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 126
TSQLPaymentGatewaySagePay = class(TSQLRecord)
private
fPaymentGatewayConfig: TSQLPaymentGatewayConfigID;
fVendor: RawUTF8;
fProductionHost: RawUTF8;
fTestingHost: RawUTF8;
fSagePayMode: RawUTF8;
fProtocolVersion: RawUTF8;
fAuthenticationTransType: RawUTF8;
fAuthenticationUrl: RawUTF8;
fAuthoriseTransType: RawUTF8;
fAuthoriseUrl: RawUTF8;
fReleaseTransType: RawUTF8;
fReleaseUrl: RawUTF8;
fVoidUrl: RawUTF8;
fRefundUrl: RawUTF8;
published
property PaymentGatewayConfig: TSQLPaymentGatewayConfigID read fPaymentGatewayConfig write fPaymentGatewayConfig;
property Vendor: RawUTF8 read fVendor write fVendor;
property ProductionHost: RawUTF8 read fProductionHost write fProductionHost;
property TestingHost: RawUTF8 read fTestingHost write fTestingHost;
property SagePayMode: RawUTF8 read fSagePayMode write fSagePayMode;
property ProtocolVersion: RawUTF8 read fProtocolVersion write fProtocolVersion;
property AuthenticationTransType: RawUTF8 read fAuthenticationTransType write fAuthenticationTransType;
property AuthenticationUrl: RawUTF8 read fAuthenticationUrl write fAuthenticationUrl;
property AuthoriseTransType: RawUTF8 read fAuthoriseTransType write fAuthoriseTransType;
property AuthoriseUrl: RawUTF8 read fAuthoriseUrl write fAuthoriseUrl;
property ReleaseTransType: RawUTF8 read fReleaseTransType write fReleaseTransType;
property ReleaseUrl: RawUTF8 read fReleaseUrl write fReleaseUrl;
property VoidUrl: RawUTF8 read fVoidUrl write fVoidUrl;
property RefundUrl: RawUTF8 read fRefundUrl write fRefundUrl;
end;
// 127
TSQLPaymentGatewayAuthorizeNet = class(TSQLRecord)
private
fPaymentGatewayConfig: TSQLPaymentGatewayConfigID;
fTransactionUrl: RawUTF8;
fCertificateAlias: RawUTF8;
fApiVersion: RawUTF8;
fDelimitedData: RawUTF8;
fDelimiterChar: RawUTF8;
fCpVersion: RawUTF8;
fCpMarketType: RawUTF8;
fCpDeviceType: RawUTF8;
fMethod: RawUTF8;
fEmailCustomer: RawUTF8;
fEmailMerchant: RawUTF8;
fTestMode: RawUTF8;
fRelayResponse: RawUTF8;
fTranKey: RawUTF8;
fUser: RawUTF8;
fPwd: RawUTF8;
fTransDescription: RawUTF8;
fDuplicateWindow: Integer;
published
property PaymentGatewayConfig: TSQLPaymentGatewayConfigID read fPaymentGatewayConfig write fPaymentGatewayConfig;
property TransactionUrl: RawUTF8 read fTransactionUrl write fTransactionUrl;
property CertificateAlias: RawUTF8 read fCertificateAlias write fCertificateAlias;
property ApiVersion: RawUTF8 read fApiVersion write fApiVersion;
property DelimitedData: RawUTF8 read fDelimitedData write fDelimitedData;
property DelimiterChar: RawUTF8 read fDelimiterChar write fDelimiterChar;
property CpVersion: RawUTF8 read fCpVersion write fCpVersion;
property CpMarketType: RawUTF8 read fCpMarketType write fCpMarketType;
property CpDeviceType: RawUTF8 read fCpDeviceType write fCpDeviceType;
property Method: RawUTF8 read fMethod write fMethod;
property EmailCustomer: RawUTF8 read fEmailCustomer write fEmailCustomer;
property EmailMerchant: RawUTF8 read fEmailMerchant write fEmailMerchant;
property TestMode: RawUTF8 read fTestMode write fTestMode;
property RelayResponse: RawUTF8 read fRelayResponse write fRelayResponse;
property TranKey: RawUTF8 read fTranKey write fTranKey;
property User: RawUTF8 read fUser write fUser;
property Pwd: RawUTF8 read fPwd write fPwd;
property TransDescription: RawUTF8 read fTransDescription write fTransDescription;
property DuplicateWindow: Integer read fDuplicateWindow write fDuplicateWindow;
end;
// 128
TSQLPaymentGatewayEway = class(TSQLRecord)
private
fPaymentGatewayConfig: TSQLPaymentGatewayConfigID;
fCustomer: RawUTF8;
fRefundPwd: RawUTF8;
fTestMode: RawUTF8;
fEnableCvn: RawUTF8;
fEnableBeagle: RawUTF8;
published
property PaymentGatewayConfig: TSQLPaymentGatewayConfigID read fPaymentGatewayConfig write fPaymentGatewayConfig;
property Customer: RawUTF8 read fCustomer write fCustomer;
property RefundPwd: RawUTF8 read fRefundPwd write fRefundPwd;
property TestMode: RawUTF8 read fTestMode write fTestMode;
property EnableCvn: RawUTF8 read fEnableCvn write fEnableCvn;
property EnableBeagle: RawUTF8 read fEnableBeagle write fEnableBeagle;
end;
// 129
TSQLPaymentGatewayCyberSource = class(TSQLRecord)
private
fPaymentGatewayConfig: TSQLPaymentGatewayConfigID;
fMerchant: RawUTF8;
fApiVersion: RawUTF8;
fProduction: RawUTF8;
fKeysDir: RawUTF8;
fKeysFile: RawUTF8;
fLogEnabled: RawUTF8;
fLogDir: RawUTF8;
fLogFile: RawUTF8;
fLogSize: Integer;
fMerchantDescr: RawUTF8;
fMerchantContact: RawUTF8;
fAutoBill: RawUTF8;
fEnableDav: Boolean;
fFraudScore: Boolean;
fIgnoreAvs: RawUTF8;
fDisableBillAvs: Boolean;
fAvsDeclineCodes: RawUTF8;
published
property PaymentGatewayConfig: TSQLPaymentGatewayConfigID read fPaymentGatewayConfig write fPaymentGatewayConfig;
property Merchant: RawUTF8 read fMerchant write fMerchant;
property ApiVersion: RawUTF8 read fApiVersion write fApiVersion;
property Production: RawUTF8 read fProduction write fProduction;
property KeysDir: RawUTF8 read fKeysDir write fKeysDir;
property KeysFile: RawUTF8 read fKeysFile write fKeysFile;
property LogEnabled: RawUTF8 read fLogEnabled write fLogEnabled;
property LogDir: RawUTF8 read fLogDir write fLogDir;
property LogFile: RawUTF8 read fLogFile write fLogFile;
property LogSize: Integer read fLogSize write fLogSize;
property MerchantDescr: RawUTF8 read fMerchantDescr write fMerchantDescr;
property MerchantContact: RawUTF8 read fMerchantContact write fMerchantContact;
property AutoBill: RawUTF8 read fAutoBill write fAutoBill;
property EnableDav: Boolean read fEnableDav write fEnableDav;
property FraudScore: Boolean read fFraudScore write fFraudScore;
property IgnoreAvs: RawUTF8 read fIgnoreAvs write fIgnoreAvs;
property DisableBillAvs: Boolean read fDisableBillAvs write fDisableBillAvs;
property AvsDeclineCodes: RawUTF8 read fAvsDeclineCodes write fAvsDeclineCodes;
end;
// 130
TSQLPaymentGatewayPayflowPro = class(TSQLRecord)
private
fPaymentGatewayConfig: TSQLPaymentGatewayConfigID;
fCertsPath: RawUTF8;
fHostAddress: RawUTF8;
fHostPort: Integer;
fTimeout: Integer;
fProxyAddress: RawUTF8;
fProxyPort: Integer;
fProxyLogon: RawUTF8;
fProxyPassword: RawUTF8;
fVendor: RawUTF8;
fUser: RawUTF8;
fPwd: RawUTF8;
fPartner: RawUTF8;
fCheckAvs: Boolean;
fCheckCvv2: Boolean;
fPreAuth: Boolean;
fEnableTransmit: RawUTF8;
fLogFileName: RawUTF8;
fLoggingLevel: Integer;
fMaxLogFileSize: Integer;
fStackTraceOn: Boolean;
fRedirectUrl: RawUTF8;
fCancelReturnUrl: RawUTF8;
published
property PaymentGatewayConfig: TSQLPaymentGatewayConfigID read fPaymentGatewayConfig write fPaymentGatewayConfig;
property CertsPath: RawUTF8 read fCertsPath write fCertsPath;
property HostAddress: RawUTF8 read fHostAddress write fHostAddress;
property HostPort: Integer read fHostPort write fHostPort;
property Timeout: Integer read fTimeout write fTimeout;
property ProxyAddress: RawUTF8 read fProxyAddress write fProxyAddress;
property ProxyPort: Integer read fProxyPort write fProxyPort;
property ProxyLogon: RawUTF8 read fProxyLogon write fProxyLogon;
property ProxyPassword: RawUTF8 read fProxyPassword write fProxyPassword;
property Vendor: RawUTF8 read fVendor write fVendor;
property User: RawUTF8 read fUser write fUser;
property Pwd: RawUTF8 read fPwd write fPwd;
property Partner: RawUTF8 read fPartner write fPartner;
property CheckAvs: Boolean read fCheckAvs write fCheckAvs;
property CheckCvv2: Boolean read fCheckCvv2 write fCheckCvv2;
property PreAuth: Boolean read fPreAuth write fPreAuth;
property EnableTransmit: RawUTF8 read fEnableTransmit write fEnableTransmit;
property LogFileName: RawUTF8 read fLogFileName write fLogFileName;
property LoggingLevel: Integer read fLoggingLevel write fLoggingLevel;
property MaxLogFileSize: Integer read fMaxLogFileSize write fMaxLogFileSize;
property StackTraceOn: Boolean read fStackTraceOn write fStackTraceOn;
property RedirectUrl: RawUTF8 read fRedirectUrl write fRedirectUrl;
property CancelReturnUrl: RawUTF8 read fCancelReturnUrl write fCancelReturnUrl;
end;
// 131
TSQLPaymentGatewayPayPal = class(TSQLRecord)
private
fPaymentGatewayConfig: TSQLPaymentGatewayConfigID;
fBusinessEmail: RawUTF8;
fApiUserName: RawUTF8;
fApiPassword: RawUTF8;
fApiSignature: RawUTF8;
fApiEnvironment: RawUTF8;
fNotifyUrl: RawUTF8;
fReturnUrl: RawUTF8;
fCancelReturnUrl: RawUTF8;
fImageUrl: RawUTF8;
fConfirmTemplate: RawUTF8;
fRedirectUrl: RawUTF8;
fConfirmUrl: RawUTF8;
fShippingCallbackUrl: RawUTF8;
fRequireConfirmedShipping: Boolean;
published
property PaymentGatewayConfig: TSQLPaymentGatewayConfigID read fPaymentGatewayConfig write fPaymentGatewayConfig;
property BusinessEmail: RawUTF8 read fBusinessEmail write fBusinessEmail;
property ApiUserName: RawUTF8 read fApiUserName write fApiUserName;
property ApiPassword: RawUTF8 read fApiPassword write fApiPassword;
property ApiSignature: RawUTF8 read fApiSignature write fApiSignature;
property ApiEnvironment: RawUTF8 read fApiEnvironment write fApiEnvironment;
property NotifyUrl: RawUTF8 read fNotifyUrl write fNotifyUrl;
property ReturnUrl: RawUTF8 read fReturnUrl write fReturnUrl;
property CancelReturnUrl: RawUTF8 read fCancelReturnUrl write fCancelReturnUrl;
property ImageUrl: RawUTF8 read fImageUrl write fImageUrl;
property ConfirmTemplate: RawUTF8 read fConfirmTemplate write fConfirmTemplate;
property RedirectUrl: RawUTF8 read fRedirectUrl write fRedirectUrl;
property ConfirmUrl: RawUTF8 read fConfirmUrl write fConfirmUrl;
property ShippingCallbackUrl: RawUTF8 read fShippingCallbackUrl write fShippingCallbackUrl;
property RequireConfirmedShipping: Boolean read fRequireConfirmedShipping write fRequireConfirmedShipping;
end;
// 132
TSQLPaymentGatewayClearCommerce = class(TSQLRecord)
private
fPaymentGatewayConfig: TSQLPaymentGatewayConfigID;
fSource: RawUTF8;
fGroupId: RawUTF8;
fClient: RawUTF8;
fUsername: RawUTF8;
fPwd: RawUTF8;
fUserAlias: RawUTF8;
fEffectiveAlias: RawUTF8;
fProcessMode: Boolean;
fServerURL: RawUTF8;
fEnableCVM: Boolean;
published
property PaymentGatewayConfig: TSQLPaymentGatewayConfigID read fPaymentGatewayConfig write fPaymentGatewayConfig;
property Source: RawUTF8 read fSource write fSource;
property GroupId: RawUTF8 read fGroupId write fGroupId;
property Client: RawUTF8 read fClient write fClient;
property Username: RawUTF8 read fUsername write fUsername;
property Pwd: RawUTF8 read fPwd write fPwd;
property UserAlias: RawUTF8 read fUserAlias write fUserAlias;
property EffectiveAlias: RawUTF8 read fEffectiveAlias write fEffectiveAlias;
property ProcessMode: Boolean read fProcessMode write fProcessMode;
property ServerURL: RawUTF8 read fServerURL write fServerURL;
property EnableCVM: Boolean read fEnableCVM write fEnableCVM;
end;
// 133
TSQLPaymentGatewayWorldPay = class(TSQLRecord)
private
fPaymentGatewayConfig: TSQLPaymentGatewayConfigID;
fRedirectUrl: RawUTF8;
//Worldpay instance Id
fInstId: RawUTF8;
fAuthMode: Boolean;
fFixContact: Boolean;
fHideContact: Boolean;
fHideCurrency: Boolean;
fLangId: RawUTF8;
fNoLanguageMenu: Boolean;
fWithDelivery: Boolean;
fTestMode: Integer;
published
property PaymentGatewayConfig: TSQLPaymentGatewayConfigID read fPaymentGatewayConfig write fPaymentGatewayConfig;
property RedirectUrl: RawUTF8 read fRedirectUrl write fRedirectUrl;
property InstId: RawUTF8 read fInstId write fInstId;
property AuthMode: Boolean read fAuthMode write fAuthMode;
property FixContact: Boolean read fFixContact write fFixContact;
property HideContact: Boolean read fHideContact write fHideContact;
property HideCurrency: Boolean read fHideCurrency write fHideCurrency;
property LangId: RawUTF8 read fLangId write fLangId;
property NoLanguageMenu: Boolean read fNoLanguageMenu write fNoLanguageMenu;
property WithDelivery: Boolean read fWithDelivery write fWithDelivery;
property TestMode: Integer read fTestMode write fTestMode;
end;
// 134
TSQLPaymentGatewayOrbital = class(TSQLRecord)
private
fPaymentGatewayConfig: TSQLPaymentGatewayConfigID;
fUsername: RawUTF8;
fConnectionPassword: RawUTF8;
fMerchantId: RawUTF8;
fEngineClass: RawUTF8;
fHostName: RawUTF8;
fPort: Integer;
fHostNameFailover: RawUTF8;
fPortFailover: Integer;
fConnectionTimeoutSeconds: Integer;
fReadTimeoutSeconds: Integer;
fAuthorizationURI: RawUTF8;
fSdkVersion: RawUTF8;
fSslSocketFactory: RawUTF8;
fResponseType: RawUTF8;
published
property PaymentGatewayConfig: TSQLPaymentGatewayConfigID read fPaymentGatewayConfig write fPaymentGatewayConfig;
property Username: RawUTF8 read fUsername write fUsername;
property ConnectionPassword: RawUTF8 read fConnectionPassword write fConnectionPassword;
property MerchantId: RawUTF8 read fMerchantId write fMerchantId;
property EngineClass: RawUTF8 read fEngineClass write fEngineClass;
property HostName: RawUTF8 read fHostName write fHostName;
property Port: Integer read fPort write fPort;
property HostNameFailover: RawUTF8 read fHostNameFailover write fHostNameFailover;
property PortFailover: Integer read fPortFailover write fPortFailover;
property ConnectionTimeoutSeconds: Integer read fConnectionTimeoutSeconds write fConnectionTimeoutSeconds;
property ReadTimeoutSeconds: Integer read fReadTimeoutSeconds write fReadTimeoutSeconds;
property AuthorizationURI: RawUTF8 read fAuthorizationURI write fAuthorizationURI;
property SdkVersion: RawUTF8 read fSdkVersion write fSdkVersion;
property SslSocketFactory: RawUTF8 read fSslSocketFactory write fSslSocketFactory;
property ResponseType: RawUTF8 read fResponseType write fResponseType;
end;
// 135
TSQLPaymentGatewaySecurePay = class(TSQLRecord)
private
fPaymentGatewayConfig: TSQLPaymentGatewayConfigID;
fMerchantId: RawUTF8;
fPwd: RawUTF8;
fServerURL: RawUTF8;
fProcessTimeout: Integer;
fEnableAmountRound: Boolean;
published
property PaymentGatewayConfig: TSQLPaymentGatewayConfigID read fPaymentGatewayConfig write fPaymentGatewayConfig;
property MerchantId: RawUTF8 read fMerchantId write fMerchantId;
property Pwd: RawUTF8 read fPwd write fPwd;
property ServerURL: RawUTF8 read fServerURL write fServerURL;
property ProcessTimeout: Integer read fProcessTimeout write fProcessTimeout;
property EnableAmountRound: Boolean read fEnableAmountRound write fEnableAmountRound;
end;
// 136
TSQLPaymentGatewayiDEAL = class(TSQLRecord)
private
fPaymentGatewayConfig: TSQLPaymentGatewayConfigID;
fMerchantId: RawUTF8;
fMerchantSubId: RawUTF8;
fMerchantReturnURL: RawUTF8;
fAcquirerURL: RawUTF8;
fAcquirerTimeout: RawUTF8;
fPrivateCert: RawUTF8;
fAcquirerKeyStoreFilename: RawUTF8;
fAcquirerKeyStorePassword: RawUTF8;
fMerchantKeyStoreFilename: RawUTF8;
fMerchantKeyStorePassword: RawUTF8;
fExpirationPeriod: RawUTF8;
published
property PaymentGatewayConfig: TSQLPaymentGatewayConfigID read fPaymentGatewayConfig write fPaymentGatewayConfig;
property MerchantId: RawUTF8 read fMerchantId write fMerchantId;
property MerchantSubId: RawUTF8 read fMerchantSubId write fMerchantSubId;
property MerchantReturnURL: RawUTF8 read fMerchantReturnURL write fMerchantReturnURL;
property AcquirerURL: RawUTF8 read fAcquirerURL write fAcquirerURL;
property AcquirerTimeout: RawUTF8 read fAcquirerTimeout write fAcquirerTimeout;
property PrivateCert: RawUTF8 read fPrivateCert write fPrivateCert;
property AcquirerKeyStoreFilename: RawUTF8 read fAcquirerKeyStoreFilename write fAcquirerKeyStoreFilename;
property AcquirerKeyStorePassword: RawUTF8 read fAcquirerKeyStorePassword write fAcquirerKeyStorePassword;
property MerchantKeyStoreFilename: RawUTF8 read fMerchantKeyStoreFilename write fMerchantKeyStoreFilename;
property MerchantKeyStorePassword: RawUTF8 read fMerchantKeyStorePassword write fMerchantKeyStorePassword;
property ExpirationPeriod: RawUTF8 read fExpirationPeriod write fExpirationPeriod;
end;
// 137
TSQLPaymentGatewayRespMsg = class(TSQLRecord)
private
fPaymentGatewayResponse: TSQLPaymentGatewayResponseID;
fPgrMessage: RawUTF8;
published
property PaymentGatewayResponse: TSQLPaymentGatewayResponseID read fPaymentGatewayResponse write fPaymentGatewayResponse;
property PgrMessage: RawUTF8 read fPgrMessage write fPgrMessage;
end;
// 138
TSQLPaymentGatewayResponse = class(TSQLRecord)
private
fPaymentServiceTypeEnum: TSQLEnumerationID;
fOrderPaymentPreference: TSQLOrderPaymentPreferenceID;
fPaymentMethodType: TSQLPaymentMethodTypeID;
fPaymentMethod: TSQLPaymentMethodID;
fTransCodeEnum: TSQLEnumerationID;
fAmount: Currency;
fCurrencyUom: TSQLUomID;
fReferenceNum: RawUTF8;
fAltReference: RawUTF8;
fSubReference: RawUTF8;
fGatewayCode: RawUTF8;
fGatewayFlag: RawUTF8;
fGatewayAvsResult: RawUTF8;
fGatewayCvResult: RawUTF8;
fGatewayScoreResult: RawUTF8;
fGatewayMessage: RawUTF8;
fTransactionDate: TDateTime;
fResultDeclined: Boolean;
fResultNsf: Boolean;
fResultBadExpire: Boolean;
fResultBadCardNumber: Boolean;
published
property PaymentServiceTypeEnum: TSQLEnumerationID read fPaymentServiceTypeEnum write fPaymentServiceTypeEnum;
property OrderPaymentPreference: TSQLOrderPaymentPreferenceID read fOrderPaymentPreference write fOrderPaymentPreference;
property PaymentMethodType: TSQLPaymentMethodTypeID read fPaymentMethodType write fPaymentMethodType;
property PaymentMethod: TSQLPaymentMethodID read fPaymentMethod write fPaymentMethod;
property TransCodeEnum: TSQLEnumerationID read fTransCodeEnum write fTransCodeEnum;
property Amount: Currency read fAmount write fAmount;
property CurrencyUom: TSQLUomID read fCurrencyUom write fCurrencyUom;
property ReferenceNum: RawUTF8 read fReferenceNum write fReferenceNum;
property AltReference: RawUTF8 read fAltReference write fAltReference;
property SubReference: RawUTF8 read fSubReference write fSubReference;
property GatewayCode: RawUTF8 read fGatewayCode write fGatewayCode;
property GatewayFlag: RawUTF8 read fGatewayFlag write fGatewayFlag;
property GatewayAvsResult: RawUTF8 read fGatewayAvsResult write fGatewayAvsResult;
property GatewayCvResult: RawUTF8 read fGatewayCvResult write fGatewayCvResult;
property GatewayScoreResult: RawUTF8 read fGatewayScoreResult write fGatewayScoreResult;
property GatewayMessage: RawUTF8 read fGatewayMessage write fGatewayMessage;
property TransactionDate: TDateTime read fTransactionDate write fTransactionDate;
property ResultDeclined: Boolean read fResultDeclined write fResultDeclined;
property ResultNsf: Boolean read fResultNsf write fResultNsf;
property ResultBadExpire: Boolean read fResultBadExpire write fResultBadExpire;
property ResultBadCardNumber: Boolean read fResultBadCardNumber write fResultBadCardNumber;
end;
// 139
TSQLPaymentGroup = class(TSQLRecord)
private
fPaymentGroupType: TSQLPaymentGroupTypeID;
fPaymentGroupName: RawUTF8;
published
property PaymentGroupType: TSQLPaymentGroupTypeID read fPaymentGroupType write fPaymentGroupType;
property PaymentGroupName: RawUTF8 read fPaymentGroupName write fPaymentGroupName;
end;
// 140
TSQLPaymentGroupType = class(TSQLRecord)
private
fEncode: RawUTF8;
fParentEncode: RawUTF8;
fParent: TSQLPaymentGroupTypeID;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property ParentEncode: RawUTF8 read fParentEncode write fParentEncode;
property Parent: TSQLPaymentGroupTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 141
TSQLPaymentGroupMember = class(TSQLRecord)
private
fPaymentGroup: TSQLPaymentGroupID;
fPayment: TSQLPaymentID;
fFromDate: TDateTime;
fThruDate: TDateTime;
fSequenceNum: Integer;
published
property PaymentGroup: TSQLPaymentGroupID read fPaymentGroup write fPaymentGroup;
property Payment: TSQLPaymentID read fPayment write fPayment;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
property SequenceNum: Integer read fSequenceNum write fSequenceNum;
end;
// 142
TSQLPayPalPaymentMethod = class(TSQLRecord)
private
{fPaymentMethod: TSQLPaymentMethodID;
fPayer: Integer;
fExpressCheckoutToken: RawUTF8;
fPayerStatus: RawUTF8;
fAvsAddr: Boolean;
fAvsZip: Boolean;
fCorrelation: Integer;
fContactMech: TSQLContactMechID;
fTransaction: Integer;
published
property PaymentMethod: TSQLPaymentMethodID read fPaymentMethod write fPaymentMethod;
property Payer: Integer read fPayer write fPayer;
property ExpressCheckoutToken: RawUTF8 read fExpressCheckoutToken write fExpressCheckoutToken;
property PayerStatus: RawUTF8 read fPayerStatus write fPayerStatus;
property AvsAddr: Boolean read fAvsAddr write fAvsAddr;
property AvsZip: Boolean read fAvsZip write fAvsZip;
property Correlation: Integer read fCorrelation write fCorrelation;
property ContactMech: TSQLContactMechID read fContactMech write fContactMech;
property Transaction: Integer read fTransaction write fTransaction;}
end;
// 143
TSQLValueLinkKey = class(TSQLRecord)
private
fMerchant: Integer;
fPublicKey: TSQLRawBlob;
fPrivateKey: TSQLRawBlob;
fExchangeKey: TSQLRawBlob;
fWorkingKey: TSQLRawBlob;
fWorkingKeyIndex: TSQLRawBlob;
fLastWorkingKey: TSQLRawBlob;
fCreatedDate: TDateTime;
fCreatedByTerminal: Integer;
fCreatedByUserLogin: Integer;
fLastModifiedDate: TDateTime;
fLastModifiedByTerminal: Integer;
fLastModifiedByUserLogin: Integer;
published
property Merchant: Integer read fMerchant write fMerchant;
property PublicKey: TSQLRawBlob read fPublicKey write fPublicKey;
property PrivateKey: TSQLRawBlob read fPrivateKey write fPrivateKey;
property ExchangeKey: TSQLRawBlob read fExchangeKey write fExchangeKey;
property WorkingKey: TSQLRawBlob read fWorkingKey write fWorkingKey;
property WorkingKeyIndex: TSQLRawBlob read fWorkingKeyIndex write fWorkingKeyIndex;
property LastWorkingKey: TSQLRawBlob read fLastWorkingKey write fLastWorkingKey;
property CreatedDate: TDateTime read fCreatedDate write fCreatedDate;
property CreatedByTerminal: Integer read fCreatedByTerminal write fCreatedByTerminal;
property CreatedByUserLogin: Integer read fCreatedByUserLogin write fCreatedByUserLogin;
property LastModifiedDate: TDateTime read fLastModifiedDate write fLastModifiedDate;
property LastModifiedByTerminal: Integer read fLastModifiedByTerminal write fLastModifiedByTerminal;
property LastModifiedByUserLogin: Integer read fLastModifiedByUserLogin write fLastModifiedByUserLogin;
end;
// 144
TSQLPartyTaxAuthInfo = class(TSQLRecord)
private
fParty: TSQLPartyID;
fTaxAuthGeoId: Integer;
fTaxAuthPartyId: Integer;
fFromDate: TDateTime;
fThruDate: TDateTime;
fPartyTaxId: Integer;
fIsExempt: Boolean;
fIsNexus: Boolean;
published
property Party: TSQLPartyID read fParty write fParty;
property TaxAuthGeoId: Integer read fTaxAuthPartyId write fTaxAuthPartyId;
property TaxAuthPartyId: Integer read fTaxAuthPartyId write fTaxAuthPartyId;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
property PartyTaxId: Integer read fPartyTaxId write fPartyTaxId;
property IsExempt: Boolean read fIsExempt write fIsExempt;
property IsNexus: Boolean read fIsNexus write fIsNexus;
end;
// 145
TSQLTaxAuthority = class(TSQLRecord)
private
fTaxAuthGeo: TSQLGeoID;
fTaxAuthParty: TSQLPartyID;
fRequireTaxIdForExemption: Boolean;
fTaxIdFormatPattern: RawUTF8;
fIncludeTaxInPrice: Currency;
published
property TaxAuthGeo: TSQLGeoID read fTaxAuthGeo write fTaxAuthGeo;
property TaxAuthParty: TSQLPartyID read fTaxAuthParty write fTaxAuthParty;
property RequireTaxIdForExemption: Boolean read fRequireTaxIdForExemption write fRequireTaxIdForExemption;
property TaxIdFormatPattern: RawUTF8 read fTaxIdFormatPattern write fTaxIdFormatPattern;
property IncludeTaxInPrice: Currency read fIncludeTaxInPrice write fIncludeTaxInPrice;
end;
// 146
TSQLTaxAuthorityAssoc = class(TSQLRecord)
private
fTaxAuthGeo: TSQLGeoID;
fTaxAuthParty: TSQLPartyID;
fToTaxAuthGeo: TSQLGeoID;
fToTaxAuthParty: TSQLPartyID;
fFromDate: TDateTime;
fThruDate: TDateTime;
fTaxAuthorityAssocType: TSQLTaxAuthorityAssocTypeID;
published
property TaxAuthGeo: TSQLGeoID read fTaxAuthGeo write fTaxAuthGeo;
property TaxAuthParty: TSQLPartyID read fTaxAuthParty write fTaxAuthParty;
property ToTaxAuthGeo: TSQLGeoID read fToTaxAuthGeo write fToTaxAuthGeo;
property ToTaxAuthParty: TSQLPartyID read fToTaxAuthParty write fToTaxAuthParty;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
property TaxAuthorityAssocType: TSQLTaxAuthorityAssocTypeID read fTaxAuthorityAssocType write fTaxAuthorityAssocType;
end;
// 147
TSQLTaxAuthorityAssocType = class(TSQLRecord)
private
fEncode: RawUTF8;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 148
TSQLTaxAuthorityCategory = class(TSQLRecord)
private
fTaxAuthGeo: TSQLGeoID;
fTaxAuthParty: TSQLPartyID;
fProductCategory: TSQLProductCategoryID;
published
property TaxAuthGeo: TSQLGeoID read fTaxAuthGeo write fTaxAuthGeo;
property TaxAuthParty: TSQLPartyID read fTaxAuthParty write fTaxAuthParty;
property ProductCategory: TSQLProductCategoryID read fProductCategory write fProductCategory;
end;
// 149
TSQLTaxAuthorityGlAccount = class(TSQLRecord)
private
fTaxAuthGeo: TSQLGeoID;
fTaxAuthParty: TSQLPartyID;
fOrganizationParty: TSQLPartyID;
fGlAccount: TSQLGlAccountID;
published
property TaxAuthGeo: TSQLGeoID read fTaxAuthGeo write fTaxAuthGeo;
property TaxAuthParty: TSQLPartyID read fTaxAuthParty write fTaxAuthParty;
property OrganizationParty: TSQLPartyID read fOrganizationParty write fOrganizationParty;
property GlAccount: TSQLGlAccountID read fGlAccount write fGlAccount;
end;
// 150
TSQLTaxAuthorityRateProduct = class(TSQLRecord)
private
fTaxAuthorityRateSeq: Integer;
fTaxAuthGeo: TSQLGeoID;
fTaxAuthParty: TSQLPartyID;
fTaxAuthorityRateType: TSQLTaxAuthorityRateTypeID;
fProductStore: TSQLProductStoreID;
fProductCategory: TSQLProductCategoryID;
fTitleTransferEnum: Integer;
fMinItemPrice: Currency;
fMinPurchase: Currency;
fTaxShipping: Boolean;
fTaxPercentage: Double;
fTaxPromotions: Boolean;
FDescription: RawUTF8;
fIsTaxInShippingPrice: Boolean;
published
property TaxAuthorityRateSeq: Integer read fTaxAuthorityRateSeq write fTaxAuthorityRateSeq;
property TaxAuthGeo: TSQLGeoID read fTaxAuthGeo write fTaxAuthGeo;
property TaxAuthParty: TSQLPartyID read fTaxAuthParty write fTaxAuthParty;
property TaxAuthorityRateType: TSQLTaxAuthorityRateTypeID read fTaxAuthorityRateType write fTaxAuthorityRateType;
property ProductStore: TSQLProductStoreID read fProductStore write fProductStore;
property ProductCategory: TSQLProductCategoryID read fProductCategory write fProductCategory;
property TitleTransferEnum: Integer read fTitleTransferEnum write fTitleTransferEnum;
property MinItemPrice: Currency read fMinItemPrice write fMinItemPrice;
property MinPurchase: Currency read fMinPurchase write fMinPurchase;
property TaxShipping: Boolean read fTaxShipping write fTaxShipping;
property TaxPercentage: Double read fTaxPercentage write fTaxPercentage;
property TaxPromotions: Boolean read fTaxPromotions write fTaxPromotions;
property Description: RawUTF8 read fDescription write fDescription;
property IsTaxInShippingPrice: Boolean read fIsTaxInShippingPrice write fIsTaxInShippingPrice;
end;
// 151
TSQLTaxAuthorityRateType = class(TSQLRecord)
private
fEncode: RawUTF8;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 152
TSQLZipSalesRuleLookup = class(TSQLRecord)
private
fStateCode: RawUTF8;
fCity: RawUTF8;
fCounty: RawUTF8;
fFromDate: TDateTime;
fIdCode: RawUTF8;
fTaxable: RawUTF8;
fShipCond: RawUTF8;
published
property StateCode: RawUTF8 read fStateCode write fStateCode;
property City: RawUTF8 read fCity write fCity;
property County: RawUTF8 read fCounty write fCounty;
property FromDate: TDateTime read fFromDate write fFromDate;
property IdCode: RawUTF8 read fIdCode write fIdCode;
property Taxable: RawUTF8 read fTaxable write fTaxable;
property ShipCond: RawUTF8 read fShipCond write fShipCond;
end;
// 153
TSQLZipSalesTaxLookup = class(TSQLRecord)
private
fZipCode: RawUTF8;
fStateCode: RawUTF8;
fCity: RawUTF8;
fCounty: RawUTF8;
fFromDate: TDateTime;
fCountyFips: RawUTF8;
fCountyDefault: Boolean;
fGeneralDefault: Boolean;
fInsideCity: Boolean;
fGeoCode: RawUTF8;
fStateSalesTax: Double;
fCitySalesTax: Double;
fCityLocalSalesTax: Double;
fCountySalesTax: Double;
fCountyLocalSalesTax: Double;
fComboSalesTax: Double;
fStateUseTax: Double;
fCityUseTax: Double;
fCityLocalUseTax: Double;
fCountyUseTax: Double;
fCountyLocalUseTax: Double;
fComboUseTax: Double;
published
property ZipCode: RawUTF8 read fZipCode write fZipCode;
property StateCode: RawUTF8 read fStateCode write fStateCode;
property City: RawUTF8 read fCity write fCity;
property County: RawUTF8 read fCounty write fCounty;
property FromDate: TDateTime read fFromDate write fFromDate;
property CountyFips: RawUTF8 read fCountyFips write fCountyFips;
property CountyDefault: Boolean read fCountyDefault write fCountyDefault;
property GeneralDefault: Boolean read fGeneralDefault write fGeneralDefault;
property InsideCity: Boolean read fInsideCity write fInsideCity;
property GeoCode: RawUTF8 read fGeoCode write fGeoCode;
property StateSalesTax: Double read fStateSalesTax write fStateSalesTax;
property CitySalesTax: Double read fCitySalesTax write fCitySalesTax;
property CityLocalSalesTax: Double read fCityLocalSalesTax write fCityLocalSalesTax;
property CountySalesTax: Double read fCountySalesTax write fCountySalesTax;
property CountyLocalSalesTax: Double read fCountyLocalSalesTax write fCountyLocalSalesTax;
property ComboSalesTax: Double read fComboSalesTax write fComboSalesTax;
property StateUseTax: Double read fStateUseTax write fStateUseTax;
property CityUseTax: Double read fCityUseTax write fCityUseTax;
property CityLocalUseTax: Double read fCityLocalUseTax write fCityLocalUseTax;
property CountyUseTax: Double read fCountyUseTax write fCountyUseTax;
property CountyLocalUseTax: Double read fCountyLocalUseTax write fCountyLocalUseTax;
property ComboUseTax: Double read fComboUseTax write fComboUseTax;
end;
// 154
TSQLPartyGlAccount = class(TSQLRecord)
private
fOrganizationParty: TSQLPartyID;
fParty: TSQLPartyID;
fRoleType: TSQLRoleTypeID;
fGlAccountType: TSQLGlAccountTypeID;
fGlAccount: TSQLGlAccountID;
published
property OrganizationParty: TSQLPartyID read fOrganizationParty write fOrganizationParty;
property Party: TSQLPartyID read fParty write fParty;
property RoleType: TSQLRoleTypeID read fRoleType write fRoleType;
property GlAccountType: TSQLGlAccountTypeID read fGlAccountType write fGlAccountType;
property GlAccount: TSQLGlAccountID read fGlAccount write fGlAccount;
end;
// 155
TSQLRateType = class(TSQLRecord)
private
fEncode: RawUTF8;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 156
TSQLRateAmount = class(TSQLRecord)
private
fRateType: TSQLRateTypeID;
fRateCurrencyUom: TSQLUomID;
fPeriodType: TSQLPeriodTypeID;
fWorkEffort: TSQLWorkEffortID;
fEmplPositionType: TSQLEmplPositionTypeID;
fFromDate: TDateTime;
fThruDate: TDateTime;
fRateAmount: Currency;
published
property RateType: TSQLRateTypeID read fRateType write fRateType;
property RateCurrencyUom: TSQLUomID read fRateCurrencyUom write fRateCurrencyUom;
property PeriodType: TSQLPeriodTypeID read fPeriodType write fPeriodType;
property WorkEffort: TSQLWorkEffortID read fWorkEffort write fWorkEffort;
property EmplPositionType: TSQLEmplPositionTypeID read fEmplPositionType write fEmplPositionType;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
property RateAmount: Currency read fRateAmount write fRateAmount;
end;
// 157
TSQLPartyRate = class(TSQLRecord)
private
fParty: TSQLPartyID;
fRateType: TSQLRateTypeID;
fDefaultRate: Boolean;
fPercentageUsed: Double;
fFromDate: TDateTime;
fThruDate: TDateTime;
published
property Party: TSQLPartyID read fParty write fParty;
property RateType: TSQLRateTypeID read fRateType write fRateType;
property DefaultRate: Boolean read fDefaultRate write fDefaultRate;
property PercentageUsed: Double read fPercentageUsed write fPercentageUsed;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
end;
// 158
TSQLGlAccountCategory = class(TSQLRecord)
private
fGlAccountCategoryType: TSQLGlAccountCategoryTypeID;
fDescription: RawUTF8;
published
property GlAccountCategoryType: TSQLGlAccountCategoryTypeID read fGlAccountCategoryType write fGlAccountCategoryType;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 159
TSQLGlAccountCategoryMember = class(TSQLRecord)
private
fGlAccount: TSQLGlAccountID;
fGlAccountCategory: TSQLGlAccountCategoryID;
fFromDate: TDateTime;
fThruDate: TDateTime;
fAmountPercentage: Double;
published
property GlAccount: TSQLGlAccountID read fGlAccount write fGlAccount;
property GlAccountCategory: TSQLGlAccountCategoryID read fGlAccountCategory write fGlAccountCategory;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
property AmountPercentage: Double read fAmountPercentage write fAmountPercentage;
end;
// 160
TSQLGlAccountCategoryType = class(TSQLRecord)
private
fEncode: RawUTF8;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
implementation
uses
Classes, SysUtils;
// applications/datamodel/data/seed/AccountingSeedData.xml
// 1
class procedure TSQLAcctgTransType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLAcctgTransType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLAcctgTransType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','AcctgTransType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update AcctgTransType set parent=(select c.id from AcctgTransType c where c.Encode=AcctgTransType.ParentEncode);');
finally
Rec.Free;
end;
end;
// 2
class procedure TSQLAcctgTransEntryType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLAcctgTransEntryType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLAcctgTransEntryType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','AcctgTransEntryType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update AcctgTransEntryType set parent=(select c.id from AcctgTransEntryType c where c.Encode=AcctgTransEntryType.ParentEncode);');
finally
Rec.Free;
end;
end;
// 3
class procedure TSQLBudgetItemType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLBudgetItemType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLBudgetItemType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','BudgetItemType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update BudgetItemType set parent=(select c.id from BudgetItemType c where c.Encode=BudgetItemType.ParentEncode);');
finally
Rec.Free;
end;
end;
// 4
class procedure TSQLBudgetType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLBudgetType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLBudgetType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','BudgetType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update BudgetType set parent=(select c.id from BudgetType c where c.Encode=BudgetType.ParentEncode);');
finally
Rec.Free;
end;
end;
// 5
class procedure TSQLFinAccountTransType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLFinAccountTransType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLFinAccountTransType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','FinAccountTransType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update FinAccountTransType set parent=(select c.id from FinAccountTransType c where c.Encode=FinAccountTransType.ParentEncode);');
finally
Rec.Free;
end;
end;
// 6
class procedure TSQLFinAccountType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLFinAccountType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLFinAccountType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','FinAccountType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update FinAccountType set parent=(select c.id from FinAccountType c where c.Encode=FinAccountType.ParentEncode);');
Server.Execute('update FinAccountType set ReplenishEnum=(select c.id from Enumeration c where c.Encode=FinAccountType.ReplenishEnumEncode);');
finally
Rec.Free;
end;
end;
// 7
class procedure TSQLFixedAssetType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLFixedAssetType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLFixedAssetType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','FixedAssetType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update FixedAssetType set parent=(select c.id from FixedAssetType c where c.Encode=FixedAssetType.ParentEncode);');
finally
Rec.Free;
end;
end;
// 8
class procedure TSQLFixedAssetIdentType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLFixedAssetIdentType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLFixedAssetIdentType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','FixedAssetIdentType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
finally
Rec.Free;
end;
end;
// 9
class procedure TSQLFixedAssetProductType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLFixedAssetProductType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLFixedAssetProductType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','FixedAssetProductType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
finally
Rec.Free;
end;
end;
// 10
class procedure TSQLGlAccountClass.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLGlAccountClass;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLGlAccountClass.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','GlAccountClass.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update GlAccountClass set parent=(select c.id from GlAccountClass c where c.Encode=GlAccountClass.ParentEncode);');
finally
Rec.Free;
end;
end;
// 11
class procedure TSQLGlAccountType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLGlAccountType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLGlAccountType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','GlAccountType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update GlAccountType set parent=(select c.id from GlAccountType c where c.Encode=GlAccountType.ParentEncode);');
finally
Rec.Free;
end;
end;
// 12
class procedure TSQLGlResourceType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLGlResourceType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLGlResourceType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','GlResourceType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
finally
Rec.Free;
end;
end;
// 13
class procedure TSQLGlXbrlClass.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLGlXbrlClass;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLGlXbrlClass.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','GlXbrlClass.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
finally
Rec.Free;
end;
end;
// 14
class procedure TSQLGlFiscalType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLGlFiscalType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLGlFiscalType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','GlFiscalType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
finally
Rec.Free;
end;
end;
// 15
class procedure TSQLGlAccountCategoryType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLGlAccountCategoryType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLGlAccountCategoryType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','GlAccountCategoryType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
finally
Rec.Free;
end;
end;
// 16
class procedure TSQLInvoiceContentType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLInvoiceContentType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLInvoiceContentType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','InvoiceContentType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update InvoiceContentType set parent=(select c.id from InvoiceContentType c where c.Encode=InvoiceContentType.ParentEncode);');
finally
Rec.Free;
end;
end;
// 17
class procedure TSQLInvoiceItemType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLInvoiceItemType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLInvoiceItemType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','InvoiceItemType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update InvoiceItemType set parent=(select c.id from InvoiceItemType c where c.Encode=InvoiceItemType.ParentEncode);');
Server.Execute('update InvoiceItemType set DefaultGlAccount=(select c.id from GlAccount c where c.Encode=InvoiceItemType.DefaultGlAccountEncode);');
Server.Execute('update InvoiceItemTypeMap set InvoiceItemType=(select c.id from InvoiceItemType c where c.Encode=InvoiceItemTypeMap.InvoiceItemTypeEncode);');
finally
Rec.Free;
end;
end;
// 18
class procedure TSQLInvoiceType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLInvoiceType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLInvoiceType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','InvoiceType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update InvoiceType set parent=(select c.id from InvoiceType c where c.Encode=InvoiceType.ParentEncode);');
Server.Execute('update InvoiceItemTypeMap set InvoiceType=(select c.id from InvoiceType c where c.Encode=InvoiceItemTypeMap.InvoiceTypeEncode);');
finally
Rec.Free;
end;
end;
// 19
class procedure TSQLInvoiceItemAssocType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLInvoiceItemAssocType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLInvoiceItemAssocType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','InvoiceItemAssocType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update InvoiceItemAssocType set parent=(select c.id from InvoiceItemAssocType c where c.Encode=InvoiceItemAssocType.ParentEncode);');
finally
Rec.Free;
end;
end;
// 19
class procedure TSQLInvoiceItemTypeMap.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLInvoiceItemTypeMap;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLInvoiceItemTypeMap.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','InvoiceItemTypeMap.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update InvoiceItemTypeMap set InvoiceType=(select c.id from InvoiceType c where c.Encode=InvoiceItemTypeMap.InvoiceTypeEncode);');
Server.Execute('update InvoiceItemTypeMap set InvoiceItemType=(select c.id from InvoiceItemType c where c.Encode=InvoiceItemTypeMap.InvoiceItemTypeEncode);');
finally
Rec.Free;
end;
end;
// 20
class procedure TSQLPaymentMethodType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLPaymentMethodType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLPaymentMethodType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','PaymentMethodType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
finally
Rec.Free;
end;
end;
// 21
class procedure TSQLPaymentType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLPaymentType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLPaymentType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','PaymentType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update PaymentType set parent=(select c.id from PaymentType c where c.Encode=PaymentType.ParentEncode);');
finally
Rec.Free;
end;
end;
// 22
class procedure TSQLPaymentGroupType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLPaymentGroupType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLPaymentGroupType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','PaymentGroupType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update PaymentGroupType set parent=(select c.id from PaymentGroupType c where c.Encode=PaymentGroupType.ParentEncode);');
finally
Rec.Free;
end;
end;
// 23
class procedure TSQLSettlementTerm.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLSettlementTerm;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLSettlementTerm.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','SettlementTerm.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update SettlementTerm set Uom=(select c.id from Uom c where c.Encode=SettlementTerm.UomEncode);');
finally
Rec.Free;
end;
end;
// 24
class procedure TSQLFixedAssetStdCostType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLFixedAssetStdCostType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLFixedAssetStdCostType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','FixedAssetStdCostType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update FixedAssetStdCostType set parent=(select c.id from FixedAssetStdCostType c where c.Encode=FixedAssetStdCostType.ParentEncode);');
finally
Rec.Free;
end;
end;
// 25
class procedure TSQLTaxAuthorityAssocType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLTaxAuthorityAssocType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLTaxAuthorityAssocType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','TaxAuthorityAssocType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
finally
Rec.Free;
end;
end;
// 26
class procedure TSQLTaxAuthorityRateType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLTaxAuthorityRateType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLTaxAuthorityRateType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','TaxAuthorityRateType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
finally
Rec.Free;
end;
end;
// 27
class procedure TSQLRateType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLRateType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLRateType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','RateType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
finally
Rec.Free;
end;
end;
// 28
class procedure TSQLProductAverageCostType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLProductAverageCostType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLProductAverageCostType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ProductAverageCostType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update ProductAverageCostType set parent=(select c.id from ProductAverageCostType c where c.Encode=ProductAverageCostType.ParentEncode);');
finally
Rec.Free;
end;
end;
// 29
class procedure TSQLBudgetReviewResultType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLBudgetReviewResultType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLBudgetReviewResultType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','BudgetReviewResultType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
finally
Rec.Free;
end;
end;
// 30
class procedure TSQLPaymentGatewayConfigType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLPaymentGatewayConfigType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLPaymentGatewayConfigType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','PaymentGatewayConfigType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update PaymentGatewayConfigType set parent=(select c.id from PaymentGatewayConfigType c where c.Encode=PaymentGatewayConfigType.ParentEncode);');
finally
Rec.Free;
end;
end;
// 31
class procedure TSQLGlAccountGroupType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLGlAccountGroupType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLGlAccountGroupType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','GlAccountGroupType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update GlAccountGroup set GlAccountGroupType=(select c.id from GlAccountGroupType c where c.Encode=GlAccountGroup.GlAccountGroupTypeEncode);');
finally
Rec.Free;
end;
end;
// 32
class procedure TSQLGlAccountGroup.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLGlAccountGroup;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLGlAccountGroup.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','GlAccountGroup.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update GlAccountGroup set GlAccountGroupType=(select c.id from GlAccountGroupType c where c.Encode=GlAccountGroup.GlAccountGroupTypeEncode);');
finally
Rec.Free;
end;
end;
end.
|
unit Unit1;
interface
uses
Winapi.Windows,
System.SysUtils, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Imaging.Jpeg,
//GLS
GLScene, GLObjects, GLTerrainRenderer, GLHeightData, GLCadencer,
GLTexture, GLWin32Viewer, GLVectorGeometry, GLCrossPlatform, GLMaterial,
GLCoordinates, GLBaseClasses, GLKeyboard;
type
TForm1 = class(TForm)
GLSceneViewer1: TGLSceneViewer;
GLScene1: TGLScene;
GLCamera1: TGLCamera;
DummyCube1: TGLDummyCube;
TerrainRenderer1: TGLTerrainRenderer;
Timer1: TTimer;
GLCadencer1: TGLCadencer;
GLMaterialLibrary1: TGLMaterialLibrary;
GLCustomHDS: TGLCustomHDS;
procedure GLSceneViewer1MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
procedure Timer1Timer(Sender: TObject);
procedure GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
procedure FormCreate(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure GLCustomHDSStartPreparingData(heightData: THeightData);
private
{ Private declarations }
public
{ Public declarations }
mx, my : Integer;
fullScreen : Boolean;
FCamHeight : Single;
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.FormCreate(Sender: TObject);
var
i : Integer;
bmp : TBitmap;
begin
// 8 MB height data cache
// Note this is the data size in terms of elevation samples, it does not
// take into account all the data required/allocated by the renderer
GLCustomHDS.MaxPoolSize:=8*1024*1024;
// Move camera starting point to an interesting hand-picked location
DummyCube1.Position.X:=50;
DummyCube1.Position.Z:=150;
// Initial camera height offset (controled with pageUp/pageDown)
FCamHeight:=20;
// We build several basic 1D textures which are just color ramps
// all use automatic texture mapping corodinates, in ObjectLinear method
// (ie. texture coordinates for a vertex depend on that vertex coordinates)
bmp:=TBitmap.Create;
bmp.PixelFormat:=pf24bit;
bmp.Width:=256;
bmp.Height:=1;
// Black-White ramp, autotexture maps to Z coordinate
// This one changes with altitude, this is a quick way to obtain
// altitude-dependant coloring
for i:=0 to 255 do
bmp.Canvas.Pixels[i, 0]:=RGB(i, i, i);
with GLMaterialLibrary1.AddTextureMaterial('BW', bmp) do begin
with Material.Texture do begin
MappingMode:=tmmObjectLinear;
MappingSCoordinates.AsVector:=VectorMake(0, 0, 0.0001, 0);
end;
end;
// Red, Blue map linearly to X and Y axis respectively
for i:=0 to 255 do
bmp.Canvas.Pixels[i, 0]:=RGB(i, 0, 0);
with GLMaterialLibrary1.AddTextureMaterial('Red', bmp) do begin
with Material.Texture do begin
MappingMode:=tmmObjectLinear;
MappingSCoordinates.AsVector:=VectorMake(0.1, 0, 0, 0);
end;
end;
for i:=0 to 255 do
bmp.Canvas.Pixels[i, 0]:=RGB(0, 0, i);
with GLMaterialLibrary1.AddTextureMaterial('Blue', bmp) do begin
with Material.Texture do begin
MappingMode:=tmmObjectLinear;
MappingSCoordinates.AsVector:=VectorMake(0, 0.1, 0, 0);
end;
end;
bmp.Free;
TerrainRenderer1.MaterialLibrary:=GLMaterialLibrary1;
end;
//
// The beef : this event does all the interesting elevation data stuff
//
procedure TForm1.GLCustomHDSStartPreparingData(heightData: THeightData);
var
y, x : Integer;
rasterLine : PByteArray;
oldType : THeightDataType;
b : Byte;
d, dy : Single;
begin
heightData.DataState:=hdsPreparing;
// retrieve data
with heightData do begin
oldType:=DataType;
Allocate(hdtByte);
// Cheap texture changed (32 is our tileSize = 2^5)
// This basicly picks a texture for each tile depending on the tile's position
case (((XLeft xor YTop) shr 5) and 3) of
0, 3 : heightData.MaterialName:='BW';
1 : heightData.materialName:='Blue';
2 : heightData.materialName:='Red';
end;
// 'Cheap' elevation data : this is just a formula z=f(x, y)
for y:=YTop to YTop+Size-1 do begin
rasterLine:=ByteRaster[y-YTop];
dy:=Sqr(y);
for x:=XLeft to XLeft+Size-1 do begin
d:=Sqrt(Sqr(x)+dy);
b:=Round(128+128*Sin(d*0.2)/(d*0.1+1));
rasterLine[x-XLeft]:=b;
end;
end;
if oldType<>hdtByte then
DataType:=oldType;
end;
inherited;
end;
// Movement, mouse handling etc.
procedure TForm1.GLSceneViewer1MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
mx:=x;
my:=y;
end;
procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
begin
if ssLeft in Shift then begin
GLCamera1.MoveAroundTarget(my-y, mx-x);
mx:=x;
my:=y;
end;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
Caption:=Format('%.1f FPS - %d',
[GLSceneViewer1.FramesPerSecond, TerrainRenderer1.LastTriangleCount]);
GLSceneViewer1.ResetPerformanceMonitor;
end;
procedure TForm1.FormKeyPress(Sender: TObject; var Key: Char);
begin
case Key of
'+' : if GLCamera1.DepthOfView<4000 then begin
GLCamera1.DepthOfView:=GLCamera1.DepthOfView*1.2;
with GLSceneViewer1.Buffer.FogEnvironment do begin
FogEnd:=FogEnd*1.2;
FogStart:=FogStart*1.2;
end;
end;
'-' : if GLCamera1.DepthOfView>300 then begin
GLCamera1.DepthOfView:=GLCamera1.DepthOfView/1.2;
with GLSceneViewer1.Buffer.FogEnvironment do begin
FogEnd:=FogEnd/1.2;
FogStart:=FogStart/1.2;
end;
end;
'*' : with TerrainRenderer1 do
if CLODPrecision>5 then CLODPrecision:=Round(CLODPrecision*0.8);
'/' : with TerrainRenderer1 do
if CLODPrecision<500 then CLODPrecision:=Round(CLODPrecision*1.2);
'8' : with TerrainRenderer1 do
if QualityDistance>40 then QualityDistance:=Round(QualityDistance*0.8);
'9' : with TerrainRenderer1 do
if QualityDistance<1000 then QualityDistance:=Round(QualityDistance*1.2);
end;
Key:=#0;
end;
procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
var
speed : Single;
begin
// handle keypresses
if IsKeyDown(VK_SHIFT) then
speed:=5*deltaTime
else speed:=deltaTime;
with GLCamera1.Position do begin
if IsKeyDown(VK_RIGHT) then
DummyCube1.Translate(Z*speed, 0, -X*speed);
if IsKeyDown(VK_LEFT) then
DummyCube1.Translate(-Z*speed, 0, X*speed);
if IsKeyDown(VK_UP) then
DummyCube1.Translate(-X*speed, 0, -Z*speed);
if IsKeyDown(VK_DOWN) then
DummyCube1.Translate(X*speed, 0, Z*speed);
if IsKeyDown(VK_PRIOR) then
FCamHeight:=FCamHeight+10*speed;
if IsKeyDown(VK_NEXT) then
FCamHeight:=FCamHeight-10*speed;
if IsKeyDown(VK_ESCAPE) then Close;
end;
// don't drop through terrain!
with DummyCube1.Position do
Y:=TerrainRenderer1.InterpolatedHeight(AsVector)+FCamHeight;
end;
end.
|
unit TestCalcLogic;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
{$RTTI EXPLICIT METHODS([vcPrivate..vcPublished]) PROPERTIES([vcPrivate..vcPublished]) FIELDS([vcPrivate..vcPublished])}
uses
System.SysUtils, System.Classes, TestFramework, CalcLogic, DUnitTestingCore, TestStructureUnit;
type
// Test methods for class TCalcLogic
TestTCalcLogic = class(TCoreTestCase)
strict private
TestCalcLogic: TCalcLogic;
private
a, b: variant;
ExpectedResult: variant;
FailMessage: string;
Operation: string;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestAdd;
procedure TestSub;
end;
TestTCalcLogic1 = class(TCoreTestCase)
strict private
TestCalcLogic1: TCalcLogic;
private
a, b: integer;
ExpectedResult: integer;
FailMessage: string;
Operation: string;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestMul;
procedure TestDiv;
end;
implementation
procedure TestTCalcLogic.SetUp;
var
ParamValue: TInputDataArray;
begin
TestCalcLogic := TCalcLogic.Create;
ParamValue := DataArray.Items[Self.FTestName];
a := ParamValue[0].AsString;
b := ParamValue[1].AsString;
ExpectedResult := ParamValue[2].AsString;
FailMessage := ParamValue[3].AsString;
Operation := ParamValue[4].AsString;
end;
procedure TestTCalcLogic.TearDown;
begin
TestCalcLogic.Free;
TestCalcLogic := nil;
end;
procedure TestTCalcLogic.TestAdd;
var
ReturnValue: Integer;
begin
if Operation = 'except' then
begin
StartExpectingException(Exception);
ReturnValue := TestCalcLogic.Add(a, b);
StopExpectingException('');
AssertResults<Integer>(ExpectedResult, ReturnValue, Operation, FailMessage);
end
else
AssertResults<Integer>(ExpectedResult, TestCalcLogic.Add(a, b), Operation, FailMessage);
end;
procedure TestTCalcLogic.TestSub;
var
ReturnValue: Integer;
begin
if Operation = 'except' then
begin
StartExpectingException(Exception);
ReturnValue := TestCalcLogic.Sub(a, b);
StopExpectingException('');
AssertResults<Integer>(ExpectedResult, ReturnValue, Operation, FailMessage);
end
else
AssertResults<Integer>(ExpectedResult, TestCalcLogic.Sub(a, b), Operation, FailMessage);
end;
procedure TestTCalcLogic1.SetUp;
var
ParamValue: TInputDataArray;
begin
TestCalcLogic1 := TCalcLogic.Create;
ParamValue := DataArray.Items[Self.FTestName];
a := StrToInt(ParamValue[0].AsString);
b := StrToInt(ParamValue[1].AsString);
ExpectedResult := StrToInt(ParamValue[2].AsString);
FailMessage := ParamValue[3].AsString;
Operation := ParamValue[4].AsString;
end;
procedure TestTCalcLogic1.TearDown;
begin
TestCalcLogic1.Free;
TestCalcLogic1 := nil;
end;
procedure TestTCalcLogic1.TestMul;
var
ReturnValue: Integer;
begin
if Operation = 'except' then
begin
StartExpectingException(Exception);
ReturnValue := TestCalcLogic1.Mul(a, b);
StopExpectingException('');
AssertResults<Integer>(ExpectedResult, ReturnValue, Operation, FailMessage);
end
else
AssertResults<Integer>(ExpectedResult, TestCalcLogic1.Mul(a, b), Operation, FailMessage);
end;
procedure TestTCalcLogic1.TestDiv;
var
ReturnValue: Integer;
begin
if Operation = 'except' then
begin
StartExpectingException(Exception);
ReturnValue := TestCalcLogic1.Division(a, b);
StopExpectingException('');
AssertResults<Integer>(ExpectedResult, ReturnValue, Operation, FailMessage);
end
else
AssertResults<Integer>(ExpectedResult, TestCalcLogic1.Division(a, b), Operation, FailMessage);
end;
initialization
end.
|
unit CustomCrypt;
{/*
Модуль Cryptor реализует интерфейс к OpenSSL и Synapse, что позволяет
шифровать сообщения, отправлять и получать почту...
Перспективные задачи:
1. Реализовать протокол аутентификации и обмена информации
2. Создать хранилище ключей
3. Сохранение и удаление переписки
*/}
{$mode objfpc}{$H+}
interface
uses
Classes, Controls,
Dialogs, mimemess, mimepart, pop3send, Process, smtpsend,
SQLiteWrap, SynaCode, SysUtils;
{ TCustomCrypt }
type
TCustomCrypt = class(TWinControl)
private
Pop3: TPOP3Send;
MailMessage: TMimeMess;
fHostPop3, fHostSmtp, fLogin, fPassword: string;
fFriendMail: string;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
//Запуск внешних утилит
function RunApp(Command: string): string; overload;
function RunApp(Command: string; NoEchoCmd: boolean): string; overload;
function RunApp(Command, FileToSave: string): string; overload;
//Архивирование
function MakeBz2(DirPath, SavedName: string): string;
function ExtractBz2(FileName, DirPath: string): string;
//Создание BlowFish пароля
function GenBfPassword(PathToKey: string): string;
//Шифрование BlowFish
function EncryptFileBf(PathToKeyOrKeyStr, OriginalFile, EncryptedFile: string): string;
function DecryptFileBf(PathToKeyOrKeyStr, OriginalFile, DecryptedFile: string): string;
//Base64
function Base64Encode(PathToFile, EncodedFile: string): string;
function Base64Decode(PathToFile, DecodedFile: string): string;
//Создание RSA ключей
function GenRsaPrivateKey(PathToKey: string; iSize: integer): string;
function GenRsaPublicKey(PathToPrivKey, PathToPubKey: string): string;
function GenRsaKeys(PathToPrivKey, PathToPubKey: string;
iSize: integer): string;
//Шифровка и Расшифровка RSA
function EncryptFile(PathToPubKey, OriginalFile, EncryptedFile: string): string;
function DecryptFile(PathToPrivKey, CipheredFile, DecodeFile: string): string;
//Получение почты Pop3
function Pop3Login(AHost, ALogin, APassword: string): boolean;
function Pop3Count: integer; // Количество писем
function GetMail(Index: integer): string; // Получить исходник письма
function GetCountSection(Mail: string): integer; // Получить количество секций
function GetSection(Mail: string; Index: integer): string;
// Получить секцию полностью
function GetSectionHead(Mail: string; Index: integer): string;
// Заголовок секции
function GetSectionBody(Mail: string; Index: integer): string; // Текст секции
// Сохранение вложения
function GetSectionFileName(Mail: string; Index: integer): string;
// Имя файла, если это вложение
function SaveSectionToFile(FileName: string; Mail: string; Index: integer): boolean;
// Сохранение в файла
function SaveSectionToMemoryStream(MemStream: TMemoryStream;
Mail: string; Index: integer): boolean; // Сохранение в памяти
// Отправка почты
function SendMail(pSubject, pTextBody, pHTMLBody: string; Files: TStrings): boolean;
function KeySend(EMail: string): boolean; // ???????????
published
property HostPop3: string read fHostPop3 write fHostPop3;
property HostSmtp: string read fHostSmtp write fHostSmtp;
end;
implementation
{ TCustomCrypt }
constructor TCustomCrypt.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Pop3 := TPOP3Send.Create;
MailMessage := TMimeMess.Create;
//UserDB := TUserList.Create (nil);
end;
destructor TCustomCrypt.Destroy;
begin
Pop3.Free;
MailMessage.Free;
inherited Destroy;
end;
function TCustomCrypt.RunApp(Command: string): string;
begin
Result := RunApp(Command, False);
end;
function TCustomCrypt.RunApp(Command: string; NoEchoCmd: boolean): string;
const
READ_BYTES = 2048;
var
S: TStringList;
M: TMemoryStream;
P: TProcess;
n: longint;
BytesRead: longint;
begin
M := TMemoryStream.Create;
BytesRead := 0;
P := TProcess.Create(nil);
P.CommandLine := Command;
{$IFDEF UNIX}
P.Options := [poUsePipes, poStderrToOutPut];
{$ENDIF UNIX}
{$IFDEF WINDOWS}
P.Options := [poUsePipes, poStderrToOutPut, poNoConsole];
{$ENDIF WINDOWS}
P.Execute;
while P.Running do
begin
M.SetSize(BytesRead + READ_BYTES);
n := P.Output.Read((M.Memory + BytesRead)^, READ_BYTES);
if n > 0 then
Inc(BytesRead, n)
else
Sleep(100);
end;
repeat
M.SetSize(BytesRead + READ_BYTES);
n := P.Output.Read((M.Memory + BytesRead)^, READ_BYTES);
if n > 0 then
Inc(BytesRead, n);
until n <= 0;
M.SetSize(BytesRead);
S := TStringList.Create;
S.LoadFromStream(M);
if NoEchoCmd then
Result := S.Text
else
begin
if S.Text <> '' then
Result := Command + #13 + #10 + #13 + #10 + S.Text
else
Result := Command;
end;
S.Free;
P.Free;
M.Free;
end;
function TCustomCrypt.RunApp(Command, FileToSave: string): string;
const
READ_BYTES = 2048;
var
MemoryStream: TMemoryStream;
Process: TProcess;
n: longint;
BytesRead: longint;
begin
MemoryStream := TMemoryStream.Create;
BytesRead := 0;
Process := TProcess.Create(nil);
Process.CommandLine := Command;
Process.Options := [poUsePipes, poStderrToOutPut];
Process.Execute;
while Process.Running do
begin
MemoryStream.SetSize(BytesRead + READ_BYTES);
n := Process.Output.Read((MemoryStream.Memory + BytesRead)^, READ_BYTES);
if n > 0 then
Inc(BytesRead, n)
else
Sleep(10);
end;
repeat
MemoryStream.SetSize(BytesRead + READ_BYTES);
n := Process.Output.Read((MemoryStream.Memory + BytesRead)^, READ_BYTES);
if n > 0 then
Inc(BytesRead, n);
until n <= 0;
MemoryStream.SetSize(BytesRead);
Result := Command;
MemoryStream.Position := 0;
MemoryStream.SaveToFile(FileToSave);
Process.Free;
MemoryStream.Free;
end;
function TCustomCrypt.MakeBz2(DirPath, SavedName: string): string;
begin
{$IFDEF UNIX}
Result := RunApp('tar cjf ' + SavedName + ' ' + DirPath);
{$ENDIF UNIX}
{$IFDEF WINDOWS}
Result := RunApp(ExtractFilePath(ParamStr(0))+'tar.exe -cjf ' + SavedName + ' ' + DirPath);
{$ENDIF WINDOWS}
end;
function TCustomCrypt.ExtractBz2(FileName, DirPath: string): string;
begin
{$IFDEF UNIX}
Result := RunApp('tar xjf ' + FileName + ' -C ' + DirPath);
{$ENDIF UNIX}
{$IFDEF WINDOWS}
Result := RunApp(ExtractFilePath(ParamStr(0))+'tar.exe -xjf ' + FileName + ' -C ' + DirPath);
{$ENDIF WINDOWS}
end;
function TCustomCrypt.GenBfPassword(PathToKey: string): string;
var
Res: HResult;
Uid: TGuid;
hFile: TextFile;
begin
Result := '';
Res := CreateGUID(Uid);
if Res = S_OK then
begin
Result := GUIDToString(Uid);
if PathToKey <> '' then
begin
AssignFile(hFile, PathToKey);
Rewrite(hFile);
Write(hFile, Result);
CloseFile(hFile);
end;
end;
end;
function TCustomCrypt.EncryptFileBf(PathToKeyOrKeyStr, OriginalFile,
EncryptedFile: string): string;
var
szKey: string;
hFile: TextFile;
begin
if FileExists(PathToKeyOrKeyStr) then
begin
AssignFile(hFile, PathToKeyOrKeyStr);
Reset(hFile);
Read(hFile, szKey);
CloseFile(hFile);
end
else
szKey := PathToKeyOrKeyStr;
{$IFDEF UNIX}
Result := RunApp('/usr/bin/openssl bf -a -in ' + OriginalFile +
' -out ' + EncryptedFile + ' -pass pass:' + szKey);
{$ENDIF UNIX}
{$IFDEF WINDOWS}
Result := RunApp(ExtractFilePath(ParamStr(0))+'openssl.exe bf -a -in ' + OriginalFile +
' -out ' + EncryptedFile + ' -pass pass:' + szKey);
{$ENDIF WINDOWS}
end;
function TCustomCrypt.DecryptFileBf(PathToKeyOrKeyStr, OriginalFile,
DecryptedFile: string): string;
var
szKey: string;
hFile: TextFile;
begin
if FileExists(PathToKeyOrKeyStr) then
begin
AssignFile(hFile, PathToKeyOrKeyStr);
Reset(hFile);
Read(hFile, szKey);
CloseFile(hFile);
end
else
szKey := PathToKeyOrKeyStr;
{$IFDEF UNIX}
Result := RunApp('/usr/bin/openssl bf -a -d -in ' + OriginalFile +
' -out ' + DecryptedFile + ' -pass pass:' + szKey);
{$ENDIF UNIX}
{$IFDEF WINDOWS}
Result := RunApp(ExtractFilePath(ParamStr(0))+'openssl.exe bf -a -d -in ' + OriginalFile +
' -out ' + DecryptedFile + ' -pass pass:' + szKey);
{$ENDIF WINDOWS}
end;
// Закодировать в Base64
function TCustomCrypt.Base64Encode(PathToFile, EncodedFile: string): string;
{$IFDEF UNIX}
var
hFile: TextFile;
{$ENDIF UNIX}
begin
{$IFDEF UNIX}
Result := trim(RunApp('/usr/bin/base64 ' + PathToFile, True));
AssignFile(hFile, EncodedFile);
Rewrite(hFile);
Write(hFile, Result);
CloseFile(hFile);
{$ENDIF UNIX}
{$IFDEF WINDOWS}
Result := trim(RunApp(ExtractFilePath(ParamStr(0))+'base64.exe -e ' + PathToFile + ' ' + EncodedFile, True));
{$ENDIF WINDOWS}
end;
// Раскодировать в Base64
function TCustomCrypt.Base64Decode(PathToFile, DecodedFile: string): string;
begin
{$IFDEF UNIX}
Result := RunApp('/usr/bin/base64 -d ' + PathToFile, DecodedFile);
{$ENDIF UNIX}
{$IFDEF WINDOWS}
Result := trim(RunApp(ExtractFilePath(ParamStr(0))+'base64.exe -d ' + PathToFile + ' ' + DecodedFile, True));
{$ENDIF WINDOWS}
end;
function TCustomCrypt.GenRsaPrivateKey(PathToKey: string; iSize: integer): string;
begin
// Создание приватного ключа, параметры:
// PathToKey - Путь к сохранению сгенирированного ключа, iSize - размер ключа
{$IFDEF UNIX}
Result := RunApp('/usr/bin/openssl genrsa -out ' + PathToKey +
' ' + IntToStr(iSize));
{$ENDIF UNIX}
{$IFDEF WINDOWS}
Result := RunApp(ExtractFilePath(ParamStr(0))+'openssl.exe genrsa -out ' + PathToKey +
' ' + IntToStr(iSize));
{$ENDIF WINDOWS}
end;
function TCustomCrypt.GenRsaPublicKey(PathToPrivKey, PathToPubKey: string): string;
begin
// Создание публичного ключа на основе приватного, параметры:
// PathToPrivKey - Путь к уже существующему файлу приватного ключа
// PathToPubKey - Путь включая имя файла к сохранению нового открытого ключа
{$IFDEF UNIX}
Result := RunApp('/usr/bin/openssl rsa -in ' + PathToPrivKey +
' -pubout -out ' + PathToPubKey);
{$ENDIF UNIX}
{$IFDEF WINDOWS}
Result := RunApp(ExtractFilePath(ParamStr(0))+'openssl.exe rsa -in ' + PathToPrivKey +
' -pubout -out ' + PathToPubKey);
{$ENDIF WINDOWS}
end;
function TCustomCrypt.GenRsaKeys(PathToPrivKey, PathToPubKey: string;
iSize: integer): string;
begin
//Генерация пары ключей
Result := GenRsaPrivateKey(PathToPrivKey, iSize);
Result := Result + GenRsaPublicKey(PathToPrivKey, PathToPubKey);
end;
function TCustomCrypt.EncryptFile(PathToPubKey, OriginalFile, EncryptedFile:
string): string;
begin
// ШИФРОВАНИЕ RSA, параметры:
// PathToPubKey - Путь к чужому открытому ключу
// OriginalFile - Путь к оригинальному файлу
// EncryptedFile - Путь для сохранения зашифрованного файла
{$IFDEF UNIX}
Result := RunApp('/usr/bin/openssl rsautl -inkey ' + PathToPubKey +
' -in ' + OriginalFile + ' -out ' + EncryptedFile + ' -pubin -encrypt');
{$ENDIF UNIX}
{$IFDEF WINDOWS}
Result := RunApp(ExtractFilePath(ParamStr(0))+'openssl.exe rsautl -inkey ' + PathToPubKey +
' -in ' + OriginalFile + ' -out ' + EncryptedFile + ' -pubin -encrypt');
{$ENDIF WINDOWS}
end;
function TCustomCrypt.DecryptFile(PathToPrivKey, CipheredFile, DecodeFile: string): string;
begin
// РАСШИФРОВКА RSA, параметры:
// PathToPrivKey - Путь к своему закрытому ключу
// CipheredFile - Путь к зашифрованному файлу
// DecodeFile - Путь и имя файла для записи расшифровки
{$IFDEF UNIX}
Result := RunApp('/usr/bin/openssl rsautl -inkey ' + PathToPrivKey +
' -in ' + CipheredFile + ' -out ' + DecodeFile + ' -decrypt');
{$ENDIF UNIX}
{$IFDEF WINDOWS}
Result := RunApp(ExtractFilePath(ParamStr(0))+'openssl.exe rsautl -inkey ' + PathToPrivKey +
' -in ' + CipheredFile + ' -out ' + DecodeFile + ' -decrypt');
{$ENDIF WINDOWS}
end;
{ TODO : Нет настроек подключения к почтовому серверу =( }
function TCustomCrypt.Pop3Login(AHost, ALogin, APassword: string): boolean;
begin
Result := False;
Pop3.TargetHost := AHost;
Pop3.UserName := ALogin;
Pop3.Password := APassword;
if Pop3.Login then
begin
Result := True;
fHostPop3 := AHost;
fLogin := ALogin;
fPassword := APassword;
end
else
raise Exception.Create('Соединение не удалось. Проверьте логин/пароль/порт.');
end;
function TCustomCrypt.Pop3Count: integer;
begin
if Pop3.Stat then
Result := Pop3.StatCount
else
Result := -1;
end;
function TCustomCrypt.GetMail(Index: integer): string;
begin
if Pop3.Retr(Index) then
Result := Pop3.FullResult.Text
else
Result := 'Error';
end;
function TCustomCrypt.GetCountSection(Mail: string): integer;
begin
with MailMessage do
begin
Lines.Text := Mail;
DecodeMessage;
Result := MessagePart.GetSubPartCount;
end;
end;
function TCustomCrypt.GetSection(Mail: string; Index: integer): string;
begin
with MailMessage do
begin
Lines.Text := Mail;
DecodeMessage;
if (Index < 0) or (Index > MessagePart.GetSubPartCount) then
Result := ''
else
try
MessagePart.GetSubPart(Index).PartBody.Text :=
DecodeBase64(MessagePart.GetSubPart(Index).PartBody.Text);
Result := MessagePart.GetSubPart(Index).Lines.Text;
finally
end;
end;
end;
function TCustomCrypt.GetSectionHead(Mail: string; Index: integer): string;
begin
with MailMessage do
begin
Lines.Text := Mail;
DecodeMessage;
if (Index < 0) or (Index > MessagePart.GetSubPartCount) then
Result := ''
else
try
Result := MessagePart.GetSubPart(Index).Headers.Text;
finally
end;
end;
end;
function TCustomCrypt.GetSectionBody(Mail: string; Index: integer): string;
begin
with MailMessage do
begin
Lines.Text := Mail;
DecodeMessage;
if (Index < 0) or (Index > MessagePart.GetSubPartCount) then
Result := ''
else
try
Result := MessagePart.GetSubPart(Index).PartBody.Text;
finally
end;
end;
end;
function TCustomCrypt.GetSectionFileName(Mail: string; Index: integer): string;
begin
with MailMessage do
begin
Lines.Text := Mail;
DecodeMessage;
if (Index < 0) or (Index > MessagePart.GetSubPartCount) then
Result := ''
else
try
Result := MessagePart.GetSubPart(Index).FileName;
finally
end;
end;
end;
function TCustomCrypt.SaveSectionToFile(FileName: string; Mail: string;
Index: integer): boolean;
begin
with MailMessage do
begin
Lines.Text := Mail;
DecodeMessage;
if (Index < 0) or (Index > MessagePart.GetSubPartCount) then
Result := False
else
try
if FileName <> '' then
begin
// Расшифрованная секция
MessagePart.GetSubPart(Index).PartBody.Text :=
DecodeBase64(MessagePart.GetSubPart(Index).PartBody.Text);
MessagePart.GetSubPart(Index).PartBody.SaveToFile(FileName); // Сохранение
Result := True;
end
else
Result := False;
except
Result := False;
end;
end;
end;
function TCustomCrypt.SaveSectionToMemoryStream(MemStream: TMemoryStream;
Mail: string; Index: integer): boolean;
begin
with MailMessage do
begin
Lines.Text := Mail;
DecodeMessage;
if (Index < 0) or (Index > MessagePart.GetSubPartCount) then
Result := False
else
try
// Расшифрованная секция
MessagePart.GetSubPart(Index).PartBody.Text :=
DecodeBase64(MessagePart.GetSubPart(Index).PartBody.Text);
MessagePart.GetSubPart(Index).PartBody.SaveToStream(MemStream); // Сохранение
Result := True;
except
Result := False;
end;
end;
end;
function TCustomCrypt.SendMail(pSubject, pTextBody, pHTMLBody: string;
Files: TStrings): boolean;
var
tmpMsg: TMimeMess;
tmpStringList: TStringList;
tmpMIMEPart: TMimePart;
fItem: string;
begin
tmpMsg := TMimeMess.Create;
tmpStringList := TStringList.Create;
Result := False;
try
// Headers
tmpMsg.Header.Subject := pSubject;
tmpMsg.Header.From := fLogin;
tmpMsg.Header.ToList.Add(fFriendMail);
// MIMe Parts
tmpMIMEPart := tmpMsg.AddPartMultipart('alternate', nil);
if length(pTextBody) > 0 then
begin
tmpStringList.Text := pTextBody;
tmpMsg.AddPartText(tmpStringList, tmpMIMEPart);
end
else
begin
tmpStringList.Text := pHTMLBody;
tmpMsg.AddPartHTML(tmpStringList, tmpMIMEPart);
end;
for fItem in Files do
tmpMsg.AddPartBinaryFromFile(fItem, tmpMIMEPart);
// кодируем и отправляем
tmpMsg.EncodeMessage;
Result := smtpsend.SendToRaw(fLogin, fFriendMail, fHostSmtp,
tmpMsg.Lines, fLogin, fPassword);
finally
tmpMsg.Free;
tmpStringList.Free;
end;
end;
{ TODO : Проверить целеособразность процедуры KeySend }
function TCustomCrypt.KeySend(EMail: string): boolean;
var
Files: TStringList;
begin
Result := False;
try
fFriendMail := EMail;
Files := TStringList.Create;
Files.Append('privXID.pem');
Files.Append('pubXID.pem');
GenRsaKeys(Files[0], Files[1], 1024);
SendMail('{86AE072A-941F-408A-BD99-4C2E4845C291}',
'{65E5DFD8-AED9-4A8F-B2EE-F780373AC3B1}', '',
Files);
finally
Files.Free;
Result := True;
end;
end;
end.
|
unit Test_FIToolkit.Config.Storage;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework,
FIToolkit.Config.Storage;
type
// Test methods for class TConfigFile
TestTConfigFile = class(TGenericTestCase)
private
const
STR_INI_SECTION = 'TestSection';
STR_INI_PARAM = 'TestParam';
INT_INI_VALUE = 777;
strict private
FConfigFile : TConfigFile;
private
function CreateConfigFile(CurrentTest : Pointer) : TConfigFile;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestAfterConstruction;
procedure TestCreate;
procedure TestLoad;
procedure TestSave;
end;
implementation
uses
System.SysUtils, System.IniFiles,
TestUtils;
function TestTConfigFile.CreateConfigFile(CurrentTest : Pointer) : TConfigFile;
var
sFileName : TFileName;
begin
Result := nil;
sFileName := GetTestIniFileName;
if CurrentTest = @TestTConfigFile.TestSave then
Result := TConfigFile.Create(sFileName, True)
else
if (CurrentTest = @TestTConfigFile.TestAfterConstruction) or (CurrentTest = @TestTConfigFile.TestLoad) then
begin
with TMemIniFile.Create(sFileName, TEncoding.UTF8) do
try
WriteInteger(STR_INI_SECTION, STR_INI_PARAM, INT_INI_VALUE);
UpdateFile;
finally
Free;
end;
Result := TConfigFile.Create(sFileName, False);
end;
end;
procedure TestTConfigFile.SetUp;
begin
FConfigFile := CreateConfigFile(GetCurrTestMethodAddr);
end;
procedure TestTConfigFile.TearDown;
var
S : String;
begin
if Assigned(FConfigFile) then
begin
S := FConfigFile.FileName;
FreeAndNil(FConfigFile);
DeleteFile(S);
end;
end;
procedure TestTConfigFile.TestAfterConstruction;
begin
FConfigFile.AfterConstruction;
CheckTrue(FConfigFile.Config.SectionExists(STR_INI_SECTION), 'CheckTrue::SectionExists');
end;
procedure TestTConfigFile.TestCreate;
var
sFileName : TFileName;
Cfg : TConfigFile;
begin
sFileName := GetTestIniFileName;
{ File not exists / Can't create }
Cfg := nil;
try
DeleteFile(sFileName);
CheckException(
procedure
begin
Cfg := TConfigFile.Create(sFileName, False);
end,
nil,
'CheckException::nil<NotExists,NotWritable>'
);
CheckFalse(FileExists(sFileName), 'CheckFalse::FilexExists<NotExists,NotWritable>');
CheckFalse(Cfg.HasFile, 'CheckFalse::HasFile<NotExists,NotWritable>');
CheckTrue(String.IsNullOrEmpty(Cfg.FileName), 'CheckTrue::Cfg.FileName.IsEmpty');
finally
if Assigned(Cfg) then
Cfg.Free;
end;
{ File not exists / Can create }
Cfg := nil;
try
DeleteFile(sFileName);
CheckException(
procedure
begin
Cfg := TConfigFile.Create(sFileName, True);
end,
nil,
'CheckException::nil<NotExists,Writable>'
);
CheckTrue(FileExists(sFileName), 'CheckTrue::FileExists<NotExists,Writable>');
CheckTrue(Cfg.HasFile, 'CheckTrue::HasFile<NotExists,Writable>');
CheckEquals(sFileName, Cfg.FileName, '(Cfg.FileName = sFileName)::<NotExists,Writable>');
finally
if Assigned(Cfg) then
Cfg.Free;
end;
{ File exists / Not writable }
Cfg := nil;
try
Assert(FileExists(sFileName));
CheckException(
procedure
begin
Cfg := TConfigFile.Create(sFileName, False);
end,
nil,
'CheckException::nil<Exists,NotWritable>'
);
CheckTrue(Cfg.HasFile, 'CheckTrue::HasFile<Exists,NotWritable>');
CheckEquals(sFileName, Cfg.FileName, '(Cfg.FileName = sFileName)::<Exists,NotWritable>');
finally
if Assigned(Cfg) then
Cfg.Free;
end;
{ File exists / Writable }
Cfg := nil;
try
Assert(FileExists(sFileName));
CheckException(
procedure
begin
Cfg := TConfigFile.Create(sFileName, True);
end,
nil,
'CheckException::nil<Exists,Writable>'
);
CheckTrue(Cfg.HasFile, 'CheckTrue::HasFile<Exists,Writable>');
CheckEquals(sFileName, Cfg.FileName, '(Cfg.FileName = sFileName)::<Exists,Writable>');
finally
if Assigned(Cfg) then
Cfg.Free;
end;
end;
procedure TestTConfigFile.TestLoad;
var
ReturnValue: Boolean;
begin
ReturnValue := FConfigFile.Load;
CheckTrue(ReturnValue, 'CheckTrue::ReturnValue');
CheckEquals(INT_INI_VALUE, FConfigFile.Config.ReadInteger(STR_INI_SECTION, STR_INI_PARAM, 0),
'Config.ReadInteger = INT_INI_VALUE');
end;
procedure TestTConfigFile.TestSave;
var
ReturnValue: Boolean;
begin
FConfigFile.Config.WriteInteger(STR_INI_SECTION, STR_INI_PARAM, INT_INI_VALUE);
ReturnValue := FConfigFile.Save;
CheckTrue(ReturnValue, 'CheckTrue::ReturnValue');
with TMemIniFile.Create(CloneFile(FConfigFile.FileName), TEncoding.UTF8) do
try
CheckEquals(INT_INI_VALUE, ReadInteger(STR_INI_SECTION, STR_INI_PARAM, 0),
'TMemIniFile.ReadInteger = INT_INI_VALUE');
finally
Free;
end;
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTConfigFile.Suite);
end.
|
unit Security4D.UnitTest.Car;
interface
uses
Security4D.Aspect,
Security4D.UnitTest.Credential;
type
TCar = class
private
fAction: string;
protected
{ protected declarations }
public
[RequiredPermission('Car', 'Insert')]
procedure Insert; virtual;
[RequiredPermission('Car', 'Update')]
procedure Update; virtual;
[RequiredPermission('Car', 'Delete')]
procedure Delete; virtual;
[RequiredRole(ROLE_ADMIN)]
[RequiredRole(ROLE_MANAGER)]
[RequiredRole(ROLE_NORMAL)]
procedure View; virtual;
property Action: string read fAction;
end;
implementation
{ TCar }
procedure TCar.Delete;
begin
fAction := 'Car Deleted';
end;
procedure TCar.Insert;
begin
fAction := 'Car Inserted';
end;
procedure TCar.Update;
begin
fAction := 'Car Updated';
end;
procedure TCar.View;
begin
fAction := 'Car Viewed';
end;
end.
|
unit FileListing;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
StdCtrls, ExtCtrls;
type
TFileType =({ftDirectory,}ftArchive,ftReadonly,
ftSystem,ftHidden,{ftCompressed,}ftTemporary,ftAll);
TFileTypes = Set of TFileType;
TFileObject = class
Name,FType : string;
Date : TDateTime;
Size,
ImgIndex,
Attr : integer;
end;
TFileSortType = (fsNone,fsName,fsSize,fsDate,fsType);
TFileListing = class(TList)
Directory : string;
DirBytes : integer;
DefaultSort : TFileSortType;
Ascend : boolean;
FileTypes : TFileTypes;
function GetFiles(Dir,Mask : string) : integer;
function FileName(index:integer):string;
function FullName(index:integer):string;
procedure ClearList;
procedure SortFiles(SortType:TFileSortType; Ascend:boolean);
Destructor Destroy; Override;
end;
function AddSlash(Const Path : String) : String;
function CommaStr(N : Longint) : String;
implementation
uses
ShellApi,
MaskSearch;
Var
AscendSort : boolean;
function CommaStr(N : Longint) : String;
Var
S : String;
r : single;
Begin
r := N;
FmtStr(s,'%.0n',[r]);
result := s;
End;
function AddSlash(Const Path : String) : String;
begin
if Path[Length(Path)] = '\' then
result := Path else result := Path + '\';
end;
function ValidNumber(const S: string; var V: extended): boolean;
var
NumCode: integer;
begin
Val(S, V, NumCode);
Result := (NumCode = 0);
end;
function ValidDate(const S: string; var D: TDateTime): boolean;
begin
try
D := StrToDate(S);
Result := TRUE;
except
D := 0;
Result := FALSE;
end;
end;
function CompareInt(I1,I2 : integer) : integer;
begin
if I1 > I2 then result := 1 else
if I1 < I2 then result := -1 else
Result := 0;
end;
function NameSort(item1,item2:pointer) : integer;
begin
Result := AnsiCompareText(TFileObject(item1).name,
TFileObject(item2).name);
if not AscendSort then Result := -Result;
end;
function DateSort(item1,item2:pointer) : integer;
begin
if TFileObject(item1).date > TFileObject(item2).date then
result := 1 else if
TFileObject(item1).date < TFileObject(item2).date then
result := -1 else result := 0;
// Result := CompareInt(TFileObject(item1).date,
// TFileObject(item2).date);
if not AscendSort then Result := -Result;
end;
function SizeSort(item1,item2:pointer) : integer;
begin
Result := CompareInt(TFileObject(item1).size,
TFileObject(item2).size);
if not AscendSort then Result := -Result;
end;
function TypeSort(item1,item2:pointer) : integer;
begin
Result := AnsiCompareText(TFileObject(item1).FType,TFileObject(item2).FType);
if not AscendSort then Result := -Result;
end;
function TFileListing.FileName(index:integer):string;
var
Fo : TfileObject;
begin
Fo := TFileObject(items[index]);;
result := Fo.name;
end;
function TFileListing.FullName(index:integer):string;
var
Fo : TFileObject;
begin
Fo := TFileObject(items[index]);
result := AddSlash(Directory)+Fo.name;
end;
procedure TFileListing.SortFiles(SortType:TFileSortType; ascend : boolean);
begin
AscendSort := Ascend;
case SortType of
fsName : Sort(NameSort);
fsDate : Sort(DateSort);
fsSize : Sort(SizeSort);
fsType : Sort(TypeSort);
end;
//
end;
procedure TFileListing.ClearList;
var
i : integer;
Fo : TfileObject;
begin
for i := 0 to count-1 do
begin
Fo := TFileObject(items[i]);
SetLength(Fo.Name,0);
Fo.Free;
end;
Clear;
end;
function TFileListing.GetFiles(Dir,Mask : string) : integer;
var
Rslt : integer;
rec : TSearchRec;
Fobj : TFileObject;
MaskList : TStringList;
function GetImageIndex(const Filename: String): Integer;
var
Fileinfo: TSHFileInfo;
begin
if SHGetFileInfo(PChar(FileName), 0, Fileinfo,
sizeof(TSHFileInfo),
SHGFI_ICON or SHGFI_SYSICONINDEX or SHGFI_USEFILEATTRIBUTES) <> 0 then
begin
Result := Fileinfo.IIcon;
end else Result := 0;
end;
function GetFileType(const Filename: String): string;
var
Fileinfo: TSHFileInfo;
begin
Result := '';
if SHGetFileInfo(PChar(FileName),0,Fileinfo,sizeof(TSHFileInfo),
SHGFI_USEFILEATTRIBUTES or SHGFI_TYPENAME) <> 0 then
begin
Result := FileInfo.szTypeName;
end else Result := '';
end;
begin
Count := 0;
Directory := Dir;
DirBytes := 0;
ClearList;
MaskList := TstringList.create;
SetFilters(Mask,MaskList,true);
Rslt := FindFirst(AddSlash(Dir)+'*.*',faAnyFile,Rec);
While Rslt = 0 do with Rec do
begin
if (Name[1] <> '.') and
(Attr and faDirectory <> faDirectory) and
CmpMask(Name,MaskList,true) then
begin
Fobj := TFileObject.Create;
Fobj.Name := Name;
Fobj.Size := Size;
Fobj.Date := FileDateToDateTime(Time);
Fobj.Attr := Attr;
// We'll only get the image index when the listview asks to paint it.
Fobj.ImgIndex := -1; // GetImageIndex(AddBackSlash(Dir)+Name);
// We have to get this now or sorting won't work.
Fobj.FType := GetFileType(Dir+'\'+Name);
Add(Fobj);
Inc(DirBytes,Size);
end;
Rslt := FindNext(Rec);
end;
FindClose(Rec);
Result := Count;
MaskList.Free;
end;
destructor TFileListing.Destroy;
begin
SetLength(Directory,0);
ClearList;
inherited Destroy;
end;
function CheckAttributes(Att :DWord; Typ :TFileTypes) :boolean;
begin
if not (ftAll in Typ) then
begin
Result := true;
if (Att and file_attribute_Archive) = file_attribute_Archive then
Result := Result and (ftArchive in Typ);
if (Att and file_attribute_Readonly) = file_attribute_Readonly then
Result := Result and (ftArchive in Typ);
if (Att and file_attribute_Hidden) = file_attribute_Hidden then
Result := Result and (ftHidden in Typ);
if (Att and file_attribute_System) = file_attribute_System then
Result := Result and (ftSystem in Typ);
if (Att and file_attribute_Temporary) = file_attribute_Temporary then
Result := Result and (ftTemporary in Typ);
end
else
Result := true; // ftAll allows any file
end;
END.
|
unit uCommon;
interface
const
// Статы
ST_SPEED = 1;
ST_SNEAK = 2;
ST_FIGHT = 3;
ST_WILL = 4;
ST_LORE = 5;
ST_LUCK = 6;
// Константы фаз
PH_UPKEEP = 1;
PH_MOVE = 2;
PH_ENCOUNTER = 3;
PH_OTHER_WORLDS_ENCOUNTER = 4;
PH_MYTHOS = 5;
// Константы Типов Карт
CT_WEAPON = 9; // Оружие
CT_TOME = 10; // Книга
CT_SPELL = 3; // Заклинание
CT_SKILL = 4; // Навык
CT_ALLY = 7; // Союзник
CT_MYTHOS = 8; // Миф
CT_COMMON_ITEM = 1; // Простые предметы (первая цифра в ID)
CT_UNIQUE_ITEM = 2; // Уникальные предметы (первая цифра в ID)
CT_ENCOUNTER = 6; // Контакт (первая цифра в ID)
CT_OW_ENCOUNTER = 7; // Контакт иного мира (первая цифра в ID)
CT_INVESTIGATOR = 9;
COMMON_ITEM_WEAPON = 1; // Оружие
COMMON_ITEM_TOME = 2; // Книга
GT_CIRCLE = 1;
GT_CRESCENT = 2;
GT_DIAMOND = 3;
GT_HEXAGON = 4;
GT_PLUS = 5;
GT_SLASH = 6;
GT_SQUARE = 7;
GT_STAR = 8;
GT_TRIANGLE = 9;
// Константы Действий
AT_SPEC = 2;
AT_WATCH_BUY = 3;
// Константы для формы торговли
TR_TAKE_ITEMS = 1;
TR_TAKE_REST_DISCARD = 2;
TR_BUY_NOM_PRICE = 3;
TR_BUY_ONE_ABOVE = 4;
TR_BUY_ONE_BELOW = 5;
TR_TAKE_FIRST = 6;
TR_TAKE_COMMON_TOME = 7;
TR_TAKE_UNIQUE_OTEM = 8;
TR_BUY_ANY_ONE_ABOVE = 9;
TR_BUY_ANY_ONE_BELOW = 10;
// Основные константы
NUMBER_OF_STREETS = 19;
NUMBER_OF_LOCATIONS = 57;
NUMBER_OF_OW_LOCATIONS = 16;
NUMBER_OF_COMMON_CARDS = 59;
NUMBER_OF_UNIQUE_CARDS = 83;
NUMBER_OF_ENCOUNTER_CARDS = 20;
NUMBER_OF_OW_ENCOUNTER_CARDS = 50;
NUMBER_OF_MYTHOS_CARDS = 30;
NUMBER_OF_INVESTIGATORS = 49;
//LOCATION_CARD_NUMBER = 20; // Число карт на каждую локацию
//COMMON_ITEMS_CARD_NUMBER = 30;
//
//MYTHOS_CARDS_NUMBER = 30;
// Colors
CC_BLUE = 1;
CC_GREEN = 2;
CC_RED = 3;
CC_YELLOW = 4;
CC_WHITE = 5;
MAX_PLAYER_ITEMS = 20;
MONSTER_MAX = 50;
MONSTER_MAX_ON_LOK = 30;
ALLIES_MAX = 50;
//COMMON_ITEMS_MAX = 100;
aStats: array [1..6] of string = ('Скорость', 'Скрытность', 'Битва', 'Воля', 'Знание', 'Удача');
aPhasesNames: array [1..5] of string = ('UPKEEP', 'MOVE', 'ENCOUNTER', 'OTHER WORLDS ENCOUNTER', 'MYTHOS');
aNeighborhoodsNames: array [1..NUMBER_OF_STREETS, 1..2] of string = (
('1000', 'Northside'),
('2000', 'Downtown'),
('3000', 'Easttown'),
('4000', 'Rivertown'),
('5000', 'Merchant District'),
('6000', 'French Hill'),
('7000', 'Miskatonic University'),
('8000', 'Southside'),
('9000', 'Uptown'),
('0000', 'Backwoods Country'),
('0000', 'Blasted Heath'),
('0000', 'Central Hill'),
('0000', 'Church Green'),
('0000', 'Factory District'),
('0000', 'Harborside'),
('0000', 'Innsmouth Shore'),
('0000', 'Kingsport Head'),
('0000', 'South Shore'),
('0000', 'Village Common'));
aLocationsNames: array [1..NUMBER_OF_LOCATIONS, 1..2] of string = (
('011', '607 Water St.'),
('012', '7th House on the Left'),
('7100', 'Administration Building'),
('2100', 'Arkham Asylum'),
('011', 'Artists'' Colony'),
('2200', 'Bank of Arkham'),
('011', 'Bishop''s Brook Bridge'),
('4100', 'Black Cave'),
('011', 'Cold Spring Glen'),
('011', 'Congregational Hospital'),
('1100', 'Curiositie Shoppe'),
('011', 'Darke''s Carnival'),
('011', 'Devil Reef'),
('011', 'Devil''s Hopyard'),
('011', 'Dunwich Village'),
('011', 'Esoteric Order of Dagon'),
('011', 'Falcon Point'),
('011', 'First National Grocery'),
('011', 'Gardners'' Place'),
('4200', 'General Store'),
('011', 'Gilman House Hotel'),
('4300', 'Graveyard'),
('011', 'Hall School'),
('011', 'Harney Jones'' Shack'),
('3100', 'Hibb''s Roadhouse'),
('8100', 'Historical Society'),
('2300', 'Independence Square'),
('6200', 'Inner Sanctum'),
('011', 'Innsmouth Jail'),
('011', 'Jail Cell'),
('7200', 'Library'),
('8200', 'Ma''s Boarding House'),
('011', 'Marsh Refinery'),
('011', 'Neil''s Curiosity Shop'),
('1200', 'Newspaper'),
('011', 'North Point Lighthouse'),
('3200', 'Police Station'),
('5100', 'River Docks'),
('7300', 'Science Building'),
('6100', 'Silver Twilight Lodge'),
('8300', 'South Church'),
('011', 'St. Erasmus''s Home'),
('9100', 'St. Mary''s Hospital'),
('011', 'Strange High House'),
('011', 'The Causeway'),
('011', 'The Rope and Anchor'),
('5200', 'The Unnamable'),
('6300', 'The Witch House'),
('1300', 'Train Station'),
('5300', 'Unvisited Isle'),
('3300', 'Velma''s Diner'),
('011', 'Whateley Farm'),
('011', 'Wireless Station'),
('011', 'Wizard''s Hill'),
('9200', 'Woods'),
('011', 'Y''ha-nthlei'),
('9300', 'Ye Olde Magick Shoppe'));
aOtherWorldsNames: array [1..NUMBER_OF_OW_LOCATIONS, 1..2] of string = (
('111', 'Р''лиех. Начало'),
('112', 'Р''лиех. Конец'),
('121', 'Плато Лэнг. Начало'),
('122', 'Плато лэнг. Конец'),
('131', 'Страна снов. Начало'),
('132', 'Страна снов. Конец'),
('141', 'Великий зал целено. Начало'),
('142', 'Великиц зал целено. Конец'),
('151', 'Юггот. Начало'),
('152', 'Юггот. Конец'),
('161', 'Город великой расы. Начало'),
('162', 'Город великой расы. Конец'),
('171', 'Бездна. Начало'),
('172', 'Бездна. Конец'),
('181', 'Другое измерение. Начало'),
('182', 'Другое измерение. Конец'));
aEncounterSymbols: array [1..8, 1..6] of integer = (
(111, 0, 0, CC_RED, CC_YELLOW, 0),
(121, 0, CC_GREEN, CC_RED, 0, 0),
(131, CC_BLUE, CC_GREEN, CC_RED, CC_YELLOW, 0),
(141, CC_BLUE, CC_GREEN, 0, 0, 0),
(151, CC_BLUE, 0, 0, CC_YELLOW, 0),
(161, 0, CC_GREEN, 0, CC_YELLOW, 0),
(171, CC_BLUE, 0, CC_RED, 0, 0),
(181, CC_BLUE, CC_GREEN, CC_RED, CC_YELLOW, 0));
aCommon_Items: array [1..NUMBER_OF_COMMON_CARDS, 1..2] of string = (
('1012', '.18 Derringer'),
('1022', '.38 Revolver'),
('1032', '.45 Automatic'),
('1042', '.357 Magnum'),
('1052', 'Ancient Tome'),
('1062', 'Athame'),
('1072', 'Axe'),
('1082', 'Brass Knuckles'),
('1092', 'Bullwhip'),
('1102', 'Carbine Rifle'),
('1112', 'Cavalry Saber'),
('1121', 'Courier Run'),
('1132', 'Cross'),
('1142', 'Crowbar'),
('1152', 'Dark Cloak'),
('1162', 'Director''s Diary'),
('1172', 'Dusty Manuscripts'),
('1182', 'Динамит'),
('1192', 'Elephant Gun'),
('1201', 'Fine Clothing'),
('1212', 'z'),
('1222', 'Flare Gun'),
('1232', 'Еда'),
('1241', 'Еда'),
('1251', 'Genealogy Research'),
('1261', 'Gray''s Anatomy'),
('1271', 'Hand Camera'),
('1282', 'Handcuffs'),
('1292', 'Kerosene'),
('1301', 'King James Bible'),
('1312', 'Knife'),
('1322', 'Lantern'),
('1332', 'Ley Line Map'),
('1342', 'Lucky Cigarette Case'),
('1351', 'Lucky Rabbit''s Foot'),
('1362', 'Magnifying Glass'),
('1372', 'Makeup Kit'),
('1382', 'Map of Arkham'),
('1391', 'Military Motorcycle'),
('1401', 'Mineralogy Report'),
('1412', 'Molotov Cocktail'),
('1422', 'Motorcycle'),
('1432', 'Newspaper Assignment'),
('1442', 'Old Journal'),
('1451', 'Patrolling the Streets'),
('1462', 'Press Pass'),
('1472', 'Материалы следствия'),
('1482', 'Rifle'),
('1493', 'Safety Deposit Key'),
('1502', 'Sedanette'),
('1512', 'Дробовик'),
('1522', 'Sledgehammer'),
('1532', 'Student Newspaper'),
('1542', 'Telescope'),
('1553', 'Time Bomb'),
('1562', 'Tommy Gun'),
('1573', 'Understudy''s Script'),
('1582', 'Виски'),
('1591', 'Виски'));
aUnique_Items: array [1..NUMBER_OF_UNIQUE_CARDS, 1..2] of string = (
('2011', 'Alien Device'),
('2021', 'Alien Statue'),
('2032', 'Ancient Spear'),
('2041', 'Ancient Tablet'),
('2051', 'Astral Mirror'),
('2061', 'Blue Watcher of the Pyramid'),
('2071', 'Book of Dzyan'),
('2082', 'Book of the Believer'),
('2091', 'Brazier of Souls'),
('2102', 'Cabala of Saboth'),
('2111', 'Camilla''s Ruby'),
('2121', 'Carcosan Page'),
('2131', 'Cryptozoology Collection'),
('2144', 'Crystal of the Elder Things'),
('2152', 'Cultes des Goules'),
('2161', 'Cursed Sphere'),
('2171', 'De Vermiis Mysteriis'),
('2181', 'Dhol Chants'),
('2191', 'Dragon''s Eye'),
('2201', 'Elder Sign'),
('2211', 'Elder Sign'),
('2221', 'Elder Sign Pendant'),
('2231', 'Elixir of Life'),
('2241', 'Eltdown Shards'),
('2251', 'Enchanted Blade'),
('2261', 'Enchanted Cane'),
('2271', 'Enchanted Jewelry'),
('2281', 'Enchanted Knife'),
('2291', 'Fetch Stick'),
('2301', 'Fire of Asshurbanipal'),
('2311', 'Flute of the Outer Gods'),
('2321', 'For the Greater Good'),
('2331', 'Gate Box'),
('2341', 'Gladius of Carcosa'),
('2351', 'Glass of Mortlan'),
('2361', 'Golden Sword of Y''ha-Talla'),
('2371', 'Golden Trumpet'),
('2381', 'Gruesome Talisman'),
('2391', 'Healing Stone'),
('2401', 'Illuminated Manuscript'),
('2411', 'Святая вода (Holy Water)'),
('2421', 'Joining the Winning Team'),
('2431', 'Key of Tawil At''Umr'),
('2441', 'Lamp of Alhazred'),
('2451', 'Lightning Gun'),
('2461', 'Livre d''Ivon'),
('2471', 'Map of the Mind'),
('2481', 'Masquerade of Night'),
('2491', 'Massa di Requiem per Shuggay'),
('2501', 'Mi-Go Brain Case'),
('2511', 'Milk of Shub-Niggurath'),
('2521', 'Naacal Key'),
('2531', 'Nameless Cults'),
('2541', 'Necronomicon'),
('2551', 'Obsidian Statue'),
('2561', 'Pallid Mask'),
('2571', 'Petrifying Solution'),
('2581', 'Powder of Ibn-Ghazi'),
('2591', 'Purifying The Town'),
('2601', 'Puzzle Box'),
('2611', 'Ritual Blade'),
('2621', 'Ritual Candles'),
('2631', 'Ruby of R''lyeh'),
('2641', 'Sacrifices to Make'),
('2651', 'Sealing The Beast''s Power'),
('2661', 'Seeker of the Yellow Sign'),
('2671', 'Seven Cryptical Books of Hsan'),
('2681', 'Shrine to an Elder God'),
('2691', 'Silver Key'),
('2701', 'Soul Gem'),
('2711', 'Staff of the Pharaoh'),
('2721', 'Sword of Glory'),
('2731', 'The King in Yellow'),
('2741', 'The Light of Reason'),
('2751', 'Throne of Carcosa'),
('2761', 'True Magick'),
('2771', 'Walking the Ley Lines'),
('2781', 'Warding of the Yellow Sign'),
('2791', 'Warding Statue'),
('2801', 'Warning Mirror'),
('2811', 'Wave of Destruction'),
('2821', 'Yithian Rifle'),
('2831', 'Zanthu Tablets'));
crd_ally: array [1..1] of string = ('Anna Kaslow');
aInvestigators: array [1..NUMBER_OF_INVESTIGATORS] of string = ('Agnes Baker', 'Akachi Onyele',
'Amanda Sharpe', '"Ashcan" Pete', 'Bob Jenkins', 'Calvin Wright',
'Carolyn Fern', 'Charlie Kane', 'Daisy Walker', 'Darrell Simmons',
'Dexter Drake', 'Diana Stanley', 'Finn Edwards', 'George Barnaby',
'Gloria Goldberg', 'Hank Samson', 'Harvey Walters', 'Jacqueline Fine',
'Jenny Barnes', 'Jim Culver', 'Joe Diamond', 'Kate Winthrop',
'Leo Anderson', 'Lily Chen', 'Lola Hayes', 'Luke Robinson',
'Mandy Thompson', 'Marie Lambeau', 'Mark Harrigan', 'Michael McGlen',
'Minh Thi Phan', 'Monterey Jack', 'Norman Withers', 'Patrice Hathaway',
'Rex Murphy', 'Rita Young', 'Roland Banks', 'Silas Marsh',
'Sister Mary', '"Skids" O''Toole', 'Tommy Muldoon', 'Tony Morgan',
'Trish Scarborough', 'Ursula Downs', 'Vincent Lee', 'Wendy Adams',
'William Yorick', 'Wilson Richards', 'Zoey Samara');
MonsterNames: array [1..MONSTER_MAX, 1..2] of string = (
('013', 'Бъяхи'),
('023', 'Бъяхи'),
('033', 'Бъяхи'),
('043', 'Бъяхи'),
('053', 'Бъяхи'),
('1063', 'Бъяхи'),
('073', 'Бъяхи'),
('083', 'Бъяхи'),
('093', 'Бъяхи'),
('103', 'Бъяхи'),
('1112', 'Хтоническое чудище'),
('123', 'Бъяхи'),
('133', 'Бъяхи'),
('1146', 'Культист'),
('153', 'Бъяхи'),
('163', 'Бъяхи'),
('173', 'Бъяхи'),
('183', 'Бъяхи'),
('1193', 'Темная молодь'),
('1202', 'Эээ'),
('213', 'Бъяхи'),
('223', 'Бъяхи'),
('233', 'Бъяхи'),
('1241', 'Дхоул'),
('1252', 'Бродящий меж миров'),
('1262', 'Старец'),
('273', 'Бъяхи'),
('1282', 'Огненный вампир'),
('1291', 'Летучий полип'),
('1302', 'Бесформенная тварь'),
('063', 'Бъяхи'),
('063', 'Бъяхи'),
('063', 'Бъяхи'),
('1343', 'Призрак'),
('1353', 'Упырь'),
('063', 'Бъяхи'),
('063', 'Бъяхи'),
('063', 'Бъяхи'),
('1391', 'Бог Кровавого Языка'),
('1402', 'Гуг'),
('1411', 'Скиталец тьмы'),
('1421', 'Верховный жрец'),
('1432', 'Пес Тиндалоса'),
('063', 'Бъяхи'),
('063', 'Бъяхи'),
('063', 'Бъяхи'),
('1473', 'Маньяк'),
('1483', 'Ми-Го'),
('063', 'Бъяхи'),
('063', 'Бъяхи'));
Allies: array [1..ALLIES_MAX, 1..2] of string = (
('013', 'Bayakee'),
('01', 'Bayakee'),
('033', 'Bayakee'),
('043', 'Bayakee'),
('053', 'Bayakee'),
('05', 'Bayakee'),
('073', 'Bayakee'),
('083', 'Bayakee'),
('093', 'Bayakee'),
('103', 'Bayakee'),
('10', 'Chthonian'),
('123', 'Bayakee'),
('133', 'Bayakee'),
('146', 'Cultist'),
('153', 'Bayakee'),
('15', 'Bayakee'),
('173', 'Bayakee'),
('183', 'Bayakee'),
('193', 'Bayakee'),
('202', 'Fire Vampire'),
('20', 'Bayakee'),
('223', 'Bayakee'),
('233', 'Bayakee'),
('243', 'Bayakee'),
('253', 'Bayakee'),
('25', 'Bayakee'),
('273', 'Bayakee'),
('282', 'Fire Vampire'),
('063', 'Bayakee'),
('063', 'Bayakee'),
('30', 'Bayakee'),
('063', 'Bayakee'),
('32', 'Rayan Din'),
('063', 'Bayakee'),
('063', 'Bayakee'),
('35', 'Bayakee'),
('063', 'Bayakee'),
('063', 'Bayakee'),
('063', 'Bayakee'),
('063', 'Bayakee'),
('40', 'Bayakee'),
('41', 'Tom "Mountain" Murphy'),
('063', 'Bayakee'),
('063', 'Bayakee'),
('063', 'Bayakee'),
('45', 'Bayakee'),
('063', 'Bayakee'),
('063', 'Bayakee'),
('063', 'Bayakee'),
('49', 'Bayakee'));
Things: array [1..3] of string = (
('$'),
('Clue(s)'),
('Monster trophie(s)'));
aMonsterMoves: array [1..36, 1..3] of integer = (
(1000, 2000, 5000),
(2000, 3000, 1000),
(3000, 4000, 2000),
(4000, 6000, 3000),
(5000, 1000, 7000),
(6000, 8000, 4000),
(7000, 5000, 9000),
(8000, 9000, 6000),
(9000, 7000, 8000),
(1100, 1000, 1000),
(2100, 2000, 2000),
(3100, 3000, 3000),
(4100, 4000, 4000),
(5100, 5000, 5000),
(6100, 6000, 6000),
(7100, 7000, 7000),
(8100, 8000, 8000),
(9100, 9000, 9000),
(1200, 2000, 5000),
(2200, 2000, 5000),
(3200, 2000, 5000),
(4200, 2000, 5000),
(5200, 5000, 5000),
(6200, 2000, 5000),
(7200, 2000, 5000),
(8200, 2000, 5000),
(9200, 9000, 9000),
(1300, 1000, 1000),
(2300, 2000, 2000),
(3300, 3000, 3000),
(4300, 4000, 4000),
(5300, 5000, 5000),
(6300, 6000, 6000),
(7300, 7000, 7000),
(8300, 8000, 8000),
(9300, 9000, 9000));
type
StrDataArray = array [1..10] of string;
TGate = record
other_world: Integer;
modif: integer;
dimension: Integer;
end;
function hon(num: integer): integer; // hundredth of number
function ton(num: integer): integer; // thousandth of number
implementation
function hon(num: integer): integer; // hundredth of number
var
tmp: integer;
begin
result := (num mod 1000) div 100;
end;
function ton(num: integer): integer; // thousandth of number
var
tmp: integer;
begin
result := num div 1000;
end;
end.
|
(*
* (c) Copyright 1995, MAP Ltd., Veldhoven
*
* Function : Pause!16.PAS
*
* Abstract : Pause! Version 1.6
*
* Description : see Summary
*
* Remarks : á ð Alt-225
* MV ð Menno A.P.J. Vogels
*
* History : Version 1.4 source, ?
*
* Version 1.5 source, 94-04
*
* 940608, removed command execution & added switch for repeating alert, MV
* 940730, some miner modifications, MV
* 950130, added some comment, MV
* 950424, added GetFields-procedure & changed GetCommand-procedure, MV
*
* Version 1.6 source, 95-mm
*
* Summary :
*)
program
Pause (input,output);
{$M 4000,0,0}
(*--- USED UNITS ---*)
uses
Crt, Dos;
(*--- GLOBAL CONSTANTS ---*)
const
LowFrequency = 50;
DefFrequency = 650;
HighFrequency = 1950;
MinTimeOn = 5;
MinTimeOff = 5;
(*--- GLOBAL VARIABLES ---*)
var
Frequency,
TimeOn,
TimeOff : Word;
DoAlert,
Multiple : Boolean;
(*--- FUNCTION AND PROCEDURE DEFINITIONS ---*)
(*
* Function : Init
* Abstract :
* Decisions :
*)
procedure Init;
begin
Frequency := DefFrequency;
TimeOn := 25;
TimeOff := 50;
DoAlert := FALSE;
Multiple := TRUE;
end; { of Init }
(*
* Function : UpStr
* Abstract : String to Upper Case
* Decisions : Converts all lower case characters of
* the input string to upper case
*)
function UpStr(S: String): String;
var i: Integer;
begin
for i := 1 to Length(S) do begin
S[i] := UpCase(S[i]);
end;
UpStr := S;
end; { of UpStr }
(*
* Function : Str2Word
* Abstract : String to Word
* Decisions : Changes a string type identifier to
* a word type identifier
*)
function Str2Word(S: String): Word;
var ErrorCode: Integer;
W : Word;
begin
if Length(S) = 0 then
Str2Word := 0
else
begin
Val(S, W, ErrorCode);
if ErrorCode = 0 then
Str2Word := W
else
Str2Word := 0;
end;
end; { of Str2Word }
(*
* Function : Alert
* Abstract :
* Decisions :
*)
procedure Alert;
var I: Word;
begin
I:=1;
repeat
Sound(Frequency);
Delay(5);
Inc(I);
until KeyPressed or (I >= TimeOn);
NoSound;
I:=1;
repeat
Delay(5);
Inc(I);
until KeyPressed or (I >= TimeOff);
NoSound;
end; { of Alert }
(*
* Function : CursorOff
* Abstract : Disable cursor display on the screen
* Decisions :
*)
procedure CursorOff;
var Register: Registers;
begin
Register.Ax := 1 SHL 8;
Register.Cx := 14 SHL 8 +0;
Intr($10, Register);
end; { of CursorOff }
(*
* Function : CursorOn
* Abstract : Enable cursor display on the screen
* Decisions :
*)
procedure CursorOn;
var Register: Registers;
begin
Register.Ax := 1 SHL 8;
Register.Cx := 6 SHL 8 +7;
Intr($10, Register);
end; { of CursorOn }
(*
* Function : Help
* Abstract : Display a 'help'-page on the screen
* Decisions :
*)
procedure Help;
begin
WriteLn;
WriteLn(' Pause! V1.6á MAP Ltd. ''94 ');
WriteLn;
WriteLn(' /? : This Help ');
WriteLn(' /A : Alert with Default Frequency & Dutycycle ');
WriteLn(' /A^ : High ');
WriteLn(' /A_ : Low ');
WriteLn(' /A:n,n,n : Custom Frequency, Alert time & Silence time ');
WriteLn(' /R : Only one alert signal ');
WriteLn(' eg. PAUSE! /a:850,5,25 ');
WriteLn;
CursorOn;
Halt(0);
end; { of Help }
(*
* Function : GetFields
*
* Abstract :
*
* Description : Split the input string into two seperate strings,
* the 'splitter' indicates where the input string
* should be split in two
*)
procedure GetFields(InStr : String;
Splitter: Char;
var OutStr1 : String;
var OutStr2 : String;
var OutStr3 : String);
var P, Nr: Byte;
StrArray: array[1..3] of String;
begin
Nr := 1;
while Length(InStr) <> 0 do begin
P := Pos(Splitter,InStr);
if P = 0 then P := Length(InStr) +1;
StrArray[Nr] := Copy(InStr, 1, P-1);
Delete(InStr, 1, P);
Inc(Nr);
end;
OutStr1 := StrArray[1];
OutStr2 := StrArray[2];
OutStr3 := StrArray[3];
end;
(*
* Function : GetCommand
* Abstract : Get the arguments from the command-line
* Decisions :
*)
procedure GetCommand;
var Count : Byte;
InStr : ComStr;
FreqStr,
TimeOnStr,
TimeOffStr: String;
begin
for Count := 1 to ParamCount do begin
InStr := UpStr(ParamStr(Count));
if InStr[1] = '/' then
case InStr[2] of
'A': begin
(*
* Example for alert switch: /a:1900,5,25
*)
DoAlert := TRUE;
if Length(InStr) > 2 then begin
case InStr[3] of
':': begin
GetFields(Copy(InStr,4,Length(InStr) -3),
',',
FreqStr,TimeOnStr,TimeOffStr);
(* Frequency <= 1900 *)
Frequency := Str2Word(FreqStr);
(* TimeOn <= 5 *)
TimeOn := Str2Word(TimeOnStr);
if TimeOn < MinTimeOn then TimeOn := MinTimeOn;
(* TimeOff <= 25 *)
TimeOff := Str2Word(TimeOffStr);
if TimeOff < MinTimeOff then TimeOff := MinTimeOff;
if Frequency = 0 then Frequency := HighFrequency;
if TimeOn > ((TimeOn+TimeOff) div 2) then begin
TimeOn := MinTimeOn;
TimeOff := MinTimeOff;
end;
end;
'_': Frequency := LowFrequency;
'^': Frequency := HighFrequency;
end; {of case}
end;
end; { of case 'A' }
'R': Multiple := FALSE;
'?': Help;
else begin
WriteLn('Invalid option: ',InStr[2]);
CursorOn;
Halt(1);
end;
end; {of case}
end; {for Count}
end; { of GetCommand }
(*
* Function : MAIN
* Abstract :
* Decisions :
*)
BEGIN
CursorOff;
Init;
GetCommand;
Write ('Press a key to continue . . .');
if NOT KeyPressed then
if DoAlert then
begin
repeat
Alert;
until KeyPressed OR (NOT Multiple);
repeat
until KeyPressed;
end
else
repeat
until KeyPressed;
WriteLn;
CursorOn;
END. { of MAIN } |
unit MyFileDialogs;
interface
uses
SysUtils, MyUtils, Vcl.StdCtrls;
type
TFileDialogs = class
class procedure OpenFileAll(Sender: TObject);
class procedure OpenFileFB(Sender: TObject);
class procedure OpenFileFBK(Sender: TObject);
class procedure OpenFileDLL(Sender: TObject);
class procedure OpenFolder(Sender: TObject);
class procedure SaveFileFB(Sender: TObject);
class procedure SaveFileFBK(Sender: TObject);
class procedure SaveFolder(Sender: TObject);
private
class procedure OpenFile(Sender: TObject; DisplayName, FileMask: string; IncludeAllFiles: boolean);
class procedure SaveFile(Sender: TObject; DisplayName, FileMask: string; IncludeAllFiles: boolean);
end;
implementation
//Load
class procedure TFileDialogs.OpenFileAll(Sender: TObject);
var
FileName: string;
begin
if TUTils.OpenFileAll(FileName) then
(Sender as TEdit).Text := FileName;
end;
class procedure TFileDialogs.OpenFile(Sender: TObject; DisplayName, FileMask: string; IncludeAllFiles: boolean);
var
FileName: string;
begin
if TUTils.OpenFile(DisplayName, FileMask, IncludeAllFiles, FileName) then
(Sender as TEdit).Text := FileName;
end;
class procedure TFileDialogs.OpenFileFB(Sender: TObject);
begin
OpenFile(Sender, 'Firebird Database (*.FDB)', '*.FDB', true);
end;
class procedure TFileDialogs.OpenFileFBK(Sender: TObject);
begin
OpenFile(Sender, 'Firebird Backup (*.FBK)', '*.FBK', true);
end;
class procedure TFileDialogs.OpenFileDLL(Sender: TObject);
begin
OpenFile(Sender, 'Dynamic Link Library (*.DLL)', '*.DLL', true);
end;
class procedure TFileDialogs.OpenFolder(Sender: TObject);
var
FileName: string;
begin
if TUTils.OpenFolder(FileName) then
(Sender as TEdit).Text := FileName;
end;
//Save
class procedure TFileDialogs.SaveFile(Sender: TObject; DisplayName, FileMask: string; IncludeAllFiles: boolean);
var
FileName: string;
begin
if TUTils.SaveFile(DisplayName, FileMask, IncludeAllFiles, FileName) then
(Sender as TEdit).Text := FileName;
end;
class procedure TFileDialogs.SaveFileFB(Sender: TObject);
begin
SaveFile(Sender, 'Firebird Database (*.FDB)', '*.FDB', false);
end;
class procedure TFileDialogs.SaveFileFBK(Sender: TObject);
begin
SaveFile(Sender, 'Firebird Backup (*.FBK)', '*.FBK', true);
end;
class procedure TFileDialogs.SaveFolder(Sender: TObject);
var
FileName: string;
begin
if TUTils.SaveFolder(FileName) then
(Sender as TEdit).Text := FileName;
end;
end.
|
unit IdTunnelMaster;
interface
uses
Classes,
IdTCPServer, IdTCPClient, IdTunnelCommon,
SyncObjs;
type
TIdTunnelMaster = class;
MClientThread = class(TThread)
public
MasterParent: TIdTunnelMaster;
UserId: Integer;
MasterThread: TIdPeerThread;
OutboundClient: TIdTCPClient;
DisconnectedOnRequest: Boolean;
Locker: TCriticalSection;
SelfDisconnected: Boolean;
procedure Execute; override;
constructor Create(master: TIdTunnelMaster);
destructor Destroy; override;
end;
TSlaveData = class(TObject)
public
Receiver: TReceiver;
Sender: TSender;
Locker: TCriticalSection;
SelfDisconnected: Boolean;
UserData: TObject;
end;
TSendMsgEvent = procedure(Thread: TIdPeerThread; var CustomMsg: string) of
object;
TSendTrnEvent = procedure(Thread: TIdPeerThread; var Header: TIdHeader; var
CustomMsg: string) of object;
TSendTrnEventC = procedure(var Header: TIdHeader; var CustomMsg: string) of
object;
TTunnelEventC = procedure(Receiver: TReceiver) of object;
TSendMsgEventC = procedure(var CustomMsg: string) of object;
TIdTunnelMaster = class(TIdTCPServer)
private
fiMappedPort: Integer;
fsMappedHost: string;
Clients: TThreadList;
fOnConnect,
fOnDisconnect,
fOnTransformRead: TIdServerThreadEvent;
fOnTransformSend: TSendTrnEvent;
fOnInterpretMsg: TSendMsgEvent;
OnlyOneThread: TCriticalSection;
StatisticsLocker: TCriticalSection;
fbActive: Boolean;
fbLockDestinationHost: Boolean;
fbLockDestinationPort: Boolean;
fLogger: TLogger;
flConnectedSlaves,
flConnectedServices,
fNumberOfConnectionsValue,
fNumberOfPacketsValue,
fCompressionRatioValue,
fCompressedBytes,
fBytesRead,
fBytesWrite: Integer;
procedure ClientOperation(Operation: Integer; UserId: Integer; s: string);
procedure SendMsg(MasterThread: TIdPeerThread; var Header: TIdHeader; s:
string);
procedure DisconectAllUsers;
procedure DisconnectAllSubThreads(TunnelThread: TIdPeerThread);
function GetNumSlaves: Integer;
function GetNumServices: Integer;
function GetClientThread(UserID: Integer): MClientThread;
protected
procedure SetActive(pbValue: Boolean); override;
procedure DoConnect(Thread: TIdPeerThread); override;
procedure DoDisconnect(Thread: TIdPeerThread); override;
function DoExecute(Thread: TIdPeerThread): boolean; override;
procedure DoTransformRead(Thread: TIdPeerThread); virtual;
procedure DoTransformSend(Thread: TIdPeerThread; var Header: TIdHeader; var
CustomMsg: string);
virtual;
procedure DoInterpretMsg(Thread: TIdPeerThread; var CustomMsg: string);
virtual;
procedure LogEvent(Msg: string);
published
property MappedHost: string read fsMappedHost write fsMappedHost;
property MappedPort: Integer read fiMappedPort write fiMappedPort;
property LockDestinationHost: Boolean read fbLockDestinationHost write
fbLockDestinationHost
default False;
property LockDestinationPort: Boolean read fbLockDestinationPort write
fbLockDestinationPort
default False;
property OnConnect: TIdServerThreadEvent read FOnConnect write FOnConnect;
property OnDisconnect: TIdServerThreadEvent read FOnDisconnect write
FOnDisconnect;
property OnTransformRead: TIdServerThreadEvent read fOnTransformRead write
fOnTransformRead;
property OnTransformSend: TSendTrnEvent read fOnTransformSend write
fOnTransformSend;
property OnInterpretMsg: TSendMsgEvent read fOnInterpretMsg write
fOnInterpretMsg;
public
property Active: Boolean read FbActive write SetActive default True;
property Logger: TLogger read fLogger write fLogger;
property NumSlaves: Integer read GetNumSlaves;
property NumServices: Integer read GetNumServices;
procedure SetStatistics(Module: Integer; Value: Integer);
procedure GetStatistics(Module: Integer; var Value: Integer);
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
implementation
uses IdException,
IdGlobal, IdStack, IdResourceStrings, SysUtils;
constructor TIdTunnelMaster.Create(AOwner: TComponent);
begin
Clients := TThreadList.Create;
inherited Create(AOwner);
fbActive := False;
flConnectedSlaves := 0;
flConnectedServices := 0;
fNumberOfConnectionsValue := 0;
fNumberOfPacketsValue := 0;
fCompressionRatioValue := 0;
fCompressedBytes := 0;
fBytesRead := 0;
fBytesWrite := 0;
OnlyOneThread := TCriticalSection.Create;
StatisticsLocker := TCriticalSection.Create;
end;
destructor TIdTunnelMaster.Destroy;
begin
Logger := nil;
Active := False;
DisconectAllUsers;
inherited Destroy;
Clients.Destroy;
OnlyOneThread.Free;
StatisticsLocker.Free;
end;
procedure TIdTunnelMaster.SetActive(pbValue: Boolean);
begin
if fbActive = pbValue then
exit;
if pbValue then
begin
inherited SetActive(True);
end
else
begin
inherited SetActive(False);
DisconectAllUsers;
end;
fbActive := pbValue;
end;
procedure TIdTunnelMaster.LogEvent(Msg: string);
begin
if Assigned(fLogger) then
fLogger.LogEvent(Msg);
end;
function TIdTunnelMaster.GetNumSlaves: Integer;
var
ClientsNo: Integer;
begin
GetStatistics(NumberOfSlavesType, ClientsNo);
Result := ClientsNo;
end;
function TIdTunnelMaster.GetNumServices: Integer;
var
ClientsNo: Integer;
begin
GetStatistics(NumberOfServicesType, ClientsNo);
Result := ClientsNo;
end;
procedure TIdTunnelMaster.GetStatistics(Module: Integer; var Value: Integer);
begin
StatisticsLocker.Enter;
try
case Module of
NumberOfSlavesType:
begin
Value := flConnectedSlaves;
end;
NumberOfServicesType:
begin
Value := flConnectedServices;
end;
NumberOfConnectionsType:
begin
Value := fNumberOfConnectionsValue;
end;
NumberOfPacketsType:
begin
Value := fNumberOfPacketsValue;
end;
CompressionRatioType:
begin
if fCompressedBytes > 0 then
begin
Value := Trunc((fBytesRead * 1.0) / (fCompressedBytes * 1.0) * 100.0)
end
else
begin
Value := 0;
end;
end;
CompressedBytesType:
begin
Value := fCompressedBytes;
end;
BytesReadType:
begin
Value := fBytesRead;
end;
BytesWriteType:
begin
Value := fBytesWrite;
end;
end;
finally
StatisticsLocker.Leave;
end;
end;
procedure TIdTunnelMaster.SetStatistics(Module: Integer; Value: Integer);
var
packets: Real;
ratio: Real;
begin
StatisticsLocker.Enter;
try
case Module of
NumberOfSlavesType:
begin
if TIdStatisticsOperation(Value) = soIncrease then
begin
Inc(flConnectedSlaves);
end
else
begin
Dec(flConnectedSlaves);
end;
end;
NumberOfServicesType:
begin
if TIdStatisticsOperation(Value) = soIncrease then
begin
Inc(flConnectedServices);
Inc(fNumberOfConnectionsValue);
end
else
begin
Dec(flConnectedServices);
end;
end;
NumberOfConnectionsType:
begin
Inc(fNumberOfConnectionsValue);
end;
NumberOfPacketsType:
begin
Inc(fNumberOfPacketsValue);
end;
CompressionRatioType:
begin
ratio := fCompressionRatioValue;
packets := fNumberOfPacketsValue;
ratio := (ratio / 100.0 * (packets - 1.0) + Value / 100.0) / packets;
fCompressionRatioValue := Trunc(ratio * 100);
end;
CompressedBytesType:
begin
fCompressedBytes := fCompressedBytes + Value;
end;
BytesReadType:
begin
fBytesRead := fBytesRead + Value;
end;
BytesWriteType:
begin
fBytesWrite := fBytesWrite + Value;
end;
end;
finally
StatisticsLocker.Leave;
end;
end;
procedure TIdTunnelMaster.DoConnect(Thread: TIdPeerThread);
begin
Thread.Data := TSlaveData.Create;
with TSlaveData(Thread.Data) do
begin
Receiver := TReceiver.Create;
Sender := TSender.Create;
SelfDisconnected := False;
Locker := TCriticalSection.Create;
end;
if Assigned(OnConnect) then
begin
OnConnect(Thread);
end;
SetStatistics(NumberOfSlavesType, Integer(soIncrease));
end;
procedure TIdTunnelMaster.DoDisconnect(Thread: TIdPeerThread);
begin
SetStatistics(NumberOfSlavesType, Integer(soDecrease));
DisconnectAllSubThreads(Thread);
if Thread.Connection.Connected then
Thread.Connection.Disconnect;
if Assigned(OnDisconnect) then
begin
OnDisconnect(Thread);
end;
with TSlaveData(Thread.Data) do
begin
Receiver.Free;
Sender.Free;
Locker.Free;
TSlaveData(Thread.Data).Free;
end;
Thread.Data := nil;
end;
function TIdTunnelMaster.DoExecute(Thread: TIdPeerThread): boolean;
var
user: TSlaveData;
clientThread: MClientThread;
s: string;
ErrorConnecting: Boolean;
sIP: string;
CustomMsg: string;
Header: TIdHeader;
begin
result := true;
user := TSlaveData(Thread.Data);
if Thread.Connection.Binding.Readable(IdTimeoutInfinite) then
begin
user.receiver.Data := Thread.Connection.CurrentReadBuffer;
SetStatistics(NumberOfPacketsType, 0);
while user.receiver.TypeDetected do
begin
if not (user.receiver.Header.MsgType in [tmData, tmDisconnect, tmConnect,
tmCustom]) then
begin
Thread.Connection.Disconnect;
break;
end;
if user.receiver.NewMessage then
begin
if user.Receiver.CRCFailed then
begin
Thread.Connection.Disconnect;
break;
end;
try
DoTransformRead(Thread);
except
Thread.Connection.Disconnect;
Break;
end;
case user.Receiver.Header.MsgType of
tmError:
begin
try
Thread.Connection.Disconnect;
break;
except
;
end;
end;
tmData:
begin
try
SetString(s, user.Receiver.Msg, user.Receiver.MsgLen);
ClientOperation(tmData, user.Receiver.Header.UserId, s);
except
;
end;
end;
tmDisconnect:
begin
try
ClientOperation(tmDisconnect, user.Receiver.Header.UserId, '');
except
;
end;
end;
tmConnect:
begin
try
clientThread := MClientThread.Create(self);
try
ErrorConnecting := False;
with clientThread do
begin
UserId := user.Receiver.Header.UserId;
MasterThread := Thread;
OutboundClient := TIdTCPClient.Create(nil);
sIP := GStack.TInAddrToString(user.Receiver.Header.IpAddr);
if fbLockDestinationHost then
begin
OutboundClient.Host := fsMappedHost;
if fbLockDestinationPort then
OutboundClient.Port := fiMappedPort
else
OutboundClient.Port := user.Receiver.Header.Port;
end
else
begin
if sIP = '0.0.0.0' then
begin
OutboundClient.Host := fsMappedHost;
OutboundClient.Port := user.Receiver.Header.Port;
end
else
begin
OutboundClient.Host := sIP;
OutboundClient.Port := user.Receiver.Header.Port;
end;
end;
OutboundClient.Connect;
end;
except
ErrorConnecting := True;
end;
if ErrorConnecting then
begin
clientThread.Destroy;
end
else
begin
clientThread.Resume;
end;
except
;
end;
end;
tmCustom:
begin
CustomMsg := '';
DoInterpretMsg(Thread, CustomMsg);
if Length(CustomMsg) > 0 then
begin
Header.MsgType := tmCustom;
Header.UserId := 0;
SendMsg(Thread, Header, CustomMsg);
end;
end;
end;
user.Receiver.ShiftData;
end
else
break;
end;
end;
end;
procedure TIdTunnelMaster.DoTransformRead(Thread: TIdPeerThread);
begin
if Assigned(fOnTransformRead) then
fOnTransformRead(Thread);
end;
procedure TIdTunnelMaster.DoTransformSend(Thread: TIdPeerThread; var Header:
TIdHeader; var CustomMsg: string);
begin
if Assigned(fOnTransformSend) then
fOnTransformSend(Thread, Header, CustomMsg);
end;
procedure TIdTunnelMaster.DoInterpretMsg(Thread: TIdPeerThread; var CustomMsg:
string);
begin
if Assigned(fOnInterpretMsg) then
fOnInterpretMsg(Thread, CustomMsg);
end;
procedure TIdTunnelMaster.DisconnectAllSubThreads(TunnelThread: TIdPeerThread);
var
Thread: MClientThread;
i: integer;
listTemp: TList;
begin
OnlyOneThread.Enter;
listTemp := Clients.LockList;
try
for i := 0 to listTemp.count - 1 do
begin
if Assigned(listTemp[i]) then
begin
Thread := MClientThread(listTemp[i]);
if Thread.MasterThread = TunnelThread then
begin
Thread.DisconnectedOnRequest := True;
Thread.OutboundClient.Disconnect;
end;
end;
end;
finally
Clients.UnlockList;
OnlyOneThread.Leave;
end;
end;
procedure TIdTunnelMaster.SendMsg(MasterThread: TIdPeerThread; var Header:
TIdHeader; s: string);
var
user: TSlaveData;
tmpString: string;
begin
if Assigned(MasterThread.Data) then
begin
TSlaveData(MasterThread.Data).Locker.Enter;
try
user := TSlaveData(MasterThread.Data);
try
tmpString := s;
try
DoTransformSend(MasterThread, Header, tmpString);
except
on E: Exception do
begin
raise
EIdTunnelTransformErrorBeforeSend.Create(RSTunnelTransformErrorBS);
end;
end;
if Header.MsgType = tmError then
begin // error ocured in transformation
raise
EIdTunnelTransformErrorBeforeSend.Create(RSTunnelTransformErrorBS);
end;
user.Sender.PrepareMsg(Header, PChar(@tmpString[1]), Length(tmpString));
MasterThread.Connection.Write(user.Sender.Msg);
except
raise;
end;
finally
TSlaveData(MasterThread.Data).Locker.Leave;
end;
end;
end;
function TIdTunnelMaster.GetClientThread(UserID: Integer): MClientThread;
var
Thread: MClientThread;
i: integer;
begin
Result := nil;
with Clients.LockList do
try
for i := 0 to Count - 1 do
begin
try
if Assigned(Items[i]) then
begin
Thread := MClientThread(Items[i]);
if Thread.UserId = UserID then
begin
Result := Thread;
break;
end;
end;
except
Result := nil;
end;
end;
finally
Clients.UnlockList;
end;
end;
procedure TIdTunnelMaster.DisconectAllUsers;
begin
TerminateAllThreads;
end;
procedure TIdTunnelMaster.ClientOperation(Operation: Integer; UserId: Integer;
s: string);
var
Thread: MClientThread;
begin
Thread := GetClientThread(UserID);
if Assigned(Thread) then
begin
Thread.Locker.Enter;
try
if not Thread.SelfDisconnected then
begin
case Operation of
tmData:
begin
try
Thread.OutboundClient.CheckForDisconnect;
if Thread.OutboundClient.Connected then
Thread.OutboundClient.Write(s);
except
try
Thread.OutboundClient.Disconnect;
except
;
end;
end;
end;
tmDisconnect:
begin
Thread.DisconnectedOnRequest := True;
try
Thread.OutboundClient.Disconnect;
except
;
end;
end;
end;
end;
finally
Thread.Locker.Leave;
end;
end;
end;
constructor MClientThread.Create(master: TIdTunnelMaster);
begin
MasterParent := master;
FreeOnTerminate := True;
DisconnectedOnRequest := False;
SelfDisconnected := False;
Locker := TCriticalSection.Create;
MasterParent.Clients.Add(self);
master.SetStatistics(NumberOfServicesType, Integer(soIncrease));
inherited Create(True);
end;
destructor MClientThread.Destroy;
var
Header: TIdHeader;
begin
MasterParent.SetStatistics(NumberOfServicesType, Integer(soDecrease));
MasterParent.Clients.Remove(self);
try
if not DisconnectedOnRequest then
begin
try
Header.MsgType := tmDisconnect;
Header.UserId := UserId;
MasterParent.SendMsg(MasterThread, Header, RSTunnelDisconnectMsg);
except
;
end;
end;
if OutboundClient.Connected then
OutboundClient.Disconnect;
except
;
end;
MasterThread := nil;
try
OutboundClient.Free;
except
;
end;
Locker.Free;
Terminate;
inherited Destroy;
end;
procedure MClientThread.Execute;
var
s: string;
Header: TIdHeader;
begin
try
while not Terminated do
begin
if OutboundClient.Connected then
begin
if OutboundClient.Binding.Readable(IdTimeoutInfinite) then
begin
s := OutboundClient.CurrentReadBuffer;
try
Header.MsgType := tmData;
Header.UserId := UserId;
MasterParent.SendMsg(MasterThread, Header, s);
except
Terminate;
break;
end;
end;
end
else
begin
Terminate;
break;
end;
end;
except
;
end;
Locker.Enter;
try
SelfDisconnected := True;
finally
Locker.Leave;
end;
end;
end.
|
unit TransparentComboBox;
interface
uses
System.SysUtils, System.Classes, FMX.Types, FMX.Controls, System.Types,
FMX.Objects, System.UITypes, FMX.Graphics, FMX.Dialogs, System.Math,
System.Math.Vectors, FMX.Edit, FMX.Layouts, FMX.Effects, SolidInput, Card,
FMX.StdCtrls, FMX.Ani, System.Threading, Input, TransparentInput;
type
TComboBoxAlign = (Top, Bottom);
TTransparentComboBox = class(TControl)
private
{ Private declarations }
FRecalcCardChoices: Boolean;
protected
{ Protected declarations }
FPointerOnClosePopup: TNotifyEvent;
FPointerOnChangePopup: TNotifyEvent;
FTransparentInput: TTransparentInput;
FLayoutClick: TLayout;
FCardChoices: TCard;
FScrollChoices: TVertScrollBox;
FItems: TStringList;
FItemIndex: Integer;
FItemsChanged: Boolean;
FItemsCount: Integer;
FBackgroundItemSelect: TRectangle;
FLabelItemSelect: TLabel;
procedure Paint; override;
procedure OnComboBoxEnter(Sender: TObject);
procedure OnComboBoxExit(Sender: TObject);
procedure OnItemComboBoxClick(Sender: TObject);
procedure ItemSelect(Index: Integer);
procedure ShowItemSelect(Sender: TObject);
procedure ResetItemSelect();
function GetFItems: TStringList;
procedure SetFItems(const Value: TStringList);
function GetFItemIndex: Integer;
procedure SetFItemIndex(const Value: Integer);
function GetFComboBoxAlign: TComboBoxAlign;
procedure SetFComboBoxAlign(const Value: TComboBoxAlign);
function GetFTextSettings: TTextSettings;
procedure SetFTextSettings(const Value: TTextSettings);
function GetFComboBoxSelectedColor: TAlphaColor;
procedure SetFComboBoxSelectedColor(const Value: TAlphaColor);
function GetFComboBoxBackgroudColor: TBrush;
procedure SetFComboBoxBackgroudColor(const Value: TBrush);
function GetFCursor: TCursor;
procedure SetFCursor(const Value: TCursor);
function GetFTextPrompt: String;
procedure SetFTextPrompt(const Value: String);
function GetFOnClick: TNotifyEvent;
function GetFOnDblClick: TNotifyEvent;
function GetFOnEnter: TNotifyEvent;
function GetFOnExit: TNotifyEvent;
function GetFOnMouseDown: TMouseEvent;
function GetFOnMouseEnter: TNotifyEvent;
function GetFOnMouseLeave: TNotifyEvent;
function GetFOnMouseMove: TMouseMoveEvent;
function GetFOnMouseUp: TMouseEvent;
function GetFOnMouseWheel: TNotifyEvent;
procedure SetFOnClick(const Value: TNotifyEvent);
procedure SetFOnDblClick(const Value: TNotifyEvent);
procedure SetFOnEnter(const Value: TNotifyEvent);
procedure SetFOnExit(const Value: TNotifyEvent);
procedure SetFOnMouseDown(const Value: TMouseEvent);
procedure SetFOnMouseEnter(const Value: TNotifyEvent);
procedure SetFOnMouseLeave(const Value: TNotifyEvent);
procedure SetFOnMouseMove(const Value: TMouseMoveEvent);
procedure SetFOnMouseUp(const Value: TMouseEvent);
procedure SetFOnMouseWheel(const Value: TNotifyEvent);
function GetFCardChoicesHeight: Single;
procedure SetFCardChoicesHeight(const Value: Single);
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure InitializeComboBox();
function Text(): String;
function Select(ItemString: String = ''): String; overload;
function Select(ItemIndex: Integer = -1): Integer; overload;
procedure ValidateText();
published
{ Published declarations }
property Align;
property Anchors;
property Enabled;
property Height;
property Opacity;
property Visible;
property Width;
property Size;
property Scale;
property Margins;
property Position;
property RotationAngle;
property RotationCenter;
{ Additional properties }
property Cursor: TCursor read GetFCursor write SetFCursor;
property Items: TStringList read GetFItems write SetFItems;
property ItemIndex: Integer read GetFItemIndex write SetFItemIndex;
property ComboBoxAlign: TComboBoxAlign read GetFComboBoxAlign write SetFComboBoxAlign;
property ComboBoxSelectedColor: TAlphaColor read GetFComboBoxSelectedColor write SetFComboBoxSelectedColor;
property ComboBoxBackgroudColor: TBrush read GetFComboBoxBackgroudColor write SetFComboBoxBackgroudColor;
property TextSettings: TTextSettings read GetFTextSettings write SetFTextSettings;
property TextPrompt: String read GetFTextPrompt write SetFTextPrompt;
property CardChoicesHeight: Single read GetFCardChoicesHeight write SetFCardChoicesHeight;
{ Events }
property OnPainting;
property OnPaint;
property OnResize;
{ Mouse events }
property OnClick: TNotifyEvent read GetFOnClick write SetFOnClick;
property OnDblClick: TNotifyEvent read GetFOnDblClick write SetFOnDblClick;
property OnMouseDown: TMouseEvent read GetFOnMouseDown write SetFOnMouseDown;
property OnMouseUp: TMouseEvent read GetFOnMouseUp write SetFOnMouseUp;
property OnMouseWheel: TNotifyEvent read GetFOnMouseWheel write SetFOnMouseWheel;
property OnMouseMove: TMouseMoveEvent read GetFOnMouseMove write SetFOnMouseMove;
property OnMouseEnter: TNotifyEvent read GetFOnMouseEnter write SetFOnMouseEnter;
property OnMouseLeave: TNotifyEvent read GetFOnMouseLeave write SetFOnMouseLeave;
property OnEnter: TNotifyEvent read GetFOnEnter write SetFOnEnter;
property OnExit: TNotifyEvent read GetFOnExit write SetFOnExit;
property OnClosePopup: TNotifyEvent read FPointerOnClosePopup write FPointerOnClosePopup;
property OnChange: TNotifyEvent read FPointerOnChangePopup write FPointerOnChangePopup;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Componentes Customizados', [TTransparentComboBox]);
end;
{ TSolidAppleComboBox }
constructor TTransparentComboBox.Create(AOwner: TComponent);
begin
inherited;
Self.Width := 400;
Self.Height := 40;
Self.HitTest := False;
if not Assigned(FItems) then
FItems := TStringList.Create;
FItemsChanged := False;
FItemsCount := 0;
SetFItemIndex(-1);
{ SolidAppleEdit }
FTransparentInput := TTransparentInput.Create(Self);
Self.AddObject(FTransparentInput);
FTransparentInput.Align := TAlignLayout.Contents;
FTransparentInput.SetSubComponent(True);
FTransparentInput.Stored := False;
FTransparentInput.IconData.Data := 'M7.41,8.58L12,13.17L16.59,8.58L18,10L12,16L6,10L7.41,8.58Z';
FTransparentInput.IconPosition := Input.Right;
FTransparentInput.Caret.Color := TAlphaColor($FFFFFFFF);
FTransparentInput.OnExit := OnComboBoxExit;
FTransparentInput.ReadOnly := True;
{ LayoutClick }
FLayoutClick := TLayout.Create(Self);
FTransparentInput.AddObject(FLayoutClick);
FLayoutClick.Align := TAlignLayout.Contents;
FLayoutClick.SetSubComponent(True);
FLayoutClick.Stored := False;
FLayoutClick.HitTest := True;
FLayoutClick.Cursor := crHandPoint;
FLayoutClick.OnClick := OnComboBoxEnter;
{ CardChoices }
FCardChoices := TCard.Create(Self);
Self.AddObject(FCardChoices);
FCardChoices.Align := TAlignLayout.Top;
FCardChoices.SetSubComponent(True);
FCardChoices.Stored := False;
FCardChoices.CornerRound := 5;
FCardChoices.ElevationOpacity := 0.1;
FCardChoices.ElevationDistance := 7;
FCardChoices.Visible := False;
FCardChoices.HitTest := False;
{ ScrollChoices }
FScrollChoices := TVertScrollBox.Create(Self);
FCardChoices.AddObject(FScrollChoices);
FScrollChoices.Align := TAlignLayout.Client;
FScrollChoices.Margins.Top := 5;
FScrollChoices.Margins.Bottom := 5;
end;
destructor TTransparentComboBox.Destroy;
begin
if Assigned(FScrollChoices) then
FScrollChoices.Free;
if Assigned(FCardChoices) then
FCardChoices.Free;
if Assigned(FLayoutClick) then
FLayoutClick.Free;
if Assigned(FTransparentInput) then
FTransparentInput.Free;
if Assigned(FItems) then
FItems.Free;
inherited;
end;
procedure TTransparentComboBox.Paint;
begin
inherited;
if not FRecalcCardChoices then
begin
SetFComboBoxAlign(GetFComboBoxAlign);
FRecalcCardChoices := True;
end;
InitializeComboBox();
ItemSelect(GetFItemIndex);
end;
procedure TTransparentComboBox.InitializeComboBox();
var
Item: TRectangle;
Data: TLabel;
Animation: TColorAnimation;
begin
if FItemsChanged or (FItemsCount <> FItems.Count) then
begin
TTask.Run(
procedure
begin
TThread.Synchronize(TThread.CurrentThread,
procedure
var
I, J: Integer;
begin
if not((not FItemsChanged) and (FItems.Count > FItemsCount)) then
begin
for J := Pred(FScrollChoices.Content.ChildrenCount) downto 0 do
begin
Item := TRectangle(FScrollChoices.Content.Children[J]);
FScrollChoices.Content.RemoveObject(Item);
Item.Visible := False;
Item.DisposeOf;
Item := nil;
end;
FItemsCount := 0;
end;
{ Preenche os items }
for I := FItemsCount to FItems.Count - 1 do
begin
Item := TRectangle.Create(Self);
Item.Parent := FScrollChoices;
FScrollChoices.Content.AddObject(Item);
Item.Align := TAlignLayout.Top;
Item.Stroke.Kind := TBrushKind.None;
Item.Fill.Color := TAlphaColor($FFFFFFFFFF);
Item.Cursor := crHandPoint;
Item.Tag := I;
Item.OnClick := OnItemComboBoxClick;
Item.Position.Y := MaxSingle;
Data := TLabel.Create(Self);
Data.Parent := Item;
Item.AddObject(Data);
Data.Align := TAlignLayout.Client;
Data.HitTest := False;
Data.Margins.Left := 15;
Data.Margins.Right := 15;
Data.StyledSettings := [];
Data.TextSettings := FTransparentInput.TextSettings;
Data.Text := FItems[I];
Animation := TColorAnimation.Create(Self);
Animation.Parent := Item;
Item.AddObject(Animation);
Animation.Duration := 0.1;
Animation.PropertyName := 'Fill.Color';
Animation.StartValue := TAlphaColor($FFFFFFFF);
Animation.StopValue := TAlphaColor($FFF2F2F2);
Animation.Trigger := 'IsMouseOver=true';
Animation.TriggerInverse := 'IsMouseOver=false';
end;
FItemsChanged := False;
FItemsCount := FItems.Count;
end);
end);
end;
end;
procedure TTransparentComboBox.OnComboBoxEnter(Sender: TObject);
begin
FTransparentInput.SetFocus;
if not FCardChoices.Visible then
begin
InitializeComboBox();
ItemSelect(GetFItemIndex);
FCardChoices.HitTest := True;
FCardChoices.Open(0.1);
end
else
OnComboBoxExit(Sender);
end;
procedure TTransparentComboBox.OnComboBoxExit(Sender: TObject);
begin
if FCardChoices.Visible then
begin
FCardChoices.Close(0.1);
FCardChoices.HitTest := False;
end;
if Assigned(FPointerOnClosePopup) then
FPointerOnClosePopup(Sender);
end;
procedure TTransparentComboBox.OnItemComboBoxClick(Sender: TObject);
begin
ItemSelect(TRectangle(Sender).Tag);
ShowItemSelect(Sender);
if Assigned(FPointerOnChangePopup) then
FPointerOnChangePopup(Self);
OnComboBoxExit(Sender);
end;
procedure TTransparentComboBox.ItemSelect(Index: Integer);
begin
if (Index > -1) and (Index <= FItems.Count - 1) then
begin
FTransparentInput.Text := FItems[Index];
SetFItemIndex(Index);
if FScrollChoices.Content.ChildrenCount > Index then
ShowItemSelect(FScrollChoices.Content.Children[Index]);
end
else
begin
ResetItemSelect();
FTransparentInput.Clear;
end;
end;
procedure TTransparentComboBox.ResetItemSelect();
begin
if Assigned(FLabelItemSelect) then
begin
FLabelItemSelect.Visible := False;
FLabelItemSelect := nil;
end;
if Assigned(FBackgroundItemSelect) then
begin
FBackgroundItemSelect.Visible := False;
FBackgroundItemSelect := nil;
end;
end;
procedure TTransparentComboBox.ShowItemSelect(Sender: TObject);
begin
ResetItemSelect();
FBackgroundItemSelect := TRectangle.Create(Self);
TRectangle(Sender).AddObject(FBackgroundItemSelect);
FBackgroundItemSelect.Align := TAlignLayout.Client;
FBackgroundItemSelect.Stroke.Kind := TBrushKind.None;
FBackgroundItemSelect.Fill.Color := TAlphaColor($FFE4EDF8);
FBackgroundItemSelect.Cursor := crHandPoint;
FBackgroundItemSelect.HitTest := False;
FLabelItemSelect := TLabel.Create(Self);
FBackgroundItemSelect.AddObject(FLabelItemSelect);
FLabelItemSelect.Align := TAlignLayout.Client;
FLabelItemSelect.HitTest := False;
FLabelItemSelect.Margins.Left := 15;
FLabelItemSelect.Margins.Right := 15;
FLabelItemSelect.StyledSettings := [];
FLabelItemSelect.TextSettings := FTransparentInput.TextSettings;
FLabelItemSelect.TextSettings.FontColor := TAlphaColor($FF1867C0);
FLabelItemSelect.HitTest := False;
FLabelItemSelect.Text := FItems[TRectangle(Sender).Tag];
end;
function TTransparentComboBox.Text: String;
begin
if (Self.ItemIndex > -1) and (FItems.Count > Self.ItemIndex) then
Result := FItems[Self.ItemIndex]
else
Result := '';
end;
procedure TTransparentComboBox.ValidateText;
begin
FTransparentInput.ValidateText();
end;
function TTransparentComboBox.GetFItems: TStringList;
begin
Result := FItems;
end;
function TTransparentComboBox.GetFOnClick: TNotifyEvent;
begin
Result := FLayoutClick.OnClick;
end;
function TTransparentComboBox.GetFOnDblClick: TNotifyEvent;
begin
Result := FLayoutClick.OnDblClick;
end;
function TTransparentComboBox.GetFOnEnter: TNotifyEvent;
begin
Result := FTransparentInput.OnEnter;
end;
function TTransparentComboBox.GetFOnExit: TNotifyEvent;
begin
Result := FTransparentInput.OnExit;
end;
function TTransparentComboBox.GetFOnMouseDown: TMouseEvent;
begin
Result := FLayoutClick.OnMouseDown;
end;
function TTransparentComboBox.GetFOnMouseEnter: TNotifyEvent;
begin
Result := FLayoutClick.OnMouseEnter;
end;
function TTransparentComboBox.GetFOnMouseLeave: TNotifyEvent;
begin
Result := FLayoutClick.OnMouseLeave;
end;
function TTransparentComboBox.GetFOnMouseMove: TMouseMoveEvent;
begin
Result := FLayoutClick.OnMouseMove;
end;
function TTransparentComboBox.GetFOnMouseUp: TMouseEvent;
begin
Result := FLayoutClick.OnMouseUp;
end;
function TTransparentComboBox.GetFOnMouseWheel: TNotifyEvent;
begin
Result := FScrollChoices.OnVScrollChange;
end;
procedure TTransparentComboBox.SetFItems(const Value: TStringList);
begin
SetFItemIndex(-1);
FItems.Clear;
FItems.AddStrings(Value);
FItemsChanged := True;
FItemsCount := 0;
end;
procedure TTransparentComboBox.SetFOnClick(const Value: TNotifyEvent);
begin
FLayoutClick.OnClick := Value;
end;
procedure TTransparentComboBox.SetFOnDblClick(const Value: TNotifyEvent);
begin
FLayoutClick.OnDblClick := Value;
end;
procedure TTransparentComboBox.SetFOnEnter(const Value: TNotifyEvent);
begin
FTransparentInput.OnEnter := Value;
end;
procedure TTransparentComboBox.SetFOnExit(const Value: TNotifyEvent);
begin
FTransparentInput.OnExit := Value;
end;
procedure TTransparentComboBox.SetFOnMouseDown(const Value: TMouseEvent);
begin
FLayoutClick.OnMouseDown := Value;
end;
procedure TTransparentComboBox.SetFOnMouseEnter(const Value: TNotifyEvent);
begin
FLayoutClick.OnMouseEnter := Value;
end;
procedure TTransparentComboBox.SetFOnMouseLeave(const Value: TNotifyEvent);
begin
FLayoutClick.OnMouseLeave := Value;
end;
procedure TTransparentComboBox.SetFOnMouseMove(const Value: TMouseMoveEvent);
begin
FLayoutClick.OnMouseMove := Value;
end;
procedure TTransparentComboBox.SetFOnMouseUp(const Value: TMouseEvent);
begin
FLayoutClick.OnMouseUp := Value;
end;
procedure TTransparentComboBox.SetFOnMouseWheel(const Value: TNotifyEvent);
begin
FScrollChoices.OnVScrollChange := Value;
end;
procedure TTransparentComboBox.SetFComboBoxSelectedColor(const Value: TAlphaColor);
begin
FTransparentInput.SelectedColor := Value;
end;
function TTransparentComboBox.GetFComboBoxSelectedColor: TAlphaColor;
begin
Result := FTransparentInput.SelectedColor;
end;
procedure TTransparentComboBox.SetFCursor(const Value: TCursor);
begin
FLayoutClick.Cursor := Value;
end;
function TTransparentComboBox.GetFCursor: TCursor;
begin
Result := FLayoutClick.Cursor;
end;
function TTransparentComboBox.GetFTextPrompt: String;
begin
Result := FTransparentInput.TextPrompt;
end;
function TTransparentComboBox.GetFTextSettings: TTextSettings;
begin
Result := FTransparentInput.TextSettings;
end;
procedure TTransparentComboBox.SetFTextPrompt(const Value: String);
begin
FTransparentInput.TextPrompt := Value;
end;
procedure TTransparentComboBox.SetFTextSettings(const Value: TTextSettings);
begin
FTransparentInput.TextSettings := Value;
end;
function TTransparentComboBox.GetFItemIndex: Integer;
begin
Result := FItemIndex;
end;
procedure TTransparentComboBox.SetFItemIndex(const Value: Integer);
begin
if (Value < FItems.Count) then
FItemIndex := Value;
end;
function TTransparentComboBox.GetFCardChoicesHeight: Single;
begin
Result := FCardChoices.Height;
end;
function TTransparentComboBox.GetFComboBoxAlign: TComboBoxAlign;
begin
Result := TComboBoxAlign.Top;
if FCardChoices.Align = TAlignLayout.Bottom then
Result := TComboBoxAlign.Top
else if FCardChoices.Align = TAlignLayout.Top then
Result := TComboBoxAlign.Bottom;
end;
function TTransparentComboBox.GetFComboBoxBackgroudColor: TBrush;
begin
Result := FTransparentInput.BackgroudColor;
end;
procedure TTransparentComboBox.SetFComboBoxBackgroudColor(const Value: TBrush);
begin
FTransparentInput.BackgroudColor := Value;
FCardChoices.Color := Value;
end;
function TTransparentComboBox.Select(ItemString: String = ''): String;
begin
Result := '';
if not ItemString.Equals('') then
Self.ItemIndex := FItems.IndexOf(ItemString);
if (Self.ItemIndex > -1) and (FItems.Count > Self.ItemIndex) then
Result := FItems[Self.ItemIndex];
ItemSelect(ItemIndex);
end;
function TTransparentComboBox.Select(ItemIndex: Integer = -1): Integer;
begin
if ItemIndex <> -1 then
Self.ItemIndex := ItemIndex;
Result := Self.ItemIndex;
ItemSelect(ItemIndex);
end;
procedure TTransparentComboBox.SetFCardChoicesHeight(const Value: Single);
begin
FCardChoices.Height := Value;
end;
procedure TTransparentComboBox.SetFComboBoxAlign(const Value: TComboBoxAlign);
begin
if Value = TComboBoxAlign.Top then
begin
FCardChoices.Align := TAlignLayout.Bottom;
FCardChoices.Margins.Bottom := FTransparentInput.Height;
FTransparentInput.IconData.Data := 'M7.41,15.41L12,10.83L16.59,15.41L18,14L12,8L6,14L7.41,15.41Z';
FCardChoices.ElevationDistance := 7;
end
else if Value = TComboBoxAlign.Bottom then
begin
FCardChoices.Align := TAlignLayout.Top;
FCardChoices.Margins.Top := FTransparentInput.Height;
FTransparentInput.IconData.Data := 'M7.41,8.58L12,13.17L16.59,8.58L18,10L12,16L6,10L7.41,8.58Z';
FCardChoices.ElevationDistance := 0;
end;
end;
end.
|
unit ThreadQueryU;
interface
uses
Windows, Classes, SysUtils, db, grids, dmThreadU;
type
ThreadQuery = class(TThread)
private
dmThread : TdmThread;
dtsResults : TDataSource;
FDatabaseName : String;
FSql : String;
FGrid : TStringGrid;
FUserName, FPassword : String;
procedure DisplayResults;
procedure SetColumns;
procedure WriteGridRow;
procedure AddRow;
{ Private declarations }
protected
procedure Execute; override;
public
constructor Create(SQL : String; dts : TDataSource; DB_Name : String;
username : String; password : String); overload;
constructor Create(SQL : String; grid : TStringGrid; DB_Name : String;
username : String; password : String); overload;
destructor Destroy; override;
end;
implementation
{ Important: Methods and properties of objects in VCL can only be used in a
method called using Synchronize, for example,
Synchronize(UpdateCaption);
and UpdateCaption could look like,
procedure ThreadQuery.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end; }
{ ThreadQuery }
constructor ThreadQuery.Create(SQL: String; dts : TDataSource; DB_Name : String;
username : String; password : String);
begin
inherited Create(true);
FSql := SQL;
FDatabaseName := DB_Name;
FUsername := username;
FPassword := password;
FGrid := nil;
dtsResults := dts;
Resume;
end;
procedure ThreadQuery.AddRow;
begin
FGrid.RowCount := FGrid.RowCount + 1;
end;
constructor ThreadQuery.Create(SQL: String; grid: TStringGrid; DB_Name,
username, password: String);
begin
inherited Create(true);
FSql := SQL;
FDatabaseName := DB_Name;
FUsername := username;
FPassword := password;
dtsResults := nil;
FGrid := grid;
Resume;
end;
destructor ThreadQuery.Destroy;
begin
dmThread.Free;
inherited Destroy;
end;
procedure ThreadQuery.DisplayResults;
begin
dtsResults.DataSet := dmThread.IBQuery1;
end;
procedure ThreadQuery.Execute;
var
i : Integer;
begin
dmThread := TdmThread.Create(FDatabaseName, FUserName, FPassword);
{ Place thread code here }
for i := 1 to 10 do
try
dmThread.IBQuery1.Close;
dmThread.IBQuery1.SQL.Clear;
dmThread.IBQuery1.SQL.Add(FSQL);
dmThread.IBQuery1.Open;
if FGrid = nil then
Synchronize(DisplayResults)
else
begin
Synchronize(SetColumns);
while not dmThread.IBQuery1.Eof do
begin
Synchronize(WriteGridRow);
dmThread.IBQuery1.Next;
if not dmThread.IBQuery1.Eof then
Synchronize(AddRow);
end;
end;
except
on E : Exception do
MessageBox(0, PChar('Database error = ' + E.Message), 'Error', MB_OK);
end;
end;
procedure ThreadQuery.SetColumns;
var
i : Integer;
begin
with dmThread.IBQuery1 do
begin
FGrid.ColCount := FieldDefs.Count;
for i := 0 to Pred(FieldDefs.Count) do
FGrid.Cells[i, 0] := FieldDefs[i].DisplayName;
end;
end;
procedure ThreadQuery.WriteGridRow;
var
i, row : Integer;
begin
row := FGrid.RowCount - 1;
with dmThread.IBQuery1 do
for i := 0 to Pred(FieldDefs.Count) do
FGrid.Cells[i, row] := Fields[i].AsString;
end;
end.
|
unit uRigControl;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Process, ExtCtrls, lNetComponents, lnet;
type TRigMode = record
mode : String[10];
pass : word;
end;
type TVFO = (VFOA,VFOB);
type
TExplodeArray = Array of String;
type TRigControl = class
rcvdFreqMode : TLTCPComponent;
rigProcess : TProcess;
tmrRigPoll : TTimer;
private
fRigCtldPath : String;
fRigCtldArgs : String;
fRunRigCtld : Boolean;
fMode : TRigMode;
fFreq : Double;
fRigPoll : Word;
fRigCtldPort : Word;
fLastError : String;
fRigId : Word;
fRigDevice : String;
fDebugMode : Boolean;
fRigCtldHost : String;
fVFO : TVFO;
RigCommand : TStringList;
fRigSendCWR : Boolean;
function RigConnected : Boolean;
function StartRigctld : Boolean;
function Explode(const cSeparator, vString: String): TExplodeArray;
procedure OnReceivedRcvdFreqMode(aSocket: TLSocket);
procedure OnRigPollTimer(Sender: TObject);
public
constructor Create;
destructor Destroy; override;
property DebugMode : Boolean read fDebugMode write fDebugMode;
property RigCtldPath : String read fRigCtldPath write fRigCtldPath;
//path to rigctld binary
property RigCtldArgs : String read fRigCtldArgs write fRigCtldArgs;
//rigctld command line arguments
property RunRigCtld : Boolean read fRunRigCtld write fRunRigCtld;
//run rigctld command before connection
property RigId : Word read fRigId write fRigId;
//hamlib rig id
property RigDevice : String read fRigDevice write fRigDevice;
//port where is rig connected
property RigCtldPort : Word read fRigCtldPort write fRigCtldPort;
// port where rigctld is listening to connecions, default 4532
property RigCtldHost : String read fRigCtldHost write fRigCtldHost;
//host where is rigctld running
property Connected : Boolean read RigConnected;
//connect rigctld
property RigPoll : Word read fRigPoll write fRigPoll;
//poll rate in miliseconds
property RigSendCWR : Boolean read fRigSendCWR write fRigSendCWR;
//send CWR instead of CW
property LastError : String read fLastError;
//last error during operation
function GetCurrVFO : TVFO;
function GetModePass : TRigMode;
function GetModeOnly : String;
function GetFreqHz : Double;
function GetFreqKHz : Double;
function GetFreqMHz : Double;
function GetModePass(vfo : TVFO) : TRigMode; overload;
function GetModeOnly(vfo : TVFO) : String; overload;
function GetFreqHz(vfo : TVFO) : Double; overload;
function GetFreqKHz(vfo : TVFO) : Double; overload;
function GetFreqMHz(vfo : TVFO) : Double; overload;
procedure SetCurrVFO(vfo : TVFO);
procedure SetModePass(mode : TRigMode);
procedure SetFreqKHz(freq : Double);
procedure ClearRit;
procedure Restart;
end;
implementation
constructor TRigControl.Create;
begin
RigCommand := TStringList.Create;
fDebugMode := DebugMode;
if DebugMode then Writeln('In create');
fRigCtldHost := 'localhost';
fRigCtldPort := 4532;
fRigPoll := 500;
fRunRigCtld := True;
rcvdFreqMode := TLTCPComponent.Create(nil);
rigProcess := TProcess.Create(nil);
tmrRigPoll := TTimer.Create(nil);
tmrRigPoll.Enabled := False;
if DebugMode then Writeln('All objects created');
tmrRigPoll.OnTimer := @OnRigPollTimer;
rcvdFreqMode.OnReceive := @OnReceivedRcvdFreqMode
end;
function TRigControl.StartRigctld : Boolean;
var
cmd : String;
begin
cmd := fRigCtldPath + ' ' +RigCtldArgs;
{
cmd := StringReplace(cmd,'%m',IntToStr(fRigId),[rfReplaceAll, rfIgnoreCase]);
cmd := StringReplace(cmd,'%r',fRigDevice,[rfReplaceAll, rfIgnoreCase]);
cmd := StringReplace(cmd,'%t',IntToStr(fRigCtldPort),[rfReplaceAll, rfIgnoreCase]);
}
if DebugMode then Writeln('Starting RigCtld ...');
if fDebugMode then Writeln(cmd);
rigProcess.CommandLine := cmd;
try
rigProcess.Execute;
sleep(1000)
except
on E : Exception do
begin
if fDebugMode then
Writeln('Starting rigctld E: ',E.Message);
fLastError := E.Message;
Result := False;
exit
end
end;
tmrRigPoll.Interval := fRigPoll;
tmrRigPoll.Enabled := True;
Result := True
end;
function TRigControl.RigConnected : Boolean;
const
ERR_MSG = 'Could not connect to rigctld';
begin
if fDebugMode then
begin
Writeln('');
Writeln('Settings:');
Writeln('-----------------------------------------------------');
Writeln('RigCtldPath:',RigCtldPath);
Writeln('RigCtldArgs:',RigCtldArgs);
Writeln('RunRigCtld: ',RunRigCtld);
Writeln('RigDevice: ',RigDevice);
Writeln('RigCtldPort:',RigCtldPort);
Writeln('RigCtldHost:',RigCtldHost);
Writeln('RigPoll: ',RigPoll);
Writeln('RigSendCWR: ',RigSendCWR);
Writeln('RigId: ',RigId);
Writeln('')
end;
if fRunRigCtld then
begin
if not StartRigctld then
begin
if fDebugMode then Writeln('rigctld failed to start!');
Result := False;
exit
end
end;
if fDebugMode then Writeln('rigctld started!');
rcvdFreqMode.Host := fRigCtldHost;
rcvdFreqMode.Port := fRigCtldPort;
//rcvdFreqMode.Connect(fRigCtldHost,fRigCtldPort);
if rcvdFreqMode.Connect(fRigCtldHost,fRigCtldPort) then
begin
if fDebugMode then Writeln('Connected to ',fRigCtldHost,':',fRigCtldPort);
result := True;
tmrRigPoll.Interval := fRigPoll;
tmrRigPoll.Enabled := True
end
else begin
if fDebugMode then Writeln('NOT connected to ',fRigCtldHost,':',fRigCtldPort);
fLastError := ERR_MSG;
Result := False
end
end;
procedure TRigControl.SetCurrVFO(vfo : TVFO);
begin
case vfo of
VFOA : RigCommand.Add('V VFOA');//sendCommand.SendMessage('V VFOA'+LineEnding);
VFOB : RigCommand.Add('V VFOB')//sendCommand.SendMessage('V VFOB'+LineEnding);
end //case
end;
procedure TRigControl.SetModePass(mode : TRigMode);
begin
if (mode.mode='CW') and fRigSendCWR then
mode.mode := 'CWR';
RigCommand.Add('M '+mode.mode+' '+IntToStr(mode.pass))
end;
procedure TRigControl.SetFreqKHz(freq : Double);
begin
RigCommand.Add('F '+FloatToStr(freq*1000))
end;
procedure TRigControl.ClearRit;
begin
RigCommand.Add('J 0')
end;
function TRigControl.GetCurrVFO : TVFO;
begin
result := fVFO
end;
function TRigControl.GetModePass : TRigMode;
begin
result := fMode
end;
function TRigControl.GetModeOnly : String;
begin
result := fMode.mode
end;
function TRigControl.GetFreqHz : Double;
begin
result := fFreq
end;
function TRigControl.GetFreqKHz : Double;
begin
result := fFreq / 1000
end;
function TRigControl.GetFreqMHz : Double;
begin
result := fFreq / 1000000
end;
function TRigControl.GetModePass(vfo : TVFO) : TRigMode;
var
old_vfo : TVFO;
begin
if fVFO <> vfo then
begin
old_vfo := fVFO;
SetCurrVFO(vfo);
Sleep(fRigPoll*2);
result := fMode;
SetCurrVFO(old_vfo)
end;
result := fMode
end;
function TRigControl.GetModeOnly(vfo : TVFO) : String;
var
old_vfo : TVFO;
begin
if fVFO <> vfo then
begin
old_vfo := fVFO;
SetCurrVFO(vfo);
Sleep(fRigPoll*2);
result := fMode.mode;
SetCurrVFO(old_vfo)
end;
result := fMode.mode
end;
function TRigControl.GetFreqHz(vfo : TVFO) : Double;
var
old_vfo : TVFO;
begin
if fVFO <> vfo then
begin
old_vfo := fVFO;
SetCurrVFO(vfo);
Sleep(fRigPoll*2);
result := fFreq;
SetCurrVFO(old_vfo)
end;
result := fFreq
end;
function TRigControl.GetFreqKHz(vfo : TVFO) : Double;
var
old_vfo : TVFO;
begin
if fVFO <> vfo then
begin
old_vfo := fVFO;
SetCurrVFO(vfo);
Sleep(fRigPoll*2);
result := fFreq/1000;
SetCurrVFO(old_vfo)
end;
result := fFreq
end;
function TRigControl.GetFreqMHz(vfo : TVFO) : Double;
var
old_vfo : TVFO;
begin
if fVFO <> vfo then
begin
old_vfo := fVFO;
SetCurrVFO(vfo);
Sleep(fRigPoll*2);
result := fFreq/1000000;
SetCurrVFO(old_vfo)
end;
result := fFreq
end;
procedure TRigControl.OnReceivedRcvdFreqMode(aSocket: TLSocket);
var
msg : String;
tmp : String;
poz : Word;
wdt : Integer;
a : TExplodeArray;
i : Integer;
f : Double;
begin
if aSocket.GetMessage(msg) > 0 then
begin
//Writeln('Whole MSG:|',msg,'|');
msg := trim(msg);
a := Explode(LineEnding,msg);
for i:=0 to Length(a)-1 do
begin
//Writeln('a[i]:',a[i]);
if a[i]='' then Continue;
if TryStrToFloat(a[i],f) then
begin
if f>20000 then
fFReq := f
else
fMode.pass := round(f);
Continue
end;
//if (a[i][1] in ['A'..'Z']) and (a[i][1] <> 'V' ) then //receiving mode info
//FT-920 returned VFO as MEM
if (a[i][1] in ['A'..'Z']) and (a[i][1] <> 'V' ) and (a[i]<>'MEM') then//receiving mode info
begin
if Pos('RPRT',a[i]) = 0 then
begin
fMode.mode := a[i];
if (fMode.mode = 'USB') or (fMode.mode = 'LSB') then
fMode.mode := 'SSB';
if fMode.mode = 'CWR' then
fMode.mode := 'CW';
end
end;
if (a[i][1] = 'V') then
begin
if Pos('VFOB',msg) > 0 then
fVFO := VFOB
else
fVFO := VFOA
end
end;
{
if (Length(a)<4) then
begin
for i:=0 to Length(a)-1 do
Writeln('a[',i,']:',a[i]);
if (msg[1] = 'V') then
begin
if Pos('VFOB',msg) > 0 then
fVFO := VFOB
else
fVFO := VFOA
end;
if (msg[1] in ['A'..'Z']) and (msg[1] <> 'V' ) then //receiving mode info
begin
if Pos('RPRT',msg) = 0 then
begin
tmp := copy(msg,1,Pos(LineEnding,msg)-1);
fMode.mode := trim(tmp);
if (fMode.mode = 'USB') or (fMode.mode = 'LSB') then
fMode.mode := 'SSB';
tmp := trim(copy(msg,Pos(LineEnding,msg)+1,5));
if not TryStrToInt(tmp,wdt) then
begin
fMode.pass := 0;
fLastError := 'Could not get mode width from radio';
if fDebugMode then Writeln(fLastError,':',msg,'*')
end
else
fMode.pass := wdt
end
end
else begin
if (msg[1] <> 'V' ) then
begin
tmp := trim(msg);
if not TryStrToFloat(tmp,fFreq) then
begin
fFreq := 0;
fLastError := 'Could not get freq from radio';
if fDebugMode then Writeln(fLastError,':',msg,'*')
end
end
end
end
else begin
if not TryStrToFloat(a[0],fFreq) then
begin
fFreq := 0;
fLastError := 'Could not get freq from radio';
if fDebugMode then Writeln(fLastError,':',msg,'*',a[0],'*')
end;
if Pos('RPRT',a[1]) = 0 then
begin
fMode.mode := trim(a[1]);
if (fMode.mode = 'USB') or (fMode.mode = 'LSB') then
fMode.mode := 'SSB';
if fMode.mode = 'CWR' then
fMode.mode := 'CW';
tmp := a[2];
if not TryStrToInt(tmp,wdt) then
begin
fMode.pass := 0;
fLastError := 'Could not get mode width from radio';
if fDebugMode then Writeln(fLastError,':',msg,'*')
end
else
fMode.pass := wdt
end;
if Pos('VFOB',a[3]) > 0 then
fVFO := VFOB
else
fVFO := VFOA
end;}
{ Writeln('-----');
Writeln('VFO :',fVFO);
Writeln('FREQ :',fFreq);
Writeln('Mode :',fMode.mode);
Writeln('Bandwidth:',fMode.pass);
Writeln('-----')}
end
end;
procedure TRigControl.OnRigPollTimer(Sender: TObject);
var
cmd : String;
i : Integer;
begin
if (RigCommand.Text<>'') then
begin
for i:=0 to RigCommand.Count-1 do
begin
sleep(100);
cmd := RigCommand.Strings[i]+LineEnding;
rcvdFreqMode.SendMessage(cmd);
if DebugMode then Writeln('Sending: '+cmd)
end;
RigCommand.Clear
end
else begin
rcvdFreqMode.SendMessage('fmv'+LineEnding)
end
end;
procedure TRigControl.Restart;
var
excode : Integer;
begin
rigProcess.Terminate(excode);
tmrRigPoll.Enabled := False;
rcvdFreqMode.Disconnect();
RigConnected
end;
function TRigControl.Explode(const cSeparator, vString: String): TExplodeArray;
var
i: Integer;
S: String;
begin
S := vString;
SetLength(Result, 0);
i := 0;
while Pos(cSeparator, S) > 0 do begin
SetLength(Result, Length(Result) +1);
Result[i] := Copy(S, 1, Pos(cSeparator, S) -1);
Inc(i);
S := Copy(S, Pos(cSeparator, S) + Length(cSeparator), Length(S));
end;
SetLength(Result, Length(Result) +1);
Result[i] := Copy(S, 1, Length(S))
end;
destructor TRigControl.Destroy;
var
excode : Integer=0;
begin
inherited;
if DebugMode then Writeln(1);
if fRunRigCtld then
begin
if rigProcess.Running then
begin
if DebugMode then Writeln('1a');
rigProcess.Terminate(excode)
end
end;
if DebugMode then Writeln(2);
tmrRigPoll.Enabled := False;
if DebugMode then Writeln(3);
rcvdFreqMode.Disconnect();
if DebugMode then Writeln(4);
FreeAndNil(rcvdFreqMode);
if DebugMode then Writeln(5);
FreeAndNil(rigProcess);
FreeAndNil(RigCommand);
if DebugMode then Writeln(6)
end;
end.
|
unit Repr;
//{$MODE Delphi}
//# BEGIN TODO Completed by: author name, id.nr., date
{ E.I.R. van Delden, 0618959, 06-06-07 }
//# END TODO
//------------------------------------------------------------------------------
// This unit contains facilities for mapping formula trees to textual
// representations.
//------------------------------------------------------------------------------
interface
uses
Classes,
Nodes;
function NodesToPrefix(ANode: TNode): String;
// returns a standard prefix representation of the formula tree with root ANode
function NodesToStringlist(ANode: TNode): TStringList;
// returns the same standard prefix representation as NodesToPrefix, but in the
// form of a string list with indentation.
type
//----------------------------------------------------------------------------
// TRepr is an abstract base class which provides facilities for mapping
// a formula tree to an infix representation.
// - function Rep(ANode, I) returns the string parts needed for the textual
// representation of the formula with root ANode.
// E.g. if ANode corresponds to the 2-ary operator And, the results would be
// - Rep(ANode, 0) = '('
// Rep(ANode, 1) = '/\'
// Rep(ANode, 2) = ')'
// Rep is abstract in class TRepr, but will be instantiated in language-
// specific subclasses.
// - function TreeToString recursively produces the entire textual
// representation of the formula tree with root ANode, using Rep for each
// in the tree.
//----------------------------------------------------------------------------
TRepr =
class(TObject)
public
function Rep(ANode: TNode; I: Integer): String; virtual; abstract;
// pre: ANode <> nil, 0 <= I < ANode.GetNrOfSons
// ret: the I-th substring in the textual representation of the operator
// ANode.OpName
function TreeToString(ANode: TNode): String; virtual;
// pre: ANode <> nil
// ret: textual representation of formula tree with root ANode
end;
//----------------------------------------------------------------------------
// TStandardRepr provides a particular implementation of Rep in the form of a
// list (indexed by ANode.OpName) of array of String.
// For a particular language the list can be built up by means of procedure
// AddRep.
//----------------------------------------------------------------------------
TStandardRepr =
class(TRepr)
protected
FList: TStringList;
public
constructor Create;
destructor Destroy; override;
function Rep(ANode: TNode; I: Integer): String; override;
procedure AddRep(ANodeClass: TNodeClass; APrio: Integer;
ASepList: array of String);
end;
implementation //===============================================================
uses
StrUtils, SysUtils;
function Ind(AInd: Integer): String;
begin
Result := DupeString(' ', AInd);
end;
function NodesToPrefix(ANode: TNode): String;
var
I: Integer;
begin
Result := ANode.OpName;
if ANode.HasData
then Result := Result + '{' + ANode.GetData + '}';
if ANode.GetNrofSons > 0 then
begin
Result := Result + '[' + NodesToPrefix(ANode.GetSon(0));
for I := 1 to ANode.GetNrofSons - 1 do
Result := Result +',' + NodesToPrefix(ANode.GetSon(I));
Result := Result + ']';
end;
end;
function NodesToStringList(ANode: TNode): TStringList;
var
R: TStringList;
procedure NTSL(ANode: TNode; AInd: Integer);
var
I: Integer;
S: String;
begin
S := ANode.OPName;
if ANode.HasData
then S := S + '[' + ANode.GetData + ']';
R.AddObject(Ind(AInd) + S, ANode);
for I := 0 to ANode.GetNrOfSons - 1
do NTSL(ANode.GetSon(I), AInd + 1);
end;{NTSL}
begin{NodesToStringList}
R := TStringList.Create;
NTSL(ANode, 0);
Result := R;
end;{NodesToStringList}
{ TRepr }
function TRepr.TreeToString(ANode: TNode): String;
begin
//# BEGIN TODO body of TRepr.TreeToString
// Replace the follwing line by your own code
// pre: ANode <> nil
// ret: textual representation of formula tree with root ANode
Assert( ANode.HasData, 'TRepr.TreeToString.pre failed; no data');
{
case ANode.GetNrofSons of
0: begin
Rep(ANode, 0); // return first sign
ANode.
end; // end 0
1: begin
TreeToString( ANode.GetSon(0)); // Recurse on single node
end; // end 1
2: begin
TreeToString( ANode.GetSon(0) ); // Recurse Left
TreeToString( ANode.GetSon(1) ); // Recurse Right
end; // end 2
end; // end case
// Leaf }
Result := '???';
//# END TODO
end;
{ TOpRepr; auxiliary class used by TStandardRepr}
type
TOpRepr =
class(TObject)
FPrio: Integer;
FSepList: array of String;
constructor Create(APrio: Integer; ASepList: array of String);
end;
constructor TOpRepr.Create(APrio: Integer; ASepList: array of String);
var
I: Integer;
begin
inherited Create;
FPrio := APrio;
SetLength(FSepList, Length(ASepList));
for I := 0 to Length(ASepList) - 1 do
FSepList[I] := ASepList[I];
end;
{ TStandardRepr }
procedure TStandardrepr.AddRep(ANodeClass: TNodeClass; APrio: Integer;
ASepList: array of String);
var
VOpName: String;
begin
VOpName := ANodeClass.OpName;
if FList.IndexOf(VOpName) <> -1 then
raise Exception.Create(
'In TStandardRepr.AddRep(' + VOpName +
',...): Attempt to add opname more than once' );
if ANodeClass.GetNrofSons + 1 <> Length(ASepList) then
raise Exception.Create(
'In TStandardRepr.AddRep(' + VOpName +
',...): Wrong length of separator list' );
FList.AddObject(VOpName, TOpRepr.Create(APrio, ASepList));
end;
constructor TStandardRepr.Create;
begin
inherited Create;
FList := TStringList.Create;
end;
destructor TStandardRepr.Destroy;
begin
FList.Free;
inherited Destroy;
end;
function TStandardRepr.Rep(ANode: TNode; I: Integer): String;
var
VOpRepr: TOpRepr;
VI: Integer;
begin
VI := FList.IndexOf(ANode.OpName);
if VI = -1
then raise Exception.Create(
'Unknown OpName in TStandardRepr.Rep(' + ANode.OpName + ',' +
IntToStr(I) + ')' );
VOpRepr := FList.Objects[VI] as TOpRepr;
if (0 <= I) and (I <= High(VOpRepr.FSepList))
then Result := VOpRepr.FSepList[I]
else raise Exception.Create(
'Invalid Index in TStandardRepr.Rep(' + ANode.OpName + ',' +
IntToStr(I) + ')' );
end;
end.
|
{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
{
Rev 1.6 1/19/05 11:18:16 AM RLebeau
bug fix for GetConnectionID()
Rev 1.5 2004.02.03 5:45:38 PM czhower
Name changes
Rev 1.4 2004.01.22 5:58:58 PM czhower
IdCriticalSection
Rev 1.3 1/21/2004 4:03:20 PM JPMugaas
InitComponent
Rev 1.2 2003.10.17 6:15:02 PM czhower
consts removed
Rev 1.1 2003.10.14 1:31:14 PM czhower
DotNet
Rev 1.0 3/22/2003 10:59:20 PM BGooijen
Initial check in.
ServerIntercept to ease debugging, data/status are logged to a file
}
unit IdServerInterceptLogBase;
interface
{$i IdCompilerDefines.inc}
uses
IdIntercept, IdGlobal, IdLogBase, IdBaseComponent, Classes;
type
TIdServerInterceptLogBase = class(TIdServerIntercept)
protected
FLock: TIdCriticalSection;
FLogTime: Boolean;
FReplaceCRLF: Boolean;
//
FHasInit: Boolean; // BGO: can be removed later, see comment below (.Init)
procedure InitComponent; override;
public
procedure Init; override;
function Accept(AConnection: TComponent): TIdConnectionIntercept; override;
destructor Destroy; override;
procedure DoLogWriteString(const AText: string); virtual; abstract;
procedure LogWriteString(const AText: string); virtual;
published
property LogTime: Boolean read FLogTime write FLogTime default True;
property ReplaceCRLF: Boolean read FReplaceCRLF write FReplaceCRLF default true;
end;
TIdServerInterceptLogFileConnection = class(TIdLogBase) //BGO: i just love long class names <g>
protected
FServerInterceptLog:TIdServerInterceptLogBase;
procedure LogReceivedData(const AText, AData: string); override;
procedure LogSentData(const AText, AData: string); override;
procedure LogStatus(const AText: string); override;
function GetConnectionID: string; virtual;
end;
implementation
uses
IdIOHandlerSocket,
IdResourceStringsCore,
IdTCPConnection,
SysUtils;
{ TIdServerInterceptLogFile }
function TIdServerInterceptLogBase.Accept(AConnection: TComponent): TIdConnectionIntercept;
begin
Result := TIdServerInterceptLogFileConnection.Create(nil);
TIdServerInterceptLogFileConnection(Result).FServerInterceptLog := Self;
TIdServerInterceptLogFileConnection(Result).LogTime := FLogTime;
TIdServerInterceptLogFileConnection(Result).ReplaceCRLF := FReplaceCRLF;
TIdServerInterceptLogFileConnection(Result).Active := True;
end;
procedure TIdServerInterceptLogBase.InitComponent;
begin
inherited InitComponent;
FReplaceCRLF := True;
FLogTime := True;
FLock := TIdCriticalSection.Create;
end;
destructor TIdServerInterceptLogBase.Destroy;
begin
FreeAndNil(FLock);
inherited Destroy;
end;
procedure TIdServerInterceptLogBase.Init;
begin
end;
procedure TIdServerInterceptLogBase.LogWriteString(const AText: string);
begin
if Length(AText) > 0 then begin
FLock.Enter;
try
if not FHasInit then begin
Init; // BGO: This is just a hack, TODO find out where to call init
FHasInit := True;
end;
DoLogWriteString(AText);
finally
FLock.Leave;
end;
end;
end;
{ TIdServerInterceptLogFileConnection }
procedure TIdServerInterceptLogFileConnection.LogReceivedData(const AText, AData: string);
begin
FServerInterceptLog.LogWriteString(GetConnectionID + ' ' + RSLogRecv + AText + ': ' + AData + EOL); {Do not translate}
end;
procedure TIdServerInterceptLogFileConnection.LogSentData(const AText, AData: string);
begin
FServerInterceptLog.LogWriteString(GetConnectionID + ' ' + RSLogSent + AText + ': ' + AData + EOL); {Do not translate}
end;
procedure TIdServerInterceptLogFileConnection.LogStatus(const AText: string);
begin
FServerInterceptLog.LogWriteString(GetConnectionID + ' ' + RSLogStat + AText + EOL);
end;
function TIdServerInterceptLogFileConnection.GetConnectionID: string;
var
LSocket: TIdIOHandlerSocket;
begin
if FConnection is TIdTCPConnection then begin
LSocket := TIdTCPConnection(FConnection).Socket;
if (LSocket <> nil) and (LSocket.Binding <> nil) then begin
with LSocket.Binding do begin
Result := PeerIP + ':' + IntToStr(PeerPort);
end;
Exit;
end;
end;
Result := '0.0.0.0:0';
end;
end.
|
unit IWDBStdCtrls;
{PUBDIST}
interface
uses
{$IFDEF Linux}QDBCtrls,{$ELSE}DBCtrls,{$ENDIF}
{$IFDEF Linux}QControls,{$ELSE}Controls,{$ENDIF}
Classes, DB,
IWControl, IWCompCheckbox, IWCompEdit, IWCompLabel, IWCompListbox, IWCompMemo,
IWCompText, IWHTMLTag, IWFileReference;
type
TIWDBCheckBox = class(TIWCustomCheckBox)
protected
FAutoEditable: Boolean;
FDataField: string;
FDataSource: TDataSource;
FValueChecked: string;
FValueUnchecked: string;
//
procedure Notification(AComponent: TComponent; AOperation: TOperation); override;
procedure SetDataField(const AValue: string);
procedure SetValue(const AValue: string); override;
public
constructor Create(AOwner: TComponent); override;
function RenderHTML: TIWHTMLTag; override;
published
//@@ AutoEditable if True will automatically set the Editable property to true when the dataset
//is in an editable mode (Edit, Insert) and set Editable to False when it is not in an editable
//mode.
property AutoEditable: Boolean read FAutoEditable write FAutoEditable;
property DataField: string read FDataField write SetDataField;
property DataSource: TDataSource read FDataSource write FDataSource;
property ValueChecked: string read FValueChecked write FValueChecked;
property ValueUnchecked: string read FValueUnchecked write FValueUnchecked;
end;
TIWDBComboBox = class(TIWCustomCombobox)
protected
FAutoEditable: Boolean;
FDataField: string;
FDataSource: TDataSource;
//
procedure Notification(AComponent: TComponent; AOperation: TOperation); override;
procedure SetValue(const AValue: string); override;
public
function RenderHTML: TIWHTMLTag; override;
published
//@@ AutoEditable if True will automatically set the Editable property to truw when the dataset
//is in an editable mode (Edit, Insert) and set Editable to False when it is not in an editable
//mode.
property AutoEditable: Boolean read FAutoEditable write FAutoEditable;
property DataField: string read FDataField write FDataField;
property DataSource: TDataSource read FDataSource write FDataSource;
property ItemIndex: Integer read FItemIndex write FItemIndex;
property Items;
property Sorted;
end;
TIWDBEdit = class(TIWCustomEdit)
protected
FAutoEditable: Boolean;
FDataField: string;
FDataSource: TDataSource;
//
procedure Notification(AComponent: TComponent; AOperation: TOperation); override;
procedure Paint; override;
procedure SetValue(const AValue: string); override;
public
function RenderHTML: TIWHTMLTag; override;
published
//@@ AutoEditable if True will automatically set the Editable property to truw when the dataset
//is in an editable mode (Edit, Insert) and set Editable to False when it is not in an editable
//mode.
property AutoEditable: Boolean read FAutoEditable write FAutoEditable;
property DataField: string read FDataField write FDataField;
property DataSource: TDataSource read FDataSource write FDataSource;
//@@ If True, this indicates that this field is to be used for password or other masked entry.
// When True, the field will not show the text the user is typing. Instead of the actual
// characters a single mask character such as * will be displayed. The actual character that is
// displayed is determined by the browser. This only affects display, and not the actual data
// that is available for use at run time.
//
// This is usually done to prevent people from obtaining a password simply by looking over the
// user's shoulder.
property PasswordPrompt: boolean read FPasswordPrompt write SetPasswordPrompt;
end;
TIWDBFile = class(TIWCustomFile)
protected
FDataField: string;
FDataSource: TDataSource;
//
procedure Notification(AComponent: TComponent; AOperation: TOperation); override;
procedure SetValue(const AValue: string); override;
published
property DataField: string read FDataField write FDataField;
property DataSource: TDataSource read FDataSource write FDataSource;
end;
TIWDBLabel = class(TIWCustomLabel)
protected
FDataField: string;
FDataSource: TDataSource;
//
procedure Notification(AComponent: TComponent; AOperation: TOperation); override;
procedure Paint; override;
public
function RenderHTML: TIWHTMLTag; override;
published
property AutoSize;
property DataField: string read FDataField write FDataField;
property DataSource: TDataSource read FDataSource write FDataSource;
end;
TIWDBListbox = class(TIWCustomListbox)
protected
FAutoEditable: Boolean;
FDataField: string;
FDataSource: TDataSource;
//
procedure Notification(AComponent: TComponent; AOperation: TOperation); override;
procedure SetValue(const AValue: string); override;
public
function RenderHTML: TIWHTMLTag; override;
published
//@@ AutoEditable if True will automatically set the Editable property to truw when the dataset
//is in an editable mode (Edit, Insert) and set Editable to False when it is not in an editable
//mode.
property AutoEditable: Boolean read FAutoEditable write FAutoEditable;
property DataField: string read FDataField write FDataField;
property DataSource: TDataSource read FDataSource write FDataSource;
property Items;
property ItemIndex: Integer read FItemIndex write FItemIndex;
property Sorted;
end;
TIWDBLookupComboBox = class(TIWCustomCombobox)
protected
FAutoEditable: Boolean;
FDataField: string;
FDataSource: TDataSource;
FKeyField: string;
FKeyItems: TStrings;
FListField: string;
FListSource: TDataSource;
//
procedure Notification(AComponent: TComponent; AOperation: TOperation); override;
procedure SetValue(const AValue: string); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function RenderHTML: TIWHTMLTag; override;
published
//@@ AutoEditable if True will automatically set the Editable property to truw when the dataset
//is in an editable mode (Edit, Insert) and set Editable to False when it is not in an editable
//mode.
property AutoEditable: Boolean read FAutoEditable write FAutoEditable;
property DataField: string read FDataField write FDataField;
property DataSource: TDataSource read FDataSource write FDataSource;
property KeyField: string read FKeyField write FKeyField;
property ListField: string read FListField write FListField;
property ListSource: TDataSource read FListSource write FListSource;
end;
TIWDBLookupListBox = class(TIWCustomListbox)
protected
FAutoEditable: Boolean;
FDataField: string;
FDataSource: TDataSource;
FKeyField: string;
FKeyItems: TStrings;
FListField: string;
FListSource: TDataSource;
//
procedure Notification(AComponent: TComponent; AOperation: TOperation); override;
procedure SetValue(const AValue: string); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function RenderHTML: TIWHTMLTag; override;
published
//@@ AutoEditable if True will automatically set the Editable property to truw when the dataset
//is in an editable mode (Edit, Insert) and set Editable to False when it is not in an editable
//mode.
property AutoEditable: Boolean read FAutoEditable write FAutoEditable;
property DataField: string read FDataField write FDataField;
property DataSource: TDataSource read FDataSource write FDataSource;
property KeyField: string read FKeyField write FKeyField;
property ListField: string read FListField write FListField;
property ListSource: TDataSource read FListSource write FListSource;
end;
TIWDBMemo = class(TIWCustomMemo)
protected
FAutoEditable: Boolean;
FDataField: string;
FDataSource: TDataSource;
//
procedure Notification(AComponent: TComponent; AOperation: TOperation); override;
procedure SetValue(const AValue: string); override;
public
function RenderHTML: TIWHTMLTag; override;
published
//@@ AutoEditable if True will automatically set the Editable property to truw when the dataset
//is in an editable mode (Edit, Insert) and set Editable to False when it is not in an editable
//mode.
property AutoEditable: Boolean read FAutoEditable write FAutoEditable;
property DataField: string read FDataField write FDataField;
property DataSource: TDataSource read FDataSource write FDataSource;
end;
TIWDBNavigator = class;
TIWDBNavImages = class(TPersistent)
protected
FDelete: TIWFileReference;
FPost: TIWFileReference;
FCancel: TIWFileReference;
FFirst: TIWFileReference;
FNext: TIWFileReference;
FInsert: TIWFileReference;
FEdit: TIWFileReference;
FRefresh: TIWFileReference;
FLast: TIWFileReference;
FPrior: TIWFileReference;
//
FDelete_Disabled: TIWFileReference;
FPost_Disabled: TIWFileReference;
FCancel_Disabled: TIWFileReference;
FFirst_Disabled: TIWFileReference;
FNext_Disabled: TIWFileReference;
FInsert_Disabled: TIWFileReference;
FEdit_Disabled: TIWFileReference;
FRefresh_Disabled: TIWFileReference;
FLast_Disabled: TIWFileReference;
FPrior_Disabled: TIWFileReference;
//
FParentDBNavigator: TIWDBNavigator;
procedure SetCancel(const Value: TIWFileReference);
procedure SetDelete(const Value: TIWFileReference);
procedure SetEdit(const Value: TIWFileReference);
procedure SetFirst(const Value: TIWFileReference);
procedure SetInsert(const Value: TIWFileReference);
procedure SetLast(const Value: TIWFileReference);
procedure SetNext(const Value: TIWFileReference);
procedure SetPost(const Value: TIWFileReference);
procedure SetPrior(const Value: TIWFileReference);
procedure SetRefresh(const Value: TIWFileReference);
procedure SetCancel_Disabled(const Value: TIWFileReference);
procedure SetDelete_Disabled(const Value: TIWFileReference);
procedure SetEdit_Disabled(const Value: TIWFileReference);
procedure SetFirst_Disabled(const Value: TIWFileReference);
procedure SetInsert_Disabled(const Value: TIWFileReference);
procedure SetLast_Disabled(const Value: TIWFileReference);
procedure SetNext_Disabled(const Value: TIWFileReference);
procedure SetPost_Disabled(const Value: TIWFileReference);
procedure SetPrior_Disabled(const Value: TIWFileReference);
procedure SetRefresh_Disabled(const Value: TIWFileReference);
public
constructor Create(const AParenDBNav: TIWDBNavigator);
destructor Destroy; override;
published
property First_Enabled: TIWFileReference read FFirst write SetFirst;
property First_Disabled: TIWFileReference read FFirst_Disabled write SetFirst_Disabled;
property Prior_Enabled: TIWFileReference read FPrior write SetPrior;
property Prior_Disabled: TIWFileReference read FPrior_Disabled write SetPrior_Disabled;
property Next_Enabled: TIWFileReference read FNext write SetNext;
property Next_Disabled: TIWFileReference read FNext_Disabled write SetNext_Disabled;
property Last_Enabled: TIWFileReference read FLast write SetLast;
property Last_Disabled: TIWFileReference read FLast_Disabled write SetLast_Disabled;
property Edit_Enabled: TIWFileReference read FEdit write SetEdit;
property Edit_Disabled: TIWFileReference read FEdit_Disabled write SetEdit_Disabled;
property Insert_Enabled: TIWFileReference read FInsert write SetInsert;
property Insert_Disabled: TIWFileReference read FInsert_Disabled write SetInsert_Disabled;
property Delete_Enabled: TIWFileReference read FDelete write SetDelete;
property Delete_Disabled: TIWFileReference read FDelete_Disabled write SetDelete_Disabled;
property Post_Enabled: TIWFileReference read FPost write SetPost;
property Post_Disabled: TIWFileReference read FPost_Disabled write SetPost_Disabled;
property Cancel_Enabled: TIWFileReference read FCancel write SetCancel;
property Cancel_Disabled: TIWFileReference read FCancel_Disabled write SetCancel_Disabled;
property Refresh_Enabled: TIWFileReference read FRefresh write SetRefresh;
property Refresh_Disabled: TIWFileReference read FRefresh_Disabled write SetRefresh_Disabled;
end;
TIWDBNavConfirmations = class(TPersistent)
protected
FFirst: string;
FPrior: string;
FNext: string;
FLast: string;
FEdit: string;
FInsert: string;
FDelete: string;
FPost: string;
FCancel: string;
FRefresh: string;
public
constructor Create(const ADesignMode: Boolean);
published
property First: string read FFirst write FFirst;
property Prior: string read FPrior write FPrior;
property Next: string read FNext write FNext;
property Last: string read FLast write FLast;
property Edit: string read FEdit write FEdit;
property Insert: string read FInsert write FInsert;
property Delete: string read FDelete write FDelete;
property Post: string read FPost write FPost;
property Cancel: string read FCancel write FCancel;
property Refresh: string read FRefresh write FRefresh;
end;
TIWOrientation = (orHorizontal, orVertical);
TIWDBNavigator = class(TIWControl)
protected
FConfirmations: TIWDBNavConfirmations;
FDataSource: TDataSource;
FImageWidth: Integer;
FImageHeight: Integer;
FOnFirst: TNotifyEvent;
FOnPrior: TNotifyEvent;
FOnNext: TNotifyEvent;
FOnLast: TNotifyEvent;
FOnEdit: TNotifyEvent;
FOnInsert: TNotifyEvent;
FOnDelete: TNotifyEvent;
FOnPost: TNotifyEvent;
FOnCancel: TNotifyEvent;
FOnRefresh: TNotifyEvent;
FVisibleButtons: TButtonSet;
FDBNavImages: TIWDBNavImages;
FOrientation: TIWOrientation;
//
procedure Notification(AComponent: TComponent; AOperation: TOperation); override;
procedure SetVisibleButtons(Value: TButtonSet);
procedure SetDBNavImages(const Value: TIWDBNavImages);
procedure SetOrientation(const Value: TIWOrientation);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function RenderHTML: TIWHTMLTag; override;
procedure Submit(const AValue: string); override;
published
//@@ Confirmations contains text messages to use to confirm a users actions. To disable an
//individual confirmation simply set it to ''.
property Confirmations: TIWDBNavConfirmations read FConfirmations write FConfirmations;
//@@ Datasource to manipulate.
property DataSource: TDataSource read FDataSource write FDataSource;
//@@ Defines image height
property ImageHeight: Integer read FImageHeight write FImageHeight;
//@@ Defines image width
property ImageWidth: Integer read FImageWidth write FImageWidth;
//@@ Controls which buttons are displayed to the user.
property VisibleButtons: TButtonSet read FVisibleButtons write SetVisibleButtons;
//@@ Custom images for DBNavigator
property CustomImages: TIWDBNavImages read FDBNavImages write SetDBNavImages;
//@@ DBNavigator orientation
property Orientation: TIWOrientation read FOrientation write SetOrientation;
//
property OnFirst: TNotifyEvent read FOnFirst write FOnFirst;
property OnPrior: TNotifyEvent read FOnPrior write FOnPrior;
property OnNext: TNotifyEvent read FOnNext write FOnNext;
property OnLast: TNotifyEvent read FOnLast write FOnLast;
property OnEdit: TNotifyEvent read FOnEdit write FOnEdit;
property OnInsert: TNotifyEvent read FOnInsert write FOnInsert;
property OnDelete: TNotifyEvent read FOnDelete write FOnDelete;
property OnPost: TNotifyEvent read FOnPost write FOnPost;
property OnCancel: TNotifyEvent read FOnCancel write FOnCancel;
property OnRefresh: TNotifyEvent read FOnRefresh write FOnRefresh;
end;
TIWDBText = class(TIWCustomText)
protected
FDataField: string;
FDataSource: TDataSource;
//
procedure Notification(AComponent: TComponent; AOperation: TOperation); override;
public
function RenderHTML: TIWHTMLTag; override;
published
//@@ Datafield to retreive data from.
property DataField: string read FDataField write FDataField;
property DataSource: TDataSource read FDataSource write FDataSource;
property Font;
property RawText;
property UseFrame;
property WantReturns;
end;
// Procs
function InEditMode(ADataset: TDataset): Boolean;
function CheckDataSource(ADataSource: TDataSource): Boolean; overload;
function CheckDataSource(ADataSource: TDataSource; const AFieldName: string; var VField: TField)
: boolean; overload;
implementation
// TODO: (for 5.1 or 6): to check all Combo and list box controls so they use ItemsHasValues
{$R IWDB.res}
uses
{$IFDEF Linux}
Types,
QButtons,
QGraphics,
{$ELSE}
Windows,
Buttons,
Graphics,
{$ENDIF}
IWResourceStrings,
SWSystem, SysUtils;
function InEditMode(ADataset: TDataset): Boolean;
begin
Result := ADataset.State in [dsEdit, dsInsert];
end;
function CheckDataSource(ADataSource: TDataSource): boolean; overload;
begin
Result := False;
if ADataSource <> nil then begin
if ADataSource.Dataset <> nil then begin
Result := ADataSource.Dataset.Active;
end;
end;
end;
function CheckDataSource(ADataSource: TDataSource; const AFieldName: string; var VField: TField)
: boolean;
begin
Result := CheckDataSource(ADataSource) and (Length(AFieldName) > 0);
if Result then begin
VField := ADataSource.Dataset.FieldByName(AFieldName);
end;
end;
function GetFieldText(AField: TField): String;
begin
if AField.IsBlob then begin
if Assigned(AField.OnGetText) then begin
result := AField.Text;
end else begin
result := AField.AsString;
end;
end
else begin
result := AField.Text;
end;
end;
procedure SetFieldText(AField: TField; AText: String);
begin
end;
{ TIWDBEdit }
procedure TIWDBEdit.Notification(AComponent: TComponent; AOperation: TOperation);
begin
inherited Notification(AComponent, AOperation);
if AOperation = opRemove then begin
if FDatasource = AComponent then begin
FDatasource := nil;
end;
end;
end;
procedure TIWDBEdit.Paint;
begin
Text := DataField;
inherited Paint;
end;
function TIWDBEdit.RenderHTML: TIWHTMLTag;
var
LField: TField;
begin
if CheckDataSource(DataSource, DataField, LField) then begin
if AutoEditable then begin
Editable := InEditMode(DataSource.Dataset);
end;
if Editable then begin
Text := GetFieldText(LField);
end else begin
Text := LField.DisplayText;
end;
if (LField.DataType = ftString) then begin
MaxLength := LField.Size;
end;
end else begin
Text := '';
if AutoEditable then begin
Editable := False;
end;
end;
Result := inherited RenderHTML;
end;
procedure TIWDBEdit.SetValue(const AValue: string);
var
LField: TField;
begin
inherited SetValue(AValue);
if CheckDataSource(DataSource, DataField, LField) then begin
if (GetFieldText(LField) <> Text) then begin
Datasource.Edit;
LField.Text := Text;
end;
end;
end;
{ TIWDBLabel }
procedure TIWDBLabel.Notification(AComponent: TComponent; AOperation: TOperation);
begin
inherited Notification(AComponent, AOperation);
if AOperation = opRemove then begin
if FDatasource = AComponent then begin
FDatasource := nil;
end;
end;
end;
procedure TIWDBLabel.Paint;
begin
if Length(DataField) = 0 then begin
Caption := Name;
end else begin
Caption := DataField;
end;
inherited Paint;
end;
function TIWDBLabel.RenderHTML: TIWHTMLTag;
var
LField: TField;
begin
if CheckDataSource(DataSource, DataField, LField) then begin
// Still need this check for TDateTimeField with .DisplayText?
if LField is TDateTimeField then begin
Caption := FormatDateTime(TDateTimeField(LField).DisplayFormat, LField.AsDateTime);
end else begin
Caption := LField.DisplayText;
end;
end else begin
Caption := '';
end;
Result := inherited RenderHTML;
end;
{ TIWDBMemo }
procedure TIWDBMemo.Notification(AComponent: TComponent; AOperation: TOperation);
begin
inherited Notification(AComponent, AOperation);
if AOperation = opRemove then begin
if FDatasource = AComponent then begin
FDatasource := nil;
end;
end;
end;
function TIWDBMemo.RenderHTML: TIWHTMLTag;
var
LField: TField;
begin
if CheckDataSource(DataSource, DataField, LField) then begin
FLines.Text := GetFieldText(LField);
FEndsWithCRLF := FLines.Text = GetFieldText(LField);
if AutoEditable then begin
Editable := InEditMode(DataSource.Dataset);
end;
end else begin
FLines.Clear;
if AutoEditable then begin
Editable := False;
end;
end;
Result := inherited RenderHTML;
end;
procedure TIWDBMemo.SetValue(const AValue: string);
var
LField: TField;
begin
inherited SetValue(AValue);
if CheckDataSource(DataSource, DataField, LField) then begin
// After SetValue Text holds the real value
// When AValue does not end with CR-LF FLisnes automatically adds CRLF
if (GetFieldText(LField) <> Text) then begin
Datasource.Edit;
LField.AsString := Text;
end;
end;
end;
{ TIWDBNavigator }
constructor TIWDBNavigator.Create(AOwner: TComponent);
var
LUseDefaults: Boolean;
begin
inherited Create(AOwner);
FSupportsSubmit := True;
//
LUseDefaults := False;
if Owner <> nil then begin
LUseDefaults := (Owner.ComponentState * [csReading, csDesigning]) = [csDesigning];
end;
FConfirmations := TIWDBNavConfirmations.Create(LUseDefaults);
FDBNavImages := TIWDBNavImages.Create(Self);
//
VisibleButtons := [nbFirst, nbPrior, nbNext, nbLast, nbInsert, nbDelete, nbEdit, nbPost, nbCancel
, nbRefresh];
Height := 25;
Width := 250;
ImageHeight := 21;
ImageWidth := 21;
end;
destructor TIWDBNavigator.Destroy;
begin
FreeAndNil(FConfirmations);
FreeAndNil(FDBNavImages);
inherited Destroy;
end;
procedure TIWDBNavigator.Notification(AComponent: TComponent; AOperation: TOperation);
begin
inherited Notification(AComponent, AOperation);
if AOperation = opRemove then begin
if FDatasource = AComponent then begin
FDatasource := nil;
end;
end;
end;
function TIWDBNavigator.RenderHTML: TIWHTMLTag;
var
LBOF: Boolean;
LCanModify: Boolean;
LEOF: Boolean;
LEditMode: Boolean;
LValidDataset: Boolean;
Const
DBNavButtonNames: array [TNavigateBtn] of String =
(RSbtnNameFirst, RSbtnNamePrior, RSbtnNameNext, RSbtnNameLast, RSbtnNameInsert,
RSbtnNameDelete, RSbtnNameEdit, RSbtnNamePost, RSbtnNameCancel, RSbtnNameRefresh);
// Don't remove. Will need this for one more thing.
DBNavButtonImages: array [TNavigateBtn] of String =
('First', 'Prior', 'Next', 'Last', 'Insert', 'Delete', 'Edit', { do not localize }
'Post', 'Cancel', 'Refresh'); { do not localize }
function DBNavImage(const AName: string; const AButton: TNavigateBtn; const AConfirmation: string;
const AEnabled: Boolean = True; const ADoValidation: Boolean = True): TIWHTMLTag;
Var
LImgTag: TIWHTMLTag;
LImageSrc: String;
LFReference: TIWFileReference;
begin
//No EOL, it causes Whitespace in Netscape
//TODO: Use PageImage
// To avoid warining messages
LFReference := nil;
//
if AEnabled then begin
case AButton of
nbFirst: LFReference := FDBNavImages.First_Enabled;
nbPrior: LFReference := FDBNavImages.Prior_Enabled;
nbNext: LFReference := FDBNavImages.Next_Enabled;
nbLast: LFReference := FDBNavImages.Last_Enabled;
nbInsert: LFReference := FDBNavImages.Insert_Enabled;
nbDelete: LFReference := FDBNavImages.Delete_Enabled;
nbEdit: LFReference := FDBNavImages.Edit_Enabled;
nbPost: LFReference := FDBNavImages.Post_Enabled;
nbCancel: LFReference := FDBNavImages.Cancel_Enabled;
nbRefresh: LFReference := FDBNavImages.Refresh_Enabled;
end;
end
else begin
case AButton of
nbFirst: LFReference := FDBNavImages.First_Disabled;
nbPrior: LFReference := FDBNavImages.Prior_Disabled;
nbNext: LFReference := FDBNavImages.Next_Disabled;
nbLast: LFReference := FDBNavImages.Last_Disabled;
nbInsert: LFReference := FDBNavImages.Insert_Disabled;
nbDelete: LFReference := FDBNavImages.Delete_Disabled;
nbEdit: LFReference := FDBNavImages.Edit_Disabled;
nbPost: LFReference := FDBNavImages.Post_Disabled;
nbCancel: LFReference := FDBNavImages.Cancel_Disabled;
nbRefresh: LFReference := FDBNavImages.Refresh_Disabled;
end;
end;
LImageSrc := LFReference.Location(WebApplication.URLBase);
if LImageSrc = '' then
LImageSrc := WebApplication.URLBase + '/gfx/DBNav_' + DBNavButtonImages[AButton] + iif(not (AEnabled and LValidDataset), 'Disabled') + '.gif';
LImgTag := TIWHTMLTag.CreateTag('IMG');
with LImgTag do try
AddStringParam('SRC', LImageSrc);
AddStringParam('ALT', DBNavButtonNames[AButton]);
AddIntegerParam('BORDER', 0);
AddIntegerParam('width', FImageWidth);
AddIntegerParam('height', FImageHeight);
except FreeAndNil(LImgTag); raise; end;
Result := LImgTag;
if AEnabled then begin
Result := TIWHTMLTag.CreateTag('A'); try
Result.AddStringParam('OnClick', 'return SubmitClickConfirm(''' + AName + ''','''
+ DBNavButtonNames[AButton] + ''''
+ ', ' + iif(ADoValidation, 'true', 'false')
+ ', ''' + AConfirmation + ''''
+ ')');
Result.Contents.AddTagAsObject(LImgTag);
except FreeAndNil(Result); raise; end;
end;
HintEvents(Result, DBNavButtonNames[AButton]);
end;
Var
LineTag: TIWHTMLTag;
LTable: TIWHTMLTag;
procedure AddImageTag(ATag: TIWHTMLTag);
begin
if LineTag = nil then begin
LineTag := LTable.Contents.AddTag('TR');
end
else
if Orientation = orVertical then begin
LineTag := LTable.Contents.AddTag('TR');
end;
with LineTag.Contents.AddTag('TD') do begin
AddIntegerParam('width', ImageWidth);
AddIntegerParam('height', ImageHeight);
Contents.AddTagAsObject(ATag);
end;
end;
begin
Result := TIWHTMLTag.CreateTag('SPAN'); try
LTable := Result.Contents.AddTag('TABLE');
LValidDataset := CheckDatasource(DataSource);
LBOF := False;
LEOF := False;
LCanModify := False;
LEditMode := False;
if LValidDataset then begin
LBOF := DataSource.Dataset.BOF;
LEOF := DataSource.Dataset.EOF;
LCanModify := DataSource.Dataset.CanModify;
LEditMode := InEditMode(DataSource.Dataset);
end;
LTable.AddIntegerParam('cellspacing', 0);
LTable.AddIntegerParam('border', 0);
LTable.AddIntegerParam('cellpadding', 0);
LineTag := nil;
if nbFirst in VisibleButtons then begin
AddImageTag(DBNavImage(HTMLName, nbFirst, Confirmations.First
, (LBOF = False) and LValidDataset));
end;
if nbPrior in VisibleButtons then begin
AddImageTag(DBNavImage(HTMLName, nbPrior, Confirmations.Prior
, (LBOF = False) and LValidDataset));
end;
if nbNext in VisibleButtons then begin
AddImageTag(DBNavImage(HTMLName, nbNext, Confirmations.Next
, (LEOF = False) and LValidDataset));
end;
if nbLast in VisibleButtons then begin
AddImageTag(DBNavImage(HTMLName, nbLast, Confirmations.Last
, (LEOF = False) and LValidDataset));
end;
if nbEdit in VisibleButtons then begin
AddImageTag(DBNavImage(HTMLName, nbEdit, Confirmations.Edit
, (LEditMode = False) and LCanModify and LValidDataset));
end;
if nbInsert in VisibleButtons then begin
AddImageTag(DBNavImage(HTMLName, nbInsert, Confirmations.Insert
, (LEditMode = False) and LCanModify and LValidDataset));
end;
if nbDelete in VisibleButtons then begin
AddImageTag(DBNavImage(HTMLName, nbDelete, Confirmations.Delete
, (LEditMode = False) and LCanModify and LValidDataset, False));
end;
if nbPost in VisibleButtons then begin
AddImageTag(DBNavImage(HTMLName, nbPost, Confirmations.Post
, LEditMode and LCanModify and LValidDataset));
end;
if nbCancel in VisibleButtons then begin
AddImageTag(DBNavImage(HTMLName, nbCancel, Confirmations.Cancel
, LEditMode and LCanModify and LValidDataset, False));
end;
if nbRefresh in VisibleButtons then begin
AddImageTag(DBNavImage(HTMLName, nbRefresh, Confirmations.Refresh
, (LEditMode = False) and LCanModify and LValidDataset, False));
end;
if LTable.Contents.Count = 0 then begin
FreeAndNil(Result);
end;
except FreeAndNil(Result); raise; end;
end;
procedure TIWDBNavigator.SetDBNavImages(const Value: TIWDBNavImages);
begin
FDBNavImages.Assign(Value);
end;
procedure TIWDBNavigator.SetOrientation(const Value: TIWOrientation);
begin
FOrientation := Value;
Invalidate;
end;
procedure TIWDBNavigator.SetVisibleButtons(Value: TButtonSet);
begin
FVisibleButtons := Value;
Invalidate;
end;
procedure TIWDBNavigator.Submit(const AValue: string);
procedure DoEvent(AEvent: TNotifyEvent);
begin
if Assigned(AEvent) then begin
AEvent(Self);
end;
end;
begin
if CheckDatasource(DataSource) then begin
if SameText(AValue, RSbtnNameFirst) then begin
if InEditMode(Datasource.Dataset) then
Datasource.Dataset.Post;
Datasource.Dataset.First;
DoEvent(OnFirst);
end else if SameText(AValue, RSbtnNamePrior) then begin
if InEditMode(Datasource.Dataset) then
Datasource.Dataset.Post;
Datasource.Dataset.Prior;
DoEvent(OnPrior);
end else if SameText(AValue, RSbtnNameNext) then begin
if InEditMode(Datasource.Dataset) then
Datasource.Dataset.Post;
Datasource.Dataset.Next;
DoEvent(OnNext);
end else if SameText(AValue, RSbtnNameLast) then begin
if InEditMode(Datasource.Dataset) then
Datasource.Dataset.Post;
Datasource.Dataset.Last;
DoEvent(OnLast);
end else if SameText(AValue, RSbtnNameEdit) then begin
if InEditMode(Datasource.Dataset) then
Datasource.Dataset.Post;
Datasource.Dataset.Edit;
DoEvent(OnEdit);
end else if SameText(AValue, RSbtnNameInsert) then begin
if InEditMode(Datasource.Dataset) then
Datasource.Dataset.Post;
Datasource.Dataset.Insert;
DoEvent(OnInsert);
end else if SameText(AValue, RSbtnNameDelete) then begin
if InEditMode(Datasource.Dataset) then
Datasource.Dataset.Cancel;
Datasource.Dataset.Delete;
DoEvent(OnDelete);
end else if SameText(AValue, RSbtnNamePost) then begin
Datasource.Dataset.Post;
DoEvent(OnPost);
end else if SameText(AValue, RSbtnNameCancel) then begin
Datasource.Dataset.Cancel;
DoEvent(OnCancel);
end else if SameText(AValue, RSbtnNameRefresh) then begin
if InEditMode(Datasource.Dataset) then
Datasource.Dataset.Cancel;
Datasource.Dataset.Refresh;
DoEvent(OnRefresh);
end else begin
raise Exception.Create(Format(RSInvalidResponse, [AValue]));
end;
end;
end;
{ TIWDBText }
procedure TIWDBText.Notification(AComponent: TComponent; AOperation: TOperation);
begin
inherited Notification(AComponent, AOperation);
if AOperation = opRemove then begin
if FDatasource = AComponent then begin
FDatasource := nil;
end;
end;
end;
function TIWDBText.RenderHTML: TIWHTMLTag;
var
LField: TField;
begin
if CheckDataSource(DataSource, DataField, LField) then begin
FLines.Text := GetFieldText(LField);
end else begin
FLines.Clear;
end;
Result := inherited RenderHTML;
end;
{ TIWDBCheckBox }
constructor TIWDBCheckBox.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ValueChecked := 'true';
ValueUnchecked := 'false';
end;
procedure TIWDBCheckBox.Notification(AComponent: TComponent; AOperation: TOperation);
begin
inherited Notification(AComponent, AOperation);
if AOperation = opRemove then begin
if FDatasource = AComponent then begin
FDatasource := nil;
end;
end;
end;
function TIWDBCheckBox.RenderHTML: TIWHTMLTag;
var
LField: TField;
begin
if CheckDataSource(DataSource, DataField, LField) then begin
FChecked := AnsiSameText(ValueChecked, GetFieldText(LField));
if AutoEditable then begin
Editable := InEditMode(DataSource.Dataset);
end;
end else begin
FChecked := False;
if AutoEditable then begin
Editable := False;
end;
end;
Result := inherited RenderHTML;
end;
procedure TIWDBCheckBox.SetDataField(const AValue: string);
begin
FDataField := AValue;
Invalidate;
end;
procedure TIWDBCheckBox.SetValue(const AValue: string);
var
s: string;
LField: TField;
begin
inherited SetValue(AValue);
if CheckDataSource(DataSource, DataField, LField) then begin
s := iif(FChecked, ValueChecked, ValueUnChecked);
if not AnsiSameText(GetFieldText(LField), s) then begin
DataSource.Edit;
LField.Text := s;
end;
end;
end;
{ TIWDBComboBox }
procedure TIWDBComboBox.Notification(AComponent: TComponent; AOperation: TOperation);
begin
inherited Notification(AComponent, AOperation);
if AOperation = opRemove then begin
if FDatasource = AComponent then begin
FDatasource := nil;
end;
end;
end;
function TIWDBComboBox.RenderHTML: TIWHTMLTag;
var
LField: TField;
begin
if CheckDataSource(DataSource, DataField, LField) then begin
FItemIndex := FItems.IndexOf(GetFieldText(LField));
if AutoEditable then begin
Editable := InEditMode(DataSource.Dataset);
end;
end else begin
FItemIndex := -1;
if AutoEditable then begin
Editable := False;
end;
end;
Result := inherited RenderHTML;
end;
procedure TIWDBComboBox.SetValue(const AValue: string);
var
s: string;
LField: TField;
begin
inherited SetValue(AValue);
if CheckDataSource(DataSource, DataField, LField) then begin
if FItemIndex > -1 then begin
with FItems do begin
if ItemsHaveValues then begin
s := Values[Names[FItemIndex]];
end
else begin
s := FItems[FItemIndex];
end;
end;
end else begin
s := '';
end;
if (GetFieldText(LField) <> s) then begin
DataSource.Edit;
LField.Text := s;
end;
end;
end;
{ TIWDBListbox }
procedure TIWDBListbox.Notification(AComponent: TComponent; AOperation: TOperation);
begin
inherited Notification(AComponent, AOperation);
if AOperation = opRemove then begin
if FDatasource = AComponent then begin
FDatasource := nil;
end;
end;
end;
function TIWDBListbox.RenderHTML: TIWHTMLTag;
var
LField: TField;
begin
if CheckDataSource(DataSource, DataField, LField) then begin
FItemIndex := FItems.IndexOf(GetFieldText(LField));
if AutoEditable then begin
Editable := InEditMode(DataSource.Dataset);
end;
end else begin
FItemIndex := -1;
if AutoEditable then begin
Editable := False;
end;
end;
Result := inherited RenderHTML;
end;
procedure TIWDBListbox.SetValue(const AValue: string);
var
s: string;
LField: TField;
begin
inherited SetValue(AValue);
if CheckDataSource(DataSource, DataField, LField) then begin
if FItemIndex > -1 then begin
with FItems do begin
if ItemsHaveValues then begin
s := Values[Names[FItemIndex]];
end
else begin
s := FItems[FItemIndex];
end;
end;
end else begin
s := '';
end;
if (GetFieldText(LField) <> s) then begin
DataSource.Edit;
LField.Text := s;
end;
end;
end;
{ TIWDBLookupComboBox }
constructor TIWDBLookupComboBox.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FKeyItems := TStringList.Create;
FItemIndex := -1;
end;
destructor TIWDBLookupComboBox.Destroy;
begin
FreeAndNil(FKeyItems);
inherited Destroy;
end;
procedure TIWDBLookupComboBox.Notification(AComponent: TComponent; AOperation: TOperation);
begin
inherited Notification(AComponent, AOperation);
if AOperation = opRemove then begin
if FDatasource = AComponent then begin
FDatasource := nil;
end;
if FListSource = AComponent then begin
FListSource := nil;
end;
end;
end;
function TIWDBLookupComboBox.RenderHTML: TIWHTMLTag;
var
LField: TField;
LKeyField: TField;
begin
FItems.Clear;
FKeyItems.Clear;
if CheckDataSource(ListSource, ListField, LField)
and CheckDataSource(ListSource, KeyField, LKeyField) then begin
ListSource.DataSet.First;
while not ListSource.Dataset.EOF do begin
FItems.Add(GetFieldText(LField));
FKeyItems.Add(GetFieldText(LKeyField));
ListSource.DataSet.Next;
end;
end;
if CheckDataSource(DataSource, DataField, LField) then begin
if LField.IsNull then begin
FItemIndex := -1;
end else begin
FItemIndex := FKeyItems.IndexOf(GetFieldText(LField));
end;
if AutoEditable then begin
Editable := InEditMode(DataSource.Dataset);
end;
end else begin
FItemIndex := -1;
if AutoEditable then begin
Editable := False;
end;
end;
Result := inherited RenderHTML;
end;
procedure TIWDBLookupComboBox.SetValue(const AValue: string);
var
s: string;
LField: TField;
begin
inherited SetValue(AValue);
if CheckDataSource(DataSource, DataField, LField) then begin
if ItemIndex = -1 then begin
s := #0;
end else begin
s := FKeyItems[ItemIndex];
end;
if ((LField.IsNull) and (S <> #0)) or (GetFieldText(LField) <> s) then begin
DataSource.Edit;
if s = #0 then begin
LField.Clear;
end else begin
LField.Text := s;
end;
end;
end;
end;
{ TIWDBLookupListBox }
constructor TIWDBLookupListBox.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FKeyItems := TStringList.Create;
end;
destructor TIWDBLookupListBox.Destroy;
begin
FreeAndNil(FKeyItems);
inherited Destroy;
end;
procedure TIWDBLookupListBox.Notification(AComponent: TComponent; AOperation: TOperation);
begin
inherited Notification(AComponent, AOperation);
if AOperation = opRemove then begin
if FDatasource = AComponent then begin
FDatasource := nil;
end;
if FListSource = AComponent then begin
FListSource := nil;
end;
end;
end;
function TIWDBLookupListBox.RenderHTML: TIWHTMLTag;
var
LField: TField;
LKeyField: TField;
begin
FItems.Clear;
FKeyItems.Clear;
if CheckDataSource(ListSource, ListField, LField)
and CheckDataSource(ListSource, KeyField, LKeyField) then begin
ListSource.DataSet.First;
while not ListSource.Dataset.EOF do begin
FItems.Add(GetFieldText(LField));
FKeyItems.Add(GetFieldText(LKeyField));
ListSource.DataSet.Next;
end;
end;
if CheckDataSource(DataSource, DataField, LField) then begin
if LField.IsNull then begin
FItemIndex := -1;
end else begin
FItemIndex := FKeyItems.IndexOf(GetFieldText(LField));
end;
if AutoEditable then begin
Editable := InEditMode(DataSource.Dataset);
end;
end else begin
FItemIndex := -1;
if AutoEditable then begin
Editable := False;
end;
end;
Result := inherited RenderHTML;
end;
procedure TIWDBLookupListBox.SetValue(const AValue: string);
var
s: string;
LField: TField;
begin
inherited SetValue(AValue);
if CheckDataSource(DataSource, DataField, LField) then begin
if FItemIndex = -1 then begin
s := #0;
end else begin
s := FKeyItems[FItemIndex];
end;
if ((LField.IsNull) and (S <> #0)) or (GetFieldText(LField) <> s) then begin
DataSource.Edit;
if s = #0 then begin
LField.Clear;
end else begin
LField.Text := s;
end;
end;
end;
end;
{ TIWDBNavConfirmations }
constructor TIWDBNavConfirmations.Create(const ADesignMode: Boolean);
begin
inherited Create;
// Since Delphi does not write out empty strings, only default at design time so that
// the user can set them to empty strings to disable them.
// This does have a side effect of not defaulting if the user dynamically creates a DBNav.
if ADesignMode then begin
Delete := RSDeleteMessage;
Post := RSUpdateMessage;
Cancel := RSCancelMessage;
end;
end;
{ TIWDBNavImages }
constructor TIWDBNavImages.Create(const AParenDBNav: TIWDBNavigator);
begin
inherited Create;
FParentDBNavigator := AParenDBNav;
FDelete := TIWFileReference.Create;
FPost := TIWFileReference.Create;
FCancel := TIWFileReference.Create;
FFirst := TIWFileReference.Create;
FNext := TIWFileReference.Create;
FInsert := TIWFileReference.Create;
FEdit := TIWFileReference.Create;
FRefresh := TIWFileReference.Create;
FLast := TIWFileReference.Create;
FPrior := TIWFileReference.Create;
FDelete_Disabled := TIWFileReference.Create;
FPost_Disabled := TIWFileReference.Create;
FCancel_Disabled := TIWFileReference.Create;
FFirst_Disabled := TIWFileReference.Create;
FNext_Disabled := TIWFileReference.Create;
FInsert_Disabled := TIWFileReference.Create;
FEdit_Disabled := TIWFileReference.Create;
FRefresh_Disabled := TIWFileReference.Create;
FLast_Disabled := TIWFileReference.Create;
FPrior_Disabled := TIWFileReference.Create;
end;
destructor TIWDBNavImages.Destroy;
begin
FreeAndNil(FDelete);
FreeAndNil(FPost);
FreeAndNil(FCancel);
FreeAndNil(FFirst);
FreeAndNil(FNext);
FreeAndNil(FInsert);
FreeAndNil(FEdit);
FreeAndNil(FRefresh);
FreeAndNil(FLast);
FreeAndNil(FPrior);
FreeAndNil(FDelete_Disabled);
FreeAndNil(FPost_Disabled);
FreeAndNil(FCancel_Disabled);
FreeAndNil(FFirst_Disabled);
FreeAndNil(FNext_Disabled);
FreeAndNil(FInsert_Disabled);
FreeAndNil(FEdit_Disabled);
FreeAndNil(FRefresh_Disabled);
FreeAndNil(FLast_Disabled);
FreeAndNil(FPrior_Disabled);
inherited Destroy;
end;
procedure TIWDBNavImages.SetCancel(const Value: TIWFileReference);
begin
FCancel.Assign(Value);
end;
procedure TIWDBNavImages.SetCancel_Disabled(const Value: TIWFileReference);
begin
FCancel_Disabled.Assign(Value);
end;
procedure TIWDBNavImages.SetDelete(const Value: TIWFileReference);
begin
FDelete.Assign(Value);
end;
procedure TIWDBNavImages.SetDelete_Disabled(const Value: TIWFileReference);
begin
FDelete_Disabled.Assign(Value);
end;
procedure TIWDBNavImages.SetEdit(const Value: TIWFileReference);
begin
FEdit.Assign(Value);
end;
procedure TIWDBNavImages.SetEdit_Disabled(const Value: TIWFileReference);
begin
FEdit_Disabled.Assign(Value);
end;
procedure TIWDBNavImages.SetFirst(const Value: TIWFileReference);
begin
FFirst.Assign(Value);
end;
procedure TIWDBNavImages.SetFirst_Disabled(const Value: TIWFileReference);
begin
FFirst_Disabled.Assign(Value);
end;
procedure TIWDBNavImages.SetInsert(const Value: TIWFileReference);
begin
FInsert.Assign(Value);
end;
procedure TIWDBNavImages.SetInsert_Disabled(const Value: TIWFileReference);
begin
FInsert_Disabled.Assign(Value);
end;
procedure TIWDBNavImages.SetLast(const Value: TIWFileReference);
begin
FLast.Assign(Value);
end;
procedure TIWDBNavImages.SetLast_Disabled(const Value: TIWFileReference);
begin
FLast_Disabled.Assign(Value);
end;
procedure TIWDBNavImages.SetNext(const Value: TIWFileReference);
begin
FNext.Assign(Value);
end;
procedure TIWDBNavImages.SetNext_Disabled(const Value: TIWFileReference);
begin
FNext_Disabled.Assign(Value);
end;
procedure TIWDBNavImages.SetPost(const Value: TIWFileReference);
begin
FPost.Assign(Value);
end;
procedure TIWDBNavImages.SetPost_Disabled(const Value: TIWFileReference);
begin
FPost_Disabled.Assign(Value);
end;
procedure TIWDBNavImages.SetPrior(const Value: TIWFileReference);
begin
FPrior.Assign(Value);
end;
procedure TIWDBNavImages.SetPrior_Disabled(const Value: TIWFileReference);
begin
FPrior_Disabled.Assign(Value);
end;
procedure TIWDBNavImages.SetRefresh(const Value: TIWFileReference);
begin
FRefresh.Assign(Value);
end;
procedure TIWDBNavImages.SetRefresh_Disabled(
const Value: TIWFileReference);
begin
FRefresh_Disabled.Assign(Value);
end;
{ TIWDBFile }
procedure TIWDBFile.Notification(AComponent: TComponent;
AOperation: TOperation);
begin
inherited Notification(AComponent, AOperation);
if AOperation = opRemove then begin
if FDatasource = AComponent then begin
FDatasource := nil;
end;
end;
end;
procedure TIWDBFile.SetValue(const AValue: string);
var
LField: TField;
LStream: TStream;
begin
inherited SetValue(AValue);
if CheckDataSource(DataSource, DataField, LField) then begin
if Assigned(FileData) then begin
Datasource.Edit;
LStream := LField.DataSet.CreateBlobStream(LField.DataSet.FieldByName(DataField), bmWrite);
try
SaveToStream(LStream);
finally
FreeAndNil(LStream);
end;
end;
end;
end;
end. |
////////////////////////////////////////////////////////////////////////////////
//
//
// FileName : SUIStatusBar.pas
// Creator : Shen Min
// Date : 2003-08-04 V4
// Comment :
//
// Copyright (c) 2002-2003 Sunisoft
// http://www.sunisoft.com
// Email: support@sunisoft.com
//
////////////////////////////////////////////////////////////////////////////////
unit SUIStatusBar;
interface
{$I SUIPack.inc}
uses Windows, ComCtrls, Graphics, Classes, Forms, Controls, Messages,
SUIThemes, SUIMgr;
type
{$IFDEF SUIPACK_D6UP}
TsuiStatusBar = class(TCustomStatusBar)
{$ENDIF}
{$IFDEF SUIPACK_D5}
TsuiStatusBar = class(TStatusBar)
{$ENDIF}
private
m_UIStyle : TsuiUIStyle;
m_FileTheme : TsuiFileTheme;
procedure SetFileTheme(const Value: TsuiFileTheme);
procedure SetUIStyle(const Value: TsuiUIStyle);
function GetPanelColor(): TColor;
procedure SetPanelColor(const Value: TColor);
procedure WMPaint(var Msg : TMessage); message WM_PAINT;
procedure WMNCHITTEST(var Msg : TMessage); message WM_NCHITTEST;
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
constructor Create(AOwner : TComponent); override;
published
property FileTheme : TsuiFileTheme read m_FileTheme write SetFileTheme;
property UIStyle : TsuiUIStyle read m_UIStyle write SetUIStyle;
property PanelColor : TColor read GetPanelColor write SetPanelColor;
property Action;
property AutoHint default False;
property Align default alBottom;
property Anchors;
property BiDiMode;
property BorderWidth;
property Color default clBtnFace;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property Font {$IFDEF SUIPACK_D6UP}stored IsFontStored{$ENDIF};
property Constraints;
property Panels;
property ParentBiDiMode;
property ParentColor default False;
property ParentFont default False;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property SimplePanel default False;
property SimpleText;
property SizeGrip default True;
property UseSystemFont default True;
property Visible;
property OnClick;
property OnContextPopup;
{$IFDEF SUIPACK_D6UP}
property OnCreatePanelClass;
{$ENDIF}
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnHint;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnResize;
property OnStartDock;
property OnStartDrag;
property OnDrawPanel;
end;
implementation
uses SUIPublic, SUIForm;
{ TsuiStatusBar }
constructor TsuiStatusBar.Create(AOwner: TComponent);
begin
inherited;
// ControlStyle := ControlStyle + [csAcceptsControls];
UIStyle := GetSUIFormStyle(AOwner);
end;
function TsuiStatusBar.GetPanelColor: TColor;
begin
Result := Color;
end;
procedure TsuiStatusBar.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (
(Operation = opRemove) and
(AComponent = m_FileTheme)
)then
begin
m_FileTheme := nil;
SetUIStyle(SUI_THEME_DEFAULT);
end;
end;
procedure TsuiStatusBar.SetFileTheme(const Value: TsuiFileTheme);
begin
m_FileTheme := Value;
SetUIStyle(m_UIStyle);
end;
procedure TsuiStatusBar.SetPanelColor(const Value: TColor);
begin
Color := Value;
end;
procedure TsuiStatusBar.SetUIStyle(const Value: TsuiUIStyle);
var
OutUIStyle : TsuiUIStyle;
begin
m_UIStyle := Value;
if UsingFileTheme(m_FileTheme, m_UIStyle, OutUIStyle) then
PanelColor := m_FileTheme.GetColor(SUI_THEME_FORM_BACKGROUND_COLOR)
else
PanelColor := GetInsideThemeColor(OutUIStyle, SUI_THEME_FORM_BACKGROUND_COLOR);
Repaint();
end;
procedure TsuiStatusBar.WMNCHITTEST(var Msg: TMessage);
var
Form : TCustomForm;
begin
Form := GetParentForm(self);
if (Form = nil) or (Form.WindowState <> wsMaximized) then
inherited;
end;
procedure TsuiStatusBar.WMPaint(var Msg: TMessage);
var
ParentForm : TCustomForm;
R : TRect;
begin
inherited;
ParentForm := GetParentForm(self);
if ParentForm = nil then
Exit;
if ParentForm.BorderStyle <> bsSizeable then
Exit;
R := Rect(Width - 16, Height - 16, Width - 1, Height - 1);
Canvas.Brush.Color := Color;
Canvas.FillRect(R);
if SizeGrip and (ParentForm.WindowState <> wsMaximized) then
begin
Inc(R.Top);
Canvas.Pen.Color := clInactiveCaption;
Canvas.Pen.Width := 1;
Canvas.MoveTo(R.Left + 1, R.Bottom);
Canvas.LineTo(R.Right, R.Top);
Canvas.MoveTo(R.Left + 5, R.Bottom);
Canvas.LineTo(R.Right, R.Top + 4);
Canvas.MoveTo(R.Left + 9, R.Bottom);
Canvas.LineTo(R.Right, R.Top + 8);
Canvas.MoveTo(R.Left + 13, R.Bottom);
Canvas.LineTo(R.Right, R.Top + 12);
end;
if Height - 16 > 3 then
begin
R := Rect(Width - 16, 3, Width - 1, Height - 16);
Canvas.FillRect(R);
end;
end;
end.
|
unit cFornecedor;
interface
uses
SysUtils;
type
Fornecedor = class (TObject)
protected
codForn : integer;
endForn : string;
bairroForn : string;
cidadeForn : string;
emailForn : string;
estadoForn : string;
descForn : string;
cepForn : integer;
dataAdmissaoForn : TDateTime;
statusForn : String;
tipoForn : string;
public
Constructor Create( codForn: integer; endForn : string;
bairroForn : string; cidadeForn : string;
emailForn : string; estadoForn : string;
descForn : string; cepForn : integer;
dataAdmissaoForn : TDateTime ; statusForn : String; tipoForn : string);
Procedure setcodForn(codForn:integer);
Function getcodForn : integer;
Procedure setendForn(endForn:string);
Function getendForn:string;
Procedure setBairroForn(bairroForn:string);
Function getbairroForn:string;
Procedure setcidadeForn(cidadeForn:string);
Function getcidadeForn:string;
Procedure setemailForn(emailForn:string);
Function getemailForn:string;
Procedure setestadoForn(estadoForn:string);
Function getestadoForn:string;
Procedure setdescForn(descForn:string);
Function getdescForn:string;
Procedure setcepForn(cepForn:integer);
Function getcepForn:integer;
Procedure setdataAdmissaoForn(dataAdmissaoForn:TDateTime);
Function getdataAdmissaoForn:TDateTime;
Procedure setstatusForn(statusForn:String);
Function getstatusForn:String;
Procedure settipoForn(tipoForn:String);
Function gettipoForn:String;
end;
implementation
Constructor Fornecedor.Create( codForn: integer; endForn : string;
bairroForn : string; cidadeForn : string;
emailForn : string; estadoForn : string;
descForn : string; cepForn : integer;
dataAdmissaoForn : TDateTime ; statusForn : String; tipoForn:string);
begin
self.codForn := codForn;
self.endForn := endForn;
self.bairroForn := bairroForn;
self.cidadeForn := cidadeForn;
self.emailForn := emailForn;
self.estadoForn := estadoForn;
self.descForn := descForn;
self.cepForn := cepForn;
self.dataAdmissaoForn := dataAdmissaoForn;
self.statusForn := statusForn;
end;
Procedure Fornecedor.setcodForn(codForn:integer);
begin
self.codForn := codForn;
end;
Function Fornecedor.getcodForn:integer;
begin
result := codForn;
end;
Procedure Fornecedor.setendForn(endForn:string);
begin
self.endForn := endForn;
end;
Function Fornecedor.getendForn:string;
begin
result := endForn;
end;
Procedure Fornecedor.setBairroForn(bairroForn:string);
begin
self.bairroForn := bairroForn;
end;
Function Fornecedor.getbairroForn:string;
begin
result := bairroForn;
end;
Procedure Fornecedor.setcidadeForn(cidadeForn:string);
begin
self.cidadeForn := cidadeForn;
end;
Function Fornecedor.getcidadeForn:string;
begin
result := cidadeForn;
end;
Procedure Fornecedor.setemailForn(emailForn:string);
begin
self.emailForn := emailForn;
end;
Function Fornecedor.getemailForn:string;
begin
result := emailForn;
end;
Procedure Fornecedor.setestadoForn(estadoForn:string);
begin
self.estadoForn := estadoForn;
end;
Function Fornecedor.getestadoForn:string;
begin
result := estadoForn;
end;
Procedure Fornecedor.setdescForn(descForn:string);
begin
self.descForn := descForn;
end;
Function Fornecedor.getdescForn:string;
begin
result := descForn;
end;
Procedure Fornecedor.setcepForn(cepForn:integer);
begin
self.cepForn := cepForn;
end;
Function Fornecedor.getcepForn:integer;
begin
result := cepForn;
end;
Procedure Fornecedor.setdataAdmissaoForn(dataAdmissaoForn:TDateTime);
begin
self.dataAdmissaoForn := dataAdmissaoForn;
end;
Function Fornecedor.getdataAdmissaoForn:TDateTime;
begin
result := dataAdmissaoForn;
end;
Procedure Fornecedor.setstatusForn(statusForn:String);
begin
self.statusForn := statusForn;
end;
Function Fornecedor.getstatusForn:String;
begin
result := statusForn;
end;
Procedure Fornecedor.settipoForn(tipoForn:string);
begin
self.tipoForn := tipoForn;
end;
Function Fornecedor.gettipoForn:string;
begin
result := tipoForn;
end;
end.
|
unit LargeBlockSpreadBenchmark;
interface
uses
BenchmarkClassUnit, Math;
const
{The number of pointers}
NumPointers = 2000;
{The block size}
BlockSize = 65537;
type
TLargeBlockSpreadBench = class(TFastcodeMMBenchmark)
protected
FPointers: array[0..NumPointers - 1] of PChar;
public
constructor CreateBenchmark; override;
destructor Destroy; override;
procedure RunBenchmark; override;
class function GetBenchmarkName: string; override;
class function GetBenchmarkDescription: string; override;
class function GetCategory: TBenchmarkCategory; override;
end;
implementation
{ TSmallResizeBench }
constructor TLargeBlockSpreadBench.CreateBenchmark;
begin
inherited;
end;
destructor TLargeBlockSpreadBench.Destroy;
begin
inherited;
end;
class function TLargeBlockSpreadBench.GetBenchmarkDescription: string;
begin
Result := 'Allocates a few random sized large blocks (>64K), checking that '
+ 'the MM manages large blocks efficiently. '
+ 'Benchmark submitted by Pierre le Riche.';
end;
class function TLargeBlockSpreadBench.GetBenchmarkName: string;
begin
Result := 'Large block spread benchmark';
end;
class function TLargeBlockSpreadBench.GetCategory: TBenchmarkCategory;
begin
Result := bmSingleThreadAllocAndFree;
end;
procedure TLargeBlockSpreadBench.RunBenchmark;
var
i, j, k, LSize: integer;
begin
{Call the inherited handler}
inherited;
{Do the benchmark}
for j := 1 to 5 do
begin
for i := 0 to high(FPointers) do
begin
{Get the block}
LSize := (1 + Random(3)) * BlockSize;
GetMem(FPointers[i], LSize);
{Fill the memory}
for k := 0 to LSize - 1 do
FPointers[i][k] := char(k);
end;
{What we end with should be close to the peak usage}
UpdateUsageStatistics;
{Free the pointers}
for i := 0 to high(FPointers) do
FreeMem(FPointers[i]);
end;
end;
end.
|
unit Gutter;
interface
uses
Windows, Types, KOL, KOLHilightEdit;
function NewGutter(AParent: PControl; Editor: PHilightMemo): PControl;
implementation
{$R Gutter.res}
type
PGutter = ^TGutter;
TGutter = object(TObj)
private
FGutter: PControl;
FEditor: PHilightMemo;
FBookmarks: PImageList;
procedure EraseBkgnd(Sender: PControl; DC: HDC);
procedure Paint(Sender: PControl; DC: HDC);
public
procedure Init; virtual;
destructor Destroy; virtual;
procedure Update(Sender: PObj);
end;
function NewGutter(AParent: PControl; Editor: PHilightMemo): PControl;
var
Gutter: PGutter;
begin
Result := NewPanel(AParent, esLowered).SetBorder(0);
Result.Font.Assign(Editor.Font);
New(Gutter, Create);
Gutter.FGutter := Result;
Gutter.FEditor := Editor;
Result.CustomObj := Gutter;
Result.OnPaint := Gutter.Paint;
Result.OnEraseBkgnd := Gutter.EraseBkgnd;
Editor.Edit.OnScroll := Gutter.Update;
Editor.Edit.OnBookmark := Gutter.Update;
end;
{ TGutter }
destructor TGutter.Destroy;
begin
Free_And_Nil(FBookmarks);
inherited;
end;
procedure TGutter.Update(Sender: PObj);
var
Width: Integer;
begin
FGutter.Invalidate;
Width := FGutter.Canvas.TextWidth(Int2Str(FEditor.Edit.TopLine + FEditor.Edit.LinesVisiblePartial)) + 16;
if Width > FGutter.Width then
FGutter.Width := Width;
end;
procedure TGutter.Init;
begin
inherited;
FBookmarks := NewImageList(FGutter);
FBookmarks.ShareImages := true;
FBookmarks.ImgWidth := 11;
FBookmarks.ImgHeight := 14;
FBookmarks.LoadBitmap('EDITORBOOKMARKS', clFuchsia);
end;
procedure TGutter.EraseBkgnd(Sender: PControl; DC: HDC);
begin
FGutter.Canvas.Brush.Color := FGutter.Color;
FGutter.Canvas.FillRect(FGutter.ClientRect);
end;
procedure TGutter.Paint(Sender: PControl; DC: HDC);
var
i: Integer;
function LineNum: string;
begin
if FEditor.Edit.TopLine + i < FEditor.Edit.Count then
Result := Int2Str(FEditor.Edit.TopLine + i + 1)
else
Result := '';
end;
begin
for i := 0 to FEditor.Edit.LinesVisiblePartial - 1 do
begin
FGutter.Canvas.Brush.Color := FGutter.Color;
if FEditor.Edit.TopLine + i = FEditor.Edit.Caret.Y then
begin
FGutter.Canvas.Brush.Color := FGutter.Color1;
FGutter.Canvas.FillRect(Rect(0, i * FEditor.Edit.LineHeight, FGutter.Width, (i + 1) * FEditor.Edit.LineHeight));
end;
FGutter.Canvas.TextOut(FGutter.Width - FGutter.Canvas.TextWidth(LineNum) - 15, i * FEditor.Edit.LineHeight, LineNum);
end;
for i := 0 to 9 do
with FEditor.Edit.Bookmarks[i] do
if (Y >= FEditor.Edit.TopLine) and (Y <= FEditor.Edit.TopLine + FEditor.Edit.LinesVisiblePartial - 1) then
FBookmarks.Draw(i, FGutter.Canvas.Handle, FGutter.Width - 13, (Y - FEditor.Edit.TopLine) * FEditor.Edit.LineHeight);
end;
end.
|
unit AviThread;
interface
uses
Windows, Graphics, Classes, AviWriter_2;
type
TBitmapsDoneEvent = procedure(Sender: TObject; BitmapList: TList; BitmapCount: integer) of object;
TTransObject = class
private
fsbm, ftbm, fres: TBitmap;
fTransitTime: integer;
fImageTime: integer;
ftInv: double;
procedure SetTransittime(const value: integer);
public
constructor Create; virtual;
destructor Destroy; override;
procedure Initialize(sbm, tbm: TBitmap); virtual;
procedure Finalize; virtual;
procedure Render(t: integer); virtual;
procedure WriteToAvi(const AviWriter: TAviWriter_2; sbm, tbm: TBitmap; NewWidth, NewHeight: integer);
property TransitTime: integer read fTransitTime write SetTransittime;
property ImageTime: integer read fImageTime write fImageTime;
property Result: TBitmap read fres;
end;
TFadeObject = class(TTransObject)
public
procedure Render(t: integer); override;
end;
TAviThread = class(TThread)
private
fAviWriter: TAviWriter_2;
fImageFileList: TStringList;
fBitmapList: TList;
fFadeObject: TFadeObject;
fFrameCount: integer;
fOnUpdate: TProgressEvent;
fOnBitmapsDone: TBitmapsDoneEvent;
fOnBadBitmap: TBadBitmapEvent;
fError: TBitmap;
fErrorHeaderSize, fErrorBitsSize: integer;
fCancelled, fTempWrite: boolean;
NewWidth, NewHeight: integer;
procedure SetImageFileList(const value: TStringList);
procedure CallOnUpDate;
procedure CallOnBitmapsDone;
procedure CallOnBadBitmap;
procedure CompInvalid;
procedure MakeBitmapList;
procedure AviWriterProgress(Sender: TObject; FrameCount: integer; var abort: boolean);
procedure AviWriterBadBitmap(Sender: TObject; bmp: TBitmap; InfoHeaderSize, BitsSize: integer);
{ Private declarations }
protected
procedure Execute; override;
public
AviWidth, AviHeight, AviFrameTime: integer;
Avifile: string;
musiclist: TStringlist;
FourCC: TFourCC;
quality: integer;
ImageTime, TransitTime: integer;
constructor Create(CreateSuspended: boolean);
destructor Destroy; override;
property ImageFileList: TStringList read fImageFileList write SetImageFileList;
property WritingTemporary: boolean read fTempWrite;
property Cancelled: boolean read fCancelled;
//either cancelled by user or by main thread via calling Terminate
property OnUpdate: TProgressEvent read fOnUpdate write fOnUpdate;
property OnBitmapsDone: TBitmapsDoneEvent read fOnBitmapsDone write fOnBitmapsDone;
property OnBadBitmap: TBadBitmapEvent read fOnBadBitmap write fOnBadBitmap;
end;
implementation
uses SysUtils, Dialogs, HelperProcs, math, Forms;
{ TTransObject }
constructor TTransObject.Create;
begin
fTransitTime := 8000;
ftInv := 1 / 8000;
fImageTime := 16000;
end;
destructor TTransObject.Destroy;
begin
inherited;
end;
procedure TTransObject.Finalize;
begin
fsbm.Free;
ftbm.Free;
fres.Free;
end;
procedure TTransObject.Initialize(sbm, tbm: TBitmap);
begin
if (sbm.Width <> tbm.Width) or (sbm.Height <> tbm.Height) then
raise Exception.Create('Source and Target must have same dimensions.');
fsbm := TBitmap.Create;
ftbm := TBitmap.Create;
fres := TBitmap.Create;
fsbm.assign(sbm);
ftbm.assign(tbm);
fsbm.PixelFormat := pf24bit;
ftbm.PixelFormat := pf24bit;
fres.PixelFormat := pf24bit; //to be safe
fres.Width := fsbm.Width;
fres.Height := fsbm.Height;
end;
procedure TTransObject.Render(t: integer);
begin
end;
procedure TTransObject.SetTransittime(const value: integer);
begin
if value <= 0 then
raise Exception.Create('Transition time must be positive');
fTransitTime := value;
ftInv := 1 / value;
end;
procedure TTransObject.WriteToAvi(const AviWriter: TAviWriter_2; sbm, tbm: TBitmap; NewWidth, NewHeight: integer);
var t: integer;
Temp: TBitmap;
DoStretch: boolean;
begin
t := 0;
Initialize(sbm, tbm);
DoStretch := (sbm.Width <> NewWidth) or (sbm.Height <> NewHeight);
while (t < fTransitTime) and (not AviWriter.Aborted) do
begin
Render(t);
if DoStretch then
begin
Temp := TBitmap.Create;
try
Temp.PixelFormat := pf24bit;
Temp.Width := NewWidth;
Temp.Height := NewHeight;
Temp.Canvas.Lock;
try
fres.Canvas.Lock;
try
CopyRectEx(Temp.Canvas, Rect(0, 0, NewWidth, NewHeight), fres, Rect(0, 0, fres.Width, fres.Height), true);
finally
fres.Canvas.UnLock;
end;
finally
Temp.Canvas.UnLock;
end;
AviWriter.AddFrame(Temp);
finally
Temp.Free;
end;
end
else
AviWriter.AddFrame(fres);
t := t + AviWriter.FrameTime;
end;
if DoStretch then
begin
Temp := TBitmap.Create;
try
Temp.PixelFormat := pf24bit;
Temp.Width := NewWidth;
Temp.Height := NewHeight;
Temp.Canvas.Lock;
try
ftbm.Canvas.Lock;
try
CopyRectEx(Temp.Canvas, Rect(0, 0, NewWidth, NewHeight), ftbm, Rect(0, 0, ftbm.Width, ftbm.Height), true);
finally
ftbm.Canvas.UnLock;
end;
finally
Temp.Canvas.UnLock;
end;
AviWriter.AddStillImage(Temp, fImageTime - fTransitTime);
finally
Temp.Free;
end;
end
else
AviWriter.AddStillImage(ftbm, fImageTime - fTransitTime);
Finalize;
end;
{ TFadeObject }
procedure TFadeObject.Render(t: integer);
var
alpha: double;
TimeLeft, n, m: integer;
at, bt: PAlphaTable;
begin
inherited;
TimeLeft := max(fTransitTime - t, 0);
alpha := AlphaHigh * ftInv * TimeLeft;
n := round(alpha);
m := AlphaHigh - n;
at := @FracAlphaTable[n];
bt := @FracAlphaTable[m];
Tween3(fsbm, ftbm, fres, at, bt);
end;
{ TAviThread }
procedure TAviThread.AviWriterProgress(Sender: TObject;
FrameCount: integer; var abort: boolean);
begin
fFrameCount := FrameCount;
SYNCHRONIZE(CallOnUpDate);
abort := fCancelled or terminated;
if terminated then
fCancelled := true;
end;
procedure TAviThread.CompInvalid;
begin
ShowMessage('The selected video compression is not supported');
end;
constructor TAviThread.Create(CreateSuspended: boolean);
begin
fImageFileList := TStringList.Create;
fBitmapList := TList.Create;
Musiclist:=TStringlist.create;
inherited Create(CreateSuspended);
end;
destructor TAviThread.Destroy;
var i: integer;
begin
inherited;
for i := 0 to fBitmapList.Count - 1 do
TBitmap(fBitmapList.Items[i]).Free;
fImageFileList.Free;
fBitmapList.Free;
MusicList.free;
end;
procedure TAviThread.Execute;
var i: integer;
sbm, tbm: TBitmap;
begin
fCancelled := false;
MakeBitmapList;
fAviWriter := TAviWriter_2.Create(nil);
try
fAviWriter.Width := AviWidth;
fAviWriter.Height := AviHeight;
fAviWriter.FrameTime := AviFrameTime;
fAviWriter.filename := Avifile;
//fAviWriter.WavFileName := musicfile;
fAviWriter.Stretch := false;
fAviWriter.OnProgress := AviWriterProgress;
fAviWriter.OnBadBitmap := AviWriterBadBitmap;
fAviWriter.PixelFormat := pf24bit;
fAviWriter.SetCompressionQuality(quality);
fAviWriter.SilenceName:=ExtractFilePath(Application.Exename)+'Silence.wav';
try
fAviWriter.SetCompression(FourCC);
except
SYNCHRONIZE(CompInvalid);
FourCC := '';
end;
for i:=0 to musiclist.Count-1 do
fAviWriter.AddWaveFile(musiclist.Strings[i],Integer(musiclist.Objects[i]));
fFadeObject := TFadeObject.Create;
fFadeObject.ImageTime := ImageTime;
fFadeObject.TransitTime := TransitTime;
try
fTempWrite := true;
fFrameCount := 0;
SYNCHRONIZE(CallOnUpDate);
sbm := TBitmap.Create;
try
sbm.PixelFormat := pf24bit;
sbm.Width := NewWidth;
sbm.Height := NewHeight;
sbm.Canvas.Lock;
try
sbm.Canvas.Brush.Color := clBlack;
sbm.Canvas.FillRect(Rect(0, 0, sbm.Width, sbm.Height));
finally
sbm.Canvas.UnLock;
end;
fAviWriter.InitVideo;
fAviWriter.AddFrame(sbm);
fFadeObject.WriteToAvi(fAviWriter, sbm, TBitmap(fBitmapList.Items[0]), NewWidth, NewHeight);
finally
sbm.Free;
end;
for i := 1 to fBitmapList.Count - 1 do
if not fCancelled then
begin
sbm := TBitmap(fBitmapList.Items[i - 1]);
tbm := TBitmap(fBitmapList.Items[i]);
fFadeObject.WriteToAvi(fAviWriter, sbm, tbm, NewWidth, NewHeight);
end
else
Break;
finally
fFadeObject.Free;
end;
fTempWrite := false;
fAviWriter.FinalizeVideo;
fAviWriter.WriteAvi;
finally
fAviWriter.Free;
end;
end;
procedure TAviThread.SetImageFileList(const value: TStringList);
begin
fImageFileList.assign(value);
end;
procedure TAviThread.CallOnUpDate;
begin
if Assigned(fOnUpdate) then
fOnUpdate(Self, fFrameCount, fCancelled);
end;
procedure TAviThread.MakeBitmapList;
var i: integer;
rbm, sbm: TBitmap;
Pic: TPicture;
sasp, tasp: double;
w, h: integer;
r: TRect;
begin
NewWidth := round(9 / 10 * AviWidth);
NewHeight := round(9 / 10 * AviHeight);
//leave a little black frame for those crummy TVs
tasp := NewWidth / NewHeight;
for i := 0 to fImageFileList.Count - 1 do
begin
rbm := TBitmap.Create;
try
Pic := TPicture.Create;
try
Pic.loadfromfile(fImageFileList.Strings[i]);
rbm.PixelFormat := pf24bit;
rbm.Width := Pic.Width;
rbm.Height := Pic.Height;
rbm.Canvas.Lock;
try
rbm.Canvas.draw(0, 0, Pic.Graphic);
finally
rbm.Canvas.UnLock;
end;
finally
Pic.Free;
end;
sasp := rbm.Width / rbm.Height;
sbm := TBitmap.Create;
sbm.PixelFormat := pf24bit;
if sasp > tasp then
begin
w := NewWidth;
h := round(w / sasp);
end
else
begin
h := NewHeight;
w := round(h * sasp);
end;
sbm.Width := NewWidth;
sbm.Height := NewHeight;
sbm.Canvas.Lock;
try
sbm.Canvas.Brush.Color := clBlack;
sbm.Canvas.FillRect(Rect(0, 0, NewWidth, NewHeight));
r.Left := (NewWidth - w) div 2;
r.Top := (NewHeight - h) div 2;
r.Right := r.Left + w;
r.Bottom := r.Top + h;
rbm.Canvas.Lock;
try
CopyRectEx(sbm.Canvas, r, rbm, Rect(0, 0, rbm.Width, rbm.Height), true);
finally
rbm.Canvas.UnLock;
end;
finally
sbm.Canvas.UnLock;
end;
fBitmapList.add(sbm);
finally
rbm.Free;
end;
end;
SYNCHRONIZE(CallOnBitmapsDone);
end;
{procedure TAviThread.WriteToAvi(sbm, tbm: TBitmap);
var t: integer;
Res, Temp: TBitmap;
alpha: double;
TimeLeft, n, m: integer;
at, bt: PAlphaTable;
tinv: double;
begin
t := 0;
if (sbm.Width <> tbm.Width) or (sbm.Height <> tbm.Height) then
raise Exception.Create('Source and Target must have same dimensions.');
sbm.Canvas.Lock;
try
tbm.Canvas.Lock;
try
Res := TBitmap.Create;
try
Res.Canvas.Lock;
try
sbm.PixelFormat := pf24bit;
tbm.PixelFormat := pf24bit; //just to be safe
Res.PixelFormat := pf24bit;
Res.Width := sbm.Width;
Res.Height := sbm.Height;
tinv := 1 / TransitTime;
while (t < TransitTime) and (not fAviWriter.Aborted) do
begin
TimeLeft := max(TransitTime - t, 0);
alpha := AlphaHigh * tinv * TimeLeft;
n := round(alpha);
m := AlphaHigh - n;
at := @FracAlphaTable[n];
bt := @FracAlphaTable[m];
Tween3(sbm, tbm, Res, at, bt);
Temp := TBitmap.Create;
try
Temp.Canvas.Lock;
try
Temp.PixelFormat := pf24bit;
Temp.Width := NewWidth;
Temp.Height := NewHeight;
CopyRectEx(Temp.Canvas, Rect(0, 0, NewWidth, NewHeight), Res, Rect(0, 0, Res.Width, Res.Height), true);
finally
Temp.Canvas.UnLock;
end;
fAviWriter.AddFrame(Temp);
finally
Temp.Free;
end;
t := t + fAviWriter.FrameTime;
end;
finally
Res.Canvas.UnLock;
end;
finally
Res.Free;
end;
if (not fAviWriter.Aborted) then
begin
Temp := TBitmap.Create;
try
Temp.Canvas.Lock;
try
Temp.PixelFormat := pf24bit;
Temp.Width := NewWidth;
Temp.Height := NewHeight;
CopyRectEx(Temp.Canvas, Rect(0, 0, NewWidth, NewHeight), tbm, Rect(0, 0, tbm.Width, tbm.Height), true);
finally
Temp.Canvas.UnLock;
end;
fAviWriter.AddStillImage(Temp, ImageTime - TransitTime);
finally
Temp.Free;
end;
end;
finally
tbm.Canvas.UnLock;
end;
finally
sbm.Canvas.UnLock;
end;
end; }
procedure TAviThread.CallOnBitmapsDone;
begin
if Assigned(fOnBitmapsDone) then
fOnBitmapsDone(Self, fBitmapList, fBitmapList.Count);
end;
procedure TAviThread.AviWriterBadBitmap(Sender: TObject; bmp: TBitmap;
InfoHeaderSize, BitsSize: integer);
begin
fError := TBitmap.Create;
try
fError.assign(bmp);
fErrorHeaderSize := InfoHeaderSize;
fErrorBitsSize := BitsSize;
SYNCHRONIZE(CallOnBadBitmap);
finally
fError.Free;
end;
end;
procedure TAviThread.CallOnBadBitmap;
begin
if Assigned(fOnBadBitmap) then
fOnBadBitmap(Self, fError, fErrorHeaderSize, fErrorBitsSize);
end;
end.
|
unit MasterMind.Evaluator.Mock;
{$IFDEF FPC}{$MODE DELPHI}{$ENDIF}
interface
uses
MasterMind.API;
type
IGuessEvaluatorMock = interface
['{21139CC3-FD94-4DC2-957D-7324C5CA00FB}']
procedure SetEvaluationResult(const Value: TGuessEvaluationResult);
function GetEvaluationResult: TGuessEvaluationResult;
property EvaluationResult: TGuessEvaluationResult read GetEvaluationResult write SetEvaluationResult;
end;
TMasterMindGuessEvaluatorMock = class(TInterfacedObject, IGuessEvaluator, IGuessEvaluatorMock)
private
FEvaluation: TGuessEvaluationResult;
public
function EvaluateGuess(const CodeToBeGuessed: TMasterMindCode; const Guess: TMasterMindCode): TGuessEvaluationResult;
procedure SetEvaluationResult(const Value: TGuessEvaluationResult);
function GetEvaluationResult: TGuessEvaluationResult;
end;
implementation
function TMasterMindGuessEvaluatorMock.EvaluateGuess(const CodeToBeGuessed: TMasterMindCode; const Guess: TMasterMindCode): TGuessEvaluationResult;
begin
Result := FEvaluation;
end;
procedure TMasterMindGuessEvaluatorMock.SetEvaluationResult(const Value: TGuessEvaluationResult);
begin
FEvaluation := Value;
end;
function TMasterMindGuessEvaluatorMock.GetEvaluationResult: TGuessEvaluationResult;
begin
Result := FEvaluation;
end;
end. |
unit uSignItems;
{ .$define debug }
interface
uses
SysUtils,
Windows,
Classes,
Graphics,
Controls,
StdCtrls,
CheckLst,
ORClasses,
ORCtrls,
Dialogs,
UBAConst,
fODBase,
UBACore,
Forms;
type
TSigItemType = (siServiceConnected, siAgentOrange, siIonizingRadiation,
siEnvironmentalContaminants, siMST, siHeadNeckCancer, siCombatVeteran, siSHAD, siCL);
TSigItemTagInfo = record
SigType: TSigItemType;
Index: integer;
end;
TlbOnDrawEvent = record
xcontrol: TWinControl;
xevent: TDrawItemEvent;
end;
TSigItems = class(TComponent)
private
FBuilding: boolean;
FStsCount: integer;
FItems: TORStringList;
FOldDrawItemEvent: TDrawItemEvent;
FOldDrawItemEvents: array of TlbOnDrawEvent;
Fcb: TList;
Flb: TCustomListBox;
FLastValidX: integer;
FValidGap: integer;
FDy: integer;
FAllCheck: array [TSigItemType] of boolean;
FAllCatCheck: boolean;
FcbX: array [TSigItemType] of integer;
function TagInfo(ASigType: TSigItemType; AIndex: integer): TSigItemTagInfo;
procedure cbClicked(Sender: TObject);
procedure cbEnter(Sender: TObject);
procedure cbExit(Sender: TObject);
procedure lbDrawItem(Control: TWinControl; Index: integer; Rect: TRect; State: TOwnerDrawState);
procedure CopyCBValues(FromIndex, ToIndex: integer);
function FindCBValues(ATag: integer): TORCheckBox;
function GetTempCkBxState(Index: integer; CBValue: TSigItemType): string;
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Add(ItemType: integer; const ID: string; Index: integer);
procedure Remove(ItemType: integer; const ID: string);
procedure ResetOrders;
procedure Clear;
procedure ClearDrawItems;
procedure ClearFcb;
function UpdateListBox(lb: TCustomListBox): boolean;
procedure EnableSettings(Index: integer; Checked: boolean);
function OK2SaveSettings: boolean;
procedure SaveSettings;
procedure DisplayPlTreatmentFactors;
procedure DisplayUnsignedStsFlags(sFlags: string);
function ItemToTag(Info: TSigItemTagInfo): integer; // CQ5074
function TagToItem(ATag: integer): TSigItemTagInfo; // CQ5074
end;
function SigItems: TSigItems;
function SigItemsCS: TSigItems;
function SigItemHeight: integer;
function GetAllBtnLeftPos: integer;
const
SIG_ITEM_VERTICAL_PAD = 2;
TC_Order_Error = 'All Service Connection and/or Rated Disabilities questions must be answered, ' + #13 +
'and at least one diagnosis selected for each order that requires a diagnosis.';
TX_Order_Error = 'All Service Connection and/or Rated Disabilities questions must be answered, ' + #13 +
'and at least one diagnosis selected for each order that requires a diagnosis.';
TC_Diagnosis_Error = ' Missing Diagnosis';
TX_Diagnosis_Error = ' One or more Orders have not been assigned a Diagnosis';
INIT_STR = '';
var
uSigItems: TSigItems = nil; // BAPHII 1.3.1
uSigItemsCS: TSigItems = nil;
implementation
uses
ORFn,
ORNet,
uConst,
TRPCB,
rOrders,
rPCE,
UBAGlobals,
uGlobalVar,
uCore,
VAUtils,
rMisc;
type
ItemStatus = (isNA, isChecked, isUnchecked, isUnknown);
SigDescType = (sdShort, sdLong);
const
SigItemDesc: array [TSigItemType, SigDescType] of string =
{ siServiceConnected } (('SC', 'Service Connected Condition'),
{ siAgentOrange } ('AO', 'Agent Orange Exposure'),
{ siIonizingRadiation } ('IR', 'Ionizing Radiation Exposure'),
{ siEnvironmentalContaminants } ('SWAC', 'Southwest Asia Conditions'),
{ siMST } ('MST', 'MST'), // 'Military Sexual Trauma'
{ siHeadNeckCancer } ('HNC', 'Head and/or Neck Cancer'),
{ siCombatVeteran } ('CV', 'Combat Veteran Related'),
{ siSHAD } ('SHD', 'Shipboard Hazard and Defense'),
{ siCL } ('CL', 'Camp Lejeune'));
SigItemDisplayOrder: array [TSigItemType] of TSigItemType =
(siServiceConnected,
siCombatVeteran,
siAgentOrange,
siIonizingRadiation,
siEnvironmentalContaminants,
siSHAD,
siMST,
siHeadNeckCancer,
siCL);
StsChar: array [ItemStatus] of char =
{ isNA } ('N',
{ isChecked } 'C',
{ isUnchecked } 'U',
{ isUnknown } '?');
ColIdx = 30000;
AllIdx = 31000;
NA_FLAGS = 'NNNNNNNN';
NA_FLAGS_CL = 'NNNNNNNNN';
var
uSingletonFlag: boolean = FALSE;
FlagCount: integer;
BaseFlags: string;
tempCkBx: TORCheckBox;
thisOrderID: string;
thisChangeItem: TChangeItem;
AllBtnLeft: integer;
function SigItems: TSigItems;
begin
if not assigned(uSigItems) then
begin
uSingletonFlag := TRUE;
try
uSigItems := TSigItems.Create(nil);
finally
uSingletonFlag := FALSE;
end;
end;
Result := uSigItems;
end;
function SigItemsCS: TSigItems;
begin
if not assigned(uSigItemsCS) then
begin
uSingletonFlag := TRUE;
try
uSigItemsCS := TSigItems.Create(nil);
finally
uSingletonFlag := FALSE;
end;
end;
Result := uSigItemsCS;
end;
function SigItemHeight: integer;
begin
Result := abs(BaseFont.height) + 2 + SIG_ITEM_VERTICAL_PAD;
end;
function GetAllBtnLeftPos: integer;
begin
Result := uSignItems.AllBtnLeft;
end;
{ TSigItems }
{
FItems Layout:
1 2 3 4 5
OrderID ^ ListBox Index ^ RPC Call was Made (0 or 1) ^ Settings by char pos ^ Disabled Flag
}
procedure TSigItems.Add(ItemType: integer; const ID: string; Index: integer);
var
idx: integer;
begin
if ItemType = CH_ORD then
begin
idx := FItems.IndexOfPiece(ID);
if idx < 0 then
idx := FItems.Add(ID);
FItems.SetStrPiece(idx, 2, IntToStr(Index));
FItems.SetStrPiece(idx, 5, INIT_STR); // hds4807 value was being reatained when same order selected in FReview.
end;
end;
procedure TSigItems.Clear;
begin
FItems.Clear;
Fcb.Clear;
Finalize(FOldDrawItemEvents);
end;
procedure TSigItems.ClearDrawItems;
begin
Finalize(FOldDrawItemEvents);
end;
procedure TSigItems.ClearFcb;
begin
Fcb.Clear;
end;
constructor TSigItems.Create(AOwner: TComponent);
begin
if not uSingletonFlag then
raise Exception.Create('Only one instance of TSigItems allowed');
inherited Create(AOwner);
FItems := TORStringList.Create;
Fcb := TList.Create;
tempCkBx := TORCheckBox.Create(AOwner);
end;
destructor TSigItems.Destroy;
begin
FreeAndNil(FItems);
FreeAndNil(Fcb);
inherited;
end;
procedure TSigItems.Remove(ItemType: integer; const ID: string);
var
idx: integer;
begin
if ItemType = CH_ORD then
begin
idx := FItems.IndexOfPiece(ID);
if idx >= 0 then
FItems.Delete(idx);
end;
end;
procedure TSigItems.ResetOrders; // Resets ListBox positions, to avoid old data messing things up
var
i: integer;
begin
for i := 0 to FItems.Count - 1 do
FItems.SetStrPiece(i, 2, '-1');
end;
function TSigItems.ItemToTag(Info: TSigItemTagInfo): integer;
begin
if Info.Index < 0 then
Result := 0
else
Result := (Info.Index * FlagCount) + ord(Info.SigType) + 1;
end;
function TSigItems.TagInfo(ASigType: TSigItemType; AIndex: integer): TSigItemTagInfo;
begin
Result.SigType := ASigType;
Result.Index := AIndex;
end;
function TSigItems.TagToItem(ATag: integer): TSigItemTagInfo;
begin
if ATag <= 0 then
begin
Result.Index := -1;
Result.SigType := TSigItemType(0);
end
else
begin
dec(ATag);
Result.SigType := TSigItemType(ATag mod FlagCount);
Result.Index := ATag div FlagCount;
end;
end;
type
TExposedListBox = class(TCustomListBox)
public
property OnDrawItem;
end;
function TSigItems.UpdateListBox(lb: TCustomListBox): boolean;
const
cbWidth = 13;
cbHeight = 13;
btnGap = 2;
AllTxt = 'All';
var
cb: TORCheckBox;
btn: TButton;
lbl: TLabel;
prnt: TWinControl;
ownr: TComponent;
FirstValidItem: TSigItemType;
x, y, MaxX, i, btnW, btnH, j, dx, ht, idx, dgrp: integer;
s, ID, Code, cType, Flags, OrderStatus, CVFlag, ChangedFlags: string;
odie: TlbOnDrawEvent;
StsCode: char;
sx, si: TSigItemType;
sts, StsIdx: ItemStatus;
StsUsed: array [TSigItemType] of boolean;
AResponses: TResponses;
UFlags, HoldFlags: string;
thisCB: TORCheckBox;
cpFlags: string;
itemText: string;
thisTagInfo: TSigItemTagInfo;
function CreateCB(AParent: TWinControl): TORCheckBox;
begin
Result := TORCheckBox.Create(ownr);
Result.Parent := AParent;
Result.height := cbHeight;
Result.Width := cbWidth;
Result.GrayedStyle := gsBlueQuestionMark;
Result.GrayedToChecked := FALSE;
Result.OnClick := cbClicked;
Result.OnEnter := cbEnter;
Result.OnExit := cbExit;
UpdateColorsFor508Compliance(Result);
Fcb.Add(Result);
end;
function notRightOne(cnter: integer): boolean;
var
ID, idx: string;
ix: integer;
begin
Result := TRUE;
ID := piece(FItems[cnter], '^', 1);
for ix := 0 to lb.Items.Count - 1 do
begin
if lb.Items.Objects[ix] is TOrder then
begin
idx := TOrder(lb.Items.Objects[ix]).ID;
if ID = idx then
Result := FALSE;
end;
if lb.Items.Objects[ix] is TChangeItem then
begin
idx := TChangeItem(lb.Items.Objects[ix]).ID;
if ID = idx then
Result := FALSE;
end;
end;
end;
begin
Result := FALSE;
// Fcb.Clear;
FBuilding := TRUE;
try
try
idx := 0;
LockBroker;
try
RPCBrokerV.ClearParameters := TRUE;
for i := 0 to FItems.Count - 1 do
begin
if notRightOne(i) then
continue;
s := FItems[i];
thisOrderID := piece(s, U, 1);
if BILLING_AWARE then
if not UBACore.IsOrderBillable(thisOrderID) then
RemoveOrderFromDxList(thisOrderID);
if (piece(s, U, 2) <> '-1') and (piece(s, U, 3) <> '1') then
begin
with RPCBrokerV do
begin
if idx = 0 then
Param[1].PType := list;
inc(idx);
Param[1].Mult[IntToStr(idx)] := piece(s, U, 1);
end;
end;
end; // for
if idx > 0 then
begin
rpcGetSC4Orders;
for i := 0 to RPCBrokerV.Results.Count - 1 do
begin
s := RPCBrokerV.Results[i];
{ Begin BillingAware }
if BILLING_AWARE then
begin
if (CharAt(piece(s, ';', 2), 1) <> '1') then
s := piece(s, U, 1);
end; { End BillingAware }
ID := piece(s, U, 1);
idx := FItems.IndexOfPiece(ID);
if idx >= 0 then
begin
FItems.SetStrPiece(idx, 3, '1'); // Mark as read from RPC
j := 2;
Flags := BaseFlags;
repeat
Code := piece(s, U, j);
if Code = 'EC' then
Code := 'SWAC'; // CQ:15431 ; resolve issue of displaying SWAC vs EC.
if Code <> '' then
begin
cType := piece(Code, ';', 1);
for si := low(TSigItemType) to high(TSigItemType) do
begin
if cType = SigItemDesc[si, sdShort] then
begin
cType := piece(Code, ';', 2);
if cType = '0' then
sts := isUnchecked
else
if cType = '1' then
sts := isChecked
else
sts := isUnknown;
Flags[ord(si) + 1] := StsChar[sts];
break;
end; // if cType = SigItemDesc[si, sdShort]
end; // for
end; // if Code <> ''
inc(j);
until (Code = '');
FItems.SetStrPiece(idx, 4, Flags);
// new code if deleted order and ba on then
// reset appropriate tf flags to "?".
if BILLING_AWARE then
begin
if not UBACore.OrderRequiresSCEI(piece(s, U, 1)) then
begin
if IsLejeuneActive then
FItems.SetStrPiece(idx, 4, NA_FLAGS_CL)
else
FItems.SetStrPiece(idx, 4, NA_FLAGS);
end
else
begin
if UBAGlobals.BAUnsignedOrders.Count > 0 then
begin
UFlags := UBACore.GetUnsignedOrderFlags(piece(s, U, 1), UBAGlobals.BAUnsignedOrders);
if UFlags <> '' then
FItems.SetStrPiece(idx, 4, UFlags)
end;
// ********************************
if UBAGlobals.BACopiedOrderFlags.Count > 0 then // BAPHII 1.3.2
begin
UFlags := UBACore.GetUnsignedOrderFlags(piece(s, U, 1), UBAGlobals.BACopiedOrderFlags); // BAPHII 1.3.2
if UFlags <> '' then // BAPHII 1.3.2
FItems.SetStrPiece(idx, 4, UFlags); // BAPHII 1.3.2
end;
// ********************************
if UBAGlobals.BAConsultPLFlags.Count > 0 then
begin
UFlags := GetConsultFlags(piece(s, U, 1), UBAGlobals.BAConsultPLFlags, Flags);
if UFlags <> '' then
FItems.SetStrPiece(idx, 4, UFlags);
end;
UBAGlobals.BAFlagsIN := Flags;
end; // else
end; // if BILLING_AWARE
end; // if idx >= 0
end; // for i := 0 to RPCBrokerV.Results.Count-1
end; // if idx > 0
finally
UnlockBroker;
end;
FStsCount := 0;
AllBtnLeft := 0;
for si := low(TSigItemType) to high(TSigItemType) do
StsUsed[si] := FALSE;
// loop thru orders selected to be signed
for i := 0 to FItems.Count - 1 do
begin
if notRightOne(i) then
continue;
s := FItems[i];
if (piece(s, U, 2) <> '-1') and (piece(s, U, 3) = '1') then
begin
s := piece(s, U, 4); // SC/EI
// code added 01/17/2006 - check dc'd nurse orders,
// originals where requiring CIDC if assigned to patient.
if (BILLING_AWARE) and (not UBACore.IsOrderBillable(piece(s, U, 1))) then
if IsLejeuneActive then
s := NA_FLAGS_CL
else
s := NA_FLAGS;
for si := low(TSigItemType) to high(TSigItemType) do
// if (not StsUsed[si]) and (s[ord(si) + 1] <> StsChar[isNA]) then
if (not StsUsed[si]) and ((length(s) > ord(si)) and
(s[ord(si) + 1] <> StsChar[isNA])) then
begin
StsUsed[si] := TRUE;
inc(FStsCount);
if FStsCount >= FlagCount then
break;
end;
end;
if FStsCount >= FlagCount then
break;
end; // for
{ Begin BillingAware }
if BILLING_AWARE then
begin
if FStsCount = 0 then // Billing Awareness. Force Grid to paint correctly
FStsCount := 1;
end;
{ End BillingAware }
if FStsCount > 0 then
begin
Result := TRUE;
FirstValidItem := TSigItemType(0);
prnt := lb.Parent;
ownr := lb.Owner;
MaxX := lb.ClientWidth;
lb.Canvas.Font := BaseFont;
btnW := 0;
for si := low(TSigItemType) to high(TSigItemType) do
begin
j := lb.Canvas.TextWidth(SigItemDesc[si, sdShort]);
if btnW < j then
btnW := j;
end;
inc(btnW, 8);
btnH := ResizeHeight(BaseFont, BaseFont, 21);
x := MaxX;
dx := (btnW - cbWidth) div 2;
for si := high(TSigItemType) downto low(TSigItemType) do
begin
FcbX[si] := x - btnW + dx;
dec(x, btnW + btnGap);
end;
if FStsCount > 1 then
begin
FAllCatCheck := FALSE;
btn := TButton.Create(ownr);
btn.Parent := prnt;
btn.height := btnH;
btn.Width := btnW;
btn.Caption := AllTxt;
btn.OnClick := cbClicked;
btn.Left := FcbX[TSigItemType(0)] + lb.Left - dx + 2 - (FcbX[TSigItemType(1)] - FcbX[TSigItemType(0)]);
AllBtnLeft := btn.Left;
btn.Top := lb.Top - btn.height - 2;
btn.Tag := AllIdx;
btn.ShowHint := TRUE;
btn.Hint := 'Set All Related Entries';
btn.TabOrder := lb.TabOrder;
UpdateColorsFor508Compliance(btn);
Fcb.Add(btn);
end;
for sx := low(TSigItemType) to high(TSigItemType) do
begin // print buttons on header of columns ie SC,AO,IR, etc....
si := SigItemDisplayOrder[sx];
if (si = siCL) and (not IsLejeuneActive) then
continue;
FAllCheck[si] := TRUE;
btn := TButton.Create(ownr);
btn.Parent := prnt;
btn.height := btnH;
btn.Width := btnW;
btn.Caption := SigItemDesc[si, sdShort];
btn.OnClick := cbClicked;
btn.Left := FcbX[sx] + lb.Left - dx + 2;
btn.Top := lb.Top - btn.height - 2;
btn.Tag := ColIdx + ord(si);
btn.ShowHint := TRUE;
btn.Hint := 'Set all ' + SigItemDesc[si, sdLong];
btn.Enabled := StsUsed[si];
// tab order before listbox but after previous buttons.
btn.TabOrder := lb.TabOrder;
UpdateColorsFor508Compliance(btn);
Fcb.Add(btn);
end;
FValidGap := ((FcbX[succ(TSigItemType(0))] - FcbX[TSigItemType(0)] - cbWidth) div 2) + 1;
FLastValidX := FcbX[FirstValidItem] - FValidGap;
lb.ControlStyle := lb.ControlStyle + [csAcceptsControls];
try
ht := SigItemHeight;
FDy := ((ht - cbHeight) div 2) + 1;
y := lb.TopIndex;
FOldDrawItemEvent := TExposedListBox(lb).OnDrawItem;
odie.xcontrol := lb;
odie.xevent := FOldDrawItemEvent;
SetLength(FOldDrawItemEvents, Length(FOldDrawItemEvents) + 1);
FOldDrawItemEvents[Length(FOldDrawItemEvents) - 1] := odie;
Flb := lb;
TExposedListBox(lb).OnDrawItem := lbDrawItem;
lb.FreeNotification(Self);
for i := 0 to FItems.Count - 1 do
begin
if notRightOne(i) then
continue;
s := FItems[i];
OrderStatus := (piece(s, U, 1));
if piece(s, U, 3) = '1' then
begin
idx := StrToIntDef(piece(s, U, 2), -1);
if idx >= 0 then
begin
Flags := piece(s, U, 4);
// loop thru treatment factors
for sx := low(TSigItemType) to high(TSigItemType) do
begin
si := SigItemDisplayOrder[sx];
if (si = siCL) and (not IsLejeuneActive) then
continue;
StsCode := Flags[ord(si) + 1];
StsIdx := isNA;
for sts := low(ItemStatus) to high(ItemStatus) do
if StsCode = StsChar[sts] then
begin
StsIdx := sts;
break;
end;
if (StsIdx <> isNA) then
begin
cb := CreateCB(lb);
cb.Left := FcbX[sx];
cb.Top := (ht * (idx - y)) + FDy;
cb.Tag := ItemToTag(TagInfo(si, idx));
cb.ShowHint := TRUE;
cb.Hint := SigItemDesc[si, sdLong];
// CQ3301/3302
thisTagInfo := TagToItem(cb.Tag);
itemText := '';
thisChangeItem := nil; // init
thisChangeItem := TChangeItem(lb.Items.Objects[thisTagInfo.Index]);
if (thisChangeItem <> nil) then
begin
itemText := (FilteredString(lb.Items[thisTagInfo.Index]));
cb.Caption := itemText + cb.Hint; // CQ3301/3302 - gives JAWS a caption to read
end;
// end CQ3301/3302
if ((si = siCombatVeteran) and (StsIdx = isUnknown)) then
begin
StsIdx := isChecked;
Flags[7] := 'C'; // HD200866 default as Combat Related - GWOT mandated Change
FItems.SetStrPiece(i, 4, Flags); // HD200866 default as Combat Related - GWOT mandated Change
end;
case StsIdx of
isChecked:
cb.State := cbChecked;
isUnchecked:
cb.State := cbUnchecked;
else
cb.State := cbGrayed;
end; // case
end; // if (StsIdx <> isNA)
end; // for sx := low(TSigItemType) to high(TSigItemType)
end; // if idx >= 0
end; // if piece(s,u,3) = '1'
end; // for i := 0 to FItems.Count-1
finally
lb.ControlStyle := lb.ControlStyle - [csAcceptsControls];
end; // if FStsCount > 0
end;
finally
FBuilding := FALSE;
end;
except
on ERangeError do
begin
ShowMsg('ERangeError in UpdateListBox' + s);
raise;
end;
end;
end;
procedure TSigItems.cbClicked(Sender: TObject);
var
i, cnt, p: integer;
cb: TORCheckBox;
sType: TSigItemType;
idx, Flags: string;
Info: TSigItemTagInfo;
wc, w: TWinControl;
begin
if FBuilding then
exit;
wc := TWinControl(Sender);
if wc.Tag = AllIdx then
begin
FAllCatCheck := not FAllCatCheck;
for sType := low(TSigItemType) to high(TSigItemType) do
FAllCheck[sType] := FAllCatCheck;
cnt := 0;
for i := 0 to Fcb.Count - 1 do
begin
w := TWinControl(Fcb[i]);
if (w <> wc) and (w.Tag >= ColIdx) and (w is TButton) then
begin
inc(cnt);
if w.Enabled then
TButton(w).Click;
if cnt >= FlagCount then
break;
end;
end;
end
else
if wc.Tag >= ColIdx then
begin
sType := TSigItemType(wc.Tag - ColIdx);
FAllCheck[sType] := not FAllCheck[sType];
for i := 0 to Fcb.Count - 1 do
begin
w := TWinControl(Fcb[i]);
if (w.Tag < ColIdx) and (w is TORCheckBox) then
begin
if TagToItem(w.Tag).SigType = sType then
TORCheckBox(w).Checked := FAllCheck[sType];
end;
end;
end
else
begin
cb := TORCheckBox(wc);
Info := TagToItem(cb.Tag);
if Info.Index >= 0 then
begin
idx := IntToStr(Info.Index);
i := FItems.IndexOfPiece(idx, U, 2);
if i >= 0 then
begin
p := ord(Info.SigType) + 1;
Flags := piece(FItems[i], U, 4);
case cb.State of
cbUnchecked:
Flags[p] := StsChar[isUnchecked];
cbChecked:
Flags[p] := StsChar[isChecked];
else
Flags[p] := StsChar[isUnknown];
end;
FItems.SetStrPiece(i, 4, Flags);
if BILLING_AWARE then
UBAGlobals.BAFlagsIN := Flags;
end;
end;
end;
end;
procedure TSigItems.cbEnter(Sender: TObject);
var
cb: TORCheckBox;
begin
cb := TORCheckBox(Sender);
cb.Color := clHighlight;
cb.Font.Color := clHighlightText;
// commented out causing check box states to be out of sync when
// checked individually and/or when by column or all.
// CQ5074
if ((cb.Focused) and (cb.State = cbGrayed)) and (not IsAMouseButtonDown) then
cb.Checked := FALSE;
// end CQ5074
end;
procedure TSigItems.cbExit(Sender: TObject);
var
cb: TORCheckBox;
begin
cb := TORCheckBox(Sender);
cb.Color := clWindow;
cb.Font.Color := clWindowText;
end;
procedure TSigItems.lbDrawItem(Control: TWinControl; Index: integer; Rect: TRect; State: TOwnerDrawState);
var
OldRect: TRect;
i, j: integer;
cb: TORCheckBox;
si: TSigItemType;
DrawGrid: boolean;
lb: TCustomListBox;
begin
lb := TCaptionCheckListBox(Control);
DrawGrid := (Index < lb.Items.Count);
if DrawGrid and (trim(lb.Items[Index]) = '') and
(Index = (lb.Items.Count - 1)) then
DrawGrid := FALSE;
if DrawGrid then
dec(Rect.Bottom);
OldRect := Rect;
Rect.Right := FLastValidX - 4;
{ Begin BillingAware }
if BILLING_AWARE then
Rect.Right := FLastValidX - 55;
{ End BillingAware }
// if assigned(FOldDrawItemEvent) then
if TRUE then
begin
for j := 0 to Length(FOldDrawItemEvents) - 1 do
begin
if FOldDrawItemEvents[j].xcontrol = lb then
begin
inc(Rect.Bottom);
FOldDrawItemEvents[j].xevent(Control, Index, Rect, State);
dec(Rect.Bottom);
end;
end;
// inc(Rect.Bottom);
// FOldDrawItemEvent(Control, Index, Rect, State);
// dec(Rect.Bottom);
end
else
begin
lb.Canvas.FillRect(Rect);
if Index < lb.Items.Count then
lb.Canvas.TextRect(Rect, Rect.Left + 2, Rect.Top, FilteredString(lb.Items[Index]));
end;
if DrawGrid then
begin
lb.Canvas.Pen.Color := Get508CompliantColor(clSilver);
lb.Canvas.MoveTo(Rect.Left, Rect.Bottom);
lb.Canvas.LineTo(OldRect.Right, Rect.Bottom);
end;
if BILLING_AWARE then
OldRect.Left := Rect.Right + 90
else
OldRect.Left := Rect.Right;
/// / SC Column
///
lb.Canvas.FillRect(OldRect);
for i := 0 to Fcb.Count - 1 do
begin
cb := TORCheckBox(Fcb[i]);
if TagToItem(cb.Tag).Index = Index then
begin
cb.Invalidate;
cb.Top := Rect.Top + FDy;
end;
end;
// EI Columns
if DrawGrid then
begin
for si := low(TSigItemType) to high(TSigItemType) do
begin
if FcbX[si] > FLastValidX then
begin
if (si = siCL) and (not IsLejeuneActive) then
continue;
lb.Canvas.MoveTo(FcbX[si] - FValidGap, Rect.Top);
lb.Canvas.LineTo(FcbX[si] - FValidGap, Rect.Bottom);
end;
end;
end;
end;
procedure TSigItems.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (AComponent = Flb) and (Operation = opRemove) then
begin
Fcb.Clear;
TExposedListBox(Flb).OnDrawItem := FOldDrawItemEvent;
FOldDrawItemEvent := nil;
Flb := nil;
end;
end;
procedure TSigItems.EnableSettings(Index: integer; Checked: boolean);
var
cb: TORCheckBox;
i: integer;
Info: TSigItemTagInfo;
begin
if Index < 0 then
exit;
for i := 0 to Fcb.Count - 1 do
begin
if TObject(Fcb[i]) is TORCheckBox then
begin
cb := TORCheckBox(Fcb[i]);
Info := TagToItem(cb.Tag);
if Info.Index = Index then
cb.Enabled := Checked;
end;
end;
i := FItems.IndexOfPiece(IntToStr(Index), U, 2);
if i >= 0 then
FItems.SetStrPiece(i, 5, BoolChar[not Checked]);
end;
function TSigItems.OK2SaveSettings: boolean;
var
i, Index: integer;
s: string;
begin
{ Begin BillingAware }
if BILLING_AWARE then
begin
if assigned(UBAGlobals.BAOrderList) then
BAOrderList.Clear
else
begin
BAOrderList := TStringList.Create;
BAOrderList.Clear;
end;
{ End BillingAware }
end;
Result := TRUE;
for i := 0 to FItems.Count - 1 do
begin
s := FItems[i];
Index := StrToIntDef(piece(s, U, 2), -1);
if (Index >= 0) and (piece(s, U, 5) <> '1') then
begin
if pos(StsChar[isUnknown], piece(s, U, 4)) > 0 then
begin
Result := FALSE;
break;
end { end if }
else
if BILLING_AWARE then
BAOrderList.Add(piece(s, U, 1) + piece(s, U, 3) + piece(s, U, 4)); // baph1
end; { end if }
end; { end for }
end;
procedure TSigItems.SaveSettings;
var
s: string;
i, Index: integer;
TmpSL: TStringList;
begin
TmpSL := TStringList.Create;
try
for i := 0 to FItems.Count - 1 do
begin
s := FItems[i];
Index := StrToIntDef(piece(s, U, 2), -1);
if (Index >= 0) and (piece(s, U, 5) <> '1') then
begin
TmpSL.Add(piece(s, U, 1) + U + piece(s, U, 4));
FItems.SetStrPiece(i, 6, '1');
end;
end;
SaveCoPayStatus(TmpSL);
finally
TmpSL.Free;
end;
i := 0;
while i < FItems.Count do
begin
if piece(FItems[i], U, 6) = '1' then
FItems.Delete(i)
else
inc(i);
end;
Fcb.Clear;
end;
{ Begin Billing Aware }
procedure TSigItems.DisplayUnsignedStsFlags(sFlags: string);
var
Index: integer;
Flags: string;
begin
Index := 0;
Flags := sFlags;
CopyCBValues(Index, Index);
end;
procedure TSigItems.DisplayPlTreatmentFactors;
var
FactorsOut: TStringList;
y: integer;
Index: integer;
begin
FactorsOut := TStringList.Create;
FactorsOut.Clear;
FactorsOut := UBAGlobals.PLFactorsIndexes;
for y := 0 to FactorsOut.Count - 1 do
begin
Index := StrToInt(piece(FactorsOut.Strings[y], U, 1));
CopyCBValues(Index, Index);
end;
end;
procedure TSigItems.CopyCBValues(FromIndex, ToIndex: integer);
var
si: TSigItemType;
FromTag, ToTag: integer;
FromCB, ToCB: TORCheckBox;
x: string;
begin
tempCkBx.GrayedStyle := gsBlueQuestionMark;
for si := low(TSigItemType) to high(TSigItemType) do
begin
FromTag := ItemToTag(TagInfo(si, FromIndex));
ToTag := ItemToTag(TagInfo(si, ToIndex));
FromCB := FindCBValues(FromTag);
ToCB := FindCBValues(ToTag);
if assigned(FromCB) then // and assigned(ToCB)) then
begin
tempCkBx.State := cbGrayed;
x := GetTempCkBxState(FromIndex, si);
if x = 'C' then
tempCkBx.State := cbChecked
else if x = 'U' then
tempCkBx.State := cbUnchecked;
ToCB.State := tempCkBx.State; // FromCB.State;
end;
end; // for
end;
function TSigItems.FindCBValues(ATag: integer): TORCheckBox;
var
i: integer;
wc: TWinControl;
begin
for i := 0 to Fcb.Count - 1 do
begin
wc := TWinControl(Fcb[i]);
if (wc is TORCheckBox) and (wc.Tag = ATag) then
begin
Result := TORCheckBox(wc);
exit;
end;
end;
Result := nil;
end;
function TSigItems.GetTempCkBxState(Index: integer; CBValue: TSigItemType): string;
var
locateIdx, thisIdx, i: integer;
iFactor: integer;
TmpCBStatus: string;
begin
try
locateIdx := Index;
iFactor := ord(CBValue) + 1;
for i := 0 to UBAGlobals.BAFlagsOut.Count - 1 do
begin
thisIdx := StrToInt(piece(UBAGlobals.BAFlagsOut.Strings[i], U, 1));
if thisIdx = locateIdx then
begin
TmpCBStatus := piece(UBAGlobals.BAFlagsOut.Strings[i], U, 2);
TmpCBStatus := Copy(TmpCBStatus, iFactor, 1);
Result := TmpCBStatus;
end;
end;
except
on EAccessViolation do
begin
// {$ifdef debug}Show508Message('EAccessViolation in uSignItems.GetTempCkBxState()');{$endif}
raise;
end;
end;
end;
{ End Billing Aware }
initialization
FlagCount := ord(high(TSigItemType)) - ord(low(TSigItemType)) + 1;
BaseFlags := StringOfChar(StsChar[isNA], FlagCount);
thisChangeItem := TChangeItem.Create; // CQ3301/3302
AllBtnLeft := 0;
finalization
FreeAndNil(uSigItems);
end.
|
unit DialogItems;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls,
Menus, LazUTF8, LCLProc, CommonFunc;
const
clHighLightMsg = TColor($FFC0C0);
type
{ TDialogItem }
TDialogItem = class(TCustomControl {CustomPanel})
// Элемент диалога
private
fPicture: TPicture;
fNameCollocutor: string; // Имя собеседника
fText: string;
fTime: string;
fAttachCount: TLabel;
fAttachPopup: TPopupMenu;
procedure EnterMouse(Sender: TObject);
procedure LeaveMouse(Sender: TObject);
procedure EnterMouseForAttachPopup(Sender: TObject);
procedure LeaveMouseForAttachPopup(Sender: TObject);
procedure OnClickAttach(Sender: TObject);
function GetTextHeigh(AText: string): integer;
private
function GetPicture: TPicture;
procedure SetAttachCount(AValue: integer);
procedure SetNameCollocutor(AValue: string);
procedure SetPicture(AValue: TPicture);
procedure SetText(AValue: string);
procedure SetTime(AValue: TDateTime);
// Разбить текст на строки, что бы он влазил в определенную ширину
procedure FormatTextWithMaxWidth(const TextIn: string; StringList: TStringList; MaxWidthPixels: integer);
protected
procedure Paint; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
public
// Перестроить размер окна
procedure ReAlign; dynamic;
// Заполнение окна
procedure Establish(AName, AText: string; ATime: TDateTime);
// Информация о вложениях
procedure ClearAttachInfo;
procedure AddAttachInfo(AFileName: string; AOnClick: TNotifyEvent);
property AttachCount: integer write SetAttachCount;
// Настройки
property Picture: TPicture read GetPicture write SetPicture;
property NameCollocutor: string write SetNameCollocutor;
property Text: string write SetText;
property Time: TDateTime write SetTime;
// Доп.свойства
property OnMouseWheelUp;
property OnMouseWheelDown;
end;
implementation
{ TDialogItem }
procedure TDialogItem.EnterMouse(Sender: TObject);
// Вход мыши в контрол
begin
if (self is TDialogItem) then
(self as TDialogItem).Color := clHighLightMsg
else
(self.Parent as TDialogItem).Color := clHighLightMsg;
end;
procedure TDialogItem.LeaveMouse(Sender: TObject);
// Уход мыши из контрола
begin
if (self is TDialogItem) then
(self as TDialogItem).Color := clWhite
else
(self.Parent as TDialogItem).Color := clWhite;
end;
procedure TDialogItem.EnterMouseForAttachPopup(Sender: TObject);
// Заход мыши на метку вложений
begin
EnterMouse(Sender);
fAttachCount.Font.Style := [fsUnderline];
end;
procedure TDialogItem.LeaveMouseForAttachPopup(Sender: TObject);
// Выход мыши из метки вложений
begin
LeaveMouse(Sender);
fAttachCount.Font.Style := [];
end;
procedure TDialogItem.OnClickAttach(Sender: TObject);
// Открытия меню вложений
var
ScreenCoord: TPoint;
begin
ScreenCoord.X := fAttachCount.Left;
ScreenCoord.Y := fAttachCount.Top + fAttachCount.Height;
ScreenCoord := ClientToScreen(ScreenCoord);
fAttachPopup.PopUp(ScreenCoord.X, ScreenCoord.Y);
end;
function TDialogItem.GetTextHeigh(AText: string): integer;
// Получить высоту текста
var
i: integer;
begin
Result := 0;
for i := 0 to Length(AText) - 1 do
if (AText[i] = #13) or (AText[i] = #10) then
Inc(Result, 1);
Result := Result * (Canvas.Font.GetTextHeight('a') + 1);
end;
function TDialogItem.GetPicture: TPicture;
begin
Result := fPicture;
end;
procedure TDialogItem.SetAttachCount(AValue: integer);
// устанавливает количество файлов в сообщении
var
StrDesc: string;
LastCh: integer;
begin
StrDesc := '';
LastCh := StrToInt(IntToStr(AValue)[Length(IntToStr(AValue))]);
if LastCh in [2, 3, 4] then
StrDesc := ' вложения'
else if LastCh in [1] then
StrDesc := ' вложение'
else
StrDesc := ' вложений';
fAttachCount.Caption := UTF8ToSys(' ') + IntToStr(AValue) + StrDesc;
end;
procedure TDialogItem.SetNameCollocutor(AValue: string);
// Устанавливает имя собеседнику
begin
fNameCollocutor := AValue;
end;
procedure TDialogItem.SetPicture(AValue: TPicture);
// Установить аватарку
begin
// fImage.Picture.Assign(AValue);
fPicture.Assign(AValue);
end;
procedure TDialogItem.SetText(AValue: string);
// Текст сообщения
begin
fText := AValue;
end;
procedure TDialogItem.SetTime(AValue: TDateTime);
// Время сообщения
var
TimeStr: string;
begin
DateTimeToString(TimeStr, 'DD.MM.YYYY hh:mm:ss', Avalue);
fTime := TimeStr;
end;
procedure TDialogItem.FormatTextWithMaxWidth(const TextIn: string; StringList: TStringList; MaxWidthPixels: integer);
// Разбить текст на строки, что бы он влазил в определенную ширину
var
WordList: TStringList;
WordBuf, CharBuf: string;
i: integer;
begin
WordList := TStringList.Create;
// Создаём список слов
WordBuf := '';
for i := 1 to LazUTF8.UTF8Length(TextIn) do
begin
CharBuf := LazUTF8.UTF8Copy(TextIn, i, 1);
if CharBuf = ' ' then
begin
WordList.Add(WordBuf);
WordBuf := '';
end
else
WordBuf := WordBuf + CharBuf;
end;
WordList.Add(WordBuf);
WordBuf := WordBuf + #0 + #0;
// Подбираем наиболее близкий к максимальной длине текст
for i := 0 to WordList.Count - 1 do
begin
if Canvas.TextWidth(WordList[i]) < MaxWidthPixels then
;
end;
ShowMessage(WordList.Text);
WordList.Free;
end;
procedure TDialogItem.Paint;
var
LeftVal: integer;
Rect: TRect;
StringList: TStringList;
begin
// Для более быстрого рисования имеет смысл отключать OnPaint когда компонент не видим
inherited Paint;
// Имя
Canvas.Font.Color := TColor($8a5f3e);
Canvas.Font.Style := [fsBold];
Canvas.TextOut(74, 4, fNameCollocutor);
// Время сообщения
Canvas.Font.Color := clGray;
Canvas.Font.Style := [];
LeftVal := (self as TDialogItem).Width - Canvas.GetTextWidth(fTime) - 8;
Canvas.TextOut(LeftVal, 4, fTime);
// Текст сообщения
Canvas.Font.Color := clBlack;
Canvas.Font.Style := [];
Rect.Left := 74;
Rect.Top := 24;
Rect.Right := LeftVal - 8;
Rect.Bottom := Height;
Canvas.TextRect(Rect, 74, 24, fText);
StringList := TStringList.Create;
StringList.Free;
// Изображение аватарки
Rect.Top := 4;
Rect.Left := 8;
Rect.Right := 64;
Rect.Bottom := 64;
Canvas.StretchDraw(Rect, fPicture.Graphic);
// Выводим инфу
Canvas.TextOut(LeftVal, 40, 'Позиция: ' + IntToStr(BoundsRect.Top));
end;
constructor TDialogItem.Create(AOwner: TComponent);
// Создание компонентов
begin
inherited Create(AOwner);
DoubleBuffered := True;
// Panel
Caption := '';
Color := clWhite;
(self as TDialogItem).Left := 4;
(self as TDialogItem).Top := 10;
(self as TDialogItem).Height := 100;
(self as TDialogItem).BorderStyle := bsNone;
(self as TDialogItem).DoubleBuffered := True;
// Avatar
fPicture := TPicture.Create;
// Attach count
fAttachCount := TLabel.Create(self as TDialogItem);
fAttachCount.Parent := self as TDialogItem;
fAttachCount.Font.Color := clBlack;
fAttachCount.Left := (self as TDialogItem).Width - fAttachCount.Width - 8;
fAttachCount.Top := (self as TDialogItem).Height - (Height - 64 {fImage.Height} - 4{fImage.Top}) - fAttachCount.Height;
fAttachCount.WordWrap := True;
fAttachCount.AutoSize := True;
fAttachCount.Anchors := [akRight, akTop];
fAttachCount.Font.Color := TColor($8a5f3e);
AttachCount := 2;
// Popup menu
fAttachPopup := TPopupMenu.Create(self as TDialogItem);
ClearAttachInfo;
// Mouse events
(self as TDialogItem).OnMouseEnter := @EnterMouse;
(self as TDialogItem).OnMouseLeave := @LeaveMouse;
fAttachCount.OnMouseEnter := @EnterMouseForAttachPopup;
fAttachCount.OnMouseLeave := @LeaveMouseForAttachPopup;
fAttachCount.OnClick := @OnClickAttach;
FormatTextWithMaxWidth('Привет как дела? Чем занимаешься? Давно не видились, хотелось бы пообщаться, если ты не против...', nil, 120);
end;
destructor TDialogItem.Destroy;
// Уничтожение компонента
begin
try
if Assigned(fAttachCount) then
fAttachCount.Free;
if Assigned(fAttachPopup) then
fAttachPopup.Free;
if Assigned(fPicture) then
fPicture.Free;
except
// Пропускаем ошибки если есть ибо не критично
Nop;
end;
inherited Destroy;
end;
procedure TDialogItem.ReAlign;
// Изменение размера
begin
inherited ReAlign;
// Нужна фича (WordWrap) которая разобьёт строку на строки что бы поместиться в RECT по ширине
(self as TDialogItem).Height := 74 + GetTextHeigh(string(fText));
end;
procedure TDialogItem.Establish(AName, AText: string; ATime: TDateTime);
// Заполнение данных
begin
NameCollocutor := AName;
Text := AText;
Time := ATime;
end;
procedure TDialogItem.ClearAttachInfo;
// Чистим список вложений
begin
fAttachPopup.Items.Clear;
fAttachCount.Visible := False;
end;
procedure TDialogItem.AddAttachInfo(AFileName: string; AOnClick: TNotifyEvent);
// Добавления пункта в меню о вложении
begin
fAttachPopup.Items.Add(TMenuItem.Create(nil));
fAttachPopup.Items[fAttachPopup.Items.Count - 1].Caption := AFileName;
fAttachPopup.Items[fAttachPopup.Items.Count - 1].OnClick := AOnClick;
AttachCount := fAttachPopup.Items.Count;
fAttachCount.Visible := True;
end;
end.
|
{
Multiplatform experience with dynamic library.
Reference: https://wiki.freepascal.org/Lazarus/FPC_Libraries
}
unit uCalc;
interface
uses
Classes, SysUtils, Dynlibs;
const
ERROR='Error';
{$IFDEF WINDOWS}
DLLPATH ='.\C_lib\calc.dll';
{$ENDIF}
{$IFDEF LINUX}
DLLPATH = './C_lib/libcalc.so';
{$ENDIF}
function Add(number1, number2: Single): String;
function Subtract(number1, number2: Single): String;
function Multiply(number1, number2: Single): String;
function Divide(number1, number2: Single): String;
implementation
function Calc(funcName: String; number1, number2: Single): String;
type
TDllCalc=function (n1, n2: Single): Single; Cdecl;
var
LibHandle: TLibHandle = NilHandle;
DllCalc: TDllCalc;
DllCalcResult: Single;
begin
Result:= ERROR;
LibHandle := LoadLibrary(DLLPATH);
if LibHandle <> NilHandle Then
begin
DllCalc:= TDllCalc(GetProcedureAddress(LibHandle, funcName));
if DllCalc <> Nil Then
begin
DllCalcResult:= DllCalc (number1, number2);
Result:= FloatToStr(DllCalcResult);
if LibHandle <> NilHandle Then
if FreeLibrary(LibHandle) Then
LibHandle:= NilHandle;
end;
end;
end;
function Add(number1, number2: Single): String;
begin
Result:= Calc('add', number1, number2);
end;
function Subtract(number1, number2: Single): String;
begin
Result:= Calc('subtract', number1, number2);
end;
function Multiply(number1, number2: Single): String;
begin
Result:= Calc('multiply', number1, number2);
end;
function Divide(number1, number2: Single): String;
begin
Result:= Calc('divide', number1, number2);
end;
end.
|
{
CTU Open Contest 2002
=====================
Sample solution for the problem: format
Martin Kacer, Oct 2002
}
Program Formatting;
Const MAXWORDS = 10200;
PENALTY = 500;
MAXLINE = 128;
Var Len: Array [1..MAXWORDS] of Integer;
Best: Array [0..MAXWORDS] of Integer;
WordCount: Integer;
{compute the lowest badness for the 'Row' characters long row
with 'Num' words (Num>2) with a total length of 'Len' (Len<=Row-Num+1)}
Function CountBadness (Row, Len, Num: Integer) : Integer;
Var SpLen, SpBig: Integer;
Begin
Dec (Num); {number of spaces between words}
SpLen := (Row - Len) div Num;
SpBig := (Row - Len) - (SpLen * Num);
{now we have Num spaces;
'SpBig' of them are 'SpLen+1' character long;
the other are 'SpLen' characters long}
CountBadness := (SpLen-1) * (SpLen-1) * (Num - SpBig)
+ SpLen * SpLen * SpBig;
End; { CountBadness }
{remember a solution for the first 'Cnt' words (badness given),
if no better has been found before}
Procedure Possible (Cnt: Integer; Badness: Integer);
Begin
If (Best[Cnt] < 0) or (Badness < Best[Cnt]) then
Best[Cnt] := Badness;
End; { Possible }
{solve one problem, iterate word by word}
Function FindBest (Row: Integer) : Integer;
Var I, J, Sum: Integer;
Begin
For I := 0 to WordCount do Best[I] := -1;
Best[0] := 0;
For I := 0 to WordCount-1 do
If Len[I+1] = Row then
Possible (I+1, Best[I])
else Begin
Possible (I+1, Best[I] + PENALTY);
Sum := Len[I+1];
J := I+1;
Repeat
Inc (J);
Sum := Sum + Len[J];
If (Sum + (J-I-1) <= Row) and (J <= WordCount) then
Possible (J, Best[I] + CountBadness (Row, Sum, J-I));
until (Sum + (J-I-1) >= Row) or (J >= WordCount);
End;
FindBest := Best [WordCount];
End; { FindBest }
{read the text and remember word lengths}
Procedure ReadText;
Var S: String[MAXLINE];
I, J: Integer;
Begin
WordCount := 0;
Repeat
ReadLn (S);
I := 1;
While (I <= Length(S)) do
Begin
While (I <= Length(S)) and (S[I] = ' ') do Inc (I);
J := I;
While (I <= Length(S)) and (S[I] <> ' ') do Inc (I);
If (J < I) then
Begin
Inc (WordCount);
Len [WordCount] := I - J;
End;
End;
until Length(S) = 0;
End; { ReadText }
Var Row : Integer;
Begin
Repeat
ReadLn (Row);
If (Row > 0) then
Begin
ReadText;
WriteLn ('Minimal badness is ',FindBest (Row),'.');
End;
until (Row = 0);
End.
|
{Imlementation of Source1}
Unit Source1;
Interface
type
p_Source1 = ^Source1Obj;
Source1Obj = object
private
{data for 1 source}
lambda : real;
deltaLambda : real;
finallyLambda : real;
public
{initialization the field}
constructor Init;
{random value of tay}
function tay(tpost : real) : real;
{getter for lambda}
function getLambda : real;
{getter for delta lambda}
function getDeltaLambda : real;
{getter for finally Lambda}
function getFinallyLambda : real;
{change lambda}
procedure updateLambda;
{setters for field}
procedure setLambda(lambda_ : real);
procedure setDeltaLambda(deltaLambda_ : real);
procedure setFinallyLambda(finallyLambda_ : real);
end;
Implementation
constructor Source1Obj.Init;
begin
lambda := 0.5;
deltaLambda := 0.1;
finallyLambda := 1.5;
end;
function Source1Obj.tay;
begin
tay := tpost - (ln(random) / lambda );
end;
function Source1Obj.getLambda;
begin
getLambda := lambda;
end;
function Source1Obj.getDeltaLambda;
begin
getDeltaLambda := deltaLambda;
end;
function Source1Obj.getFinallyLambda;
begin
getFinallyLambda := finallyLambda;
end;
procedure Source1Obj.updateLambda;
begin
lambda := lambda + deltaLambda;
end;
procedure Source1Obj.setLambda;
begin
lambda := lambda_;
end;
procedure Source1Obj.setDeltaLambda;
begin
deltaLambda := deltaLambda_;
end;
procedure Source1Obj.setFinallyLambda;
begin
finallyLambda := finallyLambda_;
end;
BEGIN
END. |
unit uBindingNavigator;
// This form demonstrates using a BindingNavigator to display
// rows from a database query sequentially.
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, CNClrLib.Control.EnumTypes,
CNClrLib.Control.EventArgs, CNClrLib.Control.Base,
CNClrLib.Control.ScrollableControl, CNClrLib.Control.ToolStrip,
CNClrLib.Control.BindingNavigator, CNClrLib.Component.BindingSource,
CNClrLib.Control.TextBoxBase, CNClrLib.Control.TextBox;
type
TfrmBindingNav = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
private
customersBindingNavigator : TCnBindingNavigator;
customersBindingSource: TCnBindingSource;
companyNameTextBox: TCnTextBox;
public
{ Public declarations }
end;
var
frmBindingNav: TfrmBindingNav;
implementation
{$R *.dfm}
uses CNClrLib.Data, CNClrLib.Windows;
procedure TfrmBindingNav.FormCreate(Sender: TObject);
begin
// This is the BindingNavigator that allows the user
// to navigate through the rows in a DataSet.
customersBindingNavigator := TCnBindingNavigator.Create(Self);
// This is the BindingSource that provides data for
// the Textbox control.
customersBindingSource := TCnBindingSource.Create(Self);
// This is the TextBox control that displays the CompanyName
// field from the DataSet.
companyNameTextBox := TCnTextBox.Create(Self);
// Set up the BindingSource component.
customersBindingNavigator.BindingSource := customersBindingSource;
customersBindingNavigator.Align := alTop;
customersBindingNavigator.Parent := Self;
// Set up the TextBox control for displaying company names.
companyNameTextBox.Align := alBottom;
companyNameTextBox.Parent := Self;
end;
procedure TfrmBindingNav.FormShow(Sender: TObject);
var
connectString: String;
connection: _SqlConnection;
dataAdapter1: _SqlDataAdapter;
ds: _DataSet;
begin
// Open a connection to the database.
// Replace the value of connectString with a valid
// connection string to a Northwind database accessible
// to your system.
connectString := 'Integrated Security=SSPI;Persist Security Info=False;' +
'Initial Catalog=Northwind;Data Source=localhost';
connection := CoSqlConnection.CreateInstance(connectString);
try
dataAdapter1 := CoSqlDataAdapter.CreateInstance(CoSqlCommand.CreateInstance('Select * From Customers', connection));
ds := CoDataSet.CreateInstance('Northwind Customers');
ds.Tables.Add_1('Customers');
dataAdapter1.Fill_3(ds.Tables.Item_1['Customers']);
// Assign the DataSet as the DataSource for the BindingSource.
customersBindingSource.DataSource := ds.Tables.Item_1['Customers'];
// Bind the CompanyName field to the TextBox control.
companyNameTextBox.DataBindings.Add(
CoBinding.CreateInstance('Text',
customersBindingSource.BindingSource,//.Unwrap,
'CompanyName',
True));
finally
connection.Dispose;
end;
end;
end.
|
{
***************************************************************************
* *
* This source is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This code is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License for more details. *
* *
* A copy of the GNU General Public License is available on the World *
* Wide Web at <http://www.gnu.org/copyleft/gpl.html>. You can also *
* obtain it by writing to the Free Software Foundation, *
* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
***************************************************************************
Author: Kudriavtsev Pavel
This unit registers the TPdx component of the FCL.
}
unit RegisterPDX;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LResources, LazarusPackageIntf, PropEdits, pdx;
resourcestring
pdxAllDbasefiles = 'Paradox Files';
procedure Register;
implementation
type
{ TPdxFileNamePropertyEditor }
TPdxFileNamePropertyEditor=class(TFileNamePropertyEditor)
protected
function GetFilter: String; override;
end;
{ TPdxLangEditor }
TPdxLangPropertyEditor = class(TStringProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure GetValues(Proc: TGetStrProc); override;
function GetValue: string; override;
procedure SetValue(const Value: string); override;
end;
{ TPdxLangEditor }
function TPdxLangPropertyEditor.GetAttributes: TPropertyAttributes;
begin
Result := [paValueList, paSortList];
end;
procedure TPdxLangPropertyEditor.GetValues(Proc: TGetStrProc);
var
i: integer;
begin
for i := 1 to 118 do
Proc(PdxLangTable[i].Name);
end;
function TPdxLangPropertyEditor.GetValue: string;
begin
Result := GetStrValue;
end;
procedure TPdxLangPropertyEditor.SetValue(const Value: string);
begin
SetStrValue(Value);
end;
{ TPdxFileNamePropertyEditor }
function TPdxFileNamePropertyEditor.GetFilter: String;
begin
Result := pdxAllDbaseFiles+' (*.db)|*.db;*.DB';
Result:= Result+ '|'+ inherited GetFilter;
end;
procedure RegisterUnitPdx;
begin
RegisterComponents('Data Access',[TPdx]);
RegisterPropertyEditor(TypeInfo(string),
TPdx, 'TableName', TPdxFileNamePropertyEditor);
RegisterPropertyEditor(TypeInfo(string),
TPdx, 'Language', TPdxLangPropertyEditor);
end;
procedure Register;
begin
RegisterUnit('pdx', @RegisterUnitPdx);
end;
initialization
{$i registerpdx.lrs}
end.
|
unit ProgressInfo;
interface
uses
NotifyEvents;
type
TProgressInfo = class(TObject)
private
FOnAssign: TNotifyEventsEx;
FProcessRecords: Cardinal;
FTotalRecords: Cardinal;
function GetPosition: Double;
public
constructor Create;
destructor Destroy; override;
procedure Assign(AProgressInfo: TProgressInfo);
procedure Clear;
property OnAssign: TNotifyEventsEx read FOnAssign;
property Position: Double read GetPosition;
property ProcessRecords: Cardinal read FProcessRecords
write FProcessRecords;
property TotalRecords: Cardinal read FTotalRecords write FTotalRecords;
end;
implementation
uses System.Math, System.SysUtils;
constructor TProgressInfo.Create;
begin
Clear;
FOnAssign := TNotifyEventsEx.Create(Self);
end;
destructor TProgressInfo.Destroy;
begin
FreeAndNil(FOnAssign);
inherited;
end;
procedure TProgressInfo.Assign(AProgressInfo: TProgressInfo);
begin
Assert(AProgressInfo <> nil);
TotalRecords := AProgressInfo.TotalRecords;
ProcessRecords := AProgressInfo.ProcessRecords;
FOnAssign.CallEventHandlers(Self);
end;
procedure TProgressInfo.Clear;
begin
ProcessRecords := 0;
TotalRecords := 0;
end;
function TProgressInfo.GetPosition: Double;
begin
if TotalRecords > 0 then
Result := ProcessRecords * 100 / TotalRecords
else
Result := 0;
end;
end.
|
unit Teste.ValueObject.URL;
interface
uses
DUnitX.TestFramework;
type
[TestFixture]
TURLTest = class
public
[Test]
procedure TestarURLRetiraCaracteresEspeciais;
end;
implementation
{ TURLTest }
uses
Module.ValueObject.URL.Impl, Module.ValueObject.URL;
procedure TURLTest.TestarURLRetiraCaracteresEspeciais;
var
_url: IURL;
begin
_url := TURL.Create('http:/%20teste');
Assert.AreEqual('http:/ teste', _url.AsString);
end;
initialization
TDUnitX.RegisterTestFixture(TURLTest);
end.
|
unit IdMultipartFormData;
{
Implementation of the Multipart From data
Author: Shiv Kumar
Copyright: (c) Chad Z. Hower and The Winshoes Working Group.
Details of implementation
-------------------------
2001-Nov Doychin Bondzhev
- Now it descends from TStream and does not do buffering.
- Changes in the way the form parts are added to the stream.
2001-Nov-23
- changed spelling error from XxxDataFiled to XxxDataField
}
interface
uses
SysUtils, Classes, IdGlobal, IdException, IdResourceStrings;
const
sContentType = 'multipart/form-data; boundary=';
crlf = #13#10;
sContentDisposition = 'Content-Disposition: form-data; name="%s"';
sFileNamePlaceHolder = '; filename="%s"';
sContentTypePlaceHolder = 'Content-Type: %s' + crlf + crlf;
type
TIdMultiPartFormDataStream = class;
TIdFormDataField = class(TCollectionItem)
protected
FFieldSize: LongInt;
FFieldValue: string;
FFileName: string;
FContentType: string;
FFieldName: string;
FFieldObject: TObject;
FInternallyAssigned: Boolean;
procedure SetFieldStream(const Value: TStream);
function GetFieldSize: LongInt;
procedure SetContentType(const Value: string);
procedure SetFieldName(const Value: string);
procedure SetFieldValue(const Value: string);
function GetFieldStream: TStream;
procedure SetFieldObject(const Value: TObject);
procedure SetFileName(const Value: string);
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
// procedure Assign(Source: TPersistent); override;
property ContentType: string read FContentType write SetContentType;
property FieldName: string read FFieldName write SetFieldName;
property FieldStream: TStream read GetFieldStream write SetFieldStream;
property FieldObject: TObject read FFieldObject write SetFieldObject;
property FileName: string read FFileName write SetFileName;
property FieldValue: string read FFieldValue write SetFieldValue;
property FieldSize: LongInt read GetFieldSize write FFieldSize;
end;
TIdFormDataFields = class(TCollection)
protected
FParentStream: TIdMultiPartFormDataStream;
function GetFormDataField(AIndex: Integer): TIdFormDataField;
{procedure SetFormDataField(AIndex: Integer;
const Value: TIdFormDataField);}
public
constructor Create(AMPStream: TIdMultiPartFormDataStream);
function Add: TIdFormDataField;
property MultipartFormDataStream: TIdMultiPartFormDataStream read FParentStream;
property Items[AIndex: Integer]: TIdFormDataField read GetFormDataField { write SetFormDataField};
end;
TIdMultiPartFormDataStream = class(TStream)
protected
FInputStream: TStream;
FBoundary: string;
FRequestContentType: string;
FItem: integer;
FInitialized: Boolean;
FInternalBuffer: string;
FPosition: Int64;
FSize: Int64;
FFields: TIdFormDataFields;
function GenerateUniqueBoundary: string;
function FormatField(AIndex: Integer): string;
function PrepareStreamForDispatch: string;
public
constructor Create;
destructor Destroy; override;
function Read(var Buffer; Count: Longint): Longint; override;
function Write(const Buffer; Count: Longint): Longint; override;
function Seek(Offset: Longint; Origin: Word): Longint; overload; override;
procedure AddFormField(const AFieldName, AFieldValue: string);
procedure AddObject(const AFieldName, AContentType: string; AFileData: TObject; const AFileName: string = '');
procedure AddFile(const AFieldName, AFileName, AContentType: string);
property Boundary: string read FBoundary;
property RequestContentType: string read FRequestContentType;
end;
EIdInvalidObjectType = class(EIdException);
implementation
{ TIdMultiPartFormDataStream }
constructor TIdMultiPartFormDataStream.Create;
begin
inherited Create;
FSize := 0;
FInitialized := false;
FBoundary := GenerateUniqueBoundary;
FRequestContentType := sContentType + FBoundary;
FFields := TIdFormDataFields.Create(Self);
end;
procedure TIdMultiPartFormDataStream.AddObject(const AFieldName,
AContentType: string; AFileData: TObject; const AFileName: string = '');
var
FItem: TIdFormDataField;
begin
FItem := FFields.Add;
with FItem do begin
FieldName := AFieldName;
FileName := AFileName;
FFieldObject := AFileData;
ContentType := AContentType;
end;
FSize := FSize + FItem.FieldSize;
end;
procedure TIdMultiPartFormDataStream.AddFile(const AFieldName, AFileName,
AContentType: string);
var
FileStream: TFileStream;
FItem: TIdFormDataField;
begin
FItem := FFields.Add;
FileStream := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite);
with FItem do begin
FieldName := AFieldName;
FileName := AFileName;
FFieldObject := FileStream;
ContentType := AContentType;
FInternallyAssigned := true;
end;
FSize := FSize + FItem.FieldSize;
end;
procedure TIdMultiPartFormDataStream.AddFormField(const AFieldName,
AFieldValue: string);
var
FItem: TIdFormDataField;
begin
FItem := FFields.Add;
with FItem do begin
FieldName := AFieldName;
FieldValue := AFieldValue;
end;
FSize := FSize + FItem.FieldSize;
end;
function TIdMultiPartFormDataStream.FormatField(AIndex: Integer): string;
function FileField(AItem: TIdFormDataField): string;
begin
with AItem do begin
result := Format('--' + Boundary + crlf + sContentDisposition +
sFileNamePlaceHolder + crlf +
sContentTypePlaceHolder, [FieldName, FileName, ContentType]);
end;
end;
function NormalField(AItem: TIdFormDataField): string;
begin
with AItem do begin
result := Format('--' + Boundary + crlf + sContentDisposition + crlf + crlf +
FieldValue + crlf, [FieldName]);
end;
end;
begin
with FFields.Items[AIndex] do begin
if Assigned(FieldObject) then begin
if Length(FileName) > 0 then begin
result := FileField(FFields.Items[AIndex]);
end
else begin
result := NormalField(FFields.Items[AIndex]);
end;
end
else begin
result := NormalField(FFields.Items[AIndex]);
end;
end;
end;
function TIdMultiPartFormDataStream.GenerateUniqueBoundary: string;
begin
Result := '--------' + FormatDateTime('mmddyyhhnnsszzz', Now);
end;
function TIdMultiPartFormDataStream.PrepareStreamForDispatch: string;
begin
result := crlf + '--' + Boundary + '--' + crlf;
end;
function TIdMultiPartFormDataStream.Read(var Buffer;
Count: Integer): Longint;
type
PByteArray = ^TByteArray;
TByteArray = array[0..High(Integer) - 1] of Byte; // 2GB size
var
LTotalRead: Integer;
LCount: Integer;
LBufferCount: Integer;
begin
if not FInitialized then begin
FInitialized := true;
FItem := 0;
SetLength(FInternalBuffer, 0);
end;
LTotalRead := 0;
LBufferCount := 0;
while (LTotalRead < Count) and ((FItem < FFields.Count) or (Length(FInternalBuffer) > 0)) do begin
if (Length(FInternalBuffer) = 0) and not Assigned(FInputStream) then begin
FInternalBuffer := FormatField(FItem);
if Assigned(FFields.Items[FItem].FieldObject) then begin
if (FFields.Items[FItem].FieldObject is TStream) then begin
FInputStream := FFields.Items[FItem].FieldObject as TStream;
FInputStream.Seek(0, soFromBeginning);
end
else
FInputStream := nil;
if (FFields.Items[FItem].FieldObject is TStrings) then begin
FInternalBuffer := FInternalBuffer + (FFields.Items[FItem].FieldObject as TStrings).Text;
Inc(FItem);
end;
end
else begin
Inc(FItem);
end;
end;
if Length(FInternalBuffer) > 0 then begin
if Length(FInternalBuffer) > Count - LBufferCount then begin
LCount := Count - LBufferCount;
end
else begin
LCount := Length(FInternalBuffer);
end;
Move(FInternalBuffer[1], TByteArray(Buffer)[LBufferCount], LCount);
Delete(FInternalBuffer, 1, LCount);
LBufferCount := LBufferCount + LCount;
FPosition := FPosition + LCount;
LTotalRead := LTotalRead + LCount;
end;
if Assigned(FInputStream) and (LTotalRead < Count) then begin
LCount := FInputStream.Read(TByteArray(Buffer)[LBufferCount], Count - LTotalRead);
if LCount < Count - LTotalRead then begin
FInputStream.Seek(0, soFromBeginning);
FInputStream := nil;
Inc(FItem);
FInternalBuffer := #13#10;
end;
LBufferCount := LBufferCount + LCount;
LTotalRead := LTotalRead + LCount;
FPosition := FPosition + LCount;
end;
if FItem = FFields.Count then begin
FInternalBuffer := FInternalBuffer + PrepareStreamForDispatch;
Inc(FItem);
end;
end;
result := LTotalRead;
end;
destructor TIdMultiPartFormDataStream.Destroy;
begin
FreeAndNil(FFields);
inherited Destroy;
end;
function TIdMultiPartFormDataStream.Seek(Offset: Integer;
Origin: Word): Longint;
begin
result := 0;
case Origin of
soFromBeginning: begin
if (Offset = 0) then begin
FInitialized := false;
FPosition := 0;
result := 0;
end
else
result := FPosition;
end;
soFromCurrent: begin
result := FPosition;
end;
soFromEnd: begin
result := FSize + Length(PrepareStreamForDispatch);
end;
end;
end;
function TIdMultiPartFormDataStream.Write(const Buffer;
Count: Integer): Longint;
begin
raise Exception.Create('Unsupported operation.');
end;
{ TIdFormDataFields }
function TIdFormDataFields.Add: TIdFormDataField;
begin
result := TIdFormDataField(inherited Add);
end;
constructor TIdFormDataFields.Create(AMPStream: TIdMultiPartFormDataStream);
begin
inherited Create(TIdFormDataField);
FParentStream := AMPStream;
end;
function TIdFormDataFields.GetFormDataField(
AIndex: Integer): TIdFormDataField;
begin
result := TIdFormDataField(inherited Items[AIndex]);
end;
{procedure TIdFormDataFields.SetFormDataField(AIndex: Integer;
const Value: TIdFormDataField);
begin
Items[AIndex].Assign(Value);
end;}
{ TIdFormDataField }
{procedure TIdFormDataField.Assign(Source: TPersistent);
begin
if Source is TIdFormDataField then begin
(Source as TIdFormDataField).FFileName := FFileName;
(Source as TIdFormDataField).FContentType := FContentType;
(Source as TIdFormDataField).FFieldObject := FFieldObject;
(Source as TIdFormDataField).FieldName := FieldName;
end
else begin
inherited Assign(Source);
end;
end;}
constructor TIdFormDataField.Create(Collection: TCollection);
begin
inherited Create(Collection);
FFieldObject := nil;
FFileName := '';
FFieldName := '';
FContentType := '';
FInternallyAssigned := false;
end;
destructor TIdFormDataField.Destroy;
begin
if Assigned(FFieldObject) and FInternallyAssigned then
FFieldObject.Free;
inherited Destroy;
end;
function TIdFormDataField.GetFieldSize: LongInt;
begin
if Length(FFileName) > 0 then begin
FFieldSize := Length(Format('--' + (Collection as TIdFormDataFields).FParentStream.Boundary
+ crlf + sContentDisposition + sFileNamePlaceHolder + crlf + sContentTypePlaceHolder,
[FieldName, FileName, ContentType]));
end
else begin
FFieldSize := Length(Format('--' + (Collection as TIdFormDataFields).FParentStream.Boundary +
crlf + sContentDisposition + crlf + crlf + FFieldValue + crlf, [FieldName]));
end;
if Assigned(FFieldObject) then begin
if FieldObject is TStrings then
FFieldSize := FFieldSize + Length((FieldObject as TStrings).Text) + 2;
if FieldObject is TStream then
FFieldSize := FFieldSize + FieldStream.Size + 2;
end;
Result := FFieldSize;
end;
function TIdFormDataField.GetFieldStream: TStream;
begin
result := nil;
if Assigned(FFieldObject) then begin
if (FFieldObject is TStream) then begin
result := TStream(FFieldObject);
end
else begin
raise EIdInvalidObjectType.Create(RSMFDIvalidObjectType);
end;
end;
end;
procedure TIdFormDataField.SetContentType(const Value: string);
begin
FContentType := Value;
GetFieldSize;
end;
procedure TIdFormDataField.SetFieldName(const Value: string);
begin
FFieldName := Value;
GetFieldSize;
end;
procedure TIdFormDataField.SetFieldObject(const Value: TObject);
begin
if Assigned(Value) then begin
if (Value is TStream) or (Value is TStrings) then begin
FFieldObject := Value;
GetFieldSize;
end
else begin
raise EIdInvalidObjectType.Create(RSMFDIvalidObjectType);
end;
end
else
FFieldObject := Value;
end;
procedure TIdFormDataField.SetFieldStream(const Value: TStream);
begin
FieldObject := Value;
end;
procedure TIdFormDataField.SetFieldValue(const Value: string);
begin
FFieldValue := Value;
GetFieldSize;
end;
procedure TIdFormDataField.SetFileName(const Value: string);
begin
FFileName := Value;
GetFieldSize;
end;
end.
|
unit NtUtils.Threads;
interface
uses
Winapi.WinNt, Ntapi.ntdef, Ntapi.ntpsapi, Ntapi.ntrtl, NtUtils.Exceptions,
NtUtils.Objects;
const
// Ntapi.ntpsapi
NtCurrentThread: THandle = THandle(-2);
// Open a thread (always succeeds for the current PID)
function NtxOpenThread(out hxThread: IHandle; TID: NativeUInt;
DesiredAccess: TAccessMask; HandleAttributes: Cardinal = 0): TNtxStatus;
// Reopen a handle to the current thread with the specific access
function NtxOpenCurrentThread(out hxThread: IHandle;
DesiredAccess: TAccessMask; HandleAttributes: Cardinal = 0): TNtxStatus;
// Query variable-size information
function NtxQueryThread(hThread: THandle; InfoClass: TThreadInfoClass;
out xMemory: IMemory): TNtxStatus;
// Set variable-size information
function NtxSetThread(hThread: THandle; InfoClass: TThreadInfoClass;
Data: Pointer; DataSize: Cardinal): TNtxStatus;
type
NtxThread = class
// Query fixed-size information
class function Query<T>(hThread: THandle;
InfoClass: TThreadInfoClass; out Buffer: T): TNtxStatus; static;
// Set fixed-size information
class function SetInfo<T>(hThread: THandle;
InfoClass: TThreadInfoClass; const Buffer: T): TNtxStatus; static;
end;
// Query exit status of a thread
function NtxQueryExitStatusThread(hThread: THandle; out ExitStatus: NTSTATUS)
: TNtxStatus;
// Get thread context
// NOTE: On success free the memory with FreeMem
function NtxGetContextThread(hThread: THandle; FlagsToQuery: Cardinal;
out Context: PContext): TNtxStatus;
// Set thread context
function NtxSetContextThread(hThread: THandle; Context: PContext):
TNtxStatus;
// Suspend/resume a thread
function NtxSuspendThread(hThread: THandle): TNtxStatus;
function NtxResumeThread(hThread: THandle): TNtxStatus;
// Terminate a thread
function NtxTerminateThread(hThread: THandle; ExitStatus: NTSTATUS): TNtxStatus;
// Delay current thread's execution
function NtxSleep(Timeout: Int64; Alertable: Boolean = False): TNtxStatus;
// Create a thread in a process
function NtxCreateThread(out hxThread: IHandle; hProcess: THandle; StartRoutine:
TUserThreadStartRoutine; Argument: Pointer; CreateFlags: Cardinal = 0;
ZeroBits: NativeUInt = 0; StackSize: NativeUInt = 0; MaxStackSize:
NativeUInt = 0; HandleAttributes: Cardinal = 0): TNtxStatus;
// Create a thread in a process
function RtlxCreateThread(out hxThread: IHandle; hProcess: THandle;
StartRoutine: TUserThreadStartRoutine; Parameter: Pointer;
CreateSuspended: Boolean = False): TNtxStatus;
implementation
uses
Ntapi.ntstatus, Ntapi.ntobapi, Ntapi.ntseapi, Ntapi.ntexapi,
NtUtils.Access.Expected;
function NtxOpenThread(out hxThread: IHandle; TID: NativeUInt;
DesiredAccess: TAccessMask; HandleAttributes: Cardinal = 0): TNtxStatus;
var
hThread: THandle;
ClientId: TClientId;
ObjAttr: TObjectAttributes;
begin
if TID = NtCurrentThreadId then
begin
hxThread := TAutoHandle.Capture(NtCurrentThread);
Result.Status := STATUS_SUCCESS;
end
else
begin
InitializeObjectAttributes(ObjAttr, nil, HandleAttributes);
ClientId.Create(0, TID);
Result.Location := 'NtOpenThread';
Result.LastCall.CallType := lcOpenCall;
Result.LastCall.AccessMask := DesiredAccess;
Result.LastCall.AccessMaskType := @ThreadAccessType;
Result.Status := NtOpenThread(hThread, DesiredAccess, ObjAttr, ClientId);
if Result.IsSuccess then
hxThread := TAutoHandle.Capture(hThread);
end;
end;
function NtxOpenCurrentThread(out hxThread: IHandle;
DesiredAccess: TAccessMask; HandleAttributes: Cardinal): TNtxStatus;
var
hThread: THandle;
Flags: Cardinal;
begin
// Duplicating the pseudo-handle is more reliable then opening thread by TID
if DesiredAccess and MAXIMUM_ALLOWED <> 0 then
begin
Flags := DUPLICATE_SAME_ACCESS;
DesiredAccess := 0;
end
else
Flags := 0;
Result.Location := 'NtDuplicateObject';
Result.Status := NtDuplicateObject(NtCurrentProcess, NtCurrentThread,
NtCurrentProcess, hThread, DesiredAccess, HandleAttributes, Flags);
if Result.IsSuccess then
hxThread := TAutoHandle.Capture(hThread);
end;
function NtxQueryThread(hThread: THandle; InfoClass: TThreadInfoClass;
out xMemory: IMemory): TNtxStatus;
var
Buffer: Pointer;
BufferSize, Required: Cardinal;
begin
Result.Location := 'NtQueryInformationThread';
Result.LastCall.CallType := lcQuerySetCall;
Result.LastCall.InfoClass := Cardinal(InfoClass);
Result.LastCall.InfoClassType := TypeInfo(TThreadInfoClass);
RtlxComputeThreadQueryAccess(Result.LastCall, InfoClass);
BufferSize := 0;
repeat
Buffer := AllocMem(BufferSize);
Required := 0;
Result.Status := NtQueryInformationThread(hThread, InfoClass, Buffer,
BufferSize, @Required);
if not Result.IsSuccess then
begin
FreeMem(Buffer);
Buffer := nil;
end;
until not NtxExpandBuffer(Result, BufferSize, Required);
if Result.IsSuccess then
xMemory := TAutoMemory.Capture(Buffer, BufferSize);
end;
function NtxSetThread(hThread: THandle; InfoClass: TThreadInfoClass;
Data: Pointer; DataSize: Cardinal): TNtxStatus;
begin
Result.Location := 'NtSetInformationThread';
Result.LastCall.CallType := lcQuerySetCall;
Result.LastCall.InfoClass := Cardinal(InfoClass);
Result.LastCall.InfoClassType := TypeInfo(TThreadInfoClass);
RtlxComputeThreadSetAccess(Result.LastCall, InfoClass);
Result.Status := NtSetInformationThread(hThread, InfoClass, Data, DataSize);
end;
class function NtxThread.Query<T>(hThread: THandle;
InfoClass: TThreadInfoClass; out Buffer: T): TNtxStatus;
begin
Result.Location := 'NtQueryInformationThread';
Result.LastCall.CallType := lcQuerySetCall;
Result.LastCall.InfoClass := Cardinal(InfoClass);
Result.LastCall.InfoClassType := TypeInfo(TThreadInfoClass);
RtlxComputeThreadQueryAccess(Result.LastCall, InfoClass);
Result.Status := NtQueryInformationThread(hThread, InfoClass, @Buffer,
SizeOf(Buffer), nil);
end;
class function NtxThread.SetInfo<T>(hThread: THandle;
InfoClass: TThreadInfoClass; const Buffer: T): TNtxStatus;
begin
Result := NtxSetThread(hThread, InfoClass, @Buffer, SizeOf(Buffer));
end;
function NtxQueryExitStatusThread(hThread: THandle; out ExitStatus: NTSTATUS)
: TNtxStatus;
var
Info: TThreadBasicInformation;
begin
Result := NtxThread.Query(hThread, ThreadBasicInformation, Info);
if Result.IsSuccess then
ExitStatus := Info.ExitStatus;
end;
function NtxGetContextThread(hThread: THandle; FlagsToQuery: Cardinal;
out Context: PContext): TNtxStatus;
begin
Context := AllocMem(SizeOf(TContext));
Context.ContextFlags := FlagsToQuery;
Result.Location := 'NtGetContextThread';
Result.LastCall.Expects(THREAD_GET_CONTEXT, @ThreadAccessType);
Result.Status := NtGetContextThread(hThread, Context);
if not Result.IsSuccess then
FreeMem(Context);
end;
function NtxSetContextThread(hThread: THandle; Context: PContext):
TNtxStatus;
begin
Result.Location := 'NtSetContextThread';
Result.LastCall.Expects(THREAD_SET_CONTEXT, @ThreadAccessType);
Result.Status := NtSetContextThread(hThread, Context);
end;
function NtxSuspendThread(hThread: THandle): TNtxStatus;
begin
Result.Location := 'NtSuspendThread';
Result.LastCall.Expects(THREAD_SUSPEND_RESUME, @ThreadAccessType);
Result.Status := NtSuspendThread(hThread);
end;
function NtxResumeThread(hThread: THandle): TNtxStatus;
begin
Result.Location := 'NtResumeThread';
Result.LastCall.Expects(THREAD_SUSPEND_RESUME, @ThreadAccessType);
Result.Status := NtResumeThread(hThread);
end;
function NtxTerminateThread(hThread: THandle; ExitStatus: NTSTATUS): TNtxStatus;
begin
Result.Location := 'NtTerminateThread';
Result.LastCall.Expects(THREAD_TERMINATE, @ThreadAccessType);
Result.Status := NtTerminateThread(hThread, ExitStatus);
end;
function NtxSleep(Timeout: Int64; Alertable: Boolean): TNtxStatus;
begin
Result.Location := 'NtDelayExecution';
Result.Status := NtDelayExecution(Alertable, Int64ToLargeInteger(Timeout));
end;
function NtxCreateThread(out hxThread: IHandle; hProcess: THandle; StartRoutine:
TUserThreadStartRoutine; Argument: Pointer; CreateFlags: Cardinal; ZeroBits:
NativeUInt; StackSize: NativeUInt; MaxStackSize: NativeUInt; HandleAttributes:
Cardinal): TNtxStatus;
var
hThread: THandle;
ObjAttr: TObjectAttributes;
begin
InitializeObjectAttributes(ObjAttr, nil, HandleAttributes);
Result.Location := 'NtCreateThreadEx';
Result.LastCall.Expects(PROCESS_CREATE_THREAD, @ProcessAccessType);
Result.Status := NtCreateThreadEx(hThread, THREAD_ALL_ACCESS, @ObjAttr,
hProcess, StartRoutine, Argument, CreateFlags, ZeroBits, StackSize,
MaxStackSize, nil);
if Result.IsSuccess then
hxThread := TAutoHandle.Capture(hThread);
end;
function RtlxCreateThread(out hxThread: IHandle; hProcess: THandle;
StartRoutine: TUserThreadStartRoutine; Parameter: Pointer;
CreateSuspended: Boolean): TNtxStatus;
var
hThread: THandle;
begin
Result.Location := 'RtlCreateUserThread';
Result.LastCall.Expects(PROCESS_CREATE_THREAD, @ProcessAccessType);
Result.Status := RtlCreateUserThread(hProcess, nil, CreateSuspended, 0, 0, 0,
StartRoutine, Parameter, hThread, nil);
if Result.IsSuccess then
hxThread := TAutoHandle.Capture(hThread);
end;
end.
|
unit employee_s;
{This file was generated on 11 Aug 2000 20:12:57 GMT by version 03.03.03.C1.06}
{of the Inprise VisiBroker idl2pas CORBA IDL compiler. }
{Please do not edit the contents of this file. You should instead edit and }
{recompile the original IDL which was located in the file employee.idl. }
{Delphi Pascal unit : employee_s }
{derived from IDL module : default }
interface
uses
CORBA,
employee_i,
employee_c;
type
TEmployeeSkeleton = class;
TEmployeeSkeleton = class(CORBA.TCorbaObject, employee_i.Employee)
private
FImplementation : Employee;
public
constructor Create(const InstanceName: string; const Impl: Employee);
destructor Destroy; override;
function GetImplementation : Employee;
function getEmployeesByName ( const name : AnsiString): ANY;
function getEmployeesByNameXML ( const name : AnsiString): AnsiString;
published
procedure _getEmployeesByName(const _Input: CORBA.InputStream; _Cookie: Pointer);
procedure _getEmployeesByNameXML(const _Input: CORBA.InputStream; _Cookie: Pointer);
end;
implementation
constructor TEmployeeSkeleton.Create(const InstanceName : string; const Impl : employee_i.Employee);
begin
inherited;
inherited CreateSkeleton(InstanceName, 'Employee', 'IDL:Employee:1.0');
FImplementation := Impl;
end;
destructor TEmployeeSkeleton.Destroy;
begin
FImplementation := nil;
inherited;
end;
function TEmployeeSkeleton.GetImplementation : employee_i.Employee;
begin
result := FImplementation as employee_i.Employee;
end;
function TEmployeeSkeleton.getEmployeesByName ( const name : AnsiString): ANY;
begin
Result := FImplementation.getEmployeesByName( name);
end;
function TEmployeeSkeleton.getEmployeesByNameXML ( const name : AnsiString): AnsiString;
begin
Result := FImplementation.getEmployeesByNameXML( name);
end;
procedure TEmployeeSkeleton._getEmployeesByName(const _Input: CORBA.InputStream; _Cookie: Pointer);
var
_Output : CORBA.OutputStream;
_name : AnsiString;
_Result : ANY;
begin
_Input.ReadString(_name);
_Result := getEmployeesByName( _name);
GetReplyBuffer(_Cookie, _Output);
_Output.WriteAny(_Result);
end;
procedure TEmployeeSkeleton._getEmployeesByNameXML(const _Input: CORBA.InputStream; _Cookie: Pointer);
var
_Output : CORBA.OutputStream;
_name : AnsiString;
_Result : AnsiString;
begin
_Input.ReadString(_name);
_Result := getEmployeesByNameXML( _name);
GetReplyBuffer(_Cookie, _Output);
_Output.WriteString(_Result);
end;
initialization
end. |
unit baseaction;
{$mode objfpc}{$H+}
interface
uses
BrookAction,
BrookHttpDefs,
BrookLogger,
HTTPDefs,
dmdatabase,
SysUtils,
session;
type
{ TBaseAction }
generic TBaseGAction<T> = class(specialize TBrookGAction<T>)
private
FPageSize: integer;
FSession: TSession;
FSorting: String;
FStartIndex: Integer;
FStartPage: integer;
procedure Request(ARequest: TBrookRequest; {%H-}AResponse: TBrookResponse); override;
procedure ActualizarCookie;
protected
procedure Post; override;
procedure ActualizarOffSet;
public
constructor Create; override;
destructor Destroy; override;
property Session: TSession read FSession;
property StartIndex :Integer read FStartIndex write FStartIndex;
property PageSize :Integer read FPageSize write FPageSize;
property Sorting :String read FSorting write FSorting;
end;
implementation
{ TBaseAction }
procedure TBaseGAction.Request(ARequest: TBrookRequest; AResponse: TBrookResponse
);
begin
if ARequest.PathInfo <> '/login' then
begin
FSession.Token := '';
// Primero se fija si el cliente envió una cookie
// llamada GTIRTOKEN con el token.
if ARequest.CookieFields.IndexOfName('GTIRTOKEN') > -1 then
begin
FSession.Token := ARequest.CookieFields.Values['GTIRTOKEN'];
end;
if FSession.Token <> '' then
begin
if not FSession.FindSessionRecord(FSession.Token) then
begin
AResponse.Code:=401;
AResponse.CodeText:= 'Session not found.';
end
else
begin
inherited Request(ARequest, AResponse);
ActualizarCookie;
end;
end
else
begin
// no mandó ni cookie ni token
AResponse.Code:=401;
AResponse.CodeText:= 'Session not found.';
end;
end
else
begin
inherited Request(ARequest, AResponse);
ActualizarCookie;
end;
end;
procedure TBaseGAction.ActualizarCookie;
begin
with HttpResponse.Cookies.Add do
begin
Name:= 'GTIRTOKEN';
Value:= FSession.Token;
FSession.UpdateExpiration;
Expires := FSession.Expire;
Path:= '/';
end;
end;
procedure TBaseGAction.ActualizarOffSet;
begin
try
StartIndex:= StrToInt(HttpRequest.QueryFields.Values['jtStartIndex']);
PageSize:= StrToInt(HttpRequest.QueryFields.Values['jtPageSize']);
Sorting:= HttpRequest.QueryFields.Values['jtSorting'];
if Sorting = 'undefined' then
Sorting := '';
except
StartIndex:= 0;
PageSize:= 0;
Sorting := '';
end;
end;
procedure TBaseGAction.Post;
begin
inherited Post;
try
StartIndex:= StrToInt(HttpRequest.QueryFields.Values['jtStartIndex']);
PageSize:= StrToInt(HttpRequest.QueryFields.Values['jtPageSize']);
Sorting:= HttpRequest.QueryFields.Values['jtSorting'];
except
StartIndex:= 0;
PageSize:= 0;
Sorting := '';
end;
end;
constructor TBaseGAction.Create;
begin
FSession := TSession.Create(datamodule1.PGConnection1);
inherited Create;
end;
destructor TBaseGAction.Destroy;
begin
FSession.Free;
inherited Destroy;
end;
end.
|
unit ExtraChargeQry;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseFDQuery, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt,
Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, DSWrap,
ExtraChargeExcelDataModule;
type
TExtraChargeW = class;
TQryExtraCharge = class(TQryBase)
private
FW: TExtraChargeW;
{ Private declarations }
public
constructor Create(AOwner: TComponent); override;
property W: TExtraChargeW read FW;
{ Public declarations }
end;
TExtraChargeW = class(TDSWrap)
private
FRange: TFieldWrap;
FWholeSale: TFieldWrap;
public
constructor Create(AOwner: TComponent); override;
procedure LoadDataFromExcelTable(AExcelTable: TExtraChargeExcelTable);
function LocateByRange(ARange: string): Boolean;
property Range: TFieldWrap read FRange;
property WholeSale: TFieldWrap read FWholeSale;
end;
implementation
constructor TExtraChargeW.Create(AOwner: TComponent);
begin
inherited;
FRange := TFieldWrap.Create(Self, 'Range');
FWholeSale := TFieldWrap.Create(Self, 'WholeSale');
end;
procedure TExtraChargeW.LoadDataFromExcelTable(AExcelTable:
TExtraChargeExcelTable);
begin
// FDQuery.DisableControls;
try
AExcelTable.First;
while not AExcelTable.Eof do
begin
// Если такой диапазон уже есть
if LocateByRange(AExcelTable.Range.Value) then
TryEdit
else
TryAppend;
Range.F.Value := AExcelTable.Range.Value;
WholeSale.F.Value := AExcelTable.WholeSale.Value;
TryPost;
AExcelTable.Next;
end;
finally
// FDQuery.EnableControls;
end;
end;
function TExtraChargeW.LocateByRange(ARange: string): Boolean;
begin
Result := FDDataSet.LocateEx(Range.FieldName, ARange, []);
end;
constructor TQryExtraCharge.Create(AOwner: TComponent);
begin
inherited;
FW := TExtraChargeW.Create(FDQuery);
FDQuery.OnUpdateRecord := DoOnQueryUpdateRecord;
end;
{$R *.dfm}
end.
|
{*********************************************************************
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Autor: Brovin Y.D.
* E-mail: y.brovin@gmail.com
*
********************************************************************}
unit FGX.VirtualKeyboard;
interface
uses
System.Classes, System.Types, System.Messaging, FMX.VirtualKeyboard, FMX.Types, FGX.VirtualKeyboard.Types,
FGX.Consts;
type
{ TfgVirtualKeyboard }
TfgVirtualKeyboardEvent = procedure (Sender: TObject; const Bounds: TRect) of object;
TfgVirtualKeyboardVisible = (Unknow, Shown, Hidden);
TfgCustomVirtualKeyboard = class(TComponent)
public const
DefaultEnabled = True;
private
FButtons: TfgButtonsCollection;
FEnabled: Boolean;
FKeyboardService: IFMXVirtualKeyboardToolbarService;
FLastState: TfgVirtualKeyboardVisible;
FOnShow: TfgVirtualKeyboardEvent;
FOnHide: TfgVirtualKeyboardEvent;
FOnSizeChanged: TfgVirtualKeyboardEvent;
protected
procedure SetEnabled(const Value: Boolean); virtual;
procedure SetButtons(const Value: TfgButtonsCollection); virtual;
procedure RefreshKeyboardButtons; virtual;
{ Virtual Keyboard Events }
procedure DoShow(const Bounds: TRect); virtual;
procedure DoSizeChanged(const Bounds: TRect); virtual;
procedure DoHide(const Bounds: TRect); virtual;
{ Message Handler }
procedure DoVirtualKeyboardChangeHandler(const Sender: TObject; const AMessage: TMessage);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function Supported: Boolean;
function Visible: Boolean;
public
property Buttons: TfgButtonsCollection read FButtons write SetButtons;
property Enabled: Boolean read FEnabled write SetEnabled default DefaultEnabled;
property OnShow: TfgVirtualKeyboardEvent read FOnShow write FOnShow;
property OnHide: TfgVirtualKeyboardEvent read FOnHide write FOnHide;
property OnSizeChanged: TfgVirtualKeyboardEvent read FOnSizeChanged write FOnSizeChanged;
end;
[ComponentPlatformsAttribute(fgMobilePlatforms)]
TfgVirtualKeyboard = class(TfgCustomVirtualKeyboard)
published
property Buttons;
property Enabled;
property OnShow;
property OnHide;
property OnSizeChanged;
end;
implementation
uses
System.SysUtils, FMX.Platform, FMX.Forms, FGX.Asserts;
{ TfgCustomVirtualKeyboard }
constructor TfgCustomVirtualKeyboard.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FButtons := TfgButtonsCollection.Create(Self, RefreshKeyboardButtons);
FEnabled := DefaultEnabled;
FLastState := TfgVirtualKeyboardVisible.Unknow;
TPlatformServices.Current.SupportsPlatformService(IFMXVirtualKeyboardToolbarService, FKeyboardService);
{ Subscriptions }
TMessageManager.DefaultManager.SubscribeToMessage(TVKStateChangeMessage, DoVirtualKeyboardChangeHandler);
end;
destructor TfgCustomVirtualKeyboard.Destroy;
begin
TMessageManager.DefaultManager.Unsubscribe(TVKStateChangeMessage, DoVirtualKeyboardChangeHandler);
FreeAndNil(FButtons);
FKeyboardService := nil;
inherited Destroy;
end;
procedure TfgCustomVirtualKeyboard.DoHide(const Bounds: TRect);
begin
if Assigned(FOnHide) then
FOnHide(Self, Bounds);
end;
procedure TfgCustomVirtualKeyboard.DoShow(const Bounds: TRect);
begin
if Assigned(FOnShow) then
FOnShow(Self, Bounds);
end;
procedure TfgCustomVirtualKeyboard.DoSizeChanged(const Bounds: TRect);
begin
if Assigned(FOnSizeChanged) then
FOnSizeChanged(Self, Bounds);
end;
procedure TfgCustomVirtualKeyboard.DoVirtualKeyboardChangeHandler(const Sender: TObject; const AMessage: TMessage);
var
VKMessage: TVKStateChangeMessage;
begin
AssertIsClass(AMessage, TVKStateChangeMessage);
VKMessage := AMessage as TVKStateChangeMessage;
case FLastState of
Unknow:
begin
if VKMessage.KeyboardVisible then
DoShow(VKMessage.KeyboardBounds)
else
DoHide(VKMessage.KeyboardBounds);
end;
Shown:
begin
if VKMessage.KeyboardVisible then
DoSizeChanged(VKMessage.KeyboardBounds)
else
DoHide(VKMessage.KeyboardBounds);
end;
Hidden:
begin
if VKMessage.KeyboardVisible then
DoShow(VKMessage.KeyboardBounds)
else
DoSizeChanged(VKMessage.KeyboardBounds);
end;
end;
if VKMessage.KeyboardVisible then
FLastState := TfgVirtualKeyboardVisible.Shown
else
FLastState := TfgVirtualKeyboardVisible.Hidden;
end;
procedure TfgCustomVirtualKeyboard.RefreshKeyboardButtons;
var
I: Integer;
Button: TfgButtonsCollectionItem;
begin
AssertIsNotNil(FButtons);
if not Supported then
Exit;
FKeyboardService.ClearButtons;
for I := 0 to FButtons.Count - 1 do
begin
Button := FButtons.GetButton(I);
if Button.Visible then
FKeyboardService.AddButton(Button.Caption, Button.OnClick);
end;
end;
procedure TfgCustomVirtualKeyboard.SetButtons(const Value: TfgButtonsCollection);
begin
AssertIsNotNil(Value);
FButtons.Assign(Value);
end;
procedure TfgCustomVirtualKeyboard.SetEnabled(const Value: Boolean);
begin
FEnabled := Value;
if Supported then
FKeyboardService.SetToolbarEnabled(Value);
end;
function TfgCustomVirtualKeyboard.Supported: Boolean;
begin
Result := FKeyboardService <> nil;
end;
function TfgCustomVirtualKeyboard.Visible: Boolean;
begin
Result := FLastState = TfgVirtualKeyboardVisible.Shown;
end;
initialization
RegisterFmxClasses([TfgCustomVirtualKeyboard, TfgVirtualKeyboard]);
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.