text
stringlengths
14
6.51M
unit chCtoPAS; interface function ChangeCHeaderToPas(CHeader : string) : string; function ChangeCDefineToPasConst(CDef : string) : string; implementation uses Col; {Auxiliar data types} type TParameter = class public VarName : string; VarType : string; public constructor Create(aVarName, aVarType : string); end; type TParameterList = class private fParams : TCollection; private function GetParam(index : integer) : TParameter; function GetCount : integer; public constructor Create; destructor Destroy; override; procedure Add(VarName, VarType : string); public property Params[index : integer] : TParameter read GetParam; default; property Count : integer read GetCount; end; {TParameter ...} constructor TParameter.Create; begin inherited Create; VarName := aVarName; VarType := aVarType; end; {TParameterList ...} function TParameterList.GetParam(index : integer) : TParameter; begin Result := TParameter(fParams[index]); end; function TParameterList.GetCount : integer; begin Result := fParams.Count; end; constructor TParameterList.Create; begin inherited Create; fParams := TCollection.Create(5, 5, rkBelonguer); end; destructor TParameterList.Destroy; begin fParams.Free; inherited Destroy; end; procedure TParameterList.Add(VarName, VarType : string); begin fParams.Insert(TParameter.Create(VarName, VarType)); end; {Auxilar variables} var FunctionName : string; ReturnType : string; ParamList : TParameterList; Sentence : string; p : integer; {Auxiliar subroutines} procedure SkipSpaces; begin while (p < length(Sentence)) and (Sentence[p] in [#0..#$20]) do inc(p); end; function ReadIdentifier : string; begin Result := ''; while (p < length(Sentence)) and (Sentence[p] in ['A'..'Z', 'a'..'z', '0'..'9', '_']) do begin Result := Result + Sentence[p]; inc(p); end; end; function ReadBlock : string; begin Result := ''; while (p < length(Sentence)) and not (Sentence[p] in [#0..#$20]) do begin Result := Result + Sentence[p]; inc(p); end; end; procedure ReadParameter; var vn : string; vt : string; begin SkipSpaces; vt := ReadIdentifier; SkipSpaces; vn := ReadIdentifier; ParamList.Add(vn, vt); end; procedure ReadParameters; var NextChar : char; begin SkipSpaces; if (p <= length(Sentence)) and (Sentence[p] <> ')') then begin ReadParameter; SkipSpaces; if p <= length(Sentence) then NextChar := Sentence[p] else NextChar := #0; while NextChar = ',' do begin inc(p); // Avoid COMA ReadParameter; SkipSpaces; if p <= length(Sentence) then NextChar := Sentence[p] else NextChar := #0; end; end; end; function BuildParams : string; var i : integer; begin Result := ''; if ParamList.Count > 0 then begin Result := ParamList[0].VarName + ' : ' + ParamList[0].VarType; i := 1; while i < ParamList.Count do begin Result := Result + '; ' + ParamList[i].VarName + ' : ' + ParamList[i].VarType; inc(i); end; Result := '(' + Result + ')'; end; end; function BuildPascalHeader : string; begin if ReturnType = 'void' then Result := 'procedure ' else Result := 'function '; Result := Result + FunctionName + BuildParams; if ReturnType <> 'void' then Result := Result + ' : ' + ReturnType + ';' else Result := Result + ';'; end; {Main routine} function ChangeCHeaderToPas(CHeader : string) : string; begin {Initialize} ParamList := TParameterList.Create; Sentence := CHeader; p := 1; {Read tokens} SkipSpaces; ReturnType := ReadIdentifier; SkipSpaces; FunctionName := ReadIdentifier; SkipSpaces; inc(p); // avoid '(' ReadParameters; inc(p); // avoid ')' if FunctionName = '' // Consider: FunctName(ParamList) then begin FunctionName := ReturnType; ReturnType := 'integer'; end; {Build PASCAL sentence} Result := BuildPascalHeader; {Get rid of the list} ParamList.Free; end; function ChangeCDefineToPasConst(CDef : string) : string; var decl, value : string; begin Sentence := CDef; p := 0; SkipSpaces; ReadBlock; SkipSpaces; decl := ReadBlock; SkipSpaces; value := ReadBlock; SkipSpaces; result := ' ' + decl + ' := ' + value + ' ' + ReadBlock; end; end.
program SPLITMVS ( INPUT , OUTPUT , OUTF001 , OUTF002 , OUTF003 , OUTF004 , OUTF005 , OUTF006 , OUTF007 , OUTF008 , OUTF009 , OUTF00A , OUTF00B , OUTF00C , OUTF00D , OUTF00E , OUTF00F ) ; (***********************************************************) (* *) (* This program creates on MVS all the files *) (* of the Pascal system from the large download file *) (* named PASCALN.TXT. *) (* *) (* It is similar to SPLITPAS.PAS, which creates *) (* directories on Windows from the same file. *) (* *) (***********************************************************) (* *) (* Author: Bernd Oppolzer - December 2017 *) (* *) (***********************************************************) const SIZEDSN = 44 ; SIZEMEM = 8 ; SIZEEXT = 3 ; MAXLINEOFFS = 72 ; MAXOUT = 100 ; type CHARPTR = -> CHAR ; ZEILE = CHAR ( 128 ) ; DSNAME = CHAR ( SIZEDSN ) ; var OUTF001 : TEXT ; OUTF002 : TEXT ; OUTF003 : TEXT ; OUTF004 : TEXT ; OUTF005 : TEXT ; OUTF006 : TEXT ; OUTF007 : TEXT ; OUTF008 : TEXT ; OUTF009 : TEXT ; OUTF00A : TEXT ; OUTF00B : TEXT ; OUTF00C : TEXT ; OUTF00D : TEXT ; OUTF00E : TEXT ; OUTF00F : TEXT ; FN : CHAR ; ZINP : ZEILE ; ZOUT : CHAR ( 1000 ) ; LOUT : INTEGER ; OUTPOS : INTEGER ; CPIN : CHARPTR ; CPOUT : CHARPTR ; TAG : CHAR ( 6 ) ; DSN : CHAR ( SIZEDSN ) ; MEM : CHAR ( SIZEMEM ) ; EXT : CHAR ( SIZEEXT ) ; HEXFLAG : CHAR ; procedure ASSIGN_FILE ( PDSN : CHARPTR ; PMEM : CHARPTR ; PEXT : CHARPTR ; HEXFLAG : CHAR ) ; (***********************************************************) (* *) (* this procedure assigns a file name and path *) (* to the pascal file OUTBIN or OUTF001 *) (* (depending on the HEXFLAG). The directory is *) (* built from the DSN, the file name is built from *) (* the member name and the extension *) (* *) (***********************************************************) var DSN : CHAR ( SIZEDSN ) ; MEM : CHAR ( SIZEMEM ) ; EXT : CHAR ( SIZEEXT ) ; PFADNAME : CHAR ( SIZEDSN ) ; PFADLEN : INTEGER ; FILENAME : CHAR ( 100 ) ; FILELEN : INTEGER ; I : INTEGER ; MD_CMD : CHAR ( 100 ) ; RC : INTEGER ; CMDPART : CHAR ( 80 ) ; const DSN_TAB : array [ 1 .. 15 ] of CHAR ( SIZEDSN ) = ( 'PASCALN.COMPILER.PAS ' , 'PASCALN.COMPILER.CNTL ' , 'PASCALN.COMPILER.MESSAGES ' , 'PASCALN.COMPILER.PROCLIB ' , 'PASCALN.RUNTIME.ASM ' , 'PASCALN.TESTPGM.ASM ' , 'PASCALN.TESTPGM.PAS ' , 'PASCALN.TESTPGM.CNTL ' , 'PASCALN.COMPILER.TEXT ' , 'PASCALN.RUNTIME.TEXT ' , 'PASCALN.RUNTIME.MATHTEXT ' , 'PASCALN.OLDCOMP.CNTL ' , 'PASCALN.OLDCOMP.SAMPLE ' , 'PASCALN.OLDCOMP.SOURCE ' , ' ' ) ; FN_TAB : array [ 1 .. 15 ] of CHAR = '123456789ABCDEF' ; begin (* ASSIGN_FILE *) MEMCPY ( ADDR ( DSN ) , PDSN , SIZEDSN ) ; MEMCPY ( ADDR ( MEM ) , PMEM , SIZEMEM ) ; MEMCPY ( ADDR ( EXT ) , PEXT , SIZEEXT ) ; WRITELN ( '-----------------------------' ) ; WRITELN ( 'dsn = ' , DSN ) ; WRITELN ( 'mem = ' , MEM ) ; WRITELN ( 'ext = ' , EXT ) ; WRITELN ( 'hex = ' , HEXFLAG ) ; WRITELN ( '-----------------------------' ) ; /********************************************************/ /* set fn (global char) depeding on filename */ /* read from input file pascaln.txt */ /********************************************************/ FN := ' ' ; for I := 1 to 15 do if DSN = DSN_TAB [ I ] then begin FN := FN_TAB [ I ] ; break end (* then *) ; /********************************************************/ /* ASSign member and open file for writing */ /********************************************************/ case FN of '1' : begin ASSIGNMEM ( OUTF001 , ADDR ( MEM ) , 8 ) ; REWRITE ( OUTF001 ) ; end (* tag/ca *) ; '2' : begin ASSIGNMEM ( OUTF002 , ADDR ( MEM ) , 8 ) ; REWRITE ( OUTF002 ) ; end (* tag/ca *) ; '3' : begin ASSIGNMEM ( OUTF003 , ADDR ( MEM ) , 8 ) ; REWRITE ( OUTF003 ) ; end (* tag/ca *) ; '4' : begin ASSIGNMEM ( OUTF004 , ADDR ( MEM ) , 8 ) ; REWRITE ( OUTF004 ) ; end (* tag/ca *) ; '5' : begin ASSIGNMEM ( OUTF005 , ADDR ( MEM ) , 8 ) ; REWRITE ( OUTF005 ) ; end (* tag/ca *) ; '6' : begin ASSIGNMEM ( OUTF006 , ADDR ( MEM ) , 8 ) ; REWRITE ( OUTF006 ) ; end (* tag/ca *) ; '7' : begin ASSIGNMEM ( OUTF007 , ADDR ( MEM ) , 8 ) ; REWRITE ( OUTF007 ) ; end (* tag/ca *) ; '8' : begin ASSIGNMEM ( OUTF008 , ADDR ( MEM ) , 8 ) ; REWRITE ( OUTF008 ) ; end (* tag/ca *) ; '9' : begin ASSIGNMEM ( OUTF009 , ADDR ( MEM ) , 8 ) ; REWRITE ( OUTF009 ) ; end (* tag/ca *) ; 'A' : begin ASSIGNMEM ( OUTF00A , ADDR ( MEM ) , 8 ) ; REWRITE ( OUTF00A ) ; end (* tag/ca *) ; 'B' : begin ASSIGNMEM ( OUTF00B , ADDR ( MEM ) , 8 ) ; REWRITE ( OUTF00B ) ; end (* tag/ca *) ; 'C' : begin ASSIGNMEM ( OUTF00C , ADDR ( MEM ) , 8 ) ; REWRITE ( OUTF00C ) ; end (* tag/ca *) ; 'D' : begin ASSIGNMEM ( OUTF00D , ADDR ( MEM ) , 8 ) ; REWRITE ( OUTF00D ) ; end (* tag/ca *) ; 'E' : begin ASSIGNMEM ( OUTF00E , ADDR ( MEM ) , 8 ) ; REWRITE ( OUTF00E ) ; end (* tag/ca *) ; 'F' : begin ASSIGNMEM ( OUTF00F , ADDR ( MEM ) , 8 ) ; REWRITE ( OUTF00F ) ; end (* tag/ca *) ; end (* case *) ; end (* ASSIGN_FILE *) ; procedure CLOSE_FILE ; begin (* CLOSE_FILE *) case FN of '1' : CLOSE ( OUTF001 ) ; '2' : CLOSE ( OUTF002 ) ; '3' : CLOSE ( OUTF003 ) ; '4' : CLOSE ( OUTF004 ) ; '5' : CLOSE ( OUTF005 ) ; '6' : CLOSE ( OUTF006 ) ; '7' : CLOSE ( OUTF007 ) ; '8' : CLOSE ( OUTF008 ) ; '9' : CLOSE ( OUTF009 ) ; 'A' : CLOSE ( OUTF00A ) ; 'B' : CLOSE ( OUTF00B ) ; 'C' : CLOSE ( OUTF00C ) ; 'D' : CLOSE ( OUTF00D ) ; 'E' : CLOSE ( OUTF00E ) ; 'F' : CLOSE ( OUTF00F ) ; end (* case *) ; end (* CLOSE_FILE *) ; procedure WRITEBUF ( var OUTF : TEXT ; HEXFLAG : CHAR ; CPOUT : CHARPTR ; LOUT : INTEGER ) ; var I : INTEGER ; H : INTEGER ; HEX : INTEGER ; CH : CHAR ; CPLAST : CHARPTR ; OUTREC : CHAR ( 80 ) ; (***********************************************************) (* *) (* the buffer (addressed by cpout, length in lout) *) (* is written to the output file. *) (* *) (* if hex, the decoding is done. *) (* *) (* if not hex, trailing blanks are eliminated. *) (* *) (***********************************************************) begin (* WRITEBUF *) if HEXFLAG = 'H' then begin OUTREC := '' ; for I := 1 to 80 do begin CH := CPOUT -> ; if ( CH >= '0' ) and ( CH <= '9' ) then H := ORD ( CH ) - ORD ( '0' ) else if ( CH >= 'A' ) and ( CH <= 'F' ) then H := ORD ( CH ) - ORD ( 'A' ) + 10 ; HEX := H * 16 ; CPOUT := PTRADD ( CPOUT , 1 ) ; CH := CPOUT -> ; if ( CH >= '0' ) and ( CH <= '9' ) then H := ORD ( CH ) - ORD ( '0' ) else if ( CH >= 'A' ) and ( CH <= 'F' ) then H := ORD ( CH ) - ORD ( 'A' ) + 10 ; HEX := HEX + H ; CPOUT := PTRADD ( CPOUT , 1 ) ; OUTREC [ I ] := CHR ( HEX ) ; end (* for *) ; WRITELN ( OUTF , OUTREC ) ; end (* then *) else begin CPLAST := PTRADD ( CPOUT , LOUT - 1 ) ; while ( LOUT > 0 ) and ( CPLAST -> = ' ' ) do begin LOUT := LOUT - 1 ; CPLAST := PTRADD ( CPLAST , - 1 ) ; end (* while *) ; for I := 1 to LOUT do begin WRITE ( OUTF , CPOUT -> ) ; CPOUT := PTRADD ( CPOUT , 1 ) ; end (* for *) ; WRITELN ( OUTF ) ; end (* else *) end (* WRITEBUF *) ; procedure WRITE_FILE ( HEXFLAG : CHAR ; CPOUT : CHARPTR ; LOUT : INTEGER ) ; begin (* WRITE_FILE *) case FN of '1' : WRITEBUF ( OUTF001 , HEXFLAG , CPOUT , LOUT ) ; '2' : WRITEBUF ( OUTF002 , HEXFLAG , CPOUT , LOUT ) ; '3' : WRITEBUF ( OUTF003 , HEXFLAG , CPOUT , LOUT ) ; '4' : WRITEBUF ( OUTF004 , HEXFLAG , CPOUT , LOUT ) ; '5' : WRITEBUF ( OUTF005 , HEXFLAG , CPOUT , LOUT ) ; '6' : WRITEBUF ( OUTF006 , HEXFLAG , CPOUT , LOUT ) ; '7' : WRITEBUF ( OUTF007 , HEXFLAG , CPOUT , LOUT ) ; '8' : WRITEBUF ( OUTF008 , HEXFLAG , CPOUT , LOUT ) ; '9' : WRITEBUF ( OUTF009 , HEXFLAG , CPOUT , LOUT ) ; 'A' : WRITEBUF ( OUTF00A , HEXFLAG , CPOUT , LOUT ) ; 'B' : WRITEBUF ( OUTF00B , HEXFLAG , CPOUT , LOUT ) ; 'C' : WRITEBUF ( OUTF00C , HEXFLAG , CPOUT , LOUT ) ; 'D' : WRITEBUF ( OUTF00D , HEXFLAG , CPOUT , LOUT ) ; 'E' : WRITEBUF ( OUTF00E , HEXFLAG , CPOUT , LOUT ) ; 'F' : WRITEBUF ( OUTF00F , HEXFLAG , CPOUT , LOUT ) ; end (* case *) ; end (* WRITE_FILE *) ; begin (* HAUPTPROGRAMM *) READLN ( ZINP ) ; while not EOF ( INPUT ) do begin MEMCPY ( ADDR ( TAG ) , ADDR ( ZINP ) , 6 ) ; (***********************************************************) (* the record tagged with FILE contains the *) (* meta information (DSN, MEM, EXT, Hex Flag) *) (***********************************************************) if TAG = '++FILE' then begin MEMCPY ( ADDR ( DSN ) , ADDR ( ZINP [ 8 ] ) , SIZEDSN ) ; MEMCPY ( ADDR ( MEM ) , ADDR ( ZINP [ 58 ] ) , SIZEMEM ) ; MEMCPY ( ADDR ( EXT ) , ADDR ( ZINP [ 71 ] ) , SIZEEXT ) ; HEXFLAG := ZINP [ 79 ] ; ASSIGN_FILE ( ADDR ( DSN ) , ADDR ( MEM ) , ADDR ( EXT ) , HEXFLAG ) ; LOUT := - 1 ; repeat if EOF ( INPUT ) then break ; READLN ( ZINP ) ; MEMCPY ( ADDR ( TAG ) , ADDR ( ZINP ) , 6 ) ; (***********************************************************) (* the other records (DATA) are collected into *) (* the large buffer ZOUT. When the buffer is complete, *) (* WRITEBUF is called to flush the buffer. *) (***********************************************************) if HEXFLAG = 'H' then begin if TAG = '++DATA' then begin if ZINP [ 7 ] = '1' then begin if LOUT > 0 then WRITE_FILE ( HEXFLAG , ADDR ( ZOUT ) , LOUT ) ; LOUT := IVALSTR ( ADDR ( ZINP [ 8 ] ) , 5 ) ; OUTPOS := IVALSTR ( ADDR ( ZINP [ 13 ] ) , 5 ) ; OUTPOS := OUTPOS * 2 ; CPOUT := ADDR ( ZOUT ) ; CPOUT := PTRADD ( CPOUT , OUTPOS ) ; CPIN := ADDR ( ZINP [ 19 ] ) ; MEMCPY ( CPOUT , CPIN , 60 ) ; end (* then *) else begin OUTPOS := IVALSTR ( ADDR ( ZINP [ 13 ] ) , 5 ) ; OUTPOS := OUTPOS * 2 ; CPOUT := ADDR ( ZOUT ) ; CPOUT := PTRADD ( CPOUT , OUTPOS ) ; CPIN := ADDR ( ZINP [ 19 ] ) ; MEMCPY ( CPOUT , CPIN , 60 ) ; end (* else *) end (* then *) end (* then *) else if TAG <> '++FILE' then WRITE_FILE ( HEXFLAG , ADDR ( ZINP ) , 80 ) ; until TAG = '++FILE' ; if LOUT > 0 then WRITE_FILE ( HEXFLAG , ADDR ( ZOUT ) , LOUT ) ; CLOSE_FILE ; end (* then *) else begin WRITELN ( '+++ falsche Satzart: ' , TAG ) ; break ; end (* else *) end (* while *) end (* HAUPTPROGRAMM *) .
unit ObjectInspectorHandler; interface uses Classes, VoyagerServerInterfaces, VoyagerInterfaces, Controls, ObjectInspectorHandleViewer; const tidParmName_ClassId = 'ClassId'; tidParmName_ObjectId = 'ObjectId'; tidParmName_xPos = 'x'; tidParmName_yPos = 'y'; const htmlAction_ShowObject = 'SHOWOBJECT'; type TMetaObjectInpectorHandler = class( TInterfacedObject, IMetaURLHandler ) public constructor Create; destructor Destroy; override; private function getName : string; function getOptions : TURLHandlerOptions; function getCanHandleURL( URL : TURL ) : THandlingAbility; function Instantiate : IURLHandler; end; TObjectInpectorHandler = class( TInterfacedObject, IURLHandler ) private constructor Create(MetaHandler : TMetaObjectInpectorHandler); destructor Destroy; override; private fMasterURLHandler : IMasterURLHandler; fControl : TObjectInspectorHandlerViewer; fClientView : IClientView; fClassId : integer; fObjectId : integer; fXPos : word; fYPos : word; fLastWorld : string; private function HandleURL( URL : TURL ) : TURLHandlingResult; function HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult; function getControl : TControl; procedure setMasterURLHandler( URLHandler : IMasterURLHandler ); end; const tidHandlerName_ObjInspector = 'ObjectInspector'; implementation uses SysUtils, URLParser, ServerCnxHandler, ServerCnxEvents, Events, Protocol; // TMetaObjectInpectorHandler constructor TMetaObjectInpectorHandler.Create; begin inherited; end; destructor TMetaObjectInpectorHandler.Destroy; begin inherited; end; function TMetaObjectInpectorHandler.getName : string; begin result := tidHandlerName_ObjInspector; end; function TMetaObjectInpectorHandler.getOptions : TURLHandlerOptions; begin result := [hopCacheable]; end; function TMetaObjectInpectorHandler.getCanHandleURL( URL : TURL ) : THandlingAbility; begin result := 0; end; function TMetaObjectInpectorHandler.Instantiate : IURLHandler; begin result := TObjectInpectorHandler.Create(self); end; // TObjectInpectorHandler constructor TObjectInpectorHandler.Create(MetaHandler : TMetaObjectInpectorHandler); begin inherited Create; fControl := TObjectInspectorHandlerViewer.Create( nil ); fControl.URLHadler := self; end; destructor TObjectInpectorHandler.Destroy; begin fControl.Free; inherited; end; function TObjectInpectorHandler.HandleURL( URL : TURL ) : TURLHandlingResult; var action : string; begin try action := GetURLAction(URL); if action = htmlAction_ShowObject then begin fXPos := StrToInt(GetParmValue(URL, tidParmName_xPos)); fYPos := StrToInt(GetParmValue(URL, tidParmName_yPos)); fClassId := StrToInt(GetParmValue(URL, tidParmName_ClassId)); fObjectId := StrToInt(GetParmValue(URL, tidParmName_ObjectId)); try fControl.ChangeObject(fClientView, fXPos, fYPos, fClassId, fObjectId); result := urlNotHandled; except result := urlHandled; end; end else if (action = urlAction_FindSuppliers) or (action = urlAction_FindClients) then result := fControl.PropSheetContainer.HandleURL(URL, false) else result := fControl.PropSheetContainer.HandleURL(URL, true); except result := urlNotHandled; end; end; function TObjectInpectorHandler.HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult; var RefreshObject : TRefreshObjectInfo absolute info; begin result := evnHandled; try case EventId of evnRefresh : begin fControl.PropSheetContainer.Refresh; result := evnHandled; end; evnHandlerExposed : begin fControl.Exposed; if fLastWorld <> '' then begin if (fLastWorld <> fClientView.getDAAddr) and (fControl.PropSheetContainer <> nil) then begin fLastWorld := fClientView.getDAAddr; fControl.PropSheetContainer.ClearConnections; end; end else fLastWorld := fClientView.getDAAddr; result := evnHandled; end; evnHandlerUnexposed : begin fMasterURLHandler.HandleURL('?frame_Id=SupplyFinder&frame_Close=YES'); fMasterURLHandler.HandleURL('?frame_Id=ClientFinder&frame_Close=YES'); fControl.Unexposed; result := evnHandled; end; evnRefreshObject : if (RefreshObject.KindOfChange = fchStructure) and (RefreshObject.ObjId = fControl.PropSheetContainer.GetObjectId) then begin fControl.PropSheetContainer.Refresh; result := evnHandled; end; evnLogonStarted : begin fControl.PropSheetContainer.ClearConnections; fMasterURLHandler.HandleURL('?frame_Id=SupplyFinder&frame_Close=YES'); fMasterURLHandler.HandleURL('?frame_Id=ClientFinder&frame_Close=YES'); fMasterURLHandler.HandleURL( '?' + 'frame_Id=' + tidHandlerName_ObjInspector + '&frame_Close=yes' ); result := evnHandled; end; else result := evnNotHandled; end; except result := evnNotHandled; end; end; function TObjectInpectorHandler.getControl : TControl; begin result := fControl; end; procedure TObjectInpectorHandler.setMasterURLHandler( URLHandler : IMasterURLHandler ); begin fMasterURLHandler := URLHandler; fControl.MasterURLHandler := URLHandler; URLHandler.HandleEvent( evnAnswerClientView, fClientView ); end; end.
unit CsQueryExecutor; { $Id: CsQueryExecutor.pas,v 1.9 2013/04/24 09:35:37 lulin Exp $ } // $Log: CsQueryExecutor.pas,v $ // Revision 1.9 2013/04/24 09:35:37 lulin // - портируем. // // Revision 1.8 2006/09/21 11:47:59 narry // - логгирование сетевых сообщений на стороне сервера // // Revision 1.7 2006/03/10 09:29:12 voba // - enh. убрал CsFree etc. // // Revision 1.6 2006/02/08 17:24:29 step // выполнение запросов перенесено из классов-потомков в процедуры объектов // {$I CsDefine.inc} interface uses SysUtils, Contnrs, IdSocketHandle, IdContext, IdTCPServer, IdGlobal, IdCustomTCPServer, IdIOHandler, CsObject, CsCommon, CsDataPipe, CsQueryTypes, CsReplyProcedures; const c_TcpServerListenQueueSize = 50; c_TcpServerTerminateWaitTime = 60 * 1000; type TCsQueryExecutor = class(TCsObject) private f_Server: TCsObject; f_IsStarted: Boolean; f_LogMessages: Boolean; f_TcpServer: TIdTcpServer; f_RegisteredReplyProcedures: TCsReplyProcedures; procedure OnTCPServerExecute(aContext: TIdContext); procedure TcpServerListenExceptionHandler(aThread: TIdListenerThread; aException: Exception); procedure TcpServerExceptionHandler(aContext: TIdContext; aException: Exception); protected procedure Cleanup; override; public constructor Create(aServer: TCsObject); reintroduce; procedure RegisterReplyProcedure(aQueryId: TCsQueryId; aReplyProc: TCsReplyProc); procedure Start(const aIp: string; aPort: TCsPort); procedure Stop; property LogMessages: Boolean read f_LogMessages write f_LogMessages; end; implementation uses l3Base, IdException, CsReply, CsConst, CsErrors, CsServer, CsEventsProcessor; { TCsQueryExecutor } procedure TCsQueryExecutor.Cleanup; begin if f_IsStarted then Stop; l3Free(f_TcpServer); l3Free(f_RegisteredReplyProcedures); f_Server := nil; inherited; end; constructor TCsQueryExecutor.Create(aServer: TCsObject); begin inherited Create; Assert(aServer.InheritsFrom(TCsServer)); f_Server := aServer; f_RegisteredReplyProcedures := TCsReplyProcedures.Create; f_TcpServer := TIdTcpServer.Create(nil); with f_TcpServer do begin ListenQueue := c_TcpServerListenQueueSize; MaxConnections := 0; TerminateWaitTime := c_TcpServerTerminateWaitTime; OnExecute := OnTCPServerExecute; OnListenException := TcpServerListenExceptionHandler; // OnException := TcpServerExceptionHandler; end; // with end; procedure TCsQueryExecutor.OnTCPServerExecute(aContext: TIdContext); var l_Reply: TCsReply; begin try l_Reply := TCsReply.Create(TCsServer(f_Server), aContext, f_RegisteredReplyProcedures); try l_Reply.Run(LogMessages); finally l3Free(l_Reply); end; except on E: Exception do TcpServerExceptionHandler(aContext, E); end; end; procedure TCsQueryExecutor.RegisterReplyProcedure(aQueryId: TCsQueryId; aReplyProc: TCsReplyProc); begin Assert(not f_IsStarted); Assert(Assigned(aReplyProc)); f_RegisteredReplyProcedures.Add(aQueryId, aReplyProc); end; procedure TCsQueryExecutor.Start(const aIp: string; aPort: TCsPort); var l_Binding: TIdSocketHandle; begin if f_IsStarted then Exit; with f_TcpServer do begin Bindings.Clear; l_Binding := Bindings.Add; l_Binding.Port := aPort; l_Binding.IP := aIp; Active := True; end; // with f_IsStarted := True; end; procedure TCsQueryExecutor.Stop; begin if not f_IsStarted then Exit; f_TcpServer.Active := False; f_TcpServer.Bindings.Clear; f_IsStarted := False; end; procedure TCsQueryExecutor.TcpServerExceptionHandler(aContext: TIdContext; aException: Exception); begin if aException is EIdConnClosedGracefully then Exit else if aException is ECsWrongVersionError then TCsServer(f_Server).EventsProcessor.ProcessEvent(c_WrongProtocolVersion, Integer(IPv4ToDWord(aContext.Binding.PeerIp))) else if aException is ECsUnregisteredQueryError then TCsServer(f_Server).EventsProcessor.ProcessEvent(c_UnregisteredQuery, Integer(IPv4ToDWord(aContext.Binding.PeerIp))); end; procedure TCsQueryExecutor.TcpServerListenExceptionHandler(aThread: TIdListenerThread; aException: Exception); begin TCsServer(f_Server).EventsProcessor.ProcessEvent(c_ServerListenerError, Integer(IPv4ToDWord(aThread.Server.Bindings[0].Ip))); aThread.TerminateAndWaitFor; end; end.
// // Created by the DataSnap proxy generator. // 01/02/2017 21:02:41 // unit ClientClassesUnit1; interface uses System.JSON, Datasnap.DSProxyRest, Datasnap.DSClientRest, Data.DBXCommon, Data.DBXClient, Data.DBXDataSnap, Data.DBXJSON, Datasnap.DSProxy, System.Classes, System.SysUtils, Data.DB, Data.SqlExpr, Data.DBXDBReaders, Data.DBXCDSReaders, Data.FireDACJSONReflect, Data.DBXJSONReflect; type IDSRestCachedTFDJSONDataSets = interface; TServerMethods1Client = class(TDSAdminRestClient) private FEchoStringCommand: TDSRestCommand; FReverseStringCommand: TDSRestCommand; FGetProdutosCommand: TDSRestCommand; FGetProdutosCommand_Cache: TDSRestCommand; FInsereProdutosClienteCommand: TDSRestCommand; public constructor Create(ARestConnection: TDSRestConnection); overload; constructor Create(ARestConnection: TDSRestConnection; AInstanceOwner: Boolean); overload; destructor Destroy; override; function EchoString(Value: string; const ARequestFilter: string = ''): string; function ReverseString(Value: string; const ARequestFilter: string = ''): string; function GetProdutos(const ARequestFilter: string = ''): TFDJSONDataSets; function GetProdutos_Cache(const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets; function InsereProdutosCliente(AProdutos: TFDJSONDataSets; const ARequestFilter: string = ''): Boolean; end; IDSRestCachedTFDJSONDataSets = interface(IDSRestCachedObject<TFDJSONDataSets>) end; TDSRestCachedTFDJSONDataSets = class(TDSRestCachedObject<TFDJSONDataSets>, IDSRestCachedTFDJSONDataSets, IDSRestCachedCommand) end; const TServerMethods1_EchoString: array [0..1] of TDSRestParameterMetaData = ( (Name: 'Value'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'string') ); TServerMethods1_ReverseString: array [0..1] of TDSRestParameterMetaData = ( (Name: 'Value'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'string') ); TServerMethods1_GetProdutos: array [0..0] of TDSRestParameterMetaData = ( (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets') ); TServerMethods1_GetProdutos_Cache: array [0..0] of TDSRestParameterMetaData = ( (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TServerMethods1_InsereProdutosCliente: array [0..1] of TDSRestParameterMetaData = ( (Name: 'AProdutos'; Direction: 1; DBXType: 37; TypeName: 'TFDJSONDataSets'), (Name: ''; Direction: 4; DBXType: 4; TypeName: 'Boolean') ); implementation function TServerMethods1Client.EchoString(Value: string; const ARequestFilter: string): string; begin if FEchoStringCommand = nil then begin FEchoStringCommand := FConnection.CreateCommand; FEchoStringCommand.RequestType := 'GET'; FEchoStringCommand.Text := 'TServerMethods1.EchoString'; FEchoStringCommand.Prepare(TServerMethods1_EchoString); end; FEchoStringCommand.Parameters[0].Value.SetWideString(Value); FEchoStringCommand.Execute(ARequestFilter); Result := FEchoStringCommand.Parameters[1].Value.GetWideString; end; function TServerMethods1Client.ReverseString(Value: string; const ARequestFilter: string): string; begin if FReverseStringCommand = nil then begin FReverseStringCommand := FConnection.CreateCommand; FReverseStringCommand.RequestType := 'GET'; FReverseStringCommand.Text := 'TServerMethods1.ReverseString'; FReverseStringCommand.Prepare(TServerMethods1_ReverseString); end; FReverseStringCommand.Parameters[0].Value.SetWideString(Value); FReverseStringCommand.Execute(ARequestFilter); Result := FReverseStringCommand.Parameters[1].Value.GetWideString; end; function TServerMethods1Client.GetProdutos(const ARequestFilter: string): TFDJSONDataSets; begin if FGetProdutosCommand = nil then begin FGetProdutosCommand := FConnection.CreateCommand; FGetProdutosCommand.RequestType := 'GET'; FGetProdutosCommand.Text := 'TServerMethods1.GetProdutos'; FGetProdutosCommand.Prepare(TServerMethods1_GetProdutos); end; FGetProdutosCommand.Execute(ARequestFilter); if not FGetProdutosCommand.Parameters[0].Value.IsNull then begin FUnMarshal := TDSRestCommand(FGetProdutosCommand.Parameters[0].ConnectionHandler).GetJSONUnMarshaler; try Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FGetProdutosCommand.Parameters[0].Value.GetJSONValue(True))); if FInstanceOwner then FGetProdutosCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TServerMethods1Client.GetProdutos_Cache(const ARequestFilter: string): IDSRestCachedTFDJSONDataSets; begin if FGetProdutosCommand_Cache = nil then begin FGetProdutosCommand_Cache := FConnection.CreateCommand; FGetProdutosCommand_Cache.RequestType := 'GET'; FGetProdutosCommand_Cache.Text := 'TServerMethods1.GetProdutos'; FGetProdutosCommand_Cache.Prepare(TServerMethods1_GetProdutos_Cache); end; FGetProdutosCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTFDJSONDataSets.Create(FGetProdutosCommand_Cache.Parameters[0].Value.GetString); end; function TServerMethods1Client.InsereProdutosCliente(AProdutos: TFDJSONDataSets; const ARequestFilter: string): Boolean; begin if FInsereProdutosClienteCommand = nil then begin FInsereProdutosClienteCommand := FConnection.CreateCommand; FInsereProdutosClienteCommand.RequestType := 'POST'; FInsereProdutosClienteCommand.Text := 'TServerMethods1."InsereProdutosCliente"'; FInsereProdutosClienteCommand.Prepare(TServerMethods1_InsereProdutosCliente); end; if not Assigned(AProdutos) then FInsereProdutosClienteCommand.Parameters[0].Value.SetNull else begin FMarshal := TDSRestCommand(FInsereProdutosClienteCommand.Parameters[0].ConnectionHandler).GetJSONMarshaler; try FInsereProdutosClienteCommand.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(AProdutos), True); if FInstanceOwner then AProdutos.Free finally FreeAndNil(FMarshal) end end; FInsereProdutosClienteCommand.Execute(ARequestFilter); Result := FInsereProdutosClienteCommand.Parameters[1].Value.GetBoolean; end; constructor TServerMethods1Client.Create(ARestConnection: TDSRestConnection); begin inherited Create(ARestConnection); end; constructor TServerMethods1Client.Create(ARestConnection: TDSRestConnection; AInstanceOwner: Boolean); begin inherited Create(ARestConnection, AInstanceOwner); end; destructor TServerMethods1Client.Destroy; begin FEchoStringCommand.DisposeOf; FReverseStringCommand.DisposeOf; FGetProdutosCommand.DisposeOf; FGetProdutosCommand_Cache.DisposeOf; FInsereProdutosClienteCommand.DisposeOf; inherited; end; end.
unit FMX.QRCode; interface uses System.Classes, System.SysUtils, System.Types, System.UITypes, FMX.Types, FMX.Controls, FMX.Graphics, FMX.Objects, FMX.MultiResBitmap, FMX.Platform, FMX.ComponentsCommon, DelphiZXingQRCode; type [ComponentPlatformsAttribute(TFMXPlatforms)] TFMXQRCode = class(TControl) private FLines: TStrings; FNeedUpdate: Boolean; FForeGround: TAlphaColor; FBackGround: TAlphaColor; FQRImage: TBitmap; FQuietZone: Integer; FIcon: TImage; procedure SetLines(const Value: TStrings); function GetText: string; procedure SetText(const Value: string); procedure OnLinesChange(Sender: TObject); procedure Update; procedure SetForeGround(const Value: TAlphaColor); procedure SetBackGround(const Value: TAlphaColor); procedure CreateQRImage; procedure SetQuiteZone(const Value: Integer); function GetIconVisible: Boolean; procedure SetIconVisible(const Value: Boolean); function GetIconSize: TControlSize; procedure SetIconSize(const Value: TControlSize); function GetIconBitmap: TFixedMultiResBitmap; procedure SetIconBitmap(const Value: TFixedMultiResBitmap); protected procedure Paint;override; procedure Resize; override; public constructor Create(AOwner: TComponent); override; destructor Destroy;override; property Text: string read GetText write SetText; published property Align; property Anchors; property ClipChildren default False; property ClipParent default False; property Cursor default crDefault; property DragMode default TDragMode.dmManual; property EnableDragHighlight default True; property Enabled default True; property Locked default False; property Height; property HitTest default True; property Padding; property Opacity; property Margins; property PopupMenu; property Position; property RotationAngle; property RotationCenter; property Scale; property Size; property Visible default True; property Width; property BackGround: TAlphaColor read FBackGround write SetBackGround default TAlphaColors.White; property ForeGround: TAlphaColor read FForeGround write SetForeGround default TAlphaColors.Black; property IconBitmap: TFixedMultiResBitmap read GetIconBitmap write SetIconBitmap; property IconSize: TControlSize read GetIconSize write SetIconSize; property IconVisible: Boolean read GetIconVisible write SetIconVisible default False; property Lines: TStrings read FLines write SetLines; property QuiteZone: Integer read FQuietZone write SetQuiteZone default 2; { Drag and Drop events } property OnDragEnter; property OnDragLeave; property OnDragOver; property OnDragDrop; property OnDragEnd; { Mouse events } property OnClick; property OnDblClick; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnMouseWheel; property OnMouseEnter; property OnMouseLeave; property OnPainting; property OnPaint; property OnResize; {$IF (RTLVersion >= 32)} // Tokyo property OnResized; {$ENDIF} end; implementation { TFMXToast } constructor TFMXQRCode.Create(AOwner: TComponent); begin inherited; FQuietZone := 2; FBackGround := TAlphaColors.White; FForeGround := TAlphaColors.Black; FLines := TStringList.Create; FLines.Text := 'https://github.com/zhaoyipeng/FMXComponents'; TStringList(FLines).OnChange := OnLinesChange; FIcon := TImage.Create(Self); FIcon.Parent := Self; FIcon.Align := TAlignLayout.Center; FIcon.Visible := False; FIcon.Stored := False; FIcon.Width := 48; FIcon.Height := 48; FQRImage := nil; FNeedUpdate := True; SetSize(148, 148); end; procedure TFMXQRCode.CreateQRImage; var QRCode: TDelphiZXingQRCode; Row, Column, I, J: Integer; Data: TBitmapData; ScreenService: IFMXScreenService; Scale1: Single; begin if TPlatformServices.Current.SupportsPlatformService(IFMXScreenService, ScreenService) then Scale1 := ScreenService.GetScreenScale else Scale1 := 1; if FNeedUpdate then begin if not Assigned(FQRImage) then FQRImage := TBitmap.Create( Round(Scale1 * Self.Width), Round(Scale1 * Self.Height)); QRCode := TDelphiZXingQRCode.Create; try QRCode.Data := Text; QRCode.Encoding := TQRCodeEncoding.qrAuto; QRCode.QuietZone := FQuietZone; FQRImage.Map(TMapAccess.Write, Data); try for Row := 0 to FQRImage.Height - 1 do begin J := Row * QRCode.Rows div FQRImage.Height; for Column := 0 to FQRImage.Width - 1 do begin I := Column * QRCode.Columns div FQRImage.Width; if (QRCode.IsBlack[J, I]) then begin Data.SetPixel(Column, Row, FForeGround); end else begin Data.SetPixel(Column, Row, FBackGround); end; end; end; finally FQRImage.Unmap(Data); end; finally QRCode.Free; end; FNeedUpdate := False; end; end; destructor TFMXQRCode.Destroy; begin FQRImage.Free; inherited; end; function TFMXQRCode.GetIconBitmap: TFixedMultiResBitmap; begin Result := FIcon.MultiResBitmap; end; function TFMXQRCode.GetIconSize: TControlSize; begin Result := FIcon.Size; end; function TFMXQRCode.GetIconVisible: Boolean; begin Result := FIcon.Visible; end; function TFMXQRCode.GetText: string; begin Result := FLines.Text; end; procedure TFMXQRCode.OnLinesChange(Sender: TObject); begin Update; end; procedure TFMXQRCode.Paint; //var // Brush: TBrush; begin inherited; CreateQRImage; Canvas.DrawBitmap(FQRImage, FQRImage.Bounds, RectF(0,0,Width,Height), AbsoluteOpacity, True ); end; procedure TFMXQRCode.Resize; begin inherited; Update; Repaint; end; procedure TFMXQRCode.SetBackGround(const Value: TAlphaColor); begin if FBackGround <> Value then begin FBackGround := Value; Update; end; end; procedure TFMXQRCode.SetForeGround(const Value: TAlphaColor); begin if FForeGround <> Value then begin FForeGround := Value; Update; end; end; procedure TFMXQRCode.SetIconBitmap(const Value: TFixedMultiResBitmap); begin FIcon.MultiResBitmap := Value; end; procedure TFMXQRCode.SetIconSize(const Value: TControlSize); begin FIcon.Size := Value; end; procedure TFMXQRCode.SetIconVisible(const Value: Boolean); begin FIcon.Visible := Value; end; procedure TFMXQRCode.SetLines(const Value: TStrings); begin FLines.Assign(Value); end; procedure TFMXQRCode.SetQuiteZone(const Value: Integer); begin if FQuietZone <> Value then begin FQuietZone := Value; Update; end; end; procedure TFMXQRCode.SetText(const Value: string); begin FLines.Text := Value; end; procedure TFMXQRCode.Update; begin FNeedUpdate := True; Repaint; end; end.
unit Unit2; interface {$DEFINE ICS} uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, WinSock, Vcl.ExtCtrls, StrUtils, Vcl.CheckLst, TypInfo, SChannel.JwaWinError, SChannel.JwaSspi, SChannel.JwaWinCrypt, SChannel.Utils, {$IFDEF ICS} SChannel.IcsWSocket, OverbyteIcsWSocket, OverbyteIcsLogger, OverbyteIcsUtils, {$ENDIF} SChannelSocketRequest; type TForm2 = class(TForm) btnReqSync: TButton; mLog: TMemo; eURL: TEdit; lblProgress: TLabel; mReq: TMemo; chbDumps: TCheckBox; lblTraf: TLabel; btnReqAsync: TButton; lbl: TLabel; chbData: TCheckBox; Memo1: TMemo; chbReuseSessions: TCheckBox; chbUseProxy: TCheckBox; eProxy: TEdit; chbManualCertCheck: TCheckBox; lbxIgnoreFlags: TCheckListBox; Label1: TLabel; chbPrintCert: TCheckBox; chbNoCheckCert: TCheckBox; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnReqSyncClick(Sender: TObject); procedure btnReqAsyncClick(Sender: TObject); private SharedSessionCreds: ISharedSessionCreds; function GetSharedCreds: ISharedSessionCreds; function GetCertCheckIgnoreFlags: TCertCheckIgnoreFlags; public {$IFDEF ICS} icsSock: TSChannelWSocket; procedure WSocketBgException(Sender: TObject; E: Exception; var CanClose: Boolean); procedure WSocketDataAvailable(Sender: TObject; ErrCode: Word); procedure WSocketSessionConnected(Sender: TObject; ErrCode: Word); procedure IcsLoggerLogEvent(Sender: TObject; LogOption: TLogOption; const Msg: string); procedure WSocketDataSent(Sender: TObject; ErrCode: Word); procedure WSocketException(Sender: TObject; SocExcept: ESocketException); procedure WSocketSessionClosed(Sender: TObject; ErrCode: Word); procedure WSocketTLSDone(Sender: TObject); {$ENDIF} procedure Log(const s: string; AddStamp: Boolean); overload; procedure Log(const s: string); overload; end; var Form2: TForm2; hClientCreds: CredHandle = (); PrintDumps: Boolean = False; PrintData: Boolean = False; PrintCerts: Boolean = False; ManualCertCheck: Boolean = False; const DefaultReq = 'HEAD / HTTP/1.1'+sLineBreak+'Connection: close'+sLineBreak+sLineBreak; implementation {$R *.dfm} procedure TForm2.FormCreate(Sender: TObject); var IgnFlag: TCertCheckIgnoreFlag; begin if mReq.Lines.Count = 0 then mReq.Text := DefaultReq; for IgnFlag := Low(TCertCheckIgnoreFlag) to High(TCertCheckIgnoreFlag) do lbxIgnoreFlags.Items.Add(GetEnumName(TypeInfo(TCertCheckIgnoreFlag), Ord(IgnFlag))); end; procedure TForm2.FormClose(Sender: TObject; var Action: TCloseAction); begin SChannelSocketRequest.SharedSessionCreds := nil; SharedSessionCreds := nil; SChannel.Utils.Fin; end; procedure TForm2.Log(const s: string; AddStamp: Boolean); begin mLog.Lines.Add(IfThen(AddStamp, TimeToStr(Now)+' ')+s); if mLog.Lines.Count > 2000 then begin mLog.Lines.BeginUpdate; // Deleting lines one by one is damn slow. // So we take length of text and cut half of it mLog.SelStart := 0; mLog.SelLength := mLog.GetTextLen div 2; mLog.SelText := ''; // Remove probably partial line mLog.Lines.Delete(0); mLog.Lines.EndUpdate; end; end; procedure TForm2.Log(const s: string); begin Log(s, True); end; function TForm2.GetSharedCreds: ISharedSessionCreds; begin if chbReuseSessions.Checked then if SharedSessionCreds = nil then SharedSessionCreds := CreateSharedCreds else else SharedSessionCreds := nil; Result := SharedSessionCreds; end; function TForm2.GetCertCheckIgnoreFlags: TCertCheckIgnoreFlags; var i: Integer; begin Result := []; for i := 0 to lbxIgnoreFlags.Items.Count - 1 do if lbxIgnoreFlags.Checked[i] then Include(Result, TCertCheckIgnoreFlag(i)); end; const SLblBtnSync: array[Boolean] of string = ('Request sync', 'Cancel'); SLblBtnAsync: array[Boolean] of string = ('Request async', 'Cancel'); procedure TForm2.btnReqSyncClick(Sender: TObject); begin // Cancel if TButton(Sender).Caption = SLblBtnSync[True] then begin SChannelSocketRequest.Cancel := True; TButton(Sender).Caption := SLblBtnSync[False]; Exit; end; // Connect if TButton(Sender).Caption = SLblBtnSync[False] then begin SChannelSocketRequest.Cancel := False; TButton(Sender).Caption := SLblBtnSync[True]; SChannelSocketRequest.PrintDumps := chbDumps.Checked; SChannelSocketRequest.PrintData := chbData.Checked; SChannelSocketRequest.PrintCerts := chbPrintCert.Checked; SChannelSocketRequest.ManualCertCheck := chbManualCertCheck.Checked; SChannelSocketRequest.CertCheckIgnoreFlags := GetCertCheckIgnoreFlags; SChannel.Utils.Init; SChannelSocketRequest.LogFn := Self.Log; SChannelSocketRequest.SharedSessionCreds := GetSharedCreds; Request(eURL.Text, IfThen(mReq.Lines.Count > 0, mReq.Text, DefaultReq)); SChannelSocketRequest.Cancel := False; SChannelSocketRequest.SharedSessionCreds := nil; // important to nil all refs before SChannel.Utils.Fin is called TButton(Sender).Caption := SLblBtnSync[False]; end; end; procedure TForm2.btnReqAsyncClick(Sender: TObject); var SessionData: TSessionData; begin {$IFDEF ICS} // Cancel if TButton(Sender).Caption = SLblBtnAsync[True] then begin if icsSock <> nil then icsSock.Close; TButton(Sender).Caption := SLblBtnAsync[False]; Exit; end; // Connect if TButton(Sender).Caption = SLblBtnAsync[False] then begin TButton(Sender).Caption := SLblBtnAsync[True]; PrintDumps := chbDumps.Checked; PrintData := chbData.Checked; PrintCerts := chbPrintCert.Checked; ManualCertCheck := chbManualCertCheck.Checked; icsSock := TSChannelWSocket.Create(Self); icsSock.OnBgException := WSocketBgException; icsSock.OnDataAvailable := WSocketDataAvailable; icsSock.OnSessionConnected := WSocketSessionConnected; icsSock.OnDataSent := WSocketDataSent; icsSock.onException := WSocketException; icsSock.OnSessionClosed := WSocketSessionClosed; icsSock.OnTLSDone := WSocketTLSDone; icsSock.IcsLogger := TIcsLogger.Create(icsSock); icsSock.IcsLogger.LogOptions := LogAllOptDump + [loSslDevel, loDestEvent, loDestFile, loAddStamp]; icsSock.IcsLogger.LogFileName := 'socket.log'; icsSock.IcsLogger.OnIcsLogEvent := IcsLoggerLogEvent; icsSock.Addr := eURL.Text; icsSock.Port := '443'; icsSock.ComponentOptions := [wsoAsyncDnsLookup{, wsoNoReceiveLoop}]; if chbUseProxy.Checked then icsSock.ProxyURL := eProxy.Text // Feature added in "ICS V8.66 - Part 10" else icsSock.ProxyURL := ''; icsSock.Secure := True; SessionData := icsSock.SessionData; SessionData.SharedCreds := GetSharedCreds; if ManualCertCheck then SessionData.Flags := SessionData.Flags + [sfNoServerVerify] else SessionData.Flags := SessionData.Flags - [sfNoServerVerify]; SessionData.CertCheckIgnoreFlags := GetCertCheckIgnoreFlags; icsSock.SessionData := SessionData; icsSock.Connect; end; {$ENDIF} end; {$IFDEF ICS} procedure TForm2.WSocketBgException(Sender: TObject; E: Exception; var CanClose: Boolean); begin Log('WSocket.BgException ' + E.Message); CanClose := True; end; procedure TForm2.WSocketDataAvailable(Sender: TObject; ErrCode: Word); var TrashCanBuf : array [0..1023] of AnsiChar; res : Integer; begin res := TWSocket(Sender).Receive(@TrashCanBuf, SizeOf(TrashCanBuf)-1); // Could be WSAEWOULDBLOCK if res = SOCKET_ERROR then begin if WSAGetLastError <> WSAEWOULDBLOCK then Log(Format('Error reading data from server: %s', [SysErrorMessage(WSAGetLastError)])); Exit; end; TrashCanBuf[res] := #0; Log('WSocket.DataAvailable('+IntToStr(ErrCode)+'), got '+IntToStr(res)+ IfThen(PrintData, sLineBreak+string(PAnsiChar(@TrashCanBuf))) ); Form2.lblTraf.Caption := Format('Traffic: %d total / %d payload', [TSChannelWSocket(Sender).ReadCount, TSChannelWSocket(Sender).PayloadReadCount]); end; procedure TForm2.WSocketSessionConnected(Sender: TObject; ErrCode: Word); var req: string; begin Log('WSocket.SessionConnected'); req := IfThen(mReq.Lines.Count > 0, mReq.Text, DefaultReq); Log('Sending request'+IfThen(PrintData, ':'+sLineBreak+req)); TWSocket(Sender).SendLine(req); end; procedure TForm2.IcsLoggerLogEvent(Sender: TObject; LogOption: TLogOption; const Msg: string); begin Log(Msg, False); if Pos('Handshake bug', Msg) <> 0 then Memo1.Lines.Add(Msg); end; procedure TForm2.WSocketDataSent(Sender: TObject; ErrCode: Word); begin Log('WSocket.DataSent'); end; procedure TForm2.WSocketException(Sender: TObject; SocExcept: ESocketException); begin Log('WSocket.Exception ' + SocExcept.Message); end; procedure TForm2.WSocketSessionClosed(Sender: TObject; ErrCode: Word); begin Log('WSocket.SessionClosed'); Log(Format('Traffic: %d total / %d payload', [TSChannelWSocket(Sender).ReadCount, TSChannelWSocket(Sender).PayloadReadCount])); FreeAndNil(icsSock); btnReqAsync.Caption := SLblBtnAsync[False]; end; type TSChannelWSocketHack = class(TSChannelWSocket) property hContext: CtxtHandle read FhContext; end; procedure TForm2.WSocketTLSDone(Sender: TObject); var Cert: TBytes; Enc: AnsiString; begin Log('WSocket.TLSDone'); if not PrintCerts then Exit; Cert := GetCurrentCert(TSChannelWSocketHack(Sender).hContext); Log('Cert data:'); Enc := Base64Encode(PAnsiChar(Cert), Length(Cert)); Log(string(Enc)); end; {$ENDIF} end.
{ Subroutine SST_R_SYN_INIT * * Init the SST front end for reading SYN files. * * The internal state of the SYN front end is initialized, and system resources * allocated. The module that will contain the syntax parsing code is created. * Subsequent calls to the DOIT entry point for this SST front end will add to * this module. } module sst_r_syn_init; define sst_r_syn_init; %include 'sst_r_syn.ins.pas'; procedure sst_r_syn_init; {init front end state for reading .syn files} var gnam: string_leafname_t; {generic name of input file} fnam_synstart: string_treename_t; {pathname to SYO_SYN.INS.PAS file} sym_p: sst_symbol_p_t; {pointer to module name symbol} stat: sys_err_t; {completion status code} { ********************************************** * * Local function LOOKUP_SYMBOL (NAME) * * Look up symbol in symbol table. The function returns the pointer to the * symbol descriptor with the name NAME. It is an error if the symbol does not * exist. } function lookup_symbol ( in name: string) {name of symbol to look up} :sst_symbol_p_t; {returned pointer to symbol descriptor} var vname: string_var80_t; {var string symbol name} sym_p: sst_symbol_p_t; {pointer to symbol descriptor} stat: sys_err_t; {completion status code} begin vname.max := sizeof(vname.str); {init local var string} string_vstring (vname, name, sizeof(name)); {make var string symbol name} sst_symbol_lookup_name (vname, sym_p, stat); {try to look up name in symbol table} sys_error_abort (stat, 'sst_syn_read', 'symbol_predef_not_found', nil, 0); lookup_symbol := sym_p; {return pointer to symbol descriptor} end; { ********************************************** * * Start of main routine. } begin gnam.max := sizeof(gnam.str); {init local var strings} fnam_synstart.max := sizeof(fnam_synstart.str); { * Read the SYN_SYN.INS.PAS file. This declares all the routines and other * symbols that the syntax parsing code we will generate needs to reference. } sys_cognivis_dir ('lib', fnam_synstart); {make pathname of SYN_SYN.INS.PAS} string_appends (fnam_synstart, '/syn_syn.ins.pas'); sst_r_pas_init; {init for reading Pascal syntax} sst_r.doit^ ( {run Pascal front end} fnam_synstart, {name of Pascal file to read} gnam, {returned generic name of input file} stat); {returned completion status code} if sys_stat_match (sst_subsys_k, sst_stat_err_handled_k, stat) then begin sys_exit_error; {exit quietly with error condition} end; sys_error_abort (stat, 'sst', 'readin', nil, 0); { * Set up the SST front end for reading the user's syntax definition file. } syo_preproc_set (nil); {de-install any Pascal front end preprocessor} sst_r.doit := addr(sst_r_syn_doit); {set up front end call table} { * Save pointers to all the pre-defined symbols we might need later. } { * Routines to call from syntax parsing code. } sym_constr_start_p := lookup_symbol ('syn_p_constr_start'); sym_constr_end_p := lookup_symbol ('syn_p_constr_end'); sym_cpos_push_p := lookup_symbol ('syn_p_cpos_push'); sym_cpos_pop_p := lookup_symbol ('syn_p_cpos_pop'); sym_cpos_get_p := lookup_symbol ('syn_p_cpos_get'); sym_cpos_set_p := lookup_symbol ('syn_p_cpos_set'); sym_tag_start_p := lookup_symbol ('syn_p_tag_start'); sym_tag_end_p := lookup_symbol ('syn_p_tag_end'); sym_ichar_p := lookup_symbol ('syn_p_ichar'); sym_test_string_p := lookup_symbol ('syn_p_test_string'); sym_test_eol_p := lookup_symbol ('syn_p_test_eol'); sym_test_eof_p := lookup_symbol ('syn_p_test_eof'); sym_test_eod_p := lookup_symbol ('syn_p_test_eod'); sym_charcase_p := lookup_symbol ('syn_p_charcase'); { * Data types. } sym_syn_t_p := lookup_symbol ('syn_t'); sym_charcase_t_p := lookup_symbol ('syn_charcase_k_t'); sym_int_p := lookup_symbol ('sys_int_machine_t'); { * Constants. } sym_charcase_down_p := lookup_symbol ('syn_charcase_down_k'); sym_charcase_up_p := lookup_symbol ('syn_charcase_up_k'); sym_charcase_asis_p := lookup_symbol ('syn_charcase_asis_k'); sym_ichar_eol_p := lookup_symbol ('syn_ichar_eol_k'); sym_ichar_eof_p := lookup_symbol ('syn_ichar_eof_k'); sym_ichar_eod_p := lookup_symbol ('syn_ichar_eod_k'); { * Expressions with fixed value. } sst_exp_const_bool (true, exp_true_p); sst_exp_const_bool (false, exp_false_p); { * Initialize the rest of the SYN front end static state (SST_R_SYN common * block). } syn_lib_new ( {start new use of the SYN library} sst_scope_root_p^.mem_p^, {parent memory context} syn_p); {return pointer to new library use state} sst_r_syn_sym_init; {create and init our symbol table} prefix.max := size_char(prefix.str); {init subroutines prefix to empty} prefix.len := 0; def_syn_p := nil; {init to not currently defining a symbol} seq_subr := 1; {init sequence numbers to make unique names} seq_label := 1; seq_int := 1; lab_fall_k := univ_ptr(addr(lab_fall_k)); lab_same_k := univ_ptr(addr(lab_same_k)); sym_error_p := nil; match_var_p := nil; match_exp_p := nil; { * Create the module for all the routines generated from the SYN file. } sst_symbol_new_name ( {create module name symbol} string_v('module_syn'(0)), sym_p, stat); sys_error_abort (stat, 'sst_syn_read', 'module_symbol_create', nil, 0); sst_scope_new; {create new subordinate scope for module} sst_scope_p^.symbol_p := sym_p; sym_p^.symtype := sst_symtype_module_k; {fill in module symbol descriptor} sym_p^.flags := [sst_symflag_def_k, sst_symflag_used_k]; sym_p^.module_scope_p := sst_scope_p; sst_opcode_new; {create MODULE opcode} sst_opc_p^.opcode := sst_opc_module_k; sst_opc_p^.module_sym_p := sym_p; sst_opcode_pos_push (sst_opc_p^.module_p); {switch to defining module contents} end;
unit Network; interface function IsConnected: Boolean; function IsWiFiConnected: Boolean; function IsMobileConnected: Boolean; implementation uses System.SysUtils, Androidapi.JNIBridge, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.JavaTypes, FMX.Helpers.Android, Androidapi.Helpers; type JConnectivityManager = interface; JNetworkInfo = interface; JNetworkInfoClass = interface(JObjectClass) ['{E92E86E8-0BDE-4D5F-B44E-3148BD63A14C}'] end; [JavaSignature('android/net/NetworkInfo')] JNetworkInfo = interface(JObject) ['{6DF61A40-8D17-4E51-8EF2-32CDC81AC372}'] {Methods} function isAvailable: Boolean; cdecl; function isConnected: Boolean; cdecl; function isConnectedOrConnecting: Boolean; cdecl; end; TJNetworkInfo = class(TJavaGenericImport<JNetworkInfoClass, JNetworkInfo>) end; JConnectivityManagerClass = interface(JObjectClass) ['{E03A261F-59A4-4236-8CDF-0068FC6C5FA1}'] {Property methods} function _GetTYPE_WIFI: Integer; cdecl; function _GetTYPE_WIMAX: Integer; cdecl; function _GetTYPE_MOBILE: Integer; cdecl; {Properties} property TYPE_WIFI: Integer read _GetTYPE_WIFI; property TYPE_WIMAX: Integer read _GetTYPE_WIMAX; property TYPE_MOBILE: Integer read _GetTYPE_MOBILE; end; [JavaSignature('android/net/ConnectivityManager')] JConnectivityManager = interface(JObject) ['{1C4C1873-65AE-4722-8EEF-36BBF423C9C5}'] {Methods} function getActiveNetworkInfo: JNetworkInfo; cdecl; function getNetworkInfo(networkType: Integer): JNetworkInfo; cdecl; end; TJConnectivityManager = class(TJavaGenericImport<JConnectivityManagerClass, JConnectivityManager>) end; function GetConnectivityManager: JConnectivityManager; var ConnectivityServiceNative: JObject; begin ConnectivityServiceNative := SharedActivityContext.getSystemService(TJContext.JavaClass.CONNECTIVITY_SERVICE); if not Assigned(ConnectivityServiceNative) then raise Exception.Create('Could not locate Connectivity Service'); Result := TJConnectivityManager.Wrap( (ConnectivityServiceNative as ILocalObject).GetObjectID); if not Assigned(Result) then raise Exception.Create('Could not access Connectivity Manager'); end; function IsConnected: Boolean; var ConnectivityManager: JConnectivityManager; ActiveNetwork: JNetworkInfo; begin ConnectivityManager := GetConnectivityManager; ActiveNetwork := ConnectivityManager.getActiveNetworkInfo; Result := Assigned(ActiveNetwork) and ActiveNetwork.isConnected; end; function IsWiFiConnected: Boolean; var ConnectivityManager: JConnectivityManager; WiFiNetwork: JNetworkInfo; begin ConnectivityManager := GetConnectivityManager; WiFiNetwork := ConnectivityManager.getNetworkInfo(TJConnectivityManager.JavaClass.TYPE_WIFI); Result := WiFiNetwork.isConnected; end; function IsMobileConnected: Boolean; var ConnectivityManager: JConnectivityManager; MobileNetwork: JNetworkInfo; begin ConnectivityManager := GetConnectivityManager; MobileNetwork := ConnectivityManager.getNetworkInfo(TJConnectivityManager.JavaClass.TYPE_MOBILE); Result := MobileNetwork.isConnected; end; end.
unit TestBaseClasses; interface uses dSpec; type TParseContext = class(TContext) public constructor Create(MethodName: string); override; end; implementation constructor TParseContext.Create(MethodName: string); begin inherited Create(MethodName); AutoDoc.Enabled := True; end; end.
unit NewAccount; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, DialMessages, Utils, Placemnt, DataErrors; type TNewAccountForm = class(TForm) AccountPropsGroupBox: TGroupBox; UserNameEdit: TEdit; UserNameLabel: TLabel; PasswordLabel: TLabel; PasswordEdit: TEdit; Password2Edit: TEdit; Password2Label: TLabel; DisplayNameEdit: TEdit; DisplayNameLabel: TLabel; OKButton: TButton; CancelButton: TButton; FormPlacement: TFormPlacement; procedure CancelButtonClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure UserNameEditExit(Sender: TObject); private { Private declarations } public { Public declarations } end; var NewAccountForm: TNewAccountForm; implementation {$R *.dfm} resourcestring rsUserNameEmpty = 'User name is empty!'; rsBadUserName = 'Bad user name!'; rsPasswordEmpty = 'Password is empty!'; rsPasswordsNotMatch = 'Passwords are not the same!'; rsDisplayNameEmpty = 'User name is empty!'; procedure TNewAccountForm.CancelButtonClick(Sender: TObject); begin Close; ModalResult := mrCancel; end; procedure TNewAccountForm.FormClose(Sender: TObject; var Action: TCloseAction); var ErrorStr: string; begin if ModalResult = mrOk then begin ErrorStr := EmptyStr; CheckError(UserNameEdit.Text = EmptyStr, ErrorStr, rsUserNameEmpty); CheckError(PasswordEdit.Text = EmptyStr, ErrorStr, rsPasswordEmpty); CheckError(PasswordEdit.Text <> Password2Edit.Text, ErrorStr, rsPasswordsNotMatch); CheckError(DisplayNameEdit.Text = EmptyStr, ErrorStr, rsDisplayNameEmpty); TryCloseModal(ErrorStr, Action); end; end; procedure TNewAccountForm.UserNameEditExit(Sender: TObject); begin with UserNameEdit do begin if Text <> EmptyStr then begin if IsError(not StrConsistsOfChars(Text, UserNameCharSet), rsBadUserName) then begin SetFocus; end; end; end; end; end.
unit uTextData; interface uses classes; type TTextDataType = (dtNone, dtProc, dtInclude, dtMacro, dtFunc, dtView, dtTrigger); THsTextData = class(TCollectionItem) private FSQL:string; FSQLName:string; FFileName: string; FLoadFileName: string; FFolder: string; FLoadedName: string; FSqlType: TTextDataType; FIsModified: Boolean; procedure SetFolder(const Value: string); function GetDisplayText: string; procedure SetSqlType(const Value: TTextDataType); protected procedure SetSQL(const Value:string); procedure SetSQLName(const Value:string); public procedure SaveToDisk; procedure LoadFromDisk(aFileName: string); function ActiveItemName: string; property DisplayText: string read GetDisplayText; property IsModified: Boolean read FIsModified; published property SQL:string read FSQL write SetSQL; property SQLName:string read FSQLName write SetSQLName; property Folder: string read FFolder write SetFolder; property FileName:string read FFileName; property SqlType: TTextDataType read FSqlType write SetSqlType; end; TTextDatas = class(TCollection) private function GetItem(Index: Integer): THsTextData; procedure SetItem(Index: Integer; const Value: THsTextData); function GetFirst:THsTextData; function GetLast:THsTextData; public constructor Create; function Add: THsTextData; function Insert(Index: Integer): THsTextData; function IsModified: Boolean; property Items[Index: Integer]: THsTextData read GetItem write SetItem;default; property First:THsTextData read GetFirst; property Last:THsTextData read GetLast; end; implementation uses {$IFDEF FPC} LazFileUtils, {$ELSE} uFileUtils, {$ENDIF} SysUtils, SynEdit, SynHighlighterSQL; { THsTextData } procedure THsTextData.SaveToDisk; begin if IsModified then begin with TStringList.Create do try Text := SQL; SqlName := ActiveItemName; if SqlName = '[UNKNOWN]' then raise Exception.Create('Cannot Save SQL without correct syntax and name.' + sLineBreak + sql); Insert(0,SQLName); FFileName := Folder + '\' + SqlName + '.sql'; SaveToFile(FileName); if FLoadFileName <> FileName then begin DeleteFileUTF8(FLoadFileName); FLoadFileName := FileName; end; FLoadedName := SqlName; finally Free; end; FIsModified := False; end; end; procedure THsTextData.LoadFromDisk(aFileName: string); var sl: TStringList; begin if FileExistsUTF8(aFileName) then begin sl := TStringList.Create; try sl.LoadFromFile(aFileName); FFileName := aFileName; if sl.Count > 0 then SQLName := sl[0]; sl.Delete(0); Sql := sl.Text; FIsModified := False; FLoadFileName := aFileName; FLoadedName := SqlName; Folder := ExcludeTrailingPathDelimiter(ExtractFilePath(FLoadFileName)); finally sl.Free; end; end; end; procedure THsTextData.SetFolder(const Value: string); begin FFolder := Value; end; procedure THsTextData.SetSQL(const Value:string); begin if Value <> FSQL then begin FSQL := Value; FIsModified := True; end; end; procedure THsTextData.SetSQLName(const Value:string); begin if Value <> FSQLName then begin FSQLName := Copy(Value,1,250); FIsModified := True; end; end; procedure THsTextData.SetSqlType(const Value: TTextDataType); begin FSqlType := Value; end; function THsTextData.ActiveItemName: string; var Source:string; Token:string; begin Result := '[UNKNOWN]'; with TSynSQLSyn.Create(nil) do try Source := Sql; ResetRange; SetLine(Source,1); while not GetEol do begin Token := GetToken; if ( (GetTokenKind = ord(tkIdentifier)) and ( SameText('macro',token) )) or ( (GetTokenKind = ord(tkIdentifier)) and ( SameText('include',token) )) or ( (GetTokenKind = ord(tkKey)) and ( SameText('view',token) or SameText('procedure',token) or SameText('trigger',token) or SameText('function',token) or SameText('script',token)) ) then begin repeat Next; until GetEOL or ( (GetTokenKind <> ord(tkspace)) and (GetTokenKind <> ord(tkComment)) ) ; Token := GetToken; if GetTokenKind = ord(tkIdentifier) then begin Result := Token; end; exit; end; Next; end; finally Free; end; end; function THsTextData.GetDisplayText: string; begin if not SameText(SqlName, FLoadedName) then Result := Format('%s WAS %s',[SqlName, FLoadedName]) else Result := SQLName; end; { TTextDatas } function TTextDatas.Add: THsTextData; begin Result := inherited Add as THsTextData; end; constructor TTextDatas.Create; begin inherited Create(THsTextData); end; function TTextDatas.GetFirst:THsTextData; begin result := nil; if Count > 0 then result := Items[0]; end; function TTextDatas.GetLast:THsTextData; begin result := nil; if Count > 0 then result := Items[Count-1]; end; function TTextDatas.GetItem(Index: Integer): THsTextData; begin Result := inherited Items[Index] as THsTextData; end; function TTextDatas.Insert(Index: Integer): THsTextData; begin Result := inherited Insert(Index) as THsTextData; end; function TTextDatas.IsModified: Boolean; var i: Integer; begin Result := False; for i := 0 to Count - 1 do if Items[i].IsModified then begin Result := True; exit; end; end; procedure TTextDatas.SetItem(Index: Integer; const Value: THsTextData); begin inherited Items[Index] := Value; end; end.
unit umain; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, AutoCompletePanel, LazUTF8; type { TForm1 } { TPais } TPais = class(TObject) private FCodigo: string; FNombre: string; procedure SetFCodigo(AValue: string); procedure SetFNombre(AValue: string); public constructor Create(Nombre, Codigo: string); property Nombre: string read FNombre write SetFNombre; property Codigo: string read FCodigo write SetFCodigo; end; TForm1 = class(TForm) AutoCompletePanel1: TAutoCompletePanel; Button1: TButton; procedure AutoCompletePanel1Search(Sender: TObject; SearchText: string; Items: TStrings); procedure Button1Click(Sender: TObject); procedure FormClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); private Data: TStringList; public end; var Form1: TForm1; implementation {$R *.lfm} { TPais } procedure TPais.SetFCodigo(AValue: string); begin if FCodigo=AValue then Exit; FCodigo:=AValue; end; procedure TPais.SetFNombre(AValue: string); begin if FNombre=AValue then Exit; FNombre:=AValue; end; constructor TPais.Create(Nombre, Codigo: string); begin Self.Nombre := Nombre; Self.Codigo := Codigo; end; { TForm1 } procedure TForm1.FormClick(Sender: TObject); begin AutoCompletePanel1.HideListBox; end; procedure TForm1.FormCreate(Sender: TObject); begin Data := TStringList.Create; Data.OwnsObjects := True; Data.AddObject('Argentina', TPais.Create('Argentina', 'AR')); Data.AddObject('Brasil', TPais.Create('Brasil', 'BR')); Data.AddObject('Paraguay', TPais.Create('Paraguay', 'PY')); Data.Add('Ninguno'); AutoCompletePanel1.SelectedObject := Data.Objects[0]; AutoCompletePanel1.SelectedObjectText := Data[0]; end; procedure TForm1.FormDestroy(Sender: TObject); begin Data.Free; end; procedure TForm1.FormShow(Sender: TObject); begin // Workaround to set size until size of label is fixed on Create event of AutoCompletePanel AutoCompletePanel1.HideListBox; end; procedure TForm1.AutoCompletePanel1Search(Sender: TObject; SearchText: string; Items: TStrings); var i: integer; s: string; begin s := UTF8LowerCase(SearchText); for i:=0 to Data.Count-1 do begin if (UTF8Pos(s, UTF8LowerCase(Data[i])) <> 0) or (s = '') then Items.AddObject(Data[i], Data.Objects[i]); end; end; procedure TForm1.Button1Click(Sender: TObject); begin if AutoCompletePanel1.SelectedObject <> nil then ShowMessage(TPais(AutoCompletePanel1.SelectedObject).Codigo) else ShowMessage('Ninguno'); end; end.
unit d_GetContents; { $Id: d_GetContents.pas,v 1.9 2012/06/05 07:54:22 dinishev Exp $ } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, BottomBtnDlg, StdCtrls, vtSpin, Buttons, ExtCtrls; type TContentsEditDlg = class(TBottomBtnDlg) edtValue6: TvtSpinEdit; lblText: TLabel; Label1: TLabel; edtCompareContentsLevel: TvtSpinEdit; private function GetValue6 : Integer; function pm_GetCompareContentsLevel: Integer; procedure pm_SetCompareContentsLevel(const Value: Integer); procedure SetValue6(aValue : Integer); public property CompareContentsLevel: Integer read pm_GetCompareContentsLevel write pm_SetCompareContentsLevel; property Level6 : Integer read GetValue6 write SetValue6; end; function RequestContents(var theLevel6, theCompareContentsLevel : Integer; aOwner: TComponent): Boolean; implementation uses l3Types; {$R *.DFM} function RequestContents(var theLevel6, theCompareContentsLevel : Integer; aOwner: TComponent): Boolean; begin with TContentsEditDlg.Create(AOwner) do try Level6 := theLevel6; CompareContentsLevel := theCompareContentsLevel; Result := Execute; if Result then begin theLevel6 := Level6; theCompareContentsLevel := CompareContentsLevel; end; finally Free; end; end; function TContentsEditDlg.GetValue6 : Integer; begin Result := edtValue6.AsInteger; end; function TContentsEditDlg.pm_GetCompareContentsLevel: Integer; begin Result := edtCompareContentsLevel.AsInteger; end; procedure TContentsEditDlg.pm_SetCompareContentsLevel(const Value: Integer); begin if Value > 0 then edtCompareContentsLevel.Value := Value else edtCompareContentsLevel.Text := ''; end; procedure TContentsEditDlg.SetValue6(aValue : Integer); begin if aValue <> Pred(High(Long)) then edtValue6.Value := aValue else edtValue6.Text := ''; end; end.
const generatedArraySize = 100; const separatorsArraySize = 7; type stringArrayType = array [1..generatedArraySize] of string; type separatorsType = array [1..separatorsArraySize] of string; function enterText(): string; begin var text: string := ''; write('Enter text please: '); readln(text); Result := text; end; function oneOf(symbol: string; triggerSymbols: stringArrayType): boolean; begin for var index := 1 to generatedArraySize do begin if symbol = triggerSymbols[index] then begin Result := true; end; end; end; function oneOfSeparators(symbol: string; separators: separatorsType): boolean; begin for var index := 1 to separatorsArraySize do begin if symbol = separators[index] then begin Result := true; end; end; end; function isWordSeparator(sympol: string): boolean; begin var separators: separatorsType = (' ', ',', '.', ':', ';', '?', '!'); Result := oneOfSeparators(sympol, separators); end; var arrayLength: integer := 0; procedure push(var stringArray: stringArrayType; var currentArrayIndex: integer; var tempWord: string); begin stringArray[currentArrayIndex] := tempWord; currentArrayIndex := currentArrayIndex + 1; end; function splitString(text: string): stringArrayType; begin var stringArray: stringArrayType; var currentArrayIndex: integer := 1; var tempWord: string := ''; for var index := 1 to text.Length do begin var wordSeparator: boolean := isWordSeparator(text[index]); if wordSeparator = true then begin if tempWord = '' then begin tempWord := ''; continue; end; push(stringArray, currentArrayIndex, tempWord); arrayLength := currentArrayIndex - 1; tempWord := ''; end else begin tempWord := tempWord + text[index]; end; end; var wordSeparator: boolean := isWordSeparator(text[text.Length]); if wordSeparator = false then begin push(stringArray, currentArrayIndex, tempWord); arrayLength := currentArrayIndex - 1; end; Result := stringArray; end; procedure viewArray(generatedArray: stringArrayType); begin write('['); for var index := 1 to arrayLength - 1 do begin write(generatedArray[index] + ', '); end; writeln(generatedArray[arrayLength] + ']'); end; function countLiteralInWord(word: string; symbols: stringArrayType): integer; begin var count: integer := 0; for var index := 1 to word.Length do begin if oneOf(word[index], symbols) then begin count := count + 1; end; end; Result := count; end; function countWordsThatStartsWith(words: stringArrayType; symbols: stringArrayType; length: integer): integer; begin var count: integer := 0; for var index := 1 to length do begin if oneOf(words[index][1], symbols) then begin count := count + 1; end; end; Result := count; end; function countWordsWithStartingSameAsEnding(words: stringArrayType; length: integer): integer; begin var count: integer := 0; for var index := 1 to length do begin var word: string := words[index]; if word[1].ToLower() = word[word.Length].ToLower() then begin count := count + 1; end; end; Result := count; end; begin var text: string := 'Artem.Velera! Bush, Danik Aloha'; var splittedText: stringArrayType := splitString(text); viewArray(splittedText); writeln('Count: ', arrayLength); var symbolTriggers1: stringArrayType; symbolTriggers1[1] := 'a'; symbolTriggers1[2] := 'A'; writeln('Number of "A" in the last word: ', countLiteralInWord(splittedText[arrayLength], symbolTriggers1)); var symbolTriggers2: stringArrayType; symbolTriggers2[1] := 'b'; symbolTriggers2[2] := 'B'; writeln('Number of words that starts with "B": ', countWordsThatStartsWith(splittedText, symbolTriggers2, arrayLength)); writeln('Number of words which starting symbol same as ending: ', countWordsWithStartingSameAsEnding(splittedText, arrayLength)); end.
unit GetAddressNotesUnit; interface uses SysUtils, BaseExampleUnit; type TGetAddressNotes = class(TBaseExample) public procedure Execute(RouteId: String; RouteDestinationId: integer); end; implementation uses NoteParametersUnit, AddressNoteUnit; procedure TGetAddressNotes.Execute(RouteId: String; RouteDestinationId: integer); var ErrorString: String; Parameters: TNoteParameters; Notes: TAddressNoteList; begin Parameters := TNoteParameters.Create(); try Parameters.RouteId := RouteId; Parameters.AddressId := RouteDestinationId; Notes := Route4MeManager.AddressNote.Get(Parameters, ErrorString); try WriteLn(''); if (Notes <> nil) then WriteLn(Format('GetAddressNotes executed successfully, %d notes returned', [Notes.Count])) else WriteLn(Format('GetAddressNotes error: "%s"', [ErrorString])); WriteLn(''); finally FreeAndNil(Notes); end; finally FreeAndNil(Parameters); end; end; end.
unit IntBar; interface uses DGLE, DGLE_Types, Engine; type TIntBar = class(TObject) private pBar: ITexture; pBack: ITexture; FTop: Integer; FLeft: Integer; procedure SetLeft(const Value: Integer); procedure SetTop(const Value: Integer); public constructor Create(Left, Top: Integer; TexFileName: AnsiString); property Top: Integer read FTop write SetTop; property Left: Integer read FLeft write SetLeft; destructor Destroy; override; procedure Render(Cur, Max: Integer); function MouseOver(): Boolean; end; implementation uses SysUtils; { TIntBar } constructor TIntBar.Create(Left, Top: Integer; TexFileName: AnsiString); begin Self.Top := Top; Self.Left := Left; pResMan.Load('Resources\Sprites\Interface\Backbar.png', IEngineBaseObject(pBack), TEXTURE_LOAD_DEFAULT_2D); pResMan.Load(PAnsiChar('Resources\Sprites\Interface\' + TexFileName), IEngineBaseObject(pBar), TEXTURE_LOAD_DEFAULT_2D); end; destructor TIntBar.Destroy; begin pBar := nil; pBack := nil; inherited; end; function TIntBar.MouseOver: Boolean; begin Result := (MousePos.X > Left) and (MousePos.X < Left + 202) and (MousePos.Y > Top) and (MousePos.Y < Top + 18); end; procedure TIntBar.Render(Cur, Max: Integer); var W, H: Cardinal; P: PAnsiChar; begin pRender2D.DrawTexture(pBack, Point2(Left, Top), Point2(202, 18)); pRender2D.DrawTexture(pBar, Point2(Left + 1, Top + 1), Point2(BarWidth(Cur, Max, 200), 16)); if MouseOver then begin P := StrToPAChar(IntToStr(Cur) + '/' + IntToStr(Max)); pFont11.GetTextDimensions(P, W, H); pFont11.Draw2DSimple(Left + (101 - (Integer(W) div 2)), Top + (8 - (Integer(H) div 2)), P, Color4); end; end; procedure TIntBar.SetLeft(const Value: Integer); begin FLeft := Value; end; procedure TIntBar.SetTop(const Value: Integer); begin FTop := Value; end; end.
unit OutputSearchAuto; interface uses ComObj, OutputSrch_TLB, OutputSearch; type TOutputSearch = class(TAutoObject, IOutputSearch) protected function Get_Count: Integer; safecall; procedure Search(const Output, World, Town, Company: WideString; Count, X, Y: Integer); safecall; function Get_Company(row: Integer): WideString; safecall; function Get_K(row: Integer): Integer; safecall; function Get_P(row: Integer): Single; safecall; function Get_Town(row: Integer): WideString; safecall; function Get_Utility(row: Integer): WideString; safecall; function Get_X(row: Integer): Integer; safecall; function Get_Y(row: Integer): Integer; safecall; function Get_C(row: Integer): Single; safecall; function Get_SortMode: Integer; safecall; procedure Set_SortMode(Value: Integer); safecall; function Get_Role: Integer; safecall; procedure Set_Role(Value: Integer); safecall; function Get_Circuits: WideString; safecall; procedure Set_Circuits(const Value: WideString); safecall; function Get_Connected(index: Integer): WordBool; safecall; public destructor Destroy; override; private fSortMode : integer; fRole : byte; fCircuits : string; fOutputSearch : OutputSearch.TOuputSearch; protected procedure Initialize; override; end; implementation uses ComServ, CacheCommon, CacheObjects, CacheRegistryData, {AutoLog,} SysUtils; function TOutputSearch.Get_Count: Integer; begin if fOutputSearch <> nil then result := fOutputSearch.Result.Count else result := 0; end; procedure TOutputSearch.Search(const Output, World, Town, Company: WideString; Count, X, Y: Integer); begin //AutoLog.Log('output', DateTimeToStr(Now) + ': Start search ' + Output); try fOutputSearch.Free; //AutoLog.Log('output', DateTimeToStr(Now) + ': free ok.. '); except //AutoLog.Log('output', DateTimeToStr(Now) + ': free error.. '); end; try //AutoLog.Log('output', DateTimeToStr(Now) + ': begin create.. '); fOutputSearch := OutputSearch.TOuputSearch.Create('Worlds\' + World + '\Outputs\' + Output, Town, Company, Count, X, Y, fSortMode, TFacilityRoleSet(fRole)); //AutoLog.Log('output', DateTimeToStr(Now) + ': end create.. '); except //AutoLog.Log('output', DateTimeToStr(Now) + ': error create.. '); fOutputSearch := nil; end; //AutoLog.Log('output', DateTimeToStr(Now) + ': end search ' + Output); end; function TOutputSearch.Get_Company(row: Integer): WideString; begin try if (fOutputSearch <> nil) and (row < fOutputSearch.Result.Count) then result := WideString(fOutputSearch.Result[row].Company) else result := ''; except result := ''; end; end; function TOutputSearch.Get_K(row: Integer): Integer; begin try if (fOutputSearch <> nil) and (row < fOutputSearch.Result.Count) then result := fOutputSearch.Result[row].K else result := 0; except result := 0; end; end; function TOutputSearch.Get_P(row: Integer): Single; begin try if (fOutputSearch <> nil) and (row < fOutputSearch.Result.Count) then result := fOutputSearch.Result[row].P else result := 0; except result := 0; end; end; function TOutputSearch.Get_Town(row: Integer): WideString; begin try if (fOutputSearch <> nil) and (row < fOutputSearch.Result.Count) then result := WideString(fOutputSearch.Result[row].Town) else result := ''; except result := ''; end; end; function TOutputSearch.Get_Utility(row: Integer): WideString; begin try if (fOutputSearch <> nil) and (row < fOutputSearch.Result.Count) then result := WideString(fOutputSearch.Result[row].Facility) else result := ''; except result := ''; end; end; function TOutputSearch.Get_X(row: Integer): Integer; begin try if (fOutputSearch <> nil) and (row < fOutputSearch.Result.Count) then result := fOutputSearch.Result[row].X else result := 0; except result := 0; end; end; function TOutputSearch.Get_Y(row: Integer): Integer; begin try if (fOutputSearch <> nil) and (row < fOutputSearch.Result.Count) then result := fOutputSearch.Result[row].Y else result := 0; except result := 0; end; end; destructor TOutputSearch.Destroy; begin try fOutputSearch.Free; except end; inherited; end; procedure TOutputSearch.Initialize; begin end; function TOutputSearch.Get_C(row: Integer): Single; begin try if (fOutputSearch <> nil) and (row < fOutputSearch.Result.Count) then result := fOutputSearch.Result.Costs[row] else result := 0; except result := 0; end; end; function TOutputSearch.Get_SortMode: Integer; begin result := fSortMode; end; procedure TOutputSearch.Set_SortMode(Value: Integer); begin fSortMode := Value; end; function TOutputSearch.Get_Role: Integer; begin result := fRole; end; procedure TOutputSearch.Set_Role(Value: Integer); begin fRole := Value; end; function TOutputSearch.Get_Circuits: WideString; begin result := fCircuits; end; procedure TOutputSearch.Set_Circuits(const Value: WideString); begin fCircuits := Value; end; function TOutputSearch.Get_Connected(index: Integer): WordBool; begin try if (fOutputSearch <> nil) and (index < fOutputSearch.Result.Count) then result := fOutputSearch.Result[index].Intercept(fCircuits) else result := false; except result := false; end; end; initialization //AutoLog.InitLogs; TAutoObjectFactory.Create(ComServer, TOutputSearch, Class_OutputSearch, ciMultiInstance); end.
unit osExtStringList; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls; type TExtStringList = class(TStringList) private FElementFormat: string; FSeparator: string; function GetAsFmtText: string; procedure SetElementFormat(const Value: string); procedure SetSeparator(const Value: string); public constructor Create; virtual; procedure PrepareForID; procedure SetMacro(Macro: string; Value: string); function IndexOfSubstr(Substr: string): integer; published property Separator: string read FSeparator write SetSeparator; property ElementFormat: string read FElementFormat write SetElementFormat; property AsFmtText: string read GetAsFmtText; end; {** Utilizado para modificar strings de SQL. Contém métodos para adição de cláusulas WHERE, GROUP BY e ORDER BY. } TSQLStringList = class(TExtStringList) private FFieldIndex: integer; FFromIndex: integer; FWhereIndex: integer; FOrderByIndex: integer; FGroupByIndex: integer; FExpressionIndex: integer; protected procedure SplitClauses; procedure InsertExpression(Expression: string); public constructor Create; override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; procedure RefreshPositionIndexes; procedure InsertWhere(Expression: string); procedure InsertWhereInt(Field: string; Value: string); procedure InsertWhereIntOp(Field: string; Operator: string; Value: string); procedure InsertWhereStr(Field: string; Value: string); procedure InsertWhereStrLike(Field: string; Value: string); procedure InsertWhereStrBetween(Field: string; FirstValue: string; LastValue: string); procedure InsertWhereDateBetween(Field: string; FirstValue: string; LastValue: string);overload; procedure InsertWhereDateBetween(Field: string; FirstValue: TDateTime; LastValue: TDateTime); overload; procedure InsertWhereStrOp(Field: string; Operator: string; Value: string); procedure InsertOrderBy(Field: string); procedure InsertField(Field: string); procedure InsertOrder(Field: string); function SplitStringAt(Substr: string): integer; end; const FROM = 'FROM'; WHERE = 'WHERE'; GROUPBY = 'GROUP BY'; ORDERBY = 'ORDER BY'; MACROCHAR = '&'; SQLDateTimeFormat = 'yyyy/mm/dd'; implementation constructor TSQLStringList.Create; begin inherited Create; FFromIndex := -1; FWhereIndex := -1; FOrderByIndex := -1; FGroupByIndex := -1; FExpressionIndex := -1; end; destructor TSQLStringList.Destroy; begin inherited Destroy; end; function TSQLStringList.SplitStringAt(Substr: string): integer; var iIndex: integer; iPos: integer; sLinha: string; sInicio: string; sFim: string; begin result := -1; iIndex := IndexOfSubstr(Substr); if iIndex <> -1 then begin sLinha := Strings[iIndex]; iPos := Pos(Substr, sLinha); if iPos > 1 then begin sInicio := Copy(sLinha, 1, iPos-1); // Extrai o inicio da linha até a substring sFim := Copy(sLinha, iPos, Length(sLinha)-iPos+1); // Extrai o final Strings[iIndex] := sInicio; Inc(iIndex); Insert(iIndex, sFim); end; result := iIndex; end; end; // Separa as strings where, group by e order by procedure TSQLStringList.SplitClauses; begin FFromIndex := SplitStringAt(FROM); FWhereIndex := SplitStringAt(WHERE); FGroupByIndex := SplitStringAt(GROUPBY); FOrderByIndex := SplitStringAt(ORDERBY); end; procedure TSQLStringList.RefreshPositionIndexes; begin FFromIndex := IndexOfSubstr(FROM); FWhereIndex := IndexOfSubstr(WHERE); FGroupByIndex := IndexOfSubstr(GROUPBY); FOrderByIndex := IndexOfSubstr(ORDERBY); // Determina o ponto de inserção das expressoes FExpressionIndex := FGroupByIndex; if FExpressionIndex = -1 then // Sem GROUP BY FExpressionIndex := FOrderByIndex; // Determina o ponto de inserção dos fields FFieldIndex := FFromIndex; end; procedure TSQLStringList.InsertExpression(Expression: string); var sConnect: string; begin if FWhereIndex = -1 then // Sem cláusula WHERE sConnect := 'WHERE ' else sConnect := 'AND '; if FExpressionIndex = -1 then Add(sConnect + Expression) // Adiciona ao final else Insert(FExpressionIndex, sConnect + Expression); RefreshPositionIndexes; end; procedure TSQLStringList.InsertOrder(Field: string); var sConnect: string; begin if Trim(Field) <> '' then begin if FOrderByIndex = -1 then // Sem cláusula ORDER BY sConnect := 'ORDER BY ' else sConnect := ', '; Add(sConnect + Field); // Adiciona ao final RefreshPositionIndexes; end; end; procedure TSQLStringList.InsertWhere(Expression: string); begin if Trim(Expression) <> '' then InsertExpression(Expression); end; procedure TSQLStringList.InsertWhereInt(Field: string; Value: string); begin if Trim(Value) <> '' then InsertExpression(Field + '=' + Value); end; procedure TSQLStringList.InsertWhereStr(Field: string; Value: string); begin if Trim(Value) <> '' then InsertExpression(Field + '= ''' + Value + ''''); end; procedure TSQLStringList.InsertWhereStrLike(Field: string; Value: string); begin if Trim(Value) <> '' then InsertExpression(Field + ' LIKE ''' + Value + '%'''); end; procedure TSQLStringList.InsertWhereStrBetween(Field: string; FirstValue: string; LastValue: string); begin if Trim(FirstValue) <> '' then InsertExpression(Field + ' >= ''' + FirstValue + ''''); if Trim(LastValue) <> '' then InsertExpression(Field + ' <= ''' + LastValue + ''''); end; procedure TSQLStringList.InsertWhereDateBetween(Field: string; FirstValue: string; LastValue: string); begin if Trim(Copy(FirstValue,1, 2)) <> '' then InsertExpression(Field + ' >= ''' + FormatDateTime(SQLDatetimeFormat, StrToDateTime(FirstValue)) + ''''); if Trim(Copy(LastValue,1, 2)) <> '' then InsertExpression(Field + ' <= ''' + FormatDateTime(SQLDatetimeFormat, StrToDateTime(LastValue)) + ''''); end; procedure TSQLStringList.InsertWhereDateBetween(Field: string; FirstValue: TDateTime; LastValue: TDateTime); begin if FirstValue <> 0 then InsertExpression(Field + ' >= ''' + FormatDateTime(SQLDatetimeFormat, FirstValue) + ''''); if LastValue <> 0 then InsertExpression(Field + ' <= ''' + FormatDateTime(SQLDatetimeFormat, LastValue) + ''''); end; procedure TSQLStringList.InsertWhereStrOp(Field: string; Operator: string; Value: string); begin if Trim(Value) <> '' then InsertExpression(Field + ' ' + Operator + ' ''' + Value + ''''); end; procedure TSQLStringList.InsertWhereIntOp(Field: string; Operator: string; Value: string); begin if Trim(Value) <> '' then InsertExpression(Field + ' ' + Operator + ' ' + Value); end; procedure TSQLStringList.InsertOrderBy(Field: string); begin InsertOrder(Field); end; procedure TSQLStringList.InsertField(Field: string); var sConnect: string; begin // ToDo: Verificar se existe algum campo para colocar a virgula ou não // Até fazer isto fica uma restrição: // A query Base deve ter pelo menos um campo sConnect := ', '; if FFieldIndex = -1 then Add(sConnect + Field) // Adiciona ao final else Insert(FFieldIndex, sConnect + Field); RefreshPositionIndexes; end; { TExtStringList } constructor TExtStringList.Create; begin inherited; FSeparator := ''; FElementFormat := ''; end; function TExtStringList.GetAsFmtText: string; var i: integer; sSep: string; begin Result := ''; sSep := ''; for i:=0 to Count - 1 do begin Result := Result + sSep + Format(FElementFormat, [Strings[i]]); sSep := FSeparator; end; end; function TExtStringList.IndexOfSubstr(Substr: string): integer; var i: integer; begin Result := -1; for i:=0 to Count -1 do if Pos(Substr, Strings[i]) <> 0 then begin Result := i; break; end; end; procedure TExtStringList.PrepareForID; begin FSeparator := ','; FElementFormat := '''%s'''; end; procedure TExtStringList.SetElementFormat(const Value: string); begin FElementFormat := Value; end; procedure TExtStringList.SetMacro(Macro, Value: string); var iIndex: integer; iPos: integer; iMacroLen: integer; sLinha: string; sInicio: string; sFim: string; begin Macro := MACROCHAR + Macro; iMacroLen := Length(Macro); iIndex := IndexOfSubstr(Macro); if iIndex <> -1 then begin sLinha := Strings[iIndex]; sInicio := ''; iPos := Pos(Macro, sLinha); if iPos > 1 then begin sInicio := Copy(sLinha, 1, iPos-1); // Extrai o inicio da linha até a substring sFim := Copy(sLinha, iPos + iMacroLen, Length(sLinha)- iPos + iMacroLen + 1); // Extrai o final Strings[iIndex] := sInicio; end; Strings[iIndex] := sInicio + Value + sFim; end; end; procedure TExtStringList.SetSeparator(const Value: string); begin FSeparator := Value; end; procedure TSQLStringList.Assign(Source: TPersistent); begin inherited; RefreshPositionIndexes; end; end.
unit UOrderedCardinalList; interface uses Classes, UCardinalsArray; type TOrderedCardinalList = Class private FOrderedList : TList; FDisabledsCount : Integer; FModifiedWhileDisabled : Boolean; FOnListChanged: TNotifyEvent; Procedure NotifyChanged; public Constructor Create; Destructor Destroy; override; Function Add(Value : Cardinal) : Integer; Procedure Remove(Value : Cardinal); Procedure Clear; Function Get(index : Integer) : Cardinal; Function Count : Integer; Function Find(const Value: Cardinal; var Index: Integer): Boolean; Procedure Disable; Procedure Enable; Property OnListChanged : TNotifyEvent read FOnListChanged write FOnListChanged; Procedure CopyFrom(Sender : TOrderedCardinalList); Function ToArray : TCardinalsArray; End; implementation uses SysUtils; { TOrderedCardinalList } function TOrderedCardinalList.Add(Value: Cardinal): Integer; begin if Find(Value,Result) then exit else begin FOrderedList.Insert(Result,TObject(Value)); NotifyChanged; end; end; procedure TOrderedCardinalList.Clear; begin FOrderedList.Clear; NotifyChanged; end; procedure TOrderedCardinalList.CopyFrom(Sender: TOrderedCardinalList); Var i : Integer; begin if Self=Sender then exit; Disable; Try Clear; for I := 0 to Sender.Count - 1 do begin Add(Sender.Get(i)); end; Finally Enable; End; end; function TOrderedCardinalList.Count: Integer; begin Result := FOrderedList.Count; end; constructor TOrderedCardinalList.Create; begin FOrderedList := TList.Create; FDisabledsCount := 0; FModifiedWhileDisabled := false; end; destructor TOrderedCardinalList.Destroy; begin FOrderedList.Free; inherited; end; procedure TOrderedCardinalList.Disable; begin inc(FDisabledsCount); end; procedure TOrderedCardinalList.Enable; begin if FDisabledsCount<=0 then raise Exception.Create('Dev error. Invalid disabled counter'); dec(FDisabledsCount); if (FDisabledsCount=0) And (FModifiedWhileDisabled) then NotifyChanged; end; function TOrderedCardinalList.Find(const Value: Cardinal; var Index: Integer): Boolean; var L, H, I: Integer; C : Int64; begin Result := False; L := 0; H := FOrderedList.Count - 1; while L <= H do begin I := (L + H) shr 1; C := Int64(FOrderedList[I]) - Int64(Value); if C < 0 then L := I + 1 else begin H := I - 1; if C = 0 then begin Result := True; L := I; end; end; end; Index := L; end; function TOrderedCardinalList.Get(index: Integer): Cardinal; begin Result := Cardinal(FOrderedList[index]); end; procedure TOrderedCardinalList.NotifyChanged; begin if FDisabledsCount>0 then begin FModifiedWhileDisabled := true; exit; end; FModifiedWhileDisabled := false; if Assigned(FOnListChanged) then FOnListChanged(Self); end; procedure TOrderedCardinalList.Remove(Value: Cardinal); Var i : Integer; begin if Find(Value,i) then begin FOrderedList.Delete(i); NotifyChanged; end; end; Function TOrderedCardinalList.ToArray : TCardinalsArray; var i : integer; begin SetLength(Result, self.Count); for i := 0 to self.Count - 1 do Result[i] := Self.Get(i); end; end.
unit MFichas.Model.Venda.Metodos.Factory; interface uses MFichas.Model.Venda.Interfaces, MFichas.Model.Venda.Metodos.Interfaces, MFichas.Model.Venda.Metodos.Abrir, MFichas.Model.Venda.Metodos.Pagar, MFichas.Model.Venda.Metodos.Finalizar; type TModelVendaMetodosFactory = class(TInterfacedObject, iModelVendaMetodosFactory) private constructor Create; public destructor Destroy; override; class function New: iModelVendaMetodosFactory; function Abrir(AParent: iModelVenda) : iModelVendaMetodosAbrir; function Pagar(AParent: iModelVenda) : iModelVendaMetodosPagar; function Finalizar(AParent: iModelVenda): iModelVendaMetodosFinalizar; end; implementation { TModelVendaMetodosFactory } function TModelVendaMetodosFactory.Abrir(AParent: iModelVenda) : iModelVendaMetodosAbrir; begin Result := TModelVendaMetodosAbrir.New(AParent); end; constructor TModelVendaMetodosFactory.Create; begin end; destructor TModelVendaMetodosFactory.Destroy; begin inherited; end; function TModelVendaMetodosFactory.Finalizar(AParent: iModelVenda): iModelVendaMetodosFinalizar; begin Result := TModelVendaMetodosFinalizar.New(AParent); end; class function TModelVendaMetodosFactory.New: iModelVendaMetodosFactory; begin Result := Self.Create; end; function TModelVendaMetodosFactory.Pagar(AParent: iModelVenda) : iModelVendaMetodosPagar; begin Result := TModelVendaMetodosPagar.New(AParent); end; end.
unit m0RESLib; (* // // module: m0reslib.pas // author: Mickael P. Golovin // // Copyright (c) 1997-2000 by Archivarius Team, free for non commercial use. // // $Id: m0reslib.pas,v 1.1 2008/02/07 09:54:24 lulin Exp $ // *) {$Include m0Define.inc} interface uses Windows, Messages, SysUtils, Consts, Classes, l3Except, m0Const, m0AddTyp, m0STRLib ; type Em0RESLibGeneral = class(El3Exception); function m0RESAllocRCDATA(var AHandle: THandle; const ARCName: string): Pointer; function m0RESFreeRCDATA(var AHandle: THandle): Pointer; implementation { -- unit.private -- } resourcestring {$IFDEF _m0LANGUAGE_ENG} SECannotFindRes = 'Cannot find resource: %s'; SECannotLoadRes = 'Cannot load resource: %s'; SECannotLockRes = 'Cannot lock resource: %s'; {$ENDIF} {$IFDEF _m0LANGUAGE_RUS} SECannotFindRes = 'Не могу найти ресурс: %s'; SECannotLoadRes = 'Не могу загрузить ресурс: %s'; SECannotLockRes = 'Не могу захватить ресурс: %s'; {$ENDIF} { -- unit.public -- } function m0RESAllocRCDATA(var AHandle: THandle; const ARCName: string): Pointer; var LInfo1: THandle; LInfo2: THandle; begin LInfo1 := FindResource(FindResourceHInstance(HInstance), PChar(UpperCase(ARCName)), RT_RCDATA); if (LInfo1 = 0) then raise Em0RESLibGeneral.Create(Format(SECannotFindRes, [ARCName])); LInfo2 := LoadResource(HInstance, LInfo1); if (LInfo2 = 0) then raise Em0RESLibGeneral.Create(Format(SECannotLoadRes, [ARCName])); try Result := Pointer(LockResource(LInfo2)); if (Result = nil) then raise Em0RESLibGeneral.Create(Format(SECannotLockRes, [ARCName])); except FreeResource(LInfo2); raise; end; AHandle := LInfo2; end; function m0RESFreeRCDATA(var AHandle: THandle): Pointer; begin Result := nil; if (AHandle <> 0) then begin if not (UnlockResource(AHandle)) then FreeResource(AHandle); AHandle := 0; end; end; end.
var s : string; i : byte; function rubah(a :char):char; begin if ord(a) >= ord('a') then rubah := upcase(a) else rubah := lowercase(a); end; begin readln(s); for i := 1 to length(s) do s[i] := rubah(s[i]); writeln(s); end.
{ Module of routines that add call arguments a subroutine call opcode. } module sst_call_arg; define sst_call_arg_enum; define sst_call_arg_exp; define sst_call_arg_int; define sst_call_arg_str; define sst_call_arg_var; %include 'sst2.ins.pas'; { ******************************************************************************** * * Local subroutine MAKE_ARG_TEMPLATE (OPC, ARGT_P, ARG_P) * * Add an empty argument to a subroutine call. OPC is the subroutine call * opcode. ARGT_P is returned pointing to the template for the new call * argument. A new call argument descriptor is created, linked to the opcode, * and initialized from the template. Some obvious errors are checked. } procedure make_arg_template ( in opc: sst_opc_t; {opcode for subroutine call} out argt_p: sst_proc_arg_p_t; {returned pointer to argument template} out arg_p: sst_proc_arg_p_t); {returned pointer to new called arg desc} val_param; const max_msg_parms = 1; {max parameters we can pass to a message} var arg_pp: sst_proc_arg_pp_t; {points to next argument chain pointer} msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; begin if opc.opcode <> sst_opc_call_k then begin {opcode is not a call ?} sys_msg_parm_int (msg_parm[1], ord(opc.opcode)); sys_message_bomb ('sst', 'opcode_unexpected', msg_parm, 1); end; argt_p := opc.call_proct_p^.first_arg_p; {init pointer to first argument template} arg_pp := addr(opc.call_proc_p^.first_arg_p); {point to start of call args chain} arg_p := arg_pp^; {init pointer to first call argument} while arg_p <> nil do begin {existing call argument found here ?} if argt_p = nil then begin {too many call arguments ?} sys_message_bomb ('sst', 'args_too_many', nil, 0); end; arg_pp := addr(arg_p^.next_p); {update pointer to chain link pointer} argt_p := argt_p^.next_p; {advance to next call argument template} arg_p := arg_p^.next_p; {advance to next call argument descriptor} end; {back and check this new argument} if argt_p = nil then begin {no room for another call argument ?} sys_message_bomb ('sst', 'args_too_many_add', nil, 0); end; sst_mem_alloc_scope (sizeof(arg_p^), arg_p); {alloc mem for new argument desc} arg_pp^ := arg_p; {add new argument to end of list} opc.call_proc_p^.n_args := {count one more argument in call} opc.call_proc_p^.n_args + 1; arg_p^.next_p := nil; {initialize call argument descriptor} arg_p^.sym_p := nil; arg_p^.name_p := nil; arg_p^.exp_p := nil; arg_p^.dtype_p := nil; arg_p^.pass := argt_p^.pass; arg_p^.rwflag_int := argt_p^.rwflag_int; arg_p^.rwflag_ext := argt_p^.rwflag_ext; arg_p^.univ := argt_p^.univ; end; { ******************************************************************************** * * Subroutine SST_CALL_ARG_EXP (OPC, EXP) * * Add the expression EXP as the next argument to the subroutine call for which * OPC is the opcode. } procedure sst_call_arg_exp ( {add expression as next argument to call} in opc: sst_opc_t; {CALL opcode to add argument to} in var exp: sst_exp_t); {expression for call argument value} val_param; var arg_p: sst_proc_arg_p_t; {points to call argument descriptor} argt_p: sst_proc_arg_p_t; {points to call argument template} begin make_arg_template (opc, argt_p, arg_p); {create and init argument descriptor} arg_p^.exp_p := addr(exp); {point to the expression to pass} arg_p^.dtype_p := exp.dtype_p; {argument data type is expression data type} sst_exp_useage_check ( {check exp compatibility with arg template} arg_p^.exp_p^, {expression to check} argt_p^.rwflag_ext, {neccessary read/write access to expression} argt_p^.dtype_p^); {dtype expression must be compatible with} end; { ******************************************************************************** } procedure sst_call_arg_enum ( {add constant enum call arg to call} in opc: sst_opc_t; {CALL opcode to add argument to} in sym: sst_symbol_t); {symbol descriptor for enumerated value} val_param; var arg_p: sst_proc_arg_p_t; {points to call argument descriptor} argt_p: sst_proc_arg_p_t; {points to call argument template} begin make_arg_template (opc, argt_p, arg_p); {create and init argument descriptor} sst_exp_const_enum (sym, arg_p^.exp_p); {create constant enum expression} arg_p^.dtype_p := arg_p^.exp_p^.dtype_p; sst_exp_useage_check ( {check exp compatibility with arg template} arg_p^.exp_p^, {expression to check} argt_p^.rwflag_ext, {neccessary read/write access to expression} argt_p^.dtype_p^); {dtype expression must be compatible with} end; { ******************************************************************************** } procedure sst_call_arg_int ( {add constant integer call arg to call} in opc: sst_opc_t; {CALL opcode to add argument to} in ival: sys_int_max_t); {integer value for argument} val_param; var arg_p: sst_proc_arg_p_t; {points to call argument descriptor} argt_p: sst_proc_arg_p_t; {points to call argument template} begin make_arg_template (opc, argt_p, arg_p); {create and init argument descriptor} sst_exp_const_int (ival, arg_p^.exp_p); {create constant integer expression} arg_p^.dtype_p := arg_p^.exp_p^.dtype_p; sst_exp_useage_check ( {check exp compatibility with arg template} arg_p^.exp_p^, {expression to check} argt_p^.rwflag_ext, {neccessary read/write access to expression} argt_p^.dtype_p^); {dtype expression must be compatible with} end; { ******************************************************************************** } procedure sst_call_arg_str ( {add constant string call arg to call} in opc: sst_opc_t; {CALL opcode to add argument to} in str: univ string; {string for argument value} in len: sys_int_machine_t); {string length} val_param; var arg_p: sst_proc_arg_p_t; {points to call argument descriptor} argt_p: sst_proc_arg_p_t; {points to call argument template} dtlen: sys_int_machine_t; {string length of target data type} dt_p: sst_dtype_p_t; {base data type of argument template} begin make_arg_template (opc, argt_p, arg_p); {create and init argument descriptor} if argt_p^.univ then begin {no need to match target argument} dtlen := len; end else begin {must match target argument data type} dt_p := argt_p^.dtype_p; {make base argument templat data type} while dt_p^.dtype = sst_dtype_copy_k do dt_p := dt_p^.copy_dtype_p; if dt_p^.dtype <> sst_dtype_array_k then begin {AR_IND_N not valid ?} sys_message_bomb ('sst', 'dtype_not_array', nil, 0); end; dtlen := dt_p^.ar_ind_n; {set required length of target string} end ; sst_exp_const_str ( {create string constant expression} str, len, {the string and string length} dtlen, {length of target string data type} arg_p^.exp_p); {returned pointer to expression descriptor} arg_p^.dtype_p := arg_p^.exp_p^.dtype_p; {copy data type to argument descriptor} sst_exp_useage_check ( {check exp compatibility with arg template} arg_p^.exp_p^, {expression to check} argt_p^.rwflag_ext, {neccessary read/write access to expression} argt_p^.dtype_p^); {dtype expression must be compatible with} end; { ******************************************************************************** } procedure sst_call_arg_var ( {add variable call arg to call} in opc: sst_opc_t; {CALL opcode to add argument to} in sym: sst_symbol_t); {variable to add as call argument} val_param; var arg_p: sst_proc_arg_p_t; {points to call argument descriptor} argt_p: sst_proc_arg_p_t; {points to call argument template} begin make_arg_template (opc, argt_p, arg_p); {create and init argument descriptor} arg_p^.exp_p := sst_exp_make_var(sym); {make expression referencing variable} arg_p^.dtype_p := arg_p^.exp_p^.dtype_p; sst_exp_useage_check ( {check exp compatibility with arg template} arg_p^.exp_p^, {expression to check} argt_p^.rwflag_ext, {neccessary read/write access to expression} argt_p^.dtype_p^); {dtype expression must be compatible with} end;
unit MainUnit; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.platform, fmx.helpers.android, FMX.Edit, FMX.StdCtrls, Android.BarcodeScanner, FMX.Layouts, FMX.Memo; type TForm5 = class(TForm) Button1: TButton; Memo1: TMemo; procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } abc: TAndroidBarcodeScanner; procedure DisplayBarcode(Sender: TAndroidBarcodeScanner; ABarcode: string); end; var Form5: TForm5; implementation {$R *.fmx} procedure TForm5.Button1Click(Sender: TObject); begin abc.Scan; end; procedure TForm5.DisplayBarcode(Sender: TAndroidBarcodeScanner; ABarcode: string); begin Memo1.Lines.Text := ABarcode; end; procedure TForm5.FormCreate(Sender: TObject); begin abc := TAndroidBarcodeScanner.Create(true); abc.OnBarcode := DisplayBarcode; end; end.
unit uPlugin; interface uses System.JSON, System.StrUtils, System.Generics.Defaults, System.Generics.Collections, System.SysUtils, System.Math, System.Classes, System.IOUtils, FMX.Graphics, FMX.Features.BitmapHelper, uUtils; type TProcInt = procedure (index : Integer) of object; TPlugin = class public FName : string; FPath : string; FType : Integer; FIcon : TBitmap; FIndex : Integer; FChanged : Boolean; public const INT_DEFAULT_INDEX : Integer = -1; ARRAY_PARSE : array of string = ['name', 'icon', 'type', 'path']; constructor Create; destructor Destroy; override; function LoadFromJson(AJSONValue : TJSONValue) : Boolean; function SaveToJson(var AJSONObject : TJSONObject) : Boolean; end; TPlugins = class(TList<TPlugin>) private FItemIndex : Integer; FOnChangeCurrent : TProcInt; FFileName : string; function GetCurrent: TPlugin; procedure SetCurrent(const Value: TPlugin); procedure SetItemIndex(const Value: Integer); procedure SetFileName(const Value: string); function GetIsEmpty: Boolean; public const INT_DEFAULT_INDEX : Integer = -1; ARRAY_TYPES : array of string = ['url', 'plugin'];//temp class var FTypes : TStringList; public constructor Create; overload; constructor Create(fileName : string); overload; destructor Destroy; override; function LoadFromJson(AJSONValue : TJSONValue) : Boolean; overload; function LoadFromJson(AJSONValue : string) : Boolean; overload; function LoadFromFile(fileName : string) : Boolean; function SaveToJson(var sJson : string) : Boolean; function SaveToArray : TArray<string>; function SaveToFile : Boolean; property Current : TPlugin read GetCurrent write SetCurrent; property ItemIndex: Integer read FItemIndex write SetItemIndex default -1; property OnChangeCurrent : TProcInt read FOnChangeCurrent write FOnChangeCurrent; property FileName : string read FFileName write SetFileName; property IsEmpty : Boolean read GetIsEmpty; end; implementation { TPlugins } {------------------------------------------------------------------------------} constructor TPlugins.Create; var item : string; begin inherited; ItemIndex := INT_DEFAULT_INDEX; FTypes := TStringList.Create; for item in ARRAY_TYPES do FTypes.Add(item); end; {------------------------------------------------------------------------------} constructor TPlugins.Create(fileName: string); begin Create; Self.FileName := fileName; end; {------------------------------------------------------------------------------} destructor TPlugins.Destroy; begin FreeAndNil(FTypes); inherited; end; {------------------------------------------------------------------------------} function TPlugins.GetCurrent: TPlugin; begin if (FItemIndex >= 0) and (FItemIndex < Count) then Result := Items[FItemIndex] else Result := nil; end; {------------------------------------------------------------------------------} function TPlugins.GetIsEmpty: Boolean; begin Result := Self.Count = 0; end; {------------------------------------------------------------------------------} function TPlugins.LoadFromFile(fileName: string): Boolean; var st : TStringList; text : string; begin Result := False; st := TStringList.Create; try if not TFile.Exists(fileName) then Exit; st.LoadFromFile(fileName); text := AnsiReplaceText(st.Text, '\', '/'); Result := self.LoadFromJson(text); finally FreeAndNil(st); end; end; {------------------------------------------------------------------------------} function TPlugins.LoadFromJson(AJSONValue: string): Boolean; begin Result := LoadFromJson(TJSONObject.ParseJSONValue(AJSONValue)); end; {------------------------------------------------------------------------------} function TPlugins.LoadFromJson(AJSONValue: TJSONValue): Boolean; var Enums: TJSONArrayEnumerator; tempJson : TJSONArray; plugin : TPlugin; temp : string; begin Result := False; try if uUtils.ValidateJSONArray(AJSONValue, tempJson) then Exit; Clear; Enums := tempJson.GetEnumerator; try while Enums.MoveNext do begin plugin := TPlugin.Create; plugin.LoadFromJson(Enums.Current); Self.Add(plugin); end; Result := True finally FreeAndNil(Enums); end; except on e : Exception do temp := e.Message; end; end; {------------------------------------------------------------------------------} function TPlugins.SaveToArray: TArray<string>; var sArray: TArray<string>; plugin : TPlugin; i : integer; begin sArray := TArray<string>.Create('1'); SetLength(sArray, self.Count); for i := 0 to self.Count - 1 do begin plugin := self[i]; sArray[i] := plugin.FName; end; Result := sArray; end; {------------------------------------------------------------------------------} function TPlugins.SaveToFile: Boolean; var st : TStringList; dirName, fName, text : string; begin Result := False; st := TStringList.Create; try if fileName.IsEmpty or not SaveToJson(text) then Exit; st.Text := text; dirName := System.IOUtils.TPath.GetDirectoryName(fileName); if ForceDirectories(dirName) then begin st.SaveToFile(fileName); Result := True; end; finally FreeAndNil(st); end; end; {------------------------------------------------------------------------------} function TPlugins.SaveToJson(var sJson: string): Boolean; var JsonArray: TJSONArray; plugin : TPlugin; temp : TJSONObject; begin Result := false; JsonArray := TJSONArray.Create; try for plugin in Self do if plugin.SaveToJson(temp) then JsonArray.Add(temp); sJson := JsonArray.ToString; Result := True; finally FreeAndNil(JsonArray); end; end; {------------------------------------------------------------------------------} procedure TPlugins.SetCurrent(const Value: TPlugin); begin if not Assigned(Value) then ItemIndex := INT_DEFAULT_INDEX else ItemIndex := IndexOf(Value); end; {------------------------------------------------------------------------------} procedure TPlugins.SetFileName(const Value: string); begin if FFileName.Equals(Value) then Exit; FFileName := Value; LoadFromFile(Value); end; {------------------------------------------------------------------------------} procedure TPlugins.SetItemIndex(const Value: Integer); var prevItemIndex : integer; begin prevItemIndex := FItemIndex; FItemIndex := Value; if prevItemIndex <> ItemIndex then if Assigned(OnChangeCurrent) then OnChangeCurrent(ItemIndex); end; {------------------------------------------------------------------------------} { TPlugin } {------------------------------------------------------------------------------} constructor TPlugin.Create; begin FIcon := TBitmap.Create(0,0); end; {------------------------------------------------------------------------------} destructor TPlugin.Destroy; begin FreeAndNil(FIcon); inherited; end; {------------------------------------------------------------------------------} function TPlugin.LoadFromJson(AJSONValue: TJSONValue): Boolean; var Enums: TJSONPairEnumerator; tempJson : TJSONObject; FoundIndex : Integer; decodeIcon : string; begin try if uUtils.ValidateJSONObject(AJSONValue, tempJson) then Exit(False); tempJson.TryGetValue<string>(ARRAY_PARSE[0], self.FName); if tempJson.TryGetValue<string>(ARRAY_PARSE[1], decodeIcon) then self.FIcon.Base64 := decodeIcon; tempJson.TryGetValue<Integer>(ARRAY_PARSE[2], self.FType); tempJson.TryGetValue<string>(ARRAY_PARSE[3], self.FPath); FIndex := INT_DEFAULT_INDEX; FChanged := True; Result := true; except Result := false; end; end; {------------------------------------------------------------------------------} function TPlugin.SaveToJson(var AJSONObject: TJSONObject): Boolean; var encodeIcon : string; begin Result := False; encodeIcon := self.FIcon.Base64; AJSONObject:= TJSONObject.Create; AJSONObject.AddPair(ARRAY_PARSE[0], FName); AJSONObject.AddPair(ARRAY_PARSE[2], integer.ToString(FType)); AJSONObject.AddPair(ARRAY_PARSE[3], FPath); AJSONObject.AddPair(ARRAY_PARSE[1], encodeIcon); //Convenient viewing file Result := True; end; {------------------------------------------------------------------------------} end.
{ Date Created: 5/22/00 11:17:32 AM } unit InfoCHECKACCOUNTSTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoCHECKACCOUNTSRecord = record PAccountName: String[32]; PAccountNumber: String[20]; PNextCheckNumber: Integer; End; TInfoCHECKACCOUNTSBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoCHECKACCOUNTSRecord end; TEIInfoCHECKACCOUNTS = (InfoCHECKACCOUNTSPrimaryKey); TInfoCHECKACCOUNTSTable = class( TDBISAMTableAU ) private FDFAccountName: TStringField; FDFAccountNumber: TStringField; FDFNextCheckNumber: TIntegerField; FDFTemplate: TBlobField; procedure SetPAccountName(const Value: String); function GetPAccountName:String; procedure SetPAccountNumber(const Value: String); function GetPAccountNumber:String; procedure SetPNextCheckNumber(const Value: Integer); function GetPNextCheckNumber:Integer; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; procedure SetEnumIndex(Value: TEIInfoCHECKACCOUNTS); function GetEnumIndex: TEIInfoCHECKACCOUNTS; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; virtual; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TInfoCHECKACCOUNTSRecord; procedure StoreDataBuffer(ABuffer:TInfoCHECKACCOUNTSRecord); property DFAccountName: TStringField read FDFAccountName; property DFAccountNumber: TStringField read FDFAccountNumber; property DFNextCheckNumber: TIntegerField read FDFNextCheckNumber; property DFTemplate: TBlobField read FDFTemplate; property PAccountName: String read GetPAccountName write SetPAccountName; property PAccountNumber: String read GetPAccountNumber write SetPAccountNumber; property PNextCheckNumber: Integer read GetPNextCheckNumber write SetPNextCheckNumber; procedure Validate; virtual; published property Active write SetActive; property EnumIndex: TEIInfoCHECKACCOUNTS read GetEnumIndex write SetEnumIndex; end; { TInfoCHECKACCOUNTSTable } procedure Register; implementation function TInfoCHECKACCOUNTSTable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; var I: Integer; NewName: string; Done: Boolean; function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean; var I: Integer; begin Result := False; for I := 0 To AOwner.ComponentCount - 1 do begin if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then begin Result := True; Break; end; end; end; { ComponentExists } begin { TInfoCHECKACCOUNTSTable.GenerateNewFieldName } NewName := DatasetName; for I := 1 to Length( FieldName ) do begin if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then NewName := NewName + FieldName[ I ]; end; if ComponentExists( Owner, NewName ) then begin I := 1; Done := False; repeat Inc( I ); if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then begin Result := NewName + IntToStr( I ); Done := True; end; until Done; end else Result := NewName; end; { TInfoCHECKACCOUNTSTable.GenerateNewFieldName } function TInfoCHECKACCOUNTSTable.CreateField( const FieldName : string ): TField; begin { First, try to find an existing field object. FindField is the same } { as FieldByName, but does not raise an exception if the field object } { cannot be found. } Result := FindField( FieldName ); if Result = nil then begin { If an existing field object cannot be found... } { Instruct the FieldDefs object to create a new field object } Result := FieldDefs.Find( FieldName ).CreateField( Owner ); { The new field object must be given a name so that it may appear in } { the Object Inspector. The Delphi default naming convention is used.} Result.Name := GenerateNewFieldName( Owner, Name, FieldName); end; end; { TInfoCHECKACCOUNTSTable.CreateField } procedure TInfoCHECKACCOUNTSTable.CreateFields; begin FDFAccountName := CreateField( 'AccountName' ) as TStringField; FDFAccountNumber := CreateField( 'AccountNumber' ) as TStringField; FDFNextCheckNumber := CreateField( 'NextCheckNumber' ) as TIntegerField; FDFTemplate := CreateField( 'Template' ) as TBlobField; end; { TInfoCHECKACCOUNTSTable.CreateFields } procedure TInfoCHECKACCOUNTSTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoCHECKACCOUNTSTable.SetActive } procedure TInfoCHECKACCOUNTSTable.Validate; begin { Enter Validation Code Here } end; { TInfoCHECKACCOUNTSTable.Validate } procedure TInfoCHECKACCOUNTSTable.SetPAccountName(const Value: String); begin DFAccountName.Value := Value; end; function TInfoCHECKACCOUNTSTable.GetPAccountName:String; begin result := DFAccountName.Value; end; procedure TInfoCHECKACCOUNTSTable.SetPAccountNumber(const Value: String); begin DFAccountNumber.Value := Value; end; function TInfoCHECKACCOUNTSTable.GetPAccountNumber:String; begin result := DFAccountNumber.Value; end; procedure TInfoCHECKACCOUNTSTable.SetPNextCheckNumber(const Value: Integer); begin DFNextCheckNumber.Value := Value; end; function TInfoCHECKACCOUNTSTable.GetPNextCheckNumber:Integer; begin result := DFNextCheckNumber.Value; end; procedure TInfoCHECKACCOUNTSTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('AccountName, String, 32, N'); Add('AccountNumber, String, 20, N'); Add('NextCheckNumber, Integer, 0, N'); Add('Template, Memo, 0, N'); end; end; procedure TInfoCHECKACCOUNTSTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, AccountName, Y, Y, N, N'); end; end; procedure TInfoCHECKACCOUNTSTable.SetEnumIndex(Value: TEIInfoCHECKACCOUNTS); begin case Value of InfoCHECKACCOUNTSPrimaryKey : IndexName := ''; end; end; function TInfoCHECKACCOUNTSTable.GetDataBuffer:TInfoCHECKACCOUNTSRecord; var buf: TInfoCHECKACCOUNTSRecord; begin fillchar(buf, sizeof(buf), 0); buf.PAccountName := DFAccountName.Value; buf.PAccountNumber := DFAccountNumber.Value; buf.PNextCheckNumber := DFNextCheckNumber.Value; result := buf; end; procedure TInfoCHECKACCOUNTSTable.StoreDataBuffer(ABuffer:TInfoCHECKACCOUNTSRecord); begin DFAccountName.Value := ABuffer.PAccountName; DFAccountNumber.Value := ABuffer.PAccountNumber; DFNextCheckNumber.Value := ABuffer.PNextCheckNumber; end; function TInfoCHECKACCOUNTSTable.GetEnumIndex: TEIInfoCHECKACCOUNTS; var iname : string; begin iname := uppercase(indexname); if iname = '' then result := InfoCHECKACCOUNTSPrimaryKey; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoCHECKACCOUNTSTable, TInfoCHECKACCOUNTSBuffer ] ); end; { Register } function TInfoCHECKACCOUNTSBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PAccountName; 2 : result := @Data.PAccountNumber; 3 : result := @Data.PNextCheckNumber; end; end; end. { InfoCHECKACCOUNTSTable }
{ *************************************************************************** } { } { } { Copyright (C) Amarildo Lacerda } { } { https://github.com/amarildolacerda } { } { } { *************************************************************************** } { } { 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 System.Classes.Helper; interface uses System.Classes, System.SysUtils, System.Rtti, System.TypInfo, System.Json; Type IFireEventProc = interface ['{BBC08E72-6518-4BF8-8BEE-0A46FD8B351C}'] procedure SetOnEvent(const Value: TProc<TObject>); procedure FireEvent(Sender: TObject); end; TObjectExt = class(System.TObject) private FOnFireEvent: TProc<TObject>; procedure SetOnFireEvent(const Value: TProc<TObject>); public procedure FireEvent; overload; procedure FireEvent(Sender: TObject); overload; property OnFireEvent: TProc<TObject> read FOnFireEvent write SetOnFireEvent; end; TCustomAttributeClass = class of TCustomAttribute; TMemberVisibilitySet = set of TMemberVisibility; TObjectHelper = class helper for TObject private function GetContextProperties(AName: string): TValue; procedure SetContextProperties(AName: string; const Value: TValue); function GetContextFields(AName: string): TValue; procedure SetContextFields(AName: string; const Value: TValue); function GetContextMethods(AName: String): TRttiMethod; public // metodos anonimous class procedure Using<T>(O: T; Proc: TProc<T>); static; class function Anonymous<T: Class>(O: T; Proc: TProc<T>): TObject; static; class procedure Run<T: Class>(O: T; Proc: TProc<T>); overload; static; class procedure Run(Proc: TProc); overload; static; class procedure WaitFor<T: Class>(O: T; Proc: TProc<T>); overload; static; class procedure WaitFor(Proc: TProc); overload; static; class function Queue<T: Class>(O: T; Proc: TProc<T>): TObject; overload; static; class procedure Queue(Proc: TProc); overload; static; class function Synchronize<T: Class>(O: T; Proc: TProc<T>): TObject; overload; static; class procedure Synchronize(Proc: TProc); overload; static; // JSON function ToJson:string; overload; function ToJsonObject:TJsonObject;overload; procedure FromJson(AJson:string);overload; class function FromJson<T:Class, constructor>(AJson:string):T;overload;static; // RTTI function ContextPropertyCount: Integer; function ContextPropertyName(idx: Integer): string; property ContextProperties[AName: string]: TValue read GetContextProperties write SetContextProperties; function IsContextProperty(AName:String):boolean; procedure GetContextPropertiesList(AList: TStrings; const AVisibility: TMemberVisibilitySet = [mvPublished, mvPublic]); procedure GetContextPropertiesItems(AList: TStrings; const AVisibility: TMemberVisibilitySet = [mvPublished, mvPublic]); function &ContextFieldsCount: Integer; function &ContextFieldName(idx: Integer): string; property ContextFields[AName: string]: TValue read GetContextFields write SetContextFields; procedure &ContextGetFieldsList(AList: TStrings; const AVisibility: TMemberVisibilitySet = [mvPublic]); property ContextMethods[AName: String]: TRttiMethod read GetContextMethods; procedure GetContextMethodsList(AList: TStrings; const AVisibility: TMemberVisibilitySet = [mvPublic]); function ContextHasAttribute(aMethod: TRttiMethod; attribClass: TCustomAttributeClass): Boolean; function ContextInvokeAttribute(attribClass: TCustomAttributeClass; params: array of TValue): Boolean; function ContextInvokeMethod(AName: string; params: array of TValue): Boolean; end; TTaskList = class(TThreadList) private FMaxThread: Integer; procedure SetMaxThread(const Value: Integer); public constructor create; procedure DoDestroyThread(Value: TObject); procedure Run(Proc: TProc); property MaxThread: Integer read FMaxThread write SetMaxThread; end; { TCollectionHelper = Class Helper for TCollection public function ToJson:string;virtual; end; } implementation uses System.DateUtils, REST.Json; class procedure TObjectHelper.Using<T>(O: T; Proc: TProc<T>); var obj: TObject; begin try Proc(O); finally freeAndNil(O); end; end; class procedure TObjectHelper.WaitFor(Proc: TProc); begin TObject.WaitFor<TObject>(nil, procedure(Sender: TObject) begin Proc; end); end; class procedure TObjectHelper.WaitFor<T>(O: T; Proc: TProc<T>); var th: TThread; begin th := TThread.CreateAnonymousThread( procedure begin Proc(O); end); th.Start; th.WaitFor; end; procedure TObjectExt.FireEvent; begin FireEvent(self); end; function TObjectHelper.&ContextFieldName(idx: Integer): string; var aCtx: TRttiContext; begin aCtx := TRttiContext.create; try result := ACtx.GetType(self.ClassType).GetFields[idx].Name; finally aCtx.Free; end; end; function TObjectHelper.&ContextFieldsCount: Integer; var aCtx: TRttiContext; begin aCtx := TRttiContext.create; try result := High(aCtx.GetType(self.ClassType).GetFields); finally aCtx.Free; end; end; procedure TObjectHelper.FromJson(AJson:string); var oJs:TJsonObject; begin oJs:=TJsonObject.ParseJSONValue(AJson) as TJSONObject ; TJson.JsonToObject(self,oJs); end; class function TObjectHelper.FromJson<T>(AJson: string): T; begin result := TJson.JsonToObject<T>(AJson); end; function TObjectHelper.GetContextFields(AName: string): TValue; var aCtx: TRttiContext; AField: TRttiField; begin result := nil; aCtx := TRttiContext.create; try AField := aCtx.GetType(self.ClassType).GetField(AName); if assigned(AField) then result := AField.GetValue(self); finally aCtx.Free; end; end; procedure TObjectHelper.&ContextGetFieldsList(AList: TStrings; const AVisibility: TMemberVisibilitySet = [mvPublic]); var aCtx: TRttiContext; AFld: TRttiField; begin AList.clear; aCtx := TRttiContext.create; try for AFld in aCtx.GetType(self.ClassType).GetFields do begin if AFld.Visibility in AVisibility then AList.Add(AFld.Name); end; finally aCtx.Free; end; end; function TObjectHelper.GetContextMethods(AName: String): TRttiMethod; var aCtx: TRttiContext; begin aCtx := TRttiContext.create; try result := aCtx.GetType(self.ClassType).GetMethod(AName); finally // ACtx.Free; end; end; procedure TObjectHelper.GetContextMethodsList(AList: TStrings; const AVisibility: TMemberVisibilitySet = [mvPublic]); var aMethod: TRttiMethod; aCtx: TRttiContext; begin AList.clear; aCtx := TRttiContext.create; try for aMethod in aCtx.GetType(self.ClassType).GetMethods do begin if aMethod.Visibility in AVisibility then AList.Add(aMethod.Name); end; finally aCtx.Free; end; end; function TObjectHelper.GetContextProperties(AName: string): TValue; var aCtx: TRttiContext; aProperty: TRttiProperty; begin result := nil; aCtx := TRttiContext.create; try aProperty := aCtx.GetType(self.ClassType).GetProperty(AName); if assigned(aProperty) then result := aProperty.GetValue(self); finally aCtx.Free; end; end; type // Adiciona funções ao TValue TValueHelper = record helper for TValue private function IsNumeric: Boolean; function IsFloat: Boolean; function AsFloat: Extended; function IsBoolean: Boolean; function IsDate: Boolean; function IsDateTime: Boolean; function IsDouble: Boolean; function AsDouble: Double; function IsInteger: Boolean; end; function TValueHelper.IsNumeric: Boolean; begin Result := Kind in [tkInteger, tkChar, tkEnumeration, tkFloat, tkWChar, tkInt64]; end; function TValueHelper.IsFloat: Boolean; begin Result := Kind = tkFloat; end; function TValueHelper.IsBoolean: Boolean; begin Result := TypeInfo = System.TypeInfo(Boolean); end; function TValueHelper.IsDate: Boolean; begin Result := TypeInfo = System.TypeInfo(TDate); end; function TValueHelper.IsDateTime: Boolean; begin Result := TypeInfo = System.TypeInfo(TDatetime); end; function TValueHelper.IsDouble: Boolean; begin Result := TypeInfo = System.TypeInfo(Double); end; function TValueHelper.IsInteger: Boolean; begin Result := TypeInfo = System.TypeInfo(integer); end; function TValueHelper.AsFloat: Extended; begin Result := AsType<Extended>; end; function TValueHelper.AsDouble: Double; begin Result := AsType<Double>; end; function ISODateTimeToString(ADateTime: TDateTime): string; begin result := DateToISO8601(ADateTime); end; function ISOStrToDateTime(DateTimeAsString: string): TDateTime; begin TryISO8601ToDate(DateTimeAsString, result); end; procedure TObjectHelper.GetContextPropertiesItems(AList: TStrings; const AVisibility: TMemberVisibilitySet); var aCtx: TRttiContext; aProperty: TRttiProperty; aRtti: TRttiType; AValue: TValue; begin AList.clear; aCtx := TRttiContext.Create; try aRtti := aCtx.GetType(self.ClassType); for aProperty in aRtti.GetProperties do begin if aProperty.Visibility in AVisibility then begin AValue := aProperty.GetValue(self); if AValue.IsDate or AValue.IsDateTime then AList.Add(aProperty.Name + '=' + ISODateTimeToString(AValue.AsDouble)) else if AValue.IsBoolean then AList.Add(aProperty.Name + '=' + ord(AValue.AsBoolean).ToString) else AList.Add(aProperty.Name + '=' + AValue.ToString); end; end; finally aCtx.free; end; end; procedure TObjectHelper.GetContextPropertiesList(AList: TStrings; const AVisibility: TMemberVisibilitySet = [mvPublished, mvPublic]); var aCtx: TRttiContext; aProperty: TRttiProperty; aRtti: TRttiType; begin AList.clear; aCtx := TRttiContext.create; try aRtti := aCtx.GetType(self.ClassType); for aProperty in aRtti.GetProperties do begin if aProperty.Visibility in AVisibility then AList.Add(aProperty.Name); end; finally aCtx.Free; end; end; function TObjectHelper.ContextHasAttribute(aMethod: TRttiMethod; attribClass: TCustomAttributeClass): Boolean; var attributes: TArray<TCustomAttribute>; attrib: TCustomAttribute; begin result := False; attributes := aMethod.GetAttributes; for attrib in attributes do if attrib.InheritsFrom(attribClass) then Exit(True); end; function TObjectHelper.ContextInvokeAttribute(attribClass: TCustomAttributeClass; params: array of TValue): Boolean; var aCtx: TRttiContext; aMethod: TRttiMethod; begin result := False; aCtx := TRttiContext.create; try for aMethod in aCtx.GetType(self.ClassType).GetMethods do begin if ContextHasAttribute(aMethod, attribClass) then begin aMethod.Invoke(self, params); result := True; end; end; finally aCtx.Free; end; end; function TObjectHelper.ContextInvokeMethod(AName: string; params: array of TValue): Boolean; var aMethod: TRttiMethod; begin aMethod := ContextMethods[AName]; if not assigned(aMethod) then Exit(False); try aMethod.Invoke(self, params); finally end; end; function TObjectHelper.IsContextProperty(AName: String): boolean; var v:TValue; begin v := ContextProperties[AName]; result := not v.IsEmpty; end; function TObjectHelper.ContextPropertyCount: Integer; var aCtx: TRttiContext; begin aCtx := TRttiContext.create; try result := High(aCtx.GetType(self.ClassType).GetProperties); finally aCtx.Free; end; end; function TObjectHelper.ContextPropertyName(idx: Integer): string; var aCtx: TRttiContext; begin aCtx := TRttiContext.create; try result := aCtx.GetType(self.ClassType).GetProperties[idx].Name; finally aCtx.Free; end; end; class procedure TObjectHelper.Queue(Proc: TProc); begin TThread.Queue(TThread.CurrentThread, procedure begin Proc; end); end; class function TObjectHelper.Queue<T>(O: T; Proc: TProc<T>): TObject; begin result := O; TThread.Queue(TThread.CurrentThread, procedure begin Proc(O); end); end; class procedure TObjectHelper.Run(Proc: TProc); begin TObject.Run<TObject>(TThread.CurrentThread, procedure(Sender: TObject) begin Proc; end); end; class procedure TObjectHelper.Run<T>(O: T; Proc: TProc<T>); begin TThread.CreateAnonymousThread( procedure begin Proc(O); end).Start; end; procedure TObjectHelper.SetContextFields(AName: string; const Value: TValue); var AField: TRttiField; aCtx: TRttiContext; begin aCtx := TRttiContext.create; try AField := aCtx.GetType(self.ClassType).GetField(AName); if assigned(AField) then AField.SetValue(self, Value); finally aCtx.Free; end; end; procedure TObjectHelper.SetContextProperties(AName: string; const Value: TValue); var aProperty: TRttiProperty; aCtx: TRttiContext; begin aCtx := TRttiContext.create; try aProperty := aCtx.GetType(self.ClassType).GetProperty(AName); if assigned(aProperty) then aProperty.SetValue(self, Value); finally aCtx.Free; end; end; class procedure TObjectHelper.Synchronize(Proc: TProc); begin TThread.Synchronize(TThread.CurrentThread, procedure begin Proc end); end; class function TObjectHelper.Synchronize<T>(O: T; Proc: TProc<T>): TObject; begin result := O; TThread.Synchronize(TThread.CurrentThread, procedure begin Proc(O); end); end; function TObjectHelper.toJson: string; begin // System.uJson result := TJson.ObjectToJsonString(self); end; function TObjectHelper.ToJsonObject: TJsonObject; begin result := TJson.ObjectToJsonObject(self); end; class function TObjectHelper.Anonymous<T>(O: T; Proc: TProc<T>): TObject; begin result := O; Proc(O); end; { TObject } procedure TObjectExt.FireEvent(Sender: TObject); begin if assigned(FOnFireEvent) then FOnFireEvent(Sender); end; procedure TObjectExt.SetOnFireEvent(const Value: TProc<TObject>); begin FOnFireEvent := Value; end; { TThreadedPool } constructor TTaskList.create; begin inherited; FMaxThread := 10; end; procedure TTaskList.DoDestroyThread(Value: TObject); begin Remove(Value); end; procedure TTaskList.Run(Proc: TProc); var T: TThread; begin T := TThread.CreateAnonymousThread(Proc); T.onTerminate := DoDestroyThread; Add(T); T.Start; end; procedure TTaskList.SetMaxThread(const Value: Integer); begin FMaxThread := Value; end; { TCollectionHelper } { function TCollectionHelper.ToJson: string; var j:TJsonArray; i:integer; begin j := TJsonArray.Create; try for I := 0 to count-1 do j.AddElement( TJson.ObjectToJsonObject( items[i] ) ); result := j.ToJSON; finally j.Free; end; end; } end.
/// Utility methods to convert images form file formats to Excel internal formats. unit tmsUXlsPictures; {$INCLUDE ..\FLXCOMPILER.INC} {$INCLUDE ..\FLXCONFIG.INC} interface uses {$IFDEF FLX_VCL} Windows, Graphics, {$IFDEF FLX_NEEDSJPEG} JPEG, {$ENDIF} {$INCLUDE UsePngLib.inc} {$ENDIF} {$IFDEF FLX_CLX} Qt, QGraphics, QGrids, Types, QControls, {$ENDIF} {$IFDEF FLX_NEEDSVARIANTS} variants,{$ENDIF} //Delphi 6 or above SysUtils, Classes, tmsUFlxMessages, tmsUExcelAdapter; type /// <summary> /// This record is for internal use. /// </summary> TSmallRect=packed record /// <summary>Internal use. </summary> Left: SmallInt; /// <summary>Internal use. </summary> Top: SmallInt; /// <summary>Internal use. </summary> Right: SmallInt; /// <summary>Internal use. </summary> Bottom: SmallInt; end; /// <summary>WMF Header. Internal use. </summary> TMetafileHeader = packed record /// <summary>Internal use. </summary> Key: Longint; /// <summary>Internal use. </summary> Handle: SmallInt; /// <summary>Internal use. </summary> Rect: TSmallRect; /// <summary>Internal use. </summary> Inch: Word; /// <summary>Internal use. </summary> Reserved: Longint; /// <summary>Internal use. </summary> CheckSum: Word; end; //------------------------------------------------------------------------------ /// <summary> /// This method will load a WMF image returned from Excel into a TPicture image. /// </summary> /// <remarks> /// WMF images are stored differently in Excel than in disk, so you need this method to do the /// conversion.<para></para> /// <para></para> /// Normally you will want to use SaveImgStreamToGraphic or SaveImgStreamToDiskImage instead of this /// method, since those ones convert any kind of images form Excel to their disk representation, not only /// metafiles. /// </remarks> /// <param name="OutPicture">TPicture where the image will be loaded.</param> /// <param name="InStream">Stream with the image as Excel returns it.</param> /// <param name="PicType">Picture type as returned from Excel. this method will only handle EMF and /// WMF, for a generic method that an convert any kind of images use /// SaveImgStreamToGraphic.</param> procedure LoadWmf(const OutPicture: TPicture; const InStream: TStream; const PicType: TXlsImgTypes); /// <summary> /// Loads an image returned by <see cref="TFlexCelImport.GetPicture@integer@TStream@TXlsImgTypes@TClientAnchor" text="TFlexCelImport.GetPicture" /> /// into a TPicture object. /// </summary> /// <remarks> /// If you want to save the image to disk instead of loading it into a TPicture, you might want to use <see cref="SaveImgStreamToDiskImage@TStream@TXlsImgTypes@TStream@boolean" text="SaveImgStreamToDiskImage" /> /// instead. /// </remarks> /// <param name="Pic">Stream with the data returned by <see cref="TFlexCelImport.GetPicture@integer@TStream@TXlsImgTypes@TClientAnchor" text="TFlexCelImport.GetPicture" />.</param> /// <param name="PicType">Picture type returned by <see cref="TFlexCelImport.GetPicture@integer@TStream@TXlsImgTypes@TClientAnchor" text="TFlexCelImport.GetPicture" />.</param> /// <param name="Picture">TPicture object where you want to load the image.</param> /// <param name="Handled">Will return True if the image could be loaded, false if it couldn't be parsed.</param> procedure SaveImgStreamToGraphic(const Pic: TStream; const PicType: TXlsImgTypes; const Picture: TPicture; out Handled: boolean); /// <summary> /// Converts an image returned by <see cref="TFlexCelImport.GetPicture@integer@TStream@TXlsImgTypes@TClientAnchor" text="TFlexCelImport.GetPicture" /> /// from Excel internal format to a format that can be saved to disk. /// </summary> /// <remarks> /// If you want to load the image into a TPicture object instead of saving it to disk, you might want to /// use <see cref="SaveImgStreamToGraphic@TStream@TXlsImgTypes@TPicture@boolean" text="SaveImgStreamToGraphic" /> /// instead. /// </remarks> /// <param name="Pic">Stream with the data returned by <see cref="TFlexCelImport.GetPicture@integer@TStream@TXlsImgTypes@TClientAnchor" text="TFlexCelImport.GetPicture" />.</param> /// <param name="PicType">Picture type returned by <see cref="TFlexCelImport.GetPicture@integer@TStream@TXlsImgTypes@TClientAnchor" text="TFlexCelImport.GetPicture" />.</param> /// <param name="OutStream">Stream where you want to save the image.</param> /// <param name="Saved">Will return true if FlexCel coud process the file, false if the file was in /// an unknown format.</param> procedure SaveImgStreamToDiskImage(const Pic: TStream; const PicType: TXlsImgTypes; const OutStream: TStream; out Saved: boolean); /// <summary> /// \Returns a bitmap containing the pattern specified. /// </summary> /// <remarks> /// You will normally not need to use this method. It is used internally by FlexCelGrid to display bitmap /// patterns in cells.<para></para> /// <para></para> /// This method creates a 4x4 or 8x4 bitmap with the pattern number specified by n, using ColorFg as the /// foreground color and ColorBg as the background color for the pattern.<para></para> /// <para></para> /// You can use the returned bitmap as bitmap for a TCanvas.Brush<para></para> /// <para></para> /// It is your responsibility to free the created bitmap when it is not more in use.<para></para> /// <para></para> /// Possible n values:<para></para> /// <img name="patterns" /><para></para> /// <para></para> /// n=1 means no background.<para></para> /// /// </remarks> /// <param name="n">Indicates the type of pattern, as in the image above.</param> /// <param name="ColorFg">Color for the foreground pattern.</param> /// <param name="ColorBg">Color for the background pattern.</param> /// <returns> /// \ \ /// </returns> function CreateBmpPattern(const n, ColorFg, ColorBg: integer): TBitmap; /// <summary> /// Computes the Aldus Checksum for a Windows Metafile. /// </summary> /// <remarks> /// This method is for internal use. /// </remarks> /// <param name="WMF">Header of the metafile.</param> function ComputeAldusChecksum(var WMF: TMetafileHeader): Word; //------------------------------------------------------------------------------ implementation function ComputeAldusChecksum(var WMF: TMetafileHeader): Word; type PWord = ^Word; var pW: PWord; pEnd: PWord; begin Result := 0; pW := @WMF; pEnd := @WMF.CheckSum; while PAddress(pW) < PAddress(pEnd) do begin Result := Result xor pW^; Inc(PAddress(pW), SizeOf(Word)); end; end; {$IFDEF USEPNGLIB} procedure LoadWmfInStream(const OutStream: TStream; const InStream: TStream; const PicType: TXlsImgTypes; out Saved: boolean); const Z_OK=0; Z_STREAM_END=1; var WmfHead: TMetafileHeader; CompressedStream: TMemoryStream; ZL: TZStreamRec; Buff: Array of byte; Res, LastOut: integer; BoundRect: TRect; IsCompressed: byte; begin Saved:=true; if PicType=xli_wmf then begin //Write Metafile Header FillChar(WmfHead, SizeOf(WmfHead), 0); WmfHead.Key:=Integer($9AC6CDD7); InStream.Position:=4; //We can't just read into WmfHead.Rect, because this is small ints, not ints InStream.ReadBuffer(BoundRect, SizeOf(BoundRect)); WmfHead.Rect.Left:=BoundRect.Left; WmfHead.Rect.Top:=BoundRect.Top; WmfHead.Rect.Right:=BoundRect.Right; WmfHead.Rect.Bottom:=BoundRect.Bottom; WmfHead.Inch:=96; WmfHead.CheckSum:=ComputeAldusChecksum(WmfHead); OutStream.WriteBuffer(WmfHead, SizeOf(WmfHead)); end; InStream.Position:=32; InStream.ReadBuffer(IsCompressed, SizeOf(IsCompressed)); InStream.Position:=34; if IsCompressed=0 then //Data is compressed begin //Uncompress Data Fillchar(ZL, SIZEOF(TZStreamRec), 0); CompressedStream:=TMemoryStream.Create; try CompressedStream.CopyFrom(InStream, InStream.Size- InStream.Position); CompressedStream.Position:=0; FillChar(Zl, SizeOf(Zl), #0); Zl.next_in:=CompressedStream.Memory; Zl.avail_in:=CompressedStream.Size; SetLength(Buff, 2048); //Arbitrary block size Zl.next_out:=@Buff[0]; Zl.avail_out:=Length(Buff); LastOut:=0; try if InflateInit_(ZL, zlib_version, SIZEOF(TZStreamRec))<> Z_OK then raise Exception.Create(ErrInvalidWmf); repeat Res:=Inflate(ZL,0); if (Res<> Z_OK) and (Res<>Z_STREAM_END) then raise Exception.Create(ErrInvalidWmf); OutStream.WriteBuffer(Buff[0], Integer(Zl.Total_Out) - LastOut); LastOut:=Zl.Total_Out; Zl.next_out:=@Buff[0]; Zl.avail_out:=Length(Buff); until Res= Z_STREAM_END; finally InflateEnd(ZL); end; //Finally finally FreeAndNil(CompressedStream); end; end else begin OutStream.CopyFrom(InStream, InStream.Size-InStream.Position); end; end; procedure LoadWmf(const OutPicture: TPicture; const InStream: TStream; const PicType: TXlsImgTypes); var MemStream: TMemoryStream; Saved: boolean; begin MemStream:=TMemoryStream.Create; try LoadWmfInStream(MemStream, InStream, PicType, Saved); MemStream.Position:=0; OutPicture.Graphic.LoadFromStream(MemStream); finally FreeAndNil(MemStream); end; //Finally end; {$ELSE} procedure LoadWmf(const OutPicture: TPicture; const InStream: TStream; const PicType: TXlsImgTypes); begin end; procedure LoadWmfInStream(const OutStream: TStream; const InStream: TStream; const PicType: TXlsImgTypes; out Saved: boolean); begin Saved := false; end; {$ENDIF} procedure SaveImgStreamToGraphic(const Pic: TStream; const PicType: TXlsImgTypes; const Picture: TPicture; out Handled: boolean); var Bmp:TBitmap; {$IFDEF FLX_VCL} Jpeg: TJpegImage; {$ENDIF} {$IFDEF USEPNGLIB} Png: TPngImage; {$IFDEF FLX_SUPPORTSWMF} Wmf: TMetafile; {$ENDIF} {$ENDIF} begin Handled:=true; case PicType of {$IFDEF FLX_VCL} xli_Jpeg: begin Jpeg:=TJPEGImage.Create; try Picture.Graphic:=Jpeg; finally FreeAndNil(Jpeg); //Remember TPicture.Graphic keeps a COPY of the TGraphic end; (Picture.Graphic as TJPEGImage).Performance:=jpBestQuality; Picture.Graphic.LoadFromStream(Pic); end; xli_Bmp: begin Bmp:=TBitmap.Create; try Picture.Graphic:=Bmp; finally FreeAndNil(Bmp); //Remember TPicture.Graphic keeps a COPY of the TGraphic end; Picture.Graphic.LoadFromStream(Pic); end; //There is no direct support for PNG, because there is not a standard Delphi class to support it. //No direct support for wmf/emf, because it uses zlib and it would have to be added to the package list. //To support it define USEPNGLIB at the top of this file {$IFDEF USEPNGLIB} xli_png: begin Png:=TPNGImage.Create; try Picture.Graphic:=Png; finally FreeAndNil(Png); //Remember TPicture.Graphic keeps a COPY of the TGraphic end; Picture.Graphic.LoadFromStream(Pic); end; {$IFDEF FLX_SUPPORTSWMF} xli_wmf, xli_emf: begin Wmf:=TMetaFile.Create; try Picture.Graphic:=Wmf; finally FreeAndNil(Wmf); end; //finally LoadWmf(Picture, Pic, PicType); end; {$ENDIF} {$ENDIF} {$ENDIF} {$IFDEF FLX_CLX} //Here png is directly supported. Not metafiles... xli_Bmp, xli_Jpeg, xli_Png: begin Bmp:=TBitmap.Create; try Picture.Graphic:=Bmp; finally FreeAndNil(Bmp); //Remember TPicture.Graphic keeps a COPY of the TGraphic end; Picture.Graphic.LoadFromStream(Pic); end; {$ENDIF} else Handled:=False; end; //case end; procedure SaveImgStreamToDiskImage(const Pic: TStream; const PicType: TXlsImgTypes; const OutStream: TStream; out Saved: boolean); begin Saved := true; case PicType of xli_Emf, xli_Wmf: LoadWmfInStream(OutStream, Pic, PicType, Saved); xli_Jpeg, xli_Png, xli_Bmp: OutStream.CopyFrom(Pic, Pic.Size); else Saved := false; end; end; {$IFDEF FLX_CLX} {$IFDEF VER140} Kylix3 is 140 too... and it allows patterns. Patterns are not allowed for d6/bcb6 clx. {$DEFINE FLX_NOPATTERN} {$ENDIF} {$ENDIF} procedure Fill8x8Image(const Bmp: TBitmap); begin Bmp.Canvas.Draw(0,4,Bmp); Bmp.Canvas.Draw(4,0,Bmp); end; {$IFDEF FLX_NOPATTERN} function CreateBmpPattern(const n, ColorFg, ColorBg: integer): TBitmap; var Ac: TCanvas; begin Result:=TBitmap.Create; try Result.Width:=8; Result.Height:=8; {$IFDEF FLX_CLX} Result.PixelFormat:=pf32bit; {$ELSE} Result.PixelFormat := pfDevice; //for win95 {$ENDIF} Ac:=Result.Canvas; case n of 1: //No pattern begin Ac.Brush.Color:=ColorBg; Ac.FillRect(Rect(0,0,8,8)); end; else //fill pattern //No pixel support on tcanvas, so we can't use patterns here. begin Ac.Brush.Color:=ColorFg; Ac.FillRect(Rect(0,0,8,8)); end; end; //case except FreeAndNil(Result); raise; end; end; {$ELSE} function CreateBmpPattern(const n, ColorFg, ColorBg: integer): TBitmap; var Ac: TCanvas; x,y: integer; begin Result:=TBitmap.Create; try Result.Width:=8; //We just need a 4x4 bitmap, but windows95 does not like it. Result.Height:=8; {$IFDEF FLX_CLX} Result.PixelFormat:=pf32bit; {$ELSE} Result.PixelFormat := pfDevice; //for win95 {$ENDIF} Ac:=Result.Canvas; case n of 1: //No pattern begin Ac.Brush.Color:=ColorBg; Ac.FillRect(Rect(0,0,8,8)); end; 2: //fill pattern begin Ac.Brush.Color:=ColorFg; Ac.FillRect(Rect(0,0,8,8)); end; 3: //50% begin Ac.Brush.Color:=ColorBg; Ac.FillRect(Rect(0,0,8,8)); for y:=0 to 7 do for x:=0 to 3 do Ac.Pixels[x*2+y mod 2,y]:=ColorFg; end; 4: //75% begin Ac.Brush.Color:=ColorFg; Ac.FillRect(Rect(0,0,4,4)); Ac.Pixels[0,0]:=ColorBg; Ac.Pixels[2,1]:=ColorBg; Ac.Pixels[0,2]:=ColorBg; Ac.Pixels[2,3]:=ColorBg; Fill8x8Image(Result); end; 5: //25% begin Ac.Brush.Color:=ColorBg; Ac.FillRect(Rect(0,0,4,4)); Ac.Pixels[0,0]:=ColorFg; Ac.Pixels[2,1]:=ColorFg; Ac.Pixels[0,2]:=ColorFg; Ac.Pixels[2,3]:=ColorFg; Fill8x8Image(Result); end; 6: //Horz lines begin Ac.Brush.Color:=ColorFg; Ac.FillRect(Rect(0,0,4,2)); Ac.Brush.Color:=ColorBg; Ac.FillRect(Rect(0,2,4,4)); Fill8x8Image(Result); end; 7: //Vert lines begin Ac.Brush.Color:=ColorFg; Ac.FillRect(Rect(0,0,2,4)); Ac.Brush.Color:=ColorBg; Ac.FillRect(Rect(2,0,4,4)); Fill8x8Image(Result); end; 8: // \ lines begin Ac.Brush.Color:=ColorBg; Ac.FillRect(Rect(0,0,4,4)); Ac.Pixels[0,0]:=ColorFg; Ac.Pixels[1,0]:=ColorFg; Ac.Pixels[1,1]:=ColorFg; Ac.Pixels[2,1]:=ColorFg; Ac.Pixels[2,2]:=ColorFg; Ac.Pixels[3,2]:=ColorFg; Ac.Pixels[3,3]:=ColorFg; Ac.Pixels[0,3]:=ColorFg; Fill8x8Image(Result); end; 9: // / lines begin Ac.Brush.Color:=ColorBg; Ac.FillRect(Rect(0,0,4,4)); Ac.Pixels[2,0]:=ColorFg; Ac.Pixels[3,0]:=ColorFg; Ac.Pixels[1,1]:=ColorFg; Ac.Pixels[2,1]:=ColorFg; Ac.Pixels[0,2]:=ColorFg; Ac.Pixels[1,2]:=ColorFg; Ac.Pixels[3,3]:=ColorFg; Ac.Pixels[0,3]:=ColorFg; Fill8x8Image(Result); end; 10: // diagonal hatch begin Ac.Brush.Color:=ColorBg; Ac.FillRect(Rect(0,0,4,4)); Ac.Pixels[0,0]:=ColorFg; Ac.Pixels[1,0]:=ColorFg; Ac.Pixels[0,1]:=ColorFg; Ac.Pixels[1,1]:=ColorFg; Ac.Pixels[2,2]:=ColorFg; Ac.Pixels[3,2]:=ColorFg; Ac.Pixels[2,3]:=ColorFg; Ac.Pixels[3,3]:=ColorFg; Fill8x8Image(Result); end; 11: // bold diagonal begin Ac.Brush.Color:=ColorFg; Ac.FillRect(Rect(0,0,4,4)); Ac.Pixels[2,0]:=ColorBg; Ac.Pixels[3,0]:=ColorBg; Ac.Pixels[0,2]:=ColorBg; Ac.Pixels[1,2]:=ColorBg; Fill8x8Image(Result); end; 12: // thin horz lines begin Ac.Brush.Color:=ColorFg; Ac.FillRect(Rect(0,0,4,1)); Ac.Brush.Color:=ColorBg; Ac.FillRect(Rect(0,1,4,4)); Fill8x8Image(Result); end; 13: // thin vert lines begin Ac.Brush.Color:=ColorFg; Ac.FillRect(Rect(0,0,1,4)); Ac.Brush.Color:=ColorBg; Ac.FillRect(Rect(1,0,4,4)); Fill8x8Image(Result); end; 14: // thin \ lines begin Ac.Brush.Color:=ColorBg; Ac.FillRect(Rect(0,0,4,4)); Ac.Pixels[0,0]:=ColorFg; Ac.Pixels[1,1]:=ColorFg; Ac.Pixels[2,2]:=ColorFg; Ac.Pixels[3,3]:=ColorFg; Fill8x8Image(Result); end; 15: // thin / lines begin Ac.Brush.Color:=ColorBg; Ac.FillRect(Rect(0,0,4,4)); Ac.Pixels[3,0]:=ColorFg; Ac.Pixels[2,1]:=ColorFg; Ac.Pixels[1,2]:=ColorFg; Ac.Pixels[0,3]:=ColorFg; Fill8x8Image(Result); end; 16: // thin horz hatch begin Ac.Brush.Color:=ColorFg; Ac.FillRect(Rect(0,0,4,4)); Ac.Brush.Color:=ColorBg; Ac.FillRect(Rect(1,1,4,4)); Fill8x8Image(Result); end; 17: // thin diag begin Ac.Brush.Color:=ColorBg; Ac.FillRect(Rect(0,0,4,4)); Ac.Pixels[0,0]:=ColorFg; Ac.Pixels[2,0]:=ColorFg; Ac.Pixels[1,1]:=ColorFg; Ac.Pixels[0,2]:=ColorFg; Ac.Pixels[2,2]:=ColorFg; Ac.Pixels[3,3]:=ColorFg; Fill8x8Image(Result); end; 18: // 12.5 % begin Ac.Brush.Color:=ColorBg; Ac.FillRect(Rect(0,0,4,4)); Ac.Pixels[0,0]:=ColorFg; Ac.Pixels[2,2]:=ColorFg; Fill8x8Image(Result); end; 19: // 6.25 % begin //Not needed now. Result.Width:=8; Ac.Brush.Color:=ColorBg; Ac.FillRect(Rect(0,0,8,8)); Ac.Pixels[0,0]:=ColorFg; Ac.Pixels[4,2]:=ColorFg; Ac.Pixels[0,4]:=ColorFg; Ac.Pixels[4,6]:=ColorFg; end; end; //case except FreeAndNil(Result); raise; end; end; {$ENDIF} end.
unit proses_buku; interface uses tipe_data, konversi; procedure CetakKategori(var B : tabBuku); // prosedur untuk mencetak buku berdasarkan kategori procedure Cetak (var B : tabBuku ; i : integer); // prosedur untuk mencetak info buku sesuai ketentuan procedure CetakDariTahun (var B : tabBuku); //procedure untuk mencetak buku berdasarkan ketentuan tahun procedure pinjam_buku (var tb : tabBuku; var tp : tabPinjam; var active_user: tuser; var isSave: boolean) ; {Meminjam buku yang ada, data di-update ke tabPinjam} procedure kembalikan_buku (var tb: tabBuku ; var tp: tabPinjam ; var tk: tabKembali ; var active_user : tuser; var isSave : Boolean ) ; {Mengembalikan buku yang telah dipinjam, di-update ke data peminjaman} function FoundBookIdIdx (var Id : integer; var ArrBook : tabBuku): integer; {Mencari indeks buku dengan id tertentu, asumsi id terdaftar} procedure SortArrBook (var ArrBook : tabBuku ); {Mengurutkan Array Daftar Buku} procedure AddJumlahBuku (var array_buku : tabBuku; var active_user : tuser; var isSave : boolean); {Menambahkan jumlah buku} procedure AddBook (var array_buku : tabBuku; var active_user : tuser; var isSave : boolean); {Menambahkan buku baru} procedure SeeLost (var array_hilang : tabHilang; var active_user : tuser); {Prosedur untuk melihat data buku yang hilang} procedure RegLost (var array_hilang : tabHilang; var isSave : boolean); {Prosedur untuk melaporkan buku yang hilang} implementation procedure CetakKategori(var B : TabBuku); (*Kamus Lokal*) var i,buku_ada : integer; stop : boolean; K : string; // Skema Validasi II (*Algoritma*) begin writeln(''); stop := false; repeat write('Masukkan kategori: '); readln(K); if ((K ='sastra') or (K ='sains') or (K ='manga') or (K ='sejarah') or (K ='programming')) then begin stop := true; end else begin writeln('Kategori ',K,' tidak valid.'); end; until(stop); // Mencari berdasarkan kategori buku writeln(); writeln('Hasil pencarian: '); buku_ada := 0; for i:=1 to B.Neff do // jika buku tidak kosong then begin if (B.T[i].Jumlah_Buku <> 0) and (B.T[i].Kategori = K) then begin buku_ada := buku_ada + 1; write(B.T[i].ID_Buku,' | '); write(B.T[i].Judul_Buku,' | '); writeln(B.T[i].Author); // select dan write data yang ada di csv. Sesuai ketentuan ID Buku | Judul | Penulis end; end; // Kasus buku kosong if (buku_ada = 0) then begin writeln('Tidak ada buku dalam kategori ini'); end; writeln(''); end; procedure Cetak (var B : TabBuku ; i : integer); // prosedur untuk mencetak info buku sesuai ketentuan (*Algoritma*) begin write(B.T[i].ID_Buku,' | '); write(B.T[i].Judul_Buku,' | '); writeln(B.T[i].Author); end; procedure CetakDariTahun (var B : TabBuku); (*Kamus Lokal*) var T : integer; // T adalah tahun buku K : string; // K adalah kategori pencarian {=,>,<,>=,<=} i,buku_ada : integer; (*Algoritma*) begin // Input writeln(''); write('Masukkan tahun: '); readln(T); write('Masukkan kategori (< > = <= >=): '); readln(K); writeln(); // Mencari berdasarkan kategori {=,>,<,>=,<=} tahun tahun terbit buku writeln('Buku yang terbit ',K,' ',T,':'); buku_ada := 0; // flag digunakan untuk proses pengecekan, buku ada sesuai dengan input pengguna atau tidak for i:=1 to B.Neff do // jika buku tidak kosong then begin if (K = '=') and (B.T[i].Tahun_Penerbit = T) then begin Cetak(B,i); // select dan write data yang ada di csv. Sesuai ketentuan ID Buku | Judul | Penulis buku_ada := buku_ada + 1; end else if (K='>=') and (B.T[i].Tahun_Penerbit >= T) then begin Cetak(B,i); buku_ada := buku_ada + 1; end else if (K='>') and (B.T[i].Tahun_Penerbit > T) then begin Cetak(B,i); buku_ada := buku_ada + 1; end else if (K='<=') and (B.T[i].Tahun_Penerbit <= T) then begin Cetak(B,i); buku_ada := buku_ada + 1; end else if (K='<') and (B.T[i].Tahun_Penerbit < T) then begin Cetak(B,i); buku_ada := buku_ada + 1; end else begin buku_ada := buku_ada + 0; end; end; // Kasus buku tidak ada if (buku_ada = 0) then begin writeln('Tidak ada buku dalam kategori ini.'); end; writeln(''); end; procedure pinjam_buku (var tb : tabBuku; var tp : tabPinjam; var active_user: tuser; var isSave: boolean) ; {Meminjam buku yang ada, data di-update ke tabPinjam} {Kamus Lokal} var id : integer; {ID buku yang ingin dipinjam} i: integer; {untuk Looping} tanggal : string; found : boolean; {untuk skema pencarian} (*Algoritma*) begin if(active_user.role = 'admin') then begin writeln(''); writeln('Hanya untuk pengunjung!'); writeln(''); end else begin writeln(''); write('Masukkan id buku yang ingin dipinjam: ') ; readln(id); write('Masukkan tanggal hari ini: ') ; readln(tanggal); (* Masukan dd/mm/yyyy *) i := 1; found := false; while( i <= tb.Neff ) and (not found) do begin (*Asumsi masukan valid*) if tb.t[i].ID_Buku = id then begin if tb.t[i].Jumlah_Buku > 0 then begin tp.Neff := tp.Neff + 1; tp.t[tp.Neff].ID_Buku:= id; tp.t[tp.Neff].Judul_Buku:= tb.t[i].Judul_Buku; tp.t[tp.Neff].Username:= active_user.Username; tp.t[tp.Neff].Tanggal_Peminjaman:= tanggal; tp.t[tp.Neff].Tanggal_Batas_Peminjaman:= tanggalToString( batas(stringToTanggal(tanggal) , 7)); {Batas peminjaman = 7 hari} tp.t[tp.Neff].Status_Pengembalian:= false; writeln('Buku ' , tb.t[i].Judul_Buku , ' berhasil dipinjam!'); writeln('Tersisa ', tb.t[i].Jumlah_Buku - 1 , ' Buku ', tb.t[i].Judul_Buku ); writeln('Terima kasih sudah meminjam!'); writeln(''); tb.t[i].Jumlah_Buku := tb.t[i].Jumlah_Buku - 1; end else (*Buku habis*) begin writeln('Buku ' , tb.t[i].Judul_Buku , ' sedang habis!'); writeln('Coba lain kali.'); writeln(''); end; found := true; end else begin i := i + 1; end; end; if (not found) then begin writeln('Maaf, buku tidak ditemukan!'); writeln(''); end; isSave := False; end; end; procedure kembalikan_buku (var tb: tabBuku ; var tp: tabPinjam ; var tk: tabKembali ; var active_user : tuser; var isSave : Boolean ) ; {Mengembalikan buku yang telah dipinjam, di-update ke data peminjaman} {Kamus Lokal} var id : integer; {ID buku yang ingin dikembalikan} i,j : integer ; {untuk Looping} tgl : string ; denda : Longint; {untuk menghitung denda keterlambatan} (*Algoritma*) begin if(active_user.role = 'admin') then begin writeln(''); writeln('Hanya untuk pengunjung!'); writeln(''); end else begin writeln(''); write('Masukkan id buku yang dikembalikan: '); readln(id); writeln('Data peminjaman:'); for i:=1 to tp.Neff do begin if (( tp.t[i].ID_Buku = id ) and (tp.t[i].Username = active_user.username)) then begin write('Username: '); writeln(tp.t[i].Username); write('Judul buku: '); writeln(tp.t[i].Judul_Buku); write('Tanggal peminjaman: '); writeln(tp.t[i].Tanggal_Peminjaman); write('Tanggal batas pengembalian: '); writeln(tp.t[i].Tanggal_Batas_Peminjaman); writeln(); write('Masukkan tanggal hari ini: '); read(tgl); {Masukan valid dd/mm/yyyy} tk.Neff := tk.Neff + 1; tk.t[tk.Neff].Username:= tp.t[i].Username; tk.t[tk.Neff].ID_Buku:= tp.t[i].ID_Buku; tk.t[tk.Neff].Tanggal_Pengembalian:= tgl; tp.t[i].Status_Pengembalian:= true; for j:= 1 to tb.Neff do begin if (tb.t[j].ID_Buku = tp.t[i].ID_Buku) then begin tb.t[j].Jumlah_Buku:= tb.t[j].Jumlah_Buku + 1; {Mengembalikan jumlah buku di tabBuku} end; end; if ( selisihHari(stringToTanggal(tgl),stringToTanggal(tp.t[i].Tanggal_Peminjaman)) <= 7 ) then begin writeln('Terima kasih sudah meminjam.'); end else {Menghitung denda} begin writeln('Anda terlambat mengembalikan buku.'); denda:= selisihHari( stringToTanggal(tgl) , stringToTanggal(tp.t[i].Tanggal_Batas_Peminjaman) ) * 2000 ; writeln('Anda terkena denda ' , denda ,'.'); writeln(''); end; end; end; isSave := False; end; end; function FoundBookIdIdx (var Id : integer; var ArrBook : tabBuku): integer; {Mencari indeks buku dengan id tertentu, asumsi id terdaftar} {KAMUS LOKAL} var i : integer; found : boolean; {ALGORITMA} begin i := 1; found := False; repeat begin if (ArrBook.T[i].ID_Buku = Id) then begin found := True; end; i := i + 1; end; until ((found) or (i > ArrBook.Neff)); FoundBookIdIdx := i-1; end; procedure SortArrBook (var ArrBook : tabBuku); {Mengurutkan Array Daftar Buku} {KAMUS LOKAL} var Check, i, j : integer; Temp : buku; stop : boolean; {ALGORITMA} begin for Check := 1 to ArrBook.Neff do begin Temp := ArrBook.T[Check]; i := Check - 1; j := 1; stop := False; repeat while (ord (ArrBook.T[i].Judul_Buku [j]) > ord (Temp.Judul_Buku [j])) and (i > 1) do begin ArrBook.T[i + 1] := ArrBook.T[i]; i := i - 1; end; if (ord (ArrBook.T[i].Judul_Buku [j]) < ord (Temp.Judul_Buku [j])) then begin ArrBook.T[i + 1] := Temp; stop := True; end else if (ord (ArrBook.T[i].Judul_Buku [j]) > ord (Temp.Judul_Buku [j])) then begin ArrBook.T[i + 1] := ArrBook.T[i]; ArrBook.T[i] := Temp; stop := True; end else begin j := j + 1; end; until stop; end; end; procedure RegLost (var array_hilang : tabHilang; var isSave : Boolean); {Prosedur untuk melaporkan buku yang hilang} {KAMUS LOKAL} var LB : kehilangan; {ALGORITMA} begin writeln(''); write ('Masukkan id buku: '); readln (LB.ID_Buku_Hilang); write ('Masukkan judul buku: '); readln (LB.Username); write ('Masukkan tanggal pelaporan: '); readln (LB.Tanggal_Laporan); writeln (); array_hilang.Neff := array_hilang.Neff + 1; array_hilang.T[ array_hilang.Neff ].ID_Buku_Hilang := LB.ID_Buku_Hilang; array_hilang.T[ array_hilang.Neff ].Username := LB.Username; array_hilang.T[ array_hilang.Neff ].Tanggal_Laporan := LB.Tanggal_Laporan; writeln ('Laporan berhasil diterima'); writeln(''); isSave := False; end; procedure SeeLost (var array_hilang : tabHilang; var active_user : tuser); {Prosedur untuk melihat data buku yang hilang} {KAMUS LOKAL} var i : integer; {ALGORITMA} begin if(active_user.role = 'pengunjung') then begin writeln(''); writeln('Fitur ini hanya dapat diakses oleh admin. Kontak admin terdekat.'); writeln('') end else begin writeln(''); if array_hilang.Neff > 0 then begin writeln ('Buku yang hilang :'); for i := 1 to array_hilang.Neff do begin writeln (array_hilang.T[i].ID_Buku_Hilang, ' | ', array_hilang.T[i].Username, ' | ', array_hilang.T[i].Tanggal_Laporan); end; end else begin writeln ('Tidak ada buku hilang.') end; writeln(''); end; end; procedure AddBook (var array_buku : tabBuku; var active_user : tuser; var isSave : boolean); {Menambahkan buku baru} {KAMUS LOKAL} var NB : buku; {New Book} {ALGORITMA} begin if(active_user.role = 'pengunjung') then begin writeln(''); writeln('Fitur ini hanya dapat diakses oleh admin. Kontak admin terdekat.'); writeln(''); end else begin writeln(''); writeln ('Masukkan informasi buku yang ditambahkan:'); write ('Masukkan id buku: '); readln (NB.ID_Buku); write ('Masukkan judul buku: '); readln (NB.Judul_Buku); write ('Masukkan pengarang buku: '); readln (NB.Author); write ('Masukkan jumlah buku: '); readln (NB.Jumlah_Buku); write ('Masukkan tahun terbit buku: '); readln (NB.Tahun_Penerbit); write ('Masukkan kategori buku: '); readln (NB.kategori); writeln (); array_buku.Neff := array_buku.Neff + 1; array_buku.T[ array_buku.Neff ].ID_Buku := NB.ID_Buku; array_buku.T[ array_buku.Neff ].Judul_Buku := NB.Judul_Buku; array_buku.T[ array_buku.Neff ].Jumlah_Buku := NB.Jumlah_Buku; array_buku.T[ array_buku.Neff ].Author := NB.Author; array_buku.T[ array_buku.Neff ].Tahun_Penerbit := NB.Tahun_Penerbit; array_buku.T[ array_buku.Neff ].Kategori := NB.Kategori; writeln ('Buku berhasil ditambahkan ke dalam sistem'); writeln (''); SortArrBook(array_buku); isSave := False; end; end; procedure AddJumlahBuku (var array_buku : tabBuku; var active_user : tuser; var isSave : boolean); {Menambahkan jumlah buku} {KAMUS LOKAL} var IdAdd, NAdd : integer; {ALGORITMA} begin if(active_user.role = 'pengunjung') then begin writeln(''); writeln('Fitur ini hanya dapat diakses oleh admin. Kontak admin terdekat.'); writeln(''); end else begin writeln(''); write ('Masukkan ID Buku: '); readln (IdAdd); write ('Masukkan jumlah buku yang ditambahkan: '); readln (NAdd); writeln (); array_buku.T[FoundBookIdIdx (IdAdd, array_buku)].Jumlah_Buku := array_buku.T[FoundBookIdIdx (IdAdd, array_buku)].Jumlah_Buku + NAdd; writeln ('Pembaharuan jumlah buku berhasil dilakukan, total buku ', array_buku .T[FoundBookIdIdx (IdAdd, array_buku)].Judul_Buku, ' di perpustakaan menjadi ', array_buku.T[FoundBookIdIdx (IdAdd, array_buku)].Jumlah_Buku); writeln(''); isSave := False; end; end; end.
unit untLogger; interface uses Windows, Forms, SysUtils, Variants, Classes, CnDebug; var MutexHandle: THandle; TraceEnable: Boolean; CnDebugEnable: Boolean; LogFileName: string; CriticalSection: TRTLCriticalSection; //Trace║»╩ř procedure InitLogger(IsTraceEnable:Boolean = False; IsCnDebugEnable: Boolean = False; IsAppendMode:Boolean = False); procedure AddLog(const str: string); procedure TraceErr(const Msg: string); overload; procedure TraceErr(const AFormat: string; Args: array of const); overload; procedure TraceMsg(const Msg: string); overload; procedure TraceMsg(const AFormat: string; Args: array of const); overload; implementation function GetCurrentUserName: string; const cnMaxUserNameLen = 254; var sUserName: string; dwUserNameLen: Cardinal; begin dwUserNameLen := cnMaxUserNameLen - 1; SetLength(sUserName, cnMaxUserNameLen); GetUserName(Pchar(sUserName), dwUserNameLen); SetLength(sUserName, dwUserNameLen - 1); Result := sUserName; end; procedure InitLogger(IsTraceEnable:Boolean = False; IsCnDebugEnable: Boolean = False; IsAppendMode:Boolean = False); var LogFile: TextFile; begin TraceEnable := IsTraceEnable; CnDebugEnable := IsCnDebugEnable; if TraceEnable then begin LogFileName := StringReplace(Application.ExeName, '.exe', '.' + GetCurrentUserName + '.log', [rfReplaceAll]); try AssignFile(LogFile, LogFileName); if (FileExists(LogFileName)) and IsAppendMode then Append(LogFile) else Rewrite(LogFile); Writeln(LogFile, Format('[%s] Logon user = %s', [DateTimeToStr(Now), GetCurrentUserName])); finally CloseFile(LogFile); end; end; end; procedure AddLog(const str: string); var LogFile: TextFile; begin EnterCriticalSection(CriticalSection); try AssignFile(LogFile, LogFileName); Append(LogFile); Writeln(LogFile, str); finally LeaveCriticalSection(CriticalSection); CloseFile(LogFile); end; end; procedure TraceErr(const Msg: string); begin if TraceEnable then //hLog.Add(Format('[%s] ERROR: %s', [DateTimeToStr(Now), Msg])); AddLog(Format('[%s] ERROR: %s', [DateTimeToStr(Now), Msg])); if CnDebugEnable then CnDebugger.TraceMsg('ERROR: ' + Msg); end; procedure TraceErr(const AFormat: string; Args: array of const); begin if TraceEnable then AddLog(Format('[%s] ERROR: ', [DateTimeToStr(Now)]) + Format(AFormat, Args)); if CnDebugEnable then CnDebugger.TraceMsg(Format('ERROR: %s', [Format(AFormat, Args)])); end; procedure TraceMsg(const Msg: string); begin if TraceEnable then //hLog.Add(Format('[%s] ', [DateTimeToStr(Now)]) + Msg); AddLog(Format('[%s] ', [DateTimeToStr(Now)]) + Msg); if CnDebugEnable then CnDebugger.TraceMsg(Msg); end; procedure TraceMsg(const AFormat: string; Args: array of const); begin if TraceEnable then //hLog.Add(Format('[%s] ', [DateTimeToStr(Now)]) + Format(AFormat, Args)); AddLog(Format('[%s] ', [DateTimeToStr(Now)]) + Format(AFormat, Args)); if CnDebugEnable then CnDebugger.TraceFmt(AFormat, Args); end; initialization InitializeCriticalSection(CriticalSection); finalization DeleteCriticalSection(CriticalSection); end.
unit AlertaDeuda; interface uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls, ExtCtrls, Mask, JvExMask, JvSpin, JvExStdCtrls, JvEdit, JvValidateEdit, IniFiles; type TAlertaDeudaDlg = class(TForm) OKBtn: TButton; CancelBtn: TButton; Bevel1: TBevel; cbAntiguedad: TCheckBox; cbSaldo: TCheckBox; cbCredito: TCheckBox; Label1: TLabel; jvDias: TJvSpinEdit; jvSaldo: TJvValidateEdit; Label2: TLabel; procedure FormCreate(Sender: TObject); procedure OKBtnClick(Sender: TObject); private { Private declarations } FIni: TIniFile; public { Public declarations } end; var AlertaDeudaDlg: TAlertaDeudaDlg; implementation {$R *.dfm} procedure TAlertaDeudaDlg.FormCreate(Sender: TObject); begin FIni := TIniFile.create( ExtractFilePath( Application.ExeName ) + 'varios.ini' ); jvDias.Value := FIni.ReadInteger( 'DEUDA', 'DIAS', 90 ); cbAntiguedad.Checked := FIni.ReadBool( 'DEUDA', 'ANTIGUEDAD', true ); jvSaldo.Value := FIni.ReadFloat( 'DEUDA', 'SALDO', 5000 ); cbSaldo.Checked := FIni.ReadBool( 'DEUDA', 'SALDOENABLED', false ); cbCredito.Checked := FIni.ReadBool( 'DEUDA', 'CREDITO', false ); FIni.Free; end; procedure TAlertaDeudaDlg.OKBtnClick(Sender: TObject); begin FIni := TIniFile.create( ExtractFilePath( Application.ExeName ) + 'varios.ini' ); FIni.WriteInteger( 'DEUDA', 'DIAS', jvDias.AsInteger ); FIni.WriteBool( 'DEUDA', 'ANTIGUEDAD', cbAntiguedad.checked ); FIni.WriteFloat( 'DEUDA', 'SALDO', jvSaldo.value ); FIni.WriteBool( 'DEUDA', 'SALDOENABLED', cbSaldo.checked ); FIni.WriteBool( 'DEUDA', 'CREDITO', cbCredito.checked ); FIni.Free; end; end.
unit Unit3; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TForm3 = class(TForm) Button1: TButton; Edit1: TEdit; Button2: TButton; ListBox1: TListBox; Edit2: TEdit; Button3: TButton; ListBox2: TListBox; Button4: TButton; Button5: TButton; Button6: TButton; ListBox3: TListBox; Label1: TLabel; Label2: TLabel; procedure Button1Click(Sender: TObject); procedure ListBox1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure Button5Click(Sender: TObject); procedure Button6Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form3: TForm3; implementation {$R *.dfm} uses System.Classes.helper, System.TypInfo; procedure TForm3.Button1Click(Sender: TObject); begin Button1.GetPropertiesList( ListBox1.Items, [mvPublished] ); // pega uma lista de properiedades do Button1 edit2.Text := Button1.Properties['Caption'].AsString; // pega o valor da propriedade caption Label1.Caption := intToStr( button1.PropertyCount ); end; procedure TForm3.Button2Click(Sender: TObject); begin button1.Properties[ 'Caption' ] := edit2.Text; // altera a proprieda do Caption end; procedure TForm3.Button3Click(Sender: TObject); begin button1.GetFieldsList( ListBox2.Items, [mvPrivate,mvPublic] ); label2.Caption := IntToStr( Button1.FieldsCount ); end; procedure TForm3.Button4Click(Sender: TObject); begin button1.InvokeMethod('Click',[]); // executa Click do button1 end; procedure TForm3.Button5Click(Sender: TObject); begin if button1.Properties['xxxx'].IsEmpty then showmessage('não existe a propriedade'); end; procedure TForm3.Button6Click(Sender: TObject); begin button1.GetMethodsList( ListBox3.items ); end; procedure TForm3.ListBox1Click(Sender: TObject); begin edit1.Text := ListBox1.Items[ ListBox1.ItemIndex ]; end; end.
unit TestFramework.DataValidators.TestTStringDataValidator; interface uses TestFramework, System.SysUtils, System.Variants, Interfaces.IDataValidator, DataValidators.TStringDataValidator; type TestTStringDataValidator = class(TTestCase) strict private FStringDataValidator: IDataValidator; public procedure SetUp; override; procedure TearDown; override; published procedure TestParse_String_Valid; procedure TestParse_String_Invalid; end; implementation procedure TestTStringDataValidator.SetUp; begin FStringDataValidator := TStringDataValidator.Create; end; procedure TestTStringDataValidator.TearDown; begin end; procedure TestTStringDataValidator.TestParse_String_Invalid; var ReturnValue: Boolean; AValue: Variant; begin AValue := 1234; ReturnValue := FStringDataValidator.Parse(AValue); Check(ReturnValue = False); end; procedure TestTStringDataValidator.TestParse_String_Valid; var ReturnValue: Boolean; AValue: Variant; begin AValue := 'my string for testing'; ReturnValue := FStringDataValidator.Parse(AValue); Check(ReturnValue = True); end; initialization // Register any test cases with the test runner RegisterTest(TestTStringDataValidator.Suite); end.
{$I OVC.INC} {$B-} {Complete Boolean Evaluation} {$I+} {Input/Output-Checking} {$P+} {Open Parameters} {$T-} {Typed @ Operator} {$W-} {Windows Stack Frame} {$X+} {Extended Syntax} {$IFNDEF Win32} {$G+} {286 Instructions} {$N+} {Numeric Coprocessor} {$C MOVEABLE,DEMANDLOAD,DISCARDABLE} {$ENDIF} {*********************************************************} {* OVCHELP.PAS 2.17 *} {* Copyright (c) 1995-98 TurboPower Software Co *} {* All rights reserved. *} {*********************************************************} unit OvcHelp; {-Help index definitions} interface uses {$IFDEF Win32} Windows, {$ELSE} WinTypes, WinProcs, {$ENDIF} IniFiles, SysUtils, OvcData; const {$IFDEF Win32} {$IFDEF VER93} HelpFileName = 'ORPHBCB.HLP'; {$ELSE} HelpFileName = 'ORPH32.HLP'; {$ENDIF} {$ELSE} HelpFileName = 'ORPH16.HLP'; {$ENDIF} {help offset} hcBase = 5000; {help context id's} hcCommandProcessor = hcBase + 0; {command processor property editor} hcEntryFieldRange = hcBase + 10; {entry field range property editor} hcSimpleFieldMask = hcBase + 20; {simple field mask property editor} hcPictureFieldMask = hcBase + 30; {picture field mask property editor} hcNumericFieldMask = hcBase + 40; {numeric field mask property editor} hcNotebookPage = hcBase + 50; {notebook page property editor} hcNotebookPageInfo = hcNotebookPage; {notebook page info property editor} hcTransfer = hcBase + 70; {transfer component editor} hcArrayEditorRange = hcEntryFieldRange; {array editor range property editor} hcRowsEditor = hcBase + 80; {table rows property editor} hcColumnsEditor = hcBase + 90; {table columns property editor} hcDbColumnsEditor = hcBase + 100; {data aware table columns property editor} procedure ShowHelpContext(HC : LongInt); {-display help} implementation {$IFDEF TRIALRUN} uses OrTrial; {$I ORTRIALF.INC} {$ENDIF} procedure ShowHelpContext(HC : LongInt); var S : string; Ini : TIniFile; Buf : array[0..255] of AnsiChar; begin S := ''; {build help file path} Ini := TIniFile.Create('MULTIHLP.INI'); try S := Ini.ReadString('Index Path', HelpFileName, ''); finally Ini.Free; end; if S > '' then begin if S[Length(S)] <> '\' then S := S + '\' + HelpFileName else S := S + HelpFileName; end else S := HelpFileName; StrPCopy(Buf, S); WinHelp(0, Buf, HELP_CONTEXT, HC); end; end.
unit tfwDebugService; // Модуль: "w:\common\components\rtl\Garant\ScriptEngine\tfwDebugService.pas" // Стереотип: "Service" // Элемент модели: "TtfwDebugService" MUID: (56F557030356) {$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc} interface {$If NOT Defined(NoScripts)} uses l3IntfUses , l3ProtoObject , tfwScriptingInterfaces ; (* MtfwDebugService = interface {* Контракт сервиса TtfwDebugService } function DebugScriptCaller: ItfwScriptCaller; end;//MtfwDebugService *) type ItfwDebugService = interface {* Интерфейс сервиса TtfwDebugService } function DebugScriptCaller: ItfwScriptCaller; end;//ItfwDebugService TtfwDebugService = {final} class(Tl3ProtoObject) private f_Alien: ItfwDebugService; {* Внешняя реализация сервиса ItfwDebugService } protected procedure pm_SetAlien(const aValue: ItfwDebugService); procedure ClearFields; override; public function DebugScriptCaller: ItfwScriptCaller; class function Instance: TtfwDebugService; {* Метод получения экземпляра синглетона TtfwDebugService } class function Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } public property Alien: ItfwDebugService write pm_SetAlien; {* Внешняя реализация сервиса ItfwDebugService } end;//TtfwDebugService {$IfEnd} // NOT Defined(NoScripts) implementation {$If NOT Defined(NoScripts)} uses l3ImplUses , SysUtils , l3Base //#UC START# *56F557030356impl_uses* //#UC END# *56F557030356impl_uses* ; var g_TtfwDebugService: TtfwDebugService = nil; {* Экземпляр синглетона TtfwDebugService } procedure TtfwDebugServiceFree; {* Метод освобождения экземпляра синглетона TtfwDebugService } begin l3Free(g_TtfwDebugService); end;//TtfwDebugServiceFree procedure TtfwDebugService.pm_SetAlien(const aValue: ItfwDebugService); begin Assert((f_Alien = nil) OR (aValue = nil)); f_Alien := aValue; end;//TtfwDebugService.pm_SetAlien function TtfwDebugService.DebugScriptCaller: ItfwScriptCaller; //#UC START# *56F557410186_56F557030356_var* //#UC END# *56F557410186_56F557030356_var* begin //#UC START# *56F557410186_56F557030356_impl* if (f_Alien <> nil) then Result := f_Alien.DebugScriptCaller else Result := nil; //#UC END# *56F557410186_56F557030356_impl* end;//TtfwDebugService.DebugScriptCaller class function TtfwDebugService.Instance: TtfwDebugService; {* Метод получения экземпляра синглетона TtfwDebugService } begin if (g_TtfwDebugService = nil) then begin l3System.AddExitProc(TtfwDebugServiceFree); g_TtfwDebugService := Create; end; Result := g_TtfwDebugService; end;//TtfwDebugService.Instance class function TtfwDebugService.Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } begin Result := g_TtfwDebugService <> nil; end;//TtfwDebugService.Exists procedure TtfwDebugService.ClearFields; begin Alien := nil; inherited; end;//TtfwDebugService.ClearFields {$IfEnd} // NOT Defined(NoScripts) end.
// Filename : SAXWriter.pas // Version : 1.1 (Delphi) // Date : July 4, 2003 // Author : Jeff Rafter // Details : http://xml.defined.net/SAX/aelfred2 // License : Please read License.txt unit SAXWriter; // "!!" // "(*..*)" // Canonical support is very very bad!!!! interface uses Classes, SysUtils, SAX, SAXHelpers, SAXExt; type TSAXWriter = class(TXMLFilterImpl) private canonical : Boolean; started : Boolean; trimOutput : Boolean; encoding : SAXString; encodingType : Byte; isRoot : Boolean; inCDATA : Boolean; indent : Integer; state : TList; prefixMappings : SAXString; wantIndent: Boolean; wrapAttributes: Boolean; protected output : TStream; function sortAttributes(atts : IAttributes) : IAttributes; public constructor Create(); reintroduce; overload; constructor Create(const canonical : Boolean); reintroduce; overload; constructor Create(const encoding : SAXString; const canonical : Boolean); reintroduce; overload; destructor Destroy(); override; procedure write(const value : SAXString); procedure writecontent(const value : SAXString); procedure writeln(); procedure flush(); function normalize(s : SAXString) : SAXString; // Handlers function resolveEntity(const publicId, systemId : SAXString) : IInputSource; override; procedure notationDecl(const name, publicId, systemId : SAXString); override; procedure unparsedEntityDecl(const name, publicId, systemId, notationName : SAXString); override; procedure setDocumentLocator(const locator: ILocator); override; procedure startDocument(); override; procedure endDocument(); override; procedure startPrefixMapping(const prefix, uri : SAXString); override; procedure endPrefixMapping(const prefix : SAXString); override; procedure startElement(const namespaceURI, localName, qName: SAXString; const atts: IAttributes); override; procedure endElement(const namespaceUri, localName, qName: SAXString); override; procedure characters(const ch : SAXString); override; procedure ignorableWhitespace(const ch : SAXString); override; procedure processingInstruction(const target, data : SAXString); override; procedure skippedEntity(const name : SAXString); override; procedure warning(const e : ISAXParseError); override; procedure error(const e : ISAXParseError); override; procedure fatalError(const e : ISAXParseError); override; // Ext handler procedure startCDATA; procedure endCDATA; // Setters procedure setEncoding(const encoding : SAXString); procedure setCanonical(const canonical : Boolean); procedure setOutput(const output : TStream); procedure setTrimOutput(const trimOutput : Boolean); procedure setWantIndent(const wantIndent : Boolean); procedure setWrapAttributes(const wrapAttributes : Boolean); end; TSAXWriterEx = class(TSAXWriter) public procedure startElement(const tag : SAXString); reintroduce; overload; procedure startElement(const tag : SAXString; const atts : IAttributes); reintroduce; overload; procedure endElement(const tag : SAXString); reintroduce; overload; procedure element(const tag, content : SAXString); overload; procedure element(const tag, content : SAXString; const atts : IAttributes); overload; end; implementation uses SAXDriver, Windows; const UTF16_BOM : Integer = $FEFF; ENCODING_UTF8 = 0; ENCODING_UTF16 = 1; ENCODING_OTHER = 2; // All other encodings treated as 8 bit! { TSAXWriter } constructor TSAXWriter.Create(); begin inherited Create; Self.canonical:= false; Self.output:= nil; Self.trimOutput:= false; Self.inCDATA:= false; if (canonical) then begin Self.wantIndent:= false; Self.wrapAttributes:= false; end else begin Self.wantIndent:= true; Self.wrapAttributes:= true; end; state:= TList.Create(); end; constructor TSAXWriter.Create(const canonical: Boolean); begin inherited Create; Self.canonical:= canonical; Self.output:= nil; Self.trimOutput:= false; Self.inCDATA:= false; if (canonical) then begin Self.wantIndent:= false; Self.wrapAttributes:= false; end else begin Self.wantIndent:= true; Self.wrapAttributes:= true; end; state:= TList.Create(); end; constructor TSAXWriter.Create(const encoding: SAXString; const canonical: Boolean); begin inherited Create; if (encoding = '') then {$IFDEF SAX_WIDESTRINGS} Self.encoding:= 'UTF-16' {$ELSE} Self.encoding:= 'UTF-8' {$ENDIF} else Self.encoding:= encoding; Self.canonical:= canonical; Self.output:= nil; Self.trimOutput:= false; Self.inCDATA:= false; if (canonical) then begin Self.wantIndent:= false; Self.wrapAttributes:= false; end else begin Self.wantIndent:= true; Self.wrapAttributes:= true; end; state:= TList.Create(); end; destructor TSAXWriter.Destroy; begin state.Free; inherited; end; procedure TSAXWriter.processingInstruction(const target, data: SAXString); begin inherited; if (not started) then begin started:= true; write('>'); end; write('<?'); write(target); if (data <> '') then begin write(' '); write(data); end; write('?>'); flush(); end; procedure TSAXWriter.startDocument; begin inherited; state.clear; indent:= 0; isRoot:= true; started:= true; {$IFDEF SAX_WIDESTRINGS} if (encoding = '') or (AnsiSameText(encoding, 'UTF-16')) then encodingType:= ENCODING_UTF16 else if (AnsiSameText(encoding, 'UTF-8')) then encodingType:= ENCODING_UTF8 else encodingType:= ENCODING_OTHER; {$ELSE} if (encoding = '') or (AnsiSameText(encoding, 'UTF-8')) then encodingType:= ENCODING_UTF8 else if (AnsiSameText(encoding, 'UTF-16')) then encodingType:= ENCODING_UTF16 else encodingType:= ENCODING_OTHER; {$ENDIF} // Write the BOM in all cases? if (encodingType = ENCODING_UTF16) then write(SAXChar(UTF16_BOM)); // Write the encoding if (not canonical) then begin write('<?xml version="1.0" encoding="'); if (encoding <> '') then write(encoding) else {$IFDEF SAX_WIDESTRINGS} write('UTF-16'); {$ELSE} write('UTF-8'); {$ENDIF} write('"?>'); writeln(); flush(); end; end; procedure TSAXWriter.startPrefixMapping(const prefix, uri: SAXString); var prefixMapping : SAXString; i : Integer; begin inherited; if (prefix <> '') then prefixMapping:= 'xmlns:' + prefix + '="' + uri + '"' else prefixMapping:= 'xmlns="' + uri + '"'; if (wrapAttributes) then begin prefixMappings:= prefixMappings + SAXChar(#13) + SAXChar(#10); for i:= 1 to Indent*2 do prefixMappings:= prefixMappings + ' '; prefixMappings:= prefixMappings + ' ' + prefixMapping; end else prefixMappings:= prefixMappings + ' ' + prefixMapping; end; procedure TSAXWriter.startElement(const namespaceURI, localName, qName: SAXString; const atts: IAttributes); var len, i : Integer; sortedAtts : IAttributes; begin inherited; if (not started) then begin started:= true; write('>'); end; if (not isRoot) then begin if (Boolean(state[state.Count-1]) = false) then begin writeln(); end; end; Inc(Indent); state.Add(Pointer(false)); isRoot:= false; write('<'); write(qName); write(prefixMappings); if (atts <> nil) then begin sortedAtts:= sortAttributes(atts); len:= sortedAtts.getLength(); for i:= 0 to len-1 do begin if ((i > 0) or (prefixMappings <> '')) and (wrapAttributes) then begin writeln(); end else write(' '); write(sortedAtts.getQName(i)); write('="'); write(normalize(sortedAtts.getValue(i))); write('"'); end; end; prefixMappings:= ''; started:= false; flush(); end; procedure TSAXWriter.characters(const ch : SAXString); var n : SAXString; begin if (not inCDATA) then begin n:= normalize(ch); if (n = '') then Exit; writecontent(n); end else writecontent(ch); inherited; end; procedure TSAXWriter.endElement(const namespaceURI, localName, qName: SAXString); begin Dec(indent); try // write an empty tag if (not started) then begin started:= true; write('/>'); Exit; end; // Write on a new line if (not Boolean(state[state.Count-1])) then begin writeln(); end; write('</'); write(qName); write('>'); flush(); finally state.Delete(state.Count-1); end; inherited; end; procedure TSAXWriter.ignorableWhitespace(const ch : SAXString); begin if (not wantIndent) then characters(ch); inherited; end; procedure TSAXWriter.warning(const e: ISAXParseError); begin inherited; raise ESAXParseException.Create(e); end; procedure TSAXWriter.error(const e: ISAXParseError); begin inherited; raise ESAXParseException.Create(e); end; procedure TSAXWriter.fatalError(const e: ISAXParseError); begin inherited; raise ESAXParseException.Create(e); end; procedure TSAXWriter.startCDATA; begin if (not started) then begin started:= true; write('>'); end; state[state.Count-1]:= Pointer(true); write('<![CDATA['); flush(); inCDATA:= True; inherited; end; procedure TSAXWriter.endCDATA; begin inCDATA:= False; write(']]>'); flush(); inherited; end; function TSAXWriter.normalize(s: SAXString): SAXString; var str : SAXString; len, i : Integer; ch : SAXChar; begin str:= ''; if (trimOutput) then s:= Trim(s); len:= Length(s); for i:= 1 to len do begin ch:= s[i]; case (ch) of '<' : begin str:= str + '&lt;'; end; '>' : begin str:= str + '&gt;'; end; '&' : begin str:= str + '&amp;'; end; '"' : begin str:= str + '&quot;'; end; #0 : begin // #0 is stipped out end; #10, #13 : begin //!! if (canonical) then //!! begin //!! str:= str + '&#'; //!! str:= str + IntToStr(Word(ch)); //!! str:= str + ';'; //!! end else str:= str + ch; end; // else, default append char else begin str:= str + ch; end; end; end; Result:= str; end; function TSAXWriter.sortAttributes(atts: IAttributes): IAttributes; begin // no op for now Result:= atts; end; procedure TSAXWriter.write(const value: SAXString); var len : Integer; {$IFDEF DELPHI6_UP} S : String; {$ENDIF} begin if (output = nil) then raise ESAXException.Create('output stream not set'); len:= Length(value); if (len > 0) then begin {$IFDEF DELPHI6_UP} { Special UTF-8 Encoding for Delphi 6 } if (encodingType = ENCODING_UTF8) then begin S:= UTF8Encode(Value); len:= Length(S); if (output.write(Pointer(S)^, len) <> len) then raise ESAXException.Create('unable to write output'); // Break out of function so we don't do "normal" output Exit; end; {$ENDIF} if (encodingType = ENCODING_UTF16) then begin len:= len * 2; if (output.write(Pointer(WideString(Value))^, len) <> len) then raise ESAXException.Create('unable to write output'); end else begin if (output.write(Pointer(String(Value))^, len) <> len) then raise ESAXException.Create('unable to write output'); end; end; end; procedure TSAXWriter.writeln; var s : SAXString; i : Integer; begin if (not wantIndent) then Exit; s:= '' + SAXChar(#13) + SAXChar(#10); write(s); for i:= 1 to Indent*2 do write(SAXChar(#32)); end; procedure TSAXWriter.writecontent(const value : SAXString); begin if (not started) then begin started:= true; write('>'); end; if (state.Count > 0) then state[state.Count-1]:= Pointer(true); write(value); flush(); end; procedure TSAXWriter.flush; begin // no op end; procedure TSAXWriter.setOutput(const output: TStream); begin Self.output:= output; end; procedure TSAXWriter.setCanonical(const canonical: Boolean); begin Self.canonical:= canonical; end; procedure TSAXWriter.setEncoding(const encoding: SAXString); begin Self.encoding:= encoding; end; procedure TSAXWriter.setTrimOutput(const trimOutput: Boolean); begin Self.trimOutput:= trimOutput; end; procedure TSAXWriter.setWantIndent(const wantIndent: Boolean); begin Self.wantIndent:= wantIndent; end; procedure TSAXWriter.setWrapAttributes(const wrapAttributes: Boolean); begin Self.wrapAttributes:= wrapAttributes; end; procedure TSAXWriter.endDocument; begin inherited; end; procedure TSAXWriter.endPrefixMapping(const prefix: SAXString); begin inherited; end; procedure TSAXWriter.notationDecl(const name, publicId, systemId: SAXString); begin inherited; end; function TSAXWriter.resolveEntity(const publicId, systemId: SAXString): IInputSource; begin Result:= inherited resolveEntity(publicId, systemId); end; procedure TSAXWriter.setDocumentLocator(const locator: ILocator); begin inherited; end; procedure TSAXWriter.skippedEntity(const name: SAXString); begin inherited; end; procedure TSAXWriter.unparsedEntityDecl(const name, publicId, systemId, notationName: SAXString); begin inherited; end; { TSAXWriterEx } procedure TSAXWriterEx.element(const tag, content: SAXString); begin startElement(tag); characters(content); endElement(tag); end; procedure TSAXWriterEx.element(const tag, content: SAXString; const atts: IAttributes); begin startElement(tag, atts); characters(content); endElement(tag); end; procedure TSAXWriterEx.endElement(const tag: SAXString); begin inherited endElement('', tag, tag); end; procedure TSAXWriterEx.startElement(const tag: SAXString); begin inherited startElement('', tag, tag, nil); end; procedure TSAXWriterEx.startElement(const tag: SAXString; const atts: IAttributes); begin inherited startElement('', tag, tag, atts); end; end.
{ TODO: + Редактор - добавление новых точек + Редактор - добавление точек посадки с множителем + GUI: Отображение точек посадки - GUI: отображение вектора скорости + Физическая реакция на включение топлива + Обработка столкновения корабля с луной: + В случае большой скорости или неправильного угла - проигрыш, перезапуск игры + В случае малой скорости и верного угла - "вы победили" + очки + флаг + Расчет очков на основе оставшегося топлива и множителя + Приближение/удаление в зависимости от скорости корабля и близости к поверхности + Изменение цвета скорости при достижении оптимального значения для посадки + При нуле топлива - не давать включать двигатель + При покидании границ уровня - проигрыш, перезапуск игры + Текстура луны + Флаг! } program lander; uses heaptrc, glr_core, glr_tween, glr_utils, uMain; var InitParams: TglrInitParams; begin SetHeapTraceOutput('heaptrace.log'); with InitParams do begin Width := 1000; Height := 600; X := 100; Y := 100; Caption := '«Lunar Lander» © Atari, 1979. Remake by perfect.daemon [tiny-glr ' + TINYGLR_VERSION + ']'; vSync := True; PackFilesPath := ''; UseDefaultAssets := True; end; Game := TGame.Create(); Core.Init(Game, InitParams); Core.Loop(); Core.DeInit(); Game.Free(); DumpHeap(); end.
unit LogFile; interface procedure SetLogFile( LogFileName : string ); procedure LogThis( MsgToLog : string ); implementation {$IFDEF Logs} uses SyncObjs; var LgFile : TextFile; Initialized : boolean = false; Lock : TCriticalSection; {$ENDIF} procedure SetLogFile( LogFileName : string ); begin {$IFDEF Logs} Lock.Acquire; AssignFile( LgFile, LogFileName ); try ReWrite( LgFile ); CloseFile( LgFile ); Initialized := true except Initialized := false end; Lock.Release {$ENDIF} end; procedure LogThis( MsgToLog : string ); begin {$IFDEF Logs} Lock.Acquire; if Initialized then begin try Append( LgFile ); try WriteLn( LgFile, MsgToLog ) finally CloseFile( LgFile ) end except Initialized := false end end; Lock.Release {$ENDIF} end; {$IFDEF Logs} initialization Lock := TCriticalSection.Create finalization Lock.Free {$ENDIF} end.
unit uLerXML; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, shellAPI, xmldom, XMLIntf, msxmldom, XMLDoc, uClienteVO, System.Generics.Collections, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.FileCtrl, uDM, uParametros, uGenericDAO, uCliente, uContatoVO, uCidadeVO, uClienteEmail, uClienteEmailVO, uProdutoVO, uContato, uClienteModuloVO; const QUEBRA_LINHA: string = #13 + #10; type TLerXML = class private FArquivo: string; procedure GravarModulo(listaModulo: TObjectList<TClienteModuloVO>); procedure GravarProduto(listaModulo: TObjectList<TClienteModuloVO>); procedure GravarCliente(Cliente: TClienteVO); procedure GravarClienteII(Cliente: TClienteVO); function GravarCidade(Cliente: TClienteVO): Integer; // procedure GravarEmails(Cliente: TClienteVO; listaEmail: TObjectList<TEmailVO>); procedure GravarModuloProduto(Cliente: TClienteVO); function LocalizarClienteCodigo(Codigo: integer; var ALatitude: string; var ALongitude: string): Integer; function LocalizarModuloCodigo(Codigo: integer): Integer; function LocalizarProdutoCodigo(Codigo: integer): Integer; function LocalizarUsuarioCodigo(Codigo: Integer): Integer; function LocalizarRevendaCodigo(Codigo: Integer): Integer; function LocalizarCidadeCodigo(Codigo: integer): Integer; procedure ExcluirEmail(IdCliente: integer); procedure ExcluirModuloProduto(IdCliente: integer); function ValidarArquivo(cliente: TClienteVO; listaModulo: TObjectList<TModuloVO>): Boolean; procedure GravarDados(cliente: TClienteVO; listaModulo: TObjectList<TModuloVO>); procedure CriarArquivoLogs(ListagemErros: TList<string>); procedure ExcluirArquivoXML; function SomenteNumeros(Valor: string): string; procedure LerArquivoXML; public procedure ListarArquivos(Formulario: TForm); procedure GravarDadosClientes(cliente: TClienteVO); end; implementation { TLerXML } uses uClassValidacao; procedure TLerXML.CriarArquivoLogs(ListagemErros: TList<string>); var Arq: Text; sCaminho: string; sArquivo: string; i: Integer; begin sCaminho := ExtractFilePath(FArquivo); sArquivo := ExtractFileName(FArquivo); sArquivo := Copy(sArquivo, 1, Length(sArquivo) -3); sArquivo := sArquivo + 'log'; if DirectoryExists(sCaminho) then begin try AssignFile(Arq, sCaminho + '\' + sArquivo); Rewrite(Arq); for I := 0 to ListagemErros.count -1 do Writeln(Arq, ListagemErros[i]); finally CloseFile(Arq); end; end; end; procedure TLerXML.ExcluirArquivoXML; begin if FileExists(FArquivo) then DeleteFile(FArquivo); end; procedure TLerXML.ExcluirEmail(IdCliente: integer); var // Qry: TFDQuery; obj: TClienteEmail; begin obj := TClienteEmail.Create; try obj.ExcluirRegistrosCliente(IdCliente); finally FreeAndNil(obj); end; // Qry := TFDQuery.Create(nil); // try // Qry.Connection := DM.Conexao; // Qry.SQL.Text := 'DELETE FROM Cliente_Email WHERE CliEm_Cliente = ' + IdCliente.ToString(); // Qry.ExecSQL(); // finally // FreeAndNil(Qry); // end; end; procedure TLerXML.ExcluirModuloProduto(IdCliente: integer); var Qry: TFDQuery; begin Qry := TFDQuery.Create(nil); try Qry.Connection := dm.Conexao; Qry.SQL.Text := 'DELETE FROM Cliente_Modulo WHERE CliMod_Cliente = ' + IdCliente.ToString(); Qry.ExecSQL(); finally FreeAndNil(Qry); end; end; procedure TLerXML.GravarCliente(Cliente: TClienteVO); var Qry: TFDQuery; sContato: string; sUsuario: string; sEndereco: string; IdRevenda: Integer; begin Qry := TFDQuery.Create(nil); try Qry.Connection := dm.Conexao; Qry.SQL.add(' EXECUTE Cliente_sp_IncluirAlterar'); Qry.SQL.add(' :Codigo,'); Qry.SQL.add(' :Nome,'); Qry.SQL.add(' :Fantasia,'); Qry.SQL.add(' :Dcto,'); Qry.SQL.add(' :Enquadramento,'); Qry.SQL.add(' :Endereco,'); Qry.SQL.add(' :Telefone,'); Qry.SQL.add(' :Contato,'); Qry.SQL.add(' :Revenda,'); Qry.SQL.add(' :Restricao,'); Qry.SQL.add(' :Ativo,'); Qry.SQL.add(' :Usuario'); if Cliente.Codigo > 0 then begin sEndereco := Cliente.Rua; if Cliente.Bairro <> '' then sEndereco := sEndereco + QUEBRA_LINHA + Cliente.Bairro; if Cliente.CEP <> '' then sEndereco := sEndereco + QUEBRA_LINHA + Cliente.CEP; if Cliente.Cidade <> '' then sEndereco := sEndereco + QUEBRA_LINHA + Cliente.Cidade; sContato := Cliente.ContatoFinanceiro; if Cliente.ContatoCompraVenda <> '' then sContato := sContato + QUEBRA_LINHA + Cliente.ContatoCompraVenda; sUsuario := ''; if Cliente.Usuario > 0 then sUsuario := IntToStr(LocalizarUsuarioCodigo(Cliente.Usuario)); IdRevenda := LocalizarRevendaCodigo(Cliente.Revenda); Qry.Close; Qry.ParamByName('Codigo').AsInteger := Cliente.Codigo; Qry.ParamByName('Nome').AsString := Cliente.RazaoSocial; Qry.ParamByName('Fantasia').AsString := Cliente.NomeFantasia; Qry.ParamByName('Dcto').AsString := Cliente.CNPJ; Qry.ParamByName('Enquadramento').AsString := Cliente.Enquadramento; Qry.ParamByName('Endereco').AsString := sEndereco; Qry.ParamByName('Telefone').AsString := Cliente.Telefone; Qry.ParamByName('Contato').AsString := sContato; Qry.ParamByName('Revenda').AsInteger := IdRevenda; Qry.ParamByName('Restricao').AsBoolean := (Cliente.PendenciaFinanceira = 'S'); Qry.ParamByName('Ativo').AsBoolean := (Cliente.Situacao = 'A'); Qry.ParamByName('Usuario').AsString := sUsuario; Qry.ExecSQL(); end; finally FreeAndNil(Qry); end; end; procedure TLerXML.GravarClienteII(Cliente: TClienteVO); var objCliente: TCliente; objClienteEmail: TClienteEmail; objClienteContato: TContato; sLatitude: string; sLongitude: string; begin sLongitude := ''; sLongitude := ''; Cliente.Id := LocalizarClienteCodigo(Cliente.Codigo, sLatitude, sLongitude); Cliente.Latitude := sLatitude; Cliente.Longitude := sLongitude; Cliente.IdRevenda := LocalizarRevendaCodigo(Cliente.Revenda); if Cliente.Usuario > 0 then Cliente.Usuario := LocalizarUsuarioCodigo(Cliente.Usuario); if Cliente.CidadeVO.Codigo > 0 then Cliente.IdCidade := GravarCidade(Cliente); cliente.Ativo := (Cliente.Situacao = 'A'); Cliente.Restricao := (Cliente.PendenciaFinanceira = 'S'); if Cliente.Id > 0 then begin objClienteEmail := TClienteEmail.Create; objClienteContato := TContato.Create; try objClienteEmail.ExcluirRegistrosCliente(Cliente.Id); objClienteContato.ExcluirPorCliente(Cliente.Id); finally FreeAndNil(objClienteEmail); FreeAndNil(objClienteContato); end; end; objCliente := TCliente.Create; try Cliente.Id := objCliente.Salvar(Cliente); finally FreeAndNil(objCliente); end; end; function TLerXML.GravarCidade(Cliente: TClienteVO): Integer; begin Cliente.CidadeVO.Id := LocalizarCidadeCodigo(Cliente.CidadeVO.Codigo); Result := TGenericDAO.Save<TCidadeVO>(Cliente.CidadeVO); end; procedure TLerXML.GravarDados(cliente: TClienteVO; listaModulo: TObjectList<TModuloVO>); begin // GravarModulo(listaModulo); // GravarProduto(listaModulo); // GravarCidade(cliente); // GravarClienteII(cliente); // GravarModuloProduto(Cliente, listaModulo); end; procedure TLerXML.GravarDadosClientes(cliente: TClienteVO); begin GravarModulo(cliente.ClienteModulo); GravarProduto(cliente.ClienteModulo); GravarCidade(cliente); GravarClienteII(cliente); GravarModuloProduto(Cliente); end; //procedure TLerXML.GravarEmails(Cliente: TClienteVO; listaEmail: TObjectList<TEmailVO>); //var // Qry: TFDQuery; // i: Integer; // iCont: Integer; //begin // if listaEmail = nil then // begin // ExcluirEmail(Cliente.Id); // Exit; // end; // // Qry := TFDQuery.Create(nil); // try // Qry.Connection := dm.Conexao; // Qry.SQL.Add('INSERT INTO Cliente_Email(CliEm_Cliente, CliEm_Email, CliEm_Notificar)'); // Qry.SQL.Add(' VALUES(:IdCliente, :Email, :Notificar)'); // // iCont := listaEmail.Count; // // if iCont > 0 then // ExcluirEmail(Cliente.Id); // // for I := 0 to iCont -1 do // begin // if I > 50 then // Break; // // if listaEmail[i].Email.Trim <> '' then // begin // if Cliente.Id > 0 then // begin // Qry.Close; // Qry.ParamByName('IdCliente').AsInteger := Cliente.Id; // Qry.ParamByName('Email').AsString := listaEmail[i].Email; // Qry.ParamByName('Notificar').AsBoolean := True; // Qry.ExecSQL(); // end; // end; // end; // finally // FreeAndNil(Qry); // end; //end; procedure TLerXML.GravarModulo(listaModulo: TObjectList<TClienteModuloVO>); var Qry: TFDQuery; // i: Integer; // iCont: Integer; Item: TClienteModuloVO; begin if listaModulo = nil then Exit; Qry := TFDQuery.Create(nil); try Qry.Connection := dm.Conexao; Qry.SQL.Text := 'EXECUTE Modulo_sp_IncluirAlterar :Codigo, :Nome'; for Item in listaModulo do begin if Item.Modulo.Codigo > 0 then begin Qry.Close; Qry.ParamByName('Codigo').AsInteger := Item.Modulo.Codigo; Qry.ParamByName('Nome').AsString := Item.Modulo.Nome; Qry.ExecSQL(); end; end; // iCont := listaModulo.Count; // for I := 0 to iCont -1 do // begin // if listaModulo[i].CodigoModulo > 0 then // begin // Qry.Close; // Qry.ParamByName('Codigo').AsInteger := listaModulo[i].CodigoModulo; // Qry.ParamByName('Nome').AsString := listaModulo[i].NomeModulo; // Qry.ExecSQL(); // end; // end; finally FreeAndNil(Qry); end; end; procedure TLerXML.GravarModuloProduto(Cliente: TClienteVO); var Qry: TFDQuery; // i: Integer; // iCont: Integer; // IdModulo: Integer; // IdProduto: Integer; Item: TClienteModuloVO; // ClienteModulo: TClienteModuloVO; // objClienteModulo: TClienteModulo; begin if Cliente.ClienteModulo = nil then begin ExcluirModuloProduto(Cliente.Id); Exit; end; // objClienteModulo := TClienteModulo.create; // try // for ClienteModulo in Cliente.ClienteModulo do // begin // ClienteModulo.IdCliente := Cliente.Id; // objClienteModulo.Salvar(ClienteModulo); // end; // finally // FreeAndNil(objClienteModulo); // end; Qry := TFDQuery.Create(nil); try Qry.Connection := dm.Conexao; Qry.SQL.Add('INSERT INTO Cliente_Modulo(CliMod_Modulo, CliMod_Produto, CliMod_Cliente)'); Qry.SQL.Add(' VALUES(:IdModulo, :IdProduto, :IdCliente)'); // iCont := Cliente.ClienteModulo.Count; if Cliente.ClienteModulo.Count > 0 then ExcluirModuloProduto(Cliente.Id); try for Item in Cliente.ClienteModulo do begin if (Item.Modulo.Codigo > 0) then begin if (Cliente.Id > 0) then begin Item.Modulo.Id := LocalizarModuloCodigo(Item.Modulo.Codigo); Item.Produto.Id := LocalizarProdutoCodigo(Item.Produto.Codigo); if (Item.Modulo.Id > 0) then begin Qry.Close; Qry.ParamByName('IdCliente').AsInteger := Cliente.Id; Qry.ParamByName('IdModulo').AsInteger := Item.Modulo.Id; if Item.Produto.Id > 0 then Qry.ParamByName('IdProduto').AsInteger := Item.Produto.Id else begin Qry.ParamByName('IdProduto').DataType := ftInteger; Qry.ParamByName('IdProduto').Value := null; end; Qry.ExecSQL(); end; end; end; end; except On E: Exception do begin raise Exception.Create(E.Message); end; end; finally FreeAndNil(Qry); end; // iCont := listaModulo.Count; // // try // for I := 0 to iCont -1 do // begin // if listaModulo[i].CodigoModulo > 0 then // begin // if Cliente.Id > 0 then // begin // // IdModulo := LocalizarModuloCodigo(listaModulo[i].CodigoModulo); // IdProduto := LocalizarProdutoCodigo(listaModulo[i].CodigoProduto); // // if (IdModulo > 0) then // begin // Qry.Close; // Qry.ParamByName('IdCliente').AsInteger := Cliente.Id; // Qry.ParamByName('IdModulo').AsInteger := IdModulo; // // if IdProduto > 0 then // Qry.ParamByName('IdProduto').AsInteger := IdProduto // else begin // Qry.ParamByName('IdProduto').DataType := ftInteger; // Qry.ParamByName('IdProduto').Value := null; // end; // Qry.ExecSQL(); // end; // end; // end; // end; // except // On E: Exception do // begin // raise Exception.Create(E.Message); // end; // end; // finally // FreeAndNil(Qry); // end; end; procedure TLerXML.GravarProduto(listaModulo: TObjectList<TClienteModuloVO>); var Qry: TFDQuery; // i: Integer; // iCont: Integer; Item: TClienteModuloVO; begin if listaModulo = nil then Exit; Qry := TFDQuery.Create(nil); try Qry.Connection := dm.Conexao; Qry.SQL.Text := 'EXECUTE Produto_sp_IncluirAlterar :Codigo, :Nome'; for Item in listaModulo do begin if Item.Produto.Codigo > 0 then begin Qry.Close; Qry.ParamByName('Codigo').AsInteger := Item.Produto.Codigo; Qry.ParamByName('Nome').AsString := Item.Produto.Nome; Qry.ExecSQL(); end; end; // iCont := listaModulo.Count; // for I := 0 to iCont -1 do // begin // if listaModulo[i].CodigoProduto > 0 then // begin // Qry.Close; // Qry.ParamByName('Codigo').AsInteger := listaModulo[i].CodigoProduto; // Qry.ParamByName('Nome').AsString := listaModulo[i].NomeProduto; // Qry.ExecSQL(); // end; // end; finally FreeAndNil(Qry); end; end; procedure TLerXML.LerArquivoXML(); var XMLDoc: IXMLDocument; nCliente, nPrincipal, nEmail, nModulo, nContato: IXMLNode; iContador, iCodigoProduto, iCodigoModulo: Integer; sEmail: string; sDocumento: string; sEnquadramento: string; ListaModulo: TObjectList<TModuloVO>; ClienteEmailVO: TClienteEmailVO; Modulo: TModuloVO; objEmail: TEmailVO; Cliente: TClienteVO; Contato: TContatoVO; sDiretorio: string; sArquivoXML: string; sArquivoLog: string; iPosicao: Integer; i: Integer; sNomeContato: string; bAchouEmail: Boolean; iCount: Integer; begin if not (FileExists(FArquivo)) then Exit; sDiretorio := ExtractFilePath(FArquivo); sArquivoXML := ExtractFileName(FArquivo); iPosicao := Pos('.', sArquivoXML); sArquivoLog := Copy(sArquivoXML, 1, iPosicao) + 'log'; if FileExists(sDiretorio + sArquivoLog) then Exit; XMLDoc := TXMLDocument.Create(nil); XMLDoc.Active := True; XMLDoc.LoadFromFile(FArquivo); // nCliente := XMLDoc.DocumentElement.ChildNodes.FindNode('Cliente'); //============================================================================== // dados do cliente //============================================================================== Cliente := TClienteVO.Create; try nPrincipal := XMLDoc.DocumentElement.ChildNodes.FindNode('Principal'); sDocumento := nPrincipal.ChildNodes['CNPJ'].Text; if sDocumento = '' then sDocumento := nPrincipal.ChildNodes['CPF'].Text; sEnquadramento := nPrincipal.ChildNodes['Enquadramento'].Text; if (sEnquadramento <> '01') and (sEnquadramento <> '02') and (sEnquadramento <> '03') then sEnquadramento := '00'; Cliente.Codigo := StrToIntDef(nPrincipal.ChildNodes['Codigo'].Text, 0); Cliente.RazaoSocial := nPrincipal.ChildNodes['Razao'].Text; Cliente.NomeFantasia := nPrincipal.ChildNodes['Fantasia'].Text; Cliente.CNPJ := sDocumento; Cliente.Enquadramento := sEnquadramento; Cliente.Rua := nPrincipal.ChildNodes['Rua'].Text; Cliente.Bairro := nPrincipal.ChildNodes['Bairro'].Text; Cliente.CEP := nPrincipal.ChildNodes['CEP'].Text; Cliente.Cidade := nPrincipal.ChildNodes['Cidade'].Text; Cliente.Telefone := nPrincipal.ChildNodes['Telefone'].Text; Cliente.ContatoFinanceiro := nPrincipal.ChildNodes['Contato_Financeiro'].Text; Cliente.ContatoCompraVenda := nPrincipal.ChildNodes['Contato_Compra_Venda'].Text; Cliente.Usuario := StrToIntDef(nPrincipal.ChildNodes['Consultor'].Text,0); Cliente.Revenda := StrToIntDef(nPrincipal.ChildNodes['Revenda'].Text,0); Cliente.PendenciaFinanceira := nPrincipal.ChildNodes['Pendencia_Fin'].Text; Cliente.Situacao := nPrincipal.ChildNodes['Situacao'].Text; //============================================================================== // Novos campos Cliente.Logradouro := Cliente.Rua; Cliente.Fone1 := nPrincipal.ChildNodes['Fone1'].Text; Cliente.Fone2 := nPrincipal.ChildNodes['Fone2'].Text; Cliente.Celular := nPrincipal.ChildNodes['Celular'].Text; Cliente.OutroTelefone := nPrincipal.ChildNodes['OutroFone'].Text; Cliente.ContatoFinanceiroFone := nPrincipal.ChildNodes['Contato_Financeiro_Fone'].Text; Cliente.ContatoCompraVendaFone:= nPrincipal.ChildNodes['Contato_Compra_Venda_Fone'].Text; Cliente.IE := nPrincipal.ChildNodes['IE'].Text; Cliente.RepresentanteLegal := nPrincipal.ChildNodes['Representante_Legal'].Text; Cliente.RepresentanteLegalCPF := nPrincipal.ChildNodes['Representante_Legal_CPF'].Text; Cliente.EmpresaVinculada := StrToIntDef(nPrincipal.ChildNodes['Empresa_Vinculada'].Text, 0); //============================================================================== // dados da cidade Cliente.CidadeVO.Codigo := StrToIntDef(nPrincipal.ChildNodes['Codigo_IBGE'].Text,0); Cliente.CidadeVO.Nome := nPrincipal.ChildNodes['Nome_Cidade'].Text; Cliente.CidadeVO.UF := nPrincipal.ChildNodes['UF'].Text; Cliente.CidadeVO.Ativo := true; //============================================================================== // dados dos emails nEmail := XMLDoc.DocumentElement.ChildNodes.FindNode('Registro_EMail'); if nEmail <> nil then begin iContador := 0; nEmail.ChildNodes.First; repeat if iContador = 0 then sEmail := nEmail.ChildNodes['Email'].Text else sEmail := nEmail.ChildNodes['Email' + iContador.ToString].Text; if trim(sEmail) = '' then break; ClienteEmailVO := TClienteEmailVO.Create; ClienteEmailVO.Id := 0; ClienteEmailVO.IdCliente := Cliente.Id; ClienteEmailVO.Email := sEmail; ClienteEmailVO.Notificar := True; if not Cliente.ClienteEmail.Contains(ClienteEmailVO) then Cliente.ClienteEmail.Add(ClienteEmailVO); if iContador >= 50 then break; inc(iContador); // nEmail := nEmail.NextSibling; until nEmail = nil; end; //============================================================================== // dados dos Módulos e Produtos nModulo := XMLDoc.DocumentElement.ChildNodes.FindNode('Registro_Modulo'); if nModulo <> nil then begin ListaModulo := TObjectList<TModuloVO>.Create(); iContador := 1; nModulo.ChildNodes.First; repeat iCodigoModulo := StrToIntDef(nModulo.ChildNodes['Cod_Grupo' + iContador.ToString].Text,0); iCodigoProduto := StrToIntDef(nModulo.ChildNodes['Cod_Produto' + iContador.ToString].Text,0); if (iCodigoModulo = 0) then Break; if iContador > 50 then Break; Modulo := TModuloVO.Create; Modulo.CodigoModulo := iCodigoModulo; Modulo.CodigoProduto := iCodigoProduto; Modulo.NomeModulo := nModulo.ChildNodes['Nome_Grupo' + iContador.ToString].Text; Modulo.NomeProduto := nModulo.ChildNodes['Nome_Produto' + iContador.ToString].Text; ListaModulo.Add(Modulo); Inc(iContador); // nModulo := nModulo.NextSibling; until nModulo = nil; end; //============================================================================== // Contatos nContato := XMLDoc.DocumentElement.ChildNodes.FindNode('Registro_Contato'); if nContato <> nil then begin iContador := 1; nContato.ChildNodes.First; repeat if iContador > 50 then Break; sNomeContato := nContato.ChildNodes['Contato_Nome' + iContador.ToString].Text; if Trim(sNomeContato) = '' then Break; Contato := TContatoVO.Create; Contato.Nome := nContato.ChildNodes['Contato_Nome' + iContador.ToString].Text; Contato.Fone1 := nContato.ChildNodes['Contato_Fone1' + iContador.ToString].Text; Contato.Fone2 := nContato.ChildNodes['Contato_Fone2' + iContador.ToString].Text; Contato.Departamento := nContato.ChildNodes['Contato_Depto' + iContador.ToString].Text; Contato.Email := nContato.ChildNodes['Contato_Email' + iContador.ToString].Text; Cliente.ListaContatoVO.Add(Contato); Inc(iContador); until nContato = nil; end; //============================================================================== // Validar e gravar dados if ValidarArquivo(Cliente, ListaModulo) then GravarDadosClientes(Cliente); // GravarDados(Cliente, ListaModulo); finally if Cliente <> nil then FreeAndNil(Cliente); if ListaModulo <> nil then FreeAndNil(ListaModulo); end; end; procedure TLerXML.ListarArquivos(Formulario: TForm); var Lista: TFileListBox; I: Integer; sDiretorio: string; Parametro: TParametros; Arq: TextFile; begin Parametro := TParametros.Create; try sDiretorio := Parametro.BuscarCaminhoImportacaoXML(); finally FreeAndNil(Parametro); end; if not DirectoryExists(sDiretorio) then Exit; Lista := TFileListBox.Create(nil); try try Lista.Parent := Formulario; Lista.Mask := '*.XML'; Lista.Directory := sDiretorio; for I := 0 to Lista.Count-1 do begin FArquivo := sDiretorio + '\' + Lista.Items[i]; LerArquivoXML(); end; except on E: Exception do begin AssignFile(Arq, sDiretorio + '\Erro.txt'); Rewrite(Arq); Writeln(Arq, 'Arq: ' + Lista.Items[i] + ' - ' + E.Message); CloseFile(Arq); end; end; finally FreeAndNil(Lista); end; end; function TLerXML.LocalizarCidadeCodigo(Codigo: integer): Integer; var Qry: TFDQuery; i: Integer; iCont: Integer; begin Qry := TFDQuery.Create(nil); try Qry.Connection := dm.Conexao; Qry.SQL.Text := 'SELECT Cid_Id FROM Cidade WHERE Cid_Codigo = ' + Codigo.ToString; Qry.Open(); Result := Qry.Fields[0].AsInteger; finally FreeAndNil(Qry); end; end; function TLerXML.LocalizarClienteCodigo(Codigo: integer; var ALatitude: string; var ALongitude: string): Integer; var Qry: TFDQuery; i: Integer; iCont: Integer; begin Qry := TFDQuery.Create(nil); try Qry.Connection := dm.Conexao; Qry.SQL.Text := 'SELECT Cli_Id, Cli_Latitude, Cli_Longitude FROM Cliente WHERE Cli_Codigo = ' + Codigo.ToString; Qry.Open(); ALatitude := Qry.Fields[1].AsString; ALongitude := Qry.Fields[2].AsString; Result := Qry.Fields[0].AsInteger; finally FreeAndNil(Qry); end; end; function TLerXML.LocalizarModuloCodigo(Codigo: integer): Integer; var Qry: TFDQuery; i: Integer; iCont: Integer; begin Qry := TFDQuery.Create(nil); try Qry.Connection := dm.Conexao; Qry.SQL.Text := 'SELECT Mod_Id FROM Modulo WHERE Mod_Codigo = ' + Codigo.ToString; Qry.Open(); Result := Qry.Fields[0].AsInteger; finally FreeAndNil(Qry); end; end; function TLerXML.LocalizarProdutoCodigo(Codigo: integer): Integer; var Qry: TFDQuery; i: Integer; iCont: Integer; begin Qry := TFDQuery.Create(nil); try Qry.Connection := dm.Conexao; Qry.SQL.Text := 'SELECT Prod_Id FROM Produto WHERE Prod_Codigo = ' + Codigo.ToString; Qry.Open(); Result := Qry.Fields[0].AsInteger; finally FreeAndNil(Qry); end; end; function TLerXML.LocalizarRevendaCodigo(Codigo: Integer): Integer; var Qry: TFDQuery; i: Integer; iCont: Integer; begin Qry := TFDQuery.Create(nil); try Qry.Connection := dm.Conexao; Qry.SQL.Text := 'SELECT Rev_Id FROM Revenda WHERE Rev_Codigo = ' + Codigo.ToString; Qry.Open(); Result := Qry.Fields[0].AsInteger; finally FreeAndNil(Qry); end; end; function TLerXML.LocalizarUsuarioCodigo(Codigo: Integer): Integer; var Qry: TFDQuery; i: Integer; iCont: Integer; begin Qry := TFDQuery.Create(nil); try Qry.Connection := dm.Conexao; Qry.SQL.Text := 'SELECT Usu_Id FROM Usuario WHERE Usu_Codigo = ' + Codigo.ToString; Qry.Open(); Result := Qry.Fields[0].AsInteger; finally FreeAndNil(Qry); end; end; function TLerXML.SomenteNumeros(Valor: string): string; var i: Integer; s: string; a: string; begin a := ''; for I := 1 to Length(Valor) do begin s := Copy(Valor, i, 1); if (s = '0') or (s = '1') or (s = '2') or (s = '3') or (s = '4') or (s = '5') or (s = '6') or (s = '7') or (s = '8') or (s = '9') then a := a + s; end; Result := a; end; function TLerXML.ValidarArquivo(cliente: TClienteVO; listaModulo: TObjectList<TModuloVO>): Boolean; var ListaErros: TList<string>; i: Integer; Id: Integer; sDocumento: string; begin ListaErros := TList<string>.Create; try if Cliente.Codigo = 0 then ListaErros.Add('Código Cliente......: - Não Informado'); if Cliente.RazaoSocial.Trim() = '' then ListaErros.Add('Razão Social........: - Não Informado'); if Cliente.CNPJ.Trim() = '' then ListaErros.Add('CNPJ/CPF............: - Não Informado'); if Cliente.Usuario > 0 then begin Id := LocalizarUsuarioCodigo(cliente.Usuario); if Id <= 0 then ListaErros.Add('Usuário.............: - Não Cadastrado'); end; if Cliente.Revenda = 0 then ListaErros.Add('Revenda.............: - Não Informado') else begin Id := LocalizarRevendaCodigo(cliente.Revenda); if Id = 0 then ListaErros.Add('Revenda.............: - Não Cadastrada'); end; if Cliente.PendenciaFinanceira.Trim() = '' then ListaErros.Add('Pendência Financeira: - Não Informado'); if Cliente.Situacao.Trim() = '' then ListaErros.Add('Situação............: - Não Informado'); sDocumento := SomenteNumeros(cliente.CNPJ); if Length(sDocumento) > 0 then begin try if Length(sDocumento) = 11 then TValidacao.ValidaCPF(sDocumento) else TValidacao.ValidaCNPJ(sDocumento); except ON E: Exception do begin ListaErros.Add('CNPJ/CPF............: - Inválido'); end; end; end; Result := True; if ListaErros.Count > 0 then begin CriarArquivoLogs(ListaErros); Result := False; end else ExcluirArquivoXML(); finally FreeAndNil(ListaErros); end; end; end.
unit uAgendamentoEmail; interface uses uDM, System.SysUtils, Data.DB, FireDAC.Comp.Client, uContaEmail, System.Generics.Collections; type TAgendamentoEmail = class private FLista: TList<string>; FListaCliente: TList<string>; function RetornarEmailConta_Email(IdUsuario: integer): string; procedure RetornarEmailClientes(AIdAgenda, AIdUsuario: Integer); procedure RetornarEmailSupervisor(AIdUsuario, AIdStatus: Integer); procedure RetornarEmailConsultor(AIdAgenda, AIdUsuario, AIdStatus: Integer); procedure RetornarEmailRevenda(AIdAgenda, AIdUsuario, AIdStatus: Integer); function EmailExiste(AEmail: string): Boolean; procedure Adicionar(AEmail: string); procedure AdicionarCliente(AEmail: string); public function RetornaEmails(AIdAgenda, AIdUsuario, AIdStatus: integer): string; function RetornaEmailCliente(AIdAgenda, AIdUsuario: integer): string; constructor create; destructor destroy; override; end; implementation { TVisitaEmail } uses uStatus, uDepartamento, uFuncoesServidor; procedure TAgendamentoEmail.Adicionar(AEmail: string); begin if not TFuncoes.EmailExisteNaLista(AEmail, FLista) then FLista.Add(AEmail); end; procedure TAgendamentoEmail.AdicionarCliente(AEmail: string); begin if not TFuncoes.EmailExisteNaLista(AEmail, FListaCliente) then FListaCliente.Add(AEmail); end; constructor TAgendamentoEmail.create; begin inherited create; FListaCliente := TList<string>.Create; FLista := TList<string>.Create; end; destructor TAgendamentoEmail.destroy; begin FreeAndNil(FLista); FreeAndNil(FListaCliente); inherited; end; function TAgendamentoEmail.EmailExiste(AEmail: string): Boolean; begin Result := TFuncoes.EmailExisteNaLista(AEmail, FLista); end; function TAgendamentoEmail.RetornaEmailCliente(AIdAgenda, AIdUsuario: integer): string; begin RetornarEmailClientes(AIdAgenda, AIdUsuario); Result := TFuncoes.RetornaListaEmail(FListaCliente); end; function TAgendamentoEmail.RetornaEmails(AIdAgenda, AIdUsuario, AIdStatus: integer): string; begin RetornarEmailSupervisor(AIdUsuario, AIdStatus); RetornarEmailConsultor(AIdAgenda, AIdUsuario, AIdStatus); RetornarEmailRevenda(AIdAgenda, AIdUsuario, AIdStatus); Result := TFuncoes.RetornaListaEmail(FLista); end; procedure TAgendamentoEmail.RetornarEmailClientes(AIdAgenda, AIdUsuario: Integer); var Qry: TFDQuery; sEmail: string; iContador: Integer; Status: TStatus; bNotificar: Boolean; idStatus: Integer; begin sEmail := RetornarEmailConta_Email(AIdUsuario); if Trim(sEmail) = '' then // se não tem conta email, exit Exit; Qry := TFDQuery.Create(nil); try Qry.Connection := dm.Conexao; Qry.SQL.Add(' SELECT'); Qry.SQL.Add(' Sta_Id'); Qry.SQL.Add(' FROM Agendamento'); Qry.SQL.Add(' INNER JOIN Cliente_Email ON Age_Cliente = CliEm_Cliente'); Qry.SQL.Add(' INNER JOIN Status ON Age_Status = Sta_Id'); Qry.SQL.Add(' WHERE Sta_NotificarCliente = 1'); Qry.SQL.Add(' AND Age_Id = ' + IntToStr(AIdAgenda)); Qry.Open(); if qry.FieldByName('Sta_Id').AsInteger = 0 then Exit; Qry.Close; Qry.SQL.Clear; Qry.SQL.Add(' SELECT'); Qry.SQL.Add(' CliEm_Email'); Qry.SQL.Add(' FROM Agendamento'); Qry.SQL.Add(' INNER JOIN Cliente_Email ON Age_Cliente = CliEm_Cliente'); Qry.SQL.Add(' INNER JOIN Status ON Age_Status = Sta_Id'); Qry.SQL.Add(' WHERE Sta_NotificarCliente = 1'); Qry.SQL.Add(' AND CliEm_Notificar = 1'); Qry.SQL.Add(' AND Age_Id = ' + IntToStr(AIdAgenda)); Qry.Open(); iContador := 0; if not Qry.IsEmpty then begin while not Qry.Eof do begin AdicionarCliente(Qry.FieldByName('CliEm_Email').AsString); Inc(iContador); Qry.Next; end; end; // se não tem no cliente, buscar no usuário logado if iContador = 0 then AdicionarCliente(sEmail); finally FreeAndNil(Qry); end; end; procedure TAgendamentoEmail.RetornarEmailConsultor(AIdAgenda, AIdUsuario, AIdStatus: Integer); var Qry: TFDQuery; sEmail: string; objStatus: TStatus; TemRegistro: Boolean; begin sEmail := RetornarEmailConta_Email(AIdUsuario); if Trim(sEmail) = '' then Exit; objStatus := TStatus.Create; try TemRegistro := objStatus.NotificarConsultor(AIdStatus); finally FreeAndNil(objStatus); end; Qry := TFDQuery.Create(nil); try if TemRegistro then begin Qry.Connection := DM.Conexao; Qry.SQL.Add(' SELECT'); Qry.SQL.Add(' Usu_Email'); Qry.SQL.Add(' FROM Agendamento'); Qry.SQL.Add(' INNER JOIN Cliente ON Age_Cliente = Cli_Id'); Qry.SQL.Add(' INNER JOIN Usuario ON Cli_Usuario = Usu_Id'); Qry.SQL.Add(' WHERE Age_Id = ' + IntToStr(AIdAgenda)); Qry.Open(); if not Qry.IsEmpty then Adicionar(Qry.FieldByName('usu_Email').AsString); end; finally FreeAndNil(Qry); end; end; function TAgendamentoEmail.RetornarEmailConta_Email(IdUsuario: integer): string; var ContaEmail: TContaEmail; begin ContaEmail := TContaEmail.Create; try Result := ContaEmail.RetornarEmail(IdUsuario); finally FreeAndNil(ContaEmail); end; end; procedure TAgendamentoEmail.RetornarEmailRevenda(AIdAgenda, AIdUsuario, AIdStatus: Integer); var Qry: TFDQuery; sEmail: string; objStatus: TStatus; TemRegistro: Boolean; begin sEmail := RetornarEmailConta_Email(AIdUsuario); if Trim(sEmail) = '' then Exit; objStatus := TStatus.Create; try TemRegistro := objStatus.NotificarRevenda(AIdStatus); finally FreeAndNil(objStatus); end; Qry := TFDQuery.Create(nil); try if TemRegistro then begin Qry.Connection := dm.Conexao; Qry.Close; Qry.SQL.Clear; Qry.SQL.Add(' SELECT'); Qry.SQL.Add(' RevEm_Email'); Qry.SQL.Add(' FROM Agendamento'); Qry.SQL.Add(' INNER JOIN Cliente On Age_Cliente = Cli_Id'); Qry.SQL.Add(' INNER JOIN Revenda ON Cli_Revenda = Rev_Id'); Qry.SQL.Add(' INNER JOIN Revenda_Email ON Rev_id = RevEm_Revenda'); Qry.SQL.Add(' WHERE Age_Id = ' + IntToStr(AIdAgenda)); Qry.Open(); while not Qry.Eof do begin Adicionar(Qry.Fields[0].AsString); Qry.Next; end; end; finally FreeAndNil(Qry); end; end; procedure TAgendamentoEmail.RetornarEmailSupervisor(AIdUsuario, AIdStatus: Integer); var sEmail: string; objStatus: TStatus; TemRegistro: Boolean; objDepartamento: TDepartamento; ListaEmail: TList<string>; begin sEmail := RetornarEmailConta_Email(AIdUsuario); if Trim(sEmail) = '' then // se não tem conta email, nao faz nada Exit; objStatus := TStatus.Create; try TemRegistro := objStatus.NotificarSupervisor(AIdStatus); finally FreeAndNil(objStatus); end; if TemRegistro then begin objDepartamento := TDepartamento.Create; try ListaEmail := objDepartamento.RetornarEmail(AIdUsuario); for sEmail in ListaEmail do Adicionar(sEmail); finally FreeAndNil(objDepartamento); FreeAndNil(ListaEmail); end; end; end; end.
unit MMO.Server; interface uses IdTCPServer, IdSchedulerOfThreadPool, IdContext, SysUtils, IdGlobal, IdComponent, MMO.ServerClient, MMO.PacketReader, MMO.ClientList, SyncObjs, MMO.Lock, MMO.PrivateServerClient, MMO.Types, MMO.ServerCreateOptions; type TTest = reference to procedure; TServer<ClientType> = class abstract private var m_clients: TClientList<ClientType>; var m_server: TIdTCPServer; var m_idSchedulerOfThreadPool: TIdSchedulerOfThreadPool; var m_maxPlayers: UInt16; var m_lock: TLock; procedure ServerOnConnect(AContext: TIdContext); procedure ServerOnDisconnect(AContext: TIdContext); procedure ServerOnExecute(AContext: TIdContext); procedure ServerOnException(AContext: TIdContext; AException: Exception); procedure ServerOnStatus(ASender: TObject; const AStatus: TIdStatus; const AStatusText: string); function GetClientByContext(AContext: TIdContext): TServerClient<ClientType>; procedure SetContextData(AContext: TIdContext; data: TObject); function GetContextData(AContext: TIdContext): TObject; procedure GuardAgainstInvalidOptions(const serverCreateOptions: TServerCreateOptions); protected procedure OnReceiveClientPacket(const client: TServerClient<ClientType>; const packetReader: TPacketReader); virtual; procedure OnClientCreate(const client: TServerClient<ClientType>); virtual; procedure OnClientDestroy(const client: TServerClient<ClientType>); virtual; procedure OnClientConnect(const client: TServerClient<ClientType>); virtual; procedure OnClientDisconnect(const client: TServerClient<ClientType>); virtual; procedure Start; public constructor Create(const serverCreateOptions: TServerCreateOptions); destructor Destroy; override; end; implementation uses IdTCPConnection; constructor TServer<ClientType>.Create(const serverCreateOptions: TServerCreateOptions); begin inherited Create; GuardAgainstInvalidOptions(serverCreateOptions); m_clients := TClientList<ClientType>.Create; m_maxPlayers := serverCreateOptions.MaxPlayers; m_lock := TLock.Create(serverCreateOptions.ThreadSafe); m_idSchedulerOfThreadPool := TIdSchedulerOfThreadPool.Create(nil); m_idSchedulerOfThreadPool.MaxThreads := m_maxPlayers + 1; m_idSchedulerOfThreadPool.PoolSize := m_maxPlayers + 1; m_server := TIdTCPServer.Create(nil); m_server.DefaultPort := serverCreateOptions.Port; m_server.MaxConnections := m_maxPlayers; m_server.ListenQueue := m_maxPlayers; m_server.OnExecute := ServerOnExecute; m_server.OnConnect := ServerOnConnect; m_server.OnDisconnect := ServerOnDisconnect; m_server.OnException := ServerOnException; m_server.OnStatus := ServerOnStatus; m_server.Scheduler := m_idSchedulerOfThreadPool; end; destructor TServer<ClientType>.Destroy; begin m_server.Free; m_clients.Free; m_idSchedulerOfThreadPool.Free; m_lock.Free; inherited; end; procedure TServer<ClientType>.Start; begin m_server.Active := true; end; procedure TServer<ClientType>.ServerOnConnect(AContext: TIdContext); var client: TPrivateServerClient<ClientType>; sessionId: TSessionId; begin m_lock.Synchronize(procedure var clientsCount: Integer; begin clientsCount := m_clients.Count; // WriteLn(String.Format('clients count : %d/%d', [clientsCount, m_maxPlayers])); if clientsCount >= m_maxPlayers then begin // WriteLn('refuse this client'); AContext.Connection.DisconnectNotifyPeer; Exit; end; client := TPrivateServerClient<ClientType>.Create(AContext); sessionId := m_clients.Add(client); client.SetSessionId(sessionId); SetContextData(AContext, client); OnClientCreate(client); self.OnClientConnect(client); end); end; procedure TServer<ClientType>.ServerOnDisconnect(AContext: TIdContext); var client: TServerClient<ClientType>; begin m_lock.Synchronize(procedure begin client := GetClientByContext(AContext); if client = nil then begin Exit; end; SetContextData(AContext, nil); self.OnClientDisconnect(client); m_clients.Remove(client); self.OnClientDestroy(client); client.Free; end); end; procedure TServer<ClientType>.ServerOnExecute(AContext: TIdContext); var buffer: TIdBytes; bufferSize: UInt32; packetReader: TPacketReader; client: TServerClient<ClientType>; idTCPConnection: TIdTCPConnection; packetHeader: TPacketHeader; begin idTCPConnection := AContext.Connection; with idTCPConnection.IOHandler do begin idTCPConnection.IOHandler.ReadBytes(buffer, SizeOfTPacketHeader, False); move(buffer[0], packetHeader, SizeOfTPacketHeader); ReadBytes(buffer, packetHeader.Size, False); end; bufferSize := Length(buffer); if not (packetHeader.Size = bufferSize) then begin idTCPConnection.DisconnectNotifyPeer; Exit; end; client := GetClientByContext(AContext); if nil = client then begin idTCPConnection.DisconnectNotifyPeer; Exit; end; packetReader := TPacketReader.CreateFromBytesArray(buffer); m_lock.Synchronize(procedure begin self.OnReceiveClientPacket(client, packetReader); end); packetReader.Free; end; procedure TServer<ClientType>.ServerOnException(AContext: TIdContext; AException: Exception); begin m_lock.Synchronize(procedure begin end); end; procedure TServer<ClientType>.ServerOnStatus(ASender: TObject; const AStatus: TIdStatus; const AStatusText: string); begin m_lock.Synchronize(procedure begin end); end; function TServer<ClientType>.GetClientByContext(AContext: TIdContext): TServerClient<ClientType>; var Client: TServerClient<ClientType>; contextObject: TObject; begin contextObject := GetContextData(AContext); for Client in m_clients do begin if client = contextObject then begin Exit(client); end; end; Exit(nil); end; procedure TServer<ClientType>.SetContextData(AContext: TIdContext; data: TObject); begin {$IFDEF USE_OBJECT_ARC} AContext.DataObject := data; {$ELSE} AContext.Data := data; {$ENDIF} end; function TServer<ClientType>.GetContextData(AContext: TIdContext): TObject; begin {$IFDEF USE_OBJECT_ARC} Exit(AContext.DataObject); {$ELSE} Exit(AContext.Data); {$ENDIF} end; procedure TServer<ClientType>.OnReceiveClientPacket(const client: TServerClient<ClientType>; const packetReader: TPacketReader); begin end; procedure TServer<ClientType>.OnClientCreate(const client: TServerClient<ClientType>); begin end; procedure TServer<ClientType>.OnClientDestroy(const client: TServerClient<ClientType>); begin end; procedure TServer<ClientType>.OnClientConnect(const client: TServerClient<ClientType>); begin end; procedure TServer<ClientType>.OnClientDisconnect(const client: TServerClient<ClientType>); begin end; procedure TServer<ClientType>.GuardAgainstInvalidOptions(const serverCreateOptions: TServerCreateOptions); const cMaxPlayers = 500; var maxPlayers: UInt16; begin maxPlayers := serverCreateOptions.MaxPlayers; if maxPlayers = 0 then begin raise Exception.Create('You must specify max players'); end; if maxPlayers > cMaxPlayers then begin raise Exception.Create(String.Format('You can''t assign more than %d players', [cMaxPlayers])); end; end; end.
unit ChoiceTask; interface uses Windows, Classes, Tasks, Kernel, Collection, BuildFacilitiesTask, FacIds, Persistent, CacheAgent, BackupInterfaces; const stgContractSupplier = 3; stgConnectSupplier = 4; const MaxSuggestions = 3; const tidBuiltFacility = 'BuiltFac'; tidCookie_ConnectFacility = 'ConnFac'; tidCookie_FacX = 'FacX'; tidCookie_FacY = 'FacY'; tidCookie_ConnToFacX = 'CnnToX'; tidCookie_ConnToFacY = 'CnnToY'; tidCookie_ConnToMetaFac = 'CnnMetaFac'; type TMetaChoice = class public constructor Create(aServiceId : string; TheIds : array of TFacId); destructor Destroy; override; private fCookies : TStringList; fServiceId : string; fFacIds : PFacIdArray; fCount : integer; public procedure SetCookies(CookieList : TStringList); public property Cookies : TStringList read fCookies; property ServiceId : string read fServiceId; property Ids : PFacIdArray read fFacIds; property FacIdCount : integer read fCount; end; TMetaChoiceTask = class(TMetaTask) public constructor Create(anId, aName, aDesc, aSuperTaskId : string; aPeriod : integer; aTaskClass : CTask); destructor Destroy; override; private fMetaChoices : TCollection; public function AddChoice(Choice : TMetaChoice) : TMetaChoice; private function GetChoiceCount : integer; function GetChoice(index : integer) : TMetaChoice; public property ChoiceCount : integer read GetChoiceCount; property Choices[index : integer] : TMetaChoice read GetChoice; end; TChoiceTask = class(TAtomicTask) protected procedure DefineTarget; override; procedure Activate; override; end; TMetaCookieBasedFacilityTask = class(TMetaBuildFacilitiesTask) private fCookieName : string; fCookieValue : string; fReqFacs : PFacIdArray; fReqCount : integer; public procedure RequireFacilities(TheReqFacs : array of TFacId); public property CookieName : string read fCookieName write fCookieName; property CookieValue : string read fCookieValue write fCookieValue; property ReqFacs : PFacIdArray read fReqFacs; property ReqCount : integer read fReqCount; end; TCookieBasedFacilityTask = class(TBuildFacilitiesTask) protected class function GetPriority(MetaTask : TMetaTask; SuperTask : TTask; Context : ITaskContext) : integer; override; end; TCookieBasedBuildStoreTask = class(TCookieBasedFacilityTask) end; TSuggestionArray = array[0..MaxSuggestions - 1] of TPoint; TConnectionInfo = class(TPersistent) public constructor Create(anInput : TInput); private fSuggestions : TSuggestionArray; fInput : TInput; protected procedure LoadFromBackup( Reader : IBackupReader ); override; procedure StoreToBackup ( Writer : IBackupWriter ); override; end; TCookieBasedBuildIndustryTask = class(TCookieBasedFacilityTask) protected procedure Initialize; override; procedure Finalize; override; private fInputs : TCollection; private procedure GetTroubleInputs; function ConnectedInput(Input : TInput) : boolean; function NeedsSuppliers : boolean; function NeedsConnection : boolean; function VerifyConnections : boolean; public function Execute : TTaskResult; override; private function CollectSuggestions(var Suggestions : array of TPoint) : integer; public procedure StoreToCache(Prefix : string; Cache : TObjectCache); override; procedure LoadFromBackup( Reader : IBackupReader ); override; procedure StoreToBackup ( Writer : IBackupWriter ); override; protected procedure FacilityRemoved(Fac : TFacility); override; end; procedure RegisterBackup; implementation uses SysUtils, ServiceInfo, Population, MathUtils, TaskUtils; type PChoiceIndex = ^TChoiceIndex; TChoiceIndex = array[0..0] of integer; // TMetaChoice constructor TMetaChoice.Create(aServiceId : string; TheIds : array of TFacId); begin inherited Create; fCookies := TStringList.Create; fServiceId := aServiceId; if TheIds[0] = FID_None then fCount := 0 else fCount := FacIds.NewFacIds(fFacIds, TheIds); end; destructor TMetaChoice.Destroy; begin fCookies.Free; if fFacIds <> nil then FreeMem(fFacIds); inherited; end; procedure TMetaChoice.SetCookies(CookieList : TStringList); var i : integer; begin for i := 0 to pred(fCookies.Count) do CookieList.Add(fCookies[i]); end; // TMetaChoiceTask constructor TMetaChoiceTask.Create(anId, aName, aDesc, aSuperTaskId : string; aPeriod : integer; aTaskClass : CTask); begin inherited Create(anId, aName, aDesc, aSuperTaskId, aPeriod, aTaskClass); fMetaChoices := TCollection.Create(0, rkBelonguer); end; destructor TMetaChoiceTask.Destroy; begin fMetaChoices.Free; inherited; end; function TMetaChoiceTask.AddChoice(Choice : TMetaChoice) : TMetaChoice; begin fMetaChoices.Insert(Choice); result := Choice; end; function TMetaChoiceTask.GetChoiceCount : integer; begin result := fMetaChoices.Count; end; function TMetaChoiceTask.GetChoice(index : integer) : TMetaChoice; begin result := TMetaChoice(fMetaChoices[index]); end; // TChoiceTask procedure TChoiceTask.DefineTarget; var Indexes : PChoiceIndex; Ratios : PChoiceIndex; count : integer; i, j : integer; TownHall : TTownHall; Choice : TMetaChoice; Service : TServiceInfo; procedure Swap(var v1, v2 : integer); var t : integer; begin t := v1; v1 := v2; v2 := t; end; function PossibleChoice(idx : integer) : boolean; begin Choice := TMetaChoiceTask(MetaTask).Choices[idx]; result := (Choice.FacIdCount = 0) or TaskUtils.TownHasFacilities(TTown(Context.getContext(tcIdx_Town)), Slice(Choice.Ids^, Choice.FacIdCount)); end; begin count := TMetaChoiceTask(MetaTask).ChoiceCount; GetMem(Indexes, count*sizeof(Indexes[0])); GetMem(Ratios, count*sizeof(Ratios[0])); try FillChar(Indexes^, count*sizeof(Indexes[0]), 0); TownHall := TTownHall(TInhabitedTown(Context.getContext(tcIdx_Town)).TownHall.CurrBlock); // Get the ratios for i := 0 to pred(count) do begin Choice := TMetaChoiceTask(MetaTask).Choices[i]; Service := TServiceInfo(TownHall.ServiceInfoById[Choice.ServiceId]); if Service <> nil then Ratios[i] := min(100, round(100*Service.Ratio)) + intcond(Service.Capacity > 0, 30, 0) else Ratios[i] := 100; Indexes[i] := i; end; // Sort the indexes usising bubble sort for i := 0 to pred(pred(count)) do for j := succ(i) to pred(count) do if Ratios[i] > Ratios[j] then begin Swap(Ratios[i], Ratios[j]); Swap(Indexes[i], Indexes[j]); end; // Get the best choice i := 0; while (i < count) and not PossibleChoice(Indexes[i]) do inc(i); if i < count then TMetaChoiceTask(MetaTask).Choices[Indexes[i]].SetCookies(SuperTask.CookieList); finally FreeMem(Indexes); FreeMem(Ratios); end; end; procedure TChoiceTask.Activate; begin SuperTask.SubTaskFinalize; end; // TMetaCookieBasedFacilityTask procedure TMetaCookieBasedFacilityTask.RequireFacilities(TheReqFacs : array of TFacId); begin fReqCount := FacIds.NewFacIds(fReqFacs, TheReqFacs); end; // TCookieBasedFacilityTask class function TCookieBasedFacilityTask.GetPriority(MetaTask : TMetaTask; SuperTask : TTask; Context : ITaskContext) : integer; begin result := inherited GetPriority(MetaTask, SuperTask, Context); if (result <> tprIgnoreTask) and (SuperTask.Cookies[TMetaCookieBasedFacilityTask(MetaTask).CookieName] <> TMetaCookieBasedFacilityTask(MetaTask).CookieValue) then result := tprIgnoreTask; end; // TConnectionInfo constructor TConnectionInfo.Create(anInput : TInput); begin inherited Create; fInput := anInput; end; procedure TConnectionInfo.LoadFromBackup(Reader : IBackupReader); begin Reader.ReadObject('Input', fInput, nil); Reader.ReadBuffer('Suggs', fSuggestions, nil, sizeof(fSuggestions)); end; procedure TConnectionInfo.StoreToBackup(Writer : IBackupWriter); begin Writer.WriteObjectRef('Input', fInput); Writer.WriteBuffer('Suggs', fSuggestions, sizeof(fSuggestions)); end; // TCookieBasedBuildIndustryTask procedure TCookieBasedBuildIndustryTask.Initialize; begin fInputs := TCollection.Create(0, rkBelonguer); end; procedure TCookieBasedBuildIndustryTask.Finalize; begin fInputs.Free; end; function TCookieBasedBuildIndustryTask.NeedsSuppliers : boolean; var i : integer; cnt : integer; Input : TInput; begin i := 0; cnt := fInputs.Count; result := false; while (i < cnt) and not result do begin Input := TConnectionInfo(fInputs[i]).fInput; result := Input.ConnectionCount = 0; inc(i); end; end; procedure TCookieBasedBuildIndustryTask.GetTroubleInputs; var Block : TBlock; i : integer; cnt : integer; Input : TInput; CnInfo : TConnectionInfo; begin fInputs.DeleteAll; Block := Facs[0].CurrBlock; cnt := Block.InputCount; for i := 0 to pred(cnt) do begin Input := Block.Inputs[i]; if (mfTradeable in Input.MetaInput.MetaFluid.Options) and (Input.MetaInput.Level = mglBasic) and ((Input.ConnectionCount = 0) or not ConnectedInput(Input)) then begin CnInfo := TConnectionInfo.Create(Input); TaskUtils.FindSupplierFor(Input, CnInfo.fSuggestions); fInputs.Insert(CnInfo); end; end; end; function TCookieBasedBuildIndustryTask.ConnectedInput(Input : TInput) : boolean; var i : integer; cnt : integer; begin cnt := Input.ConnectionCount; i := 0; while (i < cnt) and ((Input.ExtraconnectionInfo[i] = nil) or Input.ExtraconnectionInfo[i].Connected) do inc(i); result := i = cnt; end; function TCookieBasedBuildIndustryTask.NeedsConnection : boolean; var i : integer; begin i := 0; while (i < fInputs.Count) and ConnectedInput(TConnectionInfo(fInputs[i]).fInput) do inc(i); result := i < fInputs.Count; end; function TCookieBasedBuildIndustryTask.VerifyConnections : boolean; var i : integer; begin i := 0; while i < fInputs.Count do if ConnectedInput(TConnectionInfo(fInputs[i]).fInput) then fInputs.AtDelete(i) else inc(i); result := fInputs.Count > 0; end; function TCookieBasedBuildIndustryTask.Execute : TTaskResult; begin result := inherited Execute; case Stage of stgWait : if result = trFinished then begin if fInputs = nil then fInputs := TCollection.Create(0, rkBelonguer); if fInputs.Count = 0 then GetTroubleInputs; if NeedsSuppliers then begin result := trContinue; Stage := stgContractSupplier; NotifyTycoon(''); end else if VerifyConnections then begin result := trContinue; Stage := stgConnectSupplier; NotifyTycoon(''); end; end; stgContractSupplier : if NeedsSuppliers then result := trContinue else begin if VerifyConnections then begin result := trContinue; Stage := stgConnectSupplier; NotifyTycoon(''); end else result := trFinished; end; stgConnectSupplier : if NeedsConnection then result := trContinue else result := trFinished; end; end; function TCookieBasedBuildIndustryTask.CollectSuggestions(var Suggestions : array of TPoint) : integer; var i : integer; count : integer; procedure AddSuggestions(Suggs : array of TPoint); var k : integer; j : integer; begin for k := low(Suggs) to high(Suggs) do if (Suggs[k].x <> 0) or (Suggs[k].y <> 0) then begin j := 0; while (j < count) and ((Suggs[k].x <> Suggestions[j].x) or (Suggs[k].y <> Suggestions[j].y))do inc(j); if j = count then begin Suggestions[count] := Suggs[k]; inc(count); end; end; end; begin count := 0; for i := 0 to pred(fInputs.Count) do AddSuggestions(TConnectionInfo(fInputs[i]).fSuggestions); result := count; end; procedure TCookieBasedBuildIndustryTask.StoreToCache(Prefix : string; Cache : TObjectCache); var Tycoon : TTycoon; Input : TInput; Suggs : array[0..25] of TPoint; SgCnt : integer; ActCnt : integer; i : integer; j : integer; Fac : TFacility; iStr : string; begin inherited; Tycoon := TTycoon(Context.getContext(tcIdx_Tycoon)); case Stage of stgContractSupplier : begin for i := 0 to pred(fInputs.Count) do Cache.WriteString(Prefix + 'toCnnInp' + IntToStr(i), TConnectionInfo(fInputs[i]).fInput.MetaInput.MetaFluid.Name_MLS.Values[Tycoon.Language]); ActCnt := 0; SgCnt := CollectSuggestions(Suggs); Cache.WriteInteger(Prefix + 'toCnnCount', SgCnt); for i := 0 to pred(SgCnt) do begin Fac := Tycoon.WorldLocator.FacilityAt(Suggs[i].x, Suggs[i].y); if Fac <> nil then begin iStr := IntToStr(ActCnt); inc(ActCnt); Cache.WriteString(Prefix + 'toCnnName' + iStr, Fac.Name); Cache.WriteInteger(Prefix + 'toCnnX' + iStr, Fac.xPos); Cache.WriteInteger(Prefix + 'toCnnY' + iStr, Fac.yPos); Cache.WriteInteger(Prefix + 'toCnnVID' + iStr, Fac.MetaFacility.VisualClass); end; end; end; stgConnectSupplier : begin ActCnt := 0; for i := 0 to pred(fInputs.Count) do begin Input := TConnectionInfo(fInputs[i]).fInput; if not ConnectedInput(Input) then for j := 0 to pred(Input.ConnectionCount) do if (Input.ExtraConnectionInfo[j] <> nil) and not Input.ExtraConnectionInfo[j].Connected then with Input.Connections[j].Block do begin iStr := IntToStr(ActCnt); Cache.WriteString(Prefix + 'toCnnName' + iStr, Facility.Name); Cache.WriteInteger(Prefix + 'toCnnX' + iStr, Facility.xPos); Cache.WriteInteger(Prefix + 'toCnnY' + iStr, Facility.yPos); Cache.WriteInteger(Prefix + 'toCnnVID' + iStr, Facility.MetaFacility.VisualClass); Inc(ActCnt); end; Cache.WriteInteger(Prefix + 'toCnnCount', ActCnt); end; end; end; end; procedure TCookieBasedBuildIndustryTask.LoadFromBackup( Reader : IBackupReader ); begin inherited; Reader.ReadObject('Inputs', fInputs, nil); end; procedure TCookieBasedBuildIndustryTask.StoreToBackup ( Writer : IBackupWriter ); begin inherited; Writer.WriteLooseObject('Inputs', fInputs); end; procedure TCookieBasedBuildIndustryTask.FacilityRemoved(Fac : TFacility); begin inherited; fInputs.DeleteAll; end; // RegisterBackup procedure RegisterBackup; begin RegisterClass(TChoiceTask); RegisterClass(TCookieBasedFacilityTask); RegisterClass(TCookieBasedBuildStoreTask); RegisterClass(TCookieBasedBuildIndustryTask); RegisterClass(TConnectionInfo); end; end.
unit mnSynHighlighterSARD; {$mode objfpc}{$H+} {** * NOT COMPLETED * * This file is part of the "Mini Library" * * @url http://www.sourceforge.net/projects/minilib * @license modifiedLGPL (modified of http://www.gnu.org/licenses/lgpl.html) * See the file COPYING.MLGPL, included in this distribution, * @author Zaher Dirkey * *} interface uses Classes, SysUtils, SynEdit, SynEditTypes, SynEditHighlighter, mnSynHighlighterMultiProc; type { TSardProcessor } TSardProcessor = class(TCommonSynProcessor) private protected function GetIdentChars: TSynIdentChars; override; function GetEndOfLineAttribute: TSynHighlighterAttributes; override; public procedure Created; override; procedure QuestionProc; procedure SlashProc; procedure BlockProc; procedure GreaterProc; procedure LowerProc; procedure DeclareProc; procedure Next; override; procedure Prepare; override; procedure MakeProcTable; override; end; { TSynSardSyn } TSynSardSyn = class(TSynMultiProcSyn) private protected function GetSampleSource: string; override; public class function GetLanguageName: string; override; public constructor Create(AOwner: TComponent); override; procedure InitProcessors; override; published end; const SYNS_LangSard = 'Sard'; SYNS_FilterSard = 'Sard Lang Files (*.sard)|*.sard'; cSardSample = '/*' +' This examples are worked, and this comment will ignored, not compiled or parsed as we say.'#13 +' */'#13 +''#13 +' //Single Line comment'#13 +' CalcIt:Integer(p1, p2){'#13 +' :=p1 * p2 / 2;'#13 +' };'#13 +''#13 +' x := {'#13 +' y := 0;'#13 +' x := CalcIt(x, y);'#13 +' := y + x+ 500 * %10; //this is a result return of the block'#13 +' }; //do not forget to add ; here'#13 +''#13 +' f := 10.0;'#13 +' f := z + 5.5;'#13 +''#13 +' {* Embeded block comment *};'#13 +''#13 +' := "Result:" + x + '' It is an example:'#13 +' Multi Line String'#13 +' '';'#13; implementation uses mnUtils; procedure TSardProcessor.GreaterProc; begin Parent.FTokenID := tkSymbol; Inc(Parent.Run); if Parent.FLine[Parent.Run] in ['=', '>'] then Inc(Parent.Run); end; procedure TSardProcessor.LowerProc; begin Parent.FTokenID := tkSymbol; Inc(Parent.Run); case Parent.FLine[Parent.Run] of '=': Inc(Parent.Run); '<': begin Inc(Parent.Run); if Parent.FLine[Parent.Run] = '=' then Inc(Parent.Run); end; end; end; procedure TSardProcessor.DeclareProc; begin Parent.FTokenID := tkSymbol; Inc(Parent.Run); case Parent.FLine[Parent.Run] of '=': Inc(Parent.Run); ':': begin Inc(Parent.Run); if Parent.FLine[Parent.Run] = '=' then Inc(Parent.Run); end; end; end; procedure TSardProcessor.SlashProc; begin Inc(Parent.Run); case Parent.FLine[Parent.Run] of '/': begin CommentSLProc; end; '*': begin Inc(Parent.Run); if Parent.FLine[Parent.Run] = '*' then DocumentMLProc else CommentMLProc; end; else Parent.FTokenID := tkSymbol; end; end; procedure TSardProcessor.BlockProc; begin Inc(Parent.Run); case Parent.FLine[Parent.Run] of '*': SpecialCommentMLProc; else Parent.FTokenID := tkSymbol; end; end; procedure TSardProcessor.MakeProcTable; var I: Char; begin inherited; for I := #0 to #255 do case I of '?': ProcTable[I] := @QuestionProc; '''': ProcTable[I] := @StringSQProc; '"': ProcTable[I] := @StringDQProc; '`': ProcTable[I] := @StringBQProc; '/': ProcTable[I] := @SlashProc; '{': ProcTable[I] := @BlockProc; '>': ProcTable[I] := @GreaterProc; '<': ProcTable[I] := @LowerProc; ':': ProcTable[I] := @DeclareProc; '0'..'9': ProcTable[I] := @NumberProc; //else 'A'..'Z', 'a'..'z', '_': ProcTable[I] := @IdentProc; end; end; procedure TSardProcessor.QuestionProc; begin Inc(Parent.Run); case Parent.FLine[Parent.Run] of '>': begin Parent.Processors.Switch(Parent.Processors.MainProcessor); Inc(Parent.Run); Parent.FTokenID := tkProcessor; end else Parent.FTokenID := tkSymbol; end; end; procedure TSardProcessor.Next; begin Parent.FTokenPos := Parent.Run; if (Parent.FLine[Parent.Run] in [#0, #10, #13]) then ProcTable[Parent.FLine[Parent.Run]] else case Range of rscComment: begin CommentMLProc; end; rscDocument: begin DocumentMLProc; end; rscStringSQ, rscStringDQ, rscStringBQ: StringProc; else if ProcTable[Parent.FLine[Parent.Run]] = nil then UnknownProc else ProcTable[Parent.FLine[Parent.Run]]; end; end; procedure TSardProcessor.Prepare; begin inherited; // EnumerateKeywords(Ord(tkKeyword), sSardKeywords, TSynValidStringChars, @DoAddKeyword); // EnumerateKeywords(Ord(tkFunction), sSardFunctions, TSynValidStringChars, @DoAddKeyword); SetRange(rscUnknown); end; function TSardProcessor.GetEndOfLineAttribute: TSynHighlighterAttributes; begin if (Range = rscDocument) or (LastRange = rscDocument) then Result := Parent.DocumentAttri else Result := inherited GetEndOfLineAttribute; end; procedure TSardProcessor.Created; begin inherited Created; CloseSpecialComment := '*}'; end; function TSardProcessor.GetIdentChars: TSynIdentChars; begin Result := TSynValidStringChars; end; { TSynSardSyn } constructor TSynSardSyn.Create(AOwner: TComponent); begin inherited Create(AOwner); FDefaultFilter := SYNS_FilterSard; end; procedure TSynSardSyn.InitProcessors; begin inherited; Processors.Add(TSardProcessor.Create(Self, 'Sard')); Processors.MainProcessor := 'Sard'; Processors.DefaultProcessor := 'Sard'; end; class function TSynSardSyn.GetLanguageName: string; begin Result := SYNS_LangSard; end; function TSynSardSyn.GetSampleSource: string; begin Result := cSardSample; end; initialization RegisterPlaceableHighlighter(TSynSardSyn); finalization end.
unit BaseDevice; // This module has an abstract device interface the program will work with. // Each device should have it implementation. Also it has an abstraction of // command info. interface type TBytesArray = Array of Byte; type TLineIndexesArray = Array of Integer; type IConnectionCallback = interface // A device will get this interface and call it on some events. // Callbacks names are self describing. procedure OnConnected; procedure OnConnectionStatusMessage(message: string); procedure OnConnectionProgress(percent: integer); procedure OnDisconnected; procedure OnErrorOnConnection; end; type ICommandInfo = interface // Command interface // Command for a device // Commands can show forms, these forms can be used to show some data or get input from an operator // The form is shown in the gui thread // // Some commands want to send initialization before showing the form. // This initialization will be done in the interrogation thread. // // Some commands want to execute some interrogation after showing the form. // It will be done in the interrogation thread. function GetName() : string; function NeedSendInitialization() : boolean; function ShowForm() : integer; // show a form, the form should return MrYes or MrNo. MrNo means "don't execute" function NeedExecute() : boolean; procedure Execute; function Initialize : boolean; end; type IBaseRequestOnlyDevice = interface // An interface for request only device. Such device can't spam with data, it can be only requested to send data // Input line here is a data provider, most probably it will be adc. function GetName() : string; function IsConnected() : boolean; procedure Connect(connectionCallback: IConnectionCallback); procedure Disconnect; function GetInputLinesNumber() : integer; function GetMinimumValInInputLine(lineNumber : integer) : integer; // Minimal value that the input line can send. function GetMaximumValInInputLine(lineNumber : integer) : integer; // Maximum value that the input line can send. function ReadFromInputLine(lineNumber: integer; var output : TBytesArray) : boolean; function GetMaxInputLinesNumberPerRequest () : integer; // Maximum input lines that can be requested to send data. function ReadFromInputLines(var lineNumbers : TLineIndexesArray; var output : TBytesArray) : boolean; function GetCommandsNumber() : integer; function GetCommandInfo(commandNumber : integer) : ICommandInfo; procedure ShowAbout; end; implementation end.
unit ModStack_ADS; interface procedure push(e : integer); function pop : integer; function isEmpty : boolean; procedure init; procedure disposeStack; implementation type intArray = array [1..1] of integer; VAR arrPtr : ^intArray; capacity : integer; top : integer; (* index of top element *) procedure init; begin if(arrPtr <> NIL) then begin writeln('Call disposeStack first you maniac!'); halt; end; top := 0; capacity := 10; GetMem(arrPtr, SIZEOF(integer) * capacity); end; procedure push(e : integer); begin if top > capacity then begin writeln('Stackoverflow!'); halt; end; inc(top); (*$R-*) arrPtr^[top] := e; (*$R+*) end; function pop : integer; begin if isEmpty then begin writeln('Stack is empty'); halt; end; dec(top); (*$R-*) pop := arrPtr^[top+1]; (*$R+*) end; function isEmpty : boolean; begin isEmpty := top = 0; end; procedure disposeStack; begin if arrPtr = NIL then begin writeln('Stack is not initialized you moron!'); halt; end; FreeMem(arrPtr, SIZEOF(integer) * capacity); arrPtr := NIL; end; begin arrPtr := NIL; end.
unit Complex2D; interface uses classes,graphics; type ComplexTernary2D=class(TPersistent) private _qx,_qy: Integer; //число тритов по осям x и y _Tx,_Ty,_Nx,_Ny: Integer; //полное число элементов и мин/макс значение (-N, N) _T: Integer; //всего элементов в массиве base: Integer; //смещение отсчета (0,0) function Re_value(x,y: Integer): Real; function Im_value(x,y: Integer): Real; procedure set_Re(x,y: Integer; value: Real); procedure set_Im(x,y: Integer; value: Real); procedure Inversion(fbase,mult,_T1: Integer); procedure general_FFT(fbase,mult,_T1: Integer; inverse: boolean); public Re_data, Im_data: array of Real; //адресацию сделаем свою procedure Set_Length(X,Y: Integer); procedure FFT; procedure InverseFFT; procedure power_spectrum; procedure Clear; procedure LoadFromBitmap(btmp: TBitmap; offset_x: Integer=0; offset_y: Integer=0); procedure SaveToBitmap(btmp: TBitmap); property Nx: Integer read _Nx; property Ny: Integer read _Ny; property Tx: Integer read _Tx; property Ty: Integer read _Ty; property T: Integer read _T; property Re[x,y: Integer]: Real read Re_value write Set_Re; property Im[x,y: Integer]: Real read Im_value write Set_Im; procedure Assign(source:TPersistent); override; procedure AssignWithShift(source:ComplexTernary2D;x_offset,y_offset: Integer); procedure apply_Hann_window; constructor Create; end; implementation uses math,gamma_function; function ComplexTernary2D.Re_value(x,y: Integer): Real; begin Assert(x<=_Nx,'Re_value: x too big'); Assert(x>=-_Nx,'Re_value: x too small'); Assert(y<=_Ny,'Re_value: y too big'); Assert(y>=-_Ny,'Re_value: y too small'); Re_value:=Re_data[base+y*_Tx+x]; end; function ComplexTernary2D.Im_value(x,y: Integer): Real; begin Assert(x<=_Nx,'Im_value: x too big'); Assert(x>=-_Nx,'Im_value: x too small'); Assert(y<=_Ny,'Im_value: y too big'); Assert(y>=-_Ny,'Im_value: y too small'); Im_value:=Im_data[base+y*_Tx+x]; end; procedure ComplexTernary2D.set_Re(x,y: Integer; value: Real); begin Assert(x<=_Nx,'set_Re: x too big'); Assert(x>=-_Nx,'set_Re: x too small'); Assert(y<=_Ny,'set_Re: y too big'); Assert(y>=-_Ny,'set_Re: y too small'); Re_data[base+y*_Tx+x]:=value; end; procedure ComplexTernary2D.set_Im(x,y: Integer; value: Real); begin Assert(x<=_Nx,'set_Im: x too big'); Assert(x>=-_Nx,'set_Im: x too small'); Assert(y<=_Ny,'set_Im: y too big'); Assert(y>=-_Ny,'set_Im: y too small'); Im_data[base+y*_Tx+x]:=value; end; procedure ComplexTernary2D.Set_Length(x,y: Integer); begin assert(x>-1,'Set_Length: negative argument x'); assert(y>-1,'Set_Length: negative argument y'); if x<1 then begin _qx:=-1; _Tx:=0; _Nx:=-1; end else begin _qx:=math.Ceil(ln(x)/ln(3)); _Tx:=Round(power(3,_qx)); _Nx:=(_Tx-1) div 2; end; if y<1 then begin _qy:=-1; _Ty:=0; _Ny:=-1; end else begin _qy:=math.Ceil(ln(y)/ln(3)); _Ty:=Round(power(3,_qy)); _Ny:=(_Ty-1) div 2; end; _T:=_Tx*_Ty; SetLength(Re_data,_T); SetLength(Im_data,_T); base:=(_T-1) div 2; end; constructor ComplexTernary2D.Create; begin inherited Create; Set_Length(0,0); end; procedure ComplexTernary2D.general_FFT(fbase,mult,_T1: Integer; Inverse: boolean); var N1,M1,T1,k,j,incr,big_incr,i: Integer; sqrt3,Wr,Wi,Ph,incWr,incWi,TwoPi,tmpWr: Real; //W - фазовый множитель, r,i - действ. и мнимое знач. xsum,ysum,xdif,ydif,ax,ay,xp1,xm1,yp1,ym1,x0,y0: Real; //sum - суммы //dif - разности //p1,0,m1 - +1,0,-1 соотв begin sqrt3:=-sqrt(3)/2; TwoPi:=2*pi; if Inverse then begin sqrt3:=-sqrt3; TwoPi:=-TwoPi; end; inversion(fbase,mult,_T1); T1:=_T1; N1:=(T1-1) shr 1; incr:=mult; while N1>0 do begin T1:=T1 div 3; N1:=(T1-1) shr 1; big_incr:=incr*3; //для внутреннего цикла M1:=(incr-1) div (2*mult); //для внешнего //отдельно обработаем i=0, там фазовый множ. не нужен for k:=-N1 to N1 do begin j:=fbase+big_incr*k; //отдельно обраб. нулевое значение - там не нужно фаз. множителей x0:=Re_data[j]; y0:=Im_data[j]; j:=j+incr; xp1:=Re_data[j]; yp1:=Im_data[j]; j:=j-2*incr; xm1:=Re_data[j]; ym1:=Im_data[j]; xsum:=xp1+xm1; ysum:=yp1+ym1; ydif:=sqrt3*(xp1-xm1); xdif:=sqrt3*(ym1-yp1); // 4 сложения и 2 умножения (с плав. точкой) Ax:=x0-0.5*xsum; Ay:=y0-0.5*ysum; // 6 сложений и 4 умножения //сейчас j указывает на -1-й элемент Re_data[j]:=Ax-xdif; Im_data[j]:=Ay-ydif; j:=j+2*incr; //+1-й элемент Re_data[j]:=Ax+xdif; Im_data[j]:=Ay+ydif; j:=j-incr; //0-й элемент Re_data[j]:=x0+xsum; Im_data[j]:=y0+ysum; //итого, 12 сложений и 4 умножения end; //шаг фазового множителя: 2pi/incr; //на первой итерации просто 2pi, но там цикл и не запустится //на второй итер: Ph:=TwoPi/big_incr*mult; incWr:=cos(Ph); incWi:=-sin(Ph); Wr:=1; Wi:=0; for i:=1 to M1 do begin //пересчитываем фазовый множитель, потом делаем циклы для i и -i tmpWr:=Wr; Wr:=tmpWr*incWr-Wi*incWi; Wi:=Wi*incWr+tmpWr*incWi; for k:=-N1 to N1 do begin //итерация для +i j:=fbase+i*mult+big_incr*k; //x0,y0 - без изменений x0:=Re_data[j]; y0:=Im_data[j]; j:=j+incr; //а здесь надо умножить на фаз. множ. //элем. +1 - на W tmpWr:=Re_data[j]; yp1:=Im_data[j]; xp1:=tmpWr*Wr-yp1*Wi; yp1:=yp1*Wr+tmpWr*Wi; j:=j-2*incr; //элем. -1 умножаем на W* (сопряж) tmpWr:=Re_data[j]; ym1:=Im_data[j]; xm1:=tmpWr*Wr+ym1*Wi; ym1:=ym1*Wr-tmpWr*Wi; xsum:=xp1+xm1; ysum:=yp1+ym1; ydif:=sqrt3*(xp1-xm1); xdif:=sqrt3*(ym1-yp1); // 4 сложения и 2 умножения (с плав. точкой) Ax:=x0-0.5*xsum; Ay:=y0-0.5*ysum; // 6 сложений и 4 умножения //сейчас j указывает на -1-й элемент Re_data[j]:=Ax-xdif; Im_data[j]:=Ay-ydif; j:=j+2*incr; //+1-й элемент Re_data[j]:=Ax+xdif; Im_data[j]:=Ay+ydif; j:=j-incr; //0-й элемент Re_data[j]:=x0+xsum; Im_data[j]:=y0+ysum; //Теперь, то же самое для элемента -i j:=fbase-i*mult+big_incr*k; //x0,y0 - без изменений x0:=Re_data[j]; y0:=Im_data[j]; j:=j+incr; //а здесь надо умножить на фаз. множ. //элем. +1 - на W* (т.к -i) tmpWr:=Re_data[j]; yp1:=Im_data[j]; xp1:=tmpWr*Wr+yp1*Wi; yp1:=yp1*Wr-tmpWr*Wi; j:=j-2*incr; //элем. -1 умножаем на W tmpWr:=Re_data[j]; ym1:=Im_data[j]; xm1:=tmpWr*Wr-ym1*Wi; ym1:=ym1*Wr+tmpWr*Wi; xsum:=xp1+xm1; ysum:=yp1+ym1; ydif:=sqrt3*(xp1-xm1); xdif:=sqrt3*(ym1-yp1); // 4 сложения и 2 умножения (с плав. точкой) Ax:=x0-0.5*xsum; Ay:=y0-0.5*ysum; // 6 сложений и 4 умножения //сейчас j указывает на -1-й элемент Re_data[j]:=Ax-xdif; Im_data[j]:=Ay-ydif; j:=j+2*incr; //+1-й элемент Re_data[j]:=Ax+xdif; Im_data[j]:=Ay+ydif; j:=j-incr; //0-й элемент Re_data[j]:=x0+xsum; Im_data[j]:=y0+ysum; end; end; //конец одного слоя incr:=big_incr; end; end; procedure ComplexTernary2D.FFT; var x,y: Integer; begin //сначала одномерный FFT по каждой строке for y:=-_Ny to _Ny do begin general_FFT(base+y*_Tx,1,_Tx,false); end; //теперь по каждому столбцу for x:=-_Nx to _Nx do begin general_FFT(base+x,_Tx,_Ty,false); end; end; procedure ComplexTernary2D.InverseFFT; var x,y: Integer; begin //по каждому столбцу, предварительно поделив на _T for x:=-_Nx to _Nx do begin for y:=-_Ny to _Ny do begin set_Re(x,y,Re_value(x,y)/_T); set_Im(x,y,Im_value(x,y)/_T); end; general_FFT(base+x,_Tx,_Ty,true); end; for y:=-_Ny to _Ny do begin general_FFT(base+y*_Tx,1,_Tx,true); end; end; procedure ComplexTernary2D.inversion(fbase,mult,_T1: integer); var i,j,k,b,q,_qmin1,_N: Integer; trits: array of Integer; tmp: Real; begin if _T1<4 then Exit; q:=ceil(ln(_T1)/ln(3)); SetLength(trits,q); _qmin1:=q-1; _N:=(_T1-1) div 2; for j:=0 to _qmin1 do trits[j]:=-1; //самый отрицательный элемент for i:=-_N to _N do begin k:=0; b:=1; for j:=_qmin1 downto 0 do begin k:=k+trits[j]*b; b:=b*3; end; //k указывает инверсию от i. if k>i then begin //поменяем местами tmp:=Re_data[fbase+k*mult]; Re_data[fbase+k*mult]:=Re_data[fbase+i*mult]; Re_data[fbase+i*mult]:=tmp; tmp:=Im_data[fbase+k*mult]; Im_data[fbase+k*mult]:=Im_data[fbase+i*mult]; Im_data[fbase+i*mult]:=tmp; end; //прибавим единичку j:=0; while j<q do begin inc(trits[j]); if trits[j]<2 then break; trits[j]:=-1; inc(j); end; end; end; procedure ComplexTernary2D.power_spectrum; var x,y: Integer; begin for y:=-_Ny to _Ny do for x:=-_Nx to _Nx do Set_Re(x,y,Sqr(Re_value(x,y))+Sqr(Im_value(x,y))); end; procedure ComplexTernary2D.Clear; var x: Integer; begin for x:=0 to _T-1 do begin Re_data[x]:=0; Im_data[x]:=0; end; end; procedure ComplexTernary2D.LoadFromBitmap(btmp: TBitmap; offset_x, offset_y: Integer); var i,j,w,h,wh: Integer; x_offset,y_offset: Integer; i_init,j_init: Integer; begin w:=btmp.Width; h:=btmp.Height; wh:=max(w,h); //на первое время (т.е на пару лет :( ) Set_Length(wh,wh); Clear; //теперь отцентрируем x_offset:=-_Nx+((_Tx-w) div 2)+offset_x; y_offset:=-_Ny+((_Ty-h) div 2)+offset_y; if w-1+x_offset>_Nx then w:=_Nx-x_offset+1; if h-1+y_offset>_Ny then h:=_Ny-y_offset+1; if x_offset<-_Nx then i_init:=-_Nx-x_offset else i_init:=0; if y_offset<-_Ny then j_init:=-_Ny-y_offset else j_init:=0; for j:=j_init to h-1 do begin for i:=i_init to w-1 do begin Re[i+x_offset,j+y_offset]:=Real_from_monochrome(btmp.Canvas.Pixels[i,j]); end; end; end; procedure ComplexTernary2D.SaveToBitmap(btmp: TBitmap); var i,j: Integer; begin btmp.Width:=_Tx; btmp.Height:=_Ty; for i:=-_Nx to _Nx do for j:=-_Ny to _Ny do btmp.Canvas.Pixels[i+_Nx,j+_Ny]:=monochrome_from_Real(Re[i,j]); end; procedure ComplexTernary2D.Assign(source: TPersistent); var _source: ComplexTernary2D absolute source; i: Integer; begin if source is ComplexTernary2D then begin _qx:=_source._qx; _qy:=_source._qy; _Nx:=_source._Nx; _Ny:=_source._Ny; _tx:=_source._Tx; _ty:=_source._Ty; _t:=_source._T; base:=_source.base; SetLength(Re_data,_t); SetLength(Im_data,_t); for i:=0 to _T-1 do begin Re_data[i]:=_source.Re_data[i]; Im_data[i]:=_source.Im_data[i]; end; end else inherited Assign(source); end; procedure ComplexTernary2D.AssignWithShift(source: ComplexTernary2D;x_offset,y_offset: Integer); var i,j,imin,imax,jmin,jmax: Integer; begin _qx:=source._qx; _qy:=source._qy; _Nx:=source._Nx; _Ny:=source._Ny; _tx:=source._Tx; _ty:=source._Ty; _t:=source._T; base:=source.base; SetLength(Re_data,_t); SetLength(Im_data,_t); clear; jmin:=max(-_Ny,-Ny-y_offset); jmax:=min(_Ny,_Ny-y_offset); imin:=max(-_Nx,-_Nx-x_offset); imax:=min(_Nx,_Nx-x_offset); for j:=jmin to jmax do begin for i:=imin to imax do begin Re[i+x_offset,j+y_offset]:=source.Re[i,j]; Im[i+x_offset,j+y_offset]:=source.Im[i,j]; end; end; end; procedure ComplexTernary2D.apply_Hann_window; var i,j: Integer; wfx,wfy: Real; begin for i:=-_Nx to _Nx do begin wfx:=0.5*(1+cos(i*pi/_Nx)); for j:=-_Ny to _Ny do begin wfy:=wfx*0.5*(1+cos(j*pi/_Ny)); Re[i,j]:=wfy*Re[i,j]; Im[i,j]:=wfy*Im[i,j]; end; end; end; end.
{ Date Created: 5/22/00 11:17:33 AM } unit InfoLENDERGROUPSTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoLENDERGROUPSRecord = record PIndex: Integer; PGroupIndex: Integer; PLenderID: String[4]; End; TInfoLENDERGROUPSBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoLENDERGROUPSRecord end; TEIInfoLENDERGROUPS = (InfoLENDERGROUPSPrimaryKey, InfoLENDERGROUPSByLenderID, InfoLENDERGROUPSByGroupIndex); TInfoLENDERGROUPSTable = class( TDBISAMTableAU ) private FDFIndex: TAutoIncField; FDFGroupIndex: TIntegerField; FDFLenderID: TStringField; procedure SetPGroupIndex(const Value: Integer); function GetPGroupIndex:Integer; procedure SetPLenderID(const Value: String); function GetPLenderID:String; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; procedure SetEnumIndex(Value: TEIInfoLENDERGROUPS); function GetEnumIndex: TEIInfoLENDERGROUPS; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; virtual; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TInfoLENDERGROUPSRecord; procedure StoreDataBuffer(ABuffer:TInfoLENDERGROUPSRecord); property DFIndex: TAutoIncField read FDFIndex; property DFGroupIndex: TIntegerField read FDFGroupIndex; property DFLenderID: TStringField read FDFLenderID; property PGroupIndex: Integer read GetPGroupIndex write SetPGroupIndex; property PLenderID: String read GetPLenderID write SetPLenderID; procedure Validate; virtual; published property Active write SetActive; property EnumIndex: TEIInfoLENDERGROUPS read GetEnumIndex write SetEnumIndex; end; { TInfoLENDERGROUPSTable } procedure Register; implementation function TInfoLENDERGROUPSTable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; var I: Integer; NewName: string; Done: Boolean; function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean; var I: Integer; begin Result := False; for I := 0 To AOwner.ComponentCount - 1 do begin if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then begin Result := True; Break; end; end; end; { ComponentExists } begin { TInfoLENDERGROUPSTable.GenerateNewFieldName } NewName := DatasetName; for I := 1 to Length( FieldName ) do begin if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then NewName := NewName + FieldName[ I ]; end; if ComponentExists( Owner, NewName ) then begin I := 1; Done := False; repeat Inc( I ); if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then begin Result := NewName + IntToStr( I ); Done := True; end; until Done; end else Result := NewName; end; { TInfoLENDERGROUPSTable.GenerateNewFieldName } function TInfoLENDERGROUPSTable.CreateField( const FieldName : string ): TField; begin { First, try to find an existing field object. FindField is the same } { as FieldByName, but does not raise an exception if the field object } { cannot be found. } Result := FindField( FieldName ); if Result = nil then begin { If an existing field object cannot be found... } { Instruct the FieldDefs object to create a new field object } Result := FieldDefs.Find( FieldName ).CreateField( Owner ); { The new field object must be given a name so that it may appear in } { the Object Inspector. The Delphi default naming convention is used.} Result.Name := GenerateNewFieldName( Owner, Name, FieldName); end; end; { TInfoLENDERGROUPSTable.CreateField } procedure TInfoLENDERGROUPSTable.CreateFields; begin FDFIndex := CreateField( 'Index' ) as TAutoIncField; FDFGroupIndex := CreateField( 'GroupIndex' ) as TIntegerField; FDFLenderID := CreateField( 'LenderID' ) as TStringField; end; { TInfoLENDERGROUPSTable.CreateFields } procedure TInfoLENDERGROUPSTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoLENDERGROUPSTable.SetActive } procedure TInfoLENDERGROUPSTable.Validate; begin { Enter Validation Code Here } end; { TInfoLENDERGROUPSTable.Validate } procedure TInfoLENDERGROUPSTable.SetPGroupIndex(const Value: Integer); begin DFGroupIndex.Value := Value; end; function TInfoLENDERGROUPSTable.GetPGroupIndex:Integer; begin result := DFGroupIndex.Value; end; procedure TInfoLENDERGROUPSTable.SetPLenderID(const Value: String); begin DFLenderID.Value := Value; end; function TInfoLENDERGROUPSTable.GetPLenderID:String; begin result := DFLenderID.Value; end; procedure TInfoLENDERGROUPSTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('Index, AutoInc, 0, Y'); Add('GroupIndex, Integer, 0, Y'); Add('LenderID, String, 4, Y'); end; end; procedure TInfoLENDERGROUPSTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, Index, Y, Y, N, N'); Add('ByLenderID, LenderID, N, N, N, N'); Add('ByGroupIndex, GroupIndex, N, N, N, N'); end; end; procedure TInfoLENDERGROUPSTable.SetEnumIndex(Value: TEIInfoLENDERGROUPS); begin case Value of InfoLENDERGROUPSPrimaryKey : IndexName := ''; InfoLENDERGROUPSByLenderID : IndexName := 'ByLenderID'; InfoLENDERGROUPSByGroupIndex : IndexName := 'ByGroupIndex'; end; end; function TInfoLENDERGROUPSTable.GetDataBuffer:TInfoLENDERGROUPSRecord; var buf: TInfoLENDERGROUPSRecord; begin fillchar(buf, sizeof(buf), 0); buf.PIndex := DFIndex.Value; buf.PGroupIndex := DFGroupIndex.Value; buf.PLenderID := DFLenderID.Value; result := buf; end; procedure TInfoLENDERGROUPSTable.StoreDataBuffer(ABuffer:TInfoLENDERGROUPSRecord); begin DFGroupIndex.Value := ABuffer.PGroupIndex; DFLenderID.Value := ABuffer.PLenderID; end; function TInfoLENDERGROUPSTable.GetEnumIndex: TEIInfoLENDERGROUPS; var iname : string; begin iname := uppercase(indexname); if iname = '' then result := InfoLENDERGROUPSPrimaryKey; if iname = 'BYLENDERID' then result := InfoLENDERGROUPSByLenderID; if iname = 'BYGROUPINDEX' then result := InfoLENDERGROUPSByGroupIndex; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoLENDERGROUPSTable, TInfoLENDERGROUPSBuffer ] ); end; { Register } function TInfoLENDERGROUPSBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PIndex; 2 : result := @Data.PGroupIndex; 3 : result := @Data.PLenderID; end; end; end. { InfoLENDERGROUPSTable }
unit IsoProfile; interface const prfKind_Main = 0; prfId_Rendering = 1; prfId_Blitting = 2; prfId_RenderingInit = 3; prfId_RegionFill = 4; prfId_LandRendering = 5; prfId_TextRendering = 6; prfId_ConnectionsRendering = 7; prfId_SurfaceRendering = 8; prfId_AirplaneRendering = 9; prfId_ChatTextRendering = 10; prfId_ImageDrawing = 11; procedure InitIsoViewerProfiles; procedure LogIsoViewerProfiles; implementation uses Profiler; procedure InitIsoViewerProfiles; begin {$IFDEF PROFILES} RequestProfile(prfKind_Main, prfId_Rendering, 'Rendering'); RequestProfile(prfKind_Main, prfId_Blitting, 'Blitting'); { RequestProfile(prfKind_Main, prfId_RenderingInit, 'Rendering Initialization'); RequestProfile(prfKind_Main, prfId_RegionFill, 'Region Fill'); RequestProfile(prfKind_Main, prfId_LandRendering, 'Land Rendering'); RequestProfile(prfKind_Main, prfId_TextRendering, 'Text Rendering'); RequestProfile(prfKind_Main, prfId_ConnectionsRendering, 'Connections Rendering'); RequestProfile(prfKind_Main, prfId_SurfaceRendering, 'Surface Rendering'); RequestProfile(prfKind_Main, prfId_AirplaneRendering, 'Airplane Rendering'); RequestProfile(prfKind_Main, prfId_ChatTextRendering, 'Chat Text Rendering'); } RequestProfile(prfKind_Main, prfId_ImageDrawing, 'Image Drawing'); {$ENDIF} end; procedure LogIsoViewerProfiles; begin {$IFDEF PROFILES} LogResults(prfKind_Main, 'MainProfile'); {$ENDIF} end; end.
unit ThdExport; interface uses Classes, ThreadReportBase, TicklerTypes, db, TTSMLTagTable, TTSTitmTable, TTSTrakTable, TTSHitmTable, TTSLoanTable, TTSCifTable, TTSNColTable, TTSCollTable, TTSCaptionTable, TTSLNotTable, TTSGuarTable, TTSCodeTable, TTSLendTable, TTSSetupTable, TicklerGlobals; type TExport = class(TThdReportBase) private ExportFileName, LoanFileName, MastFileName, PropFileName, TitmFileName, TnotFileName, HitmFileName, CnotFileName, LnotFileName, TrakFileName : string; HitmFile, TNotFile, CNotFile, TitmFile, LNotFile, PropFile, LoanFile, MastFile, ExportFile, TrakFile : TextFile; CollList : TStringList; ColNumList : TStringList; NotesList : TStringList; LendInfo : TLenderInfoRecord; tblLend : TTTSLendTable; tblLoan : TTTSLoanTable; tblCif : TTTSCifTable; tblNCol : TTTSNColTable; tblTitm : TTTSTitmTable; tblCode : TTTSCodeTable; tblColl : TTTSCollTable; tblSetup : TTTSSETUPTable; tblHitm : TTTSHitmTable; tblTrak : TTTSTRAKTable; FExportCatSet: TExportCatSet; procedure DoLoanExport(CifFlag:string); function ExportSingleTest: boolean; procedure Expt(s: string; l: integer); procedure ExptEnd; function DCLoanRec: string; function DcTrackedItem(CifFlag:string;xtndFmt: boolean): string; function DCHistory(xtndFmt: boolean): string; function FldString(fld: TField; Last: boolean=false): string; procedure SpecialExportItemTest(cifFlag, LoanCifNumber:string); procedure ScanCifs; procedure ScanLoans; procedure ExportTrakTable; procedure CifCsv; procedure LoanCsv; procedure PropCsv; procedure StdTitmCsv(ACifFlag, ALoanCif:string); function DCCifRec: string; function DCPropRec: string; function DCComakerRec: string; procedure WriteLoanCifNoteRecord(rtype, LoanCifNumber, ANotes: string); procedure WriteTrackedNoteRecord; procedure TNotCsv; procedure CNotCsv(ACifFlag, ALoanCif: string); procedure HitmCSV(ACifFlag, ALoanCif: string); procedure LNotCsv(ACifFlag, ALoanCif: string); procedure DoMPSLoanExport(CifFlag: string); function DCMPSLoanRec: string; function DCMPSPropRec: string; function DCMPSTrackedItem(CifFlag: string; xtndFmt: boolean): string; protected procedure Execute; override; public constructor create(ARptID:integer;DoOnTerminate:TNotifyEvent); reintroduce; destructor Destroy;override; end; implementation { division field option division field FLOOD flood option OFF remove the map/panel, map effective date, and flood zone } uses FileCtrl, FFSUtils, sysutils, ReportTests, StrUtils, ProgramSettings, ReportGen; const LoanMax = 26; CifMax = 23; StdTitmMax = 13; HitmMax = 12; PropMax = 11; PropMaxSansFlood = 07; TNotMax = 7; LNotMax = 3; CNotMax = 3; TrakMax = 9; ExtTitmMax = 6; EscTitmMax = 8; LoanHeaders : array[1..LoanMax] of string = ('LoanNumber','CifNumber','Branch','Division','Balance','LoanDate', 'MaturityDate','PaidDate','Name1','Name2','FName1','FName2','Addr1', 'Addr2','City','State','Zip','Phone','LetterName','Agent', 'Agent Addr1','Agent Addr2','Agent Addr3','Officer','HoldNoticeFlag','Dept'); CifHeaders : array[1..CifMax] of string = ('CifNumber','Name1','Name2','First1','First2','Addr1','Addr2','City', 'State','Zip','Phone','LetterName','Branch','Officer','Division','Dept', 'DirectDebt','IndirectDebt','ActiveFlag','HoldNoticeFlag','CustomerCode', 'Relationship1','Relationship2'); StdTitmHeaders : array[1..StdTitmMax] of string = ('LoanCifNumber','Category','SubNumber','Description','Reference', 'ExpireDate','NoticeDate','NoticeNumber','UserName','DateStamp', 'CollRecord','LoanCifInd','AgentCode'); ExtTitmHeaders : array[1..ExtTitmMax] of string = ('NoticeCycle','ScanDate','UserId','BatchDatestamp','UtlUserID','UtlBatchDateStamp'); EscTitmHeaders : array[1..EscTitmMax] of string = ('Filler','PayeeCode','Filler','PremDueDate','Filler','Coverage','Premium','Filler'); PropHeaders : array[1..PropMax] of string = ('LoanNumber','PropNumber','ItemNumber','CollDesc','CollCode','Value1','ReleaseDate','MapPanelNum','MapEffDate', 'FloodZone','Value2'); HitmHeaders : array[1..HitmMax] of string = ('LoanNumber','Category','SubNumber','HistoryNum','Description','Reference','ExpireDate','NoticeDate','NoticeNum','UserName','DateStamp','LoanCifInd'); TNotHeaders : array[1..TNotMax] of string = ('LoanNumber','Category','Collnum','SubNumber','LineNumber','Line','LoanCifInd'); LNotHeaders : array[1..LNotMax] of string = ('LoanNumber','LineNumber','Line'); CNotHeaders : array[1..CNotMax] of string = ('CifNumber','LineNumber','Line'); TrakHeaders : array[1..TrakMax] of string = ('Code','Description','PrintNotify','NotifyLead','PrintOfficer','OfficerLead','LastScanDate','LastTotal','PushToHistory'); // LoanFields : array[1..LoanMax] of string = ('LoanNumber','CifNum','Branch','Division','Balance','OpenDate','MaturityDate', // 'PaidOutDate','Name1','Name2','Addr1','Addr2','City','State','Zip','Phone','LetterName', // 'Agent','AgentAddr1','AgentAddr2','AgentAddr3','Officer','CollCode','Active','HoldNotice', // 'DirectDebt','IndirectDebt'); // TitmFields : array[1..TitmMax] of string = ('LoanNumber','TrackCode','SubNum','Description','Reference','ExpireDate','NoticeDate','NoticeNum','UserName','DateStamp'); // HitmFields : array[1..HitmMax] of string = ('LoanNumber','TrackCode','SubNum','HistoryNum','Description','Reference','ExpireDate','NoticeDate','NoticeNum','UserName','DateStamp'); // AcolFields : array[1..AcolMax] of string = ('LoanNumber','ActCollNum','Description'); // delim = ','; constructor TExport.create(ARptID:integer;DoOnTerminate: TNotifyEvent); begin inherited create(ARptID, DoOnTerminate); CollList := TStringList.Create; NotesList := TStringList.create; ColNumList := TStringList.create; MakeDirs([drExport]); // make sure the export directory exists tblLend := TTTSLENDTable.create(pSession, dbase, 'LEND'); tblLoan := TTTSLOANTable.create(pSession, dbase, 'LOAN'); tblCif := TTTSCIFTable.create(pSession, dbase, 'CIF'); tblNCol := TTTSNCOLTable.create(pSession, dbase, 'NCOL'); tblTitm := TTTSTITMTable.create(pSession, dbase, 'TITM'); tblColl := TTTSCollTable.create(pSession, dbase, 'COLL'); tblCode := TTTSCodeTable.create(pSession, dbase, 'CODE'); tblHitm := TTTSHitmTable.create(pSession, dbase, 'HITM'); tblSetup := TTTSSETUPTable.create(pSession, dbase, 'SETUP'); tblTrak := TTTSTrakTable.create(pSession, dbase, 'TRAK'); ColNumList.Sorted := True; ColNumList.Duplicates := dupIgnore; Resume; PropHeaders[8] := CurrentLend.capValue1; end; procedure TExport.ScanCifs; var PODate: Boolean; begin tblCif.First; while (not tblCif.eof) and (not FAbortProcess) do begin ScanOne; try HoldNoticeTest(RptOptions, tblLoan.PHoldNotice); CifTest(RptOptions, tblCif.PDirectDebt, tblCif.PIndirectDebt, tblCif.PActive, PODate); // BalanceTest(RptOptions, tblCif.PDirectDebt); BalanceTest(RptOptions, tblCif.PDirectDebt + tblCif.PIndirectDebt); NotesTest(RptOptions, trim(tblCif.dfNotes.value) > ''); OfficerTest(RptOptions, tblCif.POfficer, tblCode); BranchTest(RptOptions, tblCif.PBranch, tblCode); DivisionTest(RptOptions, tblCif.PDivision, LendInfo.DivisionEnabled, tblCode); CustCodeTest(RptOptions, tblCif.PCustCode, tblColl); ColNumList.Clear; ColNumList.Add('1'); if (RptOptions.ExpCatFormat = 1) then SpecialExportItemTest('Y', tblCif.PCifNumber) else TrackedItemTest(RptOptions, tblTitm, FlagCif, tblCif.PCifNumber,ColNumList); DepartmentTest(RptOptions, tblCif.PDept, tblCode); FoundOne; case TExpFormat(RptOptions.ExpFormat) of fmtCsv, fmtCsvHead : begin CifCsv; if rptOptions.ExpTracked then StdTitmCsv('Y',tblCif.PCifNumber); if rptOptions.ExpCifNotes then CNotCsv('Y', tblCif.PCifNumber); // if rptOptions.ExpTrackedNotes then CNotCsv('Y', tblCif.PCifNumber); if rptOptions.ExpTrackedHist then HitmCSV('Y', tblCif.PCifNumber); end; fmtDataCaddy : DoLoanExport('Y'); fmtMpsCaddy : DoMPSLoanExport('Y'); end; except // do nothing if the loan doesn't pass all tests end; tblCif.Next; end; end; procedure TExport.ScanLoans; begin tblLoan.First; while (not tblLoan.eof) and (not FAbortProcess) do begin ScanOne; try HoldNoticeTest(RptOptions, tblLoan.PHoldNotice); PaidoutTest(RptOptions, tblLoan.PPaidOutDate); BalanceTest(RptOptions, tblLoan.PBalance); MaturityTest(RptOptions, tblLoan.PMaturityDate); OpenDateTest(RptOptions, tblLoan.POpenDate); NotesTest(RptOptions, trim(tblLoan.dfNotes.Value) > ''); OfficerTest(RptOptions, tblLoan.POfficer, tblCode); BranchTest(RptOptions, tblLoan.PBranch, tblCode); DivisionTest(RptOptions, tblLoan.PDivision, LendInfo.DivisionEnabled, tblCode); DepartmentTest(RptOptions, tblLoan.PDept, tblCode); CollList.Clear; ColNumList.Clear; tblNCol.SetRange([tblLoan.PLenderNum, tblLoan.PLoanNum],[tblLoan.PLenderNum, tblLoan.PLoanNum]); tblNCol.first; while not tblNCol.eof do begin CollList.Add(tblNCol.PCollCode); ColNumList.Add(inttoStr(tblNCol.PCollNum)); tblNCol.next; end; tblNCol.CancelRange; CollCodeTest(RptOptions, CollList, tblColl); if TExpFormat(RptOptions.ExpFormat) = fmtMpsCaddy then SpecialExportItemTest('N', tblLoan.PLoanNum) else if (RptOptions.ExpCatFormat = 1) then SpecialExportItemTest('N', tblLoan.PLoanNum) else TrackedItemTest(RptOptions, tblTitm, FlagLoan, tblLoan.PLoanNum,ColNumList); FoundOne; case TExpFormat(RptOptions.ExpFormat) of fmtCsv, fmtCsvHead : begin LoanCsv; PropCsv; if rptOptions.ExpTracked then StdTitmCsv('N',tblLoan.PLoanNum); if rptOptions.ExpLoanNotes then LNotCsv('N',tblLoan.PLoanNum); if rptOptions.ExpTrackedHist then HitmCSV('N',tblLoan.PLoanNum); end; fmtDataCaddy : DoLoanExport('N'); fmtMpsCaddy : DoMPSLoanExport('N'); end; except // do nothing if the loan doesn't pass all tests end; tblLoan.Next; end; end; function TExport.DCMPSLoanRec: string; begin result := 'LA' // Loan Add + rjust(tblLoan.PLoanNum, 20) + ljust(tblLoan.PName1, 40) + ljust(tblLoan.PFirstName1, 20) + ljust(tblLoan.PName2, 40) + ljust(tblLoan.PFirstName2, 20) + ljust(tblLoan.PAddr1, 40) + ljust(tblLoan.PAddr2, 40) + ljust(tblLoan.PCity, 25) + ljust(tblLoan.PState, 2) + ljust(tblLoan.PZip, 10) + ljust(tblLoan.PPhone, 40) + ljust(tblLoan.PLetterName, 40) + ljust(tblLoan.PBranch, 8) + ljust(tblLoan.PDivision, 8) + ljust(tblLoan.PDept, 8) + ljust(tblLoan.POfficer, 6) + ljust(StripChar('/', tblLoan.POpenDate), 8) + ljust(StripChar('/', tblLoan.PMaturityDate), 8) + ljust(StripChar('/', tblLoan.PPaidOutDate), 8) + rjust(CurrToStr(tblLoan.PBalance), 15) + ljust(tblLoan.PCifNum, 20) + ljust(booltoyn(tblLoan.PHoldNotice), 1); end; function TExport.DCLoanRec: string; begin result := 'LA' // Loan Add + rjust(tblLoan.PLoanNum, 20) + ljust(tblLoan.PName1, 40) + ljust(tblLoan.PFirstName1, 20) + ljust(tblLoan.PName2, 40) + ljust(tblLoan.PFirstName2, 20) + ljust(tblLoan.PAddr1, 40) + ljust(tblLoan.PAddr2, 40) + ljust(tblLoan.PCity, 25) + ljust(tblLoan.PState, 2) + ljust(tblLoan.PZip, 10) + ljust(tblLoan.PPhone, 40) + ljust(tblLoan.PLetterName, 40) + ljust(tblLoan.PBranch, 8) + ljust(tblLoan.PDivision, 8) + ljust(tblLoan.PDept, 8) + ljust(tblLoan.POfficer, 6) + ljust(StripChar('/', tblLoan.POpenDate), 8) + ljust(StripChar('/', tblLoan.PMaturityDate), 8) + ljust(StripChar('/', tblLoan.PPaidOutDate), 8) + rjust(CurrToStr(tblLoan.PBalance), 15) + ljust(tblLoan.PCifNum, 20) + ljust(booltoyn(tblLoan.PHoldNotice), 1); end; function TExport.DCCifRec: string; begin result := 'MA' // Loan Add + rjust(tblCif.PCifNumber, 20) + ljust(tblCif.PName1, 40) + ljust(tblCif.PFirstName1, 20) + ljust(tblCif.PName2, 40) + ljust(tblCif.PFirstName2, 20) + ljust(tblCif.PAddr1, 40) + ljust(tblCif.PAddr2, 40) + ljust(tblCif.PCity, 25) + ljust(tblCif.PState, 2) + ljust(tblCif.PZip, 10) + ljust(tblCif.PPhone, 40) + ljust(tblCif.PLetterName, 40) + ljust(tblCif.PBranch, 8) + ljust(tblCif.PDivision, 8) + ljust(tblCif.PDept, 8) + ljust(tblCif.POfficer, 6) + rjust(CurrToStr(tblCif.PDirectDebt), 15) + ljust(tblCif.PCustCode, 8) + ljust(tblCif.PDesc1, 60) + ljust(tblCif.PDesc2, 60) + ljust(tblCif.PActive, 1) + ljust(booltoyn(tblLoan.PHoldNotice), 1); end; function TExport.DCMPSTrackedItem(CifFlag:string;xtndFmt: boolean): string; begin result := 'TN' // tracked new + rjust(tblTitm.PLoanCif, 20) + rjust(inttostr(tblTitm.PCollNum),3) + ljust(iif(cifflag = 'Y', 'M', 'L'),1) + ljust(tblTitm.PTrackCode,8) + rjust(inttostr(tblTitm.PSubNum),3) + ljust(tblTitm.PDescription, 25) + ljust(tblTitm.PReference, 25) + ljust(stripchar('/',tblTitm.PExpireDate),8) + ljust(tblTitm.PAgentID,8); if xtndFmt then begin // result := result // + ljust(tblTitm.PNoticeNum,1) // + ljust(stripchar('/',tblTitm.PNoticeDate),8) // + ljust(tblTitm.PUserName,10) // + ljust(stripchar('/',copy(tblTitm.PDateStamp,1,10)),8) // + CrunchTime(copy(tblTitm.PDateStamp,12,6)) // + ljust(tblTitm.PUTLUserName, 10) // + ljust(stripchar('/',copy(tblTitm.PUTLDateStamp,1,10)),8) // + CrunchTime(copy(tblTitm.PUtlDateStamp,12,6)); // if LendInfo.EscrowEnabled then begin // result := result // + space(1) // + ljust(tblTitm.PPayeeCode,8) // + space(8) // + ljust(stripchar('/',tblTitm.PPremDueDate),8) // + space(28) // + rjust(currtostr(tblTitm.PCovAmt),15) // + rjust(currtostr(tblTitm.PPremAmt),15) // + space(45); // end end; end; function TExport.DcTrackedItem(CifFlag:string;xtndFmt: boolean): string; begin result := 'TN' // tracked new + rjust(tblTitm.PLoanCif, 20) + rjust(inttostr(tblTitm.PCollNum),3) + ljust(iif(cifflag = 'Y', 'M', 'L'),1) + ljust(tblTitm.PTrackCode,8) + rjust(inttostr(tblTitm.PSubNum),3) + ljust(tblTitm.PDescription, 25) + ljust(tblTitm.PReference, 25) + ljust(stripchar('/',tblTitm.PExpireDate),8) + ljust(tblTitm.PAgentID,8); if xtndFmt then begin result := result + ljust(tblTitm.PNoticeNum,1) + ljust(stripchar('/',tblTitm.PNoticeDate),8) + ljust(tblTitm.PUserName,10) + ljust(stripchar('/',copy(tblTitm.PDateStamp,1,10)),8) + ljust(CrunchTime(copy(tblTitm.PDateStamp,12,6)),4) + ljust(tblTitm.PUTLUserName, 10) + ljust(stripchar('/',copy(tblTitm.PUTLDateStamp,1,10)),8) + ljust(CrunchTime(copy(tblTitm.PUtlDateStamp,12,6)),4); if LendInfo.EscrowEnabled then begin result := result + space(1) + ljust(tblTitm.PPayeeCode,8) + space(8) + ljust(stripchar('/',tblTitm.PPremDueDate),8) + space(28) + rjust(currtostr(tblTitm.PCovAmt),15) + rjust(currtostr(tblTitm.PPremAmt),15) + space(45); end end; end; function TExport.DCMPSPropRec:string; begin result := 'PM' + ljust(tblNCol.PLenderNum, 4) + rjust(tblNCol.PLoanNum, 20) + rjust(inttostr(tblNCol.PCollNum),3) + ljust(tblNCol.PLookup, 15) + ljust(tblNCol.PCollCode, 8) + rjust(CurrToStr(tblNcol.PValue1),15) + rjust(CurrToStr(tblNcol.PValue2),15) + ljust(tblNCol.PCity, 25) + ljust(tblNCol.PState, 2) + ljust(tblNCol.PZip, 10) + ljust(stripchar('/', tblNCol.PReleaseDate),8) + ljust(booltoyn(tblNCol.PDataCaddyChgCode), 1) + ljust(tblNCol.PFloodZone, 4) + ljust(tblNCol.PBaseFloodElev, 4) + ljust(tblNCol.PLowestFloor, 2) + ljust(tblNCol.PPropKey, 20) + ljust(booltoyn(tblNCol.PCondoFlag), 1) + ljust(tblNCol.PCertNumber, 15) + ljust(tblNCol.PConstDate, 10) + ljust(tblNCol.PMapPanel, 20) + ljust(tblNCol.PCommNumber, 15) + ljust(booltoyn(tblNCol.PPostFirm), 1) + ljust(inttostr(tblNCol.PPercentTotal), 3) + ljust(booltoyn(tblNCol.PBasement), 1) + ljust(tblNCol.PDwellType, 1) + ljust(tblNCol.PCountyCode, 3) + ljust(tblNCol.PVacantOcc, 1) + ljust(tblNCol.PLienPos, 2) + ljust(tblNCol.PMapEffDate, 10) + ljust(tblNCol.PDesc1, 60) + ljust(tblNCol.PDesc2, 60) + ljust(tblNCol.PDesc3, 60) + ljust(tblNCol.PDesc4, 60); end; function TExport.DCPropRec:string; begin result := 'PA' + rjust(tblNCol.PLoanNum, 20) + rjust(inttostr(tblNCol.PCollNum),3) + ljust(tblNcol.PCollCode, 8) + ljust(tblNCol.PDesc1, 60) + ljust(tblNCol.PDesc2, 60) + ljust(tblNCol.PDesc3, 60) + ljust(tblNCol.PDesc4, 60) + rjust(CurrToStr(tblNcol.PValue1),15) + rjust(CurrToStr(tblNcol.PValue2),15) + ljust(stripchar('/', tblNCol.PReleaseDate),8); end; function TExport.DCComakerRec:string; begin result := 'La' + RJust(tblLoan.PLoanNum, 20) + LJust(tblLoan.PMisc1, 40) + LJust(tblLoan.PMisc2, 40) + LJust(tblLoan.PMisc3, 40) + LJust(tblLoan.PMisc4, 40); end; procedure TExport.WriteLoanCifNoteRecord(rtype, LoanCifNumber, ANotes:string); var x,y : integer; s : string; linecount : integer; begin NotesList.Clear; NotesList.Text := ANotes; for x := 0 to NotesList.Count - 1 do begin y := 1; linecount := 0; while y < length(NotesList[x]) do begin if x = 0 then s := rtype + 'I' + RJust(LoanCifNumber,20) else s := rtype + 'I'; inc(linecount); s := s + rjust(inttostr(linecount),3) + copy(NotesList[x], y, 70) + iif((x < NotesList.count-1) and (y+70 >= length(NotesList[x])), 'Y','N') + iif(y+70 < length(NotesList[x]), 'Y','N'); writeln(ExportFile, s); inc(y,70); end; end; end; function TExport.DCHistory(xtndFmt: boolean):string; begin result := 'TH' // tracked History + rjust(tblHitm.PLoanCif, 20) + rjust(inttostr(tblHitm.PCollNum),3) + ljust(iif(tblHitm.PCifFlag = 'Y', 'M', 'L'),1) + ljust(tblHitm.PTrackCode,8) + rjust(inttostr(tblHitm.PSubNum),3) + ljust(tblHitm.PDescription, 25) + ljust(tblHitm.PReference, 25) + ljust(stripchar('/',tblHitm.PExpireDate),8) + ljust(tblHitm.PAgentID,8); if xtndFmt then begin result := result + ljust(tblHitm.PNoticeNum,1) + ljust(stripchar('/',tblHitm.PNoticeDate),8) + ljust(tblHitm.PUserName,10) + ljust(stripchar('/',copy(tblHitm.PDateStamp,1,10)),8) + ljust(CrunchTime(copy(tblHitm.PDateStamp,12,6)),4) + ljust(tblHitm.PUTLUserName, 10) + ljust(stripchar('/',copy(tblHitm.PUTLDateStamp,1,10)),8) + ljust(CrunchTime(copy(tblHitm.PUtlDateStamp,12,6)),4); if LendInfo.EscrowEnabled then begin result := result + space(1) + ljust(tblHitm.PPayeeCode,8) + space(8) + ljust(stripchar('/',tblHitm.PPremDueDate),8) + space(28) + rjust(currtostr(tblHitm.PCovAmt),15) + rjust(currtostr(tblHitm.PPremAmt),15) + space(45); end end; end; procedure TExport.DoMPSLoanExport(CifFlag:string); var //s : string; DoTheItem : boolean; first : boolean; begin // output loan record writeln(ExportFile, DCMPSLoanRec); // output property record tblTitm.SetRange([lendinfo.Number, CifFlag, tblLoan.PLoanNum],[lendinfo.Number, CifFlag, tblLoan.PLoanNum]); tblTitm.first; first := true; while not tblTitm.eof do begin if RptOptions.ShowOnlySelected then begin //DoTheItem := false; try DoTheItem := ExportSingleTest; // TICategoryTest(RptOptions, tblTitm.PTrackCode); //DoTheItem := true; except DoTheItem := false; end; end else DoTheItem := true; if DoTheItem then begin if not first then writeln(ExportFile, DCMPSLoanRec); if tblNCol.FindKey([lendinfo.Number, tblLoan.PLoanNum, tblTitm.PCollNum ]) then begin first := false; writeln(ExportFile, DCMPSPropRec); // output tracked item record Writeln(ExportFile, DCMPSTrackedItem(CifFlag, RptOptions.ExpTrackedExtend)); end; //TNotCsv; end; tblTitm.next; end; end; procedure TExport.DoLoanExport(CifFlag:string); var notes : string; hitmcount : integer; DoTheItem : boolean; begin // now based on selected info on what to export if RptOptions.IncLoans or RptOptions.IncActiveCifs then begin if CifFlag = 'Y' then begin writeln(ExportFile, dcCifRec); if RptOptions.ExpCifNotes then begin notes := tblCif.DFNotes.Value; if not empty(notes) then WriteLoanCifNoteRecord(CifFlag, tblCif.PCifNumber, Notes); end; end else begin writeln(ExportFile, dcLoanRec); // check for agent/comaker/misc info if TExpFormat(RptOptions.ExpFormat) <> fmtMPSCaddy then begin if (empty(tblloan.PMisc1) and empty(tblLoan.PMisc2) and empty(tblLoan.PMisc3) and empty(tblLoan.PMisc4)) then // do nothing else writeln(exportfile, DCComakerRec); end; // Notes if RptOptions.ExpLoanNotes then begin notes := tblLoan.DFNotes.Value; if not empty(notes) then WriteLoanCifNoteRecord(CifFlag, tblLoan.PLoanNum, Notes); end; tblNcol.SetRange([tblLoan.PLenderNum, tblLoan.PLoanNum],[tblLoan.PLenderNum, tblLoan.PLoanNum]); tblNcol.First; while not tblNcol.eof do begin writeln(ExportFile, DCPropRec); tblNcol.Next; end; tblNcol.CancelRange; end; end; if RptOptions.ExpTracked then begin if cifflag = 'Y' then tblTitm.SetRange([LendInfo.Number, cifflag, tblCif.PCifNumber],[LendInfo.Number, CifFlag, tblCif.PCifNumber]) else tblTitm.SetRange([LendInfo.Number, cifflag, tblLoan.PLoanNum],[LendInfo.Number, CifFlag, tblLoan.PLoanNum]); tblTitm.First; while not tblTitm.Eof do begin DoTheItem := true; if RptOptions.ShowOnlySelected then begin //DoTheItem := false; if TExpFormat(RptOptions.ExpFormat) = fmtMpsCaddy then DoTheItem := ExportSingleTest else begin try TICategoryTest(RptOptions, tblTitm.PTrackCode); DoTheItem := true; except DoTheItem := false; end; end; end; if DoTheItem then begin Writeln(ExportFile, DCTrackedItem(CifFlag, RptOptions.ExpTrackedExtend)); if RptOptions.ExpTrackedNotes then WriteTrackedNoteRecord; if RptOptions.ExpTrackedHist then begin tblHitm.SetRange([tblTitm.PLenderNum, tblTitm.PCifFlag, tblTitm.PLoanCif, tblTitm.PCollNum, tblTitm.PTrackCode, tblTitm.PSubNum],[tblTitm.PLenderNum, tblTitm.PCifFlag, tblTitm.PLoanCif, tblTitm.PCollNum, tblTitm.PTrackCode, tblTitm.PSubNum]); hitmcount := tblHitm.recordCount; tblHitm.Last; while hitmcount > 0 do begin writeln(ExportFile, DCHistory(RptOptions.ExpTrackedExtend)); tblHitm.Prior; dec(hitmcount); end; tblHitm.CancelRange; end; end; tblTitm.next; end; end; end; function TExport.FldString(fld: TField; Last: boolean): string; var s : string; begin if fld.DataType = ftBoolean then s := BoolToYN(fld.AsBoolean) else s := fld.AsString; result := CsvQuote(s) + iif(last, ',',''); end; procedure TExport.HitmCSV(ACifFlag, ALoanCif:string); var s : string; begin tblHitm.SetRange([lendinfo.Number, ACifFlag, ALoanCif],[lendinfo.Number, ACifFlag, ALoanCif]); tblHitm.first; while not tblHitm.eof do begin s := CsvQuote(tblHitm.PLoanCif) + ',' // LoanNumber + CsvQuote(tblHitm.PTrackCode) + ',' // Category? + CsvQuote(IntToStr(tblHitm.PSubNum)) + ',' // SubNumber + CsvQuote(IntToStr(tblHitm.PHistoryNum)) + ',' // HistoryNum + CsvQuote(tblHitm.PDescription) + ',' // Description + CsvQuote(tblHitm.PReference) + ',' // Reference + CsvQuote(tblHitm.PExpireDate) + ',' // ExpireDate + CsvQuote(tblHitm.PNoticeDate) + ',' // NoticeDate + CsvQuote(tblHitm.PNoticeNum) + ',' // NoticeNum + CsvQuote(tblHitm.PUserName) + ',' // UserName + CsvQuote(tblHitm.PDateStamp) + ',' // DateStamp + CsvQuote(iif(tblHitm.PCifFlag='Y','M','L')); if RptOptions.ExpTrackedExtend then begin s := s + ',' + CsvQuote(tblHitm.PNoticeNum) + ',' + CsvQuote(tblHitm.PNoticeDate) + ',' + CsvQuote(tblHitm.PUserName) + ',' + CsvQuote(tblHitm.PDateStamp) + ',' + CsvQuote(tblHitm.PUTLUserName) + ',' + CsvQuote(tblHitm.PUTLDateStamp); if LendInfo.EscrowEnabled then begin s := s + ',' + CsvQuote(' ') + ',' + CsvQuote(tblHitm.PPayeeCode) + ',' + CsvQuote(space(8)) + ',' + CsvQuote(tblHitm.PPremDueDate) + ',' + CsvQuote(space(28)) + ',' + CsvQuote(currtostr(tblHitm.PCovAmt)) + ',' + CsvQuote(currtostr(tblHitm.PPremAmt)) + ',' + CsvQuote(space(45)); end; end; writeln(HitmFile, s); tblHitm.next; end; end; procedure TExport.TNotCsv; var s : string; sl : TStringList; i : integer; begin sl := TStringList.Create; sl.Text := tblTitm.DFTrackedNotes.Value; for i:=1 to sl.Count do begin s := //Field Name? CsvQuote(tblTitm.PLoanCif) + ',' //LoanNumber + CsvQuote(tblTitm.PTrackCode) + ',' //Category? + CsvQuote(IntToStr(tblTitm.PCollNum)) + ',' //collnum + CsvQuote(IntToStr(tblTitm.PSubNum)) + ',' //SubNumber + CsvQuote(IntToStr(i)) + ',' //LineNumber + CsvQuote(sl[i-1]) + ',' //Line + CsvQuote(iif(tblTitm.PCifFlag='Y','M','L')); writeln(TNotFile, s); end; sl.Free; end; procedure TExport.LNotCsv(ACifFlag, ALoanCif:string); var s : string; sl : TStringList; i : integer; begin sl := TStringList.Create; if ACifFlag='Y' then tblLoan.EnumIndex := TTSLOANbyCif; tblLoan.FindKey([lendinfo.Number, ALoanCif]); sl.Text := tblLoan.DFNotes.Value; for i:=1 to sl.Count do begin s := CsvQuote(tblLoan.PLoanNum) + ',' //LoanNumber + CsvQuote(IntToStr(i)) + ',' //LineNumber + CsvQuote(sl[i-1]); //Line writeln(LNotFile, s); end; sl.Free; tblLoan.EnumIndex := TTSLOANPrimaryKey; end; procedure TExport.CifCsv; var s : string; begin s := CsvQuote(tblCif.PCifNumber) + ',' + CsvQuote(tblCif.PName1) + ',' + CsvQuote(tblCif.PName2) + ',' + CsvQuote(tblCif.PFirstName1) + ',' + CsvQuote(tblCif.PFirstName2) + ',' + CsvQuote(tblCif.PAddr1) + ',' + CsvQuote(tblCif.PAddr2) + ',' + CsvQuote(tblCif.PCity) + ',' + CsvQuote(tblCif.PState) + ',' + CsvQuote(tblCif.PZip) + ',' + CsvQuote(tblCif.PPhone) + ',' + CsvQuote(tblCif.PLetterName) + ',' + CsvQuote(tblCif.PBranch) + ',' + CsvQuote(tblCif.POfficer) + ',' + CsvQuote(tblCif.PDivision) + ',' + CsvQuote(tblCif.PDept) + ',' + CsvQuote(CurrToStr(tblCif.PDirectDebt)) + ',' + CsvQuote(CurrToStr(tblCif.PIndirectDebt)) + ',' + CsvQuote(tblCif.PActive) + ',' + CsvQuote(booltoyn(tblCif.PHoldNotice)) + ',' + CsvQuote(tblCif.PCustCode) + ',' + CsvQuote(tblCif.PDesc1) + ',' + CsvQuote(tblCif.PDesc2); Writeln(MastFile, s); end; procedure TExport.LoanCsv; var s : string; begin s := CsvQuote(tblLoan.PLoanNum) + ',' + CsvQuote(tblLoan.PCifNum) + ',' + CsvQuote(tblLoan.PBranch) + ',' + CsvQuote(tblLoan.PDivision) + ',' + CsvQuote(currtostr(tblLoan.PBalance)) + ',' + CsvQuote(tblLoan.POpenDate) + ',' + CsvQuote(tblLoan.PMaturityDate) + ',' + CsvQuote(tblLoan.PPaidOutDate) + ',' + CsvQuote(tblLoan.PName1) + ',' + CsvQuote(tblLoan.PName2) + ',' + CsvQuote(tblLoan.PFirstName1) + ',' + CsvQuote(tblLoan.PFirstName2) + ',' + CsvQuote(tblLoan.PAddr1) + ',' + CsvQuote(tblLoan.PAddr2) + ',' + CsvQuote(tblLoan.PCity) + ',' + CsvQuote(tblLoan.PState) + ',' + CsvQuote(tblLoan.PZip) + ',' + CsvQuote(tblLoan.PPhone) + ',' + CsvQuote(tblLoan.PLetterName) + ',' + CsvQuote(tblLoan.PMisc1) + ',' + CsvQuote(tblLoan.PMisc2) + ',' + CsvQuote(tblLoan.PMisc3) + ',' + CsvQuote(tblLoan.PMisc4) + ',' + CsvQuote(tblLoan.POfficer) + ',' + CsvQuote(booltoyn(tblLoan.PHoldNotice)) + ',' + CsvQuote(tblLoan.PDept); writeln(LoanFile, s); end; procedure TExport.PropCsv; var i : integer; s : string; sl : TStringList; begin tblNCol.SetRange([lendInfo.Number, tblLoan.PLoanNum], [lendInfo.Number, tblLoan.PLoanNum]); tblNCol.First; while not tblNcol.eof do begin if tblNcol.PDesc1<>'' then begin s := CsvQuote(tblNcol.PLoanNum) + ',' + CsvQuote(inttostr(tblNcol.PCollNum)) + ',' + CsvQuote(IntToStr(1)) + ',' + CsvQuote(tblNcol.PDesc1) + ',' // 'CollRecord' // Drop as per bill + CsvQuote(tblNcol.PCollCode) + ',' + CsvQuote(currtostr(tblNcol.PValue1)) + ',' + CsvQuote(tblNcol.PReleaseDate); if LendInfo.FloodEnabled then s := s + ',' + CsvQuote(tblNcol.PMapPanel) + ',' + CsvQuote(tblNcol.PMapEffDate) + ',' + CsvQuote(tblNcol.PFloodZone) + ',' + CsvQuote(currtostr(tblNcol.PValue2)); writeln(PropFile, s); end; if tblNcol.PDesc2<>'' then begin s := CsvQuote(tblNcol.PLoanNum) + ',' + CsvQuote(inttostr(tblNcol.PCollNum)) + ',' + CsvQuote(IntToStr(2)) + ',' + CsvQuote(tblNcol.PDesc2) + ',' // 'CollRecord' // Drop as per bill + CsvQuote(tblNcol.PCollCode) + ',' + CsvQuote(currtostr(tblNcol.PValue1)) + ',' + CsvQuote(tblNcol.PReleaseDate); if LendInfo.FloodEnabled then s := s + ',' + CsvQuote(tblNcol.PMapPanel) + ',' + CsvQuote(tblNcol.PMapEffDate) + ',' + CsvQuote(tblNcol.PFloodZone) + ',' + CsvQuote(currtostr(tblNcol.PValue2)); writeln(PropFile, s); end; if tblNcol.PDesc3<>'' then begin s := CsvQuote(tblNcol.PLoanNum) + ',' + CsvQuote(inttostr(tblNcol.PCollNum)) + ',' + CsvQuote(IntToStr(3)) + ',' + CsvQuote(tblNcol.PDesc3) + ',' // 'CollRecord' // Drop as per bill + CsvQuote(tblNcol.PCollCode) + ',' + CsvQuote(currtostr(tblNcol.PValue1)) + ',' + CsvQuote(tblNcol.PReleaseDate); if LendInfo.FloodEnabled then s := s + ',' + CsvQuote(tblNcol.PMapPanel) + ',' + CsvQuote(tblNcol.PMapEffDate) + ',' + CsvQuote(tblNcol.PFloodZone) + ',' + CsvQuote(currtostr(tblNcol.PValue2)); writeln(PropFile, s); end; if tblNcol.PDesc4<>'' then begin s := CsvQuote(tblNcol.PLoanNum) + ',' + CsvQuote(inttostr(tblNcol.PCollNum)) + ',' + CsvQuote(IntToStr(4)) + ',' + CsvQuote(tblNcol.PDesc4) + ',' // 'CollRecord' // Drop as per bill + CsvQuote(tblNcol.PCollCode) + ',' + CsvQuote(currtostr(tblNcol.PValue1)) + ',' + CsvQuote(tblNcol.PReleaseDate); if LendInfo.FloodEnabled then s := s + ',' + CsvQuote(tblNcol.PMapPanel) + ',' + CsvQuote(tblNcol.PMapEffDate) + ',' + CsvQuote(tblNcol.PFloodZone) + ',' + CsvQuote(currtostr(tblNcol.PValue2)); writeln(PropFile, s); end; sl := TStringList.Create; sl.Text := tblNcol.DFMoreDesc.AsString; for i:=0 to sl.Count-1 do begin s := CsvQuote(tblNcol.PLoanNum) + ',' + CsvQuote(inttostr(tblNcol.PCollNum)) + ',' + CsvQuote(IntToStr(5+i)) + ',' + CsvQuote(sl[i]) + ',' // 'CollRecord' // Drop as per bill + CsvQuote(tblNcol.PCollCode) + ',' + CsvQuote(currtostr(tblNcol.PValue1)) + ',' + CsvQuote(tblNcol.PReleaseDate); if LendInfo.FloodEnabled then s := s + ',' + CsvQuote(tblNcol.PMapPanel) + ',' + CsvQuote(tblNcol.PMapEffDate) + ',' + CsvQuote(tblNcol.PFloodZone) + ',' + CsvQuote(currtostr(tblNcol.PValue2)); writeln(PropFile, s); end; sl.Free; tblNcol.Next; end; end; procedure TExport.StdTitmCsv(ACifFlag, ALoanCif:string); var s : string; DoTheItem : boolean; begin tblTitm.SetRange([lendinfo.Number, ACifFlag, ALoanCif],[lendinfo.Number, ACifFlag, ALoanCif]); tblTitm.first; while not tblTitm.eof do begin if RptOptions.ShowOnlySelected then begin //DoTheItem := false; try TICategoryTest(RptOptions, tblTitm.PTrackCode); DoTheItem := true; except DoTheItem := false; end; end else DoTheItem := true; if DoTheItem then begin s := CsvQuote(tblTitm.PLoanCif) + ',' + CsvQuote(tblTitm.PTrackCode) + ',' + CsvQuote(inttostr(tblTitm.PSubNum)) + ',' + CsvQuote(tblTitm.PDescription) + ',' + CsvQuote(tblTitm.PReference) + ',' + CsvQuote(tblTitm.PExpireDate) + ',' + CsvQuote(tblTitm.PNoticeDate) + ',' + CsvQuote(tblTitm.PNoticeNum) + ',' + CsvQuote(tblTitm.PUserName) + ',' + CsvQuote(tblTitm.PDateStamp) + ',' + CsvQuote(inttostr(tblTitm.PCollNum)) + ',' + CsvQuote(iif(tblTitm.PCifFlag='Y','M','L')) + ',' + CsvQuote(tblTitm.PAgentID); if RptOptions.ExpTrackedExtend then begin s := s + ',' + CsvQuote(tblTitm.PNoticeNum) + ',' + CsvQuote(tblTitm.PNoticeDate) + ',' + CsvQuote(tblTitm.PUserName) + ',' + CsvQuote(tblTitm.PDateStamp) + ',' + CsvQuote(tblTitm.PUTLUserName) + ',' + CsvQuote(tblTitm.PUTLDateStamp); if LendInfo.EscrowEnabled then begin s := s + ',' + CsvQuote(' ') + ',' + CsvQuote(tblTitm.PPayeeCode) + ',' + CsvQuote(' ') + ',' + CsvQuote(tblTitm.PPremDueDate) + ',' + CsvQuote(' ') + ',' + CsvQuote(currtostr(tblTitm.PCovAmt)) + ',' + CsvQuote(currtostr(tblTitm.PPremAmt)) + ',' + CsvQuote(' '); end; end; writeln(TitmFile, s); TNotCsv; end; tblTitm.next; end; end; procedure TExport.SpecialExportItemTest(cifFlag, LoanCifNumber:string); var pass : boolean; begin //pass := true; tblTitm.EnumIndex := TTSTITMPrimaryKey; tblTitm.SetRange([LendInfo.Number, cifflag, LoanCifNumber],[LendInfo.Number, cifflag, LoanCifNumber]); tblTitm.first; if (tblTitm.RecordCount > 0) then begin if (not RptOptions.IncWithTracked) then pass := false else begin pass := false; while (not tblTitm.eof) and (not pass) do begin Pass := ExportSingleTest; if not pass then tblTitm.Next; end; end; end else pass := RptOptions.IncWOTracked; tblTitm.cancelRange; if not pass then raise exception.create('No pass SpecialExportItemTest'); end; function TExport.ExportSingleTest: boolean; function passcat(n:integer):boolean; var c1, c2, tst : string; stage : string; begin result := true; c1 := FExportCatSet.items[n].CatFrom; c2 := FExportCatSet.items[n].CatTo; tst := padnumeric(tblTitm.PTrackCode,8); if trim(c1) > '' then if tst < c1 then result := false; if trim(c2) > '' then if tst > c2 then result := false; // stage if result then begin stage := FExportCatSet.items[n].NoticeStage; if StrToIntDef(Stage,0) > 0 then if tblTitm.PNoticeNum <> Stage then result := false; end; // Dates if result then begin if (trim(tblTitm.PNoticeDate) > '') or (trim(FExportCatSet.items[n].DateFrom) > '') or (trim(FExportCatSet.items[n].DateTo) > '') then result := DateInRange(tblTitm.PNoticeDate, FExportCatSet.items[n].DateFrom, FExportCatSet.items[n].DateTo); end; end; var x : integer; begin result := true; if FExportCatSet.count = 0 then exit; result := false; for x := 1 to FExportCatSet.count do begin if passcat(x) then begin result := true; break; end; end; end; procedure TExport.Expt(s: string; l: integer); begin if l > 0 then write(ExportFile, LeftStr(trim(s),l)) else write(ExportFile, s); end; procedure TExport.ExptEnd; begin writeln(ExportFile); end; { TExport } procedure TExport.Execute; var x : integer; //fname : string; LoanCifCount : integer; begin { Place thread code here } try tblLend.Open; tblSetup.Open; tblLoan.open; tblCif.Open; tblNCol.open; tblTitm.open; tblColl.open; tblCode.open; tblHitm.open; tblTrak.Open; // Get some settings if not tblLend.FindKey([RptRec.PLenderNum]) then raise exception.Create('Lender Not Found'); LendInfo := LendRecordToLenderInfo(tblSetup.PDefaultLenderOpts, tblLend.GetDataBuffer); ReportRecordToReportOpions(rptRec, OptionList.Text, RptOptions); //tblTrak.open; //tblGuar.open; if (TExpFormat(RptOptions.ExpFormat) = fmtMpsCaddy) or (RptOptions.ExpCatFormat = 1) then begin StringToCatSelect(RptOptions.Categories, FExportCatSet); SortExportTest(FExportCatSet); end; // prepare the output files case TExpFormat(RptOptions.ExpFormat) of fmtDataCaddy, fmtMpsCaddy : begin ExportFileName := Dir(drExport) + 'DATA' + LendInfo.Number + '.TTS'; assignfile(ExportFile, ExportFileName); rewrite(ExportFile); WriteLn(ExportFile,'VERSION 2'); end; //ExportFile := TStringStream.Create(''); fmtCsv, fmtCsvHead : begin LoanFileName := Dir(drExport) + 'LOAN' + LendInfo.Number + '.CSV'; MastFileName := Dir(drExport) + 'MAST' + LendInfo.Number + '.CSV'; PropFileName := Dir(drExport) + 'PROP' + LendInfo.Number + '.CSV'; TitmFileName := Dir(drExport) + 'TITM' + LendInfo.Number + '.CSV'; TnotFileName := Dir(drExport) + 'TNOT' + LendInfo.Number + '.CSV'; HitmFileName := Dir(drExport) + 'HITM' + LendInfo.Number + '.CSV'; LnotFileName := Dir(drExport) + 'LNOT' + LendInfo.Number + '.CSV'; CnotFileName := Dir(drExport) + 'CNOT' + LendInfo.Number + '.CSV'; TrakFileName := Dir(drExport) + 'TRAK' + LendInfo.Number + '.CSV'; { RptOptions.IncLoans LoanFile,PropFile RptOptions.IncActiveCifs MastFile RptOptions.ExpTracked TitmFile RptOptions.ExpTrackedHist HitmFile RptOptions.ExpTrackedNotes LNotFile RptOptions.ExpLoanNotes TNotFile } if RptOptions.IncLoans then begin assignfile(LoanFile, LoanFileName); rewrite(LoanFile); assignfile(PropFile, PropFileName); rewrite(PropFile); end; if RptOptions.IncActiveCifs then begin assignfile(MastFile, MastFileName ); rewrite(MastFile); end; if RptOptions.ExpCifNotes then begin // assignfile(CnotFile, CnotFileName ); // rewrite(CnotFile); end; if RptOptions.ExpTracked then begin assignfile(TitmFile, TitmFileName); rewrite(TitmFile); end; if RptOptions.ExpLoanNotes then begin assignfile(LnotFile, LnotFileName); rewrite(LnotFile); end; if RptOptions.ExpTrackedHist then begin assignfile(HitmFile, HitmFileName); rewrite(HitmFile); end; if RptOptions.ExpTrackedNotes then begin assignfile(TnotFile, TnotFileName); rewrite(TnotFile); end; if RptOptions.ExpCifNotes then begin assignfile(CnotFile, CnotFileName); rewrite(CnotFile); end; if rptOptions.ExpTrakTable then begin assignfile(TrakFile, TrakFileName); rewrite(TrakFile); end; if TExpFormat(RptOptions.ExpFormat) = fmtCsvHead then begin // if RptOptions.IncLoans then begin for x := 1 to LoanMax-1 do write(LoanFile, CsvQuote(LoanHeaders[x])+','); Writeln(LoanFile, CsvQuote(LoanHeaders[LoanMax])); // Collateral is implied with the loan if LendInfo.FloodEnabled then begin for x := 1 to PropMax-1 do write(PropFile, CsvQuote(PropHeaders[x]) + ','); writeln(PropFile, CsvQuote(PropHeaders[PropMax])); end else begin for x := 1 to PropMaxSansFlood-1 do write(PropFile, CsvQuote(PropHeaders[x]) + ','); writeln(PropFile, CsvQuote(PropHeaders[PropMaxSansFlood])); end; end; if RptOptions.IncActiveCifs then begin for x := 1 to CifMax-1 do write(MastFile, CsvQuote(CifHeaders[x])+','); writeln(MastFile, CsvQuote(CifHeaders[CifMax])); end; if RptOptions.ExpTracked then begin for x := 1 to StdTitmMax-1 do write(TitmFile, CsvQuote(StdTitmHeaders[x]) + ','); write(TitmFile, CsvQuote(StdTitmHeaders[StdTitmMax])); if RptOptions.ExpTrackedExtend then begin write(TitmFile,','); for x := 1 to ExtTitmMax-1 do write(TitmFile, CsvQuote(ExtTitmHeaders[x]) + ','); write(TitmFile, CsvQuote(ExtTitmHeaders[ExtTitmMax])); end; if RptOptions.ExpTrackedExtend and LendInfo.EscrowEnabled then begin write(TitmFile,','); for x := 1 to EscTitmMax-1 do write(TitmFile, CsvQuote(EscTitmHeaders[x]) + ','); write(TitmFile, CsvQuote(EscTitmHeaders[x])); end; writeln(TitmFile); end; if RptOptions.ExpTrackedHist then begin for x := 1 to HitmMax-1 do write(HitmFile, CsvQuote(HitmHeaders[x]) + ','); writeln(HitmFile, CsvQuote(HitmHeaders[HitmMax])); end; if RptOptions.ExpTrackedNotes then begin for x := 1 to LNotMax-1 do write(LNotFile, CsvQuote(LNotHeaders[x]) + ','); writeln(LNotFile, CsvQuote(LNotHeaders[LNotMax])); end; if RptOptions.ExpLoanNotes then begin for x := 1 to TNotMax-1 do write(TNotFile, CsvQuote(TNotHeaders[x]) + ','); writeln(TNotFile, CsvQuote(TNotHeaders[TNotMax])); end; if RptOptions.ExpCifNotes then begin for x := 1 to CNotMax-1 do write(CNotFile, CsvQuote(CNotHeaders[x]) + ','); writeln(CNotFile, CsvQuote(CNotHeaders[CNotMax])); end; if rptOptions.ExpTrakTable then begin for x := 1 to TrakMax-1 do write(TrakFile, CsvQuote(TrakHeaders[x]) + ','); writeln(TrakFile, CsvQuote(TrakHeaders[TrakMax])); end; end; end; end; try // Let's get the total count of records first LoanCifCount := 0; if rptOptions.IncLoans then begin tblLoan.SetRange([rptOptions.LenderNumber],[rptOptions.LenderNumber]); inc(LoanCifCount, tblLoan.RecordCount); end; if rptOptions.IncActiveCifs then begin tblCif.SetRange([rptOptions.LenderNumber],[rptOptions.LenderNumber]); inc(LoanCifCount, tblCif.RecordCount); end; // get started FAbortProcess := false; ResetCounter(LoanCifCount); UpdateStatus(rsScan); // get the Cifs first if selected if rptOptions.IncActiveCifs then ScanCifs; if rptOptions.IncLoans then ScanLoans; if rptOptions.ExpTrakTable then ExportTrakTable; finally case TExpFormat(RptOptions.ExpFormat) of fmtDataCaddy, fmtMpsCaddy : begin closefile(ExportFile); UpdateStatus(rsDone,inttostr(GetFoundCount())); end; fmtCsv, fmtCsvHead : begin if RptOptions.IncLoans then begin closefile(LoanFile); closefile(PropFile); end; if RptOptions.IncActiveCifs then Closefile(MastFile); if RptOptions.ExpTracked then CloseFile(TitmFile); if RptOptions.ExpLoanNotes then CloseFile(LnotFile); if RptOptions.ExpTrackedHist then CloseFile(HitmFile); if RptOptions.ExpTrackedNotes then CloseFile(TnotFile); if RptOptions.ExpCifNotes then CloseFile(CnotFile); if rptOptions.ExpTrakTable then CloseFile(TrakFile); // if RptOptions.ExpTrackedHist then zip.ZipFromStream(HitmFile, 'HITM' + RptOptions.LenderNumber + '.CSV'); // if RptOptions.ExpLoanCifNotes then zip.ZipFromStream(LNotFile, 'LNOT' + RptOptions.LenderNumber + '.CSV'); // if RptOptions.ExpTrackedNotes then zip.ZipFromStream(TNotFile, 'TNOT' + RptOptions.LenderNumber + '.CSV'); UpdateStatus(rsDone); end; end; end; except on e:exception do UpdateStatus(rsProblem,e.Message); end; end; destructor TExport.Destroy; begin NotesList.free; CollList.Free; ColNumList.Free; inherited; end; procedure TExport.WriteTrackedNoteRecord; var x,y : integer; s : string; linecount : integer; begin NotesList.Clear; NotesList.Text := tblTItm.DFTrackedNotes.Value; for x := 0 to NotesList.Count - 1 do begin y := 1; linecount := 0; while y < length(NotesList[x]) do begin if x = 0 then s := 'Ti' // tracked add note + rjust(tblTitm.PLoanCif, 20) + rjust(inttostr(tblTitm.PCollNum),3) + ljust(iif(tblTitm.pcifflag = 'Y', 'M', 'L'),1) + ljust(tblTitm.PTrackCode,8) + rjust(inttostr(tblTitm.PSubNum),3) else s := 'Ti'; inc(linecount); s := s + rjust(inttostr(linecount),3) + copy(NotesList[x], y, 70) + iif((x < NotesList.count-1) and (y+70 >= length(NotesList[x])), 'Y','N') + iif(y+70 < length(NotesList[x]), 'Y','N'); writeln(ExportFile, s); inc(y,70); end; end; end; procedure TExport.CNotCsv(ACifFlag, ALoanCif: string); var s : string; sl : TStringList; i : integer; begin sl := TStringList.Create; sl.Text := tblCif.DFNotes.Value; for i:=1 to sl.Count do begin s := CsvQuote(tblCif.PCifNumber) + ',' //CifNumber + CsvQuote(IntToStr(i)) + ',' //LineNumber + CsvQuote(sl[i-1]); //Line writeln(CNotFile, s); end; sl.Free; end; procedure TExport.ExportTrakTable; var s : string; begin with tblTrak do begin SetRange([RptRec.PLenderNum],[RptRec.PLenderNum]); First; case TExpFormat(RptOptions.ExpFormat) of fmtCsv, fmtCsvHead : begin while not Eof do begin s := CsvQuote(PTrackCode) +',' + CsvQuote(PDescription) +',' + CsvQuote(iif(PPrintNotify,'Y','N')) +',' + CsvQuote(IntToStr(PNotifyLead)) +',' + CsvQuote(iif(PPrintOfficer,'Y','N')) +',' + CsvQuote(IntToStr(POfficerLead)) +',' + CsvQuote(PLastScanDate) +',' + CsvQuote(IntToStr(PLastTotal)) +',' + CsvQuote(iif(PPushToHistory,'Y','N')); writeln(TrakFile,s); Next; end; end; fmtDataCaddy, fmtMpsCaddy : begin end; // do I need to bother doing anything here? end; //Next; Won't work Here end; end; end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clXmlUtils; interface //TODO test Widestring-string typecasts {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Windows, ActiveX, Classes, SysUtils, Variants, msxml, {$ELSE} Winapi.Windows, Winapi.ActiveX, System.Classes, System.SysUtils, System.Variants, Winapi.msxml, {$ENDIF} clUtils; procedure StringsToXml(AStrings: TStrings; ANode: IXMLDOMNode); procedure XmlToStrings(AStrings: TStrings; ANode: IXMLDOMNode); procedure SaveXmlToStrings(AList: TStrings; ADomDoc: IXMLDOMDocument); overload; procedure SaveXmlToStrings(AList: TStrings; ADomDoc: IXMLDOMDocument; const ACDataNodeNames: array of string); overload; procedure SaveXmlToFile(const AFileName: string; ADomDoc: IXMLDOMDocument); overload; procedure SaveXmlToFile(const AFileName: string; ADomDoc: IXMLDOMDocument; const ACDataNodeNames: array of string); overload; procedure SaveXmlToStream(AStream: TStream; ADomDoc: IXMLDOMDocument); overload; procedure SaveXmlToStream(AStream: TStream; ADomDoc: IXMLDOMDocument; const ACDataNodeNames: array of string); overload; procedure LoadXmlFromStream(AStream: TStream; ADomDoc: IXMLDOMDocument); function GetXmlCharSet(const ADom: IXMLDomDocument): string; overload; function GetXmlCharSet(const AXml: string): string; overload; function GetXmlCharSet(const AXml, ADefaultCharSet: string): string; overload; function GetNamespaceURI(const Attr: IXMLDOMAttribute): WideString; function GetAttributeLocalName(const Attr: IXMLDOMAttribute): WideString; function GetAttributeValue(const ANode: IXMLDOMNode; const AName: string): string; procedure SetAttributeValue(const ANode: IXMLDOMNode; const AName, AValue: string); function GetAttributeText(const AName, AValue: string): string; function GetAttributeValueByName(const ANode: IXMLDOMNode; const AName: string): string; function GetNodeByName(const ARoot: IXMLDomNode; const AName, ANameSpace: string): IXMLDomNode; overload; function GetNodeByName(const ARoot: IXMLDomNode; const AName: string): IXMLDomNode; overload; function GetNodeByAttributeName(const ARoot: IXMLDomNode; const AttributeName, AttributeValue: string): IXMLDomNode; function GetNodeValueByName(const ARoot: IXMLDomNode; const AName, ANameSpace: string): string; overload; function GetNodeValueByName(const ARoot: IXMLDomNode; const AName: string): string; overload; function GetNodeXmlByName(const ARoot: IXMLDomNode; const AName, ANameSpace: string): string; overload; function GetNodeXmlByName(const ARoot: IXMLDomNode; const AName: string): string; overload; procedure GetNodeValueListByName(const ARoot: IXMLDomNode; const AName, ANameSpace: string; AList: TStrings); overload; procedure GetNodeValueListByName(const ARoot: IXMLDomNode; const AName: string; AList: TStrings); overload; function GetNodeText(const ANode: IXMLDomNode): string; function GetNodeXml(const ANode: IXMLDomNode): string; procedure SetNodeText(const ANode: IXMLDomNode; const AValue: string); procedure AddNodeValue(const ARoot: IXMLDomNode; const AName, AValue: string); procedure RemoveNode(ANode: IXMLDOMNode); function SameNodes(const ANode1, ANode2: IXMLDomNode): Boolean; function ReplaceXmlNode(const AXml, ANodeName, ANewXml: string): string; function XmlCrlfEncode(const ASource: WideString): WideString; function XmlCrlfDecode(const ASource: WideString): WideString; overload; function XmlCrlfDecode(const ASource: TclByteArray): TclByteArray; overload; function UriReference2Id(const AValue: string): string; function Id2UriReference(const AValue: string): string; const cXMLNS_URI = 'http://www.w3.org/2000/xmlns/'; cXML_LANG_URI = 'http://www.w3.org/XML/1998/namespace'; cXMLNS = 'xmlns'; cXML = 'xml'; implementation uses clTranslator; const CDataXMLFormat = '<xsl:output indent="yes" method="xml" encoding="%s" cdata-section-elements="%s"/>'; XMLFormat = '<?xml version="1.0" encoding="%s"?>' + '<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">' + ' <xsl:output indent="yes" method="xml" encoding="%s"/> %s ' + ' <xsl:template match="/ | @* | node()">' + ' <xsl:copy>' + ' <xsl:apply-templates select="@* | node()"/>' + ' </xsl:copy>' + ' </xsl:template>' + '</xsl:stylesheet>'; function GetXMLFormat(const ACharSet: string; const ACDataNodeNames: array of string): string; var i: Integer; enc: string; begin enc := ACharSet; if (enc = '') then begin enc := 'UTF-8'; end; Result := ''; for i := Low(ACDataNodeNames) to High(ACDataNodeNames) do begin Result := Result + #32 + Format(CDataXMLFormat, [enc, ACDataNodeNames[i]]); end; Result := Format(XMLFormat, [enc, enc, Result]); end; procedure SaveXmlToFile(const AFileName: string; ADomDoc: IXMLDOMDocument); begin SaveXmlToFile(AFileName, ADomDoc, []); end; procedure SaveXmlToFile(const AFileName: string; ADomDoc: IXMLDOMDocument; const ACDataNodeNames: array of string); var b: Boolean; TransDoc, ResDoc: IXMLDOMDocument; begin TransDoc := CoDOMDocument.Create(); ResDoc := CoDOMDocument.Create(); TransDoc.loadXML(GetXMLFormat(GetXmlCharSet(ADomDoc), ACDataNodeNames)); try ADomDoc.transformNodeToObject(TransDoc, ResDoc); b := (ResDoc.xml <> ''); except b := False; end; if b then begin ResDoc.save(AFileName); end else begin ADomDoc.save(AFileName); end; end; procedure SaveXmlToStream(AStream: TStream; ADomDoc: IXMLDOMDocument); begin SaveXmlToStream(AStream, ADomDoc, []); end; procedure SaveXmlToStream(AStream: TStream; ADomDoc: IXMLDOMDocument; const ACDataNodeNames: array of string); var b: Boolean; TransDoc, ResDoc: IXMLDOMDocument; sa: IStream; begin TransDoc := CoDOMDocument.Create(); ResDoc := CoDOMDocument.Create(); TransDoc.loadXML(GetXMLFormat(GetXmlCharSet(ADomDoc), ACDataNodeNames)); try ADomDoc.transformNodeToObject(TransDoc, ResDoc); b := (ResDoc.xml <> ''); except b := False; end; sa := TStreamAdapter.Create(AStream, soReference); if b then begin ResDoc.save(sa); end else begin ADomDoc.save(sa); end; end; procedure LoadXmlFromStream(AStream: TStream; ADomDoc: IXMLDOMDocument); var sa: IStream; begin sa := TStreamAdapter.Create(AStream, soReference); ADomDoc.load(sa); end; procedure SaveXmlToStrings(AList: TStrings; ADomDoc: IXMLDOMDocument); begin SaveXmlToStrings(AList, ADomDoc, []); end; procedure SaveXmlToStrings(AList: TStrings; ADomDoc: IXMLDOMDocument; const ACDataNodeNames: array of string); var b: Boolean; TransDoc, ResDoc: IXMLDOMDocument; begin TransDoc := CoDOMDocument.Create(); ResDoc := CoDOMDocument.Create(); TransDoc.loadXML(GetXMLFormat(GetXmlCharSet(ADomDoc), ACDataNodeNames)); try ADomDoc.transformNodeToObject(TransDoc, ResDoc); b := (ResDoc.xml <> ''); except b := False; end; if b then begin AList.Text := string(ResDoc.xml); end else begin AList.Text := string(ADomDoc.xml); end; end; procedure StringsToXml(AStrings: TStrings; ANode: IXMLDOMNode); var ChildNode: IXMLDOMNode; begin ChildNode := ANode.ownerDocument.createCDATASection(AStrings.Text); ANode.appendChild(ChildNode); end; procedure XmlToStrings(AStrings: TStrings; ANode: IXMLDOMNode); begin AStrings.Text := ANode.text; end; function GetXmlCharSet(const ADom: IXMLDomDocument): string; var pi: IXMLDOMProcessingInstruction; attr: IXMLDOMNode; begin Result := ''; if (ADom.hasChildNodes) then begin if (ADom.firstChild.QueryInterface(IID_IXMLDOMProcessingInstruction, pi) = S_OK) then begin attr := pi.attributes.getNamedItem('encoding'); if (attr <> nil) then begin Result := VarToStr(attr.nodeValue); end; end; end; end; function GetXmlCharSet(const AXml: string): string; var doc: IXMLDomDocument; begin doc := CoDOMDocument.Create(); doc.loadXML(WideString(AXml)); Result := GetXmlCharSet(doc); end; function GetXmlCharSet(const AXml, ADefaultCharSet: string): string; begin Result := GetXmlCharSet(AXml); if (Trim(Result) = '') then begin Result := ADefaultCharSet; end; end; function GetNamespaceURI(const Attr: IXMLDOMAttribute): WideString; begin if (Attr.prefix = cXMLNS) then begin Result := cXMLNS_URI; end else begin Result := Attr.namespaceURI; end; end; function GetAttributeLocalName(const Attr: IXMLDOMAttribute): WideString; begin if (Attr.name = cXMLNS) then begin Result := cXMLNS; end else begin Result := Attr.baseName; end; end; function GetAttributeValueByName(const ANode: IXMLDOMNode; const AName: string): string; var i: Integer; att: IXMLDOMAttribute; element: IXMLDOMElement; begin Result := ''; if (ANode = nil) then Exit; element := (ANode as IXMLDOMElement); for i := 0 to element.attributes.length - 1 do begin att := (element.attributes.item[i] as IXMLDOMAttribute); if (att.baseName = AName) then begin Result := Trim(string(att.value)); Exit; end; end; end; function GetAttributeValue(const ANode: IXMLDOMNode; const AName: string): string; begin Result := VarToStr((ANode as IXMLDOMElement).getAttribute(WideString(AName))); end; function GetAttributeText(const AName, AValue: string): string; begin Result := Trim(AValue); if (Result = '') then Exit; Result := AName + '="' + Result + '"'; end; procedure SetAttributeValue(const ANode: IXMLDOMNode; const AName, AValue: string); begin if (AValue <> '') then begin (ANode as IXMLDOMElement).setAttribute(WideString(AName), AValue); end else begin (ANode as IXMLDOMElement).removeAttribute(WideString(AName)); end; end; function GetNodeByName(const ARoot: IXMLDomNode; const AName, ANameSpace: string): IXMLDomNode; var list: IXMLDomNodeList; begin list := ARoot.childNodes; Result := list.nextNode; while (Result <> nil) do begin if (Result.baseName = AName) and (Result.namespaceURI = ANameSpace) then Exit; Result := list.nextNode; end; Result := nil; end; function GetNodeByName(const ARoot: IXMLDomNode; const AName: string): IXMLDomNode; overload; var list: IXMLDomNodeList; begin if (ARoot = nil) then begin Result := nil; Exit; end; list := ARoot.childNodes; Result := list.nextNode; while (Result <> nil) do begin if (Result.baseName = AName) then Exit; Result := list.nextNode; end; Result := nil; end; function GetNodeByAttributeName(const ARoot: IXMLDomNode; const AttributeName, AttributeValue: string): IXMLDomNode; var list: IXMLDomNodeList; begin if (ARoot = nil) then begin Result := nil; Exit; end; list := ARoot.childNodes; Result := list.nextNode; while (Result <> nil) do begin if (GetAttributeValueByName(Result, AttributeName) = AttributeValue) then Exit; Result := list.nextNode; end; Result := nil; end; function GetNodeValueByName(const ARoot: IXMLDomNode; const AName, ANameSpace: string): string; var node: IXMLDomNode; begin node := GetNodeByName(ARoot, AName, ANameSpace); if (node <> nil) then begin Result := GetNodeText(node); end else begin Result := ''; end; end; function GetNodeValueByName(const ARoot: IXMLDomNode; const AName: string): string; overload; var node: IXMLDomNode; begin node := GetNodeByName(ARoot, AName); if (node <> nil) then begin Result := GetNodeText(node); end else begin Result := ''; end; end; function GetNodeXmlByName(const ARoot: IXMLDomNode; const AName, ANameSpace: string): string; overload; var node: IXMLDomNode; begin node := GetNodeByName(ARoot, AName, ANameSpace); if (node <> nil) then begin Result := GetNodeXml(node); end else begin Result := ''; end; end; function GetNodeXmlByName(const ARoot: IXMLDomNode; const AName: string): string; overload; var node: IXMLDomNode; begin node := GetNodeByName(ARoot, AName); if (node <> nil) then begin Result := GetNodeXml(node); end else begin Result := ''; end; end; procedure GetNodeValueListByName(const ARoot: IXMLDomNode; const AName, ANameSpace: string; AList: TStrings); var list: IXMLDomNodeList; node: IXMLDomNode; begin AList.Clear(); list := ARoot.childNodes; if (list = nil) then Exit; node := list.nextNode; while (node <> nil) do begin if (node.baseName = AName) and (node.namespaceURI = ANameSpace) then begin AList.Add(GetNodeText(node)); end; node := list.nextNode; end; node := nil; end; procedure GetNodeValueListByName(const ARoot: IXMLDomNode; const AName: string; AList: TStrings); var list: IXMLDomNodeList; node: IXMLDomNode; begin AList.Clear(); list := ARoot.childNodes; if (list = nil) then Exit; node := list.nextNode; while (node <> nil) do begin if (node.baseName = AName) then begin AList.Add(GetNodeText(node)); end; node := list.nextNode; end; node := nil; end; function GetNodeText(const ANode: IXMLDomNode): string; begin Result := Trim(string(ANode.text)); end; function GetNodeXml(const ANode: IXMLDomNode): string; begin Result := Trim(string(ANode.xml)); end; procedure SetNodeText(const ANode: IXMLDomNode; const AValue: string); var text: IXMLDomNode; begin if (AValue = '') then Exit; text := ANode.ownerDocument.createTextNode(WideString(AValue)); ANode.appendChild(text); end; procedure RemoveNode(ANode: IXMLDOMNode); begin if (ANode <> nil) and (ANode.parentNode <> nil) then begin ANode.parentNode.removeChild(ANode); end; end; procedure AddNodeValue(const ARoot: IXMLDomNode; const AName, AValue: string); var node: IXMLDomNode; begin if (AValue = '') then Exit; node := ARoot.ownerDocument.CreateElement(AName); ARoot.appendChild(node); SetNodeText(node, AValue); end; function SameNodes(const ANode1, ANode2: IXMLDomNode): Boolean; var node1, node2: IUnknown; begin node1 := nil; if (ANode1 <> nil) then begin ANode1.QueryInterface(IUnknown, node1); end; node2 := nil; if (ANode2 <> nil) then begin ANode2.QueryInterface(IUnknown, node2); end; Result := (node1 = node2); end; function ReplaceXmlNode(const AXml, ANodeName, ANewXml: string): string; var ind: Integer; begin ind := TextPos('<' + ANodeName, AXml); if (ind > 0) then begin Result := System.Copy(AXml, 1, ind - 1); Result := Result + ANewXml; ind := TextPos('</' + ANodeName + '>', AXml, ind + Length(ANodeName) + 1); if (ind > 0) then begin Result := Result + System.Copy(AXml, ind + Length(ANodeName) + 3, MaxInt); end else begin Result := AXml; end; end else begin Result := AXml; end; end; const XmlReplaceLexem = '_6adfa1049e6e_'; function XmlCrlfEncode(const ASource: WideString): WideString; var checkLexems: array of WideString; begin SetLength(checkLexems, 3); checkLexems[0] := '&#13;'; checkLexems[1] := '&#xd;'; checkLexems[2] := '&#x0d;'; Result := StrArrayReplace(ASource, checkLexems, XmlReplaceLexem); end; function XmlCrlfDecode(const ASource: WideString): WideString; var checkLexems: array of WideString; begin SetLength(checkLexems, 1); checkLexems[0] := XmlReplaceLexem; Result := StrArrayReplace(ASource, checkLexems, '&#xD;'); end; function XmlCrlfDecode(const ASource: TclByteArray): TclByteArray; var old, new: TclByteArray; begin old := TclTranslator.GetBytes(XmlReplaceLexem); new := TclTranslator.GetBytes('&#xD;'); Result := ByteArrayReplace(ASource, old, new); end; function UriReference2Id(const AValue: string): string; begin Result := AValue; if (Result <> '') and (Result[1] = '#') then begin System.Delete(Result, 1, 1); end; end; function Id2UriReference(const AValue: string): string; begin Result := AValue; if (Result <> '') then begin Result := '#' + Result; end; end; end.
{ Date Created: 6/13/00 11:54:36 AM } unit InfoCLAIMREPORTHISTORYTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoCLAIMREPORTHISTORYRecord = record PAutoinc: Word; PUserid: String[5]; PReportDate: String[10]; PTitle: String[100]; PDataIncluded: SmallInt; PUsingWhichDate: SmallInt; PSortOrder: SmallInt; PGroupedby: SmallInt; PRepro: SmallInt; POpenClaims: SmallInt; PStatementDate: SmallInt; PFromDate: String[10]; PToDate: String[10]; PReportFileName: String[12]; PReportProcessed: Boolean; End; TInfoCLAIMREPORTHISTORYBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoCLAIMREPORTHISTORYRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEIInfoCLAIMREPORTHISTORY = (InfoCLAIMREPORTHISTORYPrimaryKey, InfoCLAIMREPORTHISTORYUser, InfoCLAIMREPORTHISTORYDate); TInfoCLAIMREPORTHISTORYTable = class( TDBISAMTableAU ) private FDFAutoinc: TWordField; FDFUserid: TStringField; FDFReportDate: TStringField; FDFTitle: TStringField; FDFDataIncluded: TSmallIntField; FDFUsingWhichDate: TSmallIntField; FDFSortOrder: TSmallIntField; FDFGroupedby: TSmallIntField; FDFRepro: TSmallIntField; FDFOpenClaims: TSmallIntField; FDFStatementDate: TSmallIntField; FDFFromDate: TStringField; FDFToDate: TStringField; FDFLenderGroup: TBlobField; FDFCompanyString: TBlobField; FDFLenderString: TBlobField; FDFPrefixString: TBlobField; FDFPolicyString: TBlobField; FDFClaimString: TBlobField; FDFLossCodeString: TBlobField; FDFTranTypeString: TBlobField; FDFSettlementMethodString: TBlobField; FDFAdjusterString: TBlobField; FDFClaimTrackString: TBlobField; FDFTranTrackString: TBlobField; FDFTranStatusString: TBlobField; FDFReportFileName: TStringField; FDFReportProcessed: TBooleanField; procedure SetPAutoinc(const Value: Word); function GetPAutoinc:Word; procedure SetPUserid(const Value: String); function GetPUserid:String; procedure SetPReportDate(const Value: String); function GetPReportDate:String; procedure SetPTitle(const Value: String); function GetPTitle:String; procedure SetPDataIncluded(const Value: SmallInt); function GetPDataIncluded:SmallInt; procedure SetPUsingWhichDate(const Value: SmallInt); function GetPUsingWhichDate:SmallInt; procedure SetPSortOrder(const Value: SmallInt); function GetPSortOrder:SmallInt; procedure SetPGroupedby(const Value: SmallInt); function GetPGroupedby:SmallInt; procedure SetPRepro(const Value: SmallInt); function GetPRepro:SmallInt; procedure SetPOpenClaims(const Value: SmallInt); function GetPOpenClaims:SmallInt; procedure SetPStatementDate(const Value: SmallInt); function GetPStatementDate:SmallInt; procedure SetPFromDate(const Value: String); function GetPFromDate:String; procedure SetPToDate(const Value: String); function GetPToDate:String; procedure SetPReportFileName(const Value: String); function GetPReportFileName:String; procedure SetPReportProcessed(const Value: Boolean); function GetPReportProcessed:Boolean; procedure SetEnumIndex(Value: TEIInfoCLAIMREPORTHISTORY); function GetEnumIndex: TEIInfoCLAIMREPORTHISTORY; protected procedure CreateFields; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TInfoCLAIMREPORTHISTORYRecord; procedure StoreDataBuffer(ABuffer:TInfoCLAIMREPORTHISTORYRecord); property DFAutoinc: TWordField read FDFAutoinc; property DFUserid: TStringField read FDFUserid; property DFReportDate: TStringField read FDFReportDate; property DFTitle: TStringField read FDFTitle; property DFDataIncluded: TSmallIntField read FDFDataIncluded; property DFUsingWhichDate: TSmallIntField read FDFUsingWhichDate; property DFSortOrder: TSmallIntField read FDFSortOrder; property DFGroupedby: TSmallIntField read FDFGroupedby; property DFRepro: TSmallIntField read FDFRepro; property DFOpenClaims: TSmallIntField read FDFOpenClaims; property DFStatementDate: TSmallIntField read FDFStatementDate; property DFFromDate: TStringField read FDFFromDate; property DFToDate: TStringField read FDFToDate; property DFLenderGroup: TBlobField read FDFLenderGroup; property DFCompanyString: TBlobField read FDFCompanyString; property DFLenderString: TBlobField read FDFLenderString; property DFPrefixString: TBlobField read FDFPrefixString; property DFPolicyString: TBlobField read FDFPolicyString; property DFClaimString: TBlobField read FDFClaimString; property DFLossCodeString: TBlobField read FDFLossCodeString; property DFTranTypeString: TBlobField read FDFTranTypeString; property DFSettlementMethodString: TBlobField read FDFSettlementMethodString; property DFAdjusterString: TBlobField read FDFAdjusterString; property DFClaimTrackString: TBlobField read FDFClaimTrackString; property DFTranTrackString: TBlobField read FDFTranTrackString; property DFTranStatusString: TBlobField read FDFTranStatusString; property DFReportFileName: TStringField read FDFReportFileName; property DFReportProcessed: TBooleanField read FDFReportProcessed; property PAutoinc: Word read GetPAutoinc write SetPAutoinc; property PUserid: String read GetPUserid write SetPUserid; property PReportDate: String read GetPReportDate write SetPReportDate; property PTitle: String read GetPTitle write SetPTitle; property PDataIncluded: SmallInt read GetPDataIncluded write SetPDataIncluded; property PUsingWhichDate: SmallInt read GetPUsingWhichDate write SetPUsingWhichDate; property PSortOrder: SmallInt read GetPSortOrder write SetPSortOrder; property PGroupedby: SmallInt read GetPGroupedby write SetPGroupedby; property PRepro: SmallInt read GetPRepro write SetPRepro; property POpenClaims: SmallInt read GetPOpenClaims write SetPOpenClaims; property PStatementDate: SmallInt read GetPStatementDate write SetPStatementDate; property PFromDate: String read GetPFromDate write SetPFromDate; property PToDate: String read GetPToDate write SetPToDate; property PReportFileName: String read GetPReportFileName write SetPReportFileName; property PReportProcessed: Boolean read GetPReportProcessed write SetPReportProcessed; published property Active write SetActive; property EnumIndex: TEIInfoCLAIMREPORTHISTORY read GetEnumIndex write SetEnumIndex; end; { TInfoCLAIMREPORTHISTORYTable } procedure Register; implementation procedure TInfoCLAIMREPORTHISTORYTable.CreateFields; begin FDFAutoinc := CreateField( 'Autoinc' ) as TWordField; FDFUserid := CreateField( 'Userid' ) as TStringField; FDFReportDate := CreateField( 'ReportDate' ) as TStringField; FDFTitle := CreateField( 'Title' ) as TStringField; FDFDataIncluded := CreateField( 'DataIncluded' ) as TSmallIntField; FDFUsingWhichDate := CreateField( 'UsingWhichDate' ) as TSmallIntField; FDFSortOrder := CreateField( 'SortOrder' ) as TSmallIntField; FDFGroupedby := CreateField( 'Groupedby' ) as TSmallIntField; FDFRepro := CreateField( 'Repro' ) as TSmallIntField; FDFOpenClaims := CreateField( 'OpenClaims' ) as TSmallIntField; FDFStatementDate := CreateField( 'StatementDate' ) as TSmallIntField; FDFFromDate := CreateField( 'FromDate' ) as TStringField; FDFToDate := CreateField( 'ToDate' ) as TStringField; FDFLenderGroup := CreateField( 'LenderGroup' ) as TBlobField; FDFCompanyString := CreateField( 'CompanyString' ) as TBlobField; FDFLenderString := CreateField( 'LenderString' ) as TBlobField; FDFPrefixString := CreateField( 'PrefixString' ) as TBlobField; FDFPolicyString := CreateField( 'PolicyString' ) as TBlobField; FDFClaimString := CreateField( 'ClaimString' ) as TBlobField; FDFLossCodeString := CreateField( 'LossCodeString' ) as TBlobField; FDFTranTypeString := CreateField( 'TranTypeString' ) as TBlobField; FDFSettlementMethodString := CreateField( 'SettlementMethodString' ) as TBlobField; FDFAdjusterString := CreateField( 'AdjusterString' ) as TBlobField; FDFClaimTrackString := CreateField( 'ClaimTrackString' ) as TBlobField; FDFTranTrackString := CreateField( 'TranTrackString' ) as TBlobField; FDFTranStatusString := CreateField( 'TranStatusString' ) as TBlobField; FDFReportFileName := CreateField( 'ReportFileName' ) as TStringField; FDFReportProcessed := CreateField( 'ReportProcessed' ) as TBooleanField; end; { TInfoCLAIMREPORTHISTORYTable.CreateFields } procedure TInfoCLAIMREPORTHISTORYTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoCLAIMREPORTHISTORYTable.SetActive } procedure TInfoCLAIMREPORTHISTORYTable.SetPAutoinc(const Value: Word); begin DFAutoinc.Value := Value; end; function TInfoCLAIMREPORTHISTORYTable.GetPAutoinc:Word; begin result := DFAutoinc.Value; end; procedure TInfoCLAIMREPORTHISTORYTable.SetPUserid(const Value: String); begin DFUserid.Value := Value; end; function TInfoCLAIMREPORTHISTORYTable.GetPUserid:String; begin result := DFUserid.Value; end; procedure TInfoCLAIMREPORTHISTORYTable.SetPReportDate(const Value: String); begin DFReportDate.Value := Value; end; function TInfoCLAIMREPORTHISTORYTable.GetPReportDate:String; begin result := DFReportDate.Value; end; procedure TInfoCLAIMREPORTHISTORYTable.SetPTitle(const Value: String); begin DFTitle.Value := Value; end; function TInfoCLAIMREPORTHISTORYTable.GetPTitle:String; begin result := DFTitle.Value; end; procedure TInfoCLAIMREPORTHISTORYTable.SetPDataIncluded(const Value: SmallInt); begin DFDataIncluded.Value := Value; end; function TInfoCLAIMREPORTHISTORYTable.GetPDataIncluded:SmallInt; begin result := DFDataIncluded.Value; end; procedure TInfoCLAIMREPORTHISTORYTable.SetPUsingWhichDate(const Value: SmallInt); begin DFUsingWhichDate.Value := Value; end; function TInfoCLAIMREPORTHISTORYTable.GetPUsingWhichDate:SmallInt; begin result := DFUsingWhichDate.Value; end; procedure TInfoCLAIMREPORTHISTORYTable.SetPSortOrder(const Value: SmallInt); begin DFSortOrder.Value := Value; end; function TInfoCLAIMREPORTHISTORYTable.GetPSortOrder:SmallInt; begin result := DFSortOrder.Value; end; procedure TInfoCLAIMREPORTHISTORYTable.SetPGroupedby(const Value: SmallInt); begin DFGroupedby.Value := Value; end; function TInfoCLAIMREPORTHISTORYTable.GetPGroupedby:SmallInt; begin result := DFGroupedby.Value; end; procedure TInfoCLAIMREPORTHISTORYTable.SetPRepro(const Value: SmallInt); begin DFRepro.Value := Value; end; function TInfoCLAIMREPORTHISTORYTable.GetPRepro:SmallInt; begin result := DFRepro.Value; end; procedure TInfoCLAIMREPORTHISTORYTable.SetPOpenClaims(const Value: SmallInt); begin DFOpenClaims.Value := Value; end; function TInfoCLAIMREPORTHISTORYTable.GetPOpenClaims:SmallInt; begin result := DFOpenClaims.Value; end; procedure TInfoCLAIMREPORTHISTORYTable.SetPStatementDate(const Value: SmallInt); begin DFStatementDate.Value := Value; end; function TInfoCLAIMREPORTHISTORYTable.GetPStatementDate:SmallInt; begin result := DFStatementDate.Value; end; procedure TInfoCLAIMREPORTHISTORYTable.SetPFromDate(const Value: String); begin DFFromDate.Value := Value; end; function TInfoCLAIMREPORTHISTORYTable.GetPFromDate:String; begin result := DFFromDate.Value; end; procedure TInfoCLAIMREPORTHISTORYTable.SetPToDate(const Value: String); begin DFToDate.Value := Value; end; function TInfoCLAIMREPORTHISTORYTable.GetPToDate:String; begin result := DFToDate.Value; end; procedure TInfoCLAIMREPORTHISTORYTable.SetPReportFileName(const Value: String); begin DFReportFileName.Value := Value; end; function TInfoCLAIMREPORTHISTORYTable.GetPReportFileName:String; begin result := DFReportFileName.Value; end; procedure TInfoCLAIMREPORTHISTORYTable.SetPReportProcessed(const Value: Boolean); begin DFReportProcessed.Value := Value; end; function TInfoCLAIMREPORTHISTORYTable.GetPReportProcessed:Boolean; begin result := DFReportProcessed.Value; end; procedure TInfoCLAIMREPORTHISTORYTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('Autoinc, Word, 0, N'); Add('Userid, String, 5, N'); Add('ReportDate, String, 10, N'); Add('Title, String, 100, N'); Add('DataIncluded, SmallInt, 0, N'); Add('UsingWhichDate, SmallInt, 0, N'); Add('SortOrder, SmallInt, 0, N'); Add('Groupedby, SmallInt, 0, N'); Add('Repro, SmallInt, 0, N'); Add('OpenClaims, SmallInt, 0, N'); Add('StatementDate, SmallInt, 0, N'); Add('FromDate, String, 10, N'); Add('ToDate, String, 10, N'); Add('LenderGroup, Blob, 0, N'); Add('CompanyString, Blob, 0, N'); Add('LenderString, Blob, 0, N'); Add('PrefixString, Blob, 0, N'); Add('PolicyString, Blob, 0, N'); Add('ClaimString, Blob, 0, N'); Add('LossCodeString, Blob, 0, N'); Add('TranTypeString, Blob, 0, N'); Add('SettlementMethodString, Blob, 0, N'); Add('AdjusterString, Blob, 0, N'); Add('ClaimTrackString, Blob, 0, N'); Add('TranTrackString, Blob, 0, N'); Add('TranStatusString, Blob, 0, N'); Add('ReportFileName, String, 12, N'); Add('ReportProcessed, Boolean, 0, N'); end; end; procedure TInfoCLAIMREPORTHISTORYTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, Autoinc, Y, Y, N, N'); Add('User, Userid;Autoinc, N, N, N, N'); Add('Date, ReportDate, N, N, N, N'); end; end; procedure TInfoCLAIMREPORTHISTORYTable.SetEnumIndex(Value: TEIInfoCLAIMREPORTHISTORY); begin case Value of InfoCLAIMREPORTHISTORYPrimaryKey : IndexName := ''; InfoCLAIMREPORTHISTORYUser : IndexName := 'User'; InfoCLAIMREPORTHISTORYDate : IndexName := 'Date'; end; end; function TInfoCLAIMREPORTHISTORYTable.GetDataBuffer:TInfoCLAIMREPORTHISTORYRecord; var buf: TInfoCLAIMREPORTHISTORYRecord; begin fillchar(buf, sizeof(buf), 0); buf.PAutoinc := DFAutoinc.Value; buf.PUserid := DFUserid.Value; buf.PReportDate := DFReportDate.Value; buf.PTitle := DFTitle.Value; buf.PDataIncluded := DFDataIncluded.Value; buf.PUsingWhichDate := DFUsingWhichDate.Value; buf.PSortOrder := DFSortOrder.Value; buf.PGroupedby := DFGroupedby.Value; buf.PRepro := DFRepro.Value; buf.POpenClaims := DFOpenClaims.Value; buf.PStatementDate := DFStatementDate.Value; buf.PFromDate := DFFromDate.Value; buf.PToDate := DFToDate.Value; buf.PReportFileName := DFReportFileName.Value; buf.PReportProcessed := DFReportProcessed.Value; result := buf; end; procedure TInfoCLAIMREPORTHISTORYTable.StoreDataBuffer(ABuffer:TInfoCLAIMREPORTHISTORYRecord); begin DFAutoinc.Value := ABuffer.PAutoinc; DFUserid.Value := ABuffer.PUserid; DFReportDate.Value := ABuffer.PReportDate; DFTitle.Value := ABuffer.PTitle; DFDataIncluded.Value := ABuffer.PDataIncluded; DFUsingWhichDate.Value := ABuffer.PUsingWhichDate; DFSortOrder.Value := ABuffer.PSortOrder; DFGroupedby.Value := ABuffer.PGroupedby; DFRepro.Value := ABuffer.PRepro; DFOpenClaims.Value := ABuffer.POpenClaims; DFStatementDate.Value := ABuffer.PStatementDate; DFFromDate.Value := ABuffer.PFromDate; DFToDate.Value := ABuffer.PToDate; DFReportFileName.Value := ABuffer.PReportFileName; DFReportProcessed.Value := ABuffer.PReportProcessed; end; function TInfoCLAIMREPORTHISTORYTable.GetEnumIndex: TEIInfoCLAIMREPORTHISTORY; var iname : string; begin iname := uppercase(indexname); if iname = '' then result := InfoCLAIMREPORTHISTORYPrimaryKey; if iname = 'USER' then result := InfoCLAIMREPORTHISTORYUser; if iname = 'DATE' then result := InfoCLAIMREPORTHISTORYDate; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoCLAIMREPORTHISTORYTable, TInfoCLAIMREPORTHISTORYBuffer ] ); end; { Register } function TInfoCLAIMREPORTHISTORYBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..15] of string = ('AUTOINC','USERID','REPORTDATE','TITLE','DATAINCLUDED','USINGWHICHDATE' ,'SORTORDER','GROUPEDBY','REPRO','OPENCLAIMS','STATEMENTDATE' ,'FROMDATE','TODATE','REPORTFILENAME','REPORTPROCESSED' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 15) and (flist[x] <> s) do inc(x); if x <= 15 then result := x else result := 0; end; function TInfoCLAIMREPORTHISTORYBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftWord; 2 : result := ftString; 3 : result := ftString; 4 : result := ftString; 5 : result := ftSmallInt; 6 : result := ftSmallInt; 7 : result := ftSmallInt; 8 : result := ftSmallInt; 9 : result := ftSmallInt; 10 : result := ftSmallInt; 11 : result := ftSmallInt; 12 : result := ftString; 13 : result := ftString; 14 : result := ftString; 15 : result := ftBoolean; end; end; function TInfoCLAIMREPORTHISTORYBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PAutoinc; 2 : result := @Data.PUserid; 3 : result := @Data.PReportDate; 4 : result := @Data.PTitle; 5 : result := @Data.PDataIncluded; 6 : result := @Data.PUsingWhichDate; 7 : result := @Data.PSortOrder; 8 : result := @Data.PGroupedby; 9 : result := @Data.PRepro; 10 : result := @Data.POpenClaims; 11 : result := @Data.PStatementDate; 12 : result := @Data.PFromDate; 13 : result := @Data.PToDate; 14 : result := @Data.PReportFileName; 15 : result := @Data.PReportProcessed; end; end; end.
// *************************************************************************** // // Delphi MVC Framework // // Copyright (c) 2010-2016 Daniele Teti and the DMVCFramework Team // // https://github.com/danieleteti/delphimvcframework // // *************************************************************************** // // 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 MVCFramework.Logger; interface uses Iocp.Logger, System.SysUtils; type TLogLevel = (levNormal = 1, levWar = 2, levError = 3, levException = 4); function LogLevelAsString(ALogLevel: TLogLevel): string; procedure Log(AMessage: string); overload; procedure LogW(AMessage: string); procedure LogE(AMessage: string); procedure LogEx(AException: Exception; AMessage: string = ''); procedure Log(LogLevel: TLogLevel; const AMessage: string); overload; procedure LogEnterMethod(AMethodName: string); procedure LogExitMethod(AMethodName: string); procedure LogException(AException: Exception; AMessage: string = ''); deprecated 'Use LogEx instead'; var LogLevelLimit: TLogLevel = TLogLevel.levNormal; implementation uses System.Classes; function LogLevelAsString(ALogLevel: TLogLevel): string; begin case ALogLevel of levNormal: Result := ''; // normal is '' because is more readable levWar: Result := 'WARNING'; levError: Result := 'ERROR'; levException: Result := 'EXCEPTION'; else Result := 'UNKNOWN'; end; end; procedure LogEx(AException: Exception; AMessage: string = ''); begin Log(TLogLevel.levException, Format('[%s] %s (Custom message: "%s")', [AException.ClassName, AException.Message, AMessage])); end; procedure LogW(AMessage: string); begin Log(TLogLevel.levWar, AMessage); end; procedure LogE(AMessage: string); begin Log(TLogLevel.levError, AMessage); end; procedure LogException( AException: Exception; AMessage : string); begin LogEx(AException, AMessage); end; procedure LogEnterMethod(AMethodName: string); begin Log(TLogLevel.levNormal, '>> ' + AMethodName); end; procedure LogExitMethod(AMethodName: string); begin Log(TLogLevel.levNormal, '<< ' + AMethodName); end; procedure Log(LogLevel: TLogLevel; const AMessage: string); var Msg: string; begin if LogLevel < LogLevelLimit then Exit; Msg := Format('[%10s %5.5d] %s', [ LogLevelAsString(LogLevel), TThread.CurrentThread.ThreadID, AMessage]); case LogLevel of levNormal: AppendLog(Msg, TLogType.ltNormal); levWar: begin AppendLog(Msg, TLogType.ltWarning); AppendLog(Msg, TLogType.ltNormal); end; levError: begin AppendLog(Msg, TLogType.ltError); AppendLog(Msg, TLogType.ltWarning); AppendLog(Msg, TLogType.ltNormal); end; levException: begin AppendLog(Msg, TLogType.ltException); AppendLog(Msg, TLogType.ltError); AppendLog(Msg, TLogType.ltWarning); AppendLog(Msg, TLogType.ltNormal); end else raise Exception.Create('Invalid LOG LEVEL! Original message was: ' + AMessage); end; end; procedure Log(AMessage: string); overload; begin Log(TLogLevel.levNormal, AMessage); end; end.
unit SynSQLEditor; interface uses Classes, Controls, SynEdit, SynEditKbdHandler; const TSynTabChar = #9; TSynValidStringChars = ['_', '0'..'9', 'A'..'Z', 'a'..'z']; TSynWordBreakChars = ['.', ',', ';', ':', '"', '''', '!', '?', '[', ']', '(', ')', '{', '}', '^', '=', '+', '-', '*', '/', '\','|']; type TSynIdentChars = set of char; TDisplayCoord = record Column: integer; Row: integer; end; TCustomSQLEditor = class(TCustomSynEdit) private FFocusList: TList; FKbdHandler: TSynEditKbdHandler; function GetWordAtCursor : string; function WordEndEx(const ACoord: TPoint): TPoint; procedure PrepareIdentChars(out IdentChars, WhiteChars: TSynIdentChars); function GetDisplayXY: TDisplayCoord; function BufferToDisplayPos(const ACoord: TPoint): TDisplayCoord; protected procedure KeyPress(var Key: Char); override; procedure KeyUp(var Key: Word; Shift: TShiftState); override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; public procedure AfterConstruction; override; procedure BeforeDestruction; override; procedure SetFocus; override; procedure AddFocusControl(aControl: TWinControl); procedure RemoveFocusControl(aControl: TWinControl); procedure AddKeyUpHandler(aHandler: TKeyEvent); procedure RemoveKeyUpHandler(aHandler: TKeyEvent); procedure AddKeyDownHandler(aHandler: TKeyEvent); procedure RemoveKeyDownHandler(aHandler: TKeyEvent); procedure AddKeyPressHandler(aHandler: TKeyPressEvent); procedure RemoveKeyPressHandler(aHandler: TKeyPressEvent); procedure AddMouseCursorHandler(aHandler: TMouseCursorEvent); procedure RemoveMouseCursorHandler(aHandler: TMouseCursorEvent); function WordEnd: TPoint; property WordAtCursor: string read GetWordAtCursor; property DisplayXY: TDisplayCoord read GetDisplayXY; end; implementation uses SysUtils, SynEditMiscProcs; procedure TCustomSQLEditor.AfterConstruction; begin inherited; FFocusList := TList.Create; FKbdHandler := TSynEditKbdHandler.Create; end; procedure TCustomSQLEditor.BeforeDestruction; begin FreeAndNil(FKbdHandler); FreeAndNil(FFocusList); inherited; end; procedure TCustomSQLEditor.KeyPress(var Key: Char); begin inherited; FKbdHandler.ExecuteKeyPress(Self,Key); end; procedure TCustomSQLEditor.KeyUp(var Key: Word; Shift: TShiftState); begin inherited; FKbdHandler.ExecuteKeyUp(Self, Key, Shift); end; procedure TCustomSQLEditor.KeyDown(var Key: Word; Shift: TShiftState); begin inherited; FKbdHandler.ExecuteKeyDown( Self, Key, Shift ); end; procedure TCustomSQLEditor.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited MouseDown(Button, Shift, X, Y); if (Button = mbLeft) and (ssDouble in Shift) then Exit; FKbdHandler.ExecuteMouseDown(Self, Button, Shift, X, Y); end; procedure TCustomSQLEditor.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited MouseUp(Button, Shift, X, Y); fKbdHandler.ExecuteMouseUp( Self, Button, Shift, X, Y ); end; function TCustomSQLEditor.BufferToDisplayPos(const ACoord: TPoint): TDisplayCoord; // BufferToDisplayPos takes a position in the text and transforms it into // the row and column it appears to be on the screen var s: string; i, L: integer; x: integer; begin Result := TDisplayCoord(ACoord); if ACoord.Y - 1 < Lines.Count then begin s := Lines[ACoord.Y - 1]; l := Length(s); x := 0; for i := 1 to ACoord.X - 1 do begin if (i <= l) and (s[i] = TSynTabChar) then inc(x, TabWidth - (x mod TabWidth)) else inc(x); end; Result.Column := x + 1; end; end; function TCustomSQLEditor.GetDisplayXY: TDisplayCoord; begin Result := BufferToDisplayPos(CaretXY); end; function TCustomSQLEditor.WordEndEx(const ACoord: TPoint): TPoint; var CX, CY: integer; Line: string; IdentChars, WhiteChars: TSynIdentChars; begin CX := ACoord.X; CY := ACoord.Y; // valid line? if (CY >= 1) and (CY <= Lines.Count) then begin Line := Lines[CY - 1]; PrepareIdentChars(IdentChars, WhiteChars); CX := StrScanForCharInSet(Line, CX, WhiteChars); // if no "whitespace" is found just position at the end of the line if CX = 0 then CX := Length(Line) + 1; end; Result.X := CX; Result.Y := CY; end; procedure TCustomSQLEditor.PrepareIdentChars(out IdentChars, WhiteChars: TSynIdentChars); var WordBreakChars: TSynIdentChars; begin if Assigned(Highlighter) then begin IdentChars := Highlighter.IdentChars; WordBreakChars := Highlighter.WordBreakChars; end else begin IdentChars := TSynValidStringChars; WordBreakChars := TSynWordBreakChars; end; IdentChars := IdentChars - WordBreakChars; WhiteChars := [#1..#255] - IdentChars; end; function TCustomSQLEditor.WordEnd: TPoint; begin Result := WordEndEx(CaretXY); end; function TCustomSQLEditor.GetWordAtCursor: string; begin Result := GetWordAtRowCol(CaretXY); end; procedure TCustomSQLEditor.AddKeyUpHandler (aHandler : TKeyEvent); begin FKbdHandler.AddKeyUpHandler(aHandler); end; procedure TCustomSQLEditor.RemoveKeyUpHandler (aHandler : TKeyEvent); begin FKbdHandler.RemoveKeyUpHandler(aHandler); end; procedure TCustomSQLEditor.AddKeyDownHandler (aHandler : TKeyEvent); begin FKbdHandler.AddKeyDownHandler(aHandler); end; procedure TCustomSQLEditor.RemoveKeyDownHandler (aHandler : TKeyEvent); begin FKbdHandler.RemoveKeyDownHandler(aHandler); end; procedure TCustomSQLEditor.AddKeyPressHandler (aHandler : TKeyPressEvent); begin FKbdHandler.AddKeyPressHandler(aHandler); end; procedure TCustomSQLEditor.RemoveKeyPressHandler (aHandler : TKeyPressEvent); begin FKbdHandler.RemoveKeyPressHandler(aHandler); end; procedure TCustomSQLEditor.AddMouseCursorHandler(aHandler: TMouseCursorEvent); begin FKbdHandler.AddMouseCursorHandler(aHandler); end; procedure TCustomSQLEditor.RemoveMouseCursorHandler(aHandler: TMouseCursorEvent); begin FKbdHandler.RemoveMouseCursorHandler(aHandler); end; procedure TCustomSQLEditor.AddFocusControl(aControl: TWinControl); begin FFocusList.Add(aControl); end; procedure TCustomSQLEditor.RemoveFocusControl(aControl: TWinControl); begin FFocusList.Remove(aControl); end; procedure TCustomSQLEditor.SetFocus; var LastControl: TWinControl; begin if (FFocusList.Count > 0) then begin LastControl := TWinControl(FFocusList.Last); if LastControl.CanFocus then begin LastControl.SetFocus; end; end else begin inherited; end; end; end.
{$include lem_directives.inc} unit LemLevel; interface uses Classes, SysUtils, UMisc, LemTerrain, LemInteractiveObject, LemSteel; type TLevelInfo = class(TPersistent) private protected fReleaseRate : Integer; fLemmingsCount : Integer; fRescueCount : Integer; fTimeLimit : Integer; fClimberCount : Integer; fFloaterCount : Integer; fBomberCount : Integer; fBlockerCount : Integer; fBuilderCount : Integer; fBasherCount : Integer; fMinerCount : Integer; fDiggerCount : Integer; fGraphicSet : Integer; fGraphicSetEx : Integer; fSuperLemming : Boolean; fScreenPosition : Integer; fMusicTrack : Integer; fOddtarget : Integer; fTitle : string; protected public constructor Create; procedure Assign(Source: TPersistent); override; procedure Clear; virtual; published property ReleaseRate : Integer read fReleaseRate write fReleaseRate; property LemmingsCount : Integer read fLemmingsCount write fLemmingsCount; property RescueCount : Integer read fRescueCount write fRescueCount; property TimeLimit : Integer read fTimeLimit write fTimeLimit; property ClimberCount : Integer read fClimberCount write fClimberCount; property FloaterCount : Integer read fFloaterCount write fFloaterCount; property BomberCount : Integer read fBomberCount write fBomberCount; property BlockerCount : Integer read fBlockerCount write fBlockerCount; property BuilderCount : Integer read fBuilderCount write fBuilderCount; property BasherCount : Integer read fBasherCount write fBasherCount; property MinerCount : Integer read fMinerCount write fMinerCount; property DiggerCount : Integer read fDiggerCount write fDiggerCount; property GraphicSet : Integer read fGraphicSet write fGraphicSet; property GraphicSetEx : Integer read fGraphicSetEx write fGraphicSetEx; property SuperLemming : Boolean read fSuperLemming write fSuperLemming; property ScreenPosition : Integer read fScreenPosition write fScreenPosition; property MusicTrack : Integer read fMusicTrack write fMusicTrack; property OddTarget : Integer read fOddTarget write fOddTarget; property Title : string read fTitle write fTitle; end; TLevel = class(TComponent) private protected fLevelInfo : TLevelInfo; fTerrains : TTerrains; fInteractiveObjects : TInteractiveObjects; fSteels : TSteels; { internal } fUpdateCounter : Integer; { property access } procedure SetTerrains(Value: TTerrains); virtual; procedure SetInteractiveObjects(Value: TInteractiveObjects); virtual; procedure SetSteels(Value: TSteels); virtual; procedure SetLevelInfo(const Value: TLevelInfo); virtual; { dynamic creation } function DoCreateLevelInfo: TLevelInfo; dynamic; function DoCreateTerrains: TTerrains; dynamic; function DoCreateInteractiveObjects: TInteractiveObjects; dynamic; function DoCreateSteels: TSteels; dynamic; { protected overrides } public { TODO : TLevel maybe does not need to be a Component } constructor Create(aOwner: TComponent); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; procedure SaveToFile(const aFileName: string); procedure SaveToStream(S: TStream); procedure BeginUpdate; procedure EndUpdate; procedure ClearLevel; published property Info: TLevelInfo read fLevelInfo write SetLevelInfo; property InteractiveObjects: TInteractiveObjects read fInteractiveObjects write SetInteractiveObjects; property Terrains: TTerrains read fTerrains write SetTerrains; property Steels: TSteels read fSteels write SetSteels; end; { T_Level = class private protected public published end;} implementation { TLevelInfo } procedure TLevelInfo.Assign(Source: TPersistent); var L: TLevelInfo absolute Source; begin if Source is TLevelInfo then begin ReleaseRate := L.ReleaseRate; LemmingsCount := L.LemmingsCount; RescueCount := L.RescueCount; TimeLimit := L.TimeLimit; ClimberCount := L.ClimberCount; FloaterCount := L.FloaterCount; BomberCount := L.BomberCount; BlockerCount := L.BlockerCount; BuilderCount := L.BuilderCount; BasherCount := L.BasherCount; MinerCount := L.MinerCount; DiggerCount := L.DiggerCount; GraphicSet := L.GraphicSet; GraphicSetEx := L.GraphicSetEx; SuperLemming := L.SuperLemming; ScreenPosition := L.ScreenPosition; Title := L.Title; end else inherited Assign(Source); end; procedure TLevelInfo.Clear; begin ReleaseRate := 1; LemmingsCount := 1; RescueCount := 1; TimeLimit := 1; ClimberCount := 0; FloaterCount := 0; BomberCount := 0; BlockerCount := 0; BuilderCount := 0; BasherCount := 0; MinerCount := 0; DiggerCount := 0; GraphicSet := 0; GraphicSetEx := 0; SuperLemming := False; ScreenPosition := 0; Title := ''; end; constructor TLevelInfo.Create; begin inherited Create; Clear; end; { TLevel } procedure TLevel.Assign(Source: TPersistent); var L: TLevel absolute Source; begin if Source is TLevel then begin BeginUpdate; try Info := L.Info; InteractiveObjects := L.InteractiveObjects; Terrains := L.Terrains; Steels := L.Steels; finally EndUpdate; end; end else inherited Assign(Source) end; procedure TLevel.BeginUpdate; begin { TODO : a little more protection for beginupdate endupdate } Inc(fUpdateCounter); if fUpdateCounter = 1 then begin fInteractiveObjects.BeginUpdate; fTerrains.BeginUpdate; fSteels.BeginUpdate; end; end; procedure TLevel.ClearLevel; begin //fLevelInfo.Clear; fInteractiveObjects.Clear; fTerrains.Clear; fSteels.Clear; end; constructor TLevel.Create(aOwner: TComponent); begin inherited Create(aOwner); fLevelInfo := DoCreateLevelInfo; fInteractiveObjects := DoCreateInteractiveObjects; fTerrains := DoCreateTerrains; fSteels := DoCreateSteels; end; destructor TLevel.Destroy; begin fLevelInfo.Free; fInteractiveObjects.Free; fTerrains.Free; fSteels.Free; inherited Destroy; end; function TLevel.DoCreateInteractiveObjects: TInteractiveObjects; begin Result := TInteractiveObjects.Create(TInteractiveObject); end; function TLevel.DoCreateLevelInfo: TLevelInfo; begin Result := TLevelInfo.Create; end; function TLevel.DoCreateSteels: TSteels; begin Result := TSteels.Create(TSteel); end; function TLevel.DoCreateTerrains: TTerrains; begin Result := TTerrains.Create(TTerrain); end; procedure TLevel.EndUpdate; begin if fUpdateCounter > 0 then begin Dec(fUpdateCounter); if fUpdateCounter = 0 then begin fInteractiveObjects.EndUpdate; fTerrains.EndUpdate; fSteels.EndUpdate; end; end; end; procedure TLevel.SaveToFile(const aFileName: string); var F: TFileStream; begin F := TFileStream.Create(aFileName, fmCreate); try SaveToStream(F); finally F.Free; end; end; procedure TLevel.SaveToStream(S: TStream); begin S.WriteComponent(Self); end; procedure TLevel.SetLevelInfo(const Value: TLevelInfo); begin fLevelInfo.Assign(Value); end; procedure TLevel.SetInteractiveObjects(Value: TInteractiveObjects); begin fInteractiveObjects.Assign(Value); end; procedure TLevel.SetTerrains(Value: TTerrains); begin fTerrains.Assign(Value); end; procedure TLevel.SetSteels(Value: TSteels); begin fSteels.Assign(Value); end; end.
Program Identifying_Real_Constant; var LastChar: Char; {一个字符的缓冲区} Buffered: Boolean; {缓冲区标志} function getchar: Char; {从输入流读字符} begin if not Buffered then Read(LastChar); {如果缓冲区没有字符则读入一个} Buffered := False; GetChar := LastChar; {取缓冲区字符} end; procedure ungetc(c: char); {向输入流回放字符} begin LastChar := c; Buffered := True; end; function ReadThrough(match: string): Integer; var {将输入流与字符集合match进行匹配,返回匹配的字符个数} c: Char; {c是当前输入流的字符} num: Integer; {匹配的字符个数} begin num := 0; while true do begin c := getchar; {从输入流读字符c} if Pos(c, match) = 0 then {匹配结束} begin ungetc(c); {c没有匹配,重新放入缓冲区} break; end; Inc(num); {匹配成功,匹配字符数加一} end; ReadThrough := num; end; function Valid: Boolean; {识别输入流是否浮点常量} var hasdec, hasexp: Boolean; {hasdec表示是否有小数, hasexp表示是否有指数} n: Integer; begin Valid := False; Buffered := False; hasdec := False; hasexp := False; {标志初始化} ReadThrough(' '); {跳过输入流的前导空格} if ReadThrough('-+') > 1 then Exit; {多个正负号} if ReadThrough('0123456789') = 0 then Exit; {浮点常量缺无符号整数} n := ReadThrough('.'); if n > 1 then Exit; {多个小数点} if n = 1 then {字符串中存在小数部分} begin hasdec := True; {置小数标记} if ReadThrough('0123456789') = 0 then Exit; {小数部分缺无符号整数} end; n := ReadThrough('eE'); if n > 1 then Exit; {多个e或E} if n = 1 then {字符串中存在指数部分} begin hasexp := True; {置指数标记} if ReadThrough('+-') > 1 then Exit; {多个正负号} if ReadThrough('0123456789') = 0 then Exit; {指数部分缺无符号整数} end; ReadThrough(' '); {跳过输入流的后续空格} if Pos(getchar, #13#10) = 0 then Exit; {输入流不是回车} if (not hasexp) and (not hasdec) then Exit; {既无小数部分又无指数部分} Valid := True; {没有找到错误,常量表示合法} end; const res: array[Boolean] of string[3] = ('NO', 'YES'); begin writeln(res[Valid]); {根据Valid函数的值输出YES或NO} end.
unit uDMConfig; interface uses System.SysUtils, System.Classes, IniFiles, Forms, ufmMain; type TConfig = class(TDataModule) procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); private FIniFile: TIniFile; FConfigFileName: string; FCurrentDir: string; FDebugLevel: Word; FDebugState: boolean; public property CurrentDir: string read FCurrentDir; property DebugLevel: Word read FDebugLevel; property Debug: Boolean read FDebugState; function ReadString(const Section, Ident, Default: String): String; procedure WriteString(const Section, Ident, Value: String); function ReadInteger(const Section, Ident: String; Default: Integer): Integer; procedure WriteInteger(const Section, Ident: String; Value: Integer); function ReadBoolean(const Section, Ident: String; Default: Boolean): Boolean; procedure WriteBoolean(const Section, Ident: String; Value: Boolean); procedure UpdateFile; end; var Config: TConfig; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} procedure TConfig.DataModuleCreate(Sender: TObject); var PathLength: integer; begin FCurrentDir := ExtractFilePath(ParamStr(0)); PathLength := Length(FCurrentDir); if (PathLength > 3) and (FCurrentDir[PathLength] <> '\') then FCurrentDir := FCurrentDir + '\'; FConfigFileName := ChangeFileExt(Application.ExeName,'.ini'); TfmMain(Application.MainForm).Log('Loading configuration: ' + FConfigFileName); FIniFile := TIniFile.Create(FConfigFileName); FDebugLevel := FIniFile.ReadInteger('Main', 'Debug', 0); FDebugState := FDebugLevel >0; end; procedure TConfig.DataModuleDestroy(Sender: TObject); begin FIniFile.UpdateFile; FIniFile.Free; end; function TConfig.ReadBoolean(const Section, Ident: String; Default: Boolean): Boolean; begin Result := FIniFile.ReadBool(Section, Ident, Default); end; function TConfig.ReadInteger(const Section, Ident: String; Default: Integer): Integer; begin Result := FIniFile.ReadInteger(Section, Ident, Default); end; function TConfig.ReadString(const Section, Ident, Default: String): String; begin Result := FIniFile.ReadString(Section, Ident, Default); end; procedure TConfig.UpdateFile; begin FIniFile.UpdateFile; end; procedure TConfig.WriteBoolean(const Section, Ident: String; Value: Boolean); begin FIniFile.WriteBool(Section, Ident, Value); end; procedure TConfig.WriteInteger(const Section, Ident: String; Value: Integer); begin FIniFile.WriteInteger(Section, Ident, Value); end; procedure TConfig.WriteString(const Section, Ident, Value: String); begin FIniFile.WriteString(Section, Ident, Value); end; end.
unit ChunkStream; interface uses Classes, MemUtils; type TChunkStream = class protected fSize : integer; fStream : TStream; fStartPos : integer; fPosition : integer; fInMemory : boolean; fBuffer : pointer; fChunkHeader : pointer; function GetPosition : integer; public property InMemory : boolean read fInMemory; property Stream : TStream read fStream; property StartPos : integer read fStartPos; property Position : integer read GetPosition; public constructor Create( aStream : TStream; aSize : integer ); destructor Destroy; override; public procedure LoadChunkHeader; virtual; abstract; function ChunkHeaderSize : integer; virtual; abstract; function CurrentChunkSize : integer; virtual; abstract; function Seek( Pos : integer; Origin : word ) : integer; function SeekChunk( ChunkIndx : integer ) : integer; function LockChunk : pointer; function Lock( Count : integer ) : pointer; procedure Unlock( Locked : pointer ); function Relock( Locked : pointer; Count : integer ) : pointer; function RelockChunk( Locked : pointer ) : pointer; procedure LoadInMemory; end; implementation // TChunkStream function TChunkStream.Lock( Count : integer ) : pointer; begin if InMemory then begin Result := pchar( fBuffer ) + fPosition; Inc( fPosition, Count ); end else begin GetMem( Result, Count ); Stream.ReadBuffer( Result^, Count ); end; end; function TChunkStream.LockChunk : pointer; var ChunkSize : integer; HeaderSize : integer; begin LoadChunkHeader; ChunkSize := CurrentChunkSize; HeaderSize := ChunkHeaderSize; if InMemory then begin Result := pchar( fBuffer ) + fPosition - HeaderSize; inc( fPosition, ChunkSize - HeaderSize ); end else begin GetMem( Result, ChunkSize ); Stream.ReadBuffer( pchar( Result )[ HeaderSize ], ChunkSize - HeaderSize ); Move( fChunkHeader^, Result^, HeaderSize ); end; end; function TChunkStream.RelockChunk( Locked : pointer ) : pointer; var ChunkSize : integer; HeaderSize : integer; begin LoadChunkHeader; ChunkSize := CurrentChunkSize; HeaderSize := ChunkHeaderSize; if InMemory then begin Result := pchar( fBuffer ) + fPosition - HeaderSize; inc( fPosition, ChunkSize - HeaderSize ); end else begin Result := Locked; if AllocatedSize( Result ) < ChunkSize then ReallocMem( Result, ChunkSize ); Stream.ReadBuffer( pchar( Result )[ HeaderSize ], ChunkSize - HeaderSize ); Move( fChunkHeader^, Result^, HeaderSize ); end; end; function TChunkStream.Relock( Locked : pointer; Count : integer ) : pointer; begin if InMemory then begin Result := pchar( fBuffer ) + fPosition; Inc( fPosition, Count ); end else begin Result := Locked; if AllocatedSize( Result ) < Count then ReallocMem( Result, Count ); Stream.ReadBuffer( Result^, Count ); end; end; procedure TChunkStream.Unlock( Locked : pointer ); begin if not InMemory then FreePtr( Locked ); end; constructor TChunkStream.Create( aStream : TStream; aSize : integer ); begin inherited Create; fStream := aStream; if aSize < 0 then fSize := Stream.Size else fSize := aSize; fStartPos := Stream.Position; end; destructor TChunkStream.Destroy; begin Unlock( fChunkHeader ); if InMemory then FreeMem( fBuffer ); Stream.Free; inherited; end; function TChunkStream.GetPosition : integer; begin if InMemory then Result := fPosition else Result := Stream.Position - StartPos; end; function TChunkStream.SeekChunk( ChunkIndx : integer ) : integer; var Indx : integer; begin Seek( StartPos, soFromBeginning ); if ChunkIndx > 1 then begin Indx := 1; repeat LoadChunkHeader; if InMemory then inc( fPosition, CurrentChunkSize - ChunkHeaderSize ) else Stream.Seek( CurrentChunkSize - ChunkHeaderSize, soFromCurrent ); inc( Indx ); until Indx = ChunkIndx; end; Result := Position; end; function TChunkStream.Seek( Pos : integer; Origin : word ) : integer; begin if InMemory then begin case Origin of soFromBeginning : fPosition := Pos; soFromCurrent : Inc( fPosition, Pos ); soFromEnd : fPosition := fSize - Pos; end; Result := fPosition; end else case Origin of soFromBeginning : Result := Stream.Seek( Pos + StartPos, soFromBeginning ); else Result := Stream.Seek( Pos, Origin ); end; end; procedure TChunkStream.LoadInMemory; begin if not InMemory then with Stream do begin GetMem( fBuffer, fSize ); fPosition := GetPosition; try Seek( StartPos, soFromBeginning ); // Ignore any error reading stream ReadBuffer( fBuffer^, fSize ); except end; FreeObject( fStream ); fInMemory := true; end; end; end.
{ Date Created: 8/30/2001 12:26:35 PM } unit TTSARTALENDTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TTTSARTALENDRecord = record PArtaLendProfile: String[40]; PTicklerLender: String[4]; End; TTTSARTALENDBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TTTSARTALENDRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEITTSARTALEND = (TTSARTALENDPrimaryKey); TTTSARTALENDTable = class( TDBISAMTableAU ) private FDFArtaLendProfile: TStringField; FDFTicklerLender: TStringField; procedure SetPArtaLendProfile(const Value: String); function GetPArtaLendProfile:String; procedure SetPTicklerLender(const Value: String); function GetPTicklerLender:String; procedure SetEnumIndex(Value: TEITTSARTALEND); function GetEnumIndex: TEITTSARTALEND; protected procedure CreateFields; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TTTSARTALENDRecord; procedure StoreDataBuffer(ABuffer:TTTSARTALENDRecord); property DFArtaLendProfile: TStringField read FDFArtaLendProfile; property DFTicklerLender: TStringField read FDFTicklerLender; property PArtaLendProfile: String read GetPArtaLendProfile write SetPArtaLendProfile; property PTicklerLender: String read GetPTicklerLender write SetPTicklerLender; published property Active write SetActive; property EnumIndex: TEITTSARTALEND read GetEnumIndex write SetEnumIndex; end; { TTTSARTALENDTable } procedure Register; implementation procedure TTTSARTALENDTable.CreateFields; begin FDFArtaLendProfile := CreateField( 'ArtaLendProfile' ) as TStringField; FDFTicklerLender := CreateField( 'TicklerLender' ) as TStringField; end; { TTTSARTALENDTable.CreateFields } procedure TTTSARTALENDTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TTTSARTALENDTable.SetActive } procedure TTTSARTALENDTable.SetPArtaLendProfile(const Value: String); begin DFArtaLendProfile.Value := Value; end; function TTTSARTALENDTable.GetPArtaLendProfile:String; begin result := DFArtaLendProfile.Value; end; procedure TTTSARTALENDTable.SetPTicklerLender(const Value: String); begin DFTicklerLender.Value := Value; end; function TTTSARTALENDTable.GetPTicklerLender:String; begin result := DFTicklerLender.Value; end; procedure TTTSARTALENDTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('ArtaLendProfile, String, 40, N'); Add('TicklerLender, String, 4, N'); end; end; procedure TTTSARTALENDTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, ArtaLendProfile, Y, Y, N, N'); end; end; procedure TTTSARTALENDTable.SetEnumIndex(Value: TEITTSARTALEND); begin case Value of TTSARTALENDPrimaryKey : IndexName := ''; end; end; function TTTSARTALENDTable.GetDataBuffer:TTTSARTALENDRecord; var buf: TTTSARTALENDRecord; begin fillchar(buf, sizeof(buf), 0); buf.PArtaLendProfile := DFArtaLendProfile.Value; buf.PTicklerLender := DFTicklerLender.Value; result := buf; end; procedure TTTSARTALENDTable.StoreDataBuffer(ABuffer:TTTSARTALENDRecord); begin DFArtaLendProfile.Value := ABuffer.PArtaLendProfile; DFTicklerLender.Value := ABuffer.PTicklerLender; end; function TTTSARTALENDTable.GetEnumIndex: TEITTSARTALEND; var iname : string; begin iname := uppercase(indexname); if iname = '' then result := TTSARTALENDPrimaryKey; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'TTS Tables', [ TTTSARTALENDTable, TTTSARTALENDBuffer ] ); end; { Register } function TTTSARTALENDBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..2] of string = ('ARTALENDPROFILE','TICKLERLENDER' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 2) and (flist[x] <> s) do inc(x); if x <= 2 then result := x else result := 0; end; function TTTSARTALENDBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; end; end; function TTTSARTALENDBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PArtaLendProfile; 2 : result := @Data.PTicklerLender; end; end; end.
unit ItemController; interface uses System.Classes, FireDAC.Comp.Client, FireDAC.Stan.Param, System.Generics.Collections, System.SysUtils, InventoryDM; type TItem = class private FItemId: integer; FItemName: string; FItemDescription: string; published property ItemId: integer read FItemId write FItemId; property ItemName: string read FItemName write FItemName; property ItemDescription: string read FItemDescription write FItemDescription; end; TItemList = class (TObjectList<TItem>) end; TItemController = class private FItemList: TItemList; FItemQry: TFDQuery; FOnListChanged: TNotifyEvent; function GetItemsSQL: string; public constructor Create; destructor Destroy; override; procedure LoadItems; procedure BuildItemsQuery; procedure DoListChanged; procedure AddItem(const AItem: TItem); procedure DeleteItem(const AItem: TItem); procedure EditItem(const AItem: TItem); property ItemList: TItemList read FItemList write FItemList; property OnListChanged: TNotifyEvent read FOnListChanged write FOnListChanged; end; implementation { TItemList } procedure TItemController.AddItem(const AItem: TItem); var LInsertQry: TFDQuery; begin LInsertQry := GetNewInventoryQuery; try LInsertQry.SQL.Text := 'insert into Inventory_Items ' + #13#10 + '(Item_id, item_name, item_description)' + #13#10 + 'values' + #13#10 + '(:item_id, :item_name, :item_description)'; LInsertQry.Prepare; LInsertQry.ParamByName('Item_id').AsInteger := NextInventorySequenceValue('GEN_Item_ID'); LInsertQry.ParamByName('Item_name').AsString := AItem.ItemName; LInsertQry.ParamByName('Item_description').AsString := AItem.ItemDescription; LInsertQry.ExecSQL; FItemList.Add(AItem); DoListChanged; finally LInsertQry.Free; end; end; procedure TItemController.DeleteItem(const AItem: TItem); var LDeleteQry: TFDQuery; begin LDeleteQry := GetNewInventoryQuery; try LDeleteQry.SQL.Text := 'delete from Inventory_Items where Item_id = :Item_id'; LDeleteQry.Prepare; LDeleteQry.ParamByName('Item_id').AsInteger := AItem.ItemId; LDeleteQry.ExecSQL; FItemList.Remove(AItem); DoListChanged; finally LDeleteQry.Free; end; end; procedure TItemController.BuildItemsQuery; begin FItemQry.SQL.Text := GetItemsSQL; end; constructor TItemController.Create; begin FItemList := TItemList.Create; FItemQry := GetNewInventoryQuery; BuildItemsQuery; end; destructor TItemController.Destroy; begin FItemList.Free; FItemQry.Free; inherited; end; procedure TItemController.DoListChanged; begin if Assigned(FOnListChanged) then FOnListChanged(self); end; procedure TItemController.EditItem(const AItem: TItem); var LUpdateQry: TFDQuery; begin LUpdateQry := GetNewInventoryQuery; try LUpdateQry.SQL.Text := 'update Inventory_Items ' + #13#10 + 'set' + #13#10 + #9 + 'item_name =:item_name,' + #13#10 + #9 + 'item_description =:item_description' + #13#10 + 'where' + #13#10 + #9 + '1=1' + #13#10 + #9 + 'and Item_id =:Item_id'; LUpdateQry.Prepare; LUpdateQry.ParamByName('item_id').AsInteger := AItem.ItemId; LUpdateQry.ParamByName('item_name').AsString := AItem.ItemName; LUpdateQry.ParamByName('item_description').AsString := AItem.ItemDescription; LUpdateQry.ExecSQL; DoListChanged; finally LUpdateQry.Free; end; end; function TItemController.GetItemsSQL: string; begin result := 'select' + #13#10 + #9 + 'ii.Item_id,' + #13#10 + #9 + 'ii.item_name,' + #13#10 + #9 + 'ii.item_description' + #13#10 + 'from' + #13#10 + #9 + 'inventory_items ii' + #13#10 + 'where' + #13#10 + #9 + '1=1' end; procedure TItemController.LoadItems; var LItem: TItem; begin FItemList.Clear; FItemQry.Open; FItemQry.First; while not FItemQry.Eof do begin LItem := TItem.Create; LItem.ItemId := FItemQry.FieldByName('Item_id').AsInteger; LItem.ItemName := FItemQry.FieldByName('item_name').AsString; LItem.ItemDescription := FItemQry.FieldByName('item_description').AsString; FItemList.Add(LItem); FItemQry.Next; end; FItemQry.Close; DoListChanged; end; end.
unit View.FrmPrincipal; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls, uDWAbout, uRESTDWBase, FMX.Objects, FMX.Layouts, FMX.ScrollBox, FMX.Memo, FMX.Edit, FMX.Forms, FMX.TabControl, FMX.ListBox, StrUtils; type TFrmPrincipal = class(TForm) RESTPooler: TRESTServicePooler; TabControl: TTabControl; TabConfiguracao: TTabItem; TabLos: TTabItem; RectPrincipal: TRectangle; LytBotao: TLayout; BtnStart: TRectangle; BtnStop: TRectangle; LblRodaPe: TLabel; Label7: TLabel; Label8: TLabel; MmLogs: TMemo; CliStatus: TCircle; LblOnOff: TLabel; TmSincronizaProduto: TTimer; PBarSincronizara: TProgressBar; Layout4: TLayout; procedure FormDestroy(Sender: TObject); procedure BtnStartClick(Sender: TObject); procedure BtnStopClick(Sender: TObject); procedure TmSincronizaProdutoTimer(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } FPathAquivoTxt: String; procedure StartServer; procedure StopServer; procedure StatusServer(Values: Boolean); procedure SincronizarProdutos; public { Public declarations } const cVersao: String = '3.0.0'; procedure EscreveMmLogs(pErro: String); end; var FrmPrincipal: TFrmPrincipal; implementation uses System.IniFiles, uDm, uServerMethod; {$R *.fmx} procedure TFrmPrincipal.SincronizarProdutos; begin PBarSincronizara.Visible := True; EscreveMmLogs('Sincronizacao Inicia'); TThread.CreateAnonymousThread( procedure begin try try Dm.SincronizarProdutos(PBarSincronizara,FPathAquivoTxt); except raise end; finally TThread.Synchronize(nil, procedure begin EscreveMmLogs('Sincronizacao finalizada'); PBarSincronizara.Visible := False; end); end; end).Start; end; procedure TFrmPrincipal.StartServer; begin RESTPooler.Active := True; TmSincronizaProduto.Interval := 30000; TmSincronizaProduto.Enabled := True; FrmPrincipal.BtnStart.Enabled := not RESTPooler.Active; FrmPrincipal.BtnStop.Enabled := RESTPooler.Active; StatusServer(RESTPooler.Active); EscreveMmLogs('Server Iniciado'); end; procedure TFrmPrincipal.StatusServer(Values: Boolean); begin if Values then begin LblOnOff.Text := 'ON'; CliStatus.Fill.Color := TAlphaColor($FF0EE515); end else begin LblOnOff.Text := 'OFF'; CliStatus.Fill.Color := TAlphaColor($FFE50E0E); end; end; procedure TFrmPrincipal.StopServer; begin RESTPooler.Active := False; FrmPrincipal.BtnStart.Enabled := True; FrmPrincipal.BtnStop.Enabled := False; StatusServer(False); TmSincronizaProduto.Enabled := False; MmLogs.Lines.Add('Serviço parado ...'); end; procedure TFrmPrincipal.TmSincronizaProdutoTimer(Sender: TObject); begin SincronizarProdutos; end; procedure TFrmPrincipal.BtnStartClick(Sender: TObject); begin StartServer; end; procedure TFrmPrincipal.BtnStopClick(Sender: TObject); begin StopServer; end; procedure TFrmPrincipal.EscreveMmLogs(pErro: String); begin MmLogs.Lines.Add(pErro); end; procedure TFrmPrincipal.FormCreate(Sender: TObject); var FArquivoINI: TIniFile; begin RESTPooler.ServerMethodClass := TDmServerMethod; PBarSincronizara.Visible := False; LblRodaPe.Text := '© 2021 Consolide Registro de Marcas - Todos os direitos reservados.' + 'Versão: ' + cVersao; FArquivoINI := TIniFile.Create(System.SysUtils.GetCurrentDir + '\Config.ini'); try FPathAquivoTxt := FArquivoINI.ReadString('Integracao', 'Path', ''); finally FArquivoINI.Free; end; StartServer; end; procedure TFrmPrincipal.FormDestroy(Sender: TObject); begin StopServer; end; end.
unit tcOperationsList; interface uses l3Interfaces, tcInterfaces, tcItemList ; type TtcOperationsList = class(TtcItemList, ItcOperationsList) protected // ItcOperationsList function pm_GetOperation(Index: Integer): ItcOperation; function ItcOperationsList.Add = ItcOperationsList_Add; function ItcOperationsList_Add(const anID: Il3CString): ItcOperation; procedure ItcOperationsList.AddExisting = ItcOperationsList_AddExisting; procedure ItcOperationsList_AddExisting(const anOperation: ItcOperation); protected procedure AddExisting(const anItem: ItcItem); override; function MakeItem(const anID: Il3CString): ItcItem; override; public class function Make: ItcOperationsList; end; implementation uses SysUtils, tcOperation; { TtcOperationsList } procedure TtcOperationsList.AddExisting(const anItem: ItcItem); begin if not Supports(anItem, ItcOperation) then raise Exception.Create('Native interface not supported'); inherited AddExisting(anItem); end; function TtcOperationsList.ItcOperationsList_Add(const anID: Il3CString): ItcOperation; begin Result := Add(anID) as ItcOperation; end; procedure TtcOperationsList.ItcOperationsList_AddExisting( const anOperation: ItcOperation); begin AddExisting(anOperation); end; class function TtcOperationsList.Make: ItcOperationsList; var l_Instance: TtcOperationsList; begin l_Instance := Create; try Result := l_Instance; finally FreeAndNil(l_Instance); end; end; function TtcOperationsList.MakeItem(const anID: Il3CString): ItcItem; begin Result := TtcOperation.Make(anID); end; function TtcOperationsList.pm_GetOperation(Index: Integer): ItcOperation; begin Result := pm_GetItem(Index) as ItcOperation; end; end.
unit unitMyClasses; interface uses Generics.Collections; type /// <remarks> /// base object for the demo with Interface support as this can then easily /// be used by the children. /// </remarks> TMyBaseObject = class(TInterfacedObject) strict private FID: Integer; public constructor Create(aID : Integer); reintroduce; property ID : Integer read FID; end; /// <remarks> /// Example Interface to setup a contract to return a string /// </remarks> IMyInterface = interface ['{6E1078FA-DE3C-4CFD-900F-C674C630359C}'] function GetAsString: string; end; TMyFoo = class; TMyFee = class; TMyInterfaceHelper = class; /// <summary> /// TMyFee implements TMyBaseObject (So it has the ID Property) It also has /// a "Fee" property that is a string. /// </summary> TMyFee = class(TMyBaseObject) strict private FFee: string; procedure SetFee(const Value: string); function GetAsString: string; public constructor Create(aID : Integer; aFee: string); reintroduce; property Fee : string read FFee write SetFee; property AsString : string read GetAsString; end; /// <summary> /// TMyFoo, like TMyFee descends from TMyBaseObject. The only difference is /// that it implements the interface IMyInterface so that the GetAsString /// value can be accessed via class or interface. /// </summary> TMyFoo = class(TMyBaseObject, IMyInterface) strict private FFoo: string; /// <value> /// MyIHFooObj : IMyInterface is a reference to the helper object that we /// are using for the TMyFoo. /// </value> /// <remarks> /// This helps prevent the object TMyFoo going out of scope when we get a /// handle on the interface, as instead, the reference count is increased /// </remarks> MIHFooObj : IMyInterface; function GetMyInterfaceObj: IMyInterface; procedure SetFoo(const Value: string); function GetAsString: string; public constructor Create(aID : Integer; aFoo: string); reintroduce; property Foo : string read FFoo write SetFoo; /// <remarks> /// Calls MIHFooObj to get the string value /// </remarks> property AsString : string read GetAsString; /// <remarks> /// Completes the contract for the Interface IMyInterface using the /// Implements key word. /// </remarks> property MyInterface : IMyInterface read GetMyInterfaceObj implements IMyInterface; end; /// <remarks> /// Helper type for creating a function that returns the string value for /// GetAsString for IMyInterface /// </remarks> TMyInterfaceHelperFunc = reference to function(): string; /// <remarks> /// Helper class that implements IMyInterface using the TMyInterfaceHelperFunc to keep this generic for use. /// </remarks> TMyInterfaceHelper = class(TInterfacedObject, IMyInterface) strict private MIF_func : TMyInterfaceHelperFunc; public constructor Create(fetchStr : TMyInterfaceHelperFunc); function GetAsString: string; end; TMyBaseList = class(TObjectList<TMyBaseObject>); implementation uses SysUtils; { TMyBaseObjectDesc1 } constructor TMyFoo.Create(aID: Integer; aFoo: string); begin inherited Create(aID); MIHFooObj := TMyInterfaceHelper.Create(function : string begin Result := Self.Foo; end); Foo := aFoo; end; function TMyFoo.GetAsString: string; begin Result := MIHFooObj.GetAsString; end; function TMyFoo.GetMyInterfaceObj: IMyInterface; begin Result := MIHFooObj; end; procedure TMyFoo.SetFoo(const Value: string); begin FFoo := Value; end; { TMyBaseObjectDesc2 } constructor TMyFee.Create(aID: Integer; aFee: string); begin inherited Create(aID); Fee := aFee; end; function TMyFee.GetAsString: string; begin Result := Fee; end; procedure TMyFee.SetFee(const Value: string); begin FFee := Value; end; { TMyBaseObject } constructor TMyBaseObject.Create(aID: Integer); begin inherited Create; FID := aID; end; { TFooToString } constructor TMyInterfaceHelper.Create(fetchStr : TMyInterfaceHelperFunc); begin inherited Create; MIF_func := fetchStr; end; function TMyInterfaceHelper.GetAsString: string; begin Result := MIF_Func; end; end.
unit NoteEditorReg; interface uses DesignEditors, DesignIntf; type TNoteEditorStringsEdit = class(TPropertyEditor) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; function GetValue: String; override; end; TNotepadPropDbClick = class(TDefaultEditor) public procedure EditProperty(const Prop: IProperty; var Continue: Boolean); override; end; procedure Register; implementation uses System.Classes, Data.DB, Vcl.Forms, System.SysUtils, UFrmNoteEditor, Notepad; procedure Register; begin RegisterComponents('Digao', [TNotepad]); RegisterPropertyEditor(TypeInfo(TStrings), nil, '', TNoteEditorStringsEdit); RegisterPropertyEditor(TypeInfo(TStrings), TDataSet, 'SQL', TNoteEditorStringsEdit); RegisterPropertyEditor(TypeInfo(TStrings), TNotepad, 'Lines', TNoteEditorStringsEdit); RegisterComponentEditor(TNotepad, TNotepadPropDbClick); end; // procedure TNoteEditorStringsEdit.Edit; var Form: TFrmNoteEditor; C: TPersistent; begin C := GetComponent(0); Form := TFrmNoteEditor.Create(Application); try Form.Design := Designer; Form.PStr := TStrings(GetOrdValue); Form.LbTitle.Caption := Format('%s.%s (%s)', [C.GetNamePath, GetName, C.ClassName]); Form.ShowModal; finally Form.Free; end; end; function TNoteEditorStringsEdit.GetAttributes: TPropertyAttributes; begin Result := [paDialog, paReadOnly]; end; function TNoteEditorStringsEdit.GetValue: String; var S: TStrings; X: Integer; begin S := TStrings(GetOrdValue); X := S.Count; if X = 0 then Result := '(Empty)' else if X = 1 then Result := '(1 line)' else Result := Format('(%d lines)', [X]); end; // procedure TNotepadPropDbClick.EditProperty(const Prop: IProperty; var Continue: Boolean); begin if Prop.GetName = 'Lines' then begin Prop.Edit; Continue := False; end; end; end.
(* WG_Test: HDO, 1995-09-11; GHO 2010-05-28, HDO 2011 ------- Test program for generating Windows graphics based on unit WinGraph. ==========================================================================*) PROGRAM WG_Test; USES {$IFDEF FPC} Windows, {$ELSE} WinTypes, WinProcs, {$ENDIF} Strings, WinCrt, WinGraph; PROCEDURE Redraw_Example(dc: HDC; wnd: HWnd; r: TRect); FAR; VAR txt: ARRAY [0..255] OF CHAR; n, i: INTEGER; incX, incY: REAL; BEGIN StrCopy(txt, 'Some Text'); TextOut(dc, 10, 10, txt, StrLen(txt)); Ellipse(dc, 50, 50, 200, 100); n := 50; incX := (r.right - r. left) / n; incY := (r.bottom - r.top) / n; FOR i := 1 TO n DO BEGIN MoveTo (dc, Round(i*incX), 0); LineTo(dc, Round(incX * (n -i)), Round(i*incy)); END; (*FOR*) END; (*Redraw_Example*) PROCEDURE Redraw_Example2(dc: HDC; wnd: HWnd; r: TRect); FAR; BEGIN (*... draw anything ...*) END; (*Redraw_Example2*) PROCEDURE MousePressed_Example(dc: HDC; wnd: HWnd; x, y: INTEGER); FAR; BEGIN WriteLn('mouse pressed at: ', x, ', ', y); (*InvalidateRect(wnd, NIL, TRUE);*) END; (*MousePressed_Exmple*) BEGIN (*WG_Test*) redrawProc := Redraw_Example; mousePressedProc := MousePressed_Example; WGMain; END. (*WG_Test*)
unit UnitSimpleBank; {$APPTYPE CONSOLE} interface uses Classes, SysUtils; type IAccount = interface procedure Deposit(anAmount : Currency); procedure WithDraw(anAmount : Currency); function PrintStatement : Integer; function GetAccountName : String; function GetAccountBalance : Currency; end; TAccount = class(TInterfacedObject, IAccount) private FName : String; FBalance : Currency; FTransaction : TStringList; public constructor Create(aName : String; anAmount : Currency); procedure Deposit(anAmount : Currency); procedure WithDraw(anAmount : Currency); function GetAccountName : String; function GetAccountBalance : Currency; function PrintStatement : Integer; property Name : String read FName; property Balance : Currency read FBalance; end; TSimpleBank = class private FAccount : IAccount; Function GetAccountName : String; Function GetBalance: Currency; public constructor CreateAccount(anAccount : IAccount); procedure Deposit(anAmount : Currency); procedure WithDraw(anAmount : Currency); function PrintMiniStatement : Integer; property AccountName : String read GetAccountName; property Balance : Currency read GetBalance; end; implementation //Class TSimpleBank implementation start here constructor TSimpleBank.CreateAccount(anAccount : IAccount); begin inherited Create; FAccount := anAccount; end; Function TSimpleBank.GetAccountName : String; begin result := FAccount.GetAccountName; end; Function TSimpleBank.GetBalance: Currency; begin result := FAccount.GetAccountBalance; end; procedure TSimpleBank.Deposit(anAmount : Currency); begin FAccount.Deposit(anAmount); end; procedure TSimpleBank.WithDraw(anAmount : Currency); begin FAccount.WithDraw(anAmount); end; function TSimpleBank.PrintMiniStatement : Integer; begin result := FAccount.PrintStatement; end; //Class TAccount implementation start here constructor TAccount.Create(aName : String; anAmount : Currency); begin inherited Create; FTransaction := TStringList.Create; FName := aName; FBalance := anAmount; FTransaction.Add(FormatDateTime('dd/mm/yy hh:nn:ss ',Now)+aName + ' Open an account, deposit '+FloatToStrF(anAmount, ffCurrency,4,2)); end; procedure TAccount.Deposit(anAmount : Currency); begin if (anAmount > 0) then begin FBalance := FBalance + anAmount; FTransaction.Add(FormatDateTime('dd/mm/yy hh:nn:ss : ',Now)+FName + ' Deposit ' + FloatToStrF(anAmount, ffCurrency,4,2)); end else WriteLn('nedative deposit not allowed'); end; procedure TAccount.WithDraw(anAmount : Currency); begin if (anAmount <= FBalance) then begin FBalance := FBalance - anAmount; FTransaction.Add(FormatDateTime('dd/mm/yy hh:nn:ss : ',Now)+FName + ' WithDraw ' + FloatToStrF(anAmount, ffCurrency,4,2)); end else WriteLn('overdrawing not allowed'); end; function TAccount.PrintStatement : Integer; var i : Integer; begin FTransaction.Add(FormatDateTime('dd/mm/yy hh:nn:ss : ',Now)+FName + ' Balance ' + FloatToStrF(FBalance, ffCurrency,4,2)); for I := 0 to FTransaction.Count-1 do WriteLn(FTransaction[i]); result := FTransaction.Count; FTransaction.SaveToFile(FName+'MiniStatement.txt'); WriteLn('The mini statement:'+FName+'MiniStatement.txt'+' printed in the folder.'); Readln; end; function TAccount.GetAccountName : String; begin result := FName; end; function TAccount.GetAccountBalance : Currency; begin result := FBalance; end; end.
unit InputSrch_TLB; { This file contains pascal declarations imported from a type library. This file will be written during each import or refresh of the type library editor. Changes to this file will be discarded during the refresh process. } { InputSrch Library } { Version 1.0 } interface uses Windows, ActiveX, Classes, Graphics, OleCtrls, StdVCL; const LIBID_InputSrch: TGUID = '{B2E5C440-71A5-11D1-A1A8-DAA499D0D834}'; const { Component class GUIDs } Class_InputSearch: TGUID = '{B2E5C442-71A5-11D1-A1A8-DAA499D0D834}'; type { Forward declarations: Interfaces } IInputSearch = interface; IInputSearchDisp = dispinterface; { Forward declarations: CoClasses } InputSearch = IInputSearch; { Dispatch interface for InputSearch Object } IInputSearch = interface(IDispatch) ['{B2E5C441-71A5-11D1-A1A8-DAA499D0D834}'] procedure Search(const Input, World, Town, Company: WideString; Count, X, Y: Integer); safecall; function Get_Count: Integer; safecall; function Get_X(row: Integer): Integer; safecall; function Get_Y(row: Integer): Integer; safecall; function Get_Capacity(row: Integer): Integer; safecall; function Get_SupLevel(row: Integer): Integer; safecall; function Get_Town(row: Integer): WideString; safecall; function Get_Company(row: Integer): WideString; safecall; function Get_Utility(row: Integer): WideString; safecall; function Get_SortMode: Integer; safecall; procedure Set_SortMode(Value: Integer); safecall; function Get_Role: Integer; safecall; procedure Set_Role(Value: Integer); safecall; function Get_Circuits: WideString; safecall; procedure Set_Circuits(const Value: WideString); safecall; function Get_Connected(row: Integer): WordBool; safecall; property Count: Integer read Get_Count; property X[row: Integer]: Integer read Get_X; property Y[row: Integer]: Integer read Get_Y; property Capacity[row: Integer]: Integer read Get_Capacity; property SupLevel[row: Integer]: Integer read Get_SupLevel; property Town[row: Integer]: WideString read Get_Town; property Company[row: Integer]: WideString read Get_Company; property Utility[row: Integer]: WideString read Get_Utility; property SortMode: Integer read Get_SortMode write Set_SortMode; property Role: Integer read Get_Role write Set_Role; property Circuits: WideString read Get_Circuits write Set_Circuits; property Connected[row: Integer]: WordBool read Get_Connected; end; { DispInterface declaration for Dual Interface IInputSearch } IInputSearchDisp = dispinterface ['{B2E5C441-71A5-11D1-A1A8-DAA499D0D834}'] procedure Search(const Input, World, Town, Company: WideString; Count, X, Y: Integer); dispid 3; property Count: Integer readonly dispid 1; property X[row: Integer]: Integer readonly dispid 2; property Y[row: Integer]: Integer readonly dispid 4; property Capacity[row: Integer]: Integer readonly dispid 5; property SupLevel[row: Integer]: Integer readonly dispid 6; property Town[row: Integer]: WideString readonly dispid 7; property Company[row: Integer]: WideString readonly dispid 8; property Utility[row: Integer]: WideString readonly dispid 9; property SortMode: Integer dispid 10; property Role: Integer dispid 12; property Circuits: WideString dispid 11; property Connected[row: Integer]: WordBool readonly dispid 13; end; { InputSearchObject } CoInputSearch = class class function Create: IInputSearch; class function CreateRemote(const MachineName: string): IInputSearch; end; implementation uses ComObj; class function CoInputSearch.Create: IInputSearch; begin Result := CreateComObject(Class_InputSearch) as IInputSearch; end; class function CoInputSearch.CreateRemote(const MachineName: string): IInputSearch; begin Result := CreateRemoteComObject(MachineName, Class_InputSearch) as IInputSearch; end; end.
unit vtHintManager; // Модуль: "w:\common\components\gui\Garant\VT\vtHintManager.pas" // Стереотип: "SimpleClass" // Элемент модели: "TvtHintManager" MUID: (50C6241B0355) {$Include w:\common\components\gui\Garant\VT\vtDefine.inc} interface uses l3IntfUses , l3ProtoObject , l3ObjectList , vtMultilineHint ; type TvtHintManager = class(Tl3ProtoObject) private f_Hints: Tl3ObjectList; protected function pm_GetItem(anIndex: Integer): TvtMultilineHint; virtual; function pm_GetCount: Integer; virtual; procedure Cleanup; override; {* Функция очистки полей объекта. } procedure InitFields; override; public procedure Add(aHint: TvtMultilineHint); procedure Remove(aHint: TvtMultilineHint); class function Exists: Boolean; class function Instance: TvtHintManager; {* Метод получения экземпляра синглетона TvtHintManager } public property Item[anIndex: Integer]: TvtMultilineHint read pm_GetItem; property Count: Integer read pm_GetCount; end;//TvtHintManager implementation uses l3ImplUses {$If NOT Defined(NoScripts) AND NOT Defined(NoVCL)} , vtHintWordsPack {$IfEnd} // NOT Defined(NoScripts) AND NOT Defined(NoVCL) , SysUtils , l3Base {$If NOT Defined(NoScripts)} , TtfwClassRef_Proxy {$IfEnd} // NOT Defined(NoScripts) //#UC START# *50C6241B0355impl_uses* //#UC END# *50C6241B0355impl_uses* ; var g_TvtHintManager: TvtHintManager = nil; {* Экземпляр синглетона TvtHintManager } procedure TvtHintManagerFree; {* Метод освобождения экземпляра синглетона TvtHintManager } begin l3Free(g_TvtHintManager); end;//TvtHintManagerFree function TvtHintManager.pm_GetItem(anIndex: Integer): TvtMultilineHint; //#UC START# *50C734B60190_50C6241B0355get_var* //#UC END# *50C734B60190_50C6241B0355get_var* begin //#UC START# *50C734B60190_50C6241B0355get_impl* Assert(Assigned(f_Hints)); Result := TvtMultilineHint(f_Hints[anIndex]); //#UC END# *50C734B60190_50C6241B0355get_impl* end;//TvtHintManager.pm_GetItem function TvtHintManager.pm_GetCount: Integer; //#UC START# *50C7352402AD_50C6241B0355get_var* //#UC END# *50C7352402AD_50C6241B0355get_var* begin //#UC START# *50C7352402AD_50C6241B0355get_impl* Assert(Assigned(f_Hints)); if Assigned(f_Hints) then Result := f_Hints.Count else Result := 0; //#UC END# *50C7352402AD_50C6241B0355get_impl* end;//TvtHintManager.pm_GetCount procedure TvtHintManager.Add(aHint: TvtMultilineHint); //#UC START# *50C624A002CF_50C6241B0355_var* //#UC END# *50C624A002CF_50C6241B0355_var* begin //#UC START# *50C624A002CF_50C6241B0355_impl* f_Hints.Add(aHint); //#UC END# *50C624A002CF_50C6241B0355_impl* end;//TvtHintManager.Add procedure TvtHintManager.Remove(aHint: TvtMultilineHint); //#UC START# *50C624D30325_50C6241B0355_var* //#UC END# *50C624D30325_50C6241B0355_var* begin //#UC START# *50C624D30325_50C6241B0355_impl* f_Hints.Remove(aHint); //#UC END# *50C624D30325_50C6241B0355_impl* end;//TvtHintManager.Remove class function TvtHintManager.Exists: Boolean; begin Result := g_TvtHintManager <> nil; end;//TvtHintManager.Exists class function TvtHintManager.Instance: TvtHintManager; {* Метод получения экземпляра синглетона TvtHintManager } begin if (g_TvtHintManager = nil) then begin l3System.AddExitProc(TvtHintManagerFree); g_TvtHintManager := Create; end; Result := g_TvtHintManager; end;//TvtHintManager.Instance procedure TvtHintManager.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_50C6241B0355_var* //#UC END# *479731C50290_50C6241B0355_var* begin //#UC START# *479731C50290_50C6241B0355_impl* l3Free(f_Hints); inherited; //#UC END# *479731C50290_50C6241B0355_impl* end;//TvtHintManager.Cleanup procedure TvtHintManager.InitFields; //#UC START# *47A042E100E2_50C6241B0355_var* //#UC END# *47A042E100E2_50C6241B0355_var* begin //#UC START# *47A042E100E2_50C6241B0355_impl* inherited; f_Hints := Tl3ObjectList.Create; //#UC END# *47A042E100E2_50C6241B0355_impl* end;//TvtHintManager.InitFields initialization {$If NOT Defined(NoScripts)} TtfwClassRef.Register(TvtHintManager); {* Регистрация TvtHintManager } {$IfEnd} // NOT Defined(NoScripts) end.
// AKTools akDataUtils unit. // Модуль, содержащий функции по работе с различными данными. //============================================================================= unit akDataUtils; interface uses SysUtils, Classes, Windows; // Возвращает порядковый номер элемента массива в котором записано значение // Data. Если такого элемента не найдено, то вернется -1. function DataInArray(Data: Integer; Arr: array of Integer): Integer; overload; function DataInArray(Data: Boolean; Arr: array of Boolean): Integer; overload; function DataInArray(Data: Double; Arr: array of Double): Integer; overload; function DataInArray(Data: string; Arr: array of string; IgnoreCase: Boolean): Integer; overload; function DataInArray(Data: string; Arr: TStrings; IgnoreCase: Boolean): Integer; overload; function DataInArray(Data: Pointer; Arr: TList): Integer; overload; // Возвращает число, записанное в битах first-last в value. function GetBits(value: Integer; first, last: Byte): DWORD; // Считает CRC32 указанной строки. function GetStringCRC(Str: string; UseZero: Boolean = true): Cardinal; // Если значение верно функция вернет v1, иначе - v2 function iifs(Expr: boolean; v1, v2: Integer): Integer; overload; function iifs(Expr: boolean; v1, v2: string): string; overload; function iifs(Expr: boolean; v1, v2: Boolean): Boolean; overload; function iif(Expr: boolean; v1, v2: variant): variant; // Сравнивает значение двух переменных. Возвращает : // отрицательное число - если a меньше b // ноль - они раны // положительное число - a больше b function UniCompare(val1, val2: string): Integer; overload; function UniCompare(val1, val2: TDateTime): Integer; overload; function UniCompare(val1, val2: Integer): Integer; overload; implementation const CRC32Polynomial = $EDB88320; var crc_32_tab: array[byte] of longword; function DataInArray(Data: string; Arr: array of string; IgnoreCase: Boolean): Integer; var i: Integer; begin Result := -1; for i := Low(Arr) to High(Arr) do if ((IgnoreCase) and (AnsiCompareText(Data, Arr[i]) = 0)) or ((not IgnoreCase) and (AnsiCompareStr(Data, Arr[i]) = 0)) then begin Result := i; Break; end; end; function DataInArray(Data: Integer; Arr: array of Integer): Integer; var i: Integer; begin Result := -1; for i := Low(Arr) to High(Arr) do if (Data = Arr[i]) then begin Result := i; Break; end; end; function DataInArray(Data: Boolean; Arr: array of Boolean): Integer; var i: Integer; begin Result := -1; for i := Low(Arr) to High(Arr) do if (Data = Arr[i]) then begin Result := i; Break; end; end; function DataInArray(Data: Double; Arr: array of Double): Integer; var i: Integer; begin Result := -1; for i := Low(Arr) to High(Arr) do if (Data = Arr[i]) then begin Result := i; Break; end; end; function DataInArray(Data: string; Arr: TStrings; IgnoreCase: Boolean): Integer; overload; var i: Integer; begin Result := -1; for i := 0 to Arr.Count - 1 do if ((AnsiCompareText(Arr[i], Data) = 0) and (IgnoreCase)) or ((CompareStr(Arr[i], Data) = 0) and (not IgnoreCase)) then begin Result := i; Break; end; end; function DataInArray(Data: Pointer; Arr: TList): Integer; overload; var i: Integer; begin Result := -1; for i := 0 to Arr.Count - 1 do if (Arr[i] = Data) then begin Result := i; Break; end; end; function GetBits(value: Integer; first, last: Byte): DWORD; var f, l: Integer; a1, a2: DWord; begin l := last; f := first; if f < 0 then f := 0; if l > 31 then l := 31; a1 := (value shr (f)); a2 := a1 shl (31 - (l - f)); Result := a2 shr (31 - (l - f)) end; procedure BuildCRC32Table; {* (c) Burnashov Alexander alexburn@metrocom.ru *} var i, j: byte; crc: longword; begin for i := 0 to 255 do begin crc := i; for j := 8 downto 1 do if (crc and 1) <> 0 then crc := (crc shr 1) xor CRC32Polynomial else crc := crc shr 1; crc_32_tab[i] := crc; end; end; function UpdC32(octet: BYTE; crc: Cardinal): Cardinal; begin Result := crc_32_tab[BYTE(crc xor Cardinal(octet))] xor ((crc shr 8) and $00FFFFFF) end; function GetStringCRC(Str: string; UseZero: Boolean): Cardinal; const FirstRun: Boolean = true; type TAr = array[0..3] of byte; var l, crc: Cardinal; counter: SmallInt; ar: TAr absolute crc; am: TAr absolute l; begin if FirstRun then begin BuildCRC32Table; FirstRun := False; end; crc := $FFFFFFFF; for counter := 1 to Length(Str) do crc := UpdC32(Byte(Str[counter]), crc); am[0] := ar[3]; am[1] := ar[2]; am[2] := ar[1]; am[3] := ar[0]; Result := l; if (Result = 0) and (not UseZero) then Result := 1; end; function iif(Expr: boolean; v1, v2: variant): variant; begin if Expr then Result := v1 else Result := v2; end; function iifs(Expr: boolean; v1, v2: Integer): Integer; overload; begin if Expr then Result := v1 else Result := v2; end; function iifs(Expr: boolean; v1, v2: string): string; overload; begin if Expr then Result := v1 else Result := v2; end; function iifs(Expr: boolean; v1, v2: Boolean): Boolean; overload; begin if Expr then Result := v1 else Result := v2; end; function UniCompare(val1, val2: string): Integer; overload; begin Result := CompareText(val1, val2); end; function UniCompare(val1, val2: TDateTime): Integer; overload; begin Result := 0; if val1 = val2 then Result := 0; if val1 > val2 then Result := 1; if val1 < val2 then Result := -1; end; function UniCompare(val1, val2: Integer): Integer; overload; begin Result := 0; if val1 = val2 then Result := 0; if val1 > val2 then Result := 1; if val1 < val2 then Result := -1; end; end.
unit uMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, IPPeerClient, IPPeerServer, System.Tether.Manager, System.Tether.AppProfile, FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo, System.Actions, FMX.ActnList, FMX.StdCtrls, FMX.Edit; type TForm1 = class(TForm) DesktopTetherManager: TTetheringManager; TetheringAppProfile1: TTetheringAppProfile; Memo1: TMemo; Button1: TButton; ActionList1: TActionList; Action1: TAction; procedure DesktopTetherManagerRequestManagerPassword(const Sender: TObject; const ARemoteIdentifier: string; var Password: string); procedure TetheringAppProfile1ResourceReceived(const Sender: TObject; const AResource: TRemoteResource); procedure Action1Execute(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.fmx} procedure TForm1.Action1Execute(Sender: TObject); begin Memo1.Lines.Clear; end; procedure TForm1.DesktopTetherManagerRequestManagerPassword(const Sender: TObject; const ARemoteIdentifier: string; var Password: string); begin Password := '1234'; end; procedure TForm1.TetheringAppProfile1ResourceReceived(const Sender: TObject; const AResource: TRemoteResource); begin Memo1.Lines.Add(TimeToStr(Now) + ': ' + AResource.Value.AsString); end; end.
unit Transfer; interface uses CoreTypes; type IEnumNames = IEnumStrings; type IPropertyStorage = interface function GetClass : string; function GetName : string; function SetName(const which : string) : boolean; function GetProperty(const name : string) : string; function SetProperty(const name, value : string) : boolean; function CreateProperty(const name, value : string) : boolean; function EnumProperties : IEnumNames; function OpenStorage(const name : string) : IPropertyStorage; function CreateStorage(const theClass, name : string) : IPropertyStorage; function EnumChildren : IEnumNames; end; procedure TransferData(const src, dst : IPropertyStorage); implementation procedure TransferData(const src, dst : IPropertyStorage); var name : string; Enum : IEnumNames; s, d : IPropertyStorage; begin Enum := src.EnumProperties; if Enum <> nil then while Enum.Next(name) > 0 do dst.CreateProperty(name, src.GetProperty(name)); Enum := src.EnumChildren; if Enum <> nil then while Enum.Next(name) > 0 do begin s := src.OpenStorage(name); assert(s <> nil); d := dst.CreateStorage(s.GetClass, name); if d <> nil then TransferData(s, d); end; end; end.
// Copyright (c) 2017 Embarcadero Technologies, Inc. All rights reserved. // // This software is the copyrighted property of Embarcadero Technologies, Inc. // ("Embarcadero") and its licensors. You may only use this software if you // are an authorized licensee of Delphi, C++Builder or RAD Studio // (the "Embarcadero Products"). This software is subject to Embarcadero's // standard software license and support agreement that accompanied your // purchase of the Embarcadero Products and is considered a Redistributable, // as such term is defined thereunder. Your use of this software constitutes // your acknowledgement of your agreement to the foregoing software license // and support agreement. //--------------------------------------------------------------------------- unit StoreDataModule; // EMS Resource Module interface uses System.SysUtils, System.Classes, System.JSON, EMS.Services, EMS.ResourceAPI, EMS.ResourceTypes, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.StorageBin, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, REST.Response.Adapter, FireDAC.UI.Intf, FireDAC.ConsoleUI.Wait, FireDAC.Stan.StorageJSON, FireDAC.Comp.UI, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.IB, FireDAC.Phys.IBDef, FireDAC.DApt, CommonDataModule, FireDAC.VCLUI.Wait, FireDAC.Phys.IBBase; type [ResourceName('items')] TStoreResource = class(TDataModule) FDGUIxWaitCursor: TFDGUIxWaitCursor; FDStanStorageJSONLink: TFDStanStorageJSONLink; QueryGetItems: TFDQuery; FDSchemaAdapter: TFDSchemaAdapter; FDPhysIBDriverLink1: TFDPhysIBDriverLink; private procedure GetData(const ATenantId: string); published procedure Get(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse); procedure Post(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse); end; implementation {%CLASSGROUP 'System.Classes.TPersistent'} {$R *.dfm} uses REST.Types; procedure TStoreResource.Get(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse); var LStream: TMemoryStream; begin LStream := TMemoryStream.Create; try GetData(AContext.Tenant.Id); FDSchemaAdapter.SaveToStream(LStream, TFDStorageFormat.sfJSON); AResponse.Body.SetStream(LStream, CONTENTTYPE_APPLICATION_VND_EMBARCADERO_FIREDAC_JSON, True); except LStream.Free; raise; end; end; procedure TStoreResource.GetData(const ATenantId: string); begin CommonDM.CheckConnected; QueryGetItems.Params.ParamByName('TenantId').AsString := ATenantId; QueryGetItems.Open; end; procedure TStoreResource.Post(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse); var LStream: TStream; begin if not SameText(ARequest.Body.ContentType, CONTENTTYPE_APPLICATION_VND_EMBARCADERO_FIREDAC_JSON) then AResponse.RaiseBadRequest('content type'); if not ARequest.Body.TryGetStream(LStream) then AResponse.RaiseBadRequest('no stream'); LStream.Position := 0; FDSchemaAdapter.LoadFromStream(LStream, TFDStorageFormat.sfJSON); FDSchemaAdapter.ApplyUpdates; end; procedure Register; begin RegisterResource(TypeInfo(TStoreResource)); end; initialization Register; end.
{ Inno Setup Preprocessor Copyright (C) 2001-2002 Alex Yackimoff $Id: IsppIntf.pas,v 1.2 2009/04/02 14:20:59 mlaan Exp $ } unit IsppIntf; interface type TOptionID = 0..25; TOptions = packed set of TOptionID; PIsppParserOptions = ^TIsppParserOptions; TIsppParserOptions = packed record Options: TOptions; end; TIsppOptions = packed record ParserOptions: TIsppParserOptions; Options: TOptions; VerboseLevel: Byte; InlineStart: string[7]; InlineEnd: string[7]; SpanSymbol: AnsiChar; end; TIsppVarType = (evSpecial, evNull, evInt, evStr, evLValue, evCallContext); IIsppFuncParam = interface function GetType: TIsppVarType; stdcall; function GetAsInt: Integer; stdcall; function GetAsString(Buf: PChar; BufSize: Integer): Integer; stdcall; end; IIsppFuncResult = interface procedure SetAsInt(Value: Integer); stdcall; procedure SetAsString(Value: PChar); stdcall; procedure SetAsNull; stdcall; procedure Error(Message: PChar); stdcall; end; IIsppFuncParams = interface function Get(Index: Integer): IIsppFuncParam; stdcall; function GetCount: Integer; stdcall; end; TIsppFuncResult = packed record Reserved: Byte; ErrParam: Word; Error: Byte; end; TIsppFunction = function (Ext: Longint; const Params: IIsppFuncParams; const FuncResult: IIsppFuncResult): TIsppFuncResult; stdcall; IPreprocessor = interface procedure DefineVariable(Name: PChar; Typ: TIsppVarType; Value: Longint); procedure QueueLine(Line: PChar); end; const { TIsppFuncResult.Error values } // Function executed successfully ISPPFUNC_SUCCESS = Byte($00); // Unexpected failure ISPPFUNC_FAIL = Byte($01); // Too many arguments passed, ErrParam contains maximal number of arguments needed ISPPFUNC_MANYARGS = Byte($02); // Insufficient required arguments, ErrParam contains minimal number of arguments ISPPFUNC_INSUFARGS = Byte($03); // Wrong type of argument passed, ErrParam is the index of the argument ISPPFUNC_INTWANTED = Byte($04); // Wrong type of argument passed, ErrParam is the index of the argument ISPPFUNC_STRWANTED = Byte($05); const { Parser options } optSCBE = TOptionID(Ord('B') - Ord('A')); optSCME = TOptionID(Ord('M') - Ord('A')); optPassNulls = TOptionID(Ord('N') - Ord('A')); optPascalStrings = TOptionID(Ord('P') - Ord('A')); optAllowUndeclared = TOptionID(Ord('U') - Ord('A')); { Preprocessor options } optPassToCompiler = TOptionID(Ord('C') - Ord('A')); optEmitEmptyLines = TOptionID(Ord('E') - Ord('A')); optCircMacroCall = TOptionID(Ord('R') - Ord('A')); optVerbose = TOptionID(Ord('V') - Ord('A')); implementation end.
{*_* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Author: François PIETTE Description: A TWSocket that has server functions: it listen to connections an create other TWSocket to handle connection for each client. Creation: Aug 29, 1999 Version: 6.00b EMail: francois.piette@overbyte.be http://www.overbyte.be Support: Use the mailing list twsocket@elists.org Follow "support" link at http://www.overbyte.be for subscription. Legal issues: Copyright (C) 1999-2006 by François PIETTE Rue de Grady 24, 4053 Embourg, Belgium. Fax: +32-4-365.74.56 <francois.piette@overbyte.be> SSL implementation includes code written by Arno Garrels, Berlin, Germany, contact: <arno.garrels@gmx.de> This software is provided 'as-is', without any express 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. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. 4. You must register this software by sending a picture postcard to the author. Use a nice stamp and mention your name, street address, EMail address and any comment you like to say. Quick reference guide: TWSocketServer will normally be used to listen on a given tcp port. When a client connect, it will instanciate a new TWSocketClient component to handle communication with client. Normally you will derive your own component from TWSocketClient to add private data and methods to handle it. You tell TWSocketServer which component it has to instanciate using ClientClass property. You have to initialize instances from OnClientConnect event handler. TWSocketServer maintain a list of connected clients. You can access it using Client[] indexed property and ClientCount property. History: Sep 05, 1999 V1.01 Adpted for Delphi 1 Oct 09, 1999 V1.02 Added intermediate class TCustomWSocket Nov 12, 1999 V1.03 Added OnClientCreate event just after client component has been created. Apr 02, 2000 V1.04 Added FSessionClosedFlag to avoid double SessionClosed event triggering Apr 13, 2002 V1.05 When sending banner to client, add LineEnd instead of CR/LF as suggested by David Aguirre Grazio <djagra@xaire.com> Sep 13, 2002 V1.06 Check if Assigned(Server) in TriggerSessionClosed. Reported by Matthew Meadows <matthew.meadows@inquisite.com> Sep 16, 2002 V1.07 Fixed a Delphi 1 issue in TriggerSessionClosed where property was used in place of field variable. Jan 04, 2003 V1.08 Renamed BannerToBusy to BannerTooBusy. This will cause trouble in applications already using this property. You have to rename the property in your app ! Jan 24, 2003 V5.00 Skipped to version 5 because of SSL code Jan 26, 2004 V5.01 Introduced ICSDEFS.INC and reordered uses for FPC compatibility. May 01, 2004 V5.02 WMClientClosed was incorrectly referencing global Error variable instead of the real winsock error code. Now pass the errcode in WParam at the time of PostMessage. Removed Forms and Graphics units from the uses clause. May 23, 2005 V5.03 Added intermediate variable NewHSocket in procedure TriggerSessionAvailable Dec 30, 2005 V6.00b A.Garrels added IcsLogger * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} unit OverbyteIcsWSocketS; interface { You must define USE_SSL so that SSL code is included in the component. } { To be able to compile the component, you must have the SSL related files } { which are _NOT_ freeware. See http://www.overbyte.be for details. } {$B-} { Enable partial boolean evaluation } {$T-} { Untyped pointers } {$X+} { Enable extended syntax } {$I OverbyteIcsDefs.inc} {$IFDEF DELPHI6_UP} {$WARN SYMBOL_PLATFORM OFF} {$WARN SYMBOL_LIBRARY OFF} {$WARN SYMBOL_DEPRECATED OFF} {$ENDIF} {$IFNDEF VER80} { Not for Delphi 1 } {$H+} { Use long strings } {$J+} { Allow typed constant to be modified } {$ENDIF} {$IFDEF BCB3_UP} {$ObjExportAll On} {$ENDIF} uses {$IFDEF CLR} System.Runtime.InteropServices, {$ENDIF} {$IFDEF WIN32} Messages, {$IFDEF USEWINDOWS} Windows, {$ELSE} WinTypes, WinProcs, {$ENDIF} Classes, Graphics, Controls, Forms, {$ENDIF} {$IFNDEF NO_DEBUG_LOG} OverbyteIcsLogger, {$ENDIF} OverbyteIcsTypes, OverbyteIcsLibrary, OverbyteIcsWSocket, OverbyteIcsWinsock; const WSocketServerVersion = 600; CopyRight : String = ' TWSocketServer (c) 1999-2006 F. Piette V6.00b '; //WM_CLIENT_CLOSED = WM_USER + 30; DefaultBanner = 'Welcome to TcpSrv'; type TCustomWSocketServer = class; TWSocketClient = class; TWSocketClientClass = class of TWSocketClient; TWSocketClientCreateEvent = procedure (Sender : TObject; Client : TWSocketClient) of object; TWSocketClientConnectEvent = procedure (Sender : TObject; Client : TWSocketClient; Error : Word) of object; { TWSocketClient is used to handle all client connections. } { Altough you may use it directly, you'll probably wants to use your } { own derived component to add data and methods suited to your } { application. } { If you use a derived component, then assign it's class to } { TWSocketServer ClientClass property. } TWSocketClient = class(TWSocket) protected FBanner : String; FServer : TCustomWSocketServer; FPeerAddr : String; FPeerPort : String; FSessionClosedFlag : Boolean; {$IFDEF CLR} FHandleGc : GCHandle; {$ENDIF} public procedure StartConnection; virtual; procedure TriggerSessionClosed(ErrCode : Word); override; procedure Dup(newHSocket : TSocket); override; function GetPeerAddr: String; override; function GetPeerPort: String; override; property Server : TCustomWSocketServer read FServer write FServer; {$IFDEF CLR} property HandleGc : GCHandle read FHandleGc write FHandleGc; {$ENDIF} published property Banner : String read FBanner write FBanner; end; { TWSocketServer is made for listening for tcp client connections. } { For each connection, it instanciate a new TWSocketClient (or derived) } { to handle connection. Use ClientClass to specify your derived. } TCustomWSocketServer = class(TWSocket) protected FBanner : String; FBannerTooBusy : String; FClientClass : TWSocketClientClass; FClientList : TList; FClientNum : LongInt; FMaxClients : LongInt; FMsg_WM_CLIENT_CLOSED : UINT; FOnClientCreate : TWSocketClientCreateEvent; FOnClientConnect : TWSocketClientConnectEvent; FOnClientDisconnect : TWSocketClientConnectEvent; procedure WndProc(var MsgRec: TMessage); override; {$IFDEF WIN32} procedure Notification(AComponent: TComponent; operation: TOperation); override; {$ENDIF} procedure TriggerSessionAvailable(Error : Word); override; procedure TriggerClientCreate(Client : TWSocketClient); virtual; procedure TriggerClientConnect(Client : TWSocketClient; Error : Word); virtual; procedure TriggerClientDisconnect(Client : TWSocketClient; Error : Word); virtual; function GetClientCount : Integer; virtual; function GetClient(nIndex : Integer) : TWSocketClient; virtual; procedure WMClientClosed(var msg: TMessage); virtual; function MsgHandlersCount: Integer; override; procedure AllocateMsgHandlers; override; procedure FreeMsgHandlers; override; public {$IFDEF CLR} constructor Create; override; {$ENDIF} {$IFDEF WIN32} constructor Create(AOwner: TComponent); override; {$ENDIF} destructor Destroy; override; { Check if a given object is one of our clients } function IsClient(SomeThing : TObject) : Boolean; protected { TWSocketClient derived class to instanciate for each client } property ClientClass : TWSocketClientClass read FClientClass write FClientClass; { How many active clients we currently have } property ClientCount : Integer read GetClientCount; { Client[] give direct access to anyone of our clients } property Client[nIndex : Integer] : TWSocketClient read GetClient; published { Banner sent to client as welcome message. Can be empty. } property Banner : String read FBanner write FBanner; property BannerTooBusy : String read FBannerTooBusy write FBannerTooBusy; property MaxClients : LongInt read FMaxClients write FMaxClients; { Triggered when a client disconnect } property OnClientDisconnect : TWSocketClientConnectEvent read FOnClientDisconnect write FOnClientDisconnect; { Triggerred when a new client is connecting } property OnClientConnect : TWSocketClientConnectEvent read FOnClientConnect write FOnClientConnect; { Triggerred when a new client component has been created } property OnClientCreate : TWSocketClientCreateEvent read FOnClientCreate write FOnClientCreate; end; TWSocketServer = class(TCustomWSocketServer) public property ClientClass; property ClientCount; property Client; published {$IFNDEF NO_DEBUG_LOG} property IcsLogger; { V5.04 } {$ENDIF} property Banner; property BannerTooBusy; property MaxClients; property OnClientDisconnect; property OnClientConnect; end; {$IFDEF USE_SSL} {$I WSocketSIntfSsl.inc} {$ENDIF} {$IFDEF WIN32} procedure Register; {$ENDIF} implementation {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} {$IFDEF WIN32} procedure Register; begin RegisterComponents('FPiette', [TWSocketServer {$IFDEF USE_SSL} , TSslWSocketServer {$ENDIF} ]); end; {$ENDIF} {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TCustomWSocketServer.Create{$IFDEF WIN32}(AOwner: TComponent){$ENDIF}; begin inherited Create{$IFDEF WIN32}(AOwner){$ENDIF}; FClientList := TList.Create; FClientClass := TWSocketClient; FBanner := DefaultBanner; FBannerTooBusy := 'Sorry, too many clients'; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} destructor TCustomWSocketServer.Destroy; var I : Integer; begin if Assigned(FClientList) then begin { We need to destroy all clients } for I := FClientList.Count - 1 downto 0 do begin try {$IFDEF CLR} TWSocketClient(FClientList.Items[I]).HandleGc.Free; {$ENDIF} TWSocketClient(FClientList.Items[I]).Free; except { Ignore any exception here } end; end; { Then we can destroy client list } FClientList.Free; FClientList := nil; end; { And finally destroy ourself } inherited Destroy; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomWSocketServer.MsgHandlersCount : Integer; begin Result := 1 + inherited MsgHandlersCount; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocketServer.AllocateMsgHandlers; begin inherited AllocateMsgHandlers; FMsg_WM_CLIENT_CLOSED := FWndHandler.AllocateMsgHandler(Self); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocketServer.FreeMsgHandlers; begin if Assigned(FWndHandler) then FWndHandler.UnregisterMessage(FMsg_WM_CLIENT_CLOSED); inherited FreeMsgHandlers; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { Message handler } procedure TCustomWSocketServer.WndProc(var MsgRec: TMessage); begin with MsgRec do begin if Msg = FMsg_WM_CLIENT_CLOSED then begin { We *MUST* handle all exception to avoid application shutdown } try WMClientClosed(MsgRec) except on E:Exception do HandleBackGroundException(E); end; end else inherited WndProc(MsgRec); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { Called by destructor when child component (a clients) is create or } { destroyed. } {$IFDEF WIN32} procedure TCustomWSocketServer.Notification( AComponent : TComponent; Operation : TOperation); begin inherited Notification(AComponent, Operation); if Assigned(FClientList) and (AComponent is TWSocketClient) then begin if Operation = opInsert then { A new client has been created, add it to our list } FClientList.Add(AComponent) else if Operation = opRemove then { If one of our client has been destroyed, remove it from our list } FClientList.Remove(AComponent); end; end; {$ENDIF} {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { Called when a session is available, that is when a client is connecting } procedure TCustomWSocketServer.TriggerSessionAvailable(Error : Word); var Client : TWSocketClient; begin {$IFDEF DEBUG_OUTPUT} OutputDebugString('OnSessionAvailable'); {$ENDIF} { Call parent event handler } inherited TriggerSessionAvailable(Error); { In case of error, do nothing } if Error <> 0 then Exit; Inc(FClientNum); Client := FClientClass.Create{$IFDEF WIN32}(Self){$ENDIF}; {$IFDEF CLR} FClientList.Add(Client); Client.HandleGc := GcHandle.Alloc(Client); {$ENDIF} TriggerClientCreate(Client); Client.Name := Name + 'Client' + IntToStr(FClientNum); Client.Banner := FBanner; Client.Server := Self; {$IFNDEF NO_DEBUG_LOG} Client.IcsLogger := IcsLogger; { V5.04 } {$ENDIF} Client.HSocket := Accept; TriggerClientConnect(Client, Error); { The event handler may have destroyed the client ! } if FClientList.IndexOf(Client) < 0 then Exit; { The event handler may have closed the connection } if Client.State <> wsConnected then Exit; { Ok, the client is still there, process with the connection } if (FMaxClients > 0) and (FMaxClients < ClientCount) then begin { Sorry, toomuch clients } Client.Banner := FBannerTooBusy; Client.StartConnection; Client.Close; end else Client.StartConnection; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocketServer.TriggerClientConnect( Client : TWSocketClient; Error : Word); begin if Assigned(FOnClientConnect) then FOnClientConnect(Self, Client, Error); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocketServer.TriggerClientCreate(Client : TWSocketClient); begin if Assigned(FOnClientCreate) then FOnClientCreate(Self, Client); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocketServer.TriggerClientDisconnect( Client : TWSocketClient; Error : Word); begin if Assigned(FOnClientDisconnect) then FOnClientDisconnect(Self, Client, Error); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { get number of connect clients } function TCustomWSocketServer.GetClientCount : Integer; begin if Assigned(FClientList) then Result := FClientList.Count else Result := 0; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { Acces method to return a client by index. } { Return nil if index is out of range. } function TCustomWSocketServer.GetClient(nIndex : Integer) : TWSocketClient; begin if not Assigned(FClientList) then begin Result := nil; Exit; end; if (nIndex < 0) or (nIndex >= FClientList.Count) then begin Result := nil; Exit; end; Result := TWSocketClient(FClientList.Items[nIndex]); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { Client has closed. Remove it from client list and destroy component. } procedure TCustomWSocketServer.WMClientClosed(var msg: TMessage); var Client : TWSocketClient; {$IFDEF CLR} GCH : GCHandle; {$ENDIF} begin {$IFDEF CLR} GCH := GCHandle(IntPtr(Msg.LParam)); Client := TWSocketClient(GCH.Target); {$ENDIF} {$IFDEF WIN32} Client := TWSocketClient(Msg.LParam); {$ENDIF} try TriggerClientDisconnect(Client, Msg.WParam); finally { Calling Free will automatically remove client from list because } { we installed a notification handler. } {$IFDEF CLR} FClientList.Remove(Client); Client.HandleGc.Free; {$ENDIF} Client.Free; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { Check if a given object is one of our clients. } function TCustomWSocketServer.IsClient(SomeThing : TObject) : Boolean; begin if not Assigned(FClientList) then Result := FALSE else Result := (FClientList.IndexOf(SomeThing) >= 0); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} {* *} {* TWSocketClient *} {* *} {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TWSocketClient.StartConnection; begin if Length(FBanner) > 0 then SendStr(FBanner + FLineEnd); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { Triggered when socket is closed. Need to inform server socket to update } { client list and trigger client disconnect event. } procedure TWSocketClient.TriggerSessionClosed(ErrCode : Word); begin if not FSessionClosedFlag then begin FSessionClosedFlag := TRUE; if Assigned(FServer) then PostMessage(Server.Handle, Server.FMsg_WM_CLIENT_CLOSED, ErrCode, {$IFDEF CLR} Integer(IntPtr(Self.HandleGc))); {$ENDIF} {$IFDEF WIN32} LongInt(Self)); {$ENDIF} inherited TriggerSessionClosed(ErrCode); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { This override base class GetPeerAddr. It return cached value. } function TWSocketClient.GetPeerAddr: String; begin Result := FPeerAddr; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { This override base class GetPeerPort. It return cached value. } function TWSocketClient.GetPeerPort: String; begin Result := FPeerPort; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { Override base class. Dup is called when a client is assigned to a } { TWSocket. Assigning HSocket property will call Dup. } procedure TWSocketClient.Dup(newHSocket : TSocket); begin inherited Dup(newHSocket); { Cache PeerAddr value } FPeerAddr := inherited GetPeerAddr; FPeerPort := inherited GetPeerPort; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} {$IFDEF USE_SSL} {$I WSocketSImplSsl.inc} {$ENDIF} {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} end.
unit uPenerimaanBarang; interface uses uModel, uSupplier, System.Generics.Collections, System.Classes, System.SysUtils; type TPenerimaanBarangItem = class; TPenerimaanBarang = class(TAppObject) private FCabang: TCabang; FGudang: TGudang; FJenisPembayaran: string; FKeterangan: string; FNoBukti: string; FPenerimaanBarangItems: TObjectList<TPenerimaanBarangItem>; FPeriode: Integer; FPPN: Double; FSubTotal: Double; FDiskon: Double; FIsJurnalized: Integer; FSupplier: TSupplier; FTglBukti: TDatetime; FTempo: Integer; FTotal: Double; function GetPenerimaanBarangItems: TObjectList<TPenerimaanBarangItem>; function GetPPN: Double; function GetSubTotal: Double; function GetDiskon: Double; function GetTotal: Double; procedure SetKeterangan(const Value: string); procedure SetTglBukti(const Value: TDatetime); public constructor Create; published property Cabang: TCabang read FCabang write FCabang; property Gudang: TGudang read FGudang write FGudang; property JenisPembayaran: string read FJenisPembayaran write FJenisPembayaran; property Keterangan: string read FKeterangan write SetKeterangan; property NoBukti: string read FNoBukti write FNoBukti; property PenerimaanBarangItems: TObjectList<TPenerimaanBarangItem> read GetPenerimaanBarangItems write FPenerimaanBarangItems; property Periode: Integer read FPeriode write FPeriode; property PPN: Double read GetPPN write FPPN; property SubTotal: Double read GetSubTotal write FSubTotal; property Diskon: Double read GetDiskon write FDiskon; property IsJurnalized: Integer read FIsJurnalized write FIsJurnalized; property Supplier: TSupplier read FSupplier write FSupplier; property TglBukti: TDatetime read FTglBukti write SetTglBukti; property Tempo: Integer read FTempo write FTempo; property Total: Double read GetTotal write FTotal; end; TPenerimaanBarangItem = class(TAppObjectItem) {$TYPEINFO OFF} private FBarang: TBarang; FDiskon: Double; FHargaBeli: Double; FPenerimaanBarang: TPenerimaanBarang; FPPN: Double; FQty: Double; FUOM: TUOM; FKonversi : Double; function GetHargaSetelahDiskon: Double; public function GetHeaderField: string; override; procedure SetHeaderProperty(AHeaderProperty : TAppObject); override; published property Barang: TBarang read FBarang write FBarang; property Diskon: Double read FDiskon write FDiskon; property HargaBeli: Double read FHargaBeli write FHargaBeli; property HargaSetelahDiskon: Double read GetHargaSetelahDiskon; property PenerimaanBarang: TPenerimaanBarang read FPenerimaanBarang write FPenerimaanBarang; property PPN: Double read FPPN write FPPN; property Qty: Double read FQty write FQty; property UOM: TUOM read FUOM write FUOM; property Konversi : Double read FKonversi write FKonversi; end; type TInvoiceSupplierItem = class(TAppObjectItem) {$TYPEINFO OFF} private FBarang: TBarang; FDiskon: Double; FHargaBeli: Double; FPenerimaanBarang: TPenerimaanBarang; FPPN: Double; FQty: Double; FUOM: TUOM; FKonversi : Double; function GetHargaSetelahDiskon: Double; public function GetHeaderField: string; override; procedure SetHeaderProperty(AHeaderProperty : TAppObject); override; published property Barang: TBarang read FBarang write FBarang; property Diskon: Double read FDiskon write FDiskon; property HargaBeli: Double read FHargaBeli write FHargaBeli; property HargaSetelahDiskon: Double read GetHargaSetelahDiskon; property PenerimaanBarang: TPenerimaanBarang read FPenerimaanBarang write FPenerimaanBarang; property PPN: Double read FPPN write FPPN; property Qty: Double read FQty write FQty; property UOM: TUOM read FUOM write FUOM; property Konversi : Double read FKonversi write FKonversi; end; implementation constructor TPenerimaanBarang.Create; begin inherited; IsJurnalized := 0; end; function TPenerimaanBarang.GetPenerimaanBarangItems: TObjectList<TPenerimaanBarangItem>; begin if FPenerimaanBarangItems =nil then FPenerimaanBarangItems := TObjectList<TPenerimaanBarangItem>.Create(True); Result := FPenerimaanBarangItems; end; function TPenerimaanBarang.GetPPN: Double; var dLinePPN: Double; I: Integer; begin FPPN := 0; for I := 0 to PenerimaanBarangItems.Count - 1 do begin dLinePPN := PenerimaanBarangItems[i].Qty * PenerimaanBarangItems[i].HargaBeli * (100 - PenerimaanBarangItems[i].Diskon) / 100 * PenerimaanBarangItems[i].PPN / 100; FPPN := FPPN + dLinePPN; end; Result := FPPN; end; function TPenerimaanBarang.GetSubTotal: Double; var dLinePrice: Double; I: Integer; begin FSubTotal := 0; for I := 0 to PenerimaanBarangItems.Count - 1 do begin dLinePrice := PenerimaanBarangItems[i].Qty * PenerimaanBarangItems[i].HargaBeli; FSubTotal := FSubTotal + dLinePrice; end; Result := FSubTotal; end; function TPenerimaanBarang.GetDiskon: Double; var dLineDisc: Double; I: Integer; begin FDiskon := 0; for I := 0 to PenerimaanBarangItems.Count - 1 do begin dLineDisc := PenerimaanBarangItems[i].Qty * PenerimaanBarangItems[i].HargaBeli * PenerimaanBarangItems[i].Diskon / 100; FDiskon := FDiskon + dLineDisc; end; Result := FDiskon; end; function TPenerimaanBarang.GetTotal: Double; begin FTotal := SubTotal - Diskon + PPN; Result := FTotal; end; procedure TPenerimaanBarang.SetKeterangan(const Value: string); begin FKeterangan := Value; end; procedure TPenerimaanBarang.SetTglBukti(const Value: TDatetime); begin FTglBukti := Value; Periode := StrToInt(FormatDateTime('YYYYMM', Value)); end; function TPenerimaanBarangItem.GetHargaSetelahDiskon: Double; begin Result := HargaBeli * (100 - Diskon) / 100; end; function TPenerimaanBarangItem.GetHeaderField: string; begin Result := 'PenerimaanBarang'; end; procedure TPenerimaanBarangItem.SetHeaderProperty(AHeaderProperty : TAppObject); begin PenerimaanBarang := TPenerimaanBarang(AHeaderProperty); end; function TInvoiceSupplierItem.GetHargaSetelahDiskon: Double; begin Result := HargaBeli * (100 - Diskon) / 100; end; function TInvoiceSupplierItem.GetHeaderField: string; begin Result := 'InvoiceSupplier'; end; procedure TInvoiceSupplierItem.SetHeaderProperty(AHeaderProperty : TAppObject); begin PenerimaanBarang := TPenerimaanBarang(AHeaderProperty); end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) ePath: TEdit; Count: TButton; lbNames: TLabel; Label1: TLabel; Label2: TLabel; lbValues: TLabel; Label3: TLabel; lbFolders: TLabel; Label5: TLabel; lbNamesSize: TLabel; Label4: TLabel; lbValuesSize: TLabel; Label6: TLabel; lbLarger: TLabel; Label7: TLabel; lbTotal: TLabel; Names: TListBox; procedure CountClick(Sender: TObject); private fNames : TStringList; fValues : TStringList; fFolders : integer; fLarger : integer; fLargerName : string; fTotal : integer; private procedure CountName(List : TStringList; name : string); function ListSize(List : TStringList) : integer; procedure CountList(List : TStringList); procedure CountFolder(path : string); end; var Form1: TForm1; implementation {$R *.DFM} function TForm1.ListSize(List : TStringList) : integer; var i : integer; begin result := 0; for i := 0 to pred(List.Count) do inc(result, length(List[i]) + 4); end; procedure TForm1.CountName(List : TStringList; name : string); var n : string; i : integer; l : integer; p : integer; procedure DoCount; var idx : integer; frq : integer; begin if length(n) < 4 then exit; idx := List.IndexOf(n); if idx <> -1 then begin frq := integer(List.Objects[idx]); inc(frq); List.Objects[idx] := TObject(frq); end else List.AddObject(n, TObject($00000001)); end; begin l := length(name); if l > 1 then begin i := 1; repeat p := i; inc(i); while (i <= l) and not (name[i] in ['A'..'Z']) and not (name[i] in ['0'..'9']) do inc(i); n := copy(name, p, i - p); while (i <= l) and (name[i] in ['0'..'9']) do inc(i); DoCount; until i >= l; end else begin n := name; DoCount; end; end; procedure TForm1.CountList(List : TStringList); var i : integer; s : string; n : string; v : string; p : integer; begin for i := 0 to pred(List.Count) do begin s := List[i]; p := pos('=', s); if p = 0 then n := s else begin n := copy(s, 1, p - 1); v := copy(s, p + 1, length(s) - p); CountName(fNames, n); fValues.Add(v); end; end; end; procedure TForm1.CountFolder(path : string); var Search : TSearchRec; List : TStringList; begin inc(fFolders); if fFolders mod 5 = 0 then begin lbFolders.Caption := IntToStr(fFolders); lbFolders.Refresh; end; if FindFirst(path + '\*.*', faDirectory + faArchive, Search) = 0 then repeat if Search.Attr and faArchive <> 0 then begin inc(fTotal, Search.Size); if Search.Size > fLarger then begin fLarger := Search.Size; fLargerName := path + '\' + Search.Name; end; List := TStringList.Create; List.LoadFromFile(path + '\' + Search.Name); CountList(List); List.Free; end else if (Search.Name <> '.') and (Search.Name <> '..') then CountFolder(path + '\' + Search.Name); until FindNext(Search) <> 0; end; procedure TForm1.CountClick(Sender: TObject); var i, j : integer; tmp : string; obj : TObject; begin fTotal := 0; fLargerName := ''; fLarger := 0; fFolders := 0; fNames := TStringList.Create; fNames.Sorted := true; fNames.Duplicates := dupIgnore; fValues := TStringList.Create; fValues.Sorted := true; fValues.Duplicates := dupIgnore; CountFolder(ePath.Text); lbNames.Caption := IntToStr(fNames.Count); lbValues.Caption := IntToStr(fValues.Count); lbFolders.Caption := IntToStr(fFolders); lbNamesSize.Caption := IntToStr(ListSize(fNames)); lbValuesSize.Caption := IntToStr(ListSize(fValues)); lbLarger.Caption := IntToStr(fLarger); lbLarger.Hint := fLargerName; lbTotal.Caption := IntToStr(fTotal); fNames.Sorted := false; for i := 0 to pred(pred(fNames.Count)) do for j := succ(i) to pred(fNames.Count) do if integer(fNames.Objects[i]) < integer(fNames.Objects[j]) then begin obj := fNames.Objects[i]; tmp := fNames[i]; fNames.Objects[i] := fNames.Objects[j]; fNames[i] := fNames[j]; fNames[j] := tmp; fNames.Objects[j] := obj; end; for i := 0 to pred(fNames.Count) do Names.Items.Add(fNames[i] + ' ' + IntToStr(integer(fNames.Objects[i]))); fNames.Free; fValues.Free; end; end.
unit DAO.OcorrenciasJornal; interface uses DAO.Base, Generics.Collections, System.Classes, Model.OcorrenciasJornal; type TOcorrenciasJornalDAO = class(TDAO) public function Insert(aOcorrencias: TOcorrenciasJornal): Boolean; function Update(aOcorrencias: TOcorrenciasJornal): Boolean; function Delete(iNumero: Integer): Boolean; function FindByNumero(iNumero: Integer): TObjectList<TOcorrenciasJornal>; function FindByData(dtData: TDate): TObjectList<TOcorrenciasJornal>; function FindByAssinatura(sAssinatura: String): TObjectList<TOcorrenciasJornal>; function FindByNome(sNome: String): TObjectList<TOcorrenciasJornal>; function FindByRoteiro(sRoteiro: String): TObjectList<TOcorrenciasJornal>; function FindByEndereco(sEndereco: String): TObjectList<TOcorrenciasJornal>; end; const TABLENAME = 'jor_ocorrencias_jornal'; implementation uses System.SysUtils, FireDAC.Comp.Client, Data.DB; function TOcorrenciasJornalDAO.Insert(aOcorrencias: TOcorrenciasJornal): Boolean; var sSQL : System.string; begin Result := False; aOcorrencias.Numero := GetKeyValue(TABLENAME,'NUM_OCORRENCIA'); sSQL := 'INSERT INTO ' + TABLENAME + ' '+ '(NUM_OCORRENCIA, ' + 'DAT_OCORRENCIA, ' + 'COD_ASSINATURA, ' + 'NOM_ASSINANTE, ' + 'DES_ROTEIRO, ' + 'COD_ENTREGADOR, ' + 'COD_PRODUTO, ' + 'COD_OCORRENCIA, ' + 'DOM_REINCIDENTE, ' + 'DES_DESCRICAO, ' + 'DES_ENDERECO, ' + 'DES_RETORNO, ' + 'COD_RESULTADO, ' + 'COD_ORIGEM, ' + 'DES_OBS, ' + 'COD_STATUS, ' + 'DES_APURACAO, ' + 'DOM_PROCESSADO, ' + 'QTD_OCORRENCIAS, ' + 'VAL_OCORRENCIA, ' + 'DAT_DESCONTO, ' + 'DOM_IMPRESSAO, ' + 'DES_ANEXO, ' + 'DES_LOG) ' + 'VALUES ' + '(:pNUM_OCORRENCIA, ' + ':pDAT_OCORRENCIA, ' + ':pCOD_ASSINATURA, ' + ':pNOM_ASSINANTE, ' + ':pDES_ROTEIRO, ' + ':pCOD_ENTREGADOR, ' + ':pCOD_PRODUTO, ' + ':pCOD_OCORRENCIA, ' + ':pDOM_REINCIDENTE, ' + ':pDES_DESCRICAO, ' + ':pDES_ENDERECO, ' + ':pDES_RETORNO, ' + ':pCOD_RESULTADO, ' + ':pCOD_ORIGEM, ' + ':pDES_OBS, ' + ':pCOD_STATUS, ' + ':pDES_APURACAO, ' + ':pDOM_PROCESSADO, ' + ':pQTD_OCORRENCIAS, ' + ':pVAL_OCORRENCIA, ' + ':pDAT_DESCONTO, ' + ':pDOM_IMPRESSAO, ' + ':pDES_ANEXO, ' + ':pDES_LOG);'; Connection.ExecSQL(sSQL,[aOcorrencias.Numero, aOcorrencias.DataOcorrencia, aOcorrencias.CodigoAssinstura, aOcorrencias.Nome, aOcorrencias.Roteiro, aOcorrencias.Entregador, aOcorrencias.Produto, aOcorrencias.CodigoOcorrencia, aOcorrencias.Reincidente, aOcorrencias.Descricao, aOcorrencias.Endereco,aOcorrencias.Retorno, aOcorrencias.Resultado, aOcorrencias.Origem, aOcorrencias.Obs, aOcorrencias.Status, aOcorrencias.Apuracao, aOcorrencias.Processado, aOcorrencias.Qtde, aOcorrencias.Valor, aOcorrencias.DataDesconto, aOcorrencias.Impressao, aOcorrencias.Anexo, aOcorrencias.Log], [ftInteger, ftDate, ftString, ftString, ftString, ftInteger, ftString, ftInteger, ftString, ftString, ftString, ftString, ftInteger, ftInteger, ftString, ftInteger, ftString, ftString, ftInteger, ftFloat, ftDate, ftString, ftString, ftString]); Result := True; end; function TOcorrenciasJornalDAO.Update(aOcorrencias: TOcorrenciasJornal): Boolean; var sSQL : System.string; begin Result := False; sSQL := 'UPDATE ' + TABLENAME + ' SET '+ 'DAT_OCORRENCIA = :pDAT_OCORRENCIA, ' + 'COD_ASSINATURA = :pCOD_ASSINATURA, ' + 'NOM_ASSINANTE = :pNOM_ASSINANTE, ' + 'DES_ROTEIRO = :pDES_ROTEIRO, ' + 'COD_ENTREGADOR = :pCOD_ENTREGADOR, ' + 'COD_PRODUTO = :pCOD_PRODUTO, ' + 'COD_OCORRENCIA = :pCOD_OCORRENCIA, ' + 'DOM_REINCIDENTE = :pDOM_REINCIDENTE, ' + 'DES_DESCRICAO = :pDES_DESCRICAO, ' + 'DES_ENDERECO = :pDES_ENDERECO, ' + 'DES_RETORNO = :pDES_RETORNO, ' + 'COD_RESULTADO = :pCOD_RESULTADO, ' + 'COD_ORIGEM = :pCOD_ORIGEM, ' + 'DES_OBS = :pDES_OBS, ' + 'COD_STATUS = :pCOD_STATUS, ' + 'DES_APURACAO = :pDES_APURACAO, ' + 'DOM_PROCESSADO = :pDOM_PROCESSADO, ' + 'QTD_OCORRENCIAS = :pQTD_OCORRENCIAS, ' + 'VAL_OCORRENCIA = :pVAL_OCORRENCIA, ' + 'DAT_DESCONTO = :pDAT_DESCONTO, ' + 'DOM_IMPRESSAO = :pDOM_IMPRESSAO, ' + 'DES_ANEXO = :pDES_ANEXO, ' + 'DES_LOG = :pDES_LOG ' + 'WHERE NUM_OCORRENCIA = :pNUM_OCORRENCIA; '; Connection.ExecSQL(sSQL,[aOcorrencias.DataOcorrencia, aOcorrencias.CodigoAssinstura, aOcorrencias.Nome, aOcorrencias.Roteiro, aOcorrencias.Entregador, aOcorrencias.Produto, aOcorrencias.CodigoOcorrencia, aOcorrencias.Reincidente, aOcorrencias.Descricao, aOcorrencias.Endereco,aOcorrencias.Retorno, aOcorrencias.Resultado, aOcorrencias.Origem, aOcorrencias.Obs, aOcorrencias.Status, aOcorrencias.Apuracao, aOcorrencias.Processado, aOcorrencias.Qtde, aOcorrencias.Valor, aOcorrencias.DataDesconto, aOcorrencias.Impressao, aOcorrencias.Anexo, aOcorrencias.Log, aOcorrencias.Numero], [ftDate, ftString, ftString, ftString, ftInteger, ftString, ftInteger, ftString, ftString, ftString, ftString, ftInteger, ftInteger, ftString, ftInteger, ftString, ftString, ftInteger, ftFloat, ftDate, ftString, ftString, ftString, ftInteger]); Result := True; end; function TOcorrenciasJornalDAO.Delete(iNumero: Integer): Boolean; var sSQL : String; begin Result := False; sSQL := 'DELETE FROM ' + TABLENAME + ' WHERE NUM_OCORRENCIA = :pNUM_OCORRENCIA;'; Connection.ExecSQL(sSQL,[iNumero],[ftInteger]); Result := True; end; function TOcorrenciasJornalDAO.FindByNumero(iNumero: Integer): TObjectList<TOcorrenciasJornal>; var FDQuery: TFDQuery; ocorrencias: TObjectList<TOcorrenciasJornal>; begin FDQuery := TFDQuery.Create(nil); try FDQuery.Connection := Connection; FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME); FDQuery.SQL.Add('WHERE NUM_OCORRENCIA = :pNOM_OCORRENCIA'); FDQuery.ParamByName('pNUM_OCORRENCIA').AsInteger := iNumero; FDQuery.Open(); ocorrencias := TObjectList<TOcorrenciasJornal>.Create(); while not FDQuery.Eof do begin ocorrencias.Add(TOcorrenciasJornal.Create(FDQuery.FieldByName('NUM_OCORRENCIA').AsInteger, FDQuery.FieldByName('DAT_OCORRENCIA').AsDateTime, FDQuery.FieldByName('COD_ASSINATURA').AsString, FDQuery.FieldByName('NOM_ASSINANTE').AsString, FDQuery.FieldByName('DES_ROTEIRO').AsString, FDQuery.FieldByName('COD_ENTREGADOR').AsInteger, FDQuery.FieldByName('COD_PRODUTO').AsString, FDQuery.FieldByName('COD_OCORRENCIA').AsInteger, FDQuery.FieldByName('DOM_REINCIDENTE').AsString, FDQuery.FieldByName('DES_DESCRICAO').AsString, FDQuery.FieldByName('DES_ENDERECO').AsString, FDQuery.FieldByName('DES_RETORNO').AsString, FDQuery.FieldByName('COD_RESULTADO').AsInteger, FDQuery.FieldByName('COD_ORIGEM').AsInteger, FDQuery.FieldByName('DES_OBS').AsString, FDQuery.FieldByName('COD_STATUS').AsInteger, FDQuery.FieldByName('DES_APURACAO').AsString, FDQuery.FieldByName('DOM_PROCESSADO').AsString, FDQuery.FieldByName('QTD_OCORRENCIAS').AsInteger, FDQuery.FieldByName('VAL_OCORRENCIA').AsFloat, FDQuery.FieldByName('DAT_DESCONTO').AsDateTime, FDQuery.FieldByName('DOM_IMPRESSAO').AsString, FDQuery.FieldByName('DES_ANEXO').AsString, FDQuery.FieldByName('DES_LOG').AsString)); FDQuery.Next; end; finally FDQuery.Free; end; Result := ocorrencias; end; function TOcorrenciasJornalDAO.FindByData(dtData: TDate): TObjectList<TOcorrenciasJornal>; var FDQuery: TFDQuery; ocorrencias: TObjectList<TOcorrenciasJornal>; begin FDQuery := TFDQuery.Create(nil); try FDQuery.Connection := Connection; FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME); FDQuery.SQL.Add('WHERE DAT_OCORRENCIA = :pDAT_OCORRENCIA'); FDQuery.ParamByName('pDAT_OCORRENCIA').AsDate := dtData; FDQuery.Open(); ocorrencias := TObjectList<TOcorrenciasJornal>.Create(); while not FDQuery.Eof do begin ocorrencias.Add(TOcorrenciasJornal.Create(FDQuery.FieldByName('NUM_OCORRENCIA').AsInteger, FDQuery.FieldByName('DAT_OCORRENCIA').AsDateTime, FDQuery.FieldByName('COD_ASSINATURA').AsString, FDQuery.FieldByName('NOM_ASSINANTE').AsString, FDQuery.FieldByName('DES_ROTEIRO').AsString, FDQuery.FieldByName('COD_ENTREGADOR').AsInteger, FDQuery.FieldByName('COD_PRODUTO').AsString, FDQuery.FieldByName('COD_OCORRENCIA').AsInteger, FDQuery.FieldByName('DOM_REINCIDENTE').AsString, FDQuery.FieldByName('DES_DESCRICAO').AsString, FDQuery.FieldByName('DES_ENDERECO').AsString, FDQuery.FieldByName('DES_RETORNO').AsString, FDQuery.FieldByName('COD_RESULTADO').AsInteger, FDQuery.FieldByName('COD_ORIGEM').AsInteger, FDQuery.FieldByName('DES_OBS').AsString, FDQuery.FieldByName('COD_STATUS').AsInteger, FDQuery.FieldByName('DES_APURACAO').AsString, FDQuery.FieldByName('DOM_PROCESSADO').AsString, FDQuery.FieldByName('QTD_OCORRENCIAS').AsInteger, FDQuery.FieldByName('VAL_OCORRENCIA').AsFloat, FDQuery.FieldByName('DAT_DESCONTO').AsDateTime, FDQuery.FieldByName('DOM_IMPRESSAO').AsString, FDQuery.FieldByName('DES_ANEXO').AsString, FDQuery.FieldByName('DES_LOG').AsString)); FDQuery.Next; end; finally FDQuery.Free; end; Result := ocorrencias; end; function TOcorrenciasJornalDAO.FindByAssinatura(sAssinatura: String): TObjectList<TOcorrenciasJornal>; var FDQuery: TFDQuery; ocorrencias: TObjectList<TOcorrenciasJornal>; begin FDQuery := TFDQuery.Create(nil); try FDQuery.Connection := Connection; FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME); FDQuery.SQL.Add('WHERE COD_ASSINATURA = :pCOD_ASSINATURA'); FDQuery.ParamByName('pCOD_ASSINATURA').AsString := sAssinatura; FDQuery.Open(); ocorrencias := TObjectList<TOcorrenciasJornal>.Create(); while not FDQuery.Eof do begin ocorrencias.Add(TOcorrenciasJornal.Create(FDQuery.FieldByName('NUM_OCORRENCIA').AsInteger, FDQuery.FieldByName('DAT_OCORRENCIA').AsDateTime, FDQuery.FieldByName('COD_ASSINATURA').AsString, FDQuery.FieldByName('NOM_ASSINANTE').AsString, FDQuery.FieldByName('DES_ROTEIRO').AsString, FDQuery.FieldByName('COD_ENTREGADOR').AsInteger, FDQuery.FieldByName('COD_PRODUTO').AsString, FDQuery.FieldByName('COD_OCORRENCIA').AsInteger, FDQuery.FieldByName('DOM_REINCIDENTE').AsString, FDQuery.FieldByName('DES_DESCRICAO').AsString, FDQuery.FieldByName('DES_ENDERECO').AsString, FDQuery.FieldByName('DES_RETORNO').AsString, FDQuery.FieldByName('COD_RESULTADO').AsInteger, FDQuery.FieldByName('COD_ORIGEM').AsInteger, FDQuery.FieldByName('DES_OBS').AsString, FDQuery.FieldByName('COD_STATUS').AsInteger, FDQuery.FieldByName('DES_APURACAO').AsString, FDQuery.FieldByName('DOM_PROCESSADO').AsString, FDQuery.FieldByName('QTD_OCORRENCIAS').AsInteger, FDQuery.FieldByName('VAL_OCORRENCIA').AsFloat, FDQuery.FieldByName('DAT_DESCONTO').AsDateTime, FDQuery.FieldByName('DOM_IMPRESSAO').AsString, FDQuery.FieldByName('DES_ANEXO').AsString, FDQuery.FieldByName('DES_LOG').AsString)); FDQuery.Next; end; finally FDQuery.Free; end; Result := ocorrencias; end; function TOcorrenciasJornalDAO.FindByNome(sNome: String): TObjectList<TOcorrenciasJornal>; var FDQuery: TFDQuery; ocorrencias: TObjectList<TOcorrenciasJornal>; begin FDQuery := TFDQuery.Create(nil); try FDQuery.Connection := Connection; FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME); FDQuery.SQL.Add('WHERE NOM_ASSINANTE LIKE :pNOM_ASSINANTE'); FDQuery.ParamByName('pNOM_ASSINANTE').AsString := sNome; FDQuery.Open(); ocorrencias := TObjectList<TOcorrenciasJornal>.Create(); while not FDQuery.Eof do begin ocorrencias.Add(TOcorrenciasJornal.Create(FDQuery.FieldByName('NUM_OCORRENCIA').AsInteger, FDQuery.FieldByName('DAT_OCORRENCIA').AsDateTime, FDQuery.FieldByName('COD_ASSINATURA').AsString, FDQuery.FieldByName('NOM_ASSINANTE').AsString, FDQuery.FieldByName('DES_ROTEIRO').AsString, FDQuery.FieldByName('COD_ENTREGADOR').AsInteger, FDQuery.FieldByName('COD_PRODUTO').AsString, FDQuery.FieldByName('COD_OCORRENCIA').AsInteger, FDQuery.FieldByName('DOM_REINCIDENTE').AsString, FDQuery.FieldByName('DES_DESCRICAO').AsString, FDQuery.FieldByName('DES_ENDERECO').AsString, FDQuery.FieldByName('DES_RETORNO').AsString, FDQuery.FieldByName('COD_RESULTADO').AsInteger, FDQuery.FieldByName('COD_ORIGEM').AsInteger, FDQuery.FieldByName('DES_OBS').AsString, FDQuery.FieldByName('COD_STATUS').AsInteger, FDQuery.FieldByName('DES_APURACAO').AsString, FDQuery.FieldByName('DOM_PROCESSADO').AsString, FDQuery.FieldByName('QTD_OCORRENCIAS').AsInteger, FDQuery.FieldByName('VAL_OCORRENCIA').AsFloat, FDQuery.FieldByName('DAT_DESCONTO').AsDateTime, FDQuery.FieldByName('DOM_IMPRESSAO').AsString, FDQuery.FieldByName('DES_ANEXO').AsString, FDQuery.FieldByName('DES_LOG').AsString)); FDQuery.Next; end; finally FDQuery.Free; end; Result := ocorrencias; end; function TOcorrenciasJornalDAO.FindByRoteiro(sRoteiro: String): TObjectList<TOcorrenciasJornal>; var FDQuery: TFDQuery; ocorrencias: TObjectList<TOcorrenciasJornal>; begin FDQuery := TFDQuery.Create(nil); try FDQuery.Connection := Connection; FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME); FDQuery.SQL.Add('WHERE DES_ROTEIRO = :pDES_ROTEIRO'); FDQuery.ParamByName('pDES_ROTEIRO').AsString := sRoteiro; FDQuery.Open(); ocorrencias := TObjectList<TOcorrenciasJornal>.Create(); while not FDQuery.Eof do begin ocorrencias.Add(TOcorrenciasJornal.Create(FDQuery.FieldByName('NUM_OCORRENCIA').AsInteger, FDQuery.FieldByName('DAT_OCORRENCIA').AsDateTime, FDQuery.FieldByName('COD_ASSINATURA').AsString, FDQuery.FieldByName('NOM_ASSINANTE').AsString, FDQuery.FieldByName('DES_ROTEIRO').AsString, FDQuery.FieldByName('COD_ENTREGADOR').AsInteger, FDQuery.FieldByName('COD_PRODUTO').AsString, FDQuery.FieldByName('COD_OCORRENCIA').AsInteger, FDQuery.FieldByName('DOM_REINCIDENTE').AsString, FDQuery.FieldByName('DES_DESCRICAO').AsString, FDQuery.FieldByName('DES_ENDERECO').AsString, FDQuery.FieldByName('DES_RETORNO').AsString, FDQuery.FieldByName('COD_RESULTADO').AsInteger, FDQuery.FieldByName('COD_ORIGEM').AsInteger, FDQuery.FieldByName('DES_OBS').AsString, FDQuery.FieldByName('COD_STATUS').AsInteger, FDQuery.FieldByName('DES_APURACAO').AsString, FDQuery.FieldByName('DOM_PROCESSADO').AsString, FDQuery.FieldByName('QTD_OCORRENCIAS').AsInteger, FDQuery.FieldByName('VAL_OCORRENCIA').AsFloat, FDQuery.FieldByName('DAT_DESCONTO').AsDateTime, FDQuery.FieldByName('DOM_IMPRESSAO').AsString, FDQuery.FieldByName('DES_ANEXO').AsString, FDQuery.FieldByName('DES_LOG').AsString)); FDQuery.Next; end; finally FDQuery.Free; end; Result := ocorrencias; end; function TOcorrenciasJornalDAO.FindByEndereco(sEndereco: String): TObjectList<TOcorrenciasJornal>; var FDQuery: TFDQuery; ocorrencias: TObjectList<TOcorrenciasJornal>; begin FDQuery := TFDQuery.Create(nil); try FDQuery.Connection := Connection; FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME); FDQuery.SQL.Add('WHERE DES_ENDERECO LIKE :pDES_ENDERECO'); FDQuery.ParamByName('pDES_ENDERECO').AsString := sEndereco; FDQuery.Open(); ocorrencias := TObjectList<TOcorrenciasJornal>.Create(); while not FDQuery.Eof do begin ocorrencias.Add(TOcorrenciasJornal.Create(FDQuery.FieldByName('NUM_OCORRENCIA').AsInteger, FDQuery.FieldByName('DAT_OCORRENCIA').AsDateTime, FDQuery.FieldByName('COD_ASSINATURA').AsString, FDQuery.FieldByName('NOM_ASSINANTE').AsString, FDQuery.FieldByName('DES_ROTEIRO').AsString, FDQuery.FieldByName('COD_ENTREGADOR').AsInteger, FDQuery.FieldByName('COD_PRODUTO').AsString, FDQuery.FieldByName('COD_OCORRENCIA').AsInteger, FDQuery.FieldByName('DOM_REINCIDENTE').AsString, FDQuery.FieldByName('DES_DESCRICAO').AsString, FDQuery.FieldByName('DES_ENDERECO').AsString, FDQuery.FieldByName('DES_RETORNO').AsString, FDQuery.FieldByName('COD_RESULTADO').AsInteger, FDQuery.FieldByName('COD_ORIGEM').AsInteger, FDQuery.FieldByName('DES_OBS').AsString, FDQuery.FieldByName('COD_STATUS').AsInteger, FDQuery.FieldByName('DES_APURACAO').AsString, FDQuery.FieldByName('DOM_PROCESSADO').AsString, FDQuery.FieldByName('QTD_OCORRENCIAS').AsInteger, FDQuery.FieldByName('VAL_OCORRENCIA').AsFloat, FDQuery.FieldByName('DAT_DESCONTO').AsDateTime, FDQuery.FieldByName('DOM_IMPRESSAO').AsString, FDQuery.FieldByName('DES_ANEXO').AsString, FDQuery.FieldByName('DES_LOG').AsString)); FDQuery.Next; end; finally FDQuery.Free; end; Result := ocorrencias; end; end.
unit UDemo; interface uses SysUtils, Types, UITypes, Classes, Variants, FMX.TMSXUtil, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.TMSBaseControl, FMX.TMSGridOptions, FMX.TMSGridData, FMX.TMSGrid, FMX.Edit, FMX.TMSGridCell, FMX.TMSCustomGrid, FMX.StdCtrls, IOUtils; type TForm719 = class(TForm) TMSFMXGrid1: TTMSFMXGrid; Panel1: TPanel; Button1: TButton; Edit1: TEdit; Label1: TLabel; procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Edit1ChangeTracking(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form719: TForm719; implementation {$R *.fmx} procedure TForm719.Button1Click(Sender: TObject); var fltr : TFilterData; begin TMSFMXGrid1.Filter.Clear; fltr := TMSFMXGrid1.Filter.Add; fltr.Column := 1; fltr.Condition := 'A*'; Edit1.Text := 'A'; TMSFMXGrid1.ApplyFilter; end; procedure TForm719.Edit1ChangeTracking(Sender: TObject); var fltr : TFilterData; begin TMSFMXGrid1.UnHideRowsAll; TMSFMXGrid1.Filter.Clear; fltr := TMSFMXGrid1.Filter.Add; fltr.Column := 1; fltr.CaseSensitive := false; fltr.Condition := edit1.Text + '*'; TMSFMXGrid1.ApplyFilter; end; procedure TForm719.FormCreate(Sender: TObject); begin TMSFMXGrid1.IOOffset := Point(1,1); TMSFMXGrid1.LoadFromCSV(GetHomePath + '/CARS.CSV'); TMSFMXGrid1.ColumnWidths[1] := 100; Edit1.SetFocus; end; end.
unit AddRouteDestinationRequestUnit; interface uses REST.Json.Types, HttpQueryMemberAttributeUnit, GenericParametersUnit, AddressUnit; type TAddRouteDestinationRequest = class(TGenericParameters) private [JSONMarshalled(False)] [HttpQueryMember('route_id')] FRouteId: String; [JSONName('addresses')] FAddresses: TAddressesArray; [JSONName('optimal_position')] FOptimalPosition: boolean; public property RouteId: String read FRouteId write FRouteId; property Addresses: TAddressesArray read FAddresses write FAddresses; /// <summary> /// If true, an address will be inserted at optimal position of a route /// </summary> property OptimalPosition: boolean read FOptimalPosition write FOptimalPosition; end; implementation end.
unit fmuDump; interface uses // VCL Windows, Forms, Grids, Dialogs, StdCtrls, Buttons, ExtCtrls, Classes, Controls, SysUtils; type { TDeviceRec } TDeviceRec = record Code: Integer; Description: string; end; { TfmDump } TfmDump = class(TForm) Grid: TStringGrid; SaveDialog: TSaveDialog; OpenDialog: TOpenDialog; pnlTop: TPanel; btnSave: TBitBtn; btnCompare: TBitBtn; procedure FormCreate(Sender: TObject); procedure btnSaveClick(Sender: TObject); procedure btnCompareClick(Sender: TObject); private FDump: string; FDevice: TDeviceRec; procedure UpdatePage; end; procedure ShowDumpDlg(AOwner: TComponent; const Data: string; const ADevice: TDeviceRec); implementation {$R *.DFM} procedure ShowDumpDlg(AOwner: TComponent; const Data: string; const ADevice: TDeviceRec); var fm: TfmDump; begin fm := TfmDump.Create(AOwner); try fm.FDump := Data; fm.FDevice := ADevice; fm.UpdatePage; fm.ShowModal; finally fm.Free; end; end; { TfmDump } procedure TfmDump.FormCreate(Sender: TObject); Var i: Integer; begin for i := 1 to 16 do Grid.Cells[i,0] := IntToHex(i-1,2); Grid.ColWidths[0] := 60; end; procedure TfmDump.UpdatePage; var i, j: Integer; DataSize: Integer; RowCount: Integer; BytesCount: Integer; RowData: string; begin DataSize := Length(FDump); RowCount := DataSize div 16; if (DataSize mod 16) <> 0 then Inc(RowCount); if RowCount = 0 then RowCount := 1; Grid.RowCount := RowCount + 1; for i := 1 to RowCount do begin RowData := Copy(FDump, (i-1)*16 + 1, 16); BytesCount := Length(RowData); Grid.Cells[0, i] := IntToHex((i-1)*16, 6); for j := 1 to BytesCount do Grid.Cells[j, i] := IntToHex(Ord(RowData[j]), 2); for j := BytesCount + 1 to 16 do Grid.Cells[j, i] := ''; end; end; procedure TfmDump.btnSaveClick(Sender: TObject); var Stream: TFileStream; begin if SaveDialog.Execute then begin Stream := TFileStream.Create(SaveDialog.FileName, fmCreate); try Stream.Write(FDump[1], Length(FDump)); finally Stream.Free; end; end; end; procedure TfmDump.btnCompareClick(Sender: TObject); var S: string; Data: string; Stream: TFileStream; begin if not (FDevice.Code in [5,6]) then begin S := FDevice.Description + ' не сравнивается с эталоном.'; MessageBox(Handle, PChar(S), PChar(Application.Title), MB_OK or MB_ICONEXCLAMATION); Exit; end; if OpenDialog.Execute then begin Stream := TFileStream.Create(OpenDialog.FileName, fmOpenRead); try SetLength(Data, Stream.Size); Stream.Read(Data[1], Stream.Size); finally Stream.Free; end; if FDevice.Code = 5 then S := 'Прошивка ФП' else S := 'Прошивка ФР'; if FDump = Data then S := S + ' совпадает с эталонной.' else S := S + ' не совпадает с эталонной.'; MessageBox(Handle, PChar(S), PChar(Application.Title), MB_OK); end; end; end.
unit uFormatarTexto; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.DBCtrls, Vcl.ComCtrls, Vcl.ToolWin, Vcl.Buttons, Vcl.ImgList, uFormatacaoMemo; type TfrmFormatarTexto = class(TForm) ToolBar1: TToolBar; ToolButton3: TToolButton; ckCor: TColorBox; btn1: TToolButton; ckFontes: TComboBox; btn2: TToolButton; ckTamanho: TComboBox; btn3: TToolButton; btnItalico: TSpeedButton; btnNegrito: TSpeedButton; btnSublinhado: TSpeedButton; btnRiscado: TSpeedButton; ImageList1: TImageList; btnEsquerdo: TToolButton; ToolButton1: TToolButton; btnCentro: TToolButton; btnDireito: TToolButton; btnSalvar: TToolButton; btnVoltar: TToolButton; Editor: TRichEdit; BalloonHint1: TBalloonHint; procedure FormCreate(Sender: TObject); procedure btnVoltarClick(Sender: TObject); procedure btnNegritoClick(Sender: TObject); procedure btnItalicoClick(Sender: TObject); procedure btnSublinhadoClick(Sender: TObject); procedure ckFontesChange(Sender: TObject); procedure ckTamanhoChange(Sender: TObject); procedure ckCorChange(Sender: TObject); procedure btnRiscadoClick(Sender: TObject); procedure btnEsquerdoClick(Sender: TObject); procedure btnCentroClick(Sender: TObject); procedure btnDireitoClick(Sender: TObject); procedure btnSalvarClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private procedure Inicio; { Private declarations } public { Public declarations } constructor create(AEditor: TRichEdit); overload; constructor create(AEditor: TDBRichEdit); overload; end; var frmFormatarTexto: TfrmFormatarTexto; implementation {$R *.dfm} procedure TfrmFormatarTexto.btnCentroClick(Sender: TObject); begin TFormatacao.AlinhamentoCentro(Editor); end; procedure TfrmFormatarTexto.btnDireitoClick(Sender: TObject); begin TFormatacao.AlinhamentoDireito(Editor); end; procedure TfrmFormatarTexto.Inicio; begin Self.Top := 10; Self.Left := 10; ckFontes.Items := Screen.Fonts; ckFontes.Text := DefFontData.Name; ckTamanho.Text := IntToStr(-MulDiv(DefFontData.Height, 72, Screen.PixelsPerInch)); end; procedure TfrmFormatarTexto.btnEsquerdoClick(Sender: TObject); begin TFormatacao.AlinhamentoEsquerdo(Editor); end; procedure TfrmFormatarTexto.btnItalicoClick(Sender: TObject); begin TFormatacao.EstiloItalico(Editor); end; procedure TfrmFormatarTexto.btnNegritoClick(Sender: TObject); begin TFormatacao.EstiloNegrito(Editor); end; procedure TfrmFormatarTexto.btnRiscadoClick(Sender: TObject); begin TFormatacao.EstiloRiscado(Editor); end; procedure TfrmFormatarTexto.btnSalvarClick(Sender: TObject); begin Editor.SelectAll; Editor.CopyToClipboard; Close; ModalResult := mrOk; end; procedure TfrmFormatarTexto.btnSublinhadoClick(Sender: TObject); begin TFormatacao.EstiloSublinhado(Editor); end; procedure TfrmFormatarTexto.btnVoltarClick(Sender: TObject); begin Close; end; procedure TfrmFormatarTexto.ckCorChange(Sender: TObject); begin Editor.selattributes.Color := ckCor.Selected; end; procedure TfrmFormatarTexto.ckFontesChange(Sender: TObject); begin Editor.SelAttributes.Name := ckFontes.Items[ckFontes.ItemIndex]; end; procedure TfrmFormatarTexto.ckTamanhoChange(Sender: TObject); begin Editor.selattributes.Size := StrToInt(ckTamanho.Items[ckTamanho.ItemIndex]); end; constructor TfrmFormatarTexto.create(AEditor: TDBRichEdit); begin inherited create(nil); if Self.Height < AEditor.Height then Self.Height := AEditor.Height + 70; if Self.Width < AEditor.Width then Self.Width := AEditor.Width + 20; if Length(AEditor.Text) > 0 then begin AEditor.SelectAll; AEditor.CopyToClipboard; Editor.PasteFromClipboard; end; end; constructor TfrmFormatarTexto.create(AEditor: TRichEdit); begin inherited create(nil); if Self.Height < AEditor.Height then Self.Height := AEditor.Height + 70; if Self.Width < AEditor.Width then Self.Width := AEditor.Width + 20; if Length(AEditor.Text) > 0 then begin AEditor.SelectAll; AEditor.CopyToClipboard; Editor.PasteFromClipboard; end; end; procedure TfrmFormatarTexto.FormCreate(Sender: TObject); begin Inicio; end; procedure TfrmFormatarTexto.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case key of VK_F8: btnSalvarClick(Self); VK_ESCAPE: Close; end; end; procedure TfrmFormatarTexto.FormShow(Sender: TObject); begin Editor.SelStart := Perform(EM_LINEINDEX, 0, 0); // posiciona na primeira linha Editor.SetFocus; end; end.
{******************************************************************************* 作者: dmzn@163.com 2011-11-21 描述: 会员列表 *******************************************************************************} unit UFrameNotices; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UFrameBase, UGridPainter, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Menus, Grids, StdCtrls, cxButtons, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxButtonEdit, ExtCtrls, UGridExPainter, cxDropDownEdit, cxCalendar, UImageButton; type PNoticeItem = ^TNoticeItem; TNoticeItem = record FTitle: string; FMemo: string; FDate: string; end; TfFrameNotices = class(TfFrameBase) Panel2: TPanel; Label1: TLabel; LabelHint: TLabel; GridList: TDrawGridEx; EditTime: TcxComboBox; EditS: TcxDateEdit; EditE: TcxDateEdit; BtnSearch: TImageButton; procedure EditTimePropertiesEditValueChanged(Sender: TObject); procedure BtnSearchClick(Sender: TObject); private { Private declarations } FPainter: TGridPainter; //绘图对象 FList: TList; //列表 procedure ClearNotices(const nFree: Boolean); //清理内容 procedure LoadNotices(const nWhere: string); //载入通告 procedure OnBtnClick(Sender: TObject); //按钮点击 public { Public declarations } procedure OnCreateFrame; override; procedure OnDestroyFrame; override; class function FrameID: integer; override; end; implementation {$R *.dfm} uses DB, ULibFun, UDataModule, UMgrControl, USysFun, USysConst, USysDB, UFormNoticeView; class function TfFrameNotices.FrameID: integer; begin Result := cFI_FrameNotices; end; procedure TfFrameNotices.OnCreateFrame; begin Name := MakeFrameName(FrameID); FList := TList.Create; FPainter := TGridPainter.Create(GridList); with FPainter do begin HeaderFont.Style := HeaderFont.Style + [fsBold]; //粗体 AddHeader('序号', 50); AddHeader('标题', 50); AddHeader('内容', 50); AddHeader('通告时间', 50); AddHeader('查看', 50); end; EditTime.ItemIndex := 0; LoadDrawGridConfig(Name, GridList); AdjustLabelCaption(LabelHint, GridList); Width := GetGridHeaderWidth(GridList); BtnSearch.Top := EditTime.Top + Trunc((EditTime.Height - BtnSearch.Height) / 2); LoadNotices(''); end; procedure TfFrameNotices.OnDestroyFrame; begin SaveDrawGridConfig(Name, GridList); FPainter.Free; ClearNotices(True); end; procedure TfFrameNotices.ClearNotices(const nFree: Boolean); var nIdx: Integer; begin for nIdx:=FList.Count - 1 downto 0 do begin Dispose(PNoticeItem(FList[nIdx])); FList.Delete(nIdx); end; if nFree then FreeAndNil(FList); //xxxxx end; procedure TfFrameNotices.EditTimePropertiesEditValueChanged(Sender: TObject); var nS,nE: TDate; begin GetDateInterval(EditTime.ItemIndex, nS, nE); EditS.Date := nS; EditE.Date := nE; end; procedure TfFrameNotices.LoadNotices(const nWhere: string); var nStr,nHint: string; nIdx,nInt: Integer; nDS: TDataSet; nBtn: TImageButton; nItem: PNoticeItem; nData: TGridDataArray; begin nStr := 'Select Top 50 * From %s %s Order By CreateTime DESC'; nStr := Format(nStr, [sTable_DL_Noties, nWhere]); nDS := FDM.LockDataSet(nStr, nHint); try if not Assigned(nDS) then begin ShowDlg(nHint, sWarn); Exit; end; ClearNotices(False); FPainter.ClearData; if nDS.RecordCount < 1 then Exit; with nDS do begin nInt := 1; First; while not Eof do begin New(nItem); FList.Add(nItem); nItem.FTitle := FieldByName('NoticeTitle').AsString; nItem.FMemo := FieldByName('NoticeContent').AsString; nItem.FDate := DateTime2Str(FieldByName('CreateTime').AsDateTime); SetLength(nData, 5); for nIdx:=Low(nData) to High(nData) do begin nData[nIdx].FText := ''; nData[nIdx].FCtrls := nil; nData[nIdx].FAlign := taCenter; end; nData[0].FText := IntToStr(nInt); Inc(nInt); nData[1].FText := nItem.FTitle; nData[2].FText := nItem.FMemo; nData[3].FText := nItem.FDate; with nData[4] do begin FText := ''; FAlign := taCenter; FCtrls := TList.Create; nBtn := TImageButton.Create(Self); FCtrls.Add(nBtn); with nBtn do begin Parent := Self; nBtn.ButtonID := 'btn_view'; LoadButton(nBtn); OnClick := OnBtnClick; Tag := FList.Count - 1; end; end; FPainter.AddData(nData); Next; end; end; finally FDM.ReleaseDataSet(nDS); end; end; //Desc: 按钮处理 procedure TfFrameNotices.OnBtnClick(Sender: TObject); var nTag: Integer; begin nTag := TComponent(Sender).Tag; ShowNoticeViewForm(FList[nTag]); end; procedure TfFrameNotices.BtnSearchClick(Sender: TObject); var nStr: string; begin BtnSearch.Enabled := False; try nStr := 'Where (CreateTime>=''%s'' And CreateTime<''%s'')'; nStr := Format(nStr, [Date2Str(EditS.Date), Date2Str(EditE.Date+1)]); LoadNotices(nStr); finally BtnSearch.Enabled := True; end; end; initialization gControlManager.RegCtrl(TfFrameNotices, TfFrameNotices.FrameID); end.
{$include lem_directives.inc} unit GameSkillPanel; interface uses Classes, Controls, SysUtils, GR32, GR32_Image, GR32_Layers, { TODO : get rid of UMisc } UMisc, LemStrings, LemTypes, LemDosBmp, LemDosCmp, LemDosStructures, LemCore, LemLevel, LemDosStyle, LemDosGraphicSet, GameInterfaces, LemGame; {------------------------------------------------------------------------------- maybe this must be handled by lemgame (just bitmap writing) // info positions types: // 1. BUILDER(23) 1/14 // 2. OUT 28 15/23 // 3. IN 99% 24/31 // 4. TIME 2-31 32/40 -------------------------------------------------------------------------------} type TMinimapClickEvent = procedure(Sender: TObject; const P: TPoint) of object; type TSkillPanelToolbar = class(TCustomControl, IGameToolbar) private fStyle : TBaseDosLemmingStyle; fGraph : TBaseDosGraphicSet; fImg : TImage32; //fButtonHighlightLayer: TPositionedLayer; //fMinimapHighlightLayer: TPositionedLayer; fOriginal : TBitmap32; fLevel : TLevel; fSkillFont : array['0'..'9', 0..1] of TBitmap32; fInfoFont : array[0..37] of TBitmap32; {%} { 0..9} {A..Z} // make one of this! fGame : TLemmingGame; { TODO : do something with this hardcoded shit } fButtonRects : array[TSkillPanelButton] of TRect; fRectColor : TColor32; fViewPortRect : TRect; fOnMinimapClick : TMinimapClickEvent; // event handler for minimap fCurrentScreenOffset : Integer; procedure SetLevel(const Value: TLevel); procedure ImgMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); procedure ImgMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); procedure ImgMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); procedure SetGame(const Value: TLemmingGame); protected //procedure Paint; override; procedure ReadBitmapFromStyle; virtual; procedure ReadFont; procedure SetButtonRects; // procedure KeyDown(var Key: Word; Shift: TShiftState); override; public fLastDrawnStr: string[40]; fNewDrawStr: string[40]; RedrawnChars: Integer; constructor Create(aOwner: TComponent); override; destructor Destroy; override; // procedure DrawInfo(aType: TInfoType; const S: string); procedure DrawNewStr; property Img: TImage32 read fImg; procedure SetViewPort(const R: TRect); procedure RefreshInfo; { IGameInfoView support } procedure DrawSkillCount(aButton: TSkillPanelButton; aNumber: Integer); procedure DrawButtonSelector(aButton: TSkillPanelButton; Highlight: Boolean); procedure DrawMinimap(Map: TBitmap32); procedure SetInfoCursorLemming(const Lem: string; Num: Integer); procedure SetInfoLemmingsOut(Num: Integer); procedure SetInfoLemmingsIn(Num, Max: Integer); procedure SetInfoMinutes(Num: Integer); procedure SetInfoSeconds(Num: Integer); procedure SetCurrentScreenOffset(X: Integer); property OnMinimapClick: TMinimapClickEvent read fOnMinimapClick write fOnMinimapClick; published procedure SetStyleAndGraph(const Value: TBaseDosLemmingStyle; const aGraph: TBaseDosGraphicSet; aScale: Integer); property Level: TLevel read fLevel write SetLevel; property Game: TLemmingGame read fGame write SetGame; end; implementation uses GameWindow; function PtInRectEx(const Rect: TRect; const P: TPoint): Boolean; begin Result := (P.X >= Rect.Left) and (P.X < Rect.Right) and (P.Y >= Rect.Top) and (P.Y < Rect.Bottom); end; { TSkillPanelToolbar } constructor TSkillPanelToolbar.Create(aOwner: TComponent); var c: Char; i: Integer; begin inherited; // fBitmap := TBitmap.Create; fImg := TImage32.Create(Self); fImg.Parent := Self; fImg.RepaintMode := rmOptimizer; fImg.OnMouseDown := ImgMouseDown; fImg.OnMouseMove := ImgMouseMove; fImg.OnMouseUp := ImgMouseUp; fRectColor := DosVgaColorToColor32(DosInLevelPalette[3]); { fButtonHighlightLayer := TPositionedLayer.Create(Img.Layers); fButtonHighlightLayer.MouseEvents := False; fButtonHighlightLayer.Scaled := True; fButtonHighlightLayer.OnPaint := ButtonHighlightLayer_Paint; } { fMinimapHighlightLayer := TPositionedLayer.Create(Img.Layers); fMinimapHighlightLayer.MouseEvents := False; fMinimapHighlightLayer.Scaled := True; fMinimapHighlightLayer.OnPaint := MinimapHighlightLayer_Paint; } fOriginal := TBitmap32.Create; for i := 0 to 37 do fInfoFont[i] := TBitmap32.Create; for c := '0' to '9' do for i := 0 to 1 do fSkillFont[c, i] := TBitmap32.Create; // info positions types: // stringspositions=cursor,out,in,time=1,15,24,32 // 1. BUILDER(23) 1/14 0..13 14 // 2. OUT 28 15/23 14..22 9 // 3. IN 99% 24/31 23..30 8 // 4. TIME 2-31 32/40 31..39 9 //=40 fLastDrawnStr := StringOfChar(' ', 40); fNewDrawStr := StringOfChar(' ', 40); fNewDrawStr := SSkillPanelTemplate; // '..............' + 'OUT_.....' + 'IN_.....' + 'TIME_.-..'; // windlg([length(fnewDrawStr)]); Assert(length(fnewdrawstr) = 40, 'length error infostring'); end; destructor TSkillPanelToolbar.Destroy; var c: Char; i: Integer; begin for i := 0 to 37 do fInfoFont[i].Free; // fBitmap.Free; for c := '0' to '9' do for i := 0 to 1 do fSkillFont[c, i].Free; fOriginal.Free; inherited; end; procedure TSkillPanelToolbar.DrawButtonSelector(aButton: TSkillPanelButton; Highlight: Boolean); var R: TRect; C: TColor32; A: TRect; begin if aButton = spbNone then Exit; // if Highlight then //if aButton in [bskFaster, bskSlower, bskPause, bskNuke] then //Exit; { TODO : use other WHITE ?} case Highlight of False : begin R := fButtonRects[aButton]; Inc(R.Right); Inc(R.Bottom, 2); // top A := R; A.Bottom := A.Top + 1; fOriginal.DrawTo(fImg.Bitmap, A, A); // left A := R; A.Right := A.Left + 1; fOriginal.DrawTo(fImg.Bitmap, A, A); // right A := R; A.Left := A.Right - 1; fOriginal.DrawTo(fImg.Bitmap, A, A); // bottom A := R; A.Top := A.Bottom - 1; fOriginal.DrawTo(fImg.Bitmap, A, A); // fOriginal.DrawTo(fImg.Bitmap, R, R); // fOriginal.DrawTo(fImg.Bitmap, R, R); end; True : begin R := fButtonRects[aButton]; Inc(R.Right); Inc(R.Bottom, 2); { TODO : do something with this palettes } C := fRectColor;// clwhite32;//DosPaletteEntryToColor32(DosInLevelPalette[3]); fImg.Bitmap.FrameRectS(R, C); // C := clWhite32; //fImg.Bitmap.FrameRectS(fButtonRects[aButton], clWhite); end; end; end; (* procedure TSkillPanelToolbar.DrawInfo(aType: TInfoType; const S: string); var C: char; i, x, y, idx: integer; LocalS: string; begin // optimze this by pre-drawing // - "OUT " // - "IN " // - "TIME " // - "-" // info positions types: // 1. BUILDER(23) 1/14 0..13 // 2. OUT 28 15/23 14..22 // 3. IN 99% 24/31 23..30 // 4. TIME 2-31 32/40 31..39 case aType of itCursor: x := 0; itOut: x := 14 * 8; itIn : x := 23 * 8; itTime: x := 31 * 8 end; y := 0; LocalS := PadR(S, 14); for i := 1 to Length(LocalS) do begin idx := -1; C := UpCase(LocalS[i]); case C of '%': begin idx := 0; end; '0'..'9': begin idx := ord(c) - ord('0') + 1; end; '-': begin idx := 11; end; 'A'..'Z': begin idx := ord(c) - ord('A') + 12; end; end; // finfoforn[idx] //Assert(idx <= High(fInfoFont), 'infofont error'); if idx >= 0 then fInfoFont[idx].DrawTo(fimg.Bitmap, x, 0) else fimg.Bitmap.FillRectS(x, y, x + 8, y + 16, 0); Inc(x, 8); end; // fImg.Bitmap. end; *) procedure TSkillPanelToolbar.DrawNewStr; var O, N: char; i, x, y, idx: integer; // LocalS: string; Changed: Integer; begin Changed := 0; // optimze this by pre-drawing // - "OUT " // - "IN " // - "TIME " // - "-" // info positions types: // 1. BUILDER(23) 1/14 0..13 // 2. OUT 28 15/23 14..22 // 3. IN 99% 24/31 23..30 // 4. TIME 2-31 32/40 31..39 { case aType of itCursor: x := 0; itOut: x := 14 * 8; itIn : x := 23 * 8; itTime: x := 31 * 8 end; } y := 0; x := 0; for i := 1 to 40 do begin idx := -1; O := UpCase(fLastDrawnStr[i]); N := UpCase(fNewDrawStr[i]); if O <> N then begin case N of '%': begin idx := 0; end; '0'..'9': begin idx := ord(n) - ord('0') + 1; end; '-': begin idx := 11; end; 'A'..'Y': begin idx := ord(n) - ord('A') + 12; end; 'Z': begin idx := ord(n) - ord('A') + 12; end; end; Inc(Changed); // finfoforn[idx] if idx >= 0 then fInfoFont[idx].DrawTo(fimg.Bitmap, x, 0) else fimg.Bitmap.FillRectS(x, y, x + 8, y + 16, 0); end; Inc(x, 8); end; RedrawnChars := Changed; // fImg.Bitmap. end; procedure TSkillPanelToolbar.DrawSkillCount(aButton: TSkillPanelButton; aNumber: Integer); var S: string; L, R: Char; BtnIdx: Integer; DstRect, SrcRect: TRect; c:tcolor32; const FontYPos = 17; // Font begin // x = 3, 19, 35 etc. are the "black holes" for the numbers in the image // y = 17 // if aNumber < 0 then // aNumber Restrict(aNumber, 0, 99); // Assert(Between(aNumber, 0, 99), 'skillpanel number error 1'); S := LeadZeroStr(aNumber, 2); L := S[1]; R := S[2]; BtnIdx := Ord(aButton) - 1; // "ignore" the spbNone // white nothing if number is zero if aNumber = 0 then begin DstRect := Rect(BtnIdx * 16 + 4, 17, BtnIdx * 16 + 4 + 8, 17 + 8); c:=Color32(60*4, 52*4, 52*4); with DstRect do fImg.Bitmap.FillRect(Left, Top, Right, Bottom, c); // { TODO : use other WHITE } //=60,52,52 (*4) Exit; end; // left DstRect := Rect(BtnIdx * 16 + 4, 17, BtnIdx * 16 + 4 + 4, 17 + 8); SrcRect := Rect(0, 0, 4, 8); fSkillFont[L, 1].DrawTo(fImg.Bitmap, DstRect, SrcRect); // 1 is left // right RectMove(DstRect, 4, 0); SrcRect := Rect(4, 0, 8, 8); fSkillFont[R, 0].DrawTo(fImg.Bitmap, DstRect, SrcRect); // 0 is right // with // fimg.Bitmap.FillRect(0, 0, 20, 20, clwhite32); // fSkillFont[R, 1].DrawTo(fImg.Bitmap, BtnIdx * 16 + 3, 17) end; procedure TSkillPanelToolbar.RefreshInfo; begin DrawNewStr; fLastDrawnStr := fNewDrawStr;// := fLastDrawnStr; end; procedure TSkillPanelToolbar.ImgMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); {------------------------------------------------------------------------------- Mouse behaviour of toolbar. o Minimap scrolling o button clicks -------------------------------------------------------------------------------} var P: TPoint; i: TSkillPanelButton; R: PRect; Exec: Boolean; begin // Exec := False; P := Img.ControlToBitmap(Point(X, Y)); // check minimap scroll if PtInRectEx(DosMiniMapCorners, P) then begin Dec(P.X, DosMinimapCorners.Left); Dec(P.Y, DosMiniMapCorners.Top); P.X := P.X * 16; P.Y := P.Y * 8; if Assigned(fOnMiniMapClick) then fOnMinimapClick(Self, P); //Game.MiniMapClick(P); Exit; end; if Game.HyperSpeed or Game.FastForward then Exit; for i := Succ(Low(TSkillPanelButton)) to High(TSkillPanelButton) do // "ignore" spbNone begin R := @fButtonRects[i]; if PtInRectEx(R^, P) then begin if Game.SkillButtonsDisabledWhenPaused then Exec := not Game.Paused or (i = spbPause) else Exec := True; if Exec then if i = spbNuke then Exec := ssDouble in Shift; if Exec then begin if i <> spbPause then Game.RegainControl; Game.SetSelectedSkill(i, True, (ssRight in Shift)); end; Exit; end; end; end; procedure TSkillPanelToolbar.ImgMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); var P: TPoint; begin if ssLeft in Shift then begin P := Img.ControlToBitmap(Point(X, Y)); if PtInRectEx(DosMiniMapCorners, P) then begin Dec(P.X, DosMinimapCorners.Left); Dec(P.Y, DosMiniMapCorners.Top); P.X := P.X * 16; P.Y := P.Y * 8; if Assigned(fOnMiniMapClick) then fOnMinimapClick(Self, P); //Game.MiniMapClick(P); end; end; Game.HitTestAutoFail := true; end; procedure TSkillPanelToolbar.ImgMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); begin Game.SetSelectedSkill(spbSlower, False); Game.SetSelectedSkill(spbFaster, False); end; procedure TSkillPanelToolbar.ReadBitmapFromStyle; var Sty: TBaseDosLemmingStyle;//TDosOrigStyle; c: char; i: Integer; // pal: TDosVGAPalette8; // pal32: TArrayOfColor32; // Extr: TMainDatExtractor; Sections: TDosDatSectionList; Decompressor: TDosDatDecompressor; // MainDatFileStream: TFileStream; DataStream: TStream; Planar: TDosPlanarBitmap; Fn: string; LemmixPal: TArrayOfColor32; HiPal: TArrayOfColor32; // TempColor : TColor32; // pal begin if not (fStyle is TBaseDosLemmingStyle) then Exit; // try and concat palettes LemmixPal := DosPaletteToArrayOfColor32(DosInLevelPalette); if Game.fXmasPal then begin LemmixPal[1] := $D02020; LemmixPal[4] := $F0F000; LemmixPal[5] := $4040E0; end; HiPal := fGraph.PaletteCustom; {TODO: how o how is the palette constructed?????????} Assert(Length(HiPal) = 8, 'hipal error'); SetLength(LemmixPal, 16); for i := 8 to 15 do LemmixPal[i] := HiPal[i - 8]; LemmixPal[7] := LemmixPal[8]; sections := tdosdatsectionlist.create; Sty := TBaseDosLemmingStyle(fStyle); // TDosOrigStyle(fStyle); // Extr := TMainDatExtractor.Create(Sty.IncludeCommonPath(Sty.MainDataFile)); Fn := Sty.MainDataFile;// IncludeTrailingBackslash(Sty.CommonPath) + 'Main.dat'; // MainDatFileStream := TFileStream.Create(Fn, fmOpenRead); Decompressor := TDosDatDecompressor.Create; Planar := TDosPlanarBitmap.Create; // with Decompressor do begin SetButtonRects; {$ifdef external} if FileExists(Fn) then DataStream := TFileStream.Create(Fn, fmOpenRead) else{$endif} DataStream := CreateDataStream(Fn, ldtLemmings); try Decompressor.LoadSectionList(DataStream, Sections, False); finally DataStream.Free; end; //ExtractSkillPanel(fOriginal, DosInLevelPalette{fGraph.PaletteStandard}); Decompressor.DecompressSection(Sections[6].CompressedData, Sections[6].DecompressedData); //Planar.DirectRGB := False; Sections[6].DecompressedData.seek(0, sofrombeginning); Planar.LoadFromStream(Sections[6].DecompressedData, fOriginal, 0, 320, 40, 4, LemmixPal); fImg.Bitmap.Assign(fOriginal); // fOriginal.savetofile('skillpanel.bmp'); // info fonts //DoExtract(6); Sections[6].DecompressedData.Seek($1900, soFromBeginning); for i := 0 to 37 do Planar.LoadFromStream(Sections[6].DecompressedData, fInfofont[i], -1, 8,16, 3, LemmixPal);//DosInLevelPalette, DosInLevelPalette); // skill fonts //DoExtract(2); { TODO : christmas lemmings, fix it } // pal := DosInLevelPalette;// fGraph.palettestandard; {DosInLevelPalette;} // pal[1] := pal[3]; // WHITE LemmixPal[1] := LemmixPal[3]; // WHITE Decompressor.DecompressSection(Sections[2].CompressedData, Sections[2].DecompressedData); Sections[2].decompresseddata.seek($1900, sofrombeginning); for c := '0' to '9' do for i := 0 to 1 do begin Planar.LoadFromStream(sections[2].decompresseddata, fSkillFont[c, i], -1, 8, 8, 1, LemmixPal);//pal, pal); //fSkillFont[c,i].savetofile(AppPath+'temp\'+'skillfont_' + c + i2s(i) + '.bmp'); end; //Free; end; //fbitmap.savetofile(apppath+'sp.bmp'); // MainDatFileStream.free; decompressor.free; planar.free; sections.free; end; procedure TSkillPanelToolbar.ReadFont; begin end; procedure TSkillPanelToolbar.SetButtonRects; var Org, R: TRect; iButton: TSkillPanelButton; // Sca: Integer; // function ScaleRect(const ): begin // Sca := 3; Org := Rect(1, 16, 15, 38); // exact position of first button R := Org; {R.Left := R.Left * Sca; R.Right := R.Right * Sca; R.Top := R.Top * Sca; R.Bottom := R.Bottom * Sca; } for iButton := Succ(Low(TSkillPanelButton)) to High(TSkillPanelButton) do begin fButtonRects[iButton] := R; RectMove(R, 16{ * Sca}, 0); end; end; procedure TSkillPanelToolbar.SetInfoCursorLemming(const Lem: string; Num: Integer); var S: string; begin //exit; if Lem <> '' then begin S := PadR(Lem + ' ' + i2s(Num), 14); // Move(S[1], fNewDrawStr[1], 14); end else begin S := ' '; Move(S[1], fNewDrawStr[1], 14); end; end; procedure TSkillPanelToolbar.SetInfoLemmingsOut(Num: Integer); var S: string; begin // stringspositions cursor,out,in,time = 1,15,24,32 //fNewDrawStr := '..............' + 'OUT_.....' + 'IN_.....' + 'TIME_.-..'; S := PadR(i2s(Num), 5); Move(S[1], fNewDrawStr[19], 5); end; procedure TSkillPanelToolbar.SetInfoLemmingsIn(Num, Max: Integer); var S: string; begin // stringspositions cursor,out,in,time = 1,15,24,32 //fNewDrawStr := '..............' + 'OUT_.....' + 'IN_.....' + 'TIME_.-..'; { TODO : percentage } S := PadR(i2s(percentage(Max, Num)) + '%', 5); Move(S[1], fNewDrawStr[27], 5); end; procedure TSkillPanelToolbar.SetInfoMinutes(Num: Integer); var S: string; begin // stringspositions cursor,out,in,time = 1,15,24,32 //fNewDrawStr := '..............' + 'OUT_.....' + 'IN_.....' + 'TIME_.-..'; S := PadL(i2s(Num), 2); Move(S[1], fNewDrawStr[36], 2); end; procedure TSkillPanelToolbar.SetInfoSeconds(Num: Integer); var S: string; begin // stringspositions cursor,out,in,time = 1,15,24,32 //fNewDrawStr := '..............' + 'OUT_.....' + 'IN_.....' + 'TIME_.-..'; S := LeadZeroStr(Num, 2); Move(S[1], fNewDrawStr[39], 2); end; procedure TSkillPanelToolbar.SetLevel(const Value: TLevel); begin fLevel := Value; end; procedure TSkillPanelToolbar.SetStyleAndGraph(const Value: TBaseDosLemmingStyle; const aGraph: TBaseDosGraphicSet; aScale: Integer); begin fImg.BeginUpdate; fStyle := Value; fGraph := aGraph; if fStyle <> nil then begin ReadBitmapFromStyle; ReadFont; end; // Width := fBitmap.Width; // Height := fBitmap.Height; fImg.Scale := aScale; fImg.ScaleMode := smScale; //fImg.AutoSize := True; fImg.Height := fOriginal.Height * aScale; fImg.Width := fOriginal.Width * aScale; Width := fImg.Width; Height := fImg.Height; // AutoSize := True; // fImg.Width * fImg.Bitmap.Width // DrawNumber(bskClimber, 23); // DrawInfo('1234567890123456789012345678901234567890'); fImg.EndUpdate; fImg.Changed; Invalidate; end; procedure TSkillPanelToolbar.SetViewPort(const R: TRect); begin fViewPortRect := R; // fMinimapHighlightLayer.Changed; end; procedure TSkillPanelToolbar.DrawMinimap(Map: TBitmap32); var X: Integer; begin Map.DrawTo(Img.Bitmap, 208, 18); if Parent <> nil then begin X := -Round(TGameWindow(Parent).ScreenImg.OffsetHorz/(16 * fImg.Scale)); Img.Bitmap.FrameRectS(208 + X, 18, 208 + X + 20 + 5, 38, fRectColor); end; end; procedure TSkillPanelToolbar.SetGame(const Value: TLemmingGame); begin if fGame <> nil then fGame.InfoPainter := nil; fGame := Value; if fGame <> nil then fGame.InfoPainter := Self // else // fGame.InfoPainter := nil; end; procedure TSkillPanelToolbar.SetCurrentScreenOffset(X: Integer); begin fCurrentScreenOffset := X; end; end.
unit MapViewerWindow; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, Buttons, LandGenerator, Land; type TLandViewerWin = class(TForm) Panel1: TPanel; OpenBmp: TOpenDialog; OpenClasses: TOpenDialog; LoadBitmap: TSpeedButton; ScrollBox2: TScrollBox; DestBmp: TImage; landN: TImage; LandS: TImage; LandE: TImage; LandW: TImage; LandNEo: TImage; landSEo: TImage; landSWo: TImage; landNWo: TImage; landCenter: TImage; landNWi: TImage; landNEi: TImage; landSEi: TImage; landSWi: TImage; landSpecial: TImage; SaveDialog: TSaveDialog; SpeedButton1: TSpeedButton; procedure FormCreate(Sender: TObject); procedure LoadBitmapClick(Sender: TObject); procedure SpeedButton1Click(Sender: TObject); procedure SaveMask(Sender: TObject); private fLandRenderer : TLandRenderer; LandImgs : array[TLandType] of TImage; end; var LandViewerWin: TLandViewerWin; implementation {$R *.DFM} procedure TLandViewerWin.FormCreate(Sender: TObject); var LandType : TLandType; begin OpenClasses.InitialDir := ExtractFilePath( paramstr(0) ); if OpenClasses.Execute and (OpenClasses.FileName <> '') then begin fLandRenderer := TLandRenderer.Create( ExtractFilePath(OpenClasses.FileName) ); Application.MessageBox( pchar(IntToStr(fLandRenderer.ClassCount) + ' classes read.'), 'Done', MB_ICONINFORMATION or MB_OK ); LandImgs[ldtCenter] := landCenter; LandImgs[ldtN] := landN; LandImgs[ldtE] := landE; LandImgs[ldtS] := landS; LandImgs[ldtW] := landW; LandImgs[ldtNEo] := landNEo; LandImgs[ldtSEo] := landSEo; LandImgs[ldtSWo] := landSWo; LandImgs[ldtNWo] := landNWo; LandImgs[ldtNEi] := landNEi; LandImgs[ldtSEi] := landSEi; LandImgs[ldtSWi] := landSWi; LandImgs[ldtNWi] := landNWi; LandImgs[ldtSpecial] := landSpecial; { for LandType := low(LandType) to high(LandType) do with LandImgs[LandType] do begin Stretch := true; Width := Width div 2; Height := Height div 2; end; } end else Close; end; procedure TLandViewerWin.LoadBitmapClick(Sender: TObject); var filename : string; begin if OpenBmp.Execute and (OpenBmp.FileName <> '') then begin filename := OpenBmp.FileName; fLandRenderer.LoadRenderedLand( filename ); SpeedButton1Click( self ); end; end; procedure TLandViewerWin.SpeedButton1Click(Sender: TObject); const MaxRes = 4000; type TRGB = packed record r, g, b, x : byte; end; var x, y, i : integer; SourceRect, DestRect : TRect; LandType : TLandType; LandImg : TImage; begin DestBmp.Picture.Bitmap := TBitmap.Create; if landCenter.Width*fLandRenderer.LandSize.x < MaxRes then DestBmp.Picture.Bitmap.Width := landCenter.Width*fLandRenderer.LandSize.x else DestBmp.Picture.Bitmap.Width := MaxRes; if landCenter.Height*fLandRenderer.LandSize.y < MaxRes then DestBmp.Picture.Bitmap.Height := landCenter.Height*fLandRenderer.LandSize.y else DestBmp.Picture.Bitmap.Height := MaxRes; SourceRect := Bounds( 0, 0, landCenter.Width, landCenter.Height ); for x := 0 to pred(fLandRenderer.LandSize.x) do for y := 0 to pred(fLandRenderer.LandSize.y) do begin LandType := LandTypeOf(fLandRenderer.LandSource[y*fLandRenderer.LandSize.x + x]); LandImg := LandImgs[LandType]; DestRect := Bounds( landCenter.Width*x, landCenter.Height*y, landCenter.Width, landCenter.Height ); if LandImg <> nil then DestBmp.Picture.Bitmap.Canvas.CopyRect( DestRect, LandImg.Picture.Bitmap.Canvas, SourceRect ); end; end; procedure TLandViewerWin.SaveMask(Sender: TObject); var Mask : TBitmap; begin Mask := TBitmap.Create; end; end.
unit Unit11; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TForm11 = class(TForm) Memo1: TMemo; Button1: TButton; Button2: TButton; Button3: TButton; Button4: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Button4Click(Sender: TObject); private FDatabasename: String; procedure SetDatabasename(const Value: String); { Private declarations } public { Public declarations } procedure executar; procedure mostrarLinha(i: integer); procedure mostrar(AProc: TProc); procedure mensagem(texto:string); property Databasename: String read FDatabasename write SetDatabasename; end; var Form11: TForm11; implementation {$R *.dfm} uses db_store, data.db.helper, System.Threading; procedure TForm11.Button1Click(Sender: TObject); begin executar; end; procedure TForm11.Button2Click(Sender: TObject); var i:integer; begin TTask.Run( //TThread.CreateAnonymousThread( procedure var i:integer; begin for i := 0 to 10000 do mensagem(i.ToString()); //mostrarLinha(i); end).Start; end; procedure TForm11.Button3Click(Sender: TObject); begin mostrar( procedure var i: integer; begin for i := 0 to 1000 do mostrarLinha(i); end); end; procedure TForm11.Button4Click(Sender: TObject); begin // TThread.CreateAnonymousThread( TTask.Run( procedure begin with createQuery(FDatabasename) do try SQLDBFile := 'sigcad'; SQLFields := 'nome'; open; DoLoopEvent( procedure begin mensagem( FieldBYName('nome').asString); end); (* while eof=false do begin memo1.Lines.Add(FieldBYName('nome').asString); next; end; *) finally free; end; end).Start; end; procedure TForm11.executar; var i: integer; begin for i := 0 to 10000 do mostrarLinha(i); end; procedure TForm11.FormCreate(Sender: TObject); begin FDatabasename := 'aliasEstoque'; ConnectDataBaseFromIni('SQLEstoque', FDatabasename, 'estoque.ini', true); end; procedure TForm11.mensagem(texto: string); begin TThread.Synchronize(nil , procedure begin memo1.Lines.Add(texto); end); end; procedure TForm11.mostrar(AProc: TProc); begin AProc; end; procedure TForm11.mostrarLinha(i: integer); begin mensagem(i.ToString()); end; procedure TForm11.SetDatabasename(const Value: String); begin FDatabasename := Value; end; end.
unit kwIterateSubDecriptorsOnSubPanelEX; {* Перебирает все SubDescriptot на SubPanel, которые *могут быть* отрисованы (!). Т.е. проверка на Visible не производится. Если это нужно, то можно реализвать в скриптах. Формат: [code] @ aWord aLayerID aSubPanel IterateSubDecriptorsOnSubPanelEX [code] aLayerID - слой, в котором производится итерация aSubPanel - контрол сабпанели. aWord - функция для обработки вида: [code] PROCEDURE CheckDescription OBJECT IN aSubDescription OBJECT IN aSubPanelSub // А здесь обрабатываем полученный aSubDescription ; [code] Для извлечения нужной инфорации из aSubDescription есть набор функций: subdescriptor:GetDrawType и т.п. aSubPanelSub - визуальное представление метки. } // Модуль: "w:\common\components\rtl\Garant\ScriptEngine\kwIterateSubDecriptorsOnSubPanelEX.pas" // Стереотип: "ScriptKeyword" // Элемент модели: "IterateSubDecriptorsOnSubPanelEX" MUID: (53EDF0A20129) // Имя типа: "TkwIterateSubDecriptorsOnSubPanelEX" {$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc} interface {$If NOT Defined(NoScripts)} uses l3IntfUses , kwIterateSubDecriptorsOnSubPanel , tfwScriptingInterfaces , evSubPn , evSubPanelSub ; type TkwIterateSubDecriptorsOnSubPanelEX = {final} class(TkwIterateSubDecriptorsOnSubPanel) {* Перебирает все SubDescriptot на SubPanel, которые *могут быть* отрисованы (!). Т.е. проверка на Visible не производится. Если это нужно, то можно реализвать в скриптах. Формат: [code] @ aWord aLayerID aSubPanel IterateSubDecriptorsOnSubPanelEX [code] aLayerID - слой, в котором производится итерация aSubPanel - контрол сабпанели. aWord - функция для обработки вида: [code] PROCEDURE CheckDescription OBJECT IN aSubDescription OBJECT IN aSubPanelSub // А здесь обрабатываем полученный aSubDescription ; [code] Для извлечения нужной инфорации из aSubDescription есть набор функций: subdescriptor:GetDrawType и т.п. aSubPanelSub - визуальное представление метки. } protected procedure PushObjData(const aCtx: TtfwContext; aSubDescription: TevSubDescriptor; aSubPanelSub: TevSubPanelSub); override; class function GetWordNameForRegister: AnsiString; override; end;//TkwIterateSubDecriptorsOnSubPanelEX {$IfEnd} // NOT Defined(NoScripts) implementation {$If NOT Defined(NoScripts)} uses l3ImplUses , evSubPanelSubArray , evSubPanelSubCollection //#UC START# *53EDF0A20129impl_uses* //#UC END# *53EDF0A20129impl_uses* ; procedure TkwIterateSubDecriptorsOnSubPanelEX.PushObjData(const aCtx: TtfwContext; aSubDescription: TevSubDescriptor; aSubPanelSub: TevSubPanelSub); //#UC START# *53EDFA0401B8_53EDF0A20129_var* //#UC END# *53EDFA0401B8_53EDF0A20129_var* begin //#UC START# *53EDFA0401B8_53EDF0A20129_impl* aCtx.rEngine.PushObj(aSubDescription); aCtx.rEngine.PushObj(aSubPanelSub); //#UC END# *53EDFA0401B8_53EDF0A20129_impl* end;//TkwIterateSubDecriptorsOnSubPanelEX.PushObjData class function TkwIterateSubDecriptorsOnSubPanelEX.GetWordNameForRegister: AnsiString; begin Result := 'IterateSubDecriptorsOnSubPanelEX'; end;//TkwIterateSubDecriptorsOnSubPanelEX.GetWordNameForRegister initialization TkwIterateSubDecriptorsOnSubPanelEX.RegisterInEngine; {* Регистрация IterateSubDecriptorsOnSubPanelEX } {$IfEnd} // NOT Defined(NoScripts) end.
{ Subroutine SST_REC_VARIANT (DTYPE) * * This function returns TRUE if the record data type in DTYPE contains any * variants (overlays). It is an error if DTYPE is not a record data type. } module sst_REC_VARIANT; define sst_rec_variant; %include 'sst2.ins.pas'; const max_msg_parms = 1; {max parameters we can pass to a message} function sst_rec_variant ( {determine if record has any overlays} in dtype: sst_dtype_t) {descriptor for record's data type} :boolean; {TRUE if record has variants} val_param; var sym_p: sst_symbol_p_t; {pointer to current field symbol} msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; begin if dtype.dtype <> sst_dtype_rec_k then begin {data type is not a record ?} sys_msg_parm_int (msg_parm[1], ord(dtype.dtype)); sys_message_bomb ('sst', 'dtype_not_record', msg_parm, 1); end; sst_rec_variant := false; {init to this record has no overlays} sym_p := dtype.rec_first_p; {init current field symbol to first field} while sym_p <> nil do begin {loop thru all the fields in this record} if sym_p^.field_variant <> 0 then begin {this field is in an overlay ?} sst_rec_variant := true; {this record definately has overlays} return; end; sym_p := sym_p^.field_next_p; {advance to next field in this record} end; {back and process this new field} end; {return indicating record has no overlays}
unit uCRUDDespesas; interface uses FireDAC.Comp.Client, System.SysUtils; type TCrudDespesas = class(TObject) private FConexao : TFDConnection; FQuery : TFDQuery; Fcd_Valor: Double; Fcd_Descricao: String; Fcd_Ano: String; Fcd_Sequencia: Integer; FpoMemTable: TFDMemTable; procedure Setcd_Ano(const Value: String); procedure Setcd_Descricao(const Value: String); procedure Setcd_Valor(const Value: Double); procedure Setcd_Sequencia(const Value: Integer); procedure SetpoMemTable(const Value: TFDMemTable); public constructor Create(poConexao : TFDConnection); destructor Destroy; override; function fncRetornaValorTotalANO(pdAno:String): Double; procedure pcdGravarDadosBanco; procedure pcdExcluirDadosBanco; published property cd_Sequencia : Integer read Fcd_Sequencia write Setcd_Sequencia; property cd_Ano : String read Fcd_Ano write Setcd_Ano; property cd_Descricao : String read Fcd_Descricao write Setcd_Descricao; property cd_Valor : Double read Fcd_Valor write Setcd_Valor; property poMemTable : TFDMemTable read FpoMemTable write SetpoMemTable; end; implementation { TCrudDespesas } constructor TCrudDespesas.Create(poConexao: TFDConnection); begin FConexao := poConexao; FQuery := TFDQuery.Create(nil); FQuery.Connection := FConexao; FQuery.Close; end; destructor TCrudDespesas.Destroy; begin if Assigned(FQuery) then FreeAndNil(FQuery); inherited; end; function TCrudDespesas.fncRetornaValorTotalANO(pdAno:String): Double; begin Result := 0; FQuery.Close; FQuery.SQL.Clear; FQuery.SQL.Add('SELECT SUM(DESP_VALOR) AS VALOR FROM DESPESAS WHERE DESP_ANO = :DESP_ANO'); FQuery.ParamByName('DESP_ANO').AsString := pdAno; FQuery.Open; Result := FQuery.FieldByName('VALOR').AsFloat; end; procedure TCrudDespesas.pcdExcluirDadosBanco; begin FQuery.Close; FQuery.SQL.Clear; FQuery.SQL.Add('DELETE FROM DESPESAS WHERE DESP_SEQUENCIA = :DESP_SEQUENCIA'); FQuery.ParamByName('DESP_SEQUENCIA').AsInteger := Fcd_Sequencia; FQuery.ExecSQL; end; procedure TCrudDespesas.pcdGravarDadosBanco; begin FQuery.Close; FQuery.SQL.Clear; FQuery.SQL.Add('INSERT INTO DESPESAS (DESP_ANO, DESP_DESCRICAO, DESP_VALOR) VALUES (:DESP_ANO, :DESP_DESCRICAO, :DESP_VALOR);'); FQuery.ParamByName('DESP_DESCRICAO').AsString := Fcd_Descricao; FQuery.ParamByName('DESP_ANO').AsString := Fcd_Ano; FQuery.ParamByName('DESP_VALOR').AsFloat := Fcd_Valor; FQuery.ExecSQL; end; procedure TCrudDespesas.Setcd_Ano(const Value: String); begin Fcd_Ano := Value; end; procedure TCrudDespesas.Setcd_Descricao(const Value: String); begin Fcd_Descricao := Value; end; procedure TCrudDespesas.Setcd_Sequencia(const Value: Integer); begin Fcd_Sequencia := Value; end; procedure TCrudDespesas.Setcd_Valor(const Value: Double); begin Fcd_Valor := Value; end; procedure TCrudDespesas.SetpoMemTable(const Value: TFDMemTable); begin FpoMemTable := Value; end; end.
unit TestOrderSamplesUnit; interface uses TestFramework, Classes, SysUtils, DateUtils, BaseTestOnlineExamplesUnit, NullableBasicTypesUnit, OrderUnit; type TTestOrderSamples = class(TTestOnlineExamples) private function GetTestOrder: TOrder; published procedure AddNewOrder; procedure GetOrderById; procedure GetAllOrders; procedure ScheduleOrder; procedure GetOrdersByDate; procedure GetOrdersScheduledFor; procedure GetOrdersWithSpecifiedText; procedure GetOrdersWithCustomFields; procedure AddOrderToOptimization; procedure UpdateOrder; procedure RemoveOrder; end; implementation { TTestMemberSamples } uses UserParametersUnit, UserParameterProviderUnit, UserUnit, EnumsUnit, OrderParametersUnit, CommonTypesUnit, DataObjectUnit, AddOrderToRouteRequestUnit, OrderActionsUnit; var FOrderId: NullableInteger; { TTestOrderSamples } procedure TTestOrderSamples.AddNewOrder; var Order: TOrder; AddedOrder: TOrder; ErrorString: String; begin Order := GetTestOrder; try // Correct adding new order. Must be success. AddedOrder := FRoute4MeManager.Order.Add(Order, ErrorString); try CheckNotNull(AddedOrder); CheckEquals(EmptyStr, ErrorString); CheckTrue(AddedOrder.Id.IsNotNull); FOrderId := AddedOrder.Id; finally FreeAndNil(AddedOrder); end; finally FreeAndNil(Order); end; end; procedure TTestOrderSamples.AddOrderToOptimization; begin // todo 4: сделать unit-тест end; procedure TTestOrderSamples.GetAllOrders; var Parameters: TOrderParameters; Total: integer; ErrorString: String; Orders: TOrderList; OrderIds: TIntegerArray; i: integer; begin Parameters := TOrderParameters.Create; try Parameters.Limit := 5; Orders := FRoute4MeManager.Order.Get(Parameters, Total, ErrorString); try CheckNotNull(Orders); CheckEquals(EmptyStr, ErrorString); CheckEquals(5, Orders.Count); CheckTrue(Total > 0); SetLength(OrderIds, Orders.Count); for i := 0 to Orders.Count - 1 do OrderIds[i] := Orders[i].Id; finally FreeAndNil(Orders); end; try Parameters.Limit := 2; Orders := FRoute4MeManager.Order.Get(Parameters, Total, ErrorString); CheckNotNull(Orders); CheckEquals(EmptyStr, ErrorString); CheckEquals(2, Orders.Count); CheckTrue(Total > 0); CheckTrue(OrderIds[0] = Orders[0].Id); CheckTrue(OrderIds[1] = Orders[1].Id); finally FreeAndNil(Orders); end; try Parameters.Limit := 2; Parameters.Offset := 2; Orders := FRoute4MeManager.Order.Get(Parameters, Total, ErrorString); CheckNotNull(Orders); CheckEquals(EmptyStr, ErrorString); CheckEquals(2, Orders.Count); CheckTrue(Total > 0); CheckTrue(OrderIds[2] = Orders[0].Id); CheckTrue(OrderIds[3] = Orders[1].Id); finally FreeAndNil(Orders); end; try Parameters.Limit := 2; Parameters.Offset := Total; Orders := FRoute4MeManager.Order.Get(Parameters, Total, ErrorString); CheckNotNull(Orders); CheckEquals(EmptyStr, ErrorString); CheckEquals(0, Orders.Count); CheckTrue(Total > 0); finally FreeAndNil(Orders); end; finally FreeAndNil(Parameters); end; end; procedure TTestOrderSamples.GetOrderById; var Order: TOrder; ErrorString: String; begin // Correct OrderId. Must be success. Order := FRoute4MeManager.Order.Get(FOrderId, ErrorString); try CheckNotNull(Order); CheckEquals(EmptyStr, ErrorString); finally FreeAndNil(Order); end; // Invalid OrderId. Must be error. Order := FRoute4MeManager.Order.Get(-1, ErrorString); try CheckNull(Order); CheckNotEquals(EmptyStr, ErrorString); finally FreeAndNil(Order); end; end; procedure TTestOrderSamples.GetOrdersByDate; var ErrorString: String; Date: TDate; Orders: TOrderList; i: integer; IsFound: boolean; begin // Correct date. Must be success. Date := Now(); Orders := FRoute4MeManager.Order.Get(Date, ErrorString); try CheckNotNull(Orders); CheckTrue(Orders.Count > 0); CheckEquals(EmptyStr, ErrorString); IsFound := False; for i := 0 to Orders.Count - 1 do if (Orders[i].Id = FOrderId) then begin IsFound := True; Break; end; CheckTrue(IsFound); finally FreeAndNil(Orders); end; // TODO 1: Олега спросил почему для дат из будущего и прошлого список заказов не пуст. Ответа нет. Проанализировать какие ордера возвращаются при этом. { Date := EncodeDateTime(1980, 06, 15, 0, 0, 0, 0); // Invalid date. Must be error. Orders := FRoute4MeManager.Order.Get(Date, ErrorString); try CheckNotNull(Orders); CheckEquals(0, Orders.Count); CheckEquals(EmptyStr, ErrorString); finally FreeAndNil(Orders); end; Date := EncodeDateTime(2216, 06, 15, 0, 0, 0, 0); // Invalid date. Must be error. Orders := FRoute4MeManager.Order.Get(Date, ErrorString); try CheckNotNull(Orders); CheckEquals(0, Orders.Count); CheckEquals(EmptyStr, ErrorString); finally FreeAndNil(Orders); end;} end; procedure TTestOrderSamples.GetOrdersScheduledFor; var ErrorString: String; Orders: TOrderList; IsFound: boolean; i: integer; begin // Correct date. Must be success. Orders := FRoute4MeManager.Order.GetOrdersScheduledFor(Tomorrow, ErrorString); try CheckNotNull(Orders); CheckTrue(Orders.Count > 0); CheckEquals(EmptyStr, ErrorString); IsFound := False; for i := 0 to Orders.Count - 1 do if (Orders[i].Id = FOrderId) then begin IsFound := True; Break; end; CheckTrue(IsFound); finally FreeAndNil(Orders); end; // DONE 5: Олега спросил почему для дат из будущего и прошлого список заказов не пуст. Ответа нет. { // Invalid date. Must be error. Orders := FRoute4MeManager.Order.GetOrdersScheduledFor(IncDay(Now, -2), ErrorString); try CheckNotNull(Orders); CheckEquals(0, Orders.Count); CheckEquals(EmptyStr, ErrorString); finally FreeAndNil(Orders); end;} end; procedure TTestOrderSamples.GetOrdersWithCustomFields; var ErrorString: String; Orders: TOrdersCustomFields; Offset, Limit, Total: integer; Fields: TStringArray; Value: string; IsException: boolean; begin SetLength(Fields, 0); Limit := 2; Offset := 0; Orders := FRoute4MeManager.Order.GetOrdersWithCustomFields( Fields, Limit, Offset, Total, ErrorString); try CheckNotNull(Orders); CheckEquals(0, Orders.Count); CheckNotEquals(EmptyStr, ErrorString); CheckEquals(0, Total); finally FreeAndNil(Orders); end; Fields := ['randomField']; IsException := False; try Orders := FRoute4MeManager.Order.GetOrdersWithCustomFields( Fields, Limit, Offset, Total, ErrorString); except IsException := True; end; CheckTrue(IsException); Fields := ['order_id']; Orders := FRoute4MeManager.Order.GetOrdersWithCustomFields( Fields, Limit, Offset, Total, ErrorString); try CheckNotNull(Orders); CheckEquals(2, Orders.Count); CheckEquals(EmptyStr, ErrorString); CheckTrue(Total > 0); CheckEquals(1, Orders[0].Keys.Count); CheckEquals('order_id', Orders[0].Keys.ToArray[0]); CheckTrue(Orders[0].TryGetValue('order_id', Value)); CheckNotEquals(EmptyStr, Value); CheckEquals('order_id', Orders[1].Keys.ToArray[0]); CheckTrue(Orders[0].TryGetValue('order_id', Value)); CheckNotEquals(EmptyStr, Value); finally FreeAndNil(Orders); end; Fields := ['order_id', 'member_id']; Orders := FRoute4MeManager.Order.GetOrdersWithCustomFields( Fields, Limit, Offset, Total, ErrorString); try CheckNotNull(Orders); CheckEquals(2, Orders.Count); CheckTrue(Total > 0); CheckEquals(EmptyStr, ErrorString); CheckEquals(2, Orders[0].Keys.Count); CheckEquals('order_id', Orders[0].Keys.ToArray[1]); CheckEquals('member_id', Orders[0].Keys.ToArray[0]); CheckTrue(Orders[0].TryGetValue('order_id', Value)); CheckNotEquals(EmptyStr, Value); CheckTrue(Orders[0].TryGetValue('member_id', Value)); CheckNotEquals(EmptyStr, Value); CheckEquals('order_id', Orders[1].Keys.ToArray[1]); CheckEquals('member_id', Orders[1].Keys.ToArray[0]); CheckTrue(Orders[1].TryGetValue('order_id', Value)); CheckNotEquals(EmptyStr, Value); CheckTrue(Orders[1].TryGetValue('member_id', Value)); CheckNotEquals(EmptyStr, Value); finally FreeAndNil(Orders); end; Fields := ['randomField', 'order_id', 'randomField1']; IsException := False; try Orders := FRoute4MeManager.Order.GetOrdersWithCustomFields( Fields, Limit, Offset, Total, ErrorString); except IsException := True; end; CheckTrue(IsException); end; procedure TTestOrderSamples.GetOrdersWithSpecifiedText; var ErrorString: String; Text: String; Orders: TOrderList; Offset, Limit, Total: integer; Order: TOrder; begin Text := 'Some Unique Text S34Ds2'; Limit := 5; Offset := 0; Orders := FRoute4MeManager.Order.GetOrdersWithSpecifiedText( Text, Limit, Offset, Total, ErrorString); try CheckNotNull(Orders); CheckEquals(0, Orders.Count); CheckEquals(EmptyStr, ErrorString); CheckEquals(0, Total); finally FreeAndNil(Orders); end; Order := FRoute4MeManager.Order.Get(FOrderId, ErrorString); try CheckEquals(EmptyStr, ErrorString); // By full LastName Text := Order.LastName; Limit := 5; Offset := 0; Orders := FRoute4MeManager.Order.GetOrdersWithSpecifiedText( Text, Limit, Offset, Total, ErrorString); try CheckNotNull(Orders); CheckEquals(1, Orders.Count); CheckEquals(EmptyStr, ErrorString); CheckEquals(1, Total); finally FreeAndNil(Orders); end; // The part of FirstName Text := Copy(Order.FirstName, 2, Length(Order.FirstName) - 2); Limit := 5; Offset := 0; Orders := FRoute4MeManager.Order.GetOrdersWithSpecifiedText( Text, Limit, Offset, Total, ErrorString); try CheckNotNull(Orders); CheckEquals(1, Orders.Count); CheckEquals(EmptyStr, ErrorString); CheckEquals(1, Total); finally FreeAndNil(Orders); end; // Text with spaces Text := Order.Address1; Limit := 5; Offset := 0; Orders := FRoute4MeManager.Order.GetOrdersWithSpecifiedText( Text, Limit, Offset, Total, ErrorString); try CheckNotNull(Orders); CheckEquals(1, Orders.Count); CheckEquals(EmptyStr, ErrorString); CheckEquals(1, Total); finally FreeAndNil(Orders); end; finally FreeAndNil(Order); end; end; function TTestOrderSamples.GetTestOrder: TOrder; var Rnd: String; begin Randomize; Rnd := IntToStr(Random(100000)); Result := TOrder.Create; Result.Address1 := 'Test Address2' + Rnd; Result.AddressAlias := 'Test AddressAlias' + Rnd; Result.FirstName := 'Jefferson' + Rnd; Result.LastName := 'Cruse' + Rnd; Result.CachedLatitude := 37.773972; Result.CachedLongitude := -122.431297; end; procedure TTestOrderSamples.RemoveOrder; var ErrorString: String; begin // Deleting existing order. Must be success. CheckTrue(FRoute4MeManager.Order.Remove([FOrderId], ErrorString)); CheckEquals(EmptyStr, ErrorString); // Deleting unexisting order. Must be success. CheckTrue(FRoute4MeManager.Order.Remove([-1], ErrorString)); CheckEquals(EmptyStr, ErrorString); end; procedure TTestOrderSamples.ScheduleOrder; var ErrorString: String; begin // Set invalid date. Must be error. FRoute4MeManager.Order.ScheduleOrder(FOrderId, IncDay(Now, -10000), ErrorString); CheckNotEquals(EmptyStr, ErrorString); // Set correct date. Must be success. FRoute4MeManager.Order.ScheduleOrder(FOrderId, Tomorrow, ErrorString); CheckEquals(EmptyStr, ErrorString); end; procedure TTestOrderSamples.UpdateOrder; var Order: TOrder; UpdatedOrder: TOrder; ErrorString: String; begin Order := GetTestOrder(); try Order.Id := FOrderId; Order.FirstName := 'Mary'; // Correct updating order. Must be success. UpdatedOrder := FRoute4MeManager.Order.Update(Order, ErrorString); try CheckNotNull(UpdatedOrder); CheckEquals(EmptyStr, ErrorString); CheckEquals('Mary', UpdatedOrder.FirstName); CheckTrue(FOrderId.IsNotNull); finally FreeAndNil(UpdatedOrder); end; // Invalid OrderId. Must be error. Order.Id := -1; UpdatedOrder := FRoute4MeManager.Order.Update(Order, ErrorString); try CheckNull(UpdatedOrder); CheckNotEquals(EmptyStr, ErrorString); finally FreeAndNil(UpdatedOrder); end; finally FreeAndNil(Order); end; end; initialization RegisterTest('Examples\Online\Orders\', TTestOrderSamples.Suite); end.
{ * CGDisplayConfiguration.h * CoreGraphics * * Copyright (c) 2002 Apple Computer, Inc. All rights reserved. * } { Pascal Translation: Peter N Lewis, <peter@stairways.com.au>, August 2005 } { Modified for use with Free Pascal Version 210 Please report any bugs to <gpc@microbizz.nl> } {$mode macpas} {$packenum 1} {$macro on} {$inline on} {$calling mwpascal} unit CGDisplayConfiguration; interface {$setc UNIVERSAL_INTERFACES_VERSION := $0342} {$setc GAP_INTERFACES_VERSION := $0210} {$ifc not defined USE_CFSTR_CONSTANT_MACROS} {$setc USE_CFSTR_CONSTANT_MACROS := TRUE} {$endc} {$ifc defined CPUPOWERPC and defined CPUI386} {$error Conflicting initial definitions for CPUPOWERPC and CPUI386} {$endc} {$ifc defined FPC_BIG_ENDIAN and defined FPC_LITTLE_ENDIAN} {$error Conflicting initial definitions for FPC_BIG_ENDIAN and FPC_LITTLE_ENDIAN} {$endc} {$ifc not defined __ppc__ and defined CPUPOWERPC} {$setc __ppc__ := 1} {$elsec} {$setc __ppc__ := 0} {$endc} {$ifc not defined __i386__ and defined CPUI386} {$setc __i386__ := 1} {$elsec} {$setc __i386__ := 0} {$endc} {$ifc defined __ppc__ and __ppc__ and defined __i386__ and __i386__} {$error Conflicting definitions for __ppc__ and __i386__} {$endc} {$ifc defined __ppc__ and __ppc__} {$setc TARGET_CPU_PPC := TRUE} {$setc TARGET_CPU_X86 := FALSE} {$elifc defined __i386__ and __i386__} {$setc TARGET_CPU_PPC := FALSE} {$setc TARGET_CPU_X86 := TRUE} {$elsec} {$error Neither __ppc__ nor __i386__ is defined.} {$endc} {$setc TARGET_CPU_PPC_64 := FALSE} {$ifc defined FPC_BIG_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := TRUE} {$setc TARGET_RT_LITTLE_ENDIAN := FALSE} {$elifc defined FPC_LITTLE_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := FALSE} {$setc TARGET_RT_LITTLE_ENDIAN := TRUE} {$elsec} {$error Neither FPC_BIG_ENDIAN nor FPC_LITTLE_ENDIAN are defined.} {$endc} {$setc ACCESSOR_CALLS_ARE_FUNCTIONS := TRUE} {$setc CALL_NOT_IN_CARBON := FALSE} {$setc OLDROUTINENAMES := FALSE} {$setc OPAQUE_TOOLBOX_STRUCTS := TRUE} {$setc OPAQUE_UPP_TYPES := TRUE} {$setc OTCARBONAPPLICATION := TRUE} {$setc OTKERNEL := FALSE} {$setc PM_USE_SESSION_APIS := TRUE} {$setc TARGET_API_MAC_CARBON := TRUE} {$setc TARGET_API_MAC_OS8 := FALSE} {$setc TARGET_API_MAC_OSX := TRUE} {$setc TARGET_CARBON := TRUE} {$setc TARGET_CPU_68K := FALSE} {$setc TARGET_CPU_MIPS := FALSE} {$setc TARGET_CPU_SPARC := FALSE} {$setc TARGET_OS_MAC := TRUE} {$setc TARGET_OS_UNIX := FALSE} {$setc TARGET_OS_WIN32 := FALSE} {$setc TARGET_RT_MAC_68881 := FALSE} {$setc TARGET_RT_MAC_CFM := FALSE} {$setc TARGET_RT_MAC_MACHO := TRUE} {$setc TYPED_FUNCTION_POINTERS := TRUE} {$setc TYPE_BOOL := FALSE} {$setc TYPE_EXTENDED := FALSE} {$setc TYPE_LONGLONG := TRUE} uses MacTypes,CGBase,CGDirectDisplay,CGErrors,CFDictionary,CGGeometry; {$ALIGN POWER} { * Display reconfiguration process. * Call CGBeginDisplayConfiguration to start. * Make all desired changes, for all displays. * Commit the changes using CGPerformDisplayConfiguration(), or cancel with * CGCancelDisplayConfiguration() * * The resulting layout will be adjusted so as to remove gaps or overlaps from * the requested layout, if needed. } type CGDisplayConfigRef = ^SInt32; { an opaque 32-bit type } { Get a new CGDisplayConfigRef } function CGBeginDisplayConfiguration( var pConfigRef: CGDisplayConfigRef ): CGError; external name '_CGBeginDisplayConfiguration'; { * Set the origin point for a display * * Note that setting the origin of a display which is mirroring * another display will remove that display from any mirroring set. * * Any display whose origin is not explicitly set in a reconfiguration * will be repositioned to a location as close as possible to it's * current location without overlapping or leaving a gap between displays. * * The actual position a display is placed at will be as close as possible * to the requested location without overlapping or leaving a gap between * displays. } function CGConfigureDisplayOrigin( configRef: CGDisplayConfigRef; display: CGDirectDisplayID; x: CGDisplayCoord; y: CGDisplayCoord ): CGError; external name '_CGConfigureDisplayOrigin'; { * Set the display mode * * The mode dictionary passed in must be a dictionary vended by other CGDirectDisplay * APIs such as CGDisplayBestModeForParameters() and CGDisplayAvailableModes(). * * When changing display modes of displays in a mirroring set, other displays in * the mirroring set whose mode is not explicitly changed will be set to a display * mode capable of mirroring the bounds of the largest display being explicitly set. } function CGConfigureDisplayMode( configRef: CGDisplayConfigRef; display: CGDirectDisplayID; mode: CFDictionaryRef ): CGError; external name '_CGConfigureDisplayMode'; { * Make a display a mirror of masterDisplay. * * Use a CGDirectDisplayID of kCGNullDirectDisplay for the masterDisplay to disable * mirroring. * Use a CGDirectDisplayID of CGMainDisplayID() for the masterDisplay to mirror * the main display. * * Mirroring requests will be filled with hardware mirroring when possible, * at the device driver's choice. Displays will be matted as appropriate, * using either hardware or software matte generation, again at the device driver's choice. * * Note that when hardware mirroring is in effect, the device driver may bind the hardware * accelerator, drawing engine, and 3D engine to any one of the displays in the hardware * mirroring set. That display will become the active display for drawing purposes in that * hardware mirroring set. Use CGDisplayPrimaryDisplay() to determine the correct display * device to process drawing operations in a hardware mirroring set. * * An app that uses CGGetActiveDisplayList() to determine the proper displays to draw to * (All Carbon and Cocoa apps using windows and/or DrawSprocket fall into this class) * will automatically get the correct behavior. } function CGConfigureDisplayMirrorOfDisplay( configRef: CGDisplayConfigRef; display: CGDirectDisplayID; masterDisplay: CGDirectDisplayID ): CGError; external name '_CGConfigureDisplayMirrorOfDisplay'; { Cancel a reconfiguration operation, discarding the configRef } function CGCancelDisplayConfiguration( configRef: CGDisplayConfigRef ): CGError; external name '_CGCancelDisplayConfiguration'; { * Perform the requested reconfigurations and discard the configRef * * A configuration change can apply for the life of an app, the life of a login session, or * permanently. If a request is made to make a change permanent, and the change * cannot be supported by the Aqua UI (resolution and pixel depth constraints apply), * then the configuration change is demoted to lasting the session. * * A permanent configuration change also becomes the current session's * configuration. * * When the system reverts confgurations at app termination, the * configuration always reverts to the session or permanent configuration setting. * * When the system reverts confgurations at session termination, the * configuration always reverts to the permanent configuration setting. * * This operation may fail if: * An unsupported display mode is requested * Another app is running in full-screen mode * } const kCGConfigureForAppOnly = 0; kCGConfigureForSession = 1; kCGConfigurePermanently = 2; type CGConfigureOption = UInt32; function CGCompleteDisplayConfiguration( configRef: CGDisplayConfigRef; option: CGConfigureOption ): CGError; external name '_CGCompleteDisplayConfiguration'; { Restore the permanent display configuration from the user's display preferences settings } procedure CGRestorePermanentDisplayConfiguration; external name '_CGRestorePermanentDisplayConfiguration'; { * Applications may want to register for notifications of display changes. * * Display changes are reported via a callback mechanism. * * Callbacks are invoked when the app is listening for events, * on the event processing thread, or from within the display * reconfiguration function when in the program that is driving the * reconfiguration. * * Callbacks should avoid attempting to change display configurations, * and should not raise exceptions or perform a non-local return such as * calling longjmp(). * * Before display reconfiguration, a callback fires to inform * applications of a pending configuration change. The callback runs * once for each on-line display. The flags passed in are set to * kCGDisplayBeginConfigurationFlag. This callback does not * carry other per-display information, as details of how a * reconfiguration affects a particular device rely on device-specific * behaviors which may not be exposed by a device driver. * * After display reconfiguration, at the time the callback function * is invoked, all display state reported by CoreGraphics, QuickDraw, * and the Carbon Display Manager API will be up to date. This callback * runs after the Carbon Display Manager notification callbacks. * The callback runs once for each added, removed, and currently * on-line display. Note that in the case of removed displays, calls into * the CoreGraphics API with the removed display ID will fail. } const kCGDisplayBeginConfigurationFlag = 1 shl 0; { Set in pre-reconfiguration callback } kCGDisplayMovedFlag = 1 shl 1; { post-reconfiguration callback flag } kCGDisplaySetMainFlag = 1 shl 2; { post-reconfiguration callback flag } kCGDisplaySetModeFlag = 1 shl 3; { post-reconfiguration callback flag } kCGDisplayAddFlag = 1 shl 4; { post-reconfiguration callback flag } kCGDisplayRemoveFlag = 1 shl 5; { post-reconfiguration callback flag } kCGDisplayEnabledFlag = 1 shl 8; { post-reconfiguration callback flag } kCGDisplayDisabledFlag = 1 shl 9; { post-reconfiguration callback flag } kCGDisplayMirrorFlag = 1 shl 10;{ post-reconfiguration callback flag } kCGDisplayUnMirrorFlag = 1 shl 11; { post-reconfiguration callback flag } type CGDisplayChangeSummaryFlags = UInt32; type CGDisplayReconfigurationCallBack = procedure( display: CGDirectDisplayID; flags: CGDisplayChangeSummaryFlags; userInfo: UnivPtr ); { * Register and remove a display reconfiguration callback procedure * The userInfo argument is passed back to the callback procedure each time * it is invoked. } function CGDisplayRegisterReconfigurationCallback( proc: CGDisplayReconfigurationCallBack; userInfo: UnivPtr ): CGError; external name '_CGDisplayRegisterReconfigurationCallback'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) function CGDisplayRemoveReconfigurationCallback( proc: CGDisplayReconfigurationCallBack; userInfo: UnivPtr ): CGError; external name '_CGDisplayRemoveReconfigurationCallback'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * These APIs allow applications and higher level frameworks * such as DrawSprocket to determine interesting properties * of displays, such as if a display is built-in, if a display * is the main display, if a display is being mirrored, which * display in a hardware mirror set is bound to the graphics * accelerator (important for games!) and so on. * * An app that uses CGGetActiveDisplayList() to determine the * proper displays to draw to (All Carbon and Cocoa apps using * windows and/or DrawSprocket fall into this class) will * automatically get the correct behavior without using these APIs. * These APIs are primarily of interest to specialized applications * such as movie players, integrated TV/video graphics utilities, * and similar specialized applications. } { True if the display is connected, awake, and drawable } function CGDisplayIsActive( display: CGDirectDisplayID ): boolean_t; external name '_CGDisplayIsActive'; { True if the display is asleep and therefore not drawable } function CGDisplayIsAsleep( display: CGDirectDisplayID ): boolean_t; external name '_CGDisplayIsAsleep'; { * True if the display is valid, with a monitor connected * (support for hot plugging of monitors) } function CGDisplayIsOnline( display: CGDirectDisplayID ): boolean_t; external name '_CGDisplayIsOnline'; { True if the display is the current main display } function CGDisplayIsMain( display: CGDirectDisplayID ): boolean_t; external name '_CGDisplayIsMain'; { True if the display is built in, such as the internal display in portables } function CGDisplayIsBuiltin( display: CGDirectDisplayID ): boolean_t; external name '_CGDisplayIsBuiltin'; { True if the display is in a mirroring set } function CGDisplayIsInMirrorSet( display: CGDirectDisplayID ): boolean_t; external name '_CGDisplayIsInMirrorSet'; { True if the display is always in a mirroring set, and cannot be unmirrored } function CGDisplayIsAlwaysInMirrorSet( display: CGDirectDisplayID ): boolean_t; external name '_CGDisplayIsAlwaysInMirrorSet'; { True if the display is in a hardware mirroring set } function CGDisplayIsInHWMirrorSet( display: CGDirectDisplayID ): boolean_t; external name '_CGDisplayIsInHWMirrorSet'; { Returns display being mirrored, or kCGNullDirectDisplay if master or unmirrored } function CGDisplayMirrorsDisplay( display: CGDirectDisplayID ): CGDirectDisplayID; external name '_CGDisplayMirrorsDisplay'; { True if the display is using OpenGL acceleration } function CGDisplayUsesOpenGLAcceleration( display: CGDirectDisplayID ): boolean_t; external name '_CGDisplayUsesOpenGLAcceleration'; { * Returns the display bound to the hardware accelerator in a HW mirror set, * or 'display' if software mirrored or unmirrored } function CGDisplayPrimaryDisplay( display: CGDirectDisplayID ): CGDirectDisplayID; external name '_CGDisplayPrimaryDisplay'; { * Returns the logical unit, vendor ID, vendor model number, * and serial number for a display } function CGDisplayUnitNumber( display: CGDirectDisplayID ): UInt32; external name '_CGDisplayUnitNumber'; function CGDisplayVendorNumber( display: CGDirectDisplayID ): UInt32; external name '_CGDisplayVendorNumber'; function CGDisplayModelNumber( display: CGDirectDisplayID ): UInt32; external name '_CGDisplayModelNumber'; function CGDisplaySerialNumber( display: CGDirectDisplayID ): UInt32; external name '_CGDisplaySerialNumber'; { Returns the IOKit service port for a display device } // uncomment when IOKit translated function CGDisplayIOServicePort( display: CGDirectDisplayID ): io_service_t; { * Returns the size of the specified display in millimeters. * * If 'display' is not a valid display ID, the size returned has a width and height of 0. * * If EDID data for the display device is not available, the size is estimated based on * the device width and height in pixels from CGDisplayBounds(), with an assumed resolution * of 2.835 pixels/mm, or 72 DPI, a reasonable guess for displays predating EDID support. } function CGDisplayScreenSize( display: CGDirectDisplayID ): CGSize; external name '_CGDisplayScreenSize'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) end.
unit UThreadGetNewBlockChainFromClient; interface uses UThread; type { TThreadGetNewBlockChainFromClient } TThreadGetNewBlockChainFromClient = Class(TPCThread) protected procedure BCExecute; override; public Constructor Create; End; implementation uses Classes, UOperationBlock, UNetConnection, UNetData, UPascalCoinBank, SysUtils, UPascalCoinSafeBox; { TThreadGetNewBlockChainFromClient } procedure TThreadGetNewBlockChainFromClient.BCExecute; Var i,j : Integer; maxWork : UInt64; candidates : TList; lop : TOperationBlock; nc : TNetConnection; begin // Search better candidates: candidates := TList.Create; try lop := CT_OperationBlock_NUL; PascalNetData.MaxRemoteOperationBlock := CT_OperationBlock_NUL; // First round: Find by most work maxWork := 0; j := PascalNetData.ConnectionsCountAll; nc := Nil; for i := 0 to j - 1 do begin if PascalNetData.GetConnection(i,nc) then begin if (nc.RemoteAccumulatedWork>maxWork) And (nc.RemoteAccumulatedWork>PascalCoinSafeBox.WorkSum) then begin maxWork := nc.RemoteAccumulatedWork; end; // Preventing downloading if nc.IsDownloadingBlocks then exit; end; end; if (maxWork>0) then begin for i := 0 to j - 1 do begin If PascalNetData.GetConnection(i,nc) then begin if (nc.RemoteAccumulatedWork>=maxWork) then begin candidates.Add(nc); lop := nc.RemoteOperationBlock; end; end; end; end; // Second round: Find by most height if candidates.Count=0 then begin for i := 0 to j - 1 do begin if (PascalNetData.GetConnection(i,nc)) then begin if (nc.RemoteOperationBlock.block>=PascalCoinSafeBox.BlocksCount) And (nc.RemoteOperationBlock.block>=lop.block) then begin lop := nc.RemoteOperationBlock; end; end; end; if (lop.block>0) then begin for i := 0 to j - 1 do begin If (PascalNetData.GetConnection(i,nc)) then begin if (nc.RemoteOperationBlock.block>=lop.block) then begin candidates.Add(nc); end; end; end; end; end; PascalNetData.MaxRemoteOperationBlock := lop; if (candidates.Count>0) then begin // Random a candidate i := 0; if (candidates.Count>1) then i := Random(candidates.Count); // i = 0..count-1 nc := TNetConnection(candidates[i]); PascalNetData.GetNewBlockChainFromClient(nc,Format('Candidate block: %d sum: %d',[nc.RemoteOperationBlock.block,nc.RemoteAccumulatedWork])); end; finally candidates.Free; end; end; constructor TThreadGetNewBlockChainFromClient.Create; begin Inherited Create(True); FreeOnTerminate := true; Suspended := false; end; end.
program FindeNaechstePrimzahl (input, output); { Bestimmt die zur Eingabezahl naechstgelegen(n) Primzahl(en) } type tNatZahlPlus = 1..maxint; var EinZahl, d : tNatZahlPlus; gefunden : boolean; function istPrimzahl (p : tNatZahlPlus) : boolean; { liefert true, falls p Primzahl ist, sonst false } var q : tNatZahlPlus; begin if p < 2 then istPrimzahl := false else { p >= 2 } begin istPrimzahl := true; for q := 2 to p - 1 do if p mod q = 0 then istPrimzahl := false end; end; { istPrimzahl } begin writeln ('Zahl eingeben: '); readln(EinZahl); write ('Naechste Primzahl zu ', EinZahl, ' ist '); if istPrimzahl (EinZahl) then writeln (EinZahl) else if EinZahl = 1 then writeln ('2':5) else { EinZahl <> 1 } begin gefunden := false; if odd (EinZahl) then d := 2 else d := 1; repeat if istPrimzahl (EinZahl + d) then begin { Primzahl oberhalb von EinZahl gefunden } gefunden := true; write (EinZahl + d : 5) end; if istPrimzahl (EinZahl - d) then begin { Primzahl unterhalb von EinZahl gefunden } gefunden := true; write (EinZahl - d : 5) end; d := d + 2 until gefunden; writeln; end { EinZahl <> 1 } end. { FindeNaechstePrimzahl }
program TM1638_display_LED; {$mode objfpc}{$H+} { Raspberry Pi Application } { Add your program code below, add additional units to the "uses" section if } { required and create new units by selecting File, New Unit from the menu. } { } { To compile your program select Run, Compile (or Run, Build) from the menu. } uses RaspberryPi, GlobalConfig, GlobalConst, GlobalTypes, Platform, Threads, SysUtils, Classes, Ultibo, Console, TM1638; var TM1630Ac: TTM1630; Handle: TWindowHandle; procedure Setup(); begin {Let's create a console window again but this time on the left side of the screen} Handle := ConsoleWindowCreate(ConsoleDeviceGetDefault, CONSOLE_POSITION_FULL, True); {To prove that worked let's output some text on the console window} ConsoleWindowWriteLn(Handle, 'TM1638 Display LED'); try TM1630Ac := TTM1630.Create; except on E: Exception do begin TM1630Ac := nil; ConsoleWindowWriteLn(Handle, 'Setup() error: ' + E.Message); end; end; end; procedure Loop(); begin try TM1630Ac.SendCommand($44); // set single address TM1630Ac.Start(); TM1630Ac.ShiftOut(soLsbFirst, $c0); // 1st digit TM1630Ac.ShiftOut(soLsbFirst, $ff); TM1630Ac.Stop(); TM1630Ac.Start(); TM1630Ac.ShiftOut(soLsbFirst, $c5); // 3rd LED TM1630Ac.ShiftOut(soLsbFirst, $01); TM1630Ac.Stop(); TM1630Ac.Start(); TM1630Ac.ShiftOut(soLsbFirst, $cb); // 6th LED TM1630Ac.ShiftOut(soLsbFirst, $01); TM1630Ac.Stop(); TM1630Ac.Start(); TM1630Ac.ShiftOut(soLsbFirst, $ce); // last digit TM1630Ac.ShiftOut(soLsbFirst, $ff); TM1630Ac.Stop(); except on E: Exception do begin TM1630Ac.Free; TM1630Ac := nil; ConsoleWindowWriteLn(Handle, 'Loop() error: ' + E.Message); end; end; end; begin Setup(); while Assigned(TM1630Ac) do Loop(); ConsoleWindowWriteLn(Handle, ''); ConsoleWindowWriteLn(Handle, 'Bye'); {Halt the main thread if we ever get to here} ThreadHalt(0); end.
unit ConsGastos; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Cons07, JvBaseDlg, JvProgressDialog, JvBalloonHint, Provider, DB, DBClient, StdActns, DBActns, ActnList, Menus, ImgList, JvAppStorage, JvAppIniStorage, JvComponentBase, JvFormPlacement, JvExStdCtrls, JvEdit, JvDBSearchEdit, StdCtrls, Buttons, JvCombobox, Mask, JvExMask, JvToolEdit, JvMaskEdit, JvDBFindEdit, ComCtrls, ToolWin, JvDBGridFooter, Grids, DBGrids, JvExDBGrids, JvDBGrid, ExtCtrls, wwSpeedButton, wwDBNavigator, wwclearpanel, Wwlocate, wwfltdlg, wwidlg, wwDialog, wwrcdvw; type TFConsGastos = class(TFCons07) CdsCodigo: TWideStringField; CdsOrden: TIntegerField; CdsDENOMINA: TWideStringField; CdsCuenta: TWideStringField; CdsGrupo: TWideStringField; CdsNomCta: TWideStringField; CdsNomGru: TWideStringField; CdsSALDO: TFloatField; CdsTOTAL: TAggregateField; acResultados: TAction; ToolButton9: TToolButton; ToolButton10: TToolButton; procedure FormCreate(Sender: TObject); procedure PieGrillaDisplayText(Sender: TJvDBGridFooter; Column: TFooterColumn; const Value: Variant; var Text: string); procedure acResultadosExecute(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } public { Public declarations } procedure procesar( fecha, hasta: TDateTime ); end; var FConsGastos: TFConsGastos; implementation uses Informes, dmIng, FuncsRB; {$R *.dfm} procedure TFConsGastos.acResultadosExecute(Sender: TObject); begin inherited; cds.IndexFieldNames := 'Orden;Codigo;Grupo;Cuenta'; SetCadenaRb( 'Del ' + DateToStr( fini ) + ' al ' + DateToStr( ffin )); TDMIng.TDatos.Open; VerInforme( 'EstadoResultados.rtm', cds, cds ); end; procedure TFConsGastos.FormClose(Sender: TObject; var Action: TCloseAction); begin cds.Close; inherited; end; procedure TFConsGastos.FormCreate(Sender: TObject); begin NoAbrir := True; inherited; end; procedure TFConsGastos.PieGrillaDisplayText(Sender: TJvDBGridFooter; Column: TFooterColumn; const Value: Variant; var Text: string); begin inherited; if Column.FieldName = 'SALDO' then Text := CdsTOTAL.DisplayText else if Column.FieldName = 'NomCta' then Text := 'TOTAL RESULTADOS BRUTOS'; end; procedure TFConsGastos.procesar(fecha, hasta: TDateTime); var i: Integer; begin Cds.ProviderName := ''; with TDMIng do try FIni := fecha; FFin := hasta; cds.DisableControls; Cds.CreateDataSet; BalCons.parameters.paramByName( 'FECINI' ).value := fecha; BalCons.parameters.paramByName( 'FECFIN' ).value := hasta; BalCons.Open; while not BalCons.eof do begin cds.Append; for I := 0 to BalCons.fields.Count - 1 do cds.fields[i].value := BalCons.fields[i].value; cds.post; BalCons.next; end; BalCons.close; BalConsB.parameters.paramByName( 'FECINI' ).value := fecha; BalConsB.parameters.paramByName( 'FECFIN' ).value := hasta; BalConsB.Open; while not BalConsB.eof do begin if not (Cds.Locate( 'Cuenta', BalConsBCuenta.value, [loCaseInsensitive])) then begin cds.Append; for I := 0 to BalConsB.fields.Count - 1 do cds.fields[i].value := BalConsB.fields[i].value; end else begin cds.Edit; CdsSALDO.Value := CdsSALDO.Value + BalConsBSALDO.value; end; BalConsB.next; end; BalConsB.close; finally cds.enablecontrols; end; end; end.
unit K447393371; {* [Requestlink:447393371] } // Модуль: "w:\archi\source\projects\Archi\Tests\K447393371.pas" // Стереотип: "TestCase" // Элемент модели: "K447393371" MUID: (5162771D0104) // Имя типа: "TK447393371" {$Include w:\archi\source\projects\Archi\arDefine.inc} interface {$If Defined(nsTest) AND Defined(InsiderTest)} uses l3IntfUses {$If NOT Defined(NoScripts)} , ArchiInsiderTest {$IfEnd} // NOT Defined(NoScripts) ; type TK447393371 = class({$If NOT Defined(NoScripts)} TArchiInsiderTest {$IfEnd} // NOT Defined(NoScripts) ) {* [Requestlink:447393371] } protected function GetFolder: AnsiString; override; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } end;//TK447393371 {$IfEnd} // Defined(nsTest) AND Defined(InsiderTest) implementation {$If Defined(nsTest) AND Defined(InsiderTest)} uses l3ImplUses , TestFrameWork //#UC START# *5162771D0104impl_uses* //#UC END# *5162771D0104impl_uses* ; {$If NOT Defined(NoScripts)} function TK447393371.GetFolder: AnsiString; {* Папка в которую входит тест } begin Result := 'MacrosTest'; end;//TK447393371.GetFolder function TK447393371.GetModelElementGUID: AnsiString; {* Идентификатор элемента модели, который описывает тест } begin Result := '5162771D0104'; end;//TK447393371.GetModelElementGUID initialization TestFramework.RegisterTest(TK447393371.Suite); {$IfEnd} // NOT Defined(NoScripts) {$IfEnd} // Defined(nsTest) AND Defined(InsiderTest) end.
unit uAppconsts; {$mode objfpc}{$H+} interface const vAppName = 'wikihelp'; vRevision = 2; vVersion = 0.5; vProgramname = 'WikiHelp'; vTimeOutYear = 0; vTimeOutMonth = 0; vTimeOutDay = 0; vCopyright = '2007 Christian Ulrich'; vTracker_url = 'mantis.ullihome.de'; vProject_id = 5; implementation end.
unit ServerHorse.Controller.Interfaces; interface uses ServerHorse.Model.DAO, ServerHorse.Model.Entity.USERS, ServerHorse.Model.Entity.CUSTOMERS, ServerHorse.Model.Entity.OCCUPATION, ServerHorse.Model.Entity.COUNTRIES, ServerHorse.Model.Entity.STATES, ServerHorse.Model.Entity.CITIES, ServerHorse.Model.Entity.COMPANIES, ServerHorse.Model.Entity.AREASEXPERTISE, ServerHorse.Model.Entity.BANKACCOUNTS, ServerHorse.Model.Entity.TYPESBANKACCOUNTS; type iControllerEntity<T : class> = interface; iController = interface ['{6A60E341-CB38-4034-B924-FB9B49D98577}'] function AREASEXPERTISE : iControllerEntity<TAREASEXPERTISE>; function BANKACCOUNTS : iControllerEntity<TBANKACCOUNTS>; function CITIES : iControllerEntity<TCITIES>; function COMPANIES : iControllerEntity<TCOMPANIES>; function COUNTRIES : iControllerEntity<TCOUNTRIES>; function CUSTOMERS : iControllerEntity<TCUSTOMERS>; function OCCUPATION : iControllerEntity<TOCCUPATION>; function STATES : iControllerEntity<TSTATES>; function TYPESBANKACCOUNTS : iControllerEntity<TTYPESBANKACCOUNTS>; function USERS : iControllerEntity<TUSERS>; end; iControllerEntity<T : class> = interface ['{F7476B60-A9B9-48CA-B1B6-016DADEA41D6}'] function This : iDAOGeneric<T>; function &End : iController; end; implementation end.
{ Mark Sattolo, 428500, CSI-1100A, prof: Dr. S. Boyd tutorial group DGD-1, TA: Chris Lankester Assignment 4, Question 1 } program ConvertTime (input,output); { This program converts a positive integer giving the time in seconds to three integers representing Hours, Minutes, and Seconds. } { Data Dictionary GIVENS: Time_in_seconds - a positive integer representing the time in seconds. RESULTS: Hours, Minutes, Seconds - 3 integers representing their named time periods. INTERMEDIATES: Min_Sec - the remainder of the input after splitting out Hours. } var Time_in_seconds, Hours, Min_Sec, Minutes, Seconds: integer; begin writeln; writeln('***************************************************'); writeln('Mark Sattolo, 428500, CSI-1100A, prof: Dr. S. Boyd'); writeln('tutorial group DGD-1, TA: Chris Lankester'); writeln('Assignment 4, Question 1'); writeln('***************************************************'); writeln; { Prompt the user for the input. } write('Please enter the positive integer Time_in_seconds? '); readln(Time_in_seconds); { The div function is used to get the integer for Hours and the mod function is used to get the remainder representing minutes and seconds. } Hours := (Time_in_seconds div 60) div 60; Min_Sec := Time_in_seconds mod 3600; { div and mod are then used to separate Minutes and Seconds. } Minutes := (Time_in_seconds div 60) mod 60; Seconds := Time_in_seconds mod 60; { Write out the result. } writeln; writeln('The number of hours is ',Hours); writeln('The number of minutes is ',Minutes); writeln('The number of seconds is ',Seconds) end.
unit Plan.DBTools; interface uses System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys,FireDAC.Phys.SQLite, FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs, FireDAC.Stan.Param, FireDAC.FMXUI.Wait, Data.DB, FireDAC.Comp.Client, Generics.Collections; type TRecordState = (Nothing, New, Deleted, Updated); TDomain = record id: integer; name: string; active: boolean; num: integer; FRecState: TRecordState; constructor Create(RecState: TRecordState); procedure SetRecState(Value: TRecordState); property recstate: TRecordState read FRecState write SetRecState; end; TDomainList = TList<TDomain>; TPeriod = record id: integer; name: string; active: boolean; FRecState: TRecordState; constructor Create(RecState: TRecordState); procedure SetRecState(Value: TRecordState); property recstate: TRecordState read FRecState write SetRecState; end; TPeriodList = TList<TPeriod>; TPlanDB = class(TObject) const dbName: string = 'plan.sdb'; private { Private declarations } FDConn: TFDConnection; query: TFDQuery; public { Public declarations } constructor Create; destructor Destroy; override; function loadDomains(): TDomainList; function loadPeriods(): TPeriodList; procedure saveDomains(domains: TDomainList); procedure savePeriods(periods: TPeriodList); end; var db: TPlanDB; implementation uses FireDAC.DApt; //uses FireDAC.ConsoleUI.Wait, FireDAC.Stan.Def, FireDAC.DApt, FireDAC.Stan.Async, // FireDAC.Phys.Oracle, FireDAC.Phys.MSSQL, FireDAC.Stan.Consts; constructor TDomain.Create(RecState: TRecordState); begin id := 0; name := ''; active := true; num := 0; FRecState := RecState; end; procedure TDomain.SetRecState(Value: TRecordState); begin if FRecState <> TRecordState.New then begin FRecState := Value; end; end; constructor TPeriod.Create(RecState: TRecordState); begin id := 0; name := ''; active := true; FRecState := RecState; end; procedure TPeriod.SetRecState(Value: TRecordState); begin if FRecState <> TRecordState.New then begin FRecState := Value; end; end; constructor TPlanDB.Create; var periodsCnt: integer; begin inherited Create; FDConn := TFDConnection.Create(nil); FDConn.DriverName := 'SQLite'; FDConn.Params.Database := dbName; FDConn.Open; // if not FDConn.Connected then // raise Exception.Create('Could not connect to database.'); query := TFDQuery.Create(nil); query.Connection := FDConn; // query.Params.BindMode := pByNumber; query.ExecSQL('CREATE TABLE IF NOT EXISTS domains ( ' + 'id INTEGER PRIMARY KEY ASC AUTOINCREMENT, ' + 'name VARCHAR(128) NOT NULL UNIQUE, ' + 'active BOOLEAN NOT NULL CHECK (active = 0 or active = 1) DEFAULT 1, ' + 'num INT NOT NULL ' + ')' ); query.ExecSQL('CREATE TABLE IF NOT EXISTS periods ( ' + 'id INTEGER PRIMARY KEY ASC, ' + 'name VARCHAR(128) NOT NULL UNIQUE, ' + 'active BOOLEAN NOT NULL CHECK (active = 0 or active = 1) DEFAULT 1 ' + ')' ); query.ExecSQL('CREATE TABLE IF NOT EXISTS period_dates ( ' + 'id INTEGER PRIMARY KEY ASC AUTOINCREMENT, ' + 'period INTEGER NOT NULL REFERENCES periods (id), ' + 'alive BOOLEAN NOT NULL CHECK (alive = 0 or alive = 1) DEFAULT 1, ' + 'start_date DATETIME NOT NULL ' + ')' ); query.ExecSQL('CREATE TABLE IF NOT EXISTS doings ( ' + 'id INTEGER PRIMARY KEY ASC AUTOINCREMENT, ' + 'domain INTEGER NOT NULL REFERENCES domains (id), ' + 'period INTEGER NOT NULL REFERENCES period_dates (id), ' + 'num INTEGER NULL DEFAULT NULL, ' + 'do_date DATETIME NULL DEFAULT NULL, ' + 'state INTEGER NOT NULL DEFAULT 0, ' + 'alive BOOLEAN NOT NULL CHECK (alive = 0 or alive = 1) DEFAULT 1, ' + 'notification INTEGER NULL DEFAULT NULL, ' + 'link INTEGER NULL DEFAULT NULL REFERENCES doings (id), ' + 'parent INTEGER NULL DEFAULT NULL REFERENCES doings (id) ' + ')' ); periodsCnt := 0; try query.SQL.Text := 'SELECT count(1) cnt FROM periods'; query.Open(); periodsCnt := query.FieldByName('cnt').AsInteger; except query.Close; query.SQL.Clear; raise; end; query.Close; query.SQL.Clear; if periodsCnt = 0 then begin query.ExecSQL('INSERT INTO periods(id, name) values (:id, :name)', [1, 'After life']); query.ExecSQL('INSERT INTO periods(id, name) values (:id, :name)', [2, 'Life']); query.ExecSQL('INSERT INTO periods(id, name) values (:id, :name)', [3, '5 years']); query.ExecSQL('INSERT INTO periods(id, name) values (:id, :name)', [4, 'Year']); query.ExecSQL('INSERT INTO periods(id, name) values (:id, :name)', [5, 'Half-year']); query.ExecSQL('INSERT INTO periods(id, name) values (:id, :name)', [6, 'Quarter']); query.ExecSQL('INSERT INTO periods(id, name) values (:id, :name)', [7, 'Month']); query.ExecSQL('INSERT INTO periods(id, name) values (:id, :name)', [8, 'Week']); query.ExecSQL('INSERT INTO periods(id, name) values (:id, :name)', [9, 'Day']); end; end; destructor TPlanDB.Destroy; begin query.Free; FDConn.Close; FDConn.Free; inherited Destroy; end; function TPlanDB.loadDomains(): TDomainList; var domain: TDomain; begin try query.SQL.Text := 'SELECT id, name, active, num FROM domains WHERE active = 1 ORDER BY num ASC'; query.Open(); result := TDomainList.Create; while not query.Eof do begin domain := TDomain.Create(TRecordState.Nothing); domain.id := query.FieldByName('id').AsInteger; domain.name := query.FieldByName('name').AsString; domain.num := query.FieldByName('num').AsInteger; domain.active := query.FieldByName('active').AsBoolean; result.Add(domain); query.Next; end; except query.Close; query.SQL.Clear; raise; end; query.Close; query.SQL.Clear; end; function TPlanDB.loadPeriods(): TPeriodList; var period: TPeriod; begin try query.SQL.Text := 'SELECT id, name, active FROM periods ORDER BY id ASC'; query.Open(); result := TPeriodList.Create; while not query.Eof do begin period := TPeriod.Create(TRecordState.Nothing); period.id := query.FieldByName('id').AsInteger; period.name := query.FieldByName('name').AsString; period.active := query.FieldByName('active').AsBoolean; result.Add(period); query.Next; end; except query.Close; query.SQL.Clear; raise; end; query.Close; query.SQL.Clear; end; procedure TPlanDB.saveDomains(domains: TDomainList); var domain: TDomain; i, k: integer; begin FDConn.StartTransaction; try k := domains.Count - 1; for i := 0 to k do begin domain := domains[i]; case domain.recstate of TRecordState.Nothing: continue; TRecordState.New: begin query.SQL.Text := 'INSERT INTO domains (name, num) VALUES (:name, :num)'; query.ParamByName('name').AsString := domain.name; query.ParamByName('num').AsInteger := domain.num; query.Execute; query.Params.Clear; query.SQL.Clear; end; TRecordState.Deleted: begin query.SQL.Text := 'UPDATE domains SET active = 0 WHERE id = :id'; query.ParamByName('id').AsInteger := domain.id; query.Execute; query.Params.Clear; query.SQL.Clear; end; TRecordState.Updated: begin query.SQL.Text := 'UPDATE domains SET name = :name, num = :num WHERE id = :id'; query.ParamByName('name').AsString := domain.name; query.ParamByName('num').AsInteger := domain.num; query.ParamByName('id').AsInteger := domain.id; query.Execute; query.Params.Clear; query.SQL.Clear; end; end; end; FDConn.Commit; except FDConn.Rollback; raise; end; end; procedure TPlanDB.savePeriods(periods: TPeriodList); var period: TPeriod; i, k: integer; begin FDConn.StartTransaction; try k := periods.Count - 1; for i := 0 to k do begin period := periods[i]; case period.recstate of TRecordState.Nothing: continue; TRecordState.New: continue; TRecordState.Deleted: continue; TRecordState.Updated: begin query.SQL.Text := 'UPDATE periods SET active = :active WHERE id = :id'; query.ParamByName('active').AsBoolean := period.active; query.ParamByName('id').AsInteger := period.id; query.Execute; query.Params.Clear; query.SQL.Clear; end; end; end; FDConn.Commit; except FDConn.Rollback; raise; end; end; end.
{ Subroutine SST_DTYPE_NEW_STRING (STR_LEN,DTYPE_P) * * Create a new data type descriptor for a string. Strings are really * arrays of characters. } module sst_DTYPE_NEW_STRING; define sst_dtype_new_string; %include 'sst2.ins.pas'; procedure sst_dtype_new_string ( {create new dtype descriptor for a string} in str_len: string_index_t; {length of string} out dtype_p: sst_dtype_p_t); {pointer to new data type descriptor} begin sst_mem_alloc_scope (sizeof(dtype_p^), dtype_p); {alloc new data type descriptor} { * Fill in fixed fields. } dtype_p^.symbol_p := nil; dtype_p^.dtype := sst_dtype_array_k; dtype_p^.bits_min := sst_config.bits_char * str_len; dtype_p^.align_nat := sst_dtype_char_p^.align_nat; dtype_p^.align := sst_dtype_char_p^.align; sst_dtype_size (dtype_p^); {set SIZE_USED and SIZE_ALIGN fields} { * Fill in fields specific to this data type. } dtype_p^.ar_dtype_ele_p := sst_dtype_char_p; dtype_p^.ar_dtype_rem_p := nil; sst_exp_const_int (1, dtype_p^.ar_ind_first_p); sst_exp_const_int (str_len, dtype_p^.ar_ind_last_p); dtype_p^.ar_ind_n := str_len; dtype_p^.ar_n_subscr := 1; dtype_p^.ar_string := true; end;