text
stringlengths
14
6.51M
unit FrmAnalysisMap; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, ComCtrls, U_POWER_ANALYSIS, U_WIRING_ERROR, U_POWER_LIST_INFO, U_WE_PHASE_MAP, U_WE_EQUATION, StdCtrls, U_DIAGRAM_TYPE, FrmErrorInfo; type TfAnalysisMap = class(TForm) tbcntrl1: TTabControl; stsbrMain: TStatusBar; imgMap: TImage; btn1: TButton; pnl1: TPanel; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure tbcntrl1Change(Sender: TObject); procedure btn1Click(Sender: TObject); private { Private declarations } FPhaseDraw : TWE_PHASE_MAP; FEquation : TWE_EQUATION; FPowerAnalysis : TPowerAnalysis; FErrorList : TStringList; FError : TWIRING_ERROR; public { Public declarations } /// <summary> /// 接线图类型 /// </summary> ADiagramType : TDiagramType; /// <summary> /// 显示功率信息 /// </summary> procedure ShowPowerInfo(APower: TFourPower; dAngle : Double); overload; procedure ShowPowerInfo(APower: TThreePower; dAngle : Double); overload; procedure ShowPowerInfoAT(APower: TObject; dAngle : Double); end; //var // fAnalysisMap: TfAnalysisMap; implementation {$R *.dfm} procedure TfAnalysisMap.btn1Click(Sender: TObject); var AErrorInfo : TfErrorInfo; AThreePower : TThreePower; AFourPower : TFourPower; begin if tbcntrl1.Tabs.Count > 0 then begin AErrorInfo := TfErrorInfo.Create(nil); AErrorInfo.ADiagramType := ADiagramType; if FErrorList.Objects[tbcntrl1.TabIndex] is TThreePower then begin AThreePower := TThreePower(FErrorList.Objects[tbcntrl1.TabIndex]); AErrorInfo.LoadEquation( FError, AThreePower.Angle ); end else begin AFourPower := TFourPower(FErrorList.Objects[tbcntrl1.TabIndex]); AErrorInfo.LoadEquation( FError, AFourPower.Angle ); end; AErrorInfo.ShowModal; AErrorInfo.Free; end; end; procedure TfAnalysisMap.FormCreate(Sender: TObject); begin FPowerAnalysis := TPowerAnalysis.Create; FErrorList := TStringList.Create; FError := TWIRING_ERROR.Create; FPhaseDraw := TWE_PHASE_MAP.Create( nil ); FEquation := TWE_EQUATION.Create; end; procedure TfAnalysisMap.FormDestroy(Sender: TObject); begin FPowerAnalysis.Free; FErrorList.Free; FError.Free; FPhaseDraw.Free; FEquation.Free; end; procedure TfAnalysisMap.ShowPowerInfo(APower: TFourPower; dAngle : Double); begin if not Assigned(APower) then Exit; FPowerAnalysis.AnalysisPower(APower, FErrorList, dAngle); tbcntrl1.Tabs.Text := FErrorList.Text; if tbcntrl1.Tabs.Count > 0 then tbcntrl1Change(nil); end; procedure TfAnalysisMap.ShowPowerInfo(APower: TThreePower; dAngle : Double); begin if not Assigned(APower) then Exit; FPowerAnalysis.AnalysisPower(APower, FErrorList, dAngle); tbcntrl1.Tabs.Text := FErrorList.Text; if tbcntrl1.Tabs.Count > 0 then tbcntrl1Change(nil); end; procedure TfAnalysisMap.ShowPowerInfoAT(APower: TObject; dAngle: Double); begin if Assigned(APower) then begin if APower is TThreePower then ShowPowerInfo(TThreePower(APower), dAngle) else if APower is TFourPower then ShowPowerInfo(TFourPower(APower), dAngle); end; end; procedure TfAnalysisMap.tbcntrl1Change(Sender: TObject); var nErrorID : Integer; AThreePower : TThreePower; AFourPower : TFourPower; begin if FErrorList.Objects[tbcntrl1.TabIndex] is TThreePower then begin AThreePower := TThreePower(FErrorList.Objects[tbcntrl1.TabIndex]); TryStrToInt('$' + AThreePower.Errorcode, nErrorID); FError.ID := nErrorID; stsbrMain.Panels.Items[0].Text := '错误个数:' + IntToStr(AThreePower.Errorcount); stsbrMain.Panels.Items[1].Text := 'φ角:' + FloatToStr(AThreePower.Angle); stsbrMain.Panels.Items[2].Text := FError.Description; FEquation.GenerateEquations( FError, AThreePower.Angle ); FPhaseDraw.Canvas := imgMap.Canvas; FPhaseDraw.Rect := Rect( 2, 2, 2 + 230, 2 + 180); FPhaseDraw.DrawPhaseMap( FEquation, '' ); end else begin AFourPower := TFourPower(FErrorList.Objects[tbcntrl1.TabIndex]); TryStrToInt('$' + AFourPower.Errorcode, nErrorID); FError.ID := nErrorID; stsbrMain.Panels.Items[0].Text := '错误个数:' + IntToStr(AFourPower.Errorcount); stsbrMain.Panels.Items[1].Text := 'φ角:' + FloatToStr(AFourPower.Angle); stsbrMain.Panels.Items[2].Text := FError.Description; FEquation.GenerateEquations( FError, AFourPower.Angle ); FPhaseDraw.Canvas := imgMap.Canvas; FPhaseDraw.Rect := Rect( 2, 2, 2 + 230, 2 + 180); FPhaseDraw.DrawPhaseMap( FEquation, '' ); end; end; end.
unit uFIFO_map; interface uses windows, sysutils, math, uMAP_File, uFIFO_async, uFIFO_rec, uMutex; type tFIFO_map=class(tFIFO_async) private data : pointer; map_data : tMapFile; map_fifo : tMapFile; mode_writer : boolean; function open(as_server : boolean; as_writer : boolean) : boolean; function get_mode_writer:boolean; function get_created : boolean; protected mutex_read : tMutex; mutex_write : tMutex; shadow_fifo : pFIFO_rec; procedure read_begin;override; procedure read_end;override; procedure write_begin;override; procedure write_end;override; public constructor create(name:string; v_size:integer; log:tMapFileLog=nil); destructor destroy;override; function create_reader : boolean; function create_writer : boolean; function open_as_reader : boolean; function open_as_writer : boolean; procedure close; procedure update; procedure shadow_enable; property is_writer : boolean read get_mode_writer; property is_created : boolean read get_created; end; implementation constructor tFIFO_map.create(name:string; v_size:integer; log:tMapFileLog); begin inherited create(v_size); map_data := tMapFile.create(name+'_'+inttostr(fixed_size)+'_data', fixed_size, log); map_fifo := tMapFile.create(name+'_'+inttostr(fixed_size)+'_fifo', sizeof(fifo^), log); mutex_read := tMutex.create(name+'_'+inttostr(fixed_size)+'_read', log); mutex_write := tMutex.create(name+'_'+inttostr(fixed_size)+'_write', log); delete_objects; end; destructor tFIFO_map.destroy; begin if self = nil then exit; map_data.close; map_fifo.close; map_data.Free; map_fifo.Free; map_data := nil; map_fifo := nil; if shadow_fifo <> nil then Dispose(fifo); fifo := nil; data := nil; end; function tFIFO_map.open(as_server : boolean; as_writer : boolean) : boolean; var res_wr : boolean; res_rd : boolean; res_fifo : boolean; res_data : boolean; begin result := false; if self = nil then exit; res_rd := mutex_read.open(as_server); res_wr := mutex_write.open(as_server); res_fifo := map_fifo.open(as_server, true); res_data := map_data.open(as_server, as_writer); if not (res_fifo and res_data and res_wr and res_rd) then begin mutex_read.close; mutex_write.close; map_fifo.close; map_data.close; exit; end; fifo := map_fifo.data; data := map_data.data; fifo_data_ptr := data; if map_fifo.is_created then _FIFO_rec_init(fifo^, map_data.size, fixed_size); string_read := ''; string_next := true; mode_writer := as_writer; result := true; end; function tFIFO_map.create_writer : boolean; begin result := open(true, true); end; function tFIFO_map.create_reader : boolean; begin result := open(true, false); end; function tFIFO_map.open_as_writer : boolean; begin result := open(false, true); end; function tFIFO_map.open_as_reader : boolean; begin result := open(false, false); end; procedure tFIFO_map.close; begin if self = nil then exit; map_data.close; map_fifo.close; mutex_read.close; mutex_write.close; fifo_data_ptr := nil; fifo := nil; data := nil; end; function tFIFO_map.get_mode_writer:boolean; begin result := false; if self = nil then exit; result := mode_writer; end; procedure tFIFO_map.read_begin; begin if self = nil then exit; mutex_read.Lock; end; procedure tFIFO_map.read_end; begin if self = nil then exit; mutex_read.UnLock; end; procedure tFIFO_map.write_begin; begin if self = nil then exit; mutex_write.Lock; end; procedure tFIFO_map.write_end; begin if self = nil then exit; mutex_write.UnLock; end; function tFIFO_map.get_created : boolean; begin result := false; if self = nil then exit; if map_data = nil then exit; if map_fifo = nil then exit; result := map_fifo.is_created or map_data.is_created; end; procedure tFIFO_map.update; begin if shadow_fifo = nil then exit; fifo.wr := shadow_fifo^.wr; fifo.stat_writed := shadow_fifo^.stat_writed; fifo.errors_writed := shadow_fifo^.errors_writed; fifo.stat := shadow_fifo^.stat; end; procedure tFIFO_map.shadow_enable; begin shadow_fifo := fifo; fifo := nil; New(fifo); Move(shadow_fifo^, fifo^, sizeof(fifo^)); end; end.
{ +------------------------------------------------------------------------- } { Microsoft Windows } { Copyright (C) Microsoft Corporation. All Rights Reserved. } { File: exdispid.h } { -------------------------------------------------------------------------- } unit ExDispID; interface { Dispatch IDS for IExplorer Dispatch Events. } const DISPID_BEFORENAVIGATE = 100; { this is sent before navigation to give a chance to abort } DISPID_NAVIGATECOMPLETE = 101; { in async, this is sent when we have enough to show } DISPID_STATUSTEXTCHANGE = 102; DISPID_QUIT = 103; DISPID_DOWNLOADCOMPLETE = 104; DISPID_COMMANDSTATECHANGE = 105; DISPID_DOWNLOADBEGIN = 106; DISPID_NEWWINDOW = 107; { sent when a new window should be created } DISPID_PROGRESSCHANGE = 108; { sent when download progress is updated } DISPID_WINDOWMOVE = 109; { sent when main window has been moved } DISPID_WINDOWRESIZE = 110; { sent when main window has been sized } DISPID_WINDOWACTIVATE = 111; { sent when main window has been activated } DISPID_PROPERTYCHANGE = 112; { sent when the PutProperty method is called } DISPID_TITLECHANGE = 113; { sent when the document title changes } DISPID_TITLEICONCHANGE = 114; { sent when the top level window icon may have changed. } DISPID_FRAMEBEFORENAVIGATE = 200; DISPID_FRAMENAVIGATECOMPLETE = 201; DISPID_FRAMENEWWINDOW = 204; DISPID_BEFORENAVIGATE2 = 250; { hyperlink clicked on } DISPID_NEWWINDOW2 = 251 ; DISPID_NAVIGATECOMPLETE2 = 252; { UIActivate new document } DISPID_ONQUIT = 253 ; DISPID_ONVISIBLE = 254; { sent when the window goes visible/hidden } DISPID_ONTOOLBAR = 255; { sent when the toolbar should be shown/hidden } DISPID_ONMENUBAR = 256; { sent when the menubar should be shown/hidden } DISPID_ONSTATUSBAR = 257; { sent when the statusbar should be shown/hidden } DISPID_ONFULLSCREEN = 258; { sent when kiosk mode should be on/off } DISPID_DOCUMENTCOMPLETE = 259; { new document goes ReadyState_Complete } DISPID_ONTHEATERMODE = 260; { sent when theater mode should be on/off } DISPID_ONADDRESSBAR = 261; { sent when the address bar should be shown/hidden } DISPID_WINDOWSETRESIZABLE = 262; { sent to set the style of the host window frame } DISPID_WINDOWCLOSING = 263; { sent before script window.close closes the window } DISPID_WINDOWSETLEFT = 264; { sent when the put_left method is called on the WebOC } DISPID_WINDOWSETTOP = 265; { sent when the put_top method is called on the WebOC } DISPID_WINDOWSETWIDTH = 266; { sent when the put_width method is called on the WebOC } DISPID_WINDOWSETHEIGHT = 267; { sent when the put_height method is called on the WebOC } DISPID_CLIENTTOHOSTWINDOW = 268; { sent during window.open to request conversion of dimensions } DISPID_SETSECURELOCKICON = 269; { sent to suggest the appropriate security icon to show } DISPID_FILEDOWNLOAD = 270; { Fired to indicate the File Download dialog is opening } DISPID_NAVIGATEERROR = 271; { Fired to indicate the a binding error has occured } DISPID_PRIVACYIMPACTEDSTATECHANGE = 272; { Fired when the user's browsing experience is impacted } DISPID_NEWWINDOW3 = 273; DISPID_VIEWUPDATE = 281; { Fired when the contents of a shell browser window change } DISPID_SETPHISHINGFILTERSTATUS = 282; { Fired by the Phishing Filter API to signal what state the analysis is in } DISPID_WINDOWSTATECHANGED = 283; { Fired to indicate that the browser window's visibility or enabled state has changed } DISPID_NEWPROCESS = 284; { Fired when a navigation must be redirected due to Protected Mode } DISPID_THIRDPARTYURLBLOCKED = 285; { Fired when a third-party url is blocked due to Privacy Advisor } DISPID_REDIRECTXDOMAINBLOCKED = 286; { Fired when a x-domain redirect is blocked due to browser nav constant } DISPID_WEBWORKERSTARTED = 288; DISPID_WEBWORKERFINISHED = 289; DISPID_BEFORESCRIPTEXECUTE = 290; { Fired prior to any of a page's script is executed } { Printing events } DISPID_PRINTTEMPLATEINSTANTIATION = 225; { Fired to indicate that a print template is instantiated } DISPID_PRINTTEMPLATETEARDOWN = 226; { Fired to indicate that a print templete is completely gone } DISPID_UPDATEPAGESTATUS = 227; { Fired to indicate that the spooling status has changed } { define the events for the shell window list } DISPID_WINDOWREGISTERED = 200; { Window registered } DISPID_WINDOWREVOKED = 201; { Window Revoked } DISPID_RESETFIRSTBOOTMODE = 1; DISPID_RESETSAFEMODE = 2; DISPID_REFRESHOFFLINEDESKTOP = 3; DISPID_ADDFAVORITE = 4; DISPID_ADDCHANNEL = 5; DISPID_ADDDESKTOPCOMPONENT = 6; DISPID_ISSUBSCRIBED = 7; DISPID_NAVIGATEANDFIND = 8; DISPID_IMPORTEXPORTFAVORITES = 9; DISPID_AUTOCOMPLETESAVEFORM = 10; DISPID_AUTOSCAN = 11; DISPID_AUTOCOMPLETEATTACH = 12; DISPID_SHOWBROWSERUI = 13; DISPID_ADDSEARCHPROVIDER = 14; DISPID_RUNONCESHOWN = 15; DISPID_SKIPRUNONCE = 16; DISPID_CUSTOMIZESETTINGS = 17; DISPID_SQMENABLED = 18; DISPID_PHISHINGENABLED = 19; DISPID_BRANDIMAGEURI = 20; DISPID_SKIPTABSWELCOME = 21; DISPID_DIAGNOSECONNECTION = 22; DISPID_CUSTOMIZECLEARTYPE = 23; DISPID_ISSEARCHPROVIDERINSTALLED = 24; DISPID_ISSEARCHMIGRATED = 25; DISPID_DEFAULTSEARCHPROVIDER = 26; DISPID_RUNONCEREQUIREDSETTINGSCOMPLETE = 27; DISPID_RUNONCEHASSHOWN = 28; DISPID_SEARCHGUIDEURL = 29; DISPID_ADDSERVICE = 30; DISPID_ISSERVICEINSTALLED = 31; DISPID_ADDTOFAVORITESBAR = 32; DISPID_BUILDNEWTABPAGE = 33; DISPID_SETRECENTLYCLOSEDVISIBLE = 34; DISPID_SETACTIVITIESVISIBLE = 35; DISPID_CONTENTDISCOVERYRESET = 36; DISPID_INPRIVATEFILTERINGENABLED = 37; DISPID_SUGGESTEDSITESENABLED = 38; DISPID_ENABLESUGGESTEDSITES = 39; DISPID_NAVIGATETOSUGGESTEDSITES = 40; DISPID_SHOWTABSHELP = 41; DISPID_SHOWINPRIVATEHELP = 42; DISPID_ISSITEMODE = 43; DISPID_SETSITEMODEICONOVERLAY = 44; DISPID_CLEARSITEMODEICONOVERLAY = 45; DISPID_UPDATETHUMBNAILBUTTON = 46; DISPID_SETTHUMBNAILBUTTONS = 47; DISPID_ADDTHUMBNAILBUTTONS = 48; DISPID_ADDSITEMODE = 49; DISPID_SETSITEMODEPROPERTIES = 50; DISPID_SITEMODECREATEJUMPLIST = 51; DISPID_SITEMODEADDJUMPLISTITEM = 52; DISPID_SITEMODECLEARJUMPLIST = 53; DISPID_SITEMODEADDBUTTONSTYLE = 54; DISPID_SITEMODESHOWBUTTONSTYLE = 55; DISPID_SITEMODESHOWJUMPLIST = 56; DISPID_ADDTRACKINGPROTECTIONLIST = 57; DISPID_SITEMODEACTIVATE = 58; DISPID_ISSITEMODEFIRSTRUN = 59; DISPID_TRACKINGPROTECTIONENABLED = 60; DISPID_ACTIVEXFILTERINGENABLED = 61; DISPID_PROVISIONNETWORKS = 62; DISPID_REPORTSAFEURL = 63; DISPID_SITEMODEREFRESHBADGE = 64; DISPID_SITEMODECLEARBADGE = 65; DISPID_DIAGNOSECONNECTIONUILESS = 66; DISPID_LAUNCHNETWORKCLIENTHELP = 67; DISPID_CHANGEDEFAULTBROWSER = 68; DISPID_STOPPERIODICUPDATE = 69; DISPID_STARTPERIODICUPDATE = 70; DISPID_CLEARNOTIFICATION = 71; DISPID_ENABLENOTIFICATIONQUEUE = 72; DISPID_PINNEDSITESTATE = 73; DISPID_LAUNCHINTERNETOPTIONS = 74; DISPID_STARTPERIODICUPDATEBATCH = 75; DISPID_ENABLENOTIFICATIONQUEUESQUARE = 76; DISPID_ENABLENOTIFICATIONQUEUEWIDE = 77; DISPID_ENABLENOTIFICATIONQUEUELARGE = 78; DISPID_SCHEDULEDTILENOTIFICATION = 79; DISPID_REMOVESCHEDULEDTILENOTIFICATION = 80; DISPID_STARTBADGEUPDATE = 81; DISPID_STOPBADGEUPDATE = 82; DISPID_SHELLUIHELPERLAST = 83; DISPID_ADVANCEERROR = 10; DISPID_RETREATERROR = 11; DISPID_CANADVANCEERROR = 12; DISPID_CANRETREATERROR = 13; DISPID_GETERRORLINE = 14; DISPID_GETERRORCHAR = 15; DISPID_GETERRORCODE = 16; DISPID_GETERRORMSG = 17; DISPID_GETERRORURL = 18; DISPID_GETDETAILSSTATE = 19; DISPID_SETDETAILSSTATE = 20; DISPID_GETPERERRSTATE = 21; DISPID_SETPERERRSTATE = 22; DISPID_GETALWAYSSHOWLOCKSTATE = 23; { Dispatch IDS for ShellFavoritesNameSpace Dispatch Events. } DISPID_FAVSELECTIONCHANGE = 1; DISPID_SELECTIONCHANGE = 2; DISPID_DOUBLECLICK = 3; DISPID_INITIALIZED = 4; DISPID_MOVESELECTIONUP = 1; DISPID_MOVESELECTIONDOWN = 2; DISPID_RESETSORT = 3; DISPID_NEWFOLDER = 4; DISPID_SYNCHRONIZE = 5; DISPID_IMPORT = 6; DISPID_EXPORT = 7; DISPID_INVOKECONTEXTMENU = 8; DISPID_MOVESELECTIONTO = 9; DISPID_SUBSCRIPTIONSENABLED = 10; DISPID_CREATESUBSCRIPTION = 11; DISPID_DELETESUBSCRIPTION = 12; DISPID_SETROOT = 13; DISPID_ENUMOPTIONS = 14; DISPID_SELECTEDITEM = 15; DISPID_ROOT = 16; DISPID_DEPTH = 17; DISPID_MODE = 18; DISPID_FLAGS = 19; DISPID_TVFLAGS = 20; DISPID_NSCOLUMNS = 21; DISPID_COUNTVIEWTYPES = 22; DISPID_SETVIEWTYPE = 23; DISPID_SELECTEDITEMS = 24; DISPID_EXPAND = 25; DISPID_UNSELECTALL = 26; implementation end.
unit TestuConversao; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework, System.Generics.Defaults, Classes, uConversao, System.StrUtils; type // Test methods for class TConverteTexto TestTConverteTexto = class(TTestCase) strict private FConverteTexto: TConverteTexto; public procedure SetUp; override; procedure TearDown; override; published procedure TestAdicionarTexto; end; // Test methods for class TConverteInvertido TestTConverteInvertido = class(TTestCase) strict private FConverteInvertido: TConverteInvertido; public procedure SetUp; override; procedure TearDown; override; published procedure TestConverter; end; // Test methods for class TConvertePrimeiraMaiuscula TestTConvertePrimeiraMaiuscula = class(TTestCase) strict private FConvertePrimeiraMaiuscula: TConvertePrimeiraMaiuscula; public procedure SetUp; override; procedure TearDown; override; published procedure TestConverter; end; // Test methods for class TConverteOrdenado TestTConverteOrdenado = class(TTestCase) strict private FConverteOrdenado: TConverteOrdenado; public procedure SetUp; override; procedure TearDown; override; published procedure TestConverter; end; implementation uses System.SysUtils; procedure TestTConverteTexto.SetUp; begin FConverteTexto := TConverteTexto.Create; end; procedure TestTConverteTexto.TearDown; begin FConverteTexto := Nil; end; procedure TestTConverteTexto.TestAdicionarTexto; const a = 'Abc abc'; var Value: string; begin FConverteTexto.AdicionarTexto(a); CheckEquals(a, FConverteTexto.Texto, 'A propriedade não recebeu o valor correto'); end; procedure TestTConverteInvertido.SetUp; begin FConverteInvertido := TConverteInvertido.Create; end; procedure TestTConverteInvertido.TearDown; begin FConverteInvertido := nil; end; procedure TestTConverteInvertido.TestConverter; const a = 'abc abc'; const b = 'cba cba'; var ReturnValue: string; begin FConverteInvertido.Texto := a; ReturnValue := FConverteInvertido.Converter; CheckEquals(b, ReturnValue, 'O valor não foi invertido corretamente'); // TODO: Validate method results end; procedure TestTConvertePrimeiraMaiuscula.SetUp; begin FConvertePrimeiraMaiuscula := TConvertePrimeiraMaiuscula.Create; end; procedure TestTConvertePrimeiraMaiuscula.TearDown; begin FConvertePrimeiraMaiuscula.Free; FConvertePrimeiraMaiuscula := nil; end; procedure TestTConvertePrimeiraMaiuscula.TestConverter; const a = 'abc abc'; const b = 'Abc Abc'; var ReturnValue: string; begin FConvertePrimeiraMaiuscula.Texto := a; ReturnValue := FConvertePrimeiraMaiuscula.Converter; CheckEquals(b, ReturnValue, 'O valor não foi obteve o retorno esperado'); end; procedure TestTConverteOrdenado.SetUp; begin FConverteOrdenado := TConverteOrdenado.Create; end; procedure TestTConverteOrdenado.TearDown; begin FConverteOrdenado.Free; FConverteOrdenado := nil; end; procedure TestTConverteOrdenado.TestConverter; const a = 'abc abc'; const b = 'aabbcc'; var ReturnValue: string; begin FConverteOrdenado.Texto := a; ReturnValue := FConverteOrdenado.Converter; CheckEquals(b, ReturnValue, 'O valor não foi obteve o retorno esperado'); end; initialization // Register any test cases with the test runner RegisterTest(TestTConverteTexto.Suite); RegisterTest(TestTConverteInvertido.Suite); RegisterTest(TestTConvertePrimeiraMaiuscula.Suite); RegisterTest(TestTConverteOrdenado.Suite); end.
// All this is based on data from Alazane and the WolfPack team. // http://uo.stratics.com/heptazane/fileformats.shtml // Thanks to Cheffe for pointing out bugs and giving tips. // - Deepgreen unit uotiles; interface uses classes, sysutils, uoclidata; const EnableTerMur = True; type TStaidx = record //The record used in the staidx.mul files start:longword; //start determines the start offset of the 8x8block inside the statics.mul files len:longword; //length of the 8x8block inside the statics.mul files unknown:longword; end; TStatics = record //The record used in the statics.mul files, the statics are additional layers for one map tile TileType:word; //The index for the art.mul file x:byte; //The x-offset inside the block (from 0 to 7 ...) y:byte; //The y-offset inside the block (from 0 to 7 ...) z:shortint; //The altitude of the tile hue:word; //This is used to make some statics look different end; TMap = record TileType:word; //The index for the art.mul file z:shortint; //The altitude of the tile end; //The record and pointer on the record (bc of tlist) for the overrides PListRecord = ^TListRecord; TListRecord = record offset:longword; blocknumber:longword; end; TTTBasic = class private Cst : TCstDB; fmap_mul, fstaidx_mul, fstatics_mul:array[0..5] of TFileStream; //Basic files fmapdif_mul, fstadifi_mul, fstadif_mul:array[0..5] of TFileStream; //Override files (aka dif files) ftiledata_mul:TFileStream; fmapdifblocks, fstadifblocks:array[0..5] of TList; fusedifdata:boolean; function BlockOverride(var list:TList; blocknumber:longword; var posi:longword):boolean; function GetBlockNumber(x, y:word; facet:byte; var BlockNumber:longword) : boolean; public constructor init(p:AnsiString; usedif:boolean; CstDB : TCstDB); function GetLayerCount(x, y:word; facet:byte; var tilecnt:byte):boolean; function GetTileData(x, y:word; facet:byte; layer:byte; var TileType:word; var tilez:shortint; var TileName:AnsiString; var tileflags:longword):boolean; destructor destroy; override; end; implementation {----------------------------------------------------------------------------- Procedure : init Purpose : Create the Object Assign all the nessecary filestream Load the Difblockindex into a TList when usedif = true Arguments : p:AnsiString - The Path to the UO Directory usedif:boolean - if the override data from the dif files should be used Result : None -----------------------------------------------------------------------------} constructor TTTBasic.init(p:AnsiString; usedif:boolean; CstDB : TCstDB); //open the layer0 file (the basic map) procedure openmapfiles; begin fmap_mul[0] := TFileStream.Create(p + 'map0.mul', (fmOpenRead or fmShareDenyNone)); fmap_mul[1] := TFileStream.Create(p + 'map0.mul', (fmOpenRead or fmShareDenyNone)); if fileexists(p + 'map2.mul') then fmap_mul[2] := TFileStream.Create(p + 'map2.mul', (fmOpenRead or fmShareDenyNone)); if fileexists(p + 'map3.mul') then fmap_mul[3] := TFileStream.Create(p + 'map3.mul', (fmOpenRead or fmShareDenyNone)); if fileexists(p + 'map4.mul') then fmap_mul[4] := TFileStream.Create(p + 'map4.mul', (fmOpenRead or fmShareDenyNone)); if fileexists(p + 'map5.mul') then fmap_mul[5] := TFileStream.Create(p + 'map5.mul', (fmOpenRead or fmShareDenyNone)); end; //open the index files for the statics.mul file procedure openstaidxfiles; begin fstaidx_mul[0] := TFileStream.Create(p + 'staidx0.mul', (fmOpenRead or fmShareDenyNone)); fstaidx_mul[1] := TFileStream.Create(p + 'staidx0.mul', (fmOpenRead or fmShareDenyNone)); if fileexists(p + 'staidx2.mul') then fstaidx_mul[2] := TFileStream.Create(p + 'staidx2.mul', (fmOpenRead or fmShareDenyNone)); if fileexists(p + 'staidx3.mul') then fstaidx_mul[3] := TFileStream.Create(p + 'staidx3.mul', (fmOpenRead or fmShareDenyNone)); if fileexists(p + 'staidx4.mul') then fstaidx_mul[4] := TFileStream.Create(p + 'staidx4.mul', (fmOpenRead or fmShareDenyNone)); if fileexists(p + 'staidx5.mul') then fstaidx_mul[5] := TFileStream.Create(p + 'staidx5.mul', (fmOpenRead or fmShareDenyNone)); end; //open the statics files, here all the additional layers are stored procedure openstaticsfiles; begin fstatics_mul[0] := TFileStream.Create(p + 'statics0.mul', (fmOpenRead or fmShareDenyNone)); fstatics_mul[1] := TFileStream.Create(p + 'statics0.mul', (fmOpenRead or fmShareDenyNone)); if fileexists(p + 'statics2.mul') then fstatics_mul[2] := TFileStream.Create(p + 'statics2.mul', (fmOpenRead or fmShareDenyNone)); if fileexists(p + 'statics3.mul') then fstatics_mul[3] := TFileStream.Create(p + 'statics3.mul', (fmOpenRead or fmShareDenyNone)); if fileexists(p + 'statics4.mul') then fstatics_mul[4] := TFileStream.Create(p + 'statics4.mul', (fmOpenRead or fmShareDenyNone)); if fileexists(p + 'statics5.mul') then fstatics_mul[5] := TFileStream.Create(p + 'statics5.mul', (fmOpenRead or fmShareDenyNone)); end; //This is used to load the blocks that need to be overriden into an TList procedure LoadList(var list:TList; filename:AnsiString); function Find(value:longword; var Index: Longword): Boolean; var L, H, I, C: Integer; begin Result := False; L := 0; H := list.count - 1; while L <= H do begin I := (L + H) shr 1; C := PListRecord(list[I])^.blocknumber - 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; var tempmemstream:TMemoryStream; tempblock:longword; i, j:longword; h:PListRecord; begin tempmemstream := TMemoryStream.Create; tempmemstream.LoadFromFile(filename); tempmemstream.seek(0, sofrombeginning); list := TList.Create; list.Clear; for i := 0 to tempmemstream.Size div 4 - 1 do begin tempmemstream.Read(tempblock, 4); if find(tempblock, j) then PListRecord(list[j])^.offset := i else begin new(h); h^.offset := i; h^.blocknumber := tempblock; list.Insert(j, h); end; end; tempmemstream.Free; list.Capacity := list.Count; end; //the override files for the maplayer (layer0) //it contains all the 8x8 blocks to override procedure readmapdifblocks; begin LoadList(fmapdifblocks[0], p + 'mapdifl0.mul'); LoadList(fmapdifblocks[1], p + 'mapdifl1.mul'); if fileexists(p + 'mapdifl2.mul') then LoadList(fmapdifblocks[2], p + 'mapdifl2.mul'); if fileexists(p + 'mapdifl3.mul') then LoadList(fmapdifblocks[3], p + 'mapdifl3.mul'); if fileexists(p + 'mapdifl4.mul') then LoadList(fmapdifblocks[4], p + 'mapdifl4.mul'); if fileexists(p + 'mapdifl5.mul') then LoadList(fmapdifblocks[5], p + 'mapdifl5.mul'); end; //the override files for the statics (layer>0) //it contains all the 8x8 blocks to override procedure readstadifblocks; begin LoadList(fstadifblocks[0], p + 'stadifl0.mul'); LoadList(fstadifblocks[1], p + 'stadifl1.mul'); if fileexists(p + 'stadifl2.mul') then LoadList(fstadifblocks[2], p + 'stadifl2.mul'); if fileexists(p + 'stadifl3.mul') then LoadList(fstadifblocks[3], p + 'stadifl3.mul'); if fileexists(p + 'stadifl4.mul') then LoadList(fstadifblocks[4], p + 'stadifl4.mul'); if fileexists(p + 'stadifl5.mul') then LoadList(fstadifblocks[5], p + 'stadifl5.mul'); end; //equivalent to map.mul files, just the overrides for it procedure openmapdiffiles; begin fmapdif_mul[0] := TFileStream.Create(p + 'mapdif0.mul', (fmOpenRead or fmShareDenyNone)); fmapdif_mul[1] := TFileStream.Create(p + 'mapdif1.mul', (fmOpenRead or fmShareDenyNone)); if fileexists(p + 'mapdif2.mul') then fmapdif_mul[2] := TFileStream.Create(p + 'mapdif2.mul', (fmOpenRead or fmShareDenyNone)); if fileexists(p + 'mapdif3.mul') then fmapdif_mul[3] := TFileStream.Create(p + 'mapdif3.mul', (fmOpenRead or fmShareDenyNone)); if fileexists(p + 'mapdif4.mul') then fmapdif_mul[4] := TFileStream.Create(p + 'mapdif4.mul', (fmOpenRead or fmShareDenyNone)); if fileexists(p + 'mapdif5.mul') then fmapdif_mul[5] := TFileStream.Create(p + 'mapdif5.mul', (fmOpenRead or fmShareDenyNone)); end; //equivalent to staidx.mul, just the overrides for it procedure openstadififiles; begin fstadifi_mul[0] := TFileStream.Create(p + 'stadifi0.mul', (fmOpenRead or fmShareDenyNone)); fstadifi_mul[1] := TFileStream.Create(p + 'stadifi1.mul', (fmOpenRead or fmShareDenyNone)); if fileexists(p + 'stadifi2.mul') then fstadifi_mul[2] := TFileStream.Create(p + 'stadifi2.mul', (fmOpenRead or fmShareDenyNone)); if fileexists(p + 'stadifi3.mul') then fstadifi_mul[3] := TFileStream.Create(p + 'stadifi3.mul', (fmOpenRead or fmShareDenyNone)); if fileexists(p + 'stadifi4.mul') then fstadifi_mul[4] := TFileStream.Create(p + 'stadifi4.mul', (fmOpenRead or fmShareDenyNone)); if fileexists(p + 'stadifi5.mul') then fstadifi_mul[5] := TFileStream.Create(p + 'stadifi5.mul', (fmOpenRead or fmShareDenyNone)); end; //equivalent to statics.mul, just the overrides for it procedure openstadiffiles; begin fstadif_mul[0] := TFileStream.Create(p + 'stadif0.mul', (fmOpenRead or fmShareDenyNone)); fstadif_mul[1] := TFileStream.Create(p + 'stadif1.mul', (fmOpenRead or fmShareDenyNone)); if fileexists(p + 'stadif2.mul') then fstadif_mul[2] := TFileStream.Create(p + 'stadif2.mul', (fmOpenRead or fmShareDenyNone)); if fileexists(p + 'stadif3.mul') then fstadif_mul[3] := TFileStream.Create(p + 'stadif3.mul', (fmOpenRead or fmShareDenyNone)); if fileexists(p + 'stadif4.mul') then fstadif_mul[4] := TFileStream.Create(p + 'stadif4.mul', (fmOpenRead or fmShareDenyNone)); if fileexists(p + 'stadif5.mul') then fstadif_mul[5] := TFileStream.Create(p + 'stadif5.mul', (fmOpenRead or fmShareDenyNone)); end; begin inherited Create; Cst:=CstDB; if not (p[length(p)] = '\') then p := p + '\'; openmapfiles; openstaidxfiles; openstaticsfiles; ftiledata_mul := TFileStream.Create(p + 'tiledata.mul', (fmOpenRead or fmShareDenyNone)); fusedifdata := usedif; if fusedifdata then begin readmapdifblocks; openmapdiffiles; readstadifblocks; openstadififiles; openstadiffiles; end; end; {----------------------------------------------------------------------------- Procedure : BlockOverride Purpose : Scan for [blocknumber] in the Tlist to check for 8x8blocks to override Uses binary search method Arguments : list:TList - The list to scan blocknumber:longword - The blocknumber to search Result : posi:longword -> Position of the 8x8block in the dif files BlockOverride:boolean -> True if there is an override for the block -----------------------------------------------------------------------------} function TTTBasic.BlockOverride(var list:TList; blocknumber:longword; var posi:longword):boolean; var L, H, I, C: Integer; begin Result := False; if list = nil then exit; if (blocknumber > PListRecord(list.Last)^.blocknumber) or (blocknumber < PListRecord(list.First)^.blocknumber) then exit; if list = nil then Exit; L := 0; H := list.count - 1; while L <= H do begin I := (L + H) shr 1; C := PListRecord(list[I])^.blocknumber - blocknumber; if C < 0 then L := I + 1 else begin H := I - 1; if C = 0 then begin Result := True; L := I; end; end; end; posi := PListRecord(list[L])^.offset; end; {----------------------------------------------------------------------------- Procedure : GetBlockNumber Purpose : This function is used to get the identifier of the 8x8 block a tile is in. Also checks if a tile is out of maprange, so it wont create blocknumbers that lead to exceeding the file size. Arguments : x, y:word - The worldcoordinates of the tile facet:byte - The facet of the tile Result : BlockNumber:longword -> The Identifier of the 8x8Block GetBlockNumber:boolean -> Will be false in case of problems -----------------------------------------------------------------------------} function TTTBasic.GetBlockNumber(x, y:word; facet:byte; var BlockNumber:longword):boolean; begin result := false; case facet of 0, 1: if (x<6144) and (y<4096) then begin BlockNumber := ((X div 8) * 512) + (Y div 8); result := true; end; 2: if (x<2304) and (y<1600) then begin BlockNumber := ((X div 8) * 200) + (Y div 8); result := true; end; 3: if (x<2560) and (y<2048) then begin BlockNumber := ((X div 8) * 256) + (Y div 8); result := true; end; 4: if (x<1448) and (y<1448) then begin BlockNumber := ((X div 8) * 181) + (Y div 8); result := true; end; 5: if (x<1280) and (y<4096) and EnableTerMur then begin BlockNumber := ((X div 8) * 196) + (Y div 8); result := true; end; end; end; {----------------------------------------------------------------------------- Procedure : GetLayerCount Purpose : This function is used to count the layers on a single tile Arguments : x, y:word - The worldcoordinates of the tile facet:byte - The facet of the tile Result : LayerCount:byte -> The amount of layers to be found on the tile without the map layer (map layer = layer 0) GetLayerCount:boolean -> Will be false in case of problems -----------------------------------------------------------------------------} function TTTBasic.GetLayerCount(x, y:word; facet:byte; var tilecnt:byte):boolean; //The counting function, it counts the layers without knowing if working in an //override file or not function CountLayers(var file1, file2:TFileStream; var tilecnt:byte):boolean; var staidx:TStaidx; statics:TStatics; i:word; begin if (file1.Read(staidx, 12) = 12) and not (staidx.start = $FFFFFFFF) then begin file2.Seek(staidx.start, soFromBeginning); for i := 1 to (staidx.len div 7) do if file2.Read(statics, 7) = 7 then if (statics.x = x) and (statics.y = y) then inc(tilecnt); end; result := true; end; var blocknumber:longword; difpos:longword; begin result := false; tilecnt := 0; if GetBlockNumber(x, y, facet, BlockNumber) then begin x := x mod 8; y := y mod 8; if fusedifdata and BlockOverride(fstadifblocks[facet], BlockNumber, difpos) then begin fstadifi_mul[facet].Seek(difpos * 12, soFromBeginning); result := CountLayers(fstadifi_mul[facet], fstadif_mul[facet], tilecnt); end else begin fstaidx_mul[facet].Seek(BlockNumber * 12, soFromBeginning); result := CountLayers(fstaidx_mul[facet], fstatics_mul[facet], tilecnt); end; end; end; {----------------------------------------------------------------------------- Procedure : GetTileData Purpose : This function is used to get the altitude and type of a tile Arguments : x, y:word - The worldcoordinates of the tile facet:byte - The facet of the tile layer:byte - The layer of the tile Result : TileType:word -> The TileType of the tile z:shortint -> The Altitude of the tile GetTileData:boolean -> Will be False in case of problems -----------------------------------------------------------------------------} function TTTBasic.GetTileData(x, y:word; facet:byte; layer:byte; var TileType:word; var tilez:shortint; var TileName:AnsiString; var tileflags:longword):boolean; //The TileData is stored in the statics or stadif.mul (layer > 0) //Works as with diffiles as with the normal files function FromSta(var file1, file2:TFileStream; var tiletype:word; var tilez:shortint):boolean; var staidx:TStaidx; statics:TStatics; i:word; stopoffset:longword; begin result := false; if (file1.Read(staidx, 12) = 12) and not (staidx.start = $FFFFFFFF) then begin stopoffset := staidx.start + staidx.len; file2.Seek(staidx.start, soFromBeginning); for i := 1 to layer do repeat file2.Read(statics, 7); until ((statics.x = x) and (statics.y = y)) or (file2.Position > stopoffset); if (file2.Position <= stopoffset) then begin TileType := statics.TileType; tilez := statics.z; result := true; end; end; end; //Take the TileData out of the mapfile (layer=0) //Works as with diffiles as with the normal files function FromMap(var file1:TFileStream; var tiletype:word; var tilez:shortint):boolean; var map:TMap; begin file1.Read(map, 3); TileType := map.TileType; tilez := map.z; result := true; end; var blocknumber:longword; difpos:longword; temptilename:array[0..19] of AnsiChar; landdata_size : Cardinal; tiledata_size : Cardinal; begin landdata_size := 26 + 4*(Cst.FFLAGS and 1); tiledata_size := 37 + 4*(Cst.FFLAGS and 1); result := false; if GetBlockNumber(x, y, facet, blocknumber) then begin x := x mod 8; y := y mod 8; if layer > 0 then begin if fusedifdata and BlockOverride(fstadifblocks[facet], BlockNumber, difpos) then begin fstadifi_mul[facet].Seek(difpos * 12, soFromBeginning); result := fromsta(fstadifi_mul[facet], fstadif_mul[facet], tiletype, tilez); end else begin fstaidx_mul[facet].Seek(blocknumber * 12, soFromBeginning); result := fromsta(fstaidx_mul[facet], fstatics_mul[facet], tiletype, tilez); end; ftiledata_mul.Seek(512*(4+32*landdata_size) + 4 * (1 + TileType div 32) + TileType * tiledata_size, soFromBeginning); ftiledata_mul.Read(tileflags, 4); ftiledata_mul.Seek(tiledata_size-24,soFromCurrent); ftiledata_mul.Read(temptilename, 20); end else begin if fusedifdata and BlockOverride(fmapdifblocks[facet], BlockNumber, difpos) then begin fmapdif_mul[facet].Seek(4 + (difpos * 196) + (y * 24) + (x * 3), soFromBeginning); result := frommap(fmapdif_mul[facet], tiletype, tilez); end else begin fmap_mul[facet].Seek(4 + (blocknumber * 196) + (y * 24) + (x * 3), soFromBeginning); result := frommap(fmap_mul[facet], tiletype, tilez); end; ftiledata_mul.Seek(4 * (1 + TileType div 32) + (TileType * landdata_size), soFromBeginning); ftiledata_mul.Read(tileflags, 4); ftiledata_mul.Seek(landdata_size-24, soFromCurrent); ftiledata_mul.Read(temptilename, 20); end; tilename := trim(temptilename); end; end; //Before destroying free everything destructor TTTBasic.destroy; var i:byte; j:word; begin ftiledata_mul.free; for i := 0 to 5 do begin fmap_mul[i].free; fstaidx_mul[i].free; fstatics_mul[i].free; fmapdif_mul[i].free; fstadifi_mul[i].free; fstadif_mul[i].free; if fmapdifblocks[i] <> nil then begin for j := 0 to fmapdifblocks[i].Count - 1 do dispose(PListRecord(fmapdifblocks[i][j])); fmapdifblocks[i].free; end; if fstadifblocks[i] <> nil then begin for j := 0 to fstadifblocks[i].Count - 1 do dispose(PListRecord(fstadifblocks[i][j])); fstadifblocks[i].free; end; end; inherited destroy; end; end.
unit FmxInvalidateHack; interface uses Fmx.Types, Vcl.Controls; procedure InvalidateControl(aControl : TControl); implementation uses Contnrs; type TInvalidator = class private protected Timer : TTimer; List : TObjectList; procedure Step(Sender : TObject); public constructor Create; destructor Destroy; override; procedure AddToQueue(aControl : TControl); end; var GlobalInvalidator : TInvalidator; procedure InvalidateControl(aControl : TControl); begin if not assigned(GlobalInvalidator) then begin GlobalInvalidator := TInvalidator.Create; end; GlobalInvalidator.AddToQueue(aControl); end; { TInvalidator } constructor TInvalidator.Create; const FrameRate = 30; begin List := TObjectList.Create; List.OwnsObjects := false; Timer := TTimer.Create(nil); Timer.OnTimer := Step; Timer.Interval := round(1000 / FrameRate); Timer.Enabled := true; end; destructor TInvalidator.Destroy; begin Timer.Free; List.Free; inherited; end; procedure TInvalidator.AddToQueue(aControl: TControl); begin if List.IndexOf(aControl) = -1 then begin List.Add(aControl); end; end; procedure TInvalidator.Step(Sender: TObject); var c1: Integer; begin for c1 := 0 to List.Count-1 do begin (List[c1] as TControl).Repaint; end; List.Clear; end; initialization finalization if assigned(GlobalInvalidator) then GlobalInvalidator.Free; end.
(*!------------------------------------------------------------ * [[APP_NAME]] ([[APP_URL]]) * * @link [[APP_REPOSITORY_URL]] * @copyright Copyright (c) [[COPYRIGHT_YEAR]] [[COPYRIGHT_HOLDER]] * @license [[LICENSE_URL]] ([[LICENSE]]) *------------------------------------------------------------- *) unit HomeView; interface {$MODE OBJFPC} {$H+} uses fano; type (*!----------------------------------------------- * View instance * * @author [[AUTHOR_NAME]] <[[AUTHOR_EMAIL]]> *------------------------------------------------*) THomeView = class(TInjectableObject, IView) private fHtml : string; public constructor create(const html : string); (*!------------------------------------------------ * render view *------------------------------------------------ * @param viewParams view parameters * @param response response instance * @return response *-----------------------------------------------*) function render( const viewParams : IViewParameters; const response : IResponse ) : IResponse; end; implementation constructor THomeView.create(const html : string); begin fHtml := html; end; (*!------------------------------------------------ * render view *------------------------------------------------ * @param viewParams view parameters * @param response response instance * @return response *-----------------------------------------------*) function THomeView.render( const viewParams : IViewParameters; const response : IResponse ) : IResponse; begin response.body().write(fHtml); result := response; end; end.
unit https; interface uses MSXML2_TLB, sysutils, variants, typex, commandprocessor, classes, debug, IdSSLOpenSSL, systemx, IdSSLOpenSSLHeaders; type THTTPResults = record ResultCode: ni; Body: string; Success: boolean; error: string; end; THttpsMethod = (mGet, mPost); Tcmd_HTTPS = class(TCommand) private public addHead: string; addHeadValue: string; method: ThttpsMethod; url: string; PostData: string; Results: THTTPResults; ContentType: string; procedure DoExecute; override; procedure Init; override; end; //function QuickHTTPSGet(sURL: ansistring): ansistring; function QuickHTTPSGet(sURL: ansistring; out sOutREsponse: string; addHead: string =''; addHeadValue: string = ''): boolean; function QuickHTTPSPost(sURL: ansistring; PostData: ansistring; ContentType: ansistring = 'application/x-www-form-urlencoded'): ansistring; function HTTPSGet(sURL: string; referer: string = ''): THTTPResults; function HTTPSPost(sURL: string; PostData: string; ContentType: string = 'application/x-www-form-urlencoded'): THTTPResults; implementation function QuickHTTPSGet(sURL: ansistring; out sOutREsponse: string; addHead: string =''; addHeadValue: string = ''): boolean; var htp: IXMLhttprequest; begin {$IFDEF LOG_HTTP} Debug.Log(sURL); {$ENDIF} htp := ComsXMLHTTP30.create(); try htp.open('GET', sURL, false, null, null); if addHead <> '' then htp.setRequestHeader(addHead, addHeadValue); htp.send(''); result := htp.status = 200; if result then sOutREsponse := htp.responsetext else begin soutResponse := htp.responsetext; end; except on e: Exception do begin result := false; sOutResponse := 'error '+e.message; end; end; end; function QuickHTTPSPost(sURL: ansistring; PostData: ansistring; ContentType: ansistring = 'application/x-www-form-urlencoded'): ansistring; var htp: IXMLhttprequest; begin // raise Exception.create('carry forward'); htp := ComsXMLHTTP30.create(); try htp.open('POST', sURL, false,null,null); htp.setRequestHeader('Accept-Language', 'en'); //htp.setRequestHeader('Connection:', 'Keep-Alive'); htp.setRequestHeader('Content-Type', ContentType); htp.setRequestHeader('Content-Length', inttostr(length(PostData))); htp.send(PostData); result := htp.responsetext; finally // htp.free; end; end; function HTTPSGet(sURL: string; referer: string = ''): THTTPResults; var htp: IXMLhttprequest; begin // raise Exception.create('carry forward'); result.error := ''; htp := ComsXMLHTTP30.create(); try try htp.open('GET', sURL, false, null, null); htp.setRequestHeader('Referer', referer); htp.send(''); result.ResultCode := htp.status; result.Body := htp.responseText; result.Success := true; except on e: Exception do begin result.success := false; result.error := e.message; end; end; finally // htp.free; end; end; function HTTPSPost(sURL: string; PostData: string; ContentType: string = 'application/x-www-form-urlencoded'): THTTPResults; var htp: IXMLhttprequest; begin // raise Exception.create('carry forward'); result.error := ''; htp := ComsXMLHTTP30.create(); try htp.open('POST', sURL, false,null,null); htp.setRequestHeader('Accept-Language', 'en'); htp.setRequestHeader('Connection:', 'Keep-Alive'); htp.setRequestHeader('Content-Type', ContentType); htp.setRequestHeader('Content-Length', inttostr(length(PostData))); htp.send(PostData); result.ResultCode := htp.status; result.Body := htp.responsetext; finally // htp.free; end; end; { Tcmd_HTTPS } procedure Tcmd_HTTPS.DoExecute; begin inherited; if method = mGet then begin try results.success := QuickHTTPSGet(self.url, results.body, addhead, addHeadValue); except results.success := false; end; end else if method = mPost then begin results := HTTPSPost(url, postdata, contenttype); end; end; procedure Tcmd_HTTPS.Init; begin inherited; ContentType := 'application/x-www-form-urlencoded'; end; initialization if fileexists(dllpath+'ssleay32.dll') then begin IdOpenSSLSetLibPath(DLLPath); IdSSLOpenSSL.LoadOpenSSLLibrary; end; end.
unit BrickCamp.Model.TQuestion; interface uses Spring, Spring.Persistence.Mapping.Attributes, BrickCamp.Model.IProduct; type [Entity] [Table('QUESTION')] TQuestion = class private [Column('ID', [cpRequired, cpPrimaryKey, cpNotNull, cpDontInsert], 0, 0, 0, 'primary key')] [AutoGenerated] FId: Integer; private FProductId: Integer; FUserId: Integer; FText: string; FIsOpen: SmallInt; function GetId: Integer; function GetProductId: Integer; function GetUserId: Integer; function GetText: string; function GetIsOpen: SmallInt; procedure SetProductId(const Value: Integer); procedure SetUserId(const Value: Integer); procedure SetText(const Value: string); procedure SetIsOpen(const Value: SmallInt); public constructor Create; overload; constructor Create(const Id: integer); overload; property ID: Integer read GetId; [Column('PRODUCT_ID', [cpNotNull])] property ProductId: Integer read GetProductId write SetProductId; [Column('CUSER_ID', [cpNotNull])] property UserId: Integer read GetUserId write SetUserId; [Column('TEXT', [cpNotNull])] property Text: string read GetText write SetText; [Column('ISOPEN')] property IsOpen: SmallInt read GetIsOpen write SetIsOpen; end; implementation { TEmployee } constructor TQuestion.Create(const Id: integer); begin FId := Id; end; constructor TQuestion.Create; begin end; function TQuestion.GetId: Integer; begin Result := FId; end; function TQuestion.GetProductId: Integer; begin Result := FProductId; end; function TQuestion.GetIsOpen: SmallInt; begin Result := FIsOpen; end; function TQuestion.GetText: string; begin Result := FText; end; function TQuestion.GetUserId: Integer; begin Result := FUserId; end; procedure TQuestion.SetProductId(const Value: Integer); begin FProductId := Value; end; procedure TQuestion.SetIsOpen(const Value: SmallInt); begin FIsOpen := Value; end; procedure TQuestion.SetText(const Value: string); begin FText := Value; end; procedure TQuestion.SetUserId(const Value: Integer); begin FUserId := Value; end; end.
unit ClassSustava; interface uses Classes, Typy; type TBody = class public Pole : TList; function Pridaj( NovyBod : TBod ) : PBod; procedure Zmaz( CisloBodu : Word ); constructor Create; destructor Destroy; override; end; TPriamky = class public Pole : TList; function Pridaj( A : TBod; Smer : TVektor ) : PPriamka; constructor Create; destructor Destroy; override; end; TNUholniky = class public Pole : TList; function Pridaj( Novy : TNuholnik ) : PNUholnik; procedure Zmaz( Cislo : integer ); constructor Create; destructor Destroy; override; end; TSustava = class public Body : TBody; Priamky : TPriamky; NUholniky : TNUholniky; constructor Create; destructor Destroy; override; end; implementation uses SysUtils, Debugging; (* -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- || Trieda B O D Y || -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- *) constructor TBody.Create; begin inherited; Napis( 'TBody.Create' ); Pole := TList.Create; end; destructor TBody.Destroy; var I : integer; begin for I := 0 to Pole.Count-1 do Dispose( PBod( Pole.Items[I] ) ); Pole.Free; inherited; end; function TBody.Pridaj( NovyBod : TBod ) : PBod; var PNovyBod : PBod; begin try New( PNovyBod ) except on EOutOfMemory do begin Pole.Error( 'Nedostatok pamäte pre nový bod!' , SizeOf( NovyBod ) ); Result := nil; exit; end; end; PNovyBod^.X := NovyBod.X; PNovyBod^.Y := NovyBod.Y; PNovyBod^.Nazov := NovyBod.Nazov; Result := PNovyBod; try Pole.Add( PNovyBod ) except on EOutOfMemory do begin Pole.Error( 'Nedostatok pamäte pre nový bod!' , SizeOf( NovyBod ) ); Dispose( PNovyBod ); Result := nil; end; end; end; procedure TBody.Zmaz( CisloBodu : Word ); begin Dispose( PBod( Pole[CisloBodu] ) ); Pole.Delete( CisloBodu ); end; (* -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- || Trieda P R I A M K Y || -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- *) constructor TPriamky.Create; begin inherited; Napis( 'TPriamky.Create' ); Pole := TList.Create; end; destructor TPriamky.Destroy; var I : integer; begin for I := 0 to Pole.Count-1 do Dispose( PPriamka( Pole.Items[I] ) ); Pole.Free; inherited; end; function TPriamky.Pridaj( A : TBod; Smer : TVektor ) : PPriamka; var PNovaPriamka : PPriamka; begin try New( PNovaPriamka ) except on EOutOfMemory do begin Pole.Error( 'Nedostatok pamäte pre novú priamku!' , SizeOf( PNovaPriamka^ ) ); Result := nil; exit; end; end; PNovaPriamka^.A := A; PNovaPriamka^.Smer := Smer; Result := PNovaPriamka; try Pole.Add( PNovaPriamka ) except on EOutOfMemory do begin Pole.Error( 'Nedostatok pamäte pre novú priamku!' , SizeOf( PNovaPriamka^ ) ); Dispose( PNovaPriamka ); Result := nil; end; end; end; (* -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- || Trieda N - U H O L N I K Y || -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- *) constructor TNUholniky.Create; begin inherited; Napis( 'TNUHolniky.Create' ); Pole := TList.Create; end; destructor TNUholniky.Destroy; var I : integer; begin for I := 0 to Pole.Count-1 do begin TNUholnik( Pole[I]^ ).Body.Free; Dispose( PNUholnik( Pole[I] ) ); end; Pole.Free; inherited; end; function TNuholniky.Pridaj( Novy : TNuholnik ) : PNUholnik; var PNovy : PNUholnik; begin try New( PNovy ) except on EOutOfMemory do begin Pole.Error( 'Nedostatok pamäte pre nový N-Uholník!' , SizeOf( PNovy^ ) ); Result := nil; exit; end; end; PNovy^.Body := TList.Create; PNovy^.Body := Novy.Body; PNovy^.Nazov := Novy.Nazov; Result := PNovy; try Pole.Add( PNovy ) except on EOutOfMemory do begin Pole.Error( 'Nedostatok pamäte pre nový N-Uholník!' , SizeOf( PNovy^ ) ); Dispose( PNovy ); Result := nil; end; end; end; procedure TNuholniky.Zmaz( Cislo : integer ); begin Dispose( PNUholnik( Pole[Cislo] ) ); Pole.Delete( Cislo ); end; (* -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- || Trieda S U S T A V A || -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- *) constructor TSustava.Create; begin inherited; Body := TBody.Create; Priamky := TPriamky.Create; NUholniky := TNUholniky.Create; end; destructor TSustava.Destroy; begin Body.Free; Priamky.Free; NUholniky.Free; inherited; end; end.
{ ********************************************************************* * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Autor: Brovin Y.D. * E-mail: y.brovin@gmail.com * ******************************************************************** } unit FGX.Toasts.Android; interface uses FGX.Toasts, AndroidApi.JNI.Toasts, AndroidApi.JNI.GraphicsContentViewText, AndroidApi.JNI.Widget, System.UITypes; type { TfgAndroidToast } TfgAndroidToast = class(TfgToast) public const DefaultBackgroundColor = TAlphaColor($FF2A2A2A); private FToast: JToast; FBackgroundView: JView; FIconView: JImageView; FMessageView: JTextView; protected { inherited } procedure DoBackgroundColorChanged; override; procedure DoDurationChanged; override; procedure DoMessageChanged; override; procedure DoMessageColorChanged; override; procedure DoIconChanged; override; { Creating custom view and preparing data for Toast } function CreateBitmapIcon: JBitmap; function CreateBackgroundImage: JBitmap; procedure CreateCustomView; procedure RemoveCustomView; public constructor Create(const AMessage: string; const ADuration: TfgToastDuration); destructor Destroy; override; property Toast: JToast read FToast; end; { TfgAndroidToastService } TfgAndroidToastService = class(TInterfacedObject, IFGXToastService) public { IFGXToastService } function CreateToast(const AMessage: string; const ADuration: TfgToastDuration): TfgToast; procedure Show(const AToast: TfgToast); procedure Cancel(const AToast: TfgToast); end; TfgToastDurationHelper = record helper for TfgToastDuration public function ToJDuration: Integer; end; procedure RegisterService; procedure UnregisterService; implementation uses System.SysUtils, System.Types, System.IOUtils, AndroidApi.Helpers, Androidapi.JNIBridge, Androidapi.JNI.JavaTypes, FMX.Platform, FMX.Helpers.Android, FMX.Graphics, FMX.Surfaces, FMX.Types, FGX.Helpers.Android, FGX.Graphics, FGX.Asserts; procedure RegisterService; begin TPlatformServices.Current.AddPlatformService(IFGXToastService, TfgAndroidToastService.Create); end; procedure UnregisterService; begin TPlatformServices.Current.RemovePlatformService(IFGXToastService); end; { TfgAndroidToast } constructor TfgAndroidToast.Create(const AMessage: string; const ADuration: TfgToastDuration); begin Assert(AMessage <> ''); inherited Create; CallInUIThreadAndWaitFinishing(procedure begin FToast := TJToast.JavaClass.makeText(TAndroidHelper.Context, StrToJCharSequence(AMessage), ADuration.ToJDuration); end); Message := AMessage; Duration := ADuration; end; function TfgAndroidToast.CreateBackgroundImage: JBitmap; var Bitmap: TBitmap; begin Bitmap := Create9PatchShadow(TSizeF.Create(100, 20), BackgroundColor); try Result := BitmapToJBitmap(Bitmap) finally Bitmap.Free; end; end; procedure TfgAndroidToast.CreateCustomView; const CENTER_VERTICAL = 16; IMAGE_MARGIN_RIGHT = 10; BACKGROUND_PADDING = 20; var Layout: JLinearLayout; DestBitmap: JBitmap; Params : JViewGroup_LayoutParams; begin RemoveCustomView; { Background } Layout := TJLinearLayout.JavaClass.init(TAndroidHelper.Context); Layout.setOrientation(TJLinearLayout.JavaClass.HORIZONTAL); Layout.setPadding(BACKGROUND_PADDING, BACKGROUND_PADDING, BACKGROUND_PADDING, BACKGROUND_PADDING); Layout.setGravity(CENTER_VERTICAL); Layout.setBackgroundColor(AlphaColorToJColor(DefaultBackgroundColor)); Params := TJViewGroup_LayoutParams.JavaClass.init(TJViewGroup_LayoutParams.JavaClass.FILL_PARENT, TJViewGroup_LayoutParams.JavaClass.WRAP_CONTENT); Layout.setLayoutParams(Params); FBackgroundView := Layout; { Image } DestBitmap := CreateBitmapIcon; if DestBitmap <> nil then begin FIconView := TJImageView.JavaClass.init(TAndroidHelper.Context); FIconView.setImageBitmap(DestBitmap); FIconView.setPadding(0, 0, IMAGE_MARGIN_RIGHT, 0); Params := TJViewGroup_LayoutParams.JavaClass.init(TJViewGroup_LayoutParams.JavaClass.WRAP_CONTENT, TJViewGroup_LayoutParams.JavaClass.WRAP_CONTENT); FIconView.setLayoutParams(Params); Layout.addView(FIconView, Params); end; { Message } FMessageView := TJTextView.JavaClass.init(TAndroidHelper.Context); FMessageView.setText(StrToJCharSequence(Message)); FMessageView.setTextColor(AlphaColorToJColor(MessageColor)); Params := TJViewGroup_LayoutParams.JavaClass.init(TJViewGroup_LayoutParams.JavaClass.WRAP_CONTENT, TJViewGroup_LayoutParams.JavaClass.WRAP_CONTENT); FMessageView.setLayoutParams(Params); Layout.addView(FMessageView); FToast.setView(Layout); end; function TfgAndroidToast.CreateBitmapIcon: JBitmap; begin if HasIcon then Result := BitmapToJBitmap(Icon) else Result := nil; end; destructor TfgAndroidToast.Destroy; begin FToast := nil; inherited; end; procedure TfgAndroidToast.DoBackgroundColorChanged; begin inherited; if FBackgroundView <> nil then FBackgroundView.setBackgroundColor(AlphaColorToJColor(BackgroundColor)); end; procedure TfgAndroidToast.DoDurationChanged; begin AssertIsNotNil(FToast); inherited; CallInUIThreadAndWaitFinishing(procedure begin FToast.setDuration(Duration.ToJDuration); end); end; procedure TfgAndroidToast.DoIconChanged; begin AssertIsNotNil(Icon); AssertIsNotNil(Toast); inherited; if HasIcon then begin if FIconView = nil then CreateCustomView else FIconView.setImageBitmap(CreateBitmapIcon); end else RemoveCustomView; end; procedure TfgAndroidToast.DoMessageChanged; begin AssertIsNotNil(FToast); inherited; CallInUIThreadAndWaitFinishing(procedure begin FToast.setText(StrToJCharSequence(Message)); if FMessageView <> nil then FMessageView.setText(StrToJCharSequence(Message)); end); end; procedure TfgAndroidToast.DoMessageColorChanged; begin inherited; if FMessageView <> nil then FMessageView.setTextColor(AlphaColorToJColor(MessageColor)); end; procedure TfgAndroidToast.RemoveCustomView; begin Toast.setView(nil); FBackgroundView := nil; FIconView := nil; FMessageView := nil; end; { TfgAndroidToastService } procedure TfgAndroidToastService.Cancel(const AToast: TfgToast); begin AssertIsNotNil(AToast); AssertIsClass(AToast, TfgAndroidToast); CallInUIThreadAndWaitFinishing(procedure begin TfgAndroidToast(AToast).Toast.cancel; end); end; function TfgAndroidToastService.CreateToast(const AMessage: string; const ADuration: TfgToastDuration): TfgToast; begin Result := TfgAndroidToast.Create(AMessage, ADuration); end; procedure TfgAndroidToastService.Show(const AToast: TfgToast); begin AssertIsNotNil(AToast); AssertIsClass(AToast, TfgAndroidToast); CallInUIThreadAndWaitFinishing(procedure begin TfgAndroidToast(AToast).Toast.show; end); end; { TfgToastDurationHelper } function TfgToastDurationHelper.ToJDuration: Integer; begin case Self of TfgToastDuration.Short: Result := TJToast.JavaClass.LENGTH_SHORT; TfgToastDuration.Long: Result := TJToast.JavaClass.LENGTH_LONG; else raise Exception.Create('Unknown value of [FGX.Toasts.TfgToastDuration])'); end; end; end.
{ Minimum Spanning Tree Prim Algorithm O(N3) Input: G: UnDirected weighted graph (Infinity = No Edge) N: Number of vertices Output: Parent: Parent of each vertex in the MST, Parent[1] = 0 NoAnswer: Has no spanning trees (== Not connected) Reference: CLR, p509 By Ali } program MinimumSpanningTree; const MaxN = 100 + 1; Infinity = 10000; var N: Integer; G: array[1 .. MaxN, 1 .. MaxN] of Integer; Parent: array[1 .. MaxN] of Integer; NoAnswer: Boolean; Key: array[1 .. MaxN] of Integer; Mark: array[1 .. MaxN] of Boolean; procedure MST; var I, U, Step: Integer; Min: Integer; begin for I := 1 to N do Key[I] := Infinity; FillChar(Mark, SizeOf(Mark), 0); Key[1] := 0; Parent[1] := 0; for Step := 1 to N do begin Min := Infinity; for I := 1 to N do if not Mark[i] and (Key[I] < Min) then begin U := I; Min := Key[I]; end; if Min = Infinity then begin NoAnswer := True; Exit; end; Mark[U] := True; for I := 1 to N do if not Mark[I] and (Key[I] > G[U, I]) then begin Key[I] := G[U, I]; Parent[I] := U; end; end; NoAnswer := False; end; begin MST; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, parser1, Grids, StdCtrls, Buttons, ExtCtrls, math, ComCtrls; type TForm1 = class(TForm) tabla: TStringGrid; SaveDialog1: TSaveDialog; OpenDialog1: TOpenDialog; PageControl1: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; BitBtn1: TBitBtn; BitBtn2: TBitBtn; BitBtn3: TBitBtn; Image1: TImage; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label1: TLabel; Memo1: TMemo; ListBox1: TListBox; ComboBox1: TComboBox; Label6: TLabel; BitBtn4: TBitBtn; Button1: TButton; Image2: TImage; procedure Button1Click(Sender: TObject); procedure BitBtn3Click(Sender: TObject); procedure BitBtn2Click(Sender: TObject); procedure ComboBox1Change(Sender: TObject); procedure BitBtn4Click(Sender: TObject); procedure BitBtn1Click(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } fun : array[0..2] of TEvaluador; Hx,Hy,NT,Dy : integer; pal : array of array of single; public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} function ajusta(x:single):byte; begin if x<=0 then result := 0 else if x>255 then result := 255 else result := round(x); end; procedure TForm1.FormCreate(Sender: TObject); begin tabla.Cells[0,0] := ' Canal '; tabla.Cells[1,0] := ' F(z) '; tabla.Cells[0,1] := ' R(z) = '; tabla.Cells[0,2] := ' G(z) = '; tabla.Cells[0,3] := ' B(z) = '; tabla.Cells[1,1] := '4*(z-127.5)*(z-127.5)/255'; tabla.Cells[1,2] := '255*abs(sin(2*Pi*z/255))'; tabla.Cells[1,3] := '4*z*(255-z)/255'; fun[0] := Tevaluador.Create; fun[1] := Tevaluador.Create; fun[2] := Tevaluador.Create; NT := 256; Hx := Image1.Width; Hy := Image1.Height; Dy := Hy div 4; Image1.Canvas.Rectangle(0,0,Hx,Hy); Memo1.Lines.Clear; end; // genera paleta procedure TForm1.BitBtn1Click(Sender: TObject); var t : single; c,k : word; z,dz : single; cp : TColor; ss : string; y1,y2 : integer; begin // definimos funciones fun[0].DefineParser(tabla.Cells[1,1],'z'); fun[1].DefineParser(tabla.Cells[1,2],'z'); fun[2].DefineParser(tabla.Cells[1,3],'z'); // dimensionamos la paleta SetLength(pal,3,NT); // llenamos la paleta dz := 255/pred(NT); for c := 0 to 2 do begin z := 0; for k := 0 to NT-1 do begin t := fun[c].Eval(z); pal[c][k] := t; z := z + dz; end; end; // mostramos la paleta Memo1.Lines.Clear; for k := 0 to NT - 1 do begin ss := Format('[%4d] %6.2f %6.2f %6.2f', [k,pal[0][k],pal[1][k],pal[2][k]]); Memo1.Lines.Add(ss); end; if NT = 256 then begin // canal rojo y1 := 1; y2 := Dy-1; for k := 0 to NT - 1 do begin cp := RGB(ajusta(pal[0][k]),0,0 ); Image1.Canvas.Pen.Color := cp; Image1.Canvas.MoveTo(2*k,y1); Image1.Canvas.LineTo(2*k, y2); Image1.Canvas.MoveTo(2*k+1,y1); Image1.Canvas.LineTo(2*k+1,y2); end; // canal verde y1 := Dy +1; y2 := 2*Dy-1; for k := 0 to NT - 1 do begin cp := RGB(0,ajusta(pal[1][k]),0 ); Image1.Canvas.Pen.Color := cp; Image1.Canvas.MoveTo(2*k,y1); Image1.Canvas.LineTo(2*k, y2); Image1.Canvas.MoveTo(2*k+1,y1); Image1.Canvas.LineTo(2*k+1,y2); end; // canal azul y1 := 2*Dy+1; y2 := 3*Dy-1; for k := 0 to NT - 1 do begin cp := RGB(0,0,ajusta(pal[2][k])); Image1.Canvas.Pen.Color := cp; Image1.Canvas.MoveTo(2*k,y1); Image1.Canvas.LineTo(2*k, y2); Image1.Canvas.MoveTo(2*k+1,y1); Image1.Canvas.LineTo(2*k+1,y2); end; // mezcla de canales y1 := 3*Dy+1; for k := 0 to NT - 1 do begin cp := RGB(ajusta(pal[0][k]), ajusta(pal[1][k]), ajusta(pal[2][k]) ); Image1.Canvas.Pen.Color := cp; Image1.Canvas.MoveTo(2*k,y1); Image1.Canvas.LineTo(2*k,Hy); Image1.Canvas.MoveTo(2*k+1,y1); Image1.Canvas.LineTo(2*k+1,Hy); end; end; if NT = 512 then begin // canal rojo y1 := 1; y2 := Dy-1; for k := 0 to NT - 1 do begin cp := RGB(ajusta(pal[0][k]),0,0 ); Image1.Canvas.Pen.Color := cp; Image1.Canvas.MoveTo(k,y1); Image1.Canvas.LineTo(k, y2); end; // canal verde y1 := Dy +1; y2 := 2*Dy-1; for k := 0 to NT - 1 do begin cp := RGB(0,ajusta(pal[1][k]),0 ); Image1.Canvas.Pen.Color := cp; Image1.Canvas.MoveTo(k, y1); Image1.Canvas.LineTo(k, y2); end; // canal azul y1 := 2*Dy+1; y2 := 3*Dy-1; for k := 0 to NT - 1 do begin cp := RGB(0,0,ajusta(pal[2][k])); Image1.Canvas.Pen.Color := cp; Image1.Canvas.MoveTo(k,y1); Image1.Canvas.LineTo(k, y2); end; // mezcla de canales y1 := 3*Dy+1; for k := 0 to NT - 1 do begin cp := RGB(ajusta(pal[0][k]), ajusta(pal[1][k]), ajusta(pal[2][k]) ); Image1.Canvas.Pen.Color := cp; Image1.Canvas.MoveTo(k,y1); Image1.Canvas.LineTo(k,Hy); end; end; // fin end; // selecciona un juego de funciones procedure TForm1.BitBtn4Click(Sender: TObject); var kk : shortint; s0,s1,s2 : string; begin kk := ListBox1.ItemIndex; case kk of 0 : begin s0 := '4*(z-127.5)*(z-127.5)/255'; s1 := '255*abs(sin(2*Pi*z/255))'; s2 := '4*z*(255-z)/255'; end; 1 : begin s0 := '255*abs(sin(2*Pi*z/255))'; s1 := '255*abs(sin(2*Pi*z/255 - Pi/8))'; s2 := '255*abs(sin(2*Pi*z/255 - Pi/4))'; end; 2 : begin s0 := '255*abs(sin(5*Pi*z/510))'; s1 := '255*abs(sin(5*Pi*z/510 - Pi/8))'; s2 := '255*abs(sin(5*Pi*z/510 - Pi/4))'; end; else ShowMessage('Debe seleccionar un modelo primero ...'); end; tabla.Cells[1,1] := s0; tabla.Cells[1,2] := s1; tabla.Cells[1,3] := s2; end; procedure TForm1.ComboBox1Change(Sender: TObject); var vv : string; begin vv := ComboBox1.Items[ ComboBox1.ItemIndex ]; NT := StrToInt(vv); end; // salva la paleta procedure TForm1.BitBtn2Click(Sender: TObject); var id : TextFile; k : word; nom : string; rr : string; cp : TColor; begin if SaveDialog1.Execute then begin nom := SaveDialog1.FileName; AssignFile(id,nom); rewrite(id); writeln(id,'Archivo de paleta FCC BUAP'); writeln(id,'# ',NT); writeln(id,'# ',tabla.Cells[1,1]); writeln(id,'# ',tabla.Cells[1,2]); writeln(id,'# ',tabla.Cells[1,3]); writeln(id); for k := 1 to NT do begin rr := Format('%8.3f %8.3f %8.3f', [pal[0][k],pal[1][k],pal[2][k]]); writeln(id,rr); end; writeln(id); for k := 1 to NT do begin cp := RGB(ajusta(pal[0][k]), ajusta(pal[1][k]), ajusta(pal[2][k]) ); writeln(id,cp); end; CloseFile(id); end; end; // carga paleta procedure TForm1.BitBtn3Click(Sender: TObject); var id : TextFile; nom : string; rr : string; begin if OpenDialog1.Execute then begin nom := OpenDialog1.FileName; AssignFile(id,nom); reset(id); readln(id); readln(id,rr); rr := copy(rr,3,3); NT := StrToInt(rr); if NT=256 then ComboBox1.ItemIndex := 0 else ComboBox1.ItemIndex := 1; readln(id,rr); rr := copy(rr,3,length(rr)); tabla.Cells[1,1] := rr; readln(id,rr); rr := copy(rr,3,length(rr)); tabla.Cells[1,2] := rr; readln(id,rr); rr := copy(rr,3,length(rr)); tabla.Cells[1,3] := rr; CloseFile(id); end; end; // diseñador procedure TForm1.Button1Click(Sender: TObject); var dz,t,z,Ey : single; x,y, c,k,dx, Hx,Hy, marx,mary : word; cols : array [0..2] of TColor; begin // definimos funciones fun[0].DefineParser(tabla.Cells[1,1],'z'); fun[1].DefineParser(tabla.Cells[1,2],'z'); fun[2].DefineParser(tabla.Cells[1,3],'z'); // dimensionamos la paleta SetLength(pal,3,NT); // llenamos la paleta dz := 255/pred(NT); for c := 0 to 2 do begin z := 0; for k := 0 to NT-1 do begin t := fun[c].Eval(z); pal[c][k] := t; z := z + dz; end; end; // Graficamos Hx := Image2.Width; Hy := Image2.Height; marx := 25; mary := 25; // paso if NT = 256 then dx := 2 else dx := 1; cols[0] := clRed; cols[1] := clGreen; cols[2] := clBlue; Ey := (0.8*Hy-mary)/255; // gráfica de datos Image2.Canvas.Brush.Color := clSilver; Image2.Canvas.Rectangle(0,0,Hx,Hy); for c := 0 to 2 do begin Image2.Canvas.Pen.Color := cols[c]; x := marx; y := (Hy - mary) - round(Ey*pal[c][0]); Image2.Canvas.MoveTo(x,y); for k := 1 to NT - 1 do begin x := marx + k*dx; y := Hy - mary - round(Ey*pal[c][k]); Image2.Canvas.LineTo(x,y); end; end; // Ejes Image2.Canvas.Pen.Color := clBlack; Image2.Canvas.MoveTo(marx , Hy-mary+1 ); Image2.Canvas.LineTo(Hx-3 , Hy-mary+1 ); Image2.Canvas.MoveTo(marx , round(0.1*Hy )); Image2.Canvas.LineTo(marx , Hy-mary+1 ); // letreros Image2.Canvas.TextOut(2,Hy-mary+5,'(0,0)'); Image2.Canvas.TextOut(2,round(0.2*Hy) ,'255'); Image2.Canvas.TextOut(Hx-marx,Hy-mary+5,'255'); end; end.
{ AD.A.P.T. Library Copyright (C) 2014-2018, Simon J Stuart, All Rights Reserved Original Source Location: https://github.com/LaKraven/ADAPT Subject to original License: https://github.com/LaKraven/ADAPT/blob/master/LICENSE.md } unit ADAPT.Comparers; {$I ADAPT.inc} interface uses {$IFDEF ADAPT_USE_EXPLICIT_UNIT_NAMES} System.Classes, System.SysUtils, {$ELSE} Classes, SysUtils, {$ENDIF ADAPT_USE_EXPLICIT_UNIT_NAMES} ADAPT.Intf, ADAPT, ADAPT.Comparers.Intf, ADAPT.Comparers.Abstract; {$I ADAPT_RTTI.inc} type IADCardinalComparer = IADOrdinalComparer<Cardinal>; IADIntegerComparer = IADOrdinalComparer<Integer>; IADFloatComparer = IADOrdinalComparer<ADFloat>; IADStringComparer = IADComparer<String>; IADObjectComparer = IADComparer<TADObject>; IADInterfaceComparer = IADComparer<IADInterface>; /// <summary><c>Generic Comparer for any Class implementing the IADInterface Type.</c></summary> /// <remarks> /// <para><c>Uses the InstanceGUID for comparison.</c></para> /// </remarks> TADInterfaceComparer<T: IADInterface> = class(TADComparer<T>) public function AEqualToB(const A, B: T): Boolean; override; function AGreaterThanB(const A, B: T): Boolean; override; function AGreaterThanOrEqualToB(const A, B: T): Boolean; override; function ALessThanB(const A, B: T): Boolean; override; function ALessThanOrEqualToB(const A, B: T): Boolean; override; end; function ADCardinalComparer: IADCardinalComparer; function ADIntegerComparer: IADIntegerComparer; function ADFloatComparer: IADFloatComparer; function ADStringComparer: IADStringComparer; function ADObjectComparer: IADObjectComparer; function ADInterfaceComparer: IADInterfaceComparer; implementation var GCardinalComparer: IADCardinalComparer; GIntegerComparer: IADIntegerComparer; GFloatComparer: IADFloatComparer; GStringComparer: IADStringComparer; GObjectComparer: IADObjectComparer; GADInterfaceComparer: IADInterfaceComparer; type /// <summary><c>Specialized Comparer for Cardinal values.</c></summary> TADCardinalComparer = class(TADOrdinalComparer<Cardinal>) public function AEqualToB(const A, B: Cardinal): Boolean; override; function AGreaterThanB(const A, B: Cardinal): Boolean; override; function AGreaterThanOrEqualToB(const A, B: Cardinal): Boolean; override; function ALessThanB(const A, B: Cardinal): Boolean; override; function ALessThanOrEqualToB(const A, B: Cardinal): Boolean; override; function Add(const A, B: Cardinal): Cardinal; override; function Divide(const A, B: Cardinal): Cardinal; override; function Multiply(const A, B: Cardinal): Cardinal; override; function Subtract(const A, B: Cardinal): Cardinal; override; end; /// <summary><c>Specialized Comparer for Integer values.</c></summary> TADIntegerComparer = class(TADOrdinalComparer<Integer>) public function AEqualToB(const A, B: Integer): Boolean; override; function AGreaterThanB(const A, B: Integer): Boolean; override; function AGreaterThanOrEqualToB(const A, B: Integer): Boolean; override; function ALessThanB(const A, B: Integer): Boolean; override; function ALessThanOrEqualToB(const A, B: Integer): Boolean; override; function Add(const A, B: Integer): Integer; override; function Divide(const A, B: Integer): Integer; override; function Multiply(const A, B: Integer): Integer; override; function Subtract(const A, B: Integer): Integer; override; end; /// <summary><c>Specialized Comparer for ADFloat values.</c></summary> TADFloatComparer = class(TADOrdinalComparer<ADFloat>) public function AEqualToB(const A, B: ADFloat): Boolean; override; function AGreaterThanB(const A, B: ADFloat): Boolean; override; function AGreaterThanOrEqualToB(const A, B: ADFloat): Boolean; override; function ALessThanB(const A, B: ADFloat): Boolean; override; function ALessThanOrEqualToB(const A, B: ADFloat): Boolean; override; function Add(const A, B: ADFloat): ADFloat; override; function Divide(const A, B: ADFloat): ADFloat; override; function Multiply(const A, B: ADFloat): ADFloat; override; function Subtract(const A, B: ADFloat): ADFloat; override; end; /// <summary><c>Specialized Comparer for String values.</c></summary> TADStringComparer = class(TADComparer<String>) public function AEqualToB(const A, B: String): Boolean; override; function AGreaterThanB(const A, B: String): Boolean; override; function AGreaterThanOrEqualToB(const A, B: String): Boolean; override; function ALessThanB(const A, B: String): Boolean; override; function ALessThanOrEqualToB(const A, B: String): Boolean; override; end; TADObjectComparer = class(TADComparer<TADObject>) public function AEqualToB(const A, B: TADObject): Boolean; override; function AGreaterThanB(const A, B: TADObject): Boolean; override; function AGreaterThanOrEqualToB(const A, B: TADObject): Boolean; override; function ALessThanB(const A, B: TADObject): Boolean; override; function ALessThanOrEqualToB(const A, B: TADObject): Boolean; override; end; TADInterfaceComparer = class(TADComparer<IADInterface>) public function AEqualToB(const A, B: IADInterface): Boolean; override; function AGreaterThanB(const A, B: IADInterface): Boolean; override; function AGreaterThanOrEqualToB(const A, B: IADInterface): Boolean; override; function ALessThanB(const A, B: IADInterface): Boolean; override; function ALessThanOrEqualToB(const A, B: IADInterface): Boolean; override; end; { Singleton Getters } function ADCardinalComparer: IADCardinalComparer; begin Result := GCardinalComparer; end; function ADIntegerComparer: IADIntegerComparer; begin Result := GIntegerComparer; end; function ADFloatComparer: IADFloatComparer; begin Result := GFloatComparer; end; function ADStringComparer: IADStringComparer; begin Result := GStringComparer; end; function ADObjectComparer: IADObjectComparer; begin Result := GObjectComparer; end; function ADInterfaceComparer: IADInterfaceComparer; begin Result := GADInterfaceComparer; end; { TADCardinalComparer } function TADCardinalComparer.Add(const A, B: Cardinal): Cardinal; begin Result := A + B; end; function TADCardinalComparer.AEqualToB(const A, B: Cardinal): Boolean; begin Result := (A = B); end; function TADCardinalComparer.AGreaterThanB(const A, B: Cardinal): Boolean; begin Result := (A > B); end; function TADCardinalComparer.AGreaterThanOrEqualToB(const A, B: Cardinal): Boolean; begin Result := (A >= B); end; function TADCardinalComparer.ALessThanB(const A, B: Cardinal): Boolean; begin Result := (A < B); end; function TADCardinalComparer.ALessThanOrEqualToB(const A, B: Cardinal): Boolean; begin Result := (A <= B); end; function TADCardinalComparer.Divide(const A, B: Cardinal): Cardinal; begin Result := A div B; end; function TADCardinalComparer.Multiply(const A, B: Cardinal): Cardinal; begin Result := A * B; end; function TADCardinalComparer.Subtract(const A, B: Cardinal): Cardinal; begin Result := A - B; end; { TADIntegerComparer } function TADIntegerComparer.Add(const A, B: Integer): Integer; begin Result := A + B; end; function TADIntegerComparer.AEqualToB(const A, B: Integer): Boolean; begin Result := (A = B); end; function TADIntegerComparer.AGreaterThanB(const A, B: Integer): Boolean; begin Result := (A > B); end; function TADIntegerComparer.AGreaterThanOrEqualToB(const A, B: Integer): Boolean; begin Result := (A >= B); end; function TADIntegerComparer.ALessThanB(const A, B: Integer): Boolean; begin Result := (A < B); end; function TADIntegerComparer.ALessThanOrEqualToB(const A, B: Integer): Boolean; begin Result := (A <= B); end; function TADIntegerComparer.Divide(const A, B: Integer): Integer; begin Result := A div B; end; function TADIntegerComparer.Multiply(const A, B: Integer): Integer; begin Result := A * B; end; function TADIntegerComparer.Subtract(const A, B: Integer): Integer; begin Result := A - B; end; { TADFloatComparer } function TADFloatComparer.Add(const A, B: ADFloat): ADFloat; begin Result := A + B; end; function TADFloatComparer.AEqualToB(const A, B: ADFloat): Boolean; begin Result := (A = B); end; function TADFloatComparer.AGreaterThanB(const A, B: ADFloat): Boolean; begin Result := (A > B); end; function TADFloatComparer.AGreaterThanOrEqualToB(const A, B: ADFloat): Boolean; begin Result := (A >= B); end; function TADFloatComparer.ALessThanB(const A, B: ADFloat): Boolean; begin Result := (A < B); end; function TADFloatComparer.ALessThanOrEqualToB(const A, B: ADFloat): Boolean; begin Result := (A <= B); end; function TADFloatComparer.Divide(const A, B: ADFloat): ADFloat; begin Result := A / B; end; function TADFloatComparer.Multiply(const A, B: ADFloat): ADFloat; begin Result := A * B; end; function TADFloatComparer.Subtract(const A, B: ADFloat): ADFloat; begin Result := A - B; end; { TADStringComparer } function TADStringComparer.AEqualToB(const A, B: String): Boolean; begin Result := (A = B); end; function TADStringComparer.AGreaterThanB(const A, B: String): Boolean; begin Result := (A > B); end; function TADStringComparer.AGreaterThanOrEqualToB(const A, B: String): Boolean; begin Result := (A >= B); end; function TADStringComparer.ALessThanB(const A, B: String): Boolean; begin Result := (A < B); end; function TADStringComparer.ALessThanOrEqualToB(const A, B: String): Boolean; begin Result := (A <= B); end; { TADObjectComparer } function TADObjectComparer.AEqualToB(const A, B: TADObject): Boolean; begin Result := (A.InstanceGUID = B.InstanceGUID); end; function TADObjectComparer.AGreaterThanB(const A, B: TADObject): Boolean; begin {$IFDEF FPC} Result := (A.InstanceGUID > B.InstanceGUID); {$ELSE} Result := GUIDToString(A.InstanceGUID) > GUIDToString(B.InstanceGUID); {$ENDIF FPC} end; function TADObjectComparer.AGreaterThanOrEqualToB(const A, B: TADObject): Boolean; begin {$IFDEF FPC} Result := (A.InstanceGUID >= B.InstanceGUID); {$ELSE} Result := GUIDToString(A.InstanceGUID) >= GUIDToString(B.InstanceGUID); {$ENDIF FPC} end; function TADObjectComparer.ALessThanB(const A, B: TADObject): Boolean; begin {$IFDEF FPC} Result := (A.InstanceGUID < B.InstanceGUID); {$ELSE} Result := GUIDToString(A.InstanceGUID) < GUIDToString(B.InstanceGUID); {$ENDIF FPC} end; function TADObjectComparer.ALessThanOrEqualToB(const A, B: TADObject): Boolean; begin {$IFDEF FPC} Result := (A.InstanceGUID <= B.InstanceGUID); {$ELSE} Result := GUIDToString(A.InstanceGUID) <= GUIDToString(B.InstanceGUID); {$ENDIF FPC} end; { TADInterfaceComparer } function TADInterfaceComparer.AEqualToB(const A, B: IADInterface): Boolean; begin Result := (A.InstanceGUID = B.InstanceGUID); end; function TADInterfaceComparer.AGreaterThanB(const A, B: IADInterface): Boolean; begin {$IFDEF FPC} Result := (A.InstanceGUID > B.InstanceGUID); {$ELSE} Result := GUIDToString(A.InstanceGUID) > GUIDToString(B.InstanceGUID); {$ENDIF FPC} end; function TADInterfaceComparer.AGreaterThanOrEqualToB(const A, B: IADInterface): Boolean; begin {$IFDEF FPC} Result := (A.InstanceGUID >= B.InstanceGUID); {$ELSE} Result := GUIDToString(A.InstanceGUID) >= GUIDToString(B.InstanceGUID); {$ENDIF FPC} end; function TADInterfaceComparer.ALessThanB(const A, B: IADInterface): Boolean; begin {$IFDEF FPC} Result := (A.InstanceGUID < B.InstanceGUID); {$ELSE} Result := GUIDToString(A.InstanceGUID) < GUIDToString(B.InstanceGUID); {$ENDIF FPC} end; function TADInterfaceComparer.ALessThanOrEqualToB(const A, B: IADInterface): Boolean; begin {$IFDEF FPC} Result := (A.InstanceGUID <= B.InstanceGUID); {$ELSE} Result := GUIDToString(A.InstanceGUID) <= GUIDToString(B.InstanceGUID); {$ENDIF FPC} end; { TADInterfaceComparer<T> } function TADInterfaceComparer<T>.AEqualToB(const A, B: T): Boolean; begin Result := (A.InstanceGUID = B.InstanceGUID); end; function TADInterfaceComparer<T>.AGreaterThanB(const A, B: T): Boolean; begin {$IFDEF FPC} Result := (A.InstanceGUID > B.InstanceGUID); {$ELSE} Result := GUIDToString(A.InstanceGUID) > GUIDToString(B.InstanceGUID); {$ENDIF FPC} end; function TADInterfaceComparer<T>.AGreaterThanOrEqualToB(const A, B: T): Boolean; begin {$IFDEF FPC} Result := (A.InstanceGUID >= B.InstanceGUID); {$ELSE} Result := GUIDToString(A.InstanceGUID) >= GUIDToString(B.InstanceGUID); {$ENDIF FPC} end; function TADInterfaceComparer<T>.ALessThanB(const A, B: T): Boolean; begin {$IFDEF FPC} Result := (A.InstanceGUID < B.InstanceGUID); {$ELSE} Result := GUIDToString(A.InstanceGUID) < GUIDToString(B.InstanceGUID); {$ENDIF FPC} end; function TADInterfaceComparer<T>.ALessThanOrEqualToB(const A, B: T): Boolean; begin {$IFDEF FPC} Result := (A.InstanceGUID <= B.InstanceGUID); {$ELSE} Result := GUIDToString(A.InstanceGUID) <= GUIDToString(B.InstanceGUID); {$ENDIF FPC} end; initialization GCardinalComparer := TADCardinalComparer.Create; GIntegerComparer := TADIntegerComparer.Create; GFloatComparer := TADFloatComparer.Create; GStringComparer := TADStringComparer.Create; GObjectComparer := TADObjectComparer.Create; GADInterfaceComparer := TADInterfaceComparer.Create; end.
unit Initializer.SMART; interface uses SysUtils, Global.LanguageString, Device.PhysicalDrive, Support; type TMainformSMARTApplier = class private ReadEraseError: TReadEraseError; procedure ApplyOnTime; procedure ApplyReadEraseError; procedure SetLabelByTrueReadErrorFalseEraseError( TrueReadErrorFalseEraseError: Boolean); public procedure ApplyMainformSMART; end; implementation uses Form.Main; procedure TMainformSMARTApplier.ApplyOnTime; begin fMain.lOntime.Caption := CapPowerTime[CurrLang] + UIntToStr(fMain.SelectedDrive.SMARTInterpreted.UsedHour) + CapHour[CurrLang]; end; procedure TMainformSMARTApplier.SetLabelByTrueReadErrorFalseEraseError( TrueReadErrorFalseEraseError: Boolean); begin if ReadEraseError.TrueReadErrorFalseEraseError then fMain.lPError.Caption := CapReadError[CurrLang] else fMain.lPError.Caption := CapWriteError[CurrLang]; if fMain.SelectedDrive.SupportStatus.Supported = CDIInsufficient then fMain.lPError.Caption := fMain.lPError.Caption + CapUnsupported[CurrLang] else fMain.lPError.Caption := fMain.lPError.Caption + UIntToStr(ReadEraseError.Value) + CapCount[CurrLang]; end; procedure TMainformSMARTApplier.ApplyReadEraseError; begin ReadEraseError := fMain.SelectedDrive.SMARTInterpreted.ReadEraseError; SetLabelByTrueReadErrorFalseEraseError( ReadEraseError.TrueReadErrorFalseEraseError); end; procedure TMainformSMARTApplier.ApplyMainformSMART; begin ApplyOnTime; ApplyReadEraseError; end; end.
unit VA508AccessibilityPE; interface uses Windows, SysUtils, DesignIntf, DesignEditors, DesignConst, TypInfo, Controls, StdCtrls, Classes, Forms, VA508AccessibilityManager, Dialogs, ColnEdit, RTLConsts, VA508AccessibilityManagerEditor; type TVA508AccessibilityManager4PE = class(TVA508AccessibilityManager); TVA508AccessibilityPropertyMapper = class(TStringProperty) public function GetAttributes: TPropertyAttributes; override; procedure GetProperties(Proc: TGetPropProc); override; end; TVA508NestedPropertyType = (ptText, ptLabel, ptProperty, ptDefault); //, ptEvent); TVA508NestedPropertyEditor = class(TNestedProperty) strict private FName: String; FType: TVA508NestedPropertyType; FManager: TVA508AccessibilityManager4PE; protected property Manager: TVA508AccessibilityManager4PE read FManager; public constructor Create(AParent: TVA508AccessibilityPropertyMapper; AName: String; PType: TVA508NestedPropertyType); function AllEqual: Boolean; override; procedure Edit; override; function GetEditLimit: Integer; override; function GetAttributes: TPropertyAttributes; override; function GetName: string; override; function GetValue: string; override; procedure GetValues(Proc: TGetStrProc); override; procedure SetValue(const Value: string); override; end; { TVA508AccessibilityEventPropertyEditor = class(TVA508NestedPropertyEditor, IMethodProperty) protected function GetMethodValue(Index: Integer): TMethod; public function AllNamed: Boolean; virtual; procedure Edit; override; function GetValue: string; override; procedure GetValues(Proc: TGetStrProc); override; procedure SetValue(const AValue: string); override; function GetFormMethodName: string; virtual; function GetTrimmedEventName: string; end; } TVA508CollectionPropertyEditor = class(TCollectionProperty) public function GetColOptions: TColOptions; override; function GetAttributes: TPropertyAttributes; override; procedure GetValues(AProc: TGetStrProc); override; function GetValue: String; override; procedure SetValue(const AValue: String); override; procedure Edit; override; // function GetEditorClass: tForm; override; end; { TODO -oChris Bell : Impliment the actual code that will look to this new property } TVA508AccessibilityManagerEditor = class(TComponentEditor) public procedure Edit; override; procedure ExecuteVerb(Index: Integer); override; function GetVerb(Index: Integer): string; override; function GetVerbCount: Integer; override; end; TVA508AccessibilityLabelPropertyEditor = class(TComponentProperty) private FManager: TVA508AccessibilityManager4PE; function GetManager: TVA508AccessibilityManager4PE; public function GetAttributes: TPropertyAttributes; override; procedure GetProperties(Proc: TGetPropProc); override; function GetValue: string; override; procedure GetValues(Proc: TGetStrProc); override; procedure SetValue(const Value: string); override; end; TVA508AccessibilityPropertyPropertyEditor = class(TStringProperty) private FManager: TVA508AccessibilityManager4PE; function GetManager: TVA508AccessibilityManager4PE; function GetRootComponent(index: integer): TWinControl; public function AllEqual: Boolean; override; function GetAttributes: TPropertyAttributes; override; function GetEditLimit: Integer; override; function GetValue: string; override; procedure GetValues(Proc: TGetStrProc); override; procedure SetValue(const Value: string); override; end; TVA508AccessibilityComponentPropertyEditor = class(TComponentProperty) public function GetAttributes: TPropertyAttributes; override; end; const WinControlPropertyToMap = 'Hint'; procedure Register; implementation function GetAccessibilityManager(Editor: TPropertyEditor; Index: integer): TVA508AccessibilityManager4PE; var Control, Root: TComponent; i: integer; begin Result := nil; if assigned(Editor.GetComponent(Index)) and (Editor.GetComponent(Index) is TComponent) then begin Control := TComponent(Editor.GetComponent(Index)); Root := Control; while (assigned(Root) and (not (Root is TCustomForm))) do Root := Root.Owner; if assigned(Root) and (Root is TCustomForm) then begin for i := 0 to Root.ComponentCount-1 do begin if Root.Components[i] is TVA508AccessibilityManager then begin Result := TVA508AccessibilityManager4PE(Root.Components[i]); exit; end; end; end; end; end; function AllComponentsHaveSameManager(Editor: TPropertyEditor): boolean; var i: integer; manager: TVA508AccessibilityManager4PE; begin manager := GetAccessibilityManager(Editor, 0); Result := assigned(manager); if (not result) or (Editor.PropCount < 2) then exit; for i := 1 to Editor.PropCount-1 do begin if (GetAccessibilityManager(Editor, i) <> manager) then begin Result := FALSE; exit; end; end; end; procedure GetStringPropertyNames(Manager: TVA508AccessibilityManager4PE; Component: TWinControl; List: TStringList; Add: boolean); var i: Integer; current: TStringList; begin current := TStringList.Create; try Manager.GetProperties(Component, current); if Add then list.Assign(current) else begin for I := List.Count - 1 downto 0 do begin if current.IndexOf(list[i]) < 0 then List.Delete(i); end; end; finally current.Free; end; end; function QVal(txt: string): string; begin Result := '="' + txt + '"'; end; function StripQVal(text: string): string; var i: integer; begin i := pos('=', text); if (i > 0) then Result := copy(text,1,i-1) else Result := text; end; { TVA508AccessibilityPropertyMapper } const DelphiPaletteName = 'VA 508'; function TVA508AccessibilityPropertyMapper.GetAttributes: TPropertyAttributes; begin if AllComponentsHaveSameManager(Self) then Result := [paMultiSelect, paRevertable, paSubProperties] else Result := inherited GetAttributes; end; procedure TVA508AccessibilityPropertyMapper.GetProperties( Proc: TGetPropProc); begin if not AllComponentsHaveSameManager(Self) then exit; Proc(TVA508NestedPropertyEditor.Create(Self, AccessibilityLabelPropertyName, ptLabel)); Proc(TVA508NestedPropertyEditor.Create(Self, AccessibilityPropertyPropertyName, ptProperty)); Proc(TVA508NestedPropertyEditor.Create(Self, AccessibilityTextPropertyName, ptText)); Proc(TVA508NestedPropertyEditor.Create(Self, AccessibilityUseDefaultPropertyName, ptDefault)); // Proc(TVA508AccessibilityEventPropertyEditor.Create(Self, AccessibilityEventPropertyName, ptEvent)); end; { TVA508NestedStringProperty } function TVA508NestedPropertyEditor.AllEqual: Boolean; var i: Integer; txt, prop: string; lbl: TLabel; // V, T: TMethod; default: boolean; begin if PropCount > 1 then begin Result := False; if not (GetComponent(0) is TWinControl) then exit; case FType of ptText: begin txt := FManager.AccessText[TWinControl(GetComponent(0))]; for i := 1 to PropCount - 1 do if txt <> FManager.AccessText[TWinControl(GetComponent(i))] then exit; end; ptLabel: begin lbl := FManager.AccessLabel[TWinControl(GetComponent(0))]; for i := 1 to PropCount - 1 do if lbl <> FManager.AccessLabel[TWinControl(GetComponent(i))] then exit; end; ptProperty: begin prop := FManager.AccessProperty[TWinControl(GetComponent(0))]; for i := 1 to PropCount - 1 do if prop <> FManager.AccessProperty[TWinControl(GetComponent(i))] then exit; end; ptDefault: begin default := FManager.UseDefault[TWinControl(GetComponent(0))]; for i := 1 to PropCount - 1 do if default <> FManager.UseDefault[TWinControl(GetComponent(i))] then exit; end; { ptEvent: begin V := TMethod(FManager.OnComponentAccessRequest[TWinControl(GetComponent(0))]); for i := 1 to PropCount - 1 do begin T := TMethod(FManager.OnComponentAccessRequest[TWinControl(GetComponent(i))]); if (T.Code <> V.Code) or (T.Data <> V.Data) then Exit; end; end;} end; end; Result := True; end; constructor TVA508NestedPropertyEditor.Create(AParent: TVA508AccessibilityPropertyMapper; AName: String; PType: TVA508NestedPropertyType); begin inherited Create(AParent); FManager := GetAccessibilityManager(AParent, 0); FName := AName; FType := PType; end; procedure TVA508NestedPropertyEditor.Edit; var lbl: TLabel; begin if (FType = ptLabel) and (Designer.GetShiftState * [ssCtrl, ssLeft] = [ssCtrl, ssLeft]) then begin lbl := FManager.AccessLabel[TWinControl(GetComponent(0))]; if assigned(lbl) then Designer.SelectComponent(lbl) else inherited Edit; end else inherited Edit; end; function TVA508NestedPropertyEditor.GetAttributes: TPropertyAttributes; begin case FType of ptText: Result := [paMultiSelect, paRevertable, paAutoUpdate]; ptLabel, ptProperty: Result := [paMultiSelect, paRevertable, paValueList, paSortList, paAutoUpdate]; ptDefault: Result := [paMultiSelect, paValueList, paSortList, paRevertable]; // ptEvent: // Result := [paMultiSelect, paValueList, paSortList, paRevertable]; else Result := []; end; end; function TVA508NestedPropertyEditor.GetEditLimit: Integer; begin case FType of ptText: Result := 32767; ptDefault : Result := 63; // ptEvent: Result := MaxIdentLength; else // ptLabel, ptProperty: Result := 127; end; end; function TVA508NestedPropertyEditor.GetName: string; begin Result := FName; end; function TVA508NestedPropertyEditor.GetValue: string; var lbl: TLabel; Default: boolean; begin Result := ''; if not (GetComponent(0) is TWinControl) then exit; case FType of ptLabel: begin lbl := FManager.AccessLabel[TWinControl(GetComponent(0))]; if assigned(lbl) then Result := FManager.GetComponentName(lbl) + QVal(lbl.Caption); end; ptText: Result := FManager.AccessText[TWinControl(GetComponent(0))]; ptProperty: begin Result := FManager.AccessProperty[TWinControl(GetComponent(0))]; if Result <> '' then Result := Result + QVal(GetPropValue(GetComponent(0), Result)); end; ptDefault: begin Default := FManager.UseDefault[TWinControl(GetComponent(0))]; Result := GetEnumName(TypeInfo(Boolean), Ord(Default)); end; end; end; procedure TVA508NestedPropertyEditor.GetValues(Proc: TGetStrProc); var list: TStringList; i: integer; name: string; begin list := TStringList.Create; try case FType of ptLabel: begin FManager.GetLabelStrings(list); for i := 0 to list.count-1 do Proc(list[i]); end; ptProperty: begin GetStringPropertyNames(FManager, TWinControl(GetComponent(0)), list, TRUE); if PropCount > 1 then begin for i := 1 to PropCount-1 do begin if GetComponent(i) is TWinControl then GetStringPropertyNames(FManager, TWinControl(GetComponent(i)), list, FALSE); end; end; list.Sort; for i := 0 to list.count-1 do begin name := list[i]; if PropCount = 1 then name := name + QVal(GetPropValue(GetComponent(0), name)); Proc(name); end; end; ptDefault: begin Proc(GetEnumName(TypeInfo(Boolean), Ord(False))); Proc(GetEnumName(TypeInfo(Boolean), Ord(True))); end; end; finally list.free; end; end; procedure TVA508NestedPropertyEditor.SetValue(const Value: string); var i, BVal: Integer; lbl: TLabel; cmp: TComponent; Name: String; begin BVal := Ord(FALSE); lbl := nil; case FType of ptLabel: begin Name := StripQVal(Value); cmp := Designer.GetComponent(Name); if (cmp is TLabel) then lbl := TLabel(cmp); end; ptProperty: Name := StripQVal(Value); ptDefault: begin BVal := GetEnumValue(TypeInfo(Boolean), Value); with GetTypeData(TypeInfo(Boolean))^ do if (BVal < MinValue) or (BVal > MaxValue) then raise EPropertyError.CreateRes(@SInvalidPropertyValue); end; end; for i := 0 to PropCount - 1 do begin if GetComponent(i) is TWinControl then begin case FType of ptText: FManager.AccessText[TWinControl(GetComponent(i))] := Value; ptLabel: FManager.AccessLabel[TWinControl(GetComponent(i))] := lbl; ptProperty: FManager.AccessProperty[TWinControl(GetComponent(i))] := Name; ptDefault: FManager.UseDefault[TWinControl(GetComponent(i))] := Boolean(BVal); end; end; end; Modified; end; (* { TVA508AccessibilityEventPropertyEditor } function TVA508AccessibilityEventPropertyEditor.AllNamed: Boolean; var I: Integer; begin Result := True; for I := 0 to PropCount - 1 do if GetComponent(I).GetNamePath = '' then begin Result := False; Break; end; end; procedure TVA508AccessibilityEventPropertyEditor.Edit; var FormMethodName: string; CurDesigner: IDesigner; begin CurDesigner := Designer; { Local property so if designer is nil'ed out, no AV will happen } if not AllNamed then raise EPropertyError.CreateRes(@SCannotCreateName); FormMethodName := GetValue; if (FormMethodName = '') or CurDesigner.MethodFromAncestor(GetMethodValue(0)) then begin if FormMethodName = '' then FormMethodName := GetFormMethodName; if FormMethodName = '' then raise EPropertyError.CreateRes(@SCannotCreateName); SetValue(FormMethodName); end; CurDesigner.ShowMethod(FormMethodName); end; function TVA508AccessibilityEventPropertyEditor.GetFormMethodName: string; var I: Integer; begin if GetComponent(0) = Designer.GetRoot then begin Result := Designer.GetRootClassName; if (Result <> '') and (Result[1] = 'T') then Delete(Result, 1, 1); end else begin Result := Designer.GetObjectName(GetComponent(0)); for I := Length(Result) downto 1 do if Result[I] in ['.', '[', ']', '-', '>'] then Delete(Result, I, 1); end; if Result = '' then raise EPropertyError.CreateRes(@SCannotCreateName); Result := Result + GetTrimmedEventName; end; function TVA508AccessibilityEventPropertyEditor.GetMethodValue(Index: Integer): TMethod; begin if not (GetComponent(Index) is TWinControl) then begin Result.Code := nil; Result.Data := nil; end else Result := TMethod(Manager.OnComponentAccessRequest[TWinControl(GetComponent(Index))]); end; { TVA508AccessibilityEventPropertyEditor } function TVA508AccessibilityEventPropertyEditor.GetTrimmedEventName: string; begin Result := GetName; if (Length(Result) >= 2) and (Result[1] in ['O', 'o']) and (Result[2] in ['N', 'n']) then Delete(Result,1,2); end; function TVA508AccessibilityEventPropertyEditor.GetValue: string; begin Result := Designer.GetMethodName(GetMethodValue(0)); end; procedure TVA508AccessibilityEventPropertyEditor.GetValues(Proc: TGetStrProc); begin Designer.GetMethods(GetTypeData(TypeInfo(TVA508ComponentScreenReaderEvent)), Proc); end; procedure TVA508AccessibilityEventPropertyEditor.SetValue(const AValue: string); var CurDesigner: IDesigner; procedure CheckChainCall(const MethodName: string; Method: TMethod); var Persistent: TPersistent; Component: TComponent; InstanceMethod: string; Instance: TComponent; begin Persistent := GetComponent(0); if Persistent is TComponent then begin Component := TComponent(Persistent); if (Component.Name <> '') and (Method.Data <> CurDesigner.GetRoot) and (TObject(Method.Data) is TComponent) then begin Instance := TComponent(Method.Data); InstanceMethod := Instance.MethodName(Method.Code); if InstanceMethod <> '' then CurDesigner.ChainCall(MethodName, Instance.Name, InstanceMethod, GetTypeData(TypeInfo(TVA508ComponentScreenReaderEvent))); end; end; end; var NewMethod: Boolean; CurValue: string; OldMethod: TMethod; i: integer; event: TVA508ComponentScreenReaderEvent; begin CurDesigner := Designer; if not AllNamed then raise EPropertyError.CreateRes(@SCannotCreateName); CurValue:= GetValue; if (CurValue <> '') and (AValue <> '') and (SameText(CurValue, AValue) or not CurDesigner.MethodExists(AValue)) and not CurDesigner.MethodFromAncestor(GetMethodValue(0)) then CurDesigner.RenameMethod(CurValue, AValue) else begin NewMethod := (AValue <> '') and not CurDesigner.MethodExists(AValue); OldMethod := GetMethodValue(0); event := TVA508ComponentScreenReaderEvent(CurDesigner.CreateMethod(AValue, GetTypeData(TypeInfo(TVA508ComponentScreenReaderEvent)))); for i := 0 to PropCount - 1 do begin if (GetComponent(i) is TWinControl) then Manager.OnComponentAccessRequest[TWinControl(GetComponent(i))] := event; end; if NewMethod then begin { Designer may have been nil'ed out this point when the code editor recieved focus. This fixes an AV by using a local variable which keeps a reference to the designer } if (PropCount = 1) and (OldMethod.Data <> nil) and (OldMethod.Code <> nil) then CheckChainCall(AValue, OldMethod); CurDesigner.ShowMethod(AValue); end; end; Modified; end; *) { TVA508CollectionProperty } function TVA508CollectionPropertyEditor.GetColOptions: TColOptions; begin Result := [coMove]; end; procedure TVA508CollectionPropertyEditor.Edit; var tmpCollection: TVA508AccessibilityCollection; begin if TComponent(GetComponent(0)) is TVA508AccessibilityManager then begin va508CollectionEditor := Tva508CollectionEditor.Create(Application); try // tmpCollection := TVA508AccessibilityCollection(GetOrdValue); tmpCollection := TVA508AccessibilityCollection(GetObjectProp(GetComponent(0), GetPropInfo)); va508CollectionEditor.FillOutList(tmpCollection, TVA508AccessibilityManager(GetComponent(0))); va508CollectionEditor.ShowModal; finally va508CollectionEditor.Free; end; end else inherited; end; { function TVA508CollectionPropertyEditor.GetEditorClass: tForm; begin Result := Tva508CollectionEditor; end; } function TVA508CollectionPropertyEditor.GetAttributes: TPropertyAttributes; begin Result := inherited GetAttributes + [paDialog]; end; procedure TVA508CollectionPropertyEditor.GetValues(AProc: TGetStrProc); // var // CollB: TVA508AccessibilityCollection; // I: Integer; begin inherited; { if self.GetComponent(0) is TVA508AccessibilityItem then begin CollB := (self.GetComponent(0) as TVA508AccessibilityItem).Collection; for I := 0 to CollB.Count-1 do begin AProc(CollB.Items[I].AccessLabel.Caption); { property AccessProperty: string read FProperty write SetProperty; property AccessText: string read FText write SetText; property Component: TWinControl read FComponent write SetComponent; property UseDefault: boolean read FDefault write SetDefault; property DisplayName: string read GetDisplayName; end; end; } end; function TVA508CollectionPropertyEditor.GetValue: String; begin Result := GetStrValue; end; procedure TVA508CollectionPropertyEditor.SetValue(const AValue: String); begin SetStrValue(AValue); end; { TVA508AccessibilityManagerEditor } procedure TVA508AccessibilityManagerEditor.Edit; var tmpCollection: TVA508AccessibilityCollection; begin va508CollectionEditor := Tva508CollectionEditor.Create(Application); try // tmpCollection := TVA508AccessibilityCollection(GetOrdValue); tmpCollection := TVA508AccessibilityManager(Component).AccessData; va508CollectionEditor.FillOutList(tmpCollection, TVA508AccessibilityManager(Component)); va508CollectionEditor.ShowModal; finally va508CollectionEditor.Free; end; end; procedure TVA508AccessibilityManagerEditor.ExecuteVerb(Index: Integer); begin if Index = 0 then Edit else inherited ExecuteVerb(Index); end; function TVA508AccessibilityManagerEditor.GetVerb(Index: Integer): string; begin if Index = 0 then Result := 'Edit Accessible Controls..' else Result := inherited GetVerb(Index); end; function TVA508AccessibilityManagerEditor.GetVerbCount: Integer; begin Result := 1; end; { TVA508AccessibilityLabelPropertyEditor } function TVA508AccessibilityLabelPropertyEditor.GetAttributes: TPropertyAttributes; begin Result := [paMultiSelect, paRevertable, paValueList, paSortList, paAutoUpdate]; end; function TVA508AccessibilityLabelPropertyEditor.GetManager: TVA508AccessibilityManager4PE; begin if not assigned(FManager) then FManager := TVA508AccessibilityManager4PE(TVA508AccessibilityItem(GetComponent(0)).Manager); Result := FManager; end; procedure TVA508AccessibilityLabelPropertyEditor.GetProperties( Proc: TGetPropProc); begin exit; end; function TVA508AccessibilityLabelPropertyEditor.GetValue: string; var lbl: TLabel; begin lbl := TVA508AccessibilityItem(GetComponent(0)).AccessLabel; if assigned(lbl) then Result := GetManager.GetComponentName(lbl) + QVal(lbl.Caption); end; procedure TVA508AccessibilityLabelPropertyEditor.GetValues(Proc: TGetStrProc); var i: integer; list: TStringList; begin list := TStringList.Create; try GetManager.GetLabelStrings(list); for i := 0 to list.count-1 do Proc(list[i]); finally list.Free; end; end; procedure TVA508AccessibilityLabelPropertyEditor.SetValue(const Value: string); begin inherited SetValue(StripQVal(Value)); end; { TVA508AccessibilityPropertyPropertyEditor } function TVA508AccessibilityPropertyPropertyEditor.AllEqual: Boolean; var i: integer; prop: string; begin if PropCount > 1 then begin Result := FALSE; prop := GetManager.AccessProperty[TWinControl(GetComponent(0))]; for i := 1 to PropCount - 1 do if prop <> FManager.AccessProperty[TWinControl(GetComponent(i))] then exit; end; Result := TRUE; end; function TVA508AccessibilityPropertyPropertyEditor.GetAttributes: TPropertyAttributes; begin Result := [paMultiSelect, paRevertable, paValueList, paSortList, paAutoUpdate]; end; function TVA508AccessibilityPropertyPropertyEditor.GetEditLimit: Integer; begin Result := 127; end; function TVA508AccessibilityPropertyPropertyEditor.GetManager: TVA508AccessibilityManager4PE; begin if not assigned(FManager) then FManager := TVA508AccessibilityManager4PE(TVA508AccessibilityItem(GetComponent(0)).Manager); Result := FManager; end; function TVA508AccessibilityPropertyPropertyEditor.GetRootComponent( index: integer): TWinControl; begin Result := TVA508AccessibilityItem(GetComponent(index)).Component; end; function TVA508AccessibilityPropertyPropertyEditor.GetValue: string; begin Result := inherited GetValue; if Result <> '' then Result := Result + QVal(GetPropValue(GetRootComponent(0), Result)); end; procedure TVA508AccessibilityPropertyPropertyEditor.GetValues( Proc: TGetStrProc); var list: TStringList; i: integer; name: string; begin list := TStringList.Create; try GetStringPropertyNames(GetManager, GetRootComponent(0), list, TRUE); if PropCount > 1 then begin for i := 1 to PropCount-1 do GetStringPropertyNames(FManager, GetRootComponent(i), list, FALSE); end; list.Sort; for i := 0 to list.count-1 do begin name := list[i]; if PropCount = 1 then name := name + QVal(GetPropValue(GetRootComponent(0), name)); Proc(name); end; finally list.free; end; end; procedure TVA508AccessibilityPropertyPropertyEditor.SetValue( const Value: string); begin inherited SetValue(StripQVal(Value)); end; { TVA508AccessibilityClassPropertyEditor } function TVA508AccessibilityComponentPropertyEditor.GetAttributes: TPropertyAttributes; begin Result := [paDisplayReadOnly]; end; procedure Register; begin RegisterComponents(DelphiPaletteName, [TVA508AccessibilityManager, TVA508ComponentAccessibility, TVA508StaticText]); RegisterPropertyEditor(TypeInfo(TVA508AccessibilityCollection), TVA508AccessibilityManager, VA508DataPropertyName, TVA508CollectionPropertyEditor); RegisterPropertyEditor(TypeInfo(String), TWinControl, WinControlPropertyToMap, TVA508AccessibilityPropertyMapper); RegisterPropertyEditor(TypeInfo(TLabel), TVA508AccessibilityItem, AccessibilityLabelPropertyName, TVA508AccessibilityLabelPropertyEditor); RegisterPropertyEditor(TypeInfo(String), TVA508AccessibilityItem, AccessibilityPropertyPropertyName, TVA508AccessibilityPropertyPropertyEditor); RegisterPropertyEditor(TypeInfo(TComponent), TVA508AccessibilityItem, AccessDataComponentText, TVA508AccessibilityComponentPropertyEditor); RegisterComponentEditor(TVA508AccessibilityManager, TVA508AccessibilityManagerEditor); end; end.
{ Invokable interface IuUsersOfTravel } unit uUsersOfTravelIntf; interface uses Soap.InvokeRegistry, System.Types, Soap.XSBuiltIns; type { Invokable interfaces must derive from IInvokable } IuUsersOfTravel = interface(IInvokable) ['{EB8E9708-46B0-4737-A1D7-D6C7ED5434C7}'] { Methods of Invokable interface must not use the default } { calling convention; stdcall is recommended } end; implementation initialization { Invokable interfaces must be registered } InvRegistry.RegisterInterface(TypeInfo(IuUsersOfTravel)); end.
unit uGameDevices; interface uses KbdMacro, Windows, DirectInput, Messages, Classes; const WM_JOY_BUTTON_DOWN = WM_USER + 302; WM_JOY_BUTTON_UP = WM_USER + 303; type THIDJoystick = class (THIDKeyboard) private fButtonsCount: Integer; fRegisteredProcs: TStrings; fDIDevice: IDIRECTINPUTDEVICE8; fJoyState: DIJOYSTATE2; fAxisTrigger: DIJOYSTATE2; fLastAxis: DIJOYSTATE2; fAxisTickSkip: Integer; fCurrentAxisTick: Integer; procedure DoAxisCall(pProcName, pAxisName: String; pValue: LongInt); function GetAxisPointer(pIn: PDIJoyState2; pAxisName: String): PLongInt; public constructor Create(pSystemID: string; pHandle: HWND); destructor Destroy; Override; procedure GenerateEvents(Handle: HWND); procedure GetButtons; function GetButton(pNumber: Integer): Shortint; function GetAxis(pName: String): LongInt; procedure RegisterAxisEvent(pAxis, pProcName: String; pDelta: Integer); procedure UnRegisterAxisEvent(pAxis: String); property ButtonsCount : Integer read fButtonsCount write fButtonsCount; property DIDevice : IDIRECTINPUTDEVICE8 read fDIDevice write fDIDevice; property JoyState : DIJOYSTATE2 read fJoyState write fJoyState; property AxisTickSkip: Integer read fAxisTickSkip write fAxisTickSkip; end; TNewGameDeviceCallback = procedure(pDev: THIDJoystick) of object; TGameControl = class (TObject) private fDevices: TList; fOnNewDevice: TNewGameDeviceCallback; DInput : IDIRECTINPUT8; //DirectInput procedure AddGameDevice(pDeviceName: String; Data: IDIRECTINPUTDEVICE8; pGUID: TGUID); function GUID2Str(pGUID: TGUID): String; function GetAvailable: Boolean; public constructor Create; procedure InitDirectX; procedure DebugLog(Value: String); function GetDevice(pName: String): THIDJoystick; destructor Destroy; Override; property OnNewDevice: TNewGameDeviceCallback read fOnNewDevice write fOnNewDevice; property Available: Boolean read GetAvailable; end; implementation uses uGlobals, Forms, SysUtils, ActiveX, Variants; function EnumJoysticksCallback(const lpddi: TDIDeviceInstanceA; pvRef: Pointer): HRESULT; stdcall; var logStr: String; DI_JoyDevice : IDIRECTINPUTDEVICE8; hr: HRESULT; begin Result := Integer(DIENUM_CONTINUE); with TGameControl(pvRef) do begin hr := DInput.CreateDevice(lpddi.guidInstance, DI_JoyDevice, nil); if (not FAILED(hr)) then begin hr := DI_JoyDevice.SetDataFormat(c_dfDIJoystick2); if (not FAILED(hr)) then begin hr := DI_JoyDevice.SetCooperativeLevel((Glb.Owner as TForm).Handle, DISCL_NONEXCLUSIVE or DISCL_BACKGROUND); if (not FAILED(hr)) then begin logStr := lpddi.tszInstanceName; //logStr := lpddi.tszProductName; AddGameDevice(logStr, DI_JoyDevice, lpddi.guidInstance); end; end; end; //FDeviceGUID := lpddi.guidInstance; //Result := Integer(DIENUM_STOP); end; end; { THIDJoystick } constructor THIDJoystick.Create(pSystemID: string; pHandle: HWND); begin inherited; fRegisteredProcs := TStringList.Create; fAxisTickSkip := 1; fCurrentAxisTick := fAxisTickSkip; ZeroMemory(@fAxisTrigger, SizeOf(fAxisTrigger)); fDIDevice := nil; // for dead devices (just loaded) end; destructor THIDJoystick.Destroy; begin fRegisteredProcs.Free; inherited; end; procedure THIDJoystick.DoAxisCall(pProcName, pAxisName: String; pValue: Integer); var Params : PSafeArray; v : Variant; begin Glb.DebugLog(Format('Dev %s axis %s change to %d.', [Name, pAxisName, pValue]), 'GAME'); // prepare params v := VarArrayCreate([0, 2], varVariant); v[0] := Name; v[1] := pAxisName; v[2] := pValue; Params := PSafeArray(TVarData(v).VArray); try Glb.ScriptEngine.ExecutionSC.Run(pProcName, Params); except On E: Exception do begin Glb.LogError(E.Message); end; end; end; procedure THIDJoystick.GenerateEvents(Handle: HWND); var I: Integer; lOldState: DIJoyState2; begin if DIDevice = nil then exit; lOldState := fJoyState; GetButtons; for I := 0 to fButtonsCount - 1 do if fJoyState.rgbButtons[I] <> lOldState.rgbButtons[I] then begin if lOldState.rgbButtons[I] = 0 then PostMessage(Handle, WM_JOY_BUTTON_DOWN, Integer(self), I) else PostMessage(Handle, WM_JOY_BUTTON_UP, Integer(self), I); end; if (fRegisteredProcs.Count > 0) then begin Dec(fCurrentAxisTick); if fCurrentAxisTick = 0 then begin fCurrentAxisTick := fAxisTickSkip; // codefor each axis copied for performance // lX if (fAxisTrigger.lX > 0) and (Abs(fLastAxis.lX - fJoyState.lX) > fAxisTrigger.lX) then begin DoAxisCall(fRegisteredProcs.Values['X'], 'X', fJoyState.lX); fLastAxis.lX := fJoyState.lX; end; //lY Y if (fAxisTrigger.lY > 0) and (Abs(fLastAxis.lY - fJoyState.lY) > fAxisTrigger.lY) then begin DoAxisCall(fRegisteredProcs.Values['Y'], 'Y', fJoyState.lY); fLastAxis.lY := fJoyState.lY; end; //lZ Z if (fAxisTrigger.lZ > 0) and (Abs(fLastAxis.lZ - fJoyState.lZ) > fAxisTrigger.lZ) then begin DoAxisCall(fRegisteredProcs.Values['Z'], 'Z', fJoyState.lZ); fLastAxis.lZ := fJoyState.lZ; end; //lRx RX if (fAxisTrigger.lRx > 0) and (Abs(fLastAxis.lRx - fJoyState.lRx) > fAxisTrigger.lRx) then begin DoAxisCall(fRegisteredProcs.Values['RX'], 'Rx', fJoyState.lRx); fLastAxis.lRx := fJoyState.lRx; end; //lRy RY if (fAxisTrigger.lRy > 0) and (Abs(fLastAxis.lRy - fJoyState.lRy) > fAxisTrigger.lRy) then begin DoAxisCall(fRegisteredProcs.Values['RY'], 'Ry', fJoyState.lRy); fLastAxis.lRy := fJoyState.lRy; end; //lRz RZ if (fAxisTrigger.lRz > 0) and (Abs(fLastAxis.lRz - fJoyState.lRz) > fAxisTrigger.lRz) then begin DoAxisCall(fRegisteredProcs.Values['RZ'], 'Rz', fJoyState.lRz); fLastAxis.lRz := fJoyState.lRz; end; //rglSlider[0] SLIDER1 if (fAxisTrigger.rglSlider[0] > 0) and (Abs(fLastAxis.rglSlider[0] - fJoyState.rglSlider[0]) > fAxisTrigger.rglSlider[0]) then begin DoAxisCall(fRegisteredProcs.Values['SLIDER1'], 'Slider1', fJoyState.rglSlider[0]); fLastAxis.rglSlider[0] := fJoyState.rglSlider[0]; end; //rglSlider[1] SLIDER2 if (fAxisTrigger.rglSlider[1] > 0) and (Abs(fLastAxis.rglSlider[1] - fJoyState.rglSlider[1]) > fAxisTrigger.rglSlider[1]) then begin DoAxisCall(fRegisteredProcs.Values['SLIDER2'], 'Slider2', fJoyState.rglSlider[1]); fLastAxis.rglSlider[1] := fJoyState.rglSlider[1]; end; //rgdwPOV[0] POV1 if (fAxisTrigger.rgdwPOV[0] > 0) and (Abs(fLastAxis.rgdwPOV[0] - fJoyState.rgdwPOV[0]) > fAxisTrigger.rgdwPOV[0]) then begin DoAxisCall(fRegisteredProcs.Values['POV1'], 'POV1', fJoyState.rgdwPOV[0]); fLastAxis.rgdwPOV[0] := fJoyState.rgdwPOV[0]; end; //rgdwPOV[1] POV2 if (fAxisTrigger.rgdwPOV[1] > 0) and (Abs(fLastAxis.rgdwPOV[1] - fJoyState.rgdwPOV[1]) > fAxisTrigger.rgdwPOV[1]) then begin DoAxisCall(fRegisteredProcs.Values['POV2'], 'POV2', fJoyState.rgdwPOV[1]); fLastAxis.rgdwPOV[1] := fJoyState.rgdwPOV[1]; end; //rgdwPOV[2] POV3 if (fAxisTrigger.rgdwPOV[2] > 0) and (Abs(fLastAxis.rgdwPOV[2] - fJoyState.rgdwPOV[2]) > fAxisTrigger.rgdwPOV[2]) then begin DoAxisCall(fRegisteredProcs.Values['POV3'], 'POV3', fJoyState.rgdwPOV[2]); fLastAxis.rgdwPOV[2] := fJoyState.rgdwPOV[2]; end; //rgdwPOV[3] POV4 if (fAxisTrigger.rgdwPOV[3] > 0) and (Abs(fLastAxis.rgdwPOV[3] - fJoyState.rgdwPOV[3]) > fAxisTrigger.rgdwPOV[3]) then begin DoAxisCall(fRegisteredProcs.Values['POV4'], 'POV4', fJoyState.rgdwPOV[3]); fLastAxis.rgdwPOV[3] := fJoyState.rgdwPOV[3]; end; //lVX VX if (fAxisTrigger.lVX > 0) and (Abs(fLastAxis.lVX - fJoyState.lVX) > fAxisTrigger.lVX) then begin DoAxisCall(fRegisteredProcs.Values['VX'], 'VX', fJoyState.lVX); fLastAxis.lVX := fJoyState.lVX; end; //lVY VY if (fAxisTrigger.lVY > 0) and (Abs(fLastAxis.lVY - fJoyState.lVY) > fAxisTrigger.lVY) then begin DoAxisCall(fRegisteredProcs.Values['VY'], 'VY', fJoyState.lVY); fLastAxis.lVY := fJoyState.lVY; end; //lVZ VZ if (fAxisTrigger.lVZ > 0) and (Abs(fLastAxis.lVZ - fJoyState.lVZ) > fAxisTrigger.lVZ) then begin DoAxisCall(fRegisteredProcs.Values['VZ'], 'VZ', fJoyState.lVZ); fLastAxis.lVZ := fJoyState.lVZ; end; //lVRx VRX if (fAxisTrigger.lVRx > 0) and (Abs(fLastAxis.lVRx - fJoyState.lVRx) > fAxisTrigger.lVRx) then begin DoAxisCall(fRegisteredProcs.Values['VRX'], 'VRx', fJoyState.lVRx); fLastAxis.lVRx := fJoyState.lVRx; end; //lVRy VRY if (fAxisTrigger.lVRy > 0) and (Abs(fLastAxis.lVRy - fJoyState.lVRy) > fAxisTrigger.lVRy) then begin DoAxisCall(fRegisteredProcs.Values['VRY'], 'VRy', fJoyState.lVRy); fLastAxis.lVRy := fJoyState.lVRy; end; //lVRZ VRZ if (fAxisTrigger.lVRZ > 0) and (Abs(fLastAxis.lVRZ - fJoyState.lVRZ) > fAxisTrigger.lVRZ) then begin DoAxisCall(fRegisteredProcs.Values['VRZ'], 'VRz', fJoyState.lVRZ); fLastAxis.lVRZ := fJoyState.lVRZ; end; //rglVSlider[0] VSLIDER1 if (fAxisTrigger.rglVSlider[0] > 0) and (Abs(fLastAxis.rglVSlider[0] - fJoyState.rglVSlider[0]) > fAxisTrigger.rglVSlider[0]) then begin DoAxisCall(fRegisteredProcs.Values['VSLIDER1'], 'VSlider1', fJoyState.rglVSlider[0]); fLastAxis.rglVSlider[0] := fJoyState.rglVSlider[0]; end; //rglVSlider[1] VSLIDER2 if (fAxisTrigger.rglVSlider[1] > 0) and (Abs(fLastAxis.rglVSlider[1] - fJoyState.rglVSlider[1]) > fAxisTrigger.rglVSlider[1]) then begin DoAxisCall(fRegisteredProcs.Values['VSLIDER2'], 'VSlider2', fJoyState.rglVSlider[1]); fLastAxis.rglVSlider[1] := fJoyState.rglVSlider[1]; end; //lAX AX if (fAxisTrigger.lAX > 0) and (Abs(fLastAxis.lAX - fJoyState.lAX) > fAxisTrigger.lAX) then begin DoAxisCall(fRegisteredProcs.Values['AX'], 'AX', fJoyState.lAX); fLastAxis.lAX := fJoyState.lAX; end; //lAY AY if (fAxisTrigger.lAY > 0) and (Abs(fLastAxis.lAY - fJoyState.lAY) > fAxisTrigger.lAY) then begin DoAxisCall(fRegisteredProcs.Values['AY'], 'AY', fJoyState.lAY); fLastAxis.lAY := fJoyState.lAY; end; //lAZ AZ if (fAxisTrigger.lAZ > 0) and (Abs(fLastAxis.lAZ - fJoyState.lAZ) > fAxisTrigger.lAZ) then begin DoAxisCall(fRegisteredProcs.Values['AZ'], 'AZ', fJoyState.lAZ); fLastAxis.lAZ := fJoyState.lAZ; end; //lARx ARX if (fAxisTrigger.lARx > 0) and (Abs(fLastAxis.lARx - fJoyState.lARx) > fAxisTrigger.lARx) then begin DoAxisCall(fRegisteredProcs.Values['ARX'], 'ARx', fJoyState.lARx); fLastAxis.lARx := fJoyState.lARx; end; //lARy ARY if (fAxisTrigger.lARy > 0) and (Abs(fLastAxis.lARy - fJoyState.lARy) > fAxisTrigger.lARy) then begin DoAxisCall(fRegisteredProcs.Values['ARY'], 'ARy', fJoyState.lARy); fLastAxis.lARy := fJoyState.lARy; end; //lARz ARZ if (fAxisTrigger.lARz > 0) and (Abs(fLastAxis.lARz - fJoyState.lARz) > fAxisTrigger.lARz) then begin DoAxisCall(fRegisteredProcs.Values['ARZ'], 'ARz', fJoyState.lARz); fLastAxis.lARz := fJoyState.lARz; end; //rglASlider[0] ASLIDER1 if (fAxisTrigger.rglASlider[0] > 0) and (Abs(fLastAxis.rglASlider[0] - fJoyState.rglASlider[0]) > fAxisTrigger.rglASlider[0]) then begin DoAxisCall(fRegisteredProcs.Values['ASLIDER1'], 'ASlider1', fJoyState.rglASlider[0]); fLastAxis.rglASlider[0] := fJoyState.rglASlider[0]; end; //rglASlider[1] ASLIDER2 if (fAxisTrigger.rglASlider[1] > 0) and (Abs(fLastAxis.rglASlider[1] - fJoyState.rglASlider[1]) > fAxisTrigger.rglASlider[1]) then begin DoAxisCall(fRegisteredProcs.Values['ASLIDER2'], 'ASlider2', fJoyState.rglASlider[1]); fLastAxis.rglASlider[1] := fJoyState.rglASlider[1]; end; //lFRx FRX if (fAxisTrigger.lFRx > 0) and (Abs(fLastAxis.lFRx - fJoyState.lFRx) > fAxisTrigger.lFRx) then begin DoAxisCall(fRegisteredProcs.Values['FRX'], 'FRx', fJoyState.lFRx); fLastAxis.lFRx := fJoyState.lFRx; end; //lFRy FRY if (fAxisTrigger.lFRy > 0) and (Abs(fLastAxis.lFRy - fJoyState.lFRy) > fAxisTrigger.lFRy) then begin DoAxisCall(fRegisteredProcs.Values['FRY'], 'FRy', fJoyState.lFRy); fLastAxis.lFRy := fJoyState.lFRy; end; //lFRz FRZ if (fAxisTrigger.lFRz > 0) and (Abs(fLastAxis.lFRz - fJoyState.lFRz) > fAxisTrigger.lFRz) then begin DoAxisCall(fRegisteredProcs.Values['FRZ'], 'FRz', fJoyState.lFRz); fLastAxis.lFRz := fJoyState.lFRz; end; // rglFSlider[0] FSLIDER1 if (fAxisTrigger.rglFSlider[0] > 0) and (Abs(fLastAxis.rglFSlider[0] - fJoyState.rglFSlider[0]) > fAxisTrigger.rglFSlider[0]) then begin DoAxisCall(fRegisteredProcs.Values['FSLIDER1'], 'FSlider1', fJoyState.rglFSlider[0]); fLastAxis.rglFSlider[0] := fJoyState.rglFSlider[0]; end; // rglFSlider[1] FSLIDER2 if (fAxisTrigger.rglFSlider[1] > 0) and (Abs(fLastAxis.rglFSlider[1] - fJoyState.rglFSlider[1]) > fAxisTrigger.rglFSlider[1]) then begin DoAxisCall(fRegisteredProcs.Values['FSLIDER2'], 'FSlider2', fJoyState.rglFSlider[1]); fLastAxis.rglFSlider[1] := fJoyState.rglFSlider[1]; end; end; end; end; function THIDJoystick.GetAxis(pName: String): LongInt; var lTrPtr: PLongInt; begin lTrPtr := GetAxisPointer(@fJoyState, pName); if lTrPtr = nil then Result := -99 else Result := lTrPtr^; end; function THIDJoystick.GetAxisPointer(pIn: PDIJoyState2; pAxisName: String): PLongInt; var lName : String; begin lName := UpperCase(pAxisName); if lName = 'X' then Result := @(pIn^.lX) else if lName = 'Y' then Result := @(pIn^.lY) else if lName = 'Z' then Result := @(pIn^.lZ) else if lName = 'RX' then Result := @(pIn^.lRx) else if lName = 'RY' then Result := @(pIn^.lRy) else if lName = 'RZ' then Result := @(pIn^.lRz) else if lName = 'SLIDER1' then Result := @(pIn^.rglSlider[0]) else if lName = 'SLIDER2' then Result := @(pIn^.rglSlider[1]) else if lName = 'POV1' then Result := @(pIn^.rgdwPOV[0]) else if lName = 'POV2' then Result := @(pIn^.rgdwPOV[1]) else if lName = 'POV3' then Result := @(pIn^.rgdwPOV[2]) else if lName = 'POV4' then Result := @(pIn^.rgdwPOV[3]) else if lName = 'VX' then Result := @(pIn^.lVX) else if lName = 'VY' then Result := @(pIn^.lVY) else if lName = 'VZ' then Result := @(pIn^.lVZ) else if lName = 'VRX' then Result := @(pIn^.lVRx) else if lName = 'VRY' then Result := @(pIn^.lVRy) else if lName = 'VRZ' then Result := @(pIn^.lVRZ) else if lName = 'VSLIDER1' then Result := @(pIn^.rglVSlider[0]) else if lName = 'VSLIDER2' then Result := @(pIn^.rglVSlider[1]) else if lName = 'AX' then Result := @(pIn^.lAX) else if lName = 'AY' then Result := @(pIn^.lAY) else if lName = 'AZ' then Result := @(pIn^.lAZ) else if lName = 'ARX' then Result := @(pIn^.lARx) else if lName = 'ARY' then Result := @(pIn^.lARy) else if lName = 'ARZ' then Result := @(pIn^.lARz) else if lName = 'ASLIDER1' then Result := @(pIn^.rglASlider[0]) else if lName = 'ASLIDER2' then Result := @(pIn^.rglASlider[1]) else if lName = 'FRX' then Result := @(pIn^.lFRx) else if lName = 'FRY' then Result := @(pIn^.lFRy) else if lName = 'FRZ' then Result := @(pIn^.lFRz) else if lName = 'FSLIDER1' then Result := @(pIn^.rglFSlider[0]) else if lName = 'FSLIDER2' then Result := @(pIn^.rglFSlider[1]) else Result := nil; end; function THIDJoystick.GetButton(pNumber: Integer): Shortint; begin Result := -1; if (pNumber > 0) and (pNumber <= fButtonsCount) then Result := fJoyState.rgbButtons[pNumber-1]; end; procedure THIDJoystick.GetButtons; var I: Integer; hr: HRESULT; begin if (Glb = nil) or (not Glb.HIDControl.GameAvailable) then exit; hr := fDIDevice.Poll; if (FAILED(hr)) then begin hr := fDIDevice.Acquire; if FAILED(hr) then begin //DIERR_INPUTLOST //DebugLog('Warning: Can''t acquire joy ' + joy.Name); //continue; exit; end; end; hr := fDIDevice.GetDeviceState(SizeOf(DIJOYSTATE2), @fJoyState); if FAILED(hr) then exit; end; procedure THIDJoystick.RegisterAxisEvent(pAxis, pProcName: String; pDelta: Integer); var lName: String; lTrPtr: PLongInt; lIndex : Integer; begin lName := UpperCase(pAxis); lTrPtr := GetAxisPointer(@fAxisTrigger, lName); if (lTrPtr <> nil) and (pDelta > 0) then begin lTrPtr^ := pDelta; lIndex := fRegisteredProcs.IndexOfName(lName); if lIndex >= 0 then fRegisteredProcs.Delete(lIndex); fRegisteredProcs.Values[lName] := pProcName; Glb.DebugLog(Format('Registered handler for dev %s axis %s proc %s.', [Name, lName, pProcName]), 'GAME'); //Glb.GameControl.DebugLog('Trigger is ' + IntToStr( end; end; procedure THIDJoystick.UnRegisterAxisEvent(pAxis: String); var lName: String; lIndex : Integer; begin lName := UpperCase(pAxis); lIndex := fRegisteredProcs.IndexOfName(lName); if lIndex >= 0 then begin fRegisteredProcs.Delete(lIndex); Glb.DebugLog(Format('Handler for dev %s axis %s unregistered.', [Name, lName]), 'GAME'); end; end; { TGameControl } procedure TGameControl.AddGameDevice(pDeviceName: String; Data: IDIRECTINPUTDEVICE8; pGUID: TGUID); var caps: DIDEVCAPS; newJoy: THIDJoystick; hr: HRESULT; I, newIndex : Integer; NameOK: Boolean; begin caps.dwSize := SizeOf(DIDEVCAPS); hr := Data.GetCapabilities(caps); if FAILED(hr) then exit; // add string to log DebugLog('Found game device: ' + pDeviceName + ', no of buttons: ' + IntToStr(caps.dwButtons)); // create kbd object newJoy := THIDJoystick.Create(GUID2Str(pGUID), 1); // faked handle, but show this is real device //newJoy.Name := 'Game'+IntToStr(GameDevCounter+1); newJoy.Name := pDeviceName; newJoy.ButtonsCount := caps.dwButtons; newJoy.DIDevice := Data; fDevices.Add(newJoy); if Assigned(fOnNewDevice) then fOnNewDevice(newJoy); end; function TGameControl.GetAvailable: Boolean; begin Result := DInput <> nil; end; function TGameControl.GetDevice(pName: String): THIDJoystick; var I: Integer; begin Result := nil; for I := 0 to fDevices.Count - 1 do if UpperCase(THIDJoystick(fDevices[I]).Name) = UpperCase(pName) then begin Result := THIDJoystick(fDevices[I]); break; end; end; function TGameControl.GUID2Str(pGUID: TGUID): String; var I: Integer; begin Result := IntToHex(pGUID.D1, 8); Result := Result + ':' + IntToHex(pGUID.D2, 4); Result := Result + ':' + IntToHex(pGUID.D3, 4) + ':'; for I := Low(pGUID.D4) to High(pGUID.D4) do Result := Result + IntToHex(pGUID.D4[I], 2); end; constructor TGameControl.Create; begin fDevices := TList.Create; end; procedure TGameControl.DebugLog(Value: String); begin Glb.DebugLog(Value, 'GAME'); end; destructor TGameControl.Destroy; begin fDevices.Free; // are destroyed from form if DInput <> nil then DInput._Release; inherited; end; procedure TGameControl.InitDirectX; var hr: HRESULT; begin fDevices.Clear; DInput := nil; hr := DirectInput8Create(GetModuleHandle(nil),DIRECTINPUT_VERSION,IID_IDirectInput8,DInput,nil); if (FAILED(hr)) then begin DebugLog('Can not init Direct input. Error ' + IntToHex(hr, 8)); exit; end; if (DInput = nil) then begin DebugLog('Direct input initialization error'); exit; end; DInput.EnumDevices(DI8DEVCLASS_GAMECTRL, @EnumJoysticksCallback, self, DIEDFL_ATTACHEDONLY); end; end.
unit WiseDaq; interface uses Windows, Classes, SysUtils, cbw, Contnrs, WiseHardware; type TDaqId = word; // (Dir << 8 | ((Board << 6) | port)) = 9bits type TBoardInfo = record model: PChar; num: integer; ndaqs: integer; bitsPerDaq: array of integer; end; type PTBoardInfo = ^TBoardInfo; type TDaqPortNumbers = set of FIRSTPORTA .. EIGHTHPORTCH; type PTDaqPortNumbers = ^TDaqPortNumbers; type TWiseDaq = class(TWiseObject) private fDir: Integer; // The port direction Mask: Byte; fValue: word; // Remembered by software fId: TDaqId; fNbits: integer; refcount: integer; public Board: Integer; // The Daq board number Port: Integer; // The port number on the Daq board constructor Create(name: string; board: integer; port: integer; dir: integer; mask: integer); overload; constructor Create(name: string; did: TDaqId; mask: integer); overload; constructor Create(name: string; did: TDaqId); overload; destructor Destroy(); override; function GetValue(): word; procedure SetValue(val: word); procedure IncRef(); procedure DecRef(); function GetKey(): integer; procedure _Create(name: string; board: integer; port: integer; dir: integer; mask: integer); property Id: TDaqId read fId write fId; property Value: word read GetValue write SetValue; property Nbits: integer read fNbits write fNbits; property Dir: integer read fDir write fDir; property Key: integer read GetKey; end; var WiseBoards: array of TBoardInfo; NullString: array [0..BOARDNAMELEN] of Char; WiseDaqPortNames: array [AUXPORT .. EIGHTHPORTCH] of string; domeboard: integer; teleboard: integer; focusboard: integer; WiseDaqsInfoInitialized: boolean; function InitDaqsInfo(): string; function lookupDaq(board: integer; port: integer; direction: integer): TWiseDaq; overload; function lookupDaq(did: TDaqId): TWiseDaq; overload; function daqId(board: integer; port: integer; direction: integer): TDaqId; overload; function daqId(board: integer; port: integer): TDaqId; overload; procedure reverseDaqId(daqid: TDaqId; out board: integer; out port: integer; out dir: integer); implementation var DaqsInUse: TObjectBucketList; function daqId(board: integer; port: integer; direction: integer): TDaqId; overload; var r: integer; begin r := (board SHL 6) OR port; if direction = DIGITALIN then r := r OR (1 SHL 8) else r := r OR (0 SHL 8); Result := r; end; function daqId(board: integer; port: integer): TDaqId; overload; var r: integer; begin r := (board SHL 6) OR port; Result := r; end; procedure reverseDaqId(daqid: TDaqId; out board: integer; out port: integer; out dir: integer); begin if (daqid AND (1 SHL 8) <> 0) then dir := DIGITALIN else dir := DIGITALOUT; board := (daqid SHR 6) AND $3; port := daqid AND $3f; end; function TWiseDaq.GetKey(): integer; begin Result := (Self.Board SHL 6) OR Self.Port; end; procedure TWiseDaq._Create(name: string; board: integer; port: integer; dir: integer; mask: integer); var key, stat: integer; begin key := daqId(board, port); if DaqsInUse.Exists(Pointer(key)) then raise EWiseError.CreateFmt('[%s]: %s: Daq for Board #%d.%s already created, only one can exist!', ['TWiseDaq._Create', name, board, WiseDaqPortNames[port]]); stat := cbDConfigPort(board, port, dir); if (stat <> 0) then raise EWisePortError.CreateFmt('%s: Cannot cbDConfigPort "%s" on board %d for %s', [name, WiseDaqPortNames[Self.Port], board, DirNames[dir]]); Self.Name := name; Self.Board := board; Self.Port := port; Self.Dir := dir; Self.Mask := mask; Self.Value := 0; Self.Id := daqId(board, port, dir); Self.Nbits := WiseBoards[board].bitsPerDaq[port - FIRSTPORTA]; Self.refcount := 0; DaqsInUse.Add(Pointer(Self.Key), Self); end; constructor TWiseDaq.Create(name: string; board: integer; port: integer; dir: integer; mask: integer); begin _Create(name, board, port, dir, mask); end; constructor TWiseDaq.Create(name: string; did: TDaqId; mask: integer); var board, port, dir: integer; begin reverseDaqId(did, board, port, dir); _Create(name, board, port, dir, mask); end; constructor TWiseDaq.Create(name: string; did: TDaqId); var board, port, dir, mask: integer; begin reverseDaqId(did, board, port, dir); mask := $ff; if WiseBoards[board].bitsPerDaq[port - FIRSTPORTA] = 4 then mask := $f; _Create(name, board, port, dir, mask); end; destructor TWiseDaq.Destroy(); begin DaqsInUse.Remove(Pointer(Self.Key)); inherited Destroy; end; function lookupDaq(board: integer; port: integer; direction: integer): TWiseDaq; overload var key: TDaqId; daq: TWiseDaq; begin key := daqId(board, port); if DaqsInUse.Find(Pointer(key), Pointer(daq)) then Result := daq else Result := nil; end; function lookupDaq(did: TDaqId): TWiseDaq; overload var x, key, b, p, d: integer; begin reverseDaqId(did, b, p, d); key := daqId(b, p); if DaqsInUse.Find(Pointer(key), Pointer(x)) then Result := TWiseDaq(x) else Result := nil; end; function TWiseDaq.GetValue(): word; var tries, stat: integer; val: word; begin for tries := MaxTries downto 0 do begin stat := cbDIn(Self.Board, Self.Port, val); if (stat = 0) then begin Self.fValue := val AND Self.Mask; Result := Self.fValue; exit; end; end; raise EWisePortError.CreateFmt('[%s]: %s: Cannot read "%s" on board %d after %d tries.', ['TWiseDaq.GetVal', Self.Name, WiseDaqPortNames[Self.Port], Self.Board, MaxTries]); end; procedure TWiseDaq.SetValue(val: word); var stat, tries: Integer; begin val := val AND Self.Mask; Self.fValue := val; if (Self.Dir = DIGITALIN) then exit; for tries := MaxTries downto 0 do begin stat := cbDOut(Self.Board, Self.Port, val); if (stat = 0) then exit; end; raise EWisePortError.CreateFmt('[%s]: %s: Cannot cbDout(%d, "%s", %x) => %d (after %d tries).', ['TWiseDaq.SetVal', Self.Name, Self.Board, WiseDaqPortNames[Self.Port], val, stat, MaxTries]); end; procedure TWiseDaq.IncRef; begin Self.refcount := Self.refcount + 1; end; procedure TWiseDaq.DecRef; begin if (Self.refcount = 1) then begin DaqsInUse.Remove(Pointer(Self.Id)); Destroy; exit; end; Self.refcount := Self.refcount - 1; end; function InitDaqsInfo(): string; var nboards, boardno: integer; daqno: integer; val: integer; begin { Get the number of boards installed in system } nboards := 0; cbGetConfig (GLOBALINFO, 0, 0, GINUMBOARDS, nboards); if (nboards = 0) then begin Result := Format('Could not find any MCC boards!', []); exit; end; Result := ''; SetLength(WiseBoards, nboards); for boardno := 0 to nboards do begin cbGetConfig (BOARDINFO, boardno, 0, BIBOARDTYPE, val); if (val <= 0) then continue; WiseBoards[boardno].num := boardno; WiseBoards[boardno].model := NullString; cbGetBoardName(boardno, WiseBoards[boardno].model); {get the number of digital devices for this board } cbGetConfig (BOARDINFO, boardno, 0, BIDINUMDEVS, WiseBoards[boardno].ndaqs); SetLength(WiseBoards[boardno].bitsPerDaq, WiseBoards[boardno].ndaqs); for daqno := 0 to WiseBoards[boardno].ndaqs - 1 do begin {For each digital device, get the base address and number of bits } cbGetConfig (DIGITALINFO, boardno, daqno, DINUMBITS, val); WiseBoards[boardno].bitsPerDaq[daqno] := val; end; end; WiseDaqsInfoInitialized := true; if production then begin focusboard := 2; teleboard := 1; domeboard := 0; end else begin focusboard := 0; teleboard := 0; domeboard := 0; end; end; initialization WiseDaqPortNames[AUXPORT] := 'AUXPORT'; WiseDaqPortNames[FIRSTPORTA] := 'FIRSTPORTA'; WiseDaqPortNames[FIRSTPORTB] := 'FIRSTPORTB'; WiseDaqPortNames[FIRSTPORTCL] := 'FIRSTPORTCL'; WiseDaqPortNames[FIRSTPORTCH] := 'FIRSTPORTCH'; WiseDaqPortNames[SECONDPORTA] := 'SECONDPORTA'; WiseDaqPortNames[SECONDPORTB] := 'SECONDPORTB'; WiseDaqPortNames[SECONDPORTCL] := 'SECONDPORTCL'; WiseDaqPortNames[SECONDPORTCH] := 'SECONDPORTCH'; WiseDaqPortNames[THIRDPORTA] := 'THIRDPORTA'; WiseDaqPortNames[THIRDPORTB] := 'THIRDPORTB'; WiseDaqPortNames[THIRDPORTCL] := 'THIRDPORTCL'; WiseDaqPortNames[THIRDPORTCH] := 'THIRDPORTCH'; WiseDaqPortNames[FOURTHPORTA] := 'FOURTHPORTA'; WiseDaqPortNames[FOURTHPORTB] := 'FOURTHPORTB'; WiseDaqPortNames[FOURTHPORTCL] := 'FOURTHPORTCL'; WiseDaqPortNames[FOURTHPORTCH] := 'FOURTHPORTCH'; WiseDaqPortNames[FIFTHPORTA] := 'FIFTHPORTA'; WiseDaqPortNames[FIFTHPORTB] := 'FIFTHPORTB'; WiseDaqPortNames[FIFTHPORTCL] := 'FIFTHPORTCL'; WiseDaqPortNames[FIFTHPORTCH] := 'FIFTHPORTCH'; WiseDaqPortNames[SIXTHPORTA] := 'SIXTHPORTA'; WiseDaqPortNames[SIXTHPORTB] := 'SIXTHPORTB'; WiseDaqPortNames[SIXTHPORTCL] := 'SIXTHPORTCL'; WiseDaqPortNames[SIXTHPORTCH] := 'SIXTHPORTCH'; WiseDaqPortNames[SEVENTHPORTA] := 'SEVENTHPORTA'; WiseDaqPortNames[SEVENTHPORTB] := 'SEVENTHPORTB'; WiseDaqPortNames[SEVENTHPORTCL] := 'SEVENTHPORTCL'; WiseDaqPortNames[SEVENTHPORTCH] := 'SEVENTHPORTCH'; WiseDaqPortNames[EIGHTHPORTA] := 'EIGHTHPORTA'; WiseDaqPortNames[EIGHTHPORTB] := 'EIGHTHPORTB'; WiseDaqPortNames[EIGHTHPORTCL] := 'EIGHTHPORTCL'; WiseDaqPortNames[EIGHTHPORTCH] := 'EIGHTHPORTCH'; DaqsInUse := TObjectBucketList.Create(bl128); WiseDaqsInfoInitialized := false; end.
{** Douglas Colombo * Classe de conversão de arquivos em texto * e de Texto em Arquivos, BASE64 **} unit UBase64; {$MODE Delphi} interface uses Classes, {$IfNDef FPC} jpeg, Winapi.Windows, Vcl.Graphics, System.netEncoding, System.SysUtils, FMX.Graphics {$else} sysutils, graphics, Base64 {$EndIf}; //Type // tBase64 = class //public procedure Base64ToFile(Arquivo, caminhoSalvar : String); function Base64ToStream(imagem : String) : TMemoryStream; //function Base64ToBitmap(imagem : String) : TBitmap; function BitmapToBase64(imagem : TBitmap) : String; function FileToBase64(Arquivo : String) : String; function StreamToBase64(STream : TMemoryStream) : String; //end; implementation //{ tBase64 } //function tBase64.Base64ToBitmap(imagem: String): TBitmap; //Var sTream : TMemoryStream; //begin // if (trim(imagem) <> '') then // begin // Try // sTream := Base64ToStream(imagem); // result := TBitmap.CreateFromStream(sTream); // Finally // sTream.DisposeOf; // sTream := nil; // End; // end else // exit; //end; procedure Base64ToFile(Arquivo, caminhoSalvar : String); Var sTream : TMemoryStream; begin Try sTream := Base64ToStream(Arquivo); sTream.SaveToFile(caminhoSalvar); Finally sTream.free; sTream:=nil; End; end; function Base64ToStream(imagem: String): TMemoryStream; var {$IFNDEF FPC} Base64 : TBase64Encoding; {$ELSE} Base64 : TBase64DecodingStream; VSrcStream: TStringStream; {$ENDIF} bytes : tBytes; begin {$IFDEF FPC} VSrcStream := TStringStream.Create(imagem); {$ENDIF} Try {$IFNDEF FPC} Base64 := TBase64Encoding.Create; bytes := Base64.DecodeStringToBytes(imagem); result := TBytesStream.Create(bytes); {$ELSE} Base64:= TBase64DecodingStream.Create(VSrcStream,bdmMIME); result.CopyFrom(Base64, Base64.Size); {$ENDIF} result.Seek(0, 0); Finally Base64.Free; Base64:=nil; SetLength(bytes, 0); End; end; function BitmapToBase64(imagem: TBitmap): String; Var sTream : TMemoryStream; vEmpty : Boolean; begin result := ''; {$ifndef fpc} vEmpty:= imagem.isEmpty; {$else} vEmpty:= imagem.Empty; {$endif} if not vEmpty then begin Try sTream := TMemoryStream.Create; imagem.SaveToStream(sTream); result := StreamToBase64(sTream); {$ifndef fpc} sTream.DisposeOf; {$else} sTream.Clear; {$endif} sTream := nil; Except End; end; end; function FileToBase64(Arquivo : String): String; Var sTream : tMemoryStream; begin sTream := TMemoryStream.Create; Try sTream.LoadFromFile(Arquivo); result := StreamToBase64(sTream); Finally Stream.Free; Stream:=nil; End; end; function StreamToBase64(STream: TMemoryStream): String; Var {$IFNDEF FPC} Base64 : TBase64Encoding; {$else} Base64 : TBase64EncodingStream; VDestStream: TStringStream; {$endif} begin {$IFDEF FPC} VDestStream := TStringStream.Create(''); {$ENDIF} Try Stream.Seek(0, 0); {$IFNDEF FPC} Base64 := TBase64Encoding.Create; Result := Base64.EncodeBytesToString(sTream.Memory, sTream.Size); {$else} Base64 := TBase64EncodingStream.Create(VDestStream); Base64.CopyFrom(STream, STream.Size); Result := VDestStream.DataString; {$endif} Finally Base64.Free; Base64:=nil; {$IFDEF FPC} VDestStream.free; VDestStream:= nil; {$endif} End; end; end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { Master/Detail Field Links Editor } { } { Copyright (c) 1997-2001 Borland Software Corporation } { } {*******************************************************} unit FldLinks; interface uses SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, StdCtrls, ExtCtrls, DB, Buttons, DesignIntf, DesignEditors; type { TFieldLink } TFieldLinkProperty = class(TStringProperty) private FChanged: Boolean; FDataSet: TDataSet; protected function GetDataSet: TDataSet; procedure GetFieldNamesForIndex(List: TStrings); virtual; function GetIndexBased: Boolean; virtual; function GetIndexDefs: TIndexDefs; virtual; function GetIndexFieldNames: string; virtual; function GetIndexName: string; virtual; function GetMasterFields: string; virtual; abstract; procedure SetIndexFieldNames(const Value: string); virtual; procedure SetIndexName(const Value: string); virtual; procedure SetMasterFields(const Value: string); virtual; abstract; public constructor CreateWith(ADataSet: TDataSet); virtual; procedure GetIndexNames(List: TStrings); property IndexBased: Boolean read GetIndexBased; property IndexDefs: TIndexDefs read GetIndexDefs; property IndexFieldNames: string read GetIndexFieldNames write SetIndexFieldNames; property IndexName: string read GetIndexName write SetIndexName; property MasterFields: string read GetMasterFields write SetMasterFields; property Changed: Boolean read FChanged; procedure Edit; override; function GetAttributes: TPropertyAttributes; override; property DataSet: TDataSet read GetDataSet; end; { TLink Fields } TLinkFields = class(TForm) DetailList: TListBox; MasterList: TListBox; BindList: TListBox; Label30: TLabel; Label31: TLabel; IndexList: TComboBox; IndexLabel: TLabel; Label2: TLabel; Bevel1: TBevel; Bevel2: TBevel; AddButton: TButton; DeleteButton: TButton; ClearButton: TButton; Button1: TButton; Button2: TButton; Help: TButton; procedure FormCreate(Sender: TObject); procedure BindingListClick(Sender: TObject); procedure AddButtonClick(Sender: TObject); procedure DeleteButtonClick(Sender: TObject); procedure BindListClick(Sender: TObject); procedure ClearButtonClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure BitBtn1Click(Sender: TObject); procedure HelpClick(Sender: TObject); procedure IndexListChange(Sender: TObject); private FDataSet: TDataSet; FMasterDataSet: TDataSet; FDataSetProxy: TFieldLinkProperty; FFullIndexName: string; MasterFieldList: string; IndexFieldList: string; OrderedDetailList: TStringList; OrderedMasterList: TStringList; procedure OrderFieldList(OrderedList, List: TStrings); procedure AddToBindList(const Str1, Str2: string); procedure Initialize; property FullIndexName: string read FFullIndexName; procedure SetDataSet(Value: TDataSet); public property DataSet: TDataSet read FDataSet write SetDataSet; property DataSetProxy: TFieldLinkProperty read FDataSetProxy write FDataSetProxy; function Edit: Boolean; end; function EditMasterFields(ADataSet: TDataSet; ADataSetProxy: TFieldLinkProperty): Boolean; implementation {$R *.dfm} {$IFDEF MSWINDOWS} uses Dialogs, DBConsts, LibHelp, TypInfo, DsnDBCst; {$ENDIF} {$IFDEF LINUX} uses QDialogs, DBConsts, LibHelp, TypInfo, DsnDBCst; {$ENDIF} { Utility Functions } function StripFieldName(const Fields: string; var Pos: Integer): string; var I: Integer; begin I := Pos; while (I <= Length(Fields)) and (Fields[I] <> ';') do Inc(I); Result := Copy(Fields, Pos, I - Pos); if (I <= Length(Fields)) and (Fields[I] = ';') then Inc(I); Pos := I; end; function StripDetail(const Value: string): string; var S: string; I: Integer; begin S := Value; I := 0; while Pos('->', S) > 0 do begin I := Pos('->', S); S[I] := ' '; end; Result := Copy(Value, 0, I - 2); end; function StripMaster(const Value: string): string; var S: string; I: Integer; begin S := Value; I := 0; while Pos('->', S) > 0 do begin I := Pos('->', S); S[I] := ' '; end; Result := Copy(Value, I + 3, Length(Value)); end; function EditMasterFields(ADataSet: TDataSet; ADataSetProxy: TFieldLinkProperty): Boolean; begin with TLinkFields.Create(nil) do try DataSetProxy := ADataSetProxy; DataSet := ADataSet; Result := Edit; finally Free; end; end; { TFieldLinkProperty } function TFieldLinkProperty.GetIndexBased: Boolean; begin Result := False; end; function TFieldLinkProperty.GetIndexDefs: TIndexDefs; begin Result := nil; end; function TFieldLinkProperty.GetIndexFieldNames: string; begin Result := ''; end; function TFieldLinkProperty.GetIndexName: string; begin Result := ''; end; procedure TFieldLinkProperty.GetIndexNames(List: TStrings); var i: Integer; begin if IndexDefs <> nil then for i := 0 to IndexDefs.Count - 1 do if (ixPrimary in IndexDefs.Items[i].Options) and (IndexDefs.Items[i].Name = '') then List.Add(SPrimary) else List.Add(IndexDefs.Items[i].Name); end; procedure TFieldLinkProperty.GetFieldNamesForIndex(List: TStrings); begin end; procedure TFieldLinkProperty.SetIndexFieldNames(const Value: string); begin end; procedure TFieldLinkProperty.SetIndexName(const Value: string); begin end; function TFieldLinkProperty.GetAttributes: TPropertyAttributes; begin Result := [paDialog]; {$IFDEF LINUX} Result := Result + [paVCL] {$ENDIF} end; procedure TFieldLinkProperty.Edit; begin FChanged := EditMasterFields(DataSet, Self); if FChanged then Modified; end; constructor TFieldLinkProperty.CreateWith(ADataSet: TDataSet); begin FDataSet := ADataSet; end; function TFieldLinkProperty.GetDataSet: TDataSet; begin if FDataSet = nil then FDataSet := TDataSet(GetComponent(0)); Result := FDataSet; end; { TLinkFields } procedure TLinkFields.FormCreate(Sender: TObject); begin OrderedDetailList := TStringList.Create; OrderedMasterList := TStringList.Create; HelpContext := hcDFieldLinksDesign; end; procedure TLinkFields.FormDestroy(Sender: TObject); begin OrderedDetailList.Free; OrderedMasterList.Free; end; function TLinkFields.Edit; begin Initialize; if ShowModal = mrOK then begin if FullIndexName <> '' then DataSetProxy.IndexName := FullIndexName else DataSetProxy.IndexFieldNames := IndexFieldList; DataSetProxy.MasterFields := MasterFieldList; Result := True; end else Result := False; end; procedure TLinkFields.SetDataSet(Value: TDataSet); var IndexDefs: TIndexDefs; begin Value.FieldDefs.Update; IndexDefs := DataSetProxy.IndexDefs; if Assigned(IndexDefs) then IndexDefs.Update; if not Assigned(Value.DataSource) or not Assigned(Value.DataSource.DataSet) then DatabaseError(SMissingDataSource, Value); Value.DataSource.DataSet.FieldDefs.Update; FDataSet := Value; FMasterDataSet := Value.DataSource.DataSet; end; procedure TLinkFields.Initialize; var SIndexName: string; procedure SetUpLists(const MasterFieldList, DetailFieldList: string); var I, J: Integer; MasterFieldName, DetailFieldName: string; begin I := 1; J := 1; while (I <= Length(MasterFieldList)) and (J <= Length(DetailFieldList)) do begin MasterFieldName := StripFieldName(MasterFieldList, I); DetailFieldName := StripFieldName(DetailFieldList, J); if (MasterList.Items.IndexOf(MasterFieldName) <> -1) and (OrderedDetailList.IndexOf(DetailFieldName) <> -1) then begin with OrderedDetailList do Objects[IndexOf(DetailFieldName)] := TObject(True); with DetailList.Items do Delete(IndexOf(DetailFieldName)); with MasterList.Items do Delete(IndexOf(MasterFieldName)); BindList.Items.Add(Format('%s -> %s', [DetailFieldName, MasterFieldName])); ClearButton.Enabled := True; end; end; end; begin if not DataSetProxy.IndexBased then begin IndexLabel.Visible := False; IndexList.Visible := False; end else with DataSetProxy do begin GetIndexNames(IndexList.Items); if IndexFieldNames <> '' then SIndexName := IndexDefs.FindIndexForFields(IndexFieldNames).Name else SIndexName := IndexName; if (SIndexName <> '') and (IndexList.Items.IndexOf(SIndexName) >= 0) then IndexList.ItemIndex := IndexList.Items.IndexOf(SIndexName) else IndexList.ItemIndex := 0; end; with DataSetProxy do begin MasterFieldList := MasterFields; if (IndexFieldNames = '') and (IndexName <> '') and (IndexDefs.IndexOf(IndexName) >=0) then IndexFieldList := IndexDefs[IndexDefs.IndexOf(IndexName)].Fields else IndexFieldList := IndexFieldNames; end; IndexListChange(nil); FMasterDataSet.GetFieldNames(MasterList.Items); OrderedMasterList.Assign(MasterList.Items); SetUpLists(MasterFieldList, IndexFieldList); end; procedure TLinkFields.IndexListChange(Sender: TObject); var I: Integer; IndexExp: string; begin DetailList.Items.Clear; if DataSetProxy.IndexBased then begin DataSetProxy.IndexName := IndexList.Text; I := DataSetProxy.IndexDefs.IndexOf(DataSetProxy.IndexName); if (I <> -1) then IndexExp := DataSetProxy.IndexDefs.Items[I].Expression; if IndexExp <> '' then DetailList.Items.Add(IndexExp) else DataSetProxy.GetFieldNamesForIndex(DetailList.Items); end else DataSet.GetFieldNames(DetailList.Items); MasterList.Items.Assign(OrderedMasterList); OrderedDetailList.Assign(DetailList.Items); for I := 0 to OrderedDetailList.Count - 1 do OrderedDetailList.Objects[I] := TObject(False); BindList.Clear; AddButton.Enabled := False; ClearButton.Enabled := False; DeleteButton.Enabled := False; MasterList.ItemIndex := -1; end; procedure TLinkFields.OrderFieldList(OrderedList, List: TStrings); var I, J: Integer; MinIndex, Index, FieldIndex: Integer; begin for J := 0 to List.Count - 1 do begin MinIndex := $7FFF; FieldIndex := -1; for I := J to List.Count - 1 do begin Index := OrderedList.IndexOf(List[I]); if Index < MinIndex then begin MinIndex := Index; FieldIndex := I; end; end; List.Move(FieldIndex, J); end; end; procedure TLinkFields.AddToBindList(const Str1, Str2: string); var I: Integer; NewField: string; NewIndex: Integer; begin NewIndex := OrderedDetailList.IndexOf(Str1); NewField := Format('%s -> %s', [Str1, Str2]); with BindList.Items do begin for I := 0 to Count - 1 do begin if OrderedDetailList.IndexOf(StripDetail(Strings[I])) > NewIndex then begin Insert(I, NewField); Exit; end; end; Add(NewField); end; end; procedure TLinkFields.BindingListClick(Sender: TObject); begin AddButton.Enabled := (DetailList.ItemIndex <> LB_ERR) and (MasterList.ItemIndex <> LB_ERR); end; procedure TLinkFields.AddButtonClick(Sender: TObject); var DetailIndex: Integer; MasterIndex: Integer; begin DetailIndex := DetailList.ItemIndex; MasterIndex := MasterList.ItemIndex; AddToBindList(DetailList.Items[DetailIndex], MasterList.Items[MasterIndex]); with OrderedDetailList do Objects[IndexOf(DetailList.Items[DetailIndex])] := TObject(True); DetailList.Items.Delete(DetailIndex); MasterList.Items.Delete(MasterIndex); ClearButton.Enabled := True; AddButton.Enabled := False; end; procedure TLinkFields.ClearButtonClick(Sender: TObject); var I: Integer; BindValue: string; begin for I := 0 to BindList.Items.Count - 1 do begin BindValue := BindList.Items[I]; DetailList.Items.Add(StripDetail(BindValue)); MasterList.Items.Add(StripMaster(BindValue)); end; BindList.Clear; ClearButton.Enabled := False; DeleteButton.Enabled := False; OrderFieldList(OrderedDetailList, DetailList.Items); DetailList.ItemIndex := -1; MasterList.Items.Assign(OrderedMasterList); for I := 0 to OrderedDetailList.Count - 1 do OrderedDetailList.Objects[I] := TObject(False); AddButton.Enabled := False; end; procedure TLinkFields.DeleteButtonClick(Sender: TObject); var I: Integer; begin with BindList do begin for I := Items.Count - 1 downto 0 do begin if Selected[I] then begin DetailList.Items.Add(StripDetail(Items[I])); MasterList.Items.Add(StripMaster(Items[I])); with OrderedDetailList do Objects[IndexOf(StripDetail(Items[I]))] := TObject(False); Items.Delete(I); end; end; if Items.Count > 0 then Selected[0] := True; DeleteButton.Enabled := Items.Count > 0; ClearButton.Enabled := Items.Count > 0; OrderFieldList(OrderedDetailList, DetailList.Items); DetailList.ItemIndex := -1; OrderFieldList(OrderedMasterList, MasterList.Items); MasterList.ItemIndex := -1; AddButton.Enabled := False; end; end; procedure TLinkFields.BindListClick(Sender: TObject); begin DeleteButton.Enabled := BindList.ItemIndex <> LB_ERR; end; procedure TLinkFields.BitBtn1Click(Sender: TObject); var Gap: Boolean; I: Integer; FirstIndex: Integer; begin FirstIndex := -1; MasterFieldList := ''; IndexFieldList := ''; FFullIndexName := ''; if DataSetProxy.IndexBased then begin Gap := False; for I := 0 to OrderedDetailList.Count - 1 do begin if Boolean(OrderedDetailList.Objects[I]) then begin if Gap then begin MessageDlg(Format(SLinkDesigner, [OrderedDetailList[FirstIndex]]), mtError, [mbOK], 0); ModalResult := 0; DetailList.ItemIndex := DetailList.Items.IndexOf(OrderedDetailList[FirstIndex]); Exit; end; end else begin Gap := True; if FirstIndex = -1 then FirstIndex := I; end; end; if not Gap then FFullIndexName := DataSetProxy.IndexName; end; with BindList do begin for I := 0 to Items.Count - 1 do begin MasterFieldList := Format('%s%s;', [MasterFieldList, StripMaster(Items[I])]); IndexFieldList := Format('%s%s;', [IndexFieldList, StripDetail(Items[I])]); end; if MasterFieldList <> '' then SetLength(MasterFieldList, Length(MasterFieldList) - 1); if IndexFieldList <> '' then SetLength(IndexFieldList, Length(IndexFieldList) - 1); end; end; procedure TLinkFields.HelpClick(Sender: TObject); begin Application.HelpContext(HelpContext); end; end.
{********************************************************************* * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Autor: Brovin Y.D. * E-mail: y.brovin@gmail.com * ********************************************************************} unit FGX.ComponentReg; interface resourcestring rsCategoryExtended = 'FGX: Extended FM Controls'; rsAnimations = 'FGX: Animations'; rsStyleObjects = 'FGX: Style objects'; procedure Register; implementation uses System.Classes, DesignIntf, FMX.Graphics, FMX.Styles.Objects, FMX.Styles.Switch, FGX.ActionSheet, FGX.VirtualKeyboard, FGX.ProgressDialog, FGX.GradientEdit, FGX.BitBtn, FGX.Toolbar, FGX.ColorsPanel, FGX.LinkedLabel, FGX.FlipView, FGX.ApplicationEvents, FGX.Animations, FGX.Items, FGX.Consts, FGX.Editor.Items, FMX.Styles; procedure Register; begin { Components Registration } RegisterComponents(rsCategoryExtended, [ TfgActionSheet, TfgActivityDialog, TfgApplicationEvents, TfgBitBtn, TfgColorsPanel, TfgFlipView, TfgGradientEdit, TfgLinkedLabel, TfgProgressDialog, TfgToolBar, TfgVirtualKeyboard ]); RegisterComponents(rsAnimations, [ TfgPositionAnimation, TfgPosition3DAnimation, TfgBitmapLinkAnimation ]); RegisterComponents(rsStyleObjects, [TStyleObject, TSubImage, TActiveStyleObject, TTabStyleObject, TCheckStyleObject, TButtonStyleObject, TSystemButtonObject, TStyleTextObject, TStyleTextAnimation, TActiveStyleTextObject, TTabStyleTextObject, TButtonStyleTextObject, TActiveOpacityObject, TBrushObject, TBitmapObject, TFontObject, TPathObject, TColorObject, TStyleTag, // New XE6 objects TTintedButtonStyleObject, TTintedStyleObject, TMaskedImage, TActiveMaskedImage, TSwitchTextObject, TCustomSwitchObject, TSwitchObject, TBitmapSwitchObject ]); end; end.
{*******************************************************} { } { Delphi FireDAC Framework } { FireDAC IBM DB2 metadata } { } { Copyright(c) 2004-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$I FireDAC.inc} unit FireDAC.Phys.DB2Meta; interface uses System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.Phys.Meta, FireDAC.Phys.SQLGenerator, FireDAC.Phys; type TFDPhysDb2Metadata = class (TFDPhysConnectionMetadata) private FColumnOriginProvided: Boolean; FTxSupported: Boolean; protected function GetKind: TFDRDBMSKind; override; function GetTxSupported: Boolean; override; function GetTxSavepoints: Boolean; override; function GetEventSupported: Boolean; override; function GetEventKinds: String; override; function GetParamNameMaxLength: Integer; override; function GetNameParts: TFDPhysNameParts; override; function GetNameDefLowCaseParts: TFDPhysNameParts; override; function GetNameCaseSensParts: TFDPhysNameParts; override; function GetInlineRefresh: Boolean; override; function GetTruncateSupported: Boolean; override; function GetDefValuesSupported: TFDPhysDefaultValues; override; function GetSelectOptions: TFDPhysSelectOptions; override; function GetAsyncAbortSupported: Boolean; override; function GetArrayExecMode: TFDPhysArrayExecMode; override; function GetCreateTableOptions: TFDPhysCreateTableOptions; override; function GetBackslashEscSupported: Boolean; override; function GetColumnOriginProvided: Boolean; override; function InternalEscapeBoolean(const AStr: String): String; override; function InternalEscapeDate(const AStr: String): String; override; function InternalEscapeDateTime(const AStr: String): String; override; function InternalEscapeFloat(const AStr: String): String; override; function InternalEscapeFunction(const ASeq: TFDPhysEscapeData): String; override; function InternalEscapeTime(const AStr: String): String; override; function InternalGetSQLCommandKind(const ATokens: TStrings): TFDPhysCommandKind; override; public constructor Create(const AConnectionObj: TFDPhysConnection; AServerVersion, AClientVersion: TFDVersion; const ACSVKeywords: String; AColumnOriginProvided, ATxSupported: Boolean); end; TFDPhysDb2CommandGenerator = class(TFDPhysCommandGenerator) private function GetDB2Returning(const AStmt: String; ARequest: TFDUpdateRequest): String; protected function GetInlineRefresh(const AStmt: String; ARequest: TFDUpdateRequest): String; override; function GetIdentity(ASessionScope: Boolean): String; override; function GetSingleRowTable: String; override; function GetPessimisticLock: String; override; function GetSavepoint(const AName: String): String; override; function GetRollbackToSavepoint(const AName: String): String; override; function GetCommitSavepoint(const AName: String): String; override; function GetCall(const AName: String): String; override; function GetLimitSelect(const ASQL: String; ASkip, ARows: Integer; var AOptions: TFDPhysLimitOptions): String; override; function GetColumnType(AColumn: TFDDatSColumn): String; override; function GetColumnDef(AColumn: TFDDatSColumn): String; override; end; implementation uses System.SysUtils, FireDAC.Stan.Consts, FireDAC.Stan.Util; {-------------------------------------------------------------------------------} { TFDPhysDb2Metadata } {-------------------------------------------------------------------------------} constructor TFDPhysDb2Metadata.Create(const AConnectionObj: TFDPhysConnection; AServerVersion, AClientVersion: TFDVersion; const ACSVKeywords: String; AColumnOriginProvided, ATxSupported: Boolean); begin inherited Create(AConnectionObj, AServerVersion, AClientVersion, False); if ACSVKeywords <> '' then FKeywords.CommaText := ACSVKeywords; FColumnOriginProvided := AColumnOriginProvided; FTxSupported := ATxSupported; end; {-------------------------------------------------------------------------------} function TFDPhysDb2Metadata.GetKind: TFDRDBMSKind; begin Result := TFDRDBMSKinds.DB2; end; {-------------------------------------------------------------------------------} function TFDPhysDb2Metadata.GetNameCaseSensParts: TFDPhysNameParts; begin Result := []; end; {-------------------------------------------------------------------------------} function TFDPhysDb2Metadata.GetNameDefLowCaseParts: TFDPhysNameParts; begin Result := []; end; {-------------------------------------------------------------------------------} function TFDPhysDb2Metadata.GetParamNameMaxLength: Integer; begin Result := 128; end; {-------------------------------------------------------------------------------} function TFDPhysDb2Metadata.GetNameParts: TFDPhysNameParts; begin Result := [npSchema, npBaseObject, npObject]; end; {-------------------------------------------------------------------------------} function TFDPhysDb2Metadata.GetInlineRefresh: Boolean; begin Result := True; end; {-------------------------------------------------------------------------------} function TFDPhysDb2Metadata.GetTxSupported: Boolean; begin Result := FTxSupported; end; {-------------------------------------------------------------------------------} function TFDPhysDb2Metadata.GetTxSavepoints: Boolean; begin Result := FTxSupported; end; {-------------------------------------------------------------------------------} function TFDPhysDb2Metadata.GetEventSupported: Boolean; begin Result := True; end; {-------------------------------------------------------------------------------} function TFDPhysDb2Metadata.GetEventKinds: String; begin Result := S_FD_EventKind_DB2_DBMS_ALERT + ';' + S_FD_EventKind_DB2_DBMS_PIPE; end; {-------------------------------------------------------------------------------} function TFDPhysDb2Metadata.GetTruncateSupported: Boolean; begin Result := False; end; {-------------------------------------------------------------------------------} function TFDPhysDb2Metadata.GetDefValuesSupported: TFDPhysDefaultValues; begin Result := dvDef; end; {-------------------------------------------------------------------------------} function TFDPhysDb2Metadata.GetSelectOptions: TFDPhysSelectOptions; begin Result := [soInlineView]; end; {-------------------------------------------------------------------------------} function TFDPhysDb2Metadata.GetAsyncAbortSupported: Boolean; begin Result := True; end; {-------------------------------------------------------------------------------} function TFDPhysDb2Metadata.GetArrayExecMode: TFDPhysArrayExecMode; begin Result := aeCollectAllErrors; end; {-------------------------------------------------------------------------------} function TFDPhysDb2Metadata.GetCreateTableOptions: TFDPhysCreateTableOptions; begin Result := []; end; {-------------------------------------------------------------------------------} function TFDPhysDb2Metadata.GetBackslashEscSupported: Boolean; begin Result := True; end; {-------------------------------------------------------------------------------} function TFDPhysDb2Metadata.GetColumnOriginProvided: Boolean; begin Result := FColumnOriginProvided; end; {-------------------------------------------------------------------------------} function TFDPhysDb2Metadata.InternalEscapeBoolean(const AStr: String): String; begin if CompareText(AStr, S_FD_True) = 0 then Result := '1' else Result := '0'; end; {-------------------------------------------------------------------------------} function TFDPhysDb2Metadata.InternalEscapeDate(const AStr: String): String; begin Result := 'DATE(' + AnsiQuotedStr(AStr, '''') + ')'; end; {-------------------------------------------------------------------------------} function TFDPhysDb2Metadata.InternalEscapeDateTime(const AStr: String): String; begin if Pos(':', AStr) = 0 then Result := 'TIMESTAMP(' + AnsiQuotedStr(AStr + ' 00:00:00', '''') + ')' else Result := 'TIMESTAMP(' + AnsiQuotedStr(AStr, '''') + ')'; end; {-------------------------------------------------------------------------------} function TFDPhysDb2Metadata.InternalEscapeTime(const AStr: String): String; begin Result := 'TIME(''' + AStr + ''')'; end; {-------------------------------------------------------------------------------} function TFDPhysDb2Metadata.InternalEscapeFloat(const AStr: String): String; begin Result := AStr; end; {-------------------------------------------------------------------------------} function TFDPhysDb2Metadata.InternalEscapeFunction(const ASeq: TFDPhysEscapeData): String; var sName: String; A1, A2, A3: String; rSeq: TFDPhysEscapeData; i: Integer; function AddArgs: string; begin Result := '(' + AddEscapeSequenceArgs(ASeq) + ')'; end; begin sName := ASeq.FName; if Length(ASeq.FArgs) >= 1 then begin A1 := ASeq.FArgs[0]; if Length(ASeq.FArgs) >= 2 then begin A2 := ASeq.FArgs[1]; if Length(ASeq.FArgs) >= 3 then A3 := ASeq.FArgs[2]; end; end; case ASeq.FFunc of // the same // char efASCII, efCONCAT, efINSERT, efLEFT, efLENGTH, efLCASE, efLOCATE, efLTRIM, efREPLACE, efREPEAT, efRIGHT, efRTRIM, efSPACE, efUCASE, // numeric efACOS, efASIN, efATAN, efATAN2, efABS, efCEILING, efCOS, efCOT, efDEGREES, efEXP, efFLOOR, efLOG, efLOG10, efMOD, efPOWER, efRADIANS, efSIGN, efSIN, efSQRT, efTAN, // date and time efDAYNAME, efDAYOFWEEK, efDAYOFYEAR, efHOUR, efMINUTE, efMONTH, efMONTHNAME, efQUARTER, efSECOND, efWEEK, efYEAR: Result := sName + AddArgs; // character efCHAR: Result := 'CHR' + AddArgs; efBIT_LENGTH: Result := '(LENGTH(' + A1 + ') * 8)'; efCHAR_LENGTH: Result := 'LENGTH' + AddArgs; efOCTET_LENGTH:Result := 'LENGTH' + AddArgs; efPOSITION: Result := 'POSSTR(' + A2 + ', ' + A1 + ')'; efSUBSTRING: Result := 'SUBSTR' + AddArgs; // numeric efTRUNCATE: Result := sName + '(' + A1 + ', 0)'; efPI: Result := S_FD_Pi; efRANDOM: Result := 'RAND' + AddArgs; efROUND: if A2 = '' then Result := sName + '(' + A1 + ', 0)' else Result := sName + AddArgs; // date and time efCURDATE: Result := 'CURRENT_DATE'; efCURTIME: Result := 'CURRENT_TIME'; efNOW: Result := 'CURRENT_TIMESTAMP'; efDAYOFMONTH: Result := 'DAY' + AddArgs; efEXTRACT: begin rSeq.FKind := eskFunction; A1 := UpperCase(FDUnquote(Trim(A1), '''')); if A1 = 'DAY' then A1 := 'DAYOFMONTH'; rSeq.FName := A1; SetLength(rSeq.FArgs, 1); rSeq.FArgs[0] := ASeq.FArgs[1]; EscapeFuncToID(rSeq); Result := InternalEscapeFunction(rSeq); end; efTIMESTAMPADD: begin A1 := UpperCase(FDUnquote(Trim(A1), '''')); if A1 = 'QUARTER' then begin A2 := '((' + A2 + ') * 3)'; A1 := 'MONTH'; end else if A1 = 'WEEK' then begin A2 := '((' + A2 + ') * 7)'; A1 := 'DAY'; end else if A1 = 'FRAC_SECOND' then A1 := 'MICROSECOND'; Result := '((' + A3 + ') + (' + A2 + ') ' + A1 + ')'; end; efTIMESTAMPDIFF: begin A1 := UpperCase(FDUnquote(Trim(A1), '''')); if A1 = 'YEAR' then Result := '256' else if A1 = 'QUARTER' then Result := '128' else if A1 = 'MONTH' then Result := '64' else if A1 = 'WEEK' then Result := '32' else if A1 = 'DAY' then Result := '16' else if A1 = 'HOUR' then Result := '8' else if A1 = 'MINUTE' then Result := '4' else if A1 = 'SECOND' then Result := '2' else if A1 = 'FRAC_SECOND' then Result := '1' else UnsupportedEscape(ASeq); Result := 'TIMESTAMPDIFF(' + Result + ', CHAR(TIMESTAMP(' + A3 + ') - TIMESTAMP(' + A2 + ')))'; end; // system efCATALOG: Result := ''''''; efSCHEMA: Result := 'CURRENT_SCHEMA'; efIFNULL: Result := 'CASE WHEN ' + A1 + ' IS NULL THEN ' + A2 + ' ELSE ' + A1 + ' END'; efIF: Result := 'CASE WHEN ' + A1 + ' THEN ' + A2 + ' ELSE ' + A3 + ' END'; efDECODE: begin Result := 'CASE ' + ASeq.FArgs[0]; i := 1; while i < Length(ASeq.FArgs) - 1 do begin Result := Result + ' WHEN ' + ASeq.FArgs[i] + ' THEN ' + ASeq.FArgs[i + 1]; Inc(i, 2); end; if i = Length(ASeq.FArgs) - 1 then Result := Result + ' ELSE ' + ASeq.FArgs[i]; Result := Result + ' END'; end; // convert efCONVERT: begin A2 := UpperCase(FDUnquote(Trim(A2), '''')); if (A2 = 'LONGVARCHAR') or (A2 = 'WLONGVARCHAR') then A2 := 'LONG_VARCHAR' else if A2 = 'WCHAR' then A2 := 'CHAR' else if A2 = 'WVARCHAR' then A2 := 'VARCHAR' else if A2 = 'DATETIME' then A2 := 'TIMESTAMP' else if A2 = 'NUMERIC' then A2 := 'DECIMAL' else if A2 = 'TINYINT' then A2 := 'SMALLINT' else if (A2 = 'VARBINARY') or (A2 = 'BINARY') or (A2 = 'LONGVARBINARY') then A2 := 'BLOB' else if not ((A2 = 'BIGINT') or (A2 = 'CHAR') or (A2 = 'INTEGER') or (A2 = 'NUMERIC') or (A2 = 'REAL') or (A2 = 'SMALLINT') or (A2 = 'DATE') or (A2 = 'TIME') or (A2 = 'TIMESTAMP') or (A2 = 'VARCHAR') or (A2 = 'DECIMAL') or (A2 = 'DOUBLE') or (A2 = 'FLOAT')) then UnsupportedEscape(ASeq); Result := A2 + '(' + A1 + ')'; end; else UnsupportedEscape(ASeq); end; end; {-------------------------------------------------------------------------------} function TFDPhysDb2Metadata.InternalGetSQLCommandKind( const ATokens: TStrings): TFDPhysCommandKind; var sToken: String; begin sToken := ATokens[0]; if sToken = 'CALL' then Result := skExecute else if sToken = 'SET' then if (ATokens.Count = 1) or (ATokens.Count = 2) and (ATokens[1] = 'CURRENT') then Result := skNotResolved else if (ATokens.Count = 2) and (ATokens[1] = 'SCHEMA') or (ATokens.Count = 3) and (ATokens[2] = 'SCHEMA') then Result := skSetSchema else Result := skSet else Result := inherited InternalGetSQLCommandKind(ATokens); end; {-------------------------------------------------------------------------------} { TFDPhysDb2CommandGenerator } {-------------------------------------------------------------------------------} function TFDPhysDb2CommandGenerator.GetDB2Returning(const AStmt: String; ARequest: TFDUpdateRequest): String; var s: String; i: Integer; oCols: TFDDatSColumnList; oCol: TFDDatSColumn; begin s := ''; oCols := FTable.Columns; for i := 0 to oCols.Count - 1 do begin oCol := oCols[i]; if ColumnStorable(oCol) and ColumnReqRefresh(ARequest, oCol) then begin if s <> '' then s := s + ', '; s := s + GetColumn('', -1, oCols[i]); end; end; if s <> '' then begin Result := 'SELECT ' + s + ' FROM FINAL TABLE (' + AStmt + ')'; FCommandKind := skSelect; end else Result := AStmt; end; {-------------------------------------------------------------------------------} function TFDPhysDb2CommandGenerator.GetInlineRefresh(const AStmt: String; ARequest: TFDUpdateRequest): String; begin Result := GetDB2Returning(AStmt, ARequest); end; {-------------------------------------------------------------------------------} function TFDPhysDb2CommandGenerator.GetIdentity(ASessionScope: Boolean): String; begin Result := 'IDENTITY_VAL_LOCAL()'; end; {-------------------------------------------------------------------------------} function TFDPhysDb2CommandGenerator.GetSingleRowTable: String; begin Result := 'SYSIBM.SYSDUMMY1'; end; {-------------------------------------------------------------------------------} function TFDPhysDb2CommandGenerator.GetPessimisticLock: String; var lNeedFrom: Boolean; begin Result := 'SELECT ' + GetSelectList(True, False, lNeedFrom) + BRK + 'FROM ' + GetFrom + BRK + 'WHERE ' + GetWhere(False, True, False) + BRK + 'FOR UPDATE'; FCommandKind := skSelectForLock; ASSERT(lNeedFrom); end; {-------------------------------------------------------------------------------} function TFDPhysDb2CommandGenerator.GetSavepoint(const AName: String): String; begin Result := 'SAVEPOINT ' + AName + ' ON ROLLBACK RETAIN CURSORS'; end; {-------------------------------------------------------------------------------} function TFDPhysDb2CommandGenerator.GetRollbackToSavepoint(const AName: String): String; begin Result := 'ROLLBACK TO SAVEPOINT ' + AName; end; {-------------------------------------------------------------------------------} function TFDPhysDb2CommandGenerator.GetCommitSavepoint(const AName: String): String; begin Result := 'RELEASE SAVEPOINT ' + AName; end; {-------------------------------------------------------------------------------} function TFDPhysDb2CommandGenerator.GetCall(const AName: String): String; begin Result := 'CALL ' + AName; end; {-------------------------------------------------------------------------------} function TFDPhysDb2CommandGenerator.GetLimitSelect(const ASQL: String; ASkip, ARows: Integer; var AOptions: TFDPhysLimitOptions): String; begin if ASkip + ARows <> MAXINT then // DB2: does not support FETCH FIRST 0 ROWS ONLY and returns // "The numeric literal 0 is not valid because its value is out of range" if ARows = 0 then Result := 'SELECT * FROM (' + BRK + ASQL + BRK + ') A' + BRK + 'WHERE 0 = 1' else Result := ASQL + BRK + 'FETCH FIRST ' + IntToStr(ASkip + ARows) + ' ROWS ONLY' else begin Result := ASQL; AOptions := []; end; end; {-------------------------------------------------------------------------------} function TFDPhysDb2CommandGenerator.GetColumnType(AColumn: TFDDatSColumn): String; begin case AColumn.DataType of dtBoolean, dtSByte, dtInt16, dtByte: Result := 'SMALLINT'; dtInt32, dtUInt16: Result := 'INTEGER'; dtInt64, dtUInt32, dtUInt64: Result := 'BIGINT'; dtSingle: Result := 'REAL'; dtDouble, dtExtended: Result := 'DOUBLE'; dtCurrency: Result := 'DECIMAL' + GetColumnDim(-1, AColumn.Precision, AColumn.Scale, -1, 18, 4); dtBCD, dtFmtBCD: Result := 'DECIMAL' + GetColumnDim(-1, AColumn.Precision, AColumn.Scale, -1, FOptions.FormatOptions.MaxBcdPrecision, 0); dtDateTime, dtDateTimeStamp: Result := 'TIMESTAMP'; dtTime: Result := 'TIME'; dtDate: Result := 'DATE'; dtAnsiString: begin if (caFixedLen in AColumn.ActualAttributes) and (AColumn.Size <= 254) then Result := 'CHAR' else if AColumn.Size <= 4000 then Result := 'VARCHAR' else Result := 'LONG VARCHAR'; Result := Result + GetColumnDim(AColumn.Size, -1, -1, -1, -1, -1); end; dtWideString: begin if (caFixedLen in AColumn.ActualAttributes) and (AColumn.Size <= 127) then Result := 'GRAPHIC' else Result := 'VARGRAPHIC'; Result := Result + GetColumnDim(AColumn.Size, -1, -1, -1, -1, -1); end; dtByteString: begin if (caFixedLen in AColumn.ActualAttributes) and (AColumn.Size <= 254) then Result := 'CHAR' else if AColumn.Size <= 4000 then Result := 'VARCHAR' else Result := 'LONG VARCHAR'; Result := Result + ' FOR BIT DATA' + GetColumnDim(AColumn.Size, -1, -1, -1, -1, -1); end; dtBlob, dtHBlob, dtHBFile: Result := 'BLOB'; dtMemo, dtHMemo: Result := 'CLOB'; dtWideMemo, dtWideHMemo: Result := 'DBCLOB'; dtXML: Result := 'XML'; dtGUID: Result := 'CHAR(38)'; dtUnknown, dtTimeIntervalFull, dtTimeIntervalYM, dtTimeIntervalDS, dtRowSetRef, dtCursorRef, dtRowRef, dtArrayRef, dtParentRowRef, dtObject: Result := ''; end; end; {-------------------------------------------------------------------------------} function TFDPhysDb2CommandGenerator.GetColumnDef(AColumn: TFDDatSColumn): String; begin Result := inherited GetColumnDef(AColumn); if (Result <> '') and (caAutoInc in AColumn.ActualAttributes) then Result := Result + ' GENERATED BY DEFAULT AS IDENTITY'; end; {-------------------------------------------------------------------------------} initialization FDPhysManager().RegisterRDBMSKind(TFDRDBMSKinds.DB2, S_FD_DB2_RDBMS); end.
unit TestBrickCamp.Repositories.Employee; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses System.JSON, TestFramework, Spring.Container, Spring.Collections, BrickCamp.Model.TEmployee, BrickCamp.Model.IEmployee, BrickCamp.Repositories.IEmployee, BrickCamp.Repositories.TEmployee.Mock; type // Test methods for class TMockEmployeeRepository TestTMockEmployeeRepository = class(TTestCase) strict private FMockEmployeeRepository: TMockEmployeeRepository; public procedure SetUp; override; procedure TearDown; override; published procedure TestGetOne_ReturnsOne_Success; procedure TestGetList; end; implementation procedure TestTMockEmployeeRepository.SetUp; begin FMockEmployeeRepository := TMockEmployeeRepository.Create; end; procedure TestTMockEmployeeRepository.TearDown; begin FMockEmployeeRepository.Free; FMockEmployeeRepository := nil; end; procedure TestTMockEmployeeRepository.TestGetOne_ReturnsOne_Success; var ReturnValue: TEmployee; begin // TODO: Setup method call parameters ReturnValue := FMockEmployeeRepository.GetOne(100); Assert(Assigned(ReturnValue)); // TODO: Validate method results end; procedure TestTMockEmployeeRepository.TestGetList; var ReturnValue: TJsonArray; begin ReturnValue := FMockEmployeeRepository.GetList; // TODO: Validate method results Assert(ReturnValue.Count <> 0); end; initialization GlobalContainer.RegisterType<TEmployee>; GlobalContainer.Build; // Register any test cases with the test runner RegisterTest(TestTMockEmployeeRepository.Suite); end.
unit uMainForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, IniFiles, System.Generics.Collections, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, FireDAC.Comp.Client, Vcl.StdCtrls, FireDAC.Stan.Option, uLogger, QBAes, Vcl.ExtCtrls, FireDAC.Phys.MSSQL, FireDAC.Phys.MSSQLDef, FireDAC.Phys.OracleDef, FireDAC.Phys.Oracle, FireDAC.Stan.Intf, FireDAC.Stan.Def, FireDAC.DApt, FireDAC.Phys, FireDAC.Phys.ODBCBase, FireDAC.UI.Intf, FireDAC.VCLUI.Wait, FireDAC.Comp.UI, FireDAC.Stan.Async, uVariants, uDDThread, uExportThread; type TfrmMain = class(TForm) Timer1: TTimer; Button1: TButton; FDPhysMSSQLDriverLink1: TFDPhysMSSQLDriverLink; fdphysrcldrvrlnk1: TFDPhysOracleDriverLink; FDGUIxWaitCursor1: TFDGUIxWaitCursor; procedure Timer1Timer(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private procedure ReadConfig; function GetData: TList<TData>; public { Public declarations } end; var frmMain: TfrmMain; implementation {$R *.dfm} procedure TfrmMain.ReadConfig; var ini: TInifile; begin ini := TInifile.Create(ExtractFilePath(ParamStr(0)) + 'config.ini'); FRunTime := ini.ReadString('sys', 'time', '04:00,18:00'); ExportTime := ini.ReadString('sys', 'ExportTime', '08:00'); ini.Free; end; function TfrmMain.GetData: TList<TData>; var ini: TInifile; sections: TStrings; tbname: string; item: TData; begin result := TList<TData>.Create; ini := TInifile.Create(ExtractFilePath(ParamStr(0)) + 'config.ini'); oraHost := ini.ReadString('ora', 'host', ''); oraPort := ini.ReadString('ora', 'port', ''); oraSID := ini.ReadString('ora', 'sid', ''); oraUser := ini.ReadString('ora', 'user', ''); oraPwd := ini.ReadString('ora', 'pwd', ''); if oraPwd.Length > 30 then begin oraPwd := QBAes.AesDecrypt(oraPwd, 'lgm1224,./'); oraPwd := oraPwd.Trim; end; sqlServer := ini.ReadString('mssql', 'server', ''); sqlDBName := ini.ReadString('mssql', 'dbname', ''); sqlUser := ini.ReadString('mssql', 'user', ''); sqlPwd := ini.ReadString('mssql', 'pwd', ''); if sqlPwd.Length > 30 then begin sqlPwd := QBAes.AesDecrypt(sqlPwd, 'lgm1224,./'); sqlPwd := sqlPwd.Trim; end; sections := TStringList.Create; ini.ReadSections(sections); for tbname in sections do begin if LowerCase(tbname).StartsWith('table') then begin item.TableName := ini.ReadString(tbname, 'tablename', tbname); item.SQL := ini.ReadString(tbname, 'sql', ''); item.KeyField := ini.ReadString(tbname, 'keyfield', 'xh'); result.Add(item); end; end; sections.Free; ini.Free; end; procedure TfrmMain.Timer1Timer(Sender: TObject); var list: TList<TData>; item: TData; hhmm: string; begin ReadConfig; hhmm := formatdatetime('hh:mm', now); if FRunTime.Contains(hhmm) then begin logger.Info('ISTIMENOW'); list := GetData; for item in list do begin TDDThread.Create(item); end; list.Free; end else if ExportTime.Contains(hhmm) then begin list := GetData; TExportThread.Create; end; end; procedure TfrmMain.Button1Click(Sender: TObject); var list: TList<TData>; item: TData; begin logger.Info('ISTIMENOW'); list := GetData; for item in list do begin TDDThread.Create(item); end; list.Free; end; procedure TfrmMain.FormClose(Sender: TObject; var Action: TCloseAction); begin logger.Free; end; procedure TfrmMain.FormCreate(Sender: TObject); // var // ini: TInifile; begin // ini := TInifile.Create(ExtractFilePath(ParamStr(0)) + 'config.ini'); // ini.WriteString('ora', 'pwd', QBAes.AesEncrypt('hczssqg%#65', 'lgm1224,./')); // ini.WriteString('mssql', 'pwd', QBAes.AesEncrypt('lgm1224,./', 'lgm1224,./')); // ini.Free; logger := TLogger.Create(ParamStr(0) + '.log'); //logger.info(QBAes.AesEncrypt('jyiw04rk', 'lgm1224,./')); end; end.
{----------------------------------------------------------------------------} { Written by Nguyen Le Quang Duy } { Nguyen Quang Dieu High School, An Giang } {----------------------------------------------------------------------------} Program KINV; Const maxN =10000; maxV =10000; maxK =10; base =1000000000; Var n,k :LongInt; A :Array[1..maxN] of LongInt; BIT :Array[1..maxV] of LongInt; F :Array[1..maxK,1..maxN] of LongInt; procedure Enter; var i :LongInt; begin ReadLn(n,k); for i:=1 to n do Read(A[i]); end; function SearchBIT(i :LongInt) :LongInt; var res :LongInt; begin res:=0; while (i>0) do begin res:=(res+BIT[i]) mod base; Dec(i,i and (-i)); end; Exit(res); end; procedure UpdateBIT(i,v :LongInt); begin while (i<=maxV) do begin BIT[i]:=(BIT[i]+v) mod base; Inc(i,i and (-i)); end; end; procedure Optimize; var i,j :LongInt; begin for j:=1 to n do F[1,j]:=1; for i:=2 to k do begin for j:=1 to n do BIT[j]:=0; for j:=n downto 1 do begin F[i,j]:=SearchBIT(A[j]-1); UpdateBIT(A[j],F[i-1,j]); end; end; end; procedure PrintResult; var i,ans :LongInt; begin ans:=0; for i:=1 to n do ans:=(ans+F[k,i]) mod base; Write(ans); end; Begin Assign(Input,''); Reset(Input); Assign(Output,''); Rewrite(Output); Enter; Optimize; PrintResult; Close(Input); Close(Output); End.
unit Unit1; interface uses System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.Menus, //GLS GLScene, GLHUDObjects, GLObjects, GLCadencer, GLWin32Viewer, GLWindowsFont, GLTeapot, GLCoordinates, GLCrossPlatform, GLBaseClasses, GLBitmapFont; type TForm1 = class(TForm) GLScene1: TGLScene; GLSceneViewer1: TGLSceneViewer; GLLightSource1: TGLLightSource; GLCamera1: TGLCamera; HUDText1: TGLHUDText; GLCadencer1: TGLCadencer; Timer1: TTimer; HUDText2: TGLHUDText; HUDText3: TGLHUDText; Teapot1: TGLTeapot; WindowsBitmapFont1: TGLWindowsBitmapFont; MainMenu1: TMainMenu; MIPickFont: TMenuItem; FontDialog1: TFontDialog; MIViewTexture: TMenuItem; MIFPS: TMenuItem; procedure GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); procedure Timer1Timer(Sender: TObject); procedure FormCreate(Sender: TObject); procedure GLSceneViewer1Click(Sender: TObject); procedure MIPickFontClick(Sender: TObject); procedure MIViewTextureClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation uses Unit2; {$R *.DFM} procedure TForm1.FormCreate(Sender: TObject); begin // sorry, couldn't resist again... HUDText1.Text:= 'Lorem ipsum dolor sit amer, consectetaur adipisicing elit,'#13#10 +'sed do eiusmod tempor incididunt ut labore et dolore magna'#13#10 +'aliqua. Ut enim ad minim veniam, quis nostrud exercitation'#13#10 +'ullamco laboris nisi ut aliquip ex ea commodo consequat.'#13#10 +'Duis aute irure dolor in reprehenderit in voluptate velit'#13#10 +'esse cillum dolore eu fugiat nulla pariatur. Excepteur sint'#13#10 +'occaecat cupidatat non proident, sunt in culpa qui officia'#13#10 +'deserunt mollit anim id est laborum.'#13#10 +'Woblis ten caracuro Zapothek it Setag!'; // I needed an uppercase 'W' too... HUDText1.Text := HUDText1.Text + #13#10'Unicode text...' + WideChar($0699)+WideChar($069A)+WideChar($963f)+WideChar($54c0); WindowsBitmapFont1.EnsureString(HUDText1.Text); end; procedure TForm1.MIPickFontClick(Sender: TObject); begin FontDialog1.Font:=WindowsBitmapFont1.Font; if FontDialog1.Execute then begin WindowsBitmapFont1.Font:=FontDialog1.Font; HUDText1.ModulateColor.AsWinColor:=FontDialog1.Font.Color; end; end; procedure TForm1.MIViewTextureClick(Sender: TObject); begin with Form2.Image1 do begin Picture:=WindowsBitmapFont1.Glyphs; Form2.Width:=Picture.Width; Form2.Height:=Picture.Height; end; Form2.Show; end; procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); begin // make things move a little HUDText2.Rotation:=HUDText2.Rotation+15*deltaTime; HUDText3.Scale.X:=sin(newTime)+1.5; HUDText3.Scale.Y:=cos(newTime)+1.5; GLSceneViewer1.Invalidate; end; procedure TForm1.Timer1Timer(Sender: TObject); begin miFPS.Caption:=Format('%.1f FPS - %d x %d Font Texture', [GLSceneViewer1.FramesPerSecond, WindowsBitmapFont1.FontTextureWidth, WindowsBitmapFont1.FontTextureHeight]); GLSceneViewer1.ResetPerformanceMonitor; end; procedure TForm1.GLSceneViewer1Click(Sender: TObject); begin Teapot1.Visible:=not Teapot1.Visible; end; end.
unit UProdutoVenda; interface uses UProduto; type ProdutoVenda = class(Produto) protected valorUnitario : Real; quantidade : Real; desconto : Real; qtdTemp : Real; public Constructor CrieObjeto; Destructor Destrua_Se; Procedure setValorUnitario (vValorUnitario : Real); Procedure setQtdProduto (vQuantidade : Real); Procedure setDesconto (vDesconto : Real); Procedure setQtdTemp (vQtdTemp : Real); Function getValorUnitario : Real; Function getQtdProduto : Real; Function getDesconto : Real; Function getQtdTemp : Real; end; implementation { ProdutoVenda } constructor ProdutoVenda.CrieObjeto; begin inherited; valorUnitario := 0.0; quantidade := 0; desconto := 0; qtdTemp := 0; end; destructor ProdutoVenda.Destrua_Se; begin end; function ProdutoVenda.getDesconto: Real; begin Result := desconto; end; function ProdutoVenda.getQtdProduto: Real; begin Result := quantidade; end; function ProdutoVenda.getQtdTemp: Real; begin Result := qtdTemp; end; function ProdutoVenda.getValorUnitario: Real; begin Result := valorUnitario; end; procedure ProdutoVenda.setDesconto(vDesconto: Real); begin desconto := vDesconto; end; procedure ProdutoVenda.setQtdProduto(vQuantidade: Real); begin quantidade := vQuantidade; end; procedure ProdutoVenda.setQtdTemp(vQtdTemp: Real); begin qtdTemp := vQtdTemp; end; procedure ProdutoVenda.setValorUnitario(vValorUnitario: Real); begin valorUnitario := vValorUnitario; end; end.
unit uProcess; interface uses {$IF CompilerVersion > 22} Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, {$ELSE} Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, {$IFEND} CNClrLib.Component.OpenFileDialog, CNClrLib.Control.Base, CNClrLib.Control.EnumTypes, CNClrLib.Component.Process; type TfrmProcess = class(TForm) CnProcess1: TCnProcess; CnOpenFileDialog1: TCnOpenFileDialog; btnPrintDoc: TButton; procedure btnPrintDocClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmProcess: TfrmProcess; implementation uses CNClrLib.Host, CNClrLib.Core, CNClrLib.ComponentModel; {$R *.dfm} /// Prints a file procedure TfrmProcess.btnPrintDocClick(Sender: TObject); const // These are the Win32 error code for file not found or access denied. ERROR_FILE_NOT_FOUND = 2; ERROR_ACCESS_DENIED = 5; var clrEx: EClrException; win32Ex: _Win32Exception; begin if CnOpenFileDialog1.ShowDialog <> TDialogResult.drOK then begin TClrMessageBox.Show('The operation was canceled by the user.'); Exit; end; try cnProcess1.StartInfo.FileName := CnOpenFileDialog1.FileName; cnProcess1.StartInfo.Verb := 'Print'; cnProcess1.StartInfo.CreateNoWindow := True; cnProcess1.Start; except clrEx := EClrException.GetLastClrException; try if clrEx.IsTypeOf('System.ComponentModel.Win32Exception') then begin win32Ex := CoWin32Exception.Wrap(clrEx.DefaultInterface); if win32Ex.NativeErrorCode = ERROR_FILE_NOT_FOUND then TClrMessageBox.Show(win32Ex.Message + '. Check the path.') else if win32Ex.NativeErrorCode = ERROR_ACCESS_DENIED then begin // Note that if your word processor might generate exceptions such as this, which are handled first. TClrMessageBox.Show(win32Ex.Message + '. You do not have permission to print this file.'); end; end; finally clrEx.Free; end; end; end; end.
{ Routines that manipulate queues of CAN frames. } module can_queue; define can_queue_init; define can_queue_release; define can_queue_ent_new; define can_queue_ent_del; define can_queue_ent_put; define can_queue_ent_get; define can_queue_ent_avail; define can_queue_put; define can_queue_get; %include 'can2.ins.pas'; { ******************************************************************************** * * Subroutine CAN_QUEUE_INIT (Q, MEM) * * Initialize the queue of CAN frames, Q. MEM is the parent memory context. A * subordinate memory context will be created that will be private to the * queue. This subordinate memory context and other system resources allocated * to the queue will be released when CAN_QUEUE_RELEASE is called. } procedure can_queue_init ( {initialize a can frames queue} out q: can_queue_t; {the queue to initialize} in out mem: util_mem_context_t); {parent memory context} val_param; var stat: sys_err_t; {completion status} begin sys_thread_lock_create (q.lock, stat); sys_error_abort (stat, 'can', 'err_lock_qinit', nil, 0); sys_event_create_bool (q.ev); {create event for new entry added to queue} util_mem_context_get (mem, q.mem_p); {create new memory context for the queue} q.nframes := 0; {init queue to empty} q.first_p := nil; q.last_p := nil; q.free_p := nil; q.quit := false; {init to not closing the queue} end; { ******************************************************************************** * * Subroutine CAN_QUEUE_RELEASE (Q) * * Release all system resources allocated to the CAN frames queue Q. The queue * is returned unusable. It must be initialized before it is used again. } procedure can_queue_release ( {release system resources of a CAN frames queue} in out q: can_queue_t); {the queue, will be returned unusable} val_param; var stat: sys_err_t; {completion status} begin q.quit := true; {indicate the queue is being closed} sys_event_notify_bool (q.ev); {release any waiting thread} sys_thread_yield; sys_thread_lock_enter (q.lock); {get exclusive access to this queue} sys_event_del_bool (q.ev); q.first_p := nil; q.last_p := nil; q.free_p := nil; q.nframes := 0; util_mem_context_del (q.mem_p); {delete the private memory context} sys_thread_lock_leave (q.lock); {release exclusive access to the queue} sys_thread_lock_delete (q.lock, stat); sys_error_abort (stat, 'can', 'err_lock_del_queue', nil, 0); end; { ******************************************************************************** * * Subroutine CAN_QUEUE_ENT_NEW (Q, ENT_P) * * Get a new unused entry associated with the CAN frames queue Q. The entry * will be empty and not enqueued, and will be automatically deallocated when * the queue is deleted. ENT_P is returned NIL if the queue is being closed. } procedure can_queue_ent_new ( {return pointer to new queue entry} in out q: can_queue_t; {queue to get new unused entry for} out ent_p: can_listent_p_t); {returned pointer to the new entry} val_param; begin ent_p := nil; {init to not returning with queue entry} if q.quit then return; {queue is being closed ?} sys_thread_lock_enter (q.lock); {get exclusive access to this queue} if q.quit then begin {queue is being close ?} sys_thread_lock_leave (q.lock); {release exclusive access to the queue} return; end; if q.free_p = nil then begin {no existing unused entries available} util_mem_grab (sizeof(ent_p^), q.mem_p^, false, ent_p); {allocate new queue entry} end else begin {grab from free list} ent_p := q.free_p; {get first entry from free list} q.free_p := ent_p^.next_p; end ; sys_thread_lock_leave (q.lock); {release exclusive access to the queue} ent_p^.next_p := nil; ent_p^.prev_p := nil; end; { ******************************************************************************** * * Subroutine CAN_QUEUE_ENT_DEL (Q, ENT_P) * * Delete a entry associated with the queue Q. ENT_P is returned NIL since the * entry can no longer be accessed. } procedure can_queue_ent_del ( {delete a CAN frames queue entry} in out q: can_queue_t; {queue to delete etnry entry for} in out ent_p: can_listent_p_t); {pointer to unused entry, returned NIL} val_param; begin if q.quit then begin {queue is being closed ?} ent_p := nil; return; end; sys_thread_lock_enter (q.lock); {get exclusive access to this queue} if not q.quit then begin ent_p^.next_p := q.free_p; q.free_p := ent_p; end; sys_thread_lock_leave (q.lock); {release exclusive access to the queue} ent_p := nil; {return NIL pointer} end; { ******************************************************************************** * * Subroutine CAN_QUEUE_ENT_PUT (Q, ENT_P) * * Add a entry to the end of the CAN frames queue Q. ENT_P is pointing to the * entry to add. It is returned NIL because once the entry is in the queue it * may be accessed by other threads. It should no longer be accessed directly * without going thru the CAN_QUEUE_xxx routines. } procedure can_queue_ent_put ( {add entry to end of can frames queue} in out q: can_queue_t; {queue to add entry to} in out ent_p: can_listent_p_t); {pointer to the entry to add, returned NIL} val_param; begin if q.quit then begin {queue is being closed ?} ent_p := nil; return; end; ent_p^.next_p := nil; {init to this entry will be at end of queue} sys_thread_lock_enter (q.lock); {get exclusive access to this queue} if not q.quit then begin if q.first_p = nil then begin {this is first queue entry} q.first_p := ent_p; ent_p^.prev_p := nil; end else begin {adding to end of existing list} q.last_p^.next_p := ent_p; ent_p^.prev_p := q.last_p; end ; q.last_p := ent_p; q.nframes := q.nframes + q.nframes + 1; {count one more CAN frame in the queue} sys_event_notify_bool (q.ev); {signal event for entry added to the queue} end; sys_thread_lock_leave (q.lock); {release exclusive access to the queue} ent_p := nil; end; { ******************************************************************************** * * Subroutine CAN_QUEUE_ENT_GET (Q, TOUT, ENT_P) * * Get the next entry from the CAN frames queue Q. TOUT is the maximum seconds * to wait for a queue entry to become available. ENT_P is returned pointing * to the queue entry. ENT_P will be NIL if no queue entry was available * within the timeout TOUT. When returning with a queue entry (ENT_P not NIL), * the entry will have been removed from the queue. The caller therefore has * exclusive access to the entry. When done with the entry it should be * deleted with CAN_QUEUE_ENT_DEL to release its memory. } procedure can_queue_ent_get ( {get next queue entry, wait with timeout} in out q: can_queue_t; {queue to get entry for} in tout: real; {maximum wait time, seconds} out ent_p: can_listent_p_t); {returned pnt to entry, NIL if none} val_param; var stat: sys_err_t; label retry; begin ent_p := nil; {init to returning without queue entry} retry: if q.quit then return; {queue is being closed ?} sys_thread_lock_enter (q.lock); {get exclusive access to this queue} if q.quit then begin sys_thread_lock_leave (q.lock); return; end; if q.first_p <> nil then begin {a entry is immediately available ?} ent_p := q.first_p; {return pointer to the entry} q.first_p := ent_p^.next_p; {remove this entry from the queue} if ent_p^.next_p = nil then begin {this is last entry in queue} q.last_p := nil; end else begin {there is a subsequent entry} ent_p^.next_p^.prev_p := nil; end ; q.nframes := q.nframes - 1; {count one less entry on the queue} sys_thread_lock_leave (q.lock); {release exclusive access to the queue} ent_p^.next_p := nil; ent_p^.prev_p := nil; return; {return with unlinked queue entry} end; sys_thread_lock_leave (q.lock); {release exclusive access to the queue} if sys_event_wait_tout (q.ev, tout, stat) then begin if q.quit then return; sys_error_abort (stat, 'can', 'err_queue_wait', nil, 0); return; {return due to timeout} end; goto retry; {event signalled, try getting entry again} end; { ******************************************************************************** * * Function CAN_QUEUE_ENT_AVAIL (Q) * * Indicate whether a queue entry is available to get. The function returns * TRUE when at least one queue entry can be retrieved, and FALSE if the queue * is empty. } function can_queue_ent_avail ( {indicate whether entry from queue available} in out q: can_queue_t) {queue to check} :boolean; {TRUE for queue not empty, FALSE for empty} val_param; begin can_queue_ent_avail := false; {init to no entry immediately available} if q.quit then return; sys_thread_lock_enter (q.lock); {get exclusive access to this queue} if q.quit then begin sys_thread_lock_leave (q.lock); return; end; can_queue_ent_avail := q.nframes > 0; sys_thread_lock_leave (q.lock); {release exclusive access to the queue} end; { ******************************************************************************** * * Subroutine CAN_QUEUE_PUT (Q, FRAME) * * Add the CAN frame in FRAME to the end of the CAN frames QUEUE Q. } procedure can_queue_put ( {add CAN frame to end of queue} in out q: can_queue_t; {the CAN frames queue} in frame: can_frame_t); {the CAN frame to add} val_param; var ent_p: can_listent_p_t; {pointer to CAN frames queue entry} begin if q.quit then return; can_queue_ent_new (q, ent_p); {create new queue entry, unlinked for now} if q.quit then return; ent_p^.frame := frame; {copy CAN frame information into the entry} can_queue_ent_put (q, ent_p); {enqueue the entry} end; { ******************************************************************************** * * Function CAN_QUEUE_GET (Q, TOUT, FRAME) * * Get the next CAN frame from the CAN frames queue Q. This routine will wait * up to TOUT seconds for a CAN frame to be available. If one is available * within that time, then the function returns TRUE and the frame informaion * is returned in FRAME. If no frame is available within the timeout, then the * function returns FALSE and the contents of FRAME is undefined. } function can_queue_get ( {get next CAN frame from queue} in out q: can_queue_t; {queue to get entry for} in tout: real; {maximum wait time, seconds} out frame: can_frame_t) {the returned CAN frame} :boolean; {TRUE with frame, FALSE with timeout} val_param; var ent_p: can_listent_p_t; {pointer to CAN frames queue entry} begin can_queue_get := false; {init to not returning with a CAN frame} can_queue_ent_get (q, tout, ent_p); {try to get next queue entry} if ent_p = nil then return; {no frame available within the timeout ?} frame := ent_p^.frame; {return the CAN frame information} can_queue_ent_del (q, ent_p); {done with this queue entry} can_queue_get := true; {indicate returning with a frame} end;
unit fPrintLocation; interface uses Windows, Messages, SysUtils, StrUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, fAutoSz, StdCtrls, ExtCtrls, ORCtrls,ORFn, rCore, uCore, oRNet, Math, fOrders, ORClasses, rOrders, fMeds, rMeds, CheckLst, Grids, fFrame, fClinicWardMeds, VA508AccessibilityManager; type TfrmPrintLocation = class(TfrmAutoSz) pnlTop: TPanel; pnlBottom: TORAutoPanel; orderGrid: TStringGrid; pnlOrder: TPanel; btnOK: TButton; lblText: TLabel; btnClinic: TButton; btnWard: TButton; lblEncounter: TLabel; cbolocation: TORComboBox; ORpnlBottom: TORAutoPanel; orpnlTopBottom: TORAutoPanel; cboEncLoc: TComboBox; procedure pnlFieldsResize(Sender: TObject); procedure orderGridMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure OrderGridDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); procedure orderGridKeyPress(Sender: TObject; var Key: Char); procedure btnClinicClick(Sender: TObject); procedure btnWardClick(Sender: TObject); procedure cbolocationChange(Sender: TObject); procedure cbolocationExit(Sender: TObject); procedure btnOKClick(Sender: TObject); procedure FormResize(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); private { Private declarations } CLoc,WLoc: string; CIEN,WIEN: integer; function ValFor(FieldID, ARow: Integer): string; procedure ShowEditor(ACol, ARow: Integer; AChar: Char); procedure ProcessClinicOrders(WardList, ClinicList: TStringList; WardIEN, ClinicIEN: integer; ContainsIMO: boolean); procedure rpcChangeOrderLocation(pOrderList:TStringList; ContainsIMO: boolean); function ClinicText(ALoc: integer): string; public { Public declarations } CloseOK: boolean; DisplayOrders: boolean; class procedure PrintLocation(OrderLst: TStringList; pEncounterLoc: integer; pEncounterLocName, pEncounterLocText: string; pEncounterDT: TFMDateTime; pEncounterVC: Char; var ClinicLst, WardLst: TStringList; var wardIEN: integer; var wardLocation: string; ContainsIMOOrders: boolean; displayEncSwitch: boolean = false); class procedure SwitchEncounterLoction(pEncounterLoc: integer; pEncounterLocName, pEncounterLocText: string; pEncounterDT: TFMDateTime; pEncounterVC: Char); class function rpcIsPatientOnWard(Patient: string): string; class function rpcIsClinicOrder(IEN: string): string; end; implementation {$R *.dfm} uses VAUtils; //fFrame; Const COL_ORDERINFO = 0; COL_ORDERTEXT = 1; COL_LOCATION = 2; TAB = #9; LOCATION_CHANGE_1 = 'The patient is admitted to ward'; LOCATION_CHANGE_2 = 'You have the chart open to a clinic location of'; LOCATION_CHANGE_2W = 'You have the chart open with the patient still on ward'; LOCATION_CHANGE_3 = 'What Location are these orders associated with?'; LOCATION_CHANGE_4 = 'The patient has now been admitted to ward: '; var frmPrintLocation: TfrmPrintLocation; // ClinicIEN, WardIen: integer; // ASvc, ClinicLocation, WardLocation: string; ClinicArr: TStringList; WardArr: TStringList; { TfrmPrintLocation } procedure TfrmPrintLocation.btnClinicClick(Sender: TObject); var i: integer; begin inherited; for i := 1 to self.orderGrid.RowCount do begin self.orderGrid.Cells[COL_LOCATION,i] := frmPrintLocation.CLoc; end; end; procedure TfrmPrintLocation.btnOKClick(Sender: TObject); var i: integer; Action: TCloseAction; begin if ClinicArr = nil then ClinicArr := TStringList.Create; if WardArr = nil then wardArr := TStringList.Create; if (frmPrintLocation.cboEncLoc.Enabled = true) and (frmPrintLocation.cboEncLoc.ItemIndex = -1) then begin infoBox('A location must be selected to continue processing patient data', 'Warning', MB_OK); exit; end; if frmPrintLocation.DisplayOrders = true then begin for i := 1 to self.orderGrid.RowCount-1 do begin if ValFor(COL_LOCATION, i) = '' then begin infoBox('Every order must have a location define.','Location error', MB_OK); exit; end; if ValFor(COL_LOCATION, i) = frmPrintLocation.CLoc then ClinicArr.Add(ValFor(COL_ORDERINFO, i)) else if ValFor(COL_LOCATION, i) = frmPrintLocation.WLoc then WardArr.Add(ValFor(COL_ORDERINFO, i)); end; end; CloseOK := True; Action := caFree; frmPrintLocation.FormClose(frmPrintLocation, Action); if Action = caFree then frmPrintLocation.Close; end; procedure TfrmPrintLocation.btnWardClick(Sender: TObject); var i: integer; begin inherited; for i := 1 to self.orderGrid.RowCount do begin self.orderGrid.Cells[COL_LOCATION,i] := frmPrintLocation.WLoc; end; end; procedure TfrmPrintLocation.cbolocationChange(Sender: TObject); begin self.orderGrid.Cells[COL_LOCATION, self.orderGrid.Row] := self.cbolocation.Text; end; procedure TfrmPrintLocation.cbolocationExit(Sender: TObject); begin cboLocation.Hide; end; procedure TfrmPrintLocation.FormClose(Sender: TObject; var Action: TCloseAction); var i :Integer; //Action1: TCloseAction; begin inherited; if not CloseOK then begin if ClinicArr = nil then ClinicArr := TStringList.Create; if WardArr = nil then wardArr := TStringList.Create; if (frmPrintLocation.cboEncLoc.Enabled = true) and (frmPrintLocation.cboEncLoc.ItemIndex = -1) then begin infoBox('A location must be selected to continue processing patient data', 'Warning', MB_OK); Action := caNone; exit; end; for i := 1 to self.orderGrid.RowCount-1 do begin if ValFor(COL_LOCATION, i) = '' then begin infoBox('Every order must have a location define.','Location error', MB_OK); Action := caNone; exit; end; if ValFor(COL_LOCATION, i) = frmPrintLocation.CLoc then ClinicArr.Add(ValFor(COL_ORDERINFO, i)) else if ValFor(COL_LOCATION, i) = frmPrintLocation.WLoc then WardArr.Add(ValFor(COL_ORDERINFO, i)); end; CloseOK := True; end; Action := caFree; end; procedure TfrmPrintLocation.FormDestroy(Sender: TObject); begin inherited; frmPrintLocation := nil; end; procedure TfrmPrintLocation.FormResize(Sender: TObject); begin inherited; pnlFieldsResize(Sender) end; function TfrmPrintLocation.ClinicText(ALoc: integer): string; var aStr: string; begin CallVistA('ORIMO ISCLOC', [ALoc], aStr); if (aStr = '1') then Result := LOCATION_CHANGE_2 else Result := LOCATION_CHANGE_2W; end; procedure TfrmPrintLocation.OrderGridDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); begin inherited; OrderGrid.Canvas.TextRect(Rect, Rect.Left+2, Rect.Top+2, Piece(OrderGrid.Cells[ACol, ARow], TAB, 1)); end; procedure TfrmPrintLocation.orderGridKeyPress(Sender: TObject; var Key: Char); begin inherited; if CharInSet(Key, [#32..#127]) then ShowEditor(OrderGrid.Col, OrderGrid.Row, Key); end; procedure TfrmPrintLocation.orderGridMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var ACol, ARow: Integer; begin inherited; OrderGrid.MouseToCell(X, Y, ACol, ARow); if (ARow < 0) or (ACol < 0) then Exit; if ACol > COL_ORDERINFO then ShowEditor(ACol, ARow, #0) else begin OrderGrid.Col := COL_ORDERTEXT; OrderGrid.Row := ARow; end; //if OrderGrid.Col <> COL_ORDERTEXT then //DropLastSequence; end; procedure TfrmPrintLocation.pnlFieldsResize(Sender: TObject); Const REL_ORDER = 0.85; REL_LOCATION = 0.15; var i, center, diff, ht, RowCountShowing: Integer; ColControl: TWinControl; begin inherited; if frmPrintLocation = nil then exit; with frmPrintLocation do begin if (frmPrintLocation.WLoc = '') and (frmPrintLocation.CLoc = '') then exit; lblText.Caption := LOCATION_CHANGE_1 + ': ' + frmPrintLocation.WLoc + CRLF; if frmPrintLocation.DisplayOrders = false then begin if frmPrintlocation.CLoc = '' then begin lblText.Caption := LOCATION_CHANGE_4 + frmPrintLocation.WLoc + CRLF; cboEncLoc.Enabled := false; lblEncounter.Enabled := false; end else lblText.Caption := lblText.Caption + ClinicText(frmPrintLocation.CIEN) + ': ' + frmPrintLocation.CLoc + CRLF; btnClinic.Visible := false; btnWard.Visible := false; pnlTop.Height := lbltext.Top + lbltext.Height * 2; pnlbottom.Top := pnltop.Top + pnltop.Height + 3; ordergrid.Height := 1; pnlBottom.Height := 1; lblEncounter.Top := pnlBottom.Top + pnlBottom.Height; cboEncLoc.Top := lblEncounter.Top; cboEncLoc.Left := lblEncounter.Left + lblEncounter.Width + 4; orpnlBottom.Top := cboEncLoc.Top + cboEncLoc.Height +10; end else begin lblText.Caption := lblText.Caption + ClinicText(frmPrintLocation.CIEN) + ': ' + frmPrintLocation.CLoc + CRLF + CRLF; lblText.Caption := lblText.Caption + LOCATION_CHANGE_3; //lblText.Caption := lblText.Caption + CRLF + 'One clinic location allowed; ' + frmPrintLocation.CLoc + ' will be used'; btnClinic.Caption := 'All ' + frmPrintLocation.CLoc; btnWard.Caption := 'All ' + frmPrintLocation.WLoc; btnClinic.Width := TextWidthByFont(btnClinic.Handle, btnClinic.Caption); btnWard.Width := TextWidthByFont(btnWard.Handle, btnWard.Caption); center := frmPrintLocation.Width div 2; btnClinic.Left := center - (btnClinic.Width + 3); btnWard.Left := center + 3; end; if pnlTop.Width > width then begin pnltop.Width := width - 8; orpnlTopBottom.Width := pnltop.Width; end; if orpnlTopBottom.Width > pnltop.Width then orpnlTopBottom.Width := pnltop.Width; if pnlBottom.Width > width then begin pnlBottom.Width := width - 8; ordergrid.Width := pnlBottom.Width - 2; end; if orderGrid.Width > pnlBottom.Width then orderGrid.Width := pnlBottom.Width - 2; if frmPrintLocation.DisplayOrders = true then begin i := OrderGrid.Width - 12; i := i - GetSystemMetrics(SM_CXVSCROLL); orderGrid.ColWidths[0] := 0; orderGrid.ColWidths[1] := Round(REL_ORDER * i); orderGrid.ColWidths[2] := Round(REL_LOCATION * i); orderGrid.Cells[1,0] := 'Order'; orderGrid.Cells[2,0] := 'Location'; cboEncLoc.Left := lblEncounter.Left + lblEncounter.Width + 4; ht := pnlBottom.Top - orderGrid.Top - 6; ht := ht div (orderGrid.DefaultRowHeight+1); ht := ht * (orderGrid.DefaultRowHeight+1); Inc(ht, 3); OrderGrid.Height := ht; ColControl := nil; Case OrderGrid.Col of COL_ORDERTEXT:ColCOntrol := pnlOrder; COL_LOCATION:ColControl := cboLocation; End; if assigned(ColControl) and ColControl.Showing then begin RowCountShowing := (Height - 25) div (orderGrid.defaultRowHeight+1); if (OrderGrid.Row <= RowCountShowing) then ShowEditor(OrderGrid.Col, orderGrid.Row, #0) else ColControl.Hide; end; end; diff := frmPrintLocation.btnOK.top; //diff := (frmPrintLocation.ORpnlBottom.Top + frmPrintlocation.btnOK.Top) - frmPrintLocation.ORpnlBottom.Top; frmPrintLocation.ORpnlBottom.Height := frmPrintLocation.btnOK.Top + frmPrintLocation.btnOK.Height + diff; frmprintLocation.Height := frmprintLocation.orpnlBottom.Top + frmprintLocation.orpnlBottom.Height + 25; end; end; class procedure TfrmPrintLocation.PrintLocation(OrderLst: TStringList; pEncounterLoc:integer; pEncounterLocName, pEncounterLocText: string; pEncounterDT: TFMDateTime; pEncounterVC: Char; var ClinicLst, WardLst: TStringList; var wardIEN: integer; var wardLocation: string; ContainsIMOOrders: boolean; displayEncSwitch: boolean = false); var ASvc, OrderInfo, OrderText: string; cidx, i, widx, count: integer; begin frmPrintLocation := TfrmPrintLocation.Create(Application); try count := 0; frmPrintLocation.DisplayOrders := true; frmPrintLocation.CloseOK := false; ClinicArr := TStringList.Create; WardArr := TStringList.Create; CurrentLocationForPatient(Patient.DFN, WardIEN, WardLocation, ASvc); frmPrintLocation.lblEncounter.Enabled := displayEncSwitch; frmPrintLocation.cboEncLoc.Enabled := displayEncSwitch; frmPrintLocation.Cloc := pEncounterLocName; frmPrintLocation.WLoc := WardLocation; frmPrintLocation.CIEN := pEncounterLoc; frmPrintLocation.WIEN := wardIEN; ResizeAnchoredFormToFont(frmPrintLocation); frmPrintLocation.orderGrid.DefaultRowHeight := frmPrintLocation.cbolocation.Height; for i := 0 to OrderLst.Count - 1 do begin OrderInfo := Piece(OrderLst.Strings[i],':',1); if frmPrintLocation.rpcIsClinicOrder(OrderInfo)='0' then begin count := count+1; frmPrintlocation.orderGrid.RowCount := count + 1; OrderText := AnsiReplaceText(Piece(OrderLst.Strings[i],':',2),CRLF,''); frmPrintLocation.orderGrid.Cells[COL_ORDERINFO,count] := OrderInfo; frmPrintLocation.orderGrid.Cells[COL_ORDERTEXT,count] := OrderText; end else begin ClinicLst.Add(OrderInfo); end; end; frmPrintlocation.orderGrid.RowCount := count + 1; frmPrintLocation.cbolocation.Items.Add(frmPrintLocation.CLoc); frmPrintLocation.cbolocation.Items.Add(frmPrintLocation.WLoc); if frmPrintLocation.cboEncLoc.Enabled = True then begin frmPrintLocation.cboEncLoc.Items.Add(frmPrintLocation.CLoc); frmPrintLocation.cboEncLoc.Items.Add(frmPrintLocation.WLoc); end; if count>0 then frmPrintLocation.ShowModal; if assigned(ClinicArr) then ClinicLst.AddStrings(ClinicArr); if assigned(WardArr) then WardLst.AddStrings(WardArr); frmPrintLocation.ProcessClinicOrders(WardLst, ClinicLst, WardIEN, pEncounterLoc, ContainsIMOOrders); cidx := frmPrintLocation.cboEncLoc.Items.IndexOf(frmPrintLocation.CLoc); widx := frmPrintLocation.cboEncLoc.Items.IndexOf(frmPrintLocation.WLoc); if frmPrintLocation.cboEncLoc.ItemIndex = cidx then begin uCore.Encounter.EncounterSwitch(pEncounterLoc, pEncounterLocName, pEncounterLocText, pEncounterDT, pEncounterVC); fframe.frmFrame.DisplayEncounterText; fframe.frmFrame.OrderPrintForm := True; end else if frmPrintLocation.cboEncLoc.ItemIndex = widx then begin uCore.Encounter.EncounterSwitch(WardIEN, WardLocation, WardLocation, Patient.AdmitTime, 'H'); fFrame.frmFrame.DisplayEncounterText; end; finally frmPrintLocation.Destroy; end; end; procedure TfrmPrintLocation.ProcessClinicOrders(WardList, ClinicList: TStringList; WardIEN, ClinicIEN: integer; ContainsIMO: boolean); var i: integer; OrderArr: TStringList; begin OrderArr := TStringList.Create; for i := 0 to WardList.Count -1 do begin OrderArr.Add(WardList.Strings[i] + U + InttoStr(WardIen)); end; for i := 0 to ClinicList.Count -1 do begin OrderArr.Add(ClinicList.Strings[i] + U + InttoStr(ClinicIen)); end; rpcChangeOrderLocation(OrderArr, ContainsIMO); WardArr.Free; end; procedure TfrmPrintLocation.rpcChangeOrderLocation(pOrderList:TStringList; ContainsIMO: boolean); var IMO: string; begin // OrderIEN^Location^ISIMO -- used to alter location if ward is selected. if ContainsIMO = True then IMO := '1' else IMO := '0'; CallVistA('ORWDX CHANGE',[pOrderList, Patient.DFN, IMO]); end; class function TfrmPrintLocation.rpcIsPatientOnWard(Patient: string): string; begin // Ward Loction Name^Ward Location IEN CallVistA('ORWDX1 PATWARD', [Patient], Result); end; class function TfrmPrintLocation.rpcIsClinicOrder(IEN: string): string; begin CallVistA('ORUTL ISCLORD', [IEN], Result); end; procedure TfrmPrintLocation.ShowEditor(ACol, ARow: Integer; AChar: Char); var tmpText: string; procedure PlaceControl(AControl: TWinControl); var ARect: TRect; begin with AControl do begin ARect := OrderGrid.CellRect(ACol, ARow); SetBounds(ARect.Left + OrderGrid.Left + 1, ARect.Top + OrderGrid.Top + 1, ARect.Right - ARect.Left + 1, ARect.Bottom - ARect.Top + 1); Tag := ARow; BringToFront; Show; SetFocus; end; end; procedure SynchCombo(ACombo: TORComboBox; const ItemText, EditText: string); var i: Integer; begin ACombo.ItemIndex := -1; for i := 0 to Pred(ACombo.Items.Count) do if ACombo.Items[i] = ItemText then ACombo.ItemIndex := i; if ACombo.ItemIndex < 0 then ACombo.Text := EditText; end; begin inherited; if ARow = 0 then Exit; Case ACol of COL_LOCATION: begin TmpText := ValFor(COL_Location, ARow); SynchCombo(cboLocation, tmpText, tmpText); PlaceControl(cboLocation); end; end; end; class procedure TfrmPrintLocation.SwitchEncounterLoction(pEncounterLoc: integer; pEncounterLocName, pEncounterLocText: string; pEncounterDT: TFMDateTime; pEncounterVC: Char); var cidx, widx, WardIEN: integer; Asvc, WardLocation: string; begin frmPrintLocation := TfrmPrintLocation.Create(Application); try frmPrintLocation.DisplayOrders := false; frmPrintLocation.CloseOK := false; CurrentLocationForPatient(Patient.DFN, WardIEN, WardLocation, ASvc); frmPrintLocation.lblEncounter.Enabled := True; frmPrintLocation.cboEncLoc.Enabled := True; frmPrintLocation.Cloc := pEncounterLocName; frmPrintLocation.WLoc := WardLocation; frmPrintLocation.CIEN := pEncounterLoc; frmPrintLocation.WIEN := wardIEN; ResizeAnchoredFormToFont(frmPrintLocation); frmPrintLocation.cboEncLoc.Items.Add(frmPrintLocation.CLoc); frmPrintLocation.cboEncLoc.Items.Add(frmPrintLocation.WLoc); frmPrintLocation.Caption := 'Refresh Encounter Location Form'; frmPrintLocation.ShowModal; cidx := frmPrintLocation.cboEncLoc.Items.IndexOf(frmPrintLocation.CLoc); widx := frmPrintLocation.cboEncLoc.Items.IndexOf(frmPrintLocation.WLoc); if frmPrintLocation.cboEncLoc.Enabled = FALSE then frmPrintLocation.cboEncLoc.ItemIndex := widx; if frmPrintLocation.cboEncLoc.ItemIndex = cidx then begin Encounter.Location := pEncounterLoc; Encounter.LocationName := pEncounterLocName; Encounter.LocationText := pEncounterLocText; fframe.frmFrame.DisplayEncounterText; end else if frmPrintLocation.cboEncLoc.ItemIndex = widx then begin uCore.Encounter.EncounterSwitch(WardIEN, WardLocation, '', Patient.AdmitTime, 'H'); fFrame.frmFrame.DisplayEncounterText; end; finally frmPrintLocation.Destroy; end; end; function TfrmPrintLocation.ValFor(FieldID, ARow: Integer): string; begin Result := ''; if (ARow < 1) or (ARow >= OrderGrid.RowCount) then Exit; with OrderGrid do case FieldID of COL_ORDERINFO : Result := Piece(Cells[COL_ORDERINFO, ARow], TAB, 1); COL_ORDERTEXT : Result := Piece(Cells[COL_ORDERTEXT, ARow], TAB, 1); COL_LOCATION : Result := Piece(Cells[COL_LOCATION, ARow], TAB, 1); end; end; end.
unit UnLancarDebitoView; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, DB, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, JvExStdCtrls, JvEdit, JvValidateEdit, { Fluente } Util, UnComandaModelo, SearchUtil, Pagamentos, UnTeclado; type TLancarDebitoView = class(TForm) Label1: TLabel; EdtValor: TJvValidateEdit; btnOk: TPanel; Label2: TLabel; edtCartaoDebito: TEdit; pnlCartaoDebitoPesquisa: TPanel; procedure btnOkClick(Sender: TObject); procedure EdtValorEnter(Sender: TObject); procedure EdtValorExit(Sender: TObject); private FModelo: IPagamentoCartaoDeDebito; FCartaoDebitoPesquisa: TPesquisa; FTeclado: TTeclado; public function Modelo(const Modelo: IPagamentoCartaoDeDebito): TLancarDebitoView; function Descarregar: TLancarDebitoView; function Preparar: TLancarDebitoView; procedure ProcessarSelecaoCartaoDebito(Sender: TObject); end; var LancarDebitoView: TLancarDebitoView; implementation {$R *.dfm} procedure TLancarDebitoView.btnOkClick(Sender: TObject); var _dataSet: TDataSet; begin _dataSet := Self.FCartaoDebitoPesquisa.Modelo.DataSet; Self.FModelo.RegistrarPagamentoCartaoDeDebito( TMap.Create .Gravar('valor', Self.EdtValor.AsCurrency) .Gravar('cart_oid', _dataSet.FieldByName('cart_oid').AsString) .Gravar('cart_cod', _dataSet.FieldByName('cart_cod').AsString) ); Self.ModalResult := mrOk; end; function TLancarDebitoView.Modelo( const Modelo: IPagamentoCartaoDeDebito): TLancarDebitoView; begin Self.FModelo := Modelo; Result := Self; end; function TLancarDebitoView.Descarregar: TLancarDebitoView; begin Self.FCartaoDebitoPesquisa.Descarregar; FreeAndNil(Self.FCartaoDebitoPesquisa); Result := Self; end; procedure TLancarDebitoView.EdtValorEnter(Sender: TObject); begin if Self.FTeclado = nil then begin Self.FTeclado := TTeclado.Create(nil); Self.FTeclado.Top := Self.Height - Self.FTeclado.Height; Self.FTeclado.Parent := Self; Self.FTeclado.ControleDeEdicao(Sender as TCustomEdit); end; Self.FTeclado.Visible := True; end; procedure TLancarDebitoView.EdtValorExit(Sender: TObject); begin if Self.FTeclado <> nil then Self.FTeclado.Visible := True; end; function TLancarDebitoView.Preparar: TLancarDebitoView; begin Self.EdtValor.Value := Self.FModelo.Parametros.Ler('total').ComoDecimal; Self.FCartaoDebitoPesquisa := TConstrutorDePesquisas .Formulario(Self) .ControleDeEdicao(Self.EdtCartaoDebito) .PainelDePesquisa(Self.pnlCartaoDebitoPesquisa) .Modelo('CartaoDebitoModeloPesquisa') .AcaoAposSelecao(Self.ProcessarSelecaoCartaoDebito) .Construir; Result := Self; end; procedure TLancarDebitoView.ProcessarSelecaoCartaoDebito(Sender: TObject); var _event: TNotifyEvent; _dataSet: TDataSet; begin _event := Self.EdtCartaoDebito.OnChange; Self.EdtCartaoDebito.OnChange := nil; _dataSet := Self.FCartaoDebitoPesquisa.Modelo.DataSet; Self.EdtCartaoDebito.Text := _dataSet.FieldByName('cart_cod').AsString; Self.EdtCartaoDebito.OnChange := _event; end; end.
unit ProductCategoriesMemTable; interface uses FireDAC.Comp.Client, DSWrap, System.Classes, System.Generics.Collections; type TProductCategoriesW = class(TDSWrap) private FProductCategoryID: TFieldWrap; FCategory: TFieldWrap; FExternalID: TFieldWrap; FChecked: TFieldWrap; public constructor Create(AOwner: TComponent); override; property ProductCategoryID: TFieldWrap read FProductCategoryID; property Category: TFieldWrap read FCategory; property ExternalID: TFieldWrap read FExternalID; property Checked: TFieldWrap read FChecked; end; TProductCategoriesMemTbl = class(TFDMemTable) private FW: TProductCategoriesW; public constructor Create(AOwner: TComponent); override; procedure Add(AProductCategoryID: Integer; AExternalID, ACategory: string); function GetChecked: TArray<Integer>; property W: TProductCategoriesW read FW; end; implementation uses Data.DB, FireDAC.Comp.DataSet, System.Variants, System.SysUtils; constructor TProductCategoriesW.Create(AOwner: TComponent); begin inherited; FProductCategoryID := TFieldWrap.Create(Self, 'ProductCategoryID', '', True); FCategory := TFieldWrap.Create(Self, 'Category', 'Категория'); FExternalID := TFieldWrap.Create(Self, 'ExternalID', 'Идентификатор'); FChecked := TFieldWrap.Create(Self, 'Checked', 'X'); end; constructor TProductCategoriesMemTbl.Create(AOwner: TComponent); //var // AFDIndex: TFDIndex; begin inherited; FW := TProductCategoriesW.Create(Self); FieldDefs.Add(W.ProductCategoryID.FieldName, ftInteger); FieldDefs.Add(W.Checked.FieldName, ftInteger); FieldDefs.Add(W.ExternalID.FieldName, ftWideString, 20); FieldDefs.Add(W.Category.FieldName, ftWideString, 200); { AFDIndex := Indexes.Add; AFDIndex.Name := 'by_' + W.ProductCategoryID.FieldName; AFDIndex.Fields := W.ProductCategoryID.FieldName; AFDIndex.Distinct := True; AFDIndex.Active := True; AFDIndex.Selected := True; } CreateDataSet; Open; end; procedure TProductCategoriesMemTbl.Add(AProductCategoryID: Integer; AExternalID, ACategory: string); var V: Variant; begin V := LookupEx(W.ProductCategoryID.FieldName, AProductCategoryID, W.ProductCategoryID.FieldName); if not VarIsNull(V) then Exit; W.TryAppend; W.Checked.F.AsInteger := 1; W.ProductCategoryID.F.AsInteger := AProductCategoryID; W.ExternalID.F.AsString := AExternalID; W.Category.F.AsString := ACategory; W.TryPost; // Пытаемся сохранить end; function TProductCategoriesMemTbl.GetChecked: TArray<Integer>; var AClone: TFDMemTable; AIntList: TList<Integer>; begin AIntList := TList<Integer>.Create; AClone := W.AddClone(Format('%s = %d', [W.Checked.FieldName, 1])); try while not AClone.Eof do begin AIntList.Add( W.PK.AsInteger ); AClone.Next; end; Result := AIntList.ToArray; finally W.DropClone(AClone); FreeAndNil(AIntList); end; end; end.
unit bool_func_and_3; interface implementation function GetBool(Value: Boolean): Boolean; begin Result := Value; end; var B: Boolean = True; procedure Test; begin B := GetBool(True) and GetBool(False); end; initialization Test(); finalization Assert(not B); end.
unit App.IHandlerCore; interface uses Net.ConnectedClient, WebServer.HTTPConnectedClient, System.SysUtils; type IBaseHandler = interface procedure HandleReceiveTCPData(From: TConnectedClient; const ABytes: TBytes); procedure HandleReceiveHTTPData(From: TConnectedClient; const ABytes: TBytes); procedure HandleCommand(Command: Byte; args: array of string); procedure HandleConnectClient(ClientName: String); procedure HandleDisconnectClient(ClientName: String); end; implementation end.
unit clsTUsuarioDAO; {$M+} {$TYPEINFO ON} interface uses System.SysUtils, System.Classes, clsTDBUtils, clsTUsuarioDTO; type TUsuarioDAO = class private FDBUtils: TDBUtils; function GetLastID: Integer; public constructor Create; destructor Destroy; override; published property DBUtils: TDBUtils read FDBUtils; // function Get(const ID: Integer): TUsuarioDTO; overload; function Get(const EMail: String): TUsuarioDTO; function Post(const ID: Integer; const Usuario: TUsuarioDTO): Boolean; function Put(var Usuario: TUsuarioDTO): Boolean; function Delete(const ID: Integer): Boolean; overload; end; implementation { TUsuarioDAO } constructor TUsuarioDAO.Create; begin Self.FDBUtils := TDBUtils.Create; end; destructor TUsuarioDAO.Destroy; begin Self.FDBUtils.Free; inherited; end; function TUsuarioDAO.Delete(const ID: Integer): Boolean; var q: TColDevQuery; begin Result := False; try q:=Self.FDBUtils.QueryFactory('DELETE FROM USUARIOS.USUARIOS WHERE ID_USUARIO = '+IntToStr(ID)); q.ExecSQL; FreeAndNil(q); Result := True; except on E:Exception do begin FreeAndNil(q); // raise Exception.Create('Impossível excluir o usuário - erro : '+E.Message); end; end; end; { function TUsuarioDAO.Get(const ID: Integer): TUsuarioDTO; var q: TColDevQuery; begin try q:=Self.FDBUtils.QueryFactory('SELECT * FROM USUARIOS.USUARIOS WHERE ID_USUARIO ='+IntToStr(ID)); q.Open; if not q.Eof then begin Result := TUsuarioDTO.Create; Result.ID := q.Fields.FieldByName('id_usuario').AsInteger; Result.Nome := q.Fields.FieldByName('nome').AsString; Result.Nasc := q.Fields.FieldByName('nasc').AsDateTime; Result.Email := q.Fields.FieldByName('email').AsString; end; FreeAndNil(q); except on E:Exception do begin FreeAndNil(q); raise Exception.Create('Impossível recuperar o usuário - erro : '+E.Message); end; end; end; } function TUsuarioDAO.Get(const EMail: String): TUsuarioDTO; var q: TColDevQuery; begin Result := TUsuarioDTO.Create; try q:=Self.FDBUtils.QueryFactory('SELECT * FROM USUARIOS.USUARIOS WHERE EMAIL ='+QuotedStr(EMail), True); if not q.Eof then begin Result.ID := q.Fields.FieldByName('id_usuario').AsInteger; Result.Nome := q.Fields.FieldByName('nome').AsString; Result.Nasc := q.Fields.FieldByName('nasc').AsDateTime; Result.Email := q.Fields.FieldByName('email').AsString; end; FreeAndNil(q); except on E:Exception do begin FreeAndNil(q); raise Exception.Create('Impossível recuperar o usuário - erro : '+E.Message); end; end; end; function TUsuarioDAO.GetLastID: Integer; var q: TColDevQuery; begin try q:=Self.FDBUtils.QueryFactory('select nextval('+QuotedStr('usuarios.seq_id_usuario')+')'); q.Open; Result := q.Fields.Fields[0].AsInteger; FreeAndNil(q); except on E:Exception do begin FreeAndNil(q); raise Exception.Create('Impossível recuperar novo ID para usuário - erro : '+E.Message); end; end; end; function TUsuarioDAO.Post(const ID: Integer; const Usuario: TUsuarioDTO): Boolean; var q: TColDevQuery; begin Result := False; try q:=Self.FDBUtils.QueryFactory('SELECT * FROM USUARIOS.USUARIOS WHERE ID_USUARIO ='+IntToStr(ID)); q.Open; if not q.Eof then begin q.Edit; q.Fields.FieldByName('nome').AsString := Usuario.Nome; q.Fields.FieldByName('nasc').AsDateTime := Usuario.Nasc; q.Fields.FieldByName('email').AsString := Usuario.Email; q.Post; end; FreeAndNil(q); Result := True; except on E:Exception do begin FreeAndNil(q); //raise Exception.Create('Impossível atualizar o usuário - erro : '+E.Message); end; end; end; function TUsuarioDAO.Put(var Usuario: TUsuarioDTO): Boolean; var q: TColDevQuery; begin Result := False; try q:=Self.FDBUtils.QueryFactory('SELECT * FROM USUARIOS.USUARIOS LIMIT 1'); q.Open; q.Insert; q.FieldByName('id_usuario').AsInteger := Self.GetLastID; Usuario.ID := q.FieldByName('id_usuario').AsInteger; q.FieldByName('nome').AsString := Usuario.Nome; q.FieldByName('email').AsString := Usuario.Email; q.FieldByName('nasc').AsDateTime := Usuario.Nasc; q.Post; FreeAndNil(q); Result := True; except on E:Exception do begin FreeAndNil(q); // raise Exception.Create('Impossível incluir o usuário - erro : '+E.Message); end; end; end; end.
{* ------------------------------------------------------------------------ * * Command Parttern ♥ TAsyncCommand * ------------------------------------------------------------------------ *} unit Pattern.AsyncCommand; interface uses System.Classes, System.SysUtils, System.TypInfo, System.Diagnostics, System.TimeSpan, Vcl.ExtCtrls, // TTimer (VCL) Pattern.Command; type TAsyncCommand = class(TCommand) private const Version = '1.0'; private fUpdateInterval: integer; fOnUpdateProc: TProc; procedure OnUpdateTimer(Sender: TObject); protected fBeforeStartEvent: TProc; fAfterFinishEvent: TProc; fThread: TThread; fIsCommandDone: boolean; fTimer: TTimer; procedure Synchronize(aProc: TThreadProcedure); function GetIsCommandDone: boolean; procedure SetIsCommandDone(aIsTermianted: boolean); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function WithInjections(const Injections: array of const): TAsyncCommand; function WithEventBeforeStart(aBeforeStart: TProc): TAsyncCommand; function WithEventAfterFinish(aAfterFinish: TProc): TAsyncCommand; function WithEventOnUpdate(aOnUpdateProc: TProc): TAsyncCommand; procedure Execute; override; procedure Terminate; function IsBusy: boolean; override; function IsTerminated: boolean; property UpdateInterval: integer read fUpdateInterval write fUpdateInterval; end; implementation // ------------------------------------------------------------------------ // TAsyncCommand // ------------------------------------------------------------------------ constructor TAsyncCommand.Create(AOwner: TComponent); begin inherited; fThread := nil; fBeforeStartEvent := nil; fAfterFinishEvent := nil; fIsCommandDone := true; fUpdateInterval := 100; // --- Timer --- fTimer := TTimer.Create(nil); fTimer.Enabled := false; fTimer.Interval := fUpdateInterval; fTimer.OnTimer := OnUpdateTimer; end; destructor TAsyncCommand.Destroy; begin Self.IsBusy; // call to tear down all internal structures fTimer.Free; inherited; end; procedure TAsyncCommand.Execute; begin SetIsCommandDone(false); DoGuard; fThread := TThread.CreateAnonymousThread( procedure begin TThread.NameThreadForDebugging('Command: ' + Self.ClassName); try SetIsCommandDone(false); DoExecute; finally SetIsCommandDone(true); end; end); fThread.FreeOnTerminate := false; fTimer.Enabled := True; if Assigned(fBeforeStartEvent) then fBeforeStartEvent(); fStopwatch := TStopwatch.StartNew; fThread.Start; end; function TAsyncCommand.GetIsCommandDone: boolean; begin TMonitor.Enter(Self); try Result := fIsCommandDone; finally TMonitor.Exit(Self); end; end; procedure TAsyncCommand.SetIsCommandDone(aIsTermianted: boolean); begin TMonitor.Enter(Self); try fIsCommandDone := aIsTermianted; finally TMonitor.Exit(Self); end; end; function TAsyncCommand.IsBusy: boolean; var IsCommandDone: boolean; begin IsCommandDone := GetIsCommandDone; if IsCommandDone and (fThread <> nil) then begin fTimer.Enabled := False; FreeAndNil (fThread); fStopwatch.Stop; if Assigned(fAfterFinishEvent) then fAfterFinishEvent(); end; Result := not IsCommandDone; end; function TAsyncCommand.IsTerminated: boolean; begin Result := TThread.CheckTerminated; end; procedure TAsyncCommand.OnUpdateTimer(Sender: TObject); begin fTimer.Enabled := Self.IsBusy; if fTimer.Enabled and Assigned(fOnUpdateProc) then fOnUpdateProc; end; procedure TAsyncCommand.Synchronize(aProc: TThreadProcedure); begin if (fThread <> nil) and Assigned(aProc) then TThread.Synchronize(fThread, aProc); end; procedure TAsyncCommand.Terminate; begin if (fThread<>nil) and not GetIsCommandDone then fThread.Terminate; end; function TAsyncCommand.WithInjections(const Injections: array of const): TAsyncCommand; begin TComponentInjector.InjectProperties(Self, Injections); Result := Self; end; function TAsyncCommand.WithEventAfterFinish(aAfterFinish: TProc): TAsyncCommand; begin fAfterFinishEvent := aAfterFinish; Result := Self; end; function TAsyncCommand.WithEventBeforeStart(aBeforeStart: TProc): TAsyncCommand; begin fBeforeStartEvent := aBeforeStart; Result := Self; end; function TAsyncCommand.WithEventOnUpdate(aOnUpdateProc: TProc): TAsyncCommand; begin fOnUpdateProc := aOnUpdateProc; Result := Self; end; end.
unit SoccerTests.VotingRulePreferenceListTests; interface uses System.SysUtils, System.Generics.Collections, Soccer.Voting.Preferences, Soccer.Voting.RulePreferenceList, Soccer.Voting.AbstractRule, DUnitX.TestFramework; type [TestFixture] TVotingRulePreferenceListTests = class(TObject) public [SetupFixture] procedure InitilaizeEncodings; [Test] procedure InsertTwoRules; [Test] procedure InsertTwoRules2; end; TFirstRule = class(TInterfacedObject, ISoccerVotingRule) public function GetName: string; function ExecuteOn(AProfile: TSoccerVotingVotersPreferences; out Winners: System.Generics.Collections.TList<string>): Boolean; end; TSecondRule = class(TInterfacedObject, ISoccerVotingRule) public function GetName: string; function ExecuteOn(AProfile: TSoccerVotingVotersPreferences; out Winners: System.Generics.Collections.TList<string>): Boolean; end; implementation { TVotingRulePreferenceListTests } procedure TVotingRulePreferenceListTests.InitilaizeEncodings; begin TEncoding.Unicode; TEncoding.BigEndianUnicode; end; procedure TVotingRulePreferenceListTests.InsertTwoRules; var LList: TSoccerVotingRulePreferenceList; LRule1, LRule2: ISoccerVotingRule; begin LList := TSoccerVotingRulePreferenceList.Create ('..\..\testdata\rulepreferencelisttests.soccfg'); LRule1 := TFirstRule.Create; LRule2 := TSecondRule.Create; LList.Add(LRule2); LList.Add(LRule1); Assert.IsTrue(LList.Count = 2); Assert.IsTrue(LList.Items[0].GetName = 'first'); Assert.IsTrue(LList.Items[1].GetName = 'second'); FreeAndNil(LList); end; procedure TVotingRulePreferenceListTests.InsertTwoRules2; var LList: TSoccerVotingRulePreferenceList; LRule1, LRule2: ISoccerVotingRule; begin LList := TSoccerVotingRulePreferenceList.Create ('..\..\testdata\rulepreferencelisttests.soccfg'); LRule1 := TFirstRule.Create; LRule2 := TSecondRule.Create; LList.Add(LRule1); LList.Add(LRule2); Assert.IsTrue(LList.Count = 2); Assert.IsTrue(LList.Items[0].GetName = 'first'); Assert.IsTrue(LList.Items[1].GetName = 'second'); FreeAndNil(LList); end; { TSecondRule } function TSecondRule.ExecuteOn(AProfile: TSoccerVotingVotersPreferences; out Winners: System.Generics.Collections.TList<string>): Boolean; begin Result := false; end; function TSecondRule.GetName: string; begin Result := 'second'; end; { TFirstRule } function TFirstRule.ExecuteOn(AProfile: TSoccerVotingVotersPreferences; out Winners: System.Generics.Collections.TList<string>): Boolean; begin Result := false; end; function TFirstRule.GetName: string; begin Result := 'first'; end; initialization TDUnitX.RegisterTestFixture(TVotingRulePreferenceListTests); end.
(* * Copyright(c) 2019 Embarcadero Technologies, Inc. * * This code was generated by the TaskGen tool from file * "CLANGTask.xml" * Version: 26.0.0.0 * Runtime Version: v4.0.30319 * Changes to this file may cause incorrect behavior and will be * overwritten when the code is regenerated. *) unit CLANGStrs; interface const sTaskName = 'clang'; // CLANGPreprocessor sRunPreprocessor = 'CLANG_RunPreprocessor'; // DirectoriesAndConditionals 64 sDefines = 'CLANG_Defines'; sInternalDefines = 'CLANG_InternalDefines'; sUndefines = 'CLANG_Undefines'; sTargetOutputDir = 'CLANG_TargetOutputDir'; sOutputDir = 'CLANG_OutputDir'; sSysRoot = 'CLANG_SysRoot'; sIWithSysRoot = 'CLANG_IWithSysRoot'; sIDirAfter = 'CLANG_IDirAfter'; sIncludePath = 'CLANG_IncludePath'; sSysIncludePath = 'CLANG_SysIncludePath'; sSystemIncludePath = 'CLANG_SystemIncludePath'; sFrameworkRoot = 'CLANG_FrameworkRoot'; sWindowsVersionDefines = 'CLANG_WindowsVersionDefines'; sWindowsVersionDefines_Unspecified = 'Unspecified'; sWindowsVersionDefines_NTDDI_VERSION_NTDDI_LONGHORN__WIN32_WINNT__WIN32_WINNT_LONGHORN = 'NTDDI_VERSION=NTDDI_LONGHORN;_WIN32_WINNT=_WIN32_WINNT_LONGHORN'; sWindowsVersionDefines_NTDDI_VERSION_NTDDI_WS03SP1__WIN32_WINNT__WIN32_WINNT_WS03 = 'NTDDI_VERSION=NTDDI_WS03SP1;_WIN32_WINNT=_WIN32_WINNT_WS03'; sWindowsVersionDefines_NTDDI_VERSION_NTDDI_WS03__WIN32_WINNT__WIN32_WINNT_WS03 = 'NTDDI_VERSION=NTDDI_WS03;_WIN32_WINNT=_WIN32_WINNT_WS03'; sWindowsVersionDefines_NTDDI_VERSION_NTDDI_WINXPSP2__WIN32_WINNT__WIN32_WINNT_WINXP = 'NTDDI_VERSION=NTDDI_WINXPSP2;_WIN32_WINNT=_WIN32_WINNT_WINXP'; sWindowsVersionDefines_NTDDI_VERSION_NTDDI_WINXPSP1__WIN32_WINNT__WIN32_WINNT_WINXP = 'NTDDI_VERSION=NTDDI_WINXPSP1;_WIN32_WINNT=_WIN32_WINNT_WINXP'; sWindowsVersionDefines_NTDDI_VERSION_NTDDI_WINXP__WIN32_WINNT__WIN32_WINNT_WINXP = 'NTDDI_VERSION=NTDDI_WINXP;_WIN32_WINNT=_WIN32_WINNT_WINXP'; sWindowsVersionDefines_NTDDI_VERSION_NTDDI_WIN2KSP4__WIN32_WINNT__WIN32_WINNT_WIN2K = 'NTDDI_VERSION=NTDDI_WIN2KSP4;_WIN32_WINNT=_WIN32_WINNT_WIN2K'; sWindowsVersionDefines_NTDDI_VERSION_NTDDI_WIN2KSP3__WIN32_WINNT__WIN32_WINNT_WIN2K = 'NTDDI_VERSION=NTDDI_WIN2KSP3;_WIN32_WINNT=_WIN32_WINNT_WIN2K'; sWindowsVersionDefines_NTDDI_VERSION_NTDDI_WIN2KSP2__WIN32_WINNT__WIN32_WINNT_WIN2K = 'NTDDI_VERSION=NTDDI_WIN2KSP2;_WIN32_WINNT=_WIN32_WINNT_WIN2K'; sWindowsVersionDefines_NTDDI_VERSION_NTDDI_WIN2KSP1__WIN32_WINNT__WIN32_WINNT_WIN2K = 'NTDDI_VERSION=NTDDI_WIN2KSP1;_WIN32_WINNT=_WIN32_WINNT_WIN2K'; sWindowsVersionDefines_NTDDI_VERSION_NTDDI_WIN2K__WIN32_WINNT__WIN32_WINNT_WIN2K = 'NTDDI_VERSION=NTDDI_WIN2K;_WIN32_WINNT=_WIN32_WINNT_WIN2K'; sWindowsVersionDefines__WIN32_WINDOWS_0x500_WINVER_0x500 = '_WIN32_WINDOWS=0x500;WINVER=0x500'; sWindowsVersionDefines__WIN32_WINDOWS_0x410_WINVER_0x410 = '_WIN32_WINDOWS=0x410;WINVER=0x410'; sWindowsVersionDefines__WIN32_WINDOWS_0x400_WINVER_0x400 = '_WIN32_WINDOWS=0x400;WINVER=0x400'; sAddProjectDirToIncludePath = 'CLANG_AddProjectDirToIncludePath'; // CLANGDebugging sSourceDebuggingOn = 'CLANG_SourceDebuggingOn'; sExternalTypes = 'CLANG_ExternalTypes'; // GeneralCompilation sBorlandExtensions = 'CLANG_BorlandExtensions'; sBorlandDiagnosticFormat = 'CLANG_BorlandDiagnosticFormat'; sBorlandRTTI = 'CLANG_BorlandRTTI'; sBorlandAutoRefCount = 'CLANG_BorlandAutoRefCount'; sCatchUndefinedBehavior = 'CLANG_CatchUndefinedBehavior'; sNoBuiltInc = 'CLANG_NoBuiltInc'; sNoImplicitFloat = 'CLANG_NoImplicitFloat'; sNoStdSystemInc = 'CLANG_NoStdSystemInc'; sTargetTriple = 'CLANG_TargetTriple'; sShortEnum = 'CLANG_ShortEnum'; sDisableCPPAccesControls = 'CLANG_DisableCPPAccesControls'; sDisableRttiGenerationInfo = 'CLANG_DisableRttiGenerationInfo'; sEmitPCH = 'CLANG_EmitPCH'; sIncludePCH = 'CLANG_IncludePCH'; sEmitNativeObject = 'CLANG_EmitNativeObject'; sEmitNativeAssembly = 'CLANG_EmitNativeAssembly'; sUseBorlandABI = 'CLANG_UseBorlandABI'; sGenObjFileUsingLLVM = 'CLANG_GenObjFileUsingLLVM'; sEmitConstructorAliases = 'CLANG_EmitConstructorAliases'; sRelocationModel = 'CLANG_RelocationModel'; sUsePosIndCodeForObjectFile = 'CLANG_UsePosIndCodeForObjectFile'; sGenVerboseAssemblyOutput = 'CLANG_GenVerboseAssemblyOutput'; sTargetABI = 'CLANG_TargetABI'; sTargetCPU = 'CLANG_TargetCPU'; sTargetCPU_arm7tdmi = 'arm7tdmi'; sTargetCPU_arm10tdmi = 'arm10tdmi'; sTargetCPU_arm1022e = 'arm1022e'; sTargetCPU_arm926ej_s = 'arm926ej-s'; sTargetCPU_arm1176jzf_s = 'arm1176jzf-s'; sTargetCPU_arm1156t2_s = 'arm1156t2-s'; sTargetCPU_cortex_m0 = 'cortex-m0'; sTargetCPU_cortex_a8 = 'cortex-a8'; sTargetCPU_cortex_m4 = 'cortex-m4'; sTargetCPU_cortex_a9_mp = 'cortex-a9-mp'; sTargetCPU_swift = 'swift'; sTargetCPU_cortex_m3 = 'cortex-m3'; sTargetCPU_ep9312 = 'ep9312'; sTargetCPU_iwmmxt = 'iwmmxt'; sTargetCPU_xscale = 'xscale'; sUseFloatABI = 'CLANG_UseFloatABI'; sUseFloatABI_Unspecified = 'Unspecified'; sUseFloatABI_soft = 'soft'; sUseFloatABI_softfp = 'softfp'; sUseFloatABI_hard = 'hard'; sOnlyFramePointer = 'CLANG_OnlyFramePointer'; sFunctionSections = 'CLANG_FunctionSections'; sUseSoftFloatingPoint = 'CLANG_UseSoftFloatingPoint'; sNotUseCppHeaders = 'CLANG_NotUseCppHeaders'; sDefineDeprecatedMacros = 'CLANG_DefineDeprecatedMacros'; sMacMessageLenght = 'CLANG_MacMessageLenght'; sEnableBlocksLangFeature = 'CLANG_EnableBlocksLangFeature'; sUseSjLjExcpetions = 'CLANG_UseSjLjExcpetions'; sUseMappableDiagnostics = 'CLANG_UseMappableDiagnostics'; sUseColorsDiagnostics = 'CLANG_UseColorsDiagnostics'; sEmitLLVM = 'CLANG_EmitLLVM'; sEnableExceptions = 'CLANG_EnableExceptions'; sEnableCPPExceptions = 'CLANG_EnableCPPExceptions'; sSEH = 'CLANG_SEH'; sUnwindTables = 'CLANG_UnwindTables'; sDisableFramePtrElimOpt = 'CLANG_DisableFramePtrElimOpt'; sStackRealign = 'CLANG_StackRealign'; sCPPCompileAlways = 'CLANG_CPPCompileAlways'; sEnableBatchCompilation = 'CLANG_EnableBatchCompilation'; sStopBatchAfterWarnings = 'CLANG_StopBatchAfterWarnings'; sStopBatchAfterErrors = 'CLANG_StopBatchAfterErrors'; sStopBatchAfterFirstError = 'CLANG_StopBatchAfterFirstError'; sDisableSpellChecking = 'CLANG_DisableSpellChecking'; sNo__cxa_atexit_ForDestructors = 'CLANG_No__cxa_atexit_ForDestructors'; sNoThreadsafeStatics = 'CLANG_NoThreadsafeStatics'; sMainFileName = 'CLANG_MainFileName'; sInputLanguageType = 'CLANG_InputLanguageType'; sInputLanguageType_c__ = 'c++'; sInputLanguageType_c = 'c'; sLanguageStandard = 'CLANG_LanguageStandard'; sLanguageStandard_c89 = 'c89'; sLanguageStandard_c90 = 'c90'; sLanguageStandard_c99 = 'c99'; sLanguageStandard_c11 = 'c11'; sLanguageStandard_c__11 = 'c++11'; sLanguageStandard_c__14 = 'c++14'; sLanguageStandard_c__17 = 'c++17'; sDisableOptimizations = 'CLANG_DisableOptimizations'; sOptimizeForSize = 'CLANG_OptimizeForSize'; sOptimizeForSizeIgnoreSpeed = 'CLANG_OptimizeForSizeIgnoreSpeed'; sOptimizeForSpeed = 'CLANG_OptimizeForSpeed'; sOptimizeMaximum = 'CLANG_OptimizeMaximum'; sOptimizationLevel = 'CLANG_OptimizationLevel'; sOptimizationLevel_None = 'None'; sOptimizationLevel_Level1 = 'Level1'; sOptimizationLevel_Level2 = 'Level2'; sOptimizationLevel_Level3 = 'Level3'; sPredefineMacro = 'CLANG_PredefineMacro'; sSetErrorLimit = 'CLANG_SetErrorLimit'; sUndefineMacro = 'CLANG_UndefineMacro'; // CLANGAdvanced sUserSuppliedOptions = 'CLANG_UserSuppliedOptions'; sRemappingFile = 'CLANG_RemappingFile'; sRequireMathFuncErrorNumber = 'CLANG_RequireMathFuncErrorNumber'; // CLANGTarget sLinkWithDynamicRTL = 'CLANG_LinkWithDynamicRTL'; sGenerateConsoleApp = 'CLANG_GenerateConsoleApp'; sGeneratePackage = 'CLANG_GeneratePackage'; sGenerateDLL = 'CLANG_GenerateDLL'; sGenerateMultithreaded = 'CLANG_GenerateMultithreaded'; sGenerateUnicode = 'CLANG_GenerateUnicode'; sGenerateWindowsApp = 'CLANG_GenerateWindowsApp'; // CLANGPrecompiledHeaders sPCHName = 'CLANG_PCHName'; sPCHUsage = 'CLANG_PCHUsage'; sPCHUsage_None = 'None'; sPCHUsage_GenerateAndUse = 'GenerateAndUse'; sPCHUsage_UseDontGenerate = 'UseDontGenerate'; // CLANGOutput sUTF8Output = 'CLANG_UTF8Output'; sOutputFilename = 'CLANG_OutputFilename'; sAutoDependencyOutput = 'CLANG_AutoDependencyOutput'; sDependencyFile = 'CLANG_DependencyFile'; sDependencyFileTarget = 'CLANG_DependencyFileTarget'; sParallelDependencies = 'CLANG_ParallelDependencies'; sSubProcessesNumber = 'CLANG_SubProcessesNumber'; sDependencyIncDepHeaders = 'CLANG_DependencyIncDepHeaders'; // CLANGWarnings sWarningIsError = 'CLANG_WarningIsError'; sAllWarnings = 'CLANG_AllWarnings'; sDisableWarnings = 'CLANG_DisableWarnings'; // CLANGOptimizations // Outputs sOutput_ObjFiles = 'ObjFiles'; sOutput_PrecompiledHeaderFile = 'PrecompiledHeaderFile'; implementation end.
unit ncSerializeValue; interface uses Rtti; implementation var RttiContext: TRttiContext; { Value ToBytes: if Data.IsEmpty then WriteString('nil') else begin // Write Data (TncValue) string name WriteString(RttiContext.GetType(Data.TypeInfo).QualifiedName); // Append Data (TncValue) contents Len := Length(Result); SetLength(Result, Len + Data.DataSize); Data.ExtractRawData(@Result[Len]); end; Value FromBytes: // Read Data (TncValue) string name TypeName := ReadString; // Read Data (TncValue) contents if TypeName = 'nil' then Data := nil else TValue.Make(@aBytes[Ofs], RttiContext.FindType(TypeName).Handle, Data); } initialization RttiContext := TRttiContext.Create; finalization RttiContext.Free; end.
{ Copyright (C) 1998-2018, written by Shkolnik Mike, Scalabium Software E-Mail: mshkolnik@scalabium.com mshkolnik@yahoo.com WEB: http://www.scalabium.com } unit FileNotify; interface {$I SMVersion.inc} uses Windows, SysUtils, Classes; type EFileNotificationError = class(Exception); TFileNotificationOption = (foFile, foFolder, foAttributes, foSize, foTime, foWatchSubFolders); TFileNotificationOptions = set of TFileNotificationOption; TFileNotifyEvent = procedure(Sender: TObject; Action: TFileNotificationOption) of object; TSMFileNotificator = class; TNotificationThread = class(TThread) private FOwner: TSMFileNotificator; FHandles: array[0..7] of THandle; FHandleFilters: array[0..7] of TFileNotificationOption; FHandleCount: Integer; FActiveFilter: TFileNotificationOption; procedure ReleaseHandles; procedure AllocateHandles; protected procedure Execute; override; procedure Notify; public constructor Create(Owner: TSMFileNotificator); destructor Destroy; override; procedure Reset; end; {$IFDEF SM_ADD_ComponentPlatformsAttribute} [ComponentPlatformsAttribute(pidWin32 or pidWin64)] {$ENDIF} TSMFileNotificator = class(TComponent) private FThread: TNotificationThread; FFolder: string; FOptions: TFileNotificationOptions; FOnFileNotification: TFileNotifyEvent; procedure SetOptions(Value: TFileNotificationOptions); procedure SetFolder(Value: string); protected procedure Notify(Action: TFileNotificationOption); virtual; procedure Loaded; override; public constructor Create(AOwner: TCOmponent); override; destructor Destroy; override; published property Folder: string read FFolder write SetFolder; property Options: TFileNotificationOptions read FOptions write SetOptions; property OnFileNotification: TFileNotifyEvent read FOnFileNotification write FOnFileNotification; end; procedure Register; implementation procedure Register; begin RegisterComponents('SMComponents', [TSMFileNotificator]); end; const SErrInstall = 'Could not install notification callback'; SErrAllocHandle = 'Could not allocate notification object'; { TNotificationThread } const HANDLE_FILE = 0; HANDLE_DIR = 1; HANDLE_ATTR = 2; HANDLE_SIZE = 3; HANDLE_TIME = 4; constructor TNotificationThread.Create(Owner: TSMFileNotificator); begin inherited Create(True); FOwner := Owner; FreeOnTerminate := False; Reset; Resume; end; destructor TNotificationThread.Destroy; begin ReleaseHandles; inherited Destroy; end; procedure TNotificationThread.AllocateHandles; procedure SetNotification(FileNotificationOption: TFileNotificationOption); const ANotifyFilter: array[foFile..foTime] of Integer = (FILE_NOTIFY_CHANGE_FILE_NAME, FILE_NOTIFY_CHANGE_DIR_NAME, FILE_NOTIFY_CHANGE_ATTRIBUTES, FILE_NOTIFY_CHANGE_SIZE, FILE_NOTIFY_CHANGE_LAST_WRITE); begin FHandleFilters[FHandleCount] := FileNotificationOption; FHandles[FHandleCount] := FindFirstChangeNotification(PChar(FOwner.Folder), (foWatchSubFolders in FOwner.FOptions), ANotifyFilter[FileNotificationOption]); Inc(FHandleCount); if FHandles[FHandleCount-1] = INVALID_HANDLE_VALUE then raise EFileNotificationError.Create(SErrAllocHandle); end; begin if (FOwner <> nil) and (FOwner.FOptions <> []) then try FillChar(FHandles, SizeOf(FHandles), 0); FHandleCount := 0; if (foFile in FOwner.FOptions) then SetNotification(foFile); if (foFolder in FOwner.FOptions) then SetNotification(foFolder); if (foAttributes in FOwner.FOptions) then SetNotification(foAttributes); if (foSize in FOwner.FOptions) then SetNotification(foSize); if (foTime in FOwner.FOptions) then SetNotification(foTime); except ReleaseHandles; raise; end; end; procedure TNotificationThread.ReleaseHandles; var i: Integer; begin for i := 0 to FHandleCount-1 do if FHandles[i] <> 0 then FindCloseChangeNotification(FHandles[i]); FillChar(FHandles, SizeOf(FHandles), 0); FillChar(FHandleFilters, Sizeof(FHandleFilters), 0); FHandleCount := 0; end; procedure TNotificationThread.Reset; begin ReleaseHandles; AllocateHandles; end; procedure TNotificationThread.Execute; var i, j: Integer; begin while not Terminated do begin if FHandleCount > 0 then begin j := WaitForMultipleObjects(FHandleCount, @FHandles, False, 200); for i := 0 to FHandleCount-1 do if j = (WAIT_OBJECT_0 + i) then begin FActiveFilter := FHandleFilters[i]; Synchronize(Notify); FindNextChangeNotification(FHandles[i]); break; end; end; // else // Sleep(0); Sleep(1); end end; procedure TNotificationThread.Notify; begin FOwner.Notify(FActiveFilter); end; { TSMFileNotificator } constructor TSMFileNotificator.Create(AOwner: TCOmponent); begin inherited Create(AOwner); FOptions := [foFile, foFolder]; end; destructor TSMFileNotificator.Destroy; begin if Assigned(FThread) then begin FThread.Free; FThread := nil; end; inherited Destroy; end; procedure TSMFileNotificator.Loaded; begin inherited Loaded; if not (csDesigning in ComponentState) then FThread := TNotificationThread.Create(Self); end; procedure TSMFileNotificator.Notify(Action: TFileNotificationOption); begin if Assigned(OnFileNotification) then OnFileNotification(Self, Action); end; procedure TSMFileNotificator.SetOptions(Value: TFileNotificationOptions); begin if Value <> Options then begin FOptions := Value; if Assigned(FThread) then FThread.Reset; end; end; procedure TSMFileNotificator.SetFolder(Value: string); begin if (Value <> FFolder) then begin FFolder := Value; if Assigned(FThread) then FThread.Reset; end; end; end.
unit Hash_MD; {$I TinyDB.INC} interface uses Classes, HashBase; type THash_MD4 = class(THash) protected FCount: LongWord; FBuffer: array[0..63] of Byte; FDigest: array[0..9] of LongWord; protected class function TestVector: Pointer; override; procedure Transform(Buffer: PIntArray); virtual; public class function DigestKeySize: Integer; override; procedure Init; override; procedure Done; override; procedure Calc(const Data; DataSize: Integer); override; function DigestKey: Pointer; override; end; THash_MD5 = class(THash_MD4) protected class function TestVector: Pointer; override; procedure Transform(Buffer: PIntArray); override; end; implementation uses SysUtils; class function THash_MD4.TestVector: Pointer; assembler; asm MOV EAX,OFFSET @Vector RET @Vector: DB 025h,0EAh,0BFh,0CCh,08Ch,0C9h,06Fh,0D9h DB 02Dh,0CFh,07Eh,0BDh,07Fh,087h,07Ch,07Ch end; procedure THash_MD4.Transform(Buffer: PIntArray); {calculate the Digest, fast} var A, B, C, D: LongWord; begin A := FDigest[0]; B := FDigest[1]; C := FDigest[2]; D := FDigest[3]; Inc(A, Buffer[ 0] + (B and C or not B and D)); A := A shl 3 or A shr 29; Inc(D, Buffer[ 1] + (A and B or not A and C)); D := D shl 7 or D shr 25; Inc(C, Buffer[ 2] + (D and A or not D and B)); C := C shl 11 or C shr 21; Inc(B, Buffer[ 3] + (C and D or not C and A)); B := B shl 19 or B shr 13; Inc(A, Buffer[ 4] + (B and C or not B and D)); A := A shl 3 or A shr 29; Inc(D, Buffer[ 5] + (A and B or not A and C)); D := D shl 7 or D shr 25; Inc(C, Buffer[ 6] + (D and A or not D and B)); C := C shl 11 or C shr 21; Inc(B, Buffer[ 7] + (C and D or not C and A)); B := B shl 19 or B shr 13; Inc(A, Buffer[ 8] + (B and C or not B and D)); A := A shl 3 or A shr 29; Inc(D, Buffer[ 9] + (A and B or not A and C)); D := D shl 7 or D shr 25; Inc(C, Buffer[10] + (D and A or not D and B)); C := C shl 11 or C shr 21; Inc(B, Buffer[11] + (C and D or not C and A)); B := B shl 19 or B shr 13; Inc(A, Buffer[12] + (B and C or not B and D)); A := A shl 3 or A shr 29; Inc(D, Buffer[13] + (A and B or not A and C)); D := D shl 7 or D shr 25; Inc(C, Buffer[14] + (D and A or not D and B)); C := C shl 11 or C shr 21; Inc(B, Buffer[15] + (C and D or not C and A)); B := B shl 19 or B shr 13; Inc(A, Buffer[ 0] + $5A827999 + (B and C or B and D or C and D)); A := A shl 3 or A shr 29; Inc(D, Buffer[ 4] + $5A827999 + (A and B or A and C or B and C)); D := D shl 5 or D shr 27; Inc(C, Buffer[ 8] + $5A827999 + (D and A or D and B or A and B)); C := C shl 9 or C shr 23; Inc(B, Buffer[12] + $5A827999 + (C and D or C and A or D and A)); B := B shl 13 or B shr 19; Inc(A, Buffer[ 1] + $5A827999 + (B and C or B and D or C and D)); A := A shl 3 or A shr 29; Inc(D, Buffer[ 5] + $5A827999 + (A and B or A and C or B and C)); D := D shl 5 or D shr 27; Inc(C, Buffer[ 9] + $5A827999 + (D and A or D and B or A and B)); C := C shl 9 or C shr 23; Inc(B, Buffer[13] + $5A827999 + (C and D or C and A or D and A)); B := B shl 13 or B shr 19; Inc(A, Buffer[ 2] + $5A827999 + (B and C or B and D or C and D)); A := A shl 3 or A shr 29; Inc(D, Buffer[ 6] + $5A827999 + (A and B or A and C or B and C)); D := D shl 5 or D shr 27; Inc(C, Buffer[10] + $5A827999 + (D and A or D and B or A and B)); C := C shl 9 or C shr 23; Inc(B, Buffer[14] + $5A827999 + (C and D or C and A or D and A)); B := B shl 13 or B shr 19; Inc(A, Buffer[ 3] + $5A827999 + (B and C or B and D or C and D)); A := A shl 3 or A shr 29; Inc(D, Buffer[ 7] + $5A827999 + (A and B or A and C or B and C)); D := D shl 5 or D shr 27; Inc(C, Buffer[11] + $5A827999 + (D and A or D and B or A and B)); C := C shl 9 or C shr 23; Inc(B, Buffer[15] + $5A827999 + (C and D or C and A or D and A)); B := B shl 13 or B shr 19; Inc(A, Buffer[ 0] + $6ED9EBA1 + (B xor C xor D)); A := A shl 3 or A shr 29; Inc(D, Buffer[ 8] + $6ED9EBA1 + (A xor B xor C)); D := D shl 9 or D shr 23; Inc(C, Buffer[ 4] + $6ED9EBA1 + (D xor A xor B)); C := C shl 11 or C shr 21; Inc(B, Buffer[12] + $6ED9EBA1 + (C xor D xor A)); B := B shl 15 or B shr 17; Inc(A, Buffer[ 2] + $6ED9EBA1 + (B xor C xor D)); A := A shl 3 or A shr 29; Inc(D, Buffer[10] + $6ED9EBA1 + (A xor B xor C)); D := D shl 9 or D shr 23; Inc(C, Buffer[ 6] + $6ED9EBA1 + (D xor A xor B)); C := C shl 11 or C shr 21; Inc(B, Buffer[14] + $6ED9EBA1 + (C xor D xor A)); B := B shl 15 or B shr 17; Inc(A, Buffer[ 1] + $6ED9EBA1 + (B xor C xor D)); A := A shl 3 or A shr 29; Inc(D, Buffer[ 9] + $6ED9EBA1 + (A xor B xor C)); D := D shl 9 or D shr 23; Inc(C, Buffer[ 5] + $6ED9EBA1 + (D xor A xor B)); C := C shl 11 or C shr 21; Inc(B, Buffer[13] + $6ED9EBA1 + (C xor D xor A)); B := B shl 15 or B shr 17; Inc(A, Buffer[ 3] + $6ED9EBA1 + (B xor C xor D)); A := A shl 3 or A shr 29; Inc(D, Buffer[11] + $6ED9EBA1 + (A xor B xor C)); D := D shl 9 or D shr 23; Inc(C, Buffer[ 7] + $6ED9EBA1 + (D xor A xor B)); C := C shl 11 or C shr 21; Inc(B, Buffer[15] + $6ED9EBA1 + (C xor D xor A)); B := B shl 15 or B shr 17; Inc(FDigest[0], A); Inc(FDigest[1], B); Inc(FDigest[2], C); Inc(FDigest[3], D); end; class function THash_MD4.DigestKeySize: Integer; begin Result := 16; end; function THash_MD4.DigestKey: Pointer; begin Result := @FDigest; end; procedure THash_MD4.Init; begin FillChar(FBuffer, SizeOf(FBuffer), 0); {all Descend from MD4 (MD4, SHA1, RipeMD128, RipeMD160, RipeMD256) use this Init-Key} FDigest[0] := $67452301; FDigest[1] := $EFCDAB89; FDigest[2] := $98BADCFE; FDigest[3] := $10325476; FDigest[4] := $C3D2E1F0; {for RMD320} FDigest[5] := $76543210; FDigest[6] := $FEDCBA98; FDigest[7] := $89ABCDEF; FDigest[8] := $01234567; FDigest[9] := $3C2D1E0F; FCount := 0; end; procedure THash_MD4.Done; var I: Integer; S: Comp; begin I := FCount and $3F; FBuffer[I] := $80; Inc(I); if I > 64 - 8 then begin FillChar(FBuffer[I], 64 - I, 0); Transform(@FBuffer); I := 0; end; FillChar(FBuffer[I], 64 - I, 0); S := FCount * 8; Move(S, FBuffer[64 - 8], SizeOf(S)); Transform(@FBuffer); FillChar(FBuffer, SizeOf(FBuffer), 0); end; procedure THash_MD4.Calc(const Data; DataSize: Integer); var Index: Integer; P: PChar; begin if DataSize <= 0 then Exit; Index := FCount and $3F; Inc(FCount, DataSize); if Index > 0 then begin if DataSize < 64 - Index then begin Move(Data, FBuffer[Index], DataSize); Exit; end; Move(Data, FBuffer[Index], 64 - Index); Transform(@FBuffer); Dec(DataSize, 64 - Index); end; P := @TByteArray(Data)[Index]; Inc(Index, DataSize and not $3F); while DataSize >= 64 do begin Transform(Pointer(P)); Inc(P, 64); Dec(DataSize, 64); end; Move(TByteArray(Data)[Index], FBuffer, DataSize); end; class function THash_MD5.TestVector: Pointer; asm MOV EAX,OFFSET @Vector RET @Vector: DB 03Eh,0D8h,034h,08Ch,0D2h,0A4h,045h,0D6h DB 075h,05Dh,04Bh,0C9h,0FEh,0DCh,0C2h,0C6h end; procedure THash_MD5.Transform(Buffer: PIntArray); var A, B, C, D: LongWord; begin A := FDigest[0]; B := FDigest[1]; C := FDigest[2]; D := FDigest[3]; Inc(A, Buffer[ 0] + $D76AA478 + (D xor (B and (C xor D)))); A := A shl 7 or A shr 25 + B; Inc(D, Buffer[ 1] + $E8C7B756 + (C xor (A and (B xor C)))); D := D shl 12 or D shr 20 + A; Inc(C, Buffer[ 2] + $242070DB + (B xor (D and (A xor B)))); C := C shl 17 or C shr 15 + D; Inc(B, Buffer[ 3] + $C1BDCEEE + (A xor (C and (D xor A)))); B := B shl 22 or B shr 10 + C; Inc(A, Buffer[ 4] + $F57C0FAF + (D xor (B and (C xor D)))); A := A shl 7 or A shr 25 + B; Inc(D, Buffer[ 5] + $4787C62A + (C xor (A and (B xor C)))); D := D shl 12 or D shr 20 + A; Inc(C, Buffer[ 6] + $A8304613 + (B xor (D and (A xor B)))); C := C shl 17 or C shr 15 + D; Inc(B, Buffer[ 7] + $FD469501 + (A xor (C and (D xor A)))); B := B shl 22 or B shr 10 + C; Inc(A, Buffer[ 8] + $698098D8 + (D xor (B and (C xor D)))); A := A shl 7 or A shr 25 + B; Inc(D, Buffer[ 9] + $8B44F7AF + (C xor (A and (B xor C)))); D := D shl 12 or D shr 20 + A; Inc(C, Buffer[10] + $FFFF5BB1 + (B xor (D and (A xor B)))); C := C shl 17 or C shr 15 + D; Inc(B, Buffer[11] + $895CD7BE + (A xor (C and (D xor A)))); B := B shl 22 or B shr 10 + C; Inc(A, Buffer[12] + $6B901122 + (D xor (B and (C xor D)))); A := A shl 7 or A shr 25 + B; Inc(D, Buffer[13] + $FD987193 + (C xor (A and (B xor C)))); D := D shl 12 or D shr 20 + A; Inc(C, Buffer[14] + $A679438E + (B xor (D and (A xor B)))); C := C shl 17 or C shr 15 + D; Inc(B, Buffer[15] + $49B40821 + (A xor (C and (D xor A)))); B := B shl 22 or B shr 10 + C; Inc(A, Buffer[ 1] + $F61E2562 + (C xor (D and (B xor C)))); A := A shl 5 or A shr 27 + B; Inc(D, Buffer[ 6] + $C040B340 + (B xor (C and (A xor B)))); D := D shl 9 or D shr 23 + A; Inc(C, Buffer[11] + $265E5A51 + (A xor (B and (D xor A)))); C := C shl 14 or C shr 18 + D; Inc(B, Buffer[ 0] + $E9B6C7AA + (D xor (A and (C xor D)))); B := B shl 20 or B shr 12 + C; Inc(A, Buffer[ 5] + $D62F105D + (C xor (D and (B xor C)))); A := A shl 5 or A shr 27 + B; Inc(D, Buffer[10] + $02441453 + (B xor (C and (A xor B)))); D := D shl 9 or D shr 23 + A; Inc(C, Buffer[15] + $D8A1E681 + (A xor (B and (D xor A)))); C := C shl 14 or C shr 18 + D; Inc(B, Buffer[ 4] + $E7D3FBC8 + (D xor (A and (C xor D)))); B := B shl 20 or B shr 12 + C; Inc(A, Buffer[ 9] + $21E1CDE6 + (C xor (D and (B xor C)))); A := A shl 5 or A shr 27 + B; Inc(D, Buffer[14] + $C33707D6 + (B xor (C and (A xor B)))); D := D shl 9 or D shr 23 + A; Inc(C, Buffer[ 3] + $F4D50D87 + (A xor (B and (D xor A)))); C := C shl 14 or C shr 18 + D; Inc(B, Buffer[ 8] + $455A14ED + (D xor (A and (C xor D)))); B := B shl 20 or B shr 12 + C; Inc(A, Buffer[13] + $A9E3E905 + (C xor (D and (B xor C)))); A := A shl 5 or A shr 27 + B; Inc(D, Buffer[ 2] + $FCEFA3F8 + (B xor (C and (A xor B)))); D := D shl 9 or D shr 23 + A; Inc(C, Buffer[ 7] + $676F02D9 + (A xor (B and (D xor A)))); C := C shl 14 or C shr 18 + D; Inc(B, Buffer[12] + $8D2A4C8A + (D xor (A and (C xor D)))); B := B shl 20 or B shr 12 + C; Inc(A, Buffer[ 5] + $FFFA3942 + (B xor C xor D)); A := A shl 4 or A shr 28 + B; Inc(D, Buffer[ 8] + $8771F681 + (A xor B xor C)); D := D shl 11 or D shr 21 + A; Inc(C, Buffer[11] + $6D9D6122 + (D xor A xor B)); C := C shl 16 or C shr 16 + D; Inc(B, Buffer[14] + $FDE5380C + (C xor D xor A)); B := B shl 23 or B shr 9 + C; Inc(A, Buffer[ 1] + $A4BEEA44 + (B xor C xor D)); A := A shl 4 or A shr 28 + B; Inc(D, Buffer[ 4] + $4BDECFA9 + (A xor B xor C)); D := D shl 11 or D shr 21 + A; Inc(C, Buffer[ 7] + $F6BB4B60 + (D xor A xor B)); C := C shl 16 or C shr 16 + D; Inc(B, Buffer[10] + $BEBFBC70 + (C xor D xor A)); B := B shl 23 or B shr 9 + C; Inc(A, Buffer[13] + $289B7EC6 + (B xor C xor D)); A := A shl 4 or A shr 28 + B; Inc(D, Buffer[ 0] + $EAA127FA + (A xor B xor C)); D := D shl 11 or D shr 21 + A; Inc(C, Buffer[ 3] + $D4EF3085 + (D xor A xor B)); C := C shl 16 or C shr 16 + D; Inc(B, Buffer[ 6] + $04881D05 + (C xor D xor A)); B := B shl 23 or B shr 9 + C; Inc(A, Buffer[ 9] + $D9D4D039 + (B xor C xor D)); A := A shl 4 or A shr 28 + B; Inc(D, Buffer[12] + $E6DB99E5 + (A xor B xor C)); D := D shl 11 or D shr 21 + A; Inc(C, Buffer[15] + $1FA27CF8 + (D xor A xor B)); C := C shl 16 or C shr 16 + D; Inc(B, Buffer[ 2] + $C4AC5665 + (C xor D xor A)); B := B shl 23 or B shr 9 + C; Inc(A, Buffer[ 0] + $F4292244 + (C xor (B or not D))); A := A shl 6 or A shr 26 + B; Inc(D, Buffer[ 7] + $432AFF97 + (B xor (A or not C))); D := D shl 10 or D shr 22 + A; Inc(C, Buffer[14] + $AB9423A7 + (A xor (D or not B))); C := C shl 15 or C shr 17 + D; Inc(B, Buffer[ 5] + $FC93A039 + (D xor (C or not A))); B := B shl 21 or B shr 11 + C; Inc(A, Buffer[12] + $655B59C3 + (C xor (B or not D))); A := A shl 6 or A shr 26 + B; Inc(D, Buffer[ 3] + $8F0CCC92 + (B xor (A or not C))); D := D shl 10 or D shr 22 + A; Inc(C, Buffer[10] + $FFEFF47D + (A xor (D or not B))); C := C shl 15 or C shr 17 + D; Inc(B, Buffer[ 1] + $85845DD1 + (D xor (C or not A))); B := B shl 21 or B shr 11 + C; Inc(A, Buffer[ 8] + $6FA87E4F + (C xor (B or not D))); A := A shl 6 or A shr 26 + B; Inc(D, Buffer[15] + $FE2CE6E0 + (B xor (A or not C))); D := D shl 10 or D shr 22 + A; Inc(C, Buffer[ 6] + $A3014314 + (A xor (D or not B))); C := C shl 15 or C shr 17 + D; Inc(B, Buffer[13] + $4E0811A1 + (D xor (C or not A))); B := B shl 21 or B shr 11 + C; Inc(A, Buffer[ 4] + $F7537E82 + (C xor (B or not D))); A := A shl 6 or A shr 26 + B; Inc(D, Buffer[11] + $BD3AF235 + (B xor (A or not C))); D := D shl 10 or D shr 22 + A; Inc(C, Buffer[ 2] + $2AD7D2BB + (A xor (D or not B))); C := C shl 15 or C shr 17 + D; Inc(B, Buffer[ 9] + $EB86D391 + (D xor (C or not A))); B := B shl 21 or B shr 11 + C; Inc(FDigest[0], A); Inc(FDigest[1], B); Inc(FDigest[2], C); Inc(FDigest[3], D); end; {get the CPU Type from your system} { function GetCPUType: Integer; assembler; asm PUSH EBX PUSH ECX PUSH EDX MOV EBX,ESP AND ESP,0FFFFFFFCh PUSHFD PUSHFD POP EAX MOV ECX,EAX XOR EAX,40000h PUSH EAX POPFD PUSHFD POP EAX XOR EAX,ECX MOV EAX,3 JE @Exit PUSHFD POP EAX MOV ECX,EAX XOR EAX,200000h PUSH EAX POPFD PUSHFD POP EAX XOR EAX,ECX MOV EAX,4 JE @Exit PUSH EBX MOV EAX,1 DB 0Fh,0A2h //CPUID MOV AL,AH AND EAX,0Fh POP EBX @Exit: POPFD MOV ESP,EBX POP EDX POP ECX POP EBX end; } end.
{ ID:asiapea1 PROB:subset LANG:PASCAL } program subset; const MaxN=39; maxint=Maxn*(Maxn+1) div 2; var g:array[0..39,-maxn..maxint]of int64; t,n:longint; procedure Out; begin writeln(0);close(output);halt; end; procedure Init; begin assign(input,'subset.in');reset(input); assign(output,'subset.out');rewrite(output); read(n); t:=n*(n+1) div 2; if odd(t) then Out else t:=t div 2; fillchar(g,sizeof(g),255); end; function Main(n,t:integer):int64; var i:longint; totel:int64; begin if (t>n*(n+1) div 2) or (t<0) then g[n,t]:=0; if t=0 then g[n,t]:=1; if g[n,t]<>-1 then begin Main:=g[n,t];exit; end; totel:=0; for i:=n downto 1 do totel:=totel+Main(i-1,t-i); g[n,t]:=totel;Main:=totel; end; begin Init; Main(n,t); writeln(g[n,t] div 2);close(output); end.
namespace RemObjects.Elements.System; uses Foundation; type NSString_Extension = public extension class(NSString) public property Item[i: Integer]: Char read self.characterAtIndex(i); default; property Item[i: &Index]: Char read self.characterAtIndex(i.GetOffset(length)); default; property Item[r: Range]: String read getSubstringWithRange(r); default; private method getSubstringWithRange(aRange: Range): NSString; begin var lLength := self.length; var lStart := aRange.fStart.GetOffset(lLength); var lEnd := aRange.fEnd.GetOffset(lLength); result := substringWithRange(NSMakeRange(lStart, lEnd-lStart)); end; end; end.
{=============================================================================== 异常处理单元 ===============================================================================} unit xExceptionCatch; interface uses System.Classes, System.SysUtils, Winapi.Windows; type /// <summary> /// 信息类型 /// </summary> TMessageType = (mtNote = 0, // 无 mtInformation = MB_ICONINFORMATION, // 提示 mtQuestion = MB_ICONQUESTION, // 询问 mtWARNING = MB_ICONWARNING, // 警告 mtSTOP = MB_ICONSTOP // 错误 ); /// <summary> /// 读取文件 /// </summary> function ExceptionReadFile:string; procedure WriteMsg(sUnitName, sCode, sMsg : string ); procedure WriteSql( sSQL: string ); /// <summary> /// 消息异常(显示异常信息给用户看) /// </summary> /// <param name="sUnitName">单元名称</param> /// <param name="MsgType">提示信息类型</param> /// <param name="msgStr">提示信息</param> procedure MsgException(sUnitName:string; MsgType : TMessageType; sMsgStr : string ); /// <summary> /// 记录异常(异常信息记录到文件中,不提示给用户看) /// </summary> /// <param name="sUnitName">单元名称</param> /// <param name="sCode">异常代码</param> /// <param name="sExcStr">异常信息</param> procedure RecordException(sUnitName,sCode, sExcStr : string ); /// <summary> /// Sql异常(异常信息记录到文件中,不提示给用户看) /// </summary> /// <param name="sUnitName">单元名称</param> /// <param name="sCode">异常代码</param> /// <param name="sExcStr">异常信息</param> /// <param name="sSqlStr">执行的Sql语句</param> procedure SQLException(sUnitName,sCode, sExcStr, sSqlStr : string ); implementation { TEXCEPTION_CATCH } function ExceptionReadFile:string; var s,s2:string; FFile : TextFile; begin s:=''; Result:=''; AssignFile(FFile,'Exception Code.txt'); if FileExists('Exception Code.txt') then begin try Reset(FFile); while not Eof(FFile) do begin Readln(FFile, s2); s:=s + s2 + #13#10; end; Result:=s; finally CloseFile(FFile); end; end; end; procedure MsgException(sUnitName:string;MsgType: TMessageType; sMsgStr: string); begin WriteMsg(sUnitName, '-1', sMsgStr); MessageBox(0, PWideChar(sMsgStr), '', MB_OK + Integer(MsgType)); // Application.MessageBox(PWideChar(sMsgStr), '', MB_OK + Integer(MsgType)); end; procedure RecordException(sUnitName,sCode, sExcStr: string); begin WriteMsg(sUnitName,sCode, sExcStr); end; procedure SQLException(sUnitName,sCode, sExcStr, sSqlStr: string); begin WriteMsg(sUnitName,sCode, sExcStr); WriteSql(sSqlStr); MessageBox(0,PWideChar(sExcStr), '', MB_OK + MB_ICONWARNING); end; procedure WriteMsg(sUnitName, sCode, sMsg: string); const C_SIGN = '------------------------------------------------'; var s : string; FFile : TextFile; begin AssignFile(FFile,'Exception Code.txt'); s := ExceptionReadFile; try ReWrite(FFile); write(FFile, s); Writeln( FFile, C_SIGN + C_SIGN ); Writeln( FFile, '异常时间:' + FormatDateTime('YYYY-MM-DD hh:mm:ss', Now)); Writeln( FFile, '异常文件:' + sUnitName ); Writeln( FFile, '异常编码:' + sCode ); Writeln( FFile, '异常信息:' + sMsg ); finally CloseFile(FFile); end; end; procedure WriteSql(sSQL: string); var s : string; FFile : TextFile; begin AssignFile(FFile,'Exception Code.txt'); s := ExceptionReadFile; try ReWrite(FFile); write(FFile, s); Write( FFile, 'SQL 信息:' + sSQL ); finally CloseFile(FFile); end; end; end.
unit array_dynamic_const_1; interface implementation var Len: Int32; procedure PutLen(const A: array of int32); begin Len := Length(A); end; procedure Test; begin PutLen([1, 2, 3, 4, 5]); end; initialization Test(); finalization Assert(Len = 5); end.
{*******************************************************} { } { Midas RemoteDataModule Pooler Demo } { } {*******************************************************} unit SrvrDM; { This is the Remote Data Module (RDM) that is going to be pooled. The differences between this RDM and a regular RDM are as follows; 1) In order to share RDMs the client must be stateless. This means that the all calls that come into the server, must not rely on any informatin passed in previous calls. 2) The RDMs need to run in their own thread which is why the factory constructor is specifying tmApartment as the threading model. tmFree or tmBoth could also be used if the server is written to support Free threading. 3) This class is an internal accesible class only and is not registered in the registry. All access to this object is done from the pooler object. If you look in the Type Library you will see 2 different CoClasses for this project. One is for this class and one is for the Pooler. } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ComServ, ComObj, VCLCom, StdVcl, ActiveX, DataBkr, Server_TLB, Db, DBTables, Provider; type TPooledRDM = class(TRemoteDataModule, IPooledRDM) Session1: TSession; Database1: TDatabase; Query1: TQuery; DataSetProvider1: TDataSetProvider; procedure DataSetProvider1BeforeGetRecords(Sender: TObject; var OwnerData: OleVariant); private { Private declarations } public { Public declarations } end; var { Need a reference to the ClassFactory so the pooler can create instances of the class. } RDMFactory: TComponentFactory; implementation {$R *.DFM} { Since this is a stateless server, before records are fetched, the query needs to be positioned to the correct location. The client passes the query and the value of the first field for the last record it fetched. If you are fetching all records then you don't need to locate the last record. If the query isn't changing, then you don't need to pass the query to the server.} procedure TPooledRDM.DataSetProvider1BeforeGetRecords(Sender: TObject; var OwnerData: OleVariant); begin try Query1.Close; Query1.SQL.Text := OwnerData[0]; if not VarIsNull(OwnerData[1]) and not VarIsEmpty(OwnerData[1]) then begin Query1.Open; if not Query1.Locate(Query1.Fields[0].FieldName, OwnerData[1], []) then raise Exception.Create('Record not found'); Query1.Next; end; finally OwnerData := NULL; end; end; initialization RDMFactory := TComponentFactory.Create(ComServer, TPooledRDM, Class_PooledRDM, ciInternal, tmApartment); end.
{------------------------------------------------------------------------------- // Authentication Demo // // Description: Three Handlers to Know, They Are (In Order): // ApacheOnAccessChecker......Access Control // ApacheOnCheckUserId........Authentication {This Demo} // ApacheOnAuthChecker........Authorization // // Access Control: // Access control is any type of restriction that doesn't // require the identity of the remote user. // Use this handler to deny or grant access based on // Host, IP , Domain....etc. // // Authentication: // May I see your ID Please ? Who are you and can you // Prove it ? Use this handler to implement your desired // Authentication Scheme. // // Authorization: // OK, So you _ARE_ Mr.Foo, However I still can't Let you // in ! Once you know Who the person is, use the // Authorization handler to determine if the individual // user can enter. // //-----------------------------------------------------------------------------} unit Authentication_u; interface uses SysUtils, Classes, HTTPApp, ApacheApp, HTTPD; type TWebModule1 = class(TWebModule) procedure WebModule1Actions0Action(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); private { Private declarations } public { Public declarations } end; var WebModule1: TWebModule1; path : String; implementation uses WebReq; {$R *.xfm} procedure TWebModule1.WebModule1Actions0Action(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); begin response.content:='Access Granted: '+ Request.Content; end; function Apache_OnAccessChecker (Request: Prequest_rec): integer; begin result:= 0; end; type Pauth_config_rec = ^auth_config_rec; auth_config_rec = packed record auth_pwfile: pchar; auth_grpfile: pchar; auth_authoritative: integer; end; function create_auth_dir_config(Pool: Ppool; szDir: pchar): pointer; var sec: Pauth_config_rec; begin sec := ap_pcalloc(Pool, sizeof(auth_config_rec)); sec.auth_pwfile := nil; // just to illustrate the default really sec.auth_grpfile := nil; // unless you have a broken HP cc sec.auth_authoritative := 1; // keep the fortress secure by default result:= sec; end; function get_pw(r: Prequest_rec; user, auth_pwfile: pchar): pchar; var f: Pconfigfile_t; l: array[0..255] of char; rpw, w: pchar; begin result := nil; f := ap_pcfg_openfile(r^.pool, auth_pwfile); if f = nil then exit; while ap_cfg_getline(l, 255, f) = 0 do begin if (l[0] = '#') or (strlen(l) = 0) then continue; rpw := l; w := ap_getword(r^.pool, @rpw, ':'); if strcomp(user, w) = 0 then begin ap_cfg_closefile(f); result := ap_getword(r^.pool, @rpw, ':'); exit; end; end; ap_cfg_closefile(f); end; function authenticate_basic_user(Request: Prequest_rec): integer; var sec: auth_config_rec; c: Pconn_rec; sent_pw: pchar; real_pw: pchar; res: integer; begin //pMod := @apache_module; // This apiCall is failing with an Undefined symbol. // sec := ap_get_module_config(Request^.per_dir_config, pMod); // This means that we can't read them from the // config file, and they need to be set here. // This would be read in from AuthUserFile in the conf file sec.auth_pwfile := '/usr/local/apache/conf/kylixpassfile.txt'; sec.auth_grpfile := nil; sec.auth_authoritative := 1; // end =============================================== c := Request^.connection; res := ap_get_basic_auth_pw(Request, @sent_pw); if res <> 0 then begin result := res; exit; end; // logging left in as an aid ap_log_error(Request.server.error_fname , APLOG_EMERG, APLOG_ALERT, Request.server, PChar('user tested = ' + c^.user)); if sec.auth_pwfile = nil then begin ap_log_error(Request.server.error_fname , APLOG_EMERG, APLOG_ALERT, Request.server, PChar('pw file is nil')); result := AP_DECLINED; exit; end; real_pw := get_pw(Request, c^.user, sec.auth_pwfile); if real_pw = nil then begin ap_log_error(Request.server.error_fname , APLOG_EMERG, APLOG_ALERT, Request.server, PChar('real_pw is nil')); if sec.auth_authoritative <> 0 then begin result := AP_DECLINED; exit; end; result := AUTH_REQUIRED; exit; end; ap_log_error(Request.server.error_fname , APLOG_EMERG, APLOG_ALERT, Request.server, PChar('sent pw=' + sent_pw + ' acutal pass=' + real_pw)); if strcomp(sent_pw, real_pw) = 0 then result := AP_OK else result := AUTH_REQUIRED; end; function Apache_OnAuthChecker(Request: Prequest_rec): integer; begin //ap_note_basic_auth_failure(Request); result:= 0; end; initialization ApacheOnCreateDirConfig := create_auth_dir_config; ApacheOnAccessChecker := Apache_OnAccessChecker; ApacheOnCheckUserId := authenticate_basic_user; ApacheOnAuthChecker := Apache_OnAuthChecker; end.
unit MatomoSdkLib; interface uses System.SysUtils, System.Classes, HttpClientWrapperLib; type TMatomoEvent = record category: String; action: String; name: String; value: Double; function ToParams: TStrings; end; TMatomo = class(TObject) private FMatomoUrl: String; FSiteId: String; FId: String; FAppName: String; FUserId: String; procedure GenerateId; function GetRandomInt: String; function GetScreenResolution: String; function GetAppName: String; function GetUserAgent: String; function getDefaultParams: TStringList; function GenerateRequest(params: TStrings): String; procedure SetMatomoUrl(const Value: String); public procedure track; procedure trackEvent(event: TMatomoEvent); procedure ping; property MatomoURL: String read FMatomoUrl write SetMatomoUrl; property SiteId: String read FSiteId write FSiteId; property AppName: String read FAppName write FAppName; property Id: String read FId write FId; //TrackingId property UserId: String read FUserId write FUserId; end; implementation uses System.NetEncoding, NetHttpClientWrapper; { TMatomo } procedure TMatomo.GenerateId; var tmpGuid: string; begin tmpGuid := TGUID.NewGuid.ToString; tmpGuid := tmpGuid.Replace('{', '', [rfReplaceAll]) .Replace('-', '', [rfReplaceAll]) .Replace('Empty}', '', [rfReplaceAll]); FID := tmpGuid.Substring(0, 16); end; function TMatomo.GenerateRequest(params: TStrings): String; var i: Integer; requestParamStr: string; begin requestParamStr := ''; for i := 0 to params.Count-1 do begin if not requestParamStr.IsEmpty then requestParamStr := requestParamStr +'&'; requestParamStr := requestParamStr + params[i]; end; Result := FMatomoUrl+'?'+requestParamStr; end; function TMatomo.GetAppName: String; begin Result := AppName; if not Result.StartsWith('http', true) then Result := 'http://'+Result; end; function TMatomo.getDefaultParams: TStringList; begin Result := TStringList.Create; Result.Add('idsite='+FSiteId); Result.Add('rec=1'); Result.Add('_id='+FId); Result.Add('rand='+GetRandomInt); Result.Add('apiv=1'); Result.Add('url='+GetAppName); Result.Add('ua='+GetUserAgent); Result.Add('res='+GetScreenResolution); { TODO : Get the correct system language } Result.Add('lang=de'); if not FUserId.Trim.IsEmpty then Result.Add('uid='+FUserId); end; function TMatomo.GetRandomInt: String; begin Randomize; Result := IntToStr(Random(10000)); end; function TMatomo.GetScreenResolution: String; begin { TODO : Get the correct screen size } Result := '1280x1024'; Result := TNetEncoding.URL.EncodeQuery(Result); end; function TMatomo.GetUserAgent: String; begin { TODO : Generate correct useragent } Result := 'Microsoft Windows 10'; end; procedure TMatomo.ping; var sl: TStringList; requestUrl: String; FHttpClient: THttpClientWrapper; begin if FId.Trim.IsEmpty then GenerateId; sl := getDefaultParams; sl.Add('ping=1'); requestUrl := GenerateRequest(sl); sl.Free; FHttpClient := THttpClientWrapper.Create(TNetHttpClientWrapper.Create); FHttpClient.AsyncGet(requestUrl); end; procedure TMatomo.SetMatomoUrl(const Value: String); begin FMatomoUrl := Value; if not FMatomoUrl.EndsWith('matomo.php') then begin raise Exception.Create('Unexpected URL: URL must end with "matomo.php"'); end; end; procedure TMatomo.track; var sl: TStringList; requestUrl: String; FHttpClient: THttpClientWrapper; begin if FId.Trim.IsEmpty then GenerateId; sl := getDefaultParams; requestUrl := GenerateRequest(sl); sl.Free; FHttpClient := THttpClientWrapper.Create(TNetHttpClientWrapper.Create); FHttpClient.AsyncGet(requestUrl); end; procedure TMatomo.trackEvent(event: TMatomoEvent); var sl: TStringList; requestUrl: String; FHttpClient: THttpClientWrapper; additionalParams: TStrings; begin if FId.Trim.IsEmpty then GenerateId; sl := getDefaultParams; additionalParams := event.ToParams; sl.AddStrings(additionalParams); additionalParams.Free; requestUrl := GenerateRequest(sl); sl.Free; FHttpClient := THttpClientWrapper.Create(TNetHttpClientWrapper.Create); FHttpClient.AsyncGet(requestUrl); end; { TMatomoEvent } function TMatomoEvent.ToParams: TStrings; begin Result := TStringList.Create; Result.Add('e_c='+category); Result.Add('e_a='+action); Result.Add('e_n='+name); Result.Add('e_v='+FloatToStr(value)); end; end.
unit htmlCodec; interface function htmlDecodeStr(S: String): String; implementation type Thtmlcode = record fHtml : String; fString : String; end; const htmlCodes : array[0..3] of ThtmlCode = ( (fHtml : '&amp;'; fString : '&'), (fHtml : '&lt;'; fString : '<'), (fHtml : '&gt;'; fString : '>'), (fHtml : '&quot;'; fString : '"')); function htmlDecodeStr(S: String): String; var I, P : Integer; Achou : Boolean; begin Result := S; for I := 0 to High(htmlCodes) do repeat P := Pos(htmlCodes[I].fHtml, Result); if P>0 then begin Result := Copy(Result, 1, P-1) + htmlCodes[I].fString + Copy(Result, P+Length(htmlCodes[I].fHtml), Length(Result)); end; until (P=0); end; end.
unit UFunctionsGHH; interface Uses ZConnection, Classes, ZDataSet, SysUtils,DB,StdCtrls, Variants, Windows,global, frm_connection,utilerias, Controls,Jpeg,Graphics,ExtCtrls,Clipbrd,ShellApi,Messages,Dialogs,axctrls; type IData=class Private Public IdDb:Integer; sNameFile:String; sTypeFile:String; end; IDataPlus=class Private Public dFecha:TDate; IdFolio:Integer; sIdEgreso:String; sIdProveedor:String; sIdFactura:String; sNameFile:String; sTypeFile:String; end; Function Conectar(var conexion:TzConnection;Server,DataBase:string;Port:integer):boolean; Function CompressImage(ArchOrig:TFilename;Porcentaje:Integer):TFilename; Procedure MostrarBitmap(Const Bitmap: TBitmap;Const Image: TImage); Function LoadGraphicsFile(Const Filename: String): TBitmap; Function ImagePasteFromClipBoard:TFilename; Procedure MessageError(CAdena:WideString); Function PermisosExportar(conexion:TzConnection;Grupo,Programa:string):String; Function SwbsPrincipal(psContrato,psConvenio,psTipo,psItemO:String;ptconexion:TzConnection):string; Function GenerarTmpName(sNombre:String;sExt:String=''):String; function obtenerDirectorioTemporal : TFileName; function obtenerDirectorioWindows : TFileName; function BlobToStream(Field: TField): TMemoryStream; type TeFilter = (prNinguno,prIgual,prDiferente,prMayor,prMayorIgual,prMenor,prMenorIgual); vsMode=(vsLectura,vsEdicion,vsInsercion); smFile=(smPdf,smJpeg,smXml); implementation Function GenerarTmpName(sNombre:String;sExt:String=''):String; var sTimeFile:String; begin sTimeFile:=formatdatetime('ddmmyyhhnnss',now); if sExt<>'' then Result:=sNombre+'ftempAby'+sTimeFile+sExt else Result:=sNombre+'ftempAby'+sTimeFile; end; function obtenerDirectorioTemporal : TFileName; var TmpDir: array [0..MAX_PATH-1] of char; begin try SetString(Result, TmpDir, GetTempPath(MAX_PATH, TmpDir)); if not DirectoryExists(Result) then if not CreateDirectory(PChar(Result), nil) then begin Result := IncludeTrailingBackslash(obtenerDirectorioWindows) + 'TEMP'; if not DirectoryExists(Result) then if not CreateDirectory(Pointer(Result), nil) then begin Result := ExtractFileDrive(Result) + '\TEMP'; if not DirectoryExists(Result) then if not CreateDirectory(Pointer(Result), nil) then begin Result := ExtractFileDrive(Result) + '\TMP'; if not DirectoryExists(Result) then if not CreateDirectory(Pointer(Result), nil) then begin raise Exception.Create(SysErrorMessage(GetLastError)); end; end; end; end; except Result := ''; raise; end; end; function obtenerDirectorioWindows : TFileName; var WinDir: array [0..MAX_PATH-1] of char; begin SetString(Result, WinDir, GetWindowsDirectory(WinDir, MAX_PATH)); if Result = '' then raise Exception.Create(SysErrorMessage(GetLastError)); end; function BlobToStream(Field: TField): TMemoryStream; begin Result := nil; if Field.IsBlob then begin Result := TMemoryStream.Create; try TBlobField(Field).SaveToStream(Result); except FreeAndNil(Result); end; end; end; Function SwbsPrincipal(psContrato,psConvenio,psTipo,psItemO:String;ptconexion:TzConnection):string; var error:Boolean; QrAct:TzReadOnlyQuery; begin result:=''; Error:=false; QrAct:=TzReadOnlyQuery.Create(nil); QrAct.Connection:=ptconexion; QrAct.SQL.Text:='select swbs from actividadesxanexo where scontrato=:contrato '+ 'and sidconvenio=:convenio and stipoActividad=:tipo ' + 'and swbsanterior=:item'; QrAct.ParamByName('contrato').AsString:=pscontrato; QrAct.ParamByName('convenio').AsString:=psconvenio; QrAct.ParamByName('tipo').AsString:=psTipo; QrAct.ParamByName('item').AsString:=psItemO; try try QrAct.Open except error:=true; end; if not error then begin if QrAct.RecordCount>0 then result:=QrAct.FieldByName('swbs').AsString; end; finally freeandnil(QrAct); end; end; Function PermisosExportar(conexion:TzConnection;Grupo,Programa:string):String; var QrPermisosExp:TzReadOnlyQuery; Error:boolean; begin result:=''; Error:=false; QrPermisosExp:=TzReadOnlyQuery.Create(nil); QrPermisosExp.Connection:=conexion; QrPermisosExp.SQL.Text:='SELECT sFormatos ' + 'FROM gruposxprograma ' + 'WHERE sIdGrupo = :grupo AND sIdPrograma = :modulo'; QrPermisosExp.ParamByName('grupo').AsString:=grupo; QrPermisosExp.ParamByName('modulo').AsString:=Programa; try try QrPermisosExp.Open; except error:=true; end; if not error then begin if QrPermisosExp.RecordCount=1 then result:=QrPermisosExp.FieldByName('sFormatos').AsString; end; finally freeandnil(QrPermisosExp); end; end; Procedure MessageError(Cadena:widestring); begin MessageDlg(Cadena,Mterror,[mbok],0); end; Function ImagePasteFromClipboard:TFilename; var f : TFileStream; Jpg : TJpegImage; Hand : THandle; Buffer : Array [0..MAX_PATH] of Char; numFiles : Integer; File_Name : String; Jpg_Bmp : String; BitMap : TBitMap; ImageAux : TImage; Picture : TPicture; TempPath: array [0..MAX_PATH-1] of Char; FNombre:TFileName; begin ImageAux := TImage.Create(nil); Result:=''; if Clipboard.HasFormat(CF_HDROP) then //Checar si es Drag and Drop begin Clipboard.Open; try Hand := Clipboard.GetAsHandle(CF_HDROP); If Hand <> 0 then begin numFiles := DragQueryFile(Hand, $FFFFFFFF, nil, 0) ; if numFiles > 1 then begin Clipboard.Close; ImageAux.Free; MessageError('El Portapapeles contiene más de un único fichero. No es posible pegar'); Exit; end; Buffer[0] := #0; DragQueryFile( Hand, 0, buffer, sizeof(buffer)) ; File_Name := buffer; end; finally Clipboard.close; end; f := TFileStream.Create(File_Name, fmOpenRead); Jpg := TJpegImage.Create; Bitmap := TBitmap.Create; try //Checar si es un JPG o BMP Jpg.LoadFromStream(f); ImageAux.Picture.Assign(Jpg); Jpg_Bmp := 'JPG'; except f.seek(0,soFromBeginning); Jpg_Bmp := ''; end; if Jpg_Bmp = '' then begin try Bitmap.LoadFromStream(f); Jpg.Assign(Bitmap); ImageAux.Picture.Assign(Jpg); Jpg_Bmp := 'BMP'; except Jpg_Bmp := ''; end; end; Jpg.Free; Bitmap.Free; f.Free; GetTempPath(SizeOf(TempPath), TempPath); FNombre:=TempPath +'ClpbtempGHH'+formatdatetime('dddddd hhnnss',now)+'.jpg'; try if Jpg_Bmp = '' then begin MessageError('Fichero seleccionado no contiene ninguna Imagen del Tipo JPEG o BMP'); end else begin ImageAux.Picture.SaveToFile(FNombre); Result:=CompressImage(FNombre,90); end; finally ImageAux.Free; if FileExists(FNombre) then DeleteFile(Pchar(FNombre)); end; end else if (Clipboard.HasFormat(CF_BITMAP)) or (Clipboard.HasFormat(CF_PICTURE)) then ImageAux.Picture.Assign(Clipboard) else begin ImageAux.Free; MessageError('El Portapapeles no contiene ninguna Imagen del Tipo JPEG o BMP'); Exit; end; GetTempPath(SizeOf(TempPath), TempPath); FNombre:=TempPath +'ClpbtempGHH'+formatdatetime('dddddd hhnnss',now)+'.jpg'; Jpg := TJpegImage.Create; Picture := TPicture.Create; try try if (Clipboard.HasFormat(CF_BITMAP)) then begin Jpg.Assign(ImageAux.Picture.Graphic); jpg.SaveToFile(FNombre); Result:=CompressImage(FNombre,90); end; if (Clipboard.HasFormat(CF_PICTURE)) then begin Picture.Assign(Clipboard); Picture.SaveToFile(FNombre); Result:=CompressImage(FNombre,90); end; except on e:Exception do begin ImageAux.Free; MessageError('El Portapapeles no contiene ninguna Imagen del Tipo JPEG o BMP'); end; end; finally if Fileexists(Fnombre) then DeleteFile(PChar(FNombre)); freeandnil(Jpg); FreeandNil(Picture); end; end; Function LoadGraphicsFile(Const Filename: String): TBitmap; Var Picture: TPicture; f : TFileStream; graphic : TOleGraphic; Begin Result := NIL; If FileExists(Filename) Then Begin Result := TBitmap.Create; Try Picture := TPicture.Create; graphic := TOleGraphic.Create; Try f := TFileStream.Create (Filename,fmOpenRead or fmShareDenyNone); try try Graphic.LoadFromStream(f); Picture.Assign(Graphic); except on e:exception do begin if e.ClassName='EOleSysError' then begin try Picture.LoadFromFile(Filename); except Result:=nil; end; end; end; end; Try Result.Assign(Picture.Graphic); Except Result.Width := Picture.Graphic.Width; Result.Height := Picture.Graphic.Height; Result.PixelFormat := pf24bit; Result.Canvas.Draw(0, 0, Picture.Graphic); End; finally freeandnil(f); end; Finally Picture.Free; freeandnil(graphic); End; Except Result.Free; Raise; End; End; End; Procedure MostrarBitmap(Const Bitmap: TBitmap;Const Image : TImage); Var Half : INTEGER; Height : INTEGER; NewBitmap : TBitmap; TargetArea: TRect; Width : INTEGER; Begin NewBitmap := TBitmap.Create; TRY NewBitmap.Width := Image.Width; NewBitmap.Height := Image.Height; NewBitmap.PixelFormat := pf24bit; NewBitmap.Canvas.FillRect(NewBitmap.Canvas.ClipRect); If (Bitmap.Width / Bitmap.Height) < (Image.Width / Image.Height)Then Begin TargetArea.Top := 0; TargetArea.Bottom := NewBitmap.Height; Width := MulDiv(NewBitmap.Height, Bitmap.Width, Bitmap.Height); Half := (NewBitmap.Width - Width) DIV 2; TargetArea.Left := Half; TargetArea.Right := TargetArea.Left + Width; End Else Begin TargetArea.Left := 0; TargetArea.Right := NewBitmap.Width; Height := MulDiv(NewBitmap.Width, Bitmap.Height, Bitmap.Width); Half := (NewBitmap.Height - Height) DIV 2; TargetArea.Top := Half; TargetArea.Bottom := TargetArea.Top + Height End; NewBitmap.Canvas.StretchDraw(TargetArea, Bitmap); Image.Picture.Graphic := NewBitmap Finally NewBitmap.Free End; End; Function CompressImage(ArchOrig:TFilename;Porcentaje:Integer):TFilename; var Aux,Original,pantalla:Timage; TempPath: array [0..MAX_PATH-1] of Char; jpg:TJpegImage; Bitmap,bmp: TBitmap; Alto,Ancho,Comp:Integer; FNombre:TFileName; f : TFileStream; graphic : TOleGraphic; begin Result:=''; Comp:=Porcentaje; if (Porcentaje=0) or (Porcentaje>100) then Comp:=100; if Length(trim(ArchOrig))>0 then begin if FileExists(ArchOrig) then begin ancho:=0; Alto:=0; Original:=Timage.Create(nil); graphic := TOleGraphic.Create; Original.AutoSize:=true; try f := TFileStream.Create (ArchOrig,fmOpenRead or fmShareDenyNone); try try graphic.LoadFromStream(f); Original.Picture.Assign(graphic); except on e:Exception do begin if e.ClassName='EOleSysError' then begin try Original.Picture.LoadFromFile(ArchOrig); except Result:=''; end; end; end; end; finally f.Free; end; Ancho:=Original.Width; Alto:=Original.Height; finally freeandnil(Original); freeandnil(graphic); end; if Alto>2000 then begin Alto:=trunc(alto/3); Ancho:=trunc(Ancho/3); end else begin if Alto>1000 then begin Alto:=trunc(alto/2); Ancho:=trunc(Ancho/2); end; end; Aux:=Timage.Create(nil); Aux.Width:=ancho; Aux.Height:=alto; Bitmap := TBitmap.Create; Bitmap.Width := aux.Width; Bitmap.Height := aux.Height; Bitmap.PixelFormat := pf24bit; Bitmap.Canvas.Brush.Color := clRed; Bitmap.Canvas.FillRect(Bitmap.Canvas.ClipRect); MostrarBitmap(Bitmap, Aux); Bitmap.Free; Bitmap := LoadGraphicsFile(ArchOrig); MostrarBitmap(Bitmap, Aux); try GetTempPath(SizeOf(TempPath), TempPath); FNombre:=TempPath +'imgtempGHH'+formatdatetime('dddddd hhnnss',now)+'.jpg'; //'imgtemp2327ghh.jpg'; jpg := TJpegImage.Create; bmp := TBitmap.Create; bmp.Assign(aux.Picture.Bitmap); jpg.Assign(Bmp); Pantalla:=Timage.Create(nil); try jpg.CompressionQuality := comp; jpg.Compress; try pantalla.Picture.Assign(jpg); except pantalla.Picture.Assign(nil); end; pantalla.Picture.SaveToFile(fNombre); finally freeandnil(jpg); freeandnil(pantalla); freeandnil(bmp); end; finally freeandnil(Aux); freeandnil(Bitmap); if fileexists(FNombre) then begin Result:=FNombre; end; end; end; end; end; Function Conectar(var conexion:TzConnection;Server,DataBase:string;Port:integer):boolean; var error,isroot:boolean; QrAcceso:TzReadOnlyQuery; local_Pass:String; begin error:=false; isRoot:=false; Conexion.Disconnect; Conexion.HostName:=Global_ServAcceso; Conexion.Database:=''; Conexion.Catalog:=''; Conexion.Port:=Global_PortAcceso; Conexion.User:=IntelUser; Conexion.Password:=IntelPass; conexion.Protocol:=connection.zConnection.Protocol; try Conexion.Connect; except on e:exception do begin if pos('Access denied',e.message)>0 then begin Conexion.Disconnect; Conexion.User :=IntelUser; Conexion.Password :=IntelPass ; conexion.HostName:=server; Conexion.Database := '' ; Conexion.Catalog := '' ; conexion.Port:=port; conexion.Protocol:=connection.zConnection.Protocol; Try Conexion.Connect ; except on e : exception do begin if pos('Access denied',e.message)>0 then begin Conexion.Disconnect; Conexion.User :=IntelUser; Conexion.Password :=IntelPass ; conexion.HostName:=server; Conexion.Database := database ; Conexion.Catalog := database ; conexion.Port:=port; conexion.Protocol:=connection.zConnection.Protocol; Try Conexion.Connect ; isRoot:=true; except error:=true; End; end else error:=true; end; End; if not error then begin If not Conexion.Ping Then begin error:=true; end; end; end else error:=true; end; end; if not error then begin if conexion.Ping then begin if not isroot then begin QrAcceso:=TzReadOnlyquery.Create(nil); QrAcceso.Connection:=Conexion; QrAcceso.SQL.Text:='select * from adminintel.acceso where user=' + quotedstr(global_bduser) + ' and servidor=' +quotedstr(server); try QrAcceso.Open; except on E:exception do begin error:=true; end; end; if not error then begin try if QrAcceso.RecordCount=1 then local_Pass:=desencripta(QrAcceso.FieldByName('password').AsString) else local_Pass:=IntelPass; finally freeandnil(QrAcceso); end; Conexion.Disconnect; Conexion.HostName := server ; Conexion.Port := port; Conexion.User :=global_bduser; Conexion.Password :=Local_pass; Conexion.Database :=database ; conexion.Protocol:=connection.zConnection.Protocol; try Conexion.Connect; except on E:exception do error:=true; end; end; End; end; end; result:=not error; end; end.
Program clase5; Type encomienda = record codigo: integer; peso: integer; end; // Lista de encomiendas lista = ^nodoL; nodoL = record dato: encomienda; sig: lista; end; listaCodigos=^nodoC; nodoC=record dato: integer; sig: listaCodigos; end; arbol = ^nodo; nodo = record elem: integer; codigos: listaCodigos; HI: arbol; HD: arbol; end; {----------------------------------------------------------------------------- AgregarAdelante - Agrega una encomienda adelante en l} procedure agregarAdelante(var l: Lista; enc: encomienda); var aux: lista; begin new(aux); aux^.dato := enc; aux^.sig := l; l:= aux; end; {----------------------------------------------------------------------------- CREARLISTA - Genera una lista con datos de las encomiendas } procedure crearLista(var l: Lista); var e: encomienda; i: integer; begin l:= nil; for i:= 1 to 20 do begin e.codigo := i; e.peso:= random (10); while (e.peso = 0) do e.peso:= random (10); agregarAdelante(L, e); End; end; {----------------------------------------------------------------------------- IMPRIMIRLISTA - Muestra en pantalla la lista l } procedure imprimirLista(l: Lista); begin While (l <> nil) do begin writeln('Codigo: ', l^.dato.codigo, ' Peso: ', l^.dato.peso); l:= l^.sig; End; end; {actividad} procedure AgregarCodigo (var l: listaCodigos; cod: integer); var aux:listaCodigos; begin new(aux); aux^.dato := cod; aux^.sig := l; l:= aux; end; procedure Insertar(registro:encomienda; var a:arbol); begin if (a=nil) then begin new(a); a^.elem:=registro.peso; a^.codigos:=nil; AgregarCodigo(a^.codigos, registro.codigo); a^.HI:=nil; a^.HD:=nil; end else if (a^.elem>registro.peso) then Insertar(registro,a^.HI) else if (a^.elem<registro.peso) then Insertar(registro,a^.HD) else AgregarCodigo(a^.codigos, registro.codigo) end; procedure recorrer(l:lista; var a:arbol); begin if(l<>nil)then begin Insertar(l^.dato,a); recorrer(l^.sig,a); end; end; procedure imprimir(l:listaCodigos); begin if (l<>nil) then begin write(l^.dato, ' - '); imprimir(l^.sig); end; end; Procedure enOrden( a: arbol ); begin if ( a <> nil ) then begin enOrden (a^.HI); write ('peso ', a^.elem, ': '); imprimir(a^.codigos); writeln; enOrden (a^.HD) end; end; Var l: lista; a:arbol; begin Randomize; crearLista(l); writeln ('Lista de encomiendas generada: '); imprimirLista(l); a:=nil; recorrer(l,a); enOrden(a); readln; end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { Copyright(c) 2014-2019 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit RSConsole.RESTObjects; interface uses System.Classes, System.Generics.Collections, System.JSON, REST.Types, REST.Client; const AUTH_CRYPTO_VALUE: word = 47011; type TRESTAuthMethod = (amNONE, amSIMPLE, amBASIC, amOAUTH, amOAUTH2); TRESTAuthMethods = set of TRESTAuthMethod; TRESTRequestParams = class(TObject) private FMethod: TRESTRequestMethod; FURL: string; FResource: string; FContentType: string; FAuthMethod: TRESTAuthMethod; FAuthUsername: string; FAuthUsernameKey: string; FAuthPassword: string; FAuthPasswordKey: string; // oauth1 & oauth2 FClientID: string; FClientSecret: string; FAuthCode: string; FAccessToken: string; FAccessTokenSecret: string; FRequestToken: string; FRequestTokenSecret: string; FRefreshToken: string; FOAuth1SignatureMethod: string; FOAuth2ResponseType: string; FEndpointAuth: string; FEndpointAccessToken: string; FEndpointRequestToken: string; FEndpointRedirect: string; FAuthScope: string; FCustomParams: TRESTRequestParameterList; FCustomBody: TMemoryStream; protected procedure SetResource(const AValue: string); public constructor Create; destructor Destroy; override; procedure ResetToDefaults; procedure Assign(ASource: TRESTRequestParams); function AsJSONObject: TJSONObject; procedure FromJSONObject(const AJSONObject: TJSONObject); procedure SaveToFile(const AFilename: string); procedure LoadFromFile(const AFilename: string); function ToString: string; override; property URL: string read FURL write FURL; property Resource: string read FResource write SetResource; property Method: TRESTRequestMethod read FMethod write FMethod; property ContentType: string read FContentType write FContentType; property AuthMethod: TRESTAuthMethod read FAuthMethod write FAuthMethod; property AuthUsername: string read FAuthUsername write FAuthUsername; property AuthUsernameKey: string read FAuthUsernameKey write FAuthUsernameKey; property AuthPassword: string read FAuthPassword write FAuthPassword; property AuthPasswordKey: string read FAuthPasswordKey write FAuthPasswordKey; property ClientID: string read FClientID write FClientID; property ClientSecret: string read FClientSecret write FClientSecret; property AuthCode: string read FAuthCode write FAuthCode; property AccessToken: string read FAccessToken write FAccessToken; property AccessTokenSecret: string read FAccessTokenSecret write FAccessTokenSecret; property RequestToken: string read FRequestToken write FRequestToken; property RequestTokenSecret: string read FRequestTokenSecret write FRequestTokenSecret; property RefreshToken: string read FRefreshToken write FRefreshToken; property OAuth1SignatureMethod: string read FOAuth1SignatureMethod write FOAuth1SignatureMethod; property OAuth2ResponseType: string read FOAuth2ResponseType write FOAuth2ResponseType; property EndpointAuth: string read FEndpointAuth write FEndpointAuth; property EndpointAccessToken: string read FEndpointAccessToken write FEndpointAccessToken; property EndpointRequestToken: string read FEndpointRequestToken write FEndpointRequestToken; property EndpointRedirect: string read FEndpointRedirect write FEndpointRedirect; property AuthScope: string read FAuthScope write FAuthScope; property CustomBody: TMemoryStream read FCustomBody; property CustomParams: TRESTRequestParameterList read FCustomParams; end; TRESTRequestParamsList = TList<TRESTRequestParams>; TRESTRequestParamsObjectList = TObjectList<TRESTRequestParams>; var DefaultRESTAuthMethod: TRESTAuthMethod = amNONE; function RESTRequestMethodFromString(const ARequestMethod: string): TRESTRequestMethod; function RESTAuthMethodToString(const AAuthMethod: TRESTAuthMethod): string; function RESTAuthMethodFromString(const AAuthMethod: string): TRESTAuthMethod; function SimpleEncryptStr(const S: String; Key: word): string; function SimpleDecryptStr(const S: String; Key: word): string; implementation uses System.StrUtils, System.SysUtils, IdGlobal, IdCoderMIME, REST.Consts; function RESTRequestMethodFromString(const ARequestMethod: string): TRESTRequestMethod; begin if SameText(ARequestMethod, 'GET') then Result := TRESTRequestMethod.rmGET else if SameText(ARequestMethod, 'POST') then Result := TRESTRequestMethod.rmPOST else if SameText(ARequestMethod, 'PUT') then Result := TRESTRequestMethod.rmPUT else if SameText(ARequestMethod, 'DELETE') then Result := TRESTRequestMethod.rmDELETE else if SameText(ARequestMethod, 'PATCH') then Result := TRESTRequestMethod.rmPATCH else raise Exception.Create(sRESTUnsupportedRequestMethod); end; function RESTAuthMethodToString(const AAuthMethod: TRESTAuthMethod): string; begin case AAuthMethod of amNONE: Result := 'NONE'; amSIMPLE: Result := 'SIMPLE'; amBASIC: Result := 'BASIC'; amOAUTH: Result := 'OAUTH'; amOAUTH2: Result := 'OAUTH2'; else Result := '--unknown--'; end; end; function RESTAuthMethodFromString(const AAuthMethod: string): TRESTAuthMethod; begin if SameText(AAuthMethod, 'NONE') then Result := amNONE else if SameText(AAuthMethod, 'SIMPLE') then Result := amSIMPLE else if SameText(AAuthMethod, 'BASIC') then Result := amBASIC else if SameText(AAuthMethod, 'OAUTH') then Result := amOAUTH else if SameText(AAuthMethod, 'OAUTH2') then Result := amOAUTH2 else raise Exception.Create(sRESTUnsupportedAuthMethod); end; const CKEY1 = 53761; CKEY2 = 32618; function SimpleEncryptStr(const S: string; Key: word): string; var i: Integer; RStr: RawByteString; RStrB: TBytes absolute RStr; begin Result := ''; RStr := UTF8Encode(S); for i := 0 to Length(RStr) - 1 do begin RStrB[i] := RStrB[i] xor (Key shr 8); Key := (RStrB[i] + Key) * CKEY1 + CKEY2; end; for i := 0 to Length(RStr) - 1 do Result := Result + IntToHex(RStrB[i], 2); end; function SimpleDecryptStr(const S: String; Key: word): string; var i, tmpKey: Integer; RStr: RawByteString; RStrB: TBytes absolute RStr; tmpStr: string; begin tmpStr := UpperCase(S); SetLength(RStr, Length(tmpStr) div 2); i := 1; try while (i < Length(tmpStr)) do begin RStrB[i div 2] := StrToInt('$' + tmpStr[i] + tmpStr[i + 1]); Inc(i, 2); end; except Result := ''; Exit; end; for i := 0 to Length(RStr) - 1 do begin tmpKey := RStrB[i]; RStrB[i] := RStrB[i] xor (Key shr 8); Key := (tmpKey + Key) * CKEY1 + CKEY2; end; Result := UTF8ToString(RStr); end; { TRESTRequestParams } constructor TRESTRequestParams.Create; begin inherited; FCustomParams := TRESTRequestParameterList.Create(nil); FCustomBody := TMemoryStream.Create; ResetToDefaults; end; destructor TRESTRequestParams.Destroy; begin ResetToDefaults; FreeAndNIL(FCustomBody); FreeAndNIL(FCustomParams); inherited; end; procedure TRESTRequestParams.ResetToDefaults; begin FURL := ''; FResource := ''; FMethod := DefaultRESTRequestMethod; FContentType := ''; // do NOT reset the proxy-settings! FAuthMethod := DefaultRESTAuthMethod; FAuthUsername := ''; FAuthUsernameKey := ''; FAuthPassword := ''; FAuthPasswordKey := ''; FClientID := ''; FClientSecret := ''; FAuthCode := ''; FAccessToken := ''; FAccessTokenSecret := ''; FRequestToken := ''; FRequestTokenSecret := ''; FRefreshToken := ''; FOAuth1SignatureMethod := ''; FOAuth2ResponseType := ''; FEndpointAuth := ''; FEndpointAccessToken := ''; FEndpointRequestToken := ''; FEndpointRedirect := ''; FAuthScope := ''; FCustomParams.Clear; FCustomBody.Clear; end; procedure TRESTRequestParams.Assign(ASource: TRESTRequestParams); var LPosition: Int64; begin Assert(Assigned(ASource)); FMethod := ASource.Method; FURL := ASource.URL; FResource := ASource.Resource; FContentType := ASource.ContentType; FAuthMethod := ASource.AuthMethod; FAuthUsername := ASource.AuthUsername; FAuthUsernameKey := ASource.AuthUsernameKey; FAuthPassword := ASource.AuthPassword; FAuthPasswordKey := ASource.AuthPasswordKey; FClientID := ASource.ClientID; FClientSecret := ASource.ClientSecret; FAuthCode := ASource.AuthCode; FAccessToken := ASource.AccessToken; FAccessTokenSecret := ASource.AccessTokenSecret; FRequestToken := ASource.RequestToken; FRequestTokenSecret := ASource.RequestTokenSecret; FRefreshToken := ASource.RefreshToken; FOAuth1SignatureMethod := ASource.OAuth1SignatureMethod; FOAuth2ResponseType := ASource.OAuth2ResponseType; FEndpointAuth := ASource.EndpointAuth; FEndpointAccessToken := ASource.EndpointAccessToken; FEndpointRequestToken := ASource.EndpointRequestToken; FEndpointRedirect := ASource.EndpointRedirect; FAuthScope := ASource.AuthScope; FCustomParams.Assign(ASource.CustomParams); FCustomBody.Clear; // save stream-position LPosition := ASource.CustomBody.Position; try ASource.CustomBody.Position := 0; FCustomBody.CopyFrom(ASource.CustomBody, ASource.CustomBody.Size); finally ASource.CustomBody.Position := LPosition; end; end; function TRESTRequestParams.AsJSONObject: TJSONObject; var LRoot: TJSONObject; LAuth: TJSONObject; LParams: TJSONArray; LParameter: TRESTRequestParameter; LObject: TJSONObject; begin // write auth-info as an object ("dictionary") LAuth := TJSONObject.Create; LAuth .AddPair('method', RESTAuthMethodToString(FAuthMethod)) .AddPair('username', FAuthUsername) .AddPair('passwordkey', FAuthUsernameKey) .AddPair('password', FAuthPassword) .AddPair('passwordkey', FAuthPasswordKey) .AddPair('clientid', FClientID) .AddPair('clientsecret', FClientSecret) .AddPair('authcode', FAuthCode) .AddPair('accesstoken', FAccessToken) .AddPair('accesstokensecret', FAccessTokenSecret) .AddPair('requesttoken', FRequestToken) .AddPair('requesttokensecret', FRequestTokenSecret) .AddPair('refreshtoken', FRefreshToken) .AddPair('signaturemethod', FOAuth1SignatureMethod) .AddPair('responsetype', FOAuth2ResponseType) .AddPair('endpointauth', FEndpointAuth) .AddPair('endpointaccesstoken', FEndpointAccessToken) .AddPair('endpointrequesttoken', FEndpointRequestToken) .AddPair('endpointredirect', FEndpointRedirect) .AddPair('authscope', FAuthScope); // write custom params as an array of objects LParams := TJSONArray.Create; for LParameter in FCustomParams do begin LObject := TJSONObject.Create; LObject .AddPair('name', LParameter.Name) .AddPair('value', LParameter.Value) .AddPair('kind', RESTRequestParameterKindToString(LParameter.Kind)) .AddPair('encode', TJSONBool.Create(not (poDoNotEncode in LParameter.Options))); LParams.Add(LObject); end; // write custom body FCustomBody.Seek(0, soFromBeginning); // write all together LRoot := TJSONObject.Create; LRoot .AddPair('method', RESTRequestMethodToString(FMethod)) .AddPair('url', FURL) .AddPair('resource', FResource) .AddPair('contenttype', FContentType) .AddPair('auth', LAuth) .AddPair('parameters', LParams) .AddPair('body', TIdEncoderMIME.EncodeStream(FCustomBody)); Result := LRoot; end; procedure TRESTRequestParams.FromJSONObject(const AJSONObject: TJSONObject); var LAuth: TJSONObject; LPair: TJSONPair; i: Integer; LParams: TJSONArray; LObject: TJSONObject; LParameter: TRESTRequestParameter; LBool: TJSONBool; function ExtractObject(const Ident: string; const Container: TJSONObject): TJSONObject; overload; var p: TJSONPair; begin p := Container.Get(Ident); if Assigned(p) and (p.JsonValue is TJSONObject) then Result := TJSONObject(p.JsonValue) else Result := nil; end; function ExtractObject(const Index: Integer; const Container: TJSONArray): TJSONObject; overload; var v: TJSONValue; begin v := Container.Items[Index]; if Assigned(v) and (v is TJSONObject) then Result := TJSONObject(v) else Result := nil; end; function ExtractArray(const Ident: string; const Container: TJSONObject): TJSONArray; var p: TJSONPair; begin p := Container.Get(Ident); if Assigned(p) and (p.JsonValue is TJSONArray) then Result := TJSONArray(p.JsonValue) else Result := nil; end; begin ResetToDefaults; LPair := AJSONObject.Get('method'); if Assigned(LPair) then FMethod := RESTRequestMethodFromString(LPair.JsonValue.Value); LPair := AJSONObject.Get('url'); if Assigned(LPair) then FURL := LPair.JsonValue.Value; LPair := AJSONObject.Get('resource'); if Assigned(LPair) then FResource := LPair.JsonValue.Value; LPair := AJSONObject.Get('contenttype'); if Assigned(LPair) then FContentType := LPair.JsonValue.Value; LAuth := ExtractObject('LAuth', AJSONObject); if Assigned(LAuth) then begin LPair := LAuth.Get('method'); if Assigned(LPair) then FAuthMethod := RESTAuthMethodFromString(LPair.JsonValue.Value); LPair := LAuth.Get('username'); if Assigned(LPair) then FAuthUsername := LPair.JsonValue.Value; LPair := LAuth.Get('usernamekey'); if Assigned(LPair) then FAuthUsernameKey := LPair.JsonValue.Value; LPair := LAuth.Get('password'); if Assigned(LPair) then FAuthPassword := LPair.JsonValue.Value; LPair := LAuth.Get('passwordkey'); if Assigned(LPair) then FAuthPasswordKey := LPair.JsonValue.Value; LPair := LAuth.Get('clientid'); if Assigned(LPair) then FClientID := LPair.JsonValue.Value; LPair := LAuth.Get('clientsecret'); if Assigned(LPair) then FClientSecret := LPair.JsonValue.Value; LPair := LAuth.Get('authcode'); if Assigned(LPair) then FAuthCode := LPair.JsonValue.Value; LPair := LAuth.Get('accesstoken'); if Assigned(LPair) then FAccessToken := LPair.JsonValue.Value; LPair := LAuth.Get('accesstokensecret'); if Assigned(LPair) then FAccessTokenSecret := LPair.JsonValue.Value; LPair := LAuth.Get('requesttoken'); if Assigned(LPair) then FRequestToken := LPair.JsonValue.Value; LPair := LAuth.Get('requesttokensecret'); if Assigned(LPair) then FRequestTokenSecret := LPair.JsonValue.Value; LPair := LAuth.Get('refreshtoken'); if Assigned(LPair) then FRefreshToken := LPair.JsonValue.Value; LPair := LAuth.Get('signaturemethod'); if Assigned(LPair) then FOAuth1SignatureMethod := LPair.JsonValue.Value; LPair := LAuth.Get('responsetype'); if Assigned(LPair) then FOAuth2ResponseType := LPair.JsonValue.Value; LPair := LAuth.Get('endpointauth'); if Assigned(LPair) then FEndpointAuth := LPair.JsonValue.Value; LPair := LAuth.Get('endpointaccesstoken'); if Assigned(LPair) then FEndpointAccessToken := LPair.JsonValue.Value; LPair := LAuth.Get('endpointrequesttoken'); if Assigned(LPair) then FEndpointRequestToken := LPair.JsonValue.Value; LPair := LAuth.Get('endpointredirect'); if Assigned(LPair) then FEndpointRedirect := LPair.JsonValue.Value; LPair := LAuth.Get('authscope'); if Assigned(LPair) then FAuthScope := LPair.JsonValue.Value; end; LParams := ExtractArray('parameters', AJSONObject); if Assigned(LParams) then for i := 0 to LParams.Count - 1 do begin LObject := ExtractObject(i, LParams); if Assigned(LObject) then begin LParameter := FCustomParams.AddItem; LPair := LObject.Get('name'); if Assigned(LPair) then LParameter.Name := LPair.JsonValue.Value; LPair := LObject.Get('value'); if Assigned(LPair) then LParameter.Value := LPair.JsonValue.Value; LPair := LObject.Get('kind'); if Assigned(LPair) then LParameter.Kind := RESTRequestParameterKindFromString(LPair.JsonValue.Value); LPair := LObject.Get('encode'); if Assigned(LPair) and LPair.JsonValue.TryGetValue<TJSONBool>(LBool) then if LBool.AsBoolean then LParameter.Options := LParameter.Options - [poDoNotEncode] else LParameter.Options := LParameter.Options + [poDoNotEncode]; end; end; LPair := AJSONObject.Get('body'); if Assigned(LPair) then TIdDecoderMIME.DecodeStream(LPair.JsonValue.Value, FCustomBody); end; procedure TRESTRequestParams.SaveToFile(const AFilename: string); var LStream: TStringStream; LJSONObj: TJSONObject; begin LJSONObj := AsJSONObject; try LStream := TStringStream.Create(LJSONObj.ToJSON); try LStream.SaveToFile(AFilename); finally LStream.Free; end; finally LJSONObj.Free; end; end; procedure TRESTRequestParams.LoadFromFile(const AFilename: string); var LStream: TStringStream; LJSONObj: TJSONObject; begin LStream := TStringStream.Create; try LStream.LoadFromFile(AFilename); LJSONObj := TJSONObject.ParseJSONValue(LStream.DataString, False, True) AS TJSONObject; try FromJSONObject(LJSONObj); finally LJSONObj.Free; end; finally LStream.Free; end; end; procedure TRESTRequestParams.SetResource(const AValue: string); begin if AValue <> FResource then begin // FCustomParams.FromString(FResource, AValue); FCustomParams.CreateURLSegmentsFromString(AValue); FResource := AValue; end; end; function TRESTRequestParams.ToString: string; var S: string; begin Result := FURL; if FResource <> '' then begin // just a minimal fixing of the data for display while EndsText('/', Result) do Delete(Result, Length(Result), 1); S := FResource; while StartsText('/', S) do Delete(S, 1, 1); Result := Result + ' + --> ' + S; end; end; end.
unit class_members_3; interface implementation uses system; type TC1 = class FData: Int32; end; TC2 = class FC: TC1; function GetFC: TC1; end; TC3 = class FC: TC2; constructor Create; end; function TC2.GetFC: TC1; begin Result := FC; end; constructor TC3.Create; begin FC := TC2.Create(); FC.FC := TC1.Create(); FC.FC.FData := 53; end; var C: TC3; G: Int32; procedure Test; begin C := TC3.Create(); G := C.FC.GetFC().FData; end; initialization Test(); finalization Assert(G = 53); end.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls; type { TfrmColor } TfrmColor = class(TForm) btnChangeColor: TButton; procedure btnChangeColorClick(Sender: TObject); private { private declarations } public { public declarations } end; var frmColor: TfrmColor; implementation {$R *.lfm} { TfrmColor } procedure TfrmColor.btnChangeColorClick(Sender: TObject); begin if frmColor.Color = clYellow then //change the color to purple begin frmColor.Color:=clPurple; frmColor.Caption:='Purple'; btnChangeColor.Caption:='&Yellow'; end else //change color to yellow begin frmColor.Color:=clYellow; frmColor.Caption:='Yellow'; btnChangeColor.Caption:='&Purple'; end; end; end.
{ Important Note: Before running this AutoDemo application, make sure that the MemoEdit application has been registered using a "MemoEdit /regserver" command line. } unit AutoForm; interface uses Variants, Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Memo_TLB; type TMainForm = class(TForm) CreateButton: TButton; AddTextButton: TButton; TileButton: TButton; CascadeButton: TButton; CloseButton: TButton; ExitButton: TButton; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure CreateButtonClick(Sender: TObject); procedure AddTextButtonClick(Sender: TObject); procedure TileButtonClick(Sender: TObject); procedure CascadeButtonClick(Sender: TObject); procedure CloseButtonClick(Sender: TObject); procedure ExitButtonClick(Sender: TObject); private MemoEdit: IMemoApp; Memos: array[1..3] of OleVariant; procedure CloseMemos; end; var MainForm: TMainForm; implementation {$R *.dfm} uses ComObj; procedure TMainForm.FormCreate(Sender: TObject); begin try MemoEdit := CoMemoApp.Create; except MessageDlg( 'An instance of the "MemoApp.Application" OLE Automation class ' + 'could not be created. Make sure that the MemoEdit application has ' + 'been registered using a "MemoEdit /regserver" command line.', mtError, [mbOk], 0); Halt; end; end; procedure TMainForm.FormDestroy(Sender: TObject); begin CloseMemos; end; procedure TMainForm.CloseMemos; var I: Integer; begin for I := 1 to 3 do if not VarIsEmpty(Memos[I]) then begin Memos[I].Close; Memos[I] := Unassigned; end; end; procedure TMainForm.CreateButtonClick(Sender: TObject); var I: Integer; begin CloseMemos; for I := 1 to 3 do Memos[I] := MemoEdit.NewMemo; end; procedure TMainForm.AddTextButtonClick(Sender: TObject); var I: Integer; begin for I := 1 to 3 do if not VarIsEmpty(Memos[I]) then Memos[I].Insert('This text was added through OLE Automation'#13#10); end; procedure TMainForm.TileButtonClick(Sender: TObject); begin if MemoEdit <> nil then MemoEdit.TileWindows; end; procedure TMainForm.CascadeButtonClick(Sender: TObject); begin if MemoEdit <> nil then MemoEdit.CascadeWindows; end; procedure TMainForm.CloseButtonClick(Sender: TObject); begin CloseMemos; end; procedure TMainForm.ExitButtonClick(Sender: TObject); begin Close; end; end.
unit uMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ImgList, ImageList, ExtCtrls, StdCtrls, Buttons, ShellApi, FolderDialog, uUtil, uSnortChecker; const PB_MAX_LENGTH = 10240; PB_MIN_LENGTH = 10240; type TFMain = class(TForm) pnMain: TPanel; ilCommon: TImageList; OpenDialog1: TOpenDialog; edtUnNamed: TEdit; Label2: TLabel; edtOpenPath: TEdit; Button1: TButton; Button2: TButton; Panel1: TPanel; btnInit: TButton; Label6: TLabel; FolderDialog1: TFolderDialog; edtSavePath: TEdit; btnSavePath: TButton; chkSavePath: TCheckBox; Label1: TLabel; procedure FormCreate(Sender: TObject); procedure chkSavePathClick(Sender: TObject); procedure btnSavePathClick(Sender: TObject); procedure btnLoadFileClick(Sender: TObject); procedure Button1Click(Sender: TObject); procedure btnInitClick(Sender: TObject); procedure ParseSnort(sSnortRule: String); function CheckHasOptionSnort(sSnortRule : String): boolean; function IsTypeBin(sPayload : String): boolean; function GetCase(sPattern : String): String; private { Private declarations } public { Public declarations } m_TmpList : TStringList; m_SnortList : TStringList; m_PBList : TStringList; // Snort 규칙 sProtocol, sDPORT, sMsg, sContent : String; iUnNamedCnt : Integer; end; var FMain: TFMain; implementation uses AnsiStrings; {$R *.dfm} procedure TFMain.btnInitClick(Sender: TObject); begin edtUnNamed.Text := '0'; edtOpenPath.Text := ''; chkSavePath.Checked := False; edtSavePath.Text := ''; // edtSavePath.Enabled := False; btnSavePath.Enabled := False; edtSavePath.Text := GetCurrentDir; end; procedure TFMain.btnLoadFileClick(Sender: TObject); var i : Integer; sError : String; sTest, sType, sCase, sErrorRules: String; begin if String(edtOpenPath.Text).Length = 0 then begin ShowMessage('분리할 파일을 선택해 주세요.'); Exit; end; // init m_SnortList := TStringList.Create; m_PBList := TStringList.Create; m_TmpList := TStringList.Create; m_TmpList.LoadFromFile(OpenDialog1.FileName); iUnnamedCnt := strToInt(edtUnNamed.Text); m_PBList.Add('name' +#9+ 'pattern' +#9+ 'type' +#9+ 'case-sensitive' +#9+ 'protocol' +#9+ 'port'); try // 0. 올바른 SnortRule 체크 for i := 0 to m_TmpList.Count - 1 do begin if not CheckSnortRule(m_TmpList[i], sError) then sErrorRules := sErrorRules + ', '+ IntToStr(i+1); if sErrorRules.Length > 100 then begin delete(sErrorRules,1,2); ShowMessage(Format('[%s 번째 등]'+#13#10+'상당 수의 Snort 룰 정보가 올바르지 않습니다.',[sErrorRules])); Exit; end; end; if sErrorRules.Length <> 0 then begin delete(sErrorRules,1,2); ShowMessage(Format('[%s]번째 Snort 룰 정보가 올바르지 않습니다.',[sErrorRules])); Exit; end; for i := 0 to m_TmpList.Count - 1 do begin // 1. content, msg, nocase, sid 외에 다른 조건이 있으면 snort // 2. content 가 없으면 snort // 3. content가 2개 이상이면 snort if CheckHasOptionSnort(m_TmpList[i]) or ( ( Pos('content :',m_TmpList[i]) = 0) and (Pos('content:',m_TmpList[i]) = 0 )) or (CountPos('content :', m_TmpList[i]) >= 2) or (CountPos('content:' , m_TmpList[i]) >= 2) then begin m_SnortList.Add(m_TmpList[i]); end else begin ParseSnort(m_TmpList[i]); // 4. content에 부분으로 hex처리(||) 되어있을 때 snort if ( Pos('|',sContent) > 0) and ( CountPos('|',sContent) <> CountPos('\|',sContent) ) then begin if not (( CountPos('|',sContent) = 2 ) and (sContent.Chars[0] = '|') and (sContent.Chars[ sContent.Length -1 ] = '|')) then begin m_SnortList.Add(m_TmpList[i]); Continue; end; end; // 5. port가 any이면 snort // 6. content 길이 유효성 맞지않으면 snort // 7. port 에 옵션 처리시 snort if ( Pos('any',sDPort) > 0) or ( sContent.Length > 127) or (sContent.Length < 3 ) or (Pos(':',sDPort) > 0) or (Pos('!',sDPort) > 0)then begin m_SnortList.Add(m_TmpList[i]); Continue; end; sContent := removeEscape(sContent); if IsTypeBin(sContent) then sType := 'bin' else sType := 'txt'; sCase := getCase(m_TmpList[i]); m_PBList.Add(sMsg +#9+ sContent +#9+ sType +#9+ sCase +#9+ sProtocol +#9+ sDPort); end; end; // for loop end; // 분리 완료 m_SnortList.SaveToFile(edtSavePath.Text+'/[Separated]Snort.txt'); m_PBList.SaveToFile(edtSavePath.Text+'/[Separated]PatternBlock.txt'); showMessage('분리가 완료 되었습니다.' +#13#10+ Format('Snort : %s개/ 패턴블럭 : %s개',[ IntToStr(m_SnortList.Count), IntToStr(m_PBList.Count - 1)]) ); ShellExecute(Application.Handle, PChar('explore'), PChar(edtSavePath.Text), nil, nil, SW_SHOWNORMAL); finally FreeAndNil(m_SnortList); FreeAndNil(m_PBList); FreeAndNil(m_TmpList); end; end; function TFMain.IsTypeBin(sPayload : String): boolean; var sTemps : TStringList; i: Integer; begin Result := True; if Pos('%', sPayload) = 0 then begin Result := False; Exit; end; sTemps := TstringList.Create; sTemps := Split(sPayload, '%'); for i := 1 to sTemps.Count -1 do begin if (sTemps[i].Length <> 2 ) or ( not IsHex(sTemps[i])) then Result := False; end; FreeAndNil(sTemps); end; function TFMain.CheckHasOptionSnort(sSnortRule: String): boolean; var sTemps : TStringList; nStartPos, nEndPos, i : Integer; begin //옵션 없음 Result := False; sTemps := TstringList.Create; nStartPos := Pos('(',sSnortRule); nEndPos := Pos(';)',sSnortRule); if nStartPos = 0 then begin FreeAndNil(sTemps); Exit; end; Delete(sSnortRule, 1, nStartPos); Delete(sSnortRule, nEndPos - nStartPos, 2); sTemps := Split(sSnortRule, ';'); for i := 0 to sTemps.Count -1 do begin // msg, content, nocase 외 다른 옵션이 있거나, content에 !옵션이 있는 경우. if not (( Pos('msg',sTemps[i]) <> 0 ) or ( Pos('content',sTemps[i]) <> 0 ) or ( Pos('nocase',sTemps[i]) <> 0 ) or ( Pos('sid',sTemps[i]) <> 0 )) or ( Pos('content:!',sTemps[i]) <> 0 ) or ( Pos('content :!',sTemps[i]) <> 0 ) then begin Result := True; FreeAndNil(sTemps); Exit; end; end; FreeAndNil(sTemps); end; procedure TFMain.ParseSnort(sSnortRule: String); var sTemp : String; sAction, sSIP, sSPORT, sDIP : String; begin // init sAction := ''; sProtocol := ''; sSIP := ''; sSPORT := ''; sDIP := ''; sDPORT := ''; sMsg := ''; sContent := ''; // Header Parse // Action sSnortRule := Trim(sSnortRule); sAction := GetToken(sSnortRule, ' '); // protocol sSnortRule := Trim(sSnortRule); sProtocol := GetToken(sSnortRule, ' '); // SIP sSnortRule := Trim(sSnortRule); sSIP := GetToken(sSnortRule, ' '); // SPORT sSnortRule := Trim(sSnortRule); sSPORT := GetToken(sSnortRule, ' '); // Direction sSnortRule := Trim(sSnortRule); sTemp := GetToken(sSnortRule, ' '); // DIP sSnortRule := Trim(sSnortRule); sDIP := GetToken(sSnortRule, ' '); // DPort sSnortRule := Trim(sSnortRule); sDPORT := GetToken(sSnortRule, ' '); if sDPORT = 'any' then sDPort := '80'; // Msg Parse if( Pos('msg:',sSnortRule) > 0 ) or ( Pos('msg :',sSnortRule) > 0 ) then sMsg := parseMsg(sSnortRule) else begin sMsg := 'Unnamed Pattern ' + IntToStr(iUnnamedCnt); iUnnamedCnt := iUnnamedCnt + 1; end; // Content Parse sContent := parseContent(sSnortRule); end; function TFMain.getCase(sPattern : String): String; begin Result := 'y'; if Pos('nocase;', sPattern) > 0 then begin Result := 'n'; Exit; end; end; procedure TFMain.FormCreate(Sender: TObject); begin btnInit.Click; end; procedure TFMain.Button1Click(Sender: TObject); begin try if OpenDialog1.Execute then edtOpenPath.Text := String(OpenDialog1.FileName); finally end; end; procedure TFMain.chkSavePathClick(Sender: TObject); begin btnSavePath.Enabled := chkSavePath.Checked; edtSavePath.Enabled := chkSavePath.Checked; if chkSavePath.Checked then // edtSavePath.Text := '' else edtSavePath.Text := GetCurrentDir; end; procedure TFMain.btnSavePathClick(Sender: TObject); begin try if FolderDialog1.Execute then edtSavePath.Text := String(FolderDialog1.Directory); finally end; end; end.
unit uProduct; {$mode objfpc}{$H+} interface uses SynCommons, mORMot, uForwardDeclaration; type // 1 产品目录 TSQLProdCatalog = class(TSQLRecord) private fCatalogName: RawUTF8; //使用快速增加 fUseQuickAdd: Boolean; //样式表 fStyleSheet: RawUTF8; //头logo fHeaderLogo: RawUTF8; //内容路径前缀 fContentPathPrefix: RawUTF8; //模板路径前缀 fTemplatePathPrefix: RawUTF8; //允许显示 fViewAllowPermReqd: Boolean; //允许购买 fPurchaseAllowPermReqd: Boolean; published property CatalogName: RawUTF8 read fCatalogName write fCatalogName; property UseQuickAdd: Boolean read fUseQuickAdd write fUseQuickAdd; property StyleSheet: RawUTF8 read fStyleSheet write fStyleSheet; property HeaderLogo: RawUTF8 read fHeaderLogo write fHeaderLogo; property ContentPathPrefix: RawUTF8 read fContentPathPrefix write fContentPathPrefix; property TemplatePathPrefix: RawUTF8 read fTemplatePathPrefix write fTemplatePathPrefix; property ViewAllowPermReqd: Boolean read fViewAllowPermReqd write fViewAllowPermReqd; property PurchaseAllowPermReqd: Boolean read fPurchaseAllowPermReqd write fPurchaseAllowPermReqd; end; // 2 产品目录种类 TSQLProdCatalogCategory = class(TSQLRecord) private //产品目录 fProdCatalog: TSQLProdCatalogID; //产品分类 fProductCategory: TSQLProductCategoryID; //产品目录分类类型 fProdCatalogCategoryType: TSQLProdCatalogCategoryTypeID; fFromDate: TDateTime; fThruDate: TDateTime; //序号数字 fSequenceNum: Integer; published property ProdCatalog: TSQLProdCatalogID read fProdCatalog write fProdCatalog; property ProductCategory: TSQLProductCategoryID read fProductCategory write fProductCategory; property ProdCatalogCategoryType: TSQLProdCatalogCategoryTypeID read fProdCatalogCategoryType write fProdCatalogCategoryType; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property SequenceNum: Integer read fSequenceNum write fSequenceNum; end; // 3 产品目录种类类型 TSQLProdCatalogCategoryType = class(TSQLRecord) private fEncode: RawUTF8; fParentEncode: RawUTF8; fParent: TSQLProdCatalogCategoryTypeID; fName: RawUTF8; FDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property ParentEncode: RawUTF8 read fParentEncode write fParentEncode; property Parent: TSQLProdCatalogCategoryTypeID read fParent write fParent; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 4 产品目录库存设施 TSQLProdCatalogInvFacility = class(TSQLRecord) private fProdCatalog: TSQLProdCatalogID; fFacility: TSQLFacilityID; fFromDate: TDateTime; fThruDate: TDateTime; fSequenceNum: Integer; published property ProdCatalog: TSQLProdCatalogID read fProdCatalog write fProdCatalog; property Facility: TSQLFacilityID read fFacility write fFacility; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property SequenceNum: Integer read fSequenceNum write fSequenceNum; end; // 5 产品目录角色 TSQLProdCatalogRole = class(TSQLRecord) private fParty: TSQLPartyID; fRoleType: TSQLRoleTypeID; fProdCatalog: TSQLProdCatalogID; fFromDate: TDateTime; fThruDate: TDateTime; fSequenceNum: Integer; published property Party: TSQLPartyID read fParty write fParty; property RoleType: TSQLRoleTypeID read fRoleType write fRoleType; property ProdCatalog: TSQLProdCatalogID read fProdCatalog write fProdCatalog; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property SequenceNum: Integer read fSequenceNum write fSequenceNum; end; // 6 产品分类 TSQLProductCategory = class(TSQLRecord) private fProductCategoryType: TSQLProductCategoryTypeID; //主上级分类 fPrimaryParentCategory: TSQLProductCategoryID; fCategoryName: RawUTF8; fDescription: RawUTF8; //详细描述 fLongDescription: TSQLRawBlob; //分类图像URL fCategoryImageUrl: RawUTF8; //链接一图像 fLinkOneImageUrl: RawUTF8; //链接二图像 fLinkTwoImageUrl: RawUTF8; //详细屏幕 fDetailScreen: RawUTF8; //列表中展示 fShowInSelect: Boolean; published property ProductCategoryType: TSQLProductCategoryTypeID read fProductCategoryType write fProductCategoryType; property PrimaryParentCategory: TSQLProductCategoryID read fPrimaryParentCategory write fPrimaryParentCategory; property CategoryName: RawUTF8 read fCategoryName write fCategoryName; property Description: RawUTF8 read fDescription write fDescription; property LongDescription: TSQLRawBlob read fLongDescription write fLongDescription; property CategoryImageUrl: RawUTF8 read fCategoryImageUrl write fCategoryImageUrl; property LinkOneImageUrl: RawUTF8 read fLinkOneImageUrl write fLinkOneImageUrl; property LinkTwoImageUrl: RawUTF8 read fLinkTwoImageUrl write fLinkTwoImageUrl; property DetailScreen: RawUTF8 read fDetailScreen write fDetailScreen; property ShowInSelect: Boolean read fShowInSelect write fShowInSelect; end; // 7 产品分类属性 TSQLProductCategoryAttribute = class(TSQLRecord) private fProductCategory: TSQLProductCategoryID; fAttrName: RawUTF8; fAttrValue: RawUTF8; fDescription: RawUTF8; published property ProductCategory: TSQLProductCategoryID read fProductCategory write fProductCategory; property AttrName: RawUTF8 read fAttrName write fAttrName; property AttrValue: RawUTF8 read fAttrValue write fAttrValue; property Description: RawUTF8 read fDescription write fDescription; end; // 8 产品分类内容 TSQLProductCategoryContent = class(TSQLRecord) private fProductCategory: TSQLProductCategoryID; fContent: TSQLContentID; //产品分类内容类型 fProdCatContentType: TSQLProductCategoryContentTypeID; fFromDate: TDateTime; fThruDate: TDateTime; //购买开始日期 fPurchaseFromDate: TDateTime; //购买结束日期 fPurchaseThruDate: TDateTime; //使用数量限制 fUseCountLimit: Integer; //使用天数限制 fUseDaysLimit: Integer; published property ProductCategory: TSQLProductCategoryID read fProductCategory write fProductCategory; property Content: TSQLContentID read fContent write fContent; property ProdCatContentType: TSQLProductCategoryContentTypeID read fProdCatContentType write fProdCatContentType; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property PurchaseFromDate: TDateTime read fPurchaseFromDate write fPurchaseFromDate; property PurchaseThruDate: TDateTime read fPurchaseThruDate write fPurchaseThruDate; property UseCountLimit: Integer read fUseCountLimit write fUseCountLimit; property UseDaysLimit: Integer read fUseDaysLimit write fUseDaysLimit; end; // 9 产品分类内容类型 TSQLProductCategoryContentType = class(TSQLRecord) private fEncode: RawUTF8; fParentEncode: RawUTF8; fParent: TSQLProductCategoryContentTypeID; fHasTable: Boolean; fName: RawUTF8; fDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property ParentEncode: RawUTF8 read fParentEncode write fParentEncode; property Parent: TSQLProductCategoryContentTypeID read fParent write fParent; property HasTable: Boolean read fHasTable write fHasTable; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read fDescription write fDescription; end; // 10 产品分类总账账务 TSQLProductCategoryGlAccount = class(TSQLRecord) private fProductCategory: TSQLProductCategoryID; fOrganizationParty: TSQLPartyID; fGlAccountType: TSQLGlAccountTypeID; fGlAccount: TSQLGlAccountID; published property ProductCategory: TSQLProductCategoryID read fProductCategory write fProductCategory; property OrganizationParty: TSQLPartyID read fOrganizationParty write fOrganizationParty; property GlAccountType: TSQLGlAccountTypeID read fGlAccountType write fGlAccountType; property GlAccount: TSQLGlAccountID read fGlAccount write fGlAccount; end; // 11 产品分类关联 TSQLProductCategoryLink = class(TSQLRecord) private fProductCategory: TSQLProductCategoryID; //链接序号 fLinkSeq: Integer; fFromDate: TDateTime; fThruDate: TDateTime; fComments: RawUTF8; //序号数字 fSequenceNum: Integer; //标题文本 fTitleText: RawUTF8; //详细说明 fDetailText: TSQLRawBlob; //图像URL fImageUrl: RawUTF8; //图像2URL fImageTwoUrl: RawUTF8; //链接类型枚举 fLinkTypeEnum: TSQLEnumerationID; //链接信息 fLinkInfo: RawUTF8; //详细的子屏幕 fDetailSubScreen: RawUTF8; published property ProductCategory: TSQLProductCategoryID read fProductCategory write fProductCategory; property LinkSeq: Integer read fLinkSeq write fLinkSeq; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property Comments: RawUTF8 read fComments write fComments; property SequenceNum: Integer read fSequenceNum write fSequenceNum; property TitleText: RawUTF8 read fTitleText write fTitleText; property DetailText: TSQLRawBlob read fDetailText write fDetailText; property ImageUrl: RawUTF8 read fImageUrl write fImageUrl; property ImageTwoUrl: RawUTF8 read fImageTwoUrl write fImageTwoUrl; property LinkTypeEnum: TSQLEnumerationID read fLinkTypeEnum write fLinkTypeEnum; property LinkInfo: RawUTF8 read fLinkInfo write fLinkInfo; property DetailSubScreen: RawUTF8 read fDetailSubScreen write fDetailSubScreen; end; // 12 产品分类成员 TSQLProductCategoryMember = class(TSQLRecord) private fProductCategory: TSQLProductCategoryID; fProduct: TSQLProductID; fFromDate: TDateTime; fThruDate: TDateTime; fComments: RawUTF8; fSequenceNum: Integer; //数量 fQuantity: Double; published property ProductCategory: TSQLProductCategoryID read fProductCategory write fProductCategory; property Product: TSQLProductID read fProduct write fProduct; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property Comments: RawUTF8 read fComments write fComments; property SequenceNum: Integer read fSequenceNum write fSequenceNum; property Quantity: Double read fQuantity write fQuantity; end; // 13 产品分类角色 TSQLProductCategoryRole = class(TSQLRecord) private fProductCategory: TSQLProductCategoryID; fParty: TSQLPartyID; fRoleType: TSQLRoleTypeID; fFromDate: TDateTime; fThruDate: TDateTime; fComments: RawUTF8; published property ProductCategory: TSQLProductCategoryID read fProductCategory write fProductCategory; property Party: TSQLPartyID read fParty write fParty; property RoleType: TSQLRoleTypeID read fRoleType write fRoleType; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property Comments: RawUTF8 read fComments write fComments; end; // 14 产品分类隶属关系 TSQLProductCategoryRollup = class(TSQLRecord) private fProductCategory: TSQLProductCategoryID; fparentProductCategory: TSQLProductCategoryID; fFromDate: TDateTime; fThruDate: TDateTime; fSequenceNum: Integer; published property ProductCategory: TSQLProductCategoryID read fProductCategory write fProductCategory; property parentProductCategory: TSQLProductCategoryID read fparentProductCategory write fparentProductCategory; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property SequenceNum: Integer read fSequenceNum write fSequenceNum; end; // 15 产品分类类型 TSQLProductCategoryType = class(TSQLRecord) private fEncode: RawUTF8; fParentEncode: RawUTF8; fParent: TSQLProductCategoryTypeID; fHasTable: Boolean; fName: RawUTF8; FDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property ParentEncode: RawUTF8 read fParentEncode write fParentEncode; property Parent: TSQLProductCategoryTypeID read fParent write fParent; property HasTable: Boolean read fHasTable write fHasTable; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 16 产品分类类型属性 TSQLProductCategoryTypeAttr = class(TSQLRecord) private fProductCategoryType: TSQLProductCategoryTypeID; fAttrName: RawUTF8; fDescription: RawUTF8; published property ProductCategoryType: TSQLProductCategoryTypeID read fProductCategoryType write fProductCategoryType; property AttrName: RawUTF8 read fAttrName write fAttrName; property Description: RawUTF8 read fDescription write fDescription; end; // 17 TSQLProductConfig = class(TSQLRecord) private fProduct: TSQLProductID; fConfigItem: TSQLProductConfigItemID; fSequenceNum: Integer; fFromDate: TDateTime; fThruDate: TDateTime; FDescription: RawUTF8; FLongDescription: RawUTF8; fConfigType: RawUTF8; fDefaultConfigOption: RawUTF8; fIsMandatory: Boolean; published property Product: TSQLProductID read fProduct write fProduct; property ConfigItem: TSQLProductConfigItemID read fConfigItem write fConfigItem; property SequenceNum: Integer read fSequenceNum write fSequenceNum; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property Description: RawUTF8 read FDescription write FDescription; property LongDescription: RawUTF8 read FLongDescription write FLongDescription; property ConfigType: RawUTF8 read fConfigType write fConfigType; property DefaultConfigOption: RawUTF8 read fDefaultConfigOption write fDefaultConfigOption; property IsMandatory: Boolean read fIsMandatory write fIsMandatory; end; // 18 TSQLProductConfigItem = class(TSQLRecord) private fConfigItemType: RawUTF8;//? fConfigItemName: RawUTF8; FDescription: RawUTF8; FLongDescription: RawUTF8; fImageUrl: RawUTF8; published property ConfigItemType: RawUTF8 read fConfigItemType write fConfigItemType; property ConfigItemName: RawUTF8 read fConfigItemName write fConfigItemName; property Description: RawUTF8 read FDescription write FDescription; property LongDescription: RawUTF8 read FLongDescription write FLongDescription; property ImageUrl: RawUTF8 read fImageUrl write fImageUrl; end; // 19 TSQLProdConfItemContent = class(TSQLRecord) private fConfigItem: TSQLProductConfigItemID; fContent: TSQLContentID; fConfItemContentType: TSQLProdConfItemContentTypeID; fFromDate: TDateTime; fThruDate: TDateTime; published property ConfigItem: TSQLProductConfigItemID read fConfigItem write fConfigItem; property Content: TSQLContentID read fContent write fContent; property ConfItemContentType: TSQLProdConfItemContentTypeID read fConfItemContentType write fConfItemContentType; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; end; // 20 TSQLProdConfItemContentType = class(TSQLRecord) private fEncode: RawUTF8; fParentEncode: RawUTF8; fParent: TSQLProdConfItemContentTypeID; fHasTable: Boolean; fName: RawUTF8; FDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property ParentEncode: RawUTF8 read fParentEncode write fParentEncode; property Parent: TSQLProdConfItemContentTypeID read fParent write fParent; property HasTable: Boolean read fHasTable write fHasTable; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 21 TSQLProductConfigOption = class(TSQLRecord) private fConfigItem: TSQLProductConfigItemID; fConfigOption: RawUTF8; fConfigOptionName: RawUTF8; FDescription: RawUTF8; fSequenceNum: Integer; published property ConfigItem: TSQLProductConfigItemID read fConfigItem write fConfigItem; property ConfigOption: RawUTF8 read fConfigOption write fConfigOption; property ConfigOptionName: RawUTF8 read fConfigOptionName write fConfigOptionName; property Description: RawUTF8 read FDescription write FDescription; property SequenceNum: Integer read fSequenceNum write fSequenceNum; end; // 22 TSQLProductConfigOptionIactn = class(TSQLRecord) private fConfigItem: TSQLProductConfigItemID; fConfigOption: TSQLProductConfigOptionID; fConfigItemTo: TSQLProductConfigItemID; fConfigOptionTo: TSQLProductConfigOptionID; fConfigIactnType: RawUTF8; //? fSequenceNum: Integer; FDescription: RawUTF8; published property ConfigItem: TSQLProductConfigItemID read fConfigItem write fConfigItem; property ConfigOption: TSQLProductConfigOptionID read fConfigOption write fConfigOption; property ConfigItemTo: TSQLProductConfigItemID read fConfigItemTo write fConfigItemTo; property ConfigOptionTo: TSQLProductConfigOptionID read fConfigOptionTo write fConfigOptionTo; property ConfigIactnType: RawUTF8 read fConfigIactnType write fConfigIactnType; property SequenceNum: Integer read fSequenceNum write fSequenceNum; property Description: RawUTF8 read FDescription write FDescription; end; // 23 TSQLProductConfigProduct = class(TSQLRecord) private fConfigItem: TSQLProductConfigItemID; fConfigOption: TSQLProductConfigOptionID; fProduct: TSQLProductID; fQuantity: Double; fSequenceNum: Integer; published property ConfigItem: TSQLProductConfigItemID read fConfigItem write fConfigItem; property ConfigOption: TSQLProductConfigOptionID read fConfigOption write fConfigOption; property Product: TSQLProductID read fProduct write fProduct; property Quantity: Double read fQuantity write fQuantity; property SequenceNum: Integer read fSequenceNum write fSequenceNum; end; // 24 TSQLProductConfigConfig = class(TSQLRecord) private fConfigItem: TSQLProductConfigItemID; fConfigOption: TSQLProductConfigOptionID; fSequenceNum: Integer; FDescription: RawUTF8; published property ConfigItem: TSQLProductConfigItemID read fConfigItem write fConfigItem; property ConfigOption: TSQLProductConfigOptionID read fConfigOption write fConfigOption; property SequenceNum: Integer read fSequenceNum write fSequenceNum; property Description: RawUTF8 read FDescription write FDescription; end; // 25 TSQLProductConfigStats = class(TSQLRecord) private fProduct: TSQLProductID; fNumOfConfs: Double; fConfigType: RawUTF8; //HIDDEN, TEMPLATE, etc... published property Product: TSQLProductID read fProduct write fProduct; property NumOfConfs: Double read fNumOfConfs write fNumOfConfs; property ConfigType: RawUTF8 read fConfigType write fConfigType; end; //? 26 TSQLConfigOptionProductOption = class(TSQLRecord) private fConfigItem: Integer; fSequenceNum: Integer; fConfigOption: Integer; fproduct: Integer; fproductOption: Integer; FDescription: RawUTF8; published property ConfigItem: Integer read fConfigItem write fConfigItem; property SequenceNum: Integer read fSequenceNum write fSequenceNum; property ConfigOption: Integer read fConfigOption write fConfigOption; property product: Integer read fproduct write fproduct; property productOption: Integer read fproductOption write fproductOption; property Description: RawUTF8 read FDescription write FDescription; end; // 27 TSQLCostComponent = class(TSQLRecord) private fCostComponentType: TSQLCostComponentTypeID; fProduct: TSQLProductID; fProductFeature: TSQLProductFeatureID; fParty: TSQLPartyID; fGeo: TSQLGeoID; fWorkEffort: TSQLWorkEffortID; fFixedAsset: TSQLFixedAssetID; fCostComponentCalc: TSQLCostComponentCalcID; fFromDate: TDateTime; fThruDate: TDateTime; fCost: Double; fCostUom: TSQLUomID; published property CostComponentType: TSQLCostComponentTypeID read fCostComponentType write fCostComponentType; property Product: TSQLProductID read fProduct write fProduct; property ProductFeature: TSQLProductFeatureID read fProductFeature write fProductFeature; property Party: TSQLPartyID read fParty write fParty; property Geo: TSQLGeoID read fGeo write fGeo; property WorkEffort: TSQLWorkEffortID read fWorkEffort write fWorkEffort; property FixedAsset: TSQLFixedAssetID read fFixedAsset write fFixedAsset; property CostComponentCalc: TSQLCostComponentCalcID read fCostComponentCalc write fCostComponentCalc; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property Cost: Double read fCost write fCost; property CostUom: TSQLUomID read fCostUom write fCostUom; end; // 28 TSQLCostComponentAttribute = class(TSQLRecord) private fCostComponent: TSQLCostComponentID; fAttrName: TSQLCostComponentTypeAttrID; fAttrValue: RawUTF8; fAttrDescription: RawUTF8; published property CostComponent: TSQLCostComponentID read fCostComponent write fCostComponent; property AttrName: TSQLCostComponentTypeAttrID read fAttrName write fAttrName; property AttrValue: RawUTF8 read fAttrValue write fAttrValue; property AttrDescription: RawUTF8 read fAttrDescription write fAttrDescription; end; // 29 TSQLCostComponentType = class(TSQLRecord) private fEncode: RawUTF8; fParentEncode: RawUTF8; fParent: TSQLCostComponentTypeID; fHasTable: Boolean; fName: RawUTF8; FDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property ParentEncode: RawUTF8 read fParentEncode write fParentEncode; property Parent: TSQLCostComponentTypeID read fParent write fParent; property HasTable: Boolean read fHasTable write fHasTable; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 30 TSQLCostComponentTypeAttr = class(TSQLRecord) private fCostComponentType: TSQLCostComponentTypeID; fAttrName: TSQLCostComponentAttributeID; fDescription: RawUTF8; published property CostComponentType: TSQLCostComponentTypeID read fCostComponentType write fCostComponentType; property AttrName: TSQLCostComponentAttributeID read fAttrName write fAttrName; property Description: RawUTF8 read fDescription write fDescription; end; // 31 TSQLCostComponentCalc = class(TSQLRecord) private fCostGlAccountType: TSQLGlAccountTypeID; fOffsettingGlAccountType: TSQLGlAccountTypeID; fFixedCost: Currency; fVariableCost: Currency; fPerMilliSecond: Double; fCurrencyUom: TSQLUomID; fCostCustomMethod: TSQLCustomMethodID; fDescription: RawUTF8; published property CostGlAccountType: TSQLGlAccountTypeID read fCostGlAccountType write fCostGlAccountType; property OffsettingGlAccountType: TSQLGlAccountTypeID read fOffsettingGlAccountType write fOffsettingGlAccountType; property FixedCost: Currency read fFixedCost write fFixedCost; property VariableCost: Currency read fVariableCost write fVariableCost; property PerMilliSecond: Double read fPerMilliSecond write fPerMilliSecond; property CurrencyUom: TSQLUomID read fCurrencyUom write fCurrencyUom; property CostCustomMethod: TSQLCustomMethodID read fCostCustomMethod write fCostCustomMethod; property Description: RawUTF8 read fDescription write fDescription; end; // 32 TSQLProductCostComponentCalc = class(TSQLRecord) private fProduct: TSQLProductID; fCostComponentType: TSQLCostComponentTypeID; fCostComponentCalc: TSQLCostComponentCalcID; fFromDate: TDateTime; fThruDate: TDateTime; fSequenceNum: Integer; published property Product: TSQLProductID read fProduct write fProduct; property CostComponentType: TSQLCostComponentTypeID read fCostComponentType write fCostComponentType; property CostComponentCalc: TSQLCostComponentCalcID read fCostComponentCalc write fCostComponentCalc; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property SequenceNum: Integer read fSequenceNum write fSequenceNum; end; // 33 TSQLContainer = class(TSQLRecord) private fContainerType: TSQLContainerTypeID; fFacility: TSQLFacilityID; fDescription: RawUTF8; published property ContainerType: TSQLContainerTypeID read fContainerType write fContainerType; property Facility: TSQLFacilityID read fFacility write fFacility; property Description: RawUTF8 read fDescription write fDescription; end; // 34 TSQLContainerType = class(TSQLRecord) private fName: RawUTF8; FDescription: RawUTF8; published property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 35 TSQLContainerGeoPoint = class(TSQLRecord) private fContainer: TSQLContainerID; fGeoPoint: TSQLGeoPointID; fFromDate: TDateTime; fThruDate: TDateTime; published property Container: TSQLContainerID read fContainer write fContainer; property GeoPoint: TSQLGeoPointID read fGeoPoint write fGeoPoint; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; end; // 36 TSQLFacility = class(TSQLRecord) private fFacilityType: TSQLFacilityTypeID; fParentFacility: TSQLFacilityID; fOwnerParty: TSQLPartyID; fDefaultInventoryItemType: TSQLInventoryItemTypeID; fFacilityName: RawUTF8; fPrimaryFacilityGroup: TSQLFacilityGroupID; fOldSquareFootage: Double; fFacilitySize: Double; fFacilitySizeUom: TSQLUomID; fProductStore: TSQLProductStoreID; fDefaultDaysToShip: Double; fOpenedDate: TDateTime; fClosedDate: TDateTime; fDescription: RawUTF8; fDefaultDimensionUom: TSQLUomID; fDefaultWeightUom: TSQLUomID; fGeoPoint: TSQLGeoPointID; published property FacilityType: TSQLFacilityTypeID read fFacilityType write fFacilityType; property ParentFacility: TSQLFacilityID read fParentFacility write fParentFacility; property OwnerParty: TSQLPartyID read fOwnerParty write fOwnerParty; property DefaultInventoryItemType: TSQLInventoryItemTypeID read fDefaultInventoryItemType write fDefaultInventoryItemType; property FacilityName: RawUTF8 read fFacilityName write fFacilityName; property PrimaryFacilityGroup: TSQLFacilityGroupID read fPrimaryFacilityGroup write fPrimaryFacilityGroup; property OldSquareFootage: Double read fOldSquareFootage write fOldSquareFootage; property FacilitySize: Double read fFacilitySize write fFacilitySize; property FacilitySizeUom: TSQLUomID read fFacilitySizeUom write fFacilitySizeUom; property ProductStore: TSQLProductStoreID read fProductStore write fProductStore; property DefaultDaysToShip: Double read fDefaultDaysToShip write fDefaultDaysToShip; property OpenedDate: TDateTime read fOpenedDate write fOpenedDate; property ClosedDate: TDateTime read fClosedDate write fClosedDate; property Description: RawUTF8 read fDescription write fDescription; property DefaultDimensionUom: TSQLUomID read fDefaultDimensionUom write fDefaultDimensionUom; property DefaultWeightUom: TSQLUomID read fDefaultWeightUom write fDefaultWeightUom; property GeoPoint: TSQLGeoPointID read fGeoPoint write fGeoPoint; end; // 37 TSQLFacilityAttribute = class(TSQLRecord) private fFacility: TSQLFacilityID; fAttrName: TSQLFacilityTypeAttrID; fAttrValue: RawUTF8; fAttrDescription: RawUTF8; published property Facility: TSQLFacilityID read fFacility write fFacility; property AttrName: TSQLFacilityTypeAttrID read fAttrName write fAttrName; property AttrValue: RawUTF8 read fAttrValue write fAttrValue; property AttrDescription: RawUTF8 read fAttrDescription write fAttrDescription; end; // 38 TSQLFacilityCalendar = class(TSQLRecord) private fFacility: TSQLFacilityID; fCalendar: TSQLTechDataCalendarID; fFacilityCalendarType: TSQLFacilityCalendarTypeID; fFromDate: TDateTime; fThruDate: TDateTime; published property Facility: TSQLFacilityID read fFacility write fFacility; property Calendar: TSQLTechDataCalendarID read fCalendar write fCalendar; property FacilityCalendarType: TSQLFacilityCalendarTypeID read fFacilityCalendarType write fFacilityCalendarType; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; end; // 39 TSQLFacilityCalendarType = class(TSQLRecord) private fParent: TSQLFacilityCalendarTypeID; fHasTable: Boolean; fName: RawUTF8; FDescription: RawUTF8; published property Parent: TSQLFacilityCalendarTypeID read fParent write fParent; property HasTable: Boolean read fHasTable write fHasTable; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 40 TSQLFacilityCarrierShipment = class(TSQLRecord) private fFacility: TSQLFacilityID; fParty: TSQLPartyID; fRoleType: TSQLCarrierShipmentMethodID; //? fShipmentMethodType: TSQLShipmentMethodTypeID; published property Facility: TSQLFacilityID read fFacility write fFacility; property Party: TSQLPartyID read fParty write fParty; property RoleType: TSQLCarrierShipmentMethodID read fRoleType write fRoleType; property ShipmentMethodType: TSQLShipmentMethodTypeID read fShipmentMethodType write fShipmentMethodType; end; // 41 TSQLFacilityContactMech = class(TSQLRecord) private fFacility: TSQLFacilityID; fContactMech: TSQLContactMechID; fFromDate: TDateTime; fThruDate: TDateTime; fExtension: RawUTF8; fComments: RawUTF8; published property Facility: TSQLFacilityID read fFacility write fFacility; property ContactMech: TSQLContactMechID read fContactMech write fContactMech; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property Extension: RawUTF8 read fExtension write fExtension; property Comments: RawUTF8 read fComments write fComments; end; // 42 TSQLFacilityContactMechPurpose = class(TSQLRecord) private fFacility: TSQLFacilityID; fContactMech: TSQLContactMechID; fContactMechPurposeType: TSQLContactMechPurposeTypeID; fFromDate: TDateTime; fThruDate: TDateTime; published property Facility: TSQLFacilityID read fFacility write fFacility; property ContactMech: TSQLContactMechID read fContactMech write fContactMech; property ContactMechPurposeType: TSQLContactMechPurposeTypeID read fContactMechPurposeType write fContactMechPurposeType; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; end; // 43 TSQLFacilityGroup = class(TSQLRecord) private fEncode: RawUTF8; fFacilityGroupTypeEncode: RawUTF8; fPrimaryParentGroupEncode: RawUTF8; fFacilityGroupType: TSQLFacilityGroupTypeID; fPrimaryParentGroup: TSQLFacilityGroupID; fName: RawUTF8; fDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property FacilityGroupTypeEncode: RawUTF8 read fFacilityGroupTypeEncode write fFacilityGroupTypeEncode; property PrimaryParentGroupEncode: RawUTF8 read fPrimaryParentGroupEncode write fPrimaryParentGroupEncode; property FacilityGroupType: TSQLFacilityGroupTypeID read fFacilityGroupType write fFacilityGroupType; property PrimaryParentGroup: TSQLFacilityGroupID read fPrimaryParentGroup write fPrimaryParentGroup; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read fDescription write fDescription; end; // 44 TSQLFacilityGroupMember = class(TSQLRecord) private fFacility: TSQLFacilityID; fFacilityGroup: TSQLFacilityGroupID; fFromDate: TDateTime; fThruDate: TDateTime; fSequenceNum: Integer; published property Facility: TSQLFacilityID read fFacility write fFacility; property FacilityGroup: TSQLFacilityGroupID read fFacilityGroup write fFacilityGroup; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property SequenceNum: Integer read fSequenceNum write fSequenceNum; end; // 45 TSQLFacilityGroupRole = class(TSQLRecord) private fFacilityGroup: TSQLFacilityGroupID; fParty: TSQLPartyID; fRoleType: TSQLRoleTypeID; published property FacilityGroup: TSQLFacilityGroupID read fFacilityGroup write fFacilityGroup; property Party: TSQLPartyID read fParty write fParty; property RoleType: TSQLRoleTypeID read fRoleType write fRoleType; end; // 46 TSQLFacilityGroupRollup = class(TSQLRecord) private fFacilityGroup: TSQLFacilityGroupID; fParentFacilityGroup: TSQLFacilityGroupRollupID; fFromDate: TDateTime; fThruDate: TDateTime; fSequenceNum: Integer; published property FacilityGroup: TSQLFacilityGroupID read fFacilityGroup write fFacilityGroup; property ParentFacilityGroup: TSQLFacilityGroupRollupID read fParentFacilityGroup write fParentFacilityGroup; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property SequenceNum: Integer read fSequenceNum write fSequenceNum; end; // 47 TSQLFacilityGroupType = class(TSQLRecord) private fEncode: RawUTF8; fName: RawUTF8; FDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 48 TSQLFacilityLocation = class(TSQLRecord) private fFacility: TSQLFacilityID; fLocationSeq: Integer; fLocationTypeEnum: TSQLEnumerationID; fArea: Integer; fAisle: Integer; fSection: Integer; fLevel: Integer; fPosition: Integer; fGeoPoint: TSQLGeoPointID; published property Facility: TSQLFacilityID read fFacility write fFacility; property LocationSeq: Integer read fLocationSeq write fLocationSeq; property LocationTypeEnum: TSQLEnumerationID read fLocationTypeEnum write fLocationTypeEnum; property Area: Integer read fArea write fArea; property Aisle: Integer read fAisle write fAisle; property Section: Integer read fSection write fSection; property Level: Integer read fLevel write fLevel; property Position: Integer read fPosition write fPosition; property GeoPoint: TSQLGeoPointID read fGeoPoint write fGeoPoint; end; // 49 TSQLFacilityLocationGeoPoint = class(TSQLRecord) private fFacility: TSQLFacilityID; fLocationSeq: Integer; fGeoPoint: TSQLGeoPointID; fFromDate: TDateTime; fThruDate: TDateTime; published property Facility: TSQLFacilityID read fFacility write fFacility; property LocationSeq: Integer read fLocationSeq write fLocationSeq; property GeoPoint: TSQLGeoPointID read fGeoPoint write fGeoPoint; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; end; // 50 TSQLFacilityParty = class(TSQLRecord) private fFacility: TSQLFacilityID; fParty: TSQLPartyID; fRoleType: TSQLRoleTypeID; fFromDate: TDateTime; fThruDate: TDateTime; published property Facility: TSQLFacilityID read fFacility write fFacility; property Party: TSQLPartyID read fParty write fParty; property RoleType: TSQLRoleTypeID read fRoleType write fRoleType; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; end; // 51 TSQLFacilityContent = class(TSQLRecord) private fFacility: TSQLFacilityID; fContent: TSQLContentID; fFromDate: TDateTime; fThruDate: TDateTime; published property Facility: TSQLFacilityID read fFacility write fFacility; property Content: TSQLContentID read fContent write fContent; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; end; // 52 TSQLFacilityType = class(TSQLRecord) private fEncode: RawUTF8; fParentEncode: RawUTF8; fParent: TSQLFacilityTypeID; fHasTable: Boolean; fName: RawUTF8; FDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property ParentEncode: RawUTF8 read fParentEncode write fParentEncode; property Parent: TSQLFacilityTypeID read fParent write fParent; property HasTable: Boolean read fHasTable write fHasTable; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 53 TSQLFacilityTypeAttr = class(TSQLRecord) private fFacilityType: TSQLFacilityTypeID; fAttrName: TSQLFacilityAttributeID; fDescription: RawUTF8; published property FacilityType: TSQLFacilityTypeID read fFacilityType write fFacilityType; property AttrName: TSQLFacilityAttributeID read fAttrName write fAttrName; property Description: RawUTF8 read fDescription write fDescription; end; // 54 TSQLProductFacility = class(TSQLRecord) private fProduct: TSQLProductID; fFacility: TSQLFacilityID; fMinimumStock: Double; fReorderQuantity: Double; fDaysToShip: Double; fLastInventoryCount: Double; published property Product: TSQLProductID read fProduct write fProduct; property Facility: TSQLFacilityID read fFacility write fFacility; property MinimumStock: Double read fMinimumStock write fMinimumStock; property ReorderQuantity: Double read fReorderQuantity write fReorderQuantity; property DaysToShip: Double read fDaysToShip write fDaysToShip; property LastInventoryCount: Double read fLastInventoryCount write fLastInventoryCount; end; // 55 TSQLProductFacilityLocation = class(TSQLRecord) private fProduct: TSQLProductID; fFacility: TSQLFacilityID; fLocationSeq: Integer; fMinimumStock: Double; fMoveQuantity: Double; published property Product: TSQLProductID read fProduct write fProduct; property Facility: TSQLFacilityID read fFacility write fFacility; property LocationSeq: Integer read fLocationSeq write fLocationSeq; property MinimumStock: Double read fMinimumStock write fMinimumStock; property MoveQuantity: Double read fMoveQuantity write fMoveQuantity; end; // 56 TSQLProductFeature = class(TSQLRecord) private fEncode: RawUTF8; fProductFeatureTypeEncode: RawUTF8; fProductFeatureCategoryEncode: RawUTF8; fProductFeatureType: TSQLProductFeatureTypeID; fProductFeatureCategory: TSQLProductFeatureCategoryID; fDescription: RawUTF8; fUom: TSQLUomID; fNumberSpecified: Double; fDefaultAmount: Double; fDefaultSequenceNum: Integer; fAbbrev: RawUTF8; fIdCode: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property ProductFeatureTypeEncode: RawUTF8 read fProductFeatureTypeEncode write fProductFeatureTypeEncode; property ProductFeatureCategoryEncode: RawUTF8 read fProductFeatureCategoryEncode write fProductFeatureCategoryEncode; property ProductFeatureType: TSQLProductFeatureTypeID read fProductFeatureType write fProductFeatureType; property ProductFeatureCategory: TSQLProductFeatureCategoryID read fProductFeatureCategory write fProductFeatureCategory; property Description: RawUTF8 read fDescription write fDescription; property Uom: TSQLUomID read fUom write fUom; property NumberSpecified: Double read fNumberSpecified write fNumberSpecified; property DefaultAmount: Double read fDefaultAmount write fDefaultAmount; property DefaultSequenceNum: Integer read fDefaultSequenceNum write fDefaultSequenceNum; property Abbrev: RawUTF8 read fAbbrev write fAbbrev; property IdCode: RawUTF8 read fIdCode write fIdCode; end; // 57 TSQLProductFeatureAppl = class(TSQLRecord) private fProduct: TSQLProductID; fProductFeature: TSQLProductFeatureID; fProductFeatureApplType: TSQLProductFeatureApplTypeID; fFromDate: TDateTime; fThruDate: TDateTime; fSequenceNum: Integer; fAmount: Double; fRecurringAmount: Double; published property Product: TSQLProductID read fProduct write fProduct; property ProductFeature: TSQLProductFeatureID read fProductFeature write fProductFeature; property ProductFeatureApplType: TSQLProductFeatureApplTypeID read fProductFeatureApplType write fProductFeatureApplType; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property SequenceNum: Integer read fSequenceNum write fSequenceNum; property Amount: Double read fAmount write fAmount; property RecurringAmount: Double read fRecurringAmount write fRecurringAmount; end; // 58 TSQLProductFeatureApplType = class(TSQLRecord) private fEncode: RawUTF8; fParentEncode: RawUTF8; fParent: TSQLProductFeatureApplTypeID; fHasTable: Boolean; fName: RawUTF8; FDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property ParentEncode: RawUTF8 read fParentEncode write fParentEncode; property Parent: TSQLProductFeatureApplTypeID read fParent write fParent; property HasTable: Boolean read fHasTable write fHasTable; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 59 TSQLProductFeatureApplAttr = class(TSQLRecord) private fProduct: TSQLProductID; fProductFeature: TSQLProductFeatureID; fFromDate: TDateTime; fAttrName: RawUTF8; fAttrValue: Double; published property Product: TSQLProductID read fProduct write fProduct; property ProductFeature: TSQLProductFeatureID read fProductFeature write fProductFeature; property FromDate: TDateTime read fFromDate write fFromDate; property AttrName: RawUTF8 read fAttrName write fAttrName; property AttrValue: Double read fAttrValue write fAttrValue; end; // 60 TSQLProductFeatureCategory = class(TSQLRecord) private fEncode: RawUTF8; fParentEncode: RawUTF8; fParent: TSQLProductFeatureCategoryID; fName: RawUTF8; FDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property ParentEncode: RawUTF8 read fParentEncode write fParentEncode; property Parent: TSQLProductFeatureCategoryID read fParent write fParent; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 61 TSQLProductFeatureCategoryAppl = class(TSQLRecord) private fProductCategory: TSQLProductCategoryID; fProductFeatureCategory: TSQLProductFeatureCategoryID; fFromDate: TDateTime; fThruDate: TDateTime; published property ProductCategory: TSQLProductCategoryID read fProductCategory write fProductCategory; property ProductFeatureCategory: TSQLProductFeatureCategoryID read fProductFeatureCategory write fProductFeatureCategory; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; end; // 62 TSQLProductFeatureCatGrpAppl = class(TSQLRecord) private fProductCategory: TSQLProductCategoryID; fProductFeatureGroup: TSQLProductFeatureGroupID; fFromDate: TDateTime; fThruDate: TDateTime; published property ProductCategory: TSQLProductCategoryID read fProductCategory write fProductCategory; property ProductFeatureGroup: TSQLProductFeatureGroupID read fProductFeatureGroup write fProductFeatureGroup; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; end; // 63 TSQLProductFeatureDataResource = class(TSQLRecord) private fDataResource: TSQLDataResourceID; fProductFeature: TSQLProductFeatureID; published property DataResource: TSQLDataResourceID read fDataResource write fDataResource; property ProductFeature: TSQLProductFeatureID read fProductFeature write fProductFeature; end; // 64 TSQLProductFeatureGroup = class(TSQLRecord) private fName: RawUTF8; FDescription: RawUTF8; published property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 65 TSQLProductFeatureGroupAppl = class(TSQLRecord) private fProductFeatureGroup: TSQLProductFeatureGroupID; fProductFeature: TSQLProductFeatureID; fFromDate: TDateTime; fThruDate: TDateTime; fSequenceNum: Integer; published property ProductFeatureGroup: TSQLProductFeatureGroupID read fProductFeatureGroup write fProductFeatureGroup; property ProductFeature: TSQLProductFeatureID read fProductFeature write fProductFeature; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property SequenceNum: Integer read fSequenceNum write fSequenceNum; end; // 66 TSQLProductFeatureIactn = class(TSQLRecord) private fProductFeature: TSQLProductFeatureID; fProductFeatureTo: TSQLProductFeatureID; fProductFeatureIactnType: TSQLProductFeatureIactnTypeID; fProduct: TSQLProductID; published property ProductFeature: TSQLProductFeatureID read fProductFeature write fProductFeature; property ProductFeatureTo: TSQLProductFeatureID read fProductFeature write fProductFeature; property ProductFeatureIactnType: TSQLProductFeatureIactnTypeID read fProductFeatureIactnType write fProductFeatureIactnType; property Product: TSQLProductID read fProduct write fProduct; end; // 67 TSQLProductFeatureIactnType = class(TSQLRecord) private fEncode: RawUTF8; fParentEncode: RawUTF8; fParent: TSQLProductFeatureIactnTypeID; fHasTable: Boolean; fName: RawUTF8; FDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property ParentEncode: RawUTF8 read fParentEncode write fParentEncode; property Parent: TSQLProductFeatureIactnTypeID read fParent write fParent; property HasTable: Boolean read fHasTable write fHasTable; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 68 TSQLProductFeatureType = class(TSQLRecord) private fEncode: RawUTF8; fParentEncode: RawUTF8; fParent: TSQLProductFeatureTypeID; fHasTable: Boolean; fName: RawUTF8; FDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property ParentEncode: RawUTF8 read fParentEncode write fParentEncode; property Parent: TSQLProductFeatureTypeID read fParent write fParent; property HasTable: Boolean read fHasTable write fHasTable; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 69 TSQLProductFeaturePrice = class(TSQLRecord) private fProductFeature: TSQLProductFeatureID; fProductPriceType: TSQLProductPriceTypeID; fCurrencyUom: TSQLUomID; fFromDate: TDateTime; fThruDate: TDateTime; fPrice: Currency; fCreatedDate: TDateTime; fCreatedByUserLogin: TSQLUserLoginID; fLastModifiedDate: TDateTime; fLastModifiedByUserLogin: TSQLUserLoginID; published property ProductFeature: TSQLProductFeatureID read fProductFeature write fProductFeature; property ProductPriceType: TSQLProductPriceTypeID read fProductPriceType write fProductPriceType; property CurrencyUom: TSQLUomID read fCurrencyUom write fCurrencyUom; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property Price: Currency read fPrice write fPrice; property CreatedDate: TDateTime read fCreatedDate write fCreatedDate; property CreatedByUserLogin: TSQLUserLoginID read fCreatedByUserLogin write fCreatedByUserLogin; property LastModifiedDate: TDateTime read fLastModifiedDate write fLastModifiedDate; property LastModifiedByUserLogin: TSQLUserLoginID read fLastModifiedByUserLogin write fLastModifiedByUserLogin; end; // 70 TSQLInventoryItem = class(TSQLRecord) private fInventoryItemType: TSQLInventoryItemTypeID; fProduct: TSQLProductID; fParty: TSQLPartyID; fOwnerParty: TSQLPartyID; fStatus: TSQLStatusItemID; fDatetimeReceived: TDateTime; fDatetimeManufactured: TDateTime; fExpireDate: TDateTime; fFacility: TSQLFacilityID; fContainer: TSQLContainerID; fLot: TSQLLotID; fUom: TSQLUomID; fBinNumber: Integer; fLocationSeq: Integer; fComments: RawUTF8; fQuantityOnHandTotal: Double; fAvailableToPromiseTotal: Double; fAccountingQuantityTotal: Double; fOldQuantityOnHand: Double; fOldAvailableToPromise: Double; fSerialNumber: RawUTF8; fSoftIdentifier: RawUTF8; fActivationNumber: RawUTF8; fActivationValidThru: TDateTime; fUnitCost: Currency; fCurrencyUom: TSQLUomID; fFixedAsset: TSQLFixedAssetID; published property InventoryItemType: TSQLInventoryItemTypeID read fInventoryItemType write fInventoryItemType; property Product: TSQLProductID read fProduct write fProduct; property Party: TSQLPartyID read fParty write fParty; property OwnerParty: TSQLPartyID read fOwnerParty write fOwnerParty; property Status: TSQLStatusItemID read fStatus write fStatus; property DatetimeReceived: TDateTime read fDatetimeReceived write fDatetimeReceived; property DatetimeManufactured: TDateTime read fDatetimeManufactured write fDatetimeManufactured; property ExpireDate: TDateTime read fExpireDate write fExpireDate; property Facility: TSQLFacilityID read fFacility write fFacility; property Container: TSQLContainerID read fContainer write fContainer; property Lot: TSQLLotID read fLot write fLot; property Uom: TSQLUomID read fUom write fUom; property BinNumber: Integer read fBinNumber write fBinNumber; property LocationSeq: Integer read fLocationSeq write fLocationSeq; property Comments: RawUTF8 read fComments write fComments; property QuantityOnHandTotal: Double read fQuantityOnHandTotal write fQuantityOnHandTotal; property AvailableToPromiseTotal: Double read fAvailableToPromiseTotal write fAvailableToPromiseTotal; property AccountingQuantityTotal: Double read fAccountingQuantityTotal write fAccountingQuantityTotal; property OldQuantityOnHand: Double read fOldQuantityOnHand write fOldQuantityOnHand; property OldAvailableToPromise: Double read fOldAvailableToPromise write fOldAvailableToPromise; property SerialNumber: RawUTF8 read fSerialNumber write fSerialNumber; property SoftIdentifier: RawUTF8 read fSoftIdentifier write fSoftIdentifier; property ActivationNumber: RawUTF8 read fActivationNumber write fActivationNumber; property ActivationValidThru: TDateTime read fActivationValidThru write fActivationValidThru; property UnitCost: Currency read fUnitCost write fUnitCost; property CurrencyUom: TSQLUomID read fCurrencyUom write fCurrencyUom; property FixedAsset: TSQLFixedAssetID read fFixedAsset write fFixedAsset; end; // 71 TSQLInventoryItemAttribute = class(TSQLRecord) private fInventoryItem: TSQLInventoryItemID; fAttrName: TSQLInventoryItemTypeAttrID; fAttrValue: RawUTF8; fAttrDescription: RawUTF8; published property InventoryItem: TSQLInventoryItemID read fInventoryItem write fInventoryItem; property AttrName: TSQLInventoryItemTypeAttrID read fAttrName write fAttrName; property AttrValue: RawUTF8 read fAttrValue write fAttrValue; property AttrDescription: RawUTF8 read fAttrDescription write fAttrDescription; end; // 72 TSQLInventoryItemDetail = class(TSQLRecord) private fInventoryItem: TSQLInventoryItemID; fInventoryItemDetailSeq: Integer; fEffectiveDate: TDateTime; fQuantityOnHandDiff: Double; fAvailableToPromiseDiff: Double; fAccountingQuantityDiff: Double; fUnitCost: Double; fOrderId: Integer; //? fOrderItemSeq: Integer; fShipGroupSeq: Integer; fShipment: Integer; fShipmentItemSeq: Integer; fReturn: Integer; fReturnItemSeq: Integer; fWorkEffort: TSQLWorkEffortID; fFixedAsset: Integer; fMaintHistSeq: Integer; fItemIssuance: Integer; fReceipt: TSQLShipmentReceiptID; fPhysicalInventory: TSQLPhysicalInventoryID; fReasonEnum: TSQLEnumerationID; fDescription: RawUTF8; published property InventoryItem: TSQLInventoryItemID read fInventoryItem write fInventoryItem; property InventoryItemDetailSeq: Integer read fInventoryItemDetailSeq write fInventoryItemDetailSeq; property EffectiveDate: TDateTime read fEffectiveDate write fEffectiveDate; property QuantityOnHandDiff: Double read fQuantityOnHandDiff write fQuantityOnHandDiff; property AvailableToPromiseDiff: Double read fAvailableToPromiseDiff write fAvailableToPromiseDiff; property AccountingQuantityDiff: Double read fAccountingQuantityDiff write fAccountingQuantityDiff; property UnitCost: Double read fUnitCost write fUnitCost; property OrderId: Integer read fOrderId write fOrderId; property OrderItemSeq: Integer read fOrderItemSeq write fOrderItemSeq; property ShipGroupSeq: Integer read fShipGroupSeq write fShipGroupSeq; property Shipment: Integer read fShipment write fShipment; property ShipmentItemSeq: Integer read fShipmentItemSeq write fShipmentItemSeq; property Return: Integer read fReturn write fReturn; property ReturnItemSeq: Integer read fReturnItemSeq write fReturnItemSeq; property WorkEffort: TSQLWorkEffortID read fWorkEffort write fWorkEffort; property FixedAsset: Integer read fFixedAsset write fFixedAsset; property MaintHistSeq: Integer read fMaintHistSeq write fMaintHistSeq; property ItemIssuance: Integer read fItemIssuance write fItemIssuance; property Receipt: TSQLShipmentReceiptID read fReceipt write fReceipt; property PhysicalInventory: TSQLPhysicalInventoryID read fPhysicalInventory write fPhysicalInventory; property ReasonEnum: TSQLEnumerationID read fReasonEnum write fReasonEnum; property Description: RawUTF8 read fDescription write fDescription; end; // 73 TSQLInventoryItemStatus = class(TSQLRecord) private fInventoryItem: TSQLInventoryItemID; fStatus: TSQLStatusItemID; fStatusDatetime: TDateTime; fStatusEndDatetime: TDateTime; fChangeByUserLoginId: TSQLUserLoginID; fOwnerParty: Integer; //? fProduct: Integer; published property InventoryItem: TSQLInventoryItemID read fInventoryItem write fInventoryItem; property Status: TSQLStatusItemID read fStatus write fStatus; property StatusDatetime: TDateTime read fStatusDatetime write fStatusDatetime; property StatusEndDatetime: TDateTime read fStatusEndDatetime write fStatusEndDatetime; property ChangeByUserLoginId: TSQLUserLoginID read fChangeByUserLoginId write fChangeByUserLoginId; property OwnerParty: Integer read fOwnerParty write fOwnerParty; property Product: Integer read fProduct write fProduct; end; // 74 TSQLInventoryItemTempRes = class(TSQLRecord) private fVisit: Integer; fProduct: TSQLProductID; fProductStore: TSQLProductStoreID; fQuantity: Double; fReservedDate: TDateTime; published property Visit: Integer read fVisit write fVisit; property Product: TSQLProductID read fProduct write fProduct; property ProductStore: TSQLProductStoreID read fProductStore write fProductStore; property Quantity: Double read fQuantity write fQuantity; property ReservedDate: TDateTime read fReservedDate write fReservedDate; end; // 75 TSQLInventoryItemType = class(TSQLRecord) private fEncode: RawUTF8; fParentEncode: RawUTF8; fParent: TSQLInventoryItemTypeID; fHasTable: Boolean; fName: RawUTF8; FDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property ParentEncode: RawUTF8 read fParentEncode write fParentEncode; property Parent: TSQLInventoryItemTypeID read fParent write fParent; property HasTable: Boolean read fHasTable write fHasTable; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 76 TSQLInventoryItemTypeAttr = class(TSQLRecord) private fInventoryItemType: TSQLInventoryItemTypeID; fAttrName: TSQLInventoryItemAttributeID; fDescription: RawUTF8; published property InventoryItemType: TSQLInventoryItemTypeID read fInventoryItemType write fInventoryItemType; property AttrName: TSQLInventoryItemAttributeID read fAttrName write fAttrName; property Description: RawUTF8 read fDescription write fDescription; end; // 77 TSQLInventoryItemVariance = class(TSQLRecord) private fInventoryItem: TSQLInventoryItemID; fPhysicalInventory: TSQLPhysicalInventoryID; fVarianceReason: TSQLVarianceReasonID; fAvailableToPromiseVar: Double; fQuantityOnHandVar: Double; fComments: RawUTF8; published property InventoryItem: TSQLInventoryItemID read fInventoryItem write fInventoryItem; property PhysicalInventory: TSQLPhysicalInventoryID read fPhysicalInventory write fPhysicalInventory; property VarianceReason: TSQLVarianceReasonID read fVarianceReason write fVarianceReason; property AvailableToPromiseVar: Double read fAvailableToPromiseVar write fAvailableToPromiseVar; property QuantityOnHandVar: Double read fQuantityOnHandVar write fQuantityOnHandVar; property Comments: RawUTF8 read fComments write fComments; end; // 78 TSQLInventoryItemLabelType = class(TSQLRecord) private fParent: TSQLInventoryItemLabelTypeID; fHasTable: Boolean; fName: RawUTF8; FDescription: RawUTF8; published property Parent: TSQLInventoryItemLabelTypeID read fParent write fParent; property HasTable: Boolean read fHasTable write fHasTable; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 79 TSQLInventoryItemLabel = class(TSQLRecord) private fInventoryItemLabelType: TSQLInventoryItemLabelTypeID; FDescription: RawUTF8; published property InventoryItemLabelType: TSQLInventoryItemLabelTypeID read fInventoryItemLabelType write fInventoryItemLabelType; property Description: RawUTF8 read FDescription write FDescription; end; // 80 TSQLInventoryItemLabelAppl = class(TSQLRecord) private fInventoryItem: TSQLInventoryItemID; fInventoryItemLabelType: TSQLInventoryItemLabelTypeID; fInventoryItemLabel: TSQLInventoryItemLabelID; fSequenceNum: Integer; published property InventoryItem: TSQLInventoryItemID read fInventoryItem write fInventoryItem; property InventoryItemLabelType: TSQLInventoryItemLabelTypeID read fInventoryItemLabelType write fInventoryItemLabelType; property InventoryItemLabel: TSQLInventoryItemLabelID read fInventoryItemLabel write fInventoryItemLabel; property SequenceNum: Integer read fSequenceNum write fSequenceNum; end; // 81 TSQLInventoryTransfer = class(TSQLRecord) private fStatus: TSQLStatusItemID; fInventoryItem: TSQLInventoryItemID; fFacility: TSQLFacilityID; flocationSeq: Integer; fContainer: TSQLContainerID; fFacilityTo: TSQLFacilityID; fLocationSeqTo: Integer; fContainerTo: TSQLContainerID; fItemIssuance: TSQLItemIssuanceID; fSendDate: TDateTime; fReceiveDate: TDateTime; fComments: RawUTF8; published property Status: TSQLStatusItemID read fStatus write fStatus; property InventoryItem: TSQLInventoryItemID read fInventoryItem write fInventoryItem; property Facility: TSQLFacilityID read fFacility write fFacility; property locationSeq: Integer read flocationSeq write flocationSeq; property Container: TSQLContainerID read fContainer write fContainer; property FacilityTo: TSQLFacilityID read fFacilityTo write fFacilityTo; property LocationSeqTo: Integer read fLocationSeqTo write fLocationSeqTo; property ContainerTo: TSQLContainerID read fContainerTo write fContainerTo; property ItemIssuance: TSQLItemIssuanceID read fItemIssuance write fItemIssuance; property SendDate: TDateTime read fSendDate write fSendDate; property ReceiveDate: TDateTime read fReceiveDate write fReceiveDate; property Comments: RawUTF8 read fComments write fComments; end; // 82 批 TSQLLot = class(TSQLRecord) private fCreationDate: TDateTime; fQuantity: Double; fExpirationDate: TDateTime; published property CreationDate: TDateTime read fCreationDate write fCreationDate; property Quantity: Double read fQuantity write fQuantity; property ExpirationDate: TDateTime read fExpirationDate write fExpirationDate; end; // 83 TSQLPhysicalInventory = class(TSQLRecord) private fPhysicalInventoryDate: TDateTime; fParty: TSQLPartyID; fGeneralComments: RawUTF8; published property PhysicalInventoryDate: TDateTime read fPhysicalInventoryDate write fPhysicalInventoryDate; property Party: TSQLPartyID read fParty write fParty; property GeneralComments: RawUTF8 read fGeneralComments write fGeneralComments; end; // 84 变化原因 TSQLVarianceReason = class(TSQLRecord) private fEncode: RawUTF8; fName: RawUTF8; fDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read fDescription write fDescription; end; // 85 产品支付方式类型 TSQLProductPaymentMethodType = class(TSQLRecord) private fProduct: TSQLProductID; fPaymentMethodType: TSQLPaymentMethodTypeID; fProductPricePurpose: TSQLProductPricePurposeID; fFromDate: TDateTime; fThruDate: TDateTime; fSequenceNum: Integer; published property Product: TSQLProductID read fProduct write fProduct; property PaymentMethodType: TSQLPaymentMethodTypeID read fPaymentMethodType write fPaymentMethodType; property ProductPricePurpose: TSQLProductPricePurposeID read fProductPricePurpose write fProductPricePurpose; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property SequenceNum: Integer read fSequenceNum write fSequenceNum; end; // 86 产品价格 TSQLProductPrice = class(TSQLRecord) private fProduct: TSQLProductID; fProductPriceType: TSQLProductPriceTypeID; fProductPricePurpose: TSQLProductPricePurposeID; fCurrencyUom: TSQLUomID; fProductStoreGroup: TSQLProductStoreGroupID; fFromDate: TDateTime; fThruDate: TDateTime; fPrice: Currency; fTermUom: TSQLUomID; fCustomPriceCalcService: TSQLCustomMethodID; fPriceWithoutTax: Currency; fPriceWithTax: Currency; fTaxAmount: Currency; fTaxPercentage: Double; fTaxAuthParty: TSQLPartyID; fTaxAuthGeo: TSQLGeoID; fTaxInPrice: Boolean; fCreatedDate: TDateTime; fCreatedByUserLogin: TSQLUserLoginID; fLastModifiedDate: TDateTime; fLastModifiedByUserLogin: TSQLUserLoginID; published property Product: TSQLProductID read fProduct write fProduct; property ProductPriceType: TSQLProductPriceTypeID read fProductPriceType write fProductPriceType; property ProductPricePurpose: TSQLProductPricePurposeID read fProductPricePurpose write fProductPricePurpose; property CurrencyUom: TSQLUomID read fCurrencyUom write fCurrencyUom; property ProductStoreGroup: TSQLProductStoreGroupID read fProductStoreGroup write fProductStoreGroup; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property Price: Currency read fPrice write fPrice; property TermUom: TSQLUomID read fTermUom write fTermUom; property CustomPriceCalcService: TSQLCustomMethodID read fCustomPriceCalcService write fCustomPriceCalcService; property PriceWithoutTax: Currency read fPriceWithoutTax write fPriceWithoutTax; property PriceWithTax: Currency read fPriceWithTax write fPriceWithTax; property TaxAmount: Currency read fTaxAmount write fTaxAmount; property TaxPercentage: Double read fTaxPercentage write fTaxPercentage; property TaxAuthParty: TSQLPartyID read fTaxAuthParty write fTaxAuthParty; property TaxAuthGeo: TSQLGeoID read fTaxAuthGeo write fTaxAuthGeo; property TaxInPrice: Boolean read fTaxInPrice write fTaxInPrice; property CreatedDate: TDateTime read fCreatedDate write fCreatedDate; property CreatedByUserLogin: TSQLUserLoginID read fCreatedByUserLogin write fCreatedByUserLogin; property LastModifiedDate: TDateTime read fLastModifiedDate write fLastModifiedDate; property LastModifiedByUserLogin: TSQLUserLoginID read fLastModifiedByUserLogin write fLastModifiedByUserLogin; end; // 87 TSQLProductPriceAction = class(TSQLRecord) private fProductPriceRule: TSQLProductPriceRuleID; fProductPriceActionSeq: Integer; fProductPriceActionType: TSQLProductPriceActionTypeID; fAmount: Double; fRateCode: RawUTF8; published property ProductPriceRule: TSQLProductPriceRuleID read fProductPriceRule write fProductPriceRule; property ProductPriceActionSeq: Integer read fProductPriceActionSeq write fProductPriceActionSeq; property ProductPriceActionType: TSQLProductPriceActionTypeID read fProductPriceActionType write fProductPriceActionType; property Amount: Double read fAmount write fAmount; property RateCode: RawUTF8 read fRateCode write fRateCode; end; // 88 TSQLProductPriceActionType = class(TSQLRecord) private fEncode: RawUTF8; fName: RawUTF8; FDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 89 TSQLProductPriceAutoNotice = class(TSQLRecord) private fFacility: TSQLFacilityID; fRunDate: TDateTime; fFromDate: TDateTime; fThruDate: TDateTime; published property Facility: TSQLFacilityID read fFacility write fFacility; property RunDate: TDateTime read fRunDate write fRunDate; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; end; // 90 TSQLProductPriceChange = class(TSQLRecord) private fProduct: Integer; fProductPriceType: Integer; fProductPricePurpose: Integer; fCurrencyUom: Integer; fProductStoreGroup: Integer; fFromDate: TDateTime; fThruDate: TDateTime; fPrice: Currency; fOldPrice: Currency; fChangedDate: TDateTime; fChangedByUserLogin: TSQLUserLoginID; published property Product: Integer read fProduct write fProduct; property ProductPriceType: Integer read fProductPriceType write fProductPriceType; property ProductPricePurpose: Integer read fProductPricePurpose write fProductPricePurpose; property CurrencyUom: Integer read fCurrencyUom write fCurrencyUom; property ProductStoreGroup: Integer read fProductStoreGroup write fProductStoreGroup; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property Price: Currency read fPrice write fPrice; property OldPrice: Currency read fOldPrice write fOldPrice; property ChangedDate: TDateTime read fChangedDate write fChangedDate; property ChangedByUserLogin: TSQLUserLoginID read fChangedByUserLogin write fChangedByUserLogin; end; // 91 TSQLProductPriceCond = class(TSQLRecord) private fProductPriceRule: TSQLProductPriceRuleID; fProductPriceCondSeq: Integer; fInputParamEnum: TSQLEnumerationID; fOperatorEnum: TSQLEnumerationID; fCondValue: RawUTF8; published property ProductPriceRule: TSQLProductPriceRuleID read fProductPriceRule write fProductPriceRule; property ProductPriceCondSeq: Integer read fProductPriceCondSeq write fProductPriceCondSeq; property InputParamEnum: TSQLEnumerationID read fInputParamEnum write fInputParamEnum; property OperatorEnum: TSQLEnumerationID read fOperatorEnum write fOperatorEnum; property CondValue: RawUTF8 read fCondValue write fCondValue; end; // 92 TSQLProductPricePurpose = class(TSQLRecord) private fEncode: RawUTF8; fName: RawUTF8; FDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 93 TSQLProductPriceRule = class(TSQLRecord) private fRuleName: RawUTF8; FDescription: RawUTF8; fIsSale: Boolean; fFromDate: TDateTime; fThruDate: TDateTime; published property RuleName: RawUTF8 read fRuleName write fRuleName; property Description: RawUTF8 read FDescription write FDescription; property IsSale: Boolean read fIsSale write fIsSale; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; end; // 94 TSQLProductPriceType = class(TSQLRecord) private fEncode: RawUTF8; fName: RawUTF8; FDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 95 TSQLQuantityBreak = class(TSQLRecord) private fQuantityBreakType: TSQLQuantityBreakTypeID; fFromQuantity: Double; fFhruQuantity: Double; published property QuantityBreakType: TSQLQuantityBreakTypeID read fQuantityBreakType write fQuantityBreakType; property FromQuantity: Double read fFromQuantity write fFromQuantity; property FhruQuantity: Double read fFhruQuantity write fFhruQuantity; end; // 96 TSQLQuantityBreakType = class(TSQLRecord) private fEncode: RawUTF8; fName: RawUTF8; FDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 97 TSQLSaleType = class(TSQLRecord) private fName: RawUTF8; FDescription: RawUTF8; published property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 98 TSQLGoodIdentification = class(TSQLRecord) private fGoodIdentificationType: TSQLGoodIdentificationTypeID; fProduct: TSQLProductID; fIdValue: RawUTF8; published property GoodIdentificationType: TSQLGoodIdentificationTypeID read fGoodIdentificationType write fGoodIdentificationType; property Product: TSQLProductID read fProduct write fProduct; property IdValue: RawUTF8 read fIdValue write fIdValue; end; // 99 商品标识类型 TSQLGoodIdentificationType = class(TSQLRecord) private fEncode: RawUTF8; fParentEncode: RawUTF8; fParent: TSQLGoodIdentificationTypeID; fHasTable: Boolean; fName: RawUTF8; FDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property ParentEncode: RawUTF8 read fParentEncode write fParentEncode; property Parent: TSQLGoodIdentificationTypeID read fParent write fParent; property HasTable: Boolean read fHasTable write fHasTable; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 100 TSQLProduct = class(TSQLRecord) private fProductType: TSQLProductTypeID; fPrimaryProductCategory: TSQLProductCategoryID; fFacility: TSQLFacilityID; fIntroductionDate: TDateTime; fReleaseDate: TDateTime; fSupportDiscontinuationDate: TDateTime; fSalesDiscontinuationDate: TDateTime; //当缺货时销售终止 fSalesDiscWhenNotAvail: Boolean; fInternalName: RawUTF8; fBrandName: RawUTF8; fComments: RawUTF8; fProductName: RawUTF8; fDescription: RawUTF8; fLongDescription: TSQLRawBlob; fPriceDetailText: RawUTF8; fSmallImageUrl: RawUTF8; fMediumImageUrl: RawUTF8; fLargeImageUrl: RawUTF8; fDetailImageUrl: RawUTF8; fOriginalImageUrl: RawUTF8; fDetailScreen: TSQLRawBlob; fInventoryMessage: RawUTF8; fInventoryItemType: TSQLInventoryItemTypeID; //要求库存 fRequireInventory: Boolean; fQuantityUom: TSQLUomID; //包含的数量 fQuantityIncluded: Double; fPiecesIncluded: Double; //要求金额 fRequireAmount: Boolean; //固定面额 fFixedAmount: Currency; fAmountUomType: TSQLUomTypeID; fWeightUom: TSQLUomID; fShippingWeight: Double; fProductWeight: Double; fHeightUom: TSQLUomID; fProductHeight: Double; fShippingHeight: Double; fWidthUom: TSQLUomID; fProductWidth: Double; fShippingWidth: Double; fDepthUom: TSQLUomID; fProductDepth: Double; fShippingDepth: Double; fDiameterUom: TSQLUomID; fProductDiameter: Double; //产品等级 fProductRating: Double; fRatingTypeEnum: TSQLEnumerationID; //是否可退货 fReturnable: Boolean; //计税 fTaxable: Boolean; //收费发货 fChargeShipping: Boolean; //自动创建关键字 fAutoCreateKeywords: Boolean; //包含在促销中 fIncludeInPromotions: Boolean; //是虚拟产品 fIsVirtual: Boolean; //是变形产品 fIsVariant: Boolean; ///虚拟变形方法 fVirtualVariantMethodEnum: TSQLEnumerationID; fOriginGeo: TSQLGeoID; //需求方式枚举 fRequirementMethodEnum: TSQLEnumerationID; //物料清单级别 fBillOfMaterialLevel: Double; //用于租赁的最大人数 fReservMaxPersons: Double; //添加第二个人员。价格百分数 fReserv2ndPPPerc: Double; //添加第N个人员。价格百分数 fReservNthPPPerc: Double; //配置标识 fConfig: Integer; fCreatedDate: TDateTime; fCreatedByUserLogin: TSQLUserLoginID; fLastModifiedDate: TDateTime; {fLastModifiedByUserLogin: TSQLUserLoginID; fInShippingBox: Boolean; fDefaultShipmentBoxType: TSQLShipmentBoxTypeID; fLotIdFilledIn: TSQLRawBlob; fOrderDecimalQuantity: Boolean;} published property ProductType: TSQLProductTypeID read fProductType write fProductType; property PrimaryProductCategory: TSQLProductCategoryID read fPrimaryProductCategory write fPrimaryProductCategory; property Facility: TSQLFacilityID read fFacility write fFacility; property IntroductionDate: TDateTime read fIntroductionDate write fIntroductionDate; property ReleaseDate: TDateTime read fReleaseDate write fReleaseDate; property SupportDiscontinuationDate: TDateTime read fSupportDiscontinuationDate write fSupportDiscontinuationDate; property SalesDiscontinuationDate: TDateTime read fSalesDiscontinuationDate write fSalesDiscontinuationDate; property SalesDiscWhenNotAvail: Boolean read fSalesDiscWhenNotAvail write fSalesDiscWhenNotAvail; property InternalName: RawUTF8 read fInternalName write fInternalName; property BrandName: RawUTF8 read fBrandName write fBrandName; property Comments: RawUTF8 read fComments write fComments; property ProductName: RawUTF8 read fProductName write fProductName; property Description: RawUTF8 read fDescription write fDescription; property LongDescription: TSQLRawBlob read fLongDescription write fLongDescription; property PriceDetailText: RawUTF8 read fPriceDetailText write fPriceDetailText; property SmallImageUrl: RawUTF8 read fSmallImageUrl write fSmallImageUrl; property MediumImageUrl: RawUTF8 read fMediumImageUrl write fMediumImageUrl; property LargeImageUrl: RawUTF8 read fLargeImageUrl write fLargeImageUrl; property DetailImageUrl: RawUTF8 read fDetailImageUrl write fDetailImageUrl; property OriginalImageUrl: RawUTF8 read fOriginalImageUrl write fOriginalImageUrl; property DetailScreen: TSQLRawBlob read fDetailScreen write fDetailScreen; property InventoryMessage: RawUTF8 read fInventoryMessage write fInventoryMessage; property InventoryItemType: TSQLInventoryItemTypeID read fInventoryItemType write fInventoryItemType; property RequireInventory: Boolean read fRequireInventory write fRequireInventory; property QuantityUom: TSQLUomID read fQuantityUom write fQuantityUom; property QuantityIncluded: Double read fQuantityIncluded write fQuantityIncluded; property PiecesIncluded: Double read fPiecesIncluded write fPiecesIncluded; property RequireAmount: Boolean read fRequireAmount write fRequireAmount; property FixedAmount: Currency read fFixedAmount write fFixedAmount; property AmountUomType: TSQLUomTypeID read fAmountUomType write fAmountUomType; property WeightUom: TSQLUomID read fWeightUom write fWeightUom; property ShippingWeight: Double read fShippingWeight write fShippingWeight; property ProductWeight: Double read fProductWeight write fProductWeight; property HeightUom: TSQLUomID read fHeightUom write fHeightUom; property ProductHeight: Double read fProductHeight write fProductHeight; property ShippingHeight: Double read fShippingHeight write fShippingHeight; property WidthUom: TSQLUomID read fWidthUom write fWidthUom; property ProductWidth: Double read fProductWidth write fProductWidth; property ShippingWidth: Double read fShippingWidth write fShippingWidth; property DepthUom: TSQLUomID read fDepthUom write fDepthUom; property ProductDepth: Double read fProductDepth write fProductDepth; property ShippingDepth: Double read fShippingDepth write fShippingDepth; property DiameterUom: TSQLUomID read fDiameterUom write fDiameterUom; property ProductDiameter: Double read fProductDiameter write fProductDiameter; property ProductRating: Double read fProductRating write fProductRating; property RatingTypeEnum: TSQLEnumerationID read fRatingTypeEnum write fRatingTypeEnum; property Returnable: Boolean read fReturnable write fReturnable; property Taxable: Boolean read fTaxable write fTaxable; property ChargeShipping: Boolean read fChargeShipping write fChargeShipping; property AutoCreateKeywords: Boolean read fAutoCreateKeywords write fAutoCreateKeywords; property IncludeInPromotions: Boolean read fIncludeInPromotions write fIncludeInPromotions; property IsVirtual: Boolean read fIsVirtual write fIsVirtual; property IsVariant: Boolean read fIsVariant write fIsVariant; property VirtualVariantMethodEnum: TSQLEnumerationID read fVirtualVariantMethodEnum write fVirtualVariantMethodEnum; property OriginGeo: TSQLGeoID read fOriginGeo write fOriginGeo; property RequirementMethodEnum: TSQLEnumerationID read fRequirementMethodEnum write fRequirementMethodEnum; property BillOfMaterialLevel: Double read fBillOfMaterialLevel write fBillOfMaterialLevel; property ReservMaxPersons: Double read fReservMaxPersons write fReservMaxPersons; property Reserv2ndPPPerc: Double read fReserv2ndPPPerc write fReserv2ndPPPerc; property ReservNthPPPerc: Double read fReservNthPPPerc write fReservNthPPPerc; property Config: Integer read fConfig write fConfig; property CreatedDate: TDateTime read fCreatedDate write fCreatedDate; property CreatedByUserLogin: TSQLUserLoginID read fCreatedByUserLogin write fCreatedByUserLogin; property LastModifiedDate: TDateTime read fLastModifiedDate write fLastModifiedDate; {property LastModifiedByUserLogin: TSQLUserLoginID read fLastModifiedByUserLogin write fLastModifiedByUserLogin; property InShippingBox: Boolean read fInShippingBox write fInShippingBox; property DefaultShipmentBoxType: TSQLShipmentBoxTypeID read fDefaultShipmentBoxType write fDefaultShipmentBoxType; property LotIdFilledIn: TSQLRawBlob read fLotIdFilledIn write fLotIdFilledIn; property OrderDecimalQuantity: Boolean read fOrderDecimalQuantity write fOrderDecimalQuantity;} end; // 101 产品关联 TSQLProductAssoc = class(TSQLRecord) private fProduct: TSQLProductID; fProductTo: TSQLProductID; fProductAssocType: TSQLProductAssocTypeID; fFromDate: TDateTime; fThruDate: TDateTime; fSequenceNum: Integer; fReason: RawUTF8; fQuantity: Double; fScrapFactor: Double; fInstruction: RawUTF8; fRoutingWorkEffort: TSQLWorkEffortID; //预计计算方法 fEstimateCalcMethod: TSQLCustomMethodID; //循环信息 fRecurrenceInfo: TSQLRecurrenceInfoID; published property Product: TSQLProductID read fProduct write fProduct; property ProductTo: TSQLProductID read fProductTo write fProductTo; property ProductAssocType: TSQLProductAssocTypeID read fProductAssocType write fProductAssocType; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property SequenceNum: Integer read fSequenceNum write fSequenceNum; property Reason: RawUTF8 read fReason write fReason; property Quantity: Double read fQuantity write fQuantity; property ScrapFactor: Double read fScrapFactor write fScrapFactor; property Instruction: RawUTF8 read fInstruction write fInstruction; property RoutingWorkEffort: TSQLWorkEffortID read fRoutingWorkEffort write fRoutingWorkEffort; property EstimateCalcMethod: TSQLCustomMethodID read fEstimateCalcMethod write fEstimateCalcMethod; property RecurrenceInfo: TSQLRecurrenceInfoID read fRecurrenceInfo write fRecurrenceInfo; end; // 102 TSQLProductAssocType = class(TSQLRecord) private fEncode: RawUTF8; fParentEncode: RawUTF8; fParent: TSQLProductAssocTypeID; fHasTable: Boolean; fName: RawUTF8; FDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property ParentEncode: RawUTF8 read fParentEncode write fParentEncode; property Parent: TSQLProductAssocTypeID read fParent write fParent; property HasTable: Boolean read fHasTable write fHasTable; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 103 TSQLProductRole = class(TSQLRecord) private fProduct: TSQLProductID; fParty: TSQLPartyID; fRoleType: TSQLRoleTypeID; fFromDate: TDateTime; fThruDate: TDateTime; fSequenceNum: Integer; fComments: RawUTF8; published property Product: TSQLProductID read fProduct write fProduct; property Party: TSQLPartyID read fParty write fParty; property RoleType: TSQLRoleTypeID read fRoleType write fRoleType; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property SequenceNum: Integer read fSequenceNum write fSequenceNum; property Comments: RawUTF8 read fComments write fComments; end; // 104 TSQLProductAttribute = class(TSQLRecord) private fProduct: TSQLProductID; fAttrName: RawUTF8; fAttrValue: RawUTF8; fAttrType: RawUTF8; fAttrDescription: RawUTF8; published property Product: TSQLProductID read fProduct write fProduct; property AttrName: RawUTF8 read fAttrName write fAttrName; property AttrValue: RawUTF8 read fAttrValue write fAttrValue; property AttrType: RawUTF8 read fAttrType write fAttrType; property AttrDescription: RawUTF8 read fAttrDescription write fAttrDescription; end; // 105 产品统计信息 TSQLProductCalculatedInfo = class(TSQLRecord) private fProduct: TSQLProductID; fTotalQuantityOrdered: Double; fTotalTimesViewed: Integer; fAverageCustomerRating: Double; published property Product: TSQLProductID read fProduct write fProduct; property TotalQuantityOrdered: Double read fTotalQuantityOrdered write fTotalQuantityOrdered; property TotalTimesViewed: Integer read fTotalTimesViewed write fTotalTimesViewed; property AverageCustomerRating: Double read fAverageCustomerRating write fAverageCustomerRating; end; // 106 产品内容 TSQLProductContent = class(TSQLRecord) private fProduct: TSQLProductID; fContent: TSQLContentID; fProductContentType: TSQLProductContentTypeID; fFromDate: TDateTime; fThruDate: TDateTime; fPurchaseFromDate: TDateTime; fPurchaseThruDate: TDateTime; fUseCountLimit: Integer; fUseTime: Integer; fUseTimeUom: TSQLUomID; fUseRoleType: TSQLRoleTypeID; fSequenceNum: Integer; published property Product: TSQLProductID read fProduct write fProduct; property Content: TSQLContentID read fContent write fContent; property ProductContentType: TSQLProductContentTypeID read fProductContentType write fProductContentType; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property PurchaseFromDate: TDateTime read fPurchaseFromDate write fPurchaseFromDate; property PurchaseThruDate: TDateTime read fPurchaseThruDate write fPurchaseThruDate; property UseCountLimit: Integer read fUseCountLimit write fUseCountLimit; property UseTime: Integer read fUseTime write fUseTime; property UseTimeUom: TSQLUomID read fUseTimeUom write fUseTimeUom; property UseRoleType: TSQLRoleTypeID read fUseRoleType write fUseRoleType; property SequenceNum: Integer read fSequenceNum write fSequenceNum; end; // 107 TSQLProductContentType = class(TSQLRecord) private fEncode: RawUTF8; fParentEncode: RawUTF8; fParent: TSQLProductContentTypeID; fHasTable: Boolean; fName: RawUTF8; FDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property ParentEncode: RawUTF8 read fParentEncode write fParentEncode; property Parent: TSQLProductContentTypeID read fParent write fParent; property HasTable: Boolean read fHasTable write fHasTable; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 108 TSQLProductGeo = class(TSQLRecord) private fProduct: TSQLProductID; fGeo: TSQLGeoID; fProductGeoEnum: TSQLEnumerationID; fDescription: RawUTF8; published property Product: TSQLProductID read fProduct write fProduct; property Geo: TSQLGeoID read fGeo write fGeo; property ProductGeoEnum: TSQLEnumerationID read fProductGeoEnum write fProductGeoEnum; property Description: RawUTF8 read fDescription write fDescription; end; // 109 产品总账账户 TSQLProductGlAccount = class(TSQLRecord) private fProduct: TSQLProductID; fOrganizationParty: TSQLPartyID; fGlAccountType: TSQLGlAccountTypeID; fGlAccount: TSQLGlAccountID; published property Product: TSQLProductID read fProduct write fProduct; property OrganizationParty: TSQLPartyID read fOrganizationParty write fOrganizationParty; property GlAccountType: TSQLGlAccountTypeID read fGlAccountType write fGlAccountType; property GlAccount: TSQLGlAccountID read fGlAccount write fGlAccount; end; // 110 TSQLProductKeyword = class(TSQLRecord) private fProduct: TSQLProductID; fKeyword: RawUTF8; fKeywordType: TSQLEnumerationID; fRelevancyWeight: Double; fStatus: TSQLStatusItemID; published property Product: TSQLProductID read fProduct write fProduct; property Keyword: RawUTF8 read fKeyword write fKeyword; property KeywordType: TSQLEnumerationID read fKeywordType write fKeywordType; property RelevancyWeight: Double read fRelevancyWeight write fRelevancyWeight; property Status: TSQLStatusItemID read fStatus write fStatus; end; // 111 TSQLProductMeter = class(TSQLRecord) private fProduct: TSQLProductID; fProductMeterType: TSQLProductMeterTypeID; fMeterUom: TSQLUomID; fMeterName: RawUTF8; published property Product: TSQLProductID read fProduct write fProduct; property ProductMeterType: TSQLProductMeterTypeID read fProductMeterType write fProductMeterType; property MeterUom: TSQLUomID read fMeterUom write fMeterUom; property MeterName: RawUTF8 read fMeterName write fMeterName; end; // 112 TSQLProductMeterType = class(TSQLRecord) private fEncode: RawUTF8; fDefaultUom: TSQLUomID; fName: RawUTF8; fDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property DefaultUom: TSQLUomID read fDefaultUom write fDefaultUom; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read fDescription write fDescription; end; // 113 产品维护 TSQLProductMaint = class(TSQLRecord) private fProduct: TSQLProductID; fProductMaintSeq: RawUTF8; fProductMaintType: TSQLProductMaintTypeID; fMaintName: RawUTF8; //维护模板工作计划 fMaintTemplateWorkEffort: TSQLWorkEffortID; //间隔数量 fIntervalQuantity: Double; //间隔单位 fIntervalUom: TSQLUomID; //间隔仪表类型 fIntervalMeterType: TSQLProductMeterTypeID; //重复次数 fRepeatCount: Integer; published property Product: TSQLProductID read fProduct write fProduct; property ProductMaintSeq: RawUTF8 read fProductMaintSeq write fProductMaintSeq; property ProductMaintType: TSQLProductMaintTypeID read fProductMaintType write fProductMaintType; property MaintName: RawUTF8 read fMaintName write fMaintName; property MaintTemplateWorkEffort: TSQLWorkEffortID read fMaintTemplateWorkEffort write fMaintTemplateWorkEffort; property IntervalQuantity: Double read fIntervalQuantity write fIntervalQuantity; property IntervalUom: TSQLUomID read fIntervalUom write fIntervalUom; property IntervalMeterType: TSQLProductMeterTypeID read fIntervalMeterType write fIntervalMeterType; property RepeatCount: Integer read fRepeatCount write fRepeatCount; end; // 114 TSQLProductMaintType = class(TSQLRecord) private fEncode: RawUTF8; fParentEncode: RawUTF8; fParent: TSQLProductMaintTypeID; fHasTable: Boolean; fName: RawUTF8; FDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property ParentEncode: RawUTF8 read fParentEncode write fParentEncode; property Parent: TSQLProductMaintTypeID read fParent write fParent; property HasTable: Boolean read fHasTable write fHasTable; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 115 产品评论 TSQLProductReview = class(TSQLRecord) private fProductStore: TSQLProductStoreID; fProduct: TSQLProductID; fUserLogin: TSQLUserLoginID; fStatus: TSQLStatusItemID; fPostedAnonymous: Boolean; fPostedDateTime: TDateTime; fProductRating: Double; fProductReview: TSQLRawBlob; published property ProductStore: TSQLProductStoreID read fProductStore write fProductStore; property Product: TSQLProductID read fProduct write fProduct; property UserLogin: TSQLUserLoginID read fUserLogin write fUserLogin; property Status: TSQLStatusItemID read fStatus write fStatus; property PostedAnonymous: Boolean read fPostedAnonymous write fPostedAnonymous; property PostedDateTime: TDateTime read fPostedDateTime write fPostedDateTime; property ProductRating: Double read fProductRating write fProductRating; property ProductReview: TSQLRawBlob read fProductReview write fProductReview; end; // 116 TSQLProductSearchConstraint = class(TSQLRecord) private fProductSearchResult: TSQLProductSearchResultID; fConstraintSeq: RawUTF8; fConstraintName: RawUTF8; fInfoString: RawUTF8; //包括子分类 fIncludeSubCategories: Boolean; fIsAnd: Boolean; //任意前缀 fAnyPrefix: Boolean; //任意后缀 fAnySuffix: Boolean; //去词干 fRemoveStems: Boolean; fLowValue: RawUTF8; fHighValue: RawUTF8; published property ProductSearchResult: TSQLProductSearchResultID read fProductSearchResult write fProductSearchResult; property ConstraintSeq: RawUTF8 read fConstraintSeq write fConstraintSeq; property ConstraintName: RawUTF8 read fConstraintName write fConstraintName; property InfoString: RawUTF8 read fInfoString write fInfoString; property IncludeSubCategories: Boolean read fIncludeSubCategories write fIncludeSubCategories; property IsAnd: Boolean read fIsAnd write fIsAnd; property AnyPrefix: Boolean read fAnyPrefix write fAnyPrefix; property AnySuffix: Boolean read fAnySuffix write fAnySuffix; property RemoveStems: Boolean read fRemoveStems write fRemoveStems; property LowValue: RawUTF8 read fLowValue write fLowValue; property HighValue: RawUTF8 read fHighValue write fHighValue; end; // 117 TSQLProductSearchResult = class(TSQLRecord) private fVisit: Integer; fOrderByName: RawUTF8; fIsAscending: Boolean; fNumResults: Integer; fSecondsTotal: Double; fSearchDate: TDateTime; published property Visit: Integer read fVisit write fVisit; property OrderByName: RawUTF8 read fOrderByName write fOrderByName; property IsAscending: Boolean read fIsAscending write fIsAscending; property NumResults: Integer read fNumResults write fNumResults; property SecondsTotal: Double read fSecondsTotal write fSecondsTotal; property SearchDate: TDateTime read fSearchDate write fSearchDate; end; // 118 TSQLProductType = class(TSQLRecord) private fEncode: RawUTF8; fParentEncode: RawUTF8; fParent: TSQLProductTypeID; fIsPhysical: Boolean; fIsDigital: Boolean; fHasTable: Boolean; fName: RawUTF8; FDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property ParentEncode: RawUTF8 read fParentEncode write fParentEncode; property Parent: TSQLProductTypeID read fParent write fParent; property IsPhysical: Boolean read fIsPhysical write fIsPhysical; property IsDigital: Boolean read fIsDigital write fIsDigital; property HasTable: Boolean read fHasTable write fHasTable; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 119 TSQLProductTypeAttr = class(TSQLRecord) private fProductType: TSQLProductTypeID; fAttrName: RawUTF8; fDescription: RawUTF8; published property ProductType: TSQLProductTypeID read fProductType write fProductType; property AttrName: RawUTF8 read fAttrName write fAttrName; property Description: RawUTF8 read fDescription write fDescription; end; // 120 卖方产品 TSQLVendorProduct = class(TSQLRecord) private fProduct: TSQLProductID; fVendorParty: TSQLPartyID; fProductStoreGroup: TSQLProductStoreGroupID; published property Product: TSQLProductID read fProduct write fProduct; property VendorParty: TSQLPartyID read fVendorParty write fVendorParty; property ProductStoreGroup: TSQLProductStoreGroupID read fProductStoreGroup write fProductStoreGroup; end; // 121 TSQLProductPromo = class(TSQLRecord) private fPromoName: RawUTF8; fPromoText: RawUTF8; fUserEntered: Boolean; fShowToCustomer: Boolean; fRequireCode: Boolean; fUseLimitPerOrder: Double; fUseLimitPerCustomer: Double; fUseLimitPerPromotion: Double; fBillbackFactor: Double; fOverrideOrgParty: TSQLPartyID; fCreatedDate: TDateTime; fCreatedByUserLogin: TSQLUserLoginID; fLastModifiedDate: TDateTime; fLastModifiedByUserLogin: TSQLUserLoginID; published property PromoName: RawUTF8 read fPromoName write fPromoName; property PromoText: RawUTF8 read fPromoText write fPromoText; property UserEntered: Boolean read fUserEntered write fUserEntered; property ShowToCustomer: Boolean read fShowToCustomer write fShowToCustomer; property RequireCode: Boolean read fRequireCode write fRequireCode; property UseLimitPerOrder: Double read fUseLimitPerOrder write fUseLimitPerOrder; property UseLimitPerCustomer: Double read fUseLimitPerCustomer write fUseLimitPerCustomer; property UseLimitPerPromotion: Double read fUseLimitPerPromotion write fUseLimitPerPromotion; property BillbackFactor: Double read fBillbackFactor write fBillbackFactor; property OverrideOrgParty: TSQLPartyID read fOverrideOrgParty write fOverrideOrgParty; property CreatedDate: TDateTime read fCreatedDate write fCreatedDate; property CreatedByUserLogin: TSQLUserLoginID read fCreatedByUserLogin write fCreatedByUserLogin; property LastModifiedDate: TDateTime read fLastModifiedDate write fLastModifiedDate; property LastModifiedByUserLogin: TSQLUserLoginID read fLastModifiedByUserLogin write fLastModifiedByUserLogin; end; // 122 TSQLProductPromoAction = class(TSQLRecord) private fProductPromo: TSQLProductPromoID; fProductPromoRule: TSQLProductPromoRuleID; fProductPromoActionSeq: Integer; fProductPromoActionEnum: TSQLEnumerationID; fOrderAdjustmentType: TSQLOrderAdjustmentTypeID; fServiceName: RawUTF8; fQuantity: Double; fAmount: Double; fProduct: Integer; fParty: Integer; fUseCartQuantity: Boolean; published property ProductPromo: TSQLProductPromoID read fProductPromo write fProductPromo; property ProductPromoRule: TSQLProductPromoRuleID read fProductPromoRule write fProductPromoRule; property ProductPromoActionSeq: Integer read fProductPromoActionSeq write fProductPromoActionSeq; property ProductPromoActionEnum: TSQLEnumerationID read fProductPromoActionEnum write fProductPromoActionEnum; property OrderAdjustmentType: TSQLOrderAdjustmentTypeID read fOrderAdjustmentType write fOrderAdjustmentType; property ServiceName: RawUTF8 read fServiceName write fServiceName; property Quantity: Double read fQuantity write fQuantity; property Amount: Double read fAmount write fAmount; property Product: Integer read fProduct write fProduct; property Party: Integer read fParty write fParty; property UseCartQuantity: Boolean read fUseCartQuantity write fUseCartQuantity; end; // 123 TSQLProductPromoCategory = class(TSQLRecord) private fProductPromo: TSQLProductPromoID; fProductPromoRule: TSQLProductPromoRuleID; fProductPromoActionSeq: Integer; fproductPromoCondSeq: Integer; fProductCategory: TSQLProductCategoryID; fAndGroup: Integer; fProductPromoApplEnum: TSQLEnumerationID; fIncludeSubCategories: Boolean; published property ProductPromo: TSQLProductPromoID read fProductPromo write fProductPromo; property ProductPromoRule: TSQLProductPromoRuleID read fProductPromoRule write fProductPromoRule; property ProductPromoActionSeq: Integer read fProductPromoActionSeq write fProductPromoActionSeq; property productPromoCondSeq: Integer read fproductPromoCondSeq write fproductPromoCondSeq; property ProductCategory: TSQLProductCategoryID read fProductCategory write fProductCategory; property AndGroup: Integer read fAndGroup write fAndGroup; property ProductPromoApplEnum: TSQLEnumerationID read fProductPromoApplEnum write fProductPromoApplEnum; property IncludeSubCategories: Boolean read fIncludeSubCategories write fIncludeSubCategories; end; // 124 TSQLProductPromoCode = class(TSQLRecord) private fProductPromo: TSQLProductPromoID; fUserEntered: Boolean; fRequireEmailOrParty: Boolean; fUseLimitPerCode: Integer; fUseLimitPerCustomer: Integer; fFromDate: TDateTime; fThruDate: TDateTime; fCreatedDate: TDateTime; fCreatedByUserLogin: TSQLUserLoginID; fLastModifiedDate: TDateTime; fLastModifiedByUserLogin: TSQLUserLoginID; published property ProductPromo: TSQLProductPromoID read fProductPromo write fProductPromo; property UserEntered: Boolean read fUserEntered write fUserEntered; property RequireEmailOrParty: Boolean read fRequireEmailOrParty write fRequireEmailOrParty; property UseLimitPerCode: Integer read fUseLimitPerCode write fUseLimitPerCode; property UseLimitPerCustomer: Integer read fUseLimitPerCustomer write fUseLimitPerCustomer; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property CreatedDate: TDateTime read fCreatedDate write fCreatedDate; property CreatedByUserLogin: TSQLUserLoginID read fCreatedByUserLogin write fCreatedByUserLogin; property LastModifiedDate: TDateTime read fLastModifiedDate write fLastModifiedDate; property LastModifiedByUserLogin: TSQLUserLoginID read fLastModifiedByUserLogin write fLastModifiedByUserLogin; end; // 125 TSQLProductPromoCodeEmail = class(TSQLRecord) private fProductPromoCode: TSQLProductPromoCodeID; fEmailAddress: RawUTF8; published property ProductPromoCode: TSQLProductPromoCodeID read fProductPromoCode write fProductPromoCode; property EmailAddress: RawUTF8 read fEmailAddress write fEmailAddress; end; // 126 TSQLProductPromoCodeParty = class(TSQLRecord) private fProductPromoCode: TSQLProductPromoCodeID; fParty: TSQLPartyID; published property ProductPromoCode: TSQLProductPromoCodeID read fProductPromoCode write fProductPromoCode; property Party: TSQLPartyID read fParty write fParty; end; // 127 TSQLProductPromoCond = class(TSQLRecord) private fProductPromo: TSQLProductPromoID; fProductPromoRule: TSQLProductPromoRuleID; fProductPromoCondSeq: Integer; fInputParamEnum: TSQLEnumerationID; fOperatorEnum: TSQLEnumerationID; fCondValue: RawUTF8; fOtherValue: RawUTF8; published property ProductPromo: TSQLProductPromoID read fProductPromo write fProductPromo; property ProductPromoRule: TSQLProductPromoRuleID read fProductPromoRule write fProductPromoRule; property ProductPromoCondSeq: Integer read fProductPromoCondSeq write fProductPromoCondSeq; property InputParamEnum: TSQLEnumerationID read fInputParamEnum write fInputParamEnum; property OperatorEnum: TSQLEnumerationID read fOperatorEnum write fOperatorEnum; property CondValue: RawUTF8 read fCondValue write fCondValue; property OtherValue: RawUTF8 read fOtherValue write fOtherValue; end; // 128 TSQLProductPromoProduct = class(TSQLRecord) private fProductPromo: TSQLProductPromoID; fProductPromoRule: Integer; fProductPromoActionSeq: Integer; fProductPromoCondSeq: Integer; fProduct: TSQLProductID; fProductPromoApplEnum: TSQLEnumerationID; published property ProductPromo: TSQLProductPromoID read fProductPromo write fProductPromo; property ProductPromoRule: Integer read fProductPromoRule write fProductPromoRule; property ProductPromoActionSeq: Integer read fProductPromoActionSeq write fProductPromoActionSeq; property ProductPromoCondSeq: Integer read fProductPromoCondSeq write fProductPromoCondSeq; property Product: TSQLProductID read fProduct write fProduct; property ProductPromoApplEnum: TSQLEnumerationID read fProductPromoApplEnum write fProductPromoApplEnum; end; // 129 TSQLProductPromoRule = class(TSQLRecord) private fProductPromo: TSQLProductPromoID; fProductPromoRule: Integer; fRuleName: RawUTF8; published property ProductPromo: TSQLProductPromoID read fProductPromo write fProductPromo; property ProductPromoRule: Integer read fProductPromoRule write fProductPromoRule; property RuleName: RawUTF8 read fRuleName write fRuleName; end; // 130 TSQLProductPromoUse = class(TSQLRecord) private fOrderId: TSQLOrderHeaderID; fPromoSequence: Integer; fProductPromo: TSQLProductPromoID; fProductPromoCode: TSQLProductPromoCodeID; fParty: TSQLPartyID; fTotalDiscountAmount: Currency; fQuantityLeftInActions: Double; published property OrderId: TSQLOrderHeaderID read fOrderId write fOrderId; property PromoSequence: Integer read fPromoSequence write fPromoSequence; property ProductPromo: TSQLProductPromoID read fProductPromo write fProductPromo; property ProductPromoCode: TSQLProductPromoCodeID read fProductPromoCode write fProductPromoCode; property Party: TSQLPartyID read fParty write fParty; property TotalDiscountAmount: Currency read fTotalDiscountAmount write fTotalDiscountAmount; property QuantityLeftInActions: Double read fQuantityLeftInActions write fQuantityLeftInActions; end; // 131 TSQLProductStore = class(TSQLRecord) private fProductStoreGroup: TSQLProductStoreGroupID; fStoreName: RawUTF8; fCompanyName: RawUTF8; fTitle: RawUTF8; fSubtitle: RawUTF8; fPayToParty: TSQLPartyID; fDaysToCancelNonPay: Integer; fManualAuthIsCapture: Boolean; fProrateShipping: Boolean; fProrateTaxes: Boolean; fViewCartOnAdd: Boolean; fAutoSaveCart: Boolean; fAutoApproveReviews: Boolean; fIsDemoStore: Boolean; fIsImmediatelyFulfilled: Boolean; fInventoryFacility: TSQLFacilityID; fOneInventoryFacility: Boolean; fCheckInventory: Boolean; fReserveInventory: Boolean; fReserveOrderEnum: TSQLEnumerationID; fRequireInventory: Boolean; fBalanceResOnOrderCreation: Boolean; fRequirementMethodEnum: TSQLEnumerationID; fOrderNumberPrefix: RawUTF8; fDefaultLocaleString: RawUTF8; fDefaultCurrencyUomId: TSQLUomID; fDefaultTimeZoneString: RawUTF8; fDefaultSalesChannelEnum: TSQLEnumerationID; fAllowPassword: Boolean; fDefaultPassword: RawUTF8; fExplodeOrderItems: Boolean; fCheckGcBalance: Boolean; fRetryFailedAuths: Boolean; fHeaderApprovedStatus: TSQLStatusItemID; fItemApprovedStatus: TSQLStatusItemID; fDigitalItemApprovedStatus: TSQLStatusItemID; fHeaderDeclinedStatus: TSQLStatusItemID; fItemDeclinedStatus: TSQLStatusItemID; fHeaderCancelStatus: TSQLStatusItemID; fItemCancelStatus: TSQLStatusItemID; fAuthDeclinedMessage: RawUTF8; fAuthFraudMessage: RawUTF8; fAuthErrorMessage: RawUTF8; fVisualTheme: Integer; fStoreCreditAccountEnum: TSQLEnumerationID; fUsePrimaryEmailUsername: Boolean; fRequireCustomerRole: Boolean; fAutoInvoiceDigitalItems: Boolean; fReqShipAddrForDigItems: Boolean; fShowCheckoutGiftOptions: Boolean; fSelectPaymentTypePerItem: Boolean; fShowPricesWithVatTax: Boolean; fShowTaxIsExempt: Boolean; fVatTaxAuthGeo: Integer; fVatTaxAuthParty: Integer; fEnableAutoSuggestionList: Boolean; fEnableDigProdUpload: Boolean; fProdSearchExcludeVariants: Boolean; fDigProdUploadCategory: Integer; fAutoOrderCcTryExp: Boolean; fAutoOrderCcTryOtherCards: Boolean; fAutoOrderCcTryLaterNsf: Boolean; fAutoOrderCcTryLaterMax: Integer; fStoreCreditValidDays: Integer; {fAutoApproveInvoice: Boolean; fAutoApproveOrder: Boolean; fShipIfCaptureFails: RawUTF8; fSetOwnerUponIssuance: Boolean; fReqReturnInventoryReceive: Boolean; fAddToCartRemoveIncompat: Boolean; fAddToCartReplaceUpsell: Boolean; fSplitPayPrefPerShpGrp: Boolean; fManagedByLot: Boolean; fShowOutOfStockProducts: Boolean; fOrderDecimalQuantity: Boolean; fAllowComment: Boolean;} published property ProductStoreGroup: TSQLProductStoreGroupID read fProductStoreGroup write fProductStoreGroup; property StoreName: RawUTF8 read fStoreName write fStoreName; property CompanyName: RawUTF8 read fCompanyName write fCompanyName; property Title: RawUTF8 read fTitle write fTitle; property Subtitle: RawUTF8 read fSubtitle write fSubtitle; property PayToParty: TSQLPartyID read fPayToParty write fPayToParty; property DaysToCancelNonPay: Integer read fDaysToCancelNonPay write fDaysToCancelNonPay; property ManualAuthIsCapture: Boolean read fManualAuthIsCapture write fManualAuthIsCapture; property ProrateShipping: Boolean read fProrateShipping write fProrateShipping; property ProrateTaxes: Boolean read fProrateTaxes write fProrateTaxes; property ViewCartOnAdd: Boolean read fViewCartOnAdd write fViewCartOnAdd; property AutoSaveCart: Boolean read fAutoSaveCart write fAutoSaveCart; property AutoApproveReviews: Boolean read fAutoApproveReviews write fAutoApproveReviews; property IsDemoStore: Boolean read fIsDemoStore write fIsDemoStore; property IsImmediatelyFulfilled: Boolean read fIsImmediatelyFulfilled write fIsImmediatelyFulfilled; property InventoryFacility: TSQLFacilityID read fInventoryFacility write fInventoryFacility; property OneInventoryFacility: Boolean read fOneInventoryFacility write fOneInventoryFacility; property CheckInventory: Boolean read fCheckInventory write fCheckInventory; property ReserveInventory: Boolean read fReserveInventory write fReserveInventory; property ReserveOrderEnum: TSQLEnumerationID read fReserveOrderEnum write fReserveOrderEnum; property RequireInventory: Boolean read fRequireInventory write fRequireInventory; property BalanceResOnOrderCreation: Boolean read fBalanceResOnOrderCreation write fBalanceResOnOrderCreation; property RequirementMethodEnum: TSQLEnumerationID read fRequirementMethodEnum write fRequirementMethodEnum; property OrderNumberPrefix: RawUTF8 read fOrderNumberPrefix write fOrderNumberPrefix; property DefaultLocaleString: RawUTF8 read fDefaultLocaleString write fDefaultLocaleString; property DefaultCurrencyUomId: TSQLUomID read fDefaultCurrencyUomId write fDefaultCurrencyUomId; property DefaultTimeZoneString: RawUTF8 read fDefaultTimeZoneString write fDefaultTimeZoneString; property DefaultSalesChannelEnum: TSQLEnumerationID read fDefaultSalesChannelEnum write fDefaultSalesChannelEnum; property AllowPassword: Boolean read fAllowPassword write fAllowPassword; property DefaultPassword: RawUTF8 read fDefaultPassword write fDefaultPassword; property ExplodeOrderItems: Boolean read fExplodeOrderItems write fExplodeOrderItems; property CheckGcBalance: Boolean read fCheckGcBalance write fCheckGcBalance; property RetryFailedAuths: Boolean read fRetryFailedAuths write fRetryFailedAuths; property HeaderApprovedStatus: TSQLStatusItemID read fHeaderApprovedStatus write fHeaderApprovedStatus; property ItemApprovedStatus: TSQLStatusItemID read fItemApprovedStatus write fItemApprovedStatus; property DigitalItemApprovedStatus: TSQLStatusItemID read fDigitalItemApprovedStatus write fDigitalItemApprovedStatus; property HeaderDeclinedStatus: TSQLStatusItemID read fHeaderDeclinedStatus write fHeaderDeclinedStatus; property ItemDeclinedStatus: TSQLStatusItemID read fItemDeclinedStatus write fItemDeclinedStatus; property HeaderCancelStatus: TSQLStatusItemID read fHeaderCancelStatus write fHeaderCancelStatus; property ItemCancelStatus: TSQLStatusItemID read fItemCancelStatus write fItemCancelStatus; property AuthDeclinedMessage: RawUTF8 read fAuthDeclinedMessage write fAuthDeclinedMessage; property AuthFraudMessage: RawUTF8 read fAuthFraudMessage write fAuthFraudMessage; property AuthErrorMessage: RawUTF8 read fAuthErrorMessage write fAuthErrorMessage; property VisualTheme: Integer read fVisualTheme write fVisualTheme; property StoreCreditAccountEnum: TSQLEnumerationID read fStoreCreditAccountEnum write fStoreCreditAccountEnum; property UsePrimaryEmailUsername: Boolean read fUsePrimaryEmailUsername write fUsePrimaryEmailUsername; property RequireCustomerRole: Boolean read fRequireCustomerRole write fRequireCustomerRole; property AutoInvoiceDigitalItems: Boolean read fAutoInvoiceDigitalItems write fAutoInvoiceDigitalItems; property ReqShipAddrForDigItems: Boolean read fReqShipAddrForDigItems write fReqShipAddrForDigItems; property ShowCheckoutGiftOptions: Boolean read fShowCheckoutGiftOptions write fShowCheckoutGiftOptions; property SelectPaymentTypePerItem: Boolean read fSelectPaymentTypePerItem write fSelectPaymentTypePerItem; property ShowPricesWithVatTax: Boolean read fShowPricesWithVatTax write fShowPricesWithVatTax; property ShowTaxIsExempt: Boolean read fShowTaxIsExempt write fShowTaxIsExempt; property VatTaxAuthGeo: Integer read fVatTaxAuthGeo write fVatTaxAuthGeo; property VatTaxAuthParty: Integer read fVatTaxAuthParty write fVatTaxAuthParty; property EnableAutoSuggestionList: Boolean read fEnableAutoSuggestionList write fEnableAutoSuggestionList; property EnableDigProdUpload: Boolean read fEnableDigProdUpload write fEnableDigProdUpload; property ProdSearchExcludeVariants: Boolean read fProdSearchExcludeVariants write fProdSearchExcludeVariants; property DigProdUploadCategory: Integer read fDigProdUploadCategory write fDigProdUploadCategory; property AutoOrderCcTryExp: Boolean read fAutoOrderCcTryExp write fAutoOrderCcTryExp; property AutoOrderCcTryOtherCards: Boolean read fAutoOrderCcTryOtherCards write fAutoOrderCcTryOtherCards; property AutoOrderCcTryLaterNsf: Boolean read fAutoOrderCcTryLaterNsf write fAutoOrderCcTryLaterNsf; property AutoOrderCcTryLaterMax: Integer read fAutoOrderCcTryLaterMax write fAutoOrderCcTryLaterMax; property StoreCreditValidDays: Integer read fStoreCreditValidDays write fStoreCreditValidDays; {property AutoApproveInvoice: Boolean read fAutoApproveInvoice write fAutoApproveInvoice; property AutoApproveOrder: Boolean read fAutoApproveOrder write fAutoApproveOrder; property ShipIfCaptureFails: RawUTF8 read fShipIfCaptureFails write fShipIfCaptureFails; property SetOwnerUponIssuance: Boolean read fSetOwnerUponIssuance write fSetOwnerUponIssuance; property ReqReturnInventoryReceive: Boolean read fReqReturnInventoryReceive write fReqReturnInventoryReceive; property AddToCartRemoveIncompat: Boolean read fAddToCartRemoveIncompat write fAddToCartRemoveIncompat; property AddToCartReplaceUpsell: Boolean read fAddToCartReplaceUpsell write fAddToCartReplaceUpsell; property SplitPayPrefPerShpGrp: Boolean read fSplitPayPrefPerShpGrp write fSplitPayPrefPerShpGrp; property ManagedByLot: Boolean read fManagedByLot write fManagedByLot; property ShowOutOfStockProducts: Boolean read fShowOutOfStockProducts write fShowOutOfStockProducts; property OrderDecimalQuantity: Boolean read fOrderDecimalQuantity write fOrderDecimalQuantity; property AllowComment: Boolean read fAllowComment write fAllowComment;} end; // 132 TSQLProductStoreCatalog = class(TSQLRecord) private fProductStore: TSQLProductStoreID; fProdCatalog: TSQLProdCatalogID; fFromDate: TDateTime; fThruDate: TDateTime; fSequenceNum: Integer; published property ProductStore: TSQLProductStoreID read fProductStore write fProductStore; property ProdCatalog: TSQLProdCatalogID read fProdCatalog write fProdCatalog; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property SequenceNum: Integer read fSequenceNum write fSequenceNum; end; // 133 TSQLProductStoreEmailSetting = class(TSQLRecord) private fProductStore: TSQLProductStoreID; fEmailType: TSQLEnumerationID; fBodyScreenLocation: RawUTF8; fXslfoAttachScreenLocation: RawUTF8; fFromAddress: RawUTF8; fCcAddress: RawUTF8; fBccAddress: RawUTF8; fSubject: RawUTF8; fContentType: RawUTF8; published property ProductStore: TSQLProductStoreID read fProductStore write fProductStore; property EmailType: TSQLEnumerationID read fEmailType write fEmailType; property BodyScreenLocation: RawUTF8 read fBodyScreenLocation write fBodyScreenLocation; property XslfoAttachScreenLocation: RawUTF8 read fXslfoAttachScreenLocation write fXslfoAttachScreenLocation; property FromAddress: RawUTF8 read fFromAddress write fFromAddress; property CcAddress: RawUTF8 read fCcAddress write fCcAddress; property BccAddress: RawUTF8 read fBccAddress write fBccAddress; property Subject: RawUTF8 read fSubject write fSubject; property ContentType: RawUTF8 read fContentType write fContentType; end; // 134 商店金融账户设置 TSQLProductStoreFinActSetting = class(TSQLRecord) private fProductStore: TSQLProductStoreID; fFinAccountType: TSQLFinAccountTypeID; //要求个人识别号码 fRequirePinCode: Boolean; //决定是否基于存储在金融账户的的礼品论证码校验礼品卡号,设置为N则使用外部礼品卡提供者 fValidateGCFinAcct: Boolean; //自动生成的账号长度 fAccountCodeLength: Integer; //自动生成的个人识别号码长度 fPinCodeLength: Integer; //这类型账户的有效天数 fAccountValidDays: Integer; //这类型账户预授权的有效天数 fAuthValidDays: Integer; //这个调查通常用来收集信息,比如:购买者名称、收件人、电子邮件、消息等,非常灵活。 fPurchaseSurvey: TSQLSurveyID; //字段名称上的“发送到电子邮件地址的购买调查 fPurchSurveySendTo: RawUTF8; //采购调查是否抄送我 fPurchSurveyCopyMe: RawUTF8; //允许预授权到负值 fAllowAuthToNegative: Boolean; //最小余额 fMinBalance: Currency; //补充阈值 fReplenishThreshold: Currency; //补尝方法枚举 fReplenishMethodEnumId: TSQLEnumerationID; published property ProductStore: TSQLProductStoreID read fProductStore write fProductStore; property FinAccountType: TSQLFinAccountTypeID read fFinAccountType write fFinAccountType; property RequirePinCode: Boolean read fRequirePinCode write fRequirePinCode; property ValidateGCFinAcct: Boolean read fValidateGCFinAcct write fValidateGCFinAcct; property AccountCodeLength: Integer read fAccountCodeLength write fAccountCodeLength; property PinCodeLength: Integer read fPinCodeLength write fPinCodeLength; property AccountValidDays: Integer read fAccountValidDays write fAccountValidDays; property AuthValidDays: Integer read fAuthValidDays write fAuthValidDays; property PurchaseSurvey: TSQLSurveyID read fPurchaseSurvey write fPurchaseSurvey; property PurchSurveySendTo: RawUTF8 read fPurchSurveySendTo write fPurchSurveySendTo; property PurchSurveyCopyMe: RawUTF8 read fPurchSurveyCopyMe write fPurchSurveyCopyMe; property AllowAuthToNegative: Boolean read fAllowAuthToNegative write fAllowAuthToNegative; property MinBalance: Currency read fMinBalance write fMinBalance; property ReplenishThreshold: Currency read fReplenishThreshold write fReplenishThreshold; property ReplenishMethodEnumId: TSQLEnumerationID read fReplenishMethodEnumId write fReplenishMethodEnumId; end; // 135 产品商店设施 TSQLProductStoreFacility = class(TSQLRecord) private fProductStore: TSQLProductStoreID; fFacility: TSQLFacilityID; fFromDate: TDateTime; fThruDate: TDateTime; fSequenceNum: Integer; published property ProductStore: TSQLProductStoreID read fProductStore write fProductStore; property Facility: TSQLFacilityID read fFacility write fFacility; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property SequenceNum: Integer read fSequenceNum write fSequenceNum; end; // 136 产品商店分组 TSQLProductStoreGroup = class(TSQLRecord) private fEncode: RawUTF8; fGroupTypeEncode: RawUTF8; fPrimaryGroupEncode: RawUTF8; fProductStoreGroupType: TSQLProductStoreGroupTypeID; fPrimaryParentGroup: TSQLProductStoreGroupID; fName: RawUTF8; fDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property GroupTypeEncode: RawUTF8 read fGroupTypeEncode write fGroupTypeEncode; property PrimaryGroupEncode: RawUTF8 read fPrimaryGroupEncode write fPrimaryGroupEncode; property ProductStoreGroupType: TSQLProductStoreGroupTypeID read fProductStoreGroupType write fProductStoreGroupType; property PrimaryParentGroup: TSQLProductStoreGroupID read fPrimaryParentGroup write fPrimaryParentGroup; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read fDescription write fDescription; end; // 137 产品商店分组会员 TSQLProductStoreGroupMember = class(TSQLRecord) private fProductStore: TSQLProductStoreID; fProductStoreGroup: TSQLProductStoreGroupID; fFromDate: TDateTime; fThruDate: TDateTime; fSequenceNum: Integer; published property ProductStore: TSQLProductStoreID read fProductStore write fProductStore; property ProductStoreGroup: TSQLProductStoreGroupID read fProductStoreGroup write fProductStoreGroup; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property SequenceNum: Integer read fSequenceNum write fSequenceNum; end; // 138 产品商店分组角色 TSQLProductStoreGroupRole = class(TSQLRecord) private fProductStoreGroup: TSQLProductStoreGroupID; fParty: TSQLPartyID; fRoleType: TSQLRoleTypeID; published property ProductStoreGroup: TSQLProductStoreGroupID read fProductStoreGroup write fProductStoreGroup; property Party: TSQLPartyID read fParty write fParty; property RoleType: TSQLRoleTypeID read fRoleType write fRoleType; end; // 139 产品商店分组隶属关系 TSQLProductStoreGroupRollup = class(TSQLRecord) private fProductStoreGroup: TSQLProductStoreGroupID; fParentGroup: TSQLProductStoreGroupID; fFromDate: TDateTime; fThruDate: TDateTime; fSequenceNum: Integer; published property ProductStoreGroup: TSQLProductStoreGroupID read fProductStoreGroup write fProductStoreGroup; property ParentGroup: TSQLProductStoreGroupID read fParentGroup write fParentGroup; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property SequenceNum: Integer read fSequenceNum write fSequenceNum; end; // 140 TSQLProductStoreGroupType = class(TSQLRecord) private fName: RawUTF8; FDescription: RawUTF8; published property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 141 产品商店关键字覆盖 TSQLProductStoreKeywordOvrd = class(TSQLRecord) private fProductStore: TSQLProductStoreID; fKeyword: RawUTF8; fFromDate: TDateTime; fThruDate: TDateTime; fTarget: RawUTF8; fTargetTypeEnum: TSQLEnumerationID; published property ProductStore: TSQLProductStoreID read fProductStore write fProductStore; property Keyword: RawUTF8 read fKeyword write fKeyword; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property Target: RawUTF8 read fTarget write fTarget; property TargetTypeEnum: TSQLEnumerationID read fTargetTypeEnum write fTargetTypeEnum; end; // 142 产品商店支付设置 TSQLProductStorePaymentSetting = class(TSQLRecord) private fProductStore: TSQLProductStoreID; fPaymentMethodType: TSQLPaymentMethodTypeID; fPaymentServiceTypeEnum: TSQLEnumerationID; fPaymentService: RawUTF8; fPaymentCustomMethod: TSQLCustomMethodID; fPaymentGatewayConfig: TSQLPaymentGatewayConfigID; fPaymentPropertiesPath: RawUTF8; fApplyToAllProducts: Boolean; published property ProductStore: TSQLProductStoreID read fProductStore write fProductStore; property PaymentMethodType: TSQLPaymentMethodTypeID read fPaymentMethodType write fPaymentMethodType; property PaymentServiceTypeEnum: TSQLEnumerationID read fPaymentServiceTypeEnum write fPaymentServiceTypeEnum; property PaymentService: RawUTF8 read fPaymentService write fPaymentService; property PaymentCustomMethod: TSQLCustomMethodID read fPaymentCustomMethod write fPaymentCustomMethod; property PaymentGatewayConfig: TSQLPaymentGatewayConfigID read fPaymentGatewayConfig write fPaymentGatewayConfig; property PaymentPropertiesPath: RawUTF8 read fPaymentPropertiesPath write fPaymentPropertiesPath; property ApplyToAllProducts: Boolean read fApplyToAllProducts write fApplyToAllProducts; end; // 143 产品商店促销应用 TSQLProductStorePromoAppl = class(TSQLRecord) private fProductStore: TSQLProductStoreID; fProductPromo: TSQLProductPromoID; fFromDate: TDateTime; fThruDate: TDateTime; fSequenceNum: Integer; fManualOnly: Boolean; published property ProductStore: TSQLProductStoreID read fProductStore write fProductStore; property ProductPromo: TSQLProductPromoID read fProductPromo write fProductPromo; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property SequenceNum: Integer read fSequenceNum write fSequenceNum; property ManualOnly: Boolean read fManualOnly write fManualOnly; end; // 144 TSQLProductStoreRole = class(TSQLRecord) private fParty: TSQLPartyID; fRoleType: TSQLRoleTypeID; fProductStore: TSQLProductStoreID; fFromDate: TDateTime; fThruDate: TDateTime; fSequenceNum: Integer; published property Party: TSQLPartyID read fParty write fParty; property RoleType: TSQLRoleTypeID read fRoleType write fRoleType; property ProductStore: TSQLProductStoreID read fProductStore write fProductStore; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property SequenceNum: Integer read fSequenceNum write fSequenceNum; end; // 145 产品商店货运方式 TSQLProductStoreShipmentMeth = class(TSQLRecord) private fProductStore: TSQLProductStoreID; fShipmentMethodType: TSQLShipmentMethodTypeID; fParty: TSQLPartyID; fRoleType: TSQLRoleTypeID; fCompanyParty: TSQLPartyID; fMinWeight: Double; fMaxWeight: Double; fMinSize: Double; fMaxSize: Double; fMinTotal: Currency; fMaxTotal: Currency; fAllowUspsAddr: Boolean; fRequireUspsAddr: Boolean; fAllowCompanyAddr: Boolean; fRequireCompanyAddr: Boolean; //包括非计费项 fIncludeNoChargeItems: Boolean; //包含特征组 fIncludeFeatureGroup: Integer; fExcludeFeatureGroup: Integer; fIncludeGeo: TSQLGeoID; fExcludeGeo: TSQLGeoID; fServiceName: RawUTF8; fConfigProps: RawUTF8; fShipmentCustomMethod: TSQLCustomMethodID; fShipmentGatewayConfig: TSQLShipmentGatewayConfigID; fSequenceNumber: Integer; fAllowancePercent: Double; fMinimumPrice: Currency; published property ProductStore: TSQLProductStoreID read fProductStore write fProductStore; property ShipmentMethodType: TSQLShipmentMethodTypeID read fShipmentMethodType write fShipmentMethodType; property Party: TSQLPartyID read fParty write fParty; property RoleType: TSQLRoleTypeID read fRoleType write fRoleType; property CompanyParty: TSQLPartyID read fCompanyParty write fCompanyParty; property MinWeight: Double read fMinWeight write fMinWeight; property MaxWeight: Double read fMaxWeight write fMaxWeight; property MinSize: Double read fMinSize write fMinSize; property MaxSize: Double read fMaxSize write fMaxSize; property MinTotal: Currency read fMinTotal write fMinTotal; property MaxTotal: Currency read fMaxTotal write fMaxTotal; property AllowUspsAddr: Boolean read fAllowUspsAddr write fAllowUspsAddr; property RequireUspsAddr: Boolean read fRequireUspsAddr write fRequireUspsAddr; property AllowCompanyAddr: Boolean read fAllowCompanyAddr write fAllowCompanyAddr; property RequireCompanyAddr: Boolean read fRequireCompanyAddr write fRequireCompanyAddr; property IncludeNoChargeItems: Boolean read fIncludeNoChargeItems write fIncludeNoChargeItems; property IncludeFeatureGroup: Integer read fIncludeFeatureGroup write fIncludeFeatureGroup; property ExcludeFeatureGroup: Integer read fExcludeFeatureGroup write fExcludeFeatureGroup; property IncludeGeo: TSQLGeoID read fIncludeGeo write fIncludeGeo; property ExcludeGeo: TSQLGeoID read fExcludeGeo write fExcludeGeo; property ServiceName: RawUTF8 read fServiceName write fServiceName; property ConfigProps: RawUTF8 read fConfigProps write fConfigProps; property ShipmentCustomMethod: TSQLCustomMethodID read fShipmentCustomMethod write fShipmentCustomMethod; property ShipmentGatewayConfig: TSQLShipmentGatewayConfigID read fShipmentGatewayConfig write fShipmentGatewayConfig; property SequenceNumber: Integer read fSequenceNumber write fSequenceNumber; property AllowancePercent: Double read fAllowancePercent write fAllowancePercent; property MinimumPrice: Currency read fMinimumPrice write fMinimumPrice; end; // 146 产品商店调查应用 TSQLProductStoreSurveyAppl = class(TSQLRecord) private fProductStore: TSQLProductStoreID; fSurveyApplType: TSQLSurveyApplTypeID; fGroupName: RawUTF8; fSurvey: TSQLSurveyID; fProduct: TSQLProductID; fProductCategory: TSQLProductCategoryID; fFromDate: TDateTime; fThruDate: TDateTime; fSurveyTemplate: RawUTF8; fResultTemplate: RawUTF8; fSequenceNum: Integer; published property ProductStore: TSQLProductStoreID read fProductStore write fProductStore; property SurveyApplType: TSQLSurveyApplTypeID read fSurveyApplType write fSurveyApplType; property GroupName: RawUTF8 read fGroupName write fGroupName; property Survey: TSQLSurveyID read fSurvey write fSurvey; property Product: TSQLProductID read fProduct write fProduct; property ProductCategory: TSQLProductCategoryID read fProductCategory write fProductCategory; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property SurveyTemplate: RawUTF8 read fSurveyTemplate write fSurveyTemplate; property ResultTemplate: RawUTF8 read fResultTemplate write fResultTemplate; property SequenceNum: Integer read fSequenceNum write fSequenceNum; end; // 147 产品商店卖方支付 TSQLProductStoreVendorPayment = class(TSQLRecord) private fProductStore: TSQLProductStoreID; fVendorParty: TSQLPartyID; fPaymentMethodType: TSQLPaymentMethodTypeID; fCreditCardEnum: TSQLEnumerationID; published property ProductStore: TSQLProductStoreID read fProductStore write fProductStore; property VendorParty: TSQLPartyID read fVendorParty write fVendorParty; property PaymentMethodType: TSQLPaymentMethodTypeID read fPaymentMethodType write fPaymentMethodType; property CreditCardEnum: TSQLEnumerationID read fCreditCardEnum write fCreditCardEnum; end; // 148 产品商店卖方货运 TSQLProductStoreVendorShipment = class(TSQLRecord) private fProductStore: TSQLProductStoreID; fVendorParty: TSQLPartyID; fShipmentMethodType: TSQLShipmentMethodTypeID; fCarrierParty: TSQLPartyID; published property ProductStore: TSQLProductStoreID read fProductStore write fProductStore; property VendorParty: TSQLPartyID read fVendorParty write fVendorParty; property ShipmentMethodType: TSQLShipmentMethodTypeID read fShipmentMethodType write fShipmentMethodType; property CarrierParty: TSQLPartyID read fCarrierParty write fCarrierParty; end; // 149 TSQLWebSite = class(TSQLRecord) private fProductStore: TSQLProductStoreID; fAllowProductStoreChange: Boolean; fHostedPathAlias: RawUTF8; fIsDefault: Boolean; fDisplayMaintenancePage: Boolean; published property ProductStore: TSQLProductStoreID read fProductStore write fProductStore; property AllowProductStoreChange: Boolean read fAllowProductStoreChange write fAllowProductStoreChange; property HostedPathAlias: RawUTF8 read fHostedPathAlias write fHostedPathAlias; property IsDefault: Boolean read fIsDefault write fIsDefault; property DisplayMaintenancePage: Boolean read fDisplayMaintenancePage write fDisplayMaintenancePage; end; // 150 TSQLProductSubscriptionResource = class(TSQLRecord) private fProduct: TSQLProductID; fSubscriptionResource: TSQLSubscriptionResourceID; fFromDate: TDateTime; fThruDate: TDateTime; fPurchaseFromDate: TDateTime; fPurchaseThruDate: TDateTime; fMaxLifeTime: Double; fMaxLifeTimeUom: TSQLUomID; fAvailableTime: Double; fAvailableTimeUom: TSQLUomID; fUseCountLimit: Double; fUseTime: Double; fUseTimeUom: TSQLUomID; fUseRoleType: TSQLRoleTypeID; fAutomaticExtend: Boolean; fCanclAutmExtTime: Double; fCanclAutmExtTimeUom: TSQLUomID; fGracePeriodOnExpiry: Double; fGracePeriodOnExpiryUom: TSQLUomID; published property Product: TSQLProductID read fProduct write fProduct; property SubscriptionResource: TSQLSubscriptionResourceID read fSubscriptionResource write fSubscriptionResource; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property PurchaseFromDate: TDateTime read fPurchaseFromDate write fPurchaseFromDate; property PurchaseThruDate: TDateTime read fPurchaseThruDate write fPurchaseThruDate; property MaxLifeTime: Double read fMaxLifeTime write fMaxLifeTime; property MaxLifeTimeUom: TSQLUomID read fMaxLifeTimeUom write fMaxLifeTimeUom; property AvailableTime: Double read fAvailableTime write fAvailableTime; property AvailableTimeUom: TSQLUomID read fAvailableTimeUom write fAvailableTimeUom; property UseCountLimit: Double read fUseCountLimit write fUseCountLimit; property UseTime: Double read fUseTime write fUseTime; property UseTimeUom: TSQLUomID read fUseTimeUom write fUseTimeUom; property UseRoleType: TSQLRoleTypeID read fUseRoleType write fUseRoleType; property AutomaticExtend: Boolean read fAutomaticExtend write fAutomaticExtend; property CanclAutmExtTime: Double read fCanclAutmExtTime write fCanclAutmExtTime; property CanclAutmExtTimeUom: TSQLUomID read fCanclAutmExtTimeUom write fCanclAutmExtTimeUom; property GracePeriodOnExpiry: Double read fGracePeriodOnExpiry write fGracePeriodOnExpiry; property GracePeriodOnExpiryUom: TSQLUomID read fGracePeriodOnExpiryUom write fGracePeriodOnExpiryUom; end; // 151 TSQLSubscription = class(TSQLRecord) private fDescription: RawUTF8; fSubscriptionResource: TSQLSubscriptionResourceID; fCommunicationEvent: Integer; fContactMech: TSQLContactMechID; fOriginatedFromParty: TSQLPartyID; fOriginatedFromRoleType: TSQLRoleTypeID; fParty: TSQLPartyID; fRoleType: TSQLRoleTypeID; fPartyNeed: Integer; fNeedType: TSQLNeedTypeID; fOrderId: TSQLOrderItemID; fOrderItemSeq: Integer; fProduct: TSQLProductID; fProductCategory: TSQLProductCategoryID; fInventoryItem: TSQLInventoryItemID; fSubscriptionType: TSQLSubscriptionTypeID; fExternalSubscription: Integer; fFromDate: TDateTime; fThruDate: TDateTime; fPurchaseFromDate: TDateTime; fPurchaseThruDate: TDateTime; fMaxLifeTime: Double; fMaxLifeTimeUom: TSQLUomID; fAvailableTime: Double; fAvailableTimeUom: TSQLUomID; fUseCountLimit: Double; fUseTime: Double; fUseTimeUom: TSQLUomID; fAutomaticExtend: Boolean; fCanclAutmExtTime: Double; fCanclAutmExtTimeUom: TSQLUomID; fGracePeriodOnExpiry: Double; fGracePeriodOnExpiryUom: TSQLUomID; fExpirationCompletedDate: TDateTime; published property Description: RawUTF8 read fDescription write fDescription; property SubscriptionResource: TSQLSubscriptionResourceID read fSubscriptionResource write fSubscriptionResource; property CommunicationEvent: Integer read fCommunicationEvent write fCommunicationEvent; property ContactMech: TSQLContactMechID read fContactMech write fContactMech; property OriginatedFromParty: TSQLPartyID read fOriginatedFromParty write fOriginatedFromParty; property OriginatedFromRoleType: TSQLRoleTypeID read fOriginatedFromRoleType write fOriginatedFromRoleType; property Party: TSQLPartyID read fParty write fParty; property RoleType: TSQLRoleTypeID read fRoleType write fRoleType; property PartyNeed: Integer read fPartyNeed write fPartyNeed; property NeedType: TSQLNeedTypeID read fNeedType write fNeedType; property OrderId: TSQLOrderItemID read fOrderId write fOrderId; property OrderItemSeq: Integer read fOrderItemSeq write fOrderItemSeq; property Product: TSQLProductID read fProduct write fProduct; property ProductCategory: TSQLProductCategoryID read fProductCategory write fProductCategory; property InventoryItem: TSQLInventoryItemID read fInventoryItem write fInventoryItem; property SubscriptionType: TSQLSubscriptionTypeID read fSubscriptionType write fSubscriptionType; property ExternalSubscription: Integer read fExternalSubscription write fExternalSubscription; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property PurchaseFromDate: TDateTime read fPurchaseFromDate write fPurchaseFromDate; property PurchaseThruDate: TDateTime read fPurchaseThruDate write fPurchaseThruDate; property MaxLifeTime: Double read fMaxLifeTime write fMaxLifeTime; property MaxLifeTimeUom: TSQLUomID read fMaxLifeTimeUom write fMaxLifeTimeUom; property AvailableTime: Double read fAvailableTime write fAvailableTime; property AvailableTimeUom: TSQLUomID read fAvailableTimeUom write fAvailableTimeUom; property UseCountLimit: Double read fUseCountLimit write fUseCountLimit; property UseTime: Double read fUseTime write fUseTime; property UseTimeUom: TSQLUomID read fUseTimeUom write fUseTimeUom; property AutomaticExtend: Boolean read fAutomaticExtend write fAutomaticExtend; property CanclAutmExtTime: Double read fCanclAutmExtTime write fCanclAutmExtTime; property CanclAutmExtTimeUom: TSQLUomID read fCanclAutmExtTimeUom write fCanclAutmExtTimeUom; property GracePeriodOnExpiry: Double read fGracePeriodOnExpiry write fGracePeriodOnExpiry; property GracePeriodOnExpiryUom: TSQLUomID read fGracePeriodOnExpiryUom write fGracePeriodOnExpiryUom; property ExpirationCompletedDate: TDateTime read fExpirationCompletedDate write fExpirationCompletedDate; end; // 152 TSQLSubscriptionActivity = class(TSQLRecord) private fComments: RawUTF8; fDateSent: TDateTime; published property Comments: RawUTF8 read fComments write fComments; property DateSent: TDateTime read fDateSent write fDateSent; end; // 153 TSQLSubscriptionAttribute = class(TSQLRecord) private fSubscription: TSQLSubscriptionID; fAttrName: RawUTF8; fAttrValue: RawUTF8; fAttrDescription: RawUTF8; published property Subscription: TSQLSubscriptionID read fSubscription write fSubscription; property AttrName: RawUTF8 read fAttrName write fAttrName; property AttrValue: RawUTF8 read fAttrValue write fAttrValue; property AttrDescription: RawUTF8 read fAttrDescription write fAttrDescription; end; // 154 TSQLSubscriptionFulfillmentPiece = class(TSQLRecord) private fSubscriptionActivity: TSQLSubscriptionActivityID; fSubscription: TSQLSubscriptionID; published property SubscriptionActivity: TSQLSubscriptionActivityID read fSubscriptionActivity write fSubscriptionActivity; property Subscription: TSQLSubscriptionID read fSubscription write fSubscription; end; // 155 TSQLSubscriptionResource = class(TSQLRecord) private fParentResource: TSQLSubscriptionResourceID; fDescription: RawUTF8; fContent: TSQLContentID; fWebSite: TSQLWebSiteID; fServiceNameOnExpiry: RawUTF8; published property ParentResource: TSQLSubscriptionResourceID read fParentResource write fParentResource; property Description: RawUTF8 read fDescription write fDescription; property Content: TSQLContentID read fContent write fContent; property WebSite: TSQLWebSiteID read fWebSite write fWebSite; property ServiceNameOnExpiry: RawUTF8 read fServiceNameOnExpiry write fServiceNameOnExpiry; end; // 156 TSQLSubscriptionType = class(TSQLRecord) private fEncode: RawUTF8; fParentEncode: RawUTF8; fParent: TSQLSubscriptionTypeID; fHasTable: Boolean; fName: RawUTF8; FDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property ParentEncode: RawUTF8 read fParentEncode write fParentEncode; property Parent: TSQLSubscriptionTypeID read fParent write fParent; property HasTable: Boolean read fHasTable write fHasTable; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 157 TSQLSubscriptionTypeAttr = class(TSQLRecord) private fSubscriptionType: TSQLSubscriptionTypeID; fAttrName: RawUTF8; fDescription: RawUTF8; published property SubscriptionType: TSQLSubscriptionTypeID read fSubscriptionType write fSubscriptionType; property AttrName: RawUTF8 read fAttrName write fAttrName; property Description: RawUTF8 read fDescription write fDescription; end; // 158 TSQLSubscriptionCommEvent = class(TSQLRecord) private fSubscription: TSQLSubscriptionID; fCommunicationEvent: TSQLCommunicationEventID; published property Subscription: TSQLSubscriptionID read fSubscription write fSubscription; property CommunicationEvent: TSQLCommunicationEventID read fCommunicationEvent write fCommunicationEvent; end; // 159 TSQLMarketInterest = class(TSQLRecord) private fProductCategory: TSQLProductCategoryID; fPartyClassificationGroup: TSQLPartyClassificationGroupID; fFromDate: TDateTime; fThruDate: TDateTime; published property ProductCategory: TSQLProductCategoryID read fProductCategory write fProductCategory; property PartyClassificationGroup: TSQLPartyClassificationGroupID read fPartyClassificationGroup write fPartyClassificationGroup; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; end; // 160 TSQLReorderGuideline = class(TSQLRecord) private fProduct: TSQLProductID; fParty: TSQLPartyID; fRoleType: TSQLRoleTypeID; fFacility: TSQLFacilityID; fGeo: TSQLGeoID; fFromDate: TDateTime; fThruDate: TDateTime; fReorderQuantity: Double; fReorderLevel: Double; published property Product: TSQLProductID read fProduct write fProduct; property Party: TSQLPartyID read fParty write fParty; property RoleType: TSQLRoleTypeID read fRoleType write fRoleType; property Facility: TSQLFacilityID read fFacility write fFacility; property Geo: TSQLGeoID read fGeo write fGeo; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property ReorderQuantity: Double read fReorderQuantity write fReorderQuantity; property ReorderLevel: Double read fReorderLevel write fReorderLevel; end; // 161 TSQLSupplierPrefOrder = class(TSQLRecord) private fEncode: RawUTF8; fName: RawUTF8; fDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read fDescription write fDescription; end; // 162 TSQLSupplierProduct = class(TSQLRecord) private fProduct: TSQLProductID; fParty: TSQLPartyID; fAvailableFromDate: TDateTime; fAvailableThruDate: TDateTime; fSupplierPrefOrder: TSQLSupplierPrefOrderID; fSupplierRatingType: TSQLSupplierRatingTypeID; fStandardLeadTimeDays: Double; fMinimumOrderQuantity: Double; fOrderQtyIncrements: Double; fUnitsIncluded: Double; fQuantityUom: TSQLUomID; fAgreement: TSQLAgreementItemID; fAgreementItemSeq: Integer; fLastPrice: Currency; fShippingPrice: Currency; fCurrencyUom: TSQLUomID; fSupplierProductName: RawUTF8; fCanDropShip: Boolean; published property Product: TSQLProductID read fProduct write fProduct; property Party: TSQLPartyID read fParty write fParty; property AvailableFromDate: TDateTime read fAvailableFromDate write fAvailableFromDate; property AvailableThruDate: TDateTime read fAvailableThruDate write fAvailableThruDate; property SupplierPrefOrder: TSQLSupplierPrefOrderID read fSupplierPrefOrder write fSupplierPrefOrder; property SupplierRatingType: TSQLSupplierRatingTypeID read fSupplierRatingType write fSupplierRatingType; property StandardLeadTimeDays: Double read fStandardLeadTimeDays write fStandardLeadTimeDays; property MinimumOrderQuantity: Double read fMinimumOrderQuantity write fMinimumOrderQuantity; property OrderQtyIncrements: Double read fOrderQtyIncrements write fOrderQtyIncrements; property UnitsIncluded: Double read fUnitsIncluded write fUnitsIncluded; property QuantityUom: TSQLUomID read fQuantityUom write fQuantityUom; property Agreement: TSQLAgreementItemID read fAgreement write fAgreement; property AgreementItemSeq: Integer read fAgreementItemSeq write fAgreementItemSeq; property LastPrice: Currency read fLastPrice write fLastPrice; property ShippingPrice: Currency read fShippingPrice write fShippingPrice; property CurrencyUom: TSQLUomID read fCurrencyUom write fCurrencyUom; property SupplierProductName: RawUTF8 read fSupplierProductName write fSupplierProductName; property CanDropShip: Boolean read fCanDropShip write fCanDropShip; end; // 163 TSQLSupplierProductFeature = class(TSQLRecord) private fParty: TSQLPartyID; fProductFeature: TSQLProductFeatureID; fDescription: RawUTF8; fUom: TSQLUomID; fIdCode: RawUTF8; published property Party: TSQLPartyID read fParty write fParty; property ProductFeature: TSQLProductFeatureID read fProductFeature write fProductFeature; property Description: RawUTF8 read fDescription write fDescription; property Uom: TSQLUomID read fUom write fUom; property IdCode: RawUTF8 read fIdCode write fIdCode; end; // 164 TSQLSupplierRatingType = class(TSQLRecord) private fName: RawUTF8; fDescription: RawUTF8; published property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read fDescription write fDescription; end; // 165 TSQLProductPromoContent = class(TSQLRecord) private fProductPromo: TSQLProductPromoID; fContent: TSQLContentID; fProductPromoContentType: TSQLProductContentTypeID; fFromDate: TDateTime; fThruDate: TDateTime; published property ProductPromo: TSQLProductPromoID read fProductPromo write fProductPromo; property Content: TSQLContentID read fContent write fContent; property ProductPromoContentType: TSQLProductContentTypeID read fProductPromoContentType write fProductPromoContentType; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; end; // 166 TSQLProductGroupOrder = class(TSQLRecord) private fProduct: TSQLProductID; fFromDate: TDateTime; fThruDate: TDateTime; fStatus: TSQLStatusItemID; fReqOrderQty: Double; fSoldOrderQty: Double; fJob: TSQLJobSandboxID; published property Product: TSQLProductID read fProduct write fProduct; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property Status: TSQLStatusItemID read fStatus write fStatus; property ReqOrderQty: Double read fReqOrderQty write fReqOrderQty; property SoldOrderQty: Double read fSoldOrderQty write fSoldOrderQty; property Job: TSQLJobSandboxID read fJob write fJob; end; implementation uses Classes, SysUtils; // 1 class procedure TSQLCostComponentType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLCostComponentType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLCostComponentType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','CostComponentType.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update CostComponentType set parent=(select c.id from CostComponentType c where c.Encode=CostComponentType.ParentEncode);'); finally Rec.Free; end; end; // 2 class procedure TSQLGoodIdentificationType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLGoodIdentificationType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLGoodIdentificationType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','GoodIdentificationType.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update GoodIdentificationType set parent=(select c.id from GoodIdentificationType c where c.Encode=GoodIdentificationType.ParentEncode);'); finally Rec.Free; end; end; // 3 class procedure TSQLProdCatalogCategoryType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLProdCatalogCategoryType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLProdCatalogCategoryType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ProdCatalogCategoryType.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update ProdCatalogCategoryType set parent=(select c.id from ProdCatalogCategoryType c where c.Encode=ProdCatalogCategoryType.ParentEncode);'); finally Rec.Free; end; end; // 4 class procedure TSQLProductAssocType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLProductAssocType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLProductAssocType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ProductAssocType.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update ProductAssocType set parent=(select c.id from ProductAssocType c where c.Encode=ProductAssocType.ParentEncode);'); finally Rec.Free; end; end; // 5 class procedure TSQLProductCategoryType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLProductCategoryType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLProductCategoryType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ProductCategoryType.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update ProductCategoryType set parent=(select c.id from ProductCategoryType c where c.Encode=ProductCategoryType.ParentEncode);'); finally Rec.Free; end; end; // 6 class procedure TSQLProductCategoryContentType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLProductCategoryContentType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLProductCategoryContentType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ProductCategoryContentType.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update ProductCategoryContentType set parent=(select c.id from ProductCategoryContentType c where c.Encode=ProductCategoryContentType.ParentEncode);'); finally Rec.Free; end; end; // 7 class procedure TSQLProductContentType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLProductContentType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLProductContentType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ProductContentType.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update ProductContentType set parent=(select c.id from ProductContentType c where c.Encode=ProductContentType.ParentEncode);'); finally Rec.Free; end; end; // 8 class procedure TSQLProdConfItemContentType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLProdConfItemContentType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLProdConfItemContentType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ProdConfItemContentType.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update ProdConfItemContentType set parent=(select c.id from ProdConfItemContentType c where c.Encode=ProdConfItemContentType.ParentEncode);'); finally Rec.Free; end; end; // 9 class procedure TSQLProductFeatureApplType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLProductFeatureApplType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLProductFeatureApplType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ProductFeatureApplType.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update ProductFeatureApplType set parent=(select c.id from ProductFeatureApplType c where c.Encode=ProductFeatureApplType.ParentEncode);'); finally Rec.Free; end; end; // 10 class procedure TSQLProductFeatureIactnType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLProductFeatureIactnType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLProductFeatureIactnType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ProductFeatureIactnType.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update ProductFeatureIactnType set parent=(select c.id from ProductFeatureIactnType c where c.Encode=ProductFeatureIactnType.ParentEncode);'); finally Rec.Free; end; end; // 11 class procedure TSQLProductFeatureType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLProductFeatureType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLProductFeatureType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ProductFeatureType.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update ProductFeatureType set parent=(select c.id from ProductFeatureType c where c.Encode=ProductFeatureType.ParentEncode);'); Server.Execute('update ProductFeature set ProductFeatureType=(select c.id from ProductFeatureType c where c.Encode=ProductFeature.ProductFeatureTypeEncode);'); finally Rec.Free; end; end; // 12 class procedure TSQLProductMeterType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLProductMeterType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLProductMeterType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ProductMeterType.json']))); try while Rec.FillOne do Server.Add(Rec,true); finally Rec.Free; end; end; // 13 class procedure TSQLProductMaintType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLProductMaintType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLProductMaintType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ProductMaintType.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update ProductMaintType set parent=(select c.id from ProductMaintType c where c.Encode=ProductMaintType.ParentEncode);'); finally Rec.Free; end; end; // 14 class procedure TSQLProductPriceType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLProductPriceType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLProductPriceType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ProductPriceType.json']))); try while Rec.FillOne do Server.Add(Rec,true); finally Rec.Free; end; end; // 15 class procedure TSQLProductPricePurpose.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLProductPricePurpose; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLProductPricePurpose.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ProductPricePurpose.json']))); try while Rec.FillOne do Server.Add(Rec,true); finally Rec.Free; end; end; // 16 class procedure TSQLProductPriceActionType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLProductPriceActionType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLProductPriceActionType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ProductPriceActionType.json']))); try while Rec.FillOne do Server.Add(Rec,true); finally Rec.Free; end; end; // 17 class procedure TSQLProductType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLProductType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLProductType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ProductType.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update ProductType set parent=(select c.id from ProductType c where c.Encode=ProductType.ParentEncode);'); finally Rec.Free; end; end; // 18 class procedure TSQLFacilityType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLFacilityType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLFacilityType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','FacilityType.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update FacilityType set parent=(select c.id from FacilityType c where c.Encode=FacilityType.ParentEncode);'); finally Rec.Free; end; end; // 19 class procedure TSQLFacilityGroupType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLFacilityGroupType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLFacilityGroupType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','FacilityGroupType.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update FacilityGroup set FacilityGroupType=(select c.id from FacilityGroupType c where c.Encode=FacilityGroup.FacilityGroupTypeEncode);'); finally Rec.Free; end; end; // 20 class procedure TSQLFacilityGroup.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLFacilityGroup; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLFacilityGroup.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','FacilityGroup.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update FacilityGroup set PrimaryParentGroup=(select c.id from FacilityGroup c where c.Encode=FacilityGroup.PrimaryParentGroupEncode);'); Server.Execute('update FacilityGroup set FacilityGroupType=(select c.id from FacilityGroupType c where c.Encode=FacilityGroup.FacilityGroupTypeEncode);'); finally Rec.Free; end; end; // 21 class procedure TSQLInventoryItemType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLInventoryItemType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLInventoryItemType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','InventoryItemType.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update InventoryItemType set Parent=(select c.id from InventoryItemType c where c.Encode=InventoryItemType.ParentEncode);'); finally Rec.Free; end; end; // 22 class procedure TSQLProductStoreGroup.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLProductStoreGroup; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLProductStoreGroup.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ProductStoreGroup.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update ProductStoreGroup set PrimaryParentGroup=(select c.id from ProductStoreGroup c where c.Encode=ProductStoreGroup.PrimaryGroupEncode);'); Server.Execute('update ProductStoreGroup set ProductStoreGroupType=(select c.id from ProductStoreGroupType c where c.Encode=ProductStoreGroup.GroupTypeEncode);'); finally Rec.Free; end; end; // 23 class procedure TSQLVarianceReason.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLVarianceReason; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLVarianceReason.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','VarianceReason.json']))); try while Rec.FillOne do Server.Add(Rec,true); finally Rec.Free; end; end; // 24 class procedure TSQLSupplierPrefOrder.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLSupplierPrefOrder; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLSupplierPrefOrder.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','SupplierPrefOrder.json']))); try while Rec.FillOne do Server.Add(Rec,true); finally Rec.Free; end; end; // 25 class procedure TSQLSubscriptionType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLSubscriptionType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLSubscriptionType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','SubscriptionType.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update SubscriptionType set parent=(select c.id from SubscriptionType c where c.Encode=SubscriptionType.ParentEncode);'); finally Rec.Free; end; end; // 26 class procedure TSQLProductFeatureCategory.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLProductFeatureCategory; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLProductFeatureCategory.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ProductFeatureCategory.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update ProductFeatureCategory set parent=(select c.id from ProductFeatureCategory c where c.Encode=ProductFeatureCategory.ParentEncode);'); Server.Execute('update ProductFeature set ProductFeatureCategory=(select c.id from ProductFeatureCategory c where c.Encode=ProductFeature.ProductFeatureCategoryEncode);'); finally Rec.Free; end; end; // 27 class procedure TSQLProductFeature.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLProductFeature; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLProductFeature.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ProductFeature.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update ProductFeature set ProductFeatureType=(select c.id from ProductFeatureType c where c.Encode=ProductFeature.ProductFeatureTypeEncode);'); Server.Execute('update ProductFeature set ProductFeatureCategory=(select c.id from ProductFeatureCategory c where c.Encode=ProductFeature.ProductFeatureCategoryEncode);'); finally Rec.Free; end; end; // 28 class procedure TSQLQuantityBreakType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLQuantityBreakType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLQuantityBreakType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','QuantityBreakType.json']))); try while Rec.FillOne do Server.Add(Rec,true); finally Rec.Free; end; end; end.
{*******************************************************} { } { Delphi FireDAC Framework } { FireDAC format options editing frame } { } { Copyright(c) 2004-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$I FireDAC.inc} unit FireDAC.VCLUI.FormatOptions; interface uses {$IFDEF MSWINDOWS} Winapi.Messages, Winapi.Windows, {$ENDIF} System.SysUtils, System.Classes, Vcl.Controls, Vcl.Forms, Vcl.StdCtrls, Vcl.Grids, Vcl.ComCtrls, Vcl.Buttons, Vcl.ExtCtrls, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.VCLUI.Controls; type TfrmFDGUIxFormsFormatOptions = class(TFrame) mo_GroupBox1: TPanel; mo_Panel3: TPanel; mo_sgMapRules: TStringGrid; mo_cbxDataType: TComboBox; mo_Panel2: TPanel; mo_Panel5: TPanel; mo_cbOwnMapRules: TCheckBox; mo_gb1: TPanel; mo_Label2: TLabel; mo_Label3: TLabel; mo_edtMaxBcdPrecision: TEdit; mo_edtMaxBcdScale: TEdit; mo_gb2: TPanel; mo_Label1: TLabel; mo_Label10: TLabel; mo_cbStrsEmpty2Null: TCheckBox; mo_cbStrsTrim: TCheckBox; mo_edtMaxStringSize: TEdit; mo_edtInlineDataSize: TEdit; mo_btnAddRule: TSpeedButton; mo_btnRemRule: TSpeedButton; mo_Panel6: TPanel; mo_Label6: TLabel; mo_cbDefaultParamDataType: TComboBox; mo_Panel7: TPanel; mo_cbRound2Scale: TCheckBox; mo_cbDataSnapCompatibility: TCheckBox; mo_Panel1: TPanel; mo_Label15: TLabel; mo_edtFmtDisplayDate: TEdit; mo_Label16: TLabel; mo_edtFmtDisplayTime: TEdit; mo_Label17: TLabel; mo_edtFmtDisplayDateTime: TEdit; mo_Label18: TLabel; mo_edtFmtDisplayNum: TEdit; mo_Label19: TLabel; mo_edtFmtEditNum: TEdit; mo_cbStrsTrim2Len: TCheckBox; mo_cbCheckPrecision: TCheckBox; mo_cbADOCompatibility: TCheckBox; procedure mo_cbOwnMapRulesClick(Sender: TObject); procedure mo_btnAddRuleClick(Sender: TObject); procedure mo_btnRemRuleClick(Sender: TObject); procedure mo_sgMapRulesKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure mo_sgMapRulesSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); procedure mo_sgMapRulesTopLeftChanged(Sender: TObject); procedure mo_cbxDataTypeExit(Sender: TObject); procedure mo_cbxDataTypeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure mo_sgMapRulesEnter(Sender: TObject); procedure mo_Change(Sender: TObject); private FOnModified: TNotifyEvent; FLockModified: Boolean; procedure AdjustComboBox(ABox: TComboBox; ACol, ARow: Integer; AGrid: TStringGrid); { Private declarations } public procedure LoadFrom(AOpts: TFDFormatOptions); procedure SaveTo(AOpts: TFDFormatOptions); published property OnModified: TNotifyEvent read FOnModified write FOnModified; end; implementation {$R *.dfm} uses Data.DB, FireDAC.Stan.Consts; { --------------------------------------------------------------------------- } procedure TfrmFDGUIxFormsFormatOptions.LoadFrom(AOpts: TFDFormatOptions); function IntToStrDef(AValue, ADefault: Integer): String; begin if AValue = ADefault then Result := '' else Result := IntToStr(AValue); end; function UIntToStrDef(AValue, ADefault: LongWord): String; begin if AValue = ADefault then Result := '' else Result := IntToStr(AValue); end; var i: Integer; oRule: TFDMapRule; begin FLockModified := True; try mo_sgMapRules.Cells[0, 0] := 'SourceDataType'; mo_sgMapRules.Cells[1, 0] := 'TargetDataType'; mo_sgMapRules.Cells[2, 0] := 'PrecMin'; mo_sgMapRules.Cells[3, 0] := 'PrecMax'; mo_sgMapRules.Cells[4, 0] := 'ScaleMin'; mo_sgMapRules.Cells[5, 0] := 'ScaleMax'; mo_sgMapRules.Cells[6, 0] := 'SizeMin'; mo_sgMapRules.Cells[7, 0] := 'SizeMax'; mo_sgMapRules.Cells[8, 0] := 'NameMask'; mo_sgMapRules.Cells[9, 0] := 'TypeMask'; if AOpts.MapRules.Count = 0 then begin mo_sgMapRules.RowCount := 2; for i := 0 to mo_sgMapRules.ColCount - 1 do mo_sgMapRules.Cells[i, 1] := '' end else begin mo_sgMapRules.RowCount := AOpts.MapRules.Count + 1; for i := 0 to AOpts.MapRules.Count - 1 do begin oRule := AOpts.MapRules[i]; mo_sgMapRules.Cells[0, i + 1] := mo_cbxDataType.Items[Integer(oRule.SourceDataType)]; mo_sgMapRules.Cells[1, i + 1] := mo_cbxDataType.Items[Integer(oRule.TargetDataType)]; mo_sgMapRules.Cells[2, i + 1] := IntToStrDef(oRule.PrecMin, C_FD_DefMapPrec); mo_sgMapRules.Cells[3, i + 1] := IntToStrDef(oRule.PrecMax, C_FD_DefMapPrec); mo_sgMapRules.Cells[4, i + 1] := IntToStrDef(oRule.ScaleMin, C_FD_DefMapScale); mo_sgMapRules.Cells[5, i + 1] := IntToStrDef(oRule.ScaleMax, C_FD_DefMapScale); mo_sgMapRules.Cells[6, i + 1] := UIntToStrDef(oRule.SizeMin, C_FD_DefMapSize); mo_sgMapRules.Cells[7, i + 1] := UIntToStrDef(oRule.SizeMax, C_FD_DefMapSize); mo_sgMapRules.Cells[8, i + 1] := oRule.NameMask; mo_sgMapRules.Cells[9, i + 1] := oRule.TypeMask; end; end; mo_cbOwnMapRules.Checked := AOpts.OwnMapRules; mo_sgMapRules.Enabled := mo_cbOwnMapRules.Checked; mo_cbStrsEmpty2Null.Checked := AOpts.StrsEmpty2Null; mo_cbStrsTrim.Checked := AOpts.StrsTrim; mo_cbStrsTrim2Len.Checked := AOpts.StrsTrim2Len; mo_edtMaxStringSize.Text := IntToStr(AOpts.MaxStringSize); mo_edtMaxBcdPrecision.Text := IntToStr(AOpts.MaxBcdPrecision); mo_edtMaxBcdScale.Text := IntToStr(AOpts.MaxBcdScale); mo_cbOwnMapRulesClick(nil); mo_sgMapRules.DefaultRowHeight := mo_cbxDataType.Height - GetSystemMetrics(SM_CYBORDER); mo_edtInlineDataSize.Text := IntToStr(AOpts.InlineDataSize); mo_cbDefaultParamDataType.ItemIndex := Integer(AOpts.DefaultParamDataType); mo_cbRound2Scale.Checked := AOpts.Round2Scale; mo_cbCheckPrecision.Checked := AOpts.CheckPrecision; mo_cbDataSnapCompatibility.Checked := AOpts.DataSnapCompatibility; mo_cbADOCompatibility.Checked := AOpts.ADOCompatibility; mo_edtFmtDisplayDate.Text := AOpts.FmtDisplayDate; mo_edtFmtDisplayTime.Text := AOpts.FmtDisplayTime; mo_edtFmtDisplayDateTime.Text := AOpts.FmtDisplayDateTime; mo_edtFmtDisplayNum.Text := AOpts.FmtDisplayNumeric; mo_edtFmtEditNum.Text := AOpts.FmtEditNumeric; finally FLockModified := False; end; end; { --------------------------------------------------------------------------- } procedure TfrmFDGUIxFormsFormatOptions.SaveTo(AOpts: TFDFormatOptions); function OneChar(S: String; ADefault: Char): Char; begin S := Trim(S); if S = '' then Result := ADefault else Result := S[1]; end; var i: Integer; oRule: TFDMapRule; begin if AOpts.OwnMapRules <> mo_cbOwnMapRules.Checked then AOpts.OwnMapRules := mo_cbOwnMapRules.Checked; if AOpts.OwnMapRules then begin AOpts.MapRules.Clear; for i := 1 to mo_sgMapRules.RowCount - 1 do if ((mo_sgMapRules.Cells[0, i] <> '') or (mo_sgMapRules.Cells[8, i] <> '') or (mo_sgMapRules.Cells[9, i] <> '')) and (mo_sgMapRules.Cells[1, i] <> '') then begin oRule := AOpts.MapRules.Add; oRule.SourceDataType := TFDDataType(mo_cbxDataType.Items.IndexOf(mo_sgMapRules.Cells[0, i])); oRule.TargetDataType := TFDDataType(mo_cbxDataType.Items.IndexOf(mo_sgMapRules.Cells[1, i])); oRule.PrecMin := StrToIntDef(mo_sgMapRules.Cells[2, i], C_FD_DefMapPrec); oRule.PrecMax := StrToIntDef(mo_sgMapRules.Cells[3, i], C_FD_DefMapPrec); oRule.ScaleMin := StrToIntDef(mo_sgMapRules.Cells[4, i], C_FD_DefMapScale); oRule.ScaleMax := StrToIntDef(mo_sgMapRules.Cells[5, i], C_FD_DefMapScale); oRule.SizeMin := LongWord(StrToIntDef(mo_sgMapRules.Cells[6, i], Integer(C_FD_DefMapSize))); oRule.SizeMax := LongWord(StrToIntDef(mo_sgMapRules.Cells[7, i], Integer(C_FD_DefMapSize))); oRule.NameMask := Trim(mo_sgMapRules.Cells[8, i]); oRule.TypeMask := Trim(mo_sgMapRules.Cells[9, i]); end; end; if AOpts.StrsEmpty2Null <> mo_cbStrsEmpty2Null.Checked then AOpts.StrsEmpty2Null := mo_cbStrsEmpty2Null.Checked; if AOpts.StrsTrim <> mo_cbStrsTrim.Checked then AOpts.StrsTrim := mo_cbStrsTrim.Checked; if AOpts.StrsTrim2Len <> mo_cbStrsTrim2Len.Checked then AOpts.StrsTrim2Len := mo_cbStrsTrim2Len.Checked; if AOpts.MaxStringSize <> LongWord(StrToInt(mo_edtMaxStringSize.Text)) then AOpts.MaxStringSize := LongWord(StrToInt(mo_edtMaxStringSize.Text)); if AOpts.MaxBcdPrecision <> StrToInt(mo_edtMaxBcdPrecision.Text) then AOpts.MaxBcdPrecision := StrToInt(mo_edtMaxBcdPrecision.Text); if AOpts.MaxBcdScale <> StrToInt(mo_edtMaxBcdScale.Text) then AOpts.MaxBcdScale := StrToInt(mo_edtMaxBcdScale.Text); if AOpts.InlineDataSize <> StrToInt(mo_edtInlineDataSize.Text) then AOpts.InlineDataSize := StrToInt(mo_edtInlineDataSize.Text); if mo_cbDefaultParamDataType.ItemIndex <> Integer(AOpts.DefaultParamDataType) then AOpts.DefaultParamDataType := TFieldType(mo_cbDefaultParamDataType.ItemIndex); if mo_cbRound2Scale.Checked <> AOpts.Round2Scale then AOpts.Round2Scale := mo_cbRound2Scale.Checked; if mo_cbCheckPrecision.Checked <> AOpts.CheckPrecision then AOpts.CheckPrecision := mo_cbCheckPrecision.Checked; if mo_cbDataSnapCompatibility.Checked <> AOpts.DataSnapCompatibility then AOpts.DataSnapCompatibility := mo_cbDataSnapCompatibility.Checked; if mo_cbADOCompatibility.Checked <> AOpts.ADOCompatibility then AOpts.ADOCompatibility := mo_cbADOCompatibility.Checked; if mo_edtFmtDisplayDate.Text <> AOpts.FmtDisplayDate then AOpts.FmtDisplayDate := mo_edtFmtDisplayDate.Text; if mo_edtFmtDisplayTime.Text <> AOpts.FmtDisplayTime then AOpts.FmtDisplayTime := mo_edtFmtDisplayTime.Text; if mo_edtFmtDisplayDateTime.Text <> AOpts.FmtDisplayDateTime then AOpts.FmtDisplayDateTime := mo_edtFmtDisplayDateTime.Text; if mo_edtFmtDisplayNum.Text <> AOpts.FmtDisplayNumeric then AOpts.FmtDisplayNumeric := mo_edtFmtDisplayNum.Text; if mo_edtFmtEditNum.Text <> AOpts.FmtEditNumeric then AOpts.FmtEditNumeric := mo_edtFmtEditNum.Text; end; { --------------------------------------------------------------------------- } procedure TfrmFDGUIxFormsFormatOptions.mo_Change(Sender: TObject); begin if not FLockModified and Assigned(FOnModified) then FOnModified(Self); end; { --------------------------------------------------------------------------- } procedure TfrmFDGUIxFormsFormatOptions.mo_cbOwnMapRulesClick(Sender: TObject); begin mo_sgMapRules.Enabled := mo_cbOwnMapRules.Checked; mo_btnAddRule.Enabled := mo_cbOwnMapRules.Checked; mo_btnRemRule.Enabled := mo_cbOwnMapRules.Checked; mo_Change(nil); end; { --------------------------------------------------------------------------- } procedure TfrmFDGUIxFormsFormatOptions.mo_btnAddRuleClick(Sender: TObject); var i, j: Integer; begin mo_sgMapRules.RowCount := mo_sgMapRules.RowCount + 1; for i := mo_sgMapRules.Row to mo_sgMapRules.RowCount - 2 do for j := 0 to mo_sgMapRules.ColCount - 1 do mo_sgMapRules.Cells[j, i + 1] := mo_sgMapRules.Cells[j, i]; mo_Change(nil); end; { --------------------------------------------------------------------------- } procedure TfrmFDGUIxFormsFormatOptions.mo_btnRemRuleClick(Sender: TObject); var i, j: Integer; begin if mo_sgMapRules.RowCount > 1 then begin for i := mo_sgMapRules.Row to mo_sgMapRules.RowCount - 2 do for j := 0 to mo_sgMapRules.ColCount - 1 do mo_sgMapRules.Cells[j, i] := mo_sgMapRules.Cells[j, i + 1]; if mo_sgMapRules.RowCount = 2 then for j := 0 to mo_sgMapRules.ColCount - 1 do mo_sgMapRules.Cells[j, 1] := '' else mo_sgMapRules.RowCount := mo_sgMapRules.RowCount - 1; mo_Change(nil); end; end; { --------------------------------------------------------------------------- } procedure TfrmFDGUIxFormsFormatOptions.mo_sgMapRulesKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Key = VK_F2) and mo_cbxDataType.Visible then begin mo_cbxDataType.BringToFront; mo_cbxDataType.SetFocus; end; end; { --------------------------------------------------------------------------- } procedure TfrmFDGUIxFormsFormatOptions.mo_sgMapRulesEnter(Sender: TObject); var lCanSelect: Boolean; begin if not mo_cbxDataType.Visible then mo_sgMapRulesSelectCell(mo_sgMapRules, mo_sgMapRules.Col, mo_sgMapRules.Row, lCanSelect); end; { --------------------------------------------------------------------------- } procedure TfrmFDGUIxFormsFormatOptions.mo_sgMapRulesSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); begin if (ARow >= 1) and (ACol <= 1) then begin mo_cbxDataType.ItemIndex := mo_cbxDataType.Items.IndexOf( mo_sgMapRules.Cells[ACol, ARow]); AdjustComboBox(mo_cbxDataType, ACol, ARow, mo_sgMapRules); end else mo_cbxDataType.Visible := False; CanSelect := True; if mo_cbxDataType.Visible then mo_cbxDataType.SetFocus; end; { --------------------------------------------------------------------------- } procedure TfrmFDGUIxFormsFormatOptions.mo_sgMapRulesTopLeftChanged( Sender: TObject); begin if mo_cbxDataType.Visible then AdjustComboBox(mo_cbxDataType, mo_sgMapRules.Col, mo_sgMapRules.Row, mo_sgMapRules); end; { --------------------------------------------------------------------------- } procedure TfrmFDGUIxFormsFormatOptions.mo_cbxDataTypeExit(Sender: TObject); begin if (mo_cbxDataType.ItemIndex >= 0) and (mo_cbxDataType.ItemIndex < mo_cbxDataType.Items.Count) and (mo_sgMapRules.Cells[mo_sgMapRules.Col, mo_sgMapRules.Row] <> mo_cbxDataType.Items[mo_cbxDataType.ItemIndex]) then begin mo_sgMapRules.Cells[mo_sgMapRules.Col, mo_sgMapRules.Row] := mo_cbxDataType.Items[mo_cbxDataType.ItemIndex]; mo_Change(nil); end; end; { --------------------------------------------------------------------------- } procedure TfrmFDGUIxFormsFormatOptions.mo_cbxDataTypeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if mo_cbxDataType.DroppedDown then Exit; if Key = VK_ESCAPE then begin AdjustComboBox(mo_cbxDataType, mo_sgMapRules.Col, mo_sgMapRules.Row, mo_sgMapRules); mo_cbxDataType.SelectAll; Key := 0; end else if (Key = VK_RETURN) or (Key = VK_DOWN) then begin mo_cbxDataType.OnExit(mo_cbxDataType); if mo_sgMapRules.Row < mo_sgMapRules.RowCount - 1 then mo_sgMapRules.Row := mo_sgMapRules.Row + 1; Key := 0; end else if Key = VK_UP then begin mo_cbxDataType.OnExit(mo_cbxDataType); if mo_sgMapRules.Row > mo_sgMapRules.FixedRows then mo_sgMapRules.Row := mo_sgMapRules.Row - 1; Key := 0; end; end; { --------------------------------------------------------------------------- } procedure TfrmFDGUIxFormsFormatOptions.AdjustComboBox(ABox: TComboBox; ACol, ARow: Integer; AGrid: TStringGrid); var R: TRect; begin if ABox = nil then Exit; R := AGrid.CellRect(ACol, ARow); R.TopLeft := ABox.Parent.ScreenToClient(AGrid.ClientToScreen(R.TopLeft)); R.BottomRight := ABox.Parent.ScreenToClient(AGrid.ClientToScreen(R.BottomRight)); ABox.Left := R.Left; ABox.Top := R.Top; ABox.Width := R.Right - R.Left + 1; ABox.Text := AGrid.Cells[ACol, ARow]; ABox.Visible := True; end; end.
unit UAndroidTools; interface uses System.Messaging, AndroidAPI.Helpers, AndroidAPI.Jni.Os, AndroidAPI.Jni.GraphicsContentViewText, AndroidAPI.Jni.Net, FMX.Platform.Android, AndroidAPI.JNIBridge, AndroidAPI.Jni.JavaTypes, AndroidAPI.Jni.App; type TContentEnum = (ctVideo, ctImages, ctAudio, ctText, ctAll); TFileBrowseEvent = reference to procedure(var Filename: string; var Success: boolean); TFileBrowser = class private fOnExecute: TFileBrowseEvent; fFilename: string; class var FInstance: TFileBrowser; class function Instance: TFileBrowser; protected fMessageSubscriptionID: integer; procedure DoExecute(Success: boolean); function HandleIntentAction(const Data: JIntent): boolean; procedure HandleActivityMessage(const sender: TObject; const M: TMessage); procedure Initialize(Content: TContentEnum; OnExecute: TFileBrowseEvent); public class constructor Create; class destructor Destroy; /// <summary> Use Android API to have the user pick a file with a certain content type </summary> /// <param OnExecute> Event occuring when the user has picked a file. Write a (anonymous) procedure(var Filename: string; var Success: boolean) to handle the event. <param> class procedure BrowseForFile(Content: TContentEnum; OnExecute: TFileBrowseEvent); end; procedure PlayVideo(VideoFilename: string); implementation uses System.Sysutils; const ContentStrings: array [TContentEnum] of string = ('video/*', 'image/*', 'audio/*', 'text/*', '*/*'); { TFileBrowser } class function TFileBrowser.Instance: TFileBrowser; begin if not assigned(FInstance) then FInstance := TFileBrowser.Create; Result := FInstance; end; class constructor TFileBrowser.Create; begin FInstance := nil; end; class destructor TFileBrowser.Destroy; begin FInstance.free; end; class procedure TFileBrowser.BrowseForFile(Content: TContentEnum; OnExecute: TFileBrowseEvent); begin Instance.Initialize(Content, OnExecute); end; procedure TFileBrowser.Initialize(Content: TContentEnum; OnExecute: TFileBrowseEvent); var Intent: JIntent; begin fOnExecute := OnExecute; fMessageSubscriptionID := TMessageManager.DefaultManager.SubscribeToMessage (TMessageResultNotification, HandleActivityMessage); Intent := TJIntent.Create; Intent.setType(StringToJString(ContentStrings[Content])); Intent.setAction(TJIntent.JavaClass.ACTION_GET_CONTENT); MainActivity.startActivityForResult(Intent, 0); end; procedure TFileBrowser.DoExecute(Success: boolean); begin if assigned(fOnExecute) then fOnExecute(fFilename, Success); end; procedure TFileBrowser.HandleActivityMessage(const sender: TObject; const M: TMessage); begin if M is TMessageResultNotification then begin DoExecute(HandleIntentAction(TMessageReceivedNotification(M).Value)); end; end; function TFileBrowser.HandleIntentAction(const Data: JIntent): boolean; var C: JCursor; I: integer; begin C := MainActivity.getContentResolver.query(Data.getData, nil, StringToJString(''), nil, StringToJString('')); C.moveToFirst; Result := false; for I := 0 to C.getColumnCount - 1 do begin if JStringToString(C.getColumnName(I)) = '_data' then // '_data' column contains the path begin fFilename := JStringToString(C.getString(I)); Result := true; Break; end; end; if not Result then fFilename := ''; end; procedure PlayVideo(VideoFilename: string); var Intent: JIntent; uri: Jnet_URI; ext: string; begin ext := ExtractFileExt(VideoFilename); ext := Copy(ext, 2, length(ext) - 1); uri := TAndroidHelper.StrToJURI(VideoFilename); Intent := TJIntent.JavaClass.init(TJIntent.JavaClass.ACTION_VIEW); Intent.setDataAndType(uri, StringToJString('video/' + ext)); TAndroidHelper.Activity.startActivity(Intent); end; end.
unit ncPRConsts; { ResourceString: Dario 13/03/13 } interface uses messages; function PRFolder(status: char): String; Const prfolder_preview = #0; prfolder_backup = #1; WM_PR_NEWDOC = WM_APP + 1; WM_PR_EXTRACTIMG_START = WM_APP + 2; WM_PR_EXTRACTIMG_PROGRESS = WM_APP + 3; WM_PR_EXTRACTIMG_ERROR = WM_APP + 4; WM_PR_CREATINGDOC = WM_APP + 5; kReviewCli = 'nexREVIEWCLI'; //kTargetExeName_C = 'nexCafe5PrintMan.exe'; kTargetExeName_C = 'nexguard.exe'; //kTargetExeName_S = 'printGuard.exe'; kConsoleTitle = 'nexAP'; kThumbWidth = 200; kMMFPrefix = 'nexprintreviewmmf'; kNovaPDFOEM7printerSetupFileName = 'nexprinter.exe'; kNovaPDFOEM7printerSetupVersion = '1'; kNovaPDFOEM7iniName = 'NovaVersion'; kAfterPrintFileName = 'nexAP.exe'; kNexPrinterName = 'Impressora NexCafé'; implementation uses sysutils; function PRFolder(status: char): String; begin case status of prfolder_preview : Result := ExtractFilePath(ParamStr(0))+'print\review\'; // do not localize prfolder_backup : Result := ExtractFilePath(ParamStr(0))+'print\backup\'; // do not localize else Result := ExtractFilePath(ParamStr(0))+'print\pend\'+status+'\'; // do not localize end; end; end.
unit FIToolkit.Commons.Utils; interface uses System.SysUtils, System.IOUtils, System.TypInfo, System.Rtti, System.Generics.Defaults, FIToolkit.Commons.Types; type TIff = record public class function Get<T>(Condition : Boolean; const TruePart, FalsePart : T) : T; static; inline; end; TObjectProperties<T : class> = record public class procedure Copy(Source, Destination : T; const Filter : TObjectPropertyFilter = nil); static; end; { Helpers } TExceptionHelper = class helper for Exception public function ToString(IncludeClassName : Boolean) : String; overload; end; TFileNameHelper = record helper for TFileName public class function GetComparer : IComparer<TFileName>; static; function Expand(Check : Boolean = False) : TFileName; overload; function Expand(ExpandVars, Check : Boolean) : TFileName; overload; function IsApplicable : Boolean; function IsEmpty : Boolean; end; TPathHelper = record helper for TPath public class function ExpandIfNotExists(const Path : String; Check : Boolean = False) : String; static; class function GetDirectoryName(const FileName : TFileName; TrailingPathDelim : Boolean) : String; overload; static; class function GetExePath : String; static; class function GetFullPath(Path : String; ExpandVars, Check : Boolean) : String; overload; static; class function GetQuotedPath(const Path : String; QuoteChar : Char) : String; static; class function IncludeTrailingPathDelimiter(const Path : String) : String; static; class function IsApplicableFileName(const FileName : TFileName) : Boolean; static; end; TRttiTypeHelper = class helper for TRttiType public function GetFullName : String; function GetMethod(MethodAddress : Pointer) : TRttiMethod; overload; function IsArray : Boolean; function IsString : Boolean; end; TTypeInfoHelper = record helper for TTypeInfo public function IsArray : Boolean; function IsString : Boolean; end; TTypeKindHelper = record helper for TTypeKind public function IsArray : Boolean; function IsString : Boolean; end; TVarRecHelper = record helper for TVarRec public function ToString : String; end; { Utils } function AbortException : EAbort; function ArrayOfConstToStringArray(const Vals : array of const) : TArray<String>; function ExpandEnvVars(const S : String) : String; function GetFixInsightExePath : TFileName; function GetModuleVersion(ModuleHandle : THandle; out Major, Minor, Release, Build : Word) : Boolean; function Iff : TIff; inline; procedure PressAnyKeyPrompt; procedure PrintLn; overload; procedure PrintLn(const Arg : Variant); overload; procedure PrintLn(const Args : array of const); overload; function ReadSmallTextFile(const FileName : TFileName; StartLine, EndLine : Integer) : String; function TValueArrayToStringArray(const Vals : array of TValue) : TArray<String>; function WaitForFileAccess(const FileName : TFileName; DesiredAccess : TFileAccess; CheckingInterval, Timeout : Cardinal) : Boolean; implementation uses System.Classes, System.Variants, System.Math, System.SysConst, System.Threading, System.Win.Registry, Winapi.Windows, FIToolkit.Commons.Consts; { Internals } procedure _PrintLn(const S : String); begin {$IFDEF CONSOLE} WriteLn(S); {$ELSE} OutputDebugString(PChar(S)); {$ENDIF} end; { Utils } function AbortException : EAbort; begin Result := EAbort.CreateRes(@SOperationAborted); end; function ArrayOfConstToStringArray(const Vals : array of const) : TArray<String>; var i : Integer; begin SetLength(Result, Length(Vals)); for i := 0 to High(Vals) do Result[i] := Vals[i].ToString; end; function ExpandEnvVars(const S : String) : String; var iBufferSize : Cardinal; pBuffer : PChar; begin iBufferSize := ExpandEnvironmentStrings(PChar(S), nil, 0); if iBufferSize = 0 then Result := S else begin pBuffer := StrAlloc(iBufferSize); try if ExpandEnvironmentStrings(PChar(S), pBuffer, iBufferSize) = 0 then RaiseLastOSError; Result := String(pBuffer); finally StrDispose(pBuffer); end; end; end; function GetFixInsightExePath : TFileName; var R : TRegistry; S : String; begin Result := String.Empty; R := TRegistry.Create; try R.RootKey := HKEY_CURRENT_USER; if R.OpenKeyReadOnly(STR_FIXINSIGHT_REGKEY) then begin S := IncludeTrailingPathDelimiter(R.ReadString(STR_FIXINSIGHT_REGVALUE)) + STR_FIXINSIGHT_EXENAME; if TFile.Exists(S) then Result := S; end; finally R.Free; end; end; function GetModuleVersion(ModuleHandle : THandle; out Major, Minor, Release, Build : Word) : Boolean; var RS : TResourceStream; FileInfo : PVSFixedFileInfo; FileInfoSize : UINT; begin Result := False; Major := 0; Minor := 0; Release := 0; Build := 0; if FindResource(ModuleHandle, MakeIntResource(VS_VERSION_INFO), RT_VERSION) <> 0 then begin RS := TResourceStream.CreateFromID(ModuleHandle, VS_VERSION_INFO, RT_VERSION); try Result := VerQueryValue(RS.Memory, '\', Pointer(FileInfo), FileInfoSize); if Result then with FileInfo^ do begin Major := dwFileVersionMS shr 16; Minor := dwFileVersionMS and $FFFF; Release := dwFileVersionLS shr 16; Build := dwFileVersionLS and $FFFF; end; finally RS.Free; end; end; end; function Iff : TIff; begin Result := Default(TIff); end; procedure PressAnyKeyPrompt; var hConsole : THandle; ConsoleInput : TInputRecord; iDummy : Cardinal; begin PrintLn(RSPressAnyKey); hConsole := GetStdHandle(STD_INPUT_HANDLE); if IsConsole and (hConsole <> INVALID_HANDLE_VALUE) then repeat WaitForSingleObjectEx(hConsole, INFINITE, False); if ReadConsoleInput(hConsole, ConsoleInput, 1, iDummy) then if ConsoleInput.EventType = KEY_EVENT then if ConsoleInput.Event.KeyEvent.bKeyDown then Break; until False; end; procedure PrintLn; begin _PrintLn(sLineBreak); end; procedure PrintLn(const Arg : Variant); var S : String; begin if VarIsStr(Arg) then S := Arg else S := TValue.FromVariant(Arg).ToString; _PrintLn(S); end; procedure PrintLn(const Args : array of const); var S : String; Arg : TVarRec; begin S := String.Empty; for Arg in Args do S := S + Arg.ToString; _PrintLn(S); end; function ReadSmallTextFile(const FileName : TFileName; StartLine, EndLine : Integer) : String; var L : TStringList; B : TStringBuilder; iFirstIdx, iLastIdx, i : Integer; begin Result := String.Empty; if TFile.Exists(FileName) and (StartLine <= EndLine) then begin L := TStringList.Create; try try L.LoadFromFile(FileName); except on E: EFileStreamError do Exit; else raise; end; if (StartLine = 0) and (EndLine = 0) then Result := L.Text else begin iFirstIdx := Max(StartLine - 1, 0); iLastIdx := Min(EndLine - 1, L.Count - 1); if iFirstIdx <= iLastIdx then begin B := TStringBuilder.Create(L.Capacity); try for i := iFirstIdx to iLastIdx do if i < iLastIdx then B.AppendLine(L[i]) else B.Append(L[i]); Result := B.ToString; finally B.Free; end; end; end; finally L.Free; end; end; end; function TValueArrayToStringArray(const Vals : array of TValue) : TArray<String>; var i : Integer; begin SetLength(Result, Length(Vals)); for i := 0 to High(Vals) do Result[i] := Vals[i].ToString; end; function WaitForFileAccess(const FileName : TFileName; DesiredAccess : TFileAccess; CheckingInterval, Timeout : Cardinal) : Boolean; function HasAccess : Boolean; begin Result := False; if TFile.Exists(FileName) then try TFile.Open(FileName, TFileMode.fmOpen, DesiredAccess, TFileShare.fsRead).Free; Result := True; except Exit; end; end; var StartTickCount : Cardinal; begin Result := False; StartTickCount := TThread.GetTickCount; repeat if HasAccess then Exit(True) else TThread.Sleep(CheckingInterval); until TThread.GetTickCount - StartTickCount >= Timeout; end; { TExceptionHelper } function TExceptionHelper.ToString(IncludeClassName : Boolean) : String; const STR_SEPARATOR = ': '; STR_INDENT = ' '; var Inner, E : Exception; S : String; begin if not IncludeClassName then Result := ToString else begin Result := String.Empty; Inner := Self; while Assigned(Inner) do begin S := Inner.ClassName + STR_SEPARATOR + Inner.Message; if Result.IsEmpty then Result := S else Result := Result + sLineBreak + S; if Inner is EAggregateException then for E in EAggregateException(Inner) do Result := Result + sLineBreak + STR_INDENT + E.ToString(IncludeClassName); Inner := Inner.InnerException; end; end; end; { TFileNameHelper } function TFileNameHelper.Expand(Check : Boolean) : TFileName; begin Result := Self.Expand(False, Check); end; function TFileNameHelper.Expand(ExpandVars, Check : Boolean) : TFileName; begin Result := TPath.GetFullPath(Self, ExpandVars, Check); end; class function TFileNameHelper.GetComparer : IComparer<TFileName>; begin Result := TComparer<TFileName>.Construct( function (const Left, Right : TFileName) : Integer begin Result := String.Compare(Left, Right, True); end ); end; function TFileNameHelper.IsApplicable : Boolean; begin Result := TPath.IsApplicableFileName(Self); end; function TFileNameHelper.IsEmpty : Boolean; begin Result := String.IsNullOrEmpty(Self); end; { TIff } class function TIff.Get<T>(Condition : Boolean; const TruePart, FalsePart : T) : T; begin if Condition then Result := TruePart else Result := FalsePart; end; { TPathHelper } class function TPathHelper.ExpandIfNotExists(const Path : String; Check : Boolean) : String; begin if TFile.Exists(Path) or TDirectory.Exists(Path) then Result := Path else Result := GetFullPath(Path, True, Check); end; class function TPathHelper.GetDirectoryName(const FileName : TFileName; TrailingPathDelim : Boolean) : String; begin Result := String.Empty; if not String.IsNullOrWhiteSpace(FileName) and TPath.HasValidPathChars(FileName, True) then begin Result := GetDirectoryName(FileName); if TrailingPathDelim then Result := TPath.IncludeTrailingPathDelimiter(Result); end; end; class function TPathHelper.GetExePath : String; begin Result := GetDirectoryName(ParamStr(0), True); end; class function TPathHelper.GetFullPath(Path : String; ExpandVars, Check : Boolean) : String; begin if ExpandVars then Path := ExpandEnvVars(Path); if Check then Result := GetFullPath(Path) else Result := ExpandFileName(Path); end; class function TPathHelper.GetQuotedPath(const Path : String; QuoteChar : Char) : String; begin Result := Path; if QuoteChar <> #0 then begin if not Result.StartsWith(QuoteChar) then Result := QuoteChar + Result; if not Result.EndsWith(QuoteChar) then Result := Result + QuoteChar; end; end; class function TPathHelper.IncludeTrailingPathDelimiter(const Path : String) : String; begin Result := Path; if not Result.IsEmpty then Result := System.SysUtils.IncludeTrailingPathDelimiter(Result); end; class function TPathHelper.IsApplicableFileName(const FileName : TFileName) : Boolean; begin Result := False; if not String.IsNullOrWhiteSpace(FileName) then if TPath.HasValidPathChars(FileName, False) and not TDirectory.Exists(FileName) then Result := TPath.HasValidFileNameChars(TPath.GetFileName(FileName), False); end; { TRttiTypeHelper } function TRttiTypeHelper.GetFullName : String; begin if IsPublicType then Result := QualifiedName else Result := Name; end; function TRttiTypeHelper.GetMethod(MethodAddress : Pointer) : TRttiMethod; var M : TRttiMethod; begin Result := nil; if Assigned(MethodAddress) then for M in GetMethods do if M.CodeAddress = MethodAddress then Exit(M); end; function TRttiTypeHelper.IsArray : Boolean; begin Result := TypeKind.IsArray; end; function TRttiTypeHelper.IsString : Boolean; begin Result := TypeKind.IsString; end; { TTypeInfoHelper } function TTypeInfoHelper.IsArray : Boolean; begin Result := Kind.IsArray; end; function TTypeInfoHelper.IsString : Boolean; begin Result := Kind.IsString; end; { TTypeKindHelper } function TTypeKindHelper.IsArray : Boolean; begin Result := Self in [tkArray, tkDynArray]; end; function TTypeKindHelper.IsString : Boolean; begin Result := Self in [tkString, tkLString, tkWString, tkUString]; end; { TObjectProperties<T> } class procedure TObjectProperties<T>.Copy(Source, Destination : T; const Filter : TObjectPropertyFilter); var Ctx : TRttiContext; InstanceType : TRttiInstanceType; Prop : TRttiProperty; begin Ctx := TRttiContext.Create; try InstanceType := Ctx.GetType(T) as TRttiInstanceType; for Prop in InstanceType.GetProperties do if Prop.IsReadable and Prop.IsWritable then begin if Assigned(Filter) then if not Filter(Source, Prop) then Continue; Prop.SetValue(TObject(Destination), Prop.GetValue(TObject(Source))); end; finally Ctx.Free; end; end; { TVarRecHelper } function TVarRecHelper.ToString : String; begin case VType of vtChar: Result := Char(AnsiChar(VChar)); vtPChar: Result := String(AnsiString(PAnsiChar(VPChar))); vtPWideChar: Result := WideString(PWideChar(VPWideChar)); vtString: Result := String(VString^); vtAnsiString: Result := String(AnsiString(VAnsiString)); vtWideString: Result := WideString(VWideString); vtUnicodeString: Result := UnicodeString(VUnicodeString); else Result := TValue.FromVarRec(Self).ToString; end; end; end.
unit LLVM.Imports.Comdat; //based on Comdat.h {$MINENUMSIZE 4} interface uses LLVM.Imports , LLVM.Imports.Types; type TLLVMComdatSelectionKind = ( LLVMAnyComdatSelectionKind, ///< The linker may choose any COMDAT. LLVMExactMatchComdatSelectionKind, ///< The data referenced by the COMDAT must be the same. LLVMLargestComdatSelectionKind, ///< The linker will choose the largest COMDAT. LLVMNoDuplicatesComdatSelectionKind, ///< No other Module may specify this COMDAT. LLVMSameSizeComdatSelectionKind ///< The data referenced by the COMDAT must be the same size. ); (** * Return the Comdat in the module with the specified name. It is created * if it didn't already exist. * * @see llvm::Module::getOrInsertComdat() *) function LLVMGetOrInsertComdat(M: TLLVMModuleRef; const Name: PLLVMChar): TLLVMComdatRef;cdecl; external CLLVMLibrary; (** * Get the Comdat assigned to the given global object. * * @see llvm::GlobalObject::getComdat() *) function LLVMGetComdat(V: TLLVMValueRef): TLLVMComdatRef; cdecl; external CLLVMLibrary; (* * Assign the Comdat to the given global object. * * @see llvm::GlobalObject::setComdat() *) procedure LLVMSetComdat(V: TLLVMValueRef; C: TLLVMComdatRef); cdecl; external CLLVMLibrary; (* * Get the conflict resolution selection kind for the Comdat. * * @see llvm::Comdat::getSelectionKind() *) function LLVMGetComdatSelectionKind(C: TLLVMComdatRef): TLLVMComdatSelectionKind; cdecl; external CLLVMLibrary; (* * Set the conflict resolution selection kind for the Comdat. * * @see llvm::Comdat::setSelectionKind() *) procedure LLVMSetComdatSelectionKind(C: TLLVMComdatRef; Kind: TLLVMComdatSelectionKind);cdecl; external CLLVMLibrary; implementation end.
// // Copyright (c) 2009-2010 Mikko Mononen memon@inside.org // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // {$POINTERMATH ON} unit RN_DetourCommon; interface procedure dtSwap(var a,b: Single); overload; procedure dtSwap(var a,b: Word); overload; procedure dtSwap(var a,b: Integer); overload; procedure dtSwap(var a,b: Pointer); overload; procedure dtSwap(var a,b: PSingle); overload; function dtMin(a,b: Single): Single; overload; function dtMin(a,b: Integer): Integer; overload; function dtMin(a,b: Cardinal): Cardinal; overload; function dtMax(a,b: Single): Single; overload; function dtMax(a,b: Integer): Integer; overload; function dtMax(a,b: Cardinal): Cardinal; overload; function dtClamp(v, mn, mx: Single): Single; overload; function dtClamp(v, mn, mx: Integer): Integer; overload; procedure dtVcross(dest: PSingle; v1, v2: PSingle); function dtVdot(v1, v2: PSingle): Single; procedure dtVmad(dest: PSingle; v1, v2: PSingle; s: Single); procedure dtVlerp(dest: PSingle; v1, v2: PSingle; t: Single); procedure dtVadd(dest: PSingle; v1, v2: PSingle); procedure dtVsub(dest: PSingle; v1, v2: PSingle); procedure dtVmin(mn: PSingle; v: PSingle); procedure dtVmax(mx: PSingle; v: PSingle); procedure dtVscale(dest: PSingle; v: PSingle; t: Single); procedure dtVset(dest: PSingle; x,y,z: Single); procedure dtVcopy(dest: PSingle; a: PSingle); function dtVlen(v: PSingle): Single; function dtVlenSqr(v: PSingle): Single; function dtVdist(v1, v2: PSingle): Single; function dtVdistSqr(v1, v2: PSingle): Single; function dtVdist2D(v1, v2: PSingle): Single; function dtVdist2DSqr(v1, v2: PSingle): Single; procedure dtVnormalize(v: PSingle); function dtVequal(p0, p1: PSingle): Boolean; function dtVdot2D(u, v: PSingle): Single; function dtVperp2D(u, v: PSingle): Single; function dtTriArea2D(a, b, c: PSingle): Single; function dtOverlapQuantBounds(amin, amax, bmin, bmax: PWord): Boolean; function dtOverlapBounds(amin, amax, bmin, bmax: PSingle): Boolean; procedure dtClosestPtPointTriangle(closest, p, a, b, c: PSingle); function dtClosestHeightPointTriangle(p, a, b, c: PSingle; h: PSingle): Boolean; function dtIntersectSegmentPoly2D(p0, p1: PSingle; verts: PSingle; nverts: Integer; tmin, tmax: PSingle; segMin, segMax: PInteger): Boolean; function dtIntersectSegSeg2D(ap, aq, bp, bq: PSingle; s, t: PSingle): Boolean; function dtPointInPolygon(pt, verts: PSingle; nverts: Integer): Boolean; function dtDistancePtPolyEdgesSqr(pt, verts: PSingle; nverts: Integer; ed, et: PSingle): Boolean; function dtDistancePtSegSqr2D(pt, p, q: PSingle; t: PSingle): Single; procedure dtCalcPolyCenter(tc: PSingle; const idx: PWord; nidx: Integer; verts: PSingle); function dtOverlapPolyPoly2D(polya: PSingle; npolya: Integer; polyb: PSingle; npolyb: Integer): Boolean; function dtNextPow2(v: Cardinal): Cardinal; function dtIlog2(v: Cardinal): Cardinal; function dtAlign4(x: Integer): Integer; function dtOppositeTile(side: Integer): Integer; procedure dtSwapByte(a, b: PByte); procedure dtSwapEndian(v: PWord); overload; procedure dtSwapEndian(v: PShortInt); overload; procedure dtSwapEndian(v: PCardinal); overload; procedure dtSwapEndian(v: PInteger); overload; procedure dtSwapEndian(v: PSingle); overload; procedure dtRandomPointInConvexPoly(pts: PSingle; npts: Integer; areas: PSingle; s, t: Single; &out: PSingle); implementation uses Math, SysUtils; (* @defgroup detour Detour Members in this module are used to create, manipulate, and query navigation meshes. @note This is a summary list of members. Use the index or search feature to find minor members. *) /// @name General helper functions /// @{ /// Used to ignore a function parameter. VS complains about unused parameters /// and this silences the warning. /// @param [in] _ Unused parameter //template<class T> void dtIgnoreUnused(const T&) { } /// Swaps the values of the two parameters. /// @param[in,out] a Value A /// @param[in,out] b Value B procedure dtSwap(var a,b: Single); var T: Single; begin T := a; a := b; b := T; end; procedure dtSwap(var a,b: Word); var T: Word; begin T := a; a := b; b := T; end; procedure dtSwap(var a,b: Integer); var T: Integer; begin T := a; a := b; b := T; end; procedure dtSwap(var a,b: Pointer); var T: Pointer; begin T := a; a := b; b := T; end; procedure dtSwap(var a,b: PSingle); var T: PSingle; begin T := a; a := b; b := T; end; /// Returns the minimum of two values. /// @param[in] a Value A /// @param[in] b Value B /// @return The minimum of the two values. function dtMin(a,b: Single): Single; begin Result := Min(a,b); end; function dtMin(a,b: Integer): Integer; begin Result := Min(a,b); end; function dtMin(a,b: Cardinal): Cardinal; begin Result := Min(a,b); end; /// Returns the maximum of two values. /// @param[in] a Value A /// @param[in] b Value B /// @return The maximum of the two values. function dtMax(a,b: Single): Single; begin Result := Max(a,b); end; function dtMax(a,b: Integer): Integer; begin Result := Max(a,b); end; function dtMax(a,b: Cardinal): Cardinal; begin Result := Max(a,b); end; /// Returns the absolute value. /// @param[in] a The value. /// @return The absolute value of the specified value. //template<class T> inline T dtAbs(T a) { return a < 0 ? -a : a; } /// Returns the square of the value. /// @param[in] a The value. /// @return The square of the value. function dtSqr(a: Single): Single; begin Result := a*a; end; /// Clamps the value to the specified range. /// @param[in] v The value to clamp. /// @param[in] mn The minimum permitted return value. /// @param[in] mx The maximum permitted return value. /// @return The value, clamped to the specified range. function dtClamp(v, mn, mx: Single): Single; begin Result := EnsureRange(v, mn, mx); end; function dtClamp(v, mn, mx: Integer): Integer; begin Result := EnsureRange(v, mn, mx); end; /// Returns the square root of the value. /// @param[in] x The value. /// @return The square root of the vlaue. //float dtSqrt(float x); /// @} /// @name Vector helper functions. /// @{ /// Derives the cross product of two vectors. (@p v1 x @p v2) /// @param[out] dest The cross product. [(x, y, z)] /// @param[in] v1 A Vector [(x, y, z)] /// @param[in] v2 A vector [(x, y, z)] procedure dtVcross(dest: PSingle; v1, v2: PSingle); begin dest[0] := v1[1]*v2[2] - v1[2]*v2[1]; dest[1] := v1[2]*v2[0] - v1[0]*v2[2]; dest[2] := v1[0]*v2[1] - v1[1]*v2[0]; end; /// Derives the dot product of two vectors. (@p v1 . @p v2) /// @param[in] v1 A Vector [(x, y, z)] /// @param[in] v2 A vector [(x, y, z)] /// @return The dot product. function dtVdot(v1, v2: PSingle): Single; begin Result := v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2]; end; /// Performs a scaled vector addition. (@p v1 + (@p v2 * @p s)) /// @param[out] dest The result vector. [(x, y, z)] /// @param[in] v1 The base vector. [(x, y, z)] /// @param[in] v2 The vector to scale and add to @p v1. [(x, y, z)] /// @param[in] s The amount to scale @p v2 by before adding to @p v1. procedure dtVmad(dest: PSingle; v1, v2: PSingle; s: Single); begin dest[0] := v1[0]+v2[0]*s; dest[1] := v1[1]+v2[1]*s; dest[2] := v1[2]+v2[2]*s; end; /// Performs a linear interpolation between two vectors. (@p v1 toward @p v2) /// @param[out] dest The result vector. [(x, y, x)] /// @param[in] v1 The starting vector. /// @param[in] v2 The destination vector. /// @param[in] t The interpolation factor. [Limits: 0 <= value <= 1.0] procedure dtVlerp(dest: PSingle; v1, v2: PSingle; t: Single); begin dest[0] := v1[0]+(v2[0]-v1[0])*t; dest[1] := v1[1]+(v2[1]-v1[1])*t; dest[2] := v1[2]+(v2[2]-v1[2])*t; end; /// Performs a vector addition. (@p v1 + @p v2) /// @param[out] dest The result vector. [(x, y, z)] /// @param[in] v1 The base vector. [(x, y, z)] /// @param[in] v2 The vector to add to @p v1. [(x, y, z)] procedure dtVadd(dest: PSingle; v1, v2: PSingle); begin dest[0] := v1[0]+v2[0]; dest[1] := v1[1]+v2[1]; dest[2] := v1[2]+v2[2]; end; /// Performs a vector subtraction. (@p v1 - @p v2) /// @param[out] dest The result vector. [(x, y, z)] /// @param[in] v1 The base vector. [(x, y, z)] /// @param[in] v2 The vector to subtract from @p v1. [(x, y, z)] procedure dtVsub(dest: PSingle; v1, v2: PSingle); begin dest[0] := v1[0]-v2[0]; dest[1] := v1[1]-v2[1]; dest[2] := v1[2]-v2[2]; end; /// Selects the minimum value of each element from the specified vectors. /// @param[in,out] mn A vector. (Will be updated with the result.) [(x, y, z)] /// @param[in] v A vector. [(x, y, z)] procedure dtVmin(mn: PSingle; v: PSingle); begin mn[0] := dtMin(mn[0], v[0]); mn[1] := dtMin(mn[1], v[1]); mn[2] := dtMin(mn[2], v[2]); end; /// Selects the maximum value of each element from the specified vectors. /// @param[in,out] mx A vector. (Will be updated with the result.) [(x, y, z)] /// @param[in] v A vector. [(x, y, z)] procedure dtVmax(mx: PSingle; v: PSingle); begin mx[0] := dtMax(mx[0], v[0]); mx[1] := dtMax(mx[1], v[1]); mx[2] := dtMax(mx[2], v[2]); end; /// Scales the vector by the specified value. (@p v * @p t) /// @param[out] dest The result vector. [(x, y, z)] /// @param[in] v The vector to scale. [(x, y, z)] /// @param[in] t The scaling factor. procedure dtVscale(dest: PSingle; v: PSingle; t: Single); begin dest[0] := v[0]*t; dest[1] := v[1]*t; dest[2] := v[2]*t; end; /// Sets the vector elements to the specified values. /// @param[out] dest The result vector. [(x, y, z)] /// @param[in] x The x-value of the vector. /// @param[in] y The y-value of the vector. /// @param[in] z The z-value of the vector. procedure dtVset(dest: PSingle; x,y,z: Single); begin dest[0] := x; dest[1] := y; dest[2] := z; end; /// Performs a vector copy. /// @param[out] dest The result. [(x, y, z)] /// @param[in] a The vector to copy. [(x, y, z)] procedure dtVcopy(dest: PSingle; a: PSingle); begin dest[0] := a[0]; dest[1] := a[1]; dest[2] := a[2]; end; /// Derives the scalar length of the vector. /// @param[in] v The vector. [(x, y, z)] /// @return The scalar length of the vector. function dtVlen(v: PSingle): Single; begin Result := Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); end; /// Derives the square of the scalar length of the vector. (len * len) /// @param[in] v The vector. [(x, y, z)] /// @return The square of the scalar length of the vector. function dtVlenSqr(v: PSingle): Single; begin Result := v[0]*v[0] + v[1]*v[1] + v[2]*v[2]; end; /// Returns the distance between two points. /// @param[in] v1 A point. [(x, y, z)] /// @param[in] v2 A point. [(x, y, z)] /// @return The distance between the two points. function dtVdist(v1, v2: PSingle): Single; var dx,dy,dz: Single; begin dx := v2[0] - v1[0]; dy := v2[1] - v1[1]; dz := v2[2] - v1[2]; Result := Sqrt(dx*dx + dy*dy + dz*dz); end; /// Returns the square of the distance between two points. /// @param[in] v1 A point. [(x, y, z)] /// @param[in] v2 A point. [(x, y, z)] /// @return The square of the distance between the two points. function dtVdistSqr(v1, v2: PSingle): Single; var dx,dy,dz: Single; begin dx := v2[0] - v1[0]; dy := v2[1] - v1[1]; dz := v2[2] - v1[2]; Result := dx*dx + dy*dy + dz*dz; end; /// Derives the distance between the specified points on the xz-plane. /// @param[in] v1 A point. [(x, y, z)] /// @param[in] v2 A point. [(x, y, z)] /// @return The distance between the point on the xz-plane. /// /// The vectors are projected onto the xz-plane, so the y-values are ignored. function dtVdist2D(v1, v2: PSingle): Single; var dx,dz: Single; begin dx := v2[0] - v1[0]; dz := v2[2] - v1[2]; Result := Sqrt(dx*dx + dz*dz); end; /// Derives the square of the distance between the specified points on the xz-plane. /// @param[in] v1 A point. [(x, y, z)] /// @param[in] v2 A point. [(x, y, z)] /// @return The square of the distance between the point on the xz-plane. function dtVdist2DSqr(v1, v2: PSingle): Single; var dx,dz: Single; begin dx := v2[0] - v1[0]; dz := v2[2] - v1[2]; Result := dx*dx + dz*dz; end; /// Normalizes the vector. /// @param[in,out] v The vector to normalize. [(x, y, z)] procedure dtVnormalize(v: PSingle); var d: Single; begin d := 1.0 / Sqrt(Sqr(v[0]) + Sqr(v[1]) + Sqr(v[2])); v[0] := v[0] * d; v[1] := v[1] * d; v[2] := v[2] * d; end; /// Performs a 'sloppy' colocation check of the specified points. /// @param[in] p0 A point. [(x, y, z)] /// @param[in] p1 A point. [(x, y, z)] /// @return True if the points are considered to be at the same location. /// /// Basically, this function will return true if the specified points are /// close enough to eachother to be considered colocated. function dtVequal(p0, p1: PSingle): Boolean; var thr,d: Single; begin thr := dtSqr(1.0/16384.0); d := dtVdistSqr(p0, p1); Result := d < thr; end; /// Derives the dot product of two vectors on the xz-plane. (@p u . @p v) /// @param[in] u A vector [(x, y, z)] /// @param[in] v A vector [(x, y, z)] /// @return The dot product on the xz-plane. /// /// The vectors are projected onto the xz-plane, so the y-values are ignored. function dtVdot2D(u, v: PSingle): Single; begin Result := u[0]*v[0] + u[2]*v[2]; end; /// Derives the xz-plane 2D perp product of the two vectors. (uz*vx - ux*vz) /// @param[in] u The LHV vector [(x, y, z)] /// @param[in] v The RHV vector [(x, y, z)] /// @return The dot product on the xz-plane. /// /// The vectors are projected onto the xz-plane, so the y-values are ignored. function dtVperp2D(u, v: PSingle): Single; begin Result := u[2]*v[0] - u[0]*v[2]; end; /// @} /// @name Computational geometry helper functions. /// @{ /// Derives the signed xz-plane area of the triangle ABC, or the relationship of line AB to point C. /// @param[in] a Vertex A. [(x, y, z)] /// @param[in] b Vertex B. [(x, y, z)] /// @param[in] c Vertex C. [(x, y, z)] /// @return The signed xz-plane area of the triangle. function dtTriArea2D(a, b, c: PSingle): Single; var abx, abz, acx, acz: Single; begin abx := b[0] - a[0]; abz := b[2] - a[2]; acx := c[0] - a[0]; acz := c[2] - a[2]; Result := acx*abz - abx*acz; end; /// Determines if two axis-aligned bounding boxes overlap. /// @param[in] amin Minimum bounds of box A. [(x, y, z)] /// @param[in] amax Maximum bounds of box A. [(x, y, z)] /// @param[in] bmin Minimum bounds of box B. [(x, y, z)] /// @param[in] bmax Maximum bounds of box B. [(x, y, z)] /// @return True if the two AABB's overlap. /// @see dtOverlapBounds function dtOverlapQuantBounds(amin, amax, bmin, bmax: PWord): Boolean; var overlap: Boolean; begin overlap := true; overlap := overlap and not ((amin[0] > bmax[0]) or (amax[0] < bmin[0])); overlap := overlap and not ((amin[1] > bmax[1]) or (amax[1] < bmin[1])); overlap := overlap and not ((amin[2] > bmax[2]) or (amax[2] < bmin[2])); Result := overlap; end; /// Determines if two axis-aligned bounding boxes overlap. /// @param[in] amin Minimum bounds of box A. [(x, y, z)] /// @param[in] amax Maximum bounds of box A. [(x, y, z)] /// @param[in] bmin Minimum bounds of box B. [(x, y, z)] /// @param[in] bmax Maximum bounds of box B. [(x, y, z)] /// @return True if the two AABB's overlap. /// @see dtOverlapQuantBounds function dtOverlapBounds(amin, amax, bmin, bmax: PSingle): Boolean; var overlap: Boolean; begin overlap := true; overlap := overlap and not ((amin[0] > bmax[0]) or (amax[0] < bmin[0])); overlap := overlap and not ((amin[1] > bmax[1]) or (amax[1] < bmin[1])); overlap := overlap and not ((amin[2] > bmax[2]) or (amax[2] < bmin[2])); Result := overlap; end; /// Derives the closest point on a triangle from the specified reference point. /// @param[out] closest The closest point on the triangle. /// @param[in] p The reference point from which to test. [(x, y, z)] /// @param[in] a Vertex A of triangle ABC. [(x, y, z)] /// @param[in] b Vertex B of triangle ABC. [(x, y, z)] /// @param[in] c Vertex C of triangle ABC. [(x, y, z)] //procedure dtClosestPtPointTriangle(closest, p, a, b, c: PSingle); /// Derives the y-axis height of the closest point on the triangle from the specified reference point. /// @param[in] p The reference point from which to test. [(x, y, z)] /// @param[in] a Vertex A of triangle ABC. [(x, y, z)] /// @param[in] b Vertex B of triangle ABC. [(x, y, z)] /// @param[in] c Vertex C of triangle ABC. [(x, y, z)] /// @param[out] h The resulting height. //function dtClosestHeightPointTriangle(p, a, b, c: PSingle; h: PSingle): Boolean; //function dtIntersectSegmentPoly2D(p0, p1: PSingle; verts: PSingle; nverts: Integer; tmin, tmax: PSingle; segMin, segMax: PInteger): Boolean; //function dtIntersectSegSeg2D(ap, aq, bp, bq: PSingle; s, t: PSingle): Boolean; /// Determines if the specified point is inside the convex polygon on the xz-plane. /// @param[in] pt The point to check. [(x, y, z)] /// @param[in] verts The polygon vertices. [(x, y, z) * @p nverts] /// @param[in] nverts The number of vertices. [Limit: >= 3] /// @return True if the point is inside the polygon. //function dtPointInPolygon(pt, verts: PSingle; nverts: Integer): Boolean; //function dtDistancePtPolyEdgesSqr(pt, verts: PSingle; nverts: Integer; ed, et: PSingle): Boolean; //function dtDistancePtSegSqr2D(pt, p, q: PSingle; t: PSingle): Single; /// Derives the centroid of a convex polygon. /// @param[out] tc The centroid of the polgyon. [(x, y, z)] /// @param[in] idx The polygon indices. [(vertIndex) * @p nidx] /// @param[in] nidx The number of indices in the polygon. [Limit: >= 3] /// @param[in] verts The polygon vertices. [(x, y, z) * vertCount] //procedure dtCalcPolyCenter(tc: PSingle; const idx: PWord; nidx: Integer; verts: PSingle); /// Determines if the two convex polygons overlap on the xz-plane. /// @param[in] polya Polygon A vertices. [(x, y, z) * @p npolya] /// @param[in] npolya The number of vertices in polygon A. /// @param[in] polyb Polygon B vertices. [(x, y, z) * @p npolyb] /// @param[in] npolyb The number of vertices in polygon B. /// @return True if the two polygons overlap. //function dtOverlapPolyPoly2D(polya: PSingle; npolya: Integer; polyb: PSingle; npolyb: Integer): Boolean; /// @} /// @name Miscellanious functions. /// @{ function dtNextPow2(v: Cardinal): Cardinal; begin if v > 0 then begin Dec(v); v := v or (v shr 1); v := v or (v shr 2); v := v or (v shr 4); v := v or (v shr 8); v := v or (v shr 16); Inc(v); end; Result := v; end; { unsigned int r; unsigned int shift; r = (v > 0xffff) << 4; v >>= r; shift = (v > 0xff) << 3; v >>= shift; r |= shift; shift = (v > 0xf) << 2; v >>= shift; r |= shift; shift = (v > 0x3) << 1; v >>= shift; r |= shift; r |= (v >> 1); return r; } function dtIlog2(v: Cardinal): Cardinal; var r, shift: Cardinal; begin r := Byte(v > $ffff) shl 4; v := v shr r; shift := Byte(v > $ff) shl 3; v := v shr shift; r := r or shift; shift := Byte(v > $f) shl 2; v := v shr shift; r := r or shift; shift := Byte(v > $3) shl 1; v := v shr shift; r := r or shift; r := r or Byte(v shr 1); Result := r; end; function dtAlign4(x: Integer): Integer; begin Result := (x+3) and not 3; end; function dtOppositeTile(side: Integer): Integer; begin Result := (side+4) and $7; end; procedure dtSwapByte(a, b: PByte); var tmp: Byte; begin tmp := a^; a^ := b^; b^ := tmp; end; procedure dtSwapEndian(v: PWord); var x: PByte; begin x := PByte(v); dtSwapByte(x+0, x+1); end; procedure dtSwapEndian(v: PShortInt); var x: PByte; begin x := PByte(v); dtSwapByte(x+0, x+1); end; procedure dtSwapEndian(v: PCardinal); var x: PByte; begin x := PByte(v); dtSwapByte(x+0, x+3); dtSwapByte(x+1, x+2); end; procedure dtSwapEndian(v: PInteger); var x: PByte; begin x := PByte(v); dtSwapByte(x+0, x+3); dtSwapByte(x+1, x+2); end; procedure dtSwapEndian(v: PSingle); var x: PByte; begin x := PByte(v); dtSwapByte(x+0, x+3); dtSwapByte(x+1, x+2); end; /// @} //#endif // DETOURCOMMON_H /////////////////////////////////////////////////////////////////////////// // This section contains detailed documentation for members that don't have // a source file. It reduces clutter in the main section of the header. (** @fn float dtTriArea2D(const float* a, const float* b, const float* c) @par The vertices are projected onto the xz-plane, so the y-values are ignored. This is a low cost function than can be used for various purposes. Its main purpose is for point/line relationship testing. In all cases: A value of zero indicates that all vertices are collinear or represent the same point. (On the xz-plane.) When used for point/line relationship tests, AB usually represents a line against which the C point is to be tested. In this case: A positive value indicates that point C is to the left of line AB, looking from A toward B.<br/> A negative value indicates that point C is to the right of lineAB, looking from A toward B. When used for evaluating a triangle: The absolute value of the return value is two times the area of the triangle when it is projected onto the xz-plane. A positive return value indicates: <ul> <li>The vertices are wrapped in the normal Detour wrap direction.</li> <li>The triangle's 3D face normal is in the general up direction.</li> </ul> A negative return value indicates: <ul> <li>The vertices are reverse wrapped. (Wrapped opposite the normal Detour wrap direction.)</li> <li>The triangle's 3D face normal is in the general down direction.</li> </ul> *) ////////////////////////////////////////////////////////////////////////////////////////// procedure dtClosestPtPointTriangle(closest, p, a, b, c: PSingle); var ab,ac,ap,bp,cp: array [0..2] of Single; d1,d2,d3,d4,vc,v,d5,d6,vb,w,va,denom: Single; begin // Check if P in vertex region outside A dtVsub(@ab[0], b, a); dtVsub(@ac[0], c, a); dtVsub(@ap[0], p, a); d1 := dtVdot(@ab[0], @ap[0]); d2 := dtVdot(@ac[0], @ap[0]); if (d1 <= 0.0) and (d2 <= 0.0) then begin // barycentric coordinates (1,0,0) dtVcopy(closest, a); Exit; end; // Check if P in vertex region outside B dtVsub(@bp[0], p, b); d3 := dtVdot(@ab[0], @bp[0]); d4 := dtVdot(@ac[0], @bp[0]); if (d3 >= 0.0) and (d4 <= d3) then begin // barycentric coordinates (0,1,0) dtVcopy(closest, b); Exit; end; // Check if P in edge region of AB, if so return projection of P onto AB vc := d1*d4 - d3*d2; if (vc <= 0.0) and (d1 >= 0.0) and (d3 <= 0.0) then begin // barycentric coordinates (1-v,v,0) v := d1 / (d1 - d3); closest[0] := a[0] + v * ab[0]; closest[1] := a[1] + v * ab[1]; closest[2] := a[2] + v * ab[2]; Exit; end; // Check if P in vertex region outside C dtVsub(@cp[0], p, c); d5 := dtVdot(@ab[0], @cp[0]); d6 := dtVdot(@ac[0], @cp[0]); if (d6 >= 0.0) and (d5 <= d6) then begin // barycentric coordinates (0,0,1) dtVcopy(closest, c); Exit; end; // Check if P in edge region of AC, if so return projection of P onto AC vb := d5*d2 - d1*d6; if (vb <= 0.0) and (d2 >= 0.0) and (d6 <= 0.0) then begin // barycentric coordinates (1-w,0,w) w := d2 / (d2 - d6); closest[0] := a[0] + w * ac[0]; closest[1] := a[1] + w * ac[1]; closest[2] := a[2] + w * ac[2]; Exit; end; // Check if P in edge region of BC, if so return projection of P onto BC va := d3*d6 - d5*d4; if (va <= 0.0) and ((d4 - d3) >= 0.0) and ((d5 - d6) >= 0.0) then begin // barycentric coordinates (0,1-w,w) w := (d4 - d3) / ((d4 - d3) + (d5 - d6)); closest[0] := b[0] + w * (c[0] - b[0]); closest[1] := b[1] + w * (c[1] - b[1]); closest[2] := b[2] + w * (c[2] - b[2]); Exit; end; // P inside face region. Compute Q through its barycentric coordinates (u,v,w) denom := 1.0 / (va + vb + vc); v := vb * denom; w := vc * denom; closest[0] := a[0] + ab[0] * v + ac[0] * w; closest[1] := a[1] + ab[1] * v + ac[1] * w; closest[2] := a[2] + ab[2] * v + ac[2] * w; end; function dtIntersectSegmentPoly2D(p0, p1: PSingle; verts: PSingle; nverts: Integer; tmin, tmax: PSingle; segMin, segMax: PInteger): Boolean; const EPS = 0.00000001; var dir,edge,diff: array [0..2] of Single; i,j: Integer; n,d,t: Single; begin tmin^ := 0; tmax^ := 1; segMin^ := -1; segMax^ := -1; dtVsub(@dir[0], p1, p0); i := 0; j := nverts-1; while (i < nverts) do begin dtVsub(@edge[0], @verts[i*3], @verts[j*3]); dtVsub(@diff[0], p0, @verts[j*3]); n := dtVperp2D(@edge[0], @diff[0]); d := dtVperp2D(@dir[0], @edge[0]); if (Abs(d) < EPS) then begin // S is nearly parallel to this edge if (n < 0) then Exit(false) else begin j:=i; Inc(i); continue; end; end; t := n / d; if (d < 0) then begin // segment S is entering across this edge if (t > tmin^) then begin tmin^ := t; segMin^ := j; // S enters after leaving polygon if (tmin^ > tmax^) then Exit(false); end; end else begin // segment S is leaving across this edge if (t < tmax^) then begin tmax^ := t; segMax^ := j; // S leaves before entering polygon if (tmax^ < tmin^) then Exit(false); end; end; j := i; Inc(i); end; Result := true; end; function dtDistancePtSegSqr2D(pt, p, q: PSingle; t: PSingle): Single; var pqx,pqz,dx,dz,d: Single; begin pqx := q[0] - p[0]; pqz := q[2] - p[2]; dx := pt[0] - p[0]; dz := pt[2] - p[2]; d := pqx*pqx + pqz*pqz; t^ := pqx*dx + pqz*dz; if (d > 0) then t^ := t^ / d; if (t^ < 0) then t^ := 0 else if (t^ > 1) then t^ := 1; dx := p[0] + t^*pqx - pt[0]; dz := p[2] + t^*pqz - pt[2]; Result := dx*dx + dz*dz; end; procedure dtCalcPolyCenter(tc: PSingle; const idx: PWord; nidx: Integer; verts: PSingle); var j: Integer; v: PSingle; s: Single; begin tc[0] := 0.0; tc[1] := 0.0; tc[2] := 0.0; for j := 0 to nidx - 1 do begin v := @verts[idx[j]*3]; tc[0] := tc[0] + v[0]; tc[1] := tc[1] + v[1]; tc[2] := tc[2] + v[2]; end; s := 1.0 / nidx; tc[0] := tc[0] * s; tc[1] := tc[1] * s; tc[2] := tc[2] * s; end; function dtClosestHeightPointTriangle(p, a, b, c: PSingle; h: PSingle): Boolean; const EPS = 0.0001; var v0,v1,v2: array [0..2] of Single; dot00,dot01,dot02,dot11,dot12: Single; invDenom,u,v: Single; begin dtVsub(@v0[0], c,a); dtVsub(@v1[0], b,a); dtVsub(@v2[0], p,a); dot00 := dtVdot2D(@v0[0], @v0[0]); dot01 := dtVdot2D(@v0[0], @v1[0]); dot02 := dtVdot2D(@v0[0], @v2[0]); dot11 := dtVdot2D(@v1[0], @v1[0]); dot12 := dtVdot2D(@v1[0], @v2[0]); // Compute barycentric coordinates invDenom := 1.0 / (dot00 * dot11 - dot01 * dot01); u := (dot11 * dot02 - dot01 * dot12) * invDenom; v := (dot00 * dot12 - dot01 * dot02) * invDenom; // The (sloppy) epsilon is needed to allow to get height of points which // are interpolated along the edges of the triangles. //static const float EPS := 1e-4f; // If point lies inside the triangle, return interpolated ycoord. if (u >= -EPS) and (v >= -EPS) and ((u+v) <= 1+EPS) then begin h^ := a[1] + v0[1]*u + v1[1]*v; Exit(true); end; Result := false; end; /// @par /// /// All points are projected onto the xz-plane, so the y-values are ignored. function dtPointInPolygon(pt, verts: PSingle; nverts: Integer): Boolean; var i,j: Integer; c: Boolean; vi,vj: PSingle; begin // TODO: Replace pnpoly with triArea2D tests? c := false; i := 0; j := nverts-1; while (i < nverts) do begin vi := @verts[i*3]; vj := @verts[j*3]; if (((vi[2] > pt[2]) <> (vj[2] > pt[2])) and (pt[0] < (vj[0]-vi[0]) * (pt[2]-vi[2]) / (vj[2]-vi[2]) + vi[0]) ) then c := not c; j := i; Inc(i); end; Result := c; end; function dtDistancePtPolyEdgesSqr(pt, verts: PSingle; nverts: Integer; ed, et: PSingle): Boolean; var i,j: Integer; c: Boolean; vi,vj: PSingle; begin // TODO: Replace pnpoly with triArea2D tests? c := false; i := 0; j := nverts-1; while (i < nverts) do begin vi := @verts[i*3]; vj := @verts[j*3]; if (((vi[2] > pt[2]) <> (vj[2] > pt[2])) and (pt[0] < (vj[0]-vi[0]) * (pt[2]-vi[2]) / (vj[2]-vi[2]) + vi[0]) ) then c := not c; ed[j] := dtDistancePtSegSqr2D(pt, vj, vi, @et[j]); j := i; Inc(i); end; Result := c; end; procedure projectPoly(axis, poly: PSingle; npoly: Integer; rmin, rmax: PSingle); var i: Integer; d: Single; begin rmin^ := dtVdot2D(axis, @poly[0]); rmax^ := dtVdot2D(axis, @poly[0]); for i := 1 to npoly - 1 do begin d := dtVdot2D(axis, @poly[i*3]); rmin^ := dtMin(rmin^, d); rmax^ := dtMax(rmax^, d); end; end; function overlapRange(amin, amax, bmin, bmax, eps: Single): Boolean; begin Result := not (((amin+eps) > bmax) or ((amax-eps) < bmin)); end; /// @par /// /// All vertices are projected onto the xz-plane, so the y-values are ignored. function dtOverlapPolyPoly2D(polya: PSingle; npolya: Integer; polyb: PSingle; npolyb: Integer): Boolean; const EPS = 0.0001; var i,j: Integer; va,vb: PSingle; n: array [0..2] of Single; amin,amax,bmin,bmax: Single; begin i := 0; j := npolya-1; while i < npolya do begin va := @polya[j*3]; vb := @polya[i*3]; n[0] := vb[2]-va[2]; n[1] := 0; n[2] := -(vb[0]-va[0]); projectPoly(@n[0], polya, npolya, @amin, @amax); projectPoly(@n[0], polyb, npolyb, @bmin, @bmax); if (not overlapRange(amin, amax, bmin, bmax, eps)) then begin // Found separating axis Exit(false); end; j := i; Inc(i); end; i := 0; j := npolyb-1; while i < npolyb do begin va := @polyb[j*3]; vb := @polyb[i*3]; n[0] := vb[2]-va[2]; n[1] := 0; n[2] := -(vb[0]-va[0]); projectPoly(@n[0], polya, npolya, @amin, @amax); projectPoly(@n[0], polyb, npolyb, @bmin, @bmax); if (not overlapRange(amin, amax, bmin, bmax, eps)) then begin // Found separating axis Exit(false); end; j := i; Inc(i); end; Result := true; end; // Returns a random point in a convex polygon. // Adapted from Graphics Gems article. procedure dtRandomPointInConvexPoly(pts: PSingle; npts: Integer; areas: PSingle; s, t: Single; &out: PSingle); var areasum,thr,acc,u,dacc,v,a,b,c: Single; i,tri: Integer; pa,pb,pc: PSingle; begin // Calc triangle araes areasum := 0.0; for i := 2 to npts - 1 do begin areas[i] := dtTriArea2D(@pts[0], @pts[(i-1)*3], @pts[i*3]); areasum := areasum + dtMax(0.001, areas[i]); end; // Find sub triangle weighted by area. thr := s*areasum; acc := 0.0; u := 0.0; tri := 0; for i := 2 to npts - 1 do begin dacc := areas[i]; if (thr >= acc) and (thr < (acc+dacc)) then begin u := (thr - acc) / dacc; tri := i; break; end; acc := acc + dacc; end; v := Sqrt(t); a := 1 - v; b := (1 - u) * v; c := u * v; pa := @pts[0]; pb := @pts[(tri-1)*3]; pc := @pts[tri*3]; &out[0] := a*pa[0] + b*pb[0] + c*pc[0]; &out[1] := a*pa[1] + b*pb[1] + c*pc[1]; &out[2] := a*pa[2] + b*pb[2] + c*pc[2]; end; function vperpXZ(a, b: PSingle): Single; begin Result := a[0]*b[2] - a[2]*b[0]; end; function dtIntersectSegSeg2D(ap, aq, bp, bq: PSingle; s, t: PSingle): Boolean; var u,v,w: array [0..2] of Single; d: Single; begin dtVsub(@u[0],aq,ap); dtVsub(@v[0],bq,bp); dtVsub(@w[0],ap,bp); d := vperpXZ(@u[0],@v[0]); if (Abs(d) < 0.000001) then Exit(false); s^ := vperpXZ(@v[0],@w[0]) / d; t^ := vperpXZ(@u[0],@w[0]) / d; Result := true; end; end.
{$mode objfpc} program Exam; uses Queue; type QofChars = specialize Queue.TQueueSingle<char>; var sInput : string; var bKeepGoing : boolean; var q : QofChars; var i : integer; var ch : char; var qCount : integer; begin bKeepGoing := true; sInput := ''; WriteLn('Creating the queue.'); q := QofChars.Create; while bKeepGoing do begin ReadLn(sInput); if sInput[1] = 'a' then begin if length(sInput) = 2 then begin q.Enqueue(sInput[2]); WriteLn('character "', sInput[2], '" has been enqueued.'); end else begin WriteLn('user error: inststruction "a*" must consist of exactly two chars'); end; end; if sInput = 'd' then begin if q.GetCount = 0 then begin WriteLn('user error: Cannot dequeue: the queue is already empty'); end else begin ch := q.Dequeue; WriteLn('character "', ch, '" has been dequeued.'); end; end; if sInput = 's' then begin WriteLn('Current queue''s size is ', q.GetCount); end; if sInput = 'i' then begin WriteLn('Iterating through the queue...'); qCount := q.GetCount; for i := 1 to qCount do begin ch := q.Dequeue; WriteLn('> ', ch); q.Enqueue( ch ); end; WriteLn('Complete!'); end; if sInput = 'q' then begin bKeepGoing := false; WriteLn('Quitting. Bye!'); end; end; WriteLn('Destructing the queue.'); q.Free; end.
unit uSQLFormat_Oracle; interface {$I iGlobalConfig.pas} uses uSQLFormat_a, uSQLFormat_c, uAbstractProcessor, uDFDCl, Db; type TSQLFormat_Oracle = class(TSQLFormat_c) public function getVal(AField: TAbstractDataRow; AIdx: integer): string; override; function getEqOp(AMetaField: TMetaField): string; override; function getDDLFieldIdent(AField: PMetaField): string; override; function getDMLFieldIdent(AField: PMetaField): string; override; function getDataTypeString(AType: TFieldType; ASize: integer): string; override; function getSymCommentBegin: string; override; function getSymCommentEnd: string; override; function get1LineComment: string; override; end; implementation uses uWriterConst_h, uDFOracleWriterConst_h, uWriterTypes_h, uOracleTableAccess, uCustomTableAccess, uWriterUtils, uKrnl_r, Ora, uSQLFormatUtil, SysUtils; //---------------------------------------------------------------------------- function TSQLFormat_Oracle.getDataTypeString(AType: TFieldType; ASize: integer): string; begin // no inherited (abstract) if AType = TFieldType(ftXML) then Result := 'XMLTYPE' else case AType of ftString: Result := 'VARCHAR2(' + IntToStr(ASize) + ')'; ftInteger, ftSmallInt, ftAutoInc, ftBoolean: Result := 'NUMBER(' + intToStr(CPrecisionInteger) + ', 0)'; ... ftTimeStamp: Result := 'TIMESTAMP'; else raise EWriterIntern.Fire(self, 'Type not supported'); end; end; //---------------------------------------------------------------------------- function TSQLFormat_Oracle.getSymCommentBegin: string; begin // no inherited (abstract) Result := '/*'; //begin of sql comment line end; //---------------------------------------------------------------------------- function TSQLFormat_Oracle.getSymCommentEnd: string; begin // no inherited (abstract) Result := '*/'; //end of sql comment line end; //---------------------------------------------------------------------------- function TSQLFormat_Oracle.getEqOp(AMetaField: TMetaField): string; begin if (AMetaField.DataType = dtString) and GetStringIsLobField(AMetaField.MaxLength, CMaxLenOraVarchar2) then Result := ' LIKE ' else Result := inherited getEqOp(AMetaField); end; end.
{ GMMapVCL unit ES: incluye el componente para usar el mapa de Google Maps EN: includes the component to use the Google Maps map ========================================================================= History: ver 1.3.0 ES: nuevo: nueva función GetIEVersion en la clase TGMMap EN: new: new function GetIEVersion into TGMMap class. ver 0.1.9 ES: nuevo: documentación nuevo: se hace compatible con FireMonkey EN: new: documentation new: now compatible with FireMonkey ========================================================================= ES: IMPORTANTE PROGRAMADORES: Por favor, si tienes comentarios, mejoras, ampliaciones, errores y/o cualquier otro tipo de sugerencia, envíame un correo a: gmlib@cadetill.com EN: IMPORTANT PROGRAMMERS: please, if you have comments, improvements, enlargements, errors and/or any another type of suggestion, please send me a mail to: gmlib@cadetill.com ========================================================================= Copyright (©) 2012, by Xavier Martinez (cadetill) web http://www.cadetill.com } {*------------------------------------------------------------------------------ The GMMapVCL unit includes the classes that manages the map specialized in a particular browser. This browsers can be a TWebBrowser or TChromium. You can de/activate this browsers into the gmlib.inc file. By default, only the TGMMap (TWebBrowser) is active. HOW TO USE: put the component into a form, link to a browser, activate it and call DoMap method (usually when AfterPageLoaded event is fired with First parameter to True). @author Xavier Martinez (cadetill) @version 1.5.0 -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ La unit GMMapVCL incluye las clases que gestionan el mapa especializados en un determinado navegador. Estos navegadores pueden ser un TWebBrowser o TChromium. Puedes des/activar estos navegadores desde el archivo gmlib.inc. Por defecto, sólo está activo el TGMMap (TWebBrowser). MODO DE USO: poner el componente en el formulario, linkarlo a un navegador, activarlo y ejecutar el método DoMap (usualmente en el evento AfterPageLoaded cuando el parámetro First es True). @author Xavier Martinez (cadetill) @version 1.5.0 -------------------------------------------------------------------------------} unit GMMapVCL; {$DEFINE WEBBROWSER} {.$DEFINE CHROMIUM} {$I ..\gmlib.inc} interface uses {$IFDEF WEBBROWSER} SHDocVw, {$IFDEF DELPHIXE2} Vcl.ExtCtrls, {$ELSE} ExtCtrls, {$ENDIF} {$ENDIF} {$IFDEF CHROMIUM} cefvcl, ceflib, cefgui, {$ENDIF} {$IFDEF DELPHIXE2} System.SysUtils, System.Classes, Vcl.Dialogs, Vcl.Graphics, {$ELSE} SysUtils, Classes, Dialogs, Graphics, {$ENDIF} GMMap, GMFunctionsVCL; type {*------------------------------------------------------------------------------ Internal class containing the visual properties of Google Maps map. This class extends TCustomVisualProp to add BGColor property (into VCL is TColor and into FMX is TAlphaColor). -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Clase interna que contendrá las propiedades visuales de un mapa de Google Maps. Esta clase extiende TCustomVisualProp para añadir la propiedad BGColor (en la VCL es de tipo TColor y en FMX es de tipo TAlphaColor). -------------------------------------------------------------------------------} TVisualProp = class(TCustomVisualProp) private FBGColor: TColor; protected function GetBckgroundColor: string; override; public constructor Create; override; procedure Assign(Source: TPersistent); override; published {*------------------------------------------------------------------------------ Color used for the background of the Map when tiles have not yet loaded. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Color usado de fondo del Mapa cuando los mosaicos aun no han sido cargados. -------------------------------------------------------------------------------} property BGColor: TColor read FBGColor write FBGColor default clSilver; // backgroundColor end; {*------------------------------------------------------------------------------ Base class for classes that want to access the map using VCL. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Clase base para las clases que quieran acceder al mapa mediante VCL. -------------------------------------------------------------------------------} TCustomGMMapVCL = class(TCustomGMMap) private {*------------------------------------------------------------------------------ Visual configuration options. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Opciones de configucación visual. -------------------------------------------------------------------------------} FVisualProp: TVisualProp; // ES: evento de TWebBrowser - EN: event of TWebBrowser // internal variables FTimer: TTimer; // ES: TTimer para el control de eventos - EN: TTimer for events control protected function VisualPropToStr: string; override; procedure SetEnableTimer(State: Boolean); override; procedure SetIntervalTimer(Interval: Integer); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; procedure SaveToJPGFile(FileName: TFileName = ''); override; published property VisualProp: TVisualProp read FVisualProp write FVisualProp; end; {$IFDEF WEBBROWSER} {*------------------------------------------------------------------------------ Class to access to Google Maps map specialized for TWebBrowser browser. See the TCustomGMMap class for properties and events description. More information at https://developers.google.com/maps/documentation/javascript/reference?hl=en#Map -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Clase para el acceso al mapa de Google Maps especializada para el navegador TWebBrowser. Ver la clase TCustomGMMap para la descripción de las propiedades y eventos. Más información en https://developers.google.com/maps/documentation/javascript/reference?hl=en#Map -------------------------------------------------------------------------------} TGMMap = class(TCustomGMMapVCL) private // internal variables CurDispatch: IDispatch; // ES: variable para el control de la carga de la página web - EN: variable for control of load web page OldBeforeNavigate2: TWebBrowserBeforeNavigate2; // ES: evento de TWebBrowser - EN: event of TWebBrowser OldDocumentComplete: TWebBrowserDocumentComplete; // ES: evento de TWebBrowser - EN: event of TWebBrowser OldNavigateComplete2: TWebBrowserNavigateComplete2; // ES: eventos del TWebBrowser para el control de la carga de la página // EN: events of TWebBrowser to control the load page {$IFDEF DELPHIXE2} procedure BeforeNavigate2(ASender: TObject; const pDisp: IDispatch; const URL, Flags, TargetFrameName, PostData, Headers: OleVariant; var Cancel: WordBool); procedure DocumentComplete(ASender: TObject; const pDisp: IDispatch; const URL: OleVariant); procedure NavigateComplete2(ASender: TObject; const pDisp: IDispatch; const URL: OleVariant); {$ELSE} procedure BeforeNavigate2(ASender: TObject; const pDisp: IDispatch; var URL, Flags, TargetFrameName, PostData, Headers: OleVariant; var Cancel: WordBool); procedure DocumentComplete(ASender: TObject; const pDisp: IDispatch; var URL: OleVariant); procedure NavigateComplete2(ASender: TObject; const pDisp: IDispatch; var URL: OleVariant); {$ENDIF} function GetWebBrowser: TWebBrowser; procedure SetWebBrowser(const Value: TWebBrowser); protected procedure BrowserEventsControl; override; function ExecuteScript(NameFunct, Params: string): Boolean; override; procedure LoadBaseWeb; override; procedure LoadBlankPage; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; function GetIEVersion: string; published {*------------------------------------------------------------------------------ Browser where display the Google Maps map. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Navegador donde se mostrará el mapa de Google Maps. -------------------------------------------------------------------------------} property WebBrowser: TWebBrowser read GetWebBrowser write SetWebBrowser; end; {$ENDIF} {$IFDEF CHROMIUM} {*------------------------------------------------------------------------------ Class to access to Google Maps map specialized for TChromium browser. See the TCustomGMMap class for properties and events description. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Clase para el acceso al mapa de Google Maps especializada para el navegador TChromium. Ver la clase TCustomGMMap para la descripción de las propiedades y eventos. -------------------------------------------------------------------------------} TGMMapChr = class(TCustomGMMapVCL) private // internal variables OldOnLoadEnd: TOnLoadEnd; FTChr: TTimer; FStarTime: TDateTime; procedure OnTimerChr(Sender: TObject); procedure OnLoadEnd(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; httpStatusCode: Integer; out Result: Boolean); procedure SetWebBrowser(const Value: TChromium); function GetWebBrowser: TChromium; protected procedure BrowserEventsControl; override; function ExecuteScript(NameFunct, Params: string): Boolean; override; procedure LoadBaseWeb; override; procedure LoadBlankPage; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published {*------------------------------------------------------------------------------ Browser where display the Google Maps map -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Navegador donde se mostrará el mapa de Google Maps -------------------------------------------------------------------------------} property WebBrowser: TChromium read GetWebBrowser write SetWebBrowser; end; {$ENDIF} implementation uses {$IFDEF WEBBROWSER} MSHTML, {$IFDEF DELPHIXE2} Winapi.ActiveX, System.Win.Registry, Winapi.Windows, {$ELSE} ActiveX, Registry, Windows, {$ENDIF} {$ENDIF} {$IFDEF DELPHIXE2} Vcl.Forms, System.DateUtils, {$ELSE} Forms, DateUtils, {$ENDIF} Lang, WebControlVCL; { TGMMap } {$IFDEF WEBBROWSER} procedure TGMMap.Assign(Source: TPersistent); begin inherited; if Source is TGMMap then begin VisualProp.Assign(TGMMap(Source).VisualProp); end; end; {$IFDEF DELPHIXE2} procedure TGMMap.BeforeNavigate2(ASender: TObject; const pDisp: IDispatch; const URL, Flags, TargetFrameName, PostData, Headers: OleVariant; var Cancel: WordBool); {$ELSE} procedure TGMMap.BeforeNavigate2(ASender: TObject; const pDisp: IDispatch; var URL, Flags, TargetFrameName, PostData, Headers: OleVariant; var Cancel: WordBool); {$ENDIF} begin if Assigned(OldBeforeNavigate2) then OldBeforeNavigate2(ASender, pDisp, URL, Flags, TargetFrameName, PostData, Headers, Cancel); CurDispatch := nil; FDocLoaded := False; end; procedure TGMMap.BrowserEventsControl; begin if not (FWebBrowser is TWebBrowser) then Exit; TWebBrowser(FWebBrowser).OnBeforeNavigate2 := OldBeforeNavigate2; TWebBrowser(FWebBrowser).OnDocumentComplete := OldDocumentComplete; TWebBrowser(FWebBrowser).OnNavigateComplete2 := OldNavigateComplete2; OldBeforeNavigate2 := nil; OldDocumentComplete := nil; OldNavigateComplete2 := nil; end; constructor TGMMap.Create(AOwner: TComponent); begin inherited; FWC := TWebControl.Create(nil); end; destructor TGMMap.Destroy; begin if Assigned(FVisualProp) then FreeAndNil(FVisualProp); inherited; end; {$IFDEF DELPHIXE2} procedure TGMMap.DocumentComplete(ASender: TObject; const pDisp: IDispatch; const URL: OleVariant); {$ELSE} procedure TGMMap.DocumentComplete(ASender: TObject; const pDisp: IDispatch; var URL: OleVariant); {$ENDIF} begin if Assigned(OldDocumentComplete) then OldDocumentComplete(ASender, pDisp, URL); if (pDisp = CurDispatch) then // si son iguales, la página se ha cargado begin FDocLoaded := True; CurDispatch := nil; if Active and Assigned(AfterPageLoaded) then AfterPageLoaded(Self, True); end; end; function TGMMap.ExecuteScript(NameFunct, Params: string): Boolean; var Doc2: IHTMLDocument2; Win2: IHTMLWindow2; begin Result := Check; if not (FWebBrowser is TWebBrowser) then Exit; if not Result then Exit; Doc2 := TWebBrowser(FWebBrowser).Document as IHTMLDocument2; Win2 := Doc2.parentWindow; Win2.execScript(NameFunct + '(' + Params + ')', 'JavaScript'); if MapIsNull then raise Exception.Create(GetTranslateText('El mapa todavía no ha sido creado', Language)); end; function TGMMap.GetIEVersion: string; var Reg: TRegistry; begin Result := ''; Reg := TRegistry.Create; try Reg.RootKey := HKEY_LOCAL_MACHINE; if Reg.OpenKeyReadOnly('Software\Microsoft\Internet Explorer') then try Result := Reg.ReadString('svcVersion'); if Result = '' then Result := Reg.ReadString('Version'); finally Reg.CloseKey; end; finally Reg.Free; end; if Result = '' then Result := '0'; end; function TGMMap.GetWebBrowser: TWebBrowser; begin Result := nil; if FWebBrowser is TWebBrowser then Result := TWebBrowser(FWebBrowser); end; procedure TGMMap.LoadBaseWeb; var StringStream: TStringStream; PersistStreamInit: IPersistStreamInit; StreamAdapter: IStream; begin if not Assigned(FWebBrowser) then Exit; if not (FWebBrowser is TWebBrowser) then Exit; // creación del TStringStream con el string que contiene la página web StringStream := TStringStream.Create(GetBaseHTMLCode); try // nos aseguramos de tener algún contenido en Document if not Assigned(TWebBrowser(FWebBrowser).Document) then LoadBlankPage; // acceder a la interfaz IPersistStreamInit de Document if TWebBrowser(FWebBrowser).Document.QueryInterface(IPersistStreamInit, PersistStreamInit) = S_OK then begin // borrar datos actuales if PersistStreamInit.InitNew = S_OK then begin // creación y inicialización del IStream StreamAdapter:= TStreamAdapter.Create(StringStream); // carga de la página web mediante IPersistStreamInit PersistStreamInit.Load(StreamAdapter); end; end; finally StringStream.Free; end; end; procedure TGMMap.LoadBlankPage; begin if not (FWebBrowser is TWebBrowser) then Exit; FDocLoaded := False; TWebBrowser(FWebBrowser).Navigate('about:blank'); end; {$IFDEF DELPHIXE2} procedure TGMMap.NavigateComplete2(ASender: TObject; const pDisp: IDispatch; const URL: OleVariant); {$ELSE} procedure TGMMap.NavigateComplete2(ASender: TObject; const pDisp: IDispatch; var URL: OleVariant); {$ENDIF} begin if Assigned(OldNavigateComplete2) then OldNavigateComplete2(ASender, pDisp, URL); if CurDispatch = nil then CurDispatch := pDisp; end; procedure TGMMap.SetWebBrowser(const Value: TWebBrowser); begin if FWebBrowser = Value then Exit; if (Value <> FWebBrowser) and Assigned(FWebBrowser) then begin TWebBrowser(FWebBrowser).OnBeforeNavigate2 := OldBeforeNavigate2; TWebBrowser(FWebBrowser).OnDocumentComplete := OldDocumentComplete; TWebBrowser(FWebBrowser).OnNavigateComplete2 := OldNavigateComplete2; end; FWebBrowser := Value; TWebControl(FWC).SetBrowser(TWebBrowser(FWebBrowser)); if csDesigning in ComponentState then Exit; if Assigned(FWebBrowser) then begin OldBeforeNavigate2 := TWebBrowser(FWebBrowser).OnBeforeNavigate2; OldDocumentComplete := TWebBrowser(FWebBrowser).OnDocumentComplete; OldNavigateComplete2 := TWebBrowser(FWebBrowser).OnNavigateComplete2; TWebBrowser(FWebBrowser).OnBeforeNavigate2 := BeforeNavigate2; TWebBrowser(FWebBrowser).OnDocumentComplete := DocumentComplete; TWebBrowser(FWebBrowser).OnNavigateComplete2 := NavigateComplete2; if Active then LoadBaseWeb; end; end; {$ENDIF} { TGMMapChr } {$IFDEF CHROMIUM} procedure TGMMapChr.BrowserEventsControl; begin if not (FWebBrowser is TChromium) then Exit; TChromium(FWebBrowser).OnLoadEnd := OldOnLoadEnd; OldOnLoadEnd := nil; end; constructor TGMMapChr.Create(AOwner: TComponent); begin inherited; FWC := TWebChromium.Create(nil); OldOnLoadEnd := nil; FTChr := TTimer.Create(Self); FTChr.Enabled := False; FTChr.OnTimer := OnTimerChr; FTChr.Interval := 10; FStarTime := Now; end; destructor TGMMapChr.Destroy; begin if Assigned(FTChr) then FreeAndNil(FTChr); inherited; end; function TGMMapChr.ExecuteScript(NameFunct, Params: string): Boolean; const Param = '%s(%s)'; begin Result := Check; if not (FWebBrowser is TChromium) then Exit; if not Result then Exit; if Assigned(TChromium(FWebBrowser).Browser) then TChromium(FWebBrowser).Browser.MainFrame.ExecuteJavaScript(Format(Param, [NameFunct, Params]), '', 0); if MapIsNull then raise Exception.Create(GetTranslateText('El mapa todavía no ha sido creado', Language)); end; function TGMMapChr.GetWebBrowser: TChromium; begin Result := nil; if FWebBrowser is TChromium then Result := TChromium(FWebBrowser); end; procedure TGMMapChr.LoadBaseWeb; begin if not Assigned(FWebBrowser) then Exit; if not (FWebBrowser is TChromium) then Exit; // cargamos página inicial if Assigned(TChromium(FWebBrowser).Browser) then TChromium(FWebBrowser).Browser.MainFrame.LoadString(GetBaseHTMLCode, 'http:\\localhost'); end; procedure TGMMapChr.LoadBlankPage; begin if not (FWebBrowser is TChromium) then Exit; TChromium(FWebBrowser).Browser.MainFrame.LoadUrl('about:blank'); end; procedure TGMMapChr.OnLoadEnd(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; httpStatusCode: Integer; out Result: Boolean); begin if Assigned(OldOnLoadEnd) then OldOnLoadEnd(Sender, browser, frame, httpStatusCode, Result); if Assigned(frame) then begin FDocLoaded := True; if Active and Assigned(AfterPageLoaded) then AfterPageLoaded(Self, True); end; end; procedure TGMMapChr.OnTimerChr(Sender: TObject); begin if Active and Assigned(FWebBrowser) and Assigned(TChromium(FWebBrowser).Browser) then begin FTChr.Enabled := False; LoadBaseWeb; end; if Now > IncSecond(FStarTime, 3) then FTChr.Enabled := False; end; procedure TGMMapChr.SetWebBrowser(const Value: TChromium); begin if FWebBrowser = Value then Exit; if (Value <> FWebBrowser) and Assigned(FWebBrowser) then begin TChromium(FWebBrowser).OnLoadEnd := OldOnLoadEnd; end; FWebBrowser := Value; TWebChromium(FWC).SetBrowser(TChromium(FWebBrowser)); if csDesigning in ComponentState then Exit; if Assigned(FWebBrowser) then begin OldOnLoadEnd := TChromium(FWebBrowser).OnLoadEnd; TChromium(FWebBrowser).OnLoadEnd := OnLoadEnd; // if Active then LoadBaseWeb; if Active then begin FStarTime := Now; FTChr.Enabled := True; end; end; end; {$ENDIF} { TCustomGMMapVCL } procedure TCustomGMMapVCL.Assign(Source: TPersistent); begin inherited; if Source is TCustomGMMap then begin VisualProp.Assign(TCustomGMMapVCL(Source).VisualProp); end; end; constructor TCustomGMMapVCL.Create(AOwner: TComponent); begin inherited; VisualProp := TVisualProp.Create; FTimer := TTimer.Create(Self); FTimer.Enabled := False; FTimer.Interval := 200; FTimer.OnTimer := OnTimer; end; destructor TCustomGMMapVCL.Destroy; begin if Assigned(FTimer) then FreeAndNil(FTimer); inherited; end; procedure TCustomGMMapVCL.SaveToJPGFile(FileName: TFileName); var SD: TSaveDialog; begin inherited; if not Assigned(FWebBrowser) or not Assigned(FWC) then Exit; if FileName = '' then begin SD := TSaveDialog.Create(nil); try SD.Filter := '*.jpg|*.jpg'; SD.DefaultExt := '*.jpg'; if SD.Execute then FileName := SD.FileName; finally FreeAndNil(SD); end; end; FWC.SaveToJPGFile(FileName); end; procedure TCustomGMMapVCL.SetEnableTimer(State: Boolean); begin inherited; if Assigned(FTimer) then FTimer.Enabled := State; end; procedure TCustomGMMapVCL.SetIntervalTimer(Interval: Integer); begin inherited; if Assigned(FTimer) then FTimer.Interval := Interval; end; function TCustomGMMapVCL.VisualPropToStr: string; begin Result := FVisualProp.ToStr; end; { TVisualProp } procedure TVisualProp.Assign(Source: TPersistent); begin inherited; if Source is TVisualProp then BGColor := TVisualProp(Source).BGColor; end; constructor TVisualProp.Create; begin inherited; FBGColor := clSilver; end; function TVisualProp.GetBckgroundColor: string; begin Result := TTransform.TColorToStr(FBGColor); end; end.
unit xQuestionAction; interface uses xDBActionBase, xQuestionInfo, System.Classes, System.SysUtils, xFunction, FireDAC.Stan.Param; type TQuestionAction = class(TDBActionBase) public /// <summary> /// 获取最大编号 /// </summary> function GetMaxSN : Integer; /// <summary> /// 添加考题 /// </summary> procedure AddQuestion(AQuestion : TQuestionInfo); /// <summary> /// 删除考题 /// </summary> procedure DelQuestion(nSortID, nQID : Integer); overload; procedure DelQuestion(AQuestion : TQuestionInfo); overload; procedure DelQuestion(nSortID : Integer); overload; /// <summary> /// 修改考题 /// </summary> procedure EditQuestion(AQuestion : TQuestionInfo); /// <summary> /// 清空考题 /// </summary> procedure ClearQuestion; overload; procedure ClearQuestion(nSortID : Integer); overload; /// <summary> /// 加载考题 /// </summary> procedure LoadQuestion(nSortID : Integer; slList :TStringList); end; implementation { TQuestionAction } procedure TQuestionAction.AddQuestion(AQuestion: TQuestionInfo); const C_SQL = 'insert into QuestionInfo ( SortID, QID, QType, QName,' + 'QDescribe, QCode, QAnswer, QExplain, QRemark1, QRemark2' + ') values ( %d, %d, %d, :QName, :QDescribe, :QCode, :QAnswer,' + ':QExplain, :QRemark1, :QRemark2 )'; begin if Assigned(AQuestion) then begin with AQuestion, FQuery.Params do begin FQuery.Sql.Text := Format( C_SQL, [ Sortid, Qid, Qtype ] ); ParamByName( 'QName' ).Value := Qname ; ParamByName( 'QCode' ).Value := QCode; ParamByName( 'QDescribe' ).Value := Qdescribe; ParamByName( 'QAnswer' ).Value := Qanswer ; ParamByName( 'QExplain' ).Value := Qexplain ; ParamByName( 'QRemark1' ).Value := Qremark1 ; ParamByName( 'QRemark2' ).Value := Qremark2 ; end; ExecSQL; end; end; procedure TQuestionAction.ClearQuestion; begin FQuery.Sql.Text := 'delete from QuestionInfo'; ExecSQL; end; procedure TQuestionAction.DelQuestion(nSortID, nQID: Integer); const C_SQL = 'delete from QuestionInfo where SortID = %d and QID = %d'; begin FQuery.Sql.Text := Format( C_SQL, [ nSortID, nQID ] ); ExecSQL; end; procedure TQuestionAction.DelQuestion(AQuestion: TQuestionInfo); begin if Assigned(AQuestion) then begin DelQuestion(AQuestion.SortID, AQuestion.QID); end; end; procedure TQuestionAction.ClearQuestion(nSortID: Integer); const C_SQL = 'delete from QuestionInfo where SortID = %d'; begin FQuery.Sql.Text := Format( C_SQL, [ nSortID ] ); ExecSQL; end; procedure TQuestionAction.DelQuestion(nSortID: Integer); const C_SQL = 'delete from QuestionInfo where SortID = %d'; begin FQuery.Sql.Text := Format( C_SQL, [ nSortID ] ); ExecSQL; end; procedure TQuestionAction.EditQuestion(AQuestion: TQuestionInfo); const C_SQL ='update QuestionInfo set QType = %d,' + 'QName = :QName, QDescribe = :QDescribe, QCode = :QCode, QAnswer = :QAnswer,' + 'QExplain = :QExplain, QRemark1 = :QRemark1,' + 'QRemark2 = :QRemark2 where SortID = %d and QID = %d'; begin if Assigned(AQuestion) then begin with AQuestion, FQuery.Params do begin FQuery.Sql.Text := Format( C_SQL, [ Qtype, Sortid, Qid ] ); ParamByName( 'QName' ).Value := Qname ; ParamByName( 'QDescribe' ).Value := Qdescribe; ParamByName( 'QCode' ).Value := QCode; ParamByName( 'QAnswer' ).Value := Qanswer ; ParamByName( 'QExplain' ).Value := Qexplain ; ParamByName( 'QRemark1' ).Value := Qremark1 ; ParamByName( 'QRemark2' ).Value := Qremark2 ; end; ExecSQL; end; end; function TQuestionAction.GetMaxSN: Integer; const C_SQL = 'select max(QID) as MaxSN from QuestionInfo'; begin FQuery.Open(C_SQL); if FQuery.RecordCount = 1 then Result := FQuery.FieldByName('MaxSN').AsInteger else Result := 0; FQuery.Close; end; procedure TQuestionAction.LoadQuestion(nSortID: Integer; slList: TStringList); const C_SQL = 'select * from QuestionInfo where SortID = %d'; var AQuestion : TQuestionInfo; begin if Assigned(slList) then begin ClearStringList(slList); FQuery.Open(Format( C_SQL, [nSortID] )); while not FQuery.Eof do begin AQuestion := TQuestionInfo.Create; with AQuestion, FQuery do begin Sortid := FieldByName( 'SortID' ).AsInteger; Qid := FieldByName( 'QID' ).AsInteger; Qtype := FieldByName( 'QType' ).AsInteger; Qname := FieldByName( 'QName' ).AsString; Qdescribe := FieldByName( 'QDescribe' ).AsString; QCode := FieldByName( 'QCode' ).AsString; Qanswer := FieldByName( 'QAnswer' ).AsString; Qexplain := FieldByName( 'QExplain' ).AsString; Qremark1 := FieldByName( 'QRemark1' ).AsString; Qremark2 := FieldByName( 'QRemark2' ).AsString; end; slList.AddObject('', AQuestion); FQuery.Next; end; FQuery.Close; end; end; end.
unit std_system; interface implementation function LoByte(Value: UInt16): UInt8; begin Result := Value and $FF; end; function HiByte(Value: UInt16): UInt8; begin Result := Value shr 8; end; function LoWord(Value: UInt32): UInt16; begin Result := Value and $FFFF; end; function HiWord(Value: UInt32): UInt16; begin Result := Value shr 16; end; function LoDWord(Value: UInt64): UInt32; begin Result := Value and $FFFFFFFF; end; function HiDWord(Value: UInt64): UInt32; begin Result := Value shr 32; end; var Src: UInt64 = $0123456789ABCDEF; lb, hb: UInt8; lw, hw: UInt16; ld, hd: UInt32; procedure Test; begin lb := LoByte(Src); hb := HiByte(Src); lw := LoWord(Src); hw := HiWord(Src); ld := LoDWord(Src); hd := HiDWord(Src); end; initialization Test(); finalization Assert(lb = $EF); Assert(hb = $CD); Assert(lw = $CDEF); Assert(hw = $89AB); Assert(ld = $89ABCDEF); Assert(hd = $01234567); end.
unit uPrincipal; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.StdCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls, Vcl.ComCtrls; type TfPrincipal = class(TForm) PageControl1: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; pnlTitulo: TPanel; dbgPessoalAtividade: TDBGrid; pnlPesquisa: TPanel; Label1: TLabel; edtPesquisa: TEdit; btnPesquisar: TButton; TabSheet3: TTabSheet; pnlTituloPedidos: TPanel; Panel2: TPanel; btnListarPedidos: TButton; Panel3: TPanel; Panel4: TPanel; btnLista: TButton; pnlPedidos: TPanel; Panel1: TPanel; DBGrid1: TDBGrid; pnlItensPedido: TPanel; Panel6: TPanel; DBGrid2: TDBGrid; edtMaiorNumero: TEdit; Label2: TLabel; ListBox1: TListBox; TabSheet4: TTabSheet; Panel5: TPanel; Panel7: TPanel; GroupBox1: TGroupBox; edtCodigo: TEdit; EdtNome: TEdit; Label3: TLabel; Label4: TLabel; Button1: TButton; procedure btnPesquisarClick(Sender: TObject); procedure TabSheet2Show(Sender: TObject); procedure btnListaClick(Sender: TObject); procedure btnListarPedidosClick(Sender: TObject); procedure edtPesquisaKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } procedure listarPessoalAtividade(Nome:String); procedure listarPedidos; procedure InserirAtividade; end; var fPrincipal: TfPrincipal; implementation {$R *.dfm} uses uDAO, Rotinas, uAtividadesCRUD, uControle; { TfPrincipal } procedure TfPrincipal.btnListaClick(Sender: TObject); var Lista:TStringList; begin try Lista := TStringList.Create; Lista := Rotinas.MontarLista(Lista); ListBox1.Clear; ListBox1.Items.AddStrings(Lista); edtMaiorNumero.Text := LocalizaMaiorNumero(Lista); finally Lista.Free; end; end; procedure TfPrincipal.btnListarPedidosClick(Sender: TObject); begin listarPedidos; end; procedure TfPrincipal.btnPesquisarClick(Sender: TObject); begin listarPessoalAtividade(edtPesquisa.Text); end; procedure TfPrincipal.Button1Click(Sender: TObject); begin InserirAtividade; end; procedure TfPrincipal.edtPesquisaKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin listarPessoalAtividade(edtPesquisa.Text); end; procedure TfPrincipal.InserirAtividade; var Atividades : TAtividadesCRUD; Controle : TControle; begin try Controle := TControle.Create; Atividades := TAtividadesCRUD.Create(Controle); Atividades.Codigo := edtCodigo.Text; Atividades.Nome := EdtNome.Text; Atividades.InsereAtividade; Application.MessageBox('Atividade Inserida com sucesso','Atenção',MB_OK+MB_ICONINFORMATION); except on E: exception do begin Application.MessageBox('Erro ao Inserir dados','Atenção',MB_OK+MB_ICONERROR); end; end; end; procedure TfPrincipal.listarPedidos; begin try DAO.pesquisarPedidos; except on E: exception do begin Application.MessageBox('Erro ao pesquisar dados','Atenção',MB_OK+MB_ICONERROR); end; end; end; procedure TfPrincipal.listarPessoalAtividade(Nome: String); begin try DAO.pesquisarPessoalAtividades(Nome); except on E: exception do begin Application.MessageBox('Erro ao pesquisar dados','Atenção',MB_OK+MB_ICONERROR); end; end; end; procedure TfPrincipal.TabSheet2Show(Sender: TObject); begin edtPesquisa.SetFocus; end; end.
{ } { Unicode string functions v3.07 } { } { This unit is copyright © 2002-2004 by David J Butler } { } { This unit is part of Delphi Fundamentals. } { Its original file name is cUnicode.pas } { The latest version is available from the Fundamentals home page } { http://fundementals.sourceforge.net/ } { } { I invite you to use this unit, free of charge. } { I invite you to distibute this unit, but it must be for free. } { I also invite you to contribute to its development, } { but do not distribute a modified copy of this file. } { } { A forum is available on SourceForge for general discussion } { http://sourceforge.net/forum/forum.php?forum_id=2117 } { } { } { Description: } { Unicode functions for using WideStrings. } { } { Revision history: } { 19/04/2002 0.01 Initial version } { 26/04/2002 0.02 Added WidePos, WideReplace and Append functions. } { 28/10/2002 3.03 Refactored for Fundamentals 3. } { 18/12/2002 3.04 Removed dependancy on cUnicodeChar unit. } { 07/09/2003 3.05 Revisions. } { 10/01/2004 3.06 Unit now uses cUnicodeChar for character functions. } { Removed dependancy on cUtils unit. } { 01/04/2004 3.07 Compilable with FreePascal-1.92/Win32. } { } {$INCLUDE ..\cDefines.inc} unit cUnicode; interface uses { Delphi } SysUtils, { Fundamentals } cUnicodeChar; const UnitName = 'cUnicode'; UnitVersion = '3.07'; UnitCopyright = 'Copyright (c) 2002-2004 David J Butler'; { } { Unicode errors } { } type EUnicode = class(Exception); { } { WideString functions } { } type AnsiCharSet = Set of AnsiChar; function WideMatchAnsiCharNoCase(const M: Char; const C: WideChar): Boolean; function WidePMatchChars(const CharMatchFunc: WideCharMatchFunction; const P: PWideChar; const Length: Integer = -1): Integer; function WidePMatchCharsRev(const CharMatchFunc: WideCharMatchFunction; const P: PWideChar; const Length: Integer = -1): Integer; function WidePMatchAllChars(const CharMatchFunc: WideCharMatchFunction; const P: PWideChar; const Length: Integer = -1): Integer; function WidePMatchAnsiStr(const M: String; const P: PWideChar; const CaseSensitive: Boolean = True): Boolean; function WidePMatch(const M: WideString; const P: PWideChar): Boolean; function WideEqualAnsiStr(const M: String; const S: WideString; const CaseSensitive: Boolean = True): Boolean; function WideMatchLeftAnsiStr(const M: String; const S: WideString; const CaseSensitive: Boolean = True): Boolean; function WideZPosChar(const F: WideChar; const P: PWideChar): Integer; function WideZPosAnsiChar(const F: Char; const P: PWideChar): Integer; function WideZPosAnsiCharSet(const F: AnsiCharSet; const P: PWideChar): Integer; function WideZPosAnsiStr(const F: String; const P: PWideChar; const CaseSensitive: Boolean = True): Integer; function WideZSkipChar(const CharMatchFunc: WideCharMatchFunction; var P: PWideChar): Boolean; function WideZSkipChars(const CharMatchFunc: WideCharMatchFunction; var P: PWideChar): Integer; function WidePSkipAnsiChar(const Ch: Char; var P: PWideChar): Boolean; function WidePSkipAnsiStr(const M: String; var P: PWideChar; const CaseSensitive: Boolean = True): Boolean; function WideZExtractBeforeChar(const Ch: WideChar; var P: PWideChar; var S: WideString): Boolean; function WideZExtractBeforeAnsiChar(const Ch: Char; var P: PWideChar; var S: WideString): Boolean; function WideZExtractBeforeAnsiCharSet(const C: AnsiCharSet; var P: PWideChar; var S: WideString): Boolean; function WideZExtractAnsiCharDelimited(const LeftDelimiter, RightDelimiter: Char; var P: PWideChar; var S: WideString): Boolean; function WideZExtractAnsiCharQuoted(const Delimiter: Char; var P: PWideChar; var S: WideString): Boolean; function WideDup(const Ch: WideChar; const Count: Integer): WideString; procedure WideTrimInPlace(var S: WideString; const MatchFunc: WideCharMatchfunction = nil); procedure WideTrimLeftInPlace(var S: WideString; const MatchFunc: WideCharMatchfunction = nil); procedure WideTrimRightInPlace(var S: WideString; const MatchFunc: WideCharMatchfunction = nil); function WideTrim(const S: WideString; const MatchFunc: WideCharMatchfunction = nil): WideString; function WideTrimLeft(const S: WideString; const MatchFunc: WideCharMatchfunction = nil): WideString; function WideTrimRight(const S: WideString; const MatchFunc: WideCharMatchfunction = nil): WideString; function WideCountChar(const CharMatchFunc: WideCharMatchFunction; const S: WideString): Integer; overload; function WideCountChar(const Ch: WideChar; const S: WideString): Integer; overload; function WidePosChar(const F: WideChar; const S: WideString; const StartIndex: Integer = 1): Integer; overload; function WidePosAnsiCharSet(const F: AnsiCharSet; const S: WideString; const StartIndex: Integer = 1): Integer; function WidePos(const F: WideString; const S: WideString; const StartIndex: Integer = 1): Integer; overload; procedure WideReplaceChar(const Find: WideChar; const Replace: WideString; var S: WideString); procedure WideSetLengthAndZero(var S: WideString; const NewLength: Integer); {$IFDEF DELPHI5} function WideUpperCase(const S: WideString): WideString; function WideLowerCase(const S: WideString): WideString; {$ENDIF} function WideCopyRange(const S: WideString; const StartIndex, StopIndex: Integer): WideString; function WideCopyFrom(const S: WideString; const Index: Integer): WideString; { } { Dynamic Array functions } { } type WideStringArray = Array of WideString; function WideAppend(var V : WideStringArray; const R: WideString): Integer; overload; function WideAppendWideStringArray(var V : WideStringArray; const R: WideStringArray): Integer; function WideSplit(const S, D: WideString): WideStringArray; { } { Self-testing code } { } procedure SelfTest; implementation { } { Match } { } function WideMatchAnsiCharNoCase(const M: Char; const C: WideChar): Boolean; const ASCIICaseOffset = Ord('a') - Ord('A'); var D, N : Char; begin if Ord(C) > $7F then begin Result := False; exit; end; D := Char(Ord(C)); if D in ['A'..'Z'] then D := Char(Ord(D) + ASCIICaseOffset); N := M; if N in ['A'..'Z'] then N := Char(Ord(N) + ASCIICaseOffset); Result := D = N; end; function WidePMatchChars(const CharMatchFunc: WideCharMatchFunction; const P: PWideChar; const Length: Integer): Integer; var Q : PWideChar; L : Integer; C : WideChar; begin Result := 0; Q := P; L := Length; if not Assigned(Q) or (L = 0) then exit; C := Q^; if (L < 0) and (Ord(C) = 0) then exit; Repeat if not CharMatchFunc(C) then exit; Inc(Result); Inc(Q); if L > 0 then Dec(L); C := Q^; Until (L = 0) or ((L < 0) and (Ord(C) = 0)); end; function WidePMatchCharsRev(const CharMatchFunc: WideCharMatchFunction; const P: PWideChar; const Length: Integer): Integer; var Q : PWideChar; L : Integer; C : WideChar; begin Result := 0; Q := P; L := Length; if not Assigned(Q) or (L = 0) then exit; Inc(Q, L - 1); C := Q^; if (L < 0) and (Ord(C) = 0) then exit; Repeat if not CharMatchFunc(C) then exit; Inc(Result); Dec(Q); if L < 0 then C := Q^ else begin Dec(L); if L > 0 then C := Q^; end; Until (L = 0) or ((L < 0) and (Ord(C) = 0)); end; function WidePMatchAllChars(const CharMatchFunc: WideCharMatchFunction; const P: PWideChar; const Length: Integer): Integer; var Q : PWideChar; L : Integer; C : WideChar; begin Result := 0; Q := P; L := Length; if not Assigned(Q) or (L = 0) then exit; C := Q^; if (L < 0) and (Ord(C) = 0) then exit; Repeat if CharMatchFunc(C) then Inc(Result); Inc(Q); if L > 0 then Dec(L); C := Q^; Until (L = 0) or ((L < 0) and (Ord(C) = 0)); end; function WidePMatchAnsiStr(const M: String; const P: PWideChar; const CaseSensitive: Boolean): Boolean; var I, L : Integer; Q : PWideChar; R : PChar; begin L := Length(M); if L = 0 then begin Result := False; exit; end; R := Pointer(M); Q := P; if CaseSensitive then begin For I := 1 to L do if Ord(R^) <> Ord(Q^) then begin Result := False; exit; end else begin Inc(R); Inc(Q); end; end else begin For I := 1 to L do if not WideMatchAnsiCharNoCase(R^, Q^) then begin Result := False; exit; end else begin Inc(R); Inc(Q); end; end; Result := True; end; function WidePMatch(const M: WideString; const P: PWideChar): Boolean; var I, L : Integer; Q, R : PWideChar; begin L := Length(M); if L = 0 then begin Result := False; exit; end; R := Pointer(M); Q := P; For I := 1 to L do if R^ <> Q^ then begin Result := False; exit; end else begin Inc(R); Inc(Q); end; Result := True; end; function WideEqualAnsiStr(const M: String; const S: WideString; const CaseSensitive: Boolean): Boolean; var L : Integer; begin L := Length(M); Result := L = Length(S); if not Result or (L = 0) then exit; Result := WidePMatchAnsiStr(M, Pointer(S), CaseSensitive); end; function WideMatchLeftAnsiStr(const M: String; const S: WideString; const CaseSensitive: Boolean): Boolean; var L, N : Integer; begin L := Length(M); N := Length(S); if (L = 0) or (N = 0) or (L > N) then begin Result := False; exit; end; Result := WidePMatchAnsiStr(M, Pointer(S), CaseSensitive); end; { } { Pos } { } function WideZPosAnsiChar(const F: Char; const P: PWideChar): Integer; var Q : PWideChar; I : Integer; begin Result := -1; Q := P; if not Assigned(Q) then exit; I := 0; While Ord(Q^) <> 0 do if Ord(Q^) = Ord(F) then begin Result := I; exit; end else begin Inc(Q); Inc(I); end; end; function WideZPosAnsiCharSet(const F: AnsiCharSet; const P: PWideChar): Integer; var Q : PWideChar; I : Integer; begin Result := -1; Q := P; if not Assigned(Q) then exit; I := 0; While Ord(Q^) <> 0 do if (Ord(Q^) < $80) and (Char(Ord(Q^)) in F) then begin Result := I; exit; end else begin Inc(Q); Inc(I); end; end; function WideZPosChar(const F: WideChar; const P: PWideChar): Integer; var Q : PWideChar; I : Integer; begin Result := -1; Q := P; if not Assigned(Q) then exit; I := 0; While Ord(Q^) <> 0 do if Q^ = F then begin Result := I; exit; end else begin Inc(Q); Inc(I); end; end; function WideZPosAnsiStr(const F: String; const P: PWideChar; const CaseSensitive: Boolean): Integer; var Q : PWideChar; I : Integer; begin Result := -1; Q := P; if not Assigned(Q) then exit; I := 0; While Ord(Q^) <> 0 do if WidePMatchAnsiStr(F, Q, CaseSensitive) then begin Result := I; exit; end else begin Inc(Q); Inc(I); end; end; { } { Skip } { } function WideZSkipChar(const CharMatchFunc: WideCharMatchFunction; var P: PWideChar): Boolean; var C : WideChar; begin Assert(Assigned(CharMatchFunc)); C := P^; if Ord(C) = 0 then begin Result := False; exit; end; Result := CharMatchFunc(C); if Result then Inc(P); end; function WideZSkipChars(const CharMatchFunc: WideCharMatchFunction; var P: PWideChar): Integer; var C : WideChar; begin Assert(Assigned(CharMatchFunc)); Result := 0; if not Assigned(P) then exit; C := P^; While Ord(C) <> 0 do if not CharMatchFunc(C) then exit else begin Inc(P); Inc(Result); C := P^; end; end; function WidePSkipAnsiChar(const Ch: Char; var P: PWideChar): Boolean; begin Result := Ord(P^) = Ord(Ch); if Result then Inc(P); end; function WidePSkipAnsiStr(const M: String; var P: PWideChar; const CaseSensitive: Boolean): Boolean; begin Result := WidePMatchAnsiStr(M, P, CaseSensitive); if Result then Inc(P, Length(M)); end; { } { Extract } { } function WideZExtractBeforeChar(const Ch: WideChar; var P: PWideChar; var S: WideString): Boolean; var I : Integer; begin I := WideZPosChar(Ch, P); Result := I >= 0; if I <= 0 then begin S := ''; exit; end; SetLength(S, I); Move(P^, Pointer(S)^, I * Sizeof(WideChar)); Inc(P, I); end; function WideZExtractBeforeAnsiChar(const Ch: Char; var P: PWideChar; var S: WideString): Boolean; var I : Integer; begin I := WideZPosAnsiChar(Ch, P); Result := I >= 0; if I <= 0 then begin S := ''; exit; end; SetLength(S, I); Move(P^, Pointer(S)^, I * Sizeof(WideChar)); Inc(P, I); end; function WideZExtractBeforeAnsiCharSet(const C: AnsiCharSet; var P: PWideChar; var S: WideString): Boolean; var I : Integer; begin I := WideZPosAnsiCharSet(C, P); Result := I >= 0; if I <= 0 then begin S := ''; exit; end; SetLength(S, I); Move(P^, Pointer(S)^, I * Sizeof(WideChar)); Inc(P, I); end; function WideZExtractAnsiCharDelimited(const LeftDelimiter, RightDelimiter: Char; var P: PWideChar; var S: WideString): Boolean; var Q : PWideChar; begin Q := P; Result := Assigned(Q) and (Ord(Q^) < $80) and (Ord(Q^) = Ord(LeftDelimiter)); if not Result then begin S := ''; exit; end; Inc(Q); Result := WideZExtractBeforeAnsiChar(RightDelimiter, Q, S); if not Result then exit; Inc(Q); P := Q; end; function WideZExtractAnsiCharQuoted(const Delimiter: Char; var P: PWideChar; var S: WideString): Boolean; begin Result := WideZExtractAnsiCharDelimited(Delimiter, Delimiter, P, S); end; { } { Dup } { } function WideDup(const Ch: WideChar; const Count: Integer): WideString; var I : Integer; P : PWideChar; begin if Count <= 0 then begin Result := ''; exit; end; SetLength(Result, Count); P := Pointer(Result); For I := 1 to Count do begin P^ := Ch; Inc(P); end; end; { } { Trim } { } procedure WideTrimLeftInPlace(var S: WideString; const MatchFunc: WideCharMatchFunction); var I, L : Integer; P : PWideChar; F: WideCharMatchFunction; begin L := Length(S); if L = 0 then exit; F := MatchFunc; if not Assigned(F) then F := IsWhiteSpace; I := 0; P := Pointer(S); While F(P^) do begin Inc(I); Inc(P); Dec(L); if L = 0 then begin S := ''; exit; end; end; if I = 0 then exit; S := Copy(S, I + 1, L); end; procedure WideTrimRightInPlace(var S: WideString; const MatchFunc: WideCharMatchFunction); var I, L : Integer; P : PWideChar; F: WideCharMatchFunction; begin L := Length(S); if L = 0 then exit; F := MatchFunc; if not Assigned(F) then F := IsWhiteSpace; I := 0; P := Pointer(S); Inc(P, L - 1); While F(P^) do begin Inc(I); Dec(P); Dec(L); if L = 0 then begin S := ''; exit; end; end; if I = 0 then exit; SetLength(S, L); end; procedure WideTrimInPlace(var S: WideString; const MatchFunc: WideCharMatchFunction); var I, J, L : Integer; P : PWideChar; F: WideCharMatchFunction; begin L := Length(S); if L = 0 then exit; F := MatchFunc; if not Assigned(F) then F := IsWhiteSpace; I := 0; P := Pointer(S); Inc(P, L - 1); While F(P^) or IsControl(P^) do begin Inc(I); Dec(P); Dec(L); if L = 0 then begin S := ''; exit; end; end; J := 0; P := Pointer(S); While F(P^) or IsControl(P^) do begin Inc(J); Inc(P); Dec(L); if L = 0 then begin S := ''; exit; end; end; if (I = 0) and (J = 0) then exit; S := Copy(S, J + 1, L); end; function WideTrimLeft(const S: WideString; const MatchFunc: WideCharMatchFunction): WideString; begin Result := S; WideTrimLeftInPlace(Result, MatchFunc); end; function WideTrimRight(const S: WideString; const MatchFunc: WideCharMatchFunction): WideString; begin Result := S; WideTrimRightInPlace(Result, MatchFunc); end; function WideTrim(const S: WideString; const MatchFunc: WideCharMatchFunction): WideString; begin Result := S; WideTrimInPlace(Result, MatchFunc); end; { } { Count } { } function WideCountChar(const CharMatchFunc: WideCharMatchFunction; const S: WideString): Integer; begin Result := WidePMatchAllChars(CharMatchFunc, Pointer(S), Length(S)); end; function WideCountChar(const Ch: WideChar; const S: WideString): Integer; var Q : PWideChar; I : Integer; begin Result := 0; Q := PWideChar(S); if not Assigned(Q) then exit; For I := 1 to Length(S) do begin if Q^ = Ch then Inc(Result); Inc(Q); end; end; { } { Pos } { } function WidePosChar(const F: WideChar; const S: WideString; const StartIndex: Integer): Integer; var P : PWideChar; I, L : Integer; begin L := Length(S); if (StartIndex > L) or (StartIndex < 1) then begin Result := 0; exit; end; P := Pointer(S); Inc(P, StartIndex - 1); For I := StartIndex to L do if P^ = F then begin Result := I; exit; end else Inc(P); Result := 0; end; function WidePosAnsiCharSet(const F: AnsiCharSet; const S: WideString; const StartIndex: Integer): Integer; var P : PWideChar; I, L : Integer; begin L := Length(S); if (StartIndex > L) or (StartIndex < 1) then begin Result := 0; exit; end; P := Pointer(S); Inc(P, StartIndex - 1); For I := StartIndex to L do if (Ord(P^) <= $FF) and (Char(P^) in F) then begin Result := I; exit; end else Inc(P); Result := 0; end; function WidePos(const F: WideString; const S: WideString; const StartIndex: Integer): Integer; var P : PWideChar; I, L : Integer; begin L := Length(S); if (StartIndex > L) or (StartIndex < 1) then begin Result := 0; exit; end; P := Pointer(S); Inc(P, StartIndex - 1); For I := StartIndex to L do if WidePMatch(F, P) then begin Result := I; exit; end else Inc(P); Result := 0; end; { } { Replace } { } procedure WideReplaceChar(const Find: WideChar; const Replace: WideString; var S: WideString); var C, L, M, I, R : Integer; P, Q : PWideChar; T : WideString; begin C := WideCountChar(Find, S); if C = 0 then exit; R := Length(Replace); M := Length(S); L := M + (R - 1) * C; if L = 0 then begin S := ''; exit; end; SetLength(T, L); P := Pointer(S); Q := Pointer(T); For I := 1 to M do if P^ = Find then begin if R > 0 then begin Move(Pointer(Replace)^, Q^, Sizeof(WideChar) * R); Inc(Q, R); end; Inc(P); end else begin Q^ := P^; Inc(P); Inc(Q); end; S := T; end; procedure WideSetLengthAndZero(var S: WideString; const NewLength: Integer); var L : Integer; P : PWideChar; begin L := Length(S); if L = NewLength then exit; SetLength(S, NewLength); if L > NewLength then exit; P := Pointer(S); Inc(P, L); FillChar(P^, (NewLength - L) * Sizeof(WideChar), #0); end; {$IFDEF DELPHI5} function WideUpperCase(const S: WideString): WideString; var I : Integer; begin Result := ''; For I := 1 to Length(S) do Result := Result + WideUpCaseFolding(S[I]); end; function WideLowerCase(const S: WideString): WideString; var I : Integer; begin Result := ''; For I := 1 to Length(S) do Result := Result + WideLowCaseFolding(S[I]); end; {$ENDIF} function WideCopyRange(const S: WideString; const StartIndex, StopIndex: Integer): WideString; var L, I : Integer; begin L := Length(S); if (StartIndex > StopIndex) or (StopIndex < 1) or (StartIndex > L) or (L = 0) then Result := '' else begin if StartIndex <= 1 then if StopIndex >= L then begin Result := S; exit; end else I := 1 else I := StartIndex; Result := Copy(S, I, StopIndex - I + 1); end; end; function WideCopyFrom(const S: WideString; const Index: Integer): WideString; var L : Integer; begin if Index <= 1 then Result := S else begin L := Length(S); if (L = 0) or (Index > L) then Result := '' else Result := Copy(S, Index, L - Index + 1); end; end; { } { Dynamic Array functions } { } function WideAppend(var V : WideStringArray; const R: WideString): Integer; begin Result := Length(V); SetLength(V, Result + 1); V[Result] := R; end; function WideAppendWideStringArray(var V : WideStringArray; const R: WideStringArray): Integer; var I, LR : Integer; begin Result := Length(V); LR := Length(R); if LR > 0 then begin SetLength(V, Result + LR); For I := 0 to LR - 1 do V[Result + I] := R[I]; end; end; function WideSplit(const S, D: WideString): WideStringArray; var I, J, L, M: Integer; begin if S = '' then begin Result := nil; exit; end; M := Length(D); if M = 0 then begin SetLength(Result, 1); Result[0] := S; exit; end; L := 0; I := 1; Repeat I := WidePos(D, S, I); if I = 0 then break; Inc(L); Inc(I, M); Until False; SetLength(Result, L + 1); if L = 0 then begin Result[0] := S; exit; end; L := 0; I := 1; Repeat J := WidePos(D, S, I); if J = 0 then begin Result[L] := WideCopyFrom(S, I); break; end; Result[L] := WideCopyRange(S, I, J - 1); Inc(L); I := J + M; Until False; end; { } { Self-testing code } { } {$ASSERTIONS ON} procedure SelfTest; var S: WideString; begin Assert(WideMatchAnsiCharNoCase('A', 'a'), 'WideMatchAnsiCharNoCase'); Assert(WideMatchAnsiCharNoCase('z', 'Z'), 'WideMatchAnsiCharNoCase'); Assert(WideMatchAnsiCharNoCase('1', '1'), 'WideMatchAnsiCharNoCase'); Assert(not WideMatchAnsiCharNoCase('A', 'B'), 'WideMatchAnsiCharNoCase'); Assert(not WideMatchAnsiCharNoCase('0', 'A'), 'WideMatchAnsiCharNoCase'); Assert(WidePMatchAnsiStr('Unicode', 'uNicode', False), 'WidePMatchAnsiStr'); Assert(not WidePMatchAnsiStr('Unicode', 'uNicode', True), 'WidePMatchAnsiStr'); Assert(WidePMatchAnsiStr('Unicode', 'Unicode', True), 'WidePMatchAnsiStr'); Assert(WideTrimLeft(' X ') = 'X ', 'WideTrimLeft'); Assert(WideTrimRight(' X ') = ' X', 'WideTrimRight'); Assert(WideTrim(' X ') = 'X', 'WideTrim'); Assert(WideDup('X', 0) = '', 'WideDup'); Assert(WideDup('X', 1) = 'X', 'WideDup'); Assert(WideDup('A', 4) = 'AAAA', 'WideDup'); S := 'AXAYAA'; WideReplaceChar('A', '', S); Assert(S = 'XY', 'WideReplaceChar'); S := 'AXAYAA'; WideReplaceChar('A', 'B', S); Assert(S = 'BXBYBB', 'WideReplaceChar'); S := 'AXAYAA'; WideReplaceChar('A', 'CC', S); Assert(S = 'CCXCCYCCCC', 'WideReplaceChar'); S := 'AXAXAA'; WideReplaceChar('X', 'IJK', S); Assert(S = 'AIJKAIJKAA', 'WideReplaceChar'); Assert(WidePosChar(WideChar('A'), 'XYZABCAACDEF', 1) = 4, 'WidePosChar'); Assert(WidePosChar(WideChar('A'), 'XYZABCAACDEF', 5) = 7, 'WidePosChar'); Assert(WidePosChar(WideChar('A'), 'XYZABCAACDEF', 8) = 8, 'WidePosChar'); Assert(WidePosChar(WideChar('A'), 'XYZABCAACDEF', 9) = 0, 'WidePosChar'); Assert(WidePosChar(WideChar('Q'), 'XYZABCAACDEF', 1) = 0, 'WidePosChar'); Assert(WidePos('AB', 'XYZABCAACDEF', 1) = 4, 'WidePos'); Assert(WidePos('AA', 'XYZABCAACDEF', 1) = 7, 'WidePos'); Assert(WidePos('A', 'XYZABCAACDEF', 8) = 8, 'WidePos'); Assert(WidePos('AA', 'XYZABCAACDEF', 8) = 0, 'WidePos'); Assert(WidePos('AAQ', 'XYZABCAACDEF', 1) = 0, 'WidePos'); Assert(WideZPosAnsiChar('A', 'XYZABCAACDEF') = 3, 'WideZPosAnsiChar'); Assert(WideZPosAnsiChar('Q', 'XYZABCAACDEF') = -1, 'WideZPosAnsiChar'); end; end.
{***************************************************************} { } { Borland Delphi Visual Component Library } { } { Copyright (c) 2000-2001 Borland Software Corporation } { } {***************************************************************} unit SvrLogDetailDlg; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ActnList, SvrLogFrame, SvrLogDetailFrame, Registry; type TLogDetail = class(TForm) ActionList1: TActionList; PrevAction: TAction; NextAction: TAction; CloseAction: TAction; Button1: TButton; Button2: TButton; Button3: TButton; LogDetailFrame: TLogDetailFrame; procedure PrevActionExecute(Sender: TObject); procedure PrevActionUpdate(Sender: TObject); procedure NextActionExecute(Sender: TObject); procedure NextActionUpdate(Sender: TObject); procedure CloseActionExecute(Sender: TObject); procedure FormShow(Sender: TObject); private FLogFrame: TLogFrame; public constructor Create(AOwner: TComponent); override; procedure Load(Reg: TRegIniFile; const Section: string); procedure Save(Reg: TRegIniFile; const Section: string); property LogFrame: TLogFrame read FLogFrame write FLogFrame; end; var FLogDetail: TLogDetail; implementation {$R *.dfm} procedure TLogDetail.PrevActionExecute(Sender: TObject); begin FLogFrame.Previous; FLogFrame.ShowDetail(LogDetailFrame); end; procedure TLogDetail.PrevActionUpdate(Sender: TObject); begin (Sender as TAction).Enabled := FLogFrame.Index > 0; end; procedure TLogDetail.NextActionExecute(Sender: TObject); begin FLogFrame.Next; FLogFrame.ShowDetail(LogDetailFrame); end; procedure TLogDetail.NextActionUpdate(Sender: TObject); begin (Sender as TAction).Enabled := (FLogFrame.Count > 0) and (FLogFrame.Index < FLogFrame.Count - 1); end; constructor TLogDetail.Create(AOwner: TComponent); begin inherited Create(AOwner); end; procedure TLogDetail.CloseActionExecute(Sender: TObject); begin ModalResult := mrOk; end; const sLeft = 'Left'; sTop = 'Top'; sWidth = 'Width'; sHeight = 'Height'; procedure TLogDetail.Load(Reg: TRegIniFile; const Section: string); var LastPath: string; begin LastPath := Reg.CurrentPath; Reg.OpenKey(Section, True); try if Reg.ValueExists(sLeft) then begin Position := poDesigned; Self.Left := Reg.ReadInteger('', sLeft, Self.Left); Self.Top := Reg.ReadInteger('', sTop, Self.Top); Self.Width := Reg.ReadInteger('', sWidth, Self.Width); Self.Height := Reg.ReadInteger('', sHeight, Self.Height); end; finally Reg.OpenKey('\' + LastPath, True); end; LogDetailFrame.Load(Reg, Section); end; procedure TLogDetail.Save(Reg: TRegIniFile; const Section: string); var LastPath: string; begin LogDetailFrame.Save(Reg, Section); LastPath := Reg.CurrentPath; Reg.OpenKey(Section, True); try Reg.WriteInteger('', sLeft, Self.Left); Reg.WriteInteger('', sTop, Self.Top); Reg.WriteInteger('', sWidth, Self.Width); Reg.WriteInteger('', sHeight, Self.Height); finally Reg.OpenKey('\' + LastPath, True); end; end; procedure TLogDetail.FormShow(Sender: TObject); begin FLogFrame.ShowDetail(LogDetailFrame); end; end.
unit FTools; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms; const //ARQ_CORES = 'Cores.ini'; //DIR_SIMBOLOS = 'Simbolos'; ARQ_CONFIG = 'LemhapCards.ini'; ARQ_UPLOADER = 'Uploader.ini'; ARQ_TIPOS = 'Tipos.ini'; DIR_IMAGENS = 'Imagens'; DIR_DADOS = 'Dados'; DIR_HELP = 'Help'; DIR_EXEMPLOS = 'Exemplos'; DIR_MODELOS = 'Modelos'; DIR_MODELOS_CARTAO = 'Modelos\Cartao'; DIR_MODELOS_ENVELOPE = 'Modelos\Envelope'; DIR_MODELOS_TIMBRADO = 'Modelos\Timbrado'; DIR_MODELOS_OUTROS = 'Modelos\Outros'; type TFormTools = class(TForm) procedure FormCreate(Sender: TObject); private { Private declarations } LocalDir: String; public { Public declarations } function CutSubString(var str:string; c1,c2:char):string; function MyGetLocalDir:string; //function ApplyDark(Color:TColor; HowMuch:byte):TColor; function MyFileVerInfo(const FileName: string; var versao: string): Boolean; end; var FormTools: TFormTools; implementation {$R *.DFM} function TFormTools.CutSubString(var str:string; c1,c2:char):string; var auxstr:string; aux1,aux2:integer; begin auxstr:=str; aux1:=pos(c1,AuxStr); Delete(AuxStr,1,aux1); aux2:=pos(c2,AuxStr); Delete(AuxStr, aux2, length(AuxStr)-(aux2-1)); CutSubString:=AuxStr; //Delete(str,1,aux2+1); //Deixa o ultimo caracter C2 na string principal e se recebe uma string que //so tenha um elemente e este for igual ao c2 entao limpa a string //OBS. ACHEI MELHOR FUNCIONAR ASSIM !!! Delete(str,1,aux2); if str=c2 then str:=''; end; function TFormTools.MyGetLocalDir:string; begin MyGetLocalDir := LocalDir; end; procedure TFormTools.FormCreate(Sender: TObject); begin // Se for o diretorio raiz a funcao GETDIR retorna 'C:\' // se nao ela retorna "c:\diretorio" // Resolvi padronizar : retornando SEMPRE uma barra no final da string //GetDir(0,LocalDir); LocalDir:=ExtractFileDir(Application.ExeName); LocalDir:=LocalDir+'\'; if (pos(':\\',LocalDir)>0) then delete(LocalDir,pos(':\\',LocalDir)+1,1); end; { function TFormTools.ApplyDark(Color:TColor; HowMuch:byte):TColor; var r,g,b:Byte; begin Color:=ColorToRGB(Color); r:=GetRValue(Color); g:=GetGValue(Color); b:=GetBValue(Color); if r>HowMuch then r:=r-HowMuch else r:=0; if g>HowMuch then g:=g-HowMuch else g:=0; if b>HowMuch then b:=b-HowMuch else b:=0; result:=RGB(r,g,b); end; } function TFormTools.MyFileVerInfo(const FileName: string; var versao: string): Boolean; var Dummy : THandle; BufferSize, Len : Integer; Buffer : PChar; LoCharSet, HiCharSet : Word; Translate, Return : Pointer; StrFileInfo : string; begin Result := False; { Obtemos o tamanho em bytes do "version information" } BufferSize := GetFileVersionInfoSize(PChar(FileName), Dummy); if BufferSize <> 0 then begin GetMem(Buffer, Succ(BufferSize)); try if GetFileVersionInfo(PChar(FileName), 0, BufferSize,Buffer) then { Executamos a funcao "VerQueryValue" e conseguimos informacoes sobre o idioma/character-set } if VerQueryValue(Buffer, '\VarFileInfo\Translation',Translate, UINT(Len)) then begin LoCharSet := LoWord(Longint(Translate^)); HiCharSet := HiWord(Longint(Translate^)); { Montamos a string de pesquisa } StrFileInfo := Format('\StringFileInfo\0%x0%x\%s',[LoCharSet, HiCharSet, 'FileVersion']); { Adicionamos cada key pré-definido } if VerQueryValue(Buffer,PChar(StrFileInfo), Return,UINT(Len)) then versao:=PChar(Return); end; finally FreeMem(Buffer, Succ(BufferSize)); Result := versao <> ''; end; end else begin versao := inttostr(FileAge(FileName)); end; end; end.
unit UnPerfCounter; interface uses windows, SysUtils; type {: Um contador de alta performance, utilizado para realizar medições de tempo/velocidade. } TPerformanceCounter = class(TObject) private startTick, endTick, freq: int64; countExecs: integer; accum: int64; FStarted: boolean; public constructor create; {: Inicia o cronômetro interno. } procedure start; {: Finaliza o cronômetro interno. } procedure stop; {: Retorna (em milisegundos) o tempo da última "corrida" do cronômetro. É preciso que os métodos start() e stop() tenham sido chamados anteriormente. } function lastMs: double; {: Retorna (em milisegundos) o tempo entre o último start() e agora. } function currentMs: double; {: Retorna a quantidade de execuções por segundo (baseado no acumulador). } function execsPerSec: double; {: Reinicializa o contador de execuções. } procedure zeroExecs; {: Zera a quantidade de execuções e o acumulador. } procedure zeroExecsAccum; {: Incrementa o contador de execuções em 1. } procedure incExecs; {: Indica se já iniciou o timer. } function started: boolean; {: Acumula o lastMs atual em um acumulador interno. } procedure accumulate; {: Pára a execução e acumula o que foi gasto. } procedure stopAndAccumulate; {: Retorna o tempo acumulado em millisegundos. } function currentAccumMS: double; {: Rertorna a média do acumulado pelo número de execuções. } function avgAccumMs: double; {: Zera o acumulador. } procedure zeroAccum; {: Retorna a quantidade de eventos acontecida em um determinado período. } function execCount: integer; {: Executa um writeln com o currentMs() } procedure currentToConsole(const msg: string); {: Executa um writeln com info do currentAccum(). } procedure accumToConsole(const msg: string); end; var masterPerf: TPerformanceCounter; implementation { TPerformanceCounter } procedure TPerformanceCounter.accumToConsole(const msg: string); begin writeln(Format('%8.2f - %d execs - %s', [self.currentAccumMS, self.countExecs, msg])); end; procedure TPerformanceCounter.accumulate; begin accum:= accum + (endTick - startTick); end; function TPerformanceCounter.avgAccumMs: double; begin if countExecs > 0 then result:= currentAccumMS / countExecs else result:= currentAccumMS; end; constructor TPerformanceCounter.create; begin QueryPerformanceFrequency(freq); end; function TPerformanceCounter.currentAccumMS: double; begin result:= accum / (freq/1000); end; function TPerformanceCounter.currentMs: double; var tick: int64; begin QueryPerformanceCounter(tick); result:= (tick - startTick) / (freq/1000); end; procedure TPerformanceCounter.currentToConsole(const msg: string); begin writeln(Format('%8.2f - %s', [self.currentMs, msg])); end; function TPerformanceCounter.execCount: integer; begin Result:= countExecs; end; function TPerformanceCounter.execsPerSec: double; var curMs: double; begin curMs:= currentAccumMS; result:= (curMs / 1000) / countExecs; end; procedure TPerformanceCounter.incExecs; begin countExecs:= countExecs + 1; end; function TPerformanceCounter.lastMs: double; begin result:= (endTick - startTick) / (freq/1000); end; procedure TPerformanceCounter.start; begin QueryPerformanceCounter(startTick); FStarted:= true; end; function TPerformanceCounter.started: boolean; begin result:= FStarted; end; procedure TPerformanceCounter.stop; begin QueryPerformanceCounter(endTick); FStarted:= false; end; procedure TPerformanceCounter.stopAndAccumulate; begin stop; accumulate; incExecs; end; procedure TPerformanceCounter.zeroAccum; begin accum:= 0; end; procedure TPerformanceCounter.zeroExecs; begin countExecs:= 0; end; procedure TPerformanceCounter.zeroExecsAccum; begin zeroExecs; zeroAccum; end; initialization masterPerf:= TPerformanceCounter.create; masterPerf.start; {$IFDEF PerfConsoleAlertStart} masterPerf.currentToConsole('Iniciando Master Perf'); {$ENDIF} finalization masterPerf.Free; end.
unit TransportWS; {$mode delphi}{$H+} {$I vrode.inc} interface uses Classes, SysUtils, vr_transport, vr_utils, WebSocket2, CustomServer2; type TWebSocketConnectionDataNotSync = function(ASender: TWebSocketCustomConnection; ACode: Integer; AData: TMemoryStream): Boolean of object; { TNotSyncWebSocketClientConnection } TNotSyncWebSocketClientConnection = class(TWebSocketClientConnection) private FOnReadNotSync: TWebSocketConnectionDataNotSync; protected procedure DoSyncRead; override; public property OnReadNotSync: TWebSocketConnectionDataNotSync read FOnReadNotSync write FOnReadNotSync; end; { TWSTransportClient } TWSTransportClient = class(TCustomTransportClient) private FHost: string; FPort: Word; FResourceName: string; FClient: TNotSyncWebSocketClientConnection; FOpened: PtrInt; procedure OnClose(aSender: TWebSocketCustomConnection; aCloseCode: integer; aCloseReason: string; aClosedByPeer: boolean); procedure OnOpen(aSender: TWebSocketCustomConnection); function OnReadNotSync(ASender: TWebSocketCustomConnection; ACode: Integer; AData: TMemoryStream): Boolean; procedure OnTerminateClient(Sender: TObject); procedure StopClient; protected procedure DoSend(const AMsg: string; const AClient: Pointer = nil); override; function DoConnect: Boolean; override; function DoDisConnect: Boolean; override; public constructor Create(APort: Word; const AHost: string = ''; const AResourceName: string = ''); virtual; overload; destructor Destroy; override; end; { TNotSyncWebSocketServerConnection } TNotSyncWebSocketServerConnection = class(TWebSocketServerConnection) private FOnReadNotSync: TWebSocketConnectionDataNotSync; protected procedure DoSyncRead; override; public property OnReadNotSync: TWebSocketConnectionDataNotSync read FOnReadNotSync write FOnReadNotSync; end; { TWSTransportServer } TWSTransportServer = class(TCustomTransportServer) private FServer: TWebSocketServer; procedure OnAfterAddConnection(Server: TCustomServer; aConnection: TCustomConnection); procedure OnAfterRemoveConnection(Server: TCustomServer; aConnection: TCustomConnection); function OnClientReadNotSync(ASender: TWebSocketCustomConnection; ACode: Integer; AData: TMemoryStream): Boolean; protected function GetAlive: Boolean; override; procedure DoSend(const AMsg: string; const AClient: Pointer = nil); override; public constructor {%H-}Create(APort: Word = 0; const AHost: string = ''; const AResource: string = ''); //overload; destructor Destroy; override; end; implementation type { TTransportWebSocketServer } TTransportWebSocketServer = class(TWebSocketServer) protected function GetWebSocketConnectionClass(Socket: TTCPCustomConnectionSocket; Header: TStringList; ResourceName, Host, Port, Origin, Cookie: string; out HttpResult: integer; var Protocol, Extensions: string ): TWebSocketServerConnections; override; public property Terminated; end; { TTransportWebSocketServer } function TTransportWebSocketServer.GetWebSocketConnectionClass( Socket: TTCPCustomConnectionSocket; Header: TStringList; ResourceName, Host, Port, Origin, Cookie: string; out HttpResult: integer; var Protocol, Extensions: string): TWebSocketServerConnections; begin Result := TNotSyncWebSocketServerConnection; end; { TNotSyncWebSocketServerConnection } procedure TNotSyncWebSocketServerConnection.DoSyncRead; begin if fReadFinal and Assigned(FOnReadNotSync) then begin fReadStream.Position := 0; if FOnReadNotSync(Self, fReadCode, fReadStream) then Exit; end; inherited DoSyncRead; end; { TWSTransportServer } procedure TWSTransportServer.OnAfterAddConnection(Server: TCustomServer; aConnection: TCustomConnection); begin if aConnection is TWebSocketCustomConnection then TNotSyncWebSocketServerConnection(aConnection).OnReadNotSync := OnClientReadNotSync; DoAddConnection(aConnection); end; procedure TWSTransportServer.OnAfterRemoveConnection(Server: TCustomServer; aConnection: TCustomConnection); begin if aConnection is TWebSocketCustomConnection then TNotSyncWebSocketServerConnection(aConnection).OnReadNotSync := nil; DoRemoveConnection(aConnection); end; function TWSTransportServer.OnClientReadNotSync( ASender: TWebSocketCustomConnection; ACode: Integer; AData: TMemoryStream): Boolean; var S: string; begin Result := True; SetLength(S, aData.Size); aData.Read(S[1], aData.Size); DoReceive(S, ASender, ASender); end; function TWSTransportServer.GetAlive: Boolean; begin Result := (FServer <> nil) and not TTransportWebSocketServer(FServer).Terminated; end; procedure TWSTransportServer.DoSend(const AMsg: string; const AClient: Pointer); begin if AClient = nil then FServer.BroadcastText(AMsg) else TWebSocketCustomConnection(AClient).SendText(AMsg); end; constructor TWSTransportServer.Create(APort: Word; const AHost: string; const AResource: string); begin inherited Create(False); FServer := TTransportWebSocketServer.Create(IfThen(AHost = '', '0.0.0.0', AHost), IntToStr(APort)); FServer.OnAfterAddConnection := OnAfterAddConnection; FServer.OnAfterRemoveConnection := OnAfterRemoveConnection; FServer.FreeOnTerminate := True; FServer.Start; end; destructor TWSTransportServer.Destroy; begin FServer.TerminateThread; FServer := nil; inherited Destroy; end; { TNotSyncWebSocketClientConnection } procedure TNotSyncWebSocketClientConnection.DoSyncRead; begin if fReadFinal and Assigned(FOnReadNotSync) then begin fReadStream.Position := 0; if FOnReadNotSync(Self, fReadCode, fReadStream) then Exit; end; inherited DoSyncRead; end; { TWSTransportClient } procedure TWSTransportClient.StopClient; begin if FClient <> nil then begin FClient.OnTerminate := nil; FClient.OnClose := nil; FClient.OnReadNotSync := nil; FClient.TerminateThread; FClient := nil; DoDisconnect; end; end; procedure TWSTransportClient.DoSend(const AMsg: string; const AClient: Pointer); begin if FClient <> nil then FClient.SendText(AMsg); end; procedure TWSTransportClient.OnTerminateClient(Sender: TObject); begin StopClient; end; function TWSTransportClient.OnReadNotSync(ASender: TWebSocketCustomConnection; ACode: Integer; AData: TMemoryStream): Boolean; var sMessage: string; begin Result := True; if AData.Size = 0 then Exit; SetLength(sMessage, aData.Size); aData.Read(PChar(sMessage)^, aData.Size); DoReceive(sMessage, nil, ASender); end; procedure TWSTransportClient.OnClose(aSender: TWebSocketCustomConnection; aCloseCode: integer; aCloseReason: string; aClosedByPeer: boolean); begin StopClient; end; procedure TWSTransportClient.OnOpen(aSender: TWebSocketCustomConnection); begin FOpened := 1; end; function TWSTransportClient.DoConnect: Boolean; begin Result := False; StopClient; FClient := TNotSyncWebSocketClientConnection.Create(FHost, IntToStr(FPort), FResourceName); FClient.FreeOnTerminate := True; FClient.OnTerminate := OnTerminateClient; FClient.OnReadNotSync := OnReadNotSync; FClient.OnClose := OnClose; FClient.OnOpen := OnOpen; FClient.Start; FOpened := 0; Result := Wait(10000, @FOpened, 0, True) = 1; end; function TWSTransportClient.DoDisConnect: Boolean; begin FOpened := -1; StopClient; Result := True; end; constructor TWSTransportClient.Create(APort: Word; const AHost: string; const AResourceName: string); begin Create; FHost := IfThen(AHost = '', LOCAL_HOST, AHost); FPort := APort; FResourceName := IfThen(AResourceName = '', '/', AResourceName); end; destructor TWSTransportClient.Destroy; begin StopClient; inherited Destroy; end; end.
unit uFeaCosmetic; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, ExtCtrls, StdCtrls, Math, jpeg, uObjectFeature, Buttons, Vcl.Imaging.pngimage; type TfFeaCosmetic = class(TForm) Panel1: TPanel; PgCtrl: TPageControl; tabCirc: TTabSheet; tabRect: TTabSheet; Image2: TImage; Label1: TLabel; edRectRadius: TLabeledEdit; lbRectRadius: TLabel; Image3: TImage; edX: TLabeledEdit; edY: TLabeledEdit; Label2: TLabel; Panel2: TPanel; btnSadHole: TSpeedButton; btnCancel: TBitBtn; btnSave: TBitBtn; edVyska: TEdit; edSirka: TEdit; edPriemer: TEdit; edName: TEdit; lbName: TLabel; dlgColor: TColorDialog; lbColor: TLabel; shpColor: TShape; lbChooseColor: TLabel; procedure btnSaveClick(Sender: TObject); procedure EditFeature(fea: integer); procedure DecimalPoint(Sender: TObject; var Key: Char); procedure FormActivate(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnSadHoleClick(Sender: TObject); procedure LinkLabelClick(Sender: TObject); procedure MathExp(Sender: TObject); procedure edNameKeyPress(Sender: TObject; var Key: Char); procedure clrBoxCosmeticKeyPress(Sender: TObject; var Key: Char); procedure lbChooseColorMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); private { Private declarations } public is_editing: boolean; // udava, ci je okno otvorene pre vytvorenie alebo editovanie prvku edited_feature_ID: integer; // cislo upravovanej feature { Public declarations } end; var fFeaCosmetic: TfFeaCosmetic; implementation uses uMain, uMyTypes, uPanelSett, uConfig, uObjectPanel, uTranslate, uLib; {$R *.dfm} procedure TfFeaCosmetic.FormCreate(Sender: TObject); begin fMain.imgList_common.GetBitmap(0, btnSadHole.Glyph); btnCancel.Glyph := fPanelSett.btnCancel.Glyph; btnSave.Glyph := fPanelSett.btnSave.Glyph; PgCtrl.ActivePageIndex := 0; PgCtrl.OnDrawTab := fmain.DrawTabs; end; procedure TfFeaCosmetic.lbChooseColorMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if dlgColor.Execute then shpColor.Brush.Color := dlgColor.Color; end; procedure TfFeaCosmetic.LinkLabelClick(Sender: TObject); begin fMain.BrowseWiki('tools-maximum-depths'); end; procedure TfFeaCosmetic.FormActivate(Sender: TObject); begin if PgCtrl.ActivePageIndex = 0 then begin edPriemer.SelectAll; edPriemer.SetFocus; end; if PgCtrl.ActivePageIndex = 1 then begin edSirka.SelectAll; edSirka.SetFocus; end; end; function CheckMinMax: boolean; var dummyInt, i: integer; nastroj: string; begin result := true; with fFeaCosmetic do begin try // kontrola okruhlej diery if (PgCtrl.ActivePageIndex = 0) then begin if (StrToFloat(edPriemer.Text) < 1) then begin MessageBox(handle, PChar(TransTxt('Diameter too small')), PChar(TransTxt('Error')), MB_ICONERROR); edPriemer.Text := '1'; edPriemer.SetFocus; result := false; end; if (StrToFloat(edPriemer.Text) >= _PNL.Vyska) OR (StrToFloat(edPriemer.Text) >= _PNL.Sirka) then begin MessageBox(handle, PChar(TransTxt('Diameter too big')), PChar(TransTxt('Error')), MB_ICONERROR); edPriemer.Text := FormatFloat('##0.###', Min(_PNL.Vyska,_PNL.Sirka)-1 ); edPriemer.SetFocus; result := false; end; // kontrola maximalnej hlbky pre dany nastroj for i := 0 to cfgToolMaxDepth.Count - 1 do begin // vyberie sa maximalne velky nastroj, ktory dokaze urobit dany radius if StrToFloat(cfgToolMaxDepth.Names[i]) <= StrToFloat(edPriemer.Text) then nastroj := cfgToolMaxDepth.Names[i]; end; if GetToolMaxDepth( nastroj ) < _PNL.Hrubka then begin MessageBox(handle, PChar(TransTxt('Hole diameter too small for this panel thickness')), PChar(TransTxt('Error')), MB_ICONERROR); edPriemer.SetFocus; result := false; end; end;// kontrola okruhlej diery // kontrola obdlznikovej diery if (PgCtrl.ActivePageIndex = 1) then begin if (StrToFloat(edSirka.Text) < 1) then begin MessageBox(handle, PChar(TransTxt('Width too small')), PChar(TransTxt('Error')), MB_ICONERROR); edSirka.Text := '1'; edSirka.SetFocus; result := false; end; if (StrToFloat(edSirka.Text) >= _PNL.Sirka) then begin MessageBox(handle, PChar(TransTxt('Width too big')), PChar(TransTxt('Error')), MB_ICONERROR); edSirka.Text := FormatFloat('##0.###',_PNL.Sirka-1); edSirka.SetFocus; result := false; end; if (StrToFloat(edVyska.Text) < 1) then begin MessageBox(handle, PChar(TransTxt('Height too small')), PChar(TransTxt('Error')), MB_ICONERROR); edVyska.Text := '1'; edVyska.SetFocus; result := false; end; if (StrToFloat(edVyska.Text) >= _PNL.Vyska) then begin MessageBox(handle, PChar(TransTxt('Height too big')), PChar(TransTxt('Error')), MB_ICONERROR); edVyska.Text := FormatFloat('##0.###',_PNL.Vyska-1); edVyska.SetFocus; result := false; end; if (StrToFloat(edRectRadius.Text) > StrToFloat(edSirka.Text)/2) OR (StrToFloat(edRectRadius.Text) > StrToFloat(edVyska.Text)/2) then begin MessageBox(handle, PChar(TransTxt('Radius too big')), PChar(TransTxt('Error')), MB_ICONERROR); edRectRadius.Text := FormatFloat('##0.###', Min( StrToFloat(edSirka.Text)/2 , StrToFloat(edVyska.Text)/2 ) ); edRectRadius.SetFocus; result := false; end; // kontrola maximalnej hlbky pre dany nastroj for i := 0 to cfgToolMaxDepth.Count - 1 do begin // vyberie sa maximalne velky nastroj, ktory dokaze urobit dany radius if StrToFloat(cfgToolMaxDepth.Names[i])/2 <= StrToFloat(edRectRadius.Text) then nastroj := cfgToolMaxDepth.Names[i]; end; end;// kontrola obdlznikovej diery StrToFloat(edX.Text); StrToFloat(edY.Text); except MessageBox(handle, PChar(TransTxt('Incorrect numerical value')), PChar(TransTxt('Error')), MB_ICONERROR); result := false; end; end; // with end; procedure TfFeaCosmetic.btnSaveClick(Sender: TObject); var feaID: integer; newFea: TFeatureObject; begin if not CheckMinMax then begin ModalResult := mrNone; Exit; end; _PNL.PrepareUndoStep; if PgCtrl.ActivePageIndex = 0 then begin if is_editing then feaID := edited_feature_ID else feaID := _PNL.AddFeature(ftCosmeticCircle); if feaID = -1 then Exit; // este to dame do UNDO listu if is_editing then _PNL.CreateUndoStep('MOD', 'FEA', feaID) else _PNL.CreateUndoStep('CRT', 'FEA', feaID); newFea := _PNL.GetFeatureByID(feaID); newFea.Rozmer1 := StrToFloat(edPriemer.Text); end; if PgCtrl.ActivePageIndex = 1 then begin if is_editing then feaID := edited_feature_ID else feaID := _PNL.AddFeature(ftCosmeticRect); if feaID = -1 then Exit; // este to dame do UNDO listu if is_editing then _PNL.CreateUndoStep('MOD', 'FEA', feaID) else _PNL.CreateUndoStep('CRT', 'FEA', feaID); newFea := _PNL.GetFeatureByID(feaID); newFea.Rozmer1 := StrToFloat(edSirka.Text); newFea.Rozmer2 := StrToFloat(edVyska.Text); newFea.Rozmer3 := StrToFloat(edRectRadius.Text); end; // ========== spolocne vlastnosti =================== newFea.Poloha := MyPoint( StrToFloat(edX.Text), StrToFloat(edY.Text) ); newFea.Nazov := edName.Text; newFea.Farba := shpColor.Brush.Color; newFea.Rozmer5:= 0; ModalResult := mrOK; _PNL.Draw; end; procedure TfFeaCosmetic.clrBoxCosmeticKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then begin Key := #0; btnSave.Click; end; end; procedure TfFeaCosmetic.EditFeature(fea: integer); var feature: TFeatureObject; begin is_editing := true; edited_feature_ID := fea; feature := _PNL.GetFeatureByID(fea); edX.Text := FormatFloat('0.###', feature.X); edY.Text := FormatFloat('0.###', feature.Y); edName.Text := feature.Nazov; shpColor.Brush.Color := feature.Farba; if feature.Param2 = '' then feature.Param2 := '0'; // ak nie je zadefinovana hrana, zadefinujeme ju na 'ziadnu' case feature.Typ of ftCosmeticCircle: begin tabCirc.TabVisible := true; tabRect.TabVisible := false; edPriemer.Text := FormatFloat('0.###', feature.Rozmer1); end; ftCosmeticRect: begin tabRect.TabVisible := true; tabCirc.TabVisible := false; edSirka.Text := FormatFloat('0.###', feature.Rozmer1); edVyska.Text := FormatFloat('0.###', feature.Rozmer2); edRectRadius.Text := FormatFloat('0.###', feature.Rozmer3); lbRectRadius.Enabled := edRectRadius.Enabled; end; end; //case end; procedure TfFeaCosmetic.edNameKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then btnSave.Click; end; procedure TfFeaCosmetic.MathExp(Sender: TObject); begin uLib.SolveMathExpression(Sender); end; procedure TfFeaCosmetic.DecimalPoint(Sender: TObject; var Key: Char); begin fMain.CheckDecimalPoint(sender, key, btnSave); end; procedure TfFeaCosmetic.btnSadHoleClick(Sender: TObject); begin fMain.ShowWish('Hole'); end; end.
unit Comp_UGraphics; interface uses Controls, Types, Windows, Messages, Graphics, Classes, Comp_UTypes; procedure EraseBackground(Control: TCustomControl; Canvas: TCanvas); function RectInRect(Container, Target: TRect): Boolean; procedure AlphaBlend(Canvas: TCanvas; Bitmap: TBitmap; const X, Y: Integer); procedure ColorOverlay(Canvas: TCanvas; Source: TRect; Color: TColor; const Alpha: Byte); procedure PaintEffects(Canvas: TCanvas; Dest: TRect; Effects: TScPaintEffects); procedure DrawShadow(Canvas: TCanvas; InnerRct: TRect; Size: Integer); overload; procedure DrawShadow(Canvas: TCanvas; Inner: TRect; Orientation: TScOrientation); overload; function IsColorLight(Color: TColor): Boolean; function DarkerColor(Color: TColor; Percent: Byte): TColor; function LighterColor(Color: TColor; Percent: Byte): TColor; procedure FillPadding(Canvas: TCanvas; Color: TColor; Dest: TRect; Padding: TPadding); function ColorOf(E: TScColorSchemeElement; Scheme: TScColorScheme = csDefault): TColor; procedure DrawTextRect(Canvas: TCanvas; TextRect: TRect; Alignment: TAlignment; VertAlignment: TVerticalAlignment; Text: WideString; WrapKind: TScWrapKind); var UnicodeSupported: Boolean; implementation uses Math; function ColorOf(E: TScColorSchemeElement; Scheme: TScColorScheme = csDefault): TColor; begin if Scheme = csDefault then Scheme := ColorScheme; Result := SchemeColor[Scheme, E]; end; procedure EraseBackground(Control: TCustomControl; Canvas: TCanvas); var Shift, Pt: TPoint; DC: HDC; begin if Control.Parent = nil then Exit; if Control.Parent.HandleAllocated then begin DC := Canvas.Handle; Shift.X := 0; Shift.Y := 0; Shift := Control.Parent.ScreenToClient(Control.ClientToScreen(Shift)); SaveDC(DC); try OffsetWindowOrgEx(DC, Shift.X, Shift.Y, nil); GetBrushOrgEx(DC, Pt); SetBrushOrgEx(DC, Pt.X + Shift.X, Pt.Y + Shift.Y, nil); Control.Parent.Perform(WM_ERASEBKGND, WParam(DC), 0); Control.Parent.Perform(WM_PAINT, WParam(DC), 0); finally RestoreDC(DC, -1); end; end; end; function RectInRect(Container, Target: TRect): Boolean; begin Result := PtInRect(Container, Target.TopLeft) and PtInRect(Container, Point(Pred(Target.Right), Pred(Target.Bottom))); end; procedure AlphaBlend(Canvas: TCanvas; Bitmap: TBitmap; const X, Y: Integer); var Func: TBlendFunction; begin { Blending Params } Func.BlendOp := AC_SRC_OVER; Func.BlendFlags := 0; Func.SourceConstantAlpha := 255; Func.AlphaFormat := AC_SRC_ALPHA; { Do Blending } Windows.AlphaBlend(Canvas.Handle, X, Y, Bitmap.Width, Bitmap.Height, Bitmap.Canvas.Handle, 0, 0, Bitmap.Width, Bitmap.Height, Func); end; procedure ColorOverlay(Canvas: TCanvas; Source: TRect; Color: TColor; const Alpha: Byte); var Row, Col: Integer; Pixel: PQuadColor; Mask: TBitmap; begin if Alpha = 255 then begin Canvas.Brush.Color := Color; Canvas.FillRect(Source); { Skip complex computings } Exit; end; { Convert SystemColor } if Integer(Color) < 0 then Color := GetSysColor(Color and $000000FF); { 10/26/11: We create an Alpha Mask TBitmap here which will be aplied into Canvas } Mask := TBitmap.Create; with Mask do begin { Important for AlphaBlend Func } PixelFormat := pf32bit; { Set Size of Mask } Width := Source.Right - Source.Left; Height := Source.Bottom - Source.Top; end; for Row := 0 to Pred(Mask.Height) do begin { Read first Pixel in row } Pixel := Mask.Scanline[Row]; for Col := 0 to Pred(Mask.Width) do begin Pixel.Red := GetRValue(Color); Pixel.Green := GetGValue(Color); Pixel.Blue := GetBValue(Color); { Set Alpha } Pixel.Alpha := Alpha; { Premultiply R, G & B } Pixel.Red := MulDiv(Pixel.Red, Pixel.Alpha, $FF); Pixel.Green := MulDiv(Pixel.Green, Pixel.Alpha, $FF); Pixel.Blue := MulDiv(Pixel.Blue, Pixel.Alpha, $FF); { Move to next Pixed } Inc(Pixel); end; { for Col } end; { for Row } { Call Blending Func } AlphaBlend(Canvas, Mask, Source.Left, Source.Top); { Release } Mask.Free; end; function IsColorLight(Color: TColor): Boolean; begin Color := ColorToRGB(Color); Result := ((Color and $FF) + (Color shr 8 and $FF) + (Color shr 16 and $FF))>= $180; end; function DarkerColor(Color: TColor; Percent: Byte): TColor; var r, g, b: Byte; begin Color := ColorToRGB(Color); r := GetRValue(Color); g := GetGValue(Color); b := GetBValue(Color); r := r - MulDiv(r, Percent, 100); //Percent% closer to black g := g - MulDiv(g, Percent, 100); b := b - MulDiv(b, Percent, 100); Result := RGB(r, g, b); end; function LighterColor(Color: TColor; Percent: Byte): TColor; var r, g, b: Byte; begin Color := ColorToRGB(Color); r := GetRValue(Color); g := GetGValue(Color); b := GetBValue(Color); r := r + MulDiv(255 - r, Percent, 100); g := g + MulDiv(255 - g, Percent, 100); b := b + MulDiv(255 - b, Percent, 100); Result := RGB(r, g, b); end; procedure FillPadding(Canvas: TCanvas; Color: TColor; Dest: TRect; Padding: TPadding); begin with Canvas, Padding do begin Brush.Color := Color; FillRect(Rect(Dest.Left + Left, Dest.Top, Dest.Right - Right, Dest.Top + Top)); FillRect(Rect(Dest.Left, Dest.Top, Dest.Left + Left, Dest.Bottom)); FillRect(Rect(Dest.Right - Right, Dest.Top, Dest.Right, Dest.Bottom)); FillRect(Rect(Dest.Left + Left, Dest.Bottom - Bottom, Dest.Right - Right, Dest.Bottom)); end; end; function GetTextSize(Handle: HDC; TextRect: TRect; Text: WideString): TSize; var Flags: Integer; {$IFNDEF UNICODE} StringText: string; {$ENDIF} begin Flags := DT_NOPREFIX or DT_VCENTER or DT_END_ELLIPSIS or DT_EXTERNALLEADING or DT_CALCRECT or DT_WORDBREAK; case UnicodeSupported of True: DrawTextW(Handle, PWideChar(Text), Length(Text), TextRect, Flags); False: begin {$IFDEF UNICODE} DrawText(Handle, PWideChar(Text), Length(Text), TextRect, Flags); {$ELSE} StringText := Text; DrawText(Handle, PAnsiChar(StringText), Length(StringText), TextRect, Flags); {$ENDIF} end; end; with Result do begin cx := TextRect.Right - TextRect.Left; cy := TextRect.Bottom - TextRect.Top; end; end; procedure DrawTextRect(Canvas: TCanvas; TextRect: TRect; Alignment: TAlignment; VertAlignment: TVerticalAlignment; Text: WideString; WrapKind: TScWrapKind); var Flags: Integer; {$IFNDEF UNICODE} StringText: string; {$ENDIF} TextSize: TSize; begin Flags := DT_NOPREFIX or DT_EXTERNALLEADING; if WrapKind <> wkWordWrap then begin Flags := Flags or DT_SINGLELINE; end; { Vert Alignment } case VertAlignment of taAlignTop: Flags := Flags or DT_TOP; taAlignBottom: Flags := Flags or DT_BOTTOM; taVerticalCenter: Flags := Flags or DT_VCENTER; end; { Wrapping } case WrapKind of wkNone: ; wkEllipsis: Flags := Flags or DT_END_ELLIPSIS; wkPathEllipsis: Flags := Flags or DT_PATH_ELLIPSIS; wkWordEllipsis: Flags := Flags or DT_WORD_ELLIPSIS; wkWordWrap: begin Flags := Flags or DT_WORDBREAK or DT_TOP; if VertAlignment <> taAlignTop then begin TextSize := GetTextSize(Canvas.Handle, TextRect, Text); case VertAlignment of taVerticalCenter: OffsetRect(TextRect, 0, Floor(RectHeight(TextRect) / 2 - TextSize.cy / 2)); taAlignBottom: TextRect.Top := TextRect.Bottom - RectHeight(TextRect); end; end; end; end; { Horz Alignment } case Alignment of taLeftJustify: Flags := Flags or DT_LEFT; taRightJustify: Flags := Flags or DT_RIGHT; Classes.taCenter: Flags := Flags or DT_CENTER; end; { Draw Text } with Canvas.Brush do begin Style := bsClear; case UnicodeSupported of True: DrawTextW(Canvas.Handle, PWideChar(Text), Length(Text), TextRect, Flags); else begin {$IFDEF UNICODE} DrawText(Canvas.Handle, PWideChar(Text), Length(Text), TextRect, Flags); {$ELSE} StringText := Text; DrawText(Canvas.Handle, PAnsiChar(StringText), Length(StringText), TextRect, Flags); {$ENDIF} end; end; Style := bsSolid; end; end; procedure DrawShadow(Canvas: TCanvas; InnerRct: TRect; Size: Integer); begin { Draw Horz Shadow } DrawShadow(Canvas, Rect(InnerRct.Left, InnerRct.Bottom, InnerRct.Right + Size, InnerRct.Bottom + Size), orHorizontal); { Draw Vert Shadow } DrawShadow(Canvas, Rect(InnerRct.Right, InnerRct.Top, InnerRct.Right + Size, InnerRct.Bottom + Size - 1), orVertical); end; procedure DrawShadow(Canvas: TCanvas; Inner: TRect; Orientation: TScOrientation); var Row, Col: Integer; Alpha: Single; Pixel: PQuadColor; AlphaByte: Byte; Mask: TBitmap; begin { 10/26/11: We create an Alpha Mask TBitmap here which will be aplied into Canvas } Mask := TBitmap.Create; with Mask do begin { Important for AlphaBlend Func } PixelFormat := pf32bit; { Set Size of Mask } Width := Inner.Right - Inner.Left; Height := Inner.Bottom - Inner.Top; end; for Row := 0 to Pred(Mask.Height) do begin { Read first Pixel in row } Pixel := Mask.Scanline[Row]; for Col := 0 to Pred(Mask.Width) do begin Pixel.Red := 0; Pixel.Green := 0; Pixel.Blue := 0; { Determine Alpha Level } case Orientation of orHorizontal: begin Alpha := (Mask.Height - Row) / Mask.Height; if Col < Mask.Height then Alpha := Alpha * (Col / Mask.Height) else if Col > Mask.Width - Mask.Height then begin Alpha := Alpha * ((Mask.Width - Col) / Mask.Height); end; end; else begin Alpha := (Mask.Width - Col) / Mask.Width; if Row < Mask.Width then Alpha := Alpha * (Row / Mask.Width) else if Row > Mask.Height - Mask.Width then begin Alpha := 0;//Alpha * ((Mask.Height - Row) / Mask.Width); end; end; end; Alpha := Alpha * 0.20; { Convert 0-1 to 0-255 } AlphaByte := Round(Alpha * 255.0); { Set Alpha } Pixel.Alpha := AlphaByte; { Premultiply R, G & B } Pixel.Red := Round(Pixel.Red * Alpha); Pixel.Green := Round(Pixel.Green * Alpha); Pixel.Blue := Round(Pixel.Blue * Alpha); { Move to next Pixed } Inc(Pixel); end; { for Col } end; { for Row } { Call Blending Func } AlphaBlend(Canvas, Mask, Inner.Left, Inner.Top); { Release } Mask.Free; end; procedure DrawLight(Canvas: TCanvas; InnerRct: TRect; Size: Integer); overload; var Row, Col, Middle: Integer; Alpha: Single; Pixel: PQuadColor; AlphaByte: Byte; Mask: TBitmap; begin { 10/26/11: We create an Alpha Mask TBitmap here which will be aplied into Canvas } Mask := TBitmap.Create; Middle := ((InnerRct.Right - InnerRct.Left) div 3) * 2; if Middle = 0 then Exit; with Mask do begin { Important for AlphaBlend Func } PixelFormat := pf32bit; { Set Size of Mask } Width := InnerRct.Right - InnerRct.Left; Height := InnerRct.Bottom - InnerRct.Top; end; for Row := 0 to Pred(Mask.Height) do begin { Read first Pixel in row } Pixel := Mask.Scanline[Row]; for Col := 0 to Pred(Mask.Width) do begin Pixel.Red := 255; Pixel.Green := 255; Pixel.Blue := 255; { Determine Alpha Level } Alpha := (Middle - Row) / Middle; { Convert 0-1 to 0-255 } AlphaByte := Round(Alpha * 255.0); if Col + Row > Middle then AlphaByte := 0; { Set Alpha } Pixel.Alpha := AlphaByte; { Premultiply R, G & B } Pixel.Red := Round(Pixel.Red * Alpha); Pixel.Green := Round(Pixel.Green * Alpha); Pixel.Blue := Round(Pixel.Blue * Alpha); { Move to next Pixed } Inc(Pixel); end; { for Col } end; { for Row } { Call Blending Func } AlphaBlend(Canvas, Mask, InnerRct.Left, InnerRct.Top); { Release } Mask.Free; end; procedure FlipVert(Source: TBitmap); var Col, Row: integer; PixelSrc, PixelDest: PQuadColor; begin for Row := 0 to Pred(Source.Height) do begin PixelSrc := Source.ScanLine[Row];; PixelDest := Source.ScanLine[Source.Height - 1 - Row]; for Col := 0 to Pred(Source.Width) do begin PixelSrc.Red := PixelDest.Red; PixelSrc.Green := PixelDest.Green; PixelSrc.Blue := PixelDest.Blue; Inc(PixelSrc); Inc(PixelDest); end; end; end; procedure DrawReflection(Canvas: TCanvas; InnerRct: TRect; Size: Integer); var Row, Col: Integer; Alpha: Single; Pixel: PQuadColor; AlphaByte: Byte; Mask: TBitmap; begin { 10/26/11: We create an Alpha Mask TBitmap here which will be aplied into Canvas } Mask := TBitmap.Create; with Mask do begin { Important for AlphaBlend Func } PixelFormat := pf32bit; { Set Size of Mask } Width := InnerRct.Right - InnerRct.Left; Height := InnerRct.Bottom - InnerRct.Top; end; { Copy TRect from Canvas into Bitmap } Mask.Canvas.CopyRect(Rect(0, 0, Mask.Width, Mask.Height), Canvas, InnerRct); { Flip Bitmap } FlipVert(Mask); for Row := 0 to Pred(Mask.Height) do begin { Read first Pixel in row } Pixel := Mask.Scanline[Row]; for Col := 0 to Pred(Mask.Width) do begin if Row < Size then Alpha := (Size - Row) / Size else Alpha := 0; { Convert 0-1 to 0-255 } AlphaByte := Round(Alpha * 255.0); { Set Alpha } Pixel.Alpha := AlphaByte; { Premultiply R, G & B } Pixel.Red := Round(Pixel.Red * Alpha); Pixel.Green := Round(Pixel.Green * Alpha); Pixel.Blue := Round(Pixel.Blue * Alpha); { Move to next Pixed } Inc(Pixel); end; { for Col } end; { for Row } { Call Blending Func } AlphaBlend(Canvas, Mask, InnerRct.Left, InnerRct.Bottom + 1); { Release } Mask.Free; end; procedure PaintEffects(Canvas: TCanvas; Dest: TRect; Effects: TScPaintEffects); begin { Add Shadow } if efShadow in Effects then begin { Add Right & Bottom Shadow } DrawShadow(Canvas, Dest, szShadowSize); end; { Add Light } if efLight in Effects then begin DrawLight(Canvas, Dest, szReflectionSize); end; { Add Reflection } if efReflection in Effects then begin DrawReflection(Canvas, Dest, szReflectionSize); end; end; end.
unit frmUserInformationU; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, IBServices, StdCtrls, ActnList; type TfrmUserInformation = class(TForm) GroupBox1: TGroupBox; GroupBox2: TGroupBox; Label1: TLabel; Label2: TLabel; Label3: TLabel; edtConfirmPassword: TEdit; edtPassword: TEdit; edtUser: TEdit; Label4: TLabel; edtFirstName: TEdit; Label5: TLabel; edtMiddleName: TEdit; Label6: TLabel; edtLastName: TEdit; btnOk: TButton; btnCancel: TButton; ActionList1: TActionList; Ok: TAction; procedure OkUpdate(Sender: TObject); procedure OkExecute(Sender: TObject); procedure FormShow(Sender: TObject); private FIBSecurityService: TIBSecurityService; { Private declarations } procedure RetrieveInfo; public procedure DisplayUser(UserName : String); property SecurityService : TIBSecurityService read FIBSecurityService write FIBSecurityService; { Public declarations } end; var frmUserInformation: TfrmUserInformation; implementation uses frmAdminToolU; {$R *.dfm} { TfrmUserInformation } procedure TfrmUserInformation.DisplayUser(UserName: String); begin SecurityService.Active := true; try if UserName <> '' then begin SecurityService.DisplayUser(UserName); edtUser.Text := SecurityService.UserInfo[0].UserName; edtUser.ReadOnly := true; edtPassword.Text := ''; edtConfirmPassword.Text := ''; edtFirstName.Text := SecurityService.UserInfo[0].FirstName; edtMiddleName.Text := SecurityService.UserInfo[0].MiddleName; edtLastName.Text := SecurityService.UserInfo[0].LastName; SecurityService.SecurityAction := ActionModifyUser; end else begin edtUser.Text := ''; edtUser.ReadOnly := false; edtPassword.Text := ''; edtConfirmPassword.Text := ''; edtFirstName.Text := ''; edtMiddleName.Text := ''; edtLastName.Text := ''; SecurityService.SecurityAction := ActionAddUser; end; finally SecurityService.Active := false; end; end; procedure TfrmUserInformation.RetrieveInfo; begin if edtPassword.Text <> edtConfirmPassword.Text then raise Exception.Create('Passwords do not match'); with SecurityService do begin UserName := edtUser.Text; Password := edtPassword.Text; FirstName := edtFirstName.Text; MiddleName := edtMiddleName.Text; LastName := edtLastName.Text; end; end; procedure TfrmUserInformation.OkUpdate(Sender: TObject); begin TAction(Sender).Enabled := (edtPassword.Text = edtConfirmPassword.Text) and (edtUser.Text <> ''); end; procedure TfrmUserInformation.OkExecute(Sender: TObject); begin RetrieveInfo; SecurityService.Active := true; if SecurityService.SecurityAction = ActionAddUser then SecurityService.AddUser else SecurityService.ModifyUser; SecurityService.Active := false; end; procedure TfrmUserInformation.FormShow(Sender: TObject); begin if edtUser.Text = '' then edtUser.SetFocus else edtPassword.SetFocus; end; end.
unit ExceptionsFormUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, MTLogger, MTUtils; type TMyThread = class(TThread) private LastErrTime: TDateTime; LastErrMsg: string; LastErrClass: string; procedure AddExceptionToGUI; procedure DoUsefullWork; // "Полезная" работа protected procedure Execute; override; end; TExceptionsForm = class(TForm) Button1: TButton; ListBox1: TListBox; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } MyThread: TMyThread; public { Public declarations } procedure AddExceptionToListBox(dt: TDateTime; Msg: string; ErrClass: string); end; var ExceptionsForm: TExceptionsForm; implementation {$R *.dfm} { TMyThread } procedure TMyThread.AddExceptionToGUI; begin ExceptionsForm.AddExceptionToListBox(LastErrTime, LastErrMsg, LastErrClass); end; procedure TMyThread.DoUsefullWork; begin raise Exception.Create('DoUsefullWork - произошла ошибка!'); end; procedure TMyThread.Execute; begin DefLogger.AddToLog('Доп. поток запущен'); while not Terminated do try ThreadWaitTimeout(Self, 5000); if not Terminated then DoUsefullWork; except on E: Exception do begin // Выводим ошибку в лог: DefLogger.AddToLog(Format('%s [%s]', [E.Message, E.ClassName])); // Показываем ошибку пользователю: LastErrTime := Now; LastErrMsg := E.Message; LastErrClass := E.ClassName; Synchronize(AddExceptionToGUI); end; end; DefLogger.AddToLog('Доп. поток остановлен'); end; procedure TExceptionsForm.AddExceptionToListBox(dt: TDateTime; Msg, ErrClass: string); begin Msg := StringReplace(Msg, sLineBreak, ' ', [rfReplaceAll]); ListBox1.Items.Add(Format('%s - %s [%s]', [DateTimeToStr(dt), Msg, ErrClass])); end; procedure TExceptionsForm.Button1Click(Sender: TObject); begin if MyThread = nil then MyThread := TMyThread.Create(False); end; procedure TExceptionsForm.FormCreate(Sender: TObject); begin CreateDefLogger(Application.ExeName + '.log'); DefLogger.AddToLog('Программа запущена'); end; procedure TExceptionsForm.FormDestroy(Sender: TObject); begin MyThread.Free; DefLogger.AddToLog('Программа остановлена'); FreeDefLogger; 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, FMX.ScrollBox, FMX.Memo, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Layouts, Androidapi.JNI.GraphicsContentViewText, System.Messaging; type TForm1 = class(TForm) ScaledLayout1: TScaledLayout; Button1: TButton; Memo1: TMemo; Button2: TButton; procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); private { Private declarations } public { Public declarations } function StartSpeechRecognizer: String; procedure HandleVoiceSearch(Intent: JIntent); procedure IntentCallback(const Sender: TObject; const M: TMessage); end; var Form1: TForm1; implementation {$R *.fmx} uses FMX.Platform.Android, Androidapi.JNI.App, // TJActivity Androidapi.Helpers, Androidapi.JNI.JavaTypes, Androidapi.JNI.Speech; const AppCLASSNAME = 'com.embarcadero.firemonkey.FMXNativeActivity'; // Delphi 的 Android Activity 的 class 名稱 RecognizerRequestCode = 1112; procedure TForm1.Button1Click(Sender: TObject); begin StartSpeechRecognizer; end; procedure TForm1.Button2Click(Sender: TObject); begin Memo1.Lines.Clear; end; procedure TForm1.FormCreate(Sender: TObject); begin TMessageManager.DefaultManager.SubscribeToMessage(TMessageResultNotification, IntentCallback); end; procedure TForm1.HandleVoiceSearch(Intent: JIntent); var guesses: JArrayList; guess: JObject; x: Integer; sData: String; begin guesses := Intent.getStringArrayListExtra (TJRecognizerIntent.JavaClass.EXTRA_RESULTS); for x := 0 to guesses.Size - 1 do begin guess := guesses.get(x); sData := JStringToString(guess.toString); Memo1.Lines.Add(sData); end; end; function GetTextFromRecognizer(Intent: JIntent): string; var guesses: JArrayList; guess: JObject; x: Integer; begin guesses := Intent.getStringArrayListExtra (TJRecognizerIntent.JavaClass.EXTRA_RESULTS); for x := 0 to guesses.Size - 1 do begin guess := guesses.get(x); result := Format('%s%s', [result, JStringToString(guess.toString)]) + sLineBreak; end; Form1.HandleVoiceSearch(Intent); end; function TForm1.StartSpeechRecognizer: String; var Recognizer: JIntent; begin Recognizer := TJIntent.JavaClass.init (TJRecognizerIntent.JavaClass.ACTION_RECOGNIZE_SPEECH); Recognizer.putExtra(TJRecognizerIntent.JavaClass.EXTRA_LANGUAGE_MODEL, TJRecognizerIntent.JavaClass.LANGUAGE_MODEL_FREE_FORM); Recognizer.putExtra(TJRecognizerIntent.JavaClass.EXTRA_PROMPT, StringToJString('請說您的命令!')); Recognizer.putExtra(TJRecognizerIntent.JavaClass.EXTRA_MAX_RESULTS, 10); // default 5 Recognizer.putExtra(TJRecognizerIntent.JavaClass.EXTRA_LANGUAGE, StringToJString('zh-TW')); MainActivity.startActivityForResult(Recognizer, RecognizerRequestCode); end; procedure TForm1.IntentCallback(const Sender: TObject; const M: TMessage); var Notification: TMessageResultNotification; begin Notification := TMessageResultNotification(M); if Notification.ResultCode = TJActivity.JavaClass.RESULT_OK then GetTextFromRecognizer(Notification.Value); end; end.
{ --------------------------------------------------------------- 功能:网络通信类 描述:负责与服务器端交互 版权所有 (C) 2012 神州易桥 作者:李良波 创建时间:2012-06-14 ---------------------------------------------------------------- } unit HttpsUtil; interface uses SysUtils, Classes, IdBaseComponent, IdHTTP; type THttpsUtil = class(TObject) private FIdHTTP: TIdHTTP; FServerUrl: string; procedure Init; public constructor Create; destructor Destroy; override; function Posts(aRequest: string): string; overload; function Posts(aRequest: TStringStream): string; overload; function Get(aURL: string; aResponse: TStream): TStream; end; function HttpUtil: THttpsUtil; implementation uses uINIHelper; var FHttpUtil: THttpsUtil; function HttpUtil: THttpsUtil; begin if not Assigned(FHttpUtil) then FHttpUtil := THttpsUtil.Create; Result := FHttpUtil; end; procedure THttpsUtil.Init; begin FIdHTTP := TIdHTTP.Create(nil); with FIdHTTP do begin HTTPOptions := HTTPOptions + [hoKeepOrigProtocol]; // 关键这行 ProtocolVersion := pv1_1; // 把http版本转化为1.1 Request.Accept := 'image/gif, image/x-xbitmap, image/jpeg, image/pjpeg,' + ' application/x-shockwave-flash, application/vnd.ms-excel,' + ' application/vnd.ms-powerpoint, application/msword,' + ' application/x-ms-application, application/x-ms-xbap,' + ' application/vnd.ms-xpsdocument, application/xaml+xml, */*'; Request.AcceptLanguage := 'zh-cn'; Request.AcceptEncoding := 'gzip, deflate'; Request.Connection := 'Keep-Alive'; Request.CacheControl := 'no-cache'; Request.UserAgent := 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727;' + ' .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152;' + ' .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)'; FIdHTTP.HandleRedirects := True; FIdHTTP.ReadTimeout := 1000 * 30; // 30秒超时 end; //此处需要处理代理设置 // if gSystemLoginAndEditInterCode.SystemInterCodeYesNoExpory then // begin // FIdHTTP.ProxyParams.ProxyServer := // gSystemLoginAndEditInterCode.SystemInterCodeExporyIp; // FIdHTTP.ProxyParams.ProxyPort := StrToInt // (gSystemLoginAndEditInterCode.SystemInterCodeExporyPoint); // FIdHTTP.ProxyParams.ProxyUsername := // gSystemLoginAndEditInterCode.SystemInterCodeExporyUserName; // FIdHTTP.ProxyParams.ProxyPassword := // gSystemLoginAndEditInterCode.SystemInterCodeExporyPwd; // FIdHTTP.ProxyParams.BasicAuthentication := true; // end; end; /// <summary> /// 方法:http Post操作 /// </summary> /// <param name="aRequest">请求内容</param> /// <returns>服务端返回内容</returns> function THttpsUtil.Posts(aRequest: TStringStream): string; var aStream: TStringStream; begin aStream := TStringStream.Create('', TEncoding.UTF8); try FIdHTTP.Post(FServerUrl, aRequest, aStream); Result := aStream.DataString; finally aStream.Free; end; end; /// <summary> /// 方法:http Post操作 /// </summary> /// <param name="aRequest">请求内容</param> /// <returns>服务端返回内容</returns> function THttpsUtil.Posts(aRequest: string): string; var aStream: TStringStream; begin aStream := TStringStream.Create('', TEncoding.UTF8); try aStream.WriteString(aRequest); Result := Posts(aStream); finally aStream.Free; end; end; constructor THttpsUtil.Create; begin inherited; FServerUrl := INI_ReadString(ExtractFilePath(ParamStr(0)) + 'LocalConfig.ini', 'HttpServer', 'Url', ''); Init; end; destructor THttpsUtil.Destroy; begin FreeAndNil(FIdHTTP); inherited; end; /// <summary> /// 方法:http Get 操作 /// </summary> /// <param name="aURL"></param> /// <param name="aResponse"></param> /// <returns></returns> function THttpsUtil.Get(aURL: string; aResponse: TStream): TStream; begin FIdHTTP.Get(aURL, aResponse); Result := aResponse; end; initialization finalization if Assigned(FHttpUtil) then FreeAndNil(FHttpUtil); end.
unit Unit3; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Grids, DBGrids, StdCtrls, Mask, DBCtrls, Buttons; type TForm3 = class(TForm) DBGrid1: TDBGrid; btnCadastrar: TButton; GroupBox1: TGroupBox; Label1: TLabel; txtRamal: TDBEdit; Label2: TLabel; txtSetor: TDBEdit; Label3: TLabel; txtContato: TDBEdit; Label4: TLabel; txtDescricao: TDBEdit; btnEditar: TButton; btnExcluir: TButton; btnSalvar: TButton; btnCancelar: TButton; SpeedButton1: TSpeedButton; Label5: TLabel; nAcesso: TLabel; procedure btnCadastrarClick(Sender: TObject); procedure btnEditarClick(Sender: TObject); procedure btnSalvarClick(Sender: TObject); procedure btnCancelarClick(Sender: TObject); procedure btnExcluirClick(Sender: TObject); procedure SpeedButton1Click(Sender: TObject); procedure txtRamalKeyPress(Sender: TObject; var Key: Char); procedure txtSetorKeyPress(Sender: TObject; var Key: Char); procedure txtContatoKeyPress(Sender: TObject; var Key: Char); procedure txtDescricaoKeyPress(Sender: TObject; var Key: Char); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } public { Public declarations } end; var Form3: TForm3; implementation uses Unit1, Unit2; {$R *.dfm} procedure Habilitar; begin form3.txtRamal.enabled := true; form3.txtSetor.Enabled := true; form3.txtContato.Enabled := true; form3.txtDescricao.Enabled := true; form3.btnCadastrar.Enabled := false; form3.btnEditar.Enabled := false; form3.btnExcluir.Enabled := false; form3.btnSalvar.Enabled := true; form3.btnCancelar.Enabled := true; end; procedure Desabilitar; begin form3.txtRamal.enabled := false; form3.txtSetor.Enabled := false; form3.txtContato.Enabled := false; form3.txtDescricao.Enabled := false; form3.btnCadastrar.Enabled := true; form3.btnEditar.Enabled := true; form3.btnExcluir.Enabled := true; form3.btnSalvar.Enabled := false; form3.btnCancelar.Enabled := false; end; procedure TForm3.btnCadastrarClick(Sender: TObject); begin form1.adoquery1.Append; form2.show; dbgrid1.Enabled := false; speedbutton1.Enabled := false; btnCadastrar.Enabled := false; end; procedure TForm3.btnEditarClick(Sender: TObject); begin habilitar; form1.ADOQuery1.Edit; end; procedure TForm3.btnSalvarClick(Sender: TObject); begin desabilitar; form1.ADOQuery1.Post; end; procedure TForm3.btnCancelarClick(Sender: TObject); begin desabilitar; form1.ADOQuery1.Cancel; end; procedure TForm3.btnExcluirClick(Sender: TObject); begin if messagedlg('Deseja realmente excluir este ramal?', mtWarning, [mbYes,mbNo], 0)= mrYes then begin form1.ADOQuery1.Delete; end; end; procedure TForm3.SpeedButton1Click(Sender: TObject); begin //form1.ADOQuery1.Refresh; form1.Show; form3.Hide; end; procedure TForm3.txtRamalKeyPress(Sender: TObject; var Key: Char); begin if not (Key in ['0'..'9', chr(8)]) then Key:=#0; end; procedure TForm3.txtSetorKeyPress(Sender: TObject; var Key: Char); begin if (Key in [ chr(39)]) then Key:=#0; end; procedure TForm3.txtContatoKeyPress(Sender: TObject; var Key: Char); begin if (Key in [ chr(39)]) then Key:=#0; end; procedure TForm3.txtDescricaoKeyPress(Sender: TObject; var Key: Char); begin if (Key in [ chr(39)]) then Key:=#0; end; procedure TForm3.FormClose(Sender: TObject; var Action: TCloseAction); begin form1.Show; form3.Hide; end; end.
unit Optimizer.LastAccess; interface uses SysUtils, OS.EnvironmentVariable, Optimizer.Template, Global.LanguageString, OS.ProcessOpener; type TLastAccessOptimizer = class(TOptimizationUnit) public function IsOptional: Boolean; override; function IsCompatible: Boolean; override; function IsApplied: Boolean; override; function GetName: String; override; procedure Apply; override; procedure Undo; override; end; implementation function TLastAccessOptimizer.IsOptional: Boolean; begin exit(false); end; function TLastAccessOptimizer.IsCompatible: Boolean; begin exit(true); end; function TLastAccessOptimizer.IsApplied: Boolean; begin result := not (Pos('= 0', string(ProcessOpener.OpenProcWithOutput(EnvironmentVariable.WinDrive, 'FSUTIL behavior query disablelastaccess'))) > 0); end; function TLastAccessOptimizer.GetName: String; begin exit(CapOptLastAccess[CurrLang]); end; procedure TLastAccessOptimizer.Apply; begin ProcessOpener.OpenProcWithOutput( EnvironmentVariable.WinDrive, 'FSUTIL behavior set disablelastaccess 1'); end; procedure TLastAccessOptimizer.Undo; begin ProcessOpener.OpenProcWithOutput( EnvironmentVariable.WinDrive, 'FSUTIL behavior set disablelastaccess 0'); end; end.
unit DragDropHandler; // ----------------------------------------------------------------------------- // Project: Drag and Drop Component Suite. // Module: DragDropHandler // Description: Implements Drop and Drop Context Menu Shell Extenxions // (a.k.a. drag-and-drop handlers). // Version: 4.0 // Date: 18-MAY-2001 // Target: Win32, Delphi 5-6 // Authors: Anders Melander, anders@melander.dk, http://www.melander.dk // Copyright © 1997-2001 Angus Johnson & Anders Melander // ----------------------------------------------------------------------------- interface uses DragDrop, DragDropComObj, DragDropContext, Menus, ShlObj, ActiveX, Windows, Classes; {$include DragDrop.inc} type //////////////////////////////////////////////////////////////////////////////// // // TDragDropHandler // //////////////////////////////////////////////////////////////////////////////// // A typical drag-and-drop handler session goes like this: // 1. User right-drags (drags with the right mouse button) and drops one or more // source files which has a registered drag-and-drop handler. // 2. The shell loads the drag-and-drop handler module. // 3. The shell instantiates the registered drag drop handler object as an // in-process COM server. // 4. The IShellExtInit.Initialize method is called with the name of the target // folder and a data object which contains the dragged data. // The target folder name is stored in the TDragDropHandler.TargetFolder // property as a string and in the TargetPIDL property as a PIDL. // 5. The IContextMenu.QueryContextMenu method is called to populate the popup // menu. // TDragDropHandler uses the PopupMenu property to populate the drag-and-drop // context menu. // 6. If the user chooses one of the context menu items we have supplied, the // IContextMenu.InvokeCommand method is called. // TDragDropHandler locates the corresponding TMenuItem and fires the menu // items OnClick event. // 7. The shell unloads the drag-and-drop handler module (usually after a few // seconds). //////////////////////////////////////////////////////////////////////////////// TDragDropHandler = class(TDropContextMenu, IShellExtInit, IContextMenu) private FFolderPIDL: pItemIDList; protected function GetFolder: string; { IShellExtInit } function Initialize(pidlFolder: PItemIDList; lpdobj: IDataObject; hKeyProgID: HKEY): HResult; stdcall; { IContextMenu } function QueryContextMenu(Menu: HMENU; indexMenu, idCmdFirst, idCmdLast, uFlags: UINT): HResult; stdcall; function InvokeCommand(var lpici: TCMInvokeCommandInfo): HResult; stdcall; function GetCommandString(idCmd, uType: UINT; pwReserved: PUINT; pszName: LPSTR; cchMax: UINT): HResult; stdcall; public destructor Destroy; override; function GetFolderPIDL: pItemIDList; // Caller must free PIDL! property Folder: string read GetFolder; end; //////////////////////////////////////////////////////////////////////////////// // // TDragDropHandlerFactory // //////////////////////////////////////////////////////////////////////////////// // COM Class factory for TDragDropHandler. //////////////////////////////////////////////////////////////////////////////// TDragDropHandlerFactory = class(TDropContextMenuFactory) protected function HandlerRegSubKey: string; override; end; //////////////////////////////////////////////////////////////////////////////// // // Component registration // //////////////////////////////////////////////////////////////////////////////// procedure Register; //////////////////////////////////////////////////////////////////////////////// // // Misc. // //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // // IMPLEMENTATION // //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// implementation uses DragDropFile, DragDropPIDL, Registry, ComObj, SysUtils; //////////////////////////////////////////////////////////////////////////////// // // Component registration // //////////////////////////////////////////////////////////////////////////////// procedure Register; begin RegisterComponents(DragDropComponentPalettePage, [TDragDropHandler]); end; //////////////////////////////////////////////////////////////////////////////// // // Utilities // //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // // TDragDropHandler // //////////////////////////////////////////////////////////////////////////////// destructor TDragDropHandler.Destroy; begin if (FFolderPIDL <> nil) then ShellMalloc.Free(FFolderPIDL); inherited Destroy; end; function TDragDropHandler.GetCommandString(idCmd, uType: UINT; pwReserved: PUINT; pszName: LPSTR; cchMax: UINT): HResult; begin Result := inherited GetCommandString(idCmd, uType, pwReserved, pszName, cchMax); end; function TDragDropHandler.GetFolder: string; begin Result := GetFullPathFromPIDL(FFolderPIDL); end; function TDragDropHandler.GetFolderPIDL: pItemIDList; begin Result := CopyPIDL(FFolderPIDL); end; function TDragDropHandler.InvokeCommand(var lpici: TCMInvokeCommandInfo): HResult; begin Result := E_FAIL; try Result := inherited InvokeCommand(lpici); finally if (Result <> E_FAIL) then begin ShellMalloc.Free(FFolderPIDL); FFolderPIDL := nil; end; end; end; function TDragDropHandler.QueryContextMenu(Menu: HMENU; indexMenu, idCmdFirst, idCmdLast, uFlags: UINT): HResult; begin Result := inherited QueryContextMenu(Menu, indexMenu, idCmdFirst, idCmdLast, uFlags); end; function TDragDropHandler.Initialize(pidlFolder: PItemIDList; lpdobj: IDataObject; hKeyProgID: HKEY): HResult; begin if (pidlFolder <> nil) then begin // Copy target folder PIDL. FFolderPIDL := CopyPIDL(pidlFolder); Result := inherited Initialize(pidlFolder, lpdobj, hKeyProgID); end else Result := E_INVALIDARG; end; //////////////////////////////////////////////////////////////////////////////// // // TDragDropHandlerFactory // //////////////////////////////////////////////////////////////////////////////// function TDragDropHandlerFactory.HandlerRegSubKey: string; begin Result := 'DragDropHandlers'; end; end.
unit uSaveK08Thread; interface uses System.Classes, uGlobal, uEntity, Generics.Collections, uHik, SysUtils, uCommon, IDURI; type TSaveK08Thread = class(TThread) private procedure SaveToK08(imgs: TList<TImageInfo>); procedure ClearImages(imgs: TList<TImageInfo>); protected procedure Execute; override; end; implementation { Important: Methods and properties of objects in visual components can only be used in a method called using Synchronize, for example, Synchronize(UpdateCaption); and UpdateCaption could look like, procedure TSaveK08Thread.UpdateCaption; begin Form1.Caption := 'Updated in a thread'; end; or Synchronize( procedure begin Form1.Caption := 'Updated in thread via an anonymous method' end ) ); where an anonymous method is passed. Similarly, the developer can call the Queue method with similar parameters as above, instead passing another TThread class as the first parameter, putting the calling thread in a queue with the other thread. } { TSaveK08Thread } procedure TSaveK08Thread.Execute; var s, gxsj: String; imgs: TList<TImageInfo>; img: TImageInfo; begin gLogger.Info('SaveK08Thread Start'); gTaskRunning := True; imgs := TList<TImageInfo>.Create; gxsj := FormatDateTime('yyyymmddhh', Now()); try s := 'select a.HPHM, a.GCXH, a.KDBH, a.CDBH, a.GCSJ, a.FWQDZ, a.TP1 from T_KK_VEH_PASSREC a ' + ' inner join S_Device b on a.KDBH = b.SBBH and b.XYSB = 1 and b.QYZT = 1 ' // + ' and Left(a.CJJG, ' + Length(gCJJG).ToString + ') = ' + gCJJG.QuotedString + // +' and left(a.cjjg, 4) = ''4451'' ' + ' and Replace(Replace(convert(varchar(13), a.GXSJ, 120), ''-'', ''''), '' '','''')>=' + gStartTime.QuotedString + ' and convert(varchar(13), a.GXSJ, 120) < convert(varchar(13), getdate(), 120)' + ' and a.hpzl<>''07'' and a.hpzl>'''' and left(FWQDZ, 4) = ''http'' '; gLogger.Info(s); with gSQLHelper.Query(s) do begin gLogger.Info('Pass Record Count: ' + RecordCount.ToString); while not Eof do begin try img := TImageInfo.Create; img.HPHM := FieldByName('HPHM').AsString; img.KDBH := FieldByName('KDBH').AsString; img.GCXH := FieldByName('GCXH').AsString; img.CDBH := FieldByName('CDBH').AsString; img.Url := TIdURI.URLEncode(FieldByName('FWQDZ').AsString + FieldByName('TP1').AsString); img.Url := img.Url.Replace('&', '&amp;'); img.PassTime := FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz', FieldByName('GCSJ').AsDateTime); imgs.Add(img); if imgs.Count > 250 then begin SaveToK08(imgs); end; except on e: Exception do gLogger.Error('Get Pass Info Error ' + e.Message); end; Next; end; Free; end; SaveToK08(imgs); gStartTime := gxsj; TCommon.SaveConfig('Task', 'StartTime', gStartTime); except on e: Exception do gLogger.Error('SaveK08Thread Error ' + e.Message); end; imgs.Free; gTaskRunning := False; gLogger.Info('SaveK08Thread End'); end; procedure TSaveK08Thread.SaveToK08(imgs: TList<TImageInfo>); begin if imgs.Count > 0 then begin try if THik.DFCreateImageJob(imgs) then gLogger.Info('Create K08 Job Succeed') else gLogger.Error('Create K08 Job Failed'); except on e: Exception do gLogger.Error('Create K08 Job Failed ' + e.Message); end; end; ClearImages(imgs); end; procedure TSaveK08Thread.ClearImages(imgs: TList<TImageInfo>); var i: Integer; begin for i := imgs.Count - 1 Downto 0 do imgs[i].Free; imgs.Clear; end; end.
unit uFormMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TForm1 = class(TForm) Memo1: TMemo; Button1: TButton; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); var Comp: TComponent; Str: string; StrList: TStringList; begin for Comp in Self do Memo1.Lines.Add(Comp.Name); Memo1.Lines.Add(''); StrList := TStringList.Create; try StrList.Add('first'); StrList.Add('second'); for Str in StrList do Memo1.Lines.Add(Str); finally FreeAndNil(StrList); end; end; end.
unit SHA256; {SHA256 - 256 bit Secure Hash Function} interface (************************************************************************* DESCRIPTION : SHA256 - 256 bit Secure Hash Function REQUIREMENTS : TP5-7, D1-D7/D9-D10/D12/D17-D18/D25S, FPC, VP EXTERNAL DATA : --- MEMORY USAGE : --- DISPLAY MODE : --- REFERENCES : - Latest specification of Secure Hash Standard: http://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf - Test vectors and intermediate values: http://csrc.nist.gov/groups/ST/toolkit/documents/Examples/SHA_All.pdf Version Date Author Modification ------- -------- ------- ------------------------------------------ 0.1 03.01.02 W.Ehrhardt Reference implementation 0.2 03.01.02 we BP7 optimization 0.21 03.01.02 we TP6 changes 0.3 03.01.02 we Delphi32 optimization 0.4 03.01.02 we with TW32Buf and assignment via RB in SHA256Compress 0.5 07.01.02 we Opt. Delphi UpdateLen 0.6 23.02.02 we Free Pascal compatibility 0.7 03.03.02 we VirtualPascal compatibility 0.71 03.03.02 we FPC with ASM (intel) 0.72 03.03.02 we TP55 compatibility 0.80 23.07.03 we With SHA256File, SHA256Full 0.81 26.07.03 we With SHA256Full in self test, D6+ - warnings 2.00 26.07.03 we common vers., longint for word32, D4+ - warnings 2.01 04.08.03 we type TSHA256Block for HMAC 2.10 29.08.03 we XL versions for Win32 2.20 27.09.03 we FPC/go32v2 2.30 05.10.03 we STD.INC, TP5.0 2.40 10.10.03 we common version, english comments 2.45 11.10.03 we Speedup: Inline for Maj(), Ch() 2.50 17.11.03 we Speedup in update, don't clear W in compress 2.51 20.11.03 we Full range UpdateLen 3.00 01.12.03 we Common version 3.0 3.01 22.12.03 we TP5/5.5: RB, FS inline 3.02 22.12.03 we TP5/5.5: FS -> FS1, FS2 3.03 22,12.03 we Changed UpdateLen: Definition and TP5/5.5 inline 3.04 22.12.03 we TP5/5.5: inline function ISHR 3.05 22.12.03 we ExpandMessageBlocks/BASM 3.06 24.12.03 we FIPS notation: S[] -> A..H, partial unroll 3.07 05.03.04 we Update fips180-2 URL 3.08 26.02.05 we With {$ifdef StrictLong} 3.09 05.05.05 we $R- for StrictLong, D9: errors if $R+ even if warnings off 3.10 17.12.05 we Force $I- in SHA256File 3.11 15.01.06 we uses Hash unit and THashDesc 3.12 15.01.06 we BugFix for 16 bit without BASM 3.13 18.01.06 we Descriptor fields HAlgNum, HSig 3.14 22.01.06 we Removed HSelfTest from descriptor 3.15 11.02.06 we Descriptor as typed const 3.16 07.08.06 we $ifdef BIT32: (const fname: shortstring...) 3.17 22.02.07 we values for OID vector 3.18 30.06.07 we Use conditional define FPC_ProcVar 3.19 04.10.07 we FPC: {$asmmode intel} 3.20 02.05.08 we Bit-API: SHA256FinalBits/Ex 3.21 05.05.08 we THashDesc constant with HFinalBit field 3.22 12.11.08 we Uses BTypes, Ptr2Inc and/or Str255/Str127 3.23 11.03.12 we Updated references 3.24 26.12.12 we D17 and PurePascal 3.25 16.08.15 we Removed $ifdef DLL / stdcall 3.26 15.05.17 we adjust OID to new MaxOIDLen 3.27 29.11.17 we SHA256File - fname: string **************************************************************************) (*------------------------------------------------------------------------- (C) Copyright 2002-2017 Wolfgang Ehrhardt This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ----------------------------------------------------------------------------*) {NOTE: FIPS Ch and May functions can be optimized. Wei Dai (Crypto++ 3.1) credits Rich Schroeppel (rcs@cs.arizona.edu), V 5.1 does not!?} {$i STD.INC} {$ifdef BIT64} {$ifndef PurePascal} {$define PurePascal} {$endif} {$endif} {$define UNROLL} {Speedup for all but TP5/5.5 and maybe VP} {$ifdef VER50} {$undef UNROLL} {Only VER50, VER55 uses UNROLL} {$endif} {$ifdef VirtualPascal} {$undef UNROLL} {$endif} uses BTypes,Hash; procedure SHA256Init(var Context: THashContext); {-initialize context} procedure SHA256Update(var Context: THashContext; Msg: pointer; Len: word); {-update context with Msg data} procedure SHA256UpdateXL(var Context: THashContext; Msg: pointer; Len: longint); {-update context with Msg data} procedure SHA256Final(var Context: THashContext; var Digest: TSHA256Digest); {-finalize SHA256 calculation, clear context} procedure SHA256FinalEx(var Context: THashContext; var Digest: THashDigest); {-finalize SHA256 calculation, clear context} procedure SHA256FinalBitsEx(var Context: THashContext; var Digest: THashDigest; BData: byte; bitlen: integer); {-finalize SHA256 calculation with bitlen bits from BData (big-endian), clear context} procedure SHA256FinalBits(var Context: THashContext; var Digest: TSHA256Digest; BData: byte; bitlen: integer); {-finalize SHA256 calculation with bitlen bits from BData (big-endian), clear context} function SHA256SelfTest: boolean; {-self test for string from SHA256 document} procedure SHA256Full(var Digest: TSHA256Digest; Msg: pointer; Len: word); {-SHA256 of Msg with init/update/final} procedure SHA256FullXL(var Digest: TSHA256Digest; Msg: pointer; Len: longint); {-SHA256 of Msg with init/update/final} procedure SHA256File({$ifdef CONST} const {$endif} fname: string; var Digest: TSHA256Digest; var buf; bsize: word; var Err: word); {-SHA256 of file, buf: buffer with at least bsize bytes} implementation {$ifdef BIT16} {$F-} {$endif} const SHA256_BlockLen = 64; {Internal types for type casting} type TWorkBuf = array[0..63] of longint; {2.16.840.1.101.3.4.2.1} {joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistAlgorithm(4) hashAlgs(2) sha256(1)} const SHA256_OID : TOID_Vec = (2,16,840,1,101,3,4,2,1,-1,-1); {Len=9} {$ifndef VER5X} const SHA256_Desc: THashDesc = ( HSig : C_HashSig; HDSize : sizeof(THashDesc); HDVersion : C_HashVers; HBlockLen : SHA256_BlockLen; HDigestlen: sizeof(TSHA256Digest); {$ifdef FPC_ProcVar} HInit : @SHA256Init; HFinal : @SHA256FinalEx; HUpdateXL : @SHA256UpdateXL; {$else} HInit : SHA256Init; HFinal : SHA256FinalEx; HUpdateXL : SHA256UpdateXL; {$endif} HAlgNum : longint(_SHA256); HName : 'SHA256'; HPtrOID : @SHA256_OID; HLenOID : 9; HFill : 0; {$ifdef FPC_ProcVar} HFinalBit : @SHA256FinalBitsEx; {$else} HFinalBit : SHA256FinalBitsEx; {$endif} HReserved : (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) ); {$else} var SHA256_Desc: THashDesc; {$endif} {$ifndef BIT16} {$ifdef PurePascal} {---------------------------------------------------------------------------} procedure UpdateLen(var whi, wlo: longint; BLen: longint); {-Add BLen to 64 bit value (wlo, whi)} var tmp: int64; begin tmp := int64(cardinal(wlo))+Blen; wlo := longint(tmp and $FFFFFFFF); inc(whi,longint(tmp shr 32)); end; {---------------------------------------------------------------------------} function RB(A: longint): longint; {-reverse byte order in longint} begin RB := ((A and $FF) shl 24) or ((A and $FF00) shl 8) or ((A and $FF0000) shr 8) or ((A and longint($FF000000)) shr 24); end; {$else} {---------------------------------------------------------------------------} function RB(A: longint): longint; assembler; {&frame-} {-reverse byte order in longint} asm {$ifdef LoadArgs} mov eax,[A] {$endif} xchg al,ah rol eax,16 xchg al,ah end; {---------------------------------------------------------------------------} procedure UpdateLen(var whi, wlo: longint; BLen: longint); {-Add BLen to 64 bit value (wlo, whi)} begin asm mov edx, wlo mov ecx, whi mov eax, Blen add [edx], eax adc dword ptr [ecx], 0 end; end; {---------------------------------------------------------------------------} function Sum0(x: longint): longint; assembler; {&frame-} {-Big sigma 0: RotRight(x,2) xor RotRight(x,13) xor RotRight(x,22)} asm {$ifdef LoadArgs} mov eax,[x] {$endif} mov ecx,eax mov edx,eax ror eax,2 ror edx,13 ror ecx,22 xor eax,edx xor eax,ecx end; {---------------------------------------------------------------------------} function Sum1(x: longint): longint; assembler; {&frame-} {-Big sigma 1: RotRight(x,6) xor RotRight(x,11) xor RotRight(x,25)} asm {$ifdef LoadArgs} mov eax,[x] {$endif} mov ecx,eax mov edx,eax ror eax,6 ror edx,11 ror ecx,25 xor eax,edx xor eax,ecx end; {$define USE_ExpandMessageBlocks} {---------------------------------------------------------------------------} procedure ExpandMessageBlocks(var W: TWorkBuf; var Buf: THashBuf32); {-Calculate "expanded message blocks"} begin asm push esi push edi push ebx mov esi,[W] mov edx,[Buf] {part 1: W[i]:= RB(TW32Buf(Buf)[i])} mov ecx,16 @@1: mov eax,[edx] xchg al,ah rol eax,16 xchg al,ah mov [esi],eax add esi,4 add edx,4 dec ecx jnz @@1 {part2: W[i]:= LRot_1(W[i-3] xor W[i-8] xor W[i-14] xor W[i-16]);} mov ecx,48 @@2: mov edi,[esi-7*4] {W[i-7]} mov eax,[esi-2*4] {W[i-2]} mov ebx,eax {Sig1: RR17 xor RR19 xor SRx,10} mov edx,eax ror eax,17 ror edx,19 shr ebx,10 xor eax,edx xor eax,ebx add edi,eax mov eax,[esi-15*4] {W[i-15]} mov ebx,eax {Sig0: RR7 xor RR18 xor SR3} mov edx,eax ror eax,7 ror edx,18 shr ebx,3 xor eax,edx xor eax,ebx add eax,edi add eax,[esi-16*4] {W[i-16]} mov [esi],eax add esi,4 dec ecx jnz @@2 pop ebx pop edi pop esi end; end; {$endif} {$else} {$ifndef BASM16} {TP5/5.5} {$undef USE_ExpandMessageBlocks} {---------------------------------------------------------------------------} procedure UpdateLen(var whi, wlo: longint; BLen: longint); {-Add BLen to 64 bit value (wlo, whi)} inline( $58/ {pop ax } $5A/ {pop dx } $5B/ {pop bx } $07/ {pop es } $26/$01/$07/ {add es:[bx],ax } $26/$11/$57/$02/ {adc es:[bx+02],dx} $5B/ {pop bx } $07/ {pop es } $26/$83/$17/$00/ {adc es:[bx],0 } $26/$83/$57/$02/$00);{adc es:[bx+02],0 } {---------------------------------------------------------------------------} function RB(A: longint): longint; {-reverse byte order in longint} inline( $58/ { pop ax } $5A/ { pop dx } $86/$C6/ { xchg dh,al} $86/$E2); { xchg dl,ah} {---------------------------------------------------------------------------} function FS1(x: longint; c: integer): longint; {-Rotate x right, c<=16!!} inline( $59/ { pop cx } $58/ { pop ax } $5A/ { pop dx } $8B/$DA/ { mov bx,dx} $D1/$EB/ {L:shr bx,1 } $D1/$D8/ { rcr ax,1 } $D1/$DA/ { rcr dx,1 } $49/ { dec cx } $75/$F7); { jne L } {---------------------------------------------------------------------------} function FS2(x: longint; c: integer): longint; {-Rotate x right, c+16, c<16!!} inline( $59/ { pop cx } $5A/ { pop dx } $58/ { pop ax } $8B/$DA/ { mov bx,dx} $D1/$EB/ {L:shr bx,1 } $D1/$D8/ { rcr ax,1 } $D1/$DA/ { rcr dx,1 } $49/ { dec cx } $75/$F7); { jne L } {---------------------------------------------------------------------------} function ISHR(x: longint; c: integer): longint; {-Shift x right} inline( $59/ { pop cx } $58/ { pop ax } $5A/ { pop dx } $D1/$EA/ {L:shr dx,1 } $D1/$D8/ { rcr ax,1 } $49/ { dec cx } $75/$F9); { jne L } {---------------------------------------------------------------------------} function Sig0(x: longint): longint; {-Small sigma 0} begin Sig0 := FS1(x,7) xor FS2(x,18-16) xor ISHR(x,3); end; {---------------------------------------------------------------------------} function Sig1(x: longint): longint; {-Small sigma 1} begin Sig1 := FS2(x,17-16) xor FS2(x,19-16) xor ISHR(x,10); end; {---------------------------------------------------------------------------} function Sum0(x: longint): longint; {-Big sigma 0} begin Sum0 := FS1(x,2) xor FS1(x,13) xor FS2(x,22-16); end; {---------------------------------------------------------------------------} function Sum1(x: longint): longint; {-Big sigma 1} begin Sum1 := FS1(x,6) xor FS1(x,11) xor FS2(x,25-16); end; {$else} {TP 6/7/Delphi1 for 386+} {---------------------------------------------------------------------------} procedure UpdateLen(var whi, wlo: longint; BLen: longint); assembler; {-Add BLen to 64 bit value (wlo, whi)} asm les di,[wlo] db $66; mov ax,word ptr [BLen] db $66; sub dx,dx db $66; add es:[di],ax les di,[whi] db $66; adc es:[di],dx end; {---------------------------------------------------------------------------} function RB(A: longint): longint; assembler; {-reverse byte order in longint} asm mov ax,word ptr [A] mov dx,word ptr [A+2] xchg al,dh xchg ah,dl end; {---------------------------------------------------------------------------} function Sum0(x: longint): longint; assembler; {-Big sigma 0: RotRight(x,2) xor RotRight(x,13) xor RotRight(x,22)} asm db $66; mov ax,word ptr x db $66; mov bx,ax db $66; mov dx,ax db $66; ror ax,2 db $66; ror dx,13 db $66; ror bx,22 db $66; xor ax,dx db $66; xor ax,bx db $66; mov dx,ax db $66; shr dx,16 end; {---------------------------------------------------------------------------} function Sum1(x: longint): longint; assembler; {-Big sigma 1: RotRight(x,6) xor RotRight(x,11) xor RotRight(x,25)} asm db $66; mov ax,word ptr x db $66; mov bx,ax db $66; mov dx,ax db $66; ror ax,6 db $66; ror dx,11 db $66; ror bx,25 db $66; xor ax,dx db $66; xor ax,bx db $66; mov dx,ax db $66; shr dx,16 end; {$define USE_ExpandMessageBlocks} {---------------------------------------------------------------------------} procedure ExpandMessageBlocks(var W: TWorkBuf; var Buf: THashBuf32); assembler; {-Calculate "expanded message blocks"} asm push ds {part 1: W[i]:= RB(TW32Buf(Buf)[i])} les di,[Buf] lds si,[W] mov cx,16 @@1: db $66; mov ax,es:[di] xchg al,ah db $66; rol ax,16 xchg al,ah db $66; mov [si],ax add si,4 add di,4 dec cx jnz @@1 {part 2: W[i]:= Sig1(W[i-2]) + W[i-7] + Sig0(W[i-15]) + W[i-16];} mov cx,48 @@2: db $66; mov di,[si-7*4] {W[i-7]} db $66; mov ax,[si-2*4] {W[i-2]} db $66; mov bx,ax {Sig1: RR17 xor RR19 xor SRx,10} db $66; mov dx,ax db $66; ror ax,17 db $66; ror dx,19 db $66; shr bx,10 db $66; xor ax,dx db $66; xor ax,bx db $66; add di,ax db $66; mov ax,[si-15*4] {W[i-15]} db $66; mov bx,ax {Sig0: RR7 xor RR18 xor SR3} db $66; mov dx,ax db $66; ror ax,7 db $66; ror dx,18 db $66; shr bx,3 db $66; xor ax,dx db $66; xor ax,bx db $66; add ax,di db $66; add ax,[si-16*4] {W[i-16]} db $66; mov [si],ax add si,4 dec cx jnz @@2 pop ds end; {$endif BASM16} {$endif BIT16} {$ifdef PurePascal} {---------------------------------------------------------------------------} procedure SHA256Compress(var Data: THashContext); {-Actual hashing function} var i: integer; T, A, B, C, D, E, F, G, H: longint; W: TWorkBuf; const {$ifdef StrictLong} {$warnings off} {$R-} {avoid D9 errors!} {$endif} K: array[0..63] of longint = ( $428a2f98, $71374491, $b5c0fbcf, $e9b5dba5, $3956c25b, $59f111f1, $923f82a4, $ab1c5ed5, $d807aa98, $12835b01, $243185be, $550c7dc3, $72be5d74, $80deb1fe, $9bdc06a7, $c19bf174, $e49b69c1, $efbe4786, $0fc19dc6, $240ca1cc, $2de92c6f, $4a7484aa, $5cb0a9dc, $76f988da, $983e5152, $a831c66d, $b00327c8, $bf597fc7, $c6e00bf3, $d5a79147, $06ca6351, $14292967, $27b70a85, $2e1b2138, $4d2c6dfc, $53380d13, $650a7354, $766a0abb, $81c2c92e, $92722c85, $a2bfe8a1, $a81a664b, $c24b8b70, $c76c51a3, $d192e819, $d6990624, $f40e3585, $106aa070, $19a4c116, $1e376c08, $2748774c, $34b0bcb5, $391c0cb3, $4ed8aa4a, $5b9cca4f, $682e6ff3, $748f82ee, $78a5636f, $84c87814, $8cc70208, $90befffa, $a4506ceb, $bef9a3f7, $c67178f2 ); {$ifdef StrictLong} {$warnings on} {$ifdef RangeChecks_on} {$R+} {$endif} {$endif} begin {-Calculate "expanded message blocks"} {Part 1: Transfer buffer with little -> big endian conversion} for i:= 0 to 15 do W[i] := RB(THashBuf32(Data.Buffer)[i]); {Part 2: Calculate remaining "expanded message blocks"} for i:= 16 to 63 do begin {A=Sig1(W[i-2]), B=Sig0(W[i-15])} A := W[i-2]; A := ((A shr 17) or (A shl 15)) xor ((A shr 19) or (A shl 13)) xor (A shr 10); B := W[i-15]; B := ((B shr 7) or (B shl 25)) xor ((B shr 18) or (B shl 14)) xor (B shr 3); W[i]:= A + W[i-7] + B + W[i-16]; end; {Assign old working hasg to variables A..H} A := Data.Hash[0]; B := Data.Hash[1]; C := Data.Hash[2]; D := Data.Hash[3]; E := Data.Hash[4]; F := Data.Hash[5]; G := Data.Hash[6]; H := Data.Hash[7]; {SHA256 compression function} {partially unrolled loop} i := 0; repeat T := H + (((E shr 6) or (E shl 26)) xor ((E shr 11) or (E shl 21)) xor ((E shr 25) or (E shl 7))) + (((F xor G) and E) xor G) + W[i ] + K[i ]; H := T + (((A shr 2) or (A shl 30)) xor ((A shr 13) or (A shl 19)) xor ((A shr 22) or (A shl 10))) + (((A or B) and C) or (A and B)); inc(D,T); T := G + (((D shr 6) or (D shl 26)) xor ((D shr 11) or (D shl 21)) xor ((D shr 25) or (D shl 7))) + (((E xor F) and D) xor F) + W[i+1] + K[i+1]; G := T + (((H shr 2) or (H shl 30)) xor ((H shr 13) or (H shl 19)) xor ((H shr 22) or (H shl 10))) + (((H or A) and B) or (H and A)); inc(C,T); T := F + (((C shr 6) or (C shl 26)) xor ((C shr 11) or (C shl 21)) xor ((C shr 25) or (C shl 7))) + (((D xor E) and C) xor E) + W[i+2] + K[i+2]; F := T + (((G shr 2) or (G shl 30)) xor ((G shr 13) or (G shl 19)) xor ((G shr 22) or (G shl 10))) + (((G or H) and A) or (G and H)); inc(B,T); T := E + (((B shr 6) or (B shl 26)) xor ((B shr 11) or (B shl 21)) xor ((B shr 25) or (B shl 7))) + (((C xor D) and B) xor D) + W[i+3] + K[i+3]; E := T + (((F shr 2) or (F shl 30)) xor ((F shr 13) or (F shl 19)) xor ((F shr 22) or (F shl 10))) + (((F or G) and H) or (F and G)); inc(A,T); T := D + (((A shr 6) or (A shl 26)) xor ((A shr 11) or (A shl 21)) xor ((A shr 25) or (A shl 7))) + (((B xor C) and A) xor C) + W[i+4] + K[i+4]; D := T + (((E shr 2) or (E shl 30)) xor ((E shr 13) or (E shl 19)) xor ((E shr 22) or (E shl 10))) + (((E or F) and G) or (E and F)); inc(H,T); T := C + (((H shr 6) or (H shl 26)) xor ((H shr 11) or (H shl 21)) xor ((H shr 25) or (H shl 7))) + (((A xor B) and H) xor B) + W[i+5] + K[i+5]; C := T + (((D shr 2) or (D shl 30)) xor ((D shr 13) or (D shl 19)) xor ((D shr 22) or (D shl 10))) + (((D or E) and F) or (D and E)); inc(G,T); T := B + (((G shr 6) or (G shl 26)) xor ((G shr 11) or (G shl 21)) xor ((G shr 25) or (G shl 7))) + (((H xor A) and G) xor A) + W[i+6] + K[i+6]; B := T + (((C shr 2) or (C shl 30)) xor ((C shr 13) or (C shl 19)) xor ((C shr 22) or (C shl 10))) + (((C or D) and E) or (C and D)); inc(F,T); T := A + (((F shr 6) or (F shl 26)) xor ((F shr 11) or (F shl 21)) xor ((F shr 25) or (F shl 7))) + (((G xor H) and F) xor H) + W[i+7] + K[i+7]; A := T + (((B shr 2) or (B shl 30)) xor ((B shr 13) or (B shl 19)) xor ((B shr 22) or (B shl 10))) + (((B or C) and D) or (B and C)); inc(E,T); inc(i,8) until i>63; {Calculate new working hash} inc(Data.Hash[0],A); inc(Data.Hash[1],B); inc(Data.Hash[2],C); inc(Data.Hash[3],D); inc(Data.Hash[4],E); inc(Data.Hash[5],F); inc(Data.Hash[6],G); inc(Data.Hash[7],H); end; {$else} {---------------------------------------------------------------------------} procedure SHA256Compress(var Data: THashContext); {-Actual hashing function} var i: integer; {$ifdef UNROLL} T, {$else} T1,T2: longint; {$endif} A, B, C, D, E, F, G, H: longint; W: TWorkBuf; const {$ifdef StrictLong} {$warnings off} {$R-} {avoid D9 errors!} {$endif} K: array[0..63] of longint = ( $428a2f98, $71374491, $b5c0fbcf, $e9b5dba5, $3956c25b, $59f111f1, $923f82a4, $ab1c5ed5, $d807aa98, $12835b01, $243185be, $550c7dc3, $72be5d74, $80deb1fe, $9bdc06a7, $c19bf174, $e49b69c1, $efbe4786, $0fc19dc6, $240ca1cc, $2de92c6f, $4a7484aa, $5cb0a9dc, $76f988da, $983e5152, $a831c66d, $b00327c8, $bf597fc7, $c6e00bf3, $d5a79147, $06ca6351, $14292967, $27b70a85, $2e1b2138, $4d2c6dfc, $53380d13, $650a7354, $766a0abb, $81c2c92e, $92722c85, $a2bfe8a1, $a81a664b, $c24b8b70, $c76c51a3, $d192e819, $d6990624, $f40e3585, $106aa070, $19a4c116, $1e376c08, $2748774c, $34b0bcb5, $391c0cb3, $4ed8aa4a, $5b9cca4f, $682e6ff3, $748f82ee, $78a5636f, $84c87814, $8cc70208, $90befffa, $a4506ceb, $bef9a3f7, $c67178f2 ); {$ifdef StrictLong} {$warnings on} {$ifdef RangeChecks_on} {$R+} {$endif} {$endif} begin {-Calculate "expanded message blocks"} {$ifdef USE_ExpandMessageBlocks} {Use BASM-Code} ExpandMessageBlocks(W, THashBuf32(Data.Buffer)); {$else} {Avoid proc call overhead for TP5/5.5} {Part 1: Transfer buffer with little -> big endian conversion} for i:= 0 to 15 do W[i]:= RB(THashBuf32(Data.Buffer)[i]); {Part 2: Calculate remaining "expanded message blocks"} for i:= 16 to 63 do W[i]:= Sig1(W[i-2]) + W[i-7] + Sig0(W[i-15]) + W[i-16]; {$endif} {Assign old working hasg to variables A..H} A := Data.Hash[0]; B := Data.Hash[1]; C := Data.Hash[2]; D := Data.Hash[3]; E := Data.Hash[4]; F := Data.Hash[5]; G := Data.Hash[6]; H := Data.Hash[7]; {SHA256 compression function} {$ifdef UNROLL} {partially unrolled loop} i := 0; repeat T := H + Sum1(E) + (((F xor G) and E) xor G) + W[i ] + K[i ]; H := T + Sum0(A) + (((A or B) and C) or (A and B)); inc(D,T); T := G + Sum1(D) + (((E xor F) and D) xor F) + W[i+1] + K[i+1]; G := T + Sum0(H) + (((H or A) and B) or (H and A)); inc(C,T); T := F + Sum1(C) + (((D xor E) and C) xor E) + W[i+2] + K[i+2]; F := T + Sum0(G) + (((G or H) and A) or (G and H)); inc(B,T); T := E + Sum1(B) + (((C xor D) and B) xor D) + W[i+3] + K[i+3]; E := T + Sum0(F) + (((F or G) and H) or (F and G)); inc(A,T); T := D + Sum1(A) + (((B xor C) and A) xor C) + W[i+4] + K[i+4]; D := T + Sum0(E) + (((E or F) and G) or (E and F)); inc(H,T); T := C + Sum1(H) + (((A xor B) and H) xor B) + W[i+5] + K[i+5]; C := T + Sum0(D) + (((D or E) and F) or (D and E)); inc(G,T); T := B + Sum1(G) + (((H xor A) and G) xor A) + W[i+6] + K[i+6]; B := T + Sum0(C) + (((C or D) and E) or (C and D)); inc(F,T); T := A + Sum1(F) + (((G xor H) and F) xor H) + W[i+7] + K[i+7]; A := T + Sum0(B) + (((B or C) and D) or (B and C)); inc(E,T); inc(i,8) until i>63; {$else} for i:=0 to 63 do begin T1:= H + Sum1(E) + (((F xor G) and E) xor G) + K[i] + W[i]; T2:= Sum0(A) + (((A or B) and C) or (A and B)); H := G; G := F; F := E; E := D + T1; D := C; C := B; B := A; A := T1 + T2; end; {$endif} {Calculate new working hash} inc(Data.Hash[0],A); inc(Data.Hash[1],B); inc(Data.Hash[2],C); inc(Data.Hash[3],D); inc(Data.Hash[4],E); inc(Data.Hash[5],F); inc(Data.Hash[6],G); inc(Data.Hash[7],H); end; {$endif} {---------------------------------------------------------------------------} procedure SHA256Init(var Context: THashContext); {-initialize context} {$ifdef StrictLong} {$warnings off} {$R-} {avoid D9 errors!} {$endif} const SIV: array[0..7] of longint = ($6a09e667, $bb67ae85, $3c6ef372, $a54ff53a, $510e527f, $9b05688c, $1f83d9ab, $5be0cd19); {$ifdef StrictLong} {$warnings on} {$ifdef RangeChecks_on} {$R+} {$endif} {$endif} begin {Clear context, buffer=0!!} fillchar(Context,sizeof(Context),0); move(SIV,Context.Hash,sizeof(SIV)); end; {---------------------------------------------------------------------------} procedure SHA256UpdateXL(var Context: THashContext; Msg: pointer; Len: longint); {-update context with Msg data} var i: integer; begin {Update message bit length} if Len<=$1FFFFFFF then UpdateLen(Context.MLen[1], Context.MLen[0], Len shl 3) else begin for i:=1 to 8 do UpdateLen(Context.MLen[1], Context.MLen[0], Len) end; while Len > 0 do begin {fill block with msg data} Context.Buffer[Context.Index]:= pByte(Msg)^; inc(Ptr2Inc(Msg)); inc(Context.Index); dec(Len); if Context.Index=SHA256_BlockLen then begin {If 512 bit transferred, compress a block} Context.Index:= 0; SHA256Compress(Context); while Len>=SHA256_BlockLen do begin move(Msg^,Context.Buffer,SHA256_BlockLen); SHA256Compress(Context); inc(Ptr2Inc(Msg),SHA256_BlockLen); dec(Len,SHA256_BlockLen); end; end; end; end; {---------------------------------------------------------------------------} procedure SHA256Update(var Context: THashContext; Msg: pointer; Len: word); {-update context with Msg data} begin SHA256UpdateXL(Context, Msg, Len); end; {---------------------------------------------------------------------------} procedure SHA256FinalBitsEx(var Context: THashContext; var Digest: THashDigest; BData: byte; bitlen: integer); {-finalize SHA256 calculation with bitlen bits from BData (big-endian), clear context} var i: integer; begin {Message padding} {append bits from BData and a single '1' bit} if (bitlen>0) and (bitlen<=7) then begin Context.Buffer[Context.Index]:= (BData and BitAPI_Mask[bitlen]) or BitAPI_PBit[bitlen]; UpdateLen(Context.MLen[1], Context.MLen[0], bitlen); end else Context.Buffer[Context.Index]:= $80; for i:=Context.Index+1 to 63 do Context.Buffer[i] := 0; {2. Compress if more than 448 bits, (no room for 64 bit length} if Context.Index>= 56 then begin SHA256Compress(Context); fillchar(Context.Buffer,56,0); end; {Write 64 bit msg length into the last bits of the last block} {(in big endian format) and do a final compress} THashBuf32(Context.Buffer)[14]:= RB(Context.MLen[1]); THashBuf32(Context.Buffer)[15]:= RB(Context.MLen[0]); SHA256Compress(Context); {Hash -> Digest to little endian format} for i:=0 to 7 do THashDig32(Digest)[i]:= RB(Context.Hash[i]); {Clear context} fillchar(Context,sizeof(Context),0); end; {---------------------------------------------------------------------------} procedure SHA256FinalBits(var Context: THashContext; var Digest: TSHA256Digest; BData: byte; bitlen: integer); {-finalize SHA256 calculation with bitlen bits from BData (big-endian), clear context} var tmp: THashDigest; begin SHA256FinalBitsEx(Context, tmp, BData, bitlen); move(tmp, Digest, sizeof(Digest)); end; {---------------------------------------------------------------------------} procedure SHA256FinalEx(var Context: THashContext; var Digest: THashDigest); {-finalize SHA256 calculation, clear context} begin SHA256FinalBitsEx(Context,Digest,0,0); end; {---------------------------------------------------------------------------} procedure SHA256Final(var Context: THashContext; var Digest: TSHA256Digest); {-finalize SHA256 calculation, clear context} var tmp: THashDigest; begin SHA256FinalBitsEx(Context, tmp, 0, 0); move(tmp, Digest, sizeof(Digest)); end; {---------------------------------------------------------------------------} function SHA256SelfTest: boolean; {-self test for string from SHA256 document} const s1: string[ 3] = 'abc'; s2: string[56] = 'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'; D1: TSHA256Digest = ($ba,$78,$16,$bf,$8f,$01,$cf,$ea,$41,$41,$40,$de,$5d,$ae,$22,$23, $b0,$03,$61,$a3,$96,$17,$7a,$9c,$b4,$10,$ff,$61,$f2,$00,$15,$ad); D2: TSHA256Digest = ($24,$8d,$6a,$61,$d2,$06,$38,$b8,$e5,$c0,$26,$93,$0c,$3e,$60,$39, $a3,$3c,$e4,$59,$64,$ff,$21,$67,$f6,$ec,$ed,$d4,$19,$db,$06,$c1); D3: TSHA256Digest = ($bd,$4f,$9e,$98,$be,$b6,$8c,$6e,$ad,$32,$43,$b1,$b4,$c7,$fe,$d7, $5f,$a4,$fe,$aa,$b1,$f8,$47,$95,$cb,$d8,$a9,$86,$76,$a2,$a3,$75); D4: TSHA256Digest = ($f1,$54,$1d,$eb,$68,$d1,$34,$eb,$a9,$9f,$82,$cf,$d8,$7e,$2a,$b3, $1d,$33,$af,$4b,$6d,$e0,$08,$6a,$9b,$ed,$15,$c2,$ec,$69,$cc,$cb); var Context: THashContext; Digest : TSHA256Digest; function SingleTest(s: Str127; TDig: TSHA256Digest): boolean; {-do a single test, const not allowed for VER<7} { Two sub tests: 1. whole string, 2. one update per char} var i: integer; begin SingleTest := false; {1. Hash complete string} SHA256Full(Digest, @s[1],length(s)); {Compare with known value} if not HashSameDigest(@SHA256_Desc, PHashDigest(@Digest), PHashDigest(@TDig)) then exit; {2. one update call for all chars} SHA256Init(Context); for i:=1 to length(s) do SHA256Update(Context,@s[i],1); SHA256Final(Context,Digest); {Compare with known value} if not HashSameDigest(@SHA256_Desc, PHashDigest(@Digest), PHashDigest(@TDig)) then exit; SingleTest := true; end; begin SHA256SelfTest := false; {1 Zero bit from NESSIE test vectors} SHA256Init(Context); SHA256FinalBits(Context,Digest,0,1); if not HashSameDigest(@SHA256_Desc, PHashDigest(@Digest), PHashDigest(@D3)) then exit; {4 hightest bits of $50, D4 calculated with program shatest from RFC 4634} SHA256Init(Context); SHA256FinalBits(Context,Digest,$50,4); if not HashSameDigest(@SHA256_Desc, PHashDigest(@Digest), PHashDigest(@D4)) then exit; {strings from SHA256 document} SHA256SelfTest := SingleTest(s1, D1) and SingleTest(s2, D2) end; {---------------------------------------------------------------------------} procedure SHA256FullXL(var Digest: TSHA256Digest; Msg: pointer; Len: longint); {-SHA256 of Msg with init/update/final} var Context: THashContext; begin SHA256Init(Context); SHA256UpdateXL(Context, Msg, Len); SHA256Final(Context, Digest); end; {---------------------------------------------------------------------------} procedure SHA256Full(var Digest: TSHA256Digest; Msg: pointer; Len: word); {-SHA256 of Msg with init/update/final} begin SHA256FullXL(Digest, Msg, Len); end; {---------------------------------------------------------------------------} procedure SHA256File({$ifdef CONST} const {$endif} fname: string; var Digest: TSHA256Digest; var buf; bsize: word; var Err: word); {-SHA256 of file, buf: buffer with at least bsize bytes} var tmp: THashDigest; begin HashFile(fname, @SHA256_Desc, tmp, buf, bsize, Err); move(tmp,Digest,sizeof(Digest)); end; begin {$ifdef VER5X} fillchar(SHA256_Desc, sizeof(SHA256_Desc), 0); with SHA256_Desc do begin HSig := C_HashSig; HDSize := sizeof(THashDesc); HDVersion := C_HashVers; HBlockLen := SHA256_BlockLen; HDigestlen:= sizeof(TSHA256Digest); HInit := SHA256Init; HFinal := SHA256FinalEx; HUpdateXL := SHA256UpdateXL; HAlgNum := longint(_SHA256); HName := 'SHA256'; HPtrOID := @SHA256_OID; HLenOID := 9; HFinalBit := SHA256FinalBitsEx; end; {$endif} RegisterHash(_SHA256, @SHA256_Desc); end.
unit Rx; interface uses SysUtils, Generics.Collections, Generics.Defaults; type TimeUnit = ( MILLISECONDS = 0, SECONDS = 1, MINUTES = 2 ); IAction = interface procedure Emit; end; IScheduler = interface procedure Invoke(Action: IAction); end; StdSchedulers = record type ICurrentThreadScheduler = interface(IScheduler) ['{FAE0EAE9-8A6A-4675-9BCE-EC954396CABE}'] end; IMainThreadScheduler = interface(IScheduler) ['{C35C921D-6D92-44F1-9040-02D57946EBD8}'] end; ISeparateThreadScheduler = interface(IScheduler) ['{16C38E93-85C0-4E36-B115-81270BCD72FE}'] end; INewThreadScheduler = interface(IScheduler) ['{BAA742F7-A5A4-44DF-81E7-7592FC9E454E}'] end; IThreadPoolScheduler = interface(IScheduler) ['{6501AB55-3F4D-4185-B926-2BE3FB697F63}'] end; const IMMEDIATE = 0; public class function CreateCurrentThreadScheduler: ICurrentThreadScheduler; static; class function CreateMainThreadScheduler: IMainThreadScheduler; static; class function CreateSeparateThreadScheduler: ISeparateThreadScheduler; static; class function CreateNewThreadScheduler: INewThreadScheduler; static; class function CreateThreadPoolScheduler(PoolSize: Integer): IThreadPoolScheduler; static; end; /// <summary> /// Error descriptor interface /// </summary> IThrowable = interface function GetCode: Integer; function GetClass: TClass; function GetMessage: string; function GetStackTrace: string; function ToString: string; end; /// <summary> /// Used for controlling back-pressure mechanism /// producer-consumer /// </summary> IProducer = interface procedure Request(N: LongWord); end; /// <summary> /// Base Observer interface /// </summary> IObserver<T> = interface procedure OnNext(const A: T); procedure OnError(E: IThrowable); procedure OnCompleted; end; TSmartVariable<T> = record strict private FValue: T; FDefValue: T; FObjRef: IInterface; class function IsObject: Boolean; static; public constructor Create(const A: T); class operator Implicit(A: TSmartVariable<T>): T; class operator Implicit(A: T): TSmartVariable<T>; class operator Equal(A, B: TSmartVariable<T>): Boolean; function Get: T; procedure Clear; end; TZip<X, Y> = class strict private FAHolder: TSmartVariable<X>; FBHolder: TSmartVariable<Y>; function GetA: X; function GetB: Y; public constructor Create(const A: X; const B: Y); destructor Destroy; override; property A: X read GetA; property B: Y read GetB; end; ISubscription = interface procedure Unsubscribe; function IsUnsubscribed: Boolean; procedure SetProducer(P: IProducer); end; ISubscriber<T> = interface(IObserver<T>) procedure Unsubscribe; function IsUnsubscribed: Boolean; procedure SetProducer(P: IProducer); end; TOnNext<T> = reference to procedure(const A: T); TOnCompleted = reference to procedure; TOnError = reference to procedure(E: IThrowable); /// <summary> /// Observable is associated to data stream, /// developer may choice comfortable scheduler /// </summary> IObservable<T> = interface function Subscribe(const OnNext: TOnNext<T>): ISubscription; overload; function Subscribe(const OnNext: TOnNext<T>; const OnError: TOnError): ISubscription; overload; function Subscribe(const OnNext: TOnNext<T>; const OnError: TOnError; const OnCompleted: TOnCompleted): ISubscription; overload; function Subscribe(const OnNext: TOnNext<T>; const OnCompleted: TOnCompleted): ISubscription; overload; function Subscribe(const OnError: TOnError): ISubscription; overload; function Subscribe(const OnCompleted: TOnCompleted): ISubscription; overload; function Subscribe(A: ISubscriber<T>): ISubscription; overload; procedure OnNext(const Data: T); procedure OnError(E: IThrowable); procedure OnCompleted; procedure ScheduleOn(Scheduler: IScheduler); procedure SubscribeOn(Scheduler: IScheduler); procedure SetName(const Value: string); function WaitCompletition(const Timeout: LongWord): Boolean; end; TFilter<T> = reference to function(const A: T): Boolean; TFilterStatic<T> = function(const A: T): Boolean; TMap<X, Y> = reference to function(const Data: X): Y; TMapStatic<X, Y> = function(const Data: X): Y; TOnSubscribe<T> = reference to procedure(O: IObserver<T>); TOnSubscribe2<T> = reference to procedure(O: ISubscriber<T>); TFlatMap<X, Y> = reference to function(const Data: X): IObservable<Y>; TFlatMapStatic<X, Y> = function(const Data: X): IObservable<Y>; TFlatMapIterable<T> = reference to function(const Data: T): IObservable<T>; TFlatMapIterableStatic<T> = reference to function(const Data: T): IObservable<T>; TDefer<T> = reference to function: IObservable<T>; TArrayOfRefs = array of IInterface; TScanRoutine<CTX, T> = reference to procedure(var Context: CTX; const Value: T); TReduceRoutine<ACCUM, T> = reference to function(const A: ACCUM; const Value: T): ACCUM; TCollectAction1<ITEM, T> = reference to procedure(const List: TList<ITEM>; const Value: T); TCollectAction2<KEY, ITEM, T> = reference to procedure(const Dict: TDictionary<KEY, ITEM>; const Value: T); IFlatMapObservable<X, Y> = interface(IObservable<Y>) procedure Spawn(const Routine: TFlatMap<X, Y>); overload; procedure Spawn(const Routine: TFlatMapStatic<X, Y>); overload; procedure SetMaxConcurrency(Value: Integer); end; IFlatMapIterableObservable<T> = interface(IObservable<T>) procedure Spawn(const Routine: TFlatMapIterable<T>); overload; procedure Spawn(const Routine: TFlatMapIterableStatic<T>); overload; procedure SetMaxConcurrency(Value: Integer); end; /// <summary> /// Abstract data flow, that give ability to get powerfull set of /// operations and data type transformation. /// /// - Avoid single data approach, keep in mind data streams /// - implicit infrastructure, including Garbage collector for class instances /// giving ability to spend low time for developing scalable multithreading /// code /// /// </summary> TObservable<T> = record type TList = TList<T>; strict private Impl: IObservable<T>; Refs: TArrayOfRefs; FlatStreams: TArrayOfRefs; FFlatStreamKeys: array of string; FlatIterable: IFlatMapIterableObservable<T>; function GetImpl: IObservable<T>; function GetFlatStream<Y>: IFlatMapObservable<T, Y>; function GetFlatIterable: IFlatMapIterableObservable<T>; public /// <summary> /// <para> /// OnSubscribe run on every new Subscription /// </para> /// <para> /// Powerfull method of Observable creation /// </para> /// </summary> constructor Create(const OnSubscribe: TOnSubscribe<T>); overload; constructor Create(const OnSubscribe: TOnSubscribe2<T>); overload; /// <summary> /// Make Observable, that raise pre-known data sequence /// </summary> constructor Just(const Items: array of TSmartVariable<T>); overload; /// <summary> /// Make Observable, that raise OnCompleted and nothing else /// </summary> class function Empty: TObservable<T>; static; /// <summary> /// Defer don't make new observable, but give ability to /// define creation mechanism in the future, when any subscriber will appear /// </summary> constructor Defer(const Routine: TDefer<T>); /// <summary> /// Just sort of Observable will never raise anithing (usefull for testing purposes). /// </summary> class function Never: TObservable<T>; static; /// <summary> /// Merge N data streams /// </summary> constructor Merge(var O1, O2: TObservable<T>); overload; constructor Merge(var O1, O2, O3: TObservable<T>); overload; function Subscribe(const OnNext: TOnNext<T>): ISubscription; overload; function Subscribe(const OnNext: TOnNext<T>; const OnError: TOnError): ISubscription; overload; function Subscribe(const OnNext: TOnNext<T>; const OnError: TOnError; const OnCompleted: TOnCompleted): ISubscription; overload; function Subscribe(const OnNext: TOnNext<T>; const OnCompleted: TOnCompleted): ISubscription; overload; function Subscribe(const OnError: TOnError): ISubscription; overload; function Subscribe(const OnCompleted: TOnCompleted): ISubscription; overload; function Subscribe(Subscriber: ISubscriber<T>): ISubscription; overload; /// <summary> /// Set scheduler for producing data flow to subscribers - upstream scheduling /// </summary> function ScheduleOn(Scheduler: IScheduler): TObservable<T>; /// <summary> /// Set scheduler for producing data on subscribe event - downstream scheduling /// </summary> function SubscribeOn(Scheduler: IScheduler): TObservable<T>; (* Операции над последовательностями *) /// <summary> /// Mapping data type /// </summary> function Map<Y>(const Routine: TMap<T, Y>): TObservable<Y>; overload; function Map<Y>(const Routine: TMapStatic<T, Y>): TObservable<Y>; overload; function Map(const Routine: TMap<T, T>): TObservable<T>; overload; function Map(const Routine: TMapStatic<T, T>): TObservable<T>; overload; /// <summary> /// Keep in mind: streams must be synchronized. Observable caching data /// </summary> function Zip<Y>(var O: TObservable<Y>): TObservable<TZip<T, Y>>; overload; /// <summary> /// Speed of output stream is equal to speed of the Fastest one in couple /// </summary> function CombineLatest<Y>(var O: TObservable<Y>): TObservable<TZip<T, Y>>; overload; /// <summary> /// Speed of output stream is equal to speed of the slowest one in couple /// </summary> function WithLatestFrom<Y>(var Slow: TObservable<Y>): TObservable<TZip<T, Y>>; overload; /// <summary> /// Output stream accept items that was first, then items from /// other streams are ignored until next iteration /// </summary> function AMB<Y>(var O: TObservable<Y>): TObservable<TZip<T, Y>>; overload; function AMBWith<Y>(var Slow: TObservable<Y>): TObservable<TZip<T, Y>>; overload; // // Mathematical and Aggregate Operators function Scan<CTX>(const Initial: TSmartVariable<CTX>; const Scan: TScanRoutine<CTX, T>): TObservable<CTX>; overload; function Scan(const Initial: TSmartVariable<T>; const Scan: TScanRoutine<T, T>): TObservable<T>; overload; function Reduce<ACCUM>(const Reduce: TReduceRoutine<ACCUM, T>): TObservable<ACCUM>; overload; function Reduce(const Reduce: TReduceRoutine<T, T>): TObservable<T>; overload; function Collect<ITEM>(const Initial: array of TSmartVariable<ITEM>; const Action: TCollectAction1<ITEM, T>): TObservable<TList<ITEM>>; overload; function Collect<KEY, ITEM>(const Action: TCollectAction2<KEY, ITEM, T>): TObservable<TDictionary<KEY, ITEM>>; overload; function Distinct(Comparer: IComparer<T>): TObservable<T>; overload; /// <summary> /// Limit output stream to first Count items, then raise OnCompleted /// </summary> function Take(Count: Integer): TObservable<T>; /// <summary> /// Raise only last Count items /// </summary> function TakeLast(Count: Integer): TObservable<T>; /// <summary> /// Skip first Count items /// </summary> function Skip(Count: Integer): TObservable<T>; /// <summary> /// The output stream will produce values with delay. // Values are implicitly cached, this must be taken into account to avoid out-of-memory. /// </summary> /// <remarks> /// The timer runs in a separate thread, this must be taken into account. /// Use the Sheduler if you want to redirect the events to context /// other threads. /// </remarks> function Delay(aDelay: LongWord; aTimeUnit: TimeUnit = TimeUnit.SECONDS): TObservable<T>; overload; /// <summary> /// Filtering /// </summary> function Filter(const Routine: TFilter<T>): TObservable<T>; overload; function Filter(const Routine: TFilterStatic<T>): TObservable<T>; overload; /// <summary> /// Transform a single value into a stream. Flows can work in /// context of different threads, to limit the speed of parallel /// streams, you can specify the MaxConcurrent parameter that specifies the value /// semaphore for competently working threads. /// </summary> function FlatMap<Y>(const Routine: TFlatMap<T, Y>; const MaxConcurrent: LongWord=0): TObservable<Y>; overload; function FlatMap<Y>(const Routine: TFlatMapStatic<T, Y>; const MaxConcurrent: LongWord=0): TObservable<Y>; overload; function FlatMapIterable(const Routine: TFlatMapIterable<T>; const MaxConcurrent: LongWord=0): TObservable<T>; overload; function FlatMapIterable(const Routine: TFlatMapIterableStatic<T>; const MaxConcurrent: LongWord=0): TObservable<T>; overload; /// <summary> /// Usefull constructors /// </summary> class function From(Other: IObservable<T>): TObservable<T>; overload; static; class function From(Collection: IEnumerable<TSmartVariable<T>>): TObservable<T>; overload; static; class function From(Collection: TEnumerable<TSmartVariable<T>>): TObservable<T>; overload; static; /// <summary> /// Call OnNext, OnError, Oncompleted directly, but not /// it is desirable, this is a bad practice. /// </summary> procedure OnNext(const Data: T); procedure OnError(E: IThrowable); procedure OnCompleted; /// <summary> /// Intercept an exception and notify all subscribers /// </summary> procedure Catch; class operator Implicit(var A: TObservable<T>): IObservable<T>; class operator Implicit(A: IObservable<T>): TObservable<T>; // debug-only purposes procedure SetName(const Value: string); // others function WaitCompletition(const Timeout: LongWord): Boolean; end; Observable = record // Zip class function Zip<A, B>(var OA: TObservable<A>; var OB: TObservable<B>): TObservable<TZip<A, B>>; overload; static; class function Zip<A, B>(var OA: TObservable<A>; var OB: TObservable<B>; const OnNext: TOnNext<TZip<A, B>>): TObservable<TZip<A, B>>; overload; static; class function Zip<A, B>(var OA: TObservable<A>; var OB: TObservable<B>; const OnNext: TOnNext<TZip<A, B>>; const OnCompleted: TOnCompleted): TObservable<TZip<A, B>>; overload; static; // CombineLatest class function CombineLatest<A, B>(var OA: TObservable<A>; var OB: TObservable<B>): TObservable<TZip<A, B>>; static; // WithLatestFrom class function WithLatestFrom<A, B>(var Fast: TObservable<A>; var Slow: TObservable<B>): TObservable<TZip<A, B>>; overload; static; class function WithLatestFrom<A, B>(var Fast: TObservable<A>; var Slow: TObservable<B>; const OnNext: TOnNext<TZip<A, B>>): TObservable<TZip<A, B>>; overload; static; class function WithLatestFrom<A, B>(var Fast: TObservable<A>; var Slow: TObservable<B>; const OnNext: TOnNext<TZip<A, B>>; const OnCompleted: TOnCompleted): TObservable<TZip<A, B>>; overload; static; // AMB class function AMB<A, B>(var OA: TObservable<A>; var OB: TObservable<B>): TObservable<TZip<A, B>>; overload; static; class function AMBWith<A, B>(var Fast: TObservable<A>; var Slow: TObservable<B>): TObservable<TZip<A, B>>; overload; static; class function AMBWith<A, B>(var Fast: TObservable<A>; var Slow: TObservable<B>; const OnNext: TOnNext<TZip<A, B>>): TObservable<TZip<A, B>>; overload; static; class function AMBWith<A, B>(var Fast: TObservable<A>; var Slow: TObservable<B>; const OnNext: TOnNext<TZip<A, B>>; const OnCompleted: TOnCompleted): TObservable<TZip<A, B>>; overload; static; // usefull calls /// <summary> /// Start the intervals. The counter works in the separate thread, it's necessary /// consider. /// </summary> class function Interval(Delay: LongWord; aTimeUnit: TimeUnit = TimeUnit.SECONDS): TObservable<LongWord>; overload; static; class function IntervalDelayed(InitialDelay: LongWord; Delay: LongWord; aTimeUnit: TimeUnit = TimeUnit.SECONDS): TObservable<LongWord>; overload; static; /// <summary> /// Rx-style counters /// </summary> class function Range(Start, Stop: Integer; Step: Integer=1): TObservable<Integer>; static; /// <summary> /// Catch an exception /// (we assume that the call occurs inside the except ... end block) /// and fix the information about it in IThrowable /// </summary> class function CatchException: IThrowable; static; end; TArrayOfRefsHelper = record helper for TArrayOfRefs strict private function FindIndex(A: IInterface): Integer; public procedure Append(A: IInterface); function Contains(A: IInterface): Boolean; procedure Remove(A: IInterface); end; implementation uses Rx.Subjects, Rx.Observable.Just, Rx.Observable.Empty, Rx.Observable.Defer, Rx.Observable.Never, Rx.Observable.Filter, Rx.Observable.Map, Rx.Observable.Zip, TypInfo, Rx.Implementations, Rx.Observable.Take, Rx.Schedulers, Rx.Observable.FlatMap, Rx.Observable.Delay, Rx.Observable.AdvancedOps; type TThrowableImpl = class(TInterfacedObject, IThrowable) strict private FCode: Integer; FClass: TClass; FMessage: string; FStackTrace: string; FToString: string; public constructor Create(E: Exception); function GetCode: Integer; function GetClass: TClass; function GetMessage: string; function GetStackTrace: string; function ToString: string; reintroduce; end; TIntervalObserverPImpl = class(TIntervalObserver); { TThrowableImpl } constructor TThrowableImpl.Create(E: Exception); begin FCode := 0; FClass := E.ClassType; FMessage := E.Message; FStackTrace := E.StackTrace; FToString := E.ToString; end; function TThrowableImpl.GetClass: TClass; begin Result := FClass; end; function TThrowableImpl.GetCode: Integer; begin Result := FCode; end; function TThrowableImpl.GetMessage: string; begin Result := FMessage; end; function TThrowableImpl.GetStackTrace: string; begin Result := FStackTrace; end; function TThrowableImpl.ToString: string; begin Result := FToString; end; { TObservable<T> } function TObservable<T>.AMB<Y>(var O: TObservable<Y>): TObservable<TZip<T, Y>>; var Joiner: TJoiner<T, Y>; Impl: TZipObserver<TZip<T, Y>>; begin Impl := TZipObserver<TZip<T, Y>>.Create; Joiner := TJoiner<T, Y>.Create(Self.GetImpl, O.GetImpl, Impl.OnNextIcp, Impl.OnError, Impl.OnCompleted); Joiner.Strategy := TAMBStrategy<T, Y>.Create; Impl.Setup(Joiner); Result.Impl := Impl; Refs.Append(Result.Impl); end; function TObservable<T>.AMBWith<Y>(var Slow: TObservable<Y>): TObservable<TZip<T, Y>>; var Joiner: TJoiner<T, Y>; Impl: TZipObserver<TZip<T, Y>>; begin Impl := TZipObserver<TZip<T, Y>>.Create; Joiner := TJoiner<T, Y>.Create(Self.GetImpl, Slow.GetImpl, Impl.OnNextIcp, Impl.OnError, Impl.OnCompleted); Joiner.Strategy := TAMBWithStrategy<T, Y>.Create(fsA); Impl.Setup(Joiner); Result.Impl := Impl; Refs.Append(Result.Impl); end; procedure TObservable<T>.Catch; var E: IThrowable; begin E := Observable.CatchException; if Assigned(E) then GetImpl.OnError(E) end; function TObservable<T>.Collect<ITEM>( const Initial: array of TSmartVariable<ITEM>; const Action: TCollectAction1<ITEM, T>): TObservable<TList<ITEM>>; var ItitialList: TList<TSmartVariable<Item>>; I: Integer; begin ItitialList := TList<TSmartVariable<Item>>.Create; for I := 0 to High(Initial) do ItitialList.Add(Initial[I]); Result := TCollect1Observable<ITEM, T>.Create(GetImpl, ItitialList, Action); Result := Result.TakeLast(1); end; function TObservable<T>.Collect<KEY, ITEM>( const Action: TCollectAction2<KEY, ITEM, T>): TObservable<TDictionary<KEY, ITEM>>; begin Result := TCollect2Observable<KEY, ITEM, T>.Create(GetImpl, nil, Action); Result := Result.TakeLast(1); end; function TObservable<T>.CombineLatest<Y>( var O: TObservable<Y>): TObservable<TZip<T, Y>>; var Joiner: TJoiner<T, Y>; Impl: TZipObserver<TZip<T, Y>>; begin Impl := TZipObserver<TZip<T, Y>>.Create; Joiner := TJoiner<T, Y>.Create(Self.GetImpl, O.GetImpl, Impl.OnNextIcp, Impl.OnError, Impl.OnCompleted); Joiner.Strategy := TCombineLatestStrategy<T, Y>.Create; Impl.Setup(Joiner); Result.Impl := Impl; Refs.Append(Result.Impl); end; constructor TObservable<T>.Create(const OnSubscribe: TOnSubscribe2<T>); begin Impl := TPublishSubject<T>.Create(OnSubscribe); end; constructor TObservable<T>.Create(const OnSubscribe: TOnSubscribe<T>); begin Impl := TPublishSubject<T>.Create(OnSubscribe); end; constructor TObservable<T>.Defer(const Routine: TDefer<T>); begin Impl := Rx.Observable.Defer.TDefer<T>.Create(Routine); end; function TObservable<T>.Delay(aDelay: LongWord; aTimeUnit: TimeUnit): TObservable<T>; begin Result := TDelay<T>.Create(GetImpl, aDelay, aTimeUnit); end; function TObservable<T>.Distinct(Comparer: IComparer<T>): TObservable<T>; begin end; class function TObservable<T>.Empty: TObservable<T>; begin Result.Impl := TEmpty<T>.Create; end; function TObservable<T>.Filter(const Routine: TFilter<T>): TObservable<T>; begin Result.Impl := Rx.Observable.Filter.TFilter<T>.Create(GetImpl, Routine); Refs.Append(Result.Impl); end; function TObservable<T>.Filter(const Routine: TFilterStatic<T>): TObservable<T>; begin Result.Impl := Rx.Observable.Filter.TFilter<T>.CreateStatic(GetImpl, Routine); Refs.Append(Result.Impl); end; function TObservable<T>.FlatMap<Y>(const Routine: TFlatMap<T, Y>; const MaxConcurrent: LongWord): TObservable<Y>; var O: IFlatMapObservable<T, Y>; begin O := GetFlatStream<Y>; O.Spawn(Routine); O.SetMaxConcurrency(MaxConcurrent); Result.Impl := O; end; function TObservable<T>.FlatMap<Y>(const Routine: TFlatMapStatic<T, Y>; const MaxConcurrent: LongWord): TObservable<Y>; var O: IFlatMapObservable<T, Y>; begin O := GetFlatStream<Y>; O.Spawn(Routine); O.SetMaxConcurrency(MaxConcurrent); Result.Impl := O; end; function TObservable<T>.FlatMapIterable( const Routine: TFlatMapIterableStatic<T>; const MaxConcurrent: LongWord): TObservable<T>; var O: IFlatMapIterableObservable<T>; begin O := GetFlatIterable; O.Spawn(Routine); O.SetMaxConcurrency(MaxConcurrent); Result.Impl := O; end; function TObservable<T>.FlatMapIterable( const Routine: TFlatMapIterable<T>; const MaxConcurrent: LongWord): TObservable<T>; var O: IFlatMapIterableObservable<T>; begin O := GetFlatIterable; O.Spawn(Routine); O.SetMaxConcurrency(MaxConcurrent); Result.Impl := O; end; class function TObservable<T>.From(Collection: TEnumerable<TSmartVariable<T>>): TObservable<T>; begin Result := TObservable<T>.Just(Collection.ToArray); end; class function TObservable<T>.From(Collection: IEnumerable<TSmartVariable<T>>): TObservable<T>; begin Result.Impl := TJust<T>.Create(Collection); end; class function TObservable<T>.From(Other: IObservable<T>): TObservable<T>; var Impl: TPublishSubject<T>; begin Impl := TPublishSubject<T>.Create; Impl.Merge(Other); Result.Impl := Impl; end; function TObservable<T>.GetFlatIterable: IFlatMapIterableObservable<T>; begin if not Assigned(FlatIterable) then FlatIterable := Rx.Observable.FlatMap.TFlatMapIterableImpl<T>.Create(GetImpl); Result := FlatIterable end; function TObservable<T>.GetFlatStream<Y>: IFlatMapObservable<T, Y>; var Key: string; ti: PTypeInfo; I: Integer; begin ti := TypeInfo(Y); Key := string(ti.Name); for I := 0 to High(FFlatStreamKeys) do if Key = FFlatStreamKeys[I] then Exit(IFlatMapObservable<T, Y>(FlatStreams[I])); Result := Rx.Observable.FlatMap.TFlatMap<T,Y>.Create(GetImpl); SetLength(FFlatStreamKeys, Length(FFlatStreamKeys)+1); FlatStreams.Append(Result); end; function TObservable<T>.GetImpl: IObservable<T>; begin if not Assigned(Impl) then Impl := TPublishSubject<T>.Create; Result := Impl; end; class operator TObservable<T>.Implicit(A: IObservable<T>): TObservable<T>; begin Result.Impl := A; end; class operator TObservable<T>.Implicit(var A: TObservable<T>): IObservable<T>; begin Result := A.GetImpl end; constructor TObservable<T>.Just(const Items: array of TSmartVariable<T>); begin Impl := TJust<T>.Create(Items); end; function TObservable<T>.Map(const Routine: TMap<T, T>): TObservable<T>; begin Result.Impl := Rx.Observable.Map.TMap<T, T>.Create(GetImpl, Routine); Refs.Append(Result.Impl); end; function TObservable<T>.Map(const Routine: TMapStatic<T, T>): TObservable<T>; begin Result.Impl := Rx.Observable.Map.TMap<T, T>.CreateStatic(GetImpl, Routine); Refs.Append(Result.Impl); end; function TObservable<T>.Map<Y>(const Routine: TMapStatic<T, Y>): TObservable<Y>; begin Result.Impl := Rx.Observable.Map.TMap<T, Y>.CreateStatic(GetImpl, Routine); Refs.Append(Result.Impl); end; function TObservable<T>.Map<Y>(const Routine: TMap<T, Y>): TObservable<Y>; begin Result.Impl := Rx.Observable.Map.TMap<T, Y>.Create(GetImpl, Routine); Refs.Append(Result.Impl); end; constructor TObservable<T>.Merge(var O1, O2, O3: TObservable<T>); var Impl_: TPublishSubject<T>; O1_, O2_, O3_: IObservable<T>; begin Impl_ := TPublishSubject<T>.Create; O1_ := O1.GetImpl; O2_ := O2.GetImpl; O3_ := O3.GetImpl; Impl_.Merge(O1_); Impl_.Merge(O2_); Impl_.Merge(O3_); Impl := Impl_; end; constructor TObservable<T>.Merge(var O1, O2: TObservable<T>); var Impl_: TPublishSubject<T>; O1_, O2_: IObservable<T>; begin Impl_ := TPublishSubject<T>.Create; O1_ := O1.GetImpl; O2_ := O2.GetImpl; Impl_.Merge(O1_); Impl_.Merge(O2_); Impl := Impl_; end; class function TObservable<T>.Never: TObservable<T>; begin Result.Impl := TNever<T>.Create; end; procedure TObservable<T>.OnCompleted; begin GetImpl.OnCompleted end; procedure TObservable<T>.OnError(E: IThrowable); begin GetImpl.OnError(E) end; procedure TObservable<T>.OnNext(const Data: T); begin GetImpl.OnNext(Data) end; function TObservable<T>.Reduce( const Reduce: TReduceRoutine<T, T>): TObservable<T>; begin Result := TReduceObservable<T, T>.Create(GetImpl, Reduce); Result := Result.TakeLast(1); end; function TObservable<T>.Reduce<ACCUM>( const Reduce: TReduceRoutine<ACCUM, T>): TObservable<ACCUM>; begin Result := TReduceObservable<ACCUM, T>.Create(GetImpl, Reduce); Result := Result.TakeLast(1); end; function TObservable<T>.Subscribe(const OnError: TOnError): ISubscription; begin Result := GetImpl.Subscribe(OnError); end; function TObservable<T>.Scan(const Initial: TSmartVariable<T>; const Scan: TScanRoutine<T, T>): TObservable<T>; begin Result := TScanObservable<T, T>.Create(GetImpl, Initial, Scan); end; function TObservable<T>.Scan<CTX>(const Initial: TSmartVariable<CTX>; const Scan: TScanRoutine<CTX, T>): TObservable<CTX>; begin Result := TScanObservable<CTX, T>.Create(GetImpl, Initial, Scan); end; function TObservable<T>.ScheduleOn(Scheduler: IScheduler): TObservable<T>; begin Result := TObservable<T>.From(Self.GetImpl); Result.Impl.ScheduleOn(Scheduler) end; procedure TObservable<T>.SetName(const Value: string); begin GetImpl.SetName(Value); end; function TObservable<T>.Skip(Count: Integer): TObservable<T>; begin Result.Impl := Rx.Observable.Take.TSkip<T>.Create(GetImpl, Count); Refs.Append(Result.Impl); end; function TObservable<T>.Subscribe( const OnCompleted: TOnCompleted): ISubscription; begin Result := GetImpl.Subscribe(OnCompleted); end; function TObservable<T>.Subscribe(const OnNext: TOnNext<T>; const OnCompleted: TOnCompleted): ISubscription; begin Result := GetImpl.Subscribe(OnNext, OnCompleted); end; function TObservable<T>.Subscribe(const OnNext: TOnNext<T>; const OnError: TOnError): ISubscription; begin Result := GetImpl.Subscribe(OnNext, OnError); end; function TObservable<T>.Subscribe(const OnNext: TOnNext<T>; const OnError: TOnError; const OnCompleted: TOnCompleted): ISubscription; begin Result := GetImpl.Subscribe(OnNext, OnError, OnCompleted); end; function TObservable<T>.Subscribe(const OnNext: TOnNext<T>): ISubscription; begin Result := GetImpl.Subscribe(OnNext); end; function TObservable<T>.Zip<Y>( var O: TObservable<Y>): TObservable<TZip<T, Y>>; var Joiner: TJoiner<T, Y>; Impl: TZipObserver<TZip<T, Y>>; begin Impl := TZipObserver<TZip<T, Y>>.Create; Joiner := TJoiner<T, Y>.Create(Self.GetImpl, O.GetImpl, Impl.OnNextIcp, Impl.OnError, Impl.OnCompleted); Joiner.Strategy := TSyncStrategy<T, Y>.Create; Impl.Setup(Joiner); Result.Impl := Impl; Refs.Append(Result.Impl); end; function TObservable<T>.Subscribe(Subscriber: ISubscriber<T>): ISubscription; begin Result := GetImpl.Subscribe(Subscriber); end; function TObservable<T>.SubscribeOn(Scheduler: IScheduler): TObservable<T>; begin Result := TObservable<T>.From(Self.GetImpl); Result.Impl.SubscribeOn(Scheduler) end; function TObservable<T>.Take(Count: Integer): TObservable<T>; begin Result.Impl := Rx.Observable.Take.TTake<T>.Create(GetImpl, Count); Refs.Append(Result.Impl); end; function TObservable<T>.TakeLast(Count: Integer): TObservable<T>; begin Result.Impl := Rx.Observable.Take.TTakeLast<T>.Create(GetImpl, Count); Refs.Append(Result.Impl); end; function TObservable<T>.WaitCompletition(const Timeout: LongWord): Boolean; begin Result := GetImpl.WaitCompletition(Timeout) end; function TObservable<T>.WithLatestFrom<Y>( var Slow: TObservable<Y>): TObservable<TZip<T, Y>>; var Joiner: TJoiner<T, Y>; Impl: TZipObserver<TZip<T, Y>>; begin Impl := TZipObserver<TZip<T, Y>>.Create; Joiner := TJoiner<T, Y>.Create(Self.GetImpl, Slow.GetImpl, Impl.OnNextIcp, Impl.OnError, Impl.OnCompleted); Joiner.Strategy := TWithLatestFromStrategy<T, Y>.Create(fsA); Impl.Setup(Joiner); Result.Impl := Impl; Refs.Append(Result.Impl); end; { TSmartVariable<T> } procedure TSmartVariable<T>.Clear; begin FObjRef := nil; FValue := FDefValue end; constructor TSmartVariable<T>.Create(const A: T); begin Self := A; end; class operator TSmartVariable<T>.Equal(A, B: TSmartVariable<T>): Boolean; var Comp: IComparer<T>; begin Comp := TComparer<T>.Default; Result := Comp.Compare(A.FValue, B.FValue) = 0 end; function TSmartVariable<T>.Get: T; var Obj: TObject absolute Result; begin Result := FValue; if IsObject then if Assigned(FObjRef) then Obj := (FObjRef as IAutoRefObject).GetValue else Obj := nil end; class operator TSmartVariable<T>.Implicit(A: TSmartVariable<T>): T; var Obj: TObject absolute Result; begin if IsObject then begin if Assigned(A.FObjRef) then Obj := (A.FObjRef as IAutoRefObject).GetValue else Obj := nil; end else begin Result := A.FValue end; end; class operator TSmartVariable<T>.Implicit(A: T): TSmartVariable<T>; var Obj: TObject absolute A; begin if IsObject then if Assigned(Obj) then Result.FObjRef := TAutoRefObjectImpl.Create(Obj) else Result.FValue := A else begin Result.FValue := A end; end; class function TSmartVariable<T>.IsObject: Boolean; var ti: PTypeInfo; ObjValuePtr: PObject; begin ti := TypeInfo(T); Result := ti.Kind = tkClass; end; { Schedulers } class function StdSchedulers.CreateCurrentThreadScheduler: ICurrentThreadScheduler; begin Result := TCurrentThreadScheduler.Create end; class function StdSchedulers.CreateMainThreadScheduler: IMainThreadScheduler; begin Result := TMainThreadScheduler.Create end; class function StdSchedulers.CreateNewThreadScheduler: INewThreadScheduler; begin Result := TNewThreadScheduler.Create; end; class function StdSchedulers.CreateSeparateThreadScheduler: ISeparateThreadScheduler; begin Result := TSeparateThreadScheduler.Create end; class function StdSchedulers.CreateThreadPoolScheduler(PoolSize: Integer): IThreadPoolScheduler; begin Result := TThreadPoolScheduler.Create(PoolSize); end; { TZip<X, Y> } constructor TZip<X, Y>.Create(const A: X; const B: Y); begin FAHolder := A; FBHolder := B; end; destructor TZip<X, Y>.Destroy; begin FAHolder.Clear; FBHolder.Clear; inherited; end; function TZip<X, Y>.GetA: X; begin Result := FAHolder end; function TZip<X, Y>.GetB: Y; begin Result := FBHolder end; { TArrayOfRefsHelper } procedure TArrayOfRefsHelper.Append(A: IInterface); begin SetLength(Self, Length(Self) + 1); Self[High(Self)] := A; end; function TArrayOfRefsHelper.Contains(A: IInterface): Boolean; begin Result := FindIndex(A) <> -1; end; function TArrayOfRefsHelper.FindIndex(A: IInterface): Integer; var I: Integer; begin Result := -1; for I := 0 to High(Self) do if Self[I] = A then Exit(I); end; procedure TArrayOfRefsHelper.Remove(A: IInterface); var Index, I: Integer; begin Index := FindIndex(A); if Index <> -1 then begin for I := Index+1 to High(Self) do Self[I-1] := Self[I]; SetLength(Self, Length(Self)-1); end; end; { Observable } class function Observable.AMB<A, B>(var OA: TObservable<A>; var OB: TObservable<B>): TObservable<TZip<A, B>>; begin Result := OA.AMB<B>(OB); end; class function Observable.AMBWith<A, B>(var Fast: TObservable<A>; var Slow: TObservable<B>): TObservable<TZip<A, B>>; begin Result := Fast.AMBWith<B>(Slow); end; class function Observable.AMBWith<A, B>(var Fast: TObservable<A>; var Slow: TObservable<B>; const OnNext: TOnNext<TZip<A, B>>): TObservable<TZip<A, B>>; begin Result := Fast.AMBWith<B>(Slow); Result.Subscribe(OnNext); end; class function Observable.AMBWith<A, B>(var Fast: TObservable<A>; var Slow: TObservable<B>; const OnNext: TOnNext<TZip<A, B>>; const OnCompleted: TOnCompleted): TObservable<TZip<A, B>>; begin Result := Fast.AMBWith<B>(Slow); Result.Subscribe(OnNext, OnCompleted); end; class function Observable.CatchException: IThrowable; var E: Exception; begin E := Exception(ExceptObject); if Assigned(E) then begin Result := TThrowableImpl.Create(E); end else Result := nil; end; class function Observable.CombineLatest<A, B>(var OA: TObservable<A>; var OB: TObservable<B>): TObservable<TZip<A, B>>; begin Result := OA.CombineLatest<B>(OB) end; class function Observable.IntervalDelayed(InitialDelay, Delay: LongWord; aTimeUnit: TimeUnit): TObservable<LongWord>; begin case aTimeUnit of TimeUnit.MILLISECONDS: begin TIntervalObserverPImpl.CurDelay := Delay; TIntervalObserverPImpl.InitialDelay := InitialDelay; end; TimeUnit.SECONDS: begin TIntervalObserverPImpl.CurDelay := Delay*1000; TIntervalObserverPImpl.InitialDelay := InitialDelay*1000; end; TimeUnit.MINUTES: begin TIntervalObserverPImpl.CurDelay := Delay*1000*60; TIntervalObserverPImpl.InitialDelay := InitialDelay*1000*60; end; end; Result := TIntervalObserver.Create; end; class function Observable.Range(Start, Stop, Step: Integer): TObservable<Integer>; var L: TList<TSmartVariable<Integer>>; Cur: Integer; begin L := TList<TSmartVariable<Integer>>.Create; try Cur := Start; while Cur <= Stop do begin L.Add(Cur); Inc(Cur, Step); end; Result := TObservable<Integer>.From(L); finally L.Free; end; end; class function Observable.Interval(Delay: LongWord; aTimeUnit: TimeUnit): TObservable<LongWord>; begin case aTimeUnit of TimeUnit.MILLISECONDS: TIntervalObserverPImpl.CurDelay := Delay; TimeUnit.SECONDS: TIntervalObserverPImpl.CurDelay := Delay*1000; TimeUnit.MINUTES: TIntervalObserverPImpl.CurDelay := Delay*1000*60; end; TIntervalObserverPImpl.InitialDelay := 0; Result := TIntervalObserver.Create; end; class function Observable.Zip<A, B>(var OA: TObservable<A>; var OB: TObservable<B>): TObservable<TZip<A, B>>; begin Result := OA.Zip<B>(OB) end; class function Observable.Zip<A, B>(var OA: TObservable<A>; var OB: TObservable<B>; const OnNext: TOnNext<TZip<A, B>>): TObservable<TZip<A, B>>; begin Result := Zip<A, B>(OA, OB); Result.Subscribe(OnNext); end; class function Observable.WithLatestFrom<A, B>(var Fast: TObservable<A>; var Slow: TObservable<B>): TObservable<TZip<A, B>>; begin Result := Fast.WithLatestFrom<B>(Slow); end; class function Observable.WithLatestFrom<A, B>(var Fast: TObservable<A>; var Slow: TObservable<B>; const OnNext: TOnNext<TZip<A, B>>): TObservable<TZip<A, B>>; begin Result := Fast.WithLatestFrom<B>(Slow); Result.Subscribe(OnNext); end; class function Observable.Zip<A, B>(var OA: TObservable<A>; var OB: TObservable<B>; const OnNext: TOnNext<TZip<A, B>>; const OnCompleted: TOnCompleted): TObservable<TZip<A, B>>; begin Result := Zip<A, B>(OA, OB); Result.Subscribe(OnNext, OnCompleted); end; class function Observable.WithLatestFrom<A, B>(var Fast: TObservable<A>; var Slow: TObservable<B>; const OnNext: TOnNext<TZip<A, B>>; const OnCompleted: TOnCompleted): TObservable<TZip<A, B>>; begin Result := Fast.WithLatestFrom<B>(Slow); Result.Subscribe(OnNext, OnCompleted); end; end.
{ Copyright (C) 1998-2018, written by Mike Shkolnik, Scalabium Software E-Mail: mshkolnik@scalabium.com mshkolnik@yahoo.com WEB: http://www.scalabium.com } unit SMCVersInfo; interface uses Classes; const VI_MAJOR_VERSION = 1; VI_MINOR_VERSION = 2; VI_RELEASE = 3; VI_BUILD = 4; VI_COMPANY_NAME = 1; VI_FILE_DESCRIPTION = 2; VI_FILE_VERSION = 3; VI_INTERNAL_NAME = 4; VI_LEGAL_COPYRIGHT = 5; VI_ORIGINAL_FILENAME = 6; VI_PRODUCT_NAME = 7; VI_PRODUCT_VERSION = 8; VI_COMMENTS = 9; VI_LEGAL_TRADEMARKS = 10; type {$IFDEF SM_ADD_ComponentPlatformsAttribute} [ComponentPlatformsAttribute(pidWin32 or pidWin64)] {$ENDIF} TSMVersionInfo = class(TComponent) private FFileName: string; iDataSize: Integer; pData: Pointer; function iGetVersionInfo(Index: Integer): Integer; function sGetVersionInfo(Index: Integer): string; function GetVersionDateTime: TDateTime; procedure SetFileName(Value: string); public constructor CreateFile(AFileName: string); destructor Destroy; override; function GetVersionString(Key: string): string; published property FileName: string read FFileName write SetFileName; property MajorVersion: Integer index VI_MAJOR_VERSION read iGetVersionInfo; property MinorVersion: Integer index VI_MINOR_VERSION read iGetVersionInfo; property Release: Integer index VI_RELEASE read iGetVersionInfo; property Build: Integer index VI_BUILD read iGetVersionInfo; property DateTime: TDateTime read GetVersionDateTime; property CompanyName: string index VI_COMPANY_NAME read sGetVersionInfo; property FileDescription: string index VI_FILE_DESCRIPTION read sGetVersionInfo; property FileVersion: string index VI_FILE_VERSION read sGetVersionInfo; property InternalName: string index VI_INTERNAL_NAME read sGetVersionInfo; property LegalCopyright: string index VI_LEGAL_COPYRIGHT read sGetVersionInfo; property OriginalFilename: string index VI_ORIGINAL_FILENAME read sGetVersionInfo; property ProductName: string index VI_PRODUCT_NAME read sGetVersionInfo; property ProductVersion: string index VI_PRODUCT_VERSION read sGetVersionInfo; property Comments: string index VI_COMMENTS read sGetVersionInfo; property LegalTrademarks: string index VI_LEGAL_TRADEMARKS read sGetVersionInfo; end; procedure Register; implementation uses Windows, SysUtils; procedure Register; begin RegisterComponents('SMComponents', [TSMVersionInfo]); end; { TSMVersionInfo } constructor TSMVersionInfo.CreateFile(AFileName: string); begin inherited; FileName := AFileName; end; destructor TSMVersionInfo.Destroy; begin if iDataSize > 0 then FreeMem(pData, iDataSize); inherited; end; procedure TSMVersionInfo.SetFileName(Value: string); var lpdwHandle: dWord; begin if (FFileName <> Value) then begin FFileName := Value; if (Value <> '') then begin iDataSize := GetFileVersionInfoSize(PChar(FileName), lpdwHandle); if iDataSize > 0 then begin GetMem(pData, iDataSize); Win32Check(GetFileVersionInfo(PChar(FileName), 0, iDataSize, pData)); end end; end; end; function TSMVersionInfo.iGetVersionInfo(Index: Integer): Integer; var FixedFileInfo: PVSFixedFileInfo; lpdwHandle: dWord; begin Result := -1; if iDataSize > 0 then begin VerQueryValue(pData, '\', Pointer(FixedFileInfo), lpdwHandle); with FixedFileInfo^ do case Index of VI_MAJOR_VERSION: Result := HiWord(dwFileVersionMS); VI_MINOR_VERSION: Result := LoWord(dwFileVersionMS); VI_RELEASE: Result := HiWord(dwFileVersionLS); VI_BUILD: Result := LoWord(dwFileVersionLS); end; end; end; function TSMVersionInfo.GetVersionString(Key: string): string; var lpdwHandle: dWord; P: Pointer; S: string; Buffer: PChar; begin Result := ''; if iDataSize > 0 then begin VerQueryValue(pData, '\VarFileInfo\Translation', P, lpdwHandle); S := Format('\StringFileInfo\%.4x%.4x\%s', [LoWord(Integer(P^)), HiWord(Integer(P^)), Key]); if VerQueryValue(pData, PChar(S), Pointer(Buffer), lpdwHandle) then Result := StrPas(Buffer); end; end; function TSMVersionInfo.GetVersionDateTime: TDateTime; var FixedFileInfo: PVSFixedFileInfo; lpdwHandle: dWord; FileTime: TFileTime; SystemTime: TSystemTime; begin Result := 0; if iDataSize > 0 then begin VerQueryValue(pData, '\', Pointer(FixedFileInfo), lpdwHandle); with FixedFileInfo^ do begin FileTime.dwLowDateTime := dwFileDateLS; FileTime.dwHighDateTime := dwFileDateMS; FileTimeToSystemTime(FileTime, SystemTime); with SystemTime do Result := EncodeDate(wYear, wMonth, wDay) + EncodeTime(wHour, wMinute, wSecond, wMilliSeconds); end; end; end; function TSMVersionInfo.sGetVersionInfo(Index: Integer): string; var KeyName: string; begin Result := ''; case Index of VI_COMPANY_NAME: KeyName := 'CompanyName'; VI_FILE_DESCRIPTION: KeyName := 'FileDescription'; VI_FILE_VERSION: KeyName := 'FileVersion'; VI_INTERNAL_NAME: KeyName := 'InternalName'; VI_LEGAL_COPYRIGHT: KeyName := 'LegalCopyright'; VI_ORIGINAL_FILENAME: KeyName := 'OriginalFilename'; VI_PRODUCT_NAME: KeyName := 'ProductName'; VI_PRODUCT_VERSION: KeyName := 'ProductVersion'; VI_COMMENTS: KeyName := 'Comments'; VI_LEGAL_TRADEMARKS: KeyName := 'LegalTrademarks'; end; Result := GetVersionString(KeyName); end; end.
Program HashChaining; CONST MAX = 100; TYPE NodePtr = ^Node; Node = record val: string; del: boolean; end; HashTable = array [0..MAX - 1] OF NodePtr; FUNCTION NewNode(val: string): NodePtr; var n: NodePtr; BEGIN New(n); n^.val := val; n^.del := false; NewNode := n; END; PROCEDURE InitHashTable(var table: HashTable); var i: integer; BEGIN for i := Low(table) to High(table) do begin table[i] := NIL; end; END; FUNCTION GetHashCode(val: string): integer; BEGIN If (Length(val) = 0) then begin GetHashCode := 0; end else if Length(val) = 0 then begin GetHashCode := (Ord(val[1]) * 7 + 1) * 17; end else begin GetHashCode := (Ord(val[1]) * 7 + Ord(val[2]) + Length(val)) * 17; end; END; PROCEDURE Insert(var table: HashTable; val: string); var hashcode: integer; BEGIN hashcode := GetHashCode(val); hashcode := hashcode MOD MAX; while (table[hashcode] <> NIL) AND (NOT table[hashcode]^.del) do begin hashcode := (hashcode + 1) MOD MAX; if (hashcode = GetHashCode(val)) then begin WriteLn('ERROR: Hashtable is full'); HALT; end; end; if(table[hashcode] <> NIL) then Dispose(table[hashcode]); table[hashcode] := NewNode(val); END; FUNCTION Lookup(table: HashTable; val: string): integer; var hashcode: integer; BEGIN hashcode := GetHashCode(val); hashcode := hashcode MOD MAX; while ((table[hashcode] <> NIL) AND ((table[hashcode]^.val <> val) OR (table[hashcode]^.del))) do begin hashcode := (hashcode + 1) MOD MAX; if (hashcode = GetHashCode(val)) then begin // end; end; if table[hashcode] <> NIL then begin Lookup := hashcode; end else begin Lookup := -1; end; END; FUNCTION Contains(table: HashTable; val: string): boolean; BEGIN Contains := Lookup(table, val) <> -1; END; PROCEDURE Remove(var table: HashTable; val: string); var i: integer; BEGIN i := Lookup(table, val); if (i <> -1) then begin table[i]^.del := true; end; END; PROCEDURE WriteHashTable(table: HashTable); var i: integer; n: NodePtr; BEGIN for i := 0 to MAX - 1 do begin if(table[i] <> NIL) then begin Write(i, ': ', table[i]^.val); if(table[i]^.del) then Write(' (DEL)'); WriteLn; end; end; END; var table: HashTable; s: string; BEGIN InitHashTable(table); Insert(table, 'Stefan'); Insert(table, 'Sabine'); Insert(table, 'Albert'); Insert(table, 'Alina'); Insert(table, 'Gisella'); Insert(table, 'Gisbert'); WriteLn('Contains(Sabine)? = ', Contains(table, 'Sabine')); WriteLn('Contains(Alina)? = ', Contains(table, 'Alina')); WriteLn('Contains(Fridolin)? = ', Contains(table, 'Fridolin')); WriteLn('Contains(Sebastian)? = ', Contains(table, 'Sebastian')); WriteHashTable(table); WriteLn; Remove(table, 'Gisbert'); WriteHashTable(table); WriteLn(Contains(table, 'Gisbert')); END.
unit ColInfo; interface uses DSWrap; type TColInfo = class(TObject) private FBandCaption: String; FBandIndex: Integer; FFieldWrap: TFieldWrap; public constructor Create(AFieldWrap: TFieldWrap; ABandIndex: Integer; ABandCaption: String = ''); property BandCaption: String read FBandCaption; property BandIndex: Integer read FBandIndex; property FieldWrap: TFieldWrap read FFieldWrap; end; implementation constructor TColInfo.Create(AFieldWrap: TFieldWrap; ABandIndex: Integer; ABandCaption: String = ''); begin FFieldWrap := AFieldWrap; FBandIndex := ABandIndex; FBandCaption := ABandCaption; end; end.
unit Unit2; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Windows, Process, registry; type NomeRedeSenha = Record Nomerede : String; Senha: String; End; Function ExecutarWindows(Executavel: String; Parametros: String): boolean; Function Execomando(Comando: String): String; function GetEnvVarValue(const VarName: string): string; function SalvaRede(NomeRede, Senha: String): String; function LerRede(): NomeRedeSenha; function ApagaRede(): boolean; implementation function ExecutarWindows(Executavel: String; Parametros: String): boolean; var execwin: TProcess; begin execwin:=TProcess.Create(nil); execwin.Executable:=Executavel; execwin.Parameters.Add(Parametros); execwin.Options:=[poNewConsole]; execwin.ShowWindow:=swoHide; execwin.Execute; end; Function Execomando(Comando: String): String; // Inicio Execomando Const C_BUFSIZE = 4096; var Hbk: TProcess; Buffer: pointer; SStream: TStringStream; nread: longint; dados : String; begin Hbk := TProcess.Create(nil); // Replace the line below with your own command string Hbk.CommandLine := Comando; // Hbk.ShowWindow:= swoHIDE; Hbk.Options := [poUsePipes]; Hbk.Execute; // Prepare for capturing output Getmem(Buffer, C_BUFSIZE); SStream := TStringStream.Create(''); // Start capturing output while Hbk.Running do begin nread := Hbk.Output.Read(Buffer^, C_BUFSIZE); if nread = 0 then sleep(100) else begin // Translate raw input to a string SStream.size := 0; SStream.Write(Buffer^, nread); dados := dados + SStream.DataString; end; end; // Capture remainder of the output repeat nread := Hbk.Output.Read(Buffer^, C_BUFSIZE); if nread > 0 then begin SStream.size := 0; SStream.Write(Buffer^, nread); dados := dados + SStream.DataString; end until nread = 0; // Clean up Hbk.Free; Freemem(buffer); SStream.Free; // Retorna resultado Result := dados; End; //Fim Execomando function GetEnvVarValue(const VarName: string): string; var BufSize: Integer; begin BufSize := GetEnvironmentVariable(PChar(VarName), nil, 0); if BufSize > 0 then begin SetLength(Result, BufSize - 1); GetEnvironmentVariable(PChar(VarName), PChar(Result), BufSize); end else Result := ''; end; function SalvaRede(NomeRede, Senha: String): String; var Registro:TRegistry; begin Registro := TRegistry.Create; Registro.RootKey:=HKEY_CURRENT_USER; if registro.OpenKey('SOFTWARE\WIFI',true) then begin Registro.WriteString('NomeRede',NomeRede); Registro.WriteString('Senha',Senha); end; registro.CloseKey; registro.Free; end; function LerRede(): NomeRedeSenha; Var Registro:TRegistry; begin Registro := TRegistry.Create; Registro.RootKey:=HKEY_CURRENT_USER; if registro.OpenKey('SOFTWARE\WIFI',true) then begin Result.NomeRede := Registro.ReadString('NomeRede'); Result.Senha := Registro.ReadString('Senha'); end; registro.CloseKey; registro.Free; end; function ApagaRede: boolean; Var Registro:TRegistry; begin Registro := TRegistry.Create; Registro.RootKey:=HKEY_CURRENT_USER; if registro.OpenKey('SOFTWARE',true) then begin Registro.DeleteKey('WIFI'); Result:=False; end; registro.CloseKey; registro.Free; end; end.
unit ConnectDialog; interface uses {$IFNDEF LINUX} Windows, Messages, {$ENDIF} SysUtils, Classes, Graphics, Controls, Forms, Dialogs, DBCtrls, ExtCtrls, Grids, DBGrids, StdCtrls, ToolWin, ComCtrls, Buttons, UniDacVcl, {$IFDEF FPC} LResources, {$ENDIF} DB, DBAccess, Uni, UniDacDemoForm, DemoFrame, InheritedConnectForm, MyConnectForm, {$IFNDEF FPC}MemDS{$ELSE}MemDataSet{$ENDIF}; type TConnectDialogFrame = class(TDemoFrame) ToolBar: TPanel; DataSource: TDataSource; DBGrid: TDBGrid; UniQuery: TUniQuery; Panel1: TPanel; btOpen: TSpeedButton; btClose: TSpeedButton; DBNavigator: TDBNavigator; Panel3: TPanel; rbInherited: TRadioButton; rbMy: TRadioButton; rbDefault: TRadioButton; procedure btOpenClick(Sender: TObject); procedure btCloseClick(Sender: TObject); procedure rbDefaultClick(Sender: TObject); procedure rbMyClick(Sender: TObject); procedure rbInheritedClick(Sender: TObject); public destructor Destroy; override; procedure Initialize; override; end; implementation {$IFNDEF FPC} {$IFDEF CLR} {$R *.nfm} {$ELSE} {$R *.dfm} {$ENDIF} {$ENDIF} procedure TConnectDialogFrame.Initialize; begin UniQuery.Connection := Connection as TUniConnection; end; destructor TConnectDialogFrame.Destroy; begin UniDacForm.UniConnectDialog.DialogClass:= ''; inherited; end; procedure TConnectDialogFrame.btOpenClick(Sender: TObject); begin UniQuery.Open; end; procedure TConnectDialogFrame.btCloseClick(Sender: TObject); begin UniQuery.Close; end; procedure TConnectDialogFrame.rbDefaultClick(Sender: TObject); begin UniDacForm.UniConnectDialog.DialogClass:= ''; end; procedure TConnectDialogFrame.rbMyClick(Sender: TObject); begin UniDacForm.UniConnectDialog.DialogClass:= 'TfmMyConnect'; end; procedure TConnectDialogFrame.rbInheritedClick(Sender: TObject); begin UniDacForm.UniConnectDialog.DialogClass:= 'TfmInheritedConnect'; end; initialization {$IFDEF FPC} {$I ConnectDialog.lrs} {$ENDIF} end.
unit FormFolderSelect; (* FormFolderSelect.pas -------------------- Begin: 2007/02/02 Last revision: $Date: 2009-09-08 21:49:25 $ $Author: areeves $ Version number: $Revision: 1.2 $ Project: APHI General Purpose Delphi Library Website: http://www.naadsm.org/opensource/delphi Author: Aaron Reeves <aaron.reeves@naadsm.org> -------------------------------------------------- Copyright (C) 2007 - 2008 Animal Population Health Institute, Colorado State University This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. *) interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, ExtCtrls, Buttons, {$WARNINGS OFF} ShellCtrls, {$WARNINGS ON} QLists ; type TFormFolderSelect = class( TForm ) treeView: TShellTreeView; pnlBottom: TPanel; lblSelectedFolder: TLabel; lblFolder: TLabel; pnlTop: TPanel; pnlSpacer: TPanel; pnlButtons: TPanel; pnlNewFolder: TPanel; pnlTopContainer: TPanel; lblHeader: TLabel; pnlButtonsRight: TPanel; btnOK: TButton; btnCancel: TButton; btnNewFolder: TBitBtn; procedure treeViewChange(Sender: TObject; Node: TTreeNode); procedure btnNewFolderClick(Sender: TObject); procedure btnOKClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure treeViewExpanded(Sender: TObject; Node: TTreeNode); protected _selectedDir: string; _foldersToHide: TQStringList; procedure translateUI(); procedure translateUIManual(); procedure fillFoldersToHide(); function getSelectedDirectory(): string; public constructor create( AOwner: TComponent ); override; destructor destroy(); override; property selectedDirectory: string read getSelectedDirectory; end ; implementation {$R *.dfm} uses StrUtils, DebugWindow, WindowsUtils, MyStrUtils, MyDialogs, I88n ; constructor TFormFolderSelect.create( AOwner: TComponent ); var i,y: integer; begin inherited create( AOwner ); translateUI(); _selectedDir := ''; pnlSpacer.BevelOuter := bvNone; pnlButtons.BevelOuter := bvNone; _foldersToHide := TQStringList.create(); fillFoldersToHide(); y := 0; for i := 0 to treeView.Items[0].Count - 1 do begin if( _foldersToHide.contains( treeView.Items[0].Item[y].Text ) ) then treeView.Items[0].Item[y].Delete() else inc(y) ; end ; end ; procedure TFormFolderSelect.translateUI(); begin // This function was generated automatically by Caption Collector 0.6.2. // Generation date: Thu Feb 28 14:04:23 2008 // File name: C:/libs/delphi/general_purpose/forms/test.dfm // File date: Thu Feb 28 13:50:22 2008 // Set Caption, Hint, Text, and Filter properties with self do begin Caption := tr( 'Browse for folder' ); lblSelectedFolder.Caption := tr( 'Selected folder:' ); lblFolder.Caption := tr( 'lblFolder' ); btnOK.Caption := tr( 'OK' ); btnCancel.Caption := tr( 'Cancel' ); btnNewFolder.Hint := tr( 'Create new folder' ); lblHeader.Caption := tr( 'Select a folder from the list below:' ); end ; // If any phrases are found that could not be automatically extracted by // Caption Collector, modify the following function to take care of them. // Otherwise, this function will be empty: translateUIManual(); end ; procedure TFormFolderSelect.translateUIManual(); begin end ; destructor TFormFolderSelect.destroy(); begin _foldersToHide.free(); inherited destroy(); end ; procedure TFormFolderSelect.fillFoldersToHide(); begin _foldersToHide.append( 'Recycle Bin' ); _foldersToHide.append( 'Control Panel' ); end ; function TFormFolderSelect.getSelectedDirectory(): string; begin result := _selectedDir; end ; procedure TFormFolderSelect.treeViewChange(Sender: TObject; Node: TTreeNode); begin if( canWriteToDirectory( treeView.SelectedFolder.PathName ) ) then begin lblFolder.Caption := abbrevPath( treeView.SelectedFolder.PathName, 60 ); _selectedDir := treeView.SelectedFolder.PathName; end else begin lblFolder.Caption := tr( '(Selected folder is read-only)' ); _selectedDir := ''; end ; end ; procedure TFormFolderSelect.btnNewFolderClick(Sender: TObject); var i: integer; success: boolean; newFolder: string; function removeSlashes( str: string ): string; begin result := str; if( ( '\' = leftStr( result, 1 ) ) or ( '/' = leftStr(result, 1 ) ) ) then result := removeSlashes( rightStr( result, length( result ) - 1 ) ) ; if( ( '\' = rightStr( result, 1 ) ) or ( '/' = rightStr(result, 1 ) ) ) then result := removeSlashes( leftStr( result, length( result ) - 1 ) ) ; end ; begin newFolder := msgInput( tr( 'Please enter a name for the new folder:' ), '', tr( 'New folder name' ), IMGQuestion, self ); newFolder := removeSlashes( trim( newFolder ) ); // If the folder already exists, alert the user, select it, and exit. if( directoryExists( treeView.SelectedFolder.PathName + '\' + newFolder ) ) then begin msgOK( tr( 'A folder with this name already exists.' ), tr( 'Folder creation failed' ), IMGInformation, self ); for i := 0 to treeView.Selected.Count - 1 do begin if( newFolder = treeView.Selected.Item[i].Text ) then begin treeView.Selected.Item[i].Selected := true; break; end ; end ; treeView.Selected.Focused := true; treeView.SetFocus(); exit; end ; // Otherwise, try to create the folder. try success := forceDirectories( treeView.SelectedFolder.PathName + '\' + newFolder ); except success := false; end; // If the folder was created, select it. // If it couldn't be created, display an error message. if( success ) then begin treeView.Refresh( treeView.Selected ); treeView.Selected.Expand( false ); for i := 0 to treeView.Selected.Count - 1 do begin if( newFolder = treeView.Selected.Item[i].Text ) then begin treeView.Selected.Item[i].Selected := true; break; end ; end ; treeView.Selected.Focused := true; treeView.SetFocus(); end else begin msgOK( tr( 'The new folder could not be created: you may not have sufficient permission to create it in the selected folder.' ), tr( 'Folder creation failed' ), IMGWarning, self ); end ; end ; procedure TFormFolderSelect.btnOKClick(Sender: TObject); begin // If the selected directory is can't be written to, show an error message. // Otherwise, all is good: close the form and move on. if( canWriteToDirectory( treeView.SelectedFolder.PathName ) ) then begin _selectedDir := treeView.SelectedFolder.PathName; ModalResult := mrOK; end else begin msgOK( tr( 'The selected folder cannot be written to: you may not have sufficient permission to write to it. Please select a different folder.' ), tr( 'Folder is read-only' ), IMGWarning, self ); _selectedDir := ''; end ; end ; procedure TFormFolderSelect.btnCancelClick(Sender: TObject); begin _selectedDir := ''; ModalResult := mrCancel; end ; procedure TFormFolderSelect.treeViewExpanded(Sender: TObject; Node: TTreeNode); var i, y: integer; begin if( nil <> _foldersToHide ) then begin y := 0; for i := 0 to node.Count - 1 do begin if( _foldersToHide.contains( node.Item[y].Text ) ) then node.Item[y].Delete() else inc(y) ; end ; end ; end ; end.
unit fcaes256; (************************************************************************* DESCRIPTION : File crypt/authenticate unit using AES256 REQUIREMENTS : TP5-7, D1-D7/D9-D10, FPC, VP EXTERNAL DATA : --- MEMORY USAGE : --- DISPLAY MODE : --- REFERENCES : (http://fp.gladman.plus.com/cryptography_technology/fileencrypt/fileencrypt.htm) REMARK : Version Date Author Modification ------- -------- ------- ------------------------------------------ 0.10 04.08.06 G.Tani Initial version based on Wolfgang Ehrhardt's Fcrypta 0.41: HMAC mode removed (the unit is focused on EAX mode); KDF2 now uses Whirlpool instead of SHA1 as primitive; functions changed to use 256 bit key; the header format is the same of fcrypta (plus bit2 in Flags for key size) and the digest is still a single AES block (128 bit of size). 0.11 04.08.06 W.Ehrhardt Portable code (line length < 128, unit name) 0.12 05.08.06 we Reintroduced HMAC (Whirlpool code) 0.13 13.08.06 we Changed unit name and description 0.14 14.06.07 we Type TAES_EAXContext 0.15 15.07.08 we Unit KDF/pbkdf2 0.16 22.11.08 we TFCA256_string replaced by Str255 from BTypes **************************************************************************) (*------------------------------------------------------------------------- (C) Copyright 2003-2008 Wolfgang Ehrhardt, Giorgio Tani This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ----------------------------------------------------------------------------*) {$i STD.INC} interface uses BTypes, {$ifdef USEDLL} {$ifdef VirtualPascal} CH_INTV, AES_INTV; {$else} CH_INTF, AES_INTF; {$endif} {$else} Hash, HMAC, Whirl512, KDF, AES_Type, AES_CTR, AES_EAX; {$endif} const C_FCA_Sig = $FC; KeyIterations : word = 1000; {Iterations in KeyDeriv} type TFCA256Salt = array[0..2] of longint; {96 Bit salt} TFCA256Hdr = packed record {same header format used in Fcrypt} {a plus key size bit in Flag for 256 bit keys (bit 2)} FCAsig: byte; {Sig $FC} Flags : byte; {High $A0; Bit2: 0=128bit (as in Fcrypta)} {1=256bit; Bit1: compression; Bit0: 1=EAX, 0=HMAC-CTR} Salt : TFCA256Salt; PW_Ver: word; end; TFCA256_AuthBlock = array[0..15] of byte; type TFCA_HMAC256_Context = record aes_ctx : TAESContext; {crypt context} hmac_ctx : THMAC_Context; {auth context} end; function FCA_EAX256_init(var cx: TAES_EAXContext; pPW: pointer; pLen: word; var hdr: TFCA256Hdr): integer; {-Initialize crypt context using password pointer pPW and hdr.salt} function FCA_EAX256_initS(var cx: TAES_EAXContext; sPW: Str255; var hdr: TFCA256Hdr): integer; {-Initialize crypt context using password string sPW and hdr.salt} function FCA_EAX256_encrypt(var cx: TAES_EAXContext; var data; dLen: word): integer; {-encyrypt a block of data in place and update EAX} function FCA_EAX256_decrypt(var cx: TAES_EAXContext; var data; dLen: word): integer; {-decyrypt a block of data in place and update EAX} procedure FCA_EAX256_final(var cx: TAES_EAXContext; var auth: TFCA256_AuthBlock); {-return final EAX tag} function FCA_HMAC256_init(var cx: TFCA_HMAC256_Context; pPW: pointer; pLen: word; var hdr: TFCA256Hdr): integer; {-Initialize crypt context using password pointer pPW and hdr.salt} function FCA_HMAC256_initS(var cx: TFCA_HMAC256_Context; sPW: Str255; var hdr: TFCA256Hdr): integer; {-Initialize crypt context using password string sPW and hdr.salt} function FCA_HMAC256_encrypt(var cx: TFCA_HMAC256_Context; var data; dLen: word): integer; {-encyrypt a block of data in place and update HMAC} function FCA_HMAC256_decrypt(var cx: TFCA_HMAC256_Context; var data; dLen: word): integer; {-decyrypt a block of data in place and update HMAC} procedure FCA_HMAC256_final(var cx: TFCA_HMAC256_Context; var auth: TFCA256_AuthBlock); {-return final HMAC-Whirlpool-128 digest} implementation type TX256Key = packed record {eXtended key for PBKDF} ak: packed array[0..31] of byte; {AES 256 bit key } hk: packed array[0..31] of byte; {HMAC key / EAX nonce } pv: word; {password verifier } end; {---------------------------------------------------------------------------} function FCA_HMAC256_init(var cx: TFCA_HMAC256_Context; pPW: pointer; pLen: word; var hdr: TFCA256Hdr): integer; {-Initialize crypt context using password pointer pPW and hdr.salt} var XKey: TX256Key; CTR : TAESBlock; pwph: PHashDesc; Err : integer; begin {CTR=0, random/uniqness from hdr.salt} fillchar(CTR, sizeof(CTR), 0); {derive the AES, HMAC keys and pw verifier} pwph := FindHash_by_ID(_Whirlpool); Err := pbkdf2(pwph, pPW, pLen, @hdr.salt, sizeof(TFCA256Salt), KeyIterations, XKey, sizeof(XKey)); {init AES CTR mode with ak} if Err=0 then Err := AES_CTR_Init(XKey.ak, 8*sizeof(XKey.ak), CTR, cx.aes_ctx); {exit if any error} FCA_HMAC256_init := Err; if Err<>0 then exit; {initialise HMAC with hk, here pwph is valid} hmac_init(cx.hmac_ctx, pwph, @XKey.hk, sizeof(XKey.hk)); {return pw verifier} hdr.PW_Ver := XKey.pv; hdr.FCASig := C_FCA_Sig; hdr.Flags := $A4; {burn XKey} fillchar(XKey, sizeof(XKey),0); end; {---------------------------------------------------------------------------} function FCA_HMAC256_initS(var cx: TFCA_HMAC256_Context; sPW: Str255; var hdr: TFCA256Hdr): integer; {-Initialize crypt context using password string sPW and hdr.salt} begin FCA_HMAC256_initS := FCA_HMAC256_init(cx, @sPW[1], length(sPW), hdr); end; {---------------------------------------------------------------------------} function FCA_HMAC256_encrypt(var cx: TFCA_HMAC256_Context; var data; dLen: word): integer; {-encyrypt a block of data in place and update HMAC} begin FCA_HMAC256_encrypt := AES_CTR_Encrypt(@data, @data, dLen, cx.aes_ctx); hmac_update(cx.hmac_ctx, @data, dLen); end; {---------------------------------------------------------------------------} function FCA_HMAC256_decrypt(var cx: TFCA_HMAC256_Context; var data; dLen: word): integer; {-decyrypt a block of data in place and update HMAC} begin hmac_update(cx.hmac_ctx, @data, dLen); FCA_HMAC256_decrypt := AES_CTR_Encrypt(@data, @data, dLen, cx.aes_ctx); end; {---------------------------------------------------------------------------} procedure FCA_HMAC256_final(var cx: TFCA_HMAC256_Context; var auth: TFCA256_AuthBlock); {-return final HMAC-Whirlpool-128 digest} var mac: THashDigest; begin hmac_final(cx.hmac_ctx,mac); move(mac, auth, sizeof(auth)); end; {---------------------------------------------------------------------------} function FCA_EAX256_init(var cx: TAES_EAXContext; pPW: pointer; pLen: word; var hdr: TFCA256Hdr): integer; {-Initialize crypt context using password pointer pPW and hdr.salt} var XKey: TX256Key; Err : integer; begin {derive the EAX key / nonce and pw verifier} Err := pbkdf2(FindHash_by_ID(_Whirlpool), pPW, pLen, @hdr.salt, sizeof(TFCA256Salt), KeyIterations, XKey, sizeof(XKey)); {init AES EAX mode with ak/hk} if Err=0 then Err := AES_EAX_Init(XKey.ak, 8*sizeof(XKey.ak), xkey.hk, sizeof(XKey.hk), cx);; {exit if any error} FCA_EAX256_init := Err; if Err<>0 then exit; {return pw verifier} hdr.PW_Ver := XKey.pv; hdr.FCASig := C_FCA_Sig; hdr.Flags := $A5; {burn XKey} fillchar(XKey, sizeof(XKey),0); end; {---------------------------------------------------------------------------} function FCA_EAX256_initS(var cx: TAES_EAXContext; sPW: Str255; var hdr: TFCA256Hdr): integer; {-Initialize crypt context using password string sPW and hdr.salt} begin FCA_EAX256_initS := FCA_EAX256_init(cx, @sPW[1], length(sPW), hdr); end; {---------------------------------------------------------------------------} function FCA_EAX256_encrypt(var cx: TAES_EAXContext; var data; dLen: word): integer; {-encyrypt a block of data in place and update EAX} begin FCA_EAX256_encrypt := AES_EAX_Encrypt(@data, @data, dLen, cx); end; {---------------------------------------------------------------------------} function FCA_EAX256_decrypt(var cx: TAES_EAXContext; var data; dLen: word): integer; {-decyrypt a block of data in place and update EAX} begin FCA_EAX256_decrypt := AES_EAX_decrypt(@data, @data, dLen, cx); end; {---------------------------------------------------------------------------} procedure FCA_EAX256_final(var cx: TAES_EAXContext; var auth: TFCA256_AuthBlock); {-return final EAX tag} begin AES_EAX_Final(TAESBlock(auth), cx); end; end.
unit ucardworker; {$mode objfpc}{$H+} interface uses Classes, SysUtils, uconfig, umsrworker; type { TCardWorker } TConnectState = (csNoConn = 0, csConnected = 1, csErrorConn = 2); TCardWorker = class private FMsrWorker: TMsrWorker; FState: TConnectState; FStatusByte: byte; public procedure Connect; procedure Disconnect; constructor Create; destructor Destroy; override; function GetFirmware(): string; function ReadCard(): string; function WriteCard(): string; overload; function WriteCard(Data: string): string; overload; procedure EraseCard(); procedure Reset(); property State: TConnectState read FState write FState; property StatusByte: byte read FStatusByte write FStatusByte; end; implementation { TCardWorker } procedure TCardWorker.Connect; begin FMsrWorker.ComName := Config.ComPortName; FMsrWorker.EncoderMode := config.EncoderMode; FMsrWorker.Connect; if FMsrWorker.GetConnectionStatus() then State := csConnected else State := csErrorConn; end; procedure TCardWorker.Disconnect; begin FMsrWorker.Disconnect; State := csNoConn; end; constructor TCardWorker.Create; begin FMsrWorker := TMsrWorker.Create(); end; destructor TCardWorker.Destroy; begin if FmsrWorker <> nil then FMsrWorker.Free; inherited Destroy; end; function TCardWorker.GetFirmware(): string; var Str: string; begin str := ''; str := FMsrWorker.GetFirmware(); Result := str; end; function TCardWorker.ReadCard(): string; begin Result := FMsrWorker.ReadCard(); end; function TCardWorker.WriteCard(): string; var Data: string; begin Data := ''; Data := config.CardPrefix + IntToStr(config.CurrentCardValue); Result := WriteCard(Data); end; function TCardWorker.WriteCard(Data: string): string; var Status: array of byte; Str : string; begin Str := FMsrWorker.WriteCard('', Data, ''); SetLength(Status, Length(Str)); Move(Str[1],Status[0],Length(Str)); StatusByte := Status[1]; Result := Data; end; procedure TCardWorker.EraseCard(); begin FMsrWorker.EraseCard(); end; procedure TCardWorker.Reset(); begin FMsrWorker.Reset(); end; end.
unit SelectServerAlias; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.StrUtils, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Data.DB, Global, GlobalVars, JvExComCtrls, JvListView, nxtwWinsockTransport, nxtmSharedMemoryTransport, nxllTransport, nxptBasePooledTransport, nxtnNamedPipeTransport, nxsdServerEngine, nxreRemoteServerEngine, nxllComponent, nxdb, Vcl.StdCtrls, Vcl.Buttons, Vcl.WinXCtrls, JvExStdCtrls, JvListBox, Vcl.Imaging.pngimage, JvXPCore, JvXPButtons, JvTabBar, JvPageList, JvExControls, Vcl.ExtCtrls, JvExExtCtrls, JvExtComponent, JvPanel, JvBaseDlg, JvSelectDirectory; type TGetServersAlias = class(TForm) jvpnl_TopPanel: TJvPanel; ts_LocalOrNetworked: TToggleSwitch; jvtbr_DbBar: TJvTabBar; pglst_LocalNetworkPages: TJvPageList; jvsp_LocalDb: TJvStandardPage; jvsp_NetworkDb: TJvStandardPage; lbl_Servers: TLabel; lst_Servers: TJvListBox; lst_Alias: TJvListBox; lbl_Alias: TLabel; lbl_Issues: TLabel; mmo_IssuesMemo: TMemo; jvpnl_FooterPanel: TJvPanel; lbl_SelectedItems: TLabel; bbt_OK: TBitBtn; bbt_Cancel: TBitBtn; jvmdrntbrpntr__1: TJvModernTabBarPainter; edt_LocalAlias: TEdit; lbl_Alias1: TLabel; lbl_DatabasePath: TLabel; edt_DbPath: TEdit; btn__GetPrjPath: TJvXPButton; lbl_SelectServerType: TLabel; JvSelectDirectory1: TJvSelectDirectory; procedure FormActivate(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure ts_LocalOrNetworkedClick(Sender: TObject); procedure btn__GetPrjPathClick(Sender: TObject); procedure pglst_LocalNetworkPagesChange(Sender: TObject); procedure FormShow(Sender: TObject); procedure bbt_OKClick(Sender: TObject); procedure lst_ServersClick(Sender: TObject); procedure lst_AliasClick(Sender: TObject); private { Private declarations } Session : TnxSession; ServerWinSock : TnxWinsockTransport; ServerNamedPipe: TnxNamedPipeTransport; SharedMemory : TnxSharedMemoryTransport; ServerEngine : TnxRemoteServerEngine; fServerName : string; fAliasName : string; fTransport : TTransportUsed; fLocalDbPath : string; function GetServers: Boolean; public { Public declarations } function Execute: boolean; property ServerName: string read fServerName write fServerName; property AliasName: string read fAliasName write fAliasName; property Transport: TTransportUsed read fTransport write fTransport default tranNone; property LocalDbPath: string read fLocalDbPath write fLocalDbPath; end; var GetServersAlias: TGetServersAlias; implementation Uses DataMod; {$R *.dfm} { TForm2 } procedure TGetServersAlias.bbt_OKClick(Sender: TObject); begin if ts_LocalOrNetworked.State = tssOff then begin fAliasName := edt_LocalAlias.Text; fLocalDbPath := edt_DbPath.Text; end else begin // fServerName := lst_Servers.Items[lst_Servers.ItemIndex]; // fAliasName := lst_Alias.Items[lst_Alias.ItemIndex]; // fTransport := end; end; procedure TGetServersAlias.btn__GetPrjPathClick(Sender: TObject); begin if JvSelectDirectory1.Execute then begin // if not (dm_DataMod.nxtbl_NxDbSqlToolsPrjs.state in [dsEdit, dsInsert]) then // dm_DataMod.nxtbl_NxDbSqlToolsPrjs.edit // else // if (dm_DataMod.nxtbl_NxDbSqlToolsPrjs.Eof) or (dm_DataMod.nxtbl_NxDbSqlToolsPrjs.Bof) then // exit // else // dm_DataMod.nxtbl_NxDbSqlToolsPrjs.edit; edt_DbPath.tEXT := ExpandUNCFileName(JvSelectDirectory1.Directory); // dm_DataMod.nxtbl_NxDbSqlToolsPrjs.Post; end; end; function TGetServersAlias.Execute: boolean; begin Result := (ShowModal = mrOK); end; procedure TGetServersAlias.FormActivate(Sender: TObject); begin var OldCursor: tCursor := Screen.Cursor; Screen.Cursor := crHourGlass; try GetServers; finally Screen.Cursor := OldCursor; end; end; procedure TGetServersAlias.FormClose(Sender: TObject; var Action: TCloseAction); begin Session.Close; ServerEngine.Close; ServerWinSock.close; ServerNamedPipe.Close; FreeAndNil(ServerWinSock); FreeAndNil(ServerNamedPipe); FreeAndNil(ServerEngine); FreeAndNil(Session); end; procedure TGetServersAlias.FormCreate(Sender: TObject); begin ServerWinSock := TnxWinsockTransport.Create(nil); ServerNamedPipe := TnxNamedPipeTransport.Create(nil); ServerEngine := TnxRemoteServerEngine.Create(nil); Session := TnxSession.Create(nil); fServerName := 'None'; fAliasName := 'None'; pglst_LocalNetworkPages.ActivePage := jvsp_LocalDb; jvtbr_DbBar.Tabs.Items[0]; Height := 298; Width := 544; end; procedure TGetServersAlias.FormShow(Sender: TObject); begin if ts_LocalOrNetworked.State = tssOff then jvtbr_DbBar.Tabs[0].Selected := true else jvtbr_DbBar.Tabs[1].Selected := true; end; function TGetServersAlias.GetServers: Boolean; var sl: TStringList; index: integer; function getWinSock: Boolean; begin result := true; try ServerWinSock.GetServerNames(sl, 5000); for var index: integer := 0 to sl.count - 1 do lst_Servers.Items.Add('TCP|'+sl[index]); except on e: EDatabaseError do begin mmo_IssuesMemo.Lines.Add('===== EDatabaseError Exception. Openning and getting servers: WinSock transport'); mmo_IssuesMemo.Lines.Add('Error Msg: ' + E.Message); Result := False; end; end; end; function getNamedPipe: Boolean; begin Result := True; try ServerNamedPipe.GetServerNames(sl, 5000); for var index: integer := 0 to sl.count - 1 do lst_Servers.Items.Add('NP|'+sl[index]); except on e: EDatabaseError do begin mmo_IssuesMemo.Lines.Add('===== EDatabaseError Exception. Openning and getting servers: Named Pipe transport'); mmo_IssuesMemo.Lines.Add('Error Msg: ' + E.Message); Result := False; end; end; end; begin lst_Servers.Items.Clear; lst_Alias.Items.Clear; mmo_IssuesMemo.Lines.Clear; sl := TStringList.Create; try Result := getWinSock; if Result then Result := getNamedPipe; finally FreeAndNil(sl); end; mmo_IssuesMemo.Lines.Add('No server selected'); end; procedure TGetServersAlias.lst_AliasClick(Sender: TObject); begin if lst_Alias.ItemIndex > -1 then begin mmo_IssuesMemo.Lines.Clear; lbl_SelectedItems.Caption := lst_Servers.Items[lst_Servers.ItemIndex] + '/'+ lst_Alias.Items[lst_Alias.ItemIndex]; fAliasName := lst_Alias.Items[lst_Alias.ItemIndex]; end; end; procedure TGetServersAlias.lst_ServersClick(Sender: TObject); begin if lst_Servers.ItemIndex > -1 then begin mmo_IssuesMemo.Lines.Clear; ServerWinSock.Close; ServerNamedPipe.Close; lbl_SelectedItems.Caption := lst_Servers.Items[lst_Servers.ItemIndex]; var indexLeft : integer := Pos('|', lst_Servers.Items[lst_Servers.ItemIndex]); var indexRight : integer := Length(lst_Servers.Items[lst_Servers.ItemIndex]) - indexLeft; var TransStr: string := AnsiLeftStr(lst_Servers.Items[lst_Servers.ItemIndex], indexLeft - 1); var ServerStr: string := AnsiRightStr(lst_Servers.Items[lst_Servers.ItemIndex], indexRight ); if TransStr = 'TCP' then begin ServerWinSock.ServerName := ServerStr; ServerEngine.Transport := ServerWinSock; ServerWinSock.Open; fTransport := tranWinSock; end else begin if TransStr = 'NP' then begin ServerNamedPipe.ServerName := ServerStr; ServerEngine.Transport := ServerNamedPipe; ServerNamedPipe.Open; fTransport := tranNamePipe; end else begin ShowMessage('Error Not Server: ' + ServerStr); Exit; end; end; fServerName := ServerStr; Session.ServerEngine := ServerEngine; Session.Open; Session.GetAliasNames(lst_Alias.Items); mmo_IssuesMemo.Lines.Add('No Alias selected'); end; end; procedure TGetServersAlias.pglst_LocalNetworkPagesChange(Sender: TObject); begin if pglst_LocalNetworkPages.ActivePage = jvsp_LocalDb then Height := 298 else Height := 566; end; procedure TGetServersAlias.ts_LocalOrNetworkedClick(Sender: TObject); begin if ts_LocalOrNetworked.state = tssOff then begin fServerName := ''; fAliasName := ''; fTransport := tranNone; lst_Servers.Enabled := False; lst_Alias.Enabled := False; lbl_SelectedItems.Caption := 'Local Database'; end else begin lst_Servers.Enabled := true; lst_Alias.Enabled := true; lbl_SelectedItems.Caption := ''; lst_Servers.ItemIndex := -1; lst_Alias.ItemIndex := -1; end; end; end.
unit DAOTest; interface uses DataAccessObjects, LTClasses, Generics.Collections; type TDAOTest = class(TDAOBase) private function SelectListening(TestIndex: Integer): TObjectList<TListening>; function SelectSpeaking(TestIndex: integer) : TObjectList<TSpeaking>; function SelectReading(TestIndex: integer) : TObjectList<TReading>; function SelectWriting(TestIndex: integer) : TObjectList<TWriting>; public function SelectTestList: TObjectList<TTest>; function LoadTest(TestIndex: Integer): TTest; end; implementation { TDAOTest } function TDAOTest.SelectListening(TestIndex: Integer): TObjectList<TListening>; var Listening: TListening; begin Result := TObjectList<TListening>.Create; Query.Close; Query.CommandText := 'SELECT t1.*, t2.* FROM ' + '(SELECT * FROM listening ' + ' WHERE test_idx = :idx) t1 ' + 'LEFT JOIN quiz t2 ' + 'ON t1.quiz_idx = t2.idx;'; Query.Params.ParamByName('idx').AsInteger := TestIndex; Query.Open; while not Query.Eof do begin begin Listening := TListening.Create; Listening.TestIdx := Query.FieldByName('test_idx').AsInteger; Listening.QuizIdx := Query.FieldByName('quiz_idx').AsInteger; Listening.QuizNumber := Query.FieldByName('number').AsInteger; Listening.Quiz := Query.FieldByName('question').Asstring; Listening.A := Query.FieldByName('A').Asstring; Listening.B := Query.FieldByName('B').Asstring; Listening.C := Query.FieldByName('C').Asstring; Listening.D := Query.FieldByName('D').Asstring; Listening.Answer := Query.FieldByName('answer').Asstring; Result.Add(Listening); Query.Next; end; end; end; function TDAOTest.LoadTest(TestIndex: Integer): TTest; begin Result := TTest.Create; Result.TestIndex := TestIndex; Result.ListeningList := SelectListening(TestIndex); Result.SpeakingList := SelectSpeaking(TestIndex); Result.ReadingList := SelectReading(TestIndex); Result.WritingList := SelectWriting(TestIndex); Result.Initialize; end; function TDAOTest.SelectReading(TestIndex: integer): TObjectList<TReading>; var Reading: TReading; I: Integer; Quiz: TLRQuiz; begin Result := TObjectList<TReading>.Create; Query.Close; Query.CommandText := 'SELECT * FROM reading WHERE test_idx = :idx ORDER BY example_seq '; Query.Params.ParamByName('idx').AsInteger := TestIndex; Query.Open; while not Query.Eof do begin Reading := TReading.Create; Reading.ExampleIdx := Query.FieldByName('idx').AsInteger; Reading.ExampleNumber := Query.FieldByName('example_seq').AsInteger; Reading.ExampleText := Query.FieldByName('example_text').AsString; Result.Add(Reading); Query.Next; end; for I := 0 to Result.Count - 1 do begin Query.Close; Query.CommandText := 'SELECT t2.* FROM ' + '(SELECT * FROM reading_example_quiz ' + 'WHERE reading_idx = :idx) t1 ' + 'INNER JOIN quiz t2 ' + 'ON t1.quiz_idx = t2.idx; '; Query.Params.ParamByName('idx').AsInteger := Result.Items[I].ExampleIdx; Query.Open; while not Query.Eof do begin Quiz := TReadingQuiz.Create; Quiz.QuizIdx := Query.FieldByName('idx').AsInteger; Quiz.QuizNumber := Query.FieldByName('number').AsInteger; Quiz.Quiz := Query.FieldByName('question').Asstring; Quiz.A := Query.FieldByName('A').Asstring; Quiz.B := Query.FieldByName('B').Asstring; Quiz.C := Query.FieldByName('C').Asstring; Quiz.D := Query.FieldByName('D').Asstring; Quiz.Answer := Query.FieldByName('answer').Asstring; Result.Items[I].QuizList.Add(Quiz); Query.Next; end; end; end; function TDAOTest.SelectTestList: TObjectList<TTest>; var Test: TTest; begin Result := TObjectList<TTest>.Create; Query.Close; Query.CommandText := 'SELECT * FROM test'; Query.Open; // todo : 현재 로그인한 학생인 경우 학생이 시험을 봤던 정보도 같이 가져와서 보여줘야함. Query.First; while not Query.Eof do begin Test := TTest.Create; Test.Idx := Query.FieldByName('idx').AsInteger; Test.Title := Query.FieldByName('title').AsString; Result.Add(Test); Query.Next; end; end; function TDAOTest.SelectSpeaking(TestIndex: integer): TObjectList<TSpeaking>; var Speaking: TSpeaking; begin Result := TObjectList<TSpeaking>.Create; Query.Close; Query.CommandText := 'SELECT * FROM speaking WHERE test_idx = :index'; Query.Params.ParamByName('index').AsInteger := TestIndex; Query.Open; while not Query.Eof do begin begin Speaking := TSpeaking.Create; Speaking.TestIdx := Query.FieldByName('test_idx').AsInteger; Speaking.QuizNumber := Query.FieldByName('number').AsInteger; Speaking.Quiz := Query.FieldByName('quiz').AsString; Result.Add(Speaking); Query.Next; end; end; end; function TDAOTest.SelectWriting(TestIndex: integer): TObjectList<TWriting>; var Writing: TWriting; begin Result := TObjectList<TWriting>.Create; Query.Close; Query.CommandText := 'SELECT * FROM writing WHERE test_idx = :index'; Query.Params.ParamByName('index').AsInteger := TestIndex; Query.Open; while not Query.Eof do begin begin Writing := TWriting.Create; Writing.TestIdx := Query.FieldByName('test_idx').AsInteger; Writing.QuizNumber := Query.FieldByName('number').AsInteger; Writing.ExampleText := Query.FieldByName('example_text').AsString; Writing.Quiz := Query.FieldByName('quiz').AsString; Result.Add(Writing); Query.Next; end; end; end; end.
unit osReportUtils; interface uses Classes, acCustomSQLMainDataUn, osSQLDataSet, SysUtils, DB, ppReport, daDataModule, daQueryDataView, ppTypes,daIDE, daDBExpress, ppCTDsgn, raIDE, myChkBox, ppModule, FMTBcd, osCustomDataSetProvider, SqlExpr, osSQLDataSetProvider, daSQl, osSQLQuery, osComboFilter, ppDBPipe, osClientDataSet, acReportContainer, Forms, osCustomMainFrm, acCustomReportUn; type TIdade = class private Fdias: integer; FdataReferencia: TDateTime; protected function getAnos: integer; function getDias: integer; function getMeses: integer; function getString: string; public constructor Create(dias: integer; referencia: TDateTime = 0); property dias: integer read getDias; property anos: integer read getAnos; property meses: integer read getMeses; property dataReferencia: TDateTime read FdataReferencia write FdataReferencia; property asString: string read getString; end; function getIdadeDias(idade: string; conn: TSQLConnection = nil): integer; function getTemplateByName(name: string; stream: TMemoryStream): boolean; function getTemplateByID(id: integer; stream: TMemoryStream; var config: TConfigImpressao): boolean; function getTemplateIDByName(name: string): integer; function getTemplateLaudoRascunho(name: string; stream: TMemoryStream; var config: TConfigImpressao): boolean; procedure replaceReportSQL(report: TppReport; template: TMemoryStream; strSQL: String); procedure replaceReportSQLAddParam(report: TppReport; template: TMemoryStream; strSelect: String; strWhere: String; strOrder: string = ''); procedure replaceReportSQLAddWhere(report: TppReport; template: TMemoryStream; strWHERE: String); function tiraNumerosDoFinal(str: String): string; function ConvertMask(mask: string): string; procedure replaceReportSQL2(report: TppReport; template: TMemoryStream; strSQL: String; params: TStringList = nil; mapeamentos: TStringList = nil; recipient: TDataModule = nil); implementation uses daDataView, ppClass, FwConstants, DateUtils, Dialogs; // RelatorioEditFormUn function getTemplateByName(name: string; stream: TMemoryStream): boolean; var query: TosSQLDataset; report: string; ss: TStringStream; begin name := UpperCase(Name); Result := false; report := TacReportContainer(Application.MainForm.FindComponent('FReportDepot')). findReportByName(name); if Length(report) > 0 then begin ss := TStringStream.Create(report); stream.LoadFromStream(ss); Result := True; end else begin query := TosSQLDataSet.Create(nil); try query.SQLConnection := acCustomSQLMainData.SQLConnectionMeta; query.CommandText := ' SELECT ' + ' template, '+ ' ITEM_ID '+ ' FROM ' + ' RB_ITEM '+ ' WHERE ' + ' UPPER(name) like UPPER(' + quotedStr(name) + ')'; query.Open; if query.RecordCount>0 then begin TBLOBField(query.fields[0]).SaveToStream(stream); TacReportContainer(Application.MainForm.FindComponent('FReportDepot')). addReport(query.fields[1].AsInteger, name, TBLOBField(query.fields[0]).AsString); Result := true; end; finally FreeAndNil(query); end; end; end; function getTemplateLaudoRascunho(name: string; stream: TMemoryStream; var config: TConfigImpressao): boolean; var query: TosSQLQuery; vIdRelatorio: Integer; begin name := UpperCase(Name); Result := false; query := TosSQLQuery.Create(nil); try query.SQLConnection := acCustomSQLMainData.SQLConnectionMeta; query.CommandText := ' SELECT ' + ' I.template, '+ ' I.ITEM_ID, '+ ' r.IdRelatorio '+ ' FROM ' + ' RB_ITEM I '+ ' join relatorio r on r.item_id = I.item_id '+ ' join tipolaudo tp on tp.idrelatoriolaudo = r.idrelatorio '+ ' WHERE tp.rascunho = ''S'' '; query.open; if query.fields[0].AsString <> '' then begin TBLOBField(query.fields[0]).SaveToStream(stream); TacReportContainer(Application.MainForm.FindComponent('FReportDepot')). addReport(query.fields[1].AsInteger, name, TBLOBField(query.fields[0]).AsString); Result := true; end; if Result then begin vIdRelatorio := query.FieldByName('IdRelatorio').AsInteger; query.Close; query.SQL.Text := ' select r.margemsuperior, ' + ' r.margeminferior, ' + ' r.margemesquerda, ' + ' r.margemdireita, ' + ' r.alturapapel, ' + ' r.largurapapel, ' + ' r.orientation, ' + ' r.classeimpressora, ' + ' r.tiposaida, ' + ' rb.item_id from relatorio r'+ ' join rb_item rb on r.item_id = rb.item_id'+ ' where r.idrelatorio = '+IntToStr(vIdRelatorio); query.Open; if not query.IsEmpty then begin if not query.fieldByName('orientation').IsNull then config.orientation := query.fieldByName('orientation').AsInteger; if not query.fieldByName('larguraPapel').IsNull then config.larguraPapel := query.fieldByName('larguraPapel').AsInteger; if not query.fieldByName('alturaPapel').IsNull then config.alturaPapel := query.fieldByName('alturaPapel').AsInteger; if not query.fieldByName('margemSuperior').IsNull then config.margemSuperior := query.fieldByName('margemSuperior').AsInteger; if not query.fieldByName('margemInferior').IsNull then config.margemInferior := query.fieldByName('margemInferior').AsInteger; if not query.fieldByName('margemEsquerda').IsNull then config.margemEsquerda := query.fieldByName('margemEsquerda').AsInteger; if not query.fieldByName('margemDireita').IsNull then config.margemDireita := query.fieldByName('margemDireita').AsInteger; // if not query.fieldByName('tipoSaida').IsNull then // config.tipoSaida := query.fieldByName('tipoSaida').AsString; end; end; finally FreeAndNil(query); end; end; function getTemplateIDByName(name: string): integer; var query: TosSQLDataset; id: Integer; begin name := UpperCase(Name); id := TacReportContainer(Application.MainForm.FindComponent('FReportDepot')). findRportIdByName(name); if id <> -1 then begin Result := id; end else begin query := TosSQLDataSet.Create(nil); try query.SQLConnection := acCustomSQLMainData.SQLConnection; query.CommandText := ' SELECT ' + ' ITEM_ID '+ ' FROM ' + ' RB_Item '+ ' WHERE ' + ' UPPER(name) like UPPER(' + quotedStr(name) + ')'; query.Open; Result := -1; if not query.eof then Result := query.fields[0].asInteger; finally FreeAndNil(query); end; end; end; function getTemplateById(id: integer; stream: TMemoryStream; var config: TConfigImpressao): boolean; var query: TosSQLDataset; report: string; ss: TStringStream; ComponenteRelatorio: TacReportContainer; begin Result := false; query := TosSQLDataSet.Create(nil); try query.SQLConnection := acCustomSQLMainData.SQLConnection; query.CommandText := ' SELECT ' + ' template, '+ ' name '+ ' FROM ' + ' RB_ITEM '+ ' WHERE ' + ' ITEM_ID = ' + intToStr(id); query.Open; if query.RecordCount>0 then config.NomeRelatorio := query.FieldByName('name').AsString; if Application.MainForm <> nil then report := TacReportContainer(Application.MainForm.FindComponent('FReportDepot')).findReportById(id) else begin //Dessa forma o agendador pode ter acesso ao componente de relatório ComponenteRelatorio := TacReportContainer.Create(nil); report := ComponenteRelatorio.findReportById(id); end; try if Length(report) > 0 then begin try ss := TStringStream.Create(report); stream.LoadFromStream(ss); Result := True; finally FreeAndNil(ss); end; end else begin if query.RecordCount>0 then begin TBLOBField(query.fields[0]).SaveToStream(stream); if Application.MainForm <> nil then TacReportContainer(Application.MainForm.FindComponent('FReportDepot')).addReport(id, query.fields[1].AsString, query.fields[0].AsString) else ComponenteRelatorio.addReport(id, query.fields[1].AsString, query.fields[0].AsString); config.NomeRelatorio := query.FieldByName('name').AsString; Result := True; end; end; finally if Application.MainForm = nil then FreeAndNil(ComponenteRelatorio); end; finally FreeAndNil(query); end; end; procedure replaceReportSQLAddWhere(report: TppReport; template: TMemoryStream; strWHERE: String); var lDataModule: TdaDataModule; liIndex, i: Integer; lDataView: TdaDataView; nomePipeline: string; aSQL: TdaSQL; begin if template.Size <> 0 then report.Template.LoadFromStream(template); lDataModule := daGetDataModule(Report.MainReport); if (lDataModule <> nil) then begin liIndex := 0; while liIndex < lDatamodule.DataViewCount do begin lDataView := lDataModule.DataViews[liIndex]; for i := 0 to lDataView.DataPipelineCount-1 do begin nomePipeline := tiraNumerosDoFinal(lDataView.DataPipelines[i].Name) ; if UpperCase(nomePipeline) = 'PIPELINE' then begin aSQL := TdaQueryDataView(lDataView).SQL; aSQL.EditSQLAsText := True; aSQL.SQLText.Add(strWHERE); end; end; inc(liIndex); end; end; end; procedure replaceReportSQL2(report: TppReport; template: TMemoryStream; strSQL: String; params: TStringList; mapeamentos: TStringList; recipient: TDataModule); var liIndex: Integer; lDataModule: TdaDataModule; lDataView: TdaDataView; aSQL: TDaSQL; i: integer; nomePipeline: string; pipeline: TComponent; function getSQL(nomePipeline: String): string; var i: integer; comp: TComponent; begin for i := 0 to mapeamentos.Count-1 do begin if UpperCase(nomePipeline) = UpperCase(Copy(mapeamentos[i], 0, pos(',',mapeamentos[i])-1)) then begin comp := recipient.FindComponent(copy(mapeamentos[i], pos(',',mapeamentos[i])+1,length(mapeamentos[i]))); result := (comp as TSQLDataSet).CommandText; exit; end; end; end; function substParams(strSQL: String): string; var i: Integer; nomeParam: string; valor: integer; begin for i := 0 to params.Count-1 do begin nomeParam := copy(params[i], 0, pos('=', params[i])-1); valor := strToInt(copy(params[i], pos('=', params[i])+1, length(params[i]))); while Pos(':'+upperCase(nomeParam), upperCase(strSQL))>0 do begin strSQL := copy(strSQL, 0, Pos(':'+upperCase(nomeParam), upperCase(strSQL))-1) + intToStr(valor) + copy(strSQL,Pos(':'+upperCase(nomeParam), upperCase(strSQL))+1+length(':'+nomeParam),length(strSQL)) end; result := StrSQL; end; end; begin report.Template.LoadFromStream(template); // aSQL := nil; lDataModule := daGetDataModule(Report.MainReport); if (lDataModule <> nil) then begin liIndex := 0; while liIndex < lDatamodule.DataViewCount do begin lDataView := lDataModule.DataViews[liIndex]; for i := 0 to lDataView.DataPipelineCount-1 do begin nomePipeline := tiraNumerosDoFinal(lDataView.DataPipelines[i].Name) ; if recipient<>nil then begin pipeline := recipient.FindComponent(nomePipeline); if TosClientDataSet(TppDBPipeline(pipeline).DataSource.DataSet).dataProvider<>nil then strSQL := TosSQLDataSet(TosSQLDataSetProvider(TosClientDataSet(TppDBPipeline(pipeline).DataSource.DataSet).dataProvider).dataset).commandtext else strSQL := getSQL(nomePipeline); strSQL := substParams(strSQL); aSQL := TdaQueryDataView(lDataView).SQL; aSQL.EditSQLAsText := True; if strSQL <> '' then aSQL.SQLText.Text := strSQL; end; end; inc(liindex); end; end; end; {-------------------------------------------------------------------------  Objetivo   > Esta função foi criada para que se ache componentes renomeados pelo delphi. Por exemplo Pipeline vira Pipeline1  Parâmetros > str: a string a ser alterada  Retorno    >  Criação    >  Observações> Comentário inicializado em 07/03/2006 por Ricardo N. Acras  Atualização> 07/03/2006 - Inserido inicialização do index  ------------------------------------------------------------------------} function tiraNumerosDoFinal(str: String): string; var i, index: integer; begin index := 0; for i := length(str) downto 0 do begin if not((Ord(str[i])>=48) AND (Ord(str[i])<=57)) then begin index := i; break; end; end; result := copy(str, 0, index); end; procedure replaceReportSQL(report: TppReport; template: TMemoryStream; strSQL: String); var liIndex, i: Integer; lDataModule: TdaDataModule; lDataView: TdaDataView; aSQL: TDaSQL; nomePipeline: String; begin report.Template.LoadFromStream(template); aSQL := nil; lDataModule := daGetDataModule(Report.MainReport); if (lDataModule <> nil) then begin liIndex := 0; while (liIndex < lDatamodule.DataViewCount) and (aSQL = nil) do begin lDataView := lDataModule.DataViews[liIndex]; if (lDataView <> nil) and (lDataView is TdaQueryDataView) and (Report.Datapipeline <> nil) and (Report.DataPipeline.Dataview = lDataview) then begin for i := 0 to lDataView.DataPipelineCount-1 do begin nomePipeline := tiraNumerosDoFinal(lDataView.DataPipelines[i].Name) ; if (UpperCase(nomePipeline)=upperCase(report.DataPipeline.Name)) then begin aSQL := TdaQueryDataView(lDataView).SQL; aSQL.EditSQLAsText := True; if strSQL <> '' then aSQL.SQLText.Text := strSQL; end; end; end; Inc(liIndex); end; end; end; function ConvertMask(mask: string): string; const point: char = '.'; comma: char = ','; var n: integer; i: integer; c: char; begin n := Length(mask); if n > 0 then begin SetLength(Result, n); for i := 1 to n do begin c := mask[i]; if c = comma then c := point else if c = point then c := comma; Result[i] := c; end; end else Result := ''; end; { TIdade } constructor TIdade.Create(dias: integer; referencia: TDateTime = 0); begin Fdias := dias; if referencia = 0 then dataReferencia := acCustomSQLMainData.GetServerDate else dataReferencia := referencia end; function TIdade.getAnos: integer; var dia, mes, ano: word; diaAtual, mesAtual, anoAtual: word; numAnos: integer; begin DecodeDate(dataReferencia, anoAtual, mesAtual, diaAtual); DecodeDate(dataReferencia-Fdias, ano, mes, dia); //calcular o número de anos que a pessoa possui numAnos := anoAtual - ano; //se o mês atual é maior que o mês do nascimento, já fechou o último ano // nenhum cálculo adicional necessário //se o mês é menor ou o mês é igual mas o dia é menor deve decrementar o ano if ((mesAtual<mes) OR ((mesAtual=mes)AND(diaAtual<dia))) then numAnos := numAnos-1; result := numAnos; end; function TIdade.getMeses: integer; var dia, mes, ano: word; diaAtual, mesAtual, anoAtual: word; numMeses: integer; begin DecodeDate(dataReferencia, anoAtual, mesAtual, diaAtual); DecodeDate(dataReferencia-Fdias, ano, mes, dia); //calcular o número de meses que a pessoa possui numMeses := getAnos*12; if mesAtual<mes then numMeses := numMeses + 12-mes+mesAtual; if mes<mesAtual then numMeses := numMeses + mesAtual-mes; if mes=mesAtual then numMeses:= 12; //corrigir o número de meses pois pode ainda não ter fechado o último if diaAtual<dia then numMeses := numMeses-1; result := numMeses; end; function TIdade.getDias: integer; begin result := Fdias; end; function TIdade.getString: string; var mes, mesano: word; ano, ano2: Integer; dataNascimento: TDateTime; Total_dias: Real; begin DataNascimento:= FdataReferencia - Fdias; Total_dias:= FDias; Ano := StrToInt(FormatDateTime('YY', DataNascimento)); Ano2 := StrToInt(FormatDateTime('YYYY', DataNascimento)); Mes := StrToInt(FormatDateTime('MM', DataNascimento)); mesano:= Mes; if mes > 2 then Inc(Ano2); while Total_dias >= DaysInAYear(Ano2) do begin Total_dias := Total_dias - DaysInAYear(Ano2); Ano := Ano + 1; Ano2 := Ano2 + 1; end; while Total_dias > 28 do begin if Total_dias >= DaysInAMonth(Ano, Mes) then begin Total_dias := Total_dias - DaysInAMonth(Ano, mesano); Mes := Mes + 1; mesano:= mesano + 1; if mesano > 12 then mesano:= 1; end else break; end; Ano := Ano - StrToInt(FormatDateTime('YY', DataNascimento)); Mes := Mes - StrToInt(FormatDateTime('MM', DataNascimento)); Result:= ''; if Ano > 0 then begin result:= IntToStr(Ano); if ano > 1 then result:= result + ' anos ' else result:= result + ' ano '; end; if (Mes > 0) then begin if Ano > 0 then Result:= Result + 'e '; result:= Result + IntToStr(Mes); if Mes > 1 then result:= result + ' meses ' else result:= result + ' mês '; end; if (Total_dias > 0) and (Ano < 1) then begin if (Ano > 0) or (Mes > 0) then Result:= Result + 'e '; result:= Result + FloatToStr(Total_dias); if Total_dias > 1 then result:= result + ' dias ' else result:= result + ' dia '; end else if (Total_dias = 0) and (meses = 12) and (ano = 0) then //recem nascido result:= '0 dia'; end; function getIdadeDias(idade: string; conn: TSQLConnection = nil): integer; var tipoIdade: String; original: integer; data: TDateTime; begin result := 0; idade := trim(idade); tipoIdade := idade[length(idade)]; original := StrToInt(copy(idade, 1, length(idade)-1)); data := acCustomSQLMainData.GetServerDate(conn); case tipoIdade[1] of 'd': result := DaysBetween(data, IncDay(data, original * -1)); 'm': result := DaysBetween(data, INCMONTH(data, original * -1)); 'a': result := DaysBetween(data, IncYear(data, original * -1)); end; end; procedure replaceReportSQLAddParam(report: TppReport; template: TMemoryStream; strSelect: String; strWhere: String; strOrder: string); var liIndex, i, y: Integer; lDataModule: TdaDataModule; lDataView: TdaDataView; aSQL: TDaSQL; nomePipeline: String; crit: TdaCriteria; ord: TdaField; criterios, item: TStringList; begin report.Template.LoadFromStream(template); aSQL := nil; lDataModule := daGetDataModule(Report.MainReport); if (lDataModule <> nil) then begin liIndex := 0; while (liIndex < lDatamodule.DataViewCount) and (aSQL = nil) do begin lDataView := lDataModule.DataViews[liIndex]; if (lDataView <> nil) and (lDataView is TdaQueryDataView) and (Report.Datapipeline <> nil) and (Report.DataPipeline.Dataview = lDataview) then begin for i := 0 to lDataView.DataPipelineCount-1 do begin nomePipeline := tiraNumerosDoFinal(lDataView.DataPipelines[i].Name) ; if (UpperCase(nomePipeline)=upperCase(report.DataPipeline.Name)) then begin aSQL := TdaQueryDataView(lDataView).SQL; if aSQL.EditSQLAsText then begin if strSelect <> '' then aSQL.SQLText.Text := strSelect; end else begin if strWhere <> '' then begin crit := aSQL.AddCriteria(dacrField); crit.Expression := '1'; crit.Value := '1 AND '+strWhere; end; if strOrder <> '' then begin try criterios := TStringList.Create; criterios.Delimiter := ','; criterios.DelimitedText := '"' + StringReplace(strOrder, ',', '"' + ',' + '"', [rfReplaceAll]) + '"'; for y := 0 to criterios.Count -1 do begin try item := TStringList.Create; item.Delimiter := ' '; item.DelimitedText := criterios.Strings[y]; ord := aSQL.GetFieldForSQLFieldName(item.Strings[0]).Clone(nil); ord.ChildType := 2; if (item.Count = 2) and (UpperCase(item.Strings[1]) = 'DESC') then aSQL.AddOrderByField(ord,False) else aSQL.AddOrderByField(ord,True); finally FreeAndNil(ord); FreeAndNil(item); end; end; finally FreeAndNil(criterios); end; end; end; if osCustomMainForm.ShowQueryAction.Checked then ShowMessage(aSQL.MagicSQLText.Text); end; end; end; Inc(liIndex); end; end; end; end.
object WebModule2: TWebModule2 OldCreateOrder = False Actions = < item Default = True Name = 'WebActionItem1' PathInfo = '/List' Producer = PageProducerSelect end item Name = 'WebActionItem2' PathInfo = '/Clean' OnAction = CleanAction end item Name = 'WebActionItem3' PathInfo = '/Details' Producer = PageProducerDetails end> Left = 213 Top = 135 Height = 191 Width = 198 object PageProducerSelect: TPageProducer HTMLDoc.Strings = ( '<HTML>' '<HEADING>' '<TITLE>Registered Server Details</TITLE>' '</HEADING>' '<BODY onLoad="init()" >' '<SCRIPT TYPE="text/javascript">' '<!--' ' var LastProgID = '#39'LastProgID'#39';' '' ' var URLPath = "/"' ' function Go(s)' ' {' ' // Save the progid in a cookie' ' var exp = new Date();' ' exp.setTime(exp.getTime() + (7 * 24 * 60 * 60 * 1000));' ' document.cookie = LastProgID + '#39'='#39' + s +' ' '#39'; expires='#39' + exp.toGMTString();' ' // jump using the progid' ' window.location.href = URLPath + s;' ' }' '' ' function GetCookie(sName)' ' {' ' var aCookie = document.cookie.split("; ");' ' for (var i=0; i <aCookie.length; i++)' ' {' ' var aCrumb = aCookie[i].split("=");' ' if (sName == aCrumb[0])' ' return unescape(aCrumb[1]);' ' }' ' return null;' ' }' '' ' function init()' ' {' ' var s = GetCookie(LastProgID);' ' if (s != null)' ' document.F.S.value = s;' ' }' '// -->' '</script>' '<h2>Registered Servers</h2>' '<a>View List</a>&nbsp;|&nbsp;<a HREF="<#PATH>Details">View Detai' + 'ls</a>' '<#LIST>' '</BODY>' '</HTML>' ' ' ' ' ' ') OnHTMLTag = ServerListPageHTMLTag Left = 56 Top = 16 end object PageProducerDetails: TPageProducer HTMLDoc.Strings = ( '<HTML>' '<HEADING>' '<TITLE>Registered Server Details</TITLE>' '</HEADING>' '<h2>Registered Servers</h2>' '<a HREF=<#PATH>List>View List</a>&nbsp;|&nbsp;<a>View Details</a' + '>' '<#DETAILS>' '</BODY>' '</HTML>' ' ') OnHTMLTag = ServerListPageHTMLTag Left = 96 Top = 80 end end