text
stringlengths
14
6.51M
{ *************************************************************************** } { } { This file is part of the XPde project } { } { Copyright (c) 2002 Zeljan Rikalo <zeljko@xpde.com> } { } { 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; see the file COPYING. If not, write to } { the Free Software Foundation, Inc., 59 Temple Place - Suite 330, } { Boston, MA 02111-1307, USA. } { } { *************************************************************************** } unit SysProvider; interface uses SysUtils, Classes,xpclasses,uRegistry,distro,hwinfo,usb; (* DON'T DELETE THIS !! IMAGES FOR DEVICES : sys=0,hdd=1,usb=2,vga=3,net=4,modem=5,mass=6,audio=7,unknown=8, computer=9,keyboard=10,mouse=11,hid=12,floppy=13,cdrom=14, ports=15,cpu=16,scsi=17,camera=18,scanner=19 *) Const _MAX_FUNCS=255; // SysPictures:Array [0..MAX_DEVICE_EXP] of string=('tux.png'); // TODO: List of pictures for system DevicesSigns:Array[0..MAX_DEVICE_EXP] of string=('System devices','System devices', 'System devices','IDE ATA/ATAPI controllers','System devices', 'Universal Serial Bus controllers','Display adapters','Network adapters', 'Modems','Mass Storage controllers','Sound,video and game controllers', 'Sound,video and game controllers'); DeviceShortSign:Array[0..MAX_SIGN_SHORT] of string=('System devices','IDE ATA/ATAPI controllers', 'Universal Serial Bus controllers','Display adapters','Network adapters', 'Modems','Mass Storage controllers','Sound,video and game controllers','USB Devices','Other Devices','SCSI controllers'); devicePics:Array[0..MAX_SIGN_SHORT] of integer=(0,1,2,3,4,5,6,7,2,8,17); OtherDevices:Array[0..MAX_OTHER_DEVICES] of string=('Unknown','Keyboard','Mice and other pointing devices', 'Floppy disc controllers','Disk drives', 'DVD/CDROM drives','Floppy disc drives','FireWire Controllers', 'Ports (COM & LPT)','Processors','SCSI storage controller'); OdevicePics:Array[0..MAX_OTHER_DEVICES] of integer=(8,10,11,13,1,14,13,17,15,16,17); // Storage volumes UsbClassDevices:Array[0..MAX_USB_CLASSES] of string=('USB Interface', 'USB Sound,video and game controllers','USB Communication Controller', 'Human Interface Devices','USB Physical devices', 'USB Imaging Devices','USB Printer','Storage volumes', 'USB HUB','USB Cdc Data','USB Smart Cards', 'USB Content Security','USB App_Spec','USB Vendor_spec', 'USB Unknown Device'); UsbClassDevicesPics:Array[0..MAX_USB_CLASSES] of integer=(2,7,5,12,2,19,2,1,2,2,2,2,2,2,8); // need more scai classes ScsiClassDevices:Array[0..1] of String=('Direct-Access','CD-ROM'); type PUsbInfo=PUsbInfo_; TUsbClasses=TUsb_Classes; PPci_Info=PPci_Info_; PNoDupsPciInfo=PNoDups_Pci_Info; TCpuInfo=TCpuInfo_; TDevicesList=devices_list; type struct_iomem=record lo_:string; hi_:string; name:string; End; TIoMem=struct_iomem; PIoMem=Array of TIoMem; type TSysProvider = class(TObject) private FValidNetDevice:boolean; FCableOn:boolean; UsC:TUsbClasses; { Private declarations } // Function ProvideRegistryAll:PPci_Info; // back in private later. Procedure AddUSBToPci(var pin:PPci_Info); Procedure AddCPUToPci(var pin:PPci_Info); Procedure AddKBDToPci(var pin:PPci_Info); Procedure AddHHDsToPci(var pin:PPci_Info); Function GetMaxDeviceExp:integer; Function GetMaxShortSign:integer; Function GetMaxUsbClasses:integer; Function GetMaxOtherDevices:integer; Function ProvideDistroInfo:TUname; Function MemoryInfo:cardinal; Function CPU_Info:TCpuInfo; Function GetHostName:string; Function GetUsbInfo:PUsbInfo; Procedure ProvideNetDeviceInfo(device:string); Function GetIoMem:PIoMem; protected { Protected declarations } public DevList:Array[0..MAX_DEVICE_EXP] of String; constructor Create; destructor Destroy; Override; Procedure WriteDistroInfo; Procedure WriteHwInfo; Function ProvideRegistryAll:PPci_Info; // just for testing, back it to private later Function GuessManufacturer(manu:string):string; Function CreateLocation(pin:PPCi_Info; recno:integer):string; Function FindDriver(var pin:PPci_Info; recno:integer):boolean; Procedure ChangeDeviceInfo(var pin:PPCi_Info); Function ReorganizeInfo(Const pin:PPCi_Info):PNoDupsPciInfo; Property MaxDeviceExp:integer read GetMaxDeviceExp; Property MaxOtherDevices:integer read GetMaxOtherDevices; Property MaxShortSign:integer read GetMaxShortSign; Property MaxUsbClasses:integer read GetMaxUsbClasses; Property usbclass:TUsbClasses read Usc; Property PCIInfo:PPci_Info read ProvideRegistryAll; Property DistInfo:TUname read ProvideDistroInfo; Property CpuInfo:TCpuInfo read Cpu_Info; Property MemInfo:cardinal read MemoryInfo; Property UsbInfo:PUsbInfo read GetUsbInfo; Property HostName:String read GetHostName; Property NetDeviceValid:boolean read FValidNetDevice; Property NetDeviceCableOn:boolean read FCableOn; { Public declarations } published { Published declarations } end; implementation constructor TSysProvider.Create; var i:integer; Begin for i:=0 to MAX_DEVICE_EXP do DevList[i]:=devices[i]; usc[0].class_:=USB_CLASS_PER_INTERFACE; usc[0].name:='>ifc '; usc[1].class_:=USB_CLASS_AUDIO; usc[1].name:='audio'; usc[2].class_:=USB_CLASS_COMM; usc[2].name:='comm.'; usc[3].class_:=USB_CLASS_HID; usc[3].name:='HID '; usc[4].class_:=USB_CLASS_PHYSICAL; usc[4].name:='PID '; usc[5].class_:=USB_CLASS_STILL_IMAGE; usc[5].name:='still'; usc[6].class_:=USB_CLASS_PRINTER; usc[6].name:='print'; usc[7].class_:=USB_CLASS_MASS_STORAGE; usc[7].name:='stor.'; usc[8].class_:=USB_CLASS_HUB; usc[8].name:='hub '; usc[9].class_:=USB_CLASS_CDC_DATA; usc[9].name:='data '; usc[10].class_:=USB_CLASS_CSCID; usc[10].name:='scard'; usc[11].class_:=USB_CLASS_CONTENT_SEC; usc[11].name:='c-sec'; usc[12].class_:=USB_CLASS_APP_SPEC; usc[12].name:='app. '; usc[13].class_:=USB_CLASS_VENDOR_SPEC; usc[13].name:='vend.'; usc[14].class_:=USB_CLASS_UNKNOWN; usc[14].name:='unk. '; for i:=0 to MAX_USB_CLASSES do usc[i].cheat:=UsbClassDevices[i]; End; destructor TSysProvider.Destroy; Begin inherited; End; Procedure TSysProvider.WriteDistroInfo; var reg: TRegistry; Struct_Data:TUname; Begin Struct_Data:=Get_Distro_Version; reg:=TRegistry.create; try if reg.OpenKey('Software/XPde/System',true) then begin reg.Writeinteger(dist_reg[0],struct_Data.dist); reg.Writestring(dist_reg[1],struct_Data.name); reg.Writestring(dist_reg[2],struct_Data.sys); reg.Writestring(dist_reg[3],struct_Data.version); reg.Writestring(dist_reg[4],struct_Data.kernel); reg.Writestring(dist_reg[5],struct_Data.machine); reg.Writestring(dist_reg[6],struct_Data.krnl_date); end; finally reg.free; end; End; Procedure TSysProvider.WriteHwInfo; var reg: TRegistry; pcinf:PPCi_Info; i,x:integer; Begin reg:=TRegistry.create; try pcinf:=ReadHW('/proc/pci'); for i:=0 to length(pcinf)-1 do begin if reg.OpenKey('Hardware/XPde/'+IntToStr(pcinf[i].bus_id)+'/'+IntToStr(pcinf[i].device_id)+'/'+IntToStr(pcinf[i].device_function),true) then begin reg.Writestring(pci_reg[0],pcinf[i].device_type); reg.Writestring(pci_reg[1],pcinf[i].device_info); reg.Writeinteger(pci_reg[2],pcinf[i].device_irq); reg.Writebool(pci_reg[3],pcinf[i].device_add.master_capable); reg.Writebool(pci_reg[4],pcinf[i].device_add.no_bursts); reg.Writeinteger(pci_reg[5],pcinf[i].device_add.latency); reg.Writeinteger(pci_reg[6],pcinf[i].device_add.gnt); reg.Writeinteger(pci_reg[7],pcinf[i].device_add.lat); for x:=0 to 31 do begin if pcinf[i].device_io_from[x]<>'' then begin reg.Writestring(pci_reg[8]+IntToStr(x),pcinf[i].device_io_from[x]); reg.Writestring(pci_reg[9]+IntToStr(x),pcinf[i].device_io_to[x]); End; End; reg.Writestring(pci_reg[10],pcinf[i].non_prefetch_lo); reg.Writestring(pci_reg[11],pcinf[i].non_prefetch_hi); reg.Writestring(pci_reg[12],pcinf[i].prefetchable_lo); reg.Writestring(pci_reg[13],pcinf[i].prefetchable_hi); reg.Writestring(pci_reg[14],pcinf[i].driver); reg.CloseKey; end; End; finally reg.free; end; End; Function TSysProvider.ProvideRegistryAll:PPci_Info; // provides all hw informations for ControlPanel->System var pin:PPci_Info; sr,sr1,sr2:TSearchRec; x,fat,i,bus,j,jj,jjj:integer; busses:Array[0..1023] of integer; deviids:Array[0..1023] of integer; devfuncs:Array[0..1023] of integer; reg:TRegistry; Begin for bus:=0 to 1023 do begin busses[bus]:=-1; deviids[bus]:=-1; devfuncs[bus]:=-1; End; SetLength(pin,_MAX_FUNCS); reg:=TRegistry.Create; Fat:=faDirectory; i:=0; j:=0; jj:=0; jjj:=0; if FindFirst(reg.RootKey+'/Hardware/XPde/*',Fat,sr)=0 then repeat if (sr.Attr and Fat)=sr.Attr then begin if TryStrToInt(sr.Name,busses[j]) then begin busses[j]:=StrToInt(sr.Name); inc(j); if FindFirst(reg.RootKey+'/Hardware/XPde/'+sr.Name+'/*',Fat,sr1)=0 then repeat if (sr1.Attr and Fat)=sr1.Attr then begin if TryStrToInt(sr1.Name,deviids[jj]) then begin {$IFDEF DEBUG} writeln('Bus ',busses[j-1],' sr1.Name ',sr1.Name); {$ENDIF} deviids[jj]:=StrToInt(sr1.Name); inc(jj); if FindFirst(reg.RootKey+'/Hardware/XPde/'+sr.Name+'/'+sr1.Name+'/*',Fat,sr2)=0 then repeat if (sr2.Attr and Fat)=sr2.Attr then begin if TryStrToInt(sr2.Name,devfuncs[jjj]) then begin pin[jjj].bus_id:=StrToInt(sr.Name); pin[jjj].device_id:=StrToInt(sr1.Name); pin[jjj].device_function:=StrToInt(sr2.Name); if reg.OpenKey('Hardware/XPde/'+sr.Name+'/'+sr1.Name+'/'+sr2.Name,false) then begin pin[jjj].device_type:=reg.Readstring(pci_reg[0]); pin[jjj].device_info:=reg.Readstring(pci_reg[1]); pin[jjj].device_irq:=reg.Readinteger(pci_reg[2]); pin[jjj].device_add.master_capable:=reg.Readbool(pci_reg[3]); pin[jjj].device_add.no_bursts:=reg.Readbool(pci_reg[4]); pin[jjj].device_add.latency:=reg.Readinteger(pci_reg[5]); pin[jjj].device_add.gnt:=reg.Readinteger(pci_reg[6]); pin[jjj].device_add.lat:=reg.Readinteger(pci_reg[7]); for x:=0 to 31 do begin pin[jjj].device_io_from[x]:=reg.Readstring(pci_reg[8]+IntToStr(x)); pin[jjj].device_io_to[x]:=reg.Readstring(pci_reg[9]+IntToStr(x)); End; pin[jjj].non_prefetch_lo:=reg.Readstring(pci_reg[10]); pin[jjj].non_prefetch_hi:=reg.Readstring(pci_reg[11]); pin[jjj].prefetchable_lo:=reg.Readstring(pci_reg[12]); pin[jjj].prefetchable_hi:=reg.Readstring(pci_reg[13]); pin[jjj].driver:=reg.Readstring(pci_reg[14]); End; {$IFDEF DEBUG} writeln('Bus ',busses[j-1],' sr1.Name ',sr1.Name,' sr2.Name ',sr2.Name); {$ENDIF} // here we fill up registry struct for pciinfo devfuncs[jjj]:=StrToInt(sr2.Name); inc(jjj); End; End; until FindNext(sr2)<>0; // functions loop End; End; until FindNext(sr1)<>0; End; // end find busses inc(i); End; // founded attr until FindNext(sr)<>0; FindClose(sr); reg.Free; SetLength(pin,jjj+1); // Set real length for pin array Result:=pin; End; Function TSysProvider.ProvideDistroInfo:TUname; // provides distro information via TUName var una:TUname; reg: TRegistry; Begin reg:=TRegistry.Create; try if reg.OpenKey('Software/XPde/System',false) then begin una.dist:=reg.Readinteger(dist_reg[0]); una.name:=reg.Readstring(dist_reg[1]); una.sys:=reg.Readstring(dist_reg[2]); una.version:=reg.Readstring(dist_reg[3]); una.kernel:=reg.Readstring(dist_reg[4]); una.machine:=reg.Readstring(dist_reg[5]); una.krnl_date:=reg.Readstring(dist_reg[6]); End; finally reg.Free; End; Result:=una; End; Function TSysProvider.GetUsbInfo:PUsbInfo; // this will be abandoned as soon as possible with libusb port ! var uusb:PUsbInfo; fd:TextFile; strs:TStrings; s:string; buspos:Array[0..1023] of integer; counter,i,j,x,bus_id:integer; busfounded:boolean; Function GetUsbValueInt(Const value,data:string):integer; var ii,jj:integer; s,ss:string; Begin ss:='-1'; ii:=AnsiPos(value,data); if ii<>0 then begin s:=data; s:=copy(data,ii+length(value),length(data)); s:=trimleft(s); jj:=Pos(' ',s); if jj<>0 then begin ss:=Copy(s,1,jj-1); End; End; try Result:=StrToInt(ss); except Result:=-1; End; End; Function GetUsbValueStr(Const value,data:string):String; var ii,jj:integer; s,s1,ss:string; Begin ss:=''; s1:=data+' '; ii:=AnsiPos(value,s1); if ii<>0 then begin s:=copy(s1,ii+length(value),length(s1)); s:=trimleft(s); if (value<>usbinfobus[9]) and (value<>usbinfobus[10]) then jj:=Pos(' ',s) else jj:=length(s)+1; if jj<>0 then begin ss:=Copy(s,1,jj-1); End; End; Result:=ss; End; Function GetUsbValueClassStr(Const value,data:string):String; var ii,jj:integer; s,s1,ss:string; Begin ss:=''; s1:=data+' '; ii:=AnsiPos(value,s1); if ii<>0 then begin s:=copy(s1,ii+length(value),length(s1)); s:=trimleft(s); if (value<>usbinfobus[9]) and (value<>usbinfobus[10]) then jj:=Pos(' ',s) else jj:=length(s)+1; if jj<>0 then begin ss:=Copy(s,1,jj-1); End; End; ss:=trim(ss); if copy(ss,1,2)='00' then ss:=''; // it's some device so find it ;) Result:=ss; End; Procedure CheckForClass(var s:string); var ii,jj:integer; ss,sss1:string; Begin ss:=s; sss1:=copy(ss,1,2); if sss1='ff' then sss1:='255' else if sss1='fe' then sss1:='254' else if sss1='0d' then sss1:='13' else if sss1='0b' then sss1:='11' else if sss1='0a' then sss1:='10'; if TryStrToInt(sss1,ii) then begin for jj:=0 to MAX_USB_CLASSES do if usc[jj].class_=ii then begin s:=usc[jj].cheat; break; End; End; End; Begin for i:=0 to 1023 do buspos[i]:=-1; busfounded:=true; SetLength(uusb,0); if FileExists('/proc/bus/usb/devices') then begin strs:=TStringList.Create; try AssignFile(fd,'/proc/bus/usb/devices'); Reset(fd); while not eof(fd) do begin readln(fd,s); strs.Add(s); End; CloseFile(fd); counter:=0; for i:=0 to strs.Count-1 do begin if AnsiPos(usbinfobus[0],strs.Strings[i])<>0 then begin inc(counter); buspos[counter-1]:=i; End; End; SetLength(uusb,counter); for i:=0 to strs.Count-1 do begin for j:=0 to counter-1 do begin if i=buspos[j] then begin uusb[j].bus:=GetUsbValueInt(usbinfobus[0],strs.Strings[i]); uusb[j].lev:=GetUsbValueInt(usbinfobus[1],strs.Strings[i]); uusb[j].prnt:=GetUsbValueInt(usbinfobus[2],strs.Strings[i]); uusb[j].port:=GetUsbValueInt(usbinfobus[3],strs.Strings[i]); uusb[j].device:=GetUsbValueInt(usbinfobus[4],strs.Strings[i]); uusb[j].spd:=GetUsbValueInt(usbinfobus[5],strs.Strings[i]); uusb[j].driver:=''; bus_id:=j; busfounded:=true; End; End; if busfounded then begin if uusb[bus_id].ver='' then uusb[bus_id].ver:=GetUsbValueStr(usbinfobus[6],strs.Strings[i]); if uusb[bus_id].vendor='' then uusb[bus_id].vendor:=GetUsbValueStr(usbinfobus[7],strs.Strings[i]); {$MESSAGE WARN 'FIXME vendor can be obtained from usb vendors list and translated into Manufacturer name if uusb[n].manufacturer is empty'} if uusb[bus_id].prod_id='' then uusb[bus_id].prod_id:=GetUsbValueStr(usbinfobus[8],strs.Strings[i]); if uusb[bus_id].manufacturer='' then uusb[bus_id].manufacturer:=GetUsbValueStr(usbinfobus[9],strs.Strings[i]); if uusb[bus_id].product='' then uusb[bus_id].product:=GetUsbValueStr(usbinfobus[10],strs.Strings[i]); if uusb[bus_id].cls='' then uusb[bus_id].cls:=GetUsbValueClassStr(usbinfobus[11],strs.Strings[i]); if uusb[bus_id].cls<>'' then begin for x:=0 to MAX_USB_CLASSES do CheckForClass(uusb[bus_id].cls); End; if uusb[bus_id].driver='' then uusb[bus_id].driver:=GetUsbValueStr(usbinfobus[12],strs.Strings[i]); if uusb[bus_id].driver<>'' then busfounded:=false; End; End; {$IFDEF DEBUG} for i:=0 to Length(uusb)-1 do // if manufacturer='' and vendor<>'0000' then search_manufacturer writeln('UUSB BUS ',uusb[i].bus,' LEV ',uusb[i].lev,' PRNT ',uusb[i].prnt,' PORT ',uusb[i].port,' DEVICE ',uusb[i].device,' SPD ',uusb[i].spd,' VER ',uusb[i].ver,' VEND ',uusb[i].vendor,' PROD_ID ',uusb[i].prod_id,' MANUF ',uusb[i].manufacturer,' PROD ',uusb[i].product,' Driver=',uusb[i].driver,' CLS ',uusb[i].cls); {$ENDIF} // read /proc/bus/usb finally strs.Free; End; End; Result:=uusb; End; Procedure TSysProvider.ProvideNetDeviceInfo(device:string); // provides net device info eg. ip address,mask,HW addr,connection etc... Begin // End; Function TSysProvider.MemoryInfo:cardinal; Begin Result:=InstalledRam; End; Function TSysProvider.CPU_Info:TCpuInfo; Begin Result:=CpuInfo_; End; Function TSysProvider.GetHostName:String; var hd:THostData; Begin hd:=GetHostName_; // Strange...on Debian 3.0 I cannot get hostname via // GetEnvironmentVariable('HOSTNAME') but I can see it via // $echo $HOSTNAME ?!?!? // so ugly workaround is // to get record from Libc.PHostEnt if ProvideDistroInfo.dist=diDebian then Result:=String(hd^.h_name) else Result:=SysUtils.GetEnvironmentVariable('HOSTNAME'); End; Procedure TSysProvider.ChangeDeviceInfo(var pin:PPCi_Info); var i,j:integer; Begin for i:=0 to length(pin)-1 do begin if pin[i].device_type<>'' then begin for j:=0 to MAX_DEVICE_EXP do if pin[i].device_type=devices[j] then pin[i].device_type:=DevicesSigns[j]; End; End; AddUSBToPci(pin); AddCPUToPci(pin); AddKBDToPci(pin); AddHHDsToPci(pin); End; Function TSysProvider.ReorganizeInfo(Const pin:PPCi_Info):PNoDupsPciInfo; var pno:PNoDupSPciInfo; i,j,x:integer; pinn:Array[0..MAX_SIGN_SHORT] of integer; idup:Array[0..1024] of integer; // be sure to have enough room for PPci_Info st:TStrings; Begin for i:=0 to MAX_SIGN_SHORT do pinn[i]:=-1; SetLength(pno,MAX_SIGN_SHORT+1); for j:=0 to MAX_SIGN_SHORT do begin pno[j].kind:=DeviceShortSign[j]; pno[j].device_type:=DeviceShortSign[j]; for x:=0 to 64 do pno[j].device_point[x]:=-1; End; st:=TStringList.Create; try for i:=0 to 1024 do idup[i]:=0; for i:=0 to length(pin)-1 do begin if i=0 then st.Add(pin[i].device_info) else begin for j:=0 to St.Count-1 do begin if st.Strings[j]=pin[i].device_info then begin inc(idup[j]); // inc copy of device name pin[i].device_info:=pin[i].device_info+' #'+IntToStr(idup[j]); break; End; End; st.Add(pin[i].device_info); End; // check dups End; finally st.Free; End; for i:=0 to MAX_SIGN_SHORT do begin for j:=0 to length(pin)-1 do begin if (pin[j].device_type=pno[i].kind) and (pin[j].device_info<>'') then begin inc(pinn[i]); pno[i].device_info[pinn[i]]:=pin[j].device_info; if i=8 then begin pno[i].usbclass:=pin[j].usbclass; pno[i].device_class[pinn[i]]:=pin[j].usbclass; pno[i].device_point[pinn[i]]:=j; End; if i=9 then begin pno[i].usbclass:=pin[j].usbclass; pno[i].otherdevice:=pin[j].usbclass; pno[i].device_class[pinn[i]]:=pin[j].usbclass; pno[i].device_point[pinn[i]]:=j; End; if i=10 then begin pno[i].usbclass:=pin[j].usbclass; pno[i].otherdevice:=pin[j].usbclass; pno[i].device_class[pinn[i]]:=pin[j].usbclass; pno[i].device_point[pinn[i]]:=j; End; End; End; End; for i:=0 to MAX_SIGN_SHORT do if pinn[i]=-1 then pno[i].device_type:=''; Result:=pno; End; Function TSysProvider.GetMaxDeviceExp:integer; Begin Result:=MAX_DEVICE_EXP; End; Function TSysProvider.GetMaxShortSign:integer; Begin Result:=MAX_SIGN_SHORT; End; Function TSysProvider.GetMaxUsbClasses:integer; Begin Result:=MAX_USB_CLASSES; End; Function TSysProvider.GetMaxOtherDevices:integer; Begin Result:=MAX_OTHER_DEVICES; End; Function TSysProvider.GuessManufacturer(manu:string):string; var j:integer; s:string; Begin Result:='Unknown'; s:=manu; s:=trim(s); j:=pos(' ',s); if j<>0 then begin Result:=copy(s,1,j-1); End; End; Function TSysProvider.CreateLocation(pin:PPCi_Info; recno:integer):string; Const infos:Array[0..5] of String=('PCI bus','device','function','USB bus','Block Device','SCSI Host'); var i:integer; s1,s2:string; Begin Result:=pin[recno].device_info; if pin[recno].device_type=DeviceShortSign[8] then begin s1:=infos[3]; s1:=s1+' '+IntToStr(pin[recno].bus_id)+','; s1:=s1+infos[1]+' '+IntToStr(pin[recno].device_id)+','+infos[2]+' '+IntToStr(pin[recno].device_function); end else if pin[recno].device_type=DeviceShortSign[9] then begin s1:=infos[0]; s1:=s1+' '+IntToStr(pin[recno].bus_id)+','; if (pin[recno].usbclass=OtherDevices[4]) or (pin[recno].usbclass=OtherDevices[5]) or (pin[recno].usbclass=OtherDevices[6]) then s1:=s1+infos[1]+' /dev/hd'+char(pin[recno].device_id)+','+infos[2]+' '+IntToStr(pin[recno].device_function) else s1:=s1+infos[1]+' '+IntToStr(pin[recno].device_id)+','+infos[2]+' '+IntToStr(pin[recno].device_function); end else if pin[recno].device_type=DeviceShortSign[10] then begin s1:=infos[5]; s1:=s1+' Ch: '+IntToStr(pin[recno].bus_id)+','; (* bug with recno ?!? writeln('RECNO=',recno,' FUNCTION=',pin[recno].device_function); *) s1:=s1+' Id: '+' '+IntToStr(pin[recno].device_id)+','+' Lun: '+' '+IntToStr(pin[recno].device_function); End else begin s1:=infos[0]; s1:=s1+' '+IntToStr(pin[recno].bus_id)+','; s1:=s1+infos[1]+' '+IntToStr(pin[recno].device_id)+','+infos[2]+' '+IntToStr(pin[recno].device_function); End; Result:=s1; End; Procedure TSysProvider.AddUSBToPci(var pin:PPci_Info); var i,j,x,ar_len,us_len:integer; usbi:PUsbInfo; Function FindUSBProduct(prod:string):string; Const keywrds:Array[0..5] of String=('SCANNER','CAMERA','DISC','CDROM','PRINTER','FLOPPY'); var s:string; ii:integer; Begin s:=UsbClassDevices[MAX_USB_CLASSES]; prod:=UpperCase(prod); for ii:=0 to 5 do begin if AnsiPos(keywrds[ii],prod)<>0 then begin case ii of 0,1:s:=UsbClassDevices[5]; 2,3,4:s:=UsbClassDevices[7]; 5:s:=UsbClassDevices[6]; End; // case ii End; End; Result:=s; End; Begin ar_len:=length(pin); usbi:=GetUsbInfo; us_len:=length(usbi); SetLength(pin,ar_len+us_len); x:=-1; for i:=ar_len to length(pin)-1 do begin inc(x); if x<=us_len-1 then begin {$IFDEF DEBUG} writeln('BUS=',usbi[x].bus,' PORT=',usbi[x].port,' VEN ',usbi[x].vendor,' PROD_ID ',usbi[x].prod_id,' MANUF ',usbi[x].manufacturer,' PRODUCT ',usbi[x].product,' CLS ',usbi[x].cls,' DRV ',usbi[x].driver); {$ENDIF} if usbi[x].prod_id='0000' then begin pin[i].bus_id:=usbi[x].bus; pin[i].device_id:=usbi[x].device; pin[i].device_function:=usbi[x].port; pin[i].device_type:=DeviceShortSign[2]; pin[i].device_irq:=255; pin[i].device_info:=usbi[x].product; pin[i].sign:=usbi[x].vendor; pin[i].driver:=usbi[x].driver; End else begin pin[i].bus_id:=usbi[x].bus; pin[i].device_id:=usbi[x].device; pin[i].device_function:=usbi[x].port; pin[i].device_type:=DeviceShortSign[8]; pin[i].device_irq:=255; if (usbi[x].product<>'') and (usbi[x].cls='') then usbi[x].cls:=FindUsbProduct(usbi[x].product); // ugly if usbi[x].cls='' then usbi[x].cls:=UsbClassDevices[MAX_USB_CLASSES]; pin[i].usbclass:=usbi[x].cls; pin[i].device_info:=usbi[x].product; if pin[i].device_info='' then pin[i].device_info:='Unknown USB '+usbi[x].driver+' product'; pin[i].sign:=usbi[x].manufacturer; pin[i].driver:=usbi[x].driver; End; End; End; End; Procedure TSysProvider.AddCPUToPci(var pin:PPci_Info); var ci:TCpuInfo; i:integer; Begin ci:=Cpu_Info; i:=length(pin)+1; SetLength(pin,i); i:=i-1; pin[i].bus_id:=ci.processor; pin[i].device_id:=ci.processor; pin[i].device_function:=ci.processor; pin[i].device_type:=DeviceShortSign[9]; pin[i].device_info:=ci.model_name; pin[i].sign:=ci.vendor_id; pin[i].device_irq:=255; pin[i].usbclass:=OtherDevices[9]; End; Procedure TSysProvider.AddKBDToPci(var pin:PPci_Info); var s,s1,s2,io1,io2:string; st:TStrings; fil:TextFile; i,j,x,y:integer; founded:boolean; Begin st:=TStringList.Create; j:=-1; founded:=false; try AssignFile(fil,'/proc/ioports'); Reset(fil); while not eof(fil) do begin readln(fil,s); st.Add(s); End; CloseFile(fil); for i:=0 to st.Count-1 do if AnsiPos('keyboard',st.Strings[i])<>0 then begin j:=i; break; End; if j<>-1 then begin x:=Pos(':',st.Strings[j]); if x<>0 then begin s:=copy(st.Strings[j],1,x-1); y:=Pos('-',s); if y<>0 then begin io1:=copy(s,1,y-1); io2:=copy(s,y+1,length(s)-(y-1)); founded:=true; End; End; End; if founded then begin i:=length(pin)+1; SetLength(pin,i); i:=i-1; pin[i].bus_id:=0; pin[i].device_id:=0; pin[i].device_function:=0; pin[i].device_type:=DeviceShortSign[9]; pin[i].device_info:='Standard 101/102-Key or Linux Natural PS/2 Keyboard'; pin[i].device_irq:=1; pin[i].device_io_from[0]:=io1; pin[i].device_io_to[0]:=io2; pin[i].sign:='keyboard'; pin[i].driver:='keyboard'; pin[i].usbclass:=OtherDevices[1]; End; finally st.Free; End; End; Procedure TSysProvider.AddHHDsToPci(var pin:PPci_Info); label scsii; var hdi:PPCi_Info; i,j,x,y:integer; Begin hdi:=GetHardDiscs; if length(hdi)=0 then goto scsii; i:=length(hdi); x:=length(pin); j:=x+i; SetLength(pin,j); i:=0; for y:=x to length(pin)-1 do begin pin[y].bus_id:=hdi[i].bus_id; pin[y].device_id:=hdi[i].device_id; pin[y].device_function:=hdi[i].device_function; pin[y].device_type:=hdi[i].device_type; pin[y].device_info:=hdi[i].device_info; pin[y].device_irq:=hdi[i].device_irq; pin[y].usbclass:=hdi[i].usbclass; pin[y].sign:=hdi[i].sign; pin[y].driver:=hdi[i].driver; inc(i); End; SetLength(hdi,0); scsii: hdi:=GetScsiDiscs; if length(hdi)=0 then exit; i:=length(hdi); x:=length(pin); j:=x+i; SetLength(pin,j); i:=0; for y:=x to length(pin)-1 do begin pin[y].bus_id:=hdi[i].bus_id; pin[y].device_id:=hdi[i].device_id; pin[y].device_function:=hdi[i].device_function; pin[y].device_type:=hdi[i].device_type; pin[y].device_info:=hdi[i].device_info; pin[y].device_irq:=hdi[i].device_irq; pin[y].usbclass:=hdi[i].usbclass; pin[y].sign:=hdi[i].sign; pin[y].driver:=hdi[i].driver; inc(i); End; End; Function TSysProvider.GetIoMem:PIoMem; var i,j,x,y:integer; st:TStrings; pm:PioMem; fil:TextFile; s,s1,s2:string; Begin SetLength(pm,0); st:=TStringList.Create; try AssignFile(fil,'/proc/iomem'); Reset(fil); while not eof(fil) do begin readln(fil,s); st.Add(s); End; CloseFile(fil); SetLength(pm,st.Count+1); for i:=0 to st.Count-1 do begin st.Strings[i]:=trim(st.Strings[i]); j:=Pos(':',st.Strings[i]); if j<>0 then begin s1:=copy(st.Strings[i],1,j-1); s1:=trim(s1); x:=Pos('-',s1); if x<>0 then begin pm[i].lo_:=copy(s1,1,x-1); pm[i].hi_:=copy(s1,x+1,length(s1)-(x-1)); pm[i].name:=copy(st.Strings[i],j+1,length(st.Strings[i])-(j-1)); pm[i].name:=trim(pm[i].name); End; End; End; finally st.Free; End; Result:=pm; End; Function TSysProvider.FindDriver(var pin:PPci_Info; recno:integer):boolean; var i,j,x,y:integer; s1,s2:string; pmi:PIoMem; Begin Result:=false; y:=-1; pmi:=GetIOMem; {$IFDEF DEBUG} for i:=0 to length(pmi)-1 do begin writeln('LO ',pmi[i].lo_,' HI ',pmi[i].hi_,' Name ',pmi[i].name); End; {$ENDIF} if recno=-1 then begin // search for all pci devices for i:=0 to length(pin)-1 do begin if pin[i].usbclass='' then begin End; End; End else begin if pin[recno].usbclass='' then begin for j:=0 to length(pmi)-1 do begin if (pmi[j].lo_=pin[recno].non_prefetch_lo) or (pmi[j].lo_=pin[recno].prefetchable_lo) then begin {$IFDEF DEBUG} writeln('Founded driver ',pmi[j].name,' Y=',y); {$ENDIF} Result:=true; if length(pmi[j].name)>2 then y:=j; End; End; End; if y<>-1 then pin[recno].driver:=pmi[y].name; End; End; end.
{$IFDEF FREEPASCAL} {$MODE DELPHI} {$ENDIF} unit dll_user32_rect; interface uses atmcmbaseconst, winconst, wintype; function SetRect(var lprc: TRect; xLeft, yTop, xRight, yBottom: Integer): BOOL; stdcall; external user32 name 'SetRect'; function SetRectEmpty(var lprc: TRect): BOOL; stdcall; external user32 name 'SetRectEmpty'; function UnionRect(var lprcDst: TRect; const lprcSrc1, lprcSrc2: TRect): BOOL; stdcall; external user32 name 'UnionRect'; function CopyRect(var lprcDst: TRect; const lprcSrc: TRect): BOOL; stdcall; external user32 name 'CopyRect'; { InflateRect函数增大或减小指定矩形的宽和高 } function InflateRect(var lprc: TRect; dx, dy: Integer): BOOL; stdcall; external user32 name 'InflateRect'; function IntersectRect(var lprcDst: TRect; const lprcSrc1, lprcSrc2: TRect): BOOL; stdcall; external user32 name 'IntersectRect'; function SubtractRect(var lprcDst: TRect; const lprcSrc1, lprcSrc2: TRect): BOOL; stdcall; external user32 name 'SubtractRect'; function OffsetRect(var lprc: TRect; dx, dy: Integer): BOOL; stdcall; external user32 name 'OffsetRect'; function IsRectEmpty(const lprc: TRect): BOOL; stdcall; external user32 name 'IsRectEmpty'; function EqualRect(const lprc1, lprc2: TRect): BOOL; stdcall; external user32 name 'EqualRect'; function PtInRect(const lprc: TRect; pt: TPoint): BOOL; stdcall; external user32 name 'PtInRect'; { 该函数把相对于一个窗口的坐标空间的一组点映射成相对于另一窗口的坐标空间的一组点 hWndfrom:转换点所在窗口的句柄,如果此参数为NULL或HWND_DESETOP则假定这些点在屏幕坐标上。   hWndTo:转换到的窗口的句柄,如果此参数为NULL或HWND_DESKTOP,这些点被转换为屏幕坐标 pt := Mouse.CursorPos; MapWindowPoints(0, Handle, pt, 1); ScreenToClient 和 ClientToScreen CPoint pt(0,0); int i = ::MapWindowPoints(this->m_hWnd,GetDesktopWindow()->m_hWnd, &pt,10); } function MapWindowPoints(hWndFrom, hWndTo: HWND; var lpPoints; cPoints: UINT): Integer; stdcall; external user32 name 'MapWindowPoints'; implementation end.
unit SeletFolder_u; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, ShellCtrls, Buttons; type TdlgSelectFolder = class(TForm) Label1: TLabel; Label2: TLabel; edDestFolder: TEdit; ShellDirTree: TShellTreeView; btnOk: TBitBtn; btnCancel: TBitBtn; procedure ShellDirTreeChange(Sender: TObject; Node: TTreeNode); procedure btnOkClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var dlgSelectFolder: TdlgSelectFolder; implementation uses Advanced; {$R *.dfm} procedure TdlgSelectFolder.ShellDirTreeChange(Sender: TObject; Node: TTreeNode); begin edDestFolder.Text:=ShellDirTree.Path; end; procedure TdlgSelectFolder.btnOkClick(Sender: TObject); begin {If Not DirectoryExists(edDestFolder.Text) Then Begin MessageBox(Handle,'There are is not directory, please try again','Error',MB_OK+MB_ICONEXCLAMATION); Exit; End;} ModalResult:=mrOk; end; procedure TdlgSelectFolder.FormCreate(Sender: TObject); begin Caption:=ReadFromLanguage('Windows','wndSelectDir',Caption); btnCancel.Caption:=ReadFromLanguage('Buttons','btnCancel',btnCancel.Caption); Label1.Caption:=ReadFromLanguage('Labels','lbSelectDir',Label1.Caption); Label2.Caption:=ReadFromLanguage('Labels','bFolder',Label2.Caption); 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.4 04/09/2004 12:45:16 ANeillans { Moved the databasename and output paths into a globally accessible variable { -- makes it a lot easier to override if you need to (as I did for my local { file structure). } { { Rev 1.3 2004.06.13 8:42:42 PM czhower { Added name. } { { Rev 1.2 2004.06.13 8:06:14 PM czhower { Update for D8 } { { Rev 1.1 6/8/2004 3:52:52 PM JPMugaas { FTP List generation should work. } { { Rev 1.0 6/8/2004 2:15:50 PM JPMugaas { FTP Listing unit generation. } unit PackageFTPParsers; interface uses Package; type TFTPParsers = class(TPackage) public constructor Create; override; procedure Generate(ACompiler: TCompiler); override; end; implementation uses SysUtils, DModule; { TFTPParsers } constructor TFTPParsers.Create; begin inherited; FName := 'IdAllFTPListParsers'; FExt := '.pas'; end; procedure TFTPParsers.Generate(ACompiler: TCompiler); var i: Integer; begin inherited; //We don't call many of the inherited Protected methods because //those are for Packages while I'm making a unit. Code('unit IdAllFTPListParsers;'); Code(''); Code('interface'); Code(''); Code('{'); Code('Note that is unit is simply for listing ALL FTP List parsers in Indy.'); Code('The user could then add this unit to a uses clause in their program and'); Code('have all FTP list parsers linked into their program.'); Code(''); Code('ABSOLELY NO CODE is permitted in this unit.'); Code(''); Code('}'); Code('// RLebeau 4/17/10: this forces C++Builder to link to this unit so'); Code('// the units can register themselves correctly at program startup...'); Code(''); Code('(*$HPPEMIT ''#pragma link "IdAllFTPListParsers"''*)'); //Now add our units Code(''); Code('implementation'); Code(''); Code('uses'); for i := 0 to FUnits.Count - 1 do begin Code(' ' + ChangeFileExt(FUnits[i], '') + iif(i < FUnits.Count - 1, ',', ';')); end; // Code(''); Code('{dee-duh-de-duh, that''s all folks.}'); WriteFile(DM.OutputPath + '\Lib\Protocols\'); end; end.
unit TNsRemoteProcessManager.Domain.Interfaces.ProcessFunctionality; interface type IProcessFunctionality = interface['{E7733EEE-DC9B-4BBB-AD6C-6A347EAE7297}'] function Kill(const ProcessName : string) : Cardinal; overload; function Kill(PID : Integer) : Cardinal; overload; function StartService(const ServiceName : string) : Cardinal; function StopService(const ServiceName : string) : Cardinal; overload; function Execute(const Path, Params : string) : Boolean; end; implementation end.
unit TestSerializer; interface uses BaseTestRest, Generics.Collections, SuperObject, ContNrs, Classes, SysUtils; type TPhone = class(TObject) public _number: Int64; _code: Integer; published property number: Int64 read _number write _number; property code: Integer read _code write _code; end; TPhoneArray = array of TPhone; TPerson = class(TObject) private _age: Integer; _name: String; _father: TPerson; _phones : TPhoneArray; public function ToString: string; override; destructor Destroy; override; published property age: Integer read _age write _age; property name: string read _name write _name; property father: TPerson read _father write _father; property phones: TPhoneArray read _phones write _phones; end; TTestDesserializer = class(TBaseTestRest) published procedure person; procedure personWithFather; procedure personWithFatherAndPhones; end; TTestSerializer = class(TBaseTestRest) published procedure person; end; implementation uses RestJsonUtils; { TTestDesserializer } procedure TTestDesserializer.personWithFather; const sJson = '{' + ' "name": "Helbert",' + ' "age": 30,' + ' "father": {' + ' "name": "Luiz",' + ' "age": 60,' + ' "father": null,' + ' "phones": null' + ' }' + '}'; var vPerson: TPerson; begin vPerson := TPerson(TJsonUtil.UnMarshal(TPerson, sJson)); try CheckNotNull(vPerson); CheckEquals('Helbert', vPerson.name); CheckEquals(30, vPerson.age); CheckNotNull(vPerson.father); CheckEquals('Luiz', vPerson.father.name); CheckEquals(60, vPerson.father.age); finally vPerson.Free; end; end; procedure TTestDesserializer.personWithFatherAndPhones; const sJson = '{' + ' "name": "Helbert",' + ' "age": 30,' + ' "father": {' + ' "name": "Luiz",' + ' "age": 60,' + ' "father": null,' + ' "phones": null' + ' },' + ' "phones": [' + ' {' + ' "number": 33083518,' + ' "code": 61' + ' },' + ' {' + ' "number": 99744165,' + ' "code": 61' + ' }' + ' ]' + '}'; var vPerson: TPerson; begin vPerson := TPerson(TJsonUtil.UnMarshal(TPerson, sJson)); try CheckNotNull(vPerson); CheckEquals('Helbert', vPerson.name); CheckEquals(30, vPerson.age); CheckNotNull(vPerson.father); CheckEquals('Luiz', vPerson.father.name); CheckEquals(60, vPerson.father.age); CheckEquals(2, Length(vPerson.phones)); CheckEquals(33083518, vPerson.phones[0].number); CheckEquals(61, vPerson.phones[0].code); CheckEquals(99744165, vPerson.phones[1].number); CheckEquals(61, vPerson.phones[1].code); finally vPerson.Free; end; end; procedure TTestDesserializer.person; const sJson = '{' + ' "name": "Helbert",' + ' "age": 30' + '}'; var vPerson: TPerson; begin vPerson := TPerson(TJsonUtil.UnMarshal(TPerson, sJson)); try CheckNotNull(vPerson); CheckEquals('Helbert', vPerson.name); CheckEquals(30, vPerson.age); finally vPerson.Free; end; end; { TTestSerializer } procedure TTestSerializer.person; const sJson = '{"age":30,"name":"Helbert"}'; var vPerson: TPerson; begin vPerson := TPerson.Create; try vPerson.name := 'Helbert'; vPerson.age := 30; CheckEquals(sJson, TJsonUtil.Marshal(vPerson)); finally vPerson.Free; end; end; { TPerson } destructor TPerson.Destroy; var phone: TPhone; begin if Assigned(_phones) then for phone in _phones do phone.Free; SetLength(_phones, 0); father.Free; inherited; end; function TPerson.ToString: string; begin Result := 'name:' + name + ' age:' + IntToStr(age); end; initialization TTestDesserializer.RegisterTest; TTestSerializer.RegisterTest; end.
unit NetReaderKiCad; interface uses NetReader; // Low level access to KiCad or EESchem or PcbNew Netlist files. type TKicadNetReader = class( TveNetReader ) protected CurrentDesignator : string; HaveComponent : boolean; function GetNetlistDescriptor : string; override; function FindComponentStart : boolean; procedure FindComponentEnd; function ToNextPinToNetRecord : boolean; procedure ParsePinToNetRecord( var Netname : string; var Pin : integer ); public function CheckCompatibility : boolean; override; procedure ToFirstComponent; override; function GetNextComponent( var Designator, Value, Outline : string ) : boolean; override; procedure ToFirstConnection; override; function GetNextConnection( var NetName, Designator : string; var Pin : integer ) : boolean; override; // constructor Create; virtual; // destructor Destroy; override; end; implementation uses SysUtils; procedure ParseComponentFirstLine( LineIndex : integer; const Line : string; var Designator, Value, Outline : string ); var found : boolean; i : integer; Limit : integer; OutlineRaw : string; // parse next token from line - space is separator function GetNextText : string; begin // skip leading spaces while (i <= Limit) and (Line[i] = ' ') do begin Inc( i ); end; // if come to end of line, then error if i > Limit then begin raise ETveNetReader.CreateFmt( 'Not enough fields in Component opening on line %d', [LineIndex + 1] ); end; // copy characters until next space or line end while (i <= Limit) and (Line[i] <> ' ') do begin result := result + Line[i]; inc( i ); end; end; begin // setup line info i := 1; Limit := length( Line ); // skip leading '(' found := False; while i <= Limit do begin if Line[i] = '(' then begin inc( i ); found := True; break; end; inc( i ); end; if not Found then begin raise ETveNetReader.CreateFmt( 'Missing "(" in Component start on line %d', [LineIndex + 1] ); end; // skip next 2 items GetNextText; GetNextText; // get designator Designator := GetNextText; // get value Value := GetNextText; // get outline OutlineRaw := GetNextText; //.. must start with '{Lib=' if not (Copy( OutlineRaw, 1, 5 ) = '{Lib=') then begin raise ETveNetReader.CreateFmt( 'Missing "{Lib=" on line %d', [LineIndex + 1] ); end; //.. must end with '}' if OutlineRaw[Length(OutlineRaw)] <> '}' then begin raise ETveNetReader.CreateFmt( '"{Lib=" requires closing "}" on line %d', [LineIndex + 1] ); end; //.. extract outline name Outline := Copy( OutlineRaw, 6, Length(OutlineRaw) - 6 ); end; function TKicadNetReader.GetNetlistDescriptor : string; begin result := 'Kicad'; end; function TKicadNetReader.CheckCompatibility : boolean; begin result := True; end; procedure TKicadNetReader.ToFirstComponent; begin // skip any leading blank or comment lines, with '#' as first character LineIndex := 0; while LineIndex < LineLimit do begin Line := Lines[LineIndex]; if (Line = '') or (Line[1] = '#') then begin Inc( LineIndex ); continue; end; break; end; // skip '(' which opens the components section if Trim( Line[1] ) = '(' then begin Inc( LineIndex ); end else begin raise ETveNetReader.Create( 'Opening "(" character not found' ); end; if LineIndex >= LineLimit then begin raise ETveNetReader.Create( 'Not enough lines in file' ); end; end; // Move LineIndex to line which contains the next component record opening '(' // Returns True if component found, False if not found. function TKicadNetReader.FindComponentStart : boolean; var Input : string; begin result := False; // search for next component while LineIndex < LineLimit do begin Line := Lines[LineIndex]; Input := Trim( Line ); // end of component section is a closing ')' if Input = ')' then begin result := False; break; end; // component located if (Input <> '') and (Input[1] = '(') then begin result := True; exit; end; Inc( LineIndex ); end; end; // Move LineIndex to line which contains the component record closing ')' // Assumes LineIndex is at or beyond the start of a component record. procedure TKicadNetReader.FindComponentEnd; var Input : string; begin // go to end of this component while LineIndex < LineLimit do begin Line := Lines[LineIndex]; Input := Trim( Line ); // skip blank line if Input = '' then begin Inc( LineIndex ); continue end; // skip pin definition lines //..these must have at least 7 chars, e.g. "( 1 N )" if (Length( Input ) >= 7) and (Input[1] = '(') and (Input[Length(Input)] = ')') then begin Inc( LineIndex ); continue; end; // must be and end of component line if Input = ')' then begin Inc( LineIndex ); break; end; // if we are still executing, we have an error raise ETveNetReader.Create( Format( 'End of component character ")" expected on line %d', [LineIndex] ) ); end; end; function TKicadNetReader.GetNextComponent( var Designator, Value, Outline : string ) : boolean; begin // find next component record result := FindComponentStart; if not result then begin exit; end; // LoadComponent info from start of the record ParseComponentFirstLine( LineIndex, Line, Designator, Value, Outline ); Inc( LineIndex ); // go to end of this component record FindComponentEnd; end; procedure TKicadNetReader.ToFirstConnection; begin ToFirstComponent; HaveComponent := False; end; // Call this inside a component record, to move to the next Pin To Net line // of form " ( 1 +5V )" function TKicadNetReader.ToNextPinToNetRecord : boolean; var Input : string; begin // find next non-blank line while LineIndex < LineLimit do begin Line := Lines[LineIndex]; Input := Trim( Line ); if Input <> '' then begin break; end; Inc( LineIndex ); end; // pin to net assignment line if Input[1] = '(' then begin result := True; exit; end; // end of component line if Input[1] = ')' then begin result := False; exit; end; // invalid line raise ETveNetReader.Create( Format( '"(" or ")" expected at start line %d', [LineIndex] ) ); end; // Extract Pin and Net from a PinToNet record which is in variable Line // Line will be of form " ( 1 +5V )" procedure TKicadNetReader.ParsePinToNetRecord( var Netname : string; var Pin : integer ); var i : integer; Limit : integer; Found : boolean; PinStr : string; begin // initialise i := 1; Limit := Length(Line); // skip leading spaces until '(' while i <= Limit do begin if Line[i] = ' ' then begin Inc( i ); continue; end; if Line[i] = '(' then begin Inc( i ); break; end; // to get here is error raise ETveNetReader.Create( Format( '"(" expected at start line %d', [LineIndex] ) ); end; // skip spaces while (i <= Limit) and (Line[i] = ' ') do begin inc( i ); end; // next field is number of pin while (i <= Limit) and (Line[i] <> ' ') do begin PinStr := PinStr + Line[i]; inc( i ); end; try Pin := StrToInt( PinStr ); except raise ETveNetReader.Create( Format( 'Invalid pin number on line %d', [LineIndex] ) ); end; // skip spaces while (i <= Limit) and (Line[i] = ' ') do begin inc( i ); end; // next field is net name NetName := ''; while (i <= Limit) and (Line[i] <> ' ') do begin NetName := NetName + Line[i]; inc( i ); end; end; function TKicadNetReader.GetNextConnection( var NetName, Designator : string; var Pin : integer ) : boolean; var Value : string; Outline : string; begin result := False; exit; // do until we find a pin to net assignment or run out of components while LineIndex < LineLimit do begin // must be inside a component if not HaveComponent then begin result := FindComponentStart; // no more components if not result then begin exit; end; // setup for this new component HaveComponent := True; ParseComponentFirstLine( LineIndex, Line, CurrentDesignator, Value, Outline ); Inc( LineIndex ); end; // go to next Pin To Net record inside component record if ToNextPinToNetRecord then begin; ParsePinToNetRecord( Netname, Pin ); Inc( LineIndex ); // if pin has genuine net name if NetName <> '?' then begin Designator := CurrentDesignator; result := True; exit; end; end else begin // try again for next component HaveComponent := False; Inc( LineIndex ); end; end; // we should not get here raise ETveNetReader.Create( '")" expected before end of data' ); end; end. Component definitions contain the pin to net assignments ( IGNORE, OUTLINE, DESIGNATOR, VALUE, OUTLINE ( PIN_NO NET ) ( PIN_NO NET ) ) ( 33A51A4E $noname R4 10K {Lib=R} ( 1 N-000112 ) ( 2 +5V ) ) Note : ORCAD PCB2 format is very similar : ( 00000157 SO-8 U26 TLC393 ( 1 NetR132_1 ) ( 2 NetR128_1 ) ( 3 NetR130_1 ) ( 4 GND_2 ) ( 5 NetR128_1 ) ( 6 NetU26_6 ) ( 7 NetU26_7 ) ( 8 VBAT_1 ) )
program simpletask; {$IFNDEF HASAMIGA} {$FATAL This source is compatible with Amiga, AROS and MorphOS only !} {$ENDIF} { Project : simpletask Source : RKRM } { Uses the amiga.lib function CreateTask() to create a simple subtask. See the Includes and Autodocs manual for CreateTask() source code } {$MODE OBJFPC}{$H+}{$HINTS ON} {$UNITPATH ../../../Base/CHelpers} {$UNITPATH ../../../Base/Trinity} {$IFDEF AMIGA} {$UNITPATH ../../../Sys/Amiga} {$ENDIF} {$IFDEF AROS} {$UNITPATH ../../../Sys/AROS} {$ENDIF} {$IFDEF MORPHOS} {$UNITPATH ../../../Sys/MorphOS} {$ENDIF} Uses Exec, AmigaDOS, AmigaLib, SysUtils; const STACK_SIZE = 1000; var //* Task name, pointers for allocated task struct and stack */ task : PTask = nil; simpletaskname : PChar = 'SimpleTask'; sharedvar : ULONG; //* our function prototypes */ procedure simpletasker; forward; procedure cleanexit(s: PChar; e: LONG); forward; Procedure Main(argc: Integer; argv: PPChar); begin sharedvar := 0; task := CreateTask(simpletaskname, 0, @simpletasker, STACK_SIZE); if not assigned(task) then cleanexit('Can''t create task', RETURN_FAIL); WriteLn('This program initialized a variable to zero, then started a'); WriteLn('separate task which is incrementing that variable right now,'); WriteLn('while this program waits for you to press RETURN.'); Write('Press RETURN now: '); ReadLn; WriteLn(Format('The shared variable now equals %d', [sharedvar])); //* We can simply remove the task we added because our simpletask does not make */ //* any system calls which could cause it to be awakened or signalled later. */ Forbid(); DeleteTask(task); Permit(); cleanexit('', RETURN_OK); end; procedure simpletasker; begin while (sharedvar < $8000000) do inc(sharedvar); //* Wait forever because main() is going to RemTask() us */ Wait(0); end; procedure cleanexit(s: PChar; e: LONG); begin if (s^ <> #0) then WriteLn(s); Halt(e); end; begin Main(ArgC, ArgV); end.
{***********************************************************} { Exemplo de lanšamento de nota fiscal orientado a objetos, } { com banco de dados Oracle } { Reinaldo Silveira - reinaldopsilveira@gmail.com } { Franca/SP - set/2019 } {***********************************************************} unit U_BaseControl; interface uses System.Classes, Data.SqlExpr, System.SysUtils; type TBaseControl = class(TComponent) private { private declarations } FQuery: TSQLQuery; function GetQuery: TSQLQuery; protected { protected declarations } public { public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Query: TSQLQuery read GetQuery; function GetID(pSeqName: String): Integer; function FloatToSQL(pValue: Double): String; end; implementation { TBaseControl } uses U_Conexao; constructor TBaseControl.Create(AOwner: TComponent); begin inherited Create(AOwner); FQuery := TSQLQuery.Create(Self); FQuery.SQLConnection := TConexao.GetInstance.Conexao; end; destructor TBaseControl.Destroy; begin FQuery.Free; inherited; end; function TBaseControl.FloatToSQL(pValue: Double): String; begin Result := StringReplace(FloatToStr(pValue), FormatSettings.DecimalSeparator, '.', []); end; function TBaseControl.GetID(pSeqName: String): Integer; begin try Query.Close; Query.SQL.Text := Format('select %s.NEXTVAL from DUAL', [pSeqName]); Query.Open; Result := Query.Fields[0].AsInteger; except on E: Exception do raise Exception.CreateFmt('Erro ao obter o sequencial: %s', [E.message]); end; end; function TBaseControl.GetQuery: TSQLQuery; begin Result := FQuery; end; end.
(*----------------------------------------------------------*) (* Übung 4 ; Beispiel 1 Zahlen Mit Basis *) (* Entwickler: Neuhold Michael *) (* Datum: 31.10.2018 *) (* Lösungsidee: Umwandlung von beliebigen Zahlensystem nach *) (* Dezimal und umgekehrt; *) (* Rechnen mit verschiedenen Zahlensystemen *) (* Rückgabewert in Dezimal *) (*----------------------------------------------------------*) PROGRAM ZahlenMitBasis; uses Math; CONST sZahl = 48; sABC = 65; (* Trennzeile für verschönerte Terminalausgabe; wiederholte Verwendung, übersichtlicher *) PROCEDURE TrennZeichen; BEGIN WriteLn('----------------------------------------------------'); END; (* Welcome Text - Menü - Wird zwar nur einmal benötigt, aber um den Main Teil sauber zuhalten ausgelagert*) FUNCTION Welcome: INTEGER; VAR a : INTEGER; BEGIN TrennZeichen; WriteLn('| Zahlen mit Basis |'); TrennZeichen; WriteLn('| 1. Von beliebigen Zahlensystem ins Dezimale |'); WriteLn('| 2. Vom dezimalen Zahlensystem in ein beliebiges |'); WriteLn('| 3. SUM |'); WriteLn('| 4. DIFF |'); WriteLn('| 5. PROD |'); WriteLn('| 6. QUOT |'); TrennZeichen; Write('Auswahl: '); ReadLn(a); TrennZeichen; Welcome := a; END; (* Bekommt Zeichenkette und liefert den dazugehörigen Dezimalwert *) FUNCTION ValueOf(digits: STRING; base: INTEGER): INTEGER; VAR i, value, oDig, len: INTEGER; err: BOOLEAN; BEGIN i := 1; value := 0; err := FALSE; len := length(digits); IF (base > 10) AND (base <= 35) THEN BEGIN repeat oDig := Ord(digits[i]); IF (oDig >= sZahl) AND (oDig <= (sZahl+base-1)) THEN value := value + ((oDig-sZahl)*(base**(len-i))) ELSE IF (oDig >= sABC) AND (oDig < (sABC+(base-10))) THEN value := value + ((10+(oDig-sABC))*(base**(len-i))) ELSE err := TRUE; i := i + 1; until (err = TRUE) OR (i > len); IF err = FALSE THEN ValueOf := value ELSE ValueOf := -1; END ELSE IF base <= 10 THEN BEGIN repeat (* Error Handling *) oDig := Ord(digits[i]); IF (oDig >= sZahl) AND (oDig <= (sZahl+base-1)) THEN (* -1 steht für den Abzug der 0 *) value := value + ((oDig-sZahl)*(base**(len-i))) ELSE err := TRUE; i := i + 1; until (err = TRUE) OR (i > len); IF err = FALSE THEN ValueOf := value ELSE ValueOf := -1; END ELSE ValueOf := -1; END; (* Bekommt Dezimalwert und liefert diesen Wert in einem bestimmten Zahlensystem *) FUNCTION DigitsOf(value: INTEGER; base: INTEGER): STRING; VAR zeichenkette: STRING; rest: INTEGER; BEGIN zeichenkette := ''; IF (value >= 0) AND (base <= 36) THEN BEGIN repeat rest := value MOD base; IF rest > 9 THEN zeichenkette := Chr(sABC+(rest-10)) + zeichenkette ELSE zeichenkette := Chr(sZahl+rest) + zeichenkette; value := value DIV base; until (value = 0); DigitsOf := zeichenkette; END ELSE DigitsOf := 'ERROR'; END; (* Folgend die Rechenoperationen mit Hilfe der ValueOf Funktion *) (* Addition *) FUNCTION CalcAdd(d1, d2: String; b1, b2: INTEGER):INTEGER; BEGIN CalcAdd := ValueOf(d1,b1) + ValueOf(d2,b2); END; (* Subtraktion *) FUNCTION CalcSub(d1, d2: String; b1, b2: INTEGER):INTEGER; BEGIN CalcSub := ValueOf(d1,b1) - ValueOf(d2,b2); END; (* Multiplikation *) FUNCTION CalcProd(d1, d2: String; b1, b2: INTEGER):INTEGER; BEGIN CalcProd := ValueOf(d1,b1) * ValueOf(d2,b2); END; (* Division *) FUNCTION CalcQuot(d1, d2: String; b1, b2: INTEGER):INTEGER; BEGIN CalcQuot := ValueOf(d1,b1) DIV ValueOf(d2,b2); END; (* Wiederholte Eingabe Aufforderung - deswegen Prozedure *) PROCEDURE CalcIO(VAR zfCalc1, zfCalc2 : STRING; VAR bCalc1, bCalc2 : INTEGER); BEGIN Write('Zeichenfolge: '); ReadLn(zfCalc1); Write('Basis: '); ReadLn(bCalc1); Write('Zeichenfolge: '); ReadLn(zfCalc2); Write('Basis: '); ReadLn(bCalc2); END; (* Main *) VAR ziffernfolge : INTEGER; basis, bCalc1, bCalc2, auswahl: INTEGER; zeichenfolge, zfCalc1, zfCalc2 : STRING; BEGIN auswahl := Welcome; (* Welcome ist eine Funktion ohne Parameterübergabe; nur mit einem Return-Wert *) IF auswahl = 1 THEN BEGIN Write('Zeichenfolge: '); ReadLn(zeichenfolge); Write('Basis: '); ReadLn(basis); WriteLn('Ausgabe in Dezimal: ', ValueOf(zeichenfolge,basis)); TrennZeichen; (* Ebenfalls eine Funktion ohne Parameterübergabe *) END ELSE IF auswahl = 2 THEN BEGIN Write('Zahlenfolge: '); ReadLn(ziffernfolge); Write('Basis: '); ReadLn(basis); WriteLn('Ausgabe in angegebener Basis: ',DigitsOf(ziffernfolge,basis)); TrennZeichen; END ELSE IF auswahl = 3 THEN BEGIN CalcIO(zfCalc1,zfCalc2,bCalc1,bCalc2); WriteLn('Ergebnis der Addition: ', CalcAdd(zfCalc1,zfCalc2,bCalc1,bCalc2)); TrennZeichen; END ELSE IF auswahl = 4 THEN BEGIN CalcIO(zfCalc1,zfCalc2,bCalc1,bCalc2); WriteLn('Ergebnis der Subtraktion: ', CalcSub(zfCalc1,zfCalc2,bCalc1,bCalc2)); TrennZeichen; END ELSE IF auswahl = 5 THEN BEGIN CalcIO(zfCalc1,zfCalc2,bCalc1,bCalc2); WriteLn('Ergebnis der Multiplikation: ', CalcProd(zfCalc1,zfCalc2,bCalc1,bCalc2)); TrennZeichen; END ELSE IF auswahl = 6 THEN BEGIN CalcIO(zfCalc1,zfCalc2,bCalc1,bCalc2); WriteLn('Ergebnis der Division: ', CalcQuot(zfCalc1,zfCalc2,bCalc1,bCalc2)); TrennZeichen; END; END.
unit OmniXML_IniHash; interface {$I OmniXML.inc} {$IFDEF OmniXML_DXE4_UP} {$ZEROBASEDSTRINGS OFF} {$ENDIF} uses Classes, SysUtils; type PPHashItem = ^PHashItem; PHashItem = ^THashItem; THashItem = record Next: PHashItem; Key: string; Value: Integer; end; TStringHash = class private Buckets: array of PHashItem; protected function Find(const Key: string): PPHashItem; function HashOf(const Key: string): Cardinal; virtual; public constructor Create(Size: Cardinal = 256); destructor Destroy; override; procedure Add(const Key: string; Value: Integer); procedure Clear; procedure Remove(const Key: string); function Modify(const Key: string; Value: Integer): Boolean; function ValueOf(const Key: string): Integer; end; implementation { TStringHash } procedure TStringHash.Add(const Key: string; Value: Integer); var Hash: Integer; Bucket: PHashItem; begin Hash := HashOf(Key) mod Cardinal(Length(Buckets)); New(Bucket); Bucket^.Key := Key; Bucket^.Value := Value; Bucket^.Next := Buckets[Hash]; Buckets[Hash] := Bucket; end; procedure TStringHash.Clear; var I: Integer; P, N: PHashItem; begin for I := 0 to Length(Buckets) - 1 do begin P := Buckets[I]; while P <> nil do begin N := P^.Next; Dispose(P); P := N; end; Buckets[I] := nil; end; end; constructor TStringHash.Create(Size: Cardinal); begin inherited Create; SetLength(Buckets, Size); end; destructor TStringHash.Destroy; begin Clear; inherited Destroy; end; function TStringHash.Find(const Key: string): PPHashItem; var Hash: Integer; begin Hash := HashOf(Key) mod Cardinal(Length(Buckets)); Result := @Buckets[Hash]; while Result^ <> nil do begin if (Result^)^.Key = Key then Exit else Result := @Result^^.Next; end; end; function TStringHash.HashOf(const Key: string): Cardinal; var I: Integer; begin Result := 0; for I := 1 to Length(Key) do Result := ((Result shl 2) or (Result shr (SizeOf(Result) * 8 - 2))) xor Ord(Key[I]); end; function TStringHash.Modify(const Key: string; Value: Integer): Boolean; var P: PHashItem; begin P := Find(Key)^; if P <> nil then begin Result := True; P^.Value := Value; end else Result := False; end; procedure TStringHash.Remove(const Key: string); var P: PHashItem; Prev: PPHashItem; begin Prev := Find(Key); P := Prev^; if P <> nil then begin Prev^ := P^.Next; Dispose(P); end; end; function TStringHash.ValueOf(const Key: string): Integer; var P: PHashItem; begin P := Find(Key)^; if P <> nil then Result := P^.Value else Result := -1; end; end.
unit UnitTable.Model; interface uses System.Generics.Collections, UnitMigration4D.Interfaces; type TTable = class(TInterfacedObject, iTable, iCollumn) private FCollumns: TDictionary<String, String>; FNameTable: string; public constructor Create; destructor Destroy; override; class function New: iTable; function SetName(Value: string): iTable; function AddCollumn(Name: string; atype: string): iCollumn; function &End: iTable; function Name: string; function GetColumns: TDictionary<string, string>; function Fields: iCollumn; end; implementation { TTable } function TTable.&End: iTable; begin Result := Self; end; function TTable.Fields: iCollumn; begin Result := Self; end; function TTable.GetColumns: TDictionary<string, string>; begin Result := FCollumns; end; constructor TTable.Create; begin FCollumns := TDictionary<String, String>.Create; end; destructor TTable.Destroy; begin FCollumns.DisposeOf; inherited; end; function TTable.Name: string; begin Result := FNameTable; end; class function TTable.New: iTable; begin Result := Self.Create; end; function TTable.AddCollumn(Name: string; atype: string): iCollumn; begin Result := Self; FCollumns.Add(Name, atype); end; function TTable.SetName(Value: string): iTable; begin Result := Self; FNameTable := Value; end; end.
unit uReqBuilder; { Sandcat Request Panel Copyright (c) 2011-2014, Syhunt Informatica License: 3-clause BSD license See https://github.com/felipedaragon/sandcat/ for details. } interface uses Classes, SysUtils, Windows, Graphics, StdCtrls, {$IF CompilerVersion >= 23} Vcl.Controls, Vcl.ExtCtrls, {$ELSE} Controls, ExtCtrls, {$IFEND} uUIComponents; type TSandRequestPanel = class(TCustomControl) private fLoaded: boolean; fToolbarPanel: TPanel; procedure HeadersEditEnter(Sender: TObject); procedure POSTEditEnter(Sender: TObject); procedure URLEditEnter(Sender: TObject); protected public AgentEdit: TEdit; HeadersEdit: TMemo; POSTDataEdit: TMemo; Prefs: TSandJSON; QuickPrefsPanel: TPanel; RefererEdit: TEdit; ToolbarBar: TSandUIEngine; URLEdit: TMemo; function GetHeaders: string; function GetPOSTData: string; function GetURL: string; procedure Load; procedure SetPOSTData(s: string); procedure SetUserAgent(s: string); procedure SetWordWrap(b: boolean); constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; implementation uses uMain, CatStrings, uMisc, uZones; function TSandRequestPanel.GetHeaders: string; const cRef = 'Referer:'; cAgent = 'User-Agent:'; var s: string; begin s := HeadersEdit.Text; if AgentEdit.Text <> emptystr then begin if pos(cAgent, s) = 0 then s := s + crlf + cAgent + ' ' + AgentEdit.Text; end; if RefererEdit.Text <> emptystr then begin if pos(cRef, s) = 0 then s := s + crlf + cRef + ' ' + RefererEdit.Text; end; result := s; end; procedure TSandRequestPanel.SetPOSTData(s: string); begin POSTDataEdit.Text := s; POSTDataEdit.Visible := true; ToolbarBar.Eval('$(#viewreqdata).checked = true;'); end; procedure TSandRequestPanel.SetUserAgent(s: string); begin AgentEdit.Text := s; QuickPrefsPanel.Visible := true; ToolbarBar.Eval('$(#viewprefs).checked = true;'); end; function TSandRequestPanel.GetURL: string; begin result := URLEdit.Text; result := replacestr(result, crlf, emptystr); end; function TSandRequestPanel.GetPOSTData: string; begin result := POSTDataEdit.Text; result := replacestr(result, crlf, emptystr); end; procedure TSandRequestPanel.SetWordWrap(b: boolean); begin URLEdit.WordWrap := b; POSTDataEdit.WordWrap := b; end; procedure TSandRequestPanel.Load; begin if URLEdit.Text = emptystr then URLEdit.Text := tabmanager.ActiveTab.GetURL; if fLoaded then exit; fLoaded := true; ToolbarBar.LoadHTML(uix.Pages.reqbuilderbar, pluginsdir); if uix.TIS.ReqBuilderToolbar <> emptystr then ToolbarBar.Eval(uix.TIS.ReqBuilderToolbar + crlf + cUIXUpdate); URLEdit.SetFocus; uix.ActiveMemo := URLEdit; end; procedure TSandRequestPanel.URLEditEnter(Sender: TObject); begin uix.ActiveMemo := URLEdit; end; procedure TSandRequestPanel.POSTEditEnter(Sender: TObject); begin uix.ActiveMemo := POSTDataEdit; end; procedure TSandRequestPanel.HeadersEditEnter(Sender: TObject); begin uix.ActiveMemo := HeadersEdit; end; constructor TSandRequestPanel.Create(AOwner: TComponent); procedure SetMemoDefaults(m: TMemo; a: TAlign; texthint: string = ''); begin m.Parent := self; m.Align := a; m.ReadOnly := false; m.HideSelection := false; m.ScrollBars := ssBoth; m.texthint := texthint; end; begin inherited Create(AOwner); ControlStyle := ControlStyle + [csAcceptsControls]; fLoaded := false; Prefs := TSandJSON.Create; Prefs['usecookies'] := true; Prefs['usecredentials'] := true; Prefs['ignorecache'] := true; fToolbarPanel := TPanel.Create(self); fToolbarPanel.Align := altop; fToolbarPanel.ParentBackground := true; fToolbarPanel.ParentBackground := false; fToolbarPanel.Parent := self; fToolbarPanel.Height := 35; fToolbarPanel.BevelInner := bvNone; fToolbarPanel.BevelOuter := bvNone; ToolbarBar := TSandUIEngine.Create(fToolbarPanel); ToolbarBar.Parent := fToolbarPanel; ToolbarBar.Align := alclient; // URLEdit URLEdit := TMemo.Create(self); SetMemoDefaults(URLEdit, alclient, 'http://'); URLEdit.OnEnter := URLEditEnter; // POSTDataEdit POSTDataEdit := TMemo.Create(self); SetMemoDefaults(POSTDataEdit, AlBottom, 'POST Data'); POSTDataEdit.OnEnter := POSTEditEnter; POSTDataEdit.Visible := false; // HeadersEdit HeadersEdit := TMemo.Create(self); SetMemoDefaults(HeadersEdit, AlRight, 'Headers'); HeadersEdit.OnEnter := HeadersEditEnter; HeadersEdit.Visible := false; HeadersEdit.Width := 400; // QuickPrefsPanel QuickPrefsPanel := TPanel.Create(self); QuickPrefsPanel.Parent := self; QuickPrefsPanel.Align := AlBottom; QuickPrefsPanel.Visible := false; QuickPrefsPanel.Height := 44; QuickPrefsPanel.ParentBackground := true; // vcl fix QuickPrefsPanel.ParentBackground := false; // vcl fix // RefererEdit RefererEdit := TEdit.Create(self); RefererEdit.Parent := QuickPrefsPanel; RefererEdit.Align := altop; RefererEdit.texthint := 'Referer'; // AgentEdit AgentEdit := TEdit.Create(self); AgentEdit.Parent := QuickPrefsPanel; AgentEdit.Align := alclient; AgentEdit.texthint := 'User-Agent'; end; destructor TSandRequestPanel.Destroy; begin SetWordWrap(false); // weird vcl crash workaround HeadersEdit.Free; RefererEdit.Free; AgentEdit.Free; URLEdit.Free; POSTDataEdit.Free; ToolbarBar.Free; fToolbarPanel.Free; QuickPrefsPanel.Free; Prefs.Free; inherited Destroy; end; end.
unit Database.Model; interface uses System.Classes, System.SysUtils, Data.DB, Data.SqlExpr, Common.Types, Connection.Model, Database.Types, Database.Datamodule; type TDatabaseModel = class private class var FSQLConnection: TSQLConnection; public class function NewInstance: TObject; override; class function GetInstance: TDatabaseModel; class function GetCounter: Integer; class property SQLConnection: TSQLConnection read FSQLConnection; // constructor Create; procedure FreeInstance; override; function ExecSQLCmd(const ASQLCmd: string; AParams: TParams): TFunctionResult; function GetSequenceNextValue(ASequenceName: string): Integer; function GetDataset(const ASQLCmd: string; AParams: TParams = nil): TDataSet; function GetSQLResult(const ASQLCmd: string; AParams: TParams = nil; ADefaultValue: string = ''): string; overload; function GetSQLResult(const ASQLCmd: string; AParams: TParams = nil; ADefaultValue: Integer = 0): Integer; overload; end; implementation var AnInstance: TObject = nil; ACounter: Integer = 0; IsFinalized: Boolean = False; { TDatabaseModel } //constructor TDatabaseModel.Create; //begin // if AnInstance = nil then // begin // inherited Create; // FSQLConnection := TConnectionModel.SQLConnection; // end; //end; function TDatabaseModel.ExecSQLCmd(const ASQLCmd: string; AParams: TParams): TFunctionResult; begin Result.Successful := False; try TConnectionModel.SQLConnection.Execute(ASQLCmd, AParams); Result.Successful := True; except on e: Exception do begin Result.MessageOnError := e.Message; end; end; end; procedure TDatabaseModel.FreeInstance; begin Dec(ACounter); if IsFinalized then inherited FreeInstance; end; class function TDatabaseModel.GetCounter: Integer; begin Result := ACounter; end; function TDatabaseModel.GetDataset(const ASQLCmd: string; AParams: TParams): TDataSet; begin try FSQLConnection.Execute(ASQLCmd, AParams, Result); except on e: Exception do Result := nil; end; end; class function TDatabaseModel.GetInstance: TDatabaseModel; begin Result := TDatabaseModel.Create; end; function TDatabaseModel.GetSequenceNextValue(ASequenceName: string): Integer; begin Result := GetSQLResult('select next value for ' + ASequenceName + ' from RDB$DATABASE', nil, 0); end; function TDatabaseModel.GetSQLResult(const ASQLCmd: string; AParams: TParams; ADefaultValue: string): string; var ds: TDataSet; begin ds := GetDataset(ASQLCmd, AParams); if Assigned(ds) then begin Result := ds.Fields[0].AsString; end else begin Result := ADefaultValue; end; end; function TDatabaseModel.GetSQLResult(const ASQLCmd: string; AParams: TParams; ADefaultValue: Integer): Integer; var ds: TDataSet; begin ds := GetDataset(ASQLCmd, AParams); if Assigned(ds) then begin Result := ds.Fields[0].AsInteger; end else begin Result := ADefaultValue; end; end; class function TDatabaseModel.NewInstance: TObject; begin Inc(ACounter); if AnInstance = nil then begin AnInstance := inherited NewInstance; FSQLConnection := TConnectionModel.SQLConnection; dmDatabase := TdmDatabase.Create(nil); end; Result := AnInstance; end; initialization TDatabaseModel.Create; finalization IsFinalized := True; AnInstance.Free; end.
unit AqDrop.Core.Observers; interface uses System.Classes, System.Generics.Collections, System.SysUtils, AqDrop.Core.Types, AqDrop.Core.InterfacedObject, AqDrop.Core.Observers.Intf, AqDrop.Core.Collections.Intf; type TAqNotifyEvent<T> = procedure(pMessage: T) of object; TAqObservationChannel<T> = class(TAqARCObject, IAqCustomObservable<T>, IAqObservable<T>) strict private FObservers: IAqIDDictionary<IAqObserver<T>>; public constructor Create(const pCreateLocker: Boolean = False); procedure Notify(pMessage: T); function RegisterObserver(pObserver: IAqObserver<T>): TAqID; overload; function RegisterObserver(pMethod: TProc<T>): TAqID; overload; function RegisterObserver(pEvent: TAqGenericEvent<T>): TAqID; overload; procedure UnregisterObserver(const pObserverID: TAqID); end; TAqObservable<T> = class(TAqObservationChannel<T>); TAqObserver<T> = class(TAqARCObject, IAqObserver<T>) public procedure Observe(const pMessage: T); virtual; abstract; end; TAqObserverByMethod<T> = class(TAqObserver<T>) strict private FObserverMethod: TProc<T>; public constructor Create(const pMethod: TProc<T>); procedure Observe(const pMessage: T); override; end; TAqObserverByEvent<T> = class(TAqObserver<T>) strict private FObserverEvent: TAqNotifyEvent<T>; public constructor Create(const pEvent: TAqNotifyEvent<T>); procedure Observe(const pMessage: T); override; end; TAqObservablesChain<T> = class(TAqARCObject, IAqObservablesChain<T>) strict private [weak] FParent: TAqObservablesChain<T>; FChildren: IAqList<TAqObservablesChain<T>>; FObservationChannel: IAqObservable<T>; function ElectNewKeyNode: TAqObservablesChain<T>; procedure ReleaseChild(const pChild: TAqObservablesChain<T>; const pNewKeyNode: TAqObservablesChain<T>); function GetObservationChannel: IAqObservable<T>; strict protected procedure DoNotifyObservers(pMessage: T); public constructor Create; destructor Destroy; override; function Share: IAqObservablesChain<T>; procedure Unchain; procedure Notify(pMessage: T); property ObservationChannel: IAqObservable<T> read GetObservationChannel; end; resourcestring StrItWasNotPossibleToRemoveTheObserverFromTheChannelObserverNotFound = 'It was not possible to remove the observer from the channel (observer not found).'; implementation uses AqDrop.Core.Exceptions, AqDrop.Core.Collections; { TAqObserverByMethod<T> } constructor TAqObserverByMethod<T>.Create(const pMethod: TProc<T>); begin inherited Create; FObserverMethod := pMethod; end; procedure TAqObserverByMethod<T>.Observe(const pMessage: T); begin FObserverMethod(pMessage); end; { TAqObserverByEvent<T> } constructor TAqObserverByEvent<T>.Create(const pEvent: TAqNotifyEvent<T>); begin inherited Create; FObserverEvent := pEvent; end; procedure TAqObserverByEvent<T>.Observe(const pMessage: T); begin FObserverEvent(pMessage); end; { TAqObservationChannel<T> } function TAqObservationChannel<T>.RegisterObserver(pObserver: IAqObserver<T>): TAqID; begin if FObservers.HasLocker then begin FObservers.BeginWrite; end; try Result := FObservers.Add(pObserver); finally if FObservers.HasLocker then begin FObservers.EndWrite; end; end; end; constructor TAqObservationChannel<T>.Create(const pCreateLocker: Boolean = False); var lLockerType: TAqLockerType; begin inherited Create; if pCreateLocker then begin lLockerType := TAqLockerType.lktNone; end else begin lLockerType := TAqLockerType.lktMultiReaderExclusiveWriter; end; FObservers := TAqIDDictionary<IAqObserver<T>>.Create(False, lLockerType); end; procedure TAqObservationChannel<T>.UnregisterObserver(const pObserverID: TAqID); begin if not pObserverID.IsEmpty then begin if FObservers.HasLocker then begin FObservers.BeginWrite; end; try if not FObservers.ContainsKey(pObserverID) then begin raise EAqInternal.Create(StrItWasNotPossibleToRemoveTheObserverFromTheChannelObserverNotFound); end; FObservers.Remove(pObserverID); finally if FObservers.HasLocker then begin FObservers.EndWrite; end; end; end; end; procedure TAqObservationChannel<T>.Notify(pMessage: T); var lObserver: IAqObserver<T>; begin if FObservers.HasLocker then begin FObservers.BeginRead; end; try for lObserver in FObservers.Values do begin lObserver.Observe(pMessage); end; finally if FObservers.HasLocker then begin FObservers.EndRead; end; end; end; function TAqObservationChannel<T>.RegisterObserver(pEvent: TAqGenericEvent<T>): TAqID; begin Result := RegisterObserver(TAqObserverByEvent<T>.Create(pEvent)); end; function TAqObservationChannel<T>.RegisterObserver(pMethod: TProc<T>): TAqID; begin Result := RegisterObserver(TAqObserverByMethod<T>.Create(pMethod)); end; { TAqObservablesChain<T> } constructor TAqObservablesChain<T>.Create; begin FObservationChannel := TAqObservationChannel<T>.Create; FChildren := TAqList<TAqObservablesChain<T>>.Create; end; destructor TAqObservablesChain<T>.Destroy; begin Unchain; inherited; end; procedure TAqObservablesChain<T>.DoNotifyObservers(pMessage: T); var lChild: TAqObservablesChain<T>; begin FObservationChannel.Notify(pMessage); for lChild in FChildren do begin lChild.DoNotifyObservers(pMessage); end; end; function TAqObservablesChain<T>.ElectNewKeyNode: TAqObservablesChain<T>; var lChild: TAqObservablesChain<T>; begin if FChildren.Count > 0 then begin Result := FChildren.Extract; for lChild in FChildren do begin Result.FChildren.Add(lChild); end; Result.FParent := FParent; end else begin Result := nil; end; end; function TAqObservablesChain<T>.GetObservationChannel: IAqObservable<T>; begin Result := FObservationChannel; end; procedure TAqObservablesChain<T>.Notify(pMessage: T); var lChild: TAqObservablesChain<T>; begin if Assigned(FParent) then begin FParent.Notify(pMessage); end else begin DoNotifyObservers(pMessage); end; end; procedure TAqObservablesChain<T>.ReleaseChild(const pChild, pNewKeyNode: TAqObservablesChain<T>); begin FChildren.DeleteItem(pChild); if Assigned(pNewKeyNode) then begin FChildren.Add(pNewKeyNode); end; end; function TAqObservablesChain<T>.Share: IAqObservablesChain<T>; var lChild: TAqObservablesChain<T>; begin lChild := TAqObservablesChain<T>.Create; try lChild.FParent := Self; FChildren.Add(lChild); Result := lChild; except lChild.Free; raise; end; end; procedure TAqObservablesChain<T>.Unchain; var lNewKeyNode: TAqObservablesChain<T>; begin lNewKeyNode := ElectNewKeyNode; if Assigned(FParent) then begin FParent.ReleaseChild(Self, lNewKeyNode); end; FChildren.Clear; end; end.
(******************************************************************************* The MIT License (MIT) Copyright (c) 2011 by Sivv LLC, Copyright (c) 2007 by Arcana Technologies Incorporated Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Donations are appreciated if you find this code useful. Please visit http://arcana.sivv.com to donate *******************************************************************************) unit jsonUtils; interface uses SysUtils, Classes, Types, DB, json; function DatasetToJSON(Dataset : TDataset; RowStart : integer = 0; RowCount : integer = High(integer); PropertyName : string = 'data'; Compact : boolean = false; DateFormat : PJSONDateFormatter = nil; DataOnly : boolean = false) : String; overload; function DatasetToJSON(Dataset : TDataset; FieldList : array of String; RowStart : integer = 0; RowCount : integer = High(integer); PropertyName : string = 'data'; Compact : boolean = false; DateFormat : PJSONDateFormatter = nil; DataOnly : boolean = false) : String; overload; function DataRowToJSON(Dataset : TDataset; PropertyName : string = 'data'; Compact : boolean = false; DateFormat : PJSONDateFormatter = nil; DataOnly : boolean = false) : String; overload; function DataRowToJSON(Dataset : TDataset; FieldList : array of String; PropertyName : string = 'data'; Compact : boolean = false; DateFormat : PJSONDateFormatter = nil; DataOnly : boolean = false) : String; overload; const JSONContentType : string = 'applicaton/json'; implementation function DatasetToJSON(Dataset : TDataset; RowStart : integer = 0; RowCount : integer = High(integer); PropertyName : string = 'data'; Compact : boolean = false; DateFormat : PJSONDateFormatter = nil; DataOnly : boolean = false) : String; overload; begin Result := DatasetToJSON(Dataset, [], RowStart, RowCount, PropertyName, Compact, DateFormat, DataOnly); end; function DatasetToJSON(Dataset : TDataset; FieldList : array of String; RowStart : integer = 0; RowCount : integer = High(integer); PropertyName : string = 'data'; Compact : boolean = false; DateFormat : PJSONDateFormatter = nil; DataOnly : boolean = false) : String; overload; var x: Integer; i, iCnt : integer; s: string; sl : TStringList; sField: String; begin if DateFormat = nil then DateFormat := @JSONDates; Result := ''; sl := TStringList.Create; try if RowStart >= 0 then begin Dataset.First; if RowStart > 0 then Dataset.MoveBy(RowStart); end; iCnt := 0; sField := ''; while (not Dataset.EOF) and (iCnt < RowCount) do begin s := ''; for x := 0 to Dataset.FieldCount - 1 do begin if InArray(Dataset.Fields[x].FieldName,FieldList) then begin if x <> 0 then s := s+','; if not Compact then sField := '"'+EncodeJSONString(Dataset.Fields[x].FieldName)+'" : '; case Dataset.Fields[x].DataType of ftString, ftFmtMemo, ftFixedChar, ftWideString, ftFixedWideChar, ftWideMemo, ftGuid, ftMemo: s := s + sField +'"'+EncodeJSONString(Dataset.Fields[x].AsString)+'"'; ftSmallint, ftInteger, ftWord, ftFloat, ftCurrency, ftBCD, ftAutoInc, ftLargeint: s := s + sField +EncodeJSONString(Dataset.Fields[x].AsString); ftBoolean: s := s + sField +lowercase(BoolToStr(Dataset.Fields[x].AsBoolean,True)); ftDate: s := s + sField +DateFormat.DateToString(Dataset.Fields[x].AsDateTime,ddDate); ftTime: s := s + sField +DateFormat.DateToString(Dataset.Fields[x].AsDateTime,ddTime); ftTimeStamp, ftOraTimeStamp, ftDateTime: s := s + sField +DateFormat.DateToString(Dataset.Fields[x].AsDateTime,ddDateTime); {ftUnknown, ftBytes, ftVarBytes, ftBlob, ftGraphic, ftParadoxOle, ftDBaseOle, ftTypedBinary, ftCursor, ftADT, ftArray, ftReference, ftDataSet, ftOraBlob, ftOraClob, ftVariant, ftInterface, ftIDispatch, ftFMTBcd, ftOraInterval} end; end; end; if s = '' then break; sl.Add(s); Dataset.Next; inc(iCnt); end; if sl.Count = 0 then exit; if not DataOnly then Result := '{ "'+EncodeJSONString(PropertyName)+'" : ['; for i := 0 to sl.Count - 1 do begin if i <> 0 then Result := Result+','; if not Compact then Result := Result+'{'+sl[i]+'}' else Result := Result+'['+sl[i]+']'; end; if not DataOnly then Result := Result+']}'; finally sl.Free; end; end; function DataRowToJSON(Dataset : TDataset; PropertyName : string = 'data'; Compact : boolean = false; DateFormat : PJSONDateFormatter = nil; DataOnly : boolean = false) : String; overload; begin Result := DataRowToJSON(Dataset, [], PropertyName, Compact, DateFormat, DataOnly); end; function DataRowToJSON(Dataset : TDataset; FieldList : array of String; PropertyName : string = 'data'; Compact : boolean = false; DateFormat : PJSONDateFormatter = nil; DataOnly : boolean = false) : String; overload; begin Result := DatasetToJSON(Dataset,FieldList,-1,1, PropertyName, Compact, DateFormat, DataOnly); end; end.
unit Flyweight.Car; interface type TCar = class private FOwner: string; FModel: string; FCompany: string; FColor: string; FNumber: string; procedure SetColor(const Value: string); procedure SetCompany(const Value: string); procedure SetModel(const Value: string); procedure SetNumber(const Value: string); procedure SetOwner(const Value: string); public property Owner: string read FOwner write SetOwner; property Number: string read FNumber write SetNumber; property Company: string read FCompany write SetCompany; property Model: string read FModel write SetModel; property Color: string read FColor write SetColor; class function New(ACompany, AModel, AColor: string): TCar; overload; class function New(ANumber, AOwner, ACompany, AModel, AColor: string) : TCar; overload; end; implementation { TCar } class function TCar.New(ACompany, AModel, AColor: string): TCar; begin Result := Self.Create; Result.Company := ACompany; Result.Model := AModel; Result.Color := AColor; end; class function TCar.New(ANumber, AOwner, ACompany, AModel, AColor: string): TCar; begin Result := Self.Create; Result.Number := ANumber; Result.Owner := AOwner; Result.Company := ACompany; Result.Model := AModel; Result.Color := AColor; end; procedure TCar.SetColor(const Value: string); begin FColor := Value; end; procedure TCar.SetCompany(const Value: string); begin FCompany := Value; end; procedure TCar.SetModel(const Value: string); begin FModel := Value; end; procedure TCar.SetNumber(const Value: string); begin FNumber := Value; end; procedure TCar.SetOwner(const Value: string); begin FOwner := Value; end; end.
object EdPartsForm: TEdPartsForm Left = 274 Top = 90 HelpContext = 6 ActiveControl = DBEdit2 BorderIcons = [biSystemMenu, biMinimize] BorderStyle = bsSingle Caption = 'Edit Parts' ClientHeight = 380 ClientWidth = 422 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -16 Font.Name = 'Tahoma' Font.Style = [] OldCreateOrder = True Position = poScreenCenter OnCloseQuery = FormCloseQuery PixelsPerInch = 96 TextHeight = 19 object Panel1: TPanel Left = 0 Top = 0 Width = 422 Height = 53 Margins.Left = 2 Margins.Top = 2 Margins.Right = 2 Margins.Bottom = 2 Align = alTop BevelOuter = bvNone TabOrder = 0 object PrintBtn: TSpeedButton Left = 360 Top = 5 Width = 45 Height = 42 Hint = 'Print form image' Margins.Left = 2 Margins.Top = 2 Margins.Right = 2 Margins.Bottom = 2 Glyph.Data = { 2A010000424D2A010000000000007600000028000000130000000F0000000100 040000000000B400000000000000000000001000000000000000000000000000 8000008000000080800080000000800080008080000080808000C0C0C0000000 FF0000FF000000FFFF00FF000000FF00FF00FFFF0000FFFFFF00333333333333 3333333F0EFF3300000000000003333F00FF37877777777777703330000030F8 8888888888870333003330F9988888888887703F11EE37FFFFFFFFFFFFF77039 0910330888888888888F703865F03330870000000078F03765F03333000FFFFF F000033865F03333330F44448033333765F033333330FFFFFF03333865F03333 3330F4444803333765F0333333330FFFFFF0333865F033333333000000003336 66C0333333333333333333300000} OnClick = PrintBtnClick end object Bevel1: TBevel Left = 0 Top = 51 Width = 422 Height = 2 Margins.Left = 2 Margins.Top = 2 Margins.Right = 2 Margins.Bottom = 2 Align = alBottom Shape = bsTopLine ExplicitTop = 34 ExplicitWidth = 313 end object Navigator: TDBNavigator Left = 8 Top = 7 Width = 300 Height = 40 HelpContext = 6 Margins.Left = 2 Margins.Top = 2 Margins.Right = 2 Margins.Bottom = 2 DataSource = PartsSource1 ParentShowHint = False ShowHint = True TabOrder = 0 end end object Panel2: TPanel Left = 0 Top = 53 Width = 422 Height = 268 Margins.Left = 2 Margins.Top = 2 Margins.Right = 2 Margins.Bottom = 2 Align = alTop BevelOuter = bvNone TabOrder = 1 object Label1: TLabel Left = 8 Top = 11 Width = 48 Height = 19 Margins.Left = 2 Margins.Top = 2 Margins.Right = 2 Margins.Bottom = 2 Caption = 'PartNo' end object Label2: TLabel Left = 8 Top = 49 Width = 79 Height = 19 Margins.Left = 2 Margins.Top = 2 Margins.Right = 2 Margins.Bottom = 2 Caption = 'Description' end object Label3: TLabel Left = 8 Top = 92 Width = 51 Height = 19 Margins.Left = 2 Margins.Top = 2 Margins.Right = 2 Margins.Bottom = 2 Caption = 'Vendor' end object Label4: TLabel Left = 8 Top = 139 Width = 58 Height = 19 Margins.Left = 2 Margins.Top = 2 Margins.Right = 2 Margins.Bottom = 2 Caption = 'OnHand' end object Label5: TLabel Left = 223 Top = 139 Width = 62 Height = 19 Margins.Left = 2 Margins.Top = 2 Margins.Right = 2 Margins.Bottom = 2 Caption = 'OnOrder' end object Label7: TLabel Left = 8 Top = 227 Width = 31 Height = 19 Margins.Left = 2 Margins.Top = 2 Margins.Right = 2 Margins.Bottom = 2 Caption = 'Cost' end object Label8: TLabel Left = 239 Top = 227 Width = 58 Height = 19 Margins.Left = 2 Margins.Top = 2 Margins.Right = 2 Margins.Bottom = 2 Caption = 'ListPrice' end object DBEdit2: TDBEdit Left = 95 Top = 46 Width = 313 Height = 27 HelpContext = 6 Margins.Left = 2 Margins.Top = 2 Margins.Right = 2 Margins.Bottom = 2 DataField = 'Description' DataSource = PartsSource1 TabOrder = 1 end object DBEdit4: TDBEdit Left = 95 Top = 136 Width = 82 Height = 27 HelpContext = 6 Margins.Left = 2 Margins.Top = 2 Margins.Right = 2 Margins.Bottom = 2 DataField = 'OnHand' DataSource = PartsSource1 TabOrder = 3 end object DBEdit5: TDBEdit Left = 296 Top = 136 Width = 109 Height = 27 HelpContext = 6 Margins.Left = 2 Margins.Top = 2 Margins.Right = 2 Margins.Bottom = 2 DataField = 'OnOrder' DataSource = PartsSource1 TabOrder = 4 end object DBEdit7: TDBEdit Left = 63 Top = 224 Width = 102 Height = 27 HelpContext = 6 Margins.Left = 2 Margins.Top = 2 Margins.Right = 2 Margins.Bottom = 2 DataField = 'Cost' DataSource = PartsSource1 TabOrder = 6 end object DBEdit8: TDBEdit Left = 303 Top = 224 Width = 102 Height = 27 HelpContext = 6 Margins.Left = 2 Margins.Top = 2 Margins.Right = 2 Margins.Bottom = 2 DataField = 'ListPrice' DataSource = PartsSource1 TabOrder = 7 end object DBEdPartNo: TDBEdit Left = 80 Top = 6 Width = 102 Height = 27 HelpContext = 6 Margins.Left = 2 Margins.Top = 2 Margins.Right = 2 Margins.Bottom = 2 DataField = 'PartNo' DataSource = PartsSource1 TabOrder = 0 end object DataComboBox1: TDBLookupComboBox Left = 95 Top = 87 Width = 310 Height = 27 Margins.Left = 2 Margins.Top = 2 Margins.Right = 2 Margins.Bottom = 2 DataField = 'VendorNo' DataSource = PartsSource1 KeyField = 'VENDORNO' ListField = 'VENDORNAME' ListSource = MastData.VendorSource TabOrder = 2 end object DBCheckBox1: TDBCheckBox Left = 8 Top = 181 Width = 145 Height = 17 Caption = 'Backordered' DataField = 'BackOrd' DataSource = PartsSource1 TabOrder = 5 ValueChecked = 'Yes' ValueUnchecked = 'No' end end object BitBtn1: TBitBtn Left = 208 Top = 337 Width = 91 Height = 35 Kind = bkOK NumGlyphs = 2 TabOrder = 2 end object BitBtn2: TBitBtn Left = 314 Top = 337 Width = 91 Height = 35 Kind = bkCancel NumGlyphs = 2 TabOrder = 3 end object PartsSource1: TDataSource DataSet = MastData.cdsParts Left = 40 Top = 328 end end
unit uBootLoader; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fgl, Windows, Forms, uModbus; type TWriteEvent = procedure(const aSize, aCurrentPage: Word) of object; { IBootloader } IBootloader = interface ['{EBCE0859-39E7-453D-AA36-A5F12A53D7D7}'] procedure Flash; procedure StopFlash; function IsFlashing: Boolean; end; { TBootloader } TPages = specialize TFpgList<IFrame>; TThreadFlash = class; TBootloader = class(TInterfacedObject, IBootloader) protected // Адрес устройства fSlaveId: Byte; // Канал связи fController: IController; // Таймаут ответа устройства fTimeout: Dword; // Имя файла и файловый поток fFileName: String; fStream: TFileStream; // Контейнер страниц из файлового потока fPages: TPages; // Поток прошивки fThreadFlash: TThreadFlash; // Обработчики событий fOnWrite: TWriteEvent; fOnStatus: TGetStrProc; fOnTerminate: TNotifyEvent; protected procedure CreatePages; virtual; abstract; function GetPages: TPages; public constructor Create( const aFileName: String; const aSlaveId: Byte; const aController: IController; const aOnWrite: TWriteEvent = nil; const aOnStatus: TGetStrProc = nil; const aOnTerminate: TNotifyEvent = nil); reintroduce; procedure AfterConstruction; override; destructor Destroy; override; public procedure Flash; virtual; abstract; procedure StopFlash; function IsFlashing: Boolean; end; { TBootloader1 } TBootloader1 = class(TBootloader) private fRunBootLoader: IFrame; fRunApplication: IFrame; protected procedure CreatePages; override; procedure CreateCommands; public procedure Flash; override; end; { TThreadFlash } TThreadFlash = class(TThread) protected fFlashing: Integer; fBootloader: TBootLoader; fStatus: String; fSize, fCurrentPage: Word; protected procedure DoWrite; procedure DoStatus; public constructor Create(const aBootloader: TBootloader); reintroduce; public function IsFlashing: Boolean; procedure Stop; end; { TThreadFlash1 } TThreadFlash1 = class(TThreadFlash) private function RunBootloader(const aFrame: IFrame): Boolean; function RunApplication(const aFrame: IFrame): Boolean; function WritePage(const aFrame: IFrame): Boolean; protected procedure Execute; override; end; implementation uses // Logger, uSetting; const WM_COUNT = WM_USER + 1; { TBootloader } function TBootloader.GetPages: TPages; begin Result := fPages; end; constructor TBootloader.Create(const aFileName: String; const aSlaveId: Byte; const aController: IController; const aOnWrite: TWriteEvent; const aOnStatus: TGetStrProc; const aOnTerminate: TNotifyEvent); begin inherited Create; fFileName := aFileName; fSlaveId := aSlaveId; fController := aController; fPages := TPages.Create; fThreadFlash := nil; fOnWrite := aOnWrite; fOnStatus := aOnStatus; fOnTerminate := aOnTerminate; end; procedure TBootloader.AfterConstruction; begin inherited AfterConstruction; fTimeout := GetSetting.Timeout; fStream := TFileStream.Create(Utf8ToAnsi(fFileName), fmOpenRead); fStream.Position := 0; end; destructor TBootloader.Destroy; begin StopFlash; FreeAndNil(fPages); FreeAndNil(fStream); inherited Destroy; end; procedure TBootloader.StopFlash; begin if fThreadFlash <> nil then begin fThreadFlash.Stop; fThreadFlash.Free; fThreadFlash := nil; end; end; function TBootloader.IsFlashing: Boolean; begin Result := (fThreadFlash <> nil) and fThreadFlash.IsFlashing; end; { TBootloader1 } procedure TBootloader1.CreatePages; const NBB_BLOCK: Word = 990; // Последняя страница во Flash MAX_FILE_SIZE = 126720; // Максимальный размер файла SizeOfPage = 128; var // Текущая страница CurrentPage: Word; CRC16: Word; // Количество байт для записи NumberBytesToWrite: Byte; // Размер буфера данных Buffer: TBuffer; I: Integer; // Фрейм запроса Frame: IFrame; begin if fStream = nil then Exit; CRC16 := $FFFF; CurrentPage := 0; // Очищаем буфер FillChar({%H-}Buffer, SizeOf(Buffer), $0); // Проверка файла if (fStream.Size = 0) or (fStream.Size > MAX_FILE_SIZE) then raise Exception.Create(Format('Недопустимый размер файла ''%s''', [fFileName])); // 1. Пишем содержимое прошивки из файла repeat // Читаем очередные данные NumberBytesToWrite := fStream.Read(Buffer, SizeOfPage); if NumberBytesToWrite = 0 then Break; // Если количество прочитанных байт меньше размера страницы, оставшиеся данные заполняем 1 if NumberBytesToWrite < SizeOfPage then for I := NumberBytesToWrite to SizeOfPage - 1 do Buffer[I] := $FF; // Код CRC16 CalcCRC16(@Buffer, SizeOfPage, CRC16); // Создаем фрейм запроса и помещаем его в контейнер Frame := WritePage(fSlaveId, CurrentPage, SizeOfPage, @Buffer, fTimeout); fPages.Add(Frame); Inc(CurrentPage); until CurrentPage = 0; // 2. Стираем оставшиеся страницы // Очищаем буфер FillChar(Buffer, SizeOf(Buffer), $FF); while CurrentPage < NBB_BLOCK do begin // Код CRC16 CalcCRC16(@Buffer, SizeOfPage, CRC16); // Создаем фрейм запроса и помещаем его в контейнер Frame := WritePage(fSlaveId, CurrentPage, SizeOfPage, @Buffer, fTimeout); fPages.Add(Frame); Inc(CurrentPage); end; // 3. Запись контрольной суммы Buffer[0] := Lo(CRC16); Buffer[1] := Hi(CRC16); // Создаем фрейм запроса и помещаем его в контейнер Frame := WritePage(fSlaveId, CurrentPage, SizeOfPage, @Buffer, fTimeout); fPages.Add(Frame); end; procedure TBootloader1.CreateCommands; begin fRunBootloader := RunBootLoader(fSlaveId, fTimeout); fRunApplication := RunApplication(fSlaveId, fTimeout); end; procedure TBootloader1.Flash; begin CreateCommands; CreatePages; if (fRunBootloader = nil) or (fRunApplication = nil) or (fPages.Count = 0) then raise Exception.Create('Ошибка создания запроса'); fThreadFlash := TThreadFlash1.Create(Self); fThreadFlash.OnTerminate := fOnTerminate; fThreadFlash.Start; end; { TThreadFlash } constructor TThreadFlash.Create(const aBootloader: TBootloader); begin inherited Create(True); fBootloader := aBootloader; fFlashing := 0; FreeOnTerminate := False; end; procedure TThreadFlash.DoWrite; begin fBootloader.fOnWrite(fBootloader.fPages.Count, fCurrentPage); end; procedure TThreadFlash.DoStatus; begin fBootloader.fOnStatus(fStatus); end; function TThreadFlash.IsFlashing: Boolean; begin Result := Windows.InterlockedCompareExchange(fFlashing, 0, 0) = 1; end; procedure TThreadFlash.Stop; const TIMEOUT_CLOSE = 1000; begin Windows.InterLockedExchange(fFlashing, 0); WaitForSingleObject(Handle, TIMEOUT_CLOSE); end; { TThreadFlash1 } function TThreadFlash1.RunBootloader(const aFrame: IFrame): Boolean; const MB_DEVICE_FUNCTION: Byte = $68; MB_RUN_BOOTLOADER: Byte = 2; begin if Assigned(fBootloader.fOnStatus) then begin fStatus := 'Запуск Bootloader''a'''; Synchronize(@DoStatus); end; Result := False; try while not fBootloader.fController.InQueue(aFrame) do begin sleep(20); if not IsFlashing then Exit; end; case aFrame.Responded of True: begin // Проверить ответ Result := (aFrame.ResponsePdu^[0] = MB_DEVICE_FUNCTION) and (aFrame.ResponsePdu^[1] = MB_RUN_BOOTLOADER) and (aFrame.ResponsePdu^[2] = 0); PostMessage(Application.MainFormHandle, WM_COUNT, 1, 0); end; False: PostMessage(Application.MainFormHandle, WM_COUNT, 0, 1); end; finally if Assigned(fBootloader.fOnStatus) then begin case Result of True: fStatus := 'Bootloader запущен'; False: fStatus := 'Ошибка запуска Bootloader''a'''; end; Synchronize(@DoStatus); end; end; end; function TThreadFlash1.RunApplication(const aFrame: IFrame): Boolean; const MB_DEVICE_FUNCTION: Byte = $68; MB_RUN_APPLICATION: Byte = 1; begin if Assigned(fBootloader.fOnStatus) then begin fStatus := 'Запуск приложения'; Synchronize(@DoStatus); end; Result := False; try while not fBootloader.fController.InQueue(aFrame) do begin sleep(20); if not IsFlashing then Exit; end; case aFrame.Responded of True: begin // Проверить ответ Result := (aFrame.ResponsePdu^[0] = MB_DEVICE_FUNCTION) and (aFrame.ResponsePdu^[1] = MB_RUN_APPLICATION) and (aFrame.ResponsePdu^[2] = 0); Result := True; PostMessage(Application.MainFormHandle, WM_COUNT, 1, 0); end; False: PostMessage(Application.MainFormHandle, WM_COUNT, 0, 1); end; finally if Assigned(fBootloader.fOnStatus) then begin case Result of True: fStatus := 'Приложение запущено'; False: fStatus := 'Ошибка запуска приложения'; end; Synchronize(@DoStatus); end; end; end; function TThreadFlash1.WritePage(const aFrame: IFrame): Boolean; const MB_FLASH_FUNCTION: Byte = $64; begin Result := False; try while not fBootloader.fController.InQueue(aFrame) do begin sleep(20); if not IsFlashing then Exit; end; case aFrame.Responded of True: begin // Проверить ответ Result := (aFrame.ResponsePdu^[0] = MB_FLASH_FUNCTION); PostMessage(Application.MainFormHandle, WM_COUNT, 1, 0); end; False: PostMessage(Application.MainFormHandle, WM_COUNT, 0, 1); end; finally if Assigned(fBootloader.fOnWrite) then begin if Result then Inc(fCurrentPage); Synchronize(@DoWrite); end; //if Assigned(fBootloader.fOnStatus) then //begin // fStatus := Format('%d из %d', [fCurrentPage, fBootloader.fPages.Count]); // Synchronize(@DoStatus); //end; end; end; procedure TThreadFlash1.Execute; var Bootloader: TBootloader1; Frame: IFrame; begin if not (fBootloader is TBootloader1) then Exit; BootLoader := TBootloader1(fBootLoader); Windows.InterLockedExchange(fFlashing, 1); try try // Запуск Bootloader while not RunBootloader(Bootloader.fRunBootLoader) do begin if not IsFlashing then Exit; Sleep(20); end; sleep(1000); // Загрузка прошивки if Assigned(fBootloader.fOnStatus) then begin fStatus := 'Старт прошивки...'; Synchronize(@DoStatus); end; for Frame in Bootloader.fPages do begin while not WritePage(Frame) do begin if not IsFlashing then Exit; Sleep(20); end; if not IsFlashing then Exit; end; if Assigned(fBootloader.fOnStatus) then begin fStatus := 'Прошивание закончено'; Synchronize(@DoStatus); end; finally sleep(1000); // Запуск приложения RunApplication(Bootloader.fRunApplication); end; finally Windows.InterLockedExchange(fFlashing, 0); end; end; end.
unit uMongoQuery; interface uses System.SysUtils, System.Classes, mongoWire, bsonDoc, bsonUtils, FMX.Forms, uEditMongo, uMongoDocument, System.Generics.Collections, FMX.Layouts, uConexaoMongo, FMX.ListBox, uMongo_Tipificacoes, System.Variants, DataSnap.DBClient, Data.DB, Generics.Collections; type TMongoQuery = class(TComponent) private FMongoConexao : TMongoConexao; FAtivar : Boolean; FCollection : String; FMongoQuery : TMongoWireQuery; FDataSet : TClientDataSet; procedure setAtivar(const Value: boolean); procedure preencherMongoDoc(Layout : TLayout; var MongoDoc : TMongoDocument); procedure criarDataSetLayout(Layout : TLayout); procedure criarDataSetLista(Lista : TList<String>); public FMongoWireQuery : TMongoWireQuery; constructor Create(AOwner: TComponent); override; function InserirLayout(Layout : TLayout) : Boolean; function UpdateLayout(Layout : TLayout) : Boolean; function DeleteLayout(Layout : TLayout) : Boolean; function SelectLayout(Layout : TLayout) : Boolean; function SelectEditLayout(Layout : TLayout) : Boolean; procedure buscaFoneticaDataSet(Texto, Index, Campo : String); procedure buscaConteudo(Texto, Campo : String); published property MongoConexao : TMongoConexao read FMongoConexao write FMongoConexao; property Ativar : Boolean read FAtivar write setAtivar; property Collection : String read FCollection write FCollection; property MongoQuery : TMongoWireQuery read FMongoQuery write FMongoQuery; property DataSet : TClientDataSet read FDataSet write FDataSet; end; procedure Register; implementation procedure Register; begin RegisterComponents('Mongo Components', [TMongoQuery]); end; constructor TMongoQuery.Create(AOwner: TComponent); begin inherited Create(AOwner); FCollection := 'MinhaCollection'; end; procedure TMongoQuery.setAtivar(const Value: boolean); begin FAtivar := Value; end; function TMongoQuery.InserirLayout(Layout: TLayout) : Boolean; var d : IBSONDocument; MongoDoc : TMongoDocument; i : Integer; begin Result := True; d := nil; MongoDoc := TMongoDocument.Create; try try preencherMongoDoc(Layout, MongoDoc); MongoDoc.convertBSON(d); FMongoConexao.FMongoWire.Insert(FCollection, d); except Result := False; end; finally MongoDoc.Free; end; end; function TMongoQuery.UpdateLayout(Layout: TLayout) : Boolean; var d, dChave : IBSONDocument; MongoDoc : TMongoDocument; i : Integer; begin Result := True; d := nil; MongoDoc := TMongoDocument.Create; try try preencherMongoDoc(Layout, MongoDoc); MongoDoc.convertBSON(d); MongoDoc.convertCampoChave(dChave); FMongoConexao.FMongoWire.Update(FCollection, dChave, d); except Result := False; end; finally MongoDoc.Free; end; end; function TMongoQuery.DeleteLayout(Layout: TLayout) : Boolean; var d, dChave : IBSONDocument; MongoDoc : TMongoDocument; i : Integer; begin Result := True; d := nil; MongoDoc := TMongoDocument.Create; try try preencherMongoDoc(Layout, MongoDoc); MongoDoc.convertCampoChave(dChave); FMongoConexao.FMongoWire.Delete(FCollection, dChave); except Result := False; end; finally MongoDoc.Free; end; end; function TMongoQuery.SelectEditLayout(Layout : TLayout) : Boolean; var d, dChave : IBSONDocument; MongoDoc : TMongoDocument; i : Integer; Edit : TEditMongo; begin MongoDoc := TMongoDocument.Create; try try preencherMongoDoc(Layout, MongoDoc); MongoDoc.convertCampoChave(dChave); d:=FMongoConexao.FMongoWire.Get(FCollection,dChave); for i:= 0 to Pred(Layout.ControlsCount) do begin if (Layout.Controls[i] is TEditMongo) then begin Edit := TEditMongo(Layout.Controls[i]); Edit.Text := VarToStr(d[Edit.MongoCampo]); end; end; except Result := False; end; finally MongoDoc.Free; end; end; function TMongoQuery.SelectLayout(Layout: TLayout) : Boolean; var d : IBSONDocument; i : Integer; Edit : TEditMongo; begin Result := True; d:=BSON; try FMongoWireQuery := TMongoWireQuery.Create(FMongoConexao.FMongoWire); FMongoWireQuery.Query(FCollection, nil); criarDataSetLayout(Layout); while FMongoWireQuery.Next(d) do begin FDataSet.Append; for i:= 0 to Pred(Layout.ControlsCount) do begin if (Layout.Controls[i] is TEditMongo) then begin Edit := TEditMongo(Layout.Controls[i]); FDataSet.FieldByName(Edit.MongoCampo).AsVariant := d[Edit.MongoCampo]; end; end; FDataSet.Post; end; FDataSet.Open; except Result := False; end; end; procedure TMongoQuery.criarDataSetLayout(Layout : TLayout); var i : Integer; Edit : TEditMongo; begin FDataSet.Close; FDataSet.FieldDefs.Clear; for i:= 0 to Pred(Layout.ControlsCount) do begin if (Layout.Controls[i] is TEditMongo) then begin Edit := TEditMongo(Layout.Controls[i]); case Edit.MongoTipoCampo of Texto: FDataSet.FieldDefs.add(Edit.MongoCampo, ftString, 255); Numerico: FDataSet.FieldDefs.add(Edit.MongoCampo, ftInteger); Moeda : FDataSet.FieldDefs.add(Edit.MongoCampo, ftFloat); DataHora : FDataSet.FieldDefs.add(Edit.MongoCampo, ftString, 50); end; end; end; FDataSet.CreateDataSet; end; procedure TMongoQuery.criarDataSetLista(Lista : TList<String>); var I : Integer; begin FDataSet.Close; FDataSet.FieldDefs.Clear; for I := 0 to Lista.Count -1 do begin FDataSet.FieldDefs.add(Lista[I], ftString, 255); end; FDataSet.CreateDataSet; end; procedure TMongoQuery.preencherMongoDoc(Layout: TLayout; var MongoDoc: TMongoDocument); var i : Integer; begin for i:= 0 to Pred(Layout.ControlsCount) do begin if (Layout.Controls[i] is TEditMongo) then begin if TEditMongo(Layout.Controls[i]).CampoChave then begin MongoDoc.addCampoChave(TEditMongo(Layout.Controls[i]).MongoCampo,TEditMongo(Layout.Controls[i]).Text, TEditMongo(Layout.Controls[i]).MongoTipoCampo); end; case TEditMongo(Layout.Controls[i]).MongoTipoCampo of Texto : begin MongoDoc.addKey(TEditMongo(Layout.Controls[i]).MongoCampo, TEditMongo(Layout.Controls[i]).Text, Texto); end; Numerico : begin MongoDoc.addKey(TEditMongo(Layout.Controls[i]).MongoCampo, TEditMongo(Layout.Controls[i]).toNumerico, Numerico); end; Moeda : begin MongoDoc.addKey(TEditMongo(Layout.Controls[i]).MongoCampo, TEditMongo(Layout.Controls[i]).toMoeda, Moeda); end; DataHora : begin MongoDoc.addKey(TEditMongo(Layout.Controls[i]).MongoCampo, TEditMongo(Layout.Controls[i]).toDataHora, DataHora); end; end; end; end; end; procedure TMongoQuery.buscaFoneticaDataSet(Texto, Index, Campo : String); var d : IBSONDocument; q : TMongoWireQuery; Lista : TList<String>; begin d := BSON; q := TMongoWireQuery.Create(FMongoConexao.FMongoWire); Lista := TList<String>.Create; try //O index jŠ deve vir com '$' Lista.Add(Campo); criarDataSetLista(Lista); q.Query(FCollection,BSON([Index, BSON(['$search', Texto])])); FDataSet.Append; while q.Next(d) do begin FDataSet.FieldByName(Campo).AsVariant := d[Campo]; end; FDataSet.Post; finally q.Destroy; Lista.Destroy; end; end; procedure TMongoQuery.buscaConteudo(Texto, Campo : String); var d : IBSONDocument; q : TMongoWireQuery; Lista : TList<String>; begin d := BSON; q := TMongoWireQuery.Create(FMongoConexao.FMongoWire); Lista := TList<String>.Create; try Lista.Add(Campo); criarDataSetLista(Lista); q.Query(FCollection,BSON([Campo, BSON(['$regex', bsonRegExPrefix+'/^'+Texto, '$options' , 'm'])])); FDataSet.DisableControls; while q.Next(d) do begin FDataSet.Append; FDataSet.FieldByName(Campo).AsVariant := d[Campo]; FDataSet.Post; end; FDataSet.EnableControls;; finally q.Destroy; Lista.Destroy; end; end; end.
unit JLLabel; {==========================================================================} { JL's RotateLabel with 3D-effects } { } { Copyright © 1996 by Jörg Lingner, Munich, Germany (jlingner@t-online.de) } { } { FREEWARE } { Free to use and redistribute. } { No warranty is given by the author, expressed or implied. } { } { 3D-effects: from RZLABEL-component } { Copyright © by Ray Konopka (Raize Software Solutions, Inc.) } {--------------------------------------------------------------------------} { This component works like TLabel and has 2 additional properties: } { } { Escapement: draw text with angle (0..360 deg) } { selected font must be a TrueType!!! } { } { TextStyle: draw text with 3D-effects tsRecessed } { tsRaised } { tsNone } { } {--------------------------------------------------------------------------} { Vers. Date Remarks } { 1.0 30.03.97 Initial release } { } {==========================================================================} interface uses WinProcs, Wintypes, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Menus; type TTextStyle = (tsNone,tsRaised,tsRecessed); TRotateLabel = class(TCustomLabel) private fEscapement : Integer; fTextStyle : TTextStyle; procedure SetEscapement(aVal:Integer); procedure SetTextStyle (aVal:TTextStyle); procedure CalcTextPos(var aRect:TRect;aAngle:Integer;aTxt:String); procedure DrawAngleText(aCanvas:TCanvas;aRect:TRect;aAngle:Integer;aTxt:String); protected procedure DoDrawText(var Rect:TRect;Flags:Word); procedure Paint; override; public constructor Create(AOwner: TComponent); override; published property Escapement: Integer read fEscapement write SetEscapement; property TextStyle : TTextStyle read fTextStyle write SetTextStyle; property Align; property Alignment; property AutoSize; property Caption; property Color; property DragCursor; property DragMode; property Enabled; property FocusControl; property Font; property ParentColor; property ParentFont; property ParentShowHint; property PopupMenu; property ShowAccelChar; property ShowHint; property Transparent; property Visible; property WordWrap; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnMouseDown; property OnMouseMove; property OnMouseUp; {$IFDEF WIN32} property OnStartDrag; {$ENDIF} end; procedure Register; {==========================================================================} implementation procedure Register; {==========================================================================} begin RegisterComponents('Grafik', [TRotateLabel]); end; {==========================================================================} constructor TRotateLabel.Create(aOwner:TComponent); {==========================================================================} begin inherited Create(aOwner); fEscapement:= 45; fTextStyle := tsRaised; Font.Name := 'Arial'; end; {==========================================================================} procedure TRotateLabel.SetEscapement(aVal:Integer); {==========================================================================} begin if fEscapement <> aVal then begin if aVal < 0 then begin while aVal < -360 do aVal := aVal + 360; aVal := 360 + aVal; end; while aVal > 360 do aVal := aVal - 360; fEscapement := aVal; Invalidate; end; end; {==========================================================================} procedure TRotateLabel.SetTextStyle(aVal:TTextStyle); {==========================================================================} begin if fTextStyle <> aVal then begin fTextStyle := aVal; Invalidate; end; end; {==========================================================================} procedure TRotateLabel.Paint; {==========================================================================} const Alignments: array[TAlignment] of Word = (DT_LEFT,DT_RIGHT,DT_CENTER); WordWraps : array[Boolean] of Word = (0,DT_WORDBREAK); var Rect: TRect; begin with Canvas do begin if not Transparent then begin Brush.Color := Self.Color; Brush.Style := bsSolid; FillRect(ClientRect); end; Brush.Style := bsClear; Rect := ClientRect; DoDrawText(Rect,DT_EXPANDTABS or WordWraps[WordWrap] or Alignments[Alignment]); end; end; {==========================================================================} procedure TRotateLabel.CalcTextPos(var aRect:TRect;aAngle:Integer;aTxt:String); {==========================================================================} { Calculate text pos. depend. on: Font, Escapement, Alignment and length } { if AutoSize true : set properties Height and Width } {--------------------------------------------------------------------------} var DC : HDC; hSavFont: HFont; Size : TSize; x,y : Integer; cStr : array[0..255] of Char; begin StrPCopy(cStr,aTxt); DC := GetDC(0); hSavFont := SelectObject(DC,Font.Handle); {$IFDEF WIN32} GetTextExtentPoint32(DC,cStr,Length(aTxt),Size); {$ELSE} GetTextExtentPoint(DC,cStr,Length(aTxt),Size); {$ENDIF} SelectObject (DC,hSavFont); ReleaseDC(0,DC); if aAngle<=90 then begin { 1.Quadrant } x := 0; y := Trunc(Size.cx * sin(aAngle*Pi/180)); end else if aAngle<=180 then begin { 2.Quadrant } x := Trunc(Size.cx * -cos(aAngle*Pi/180)); y := Trunc(Size.cx * sin(aAngle*Pi/180) + Size.cy * cos((180-aAngle)*Pi/180)); end else if aAngle<=270 then begin { 3.Quadrant } x := Trunc(Size.cx * -cos(aAngle*Pi/180) + Size.cy * sin((aAngle-180)*Pi/180)); y := Trunc(Size.cy * sin((270-aAngle)*Pi/180)); end else if aAngle<=360 then begin { 4.Quadrant } x := Trunc(Size.cy * sin((360-aAngle)*Pi/180)); y := 0; end; aRect.Top := aRect.Top +y; aRect.Left:= aRect.Left+x; x := Abs(Trunc(Size.cx * cos(aAngle*Pi/180))) + Abs(Trunc(Size.cy * sin(aAngle*Pi/180))); y := Abs(Trunc(Size.cx * sin(aAngle*Pi/180))) + Abs(Trunc(Size.cy * cos(aAngle*Pi/180))); if Autosize then begin Width := x; Height := y; end else if Alignment = taCenter then begin aRect.Left:= aRect.Left + ((Width-x) div 2); end else if Alignment = taRightJustify then begin aRect.Left:= aRect.Left + Width - x; end; end; {==========================================================================} procedure TRotateLabel.DrawAngleText(aCanvas:TCanvas;aRect:tRect;aAngle:Integer;aTxt:String); {==========================================================================} { Draw text with FontIndirect (angle -> escapement) } {--------------------------------------------------------------------------} var LFont : TLogFont; hOldFont, hNewFont: HFont; begin CalcTextPos(aRect,aAngle,aTxt); GetObject(aCanvas.Font.Handle,SizeOf(LFont),Addr(LFont)); LFont.lfEscapement := aAngle*10; hNewFont := CreateFontIndirect(LFont); hOldFont := SelectObject(aCanvas.Handle,hNewFont); aCanvas.TextOut(aRect.Left,aRect.Top,aTxt); hNewFont := SelectObject(aCanvas.Handle,hOldFont); DeleteObject(hNewFont); end; {==========================================================================} procedure TRotateLabel.DoDrawText(var Rect:TRect;Flags:Word); {==========================================================================} { Draw the text normal or with angle and with 3D-effects } { } { 3D-effects: RZLABEL-component } { (c) by Ray Konopka (Raize Software Solutions, Inc.) } {--------------------------------------------------------------------------} var Text : String; TmpRect : TRect; UpperColor : TColor; LowerColor : TColor; {$IFDEF WINDOWS} cStr : array[0..255] of Char; {$ENDIF} begin Text := Caption; {$IFDEF WINDOWS} StrPCopy(cStr,Text); {$ENDIF} if (Flags and DT_CALCRECT <> 0) and ((Text = '') or ShowAccelChar and (Text[1] = '&') and (Text[2] = #0)) then Text := Text + ' '; if not ShowAccelChar then Flags := Flags or DT_NOPREFIX; Canvas.Font := Font; UpperColor := clBtnHighlight; LowerColor := clBtnShadow; if FTextStyle = tsRecessed then begin UpperColor := clBtnShadow; LowerColor := clBtnHighlight; end; if FTextStyle in [tsRecessed,tsRaised] then begin TmpRect := Rect; OffsetRect(TmpRect,1,1); Canvas.Font.Color := LowerColor; if fEscapement <> 0 then DrawAngleText(Canvas,TmpRect,fEscapement,Text) {$IFDEF WIN32} else DrawText(Canvas.Handle,pChar(Text),Length(Text),TmpRect,Flags); {$ELSE} else DrawText(Canvas.Handle,cStr,Length(Text),TmpRect,Flags); {$ENDIF} TmpRect := Rect; OffsetRect(TmpRect,-1,-1); Canvas.Font.Color := UpperColor; if fEscapement <> 0 then DrawAngleText(Canvas,TmpRect,fEscapement,Text) {$IFDEF WIN32} else DrawText(Canvas.Handle,pChar(Text),Length(Text),TmpRect,Flags); {$ELSE} else DrawText(Canvas.Handle,cStr,Length(Text),TmpRect,Flags); {$ENDIF} end; Canvas.Font.Color := Font.Color; if not Enabled then Canvas.Font.Color := clGrayText; if fEscapement <> 0 then DrawAngleText(Canvas,Rect,fEscapement,Text) {$IFDEF WIN32} else DrawText(Canvas.Handle,pChar(Text),Length(Text),Rect,Flags); {$ELSE} else DrawText(Canvas.Handle,cStr,Length(Text),Rect,Flags); {$ENDIF} end; {==========================================================================} end.
unit FormUnit1; interface uses Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.AppEvnts, Vcl.StdCtrls, IdHTTPWebBrokerBridge, Web.HTTPApp, IdBaseComponent, IdComponent, IdUDPBase, IdUDPServer, IdGlobal, IdSocketHandle, System.Bluetooth, System.Bluetooth.Components, Vcl.ExtCtrls, Vcl.Buttons; type TForm1 = class(TForm) ButtonStart: TButton; ButtonStop: TButton; EditPort: TEdit; Label1: TLabel; ApplicationEvents1: TApplicationEvents; ButtonOpenBrowser: TButton; Memo1: TMemo; IdUDPServer1: TIdUDPServer; BitBtnMsgBluetooth: TBitBtn; BluetoothPC: TBluetooth; procedure FormCreate(Sender: TObject); procedure ApplicationEvents1Idle(Sender: TObject; var Done: Boolean); procedure ButtonStartClick(Sender: TObject); procedure ButtonStopClick(Sender: TObject); procedure ButtonOpenBrowserClick(Sender: TObject); procedure IdUDPServer1UDPRead(AThread: TIdUDPListenerThread; const AData: TIdBytes; ABinding: TIdSocketHandle); procedure FormShow(Sender: TObject); procedure TimerBluetoothTimer(Sender: TObject); procedure BitBtnMsgBluetoothClick(Sender: TObject); private FServer: TIdHTTPWebBrokerBridge; ///////////////////Bluetooth////////////////////////////////////////////// FSocket : TBluetoothSocket; const UUID = '{00001101-0000-1000-8000-00805F9B34FB}'; function ObterDevicePeloNome(NomeDevice: String): TBluetoothDevice; function ConectarControladoraBluetooth(NomeDevice: String): boolean; //////////////////Bluetooth//////////////////////////////////////////////// procedure StartServer; function HexToString(H: String): String; { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} uses WinApi.Windows, Winapi.ShellApi, Datasnap.DSSession; procedure TForm1.ApplicationEvents1Idle(Sender: TObject; var Done: Boolean); begin ButtonStart.Enabled := not FServer.Active; ButtonStop.Enabled := FServer.Active; EditPort.Enabled := not FServer.Active; end; procedure TForm1.BitBtnMsgBluetoothClick(Sender: TObject); Var strRecebida : string; begin BluetoothPC.Enabled:=True; if (FSocket = nil) or (not FSocket.Connected) then ConectarControladoraBluetooth('CONTROLADORA_HC05_200'); if (FSocket <> nil) and (FSocket.Connected) then begin Memo1.Lines.Add(''); Memo1.Lines.Add(DateTimeToStr(Now)); strRecebida:=''; FSocket.SendData(TEncoding.UTF8.GetBytes('L')); Memo1.Lines.Add('Enviado: L'); sleep(300); strRecebida:=Trim(TEncoding.ANSI.GetString(FSocket.ReceiveData)); Memo1.Lines.Add('Recebido -------->: ' + strRecebida); Application.ProcessMessages; FreeAndNil(FSocket); end; end; procedure TForm1.ButtonOpenBrowserClick(Sender: TObject); var LURL: string; begin StartServer; LURL := Format('http://localhost:%s', [EditPort.Text]); ShellExecute(0, nil, PChar(LURL), nil, nil, SW_SHOWNOACTIVATE); end; procedure TForm1.ButtonStartClick(Sender: TObject); begin StartServer; end; procedure TerminateThreads; begin if TDSSessionManager.Instance <> nil then TDSSessionManager.Instance.TerminateAllSessions; end; procedure TForm1.ButtonStopClick(Sender: TObject); begin TerminateThreads; FServer.Active := False; FServer.Bindings.Clear; end; procedure TForm1.FormCreate(Sender: TObject); begin FServer := TIdHTTPWebBrokerBridge.Create(Self); end; procedure TForm1.FormShow(Sender: TObject); begin IdUDPServer1.Bindings.Add.IP:='192.168.25.50'; IdUDPServer1.Bindings.Add.Port:=26800; // IdUDPServer1.Active:=True; if IdUDPServer1.Active then begin Memo1.Lines.Add('Serviço UDP Ativado com Sucesso'); end else begin Memo1.Lines.Add('Serviço UDP Não Ativado'); end; end; function TForm1.HexToString(H: String): String; Var I : Integer; begin Result:= ''; for I := 1 to length (H) div 2 do Result:= Result+Char(StrToInt('$'+Copy(H,(I-1)*2+1,2))); end; procedure TForm1.IdUDPServer1UDPRead(AThread: TIdUDPListenerThread; const AData: TIdBytes; ABinding: TIdSocketHandle); var StringRecebida : String; i : integer; begin StringRecebida:=''; for i:=0 to Length(AData) - 1 do begin StringRecebida:=StringRecebida + HexToString( IntToHex(Integer(AData[i]), 2) ); end; if StringRecebida <> '' then begin Memo1.Lines.Add(''); Memo1.Lines.Add('Recebido: ' + StringRecebida + ' - ' + 'IP Origem: ' + ABinding.PeerIP + ' - ' + 'Porta Origem: ' + ABinding.PeerPort.ToString ); end; end; procedure TForm1.StartServer; begin if not FServer.Active then begin FServer.Bindings.Clear; FServer.DefaultPort := StrToInt(EditPort.Text); FServer.Active := True; end; end; procedure TForm1.TimerBluetoothTimer(Sender: TObject); begin end; ////////////////////////Bluetooth/////////////////////////////////////////////// function TForm1.ObterDevicePeloNome(NomeDevice: String): TBluetoothDevice; var lDevice: TBluetoothDevice; begin Result := nil; for lDevice in BluetoothPC.PairedDevices do begin if Trim(lDevice.DeviceName) = NomeDevice then begin Result := lDevice; end; end; end; function TForm1.ConectarControladoraBluetooth(NomeDevice: String): boolean; var lDevice: TBluetoothDevice; begin Result := False; lDevice := ObterDevicePeloNome(NomeDevice); if lDevice <> nil then begin FSocket := lDevice.CreateClientSocket(StringToGUID(UUID), False); if FSocket <> nil then begin FSocket.Connect; Result := FSocket.Connected end; end; end; //////////////////////////////////////////////////////////////////////////////// end.
unit fmAnadirRetirarCapital; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, fmBase, StdCtrls, Buttons, JvExStdCtrls, JvEdit, JvValidateEdit, ExtCtrls; type TfAnadirRetirarCapital = class(TfBase) eCapital: TJvValidateEdit; Label1: TLabel; Label2: TLabel; bOk: TBitBtn; bCancel: TBitBtn; Bevel2: TBevel; procedure eCapitalKeyPress(Sender: TObject; var Key: Char); private function GetCapital: currency; procedure SetAnadir(const Value: boolean); public property Capital: currency read GetCapital; property Anadir: boolean write SetAnadir; end; implementation {$R *.dfm} procedure TfAnadirRetirarCapital.eCapitalKeyPress(Sender: TObject; var Key: Char); begin inherited; bOk.Enabled := eCapital.Value > 0; end; function TfAnadirRetirarCapital.GetCapital: currency; begin result := eCapital.Value; end; procedure TfAnadirRetirarCapital.SetAnadir(const Value: boolean); begin if Value then begin Caption := 'Aņadir Capital'; bOK.Caption := 'Aņadir'; end else begin Caption := 'Retirar Capital'; bOK.Caption := 'Retirar'; end; end; end.
unit TissConsulta; interface uses SysUtils, Classes,Windows,Dialogs,Messages,forms,xmldom, XMLIntf, msxmldom, XMLDoc,untTissComp,Graphics; {COMPONENTE INICIADO POR Fabiano Espero ter ajudado alguem com este componente, e espero que mais progrmadores se juntem nesta idéia para assim realizarmo o projeto TISS com sucesso, pela graça de Maria e o amor de Nosso Senhor JESUS CRISTO} const MSG_TOVALIDATE_PTBR = 'A SER VALIDADO'; MSG_ISVALID_PTBR = 'VÁLIDO'; MSG_ISNTVALID_PTBR = 'INVÁLIDO'; type Tpessoa = (Fisico,Juridico,Outro); TTissConsulta = class(TComponent) private { Private declarations } FEncoding: String; FVersaoXml: String; FMensagemTissXml: String; FTipoTrans: String; FSequencialTrans: String; FArquivo: String; FDataRegistroTrans: TDateTime; FHoraRegistroTrans: TDateTime; FTipo: Tpessoa; FCNPJCPF: String; FVersaoTISS: String; FRegANS: String; FNomeAplica: string; FVersaoAplica: string; FFabricaAplica: string; FDataEmis : TDateTime; FNumLote: String; FNumPres: String; FNumGuia: String; FNumCarteira: String; FPaciente: String; FNomePlano: String; FValidadeCart: TDateTime; FNumCNS: String; FNomeContradado: String; FtipoLogradouro: String; FLogradouro: String; FEndNum: String; FComplemento: String; FcodigoIBGE: Currency; FMunicipio: String; FUF: String; fCEP: String; fCNES: Currency; fCodigoTabela: Integer; fUFCONSELHO: String; fSIGLACONSELHO: String; fCIDNomeTab: String; fCIDDescDiag: String; FTipoSaida: String; FCodProc: String; fNUMEROCONSELHO: String; FMedico: String; FTipoConsulta: String; fCIDCodDiag: String; fdataAtendimento: TDateTime; FTissReq: TTissReq; FCompVersao: TCompVersao; FTissValid: TTissValidacao; FEvolucaoValor: Currency; FIndicAcid: String; FUnidTemp: String; FTipDoenca: String; FObs: String; FArqNomeHash: Boolean; FZerosArq: integer; Fvalidado: Boolean; FAnsVersaoxsd: TTissAnsVersao; procedure setEncoding(const Value: String); procedure setVersaoXml(const Value: String); procedure setMensagemTissXml(const Value: String); procedure setTipoTrans(const Value: String); procedure setSequencialTrans(const Value: String); procedure setArquivo(const Value: String); procedure setDataRegistroTrans(const Value: TDateTime); procedure setHoraRegistroTrans(const Value: TDateTime); procedure setTipo(const Value: Tpessoa); procedure setCNPJCPF(const Value: String); function RegANS: String; procedure setRegANS(const Value: String); procedure setDataEmis(const Value: TDateTime); procedure setVersaoTISS(const Value: String); procedure setNomeAplica(const Value: String); procedure setVersaoAplica(const Value: String); procedure setFabricaAplica(const Value: String); procedure setNumLote(const Value: String); procedure setNumPres(const Value: String); procedure setNumGuia(const Value: String); procedure setNumCarteira(const Value: String); procedure setPaciente(const Value: String); procedure setNomePlano(const Value: String); procedure setValidadeCart(const Value: TDateTime); procedure setNumCNS(const Value: String); procedure setNomeContradado(const Value: String); procedure settipoLogradouro(const Value: String); procedure setLogradouro(const Value: String); procedure setComplemento(const Value: String); procedure setEndNum(const Value: String); procedure setcodigoIBGE(const Value: Currency); procedure setMunicipio(const Value: String); procedure setUF(const Value: String); procedure setCEP(const Value: String); procedure setCNES(const Value: Currency); procedure setCIDCodDiag(const Value: String); procedure setCIDDescDiag(const Value: String); procedure setCIDNomeTab(const Value: String); procedure setCodigoTabela(const Value: Integer); procedure setCodProc(const Value: String); procedure setdataAtendimento(const Value: TDateTime); procedure setMEDICO(const Value: String); procedure setNUMEROCONSELHO(const Value: String); procedure setSIGLACONSELHO(const Value: String); procedure setTipoConsulta(const Value: String); procedure setTipoSaida(const Value: String); procedure setUFCONSELHO(const Value: String); function TiraMascara(Texto: String): String; function hash(arquivohash:string): String; procedure Verifica; procedure setEvolucaoValor(const Value: Currency); procedure setIndicAcid(const Value: String); procedure setUnidTemp(const Value: String); procedure setTipDoenca(const Value: String); procedure setObs(const Value: String); procedure setFArqNomeHash(const Value: Boolean); procedure SetZerosArq(const Value: integer); procedure setvalidado(const Value: Boolean); procedure setAnsVersaoxsd(const Value: TTissAnsVersao); private FFontePadora: TTissIdentFontPag; fCBOS: String; procedure SetFontePagora(const Value: TTissIdentFontPag); procedure setCBOS(const Value: String); property validado: Boolean read Fvalidado write setvalidado; protected { Protected declarations } public { Public declarations } procedure criaCabecalho; procedure criaRodape; procedure adicionarGuia; constructor Create(Aowner: TComponent);override; function arqvalidado: Boolean; published { Published declarations } //versão do xsd da ANS property ansVersaoXSD: TTissAnsVersao read FAnsVersaoxsd write setAnsVersaoxsd; //fonte pagadora property TissFontePadora: TTissIdentFontPag read FFontePadora write SetFontePagora; property Versao:TCompVersao read FCompVersao write FCompVersao; property TissVersaoXml: String read FVersaoXml write setVersaoXml; property TissVersaoTISS: String read FVersaoTISS write setVersaoTISS; property TissNomeAplica: String read FNomeAplica write setNomeAplica; property TissVersaoAplica: String read FVersaoAplica write setVersaoAplica; property TissFabricaAplica: String read FFabricaAplica write setFabricaAplica; property TissEncoding:String read FEncoding write setEncoding; property TissMensagemTissXml:String read FMensagemTissXml write setMensagemTissXml; property TissTipoTrans:String read FTipoTrans write setTipoTrans; property TissArquivo:String read FArquivo write setArquivo; property TissDataRegistroTrans:TDateTime read FDataRegistroTrans write setDataRegistroTrans; property TissHoraRegistroTrans:TDateTime read FHoraRegistroTrans write setHoraRegistroTrans; property TissSequencialTrans:String read FSequencialTrans write setSequencialTrans; property TissTipo:Tpessoa read FTipo write setTipo; property TissCNPJCPF:String read FCNPJCPF write setCNPJCPF; property TissRegANS:String read FRegANS write setRegANS; property TissDataEmis:TDateTime read FDataEmis write setDataEmis; property TissNumLote:String read FNumLote write setNumLote; property TissNumPres:String read FNumPres write setNumPres; property TissNumGuia:String read FNumGuia write setNumGuia; property TissNumCarteira:String read FNumCarteira write setNumCarteira; property TissPaciente:String read FPaciente write setPaciente; property TissNomePlano:String read FNomePlano write setNomePlano; property TissValidadeCart:TDateTime read FValidadeCart write setValidadeCart; property TissNumCNS:String read FNumCNS write setNumCNS; property TissNomeContradado:String read FNomeContradado write setNomeContradado; property TisstipoLogradouro:String read FtipoLogradouro write settipoLogradouro; property TissLogradouro:String read FLogradouro write setLogradouro; property TissEndNum:String read FEndNum write setEndNum; property TissComplemento:String read FComplemento write setComplemento; property TisscodigoIBGE:Currency read FcodigoIBGE write setcodigoIBGE; property TissMunicipio:String read FMunicipio write setMunicipio; property TissUF:String read FUF write setUF; property TissCEP:String read fCEP write setCEP; property TissCNES:Currency read fCNES write setCNES; property TissMEDICO:String read FMedico write setMEDICO; property TissSIGLACONSELHO:String read fSIGLACONSELHO write setSIGLACONSELHO; property TissNUMEROCONSELHO:String read fNUMEROCONSELHO write setNUMEROCONSELHO; property TissUFCONSELHO:String read fUFCONSELHO write setUFCONSELHO; property TissCBOS:String read fCBOS write setCBOS; property TissCIDNomeTab:String read fCIDNomeTab write setCIDNomeTab; property TissCIDCodDiag:String read fCIDCodDiag write setCIDCodDiag; property TissCIDDescDiag:String read fCIDDescDiag write setCIDDescDiag; property TissdataAtendimento:TDateTime read fdataAtendimento write setdataAtendimento; property TissCodigoTabela:Integer read fCodigoTabela write setCodigoTabela; property TissCodProc:String read FCodProc write setCodProc; property TissTipoConsulta:String read FTipoConsulta write setTipoConsulta; property TissTipoSaidaa:String read FTipoSaida write setTipoSaida; //Hipotese diagnostica //property TissHipoteseDiag:String read FHipoteseDiag write setHipoteseDiag; property TissEvolucaoValor:Currency read FEvolucaoValor write setEvolucaoValor; property TissUnidTemp:String read FUnidTemp write setUnidTemp; property TissIndicAcid:String read FIndicAcid write setIndicAcid; property TissTipDoenca:String read FTipDoenca write setTipDoenca; //observacao property TissObs:String read FObs write setObs; property TissConfig: TTissReq read FTissReq write FTissReq; //Validação property TissValid: TTissValidacao read FTissValid write FTissValid; //zeros na formação do arquivo property TissZerosArq: integer read FZerosArq write SetZerosArq; end; procedure Register; implementation uses Md5tiss, U_Ciphertiss, md52, untValida, untFunc; procedure Register; begin RegisterComponents('Tiss', [TTissConsulta]); end; procedure TTissConsulta.adicionarGuia; var arquivo: TextFile; begin try AssignFile(arquivo,FArquivo); Append(arquivo); Writeln(arquivo,'<ansTISS:guiaConsulta>'); Writeln(arquivo,'<ansTISS:identificacaoGuia>'); if (FAnsVersaoxsd <> v2_01_03) then begin Writeln(arquivo,'<ansTISS:identificacaoFontePagadora>'); case FTissReq.PadraoTipFontPg of RegistroANS: Writeln(arquivo,'<ansTISS:registroANS>'+FFontePadora.TissRegAns+'</ansTISS:registroANS>'); CNPJ: Writeln(arquivo,'<ansTISS:cnpjFontePagadora>'+FFontePadora.TissCnpj+'</ansTISS:cnpjFontePagadora>'); end; Writeln(arquivo,'</ansTISS:identificacaoFontePagadora>'); end; if FTissReq.UsarRegANS then if FAnsVersaoxsd = v2_01_03 then Writeln(arquivo,'<ansTISS:registroANS>'+fRegAns+'</ansTISS:registroANS>'); if FansVersaoXSD = v2_01_03 then Writeln(arquivo,'<ansTISS:dataEmissaoGuia>'+FormatDateTime('DD/MM/YYYY',FDataEmis)+'</ansTISS:dataEmissaoGuia>') else Writeln(arquivo,'<ansTISS:dataEmissaoGuia>'+FormatDateTime('YYYY-MM-DD',FDataEmis)+'</ansTISS:dataEmissaoGuia>'); if FTissReq.UsarNumPres then Writeln(arquivo,'<ansTISS:numeroGuiaPrestador>'+FNumPres+'</ansTISS:numeroGuiaPrestador>'); if FTissReq.UsarNumGuia then Writeln(arquivo,'<ansTISS:numeroGuiaOperadora>'+FNumGuia+'</ansTISS:numeroGuiaOperadora>'); Writeln(arquivo,'</ansTISS:identificacaoGuia>'); Writeln(arquivo,'<ansTISS:beneficiario>'); if FTissReq.UsarNumCarteira then Writeln(arquivo,'<ansTISS:numeroCarteira>'+FNumCarteira+'</ansTISS:numeroCarteira>'); if FTissReq.UsarPaciente then Writeln(arquivo,'<ansTISS:nomeBeneficiario>'+FPaciente+'</ansTISS:nomeBeneficiario>'); if FTissReq.UsarNomePlano then Writeln(arquivo,'<ansTISS:nomePlano>'+FNomePlano+'</ansTISS:nomePlano>'); if FTissReq.UsarValidadeCart then begin if FansVersaoXSD = v2_01_03 then Writeln(arquivo,'<ansTISS:validadeCarteira>'+FormatDateTime('DD/MM/YYYY',FValidadeCart)+'</ansTISS:validadeCarteira>') else Writeln(arquivo,'<ansTISS:validadeCarteira>'+FormatDateTime('YYYY-MM-DD',FValidadeCart)+'</ansTISS:validadeCarteira>'); end; if FTissReq.UsarNumCNS then Writeln(arquivo,'<ansTISS:numeroCNS>'+FNumCNS+'</ansTISS:numeroCNS>'); Writeln(arquivo,'</ansTISS:beneficiario>'); Writeln(arquivo,'<ansTISS:dadosContratado>'); Writeln(arquivo,'<ansTISS:identificacao>'); if FTissReq.UsarCNPJCPF then begin if FTipo = Juridico then Writeln(arquivo,'<ansTISS:CNPJ>'+FCNPJCPF+'</ansTISS:CNPJ>'); if FTipo = Fisico then Writeln(arquivo,'<ansTISS:CPF>'+FCNPJCPF+'</ansTISS:CPF>'); if FTipo = Outro then Writeln(arquivo,'<ansTISS:codigoPrestadorNaOperadora>'+FCNPJCPF+'</ansTISS:codigoPrestadorNaOperadora>'); end; Writeln(arquivo,'</ansTISS:identificacao>'); if FTissReq.UsarNomeContradado then Writeln(arquivo,'<ansTISS:nomeContratado>'+FNomeContradado+'</ansTISS:nomeContratado>'); if FTissReq.UsarEndContratado then begin Writeln(arquivo,'<ansTISS:enderecoContratado>'); if FTissReq.UsartipoLogradouro then Writeln(arquivo,'<ansTISS:tipoLogradouro>'+FtipoLogradouro+'</ansTISS:tipoLogradouro>'); if FTissReq.UsarLogradouro then Writeln(arquivo,'<ansTISS:logradouro>'+FLogradouro+'</ansTISS:logradouro>'); if FTissReq.UsarEndNum then Writeln(arquivo,'<ansTISS:numero>'+FEndNum+'</ansTISS:numero>'); if FTissReq.UsarComplemento then Writeln(arquivo,'<ansTISS:complemento>'+FComplemento+'</ansTISS:complemento>'); if FTissReq.UsarcodigoIBGE then Writeln(arquivo,'<ansTISS:codigoIBGEMunicipio>'+FormatFloat('0000000',FcodigoIBGE)+'</ansTISS:codigoIBGEMunicipio>'); if FTissReq.UsarMunicipio then Writeln(arquivo,'<ansTISS:municipio>'+FMunicipio+'</ansTISS:municipio>'); if FTissReq.UsarUF then Writeln(arquivo,'<ansTISS:codigoUF>'+FUF+'</ansTISS:codigoUF>'); if FTissReq.UsarCEP then Writeln(arquivo,'<ansTISS:cep>'+fCEP+'</ansTISS:cep>'); Writeln(arquivo,'</ansTISS:enderecoContratado>'); end; if FTissReq.UsarCNES then Writeln(arquivo,'<ansTISS:numeroCNES>'+FormatFloat('0000000', fCNES)+'</ansTISS:numeroCNES>'); Writeln(arquivo,'</ansTISS:dadosContratado>'); Writeln(arquivo,'<ansTISS:profissionalExecutante>'); if FTissReq.UsarMEDICO then Writeln(arquivo,'<ansTISS:nomeProfissional>'+fMEDICO+'</ansTISS:nomeProfissional>'); Writeln(arquivo,'<ansTISS:conselhoProfissional>'); if FTissReq.UsarSIGLACONSELHO then Writeln(arquivo,'<ansTISS:siglaConselho>'+fSIGLACONSELHO+'</ansTISS:siglaConselho>'); if FTissReq.UsarNUMEROCONSELHO then Writeln(arquivo,'<ansTISS:numeroConselho>'+fNUMEROCONSELHO+'</ansTISS:numeroConselho>'); if FTissReq.UsarUFCONSELHO then Writeln(arquivo,'<ansTISS:ufConselho>'+fUFCONSELHO+'</ansTISS:ufConselho>'); Writeln(arquivo,'</ansTISS:conselhoProfissional>'); if FTissReq.UsarCBOS then Writeln(arquivo,'<ansTISS:cbos>'+fCBOS+'</ansTISS:cbos>'); Writeln(arquivo,'</ansTISS:profissionalExecutante>'); if FTissReq.UsarHipoteseDiag then begin Writeln(arquivo,'<ansTISS:hipoteseDiagnostica>'); Writeln(arquivo,'<ansTISS:CID>'); if FTissReq.UsarCIDNomeTab then Writeln(arquivo,'<ansTISS:nomeTabela>'+fCIDNomeTab+'</ansTISS:nomeTabela>'); if FTissReq.UsarCIDCodDiag then Writeln(arquivo,'<ansTISS:codigoDiagnostico>'+fCIDCodDiag+'</ansTISS:codigoDiagnostico>'); if FTissReq.UsarCIDDescDiag then Writeln(arquivo,'<ansTISS:descricaoDiagnostico>'+fCIDDescDiag+'</ansTISS:descricaoDiagnostico>'); Writeln(arquivo,'</ansTISS:CID>'); if FTissReq.UsarTipDoenca then Writeln(arquivo,'<ansTISS:tipoDoenca>'+FTipDoenca+'</ansTISS:tipoDoenca>'); Writeln(arquivo,'<ansTISS:tempoReferidoEvolucaoDoenca>'); if FTissReq.UsarEvolucaoValor then Writeln(arquivo,'<ansTISS:valor>'+CurrToStr(FEvolucaoValor)+'</ansTISS:valor>'); if FTissReq.UsarUnidTemp then Writeln(arquivo,'<ansTISS:unidadeTempo>'+FUnidTemp+'</ansTISS:unidadeTempo>'); Writeln(arquivo,'</ansTISS:tempoReferidoEvolucaoDoenca>'); if FTissReq.UsarIndicAcid then Writeln(arquivo,'<ansTISS:indicadorAcidente>'+FIndicAcid+'</ansTISS:indicadorAcidente>'); Writeln(arquivo,'</ansTISS:hipoteseDiagnostica>'); end; Writeln(arquivo,'<ansTISS:dadosAtendimento>'); if FTissReq.UsardataAtendimento then begin if FAnsVersaoxsd = v2_01_03 then Writeln(arquivo,'<ansTISS:dataAtendimento>'+FormatDateTime('DD/MM/YYYY',fdataAtendimento)+'</ansTISS:dataAtendimento>') else Writeln(arquivo,'<ansTISS:dataAtendimento>'+FormatDateTime('YYYY-MM-DD',fdataAtendimento)+'</ansTISS:dataAtendimento>'); end; Writeln(arquivo,'<ansTISS:procedimento>'); if FTissReq.UsarCodigoTabela then Writeln(arquivo,'<ansTISS:codigoTabela>'+FormatFloat('00',fCodigoTabela)+'</ansTISS:codigoTabela>'); if FTissReq.UsarCodProc then Writeln(arquivo,'<ansTISS:codigoProcedimento>'+TiraMascara(FCodProc)+'</ansTISS:codigoProcedimento>'); Writeln(arquivo,'</ansTISS:procedimento>'); if FTissReq.UsarTipoConsulta then Writeln(arquivo,'<ansTISS:tipoConsulta>'+FTipoConsulta+'</ansTISS:tipoConsulta>'); if FTissReq.UsarTipoSaidaa then Writeln(arquivo,'<ansTISS:tipoSaida>'+FTipoSaida+'</ansTISS:tipoSaida>'); Writeln(arquivo,'</ansTISS:dadosAtendimento>'); if FTissReq.UsarObs then Writeln(arquivo,'<ansTISS:observacao>'+FObs+'</ansTISS:observacao>'); Writeln(arquivo,'</ansTISS:guiaConsulta>'); CloseFile(arquivo); except on e: Exception do begin Application.MessageBox(PChar('Erro ao criar arquivo:'+#13+e.Message),'ATENÇÃO',MB_OK+MB_ICONERROR); end; end; end; function TTissConsulta.arqvalidado: Boolean; begin result := Fvalidado; end; constructor TTissConsulta.create(Aowner: TComponent); begin FZerosArq := 20; FEncoding:='ISO-8859-1'; FVersaoXml:='1.0'; FVersaoTISS:='2.02.03'; FTipo:=Juridico; FMensagemTissXml:='xmlns="http://www.w3.org/2001/XMLSchema" xmlns:ansTISS="http://www.ans.gov.br/padroes/tiss/schemas"'; FTissReq := TTissReq.Create; FCompVersao := TCompVersao.create; FTissValid := TTissValidacao.create; FFontePadora := TTissIdentFontPag.Create; FAnsVersaoxsd := v2_02_03; // FBusca := TBusca.Create(self); inherited; end; { TTissConsulta } procedure TTissConsulta.criaCabecalho; var arquivo: TextFile; begin DecimalSeparator := '.'; if Trim(FArquivo) = '' then begin Application.MessageBox('Informe o arquivo xml a ser criado!!!','ATENÇÃO',MB_OK+MB_ICONEXCLAMATION); Abort; end; try AssignFile(arquivo,FArquivo); Rewrite(arquivo); Append(arquivo); Writeln(arquivo,'<?xml version="'+FVersaoXml+'" encoding="'+FEncoding+'" ?>'); Writeln(arquivo,'<ansTISS:mensagemTISS '+FMensagemTissXml+'>'); Writeln(arquivo,'<ansTISS:cabecalho>'); //TAG IDENTIFICAÇÃO DA TRANSAÇÃO Writeln(arquivo,'<ansTISS:identificacaoTransacao>'); Writeln(arquivo,'<ansTISS:tipoTransacao>'+FTipoTrans+'</ansTISS:tipoTransacao>'); if FTissReq.UsarSequencialTrans then Writeln(arquivo,'<ansTISS:sequencialTransacao>'+FSequencialTrans+'</ansTISS:sequencialTransacao>'); if FTissReq.UsarDataRegistroTrans then begin if FAnsVersaoxsd = v2_01_03 then Writeln(arquivo,'<ansTISS:dataRegistroTransacao>'+FormatDateTime('DD/MM/YYYY',FDataRegistroTrans)+'</ansTISS:dataRegistroTransacao>') else Writeln(arquivo,'<ansTISS:dataRegistroTransacao>'+FormatDateTime('YYYY-MM-DD',FDataRegistroTrans)+'</ansTISS:dataRegistroTransacao>'); end; if FTissReq.UsarHoraRegistroTrans then begin if FAnsVersaoxsd = v2_01_03 then Writeln(arquivo,'<ansTISS:horaRegistroTransacao>'+FormatDateTime('hh:mm',FHoraRegistroTrans)+'</ansTISS:horaRegistroTransacao>') else Writeln(arquivo,'<ansTISS:horaRegistroTransacao>'+FormatDateTime('hh:mm:ss',FHoraRegistroTrans)+'</ansTISS:horaRegistroTransacao>'); end; Writeln(arquivo,'</ansTISS:identificacaoTransacao>'); //TAG ORIGEM Writeln(arquivo,'<ansTISS:origem>'); Writeln(arquivo,'<ansTISS:codigoPrestadorNaOperadora>'); if FTissReq.UsarCNPJCPF then begin if FTipo = Juridico then Writeln(arquivo,'<ansTISS:CNPJ>'+FCNPJCPF+'</ansTISS:CNPJ>'); if FTipo = Fisico then Writeln(arquivo,'<ansTISS:CPF>'+FCNPJCPF+'</ansTISS:CPF>'); if FTipo = Outro then Writeln(arquivo,'<ansTISS:codigoPrestadorNaOperadora>'+FCNPJCPF+'</ansTISS:codigoPrestadorNaOperadora>'); end; // mmCabecalho.Lines.Add('<ansTISS:codigoPrestadorNaOperadora>'+fdsFaturamentoREGPRESTADORA.AsString+'</ansTISS:codigoPrestadorNaOperadora>'); Writeln(arquivo,'</ansTISS:codigoPrestadorNaOperadora>'); Writeln(arquivo,'</ansTISS:origem>'); Writeln(arquivo,'<ansTISS:destino>'); if FTissReq.UsarRegANS then Writeln(arquivo,'<ansTISS:registroANS>'+fRegANS+'</ansTISS:registroANS>'); Writeln(arquivo,'</ansTISS:destino>'); Writeln(arquivo,'<ansTISS:versaoPadrao>'+FVersaoTISS+'</ansTISS:versaoPadrao>'); // identificacao Software Gerador case ansVersaoXSD of v2_02_02,v2_02_03: begin Writeln(arquivo,'<ansTISS:identificacaoSoftwareGerador>'); Writeln(arquivo,'<ansTISS:nomeAplicativo>'+FNomeAplica+'</ansTISS:nomeAplicativo>'); Writeln(arquivo,'<ansTISS:versaoAplicativo>'+FVersaoAplica+'</ansTISS:versaoAplicativo>'); Writeln(arquivo,'<ansTISS:fabricanteAplicativo>'+FFabricaAplica+'</ansTISS:fabricanteAplicativo>'); Writeln(arquivo,'</ansTISS:identificacaoSoftwareGerador>'); end; end; Writeln(arquivo,'</ansTISS:cabecalho>'); Writeln(arquivo,'<ansTISS:prestadorParaOperadora>'); Writeln(arquivo,'<ansTISS:loteGuias>'); if FTissReq.UsarNumLote then Writeln(arquivo,'<ansTISS:numeroLote>'+FNumLote+'</ansTISS:numeroLote>'); Writeln(arquivo,'<ansTISS:guias>'); Writeln(arquivo,'<ansTISS:guiaFaturamento>'); CloseFile(arquivo); except on e: Exception do begin Application.MessageBox(PChar('Erro ao acessar arquivo:'+#13+e.Message),'ATENÇÃO',MB_OK+MB_ICONERROR); end; end; end; procedure TTissConsulta.criaRodape; var arquivo,arquivoTemp: TextFile; numhash,linha,nomeArq: string; TrocaString: TStringList; begin try Fvalidado := False; AssignFile(arquivo,FArquivo); Append(arquivo); Writeln(arquivo,'</ansTISS:guiaFaturamento>'); Writeln(arquivo,'</ansTISS:guias>'); Writeln(arquivo,'</ansTISS:loteGuias>'); Writeln(arquivo,'</ansTISS:prestadorParaOperadora>'); Writeln(arquivo,'</ansTISS:mensagemTISS>'); CloseFile(arquivo); AssignFile(arquivoTemp,'temp.xml'); Rewrite(arquivoTemp); numhash := hash(FArquivo); AssignFile(arquivo,FArquivo); Reset(arquivo); while not Eof(arquivo) do begin Readln(arquivo,linha); if (linha <> '</ansTISS:mensagemTISS>') and (linha <> '</ans:mensagemTISS>') then Writeln(arquivotemp,linha); end; CloseFile(arquivo); //TAG EPILOGO Writeln(arquivotemp,'<ansTISS:epilogo>'); Writeln(arquivotemp,'<ansTISS:hash>'+numhash+'</ansTISS:hash>'); Writeln(arquivotemp,'</ansTISS:epilogo>'); Writeln(arquivotemp,'</ansTISS:mensagemTISS>'); CloseFile(arquivoTemp); AssignFile(arquivoTemp,'temp.xml'); Reset(arquivoTemp); AssignFile(arquivo,FArquivo); Rewrite(arquivo); while not Eof(arquivoTemp) do begin Readln(arquivoTemp,linha); Writeln(arquivo,linha); end; CloseFile(arquivo); CloseFile(arquivoTemp); {Troca String <ansTISS></ansTISS> por <ans></ans> para as Versões 2.01.03,2.02.01} if (FAnsVersaoxsd <> v2_02_02) and (FAnsVersaoxsd <> v2_02_03)then begin TrocaString := TStringList.Create; TrocaString.Clear; try TrocaString.LoadFromFile(TissArquivo); TrocaString.Text := StringReplace(TrocaString.Text,'ansTISS','ans',[rfignorecase,rfreplaceall]); TrocaString.SaveToFile(TissArquivo); finally TrocaString.Free; end; end; except on e: Exception do begin Application.MessageBox(PChar('Erro ao acessar arquivo:'+#13+e.Message),'ATENÇÃO',MB_OK+MB_ICONERROR); end; end; if FTissValid.UsarValidacao then begin if Trim(FTissValid.TissXSD) = EmptyStr then begin Application.MessageBox('Para realizar a validação informe o Schema','ATENÇÃO',MB_OK+MB_ICONERROR); Abort; end else begin if not (FileExists(Trim(FTissValid.TissXSD))) then begin Application.MessageBox('Não foi possível encontrar o Schema para Validação','ATENÇÃO',MB_OK+MB_ICONERROR); Abort; end end; try Application.CreateForm(TfrmValida,frmValida); with frmValida do begin if FileExists(TissArquivo) then begin Memo1.Text := fileValidate(TissArquivo,FTissValid.TissXSD); if ( Memo1.Text = EmptyStr ) then begin lblInfo.Caption := MSG_ISVALID_PTBR; lblInfo.Font.Color := clGreen; Fvalidado := True; end else begin lblInfo.Caption := MSG_ISNTVALID_PTBR; lblInfo.Font.Color := clRed; Fvalidado := True; end; end; end; frmValida.ShowModal; finally FreeAndNil(frmValida); end; end; if TissConfig.UsarArqNomeHash then begin try if not TissConfig.UsarNomeArq then begin RenameFile(FArquivo,ExtractFilePath(FArquivo)+RetZero(TissSequencialTrans,TissZerosArq)+'_'+ numhash+'.xml'); TissArquivo := ExtractFilePath(FArquivo)+RetZero(TissSequencialTrans,TissZerosArq)+'_'+ numhash+'.xml'; end else begin nomearq := copy(ExtractFileName(FArquivo),1,length(ExtractFileName(FArquivo))-4); RenameFile(FArquivo,nomeArq + ExtractFilePath(FArquivo)+RetZero(TissSequencialTrans,TissZerosArq)+'_'+ numhash+'.xml'); TissArquivo := nomeArq + ExtractFilePath(FArquivo)+RetZero(TissSequencialTrans,TissZerosArq)+'_'+ numhash+'.xml'; end; except on e:exception do begin Application.MessageBox(Pchar('Erro ao renomear o arquivo: '+ #13+ e.Message),'ATENÇÃO',MB_OK+MB_ICONERROR); end; end; end; end; function TTissConsulta.hash(arquivohash:string): String; var arquivo: TextFile; MD5: TMD5; xml: TXMLDocument; TrocaString: TStringList; begin {Troca String <ansTISS></ansTISS> por <ans></ans> para as Versões 2.01.03,2.02.01} if (FAnsVersaoxsd <> v2_02_02) and (FAnsVersaoxsd <> v2_02_03)then begin TrocaString := TStringList.Create; TrocaString.Clear; try TrocaString.LoadFromFile(arquivohash); TrocaString.Text := StringReplace(TrocaString.Text,'ansTISS','ans',[rfignorecase,rfreplaceall]); TrocaString.SaveToFile(arquivohash); finally TrocaString.Free; end; end; try MD5 := TMD5.Create; xml := TXMLDocument.Create(self); xml.FileName := arquivohash; xml.Active := True; Result :=LowerCase(md5.GeraHash(xml)); xml.Active := False; finally FreeAndNil(MD5); FreeAndNil(xml); end; end; function TTissConsulta.RegANS: String; begin end; procedure TTissConsulta.setDataEmis(const Value: TDateTime); begin FDataEmis := Value; end; procedure TTissConsulta.setAnsVersaoxsd(const Value: TTissAnsVersao); begin FAnsVersaoxsd := Value; end; procedure TTissConsulta.setArquivo(const Value: String); begin FArquivo := Value; end; procedure TTissConsulta.setCBOS(const Value: String); begin fCBOS := Value; end; procedure TTissConsulta.setCEP(const Value: String); begin fCEP := Value; end; procedure TTissConsulta.setCIDCodDiag(const Value: String); begin fCIDCodDiag := Value; end; procedure TTissConsulta.setCIDDescDiag(const Value: String); begin fCIDDescDiag := Value; end; procedure TTissConsulta.setCIDNomeTab(const Value: String); begin fCIDNomeTab := Value; end; procedure TTissConsulta.setCNES(const Value: Currency); begin fCNES := Value; end; procedure TTissConsulta.setCNPJCPF(const Value: String); begin FCNPJCPF := Value; end; procedure TTissConsulta.setcodigoIBGE(const Value: Currency); begin FcodigoIBGE := Value; end; procedure TTissConsulta.setCodigoTabela(const Value: Integer); begin fCodigoTabela := Value; end; procedure TTissConsulta.setCodProc(const Value: String); begin FCodProc := Value; end; procedure TTissConsulta.setComplemento(const Value: String); begin FComplemento := Value; end; procedure TTissConsulta.setdataAtendimento(const Value: TDateTime); begin fdataAtendimento := Value; end; procedure TTissConsulta.setDataRegistroTrans(const Value: TDateTime); begin FDataRegistroTrans := Value; end; procedure TTissConsulta.setEncoding(const Value: String); begin FEncoding := Value; end; procedure TTissConsulta.setEndNum(const Value: String); begin FEndNum := Value; end; procedure TTissConsulta.setEvolucaoValor(const Value: Currency); begin FEvolucaoValor := Value; end; procedure TTissConsulta.setFArqNomeHash(const Value: Boolean); begin FArqNomeHash := Value; end; procedure TTissConsulta.SetFontePagora(const Value: TTissIdentFontPag); begin FFontePadora := Value; end; procedure TTissConsulta.setHoraRegistroTrans(const Value: TDateTime); begin FHoraRegistroTrans := value; end; procedure TTissConsulta.setIndicAcid(const Value: String); begin FIndicAcid := Value; end; procedure TTissConsulta.setLogradouro(const Value: String); begin FLogradouro := Value; end; procedure TTissConsulta.setMEDICO(const Value: String); begin FMedico := Value; end; procedure TTissConsulta.setMensagemTissXml(const Value: String); begin FMensagemTissXml := Value; end; procedure TTissConsulta.setMunicipio(const Value: String); begin FMunicipio := Value; end; procedure TTissConsulta.setNomeContradado(const Value: String); begin FNomeContradado := Value; end; procedure TTissConsulta.setNomePlano(const Value: String); begin FNomePlano := Value; end; procedure TTissConsulta.setNumCarteira(const Value: String); begin FNumCarteira := Value; end; procedure TTissConsulta.setNumCNS(const Value: String); begin FNumCNS := Value; end; procedure TTissConsulta.setNUMEROCONSELHO(const Value: String); begin fNUMEROCONSELHO := Value; end; procedure TTissConsulta.setNumPres(const Value: String); begin FNumPres := Value; end; procedure TTissConsulta.setNumGuia(const Value: String); begin FNumGuia := Value; end; procedure TTissConsulta.setNumLote(const Value: String); begin FNumLote := Value; end; procedure TTissConsulta.setObs(const Value: String); begin FObs := Value; end; procedure TTissConsulta.setPaciente(const Value: String); begin FPaciente := Value; end; procedure TTissConsulta.setRegANS(const Value: String); begin FRegANS := Value; end; procedure TTissConsulta.setSequencialTrans(const Value: String); begin FSequencialTrans := Value; end; procedure TTissConsulta.setSIGLACONSELHO(const Value: String); begin fSIGLACONSELHO := Value; end; procedure TTissConsulta.setTipDoenca(const Value: String); begin FTipDoenca := Value; end; procedure TTissConsulta.setTipo(const Value: Tpessoa); begin FTipo := Value; end; procedure TTissConsulta.setTipoConsulta(const Value: String); begin FTipoConsulta := Value; end; procedure TTissConsulta.settipoLogradouro(const Value: String); begin FtipoLogradouro := Value; end; procedure TTissConsulta.setTipoSaida(const Value: String); begin FTipoSaida := Value; end; procedure TTissConsulta.setTipoTrans(const Value: String); begin FTipoTrans := Value; end; procedure TTissConsulta.setUF(const Value: String); begin FUF := Value; end; procedure TTissConsulta.setUFCONSELHO(const Value: String); begin fUFCONSELHO := Value; end; procedure TTissConsulta.setUnidTemp(const Value: String); begin FUnidTemp := Value; end; procedure TTissConsulta.setValidadeCart(const Value: TDateTime); begin FValidadeCart := Value; end; procedure TTissConsulta.setvalidado(const Value: Boolean); begin Fvalidado := Value; end; procedure TTissConsulta.setVersaoTISS(const Value: String); begin FVersaoTISS := Value; end; procedure TTissConsulta.setNomeAplica(const Value: String); begin FNomeAplica := Value; end; procedure TTissConsulta.setVersaoAplica(const Value: String); begin FVersaoAplica := Value; end; procedure TTissConsulta.setFabricaAplica(const Value: String); begin FFabricaAplica := Value; end; procedure TTissConsulta.setVersaoXml(const Value: String); begin FVersaoXml := Value; end; procedure TTissConsulta.SetZerosArq(const Value: integer); begin FZerosArq := Value; end; function TTissConsulta.TiraMascara(Texto: String): String; var aux: string; i: integer; begin Aux := ''; for i :=1 to Length(Texto) do begin if (texto[i] in ['0'..'9']) then begin Aux := Aux + copy(texto,i,1); end; end; Result := Aux; end; procedure TTissConsulta.Verifica; begin {if FTissReq.UsarCBOS = True then begin if fCBOS = 0 then begin Application.MessageBox('Informe o CBOS','ATENÇÃO',MB_OK+MB_ICONEXCLAMATION); Abort; end; end; //TA EM FASE DE DESENVOLVIMENTO ESTA ROTINA {FComplemento:= True; FNomeContradado:= True; FHoraRegistroTrans:= True; fCNES:= True; FTissReq:= True; FMedico:= True; FValidadeCart:= True; fCEP:= True; FCNPJCPF:= True; FTipo:= True; FNumLote:= True; FCodProc:= True; fCIDCodDiag:= True; fCodigoTabela:= True; FTipoSaida:= True; FMunicipio:= True; FtipoLogradouro:= True; fCIDNomeTab:= True; FSequencialTrans:= True; fSIGLACONSELHO:= True; FNomePlano:= True; FDataRegistroTrans:= True; FRegANS:= True; FTipoConsulta:= True; FEndNum:= True; FNumCNS:= True; FNumGuia:= True; FUF:= True; FPaciente:= True; fUFCONSELHO:= True; fCIDDescDiag:= True; FNumCarteira:= True; FcodigoIBGE:= True; FLogradouro:= True; fNUMEROCONSELHO:= True; fdataAtendimento:= True; FTipoTrans:= True;} end; end.
unit diskfont; // unit diskfont for morphos {$UNITPATH ../Trinity/} {$PACKRECORDS 2} interface uses TriniTypes, Exec, AGraphics; const MAXFONTPATH = 256; type PFontContents = ^TFontContents; TFontContents = record fc_FileName : packed array[0..MAXFONTPATH-1] of char; fc_YSize : UWORD; fc_Style : UBYTE; fc_Flags : UBYTE; end; PTFontContents = ^TTFontContents; TTFontContents = record tfc_FileName : packed array[0..MAXFONTPATH-3] of char; tfc_TagCount : UWORD; tfc_YSize : UWORD; tfc_Style : UBYTE; tfc_Flags : UBYTE; end; const FCH_ID = $0f00; TFCH_ID = $0f02; OFCH_ID = $0f03; type PFontContentsHeader = ^TFontContentsHeader; TFontContentsHeader = record fch_FileID : UWORD; fch_NumEntries : UWORD; end; const DFH_ID = $0f80; MAXFONTNAME = 32; type PDiskFontHeader = ^TDiskFontHeader; TDiskFontHeader = record dfh_DF : TNode; dfh_FileID : UWORD; dfh_Revision : UWORD; dfh_Segment : SLONG; dfh_Name : packed array [0..MAXFONTNAME-1] of char; dfh_TF : TTextFont; end; //const // dfh_TagList dfh_Segment const AFB_MEMORY = 0; AFF_MEMORY = (1 shl AFB_MEMORY); AFB_DISK = 1; AFF_DISK = (1 shl AFB_DISK); AFB_SCALED = 2; AFF_SCALED = (1 shl AFB_SCALED); AFB_BITMAP = 3; AFF_BITMAP = (1 shl AFB_BITMAP); AFB_TAGGED = 16; AFF_TAGGED = (1 shl AFB_TAGGED); type PAvailFonts = ^TAvailFonts; TAvailFonts = record af_Type : UWORD; af_Attr : TTextAttr; end; PTAvailFonts = ^TTAvailFonts; TTAvailFonts = record taf_Type : UWORD; taf_Attr : TTextAttr; end; PAvailFontsHeader = ^TAvailFontsHeader; TAvailFontsHeader = record afh_NumEntries: UWORD; end; const DISKFONTNAME : PChar = 'diskfont.library'; var DiskfontBase : pLibrary; function OpenDiskFont(textAttr: pTextAttr location 'a0'): pTextFont; syscall DiskfontBase 030; function AvailFonts(buffer: STRPTR location 'a0'; bufBytes: SLONG location 'd0'; flags: SLONG location 'd1'): SLONG; syscall DiskfontBase 036; function NewFontContents(fontsLock: BPTR location 'a0'; fontName: STRPTR location 'a1'): pFontContentsHeader; syscall DiskfontBase 042; procedure DisposeFontContents(fontContentsHeader: pFontContentsHeader location 'a1'); syscall DiskfontBase 048; function NewScaledDiskFont(sourceFont: pTextFont location 'a0'; destTextAttr: pTextAttr location 'a1'): pDiskFontHeader; syscall DiskfontBase 054; //*** V45 ***/ function GetDiskFontCtrl(tagid: SLONG location 'd0'): SLONG; syscall DiskfontBase 060; procedure SetDiskFontCtrlA(taglist: pTagItem location 'a0'); syscall DiskfontBase 066; // Varargs version procedure SetDiskFontCtrl(tagArray: array of ULONG); implementation procedure SetDiskFontCtrl(tagArray: array of ULONG); begin SetDiskFontCtrlA(@tagArray); end; end.
{Hint: save all files to location: C:\adt32\eclipse\workspace\AppSMSDemo1\jni } unit unit1; {$mode delphi} interface uses Classes, SysUtils, And_jni, And_jni_Bridge, Laz_And_Controls, Laz_And_Controls_Events, AndroidWidget, broadcastreceiver; type { TAndroidModule1 } TAndroidModule1 = class(jForm) jBroadcastReceiver1: jBroadcastReceiver; jBroadcastReceiver2: jBroadcastReceiver; jButton1: jButton; jEditText1: jEditText; jEditText2: jEditText; jEditText3: jEditText; jSMS1: jSMS; jTextView1: jTextView; jTextView2: jTextView; jTextView3: jTextView; jTextView4: jTextView; procedure AndroidModule1JNIPrompt(Sender: TObject); procedure AndroidModule1RequestPermissionResult(Sender: TObject; requestCode: integer; manifestPermission: string; grantResult: TManifestPermissionResult); procedure jBroadcastReceiver1Receiver(Sender: TObject; intent: jObject); procedure jBroadcastReceiver2Receiver(Sender: TObject; intent: jObject); procedure jButton1Click(Sender: TObject); private {private declarations} public {public declarations} end; var AndroidModule1: TAndroidModule1; implementation {$R *.lfm} { TAndroidModule1 } procedure TAndroidModule1.jButton1Click(Sender: TObject); begin if IsRuntimePermissionGranted('android.permission.SEND_SMS') then begin if jSMS1.Send(jEditText1.Text, jEditText2.Text, 'com.example.appsmsdemo1.SMS_DELIVERED') >= 1 then //warning: for message mult-parts return "parts_count" [thanks to CC!] ShowMessage('Message Sending .... OK!') else ShowMessage('Message Sending .... Fail!'); end else ShowMessage('Sorry... Runtime [SEND_SMS] Permission NOT Granted ...'); jEditText2.Text:= ''; end; procedure TAndroidModule1.AndroidModule1JNIPrompt(Sender: TObject); var manifestPermissions: TDynArrayOfString; begin //https://developer.android.com/guide/topics/security/permissions#normal-dangerous //https://www.captechconsulting.com/blogs/runtime-permissions-best-practices-and-how-to-gracefully-handle-permission-removal if IsRuntimePermissionNeed() then // that is, target API >= 23 begin ShowMessage('RequestRuntimePermission....'); SetLength(manifestPermissions, 3); manifestPermissions[0]:= 'android.permission.RECEIVE_SMS'; //from AndroodManifest.xml manifestPermissions[1]:= 'android.permission.SEND_SMS'; //from AndroodManifest.xml // required for sms send otherwise error is occured on my device - elera manifestPermissions[2]:= 'android.permission.READ_PHONE_STATE'; Self.RequestRuntimePermission(manifestPermissions, 2001); SetLength(manifestPermissions, 0); end; jEditText1.SetFocus; end; procedure TAndroidModule1.AndroidModule1RequestPermissionResult( Sender: TObject; requestCode: integer; manifestPermission: string; grantResult: TManifestPermissionResult); begin case requestCode of //android.permission.RECEIVE_SMS 2001:begin if grantResult = PERMISSION_GRANTED then begin ShowMessage('Success! ['+manifestPermission+'] Permission granted!!! ' ); if manifestPermission = 'android.permission.RECEIVE_SMS' then jBroadcastReceiver1.RegisterIntentActionFilter('android.provider.Telephony.SMS_RECEIVED'); //register custom app action to retrieve DELIVERED status if manifestPermission = 'android.permission.SEND_SMS' then jBroadcastReceiver2.RegisterIntentActionFilter('com.example.appsmsdemo1.SMS_DELIVERED'); end else//PERMISSION_DENIED ShowMessage('Sorry... ['+manifestPermission+'] permission not granted... ' ) end; end; end; procedure TAndroidModule1.jBroadcastReceiver1Receiver(Sender: TObject; intent: jObject); var smsCaller, smsReceived, smsBody: string; auxList: TStringList; begin if IsRuntimePermissionGranted('android.permission.RECEIVE_SMS') then begin ShowMessage('New Message Receiving ....'); smsReceived:= jSMS1.Read(intent, '#'); if smsReceived <> '' then begin auxList:= TStringList.Create; auxList.Delimiter:= '#'; auxList.StrictDelimiter:= True; auxList.DelimitedText:= smsReceived; if auxList.Count > 1 then; begin smsCaller:= auxList.Strings[0]; smsBody:= auxList.Strings[1]; jEditText3.AppendLn('['+ smsCaller+']'); jEditText3.AppendLn(smsBody); jEditText3.AppendLn(' '); end; auxList.Free; end; end else ShowMessage('Sorry.. Runtime [RECEIVE_SMS] Permission NOT Granted ...'); end; //DELIVERED status procedure TAndroidModule1.jBroadcastReceiver2Receiver(Sender: TObject; intent: jObject); begin if (jBroadcastReceiver(Sender).GetResultCode() = RESULT_OK then //ok ShowMessage('Ok. SMS delivered !!') else ShowMessage('Sorry... SMS Not delivered...') end; end.
unit Authentication; interface uses Storage; type /// <summary> /// Класс хранящий информацию о текущем пользователе /// </summary> /// <remarks> /// </remarks> TUser = class strict private class var FLocal: boolean; class var FLocalMaxAtempt: Byte; private FSession: String; FLogin: String; procedure SetLocal(const Value: Boolean); function GetLocal: Boolean; procedure SetLocalMaxAtempt(const Value: Byte = 10); function GetLocalMaxAtempt: Byte; public property Session: String read FSession; Property Local: Boolean read GetLocal Write SetLocal; Property LocalMaxAtempt: Byte read GetLocalMaxAtempt Write SetLocalMaxAtempt; property Login: String read FLogin; constructor Create(ASession: String; ALogin: String = ''; ALocal: Boolean = false); end; /// <summary> /// Класс аутентификации пользователя /// </summary> /// <remarks> /// </remarks> TAuthentication = class /// <summary> /// Проверка логина и пароля. В случае успеха возвращает данные о пользователе. /// </summary> class function CheckLogin(pStorage: IStorage; const pUserName, pPassword: string; var pUser: TUser; ANeedShowException: Boolean = True): boolean; // Получить список логинов с сервера class function GetLoginList(pStorage: IStorage): string; class function spCheckGoogleOTPAuthent (pStorage: IStorage; const pSession, pProjectName, pUserName, pGoogleSecret: string; ANeedShowException: Boolean = True): boolean; end; implementation uses iniFiles, Xml.XMLDoc, UtilConst, SysUtils, IdIPWatch, Xml.XmlIntf, CommonData, WinAPI.Windows, vcl.Forms, vcl.Dialogs, dsdAction, GoogleOTPRegistration, GoogleOTPDialogPsw; {------------------------------------------------------------------------------} function GetIniFile(out AIniFileName: String):boolean; const FileName: String = '\Boutique.ini'; var dir: string; f: TIniFile; Begin result := False; dir := ExtractFilePath(Application.exeName)+'ini'; AIniFileName := dir + FileName; // if not DirectoryExists(dir) AND not ForceDirectories(dir) then Begin ShowMessage('Пользователь не может получить доступ к файлу настроек:'+#13 + AIniFileName+#13 + 'Дальнейшая работа программы невозможна.'+#13 + 'Обратитесь к администратору.'); exit; End; // if not FileExists (AIniFileName) then Begin f := TiniFile.Create(AIniFileName); try try F.WriteString('Common','BoutiqueName',''); Except ShowMessage('Пользователь не может получить доступ к файлу настроек:'+#13 + AIniFileName+#13 + 'Дальнейшая работа программы невозможна.'+#13 + 'Обратитесь к администратору.'); exit; end; finally f.Free; end; end; // result := True; End; {------------------------------------------------------------------------------} constructor TUser.Create(ASession: String; ALogin: String = ''; ALocal: Boolean = false); begin FSession := ASession; FLocal := ALocal; FLogin := ALogin; end; {------------------------------------------------------------------------------} class function TAuthentication.spCheckGoogleOTPAuthent (pStorage: IStorage; const pSession, pProjectName, pUserName, pGoogleSecret: string; ANeedShowException: Boolean = True): boolean; var GoogleSecret: string; N: IXMLNode; pXML : String; begin Result := True; // Genegate and registretion GoogleSecret if pGoogleSecret = '' then begin with TGoogleOTPRegistrationForm.Create(nil) do try Result:= Execute (pProjectName, pUserName, GoogleSecret); finally Free; end; end else GoogleSecret := pGoogleSecret; if not Result OR (GoogleSecret = '') then Exit; // Validate Pas with TGoogleOTPDialogPswForm.Create(nil) do try Result:= Execute (pStorage, pSession, GoogleSecret); finally Free; end; if Result and (pGoogleSecret <> GoogleSecret) then begin pXML := '<xml Session = "' + pSession + '" >' + '<gpUpdate_Object_User_GoogleSecret OutputType="otResult">' + '<inGoogleSecret DataType="ftString" Value="%s" />' + '</gpUpdate_Object_User_GoogleSecret>' + '</xml>'; N := LoadXMLData(pStorage.ExecuteProc(Format(pXML, [GoogleSecret]), False, 4, TRUE)).DocumentElement; // Result:= Assigned(N); end; end; {------------------------------------------------------------------------------} class function TAuthentication.CheckLogin(pStorage: IStorage; const pUserName, pPassword: string; var pUser: TUser; ANeedShowException: Boolean = True): boolean; var IP_str:string; N: IXMLNode; pXML : String; BoutiqueName, IniFileName, S, ProjectName: String; f: TIniFile; isBoutique, isProject : Boolean; begin //ловим ProjectTest.exe S:= ExtractFileName(ParamStr(0)); // isBoutique:= (AnsiUpperCase(gc_ProgramName) = AnsiUpperCase('Boutique.exe')) or(AnsiUpperCase(gc_ProgramName) = AnsiUpperCase('Boutique_Demo.exe')); // isProject:= (AnsiUpperCase(gc_ProgramName) = AnsiUpperCase('Project.exe')) and (UpperCase(S) <> UpperCase('ProjectTest.exe')) ; if Pos('.', gc_ProgramName) > 0 then ProjectName := Copy(gc_ProgramName, 1, Pos('.', gc_ProgramName) - 1) else ProjectName := gc_ProgramName; {создаем XML вызова процедуры на сервере} if isBoutique = TRUE then begin // if GetIniFile (IniFileName) then try BoutiqueName:= ''; f := TiniFile.Create(IniFileName); BoutiqueName:= f.ReadString('Common','BoutiqueName',''); finally f.Free; end else begin result:=false; exit; end; // для Бутиков - еще 1 параметр pXML := '<xml Session = "" >' + '<gpCheckLogin OutputType="otResult">' + '<inUserLogin DataType="ftString" Value="%s" />' + '<inUserPassword DataType="ftString" Value="%s" />' + '<inIP DataType="ftString" Value="%s" />' + '<inBoutiqueName DataType="ftString" Value="%s" />' + '</gpCheckLogin>' + '</xml>'; end else // для Project - еще 2 параметра - для Google Authenticator if isProject = TRUE then pXML := '<xml Session = "" >' + '<gpCheckLogin OutputType="otResult">' + '<inUserLogin DataType="ftString" Value="%s" />' + '<inUserPassword DataType="ftString" Value="%s" />' + '<inIP DataType="ftString" Value="%s" />' + '<ioisGoogleOTP DataType="ftBoolean" Value="%s" />' + '<ioGoogleSecret DataType="ftString" Value="%s" />' + '</gpCheckLogin>' + '</xml>' else if POS(AnsiUpperCase('Farmacy'), AnsiUpperCase(ProjectName)) = 1 then pXML := '<xml Session = "" >' + '<gpCheckLogin OutputType="otResult">' + '<inUserLogin DataType="ftString" Value="%s" />' + '<inUserPassword DataType="ftString" Value="%s" />' + '<inIP DataType="ftString" Value="%s" />' + '<inProjectName DataType="ftString" Value="%s" />' + '</gpCheckLogin>' + '</xml>' else pXML := '<xml Session = "" >' + '<gpCheckLogin OutputType="otResult">' + '<inUserLogin DataType="ftString" Value="%s" />' + '<inUserPassword DataType="ftString" Value="%s" />' + '<inIP DataType="ftString" Value="%s" />' + '</gpCheckLogin>' + '</xml>'; with TIdIPWatch.Create(nil) do begin Active:=true; IP_str:=LocalIP; Free; end; if isBoutique = TRUE then // для Бутиков - еще 1 параметр N := LoadXMLData(pStorage.ExecuteProc(Format(pXML, [pUserName, pPassword, IP_str, BoutiqueName]), False, 4, ANeedShowException)).DocumentElement else if isProject = TRUE then // для Project - еще еще 2 параметра - для Google Authenticator N := LoadXMLData(pStorage.ExecuteProc(Format(pXML, [pUserName, pPassword, IP_str, 'False', '']), False, 4, ANeedShowException)).DocumentElement else if POS(AnsiUpperCase('Farmacy'), AnsiUpperCase(ProjectName)) = 1 then N := LoadXMLData(pStorage.ExecuteProc(Format(pXML, [pUserName, pPassword, IP_str, ProjectName]), False, 4, ANeedShowException)).DocumentElement else N := LoadXMLData(pStorage.ExecuteProc(Format(pXML, [pUserName, pPassword, IP_str]), False, 4, ANeedShowException)).DocumentElement; // result := TRUE; // if Assigned(N) then begin // Google Authenticator if (isProject = TRUE) and N.GetAttribute(AnsiLowerCase('ioisGoogleOTP')) then result := spCheckGoogleOTPAuthent(pStorage, N.GetAttribute(AnsiLowerCase(gcSession)), ProjectName, pUserName, N.GetAttribute(AnsiLowerCase('ioGoogleSecret')), ANeedShowException); // pUser := TUser.Create(N.GetAttribute(AnsiLowerCase(gcSession))); pUser.FLogin := pUserName; end; // if result = FALSE then pUser:= nil; // result := (pUser <> nil); end; {------------------------------------------------------------------------------} class function TAuthentication.GetLoginList(pStorage: IStorage): string; var N: IXMLNode; pXML : String; begin Result := ''; {создаем XML вызова процедуры на сервере} pXML := '<xml Session = "" >' + '<gpSelect_Object_UserLogin OutputType="otResult">' + '</gpSelect_Object_UserLogin>' + '</xml>'; N := LoadXMLData(pStorage.ExecuteProc(pXML, False, 2, False)).DocumentElement; // if Assigned(N) then begin Result := N.GetAttribute(AnsiLowerCase('outLogin')); end; end; function TUser.GetLocal: Boolean; begin Result := TUser.FLocal; end; procedure TUser.SetLocal(const Value: Boolean); var I : Integer; F: TForm; begin TUser.FLocal := Value; for I := 0 to Screen.FormCount - 1 do Begin try F := Screen.Forms[I]; if assigned(F) AND (F.Handle <> 0) AND (F.ClassNameIs('TMainCashForm') or F.ClassNameIs('TMainCashForm2')) then PostMessage(F.Handle, UM_LOCAL_CONNECTION,0,0); Except end; End; end; function TUser.GetLocalMaxAtempt: Byte; begin Result := TUser.FLocalMaxAtempt; end; procedure TUser.SetLocalMaxAtempt(const Value: Byte = 10); begin TUser.FLocalMaxAtempt := Value; end; end.
{******************************************} { } { FastReport 5.0 } { UniDAC enduser components } { } // Created by: Devart // E-mail: unidac@devart.com { } {******************************************} unit frxUniDACComponents; interface {$I frx.inc} uses Windows, SysUtils, Classes, frxClass, frxCustomDB, DB, Uni, Graphics, UniDacVcl, frxDACComponents {$IFDEF Delphi6} , Variants {$ENDIF} {$IFDEF QBUILDER} , fqbClass {$ENDIF} ; type TfrxUniDACComponentsClass = class of TfrxUniDACComponents; TUniDACTable = class(TUniTable) protected procedure InitFieldDefs; override; end; TUniDACQuery = class(TUniQuery) protected procedure InitFieldDefs; override; end; TfrxUniDACComponents = class(TfrxDACComponents) private FOldComponents: TfrxDACComponents; function GetDefaultDatabase: TUniConnection; procedure SetDefaultDatabase(Value: TUniConnection); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function GetDescription: string; override; class function GetComponentsBitmap: TBitmap; override; class function GetComponentsName: string; override; class function ResourceName: string; override; class function GetDatabaseClass: TfrxDACDatabaseClass; override; class function GetTableClass: TfrxDACTableClass; override; class function GetQueryClass: TfrxDACQueryClass; override; published property DefaultDatabase: TUniConnection read GetDefaultDatabase write SetDefaultDatabase; end; TfrxUniDACDatabase = class(TfrxDACDatabase) protected function GetPort: integer; procedure SetPort(Value: integer); function GetDatabaseName: string; override; procedure SetDatabaseName(const Value: string); override; function GetProviderName: string; procedure SetProviderName(const Value: string); function GetSpecificOptions: TSpecificOptionsList; procedure SetSpecificOptions(Value: TSpecificOptionsList); public constructor Create(AOwner: TComponent); override; class function GetDescription: string; override; published property LoginPrompt; property DatabaseName; property Username; property Password; property Server; property Port: integer read GetPort write SetPort; property ProviderName: string read GetProviderName write SetProviderName; property Connected; property Params; property SpecificOptions: TSpecificOptionsList read GetSpecificOptions write SetSpecificOptions; end; TfrxUniDACTable = class(TfrxDACTable) private FTable: TUniDACTable; protected procedure SetDatabase(const Value: TfrxDACDatabase); override; procedure SetMaster(const Value: TDataSource); override; procedure SetMasterFields(const Value: string); override; procedure SetIndexFieldNames(const Value: string); override; function GetIndexFieldNames: string; override; function GetTableName: string; override; procedure SetTableName(const Value: string); override; function GetSpecificOptions: TSpecificOptionsList; procedure SetSpecificOptions(Value: TSpecificOptionsList); public constructor Create(AOwner: TComponent); override; class function GetDescription: string; override; property Table: TUniDACTable read FTable; published property Database; property TableName: string read GetTableName write SetTableName; property SpecificOptions: TSpecificOptionsList read GetSpecificOptions write SetSpecificOptions; end; TfrxUniDACQuery = class(TfrxDACQuery) protected procedure SetDatabase(const Value: TfrxDACDatabase); override; function GetSpecificOptions: TSpecificOptionsList; procedure SetSpecificOptions(Value: TSpecificOptionsList); public constructor Create(AOwner: TComponent); override; class function GetDescription: string; override; {$IFDEF QBUILDER} function QBEngine: TfqbEngine; override; {$ENDIF} published property Database; property IndexName; property MasterFields; property SpecificOptions: TSpecificOptionsList read GetSpecificOptions write SetSpecificOptions; end; {$IFDEF QBUILDER} TfrxEngineUniDAC = class(TfrxEngineDAC) public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure ReadFieldList(const ATableName: string; var AFieldList: TfqbFieldList); override; end; {$ENDIF} procedure RegisterDacComponents(Components: TfrxUniDACComponentsClass); procedure UnRegisterDacComponents(Components: TfrxUniDACComponentsClass); var CatBmp: TBitmap; UniDACComponents: TfrxDACComponents; implementation {$R *.res} uses frxUniDACRTTI, {$IFNDEF NO_EDITORS} frxUniDACEditor, {$ENDIF} frxDsgnIntf, frxRes; procedure RegisterDacComponents(Components: TfrxUniDACComponentsClass); begin frxObjects.RegisterCategory(Components.GetComponentsName, Components.GetComponentsBitmap, Components.GetComponentsName + ' Components'); frxObjects.RegisterObject1(Components.GetDatabaseClass, nil, '', Components.GetComponentsName, 0, 37); frxObjects.RegisterObject1(Components.GetTableClass, nil, '', Components.GetComponentsName, 0, 38); frxObjects.RegisterObject1(Components.GetQueryClass, nil, '', Components.GetComponentsName, 0, 39); end; procedure UnRegisterDacComponents(Components: TfrxUniDACComponentsClass); begin frxObjects.UnRegister(Components.GetDatabaseClass); frxObjects.UnRegister(Components.GetTableClass); frxObjects.UnRegister(Components.GetQueryClass); end; { TUniDACTable } procedure TUniDACTable.InitFieldDefs; begin if (TableName <> '') and (Assigned(Connection)) then inherited; end; { TUniDACQuery } procedure TUniDACQuery.InitFieldDefs; begin if (SQL.Text <> '') and Assigned(Connection) then inherited; end; { TfrxUniDACComponents } constructor TfrxUniDACComponents.Create(AOwner: TComponent); begin inherited; FOldComponents := UniDACComponents; UniDACComponents := Self; end; destructor TfrxUniDACComponents.Destroy; begin if UniDACComponents = Self then UniDACComponents := FOldComponents; inherited; end; function TfrxUniDACComponents.GetDefaultDatabase: TUniConnection; begin Result := TUniConnection(FDefaultDatabase); end; procedure TfrxUniDACComponents.SetDefaultDatabase(Value: TUniConnection); begin FDefaultDatabase := Value; end; class function TfrxUniDACComponents.GetComponentsBitmap: TBitmap; begin Result := CatBmp; end; class function TfrxUniDACComponents.GetComponentsName: string; begin Result := 'UniDAC'; end; class function TfrxUniDACComponents.GetDatabaseClass: TfrxDACDatabaseClass; begin Result := TfrxUniDACDatabase; end; class function TfrxUniDACComponents.GetTableClass: TfrxDACTableClass; begin Result := TfrxUniDACTable; end; class function TfrxUniDACComponents.GetQueryClass: TfrxDACQueryClass; begin Result := TfrxUniDACQuery; end; class function TfrxUniDACComponents.ResourceName: string; begin Result := 'FRXUNIDACOBJECTS'; end; function TfrxUniDACComponents.GetDescription: string; begin Result := 'UniDAC'; end; { TfrxUniDACDatabase } constructor TfrxUniDACDatabase.Create(AOwner: TComponent); begin inherited; FDatabase := TUniConnection.Create(nil); Component := FDatabase; end; class function TfrxUniDACDatabase.GetDescription: string; begin Result := 'UniDAC Database'; end; function TfrxUniDACDatabase.GetPort: integer; begin Result := TUniConnection(FDatabase).Port; end; procedure TfrxUniDACDatabase.SetPort(Value: integer); begin TUniConnection(FDatabase).Port := Value; end; function TfrxUniDACDatabase.GetDatabaseName: string; begin Result := TUniConnection(FDatabase).Database; end; procedure TfrxUniDACDatabase.SetDatabaseName(const Value: string); begin TUniConnection(FDatabase).Database := Value; end; function TfrxUniDACDatabase.GetProviderName: string; begin Result := TUniConnection(FDatabase).ProviderName; end; procedure TfrxUniDACDatabase.SetProviderName(const Value: string); begin TUniConnection(FDatabase).ProviderName := Value; end; function TfrxUniDACDatabase.GetSpecificOptions: TSpecificOptionsList; begin Result := TUniConnection(FDatabase).SpecificOptions; end; procedure TfrxUniDACDatabase.SetSpecificOptions(Value: TSpecificOptionsList); begin TUniConnection(FDatabase).SpecificOptions := Value; end; { TfrxUniDACTable } constructor TfrxUniDACTable.Create(AOwner: TComponent); begin FTable := TUniDACTable.Create(nil); DataSet := FTable; SetDatabase(nil); inherited; end; class function TfrxUniDACTable.GetDescription: string; begin Result := 'UniDAC Table'; end; procedure TfrxUniDACTable.SetDatabase(const Value: TfrxDACDatabase); begin inherited; if Value <> nil then FTable.Connection := TUniConnection(Value.Database) else if UniDACComponents <> nil then FTable.Connection := TUniConnection(UniDACComponents.DefaultDatabase) else FTable.Connection := nil; end; function TfrxUniDACTable.GetIndexFieldNames: string; begin Result := FTable.IndexFieldNames; end; function TfrxUniDACTable.GetTableName: string; begin Result := FTable.TableName; end; procedure TfrxUniDACTable.SetIndexFieldNames(const Value: string); begin FTable.IndexFieldNames := Value; end; procedure TfrxUniDACTable.SetTableName(const Value: string); begin FTable.TableName := Value; if Assigned(FTable.Connection) then FTable.InitFieldDefs; end; procedure TfrxUniDACTable.SetMaster(const Value: TDataSource); begin FTable.MasterSource := Value; end; procedure TfrxUniDACTable.SetMasterFields(const Value: string); var MasterNames: string; DetailNames: string; begin GetMasterDetailNames(MasterFields, MasterNames, DetailNames); FTable.MasterFields := MasterNames; FTable.DetailFields := DetailNames; end; function TfrxUniDACTable.GetSpecificOptions: TSpecificOptionsList; begin Result := FTable.SpecificOptions; end; procedure TfrxUniDACTable.SetSpecificOptions(Value: TSpecificOptionsList); begin FTable.SpecificOptions := Value; end; { TfrxUniDACQuery } constructor TfrxUniDACQuery.Create(AOwner: TComponent); begin FQuery := TUniDACQuery.Create(nil); inherited Create(AOwner); end; class function TfrxUniDACQuery.GetDescription: string; begin Result := 'UniDAC Query'; end; procedure TfrxUniDACQuery.SetDatabase(const Value: TfrxDACDatabase); begin inherited; if Value <> nil then FQuery.Connection := Value.Database else if UniDACComponents <> nil then FQuery.Connection := TUniConnection(UniDACComponents.DefaultDatabase) else FQuery.Connection := nil; end; function TfrxUniDACQuery.GetSpecificOptions: TSpecificOptionsList; begin Result := (FQuery as TCustomUniDataSet).SpecificOptions; end; procedure TfrxUniDACQuery.SetSpecificOptions(Value: TSpecificOptionsList); begin (FQuery as TCustomUniDataSet).SpecificOptions := Value; end; {$IFDEF QBUILDER} function TfrxUniDACQuery.QBEngine: TfqbEngine; begin Result := TfrxEngineUniDAC.Create(nil); TfrxEngineUniDAC(Result).FQuery.Connection := TUniConnection(FQuery.Connection); end; {$ENDIF} { TfrxEngineUniDAC } {$IFDEF QBUILDER} constructor TfrxEngineUniDAC.Create(AOwner: TComponent); begin inherited; FQuery := TUniDACQuery.Create(Self); end; destructor TfrxEngineUniDAC.Destroy; begin FQuery.Free; inherited; end; procedure TfrxEngineUniDAC.ReadFieldList(const ATableName: string; var AFieldList: TfqbFieldList); var TempTable: TUniDACTable; Fields: TFieldDefs; i: Integer; tmpField: TfqbField; begin AFieldList.Clear; TempTable := TUniDACTable.Create(Self); try TempTable.Connection := TUniConnection(FQuery.Connection); TempTable.TableName := ATableName; Fields := TempTable.FieldDefs; try TempTable.Active := True; tmpField:= TfqbField(AFieldList.Add); tmpField.FieldName := '*'; for i := 0 to Fields.Count - 1 do begin tmpField := TfqbField(AFieldList.Add); tmpField.FieldName := Fields.Items[i].Name; tmpField.FieldType := Ord(Fields.Items[i].DataType) end; except end; finally TempTable.Free; end; end; {$ENDIF} initialization CatBmp := TBitmap.Create; CatBmp.LoadFromResourceName(hInstance, TfrxUniDACComponents.ResourceName); RegisterDacComponents(TfrxUniDACComponents); finalization UnRegisterDacComponents(TfrxUniDACComponents); CatBmp.Free; end.
unit uGSAxCustomTransceiverPlugIn; {$I twcomp.pas} interface uses ComObj, Windows, Variants, ActiveX, SysUtils, Registry, CAS_TABLE, pGSAxCustomTransceiverPlugIn_TLB, CAS_LOGGER, CAS_REGISTRY, CAS_TOOLSGUID; type resultType = (rtOk, rtInformation, rtWarning, rtError); TGSAxCustomTransceiverPlugIn = class(TAutoObject, IGSAxTransceiverGenerator, IGSAxTransceiverInterpreter) // Summary: // Base class for all implemented ERP connect plugins of our solution partners. // Description: // This class is used as uniform definition for the interfaces of ERP connect. // For a solution partner it's necessary to implement the two interfaces // IGSAxTransceiverInterpreter and IGSAxTransceiverGenerator. It's possible to // derive from this class. It's also possible to implement a COM object in // another development language than Delphi. // If this class will be used as base class, the project is directly // compatible with the interface. It can be modified with the DemoTransceiver- // Example as template private FDatasource : TCASDatasource; FCASTable : TCASTable; FSyncOrder: Widestring; protected // Help functions function BinaryToGuidStr(const Binary : OleVariant) : Widestring; function VarArrayToHex(const value: OleVariant): Widestring; function CreateNewGUID : OleVariant; function GUIDStrToBinary( GuidStr: Widestring) : OleVariant; function Add0x( GuidStr: Widestring) : Widestring; function Del0x( GuidStr: Widestring) : Widestring; procedure SetFieldListValue ( var FieldList : OleVariant; var Values : OleVariant; FieldName : Widestring; FieldValue : OleVariant ); function ReplaceCharsByChars( SourceStr: Widestring; SubStr: Widestring; ReplaceStr: Widestring ) : Widestring; function GetModulePathByInstance( Instance: hModule ): Widestring; // Implementation of the generator interfaces procedure Prepare(const Tablename: WideString);virtual;safecall; function GetSystemID: WideString; virtual; safecall; function GetDeletedRecords(const Tablename: WideString): OleVariant; virtual; safecall; function GetInsertedRecords(const Tablename: WideString): OleVariant; virtual; safecall; function GetUpdatedRecords(const Tablename: WideString): OleVariant; virtual; safecall; function GetXMLDocument(const Operation, Tablename: WideString; ExtKey: OleVariant): WideString; virtual; safecall; procedure Finish(const Tablename: WideString); virtual; safecall; procedure IGSAxTransceiverGenerator.Login = Login; // Reference on the public method LogIn. It also exists in IGSAxTransceiverInterpreter procedure SetRelation(const Operation: WideString; const TableName: WideString; Key: OleVariant; CorrespondingKey: OleVariant; OpTimeStamp: OleVariant); virtual; safecall; function IGSAxTransceiverGenerator.GetSupportedTables = GetSupportedTables; procedure BeforeComplete(const TableName: WideString); virtual; safecall; procedure AfterComplete(const TableName: WideString); virtual; safecall; procedure IGSAxTransceiverGenerator.SetSyncOrder = SetSyncOrder; function IGSAxTransceiverGenerator.GetNeededLoginParams = GetNeededLoginParams; function OnlineRefreshIsAllowed(const TableName: WideString): OleVariant; virtual; safecall; function IGSAxTransceiverGenerator.MatchOfCompanyContactsIsDesired = MatchOfCompanyContactsIsDesired; // Implementation of the interpreter interfaces procedure IGSAxTransceiverInterpreter.Login = Login; // Reference on the public method LogIn. It also exists in IGSAxTransceiverGenerator function IGSAxTransceiverInterpreter.GetSupportedTables = GetSupportedTables; procedure XMLInsert(const SourceSystemID: WideString; const Tablename: WideString; const ExtKey: WideString; const XMLMessage: WideString; out resultType: OleVariant; out resultKey: OleVariant; out resultMessage: OleVariant); virtual; safecall; procedure XMLUpdate(const SourceSystemID: WideString; const Tablename: WideString; const ExtKey: WideString; const XMLMessage: WideString; out resultType: OleVariant; out resultKey: OleVariant; out resultMessage: OleVariant); virtual; safecall; procedure XMLDelete(const SourceSystemID: WideString; const Tablename: WideString; const ExtKey: WideString; const XMLMessage: WideString; out resultType: OleVariant; out resultKey: OleVariant; out resultMessage: OleVariant); virtual; safecall; function GetSupportedTables: OleVariant; virtual; safecall; procedure Login(const Connection: WideString; const User: WideString; const PassWord: WideString); virtual; safecall; procedure IGSAxTransceiverInterpreter.SetSyncOrder = SetSyncOrder; function IGSAxTransceiverInterpreter.GetNeededLoginParams = GetNeededLoginParams; function IGSAxTransceiverInterpreter.MatchOfCompanyContactsIsDesired = MatchOfCompanyContactsIsDesired; function ChangeOfCorrelationIsAllowed: OleVariant; virtual; safecall; function GetMatchingFields: OleVariant; virtual; safecall; procedure ChangeCorrelation(OldTableGUID: OleVariant; NewTableGUID: OleVariant); virtual; safecall; procedure SetSyncOrder(const SyncOrder: WideString); virtual; safecall; function GetNeededLoginParams: OleVariant; virtual; safecall; function MatchOfCompanyContactsIsDesired: OleVariant; virtual; safecall; property DataSource: TCASDataSource Read FDataSource Write FDataSource; property CASTable : TCASTable read FCASTable; property SyncOrder: Widestring Read FSyncOrder Write FSyncOrder; public procedure Initialize; override; destructor Destroy; override; class procedure RegisterPlugIn( SystemID, ClassInterpreter, ClassGenerator : WideString ); end; implementation const GenesisRegistryPath1 : Widestring = 'Software\CAS-Software\Genesis\1.0\'; CAS_HEX_CHARS : array[0..15] of Ansichar = ('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'); {==============================================================================} { Initialize } {==============================================================================} procedure TGSAxCustomTransceiverPlugIn.Initialize; // Summary: // Creates a DataSource and a Table to connect with ADO begin inherited; FDatasource := TCASDatasource.Create(nil); FCASTable := TCASTable.Create(nil); FDatasource.DataProviderType := dpADO; FCASTable.Datasource := FDatasource; end; {==============================================================================} { Destroy } {==============================================================================} destructor TGSAxCustomTransceiverPlugIn.Destroy; begin try FDatasource.Free; FCASTable.Free; finally inherited; end; end; {==============================================================================} function TGSAxCustomTransceiverPlugIn.CreateNewGUID : OleVariant; begin result := TCASGUID.NewGUID.ToBinary; end; {==============================================================================} { BinaryToGUIDStr } {==============================================================================} function TGSAxCustomTransceiverPlugIn.BinaryToGuidStr(const Binary : OleVariant) : Widestring; begin Result := '00000000000000000000000000000000'; if varIsArray(Binary) then Result := VarArrayToHex(Binary); Result := Add0x( Result ); end; {==============================================================================} { GUIDStrToBinary } {==============================================================================} function TGSAxCustomTransceiverPlugIn.GUIDStrToBinary( GuidStr: Widestring) : OleVariant; var i: integer; s: Widestring; begin s := GuidStr; Result := VarArrayCreate ( [ 0, 15], varByte ); if (GuidStr = '') or (GuidStr = '0') then s := '00000000000000000000000000000000'; s := Del0x(s); for i := 0 to 15 do Result[ i ] := StrToInt( '$' + copy( s, 2*i+1, 2 )); end; {==============================================================================} { Del0x } {==============================================================================} function TGSAxCustomTransceiverPlugIn.Del0x( GuidStr: Widestring) : Widestring; begin Result := GuidStr; if copy( GuidStr, 1, 2 ) = '0x' then delete( Result, 1, 2 ); end; {==============================================================================} { Add0x } {==============================================================================} function TGSAxCustomTransceiverPlugIn.Add0x( GuidStr: Widestring) : Widestring; begin if copy( GuidStr, 1, 2 ) = '0x' then Result := GuidStr else Result := '0x' + GuidStr; end; {==============================================================================} { VarArrayToHex } {==============================================================================} function TGSAxCustomTransceiverPlugIn.VarArrayToHex(const value: OleVariant): Widestring; var nVarIdx, nResIdx: integer; ch: BYTE; begin if VarIsArray(value) then begin SetLength(result, 2 * (VarArrayHighBound(value, 1) - VarArrayLowBound(value, 1) + 1)); nResIdx := 1; for nVarIdx := VarArrayLowBound(value, 1) to VarArrayHighBound(value, 1) do begin ch := BYTE(value[nVarIdx]); result[2 * nResIdx - 1] := Widechar( CAS_HEX_CHARS[(ch shr 4) and $0F] ); result[2 * nResIdx] := Widechar( CAS_HEX_CHARS[ch and $0F] ); Inc(nResIdx); end; end; end; {==============================================================================} { SetFieldListValue } {==============================================================================} procedure TGSAxCustomTransceiverPlugIn.SetFieldListValue ( var FieldList : OleVariant; var Values : OleVariant; FieldName : Widestring; FieldValue : OleVariant ); var MaxIndex : integer; FieldListIndex : integer; begin if VarIsArray(FieldList) then begin MaxIndex := VarArrayHighBound ( FieldList, 1 ); // Search for FieldName in the FieldList FieldName := AnsiUppercase(FieldName); FieldListIndex := VarArrayLowBound ( FieldList, 1 ); repeat if AnsiUppercase(FieldList[FieldListIndex]) = FieldName then break; inc ( FieldListIndex ); until FieldListIndex > MaxIndex; // Add the FieldName to FieldList if FieldListIndex > MaxIndex then begin VarArrayReDim ( FieldList, MaxIndex + 1 ); VarArrayReDim ( Values, MaxIndex + 1 ); FieldList[FieldListIndex] := FieldName; end; // Insert the FieldValue Values[FieldListIndex] := FieldValue; end else begin FieldList := VarArrayOf( [ FieldName ] ); Values := VarArrayOf( [ FieldValue ] ); end end; {==============================================================================} { ReplaceCharsByChars } {==============================================================================} function TGSAxCustomTransceiverPlugIn.ReplaceCharsByChars(SourceStr, SubStr, ReplaceStr: Widestring): Widestring; var tmpStr : Widestring; lFound : Integer; begin Result := ''; tmpStr := SourceStr; while length(tmpStr) > 0 do begin lFound := Pos( SubStr, tmpStr ); if lFound > 0 then begin Result := Result + Copy(tmpStr,1,lFound-1) + ReplaceStr; System.delete(tmpStr,1,lFound + Length(SubStr) -1); end else begin Result := Result + tmpStr; tmpStr := ''; end; end; end; {==============================================================================} { GetModulePathByInstance } { Determines the path of the instance, e.g. D:\Projects\server\ } {==============================================================================} function TGSAxCustomTransceiverPlugIn.GetModulePathByInstance(Instance: hModule): Widestring; var s: Widestring; Buffer: array[0..Windows.MAX_PATH] of Widechar; begin SetString(s, Buffer, GetModuleFileNameW(Instance, Buffer, MAX_PATH) ); Result := ExtractFilePath(s); end; {==============================================================================} { GetDeletedRecords } {==============================================================================} function TGSAxCustomTransceiverPlugIn.GetDeletedRecords(const Tablename: WideString): OleVariant; // Summary: // Method to determine deleted datasets of a table. // Description: // The method GetXMLDocument is called for each deleted dataset. An appropriate // delete message will be created // Parameters: // TableName - The name of the table with deleted datasets // Returns: // OleVariantArray with unique keys of the deleted dataset begin result := unassigned; end; {==============================================================================} { GetInsertedRecords } {==============================================================================} function TGSAxCustomTransceiverPlugIn.GetInsertedRecords(const Tablename: WideString): OleVariant; // Summary: // Method to determine new datasets of a table. // Description: // The method GetXMLDocument is called for each new dataset. An appropriate // insert message will be created // Parameters: // TableName - The name of the table with new datasets // Returns: // OleVariantArray with unique keys of the new dataset begin result := unassigned; end; {==============================================================================} { GetSystemID } {==============================================================================} function TGSAxCustomTransceiverPlugIn.GetSystemID: WideString; // Summary: // Method to determine the SystemID. // Description: // Each plugin retrives his own unique name. This name will be displayed // as driver in the konfiguration form. // It's neccesary to use this name for the file names of // the transformation stylesheets // Returns: // Unique name of the plugin begin result := ''; end; {==============================================================================} { GetUpdatedRecords } {==============================================================================} function TGSAxCustomTransceiverPlugIn.GetUpdatedRecords(const Tablename: WideString): OleVariant; // Summary: // Method to determine changed datasets of a table. // Description: // The method GetXMLDocument is called for each changed dataset. An appropriate // update message will be created // Parameters: // TableName - The name of the table with changed datasets // Returns: // OleVariantArray with unique keys of the changed dataset begin result := unassigned; end; {==============================================================================} { GetXMLDocument } {==============================================================================} function TGSAxCustomTransceiverPlugIn.GetXMLDocument(const Operation, Tablename: WideString; ExtKey: OleVariant): WideString; // Summary: // Method to generate a xml message // Description: // This method is called for each deleted, changed or created dataset. // A xml message will be created for the dataset of the table. // Parameters: // Operation - Insert, Update or Delete. // If the operation is Delete the value of the xml message is // limited to the important key values // TableName - Address, BSProduct, BSProductGroup, BSVoucher, Project // table name of the dataset // ExtKey - Unique key of the table. It can be a gw-GUID or a ERP-System-Key // Returns: // Generated xml message of the current dataset begin result := ''; end; {==============================================================================} { Finish } {==============================================================================} procedure TGSAxCustomTransceiverPlugIn.Finish(const Tablename: WideString); // Summary: // Method is called after the synchronisation // Description: // After all datasets are synchronized this method will be called to do some // things at the end // Parameters: // TableName - The name of the table which was synchronized begin // do nothing end; {==============================================================================} {==============================================================================} {==============================================================================} {==============================================================================} { XMLDelete } {==============================================================================} procedure TGSAxCustomTransceiverPlugIn.XMLDelete(const SourceSystemID: WideString; const Tablename: WideString; const ExtKey: WideString; const XMLMessage: WideString; out resultType: OleVariant; out resultKey: OleVariant; out resultMessage: OleVariant); begin resultType := rtOk; VarClear(resultKey); resultMessage := ''; end; {==============================================================================} { XMLInsert} {==============================================================================} procedure TGSAxCustomTransceiverPlugIn.XMLInsert(const SourceSystemID: WideString; const Tablename: WideString; const ExtKey: WideString; const XMLMessage: WideString; out resultType: OleVariant; out resultKey: OleVariant; out resultMessage: OleVariant); begin resultType := rtOk; VarClear(resultKey); resultMessage := ''; end; {==============================================================================} { XMLUpdate } {==============================================================================} procedure TGSAxCustomTransceiverPlugIn.XMLUpdate(const SourceSystemID: WideString; const Tablename: WideString; const ExtKey: WideString; const XMLMessage: WideString; out resultType: OleVariant; out resultKey: OleVariant; out resultMessage: OleVariant); begin resultType := rtOk; VarClear(resultKey); resultMessage := ''; end; {==============================================================================} { class procedure RegisterPlugIn } {==============================================================================} class procedure TGSAxCustomTransceiverPlugIn.RegisterPlugIn(SystemID, ClassInterpreter, ClassGenerator: WideString); var Registry : TCASRegistry; begin try Registry := TCASRegistry.Create; try Registry.RootKey := HKEY_LOCAL_MACHINE; Registry.OpenKey( '\' + GenesisRegistryPath1 + 'Transceiver\InterpreterPlugIns\', true ); if ClassInterpreter <> '' then Registry.WriteString(SystemID,ClassInterpreter); Registry.OpenKey( '\' + GenesisRegistryPath1 + 'Transceiver\GeneratorPlugIns\', true ); if ClassGenerator <> '' then Registry.WriteString(SystemID,ClassGenerator); finally Registry.Free; end; except LogException(ExceptObject,cLoggerPrefixTryExcept,varNull,'TGSAxCustomTransceiverPlugIn.RegisterPlugIn',CAS_LOGGER.Debug); end; end; {==============================================================================} { Prepare } {==============================================================================} procedure TGSAxCustomTransceiverPlugIn.Prepare(const Tablename: WideString); begin //do nothing end; {==============================================================================} { Login } {==============================================================================} procedure TGSAxCustomTransceiverPlugIn.Login(const Connection, User, PassWord: WideString); begin FDataSource.DataProvider := 'dsn=' + Connection + ';uid=' + User + ';pwd=' + PassWord; FDataSource.Active := True; end; {==============================================================================} { GetSupportedTables } {==============================================================================} function TGSAxCustomTransceiverPlugIn.GetSupportedTables: OleVariant; begin VarClear(result); end; {==============================================================================} { SetSyncOrder } {==============================================================================} procedure TGSAxCustomTransceiverPlugIn.SetSyncOrder(const SyncOrder: WideString); begin FSyncOrder := SyncOrder; end; {==============================================================================} { BeforeComplete } {==============================================================================} procedure TGSAxCustomTransceiverPlugIn.BeforeComplete(const TableName: WideString); // Summary: // Method to prepare for a complete synchronization // Description: // Typically a complete synchronization will de done at first. After this // an incremental synchronization should run. // To prepare for further complete syhcnronizations its possible to implement // this method // Parameters: // TableName - Name of table for the complete synchrinisation begin //do nothing end; {==============================================================================} { AfterComplete } {==============================================================================} procedure TGSAxCustomTransceiverPlugIn.AfterComplete(const TableName: WideString); // Summary: // Method to finish a complete synchronization // Description: // Typically a complete synchronization will de done at first. After this // an incremental synchronization should run. // To finish further complete syhcnronizations its possible to implement // this method // Parameters: // TableName - Name of table for the complete synchrinisation begin //do nothing end; {==============================================================================} { GetNeededLoginParams } {==============================================================================} function TGSAxCustomTransceiverPlugIn.GetNeededLoginParams: OleVariant; begin VarClear(result); result := VarArrayCreate([0,1] , varVariant); result[0] := 'Username'; result[1] := 'Password'; end; {==============================================================================} { SetRelation } {==============================================================================} procedure TGSAxCustomTransceiverPlugIn.SetRelation(const Operation, TableName: WideString; Key, CorrespondingKey, OpTimeStamp: OleVariant); begin //do nothing end; {==============================================================================} { OnlineRefreshIsAllowed } {==============================================================================} function TGSAxCustomTransceiverPlugIn.OnlineRefreshIsAllowed(const TableName: WideString): OleVariant; begin result := 1; end; {==============================================================================} { MatchOfCompanyContactsIsDesired } {==============================================================================} function TGSAxCustomTransceiverPlugIn.MatchOfCompanyContactsIsDesired: OleVariant; // Summary: // Method to check if the plugin supports the synchronization of contacts // which are no (!) customers begin result := 0; end; {==============================================================================} { ChangeOfCorrelationIsAllowed } {==============================================================================} function TGSAxCustomTransceiverPlugIn.ChangeOfCorrelationIsAllowed: OleVariant; // Summary: // Method to check if the plugin supports changes of key assignment begin result := 0; end; {==============================================================================} { ChangeCorrelation } {==============================================================================} procedure TGSAxCustomTransceiverPlugIn.ChangeCorrelation(OldTableGUID, NewTableGUID: OleVariant); // Summary: // Method to change key assignments // Description: // In der BSExternalTableRelation wird einfach der TableGUID von OldTableGUID auf NewTableGUID // geändert. Auf diese Weise ist es möglich, daß Ansprechpartner, die als Kunden im ERP-System // geführt werden, auf den Firmensatz gemapped werden begin //do nothing end; {==============================================================================} { GetMatchingFields } {==============================================================================} function TGSAxCustomTransceiverPlugIn.GetMatchingFields: OleVariant; // Summary: // Method to support the changes of key assignments // Description: // see also ChangeCorrelation // This method retrievs the values of the fields which are relevant to the // synchronization of addresses begin VarClear(result); end; end.
unit uSubtracaoTest; interface uses TestFrameWork ,uSubtracao; type TSubtracaoTest = class(TTestCase) procedure verificarSubtracaoDoisNumerosPositivos(); procedure verificarSubtracaoNumeroPositivoENumeroNegativo(); end; implementation { TSomaTest } procedure TSubtracaoTest.verificarSubtracaoDoisNumerosPositivos; var operacao: TSubtracao; begin operacao := TSubtracao.Create(); try Assert(operacao.executar(3, 4) = -1); finally operacao.Free(); end; end; procedure TSubtracaoTest.verificarSubtracaoNumeroPositivoENumeroNegativo; var operacao: TSubtracao; begin operacao := TSubtracao.Create(); try Assert(operacao.executar(3, -4) = 7); finally operacao.Free(); end; end; initialization TestFrameWork.RegisterTest(TSubtracaoTest.Suite); end.
program ejercicio_13; const dimF=1990; cantPuntos=5; type puntos = array[1..cantPuntos] of double; //Los puntos/zonas diferentes del planeta (para ver la comprobacion bajamos de 100 puntos a 5) anios = array[1980..dimF] of puntos; //El periodo donde se realiza el estudio (Lo dejamos en 10 datos); procedure cargarVector(var vec: anios); var i:integer; j:integer; begin for i:=1980 to dimF do begin writeln('Aņo: ', i); for j:= 1 to cantPuntos do begin writeln('Ingrese la temperatura de la zona: '); readln(vec[i][j]); // Vec[I] es un arreglo de tipo "puntos", es decir, es un arreglo de otro arreglo donde este ultimo (el arreglo de puntos) almacena datos de tipo REAL correspondiente a la temperatura. end; end; end; procedure calcularPromedio(vecPuntos:puntos;var promedio,tempMasAlta: double); var i: integer; sumaTemperatura: double; begin tempMasAlta:= -999; sumaTemperatura:= 0; for i:=1 to cantPuntos do begin //Para todas las zonas/puntos de ese aņo if (vecPuntos[i] > tempMasAlta) then tempMasAlta:= vecPuntos[i]; sumaTemperatura:= sumaTemperatura + vecPuntos[i]; end; promedio:= sumaTemperatura / cantPuntos; end; procedure calcular(vec: anios; var anioConPromedioMasAlto, anioConTempMasAlta: integer ); var i: integer; maxPromedio,promedio:double; tempMasAlta,maxTemperatura: double; begin maxPromedio:= -999; maxTemperatura:=-999; for i:= 1980 to dimF do begin calcularPromedio(vec[i],promedio,tempMasAlta); //Devuelve el promedio y si la temperatura de algunas de esas zonas de ese aņo es mas alta que el maximo actualiza el max y lo devuelve if (promedio > maxPromedio) then begin maxPromedio:= promedio; anioConPromedioMasAlto:= i; end; if (tempMasAlta > maxTemperatura) then begin maxTemperatura:= tempMasAlta; anioConTempMasAlta:= i; end; end; end; var vec: anios; maxAnio:integer; anioConTempMasAlta: integer; begin maxAnio:= 999; anioConTempMasAlta:= 999; cargarVector(vec); //En realidad carga una matriz calcular(vec, maxAnio, anioConTempMasAlta); writeln('El aņo con mayor temperatura promedio a nivel mundial fue: ', maxAnio); writeln('El aņo con la mayor temperatura detectada en el periodo analizado fue: ', anioConTempMasAlta); readln; end.
program Constant; {$mode objfpc}{$H+} uses {$IFDEF UNIX} {$IFDEF UseCThreads} cthreads, {$ENDIF} {$ENDIF} Classes, sysutils { you can add units after this }; const GallonPrice = 6.5; var Payment: integer; Consumption: integer; Kilos: single; begin Write('How much did you pay for your car''s fuel: '); Readln(Payment); Write('What is the consumption of your car? (Kilos per Gallon): '); Readln(Consumption); Kilos := (Payment / GallonPrice) * Consumption; Writeln('This fuel will keep your car running for : ', Format('%0.1f', [Kilos]), ' Kilometers'); Write('Press enter'); Readln; end.
unit uEmployeeType; interface uses uTypePersonInterface,uPerson,Windows,DB; type TEmployeeType = class(TInterfacedObject,ITypePerson) procedure Save(obj:TObject); procedure Delete(obj:TObject); function ListPerson(obj:TObject):string; function PesquisarPessoa(obj:TObject):OleVariant; function ListCombo:string; procedure saveService(psService:string); end; implementation uses uSupplier,forms, SysUtils,Dialogs,uEmployeeDao,uEmployee; { TEmployeeType } procedure TEmployeeType.Delete(obj: TObject); var oCliente:TEmployeeDao; begin oCliente := TEmployeeDao.Create; try oCliente.DeleteEmployee((obj as TEmployee)); finally FreeAndNil(oCliente); end; end; function TEmployeeType.ListCombo: string; var oCliente:TEmployeeDao; begin try oCliente := TEmployeeDao.Create; Result := oCliente.ListCombo; finally FreeAndNil(oCliente); end; end; function TEmployeeType.ListPerson(obj: TObject): string; var oCliente:TEmployeeDao; begin oCliente := TEmployeeDao.Create; try result := oCliente.ListPerson((obj as TEmployee)); finally FreeAndNil(oCliente); end; end; function TEmployeeType.PesquisarPessoa(obj: TObject): OleVariant; var oCliente:TEmployeeDao; begin try oCliente := TEmployeeDao.Create; Result := oCliente.PesquisarPessoa((obj as TEmployee)); finally FreeAndNil(oCliente); end; end; procedure TEmployeeType.Save(obj: TObject); var oCliente:TEmployeeDao; begin try try oCliente := TEmployeeDao.Create; oCliente.save((obj as TEmployee)); finally FreeAndNil(oCliente); end; ShowMessage('Saved successfully.'); except ShowMessage('Error saving.'); raise; end; end; procedure TEmployeeType.saveService(psService: string); begin end; end.
unit DBTableMappingUnit; interface uses TableMappingUnit, TableColumnMappingsUnit, DBTableColumnMappingsUnit, Classes; type TColumnNamingMode = ( UseFullyQualifiedColumnNaming, UseNonQualifiedColumnNaming ); TDBTableMapping = class (TTableMapping) protected FAliasTableName: String; FColumnMappingsForSelect: TDBTableColumnMappings; FPrimaryKeyColumnMappings: TDBTableColumnMappings; function GetSelectList(const CustomTableNamePrefix: string = ''): String; function GetAliasColumnAssigningOperatorName: String; virtual; function GetColumnMappings: TTableColumnMappings; override; function GetTableNameWithAlias: String; function GetColumnMappingsForModification: TDBTableColumnMappings; public destructor Destroy; override; constructor Create; procedure SetTableNameMappingWithAlias( const TableName: String; ObjectClass: TClass; const AliasTableName: String; ObjectListClass: TClass = nil ); function AddColumnMappingForSelectWithAlias( const ColumnName, ObjectPropertyName, AliasColumnName: String; const AllowMappingOnDomainObjectProperty: Boolean = True ): TDBTableColumnMapping; function FindSelectColumnMappingByObjectPropertyName( const ObjectPropertyName: string ): TDBTableColumnMapping; function AddColumnMappingForSelectWithOtherTableName( const ColumnName, ObjectPropertyName, TableName: String; const AllowMappingOnDomainObjectProperty: Boolean = True ): TDBTableColumnMapping; function AddColumnMappingForSelectWithAliasAndOtherTableName( const ColumnName, ObjectPropertyName, AliasColumnName, TableName: String; const AllowMappingOnDomainObjectProperty: Boolean = True ): TDBTableColumnMapping; procedure AddColumnMappingForSelect( const ColumnName, ObjectPropertyName: String; const AllowMappingOnDomainObjectProperty: Boolean = True ); procedure AddColumnNameForSelect( const ColumnName: String ); procedure AddColumnNameWithAliasForSelect( const ColumnName, AliasColumnName: String ); procedure AddColumnMappingForModification( const ColumnName, ObjectPropertyName: String; const ConversionTypeName: String = '' ); procedure AddPrimaryKeyColumnMapping( const ColumnName, ObjectPropertyName: String; const ConversionTypeName: String = '' ); property ColumnMappingsForSelect: TDBTableColumnMappings read FColumnMappingsForSelect; property ColumnMappingsForModification: TDBTableColumnMappings read GetColumnMappingsForModification; property PrimaryKeyColumnMappings: TDBTableColumnMappings read FPrimaryKeyColumnMappings; function GetSelectListForSelectGroup( const CustomTableNamePrefix: String = '' ): String; procedure GetSelectListForSelectByIdentity( var SelectList: String; var WhereClauseForSelectByIdentity: String ); function GetUpdateList: String; procedure GetInsertList( var ColumnNameList: String; var ColumnValuePlaceholderList: String ); function GetModificationColumnCommaSeparatedList: String; function GetSelectColumnNameListWithoutTablePrefix: String; function GetUniqueObjectColumnCommaSeparatedList( const ColumnNamingMode: TColumnNamingMode ): String; function GetWhereClauseForSelectUniqueObject: String; published property AliasTableName: String read FAliasTableName; property TableNameWithAlias: String read GetTableNameWithAlias; end; implementation uses SysUtils; { TDBTableMapping } procedure TDBTableMapping.AddColumnMappingForModification( const ColumnName, ObjectPropertyName: String; const ConversionTypeName: String ); begin ColumnMappingsForModification.AddColumnMapping( ColumnName, ObjectPropertyName, ConversionTypeName ); end; procedure TDBTableMapping.AddColumnMappingForSelect( const ColumnName, ObjectPropertyName: String; const AllowMappingOnDomainObjectProperty: Boolean ); begin FColumnMappingsForSelect.AddColumnMapping( ColumnName, ObjectPropertyName, AllowMappingOnDomainObjectProperty ); end; function TDBTableMapping.AddColumnMappingForSelectWithAlias( const ColumnName, ObjectPropertyName, AliasColumnName: String; const AllowMappingOnDomainObjectProperty: Boolean ): TDBTableColumnMapping; begin FColumnMappingsForSelect.AddColumnMappingWithAlias( ColumnName, ObjectPropertyName, AliasColumnName, AllowMappingOnDomainObjectProperty ); end; function TDBTableMapping.AddColumnMappingForSelectWithAliasAndOtherTableName( const ColumnName, ObjectPropertyName, AliasColumnName, TableName: String; const AllowMappingOnDomainObjectProperty: Boolean ): TDBTableColumnMapping; begin FColumnMappingsForSelect.AddColumnMappingWithAliasAndTableName( ColumnName, ObjectPropertyName, AliasColumnName, TableName, AllowMappingOnDomainObjectProperty ); end; function TDBTableMapping.AddColumnMappingForSelectWithOtherTableName( const ColumnName, ObjectPropertyName, TableName: String; const AllowMappingOnDomainObjectProperty: Boolean ): TDBTableColumnMapping; begin FColumnMappingsForSelect.AddColumnMappingWithTableName( ColumnName, ObjectPropertyName, TableName, AllowMappingOnDomainObjectProperty ); end; procedure TDBTableMapping.AddColumnNameForSelect( const ColumnName: String ); begin AddColumnMappingForSelect( ColumnName, '', False ); end; procedure TDBTableMapping.AddColumnNameWithAliasForSelect( const ColumnName, AliasColumnName: String ); begin AddColumnMappingForSelectWithAlias( ColumnName, '', AliasColumnName, False ); end; procedure TDBTableMapping.AddPrimaryKeyColumnMapping( const ColumnName, ObjectPropertyName: String; const ConversionTypeName: String ); begin FPrimaryKeyColumnMappings.AddColumnMapping( ColumnName, ObjectPropertyName, ConversionTypeName ); end; constructor TDBTableMapping.Create; begin inherited; FColumnMappingsForSelect := GetColumnMappings as TDBTableColumnMappings; FPrimaryKeyColumnMappings := GetColumnMappings as TDBTableColumnMappings; end; destructor TDBTableMapping.Destroy; begin FreeAndNil(FColumnMappingsForSelect); FreeAndNil(FPrimaryKeyColumnMappings); inherited; end; function TDBTableMapping.FindSelectColumnMappingByObjectPropertyName( const ObjectPropertyName: string): TDBTableColumnMapping; begin Result := FColumnMappingsForSelect.FindColumnMappingByObjectPropertyName( ObjectPropertyName ) as TDBTableColumnMapping; end; function TDBTableMapping.GetAliasColumnAssigningOperatorName: String; begin Result := 'as'; end; function TDBTableMapping.GetColumnMappings: TTableColumnMappings; begin Result := TDBTableColumnMappings.Create; end; function TDBTableMapping.GetColumnMappingsForModification: TDBTableColumnMappings; begin Result := FColumnMappings as TDBTableColumnMappings; end; procedure TDBTableMapping.GetInsertList( var ColumnNameList, ColumnValuePlaceholderList: String ); var ColumnMapping: TTableColumnMapping; begin ColumnNameList := ''; ColumnValuePlaceholderList := ''; for ColumnMapping in ColumnMappingsForModification do begin if ColumnNameList = '' then begin ColumnNameList := ColumnMapping.ColumnName; ColumnValuePlaceholderList := ':' + ColumnMapping.ObjectPropertyName; end else begin ColumnNameList := ColumnNameList + ',' + ColumnMapping.ColumnName; ColumnValuePlaceholderList := ColumnValuePlaceholderList + ', :' + ColumnMapping.ObjectPropertyName; end; end; end; function TDBTableMapping.GetModificationColumnCommaSeparatedList: String; var ColumnNameList, ColumnValuePlaceholderList: String; begin GetInsertList(ColumnNameList, ColumnValuePlaceholderList); Result := ColumnNameList; end; function TDBTableMapping.GetSelectColumnNameListWithoutTablePrefix: String; var ColumnMapping: TDBTableColumnMapping; SelectListElement: String; begin for ColumnMapping in ColumnMappingsForSelect do begin if ColumnMapping.AliasColumnName <> '' then SelectListElement := ColumnMapping.AliasColumnName else SelectListElement := ColumnMapping.ColumnName; if Result = '' then Result := SelectListElement else Result := Result + ',' + SelectListElement; end; end; function TDBTableMapping.GetSelectList( const CustomTableNamePrefix: String ): String; var ColumnMapping: TDBTableColumnMapping; SelectListElement, UsedTableName: String; begin for ColumnMapping in ColumnMappingsForSelect do begin if CustomTableNamePrefix <> '' then UsedTableName := CustomTableNamePrefix else if ColumnMapping.TableName <> '' then UsedTableName := ColumnMapping.TableName else if AliasTableName = ''then UsedTableName := TableName else UsedTableName := AliasTableName; SelectListElement := UsedTableName + '.' + ColumnMapping.ColumnName; if ColumnMapping.AliasColumnName <> '' then SelectListElement := SelectListElement + ' ' + GetAliasColumnAssigningOperatorName + ' ' + ColumnMapping.AliasColumnName; if Result = '' then Result := SelectListElement else Result := Result + ',' + SelectListElement; end; end; procedure TDBTableMapping.GetSelectListForSelectByIdentity( var SelectList, WhereClauseForSelectByIdentity: String ); var PrimaryKeyColumnMapping: TTableColumnMapping; PrimaryKetColumnComparisonExpression: String; begin SelectList := GetSelectList; WhereClauseForSelectByIdentity := GetWhereClauseForSelectUniqueObject; end; function TDBTableMapping.GetSelectListForSelectGroup( const CustomTableNamePrefix: String ): String; begin Result := GetSelectList(CustomTableNamePrefix); end; function TDBTableMapping.GetTableNameWithAlias: String; begin Result := FTableName; if FAliasTableName <> '' then Result := Result + ' as ' + FAliasTableName; end; function TDBTableMapping.GetUniqueObjectColumnCommaSeparatedList( const ColumnNamingMode: TColumnNamingMode ): String; var PrimaryKeyColumnMapping: TTableColumnMapping; UniqueColumnExpression: String; begin for PrimaryKeyColumnMapping in FPrimaryKeyColumnMappings do begin if ColumnNamingMode = UseFullyQualifiedColumnNaming then UniqueColumnExpression := TableName + '.' + PrimaryKeyColumnMapping.ColumnName else UniqueColumnExpression := PrimaryKeyColumnMapping.ColumnName; if Result = '' then Result := UniqueColumnExpression else Result := Result + ',' + UniqueColumnExpression; end; end; function TDBTableMapping.GetUpdateList: String; var ColumnMapping: TTableColumnMapping; ColumnSetValueString: String; begin for ColumnMapping in ColumnMappingsForModification do begin ColumnSetValueString := ColumnMapping.ColumnName + '=:' + ColumnMapping.ObjectPropertyName; if Result = '' then Result := ColumnSetValueString else Result := Result + ',' + ColumnSetValueString; end; end; function TDBTableMapping.GetWhereClauseForSelectUniqueObject: String; var PrimaryKeyColumnMapping: TDBTableColumnMapping; PrimaryKeyColumnComparisonExpression: String; UsedTableName: String; begin Result := ''; if AliasTableName <> '' then UsedTableName := AliasTableName else UsedTableName := TableName; for PrimaryKeyColumnMapping in FPrimaryKeyColumnMappings do begin PrimaryKeyColumnComparisonExpression := UsedTableName + '.' + PrimaryKeyColumnMapping.ColumnName + '=:' + PrimaryKeyColumnMapping.ObjectPropertyName; if Result = '' then Result := PrimaryKeyColumnComparisonExpression else Result := Result + ' AND ' + PrimaryKeyColumnComparisonExpression; end; end; procedure TDBTableMapping.SetTableNameMappingWithAlias( const TableName: String; ObjectClass: TClass; const AliasTableName: String; ObjectListClass: TClass ); begin SetTableNameMapping(TableName, ObjectClass, ObjectListClass); FAliasTableName := AliasTableName; end; end.
unit zRevizor; interface uses Windows, SysUtils, Classes, Dialogs, Forms, zCRC32, AbArcTyp, AbZipTyp, AbUnzPrc, AbDfBase, AbDfEnc, AbDfDec; type // Структура "файл" TRevizorFile = class Name : string; // Имя Size : dword; // Размер Attr : byte; // Атрибуты CRC : dword; // Контрольная сумма RC : byte; // Результат сравнения end; TRevizorHDR = packed record SIGN : array[1..3] of char; // Сигнатура DateTime : TDateTime; // Дата генерации Version : Double; // Версия RootDirCount : dword; // Кол-во корневых каталогов code_num : byte; // Байт для доп. кодирования CRC : dword; // Контрольная сумма файла Mode : dword; // Битовая маска режимов DopData : dword; // Битовая маска с описанием доп.данных end; TRevizorDirHDR = packed record SIGN : char; // Сигнатура FilesCount : dword; // Кол-во файлов SubdirsCount : dword; // Кол-во подкаталогов end; TRevizorFileHDR = packed record Size : dword; // Размер Attr : byte; // Атрибуты CRC : dword; // Контрольная сумма end; TRevizor = class; // Событие "сканирование файла" TRevizorScanEvent = procedure(Sender : TObject; ObjName : string; F1 : TRevizorFile ) of object; // Событие "результат сравнения" TRevizorCmpEvent = procedure(Sender : TObject; ObjName : string; ACode : integer; F1, F2 : TRevizorFile) of object; // Событие "фильтр" TRevizorFltEvent = function(ObjName : string):boolean of object; // Класс "каталог" TRevizorDir = class FilesArray : TList; // Файлы SubDirsArray : array of TRevizorDir; // Подкаталоги Parent : TRevizorDir; // Родительский каталог DirName : string; RC : byte; private FParentRevizor : TRevizor; function GetFullDirName: string; procedure DoRevizorScanEvent(Sender : TObject; ObjName : string; F1 : TRevizorFile); procedure DoRevizorCmpEvent(Sender : TObject; ObjName : string; ACode : integer; F1, F2 : TRevizorFile); function DoRevizorFltEvent(ObjName : string) : boolean; public constructor Create(AParentRevizor : TRevizor); destructor Destroy; override; // Очистка (рекурсивная вглубь) procedure Clear; // Построение от текущего уровня вглубь function Refresh(ASpeedMode : boolean = false) : boolean; // Сравнение function Compare(ASpeedMode : boolean = false) : boolean; // Сканирование файла function ScanFile(AFileDir : string; SR : TSearchRec; var Res : TRevizorFile; ASpeedMode : boolean = false) : boolean; function CompareFiles(F1, F2 : TRevizorFile; ASpeedMode : boolean = false) : boolean; // Сохранение в поток function SaveToStream(AStream : TStream) : boolean; // Загрузка из потока function LoadFromStream(AStream : TStream) : boolean; published property FullDirName : string read GetFullDirName; end; // Ревизор диска - строит описание указанных папок TRevizor = class private FOnScanFile: TRevizorScanEvent; FOnCmpFile: TRevizorCmpEvent; FOnFilterFile: TRevizorFltEvent; FScanMask: string; FExcludeMask: string; procedure SetOnScanFile(const Value: TRevizorScanEvent); procedure SetOnCmpFile(const Value: TRevizorCmpEvent); procedure SetOnFilterFile(const Value: TRevizorFltEvent); procedure SetScanMask(const Value: string); procedure SetExcludeMask(const Value: string); public DirsArray : array of TRevizorDir; // Контролируемые каталоги RevizorHDR : TRevizorHDR; LastRefreshMode : Boolean; constructor Create; destructor Destroy; override; // Очистка списка сканируемых каталогов и всего построенного дерева procedure Clear; // Добавление вканируемого каталога function AddRootDir(ADirName : string) : boolean; // Удаление сканируемого каталога function DeleteRootDir(ADirName : string) : boolean; // Построение по текущему состоянию диска function Refresh(ASpeedMode : boolean = false) : boolean; // Сравнение function Compare(ASpeedMode : boolean = false) : boolean; // Сохранение в поток function SaveToStream(AStream : TmemoryStream) : boolean; // Загрузка из потока function LoadFromStream(AStream : TmemoryStream) : boolean; published property OnScanFile : TRevizorScanEvent read FOnScanFile write SetOnScanFile; property OnCmpFile : TRevizorCmpEvent read FOnCmpFile write SetOnCmpFile; property OnFilterFile : TRevizorFltEvent read FOnFilterFile write SetOnFilterFile; property ScanMask : string read FScanMask write SetScanMask; property ExcludeMask : string read FExcludeMask write SetExcludeMask; end; // Декодировать бинарные данные Function DecodeRevizorBinData(MS : TMemoryStream) : boolean; // Кодировать function CodeRevizorBinData(MS: TMemoryStream) : boolean; implementation uses zutil, Math; function CalkFileCRC(AFileName: string; var CRC, Size: DWord): boolean; var FS : TFileStream; Buf : array[0..$FFFF] of byte; Res, i, poz : integer; begin Result := false; CRC := 0; try FS := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyNone); Size := FS.Size; Poz := 0; Res := FS.Read(Buf, sizeof(Buf)); while Res > 0 do begin for i :=0 to Res - 1 do begin inc(poz); {$R-} CRC := CRC + Buf[i]*poz; {$R+} end; Res := FS.Read(Buf, sizeof(Buf)); end; FS.Free; Result := true; except end; end; function DecodeRevizorBinData(MS: TMemoryStream): boolean; var i, ResSize : integer; w : word; b : byte; RevizorHDR : TRevizorHDR; CRC, HeaderCRC : DWORD; AbDeflateHelper : TAbDeflateHelper; PackedStream, UnpackedStream : TMemoryStream; begin Result := false; {$R-} // Чтение заголовка MS.Seek(0,0); MS.Read(RevizorHDR, sizeof(RevizorHDR)); // Запись заголовка с CRC = 0 MS.Seek(0,0); HeaderCRC := RevizorHDR.CRC; RevizorHDR.CRC := 0; MS.Write(RevizorHDR, sizeof(RevizorHDR)); MS.Seek(0,0); CRC := 0; // Цикл декодирования данных for i := sizeof(RevizorHDR) to MS.Size - 1 do begin w := word(i*30 + RevizorHDR.code_num * 5 + 753); b := byte( Pointer(Longint(MS.Memory) + i)^ ); CRC := DWORD(CRC + b * i); asm rol b, 2 end; b := byte(not(b xor w)); ResSize := 1; Move(b, Pointer(Longint(MS.Memory) + i)^, ResSize); end; // Цикл расчета CRC заголовка for i := 0 to sizeof(RevizorHDR) - 1 do begin b := byte( Pointer(Longint(MS.Memory) + i)^ ); CRC := CRC + b * i; end; Result := CRC = HeaderCRC; if Result then begin PackedStream := nil; UnPackedStream := nil; AbDeflateHelper := nil; try try // Создание структур и классов PackedStream := TMemoryStream.Create; UnPackedStream := TMemoryStream.Create; AbDeflateHelper := TAbDeflateHelper.Create; // Копирование данных в поток MS.Seek(SizeOf(RevizorHDR), 0); PackedStream.CopyFrom(MS, MS.Size - SizeOf(RevizorHDR)); // Распаковка PackedStream.Seek(0,0); UnPackedStream.Seek(0,0); Inflate(PackedStream, UnPackedStream, AbDeflateHelper); MS.SetSize(SizeOf(RevizorHDR)); UnPackedStream.Seek(0,0); MS.CopyFrom(UnPackedStream, UnPackedStream.Size); finally AbDeflateHelper.Free; AbDeflateHelper := nil; UnPackedStream.Free; UnPackedStream := nil; PackedStream.Free; PackedStream := nil; end; except Result := false; end; end; {$R+} end; function CodeRevizorBinData(MS: TMemoryStream) : boolean; var i, ResSize : integer; w : word; b : byte; RevizorHDR : TRevizorHDR; AbDeflateHelper : TAbDeflateHelper; PackedStream, UnpackedStream : TMemoryStream; begin Result := false; {$R-} // Загрузка данных в буфер MS.Seek(0,0); MS.Read(RevizorHDR, SizeOf(RevizorHDR)); // Создание структур и классов PackedStream := TMemoryStream.Create; UnPackedStream := TMemoryStream.Create; AbDeflateHelper := TAbDeflateHelper.Create; // Копирование данных в поток UnPackedStream.CopyFrom(MS, MS.Size - SizeOf(RevizorHDR)); // Сжатие UnpackedStream.Seek(0,0); PackedStream.Seek(0,0); Deflate(UnpackedStream, PackedStream, AbDeflateHelper); PackedStream.Seek(0,0); MS.SetSize(0); RevizorHDR.CRC := 0; MS.Write(RevizorHDR, SizeOf(RevizorHDR)); PackedStream.Seek(0,0); MS.CopyFrom(PackedStream, PackedStream.Size); // Разрушение классов и освобожение памяти PackedStream.Free; UnPackedStream.Free; AbDeflateHelper.Free; // Цикл кодирования данных for i := sizeof(RevizorHDR) to MS.Size - 1 do begin b := byte( Pointer(Longint(MS.Memory) + i)^ ); w := word(i*30 + RevizorHDR.code_num * 5 + 753); b := (not b) xor w; asm ror b, 2 end; ResSize := 1; Move(b, Pointer(Longint(MS.Memory) + i)^, ResSize); end; RevizorHDR.CRC := 0; for i := 0 to MS.Size - 1 do RevizorHDR.CRC := DWORD(RevizorHDR.CRC + byte( Pointer(Longint(MS.Memory) + i)^ ) * i); MS.Seek(0,0); MS.Write(RevizorHDR, SizeOf(RevizorHDR)); MS.Seek(0,0); Result := true; {$R+} end; { TDiskRevizor } function TRevizor.AddRootDir(ADirName: string): boolean; var i : integer; begin Result := false; // Подготовка имени каталога ADirName := AnsiLowerCase(NormalDir(Trim(ADirName))); // Поиск в списке для блокировки повторного добавления for i := 0 to Length(DirsArray) - 1 do if pos(ADirName, AnsiLowerCase(DirsArray[i].FullDirName)) = 1 then exit; // Добавление SetLength(DirsArray, Length(DirsArray) + 1); DirsArray[Length(DirsArray) - 1] := TRevizorDir.Create(Self); DirsArray[Length(DirsArray) - 1].Parent := nil; DirsArray[Length(DirsArray) - 1].DirName := ADirName; end; procedure TRevizor.Clear; var i : integer; begin // Очистка классов if Length(DirsArray) > 0 then for i := 0 to Length(DirsArray) - 1 do if DirsArray[i] <> nil then begin DirsArray[i].Free; DirsArray[i] := nil; end; // Очистка таблицы DirsArray := nil; end; constructor TRevizor.Create; begin DirsArray := nil; LastRefreshMode := false; end; function TRevizor.DeleteRootDir(ADirName: string): boolean; var i : integer; begin Result := false; // Подготовка имени каталога ADirName := AnsiLowerCase(NormalDir(Trim(ADirName))); // Поиск в списке для блокировки повторного добавления for i := 0 to Length(DirsArray) - 1 do if pos(ADirName, AnsiLowerCase(DirsArray[i].FullDirName)) = 1 then begin DirsArray[i].Free; DirsArray[i] := nil; exit; end; end; destructor TRevizor.Destroy; begin Clear; inherited; end; { TRevizorDir } procedure TRevizorDir.Clear; var i : integer; begin // Очистка списка файлов if FilesArray.Count > 0 then for i := 0 to FilesArray.Count - 1 do if FilesArray[i] <> nil then begin TRevizorFile(FilesArray[i]).Free; FilesArray[i] := nil; end; FilesArray.Clear; // Очиска подкаталогов if Length(SubDirsArray) > 0 then for i := 0 to Length(SubDirsArray) - 1 do if SubDirsArray[i] <> nil then begin SubDirsArray[i].Free; SubDirsArray[i] := nil; end; SetLength(SubDirsArray, 0); SubDirsArray := nil; end; constructor TRevizorDir.Create; begin FParentRevizor := AParentRevizor; FilesArray := TList.Create; SubDirsArray := nil; Parent := nil; RC := 0; end; destructor TRevizorDir.Destroy; begin Clear; inherited; end; function TRevizorDir.GetFullDirName: string; begin Result := DirName; if Parent <> nil then Result := Parent.FullDirName + DirName; Result := NormalDir(Result); end; function TRevizorDir.Refresh(ASpeedMode : boolean = false) : boolean; var SR : TSearchRec; Res : integer; FDir : string; TmpFI : TRevizorFile; TmpDI : TRevizorDir; begin // Очистка Clear; FDir := NormalDir(FullDirName); // Сканирование Res := FindFirst(FDir+'*.*', faAnyFile ,SR); while Res = 0 do begin if (SR.Name <> '.') and (SR.Name <> '..') then if (SR.Attr and faDirectory) <> 0 then begin DoRevizorScanEvent(self, FDir + SR.Name, nil); TmpDI := TRevizorDir.Create(FParentRevizor); TmpDI.Parent := self; TmpDI.DirName := SR.Name; TmpDI.Refresh(ASpeedMode); // Добавление SetLength(SubDirsArray, length(SubDirsArray)+1); SubDirsArray[length(SubDirsArray)-1] := TmpDI; TmpDI := nil; end else begin if DoRevizorFltEvent(SR.name) then begin TmpFI := TRevizorFile.Create; ScanFile(Fdir, SR, TmpFI, ASpeedMode); FilesArray.Add(TmpFI); end; end; Res := FindNext(SR); end; FindClose(SR); end; function TRevizorDir.SaveToStream(AStream: TStream): boolean; var S : string; i : integer; b : byte; RevizorDirHDR : TRevizorDirHDR; RevizorFileHDR : TRevizorFileHDR; begin // Запись заголовка RevizorDirHDR.SIGN := 'D'; RevizorDirHDR.FilesCount := FilesArray.Count; RevizorDirHDR.SubdirsCount := length(SubDirsArray); AStream.Write(RevizorDirHDR, sizeof(RevizorDirHDR)); // Запись имени каталога S := DirName; b := length(S); AStream.Write(b, 1); AStream.Write(S[1], b); // Запись данных о файлах for i := 0 to FilesArray.Count - 1 do begin S := TRevizorFile(FilesArray[i]).Name; b := length(S); AStream.Write(b, 1); AStream.Write(S[1], b); RevizorFileHDR.Size := TRevizorFile(FilesArray[i]).Size; RevizorFileHDR.Attr := TRevizorFile(FilesArray[i]).Attr; RevizorFileHDR.CRC := TRevizorFile(FilesArray[i]).CRC; AStream.Write(RevizorFileHDR, SizeOf(RevizorFileHDR)); end; // Запись данных о подкаталогах for i := 0 to length(SubDirsArray) - 1 do SubDirsArray[i].SaveToStream(AStream); end; function TRevizorDir.LoadFromStream(AStream: TStream): boolean; var i : integer; b : byte; RevizorDirHDR : TRevizorDirHDR; RevizorFileHDR : TRevizorFileHDR; TmpFI : TRevizorFile; begin // Чтение заголовка AStream.Read(RevizorDirHDR, sizeof(RevizorDirHDR)); if RevizorDirHDR.SIGN <> 'D' then exit; SetLength(SubDirsArray, RevizorDirHDR.SubdirsCount); // Чтение имени каталога AStream.Read(b, 1); if b > 0 then begin SetLength(DirName, b); AStream.Read(DirName[1], b); end else DirName := ''; // Чтение данных о файлах if RevizorDirHDR.FilesCount > 0 then for i := 0 to RevizorDirHDR.FilesCount - 1 do begin TmpFI := TRevizorFile.Create; AStream.Read(b, 1); if b > 0 then begin SetLength(TmpFI.Name, b); AStream.Read(TmpFI.Name[1], b); end else TmpFI.Name := ''; AStream.Read(RevizorFileHDR, SizeOf(RevizorFileHDR)); TmpFI.Size := RevizorFileHDR.Size; TmpFI.Attr := RevizorFileHDR.Attr; TmpFI.CRC := RevizorFileHDR.CRC; FilesArray.Add(TmpFI); end; // Чтение данных о подкаталогах for i := 0 to length(SubDirsArray) - 1 do begin SubDirsArray[i] := TRevizorDir.Create(FParentRevizor); SubDirsArray[i].Parent := Self; SubDirsArray[i].LoadFromStream(AStream); end; end; function TRevizorDir.ScanFile(AFileDir: string; SR : TSearchRec; var Res: TRevizorFile;ASpeedMode : boolean = false): boolean; var CRC, Size: DWord; begin Res.Name := AnsiLowerCase(SR.Name); Res.Size := SR.Size; Res.Attr := byte(SR.Attr); Res.CRC := 0; // Вычисление CRC if not(ASpeedMode) then if CalkFileCRC(NormalDir(AFileDir) + SR.Name, CRC, Size) then Res.CRC := CRC; DoRevizorScanEvent(Self, NormalDir(AFileDir) + SR.Name, Res); Result := true; end; function TRevizor.Refresh(ASpeedMode : boolean = false) : boolean; var i : integer; begin Result := true; LastRefreshMode := ASpeedMode; // Очистка классов for i := 0 to Length(DirsArray) - 1 do if DirsArray[i] <> nil then DirsArray[i].Refresh(ASpeedMode); end; function TRevizor.SaveToStream(AStream: TmemoryStream): boolean; var i : integer; RevizorHDR : TRevizorHDR; w : word; begin Result := true; // Очистка потока AStream.Seek(0,0); AStream.Size := 0; // Сохранение заголовка RevizorHDR.SIGN := 'ARZ'; RevizorHDR.DateTime := Now; RevizorHDR.Version := 1.00; RevizorHDR.DopData := 0; RevizorHDR.Mode := 0; if LastRefreshMode then RevizorHDR.Mode := 1; RevizorHDR.RootDirCount := Length(DirsArray); AStream.Write(RevizorHDR, SizeOf(RevizorHDR)); // Сохранение маски сканирования w := length(FScanMask); AStream.Write(w, 2); if w > 0 then AStream.Write(FScanMask[1], w); // Сохранение маски исключения w := length(FExcludeMask); AStream.Write(w, 2); if w > 0 then AStream.Write(FExcludeMask[1], w); // Очистка классов for i := 0 to Length(DirsArray) - 1 do if DirsArray[i] <> nil then DirsArray[i].SaveToStream(AStream); CodeRevizorBinData(AStream); end; function TRevizor.LoadFromStream(AStream: TmemoryStream): boolean; var i : integer; w : word; begin clear; AStream.Seek(0,0); Result := DecodeRevizorBinData(AStream); if not(Result) then exit; AStream.Seek(0,0); AStream.Read(RevizorHDR, sizeof(RevizorHDR)); // Чтение маски сканирования AStream.Read(W, 2); if w > 0 then begin SetLength(FScanMask, w); AStream.Read(FScanMask[1], w); end else FScanMask := ''; // Чтение маски исключения AStream.Read(W, 2); if w > 0 then begin SetLength(FExcludeMask, w); AStream.Read(FExcludeMask[1], w); end else FExcludeMask := ''; SetLength(DirsArray, RevizorHDR.RootDirCount); for i := 0 to RevizorHDR.RootDirCount - 1 do begin DirsArray[i] := TRevizorDir.Create(Self); DirsArray[i].Parent := nil; DirsArray[i].LoadFromStream(AStream); end; end; function TRevizorDir.Compare(ASpeedMode : boolean = false) : boolean; var SR : TSearchRec; Res : integer; FDir, LowerName : string; TmpFI : TRevizorFile; i : integer; Found : integer; begin TmpFI := TRevizorFile.Create; FDir := NormalDir(FullDirName); if FilesArray.Count > 0 then for i := 0 to FilesArray.Count - 1 do TRevizorFile(FilesArray[i]).RC := 0; if i > 0 then for i := 0 to length(SubDirsArray) - 1 do SubDirsArray[i].RC := 0; // Сканирование Res := FindFirst(FDir+'*.*', faAnyFile ,SR); while Res = 0 do begin LowerName := AnsiLowerCase(SR.Name); if (SR.Name <> '.') and (SR.Name <> '..') then if (SR.Attr and faDirectory) <> 0 then begin Found := -1; for i := 0 to length(SubDirsArray) - 1 do if AnsiLowerCase(SubDirsArray[i].DirName) = LowerName then begin Found := i; SubDirsArray[i].RC := 1; SubDirsArray[i].Compare(ASpeedMode); // Мы нашли каталог и сканируем его рекурсивно end; if Found = -1 then // Это новый каталог DoRevizorCmpEvent(Self, LowerName, 5, nil, nil); end else begin Found := -1; if DoRevizorFltEvent(SR.name) then begin for i := 0 to FilesArray.Count - 1 do begin if TRevizorFile(FilesArray[i]).Name = LowerName then begin TRevizorFile(FilesArray[i]).RC := 1; Found := i; Break; end; end; if Found = -1 then begin // Это новый файл, такого еще не было DoRevizorCmpEvent(Self, LowerName, 2, nil, nil); end else begin // Такой файл есть в базе ScanFile(Fdir, SR, TmpFI, ASpeedMode); if CompareFiles(TmpFI, TRevizorFile(FilesArray[Found]), ASpeedMode) then DoRevizorCmpEvent(Self, TRevizorFile(FilesArray[Found]).Name, 3, TmpFI, TRevizorFile(FilesArray[Found])); // Файл изменен end; end; end; Res := FindNext(SR); end; // Удаленные файлы if FilesArray.Count > 0 then for i := 0 to FilesArray.Count - 1 do if TRevizorFile(FilesArray[i]).RC = 0 then DoRevizorCmpEvent(Self, TRevizorFile(FilesArray[i]).Name, 1, nil, TRevizorFile(FilesArray[i])); // Удаленные каталоги if length(SubDirsArray) > 0 then for i := 0 to length(SubDirsArray) - 1 do if SubDirsArray[i].RC = 0 then DoRevizorCmpEvent(Self, SubDirsArray[i].DirName, 4, nil, nil); FindClose(SR); TmpFI.Free; TmpFI := nil; end; function TRevizor.Compare(ASpeedMode : boolean = false) : boolean; var i : integer; begin Result := true; // Сравнение if Length(DirsArray) > 0 then for i := 0 to Length(DirsArray) - 1 do if DirsArray[i] <> nil then DirsArray[i].Compare(ASpeedMode); end; procedure TRevizor.SetOnScanFile(const Value: TRevizorScanEvent); begin FOnScanFile := Value; end; procedure TRevizor.SetOnCmpFile(const Value: TRevizorCmpEvent); begin FOnCmpFile := Value; end; procedure TRevizorDir.DoRevizorCmpEvent(Sender: TObject; ObjName: string; ACode: integer; F1, F2: TRevizorFile); begin if (FParentRevizor <> nil) and Assigned(FParentRevizor.FOnCmpFile) then FParentRevizor.FOnCmpFile(Sender, ObjName, ACode, F1, F2); end; procedure TRevizorDir.DoRevizorScanEvent(Sender: TObject; ObjName: string; F1 : TRevizorFile); begin if (FParentRevizor <> nil) and Assigned(FParentRevizor.FOnScanFile) then FParentRevizor.FOnScanFile(Sender, ObjName, F1); end; procedure TRevizor.SetOnFilterFile(const Value: TRevizorFltEvent); begin FOnFilterFile := Value; end; function TRevizorDir.DoRevizorFltEvent(ObjName: string): boolean; begin if (FParentRevizor <> nil) and Assigned(FParentRevizor.FOnFilterFile) then Result := FParentRevizor.FOnFilterFile(ObjName) else Result := true; end; procedure TRevizor.SetScanMask(const Value: string); begin FScanMask := Value; end; procedure TRevizor.SetExcludeMask(const Value: string); begin FExcludeMask := Value; end; function TRevizorDir.CompareFiles(F1, F2: TRevizorFile; ASpeedMode: boolean): boolean; begin Result := (F1.Size <> F2.Size); if not(ASpeedMode) then Result := Result or (F1.CRC <> F2.CRC); end; end.
//*************************************************************************** // // 名称:RTXC.Plugin.pas // 工具:RAD Studio XE6 // 日期:2014/11/8 15:11:21 // 作者:ying32 // QQ :396506155 // MSN :ying_32@live.cn // E-mail:yuanfen3287@vip.qq.com // Website:http://www.ying32.com // //--------------------------------------------------------------------------- // // 备注:RTX客户端插件类 // // //*************************************************************************** unit RTXC.Plugin; {$WARN SYMBOL_PLATFORM OFF} interface uses ComObj, Comserv, Variants, SysUtils, RTXCNotetipsPluginLib_TLB, RTXCAPILib_TLB, CLIENTOBJECTSLib_TLB, RTXCModulEinterfaceLib_TLB, // RTXC.ClientObjectsEventSink, RTXC.EventSink, RTXC.Event, StdVcl; type TRTXCNotetipsPlugin = class sealed(TAutoObject, IRTXCModule, IRTXCPlugin) private FRTXRoot: IRTXCRoot; FRTXModuleSite: IRTXCModuleSite; FClientObjectsModule: IClientObjectsModule; FModuleSiteEvent: TRTXCModuleSiteEventsSink; function getClassNoT: string; inline; function GetClientObjsModule: IClientObjectsModule; protected /// <remarks> /// 接口部分实现 /// </remarks> function Get_Identifier: WideString; safecall; function Get_ModuleSite: IDispatch; safecall; function Get_Name: WideString; safecall; function OnInvoke(Receiver, Parameter, Extra: OleVariant): OleVariant; safecall; procedure OnAccountChange; safecall; procedure OnLoad(const RTXCModuleSite: IDispatch); safecall; procedure OnUnload(Reason: RTXC_MODULE_UNLOAD_REASON); safecall; function Get_Info(Field: RTXC_PLUGIN_INFO_FIELD): WideString; safecall; public function GetModuleObject<T>(const Identifier: string): T; procedure SendMessage(const Receiver, ATitle, AMsg: string); procedure DoOnDataReceived(const Key: WideString); public property RTXRoot: IRTXCRoot read FRTXRoot; property RTXModuleSite: IRTXCModuleSite read FRTXModuleSite; property ClientObjectsModule: IClientObjectsModule read FClientObjectsModule; end; implementation uses RTXC.Consts, ufrmTipsWindow; { TRTXCNotetipsPlugin } function TRTXCNotetipsPlugin.Get_Identifier: WideString; begin Result := getClassNoT; end; function TRTXCNotetipsPlugin.Get_Info(Field: RTXC_PLUGIN_INFO_FIELD): WideString; begin Result := '事务提醒备忘录'; end; function TRTXCNotetipsPlugin.Get_ModuleSite: IDispatch; begin Result := FRTXModuleSite; end; function TRTXCNotetipsPlugin.Get_Name: WideString; begin Result := '备忘录'; end; procedure TRTXCNotetipsPlugin.OnAccountChange; begin end; function TRTXCNotetipsPlugin.OnInvoke(Receiver, Parameter, Extra: OleVariant): OleVariant; begin Result := null;; end; procedure TRTXCNotetipsPlugin.OnLoad(const RTXCModuleSite: IDispatch); begin if RTXCModuleSite = nil then begin FRTXRoot := nil; FRTXModuleSite := nil; Exit; end; FRTXModuleSite := RTXCModuleSite as IRTXCModuleSite; FRTXRoot := FRTXModuleSite.RTXCRoot; FClientObjectsModule := GetClientObjsModule; // Module Site Event FModuleSiteEvent := TRTXCModuleSiteEventsSink.Create(RTXModuleSite); FModuleSiteEvent.OnDataReceived := DoOnDataReceived; end; procedure TRTXCNotetipsPlugin.OnUnload(Reason: RTXC_MODULE_UNLOAD_REASON); safecall; begin if FModuleSiteEvent <> nil then FModuleSiteEvent.Free; end; procedure TRTXCNotetipsPlugin.DoOnDataReceived(const Key: WideString); var LData: IRTXCData; // LBuddyMgr: IRTXCRTXBuddyManager; // LBuddy: IRTXCRTXBuddy; begin try LData := RTXModuleSite.GetData(Key, True); except Exit; end; if LData <> nil then begin // LBuddyMgr := Self.RTXRoot.RTXBuddyManager; //LBuddy := LBuddyMgr.Buddy[LData.GetString(RDK_SENDER)]; ShowTipsWindow(LData.GetString(RDK_SENDER), LData.GetString(RDK_TITLE), LData.GetString(RDK_MSG_CONTENT)); end; end; function TRTXCNotetipsPlugin.getClassNoT: string; begin Result := ToString; Delete(Result, 1, 1); end; function TRTXCNotetipsPlugin.GetModuleObject<T>(const Identifier: string): T; type PT = ^T; var Obj: Cardinal; begin Obj := Cardinal(Pointer(FClientObjectsModule.Object_[Identifier])); Result := PT(@Obj)^; end; function TRTXCNotetipsPlugin.GetClientObjsModule: IClientObjectsModule; begin Result := FRTXRoot.Module[RTX_MODULE_IDENTIFIER_CLIENT_OBJS] as IClientObjectsModule; end; procedure TRTXCNotetipsPlugin.SendMessage(const Receiver, ATitle, AMsg: string); var LData: IRTXCData; begin try LData := FRTXRoot.CreateRTXCData; LData.SetString(RDK_KEY, GUIDToString(TGuid.NewGuid)); LData.SetString(RDK_TITLE, ATitle); LData.SetString(RDK_MSG_CONTENT, AMsg); RTXModuleSite.SendData(Receiver, LData, RTXC_SEND_DATA_FLAG_FILTERING_IS_FORBIDDEN); except end; end; initialization TAutoObjectFactory.Create(ComServer, TRTXCNotetipsPlugin, CLASS_RTXCNotetipsPlugin, ciMultiInstance, tmApartment); end.
unit Builder.Interfaces.IDirector; interface uses Builder.Interfaces.IBuilder; type IDirector = interface ['{90EDD5E5-3A76-407C-97B3-3F0E1A099817}'] function MakeSUV(ABuilder: IBuilder): IBuilder; function MakeSportsCar(ABuilder: IBuilder): IBuilder; function MakePopularCar(ABuilder: IBuilder): IBuilder; end; implementation end.
unit uCadastroKit; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uCadastroPadrao, Data.DB, Datasnap.DBClient, Vcl.StdCtrls, Vcl.Grids, Vcl.DBGrids, DBGridCBN, Vcl.ComCtrls, Vcl.Imaging.pngimage, Vcl.ExtCtrls, Vcl.Buttons, frameBuscaProduto, Vcl.Mask, RxToolEdit, RxCurrEdit, Contnrs; type TfrmCadastroKit = class(TfrmCadastroPadrao) edtCodigo: TCurrencyEdit; edtKit: TEdit; lblRazao: TLabel; DBGridCBN1: TDBGridCBN; BuscaProduto1: TBuscaProduto; btnAddProduto: TBitBtn; cdsProd: TClientDataSet; dsProd: TDataSource; Label1: TLabel; cdsProdcodigo: TIntegerField; cdsProdcodigo_produto: TIntegerField; cdsProdproduto: TStringField; cdsCODIGO: TIntegerField; cdsDESCRICAO: TStringField; Label2: TLabel; edtQtde: TCurrencyEdit; Label3: TLabel; cdsProdqtde: TIntegerField; procedure FormCreate(Sender: TObject); procedure btnAddProdutoClick(Sender: TObject); procedure DBGridCBN1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private LExcluidos :TStringList; private { Altera um registro existente no CDS de consulta } procedure AlterarRegistroNoCDS(Registro :TObject); override; { Carrega todos os registros pra aba de Consulta } procedure CarregarDados; override; procedure ExecutarDepoisAlterar; override; procedure ExecutarDepoisIncluir; override; { Inclui um registro no CDS } procedure IncluirRegistroNoCDS(Registro :TObject); override; { Limpa as informações da aba Dados } procedure LimparDados; override; { Mostra um registro detalhado na aba de Dados } procedure MostrarDados; override; private { Persiste os dados no banco de dados } function GravarDados :TObject; override; { Verifica os dados antes de persistir } function VerificaDados :Boolean; override; private procedure ExcluiProdutoKit; end; var frmCadastroKit: TfrmCadastroKit; implementation uses Kit, Repositorio, FabricaRepositorio, Produto_Kit; {$R *.dfm} { TfrmCadastroPadrao2 } procedure TfrmCadastroKit.AlterarRegistroNoCDS(Registro: TObject); var Kit :TKit; begin inherited; Kit := (Registro as TKit); self.cds.Edit; self.cdsCODIGO.AsInteger := Kit.codigo; self.cdsDESCRICAO.AsString := Kit.descricao; self.cds.Post; end; procedure TfrmCadastroKit.btnAddProdutoClick(Sender: TObject); begin if not assigned(BuscaProduto1.Produto) then exit; cdsProd.Append; cdsProdcodigo_produto.AsInteger := BuscaProduto1.Produto.codigo; cdsProdproduto.AsString := BuscaProduto1.Produto.descricao; cdsProdqtde.AsInteger := edtQtde.AsInteger; cdsProd.Post; BuscaProduto1.limpa; BuscaProduto1.edtCodigo.SetFocus; end; procedure TfrmCadastroKit.CarregarDados; var Kits :TObjectList; Repositorio :TRepositorio; nX :Integer; begin inherited; Repositorio := nil; Kits := nil; try Repositorio := TFabricaRepositorio.GetRepositorio(TKit.ClassName); Kits := Repositorio.GetAll; if Assigned(Kits) and (Kits.Count > 0) then begin for nX := 0 to (Kits.Count-1) do self.IncluirRegistroNoCDS(Kits.Items[nX]); end; finally FreeAndNil(Repositorio); FreeAndNil(Kits); end; end; procedure TfrmCadastroKit.DBGridCBN1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_Delete then begin if confirma('Confirma remoção do produto "'+cdsProdproduto.AsString+'" deste kit?') then begin if not assigned(LExcluidos) then LExcluidos := TStringList.Create; if cdsProdcodigo.AsInteger > 0 then LExcluidos.Add(cdsProdcodigo.AsString); cdsProd.Delete; end; end; end; procedure TfrmCadastroKit.ExcluiProdutoKit; var i :integer; Kit :TKit; begin try Kit := TKit.Create; for i := 0 to LExcluidos.Count-1 do Kit.RemoveKit(StrToInt(LExcluidos[i])); finally FreeAndNil(Kit); end; end; procedure TfrmCadastroKit.ExecutarDepoisAlterar; begin inherited; edtKit.SetFocus; end; procedure TfrmCadastroKit.ExecutarDepoisIncluir; begin inherited; edtKit.SetFocus; end; procedure TfrmCadastroKit.FormCreate(Sender: TObject); begin inherited; cdsProd.CreateDataSet; end; function TfrmCadastroKit.GravarDados: TObject; var Kit :TKit; RepositorioKit :TRepositorio; codigoCidade :integer; ProdutoKit :TProduto_kit; i :integer; begin Kit := nil; RepositorioKit := nil; try RepositorioKit := TFabricaRepositorio.GetRepositorio(TKit.ClassName); Kit := TKit(RepositorioKit.Get(self.edtCodigo.AsInteger)); if not Assigned(Kit) then Kit := TKit.Create; Kit.descricao := TRIM( self.edtKit.Text ); cdsProd.First; while not cdsProd.Eof do begin ProdutoKit := TProduto_kit.Create; ProdutoKit.codigo := cdsProdcodigo.AsInteger; ProdutoKit.codigo_produto := cdsProdcodigo_produto.AsInteger; ProdutoKit.quantidade := cdsProdqtde.AsInteger; Kit.addKit(ProdutoKit); cdsProd.Next; end; RepositorioKit.Salvar(Kit); if assigned(LExcluidos) then ExcluiProdutoKit; result := Kit; finally FreeAndNil(RepositorioKit); end; end; procedure TfrmCadastroKit.IncluirRegistroNoCDS(Registro: TObject); var Kit :TKit; begin inherited; Kit := (Registro as TKit); self.cds.Append; self.cdsCODIGO.AsInteger := Kit.codigo; self.cdsDESCRICAO.AsString := Kit.descricao; self.cds.Post; end; procedure TfrmCadastroKit.LimparDados; begin inherited; edtCodigo.Clear; edtKit.Clear; cdsProd.EmptyDataSet; BuscaProduto1.limpa; if assigned(LExcluidos) then FreeAndNil(LExcluidos); end; procedure TfrmCadastroKit.MostrarDados; var Kit :TKit; RepositorioKit :TRepositorio; ProdutoKit :TProduto_kit; begin inherited; Kit := nil; RepositorioKit := nil; try RepositorioKit := TFabricaRepositorio.GetRepositorio(TKit.ClassName); Kit := TKit(RepositorioKit.Get(cdsCODIGO.AsInteger)); if not Assigned(Kit) then exit; self.edtCodigo.AsInteger := Kit.codigo; self.edtKit.Text := Kit.descricao; for ProdutoKit in Kit.ProdutosKit do begin cdsProd.Append; cdsProdcodigo.AsInteger := ProdutoKit.codigo; cdsProdcodigo_produto.AsInteger := ProdutoKit.codigo_produto; cdsProdproduto.AsString := ProdutoKit.Produto.descricao; cdsProdqtde.AsInteger := ProdutoKit.quantidade; cdsProd.Post; end; finally FreeAndNil(RepositorioKit); FreeAndNil(Kit); end; end; function TfrmCadastroKit.VerificaDados: Boolean; begin result := false; if trim(edtKit.Text) = '' then begin avisar('Favor informar o nome do kit'); edtKit.SetFocus; end else if cdsProd.IsEmpty then begin avisar('Nenhum produto foi informado, favor informar.'); BuscaProduto1.edtCodigo.SetFocus; end else result := true; end; end.
{==============================================================================* * Copyright © 2020, Pukhkiy Igor * * All rights reserved. * *==============================================================================* * 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/. * *==============================================================================* * The Initial Developer of the Original Code is Pukhkiy Igor (Ukraine). * * Contacts: nspytnik-programming@yahoo.com * *==============================================================================* * DESCRIPTION: * * RDBDataModule.pas - module init connection * * Last modified: 29.07.2020 17:49:30 * * Author : Pukhkiy Igor * * Email : nspytnik-programming@yahoo.com * * www : * * * * File version: 0.0.0.1d * *==============================================================================} unit RDBDataModule; interface uses System.SysUtils, System.Classes, RDBManager, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Phys, FireDAC.Comp.Client, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.ConsoleUI.Wait, FireDAC.Phys.PG, FireDAC.Phys.PGDef, FireDAC.Phys.SQLite, FireDAC.Phys.SQLiteDef, FireDAC.DApt, Data.DB, FireDAC.Moni.Base, FireDAC.Moni.RemoteClient, CrtUtils, RDBTimer; type TRDBM = class(TDataModule) FDManager: TFDManager; FDMoniRemoteClientLink: TFDMoniRemoteClientLink; procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); procedure FDConnectionRecover(ASender, AInitiator: TObject; AException: Exception; var AAction: TFDPhysConnectionRecoverAction); procedure FDConnectionRestored(Sender: TObject); procedure FDConnectionLost(Sender: TObject); procedure FDConnectionError(ASender, AInitiator: TObject; var AException: Exception); private { Private declarations } FRDBManager: TRDBManager; FConnected: Boolean; FVisitBusy,FVisitError: Boolean; FLastDBError: Exception; procedure OnTimerRecovery(Id: Integer; Context: TObject); procedure OnVisit(Id: Integer; Context: TObject); function GetClientID: string; public { Public declarations } procedure ReConnect; procedure Terminate; function GetNewConnection(const ConnectionDefName: string): TFDCustomConnection; procedure ReleaseConnection(Conn: TFDCustomConnection); procedure OnException(E: Exception); end; var RDBM: TRDBM; ConnectionMaster: string = 'master-connection'; ConnectionSlave: string = 'slave-connection'; ConnectionFile: string = 'ConnDef.ini'; TimerVisit: Integer = 15; ApplicationName: string = 'RDB v1.0(Replication database application)'; const ApplicationNameDef = 'RDB v%s(Replication database application)'; idMasterUTimer = 0; idMasterDTimer = 1; idSlaveUTimer = 2; idSlaveDTimer = 3; idVisitTimer = 4; implementation {%CLASSGROUP 'System.Classes.TPersistent'} uses Logger, Windows, TypInfo; {$R *.dfm} procedure TRDBM.DataModuleCreate(Sender: TObject); begin FDManager.ConnectionDefFileName := ConnectionFile; FRDBManager := TRDBManager.Create(TRDBAlertPG); FRDBManager.OnException := OnException; end; procedure TRDBM.DataModuleDestroy(Sender: TObject); begin Terminate; FRDBManager.Free; end; procedure TRDBM.FDConnectionError(ASender, AInitiator: TObject; var AException: Exception); var E: EFDDBEngineException absolute AException; conn: TFDCustomConnection; s: string; begin FLastDBError := AException; { TODO : Добавить синхронизацию ислючений, чтобы не дублировались } if not (AException is EFDDBEngineException) then begin LogE('[CONNECTION ERROR] ClassName: %s, Message: %s', [AException.ClassName, AException.Message]); end else if (E.Kind <> ekUKViolated) then begin LogE('[CONNECTION ERROR] ClassName: %s, Message: %s => SQL: %s Params: %s', [E.ClassName, E.Message, E.SQL, E.Params.CommaText]); end; if (AException is EFDDBEngineException) then begin s := Format('ClassName: %s, Message: %s => SQL: %s Params: %s', [E.ClassName, E.Message, E.SQL, E.Params.CommaText]); conn := GetNewConnection(ConnectionMaster); try conn.ExecSQL('INSERT INTO _replica.logger (client_id, msg, msg_type) VALUES (:id, :msg, :type)', [GetClientID, s, GetEnumName(TypeInfo(TFDCommandExceptionKind), Integer(E.Kind))], [ftLargeint, ftString, ftString]); except // ну шлепнули нам здесь, чего в цикл пускать? // тихо уходим end; ReleaseConnection(conn); end; end; procedure TRDBM.FDConnectionLost(Sender: TObject); var conn: TFDCustomConnection absolute Sender; begin LogW('[CONNECTION LOST] Name: %s', [conn.ConnectionDefName]); try FRDBManager.Alerter.Active := false; except on E: Exception do LogE('ClassName: %s Message: %s', [E.ClassName, E.Message]); end; if conn.Tag = idMasterUTimer then begin CRTTimer.Change(idMasterUTimer, -1, -1, nil, true, nil); CRTTimer.Change(idMasterDTimer, idxValueMasterDTime, 15, conn, false, OnTimerRecovery); end else begin CRTTimer.Change(idSlaveUTimer, -1, -1, nil, true, nil); CRTTimer.Change(idSlaveDTimer, idxValueSlaveDTime, 15, conn, false, OnTimerRecovery); end; end; procedure TRDBM.FDConnectionRecover(ASender, AInitiator: TObject; AException: Exception; var AAction: TFDPhysConnectionRecoverAction); var conn: TFDCustomConnection absolute ASender; begin LogW('[CONNECTION RECOVER] Action: %d ClassName: %s Message: %s', [Integer(AAction), AException.ClassName, AException.Message]); FRDBManager.Paused := true; end; procedure TRDBM.FDConnectionRestored(Sender: TObject); begin LogW('[CONNECTION RESTORED] ClassName: ' + Sender.ClassName); FRDBManager.Alerter.Active := true; FRDBManager.Paused := false; FRDBManager.UpdateTable('', ''); end; var id: Integer; function TRDBM.GetClientID: string; begin Result := FRDBManager.GetClientID end; function TRDBM.GetNewConnection(const ConnectionDefName: string): TFDCustomConnection; begin Result := TFDConnection.Create(Self); Result.ConnectionDefName := ConnectionDefName; Result.LoginPrompt := false; Result.TxOptions.Isolation := xiSnapshot; Result.OnError := FDConnectionError; Result.OnLost := FDConnectionLost; Result.OnRestored := FDConnectionRestored; Result.OnRecover := FDConnectionRecover; Result.Name := 'Con_'+id.ToString; Result.Params.Values['ApplicationName'] := ApplicationName; Inc(id); Result.Connected := true; end; procedure TRDBM.OnException(E: Exception); var Inner: Exception; begin if E = FLastDBError then begin LogE('Aborted!'); exit; end; FLastDBError := nil; Inner := E; while Inner <> nil do begin LogE('ClassName: %s Message: %s', [Inner.ClassName, Inner.Message]); Inner := Inner.InnerException; end; end; procedure TRDBM.OnTimerRecovery(Id: Integer; Context: TObject); var c: TFDConnection absolute Context; begin LogI('[OnTimerRecovery] TRY RECOVERY ID = %d',[ID]); try c.Ping; if c.Connected and c.Ping then begin if c.InTransaction then c.Rollback; CRTTimer.Change(id, -1, -1, nil, true, nil); if c.Tag = idMasterUTimer then CRTTimer.Change(idMasterUTimer, idxValueMasterUTime, -1, c, false, nil) else CRTTimer.Change(idSlaveUTimer, idxValueSlaveUTime, -1, c, false, nil); LogI('[OnTimerRecovery] RECOVERY SUCCESS ID = %d', [ID]); if FRDBManager.CanExecute then begin FRDBManager.Alerter.Active := true; FRDBManager.Paused := false; FRDBManager.UpdateTable('', ''); end; end; except on E: Exception do LogE('[OnTimerRecovery] ClassName: %s Message: %s', [E.ClassName, E.Message]); end; end; procedure TRDBM.OnVisit(Id: Integer; Context: TObject); begin try FVisitBusy := not FRDBManager.ClientVisit; except on E: Exception do begin FVisitError := true; LogE('client_visit() ClassName: %s Message: %s', [E.ClassName, E.Message]); end; end; end; procedure TRDBM.ReConnect; var s: string; c: IFDStanConnectionDef; conn: TFDCustomConnection; begin if FindCmdLineSwitch('file', s) then ConnectionFile := s; if FindCmdLineSwitch('master', s) then ConnectionMaster := s; if FindCmdLineSwitch('slave', s) then ConnectionSlave := s; FRDBManager.Paused := true; FDManager.Close; FDManager.ConnectionDefFileName := ConnectionFile; FDManager.Open; c := FDManager.ConnectionDefs.ConnectionDefByName(ConnectionMaster); PanelUpdateValue(idxValueMasterName, c.Name); PanelUpdateValue(idxValueMasterSrv, TFDPhysPGConnectionDefParams(c.Params).Server); PanelUpdateValue(idxValueMasterDB, c.Params.Database); c := FDManager.ConnectionDefs.ConnectionDefByName(ConnectionSlave); PanelUpdateValue(idxValueSlaveName, c.name); PanelUpdateValue(idxValueSlaveSrv, TFDPhysPGConnectionDefParams(c.Params).Server); PanelUpdateValue(idxValueSlaveDB, c.Params.Database); c := nil; FRDBManager.Paused := true; FDManager.Close; FDManager.ConnectionDefFileName := ConnectionFile; FDManager.Open; conn := GetNewConnection(ConnectionMaster); CRTTimer.Clear; conn.Tag := idMasterUTimer; CRTTimer.Add(idMasterUTimer, idxValueMasterUTime, -1, conn, false, nil); CRTTimer.Add(idMasterDTimer, -1, -1, nil, true, nil); ReleaseConnection(FRDBManager.SrcConnection(conn)); conn := GetNewConnection(ConnectionSlave); conn.Tag := idSlaveUTimer; CRTTimer.Add(idSlaveUTimer, idxValueSlaveUTime, -1, conn, false, nil); CRTTimer.Add(idSlaveDTimer, -1, -1, nil, true, nil); ReleaseConnection(FRDBManager.DestConnection(conn)); CRTTimer.Add(idVisitTimer, -1, 60 * TimerVisit, nil, false, OnVisit); WriteInfo('Started ' + DateTimeToStr(Now) + '.'); WriteInfo('Code page = '+ GetACP.ToString); WriteInfo('log enable = '+ BoolToStr(FindCmdLineSwitch('log'), true)); WriteInfo('timer visit = %d min', [TimerVisit]); OnVisit(-1, nil); if not FVisitBusy and not FVisitError then begin FRDBManager.Paused := false; FRDBManager.UpdateTable('', ''); end else if not FVisitError then begin WriteInfo('Application in IDLE mode. Other client has connection to replication.'); end else begin WriteInfo('Erorr occured.'); end; end; procedure TRDBM.ReleaseConnection(Conn: TFDCustomConnection); begin if Conn <> nil then begin Conn.Connected := false; Conn.Free; end; end; procedure TRDBM.Terminate; begin FRDBManager.Terminate; FRDBManager.WaitFor; FDManager.Close; ReleaseConnection(FRDBManager.SrcConnection(nil)); ReleaseConnection(FRDBManager.DestConnection(nil)); end; end.
unit DIOTA.Dto.Response.GetNodeInfoResponse; interface uses DIOTA.IotaAPIClasses; type TGetNodeInfoResponse = class(TIotaAPIResponse) private FFeatures: TArray<String>; FLatestMilestoneIndex: Integer; FJreVersion: String; FJreFreeMemory: Int64; FTransactionsToRequest: Integer; FLatestSolidSubtangleMilestone: String; FJreAvailableProcessors: Integer; FJreMaxMemory: Int64; FTips: Integer; FTime: Int64; FLatestMilestone: String; FPacketsQueueSize: Integer; FJreTotalMemory: Int64; FNeighbors: Integer; FLatestSolidSubtangleMilestoneIndex: Integer; FAppVersion: String; FAppName: String; FMilestoneStartIndex: Integer; FCoordinatorAddress: String; function GetFeatures(Index: Integer): String; function GetFeaturesCount: Integer; public constructor Create(AAppName: String); reintroduce; overload; virtual; constructor Create(AAppName, AAppVersion, AJreVersion: String; AJreAvailableProcessors: Integer; AJreFreeMemory, AJreMaxMemory, AJreTotalMemory: Int64; ALatestMilestone: String; ALatestMilestoneIndex: Integer; ALatestSolidSubtangleMilestone: String; ALatestSolidSubtangleMilestoneIndex: Integer; AMilestoneStartIndex: Integer; ANeighbors, APacketsQueueSize: Integer; ATime: Int64; ATips, ATransactionsToRequest: Integer; AFeatures: TArray<String>; ACoordinatorAddress: String); reintroduce; overload; virtual; //Name of the IOTA software you're currently using. (IRI stands for IOTA Reference Implementation) property AppName: String read FAppName; //The version of the IOTA software this node is running. property AppVersion: String read FAppVersion; //The JRE version this node runs on property JreVersion: String read FJreVersion; //Available cores for JRE on this node. property JreAvailableProcessors: Integer read FJreAvailableProcessors; //The amount of free memory in the Java Virtual Machine. property JreFreeMemory: Int64 read FJreFreeMemory; //The maximum amount of memory that the Java virtual machine will attempt to use. property JreMaxMemory: Int64 read FJreMaxMemory; //The total amount of memory in the Java virtual machine. property JreTotalMemory: Int64 read FJreTotalMemory; //The hash of the latest transaction that was signed off by the coordinator. property LatestMilestone: String read FLatestMilestone; //Index of the @link #latestMilestone property LatestMilestoneIndex: Integer read FLatestMilestoneIndex; { * The hash of the latest transaction which is solid and is used for sending transactions. * For a milestone to become solid, your local node must approve the subtangle of coordinator-approved transactions, * and have a consistent view of all referenced transactions. } property LatestSolidSubtangleMilestone: String read FLatestSolidSubtangleMilestone; //Index of the @link #latestSolidSubtangleMilestone property LatestSolidSubtangleMilestoneIndex: Integer read FLatestSolidSubtangleMilestoneIndex; //The start index of the milestones. //This index is encoded in each milestone transaction by the coordinator property MilestoneStartIndex: Integer read FMilestoneStartIndex; //Number of neighbors this node is directly connected with. property Neighbors: Integer read FNeighbors; //The amount of transaction packets which are currently waiting to be broadcast. property PacketsQueueSize: Integer read FPacketsQueueSize; //The difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC property Time: Int64 read FTime; //Number of tips in the network property Tips: Integer read FTips; { * When a node receives a transaction from one of its neighbors, * this transaction is referencing two other transactions t1 and t2 (trunk and branch transaction). * If either t1 or t2 (or both) is not in the node's local database, * then the transaction hash of t1 (or t2 or both) is added to the queue of the "transactions to request". * At some point, the node will process this queue and ask for details about transactions in the * "transaction to request" queue from one of its neighbors. * This number represents the amount of "transaction to request" } property TransactionsToRequest: Integer read FTransactionsToRequest; //Every node can have features enabled or disabled. //This list will contain all the names of the features of a node as specified in {@link Feature}. property Features[Index: Integer]: String read GetFeatures; property FeaturesCount: Integer read GetFeaturesCount; //The address of the Coordinator being followed by this node. property CoordinatorAddress: String read FCoordinatorAddress; end; implementation { TGetNodeInfoResponse } constructor TGetNodeInfoResponse.Create(AAppName, AAppVersion, AJreVersion: String; AJreAvailableProcessors: Integer; AJreFreeMemory, AJreMaxMemory, AJreTotalMemory: Int64; ALatestMilestone: String; ALatestMilestoneIndex: Integer; ALatestSolidSubtangleMilestone: String; ALatestSolidSubtangleMilestoneIndex, AMilestoneStartIndex, ANeighbors, APacketsQueueSize: Integer; ATime: Int64; ATips, ATransactionsToRequest: Integer; AFeatures: TArray<String>; ACoordinatorAddress: String); begin inherited Create; FAppName := AAppName; FAppVersion := AAppVersion; FJreVersion := AJreVersion; FJreAvailableProcessors := FJreAvailableProcessors; FJreFreeMemory := AJreFreeMemory; FJreMaxMemory := AJreMaxMemory; FJreTotalMemory := AJreTotalMemory; FLatestMilestone := ALatestMilestone; FLatestMilestoneIndex := ALatestMilestoneIndex; FLatestSolidSubtangleMilestone := ALatestSolidSubtangleMilestone; FLatestSolidSubtangleMilestoneIndex := ALatestSolidSubtangleMilestoneIndex; FMilestoneStartIndex := AMilestoneStartIndex; FNeighbors := ANeighbors; FPacketsQueueSize := APacketsQueueSize; FTime := ATime; FTips := ATips; FTransactionsToRequest := ATransactionsToRequest; FFeatures := AFeatures; FCoordinatorAddress := ACoordinatorAddress; end; constructor TGetNodeInfoResponse.Create(AAppName: String); begin FAppName := AAppName; end; function TGetNodeInfoResponse.GetFeatures(Index: Integer): String; begin Result := FFeatures[Index]; end; function TGetNodeInfoResponse.GetFeaturesCount: Integer; begin Result := Length(FFeatures); end; end.
unit AppConfiguration; interface uses System.SysUtils, System.Classes, System.JSON, System.IOUtils; type TAppConfiguration = class private const KeySourceUnitsSearch = 'sourceUnitsSearch'; KeyReadmeIsUpdate = 'readmeIsUpdateVersion'; KeyReadmeFilePath = 'readmeFileName'; KeyReadmeSearchPattern = 'readmeSearchPattern'; private FSourceDir: string; FSrcSearchPattern: string; FReadmeIsUpdate: boolean; FReadmeFilePath: string; FReadmeSearchPattern: string; function PosTrillingBackslash(const aText: string): integer; public procedure LoadFromFile; property SourceDir: string read FSourceDir write FSourceDir; property SrcSearchPattern: string read FSrcSearchPattern write FSrcSearchPattern; property ReadmeIsUpdate: boolean read FReadmeIsUpdate write FReadmeIsUpdate; property ReadmeFilePath: string read FReadmeFilePath write FReadmeFilePath; property ReadmeSearchPattern: string read FReadmeSearchPattern write FReadmeSearchPattern; end; implementation function TAppConfiguration.PosTrillingBackslash(const aText: string): integer; begin Result := aText.Length; while (Result > 0) and (aText[Result] <> '\') do Result := Result - 1; end; procedure TAppConfiguration.LoadFromFile; var aJsonData: string; jsObject: TJSONObject; jsTrue: TJSONTrue; aSourceUnitsSearch: string; i: integer; begin aJsonData := TFile.ReadAllText('app-config.json'); jsObject := TJSONObject.ParseJSONValue(aJsonData) as TJSONObject; jsTrue := TJSONTrue.Create; try aSourceUnitsSearch := jsObject.GetValue(KeySourceUnitsSearch).Value; i := PosTrillingBackslash(aSourceUnitsSearch); SourceDir := aSourceUnitsSearch.Substring(0, i); SrcSearchPattern := aSourceUnitsSearch.Substring(i); ReadmeIsUpdate := (jsObject.GetValue(KeyReadmeIsUpdate) .Value = jsTrue.Value); ReadmeFilePath := jsObject.GetValue(KeyReadmeFilePath).Value; ReadmeSearchPattern := jsObject.GetValue(KeyReadmeSearchPattern).Value; finally jsObject.Free; jsTrue.Free; end; end; end.
unit cCadProduto; interface uses classes, controls, SysUtils,ExtCtrls, Dialogs, ZAbstractConnection, ZConnection, ZAbstractRODataset, ZAbstractDataset, ZDataset; Type TProduto= class private ConexaoDB:TZConnection; //passando a conexão em tempo de criação da classe F_produtoId:integer; F_nome:String; F_descricao:String; F_valor:Double; F_quantidade:Double; F_categoriaID:integer; public constructor Create(aConexao:TZConnection); destructor Destroy; override; function Inserir:Boolean; function Atualizar:Boolean; function Apagar:Boolean; function Selecionar(id:integer):Boolean; published property codigo :integer read F_produtoId write F_produtoId; property nome :string read F_nome write F_nome; property descricao :string read F_descricao write F_descricao; property valor :Double read F_valor write F_valor; property quantidade :Double read F_quantidade write F_quantidade; property categoriaID :integer read F_categoriaID write F_categoriaID; end; implementation { TProduto } {$Region Construtor e destructor'} constructor TProduto.Create(aConexao: TZConnection); begin ConexaoDB:= aConexao; end; destructor TProduto.Destroy; begin inherited; end; {$endRegion} function TProduto.Apagar: Boolean; var Qry:TZQuery; begin if MessageDlg('Apagar o Registro: '+#13+#13+ 'Código: '+IntToStr(F_produtoId)+ #13+ 'Descrição: '+F_nome, mtConfirmation, [mbYes, mbNo],0)=mrNo then begin Result:=false; Abort; end; try Qry:= TZQuery.Create(nil); Qry.Connection:=ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('delete from produtos where produtoId=:produtoId'); Qry.ParamByName('produtoId').AsInteger:= F_produtoId; try Qry.ExecSQL except result:=false; end; finally if Assigned(Qry)then FreeAndNil(Qry); end; end; function TProduto.Atualizar: Boolean; var Qry:TZQuery; begin result:=true; try Qry:= TZQuery.Create(nil); Qry.Connection:=ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add(' Update produtos '+ 'set nome = :nome ,'+ 'descricao =:descricao, '+ 'valor =:valor, '+ 'quantidade =:quantidade, '+ 'categoriaID =:categoriaID '+ 'where produtoId =:produtoId'); Qry.ParamByName('produtoId').AsInteger:=Self.F_produtoId; Qry.ParamByName('nome').AsString:=Self.F_nome; Qry.ParamByName('descricao').AsString:=Self.F_descricao; Qry.ParamByName('valor').AsFloat:=Self.F_valor; Qry.ParamByName('quantidade').AsFloat:=Self.F_quantidade; Qry.ParamByName('categoriaID').AsInteger:=Self.F_categoriaID; try Qry.ExecSQL except result:=false; end; finally if Assigned(Qry)then FreeAndNil(Qry); end; end; function TProduto.Inserir: Boolean; var Qry:TZQuery; begin result:=true; try Qry:= TZQuery.Create(nil); Qry.Connection:=ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('insert into produtos '+ ' ( nome, '+ ' descricao, '+ ' valor, '+ ' quantidade, '+ ' categoriaID) '+ ' values (:nome , '+ ' :descricao , '+ ' :valor, '+ ' :quantidade, '+ ' :categoriaID)'); Qry.ParamByName('nome').AsString:=Self.F_nome; Qry.ParamByName('descricao').AsString:=Self.F_descricao; Qry.ParamByName('valor').AsFloat:=Self.F_valor; Qry.ParamByName('quantidade').AsFloat:=Self.F_quantidade; Qry.ParamByName('categoriaID').AsInteger:=Self.F_categoriaID; try Qry.ExecSQL except result:=false; end; finally if Assigned(Qry)then FreeAndNil(Qry); end; end; function TProduto.Selecionar(id: integer): Boolean; var Qry:TZQuery; begin result:=true; try Qry:= TZQuery.Create(nil); Qry.Connection:=ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add( 'select produtoId,'+ ' nome, '+ ' descricao, '+ ' valor, '+ ' quantidade, '+ ' categoriaID '+ ' From produtos '+ ' Where produtoId =:produtoId'); Qry.ParamByName('produtoId').Value:=id; try Qry.Open; Self.F_produtoId:= Qry.FieldByName('produtoId').AsInteger; Self.F_nome:= Qry.FieldByName('nome').AsString; Self.F_descricao:= Qry.FieldByName('descricao').AsString; Self.F_valor:= Qry.FieldByName('valor').AsFloat; Self.F_quantidade:= Qry.FieldByName('quantidade').AsFloat; Self.F_categoriaID:= Qry.FieldByName('categoriaID').AsInteger; except result:=false; end; finally if Assigned(Qry)then FreeAndNil(Qry); end; end; end.
unit frRentabilidadMercado; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Gauges, ExtCtrls, dmRentabilidadMercado, GIFImg; type TfRentabilidadMercado = class(TFrame) pGananciasCerradoUSA: TPanel; Image11: TImage; Label47: TLabel; Label49: TLabel; pGananciasAbiertoUSA: TPanel; Image15: TImage; lLargo: TLabel; Label36: TLabel; gAbiertoGananciaLargos: TGauge; gAbiertoPerdidasLargos: TGauge; gAbiertoGananciasCortos: TGauge; gAbiertoPerdidasCortos: TGauge; gCerradoPerdidasLargos: TGauge; gCerradoGananciasCortos: TGauge; gCerradoPerdidasCortos: TGauge; gCerradoGananciasLargos: TGauge; lCerradoGananciasLargos: TLabel; lCerradoPerdidasLargos: TLabel; lCerradoGananciasCortos: TLabel; lCerradoPerdidasCortos: TLabel; lAbiertoGananciaLargos: TLabel; lAbiertoPerdidasLargos: TLabel; lAbiertoGananciasCortos: TLabel; lAbiertoPerdidasCortos: TLabel; Bevel1: TBevel; private lastOIDMercado, lastOIDSesion: integer; rentabilidad: TRentabilidadMercado; procedure ConfigControls(const maxAbiertas, maxCerradas: currency); public constructor Create(AOwner: TComponent); override; procedure Reset; procedure Load(const OIDSesion, OIDMercado: integer); overload; procedure Load(const OIDSesion, OIDMercado: integer; const maxAbiertas, maxCerradas: currency); overload; // procedure Close; end; implementation {$R *.dfm} uses IBCustomDataSet; { TfRentabilidadMercado } procedure TfRentabilidadMercado.Load(const OIDSesion, OIDMercado: integer); var maxCerradas, maxAbiertas: currency; begin if (lastOIDMercado <> OIDMercado) or (lastOIDSesion <> OIDSesion) then begin lastOIDMercado := OIDMercado; lastOIDSesion := OIDSesion; rentabilidad.Load(OIDSesion, OIDMercado); maxAbiertas := 0; if maxAbiertas < rentabilidad.MercadoRentabilidadPERCENT_CORTO_ABIERTO_GANANCIAS.Value then maxAbiertas := rentabilidad.MercadoRentabilidadPERCENT_CORTO_ABIERTO_GANANCIAS.Value; if maxAbiertas < rentabilidad.MercadoRentabilidadPERCENT_CORTO_ABIERTO_PERDIDAS.Value then maxAbiertas := rentabilidad.MercadoRentabilidadPERCENT_CORTO_ABIERTO_PERDIDAS.Value; if maxAbiertas < rentabilidad.MercadoRentabilidadPERCENT_LARGO_ABIERTO_GANANCIAS.Value then maxAbiertas := rentabilidad.MercadoRentabilidadPERCENT_LARGO_ABIERTO_GANANCIAS.Value; if maxAbiertas < rentabilidad.MercadoRentabilidadPERCENT_LARGO_ABIERTO_PERDIDAS.Value then maxAbiertas := rentabilidad.MercadoRentabilidadPERCENT_LARGO_ABIERTO_PERDIDAS.Value; maxCerradas := 0; if maxCerradas < rentabilidad.MercadoRentabilidadPERCENT_CORTO_CERRADO_GANANCIAS.Value then maxCerradas := rentabilidad.MercadoRentabilidadPERCENT_CORTO_CERRADO_GANANCIAS.Value; if maxCerradas < rentabilidad.MercadoRentabilidadPERCENT_CORTO_CERRADO_PERDIDAS.Value then maxCerradas := rentabilidad.MercadoRentabilidadPERCENT_CORTO_CERRADO_PERDIDAS.Value; if maxCerradas < rentabilidad.MercadoRentabilidadPERCENT_LARGO_CERRADO_GANANCIAS.Value then maxCerradas := rentabilidad.MercadoRentabilidadPERCENT_LARGO_CERRADO_GANANCIAS.Value; if maxCerradas < rentabilidad.MercadoRentabilidadPERCENT_LARGO_CERRADO_PERDIDAS.Value then maxCerradas := rentabilidad.MercadoRentabilidadPERCENT_LARGO_CERRADO_PERDIDAS.Value; ConfigControls(maxAbiertas, maxCerradas); end; end; {procedure TfRentabilidadMercado.Close; procedure config(const g: TGauge; const l: TLabel); begin g.Progress := 0; l.Caption := '-'; end; begin rentabilidad.Close; config(gAbiertoGananciaLargos, lAbiertoGananciaLargos); config(gAbiertoGananciaLargos, lAbiertoGananciaLargos); config(gAbiertoPerdidasLargos, lAbiertoPerdidasLargos); config(gAbiertoGananciasCortos, lAbiertoGananciasCortos); config(gAbiertoPerdidasCortos, lAbiertoPerdidasCortos); config(gCerradoGananciasLargos, lCerradoGananciasLargos); config(gCerradoPerdidasLargos, lCerradoPerdidasLargos); config(gCerradoGananciasCortos, lCerradoGananciasCortos); config(gCerradoPerdidasCortos, lCerradoPerdidasCortos); end;} procedure TfRentabilidadMercado.ConfigControls(const maxAbiertas, maxCerradas: currency); procedure config(const g: TGauge; const l: TLabel; const field: TIBBCDField; const max: currency); begin if field.IsNull then begin l.Caption := '-'; g.Progress := 0; end else begin if max = 0 then g.Progress := 0 else g.Progress := Round((field.Value * 100) / max); l.Caption := field.DisplayText; end; end; begin config(gAbiertoGananciaLargos, lAbiertoGananciaLargos, rentabilidad.MercadoRentabilidadPERCENT_LARGO_ABIERTO_GANANCIAS, maxAbiertas); config(gAbiertoPerdidasLargos, lAbiertoPerdidasLargos, rentabilidad.MercadoRentabilidadPERCENT_LARGO_ABIERTO_PERDIDAS, maxAbiertas); config(gAbiertoGananciasCortos, lAbiertoGananciasCortos, rentabilidad.MercadoRentabilidadPERCENT_CORTO_ABIERTO_GANANCIAS, maxAbiertas); config(gAbiertoPerdidasCortos, lAbiertoPerdidasCortos, rentabilidad.MercadoRentabilidadPERCENT_CORTO_ABIERTO_PERDIDAS, maxAbiertas); config(gCerradoGananciasLargos, lCerradoGananciasLargos, rentabilidad.MercadoRentabilidadPERCENT_LARGO_CERRADO_GANANCIAS, maxCerradas); config(gCerradoPerdidasLargos, lCerradoPerdidasLargos, rentabilidad.MercadoRentabilidadPERCENT_LARGO_CERRADO_PERDIDAS, maxCerradas); config(gCerradoGananciasCortos, lCerradoGananciasCortos, rentabilidad.MercadoRentabilidadPERCENT_CORTO_CERRADO_GANANCIAS, maxCerradas); config(gCerradoPerdidasCortos, lCerradoPerdidasCortos, rentabilidad.MercadoRentabilidadPERCENT_CORTO_CERRADO_PERDIDAS, maxCerradas); end; constructor TfRentabilidadMercado.Create(AOwner: TComponent); begin inherited; rentabilidad := TRentabilidadMercado.Create(Self); lastOIDMercado := -1; lastOIDSesion := -1; end; procedure TfRentabilidadMercado.Load(const OIDSesion, OIDMercado: integer; const maxAbiertas, maxCerradas: currency); begin if (lastOIDMercado <> OIDMercado) or (lastOIDSesion <> OIDSesion) then begin lastOIDMercado := OIDMercado; lastOIDSesion := OIDSesion; rentabilidad.Load(OIDSesion, OIDMercado); ConfigControls(maxAbiertas, maxCerradas); end; end; procedure TfRentabilidadMercado.Reset; begin lastOIDMercado := -1; lastOIDSesion := -1; end; end.
unit AbstractDataReader; interface uses DB, DataReader, SysUtils, Classes; type TAbstractDataReader = class abstract (TInterfacedObject, IDataReader) public procedure Restart; virtual; abstract; function Next: Boolean; virtual; abstract; function GetRecordCount: Integer; virtual; abstract; function GetValue(const FieldName: String): Variant; virtual; abstract; function GetValueAsString(const FieldName: String): String; virtual; abstract; function GetValueAsInteger(const FieldName: String): Integer; virtual; abstract; function GetValueAsFloat(const FieldName: String): Double; virtual; abstract; function GetValueAsDateTime(const FieldName: String): TDateTime; virtual; abstract; function GetValueAsBoolean(const FieldName: String): Boolean; virtual; abstract; property Items[const FieldName: String]: Variant read GetValue; default; function ToDataSet: TDataSet; virtual; abstract; function GetSelf: TObject; end; implementation { TAbstractDataReader } function TAbstractDataReader.GetSelf: TObject; begin Result := Self; end; end.
unit Model.Fabrication; interface uses System.SysUtils, Forms, RTTI, System.Generics.Collections, View.TemplateForm, Model.ProSu.Interfaces; type TFactoryMethod<TBaseType> = reference to function: TBaseType; TFactory<TKey, TBaseType> = class private fFactoryMethods: TDictionary<TKey, TFactoryMethod<TBaseType>>; function GetCount: Integer; public constructor Create; property Count: Integer read GetCount; procedure RegisterFactoryMethod(key: TKey; factoryMethod: TFactoryMethod<TBaseType>); procedure UnregisterFactoryMethod(key: TKey); function IsRegistered(key: TKey): boolean; function GetInstance(key: TKey): TBaseType; end; TFormCreationFunc = TFactoryMethod<TTemplateForm>; TMyFactory = class FormFactory: TFactory<string, TTemplateForm>; constructor Create; procedure RegisterForm<T>(const TypeName : string; aFunc : TFactoryMethod<TTemplateForm>); function GetForm(const TypeName : string) : TTemplateForm; end; var MyFactory : TMyFactory; implementation { TMyFactory } constructor TMyFactory.Create; begin inherited; FormFactory:= TFactory<string, TTemplateForm>.Create; end; function TMyFactory.GetForm(const TypeName: string): TTemplateForm; begin Result := FormFactory.GetInstance(TypeName); end; procedure TMyFactory.RegisterForm<T>(const TypeName: string; aFunc : TFactoryMethod<TTemplateForm>); begin FormFactory.RegisterFactoryMethod(TypeName, aFunc); end; /////////////// constructor TFactory<TKey, TBaseType>.Create; begin inherited Create; fFactoryMethods := TDictionary<TKey, TFactoryMethod<TBaseType>>.Create; end; function TFactory<TKey, TBaseType>.GetCount: Integer; begin Result := fFactoryMethods.Count; end; function TFactory<TKey, TBaseType>.GetInstance(key: TKey): TBaseType; var factoryMethod: TFactoryMethod<TBaseType>; begin if not fFactoryMethods.TryGetValue(key, factoryMethod) or not Assigned(factoryMethod) then raise Exception.Create('Factory not registered'); Result := factoryMethod; end; function TFactory<TKey, TBaseType>.IsRegistered(key: TKey): boolean; begin Result := fFactoryMethods.ContainsKey(key); end; procedure TFactory<TKey, TBaseType>.RegisterFactoryMethod(key: TKey; factoryMethod: TFactoryMethod<TBaseType>); begin if IsRegistered(key) then raise Exception.Create('Factory already registered'); fFactoryMethods.Add(key, factoryMethod); end; procedure TFactory<TKey, TBaseType>.UnRegisterFactoryMethod(key: TKey); begin if not IsRegistered(key) then raise Exception.Create('Factory not registered'); fFactoryMethods.Remove(key); end; //////////////// initialization MyFactory := TMyFactory.Create; end.
unit ContainsRepositoryCriterionOperationUnit; interface uses AbstractContainsRepositoryCriterionOperationUnit; type TContainsRepositoryCriterionOperation = class (TAbstractContainsRepositoryCriterionOperation) protected function GetValue: String; override; function GetAnyTextPlaceholder: String; override; public constructor Create; overload; end; TContainsRepositoryCriterionOperationClass = class of TContainsRepositoryCriterionOperation; implementation { TContainsRepositoryCriterionOperation } constructor TContainsRepositoryCriterionOperation.Create; begin inherited; end; function TContainsRepositoryCriterionOperation.GetAnyTextPlaceholder: String; begin Result := '*'; end; function TContainsRepositoryCriterionOperation.GetValue: String; begin Result := '='; end; end.
unit uUtilsDatabase; interface uses StrUtils, SysUtils, ADODB, DBGrids, Classes, uRotinas_Nitgen, uDataModule; {Funções de banco de dados} function Busca_Valor(pTabela,pCampoRetorno,pCampoFiltrar,pValor:string): Variant; function Busca_Valor_Fixo(pComando:string):string; function Busca_Valores(pComando:string): TStringList; function CarregarDigitaisLeitor(pNitgen:TNitgen;pFuncionario:integer;pConsistir:boolean):Boolean; function CurrValue(pSequencia:string):integer; function ExecutarSQL(pComando:string;p_ExibirErro:Boolean=true):boolean; function InstanciarQuery:TADOQuery; function Like(pTexto:string):string; function Obter_Usuario_Ativo:string; implementation uses uUtils, Variants; function InstanciarQuery:TADOQuery; begin result := nil; try result := TADOQuery.Create(Nil); result.Close; result.SQL.Clear; result.Connection := uDataModule.Banco_dm.Conexao_banco_aco; result := result; except on E:Exception do Erro(Nm_Unit,'InstanciarQuery',E.Message,True,true,E); end; end; function Busca_Valor_Fixo(pComando:string):string; var Temp_q: TADOQuery; i:integer; vCampoFiltrar,vValor:string; begin try Result := ''; Temp_q := InstanciarQuery; try begin Temp_q.SQL.Clear; Temp_q.SQL.Add(pComando); Temp_q.Open; Temp_q.First; if not Temp_q.IsEmpty then result := Temp_q.FieldByName(Temp_q.FieldDefList[0].Name).AsString; end; finally Temp_q.Free; end; Except on E:Exception do Erro(Nm_Unit,'Busca_Valor_Fixo',E.Message,True,true,E); end; end; function Obter_Usuario_Ativo; var qy_Temp:TADOQuery; begin Try qy_Temp := InstanciarQuery; Try qy_Temp.SQL.Add('SELECT CURRENT_USER AS user'); qy_Temp.Open; result := qy_Temp.FieldByName('user').AsString; Finally qy_Temp.Free; End; Except on E:Exception do Erro(Nm_Unit,'Obter_Usuario_Ativo',E.Message,True,true,E); End; end; function Like(pTexto:string):string; begin result := LowerCase(AnsiReplaceStr(QuotedStr('%'+pTexto+'%'),' ','%')); end; function Busca_Valor(pTabela,pCampoRetorno,pCampoFiltrar,pValor:string): Variant; var Temp_q: TADOQuery; i:integer; vCampoFiltrar,vValor:string; begin try Result := null; Temp_q := InstanciarQuery; try if pValor <> '' then begin Temp_q.SQL.Clear; Temp_q.SQL.Add('select '+pCampoRetorno+' from '+pTabela); Temp_q.SQL.Add('where 1=1'); if pos(';',pCampoFiltrar) = 0 then Temp_q.SQL.Add('and '+pCampoFiltrar+' = '+pValor) else for i := 0 to StrToInt(Opcao(pCampoFiltrar,';',0,'C'))-1 do begin vCampoFiltrar := Opcao(pCampoFiltrar,';',i+1,'T'); vValor := Opcao(pValor,';',i+1,'T'); if vCampoFiltrar <> '' then Temp_q.SQL.Add('and '+vCampoFiltrar+' = '+vValor); end; Temp_q.Open; Temp_q.First; if not Temp_q.IsEmpty then result := Temp_q.FieldByName(Temp_q.FieldDefList[0].Name).AsVariant; end; finally Temp_q.Free; end; Except on E:Exception do Erro(Nm_Unit,'Busca_Valor',E.Message,True,true,E); end; end; function Busca_Valores(pComando:string): TStringList; var Temp_q: TADOQuery; begin Result := TStringList.Create; Temp_q := InstanciarQuery; try try Temp_q.SQL.Clear; Temp_q.SQL.Add(pComando); Temp_q.Open; Temp_q.First; while not Temp_q.Eof do begin result.Add (Temp_q.FieldByName(Temp_q.FieldDefList[0].Name).AsString); Temp_q.Next; end; finally Temp_q.Free; end; Except on E:Exception do Erro(Nm_Unit,'Busca_Valores',E.Message,True,true,E); end; end; function ExecutarSQL(pComando:string;p_ExibirErro:Boolean=true):boolean; var Temp_q: TADOQuery; begin Result := false; try Temp_q := InstanciarQuery; try Temp_q.SQL.Clear; Temp_q.SQL.Add(pComando); Temp_q.ExecSQL; result := Temp_q.RowsAffected > 0; finally Temp_q.Free; end; Except on E:Exception do Erro(Nm_Unit,'ExecutarSQL',E.Message,p_ExibirErro,True,E); end; end; function CarregarDigitaisLeitor(pNitgen:TNitgen;pFuncionario:integer;pConsistir:boolean):Boolean; var qyTemp:TADOQuery; vMsgErro:string; begin {Esta procedure Insere na memoria do leitor todas as digitais cadastradas} try qyTemp := InstanciarQuery; try Result := True; {Limpa a memoria do leitor} pNitgen.objNSearch.ClearDB; qyTemp.SQL.Clear; qyTemp.SQL.Add('select a.nr_seq_funcionario,'); qyTemp.SQL.Add(' a.cd_biometria'); qyTemp.SQL.Add('from funcionario_biometria a,'); qyTemp.SQL.Add(' funcionario b'); qyTemp.SQL.Add('where a.nr_seq_funcionario = b.nr_sequencia'); qyTemp.SQL.Add('and b.ie_inativo <> ''S'''); if pFuncionario <> 0 then qyTemp.SQL.Add('and a.nr_seq_funcionario = '+IntToStr(pFuncionario)); qyTemp.Open; if qyTemp.RecordCount = 0 then begin Result := false; Erro(Nm_Unit,'CarregarDigitaisLeitor','Não existe nenhuma digital cadastrada',pConsistir,false,Nil); Exit; end; qyTemp.First; while not qyTemp.Eof do begin {Carrega na memoria do leitor as digitais} pNitgen.Popular_FIR_Leitor(qyTemp.FieldByName('NR_SEQ_FUNCIONARIO').AsInteger, qyTemp.FieldByName('CD_BIOMETRIA').AsWideString,vMsgErro); if vMsgErro <> '' then Erro(Nm_Unit,'CarregarDigitaisLeitor',vMsgErro,pConsistir,true,Nil); qyTemp.Next; end; finally qyTemp.Free; end; except on E:Exception do begin Erro(Nm_Unit,'CarregarDigitaisLeitor',E.Message,false,true,E); Result := false; end; end; end; function CurrValue(pSequencia:string):integer; var Qy_Temp:TADOQuery; begin result := 0; try Qy_Temp := InstanciarQuery; try Qy_Temp.SQL.Clear; Qy_Temp.SQL.Add('SELECT currval('+QuotedStr(pSequencia)+')'); Qy_Temp.Open; result := Qy_Temp.FieldByName('currval').AsInteger; finally Qy_Temp.Free; end; Except on E:Exception do Erro(Nm_Unit,'CurrValue',E.Message,True,True,E); end; end; end.
unit GlobalDefs; interface uses System.SyncObjs, Log, ServerSocket, System.SysUtils; var MainCS: TCriticalSection; Logger: TLog; Server: TServer; const TCP_RELAYIP = $0100007F; TCP_RELAYPORT = 9700; UDP_RELAYIP = $0100007F; UDP_RELAYPORT = 9600; type TCLPID = ( CLPID_PLAYER_LOGIN = $0002, CLPID_KEEPALIVE = $0000, CLPID_CHAT = $0006, CLPID_WHISPER = $0008, CLPID_CHANGEGAMESETTINGS = $001C, CLPID_CHANGEROOMSETTINGS = $0117, CLPID_REQUESTAFKSTATUS = $0341, CLPID_AFK = $0343, CLPID_REQUESTPLAYERSINGAME = $0345, CLPID_REQUESTPLAYSIGN = $0027, CLPID_REQUESTPLAYSIGN2 = $039F, CLPID_LOADINFO = $034A, CLPID_REQUESTGAMEINFO = $0024, CLPID_CHANGEUSERSETTINGS = $0028, CLPID_EXITROOMREQUEST = $0021, CLPID_ENABLESWEAPON = $03B6, CLPID_FEEDPET = $00D1, CLPID_CHANGEPETNAME = $00D3, CLPID_HATCH = $010B, CLPID_PETREGISTER = $00CD, CLPID_PREEVOLVE = $00E9, CLPID_ENTER_AGIT = $0446, CLPID_AGIT_MAP_CATALOGUE = $0452, CLPID_AGIT_TUTORIAL = $04A4, CLPID_AGIT_TUTORIAL_DONE = $04A2, CLPID_FAIRY_TREE = $04A0, CLPID_AGIT_STORE_CATALOG = $045A, CLPID_AGIT_STORE_MATERIAL = $045C, CLPID_AGIT_LOADING_COMPLETE = $044A, CLPID_ROOMUSER_PRESS_STATE = $033B, CLPID_SERVERLIST = $009A, CLPID_CHANNELLIST = $000E, CLPID_NOTHING = $FFFF, CLPID_562 = $0232 ); TSVPID = ( SVPID_IV_SET = $0001, SVPID_INVENTORY = $00E0, SVPID_SENDVP = $0180, SVPID_CHAT = $0007, SVPID_WHISPER = $0009, SVPID_GAMEUPDATE = $001D, SVPID_ROOMUPDATE = $0119, SVPID_AFKSTATUS = $0342, SVPID_AFK = $0344, SVPID_PLAYERSINGAME = $0346, SVPID_LOADSYNC = $034A, SVPID_SWEAPONSTATUS = $05A4, SVPID_GAMEINFORMATION = $0026, SVPID_PLAYSIGN = $0349, SVPID_ENABLESWEAPON = $03B7, SVPID_PLAYSIGN2 = $03A0, SVPID_EXITROOM = $0022, SVPID_USERUPDATE = $0029, SVPID_CHANGELEADER = $0080, SVPID_EXITSIGN = $0081, SVPID_FEEDPET = $00D2, SVPID_CHANGEPETNAME = $00D4, SVPID_HATCH = $010C, SVPID_PETREGISTER = $00CE, SVPID_PREEVOLVE = $00EA, SVPID_PETEVOLVE = $00EC, SVPID_ENTER_AGIT = $0448, SVPID_AGIT_MAP_CATALOGUE = $0453, SVPID_AGIT_TUTORIAL = $04A5, SVPID_AGIT_TUTORIAL_DONE = $04A3, SVPID_FAIRY_TREE = $04A1, SVPID_AGIT_STORE_CATALOG = $045B, SVPID_AGIT_STORE_MATERIAL = $045D, SVPID_AGIT_LOADING_COMPLETE = $044B, SVPID_ROOMUSER_PRESS_STATE = $033C, SVPID_UNKNOWN_0611 = $0611, SVPID_UNKNOWN_0414 = $0414, SVPID_SERVERLIST = $009B, SVPID_CHANNELLIST = $000F, SVPID_NOTHING = $FFFF ); implementation end.
unit SDK.Service.CodigoAuxiliar; interface uses SDK.Types, SDK.Model.CodigoAuxiliar, SDK.Service, SDK.XML, XMLIntf, SysUtils, Math, Variants; type TCodigoAuxiliarService = class(TBatchService) public constructor Create(const AClient: IClient); reintroduce; overload; function Get(const AId: TString): ICodigoAuxiliar; function GetAll(const AProdutoId: Variant; AStart: Integer = 0; ACount: Integer = 0; const ASortParams: TStringArray = nil): TCodigoAuxiliarListRec; function Filter(const AProdutoId: Variant; const AQuery: TString; AStart: Integer = 0; ACount: Integer = 0; const ASortParams: TStringArray = nil): TCodigoAuxiliarListRec; function Insert(const AIdProduto: Variant; ARequest: IBatchRequest): IBatchResponse; function Update(const AIdProduto, AId: TString; const AModel: IModel): TServiceCommandResult; function Delete(const AIdProduto, AId: Variant): Boolean; reintroduce; end; implementation { TCodigoAuxiliarService } constructor TCodigoAuxiliarService.Create(const AClient: IClient); begin inherited Create('/api/v1/produto/produtos/%s/codigos-auxiliares', AClient); end; function TCodigoAuxiliarService.Get(const AId: TString): ICodigoAuxiliar; var Response: IResponse; Nodes: TCustomXMLNodeArray; Document: IXMLDocument; begin Result := nil; Response := FClient.Get(Concat(FPath, '/', AId), nil, nil); Document := Response.AsXML; Nodes := TXMLHelper.XPathSelect(Document, '//CodigoAuxiliar'); if Length(Nodes) > 0 then TXMLHelper.Deserialize(Nodes[0], TCodigoAuxiliar, FDeserializers).QueryInterface(ICodigoAuxiliar, Result); end; function TCodigoAuxiliarService.GetAll(const AProdutoId: Variant; AStart, ACount: Integer; const ASortParams: TStringArray): TCodigoAuxiliarListRec; begin Result := Filter(AProdutoId, EmptyStr, AStart, ACount, ASortParams); end; function TCodigoAuxiliarService.Insert(const AIdProduto: Variant; ARequest: IBatchRequest): IBatchResponse; begin Result := inherited Insert(ARequest, PathWithDependencies([VarToStr(AIdProduto)])); end; function TCodigoAuxiliarService.Delete(const AIdProduto, AId: Variant): Boolean; begin Result := inherited DeleteWithPath(VarToStr(AId), PathWithDependencies([VarToStr(AIdProduto)])); end; function TCodigoAuxiliarService.Update(const AIdProduto, AId: TString; const AModel: IModel): TServiceCommandResult; begin Result := inherited Update(AId, AModel, PathWithDependencies([AIdProduto])); end; function TCodigoAuxiliarService.Filter(const AProdutoId: Variant; const AQuery: TString; AStart: Integer; ACount: Integer; const ASortParams: TStringArray): TCodigoAuxiliarListRec; var Response: IResponse; Nodes: TCustomXMLNodeArray; NodeIdx: Integer; Document: IXMLDocument; CodigoAuxiliarList, PaginationList: TCodigoAuxiliarList; CodigoAuxiliar: ICodigoAuxiliar; URL: TString; ResultNodes: TCustomXMLNodeArray; Start, Count, Total, TotalPack, Position: Integer; begin Start := AStart; Count := ACount; URL := Concat(PathWithDependencies([VarToStr(AProdutoId)]), '?', ToParams(AQuery, Start, Count, ASortParams)); Response := FClient.Get(URL, nil, nil); Document := Response.AsXML; Nodes := TXMLHelper.XPathSelect(Document, '//ResultList/items/*'); CodigoAuxiliarList := TCodigoAuxiliarList.Create; for NodeIdx := 0 to Length(Nodes) - 1 do begin TXMLHelper.Deserialize(Nodes[NodeIdx], TCodigoAuxiliar, FDeserializers).QueryInterface(ICodigoAuxiliar, CodigoAuxiliar); CodigoAuxiliarList.Add(CodigoAuxiliar); end; ResultNodes := TXMLHelper.XPathSelect(Document, '//ResultList'); if Length(ResultNodes) > 0 then begin Start := ResultNodes[0].ChildValues['start']; Count := ResultNodes[0].ChildValues['count']; Total := ResultNodes[0].ChildValues['total']; if ACount = 0 then TotalPack := Total + Start else TotalPack := Min(Total, ACount) + Start; Position := Count + Start; if Position < TotalPack then begin PaginationList := Filter(AProdutoId, AQuery, Start, TotalPack - Position, ASortParams); for CodigoAuxiliar in PaginationList do CodigoAuxiliarList.Add(CodigoAuxiliar); end; end; Result := TCodigoAuxiliarListRec.Create(CodigoAuxiliarList); end; end.
/// Conference Domain dependencies interface definition unit DomConferenceDepend; interface uses SysUtils, Classes, SynCommons, mORMot, DomConferenceTypes; type TBookingRepositoryError = ( brSuccess, brDuplicatedInfo, brWriteFailure); IBookingRepository = interface(IInvokable) ['{8E121C97-7E53-4208-BE05-1660EAD8AB43}'] function SaveNewRegistration(const Attendee: TAttendee; out RegistrationNumber: TAttendeeRegistrationNumber): TBookingRepositoryError; end; implementation initialization TJSONSerializer.RegisterObjArrayForJSON([ ]); TInterfaceFactory.RegisterInterfaces([ TypeInfo(IBookingRepository) ]); end.
unit fAppNotificationReceiver; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.ListBox, FMX.Edit, FMX.Controls.Presentation, FMX.StdCtrls, FMX.ListView.Types, FMX.ListView.Appearances, FMX.ListView.Adapters.Base, FMX.ListView, FMX.DialogService, System.Threading, System.Messaging, System.PushNotification, System.JSON, Datasnap.DSClientRest {$IFDEF ANDROID} , Lib.Android.Account, Lib.AndroidUtils, lPush, lPushData, Lib.DeviceInfo, Lib.Ver, FMX.Layouts, FMX.ScrollBox, FMX.Memo, FMX.TabControl, System.Actions, FMX.ActnList {$ENDIF} ,aConsts, aIni, ccPush, System.Notification; type TForm1 = class(TForm) StyleBook1: TStyleBook; PushManagerApp: TPushManager; DSRestConnection1: TDSRestConnection; ActionList1: TActionList; acSend: TAction; tabs: TTabControl; tabPush: TTabItem; TabItem2: TTabItem; Label2: TLabel; edtNome: TEdit; Label3: TLabel; lstPush: TListView; lblDeviceToken: TLabel; lblLog: TLabel; mmLog: TMemo; Label1: TLabel; Layout1: TLayout; spSend: TSpeedButton; cbAccounts: TComboBox; Label4: TLabel; lstDevices: TListView; SpeedButton1: TSpeedButton; acGetDevices: TAction; Label5: TLabel; cbControlAccounts: TComboBox; Panel1: TPanel; aiWait: TAniIndicator; edtServer: TEdit; NotificationCenterMain: TNotificationCenter; procedure PushManagerAppMessage(Sender: TObject; const ANotification: TPushServiceNotification); procedure PushManagerAppPushChange(Sender: TObject; AChange: TPushService.TChanges); procedure FormCreate(Sender: TObject); procedure FormActivate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure acSendExecute(Sender: TObject); procedure acGetDevicesExecute(Sender: TObject); private procedure LoadIni; procedure SaveIni; procedure SetupServer; procedure FillAccounts; function GetAccount: string; function GetControlAccount: string; procedure AddItem(const Title, Msg: string); procedure ShowNotification(const ATitle, AMsg: string); procedure BuildDeviceList(DeviceList: TJSONArray); function DoSendRegistration(const DeviceToken, Account, UserName: string): TJSONValue; public procedure SendRegistration(const DeviceToken, Account, UserName: string); end; var Form1: TForm1; implementation {$R *.fmx} procedure TForm1.acGetDevicesExecute(Sender: TObject); var DeviceResult: TJSONObject; Errorvalue: TJSONValue; DeviceList: TJSONArray; begin acGetDevices.Enabled:= false; aiWait.Visible:= true; aiWait.Enabled:= true; try if GetControlAccount = EmptyStr then TDialogService.MessageDialog('Por favor, selecione uma conta.', TMsgDlgType.mtWarning, [TMsgDlgBtn.mbOK], TMsgDlgBtn.mbOK, 0, nil) else with TPushMethodsClient.Create(DSRestConnection1, true) do try DeviceResult:= UserDevices(GetControlAccount); if assigned(DeviceResult) and DeviceResult.TryGetValue('success', DeviceList) then BuildDeviceList(DeviceList) else if DeviceResult.TryGetValue('error', Errorvalue) then TDialogService.MessageDialog(ErrorValue.Value, TMsgDlgType.mtError, [TMsgDlgBtn.mbOK], TMsgDlgBtn.mbOK, 0, nil) finally Free; end; finally acGetDevices.Enabled:= True; aiWait.Enabled:= false; aiWait.Visible:= false; end; end; procedure TForm1.acSendExecute(Sender: TObject); begin acSend.Enabled:= false; aiWait.Visible:= true; aiWait.Enabled:= true; try SaveIni; if (not lblDeviceToken.Text.Trim.IsEmpty) and (not GetAccount.Trim.IsEmpty) and (not edtNome.Text.Trim.IsEmpty) then SendRegistration(lblDeviceToken.Text, GetAccount, edtNome.Text); finally acSend.Enabled:= true; aiWait.Enabled:= false; aiWait.Visible:= false; end; end; procedure TForm1.AddItem(const Title, Msg: string); var AItem: TListViewItem; begin AItem:= lstPush.Items.Add; AItem.Text:= Title; AItem.Detail:= Msg; end; procedure TForm1.ShowNotification(const ATitle, AMsg: string); var MyNotification: TNotification; begin MyNotification:= NotificationCenterMain.CreateNotification; try MyNotification.Name:= 'DistAlarm' + AMsg; MyNotification.AlertBody := AMsg; NotificationCenterMain.PresentNotification(MyNotification); finally MyNotification.Free; end; end; procedure TForm1.LoadIni; begin edtNome.Text:= Ini.Nome; cbAccounts.ItemIndex:= cbAccounts.Items.IndexOf(Ini.Conta); end; procedure TForm1.SaveIni; begin Ini.Nome:= edtNome.Text; if cbAccounts.ItemIndex > -1 then Ini.Conta:= cbAccounts.Items[cbAccounts.ItemIndex] else Ini.Conta:= EmptyStr; end; procedure TForm1.SetupServer; var i: integer; S, P: string; begin S:= EmptyStr; P:= EmptyStr; i:= Pos(edtServer.Text, ':'); if i > 0 then begin S:= Copy(edtServer.Text, 1, i - 1); P:= Copy(edtServer.Text, i + 1, Length(edtServer.Text)); end else S:= edtServer.Text; DSRestConnection1.Host:= S; if P <> EmptyStr then DSRestConnection1.Port:= StrToInt(P); end; procedure TForm1.FillAccounts; begin cbAccounts.Items.Clear; FillAccountEmails('com.google', cbAccounts.Items); cbControlAccounts.Items.Assign(cbAccounts.Items); end; function TForm1.GetAccount: string; begin if cbAccounts.ItemIndex > -1 then result:= cbAccounts.Items[cbAccounts.ItemIndex] else result:= EmptyStr; end; function TForm1.GetControlAccount: string; begin if cbControlAccounts.ItemIndex > -1 then result:= cbControlAccounts.Items[cbControlAccounts.ItemIndex] else result:= EmptyStr; end; procedure TForm1.BuildDeviceList(DeviceList: TJSONArray); var AItem: TListViewItem; AValue: TJSONValue; user_id, device_id, device_model, os_name, os_ver: TJSONValue; begin lstDevices.Items.Clear; for AValue in DeviceList do begin AValue.TryGetValue('USER_ID', user_id); AValue.TryGetValue('DEVICE_ID', device_id); AValue.TryGetValue('DEVICE_MODEL', device_model); AValue.TryGetValue('OS_NAME', os_name); AValue.TryGetValue('OS_VER', os_ver); AItem:= lstDevices.Items.Add; AItem.Text:= device_id.Value; AItem.Detail:= format('%s - %s - %s', [device_model.Value, os_name.Value, os_ver.Value]); end; end; function TForm1.DoSendRegistration(const DeviceToken, Account, UserName: string): TJSONValue; var deviceInfo: TPushDevice; begin result:= nil; try deviceInfo:= TPushDevice.Create(Account, UserName, TMobileDeviceInfo.DeviceID, DeviceToken, TMobileDeviceInfo.DeviceModel, TMobileDeviceInfo.OSName, TMobileDeviceInfo.OSVersion, TAppVer.GetVerName, RECEIVE_PUSH_YES); try with TPushMethodsClient.Create(DSRestConnection1, true) do try result:= UpdateDevice(deviceInfo); finally Free; end; finally deviceInfo.Free; end; except On E: Exception do begin Result:= TJSONObject.Create.AddPair('result', E.Message); end; end; end; procedure TForm1.SendRegistration(const DeviceToken, Account, UserName: string); begin TTask.Run( procedure var Result: TJSONValue; Tries: integer; ResultValue: string; begin Tries:= 0; repeat try Result:= DoSendRegistration(DeviceToken, Account, UserName); except end; if assigned(Result) and Result.TryGetValue('success', ResultValue) then begin if (ResultValue = EmptyStr) then TThread.Current.Sleep(TIME_BETWEEN_TRIES) else begin TThread.Synchronize(nil, procedure begin mmLog.Lines.Add(ResultValue); end ); end; end; Inc(Tries); until (ResultValue <> '0') or (Tries = MAX_REG_TRIES); end); end; procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); begin SaveIni; end; procedure TForm1.FormCreate(Sender: TObject); begin //Connect to push registration service PushManagerApp.Active:= true; FillAccounts; LoadIni; end; procedure TForm1.FormActivate(Sender: TObject); begin //Process offline messages PushManagerApp.CheckStartupMessage; end; procedure TForm1.PushManagerAppMessage(Sender: TObject; const ANotification: TPushServiceNotification); var Value, ATitle, AMsg: string; begin ATitle:= EmptyStr; AMsg:= EmptyStr; if ANotification.Json.TryGetValue('title', Value) then ATitle:= Value; if ANotification.Json.TryGetValue('message', Value) then AMsg:= Value; if (not ATitle.IsEmpty) then AddItem(ATitle, AMsg); if not PushManagerApp.IsStartupMessage then ShowNotification(ATitle, AMsg); end; procedure TForm1.PushManagerAppPushChange(Sender: TObject; AChange: TPushService.TChanges); begin if TPushService.TChange.DeviceToken in AChange then begin lblDeviceToken.Text:= PushManagerApp.DeviceToken; //SendRegistration(PushManagerApp.DeviceToken, GetAccount, edtNome.Text); end; end; end.
namespace RemObjects.Elements.Profiler; interface uses RemObjects.Elements.RTL; type Profiler = public static class private var fLock: {$IFDEF ISLAND}Monitor{$ELSE}Object{$ENDIF} := new {$IFDEF ISLAND}Monitor{$ELSE}Object{$ENDIF}; var fThreads: Dictionary<String, ThreadInfo> := new Dictionary<String,ThreadInfo>; constructor; method GetDefaultFileName: String; protected const SubCallCount: Integer = 9; public method WriteData; method Reset; // sets all counters to 0 method Enter(aName: String); method &Exit(aName: String); property LogFileBaseName: String; end; ThreadInfo = class private public property Items: List<FrameInfo> := new List<FrameInfo>; property Bias: Int64; property Methods: Dictionary<String, MethodInfo> := new Dictionary<String,MethodInfo>; end; SITuple = class(Object{$IFDEF ECHOES}, IEquatable<SITuple>{$ELSEIF TOFFEE}Foundation.INSCopying{$ENDIF}) public constructor (aKey: String; aInt: Integer); property Key: String read private write; property Int: Integer read private write; {$IFDEF ISLAND OR ECHOES} method &Equals(obj: Object): Boolean; override; begin exit Equals(SITuple(obj)); end; method &Equals(other: SITuple): Boolean; begin exit (other.Key = Key) and (other.Int = Int); end; method GetHashCode: Integer; override; begin exit Key.GetHashCode xor Int; end; {$ELSEIF COOPER} method &equals(other: SITuple): Boolean; begin exit (other.Key = Key) and (other.Int = Int); end; method hashCode: Integer; override; begin exit Key.hashCode xor Int; end; {$ELSEIF TOFFEE} method isEqual(obj: Object): Boolean; override; begin exit isEqual(SITuple(obj)); end; method isEqual(other: SITuple): Boolean; begin exit (other.Key = Key) and (other.Int = Int); end; method hash: Foundation.NSUInteger; override; begin exit Key.hash xor Int; end; method copyWithZone(aZone: ^Foundation.NSZone): not nullable id; begin result := new SITuple(); result.Key := Key; result.Int := Int; end; {$ENDIF} end; MethodInfo = class public property PK: Integer; property Count: Int64; property Name: String; property TotalTicks: Int64; property SelfTicks: Int64; property MinTotalTicks: Int64 := $7FFFFFFFFFFFFFFF; property MinSelfTicks: Int64 := $7FFFFFFFFFFFFFFF; property MaxTotalTicks: Int64; property MaxSelfTicks: Int64; property SubCalls: Dictionary<SITuple, SubCall> := new Dictionary<SITuple,SubCall>; end; SubCall= class public property &Method: MethodInfo; property Count: Int64; property TotalTicks: Int64; property SelfTicks: Int64; property MinTotalTicks: Int64 := $7FFFFFFFFFFFFFFF; property MinSelfTicks: Int64 := $7FFFFFFFFFFFFFFF; property MaxTotalTicks: Int64; property MaxSelfTicks: Int64; end; FrameInfo = class public private public property Prev: FrameInfo; property &Method: String; property StartTime: Int64; property SubtractFromTotal: Int64; property SubCallTime: Int64; end; implementation {$IFDEF TOFFEE OR ISLAND} method __elements_write_data; begin Profiler.WriteData; end; {$ENDIF} method GetTimestamp: Int64; begin {$IFDEF ECHOES} exit System.Diagnostics.Stopwatch.GetTimestamp; {$else} exit DateTime.UtcNow.Ticks; {$ENDIF} end; constructor Profiler; begin {$IFDEF ECHOES} AppDomain.CurrentDomain.ProcessExit += (o, e) -> begin try finally WriteData; end; end; System.Diagnostics.Stopwatch.GetTimestamp; // preload that {$ELSEIF COOPER} Runtime.Runtime.addShutdownHook(new Thread(-> WriteData)); {$ELSEIF WINDOWS and ISLAND} ExternalCalls.atexit(-> WriteData); {$ELSEIF TOFFEE or ISLAND} rtl.atexit(@__elements_write_data); {$else} {$ERROR Invalid Target!} {$ENDIF} end; method Profiler.Enter(aName: String); begin var lStart := GetTimestamp; var lTID := {$IFDEF ISLAND}RemObjects.Elements.System.Thread.CurrentThreadID{$ELSE}Thread.CurrentThread.ThreadId{$ENDIF}; var lTI: ThreadInfo; locking fLock do begin lTI := fThreads[Integer(lTID).ToString]; if lTI = nil then begin lTI := new ThreadInfo; fThreads.Add(Integer(lTID).ToString, lTI); end; end; var lMI: MethodInfo := lTI.Methods[aName]; if lMI = nil then begin lMI := new MethodInfo; lMI.Name := aName; lTI.Methods.Add(aName, lMI); end; lTI.Items.Add(new FrameInfo(&method := aName, StartTime := lStart - lTI.Bias, Prev := if lTI.Items.Count = 0 then nil else lTI.Items[lTI.Items.Count-1])); lTI.Bias := lTI.Bias + GetTimestamp - lStart; end; method Profiler.&Exit(aName: String); begin var lStart := GetTimestamp; var lTID := {$IFDEF ISLAND}RemObjects.Elements.System.Thread.CurrentThreadID{$ELSE}Thread.CurrentThread.ThreadId{$ENDIF}; var lTI: ThreadInfo; locking fLock do begin lTI := fThreads[Integer(lTID).ToString]; if lTI = nil then begin lTI := new ThreadInfo; fThreads.Add(Integer(lTID).ToString, lTI); end; end; var lLastE := lTI.Items[lTI.Items.Count -1]; lTI.Items.RemoveAt(lTI.Items.Count-1); assert(lLastE.Method = aName); var lTime := lStart - lTI.Bias - lLastE.StartTime; if lTI.Items.Count > 0 then lTI.Items[lTI.Items.Count -1].SubCallTime := lTI.Items[lTI.Items.Count -1].SubCallTime + lTime; var lMI := lTI.Methods[aName]; lMI.Count := lMI.Count + 1; var lSelfTime := lTime - lLastE.SubCallTime; lMI.TotalTicks := lMI.TotalTicks + lTime - lLastE.SubtractFromTotal; var lWorkLastE := lLastE.Prev; while lWorkLastE <> nil do begin if lWorkLastE.Method = aName then begin lWorkLastE.SubtractFromTotal := lWorkLastE.SubtractFromTotal + lTime - lLastE.SubtractFromTotal; end; lWorkLastE := lWorkLastE.Prev; end; lMI.MinTotalTicks := Math.Min(lMI.MinTotalTicks, lTime); lMI.MaxTotalTicks := Math.Max(lMI.MaxTotalTicks, lTime); lMI.SelfTicks := lMI.SelfTicks + lSelfTime; lMI.MinSelfTicks := Math.Min(lMI.MinSelfTicks, lSelfTime); lMI.MaxSelfTicks := Math.Max(lMI.MaxSelfTicks, lSelfTime); lLastE := lLastE.Prev; for i: Integer := 1 to SubCallCount do begin if lLastE = nil then break; var tp := new SITuple(aName, i); var lCA := lTI.Methods[lLastE.Method]; var sc: SubCall := lCA.SubCalls[tp]; if sc = nil then begin sc := new SubCall; lCA.SubCalls.Add(tp, sc); sc.Method :=lMI; end; sc.Count := sc.Count + 1; sc.SelfTicks := sc.SelfTicks + lSelfTime; sc.TotalTicks := sc.TotalTicks + lTime - lLastE.SubtractFromTotal; sc.MinTotalTicks := Math.Min(sc.MinTotalTicks, lTime); sc.MaxTotalTicks := Math.Max(sc.MaxTotalTicks, lTime); sc.MinSelfTicks := Math.Min(sc.MinSelfTicks, lSelfTime); sc.MaxSelfTicks := Math.Max(sc.MaxSelfTicks, lSelfTime); lLastE := lLastE.Prev; end; lTI.Bias := lTI.Bias + GetTimestamp - lStart; end; method Profiler.GetDefaultFileName: String; begin const ELEMENTS_PROFILER_LOG_FILE = "ELEMENTS_PROFILER_LOG_FILE"; result := Environment.EnvironmentVariable[ELEMENTS_PROFILER_LOG_FILE]; if defined("TOFFEE") and not assigned(result) then result := (Foundation.NSProcessInfo.processInfo.arguments.Where(s -> (s as String).StartsWith("--"+ELEMENTS_PROFILER_LOG_FILE+"=")).FirstOrDefault as String):Substring(3+length(ELEMENTS_PROFILER_LOG_FILE)); if defined("ECHOES") and not assigned(result) then result := Path.ChangeExtension(&System.Reflection.Assembly.GetEntryAssembly():Location, ".profiler.log"); end; method Profiler.WriteData; begin var lFilename := coalesce(LogFileBaseName, GetDefaultFileName, "app.profile"); var lWriter := new StringBuilder; begin lWriter.AppendLine(''); lWriter.AppendLine('create table methods (id integer primary key, thread integer, count integer, name text, totalticks integer, selfticks integer, mintotal integer, maxtotal integer, minself integer, maxself integer);'); lWriter.AppendLine('create table subcalls (fromid integer, toid integer, level integer, count integer, totalticks integer, selfticks integer, mintotal integer, maxtotal integer, minself integer, maxself integer);'); var nc := 0; fThreads.ForEach(el -> begin el.Value.Methods.ForEach(m -> begin inc(nc); m.Value.PK := nc; end); end); fThreads.ForEach(el -> begin var lThread := el.Key; el.Value.Methods.ForEach(m -> begin lWriter.AppendFormat('insert into methods values ({0}, {1}, {2}, ''{3}'', {4}, {5}, {6},{7},{8},{9});{10}', m.Value.PK, lThread, m.Value.Count, m.Value.Name, m.Value.TotalTicks, m.Value.SelfTicks, m.Value.MinTotalTicks, m.Value.MaxTotalTicks, m.Value.MinSelfTicks, m.Value.MaxSelfTicks, Environment.LineBreak); m.Value.SubCalls.ForEach(n -> begin lWriter.AppendFormat('insert into subcalls values ({0}, {1}, {2}, {3}, {4}, {5}, {6},{7},{8},{9});{10}', m.Value.PK, n.Value.Method.PK, n.Key.Int, n.Value.Count, n.Value.TotalTicks, n.Value.SelfTicks, n.Value.MinTotalTicks, n.Value.MaxTotalTicks, n.Value.MinSelfTicks, n.Value.MaxSelfTicks, Environment.LineBreak); end); end); end); end; File.WriteText(lFilename, lWriter.ToString, Encoding.UTF8); writeLn("Elements Profiler results have been saved to '"+lFilename+"'."); end; method Profiler.Reset; begin fThreads.RemoveAll; end; constructor SITuple(aKey: String; aInt: Integer); begin Key := aKey; Int := aInt; end; end.
unit uRecipeIPv4Address; interface uses Classes, RegularExpressions, uDemo, uRecipe; type TRecipeIPv4Address = class(TRecipe) public class function Description: String; override; function Pattern: String; override; procedure GetInputs(const Inputs: TStrings); override; end; implementation { TRecipeIPv4Address } class function TRecipeIPv4Address.Description: String; begin Result := 'Recipes\IPv4 Address'; end; {$REGION} /// <B>Source</B>: http://www.regexlib.com/REDetails.aspx?regexp_id=194 /// <B>Author</B>: Andrew Polshaw /// /// This matches an IP address, putting each number in its own group that can be /// retrieved by number. If you do not care about capturing the numbers, then /// you can make this shorter by putting everything after \b until immediately /// after the first \. in a group ( ) with a {3} after it. Then put the number /// matching regex in once more. It only permits numbers in the range 0-255. /// /// <B>Notes</B>: /// -Replaced "beginning of string (^)" and "end of string ($)" with /// "word boundaries (\b)" /// -Added support for leading zeros function TRecipeIPv4Address.Pattern: String; begin Result := '\b'+ '(\d{1,2}|0\d|0\d\d|1\d\d|2[0-4]\d|25[0-5])\.' + '(\d{1,2}|0\d|0\d\d|1\d\d|2[0-4]\d|25[0-5])\.' + '(\d{1,2}|0\d|0\d\d|1\d\d|2[0-4]\d|25[0-5])\.' + '(\d{1,2}|0\d|0\d\d|1\d\d|2[0-4]\d|25[0-5])\b'; end; procedure TRecipeIPv4Address.GetInputs(const Inputs: TStrings); begin Inputs.Add('0.0.0.0'); Inputs.Add('255.255.255.02'); Inputs.Add('192.168.0.136'); Inputs.Add('023.44.33.22'); Inputs.Add('256.1.3.4'); Inputs.Add('Lorem ipsum 0.0.0.0 dolor sit amet, consectetur adipisicing'); Inputs.Add('255.255.255.02 elit, sed do 192.168.0.136 eiusmod tempor'); Inputs.Add('incididunt 256.1.3.4 ut labore et dolore magna aliqua.'); end; {$ENDREGION} initialization RegisterDemo(TRecipeIPv4Address); end.
unit fmFramePatterns; interface uses KrUtil, uniKrUtil, krVar, KrDB, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, // uniGUITypes, uniGUIAbstractClasses, uniGUIClasses, uniGUIFrame, uniLabel, uniGUIBaseClasses, uniPanel, uniGUIForm, uniDBEdit, uniEdit, uniDBLookupComboBox, uniDBDateTimePicker, UniDateTimePicker; type TfrmFramePatterns = class(TUniFrame) procedure UniFrameCreate(Sender: TObject); procedure UniFrameDestroy(Sender: TObject); private { Private declarations } fCallBackConfirm:Boolean; function GetDataNula: String; procedure AddEditLookpCombobox; procedure CallBackConfirm(Sender: TComponent; AResult: Integer); // procedure OnColumnSort(Column: TUniDBGridColumn; Direction: Boolean); procedure SortedBy; public { Public declarations } Const MaskFone :String = '(99)9999-9999'; // Fone MaskCelular :String = '(99)9 9999-9999'; // Celular com 9 digitos MaskDate :String = '99/99/9999'; // Data MaskTime :String = '99:99'; // Hora MaskCPF :String = '999.999.999-99'; // CPF MaskPlaca :String = 'aaa-9999'; // Placa de Autovóvel MaskIP :String = '9999.9999.9999.9999'; // IP de computador MaskCNPJ :String = '99.999.999/9999-99'; // CNPJ MaskVIPROC :String = '9999999/9999'; // VIPROC MaskIPol :String = '999-9999/9999'; // Inquérito Policial ResultCPF:String='___.___.___-__' ; // function DelCharEspeciais(Str:String):string; function Idade(DataNasc:String):string; Overload; function Idade(DataNasc:String; dtAtual:TDate):string; Overload; procedure OpenURL(URL:String); procedure OpenURLWindow(URL:String); procedure AddMask(Edit: TUniDBEdit; Mask: String); Overload; // Adiciona mascara procedure AddMask(Edit: TUniEdit; Mask: String); Overload; // Adiciona mascara procedure AddMask(Edit: TUniDBDateTimePicker; Mask:String); Overload; // Adiciona mascara procedure AddMask(Edit: TUniDateTimePicker; Mask:String); Overload; // Adiciona mascara procedure AddMaskDate; function Confirm(msg: String): Boolean; function Soundex(S: String): String; procedure Warning(msg: String); procedure DisplayError(Msg:string); // Mensagem de dialog de erro Procedure AddFeriados(Data:String); function Criptografar(wStri: String): String; function GeraSenha(n: integer): String; function GerarNomeArquivo:String; // // Validação Function IsEMail(Value: String):Boolean; function isKeyValid(Value:Char):Boolean; function IsCnpj(const aCode:string):boolean; //Retorna verdadeiro se aCode for um CNPJ válido function IsCpf(const aCode:string):boolean; //Retorna verdadeiro se aCode for um CPF válido function IsCpfCnpj(const aCode:string):boolean;//Retorna verdadeiro se aCode for um CPF ou CNPJ válido function IsDate(fDate:String):Boolean; // verifica se uma determinada data é válida ou não function IsPlaca(Value:String):Boolean; // Faz a validação de uma placa de automóvel function IsTitulo(numero: String): Boolean; // Validação de titulo de eleitor function IsIP(IP: string): Boolean; // Verifica se o IP inofmado é válido function IsIE(UF, IE: string): boolean; function BoolToStr2(Bool:Boolean):String; overload;// Converte o valor de uma variável booleana em String function BoolToStr2(Bool:Integer):String; overload; function IsTituloEleitor(NumTitulo: string): Boolean; // Valida Título de Eleitor function IsNum(Value:String):Boolean; // Date e Time function Dias_Uteis(DT_Ini, DT_Fin:TDateTime):Integer; { Public declarations } Function GetWhere(Value:TStrings):String; function StrToBool1(Str:string):boolean; // property DataNula :String read GetDataNula; end; implementation {$R *.dfm} procedure TfrmFramePatterns.CallBackConfirm(Sender: TComponent; AResult: Integer); begin fCallBackConfirm := AResult = mrYes; end; procedure TfrmFramePatterns.OpenURLWindow(URL:String); Begin uniKrUtil.OpenURLWindow(URL); End; procedure TfrmFramePatterns.OpenURL(URL:String); Begin uniKrUtil.OpenURL(URL); End; function TfrmFramePatterns.DelCharEspeciais(Str: String): string; begin Result := KrUtil.DelCharEspeciais(Str); end; function TfrmFramePatterns.Dias_Uteis(DT_Ini, DT_Fin: TDateTime): Integer; begin Result := KrUtil.Dias_Uteis(DT_Ini, DT_Fin); end; procedure TfrmFramePatterns.DisplayError(Msg: string); begin uniKrUtil.DisplayError(Msg); end; function TfrmFramePatterns.GerarNomeArquivo: String; begin Result:=krUtil.GerarNomeArquivo; end; function TfrmFramePatterns.GeraSenha(n: integer): String; begin Result:=krUtil.GeraSenha(n); end; function TfrmFramePatterns.GetDataNula: String; begin Result:=krVar.DataNula; end; function TfrmFramePatterns.GetWhere(Value: TStrings): String; begin Result:=KrUtil.GetWhere(Value); end; function TfrmFramePatterns.Soundex(S: String): String; begin Result:=KrUtil.Soundex(S); end; function TfrmFramePatterns.StrToBool1(Str: string): boolean; begin Result:=KrUtil.StrToBool1(Str); end; procedure TfrmFramePatterns.UniFrameCreate(Sender: TObject); begin KrUtil.Create; SortedBy; ArrayForms.Add(self.Name); AjustarFetchRow(self); end; procedure TfrmFramePatterns.UniFrameDestroy(Sender: TObject); begin ArrayForms.Delete(ArrayForms.Add(self.Name)); end; {procedure TfrmFrameCadastro.OnColumnSort(Column: TUniDBGridColumn; Direction: Boolean); begin // Uses uniDBGrid, ZAbstractDataset, ZAbstractRODataset inherited; // Ordena as informações pelo campo da coluna que foi clicada if TZAbstractDataSet(Column.Field.DataSet).Active then Begin if Column.FieldName <> TZAbstractDataSet(Column.Field.DataSet).SortedFields then Begin TZAbstractDataSet(Column.Field.DataSet).SortedFields := Column.FieldName; TZAbstractDataSet(Column.Field.DataSet).SortType := stAscending; End else Begin case TZAbstractDataSet(Column.Field.DataSet).SortType of stAscending : TZAbstractDataSet(Column.Field.DataSet).SortType := stDescending; stDescending: TZAbstractDataSet(Column.Field.DataSet).SortType := stAscending; end; End; End; end;} procedure TfrmFramePatterns.SortedBy; Var I, J :Integer; begin inherited; (* For I:=0 To Self.ComponentCount - 1 do Begin if (LowerCase(self.Components[I].ClassName) = 'tunidbgrid') and (TUniDBGrid(self.Components[I]).Tag = 0) then Begin TUniDBGrid(self.Components[I]).OnColumnSort := OnColumnSort; TUniDBGrid(self.Components[I]).Tag := 1; // { if TUniDBGrid(self.Components[I]).DataSource.DataSet.Active then For J:= 0 to TUniDBGrid(self.Components[I]).Columns.Count - 1 do if not TUniDBGrid(self.Components[I]).Columns[J].Sortable then TUniDBGrid(self.Components[I]).Columns[J].Sortable := True;} End; end; *) end; (*procedure TfrmFrameCadastro.UniFormKeyPress(Sender: TObject; var Key: Char); begin if Key = #27 then Close; end; *) (*procedure TfrmFrameCadastro.UniFormShow(Sender: TObject); begin AddMaskDate; AddEditLookpCombobox; end; *) function TfrmFramePatterns.BoolToStr2(Bool:Boolean):String; Begin Result:=KrUtil.BoolToStr2(Bool); End; function TfrmFramePatterns.Idade(DataNasc: String): string; begin Result:=KrUtil.Idade(DataNasc); end; function TfrmFramePatterns.Idade(DataNasc: String; dtAtual: TDate): string; begin Result:=KrUtil.Idade(DataNasc, dtAtual); end; function TfrmFramePatterns.IsCnpj(const aCode: string): boolean; begin Result:=KrUtil.IsCnpj(aCode); end; function TfrmFramePatterns.IsCpf(const aCode: string): boolean; begin Result:=KrUtil.IsCpf(aCode); end; function TfrmFramePatterns.IsCpfCnpj(const aCode: string): boolean; begin Result:=KrUtil.IsCpfCnpj(aCode); end; function TfrmFramePatterns.IsDate(fDate: String): Boolean; begin Result:=KrUtil.IsDate(fDate); end; function TfrmFramePatterns.IsEMail(Value: String):Boolean; begin Result:=KrUtil.IsEMail(Value); end; function TfrmFramePatterns.IsIE(UF, IE: string): boolean; begin Result:=KrUtil.IsIE(UF, IE); end; function TfrmFramePatterns.IsIP(IP: string): Boolean; begin Result:=KrUtil.IsIP(IP); end; function TfrmFramePatterns.isKeyValid(Value: Char): Boolean; begin Result:=KrUtil.isKeyValid(Value); end; function TfrmFramePatterns.IsNum(Value: String): Boolean; begin Result:=KrUtil.IsNum(Value); end; function TfrmFramePatterns.IsPlaca(Value: String): Boolean; begin Result:=KrUtil.IsPlaca(Value); end; function TfrmFramePatterns.IsTitulo(numero: String): Boolean; begin Result:=KrUtil.IsTitulo(numero); end; function TfrmFramePatterns.IsTituloEleitor(NumTitulo: string): Boolean; begin Result := KrUtil.IsTituloEleitor(NumTitulo); end; procedure TfrmFramePatterns.AddMaskDate; Var I:Integer; begin // Adiciona mascara do componente informado For I:=0 to ComponentCount - 1 do if lowercase(Components[I].ClassName) = 'tunidbdatetimepicker' then AddMask(TUniDBDateTimePicker(Components[I]), MaskDate); end; procedure TfrmFramePatterns.AddMask(Edit: TUniDBDateTimePicker; Mask:String); begin // Uses uniDBDateTimePicker Edit.ClientEvents.ExtEvents.Add ('Onfocus=function function focus(sender, the, eOpts)'+ ' { $("#"+sender.id+"-inputEl").mask("'+Mask+'"); }'); end; procedure TfrmFramePatterns.AddMask(Edit: TUniDateTimePicker; Mask:String); begin // Uses uniDBDateTimePicker Edit.ClientEvents.ExtEvents.Add ('Onfocus=function function focus(sender, the, eOpts)'+ ' { $("#"+sender.id+"-inputEl").mask("'+Mask+'"); }'); end; procedure TfrmFramePatterns.AddMask(Edit: TUniDBEdit; Mask:String); begin Edit.ClientEvents.ExtEvents.Add ('Onfocus=function function focus(sender, the, eOpts)'+ ' { $("#"+sender.id+"-inputEl").mask("'+Mask+'"); }'); end; procedure TfrmFramePatterns.AddMask(Edit: TUniEdit; Mask:String); begin Edit.ClientEvents.ExtEvents.Add ('Onfocus=function function focus(sender, the, eOpts)'+ ' { $("#"+sender.id+"-inputEl").mask("'+Mask+'"); }'); end; procedure TfrmFramePatterns.AddEditLookpCombobox; Var I:Integer; begin // Uses uniDBLookupComboBox For I:=0 to ComponentCount - 1 do if lowercase(Components[I].ClassName) = 'tunidblookupcombobox' then TUniDBLookupComboBox(Components[I]).ClientEvents.ExtEvents.Add ('OnAfterrender=function afterrender(sender, eOpts)'+ ' { sender.allowBlank=true; sender.editable = true;}'); // sender.allowBlank=true; sender.editable = true; end; function TfrmFramePatterns.Confirm(msg:String):Boolean; Begin MessageDlg(Msg, mtConfirmation, mbYesNo,CallBackConfirm); Result := fCallBackConfirm; End; procedure TfrmFramePatterns.Warning(msg:String); Begin uniKrUtil.Warning(msg); End; procedure TfrmFramePatterns.AddFeriados(Data: String); begin KrUtil.AddFeriados(Data); end; function TfrmFramePatterns.BoolToStr2(Bool: Integer): String; begin Result:=KrUtil.BoolToStr2(Bool); end; function TfrmFramePatterns.Criptografar(wStri: String): String; begin Result := krUtil.Criptografar(wStri); end; end.
{$ifdef license} (* Copyright 2020 ChapmanWorld LLC ( https://chapmanworld.com ) Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *) {$endif} /// <summary> /// Provides the standard implementation, conditionally selecting the /// appropriate implementation for the target platform. /// </summary> unit cwDynLib.Standard; {$ifdef fpc} {$mode delphiunicode} {$endif} interface uses cwDynLib , cwStatus ; type TDynlib = class( TInterfacedObject, IDynlib ) private fLibrary: string; fHandle: nativeuint; protected //- IDynlib -// function LoadLibrary( const filepath: string ): TStatus; function FreeLibrary: boolean; function GetProcAddress( const funcName: string; out ptrProc: pointer ): TStatus; public constructor Create; reintroduce; destructor Destroy; override; end; implementation uses sysutils {$ifndef MSWINDOWS} {$ifndef fpc} , posix.errno {$endif} {$endif} ; {$ifdef MSWINDOWS} function winLoadLibrary( lpLibFileName: pointer ): nativeuint; stdcall; external 'kernel32' name 'LoadLibraryA'; function winFreeLibrary( hLibModule: nativeuint ): boolean; stdcall; external 'kernel32' name 'FreeLibrary'; function winGetProcAddress( hModule: nativeuint; lpProcName: pointer ): pointer; stdcall; external 'kernel32' name 'GetProcAddress'; function winGetLastError(): uint32; stdcall; external 'kernel32' name 'GetLastError'; {$else} {$ifdef MACOS} //- MACOS const clibname = 'libdl.dylib'; // MacOS x86 symbol exports have preceeding underscore. function dlopen( filename: pointer; flags: int32 ): pointer; cdecl; external clibname name '_dlopen'; function dlsym( handle: pointer; symbolname: pointer ): pointer; cdecl; external clibname name '_dlsym'; function dlclose( handle: pointer ): int32; cdecl; external clibname name '_dlclose'; {$else} //- Posix const clibname = 'libdl.so'; function dlopen( filename: pointer; flags: int32 ): pointer; cdecl; external clibname name 'dlopen'; function dlsym( handle: pointer; symbolname: pointer ): pointer; cdecl; external clibname name 'dlsym'; function dlclose( handle: pointer ): int32; cdecl; external clibname name 'dlclose'; {$endif} const cSuccess = 0; cRTLD_LAZY = 1; {$endif} constructor TDynlib.Create; begin inherited Create; fHandle := 0; end; destructor TDynlib.Destroy; begin if fHandle<>0 then begin FreeLibrary; end; inherited Destroy; end; function TDynlib.FreeLibrary: boolean; begin Result := False; if fHandle=0 then begin exit; end; {$ifdef MSWINDOWS} if not winFreeLibrary(fHandle) then begin fHandle := 0; exit; end; {$else} {$hints off} if not (dlClose(pointer(fHandle)) = cSuccess) then begin {$hints on} fHandle := 0; exit; end; {$endif} fHandle := 0; Result := True; end; function TDynlib.GetProcAddress(const funcName: string; out ptrProc: pointer): TStatus; begin Result := TStatus.Unknown; {$ifdef MSWINDOWS} ptrProc := winGetProcAddress(fHandle,pAnsiChar(UTF8Encode(funcName))); {$else} {$hints off} ptrProc := dlSym( pointer(fHandle), pointer(UTF8Encode(funcname)) ); {$hints on} {$endif} if not assigned(ptrProc) then begin Result := stFailedToLoadEntryPoint; exit; end; Result := TStatus.Success; end; function TDynlib.LoadLibrary(const filepath: string): TStatus; begin Result := TStatus.Unknown; {$ifdef MSWINDOWS} fHandle := winLoadLibrary(pAnsiChar(UTF8Encode(filepath))); {$else} {$hints off} fHandle := NativeUInt( dlOpen(pointer(UTF8Encode(filepath)),cRTLD_LAZY) ); {$hints on} {$endif} if fHandle=0 then begin Result := stModuleNotLoaded; exit; end; fLibrary := filepath; Result := TStatus.Success; end; end.
unit Entidade.Pedido; interface uses SimpleAttributes; Type TPEDIDO = class private FID: Integer; FNOME: String; FDATA: TDatetime; FVALOR: Currency; procedure SetID(const Value: Integer); procedure SetNOME(const Value: String); procedure SetDATA(const Value: TDatetime); procedure SetVALOR(const Value: Currency); public constructor Create; destructor Destroy; override; published [PK, AutoInc] property ID : Integer read FID write SetID; property NOME : String read FNOME write SetNOME; property DATA : TDatetime read FDATA write SetDATA; property VALOR : Currency read FVALOR write SetVALOR; end; implementation { TMinhaClasse } constructor TPEDIDO.Create; begin end; destructor TPEDIDO.Destroy; begin inherited; end; procedure TPEDIDO.SetDATA(const Value: TDatetime); begin FDATA := Value; end; procedure TPEDIDO.SetID(const Value: Integer); begin FID := Value; end; procedure TPEDIDO.SetNOME(const Value: String); begin FNOME := Value; end; procedure TPEDIDO.SetVALOR(const Value: Currency); begin FVALOR := Value; end; end.
unit Duplicata; interface type TDuplicata = class private FNumeroDuplicata :String; FDataVencimento :TDateTime; FValorDuplicata :Real; private function GetDataVencimento :TDateTime; function GetNumeroDuplicata :String; function GetValorDuplicata :Real; public constructor Create(NumeroDuplicata :String; DataVencimento :TDateTime; ValorDuplicata :Real); public property NumeroDuplicata :String read GetNumeroDuplicata; property DataVencimento :TDateTime read GetDataVencimento; property ValorDuplicata :Real read GetValorDuplicata; end; implementation uses StringUtilitario, ExcecaoParametroInvalido, SysUtils; { TDuplicata } constructor TDuplicata.Create(NumeroDuplicata: String; DataVencimento: TDateTime; ValorDuplicata: Real); const NOME_METODO = 'Create(NumeroDuplicata: String; DataVencimento: TDateTime; ValorDuplicata: Real)'; begin if TStringUtilitario.EstaVazia(NumeroDuplicata) then raise TExcecaoParametroInvalido.Create(self.ClassName, NOME_METODO, 'NumeroDuplicata'); if (DataVencimento <= 0) then raise TExcecaoParametroInvalido.Create(self.ClassName, NOME_METODO, 'DataVencimento'); if (ValorDuplicata <= 0) then raise TExcecaoParametroInvalido.Create(self.ClassName, NOME_METODO, 'ValorDuplicata'); self.FNumeroDuplicata := NumeroDuplicata; self.FDataVencimento := DataVencimento; self.FValorDuplicata := ValorDuplicata; end; function TDuplicata.GetDataVencimento: TDateTime; begin result := self.FDataVencimento; end; function TDuplicata.GetNumeroDuplicata: String; begin result := UpperCase(Trim(self.FNumeroDuplicata)); end; function TDuplicata.GetValorDuplicata: Real; begin result := self.FValorDuplicata; end; end.
unit OLAPTest; interface uses DB, TestFramework; type // Класс тестирует поведение класса TELOLAPSalers. TOLAPTest = class(TTestCase) protected // подготавливаем данные для тестирования procedure SetUp; override; // возвращаем данные после тестирования} procedure TearDown; override; published // Проверка создания корректного SQL выражения для построения отчета procedure CreateSQLExpression; // Проверка правильного заполнения данных отчета // procedure CheckOlapSaleReportOption; // Проверка сохранения и восстановления схем по умолчанию // procedure CheckSaveRestoreShema; // Проверка сохранения и восстановления схем по умолчанию на сервере // procedure CheckSaveRestoreShemaOnServer; end; TField = class(DB.TField) private FFieldKind: TFieldKind; end; implementation uses dsdDB, DBClient, Classes, dsdOlap, SysUtils, Storage, UtilConst, Authentication, CommonData {, Forms, cxCustomPivotGrid, cxGridDBTableView, cxGridTableView, cxGridDBBandedTableView, cxGridBandedTableView, cxCurrencyEdit, cxGridCustomTableView, cxCustomData, Controls, cxDBPivotGrid, cxDBData, Dialogs}; { TOLAPTest } (*procedure TOLAPTest.CheckOlapSaleReportOption; var OlapSaleReportOption: TELOlapSaleReportOption; LMessage: string; begin OlapSaleReportOption := TELOlapSaleReportOption.Create; Check(not TELOlapSalers.CheckReportOption(OlapSaleReportOption, LMessage), LMessage); OlapSaleReportOption.Objects['SHOP_NAME'].Visible := true; OlapSaleReportOption.Objects['SOLD_SUMM'].Visible := true; Check(TELOlapSalers.CheckReportOption(OlapSaleReportOption, LMessage), LMessage); end; procedure TOLAPTest.CheckSaveRestoreShema; var OlapSaleReportOption: TELOlapSaleReportOption; XML_Scheme: String; i: integer; VisibleCount: integer; JsonString: String; begin // Создали новый объект OlapSaleReportOption := TELOlapSaleReportOption.Create; // Установили для него видимость OlapSaleReportOption.isOLAPonServer := true; OlapSaleReportOption.isCreateDate := true; OlapSaleReportOption.SummaryType := stUniqueCount; OlapSaleReportOption.Objects['SHOP_NAME'].Visible := true; OlapSaleReportOption.Objects['SOLD_SUMM'].Visible := true; // Получили схему XML_Scheme := OlapSaleReportOption.XMLScheme; // Очистили объект OlapSaleReportOption.Free; // Создали новый OlapSaleReportOption := TELOlapSaleReportOption.Create; // 2. Это SHOP_NAME и SOLD_SUMM Check(not OlapSaleReportOption.Objects['SHOP_NAME'].Visible); Check(not OlapSaleReportOption.Objects['SOLD_SUMM'].Visible); // Наложили на него схему OlapSaleReportOption.XmlScheme := XML_Scheme; // Проверили // 1. Видимых только два VisibleCount := 0; for i := 0 to OlapSaleReportOption.FieldCount - 1 do if OlapSaleReportOption.Objects[i].Visible then Inc(VisibleCount); Check(VisibleCount = 2, 'Видимых полей ' + IntToStr(VisibleCount) + ' вместо 2'); // 2. Это SHOP_NAME и SOLD_SUMM Check(OlapSaleReportOption.Objects['SHOP_NAME'].Visible); Check(OlapSaleReportOption.Objects['SOLD_SUMM'].Visible); Check(OlapSaleReportOption.isOLAPonServer, 'OlapSaleReportOption.isOLAPonServer'); Check(OlapSaleReportOption.isCreateDate, 'OlapSaleReportOption.isCreateDate'); Check(OlapSaleReportOption.SummaryType = stUniqueCount, 'OlapSaleReportOption.SummaryType'); end; procedure TOLAPTest.CheckSaveRestoreShemaOnServer; var OlapSaleReportOption: TELOlapSaleReportOption; XML_Scheme: String; List: TStringList; i: integer; VisibleCount: integer; begin List := TStringList.Create; // Создали новый объект OlapSaleReportOption := TELOlapSaleReportOption.Create; // Установили для него видимость OlapSaleReportOption.Objects['SHOP_NAME'].Visible := true; OlapSaleReportOption.Objects['SOLD_SUMM'].Visible := true; // Получили схему XML_Scheme := OlapSaleReportOption.XMLScheme; // Очистили объект OlapSaleReportOption.Free; List.Values['Первая схема'] := XML_Scheme; // Создали новый объект OlapSaleReportOption := TELOlapSaleReportOption.Create; // Установили для него видимость OlapSaleReportOption.Objects['SOLD_SUMM'].Visible := true; // Получили схему XML_Scheme := OlapSaleReportOption.XMLScheme; // Очистили объект OlapSaleReportOption.Free; List.Values['Вторая схема'] := XML_Scheme; TELListCube.SaveShema(List.Text, 'ELOLAPSalesTest'); List.Free; List := TStringList.Create; List.Text := TELListCube.LoadShema('ELOLAPSalesTest'); // Создали новый объект OlapSaleReportOption := TELOlapSaleReportOption.Create; // Наложили на него схему OlapSaleReportOption.XmlScheme := List.Values['Первая схема']; // Проверили // 1. Видимых только два VisibleCount := 0; for i := 0 to OlapSaleReportOption.FieldCount - 1 do if OlapSaleReportOption.Objects[i].Visible then Inc(VisibleCount); Check(VisibleCount = 2, 'Видимых полей ' + IntToStr(VisibleCount) + ' вместо 2'); // 2. Это SHOP_NAME и SOLD_SUMM Check(OlapSaleReportOption.Objects['SHOP_NAME'].Visible); Check(OlapSaleReportOption.Objects['SOLD_SUMM'].Visible); end; *) procedure TOLAPTest.CreateSQLExpression; var // LClmn: TcxGridDBBandedColumn; // LBand: TcxGridBand; OlapSaleReportOption: TOlapReportOption; i, j: integer; // LBands: TStringList; // SummaryGroup : TcxDataSummaryGroup; List: TStringList; FIndex: integer; FieldDefs: TFieldDefs; DataFields: TStringList; StoredProc: TdsdStoredProc; DataSet: TClientDataSet; DataList: TStringList; begin DataSet := TClientDataSet.Create(nil); StoredProc := TdsdStoredProc.Create(nil); StoredProc.OutputType := otDataSet; StoredProc.DataSet := DataSet; StoredProc.StoredProcName := 'gpGet_OlapSoldReportOption'; StoredProc.Execute; //StoredProc.StoredProcName := 'gp_Select_Dynamic_cur'; //StoredProc. DataList := TStringList.Create; FieldDefs := TFieldDefs.Create(nil); List:=TStringList.Create; OlapSaleReportOption := TOlapReportOption.Create(DataSet); OlapSaleReportOption.SummaryType := dsdOlap.stAverage; OlapSaleReportOption.Objects['sale_summ'].Visible := true; // OlapSaleReportOption.Objects['EXCHANGE_SUMM'].Visible := true; //OlapSaleReportOption.Objects['WEIGHT'].Visible := true; //OlapSaleReportOption.Objects['EXCHANGE_PERCENT'].Visible := true; OlapSaleReportOption.Objects['JuridicalName'].Visible := true; OlapSaleReportOption.Objects['GoodsName'].Visible := true; with OlapSaleReportOption.Objects['YEAR_DATE_DOC'] do begin Visible := true; end; { with OlapSaleReportOption.Objects['MONTH_YEAR_DATE_DOC'] do begin Visible := true; end; with OlapSaleReportOption.Objects['DAYOFWEEK_DATE_DOC'] do begin Visible := true; end; with OlapSaleReportOption.Objects['MONTH_DATE_DOC'] do begin Visible := true; end; } { with OlapSaleReportOption.Objects['DATE_DOC'] do begin Visible := true; end;} (* with OlapSaleReportOption.Objects['POSITION_NAME'] do begin // Visible := true; end; with OlapSaleReportOption.Objects['DEPARTMENT_NAME'] do begin Visible := true; end; with OlapSaleReportOption.Objects['PRODUCER_NAME'] do begin Visible := true; end; with OlapSaleReportOption.Objects['BRANCH_NAME'] do begin // Visible := true; end; with OlapSaleReportOption.Objects['GOOD_NAME'] as TDimensionOLAPField do begin // FilterList.Add('126789012'); Visible := true; end; with OlapSaleReportOption.Objects['GOOD_CAT_NAME'] do begin // Visible := true; end; with OlapSaleReportOption.Objects['GOOD_TYPE_DISTRIBUTOR_NAME'] do begin // Visible := true; end; with OlapSaleReportOption.Objects['GOOD_PRODUCER_TYPE_NAME'] do begin // Visible := true; end; with OlapSaleReportOption.Objects['SHOP_NAME'] do begin // Visible := true; end; with OlapSaleReportOption.Objects['TRANSACTOR_NAME'] do begin // Visible := true; end; with OlapSaleReportOption.Objects['DOCUMENT_NUMBER'] do begin // Visible := true; end; with OlapSaleReportOption.Objects['DOC_DATE_DIM'] do begin // Visible := true; end; with OlapSaleReportOption.Objects['RTT'] do begin // Visible := true; end; with OlapSaleReportOption.Objects['CONTRACT_NAME'] do begin Visible := true; end; with OlapSaleReportOption.Objects['DELIV_TIME'] do begin Visible := true; end; with OlapSaleReportOption.Objects['DELIV_TIME_FACT'] do begin Visible := true; end; *) OlapSaleReportOption.FromDate := StrToDate('01.01.2014'); OlapSaleReportOption.ToDate := StrToDate('01.01.2015'); // OlapSaleReportOption.isOLAPonServer := true; OlapSaleReportOption.isOLAPonServer := false; Check (false, TOlap.CreateSQLExpression(OlapSaleReportOption, DataSet.FieldDefs, DataList)); exit; (* DataFields := TStringList.Create; with TForm1.Create(nil) do begin FELOlapSaleReportOption := OlapSaleReportOption; FieldDefs := TFieldDefs.Create(SQLQuery); SQLQuery.SQL.Text := TELOlapSalers.CreateSQLExpression(OlapSaleReportOption, FieldDefs, DataFields); OracleSession.Connected := true; SQLQuery.FieldDefs.Clear; SQLQuery.FieldDefs.Assign(FieldDefs); for i := 0 to SQLQuery.FieldDefs.Count - 1 do SQLQuery.FieldDefs[i].CreateField(SQLQuery); for i := 0 to OlapSaleReportOption.FieldCount - 1 do if OlapSaleReportOption.Objects[i] is TDataOLAPField then with OlapSaleReportOption.Objects[i] do if Visible then with FieldDefs.AddFieldDef do begin Name := 'ITOG_' + FieldName; DataType := ftFloat; CreateField(SQLQuery).FieldKind := fkCalculated; end; LDataFields := DataFields; SQLQuery.Open; cxGrid.BeginUpdate; tvReport.DataController.CreateAllItems; for i := 0 to tvReport.ColumnCount - 1 do tvReport.Columns[i].Visible := false; LBand := tvReport.Bands.Add; if Assigned(LBand) then begin LBand.Caption := 'Заголовок'; LBand.FixedKind := fkLeft; LBand.Options.HoldOwnColumnsOnly := true; LBand.Options.Moving := false; end; // Создаем список для хранения данных о созданных Band LBands := TStringList.Create; try // В итераторе заполняем бенды и устанавливаем им заголовки with FELOlapSaleReportOption.GetIterator do while HasNextItem do if List.IndexOf(Item) = -1 then begin List.Add(Item); with tvReport.Bands.Add do begin Caption := Item; Options.Moving := false; LBands.Values[Caption] := IntToStr(Index); end; end; with tvReport.DataController.Summary do begin SummaryGroups.Clear; SummaryGroup := SummaryGroups.Add; end; for i := 0 to FELOlapSaleReportOption.FieldCount - 1 do if FELOlapSaleReportOption.Objects[i].Visible then begin if not (FELOlapSaleReportOption.Objects[i] is TDataOLAPField) then begin LClmn := tvReport.GetColumnByFieldName(FELOlapSaleReportOption.Objects[i].FieldName); if Assigned(LClmn) then begin LClmn.Caption := FELOlapSaleReportOption.Objects[i].Caption; LClmn.Position.BandIndex := LBand.Index; LClmn.Visible := true; LClmn.Width := 200; with TcxGridTableSummaryGroupItemLink(SummaryGroup.Links.Add) do begin Column := LClmn; end; end; end else begin for j := 0 to LBands.Count - 1 do begin LClmn := tvReport.GetColumnByFieldName(LBands.Names[j] + '_' + FELOlapSaleReportOption.Objects[i].FieldName); if Assigned(LClmn) then begin LClmn.Caption := FELOlapSaleReportOption.Objects[i].Caption; LClmn.Position.BandIndex := StrToInt(LBands.Values[LBands.Names[j]]); LClmn.Width := 80; LClmn.PropertiesClass := TcxCurrencyEditProperties; TcxCurrencyEditProperties(LClmn.Properties).DisplayFormat := TDataOLAPField(FELOlapSaleReportOption.Objects[i]).DisplayFormat; LClmn.Visible := true; LClmn.Options.Moving := false; LClmn.Summary.FooterKind := skSum; //case TDataOLAPField(FELOlapSaleReportOption.Objects[i]).SummaryType of // TSummaryType(stSum), TSummaryType(stCustom): LClmn.Summary.FooterKind := skSum; //end; LClmn.Summary.FooterFormat := TcxCurrencyEditProperties(LClmn.Properties).DisplayFormat; // LClmn.Summary.GroupKind := LClmn.Summary.FooterKind; // LClmn.Summary.GroupFormat := LClmn.Summary.FooterFormat; // LClmn.Summary.GroupFooterKind := LClmn.Summary.FooterKind; // LClmn.Summary.GroupFooterFormat := LClmn.Summary.FooterFormat; //Add summary items with SummaryGroup.SummaryItems.Add as TcxGridDBTableSummaryItem do begin DisplayText := '33'; VisibleForCustomization := true; Tag := 1; DisplayName := 'dsfs'; Column := LClmn; Position := spGroup; Kind := LClmn.Summary.FooterKind; Format := LClmn.Summary.FooterFormat; end; end; end; end; end; with tvReport.Bands.Add do begin Caption := 'Итого'; FIndex := Index; end; for i := 0 to OlapSaleReportOption.FieldCount - 1 do if OlapSaleReportOption.Objects[i] is TDataOLAPField then with OlapSaleReportOption.Objects[i] do if Visible then begin LClmn := tvReport.GetColumnByFieldName('ITOG_'+FieldName); if Assigned(LClmn) then begin LClmn.PropertiesClass := TcxCurrencyEditProperties; TcxCurrencyEditProperties(LClmn.Properties).DisplayFormat := ',0.00'; LClmn.Visible := true; LClmn.Position.BandIndex := FIndex; LClmn.Caption := Caption; LClmn.Summary.FooterKind := skSum; LClmn.Summary.FooterFormat := TcxCurrencyEditProperties(LClmn.Properties).DisplayFormat; end; end; cxGrid.Align := alClient; cxGrid.Visible := true; cxGrid.EndUpdate; finally LBands.Free; cxGrid.Align := alClient; cxGrid.EndUpdate; cxGrid.Visible := true; end; cxDBPivotGrid.CreateAllFields; cxDBPivotGrid.DataController.Filter.AutoDataSetFilter := true; *) (* cxDBPivotGrid.CreateAllFields; for i := 0 to OlapSaleReportOption.Fields.Count - 1 do begin if TOLAPField(OlapSaleReportOption.Fields.Objects[i]).Visible then begin // if OlapSaleReportOption.Fields.Objects[i] is TDataOLAPField then begin // if TDataOLAPField(OlapSaleReportOption.Fields.Objects[i]).SummaryType = stUniqueCount then // cxDBPivotGrid.GetFieldByName(TOLAPField(OlapSaleReportOption.Fields.Objects[i]).FieldName).SummaryType := stCount; // end; cxDBPivotGrid.GetFieldByName(TOLAPField(OlapSaleReportOption.Fields.Objects[i]).FieldName).Caption := TOLAPField(OlapSaleReportOption.Fields.Objects[i]).Caption; end; end; *) (*ShowModal; Application.ProcessMessages; // sleep(3000); Free; end;*) end; procedure TOLAPTest.SetUp; begin inherited; TAuthentication.CheckLogin(TStorageFactory.GetStorage, 'Админ', gc_AdminPassword, gc_User); end; procedure TOLAPTest.TearDown; begin inherited; end; initialization TestFramework.RegisterTest('Reports', TOLAPTest.Suite); end.
unit UARP; {------------------------------------------------------------------------------- 通过 DOS 命令行,执行 arp -a 命令,获得 ARP 的 MAC 地址列表。然后解析出来。 pcplayer 2013-8-21 -------------------------------------------------------------------------------} interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, UDosCommand; type TARPCmd = class(TComponent) private FARPStr: string; // FARPList: TStringList; //分解后的 IP - MAC 列表 procedure GetIPMAC(const S: string; var IP, MAC: string); overload; procedure GetIPMacList; function GetMACCount: Integer; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure RefreshARP; procedure GetIPMAC(const Index: Integer; var IP, MAC: string); overload; property MacCount: Integer read GetMACCount; end; implementation { TARPCmd } constructor TARPCmd.Create(AOwner: TComponent); begin inherited; FARPList := TStringList.Create; end; destructor TARPCmd.Destroy; begin FARPList.Free; inherited; end; procedure TARPCmd.GetIPMAC(const S: string; var IP, MAC: string); var i: Integer; begin {--------------------------------------------------------------------- 将一条 224.11.11.11 01-00-5e-0b-0b-0b 静态 分解为 IP 和 MAC ---------------------------------------------------------------------} //S := TrimLeft(S); MAC := S; MAC := TrimLeft(MAC); i := POS(' ', MAC); IP := Copy(MAC, 1, i -1); Delete(MAC, 1, i); //去掉前面的 IP 部分 MAC := TrimLeft(MAC); i := POS(' ', MAC); MAC := Copy(MAC, 1, i -1); IP := Trim(IP); MAC := Trim(MAC); end; procedure TARPCmd.GetIPMAC(const Index: Integer; var IP, MAC: string); var S: string; begin S := FARPList[Index]; GetIPMAC(S, IP, MAC); end; procedure TARPCmd.GetIPMacList; var i: Integer; S: string; begin {--------------------------------------------------------------------- 去掉ARP 命令返回文本里非 IP-MAC 的部分。 ---------------------------------------------------------------------} FARPList.Text := FARPStr; for i := FARPList.Count -1 downto 0 do begin //检查如果不是 192.168.0.1 20-4e-7f-2f-50-04 动态 这种格式的,就删除掉。 S := FARPList.Strings[i]; if S = '' then begin FARPList.Delete(i); Continue; end; if S[1] <> ' ' then begin FARPList.Delete(i); //前面没空格的,删除掉。 Continue; end; if not (S[3] in ['0'..'9']) then begin FARPList.Delete(i); //前面第一位不是数字的,删除。 end; end; end; function TARPCmd.GetMACCount: Integer; begin Result := FARPList.Count; end; procedure TARPCmd.RefreshARP; begin FARPStr := GetDosOutput('arp -a'); Self.GetIPMacList; end; end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Unit2; type TForm1 = class(TForm) Label1: TLabel; sideA: TEdit; sideB: TEdit; sideC: TEdit; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; cornerA: TEdit; cornerB: TEdit; cornerC: TEdit; Label6: TLabel; Label7: TLabel; Label8: TLabel; countCorners: TButton; Label9: TLabel; square: TEdit; countSquare: TButton; Label10: TLabel; sideA1: TEdit; sideB1: TEdit; sideC1: TEdit; Label11: TLabel; Label12: TLabel; Label13: TLabel; compareTriangles: TButton; whichBigger: TEdit; Label14: TLabel; heightA: TEdit; heightB: TEdit; Label15: TLabel; Label16: TLabel; Label17: TLabel; countHeights: TButton; Label18: TLabel; bisectorA: TEdit; bisectorB: TEdit; bisectorC: TEdit; Label19: TLabel; Label20: TLabel; Label21: TLabel; countBisectors: TButton; Label22: TLabel; medA: TEdit; medB: TEdit; medC: TEdit; Label23: TLabel; Label24: TLabel; Label25: TLabel; countMed: TButton; Label26: TLabel; sideA3: TEdit; sideB3: TEdit; sideC3: TEdit; Label27: TLabel; Label28: TLabel; Label29: TLabel; multiply: TButton; number: TEdit; Label30: TLabel; cornerArad: TEdit; cornerBrad: TEdit; cornerCrad: TEdit; Label31: TLabel; Label32: TLabel; Label33: TLabel; Label34: TLabel; x1: TEdit; y1: TEdit; x2: TEdit; Label35: TLabel; Label36: TLabel; Label37: TLabel; Button1: TButton; y2: TEdit; Label38: TLabel; x3: TEdit; y3: TEdit; x4: TEdit; Label39: TLabel; Label40: TLabel; Label41: TLabel; y4: TEdit; Label42: TLabel; heightC: TEdit; Label43: TLabel; Label44: TLabel; Edit1: TEdit; Edit2: TEdit; procedure countCornersClick(Sender: TObject); procedure countSquareClick(Sender: TObject); procedure compareTrianglesClick(Sender: TObject); procedure countHeightsClick(Sender: TObject); procedure countBisectorsClick(Sender: TObject); procedure countMedClick(Sender: TObject); procedure multiplyClick(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); var a:Triangle; begin a:=Triangle.Create(strtoint(sideA.Text),strtoint(sideB.Text),strtoint(sideC.Text)); if(a.sideA<>0) and (a.sideB<>0) and (a.sideC<>0) then begin a.CountCoords(strtoint(x1.Text),strtoint(y1.Text),strtoint(x2.Text),strtoint(y2.Text)); x3.Text:=FormatFloat('0.00',a.coords[0]); y3.Text:=FormatFloat('0.00',a.coords[1]); x4.Text:=FormatFloat('0.00',a.coords[2]); y4.Text:=FormatFloat('0.00',a.coords[3]); Edit1.Text:=FormatFloat('0.00',a.coordX2); Edit2.Text:=FormatFloat('0.00',a.coordY2); end else begin showMessage('Error'); end; end; procedure TForm1.compareTrianglesClick(Sender: TObject); var a,b:Triangle; begin a:=Triangle.Create(strtoint(sideA.Text),strtoint(sideB.Text),strtoint(sideC.Text)); b:=Triangle.Create(strtoint(sideA1.Text),strtoint(sideB1.Text),strtoint(sideC1.Text)); if(a.sideA<>0) and (a.sideB<>0) and (a.sideC<>0) and (b.sideA<>0) and (b.sideB<>0) and (b.sideC<>0) then begin if a.CompareSquare(b)=1 then begin whichBigger.Text:='The first one bigger.' end else begin whichBigger.Text:='The second one bigger.' end; end else begin showMessage('Error'); end; end; procedure TForm1.countBisectorsClick(Sender: TObject); var a:Triangle; begin a:=Triangle.Create(strtoint(sideA.Text),strtoint(sideB.Text),strtoint(sideC.Text)); if(a.sideA<>0) and (a.sideB<>0) and (a.sideC<>0) then begin a.Bisector; bisectorA.Text:=FormatFloat('0.0', a.res[0]); bisectorB.Text:=FormatFloat('0.0', a.res[1]); bisectorC.Text:=FormatFloat('0.0', a.res[2]); end else begin showMessage('Error'); end; end; procedure TForm1.countCornersClick(Sender: TObject); var a:Triangle; begin a:=Triangle.Create(strtoint(sideA.Text),strtoint(sideB.Text),strtoint(sideC.Text)); if(a.sideA<>0) and (a.sideB<>0) and (a.sideC<>0) then begin a.CountCorners(); cornerA.Text:=FormatFloat('0.0', a.res[0]); cornerB.Text:=FormatFloat('0.0', a.res[1]); cornerC.Text:=FormatFloat('0.0', a.res[2]); cornerArad.Text:=FormatFloat('0.00', a.res1[0]); cornerBrad.Text:=FormatFloat('0.00', a.res1[1]); cornerCrad.Text:=FormatFloat('0.00', a.res1[2]); end else begin showMessage('Error'); end; end; procedure TForm1.countHeightsClick(Sender: TObject); var a:Triangle; begin a:=Triangle.Create(strtoint(sideA.Text),strtoint(sideB.Text),strtoint(sideC.Text)); if(a.sideA<>0) and (a.sideB<>0) and (a.sideC<>0) then begin a.Height; heightA.Text:=FormatFloat('0.0', a.res[0]); heightB.Text:=FormatFloat('0.0', a.res[1]); heightC.Text:=FormatFloat('0.0', a.res[2]); end else begin showMessage('Error'); end; end; procedure TForm1.countMedClick(Sender: TObject); var a:Triangle; begin a:=Triangle.Create(strtoint(sideA.Text),strtoint(sideB.Text),strtoint(sideC.Text)); if(a.sideA<>0) and (a.sideB<>0) and (a.sideC<>0) then begin a.Med; medA.Text:=FormatFloat('0.0', a.res[0]); medB.Text:=FormatFloat('0.0', a.res[1]); medC.Text:=FormatFloat('0.0', a.res[2]); end else begin showMessage('Error'); end end; procedure TForm1.countSquareClick(Sender: TObject); var a:Triangle; begin a:=Triangle.Create(strtoint(sideA.Text),strtoint(sideB.Text),strtoint(sideC.Text)); if(a.sideA<>0) and (a.sideB<>0) and (a.sideC<>0) then begin square.Text:=FormatFloat('0.0', a.CountSquare); end else begin showMessage('Error'); end; end; procedure TForm1.multiplyClick(Sender: TObject); var a, b:Triangle; begin b:=Triangle.Create; a:=Triangle.Create(strtoint(sideA.Text),strtoint(sideB.Text),strtoint(sideC.Text)); if(a.sideA<>0) and (a.sideB<>0) and (a.sideC<>0) then begin a.MultiplyTriangle(b, strtoint(number.Text)); sideA3.Text:=inttostr(b.sideA); sideB3.Text:=inttostr(b.sideB); sideC3.Text:=inttostr(b.sideC); end else begin showMessage('Error'); end end; end.
unit HeatCalibration; interface uses CommonCalibration ; const HEAT_POINT_MULTIPLIER = 1000 * 1000 * 1000; //множитель, используемый для масштабирования калибровочного коэффициента до единиц и обратно //чтобы не терялась точность type THeatCalibrationTable = class( TCalibrationTable ) private //TODO можно сделать локальными begTemp: integer; //температура в градусах! endTemp: integer; recalcBaseFromTunePoint: boolean; //признак того, что необходимо произвести пересчёт базовых реперных точек для подстройки под корректирующую точку public constructor Create( aBegTemp, aEndTemp: single ); procedure AddHeatRefPoint( aSampleTemp: integer; aArea: integer; aWeight: single; aSpecificHeat: single; aVirtyualPoint: boolean; aDescription: string ); overload; procedure AddHeatRefPoint( aSampleTemp: integer; aArea: integer; aWeight: single; aSpecificHeat: single; aRealValue: single; aVirtyualPoint: boolean; aDescription: string ); overload; function GetInterpolationType( ): TInterpolationType; procedure SetInterpolationType( aInterpType: TInterpolationType ); procedure LoadFromFileByRangeNo( aDiffTempRange: integer ); override; procedure Calc( ); //function GetTemperatureOffset( ): integer; function GetHeatFactor( aSampleTemp: single ): single; procedure SetTemperatureRange( aBegTemp, aEndTemp: single ); function IsUseHeatTunePoint( ): boolean; function IsUseMarginPoints( ): boolean; function GetTunePointArea( ): integer; function GetTunePointDh( ): single; function GetTunePointMass( ): single; function GetTunePointTransTemp( ): single; function GetTunePointFactor( ): single; procedure SetUseHeatTunePoint( aUseHeat: boolean ); procedure SetUseMarginPoints( aUseMargin: boolean ); procedure SetTunePointArea( aArea: integer ); procedure SetTunePointDh( aDh: single ); procedure SetTunePointMass( aMass: single ); procedure SetTunePointTransTemp( aTransTemp: single ); procedure SetRecalcBaseFromTunePoint( aRecalc: boolean ); end; implementation uses CustomCollection, Procs, MathUtils, Polynomial, Config; procedure THeatCalibrationTable.AddHeatRefPoint( aSampleTemp: integer; aArea: integer; aWeight: single; aSpecificHeat: single; aVirtyualPoint: boolean; aDescription: string ); var realValue: single; begin realValue := aSpecificHeat * aWeight / 1000 / aArea; AddHeatRefPoint( aSampleTemp, aArea, aWeight, aSpecificHeat, realValue, aVirtyualPoint, aDescription ); end; procedure THeatCalibrationTable.AddHeatRefPoint( aSampleTemp: integer; aArea: integer; aWeight: single; aSpecificHeat: single; aRealValue: single; aVirtyualPoint: boolean; aDescription: string ); var rp: TrefPoint; begin rp := TrefPoint.Create( aSampleTemp ); rp.unitValue := aSampleTemp; rp.realValue := aRealvalue; rp.area := aArea; rp.weight := aWeight; rp.specificHeat := aSpecificHeat; rp.description := aDescription; inherited AddRefPoint( aSampleTemp, rp ); end; procedure THeatCalibrationTable.Calc; var i, j, index, lastIndex: integer; temperature1, temperature2: integer; refPoint: TrefPoint; buffer: array of TXYPoint; a, b, step, currValue, factor: extended; arr, arr2: array of integer; lagrPoly: TPolynom; koeff, realKoeff: extended; begin refPoints.Sort; ZeroItems( ); if interpType = itLine then //нет интерполяции begin for i := 0 to GetRefPointsCount - 2 do begin temperature1 := GetRefPoints.GetItem( i ).unitValue; temperature2 := GetRefPoints.GetItem( i + 1 ).unitValue; for j := temperature1 to temperature2 do begin index := HLLim( 0, GetItemCount - 1, j + temperatureOffset ); items[index] := LineInterp( temperature1, GetRefPoints.GetItem( i ).realValue, temperature2, GetRefPoints.GetItem( i + 1 ).realValue, j ); end; end; end else if interpType = itMinSquare then // аппроксимация методом наименьших квадратов begin //определяем коэфф наклона кривой по методу наименьших квадратов //крайние точки (автоматически рассчитанные) тут не участвуют SetLength( buffer, GetRefPointsCount - 2 ); for i := 1 to GetRefPointsCount - 2 do begin buffer[i - 1].x := GetRefPoints.GetItem( i ).unitValue; buffer[i - 1].y := GetRefPoints.GetItem( i ).realValue; end; MinSquareLine( buffer, a, b ); for i := GetRefPoints.GetItem( 0 ).unitValue to GetRefPoints.GetItem( GetRefPointsCount - 1 ).unitValue do begin index := HLLim( 0, GetItemCount - 1, i + temperatureOffset ); items[index] := i * a + b; end; end else if interpType = itBezie then // аппроксимация Безье begin SetLength( arr, GetRefPointsCount ); SetLength( arr2, GetRefPointsCount ); for i := 0 to GetRefPointsCount - 1 do begin arr[i] := Round( GetRefPoints.GetItem( i ).realValue * HEAT_POINT_MULTIPLIER ); arr2[i] := Round( GetRefPoints.GetItem( i ).unitValue ); end; step := 1 / ( GetItemCount - 1 ); //шаг приращения во время аппроксимации currValue := 0; //текущее значение точки рассчёта аппроксимации lastIndex := 0; for i := 0 to GetItemCount - 1 do begin index := Round( HLLim( 0, GetItemCount - 1, Round( Par( arr2, currValue ) ) + temperatureOffset ) ); items[index] := Par( arr, currValue ) / HEAT_POINT_MULTIPLIER; if index - lastIndex > 1 then //откуда то могут браться пустые значения, тут они заполняются линейной интерполяцией for j := lastIndex to index do items[j] := LineInterp( lastIndex, items[lastIndex], index, items[index], j ); currValue := currValue + step; lastIndex := index; end; Setlength( arr, 0 ); Setlength( arr2, 0 ); end else if interpType = itPolynomial then begin SetLength( buffer, 0 ); if tp_useMarginPoints then begin SetLength( buffer, GetRefPointsCount ); for i := 0 to GetRefPointsCount - 1 do begin buffer[i].x := GetRefPoints.GetItem( i ).unitValue; buffer[i].y := GetRefPoints.GetItem( i ).realValue * HEAT_POINT_MULTIPLIER * 10; end; end else begin SetLength( buffer, GetRefPointsCount - 2 ); for i := 1 to GetRefPointsCount - 2 do begin buffer[i - 1].x := GetRefPoints.GetItem( i ).unitValue; buffer[i - 1].y := GetRefPoints.GetItem( i ).realValue * HEAT_POINT_MULTIPLIER * 10; end; end; lagrPoly := Lagrange( buffer ); for i := GetRefPoints.GetItem( 0 ).unitValue to GetRefPoints.GetItem( GetRefPointsCount - 1 ).unitValue do begin index := HLLim( 0, GetItemCount - 1, i + temperatureOffset ); items[index] := lagrPoly.calc( i ) / HEAT_POINT_MULTIPLIER / 10; end; end; //использовать подстроечную точку if ( useHeatTunePoint ) and ( tp_area > 0 ) then begin //realMass := tp_mass / 1000; //приводим милиграммы к граммам koeff := tp_dH * ( tp_mass / 1000 ) / tp_area; tp_factor := koeff; realKoeff := items[Round( HLLim( 0, High( items ), Round( tp_transTemp ) + temperatureOffset ) )]; factor := koeff / realKoeff; if recalcBaseFromTunePoint then //не только пересчитываем значение калибровочной кривой, но и пересчитываем сами реперные точки begin for i := 0 to GetRefPointsCount - 1 do begin refPoint := GetRefPoints.GetItem( i ); refPoint.area := Round( ( refPoint.specificHeat * ( refPoint.weight / 1000 ) ) / ( factor * refPoint.realValue ) ); //if not refPoint.virtualPoint then // if refPoint.area<>0 then // refPoint.realValue := ( refPoint.specificHeat * ( refPoint.weight / 1000 ) ) / refPoint.area; GetRefPoints.SetItem( i, refPoint ); end; // for i := 0 to High( items ) do // items[i] := items[i] * factor; end else for i := 0 to High( items ) do items[i] := items[i] * factor; end; begRealValue := items[0]; endRealValue := items[GetItemCount - 1]; end; constructor THeatCalibrationTable.Create( aBegTemp, aEndTemp: single ); begin SetTemperatureRange( aBegTemp, aEndTemp ); tableType := cttHeat; inherited Create( ); end; function THeatCalibrationTable.GetHeatFactor( aSampleTemp: single ): single; var index: integer; begin index := Round( HLLim( 0, GetItemCount - 1, aSampleTemp + temperatureOffset ) ); Result := items[index]; end; function THeatCalibrationTable.GetInterpolationType: TInterpolationType; begin Result := interpType; end; //function THeatCalibrationTable.GetTemperatureOffset: integer; //begin // Result := temperatureOffset; //end; function THeatCalibrationTable.GetTunePointArea: Integer; begin Result := tp_area; end; function THeatCalibrationTable.GetTunePointDh: single; begin Result := tp_dH; end; function THeatCalibrationTable.GetTunePointFactor: single; begin Result := tp_factor; end; function THeatCalibrationTable.GetTunePointMass: single; begin Result := tp_mass; end; function THeatCalibrationTable.GetTunePointTransTemp: single; begin Result := tp_transTemp; end; function THeatCalibrationTable.IsUseHeatTunePoint: boolean; begin Result := useHeatTunePoint; end; function THeatCalibrationTable.IsUseMarginPoints: boolean; begin Result := tp_useMarginPoints; end; procedure THeatCalibrationTable.LoadFromFileByRangeNo( aDiffTempRange: integer ); begin case aDiffTempRange of 1: LoadFromFile( gConfig.heatCalibrationTable1 ); 2: LoadFromFile( gConfig.heatCalibrationTable2 ); 3: LoadFromFile( gConfig.heatCalibrationTable3 ); 4: LoadFromFile( gConfig.heatCalibrationTable4 ); 5: LoadFromFile( gConfig.heatCalibrationTable5 ); end; end; procedure THeatCalibrationTable.SetInterpolationType( aInterpType: TInterpolationType ); begin interpType := aInterpType; end; procedure THeatCalibrationTable.SetRecalcBaseFromTunePoint( aRecalc: boolean ); begin recalcBaseFromTunePoint := aRecalc; end; procedure THeatCalibrationTable.SetTemperatureRange( aBegTemp, aEndTemp: single ); begin begTemp := Round( aBegTemp ); endTemp := Round( aEndTemp ); SetLength( items, endTemp - begTemp ); temperatureOffset := 0 - begTemp; end; procedure THeatCalibrationTable.SetTunePointArea( aArea: integer ); begin tp_area := aArea; end; procedure THeatCalibrationTable.SetTunePointDh( aDh: single ); begin tp_dH := aDh; end; procedure THeatCalibrationTable.SetTunePointMass( aMass: single ); begin tp_mass := aMass; end; procedure THeatCalibrationTable.SetTunePointTransTemp( aTransTemp: single ); begin tp_transTemp := aTransTemp; end; procedure THeatCalibrationTable.SetUseHeatTunePoint( aUseHeat: boolean ); begin useHeatTunePoint := aUseHeat; end; procedure THeatCalibrationTable.SetUseMarginPoints( aUseMargin: boolean ); begin tp_useMarginPoints := aUseMargin; end; end.
unit Polytest; {The code below was posted by: "John Hutchings" <johnh@datavis.com.au> Date: Fri, 19 Oct 2001 06:20:44 +1000 Newsgroups: borland.public.delphi.graphics // The code below is from Wm. Randolph Franklin <wrf@ecse.rpi.edu> // with some minor modifications for speed. It returns 1 for strictly // interior points, 0 for strictly exterior, and 0 or 1 for points on // the boundary. Comment: returns a Boolean ! } interface uses Classes, SysUtils, {$IFDEF WINDOWS} Wintypes; {$ENDIF} {$IFDEF WIN32} Windows; {$ENDIF} {$IFDEF LINUX} Types, Untranslated; {$ENDIF} function PointInPolygonTest(x, y, N: Integer; aList: Array of TPoint): Boolean; implementation function PointInPolygonTest(x, y, N: Integer; aList: Array of TPoint): Boolean; var I, J : Integer; Function xp(aVal:Integer):Integer; Begin Result:= PPoint(@aList[aVal]).X; end; Function yp(aVal:Integer):Integer; Begin Result:= PPoint(@aList[aVal]).Y; end; begin Result := False; {L := Length(aList);} if (N = 0) then exit; J := N-1; for I := 0 to N-1 do begin if ((((yp(I) <= y) and (y < yp(J))) or ((yp(J) <= y) and (y < yp(I)))) and (x < (xp(J)-xp(I))*(y-yp(I))/(yp(J)-yp(I))+xp(I))) then Result := not Result; J:=I; end; end; end.
unit DCUTbl; (* The table of used units module of the DCU32INT utility by Alexei Hmelnov. It is used to obtain the necessary imported declarations. If the imported unit was not found, the program will still work, but, for example, will show the corresponding constant value as a HEX dump. ---------------------------------------------------------------------------- E-Mail: alex@icc.ru http://hmelnov.icc.ru/DCU/ ---------------------------------------------------------------------------- See the file "readme.txt" for more details. ------------------------------------------------------------------------ IMPORTANT NOTE: This software is provided 'as-is', without any expressed or implied warranty. In no event will the author 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. 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. *) interface uses SysUtils,Classes,DCU32,DCP{$IFDEF Win32},Windows{$ENDIF}; const PathSep = {$IFNDEF LINUX}';'{$ELSE}':'{$ENDIF}; DirSep = {$IFNDEF LINUX}'\'{$ELSE}'/'{$ENDIF}; var DCUPath: String='*'; {To disable LIB directory autodetection use -U flag} PASPath: String='*' {Let only presence of -P signals, that source lines are required}; TopLevelUnitClass: TUnitClass = TUnit; IgnoreUnitStamps: Boolean = true; function ExtractFileNamePkg(const FN: String): String; function GetDCUByName(FName,FExt: String; VerRq: integer; MSILRq: boolean; PlatformRq: TDCUPlatform; StampRq: integer): TUnit; function GetDCUOfMemory(MemP: Pointer): TUnit; procedure FreeDCU; procedure LoadSourceLines(FName: String; Lines: TStrings); procedure SetUnitAliases(const V: String); function IsDCPName(const S: String): Boolean; function LoadPackage(const FName: String; IsMain: Boolean): TDCPackage; const PkgSep = '@'; implementation {const PkgErr = Pointer(1);} var PathList: TStringList = Nil; FUnitAliases: TStringList = Nil; AddedUnitDirToPath: boolean = false; AutoLibDirNDX: Integer = -1; procedure FreePackages; var i: integer; Pkg: TDCPackage; begin if PathList=Nil then Exit; for i:=0 to PathList.Count-1 do begin Pkg := TDCPackage(PathList.Objects[i]); {if Pkg=PkgErr then Continue;} Pkg.Free; end ; PathList.Clear; end ; function ExtractFileNamePkg(const FN: String): String; {Extract file name for packaged or normal files} var CP: PChar; begin Result := ExtractFileName(FN); CP := StrScan(PChar(Result),PkgSep); if CP<>Nil then Result := StrPas(CP+1); end ; function GetDelphiLibDir(VerRq: integer; MSILRq: boolean; PlatformRq: TDCUPlatform): String; { Delphi LIB directory autodetection } {$IFDEF Win32} const sRoot = 'RootDir'; sPlatformDir: array[TDCUPlatform]of String = ('win32','win64','osx32','iOSSimulator','iOSDevice','Android'); var Key: HKey; sPath,sRes,sLib: String; DataType, DataSize: Integer; {$ENDIF} begin Result := ''; {$IFDEF Win32} sPath := ''; sLib := 'Lib'; case VerRq of verD2..verD7: sPath := Format('SOFTWARE\Borland\Delphi\%d.0',[VerRq]); verD8: sPath := 'SOFTWARE\Borland\BDS\2.0'; verD2005: sPath := 'SOFTWARE\Borland\BDS\3.0'; verD2006: sPath := 'SOFTWARE\Borland\BDS\4.0'; // verD2007: sPath := 'SOFTWARE\Borland\BDS\5.0'; This version was not detected verD2009: sPath := 'SOFTWARE\CodeGear\BDS\6.0'; verD2010: sPath := 'SOFTWARE\CodeGear\BDS\7.0'; verD_XE: sPath := 'SOFTWARE\Embarcadero\BDS\8.0'; verD_XE2: sPath := 'SOFTWARE\Embarcadero\BDS\9.0'; verD_XE3: sPath := 'SOFTWARE\Embarcadero\BDS\10.0'; verD_XE4: sPath := 'SOFTWARE\Embarcadero\BDS\11.0'; verD_XE5: sPath := 'SOFTWARE\Embarcadero\BDS\12.0'; //verAppMethod: sPath := 'SOFTWARE\Embarcadero\BDS\13.0'; == verD_XE7 verD_XE6: sPath := 'SOFTWARE\Embarcadero\BDS\14.0'; verD_XE7: sPath := 'SOFTWARE\Embarcadero\BDS\15.0'; end ; if sPath='' then Exit; if RegOpenKeyEx(HKEY_CURRENT_USER, PChar(sPath), 0, KEY_READ, Key)<>ERROR_SUCCESS then if RegOpenKeyEx(HKEY_LOCAL_MACHINE, PChar(sPath), 0, KEY_READ, Key)<>ERROR_SUCCESS then Exit; try if RegQueryValueEx(Key, sRoot, nil, @DataType, nil, @DataSize)<>ERROR_SUCCESS then Exit; if DataType<>REG_SZ then Exit; if DataSize<=SizeOf(Char) then Exit; SetString(sRes, nil, (DataSize div SizeOf(Char)) - 1); if RegQueryValueEx(Key, sRoot, nil, @DataType, PByte(sRes), @DataSize) <> ERROR_SUCCESS then Exit; if sRes[Length(sRes)]<>DirSep then sRes := sRes+DirSep; if VerRq>=verD_XE then sLib := 'lib'+DirSep+sPlatformDir[PlatformRq]+DirSep+'release'; Result := sRes+sLib+DirSep; finally RegCloseKey(Key); end ; {$ENDIF} end ; function IsDCPName(const S: String): Boolean; var Ext: String; begin Ext := ExtractFileExt(S); Result := (CompareText(Ext,'.dcp')=0)or(CompareText(Ext,'.dcpil')=0); end ; function AddToPathList(S: String; SurePkg: boolean): integer; begin if S='' then begin Result := -1; Exit; end ; Result := PathList.IndexOf(S); if Result>=0 then Exit; {It may be wrong on Unix} if SurePkg or IsDCPName(S) then begin if FileExists(S) then begin Result := PathList.AddObject(S,TDCPackage.Create); Exit; end ; Result := -1; if SurePkg then Exit; end ; if not (AnsiLastChar(S)^ in [{$IFNDEF Linux}':',{$ENDIF} DirSep]) then S := S + DirSep; Result := PathList.Add(S); end ; procedure FindPackagesAndAddToPathList(const Mask: String); var SR: TSearchRec; Path,FN,Ext: String; lExt: Integer; begin Ext := ExtractFileExt(Mask); lExt := Length(Ext); if SysUtils.FindFirst(Mask, faAnyFile, sr)<>0 then Exit; Path := ExtractFilePath(Mask); repeat if (sr.Attr and faDirectory)=0 then begin Ext := ExtractFileExt(sr.Name); if Length(Ext)=lExt then //Check that we don`t have .dcpil instead of .dcp AddToPathList(Path+sr.Name,true{SurePkg}); end ; until FindNext(sr) <> 0; end ; procedure SetPathList(const DirList: string); var I, P, L,hDir: Integer; sDir: String; CP: PChar; begin P := 1; L := Length(DirList); while True do begin while (P <= L) and (DirList[P] = PathSep) do Inc(P); if P > L then Break; I := P; while (P <= L) and (DirList[P] <> PathSep) do begin if DirList[P] in LeadBytes then Inc(P); Inc(P); end; sDir := Copy(DirList, I, P-I); if sDir='' then Continue {Paranoic}; CP := PChar(sDir); if ((StrScan(CP,'*')<>Nil)or(StrScan(CP,'?')<>Nil))and IsDCPName(sDir) then begin FindPackagesAndAddToPathList(sDir); Continue; end ; hDir := AddToPathList(sDir,False{SurePkg}); if sDir='*' then AutoLibDirNDX := hDir; //Mark the place to add the directory from registry end; end; (* function AllFilesSearch(Name: string; var DirList: string): string; var I, P, L: Integer; begin Result := Name; P := 1; L := Length(DirList); while True do begin while (P <= L) and (DirList[P] = PathSep) do Inc(P); if P > L then Break; I := P; while (P <= L) and (DirList[P] <> PathSep) do begin if DirList[P] in LeadBytes then Inc(P); Inc(P); end; Result := Copy(DirList, I, P - I); if not (AnsiLastChar(Result)^ in [{$IFNDEF Linux}':',{$ENDIF} DirSep]) then Result := Result + DirSep; Result := Result + Name; if FileExists(Result) then begin Delete(DirList,1,P+1); Exit; end ; end; Result := ''; DirList := ''; end; *) type TDCUSearchRec = record hPath: integer; FN,UnitName: String; Res: PDCPUnitHdr; end ; function InitDCUSearch(FN,FExt: String; var SR: TDCUSearchRec): boolean {HasPath}; var Dir: String; CP: PChar; AddedUnitDir: boolean; begin FillChar(SR,SizeOf(TDCUSearchRec),0); SR.FN := FN; SR.hPath := -1; Dir := ExtractFileDir(FN); Result := Dir<>''; AddedUnitDir := AddedUnitDirToPath; if not AddedUnitDirToPath then begin if (PASPath<>'*') then begin if (PASPath='') then PASPath := Dir else PASPath := Dir + PathSep + PASPath; end ; AddedUnitDirToPath := true; end ; CP := PChar(FN)+Length(Dir); CP := StrScan(CP+1,PkgSep); if CP<>Nil then begin SetLength(FN,CP-PChar(FN)); //Package name with path SR.hPath := AddToPathList(FN,true{SurePkg}); if SR.hPath>=0 then SR.UnitName := StrPas(CP+1); SR.UnitName := ChangeFileExt(SR.UnitName,''); Exit; end ; {if ExtractFileExt(SR.FN)='' then SR.FN := SR.FN+'.dcu';} SR.UnitName := ExtractFileName(SR.FN); SR.FN := SR.FN+FExt; (* if (DCUPath='') then DCUPath := Dir else DCUPath := Dir + {$IFNDEF LINUX}';'{$ELSE}';'{$ENDIF}+DCUPath; *) if not AddedUnitDir then AddToPathList(Dir,False{SurePkg}); if Dir='' then SR.hPath := 0; end ; function FindDCU(var SR: TDCUSearchRec): String; var S: String; Pkg: TDCPackage; begin Result := ''; SR.Res := Nil; if SR.hPath<0 then begin if FileExists(SR.FN) then Result := SR.FN; Exit; end ; if PathList=Nil then Exit {Paranoic}; if SR.hPath>=PathList.Count then SR.hPath := -1 else begin S := PathList[SR.hPath]; Pkg := TDCPackage(PathList.Objects[SR.hPath]); Inc(SR.hPath); if Pkg=Nil then begin if S='*'+DirSep then Exit; Result := S+SR.FN; if FileExists(Result) then Exit; Result := ''; end else if Pkg.Load(S,false) then begin SR.Res := Pkg.GetFileByName(SR.UnitName); if SR.Res<>Nil then Result := S+PkgSep+SR.UnitName+ExtractFileExt(SR.FN); end ; end ; end ; var UnitList: TStringList = Nil; function GetUnitList: TStringList; begin if UnitList=Nil then begin UnitList := TStringList.Create; UnitList.Sorted := true; UnitList.Duplicates := dupError; end ; Result := UnitList; end ; procedure RegisterUnit(const Name: String; U: TUnit); var UL: TStringList; begin UL := GetUnitList; UL.AddObject(Name,U); end ; procedure NeedPathList; begin if PathList=Nil then begin PathList := TStringList.Create; SetPathList(DCUPath); end ; end; function GetDCUByName(FName,FExt: String; VerRq: integer; MSILRq: boolean; PlatformRq: TDCUPlatform; StampRq: integer): TUnit; var UL: TStringList; NDX: integer; U0: TUnit; // SearchPath: String; SR: TDCUSearchRec; FN,UnitName: String; HasPath: Boolean; Cl: TUnitClass; begin UL := GetUnitList; NeedPathList; if (AutoLibDirNDX>=0)and(VerRq>0) then begin FN := GetDelphiLibDir(VerRq,MSILRq,PlatformRq); if (FN<>'')and(PathList.IndexOf(FN)>=0) then FN := ''; if FN='' then PathList.Delete(AutoLibDirNDX) else PathList[AutoLibDirNDX] := FN; AutoLibDirNDX := -1; //Substitution for * was made end ; {if not AddedUnitDirToPath then begin AddUnitDirToPath(FName); AddedUnitDirToPath := true; end ;} UnitName := ExtractFileNamePkg(FName); HasPath := Length(UnitName)<Length(FName); if HasPath or(FExt=''{FExt is not empty for the units from uses}) then UnitName := ChangeFileExt(UnitName,''); if not HasPath and(FUnitAliases<>Nil) then begin FN := FUnitAliases.Values[UnitName{FName}]; if FN<>'' then begin UnitName{FName} := FN; FName{FName} := FN; end ; end ; if IgnoreUnitStamps or not((VerRq>verD2){In Delphi 2.0 Stamp is not used}and (VerRq<=verD7){The higher versions ignore the value too}or(VerRq>=verK1)) then StampRq := 0; if UL.Find(UnitName{FName},NDX) then Result := TUnit(UL.Objects[NDX]) else begin InitDCUSearch(FName,FExt,SR); // SearchPath := DCUPath; Result := Nil; U0 := CurUnit; try FN := FName; repeat FName := FindDCU(SR); if FName<>'' then begin if VerRq=0 then Cl := TopLevelUnitClass else Cl := TUnit; Result := Cl.Create; try if Result.Load(FName,VerRq,MSILRq,PlatformRq,SR.Res) then begin if (StampRq=0)or(StampRq=Result.Stamp) then {Let`s check it here to try to find the correct stamp somewhere else} break; end; except on E: Exception do begin if VerRq=0 then //Main Unit => reraise; raise; //The unit with the required version found, but it was wrong. //Report the problem and stop the search Writeln(Format('!!!%s: %s',[E.ClassName,E.Message])); Result.Free; Result := Nil; break; end ; end ; Result.Free; Result := Nil; end ; until SR.hPath<0; if Result<>Nil then RegisterUnit(UnitName{Result.UnitName - some units in packages may have different source file name}, Result) else RegisterUnit(FN, Nil); //Means: don't seek this name again, //It's supposed that FName is a unit name without path finally CurUnit := U0; end ; end ; if Result=Nil then Exit; if (StampRq<>0)and(StampRq<>Result.Stamp) then Result := Nil; end ; function GetDCUOfMemory(MemP: Pointer): TUnit; var UL: TStringList; U: TUnit; i: Integer; begin if MemP<>Nil then begin if (CurUnit<>Nil)and CurUnit.IsValidMemPtr(MemP) then begin Result := CurUnit; Exit; end ; UL := GetUnitList; for i:=0 to UL.Count-1 do begin U := TUnit(UL.Objects[i]); if (U<>Nil)and U.IsValidMemPtr(MemP) then begin Result := U; Exit; end ; end ; end ; Result := Nil; end ; procedure FreeDCU; var i: integer; U: TUnit; begin if UnitList=Nil then Exit; for i:=0 to UnitList.Count-1 do begin U := TUnit(UnitList.Objects[i]); U.Free; end ; UnitList.Free; UnitList := Nil; FreePackages; end ; function FindPAS(FName: String): String; var S: String; begin if PASPath='*' then begin Result := ''; Exit; end ; S := ExtractFilePath(FName); if S<>'' then begin if FileExists(FName) then begin Result := FName; Exit; end ; FName := ExtractFileName(FName); end ; Result := FileSearch(FName,PASPath); end ; procedure LoadSourceLines(FName: String; Lines: TStrings); var S: String; begin S := FindPAS(FName); if S='' then Exit; Lines.LoadFromFile(S); end ; procedure SetUnitAliases(const V: String); var CP,EP,NP: PChar; S: String; begin if FUnitAliases<>Nil then FUnitAliases.Clear; if V='' then Exit; if FUnitAliases=Nil then FUnitAliases := TStringList.Create; CP := PChar(V); repeat NP := StrScan(CP,';'); if NP=Nil then EP := StrEnd(CP) else begin EP := NP; NP := EP+1; end ; SetString(S,CP,EP-CP); if S<>'' then FUnitAliases.Add(S); CP := NP; until CP=Nil; end ; function LoadPackage(const FName: String; IsMain: Boolean): TDCPackage; var hPkg: Integer; begin Result :=Nil; NeedPathList; hPkg := AddToPathList(FName,true{SurePkg}); if hPkg<0 then Exit; Result := TDCPackage(PathList.Objects[hPkg]); if Result=Nil then Exit; if not Result.Load(FName,IsMain) then Result := Nil; end; initialization finalization FUnitAliases.Free; PathList.Free; end.
unit NtUtils.Packages; { This module provides functions for retrieving information about packaged applications. } interface uses Ntapi.WinNt, Ntapi.appmodel, Ntapi.ntseapi, Ntapi.ntpebteb, Ntapi.Versions, DelphiApi.Reflection, DelphiUtils.AutoObjects, NtUtils; type IPackageInfoReference = IHandle; TPkgxPackageId = record ProcessorArchitecture: TProcessorArchitecture; Version: TPackageVersion; Name: String; Publisher: String; ResourceID: String; PublisherID: String; end; TPkgxPackageNameAndProperties = record FullName: String; Properties: TPackageProperties; end; TPkgxPackageInfo = record Properties: TPackageProperties; Path: String; PackageFullName: String; PackageFamilyName: String; [Aggregate] ID: TPkgxPackageId; end; // Retrieve identification information of a package by its full name [MinOSVersion(OsWin8)] function PkgxQueryPackageId( out PackageId: TPkgxPackageId; const FullName: String; Flags: TPackageInformationFlags = PACKAGE_INFORMATION_FULL ): TNtxStatus; // Construct full package name from its identification information [MinOSVersion(OsWin8)] function PkgxFullNameFromId( out FullName: String; const PackageId: TPkgxPackageId ): TNtxStatus; // Construct package family name from its identification information [MinOSVersion(OsWin8)] function PkgxFamilyNameFromId( out FamilyName: String; const PackageId: TPkgxPackageId ): TNtxStatus; // Convert a full package name to a family name [MinOSVersion(OsWin8)] function PkgxFamilyNameFromFullName( out FamilyName: String; const FullName: String ): TNtxStatus; // Convert a pakage name and publisher from a family name [MinOSVersion(OsWin8)] function PkgxNameAndPublisherIdFromFamilyName( const FamilyName: String; out Name: String; out PulisherId: String ): TNtxStatus; // Retrieve the list of packages in a family [MinOSVersion(OsWin8)] function PkgxEnumeratePackagesInFamily( out FullNames: TArray<String>; const FamilyName: String ): TNtxStatus; // Retrieve the list of packages in a family according to a filter [MinOSVersion(OsWin81)] function PkgxEnumeratePackagesInFamilyEx( out Packages: TArray<TPkgxPackageNameAndProperties>; const FamilyName: String; Filter: TPackageFilters = MAX_UINT ): TNtxStatus; // Determine package origin based on its full name [MinOSVersion(OsWin81)] function PkgxQueryPackageOrigin( out Origin: TPackageOrigin; const FullName: String ): TNtxStatus; // Open information about a package [MinOSVersion(OsWin8)] function PkgxOpenPackageInfo( out InfoReference: IPackageInfoReference; const FullName: String ): TNtxStatus; // Open information about a package of another user [MinOSVersion(OsWin10TH1)] function PkgxOpenPackageInfoForUser( out InfoReference: IPackageInfoReference; const FullName: String; [opt] const UserSid: ISid ): TNtxStatus; // Query information about a package [MinOSVersion(OsWin8)] function PkgxQueryPackageInfo( out Info: TArray<TPkgxPackageInfo>; const InfoReference: IPackageInfoReference; Flags: TPackageFilters = MAX_UINT ): TNtxStatus; // Query information about a package using a specific path type [MinOSVersion(OsWin1019H1)] function PkgxQueryPackageInfo2( out Info: TArray<TPkgxPackageInfo>; const InfoReference: IPackageInfoReference; PathType: TPackagePathType; Flags: TPackageFilters = MAX_UINT ): TNtxStatus; // Check is a package is a MSIX package [MinOSVersion(OsWin1021H1)] function PkgxIsMsixPackage( const FullName: String; out IsMSIXPackage: LongBool ): TNtxStatus; // Retrieve an app model policy for package by its access token [MinOSVersion(OsWin10RS1)] function PkgxQueryAppModelPolicy( [Access(TOKEN_QUERY)] const hxToken: IHandle; PolicyType: TAppModelPolicyType; out Policy: TAppModelPolicyValue; ReturnValueOnly: Boolean = True // aka clear type bits of the policy ): TNtxStatus; // Check if the current OS version supports the specified app model policy type function PkgxIsPolicyTypeSupported( PolicyType: TAppModelPolicyType ): Boolean; // Find TypeInfo of the enumeration that corresponds to an app model policy type function PkgxGetPolicyTypeInfo( PolicyType: TAppModelPolicyType ): Pointer; implementation uses Ntapi.ntstatus, Ntapi.ntldr, NtUtils.Ldr, NtUtils.SysUtils; {$BOOLEVAL OFF} {$IFOPT R+}{$DEFINE R+}{$ENDIF} {$IFOPT Q+}{$DEFINE Q+}{$ENDIF} { Helper functions } type TAutoPackageInfoReference = class(TCustomAutoHandle, IPackageInfoReference) procedure Release; override; end; procedure TAutoPackageInfoReference.Release; begin if (FHandle <> 0) and LdrxCheckModuleDelayedImport(kernelbase, 'ClosePackageInfo').IsSuccess then ClosePackageInfo(FHandle); FHandle := 0; inherited; end; function PkgxpCapturePackageId( [in] Buffer: PPackageId ): TPkgxPackageId; begin Result.ProcessorArchitecture := Buffer.ProcessorArchitecture; Result.Version := Buffer.Version; Result.Name := String(Buffer.Name); Result.Publisher := String(Buffer.Publisher); Result.ResourceID := String(Buffer.ResourceID); Result.PublisherID := String(Buffer.PublisherID); end; function PkgxpConvertPackageId( const PackageId: TPkgxPackageId ): TPackageId; begin Result.Reserved := 0; Result.ProcessorArchitecture := PackageId.ProcessorArchitecture; Result.Version := PackageId.Version; Result.Name := PWideChar(PackageId.Name); Result.Publisher := PWideChar(PackageId.Publisher); Result.ResourceID := PWideChar(PackageId.ResourceID); Result.PublisherID := PWideChar(PackageId.PublisherID); end; function PkgxpCapturePackageInfo( const Buffer: TPackageInfo ): TPkgxPackageInfo; begin Result.Properties := Buffer.Flags; Result.Path := String(Buffer.Path); Result.PackageFullName := String(Buffer.PackageFullName); Result.PackageFamilyName := String(Buffer.PackageFamilyName); Result.ID := PkgxpCapturePackageId(@Buffer.PackageId); end; { Functions } function PkgxQueryPackageId; var BufferSize: Cardinal; Buffer: IMemory<PPackageId>; begin Result := LdrxCheckModuleDelayedImport(kernelbase, 'PackageIdFromFullName'); if not Result.IsSuccess then Exit; BufferSize := SizeOf(TPackageId); repeat IMemory(Buffer) := Auto.AllocateDynamic(BufferSize); Result.Location := 'PackageIdFromFullName'; Result.Win32ErrorOrSuccess := PackageIdFromFullName(PWideChar(FullName), Flags, BufferSize, Buffer.Data); until not NtxExpandBufferEx(Result, IMemory(Buffer), BufferSize, nil); if Result.IsSuccess then PackageId := PkgxpCapturePackageId(Buffer.Data); end; function PkgxFullNameFromId; var Id: TPackageId; BufferLength: Cardinal; Buffer: IMemory<PWideChar>; begin Result := LdrxCheckModuleDelayedImport(kernelbase, 'PackageFullNameFromId'); if not Result.IsSuccess then Exit; BufferLength := 0; Id := PkgxpConvertPackageId(PackageId); repeat IMemory(Buffer) := Auto.AllocateDynamic(BufferLength * SizeOf(WideChar)); Result.Location := 'PackageFullNameFromId'; Result.Win32ErrorOrSuccess := PackageFullNameFromId(Id, BufferLength, Buffer.Data); until not NtxExpandBufferEx(Result, IMemory(Buffer), BufferLength * SizeOf(WideChar), nil); if Result.IsSuccess then FullName := RtlxCaptureString(Buffer.Data, BufferLength); end; function PkgxFamilyNameFromId; var Id: TPackageId; BufferLength: Cardinal; Buffer: IMemory<PWideChar>; begin Result := LdrxCheckModuleDelayedImport(kernelbase, 'PackageFamilyNameFromId'); if not Result.IsSuccess then Exit; BufferLength := 0; Id := PkgxpConvertPackageId(PackageId); repeat IMemory(Buffer) := Auto.AllocateDynamic(BufferLength * SizeOf(WideChar)); Result.Location := 'PackageFamilyNameFromId'; Result.Win32ErrorOrSuccess := PackageFamilyNameFromId(Id, BufferLength, Buffer.Data); until not NtxExpandBufferEx(Result, IMemory(Buffer), BufferLength * SizeOf(WideChar), nil); if Result.IsSuccess then FamilyName := RtlxCaptureString(Buffer.Data, BufferLength); end; function PkgxFamilyNameFromFullName; var BufferLength: Cardinal; Buffer: IMemory<PWideChar>; begin Result := LdrxCheckModuleDelayedImport(kernelbase, 'PackageFamilyNameFromFullName'); if not Result.IsSuccess then Exit; BufferLength := 0; repeat IMemory(Buffer) := Auto.AllocateDynamic(BufferLength * SizeOf(WideChar)); Result.Location := 'PackageFamilyNameFromFullName'; Result.Win32ErrorOrSuccess := PackageFamilyNameFromFullName( PWideChar(FullName), BufferLength, Buffer.Data); until not NtxExpandBufferEx(Result, IMemory(Buffer), BufferLength * SizeOf(WideChar), nil); if Result.IsSuccess then FamilyName := RtlxCaptureString(Buffer.Data, BufferLength); end; function PkgxNameAndPublisherIdFromFamilyName; var NameLength, PublisherIdLength: Cardinal; NameBuffer, PublisherBuffer: IMemory<PWideChar>; begin Result := LdrxCheckModuleDelayedImport(kernelbase, 'PackageNameAndPublisherIdFromFamilyName'); if not Result.IsSuccess then Exit; NameLength := 0; PublisherIdLength := 0; repeat IMemory(NameBuffer) := Auto.AllocateDynamic(NameLength * SizeOf(WideChar)); IMemory(PublisherBuffer) := Auto.AllocateDynamic(PublisherIdLength * SizeOf(WideChar)); Result.Location := 'PackageNameAndPublisherIdFromFamilyName'; Result.Win32ErrorOrSuccess := PackageNameAndPublisherIdFromFamilyName( PWideChar(FamilyName), NameLength, NameBuffer.Data, PublisherIdLength, PublisherBuffer.Data); until not NtxExpandBufferEx(Result, IMemory(NameBuffer), NameLength * SizeOf(WideChar), nil) or not NtxExpandBufferEx(Result, IMemory(PublisherBuffer), PublisherIdLength * SizeOf(WideChar), nil); if Result.IsSuccess then begin Name := RtlxCaptureString(NameBuffer.Data, NameLength); PulisherId := RtlxCaptureString(PublisherBuffer.Data, PublisherIdLength); end; end; function PkgxEnumeratePackagesInFamily; var Count, BufferLength: Cardinal; Names: IMemory<PPackageFullNames>; Buffer: IMemory<PWideChar>; i: Integer; begin Result := LdrxCheckModuleDelayedImport(kernelbase, 'GetPackagesByPackageFamily'); if not Result.IsSuccess then Exit; Count := 0; BufferLength := 0; repeat IMemory(Names) := Auto.AllocateDynamic(Count * SizeOf(PWideChar)); IMemory(Buffer) := Auto.AllocateDynamic(BufferLength * SizeOf(WideChar)); Result.Location := 'GetPackagesByPackageFamily'; Result.Win32ErrorOrSuccess := GetPackagesByPackageFamily( PWideChar(FamilyName), Count, Names.Data, BufferLength, Buffer.Data); until not NtxExpandBufferEx(Result, IMemory(Names), Count * SizeOf(PWideChar), nil) or not NtxExpandBufferEx(Result, IMemory(Buffer), BufferLength * SizeOf(WideChar), nil); if not Result.IsSuccess then Exit; SetLength(FullNames, Count); for i := 0 to High(FullNames) do FullNames[i] := String(Names.Data{$R-}[i]{$IFDEF R+}{$R+}{$ENDIF}); end; function PkgxEnumeratePackagesInFamilyEx; var Count, BufferLength: Cardinal; Names: IMemory<PPackageFullNames>; Buffer: IMemory<PWideChar>; Properties: IMemory<PPackagePropertiesArray>; i: Integer; begin Result := LdrxCheckModuleDelayedImport(kernelbase, 'FindPackagesByPackageFamily'); if not Result.IsSuccess then Exit; Count := 0; BufferLength := 0; repeat IMemory(Names) := Auto.AllocateDynamic(Count * SizeOf(PWideChar)); IMemory(Properties) := Auto.AllocateDynamic(Count * SizeOf(TPackageProperties)); IMemory(Buffer) := Auto.AllocateDynamic(BufferLength * SizeOf(WideChar)); Result.Location := 'FindPackagesByPackageFamily'; Result.Win32ErrorOrSuccess := FindPackagesByPackageFamily( PWideChar(FamilyName), Filter, Count, Names.Data, BufferLength, Buffer.Data, Properties.Data); until not NtxExpandBufferEx(Result, IMemory(Names), Count * SizeOf(PWideChar), nil) or not NtxExpandBufferEx(Result, IMemory(Buffer), BufferLength * SizeOf(WideChar), nil); if not Result.IsSuccess then Exit; SetLength(Packages, Count); for i := 0 to High(Packages) do begin Packages[i].FullName := String(Names.Data{$R-}[i]{$IFDEF R+}{$R+}{$ENDIF}); Packages[i].Properties := Properties.Data{$R-}[i]{$IFDEF R+}{$R+}{$ENDIF}; end; end; function PkgxQueryPackageOrigin; begin Result := LdrxCheckModuleDelayedImport(kernelbase, 'GetStagedPackageOrigin'); if not Result.IsSuccess then Exit; Result.Location := 'GetStagedPackageOrigin'; Result.Win32ErrorOrSuccess := GetStagedPackageOrigin(PWideChar(FullName), Origin); end; function PkgxOpenPackageInfo; var PackageInfoReference: TPackageInfoReference; begin Result := LdrxCheckModuleDelayedImport(kernelbase, 'OpenPackageInfoByFullName'); if not Result.IsSuccess then Exit; Result.Location := 'OpenPackageInfoByFullName'; Result.Win32ErrorOrSuccess := OpenPackageInfoByFullName(PWideChar(FullName), 0, PackageInfoReference); if Result.IsSuccess then InfoReference := TAutoPackageInfoReference.Capture(PackageInfoReference); end; function PkgxOpenPackageInfoForUser; var PackageInfoReference: TPackageInfoReference; begin Result := LdrxCheckModuleDelayedImport(kernelbase, 'OpenPackageInfoByFullNameForUser'); if not Result.IsSuccess then Exit; Result.Location := 'OpenPackageInfoByFullNameForUser'; Result.Win32ErrorOrSuccess := OpenPackageInfoByFullNameForUser( Auto.RefOrNil<PSid>(UserSid), PWideChar(FullName), 0, PackageInfoReference); if Result.IsSuccess then InfoReference := TAutoPackageInfoReference.Capture(PackageInfoReference); end; function PkgxQueryPackageInfo; var BufferSize: Cardinal; Buffer: IMemory<PPackageInfoArray>; Count: Cardinal; i: Integer; begin Result := LdrxCheckModuleDelayedImport(kernelbase, 'GetPackageInfo'); if not Result.IsSuccess then Exit; BufferSize := 0; repeat IMemory(Buffer) := Auto.AllocateDynamic(BufferSize); Result.Location := 'GetPackageInfo'; Result.Win32ErrorOrSuccess := GetPackageInfo(InfoReference.Handle, Flags, BufferSize, Buffer.Data, @Count); until not NtxExpandBufferEx(Result, IMemory(Buffer), BufferSize, nil); if not Result.IsSuccess then Exit; SetLength(Info, Count); for i := 0 to High(Info) do Info[i] := PkgxpCapturePackageInfo(Buffer .Data{$R-}[i]{$IFDEF R+}{$R+}{$ENDIF}) end; function PkgxQueryPackageInfo2; var BufferSize: Cardinal; Buffer: IMemory<PPackageInfoArray>; Count: Cardinal; i: Integer; begin Result := LdrxCheckModuleDelayedImport(kernelbase, 'GetPackageInfo2'); if not Result.IsSuccess then Exit; BufferSize := 0; repeat IMemory(Buffer) := Auto.AllocateDynamic(BufferSize); Result.Location := 'GetPackageInfo2'; Result.Win32ErrorOrSuccess := GetPackageInfo2(InfoReference.Handle, Flags, PathType, BufferSize, Buffer.Data, @Count); until not NtxExpandBufferEx(Result, IMemory(Buffer), BufferSize, nil); if not Result.IsSuccess then Exit; SetLength(Info, Count); for i := 0 to High(Info) do Info[i] := PkgxpCapturePackageInfo(Buffer .Data{$R-}[i]{$IFDEF R+}{$R+}{$ENDIF}) end; function PkgxIsMsixPackage; begin Result := LdrxCheckModuleDelayedImport(kernelbase, 'CheckIsMSIXPackage'); if Result.IsSuccess then begin Result.Location := 'CheckIsMSIXPackage'; Result.HResult := CheckIsMSIXPackage(PWideChar(FullName), IsMSIXPackage); end; end; var GetAppModelPolicy: function ( [Access(TOKEN_QUERY)] hToken: THandle; PolicyType: TAppModelPolicyType; out Policy: TAppModelPolicyValue ): TWin32Error; stdcall; function PkgxQueryAppModelPolicy; const {$IFDEF Win64} SEARCH_OFFSET = $19; SEARCH_VALUE = $E800000001BA3024; PROLOG_VALUE = $48EC8348; {$ELSE} SEARCH_OFFSET = $18; SEARCH_VALUE = $E84250D233FC458D; PROLOG_VALUE = $8B55FF8B; {$ENDIF} var KernelBaseModule: TModuleEntry; pAsmCode, pPrefix, pRva, pFunction: Pointer; begin // GetAppModelPolicy doesn't check if the policy type is supported on the // current OS version and can, thus, read out of bound. Fix it here. if not PkgxIsPolicyTypeSupported(PolicyType) then begin Result.Location := 'PkgxQueryAppModelPolicy'; Result.Status := STATUS_INVALID_INFO_CLASS; Exit; end; try if not Assigned(GetAppModelPolicy) then begin // GetAppModelPolicy is an unexporetd function in kernelbase. To locate // it, we need to parse an exported function that uses it, such as // AppPolicyGetLifecycleManagement. Result := LdrxFindModule(KernelBaseModule, ByBaseName(kernelbase)); if not Result.IsSuccess then Exit; Result := LdrxGetProcedureAddress(KernelBaseModule.DllBase, 'AppPolicyGetLifecycleManagement', pAsmCode); if not Result.IsSuccess then Exit; // First, we check a few bytes before the call instruction to make sure // we recognize the code pPrefix := PByte(pAsmCode) + SEARCH_OFFSET; if PUInt64(pPrefix)^ <> SEARCH_VALUE then begin Result.Location := 'PkgxQueryAppModelPolicy'; Result.Status := STATUS_ENTRYPOINT_NOT_FOUND; Exit; end; // Then, we find where the call instruction points pRva := PByte(pPrefix) + SizeOf(UInt64); pFunction := PByte(pRva) + PCardinal(pRva)^ + SizeOf(Cardinal); // Make sure we point to a function prolog inside the same module if not KernelBaseModule.IsInRange(pFunction) or (PCardinal(pFunction)^ <> PROLOG_VALUE) then begin Result.Location := 'PkgxQueryAppModelPolicy (#2)'; Result.Status := STATUS_ENTRYPOINT_NOT_FOUND; Exit; end; // Everything seems correct, save the address @GetAppModelPolicy := pFunction; end; // Query the policy value Result.Location := 'GetAppModelPolicy'; Result.LastCall.Expects<TTokenAccessMask>(TOKEN_QUERY); Result.LastCall.UsesInfoClass(PolicyType, icQuery); Result.Win32ErrorOrSuccess := GetAppModelPolicy(hxToken.Handle, PolicyType, Policy); // Extract the value to simplify type casting if Result.IsSuccess and ReturnValueOnly then Policy := Policy and APP_MODEL_POLICY_VALUE_MASK; except Result.Location := 'PkgxQueryAppModelPolicy'; Result.Status := STATUS_ACCESS_VIOLATION; end; end; function PkgxIsPolicyTypeSupported( PolicyType: TAppModelPolicyType ): Boolean; var RequiredVersion: TWindowsVersion; begin case PolicyType of AppModelPolicy_Type_Unspecified.. AppModelPolicy_Type_WinInetStoragePartitioning: RequiredVersion := OsWin10RS1; AppModelPolicy_Type_IndexerProtocolHandlerHost.. AppModelPolicy_Type_PackageMayContainPrivateMapiProvider: RequiredVersion := OsWin10RS2; AppModelPolicy_Type_AdminProcessPackageClaims.. AppModelPolicy_Type_GlobalSystemAppdataAccess: RequiredVersion := OsWin10RS3; AppModelPolicy_Type_ConsoleHandleInheritance.. AppModelPolicy_Type_ConvertCallerTokenToUserTokenForDeployment: RequiredVersion := OsWin10RS4; AppModelPolicy_Type_ShellExecuteRetrieveIdentityFromCurrentProcess: RequiredVersion := OsWin10RS5; AppModelPolicy_Type_CodeIntegritySigning..AppModelPolicy_Type_PTCActivation: RequiredVersion := OsWin1019H1; AppModelPolicy_Type_COMIntraPackageRPCCall.. AppModelPolicy_Type_PullPackageDependencyData: RequiredVersion := OsWin1020H1; AppModelPolicy_Type_AppInstancingErrorBehavior.. AppModelPolicy_Type_ModsPowerNotifification: RequiredVersion := OsWin11; else Exit(False); end; Result := RtlOsVersionAtLeast(RequiredVersion); end; function PkgxGetPolicyTypeInfo; begin case PolicyType of AppModelPolicy_Type_LifecycleManager: Result := TypeInfo(TAppModelPolicy_LifecycleManager); AppModelPolicy_Type_AppdataAccess: Result := TypeInfo(TAppModelPolicy_AppdataAccess); AppModelPolicy_Type_WindowingModel: Result := TypeInfo(TAppModelPolicy_WindowingModel); AppModelPolicy_Type_DLLSearchOrder: Result := TypeInfo(TAppModelPolicy_DLLSearchOrder); AppModelPolicy_Type_Fusion: Result := TypeInfo(TAppModelPolicy_Fusion); AppModelPolicy_Type_NonWindowsCodecLoading: Result := TypeInfo(TAppModelPolicy_NonWindowsCodecLoading); AppModelPolicy_Type_ProcessEnd: Result := TypeInfo(TAppModelPolicy_ProcessEnd); AppModelPolicy_Type_BeginThreadInit: Result := TypeInfo(TAppModelPolicy_BeginThreadInit); AppModelPolicy_Type_DeveloperInformation: Result := TypeInfo(TAppModelPolicy_DeveloperInformation); AppModelPolicy_Type_CreateFileAccess: Result := TypeInfo(TAppModelPolicy_CreateFileAccess); AppModelPolicy_Type_ImplicitPackageBreakaway: Result := TypeInfo(TAppModelPolicy_ImplicitPackageBreakaway); AppModelPolicy_Type_ProcessActivationShim: Result := TypeInfo(TAppModelPolicy_ProcessActivationShim); AppModelPolicy_Type_AppKnownToStateRepository: Result := TypeInfo(TAppModelPolicy_AppKnownToStateRepository); AppModelPolicy_Type_AudioManagement: Result := TypeInfo(TAppModelPolicy_AudioManagement); AppModelPolicy_Type_PackageMayContainPublicCOMRegistrations: Result := TypeInfo(TAppModelPolicy_PackageMayContainPublicCOMRegistrations); AppModelPolicy_Type_PackageMayContainPrivateCOMRegistrations: Result := TypeInfo(TAppModelPolicy_PackageMayContainPrivateCOMRegistrations); AppModelPolicy_Type_LaunchCreateprocessExtensions: Result := TypeInfo(TAppModelPolicy_LaunchCreateprocessExtensions); AppModelPolicy_Type_CLRCompat: Result := TypeInfo(TAppModelPolicy_CLRCompat); AppModelPolicy_Type_LoaderIgnoreAlteredSearchForRelativePath: Result := TypeInfo(TAppModelPolicy_LoaderIgnoreAlteredSearchForRelativePath); AppModelPolicy_Type_ImplicitlyActivateClassicAAAServersAsIU: Result := TypeInfo(TAppModelPolicy_ImplicitlyActivateClassicAAAServersAsIU); AppModelPolicy_Type_COMClassicCatalog: Result := TypeInfo(TAppModelPolicy_COMClassicCatalog); AppModelPolicy_Type_COMUnmarshaling: Result := TypeInfo(TAppModelPolicy_COMUnmarshaling); AppModelPolicy_Type_COMAppLaunchPerfEnhancements: Result := TypeInfo(TAppModelPolicy_COMAppLaunchPerfEnhancements); AppModelPolicy_Type_COMSecurityInitialization: Result := TypeInfo(TAppModelPolicy_COMSecurityInitialization); AppModelPolicy_Type_ROInitializeSingleThreadedBehavior: Result := TypeInfo(TAppModelPolicy_ROInitializeSingleThreadedBehavior); AppModelPolicy_Type_COMDefaultExceptionHandling: Result := TypeInfo(TAppModelPolicy_COMDefaultExceptionHandling); AppModelPolicy_Type_COMOopProxyAgility: Result := TypeInfo(TAppModelPolicy_COMOopProxyAgility); AppModelPolicy_Type_AppServiceLifetime: Result := TypeInfo(TAppModelPolicy_AppServiceLifetime); AppModelPolicy_Type_WebPlatform: Result := TypeInfo(TAppModelPolicy_WebPlatform); AppModelPolicy_Type_WinInetStoragePartitioning: Result := TypeInfo(TAppModelPolicy_WinInetStoragePartitioning); AppModelPolicy_Type_IndexerProtocolHandlerHost: Result := TypeInfo(TAppModelPolicy_IndexerProtocolHandlerHost); AppModelPolicy_Type_LoaderIncludeUserDirectories: Result := TypeInfo(TAppModelPolicy_LoaderIncludeUserDirectories); AppModelPolicy_Type_ConvertAppcontainerToRestrictedAppcontainer: Result := TypeInfo(TAppModelPolicy_ConvertAppcontainerToRestrictedAppcontainer); AppModelPolicy_Type_PackageMayContainPrivateMapiProvider: Result := TypeInfo(TAppModelPolicy_PackageMayContainPrivateMapiProvider); AppModelPolicy_Type_AdminProcessPackageClaims: Result := TypeInfo(TAppModelPolicy_AdminProcessPackageClaims); AppModelPolicy_Type_RegistryRedirectionBehavior: Result := TypeInfo(TAppModelPolicy_RegistryRedirectionBehavior); AppModelPolicy_Type_BypassCreateprocessAppxExtension: Result := TypeInfo(TAppModelPolicy_BypassCreateprocessAppxExtension); AppModelPolicy_Type_KnownFolderRedirection: Result := TypeInfo(TAppModelPolicy_KnownFolderRedirection); AppModelPolicy_Type_PrivateActivateAsPackageWinrtClasses: Result := TypeInfo(TAppModelPolicy_PrivateActivateAsPackageWinrtClasses); AppModelPolicy_Type_AppPrivateFolderRedirection: Result := TypeInfo(TAppModelPolicy_AppPrivateFolderRedirection); AppModelPolicy_Type_GlobalSystemAppdataAccess: Result := TypeInfo(TAppModelPolicy_GlobalSystemAppdataAccess); AppModelPolicy_Type_ConsoleHandleInheritance: Result := TypeInfo(TAppModelPolicy_ConsoleHandleInheritance); AppModelPolicy_Type_ConsoleBufferAccess: Result := TypeInfo(TAppModelPolicy_ConsoleBufferAccess); AppModelPolicy_Type_ConvertCallerTokenToUserTokenForDeployment: Result := TypeInfo(TAppModelPolicy_ConvertCallerTokenToUserTokenForDeployment); AppModelPolicy_Type_ShellexecuteRetrieveIdentityFromCurrentProcess: Result := TypeInfo(TAppModelPolicy_ShellexecuteRetrieveIdentityFromCurrentProcess); AppModelPolicy_Type_CodeIntegritySigning: Result := TypeInfo(TAppModelPolicy_CodeIntegritySigning); AppModelPolicy_Type_PTCActivation: Result := TypeInfo(TAppModelPolicy_PTCActivation); AppModelPolicy_Type_COMIntraPackageRPCCall: Result := TypeInfo(TAppModelPolicy_COMIntraPackageRPCCall); AppModelPolicy_Type_LoadUser32ShimOnWindowsCoreOS: Result := TypeInfo(TAppModelPolicy_LoadUser32ShimOnWindowsCoreOS); AppModelPolicy_Type_SecurityCapabilitiesOverride: Result := TypeInfo(TAppModelPolicy_SecurityCapabilitiesOverride); AppModelPolicy_Type_CurrentDirectoryOverride: Result := TypeInfo(TAppModelPolicy_CurrentDirectoryOverride); AppModelPolicy_Type_COMTokenMatchingForAAAServers: Result := TypeInfo(TAppModelPolicy_COMTokenMatchingForAAAServers); AppModelPolicy_Type_UseOriginalFileNameInTokenFQBNAttribute: Result := TypeInfo(TAppModelPolicy_UseOriginalFileNameInTokenFQBNAttribute); AppModelPolicy_Type_LoaderIncludeAlternateForwarders: Result := TypeInfo(TAppModelPolicy_LoaderIncludeAlternateForwarders); AppModelPolicy_Type_PullPackageDependencyData: Result := TypeInfo(TAppModelPolicy_PullPackageDependencyData); AppModelPolicy_Type_AppInstancingErrorBehavior: Result := TypeInfo(TAppModelPolicy_AppInstancingErrorBehavior); AppModelPolicy_Type_BackgroundTaskRegistrationType: Result := TypeInfo(TAppModelPolicy_BackgroundTaskRegistrationType); AppModelPolicy_Type_ModsPowerNotifification: Result := TypeInfo(TAppModelPolicy_ModsPowerNotifification); else Result := nil; end; end; end.
(*--------------------------------------------------------*) (* Übung 2 (BSP. 1. Spannweitenberechnung) *) (* Entwickler: Neuhold Michael *) (* Datum: 17.10.2018 *) (* Verson: 1.0 *) (* Lösungsidee: Aus mehreren eingegebenen Zahlen *) (* die größtmögliche Range berechnen. *) (*--------------------------------------------------------*) PROGRAM Bereich; VAR min,max,range,value: INTEGER; BEGIN min := 0; max := 0; WriteLn('<#------ RANGE CALCULATOR ------#>'); Writeln('Bitte geben Sie Zahlen ein. (0 = Abbruch)'); Readln(value); IF value > 0 THEN (* 0 = Abbruch *) BEGIN min := value; max := value; REPEAT IF value < min THEN min := value (* new min value *) ELSE IF value > max THEN max := value; (* new max value *) Readln(value) UNTIL value <= 0 (* 0 = Abbruch *) END; range := max - min; Writeln('Die Range beträgt: ',range); END.
unit Adjuster; interface uses Classes, Project; type TBoardItemAdjuster = class protected FProject : TveProject; public // Do Mark before reassigning outlines to components, then do Adjust after. // Reason - some components need altering when an outline type swapped or // assigned after Creation - especially for Sizeable outlines. procedure MarkComponents( Project : TveProject ); procedure AdjustComponents; { constructor Create; destructor Destroy; override; } end; implementation uses Outlines, SizeableOutlines, RadialOutlines; // values for ReservedAdjust integer member of TveBoardItem const // ** VALUES FOR TveBoardItem.ReservedAdjust1 member ** // set to this to mark item as not having a leaded outline // A new Board Item also has value initialised to zero by constructor NON_LEADED_OR_NEW = 0; // set to this to mark item as having a leaded outline LEADED = 1; procedure TBoardItemAdjuster.MarkComponents( Project : TveProject ); //const BoolToLeadedNo : array[boolean] of integer := ( NON_LEADED, LEADED ); var i : integer; Item : TveBoardItem; begin FProject := Project; // record all items which have sizable outlines for i := 0 to Project.BoardItemCount -1 do begin Item := Project.BoardItems[i]; // store value for components which have for leaded or radial outlines. // this value means "I already have a leaded or radial outline" if (Item.Outline is TveLeadedOutline) or (Item.Outline is TveRadialOutline) then begin Item.ReservedAdjust1 := LEADED; end // store value for non-leaded else begin Item.ReservedAdjust1 := NON_LEADED_OR_NEW; end; end; end; procedure TBoardItemAdjuster.AdjustComponents; var i : integer; Item : TveBoardItem; begin for i := 0 to FProject.BoardItemCount -1 do begin Item := FProject.BoardItems[i]; // if item has leaded or radial outline AND (did not have one before or // is new), then its has just received a leaded outline and the // component length needs adjusting if (Item.ReservedAdjust1 = NON_LEADED_OR_NEW) then begin Item.Outline.SetDefaultLength( Item ); end; end; end; end.
unit PImage; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls; type TPImage = class(TImage) private { Private declarations } FAutoRected : Boolean; FPicIsPreDef : Boolean; FPreDefPicFileName : String; FResourceName : string; protected { Protected declarations } procedure SetAutoRected(Value : Boolean); procedure SetPreDefPicFileName(Value : string); procedure SetResourceName(Value : string); procedure WMPaint(var Message: TWMPaint); message WM_PAINT; public { Public declarations } constructor Create(AOwner: TComponent); override; published { Published declarations } property AutoRected : Boolean read FAutoRected write SetAutoRected; property PicIsPreDef : Boolean read FPicIsPreDef write FPicIsPreDef; property Picture stored False; property PreDefPicFileName : string read FPreDefPicFileName write SetPreDefPicFileName; property ResourceName: string read FResourceName write SetResourceName; end; procedure Register; implementation constructor TPImage.Create(AOwner: TComponent); begin inherited; end; procedure TPImage.SetAutoRected(Value : Boolean); begin FAutoRected := Value; if FAutoRected then begin if Width < Height then Height := Width else Width := Height; end; end; procedure TPimage.WMPaint(var Message: TWMPaint); begin inherited; if FAutoRected then begin if Width < Height then Height := Width else Width := Height; end; end; procedure TPImage.SetPreDefPicFileName(Value : string); var tmpPicture: TPicture; tmpBitmap: TBitmap; begin if (Value = '') then begin FPreDefPicFileName := Value; exit; end; if FPreDefPicFileName <> Value then if FileExists(Value) then FPreDefPicFileName := Value; tmpPicture := TPicture.Create; tmpBitmap := TBitmap.Create; if not (csDesigning in ComponentState) then //运行时 begin if FPicIsPreDef = True then //预定义 begin try tmpPicture.Bitmap.LoadFromFile(FPreDefPicFileName); except try tmpPicture.Bitmap.LoadFromResourceName(HInstance,FResourceName); except end; end; end else begin try tmpPicture.Bitmap.LoadFromResourceName(HInstance,FResourceName); except end; end; Picture := tmpPicture; end else //设计时 begin if FPicIsPreDef = True then //预定义 begin if FPreDefPicFileName <> '' then try tmpBitmap.LoadFromFile(FPreDefPicFileName); except showmessage('无法装载位图文件'); end; end; Picture.Bitmap := tmpBitmap; end; tmpPicture.Free; tmpBitmap.Free; end; procedure TPImage.SetResourceName(Value : string); var tmpPicture: TPicture; tmpBitmap: TBitmap; begin FResourceName := Value; tmpPicture := TPicture.Create; tmpBitmap := TBitmap.Create; if not (csDesigning in ComponentState) then //运行时 begin if FPicIsPreDef <> True then //未预定义 begin try tmpPicture.Bitmap.LoadFromResourceName(HInstance,FResourceName); except end; end; Picture := tmpPicture; end; tmpPicture.Free; tmpBitmap.Free; end; procedure Register; begin RegisterComponents('PosControl', [TPImage]); end; end.
unit uOptions; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, ExtCtrls, CheckLst, uMyIniFiles, ActnList, Menus, Registry, StrUtils, Mask, JvExMask, JvToolEdit, SynEdit, SynJass, SynEditTypes, SynEditHighlighter, Grids, ValEdit; type TTemplate = record Text,FileName:String; Title:String; ShortCut:TShortCut; Pos:Integer; end; TOptionsDialog = class(TForm) pctrlOptions: TPageControl; btnOK: TButton; btnCancel: TButton; tsGeneral: TTabSheet; tsEditor: TTabSheet; chkSaveWindowPos: TCheckBox; chkReopenWorkspace: TCheckBox; chkReopenLastFiles: TCheckBox; chkCreateEmpty: TCheckBox; gbGeneral: TGroupBox; chkAutoIndent: TCheckBox; chkGroupUndo: TCheckBox; chkHighlightLine: TCheckBox; chkInsertMode: TCheckBox; chkScrollPastEOF: TCheckBox; chkScrollPastEOL: TCheckBox; chkIndentGuides: TCheckBox; chkSpecialCharacters: TCheckBox; chkTabsToSpaces: TCheckBox; chkWordWrap: TCheckBox; gbGutterMargin: TGroupBox; lblExtraLine: TLabel; Edit2: TEdit; udExtraSpacing: TUpDown; lblInsertCaret: TLabel; cmbInsertCaret: TComboBox; lblOverwriteCaret: TLabel; cmbOverwriteCaret: TComboBox; Edit3: TEdit; udMaxUndo: TUpDown; lblMaxUndo: TLabel; lblTabWidth: TLabel; Edit4: TEdit; udTabWidth: TUpDown; chkShowGutter: TCheckBox; chkShowRightMargin: TCheckBox; chkShowLineNumbers: TCheckBox; chkShowLeadingZeros: TCheckBox; chkZeroStart: TCheckBox; lblRightMarginPos: TLabel; Edit5: TEdit; udRightMargin: TUpDown; lblGutterColor: TLabel; cbGutter: TColorBox; lblFoldingBarColor: TLabel; cbFoldingBar: TColorBox; lblFoldingLinesColor: TLabel; cbFoldingLines: TColorBox; chkHighlightGuides: TCheckBox; btnFont: TButton; chkCodeFolding: TCheckBox; lblFoldingButton: TLabel; cmbFoldingButton: TComboBox; dlgOpen: TOpenDialog; tsKeyboard: TTabSheet; dlgFont: TFontDialog; gbKeyboard: TGroupBox; lblKeyCategories: TLabel; lstKeyCat: TListBox; lstKeyCmd: TListBox; lblKeyCommands: TLabel; lblShortcutKey: TLabel; lblShortCutAssigned: TLabel; lblShortCutAssignedTo: TLabel; btnHelp: TButton; chkOneCopy: TCheckBox; chkCtrl: TCheckBox; chkShift: TCheckBox; chkAlt: TCheckBox; cmbShortCut: TComboBox; tsJass: TTabSheet; chcFuncCase: TCheckBox; GroupBox1: TGroupBox; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; ComboBox1: TComboBox; cmbSSection: TComboBox; clrBack: TColorBox; clrColor: TColorBox; chkBold: TCheckBox; chkItalic: TCheckBox; chkUnderline: TCheckBox; cmbStyle: TComboBox; styleAdd: TButton; styleDelete: TButton; GroupBox2: TGroupBox; Label7: TLabel; btnNFAdd: TButton; btnNFRemove: TButton; chkEnterIndent: TCheckBox; chkVSTheme: TCheckBox; chkParamLight: TCheckBox; lstNatives: TCheckListBox; PageControl1: TPageControl; TabSheet1: TTabSheet; SynDemo: TSynEdit; TabSheet2: TTabSheet; values: TValueListEditor; TabSheet3: TTabSheet; GroupBox3: TGroupBox; GroupBox4: TGroupBox; tmpList: TListBox; Button1: TButton; Button2: TButton; grpFiles: TGroupBox; foJ: TCheckBox; foAI: TCheckBox; foMDL: TCheckBox; tmpData: TSynEdit; tmpTitle: TEdit; Label8: TLabel; Label9: TLabel; tmpShortcut: THotKey; Button3: TButton; procedure FormCreate(Sender: TObject); procedure UpdateTemplates; procedure btnOKClick(Sender: TObject); procedure btnFontClick(Sender: TObject); procedure lstKeyCatClick(Sender: TObject); procedure lstKeyCmdClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure chkCtrlClick(Sender: TObject); procedure chkShiftClick(Sender: TObject); procedure chkAltClick(Sender: TObject); procedure cmbShortCutChange(Sender: TObject); procedure lstKeyCmdDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); procedure cmbSSectionChange(Sender: TObject); procedure chkBoldClick(Sender: TObject); procedure UpdateJASSHighlight; procedure FormShow(Sender: TObject); procedure styleAddClick(Sender: TObject); procedure cmbStyleChange(Sender: TObject); procedure lstNativesClick(Sender: TObject); procedure btnNFAddClick(Sender: TObject); procedure btnNFRemoveClick(Sender: TObject); procedure valuesDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); procedure valuesDblClick(Sender: TObject); procedure tmpListClick(Sender: TObject); procedure tmpDataChange(Sender: TObject); procedure tmpTitleChange(Sender: TObject); procedure tmpShortcutChange(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); private { Private declarations } fSettingsCopy: TMyIniFile; fSettingShortCut: Boolean; Temps: array of TTemplate; procedure SynEditing(Enable: Boolean); procedure ShortcutAssigned; procedure ShortcutChanged; function ShortcutGet: String; public ListCache:TBitmap; JassSyn: TSynEdit_JassSyn; end; var OptionsDialog: TOptionsDialog; CommandNames: TStringList; procedure SaveHighlightStyle(Ini:TMyIniFile; StyleNum:Integer; Style:THighlightStyle); procedure LoadHighlightStyle(Ini:TMyIniFile; StyleNum:Integer; Style:THighlightStyle); implementation uses uMain, IniFiles, uUtils, uFuncInfo, uDocuments; {$R *.dfm} procedure TOptionsDialog.SynEditing(Enable: Boolean); begin cmbStyle.Enabled := Enable; //styleDelete.Enabled := Enable; cmbSSection.Enabled := Enable; clrColor.Enabled := Enable; clrBack.Enabled := Enable; chkBold.Enabled := Enable; chkItalic.Enabled := Enable; chkUnderline.Enabled := Enable; SynDemo.Enabled := Enable; end; procedure TOptionsDialog.UpdateTemplates; var i:Integer; begin tmpList.Items.BeginUpdate; tmpList.Items.Clear; for i := 0 to High(Temps) do tmpList.Items.Add(Temps[i].Title); tmpList.Items.EndUpdate; end; procedure TOptionsDialog.FormCreate(Sender: TObject); var i,c: Integer; TempFileName: String; JassA:THighlightStyle; JassB:THighlightStyle; Temp:TTemplate; sr: TSearchRec; S:TStringList; function FromString(S:String):String; begin Result := AnsiReplaceStr(S, '\r', #13); Result := AnsiReplaceStr(Result, '\n', #10); Result := AnsiReplaceStr(Result, '\"', '"'); Result := AnsiReplaceStr(Result, '\\', '\'); end; begin // Templates S := TStringList.Create; SetLength(Temps, 0); if FindFirst(AppPath+'Scripts\*.jcs', faAnyFile , sr) = 0 then begin repeat S.LoadFromFile(AppPath+'Scripts\'+sr.Name); if (S.Count > 0) and ( S[0] = '//JCSTEMPSYS !Remove this comment if you edit the script') then begin Temp.FileName := AppPath+'Scripts\'+sr.Name; Temp.Title := FromString(Copy(S[4], 28, Length(S[4])-28-15)); Temp.ShortCut := TextToShortCut(Copy(S[5], 26, Length(S[5])-27)); Temp.Text := FromString(Copy(S[10], 20, Length(S[10])-21)); Temp.Pos := StrToInt(Copy(S[11], 43, Length(S[11])-43)); SetLength(Temps, High(Temps)+2); Temps[High(Temps)] := Temp; end; S.Clear; until FindNext(sr) <> 0; FindClose(sr); end; S.Free; UpdateTemplates; TempFileName := PChar(ExtractFilePath(Settings.FileName) + 'SettingsCopy.ini'); CopyFile(PChar(Settings.FileName), PChar(TempFileName), False); fSettingsCopy := TMyIniFile.Create(TempFileName); for i := 0 to values.RowCount-2 do values.ItemProps[i].EditStyle := esEllipsis; with fSettingsCopy do begin // Syntax Highlight JassSyn:= TSynEdit_JassSyn.Create(nil); DocumentFactory.InitJassSynColors(JassSyn); for i := 0 to High(JassSyn.ThemeStr) do begin values.InsertRow(JassSyn.ThemeStr[i], '', True); end; for i := 0 to DocumentFactory.JassSyn.Styles.Count-1 do begin JassA := THighlightStyle(DocumentFactory.JassSyn.Styles[i]); JassB:=THighlightStyle.Create(JassA.Keyword); JassB.Title := JassA.Title; if JassB.Keyword then JassB.Names.Text := JassA.Names.Text; JassSyn.Styles.Add(JassB); cmbSSection.Items.Add(JassB.Title); end; c := ReadInteger('Jass', 'StyleCount', 0); if c = 0 then SynEditing(False) else begin for i := 0 to c-1 do begin cmbStyle.Items.Add(ReadString('JassStyle'+IntToStr(i), 'Title', '')); end; cmbStyle.ItemIndex := ReadInteger('Jass', 'UseStyle', 0); end; JassSyn.AssignStyleTree; JassSyn.LoadSynSettings; SynDemo.Highlighter := JassSyn; cmbStyle.ItemIndex := ReadInteger('Jass', 'UseStyle', 0); // Native Files c := ReadInteger('JassFiles', 'Count', 0); for i := 0 to c-1 do begin lstNatives.Items.Add(ReadString('JassFiles', IntToStr(i), '')); lstNatives.Checked[i] := ReadBool('JassSyn', IntToStr(i), false); end; // File with TRegistry.Create do begin RootKey := HKEY_CLASSES_ROOT; for i := 0 to grpFiles.ControlCount-1 do begin if OpenKey(TCheckbox(grpFiles.Controls[i]).Caption, False) then begin if ReadString('') = 'JassCraft.File' then TCheckbox(grpFiles.Controls[i]).Checked := True else TCheckbox(grpFiles.Controls[i]).Checked := False; end else TCheckbox(grpFiles.Controls[i]).Checked := False; end; Free; end; // Read data chkOneCopy.Checked := ReadBool('General', 'OnlyOneCopy', False); chkSaveWindowPos.Checked := ReadBool('General', 'SaveWindowPosition', False); chkReopenWorkspace.Checked := ReadBool('General', 'ReopenLastWorkspace', False); chkReopenLastFiles.Checked := ReadBool('General', 'ReopenLastFiles', False); chkCreateEmpty.Checked := ReadBool('General', 'CreateEmptyDocument', False); chkVSTheme.Checked := ReadBool('General', 'VSTheme', True); // Editor // Setup controls for i := 8 to 11 do begin cmbInsertCaret.Items.Add(sStrings[i]); cmbOverwriteCaret.Items.Add(sStrings[i]); end; for i := 16 to 17 do cmbFoldingButton.Items.Add(sStrings[i]); // Read data chkAutoIndent.Checked := ReadBool('Editor', 'AutoIndent', False); chkCodeFolding.Checked := ReadBool('Editor', 'CodeFolding', False); chkGroupUndo.Checked := ReadBool('Editor', 'GroupUndo', False); chkHighlightLine.Checked := ReadBool('Editor', 'HighlightActiveLine', False); chkHighlightGuides.Checked := ReadBool('Editor', 'HighlightIndentGuides', False); chkInsertMode.Checked := ReadBool('Editor', 'InsertMode', False); chkScrollPastEOF.Checked := ReadBool('Editor', 'ScrollPastEOF', False); chkScrollPastEOL.Checked := ReadBool('Editor', 'ScrollPastEOL', False); chkIndentGuides.Checked := ReadBool('Editor', 'ShowIndentGuides', False); chkSpecialCharacters.Checked := ReadBool('Editor', 'ShowSpecialCharacters', False); chkTabsToSpaces.Checked := ReadBool('Editor', 'TabsToSpaces', False); chkWordWrap.Checked := ReadBool('Editor', 'WordWrap', False); udExtraSpacing.Position := ReadInteger('Editor', 'ExtraLineSpacing', 0); udMaxUndo.Position := ReadInteger('Editor', 'MaximumUndo', 1024); cmbInsertCaret.ItemIndex := ReadInteger('Editor', 'InsertCaret', 0); cmbOverwriteCaret.ItemIndex := ReadInteger('Editor', 'OverwriteCaret', 0); cmbFoldingButton.ItemIndex := ReadInteger('Editor', 'FoldingButtonStyle', 0); udTabWidth.Position := ReadInteger('Editor', 'TabWidth', 4); dlgFont.Font.Name := ReadString('Editor', 'FontName', ''); dlgFont.Font.Size := ReadInteger('Editor', 'FontSize', 10); btnFont.Caption := Format('Font: %s, %d', [dlgFont.Font.Name, dlgFont.Font.Size]); chkShowGutter.Checked := ReadBool('Editor', 'ShowGutter', False); chkShowRightMargin.Checked := ReadBool('Editor', 'ShowRightMargin', False); chkShowLineNumbers.Checked := ReadBool('Editor', 'ShowLineNumbers', False); chkShowLeadingZeros.Checked := ReadBool('Editor', 'ShowLeadingZeros', False); chkZeroStart.Checked := ReadBool('Editor', 'ZeroStart', False); udRightMargin.Position := ReadInteger('Editor', 'RightMarginPosition', 80); cbGutter.Selected := ReadColor('Editor', 'GutterColor', clBtnFace); cbFoldingBar.Selected := ReadColor('Editor', 'FoldingBarColor', clDefault); cbFoldingLines.Selected := ReadColor('Editor', 'FoldingBarLinesColor', clDefault); // Jass chcFuncCase.Checked := ReadBool('Jass', 'FuncCase', True); chkEnterIndent.Checked := ReadBool('Jass', 'EnterIndent', True); chkParamLight.Checked := ReadBool('Jass', 'ParamLight', True); // Keyboard & Mouse // Setup controls with MainForm.actlMain do begin lstKeyCat.Items.BeginUpdate; try for i := 0 to ActionCount - 1 do if lstKeyCat.Items.IndexOf(Actions[i].Category) = -1 then lstKeyCat.Items.Add(Actions[i].Category); if lstKeyCat.Count > 0 then begin lstKeyCat.ItemIndex := 0; lstKeyCatClick(nil); end; finally lstKeyCat.Items.EndUpdate; end; CommandNames := TStringList.Create; for i := 0 to ActionCount - 1 do CommandNames.Add(Actions[i].Name); CommandNames.Sort; end; end; end; procedure SaveHighlightStyle(Ini:TMyIniFile; StyleNum:Integer; Style:THighlightStyle); begin Ini.WriteColor('JassStyle'+IntToStr(StyleNum), Style.Title+'|BgColor', Style.BgColor); Ini.WriteColor('JassStyle'+IntToStr(StyleNum), Style.Title+'|FrColor', Style.Font.Color); Ini.WriteBool('JassStyle'+IntToStr(StyleNum), Style.Title+'|Bold', fsBold in Style.Font.Style); Ini.WriteBool('JassStyle'+IntToStr(StyleNum), Style.Title+'|Italic', fsItalic in Style.Font.Style); Ini.WriteBool('JassStyle'+IntToStr(StyleNum), Style.Title+'|Underline', fsUnderline in Style.Font.Style); end; procedure LoadHighlightStyle(Ini:TMyIniFile; StyleNum:Integer; Style:THighlightStyle); begin Style.Font.Color := Ini.ReadColor('JassStyle'+IntToStr(StyleNum), Style.Title+'|FrColor', clBlack); Style.BgColor := Ini.ReadColor('JassStyle'+IntToStr(StyleNum), Style.Title+'|BgColor', clWhite); Style.Font.Style := []; if Ini.ReadBool('JassStyle'+IntToStr(StyleNum), Style.Title+'|Bold', false) then Style.Font.Style := Style.Font.Style + [fsBold]; if Ini.ReadBool('JassStyle'+IntToStr(StyleNum), Style.Title+'|Italic', false) then Style.Font.Style := Style.Font.Style + [fsItalic]; if Ini.ReadBool('JassStyle'+IntToStr(StyleNum), Style.Title+'|Underline', false) then Style.Font.Style := Style.Font.Style + [fsUnderline]; end; procedure TOptionsDialog.btnOKClick(Sender: TObject); var i:Integer; S:TStringList; sr:TSearchRec; function ToString(S:String):String; begin Result := AnsiReplaceStr(S, '\', '\\'); Result := AnsiReplaceStr(Result, #13, '\r'); Result := AnsiReplaceStr(Result, #10, '\n'); Result := AnsiReplaceStr(Result, '"', '\"'); end; begin with fSettingsCopy do begin // Templates S := TStringList.Create; if FindFirst(AppPath+'Scripts\*.jcs', faAnyFile , sr) = 0 then begin repeat S.LoadFromFile(AppPath+'Scripts\'+sr.Name); if (S.Count > 0) and ( S[0] = '//JCSTEMPSYS !Remove this comment if you edit the script') then begin DeleteFile(AppPath+'Scripts\'+sr.Name) end; S.Clear; until FindNext(sr) <> 0; FindClose(sr); end; for i := 0 to High(Temps) do begin if Temps[i].FileName = '' then Temps[i].FileName := AppPath+'Scripts\'+Temps[i].Title+'.jcs'; S.Add('//JCSTEMPSYS !Remove this comment if you edit the script'); S.Add('function Init()'); S.Add('{'); S.Add('var int MenuItem'); S.Add('Menu.CreateRoot(MenuItem, "'+ToString(Temps[i].Title)+'", "&Templates")'); S.Add('Menu.Shortcut(MenuItem, "'+ShortcutToText(Temps[i].ShortCut)+'")'); S.Add('Menu.OnClick(MenuItem, Click)'); S.Add('}'); S.Add('function Click()'); S.Add('{'); S.Add('JassCraft.SelText("'+ToString(Temps[i].Text)+'")'); S.Add('JassCraft.SelStart(JassCraft.SelStart(-1)-'+IntToStr(Temps[i].Pos)+')'); S.Add('}'); S.SaveToFile(Temps[i].FileName); S.Clear; end; S.Free; // File Types with TRegistry.Create do begin RootKey := HKEY_CLASSES_ROOT; OpenKey('\JassCraft.File', True); WriteString('', 'JassCraft File'); CloseKey; OpenKey('\JassCraft.File\DefaultIcon', True); WriteString('', '"'+Application.ExeName+'",1'); CloseKey; OpenKey('\JassCraft.File\shell\Open\command', True); WriteString('', '"'+Application.ExeName+'" "%1"'); CloseKey; for i := 0 to grpFiles.ControlCount-1 do begin if TCheckBox(grpFiles.Controls[i]).Checked then begin OpenKey('\'+TCheckBox(grpFiles.Controls[i]).Caption, True); WriteString('', 'JassCraft.File'); CloseKey; end; end; Free; end; // General WriteBool('General', 'OnlyOneCopy', chkOneCopy.Checked); WriteBool('General', 'SaveWindowPosition', chkSaveWindowPos.Checked); WriteBool('General', 'ReopenLastWorkspace', chkReopenWorkspace.Checked); WriteBool('General', 'ReopenLastFiles', chkReopenLastFiles.Checked); WriteBool('General', 'CreateEmptyDocument', chkCreateEmpty.Checked); WriteBool('General', 'VSTheme', chkVSTheme.Checked); // Editor WriteBool('Editor', 'AutoIndent', chkAutoIndent.Checked); WriteBool('Editor', 'CodeFolding', chkCodeFolding.Checked); WriteBool('Editor', 'GroupUndo', chkGroupUndo.Checked); WriteBool('Editor', 'HighlightActiveLine', chkHighlightLine.Checked); WriteBool('Editor', 'HighlightIndentGuides', chkIndentGuides.Checked); WriteBool('Editor', 'InsertMode', chkInsertMode.Checked); WriteBool('Editor', 'ScrollPastEOF', chkScrollPastEOF.Checked); WriteBool('Editor', 'ScrollPastEOL', chkScrollPastEOL.Checked); WriteBool('Editor', 'ShowIndentGuides', chkIndentGuides.Checked); WriteBool('Editor', 'ShowSpecialCharacters', chkSpecialCharacters.Checked); WriteBool('Editor', 'TabsToSpaces', chkTabsToSpaces.Checked); WriteBool('Editor', 'WordWrap', chkWordWrap.Checked); WriteInteger('Editor', 'ExtraLineSpacing', udExtraSpacing.Position); WriteInteger('Editor', 'MaximumUndo', udMaxUndo.Position); WriteInteger('Editor', 'InsertCaret', cmbInsertCaret.ItemIndex); WriteInteger('Editor', 'OverwriteCaret', cmbOverwriteCaret.ItemIndex); WriteInteger('Editor', 'FoldingButtonStyle', cmbFoldingButton.ItemIndex); WriteInteger('Editor', 'TabWidth', udTabWidth.Position); WriteString('Editor', 'FontName', dlgFont.Font.Name); WriteInteger('Editor', 'FontSize', dlgFont.Font.Size); WriteBool('Editor', 'ShowGutter', chkShowGutter.Checked); WriteBool('Editor', 'ShowRightMargin', chkShowRightMargin.Checked); WriteBool('Editor', 'ShowLineNumbers', chkShowLineNumbers.Checked); WriteBool('Editor', 'ShowLeadingZeros', chkShowLeadingZeros.Checked); WriteBool('Editor', 'ZeroStart', chkZeroStart.Checked); WriteInteger('Editor', 'RightMarginPosition', udRightMargin.Position); WriteColor('Editor', 'GutterColor', cbGutter.Selected); WriteColor('Editor', 'FoldingBarColor', cbFoldingBar.Selected); WriteColor('Editor', 'FoldingBarLinesColor', cbFoldingLines.Selected); //Jass WriteBool('Jass', 'FuncCase', chcFuncCase.Checked); WriteBool('Jass', 'ParamLight', chkParamLight.Checked); WriteBool('Jass', 'EnterIndent', chkEnterIndent.Checked); if cmbStyle.ItemIndex <> -1 then WriteInteger('Jass', 'UseStyle', cmbStyle.ItemIndex); // Native Files WriteInteger('JassFiles', 'Count', lstNatives.Items.Count); for i := 0 to lstNatives.Items.Count-1 do begin WriteString('JassFiles', IntToStr(i), lstNatives.Items[i]); WriteBool('JassSyn', IntToStr(i), lstNatives.Checked[i]); end; end; DeleteFile(Settings.FileName); CopyFile(PChar(fSettingsCopy.FileName), PChar(Settings.FileName), False); ModalResult := mrOK; end; procedure TOptionsDialog.btnFontClick(Sender: TObject); begin if dlgFont.Execute then btnFont.Caption := Format('Font: %s, %d', [dlgFont.Font.Name, dlgFont.Font.Size]); end; procedure TOptionsDialog.lstKeyCatClick(Sender: TObject); var i: Integer; Category,s: String; Action:TAction; begin if lstKeyCat.ItemIndex <> -1 then begin lstKeyCmd.Clear; Category := lstKeyCat.Items[lstKeyCat.ItemIndex]; with MainForm.actlMain do for i := 0 to ActionCount - 1 do if SameText(Category, Actions[i].Category) then begin Action := TAction(Actions[i]); if Action.HelpKeyword <> '' then s := Action.HelpKeyword + ' -> ' +Action.Caption else s := Action.Caption; lstKeyCmd.AddItem(s, Action); end; if lstKeyCmd.Count > 0 then begin lstKeyCmd.ItemIndex := 0; lstKeyCmdClick(nil); end; end; end; procedure TOptionsDialog.lstKeyCmdClick(Sender: TObject); var Shortcut: String; P: Integer; begin fSettingShortCut := True; Shortcut := fSettingsCopy.ReadString('Keyboard', TAction(lstKeyCmd.Items.Objects[lstKeyCmd.ItemIndex]).Name, ''); chkCtrl.Checked := Pos('Ctrl', Shortcut) > 0; chkShift.Checked := Pos('Shift', Shortcut) > 0; chkAlt.Checked := Pos('Alt', Shortcut) > 0; repeat P := Pos('+', Shortcut); if P = 0 then cmbShortCut.ItemIndex := cmbShortCut.Items.IndexOf( Copy(Shortcut, 1, MaxInt)) else Delete(Shortcut, 1, P); until P = 0; fSettingShortCut := False; lblShortCutAssignedTo.Caption := ''; end; procedure TOptionsDialog.FormDestroy(Sender: TObject); var i:Integer; begin DeleteFile(fSettingsCopy.FileName); CommandNames.Free; for i := 0 to JassSyn.Styles.Count-1 do begin THighlightStyle(JassSyn.Styles[i]).Free; end; end; procedure TOptionsDialog.btnCancelClick(Sender: TObject); begin DeleteFile(fSettingsCopy.FileName); ModalResult := mrCancel; end; procedure TOptionsDialog.ShortcutAssigned; var i: Integer; Shortcut: String; begin lblShortCutAssignedTo.Caption := ''; if not fSettingShortCut then begin Shortcut := ShortcutGet; with MainForm.actlMain do for i := 0 to ActionCount - 1 do if (TAction(Actions[i]).ShortCut = TextToShortCut(Shortcut)) and (Shortcut <> '') then lblShortCutAssignedTo.Caption := AnsiReplaceStr(TAction(Actions[i]).Caption, '&', ''); end; end; procedure TOptionsDialog.ShortcutChanged; begin if not fSettingShortCut then fSettingsCopy.WriteString('Keyboard', TAction(lstKeyCmd.Items.Objects[lstKeyCmd.ItemIndex]).Name, ShortcutGet); end; function TOptionsDialog.ShortcutGet: String; begin if chkCtrl.Checked then Result := 'Ctrl+'; if chkShift.Checked then Result := Result + 'Shift+'; if chkAlt.Checked then Result := Result + 'Alt+'; if cmbShortCut.Items[cmbShortCut.ItemIndex] <> '' then Result := Result + cmbShortCut.Items[cmbShortCut.ItemIndex] else Result := ''; end; procedure TOptionsDialog.chkCtrlClick(Sender: TObject); begin ShortcutAssigned; ShortcutChanged; end; procedure TOptionsDialog.chkShiftClick(Sender: TObject); begin ShortcutAssigned; ShortcutChanged; end; procedure TOptionsDialog.chkAltClick(Sender: TObject); begin ShortcutAssigned; ShortcutChanged; end; procedure TOptionsDialog.cmbShortCutChange(Sender: TObject); begin ShortcutAssigned; ShortcutChanged; end; procedure TOptionsDialog.lstKeyCmdDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); var i:Integer; Text:String; Action:TAction; Icon:TIcon; function CalcColorIndex(StartColor, EndColor: TColor; Steps, ColorIndex: Integer): TColor; var BeginRGBValue: Array[0..2] of Byte; RGBDifference: Array[0..2] of Integer; Red, Green, Blue: Byte; NumColors: Integer; begin if (ColorIndex < 1) or (ColorIndex > Steps) then raise ERangeError.Create('ColorIndex can''t be less than 1 or greater than ' + IntToStr(Steps)); NumColors := Steps; Dec(ColorIndex); BeginRGBValue[0] := GetRValue(ColorToRGB(StartColor)); BeginRGBValue[1] := GetGValue(ColorToRGB(StartColor)); BeginRGBValue[2] := GetBValue(ColorToRGB(StartColor)); RGBDifference[0] := GetRValue(ColorToRGB(EndColor)) - BeginRGBValue[0]; RGBDifference[1] := GetGValue(ColorToRGB(EndColor)) - BeginRGBValue[1]; RGBDifference[2] := GetBValue(ColorToRGB(EndColor)) - BeginRGBValue[2]; // Calculate the bands color Red := BeginRGBValue[0] + MulDiv(ColorIndex, RGBDifference[0], NumColors - 1); Green := BeginRGBValue[1] + MulDiv(ColorIndex, RGBDifference[1], NumColors - 1); Blue := BeginRGBValue[2] + MulDiv(ColorIndex, RGBDifference[2], NumColors - 1); Result := RGB(Red, Green, Blue); end; begin with lstKeyCmd.Canvas do begin Text := lstKeyCmd.Items[Index]; if (ListCache = nil) then begin ListCache := TBitmap.Create; ListCache.Height := 22; ListCache.Width := 25; for i := 0 to 25 do begin ListCache.Canvas.Pen.Color := CalcColorIndex($fbfefe, $acc3c4, 26, i+1); ListCache.Canvas.MoveTo(i, 0); ListCache.Canvas.LineTo(i, ListCache.Height+1); end; end; Draw(0,Rect.Top, ListCache); Font.Color := clBlack; if odSelected in State then begin Pen.Color := $c56a31; Brush.Color := $eed2c1; Rectangle(Rect); end else begin Pen.Color := clWhite; Brush.Color := clWhite; Rect.Left := 25; FillRect(Rect); end; if Pos('&', Text) <> 0 then Delete(Text, Pos('&', Text), 1); TextOut(30, Rect.Top+5, Text); Action := TAction(lstKeyCmd.Items.Objects[Index]); if (Action.ImageIndex <> -1) and Assigned(Action.ActionList.Images) then if Action.ImageIndex < Action.ActionList.Images.Count then begin Icon := TIcon.Create; Action.ActionList.Images.GetIcon(Action.ImageIndex, Icon); Draw(4,Rect.Top+3, Icon); Icon.Free; end; Font.Color := $00000000; Brush.Color := $00000000; TextOut(0,0,''); end; end; procedure TOptionsDialog.cmbSSectionChange(Sender: TObject); var Att:THighlightStyle; begin if cmbSSection.ItemIndex = -1 then Exit; Att := THighlightStyle(JassSyn.Styles[cmbSSection.ItemIndex]); clrBack.Selected := Att.BgColor; clrColor.Selected := Att.Font.Color; chkBold.Checked := fsBold in Att.Font.Style; chkItalic.Checked := fsItalic in Att.Font.Style; chkUnderline.Checked := fsUnderline in Att.Font.Style; end; procedure TOptionsDialog.UpdateJASSHighlight; var Att:THighlightStyle; begin if cmbSSection.ItemIndex = -1 then Exit; if cmbStyle.ItemIndex = -1 then Exit; Att := THighlightStyle(JassSyn.Styles[cmbSSection.ItemIndex]); Att.Font.Style := []; if chkBold.Checked then Att.Font.Style := [fsBold] + Att.Font.Style; if chkItalic.Checked then Att.Font.Style := [fsItalic] + Att.Font.Style; if chkUnderline.Checked then Att.Font.Style := [fsUnderline] + Att.Font.Style; Att.Font.Color := clrColor.Selected; Att.BgColor := clrBack.Selected; fSettingsCopy.WriteColor('JassStyle'+IntToStr(cmbStyle.ItemIndex), Att.Title+'|BgColor', Att.BgColor); fSettingsCopy.WriteColor('JassStyle'+IntToStr(cmbStyle.ItemIndex), Att.Title+'|FrColor', Att.Font.Color); fSettingsCopy.WriteBool('JassStyle'+IntToStr(cmbStyle.ItemIndex), Att.Title+'|Bold', fsBold in Att.Font.Style); fSettingsCopy.WriteBool('JassStyle'+IntToStr(cmbStyle.ItemIndex), Att.Title+'|Italic', fsItalic in Att.Font.Style); fSettingsCopy.WriteBool('JassStyle'+IntToStr(cmbStyle.ItemIndex), Att.Title+'|Underline', fsUnderline in Att.Font.Style); JassSyn.LoadSynSettings; JassSyn.ApplyTheme(SynDemo); end; procedure TOptionsDialog.chkBoldClick(Sender: TObject); begin UpdateJASSHighlight; end; procedure TOptionsDialog.FormShow(Sender: TObject); begin cmbStyleChange(nil); if tmpList.Items.Count > 0 then tmpList.ItemIndex := 0; tmpListClick(nil); end; procedure TOptionsDialog.styleAddClick(Sender: TObject); var s:String; begin s := InputBox('Create Style', 'Name of the style:', ''); if s = '' then Exit; fSettingsCopy.WriteString('JassStyle'+InttoStr(cmbStyle.Items.Count),'Title', s); cmbStyle.Items.Add(s); fSettingsCopy.WriteInteger('Jass', 'StyleCount', cmbStyle.Items.Count); cmbStyle.ItemIndex := cmbStyle.Items.Count-1; SynEditing(True); end; procedure TOptionsDialog.cmbStyleChange(Sender: TObject); var i:Integer; begin if cmbStyle.ItemIndex = -1 then Exit; for i := 0 to High(JassSyn.Theme) do begin JassSyn.Theme[i] := Settings.ReadColor('JassStyle'+IntToStr(cmbStyle.ItemIndex), JassSyn.ThemeStr[i], clWhite); values.ItemProps[i].EditMask := ColorToString(JassSyn.Theme[i]); end; for i := 0 to JassSyn.Styles.Count-1 do begin LoadHighlightStyle(fSettingsCopy, cmbStyle.ItemIndex, THighlightStyle(JassSyn.Styles[i])); end; cmbSSection.ItemIndex := 0; cmbSSectionChange(nil); JassSyn.LoadSynSettings; JassSyn.ApplyTheme(SynDemo); end; procedure TOptionsDialog.lstNativesClick(Sender: TObject); begin btnNFRemove.Enabled := (lstNatives.ItemIndex <> -1); end; procedure TOptionsDialog.btnNFAddClick(Sender: TObject); begin if dlgOpen.Execute then begin if ExtractFilePath(dlgOpen.FileName) = AppPath then lstNatives.Items.Add(ExtractFileName(dlgOpen.FileName)) else lstNatives.Items.Add(dlgOpen.FileName); end; end; procedure TOptionsDialog.btnNFRemoveClick(Sender: TObject); begin if lstNatives.ItemIndex <> -1 then lstNatives.Items.Delete(lstNatives.ItemIndex); end; procedure TOptionsDialog.valuesDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); begin if (ACol = 1) and (ARow <> 0) then with values.Canvas do begin Brush.Color := JassSyn.Theme[ARow-1]; if values.Selection.Top = ARow then Rectangle(Rect) else FillRect(Rect); end; end; procedure TOptionsDialog.valuesDblClick(Sender: TObject); begin with TColorDialog.Create(nil) do begin Color := StringToColor(values.ItemProps[values.Selection.Top-1].EditMask); if Execute then begin values.ItemProps[values.Selection.Top-1].EditMask := ColorToString(Color); JassSyn.Theme[values.Selection.Top-1] := Color; fSettingsCopy.WriteColor('JassStyle'+IntToStr(cmbStyle.ItemIndex), JassSyn.ThemeStr[values.Selection.Top-1], Color); JassSyn.ApplyTheme(SynDemo); end; Free; end; end; procedure TOptionsDialog.tmpListClick(Sender: TObject); begin tmpData.Text := Temps[tmpList.ItemIndex].Text; tmpTitle.Text := Temps[tmpList.ItemIndex].Title; tmpShortcut.HotKey := Temps[tmpList.ItemIndex].ShortCut; tmpData.SelStart := Length(tmpData.Text)-Temps[tmpList.ItemIndex].Pos; tmpData.SelLength := 0; if tmpData.CanFocus then tmpData.SetFocus; end; procedure TOptionsDialog.tmpDataChange(Sender: TObject); begin if tmpList.ItemIndex = -1 then Exit; Temps[tmpList.ItemIndex].Text := tmpData.Text; end; procedure TOptionsDialog.tmpTitleChange(Sender: TObject); begin if tmpList.ItemIndex = -1 then Exit; Temps[tmpList.ItemIndex].Title := tmpTitle.Text; end; procedure TOptionsDialog.tmpShortcutChange(Sender: TObject); begin if tmpList.ItemIndex = -1 then Exit; Temps[tmpList.ItemIndex].ShortCut := tmpShortcut.HotKey; end; procedure TOptionsDialog.Button1Click(Sender: TObject); var Temp:TTemplate; begin Temp.Title := InputBox('JassCraft', 'Enter template name:', ''); if Temp.Title = '' then Exit; SetLength(Temps, High(Temps)+2); Temps[High(Temps)] := Temp; UpdateTemplates; end; procedure TOptionsDialog.Button2Click(Sender: TObject); var i:Integer; begin for i := tmpList.ItemIndex+1 to High(Temps) do Temps[i-1] := Temps[i]; SetLength(Temps, High(Temps)); UpdateTemplates; end; procedure TOptionsDialog.Button3Click(Sender: TObject); begin Temps[tmpList.ItemIndex].Pos := Length(tmpData.Text)-tmpData.SelStart; end; end.
unit Localize; interface uses AvL; type TLocalizeStringID = (lsSetupCaption, lsUninstallCaption, lsBtnPrev, lsBtnNext, lsBtnCancel, lsBtnFinish, lsWelcomeText, lsWelcomeHeaderCaption, lsWelcomeHeaderText, lsWelcomeBtnNext, lsUninstallWelcomeText, lsUninstallWelcomeHeaderCaption, lsUninstallWelcomeHeaderText, lsUninstallWelcomeBtnNext, lsInstallPathHeaderCaption, lsInstallPathHeaderText, lsInstallPathText, lsInstallPathBrowse, lsInstallPathBrowseTitle, lsShortcutsPathHeaderCaption, lsShortcutsPathHeaderText, lsShortcutsPathCreateShortcuts, lsShortcutsPathCreateOnDesktop, lsProgressHeaderCaption, lsProgressHeaderText, lsUninstallProgressHeaderCaption, lsUninstallProgressHeaderText, lsFinishHeaderCaption, lsFinishHeaderText, lsUninstallFinishHeaderCaption, lsUninstallFinishHeaderText, lsFinishLeftoverLabel); //TODO: Rename lsUninstall* to ls* on uninstaller script generation const UninstallRenames: array[0..8] of record Old, New: TLocalizeStringID end = ( (Old: lsUninstallCaption; New: lsSetupCaption), (Old: lsUninstallWelcomeText; New: lsWelcomeText), (Old: lsUninstallWelcomeHeaderCaption; New: lsWelcomeHeaderCaption), (Old: lsUninstallWelcomeHeaderText; New: lsWelcomeHeaderText), (Old: lsUninstallWelcomeBtnNext; New: lsWelcomeBtnNext), (Old: lsUninstallProgressHeaderCaption; New: lsProgressHeaderCaption), (Old: lsUninstallProgressHeaderText; New: lsProgressHeaderText), (Old: lsUninstallFinishHeaderCaption; New: lsFinishHeaderCaption), (Old: lsUninstallFinishHeaderText; New: lsFinishHeaderText)); function L(ID: TLocalizeStringID): string; implementation uses Setup, SetupScript, SetupUtils; const DefLocalization: array[TLocalizeStringID] of string = ( '%ProgramName% %ProgramVer% Setup', 'Uninstall %ProgramName% %ProgramVer%', '< Back', 'Next >', 'Cancel', 'Finish', 'This program will install %ProgramName% %ProgramVer% to your computer', 'Welcome', '%ProgramName% setup', 'Next >', 'This program will uninstall %ProgramName% %ProgramVer% from your computer', 'Welcome', 'Uninstall %ProgramName%', 'Uninstall', 'Install path', 'Select install path', '%InstallSize% of space needed', 'Browse...', 'Select destination directory', 'Shortcuts', 'Configure shortcuts', 'Create shortcuts', 'Create shortcut on desktop', 'Install', 'Installing %ProgramName%...', 'Uninstall', 'Uninstalling %ProgramName%...', 'Finish', '%ProgramName% successfully installed', 'Finish', '%ProgramName% successfully uninstalled', 'Delete leftovers:' ); function L(ID: TLocalizeStringID): string; begin Result := SubstituteMacro(Script[SSLanguage, IntToStr(Ord(ID)), DefLocalization[ID]]); end; end.
unit mnResStrsC; interface resourcestring {$IFDEF MN_CHINESE} // in mnDateRange SCustom = '自定义范围'; SToday = '本日'; SThisWeek = '本周'; SThisMonth = '本月'; SThisQuarter = '本季度'; SThisYear = '本年'; SYesterday = '上日'; SLastWeek = '上周'; SLastMonth = '上月'; SLastQuarter = '上季度'; SLastYear = '上年'; SLatest7Days = '之前7日'; SLatest1Month = '之前1月'; SLatest3Months = '之前3月'; SLatest12Months = '之前12月'; SSoFarThisWeek = '本周至今'; SSoFarThisMonth = '本月至今'; SSoFarThisQuarter = '本季度至今'; SSoFarThisYear = '本年至今'; SFromDateEditNotAssigned = 'FromDateEdit没有设置'; SToDateEditNotAssigned = 'ToDateEdit没有设置'; // in mnWaitDialog SDefaultWaitDialogCaption = 'WaitDialog'; SDefaultWaitDialogPrompt = '请等待...'; SDefaultMsgConfirmCancel = '确认取消吗?'; SDefaultMsgCancelled = '对话框已被取消'; SShowVisibleWaitDialog = '尝试显示一个可见的WaitDialog'; SCloseInvisibleWaitDialog = '尝试关闭一个不可见的WaitDialog'; SChangeHasGaugeWhenVisible = '当WaitDialog可见时,不能改变HasGauge属性'; SChangeCanCancelWhenVisible = '当WaitDialog可见时,不能改变CanCancel属性'; {$ELSE} // in mnDateRange SCustom = 'Custom'; SToday = 'Today'; SThisWeek = 'This Week'; SThisMonth = 'This Month'; SThisQuarter = 'This Quarter'; SThisYear = 'This Year'; SYesterday = 'Yesterday'; SLastWeek = 'Last Week'; SLastMonth = 'Last Month'; SLastQuarter = 'Last Quarter'; SLastYear = 'Last Year'; SLatest7Days = 'Latest 7 Days'; SLatest1Month = 'Latest 1 Month'; SLatest3Months = 'Latest 3 Months'; SLatest12Months = 'Latest 12 Months'; SSoFarThisWeek = 'So Far This Week'; SSoFarThisMonth = 'So Far This Month'; SSoFarThisQuarter = 'So Far This Quarter'; SSoFarThisYear = 'So Far This Year'; SFromDateEditNotAssigned = 'FromDateEdit not assigned'; SToDateEditNotAssigned = 'ToDateEdit not assigned'; // in mnWaitDialog SDefaultWaitDialogCaption = 'WaitDialog'; SDefaultWaitDialogPrompt = 'Please wait...'; SDefaultMsgConfirmCancel = 'Confirm to cancel?'; SDefaultMsgCancelled = 'Dialog has been cancelled'; SShowVisibleWaitDialog = 'Try to show a visible WaitDialog'; SCloseInvisibleWaitDialog = 'Try to close an invisible WaitDialog'; SChangeHasGaugeWhenVisible = 'Can''t change HasGauge property when WaitDialog is visible'; SChangeCanCancelWhenVisible = 'Can''t change CanCancel property when WaitDialog is visible'; {$ENDIF} const SDateRangeTexts: array [0..18] of string = ( SCustom, SToday, SThisWeek, SThisMonth, SThisQuarter, SThisYear, SYesterday, SLastWeek, SLastMonth, SLastQuarter, SLastYear, SLatest7Days, SLatest1Month, SLatest3Months, SLatest12Months, SSoFarThisWeek, SSoFarThisMonth, SSoFarThisQuarter, SSoFarThisYear); implementation end.
unit uUtility; interface uses Windows, StrUtils, SysUtils, Classes; function CStrLen( CString : PAnsiChar ) : NativeUInt; procedure CStrShrink( CString : AnsiString ); procedure CStrCopy( Dest : PAnsiChar; Source : PAnsiChar; MaxLen : integer ); function SplitStrings( const Source : PAnsiChar; Size : NativeUInt; const Strings : TStrings ) : NativeUInt; var IsWin64 : boolean; implementation function IsWin64Func : boolean; var Kernel32Handle : THandle; IsWow64Process : function( Handle : Windows.THandle; var Res : Windows.BOOL ) : Windows.BOOL; stdcall; GetNativeSystemInfo : procedure( var lpSystemInfo : TSystemInfo ); stdcall; isWoW64 : BOOL; SystemInfo : TSystemInfo; const PROCESSOR_ARCHITECTURE_AMD64 = 9; PROCESSOR_ARCHITECTURE_IA64 = 6; begin Kernel32Handle := GetModuleHandle( 'KERNEL32.DLL' ); if Kernel32Handle = 0 then Kernel32Handle := LoadLibrary( 'KERNEL32.DLL' ); if Kernel32Handle <> 0 then begin IsWow64Process := GetProcAddress( Kernel32Handle, 'IsWow64Process' ); GetNativeSystemInfo := GetProcAddress( Kernel32Handle, 'GetNativeSystemInfo' ); if Assigned( IsWow64Process ) then begin IsWow64Process( GetCurrentProcess, isWoW64 ); Result := isWoW64 and Assigned( GetNativeSystemInfo ); if Result then begin GetNativeSystemInfo( SystemInfo ); Result := ( SystemInfo.wProcessorArchitecture = PROCESSOR_ARCHITECTURE_AMD64 ) or ( SystemInfo.wProcessorArchitecture = PROCESSOR_ARCHITECTURE_IA64 ); end; end else Result := FALSE; end else Result := FALSE; end; procedure CStrCopy( Dest : PAnsiChar; Source : PAnsiChar; MaxLen : integer ); var Count : integer; begin if Source = nil then begin Dest[ 0 ] := #0; Exit; end; Count := CStrLen( Source ); if Count < MaxLen then begin CopyMemory( Dest, Source, Count + 1 ); // include last NULL char end else begin Count := MaxLen - 1; CopyMemory( Dest, Source, Count ); // include last NULL char Dest[ MaxLen - 1 ] := #0; end; end; procedure CStrShrink( CString : AnsiString ); begin SetLength( CString, CStrLen( PAnsiChar( @CString[ 1 ] ) ) ); end; // Return the length of the null-terminated string STR. Scan for // the null terminator quickly by testing four bytes at a time. function CStrLen( CString : PAnsiChar ) : NativeUInt; var AnsiCharPtr : PAnsiChar; NativePtr : PNativeUInt; Native : NativeUInt; HiMagic : NativeUInt; LoMagic : NativeUInt; MagicBits : NativeUInt; begin if CString = nil then Exit( 0 ); // Handle the first few characters by reading one character at a time. // Do this until CStr is aligned on a longword boundary. AnsiCharPtr := CString; while NativeUInt( AnsiCharPtr ) and ( sizeof( NativeUInt ) - 1 ) <> 0 do begin Inc( AnsiCharPtr ); if AnsiCharPtr^ = #0 then begin Result := NativeUInt( AnsiCharPtr ) - NativeUInt( CString ); Exit; end; end; // All these elucidatory comments refer to 4-byte longwords, // but the theory applies equally well to 8-byte longwords. NativePtr := PNativeUInt( AnsiCharPtr ); (* Bits 31, 24, 16, and 8 of this number are zero. Call these bits the "holes." Note that there is a hole just to the left of each byte, with an extra at the end: bits: 01111110 11111110 11111110 11111111 bytes: AAAAAAAA BBBBBBBB CCCCCCCC DDDDDDDD The 1-bits make sure that carries propagate to the next 0-bit. The 0-bits provide holes for carries to fall into. *) // 64-bit version of the magic. if sizeof( Native ) > 4 then begin MagicBits := $7EFEFEFEFEFEFEFF; HiMagic := $8080808080808080; LoMagic := $0101010101010101; end else begin MagicBits := $7EFEFEFF; HiMagic := $80808080; LoMagic := $01010101; end; (* We tentatively exit the loop if adding MAGIC_BITS to LONGWORD fails to change any of the hole bits of LONGWORD. 1) Is this safe? Will it catch all the zero bytes? Suppose there is a byte with all zeros. Any carry bits propagating from its left will fall into the hole at its least significant bit and stop. Since there will be no carry from its most significant bit, the LSB of the byte to the left will be unchanged, and the zero will be detected. 2) Is this worthwhile? Will it ignore everything except zero bytes? Suppose every byte of LONGWORD has a bit set somewhere. There will be a carry into bit 8. If bit 8 is set, this will carry into bit 16. If bit 8 is clear, one of bits 9-15 must be set, so there will be a carry into bit 16. Similarly, there will be a carry into bit 24. If one of bits 24-30 is set, there will be a carry into bit 31, so all of the hole bits will be changed. The one misfire occurs when bits 24-30 are clear and bit 31 is set; in this case, the hole at bit 31 is not changed. If we had access to the processor carry flag, we could close this loophole by putting the fourth hole at bit 32! So it ignores everything except 128's, when they're aligned properly. *) // Instead of the traditional loop which tests each character, // we will test a longword at a time. The tricky part is testing // if *any of the four* bytes in the longword in question are zero. while TRUE do begin Native := NativePtr^; Inc( NativePtr ); // Value = ( Native - LoMagic ) and HiMagic, if Value <> 0 then // We have NUL or a non-ASCII char > 127 // $BABA0042 - #01010101 --> $B9B8FF41 and $80808080 --> // $80808000, Value = Value and not Native $80808000 and $4545FFBD --> // $00008000 // ** if ( ( Native - LoMagic ) and HiMagic and not Native ) <> 0 then begin Dec( NativePtr ); // Which of the bytes was the zero? AnsiCharPtr := PAnsiChar( NativePtr ); if AnsiCharPtr[ 0 ] = #0 then begin Result := NativeUInt( AnsiCharPtr ) - NativeUInt( CString ); Exit; end; if AnsiCharPtr[ 1 ] = #0 then begin Result := NativeUInt( AnsiCharPtr ) - NativeUInt( CString ) + 1; Exit; end; if AnsiCharPtr[ 2 ] = #0 then begin Result := NativeUInt( AnsiCharPtr ) - NativeUInt( CString ) + 2; Exit; end; if AnsiCharPtr[ 3 ] = #0 then begin Result := NativeUInt( AnsiCharPtr ) - NativeUInt( CString ) + 3; Exit; end; if sizeof( Native ) > 4 then begin if AnsiCharPtr[ 4 ] = #0 then begin Result := NativeUInt( AnsiCharPtr ) - NativeUInt( CString ) + 4; Exit; end; if AnsiCharPtr[ 5 ] = #0 then begin Result := NativeUInt( AnsiCharPtr ) - NativeUInt( CString ) + 5; Exit; end; if AnsiCharPtr[ 7 ] = #0 then begin Result := NativeUInt( AnsiCharPtr ) - NativeUInt( CString ) + 6; Exit; end; if AnsiCharPtr[ 7 ] = #0 then begin Result := NativeUInt( AnsiCharPtr ) - NativeUInt( CString ) + 7; Exit; end; end; end; end; end; // On Windows, the default LineBreak value is // a carriage return and line feed combination (#13#10) // whereas on Mac OS X, it is just a line feed (#10). function SplitStrings( const Source : PAnsiChar; Size : NativeUInt; const Strings : TStrings ) : NativeUInt; var AString : AnsiString; FirstCharIndex : NativeUInt; LineBreakIndex : NativeUInt; begin LineBreakIndex := 0; FirstCharIndex := 0; while TRUE do begin // -----------| --------- Size -------- | Dummy | // -------- LineBreakIndex| | | // [ ------- ][ ABCD#1x#1x][00][ ...... ][00][xx] : return LineBreakIndex // [ ------- ][ ABCDEFG#1x][00][ ...... ][00][xx] : return LineBreakIndex // [ ------- ][ ABCDEFGHIJ][00][ ...... ][00][xx] : return LineBreakIndex // [ ------- ][ --------------ABCD#1x#1x][00][xx] : return LineBreakIndex // [ ------- ][ --------------ABCDEFG#1x][00][xx] : return LineBreakIndex // -----------------------|FirstCharIndex // [ ------- ][ ABCD#1x#1xABCDEFGHIJKLMN][00][xx] : return FirstCharIndex // -----------| --------- size -------- | // --------------------- LineBreakIndex | if Source[ LineBreakIndex ] = #00 then begin Result := LineBreakIndex; // assume all chars are handled if ( FirstCharIndex < LineBreakIndex ) then // remaining some chars begin if ( LineBreakIndex = Size ) then Result := FirstCharIndex // to be buffered < Size - FirstCharIndex > else begin // Incomplete string, Append $13#10 for Last String SetString( AString, Source + FirstCharIndex, LineBreakIndex - FirstCharIndex ); Strings.Add( AString ); end; end; Exit; if ( FirstCharIndex < LineBreakIndex ) and ( LineBreakIndex < Size ) then begin SetString( AString, Source + FirstCharIndex, LineBreakIndex - FirstCharIndex ); Strings.Add( AString ); end; if ( FirstCharIndex < LineBreakIndex ) and ( LineBreakIndex = Size ) then Result := FirstCharIndex // to be buffered else Result := LineBreakIndex; Exit; end; // #10 : #XX if Source[ LineBreakIndex ] = #10 then begin SetString( AString, Source + FirstCharIndex, LineBreakIndex - FirstCharIndex ); Strings.Add( AString ); Inc( LineBreakIndex ); if Source[ LineBreakIndex ] = #13 then Inc( LineBreakIndex ); FirstCharIndex := LineBreakIndex; continue; end; // #13 : #XX if Source[ LineBreakIndex ] = #13 then begin SetString( AString, Source + FirstCharIndex, LineBreakIndex - FirstCharIndex ); Strings.Add( AString ); Inc( LineBreakIndex ); if Source[ LineBreakIndex ] = #10 then Inc( LineBreakIndex ); FirstCharIndex := LineBreakIndex; continue; end; Inc( LineBreakIndex ); end; end; initialization IsWin64 := IsWin64Func( ); end.
unit CrewEndpoint; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Crew; type ICrewEndpoint = interface(IInterface) ['{8EE44A68-4366-4298-B89A-96C76FD1B80E}'] function All: ICrewList; function One(const Id: string): ICrew; end; function NewCrewEndpoint: ICrewEndpoint; implementation uses Endpoint_Helper; const Endpoint = 'crew/'; type { TCrewEndpoint } TCrewEndpoint = class(TInterfacedObject, ICrewEndpoint) function All: ICrewList; function One(const Id: string): ICrew; end; function NewCrewEndpoint: ICrewEndpoint; begin Result := TCrewEndpoint.Create; end; { TCrewEndpoint } function TCrewEndpoint.All: ICrewList; begin Result := NewCrewList; EndpointToModel(Endpoint, Result); end; function TCrewEndpoint.One(const Id: string): ICrew; begin Result := NewCrew; EndpointToModel(SysUtils.ConcatPaths([Endpoint, Id]), Result); end; end.
unit ObjectMovingBalls; { Copyright (c) 2014 George Wright Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License, as described at http://www.apache.org/licenses/ and http://www.pp4s.co.uk/licenses/ } interface uses System.Types, SmartCL.System, SmartCL.Components, SmartCL.Application, SmartCL.Game, SmartCL.GameApp, SmartCL.Graphics; type TBall = class(TObject) private x, y, width, height : float; colour : string; Speed : integer; public constructor create(newX, newY, newHeight, newWidth: float; newColour: string; newSpeed : integer); procedure move; end; type TCanvasProject = class(TW3CustomGameApplication) private { Private fields and methods } i : integer; protected procedure ApplicationStarting; override; procedure ApplicationClosing; override; procedure PaintView(Canvas: TW3Canvas); override; end; const DELAY = 50; var Ball : array [0..6] of TBall; Timer : integer; implementation constructor TBall.create(newX, newY, newHeight, newWidth : float; newColour : string; newSpeed : integer); begin x := newX; y := newY; height := newHeight; width := newWidth; colour := newColour; speed := newSpeed; end; procedure TBall.move; begin if (x < 300 - width) and (y <= 0) then x += speed; if (x >= 300 - width) and (y < 300 - height) then y += speed; if (x > 0) and (y >= 300 - height) then x -= speed; if (y > 0) and (x <= 0) then y -= speed; if x > 300 - width then x := 300 - width; if x < 0 then x := 0; if y < 0 then y := 0; if y > 300 - height then y := 300 - height; end; { TCanvasProject } procedure TCanvasProject.ApplicationStarting; begin inherited; GameView.Delay := 20; Timer := 0; //newX, newY, newHeight, newWidth, newColour, newSpeed Ball[0] := TBall.create(- DELAY, 0, DELAY - 10, DELAY - 10, 'red', 1); Ball[1] := TBall.create(- DELAY * 2, 0, DELAY - 10, DELAY - 10, 'orange', 2); Ball[2] := TBall.create(- DELAY * 3, 0, DELAY - 10, DELAY - 10, 'yellow', 3); Ball[3] := TBall.create(- DELAY * 4, 0, DELAY - 10, DELAY - 10, 'green', 4); Ball[4] := TBall.create(- DELAY * 5, 0, DELAY - 10, DELAY - 10, 'blue', 5); Ball[5] := TBall.create(- DELAY * 6, 0, DELAY - 10, DELAY - 10, 'purple', 6); Ball[6] := TBall.create(- DELAY * 7, 0, DELAY - 10, DELAY - 10, 'rgb(153, 50, 204)', 7); GameView.StartSession(True); end; procedure TCanvasProject.ApplicationClosing; begin GameView.EndSession; inherited; end; // Note: In a real live game you would try to cache as much // info as you can. Typical tricks are: // 1: Only get the width/height when resized // 2: Pre-calculate strings, especially RGB/RGBA values // 3: Only redraw what has changed, avoid a full repaint // The code below is just to get you started procedure TCanvasProject.PaintView(Canvas: TW3Canvas); begin if Timer = 0 then begin // Clear background Canvas.FillStyle := 'white'; Canvas.FillRectF(0, 0, GameView.Width, GameView.Height); end; while i <= 6 do begin Canvas.FillStyle := (Ball[i].colour); Canvas.BeginPath; Canvas.Ellipse(Ball[i].x, Ball[i].y, Ball[i].x + Ball[i].width, Ball[i].y + Ball[i].height); Canvas.ClosePath; Canvas.Fill; Ball[i].move; inc(i); end; i := 0; Timer += 1; end; end.
unit Iterator.Util.Utils; interface type TUtils = class public class function IIF(AExpression: Boolean; AValue1, AValue2: Variant) : Variant; end; implementation { TUtils } class function TUtils.IIF(AExpression: Boolean; AValue1, AValue2: Variant): Variant; begin if AExpression then Result := AValue1 else Result := AValue2; end; end.
unit colour; {$mode objfpc}{$H+} interface uses Classes, SysUtils, props; type TColour = class private _red, _green, _blue: single; public constructor Create; constructor Create(r, g, b: single); class function GetDescription(colour: TColour): string; property Red: single read _red write _red; property Green: single read _green write _green; property Blue: single read _blue write _blue; end; TColourProperty = specialize TValueProperty<TColour>; implementation constructor TColour.Create; begin _red := 1.0; _green := 1.0; _blue := 1.0; end; constructor TColour.Create(r, g, b: single); begin _red := r; _green := g; _blue := b; end; class function TColour.GetDescription(colour: TColour): string; begin result := Format('%1.2f %1.2f %1.2f', [colour.Red, colour.Green, colour.Blue]); end; end.
unit ReferenceFormRecordViewModelMapper; interface uses CardFormViewModel, ReferenceFormRecordViewModel; type IReferenceFormRecordViewModelMapper = interface function MapReferenceFormRecordViewModelFrom( CardFormViewModel: TCardFormViewModel; const CanBeChanged: Boolean = True; const CanBeRemoved: Boolean = True ): TReferenceFormRecordViewModel; end; implementation end.
unit Displayer; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ToolWin, ComCtrls, uCEFWinControl, uCEFChromiumWindow, uCEFTypes, uCEFChromium, uCEFWindowParent, ExtCtrls; type TDisplayForm = class(TForm) ChromiumWindow: TChromiumWindow; Timer1: TTimer; procedure FormShow(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure ChromiumWindowAfterCreated(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure ChromiumWindowBeforeClose(Sender: TObject); private { Private declarations } FHTMLSource : ustring; FCanClose : boolean; FClosing : boolean; public { Public declarations } constructor Create(AOwner : TComponent; HTMLSource : ustring); end; var DisplayForm: TDisplayForm; implementation {$R *.dfm} constructor TDisplayForm.Create(AOwner : TComponent; HTMLSource : ustring); begin inherited Create(AOwner); FHTMLSource := HTMLSource; end; procedure TDisplayForm.FormShow(Sender: TObject); begin if not(ChromiumWindow.CreateBrowser()) then Timer1.Enabled := true; end; procedure TDisplayForm.Timer1Timer(Sender: TObject); begin Timer1.Enabled := false; if not(ChromiumWindow.CreateBrowser()) and not(ChromiumWindow.Initialized) then Timer1.Enabled := true; end; procedure TDisplayForm.ChromiumWindowAfterCreated(Sender: TObject); var TempFilePath : string; begin Caption := '²âÊÔÓʼþ'; TempFilePath := ExtractFilePath(Application.ExeName); ChromiumWindow.ChromiumBrowser.LoadUrl(TempFilePath + 'temp.html'); end; procedure TDisplayForm.FormCreate(Sender: TObject); begin FCanClose := false; FClosing := false; end; procedure TDisplayForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin CanClose := FCanClose; if not(FClosing) then begin FClosing := true; Self.Visible := false; ChromiumWindow.CloseBrowser(true); end; end; procedure TDisplayForm.ChromiumWindowBeforeClose(Sender: TObject); begin FCanClose := true; PostMessage(Handle, WM_CLOSE, 0, 0); end; end.
unit SystemMonitorBasic; interface uses SysUtils, Classes, DataServices, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.MSSQL, FireDAC.Comp.Client, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, DB, FireDAC.Stan.Option, System.Generics.Collections; type TSystemMonitorBasic = class private FSystemMonitorID: Integer; FName: String; FSystemMonitorHost: String; FSystemMonitorEntity: String; FSystemMonitorParentEntity: String; FActive: Boolean; public constructor Create; overload; constructor Create(ASystemMonitorBasic: TSystemMonitorBasic); overload; property SystemMonitorID: Integer read FSystemMonitorID write FSystemMonitorID; property Name: String read FName write FName; property SystemMonitorHost: String read FSystemMonitorHost write FSystemMonitorHost; property SystemMonitorEntity: String read FSystemMonitorEntity write FSystemMonitorEntity; property SystemMonitorParentEntity: String read FSystemMonitorParentEntity write FSystemMonitorParentEntity; property Active: Boolean read FActive write FActive; end; TSystemMonitorBasicList = class private FList: TObjectList<TSystemMonitorBasic>; function GetCount: Integer; function GetListItem(AIndex: Integer): TSystemMonitorBasic; procedure SetListItem(AIndex: Integer; AValue: TSystemMonitorBasic); protected class function GetInitialSQL: TStrings; class function CreateSystemMonitorBasic(ADataSet: TDataSet): TSystemMonitorBasic; public constructor Create; overload; constructor Create(ASystemMonitorBasicList: TSystemMonitorBasicList); overload; destructor Destroy; override; procedure Add(AValue: TSystemMonitorBasic); procedure Delete(AIndex: Integer); property Count: Integer read GetCount; property SystemMonitors[AIndex: Integer]: TSystemMonitorBasic read GetListitem write Setlistitem; default; class function GetAll(AConnection: TFDConnection): TSystemMonitorBasicList; end; implementation {$REGION 'TSystemMonitorBasic'} constructor TSystemMonitorBasic.Create; begin FSystemMonitorID := -1; FName := String.Empty; FSystemMonitorHost := String.Empty; FSystemMonitorEntity := String.Empty; FSystemMonitorParentEntity := String.Empty; FActive := FALSE; end; constructor TSystemMonitorBasic.Create(ASystemMonitorBasic: TSystemMonitorBasic); begin FSystemMonitorID := -1; FName := String.Empty; FSystemMonitorHost := String.Empty; FSystemMonitorEntity := String.Empty; FSystemMonitorParentEntity := String.Empty; FActive := FALSE; if nil <> ASystemMonitorBasic then begin FSystemMonitorID := ASystemMonitorBasic.SystemMonitorID; FName := ASystemMonitorBasic.Name; FSystemMonitorHost := ASystemMonitorBasic.SystemMonitorHost; FSystemMonitorEntity := ASystemMonitorBasic.SystemMonitorEntity; FSystemMonitorParentEntity := ASystemMonitorBasic.SystemMonitorParentEntity; FActive := ASystemMonitorBasic.Active; end; end; {$ENDREGION} {$REGION 'TSystemMonitorBasicList'} constructor TSystemMonitorBasicList.Create; begin FList := TObjectList<TSystemMonitorBasic>.Create(TRUE); end; constructor TSystemMonitorBasicList.Create(ASystemMonitorBasicList: TSystemMonitorBasicList); begin FList := TObjectList<TSystemMonitorBasic>.Create(TRUE); for var i := 0 to (ASystemMonitorBasicList.Count - 1) do Flist.Add(TSystemMonitorBasic.Create(ASystemMonitorBasicList[i])); end; destructor TSystemMonitorBasicList.Destroy; begin Flist.Free; inherited Destroy; end; function TSystemMonitorBasicList.GetCount: Integer; begin Result := FList.Count; end; function TSystemMonitorBasicList.GetListItem(AIndex: Integer): TSystemMonitorBasic; begin Result := FList[AIndex]; end; procedure TSystemMonitorBasicList.SetListItem(AIndex: Integer; AValue: TSystemMonitorBasic); begin FList[AIndex] := AValue; end; class function TSystemMonitorBasicList.GetInitialSQL: TStrings; begin Result := TStringList.Create; Result.Add('Select SystemMonitor.SystemMonitorID SystemMonitorID, '); Result.Add('SystemMonitor.Name SystemMonitor, '); Result.Add('smh.Name SystemMonitorHost, '); Result.Add('sme.Name SystemMonitorEntity, '); Result.Add('smpe.Name SystemMonitorParentEntity, '); Result.Add('SystemMonitor.RecordStatus '); Result.Add('From SystemMonitor '); Result.Add('Inner Join Host smh On SystemMonitor.HostID = smh.HostID '); Result.Add('Inner Join Entity sme On smh.EntityID = sme.EntityID '); Result.Add('Left Join Entity smpe On smpe.EntityID = sme.ParentEntityID '); Result.Add('Where SystemMonitor.SystemMonitorID > 0 '); end; class function TSystemMonitorBasicList.CreateSystemMonitorBasic(ADataSet: TDataSet): TSystemMonitorBasic; begin Result := TSystemMonitorBasic.Create; Result.SystemMonitorID := ADataSet.Fields[0].AsInteger; Result.Name := ADataSet.Fields[1].AsString; Result.SystemMonitorHost := ADataSet.Fields[2].AsString; Result.SystemMonitorEntity := ADataSet.Fields[3].AsString; Result.SystemMonitorParentEntity := ADataSet.Fields[4].AsString; Result.Active := (0 <> ADataSet.Fields[5].AsInteger); end; procedure TSystemMonitorBasicList.Add(AValue: TSystemMonitorBasic); begin Flist.Add(AValue); end; procedure TSystemMonitorBasicList.Delete(AIndex: Integer); begin Flist.Delete(AIndex); end; class function TSystemMonitorBasicList.GetAll(AConnection: TFDConnection): TSystemMonitorBasicList; begin Result := nil; try var LQuery := TDataServices.GetQuery(AConnection); try var LSQL := GetInitialSQL; try for var i := 0 to (LSQL.Count - 1) do LQuery.SQL.Add(LSQL[i]); finally LSQL.Free; end; AConnection.Open; LQuery.Open; if not LQuery.IsEmpty then begin Result := TSystemMonitorBasicList.Create; LQuery.First; while not LQuery.EOF do begin Result.Add(CreateSystemMonitorBasic(LQuery)); LQuery.Next; end; end; finally LQuery.Close; LQuery.Free; end; finally AConnection.Close; end; end; {$ENDREGION} end.
unit ViewModel.TitleList; interface uses Model.Interfaces; function CreateTitleListViewModelClass: ITitleListViewModelInterface; implementation uses Model.Title, Model.FormDeclarations, Model.ProSu.Interfaces, Model.ProSu.InterfaceActions, Model.ProSu.Provider, Model.ProSu.Subscriber; type TTitleListViewModel = class(TInterfacedObject, ITitleListViewModelInterface) private fModel: ITitleModelInterface; fProvider : IProviderInterface; fSubscriberToEdit : ISubscriberInterface; function GetModel: ITitleModelInterface; procedure SetModel(const newModel: ITitleModelInterface); function GetProvider: IProviderInterface; function GetSubscriberToEdit: ISubscriberInterface; procedure SendNotification(const actions : TInterfaceActions); procedure SendErrorNotification (const errorType: TInterfaceErrors; const errorMessage: string); procedure NotificationFromProvider(const notifyClass : INotificationClass); public property Model: ITitleModelInterface read GetModel write SetModel; property Provider: IProviderInterface read GetProvider; property SubscriberToEdit: ISubscriberInterface read GetSubscriberToEdit; constructor Create; end; { TTitleViewModel } constructor TTitleListViewModel.Create; begin fProvider:=CreateProSuProviderClass; fModel := CreateTitleModelClass; end; function TTitleListViewModel.GetModel: ITitleModelInterface; begin result:=fModel; end; function TTitleListViewModel.GetProvider: IProviderInterface; begin result:=fProvider; end; function TTitleListViewModel.GetSubscriberToEdit: ISubscriberInterface; begin if not Assigned(fSubscriberToEdit) then fSubscriberToEdit := CreateProSuSubscriberClass; Result := fSubscriberToEdit; end; procedure TTitleListViewModel.NotificationFromProvider( const notifyClass: INotificationClass); begin end; procedure TTitleListViewModel.SendErrorNotification( const errorType: TInterfaceErrors; const errorMessage: string); var tmpErrorNotificationClass: TErrorNotificationClass; begin tmpErrorNotificationClass:=TErrorNotificationClass.Create; try tmpErrorNotificationClass.Actions:=errorType; tmpErrorNotificationClass.ActionMessage:=errorMessage; fProvider.NotifySubscribers(tmpErrorNotificationClass); finally tmpErrorNotificationClass.Free; end; end; procedure TTitleListViewModel.SendNotification(const actions: TInterfaceActions); var tmpNotification : TNotificationClass; begin tmpNotification := TNotificationClass.Create; try tmpNotification.Actions := actions; fProvider.NotifySubscribers(tmpNotification); finally tmpNotification.Free; end; end; procedure TTitleListViewModel.SetModel(const newModel: ITitleModelInterface); begin fModel:=newModel; end; function CreateTitleListViewModelClass: ITitleListViewModelInterface; begin result:=TTitleListViewModel.Create; end; end.
unit Movimento; interface uses SysUtils, Contnrs, Pedido, Generics.Collections; type TMovimento = class private Fcodigo_caixa: integer; Fcodigo: integer; Ftipo_moeda: integer; Fcodigo_pedido: integer; Fdata: TDateTime; FPedido :TPedido; FValor_PAgo :Real; function GetPedido: TPedido; public property codigo :integer read Fcodigo write Fcodigo; property codigo_caixa :integer read Fcodigo_caixa write Fcodigo_caixa; property tipo_moeda :integer read Ftipo_moeda write Ftipo_moeda; property codigo_pedido :integer read Fcodigo_pedido write Fcodigo_pedido; property data :TDateTime read Fdata write Fdata; property valor_pago :Real read FValor_pago write FValor_pago; public class function MovimentosDoPedido(codigo_pedido :integer):TObjectList<TMovimento>; private destructor Destroy;override; public property Pedido :TPedido read GetPedido; end; implementation uses repositorio, fabricaRepositorio, EspecificacaoMovimentosPorCodigoPedido; { TMovimento } destructor TMovimento.Destroy; begin if assigned(self.FPedido) then FreeAndNil(FPedido); inherited; end; function TMovimento.GetPedido: TPedido; var Repositorio :TRepositorio; begin Repositorio := nil; try if not Assigned(self.FPedido) then begin Repositorio := TFabricaRepositorio.GetRepositorio(TPedido.ClassName); self.FPedido := TPedido( Repositorio.Get(self.Fcodigo_pedido) ); end; result := self.FPedido; finally FreeAndNil(Repositorio); end; end; class function TMovimento.MovimentosDoPedido(codigo_pedido :integer): TObjectList<TMovimento>; var repositorio :TRepositorio; Especificacao :TEspecificacaoMovimentosPorCodigoPedido; begin try repositorio := nil; Especificacao := nil; repositorio := TFabricaRepositorio.GetRepositorio(TMovimento.ClassName); Especificacao := TEspecificacaoMovimentosPorCodigoPedido.Create( codigo_pedido ); result := repositorio.GetListaPorEspecificacao<TMovimento>( Especificacao ); finally FreeAndNil(repositorio); FreeAndNil(Especificacao); end; end; end.
// ============================================================================= // Module name : $RCSfile: DeviceConfig.pas,v $ // Description : This unit defines classes specially for configurations of // measurement devices // Compiler : Delphi 2007 // Author : 2015-12-11 /bsu/ // History : //============================================================================== unit DeviceConfig; interface uses Classes, SysUtils, ConfigBase, StringPairs; type EDeviceType = ( DT_MULTIMETER, DT_OSCILOSCOPE, DT_POWERSUPPLY, DT_RELAICONTROL, DT_THERMOMETER, DT_PCANADAPTOR ); TDeviceConfigurator = class protected t_devices: TStrings; public constructor Create(); destructor Destroy(); override; function LoadDeviceSettings(const devname, fname: string): boolean; function GetDeviceConfig(const devname: string): TConfigBase; function GetDeviceConfigSection(const devname, secname: string): TStringPairs; procedure ClearDevices(); end; implementation //uses StrUtils, IniFiles; constructor TDeviceConfigurator.Create(); begin inherited Create(); t_devices := TStringList.Create(); end; destructor TDeviceConfigurator.Destroy(); begin ClearDevices(); t_devices.Free(); inherited Destroy(); end; function TDeviceConfigurator.LoadDeviceSettings(const devname, fname: string): boolean; var t_devconf: TConfigBase; begin t_devconf := GetDeviceConfig(devname); if (not assigned(t_devconf)) then t_devconf := TConfigBase.Create(); result := t_devconf.UpdateFromFile(fname); end; function TDeviceConfigurator.GetDeviceConfig(const devname: string): TConfigBase; var i_idx: integer; begin result := nil; i_idx := t_devices.IndexOfName(devname); if (i_idx >= 0) then result := TConfigBase(t_devices.Objects[i_idx]); end; function TDeviceConfigurator.GetDeviceConfigSection(const devname, secname: string): TStringPairs; var t_devconf: TConfigBase; begin result := nil; t_devconf := GetDeviceConfig(devname); if assigned(t_devconf) then result := t_devconf.GetConfig(secname); end; procedure TDeviceConfigurator.ClearDevices(); begin while (t_devices.Count > 0) do if assigned(t_devices.Objects[0]) then begin t_devices.Objects[0].Free(); t_devices.Delete(0); end; end; end.
unit oBaseFrame; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, TAGraph, TASeries, TASources, TATransformations, TAChartAxis, TATools, Forms, ExtCtrls, StdCtrls, ueSelector, ueLED, oGlobal, oDataCollector, types; type TDataAvailEvent = procedure(Sender: TObject; AWave: TWaveDataArray) of object; { TBaseFrame } TBaseFrame = class(TFrame) CbLinkedSensitivities: TCheckBox; CenterBevel: TBevel; CbLeftON: TCheckBox; CbRightON: TCheckBox; Chart: TChart; ChartToolset: TChartToolset; ControlPanel: TPanel; DataPointCrosshairTool: TDataPointCrosshairTool; GbLeftSensitivity: TGroupBox; GbRightSensitivity: TGroupBox; LEDLeft: TueLED; LEDRightPanel: TPanel; LEDRight: TueLED; LeftAxisTransformations: TChartAxisTransformations; LeftAxisTransformationsAutoScaleAxisTransform1: TAutoScaleAxisTransform; LeftChannelChartSource: TUserDefinedChartSource; LeftChannelSeries: TLineSeries; PanDragTool: TPanDragTool; Panel1: TPanel; LeftSensitityPanel: TPanel; LEDLeftPanel: TPanel; RightSensitivityPanel: TPanel; RightAxisTransformations: TChartAxisTransformations; RightAxisTransformationsAutoScaleAxisTransform1: TAutoScaleAxisTransform; RightChannelChartSource: TUserDefinedChartSource; RightChannelSeries: TLineSeries; SwLeftSensitivity: TuESelector; SwRightSensitivity: TuESelector; Timer: TTimer; ZoomDragTool: TZoomDragTool; procedure CbLeftONClick(Sender: TObject); procedure CbRightONClick(Sender: TObject); procedure DataPointCrosshairToolAfterMouseDown(ATool: TChartTool; APoint: TPoint); procedure DataPointCrosshairToolAfterMouseUp(ATool: TChartTool; APoint: TPoint); procedure SwLeftSensitivityChange(Sender: TObject); procedure SwRightSensitivityChange(Sender: TObject); private FMode: TPlayRecordMode; FOnBeginPlayback: TNotifyEvent; FOnEndPlayback: TNotifyEvent; FOnDataAvail: TDataAvailEvent; FOnDataReceived: TNotifyEvent; procedure SetSensValue(AChannelIndex: TChannelIndex; AValue: Double); protected FDataCollector: TDataCollector; FSampleRate: Integer; FSensitivityLock: Integer; FCrosshairActive: Boolean; function LeftAxis: TChartAxis; inline; function RightAxis: TChartAxis; inline; function GetAxis(AChannelindex: TChannelIndex): TChartAxis; procedure SetSensitivity(AChannelIndex: TChannelIndex; AValue: Double); virtual; abstract; procedure SetupTimebase; virtual; abstract; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Activate; virtual; procedure Deactivate; virtual; procedure AutoSizeControls; virtual; procedure SetDataCollector(AValue: TDataCollector); procedure SetSampleRate(AValue: Integer); function StartPlayback(const AFileName: String): Boolean; overload; function StartPlayback(AMemory: Pointer; ALength: DWord; ALoop: Boolean): Boolean; overload; function StartRecording(ASampleRate: Integer): Boolean; procedure Stop; procedure Pause; procedure Resume; procedure ControlsToParams; procedure ParamsToControls; property OnBeginPlayback: TNotifyEvent read FOnBeginPlayback write FOnBeginPlayback; property OnEndPlayback: TNotifyEvent read FOnEndPlayback write FOnEndPlayback; property OnDataReceived: TNotifyEvent read FOnDataReceived write FOnDataReceived; end; implementation {$R *.lfm} uses Math, Dialogs, TAChartUtils, TAChartAxisUtils; constructor TBaseFrame.Create(AOwner: TComponent); begin inherited; end; destructor TBaseFrame.Destroy; begin inherited; end; procedure TBaseFrame.Activate; begin ParamsToControls; end; procedure TBaseFrame.AutoSizeControls; begin // to be overridden by ancestors if needed end; procedure TBaseFrame.CbLeftONClick(Sender: TObject); begin LEDLeft.Active := CbLeftON.Checked; LeftChannelSeries.Active := CbLeftON.Checked; with LeftAxis do begin Visible := CbLeftON.Checked; Range.UseMin := CbLeftON.Checked; Range.UseMax := CbLeftON.Checked; end; with RightAxis do begin Alignment := TChartAxisAlignment(IfThen(LeftAxis.Visible, ord(calRight), ord(calLeft))); Title.LabelFont.Orientation := IfThen(Alignment = calRight, -900, 900); end; end; procedure TBaseFrame.CbRightONClick(Sender: TObject); begin LEDRight.Active := CbRightON.Checked; RightChannelSeries.Active := CbRightON.Checked; with RightAxis do begin Visible := CbRightON.Checked; Range.UseMin := CbRightON.Checked; Range.UseMax := CbRightON.Checked; Alignment := TChartAxisAlignment(IfThen(LeftAxis.Visible, ord(calRight), ord(calLeft))); Title.LabelFont.Orientation := IfThen(Alignment = calRight, -900, 900); end; end; procedure TBaseFrame.ControlsToParams; begin SensitivityParams.ChannelMax[ciLeft] := SENSITIVITIES[SwLeftSensitivity.Index]; SensitivityParams.ChannelMax[ciRight] := SENSITIVITIES[SwRightSensitivity.Index]; SensitivityParams.ChannelOn[ciLeft] := CbLeftON.Checked; SensitivityParams.ChannelOn[ciRight] := CbRightON.Checked; SensitivityParams.ChannelsLinked := CbLinkedSensitivities.Checked; end; procedure TBaseFrame.DataPointCrosshairToolAfterMouseDown(ATool: TChartTool; APoint: TPoint); begin Unused(ATool, APoint); FCrosshairActive := true; end; procedure TBaseFrame.DataPointCrosshairToolAfterMouseUp(ATool: TChartTool; APoint: TPoint); begin Unused(APoint); if ATool is TDataPointCrosshairTool then begin TDatapointCrosshairTool(ATool).Hide; FCrosshairActive := false; end; end; procedure TBaseFrame.Deactivate; begin ControlsToParams; end; function TBaseFrame.GetAxis(AChannelIndex: TChannelIndex): TChartAxis; begin case AChannelindex of ciLeft : Result := LeftAxis; ciRight: Result := RightAxis; end; end; function TBaseFrame.LeftAxis: TChartAxis; begin Result := Chart.AxisList[1]; end; procedure TBaseFrame.ParamsToControls; begin SetSensValue(ciLeft, SensitivityParams.ChannelMax[ciLeft]); SetSensvalue(ciRight, SensitivityParams.ChannelMax[ciRight]); CbLeftON.Checked := SensitivityParams.ChannelOn[ciLeft]; CbLeftONClick(nil); CbRightON.Checked := SensitivityParams.ChannelOn[ciRight]; CbRightOnClick(nil); CbLinkedSensitivities.Checked := SensitivityParams.ChannelsLinked; end; procedure TBaseFrame.Pause; begin if FDataCollector.Running then begin Timer.Enabled := false; FDataCollector.Pause; end; end; procedure TBaseFrame.Resume; begin if FDataCollector.Paused then begin Timer.Enabled := true; FDataCollector.Resume; end; end; function TBaseFrame.RightAxis: TChartAxis; begin Result := Chart.AxisList[2]; end; procedure TBaseFrame.SetDataCollector(AValue: TDataCollector); begin FDataCollector := AValue; end; procedure TBaseFrame.SetSampleRate(AValue: Integer); begin FSampleRate := AValue; end; procedure TBaseFrame.SetSensValue(AChannelIndex: TChannelIndex; AValue: Double); const EPS = 1e-6; var i: Integer; begin // Set axis limits SetSensitivity(AChannelIndex, AValue); // Set rotary switch to corresponding value for i:= 0 to High(SENSITIVITIES) do if SameValue(SENSITIVITIES[i], AValue, EPS) then begin case AChannelIndex of ciLeft : SwLeftSensitivity.Index := i; ciRight: SwRightSensitivity.Index := i; end; exit; end; end; function TBaseFrame.StartPlayback(const AFileName: String): Boolean; begin Result := false; if FDataCollector.Running then exit; if (AFilename = '') then exit; if not FileExists(AFileName) then begin MessageDlg(Format('File "%s" not found.', [AFileName]), mtError, [mbOK], 0); exit; end; if FDataCollector.StartPlayback(AFileName) then begin FSampleRate := FDataCollector.GetSampleRate; if Assigned(FOnBeginPlayback) then FOnBeginPlayback(self); SetupTimebase; FMode := prmPlay; Timer.Enabled := true; Result := true; end else begin Timer.Enabled := false; FMode := prmNone; MessageDlg(FDataCollector.ErrMsg, mtError, [mbOK], 0); end; end; function TBaseFrame.StartPlayback(AMemory: Pointer; ALength: DWord; ALoop: Boolean): Boolean; begin Result := false; if FDataCollector.Running then exit; if (AMemory = nil) then exit; if FDataCollector.StartPlayback(AMemory, ALength, ALoop) then begin FSampleRate := FDataCollector.GetSampleRate; if Assigned(FOnBeginPlayback) then FOnBeginPlayback(self); SetupTimebase; FMode := prmPlay; Timer.Enabled := true; Result := true; end else begin Timer.Enabled := false; FMode := prmNone; MessageDlg(FDataCollector.ErrMsg, mtError, [mbOK], 0); end; end; function TBaseFrame.StartRecording(ASampleRate: Integer): Boolean; begin Result := false; if FDataCollector.Running then exit; if FDataCollector.StartRecording(ASampleRate) then begin FSampleRate := ASampleRate; { if Assigned(FOnBeginRecording) then FOnBeginRecording(self); } SetupTimebase; FMode := prmRecord; Timer.Enabled := true; Result := true; end else begin Timer.Enabled := false; FMode := prmNone; MessageDlg(FDataCollector.ErrMsg, mtError, [mbOk], 0); end; end; procedure TBaseFrame.Stop; begin FMode := prmNone; Timer.Enabled := false; FDataCollector.Stop; if Assigned(FOnEndPlayback) then FOnEndPlayback(self); end; procedure TBaseFrame.SwLeftSensitivityChange(Sender: TObject); begin if FSensitivityLock > 0 then exit; inc(FSensitivityLock); try SetSensitivity(ciLeft, SENSITIVITIES[SwLeftSensitivity.Index]); if CbLinkedSensitivities.Checked then begin SwRightSensitivity.Index := SwLeftSensitivity.Index; SetSensitivity(ciRight, SENSITIVITIES[SwLeftSensitivity.Index]); end; finally dec(FSensitivityLock); end; end; procedure TBaseFrame.SwRightSensitivityChange(Sender: TObject); begin if FSensitivityLock > 0 then exit; inc(FSensitivityLock); try SetSensitivity(ciRight, SENSITIVITIES[SwRightSensitivity.Index]); if CbLinkedSensitivities.Checked then begin SwLeftSensitivity.Index := SwRightSensitivity.Index; SetSensitivity(ciLeft, SENSITIVITIES[SwRightSensitivity.Index]); end; finally dec(FSensitivityLock); end; end; end.
unit Repositorio; interface uses DB, FireDAC.Comp.Client, uModulo, Variants, Contnrs, Auditoria, EventoExecutarOperacao, Especificacao, Classes, Generics.Collections, Dialogs, Forms; type TTipoAuditoria = (taInclusao, taAlteracao, taExclusao); type TRepositorio = class private procedure GravaAuditoria (AntigoObjeto, Objeto :TObject; TipoAuditoria :TTipoAuditoria); protected FQuery :TFDQuery; FDM :TDM; FAtualizarTela :TEventoExecutarOperacao; protected function Get(Dataset :TDataSet) :TObject; overload; virtual; function GetNomeDaTabela :String; virtual; function GetIdentificador(Objeto :TObject) :Variant; virtual; function GetChaveParaRemocao(Objeto :TObject) :Variant; virtual; function GetRepositorio :TRepositorio; virtual; //============================================================================== // Métodos que retornam SQL. //============================================================================== protected FIdentificador :String; function SQLGet :String; virtual; function CondicaoSQLGetAll :String; virtual; function SQLGetAll :String; virtual; function SQLGetExiste(campo:String) :String; virtual; function SQLSalvar :String; virtual; function SQLRemover :String; virtual; function IsInsercao(Objeto :TObject) :Boolean; virtual; function IsComponente() :Boolean; virtual; function IsColecao() :Boolean; virtual; protected procedure SetParametros (Objeto :TObject ); virtual; procedure SetParametro (NomeDoParametro :String; Valor :Variant); procedure SetParametroBlob(NomeDoParametro :String; Stream :TMemoryStream); procedure SetIdentificador(Objeto :TObject; Identificador :Variant); virtual; protected procedure LimpaParametro (NomeDoParametro :String); procedure ExecutaDepoisDeSalvar (Objeto :TObject); virtual; //============================================================================== // Auditoria //============================================================================== protected { procedure SetCamposIncluidos(Auditoria :TAuditoria; Objeto :TObject); virtual; procedure SetCamposAlterados(Auditoria :TAuditoria; AntigoObjeto, Objeto :TObject); virtual; procedure SetCamposExcluidos(Auditoria :TAuditoria; Objeto :TObject); virtual; } public constructor Create; destructor Destroy; override; public //============================================================================== // Métodos de recuperação de dados //============================================================================== function Get (const Identificador :Variant; const campo :String = '') :TObject; overload; function GetListaPorIdentificador(const Identificador :Variant) :TObjectList; function GetAll :TObjectList; function GetExiste (const campo :String; const Identificador :Variant) :Boolean; function GetPorEspecificacao (Especificacao :TEspecificacao; const identificador :String = '') :TObject; function GetListaPorEspecificacao<T :class>(Especificacao :TEspecificacao; const identificador :String = '') :TObjectList<T>; //============================================================================== // Métodos de controle de transação. //============================================================================== procedure HabilitaAutoCommit; procedure DesabilitaAutoCommit; procedure ExecutaRollbackNaTransacao; procedure ExecutaCommitNaTransacao; //============================================================================== // Métodos de persistência no banco dados. //============================================================================== function Salvar (Objeto :TObject) :Boolean; virtual; function Salvar_2(Objeto :TObject) :Boolean; virtual; function Remover(Objeto :TObject) :Boolean; virtual; function RemoverPorIdentificador(const Identificador :Variant) :Boolean; //============================================================================== // Evento para atualizar a tela //============================================================================== procedure AdicionarEventoDeAtualizarTela(AtualizarTela :TEventoExecutarOperacao); //============================================================================== // Auditoria //============================================================================== protected procedure SetCamposIncluidos(Auditoria :TAuditoria; Objeto :TObject); virtual; procedure SetCamposAlterados(Auditoria :TAuditoria; AntigoObjeto, Objeto :TObject); virtual; procedure SetCamposExcluidos(Auditoria :TAuditoria; Objeto :TObject); virtual; public class function HorarioBancoDeDados :TDateTime; end; implementation uses SysUtils, ExcecaoMetodoNaoImplementado, FabricaRepositorio; { TRepositorio } constructor TRepositorio.Create; begin self.FQuery := dm.GetConsulta; FDM := DM; end; function TRepositorio.Get(Dataset :TDataset): TObject; begin raise TExcecaoMetodoNaoImplementado.Create(self.ClassName, 'Get(Dataset :TDataset)'); end; destructor TRepositorio.Destroy; begin FreeAndNil(self.FQuery); inherited; end; function TRepositorio.Get(const Identificador :Variant; const campo :String): TObject; begin try result := nil; if (self.FQuery.Connection.TxOptions.AutoCommit) and (self.FQuery.Connection.InTransaction) then self.FQuery.Connection.Commit; self.FQuery.SQL.Clear; if campo = '' then begin self.FQuery.SQL.Add(self.SQLGet); self.FQuery.Params[0].Value := Identificador; end else begin self.FQuery.SQL.Add(self.SQLGetExiste(campo)); self.FQuery.ParamByName(campo).Value := Identificador; end; self.FQuery.Open; if not self.FQuery.IsEmpty then result := self.Get(self.FQuery); except on E: Exception do begin dm.LogErros.AdicionaErro('Repositorio', E.ClassName, E.Message); raise Exception.Create(E.Message); end; end; end; function TRepositorio.SQLGet: String; begin raise TExcecaoMetodoNaoImplementado.Create(self.ClassName, 'SQLGet: String;'); end; {------------------------------------------------------------------------------- Método: TRepositorio.Salvar Autor: Ricardo Medeiros Descrição: Método que recebe um objeto e o persiste de acordo com os parâmetros setados na sub-classe. Data: 2013.07.16 Parâmetros: Objeto :TObject; Retorno: Boolean -------------------------------------------------------------------------------} function TRepositorio.Salvar(Objeto: TObject): Boolean; var ObjetoAntigo :TObject; Repositorio :TRepositorio; infoAdc :String; begin Result := true; Repositorio := self.GetRepositorio; ObjetoAntigo := nil; try try self.FQuery.SQL.Clear; self.FQuery.SQL.Add(self.SQLSalvar); self.SetParametros(Objeto); if not self.IsInsercao(Objeto) then ObjetoAntigo := Repositorio.Get(self.GetIdentificador(Objeto)); self.FQuery.ExecSQL; if self.IsInsercao(Objeto) then begin if not self.IsComponente then self.SetIdentificador(Objeto, dm.GetValorGenerator('GEN_'+self.GetNomeDaTabela+'_ID')); end; self.ExecutaDepoisDeSalvar(Objeto); finally FreeAndNil(Repositorio); FreeAndNil(ObjetoAntigo); end; except on E: Exception do begin dm.LogErros.AdicionaErro('Repositorio', E.ClassName, E.Message + ' '+ Objeto.ClassName +' '+ Self.classname); Result := false; raise Exception.create('Erro ao salvar!'+#13#10+'Para mais informações, consulte o log de erros.'); end; end; end; function TRepositorio.Salvar_2(Objeto: TObject): Boolean; var ObjetoAntigo :TObject; Repositorio :TRepositorio; begin Result := true; Repositorio := self.GetRepositorio; ObjetoAntigo := nil; try try dm.FDConnection.TxOptions.AutoCommit := true; self.FQuery.Connection := dm.FDConnection; self.FQuery.SQL.Clear; self.FQuery.SQL.Add(self.SQLSalvar); self.SetParametros(Objeto); if not self.IsInsercao(Objeto) then ObjetoAntigo := Repositorio.Get(self.GetIdentificador(Objeto)); self.FQuery.ExecSQL; if self.IsInsercao(Objeto) then begin if not self.IsComponente then self.SetIdentificador(Objeto, dm.GetValorGenerator('GEN_'+self.GetNomeDaTabela+'_ID','0')); self.GravaAuditoria(nil, Objeto, taInclusao); end else self.GravaAuditoria(ObjetoAntigo, Objeto, taAlteracao); self.ExecutaDepoisDeSalvar(Objeto); finally FreeAndNil(Repositorio); FreeAndNil(ObjetoAntigo); dm.FDConnection.TxOptions.AutoCommit := false; self.FQuery.Connection := dm.conexao; end; except on E: Exception do begin dm.LogErros.AdicionaErro('Repositorio', E.ClassName, E.Message); Result := false; raise Exception.create('Erro ao salvar.'+#13#10+'Para mais informações consulte o log de erros.'); end; end; end; function TRepositorio.SQLSalvar: String; begin raise TExcecaoMetodoNaoImplementado.Create(self.ClassName, 'SQLSalvar: String;'); end; procedure TRepositorio.SetParametros(Objeto :TObject); begin raise TExcecaoMetodoNaoImplementado.Create(self.ClassName, 'SetParametros;'); end; procedure TRepositorio.SetParametro(NomeDoParametro: String; Valor: Variant); begin self.FQuery.ParamByName(NomeDoParametro).Value := Valor; end; procedure TRepositorio.LimpaParametro(NomeDoParametro: String); begin self.FQuery.ParamByName(NomeDoParametro).Clear; end; function TRepositorio.GetAll: TObjectList; var obj :TObject; begin try result := nil; self.FQuery.SQL.Clear; self.FQuery.SQL.Add(self.SQLGetAll); self.FQuery.Open; if self.FQuery.IsEmpty then exit; result := TObjectList.Create; while not self.FQuery.Eof do begin obj := self.Get(self.FQuery); if Assigned(obj) then result.Add(obj); self.FQuery.Next; end; except on E: Exception do begin dm.LogErros.AdicionaErro('Repositorio', E.ClassName, E.Message); raise Exception.Create(E.Message); end; end; end; function TRepositorio.SQLGetAll: String; begin raise TExcecaoMetodoNaoImplementado.Create(self.ClassName, 'SQLGetAll: String;'); end; function TRepositorio.GetExiste(const campo :String; const Identificador :Variant): Boolean; begin try result := false; self.FQuery.SQL.Clear; self.FQuery.SQL.Add(self.SQLGetExiste(campo)); self.FQuery.Params[0].Value := Identificador; self.FQuery.Open; if not self.FQuery.IsEmpty then Result:= true; except on E: Exception do begin dm.LogErros.AdicionaErro('Repositorio', E.ClassName, E.Message); raise Exception.Create(E.Message); end; end; end; function TRepositorio.SQLGetExiste(campo:String): String; begin raise TExcecaoMetodoNaoImplementado.Create(self.ClassName, 'SQLGetExiste: String;'); end; {------------------------------------------------------------------------------- Método: TRepositorio.GetPorEspecificacao Autor: Ricardo Medeiros Descrição: Método que recebe uma especificação de consulta. Ao encontrar o primeiro objeto que atende a especificação, o mesmo é retornado e a função é finalizada. Data: 2013.07.16 Parâmetros: Especificacao: TEspecificacao Retorno: TObject -------------------------------------------------------------------------------} function TRepositorio.GetPorEspecificacao( Especificacao: TEspecificacao; const identificador :String): TObject; begin try result := nil; self.FQuery.SQL.Clear; FIdentificador := identificador; self.FQuery.SQL.Add(self.SQLGetAll); self.FQuery.Open; if self.FQuery.IsEmpty then exit; while not self.FQuery.Eof do begin result := self.Get(self.FQuery); // Se o objeto não é nulo e atende a especificação então é retornado if Assigned(result) and Especificacao.SatisfeitoPor(result) then exit; self.FQuery.Next; FreeAndNil(result); end; result := nil; // se não sair no while, não encontrou except on E: Exception do begin dm.LogErros.AdicionaErro('Repositorio', E.ClassName, E.Message); raise Exception.Create(E.Message); end; end; end; {------------------------------------------------------------------------------- Método: TRepositorio.GetListaPorEspecificacao Autor: Ricardo Medeiros Descrição: Método que recebe uma especificação de consulta. Ao encontrar o primeiro objeto que atende a especificação, o mesmo é adicionado na lista de retorno. Data: 2013.07.16 Parâmetros: Especificacao: TEspecificacao Retorno: TList -------------------------------------------------------------------------------} function TRepositorio.GetListaPorEspecificacao<T>( Especificacao: TEspecificacao; const identificador :String): TObjectList<T>; var obj :TObject; begin try result := nil; self.FQuery.SQL.Clear; FIdentificador := identificador; self.FQuery.SQL.Add(self.SQLGetAll); self.FQuery.Open; if self.FQuery.IsEmpty then exit; result := TObjectList<T>.Create(true); while not self.FQuery.Eof do begin obj := self.Get(self.FQuery); Application.ProcessMessages; { Se o objeto não é nulo e atende a especificação então ele é adicionado na lista para ser retornado. } if Assigned(obj) and Especificacao.SatisfeitoPor(obj) then result.Add(obj) else FreeAndNil(obj); self.FQuery.Next; end; except on E: Exception do begin dm.LogErros.AdicionaErro('Repositorio', E.ClassName, E.Message); raise Exception.Create(E.Message); end; end; end; function TRepositorio.GetNomeDaTabela: String; begin raise TExcecaoMetodoNaoImplementado.Create(self.ClassName, 'GetNomeDaTabela: String;'); end; procedure TRepositorio.SetCamposAlterados(Auditoria: TAuditoria; AntigoObjeto, Objeto: TObject); begin end; procedure TRepositorio.SetCamposExcluidos(Auditoria: TAuditoria; Objeto: TObject); begin end; procedure TRepositorio.SetCamposIncluidos(Auditoria: TAuditoria; Objeto: TObject); begin end; procedure TRepositorio.SetIdentificador(Objeto :TObject; Identificador :Variant); begin raise TExcecaoMetodoNaoImplementado.Create(self.ClassName, 'SetIdentificador(Identificador: Variant);'); end; function TRepositorio.IsInsercao(Objeto: TObject): Boolean; begin raise TExcecaoMetodoNaoImplementado.Create(self.ClassName, 'IsInsercao(Objeto: TObject): Boolean;'); end; function TRepositorio.Remover(Objeto: TObject): Boolean; begin try self.FQuery.SQL.Clear; self.FQuery.SQL.Add(self.SQLRemover); if not self.IsColecao then self.FQuery.Params[0].Value := self.GetIdentificador(Objeto) else self.FQuery.Params[0].Value := self.GetChaveParaRemocao(Objeto); self.FQuery.ExecSQL; // self.GravaAuditoria(nil, Objeto, taExclusao); except on E: Exception do dm.LogErros.AdicionaErro('Repositorio', E.ClassName, E.Message); end; end; function TRepositorio.GetIdentificador(Objeto: TObject): Variant; begin raise TExcecaoMetodoNaoImplementado.Create(self.ClassName, 'GetIdentificador(Objeto: TObject): Variant'); end; function TRepositorio.SQLRemover: String; begin raise TExcecaoMetodoNaoImplementado.Create(self.ClassName, 'SQLRemover: String;'); end; procedure TRepositorio.ExecutaDepoisDeSalvar; begin {} end; { procedure TRepositorio.GravaAuditoria(AntigoObjeto, Objeto: TObject; TipoAuditoria :TTipoAuditoria); var Repositorio :TRepositorio; Auditoria :TAuditoria; begin Auditoria := nil; Repositorio := nil; try Auditoria := TAuditoria.Create(dm.UsuarioLogado, self.GetNomeDaTabela, dm.NomeDoTerminal); if (TipoAuditoria = taInclusao) then self.SetCamposIncluidos(Auditoria, Objeto) else if (TipoAuditoria = taAlteracao) then self.SetCamposAlterados(Auditoria, AntigoObjeto, Objeto) else if (TipoAuditoria = taExclusao) then self.SetCamposExcluidos(Auditoria, Objeto); if not Auditoria.TemCamposParaPersistir then exit; Repositorio := TFabricaRepositorio.GetRepositorio(TAuditoria.ClassName); Repositorio.Salvar(Auditoria); finally FreeAndNil(Auditoria); FreeAndNil(Repositorio); end; end; procedure TRepositorio.SetCamposAlterados(Auditoria :TAuditoria; AntigoObjeto, Objeto :TObject); begin // Método a ser implementado nas sub-classes end; procedure TRepositorio.SetCamposExcluidos(Auditoria :TAuditoria; Objeto :TObject); begin // Método a ser implementado nas sub-classes end; procedure TRepositorio.SetCamposIncluidos(Auditoria :TAuditoria; Objeto :TObject); begin // Método a ser implementado nas sub-classes end; } function TRepositorio.GetRepositorio: TRepositorio; begin raise TExcecaoMetodoNaoImplementado.Create(self.ClassName, 'GetRepositorio: TRepositorio;'); end; procedure TRepositorio.GravaAuditoria(AntigoObjeto, Objeto: TObject; TipoAuditoria: TTipoAuditoria); var Repositorio :TRepositorio; Auditoria :TAuditoria; begin Auditoria := nil; Repositorio := nil; try Auditoria := TAuditoria.Create(dm.UsuarioLogado, self.GetNomeDaTabela, dm.NomeDoTerminal); if (TipoAuditoria = taInclusao) then self.SetCamposIncluidos(Auditoria, Objeto) else if (TipoAuditoria = taAlteracao) then self.SetCamposAlterados(Auditoria, AntigoObjeto, Objeto) else if (TipoAuditoria = taExclusao) then self.SetCamposExcluidos(Auditoria, Objeto); if not Auditoria.TemCamposParaPersistir then exit; Repositorio := TFabricaRepositorio.GetRepositorio(TAuditoria.ClassName); Repositorio.Salvar(Auditoria); finally FreeAndNil(Auditoria); FreeAndNil(Repositorio); end; end; class function TRepositorio.HorarioBancoDeDados: TDateTime; var Query :TFDQuery; begin Query := nil; result := 0; try try Query := dm.GetConsulta('select current_time HORA_ATUAL from rdb$database'); Query.Open; if not Query.IsEmpty then result := Query.Fields[0].AsDateTime; finally Query.Close; FreeAndNil(Query); end; except on E: Exception do begin dm.LogErros.AdicionaErro('Repositorio', E.ClassName, E.Message); raise Exception.Create(E.Message); end; end; end; procedure TRepositorio.DesabilitaAutoCommit; begin self.FQuery.Connection.TxOptions.AutoCommit := false; end; procedure TRepositorio.HabilitaAutoCommit; begin self.FQuery.Connection.TxOptions.AutoCommit := true; end; procedure TRepositorio.ExecutaCommitNaTransacao; begin self.FQuery.Connection.Commit; end; procedure TRepositorio.ExecutaRollbackNaTransacao; begin self.FQuery.Connection.Rollback; end; function TRepositorio.GetListaPorIdentificador( const Identificador: Variant): TObjectList; var obj :TObject; begin try result := nil; self.FQuery.SQL.Clear; self.FQuery.SQL.Add(self.SQLGet); self.FQuery.Params[0].Value := Identificador; self.FQuery.Open; if self.FQuery.IsEmpty then exit; result := TObjectList.Create; while not self.FQuery.Eof do begin obj := self.Get(self.FQuery); if Assigned(obj) then result.Add(obj); self.FQuery.Next; end; except on E: Exception do begin dm.LogErros.AdicionaErro('Repositorio', E.ClassName, E.Message); raise Exception.Create(E.Message); end; end; end; function TRepositorio.IsComponente: Boolean; begin result := false; end; function TRepositorio.GetChaveParaRemocao(Objeto: TObject): Variant; begin raise TExcecaoMetodoNaoImplementado.Create(self.ClassName, 'GetChaveParaRemocao(Objeto: TObject): Variant'); end; function TRepositorio.IsColecao: Boolean; begin result := false; end; procedure TRepositorio.SetParametroBlob(NomeDoParametro: String; Stream: TMemoryStream); begin self.FQuery.ParamByName(NomeDoParametro).LoadFromStream(Stream, ftBlob); end; procedure TRepositorio.AdicionarEventoDeAtualizarTela( AtualizarTela: TEventoExecutarOperacao); begin self.FAtualizarTela := AtualizarTela; end; function TRepositorio.RemoverPorIdentificador( const Identificador: Variant): Boolean; begin try self.FQuery.SQL.Clear; self.FQuery.SQL.Add(self.SQLRemover); self.FQuery.Params[0].Value := Identificador; self.FQuery.ExecSQL; //self.GravaAuditoria(nil, Objeto, taExclusao); except on E: Exception do dm.LogErros.AdicionaErro('Repositorio', E.ClassName, E.Message); end; end; function TRepositorio.CondicaoSQLGetAll: String; begin raise TExcecaoMetodoNaoImplementado.Create(self.ClassName, 'CondicaoSQLGetAll: String;'); end; end.
//Copyright 2019 Andrey S. Ionisyan (anserion@gmail.com) // //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. //===================================================================== //арифметика кватернионов //===================================================================== unit arith_quaternion; {$mode objfpc}{$H+} interface uses math; type TQuaternion=record a,b,c,d:real; end; TQuaternionVector=array of TQuaternion; TQuaternionMatrix=array of TQuaternionVector; function q_zero:TQuaternion; procedure q_set(var q:TQuaternion; a,b,c,d:real); function q_rnd:TQuaternion; //function q_root_of_one():TQuaternion; function q_dup(q:TQuaternion):TQuaternion; function q_amp(q:TQuaternion):real; function q_amp_bcd(q:TQuaternion):real; function q_arg(q:TQuaternion):real; function q_norm(q:TQuaternion):TQuaternion; function q_conj(q:TQuaternion):TQuaternion; function q_neg(q:TQuaternion):TQuaternion; function q_inv(q:TQuaternion):TQuaternion; function q_add(a,b:TQuaternion):TQuaternion; function q_sub(a,b:TQuaternion):TQuaternion; function q_scalar(lambda:real; q:TQuaternion):TQuaternion; function q_dot(a,b:TQuaternion):real; function q_dot_q(a,b:TQuaternion):TQuaternion; function q_dot_bcd(a,b:TQuaternion):real; function q_cross(a,b:TQuaternion):TQuaternion; function q_cross_bcd(a,b:TQuaternion):TQuaternion; function q_outer(a,b:TQuaternion):TQuaternion; function q_mul(a,b:TQuaternion):TQuaternion; function q_div(a,b:TQuaternion):TQuaternion; function q_cos(q1,q2:TQuaternion):real; function q_i(q:TQuaternion):TQuaternion; function q_exp(q:TQuaternion):TQuaternion; function q_ln(q:TQuaternion):TQuaternion; implementation procedure q_set(var q:TQuaternion; a,b,c,d:real); begin q.a:=a; q.b:=b; q.c:=c; q.d:=d; end; function q_zero:TQuaternion; begin q_zero.a:=0; q_zero.b:=0; q_zero.c:=0; q_zero.d:=0; end; function q_rnd:TQuaternion; begin q_set(q_rnd,random,random,random,random); end; function q_dup(q:TQuaternion):TQuaternion; begin q_dup.a:=q.a; q_dup.b:=q.b; q_dup.c:=q.c; q_dup.d:=q.d; end; function q_conj(q:TQuaternion):TQuaternion; begin q_conj.a:=q.a; q_conj.b:=-q.b; q_conj.c:=-q.c; q_conj.d:=-q.d; end; function q_neg(q:TQuaternion):TQuaternion; begin q_neg.a:=-q.a; q_neg.b:=-q.b; q_neg.c:=-q.c; q_neg.d:=-q.d; end; function q_inv(q:TQuaternion):TQuaternion; begin if (q.a=0) and (q.b=0) and (q.c=0) and (q.d=0) then q_inv:=q_zero else q_inv:=q_scalar(1/(q.a*q.a+q.b*q.b+q.c*q.c+q.d*q.d),q_conj(q)); end; function q_amp(q:TQuaternion):real; begin q_amp:=sqrt(q.a*q.a+q.b*q.b+q.c*q.c+q.d*q.d); end; function q_amp_bcd(q:TQuaternion):real; begin q_amp_bcd:=sqrt(q.b*q.b+q.c*q.c+q.d*q.d); end; function q_arg(q:TQuaternion):real; begin if (q.a=0) and (q.b=0) and (q.c=0) and (q.d=0) then q_arg:=0 else q_arg:=arccos(q.a/q_amp(q)); end; function q_norm(q:TQuaternion):TQuaternion; begin if (q.a=0) and (q.b=0) and (q.c=0) and (q.d=0) then q_norm:=q else q_norm:=q_scalar(1/q_amp(q),q); end; function q_add(a,b:TQuaternion):TQuaternion; begin q_add.a:=a.a+b.a; q_add.b:=a.b+b.b; q_add.c:=a.c+b.c; q_add.d:=a.d+b.d; end; function q_sub(a,b:TQuaternion):TQuaternion; begin q_sub.a:=a.a-b.a; q_sub.b:=a.b-b.b; q_sub.c:=a.c-b.c; q_sub.d:=a.d-b.d; end; function q_scalar(lambda:real; q:TQuaternion):TQuaternion; begin q_scalar.a:=lambda*q.a; q_scalar.b:=lambda*q.b; q_scalar.c:=lambda*q.c; q_scalar.d:=lambda*q.d; end; function q_dot(a,b:TQuaternion):real; begin q_dot:=a.a*b.a+a.b*b.b+a.c*b.c+a.d*b.d; end; function q_dot_bcd(a,b:TQuaternion):real; begin q_dot_bcd:=a.b*b.b+a.c*b.c+a.d*b.d; end; function q_cross(a,b:TQuaternion):TQuaternion; begin q_cross:=q_scalar(0.5,q_sub(q_mul(a,b),q_mul(b,a))); end; function q_dot_q(a,b:TQuaternion):TQuaternion; begin q_dot_q:=q_scalar(0.5,q_add(q_mul(q_conj(a),b),q_mul(q_conj(b),a))); end; function q_cross_bcd(a,b:TQuaternion):TQuaternion; begin q_cross_bcd.a:=0; q_cross_bcd.b:=a.c*b.d-a.d*b.c; q_cross_bcd.c:=a.d*b.b-a.b*b.d; q_cross_bcd.d:=a.b*b.c-a.c*b.b; end; function q_outer(a,b:TQuaternion):TQuaternion; begin q_outer:=q_scalar(0.5,q_sub(q_mul(q_conj(a),b),q_mul(q_conj(b),a))); end; function q_mul(a,b:TQuaternion):TQuaternion; var tmp1,tmp2,tmp3:TQuaternion; begin q_mul.a:=a.a*b.a-q_dot_bcd(a,b); tmp1:=q_scalar(a.a,b); tmp2:=q_scalar(b.a,a); tmp3:=q_cross_bcd(a,b); q_mul.b:=tmp1.b+tmp2.b+tmp3.b; q_mul.c:=tmp1.c+tmp2.c+tmp3.c; q_mul.d:=tmp1.d+tmp2.d+tmp3.d; end; function q_div(a,b:TQuaternion):TQuaternion; begin q_div:=q_mul(a,q_inv(b)); end; function q_cos(q1,q2:TQuaternion):real; var amp1,amp2:real; begin amp1:=q_amp(q1); amp2:=q_amp(q2); if (amp1=0) or (amp2=0) then q_cos:=0 else q_cos:=q_dot(q1,q2)/(amp1*amp2); end; function q_i(q:TQuaternion):TQuaternion; begin if (q.b=0) and (q.c=0) and (q.d=0) then q_i:=q else begin q.a:=0; q_i:=q_scalar(1.0/q_amp(q),q); end; end; function q_exp(q:TQuaternion):TQuaternion; var amp_u:real; tmp,u,i:TQuaternion; begin if (q.a=0) and (q.b=0) and (q.c=0) and (q.d=0) then begin tmp.a:=1; tmp.b:=0; tmp.c:=0; tmp.d:=0; q_exp:=tmp; end else begin u:=q_dup(q); u.a:=0; amp_u:=q_amp(u); i:=q_i(q); tmp:=q_scalar(sin(amp_u),i); tmp.a:=tmp.a+cos(amp_u); q_exp:=q_scalar(exp(amp_u),tmp); end; end; function q_ln(q:TQuaternion):TQuaternion; var amp_q:real; tmp:TQuaternion; begin if (q.a=0) and (q.b=0) and (q.c=0) and (q.d=0) then q_ln:=q_zero else begin amp_q:=q_amp(q); tmp:=q_scalar(q_arg(q),q_i(q)); tmp.a:=tmp.a+ln(amp_q); q_ln:=tmp; end; end; end.
unit Token; interface type TToken = class private FCodigoSeguranca: String; FID: String; procedure SetCodigoSeguranca(const Value: String); procedure setID(const Value: String); public property ID :String read FID write setID; property CodigoSeguranca :String read FCodigoSeguranca write SetCodigoSeguranca; end; implementation { TToken } { TToken } procedure TToken.SetCodigoSeguranca(const Value: String); begin FCodigoSeguranca := Value; end; procedure TToken.setID(const Value: String); begin FID := Value; end; end.
unit DialogPrint; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, AncestorDialogScale, StdCtrls, Mask, Buttons, ExtCtrls, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Vcl.Menus, dxSkinsCore, dxSkinsDefaultPainters, cxControls, cxContainer, cxEdit, cxTextEdit, cxCurrencyEdit, dsdDB, Vcl.ActnList, dsdAction, cxPropertiesStore, dsdAddOn, cxButtons, dxSkinBlack, dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy, dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMoneyTwins, dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus, dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008, dxSkinTheAsphaltWorld, dxSkinValentine, dxSkinVS2010, dxSkinWhiteprint, dxSkinXmas2008Blue, Vcl.ComCtrls, dxCore, cxDateUtils, cxMaskEdit, cxDropDownEdit, cxCalendar; type TDialogPrintForm = class(TAncestorDialogScaleForm) PrintPanel: TPanel; PrintCountEdit: TcxCurrencyEdit; PrintCountLabel: TLabel; PrintIsValuePanel: TPanel; cbPrintMovement: TCheckBox; cbPrintAccount: TCheckBox; cbPrintTransport: TCheckBox; cbPrintQuality: TCheckBox; cbPrintPack: TCheckBox; cbPrintSpec: TCheckBox; cbPrintTax: TCheckBox; cbPrintPreview: TCheckBox; cbPrintPackGross: TCheckBox; cbPrintDiffOrder: TCheckBox; PanelDateValue: TPanel; LabelDateValue: TLabel; DateValueEdit: TcxDateEdit; procedure cbPrintTransportClick(Sender: TObject); procedure cbPrintQualityClick(Sender: TObject); procedure cbPrintTaxClick(Sender: TObject); procedure cbPrintAccountClick(Sender: TObject); procedure cbPrintPackClick(Sender: TObject); procedure cbPrintSpecClick(Sender: TObject); private function Checked: boolean; override;//Проверка корректного ввода в Edit public function Execute(MovementDescId:Integer;CountMovement:Integer; isMovement, isAccount, isTransport, isQuality, isPack, isPackGross, isSpec, isTax : Boolean): Boolean; virtual; end; var DialogPrintForm: TDialogPrintForm; implementation {$R *.dfm} uses UtilScale, DMMainScale; {------------------------------------------------------------------------------} function TDialogPrintForm.Execute(MovementDescId:Integer;CountMovement:Integer; isMovement, isAccount, isTransport, isQuality, isPack, isPackGross, isSpec, isTax : Boolean): Boolean; //Проверка корректного ввода в Edit begin // для ScaleCeh только одна печать if (SettingMain.isCeh = TRUE)or((MovementDescId<>zc_Movement_Sale)and(MovementDescId<>zc_Movement_SendOnPrice)) then cbPrintMovement.Checked:= TRUE else cbPrintMovement.Checked:= isMovement; // PanelDateValue.Visible:= (SettingMain.isCeh = FALSE) or (ParamsMovement.ParamByName('isOperDatePartner').AsBoolean = true); // cbPrintPackGross.Checked:= FALSE; cbPrintDiffOrder.Checked:= FALSE;//(MovementDescId=zc_Movement_Sale)or(MovementDescId=zc_Movement_SendOnPrice); // cbPrintAccount.Enabled:=(SettingMain.isCeh = FALSE);//or(MovementDescId=zc_Movement_Sale)or(MovementDescId<>zc_Movement_SendOnPrice); cbPrintTransport.Enabled:=cbPrintAccount.Enabled; cbPrintQuality.Enabled:=cbPrintAccount.Enabled; cbPrintPack.Enabled:=cbPrintAccount.Enabled; cbPrintSpec.Enabled:=cbPrintAccount.Enabled; cbPrintTax.Enabled:=cbPrintAccount.Enabled; cbPrintDiffOrder.Enabled:=cbPrintAccount.Enabled; // cbPrintAccount.Checked:=(isAccount) and (cbPrintAccount.Enabled); cbPrintTransport.Checked:=(isTransport) and (cbPrintTransport.Enabled); cbPrintQuality.Checked:=(isQuality) and (cbPrintQuality.Enabled); cbPrintPack.Checked:=(isPack) and (cbPrintPack.Enabled); cbPrintSpec.Checked:=(isSpec) and (cbPrintSpec.Enabled); cbPrintTax.Checked:=(isTax) and (cbPrintTax.Enabled); // cbPrintPreview.Checked:=GetArrayList_Value_byName(Default_Array,'isPrintPreview') = AnsiUpperCase('TRUE'); if SettingMain.isCeh = FALSE then PrintCountEdit.Text:=IntToStr(CountMovement) else PrintCountEdit.Text:=GetArrayList_Value_byName(Default_Array,'PrintCount'); // ParamsMovement.ParamByName('isOperDatePartner').AsBoolean:= DMMainScaleForm.gpGet_Scale_Movement_OperDatePartner(ParamsMovement); DateValueEdit.Text:= DateToStr(ParamsMovement.ParamByName('OperDatePartner').AsDateTime); // ActiveControl:=PrintCountEdit; // // Result:=(ShowModal=mrOk); end; function TDialogPrintForm.Checked: boolean; //Проверка корректного ввода в Edit begin Result:=false; // if PanelDateValue.Visible = TRUE then begin try ParamsMovement.ParamByName('OperDatePartner').AsDateTime:= StrToDate(DateValueEdit.Text) except if ParamsMovement.ParamByName('isOperDatePartner').AsBoolean = true then begin ShowMessage('Ошибка.Дата у покупателя сформирована неверно.'); exit; end // еще раз else ParamsMovement.ParamByName('isOperDatePartner').AsBoolean:= DMMainScaleForm.gpGet_Scale_Movement_OperDatePartner(ParamsMovement); end; // if (ParamsMovement.ParamByName('OperDatePartner').AsDateTime < ParamsMovement.ParamByName('OperDate').AsDateTime) and (ParamsMovement.ParamByName('MovementId_find').AsInteger = 0) then begin ShowMessage('Ошибка.Дата у покупателя = <'+DateToStr(ParamsMovement.ParamByName('OperDatePartner').AsDateTime)+'> не может быть раньше даты документа = <'+DateToStr(ParamsMovement.ParamByName('OperDate').AsDateTime)+'>.'); exit; end; if ParamsMovement.ParamByName('OperDatePartner').AsDateTime > 14 + ParamsMovement.ParamByName('OperDate').AsDateTime then begin ShowMessage('Ошибка.Дата у покупателя = <'+DateToStr(ParamsMovement.ParamByName('OperDatePartner').AsDateTime)+'> не может быть позже даты документа = <'+DateToStr(ParamsMovement.ParamByName('OperDate').AsDateTime)+'> более чем на 14 дней.'); exit; end; end; // try Result:=(StrToInt(PrintCountEdit.Text)>0) and (StrToInt(PrintCountEdit.Text)<11); except Result:=false; end; // if not Result then ShowMessage('Ошибка.Значение <Кол-во копий> не попадает в диапазон от <1> до <10>.'); // // if ParamsMovement.ParamByName('isOperDatePartner').AsBoolean = true then if MessageDlg('Документ будет сформирован'+#10+#13+'с Датой покупателя = <'+DateToStr(ParamsMovement.ParamByName('OperDatePartner').AsDateTime)+'>.'+#10+#13+'Продолжить?',mtConfirmation,mbYesNoCancel,0) <> 6 then begin Result:=false; exit; end; end; {------------------------------------------------------------------------------} procedure TDialogPrintForm.cbPrintTransportClick(Sender: TObject); begin if cbPrintTransport.Checked then if (ParamsMovement.ParamByName('MovementDescId').AsInteger<>zc_Movement_Sale) and(ParamsMovement.ParamByName('MovementDescId').AsInteger<>zc_Movement_SendOnPrice) then cbPrintTransport.Checked:=false; end; {------------------------------------------------------------------------------} procedure TDialogPrintForm.cbPrintQualityClick(Sender: TObject); begin if cbPrintQuality.Checked then if (ParamsMovement.ParamByName('MovementDescId').AsInteger<>zc_Movement_Sale) and(ParamsMovement.ParamByName('MovementDescId').AsInteger<>zc_Movement_SendOnPrice) and(ParamsMovement.ParamByName('MovementDescId').AsInteger<>zc_Movement_Loss) then cbPrintQuality.Checked:=false; end; {------------------------------------------------------------------------------} procedure TDialogPrintForm.cbPrintTaxClick(Sender: TObject); begin if cbPrintTax.Checked then if (ParamsMovement.ParamByName('MovementDescId').AsInteger<>zc_Movement_Sale) or (GetArrayList_Value_byName(Default_Array,'isTax') <> AnsiUpperCase('TRUE')) then cbPrintTax.Checked:=false; end; {------------------------------------------------------------------------------} procedure TDialogPrintForm.cbPrintAccountClick(Sender: TObject); begin if cbPrintAccount.Checked then if (ParamsMovement.ParamByName('MovementDescId').AsInteger<>zc_Movement_Sale) then cbPrintAccount.Checked:=false; end; {------------------------------------------------------------------------------} procedure TDialogPrintForm.cbPrintPackClick(Sender: TObject); begin if cbPrintPack.Checked then if (ParamsMovement.ParamByName('MovementDescId').AsInteger<>zc_Movement_Sale)and(ParamsMovement.ParamByName('MovementDescId').AsInteger<>zc_Movement_SendOnPrice) then cbPrintPack.Checked:=false; end; {------------------------------------------------------------------------------} procedure TDialogPrintForm.cbPrintSpecClick(Sender: TObject); begin if cbPrintSpec.Checked then if (ParamsMovement.ParamByName('MovementDescId').AsInteger<>zc_Movement_Sale)and(ParamsMovement.ParamByName('MovementDescId').AsInteger<>zc_Movement_SendOnPrice) then cbPrintSpec.Checked:=false; end; {------------------------------------------------------------------------------} end.
{ } { SplashForm } { } Unit Splash; Interface Uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Gauges, ExtCtrls, XCtrls, XSplash, RXCtrls; type TSplashForm = class(TXSplashForm) Panel1: TPanel; Bevel1: TBevel; Label1: TLabel; Image1: TImage; TaskLabel: TXLabel; AutsLabel: TXLabel; HardLabel: TXLabel; Bevel2: TBevel; Progress: TGauge; ProgressBevel: TBevel; protected function GetHardLabel: String;override; procedure SetHardLabel(Const Value: String);override; function GetTaskLabel: String;override; procedure SetTaskLabel(Const Value: String);override; function GetAutsLabel: String;override; procedure SetAutsLabel(Const Value: String);override; function GetImage: TImage;override; function GetVisProgress: Boolean;override; procedure SetVisProgress(Value: Boolean);override; function GetProgress: Integer;override; procedure SetProgress(Value: Integer);override; procedure SetProgressCount(Value: Integer);override; public { Procedure Init(ACount: Integer; Const ABmp, AHard, ATask, Auts: String);} end; Var SplashForm: TSplashForm=nil; Implementation Uses XMisc, XTFC; {$R *.DFM} Function TSplashForm.GetHardLabel: String; begin Result:=HardLabel.Caption; end; Procedure TSplashForm.SetHardLabel(Const Value: String); begin HardLabel.Caption:=Value; end; Function TSplashForm.GetTaskLabel: String; begin Result:=TaskLabel.Caption; end; Procedure TSplashForm.SetTaskLabel(Const Value: String); begin TaskLabel.Caption:=Value; end; Function TSplashForm.GetAutsLabel: String; begin Result:=AutsLabel.Caption; end; Procedure TSplashForm.SetAutsLabel(Const Value: String); begin AutsLabel.Caption:=Value; end; Function TSplashForm.GetImage: TImage; begin Result:=Image1; end; Function TSplashForm.GetVisProgress: Boolean; begin Result:=Progress.Visible; end; Procedure TSplashForm.SetVisProgress(Value: Boolean); begin if Value then begin Progress.Visible:=True; ProgressBevel.Visible:=True; end else begin Progress.Visible:=False; ProgressBevel.Visible:=False; end; end; Function TSplashForm.GetProgress: Integer; begin Result:=Progress.Progress; end; Procedure TSplashForm.SetProgress(Value: Integer); begin Progress.Progress:=Value; Update; end; Procedure TSplashForm.SetProgressCount(Value: Integer); begin Inherited; Progress.MaxValue:=GetProgressCount*10; Show; end; { Procedure TSplashForm.Init(ACount: Integer; Const ABmp, AHard, ATask, Auts: String); begin if AHard<>'' then HardLab.Caption:=AHard; if ATask<>'' then TaskLab.Caption:=ATask; if Auts<>'' then AutsLab.Caption:=Auts; if ABmp<>'' then Image1.Picture.LoadFromFile(ABmp); XProgressCount:=ACount; end; } Initialization RegisterAliasXSplash(scDefaultClass, TSplashForm); Finalization UnRegisterXSplash(TSplashForm); end.
unit uFuncoes; interface uses DB, SysUtils, Classes, Forms, Dialogs, Windows, Messages, Graphics, ExtCtrls, ADODB; procedure VerticalText(Form : TForm; Texto1, Texto2 : String; Top : Integer; FontSize : Integer);overload; procedure VerticalText(img : TImage; Texto1, Texto2 : String; Top : Integer; FontSize : Integer);overload; function GetLocalVersion: String; function cript(str: WideString): WideString; implementation /// <summary> /// Escreve texto na vertical. /// </summary> procedure VerticalText(Form : TForm; Texto1, Texto2 : String; Top : Integer; FontSize : Integer); var lf : TLogFont; tf : TFont; Fonte : String; TamanhoFont : Integer; begin Fonte := 'Arial'; TamanhoFont := FontSize; with Form.Canvas do begin SetBkMode(Handle, TRANSPARENT); Font.Name := Fonte; Font.Size := TamanhoFont; Font.Color := clWhite; Font.Style := [fsBold]; tf := TFont.Create; tf.Assign(Font); GetObject(tf.Handle, sizeof(lf), @lf); lf.lfEscapement := 900; lf.lfOrientation := 300; tf.Handle := CreateFontIndirect(lf); Font.Assign(tf); tf.Free; TextOut(5,Top,Texto1); end; with Form.Canvas do begin SetBkMode(Handle, TRANSPARENT); Font.Name := 'Arial'; Font.Size := 10; Font.Color := clBlack; Font.Style := [fsBold]; tf := TFont.Create; tf.Assign(Font); GetObject(tf.Handle, sizeof(lf), @lf); lf.lfEscapement := 900; lf.lfOrientation := 400; tf.Handle := CreateFontIndirect(lf); Font.Assign(tf); tf.Free; TextOut(50,Top,Texto2); end; end; /// <summary> /// Escreve texto na vertical. /// </summary> procedure VerticalText(Img : TImage; Texto1, Texto2 : String; Top : Integer; FontSize : Integer);overload; var lf : TLogFont; tf : TFont; Fonte : String; TamanhoFont : Integer; begin Fonte := 'Arial'; TamanhoFont := FontSize; with Img.Canvas do begin SetBkMode(Handle, TRANSPARENT); Font.Name := Fonte; Font.Size := TamanhoFont; Font.Color := clWhite; Font.Style := [fsBold]; tf := TFont.Create; tf.Assign(Font); GetObject(tf.Handle, sizeof(lf), @lf); lf.lfEscapement := 900; lf.lfOrientation := 300; tf.Handle := CreateFontIndirect(lf); Font.Assign(tf); tf.Free; TextOut(-2,Top,Texto1); end; with Img.Canvas do begin SetBkMode(Handle, TRANSPARENT); Font.Name := 'Arial'; Font.Size := 10; Font.Color := clBlack; Font.Style := [fsBold]; tf := TFont.Create; tf.Assign(Font); GetObject(tf.Handle, sizeof(lf), @lf); lf.lfEscapement := 900; lf.lfOrientation := 400; tf.Handle := CreateFontIndirect(lf); Font.Assign(tf); tf.Free; TextOut(45,Top,Texto2); end; end; /// <summary> /// Retorna versão do executável atual. /// </summary> function GetLocalVersion: String; type PFFI = ^vs_FixedFileInfo; var F : PFFI; Handle : Dword; Len : Longint; Data : Pchar; Buffer : Pointer; Tamanho : Dword; Parquivo: Pchar; Arquivo : String; begin Arquivo := Application.ExeName; Parquivo := StrAlloc(Length(Arquivo) + 1); StrPcopy(Parquivo, Arquivo); Len := GetFileVersionInfoSize(Parquivo, Handle); Result := ''; if Len > 0 then begin Data:=StrAlloc(Len+1); if GetFileVersionInfo(Parquivo,Handle,Len,Data) then begin VerQueryValue(Data, '',Buffer,Tamanho); F := PFFI(Buffer); Result := Format('%d.%d.%d.%d', [HiWord(F^.dwFileVersionMs), LoWord(F^.dwFileVersionMs), HiWord(F^.dwFileVersionLs), Loword(F^.dwFileVersionLs)] ); end; StrDispose(Data); end; StrDispose(Parquivo); end; function cript(str: WideString): WideString; var c: integer; begin result := ''; for c := 1 to length(str) do result := chr(ord(str[c]) xor $DD) + result; end; end.
unit Services.Hospedes; interface uses System.SysUtils, System.Classes, 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, System.JSON, DataSet.Serialize, FireDAC.UI.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Phys, FireDAC.Phys.MySQL, FireDAC.Phys.MySQLDef, FireDAC.VCLUI.Wait, FireDAC.ConsoleUI.Wait, FireDAC.FMXUI.Wait; type TServiceHospedes = class(TDataModule) qryCadastroHospedes: TFDQuery; qryPesquisaHospedes: TFDQuery; qryCadastroHospedesID: TFDAutoIncField; qryCadastroHospedesNOME: TStringField; qryCadastroHospedesdocumento: TStringField; qryCadastroHospedestelefone: TStringField; qryPesquisaHospedesID: TFDAutoIncField; qryPesquisaHospedesNOME: TStringField; qryPesquisaHospedesdocumento: TStringField; qryPesquisaHospedestelefone: TStringField; procedure DataModuleCreate(Sender: TObject); private { Private declarations } public function ListAll: TFDQuery; function Append(const AJson: TJSONObject): Boolean; procedure Delete(AId: integer); function Update(const AJson: TJSONObject; AId: integer): Boolean; function GetById(const AId: string): TFDQuery; end; implementation uses Services.Connection; {%CLASSGROUP 'FMX.Controls.TControl'} {$R *.dfm} { TServiceHospedes } function TServiceHospedes.Append(const AJson: TJSONObject): Boolean; begin qryCadastroHospedes.SQL.Add('where 1<>1'); qryCadastroHospedes.Open(); qryCadastroHospedes.LoadFromJSON(AJson, False); Result := qryCadastroHospedes.ApplyUpdates(0) = 0; end; procedure TServiceHospedes.DataModuleCreate(Sender: TObject); begin qryCadastroHospedes.Active := True; qryPesquisaHospedes.Active := True; end; procedure TServiceHospedes.Delete(AId: integer); begin qryCadastroHospedes.SQL.Clear; qryCadastroHospedes.SQL.Add('DELETE FROM HOSPEDES WHERE ID = :ID'); qryCadastroHospedes.ParamByName('ID').Value := AId; qryCadastroHospedes.ExecSQL; end; function TServiceHospedes.GetById(const AId: string): TFDQuery; begin qryCadastroHospedes.SQL.Add('where id = :id'); qryCadastroHospedes.ParamByName('id').AsInteger := AId.ToInteger; qryCadastroHospedes.Open(); Result := qryCadastroHospedes; end; function TServiceHospedes.ListAll: TFDQuery; begin qryPesquisaHospedes.Open(); Result := qryPesquisaHospedes; end; function TServiceHospedes.Update(const AJson: TJSONObject; AId: integer): Boolean; begin qryCadastroHospedes.Close; qryCadastroHospedes.SQL.Add('where id = :id'); qryCadastroHospedes.ParamByName('ID').Value := AId; qryCadastroHospedes.Open(); qryCadastroHospedes.MergeFromJSONObject(AJson, False); Result := qryCadastroHospedes.ApplyUpdates(0) = 0; end; end.
{ ID:because3 PROG:rockers LANG:PASCAL } program rockers; var f:array [0..20,0..20,0..20] of longint; s:array [1..20] of longint; n,t,m,i,j,k:longint; function max(a,b:longint):longint; begin if a>b then exit(a) else exit(b); end; BEGIN assign(input,'rockers.in'); reset(input); assign(output,'rockers.out'); rewrite(output); readln(n,t,m); for i:=1 to n do read(s[i]); close(input); fillchar(f,sizeof(f),0); for i:=1 to n do for j:=1 to m do for k:=1 to t do begin f[i,j,k]:=max(f[i,j-1,t],f[i-1,j,k]); if k>=s[i] then f[i,j,k]:=max(f[i,j,k],max(f[i-1,j,k-s[i]],f[i-1,j-1,t])+1); end; writeln(f[n,m,t]); close(output); END.
// ************************************************************************ // // The types declared in this file were generated from data read from the // WSDL File described below: // WSDL : http://carme/secure/ws/awsi/LpsDataServer.php?wsdl // Encoding : ISO-8859-1 // Version : 1.0 // (9/9/2013 7:07:38 AM - 1.33.2.5) // ************************************************************************ // unit AWSI_Server_LPSData; interface uses InvokeRegistry, SOAPHTTPClient, Types, XSBuiltIns; type // ************************************************************************ // // The following types, referred to in the WSDL document are not being represented // in this file. They are either aliases[@] of other types represented or were referred // to but never[!] declared in the document. The types from the latter category // typically map to predefined/known XML or Borland types; however, they could also // indicate incorrect WSDL documents that failed to declare or import a schema type. // ************************************************************************ // // !:string - "http://www.w3.org/2001/XMLSchema" // !:int - "http://www.w3.org/2001/XMLSchema" // !:float - "http://www.w3.org/2001/XMLSchema" // !:integer - "http://www.w3.org/2001/XMLSchema" clsUserCredentials = class; { "http://carme/secure/ws/WSDL" } clsCircle = class; { "http://carme/secure/ws/WSDL" } clsPointItem = class; { "http://carme/secure/ws/WSDL" } clsShapeItem = class; { "http://carme/secure/ws/WSDL" } clsCompsRequest = class; { "http://carme/secure/ws/WSDL" } clsResults = class; { "http://carme/secure/ws/WSDL" } clsSaleHistoryItem = class; { "http://carme/secure/ws/WSDL" } clsAcknowledgementResponseData = class; { "http://carme/secure/ws/WSDL" } clsAcknowledgementResponse = class; { "http://carme/secure/ws/WSDL" } clsSubjectProperty = class; { "http://carme/secure/ws/WSDL" } clsXml178Data = class; { "http://carme/secure/ws/WSDL" } clsGetSubjectInformation = class; { "http://carme/secure/ws/WSDL" } clsGetSubjectInformationResponse = class; { "http://carme/secure/ws/WSDL" } clsXml179Data = class; { "http://carme/secure/ws/WSDL" } clsNeighborhoodCompsCount = class; { "http://carme/secure/ws/WSDL" } clsGetNeighborhoodCompsCountResponse = class; { "http://carme/secure/ws/WSDL" } clsCompsRecord177ArrayItem = class; { "http://carme/secure/ws/WSDL" } clsXml174Data = class; { "http://carme/secure/ws/WSDL" } clsGetStandardComps = class; { "http://carme/secure/ws/WSDL" } clsGetStandardCompsResponse = class; { "http://carme/secure/ws/WSDL" } clsCompsRecords = class; { "http://carme/secure/ws/WSDL" } clsXml177Data = class; { "http://carme/secure/ws/WSDL" } clsGet50NeighborhoodComps = class; { "http://carme/secure/ws/WSDL" } clsGet50NeighborhoodCompsResponse = class; { "http://carme/secure/ws/WSDL" } clsXml175Data = class; { "http://carme/secure/ws/WSDL" } clsGetNeighborhoodComps500 = class; { "http://carme/secure/ws/WSDL" } clsGetNeighborhoodComps500Response = class; { "http://carme/secure/ws/WSDL" } clsGetUsageAvailabilityData = class; { "http://carme/secure/ws/WSDL" } clsGetUsageAvailabilityResponse = class; { "http://carme/secure/ws/WSDL" } clsAcknowledgement = class; { "http://carme/secure/ws/WSDL" } clsGetSubjectInformationRequest = class; { "http://carme/secure/ws/WSDL" } clsGetNeighborhoodCompsCountRequest = class; { "http://carme/secure/ws/WSDL" } clsGetStandardCompsRequest = class; { "http://carme/secure/ws/WSDL" } clsGet50NeighborhoodCompsRequest = class; { "http://carme/secure/ws/WSDL" } clsGetNeighborhoodComps500Request = class; { "http://carme/secure/ws/WSDL" } clsUsageAccessCredentials = class; { "http://carme/secure/ws/WSDL" } // ************************************************************************ // // Namespace : http://carme/secure/ws/WSDL // ************************************************************************ // clsUserCredentials = class(TRemotable) private FUsername: WideString; FPassword: WideString; FCompanyKey: WideString; FOrderNumberKey: WideString; FPurchase: Integer; FCustomerOrderNumber: WideString; published property Username: WideString read FUsername write FUsername; property Password: WideString read FPassword write FPassword; property CompanyKey: WideString read FCompanyKey write FCompanyKey; property OrderNumberKey: WideString read FOrderNumberKey write FOrderNumberKey; property Purchase: Integer read FPurchase write FPurchase; property CustomerOrderNumber: WideString read FCustomerOrderNumber write FCustomerOrderNumber; end; // ************************************************************************ // // Namespace : http://carme/secure/ws/WSDL // ************************************************************************ // clsCircle = class(TRemotable) private FLongitude: Single; FLatitude: Single; Fradius: Single; published property Longitude: Single read FLongitude write FLongitude; property Latitude: Single read FLatitude write FLatitude; property radius: Single read Fradius write Fradius; end; // ************************************************************************ // // Namespace : http://carme/secure/ws/WSDL // ************************************************************************ // clsPointItem = class(TRemotable) private FLongitude: Single; FLatitude: Single; published property Longitude: Single read FLongitude write FLongitude; property Latitude: Single read FLatitude write FLatitude; end; clsPointsArray = array of clsPointItem; { "http://carme/secure/ws/WSDL" } // ************************************************************************ // // Namespace : http://carme/secure/ws/WSDL // ************************************************************************ // clsShapeItem = class(TRemotable) private FCircle: clsCircle; FPoints: clsPointsArray; public destructor Destroy; override; published property Circle: clsCircle read FCircle write FCircle; property Points: clsPointsArray read FPoints write FPoints; end; clsShapesArray = array of clsShapeItem; { "http://carme/secure/ws/WSDL" } // ************************************************************************ // // Namespace : http://carme/secure/ws/WSDL // ************************************************************************ // clsCompsRequest = class(TRemotable) private FNumComps: integer; FShapes: clsShapesArray; FStartDate: WideString; FEndDate: WideString; public destructor Destroy; override; published property NumComps: integer read FNumComps write FNumComps; property Shapes: clsShapesArray read FShapes write FShapes; property StartDate: WideString read FStartDate write FStartDate; property EndDate: WideString read FEndDate write FEndDate; end; // ************************************************************************ // // Namespace : http://carme/secure/ws/WSDL // ************************************************************************ // clsResults = class(TRemotable) private FCode: Integer; FType_: WideString; FDescription: WideString; published property Code: Integer read FCode write FCode; property Type_: WideString read FType_ write FType_; property Description: WideString read FDescription write FDescription; end; // ************************************************************************ // // Namespace : http://carme/secure/ws/WSDL // ************************************************************************ // clsSaleHistoryItem = class(TRemotable) private FBuyer1FirstName: WideString; FBuyer1LastName: WideString; FBuyer2FirstName: WideString; FBuyer2LastName: WideString; FSeller1FirstName: WideString; FSeller1LastName: WideString; FSeller2FirstName: WideString; FSeller2LastName: WideString; FDeedType: WideString; FSalePrice: WideString; FSaleDate: WideString; FREOFlag: WideString; published property Buyer1FirstName: WideString read FBuyer1FirstName write FBuyer1FirstName; property Buyer1LastName: WideString read FBuyer1LastName write FBuyer1LastName; property Buyer2FirstName: WideString read FBuyer2FirstName write FBuyer2FirstName; property Buyer2LastName: WideString read FBuyer2LastName write FBuyer2LastName; property Seller1FirstName: WideString read FSeller1FirstName write FSeller1FirstName; property Seller1LastName: WideString read FSeller1LastName write FSeller1LastName; property Seller2FirstName: WideString read FSeller2FirstName write FSeller2FirstName; property Seller2LastName: WideString read FSeller2LastName write FSeller2LastName; property DeedType: WideString read FDeedType write FDeedType; property SalePrice: WideString read FSalePrice write FSalePrice; property SaleDate: WideString read FSaleDate write FSaleDate; property REOFlag: WideString read FREOFlag write FREOFlag; end; clsSalesHistory = array of clsSaleHistoryItem; { "http://carme/secure/ws/WSDL" } // ************************************************************************ // // Namespace : http://carme/secure/ws/WSDL // ************************************************************************ // clsAcknowledgementResponseData = class(TRemotable) private FReceived: Integer; published property Received: Integer read FReceived write FReceived; end; // ************************************************************************ // // Namespace : http://carme/secure/ws/WSDL // ************************************************************************ // clsAcknowledgementResponse = class(TRemotable) private FResults: clsResults; FResponseData: clsAcknowledgementResponseData; public destructor Destroy; override; published property Results: clsResults read FResults write FResults; property ResponseData: clsAcknowledgementResponseData read FResponseData write FResponseData; end; // ************************************************************************ // // Namespace : http://carme/secure/ws/WSDL // ************************************************************************ // clsSubjectProperty = class(TRemotable) private FAddress: WideString; FAPN: WideString; FAssessedImproveValue: WideString; FAssessedLandValue: WideString; FAssessmentYear: WideString; FBasement: WideString; FBasementFinish: WideString; FBath: WideString; FBedrooms: WideString; FBriefLegalDescription: WideString; FCensusTract: WideString; FCity: WideString; FCounty: WideString; FDesignStyle: WideString; FFireplace: WideString; FGarage: WideString; FGarageNum: WideString; FGarageType: WideString; FGLA: WideString; FLatitude: WideString; FLongitude: WideString; FLotSize: WideString; FOwner: WideString; FPool: WideString; FState: WideString; FStories: WideString; FSubdivisionName: WideString; FTaxes: WideString; FTaxYear: WideString; FTotalAssessedValue: WideString; FTotalRooms: WideString; FUseCode: WideString; FYearBuilt: WideString; FZip: WideString; FZip4: WideString; FSalesHistory: clsSalesHistory; public destructor Destroy; override; published property Address: WideString read FAddress write FAddress; property APN: WideString read FAPN write FAPN; property AssessedImproveValue: WideString read FAssessedImproveValue write FAssessedImproveValue; property AssessedLandValue: WideString read FAssessedLandValue write FAssessedLandValue; property AssessmentYear: WideString read FAssessmentYear write FAssessmentYear; property Basement: WideString read FBasement write FBasement; property BasementFinish: WideString read FBasementFinish write FBasementFinish; property Bath: WideString read FBath write FBath; property Bedrooms: WideString read FBedrooms write FBedrooms; property BriefLegalDescription: WideString read FBriefLegalDescription write FBriefLegalDescription; property CensusTract: WideString read FCensusTract write FCensusTract; property City: WideString read FCity write FCity; property County: WideString read FCounty write FCounty; property DesignStyle: WideString read FDesignStyle write FDesignStyle; property Fireplace: WideString read FFireplace write FFireplace; property Garage: WideString read FGarage write FGarage; property GarageNum: WideString read FGarageNum write FGarageNum; property GarageType: WideString read FGarageType write FGarageType; property GLA: WideString read FGLA write FGLA; property Latitude: WideString read FLatitude write FLatitude; property Longitude: WideString read FLongitude write FLongitude; property LotSize: WideString read FLotSize write FLotSize; property Owner: WideString read FOwner write FOwner; property Pool: WideString read FPool write FPool; property State: WideString read FState write FState; property Stories: WideString read FStories write FStories; property SubdivisionName: WideString read FSubdivisionName write FSubdivisionName; property Taxes: WideString read FTaxes write FTaxes; property TaxYear: WideString read FTaxYear write FTaxYear; property TotalAssessedValue: WideString read FTotalAssessedValue write FTotalAssessedValue; property TotalRooms: WideString read FTotalRooms write FTotalRooms; property UseCode: WideString read FUseCode write FUseCode; property YearBuilt: WideString read FYearBuilt write FYearBuilt; property Zip: WideString read FZip write FZip; property Zip4: WideString read FZip4 write FZip4; property SalesHistory: clsSalesHistory read FSalesHistory write FSalesHistory; end; // ************************************************************************ // // Namespace : http://carme/secure/ws/WSDL // ************************************************************************ // clsXml178Data = class(TRemotable) private FDateTimeStamp: WideString; FErrorMsg: WideString; FOrderGUID: WideString; FStatus: WideString; FSubjectProperty: clsSubjectProperty; public destructor Destroy; override; published property DateTimeStamp: WideString read FDateTimeStamp write FDateTimeStamp; property ErrorMsg: WideString read FErrorMsg write FErrorMsg; property OrderGUID: WideString read FOrderGUID write FOrderGUID; property Status: WideString read FStatus write FStatus; property SubjectProperty: clsSubjectProperty read FSubjectProperty write FSubjectProperty; end; // ************************************************************************ // // Namespace : http://carme/secure/ws/WSDL // ************************************************************************ // clsGetSubjectInformation = class(TRemotable) private FXml178Data: clsXml178Data; FServiceAcknowledgement: WideString; public destructor Destroy; override; published property Xml178Data: clsXml178Data read FXml178Data write FXml178Data; property ServiceAcknowledgement: WideString read FServiceAcknowledgement write FServiceAcknowledgement; end; // ************************************************************************ // // Namespace : http://carme/secure/ws/WSDL // ************************************************************************ // clsGetSubjectInformationResponse = class(TRemotable) private FResults: clsResults; FResponseData: clsGetSubjectInformation; public destructor Destroy; override; published property Results: clsResults read FResults write FResults; property ResponseData: clsGetSubjectInformation read FResponseData write FResponseData; end; // ************************************************************************ // // Namespace : http://carme/secure/ws/WSDL // ************************************************************************ // clsXml179Data = class(TRemotable) private FDateTimeStamp: WideString; FErrorMsg: WideString; FOrderGUID: WideString; FStatus: WideString; FTotalProperties: WideString; published property DateTimeStamp: WideString read FDateTimeStamp write FDateTimeStamp; property ErrorMsg: WideString read FErrorMsg write FErrorMsg; property OrderGUID: WideString read FOrderGUID write FOrderGUID; property Status: WideString read FStatus write FStatus; property TotalProperties: WideString read FTotalProperties write FTotalProperties; end; // ************************************************************************ // // Namespace : http://carme/secure/ws/WSDL // ************************************************************************ // clsNeighborhoodCompsCount = class(TRemotable) private FXml179Data: clsXml179Data; FServiceAcknowledgement: WideString; public destructor Destroy; override; published property Xml179Data: clsXml179Data read FXml179Data write FXml179Data; property ServiceAcknowledgement: WideString read FServiceAcknowledgement write FServiceAcknowledgement; end; // ************************************************************************ // // Namespace : http://carme/secure/ws/WSDL // ************************************************************************ // clsGetNeighborhoodCompsCountResponse = class(TRemotable) private FResults: clsResults; FResponseData: clsNeighborhoodCompsCount; public destructor Destroy; override; published property Results: clsResults read FResults write FResults; property ResponseData: clsNeighborhoodCompsCount read FResponseData write FResponseData; end; // ************************************************************************ // // Namespace : http://carme/secure/ws/WSDL // ************************************************************************ // clsCompsRecord177ArrayItem = class(TRemotable) private FProximity: WideString; FSiteAddress: WideString; FSiteUnit: WideString; FSiteUnitType: WideString; FSiteCity: WideString; FSiteState: WideString; FSiteZip: WideString; FSiteZip4: WideString; FRecordingDate: WideString; FSalePrice: WideString; FAssessmentValue: WideString; FPriceperSquareFoot: WideString; FBuildingArea: WideString; FTotalRooms: WideString; FBedrooms: WideString; FBaths: WideString; FYearBuilt: WideString; FLotSize: WideString; FPool: WideString; FFireplace: WideString; FAPN: WideString; FDocumentNumber: WideString; FDocumentType: WideString; FPriceCode: WideString; FUseCodeDescription: WideString; FLotCode: WideString; FLotNumber: WideString; FBlock: WideString; FSection: WideString; FDistrict: WideString; FLandLot: WideString; FUnit_: WideString; FCityMunicipalityTownship: WideString; FSubdivisionName: WideString; FPhaseNumber: WideString; FTractNumber: WideString; FLegalBriefDescription: WideString; FSectionTownshipRangeMeridian: WideString; FMapReference: WideString; FGarageType: WideString; FGarageNums: WideString; FCounty: WideString; FTaxes: WideString; FTaxYear: WideString; FLatitude: WideString; FLongitude: WideString; FBasementFinished: WideString; FCensusTract: WideString; FBasement: WideString; FDesign: WideString; FSalesHistory: clsSalesHistory; public destructor Destroy; override; published property Proximity: WideString read FProximity write FProximity; property SiteAddress: WideString read FSiteAddress write FSiteAddress; property SiteUnit: WideString read FSiteUnit write FSiteUnit; property SiteUnitType: WideString read FSiteUnitType write FSiteUnitType; property SiteCity: WideString read FSiteCity write FSiteCity; property SiteState: WideString read FSiteState write FSiteState; property SiteZip: WideString read FSiteZip write FSiteZip; property SiteZip4: WideString read FSiteZip4 write FSiteZip4; property RecordingDate: WideString read FRecordingDate write FRecordingDate; property SalePrice: WideString read FSalePrice write FSalePrice; property AssessmentValue: WideString read FAssessmentValue write FAssessmentValue; property PriceperSquareFoot: WideString read FPriceperSquareFoot write FPriceperSquareFoot; property BuildingArea: WideString read FBuildingArea write FBuildingArea; property TotalRooms: WideString read FTotalRooms write FTotalRooms; property Bedrooms: WideString read FBedrooms write FBedrooms; property Baths: WideString read FBaths write FBaths; property YearBuilt: WideString read FYearBuilt write FYearBuilt; property LotSize: WideString read FLotSize write FLotSize; property Pool: WideString read FPool write FPool; property Fireplace: WideString read FFireplace write FFireplace; property APN: WideString read FAPN write FAPN; property DocumentNumber: WideString read FDocumentNumber write FDocumentNumber; property DocumentType: WideString read FDocumentType write FDocumentType; property PriceCode: WideString read FPriceCode write FPriceCode; property UseCodeDescription: WideString read FUseCodeDescription write FUseCodeDescription; property LotCode: WideString read FLotCode write FLotCode; property LotNumber: WideString read FLotNumber write FLotNumber; property Block: WideString read FBlock write FBlock; property Section: WideString read FSection write FSection; property District: WideString read FDistrict write FDistrict; property LandLot: WideString read FLandLot write FLandLot; property Unit_: WideString read FUnit_ write FUnit_; property CityMunicipalityTownship: WideString read FCityMunicipalityTownship write FCityMunicipalityTownship; property SubdivisionName: WideString read FSubdivisionName write FSubdivisionName; property PhaseNumber: WideString read FPhaseNumber write FPhaseNumber; property TractNumber: WideString read FTractNumber write FTractNumber; property LegalBriefDescription: WideString read FLegalBriefDescription write FLegalBriefDescription; property SectionTownshipRangeMeridian: WideString read FSectionTownshipRangeMeridian write FSectionTownshipRangeMeridian; property MapReference: WideString read FMapReference write FMapReference; property GarageType: WideString read FGarageType write FGarageType; property GarageNums: WideString read FGarageNums write FGarageNums; property County: WideString read FCounty write FCounty; property Taxes: WideString read FTaxes write FTaxes; property TaxYear: WideString read FTaxYear write FTaxYear; property Latitude: WideString read FLatitude write FLatitude; property Longitude: WideString read FLongitude write FLongitude; property BasementFinished: WideString read FBasementFinished write FBasementFinished; property CensusTract: WideString read FCensusTract write FCensusTract; property Basement: WideString read FBasement write FBasement; property Design: WideString read FDesign write FDesign; property SalesHistory: clsSalesHistory read FSalesHistory write FSalesHistory; end; clsCompsRecord = array of clsCompsRecord177ArrayItem; { "http://carme/secure/ws/WSDL" } // ************************************************************************ // // Namespace : http://carme/secure/ws/WSDL // ************************************************************************ // clsXml174Data = class(TRemotable) private FDateTimeStamp: WideString; FErrorMsg: WideString; FOrderGUID: WideString; FStatus: WideString; FCompsRecords: clsCompsRecord; public destructor Destroy; override; published property DateTimeStamp: WideString read FDateTimeStamp write FDateTimeStamp; property ErrorMsg: WideString read FErrorMsg write FErrorMsg; property OrderGUID: WideString read FOrderGUID write FOrderGUID; property Status: WideString read FStatus write FStatus; property CompsRecords: clsCompsRecord read FCompsRecords write FCompsRecords; end; // ************************************************************************ // // Namespace : http://carme/secure/ws/WSDL // ************************************************************************ // clsGetStandardComps = class(TRemotable) private FXml179Data: clsXml174Data; FServiceAcknowledgement: WideString; public destructor Destroy; override; published property Xml179Data: clsXml174Data read FXml179Data write FXml179Data; property ServiceAcknowledgement: WideString read FServiceAcknowledgement write FServiceAcknowledgement; end; // ************************************************************************ // // Namespace : http://carme/secure/ws/WSDL // ************************************************************************ // clsGetStandardCompsResponse = class(TRemotable) private FResults: clsResults; FResponseData: clsGetStandardComps; public destructor Destroy; override; published property Results: clsResults read FResults write FResults; property ResponseData: clsGetStandardComps read FResponseData write FResponseData; end; // ************************************************************************ // // Namespace : http://carme/secure/ws/WSDL // ************************************************************************ // clsCompsRecords = class(TRemotable) private FCompsRecord: clsCompsRecord; public destructor Destroy; override; published property CompsRecord: clsCompsRecord read FCompsRecord write FCompsRecord; end; // ************************************************************************ // // Namespace : http://carme/secure/ws/WSDL // ************************************************************************ // clsXml177Data = class(TRemotable) private FDateTimeStamp: WideString; FErrorMsg: WideString; FOrderGUID: WideString; FStatus: WideString; FCompsRecords: clsCompsRecords; public destructor Destroy; override; published property DateTimeStamp: WideString read FDateTimeStamp write FDateTimeStamp; property ErrorMsg: WideString read FErrorMsg write FErrorMsg; property OrderGUID: WideString read FOrderGUID write FOrderGUID; property Status: WideString read FStatus write FStatus; property CompsRecords: clsCompsRecords read FCompsRecords write FCompsRecords; end; // ************************************************************************ // // Namespace : http://carme/secure/ws/WSDL // ************************************************************************ // clsGet50NeighborhoodComps = class(TRemotable) private FXml177Data: clsXml177Data; FServiceAcknowledgement: WideString; public destructor Destroy; override; published property Xml177Data: clsXml177Data read FXml177Data write FXml177Data; property ServiceAcknowledgement: WideString read FServiceAcknowledgement write FServiceAcknowledgement; end; // ************************************************************************ // // Namespace : http://carme/secure/ws/WSDL // ************************************************************************ // clsGet50NeighborhoodCompsResponse = class(TRemotable) private FResults: clsResults; FResponseData: clsGet50NeighborhoodComps; public destructor Destroy; override; published property Results: clsResults read FResults write FResults; property ResponseData: clsGet50NeighborhoodComps read FResponseData write FResponseData; end; // ************************************************************************ // // Namespace : http://carme/secure/ws/WSDL // ************************************************************************ // clsXml175Data = class(TRemotable) private FDateTimeStamp: WideString; FErrorMsg: WideString; FOrderGUID: WideString; FStatus: WideString; FOutputURL: WideString; published property DateTimeStamp: WideString read FDateTimeStamp write FDateTimeStamp; property ErrorMsg: WideString read FErrorMsg write FErrorMsg; property OrderGUID: WideString read FOrderGUID write FOrderGUID; property Status: WideString read FStatus write FStatus; property OutputURL: WideString read FOutputURL write FOutputURL; end; // ************************************************************************ // // Namespace : http://carme/secure/ws/WSDL // ************************************************************************ // clsGetNeighborhoodComps500 = class(TRemotable) private FXml175Data: clsXml175Data; FServiceAcknowledgement: WideString; public destructor Destroy; override; published property Xml175Data: clsXml175Data read FXml175Data write FXml175Data; property ServiceAcknowledgement: WideString read FServiceAcknowledgement write FServiceAcknowledgement; end; // ************************************************************************ // // Namespace : http://carme/secure/ws/WSDL // ************************************************************************ // clsGetNeighborhoodComps500Response = class(TRemotable) private FResults: clsResults; FResponseData: clsGetNeighborhoodComps500; public destructor Destroy; override; published property Results: clsResults read FResults write FResults; property ResponseData: clsGetNeighborhoodComps500 read FResponseData write FResponseData; end; // ************************************************************************ // // Namespace : http://carme/secure/ws/WSDL // ************************************************************************ // clsGetUsageAvailabilityData = class(TRemotable) private FServiceName: WideString; FWebServiceId: Integer; FProductAvailable: WideString; FMessage: WideString; FExpirationDate: WideString; FAppraiserQuantity: Integer; FOwnerQuantity: Integer; published property ServiceName: WideString read FServiceName write FServiceName; property WebServiceId: Integer read FWebServiceId write FWebServiceId; property ProductAvailable: WideString read FProductAvailable write FProductAvailable; property Message: WideString read FMessage write FMessage; property ExpirationDate: WideString read FExpirationDate write FExpirationDate; property AppraiserQuantity: Integer read FAppraiserQuantity write FAppraiserQuantity; property OwnerQuantity: Integer read FOwnerQuantity write FOwnerQuantity; end; // ************************************************************************ // // Namespace : http://carme/secure/ws/WSDL // ************************************************************************ // clsGetUsageAvailabilityResponse = class(TRemotable) private FResults: clsResults; FResponseData: clsGetUsageAvailabilityData; public destructor Destroy; override; published property Results: clsResults read FResults write FResults; property ResponseData: clsGetUsageAvailabilityData read FResponseData write FResponseData; end; // ************************************************************************ // // Namespace : http://carme/secure/ws/WSDL // ************************************************************************ // clsAcknowledgement = class(TRemotable) private FReceived: Integer; FServiceAcknowledgement: WideString; published property Received: Integer read FReceived write FReceived; property ServiceAcknowledgement: WideString read FServiceAcknowledgement write FServiceAcknowledgement; end; // ************************************************************************ // // Namespace : http://carme/secure/ws/WSDL // ************************************************************************ // clsGetSubjectInformationRequest = class(TRemotable) private FStreetAddress: WideString; FCity: WideString; FState: WideString; FZip: WideString; FOwnerName: WideString; published property StreetAddress: WideString read FStreetAddress write FStreetAddress; property City: WideString read FCity write FCity; property State: WideString read FState write FState; property Zip: WideString read FZip write FZip; property OwnerName: WideString read FOwnerName write FOwnerName; end; // ************************************************************************ // // Namespace : http://carme/secure/ws/WSDL // ************************************************************************ // clsGetNeighborhoodCompsCountRequest = class(TRemotable) private FStreetAddress: WideString; FCity: WideString; FState: WideString; FZip: WideString; FOwnerName: WideString; published property StreetAddress: WideString read FStreetAddress write FStreetAddress; property City: WideString read FCity write FCity; property State: WideString read FState write FState; property Zip: WideString read FZip write FZip; property OwnerName: WideString read FOwnerName write FOwnerName; end; // ************************************************************************ // // Namespace : http://carme/secure/ws/WSDL // ************************************************************************ // clsGetStandardCompsRequest = class(TRemotable) private FStreetAddress: WideString; FCity: WideString; FState: WideString; FZip: WideString; FOwnerName: WideString; published property StreetAddress: WideString read FStreetAddress write FStreetAddress; property City: WideString read FCity write FCity; property State: WideString read FState write FState; property Zip: WideString read FZip write FZip; property OwnerName: WideString read FOwnerName write FOwnerName; end; // ************************************************************************ // // Namespace : http://carme/secure/ws/WSDL // ************************************************************************ // clsGet50NeighborhoodCompsRequest = class(TRemotable) private FStreetAddress: WideString; FCity: WideString; FState: WideString; FZip: WideString; FOwnerName: WideString; published property StreetAddress: WideString read FStreetAddress write FStreetAddress; property City: WideString read FCity write FCity; property State: WideString read FState write FState; property Zip: WideString read FZip write FZip; property OwnerName: WideString read FOwnerName write FOwnerName; end; // ************************************************************************ // // Namespace : http://carme/secure/ws/WSDL // ************************************************************************ // clsGetNeighborhoodComps500Request = class(TRemotable) private FStreetAddress: WideString; FCity: WideString; FState: WideString; FZip: WideString; FOwnerName: WideString; published property StreetAddress: WideString read FStreetAddress write FStreetAddress; property City: WideString read FCity write FCity; property State: WideString read FState write FState; property Zip: WideString read FZip write FZip; property OwnerName: WideString read FOwnerName write FOwnerName; end; // ************************************************************************ // // Namespace : http://carme/secure/ws/WSDL // ************************************************************************ // clsUsageAccessCredentials = class(TRemotable) private FCustomerId: Integer; FServiceId: WideString; published property CustomerId: Integer read FCustomerId write FCustomerId; property ServiceId: WideString read FServiceId write FServiceId; end; // ************************************************************************ // // Namespace : LpsDataServerClass // soapAction: LpsDataServerClass#%operationName% // transport : http://schemas.xmlsoap.org/soap/http // style : rpc // binding : LpsDataServerBinding // service : LpsDataServer // port : LpsDataServerPort // URL : http://carme/secure/ws/awsi/LpsDataServer.php // ************************************************************************ // LpsDataServerPortType = interface(IInvokable) ['{0B448D1B-BBAA-CF9C-546A-061A615209F5}'] function LpsDataService_GetUsageAvailability(const UsageAccessCredentials: clsUsageAccessCredentials): clsGetUsageAvailabilityResponse; stdcall; function LpsDataService_GetSubjectInformation(const UserCredentials: clsUserCredentials; const AddressSearch: clsGetSubjectInformationRequest): clsGetSubjectInformationResponse; stdcall; function LpsDataService_GetNeighborhoodCompsCount(const UserCredentials: clsUserCredentials; const AddressSearch: clsGetNeighborhoodCompsCountRequest; const CompsRequest: clsCompsRequest): clsGetNeighborhoodCompsCountResponse; stdcall; function LpsDataService_GetStandardComps(const UserCredentials: clsUserCredentials; const AddressSearch: clsGetStandardCompsRequest; const CompsRequest: clsCompsRequest): clsGetStandardCompsResponse; stdcall; function LpsDataService_Get50NeighborhoodComps(const UserCredentials: clsUserCredentials; const AddressSearch: clsGet50NeighborhoodCompsRequest; const CompsRequest: clsCompsRequest): clsGet50NeighborhoodCompsResponse; stdcall; function LpsDataService_GetNeighborhoodComps500(const UserCredentials: clsUserCredentials; const AddressSearch: clsGetNeighborhoodComps500Request; const CompsRequest: clsCompsRequest): clsGetNeighborhoodComps500Response; stdcall; function LpsDataService_Acknowledgement(const UserCredentials: clsUserCredentials; const Acknowledgement: clsAcknowledgement): clsAcknowledgementResponse; stdcall; end; function GetLpsDataServerPortType(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): LpsDataServerPortType; implementation function GetLpsDataServerPortType(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): LpsDataServerPortType; const defWSDL = 'http://carme/secure/ws/awsi/LpsDataServer.php?wsdl'; defURL = 'http://carme/secure/ws/awsi/LpsDataServer.php'; defSvc = 'LpsDataServer'; defPrt = 'LpsDataServerPort'; var RIO: THTTPRIO; begin Result := nil; if (Addr = '') then begin if UseWSDL then Addr := defWSDL else Addr := defURL; end; if HTTPRIO = nil then RIO := THTTPRIO.Create(nil) else RIO := HTTPRIO; try Result := (RIO as LpsDataServerPortType); if UseWSDL then begin RIO.WSDLLocation := Addr; RIO.Service := defSvc; RIO.Port := defPrt; end else RIO.URL := Addr; finally if (Result = nil) and (HTTPRIO = nil) then RIO.Free; end; end; destructor clsShapeItem.Destroy; var I: Integer; begin for I := 0 to Length(FPoints)-1 do if Assigned(FPoints[I]) then FPoints[I].Free; SetLength(FPoints, 0); if Assigned(FCircle) then FCircle.Free; inherited Destroy; end; destructor clsCompsRequest.Destroy; var I: Integer; begin for I := 0 to Length(FShapes)-1 do if Assigned(FShapes[I]) then FShapes[I].Free; SetLength(FShapes, 0); inherited Destroy; end; destructor clsAcknowledgementResponse.Destroy; begin if Assigned(FResults) then FResults.Free; if Assigned(FResponseData) then FResponseData.Free; inherited Destroy; end; destructor clsSubjectProperty.Destroy; var I: Integer; begin for I := 0 to Length(FSalesHistory)-1 do if Assigned(FSalesHistory[I]) then FSalesHistory[I].Free; SetLength(FSalesHistory, 0); inherited Destroy; end; destructor clsXml178Data.Destroy; begin if Assigned(FSubjectProperty) then FSubjectProperty.Free; inherited Destroy; end; destructor clsGetSubjectInformation.Destroy; begin if Assigned(FXml178Data) then FXml178Data.Free; inherited Destroy; end; destructor clsGetSubjectInformationResponse.Destroy; begin if Assigned(FResults) then FResults.Free; if Assigned(FResponseData) then FResponseData.Free; inherited Destroy; end; destructor clsNeighborhoodCompsCount.Destroy; begin if Assigned(FXml179Data) then FXml179Data.Free; inherited Destroy; end; destructor clsGetNeighborhoodCompsCountResponse.Destroy; begin if Assigned(FResults) then FResults.Free; if Assigned(FResponseData) then FResponseData.Free; inherited Destroy; end; destructor clsCompsRecord177ArrayItem.Destroy; var I: Integer; begin for I := 0 to Length(FSalesHistory)-1 do if Assigned(FSalesHistory[I]) then FSalesHistory[I].Free; SetLength(FSalesHistory, 0); inherited Destroy; end; destructor clsXml174Data.Destroy; var I: Integer; begin for I := 0 to Length(FCompsRecords)-1 do if Assigned(FCompsRecords[I]) then FCompsRecords[I].Free; SetLength(FCompsRecords, 0); inherited Destroy; end; destructor clsGetStandardComps.Destroy; begin if Assigned(FXml179Data) then FXml179Data.Free; inherited Destroy; end; destructor clsGetStandardCompsResponse.Destroy; begin if Assigned(FResults) then FResults.Free; if Assigned(FResponseData) then FResponseData.Free; inherited Destroy; end; destructor clsCompsRecords.Destroy; var I: Integer; begin for I := 0 to Length(FCompsRecord)-1 do if Assigned(FCompsRecord[I]) then FCompsRecord[I].Free; SetLength(FCompsRecord, 0); inherited Destroy; end; destructor clsXml177Data.Destroy; begin if Assigned(FCompsRecords) then FCompsRecords.Free; inherited Destroy; end; destructor clsGet50NeighborhoodComps.Destroy; begin if Assigned(FXml177Data) then FXml177Data.Free; inherited Destroy; end; destructor clsGet50NeighborhoodCompsResponse.Destroy; begin if Assigned(FResults) then FResults.Free; if Assigned(FResponseData) then FResponseData.Free; inherited Destroy; end; destructor clsGetNeighborhoodComps500.Destroy; begin if Assigned(FXml175Data) then FXml175Data.Free; inherited Destroy; end; destructor clsGetNeighborhoodComps500Response.Destroy; begin if Assigned(FResults) then FResults.Free; if Assigned(FResponseData) then FResponseData.Free; inherited Destroy; end; destructor clsGetUsageAvailabilityResponse.Destroy; begin if Assigned(FResults) then FResults.Free; if Assigned(FResponseData) then FResponseData.Free; inherited Destroy; end; initialization InvRegistry.RegisterInterface(TypeInfo(LpsDataServerPortType), 'LpsDataServerClass', 'ISO-8859-1'); InvRegistry.RegisterDefaultSOAPAction(TypeInfo(LpsDataServerPortType), 'LpsDataServerClass#%operationName%'); InvRegistry.RegisterExternalMethName(TypeInfo(LpsDataServerPortType), 'LpsDataService_GetUsageAvailability', 'LpsDataService.GetUsageAvailability'); InvRegistry.RegisterExternalMethName(TypeInfo(LpsDataServerPortType), 'LpsDataService_GetSubjectInformation', 'LpsDataService.GetSubjectInformation'); InvRegistry.RegisterExternalMethName(TypeInfo(LpsDataServerPortType), 'LpsDataService_GetNeighborhoodCompsCount', 'LpsDataService.GetNeighborhoodCompsCount'); InvRegistry.RegisterExternalMethName(TypeInfo(LpsDataServerPortType), 'LpsDataService_GetStandardComps', 'LpsDataService.GetStandardComps'); InvRegistry.RegisterExternalMethName(TypeInfo(LpsDataServerPortType), 'LpsDataService_Get50NeighborhoodComps', 'LpsDataService.Get50NeighborhoodComps'); InvRegistry.RegisterExternalMethName(TypeInfo(LpsDataServerPortType), 'LpsDataService_GetNeighborhoodComps500', 'LpsDataService.GetNeighborhoodComps500'); InvRegistry.RegisterExternalMethName(TypeInfo(LpsDataServerPortType), 'LpsDataService_Acknowledgement', 'LpsDataService.Acknowledgement'); RemClassRegistry.RegisterXSClass(clsUserCredentials, 'http://carme/secure/ws/WSDL', 'clsUserCredentials'); RemClassRegistry.RegisterXSClass(clsCircle, 'http://carme/secure/ws/WSDL', 'clsCircle'); RemClassRegistry.RegisterXSClass(clsPointItem, 'http://carme/secure/ws/WSDL', 'clsPointItem'); RemClassRegistry.RegisterXSInfo(TypeInfo(clsPointsArray), 'http://carme/secure/ws/WSDL', 'clsPointsArray'); RemClassRegistry.RegisterXSClass(clsShapeItem, 'http://carme/secure/ws/WSDL', 'clsShapeItem'); RemClassRegistry.RegisterXSInfo(TypeInfo(clsShapesArray), 'http://carme/secure/ws/WSDL', 'clsShapesArray'); RemClassRegistry.RegisterXSClass(clsCompsRequest, 'http://carme/secure/ws/WSDL', 'clsCompsRequest'); RemClassRegistry.RegisterXSClass(clsResults, 'http://carme/secure/ws/WSDL', 'clsResults'); RemClassRegistry.RegisterExternalPropName(TypeInfo(clsResults), 'Type_', 'Type'); RemClassRegistry.RegisterXSClass(clsSaleHistoryItem, 'http://carme/secure/ws/WSDL', 'clsSaleHistoryItem'); RemClassRegistry.RegisterXSInfo(TypeInfo(clsSalesHistory), 'http://carme/secure/ws/WSDL', 'clsSalesHistory'); RemClassRegistry.RegisterXSClass(clsAcknowledgementResponseData, 'http://carme/secure/ws/WSDL', 'clsAcknowledgementResponseData'); RemClassRegistry.RegisterXSClass(clsAcknowledgementResponse, 'http://carme/secure/ws/WSDL', 'clsAcknowledgementResponse'); RemClassRegistry.RegisterXSClass(clsSubjectProperty, 'http://carme/secure/ws/WSDL', 'clsSubjectProperty'); RemClassRegistry.RegisterXSClass(clsXml178Data, 'http://carme/secure/ws/WSDL', 'clsXml178Data'); RemClassRegistry.RegisterXSClass(clsGetSubjectInformation, 'http://carme/secure/ws/WSDL', 'clsGetSubjectInformation'); RemClassRegistry.RegisterXSClass(clsGetSubjectInformationResponse, 'http://carme/secure/ws/WSDL', 'clsGetSubjectInformationResponse'); RemClassRegistry.RegisterXSClass(clsXml179Data, 'http://carme/secure/ws/WSDL', 'clsXml179Data'); RemClassRegistry.RegisterXSClass(clsNeighborhoodCompsCount, 'http://carme/secure/ws/WSDL', 'clsNeighborhoodCompsCount'); RemClassRegistry.RegisterXSClass(clsGetNeighborhoodCompsCountResponse, 'http://carme/secure/ws/WSDL', 'clsGetNeighborhoodCompsCountResponse'); RemClassRegistry.RegisterXSClass(clsCompsRecord177ArrayItem, 'http://carme/secure/ws/WSDL', 'clsCompsRecord177ArrayItem'); RemClassRegistry.RegisterExternalPropName(TypeInfo(clsCompsRecord177ArrayItem), 'Unit_', 'Unit'); RemClassRegistry.RegisterXSInfo(TypeInfo(clsCompsRecord), 'http://carme/secure/ws/WSDL', 'clsCompsRecord'); RemClassRegistry.RegisterXSClass(clsXml174Data, 'http://carme/secure/ws/WSDL', 'clsXml174Data'); RemClassRegistry.RegisterXSClass(clsGetStandardComps, 'http://carme/secure/ws/WSDL', 'clsGetStandardComps'); RemClassRegistry.RegisterXSClass(clsGetStandardCompsResponse, 'http://carme/secure/ws/WSDL', 'clsGetStandardCompsResponse'); RemClassRegistry.RegisterXSClass(clsCompsRecords, 'http://carme/secure/ws/WSDL', 'clsCompsRecords'); RemClassRegistry.RegisterXSClass(clsXml177Data, 'http://carme/secure/ws/WSDL', 'clsXml177Data'); RemClassRegistry.RegisterXSClass(clsGet50NeighborhoodComps, 'http://carme/secure/ws/WSDL', 'clsGet50NeighborhoodComps'); RemClassRegistry.RegisterXSClass(clsGet50NeighborhoodCompsResponse, 'http://carme/secure/ws/WSDL', 'clsGet50NeighborhoodCompsResponse'); RemClassRegistry.RegisterXSClass(clsXml175Data, 'http://carme/secure/ws/WSDL', 'clsXml175Data'); RemClassRegistry.RegisterXSClass(clsGetNeighborhoodComps500, 'http://carme/secure/ws/WSDL', 'clsGetNeighborhoodComps500'); RemClassRegistry.RegisterXSClass(clsGetNeighborhoodComps500Response, 'http://carme/secure/ws/WSDL', 'clsGetNeighborhoodComps500Response'); RemClassRegistry.RegisterXSClass(clsGetUsageAvailabilityData, 'http://carme/secure/ws/WSDL', 'clsGetUsageAvailabilityData'); RemClassRegistry.RegisterXSClass(clsGetUsageAvailabilityResponse, 'http://carme/secure/ws/WSDL', 'clsGetUsageAvailabilityResponse'); RemClassRegistry.RegisterXSClass(clsAcknowledgement, 'http://carme/secure/ws/WSDL', 'clsAcknowledgement'); RemClassRegistry.RegisterXSClass(clsGetSubjectInformationRequest, 'http://carme/secure/ws/WSDL', 'clsGetSubjectInformationRequest'); RemClassRegistry.RegisterXSClass(clsGetNeighborhoodCompsCountRequest, 'http://carme/secure/ws/WSDL', 'clsGetNeighborhoodCompsCountRequest'); RemClassRegistry.RegisterXSClass(clsGetStandardCompsRequest, 'http://carme/secure/ws/WSDL', 'clsGetStandardCompsRequest'); RemClassRegistry.RegisterXSClass(clsGet50NeighborhoodCompsRequest, 'http://carme/secure/ws/WSDL', 'clsGet50NeighborhoodCompsRequest'); RemClassRegistry.RegisterXSClass(clsGetNeighborhoodComps500Request, 'http://carme/secure/ws/WSDL', 'clsGetNeighborhoodComps500Request'); RemClassRegistry.RegisterXSClass(clsUsageAccessCredentials, 'http://carme/secure/ws/WSDL', 'clsUsageAccessCredentials'); end.
unit UploadCheckoutTesting; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, Registry, StrUtils, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, Vcl.Menus, dsdDB, DB, Vcl.ExtCtrls, Vcl.StdCtrls, cxButtons, cxGroupBox, cxRadioGroup, cxLabel, cxTextEdit, cxCurrencyEdit, Vcl.ActnList, cxClasses, cxPropertiesStore, dxSkinsCore, dxSkinsDefaultPainters, Vcl.ComCtrls, cxProgressBar, ZConnection; type TUploadThread = class(TThread) private { Private declarations } FFileName: string; FFilePath: string; FError: string; protected procedure Execute; override; end; TUploadCheckoutTestingForm = class(TForm) edMsgDescription: TEdit; cxProgressBar1: TcxProgressBar; Timer: TTimer; labInterval: TcxLabel; procedure FormShow(Sender: TObject); procedure TimerTimer(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } FInterval : Integer; FStep : Integer; FUploadThread : TUploadThread; public { Public declarations } procedure LoadFileFromFile(FileName, FilePath: string); end; implementation uses UtilConst, CommonData, ZStoredProcedure, FormStorage, UnilWin; {$R *.dfm} {TUploadThread} procedure TUploadThread.Execute; var Stream: TStream; ZConnection: TZConnection; function GetConnection: TZConnection; var f: System.text; ConnectionString: string; List: TStringList; begin AssignFile(F, ConnectionPath); Reset(f); readln(f, ConnectionString); readln(f, ConnectionString); CloseFile(f); // Вырезаем строку подключения ConnectionString := Copy(ConnectionString, Pos('=', ConnectionString) + 3, maxint); ConnectionString := Copy(ConnectionString, 1, length(ConnectionString) - 2); ConnectionString := ReplaceStr(ConnectionString, ' ', #13#10); List := TStringList.Create; result := TZConnection.Create(nil); try List.Text := ConnectionString; result.HostName := List.Values['host']; result.Port := StrToInt(List.Values['port']); result.User := List.Values['user']; result.Password := List.Values['password']; result.Database := List.Values['dbname']; result.Protocol := 'postgresql-9'; result.Properties.Add('timeout=12'); finally List.Free end; end; begin FError := ''; ZConnection := GetConnection; try try ZConnection.Connected := true; Stream := TStringStream.Create(ConvertConvert(FileReadString(FFilePath))); with TZStoredProc.Create(nil), UnilWin.GetFileVersion(FFilePath) do begin try Connection := ZConnection; StoredProcName := 'gpInsertUpdate_Object_Program'; Params.Clear; Params.CreateParam(ftString, 'inProgramName', ptInput); Params.CreateParam(ftFloat, 'inMajorVersion', ptInput); Params.CreateParam(ftFloat, 'inMinorVersion', ptInput); Params.CreateParam(ftBlob, 'inProgramData', ptInput); Params.CreateParam(ftString, 'inSession', ptInput); ParamByName('inProgramName').AsString := ExtractFileName(FFileName) + GetBinaryPlatfotmSuffics(FFilePath, ''); ParamByName('inMajorVersion').AsFloat := VerHigh; ParamByName('inMinorVersion').AsFloat := VerLow; ParamByName('inProgramData').LoadFromStream(Stream, ftMemo); ParamByName('inSession').AsString := gc_User.Session; ExecProc; finally Free; Stream.Free; end; end; finally ZConnection.Free; end; except on E: Exception do FError := E.Message; end; end; {TUploadCheckoutTestingForm} procedure TUploadCheckoutTestingForm.LoadFileFromFile(FileName, FilePath: string); begin FUploadThread := TUploadThread.Create(True); try FUploadThread.FFileName := FileName; FUploadThread.FFilePath := FilePath; FUploadThread.Start; finally end; end; procedure TUploadCheckoutTestingForm.FormClose(Sender: TObject; var Action: TCloseAction); begin if Assigned(FUploadThread) then Action := caNone; end; procedure TUploadCheckoutTestingForm.FormCreate(Sender: TObject); begin FInterval := 0; FStep := 0; FUploadThread := Nil; end; procedure TUploadCheckoutTestingForm.FormShow(Sender: TObject); begin Timer.Enabled := True; end; procedure TUploadCheckoutTestingForm.TimerTimer(Sender: TObject); begin Timer.Enabled := False; try FInterval := FInterval + Timer.Interval; if Assigned(FUploadThread) and FUploadThread.Finished and (FStep = 2) then begin FreeAndNil(FUploadThread); ModalResult := mrCancel; end else if Assigned(FUploadThread) and FUploadThread.Finished and (FStep = 1) then begin if FUploadThread.FError <> '' then ShowMessage(FUploadThread.FError); FreeAndNil(FUploadThread); FStep := 2; edMsgDescription.Text := 'Отправка файла сервиса'; Application.ProcessMessages; LoadFileFromFile('FarmacyCashServise_Test.exe', ExtractFileDir(ParamStr(0)) + '\FarmacyCashServise.exe'); end else if not Assigned(FUploadThread) and (FStep = 0) then begin if MessageDlg('Отправить тестовые файлы кассы и сервиса на сервер?',mtConfirmation,mbYesNo,0) = mrYes then begin edMsgDescription.Text := 'Отправка файла кассы'; FStep := 1; LoadFileFromFile('FarmacyCash_Test.exe', ExtractFileDir(ParamStr(0)) + '\FarmacyCash.exe'); end else ModalResult := mrCancel; end; labInterval.Caption := IntToStr(FInterval div 60000) + ':' + IfThen(Length(IntToStr(FInterval mod 60000 div 1000)) = 1, '0', '') + IntToStr(FInterval mod 60000 div 1000); finally Timer.Enabled := True; end; end; initialization RegisterClass(TUploadCheckoutTestingForm); end.
program BoolLogicTest; var val: boolean = true; val2: boolean = false; begin writeln('Should be true: ', val or val2); writeln('Should be false: ', val and val2); end.
unit uAlunoService; {$mode objfpc}{$H+} interface uses Classes, SysUtils, db, sqldb, Forms, LCLType, uAluno, DateUtils; type TSituacaoAluno = (saTodos, saAtivo, saInativo, saAdimplente, saInadimplente); TSetSituacaoAluno = Set of TSituacaoAluno; TAlunoService = class private public // retorna um objeto aluno a partir do id. Caso não seja encontrado, retornará nil. class function obterAluno(id: integer; pSituacaoAluno: TSetSituacaoAluno = [saTodos]): TAluno; overload; // retorna um objeto aluno a partir do regsitro corrente do DataSet. class function obterAluno(dataSet: TDataSet): TAluno; overload; // Aplica as regras de validação referentes à inclusão do aluno. class procedure validarDados(dataSet: TDataSet); // Torna o aluno impedido participar das aulas. class procedure desativarAluno(idAluno: integer); // Torna o aluno apto participar das aulas. class procedure ativarAluno(idAluno: integer); // Aplica as regras de validação referentes à exclusão do aluno. class procedure validarExclusao(dataSet: TDataSet); end; implementation uses uDATMOD, uClassUtil; //******************** MÉTODOS PÚBLICOS ********************// class function TAlunoService.obterAluno(dataSet: TDataSet): TAluno; begin result := TAluno.create(dataSet); end; class function TAlunoService.obterAluno(id: integer; pSituacaoAluno: TSetSituacaoAluno = [saTodos]): TAluno; overload; var filtro: string; begin result := nil; if saAtivo in pSituacaoAluno then filtro := 'data_inativacao is null and '; try DataModuleApp.qryAlunoObj.Close; DataModuleApp.qryAlunoObj.ServerFilter:= filtro +' a.id = ' + id.ToString; DataModuleApp.qryAlunoObj.ServerFiltered:=true; DataModuleApp.qryAlunoObj.Open; //if not qry.IsEmpty then if not DataModuleApp.qryAlunoObj.IsEmpty then result := TAluno.create(DataModuleApp.qryAlunoObj); if not Assigned(result) then raise Exception.Create('Aluno não cadastrado ou inativo.'); finally DataModuleApp.qryAlunoObj.Close; end; end; class procedure TAlunoService.desativarAluno(idAluno: integer); begin if Application.MessageBox('O aluno será impedido de participar das atividades da escola. Deseja continuar?', 'Validação', MB_ICONQUESTION + MB_YESNO) = IDNO then raise Exception.Create('Desativação do aluno cancelada.'); try DataModuleApp.MySQL57Connection.ExecuteDirect('update aluno set data_inativacao = date(now()) where id = ' + idAluno.toString); DataModuleApp.sqlTransactionGeral.CommitRetaining; Application.MessageBox('Aluno desativado com sucesso.', 'SUCESSO', MB_ICONINFORMATION); except on e: Exception do Application.MessageBox(PChar(TUtil.mensagemErro(e) + '.'), 'ERRO', MB_ICONERROR); end; end; class procedure TAlunoService.ativarAluno(idAluno: integer); begin if Application.MessageBox('O aluno poderá participar das atividades da escola. Deseja continuar?', 'Validação', MB_ICONQUESTION + MB_YESNO) = IDNO then raise Exception.Create('Ativação do aluno cancelada.'); try DataModuleApp.MySQL57Connection.ExecuteDirect('update aluno set data_inativacao = null where id = ' + idAluno.toString); DataModuleApp.sqlTransactionGeral.CommitRetaining; Application.MessageBox('Aluno desativado com sucesso.', 'SUCESSO', MB_ICONINFORMATION); except on e: Exception do Application.MessageBox(PChar(TUtil.mensagemErro(e) + '.'), 'ERRO', MB_ICONERROR); end; end; class procedure TAlunoService.validarDados(dataSet: TDataSet); begin // Regra de validação 01 if dataSet.FieldByName('nome').IsNull or (dataSet.FieldByName('nome').AsString.Trim.Length < 10) or (dataSet.FieldByName('nome').AsString.Trim.Length > 70) then raise Exception.Create('O nome do aluno deve conter entre 10 e 70 caracteres.'); // Regra de validação 02 if dataSet.FieldByName('data_nascimento').IsNull then raise Exception.Create('A data de nascimento do aluno tem que ser informada.'); // Regra de validação 03 if Trunc(dataSet.FieldByName('data_nascimento').AsDateTime) > Date then raise Exception.Create('A data de nascimento do aluno não pode ser futura.'); // Regra de validação 04 if (dataSet.FieldByName('telefone').AsString.Trim.Length = 0) and (dataSet.FieldByName('celular').AsString.Trim.Length = 0) then if Application.MessageBox('Não foi informado telefone ou celular ao aluno. Deseja continuar?', 'Validação', MB_ICONQUESTION + MB_YESNO) = IDNO then raise Exception.Create('Atualização dos dados do aluno cancelada.'); // Regra de validação 05 if dataSet.FieldByName('fk_motivo_matricula_id').IsNull then raise Exception.Create('Um motivo à matrícula do aluno deve ser informado.'); // Regra de validação 06 if dataSet.FieldByName('fk_doenca_pre_existente_id').IsNull then raise Exception.Create('É necessário indicar a pré-existência de doença.'); {************************ Validação do responsável **************************} // Regra de validação 08 if YearsBetween(Trunc(Date), Trunc(dataSet.FieldByName('data_nascimento').AsDateTime)) < 18 then begin if (dataSet.FieldByName('nome_responsavel').AsString.Trim.Length < 10) or (dataSet.FieldByName('nome_responsavel').AsString.Trim.Length > 70) then raise Exception.Create('O nome do responsável deve conter entre 10 e 70 caracteres.'); end; // Regra de validação 11 if (dataSet.FieldByName('email_responsavel').AsString.Trim.Length < 10) or (dataSet.FieldByName('email_responsavel').AsString.Trim.Length > 40) then raise Exception.Create('O e-mail do responsável deve conter entre 10 e 40 caracteres.'); // Regra de validação 12 if dataSet.FieldByName('cpf_responsavel').AsString.Trim.Length = 0 then raise Exception.Create('O C.P.F. do responsável tem que ser informado.'); // Regra de validação 09 TUtil.validar_Email(dataSet.FieldByName('email_responsavel').AsString); // Regra de validação 10 TUtil.CheckCPF(dataSet.FieldByName('cpf_responsavel').AsString); // Regra de validação 13 if dataSet.FieldByName('celular_responsavel').IsNull then raise Exception.Create('O celular do responsável tem que ser informado.'); // Regra de validação 14 if dataSet.FieldByName('celular_responsavel').AsString.Replace(' ', '').Trim.Length <> 11 then raise Exception.Create('O celular do responsável tem que ter 11 dígitos.'); end; class procedure TAlunoService.validarExclusao(dataSet: TDataSet); begin if dataSet.FieldByName('celular_responsavel').IsNull then raise Exception.Create('O celular do responsável tem que ser informado.'); end; //******************** MÉTODOS PRIVADOS ********************// end.
unit uScpJsonFormatter; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, uUser, System.Json, uSimpleConnectionProtocol; Type TSCPJsonFormatter = class (TObject) private public class function createAuthJsonString(aUser: TUser): String; class function createSmsJsonString(aUser: TUser): String; class function createGreetingJsonString(aUser: TUSer): String; class function createConnectionJsonString(aUser: TUser): String; class function getJsonGreetingData(aJson: String; aUser: TUser): TUser; class function getJsonSmsData(aJson: String; aUser: TUser): TUser; class function getJsonAuthData(aJson: String; aUser: TUser): TUser; class function getJsonErrorData(aJson: String; aUser: TUser): TUser; class function getJsonConnectionData(aJson: String; aUser: TUser): TUser; end; implementation { TSCPJsonFormatter } uses uSmsClient; class function TSCPJsonFormatter.createAuthJsonString(aUser: TUser): String; var lJObject, lInnserJson: TJsonObject; begin result:=string.Empty; if aUser = nil then Exit; try lJObject:=TJSONObject.Create; lInnserJson:=TJSONObject.Create; lInnserJson.AddPair(KEY_LOGIN, aUser.Login); lInnserJson.AddPair(KEY_PASS, aUser.Password); lInnserJson.AddPair(KEY_COMMENTS, aUser.Comments); lJObject.AddPair(KEY_AUTH, lInnserJson); result:=lJObject.ToString; //TSimpleConnectionProtocol.MsgLog(result, aUser, mtINFO, frmSmsClient); finally lJObject.Free; lJObject:=nil; end; end; class function TSCPJsonFormatter.createConnectionJsonString( aUser: TUser): String; var lJObject, lInnserJson: TJsonObject; begin result:=string.Empty; if aUser = nil then Exit; try lJObject:=TJSONObject.Create; lInnserJson:=TJSONObject.Create; lInnserJson.AddPair(KEY_COMMENTS, aUser.Comments); lInnserJson.AddPair(KEY_SOCK_CLOSE, aUser.ClosedSocket.ToString()); lJObject.AddPair(PROT_CONNECTION, lInnserJson); result:=lJObject.ToString; finally lJObject.Free; lJObject:=nil; end; end; class function TSCPJsonFormatter.createGreetingJsonString(aUser: TUSer): String; var lJObject, lInnserJson: TJsonObject; function BooleanToString(aFlag: Boolean): String; begin if aFlag then result:='true' else result:='false'; end; begin result:=string.Empty; if aUser = nil then Exit; try lJObject:=TJSONObject.Create; lInnserJson:=TJSONObject.Create; lInnserJson.AddPair(KEY_CRYPT, BooleanToString(aUser.isEncrypted)); lInnserJson.AddPair(KEY_COMMENTS, aUser.Comments); lJObject.AddPair(PROT_HELLO, lInnserJson); result:=lJObject.ToString; finally lJObject.Free; lJObject:=nil; end; end; class function TSCPJsonFormatter.createSmsJsonString(aUser: TUser): String; var lJObject, lInnserJson: TJsonObject; lJsonArray: TJsonArray; I: Integer; begin result:=string.Empty; if aUser = nil then Exit; try lJObject:=TJSONObject.Create; lInnserJson:=TJSONObject.Create; lJsonArray:=TJsonArray.Create; lInnserJson.AddPair(KEY_SMS_MSG, aUser.SmsMsg); lInnserJson.AddPair(KEY_COMMENTS, aUser.Comments); // TSimpleConnectionProtocol.MsgDlg(aUser.Tels.Strings[0]); for I := 0 to aUser.Tels.Count-1 do lJsonArray.Add(aUser.Tels.Strings[I]); lInnserJson.AddPair(KEY_TEL_LIST, lJsonArray); lJObject.AddPair(PROT_SMS, lInnserJson); result:=lJObject.ToString; finally lJObject.Free; // lInnserJson.Free; // lJObject:=nil; // lJsonArray.Free; // lJsonArray:=nil; end; end; class function TSCPJsonFormatter.getJsonAuthData(aJson: String; aUser: TUser): TUser; var lJsonObject: TJsonObject; linnerJObject: TJsonObject; begin //TSimpleConnectionProtocol.MsgDlg('Ok!'); result:=nil; if (aJson.IsEmpty) or (aUser = nil) then Exit; try lJsonObject:=TJsonObject.ParseJSONValue(aJson) as TJsonObject; if lJsonObject <> nil then begin linnerJObject:=lJsonObject.GetValue(PROT_AUTH) as TJsonObject; if linnerJObject <> nil then begin aUser.isAuthorized:=linnerJObject.GetValue(KEY_AUTHORIZED).Value.ToBoolean; aUser.Comments:=linnerJObject.GetValue(KEY_COMMENTS).Value; aUser.ClosedSocket:=linnerJObject.GetValue(KEY_SOCK_CLOSE).Value.ToBoolean; end; end else TSimpleConnectionProtocol.MsgLog(Format(ERR_NOT_JSON, [aJson]), aUser, TMsgType.mtERR, frmSmsClient); result:=aUser; except on E: Exception do begin TSimpleConnectionProtocol.MsgLog(E.Message, aUser, mtERR, frmSmsClient); Exit; end; end; end; class function TSCPJsonFormatter.getJsonConnectionData(aJson: String; aUser: TUser): TUser; var lJsonObject: TJsonObject; linnerJObject: TJsonObject; begin result:=nil; if (aJson.IsEmpty) or (aUser = nil) then Exit; try lJsonObject:=TJsonObject.ParseJSONValue(aJson) as TJsonObject; if lJsonObject <> nil then begin linnerJObject:=lJsonObject.GetValue('PROT_CONNECTION') as TJsonObject; if linnerJObject <> nil then begin aUser.Comments:=linnerJObject.GetValue('KEY_COMMENTS').Value; aUser.ClosedSocket:=linnerJObject.GetValue('KEY_SOCK_CLOSE').Value.ToBoolean; end; end else TSimpleConnectionProtocol.MsgLog(Format(ERR_NOT_JSON, [aJson]), aUser, TMsgType.mtERR, frmSmsClient); result:=aUser; except on E: Exception do begin TSimpleConnectionProtocol.MsgLog(E.Message, aUser, mtERR, frmSmsClient); Exit; end; end; end; class function TSCPJsonFormatter.getJsonErrorData(aJson: String; aUser: TUser): TUser; var lJsonObject: TJsonObject; linnerJObject: TJsonObject; begin result:=nil; if (aJson.IsEmpty) or (aUser = nil) then Exit; try lJsonObject:=TJsonObject.ParseJSONValue(aJson) as TJsonObject; if lJsonObject <> nil then begin linnerJObject:=lJsonObject.GetValue('PROT_UNKNOWN') as TJsonObject; if linnerJObject <> nil then begin aUser.ErrMsg:=linnerJObject.GetValue('KEY_ERR_MSG').Value; aUser.ErrType:=linnerJObject.GetValue('KEY_ERR_TYPE').Value; end; end else TSimpleConnectionProtocol.MsgLog(Format(ERR_NOT_JSON, [aJson]), aUser, TMsgType.mtERR, frmSmsClient); result:=aUser; except on E: Exception do begin TSimpleConnectionProtocol.MsgLog(E.Message, aUser, mtERR, frmSmsClient); Exit; end; end; end; class function TSCPJsonFormatter.getJsonGreetingData(aJson: String; aUser: TUser): TUser; var lJsonObject: TJsonObject; linnerJObject: TJsonObject; begin result:=nil; if (aJson.IsEmpty) or (aUser = nil) then Exit; try lJsonObject:=TJsonObject.ParseJSONValue(aJson) as TJsonObject; if lJsonObject <> nil then begin linnerJObject:=lJsonObject.GetValue('PROT_HELLO') as TJsonObject; if linnerJObject <> nil then begin aUser.isAuthorized:=linnerJObject.GetValue('KEY_AUTHORIZED').Value.ToBoolean; aUser.Comments:=linnerJObject.GetValue('KEY_COMMENTS').Value; aUser.isEncrypted:=linnerJObject.GetValue('KEY_CRYPT').Value.ToBoolean; end; end else TSimpleConnectionProtocol.MsgLog(Format(ERR_NOT_JSON, [aJson]), aUser, TMsgType.mtERR, frmSmsClient); result:=aUser; except on E: Exception do begin TSimpleConnectionProtocol.MsgLog(E.Message, aUser, mtERR, frmSmsClient); Exit; end; end; end; class function TSCPJsonFormatter.getJsonSmsData(aJson: String; aUser: TUser): TUser; var lJsonObject: TJsonObject; linnerJObject: TJsonObject; lJsonArray: TJsonArray; begin result:=nil; if (aJson.IsEmpty) or (aUser = nil) then Exit; try lJsonObject:=TJsonObject.ParseJSONValue(aJson) as TJsonObject; if lJsonObject <> nil then begin linnerJObject:=lJsonObject.GetValue('PROT_SMS') as TJsonObject; if linnerJObject <> nil then begin aUser.Status:=linnerJObject.GetValue('KEY_STATUS').Value; aUser.Comments:=linnerJObject.GetValue('KEY_COMMENTS').Value; aUser.SmsMsg:=linnerJObject.GetValue('KEY_SMS_MSG').Value; end; end else TSimpleConnectionProtocol.MsgLog(Format(ERR_NOT_JSON, [aJson]), aUser, TMsgType.mtERR, frmSmsClient); result:=aUser; except on E: Exception do begin TSimpleConnectionProtocol.MsgLog(E.Message, aUser, mtERR, frmSmsClient); Exit; end; end; end; end.
unit StackedControlUnit; interface uses ExtCtrls, SysUtils, StdCtrls, ComCtrls, Controls, Classes; type TControlSizingMode = (csmUseOwnControlSize, csmUseStackedControlSize); TStackedControl = class (TPanel) strict protected FActiveControl: TControl; procedure HideAllControlsExcept(ExceptionalControl: TControl); procedure ShowControlAsActive( AControl: TControl; const ControlSizingMode: TControlSizingMode = csmUseOwnControlSize ); procedure CustomizeControl(AControl: TControl); public constructor Create(AOwner: TComponent); override; function AddControl(AControl: TControl): Integer; function Contains(Control: TControl): Boolean; procedure SetActiveControlByIndex( const Index: Integer; const ControlSizingMode: TControlSizingMode = csmUseOwnControlSize ); overload; procedure SetActiveControl( AControl: TControl ); overload; procedure SetActiveControl( AControl: TControl; const ControlSizingMode: TControlSizingMode ); overload; procedure RemoveControl(const Index: Integer); overload; function ExtractControl(const Index: Integer): TControl; function GetIndexOfControl(AControl: TControl): Integer; property ActiveControl: TControl read FActiveControl write SetActiveControl; procedure Show; end; implementation uses Forms, AuxDebugFunctionsUnit; { TStackedControl } function TStackedControl.AddControl(AControl: TControl): Integer; begin AControl.Parent := Self; CustomizeControl(AControl); Result := GetIndexOfControl(AControl); AControl.Visible := False; end; function TStackedControl.Contains(Control: TControl): Boolean; var ChildControl: TControl; I: Integer; begin for I := 0 to ControlCount - 1 do begin ChildControl := Controls[I]; if ChildControl = Control then begin Result := True; Exit; end; end; Result := False; end; constructor TStackedControl.Create(AOwner: TComponent); begin inherited; BevelOuter := bvNone; end; procedure TStackedControl.CustomizeControl(AControl: TControl); begin AControl.Left := 0; AControl.Top := 0; AControl.Anchors := [akLeft, akTop, akRight, akBottom]; // Set itself as owner InsertComponent(AControl); end; function TStackedControl.ExtractControl(const Index: Integer): TControl; begin Result := Controls[Index]; Result.Parent := nil; // Set application as owner Application.InsertComponent(Result); end; function TStackedControl.GetIndexOfControl(AControl: TControl): Integer; var I: Integer; begin for I := 0 to ControlCount - 1 do if Controls[I] = AControl then begin Result := I; Exit; end; Result := -1; end; procedure TStackedControl.HideAllControlsExcept(ExceptionalControl: TControl); var I: Integer; begin for I := 0 to ControlCount - 1 do begin if Controls[I] <> ExceptionalControl then begin Controls[I].Align := alNone; Controls[I].Hide; end; end; end; procedure TStackedControl.RemoveControl(const Index: Integer); begin RemoveControl(Controls[Index]); end; procedure TStackedControl.SetActiveControlByIndex( const Index: Integer; const ControlSizingMode: TControlSizingMode ); begin SetActiveControl(Controls[Index]); end; procedure TStackedControl.SetActiveControl(AControl: TControl); begin SetActiveControl(AControl, csmUseOwnControlSize); end; procedure TStackedControl.SetActiveControl( AControl: TControl; const ControlSizingMode: TControlSizingMode ); begin HideAllControlsExcept(AControl); ShowControlAsActive(AControl, ControlSizingMode); end; procedure TStackedControl.Show; begin if not Assigned(FActiveControl) and (ControlCount > 0) then SetActiveControlByIndex(0); Visible := True; end; procedure TStackedControl.ShowControlAsActive( AControl: TControl; const ControlSizingMode: TControlSizingMode ); begin FActiveControl := AControl; if ControlSizingMode = csmUseOwnControlSize then begin Width := FActiveControl.Width; Height := FActiveControl.Height; end; FActiveControl.Align := alClient; FActiveControl.Show; end; end.
unit SimpleDSLCompiler.AST; interface uses System.Generics.Collections; type TASTTerm = class end; { TASTTerm } TASTTermConstant = class(TASTTerm) strict private FValue: integer; strict protected function GetValue: integer; inline; procedure SetValue(const value: integer); inline; public property Value: integer read GetValue write SetValue; end; { TASTTermConstant } TASTTermVariable = class(TASTTerm) strict private FVariableIdx: integer; strict protected function GetVariableIdx: integer; inline; procedure SetVariableIdx(const value: integer); inline; public property VariableIdx: integer read GetVariableIdx write SetVariableIdx; end; { TASTTermVariable } TASTExpression = class; TExpressionList = TList<TASTExpression>; TASTTermFunctionCall = class(TASTTerm) strict private FFunctionIdx: integer; FParameters : TExpressionList; strict protected function GetFunctionIdx: integer; inline; function GetParameters: TExpressionList; inline; procedure SetFunctionIdx(const value: integer); inline; public procedure AfterConstruction; override; procedure BeforeDestruction; override; property FunctionIdx: integer read GetFunctionIdx write SetFunctionIdx; property Parameters: TExpressionList read GetParameters; end; { IASTTermFunctionCall } TBinaryOperation = (opNone, opAdd, opSubtract, opCompareLess); TASTExpression = class strict private FBinaryOp: TBinaryOperation; FTerm1 : TASTTerm; FTerm2 : TASTTerm; strict protected function GetBinaryOp: TBinaryOperation; inline; function GetTerm1: TASTTerm; inline; function GetTerm2: TASTTerm; inline; procedure SetBinaryOp(const value: TBinaryOperation); inline; procedure SetTerm1(const value: TASTTerm); procedure SetTerm2(const value: TASTTerm); public procedure BeforeDestruction; override; property BinaryOp: TBinaryOperation read GetBinaryOp write SetBinaryOp; property Term1: TASTTerm read GetTerm1 write SetTerm1; property Term2: TASTTerm read GetTerm2 write SetTerm2; end; { TASTExpression } TASTBlock = class; TASTStatement = class end; { TASTStatement } TASTIfStatement = class(TASTStatement) strict private FCondition: TASTExpression; FElseBlock: TASTBlock; FThenBlock: TASTBlock; strict protected function GetCondition: TASTExpression; inline; function GetElseBlock: TASTBlock; inline; function GetThenBlock: TASTBlock; inline; procedure SetCondition(const value: TASTExpression); procedure SetElseBlock(const value: TASTBlock); procedure SetThenBlock(const value: TASTBlock); public procedure BeforeDestruction; override; property Condition: TASTExpression read GetCondition write SetCondition; property ThenBlock: TASTBlock read GetThenBlock write SetThenBlock; property ElseBlock: TASTBlock read GetElseBlock write SetElseBlock; end; { TASTIfStatement } TASTReturnStatement = class(TASTStatement) strict private FExpression: TASTExpression; strict protected function GetExpression: TASTExpression; inline; procedure SetExpression(const value: TASTExpression); public procedure BeforeDestruction; override; property Expression: TASTExpression read GetExpression write SetExpression; end; { TASTReturnStatement } TStatementList = TList<TASTStatement>; TASTBlock = class strict private FStatements: TStatementList; strict protected function GetStatements: TStatementList; inline; public procedure AfterConstruction; override; procedure BeforeDestruction; override; property Statements: TStatementList read GetStatements; end; { IASTBlock } TAttributeList = TList<string>; TParameterList = TList<string>; TASTFunction = class strict private FAttributes: TAttributeList; FBody : TASTBlock; FName : string; FParamNames: TParameterList; strict protected function GetAttributes: TAttributeList; inline; function GetBody: TASTBlock; inline; function GetName: string; inline; function GetParamNames: TParameterList; inline; procedure SetBody(const value: TASTBlock); procedure SetName(const value: string); inline; procedure SetParamNames(const value: TParameterList); inline; public procedure AfterConstruction; override; procedure BeforeDestruction; override; property Name: string read GetName write SetName; property Attributes: TAttributeList read GetAttributes; property ParamNames: TParameterList read GetParamNames write SetParamNames; property Body: TASTBlock read GetBody write SetBody; end; { TASTFunction } TASTFunctions = class strict private FFunctions: TList<TASTFunction>; strict protected function GetItems(idxFunction: integer): TASTFunction; inline; public function Add(const func: TASTFunction): integer; procedure AfterConstruction; override; procedure BeforeDestruction; override; function Count: integer; inline; function IndexOf(const name: string): integer; property Items[idxFunction: integer]: TASTFunction read GetItems; default; end; { TASTFunctions } ISimpleDSLAST = interface ['{114E494C-8319-45F1-91C8-4102AED1809E}'] function GetFunctions: TASTFunctions; // property Functions: TASTFunctions read GetFunctions; end; { ISimpleDSLAST } TSimpleDSLASTFactory = reference to function: ISimpleDSLAST; function CreateSimpleDSLAST: ISimpleDSLAST; implementation uses System.SysUtils; type TSimpleDSLAST = class(TInterfacedObject, ISimpleDSLAST) strict private FFunctions: TASTFunctions; public procedure AfterConstruction; override; procedure BeforeDestruction; override; function GetFunctions: TASTFunctions; inline; property Functions: TASTFunctions read GetFunctions; end; { TSimpleDSLAST } { exports } function CreateSimpleDSLAST: ISimpleDSLAST; begin Result := TSimpleDSLAST.Create; end; { CreateSimpleDSLAST } { TASTTermConstant } function TASTTermConstant.GetValue: integer; begin Result := FValue; end; { TASTTermConstant.GetValue } procedure TASTTermConstant.SetValue(const value: integer); begin FValue := value; end; { TASTTermConstant.SetValue } { TASTTermVariable } function TASTTermVariable.GetVariableIdx: integer; begin Result := FVariableIdx; end; { TASTTermVariable.GetVariableIdx } procedure TASTTermVariable.SetVariableIdx(const value: integer); begin FVariableIdx := value; end; { TASTTermVariable.SetVariableIdx } { TASTTermFunctionCall } procedure TASTTermFunctionCall.AfterConstruction; begin inherited; FParameters := TExpressionList.Create; end; { TASTTermFunctionCall.AfterConstruction } procedure TASTTermFunctionCall.BeforeDestruction; begin FreeAndNil(FParameters); inherited; end; { TASTTermFunctionCall.BeforeDestruction } function TASTTermFunctionCall.GetFunctionIdx: integer; begin Result := FFunctionIdx; end; { TASTTermFunctionCall.GetFunctionIdx } function TASTTermFunctionCall.GetParameters: TExpressionList; begin Result := FParameters; end; { TASTTermFunctionCall.GetParameters } procedure TASTTermFunctionCall.SetFunctionIdx(const value: integer); begin FFunctionIdx := value; end; { TASTTermFunctionCall.SetFunctionIdx } { TASTExpression } procedure TASTExpression.BeforeDestruction; begin FreeAndNil(FTerm1); FreeAndNil(FTerm2); inherited; end; { TASTExpression.BeforeDestruction } function TASTExpression.GetBinaryOp: TBinaryOperation; begin Result := FBinaryOp; end; { TASTExpression.GetBinaryOp } function TASTExpression.GetTerm1: TASTTerm; begin Result := FTerm1; end; { TASTExpression.GetTerm1 } function TASTExpression.GetTerm2: TASTTerm; begin Result := FTerm2; end; { TASTExpression.GetTerm2 } procedure TASTExpression.SetBinaryOp(const value: TBinaryOperation); begin FBinaryOp := value; end; { TASTExpression.SetBinaryOp } procedure TASTExpression.SetTerm1(const value: TASTTerm); begin if value <> FTerm1 then begin FTerm1.Free; FTerm1 := value; end; end; { TASTExpression.SetTerm1 } procedure TASTExpression.SetTerm2(const value: TASTTerm); begin if value <> FTerm2 then begin FTerm2.Free; FTerm2 := value; end; end; { TASTExpression.SetTerm2 } { TASTIfStatement } procedure TASTIfStatement.BeforeDestruction; begin FreeAndNil(FCondition); FreeAndNil(FThenBlock); FreeAndNil(FElseBlock); inherited; end; { TASTIfStatement.BeforeDestruction } function TASTIfStatement.GetCondition: TASTExpression; begin Result := FCondition; end; { TASTIfStatement.GetCondition } function TASTIfStatement.GetElseBlock: TASTBlock; begin Result := FElseBlock; end; { TASTIfStatement.GetElseBlock } function TASTIfStatement.GetThenBlock: TASTBlock; begin Result := FThenBlock; end; { TASTIfStatement.GetThenBlock } procedure TASTIfStatement.SetCondition(const value: TASTExpression); begin if value <> FCondition then begin FCondition.Free; FCondition := value; end; end; { TASTIfStatement.SetCondition } procedure TASTIfStatement.SetElseBlock(const value: TASTBlock); begin if value <> FElseBlock then begin FElseBlock.Free; FElseBlock := value; end; end; { TASTIfStatement.SetElseBlock } procedure TASTIfStatement.SetThenBlock(const value: TASTBlock); begin if value <> FThenBlock then begin FThenBlock.Free; FThenBlock := value; end; end; { TASTIfStatement.SetThenBlock } { TASTReturnStatement } procedure TASTReturnStatement.BeforeDestruction; begin FreeAndNil(FExpression); inherited; end; { TASTReturnStatement.BeforeDestruction } function TASTReturnStatement.GetExpression: TASTExpression; begin Result := FExpression; end; { TASTReturnStatement.GetExpression } procedure TASTReturnStatement.SetExpression(const value: TASTExpression); begin if value <> FExpression then begin FExpression.Free; FExpression := value; end; end; { TASTReturnStatement.SetExpression } { TASTBlock } procedure TASTBlock.AfterConstruction; begin inherited; FStatements := TStatementList.Create; end; { TASTBlock.AfterConstruction } procedure TASTBlock.BeforeDestruction; begin FreeAndNil(FStatements); inherited; end; { TASTBlock.BeforeDestruction } function TASTBlock.GetStatements: TStatementList; begin Result := FStatements; end; { TASTBlock.GetStatements } { TASTFunction } procedure TASTFunction.AfterConstruction; begin inherited; FAttributes := TAttributeList.Create; FParamNames := TParameterList.Create; end; { TASTFunction.AfterConstruction } procedure TASTFunction.BeforeDestruction; begin FreeAndNil(FBody); FreeAndNil(FParamNames); FreeAndNil(FAttributes); inherited; end; { TASTFunction.BeforeDestruction } function TASTFunction.GetAttributes: TAttributeList; begin Result := FAttributes; end; { TASTFunction.GetAttributes } function TASTFunction.GetBody: TASTBlock; begin Result := FBody; end; { TASTFunction.GetBody } function TASTFunction.GetName: string; begin Result := FName; end; { TASTFunction.GetName } function TASTFunction.GetParamNames: TParameterList; begin Result := FParamNames; end; { TASTFunction.GetParamNames } procedure TASTFunction.SetBody(const value: TASTBlock); begin if value <> FBody then begin FBody.Free; FBody := value; end; end; { TASTFunction.SetBody } procedure TASTFunction.SetName(const value: string); begin FName := value; end; { TASTFunction.SetName } procedure TASTFunction.SetParamNames(const value: TParameterList); begin FParamNames := value; end; { TASTFunction.SetParamNames } { TASTFunctions } function TASTFunctions.Add(const func: TASTFunction): integer; begin Result := FFunctions.Add(func); end; { TASTFunctions.Add } procedure TASTFunctions.AfterConstruction; begin inherited; FFunctions := TList<TASTFunction>.Create; end; { TASTFunctions.AfterConstruction } procedure TASTFunctions.BeforeDestruction; begin FreeAndNil(FFunctions); inherited; end; { TASTFunctions.BeforeDestruction } function TASTFunctions.Count: integer; begin Result := FFunctions.Count; end; { TASTFunctions.Count } function TASTFunctions.GetItems(idxFunction: integer): TASTFunction; begin Result := FFunctions[idxFunction]; end; { TASTFunctions.GetItems } function TASTFunctions.IndexOf(const name: string): integer; begin for Result := 0 to Count - 1 do if SameText(Items[Result].Name, name) then Exit; Result := -1; end; { TASTFunctions.IndexOf } { TSimpleDSLAST } procedure TSimpleDSLAST.AfterConstruction; begin inherited; FFunctions := TASTFunctions.Create; end; { TSimpleDSLAST.AfterConstruction } procedure TSimpleDSLAST.BeforeDestruction; begin FreeAndNil(FFunctions); inherited; end; { TSimpleDSLAST.BeforeDestruction } function TSimpleDSLAST.GetFunctions: TASTFunctions; begin Result := FFunctions; end; { TSimpleDSLAST.GetFunctions } end.
{**********************************************************************} { } { "The contents of this file are subject to the Mozilla Public } { License Version 1.1 (the "License"); you may not use this } { file except in compliance with the License. You may obtain } { a copy of the License at http://www.mozilla.org/MPL/ } { } { Software distributed under the License is distributed on an } { "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express } { or implied. See the License for the specific language } { governing rights and limitations under the License. } { } { Copyright Creative IT. } { Current maintainer: Eric Grange } { } {**********************************************************************} { Synopse mORMot framework. Copyright (C) 2012 Arnaud Bouchez Synopse Informatique - http://synopse.info } unit dwsHTTPSysWebEnv; interface uses Windows, Classes, SysUtils, StrUtils, SynCommons, SynWinSock, dwsWebEnvironment, dwsUtils, dwsHTTPSysAPI, dwsWebServerHelpers; type THttpSysWebRequestPrepares = set of ( prepAuthentication, prepHeaders, prepIP_UTF8 ); THttpSysWebRequest = class (TWebRequest) private FRequest : PHTTP_REQUEST_V2; FPrepared : THttpSysWebRequestPrepares; FAuthentication : TWebRequestAuthentication; FAuthenticatedUser : String; FHeaders : TStrings; FIP_UTF8 : RawByteString; FLastIP : TVarSin; FInContent : RawByteString; FInContentType : RawByteString; protected procedure SetRequest(val : PHTTP_REQUEST_V2); function GetHeaders : TStrings; override; procedure PrepareAuthenticationInfo; procedure PrepareHeaders; procedure PrepareIP_UTF8; function GetAuthentication : TWebRequestAuthentication; override; function GetAuthenticatedUser : String; override; public constructor Create; destructor Destroy; override; property Request : PHTTP_REQUEST_V2 read FRequest write SetRequest; function RemoteIP : String; override; function RemoteIP_UTF8 : PAnsiChar; function RemoteIP_UTF8_Length : Integer; function RawURL : RawByteString; override; function URL : String; override; function Method : String; override; function MethodVerb : TWebRequestMethodVerb; override; function Security : String; override; function ContentData : RawByteString; override; function ContentType : RawByteString; override; property InContent : RawByteString read FInContent write FInContent; property InContentType : RawByteString read FInContentType write FInContentType; property Authentication : TWebRequestAuthentication read FAuthentication write FAuthentication; property AuthenticatedUser : String read FAuthenticatedUser write FAuthenticatedUser; end; THttpSysWebResponse = class (TWebResponse) private public end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ procedure GetDomainUserFromToken(hToken : THandle; var result: String); var err : Boolean; buffer : array [0..511] of Byte; bufferSize, userSize, domainSize : DWORD; pBuffer : PTokenUser; nameUse : SID_NAME_USE; p : PChar; begin err:=GetTokenInformation(hToken, TokenUser, @buffer, SizeOf(buffer), bufferSize); if not err then Exit; pBuffer:=@buffer; // get field sizes userSize:=0; domainSize:=0; LookupAccountSid(nil, pBuffer.User.Sid, nil, userSize, nil, domainSize, nameUse); if (userSize=0) or (domainSize=0) then Exit; SetLength(result, userSize+domainSize-1); p:=Pointer(result); err:=LookupAccountSid(nil, pBuffer.User.Sid, @p[domainSize], userSize, p, domainSize, nameUse); if err then p[domainSize]:='\' else result:=''; end; procedure GetSinIP(const Sin: TVarSin; var Result : RawByteString); var p : PAnsiChar; host : array[0..NI_MAXHOST] of AnsiChar; hostlen, servlen : integer; r : integer; begin if not IsNewApi(Sin.AddressFamily) then begin p := inet_ntoa(Sin.sin_addr); if p <> nil then Result := p else Result := '' end else begin hostlen := NI_MAXHOST; servlen := NI_MAXSERV; r := getnameinfo(@sin, SizeOfVarSin(sin), host, hostlen, nil, servlen, NI_NUMERICHOST + NI_NUMERICSERV); if r=0 then begin hostlen := StrLen(@host); SetLength(Result, hostlen); Move(host, Pointer(Result)^, hostlen); end else Result := ''; end; end; // ------------------ // ------------------ THttpSysWebRequest ------------------ // ------------------ // Create // constructor THttpSysWebRequest.Create; begin inherited; FHeaders:=TFastCompareStringList.Create; end; // Destroy // destructor THttpSysWebRequest.Destroy; begin FHeaders.Free; inherited; end; // SetRequest // procedure THttpSysWebRequest.SetRequest(val : PHTTP_REQUEST_V2); var p : PChar; n : Integer; begin FRequest:=val; SetString(FPathInfo, FRequest.CookedUrl.pAbsPath, FRequest.CookedUrl.AbsPathLength div SizeOf(Char)); // eliminate leading '?' p:=FRequest.CookedUrl.pQueryString; n:=FRequest.CookedUrl.QueryStringLength; if (p<>nil) and (p^='?') then begin Inc(p); Dec(n); end; SetString(FQueryString, p, n div SizeOf(Char)); FPrepared:=[]; ResetCookies; ResetFields; end; // PrepareAuthenticationInfo // procedure THttpSysWebRequest.PrepareAuthenticationInfo; const cHRAtoWRA : array [HTTP_REQUEST_AUTH_TYPE] of TWebRequestAuthentication = ( wraNone, wraBasic, wraDigest, wraNTLM, wraNegotiate, wraKerberos ); var authInfo : PHTTP_REQUEST_AUTH_INFO; begin Include(FPrepared, prepAuthentication); FAuthentication:=wraNone; FAuthenticatedUser:=''; if (request.RequestInfoCount>0) and (request.pRequestInfo.InfoType=HttpRequestInfoTypeAuth) then begin authInfo:=PHTTP_REQUEST_AUTH_INFO(request.pRequestInfo.pInfo); case authInfo.AuthStatus of HttpAuthStatusSuccess : begin FAuthentication:=cHRAtoWRA[authInfo.AuthType]; if authInfo.AccessToken<>0 then GetDomainUserFromToken(authInfo.AccessToken, FAuthenticatedUser); end; HttpAuthStatusFailure : FAuthentication:=wraFailed; end; end; end; // PrepareHeaders // procedure THttpSysWebRequest.PrepareHeaders; const cKNOWNHEADERS_NAME : array [reqCacheControl..reqUserAgent] of String = ( 'Cache-Control', 'Connection', 'Date', 'Keep-Alive', 'Pragma', 'Trailer', 'Transfer-Encoding', 'Upgrade', 'Via', 'Warning', 'Allow', 'Content-Length', 'Content-Type', 'Content-Encoding', 'Content-Language', 'Content-Location', 'Content-MD5', 'Content-Range', 'Expires', 'Last-Modified', 'Accept', 'Accept-Charset', 'Accept-Encoding', 'Accept-Language', 'Authorization', 'Cookie', 'Expect', 'From', 'Host', 'If-Match', 'If-Modified-Since', 'If-None-Match', 'If-Range', 'If-Unmodified-Since', 'Max-Forwards', 'Proxy-Authorization', 'Referer', 'Range', 'TE', 'Translate', 'User-Agent'); var i: Integer; h : THttpHeader; p : PHTTP_UNKNOWN_HEADER; head : PHTTP_REQUEST_HEADERS; buf : String; begin Include(FPrepared, prepHeaders); FHeaders.Clear; head:=@request.Headers; Assert(Low(cKNOWNHEADERS_NAME) = Low(head.KnownHeaders)); Assert(High(cKNOWNHEADERS_NAME) = High(head.KnownHeaders)); // set headers content for h:=Low(head.KnownHeaders) to High(head.KnownHeaders) do begin if head.KnownHeaders[h].RawValueLength<>0 then begin buf:= cKNOWNHEADERS_NAME[h] +'=' +UTF8DecodeToString(PUTF8Char(head.KnownHeaders[h].pRawValue), head.KnownHeaders[h].RawValueLength); FHeaders.Add(buf); end; end; p:=head.pUnknownHeaders; if p<>nil then begin for i:=1 to head.UnknownHeaderCount do begin buf:= UTF8DecodeToString(PUTF8Char(p.pName), p.NameLength) +'=' +UTF8DecodeToString(PUTF8Char(p.pRawValue), p.RawValueLength); FHeaders.Add(buf); end; end; end; // GetHeaders // PrepareIP_UTF8 // var cNullIPVarSin : TVarSin; procedure THttpSysWebRequest.PrepareIP_UTF8; var p : PVarSin; begin Include(FPrepared, prepIP_UTF8); if Request^.Address.pRemoteAddress<>nil then p:=PVarSin(Request^.Address.pRemoteAddress) else p:=@cNullIPVarSin; if not CompareMem(p, @FLastIP, SizeOf(FLastIP)) then begin FLastIP:=p^; GetSinIP(p^, FIP_UTF8); end; end; // function THttpSysWebRequest.GetHeaders : TStrings; begin if not (prepHeaders in FPrepared) then PrepareHeaders; Result:=FHeaders; end; // GetAuthentication // function THttpSysWebRequest.GetAuthentication : TWebRequestAuthentication; begin if not (prepAuthentication in FPrepared) then PrepareAuthenticationInfo; Result:=FAuthentication; end; // GetAuthenticatedUser // function THttpSysWebRequest.GetAuthenticatedUser : String; begin if not (prepAuthentication in FPrepared) then PrepareAuthenticationInfo; Result:=FAuthenticatedUser; end; // RemoteIP // function THttpSysWebRequest.RemoteIP : String; begin Result:=UTF8ToString(RemoteIP_UTF8); end; // RemoteIP_UTF8 // function THttpSysWebRequest.RemoteIP_UTF8 : PAnsiChar; begin if not (prepIP_UTF8 in FPrepared) then PrepareIP_UTF8; Result:=Pointer(FIP_UTF8); end; // RemoteIP_UTF8_Length // function THttpSysWebRequest.RemoteIP_UTF8_Length : Integer; begin if not (prepIP_UTF8 in FPrepared) then PrepareIP_UTF8; Result:=Length(FIP_UTF8); end; // RawURL // function THttpSysWebRequest.RawURL : RawByteString; begin Result:=Request^.pRawUrl; end; // URL // function THttpSysWebRequest.URL : String; begin Result:=UTF8ToString(UrlDecode(Request^.pRawUrl)); end; // Method // function THttpSysWebRequest.Method : String; const cVERB_TEXT : array [hvOPTIONS..hvSEARCH] of String = ( 'OPTIONS', 'GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'TRACE', 'CONNECT', 'TRACK', 'MOVE', 'COPY', 'PROPFIND', 'PROPPATCH', 'MKCOL', 'LOCK', 'UNLOCK', 'SEARCH' ); begin case Request^.Verb of Low(cVERB_TEXT)..High(cVERB_TEXT) : Result:=cVERB_TEXT[Request^.Verb] else SetString(Result, Request^.pUnknownVerb, Request^.UnknownVerbLength); end; end; // MethodVerb // function THttpSysWebRequest.MethodVerb : TWebRequestMethodVerb; begin case Request^.Verb of hvOPTIONS..hvSEARCH : Result:=TWebRequestMethodVerb(Ord(Request^.Verb)+(Ord(wrmvOPTIONS)-Ord(hvOPTIONS))); else Result:=wrmvUnknown; end; end; // Security // function THttpSysWebRequest.Security : String; begin if request^.pSslInfo<>nil then Result:=Format('SSL, %d bits', [request^.pSslInfo^.ConnectionKeySize*8]) else Result:=''; end; // ContentData // function THttpSysWebRequest.ContentData : RawByteString; begin Result:=InContent; end; // ContentType // function THttpSysWebRequest.ContentType : RawByteString; begin Result:=InContentType; end; end.
unit uCadastroReceita; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Grids, Vcl.StdCtrls, Vcl.WinXPickers, Vcl.Buttons; type TReg = record id:integer; nome:string[255]; tempoPreparo:string[255]; quantidade:integer; ativo: boolean; end; TfCadastroReceita = class(TForm) editTextNome: TEdit; editTextQuantidade: TEdit; lblNome: TLabel; lblQuantidadeProduzida: TLabel; lblTempoPreapro: TLabel; btnCadastrar: TSpeedButton; editTextId: TEdit; timerPickerTempoPreparo: TTimePicker; procedure FormActivate(Sender: TObject); procedure btnCadastrarClick(Sender: TObject); private mensagensErro: TStringList; procedure AbrirArquivo(caminho: string); procedure MostrarMensagensErro(); procedure EscreverArquivo(); procedure LimparTela(); procedure MostrarDialogMensagemSucesso(); procedure LimparMensagensErro(); procedure MostrarDialogMensagensErro(); procedure ConfigurarID(var reg: tReg); procedure ValidarNome(nome:string); procedure ValidarQuantidade(quantidade:integer); procedure ValidarTempoPreparo(tempoPreparo:string); procedure InicializarDados(var nome : string; var quantidade : integer; var tempoPreparo : string); procedure InicializarRegistro(var reg:tReg); function getRegistroReceita() : TReg; function ReceitaIsValid() : boolean; function getCodigo: integer; function getMensagemErro() : PWideChar; function getText(edit: TEdit) : string; function getIntegerText(edit: TEdit): integer; function getTimeText(timer: TTimePicker): string; const caminhoArquivoReceitas = 'C:\Users\TECBMNLS\Documents\Embarcadero\Studio\Projects\CadastroReceitasRepository\CadastroReceitas\dados\receitas'; lengthMaximoNomeReceita = 255; valorMinimoQuantidade = 0; valorMaximoQuantidade = 1000; mensagemInseridoSucesso = 'Registro salvo com sucesso.'; tituloDialogSucesso = 'Sucesso'; quebrarLinha = #10; tituloDialogAviso = 'Aviso'; mensagemNomeObrigatorio = 'O nome é obrigatório.'; mensagemNomeMuitoLongo = 'O nome é muito longo.'; mensagemQuantidadeInvalida = 'A quantidade é inválida.'; mensagemTempoPreparoObrigatorio = 'O tempo de preparo é obrigatório.'; public { Public declarations } end; var fCadastroReceita: TfCadastroReceita; implementation {$R *.dfm} procedure TfCadastroReceita.AbrirArquivo(caminho: string); var arq: file of TReg; begin AssignFile(arq, caminho); if (not FileExists(caminho)) then Rewrite(arq) else Reset(arq); CloseFile(arq); end; function TfCadastroReceita.getCodigo: integer; var arq:File of tReg; begin AssignFile(arq, caminhoArquivoReceitas); reset(arq); result:= FileSize(arq) + 1; CloseFile(arq); end; function TfCadastroReceita.getMensagemErro: PWideChar; var I: Integer; mensagem: string; pWideCharMensagem: PWideChar; begin mensagem:= ''; for I := 0 to mensagensErro.Count - 1 do begin mensagem:= mensagem + mensagensErro.Strings[I] + quebrarLinha; end; pWideCharMensagem := PWideChar(mensagem); result:= pWideCharMensagem; end; procedure TfCadastroReceita.EscreverArquivo(); var reg: TReg; arq: file of TReg; begin reg := getRegistroReceita(); AssignFile(arq, caminhoArquivoReceitas); Reset(arq); Seek(arq, reg.id - 1); Write(arq,reg); CloseFile(arq); end; procedure TfCadastroReceita.FormActivate(Sender: TObject); begin self.AbrirArquivo(caminhoArquivoReceitas); self.LimparMensagensErro(); end; procedure TfCadastroReceita.LimparMensagensErro; begin self.mensagensErro := TStringList.Create; self.mensagensErro.Clear; end; procedure TfCadastroReceita.LimparTela; begin editTextNome.Text := ''; editTextQuantidade.Text := ''; timerPickerTempoPreparo.Time := strtotime('00:00'); end; procedure TfCadastroReceita.MostrarDialogMensagensErro; begin Application.MessageBox(self.getMensagemErro(), tituloDialogAviso, MB_OK+MB_ICONERROR); end; procedure TfCadastroReceita.MostrarDialogMensagemSucesso; begin Application.MessageBox(mensagemInseridoSucesso, tituloDialogSucesso, MB_OK+MB_ICONINFORMATION); end; procedure TfCadastroReceita.MostrarMensagensErro; begin if (mensagensErro.Count > 0) then begin self.MostrarDialogMensagensErro(); end; end; function TfCadastroReceita.getRegistroReceita : TReg; var reg: TReg; begin self.InicializarRegistro(reg); result := reg; end; function TfCadastroReceita.getText(edit: TEdit): string; begin result:= Trim(edit.Text); end; function TfCadastroReceita.getIntegerText(edit: TEdit): integer; var text: string; begin text:= Trim(edit.Text); if(text = '') then begin result:= 0 end else result:= strtoint(text); end; function TfCadastroReceita.getTimeText(timer: TTimePicker): string; begin result := timetostr(timer.time); end; procedure TfCadastroReceita.InicializarDados(var nome : string; var quantidade : integer; var tempoPreparo : string); begin nome:= getText(editTextNome); quantidade:= getIntegerText(editTextQuantidade); tempoPreparo := getTimeText(timerPickerTempoPreparo); end; procedure TfCadastroReceita.InicializarRegistro(var reg:tReg); begin self.ConfigurarID(reg); reg.nome := getText(editTextNome); reg.quantidade := getIntegerText(editTextQuantidade); reg.tempoPreparo := getTimeText(timerPickerTempoPreparo); reg.ativo := true; end; procedure TfCadastroReceita.btnCadastrarClick(Sender: TObject); begin if (ReceitaIsValid()) then begin self.EscreverArquivo(); self.LimparTela(); self.MostrarDialogMensagemSucesso(); end else self.MostrarMensagensErro(); end; procedure TfCadastroReceita.ConfigurarID(var reg: tReg); begin if editTextId.Text = '' then reg.id := getCodigo() else reg.id := getIntegerText(editTextId); end; function TfCadastroReceita.ReceitaIsValid: boolean; var nome: string; quantidade: integer; tempoPreparo: string; begin self.LimparMensagensErro(); self.InicializarDados(nome, quantidade, tempoPreparo); self.ValidarNome(nome); self.ValidarQuantidade(quantidade); self.ValidarTempoPreparo(tempoPreparo); result:= mensagensErro.Count = 0; end; procedure TfCadastroReceita.ValidarNome(nome: string); begin if (nome.IsEmpty()) then begin mensagensErro.Add(mensagemNomeObrigatorio); end else if (nome.Length > lengthMaximoNomeReceita) then begin mensagensErro.Add(mensagemNomeMuitoLongo); end; end; procedure TfCadastroReceita.ValidarQuantidade(quantidade: integer); begin if ((quantidade <= valorMinimoQuantidade) or (quantidade > valorMaximoQuantidade)) then begin mensagensErro.Add(mensagemQuantidadeInvalida); end; end; procedure TfCadastroReceita.ValidarTempoPreparo(tempoPreparo: string); begin if (tempoPreparo = '00:00:00') then begin mensagensErro.Add(mensagemTempoPreparoObrigatorio); end; end; end.
unit VerInfo; {$mode objfpc}{$H+} interface uses SysUtils, Classes, Forms // FPC 3.0 fileinfo reads exe resources as long as you register the appropriate units , fileinfo , winpeimagereader {need this for reading exe info} //, elfreader {needed for reading ELF executables} //, machoreader {needed for reading MACH-O executables} ; const InfoNum = 10; InfoKey: array[1..InfoNum] of string = ('CompanyName', 'FileDescription', 'FileVersion', 'InternalName', 'LegalCopyright', 'LegalTradeMarks', 'OriginalFileName', 'ProductName', 'ProductVersion', 'Comments'); var InfoData: array[1..InfoNum] of string; procedure GetVersionInfo; implementation procedure GetVersionInfo; var FileVerInfo: TFileVersionInfo; i: integer; begin FileVerInfo:=TFileVersionInfo.Create(nil); try FileVerInfo.ReadFileInfo; for i := low(InfoKey) to high(InfoKey) do begin InfoData[i] := FileVerInfo.VersionStrings.Values[InfoKey[i]]; end; finally FileVerInfo.Free; end; end; end.