text stringlengths 14 6.51M |
|---|
unit MStringGrid;
{$mode objfpc}{$H+}{$M+}
{ TMStringGrid allows rows to be appended, deleted and inserted at runtime
To append a row to the bottom of the grid
- move to the last row and press Down Arrow
To delete the current row
- press Ctrl+Del
To insert a row at the current row position
- press Ctrl+Ins
TMStringGrid is placed in the public domain.
Condition Of Use: You are on your own, don't look to me to save you.
Update A:
TMStringGrid.RowOptions has been updated to include [roAllowKeys] in
response to a person wanting to enable/disable the RowOptions functionality
when using DrawCell with programmer-drawn header and footer rows.
The OnRowAppend, OnRowInsert and OnRowDelete events alluded to in the
original version have also been implemented.
I have also removed my default RowCount & ColCount settings from Create as
it threw a few people off when they set these properties at design-time.
John McCarten
1 November 1999
If you have anything else you may want shoved in
(you write, I write - same, same) I can be contacted at
john@apollo-group.co.nz
Installing into D4 Pro.
1. Create a new package or open an existing one
2. Add MStringGrid.pas as Unit
3. Compile package
4. Install if necessary
By default MStringGrid will install on the Samples palette - this
can be changed with the RegisterComponents method further down.
I don't use any other D versions so installing into them is for you
to sort out.
}
interface
uses
SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Grids, Menus;
type
TMStringGridRowOptions = set of (roAllowAppend, roAllowDelete, roAllowInsert, roAllowKeys);
TMStringGridRowsChangedEvent = procedure (Sender: TObject; ARow: Integer) of object;
TMStringGridRowAppendEvent = procedure (Sender: TObject; ARow: Integer; var CanAppend: Boolean) of object;
TMStringGridRowInsertEvent = procedure (Sender: TObject; ARow: Integer; var CanInsert: Boolean) of object;
TMStringGridRowDeleteEvent = procedure (Sender: TObject; ARow: Integer; var CanDelete: Boolean) of object;
{ TMStringGrid }
TMStringGrid = class(TStringGrid)
private
FInsertMnu : TMenuItem;
FDeleteMnu : TMenuItem;
FAppendMnu : TMenuItem;
FRowOptions : TMStringGridRowOptions;
FRowsChanged: TMStringGridRowsChangedEvent;
FRowAppend: TMStringGridRowAppendEvent;
FRowDelete: TMStringGridRowDeleteEvent;
FRowInsert: TMStringGridRowInsertEvent;
protected
FPopup : TPopupMenu;
procedure KeyDown (var Key: Word; Shift: TShiftState); override;
function AppendMenu(aCaption : string; aProc : TNotifyEvent ) : TMenuItem;
public
constructor Create(AOwner: TComponent); override;
destructor destroy; override;
procedure RowAppend( Sender: TObject );
procedure RowDelete( Sender: TObject );
procedure RowInsert( Sender: TObject );
{ RowAppend, RowDelete and RowInsert are public to let me manipulate the
grid in response to menu and toolbar button actions.
}
// procedure LoadContent(cfg: TXMLConfig);
published
property RowOptions: TMStringGridRowOptions read FRowOptions write FRowOptions;
{ RowOptions allows me to control user append, insert and delete actions depending
on the state of the grid and/or the row that the user is currently in.
}
property OnRowsChanged: TMStringGridRowsChangedEvent read FRowsChanged write FRowsChanged;
{ OnRowsChanged fires when the number of rows in the grid change }
property OnRowAppend: TMStringGridRowAppendEvent read FRowAppend write FRowAppend;
property OnRowDelete: TMStringGridRowDeleteEvent read FRowDelete write FRowDelete;
property OnRowInsert: TMStringGridRowInsertEvent read FRowInsert write FRowInsert;
{ These events fire when the appropriate method is called. in your program
you can cancel the keyboard action if the user is in the wrong row
ie: programmer-drawn header or footer rows.
}
end;
procedure Register;
implementation
resourcestring
sDeleteLine = '&Delete current row';
sInsertLine = '&Insert row';
sAppendLine = '&Append row';
procedure Register;
begin
RegisterComponents('xPL Components', [TMStringGrid]);
end;
function TMStringGrid.AppendMenu(aCaption : string; aProc : TNotifyEvent ) : TMenuItem;
begin
Result := TMenuItem.Create( FPopUp );
Result.Caption := aCaption;
Result.OnClick := aProc;
FPopup.Items.Add(Result);
end;
constructor TMStringGrid.Create(AOwner: TComponent);
begin
inherited;
FRowOptions := [roAllowAppend, roAllowDelete, roAllowInsert, roAllowKeys];
Options := Options + [goColSizing];
FPopUp := TPopupMenu.Create( self );
PopupMenu := FPopUp;
FDeleteMnu := AppendMenu(sDeleteLine,@RowDelete);
FAppendMnu := AppendMenu(sAppendLine,@RowAppend);
FInsertMnu := AppendMenu(sInsertLine,@RowInsert);
end;
destructor TMStringGrid.Destroy;
begin
FInsertMnu.Free;
FAppendMnu.Free;
FDeleteMnu.Free;
FPopup.Free;
inherited;
end;
procedure TMStringGrid.KeyDown (var Key: Word; Shift: TShiftState);
const
MVK_APPEND = $28;
MVK_DELETE = $2E;
MVK_INSERT = $2D;
{ virtual key constants have been prefixed with MVK_ to avoid
any conflicts with standard VK_ assignments. You can change
these key assignments to whatever.
}
begin
if roAllowKeys in FRowOptions then
begin
if (Row = RowCount-1) and (Key = MVK_APPEND) then
RowAppend(self);
if (ssCtrl in Shift) and (Key = MVK_DELETE) then
RowDelete(self);
if (ssCtrl in Shift) and (Key = MVK_INSERT) then
RowInsert(self);
end;
inherited;
end;
//procedure TMStringGrid.LoadContent(cfg: TXMLConfig);
//var version : integer;
// k : integer;
//begin
// Version:=cfg.GetValue('grid/version',-1);
// k:=cfg.getValue('grid/content/cells/cellcount', 0);
// if k>0 then RowCount := k div ColCount;
// BeginUpdate;
// inherited LoadContent(Cfg, Version);
// EndUpdate;
//end;
procedure TMStringGrid.RowAppend( Sender: TObject );
var
IsOK: Boolean;
ColIndex: Integer;
begin
{ append row if allowed }
if roAllowAppend in FRowOptions then
begin
IsOK := True;
{ raise OnRowAppend event }
if Assigned(FRowAppend) then
FRowAppend(Self, Row, IsOK);
{ action Append if IsOK }
if IsOK then
begin
{ append new row to bottom of grid }
RowCount := RowCount + 1;
{ set current row to new row }
Row := RowCount - 1;
{ blank new row - some interesting effects if you don't}
for ColIndex := 0 to ColCount-1 do
Cells[ColIndex, Row] := '';
{ raise OnRowsChanged event - return current row }
if Assigned(FRowsChanged) then
FRowsChanged(Self, Row);
end;
end;
end;
procedure TMStringGrid.RowDelete( Sender: TObject );
var
IsOK: Boolean;
ColIndex,
RowIndex: Integer;
begin
{ delete row if allowed }
{ don't allow deletion of 1st row when only one row }
if (roAllowDelete in FRowOptions) and (RowCount > 1) then
begin
IsOK := True;
{ raise OnRowDelete event }
if Assigned(FRowDelete) then
FRowDelete(Self, Row, IsOK);
{ action Delete if IsOK }
if IsOK then
begin
{ move cells data from next to last rows up one - overwriting current row}
for RowIndex := Row to RowCount-2 do
for ColIndex := 0 to ColCount-1 do
Cells[ColIndex, RowIndex] := Cells[ColIndex, RowIndex+1];
{ delete last row }
RowCount := RowCount - 1;
{ raise OnRowsChanged event - return current row}
if Assigned(FRowsChanged) then
FRowsChanged(Self, Row);
end;
end;
end;
procedure TMStringGrid.RowInsert( Sender: TObject );
var
IsOK: Boolean;
ColIndex,
RowIndex: Integer;
begin
{ insert row if allowed }
if roAllowInsert in FRowOptions then
begin
IsOK := True;
{ raise OnRowInsert event }
if Assigned(FRowInsert) then
FRowInsert(Self, Row, IsOK);
{ action Insert if IsOK }
if IsOK then
begin
{ append new row to bottom of grid }
RowCount := RowCount + 1;
{ move cells data from current to old last rows down one }
for RowIndex := RowCount-1 downto Row+1 do
for ColIndex := 0 to ColCount-1 do
Cells[ColIndex, RowIndex] := Cells[ColIndex, RowIndex-1];
{ blank current row - effectively the newly inserted row}
for ColIndex := 0 to ColCount-1 do
Cells[ColIndex, Row] := '';
{ raise OnRowsChanged event - return current row}
if Assigned(FRowsChanged) then
FRowsChanged(Self, Row);
end;
end;
end;
end.
|
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 1024,0,0}
{
by Behdad Esfahbod
Algorithmic Problems Book
April '2000
Problem 67 Winning Strategy
N=2^K-1 => Second Pl. else First Pl.
N=2^K-1 is the kernel of the game
}
program
MaximumHalfGame;
var
N, T : Integer;
procedure ReadInput;
begin
Write('Enter N > ');
Readln(N);
end;
function
Is2PowerNDec (X : Integer) : Boolean;
begin
Is2PowerNDec := Trunc(Ln(X) / Ln(2)) + 1 = Trunc(Ln(X + 1) / Ln(2));
end;
procedure Play;
begin
while N > 0 do
begin
if Is2PowerNDec(N) then
begin
Write('How many matches do you take? ');
Readln(T);
if (T <> 1) and (T > N div 2) then begin Writeln('Error'); Halt; end;
end
else
begin
T := N - ((1 shl Trunc(Ln(N) / Ln(2))) - 1);
Writeln('I take ', T, ' match(es).');
end;
Dec(N, T);
if N <> 0 then
begin
Writeln('Number of remaining matches = ', N);
Writeln;
end;
end;
end;
procedure Solve;
begin
if Is2PowerNDec(N) then
Writeln('The second player has a winning strategy.')
else
Writeln('The first player has a winning strategy.');
Play;
Writeln('I won!');
end;
begin
ReadInput;
Solve;
end.
|
unit dmdatabase;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, pqconnection, sqldb, FileUtil,
inifiles,
fpJson, db,
BrookLogger;
type
{ Tdatamodule1 }
Tdatamodule1 = class(TDataModule)
PGConnection1: TPQConnection;
qryArticulos: TSQLQuery;
qryFotos: TSQLQuery;
SQLTransaction1: TSQLTransaction;
procedure DataModuleCreate(Sender: TObject);
private
public
procedure ExecQuery(ASql: string);
procedure AddFotosToJson(AJson: TJSONObject; IdArticulo: Integer);
function LoadPicture(AWav: TMemoryStream; AIdStudyProcedure: Integer): Boolean;
procedure SavePicture(AFile: TMemoryStream; AFileName: string);
end;
var
datamodule1: Tdatamodule1;
const
cPathBig = '/var/www/html/cecistore/uploads/';
cPathSmall = '/var/www/html/cecistore/uploads/small/';
implementation
{$R *.lfm}
{ Tdatamodule1 }
procedure Tdatamodule1.DataModuleCreate(Sender: TObject);
var
lIni: TIniFile;
begin
try
PGConnection1.Params.Clear;
lIni := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'store.ini');
try
PGConnection1.DatabaseName:= lIni.ReadString('default', 'db', 'store');
PGConnection1.HostName:= lIni.ReadString('default', 'host', '127.0.0.1');
PGConnection1.Params.Add('port=' + lIni.ReadString('default', 'port', '5432'));
PGConnection1.UserName:= lIni.ReadString('default', 'user', 'postgres');
PGConnection1.Password:= lIni.ReadString('default', 'password', 'postgres');
PGConnection1.Connected:= True;
finally
lIni.Free;
end;
except
on E: Exception do
TBrookLogger.Service.Info(E.Message);
end;
end;
procedure Tdatamodule1.ExecQuery(ASql: string);
var
lQuery: TSQLQuery;
begin
lQuery := TSQLQuery.Create(nil);
try
lQuery.DataBase := PGConnection1;
lQuery.SQL.Text:= ASql;
if not SQLTransaction1.Active then
SQLTransaction1.StartTransaction;
lQuery.ExecSQL;
SQLTransaction1.Commit;
finally
lQuery.Free;
end;
end;
procedure Tdatamodule1.AddFotosToJson(AJson: TJSONObject; IdArticulo: Integer);
var
lArray: TJSONArray;
lItem: TJSONObject;
lSql: TSQLQuery;
begin
lArray := TJSONArray.Create;
lSql := TSQLQuery.Create(nil);
try
lSql.DataBase := PGConnection1;
lSql.SQL.Text:= 'select Principal, Path from fotos where IdArticulo = :IdArticulo';
lSql.ParamByName('IdArticulo').AsInteger:= IdArticulo;
lSql.Open;
while not lSql.EOF do
begin
lItem := TJSONObject.Create;
lItem.Add('Principal', lSql.FieldByName('Principal').AsBoolean);
lItem.Add('Path', lSql.FieldByName('Path').AsString);
lArray.Add(lItem);
lSql.Next;
end;
AJson.Add('Fotos', lArray);
finally
lSql.Free;
end;
end;
procedure Tdatamodule1.SavePicture(AFile: TMemoryStream; AFileName: string);
var
lQry: TSQLQuery;
begin
lQry := TSQLQuery.Create(nil);
try
lQry.DataBase := PGConnection1;
lQry.SQL.Text:= 'select savefile(:FileStream, :FileName)';
lQry.ParamByName('FileStream').LoadFromStream(AFile, ftBlob);
lQry.ParamByName('FileName').AsString := AFileName;
SQLTransaction1.StartTransaction;
lQry.ExecSQL;
SQLTransaction1.Commit;
AFile.Position:= 0;
finally
lQry.Free;
end;
end;
function Tdatamodule1.LoadPicture(AWav: TMemoryStream; AIdStudyProcedure: Integer): Boolean;
var
lQry: TSQLQuery;
begin
Result := False;
lQry := TSQLQuery.Create(nil);
try
lQry.DataBase := PGConnection1;
lQry.SQL.Text:= 'select wav from studywav where idstudyprocedure = :idstudyprocedure';
lQry.ParamByName('idstudyprocedure').AsInteger := AIdStudyProcedure;
lQry.Open;
if not lQry.EOF then
begin
(lQry.FieldByName('wav') as TBlobField).SaveToStream(AWav);
AWav.Position:= 0;
Result := True;
end;
finally
lQry.Free;
end;
end;
end.
|
unit fCsltNote;
interface
uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls,
Buttons, ORCtrls, ORfn, ExtCtrls, fBase508Form, VA508AccessibilityManager;
type
TfrmCsltNote = class(TfrmBase508Form)
cmdOK: TButton;
cmdCancel: TButton;
cboCsltNote: TORComboBox;
lblAction: TLabel;
pnlBase: TORAutoPanel;
procedure cmdOKClick(Sender: TObject);
procedure cmdCancelClick(Sender: TObject);
private
FNoteIEN: string ;
FChanged: Boolean;
end;
procedure SelectNoteForProcessing(FontSize: Integer; ActionType: integer; NoteList: TStrings;
var NoteIEN: integer; CPStatus: integer) ;
implementation
{$R *.DFM}
uses rConsults, rCore, uCore, fConsults, uConsults;
const
TX_NOTE_TEXT = 'Select a document or press Cancel.';
TX_NOTE_CAP = 'No Document Selected';
procedure SelectNoteForProcessing(FontSize: Integer; ActionType: integer; NoteList: TStrings;
var NoteIEN: integer; CPStatus: integer) ;
{ displays progress note selection form and returns a record of the selection }
var
frmCsltNote: TfrmCsltNote;
W, H, i: Integer;
begin
frmCsltNote := TfrmCsltNote.Create(Application);
try
with frmCsltNote do
begin
Font.Size := FontSize;
W := ClientWidth;
H := ClientHeight;
ResizeToFont(FontSize, W, H);
ClientWidth := W; pnlBase.Width := W;
ClientHeight := H; pnlBase.Height := H;
FChanged := False;
Caption := fConsults.ActionType[ActionType];
case ActionType of
CN_ACT_CP_COMPLETE:
begin
if CPStatus = CP_INSTR_INCOMPLETE then
begin
lblAction.Caption := 'Interpret Clinical Procedure Results:';
cboCsltNote.Caption := lblAction.Caption;
for i := 0 to NoteList.Count-1 do
if ((not (Copy(Piece(Piece(NoteList[i], U, 1), ';', 2), 1, 4) = 'MCAR')) and
(Piece(NoteList[i], U, 13) <> '%') and
(Piece(NoteList[i], U, 7) <> 'completed')) then
cboCsltNote.Items.Add(Piece(NoteList[i], U, 1) + U + MakeConsultNoteDisplayText(Notelist[i]));
cboCsltNote.ItemIndex := 0;
FNoteIEN := cboCsltNote.ItemID;
//ShowModal;
end
else if CPStatus in [CP_NO_INSTRUMENT, CP_INSTR_COMPLETE] then
begin
lblAction.Caption := 'Select incomplete note to continue with:';
cboCsltNote.Caption := lblAction.Caption;
for i := 0 to NoteList.Count-1 do
if ((not (Copy(Piece(Piece(NoteList[i], U, 1), ';', 2), 1, 4) = 'MCAR')) and
(Piece(NoteList[i], U, 7) <> 'completed') and
((Piece(Piece(NoteList[i], U, 5), ';', 1) = IntToStr(User.DUZ)) or
(Piece(Piece(NoteList[i], U, 5), ';', 1) = '0'))) then
cboCsltNote.Items.Add(Piece(NoteList[i], U, 1) + U + MakeConsultNoteDisplayText(Notelist[i]));
if cboCsltNote.Items.Count > 0 then cboCsltNote.Items.Insert(0, CN_NEW_CP_NOTE + '^<Create new note>');
if cboCsltNote.Items.Count > 0 then
ShowModal
else
FNoteIEN := CN_NEW_CP_NOTE;
end;
end;
CN_ACT_COMPLETE:
begin
lblAction.Caption := 'Select incomplete note to continue with:';
cboCsltNote.Caption := lblAction.Caption;
for i := 0 to NoteList.Count-1 do
if ((not (Copy(Piece(Piece(NoteList[i], U, 1), ';', 2), 1, 4) = 'MCAR')) and
(Piece(NoteList[i], U, 7) <> 'completed') and
(Piece(Piece(NoteList[i], U, 5), ';', 1) = IntToStr(User.DUZ))) then
cboCsltNote.Items.Add(Piece(NoteList[i], U, 1) + U + MakeConsultNoteDisplayText(Notelist[i]));
if cboCsltNote.Items.Count > 0 then cboCsltNote.Items.Insert(0, CN_NEW_CSLT_NOTE + '^<Create new note>');
if cboCsltNote.Items.Count > 0 then
ShowModal
else
FNoteIEN := CN_NEW_CSLT_NOTE;
end;
(* CN_ACT_ADDENDUM: // no longer called in v15
begin
lblAction.Caption := 'Select completed note to addend to:';
for i := 0 to NoteList.Count-1 do
begin
if Copy(Piece(NoteList[i], U, 2), 1, 8) = 'Addendum' then continue;
if Piece(NoteList[i], U, 13) = '%' then continue;
cboCsltNote.Items.Add(Piece(NoteList[i], U, 1) + U + MakeConsultNoteDisplayText(Notelist[i]));
end;
if cboCsltNote.Items.Count > 0 then
ShowModal
else
FNoteIEN := '-30';
end;*)
end; {case}
NoteIEN:= StrToIntDef(FNoteIEN, -1) ;
end; {with frmCsltNote}
finally
frmCsltNote.Release;
end;
end;
procedure TfrmCsltNote.cmdCancelClick(Sender: TObject);
begin
FNoteIEN := '-1';
Close;
end;
procedure TfrmCsltNote.cmdOKClick(Sender: TObject);
begin
with cboCsltNote do
begin
if ItemIEN = 0 then
begin
InfoBox(TX_NOTE_TEXT, TX_NOTE_CAP, MB_OK or MB_ICONWARNING);
FChanged := False ;
FNoteIEN := '-1';
Exit;
end;
FChanged := True;
FNoteIEN := Piece(Items[ItemIndex],U,1);
Close;
end ;
end;
end.
|
//Модуль для создания записей о дочерних окнах
unit uChild;
interface
uses
Classes, Forms;
type
TChildActions = (
childAdd,
childEdit,
childDelete,
childRefresh,
childToExcel
);
//описание для всех MDI Child программы
PChildInfo = ^TChildInfo;
TChildInfo = record
Bof: boolean; //признак что текущая запись - первая
Eof: boolean; //признак что текущая запись - последняя
Actions: array[TChildActions] of TNotifyEvent;
end;
//создает запись для хранения свойств дочернего окна
procedure NewChildInfo(var p: PChildInfo); overload;
procedure NewChildInfo(var p: PChildInfo; frm: TForm); overload;
implementation
procedure NewChildInfo(var p: PChildInfo);
var
i: TChildActions;
begin
new(p);
for i := low(TChildActions) to high(TChildActions) do
p.Actions[i] := nil;
end;
procedure NewChildInfo(var p: PChildInfo; frm: TForm);
begin
NewChildInfo(p);
frm.Tag := integer(p);
end;
end.
|
unit RoleService;
interface
uses
RoleInterface, superobject, uTableMap, BaseService, System.SysUtils;
type
TRoleService = class(TBaseService, IRoleInterface)
public
function getdata(var con: integer; map: ISuperObject): ISuperObject;
function getAlldata(map: ISuperObject = nil): ISuperObject;
function save(map: ISuperObject): Boolean;
function del(id: string): Boolean;
function getMenu(var con: integer; map: ISuperObject): ISuperObject;
function addmenu(roleid: string; menuid: string): Boolean;
function delmenu(roleid: string; menuid: string): boolean;
function getSelMenu(var con: integer; map: ISuperObject): ISuperObject;
end;
implementation
{ TRoleService }
function TRoleService.addmenu(roleid, menuid: string): Boolean;
var
menus: string;
ret: ISuperObject;
begin
try
ret := db.Default.FindFirst(dict_role, 'and id=' + roleid);
menus := ret.S['menus'] + menuid;
with db.Default.EditData(dict_role, 'id', ret.S['id']) do
begin
FieldByName('menus').AsString := menus;
Post;
Result := true;
end;
except
Result := false;
end;
end;
function TRoleService.del(id: string): Boolean;
begin
Result := Db.Default.DeleteByKey(dict_role, 'id', id);
end;
function TRoleService.delmenu(roleid, menuid: string): boolean;
var
menus: string;
ret: ISuperObject;
begin
try
ret := db.Default.FindFirst(dict_role, 'and id=' + roleid);
menus := ret.S['menus'];
menus := menus.replace(menuid + ',', '');
with db.Default.EditData(dict_role, 'id', ret.S['id']) do
begin
FieldByName('menus').AsString := menus;
Post;
Result := true;
end;
except
Result := false;
end;
end;
function TRoleService.getAlldata(map: ISuperObject): ISuperObject;
begin
Result := Db.Default.Find(dict_role, '');
end;
function TRoleService.getMenu(var con: integer; map: ISuperObject): ISuperObject;
var
rolejo, list: ISuperObject;
sql: string;
roleid: string;
menus: string;
begin
roleid := map.S['roleid'];
rolejo := Db.Default.FindFirst(dict_role, 'and id=' + roleid);
menus := rolejo.S['menus'];
if menus <> '' then
begin
menus := Copy(menus, 0, Length(menus) - 1);
end
else
begin
menus := '0';
end;
sql := ' dict_menu where id in (' + menus + ')';
list := Db.Default.QueryPage(con, '*', sql, 'id', map.I['page'] - 1, map.I['limit']);
Result := list;
end;
function TRoleService.getSelMenu(var con: integer; map: ISuperObject): ISuperObject;
var
rolejo, list: ISuperObject;
sql: string;
roleid: string;
menus: string;
begin
roleid := map.S['roleid'];
rolejo := Db.Default.FindFirst(dict_role, 'and id=' + roleid);
menus := rolejo.S['menus'];
if menus <> '' then
begin
menus := Copy(menus, 0, Length(menus) - 1);
end
else
begin
menus := '0';
end;
sql := ' dict_menu where id not in (' + menus + ')';
list := Db.Default.QueryPage(con, '*', sql, 'id', map.I['page'] - 1, map.I['limit']);
Result := list;
end;
function TRoleService.getdata(var con: integer; map: ISuperObject): ISuperObject;
var
list: ISuperObject;
begin
list := Db.Default.FindPage(con, dict_role, 'id', map.I['page'] - 1, map.I['limit']);
Result := list;
end;
function TRoleService.save(map: ISuperObject): Boolean;
var
ret: ISuperObject;
id: string;
begin
id := map.S['id'];
if id = '' then
begin
map.Delete('id');
ret := Db.Default.FindFirst(dict_role, map);
if ret = nil then
begin
with Db.Default.AddData(dict_role) do
begin
FieldByName('rolename').AsString := map.S['rolename'];
Post;
Result := true;
end;
end
else
begin
Result := false;
end;
end
else
begin
ret := Db.Default.FindFirst(dict_role, 'and id<>' + id + ' and rolename=' + Q(map.S['rolename']));
if ret = nil then
begin
with db.Default.EditData(dict_role, 'id', id) do
begin
FieldByName('rolename').AsString := map.S['rolename'];
Post;
Result := true;
end;
end
else
begin
Result := false;
end;
end;
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Copyright(c) 2016-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit System.JSON.Converters;
interface
uses System.Generics.Collections, System.TypInfo, System.Rtti, System.JSON.Writers, System.JSON.Readers, System.JSON.Serializers;
type
// --------------------------------------------------------------------- //
// Converter for Enums
// --------------------------------------------------------------------- //
TJsonEnumNameConverter = class(TJsonConverter)
public
procedure WriteJson(const AWriter: TJsonWriter; const AValue: TValue; const ASerializer: TJsonSerializer); override;
function ReadJson(const AReader: TJsonReader; ATypeInf: PTypeInfo; const AExistingValue: TValue;
const ASerializer: TJsonSerializer): TValue; override;
function CanConvert(ATypeInf: PTypeInfo): Boolean; override;
end;
// --------------------------------------------------------------------- //
// Converter for Sets
// --------------------------------------------------------------------- //
TJsonSetNamesConverter = class(TJsonConverter)
private
function ExtractSetValue(ATypeInf: PTypeInfo; const AValue: TValue): Int64;
public
procedure WriteJson(const AWriter: TJsonWriter; const AValue: TValue; const ASerializer: TJsonSerializer); override;
function ReadJson(const AReader: TJsonReader; ATypeInf: PTypeInfo; const AExistingValue: TValue;
const ASerializer: TJsonSerializer): TValue; override;
function CanConvert(ATypeInf: PTypeInfo): Boolean; override;
end;
// --------------------------------------------------------------------- //
// Converter for creating custom objects
// --------------------------------------------------------------------- //
TJsonCustomCreationConverter<T> = class(TJsonConverter)
private
FType: PTypeInfo;
protected
function CreateInstance(ATypeInf: PTypeInfo): TValue; virtual; abstract;
public
constructor Create;
procedure WriteJson(const AWriter: TJsonWriter; const AValue: TValue; const ASerializer: TJsonSerializer); override;
function ReadJson(const AReader: TJsonReader; ATypeInf: PTypeInfo; const AExistingValue: TValue;
const ASerializer: TJsonSerializer): TValue; override;
function CanConvert(ATypeInf: PTypeInfo): Boolean; override;
function CanWrite: Boolean; override;
end;
// --------------------------------------------------------------------- //
// Converter for TListHelper
// --------------------------------------------------------------------- //
TJsonListHelperConverter = class(TJsonConverter)
private
FRttiCtx: TRttiContext;
public
constructor Create;
procedure WriteJson(const AWriter: TJsonWriter; const AValue: TValue; const ASerializer: TJsonSerializer); override;
function ReadJson(const AReader: TJsonReader; ATypeInf: PTypeInfo; const AExistingValue: TValue;
const ASerializer: TJsonSerializer): TValue; override;
function CanConvert(ATypeInf: PTypeInfo): Boolean; override;
end;
// --------------------------------------------------------------------- //
// Converter for TList
// --------------------------------------------------------------------- //
TJsonListConverter<V> = class(TJsonConverter)
protected
function CreateInstance: TList<V>; virtual;
public
procedure WriteJson(const AWriter: TJsonWriter; const AValue: TValue; const ASerializer: TJsonSerializer); override;
function ReadJson(const AReader: TJsonReader; ATypeInf: PTypeInfo; const AExistingValue: TValue;
const ASerializer: TJsonSerializer): TValue; override;
function CanConvert(ATypeInf: PTypeInfo): Boolean; override;
end;
// --------------------------------------------------------------------- //
// Converter for TStack
// --------------------------------------------------------------------- //
TJsonStackConverter<V> = class(TJsonConverter)
protected
function CreateInstance: TStack<V>; virtual;
public
procedure WriteJson(const AWriter: TJsonWriter; const AValue: TValue; const ASerializer: TJsonSerializer); override;
function ReadJson(const AReader: TJsonReader; ATypeInf: PTypeInfo; const AExistingValue: TValue;
const ASerializer: TJsonSerializer): TValue; override;
function CanConvert(ATypeInf: PTypeInfo): Boolean; override;
end;
// --------------------------------------------------------------------- //
// Converter for TQueue
// --------------------------------------------------------------------- //
TJsonQueueConverter<V> = class(TJsonConverter)
protected
function CreateInstance: TQueue<V>; virtual;
public
procedure WriteJson(const AWriter: TJsonWriter; const AValue: TValue; const ASerializer: TJsonSerializer); override;
function ReadJson(const AReader: TJsonReader; ATypeInf: PTypeInfo; const AExistingValue: TValue;
const ASerializer: TJsonSerializer): TValue; override;
function CanConvert(ATypeInf: PTypeInfo): Boolean; override;
end;
// --------------------------------------------------------------------- //
// Converter for TDictionary
// --------------------------------------------------------------------- //
TJsonDictionaryConverter<K, V> = class(TJsonConverter)
protected
function CreateDictionary: TDictionary<K, V>; virtual;
function PropertyToKey(const APropertyName: string): K; virtual; abstract;
function KeyToProperty(const AKey: K): string; virtual; abstract;
function ReadKey(const AReader: TJsonReader; const ASerializer: TJsonSerializer): string;
function ReadValue(const AReader: TJsonReader; const ASerializer: TJsonSerializer): V; virtual;
procedure WriteValue(const AWriter: TJsonWriter; const AValue: V; const ASerializer: TJsonSerializer); virtual;
public
procedure WriteJson(const AWriter: TJsonWriter; const AValue: TValue; const ASerializer: TJsonSerializer); override;
function ReadJson(const AReader: TJsonReader; ATypeInf: PTypeInfo; const AExistingValue: TValue;
const ASerializer: TJsonSerializer): TValue; override;
function CanConvert(ATypeInf: PTypeInfo): Boolean; override;
end;
// --------------------------------------------------------------------- //
// Converter for TDictionary with string keys
// --------------------------------------------------------------------- //
TJsonStringDictionaryConverter<V> = class(TJsonDictionaryConverter<string, V>)
protected
function PropertyToKey(const APropertyName: string): string; override;
function KeyToProperty(const AKey: string): string; override;
end;
implementation
uses System.SysUtils, System.JSON.Types, System.JSON.Utils, System.JSONConsts;
{ TJsonListHelperConverter }
constructor TJsonListHelperConverter.Create;
begin
inherited Create;
FRttiCtx := TRttiContext.Create;
end;
function TJsonListHelperConverter.CanConvert(ATypeInf: PTypeInfo): Boolean;
begin
Result := ATypeInf = TypeInfo(System.Generics.Collections.TListHelper);
end;
function TJsonListHelperConverter.ReadJson(const AReader: TJsonReader;
ATypeInf: PTypeInfo; const AExistingValue: TValue;
const ASerializer: TJsonSerializer): TValue;
var
LStartReading: Boolean;
begin
LStartReading := False;
// Unmarshal TList<T>.FListHelper as dynamic array using 10.3 layout
if AReader.TokenType = TJsonToken.StartArray then
LStartReading := True
else
// Unmarshal TList<T>.FListHelper as dynamic array using 10.2 layout
begin
AReader.Read;
if (AReader.TokenType = TJsonToken.PropertyName) and
SameText(AReader.Value.AsString, 'FCount') then
begin
AReader.Read;
if AReader.TokenType = TJsonToken.Integer then
begin
AReader.Read;
if AReader.TokenType = TJsonToken.EndObject then
begin
AReader.Read;
if (AReader.TokenType = TJsonToken.PropertyName) and
SameText(AReader.Value.AsString, 'FItems') then
begin
AReader.Read;
LStartReading := True;
end;
end;
end;
end;
end;
if LStartReading then
begin
Result := AExistingValue;
SetTListHelperValueFromArrayValue(FRttiCtx, Result,
function (AArrType: TRttiType): TValue
var
LpArr: Pointer;
LSize: NativeInt;
begin
LSize := 0;
LpArr := nil;
DynArraySetLength(LpArr, AArrType.Handle, 1, @LSize);
TValue.Make(@LpArr, AArrType.Handle, Result);
ASerializer.Populate(AReader, Result);
end);
end;
end;
procedure TJsonListHelperConverter.WriteJson(const AWriter: TJsonWriter;
const AValue: TValue; const ASerializer: TJsonSerializer);
var
LCount: Integer;
LValArr: TValue;
I: Integer;
begin
LValArr := GetArrayValueFromTListHelperValue(FRttiCtx, AValue, LCount);
if JSONSerializationVersion <= 32 then
begin
AWriter.WriteStartObject;
AWriter.WritePropertyName('FCount');
AWriter.WriteValue(LCount);
AWriter.WriteEndObject;
AWriter.WritePropertyName('FItems');
end;
AWriter.WriteStartArray;
for I := 0 to LCount - 1 do
ASerializer.Serialize(AWriter, LValArr.GetArrayElement(I));
AWriter.WriteEndArray;
end;
{ TJsonListConverter<V> }
function TJsonListConverter<V>.CanConvert(ATypeInf: PTypeInfo): Boolean;
begin
Result := TJsonTypeUtils.InheritsFrom(ATypeInf, TList<V>)
end;
function TJsonListConverter<V>.CreateInstance: TList<V>;
begin
Result := TList<V>.Create;
end;
function TJsonListConverter<V>.ReadJson(const AReader: TJsonReader; ATypeInf: PTypeInfo; const AExistingValue: TValue;
const ASerializer: TJsonSerializer): TValue;
var
List: TList<V>;
Arr: TArray<V>;
begin
if AReader.TokenType = TJsonToken.Null then
Result := nil
else
begin
ASerializer.Populate(AReader, Arr);
if AExistingValue.IsEmpty then
List := CreateInstance
else
List := AExistingValue.AsType<TList<V>>;
List.AddRange(Arr);
Result := TValue.From(List);
end;
end;
procedure TJsonListConverter<V>.WriteJson(const AWriter: TJsonWriter; const AValue: TValue;
const ASerializer: TJsonSerializer);
var
List: TList<V>;
Arr: TArray<V>;
begin
if AValue.TryAsType(List) then
ASerializer.Serialize(AWriter, List.ToArray)
else
raise EJsonException.Create(Format(SConverterNotMatchingType, [AValue.TypeInfo^.Name, TList<V>.ClassName]));
end;
{ TJsonDictionaryConverter<K, V> }
function TJsonDictionaryConverter<K, V>.CanConvert(ATypeInf: PTypeInfo): Boolean;
begin
if ATypeInf^.Kind = tkClass then
Result := ATypeInf.TypeData^.ClassType.InheritsFrom(TDictionary<K, V>)
else
Result := False;
end;
function TJsonDictionaryConverter<K, V>.CreateDictionary: TDictionary<K, V>;
begin
Result := TObjectDictionary<K, V>.Create;
end;
function TJsonDictionaryConverter<K, V>.ReadJson(const AReader: TJsonReader; ATypeInf: PTypeInfo;
const AExistingValue: TValue; const ASerializer: TJsonSerializer): TValue;
var
Dictionary: TDictionary<K, V>;
LKey: K;
LValue: V;
begin
if AReader.TokenType = TJsonToken.Null then
Result := nil
else
begin
if AExistingValue.IsEmpty then
Dictionary := CreateDictionary
else
Dictionary := AExistingValue.AsType<TDictionary<K, V>>;
LKey := PropertyToKey(ReadKey(AReader, ASerializer));
while AReader.TokenType <> TJsonToken.EndObject do
begin
LValue := ReadValue(AReader, ASerializer);
Dictionary.AddOrSetValue(LKey, LValue);
LKey := PropertyToKey(ReadKey(AReader, ASerializer));
end;
end;
Result := TValue.From(Dictionary);
end;
function TJsonDictionaryConverter<K, V>.ReadKey(const AReader: TJsonReader; const ASerializer: TJsonSerializer): string;
begin
AReader.Read;
case AReader.TokenType of
TJsonToken.EndObject:; // skip
TJsonToken.PropertyName:
Result := AReader.Value.AsString;
else
raise Exception.Create('');
end;
end;
function TJsonDictionaryConverter<K, V>.ReadValue(const AReader: TJsonReader; const ASerializer: TJsonSerializer): V;
begin
Result := ASerializer.Deserialize<V>(AReader);
end;
procedure TJsonDictionaryConverter<K, V>.WriteJson(const AWriter: TJsonWriter; const AValue: TValue;
const ASerializer: TJsonSerializer);
var
Dictionary: TDictionary<K, V>;
LValue: V;
LKey: K;
begin
if not AValue.TryAsType(Dictionary) then
raise EJsonException.Create(Format(SConverterNotMatchingType, [AValue.TypeInfo^.Name, TDictionary<K, V>.ClassName]));
AWriter.WriteStartObject;
for LKey in Dictionary.Keys do
begin
AWriter.WritePropertyName(KeyToProperty(LKey));
WriteValue(AWriter, Dictionary[LKey], ASerializer);
end;
AWriter.WriteEndObject;
end;
procedure TJsonDictionaryConverter<K, V>.WriteValue(const AWriter: TJsonWriter; const AValue: V;
const ASerializer: TJsonSerializer);
begin
ASerializer.Serialize<V>(AWriter, AValue);
end;
{ TJsonStringDictionaryConverter<V> }
function TJsonStringDictionaryConverter<V>.KeyToProperty(const AKey: string): string;
begin
Result := AKey;
end;
function TJsonStringDictionaryConverter<V>.PropertyToKey(const APropertyName: string): string;
begin
Result := APropertyName;
end;
{ TJsonCustomCreationConverter<T> }
function TJsonCustomCreationConverter<T>.CanConvert(ATypeInf: PTypeInfo): Boolean;
begin
Result := TJsonTypeUtils.IsAssignableFrom(ATypeInf, FType);
end;
function TJsonCustomCreationConverter<T>.CanWrite: Boolean;
begin
Result := False;
end;
constructor TJsonCustomCreationConverter<T>.Create;
begin
FType := TypeInfo(T);
end;
function TJsonCustomCreationConverter<T>.ReadJson(const AReader: TJsonReader; ATypeInf: PTypeInfo;
const AExistingValue: TValue; const ASerializer: TJsonSerializer): TValue;
var
LValue: T;
begin
if AReader.TokenType = TJsonToken.Null then
Result := nil
else
begin
Result := CreateInstance(ATypeInf);
if Result.IsEmpty then
raise EJsonException.Create(SErrorTypeNotInstantiable);
end;
ASerializer.Populate(AReader, Result);
end;
procedure TJsonCustomCreationConverter<T>.WriteJson(const AWriter: TJsonWriter; const AValue: TValue;
const ASerializer: TJsonSerializer);
begin
raise EJsonException.Create(SWriteJsonNotImplemented);
end;
{ TEnumNamesConverter }
function TJsonEnumNameConverter.CanConvert(ATypeInf: PTypeInfo): Boolean;
begin
Result := ATypeInf^.Kind = tkEnumeration;
end;
function TJsonEnumNameConverter.ReadJson(const AReader: TJsonReader; ATypeInf: PTypeInfo; const AExistingValue: TValue;
const ASerializer: TJsonSerializer): TValue;
var
LEnumValue: Integer;
TypeData: PTypeData;
begin
LEnumValue := GetEnumValue(ATypeInf, AReader.Value.AsString);
TypeData := ATypeInf^.TypeData;
if (LEnumValue >= TypeData^.MinValue) and (LEnumValue <= TypeData^.MaxValue) then
TValue.Make(@LEnumValue, ATypeInf, Result)
else
raise EJsonException.Create(Format(SConverterStringNotMatchingEnum, [AReader.Value.AsString, ATypeInf^.Name]));
end;
procedure TJsonEnumNameConverter.WriteJson(const AWriter: TJsonWriter; const AValue: TValue; const ASerializer: TJsonSerializer);
begin
AWriter.WriteValue(GetEnumName(AValue.TypeInfo, AValue.AsOrdinal));
end;
{ TJsonStackConverter<V> }
function TJsonStackConverter<V>.CanConvert(ATypeInf: PTypeInfo): Boolean;
begin
Result := TJsonTypeUtils.InheritsFrom(ATypeInf, TStack<V>)
end;
function TJsonStackConverter<V>.CreateInstance: TStack<V>;
begin
Result := TStack<V>.Create;
end;
function TJsonStackConverter<V>.ReadJson(const AReader: TJsonReader; ATypeInf: PTypeInfo; const AExistingValue: TValue;
const ASerializer: TJsonSerializer): TValue;
var
Stack: TStack<V>;
Arr: TArray<V>;
Val: V;
begin
if AReader.TokenType = TJsonToken.Null then
Result := nil
else
begin
ASerializer.Populate(AReader, Arr);
if AExistingValue.IsEmpty then
Stack := CreateInstance
else
Stack := AExistingValue.AsType<TStack<V>>;
for Val in Arr do
Stack.Push(Val);
Result := TValue.From(Stack);
end;
end;
procedure TJsonStackConverter<V>.WriteJson(const AWriter: TJsonWriter; const AValue: TValue;
const ASerializer: TJsonSerializer);
var
Stack: TStack<V>;
Arr: TArray<V>;
begin
if AValue.TryAsType(Stack) then
ASerializer.Serialize(AWriter, Stack.ToArray)
else
raise EJsonException.Create(Format(SConverterNotMatchingType, [AValue.TypeInfo^.Name, TStack<V>.ClassName]));
end;
{ TJsonQueueConverter<V> }
function TJsonQueueConverter<V>.CanConvert(ATypeInf: PTypeInfo): Boolean;
begin
Result := TJsonTypeUtils.InheritsFrom(ATypeInf, TQueue<V>)
end;
function TJsonQueueConverter<V>.CreateInstance: TQueue<V>;
begin
Result := TQueue<V>.Create;
end;
function TJsonQueueConverter<V>.ReadJson(const AReader: TJsonReader; ATypeInf: PTypeInfo; const AExistingValue: TValue;
const ASerializer: TJsonSerializer): TValue;
var
Queue: TQueue<V>;
Arr: TArray<V>;
Val: V;
begin
if AReader.TokenType = TJsonToken.Null then
Result := nil
else
begin
ASerializer.Populate(AReader, Arr);
if AExistingValue.IsEmpty then
Queue := CreateInstance
else
Queue := AExistingValue.AsType<TQueue<V>>;
for Val in Arr do
Queue.Enqueue(Val);
Result := TValue.From(Queue);
end;
end;
procedure TJsonQueueConverter<V>.WriteJson(const AWriter: TJsonWriter; const AValue: TValue;
const ASerializer: TJsonSerializer);
var
Queue: TQueue<V>;
Arr: TArray<V>;
begin
if AValue.TryAsType(Queue) then
ASerializer.Serialize(AWriter, Queue.ToArray)
else
raise EJsonException.Create(Format(SConverterNotMatchingType, [AValue.TypeInfo^.Name, TStack<V>.ClassName]));
end;
{ TJsonSetNamesConverter }
function TJsonSetNamesConverter.CanConvert(ATypeInf: PTypeInfo): Boolean;
begin
Result := (ATypeInf^.Kind = tkSet) and (ATypeInf^.TypeData^.CompType <> nil);
end;
function TJsonSetNamesConverter.ExtractSetValue(ATypeInf: PTypeInfo; const AValue: TValue): Int64;
begin
case ATypeInf^.TypeData^.OrdType of
otSByte: Result := Int8(AValue.GetReferenceToRawData^);
otSWord: Result := Int16(AValue.GetReferenceToRawData^);
otSLong: Result := Int32(AValue.GetReferenceToRawData^);
otUByte: Result := UInt8(AValue.GetReferenceToRawData^);
otUWord: Result := UInt16(AValue.GetReferenceToRawData^);
otULong: Result := UInt32(AValue.GetReferenceToRawData^);
else
Result := 0;
end;
end;
function TJsonSetNamesConverter.ReadJson(const AReader: TJsonReader; ATypeInf: PTypeInfo; const AExistingValue: TValue;
const ASerializer: TJsonSerializer): TValue;
var
LSetTypeData, LEnumTypeData: PTypeData;
LSetType: PTypeInfo;
LEnumType: PTypeInfo;
LSetValue: Int64;
LEnumValue: Integer;
begin
LSetType := ATypeInf;
LSetTypeData := LSetType.TypeData;
LEnumType := LSetType^.TypeData^.CompType^;
LEnumTypeData := LEnumType^.TypeData;
LSetValue := ExtractSetValue(LSetType, AExistingValue);
while AReader.Read and (AReader.TokenType <> TJsonToken.EndArray) do
begin
LEnumValue := GetEnumValue(LEnumType, AReader.Value.AsString);
if (LEnumValue >= LEnumTypeData^.MinValue) and (LEnumValue <= LEnumTypeData^.MaxValue) then
LSetValue := LSetValue or (1 shl LEnumValue)
else
raise EJsonException.Create(Format(SConverterStringNotMatchingEnum, [AReader.Value.AsString, ATypeInf^.Name]));
end;
case LSetTypeData^.OrdType of
otSByte: TValue.Make(Int8(LSetValue), LSetType, Result);
otSWord: TValue.Make(Int16(LSetValue), LSetType, Result);
otSLong: TValue.Make(Int32(LSetValue), LSetType, Result);
otUByte: TValue.Make(UInt8(LSetValue), LSetType, Result);
otUWord: TValue.Make(UInt16(LSetValue), LSetType, Result);
otULong: TValue.Make(UInt32(LSetValue), LSetType, Result);
else
TValue.Make(0, LSetType, Result);
end;
end;
procedure TJsonSetNamesConverter.WriteJson(const AWriter: TJsonWriter; const AValue: TValue; const ASerializer: TJsonSerializer);
var
LEnumTypeData: PTypeData;
LSetType: PTypeInfo;
LEnumType: PTypeInfo;
LSetValue: Int64;
I: Integer;
begin
LSetType := AValue.TypeInfo;
LEnumType := LSetType^.TypeData^.CompType^;
LEnumTypeData := LEnumType^.TypeData;
LSetValue := ExtractSetValue(LSetType, AValue);
AWriter.WriteStartArray;
for I := 0 to LEnumTypeData^.MaxValue do
if ((1 shl I) and LSetValue) > 0 then
AWriter.WriteValue(GetEnumName(LEnumType, I));
AWriter.WriteEndArray;
end;
end.
|
unit iaExample.CDE.WaitingThread;
interface
uses
System.Classes,
System.SyncObjs;
type
TExampleWaitingThread = class(TThread)
private
fCDE:TCountdownEvent;
protected
procedure Execute(); override;
procedure AllDone();
public
constructor Create(const pCDE:TCountdownEvent);
end;
implementation
uses
System.SysUtils,
iaTestSupport.Log;
constructor TExampleWaitingThread.Create(const pCDE:TCountdownEvent);
begin
fCDE := pCDE;
inherited Create(False);
end;
procedure TExampleWaitingThread.Execute();
begin
NameThreadForDebugging('ExampleCDEBackgroundThread');
try
fCDE.WaitFor(); //could provide timeout here, otherwise INFINITE
//resources exhausted: either refill or cleanup and exit.
//We'll simply exit for the demo
Synchronize(AllDone);
except on E:Exception do
begin
LogIt('CDE demo: waiting thread exception trapped: ' + E.Message);
end;
end;
end;
procedure TExampleWaitingThread.AllDone();
begin
WriteLn('CDE count reached zero');
end;
end.
|
unit utils;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, strutils, fpjson, jsonparser, dateutils, RegExpr;
type
TMCItem = record
name: string;
id: string;
end;
type
TMCItemArray = array of TMCItem;
function readfile(fnam: string): string;
function cuterandom(min,max: integer): Integer;
function veryBadToLower(str: String): String;
procedure writefile(fnam: string; txt: string);
procedure logWrite(str: String);
function ReadTweakerLog(): TMCItemArray;
implementation
uses
main;
function ReadTweakerLog(): TMCItemArray;
var
id, name: String;
raw_text: TStringList;
start_line, i: Integer;
re: TRegExpr;
itemarr: TMCItemArray;
item: TMCItem;
begin
SetLength(itemarr,1);
raw_text := TStringList.Create;
raw_text.LoadFromFile('minetweaker.log');
re := TRegExpr.Create; //'<(.*)>'
//,\s(.*)
for i:=0 to raw_text.Count-1 do
begin
if pos('<',raw_text[i]) = 0 then
Continue;
re.Expression := '<(.*)>';
re.Exec(raw_text[i]);
id := re.Match[0];
re.Expression := ',\s(.*)';
re.Exec(raw_text[i]);
name := re.Match[1];
item.id := id;
item.name := name;
itemarr[Length(itemarr)-1] := item;
SetLength(itemarr,Length(itemarr)+1);
end;
SetLength(itemarr,Length(itemarr)-1);
Result := itemarr;
end;
procedure logWrite(str: String);
var
logTime: TDateTime;
begin
logTime := now();
writeln(format('[%s] %s',
[formatDateTime('hh:nn:ss', logTime),
str]));
end;
function readfile(fnam: string): string;
var
text: TStringList;
begin
text := TStringList.Create;
text.LoadFromFile(fnam);
Result := text.Text;
end;
procedure writefile(fnam: string; txt: string);
var
strm: TFileStream;
n: longint;
begin
strm := TFileStream.Create(fnam, fmCreate);
n := Length(txt);
try
strm.Position := 0;
strm.Write(txt[1], n);
finally
strm.Free;
end;
end;
function cuterandom(min,max: integer): Integer;
begin
cuterandom := random(max-min+1)+min;
end;
function veryBadToLower(str: String): String;
const
convLowers: Array [0..87] of String = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
'v', 'w', 'x', 'y', 'z', 'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï',
'ð', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'а', 'б', 'в', 'г', 'д', 'е', 'ё', 'ж',
'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'ъ', 'ы',
'ь', 'э', 'ю', 'я');
convUppers: Array [0..87] of String = ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
'V', 'W', 'X', 'Y', 'Z', 'À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï',
'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'А', 'Б', 'В', 'Г', 'Д', 'Е', 'Ё', 'Ж',
'З', 'И', 'Й', 'К', 'Л', 'М', 'Н', 'О', 'П', 'Р', 'С', 'Т', 'У', 'Ф', 'Х', 'Ц', 'Ч', 'Ш', 'Щ', 'Ъ', 'Ъ',
'Ь', 'Э', 'Ю', 'Я');
var
i: Integer;
begin
result := str;
for i := 0 to 87 do
result := stringReplace(result, convUppers[i], convLowers[i], [rfReplaceAll]);
end;
begin
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: FRColorEditor<p>
RGB+Alpha color editor.<p>
<b>Historique : </b><font size=-1><ul>
<li>24/04/09 - DanB - removed some ifdef MSWINDOWS, which were actually for Kylix
<li>05/09/08 - DanB - Removed Kylix support
<li>06/06/07 - DaStr - Added GLColor to uses (BugtrackerID = 1732211)
<li>29/03/07 - DaStr - Renamed LINUX to KYLIX (BugTrackerID=1681585)
<li>03/07/04 - LR - Make change for Linux
<li>06/02/00 - Egg - Creation
</ul></font>
}
unit FRColorEditor;
interface
{$i GLScene.inc}
uses
WinApi.Windows, System.Classes, System.SysUtils, VCL.Forms, VCL.StdCtrls,
VCL.ComCtrls, VCL.ExtCtrls, VCL.Dialogs, VCL.Controls, VCL.Graphics,
//GLS
GLVectorGeometry, GLColor, GLTexture, GLCrossPlatform, GLVectorTypes;
type
TRColorEditor = class(TFrame)
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
PAPreview: TPanel;
ColorDialog: TColorDialog;
Panel1: TPanel;
ColorEditorPaintBox: TPaintBox;
RedEdit: TEdit;
GreenEdit: TEdit;
BlueEdit: TEdit;
AlphaEdit: TEdit;
procedure TBEChange(Sender: TObject);
procedure PAPreviewDblClick(Sender: TObject);
procedure ColorEditorPaintBoxPaint(Sender: TObject);
procedure FrameResize(Sender: TObject);
procedure ColorEditorPaintBoxMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure ColorEditorPaintBoxMouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
procedure ColorEditorPaintBoxMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure RedEditChange(Sender: TObject);
procedure GreenEditChange(Sender: TObject);
procedure BlueEditChange(Sender: TObject);
procedure AlphaEditChange(Sender: TObject);
private
{ Private declarations }
FOnChange : TNotifyEvent;
updating : Boolean;
WorkBitmap : tBitmap;
RedValue : Integer;
GreenValue : integer;
BlueValue : integer;
AlphaVAlue : integer;
DraggingValue : (None,Red,Green,Blue,Alpha);
procedure SetColor(const val : THomogeneousFltVector);
function GetColor : THomogeneousFltVector;
procedure DrawContents;
procedure DragColorSliderToPosition(XPos : integer);
procedure ContentsChanged;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Color : THomogeneousFltVector read GetColor write SetColor;
published
property OnChange : TNotifyEvent read FOnChange write FOnChange;
end;
implementation
{$R *.dfm}
const
MaxColorValue = 255;
MaxAlphaValue = 1000;
ColorSliderLeft = 40;
ColorSliderWidth = 128;
ColorSliderHeight = 16;
ColorViewHeight = 7;
ColorSliderMaxValue = ColorSliderWidth - 2;
RTop = 8;
GTop = 30;
BTop = 52;
ATop = 74;
PreviewPanelLeft = 216;
PreviewPanelTop = 10;
PreviewPanelWidth = 65;
PreviewPanelHeight = 74;
AlphaCheckSize = 9;
AlphaChecksHigh = 4;
AlphaChecksWide = 7;
procedure TRColorEditor.TBEChange(Sender: TObject);
begin
PAPreview.Color:=RGB(RedValue, GreenValue, BlueValue);
if (not updating) and Assigned(FOnChange) then FOnChange(Self);
end;
// SetColor
//
procedure TRColorEditor.SetColor(const val : THomogeneousFltVector);
begin
RedValue:=Round(val.X*255);
GreenValue:=Round(val.Y*255);
BlueValue:=Round(val.Z*255);
AlphaValue:=Round(val.W*1000);
ContentsChanged;
end;
// GetColor
//
function TRColorEditor.GetColor : THomogeneousFltVector;
begin
Result:=VectorMake(RedValue/255, GreenValue/255, BlueValue/255,
AlphaValue/1000);
end;
procedure TRColorEditor.PAPreviewDblClick(Sender: TObject);
begin
ColorDialog.Color:=PAPreview.Color;
if ColorDialog.Execute then
SetColor(ConvertWinColor(ColorDialog.Color));
end;
procedure TRColorEditor.ColorEditorPaintBoxPaint(Sender: TObject);
begin
with ColorEditorPaintBox,ColorEditorPaintBox.Canvas do
begin
Draw(0,0,WorkBitmap);
end;
RedEdit.Height := 16;
GreenEdit.Height := 16;
BlueEdit.Height := 16;
AlphaEdit.Height := 16;
end;
constructor TRColorEditor.Create(AOwner: TComponent);
begin
inherited;
WorkBitmap := TBitmap.Create;
WorkBitmap.PixelFormat := glpf24bit;
WorkBitmap.HandleType := bmDib;
RedValue := 200;
GreenValue := 120;
BlueValue := 60;
AlphaValue := 450;
end;
destructor TRColorEditor.Destroy;
begin
inherited;
WorkBitmap.Free;
end;
procedure TRColorEditor.FrameResize(Sender: TObject);
begin
WorkBitmap.Width := ColorEditorPaintBox.Width;
WorkBitmap.Height := ColorEditorPaintBox.Height;
With WorkBitmap.Canvas do
begin
Pen.Color := clLime;
MoveTo(0,0);
LineTo(Width-1,Height-1);
MoveTo(Width-1,0);
LineTo(0,Height-1);
end;
DrawCOntents;
// Edits have an annoying habit of forgetting their height if they are small
RedEdit.Height := 18;
GreenEdit.Height := 18;
BlueEdit.Height := 18;
AlphaEdit.Height := 18;
end;
function ColorValueToColorViewPosition(ColorValue : integer) : integer;
begin
Result := Round( (ColorSliderMaxValue/(MaxColorValue+1)) * ColorValue);
end;
function AlphaValueToColorViewPosition(AlphaValue : integer) : integer;
begin
Result := Round( (ColorSliderMaxValue/(MaxAlphaValue+1)) * AlphaValue);
end;
function ColorViewPositionToColorValue(ColorViewPosition : integer) : integer;
begin
if ColorViewPosition < 0 then ColorViewPosition := 0;
if ColorViewPosition > ColorSliderMaxValue then ColorViewPosition := ColorSliderMaxValue;
Result := Round(ColorViewPosition / (ColorSliderMaxValue/(MaxColorValue)));
end;
function ColorViewPositionToAlphaValue(ColorViewPosition : integer) : integer;
begin
if ColorViewPosition < 0 then ColorViewPosition := 0;
if ColorViewPosition > ColorSliderMaxValue then ColorViewPosition := ColorSliderMaxValue;
Result := Round(ColorViewPosition / (ColorSliderMaxValue/(MaxAlphaValue)));
end;
procedure TRColorEditor.DrawContents;
var
Position : integer;
tx,ty : integer;
RViewColor : tColor;
GViewColor : tColor;
BViewColor : tColor;
AViewColor : tColor;
ViewLevel : integer;
WhiteCheckColor : tColor;
BlackCheckColor : tColor;
AValue : single;
begin
with WorkBitmap.Canvas do
begin
Brush.Color := clBtnFace;
FillRect(Rect(0,0,WorkBitmap.Width,WorkBitmap.Height));
Font.Color := clBlack;
Font.Name := 'Arial';
Font.Height := 14;
TextOut(6,5,'Red');
TextOut(6,26,'Green');
TextOut(6,48,'Blue');
TextOut(6,70,'Alpha');
Brush.Color := clBlack;
FrameRect(Rect(ColorSliderLeft,RTop,ColorSliderLeft+ColorSliderWidth,RTop+ColorViewHeight));
FrameRect(Rect(ColorSliderLeft,GTop,ColorSliderLeft+ColorSliderWidth,GTop+ColorViewHeight));
FrameRect(Rect(ColorSliderLeft,BTop,ColorSliderLeft+ColorSliderWidth,BTop+ColorViewHeight));
FrameRect(Rect(ColorSliderLeft,ATop,ColorSliderLeft+ColorSliderWidth,ATop+ColorViewHeight));
// Color View Frames
Pen.Color := clBtnShadow;
PolyLine([ Point(ColorSliderLeft-1,RTop+ColorViewHeight),
Point(ColorSliderLeft-1,RTop-1),
Point(ColorSliderLeft+ColorSliderWidth+1,RTop-1) ]);
PolyLine([ Point(ColorSliderLeft-1,GTop+ColorViewHeight),
Point(ColorSliderLeft-1,GTop-1),
Point(ColorSliderLeft+ColorSliderWidth+1,GTop-1) ]);
PolyLine([ Point(ColorSliderLeft-1,BTop+ColorViewHeight),
Point(ColorSliderLeft-1,BTop-1),
Point(ColorSliderLeft+ColorSliderWidth+1,BTop-1) ]);
PolyLine([ Point(ColorSliderLeft-1,ATop+ColorViewHeight),
Point(ColorSliderLeft-1,ATop-1),
Point(ColorSliderLeft+ColorSliderWidth+1,ATop-1) ]);
Pen.Color := clBtnHighlight;
PolyLine([ Point(ColorSliderLeft,RTop+ColorViewHeight),
Point(ColorSliderLeft+ColorSliderWidth,RTop+ColorViewHeight),
Point(ColorSliderLeft+ColorSliderWidth,RTop) ]);
PolyLine([ Point(ColorSliderLeft,GTop+ColorViewHeight),
Point(ColorSliderLeft+ColorSliderWidth,GTop+ColorViewHeight),
Point(ColorSliderLeft+ColorSliderWidth,GTop) ]);
PolyLine([ Point(ColorSliderLeft,BTop+ColorViewHeight),
Point(ColorSliderLeft+ColorSliderWidth,BTop+ColorViewHeight),
Point(ColorSliderLeft+ColorSliderWidth,BTop) ]);
PolyLine([ Point(ColorSliderLeft,ATop+ColorViewHeight),
Point(ColorSliderLeft+ColorSliderWidth,ATop+ColorViewHeight),
Point(ColorSliderLeft+ColorSliderWidth,ATop) ]);
// Color pointer triangles
Pen.Color := clBlack;
Position:=ColorValueToColorViewPosition(RedValue) + ColorSliderLeft;
PolyLine([ Point(Position,RTop+ColorViewHeight+2),
Point(Position+6,RTop+ColorViewHeight+8),
Point(Position-6,RTop+ColorViewHeight+8),
Point(Position,RTop+ColorViewHeight+2)]);
Position:=ColorValueToColorViewPosition(GreenValue) + ColorSliderLeft;
PolyLine([ Point(Position,GTop+ColorViewHeight+2),
Point(Position+6,GTop+ColorViewHeight+8),
Point(Position-6,GTop+ColorViewHeight+8),
Point(Position,GTop+ColorViewHeight+2)]);
Position:=ColorValueToColorViewPosition(BlueValue) + ColorSliderLeft;
PolyLine([ Point(Position,BTop+ColorViewHeight+2),
Point(Position+6,BTop+ColorViewHeight+8),
Point(Position-6,BTop+ColorViewHeight+8),
Point(Position,BTop+ColorViewHeight+2)]);
Position:=AlphaValueToColorViewPosition(AlphaValue) + ColorSliderLeft;
PolyLine([ Point(Position,ATop+ColorViewHeight+2),
Point(Position+6,ATop+ColorViewHeight+8),
Point(Position-6,ATop+ColorViewHeight+8),
Point(Position,ATop+ColorViewHeight+2)]);
// Color view spectrums
For tx := 1 to ColorSliderWidth - 2 do
begin
ViewLevel := (tx * 256) div ColorSliderWidth;
AViewColor := (ViewLevel) + (ViewLevel shl 8) + (viewLevel shl 16);
RViewColor := (ViewLevel) + (GreenValue Shl 8) + (BlueValue Shl 16);
GViewColor := (RedValue) + (ViewLevel shl 8) + (BlueValue Shl 16);
BViewColor := (RedValue) + (GreenValue Shl 8) + (ViewLevel Shl 16);
For ty := 1 to ColorViewHeight -2 do
begin
Pixels[ColorSliderLeft+tx,Rtop+Ty]:=RViewCOlor;
Pixels[ColorSliderLeft+tx,Gtop+Ty]:=GViewColor;
Pixels[ColorSliderLeft+tx,Btop+Ty]:=BViewColor;
Pixels[ColorSliderLeft+tx,Atop+Ty]:=AViewColor;
end;
end;
// Color preview panel
Pen.Color := clBtnShadow;
PolyLine([ Point(PreviewPanelLeft-1,PreviewPanelTop+PreviewPanelHeight),
Point(PreviewPanelLeft-1,PreviewPanelTop-1),
Point(PreviewPanelLeft+PreviewPanelWidth,PreviewPanelTop-1) ]);
Pen.Color := clBtnHighlight;
PolyLine([ Point(PreviewPanelLeft,PreviewPanelTop+PreviewPanelHeight),
Point(PreviewPanelLeft+PreviewPanelWidth,PreviewPanelTop+PreviewPanelHeight),
Point(PreviewPanelLeft+PreviewPanelWidth,PreviewPanelTop) ]);
Brush.Color := (RedValue) + (GreenValue Shl 8) + (BlueValue Shl 16);
Pen.Color := clBlack;
Rectangle(Rect(PreviewPanelLeft,PreviewPanelTop,PreviewPanelLeft+PreviewPanelWidth,PreviewPanelTop+PreviewPanelHeight div 2 ) );
PolyLine([ Point(PreviewPanelLeft,PreviewPanelTop+PreviewPanelHeight div 2 -1),
Point(PreviewPanelLeft,PreviewPanelTop+PreviewPanelHeight -1),
Point(PreviewPanelLeft+PreviewPanelWidth-1,PreviewPanelTop+PreviewPanelHeight-1),
Point(PreviewPanelLeft+PreviewPanelWidth-1,PreviewPanelTop+PreviewPanelHeight div 2-1)
]);
AValue := AlphaValue / MaxAlphaValue;
BlackCheckColor := Round(RedValue * Avalue) + Round(GreenValue*AValue) shl 8 + Round(BlueValue*AValue) shl 16;
WhiteCheckColor := Round(RedValue * Avalue + (255 * (1-AValue))) + Round(GreenValue*AValue + (255 * (1-AValue))) shl 8 + Round(BlueValue*AValue + (255 * (1-AValue))) shl 16;
For ty := 0 to AlphaChecksHigh - 1 do
begin
For tx := 0 to AlphaChecksWide - 1 do
begin
if (tx+ty) and 1 = 0 then Brush.Color := BlackCheckColor else Brush.Color := WhiteCheckColor;
FillRect(Rect( PreviewPanelLeft+1 + tx*AlphaCheckSize,
PreviewPanelTop+PreviewPanelHeight Div 2 + ty*AlphaCheckSize,
PreviewPanelLeft+1 + (tx+1)*AlphaCheckSize,
PreviewPanelTop+PreviewPanelHeight Div 2 + (ty+1)*AlphaCheckSize
));
end;
end;
end;
end;
procedure TRColorEditor.ColorEditorPaintBoxMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
DraggingValue := None;
if Button = TMouseButton(mbLeft) then
begin
if (X > ColorSliderLeft-5) and ( X < (ColorSliderLeft+ColorSliderMaxValue+5)) then
begin
// In X range For Color Sliders
If (Y > RTop) and ( (RTop+ColorSliderHeight) > Y ) then DraggingValue := Red;
If (Y > GTop) and ( (GTop+ColorSliderHeight) > Y ) then DraggingValue := Green;
If (Y > BTop) and ( (BTop+ColorSliderHeight) > Y ) then DraggingValue := Blue;
If (Y > ATop) and ( (ATop+ColorSliderHeight) > Y ) then DraggingValue := Alpha;
If DraggingValue <> None then DragColorSliderToPosition(X-ColorSliderLeft-1);
end
end;
end;
procedure TRColorEditor.DragColorSliderToPosition(XPos: integer);
begin
case DraggingValue of
Red: RedValue := ColorViewPositionToColorValue(XPos);
Green: GreenValue := ColorViewPositionToColorValue(XPos);
Blue: BlueValue := ColorViewPositionToColorValue(XPos);
Alpha: AlphaValue := ColorViewPositionToAlphaValue(XPos);
end;
ContentsChanged;
end;
procedure TRColorEditor.ContentsChanged;
begin
if Not Updating then
begin
UpDating := True;
DrawContents;
ColorEditorPaintBox.Canvas.Draw(0,0,WorkBitmap);
RedEdit.Text := IntToStr(RedValue);
GreenEdit.Text := IntToStr(GreenValue);
BlueEdit.Text := IntToStr(BlueValue);
AlphaEdit.Text := IntToStr(AlphaValue);
PaPreview.Color := RedValue + (GreenValue Shl 8) + (BlueValue Shl 16);
UpDating := False;
TBEChange(Self);
end;
end;
procedure TRColorEditor.ColorEditorPaintBoxMouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
begin
if DraggingValue <> None then DragColorSliderToPosition(X-ColorSliderLeft-1);
end;
procedure TRColorEditor.ColorEditorPaintBoxMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if Button = TMouseButton(mbLeft) then DraggingValue := None;
end;
procedure TRColorEditor.RedEditChange(Sender: TObject);
var
IntValue : integer;
begin
IntValue := StrToIntDef(RedEdit.Text,-1);
If (IntValue < 0) or (IntValue > MaxColorValue) then
begin
RedEdit.Color:=clRed;
end
else
begin
RedEdit.Color:=clWindow;
RedValue := IntValue;
ContentsChanged;
end;
end;
procedure TRColorEditor.GreenEditChange(Sender: TObject);
var
IntValue : integer;
begin
IntValue := StrToIntDef(GreenEdit.Text,-1);
If (IntValue < 0) or (IntValue > MaxColorValue) then
begin
GreenEdit.Color:=clRed;
end
else
begin
GreenEdit.Color:=clWindow;
GreenValue := IntValue;
ContentsChanged;
end;
end;
procedure TRColorEditor.BlueEditChange(Sender: TObject);
var
IntValue : integer;
begin
IntValue := StrToIntDef(BlueEdit.Text,-1);
If (IntValue < 0) or (IntValue > MaxColorValue) then
begin
BlueEdit.Color:=clRed;
end
else
begin
BlueEdit.Color:=clWindow;
BlueValue := IntValue;
ContentsChanged;
end;
end;
procedure TRColorEditor.AlphaEditChange(Sender: TObject);
var
IntValue : integer;
begin
IntValue := StrToIntDef(AlphaEdit.Text,-1);
If (IntValue < 0) or (IntValue > MaxAlphaValue) then
begin
AlphaEdit.Color:=clRed;
end
else
begin
AlphaEdit.Color:=clWindow;
AlphaValue := IntValue;
ContentsChanged;
end;
end;
end.
|
{*********************************************}
{ TeeBI Software Library }
{ TDataItems editor dialog (Table Structure) }
{ Copyright (c) 2015-2016 by Steema Software }
{ All Rights Reserved }
{*********************************************}
unit FMXBI.Editor.Items;
interface
{
Editor dialog to modify the structure of a TDataItem that is in "Table" mode.
Also a BIGrid in read-write mode to enable adding, modifying and removing
rows.
}
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms,
{$IF CompilerVersion<=27}
{$DEFINE HASFMX20}
{$ENDIF}
{$IFNDEF HASFMX20}
FMX.Graphics, FMX.Controls.Presentation,
{$ENDIF}
FMX.Dialogs, FMX.StdCtrls, FMX.Layouts, FMX.ListBox, FMX.Objects, FMX.Edit,
BI.DataItem, FMXBI.GridForm;
type
TItemsEditor = class(TForm)
Layout1: TLayout;
GroupBox1: TGroupBox;
LayoutButtons: TLayout;
Layout2: TLayout;
Layout3: TLayout;
LBFields: TListBox;
LayoutGrid: TLayout;
SBAdd: TSpeedButton;
SBRemove: TSpeedButton;
Label1: TLabel;
EName: TEdit;
LDuplicateName: TText;
Label2: TLabel;
CBKind: TComboBox;
Layout4: TLayout;
SBUp: TSpeedButton;
SBDown: TSpeedButton;
Layout5: TLayout;
BOK: TButton;
procedure LBFieldsChange(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure SBAddClick(Sender: TObject);
procedure SBRemoveClick(Sender: TObject);
procedure SBUpClick(Sender: TObject);
procedure SBDownClick(Sender: TObject);
procedure ENameChangeTracking(Sender: TObject);
procedure ENameChange(Sender: TObject);
procedure CBKindChange(Sender: TObject);
private
{ Private declarations }
IGrid : TBIGridForm;
Items : TDataItems;
FOnChanged : TNotifyEvent;
procedure Changed;
procedure DataChanged(Sender: TObject);
function DataOf(const AIndex:Integer): TDataItem;
function SelectedField:TDataItem;
function SelectedItems:TDataItems;
procedure SwapFields(const A,B:Integer);
class function Valid(const AItems:TDataItems):Boolean; static;
public
{ Public declarations }
class function Embedd(const AOwner:TComponent; const AParent:TControl;
const AItems:TDataItems):TItemsEditor; static;
class function Edit(const AOwner:TComponent;
const AItems:TDataItems):TModalResult; static;
procedure Refresh(const AItems:TDataItems);
property OnChanged:TNotifyEvent read FOnChanged write FOnChanged;
end;
implementation
|
unit FC.Trade.Properties;
{$I Compiler.inc}
interface
uses Classes, SysUtils, Controls, BaseUtils, Variants, Serialization,Generics.Collections,Properties.Obj,
StockChart.Definitions,
StockChart.Indicators.Properties,
FC.Definitions;
type
TTraderExpertWeighingType = (ewtAllEqual,ewtTimeFrame,ewtSeniority);
const
TraderExpertWeighingTypeNames : array [TTraderExpertWeighingType] of string = ('All Equal','Weighed by Time Frame','Weighed by Seniority');
type
//----------------------------------------------------------------------------
{ TSCTraderPropertyExpertWeighingType }
TSCTraderPropertyExpertWeighingType = class (TPropertyCombo)
private
procedure SetValue_(const Value: TTraderExpertWeighingType);
function GetValue_: TTraderExpertWeighingType;
public
constructor CreateNaked; override;
constructor Create (aNotifier: IPropertyChangeHandler);
property Value: TTraderExpertWeighingType read GetValue_ write SetValue_;
end;
//----------------------------------------------------------------------------
{ TSCTraderPropertyLeadExpert }
TSCTraderPropertyLeadExpert = class (TPropertyCombo)
private
procedure SetValue_(const Value: ISCIndicator);
function GetValue_: ISCIndicator;
protected
function StoreItems: boolean; override;
public
constructor Create (aNotifier: IPropertyChangeHandler);
destructor Destroy; override;
procedure AddItem(const aValue: ISCIndicator);
function ValueAsText: string; override;
property Value: ISCIndicator read GetValue_ write SetValue_;
end;
//----------------------------------------------------------------------------
{ TSCTraderPropertyExpertPriority }
TExpertPriority = integer;
TSCTraderPropertyExpertPriority = class (TPropertyCombo)
private
FOwnerList: TList;
FExpert : ISCIndicator;
FCopy : boolean;
procedure SetValue_(const aValue: TExpertPriority);
function GetValue_: TExpertPriority;
function GetNeighbour(index: integer): TSCTraderPropertyExpertPriority;
protected
function StoreItems: boolean; override;
procedure SetValue(const aValue: variant); override;
procedure UpdateItems;
function FindNeighbourByValue(aValue: integer): TSCTraderPropertyExpertPriority;
property Neighbours[index: integer]: TSCTraderPropertyExpertPriority read GetNeighbour;
public
constructor Create (aNotifier: IPropertyChangeHandler; aExpert: ISCIndicator; aOwnerList: Tlist);
procedure Init;
procedure ReadData(const aReader: IDataReader); override;
procedure WriteData(const aWriter: IDataWriter); override;
procedure OnAssignedFrom(aSource: TProperty); override;
procedure OnAfterEdit; override;
property OwnerList: TList read FOwnerList write FOwnerList;
property Value: TExpertPriority read GetValue_ write SetValue_;
end;
//----------------------------------------------------------------------------
{ TPropertyExperts }
TPropertyExperts = class (TProperty)
private
FOwner : IStockTrader;
procedure OnClick(sender: TObject);
procedure SetExperts(const aExperts: ISCIndicatorCollection);
function GetExperts:ISCIndicatorCollection;
protected
public
function CreateControl: TWinControl; override;
function ValueAsText: string; override;
//from ISCPersistentObject
procedure ReadData(const aReader: IDataReader); override;
procedure WriteData(const aWriter: IDataWriter); override;
property Value:ISCIndicatorCollection read GetExperts write SetExperts;
constructor Create(const aCategory, aName: string; aOwner: IStockTrader);
end;
//----------------------------------------------------------------------------
{ TPropertyMinimizationLossType }
TMinimizationLossType =(mltNone,mltFixAtZeroPoint,mltMinimizeAll);
TPropertyMinimizationLossType = class (TPropertyCombo)
private
procedure SetValue_(const Value: TMinimizationLossType);
function GetValue_: TMinimizationLossType;
public
constructor CreateNaked; override;
constructor Create (aNotifier: IPropertyChangeHandler);
property Value: TMinimizationLossType read GetValue_ write SetValue_;
end;
//----------------------------------------------------------------------------
{ TPropertyStockTimeInterval }
TPropertyStockTimeInterval = class (TPropertyCombo)
private
procedure SetValue_(const Value: TStockTimeInterval);
function GetValue_: TStockTimeInterval;
public
constructor CreateNaked; override;
constructor Create (aNotifier: IPropertyChangeHandler);
property Value: TStockTimeInterval read GetValue_ write SetValue_;
end;
//----------------------------------------------------------------------------
{ TPropertyPriceRelation }
TPriceRelation = (rlHigher,rlLower);
TPropertyPriceRelation = class (TPropertyCombo)
private
procedure SetValue_(const aValue: TPriceRelation);
function GetValue_: TPriceRelation;
public
constructor CreateNaked; override;
property Value: TPriceRelation read GetValue_ write SetValue_;
end;
//----------------------------------------------------------------------------
{ TPropertyPriceKind }
TPropertyPriceKind = class (TPropertyCombo)
private
procedure SetValue_(const aValue: TStockBrokerPriceKind);
function GetValue_: TStockBrokerPriceKind;
public
constructor CreateNaked; override;
property Value: TStockBrokerPriceKind read GetValue_ write SetValue_;
end;
const
IndicatorRelationNames: array [TPriceRelation ] of string =('>','<');
implementation
uses Properties.Controls, FC.Trade.ChooseExpertsDialog,StockChart.Obj;
{ TSCTraderPropertyExpertWeighingType }
constructor TSCTraderPropertyExpertWeighingType.Create(aNotifier: IPropertyChangeHandler);
begin
inherited Create('Method','Expert Weight',aNotifier);
end;
constructor TSCTraderPropertyExpertWeighingType.CreateNaked;
var
i:TTraderExpertWeighingType;
begin
inherited;
for i:=Low(TraderExpertWeighingTypeNames) to High(TraderExpertWeighingTypeNames) do
AddItem(TraderExpertWeighingTypeNames[i],integer(i));
Value:=Low(TTraderExpertWeighingType);
end;
function TSCTraderPropertyExpertWeighingType.GetValue_: TTraderExpertWeighingType;
begin
result:=TTraderExpertWeighingType(inherited GetValue);
end;
procedure TSCTraderPropertyExpertWeighingType.SetValue_(const Value: TTraderExpertWeighingType);
begin
inherited SetValue(integer(Value));
end;
{ TSCTraderPropertyLeadExpert }
function TSCTraderPropertyLeadExpert.GetValue_: ISCIndicator;
begin
result:=IInterface(inherited GetValue) as ISCIndicator;
end;
constructor TSCTraderPropertyLeadExpert.Create(aNotifier: IPropertyChangeHandler);
begin
inherited Create('Method','Lead Expert',aNotifier);
end;
destructor TSCTraderPropertyLeadExpert.Destroy;
begin
inherited;
end;
procedure TSCTraderPropertyLeadExpert.SetValue_(const Value: ISCIndicator);
begin
inherited SetValue(Value);
end;
procedure TSCTraderPropertyLeadExpert.AddItem(const aValue: ISCIndicator);
begin
inherited AddItem(aValue.GetName+'['+GetParentStockChart(aValue).StockSymbol.GetTimeIntervalName+']' ,aValue);
end;
function TSCTraderPropertyLeadExpert.StoreItems: boolean;
begin
result:=true;
end;
function TSCTraderPropertyLeadExpert.ValueAsText: string;
begin
if Value=nil then
result:=''
else
result:=inherited ValueAsText;
end;
{ TSCTraderPropertyExpertPriority }
constructor TSCTraderPropertyExpertPriority.Create(
aNotifier: IPropertyChangeHandler; aExpert: ISCIndicator;
aOwnerList: Tlist);
begin
inherited Create('Priority',
Format('%s-%d [%s]',[ aExpert.GetName,
integer(GetParentStockChart(aExpert).StockSymbol.TimeInterval)+1,
GetParentStockChart(aExpert).StockSymbol.GetTimeIntervalName]),
aNotifier);
FOwnerList:=aOwnerList;
FExpert:=aExpert;
end;
function TSCTraderPropertyExpertPriority.GetValue_: TExpertPriority;
begin
result:= inherited GetValue;
end;
procedure TSCTraderPropertyExpertPriority.Init;
var
i: integer;
begin
UpdateItems;
for i:=0 to ItemCount-1 do
if FindNeighbourByValue(ItemValues[i])=nil then
begin
SetValue(ItemValues[i]);
exit;
end;
raise EAlgoError.Create;
end;
procedure TSCTraderPropertyExpertPriority.SetValue(const aValue: variant);
var
i: integer;
begin
UpdateItems;
inherited;
if (FOwnerList<>nil) then
for i:=0 to FOwnerList.Count-1 do
if not IsEqualGUID(Neighbours[i].FExpert.GetID,self.FExpert.GetID) then
Neighbours[i].UpdateItems;
end;
procedure TSCTraderPropertyExpertPriority.SetValue_( const aValue: TExpertPriority);
begin
inherited SetValue(aValue);
end;
procedure TSCTraderPropertyExpertPriority.UpdateItems;
var
aList: TList<integer>;
i: integer;
begin
Clear;
if FOwnerList=nil then
exit;
aList:=TList<integer>.Create;
try
for i:=0 to FOwnerList.Count-1 do
aList.Add(i);
// if not FCopy then
// for i:=0 to FOwnerList.Count-1 do
// if not IsEqualGUID(Neighbours[i].FExpert.GetID,self.FExpert.GetID) then
// aList.Remove(Neighbours[i].Value);
for i:=0 to aList.Count-1 do
AddItem(IntToStr(aList[i]),aList[i]);
finally
aList.Free;
end;
Assert(ItemCount>0);
end;
procedure TSCTraderPropertyExpertPriority.ReadData(const aReader: IDataReader);
begin
FExpert:=aReader.ReadInterface as ISCIndicator;
inherited;
end;
procedure TSCTraderPropertyExpertPriority.WriteData(const aWriter: IDataWriter);
begin
aWriter.WriteObject(FExpert as IPersistentObject);
inherited;
end;
procedure TSCTraderPropertyExpertPriority.OnAssignedFrom( aSource: TProperty);
begin
inherited;
FCopy:=true;
FOwnerList:=TSCTraderPropertyExpertPriority(aSource).FOwnerList;
UpdateItems;
end;
function TSCTraderPropertyExpertPriority.GetNeighbour(index: integer): TSCTraderPropertyExpertPriority;
begin
result:=TSCTraderPropertyExpertPriority(FOwnerList[index]);
end;
procedure TSCTraderPropertyExpertPriority.OnAfterEdit;
var
aN: TSCTraderPropertyExpertPriority;
begin
inherited;
aN:=FindNeighbourByValue(self.Value);
if aN<>nil then
raise EPropertyError.Create(aN,'Duplicate priority');
end;
function TSCTraderPropertyExpertPriority.FindNeighbourByValue(aValue: integer): TSCTraderPropertyExpertPriority;
var
j: integer;
begin
result:=nil;
for j:=0 to FOwnerList.Count-1 do
if not IsEqualGUID(Neighbours[j].FExpert.GetID,self.FExpert.GetID) then
if Neighbours[j].Value=aValue then
begin
result:=Neighbours[j];
break;
end;
end;
function TSCTraderPropertyExpertPriority.StoreItems: boolean;
begin
result:=true;
end;
{ TPropertyExperts }
constructor TPropertyExperts.Create(const aCategory, aName: string; aOwner: IStockTrader);
var
i: integer;
aExperts: ISCIndicatorCollection;
begin
inherited Create(aCategory,aName,aOwner as IPropertyChangeHandler);
FOwner:=aOwner;
aExperts:=TSCIndicatorCollection.Create();
for i:=0 to FOwner.ExpertCount-1 do
aExperts.Add(FOwner.GetExpert(i));
Value:=aExperts;
end;
function TPropertyExperts.ValueAsText: string;
begin
result:=IntToStr(VarArrayHighBound(inherited Value,1)-VarArrayLowBound(inherited Value,1)+1)+' experts' ;
end;
procedure TPropertyExperts.OnClick(sender: TObject);
var
aDialog: TfmSelectExpertsDialog;
it: TStockTimeInterval;
i: integer;
aChart: IStockChart;
aExpert: ISCExpert;
aMyExperts:ISCIndicatorCollection;
aExperts :ISCIndicatorCollection;
begin
aDialog:=TfmSelectExpertsDialog.Create(nil);
aMyExperts:=GetExperts;
try
for it:=low(TStockTimeInterval) to high(TStockTimeInterval) do
begin
aChart:=FOwner.GetProject.GetStockChart(it);
aExperts:=aChart.FindIndicators(ISCExpert);
for i:=0 to aExperts.Count-1 do
begin
aExpert:=aExperts[i] as ISCExpert;
aDialog.AddExpert(aExpert);
aDialog.Checked[aExpert]:=aMyExperts.IndexOf(aExpert)<>-1;
end;
end;
if aDialog.ShowModal=mrOk then
begin
aMyExperts.Clear;
for it:=low(TStockTimeInterval) to high(TStockTimeInterval) do
begin
aChart:=FOwner.GetProject.GetStockChart(it);
aExperts:=aChart.FindIndicators(ISCExpert);
for i:=0 to aExperts.Count-1 do
begin
aExpert:=aExperts[i] as ISCExpert;
if aDialog.Checked[aExpert] then
aMyExperts.Add(aExpert);
end;
end;
Value:=aMyExperts;
end;
finally
aDialog.Free;
end;
end;
function TPropertyExperts.CreateControl: TWinControl;
begin
result:=TButtonControl.Create(nil);
TButtonControl(result).OnClick:=OnClick;
end;
procedure TPropertyExperts.ReadData(const aReader: IDataReader);
begin
inherited;
if FOwner<>nil then
aReader.ReadObjectExisting(FOwner as IPersistentObject)
else
FOwner:=aReader.ReadInterface as IStockTrader;
end;
procedure TPropertyExperts.WriteData(const aWriter: IDataWriter);
begin
inherited;
aWriter.WriteObject(FOwner as IPersistentObject);
end;
function TPropertyExperts.GetExperts: ISCIndicatorCollection;
var
aExperts: ISCIndicatorCollection;
i: integer;
v: variant;
begin
aExperts:=TSCIndicatorCollection.Create();
v:=inherited Value;
for i:=VarArrayLowBound(v,1) to VarArrayHighBound(v,1) do
aExperts.Add(IInterface(v[i]) as ISCIndicator);
result:=aExperts;
end;
procedure TPropertyExperts.SetExperts(const aExperts: ISCIndicatorCollection);
var
v: variant;
i: integer;
begin
v:=VarArrayCreate([0,aExperts.Count-1],varUnknown);
for i:=0 to aExperts.Count-1 do
v[i]:=aExperts[i];
inherited Value:=v;
end;
{ TPropertyMinimizationLossType }
constructor TPropertyMinimizationLossType.Create(aNotifier: IPropertyChangeHandler);
begin
inherited Create('Method','Risks Minimization',aNotifier);
AddObsoleteName('Minimize Any Possible Loss');
end;
constructor TPropertyMinimizationLossType.CreateNaked;
var
i:TMinimizationLossType;
const
aNames: array [TMinimizationLossType] of string =
('No minimization',
'Move stop loss to open price when order becomes profitable',
'Always move stop loss to open price to minimize any possible losses');
begin
inherited;
for i:=Low(aNames) to High(aNames) do
AddItem(aNames[i],integer(i));
Value:=Low(TMinimizationLossType);
end;
function TPropertyMinimizationLossType.GetValue_: TMinimizationLossType;
begin
result:=TMinimizationLossType(inherited GetValue);
end;
procedure TPropertyMinimizationLossType.SetValue_(const Value: TMinimizationLossType);
begin
inherited SetValue(integer(Value));
end;
{ TPropertyStockTimeInterval }
constructor TPropertyStockTimeInterval.Create(aNotifier: IPropertyChangeHandler);
begin
inherited Create('Method','Interval',aNotifier);
end;
constructor TPropertyStockTimeInterval.CreateNaked;
var
i:TStockTimeInterval;
begin
inherited;
for i:=Low(TStockTimeInterval) to High(TStockTimeInterval) do
AddItem(StockTimeIntervalNames[i],integer(i));
Value:=low(TStockTimeInterval);
end;
function TPropertyStockTimeInterval.GetValue_: TStockTimeInterval;
begin
result:=TStockTimeInterval(inherited GetValue);
end;
procedure TPropertyStockTimeInterval.SetValue_(const Value: TStockTimeInterval);
begin
inherited SetValue(integer(Value));
end;
{ TPropertyPriceRelation }
constructor TPropertyPriceRelation.CreateNaked;
var
i:TPriceRelation;
begin
inherited CreateNaked;
for i:=Low(IndicatorRelationNames) to High(IndicatorRelationNames) do
AddItem(IndicatorRelationNames[i],integer(i));
Value:=Low(TPriceRelation);
end;
function TPropertyPriceRelation.GetValue_: TPriceRelation;
begin
result:=TPriceRelation(inherited GetValue);
end;
procedure TPropertyPriceRelation.SetValue_(const aValue: TPriceRelation);
begin
inherited SetValue(integer(aValue));
end;
{ TPropertyPriceKind }
constructor TPropertyPriceKind.CreateNaked;
var
i:TStockBrokerPriceKind;
begin
inherited CreateNaked;
for i:=Low(StockBrokerPriceKindNames) to High(StockBrokerPriceKindNames) do
AddItem(StockBrokerPriceKindNames[i],integer(i));
Value:=Low(StockBrokerPriceKindNames);
end;
function TPropertyPriceKind.GetValue_: TStockBrokerPriceKind;
begin
result:=TStockBrokerPriceKind(inherited GetValue);
end;
procedure TPropertyPriceKind.SetValue_(const aValue: TStockBrokerPriceKind);
begin
inherited SetValue(integer(aValue));
end;
end.
|
unit account_impl;
{This file was generated on 15 Jun 2000 15:10:50 GMT by version 03.03.03.C1.04}
{of the Inprise VisiBroker idl2pas CORBA IDL compiler. }
{Please do not edit the contents of this file. You should instead edit and }
{recompile the original IDL which was located in the file account.idl. }
{Delphi Pascal unit : account_impl }
{derived from IDL module : default }
interface
uses
SysUtils,
CORBA,
account_i,
account_c;
type
TAccount = class;
TAccount = class(TInterfacedObject, account_i.Account)
protected
_balance : Single;
public
constructor Create;
function balance : Single;
end;
implementation
constructor TAccount.Create;
begin
inherited;
_balance := Random * 10000;
end;
function TAccount.balance : Single;
begin
Result := _balance;
writeln('Got a balance call from a client...');
end;
initialization
randomize;
end. |
unit RPRemovedExemptions;
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, DBCtrls, DBTables, DB, Buttons, Grids,
Wwdbigrd, Wwdbgrid, ExtCtrls, Wwtable, Wwdatsrc, Menus, RPCanvas,
RPrinter, RPBase, RPFiler, Types, RPDefine, (*Progress,*) TabNotBk, RPTXFilr,
PASTypes, Zipcopy, ComCtrls, Mask;
type
TRemovedExemptionReportForm = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
ScrollBox1: TScrollBox;
CloseButton: TBitBtn;
TitleLabel: TLabel;
RemovedExemptionsTable: TTable;
ExemptionCodeTable: TTable;
ParcelTable: TTable;
SwisCodeTable: TTable;
PrintButton: TBitBtn;
PrintDialog: TPrintDialog;
SortRemovedExemptionsTable: TTable;
Label2: TLabel;
Label7: TLabel;
Label1: TLabel;
ExemptionLookupTable: TTable;
ReportPrinter: TReportPrinter;
ReportFiler: TReportFiler;
Notebook: TTabbedNotebook;
Label5: TLabel;
ExemptionCodeListBox: TListBox;
Label11: TLabel;
OptionsGroupBox: TGroupBox;
Label12: TLabel;
PrintSection1CheckBox: TCheckBox;
Label10: TLabel;
PrintSection2CheckBox: TCheckBox;
CreateParcelListCheckBox: TCheckBox;
ZipCopyDlg: TZipCopyDlg;
LoadButton: TBitBtn;
SaveButton: TBitBtn;
OpenDialog: TOpenDialog;
SaveDialog: TSaveDialog;
LoadFromParcelListCheckBox: TCheckBox;
Label14: TLabel;
SchoolCodeListBox: TListBox;
Label9: TLabel;
SwisCodeListBox: TListBox;
Label15: TLabel;
SchoolCodeTable: TTable;
PrintRemovedSTARsCheckBox: TCheckBox;
ExtractToExcelCheckBox: TCheckBox;
PrintOnlyExemptionsMarkedProrataCheckBox: TCheckBox;
EditYearRemovedFrom: TEdit;
Label17: TLabel;
RollSectionListBox: TListBox;
PrintOrderRadioGroup: TRadioGroup;
ActualDateGroupBox: TGroupBox;
Label3: TLabel;
Label8: TLabel;
AllActualDatesCheckBox: TCheckBox;
ToEndofActualDatesCheckBox: TCheckBox;
EndActualDateEdit: TMaskEdit;
StartActualDateEdit: TMaskEdit;
EffectiveDateGroupBox: TGroupBox;
Label4: TLabel;
Label6: TLabel;
AllEffectiveDatesCheckBox: TCheckBox;
ToEndOfEffectiveDatesCheckBox: TCheckBox;
EndEffectiveDateEdit: TMaskEdit;
StartEffectiveDateEdit: TMaskEdit;
PrintReasonRemovedCheckBox: TCheckBox;
Label13: TLabel;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure PrintButtonClick(Sender: TObject);
procedure ReportPrint(Sender: TObject);
procedure LoadButtonClick(Sender: TObject);
procedure SaveButtonClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure AllActualDatesCheckBoxClick(Sender: TObject);
procedure AllEffectiveDatesCheckBoxClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
UnitName : String;
AssessmentYear : String;
ReportCancelled : Boolean;
FormAccessRights : Integer; {Read only or read write, based on security level?}
{Values = raReadOnly, raReadWrite}
ProcessingType : Integer;
SelectedExemptionCodes,
SelectedSchoolCodes,
SelectedSwisCodes : TStringList;
PrintOrder : Integer;
LoadFromParcelList,
CreateParcelList : Boolean;
OrigSortFileName : String;
SelectedRollSections : TStringList;
PrintToExcel : Boolean;
ExtractFile : TextFile;
ExemptionsAlreadyExtracted : Boolean;
PrintProrataOnly,
PrintSTARExemptions,
PrintReasonRemoved : Boolean;
YearRemovedFrom : String;
PrintAllActualDates,
PrintToEndOfActualDates : Boolean;
StartActualDate,
EndActualDate : TDateTime;
PrintAllEffectiveDates,
PrintToEndOfEffectiveDates : Boolean;
StartEffectiveDate,
EndEffectiveDate : TDateTime;
Procedure InitializeForm; {Open the tables and setup.}
Procedure FillSortFiles(var Quit : Boolean);
{Fill all the sort files needed for the assessor's report.}
Procedure PrintReportHeader(Sender : TObject;
ReportTime : TDateTime;
PageNum : Integer;
SubHeader : String;
SwisCode : String);
{Print the overall report header.}
Procedure PrintExemptionSection1( Sender : TObject;
ReportTime : TDateTime;
var PageNum : Integer;
var Quit : Boolean);
{Print the exemptions by SBL. Break by swis.}
Procedure PrintExemptionSection2( Sender : TObject;
ReportTime : TDateTime;
var PageNum : Integer;
var Quit : Boolean);
{Print the exemptions by EXCode \SBL. Break by swis.}
Procedure FillListBoxes(ProcessingType : Integer;
AssessmentYear : String);
end;
implementation
uses GlblVars, WinUtils, Utilitys, PASUTILS, UTILEXSD, GlblCnst,
PRCLLIST, Prog, EnStarTy, RptDialg,
Preview; {Report preview form}
const
LinesAtBottom = 2;
poParcelID = 0;
poName = 1;
poLegalAddress = 2;
{$R *.DFM}
{========================================================}
Procedure TRemovedExemptionReportForm.FormActivate(Sender: TObject);
begin
SetFormStateMaximized(Self);
end;
{========================================================}
Procedure TRemovedExemptionReportForm.FillListBoxes(ProcessingType : Integer;
AssessmentYear : String);
begin
FillOneListBox(ExemptionCodeListBox, ExemptionCodeTable,
'EXCode', 'Description', 10,
True, True, ProcessingType, AssessmentYear);
FillOneListBox(SwisCodeListBox, SwisCodeTable,
'SwisCode', 'MunicipalityName', 20,
True, True, ProcessingType, AssessmentYear);
FillOneListBox(SchoolCodeListBox, SchoolCodeTable,
'SchoolCode', 'SchoolName', 20,
True, True, ProcessingType, AssessmentYear);
end; {FillListBoxes}
{========================================================}
Procedure TRemovedExemptionReportForm.InitializeForm;
begin
UnitName := 'RPRemovedExemptions'; {mmm}
ProcessingType := GlblProcessingType;
AssessmentYear := GetTaxRlYr;
OpenTablesForForm(Self, GlblProcessingType);
FillListBoxes(ProcessingType, AssessmentYear);
OrigSortFileName := SortRemovedExemptionsTable.TableName;
SelectedRollSections := TStringList.Create;
SelectItemsInListBox(RollSectionListBox);
end; {InitializeForm}
{===================================================================}
Procedure TRemovedExemptionReportForm.AllActualDatesCheckBoxClick(Sender: TObject);
begin
If AllActualDatesCheckBox.Checked
then
begin
ToEndofActualDatesCheckBox.Checked := False;
ToEndofActualDatesCheckBox.Enabled := False;
StartActualDateEdit.Text := '';
StartActualDateEdit.Enabled := False;
StartActualDateEdit.Color := clBtnFace;
EndActualDateEdit.Text := '';
EndActualDateEdit.Enabled := False;
EndActualDateEdit.Color := clBtnFace;
end
else EnableSelectionsInGroupBoxOrPanel(ActualDateGroupBox);
end; {AllActualDatesCheckBoxClick}
{===================================================================}
Procedure TRemovedExemptionReportForm.AllEffectiveDatesCheckBoxClick(Sender: TObject);
begin
If AllEffectiveDatesCheckBox.Checked
then
begin
ToEndofEffectiveDatesCheckBox.Checked := False;
ToEndofEffectiveDatesCheckBox.Enabled := False;
StartEffectiveDateEdit.Text := '';
StartEffectiveDateEdit.Enabled := False;
StartEffectiveDateEdit.Color := clBtnFace;
EndEffectiveDateEdit.Text := '';
EndEffectiveDateEdit.Enabled := False;
EndEffectiveDateEdit.Color := clBtnFace;
end
else EnableSelectionsInGroupBoxOrPanel(EffectiveDateGroupBox);
end; {AllEffectiveDatesCheckBoxClick}
{===================================================================}
Procedure AddOneSortRecord( SwisSBLKey : String;
ParcelTable,
RemovedExemptionsTable,
SortRemovedExemptionsTable : TTable;
PrintReasonRemoved,
PrintToExcel,
ExemptionsAlreadyExtracted : Boolean;
var ExtractFile : TextFile;
var Quit : Boolean);
{Insert one record in the exemption sort table.}
var
TempStr : String;
begin
with SortRemovedExemptionsTable do
try
Insert;
FieldByName('SwisCode').Text := Copy(SwisSBLKey, 1, 6);
FieldByName('SBLKey').Text := Copy(SwisSBLKey, 7, 20);
FieldByName('Name').Text := Take(20, ParcelTable.FieldByName('Name1').Text);
FieldByName('Location').Text := GetLegalAddressFromTable(ParcelTable);
FieldByName('RollSection').Text := ParcelTable.FieldByName('RollSection').Text;
FieldByName('SchoolCode').Text := Take(6, ParcelTable.FieldByName('SchoolCode').Text);
FieldByName('ExemptionCode').Text := RemovedExemptionsTable.FieldByName('ExemptionCode').Text;
FieldByName('CountyAmount').AsInteger := RemovedExemptionsTable.FieldByName('CountyAmount').AsInteger;
FieldByName('TownAmount').AsInteger := RemovedExemptionsTable.FieldByName('TownAmount').AsInteger;
FieldByName('SchoolAmount').AsInteger := RemovedExemptionsTable.FieldByName('SchoolAmount').AsInteger;
try
FieldByName('VillageAmount').AsInteger := RemovedExemptionsTable.FieldByName('VillageAmount').AsInteger;
except
end;
FieldByName('YearRemovedFrom').Text := RemovedExemptionsTable.FieldByName('YearRemovedFrom').Text;
FieldByName('ActualDateRemoved').AsDateTime := RemovedExemptionsTable.FieldByName('ActualDateRemoved').AsDateTime;
FieldByName('EffectiveDateRemoved').AsDateTime := RemovedExemptionsTable.FieldByName('EffectiveDateRemoved').AsDateTime;
FieldByName('RemovedDueToSale').AsBoolean := RemovedExemptionsTable.FieldByName('RemovedDueToSale').AsBoolean;
FieldByName('RemovedBy').Text := RemovedExemptionsTable.FieldByName('RemovedBy').Text;
FieldByName('Reason').AsString := RemovedExemptionsTable.FieldByName('Reason').AsString;
If (PrintToExcel and
(not ExemptionsAlreadyExtracted))
then
begin
If FieldByName('RemovedDueToSale').AsBoolean
then TempStr := 'X'
else TempStr := '';
Write(ExtractFile,
FieldByName('SwisCode').Text,
FormatExtractField(ConvertSBLOnlyToDashDot(FieldByName('SBLKey').Text)),
FormatExtractField(FieldByName('ExemptionCode').Text),
FormatExtractField(FieldByName('Name').Text),
FormatExtractField(FieldByName('Location').Text),
FormatExtractField(FieldByName('RollSection').Text),
FormatExtractField(FieldByName('SchoolCode').Text),
FormatExtractField(FieldByName('YearRemovedFrom').Text),
FormatExtractField(FieldByName('ActualDateRemoved').Text),
FormatExtractField(FieldByName('EffectiveDateRemoved').Text),
FormatExtractField(FieldByName('RemovedBy').Text),
FormatExtractField(TempStr),
FormatExtractField(FieldByName('CountyAmount').Text),
FormatExtractField(FieldByName('TownAmount').Text),
FormatExtractField(FieldByName('SchoolAmount').Text));
{$H+}
If PrintReasonRemoved
then Writeln(ExtractFile, FormatExtractField(ExtractPlainTextFromRichText(FieldByName('Reason').AsString, True)))
else Writeln(ExtractFile);
{$H-}
end; {If (PrintToExcel and ...}
Post;
except
Quit := True;
SystemSupport(005, SortRemovedExemptionsTable, 'Error inserting exemption sort record.',
'RPRemovedExemptions', GlblErrorDlgBox);
end;
end; {AddOneEXSortRecord}
{===================================================================}
Function RecMeetsCriteria(RemovedExemptionsTable,
ParcelTable : TTable;
SwisSBLKey : String;
PrintProrataOnly : Boolean;
PrintSTARExemptions : Boolean;
YearRemovedFrom : String;
PrintAllActualDates,
PrintToEndOfActualDates : Boolean;
StartActualDate,
EndActualDate : TDateTime;
PrintAllEffectiveDates,
PrintToEndOfEffectiveDates : Boolean;
StartEffectiveDate,
EndEffectiveDate : TDateTime;
SelectedSwisCodes,
SelectedSchoolCodes,
SelectedRollSections,
SelectedExemptionCodes : TStringList) : Boolean;
begin
Result := True;
{In the selected swis list?}
If (SelectedSwisCodes.IndexOf(Copy(SwisSBLKey, 1, 6)) = -1)
then Result := False;
{In the selected school list?}
If (SelectedSchoolCodes.IndexOf(ParcelTable.FieldByName('SchoolCode').Text) = -1)
then Result := False;
{Don't include rs 9.}
If (ParcelTable.FieldByName('RollSection').Text = '9')
then Result := False;
If (ParcelTable.FieldByName('ActiveFlag').Text = InactiveParcelFlag)
then Result := False;
If (Result and
(SelectedRollSections.IndexOf(ParcelTable.FieldByName('RollSection').Text) = -1))
then Result := False;
If (Result and
PrintProrataOnly and
(not RemovedExemptionsTable.FieldByName('RemovedDueToSale').AsBoolean))
then Result := False;
If (Result and
(not PrintSTARExemptions) and
ExemptionIsSTAR(RemovedExemptionsTable.FieldByName('ExemptionCode').Text))
then Result := False;
If (Result and
(Deblank(YearRemovedFrom) <> '') and
(YearRemovedFrom <> RemovedExemptionsTable.FieldByName('YearRemovedFrom').Text))
then Result := False;
If Result
then Result := InDateRange(RemovedExemptionsTable.FieldByName('ActualDateRemoved').AsDateTime,
PrintAllActualDates,
PrintToEndOfActualDates,
StartActualDate,
EndActualDate);
If Result
then Result := InDateRange(RemovedExemptionsTable.FieldByName('EffectiveDateRemoved').AsDateTime,
PrintAllEffectiveDates,
PrintToEndOfEffectiveDates,
StartEffectiveDate,
EndEffectiveDate);
{FXX04232009-7(4.20.1.1)[D484]: The Removed Exemptions report is not honoring the selected exemptions.}
If (Result and
_Compare(SelectedExemptionCodes.IndexOf(RemovedExemptionsTable.FieldByName('ExemptionCode').AsString), -1, coEqual))
then Result := False;
end; {RecMeetsCriteria}
{===================================================================}
Procedure TRemovedExemptionReportForm.FillSortFiles(var Quit : Boolean);
var
FirstTimeThrough, Done,
FirstTimeThroughRemovedExemptions, DoneRemovedExemptions : Boolean;
Index : Integer;
SwisSBLKey : String;
begin
Quit := False;
Index := 1;
ProgressDialog.UserLabelCaption := 'Sorting Removed Exemption File.';
{CHG03101999-1: Send info to a list or load from a list.}
If CreateParcelList
then ParcelListDialog.ClearParcelGrid(True);
{Now go through the exemption file.}
FirstTimeThrough := True;
Done := False;
If LoadFromParcelList
then
begin
ParcelListDialog.GetParcel(ParcelTable, Index);
ProgressDialog.Start(ParcelListDialog.NumItems, True, True);
end
else
begin
ParcelTable.First;
ProgressDialog.Start(GetRecordCount(ParcelTable), True, True);
end;
repeat
Application.ProcessMessages;
If FirstTimeThrough
then FirstTimeThrough := False
else
If LoadFromParcelList
then
begin
Index := Index + 1;
ParcelListDialog.GetParcel(ParcelTable, Index);
end
else ParcelTable.Next;
If (ParcelTable.EOF or
(LoadFromParcelList and
(Index > ParcelListDialog.NumItems)))
then Done := True;
If LoadFromParcelList
then ProgressDialog.Update(Self, ParcelListDialog.GetParcelID(Index))
else ProgressDialog.Update(Self, ConvertSwisSBLToDashDot(ExtractSSKey(ParcelTable)));
SwisSBLKey := ExtractSSKey(ParcelTable);
{Now set a range for all the removed exemptions for this parcel and
see which ones are in the correct range.}
If not Done
then
begin
SetRangeOld(RemovedExemptionsTable, ['SwisSBLKey'], [SwisSBLKey], [SwisSBLKey]);
FirstTimeThroughRemovedExemptions := True;
DoneRemovedExemptions := False;
repeat
If FirstTimeThroughRemovedExemptions
then FirstTimeThroughRemovedExemptions := False
else RemovedExemptionsTable.Next;
If RemovedExemptionsTable.EOF
then DoneRemovedExemptions := True;
If ((not DoneRemovedExemptions) and
RecMeetsCriteria(RemovedExemptionsTable, ParcelTable, SwisSBLKey,
PrintProrataOnly, PrintSTARExemptions, YearRemovedFrom,
PrintAllActualDates, PrintToEndOfActualDates,
StartActualDate, EndActualDate,
PrintAllEffectiveDates, PrintToEndOfEffectiveDates,
StartEffectiveDate, EndEffectiveDate,
SelectedSwisCodes, SelectedSchoolCodes,
SelectedRollSections, SelectedExemptionCodes))
then AddOneSortRecord(SwisSBLKey, ParcelTable,
RemovedExemptionsTable,
SortRemovedExemptionsTable,
PrintReasonRemoved, PrintToExcel,
ExemptionsAlreadyExtracted,
ExtractFile, Quit);
until DoneRemovedExemptions;
end; {If not Done}
ReportCancelled := ProgressDialog.Cancelled;
until (Done or ReportCancelled or Quit);
end; {FillSortFiles}
{====================================================================}
Procedure TRemovedExemptionReportForm.SaveButtonClick(Sender: TObject);
{FXX04091999-8: Add ability to save and load search report options.}
begin
SaveReportOptions(Self, OpenDialog, SaveDialog, 'RemovedExemptionReport.rex', 'Removed Exemption Report');
end; {SaveButtonClick}
{====================================================================}
Procedure TRemovedExemptionReportForm.LoadButtonClick(Sender: TObject);
{FXX04091999-8: Add ability to save and load search report options.}
begin
LoadReportOptions(Self, OpenDialog, 'RemovedExemptionReport.rex', 'Exemption Report');
end; {LoadButtonClick}
{===================================================================}
Procedure TRemovedExemptionReportForm.PrintButtonClick(Sender: TObject);
var
Quit, Proceed : Boolean;
SpreadsheetFileName, SortFileName, NewFileName : String;
I : Integer;
begin
Quit := False;
ReportCancelled := False;
Proceed := True;
{FXX03181999-1: Make sure they select a report type to print.}
If ((not PrintSection1CheckBox.Checked) and
(not PrintSection2CheckBox.Checked))
then
begin
Proceed := False;
MessageDlg('Please select what report type(s) to print.' + #13 +
'You can select to view parcels within a special district code,' + #13 +
'special districts within a parcel, or both.', mtError, [mbOK], 0)
end;
If Proceed
then
begin
If ((StartActualDateEdit.Text = ' / / ') and
(EndActualDateEdit.Text = ' / / ') and
(not AllActualDatesCheckBox.Checked) and
(not ToEndOfActualDatesCheckBox.Checked))
then
begin
AllActualDatesCheckBox.Checked := True;
PrintAllActualDates := True;
end;
If ((StartEffectiveDateEdit.Text = ' / / ') and
(EndEffectiveDateEdit.Text = ' / / ') and
(not AllEffectiveDatesCheckBox.Checked) and
(not ToEndOfEffectiveDatesCheckBox.Checked))
then
begin
AllEffectiveDatesCheckBox.Checked := True;
PrintAllEffectiveDates := True;
end;
{CHG10121998-1: Add user options for default destination and show vet max msg.}
SetPrintToScreenDefault(PrintDialog);
{CHG03282002-6: Allow for roll section selection on sd, ex reports.}
SelectedRollSections.Clear;
with RollSectionListBox do
For I := 0 to (Items.Count - 1) do
If Selected[I]
then SelectedRollSections.Add(Take(1, Items[I]));
If PrintDialog.Execute
then
begin
CreateParcelList := CreateParcelListCheckBox.Checked;
LoadFromParcelList := LoadFromParcelListCheckBox.Checked;
{FXX09301998-1: Disable print button after clicking to avoid clicking twice.}
PrintButton.Enabled := False;
Application.ProcessMessages;
{CHG10131998-1: Set the printer settings based on what printer they selected
only - they no longer need to worry about paper or landscape
mode.}
AssignPrinterSettings(PrintDialog, ReportPrinter, ReportFiler, [ptBoth], True, Quit);
If (ReportPrinter.Orientation = poLandscape)
then
If (MessageDlg('Do you want to print on letter size paper?',
mtConfirmation, [mbYes, mbNo], 0) = idYes)
then
begin
ReportPrinter.SetPaperSize(dmPaper_Letter, 0, 0);
ReportFiler.SetPaperSize(dmPaper_Letter, 0, 0);
ReportPrinter.Orientation := poLandscape;
ReportFiler.Orientation := poLandscape;
If (ReportPrinter.SupportDuplex and
(MessageDlg('Do you want to print on both sides of the paper?',
mtConfirmation, [mbYes, mbNo], 0) = idYes))
then
If (MessageDlg('Do you want to vertically duplex this report?',
mtConfirmation, [mbYes, mbNo], 0) = idYes)
then ReportPrinter.Duplex := dupVertical
else ReportPrinter.Duplex := dupHorizontal;
ReportPrinter.ScaleX := 92;
ReportPrinter.ScaleY := 90;
ReportPrinter.SectionLeft := 1.5;
ReportFiler.ScaleX := 92;
ReportFiler.ScaleY := 90;
ReportFiler.SectionLeft := 1.5;
end; {If (MessageDlg('Do you want to...}
If not Quit
then
begin
SelectedSwisCodes := TStringList.Create;
SelectedExemptionCodes := TStringList.Create;
SelectedSchoolCodes := TStringList.Create;
PrintReasonRemoved := PrintReasonRemovedCheckBox.Checked;
PrintProrataOnly := PrintOnlyExemptionsMarkedProrataCheckBox.Checked;
PrintSTARExemptions := PrintRemovedSTARsCheckBox.Checked;
YearRemovedFrom := EditYearRemovedFrom.Text;
PrintAllActualDates := AllActualDatesCheckBox.Checked;
PrintToEndOfActualDates := ToEndofActualDatesCheckBox.Checked;
try
If (StartActualDateEdit.Text <> ' / / ')
then StartActualDate := StrToDate(StartActualDateEdit.Text);
except
StartActualDate := 0;
end;
try
If (EndActualDateEdit.Text <> ' / / ')
then EndActualDate := StrToDate(EndActualDateEdit.Text);
except
EndActualDate := 0;
end;
PrintAllEffectiveDates := AllEffectiveDatesCheckBox.Checked;
PrintToEndOfEffectiveDates := ToEndofEffectiveDatesCheckBox.Checked;
try
If (StartEffectiveDateEdit.Text <> ' / / ')
then StartEffectiveDate := StrToDate(StartEffectiveDateEdit.Text);
except
StartEffectiveDate := 0;
end;
try
If (EndEffectiveDateEdit.Text <> ' / / ')
then EndEffectiveDate := StrToDate(EndEffectiveDateEdit.Text);
except
EndEffectiveDate := 0;
end;
For I := 0 to (SwisCodeListBox.Items.Count - 1) do
If SwisCodeListBox.Selected[I]
then SelectedSwisCodes.Add(Take(6, SwisCodeListBox.Items[I]));
For I := 0 to (SchoolCodeListBox.Items.Count - 1) do
If SchoolCodeListBox.Selected[I]
then SelectedSchoolCodes.Add(Take(6, SchoolCodeListBox.Items[I]));
For I := 0 to (ExemptionCodeListBox.Items.Count - 1) do
If ExemptionCodeListBox.Selected[I]
then SelectedExemptionCodes.Add(Take(5, ExemptionCodeListBox.Items[I]));
{CHG09222003-1(2.07j): Option to print to Excel.}
PrintToExcel := ExtractToExcelCheckBox.Checked;
If PrintToExcel
then
begin
ExemptionsAlreadyExtracted := False;
SpreadsheetFileName := GetPrintFileName(Self.Caption, True);
AssignFile(ExtractFile, SpreadsheetFileName);
Rewrite(ExtractFile);
Write(ExtractFile, 'Swis Cd,',
'Parcel ID,',
'EX Code,',
'Owner,',
'Legal Address,',
'RS,',
'School,',
'Year Removed From,',
'Date Removed,',
'Effective Date Removed,',
'Removed By,',
'Prorata?,',
'County EX Amt,',
GetMunicipalityTypeName(GlblMunicipalityType) + ' EX Amt,',
'School EX Amt');
If PrintReasonRemoved
then Writeln(ExtractFile, ',Reason')
else Writeln(ExtractFile);
end; {If PrintToExcel}
PrintOrder := PrintOrderRadioGroup.ItemIndex;
{Copy the sort table and open the tables.}
{FXX12011997-1: Name the sort files with the date and time and
extension of .SRT.}
CopyAndOpenSortFile(SortRemovedExemptionsTable, 'RemovedExemptionList',
OrigSortFileName, SortFileName,
True, True, Quit);
FillSortFiles(Quit);
{Now print the report.}
If not (Quit or ReportCancelled)
then
begin
{If they want to preview the print (i.e. have it
go to the screen), then we need to come up with
a unique file name to tell the ReportFiler
component where to put the output.
Once we have done that, we will execute the
report filer which will print the report to
that file. Then we will create and show the
preview print form and give it the name of the
file. When we are done, we will delete the file
and make sure that we go back to the original
directory.}
If PrintDialog.PrintToFile
then
begin
NewFileName := GetPrintFileName(Self.Caption, True);
ReportFiler.FileName := NewFileName;
GlblPreviewPrint := True;
try
PreviewForm := TPreviewForm.Create(self);
PreviewForm.FilePrinter.FileName := NewFileName;
PreviewForm.FilePreview.FileName := NewFileName;
ReportFiler.Execute;
PreviewForm.ShowModal;
finally
PreviewForm.Free;
{Now delete the file.}
try
Chdir(GlblReportDir);
OldDeleteFile(NewFileName);
finally
{We don't care if it does not get deleted, so we won't put up an
error message.}
ChDir(GlblProgramDir);
end;
end; {try PreviewForm := ...}
ShowReportDialog('RemovedExemptionReport.rpt', ReportFiler.FileName, True);
end {If PrintDialog.PrintToFile}
else ReportPrinter.Execute;
end; {If not Quit}
ProgressDialog.Finish;
{FXX10111999-3: Tell people that printing is starting and
done.}
DisplayPrintingFinishedMessage(PrintDialog.PrintToFile);
{Make sure to close and delete the sort file.}
SortRemovedExemptionsTable.Close;
{Now delete the file.}
try
ChDir(GlblDataDir);
OldDeleteFile(SortFileName);
finally
{We don't care if it does not get deleted, so we won't put up an
error message.}
ChDir(GlblProgramDir);
end;
SelectedSwisCodes.Free;
SelectedExemptionCodes.Free;
SelectedSchoolCodes.Free;
If CreateParcelList
then ParcelListDialog.Show;
If PrintToExcel
then
begin
CloseFile(ExtractFile);
SendTextFileToExcelSpreadsheet(SpreadsheetFileName, True,
False, '');
end; {If PrintToExcel}
end; {If not Quit}
end; {If PrintDialog.Execute}
PrintButton.Enabled := True;
ResetPrinter(ReportPrinter);
end; {If ((not PrintSection1CheckBox.Checked) and ...}
end; {StartButtonClick}
{===================================================================}
{=============== THE FOLLOWING ARE PRINTING PROCEDURES ============}
{===================================================================}
Procedure TRemovedExemptionReportForm.PrintReportHeader(Sender : TObject;
ReportTime : TDateTime;
PageNum : Integer;
SubHeader : String;
SwisCode : String);
{Print the overall report header.}
begin
with Sender as TBaseReport do
begin
Bold := True;
ClearTabs;
SetTab(0.3, pjLeft, 8.0, 0, BoxLineNone, 0);
SetTab(4.5, pjCenter, 3.0, 0, BoxLineNone, 0);
SetTab(10.2, pjRight, 0.7, 0, BoxLineNone, 0);
{Print the date and page number.}
SectionTop := 0.5;
SectionLeft := 0.5;
SectionRight := PageWidth - 0.5;
SetFont('Times New Roman',8);
Println(#9 + 'Date: ' + DateToStr(Date) +
' Time: ' + TimeToStr(ReportTime) +
#9 +
#9 + 'Page: ' + IntToStr(CurrentPage));
SetFont('Times New Roman',12);
Println(#9 +
#9 + 'Removed Exemption Report');
Println(#9 +
#9 + Subheader);
Println('');
SetFont('Times New Roman',10);
ClearTabs;
end; {with Sender as TBaseReport do}
end; {PrintReportHeader}
{===================================================================}
Procedure PrintExemptionSection1Header(Sender : TObject);
{Print the header for the exemption listing by SBL.}
begin
with Sender as TBaseReport do
begin
Bold := True;
ClearTabs;
SetTab(0.3, pjCenter, 1.4, 5, BoxLineAll, 0); {Parcel ID}
SetTab(1.7, pjCenter, 1.3, 5, BoxLineAll, 0); {Name}
SetTab(3.0, pjCenter, 1.3, 5, BoxLineAll, 0); {Location}
SetTab(4.3, pjCenter, 0.2, 5, BoxLineAll, 0); {R\S}
SetTab(4.5, pjCenter, 0.6, 5, BoxLineAll, 0); {School code}
SetTab(5.1, pjCenter, 0.6, 5, BoxLineAll, 0); {EX Code}
SetTab(5.7, pjCenter, 0.4, 5, BoxLineAll, 0); {Year removed from}
SetTab(6.1, pjCenter, 0.9, 5, BoxLineAll, 0); {Actual date removed}
SetTab(7.0, pjCenter, 0.9, 5, BoxLineAll, 0); {Effective date removed}
SetTab(7.9, pjCenter, 1.0, 5, BoxLineAll, 0); {County amt}
SetTab(8.9, pjCenter, 1.0, 5, BoxLineAll, 0); {Town amt}
SetTab(9.9, pjCenter, 1.0, 5, BoxLineAll, 0); {School amt}
Print(#9 + #9 + #9 + #9 +
#9 + 'School' +
#9 + 'Exempt' +
#9 + 'Year' +
#9 + 'Actual' +
#9 + 'Effective');
If (rtdCounty in GlblRollTotalsToShow)
then Print(#9 + 'County')
else Print(#9);
If (rtdMunicipal in GlblRollTotalsToShow)
then Print(#9 + GetMunicipalityTypeName(GlblMunicipalityType))
else Print(#9);
If (rtdSchool in GlblRollTotalsToShow)
then Println(#9 + 'School')
else Println(#9);
Print(#9 + 'Parcel ID' +
#9 + 'Owner' +
#9 + 'Location' +
#9 + 'RS' +
#9 + 'Code' +
#9 + 'Code' +
#9 + 'Remv' +
#9 + 'Date Removed' +
#9 + 'Date Removed');
If (rtdCounty in GlblRollTotalsToShow)
then Print(#9 + 'EX Amount')
else Print(#9);
If (rtdMunicipal in GlblRollTotalsToShow)
then Print(#9 + 'EX Amount')
else Print(#9);
If (rtdSchool in GlblRollTotalsToShow)
then Println(#9 + 'EX Amount')
else Println(#9);
ClearTabs;
SetTab(0.3, pjLeft, 1.4, 5, BoxLineAll, 0); {Parcel ID}
SetTab(1.7, pjLeft, 1.3, 5, BoxLineAll, 0); {Name}
SetTab(3.0, pjLeft, 1.3, 5, BoxLineAll, 0); {Location}
SetTab(4.3, pjLeft, 0.2, 5, BoxLineAll, 0); {R\S}
SetTab(4.5, pjLeft, 0.6, 5, BoxLineAll, 0); {School code}
SetTab(5.1, pjLeft, 0.6, 5, BoxLineAll, 0); {EX Code}
SetTab(5.7, pjLeft, 0.4, 5, BoxLineAll, 0); {Year removed from}
SetTab(6.1, pjLeft, 0.9, 5, BoxLineAll, 0); {Actual date removed}
SetTab(7.0, pjLeft, 0.9, 5, BoxLineAll, 0); {Effective date removed}
SetTab(7.9, pjRight, 1.0, 5, BoxLineAll, 0); {County amt}
SetTab(8.9, pjRight, 1.0, 5, BoxLineAll, 0); {Town amt}
SetTab(9.9, pjRight, 1.0, 5, BoxLineAll, 0); {School amt}
Bold := False;
end; {with Sender as TBaseReport do}
end; {PrintExemptionSection1Header}
{===================================================================}
Procedure PrintEXSection1Totals(Sender : TObject;
SwisCode : String;
TotalType : Char; {'S' = Swis, 'M' = munic}
CountyAmount,
TownAmount,
SchoolAmount : LongInt);
begin
with Sender as TBaseReport do
begin
Println('');
Bold := True;
case TotalType of
'M' : Print(#9 + 'Grand Total ' + Copy(SwisCode, 1, 4));
'S' : Print(#9 + 'Total Swis ' + SwisCode);
end;
{CHG01192004-1(2.08): Let each municipality decide what roll totals to display.}
Print(#9 + #9 + #9 + #9 + #9 + #9 + #9 + #9);
If (rtdCounty in GlblRollTotalsToShow)
then Print(#9 + FormatFloat(NoDecimalDisplay_BlankZero, CountyAmount))
else Print(#9);
If (rtdMunicipal in GlblRollTotalsToShow)
then Print(#9 + FormatFloat(NoDecimalDisplay_BlankZero, TownAmount))
else Print(#9);
If (rtdSchool in GlblRollTotalsToShow)
then Println(#9 + FormatFloat(NoDecimalDisplay_BlankZero, SchoolAmount))
else Println(#9);
Bold := False;
end; {with Sender as TBaseReport do}
end; {PrintEXSection1Totals}
{===================================================================}
Procedure TRemovedExemptionReportForm.PrintExemptionSection1( Sender : TObject;
ReportTime : TDateTime;
var PageNum : Integer;
var Quit : Boolean);
{Print the exemptions by SBL. Break by swis.}
var
FirstEntryOnPage,
Done, FirstTimeThrough : Boolean;
PreviousSBLKey : String;
PreviousSwisCode : String;
SwisCountyAmount, SwisTownAmount,
SwisSchoolAmount, TotalCountyAmount, TotalTownAmount,
TotalSchoolAmount : LongInt;
begin
Done := False;
FirstTimeThrough := True;
FirstEntryOnPage := True;
ProgressDialog.Reset;
ProgressDialog.TotalNumRecords := GetRecordCount(SortRemovedExemptionsTable);
ProgressDialog.UserLabelCaption := 'Exemptions By S\B\L.';
SwisCountyAmount := 0;
SwisTownAmount := 0;
SwisSchoolAmount := 0;
TotalCountyAmount := 0;
TotalTownAmount := 0;
TotalSchoolAmount := 0;
{FXX02031999-3: Add print by name and addr.}
case PrintOrder of
poParcelID : SortRemovedExemptionsTable.IndexName := 'BYSWIS_SBL_EXCODE';
poName : SortRemovedExemptionsTable.IndexName := 'BYSWIS_NAME_EXCODE';
poLegalAddress : SortRemovedExemptionsTable.IndexName := 'BYSWIS_LOCATION_EXCODE';
end;
with Sender as TBaseReport do
begin
try
SortRemovedExemptionsTable.First;
except
Quit := True;
SystemSupport(050, SortRemovedExemptionsTable, 'Error getting exemption sort record.',
UnitName, GlblErrorDlgBox);
end;
PreviousSwisCode := SortRemovedExemptionsTable.FieldByName('SwisCode').Text;
PreviousSBLKey := '';
PageNum := PageNum + 1;
PrintReportHeader(Sender, ReportTime, PageNum,
'Exemption Codes Within Parcel',
PreviousSwisCode);
PrintExemptionSection1Header(Sender);
repeat
If FirstTimeThrough
then FirstTimeThrough := False
else
try
SortRemovedExemptionsTable.Next;
except
Quit := True;
SystemSupport(050, SortRemovedExemptionsTable, 'Error getting exemption sort record.',
UnitName, GlblErrorDlgBox);
end;
{FXX02021998-4: Need an app.procmsgs to allow concurrent processing.}
Application.ProcessMessages;
If SortRemovedExemptionsTable.EOF
then Done := True;
If (Done or
(Take(6, PreviousSwisCode) <> Take(6, SortRemovedExemptionsTable.FieldByName('SwisCode').Text)))
then
begin
PrintEXSection1Totals(Sender, PreviousSwisCode, 'S',
SwisCountyAmount,
SwisTownAmount,
SwisSchoolAmount);
TotalCountyAmount := TotalCountyAmount + SwisCountyAmount;
TotalTownAmount := TotalTownAmount + SwisTownAmount;
TotalSchoolAmount := TotalSchoolAmount + SwisSchoolAmount;
SwisCountyAmount := 0;
SwisTownAmount := 0;
SwisSchoolAmount := 0;
end; {If (Take(6, PreviousSwisCode) ...}
If not Done or Quit
then
begin
ProgressDialog.Update(Self,
'S\B\L: ' + ConvertSBLOnlyToDashDot(SortRemovedExemptionsTable.FieldByName('SBLKey').Text));
{If they switched swis codes or they are at
the end of this page, start a new page.}
If ((Take(6, PreviousSwisCode) <> Take(6, SortRemovedExemptionsTable.FieldByName('SwisCode').Text)) or
(LinesLeft < LinesAtBottom))
then
begin
NewPage;
FirstEntryOnPage := True;
PageNum := PageNum + 1;
PrintReportHeader(Sender, ReportTime, PageNum,
'Exemption Codes Within Parcel',
SortRemovedExemptionsTable.FieldByName('SwisCode').Text);
PrintExemptionSection1Header(Sender);
end; {If (LinesLeft < 5)}
{Only print the SBL, name ... assessment if this is the
first exemption for this parcel.}
with SortRemovedExemptionsTable do
begin
If ((Take(20, PreviousSBLKey) <> Take(20, FieldByName('SBLKey').Text)) or
FirstEntryOnPage)
then Print(#9 + ConvertSBLOnlyToDashDot(FieldByName('SBLKey').Text) +
#9 + Take(13, FieldByName('Name').Text) +
#9 + Take(13, FieldByName('Location').Text) +
#9 + FieldByName('RollSection').Text +
#9 + FieldByName('SchoolCode').Text)
else Print(#9 + #9 + #9 + #9 + #9); {Skip these fields.}
{Now print the exemption amounts.}
Print(#9 + FieldByName('ExemptionCode').Text +
#9 + FieldByName('YearRemovedFrom').Text +
#9 + FieldByName('ActualDateRemoved').Text +
#9 + FieldByName('EffectiveDateRemoved').Text);
{CHG01192004-1(2.08): Let each municipality decide what roll totals to display.}
If (rtdCounty in GlblRollTotalsToShow)
then Print(#9 + FormatFloat(NoDecimalDisplay_BlankZero,
TCurrencyField(FieldByName('CountyAmount')).Value))
else Print(#9);
If (rtdMunicipal in GlblRollTotalsToShow)
then Print(#9 + FormatFloat(NoDecimalDisplay_BlankZero,
TCurrencyField(FieldByName('TownAmount')).Value))
else Print(#9);
If (rtdSchool in GlblRollTotalsToShow)
then Println(#9 + FormatFloat(NoDecimalDisplay_BlankZero,
TCurrencyField(FieldByName('SchoolAmount')).Value))
else Println(#9);
SwisCountyAmount := SwisCountyAmount + FieldByName('CountyAmount').AsInteger;
SwisTownAmount := SwisTownAmount + FieldByName('TownAmount').AsInteger;
SwisSchoolAmount := SwisSchoolAmount + FieldByName('SchoolAmount').AsInteger;
FirstEntryOnPage := False;
end; {with SortRemovedExemptionsTable do}
end; {If not Done or Quit}
PreviousSwisCode := SortRemovedExemptionsTable.FieldByName('SwisCode').Text;
PreviousSBLKey := SortRemovedExemptionsTable.FieldByName('SBLKey').Text;
ReportCancelled := ProgressDialog.Cancelled;
until (Done or Quit or ReportCancelled);
end; {with Sender as TBaseReport do}
PrintEXSection1Totals(Sender, PreviousSwisCode, 'M',
TotalCountyAmount,
TotalTownAmount,
TotalSchoolAmount);
ExemptionsAlreadyExtracted := True;
end; {PrintExemptionSection1}
{===================================================================}
Procedure PrintExemptionSection2Header(Sender : TObject);
{Print the header for the exemption listing by SBL.}
begin
with Sender as TBaseReport do
begin
ClearTabs;
Bold := True;
SetTab(0.3, pjCenter, 0.6, 5, BoxLineAll, 0); {EX Code}
SetTab(0.9, pjCenter, 1.0, 5, BoxLineAll, 0); {Parcel ID}
SetTab(1.9, pjCenter, 1.3, 5, BoxLineAll, 0); {Name}
SetTab(3.2, pjCenter, 1.3, 5, BoxLineAll, 0); {Location}
SetTab(4.5, pjCenter, 0.2, 5, BoxLineAll, 0); {R\S}
SetTab(4.7, pjCenter, 0.6, 5, BoxLineAll, 0); {School code}
SetTab(5.3, pjCenter, 0.4, 5, BoxLineAll, 0); {Year removed from}
SetTab(5.7, pjCenter, 0.8, 5, BoxLineAll, 0); {Actual date removed}
SetTab(6.5, pjCenter, 0.8, 5, BoxLineAll, 0); {Effective date removed}
SetTab(7.3, pjCenter, 0.5, 5, BoxLineAll, 0); {Prorate}
SetTab(7.8, pjCenter, 1.0, 5, BoxLineAll, 0); {County amt}
SetTab(8.8, pjCenter, 1.0, 5, BoxLineAll, 0); {Town amt}
SetTab(9.8, pjCenter, 1.0, 5, BoxLineAll, 0); {School amt}
Print(#9 + 'Exempt' +
#9 + #9 + #9 + #9 +
#9 + 'School' +
#9 + 'Year' +
#9 + 'Actual' +
#9 + 'Effective' +
#9 + 'Pro-');
If (rtdCounty in GlblRollTotalsToShow)
then Print(#9 + 'County')
else Print(#9);
If (rtdMunicipal in GlblRollTotalsToShow)
then Print(#9 + GetMunicipalityTypeName(GlblMunicipalityType))
else Print(#9);
If (rtdSchool in GlblRollTotalsToShow)
then Println(#9 + 'School')
else
If (rtdVillageReceivingPartialRoll in GlblRollTotalsToShow)
then Println(#9 + 'Village')
else Println(#9);
Print(#9 + 'Code' +
#9 + 'Parcel ID' +
#9 + 'Owner' +
#9 + 'Location' +
#9 + 'RS' +
#9 + 'Code' +
#9 + 'Remv' +
#9 + 'Date Remv' +
#9 + 'Date Remv' +
#9 + 'Rate');
If (rtdCounty in GlblRollTotalsToShow)
then Print(#9 + 'Ex Amount')
else Print(#9);
If (rtdMunicipal in GlblRollTotalsToShow)
then Print(#9 + 'Ex Amount')
else Print(#9);
If (rtdSchool in GlblRollTotalsToShow)
then Println(#9 + 'Ex Amount')
else Println(#9);
ClearTabs;
SetTab(0.3, pjLeft, 0.6, 5, BoxLineAll, 0); {EX Code}
SetTab(0.9, pjLeft, 1.0, 5, BoxLineAll, 0); {Parcel ID}
SetTab(1.9, pjLeft, 1.3, 5, BoxLineAll, 0); {Name}
SetTab(3.2, pjLeft, 1.3, 5, BoxLineAll, 0); {Location}
SetTab(4.5, pjLeft, 0.2, 5, BoxLineAll, 0); {R\S}
SetTab(4.7, pjLeft, 0.6, 5, BoxLineAll, 0); {School code}
SetTab(5.3, pjLeft, 0.4, 5, BoxLineAll, 0); {Year removed from}
SetTab(5.7, pjLeft, 0.9, 5, BoxLineAll, 0); {Actual date removed}
SetTab(6.6, pjLeft, 0.9, 5, BoxLineAll, 0); {Effective date removed}
SetTab(7.3, pjCenter, 0.5, 5, BoxLineAll, 0); {Prorate}
SetTab(7.8, pjRight, 1.0, 5, BoxLineAll, 0); {County amt}
SetTab(8.8, pjRight, 1.0, 5, BoxLineAll, 0); {Town amt}
SetTab(9.8, pjRight, 1.0, 5, BoxLineAll, 0); {School amt}
Bold := False;
end; {with Sender as TBaseReport do}
end; {PrintExemptionSection2Header}
{===================================================================}
Procedure PrintEXTotals(Sender : TObject; {Report printer}
TotalType : Char; {'X' = exemption code, 'S' = swis code, 'T' = overall total}
TotalCode : String; {The exemption or swis code this total is for.}
TotalNumParcels : LongInt;
TotalCountyAmount,
TotalTownAmount,
TotalSchoolAmount,
TotalVillageAmount : LongInt);
var
TotalHeader : String;
begin
case TotalType of
'X' : TotalHeader := 'Total EX ' + Trim(TotalCode) + ':';
'S' : TotalHeader := 'Total Swis ' + Trim(TotalCode) + ':';
'T' : TotalHeader := 'Overall Total: ';
end;
with Sender as TBaseReport do
begin
Bold := True;
Print(#9 + #9 + TotalHeader + #9 +
#9 + '# Exemptions: ' + IntToStr(TotalNumParcels) +
#9 + #9 + #9 + #9 + #9 + #9);
If (rtdCounty in GlblRollTotalsToShow)
then Print(#9 + FormatFloat(NoDecimalDisplay_BlankZero,
TotalCountyAmount))
else Print(#9);
If (rtdMunicipal in GlblRollTotalsToShow)
then Print(#9 + FormatFloat(NoDecimalDisplay_BlankZero,
TotalTownAmount))
else Print(#9);
If (rtdSchool in GlblRollTotalsToShow)
then Println(#9 + FormatFloat(NoDecimalDisplay_BlankZero,
TotalSchoolAmount))
else
If (rtdVillageReceivingPartialRoll in GlblRollTotalsToShow)
then Println(#9 + FormatFloat(NoDecimalDisplay_BlankZero,
TotalVillageAmount))
else Println(#9);
Println('');
Bold := False;
end; {with Sender as TBaseReport do}
end; {PrintEXTotals}
{===================================================================}
Procedure TRemovedExemptionReportForm.PrintExemptionSection2( Sender : TObject;
ReportTime : TDateTime;
var PageNum : Integer;
var Quit : Boolean);
{Print the exemptions by EXCode \SBL. Break by swis.}
var
Done, FirstTimeThrough, FirstLineOnPage : Boolean;
PreviousSwisCode : String;
PreviousEXCode : String;
NumParcelsForEXCode,
NumParcelsForSwisCode,
TotalNumParcels : LongInt;
CountyAmountForEXCode,
TownAmountForEXCode,
SchoolAmountForEXCode,
VillageAmountForEXCode,
CountyAmountForSwisCode,
TownAmountForSwisCode,
SchoolAmountForSwisCode,
VillageAmountForSwisCode,
TotalCountyAmount,
TotalTownAmount,
TotalSchoolAmount,
TotalVillageAmount : LongInt;
begin
Done := False;
FirstTimeThrough := True;
FirstLineOnPage := True;
NumParcelsForEXCode := 0;
NumParcelsForSwisCode := 0;
TotalNumParcels := 0;
CountyAmountForEXCode := 0;
TownAmountForEXCode := 0;
SchoolAmountForEXCode := 0;
VillageAmountForEXCode := 0;
CountyAmountForSwisCode := 0;
TownAmountForSwisCode := 0;
SchoolAmountForSwisCode := 0;
VillageAmountForSwisCode := 0;
TotalCountyAmount := 0;
TotalTownAmount := 0;
TotalSchoolAmount := 0;
TotalVillageAmount := 0;
ProgressDialog.Reset;
ProgressDialog.TotalNumRecords := GetRecordCount(SortRemovedExemptionsTable);
ProgressDialog.UserLabelCaption := 'Exemptions By Exemption Code.';
{FXX02031999-3: Add print by name and addr.}
case PrintOrder of
poParcelID : SortRemovedExemptionsTable.IndexName := 'BYSWIS_EXCODE_SBL';
poName : SortRemovedExemptionsTable.IndexName := 'BYSWIS_EXCODE_NAME';
poLegalAddress : SortRemovedExemptionsTable.IndexName := 'BYSWIS_EXCODE_LOCATION';
end;
with Sender as TBaseReport do
begin
SortRemovedExemptionsTable.First;
PreviousSwisCode := SortRemovedExemptionsTable.FieldByName('SwisCode').Text;
PreviousEXCode := '';
PageNum := PageNum + 1;
PrintReportHeader(Sender, ReportTime, PageNum,
'Parcels Within Exemption Code',
PreviousSwisCode);
PrintExemptionSection2Header(Sender);
repeat
If FirstTimeThrough
then FirstTimeThrough := False
else SortRemovedExemptionsTable.Next;
{FXX02021998-4: Need an app.procmsgs to allow concurrent processing.}
Application.ProcessMessages;
If SortRemovedExemptionsTable.EOF
then Done := True;
{Check to see if we need to print totals or start a new page.}
If not Quit
then
begin
{If we are on a different exemption code, then print out the totals
for the last exemption code.}
If (((Take(5, PreviousEXCode) <> Take(5, SortRemovedExemptionsTable.FieldByName('ExemptionCode').Text)) and
(Deblank(PreviousEXCode) <> '')) or
Done)
then
begin
PrintEXTotals(Sender, 'X', PreviousEXCode,
NumParcelsForEXCode,
CountyAmountForEXCode,
TownAmountForEXCode,
SchoolAmountForEXCode,
VillageAmountForEXCode);
NumParcelsForEXCode := 0;
CountyAmountForEXCode := 0;
TownAmountForEXCode := 0;
SchoolAmountForEXCode := 0;
VillageAmountForEXCode := 0;
end; {If (Take(5, PreviousEXCode) <> Take(5, SortRemovedExemptionsTable.FieldByName('ExemptionCode').Text))}
{If this is a different swis code, print out the totals for
the swis.}
If ((Take(6, PreviousSwisCode) <> Take(6, SortRemovedExemptionsTable.FieldByName('SwisCode').Text)) or
Done)
then
begin
{Print the totals for this swis code.}
PrintEXTotals(Sender, 'S', PreviousSwisCode,
NumParcelsForSwisCode,
CountyAmountForSwisCode,
TownAmountForSwisCode,
SchoolAmountForSwisCode,
VillageAmountForSwisCode);
NumParcelsForSwisCode := 0;
CountyAmountForSwisCode := 0;
TownAmountForSwisCode := 0;
SchoolAmountForSwisCode := 0;
VillageAmountForSwisCode := 0;
end; {If (Take(6, PreviousSwisCode) <> Take(6, SortRemovedExemptionsTable.FieldByName('SwisCode').Text))}
{If they switched swis codes or they are at
the end of this page, start a new page.}
If ((Take(6, PreviousSwisCode) <> Take(6, SortRemovedExemptionsTable.FieldByName('SwisCode').Text)) or
(LinesLeft < LinesAtBottom))
then
begin
NewPage;
PageNum := PageNum + 1;
PrintReportHeader(Sender, ReportTime, PageNum,
'Parcels Within Exemption Code',
SortRemovedExemptionsTable.FieldByName('SwisCode').Text);
PrintExemptionSection2Header(Sender);
FirstLineOnPage := True;
end; {If (LinesLeft < 5)}
end; {If not Quit}
If not Done or Quit
then
begin
ProgressDialog.Update(Self,
'EX Code: ' +
SortRemovedExemptionsTable.FieldByName('ExemptionCode').Text);
{Only print the Exemption code if this is the
first parcel for this exemption.}
with SortRemovedExemptionsTable do
begin
Bold := True;
If ((Take(5, PreviousEXCode) <> Take(5, FieldByName('ExemptionCode').Text)) or
FirstLineOnPage)
then Print(#9 + FieldByName('ExemptionCode').Text)
else Print(#9); {Skip the ex code.}
Bold := False;
{Now print the exemption amounts.}
Print(#9 + ConvertSBLOnlyToDashDot(FieldByName('SBLKey').Text) +
#9 + Take(13, FieldByName('Name').Text) +
#9 + Take(13, FieldByName('Location').Text) +
#9 + FieldByName('RollSection').Text +
#9 + FieldByName('SchoolCode').Text +
#9 + FieldByName('YearRemovedFrom').Text +
#9 + FieldByName('ActualDateRemoved').Text +
#9 + FieldByName('EffectiveDateRemoved').Text +
#9 + BoolToChar_Blank_X(FieldByName('RemovedDueToSale').AsBoolean));
If (rtdCounty in GlblRollTotalsToShow)
then Print(#9 + FormatFloat(CurrencyDisplayNoDollarSign,
FieldByName('CountyAmount').AsInteger))
else Print(#9);
If (rtdMunicipal in GlblRollTotalsToShow)
then Print(#9 + FormatFloat(NoDecimalDisplay_BlankZero,
FieldByName('TownAmount').AsInteger))
else Print(#9);
If (rtdSchool in GlblRollTotalsToShow)
then Println(#9 + FormatFloat(NoDecimalDisplay_BlankZero,
FieldByName('SchoolAmount').AsInteger))
else
If (rtdVillageReceivingPartialRoll in GlblRollTotalsToShow)
then Println(#9 + FormatFloat(NoDecimalDisplay_BlankZero,
FieldByName('VillageAmount').AsInteger))
else Println('');
FirstLineOnPage := False;
NumParcelsForEXCode := NumParcelsForEXCode + 1;
CountyAmountForEXCode := CountyAmountForEXCode +
FieldByName('CountyAmount').AsInteger;
TownAmountForEXCode := TownAmountForEXCode +
FieldByName('TownAmount').AsInteger;
SchoolAmountForEXCode := SchoolAmountForEXCode +
FieldByName('SchoolAmount').AsInteger;
VillageAmountForEXCode := VillageAmountForEXCode +
FieldByName('VillageAmount').AsInteger;
{FXX05101999-2: Need to update swis totals here so
if one ex code, they get updated.
Same thing for totals.}
NumParcelsForSwisCode := NumParcelsForSwisCode + 1;
CountyAmountForSwisCode := CountyAmountForSwisCode +
FieldByName('CountyAmount').AsInteger;
TownAmountForSwisCode := TownAmountForSwisCode +
FieldByName('TownAmount').AsInteger;
SchoolAmountForSwisCode := SchoolAmountForSwisCode +
FieldByName('SchoolAmount').AsInteger;
VillageAmountForSwisCode := VillageAmountForSwisCode +
FieldByName('VillageAmount').AsInteger;
TotalNumParcels := TotalNumParcels + 1;
TotalCountyAmount := TotalCountyAmount +
FieldByName('CountyAmount').AsInteger;
TotalTownAmount := TotalTownAmount +
FieldByName('TownAmount').AsInteger;
TotalSchoolAmount := TotalSchoolAmount +
FieldByName('SchoolAmount').AsInteger;
TotalVillageAmount := TotalVillageAmount +
FieldByName('VillageAmount').AsInteger;
end; {with SortRemovedExemptionsTable do}
end; {If not Done or Quit}
PreviousSwisCode := SortRemovedExemptionsTable.FieldByName('SwisCode').Text;
PreviousEXCode := SortRemovedExemptionsTable.FieldByName('ExemptionCode').Text;
ReportCancelled := ProgressDialog.Cancelled;
until (Done or Quit or ReportCancelled);
{Print out the overall exemption totals.}
If not (Quit or ReportCancelled)
then PrintEXTotals(Sender, 'T', PreviousSwisCode,
TotalNumParcels,
TotalCountyAmount,
TotalTownAmount,
TotalSchoolAmount,
TotalVillageAmount);
end; {with Sender as TBaseReport do}
end; {PrintExemptionSection2}
{===================================================================}
Procedure TRemovedExemptionReportForm.ReportPrint(Sender: TObject);
{To print the report, we will print each of the segments seperately.
We will not use the normal paging event driven methods.
We will control all paging.}
var
Quit : Boolean;
ReportTime : TDateTime;
PageNum : Integer;
begin
Quit := False;
PageNum := 1;
ReportTime := Now;
{FXX10091998-5: Allow them to select which section(s) to print.}
If ((not (Quit or ReportCancelled)) and
PrintSection1CheckBox.Checked)
then PrintExemptionSection1(Sender, ReportTime, PageNum, Quit);
{FXX06231998-2: Allow them to not print section 2.}
If ((not (Quit or ReportCancelled)) and
PrintSection2CheckBox.Checked)
then
begin
{FXX12021998-5: If printing both sections, need to form feed.}
If PrintSection1CheckBox.Checked
then TBaseReport(Sender).NewPage;
PrintExemptionSection2(Sender, ReportTime, PageNum, Quit);
end; {If ((not (Quit or ReportCancelled)) and ...}
end; {TextFilerPrint}
{===================================================================}
Procedure TRemovedExemptionReportForm.FormClose( Sender: TObject;
var Action: TCloseAction);
begin
SelectedRollSections.Free;
CloseTablesForForm(Self);
{Free up the child window and set the ClosingAForm Boolean to
true so that we know to delete the tab.}
Action := caFree;
GlblClosingAForm := True;
GlblClosingFormCaption := Caption;
end; {FormClose}
end. |
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit DSAzureTableDialog;
interface
uses
Vcl.Buttons, System.Classes, Vcl.Controls, Data.DBXJSON, Vcl.Dialogs, DSAzure, Vcl.ExtCtrls, Vcl.Forms,
System.Generics.Collections, Vcl.Graphics, Vcl.Grids, Vcl.ImgList, Vcl.Menus, Vcl.StdCtrls, System.SysUtils,
Vcl.ValEdit, Xml.XMLIntf;
type
///<summary> Possible data types for a table 'column' (Entity property)
///</summary>
TPropertyDataType =
(azdtBinary, azdtBoolean, azdtDateTime, azdtDouble, azdtGuid, azdtInt32, azdtInt64, azdtString, azdtUnknown);
TRowType = (azrUnknown, azrLoading, azrRow, azrTruncated);
/// <summary>
/// Continuation token which may exist if results of a entity population are partial.
/// </summary>
/// <remarks>
/// An entity population will be partial if there are more than 1000 results or if there is a timeout.
/// </remarks>
TAzureRowContinuationToken = record
IsValid: Boolean; //True if the population result was partial and this token should be used
NextRowKey: String;
NextPartitionKey: String;
end;
///<summary>
/// Representing a single cell (Row/Column) of a table
///</summary>
TAzureTableColumn = class
protected
FDataType: TPropertyDataType;
public
Name: String;
Value: String;
constructor Create; Virtual;
/// <summary> Creates a clone of the instance </summary>
function Copy: TAzureTableColumn;
procedure SetDataType(Value: String);
property DataType: TPropertyDataType read FDataType write FDataType;
end;
TAzureRow = class
protected
FRowType: TRowType;
public
Constructor Create(RowType: TRowType = azrRow); Virtual;
property RowType: TRowType read FRowType;
end;
///<summary>
/// Table Entity (Row) specific information.
///</summary>
TAzureTableRow = class(TAzureRow)
protected
//NOTE: Timestamp is ignored, as suggested here: http://msdn.microsoft.com/en-us/library/dd179338.aspx
FRowKey: TAzureTableColumn;
FPartitionKey: TAzureTableColumn;
FColumns: TDictionary<String,TAzureTableColumn>;
public
constructor Create; Reintroduce;
destructor Destroy; Override;
function GetID: String; Virtual;
procedure SetColumn(Key: String; Value: TAzureTableColumn);
function ClearColumn(Key: String; InstanceOwner: Boolean = True): TAzureTableColumn;
procedure ClearColumns(InstanceOwner: Boolean = True);
function GetColumn(Key: String; IgnoreCase: Boolean = False): TAzureTableColumn;
property RowKey: TAzureTableColumn read FRowKey;
property PartitionKey: TAzureTableColumn read FPartitionKey;
property Columns: TDictionary<String,TAzureTableColumn> read FColumns write FColumns;
end;
///<summary>
/// Wrapper for a Table Row, which allows for modification which can either be committed or rolled back.
///</summary>
TAzureTemporaryTableRow = class(TAzureTableRow)
protected
FWrapped: TAzureTableRow;
FNewRow: Boolean;
public
constructor Create(RowKey, PartitionKey: String); Reintroduce; Overload;
constructor Create(Wrapped: TAzureTableRow); Reintroduce; Overload;
destructor Destroy; Override;
function GetID: String; Override;
/// <summary> This commits the changes into the wrapped object, but does not push these changes
/// to the Azure server. That is the job of whoever calls this commit.
/// </summary>
function Commit: TAzureTableRow;
property Wrapped: TAzureTableRow read FWrapped;
property IsNewRow: Boolean read FNewRow;
end;
/// <summary> Dialog for managing an Azure table, with the ability to add/remove and edit rows and columns.
/// </summary>
TTAzureTableDialog = class(TForm)
CloseButton: TButton;
commitButton: TButton;
outerpanel: TPanel;
leftCol: TPanel;
panSplit: TSplitter;
rightCol: TPanel;
ColumnTable: TValueListEditor;
EntityLabel: TLabel;
RowList: TListBox;
Panel1: TPanel;
RowsLabel: TLabel;
ImageList1: TImageList;
filterField: TButtonedEdit;
ImportRowsDialog: TOpenDialog;
procedure FormDestroy(Sender: TObject);
procedure commitButtonClick(Sender: TObject);
procedure RowListClick(Sender: TObject);
procedure filterFieldRightButtonClick(Sender: TObject);
procedure filterFieldKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
protected
FConnectionInfo: TAzureConnectionString;
FTableName: String;
FCurrentEntity: TAzureTemporaryTableRow;
FCurrentColumn: TAzureTableColumn;
FAddingRow: Boolean;
FDeleteColumnItem: TMenuItem;
FAdvancedFilterPrefix: String;
function ByteContent(DataStream: TStream): TBytes;
procedure InitializeRows;
procedure ClearRows;
procedure ClearColumnTable;
procedure AddRow(ColumnEntry: TAzureTableColumn);
procedure FilterRows;
procedure RowsPopulated(Rows: TList<TAzureTableRow>; ContinuationToken: TAzureRowContinuationToken);
procedure RowCreatedOrUpdated(Row: TAzureTableRow; IsNew: Boolean);
procedure BatchRowsCreated(Success: Boolean);
procedure RowDeleted(Row: TAzureTableRow; Success: Boolean);
function CreateRowListPopupMenu: TPopupMenu;
procedure UpdateRowListPopupMenu(Sender: TObject);
procedure HandleRowKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
function CreateColumnsPopupMenu: TPopupMenu;
procedure UpdateColumnsPopupMenu(Sender: TObject);
procedure CreateDTMenuItem(Menu: TPopupMenu; Parent: TMenuItem; DataTypeName: String);
procedure HandleColumnDblClick(Sender: TObject);
function GetSelectedRow: TAzureTableRow;
function GetLastRow: TAzureTableRow;
procedure EnableRowSelection(Enabled: Boolean = True);
procedure ImportRows(RowArray: TJSONArray);
//Context Menu actions
procedure SetCurrentEntity(Row: TAzureTemporaryTableRow = nil);
procedure AddRowAction(Sender: TObject);
procedure DeleteRowAction(Sender: TObject);
procedure ImportRowsAction(Sender: TObject);
procedure RefreshRowsAction(Sender: TObject);
procedure EditColumnAction(Sender: TObject);
procedure AddColumnAction(Sender: TObject);
procedure DeleteColumnAction(Sender: TObject);
procedure SetDataTypeAction(Sender: TObject);
procedure SetColumnValue(OriginalName: String; Column: TAzureTableColumn);
public
constructor Create(AOwner: TComponent; ConnectionInfo: TAzureConnectionString); reintroduce;
procedure SetTable(TableName: String);
property AdvancedFilterPrefix: String read FAdvancedFilterPrefix write FAdvancedFilterPrefix;
end;
/// <summary> Returns the string representation of the given data type </summary>
function GetDataType(DataType: TPropertyDataType): String; Overload;
/// <summary> Returns the data type for the given string representation. </summary>
function GetDataType(DataType: String): TPropertyDataType; Overload;
/// <summary> Returns true if the given value is a valid format to be transformed into the specified data type
/// </summary>
function ValidateValueForDataType(Value: String; DataType: TPropertyDataType): Boolean;
/// <summary> Helper function for populating a row object from the 'content' node of an Azure xml file. </summary>
function GetRowFromConentNode(ContentNode: IXMLNode): TAzureTableRow;
const
ADD_ROW = 'AddRow';
DELETE_ROW = 'DeleteRow';
IMPORT_ROWS = 'ImportRows';
REFRESH_ROWS = 'RefreshRows';
EDIT_COLUMN = 'EditColumn';
ADD_COLUMN = 'AddColumn';
DELETE_COLUMN = 'DeleteColumn';
DATA_TYPE_ITEM = 'DataType';
XML_ROWKEY = 'RowKey';
XML_PARTITION = 'PartitionKey';
XML_TIMESTAMP = 'Timestamp';
DT_XML_PREFIX = 'Edm.';
DT_BINARY = 'Binary';
DT_BOOLEAN = 'Boolean';
DT_DATETIME = 'DateTime';
DT_DOUBLE = 'Double';
DT_GUID = 'Guid';
DT_INT32 = 'Int32';
DT_INT64 = 'Int64';
DT_STRING = 'String';
implementation
{$R *.dfm}
uses
Winapi.ActiveX, AzureUI, Data.DBXClientResStrs, DSAzureTable, DSAzureTableRowDialog,
System.StrUtils, Winapi.Windows, Xml.XMLDoc;
type
TRowPopulatorCallback = procedure(Rows: TList<TAzureTableRow>; ContinuationToken: TAzureRowContinuationToken) of object;
TBatchRowCreatedCallback = procedure(Success: Boolean) of object;
TRowCreatedCallback = procedure(Row: TAzureTableRow; IsNew: Boolean) of object;
TRowDeletedCallback = procedure(Row: TAzureTableRow; Success: Boolean) of object;
/// <summary> Thread for populating Table rows (Entities) </summary>
TRowPopulator = class(TThread)
protected
FTableName: String;
FFilter: String;
FConnectionInfo: TAzureConnectionString;
FCallback: TRowPopulatorCallback;
FTableService: TAzureTableService;
FAdvancedFilterPrefix: String;
function BuildFilterString: String;
public
constructor Create(TableName: String;
ConnectionInfo: TAzureConnectionString;
Callback: TRowPopulatorCallback;
AdvancedFilterPrefix: String; Filter: String = ''); Virtual;
destructor Destroy; override;
procedure Execute; override;
end;
/// <summary> Thread for creating or updating a given row (Entity) </summary>
TRowCreator = class(TThread)
protected
FTableName: String;
FRow: TAzureTemporaryTableRow;
FConnectionInfo: TAzureConnectionString;
FCallback: TRowCreatedCallback;
FTableService: TAzureTableService;
public
constructor Create(TableName: String; Row: TAzureTemporaryTableRow;
ConnectionInfo: TAzureConnectionString;
Callback: TRowCreatedCallback); Virtual;
destructor Destroy; override;
procedure Execute; override;
end;
/// <summary> Thread for creating (not updating) a batch of Rows (Entities) </summary>
TBatchRowCreator = class(TThread)
protected
FTableName: String;
FRows: TJSONArray;
FConnectionInfo: TAzureConnectionString;
FCallback: TBatchRowCreatedCallback;
FTableService: TAzureTableService;
function CreateRow(Row: TJSONObject): Boolean;
public
constructor Create(TableName: String; Rows: TJSONArray;
ConnectionInfo: TAzureConnectionString;
Callback: TBatchRowCreatedCallback); Virtual;
destructor Destroy; override;
procedure Execute; override;
end;
/// <summary> Thread for deleting a row (Entity) </summary>
TRowDeletor = class(TThread)
protected
FTableName: String;
FRow: TAzureTableRow;
FConnectionInfo: TAzureConnectionString;
FCallback: TRowDeletedCallback;
FTableService: TAzureTableService;
public
constructor Create(TableName: String; Row: TAzureTableRow;
ConnectionInfo: TAzureConnectionString;
Callback: TRowDeletedCallback); Virtual;
destructor Destroy; override;
procedure Execute; override;
end;
{ TTAzureTableDialog }
function GetDataType(DataType: String): TPropertyDataType;
begin
Result := azdtUnknown;
if AnsiStartsStr(DT_XML_PREFIX, DataType) then
DataType := Copy(DataType, Length(DT_XML_PREFIX) + 1);
if DataType = DT_BINARY then
Result := azdtBinary
else if DataType = DT_BOOLEAN then
Result := azdtBoolean
else if DataType = DT_DATETIME then
Result := azdtDateTime
else if DataType = DT_DOUBLE then
Result := azdtDouble
else if DataType = DT_GUID then
Result := azdtGuid
else if DataType = DT_INT32 then
Result := azdtInt32
else if DataType = DT_INT64 then
Result := azdtInt64
else if DataType = DT_STRING then
Result := azdtString;
end;
function GetDataType(DataType: TPropertyDataType): String;
begin
case DataType of
azdtBinary: Result:= DT_XML_PREFIX + DT_BINARY;
azdtBoolean: Result:= DT_XML_PREFIX + DT_BOOLEAN;
azdtDateTime: Result:= DT_XML_PREFIX + DT_DATETIME;
azdtDouble: Result:= DT_XML_PREFIX + DT_DOUBLE;
azdtGuid: Result:= DT_XML_PREFIX + DT_GUID;
azdtInt32: Result:= DT_XML_PREFIX + DT_INT32;
azdtInt64: Result:= DT_XML_PREFIX + DT_INT64;
azdtString: Result:= DT_XML_PREFIX + DT_STRING;
else
Result:= EmptyStr;
end;
end;
function ValidateValueForDataType(Value: String; DataType: TPropertyDataType): Boolean;
begin
Result := False;
if DataType = azdtUnknown then
Exit(False);
if DataType = azdtString then
Exit(True);
if DataType = azdtGuid then
Exit(True);
if DataType = azdtBoolean then
Exit((LowerCase(Value) = 'true') or (LowerCase(Value) = 'false'));
if (DataType = azdtInt32) or (DataType = azdtInt64) then
begin
try
StrToInt(Value);
Exit(True);
except
Exit(False);
end;
end;
if (DataType = azdtDouble) then
begin
try
StrToFloat(Value);
Exit(True);
except
Exit(False);
end;
end;
if (DataType = azdtDateTime) or (DataType = azdtBinary) then
Result := True;
end;
function GetRowFromConentNode(ContentNode: IXMLNode): TAzureTableRow;
var
PropertiesNode: IXMLNode;
PropertyNode: IXMLNode;
PropName: String;
Aux: Integer;
Row: TAzureTableRow;
Column: TAzureTableColumn;
begin
if (ContentNode = nil) or (ContentNode.NodeName <> NODE_TABLE_CONTENT) then
Exit(nil);
Result := nil;
if (ContentNode.HasChildNodes) then
begin
PropertiesNode := GetFirstMatchingChildNode(ContentNode, NODE_PROPERTIES);
if (PropertiesNode <> nil) and (PropertiesNode.HasChildNodes) then
begin
PropertyNode := PropertiesNode.ChildNodes.First;
Row := TAzureTableRow.Create;
while PropertyNode <> nil do
begin
try
PropName := PropertyNode.NodeName;
Aux := AnsiPos(':', PropName);
if Aux > -1 then
PropName := Copy(PropName, Aux + 1);
if PropName = XML_PARTITION then
Row.PartitionKey.Value := PropertyNode.Text
else if PropName = XML_ROWKEY then
Row.RowKey.Value := PropertyNode.Text
else
begin
Column := TAzureTableColumn.Create;
Column.Name := PropName;
Column.Value := PropertyNode.Text;
if PropertyNode.HasAttribute('m:type') then
Column.SetDataType(PropertyNode.Attributes['m:type']);
Row.Columns.Add(PropName, Column);
end;
except
break;
end;
PropertyNode := PropertyNode.NextSibling;
end;
Result := Row;
end;
end;
end;
procedure TTAzureTableDialog.SetCurrentEntity(Row: TAzureTemporaryTableRow);
var
Key: String;
Value: TAzureTableColumn;
begin
if (FCurrentEntity <> nil) and commitButton.Enabled then
begin
if not (MessageDlg(SConfirmRowChangeLoss, mtConfirmation, [mbYes, mbNo], 0) = mrYes) then
begin
FreeAndNil(Row);
Exit;
end;
end;
FreeAndNil(FCurrentEntity);
FCurrentEntity := Row;
ColumnTable.Enabled := (Row <> nil);
commitButton.Enabled := (Row <> nil) and Row.IsNewRow;
if Row = nil then
begin
EntityLabel.Caption := EmptyStr;
ClearColumnTable;
end
else
begin
EntityLabel.Caption := Format(SEntityTitle, [FCurrentEntity.GetID]);
ColumnTable.Strings.BeginUpdate;
try
ClearColumnTable;
ColumnTable.InsertRow(XML_ROWKEY, Row.RowKey.Value, True);
ColumnTable.InsertRow(XML_PARTITION, Row.PartitionKey.Value, True);
for Key in Row.Columns.Keys do
begin
//hide timestamp, as the online documentation says to do
if Key <> XML_TIMESTAMP then
begin
Value := Row.Columns.Items[Key];
ColumnTable.InsertRow(Key, Value.Value, True);
end;
end;
finally
ColumnTable.Strings.EndUpdate;
end;
end;
end;
procedure TTAzureTableDialog.SetDataTypeAction(Sender: TObject);
var
DataType: TPropertyDataType;
begin
if (FCurrentColumn <> nil) and (Sender is TMenuItem) then
begin
DataType := GetDataType(TMenuItem(Sender).Name);
if (DataType <> FCurrentColumn.DataType) then
begin
if ValidateValueForDataType(FCurrentColumn.Value, DataType) then
begin
FCurrentColumn.DataType := DataType;
commitButton.Enabled := True;
end
else
MessageDlg(Format(SInvalidDataType, [TMenuItem(Sender).Name, FCurrentColumn.Value]),
mtError, [mbOK], 0);
end;
end;
end;
procedure TTAzureTableDialog.SetColumnValue(OriginalName: String; Column: TAzureTableColumn);
var
RowIndex: Integer;
begin
if (FCurrentEntity = nil) or (Column = nil) then
Exit;
if ColumnTable.FindRow(OriginalName, RowIndex) then
begin
ColumnTable.Keys[RowIndex] := Column.Name;
ColumnTable.Values[Column.Name] := Column.Value;
end
else
begin
ColumnTable.InsertRow(Column.Name, Column.Value, True);
end;
end;
procedure TTAzureTableDialog.EditColumnAction(Sender: TObject);
var
Dialog: TTAzureTableRowDialog;
OriginalName: String;
begin
if (FCurrentEntity = nil) or (FCurrentColumn = nil) then
Exit;
Dialog := TTAzureTableRowDialog.Create(Self, FCurrentColumn, FCurrentEntity);
try
ColumnTable.Strings.BeginUpdate;
if (Dialog.ShowModal = mrOK) then
begin
OriginalName := FCurrentColumn.Name;
//name of property has changed
if OriginalName <> Dialog.Name then
begin
FCurrentEntity.ClearColumn(OriginalName, False);
FCurrentEntity.SetColumn(Dialog.Name, Dialog.PersistChanges);
end
else
Dialog.PersistChanges;
SetColumnValue(OriginalName, FCurrentColumn);
commitButton.Enabled := True;
end;
finally
ColumnTable.Strings.EndUpdate;
FreeAndNil(Dialog);
end;
end;
procedure TTAzureTableDialog.AddColumnAction(Sender: TObject);
var
Dialog: TTAzureTableRowDialog;
NewColumn: TAzureTableColumn;
begin
if FCurrentEntity = nil then
Exit;
Dialog := TTAzureTableRowDialog.Create(Self, nil, FCurrentEntity);
try
if (Dialog.ShowModal = mrOK) then
begin
NewColumn := Dialog.PersistChanges;
AddRow(NewColumn);
commitButton.Enabled := True;
end;
finally
FreeAndNil(Dialog);
end;
end;
procedure TTAzureTableDialog.AddRow(ColumnEntry: TAzureTableColumn);
begin
if (FCurrentEntity = nil) or (ColumnEntry = nil) then
Exit;
ColumnTable.Strings.BeginUpdate;
try
if (ColumnTable.Strings.IndexOfName(EmptyStr) = (ColumnTable.Strings.Count - 1)) then
ColumnTable.Strings.Delete(ColumnTable.Strings.Count - 1);
ColumnTable.InsertRow(ColumnEntry.Name, ColumnEntry.Value, True);
FCurrentEntity.SetColumn(ColumnEntry.Name, ColumnEntry);
finally
ColumnTable.Strings.EndUpdate;
end;
end;
procedure TTAzureTableDialog.AddRowAction(Sender: TObject);
var
NewRow: TAzureTemporaryTableRow;
PartitionKey: String;
SelectedRow: TAzureTableRow;
begin
if not FAddingRow then
begin
SelectedRow := GetSelectedRow;
//If no row is selected, use the partition key from the last row
if (SelectedRow = nil) then
SelectedRow := GetLastRow;
if SelectedRow <> nil then
PartitionKey := SelectedRow.PartitionKey.Value;
NewRow := TAzureTemporaryTableRow.Create(EmptyStr, PartitionKey);
SetCurrentEntity(NewRow);
end;
end;
procedure TTAzureTableDialog.BatchRowsCreated(Success: Boolean);
begin
if not Assigned(Self) then
Exit;
EnableRowSelection(True);
if not Success then
MessageDlg(SImportEntitiesError, mtError, [mbOK], 0);
InitializeRows;
end;
function TTAzureTableDialog.ByteContent(DataStream: TStream): TBytes;
var
Buffer: TBytes;
begin
if not Assigned(DataStream) then
exit(nil);
SetLength(Buffer, DataStream.Size);
// the content may have been read
DataStream.Position := 0;
if DataStream.Size > 0 then
DataStream.Read(Buffer[0], DataStream.Size);
Result := Buffer;
end;
procedure TTAzureTableDialog.ClearColumnTable;
begin
try
if ColumnTable.Strings.Count > 0 then
begin
SelectTopCell(ColumnTable, True);
ColumnTable.Strings.Clear;
end;
except
end;
end;
procedure TTAzureTableDialog.ClearRows;
var
I: Integer;
begin
ClearColumnTable;
for I := 0 to Pred(RowList.Items.Count) do
begin
//if the current instance is the same as FCurrentEntity set it to nil here
//so we don't get an access violation when later freeing FCurrententity. This will probably
//never be the case, but it doesn't hurt to be safe
if RowList.Items.Objects[I] = FCurrentEntity then
FCurrentEntity := nil;
RowList.Items.Objects[I].Free;
RowList.Items.Objects[I] := nil;
end;
FreeAndNil(FCurrentEntity);
RowList.Clear;
end;
procedure TTAzureTableDialog.commitButtonClick(Sender: TObject);
var
Row: TAzureTemporaryTableRow;
begin
Assert(FCurrentEntity <> nil);
Row := FCurrentEntity;
//prevent the current entity from being freed, as it will be freed later in the TRowCreator thread
FCurrentEntity := nil;
EnableRowSelection(False);
TRowCreator.Create(FTableName, Row, FConnectionInfo, RowCreatedOrUpdated);
end;
constructor TTAzureTableDialog.Create(AOwner: TComponent; ConnectionInfo: TAzureConnectionString);
begin
inherited Create(AOwner);
FConnectionInfo := ConnectionInfo;
RowList.PopupMenu := CreateRowListPopupMenu;
RowList.OnKeyUp := HandleRowKeyUp;
EntityLabel.Caption := EmptyStr;
ColumnTable.Enabled := False;
ColumnTable.PopupMenu := CreateColumnsPopupMenu;
ColumnTable.OnDblClick := HandleColumnDblClick;
FAdvancedFilterPrefix := '~';
end;
function TTAzureTableDialog.CreateColumnsPopupMenu: TPopupMenu;
var
Menu: TPopupMenu;
Item: TMenuItem;
begin
Menu := TPopupMenu.Create(Self);
Menu.OnPopup := UpdateColumnsPopupMenu;
Item := Menu.CreateMenuItem;
Item.Name := EDIT_COLUMN;
Item.Caption := SEditColumn;
Item.OnClick := EditColumnAction;
Menu.Items.Add(Item);
FDeleteColumnItem := Menu.CreateMenuItem;
FDeleteColumnItem.Name := DELETE_COLUMN;
FDeleteColumnItem.Caption := SDeleteColumn;
FDeleteColumnItem.OnClick := DeleteColumnAction;
Menu.Items.Add(FDeleteColumnItem);
Item := Menu.CreateMenuItem;
Item.Name := 'N1';
Item.Caption := cLineCaption;
Menu.Items.Add(Item);
Item := Menu.CreateMenuItem;
Item.Name := ADD_COLUMN;
Item.Caption := SAddColumn;
Item.OnClick := AddColumnAction;
Menu.Items.Add(Item);
Result := Menu;
end;
procedure TTAzureTableDialog.CreateDTMenuItem(Menu: TPopupMenu; Parent: TMenuItem; DataTypeName: String);
var
Item: TMenuItem;
begin
Item := Menu.CreateMenuItem;
Item.Name := DataTypeName;
Item.Caption := DT_XML_PREFIX + DataTypeName;
Item.OnClick := SetDataTypeAction;
Parent.Add(Item);
end;
function TTAzureTableDialog.CreateRowListPopupMenu: TPopupMenu;
var
Menu: TPopupMenu;
Item: TMenuItem;
begin
Menu := TPopupMenu.Create(Self);
Menu.OnPopup := UpdateRowListPopupMenu;
Item := Menu.CreateMenuItem;
Item.Name := ADD_ROW;
Item.Caption := SAddTableEntity;
Item.OnClick := AddRowAction;
Menu.Items.Add(Item);
Item := Menu.CreateMenuItem;
Item.Name := DELETE_ROW;
Item.Caption := SDeleteTableEntity;
Item.OnClick := DeleteRowAction;
Menu.Items.Add(Item);
Item := Menu.CreateMenuItem;
Item.Name := IMPORT_ROWS;
Item.Caption := SImportTableEntities;
Item.OnClick := ImportRowsAction;
Menu.Items.Add(Item);
Item := Menu.CreateMenuItem;
Item.Name := REFRESH_ROWS;
Item.Caption := SRefresh;
Item.OnClick := RefreshRowsAction;
Menu.Items.Add(Item);
Result := Menu;
end;
procedure TTAzureTableDialog.DeleteColumnAction(Sender: TObject);
var
Index: Integer;
begin
if (FCurrentColumn <> nil) and (FCurrentEntity <> nil) then
begin
Index := ColumnTable.Strings.IndexOfName(FCurrentColumn.Name);
if (Index > -1) then
begin
commitButton.Enabled := True;
ColumnTable.DeleteRow(Index + 1);
FCurrentEntity.ClearColumn(FCurrentColumn.Name, True);
end;
end;
end;
procedure TTAzureTableDialog.DeleteRowAction(Sender: TObject);
var
Row: TAzureTableRow;
begin
Row := GetSelectedRow;
if Row <> nil then
begin
if ConfirmDeleteItem then
begin
EnableRowSelection(False);
ClearColumnTable;
TRowDeletor.Create(FTableName, Row, FConnectionInfo, RowDeleted);
end;
end;
end;
procedure TTAzureTableDialog.EnableRowSelection(Enabled: Boolean);
begin
if not Assigned(Self) or not Assigned(RowList) then
Exit;
if not Enabled then
SetCurrentEntity(nil);
RowList.Enabled := Enabled;
FilterField.Enabled := Enabled;
end;
procedure TTAzureTableDialog.filterFieldKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if (Key = VK_RETURN) then
FilterRows;
end;
procedure TTAzureTableDialog.filterFieldRightButtonClick(Sender: TObject);
begin
FilterRows;
end;
procedure TTAzureTableDialog.FilterRows;
begin
InitializeRows;
end;
procedure TTAzureTableDialog.FormDestroy(Sender: TObject);
begin
ClearRows;
end;
function TTAzureTableDialog.GetLastRow: TAzureTableRow;
var
Count: Integer;
begin
Result := nil;
Count := RowList.Count;
if Count > 0 then
begin
Result := TAzureTableRow(RowList.Items.Objects[Count - 1]);
if (Result <> nil) and (Result.RowType <> azrRow) and (Count > 1) then
begin
Result := TAzureTableRow(RowList.Items.Objects[Count - 2]);
Assert(Result.RowType = azrRow);
end;
end;
end;
function TTAzureTableDialog.GetSelectedRow: TAzureTableRow;
var
Index: Integer;
Row: TAzureRow;
begin
Result := nil;
Index := RowList.ItemIndex;
if Index > -1 then
begin
Row := TAzureRow(RowList.Items.Objects[Index]);
if Row.RowType = azrRow then
Result := TAzureTableRow(Row);
end;
end;
procedure TTAzureTableDialog.HandleColumnDblClick(Sender: TObject);
begin
//Populate FCurrentcolumn
UpdateColumnsPopupMenu(Sender);
//open colum edit dialog, if current selected column is valid
EditColumnAction(Sender);
end;
procedure TTAzureTableDialog.HandleRowKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if (Key = VK_DELETE) then
DeleteRowAction(Sender);
end;
procedure TTAzureTableDialog.SetTable(TableName: String);
begin
FTableName := TableName;
if TableName = '' then
Caption := STableEditorTitle
else
Caption := Format(STableEditorTitle2, [TableName]);
InitializeRows;
end;
procedure TTAzureTableDialog.UpdateColumnsPopupMenu(Sender: TObject);
var
P: TPoint;
Col: Integer;
Row: Integer;
MenuItem: TMenuItem;
begin
FCurrentColumn := nil;
FDeleteColumnItem.Enabled := False;
GetCursorPos(P);
P.X := P.X - ColumnTable.ClientOrigin.X;
P.Y := P.Y - ColumnTable.ClientOrigin.Y;
ColumnTable.MouseToCell(P.X, P.Y, Col, Row);
for MenuItem in ColumnTable.PopupMenu.Items do
begin
if FCurrentEntity = nil then
MenuItem.Enabled := False
else if (MenuItem.Name = EDIT_COLUMN) or (MenuItem.Name = DELETE_COLUMN) then
begin
//enabled if it isn't the RowKey or PartitionKey row. For those rows, it is only enabled
//if it is the edit item and it is a new row.
MenuItem.Enabled := (Row > -1) and ((Row > 2) or (FCurrentEntity.IsNewRow and (MenuItem.Name = EDIT_COLUMN)));
if MenuItem.Enabled then
begin
FCurrentColumn := FCurrentEntity.GetColumn(ColumnTable.Keys[Row]);
end;
end;
end;
end;
procedure TTAzureTableDialog.UpdateRowListPopupMenu(Sender: TObject);
var
Row: TAzureTableRow;
MenuItem: TMenuItem;
begin
Row := GetSelectedRow;
for MenuItem in RowList.PopupMenu.Items do
begin
if (MenuItem.Name = DELETE_ROW) then
MenuItem.Enabled := (Row <> nil)
else
MenuItem.Visible := True;
end;
end;
procedure TTAzureTableDialog.ImportRows(RowArray: TJSONArray);
begin
EnableRowSelection(False);
TBatchRowCreator.Create(FTableName, RowArray, FConnectionInfo, BatchRowsCreated);
end;
procedure TTAzureTableDialog.ImportRowsAction(Sender: TObject);
var
FileStream: TFileStream;
FileBytes: TBytes;
RowValue: TJSONValue;
begin
if ImportRowsDialog.Execute then
begin
FileStream := nil;
FileBytes := nil;
try
try
FileStream := TFileStream.Create(ImportRowsDialog.FileName, fmOpenRead);
FileBytes := ByteContent(FileStream);
RowValue := TJSONObject.ParseJSONValue(FileBytes, 0);
if RowValue is TJSONArray then
ImportRows(TJSONArray(RowValue));
except
MessageDlg(SImportEntitiesError, mtError, [mbOK], 0);
end;
finally
FreeAndNil(FileStream);
end;
end;
end;
procedure TTAzureTableDialog.InitializeRows;
begin
EnableRowSelection(False);
ClearRows;
RowList.AddItem(SNodeLoading, TAzureRow.Create(azrLoading));
TRowPopulator.Create(FTableName, FConnectionInfo, RowsPopulated, FAdvancedFilterPrefix, filterField.Text);
end;
procedure TTAzureTableDialog.RefreshRowsAction(Sender: TObject);
begin
if not FAddingRow then
InitializeRows;
end;
procedure TTAzureTableDialog.RowCreatedOrUpdated(Row: TAzureTableRow; IsNew: Boolean);
begin
if not Assigned(Self) then
Exit;
EnableRowSelection(True);
RowList.ClearSelection;
if Row = nil then
begin
if IsNew then
MessageDlg(SAddEntityError, mtError, [mbOK], 0)
else
MessageDlg(SUpdateEntityError, mtError, [mbOK], 0);
InitializeRows;
end;
if IsNew and (Row <> nil) then
begin
RowList.AddItem(Row.GetID, Row);
end
end;
procedure TTAzureTableDialog.RowDeleted(Row: TAzureTableRow; Success: Boolean);
begin
if not Assigned(Self) then
Exit;
EnableRowSelection(True);
if (Success) then
begin
if FCurrentEntity = Row then
SetCurrentEntity(nil);
RowList.DeleteSelected;
FreeAndNil(Row);
end
else if Row <> nil then
MessageDlg(Format(SDeleteEntityError, [Row.GetID]), mtError, [mbOK], 0);
end;
procedure TTAzureTableDialog.RowListClick(Sender: TObject);
var
Row: TAzureTableRow;
begin
Row := GetSelectedRow;
if Row <> nil then
begin
if (FCurrentEntity <> nil) and (not FCurrentEntity.IsNewRow) then
begin
//If the selected row is the one already being viewed then no need to replace it
if (FCurrentEntity.RowKey = Row.RowKey) and
(FCurrentEntity.PartitionKey = Row.PartitionKey) then
Exit;
end;
SetCurrentEntity(TAzureTemporaryTableRow.Create(Row));
end
else
SetCurrentEntity(nil);
end;
procedure TTAzureTableDialog.RowsPopulated(Rows: TList<TAzureTableRow>; ContinuationToken: TAzureRowContinuationToken);
var
Row: TAzureTableRow;
Aux: TAzureRow;
begin
if not Assigned(Self) then
Exit;
EnableRowSelection(True);
ClearRows;
if Rows <> nil then
begin
RowList.Items.BeginUpdate;
try
for Row in Rows do
begin
RowList.AddItem(Row.GetID, Row);
end;
if ContinuationToken.IsValid then
begin
Aux := TAzureRow.Create(azrTruncated);
RowList.AddItem(SResultsTruncated, Aux);
end;
//The items are now managed by the list
Rows.Clear;
FreeAndNil(Rows);
finally
RowList.Items.EndUpdate;
end;
end;
end;
{ TTableRowData }
function TAzureTableRow.ClearColumn(Key: String; InstanceOwner: Boolean): TAzureTableColumn;
begin
Result := GetColumn(Key);
FColumns.Remove(Key);
if InstanceOwner then
begin
FreeAndNil(Result);
end;
end;
procedure TAzureTableRow.ClearColumns(InstanceOwner: Boolean);
var
C: TAzureTableColumn;
begin
if InstanceOwner then
begin
for C in FColumns.Values do
C.Free;
end;
FColumns.Clear;
end;
constructor TAzureTableRow.Create;
begin
inherited Create(azrRow);
FRowKey := TAzureTableColumn.Create;
FRowKey.Name := XML_ROWKEY;
FPartitionKey := TAzureTableColumn.Create;
FPartitionKey.Name := XML_PARTITION;
FColumns := TDictionary<String,TAzureTableColumn>.Create;
end;
destructor TAzureTableRow.Destroy;
begin
ClearColumns;
FreeAndNil(FColumns);
FreeAndNil(FRowKey);
FreeAndNil(FPartitionKey);
inherited;
end;
function TAzureTableRow.GetColumn(Key: String; IgnoreCase: Boolean): TAzureTableColumn;
var
KeyLower: String;
AKey: String;
begin
Result := nil;
if CompareText(Key, XML_ROWKEY) = 0 then
Exit(FRowKey);
if CompareText(Key, XML_PARTITION) = 0 then
Exit(FPartitionKey);
if IgnoreCase then
begin
KeyLower := AnsiLowerCase(Key);
for AKey in FColumns.Keys do
begin
if KeyLower = AnsiLowerCase(AKey) then
Exit(FColumns.Items[AKey]);
end;
end
else if not FColumns.TryGetValue(Key, Result) then
Exit(nil);
end;
function TAzureTableRow.GetID: String;
begin
Result := Format('%s.%s', [RowKey.Value, PartitionKey.Value]);
end;
procedure TAzureTableRow.SetColumn(Key: String; Value: TAzureTableColumn);
begin
if (Key <> EmptyStr) and (Value <> nil) then
begin
ClearColumn(Key);
FColumns.Add(Key, Value);
end;
end;
{ TRowPopulator }
constructor TRowPopulator.Create(TableName: String; ConnectionInfo: TAzureConnectionString;
Callback: TRowPopulatorCallback; AdvancedFilterPrefix: String;
Filter: String);
begin
inherited Create;
Assert(ConnectionInfo <> nil);
Assert(TableName <> EmptyStr);
FTableName := TableName;
FFilter := Filter;
FConnectionInfo := ConnectionInfo;
FCallback := Callback;
FAdvancedFilterPrefix := AdvancedFilterPrefix;
end;
destructor TRowPopulator.Destroy;
begin
FreeAndNil(FTableService);
inherited;
end;
function TRowPopulator.BuildFilterString: String;
var
Filter: String;
begin
Filter := FFilter;
Result := Filter;
if Trim(Filter) = EmptyStr then
Exit(EmptyStr);
if (Trim(FAdvancedFilterPrefix) = EmptyStr) then
Result := Trim(Filter)
else if AnsiStartsStr(FAdvancedFilterPrefix, FFilter) then
Result := Trim(Copy(Filter, Length(FAdvancedFilterPrefix) + 1))
else
begin
Filter := Trim(Filter);
Result := Format('(RowKey eq ''%s'') or (PartitionKey eq ''%s'')', [Filter, Filter]);
end;
end;
procedure TRowPopulator.Execute;
const
NextRow = 'x-ms-continuation-NextRowKey';
NextPartition = 'x-ms-continuation-NextPartitionKey';
var
xml: String;
xmlDoc: IXMLDocument;
Rows: TList<TAzureTableRow>;
TableNode: IXMLNode;
ContentNode: IXMLNode;
Row: TAzureTableRow;
ContinuationToken: TAzureRowContinuationToken;
begin
inherited;
FreeOnTerminate := True;
CoInitialize(nil);
Rows := nil;
xmlDoc := nil;
try
try
FTableService := TAzureTableService.Create(FConnectionInfo);
xml := FTableService.QueryEntities(FTableName, BuildFilterString);
xmlDoc := TXMLDocument.Create(nil);
xmlDoc.LoadFromXML(xml);
ContinuationToken.NextRowKey := FTableService.ResponseHeader[NextRow];
ContinuationToken.NextPartitionKey := FTableService.ResponseHeader[NextPartition];
ContinuationToken.IsValid := FTableService.ResponseHeaderExists[NextRow] or
FTableService.ResponseHeaderExists[NextPartition];
Rows := TList<TAzureTableRow>.Create;
TableNode := xmlDoc.DocumentElement.ChildNodes.FindNode(NODE_TABLE);
while (TableNode <> nil) and (TableNode.HasChildNodes) do
begin
if (TableNode.NodeName = NODE_TABLE) then
begin
ContentNode := TableNode.ChildNodes.FindNode(NODE_TABLE_CONTENT);
Row := GetRowFromConentNode(ContentNode);
if Row <> nil then
Rows.Add(Row);
end;
TableNode := TableNode.NextSibling;
end;
except
FreeAndNil(Rows);
end;
finally
CoUnInitialize();
TThread.Synchronize(nil, procedure begin FCallback(Rows, ContinuationToken); end);
end;
end;
{ TAzureTableColumn }
function TAzureTableColumn.Copy: TAzureTableColumn;
begin
if not Assigned(Self) then
Exit(nil);
Result := TAzureTableColumn.Create;
Result.Name := Name;
Result.Value := Value;
Result.DataType := DataType;
end;
constructor TAzureTableColumn.Create;
begin
DataType := azdtString;
end;
procedure TAzureTableColumn.SetDataType(Value: String);
begin
DataType := GetDataType(Value);
end;
{ TAzureRow }
constructor TAzureRow.Create(RowType: TRowType);
begin
FRowType := RowType;
end;
{ TRowCreator }
constructor TRowCreator.Create(TableName: String; Row: TAzureTemporaryTableRow;
ConnectionInfo: TAzureConnectionString; Callback: TRowCreatedCallback);
begin
inherited Create;
Assert(Row <> nil);
FTableName := TableName;
FRow := Row;
FConnectionInfo := ConnectionInfo;
FCallback := Callback;
end;
destructor TRowCreator.Destroy;
begin
FreeAndNil(FTableService);
inherited;
end;
procedure TRowCreator.Execute;
var
RowObj: TJSONObject;
AddedRow: TAzureTableRow;
Key: String;
Value: TAzureTableColumn;
xml: String;
xmlDoc: IXMLDocument;
ContentNode: IXMLNode;
IsNew: Boolean;
begin
inherited;
FreeOnTerminate := True;
AddedRow := nil;
IsNew := FRow.IsNewRow;
try
RowObj := TJSONObject.Create;
RowObj.AddPair(XML_ROWKEY, TJSONString.Create(FRow.RowKey.Value));
RowObj.AddPair(XML_PARTITION, TJSONString.Create(FRow.PartitionKey.Value));
for Key in FRow.Columns.Keys do
begin
Value := FRow.GetColumn(Key);
if Value.DataType = azdtString then
RowObj.AddPair(Key, TJSONString.Create(Value.Value))
else
RowObj.AddPair(Key, TJSONArray.Create(Value.Value, GetDataType(Value.DataType)));
end;
FTableService := TAzureTableService.Create(FConnectionInfo);
try
if FRow.IsNewRow then
begin
try
CoInitialize(nil);
xml := FTableService.InsertEntity(FTableName, RowObj);
xmlDoc := TXMLDocument.Create(nil);
xmlDoc.LoadFromXML(xml);
ContentNode := xmlDoc.DocumentElement.ChildNodes.FindNode(NODE_TABLE_CONTENT);
AddedRow := GetRowFromConentNode(ContentNode);
finally
CoUninitialize;
end;
end
else if FTableService.UpdateEntity(FTableName, RowObj) then
begin
AddedRow := FRow.Commit;
end;
except
FreeAndNil(AddedRow);
end;
finally
FreeAndNil(RowObj);
FreeAndNil(FRow);
TThread.Synchronize(nil, procedure begin FCallback(AddedRow, IsNew); end);
end;
end;
{ TRowDeletor }
constructor TRowDeletor.Create(TableName: String; Row: TAzureTableRow; ConnectionInfo: TAzureConnectionString;
Callback: TRowDeletedCallback);
begin
inherited Create;
Assert(Row <> nil);
FTableName := TableName;
FRow := Row;
FConnectionInfo := ConnectionInfo;
FCallback := Callback;
end;
destructor TRowDeletor.Destroy;
begin
FreeAndNil(FTableService);
inherited;
end;
procedure TRowDeletor.Execute;
var
Success: Boolean;
begin
inherited;
FreeOnTerminate := True;
Success := False;
try
FTableService := TAzureTableService.Create(FConnectionInfo);
try
Success := FTableService.DeleteEntity(FTableName, FRow.PartitionKey.Value, FRow.RowKey.Value);
except
Success := False;
end;
finally
TThread.Synchronize(nil, procedure begin FCallback(FRow, Success); end);
end;
end;
{ TBatchRowCreator }
constructor TBatchRowCreator.Create(TableName: String; Rows: TJSONArray; ConnectionInfo: TAzureConnectionString;
Callback: TBatchRowCreatedCallback);
begin
inherited Create;
Assert(Rows <> nil);
FTableName := TableName;
FRows := Rows;
FConnectionInfo := ConnectionInfo;
FCallback := Callback;
end;
destructor TBatchRowCreator.Destroy;
begin
FreeAndNil(FTableService);
inherited;
end;
function TBatchRowCreator.CreateRow(Row: TJSONObject): Boolean;
var
RowKey: String;
PartitionKey: String;
Pair: TJSONPair;
begin
if Row = nil then
Exit(False);
Pair := Row.Get('RowKey');
//get RowKey and PartitionKey, which are required Entity properties
if Pair = nil then
Exit(False)
else
RowKey := Pair.Value;
Pair := Row.Get('PartitionKey');
if Pair = nil then
Exit(False)
else
PartitionKey := Pair.Value;
Result := True;
try
FTableService.InsertEntity(FTableName, Row);
except
Result := False;
end;
end;
procedure TBatchRowCreator.Execute;
var
Aux: TJSONValue;
RowObj: TJSONObject;
I: Integer;
Success: Boolean;
begin
inherited;
FreeOnTerminate := True;
Success := True;
try
FTableService := TAzureTableService.Create(FConnectionInfo);
for I := 0 to FRows.Size - 1 do
begin
Aux := FRows.Get(I);
if Aux is TJSONObject then
begin
RowObj := TJSONObject(Aux);
try
Success := CreateRow(RowObj) and Success;
except
Success := False;
end;
end;
end;
finally
FreeAndNil(FRows);
TThread.Synchronize(nil, procedure begin FCallback(Success); end);
end;
end;
{ TAzureTemporaryTableRow }
constructor TAzureTemporaryTableRow.Create(RowKey, PartitionKey: String);
begin
Inherited Create;
FNewRow := True;
FWrapped := TAzureTableRow.Create;
FRowKey.Value := RowKey;
FPartitionKey.Value := PartitionKey;
end;
constructor TAzureTemporaryTableRow.Create(Wrapped: TAzureTableRow);
var
Key: String;
Value: TAzureTableColumn;
begin
Inherited Create;
FNewRow := False;
FWrapped := Wrapped;
if Wrapped <> nil then
begin
FRowKey.Value := Wrapped.RowKey.Value;
FPartitionKey.Value := Wrapped.PartitionKey.Value;
for Key in Wrapped.Columns.Keys do
begin
Value := Wrapped.GetColumn(Key);
SetColumn(Key, Value.Copy);
end;
end;
end;
destructor TAzureTemporaryTableRow.Destroy;
begin
if IsNewRow then
FreeAndNil(FWrapped);
inherited;
end;
function TAzureTemporaryTableRow.GetID: String;
begin
if IsNewRow then
Result := SNewEntityTitle
else
Result := Inherited GetID;
end;
function TAzureTemporaryTableRow.Commit: TAzureTableRow;
var
Key: String;
Value: TAzureTableColumn;
begin
if FWrapped = nil then
Exit(nil);
if not IsNewRow then
FWrapped.ClearColumns;
FWrapped.RowKey.Value := RowKey.Value;
FWrapped.PartitionKey.Value := PartitionKey.Value;
for Key in Columns.Keys do
begin
Value := GetColumn(Key);
FWrapped.SetColumn(Key, Value.Copy);
end;
Result := FWrapped;
end;
end.
|
unit Unit1;
interface
uses
System.SysUtils, System.Classes, System.Math,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.StdCtrls,
Vcl.ComCtrls, Vcl.ExtCtrls,
//GLScene
GLObjects, GLGraph, GLScene, GLVectorGeometry, GLVectorTypes,
GLWin32Viewer, GLCrossPlatform, GLCoordinates, GLBaseClasses;
type
TForm1 = class(TForm)
GLScene1: TGLScene;
GLSceneViewer1: TGLSceneViewer;
GLCamera1: TGLCamera;
GLLightSource1: TGLLightSource;
HeightField1: TGLHeightField;
YZGrid: TGLXYZGrid;
XZGrid: TGLXYZGrid;
XYGrid: TGLXYZGrid;
Panel1: TPanel;
CBCentered: TCheckBox;
Label1: TLabel;
TBXYPosition: TTrackBar;
TBYZPosition: TTrackBar;
TBXZPosition: TTrackBar;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
procedure GLSceneViewer1MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
procedure CBCenteredClick(Sender: TObject);
procedure TBXYPositionChange(Sender: TObject);
procedure TBYZPositionChange(Sender: TObject);
procedure TBXZPositionChange(Sender: TObject);
procedure FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
procedure HeightField1GetHeight(const x, y: Single; var z: Single;
var Color: TVector4f; var TexPoint: TTexPoint);
private
{ Private declarations }
public
{ Public declarations }
mx, my : Integer;
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.HeightField1GetHeight(const x, y: Single; var z: Single;
var color: TVector4f; var texPoint: TTexPoint);
begin
z:=VectorNorm(x, y);
z:=cos(z*12)/(2*(z*6.28+1));
end;
procedure TForm1.CBCenteredClick(Sender: TObject);
begin
if CBCentered.Checked then begin
XZGrid.YSamplingScale.Origin:=0;
YZGrid.XSamplingScale.Origin:=0;
XYGrid.ZSamplingScale.Origin:=0;
end else begin
XZGrid.YSamplingScale.Origin:=-1;
YZGrid.XSamplingScale.Origin:=-1;
XYGrid.ZSamplingScale.Origin:=-1;
end;
end;
procedure TForm1.TBXYPositionChange(Sender: TObject);
begin
XYGrid.ZSamplingScale.Origin:=-(TBXYPosition.Position/10);
end;
procedure TForm1.TBYZPositionChange(Sender: TObject);
begin
YZGrid.XSamplingScale.Origin:=-(TBYZPosition.Position/10);
end;
procedure TForm1.TBXZPositionChange(Sender: TObject);
begin
XZGrid.YSamplingScale.Origin:=-(TBXZPosition.Position/10);
end;
// following code takes care of camera movement, see camera & movement demos
// for explanations and more samples
procedure TForm1.GLSceneViewer1MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
mx:=X; my:=Y;
end;
procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
begin
if Shift<>[] then begin
GLCamera1.MoveAroundTarget(my-y, mx-x);
mx:=x; my:=y;
end;
end;
procedure TForm1.FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
begin
GLCamera1 := GLSceneViewer1.Camera;
// Note that 1 wheel-step induces a WheelDelta of 120,
// this code adjusts the distance to target with a 10% per wheel-step ratio
GLCamera1.AdjustDistanceToTarget(Power(1.1, WheelDelta / 120));
end;
end.
|
unit StreamingUnit;
interface
uses
System.Classes, System.SysUtils, System.Generics.Collections;
type
TNewUnknownComponentEvent = procedure(const AClassName: string; var AComponent: TComponent) of object;
TUnknownClassEvent = procedure(const AClassName: string; out AComponentClass: TComponentClass) of object;
TPreviewReader = class(TReader)
private
FOnNewUnknownComponent: TNewUnknownComponentEvent;
FOnUnknownClass: TUnknownClassEvent;
FClassName: string;
procedure FindCompClass(Reader: TReader; const ClassName: string; var ComponentClass: TComponentClass);
procedure DoCreateComponent(Reader: TReader; ComponentClass: TComponentClass; var Component: TComponent);
procedure DoError(Reader: TReader; const Message: string; var Handled: Boolean);
procedure SetOnUnknownClass(const Value: TUnknownClassEvent);
procedure SetOnNewUnknownComponent(const Value: TNewUnknownComponentEvent);
protected
function FindMethodInstance(Root: TComponent; const MethodName: string): TMethod; override;
public
property OnNewUnknownComponent: TNewUnknownComponentEvent read FOnNewUnknownComponent write SetOnNewUnknownComponent;
property OnUnknownClass: TUnknownClassEvent read FOnUnknownClass write SetOnUnknownClass;
constructor Create(Stream: TStream; BufSize: Integer);
end;
implementation
{ TPreviewReader }
constructor TPreviewReader.Create(Stream: TStream; BufSize: Integer);
begin
inherited Create(Stream, BufSize);
FClassName := string.Empty;
FOnUnknownClass := nil;
FOnNewUnknownComponent := nil;
OnFindComponentClass := FindCompClass;
OnCreateComponent := DoCreateComponent;
OnError := DoError;
end;
procedure TPreviewReader.DoError(Reader: TReader; const Message: string; var Handled: Boolean);
begin
Handled := True;
end;
procedure TPreviewReader.FindCompClass(Reader: TReader; const ClassName: string; var ComponentClass: TComponentClass);
begin
if (ComponentClass = nil) and Assigned(FOnUnknownClass) then
begin
FOnUnknownClass(ClassName, ComponentClass);
FClassName := ClassName;
end;
end;
procedure TPreviewReader.DoCreateComponent(Reader: TReader; ComponentClass: TComponentClass; var Component: TComponent);
begin
if Assigned(FOnNewUnknownComponent) and not FClassName.IsEmpty then
begin
FOnNewUnknownComponent(FClassName, Component);
FClassName := string.Empty;
end;
end;
function TPreviewReader.FindMethodInstance(Root: TComponent; const MethodName: string): TMethod;
begin
Result.Data := nil;
Result.Code := nil;
end;
procedure TPreviewReader.SetOnNewUnknownComponent(const Value: TNewUnknownComponentEvent);
begin
FOnNewUnknownComponent := Value;
end;
procedure TPreviewReader.SetOnUnknownClass(const Value: TUnknownClassEvent);
begin
FOnUnknownClass := Value;
end;
end.
|
{------------------------------------------------------------------------------
This file is part of the MotifMASTER project. This software is
distributed under GPL (see gpl.txt for details).
This software is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Copyright (C) 1999-2007 D.Morozov (dvmorozov@mail.ru)
------------------------------------------------------------------------------}
unit ComponentList;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, CBRCComponent, Tools, SelfSaved, ClassInheritIDs;
type
ISelfChecked = interface
['{E7E7008A-EE1C-4828-B1D6-A53806820A66}']
procedure IsReady;
function MyNameIs: string;
procedure SetSelfCheckingMode(const AMode: LongInt);
function GetSelfCheckingMode: LongInt;
end;
const SelfCheckedGUID: TGUID = '{E7E7008A-EE1C-4828-B1D6-A53806820A66}';
type
EComponentList = class(Exception);
TComponentList = class(TCBRCComponent, ISelfChecked)
protected
List: TList;
State: LongInt;
function GetCount: Integer;
function GetItem(index: Integer): TComponent;
function GetCapacity: Integer;
procedure SetItem(index: Integer; Item: TComponent);
procedure SetCapacity(ACapacity: Integer);
procedure LinkItemWithList(const Item: TComponent); virtual;
function GetSelfCheckingMode: LongInt; virtual; abstract;
procedure SetSelfCheckingMode(const AMode: LongInt); virtual; abstract;
class function GetPropHeaderRec: TPropHeaderRec; override;
class procedure ReadProperties(
const Reader: TReader;
const PropHeaderRec: TPropHeaderRec;
const AnObject: TSelfSavedComponent
); override;
class procedure WriteProperties(
const Writer: TWriter;
const AnObject: TSelfSavedComponent
); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure IsReady; virtual;
function MyNameIs: string; virtual;
procedure SetCheckingModeInItems(const AMode: LongInt);
procedure SendErrorMessage(
const ExceptionMsg, ObjectName: string;
const ItemNumber: LongInt); virtual;
procedure Sort(Compare: TListSortCompare);
procedure Pack;
function GetState: LongInt;
procedure SetState(AState: LongInt);
procedure ActionAfterReading; virtual;
procedure LinkAllItemsWithList;
procedure Clear;
procedure ClearAll;
function Add(Item: TComponent): Integer; virtual;
procedure Delete(Index: Integer); virtual;
procedure Insert(Index: Integer; Item: TComponent); virtual;
function Remove(Item: Pointer): Integer;
function IndexOf(Item: Pointer): Integer;
property Items[index: Integer]: TComponent read GetItem write SetItem;
property Capacity: Integer read GetCapacity write SetCapacity;
property Count: Integer read GetCount;
end;
const
cfActive: LongInt = 1;
cfPassive: LongInt = 2;
type
TSelfCleanList = class(TList)
public
procedure ClearAll; virtual;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Common', [TComponentList]);
end;
constructor TComponentList.Create;
begin
inherited Create(AOwner);
List := TList.Create;
SetState(cfActive);
end;
destructor TComponentList.Destroy;
begin
Clear;
UtilizeObject(List);
inherited Destroy;
end;
procedure TComponentList.Clear;
begin
if State = cfActive then ClearAll;
List.Clear;
end;
function TComponentList.GetCount;
begin
GetCount := List.Count;
end;
function TComponentList.GetItem;
begin
Result := List.Items[Index];
end;
procedure TComponentList.SetItem;
begin
List.Items[Index] := Item;
end;
function TComponentList.GetCapacity: Integer;
begin
GetCapacity := List.Capacity
end;
procedure TComponentList.SetCapacity(ACapacity: Integer);
begin
List.Capacity := ACapacity;
end;
procedure TComponentList.ActionAfterReading;
begin
LinkAllItemsWithList;
end;
procedure TComponentList.LinkAllItemsWithList;
var i: LongInt;
TC: TComponent;
begin
for i := 0 to Count - 1 do
begin
TC := Items[i];
LinkItemWithList(TC);
end;
end;
function TComponentList.Add;
begin
Add := List.Add(Item);
LinkItemWithList(Item);
end;
procedure TComponentList.Sort(Compare: TListSortCompare);
begin
List.Sort(Compare);
end;
procedure TComponentList.Delete(Index: Integer);
var TC: TComponent;
begin
if State = cfActive then
begin
TC := Items[Index];
UtilizeObject(TC);
end;
List.Delete(Index);
end;
function TComponentList.Remove(Item: Pointer): Integer;
begin
Result := IndexOf(Item);
Delete(Result);
end;
procedure TComponentList.ClearAll;
begin
while Count <> 0 do Delete(0);
end;
function TComponentList.IndexOf(Item: Pointer): Integer;
begin
Result := List.IndexOf(Item);
end;
procedure TComponentList.SetState;
begin
State := AState;
end;
function TComponentList.GetState: LongInt;
begin
Result := State;
end;
procedure TComponentList.Insert(Index: Integer; Item: TComponent);
begin
List.Insert(Index, Item);
LinkItemWithList(Item);
end;
procedure TComponentList.Pack;
begin
List.Pack;
end;
procedure TSelfCleanList.ClearAll;
var i: LongInt;
Item: Pointer;
begin
for i := 0 to Count - 1 do
begin
Item := Items[i];
if Assigned(Item) then
with TObject(Item) do try
UtilizeObject(TObject(Item));
Items[i] := nil;
except Items[i] := nil end;
end;
Clear;
end;
procedure TComponentList.LinkItemWithList(const Item: TComponent);
begin
end;
procedure TComponentList.IsReady;
var i: LongInt;
ISC: ISelfChecked;
begin
try
for i := 0 to Count - 1 do
if Items[i].GetInterface(SelfCheckedGUID, ISC) then ISC.IsReady;
except
on E: Exception do SendErrorMessage(E.Message, ISC.MyNameIs, i);
end;
end;
procedure TComponentList.SetCheckingModeInItems(const AMode: LongInt);
var i: LongInt;
ISC: ISelfChecked;
begin
for i := 0 to Count - 1 do
if Items[i].GetInterface(SelfCheckedGUID, ISC) then
ISC.SetSelfCheckingMode(AMode);
end;
procedure TComponentList.SendErrorMessage(
const ExceptionMsg, ObjectName: string;
const ItemNumber: LongInt);
var Str: string;
begin
Str := ExceptionMsg + ' in ' + ObjectName;
if MyNameIs <> '' then Str := Str + ' in ' + MyNameIs;
raise EComponentList.Create(Str);
end;
function TComponentList.MyNameIs: string;
begin
Result := '';
end;
class function TComponentList.GetPropHeaderRec: TPropHeaderRec;
begin
Result.ClassInheritID := CLClassInheritID;
Result.PropVersionNum := CLCurVerNum;
end;
class procedure TComponentList.ReadProperties(const Reader: TReader;
const PropHeaderRec: TPropHeaderRec;
const AnObject: TSelfSavedComponent);
var Comp: TComponent;
SaveReaderOwner: TComponent;
begin
with AnObject as TComponentList do
begin
Reader.ReadListBegin;
Clear;
SaveReaderOwner := Reader.Owner;
Reader.Owner := nil;
while not Reader.EndOfList do
begin
Comp := Reader.ReadComponent(nil);
Add(Comp);
end;
Reader.ReadListEnd;
Reader.Owner := SaveReaderOwner;
ActionAfterReading;
end;
end;
class procedure TComponentList.WriteProperties(const Writer: TWriter;
const AnObject: TSelfSavedComponent);
var i: Integer;
TempComp: TComponent;
begin
with AnObject as TComponentList do
begin
Writer.WriteListBegin;
for i := 0 to Count - 1 do
begin
TempComp := Items[i];
Writer.WriteComponent(TempComp);
end;
Writer.WriteListEnd;
end;
end;
initialization
RegisterClass(TComponentList);
end.
|
unit UnitWifiPasswords;
interface
uses
Windows, Classes, UnitFunctions;
function ListWifiPasswords: string;
implementation
const
CRYPT_STRING_HEX = 4;
CRYPTPROTECT_LOCAL_MACHINE = 4;
type
PDATA_BLOB = ^TDATA_BLOB;
TDATA_BLOB = record
cbData: DWORD;
pbData: PByte;
end;
PCRYPTPROTECT_PROMPTSTRUCT = ^TCRYPTPROTECT_PROMPTSTRUCT;
TCRYPTPROTECT_PROMPTSTRUCT = record
cbSize: DWORD;
dwPromptFlags: DWORD;
hwndApp: HWND;
szPrompt: PWChar;
end;
var
Size: DWORD = 1024;
function ParseConfig(T_, ForS, _T: string): string;
var
a, b: integer;
begin
Result := '';
if (T_ = '') or (ForS = '') or (_T = '') then Exit;
a := Pos(T_, ForS);
if a = 0 then Exit else a := a + Length(T_);
ForS := Copy(ForS, a, Length(ForS) - a + 1);
b := Pos(_T, ForS);
if b > 0 then Result := Copy(ForS, 1, b - 1);
end;
procedure FindXmlFiles(StartDir, FileMask: string; var FilesList: TStringList);
const
MASK_ALL_FILES = '*.*';
CHAR_POINT = '.';
var
sRec: TSearchRec;
DirList: TStringList;
IsFound: Boolean;
i: integer;
begin
if StartDir[length(StartDir)] <> '\' then StartDir := StartDir + '\';
IsFound := FindFirst(StartDir + FileMask, faAnyFile - faDirectory, sRec) = 0;
while IsFound do
begin
FilesList.Add(StartDir + sRec.Name);
IsFound := FindNext(sRec) = 0;
end;
FindClose(sRec);
DirList := TStringList.Create;
try
IsFound := FindFirst(StartDir + MASK_ALL_FILES, faAnyFile, sRec) = 0;
while IsFound do
begin
if ((sRec.Attr and faDirectory) <> 0) and (sRec.Name[1] <> CHAR_POINT) then
DirList.Add(StartDir + sRec.Name);
IsFound := FindNext(sRec) = 0;
end;
FindClose(sRec);
for i := 0 to DirList.Count - 1 do FindXmlFiles(DirList[i], FileMask, FilesList);
finally
DirList.Free;
end;
end;
function CryptUnprotectData(pDataIn: PDATA_BLOB; szDataDescr: PWChar;
pOptionalEntropy: PDATA_BLOB; pvReserved: Pointer;
pPromptStruct: PCRYPTPROTECT_PROMPTSTRUCT;
dwFlags: DWORD; pDataOut: PDATA_BLOB): BOOL; stdcall;
external 'Crypt32.dll';
function CryptStringToBinary(pszString: PwideChar; cchString: DWORD; dwFlags: DWORD;
pbBinary: pbyte; var pcbBinary: dword; pdwSkip: PDWORD;
pdwFlags: PDWORD): BOOL; stdcall;
external 'Crypt32.dll' name 'CryptStringToBinaryW';
function ListWifiPasswords: string;
var
ByteKey: array[0..1024] of PByte;
FilesList, Datas: TStringList;
TmpStr: WideString;
Src, Dst: TDATA_BLOB;
i:integer;
SSID, Auth, Encr, Keytype: string;
TmpBool: BOOL;
Password, ProfilesPath: string;
begin
Result := '';
try
begin
Datas := TStringList.Create;
FilesList := TStringList.Create;
ProfilesPath := RootDir + 'ProgramData\Microsoft\Wlansvc\Profiles\';
FindXmlFiles(ProfilesPath, '*.xml', FilesList);
for i := 0 to FilesList.Count - 1 do
begin
Datas.LoadFromFile(FilesList[i]);
SSID := (ParseConfig('<name>', Datas.Text, '</name>')); //essid
Auth := (ParseConfig('<authentication>', Datas.Text, '</authentication>'));//cifrado wep o wpa
Encr := (ParseConfig('<encryption>', Datas.Text, '</encryption>')); //encyption type
Keytype := (ParseConfig('<keyType>', Datas.Text, '</keyType>')); //key type
TmpStr := (ParseConfig('<keyMaterial>', Datas.Text, '</keyMaterial>')); //clave wireles
// convertir a byte array
TmpBool := CryptStringToBinary(PWideChar(TmpStr), Length(TmpStr),
CRYPT_STRING_HEX, @ByteKey, Size, nil, nil);
if TmpBool = true then
begin
try
Dst.cbData := Size;
Dst.pbdata := @ByteKey[0];
Password := TmpStr;
if CryptUnProtectData(@Dst, nil, nil, nil, nil, CRYPTPROTECT_LOCAL_MACHINE, @Src) then
Password := PAnsiChar(Src.pbData);
Result := Result + SSID + '|';
Result := Result + Auth + '|';
Result := Result + Encr + '|';
Result := Result + Keytype + '|';
Result := Result + Password + '|' + #13#10;
finally
end;
end;
end;
Datas.free;
FilesList.Free;
end;
except
end;
end;
end.
|
program table_formatter_1041571;
uses parser;
var
currentTable : nodePtr;
procedure printCell(currentCell : nodePtr);
var
content : string;
i : integer;
begin
content := currentCell^.content;
write(content);
for i := length(content) to cellWidth do write('_');
write(' | ');
end;
procedure printRow(currentRow : nodePtr);
var
nextCell : nodePtr;
widthCounter : integer;
begin
nextCell := currentRow^.child;
widthCounter := 0;
write('| ');
repeat
printCell(nextCell);
if (nextCell^.next <> nil) then
nextCell := nextCell^.next
else
nextCell := ConstructNode;
widthCounter := widthCounter + 1;
until (widthCounter = rowWidth);
writeln;
end;
procedure printTable(currentTable : nodePtr);
var
nextRow : nodePtr;
begin
nextRow := currentTable^.child;
repeat
printRow(nextRow);
nextRow := nextRow^.next;
until (nextRow = nil);
end;
begin
Parse;
printTable(parseTree.root^.child);
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ Dataset Designer Associate Attributes Dialog }
{ }
{ Copyright (c) 1997,99 Inprise Corporation }
{ }
{*******************************************************}
unit DSAttrA;
interface
uses Windows, Messages, SysUtils, Classes, Graphics, Forms, Controls,
StdCtrls, Buttons, ExtCtrls, DRIntf, LibHelp;
type
TAssociateAttributes = class(TForm)
OKBtn: TButton;
CancelBtn: TButton;
HelpBtn: TButton;
GroupBox1: TGroupBox;
AttributeNamesList: TListBox;
Edit: TEdit;
procedure OKBtnClick(Sender: TObject);
procedure CancelBtnClick(Sender: TObject);
procedure HelpBtnClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure EditChange(Sender: TObject);
procedure EditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure ListBoxClick(Sender: TObject);
procedure ListBoxDblClick(Sender: TObject);
private
procedure AddToList(const Value: string);
public
function Execute(var AttrID: TAttrID; var Continue: Boolean): Boolean;
end;
function GetAssociateAttributes(var AttrID: TAttrID; var Continue: Boolean): Boolean;
implementation
uses DsnDBCst;
{$R *.DFM}
function GetAssociateAttributes(var AttrID: TAttrID; var Continue: Boolean): Boolean;
var
AssociateAttributes: TAssociateAttributes;
begin
AssociateAttributes := TAssociateAttributes.Create(Application);
try
Result := AssociateAttributes.Execute(AttrID, Continue);
finally
AssociateAttributes.Free;
end;
end;
procedure TAssociateAttributes.OKBtnClick(Sender: TObject);
begin
ModalResult := mrOK;
end;
procedure TAssociateAttributes.CancelBtnClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TAssociateAttributes.AddToList(const Value: string);
begin
AttributeNamesList.Items.Add(Value);
end;
procedure TAssociateAttributes.FormCreate(Sender: TObject);
begin
GetAttrNames(AddToList);
HelpContext := hcDAssociateAttributes;
if AttributeNamesList.Items.Count > 0 then
Edit.Text := AttributeNamesList.Items[0] else
raise Exception.CreateRes(@SDSNoAttrs);
end;
procedure TAssociateAttributes.EditChange(Sender: TObject);
var
I, L, C, Count: Integer;
S: string;
begin
Count := AttributeNamesList.Items.Count;
if Count > 0 then
begin
S := Edit.Text;
L := Length(S);
C := -1;
I := 0;
if L > 0 then
begin
while I < Count do
begin
C := AnsiCompareText(Copy(AttributeNamesList.Items[I], 1, L), S);
if C >= 0 then Break;
Inc(I);
end;
end;
if C = 0 then
begin
if AttributeNamesList.ItemIndex <> I then
begin
AttributeNamesList.ItemIndex := -1;
AttributeNamesList.TopIndex := I;
AttributeNamesList.ItemIndex := I;
end;
OKBtn.Enabled := True;
end else
begin
AttributeNamesList.ItemIndex := -1;
if L = 0 then AttributeNamesList.TopIndex := 0;
OKBtn.Enabled := False;
end;
end;
end;
procedure TAssociateAttributes.ListBoxClick(Sender: TObject);
begin
if AttributeNamesList.ItemIndex >= 0 then
begin
Edit.Text := AttributeNamesList.Items[AttributeNamesList.ItemIndex];
Edit.SelectAll;
end;
end;
procedure TAssociateAttributes.ListBoxDblClick(Sender: TObject);
begin
if OKBtn.Enabled then OKBtn.Click;
end;
procedure TAssociateAttributes.EditKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if not (ssAlt in Shift) and (Key in [VK_UP, VK_DOWN, VK_PRIOR, VK_NEXT]) then
begin
SendMessage(AttributeNamesList.Handle, WM_KEYDOWN, Key, 0);
Key := 0;
end;
end;
function TAssociateAttributes.Execute(var AttrID: TAttrID; var Continue: Boolean): Boolean;
var
ModalResult: Integer;
begin
if not IsNullID(AttrID) then Edit.Text := GetAttrName(AttrID);
Edit.SelectAll;
AttributeNamesList.ItemIndex := AttributeNamesList.Items.IndexOf(Edit.Text);
OKBtn.Enabled := AttributeNamesList.ItemIndex >= 0;
ModalResult := ShowModal;
Result := ModalResult = mrOk;
Continue := ModalREsult <> mrCancel;
if Result and (AttributeNamesList.ItemIndex >= 0) then
AttrID := FindAttrID(AttributeNamesList.Items[AttributeNamesList.ItemIndex]);
end;
procedure TAssociateAttributes.HelpBtnClick(Sender: TObject);
begin
Application.HelpContext(HelpContext);
end;
end.
|
{
Create Temper Patterns
darkconsole https://darkconsole.tumblr.com
Given a list of COBJ forms create versions for Tempering the item.
}
Unit
UserScript;
Uses
'Dcc\Skyrim';
Var
TemperType: Integer; // 1 = workbench, 2 = grindstone.
Workbench: IInterface;
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
Procedure DccProcessThing(Form: IInterface);
Begin
AddMessage('[>>>] ' + EditorID(Form) + '');
End;
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
Function Initialize: Integer;
Var
InputResult: Boolean;
InputTemperType: Integer;
Begin
InputResult := InputQuery(
'Select Temper Type',
('1 = Workbench' + Skyrim.LineBreak + '2 = Grindstone' + Skyrim.LineBreak),
InputTemperType
);
// stop if no input.
If(InputResult = FALSE)
Then Result := 1;
// mark down what was selected in the global.
InputTemperType := Trim(InputTemperType);
TemperType := StrToIntDef(InputTemperType,1);
End;
Function Process(Form: IInterface): Integer;
Begin
If(CompareText('COBJ',Signature(Form)) <> 0)
Then Begin
AddMessage('[!!!] ' + EditorID(Form) + ' is not an constructable.');
End
Else Begin
DccProcessThing(Form);
End;
Result := 0;
End;
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
End.
|
unit ANovoConcorrente;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios,
PainelGradiente, Db, DBTables, Tabela, Localizacao, DBKeyViolation,
BotaoCadastro, StdCtrls, Buttons, ExtCtrls, Componentes1, DBCtrls, Mask,
DBClient;
type
TFNovoConcorrente = class(TFormularioPermissao)
PanelColor1: TPanelColor;
BotaoGravar1: TBotaoGravar;
BotaoCancelar1: TBotaoCancelar;
BFechar: TBitBtn;
ValidaGravacao1: TValidaGravacao;
Localiza: TConsultaPadrao;
DataConcorrentes: TDataSource;
PainelGradiente1: TPainelGradiente;
PanelColor2: TPanelColor;
Label13: TLabel;
Label14: TLabel;
Label15: TLabel;
BRua: TSpeedButton;
Label1: TLabel;
Label16: TLabel;
Label2: TLabel;
Label3: TLabel;
BCidade: TSpeedButton;
Label4: TLabel;
ENome: TDBEditColor;
EEndereco: TDBEditColor;
ENum: TDBEditColor;
ECidade: TDBEditLocaliza;
Label5: TLabel;
ETelefone: TDBEditPos2;
Label6: TLabel;
ENomProprietario: TDBEditColor;
EQtdFuncionarios: TDBEditColor;
Label7: TLabel;
Label8: TLabel;
EQtdTecnicos: TDBEditColor;
Label9: TLabel;
EQtdVendedores: TDBEditColor;
Label10: TLabel;
EFaturamento: TDBEditColor;
Label18: TLabel;
EMemo: TDBMemoColor;
EUf: TDBEditUF;
BUF: TSpeedButton;
EBairro: TDBEditColor;
ECep: TDBEditColor;
Concorrente: TSQL;
ConcorrenteCODCONCORRENTE: TFMTBCDField;
ConcorrenteNOMCONCORRENTE: TWideStringField;
ConcorrenteDESENDERECO: TWideStringField;
ConcorrenteNUMENDERECO: TFMTBCDField;
ConcorrenteDESBAIRRO: TWideStringField;
ConcorrenteNUMCEP: TWideStringField;
ConcorrenteDESCIDADE: TWideStringField;
ConcorrenteDESUF: TWideStringField;
ConcorrenteDESFONE1: TWideStringField;
ConcorrenteNOMPROPRIETARIO: TWideStringField;
ConcorrenteQTDFUNCIONARIO: TFMTBCDField;
ConcorrenteQTDTECNICO: TFMTBCDField;
ConcorrenteQTDVENDEDOR: TFMTBCDField;
ConcorrenteVALFATURAMENTOMENSAL: TFMTBCDField;
ConcorrenteDESOBSERVACAO: TWideStringField;
ECodigo: TDBKeyViolation;
ConcorrenteDATULTIMAALTERACAO: TSQLTimeStampField;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BFecharClick(Sender: TObject);
procedure BRuaClick(Sender: TObject);
procedure ECidadeCadastrar(Sender: TObject);
procedure ConcorrenteBeforePost(DataSet: TDataSet);
procedure ConcorrenteAfterInsert(DataSet: TDataSet);
procedure ConcorrenteAfterEdit(DataSet: TDataSet);
procedure ECidadeRetorno(Retorno1, Retorno2: String);
procedure ECodigoChange(Sender: TObject);
procedure ConcorrenteAfterPost(DataSet: TDataSet);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FNovoConcorrente: TFNovoConcorrente;
implementation
uses
APrincipal, AConsultaRuas, FunString, ACadCidades, AConcorrentes, UnSistema;
{$R *.DFM}
{ ****************** Na criação do Formulário ******************************** }
procedure TFNovoConcorrente.FormCreate(Sender: TObject);
begin
{ abre tabelas }
{ chamar a rotina de atualização de menus }
Concorrente.Open;
end;
{ ******************* Quando o formulario e fechado ************************** }
procedure TFNovoConcorrente.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{ fecha tabelas }
{ chamar a rotina de atualização de menus }
Concorrente.Close;
Action := CaFree;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Ações Diversas
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
procedure TFNovoConcorrente.BFecharClick(Sender: TObject);
begin
Self.Close;
end;
{******************************************************************************}
procedure TFNovoConcorrente.BRuaClick(Sender: TObject);
var
VpfCodCidade,
VpfCEP,
VpfRua,
VpfBairro,
VpfDesCidade: string;
begin
if Concorrente.State in [dsedit, dsInsert] then
begin
VpfCEP := SubstituiStr(VpfCEP,'-','');
FConsultaRuas := TFConsultaRuas.CriarSDI(Application, '', FPrincipal.VerificaPermisao('FConsultaRuas'));
if FConsultaRuas.BuscaEndereco(VpfCodCidade, VpfCEP,
VpfRua, VpfBairro, VpfDesCidade)
then
begin
ConcorrenteNUMCEP.AsString:= VpfCEP;
ConcorrenteDESCIDADE.AsString:= VpfDesCidade;
ConcorrenteDESBAIRRO.AsString:= VpfBairro;
ECidade.Atualiza;
end;
end;
end;
{******************************************************************************}
procedure TFNovoConcorrente.ECidadeCadastrar(Sender: TObject);
begin
FCidades := TFCidades.CriarSDI(Application, '', FPrincipal.VerificaPermisao('FCidades'));
FCidades.ShowModal;
end;
{******************************************************************************}
procedure TFNovoConcorrente.ConcorrenteBeforePost(DataSet: TDataSet);
begin
if Concorrente.State = dsInsert then
ECodigo.VerificaCodigoUtilizado;
ConcorrenteDATULTIMAALTERACAO.AsDateTime := Sistema.RDataServidor;
end;
{******************************************************************************}
procedure TFNovoConcorrente.ConcorrenteAfterInsert(DataSet: TDataSet);
begin
ECodigo.ProximoCodigo;
ECodigo.ReadOnly:= False;
end;
procedure TFNovoConcorrente.ConcorrenteAfterPost(DataSet: TDataSet);
begin
Sistema.MarcaTabelaParaImportar('CONCORRENTE');
end;
{******************************************************************************}
procedure TFNovoConcorrente.ConcorrenteAfterEdit(DataSet: TDataSet);
begin
ECodigo.ReadOnly:= True;
end;
{******************************************************************************}
procedure TFNovoConcorrente.ECidadeRetorno(Retorno1, Retorno2: String);
begin
if Concorrente.State in [dsinsert,dsedit] then
ConcorrenteDESUF.AsString := retorno2;
end;
procedure TFNovoConcorrente.ECodigoChange(Sender: TObject);
begin
if Concorrente.state in [dsinsert,dsedit] then
ValidaGravacao1.execute;
end;
Initialization
{ *************** Registra a classe para evitar duplicidade ****************** }
RegisterClasses([TFNovoConcorrente]);
end.
|
unit Vigilante.Infra.Build.Builder.Impl;
interface
uses
System.JSON, Vigilante.Build.Model, Vigilante.Infra.Build.Builder;
type
TBuildBuilder = class(TInterfacedObject, IBuildBuilder)
private
FJSON: TJSONObject;
public
constructor Create(const AJSON: TJSONObject);
function PegarBuild: IBuildModel;
end;
implementation
uses
ContainerDI, Vigilante.Build.Model.Impl, Vigilante.Infra.Build.JSONDataAdapter;
constructor TBuildBuilder.Create(const AJSON: TJSONObject);
begin
FJSON := AJSON;
end;
function TBuildBuilder.PegarBuild: IBuildModel;
var
_adapter: IBuildJSONDataAdapter;
begin
_adapter := CDI.Resolve<IBuildJSONDataAdapter>([FJSON]);
Result := TBuildModel.Create(_adapter.Nome, _adapter.URL, _adapter.Situacao,
_adapter.Building, _adapter.BuildAtual, _adapter.UltimoBuildFalha,
_adapter.UltimoBuildSucesso, _adapter.URLUltimoBuild);
end;
end.
|
unit BF_OMAC;
(*************************************************************************
DESCRIPTION : Blowfish OMAC1/2 routines
REQUIREMENTS : TP5-7, D1-D7/D9-D10/D12, FPC, VP
EXTERNAL DATA : ---
MEMORY USAGE : ---
DISPLAY MODE : ---
REFERENCES : [1] OMAC page: http://www.nuee.nagoya-u.ac.jp/labs/tiwata/omac/omac.html
[2] T.Iwata and K.Kurosawa. OMAC: One-Key CBC MAC - Addendum
(http://csrc.nist.gov/CryptoToolkit/modes/proposedmodes/omac/omac-ad.pdf)
Version Date Author Modification
------- -------- ------- ------------------------------------------
0.10 16.06.07 W.Ehrhardt Initial version analog AES_OMAC
0.11 23.11.08 we Uses BTypes
0.12 05.08.10 we BF_OMAC_Update with ILen: longint, XL Version with $define OLD_XL_Version
**************************************************************************)
(*-------------------------------------------------------------------------
(C) Copyright 2007-2010 Wolfgang Ehrhardt
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from
the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software in
a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
----------------------------------------------------------------------------*)
{$i STD.INC}
{.$define OLD_XL_Version}
interface
uses
BTypes, BF_Base;
function BF_OMAC_Init({$ifdef CONST} const Key {$else} var Key {$endif};
KeyBytes: word; var ctx: TBFContext): integer;
{-OMAC init: BF key expansion, error if inv. key size}
{$ifdef DLL} stdcall; {$endif}
function BF_OMAC_Update(data: pointer; ILen: longint; var ctx: TBFContext): integer;
{-OMAC data input, may be called more than once}
{$ifdef DLL} stdcall; {$endif}
procedure BF_OMAC_Final(var tag: TBFBlock; var ctx: TBFContext);
{-end data input, calculate OMAC=OMAC1 tag}
{$ifdef DLL} stdcall; {$endif}
procedure BF_OMAC1_Final(var tag: TBFBlock; var ctx: TBFContext);
{-end data input, calculate OMAC1 tag}
{$ifdef DLL} stdcall; {$endif}
procedure BF_OMAC2_Final(var tag: TBFBlock; var ctx: TBFContext);
{-end data input, calculate OMAC2 tag}
{$ifdef DLL} stdcall; {$endif}
{$ifdef OLD_XL_Version}
{---------------------------------------------------------------------------}
function BF_OMAC_UpdateXL(data: pointer; ILen: longint; var ctx: TBFContext): integer;
{-OMAC data input, may be called more than once}
{$endif}
implementation
{---------------------------------------------------------------------------}
function BF_OMAC_Init({$ifdef CONST} const Key {$else} var Key {$endif};
KeyBytes: word; var ctx: TBFContext): integer;
{-OMAC init: BF key expansion, error if inv. key size}
begin
{BF key expansion, error if inv. key size}
{IV = Y[0] = [0]}
BF_OMAC_Init := BF_Init(Key, KeyBytes, ctx);
if BF_GetFastInit then fillchar(ctx.IV,sizeof(ctx.IV),0);
end;
{---------------------------------------------------------------------------}
function BF_OMAC_Update(data: pointer; ILen: longint; var ctx: TBFContext): integer;
{-OMAC data input, may be called more than once}
var
n: word;
begin
if (data=nil) and (ILen<>0) then begin
BF_OMAC_Update := BF_Err_NIL_Pointer;
exit;
end;
{$ifdef BIT16}
if (ofs(data^)+ILen>$FFFF) then begin
BF_OMAC_Update:= BF_Err_Invalid_16Bit_Length;
exit;
end;
{$endif}
BF_OMAC_Update := 0;
while ILen>0 do with ctx do begin
if bLen>=BFBLKSIZE then begin
{process full buffer}
{X[i] := M[i] xor Y[i-1]}
BF_XorBlock(buf, IV, buf);
BF_Encrypt(ctx, buf, IV);
bLen := 0;
while ILen>BFBLKSIZE do with ctx do begin
{continue with full blocks if more }
{than one block remains unprocessed}
{X[i] := M[i] xor Y[i-1]}
BF_XorBlock(PBFBlock(data)^, IV, buf);
{Y[i] := EK[X[i]}
BF_Encrypt(ctx, buf, IV);
inc(Ptr2Inc(data), BFBLKSIZE);
dec(ILen, BFBLKSIZE); {ILen>0!}
end;
end;
n := BFBLKSIZE-bLen; if ILen<n then n:=ILen;
{n>0 because ILen>0 and bLen<BFBLKSIZE}
move(data^, buf[bLen], n);
inc(bLen,n);
inc(Ptr2Inc(data),n);
dec(ILen,n);
end;
end;
{$ifdef OLD_XL_Version}
{---------------------------------------------------------------------------}
function BF_OMAC_UpdateXL(data: pointer; ILen: longint; var ctx: TBFContext): integer;
{-OMAC data input, may be called more than once}
begin
BF_OMAC_UpdateXL := BF_OMAC_Update(data, ILen, ctx);
end;
{$endif}
{---------------------------------------------------------------------------}
procedure BF_OMACx_Final(OMAC2: boolean; var tag: TBFBlock; var ctx: TBFContext);
{-end data input, calculate OMAC tag}
{Turn off range checking for byte shifts}
{$ifopt R+} {$define SetRPlus} {$else} {$undef SetRPlus} {$endif}
{$R-}
{---------------------------------------}
procedure mul_u(var L: TBFBlock);
{-Calculate L.u}
const
masks: array[0..1] of byte = (0,$1B);
var
i: integer;
mask: byte;
begin
mask := masks[L[0] shr 7];
for i:=0 to BFBLKSIZE-2 do L[i] := (L[i] shl 1) or (L[i+1] shr 7);
L[BFBLKSIZE-1] := (L[BFBLKSIZE-1] shl 1) xor mask;
end;
{---------------------------------------}
procedure div_u(var L: TBFBlock);
{-Calculate L.u^-1}
const
mask1: array[0..1] of byte = (0, $0D);
mask2: array[0..1] of byte = (0, $80);
var
i,j: integer;
begin
j := L[BFBLKSIZE-1] and 1;
for i:=BFBLKSIZE-1 downto 1 do L[i] := (L[i] shr 1) or (L[i-1] shl 7);
L[0] := (L[0] shr 1) xor mask2[j];
L[BFBLKSIZE-1] := L[BFBLKSIZE-1] xor mask1[j];
end;
{$ifdef SetRPlus}
{$R+}
{$endif}
begin
with ctx do begin
fillchar(tag, sizeof(tag), 0);
{L := EK(0)}
BF_Encrypt(ctx, tag, tag);
if blen>=BFBLKSIZE then begin
{Complete last block, no padding and use L.u}
mul_u(tag);
end
else begin
{Incomplete last block, pad buf and use L.u^2 or L.u^-1}
buf[bLen] := $80;
inc(bLen);
while blen<BFBLKSIZE do begin
buf[bLen] := 0;
inc(bLen);
end;
if OMAC2 then begin
{calc L.u^-1}
div_u(tag);
end
else begin
{calc L.u^2}
mul_u(tag);
mul_u(tag);
end;
end;
{X[m] := pad(M[n]) xor Y[m-1]}
BF_XorBlock(buf, IV, buf);
{X[m] := X[m] xor L.u^e, e=-1,1,2}
BF_XorBlock(buf, tag, buf);
{T := EK(X[m])}
BF_Encrypt(ctx, buf, tag);
end;
end;
{---------------------------------------------------------------------------}
procedure BF_OMAC_Final(var tag: TBFBlock; var ctx: TBFContext);
{-end data input, calculate OMAC=OMAC1 tag}
begin
BF_OMACx_Final(false, tag, ctx);
end;
{---------------------------------------------------------------------------}
procedure BF_OMAC1_Final(var tag: TBFBlock; var ctx: TBFContext);
{-end data input, calculate OMAC1 tag}
begin
BF_OMACx_Final(false, tag, ctx);
end;
{---------------------------------------------------------------------------}
procedure BF_OMAC2_Final(var tag: TBFBlock; var ctx: TBFContext);
{-end data input, calculate OMAC2 tag}
begin
BF_OMACx_Final(true, tag, ctx);
end;
end.
|
unit esExceptions;
interface
{$I Compilers.inc}
Uses
SysUtils, Classes;
type
EsException = class(Exception)
{{В класс встроена поддержка Inner Exception, более простая чем в Delphi.
Работает начиная с XE4
Для того, чтобы обернуть исключение, надо писать:
try
DoSomething();
except
on E: Exception1 do
raise EsException.Create(E, 'Более высокоуровневое описание');
end;
}
public
constructor Create(aInnerException: Exception);overload;//Если к тексту внутреннего исключения добавить нечего, использовать этот конструктор
constructor Create(aInnerException: Exception; const msg: string);overload;
constructor CreateFmt(aInnerException: Exception; const msgFormat: string; const args: array of const);overload;
{$IFDEF COMPILER_18_UP}
function Message(): string;reintroduce;//переопределено для того, чтобы при обертывании исключения без добавления текста by Create(aInnerException: Exception)
//можно было бы проще достучаться до текста вложенного исключения
{$ENDIF}
end;
{{Исключение с подробностями.
Подробности могут состоять из длинного текста}
ExceptionWithDetails = class(EsException)
private
FDetails: TStrings;
function GetDetailsAsText: string;
function GetDetails: TStrings;
protected
property Details: TStrings read GetDetails;
public
constructor CreateWithDetails(aInnerException: Exception; const aDetails, aMessage: string; const Args: array of const);overload;
constructor CreateWithDetails(const aDetails, aMessage: string; const Args: array of const);overload;
constructor CreateWithDetails(const aMessage: string; const Args: array of const; const details: TStrings);overload;
constructor CreateWithDetails(const aMessage: string; const details: TStrings);overload;
procedure AfterConstruction();override;
destructor Destroy;override;
function AddDetail(const detail: string): ExceptionWithDetails;overload;
function AddDetail(const msgFormat: string; const Args: array of const): ExceptionWithDetails;overload;
procedure AddDetails(source: TStrings);
procedure StoreDetailsTo(dest: TStrings);
property DetailsAsText: string read GetDetailsAsText;
End;
{{Ошибка в коде программы. Такие ошибки в идеале не должны возникать.
Дальнейшее выполнение данной ветки кода выполнять бессмысленно - мы не знаем точной причины ошибки,
не понимаем как можно устранить.
См. также ECorrectException}
EInternalException = class(EsException);
{{Исключение, говорящее о внутренней ошибке в программе, допустим не передан требуемый параметр в процедуру.
См. EnsureNotNull}
ECheckException = class(EInternalException);
{{"Корректное" исключение.
Может возникать при штатном режиме работы программы.
Например, пользователь ввел недопустимое значение, или
нам не нравится ответ от счетчика и мы не можем его обработать.
Для каждого типа "корректных" ошибок лучше заводить свой подкласс -
это позволит писать осмысленные обработчики ошибок.
См. также EInternalException.
Для таких исключений лучше не показывать StackTrace - эти ошибки должны устраняться пользователем}
ECorrectException = class(ExceptionWithDetails);
{{Ошибка внешнего окружения. Например, в БД нет записей, которые необходимы для работы программы}
EnvironmentException = class(ExceptionWithDetails);
EUserInputException = class(ECorrectException);
{{Raises an ECheckException if obj is null, with given msg.
Если msg не содержит пробелов, подразумевается, что это имя параметра процедуры.
Сообщение об ошибке будет '"msg" is null'}
procedure EnsureNotNull(obj: TObject; const msg: string);overload;{$IFDEF COMPILER_18_UP}inline;{$ENDIF}
procedure EnsureNotNull(obj: IInterface; const msg: string);overload;{$IFDEF COMPILER_18_UP}inline;{$ENDIF}
procedure EnsureNotNull(obj: TObject; const msg: string; const Args: array of const);overload;
{{Raises an ECheckException if Trim(s) == '', with given msg.
Если msg не содержит пробелов, подразумевается, что это имя параметра процедуры.
Сообщение об ошибке будет '"msg" is empty'}
procedure EnsureNotEmpty(const s: string; const msg: string);overload;{$IFDEF COMPILER_18_UP}inline;{$ENDIF}
procedure EnsureNotEmpty(const s: string; const msg: string; const Args: array of const);overload;
{{Выбрасывает ECheckException if not condtion}
procedure mustBeTrue(condition: boolean; const msg: string);{$IFDEF COMPILER_18_UP}inline;{$ENDIF}
{{Выбрасывает ECheckException if not condtion}
procedure mustBeTrueFmt(condition: boolean; const msg: string; const Args: array of const);
implementation
{$IFDEF COMPILER_18_UP}
type
EsDummyException = class(Exception);//это на случай, если текущий Exception отличается от переданного в EsException в качестве InnerException
ExceptionHelper = class helper for Exception
procedure AssignInnerException(E: Exception);
end;
{$ENDIF}
procedure mustBeTrue(condition: boolean; const msg: string);
begin
if (not(condition)) then
raise ECheckException.Create(msg);
end;
procedure mustBeTrueFmt(condition: boolean; const msg: string; const Args: array of const);
begin
if (not(condition)) then
raise ECheckException.CreateFmt(msg, Args);
end;
procedure EnsureNotEmpty(const s: string; const msg: string);
begin
if Trim(s) = '' then
begin
if Pos(' ', msg) > 0 then
raise ECheckException.Create(msg);
raise ECheckException.CreateFmt('"%s" is empty', [msg]);
end;
end;
procedure EnsureNotEmpty(const s: string; const msg: string; const Args: array of const);
begin
if Trim(s) = '' then
raise ECheckException.CreateFmt(msg, Args);
end;
procedure EnsureNotNull(obj: TObject; const msg: string);
begin
if obj = nil then
begin
if Pos(' ', msg) > 0 then
raise ECheckException.Create(msg);
raise ECheckException.CreateFmt('"%s" is null', [msg]);
end;
end;
procedure EnsureNotNull(obj: IInterface; const msg: string);overload;
begin
if not Assigned(obj) then
begin
if Pos(' ', msg) > 0 then
raise ECheckException.Create(msg);
raise ECheckException.CreateFmt('"%s" is null', [msg]);
end;
end;
procedure EnsureNotNull(obj: TObject; const msg: string; const Args: array of const);
begin
if obj = nil then
raise ECheckException.CreateFmt(msg, Args);
end;
{ ExceptionWithDetails }
procedure ExceptionWithDetails.AfterConstruction;
begin
inherited;
GetDetails();//just create details if not created already
end;
constructor ExceptionWithDetails.CreateWithDetails(aInnerException: Exception; const aDetails, aMessage: string; const Args: array of const);
begin
inherited CreateFmt(aInnerException, aMessage, Args);
GetDetails.Add(aDetails);
end;
constructor ExceptionWithDetails.CreateWithDetails(const aMessage: string; const Args: array of const; const details: TStrings);
begin
inherited CreateFmt(aMessage, Args);
AddDetails(details);
end;
constructor ExceptionWithDetails.CreateWithDetails(const aMessage: string; const details: TStrings);
begin
inherited Create(aMessage);
AddDetails(details);
end;
constructor ExceptionWithDetails.CreateWithDetails(const aDetails, aMessage: string; const Args: array of const);
begin
inherited CreateFmt(aMessage, Args);
GetDetails.Add(aDetails);
end;
destructor ExceptionWithDetails.Destroy;
begin
FreeAndNil(FDetails);
inherited;
end;
function ExceptionWithDetails.GetDetails: TStrings;
begin
if FDetails = nil then
FDetails := TStringList.Create();
Result := FDetails;
end;
function ExceptionWithDetails.GetDetailsAsText: string;
begin
Result:= Details.Text;
end;
procedure ExceptionWithDetails.StoreDetailsTo(dest: TStrings);
begin
if Assigned(dest) then
dest.AddStrings(Details);
end;
function ExceptionWithDetails.AddDetail(const detail: string): ExceptionWithDetails;
begin
Details.Add(detail);
Result := Self;
end;
function ExceptionWithDetails.AddDetail(const msgFormat: string;
const Args: array of const): ExceptionWithDetails;
begin
Result := AddDetail(Format(msgFormat, Args));
end;
procedure ExceptionWithDetails.AddDetails(source: TStrings);
begin
if Assigned(source) then
Details.AddStrings(source);
end;
{ EsException }
constructor EsException.Create(aInnerException: Exception; const msg: string);
begin
inherited Create(msg);
{$IFDEF COMPILER_18_UP}
AssignInnerException(aInnerException);
{$ENDIF}
end;
constructor EsException.Create(aInnerException: Exception);
begin
inherited Create('');
{$IFDEF COMPILER_18_UP}
AssignInnerException(aInnerException);
{$ENDIF}
end;
constructor EsException.CreateFmt(aInnerException: Exception; const msgFormat: string; const args: array of const);
begin
inherited CreateFmt(msgFormat, args);
{$IFDEF COMPILER_18_UP}
AssignInnerException(aInnerException);
{$ENDIF}
end;
{$IFDEF COMPILER_18_UP}
function EsException.Message: string;
begin
Result := inherited Message;
if Result = '' then
if Assigned(InnerException) then
Result := InnerException.Message;
end;
{ ExceptionHelper }
procedure ExceptionHelper.AssignInnerException(E: Exception);
var
tmp: TObject;
begin
tmp := AcquireExceptionObject();
if (tmp = E) then
with Self do
FInnerException := E
else begin
ReleaseExceptionObject();
with Self do
FInnerException := EsDummyException.CreateFmt('%s: %s (%s)', [E.ClassName, E.Message, E.ToString]);
end;
end;
{$ENDIF}
end.
|
unit Un_Clientes;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, DBCtrls, Grids, DBGrids, DB, Buttons;
type
T_Clientes = class(TForm)
pnlClientes: TPanel;
dsClientes: TDataSource;
dbgClientes: TDBGrid;
dbnClientes: TDBNavigator;
gbCliente: TGroupBox;
edtNome: TLabeledEdit;
edtEndereco: TLabeledEdit;
edtBairro: TLabeledEdit;
edtCidade: TLabeledEdit;
edtCEP: TLabeledEdit;
edtFone1: TLabeledEdit;
edtFone2: TLabeledEdit;
edtFax: TLabeledEdit;
edtCelular: TLabeledEdit;
edtEmail: TLabeledEdit;
pnlCodCli: TPanel;
Label1: TLabel;
edtObs: TMemo;
btnSair: TBitBtn;
btnNova: TBitBtn;
btnAlterar: TBitBtn;
btnExcluir: TBitBtn;
sbSim: TSpeedButton;
sbNao: TSpeedButton;
procedure dsClientesDataChange(Sender: TObject; Field: TField);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure dbgClientesKeyPress(Sender: TObject; var Key: Char);
procedure btnNovaClick(Sender: TObject);
procedure btnAlterarClick(Sender: TObject);
procedure btnExcluirClick(Sender: TObject);
procedure sbNaoClick(Sender: TObject);
procedure sbSimClick(Sender: TObject);
procedure edtCEPExit(Sender: TObject);
procedure edtFone1Exit(Sender: TObject);
procedure edtCelularExit(Sender: TObject);
procedure edtFone2Exit(Sender: TObject);
procedure edtFaxExit(Sender: TObject);
procedure btnSairClick(Sender: TObject);
private { Private declarations }
cFlg, cBusca : String;
Procedure Controle( x : Boolean );
Procedure Dados( x : String );
public { Public declarations }
cPorta : String;
end;
var
_Clientes: T_Clientes;
implementation
uses Un_dm, Un_UDF;
{$R *.dfm}
procedure T_Clientes.FormCreate(Sender: TObject);
begin
cFlg := '';
cBusca := '';
cPorta := '';
pnlCodCli.Hint := 'Informação do Código e o'#13'Nº de serviços registrados para este.';
end;
procedure T_Clientes.FormShow(Sender: TObject);
begin
_dm.qr02.Close;
_dm.qr02.SQL.Text := 'select * from CLIENTES order by NomeCliente';
_dm.qr02.Open;
Controle( True );
dbgClientes.SetFocus;
end;
procedure T_Clientes.btnSairClick(Sender: TObject);
begin
Close;
end;
procedure T_Clientes.dsClientesDataChange(Sender: TObject; Field: TField);
begin
_dm.qr11.Close;
_dm.qr11.SQL.Text := 'select * from SERVICOS where CodCliente = ' + _dm.qr02.FieldByName( 'CodCliente' ).AsString + '';
_dm.qr11.Open;
pnlCodCli.Caption := 'Cod: ' + _dm.qr02.FieldByName( 'CodCliente' ).AsString + ' Serv: ' + IntToStr( _dm.qr11.RecordCount );
Dados( '' );
end;
procedure T_Clientes.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
Case Key Of
VK_ESCAPE :
Begin
If cFlg <> '' Then
Begin
_dm.qr02.Close;
_dm.qr02.Open;
cFlg := '';
Controle( True );
dbgClientes.SetFocus;
End
Else
Close;
End;
VK_RETURN :
Begin
Perform( WM_NEXTDLGCTL, 0, 0 );
Key := 0;
End;
End;
If ( Key = VK_END ) or ( Key = VK_HOME ) or
( Key = VK_LEFT ) or ( Key = VK_UP ) or ( Key = VK_RIGHT ) or ( Key = VK_DOWN ) Then
Begin
cBusca := '';
End;
end;
procedure T_Clientes.dbgClientesKeyPress(Sender: TObject; var Key: Char);
begin
If ( Key = #37 ) or ( Key = #38 ) or ( Key = #39 ) or ( Key = #40 ) Then
Begin
cBusca := '';
End;
If Key <> #8 Then
Begin
cBusca := cBusca + Key;
End
Else
Begin
cBusca := Copy( cBusca, 1, Length( cBusca ) - 1 );
End;
_dm.qr02.Locate( 'NomeCliente', cBusca, [loPartialKey, loCaseInsensitive] );
end;
procedure T_Clientes.Controle(x: Boolean);
begin
dbgClientes.Enabled := x;
btnNova.Enabled := x;
btnAlterar.Enabled := x;
btnExcluir.Enabled := x;
btnSair.Enabled := x;
sbSim.Visible := Not x;
sbNao.Visible := Not x;
gbCliente.Enabled := Not x;
end;
procedure T_Clientes.Dados(x: String);
begin
If x = 'N' Then
Begin
edtNome.Text := '';
edtEndereco.Text := '';
edtBairro.Text := '';
edtCidade.Text := '';
edtCEP.Text := '';
edtFone1.Text := '';
edtFone2.Text := '';
edtFax.Text := '';
edtCelular.Text := '';
edtEmail.Text := '';
edtObs.Lines.Clear;
edtObs.Text := '';
End
Else
Begin
edtNome.Text := ControlaCampoTexto( _dm.qr02.FieldByName( 'NomeCliente' ).AsString );
edtEndereco.Text := ControlaCampoTexto( _dm.qr02.FieldByName( 'Endereco' ).AsString );
edtBairro.Text := ControlaCampoTexto( _dm.qr02.FieldByName( 'Bairro' ).AsString );
edtCidade.Text := ControlaCampoTexto( _dm.qr02.FieldByName( 'Cidade' ).AsString );
edtCEP.Text := ControlaCampoTexto( _dm.qr02.FieldByName( 'CEP' ).AsString );
edtFone1.Text := ControlaCampoTexto( _dm.qr02.FieldByName( 'Fone1' ).AsString );
edtFone2.Text := ControlaCampoTexto( _dm.qr02.FieldByName( 'Fone2' ).AsString );
edtFax.Text := ControlaCampoTexto( _dm.qr02.FieldByName( 'Fax' ).AsString );
edtCelular.Text := ControlaCampoTexto( _dm.qr02.FieldByName( 'Celular' ).AsString );
edtEmail.Text := ControlaCampoTexto( _dm.qr02.FieldByName( 'E-mail' ).AsString );
edtObs.Text := ControlaCampoTexto( _dm.qr02.FieldByName( 'Obs' ).AsString );
end;
end;
procedure T_Clientes.btnNovaClick(Sender: TObject);
begin
cFlg := 'N';
cBusca := '';
Controle( False );
Dados( 'N' );
edtNome.SetFocus;
end;
procedure T_Clientes.btnAlterarClick(Sender: TObject);
begin
cFlg := 'A';
cBusca := '';
Controle( False );
Dados( '' );
edtNome.SetFocus;
end;
procedure T_Clientes.btnExcluirClick(Sender: TObject);
Var
lExc : Boolean;
begin
_dm.qr12.Close;
_dm.qr12.SQL.Text := 'select * from SERVICOS where CodCliente = ' + _dm.qr02.FieldByName( 'CodCliente' ).AsString + '';
_dm.qr12.Open;
If _dm.qr12.RecordCount > 0 Then
Begin
MessageDlg( 'Exclusão do Cliente não poderá ser processada, sem a'#13'exclusão dos serviços registrados.'#13''#13'Será aberto o modulo de exclusão de Serviços deste Cliente.', mtWarning, [ mbOk ], 0 );
If MessageDlg( 'ATENÇÃO:'#13''#13'Excluir TODOS os Serviços de [ ' + _dm.qr02.FieldByName( 'NomeCliente' ).AsString + ' ] ?', mtWarning, [ mbYes, mbNo ], 0 ) = mrYes Then
Begin
_dm.qr12.Close;
_dm.qr12.SQL.Text := 'delete from SERVICOS where CodCliente = ' + _dm.qr02.FieldByName( 'CodCliente' ).AsString + '';
_dm.qr12.ExecSQL;
lExc := True;
End
Else
Begin
lExc := False;
End;
End
Else
lExc := True;
If ( lExc ) And ( MessageDlg( 'Exclusão do Cliente ?'#13'' + _dm.qr02.FieldByName( 'NomeCliente' ).AsString, mtConfirmation, [ mbYes, mbNo ], 0 ) = mrYes ) Then
Begin
_dm.qr12.Close;
_dm.qr12.SQL.Text := 'delete from CLIENTES where CodCliente = ' + _dm.qr02.FieldByName( 'CodCliente' ).AsString + '';
_dm.qr12.ExecSQL;
End;
_dm.qr02.Close;
_dm.qr02.Open;
cBusca := '';
dbgClientes.SetFocus;
end;
procedure T_Clientes.edtCEPExit(Sender: TObject);
begin
If edtCEP.Text <> '' Then edtCEP.Text := FormataCEP( edtCEP.Text );
end;
procedure T_Clientes.edtFone1Exit(Sender: TObject);
begin
If edtFone1.Text <> '' Then edtFone1.Text := FormataFone( edtFone1.Text );
end;
procedure T_Clientes.edtFone2Exit(Sender: TObject);
begin
// If edtFone2.Text <> '' Then edtFone2.Text := FormataFone( edtFone2.Text );
end;
procedure T_Clientes.edtFaxExit(Sender: TObject);
begin
// If edtFax.Text <> '' Then edtFax.Text := FormataFone( edtFax.Text );
end;
procedure T_Clientes.edtCelularExit(Sender: TObject);
begin
If edtCelular.Text <> '' Then edtCelular.Text := FormataFone( edtCelular.Text );
end;
procedure T_Clientes.sbNaoClick(Sender: TObject);
begin
_dm.qr02.Close;
_dm.qr02.Open;
cFlg := '';
cBusca := '';
Controle( True );
dbgClientes.SetFocus;
end;
procedure T_Clientes.sbSimClick(Sender: TObject);
begin
If edtNome.Text = '' Then
Begin
edtNome.SetFocus;
Exit;
End;
edtEndereco.Text := ControlaCampoTexto( edtEndereco.Text );
edtBairro.Text := ControlaCampoTexto( edtBairro.Text );
edtCidade.Text := ControlaCampoTexto( edtCidade.Text );
If edtCEP.Text = '' Then edtCEP.Text := '50.000-000';
edtFone1.Text := ControlaCampoTexto( edtFone1.Text );
edtFone2.Text := ControlaCampoTexto( edtFone2.Text );
edtFax.Text := ControlaCampoTexto( edtFax.Text );
edtCelular.Text := ControlaCampoTexto( edtCelular.Text );
edtEmail.Text := ControlaCampoTexto( edtEmail.Text );
edtObs.Text := ControlaCampoTexto( edtObs.Text );
If cFlg = 'N' Then
Begin
_dm.qr12.Close;
_dm.qr12.SQL.Text := 'select * from CLIENTES';
_dm.qr12.Open;
_dm.qr12.Insert;
_dm.qr12.FieldByName( 'NomeCliente' ).AsString := edtNome.Text;
_dm.qr12.FieldByName( 'ENDERECO' ).AsString := edtEndereco.Text;
_dm.qr12.FieldByName( 'BAIRRO' ).AsString := edtBairro.Text;
_dm.qr12.FieldByName( 'CIDADE' ).AsString := edtCidade.Text;
_dm.qr12.FieldByName( 'CEP' ).AsString := edtCEP.Text;
_dm.qr12.FieldByName( 'FONE1' ).AsString := edtFone1.Text;
_dm.qr12.FieldByName( 'FONE2' ).AsString := edtFone2.Text;
_dm.qr12.FieldByName( 'FAX' ).AsString := edtFax.Text;
_dm.qr12.FieldByName( 'CELULAR' ).AsString := edtCelular.Text;
_dm.qr12.FieldByName( 'OBS' ).AsString := edtObs.Text;
_dm.qr12.FieldByName( 'e-mail' ).AsString := edtEmail.Text;
_dm.qr12.Post;
_dm.qr12.Close;
End;
If cFlg = 'A' Then
Begin
_dm.qr12.Close;
_dm.qr12.SQL.Text := 'select * from CLIENTES';
_dm.qr12.Open;
_dm.qr12.Locate( 'CodCliente', _dm.qr02CodCliente.AsString, [] );
_dm.qr12.Edit;
_dm.qr12.FieldByName( 'NomeCliente' ).AsString := edtNome.Text;
_dm.qr12.FieldByName( 'ENDERECO' ).AsString := edtEndereco.Text;
_dm.qr12.FieldByName( 'BAIRRO' ).AsString := edtBairro.Text;
_dm.qr12.FieldByName( 'CIDADE' ).AsString := edtCidade.Text;
_dm.qr12.FieldByName( 'CEP' ).AsString := edtCEP.Text;
_dm.qr12.FieldByName( 'FONE1' ).AsString := edtFone1.Text;
_dm.qr12.FieldByName( 'FONE2' ).AsString := edtFone2.Text;
_dm.qr12.FieldByName( 'FAX' ).AsString := edtFax.Text;
_dm.qr12.FieldByName( 'CELULAR' ).AsString := edtCelular.Text;
_dm.qr12.FieldByName( 'OBS' ).AsString := edtObs.Text;
_dm.qr12.FieldByName( 'e-mail' ).AsString := edtEmail.Text;
_dm.qr12.Post;
_dm.qr12.Close;
End;
_dm.qr02.Close;
_dm.qr02.Open;
cFlg := '';
cBusca := '';
cPorta := '';
Controle( True );
dbgClientes.SetFocus;
end;
end.
|
unit JRenderBufferIntuition;
{$mode objfpc}{$H+}
interface
uses
{FPC} SysUtils,
{Amiga} Exec, Intuition, AGraphics, layers, GadTools, Utility,
{JAE} JATypes, JABitmap;
type
TJRenderBufferIntuitionStatus = (
BufferStatus_Render = 0, {Buffer ready for render}
BufferStatus_Swap = 1, {Buffer ready for swap}
BufferStatus_Busy = 3 {Buffer is currently busy}
);
TJRenderBufferIntuition = record
Width : SInt16;
Height : SInt16;
Depth : SInt16;
Bitmap : pBitMap;
ColourMap : pColorMap;
{Layer Clipping Region}
LayerInfo : pLayer_Info;
Layer : pLayer;
{RasterPort}
RasterPort : PRastPort;
TmpRas : TTmpRas;
TmpRasBuffer : pointer;
TmpRasBufferSize : UInt32;
AreaInfo : TAreaInfo;
AreaInfoVertices : pointer;
AreaInfoVerticesCount : UInt32;
ScreenBuffer : pScreenBuffer;
Status : TJRenderBufferIntuitionStatus;
Index : UInt16;
end;
PJRenderBufferIntuition = ^TJRenderBufferIntuition;
function CreateRenderBufferIntuition(
AIndex : UInt32;
AWidth, AHeight, ADepth : UInt32;
AScreen : pScreen;
AScreenBufferType : UInt32;
AColourMap : pColorMap;
ADoubleBufferMessagePort : pMsgPort) : PJRenderBufferIntuition;
function DestroyRenderBufferIntuition(ARenderBufferIntuition : PJRenderBufferIntuition) : boolean;
implementation
function BufferBitmapsSetup(ARenderBuffer : PJRenderBufferIntuition; AWidth, AHeight, ADepth : UInt16) : boolean;
begin
{TODO : currently gets chip memory for standard graphics, probably different for picasso/RTG}
{allocate memory for the bitmap}
ARenderBuffer^.Bitmap := AllocBitMap(AWidth, AHeight, ADepth, 0, {BMF_CLEAR,} nil);
Result := true;
end;
{AScreenBufferType = SB_SCREEN_BITMAP or SB_COPY_BITMAP}
function CreateRenderBufferIntuition(AIndex : UInt32; AWidth,AHeight,ADepth : UInt32; AScreen : pScreen; AScreenBufferType : UInt32; AColourMap : pColorMap; ADoubleBufferMessagePort : pMsgPort) : PJRenderBufferIntuition;
var
TextAttributes : TTextAttr;
Font : PTextFont;
begin
{get memory for structure}
Result := PJRenderBufferIntuition(AllocMem(SizeOf(TJRenderBufferIntuition)));
Result^.Width := AWidth;
Result^.Height := AHeight;
Result^.Depth := ADepth;
Result^.ColourMap := AColourMap;
{create bitmap}
BufferBitmapsSetup(Result, AWidth, AHeight, ADepth);
{allocate a screen buffer}
Result^.ScreenBuffer := AllocScreenBuffer(AScreen, Result^.Bitmap, AScreenBufferType);
{store the bufferIndex inside the userdata for identification from a message}
Result^.ScreenBuffer^.sb_DBufInfo^.dbi_UserData1 := APTR(AIndex);
{setup double-buffer safe message reply-port}
Result^.ScreenBuffer^.sb_DBufInfo^.dbi_SafeMessage.mn_ReplyPort := ADoubleBufferMessagePort;
// create layer take rastport
Result^.LayerInfo := NewLayerInfo();
Result^.Layer := CreateUpfrontLayer(Result^.LayerInfo, Result^.Bitmap, 0, 0, Result^.Width-1, Result^.Height-1, LAYERSIMPLE, nil);
Result^.RasterPort := Result^.Layer^.RP;
{set rasterport to doublebuffered}
Result^.RasterPort^.Flags := DBUFFER;
{Setup the font}
TextAttributes.ta_Name := 'courier.font'; //11
//TextAttributes.ta_Name := 'topaz.font'; //8
TextAttributes.ta_YSize := 13;
TextAttributes.ta_Style := 0;
TextAttributes.ta_Flags := 0;
Font := OpenFont(@TextAttributes);
SetFont(Result^.RasterPort, Font);
{Setup the TmpRas for Area Fill Functions}
{TODO : we need to pass the renderbuffer dimensions. docs say 8 - is this
an assumed bitdepth or it's 8 per pixel across the board for tmpras?}
{Width * Height * 8}
{Apparently this is the space for one scanline, setting at least a
4K TmpRas can apparently trick/force the last blit operation performed
to exit early allowing for some concurrent CPU execution at that time}
//Result^.TmpRasBufferSize := 1024*4;
Result^.TmpRasBufferSize := AWidth * AHeight;
Result^.TmpRasBuffer := AllocVec(Result^.TmpRasBufferSize, MEMF_CHIP or MEMF_CLEAR);
InitTmpRas(@Result^.TmpRas, Result^.TmpRasBuffer, Result^.TmpRasBufferSize);
Result^.RasterPort^.TmpRas := @(Result^.TmpRas);
{The size of the region pointed to by buffer should be five (5) times as
large as maxvectors. This size is in bytes.}
Result^.AreaInfoVerticesCount := 12800;
Result^.AreaInfoVertices := AllocVec(Result^.AreaInfoVerticesCount*5, {MEMF_CHIP or }MEMF_CLEAR);
InitArea(@Result^.AreaInfo, Result^.AreaInfoVertices, Result^.AreaInfoVerticesCount);
Result^.RasterPort^.AreaInfo := @(Result^.AreaInfo);
{set initial status to render}
Result^.Status := BufferStatus_Render;
end;
function DestroyRenderBufferIntuition(ARenderBufferIntuition : PJRenderBufferIntuition) : boolean;
begin
Result := true;
if (ARenderBufferIntuition=nil) then exit(false);
with ARenderBufferIntuition^ do
begin
RasterPort^.AreaInfo := nil;
RasterPort^.Bitmap := nil;
RasterPort^.TmpRas := nil;
FreeVec(AreaInfoVertices);
FreeVec(TmpRasBuffer);
{Close the font}
CloseFont(RasterPort^.Font);
DeleteLayer(0, Layer);
DisposeLayerInfo(LayerInfo);
{free the system bitmap}
if (ARenderBufferIntuition^.Bitmap<>nil) then
begin
{Note that the AutoDoc FreeBitMap() recommends calling WaitBlit() before releasing
the Bitmap to be sure that nothing is being written in it.}
WaitBlit();
FreeBitMap(ARenderBufferIntuition^.Bitmap);
end;
end;
FreeMem(ARenderBufferIntuition);
end;
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
{$HPPEMIT '#pragma link "Datasnap.DSProxyJavaBlackBerry"'} { Do not Localize }
unit Datasnap.DSProxyJavaBlackBerry;
interface
const
sJavaBlackBerryRESTProxyWriter = 'Java (Black Berry) REST';
implementation
uses
Datasnap.DSCommonProxy,
Datasnap.DSProxyWriter,
Datasnap.DSProxyJavaAndroid,
System.Classes,
System.SysUtils;
type
TDSClientProxyWriterJavaBlackBerry = class(TDSProxyWriter)
public
function CreateProxyWriter: TDSCustomProxyWriter; override;
function Properties: TDSProxyWriterProperties; override;
function FileDescriptions: TDSProxyFileDescriptions; override;
end;
TDSCustomJavaBlackBerryProxyWriter = class (TDSCustomJavaAndroidProxyWriter)
protected
procedure WriteInterface; override;
end;
TDSJavaBlackBerryProxyWriter = class(TDSCustomJavaBlackBerryProxyWriter)
private
FStreamWriter: TStreamWriter;
protected
procedure DerivedWrite(const Line: UnicodeString); override;
procedure DerivedWriteLine; override;
public
property StreamWriter: TStreamWriter read FStreamWriter write FStreamWriter;
end;
const
sDSProxyJavaBlackBerryLanguage = 'java_blackberry';
{ TDSClientProxyWriterJavaBlackBerry }
function TDSClientProxyWriterJavaBlackBerry.CreateProxyWriter
: TDSCustomProxyWriter;
begin
Result := TDSJavaBlackBerryProxyWriter.Create;
end;
function TDSClientProxyWriterJavaBlackBerry.FileDescriptions
: TDSProxyFileDescriptions;
begin
SetLength(Result, 1);
Result[0].ID := sImplementation; // do not localize
Result[0].DefaultFileExt := '.java';
end;
function TDSClientProxyWriterJavaBlackBerry.Properties
: TDSProxyWriterProperties;
begin
Result.UsesUnits := 'Datasnap.DSProxyJavaBlackBerry';
Result.DefaultExcludeClasses := sDSMetadataClassName+ ',' + sDSAdminClassName; // do not localize
Result.DefaultExcludeMethods := sASMethodsPrefix;
Result.Author := 'Embarcadero'; // do not localize
Result.Comment := 'com\embarcadero\javablackberry'; // do not localize
Result.Language := sDSProxyJavaBlackBerryLanguage;
Result.Features := [feRESTClient];
Result.DefaultEncoding := TEncoding.UTF8;
end;
{ TDSCustomJavaBlackBerryProxyWriter }
procedure TDSCustomJavaBlackBerryProxyWriter.WriteInterface;
begin
WriteLine('package com.embarcadero.javablackberry;');
WriteLine;
WriteLine('import java.util.Date;');
WriteLine;
end;
{ TDSJavaBlackBerryProxyWriter }
procedure TDSJavaBlackBerryProxyWriter.DerivedWrite(const Line: UnicodeString);
begin
if StreamWriter <> nil then
StreamWriter.Write(Line)
else
ProxyWriters[sImplementation].Write(Line);
end;
procedure TDSJavaBlackBerryProxyWriter.DerivedWriteLine;
begin
if StreamWriter <> nil then
StreamWriter.WriteLine
else
ProxyWriters[sImplementation].WriteLine;
end;
initialization
TDSProxyWriterFactory.RegisterWriter(sJavaBlackBerryRESTProxyWriter,
TDSClientProxyWriterJavaBlackBerry);
finalization
TDSProxyWriterFactory.UnregisterWriter(sJavaBlackBerryRESTProxyWriter);
end.
|
{**************************************************************************************************}
{ }
{ Project JEDI Code Library (JCL) }
{ }
{ The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); }
{ you may not use this file except in compliance with the License. You may obtain a copy of the }
{ License at http://www.mozilla.org/MPL/ }
{ }
{ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF }
{ ANY KIND, either express or implied. See the License for the specific language governing rights }
{ and limitations under the License. }
{ }
{ The Original Code is JclSortedMaps.pas. }
{ }
{ The Initial Developer of the Original Code is Florent Ouchet. Portions created by }
{ Florent Ouchet are Copyright (C) Florent Ouchet <outchy att users dott sourceforge dott net }
{ All rights reserved. }
{ }
{ Contributors: }
{ }
{**************************************************************************************************}
{ }
{ The Delphi Container Library }
{ }
{**************************************************************************************************}
{ }
{ Last modified: $Date:: 2008-06-05 15:35:37 +0200 (jeu., 05 juin 2008) $ }
{ Revision: $Rev:: 2376 $ }
{ Author: $Author:: obones $ }
{ }
{**************************************************************************************************}
unit JclSortedMaps;
interface
{$I jcl.inc}
uses
Classes,
{$IFDEF UNITVERSIONING}
JclUnitVersioning,
{$ENDIF UNITVERSIONING}
{$IFDEF SUPPORTS_GENERICS}
{$IFDEF CLR}
System.Collections.Generic,
{$ENDIF CLR}
JclAlgorithms,
{$ENDIF SUPPORTS_GENERICS}
JclBase, JclAbstractContainers, JclContainerIntf, JclSynch;
{$I containers\JclContainerCommon.imp}
{$I containers\JclSortedMaps.imp}
{$I containers\JclSortedMaps.int}
type
(*$JPPEXPANDMACRO JCLSORTEDMAPINT(TJclIntfIntfSortedEntry,TJclIntfIntfSortedEntryArray,TJclIntfIntfSortedMap,TJclIntfAbstractContainer,IJclIntfIntfMap,IJclIntfIntfSortedMap,IJclIntfSet,IJclIntfCollection,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: IInterface): IInterface;
function FreeValue(var Value: IInterface): IInterface;
function KeysCompare(const A\, B: IInterface): Integer;
function ValuesCompare(const A\, B: IInterface): Integer;,,,,const ,IInterface,const ,IInterface)*)
(*$JPPEXPANDMACRO JCLSORTEDMAPINT(TJclAnsiStrIntfSortedEntry,TJclAnsiStrIntfSortedEntryArray,TJclAnsiStrIntfSortedMap,TJclAnsiStrAbstractContainer,IJclAnsiStrIntfMap,IJclAnsiStrIntfSortedMap,IJclAnsiStrSet,IJclIntfCollection, IJclStrContainer\, IJclAnsiStrContainer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: AnsiString): AnsiString;
function FreeValue(var Value: IInterface): IInterface;
function KeysCompare(const A\, B: AnsiString): Integer;
function ValuesCompare(const A\, B: IInterface): Integer;,,,,const ,AnsiString,const ,IInterface)*)
(*$JPPEXPANDMACRO JCLSORTEDMAPINT(TJclIntfAnsiStrSortedEntry,TJclIntfAnsiStrSortedEntryArray,TJclIntfAnsiStrSortedMap,TJclAnsiStrAbstractContainer,IJclIntfAnsiStrMap,IJclIntfAnsiStrSortedMap,IJclIntfSet,IJclAnsiStrCollection, IJclStrContainer\, IJclAnsiStrContainer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: IInterface): IInterface;
function FreeValue(var Value: AnsiString): AnsiString;
function KeysCompare(const A\, B: IInterface): Integer;
function ValuesCompare(const A\, B: AnsiString): Integer;,,,,const ,IInterface,const ,AnsiString)*)
(*$JPPEXPANDMACRO JCLSORTEDMAPINT(TJclAnsiStrAnsiStrSortedEntry,TJclAnsiStrAnsiStrSortedEntryArray,TJclAnsiStrAnsiStrSortedMap,TJclAnsiStrAbstractContainer,IJclAnsiStrAnsiStrMap,IJclAnsiStrAnsiStrSortedMap,IJclAnsiStrSet,IJclAnsiStrCollection, IJclStrContainer\, IJclAnsiStrContainer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: AnsiString): AnsiString;
function FreeValue(var Value: AnsiString): AnsiString;
function KeysCompare(const A\, B: AnsiString): Integer;
function ValuesCompare(const A\, B: AnsiString): Integer;,,,,const ,AnsiString,const ,AnsiString)*)
(*$JPPEXPANDMACRO JCLSORTEDMAPINT(TJclWideStrIntfSortedEntry,TJclWideStrIntfSortedEntryArray,TJclWideStrIntfSortedMap,TJclWideStrAbstractContainer,IJclWideStrIntfMap,IJclWideStrIntfSortedMap,IJclWideStrSet,IJclIntfCollection, IJclStrContainer\, IJclWideStrContainer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: WideString): WideString;
function FreeValue(var Value: IInterface): IInterface;
function KeysCompare(const A\, B: WideString): Integer;
function ValuesCompare(const A\, B: IInterface): Integer;,,,,const ,WideString,const ,IInterface)*)
(*$JPPEXPANDMACRO JCLSORTEDMAPINT(TJclIntfWideStrSortedEntry,TJclIntfWideStrSortedEntryArray,TJclIntfWideStrSortedMap,TJclWideStrAbstractContainer,IJclIntfWideStrMap,IJclIntfWideStrSortedMap,IJclIntfSet,IJclWideStrCollection, IJclStrContainer\, IJclWideStrContainer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: IInterface): IInterface;
function FreeValue(var Value: WideString): WideString;
function KeysCompare(const A\, B: IInterface): Integer;
function ValuesCompare(const A\, B: WideString): Integer;,,,,const ,IInterface,const ,WideString)*)
(*$JPPEXPANDMACRO JCLSORTEDMAPINT(TJclWideStrWideStrSortedEntry,TJclWideStrWideStrSortedEntryArray,TJclWideStrWideStrSortedMap,TJclWideStrAbstractContainer,IJclWideStrWideStrMap,IJclWideStrWideStrSortedMap,IJclWideStrSet,IJclWideStrCollection, IJclStrContainer\, IJclWideStrContainer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: WideString): WideString;
function FreeValue(var Value: WideString): WideString;
function KeysCompare(const A\, B: WideString): Integer;
function ValuesCompare(const A\, B: WideString): Integer;,,,,const ,WideString,const ,WideString)*)
{$IFDEF CONTAINER_ANSISTR}
TJclStrIntfSortedMap = TJclAnsiStrIntfSortedMap;
TJclIntfStrSortedMap = TJclIntfAnsiStrSortedMap;
TJclStrStrSortedMap = TJclAnsiStrAnsiStrSortedMap;
{$ENDIF CONTAINER_ANSISTR}
{$IFDEF CONTAINER_WIDESTR}
TJclStrIntfSortedMap = TJclWideStrIntfSortedMap;
TJclIntfStrSortedMap = TJclIntfWideStrSortedMap;
TJclStrStrSortedMap = TJclWideStrWideStrSortedMap;
{$ENDIF CONTAINER_WIDESTR}
(*$JPPEXPANDMACRO JCLSORTEDMAPINT(TJclSingleIntfSortedEntry,TJclSingleIntfSortedEntryArray,TJclSingleIntfSortedMap,TJclSingleAbstractContainer,IJclSingleIntfMap,IJclSingleIntfSortedMap,IJclSingleSet,IJclIntfCollection, IJclSingleContainer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Single): Single;
function FreeValue(var Value: IInterface): IInterface;
function KeysCompare(const A\, B: Single): Integer;
function ValuesCompare(const A\, B: IInterface): Integer;,,,,const ,Single,const ,IInterface)*)
(*$JPPEXPANDMACRO JCLSORTEDMAPINT(TJclIntfSingleSortedEntry,TJclIntfSingleSortedEntryArray,TJclIntfSingleSortedMap,TJclSingleAbstractContainer,IJclIntfSingleMap,IJclIntfSingleSortedMap,IJclIntfSet,IJclSingleCollection, IJclSingleContainer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: IInterface): IInterface;
function FreeValue(var Value: Single): Single;
function KeysCompare(const A\, B: IInterface): Integer;
function ValuesCompare(const A\, B: Single): Integer;,,,,const ,IInterface,const ,Single)*)
(*$JPPEXPANDMACRO JCLSORTEDMAPINT(TJclSingleSingleSortedEntry,TJclSingleSingleSortedEntryArray,TJclSingleSingleSortedMap,TJclSingleAbstractContainer,IJclSingleSingleMap,IJclSingleSingleSortedMap,IJclSingleSet,IJclSingleCollection, IJclSingleContainer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Single): Single;
function FreeValue(var Value: Single): Single;
function KeysCompare(const A\, B: Single): Integer;
function ValuesCompare(const A\, B: Single): Integer;,,,,const ,Single,const ,Single)*)
(*$JPPEXPANDMACRO JCLSORTEDMAPINT(TJclDoubleIntfSortedEntry,TJclDoubleIntfSortedEntryArray,TJclDoubleIntfSortedMap,TJclDoubleAbstractContainer,IJclDoubleIntfMap,IJclDoubleIntfSortedMap,IJclDoubleSet,IJclIntfCollection, IJclDoubleContainer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Double): Double;
function FreeValue(var Value: IInterface): IInterface;
function KeysCompare(const A\, B: Double): Integer;
function ValuesCompare(const A\, B: IInterface): Integer;,,,,const ,Double,const ,IInterface)*)
(*$JPPEXPANDMACRO JCLSORTEDMAPINT(TJclIntfDoubleSortedEntry,TJclIntfDoubleSortedEntryArray,TJclIntfDoubleSortedMap,TJclDoubleAbstractContainer,IJclIntfDoubleMap,IJclIntfDoubleSortedMap,IJclIntfSet,IJclDoubleCollection, IJclDoubleContainer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: IInterface): IInterface;
function FreeValue(var Value: Double): Double;
function KeysCompare(const A\, B: IInterface): Integer;
function ValuesCompare(const A\, B: Double): Integer;,,,,const ,IInterface,const ,Double)*)
(*$JPPEXPANDMACRO JCLSORTEDMAPINT(TJclDoubleDoubleSortedEntry,TJclDoubleDoubleSortedEntryArray,TJclDoubleDoubleSortedMap,TJclDoubleAbstractContainer,IJclDoubleDoubleMap,IJclDoubleDoubleSortedMap,IJclDoubleSet,IJclDoubleCollection, IJclDoubleContainer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Double): Double;
function FreeValue(var Value: Double): Double;
function KeysCompare(const A\, B: Double): Integer;
function ValuesCompare(const A\, B: Double): Integer;,,,,const ,Double,const ,Double)*)
(*$JPPEXPANDMACRO JCLSORTEDMAPINT(TJclExtendedIntfSortedEntry,TJclExtendedIntfSortedEntryArray,TJclExtendedIntfSortedMap,TJclExtendedAbstractContainer,IJclExtendedIntfMap,IJclExtendedIntfSortedMap,IJclExtendedSet,IJclIntfCollection, IJclExtendedContainer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Extended): Extended;
function FreeValue(var Value: IInterface): IInterface;
function KeysCompare(const A\, B: Extended): Integer;
function ValuesCompare(const A\, B: IInterface): Integer;,,,,const ,Extended,const ,IInterface)*)
(*$JPPEXPANDMACRO JCLSORTEDMAPINT(TJclIntfExtendedSortedEntry,TJclIntfExtendedSortedEntryArray,TJclIntfExtendedSortedMap,TJclExtendedAbstractContainer,IJclIntfExtendedMap,IJclIntfExtendedSortedMap,IJclIntfSet,IJclExtendedCollection, IJclExtendedContainer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: IInterface): IInterface;
function FreeValue(var Value: Extended): Extended;
function KeysCompare(const A\, B: IInterface): Integer;
function ValuesCompare(const A\, B: Extended): Integer;,,,,const ,IInterface,const ,Extended)*)
(*$JPPEXPANDMACRO JCLSORTEDMAPINT(TJclExtendedExtendedSortedEntry,TJclExtendedExtendedSortedEntryArray,TJclExtendedExtendedSortedMap,TJclExtendedAbstractContainer,IJclExtendedExtendedMap,IJclExtendedExtendedSortedMap,IJclExtendedSet,IJclExtendedCollection, IJclExtendedContainer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Extended): Extended;
function FreeValue(var Value: Extended): Extended;
function KeysCompare(const A\, B: Extended): Integer;
function ValuesCompare(const A\, B: Extended): Integer;,,,,const ,Extended,const ,Extended)*)
{$IFDEF MATH_EXTENDED_PRECISION}
TJclFloatIntfSortedMap = TJclExtendedIntfSortedMap;
TJclIntfFloatSortedMap = TJclIntfExtendedSortedMap;
TJclFloatFloatSortedMap = TJclExtendedExtendedSortedMap;
{$ENDIF MATH_EXTENDED_PRECISION}
{$IFDEF MATH_DOUBLE_PRECISION}
TJclFloatIntfSortedMap = TJclDoubleIntfSortedMap;
TJclIntfFloatSortedMap = TJclIntfDoubleSortedMap;
TJclFloatFloatSortedMap = TJclDoubleDoubleSortedMap;
{$ENDIF MATH_DOUBLE_PRECISION}
{$IFDEF MATH_SINGLE_PRECISION}
TJclFloatIntfSortedMap = TJclSingleIntfSortedMap;
TJclIntfFloatSortedMap = TJclIntfSingleSortedMap;
TJclFloatFloatSortedMap = TJclSingleSingleSortedMap;
{$ENDIF MATH_SINGLE_PRECISION}
(*$JPPEXPANDMACRO JCLSORTEDMAPINT(TJclIntegerIntfSortedEntry,TJclIntegerIntfSortedEntryArray,TJclIntegerIntfSortedMap,TJclIntegerAbstractContainer,IJclIntegerIntfMap,IJclIntegerIntfSortedMap,IJclIntegerSet,IJclIntfCollection,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Integer): Integer;
function FreeValue(var Value: IInterface): IInterface;
function KeysCompare(A\, B: Integer): Integer;
function ValuesCompare(const A\, B: IInterface): Integer;,,,,,Integer,const ,IInterface)*)
(*$JPPEXPANDMACRO JCLSORTEDMAPINT(TJclIntfIntegerSortedEntry,TJclIntfIntegerSortedEntryArray,TJclIntfIntegerSortedMap,TJclIntegerAbstractContainer,IJclIntfIntegerMap,IJclIntfIntegerSortedMap,IJclIntfSet,IJclIntegerCollection,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: IInterface): IInterface;
function FreeValue(var Value: Integer): Integer;
function KeysCompare(const A\, B: IInterface): Integer;
function ValuesCompare(A\, B: Integer): Integer;,,,,const ,IInterface,,Integer)*)
(*$JPPEXPANDMACRO JCLSORTEDMAPINT(TJclIntegerIntegerSortedEntry,TJclIntegerIntegerSortedEntryArray,TJclIntegerIntegerSortedMap,TJclIntegerAbstractContainer,IJclIntegerIntegerMap,IJclIntegerIntegerSortedMap,IJclIntegerSet,IJclIntegerCollection,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Integer): Integer;
function FreeValue(var Value: Integer): Integer;
function KeysCompare(A\, B: Integer): Integer;
function ValuesCompare(A\, B: Integer): Integer;,,,,,Integer,,Integer)*)
(*$JPPEXPANDMACRO JCLSORTEDMAPINT(TJclCardinalIntfSortedEntry,TJclCardinalIntfSortedEntryArray,TJclCardinalIntfSortedMap,TJclCardinalAbstractContainer,IJclCardinalIntfMap,IJclCardinalIntfSortedMap,IJclCardinalSet,IJclIntfCollection,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Cardinal): Cardinal;
function FreeValue(var Value: IInterface): IInterface;
function KeysCompare(A\, B: Cardinal): Integer;
function ValuesCompare(const A\, B: IInterface): Integer;,,,,,Cardinal,const ,IInterface)*)
(*$JPPEXPANDMACRO JCLSORTEDMAPINT(TJclIntfCardinalSortedEntry,TJclIntfCardinalSortedEntryArray,TJclIntfCardinalSortedMap,TJclCardinalAbstractContainer,IJclIntfCardinalMap,IJclIntfCardinalSortedMap,IJclIntfSet,IJclCardinalCollection,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: IInterface): IInterface;
function FreeValue(var Value: Cardinal): Cardinal;
function KeysCompare(const A\, B: IInterface): Integer;
function ValuesCompare(A\, B: Cardinal): Integer;,,,,const ,IInterface,,Cardinal)*)
(*$JPPEXPANDMACRO JCLSORTEDMAPINT(TJclCardinalCardinalSortedEntry,TJclCardinalCardinalSortedEntryArray,TJclCardinalCardinalSortedMap,TJclCardinalAbstractContainer,IJclCardinalCardinalMap,IJclCardinalCardinalSortedMap,IJclCardinalSet,IJclCardinalCollection,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Cardinal): Cardinal;
function FreeValue(var Value: Cardinal): Cardinal;
function KeysCompare(A\, B: Cardinal): Integer;
function ValuesCompare(A\, B: Cardinal): Integer;,,,,,Cardinal,,Cardinal)*)
(*$JPPEXPANDMACRO JCLSORTEDMAPINT(TJclInt64IntfSortedEntry,TJclInt64IntfSortedEntryArray,TJclInt64IntfSortedMap,TJclInt64AbstractContainer,IJclInt64IntfMap,IJclInt64IntfSortedMap,IJclInt64Set,IJclIntfCollection,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Int64): Int64;
function FreeValue(var Value: IInterface): IInterface;
function KeysCompare(const A\, B: Int64): Integer;
function ValuesCompare(const A\, B: IInterface): Integer;,,,,const ,Int64,const ,IInterface)*)
(*$JPPEXPANDMACRO JCLSORTEDMAPINT(TJclIntfInt64SortedEntry,TJclIntfInt64SortedEntryArray,TJclIntfInt64SortedMap,TJclInt64AbstractContainer,IJclIntfInt64Map,IJclIntfInt64SortedMap,IJclIntfSet,IJclInt64Collection,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: IInterface): IInterface;
function FreeValue(var Value: Int64): Int64;
function KeysCompare(const A\, B: IInterface): Integer;
function ValuesCompare(const A\, B: Int64): Integer;,,,,const ,IInterface,const ,Int64)*)
(*$JPPEXPANDMACRO JCLSORTEDMAPINT(TJclInt64Int64SortedEntry,TJclInt64Int64SortedEntryArray,TJclInt64Int64SortedMap,TJclInt64AbstractContainer,IJclInt64Int64Map,IJclInt64Int64SortedMap,IJclInt64Set,IJclInt64Collection,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Int64): Int64;
function FreeValue(var Value: Int64): Int64;
function KeysCompare(const A\, B: Int64): Integer;
function ValuesCompare(const A\, B: Int64): Integer;,,,,const ,Int64,const ,Int64)*)
{$IFNDEF CLR}
(*$JPPEXPANDMACRO JCLSORTEDMAPINT(TJclPtrIntfSortedEntry,TJclPtrIntfSortedEntryArray,TJclPtrIntfSortedMap,TJclPtrAbstractContainer,IJclPtrIntfMap,IJclPtrIntfSortedMap,IJclPtrSet,IJclIntfCollection,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Pointer): Pointer;
function FreeValue(var Value: IInterface): IInterface;
function KeysCompare(A\, B: Pointer): Integer;
function ValuesCompare(const A\, B: IInterface): Integer;,,,,,Pointer,const ,IInterface)*)
(*$JPPEXPANDMACRO JCLSORTEDMAPINT(TJclIntfPtrSortedEntry,TJclIntfPtrSortedEntryArray,TJclIntfPtrSortedMap,TJclPtrAbstractContainer,IJclIntfPtrMap,IJclIntfPtrSortedMap,IJclIntfSet,IJclPtrCollection,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: IInterface): IInterface;
function FreeValue(var Value: Pointer): Pointer;
function KeysCompare(const A\, B: IInterface): Integer;
function ValuesCompare(A\, B: Pointer): Integer;,,,,const ,IInterface,,Pointer)*)
(*$JPPEXPANDMACRO JCLSORTEDMAPINT(TJclPtrPtrSortedEntry,TJclPtrPtrSortedEntryArray,TJclPtrPtrSortedMap,TJclPtrAbstractContainer,IJclPtrPtrMap,IJclPtrPtrSortedMap,IJclPtrSet,IJclPtrCollection,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Pointer): Pointer;
function FreeValue(var Value: Pointer): Pointer;
function KeysCompare(A\, B: Pointer): Integer;
function ValuesCompare(A\, B: Pointer): Integer;,,,,,Pointer,,Pointer)*)
{$ENDIF ~CLR}
(*$JPPEXPANDMACRO JCLSORTEDMAPINT(TJclIntfSortedEntry,TJclIntfSortedEntryArray,TJclIntfSortedMap,TJclIntfAbstractContainer,IJclIntfMap,IJclIntfSortedMap,IJclIntfSet,IJclCollection, IJclValueOwner\,,
FOwnsValues: Boolean;,
{ IJclValueOwner }
function FreeValue(var Value: TObject): TObject;
function GetOwnsValues: Boolean;
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: IInterface): IInterface;
function KeysCompare(const A\, B: IInterface): Integer;
function ValuesCompare(A\, B: TObject): Integer;,
property OwnsValues: Boolean read FOwnsValues;,,; AOwnsValues: Boolean,const ,IInterface,,TObject)*)
(*$JPPEXPANDMACRO JCLSORTEDMAPINT(TJclAnsiStrSortedEntry,TJclAnsiStrSortedEntryArray,TJclAnsiStrSortedMap,TJclAnsiStrAbstractContainer,IJclAnsiStrMap,IJclAnsiStrSortedMap,IJclAnsiStrSet,IJclCollection, IJclStrContainer\, IJclAnsiStrContainer\, IJclValueOwner\,,
FOwnsValues: Boolean;,
{ IJclValueOwner }
function FreeValue(var Value: TObject): TObject;
function GetOwnsValues: Boolean;
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: AnsiString): AnsiString;
function KeysCompare(const A\, B: AnsiString): Integer;
function ValuesCompare(A\, B: TObject): Integer;,
property OwnsValues: Boolean read FOwnsValues;,,; AOwnsValues: Boolean,const ,AnsiString,,TObject)*)
(*$JPPEXPANDMACRO JCLSORTEDMAPINT(TJclWideStrSortedEntry,TJclWideStrSortedEntryArray,TJclWideStrSortedMap,TJclWideStrAbstractContainer,IJclWideStrMap,IJclWideStrSortedMap,IJclWideStrSet,IJclCollection, IJclStrContainer\, IJclWideStrContainer\, IJclValueOwner\,,
FOwnsValues: Boolean;,
{ IJclValueOwner }
function FreeValue(var Value: TObject): TObject;
function GetOwnsValues: Boolean;
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: WideString): WideString;
function KeysCompare(const A\, B: WideString): Integer;
function ValuesCompare(A\, B: TObject): Integer;,
property OwnsValues: Boolean read FOwnsValues;,,; AOwnsValues: Boolean,const ,WideString,,TObject)*)
{$IFDEF CONTAINER_ANSISTR}
TJclStrSortedMap = TJclAnsiStrSortedMap;
{$ENDIF CONTAINER_ANSISTR}
{$IFDEF CONTAINER_WIDESTR}
TJclStrSortedMap = TJclWideStrSortedMap;
{$ENDIF CONTAINER_WIDESTR}
(*$JPPEXPANDMACRO JCLSORTEDMAPINT(TJclSingleSortedEntry,TJclSingleSortedEntryArray,TJclSingleSortedMap,TJclSingleAbstractContainer,IJclSingleMap,IJclSingleSortedMap,IJclSingleSet,IJclCollection, IJclSingleContainer\, IJclValueOwner\,,
FOwnsValues: Boolean;,
{ IJclValueOwner }
function FreeValue(var Value: TObject): TObject;
function GetOwnsValues: Boolean;
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Single): Single;
function KeysCompare(const A\, B: Single): Integer;
function ValuesCompare(A\, B: TObject): Integer;,
property OwnsValues: Boolean read FOwnsValues;,,; AOwnsValues: Boolean,const ,Single,,TObject)*)
(*$JPPEXPANDMACRO JCLSORTEDMAPINT(TJclDoubleSortedEntry,TJclDoubleSortedEntryArray,TJclDoubleSortedMap,TJclDoubleAbstractContainer,IJclDoubleMap,IJclDoubleSortedMap,IJclDoubleSet,IJclCollection, IJclDoubleContainer\, IJclValueOwner\,,
FOwnsValues: Boolean;,
{ IJclValueOwner }
function FreeValue(var Value: TObject): TObject;
function GetOwnsValues: Boolean;
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Double): Double;
function KeysCompare(const A\, B: Double): Integer;
function ValuesCompare(A\, B: TObject): Integer;,
property OwnsValues: Boolean read FOwnsValues;,,; AOwnsValues: Boolean,const ,Double,,TObject)*)
(*$JPPEXPANDMACRO JCLSORTEDMAPINT(TJclExtendedSortedEntry,TJclExtendedSortedEntryArray,TJclExtendedSortedMap,TJclExtendedAbstractContainer,IJclExtendedMap,IJclExtendedSortedMap,IJclExtendedSet,IJclCollection, IJclExtendedContainer\, IJclValueOwner\,,
FOwnsValues: Boolean;,
{ IJclValueOwner }
function FreeValue(var Value: TObject): TObject;
function GetOwnsValues: Boolean;
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Extended): Extended;
function KeysCompare(const A\, B: Extended): Integer;
function ValuesCompare(A\, B: TObject): Integer;,
property OwnsValues: Boolean read FOwnsValues;,,; AOwnsValues: Boolean,const ,Extended,,TObject)*)
{$IFDEF MATH_EXTENDED_PRECISION}
TJclFloatSortedMap = TJclExtendedSortedMap;
{$ENDIF MATH_EXTENDED_PRECISION}
{$IFDEF MATH_DOUBLE_PRECISION}
TJclFloatSortedMap = TJclDoubleSortedMap;
{$ENDIF MATH_DOUBLE_PRECISION}
{$IFDEF MATH_SINGLE_PRECISION}
TJclFloatSortedMap = TJclSingleSortedMap;
{$ENDIF MATH_SINGLE_PRECISION}
(*$JPPEXPANDMACRO JCLSORTEDMAPINT(TJclIntegerSortedEntry,TJclIntegerSortedEntryArray,TJclIntegerSortedMap,TJclIntegerAbstractContainer,IJclIntegerMap,IJclIntegerSortedMap,IJclIntegerSet,IJclCollection, IJclValueOwner\,,
FOwnsValues: Boolean;,
{ IJclValueOwner }
function FreeValue(var Value: TObject): TObject;
function GetOwnsValues: Boolean;
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Integer): Integer;
function KeysCompare(A\, B: Integer): Integer;
function ValuesCompare(A\, B: TObject): Integer;,
property OwnsValues: Boolean read FOwnsValues;,,; AOwnsValues: Boolean,,Integer,,TObject)*)
(*$JPPEXPANDMACRO JCLSORTEDMAPINT(TJclCardinalSortedEntry,TJclCardinalSortedEntryArray,TJclCardinalSortedMap,TJclCardinalAbstractContainer,IJclCardinalMap,IJclCardinalSortedMap,IJclCardinalSet,IJclCollection, IJclValueOwner\,,
FOwnsValues: Boolean;,
{ IJclValueOwner }
function FreeValue(var Value: TObject): TObject;
function GetOwnsValues: Boolean;
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Cardinal): Cardinal;
function KeysCompare(A\, B: Cardinal): Integer;
function ValuesCompare(A\, B: TObject): Integer;,
property OwnsValues: Boolean read FOwnsValues;,,; AOwnsValues: Boolean,,Cardinal,,TObject)*)
(*$JPPEXPANDMACRO JCLSORTEDMAPINT(TJclInt64SortedEntry,TJclInt64SortedEntryArray,TJclInt64SortedMap,TJclInt64AbstractContainer,IJclInt64Map,IJclInt64SortedMap,IJclInt64Set,IJclCollection, IJclValueOwner\,,
FOwnsValues: Boolean;,
{ IJclValueOwner }
function FreeValue(var Value: TObject): TObject;
function GetOwnsValues: Boolean;
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Int64): Int64;
function KeysCompare(const A\, B: Int64): Integer;
function ValuesCompare(A\, B: TObject): Integer;,
property OwnsValues: Boolean read FOwnsValues;,,; AOwnsValues: Boolean,const ,Int64,,TObject)*)
{$IFNDEF CLR}
(*$JPPEXPANDMACRO JCLSORTEDMAPINT(TJclPtrSortedEntry,TJclPtrSortedEntryArray,TJclPtrSortedMap,TJclPtrAbstractContainer,IJclPtrMap,IJclPtrSortedMap,IJclPtrSet,IJclCollection, IJclValueOwner\,,
FOwnsValues: Boolean;,
{ IJclValueOwner }
function FreeValue(var Value: TObject): TObject;
function GetOwnsValues: Boolean;
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Pointer): Pointer;
function KeysCompare(A\, B: Pointer): Integer;
function ValuesCompare(A\, B: TObject): Integer;,
property OwnsValues: Boolean read FOwnsValues;,,; AOwnsValues: Boolean,,Pointer,,TObject)*)
{$ENDIF ~CLR}
(*$JPPEXPANDMACRO JCLSORTEDMAPINT(TJclSortedEntry,TJclSortedEntryArray,TJclSortedMap,TJclAbstractContainerBase,IJclMap,IJclSortedMap,IJclSet,IJclCollection, IJclKeyOwner\, IJclValueOwner\,,
FOwnsKeys: Boolean;
FOwnsValues: Boolean;,
{ IJclKeyOwner }
function FreeKey(var Key: TObject): TObject;
function GetOwnsKeys: Boolean;
{ IJclValueOwner }
function FreeValue(var Value: TObject): TObject;
function GetOwnsValues: Boolean;
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function KeysCompare(A\, B: TObject): Integer;
function ValuesCompare(A\, B: TObject): Integer;,
property OwnsKeys: Boolean read FOwnsKeys;
property OwnsValues: Boolean read FOwnsValues;,; AOwnsKeys: Boolean,; AOwnsValues: Boolean,,TObject,,TObject)*)
{$IFDEF SUPPORTS_GENERICS}
(*$JPPEXPANDMACRO JCLSORTEDMAPINT(TJclSortedEntry<TKey\,TValue>,TJclSortedEntryArray<TKey\,TValue>,TJclSortedMap<TKey\,TValue>,TJclAbstractContainerBase,IJclMap<TKey\,TValue>,IJclSortedMap<TKey\,TValue>,IJclSet<TKey>,IJclCollection<TValue>, IJclPairOwner<TKey\,TValue>\,,
FOwnsKeys: Boolean;
FOwnsValues: Boolean;,
{ IJclPairOwner }
function FreeKey(var Key: TKey): TKey;
function FreeValue(var Value: TValue): TValue;
function GetOwnsKeys: Boolean;
function GetOwnsValues: Boolean;
function KeysCompare(const A\, B: TKey): Integer; virtual; abstract;
function ValuesCompare(const A\, B: TValue): Integer; virtual; abstract;
function CreateEmptyArrayList(ACapacity: Integer; AOwnsObjects: Boolean): IJclCollection<TValue>; virtual; abstract;
function CreateEmptyArraySet(ACapacity: Integer; AOwnsObjects: Boolean): IJclSet<TKey>; virtual; abstract;,
property OwnsKeys: Boolean read FOwnsKeys;
property OwnsValues: Boolean read FOwnsValues;,; AOwnsKeys: Boolean,; AOwnsValues: Boolean,const ,TKey,const ,TValue)*)
// E = external helper to compare items
TJclSortedMapE<TKey, TValue> = class(TJclSortedMap<TKey,TValue>, {$IFDEF THREADSAFE} IJclLockable, {$ENDIF THREADSAFE}
IJclIntfCloneable, IJclCloneable, IJclPackable, IJclContainer, IJclMap<TKey,TValue>, IJclSortedMap<TKey,TValue>, IJclPairOwner<TKey,TValue>)
private
FKeyComparer: IComparer<TKey>;
FValueComparer: IComparer<TValue>;
FValueEqualityComparer: IEqualityComparer<TValue>;
protected
procedure AssignPropertiesTo(Dest: TJclAbstractContainerBase); override;
function KeysCompare(const A, B: TKey): Integer; override;
function ValuesCompare(const A, B: TValue): Integer; override;
function CreateEmptyArrayList(ACapacity: Integer; AOwnsObjects: Boolean): IJclCollection<TValue>; override;
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function CreateEmptyArraySet(ACapacity: Integer; AOwnsObjects: Boolean): IJclSet<TKey>; override;
{ IJclCloneable }
function IJclCloneable.Clone = ObjectClone;
{ IJclIntfCloneable }
function IJclIntfCloneable.Clone = IntfClone;
public
constructor Create(const AKeyComparer: IComparer<TKey>; const AValueComparer: IComparer<TValue>;
const AValueEqualityComparer: IEqualityComparer<TValue>; ACapacity: Integer; AOwnsValues: Boolean;
AOwnsKeys: Boolean);
property KeyComparer: IComparer<TKey> read FKeyComparer write FKeyComparer;
property ValueComparer: IComparer<TValue> read FValueComparer write FValueComparer;
property ValueEqualityComparer: IEqualityComparer<TValue> read FValueEqualityComparer write FValueEqualityComparer;
end;
// F = Functions to compare items
TJclSortedMapF<TKey, TValue> = class(TJclSortedMap<TKey, TValue>, {$IFDEF THREADSAFE} IJclLockable, {$ENDIF THREADSAFE}
IJclIntfCloneable, IJclCloneable, IJclPackable, IJclContainer, IJclMap<TKey,TValue>, IJclSortedMap<TKey,TValue>, IJclPairOwner<TKey, TValue>)
private
FKeyCompare: TCompare<TKey>;
FValueCompare: TCompare<TValue>;
FValueEqualityCompare: TEqualityCompare<TValue>;
protected
procedure AssignPropertiesTo(Dest: TJclAbstractContainerBase); override;
function KeysCompare(const A, B: TKey): Integer; override;
function ValuesCompare(const A, B: TValue): Integer; override;
function CreateEmptyArrayList(ACapacity: Integer; AOwnsObjects: Boolean): IJclCollection<TValue>; override;
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function CreateEmptyArraySet(ACapacity: Integer; AOwnsObjects: Boolean): IJclSet<TKey>; override;
{ IJclCloneable }
function IJclCloneable.Clone = ObjectClone;
{ IJclIntfCloneable }
function IJclIntfCloneable.Clone = IntfClone;
public
constructor Create(AKeyCompare: TCompare<TKey>; AValueCompare: TCompare<TValue>;
AValueEqualityCompare: TEqualityCompare<TValue>; ACapacity: Integer; AOwnsValues: Boolean; AOwnsKeys: Boolean);
property KeyCompare: TCompare<TKey> read FKeyCompare write FKeyCompare;
property ValueCompare: TCompare<TValue> read FValueCompare write FValueCompare;
property ValueEqualityCompare: TEqualityCompare<TValue> read FValueEqualityCompare write FValueEqualityCompare;
end;
// I = items can compare themselves to an other
TJclSortedMapI<TKey: IComparable<TKey>; TValue: IComparable<TValue>, IEquatable<TValue>> = class(TJclSortedMap<TKey, TValue>,
{$IFDEF THREADSAFE} IJclLockable, {$ENDIF THREADSAFE} IJclIntfCloneable, IJclCloneable, IJclPackable, IJclContainer,
IJclMap<TKey,TValue>, IJclSortedMap<TKey,TValue>, IJclPairOwner<TKey, TValue>)
protected
function KeysCompare(const A, B: TKey): Integer; override;
function ValuesCompare(const A, B: TValue): Integer; override;
function CreateEmptyArrayList(ACapacity: Integer; AOwnsObjects: Boolean): IJclCollection<TValue>; override;
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function CreateEmptyArraySet(ACapacity: Integer; AOwnsObjects: Boolean): IJclSet<TKey>; override;
{ IJclCloneable }
function IJclCloneable.Clone = ObjectClone;
{ IJclIntfCloneable }
function IJclIntfCloneable.Clone = IntfClone;
end;
{$ENDIF SUPPORTS_GENERICS}
{$IFDEF UNITVERSIONING}
const
UnitVersioning: TUnitVersionInfo = (
RCSfile: '$URL: https://jcl.svn.sourceforge.net:443/svnroot/jcl/tags/JCL-1.102-Build3072/jcl/source/prototypes/JclSortedMaps.pas $';
Revision: '$Revision: 2376 $';
Date: '$Date: 2008-06-05 15:35:37 +0200 (jeu., 05 juin 2008) $';
LogPath: 'JCL\source\common'
);
{$ENDIF UNITVERSIONING}
implementation
uses
SysUtils,
JclArrayLists,
JclArraySets;
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclIntfIntfSortedMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclIntfIntfSortedMap.Create(FSize);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclIntfArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclIntfArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclIntfIntfSortedMap.FreeKey(var Key: IInterface): IInterface;
begin
Result := Key;
Key := nil;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclIntfIntfSortedMap.FreeValue(var Value: IInterface): IInterface;
begin
Result := Value;
Value := nil;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO KEYSCOMPARE
function TJclIntfIntfSortedMap.KeysCompare(const A, B: IInterface): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPDEFINEMACRO VALUESCOMPARE
function TJclIntfIntfSortedMap.ValuesCompare(const A, B: IInterface): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPEXPANDMACRO JCLSORTEDMAPIMP(TJclIntfIntfSortedMap,TJclIntfIntfSortedEntry,IJclIntfIntfMap,IJclIntfIntfSortedMap,IJclIntfSet,IJclIntfIterator,IJclIntfCollection,,,,const ,IInterface,nil,const ,IInterface,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO KEYSCOMPARE}
{$JPPUNDEFMACRO VALUESCOMPARE}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclAnsiStrIntfSortedMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclAnsiStrIntfSortedMap.Create(FSize);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclAnsiStrArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclIntfArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclAnsiStrIntfSortedMap.FreeKey(var Key: AnsiString): AnsiString;
begin
Result := Key;
Key := '';
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclAnsiStrIntfSortedMap.FreeValue(var Value: IInterface): IInterface;
begin
Result := Value;
Value := nil;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO KEYSCOMPARE
function TJclAnsiStrIntfSortedMap.KeysCompare(const A, B: AnsiString): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPDEFINEMACRO VALUESCOMPARE
function TJclAnsiStrIntfSortedMap.ValuesCompare(const A, B: IInterface): Integer;
begin
if Integer(A) > Integer(B) then
Result := 1
else
if Integer(A) < Integer(B) then
Result := -1
else
Result := 0;
end;
}
{$JPPEXPANDMACRO JCLSORTEDMAPIMP(TJclAnsiStrIntfSortedMap,TJclAnsiStrIntfSortedEntry,IJclAnsiStrIntfMap,IJclAnsiStrIntfSortedMap,IJclAnsiStrSet,IJclAnsiStrIterator,IJclIntfCollection,,,,const ,AnsiString,'',const ,IInterface,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO KEYSCOMPARE}
{$JPPUNDEFMACRO VALUESCOMPARE}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclIntfAnsiStrSortedMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclIntfAnsiStrSortedMap.Create(FSize);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclIntfArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclAnsiStrArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclIntfAnsiStrSortedMap.FreeKey(var Key: IInterface): IInterface;
begin
Result := Key;
Key := nil;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclIntfAnsiStrSortedMap.FreeValue(var Value: AnsiString): AnsiString;
begin
Result := Value;
Value := '';
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO KEYSCOMPARE
function TJclIntfAnsiStrSortedMap.KeysCompare(const A, B: IInterface): Integer;
begin
if Integer(A) > Integer(B) then
Result := 1
else
if Integer(A) < Integer(B) then
Result := -1
else
Result := 0;
end;
}
{$JPPDEFINEMACRO VALUESCOMPARE
function TJclIntfAnsiStrSortedMap.ValuesCompare(const A, B: AnsiString): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPEXPANDMACRO JCLSORTEDMAPIMP(TJclIntfAnsiStrSortedMap,TJclIntfAnsiStrSortedEntry,IJclIntfAnsiStrMap,IJclIntfAnsiStrSortedMap,IJclIntfSet,IJclIntfIterator,IJclAnsiStrCollection,,,,const ,IInterface,nil,const ,AnsiString,'')}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO KEYSCOMPARE}
{$JPPUNDEFMACRO VALUESCOMPARE}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclAnsiStrAnsiStrSortedMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclAnsiStrAnsiStrSortedMap.Create(FSize);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclAnsiStrArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclAnsiStrArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclAnsiStrAnsiStrSortedMap.FreeKey(var Key: AnsiString): AnsiString;
begin
Result := Key;
Key := '';
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclAnsiStrAnsiStrSortedMap.FreeValue(var Value: AnsiString): AnsiString;
begin
Result := Value;
Value := '';
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO KEYSCOMPARE
function TJclAnsiStrAnsiStrSortedMap.KeysCompare(const A, B: AnsiString): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPDEFINEMACRO VALUESCOMPARE
function TJclAnsiStrAnsiStrSortedMap.ValuesCompare(const A, B: AnsiString): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPEXPANDMACRO JCLSORTEDMAPIMP(TJclAnsiStrAnsiStrSortedMap,TJclAnsiStrAnsiStrSortedEntry,IJclAnsiStrAnsiStrMap,IJclAnsiStrAnsiStrSortedMap,IJclAnsiStrSet,IJclAnsiStrIterator,IJclAnsiStrCollection,,,,const ,AnsiString,'',const ,AnsiString,'')}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO KEYSCOMPARE}
{$JPPUNDEFMACRO VALUESCOMPARE}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclWideStrIntfSortedMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclWideStrIntfSortedMap.Create(FSize);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclWideStrArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclIntfArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclWideStrIntfSortedMap.FreeKey(var Key: WideString): WideString;
begin
Result := Key;
Key := '';
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclWideStrIntfSortedMap.FreeValue(var Value: IInterface): IInterface;
begin
Result := Value;
Value := nil;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO KEYSCOMPARE
function TJclWideStrIntfSortedMap.KeysCompare(const A, B: WideString): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPDEFINEMACRO VALUESCOMPARE
function TJclWideStrIntfSortedMap.ValuesCompare(const A, B: IInterface): Integer;
begin
if Integer(A) > Integer(B) then
Result := 1
else
if Integer(A) < Integer(B) then
Result := -1
else
Result := 0;
end;
}
{$JPPEXPANDMACRO JCLSORTEDMAPIMP(TJclWideStrIntfSortedMap,TJclWideStrIntfSortedEntry,IJclWideStrIntfMap,IJclWideStrIntfSortedMap,IJclWideStrSet,IJclWideStrIterator,IJclIntfCollection,,,,const ,WideString,'',const ,IInterface,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO KEYSCOMPARE}
{$JPPUNDEFMACRO VALUESCOMPARE}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclIntfWideStrSortedMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclIntfWideStrSortedMap.Create(FSize);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclIntfArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclWideStrArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclIntfWideStrSortedMap.FreeKey(var Key: IInterface): IInterface;
begin
Result := Key;
Key := nil;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclIntfWideStrSortedMap.FreeValue(var Value: WideString): WideString;
begin
Result := Value;
Value := '';
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO KEYSCOMPARE
function TJclIntfWideStrSortedMap.KeysCompare(const A, B: IInterface): Integer;
begin
if Integer(A) > Integer(B) then
Result := 1
else
if Integer(A) < Integer(B) then
Result := -1
else
Result := 0;
end;
}
{$JPPDEFINEMACRO VALUESCOMPARE
function TJclIntfWideStrSortedMap.ValuesCompare(const A, B: WideString): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPEXPANDMACRO JCLSORTEDMAPIMP(TJclIntfWideStrSortedMap,TJclIntfWideStrSortedEntry,IJclIntfWideStrMap,IJclIntfWideStrSortedMap,IJclIntfSet,IJclIntfIterator,IJclWideStrCollection,,,,const ,IInterface,nil,const ,WideString,'')}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO KEYSCOMPARE}
{$JPPUNDEFMACRO VALUESCOMPARE}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclWideStrWideStrSortedMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclWideStrWideStrSortedMap.Create(FSize);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclWideStrArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclWideStrArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclWideStrWideStrSortedMap.FreeKey(var Key: WideString): WideString;
begin
Result := Key;
Key := '';
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclWideStrWideStrSortedMap.FreeValue(var Value: WideString): WideString;
begin
Result := Value;
Value := '';
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO KEYSCOMPARE
function TJclWideStrWideStrSortedMap.KeysCompare(const A, B: WideString): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPDEFINEMACRO VALUESCOMPARE
function TJclWideStrWideStrSortedMap.ValuesCompare(const A, B: WideString): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPEXPANDMACRO JCLSORTEDMAPIMP(TJclWideStrWideStrSortedMap,TJclWideStrWideStrSortedEntry,IJclWideStrWideStrMap,IJclWideStrWideStrSortedMap,IJclWideStrSet,IJclWideStrIterator,IJclWideStrCollection,,,,const ,WideString,'',const ,WideString,'')}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO KEYSCOMPARE}
{$JPPUNDEFMACRO VALUESCOMPARE}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclSingleIntfSortedMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclSingleIntfSortedMap.Create(FSize);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclSingleArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclIntfArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclSingleIntfSortedMap.FreeKey(var Key: Single): Single;
begin
Result := Key;
Key := 0.0;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclSingleIntfSortedMap.FreeValue(var Value: IInterface): IInterface;
begin
Result := Value;
Value := nil;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO KEYSCOMPARE
function TJclSingleIntfSortedMap.KeysCompare(const A, B: Single): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPDEFINEMACRO VALUESCOMPARE
function TJclSingleIntfSortedMap.ValuesCompare(const A, B: IInterface): Integer;
begin
if Integer(A) > Integer(B) then
Result := 1
else
if Integer(A) < Integer(B) then
Result := -1
else
Result := 0;
end;
}
{$JPPEXPANDMACRO JCLSORTEDMAPIMP(TJclSingleIntfSortedMap,TJclSingleIntfSortedEntry,IJclSingleIntfMap,IJclSingleIntfSortedMap,IJclSingleSet,IJclSingleIterator,IJclIntfCollection,,,,const ,Single,0.0,const ,IInterface,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO KEYSCOMPARE}
{$JPPUNDEFMACRO VALUESCOMPARE}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclIntfSingleSortedMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclIntfSingleSortedMap.Create(FSize);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclIntfArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclSingleArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclIntfSingleSortedMap.FreeKey(var Key: IInterface): IInterface;
begin
Result := Key;
Key := nil;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclIntfSingleSortedMap.FreeValue(var Value: Single): Single;
begin
Result := Value;
Value := 0.0;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO KEYSCOMPARE
function TJclIntfSingleSortedMap.KeysCompare(const A, B: IInterface): Integer;
begin
if Integer(A) > Integer(B) then
Result := 1
else
if Integer(A) < Integer(B) then
Result := -1
else
Result := 0;
end;
}
{$JPPDEFINEMACRO VALUESCOMPARE
function TJclIntfSingleSortedMap.ValuesCompare(const A, B: Single): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPEXPANDMACRO JCLSORTEDMAPIMP(TJclIntfSingleSortedMap,TJclIntfSingleSortedEntry,IJclIntfSingleMap,IJclIntfSingleSortedMap,IJclIntfSet,IJclIntfIterator,IJclSingleCollection,,,,const ,IInterface,nil,const ,Single,0.0)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO KEYSCOMPARE}
{$JPPUNDEFMACRO VALUESCOMPARE}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclSingleSingleSortedMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclSingleSingleSortedMap.Create(FSize);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclSingleArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclSingleArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclSingleSingleSortedMap.FreeKey(var Key: Single): Single;
begin
Result := Key;
Key := 0.0;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclSingleSingleSortedMap.FreeValue(var Value: Single): Single;
begin
Result := Value;
Value := 0.0;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO KEYSCOMPARE
function TJclSingleSingleSortedMap.KeysCompare(const A, B: Single): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPDEFINEMACRO VALUESCOMPARE
function TJclSingleSingleSortedMap.ValuesCompare(const A, B: Single): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPEXPANDMACRO JCLSORTEDMAPIMP(TJclSingleSingleSortedMap,TJclSingleSingleSortedEntry,IJclSingleSingleMap,IJclSingleSingleSortedMap,IJclSingleSet,IJclSingleIterator,IJclSingleCollection,,,,const ,Single,0.0,const ,Single,0.0)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO KEYSCOMPARE}
{$JPPUNDEFMACRO VALUESCOMPARE}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclDoubleIntfSortedMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclDoubleIntfSortedMap.Create(FSize);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclDoubleArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclIntfArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclDoubleIntfSortedMap.FreeKey(var Key: Double): Double;
begin
Result := Key;
Key := 0.0;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclDoubleIntfSortedMap.FreeValue(var Value: IInterface): IInterface;
begin
Result := Value;
Value := nil;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO KEYSCOMPARE
function TJclDoubleIntfSortedMap.KeysCompare(const A, B: Double): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPDEFINEMACRO VALUESCOMPARE
function TJclDoubleIntfSortedMap.ValuesCompare(const A, B: IInterface): Integer;
begin
if Integer(A) > Integer(B) then
Result := 1
else
if Integer(A) < Integer(B) then
Result := -1
else
Result := 0;
end;
}
{$JPPEXPANDMACRO JCLSORTEDMAPIMP(TJclDoubleIntfSortedMap,TJclDoubleIntfSortedEntry,IJclDoubleIntfMap,IJclDoubleIntfSortedMap,IJclDoubleSet,IJclDoubleIterator,IJclIntfCollection,,,,const ,Double,0.0,const ,IInterface,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO KEYSCOMPARE}
{$JPPUNDEFMACRO VALUESCOMPARE}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclIntfDoubleSortedMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclIntfDoubleSortedMap.Create(FSize);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclIntfArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclDoubleArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclIntfDoubleSortedMap.FreeKey(var Key: IInterface): IInterface;
begin
Result := Key;
Key := nil;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclIntfDoubleSortedMap.FreeValue(var Value: Double): Double;
begin
Result := Value;
Value := 0.0;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO KEYSCOMPARE
function TJclIntfDoubleSortedMap.KeysCompare(const A, B: IInterface): Integer;
begin
if Integer(A) > Integer(B) then
Result := 1
else
if Integer(A) < Integer(B) then
Result := -1
else
Result := 0;
end;
}
{$JPPDEFINEMACRO VALUESCOMPARE
function TJclIntfDoubleSortedMap.ValuesCompare(const A, B: Double): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPEXPANDMACRO JCLSORTEDMAPIMP(TJclIntfDoubleSortedMap,TJclIntfDoubleSortedEntry,IJclIntfDoubleMap,IJclIntfDoubleSortedMap,IJclIntfSet,IJclIntfIterator,IJclDoubleCollection,,,,const ,IInterface,nil,const ,Double,0.0)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO KEYSCOMPARE}
{$JPPUNDEFMACRO VALUESCOMPARE}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclDoubleDoubleSortedMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclDoubleDoubleSortedMap.Create(FSize);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclDoubleArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclDoubleArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclDoubleDoubleSortedMap.FreeKey(var Key: Double): Double;
begin
Result := Key;
Key := 0.0;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclDoubleDoubleSortedMap.FreeValue(var Value: Double): Double;
begin
Result := Value;
Value := 0.0;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO KEYSCOMPARE
function TJclDoubleDoubleSortedMap.KeysCompare(const A, B: Double): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPDEFINEMACRO VALUESCOMPARE
function TJclDoubleDoubleSortedMap.ValuesCompare(const A, B: Double): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPEXPANDMACRO JCLSORTEDMAPIMP(TJclDoubleDoubleSortedMap,TJclDoubleDoubleSortedEntry,IJclDoubleDoubleMap,IJclDoubleDoubleSortedMap,IJclDoubleSet,IJclDoubleIterator,IJclDoubleCollection,,,,const ,Double,0.0,const ,Double,0.0)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO KEYSCOMPARE}
{$JPPUNDEFMACRO VALUESCOMPARE}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclExtendedIntfSortedMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclExtendedIntfSortedMap.Create(FSize);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclExtendedArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclIntfArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclExtendedIntfSortedMap.FreeKey(var Key: Extended): Extended;
begin
Result := Key;
Key := 0.0;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclExtendedIntfSortedMap.FreeValue(var Value: IInterface): IInterface;
begin
Result := Value;
Value := nil;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO KEYSCOMPARE
function TJclExtendedIntfSortedMap.KeysCompare(const A, B: Extended): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPDEFINEMACRO VALUESCOMPARE
function TJclExtendedIntfSortedMap.ValuesCompare(const A, B: IInterface): Integer;
begin
if Integer(A) > Integer(B) then
Result := 1
else
if Integer(A) < Integer(B) then
Result := -1
else
Result := 0;
end;
}
{$JPPEXPANDMACRO JCLSORTEDMAPIMP(TJclExtendedIntfSortedMap,TJclExtendedIntfSortedEntry,IJclExtendedIntfMap,IJclExtendedIntfSortedMap,IJclExtendedSet,IJclExtendedIterator,IJclIntfCollection,,,,const ,Extended,0.0,const ,IInterface,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO KEYSCOMPARE}
{$JPPUNDEFMACRO VALUESCOMPARE}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclIntfExtendedSortedMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclIntfExtendedSortedMap.Create(FSize);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclIntfArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclExtendedArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclIntfExtendedSortedMap.FreeKey(var Key: IInterface): IInterface;
begin
Result := Key;
Key := nil;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclIntfExtendedSortedMap.FreeValue(var Value: Extended): Extended;
begin
Result := Value;
Value := 0.0;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO KEYSCOMPARE
function TJclIntfExtendedSortedMap.KeysCompare(const A, B: IInterface): Integer;
begin
if Integer(A) > Integer(B) then
Result := 1
else
if Integer(A) < Integer(B) then
Result := -1
else
Result := 0;
end;
}
{$JPPDEFINEMACRO VALUESCOMPARE
function TJclIntfExtendedSortedMap.ValuesCompare(const A, B: Extended): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPEXPANDMACRO JCLSORTEDMAPIMP(TJclIntfExtendedSortedMap,TJclIntfExtendedSortedEntry,IJclIntfExtendedMap,IJclIntfExtendedSortedMap,IJclIntfSet,IJclIntfIterator,IJclExtendedCollection,,,,const ,IInterface,nil,const ,Extended,0.0)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO KEYSCOMPARE}
{$JPPUNDEFMACRO VALUESCOMPARE}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclExtendedExtendedSortedMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclExtendedExtendedSortedMap.Create(FSize);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclExtendedArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclExtendedArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclExtendedExtendedSortedMap.FreeKey(var Key: Extended): Extended;
begin
Result := Key;
Key := 0.0;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclExtendedExtendedSortedMap.FreeValue(var Value: Extended): Extended;
begin
Result := Value;
Value := 0.0;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO KEYSCOMPARE
function TJclExtendedExtendedSortedMap.KeysCompare(const A, B: Extended): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPDEFINEMACRO VALUESCOMPARE
function TJclExtendedExtendedSortedMap.ValuesCompare(const A, B: Extended): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPEXPANDMACRO JCLSORTEDMAPIMP(TJclExtendedExtendedSortedMap,TJclExtendedExtendedSortedEntry,IJclExtendedExtendedMap,IJclExtendedExtendedSortedMap,IJclExtendedSet,IJclExtendedIterator,IJclExtendedCollection,,,,const ,Extended,0.0,const ,Extended,0.0)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO KEYSCOMPARE}
{$JPPUNDEFMACRO VALUESCOMPARE}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclIntegerIntfSortedMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclIntegerIntfSortedMap.Create(FSize);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclIntegerArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclIntfArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclIntegerIntfSortedMap.FreeKey(var Key: Integer): Integer;
begin
Result := Key;
Key := 0;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclIntegerIntfSortedMap.FreeValue(var Value: IInterface): IInterface;
begin
Result := Value;
Value := nil;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO KEYSCOMPARE
function TJclIntegerIntfSortedMap.KeysCompare(A, B: Integer): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPDEFINEMACRO VALUESCOMPARE
function TJclIntegerIntfSortedMap.ValuesCompare(const A, B: IInterface): Integer;
begin
if Integer(A) > Integer(B) then
Result := 1
else
if Integer(A) < Integer(B) then
Result := -1
else
Result := 0;
end;
}
{$JPPEXPANDMACRO JCLSORTEDMAPIMP(TJclIntegerIntfSortedMap,TJclIntegerIntfSortedEntry,IJclIntegerIntfMap,IJclIntegerIntfSortedMap,IJclIntegerSet,IJclIntegerIterator,IJclIntfCollection,,,,,Integer,0,const ,IInterface,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO KEYSCOMPARE}
{$JPPUNDEFMACRO VALUESCOMPARE}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclIntfIntegerSortedMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclIntfIntegerSortedMap.Create(FSize);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclIntfArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclIntegerArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclIntfIntegerSortedMap.FreeKey(var Key: IInterface): IInterface;
begin
Result := Key;
Key := nil;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclIntfIntegerSortedMap.FreeValue(var Value: Integer): Integer;
begin
Result := Value;
Value := 0;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO KEYSCOMPARE
function TJclIntfIntegerSortedMap.KeysCompare(const A, B: IInterface): Integer;
begin
if Integer(A) > Integer(B) then
Result := 1
else
if Integer(A) < Integer(B) then
Result := -1
else
Result := 0;
end;
}
{$JPPDEFINEMACRO VALUESCOMPARE
function TJclIntfIntegerSortedMap.ValuesCompare(A, B: Integer): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPEXPANDMACRO JCLSORTEDMAPIMP(TJclIntfIntegerSortedMap,TJclIntfIntegerSortedEntry,IJclIntfIntegerMap,IJclIntfIntegerSortedMap,IJclIntfSet,IJclIntfIterator,IJclIntegerCollection,,,,const ,IInterface,nil,,Integer,0)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO KEYSCOMPARE}
{$JPPUNDEFMACRO VALUESCOMPARE}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclIntegerIntegerSortedMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclIntegerIntegerSortedMap.Create(FSize);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclIntegerArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclIntegerArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclIntegerIntegerSortedMap.FreeKey(var Key: Integer): Integer;
begin
Result := Key;
Key := 0;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclIntegerIntegerSortedMap.FreeValue(var Value: Integer): Integer;
begin
Result := Value;
Value := 0;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO KEYSCOMPARE
function TJclIntegerIntegerSortedMap.KeysCompare(A, B: Integer): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPDEFINEMACRO VALUESCOMPARE
function TJclIntegerIntegerSortedMap.ValuesCompare(A, B: Integer): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPEXPANDMACRO JCLSORTEDMAPIMP(TJclIntegerIntegerSortedMap,TJclIntegerIntegerSortedEntry,IJclIntegerIntegerMap,IJclIntegerIntegerSortedMap,IJclIntegerSet,IJclIntegerIterator,IJclIntegerCollection,,,,,Integer,0,,Integer,0)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO KEYSCOMPARE}
{$JPPUNDEFMACRO VALUESCOMPARE}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclCardinalIntfSortedMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclCardinalIntfSortedMap.Create(FSize);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclCardinalArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclIntfArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclCardinalIntfSortedMap.FreeKey(var Key: Cardinal): Cardinal;
begin
Result := Key;
Key := 0;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclCardinalIntfSortedMap.FreeValue(var Value: IInterface): IInterface;
begin
Result := Value;
Value := nil;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO KEYSCOMPARE
function TJclCardinalIntfSortedMap.KeysCompare(A, B: Cardinal): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPDEFINEMACRO VALUESCOMPARE
function TJclCardinalIntfSortedMap.ValuesCompare(const A, B: IInterface): Integer;
begin
if Integer(A) > Integer(B) then
Result := 1
else
if Integer(A) < Integer(B) then
Result := -1
else
Result := 0;
end;
}
{$JPPEXPANDMACRO JCLSORTEDMAPIMP(TJclCardinalIntfSortedMap,TJclCardinalIntfSortedEntry,IJclCardinalIntfMap,IJclCardinalIntfSortedMap,IJclCardinalSet,IJclCardinalIterator,IJclIntfCollection,,,,,Cardinal,0,const ,IInterface,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO KEYSCOMPARE}
{$JPPUNDEFMACRO VALUESCOMPARE}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclIntfCardinalSortedMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclIntfCardinalSortedMap.Create(FSize);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclIntfArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclCardinalArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclIntfCardinalSortedMap.FreeKey(var Key: IInterface): IInterface;
begin
Result := Key;
Key := nil;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclIntfCardinalSortedMap.FreeValue(var Value: Cardinal): Cardinal;
begin
Result := Value;
Value := 0;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO KEYSCOMPARE
function TJclIntfCardinalSortedMap.KeysCompare(const A, B: IInterface): Integer;
begin
if Integer(A) > Integer(B) then
Result := 1
else
if Integer(A) < Integer(B) then
Result := -1
else
Result := 0;
end;
}
{$JPPDEFINEMACRO VALUESCOMPARE
function TJclIntfCardinalSortedMap.ValuesCompare(A, B: Cardinal): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPEXPANDMACRO JCLSORTEDMAPIMP(TJclIntfCardinalSortedMap,TJclIntfCardinalSortedEntry,IJclIntfCardinalMap,IJclIntfCardinalSortedMap,IJclIntfSet,IJclIntfIterator,IJclCardinalCollection,,,,const ,IInterface,nil,,Cardinal,0)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO KEYSCOMPARE}
{$JPPUNDEFMACRO VALUESCOMPARE}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclCardinalCardinalSortedMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclCardinalCardinalSortedMap.Create(FSize);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclCardinalArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclCardinalArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclCardinalCardinalSortedMap.FreeKey(var Key: Cardinal): Cardinal;
begin
Result := Key;
Key := 0;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclCardinalCardinalSortedMap.FreeValue(var Value: Cardinal): Cardinal;
begin
Result := Value;
Value := 0;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO KEYSCOMPARE
function TJclCardinalCardinalSortedMap.KeysCompare(A, B: Cardinal): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPDEFINEMACRO VALUESCOMPARE
function TJclCardinalCardinalSortedMap.ValuesCompare(A, B: Cardinal): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPEXPANDMACRO JCLSORTEDMAPIMP(TJclCardinalCardinalSortedMap,TJclCardinalCardinalSortedEntry,IJclCardinalCardinalMap,IJclCardinalCardinalSortedMap,IJclCardinalSet,IJclCardinalIterator,IJclCardinalCollection,,,,,Cardinal,0,,Cardinal,0)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO KEYSCOMPARE}
{$JPPUNDEFMACRO VALUESCOMPARE}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclInt64IntfSortedMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclInt64IntfSortedMap.Create(FSize);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclInt64ArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclIntfArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclInt64IntfSortedMap.FreeKey(var Key: Int64): Int64;
begin
Result := Key;
Key := 0;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclInt64IntfSortedMap.FreeValue(var Value: IInterface): IInterface;
begin
Result := Value;
Value := nil;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO KEYSCOMPARE
function TJclInt64IntfSortedMap.KeysCompare(const A, B: Int64): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPDEFINEMACRO VALUESCOMPARE
function TJclInt64IntfSortedMap.ValuesCompare(const A, B: IInterface): Integer;
begin
if Integer(A) > Integer(B) then
Result := 1
else
if Integer(A) < Integer(B) then
Result := -1
else
Result := 0;
end;
}
{$JPPEXPANDMACRO JCLSORTEDMAPIMP(TJclInt64IntfSortedMap,TJclInt64IntfSortedEntry,IJclInt64IntfMap,IJclInt64IntfSortedMap,IJclInt64Set,IJclInt64Iterator,IJclIntfCollection,,,,const ,Int64,0,const ,IInterface,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO KEYSCOMPARE}
{$JPPUNDEFMACRO VALUESCOMPARE}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclIntfInt64SortedMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclIntfInt64SortedMap.Create(FSize);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclIntfArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclInt64ArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclIntfInt64SortedMap.FreeKey(var Key: IInterface): IInterface;
begin
Result := Key;
Key := nil;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclIntfInt64SortedMap.FreeValue(var Value: Int64): Int64;
begin
Result := Value;
Value := 0;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO KEYSCOMPARE
function TJclIntfInt64SortedMap.KeysCompare(const A, B: IInterface): Integer;
begin
if Integer(A) > Integer(B) then
Result := 1
else
if Integer(A) < Integer(B) then
Result := -1
else
Result := 0;
end;
}
{$JPPDEFINEMACRO VALUESCOMPARE
function TJclIntfInt64SortedMap.ValuesCompare(const A, B: Int64): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPEXPANDMACRO JCLSORTEDMAPIMP(TJclIntfInt64SortedMap,TJclIntfInt64SortedEntry,IJclIntfInt64Map,IJclIntfInt64SortedMap,IJclIntfSet,IJclIntfIterator,IJclInt64Collection,,,,const ,IInterface,nil,const ,Int64,0)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO KEYSCOMPARE}
{$JPPUNDEFMACRO VALUESCOMPARE}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclInt64Int64SortedMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclInt64Int64SortedMap.Create(FSize);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclInt64ArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclInt64ArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclInt64Int64SortedMap.FreeKey(var Key: Int64): Int64;
begin
Result := Key;
Key := 0;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclInt64Int64SortedMap.FreeValue(var Value: Int64): Int64;
begin
Result := Value;
Value := 0;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO KEYSCOMPARE
function TJclInt64Int64SortedMap.KeysCompare(const A, B: Int64): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPDEFINEMACRO VALUESCOMPARE
function TJclInt64Int64SortedMap.ValuesCompare(const A, B: Int64): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPEXPANDMACRO JCLSORTEDMAPIMP(TJclInt64Int64SortedMap,TJclInt64Int64SortedEntry,IJclInt64Int64Map,IJclInt64Int64SortedMap,IJclInt64Set,IJclInt64Iterator,IJclInt64Collection,,,,const ,Int64,0,const ,Int64,0)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO KEYSCOMPARE}
{$JPPUNDEFMACRO VALUESCOMPARE}
{$IFNDEF CLR}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclPtrIntfSortedMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclPtrIntfSortedMap.Create(FSize);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclPtrArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclIntfArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclPtrIntfSortedMap.FreeKey(var Key: Pointer): Pointer;
begin
Result := Key;
Key := nil;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclPtrIntfSortedMap.FreeValue(var Value: IInterface): IInterface;
begin
Result := Value;
Value := nil;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO KEYSCOMPARE
function TJclPtrIntfSortedMap.KeysCompare(A, B: Pointer): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPDEFINEMACRO VALUESCOMPARE
function TJclPtrIntfSortedMap.ValuesCompare(const A, B: IInterface): Integer;
begin
if Integer(A) > Integer(B) then
Result := 1
else
if Integer(A) < Integer(B) then
Result := -1
else
Result := 0;
end;
}
{$JPPEXPANDMACRO JCLSORTEDMAPIMP(TJclPtrIntfSortedMap,TJclPtrIntfSortedEntry,IJclPtrIntfMap,IJclPtrIntfSortedMap,IJclPtrSet,IJclPtrIterator,IJclIntfCollection,,,,,Pointer,nil,const ,IInterface,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO KEYSCOMPARE}
{$JPPUNDEFMACRO VALUESCOMPARE}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclIntfPtrSortedMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclIntfPtrSortedMap.Create(FSize);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclIntfArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclPtrArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclIntfPtrSortedMap.FreeKey(var Key: IInterface): IInterface;
begin
Result := Key;
Key := nil;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclIntfPtrSortedMap.FreeValue(var Value: Pointer): Pointer;
begin
Result := Value;
Value := nil;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO KEYSCOMPARE
function TJclIntfPtrSortedMap.KeysCompare(const A, B: IInterface): Integer;
begin
if Integer(A) > Integer(B) then
Result := 1
else
if Integer(A) < Integer(B) then
Result := -1
else
Result := 0;
end;
}
{$JPPDEFINEMACRO VALUESCOMPARE
function TJclIntfPtrSortedMap.ValuesCompare(A, B: Pointer): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPEXPANDMACRO JCLSORTEDMAPIMP(TJclIntfPtrSortedMap,TJclIntfPtrSortedEntry,IJclIntfPtrMap,IJclIntfPtrSortedMap,IJclIntfSet,IJclIntfIterator,IJclPtrCollection,,,,const ,IInterface,nil,,Pointer,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO KEYSCOMPARE}
{$JPPUNDEFMACRO VALUESCOMPARE}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclPtrPtrSortedMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclPtrPtrSortedMap.Create(FSize);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclPtrArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclPtrArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclPtrPtrSortedMap.FreeKey(var Key: Pointer): Pointer;
begin
Result := Key;
Key := nil;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclPtrPtrSortedMap.FreeValue(var Value: Pointer): Pointer;
begin
Result := Value;
Value := nil;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO KEYSCOMPARE
function TJclPtrPtrSortedMap.KeysCompare(A, B: Pointer): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPDEFINEMACRO VALUESCOMPARE
function TJclPtrPtrSortedMap.ValuesCompare(A, B: Pointer): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPEXPANDMACRO JCLSORTEDMAPIMP(TJclPtrPtrSortedMap,TJclPtrPtrSortedEntry,IJclPtrPtrMap,IJclPtrPtrSortedMap,IJclPtrSet,IJclPtrIterator,IJclPtrCollection,,,,,Pointer,nil,,Pointer,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO KEYSCOMPARE}
{$JPPUNDEFMACRO VALUESCOMPARE}
{$ENDIF ~CLR}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclIntfSortedMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclIntfSortedMap.Create(FSize, False);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclIntfArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclArrayList.Create(Param, False)}
{$JPPDEFINEMACRO FREEKEY
function TJclIntfSortedMap.FreeKey(var Key: IInterface): IInterface;
begin
Result := Key;
Key := nil;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclIntfSortedMap.FreeValue(var Value: TObject): TObject;
begin
if FOwnsValues then
begin
Result := nil;
FreeAndNil(Value);
end
else
begin
Result := Value;
Value := nil;
end;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES
function TJclIntfSortedMap.GetOwnsValues: Boolean;
begin
Result := FOwnsValues;
end;
}
{$JPPDEFINEMACRO KEYSCOMPARE
function TJclIntfSortedMap.KeysCompare(const A, B: IInterface): Integer;
begin
if Integer(A) > Integer(B) then
Result := 1
else
if Integer(A) < Integer(B) then
Result := -1
else
Result := 0;
end;
}
{$JPPDEFINEMACRO VALUESCOMPARE
function TJclIntfSortedMap.ValuesCompare(A, B: TObject): Integer;
begin
if Integer(A) > Integer(B) then
Result := 1
else
if Integer(A) < Integer(B) then
Result := -1
else
Result := 0;
end;
}
{$JPPEXPANDMACRO JCLSORTEDMAPIMP(TJclIntfSortedMap,TJclIntfSortedEntry,IJclIntfMap,IJclIntfSortedMap,IJclIntfSet,IJclIntfIterator,IJclCollection,,; AOwnsValues: Boolean,
FOwnsValues := AOwnsValues;,const ,IInterface,nil,,TObject,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO KEYSCOMPARE}
{$JPPUNDEFMACRO VALUESCOMPARE}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclAnsiStrSortedMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclAnsiStrSortedMap.Create(FSize, False);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclAnsiStrArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclArrayList.Create(Param, False)}
{$JPPDEFINEMACRO FREEKEY
function TJclAnsiStrSortedMap.FreeKey(var Key: AnsiString): AnsiString;
begin
Result := Key;
Key := '';
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclAnsiStrSortedMap.FreeValue(var Value: TObject): TObject;
begin
if FOwnsValues then
begin
Result := nil;
FreeAndNil(Value);
end
else
begin
Result := Value;
Value := nil;
end;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES
function TJclAnsiStrSortedMap.GetOwnsValues: Boolean;
begin
Result := FOwnsValues;
end;
}
{$JPPDEFINEMACRO KEYSCOMPARE
function TJclAnsiStrSortedMap.KeysCompare(const A, B: AnsiString): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPDEFINEMACRO VALUESCOMPARE
function TJclAnsiStrSortedMap.ValuesCompare(A, B: TObject): Integer;
begin
if Integer(A) > Integer(B) then
Result := 1
else
if Integer(A) < Integer(B) then
Result := -1
else
Result := 0;
end;
}
{$JPPEXPANDMACRO JCLSORTEDMAPIMP(TJclAnsiStrSortedMap,TJclAnsiStrSortedEntry,IJclAnsiStrMap,IJclAnsiStrSortedMap,IJclAnsiStrSet,IJclAnsiStrIterator,IJclCollection,,; AOwnsValues: Boolean,
FOwnsValues := AOwnsValues;,const ,AnsiString,'',,TObject,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO KEYSCOMPARE}
{$JPPUNDEFMACRO VALUESCOMPARE}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclWideStrSortedMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclWideStrSortedMap.Create(FSize, False);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclWideStrArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclArrayList.Create(Param, False)}
{$JPPDEFINEMACRO FREEKEY
function TJclWideStrSortedMap.FreeKey(var Key: WideString): WideString;
begin
Result := Key;
Key := '';
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclWideStrSortedMap.FreeValue(var Value: TObject): TObject;
begin
if FOwnsValues then
begin
Result := nil;
FreeAndNil(Value);
end
else
begin
Result := Value;
Value := nil;
end;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES
function TJclWideStrSortedMap.GetOwnsValues: Boolean;
begin
Result := FOwnsValues;
end;
}
{$JPPDEFINEMACRO KEYSCOMPARE
function TJclWideStrSortedMap.KeysCompare(const A, B: WideString): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPDEFINEMACRO VALUESCOMPARE
function TJclWideStrSortedMap.ValuesCompare(A, B: TObject): Integer;
begin
if Integer(A) > Integer(B) then
Result := 1
else
if Integer(A) < Integer(B) then
Result := -1
else
Result := 0;
end;
}
{$JPPEXPANDMACRO JCLSORTEDMAPIMP(TJclWideStrSortedMap,TJclWideStrSortedEntry,IJclWideStrMap,IJclWideStrSortedMap,IJclWideStrSet,IJclWideStrIterator,IJclCollection,,; AOwnsValues: Boolean,
FOwnsValues := AOwnsValues;,const ,WideString,'',,TObject,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO KEYSCOMPARE}
{$JPPUNDEFMACRO VALUESCOMPARE}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclSingleSortedMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclSingleSortedMap.Create(FSize, False);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclSingleArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclArrayList.Create(Param, False)}
{$JPPDEFINEMACRO FREEKEY
function TJclSingleSortedMap.FreeKey(var Key: Single): Single;
begin
Result := Key;
Key := 0.0;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclSingleSortedMap.FreeValue(var Value: TObject): TObject;
begin
if FOwnsValues then
begin
Result := nil;
FreeAndNil(Value);
end
else
begin
Result := Value;
Value := nil;
end;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES
function TJclSingleSortedMap.GetOwnsValues: Boolean;
begin
Result := FOwnsValues;
end;
}
{$JPPDEFINEMACRO KEYSCOMPARE
function TJclSingleSortedMap.KeysCompare(const A, B: Single): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPDEFINEMACRO VALUESCOMPARE
function TJclSingleSortedMap.ValuesCompare(A, B: TObject): Integer;
begin
if Integer(A) > Integer(B) then
Result := 1
else
if Integer(A) < Integer(B) then
Result := -1
else
Result := 0;
end;
}
{$JPPEXPANDMACRO JCLSORTEDMAPIMP(TJclSingleSortedMap,TJclSingleSortedEntry,IJclSingleMap,IJclSingleSortedMap,IJclSingleSet,IJclSingleIterator,IJclCollection,,; AOwnsValues: Boolean,
FOwnsValues := AOwnsValues;,const ,Single,0.0,,TObject,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO KEYSCOMPARE}
{$JPPUNDEFMACRO VALUESCOMPARE}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclDoubleSortedMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclDoubleSortedMap.Create(FSize, False);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclDoubleArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclArrayList.Create(Param, False)}
{$JPPDEFINEMACRO FREEKEY
function TJclDoubleSortedMap.FreeKey(var Key: Double): Double;
begin
Result := Key;
Key := 0.0;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclDoubleSortedMap.FreeValue(var Value: TObject): TObject;
begin
if FOwnsValues then
begin
Result := nil;
FreeAndNil(Value);
end
else
begin
Result := Value;
Value := nil;
end;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES
function TJclDoubleSortedMap.GetOwnsValues: Boolean;
begin
Result := FOwnsValues;
end;
}
{$JPPDEFINEMACRO KEYSCOMPARE
function TJclDoubleSortedMap.KeysCompare(const A, B: Double): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPDEFINEMACRO VALUESCOMPARE
function TJclDoubleSortedMap.ValuesCompare(A, B: TObject): Integer;
begin
if Integer(A) > Integer(B) then
Result := 1
else
if Integer(A) < Integer(B) then
Result := -1
else
Result := 0;
end;
}
{$JPPEXPANDMACRO JCLSORTEDMAPIMP(TJclDoubleSortedMap,TJclDoubleSortedEntry,IJclDoubleMap,IJclDoubleSortedMap,IJclDoubleSet,IJclDoubleIterator,IJclCollection,,; AOwnsValues: Boolean,
FOwnsValues := AOwnsValues;,const ,Double,0.0,,TObject,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO KEYSCOMPARE}
{$JPPUNDEFMACRO VALUESCOMPARE}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclExtendedSortedMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclExtendedSortedMap.Create(FSize, False);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclExtendedArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclArrayList.Create(Param, False)}
{$JPPDEFINEMACRO FREEKEY
function TJclExtendedSortedMap.FreeKey(var Key: Extended): Extended;
begin
Result := Key;
Key := 0.0;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclExtendedSortedMap.FreeValue(var Value: TObject): TObject;
begin
if FOwnsValues then
begin
Result := nil;
FreeAndNil(Value);
end
else
begin
Result := Value;
Value := nil;
end;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES
function TJclExtendedSortedMap.GetOwnsValues: Boolean;
begin
Result := FOwnsValues;
end;
}
{$JPPDEFINEMACRO KEYSCOMPARE
function TJclExtendedSortedMap.KeysCompare(const A, B: Extended): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPDEFINEMACRO VALUESCOMPARE
function TJclExtendedSortedMap.ValuesCompare(A, B: TObject): Integer;
begin
if Integer(A) > Integer(B) then
Result := 1
else
if Integer(A) < Integer(B) then
Result := -1
else
Result := 0;
end;
}
{$JPPEXPANDMACRO JCLSORTEDMAPIMP(TJclExtendedSortedMap,TJclExtendedSortedEntry,IJclExtendedMap,IJclExtendedSortedMap,IJclExtendedSet,IJclExtendedIterator,IJclCollection,,; AOwnsValues: Boolean,
FOwnsValues := AOwnsValues;,const ,Extended,0.0,,TObject,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO KEYSCOMPARE}
{$JPPUNDEFMACRO VALUESCOMPARE}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclIntegerSortedMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclIntegerSortedMap.Create(FSize, False);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclIntegerArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclArrayList.Create(Param, False)}
{$JPPDEFINEMACRO FREEKEY
function TJclIntegerSortedMap.FreeKey(var Key: Integer): Integer;
begin
Result := Key;
Key := 0;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclIntegerSortedMap.FreeValue(var Value: TObject): TObject;
begin
if FOwnsValues then
begin
Result := nil;
FreeAndNil(Value);
end
else
begin
Result := Value;
Value := nil;
end;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES
function TJclIntegerSortedMap.GetOwnsValues: Boolean;
begin
Result := FOwnsValues;
end;
}
{$JPPDEFINEMACRO KEYSCOMPARE
function TJclIntegerSortedMap.KeysCompare(A, B: Integer): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPDEFINEMACRO VALUESCOMPARE
function TJclIntegerSortedMap.ValuesCompare(A, B: TObject): Integer;
begin
if Integer(A) > Integer(B) then
Result := 1
else
if Integer(A) < Integer(B) then
Result := -1
else
Result := 0;
end;
}
{$JPPEXPANDMACRO JCLSORTEDMAPIMP(TJclIntegerSortedMap,TJclIntegerSortedEntry,IJclIntegerMap,IJclIntegerSortedMap,IJclIntegerSet,IJclIntegerIterator,IJclCollection,,; AOwnsValues: Boolean,
FOwnsValues := AOwnsValues;,,Integer,0,,TObject,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO KEYSCOMPARE}
{$JPPUNDEFMACRO VALUESCOMPARE}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclCardinalSortedMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclCardinalSortedMap.Create(FSize, False);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclCardinalArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclArrayList.Create(Param, False)}
{$JPPDEFINEMACRO FREEKEY
function TJclCardinalSortedMap.FreeKey(var Key: Cardinal): Cardinal;
begin
Result := Key;
Key := 0;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclCardinalSortedMap.FreeValue(var Value: TObject): TObject;
begin
if FOwnsValues then
begin
Result := nil;
FreeAndNil(Value);
end
else
begin
Result := Value;
Value := nil;
end;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES
function TJclCardinalSortedMap.GetOwnsValues: Boolean;
begin
Result := FOwnsValues;
end;
}
{$JPPDEFINEMACRO KEYSCOMPARE
function TJclCardinalSortedMap.KeysCompare(A, B: Cardinal): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPDEFINEMACRO VALUESCOMPARE
function TJclCardinalSortedMap.ValuesCompare(A, B: TObject): Integer;
begin
if Integer(A) > Integer(B) then
Result := 1
else
if Integer(A) < Integer(B) then
Result := -1
else
Result := 0;
end;
}
{$JPPEXPANDMACRO JCLSORTEDMAPIMP(TJclCardinalSortedMap,TJclCardinalSortedEntry,IJclCardinalMap,IJclCardinalSortedMap,IJclCardinalSet,IJclCardinalIterator,IJclCollection,,; AOwnsValues: Boolean,
FOwnsValues := AOwnsValues;,,Cardinal,0,,TObject,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO KEYSCOMPARE}
{$JPPUNDEFMACRO VALUESCOMPARE}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclInt64SortedMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclInt64SortedMap.Create(FSize, False);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclInt64ArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclArrayList.Create(Param, False)}
{$JPPDEFINEMACRO FREEKEY
function TJclInt64SortedMap.FreeKey(var Key: Int64): Int64;
begin
Result := Key;
Key := 0;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclInt64SortedMap.FreeValue(var Value: TObject): TObject;
begin
if FOwnsValues then
begin
Result := nil;
FreeAndNil(Value);
end
else
begin
Result := Value;
Value := nil;
end;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES
function TJclInt64SortedMap.GetOwnsValues: Boolean;
begin
Result := FOwnsValues;
end;
}
{$JPPDEFINEMACRO KEYSCOMPARE
function TJclInt64SortedMap.KeysCompare(const A, B: Int64): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPDEFINEMACRO VALUESCOMPARE
function TJclInt64SortedMap.ValuesCompare(A, B: TObject): Integer;
begin
if Integer(A) > Integer(B) then
Result := 1
else
if Integer(A) < Integer(B) then
Result := -1
else
Result := 0;
end;
}
{$JPPEXPANDMACRO JCLSORTEDMAPIMP(TJclInt64SortedMap,TJclInt64SortedEntry,IJclInt64Map,IJclInt64SortedMap,IJclInt64Set,IJclInt64Iterator,IJclCollection,,; AOwnsValues: Boolean,
FOwnsValues := AOwnsValues;,const ,Int64,0,,TObject,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO KEYSCOMPARE}
{$JPPUNDEFMACRO VALUESCOMPARE}
{$IFNDEF CLR}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclPtrSortedMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclPtrSortedMap.Create(FSize, False);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclPtrArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclArrayList.Create(Param, False)}
{$JPPDEFINEMACRO FREEKEY
function TJclPtrSortedMap.FreeKey(var Key: Pointer): Pointer;
begin
Result := Key;
Key := nil;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclPtrSortedMap.FreeValue(var Value: TObject): TObject;
begin
if FOwnsValues then
begin
Result := nil;
FreeAndNil(Value);
end
else
begin
Result := Value;
Value := nil;
end;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES
function TJclPtrSortedMap.GetOwnsValues: Boolean;
begin
Result := FOwnsValues;
end;
}
{$JPPDEFINEMACRO KEYSCOMPARE
function TJclPtrSortedMap.KeysCompare(A, B: Pointer): Integer;
begin
Result := ItemsCompare(A, B);
end;
}
{$JPPDEFINEMACRO VALUESCOMPARE
function TJclPtrSortedMap.ValuesCompare(A, B: TObject): Integer;
begin
if Integer(A) > Integer(B) then
Result := 1
else
if Integer(A) < Integer(B) then
Result := -1
else
Result := 0;
end;
}
{$JPPEXPANDMACRO JCLSORTEDMAPIMP(TJclPtrSortedMap,TJclPtrSortedEntry,IJclPtrMap,IJclPtrSortedMap,IJclPtrSet,IJclPtrIterator,IJclCollection,,; AOwnsValues: Boolean,
FOwnsValues := AOwnsValues;,,Pointer,nil,,TObject,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO KEYSCOMPARE}
{$JPPUNDEFMACRO VALUESCOMPARE}
{$ENDIF ~CLR}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclSortedMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclSortedMap.Create(FSize, False, False);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclArraySet.Create(Param, False)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclArrayList.Create(Param, False)}
{$JPPDEFINEMACRO FREEKEY
function TJclSortedMap.FreeKey(var Key: TObject): TObject;
begin
if FOwnsKeys then
begin
Result := nil;
FreeAndNil(Key);
end
else
begin
Result := Key;
Key := nil;
end;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclSortedMap.FreeValue(var Value: TObject): TObject;
begin
if FOwnsValues then
begin
Result := nil;
FreeAndNil(Value);
end
else
begin
Result := Value;
Value := nil;
end;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS
function TJclSortedMap.GetOWnsKeys: Boolean;
begin
Result := FOwnsKeys;
end;
}
{$JPPDEFINEMACRO GETOWNSVALUES
function TJclSortedMap.GetOwnsValues: Boolean;
begin
Result := FOwnsValues;
end;
}
{$JPPDEFINEMACRO KEYSCOMPARE
function TJclSortedMap.KeysCompare(A, B: TObject): Integer;
begin
if Integer(A) > Integer(B) then
Result := 1
else
if Integer(A) < Integer(B) then
Result := -1
else
Result := 0;
end;
}
{$JPPDEFINEMACRO VALUESCOMPARE
function TJclSortedMap.ValuesCompare(A, B: TObject): Integer;
begin
if Integer(A) > Integer(B) then
Result := 1
else
if Integer(A) < Integer(B) then
Result := -1
else
Result := 0;
end;
}
{$JPPEXPANDMACRO JCLSORTEDMAPIMP(TJclSortedMap,TJclSortedEntry,IJclMap,IJclSortedMap,IJclSet,IJclIterator,IJclCollection,; AOwnsKeys: Boolean,; AOwnsValues: Boolean,
FOwnsKeys := AOwnsKeys;
FOwnsValues := AOwnsValues;,,TObject,nil,,TObject,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO KEYSCOMPARE}
{$JPPUNDEFMACRO VALUESCOMPARE}
{$IFDEF SUPPORTS_GENERICS}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)CreateEmptyArraySet(Param, False)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)CreateEmptyArrayList(Param, False)}
{$JPPDEFINEMACRO FREEKEY
function TJclSortedMap<TKey,TValue>.FreeKey(var Key: TKey): TKey;
begin
if FOwnsKeys then
begin
Result := Default(TKey);
FreeAndNil(Key);
end
else
begin
Result := Key;
Key := Default(TKey);
end;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclSortedMap<TKey,TValue>.FreeValue(var Value: TValue): TValue;
begin
if FOwnsValues then
begin
Result := Default(TValue);
FreeAndNil(Value);
end
else
begin
Result := Value;
Value := Default(TValue);
end;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS
function TJclSortedMap<TKey,TValue>.GetOWnsKeys: Boolean;
begin
Result := FOwnsKeys;
end;
}
{$JPPDEFINEMACRO GETOWNSVALUES
function TJclSortedMap<TKey,TValue>.GetOwnsValues: Boolean;
begin
Result := FOwnsValues;
end;
}
{$JPPDEFINEMACRO KEYSCOMPARE}
{$JPPDEFINEMACRO VALUESCOMPARE}
{$JPPEXPANDMACRO JCLSORTEDMAPIMP(TJclSortedMap<TKey\,TValue>,TJclSortedEntry<TKey\,TValue>,IJclMap<TKey\,TValue>,IJclSortedMap<TKey\,TValue>,IJclSet<TKey>,IJclIterator<TKey>,IJclCollection<TValue>,; AOwnsKeys: Boolean,; AOwnsValues: Boolean,
FOwnsKeys := AOwnsKeys;
FOwnsValues := AOwnsValues;,const ,TKey,Default(TKey),const ,TValue,Default(TValue))}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO KEYSCOMPARE}
{$JPPUNDEFMACRO VALUESCOMPARE}
//=== { TJclSortedMapE<TKey, TValue> } =======================================
constructor TJclSortedMapE<TKey, TValue>.Create(const AKeyComparer: IComparer<TKey>;
const AValueComparer: IComparer<TValue>; const AValueEqualityComparer: IEqualityComparer<TValue>; ACapacity: Integer;
AOwnsValues: Boolean; AOwnsKeys: Boolean);
begin
inherited Create(ACapacity, AOwnsValues, AOwnsKeys);
FKeyComparer := AKeyComparer;
FValueComparer := AValueComparer;
FValueEqualityComparer := AValueEqualityComparer;
end;
procedure TJclSortedMapE<TKey, TValue>.AssignPropertiesTo(Dest: TJclAbstractContainerBase);
var
ADest: TJclSortedMapE<TKey, TValue>;
begin
inherited AssignPropertiesTo(Dest);
if Dest is TJclSortedMapE<TKey, TValue> then
begin
ADest := TJclSortedMapE<TKey, TValue>(Dest);
ADest.FKeyComparer := FKeyComparer;
ADest.FValueComparer := FValueComparer;
end;
end;
function TJclSortedMapE<TKey, TValue>.CreateEmptyArrayList(ACapacity: Integer;
AOwnsObjects: Boolean): IJclCollection<TValue>;
begin
if FValueEqualityComparer = nil then
raise EJclNoEqualityComparerError.Create;
Result := TJclArrayListE<TValue>.Create(FValueEqualityComparer, ACapacity, AOwnsObjects);
end;
function TJclSortedMapE<TKey, TValue>.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclSortedMapE<TKey, TValue>.Create(FKeyComparer, FValueComparer, FValueEqualityComparer, FCapacity,
FOwnsValues, FOwnsKeys);
AssignPropertiesTo(Result);
end;
function TJclSortedMapE<TKey, TValue>.CreateEmptyArraySet(ACapacity: Integer; AOwnsObjects: Boolean): IJclSet<TKey>;
begin
Result := TJclArraySetE<TKey>.Create(FKeyComparer, FCapacity, AOwnsObjects);
end;
function TJclSortedMapE<TKey, TValue>.KeysCompare(const A, B: TKey): Integer;
begin
if KeyComparer = nil then
raise EJclNoComparerError.Create;
Result := KeyComparer.Compare(A, B);
end;
function TJclSortedMapE<TKey, TValue>.ValuesCompare(const A, B: TValue): Integer;
begin
if ValueComparer = nil then
raise EJclNoComparerError.Create;
Result := ValueComparer.Compare(A, B);
end;
//=== { TJclSortedMapF<TKey, TValue> } =======================================
constructor TJclSortedMapF<TKey, TValue>.Create(AKeyCompare: TCompare<TKey>; AValueCompare: TCompare<TValue>;
AValueEqualityCompare: TEqualityCompare<TValue>; ACapacity: Integer; AOwnsValues: Boolean; AOwnsKeys: Boolean);
begin
inherited Create(ACapacity, AOwnsValues, AOwnsKeys);
FKeyCompare := AKeyCompare;
FValueCompare := AValueCompare;
FValueEqualityCompare := AValueEqualityCompare;
end;
procedure TJclSortedMapF<TKey, TValue>.AssignPropertiesTo(Dest: TJclAbstractContainerBase);
var
ADest: TJclSortedMapF<TKey, TValue>;
begin
inherited AssignPropertiesTo(Dest);
if Dest is TJclSortedMapF<TKey, TValue> then
begin
ADest := TJclSortedMapF<TKey, TValue>(Dest);
ADest.FKeyCompare := FKeyCompare;
ADest.FValueCompare := FValueCompare;
end;
end;
function TJclSortedMapF<TKey, TValue>.CreateEmptyArrayList(ACapacity: Integer;
AOwnsObjects: Boolean): IJclCollection<TValue>;
begin
if not Assigned(FValueEqualityCompare) then
raise EJclNoEqualityComparerError.Create;
Result := TJclArrayListF<TValue>.Create(FValueEqualityCompare, ACapacity, AOwnsObjects);
end;
function TJclSortedMapF<TKey, TValue>.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclSortedMapF<TKey, TValue>.Create(FKeyCompare, FValueCompare, FValueEqualityCompare, FCapacity,
FOwnsValues, FOwnsKeys);
AssignPropertiesTo(Result);
end;
function TJclSortedMapF<TKey, TValue>.CreateEmptyArraySet(ACapacity: Integer; AOwnsObjects: Boolean): IJclSet<TKey>;
begin
Result := TJclArraySetF<TKey>.Create(FKeyCompare, FCapacity, AOwnsObjects);
end;
function TJclSortedMapF<TKey, TValue>.KeysCompare(const A, B: TKey): Integer;
begin
if not Assigned(KeyCompare) then
raise EJclNoComparerError.Create;
Result := KeyCompare(A, B);
end;
function TJclSortedMapF<TKey, TValue>.ValuesCompare(const A, B: TValue): Integer;
begin
if not Assigned(ValueCompare) then
raise EJclNoComparerError.Create;
Result := ValueCompare(A, B);
end;
//=== { TJclSortedMapI<TKey, TValue> } =======================================
function TJclSortedMapI<TKey, TValue>.CreateEmptyArrayList(ACapacity: Integer;
AOwnsObjects: Boolean): IJclCollection<TValue>;
begin
Result := TJclArrayListI<TValue>.Create(ACapacity, AOwnsObjects);
end;
function TJclSortedMapI<TKey, TValue>.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclSortedMapI<TKey, TValue>.Create(FCapacity, FOwnsValues, FOwnsKeys);
AssignPropertiesTo(Result);
end;
function TJclSortedMapI<TKey, TValue>.CreateEmptyArraySet(ACapacity: Integer; AOwnsObjects: Boolean): IJclSet<TKey>;
begin
Result := TJclArraySetI<TKey>.Create(FCapacity, AOwnsObjects);
end;
function TJclSortedMapI<TKey, TValue>.KeysCompare(const A, B: TKey): Integer;
begin
Result := A.CompareTo(B);
end;
function TJclSortedMapI<TKey, TValue>.ValuesCompare(const A, B: TValue): Integer;
begin
Result := A.CompareTo(B);
end;
{$ENDIF SUPPORTS_GENERICS}
{$IFDEF UNITVERSIONING}
initialization
RegisterUnitVersion(HInstance, UnitVersioning);
finalization
UnregisterUnitVersion(HInstance);
{$ENDIF UNITVERSIONING}
end.
|
unit uLoadForm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Objects,
FMX.Controls.Presentation, FMX.StdCtrls, xConsts, xFunction;
type
TfLoadForm = class(TForm)
pnl1: TPanel;
lblModel: TLabel;
lblCOMPANY: TLabel;
lblVersion: TLabel;
lblObjectName: TLabel;
lblLoadInfo: TLabel;
img1: TImage;
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
/// <summary>
/// ¼ÓÔØÐÅÏ¢ÃèÊö
/// </summary>
procedure LoadInfo( sInfo : string );
end;
var
fLoadForm: TfLoadForm;
implementation
{$R *.fmx}
procedure TfLoadForm.FormShow(Sender: TObject);
begin
lblModel.Text := C_SYS_OBJECT_MODEL;
lblCOMPANY.Text := C_SYS_COMPANY;
lblObjectName.Text := C_SYS_OBJECT_NAME;
lblVersion.Text := '°æ±¾£ºV' + GetFileVersion;
if FileExists('res\logo\Load.bmp') then
img1.Bitmap.LoadFromFile('res\logo\Load.bmp');
end;
procedure TfLoadForm.LoadInfo(sInfo: string);
begin
lblLoadInfo.Text := sInfo;
end;
end.
|
(*
Unit owner :
Pierr Yager <pierre.y@gmail.com>
*)
unit ZeroMQ.Wrapper;
interface
uses
Generics.Collections,
ZeroMQ.API;
type
ZMQ = (
Pair,
Publisher, Subscriber,
Requester, Responder,
Dealer, Router,
Pull, Push,
XPublisher, XSubscriber
);
MessageFlag = (DontWait, SendMore);
MessageFlags = set of MessageFlag;
IZMQPair = interface
['{7F6D7BE5-7182-4972-96E1-4B5798608DDE}']
{ Server pair }
function Bind(const Address: string): Integer;
{ Client pair }
function Connect(const Address: string): Integer;
{ Socket Options }
function SocketType: ZMQ;
{ Required for ZMQ.Subscriber pair }
function Subscribe(const Filter: string): Integer;
function HaveMore: Boolean;
{ Raw messages }
function SendMessage(var Msg: TZmqMsg; Flags: MessageFlags): Integer;
function ReceiveMessage(var Msg: TZmqMsg; Flags: MessageFlags): Integer;
{ Simple string message }
function SendString(const Data: string; Flags: MessageFlags): Integer; overload;
function SendString(const Data: string; DontWait: Boolean = False): Integer; overload;
function ReceiveString(DontWait: Boolean = False): string;
{ Multipart string message }
function SendStrings(const Data: array of string; DontWait: Boolean = False): Integer;
function ReceiveStrings(const DontWait: Boolean = False): TArray<string>;
{ High Level Algorithgms - Forward message to another pair }
procedure ForwardMessage(Pair: IZMQPair);
end;
PollEvent = (PollIn, PollOut, PollErr);
PollEvents = set of PollEvent;
TZMQPollEvent = reference to procedure (Events: PollEvents);
IZMQPoll = interface
procedure RegisterPair(const Pair: IZMQPair; Events: PollEvents = []; const Proc: TZMQPollEvent = nil);
function PollOnce(Timeout: Integer = -1): Integer;
procedure FireEvents;
end;
ZMQDevice = (
Queue, Forwarder, Streamer
);
IZeroMQ = interface
['{593FC079-23AD-451E-8877-11584E93D80E}']
function Start(Kind: ZMQ): IZMQPair;
function StartDevice(Kind: ZMQDevice; Frontend, Backend: IZMQPair): Integer;
function Poller: IZMQPoll;
function InitMessage(var Msg: TZmqMsg; Size: Integer = 0): Integer;
function CloseMessage(var Msg: TZmqMsg): Integer;
end;
TZeroMQ = class(TInterfacedObject, IZeroMQ)
private
FContext: Pointer;
FPairs: TList<IZMQPair>;
public
constructor Create(IoThreads: Integer = 1);
destructor Destroy; override;
function Start(Kind: ZMQ): IZMQPair;
function StartDevice(Kind: ZMQDevice; Frontend, Backend: IZMQPair): Integer;
function Poller: IZMQPoll;
function InitMessage(var Msg: TZmqMsg; Size: Integer = 0): Integer;
function CloseMessage(var Msg: TZmqMsg): Integer;
end;
implementation
type
TZMQPair = class(TInterfacedObject, IZMQPair)
private
FSocket: Pointer;
public
constructor Create(Socket: Pointer);
destructor Destroy; override;
{ Server pair }
function Bind(const Address: string): Integer;
{ Client pair }
function Connect(const Address: string): Integer;
{ Required for ZMQ.Subscriber pair }
function Subscribe(const Filter: string): Integer;
function HaveMore: Boolean;
{ Socket Options }
function SocketType: ZMQ;
{ Raw messages }
function SendMessage(var Msg: TZmqMsg; Flags: MessageFlags): Integer;
function ReceiveMessage(var Msg: TZmqMsg; Flags: MessageFlags): Integer;
{ Simple string message }
function SendString(const Data: string; Flags: MessageFlags): Integer; overload;
function SendString(const Data: string; DontWait: Boolean = False): Integer; overload;
function ReceiveString(DontWait: Boolean = False): string;
{ Multipart string message }
function SendStrings(const Data: array of string; DontWait: Boolean = False): Integer;
function ReceiveStrings(const DontWait: Boolean = False): TArray<string>;
{ High Level Algorithgms - Forward message to another pair }
procedure ForwardMessage(Pair: IZMQPair);
end;
TZMQPoll = class(TInterfacedObject, IZMQPoll)
private
FPollItems: TArray<TZmqPollItem>;
FPollEvents: TArray<TZMQPollEvent>;
public
procedure RegisterPair(const Pair: IZMQPair; Events: PollEvents = []; const Event: TZMQPollEvent = nil);
function PollOnce(Timeout: Integer = -1): Integer;
procedure FireEvents;
end;
{ TZeroMQ }
constructor TZeroMQ.Create(IoThreads: Integer);
begin
inherited Create;
FPairs := TList<IZMQPair>.Create;
FContext := zmq_init(IoThreads);
end;
destructor TZeroMQ.Destroy;
begin
FPairs.Free;
zmq_term(FContext);
inherited;
end;
function TZeroMQ.Start(Kind: ZMQ): IZMQPair;
begin
Result := TZMQPair.Create(zmq_socket(FContext, Ord(Kind)));
FPairs.Add(Result);
end;
function TZeroMQ.StartDevice(Kind: ZMQDevice; Frontend,
Backend: IZMQPair): Integer;
{$IFNDEF EXPERIMENTAL}
const
R_OR_D = [ZMQ.Router, ZMQ.Dealer];
P_OR_S = [ZMQ.Publisher, ZMQ.Subscriber];
P_OR_P = [ZMQ.Push, ZMQ.Pull];
var
P: IZMQPoll;
FST, BST: ZMQ;
{$ENDIF}
begin
{$IFDEF EXPERIMENTAL}
Result := zmq_device(Ord(Kind) + 1, (Frontend as TZMQPair).FSocket, (Backend as TZMQPair).FSocket);
{$ELSE}
FST := Frontend.SocketType;
BST := Backend.SocketType;
if ((Kind = ZMQDevice.Queue) and (FST <> BST) and (FST in R_OR_D) and (BST in R_OR_D))
or ((Kind = ZMQDevice.Forwarder) and (FST <> BST) and (FST in P_OR_S) and (BST in P_OR_S))
or ((Kind = ZMQDevice.Streamer) and (FST <> BST) and (FST in P_OR_P) and (BST in P_OR_P))
then
begin
P := Poller;
P.RegisterPair(Frontend, [PollEvent.PollIn],
procedure(Event: PollEvents)
begin
if PollEvent.PollIn in Event then
Frontend.ForwardMessage(Backend);
end
);
P.RegisterPair(Backend, [PollEvent.PollIn],
procedure(Event: PollEvents)
begin
if PollEvent.PollIn in Event then
Backend.ForwardMessage(Frontend);
end
);
while True do
if P.PollOnce > 0 then
P.FireEvents;
end
else
Result := -1;
{$ENDIF}
end;
function TZeroMQ.InitMessage(var Msg: TZmqMsg; Size: Integer): Integer;
begin
if Size = 0 then
Result := zmq_msg_init(@Msg)
else
Result := zmq_msg_init_size(@Msg, Size)
end;
function TZeroMQ.Poller: IZMQPoll;
begin
Result := TZMQPoll.Create;
end;
function TZeroMQ.CloseMessage(var Msg: TZmqMsg): Integer;
begin
Result := zmq_msg_close(@Msg);
end;
{ TZMQPair }
constructor TZMQPair.Create(Socket: Pointer);
begin
inherited Create;
FSocket := Socket;
end;
destructor TZMQPair.Destroy;
begin
zmq_close(FSocket);
inherited;
end;
function TZMQPair.Bind(const Address: string): Integer;
begin
Result := zmq_bind(FSocket, PAnsiChar(AnsiString(Address)));
end;
function TZMQPair.Connect(const Address: string): Integer;
begin
Result := zmq_connect(FSocket, PAnsiChar(AnsiString(Address)));
end;
function TZMQPair.Subscribe(const Filter: string): Integer;
var
str: UTF8String;
begin
str := UTF8String(Filter);
Result := zmq_setsockopt(FSocket, ZMQ_SUBSCRIBE, PAnsiChar(str), Length(str));
end;
function TZMQPair.HaveMore: Boolean;
var
more: Integer;
more_size: Cardinal;
begin
more_size := SizeOf(more);
zmq_getsockopt(FSocket, ZMQ_RCVMORE, @more, @more_size);
Result := more > 0;
end;
function TZMQPair.ReceiveMessage(var Msg: TZmqMsg;
Flags: MessageFlags): Integer;
begin
Result := zmq_recvmsg(FSocket, @Msg, Byte(Flags));
end;
function TZMQPair.ReceiveString(DontWait: Boolean): string;
var
msg: TZmqMsg;
str: UTF8String;
len: Cardinal;
begin
zmq_msg_init(@msg);
if zmq_recvmsg(FSocket, @msg, Ord(DontWait)) = 0 then
Exit('');
len := zmq_msg_size(@msg);
SetLength(str, len);
Move(zmq_msg_data(@msg)^, PAnsiChar(str)^, len);
zmq_msg_close(@msg);
Result := string(str);
end;
function TZMQPair.ReceiveStrings(const DontWait: Boolean): TArray<string>;
var
L: TList<string>;
begin
L := TList<string>.Create;
try
repeat
L.Add(ReceiveString(DontWait));
until not HaveMore;
Result := L.ToArray;
finally
L.Free;
end;
end;
function TZMQPair.SendMessage(var Msg: TZmqMsg; Flags: MessageFlags): Integer;
begin
Result := zmq_sendmsg(FSocket, @Msg, Byte(Flags));
end;
function TZMQPair.SendString(const Data: string; Flags: MessageFlags): Integer;
var
msg: TZmqMsg;
str: UTF8String;
len: Integer;
begin
str := UTF8String(Data);
len := Length(str);
Result := zmq_msg_init_size(@msg, len);
if Result = 0 then
begin
Move(PAnsiChar(str)^, zmq_msg_data(@msg)^, len);
Result := SendMessage(msg, Flags);
zmq_msg_close(@msg);
end;
end;
function TZMQPair.SendString(const Data: string; DontWait: Boolean): Integer;
begin
Result := SendString(Data, MessageFlags(Ord(DontWait)));
end;
function TZMQPair.SendStrings(const Data: array of string;
DontWait: Boolean): Integer;
var
I: Integer;
Flags: MessageFlags;
begin
Result := 0;
if Length(Data) = 1 then
Result := SendString(Data[0], DontWait)
else
begin
Flags := [MessageFlag.SendMore] + MessageFlags(Ord(DontWait));
for I := Low(Data) to High(Data) do
begin
if I = High(Data) then
Exclude(Flags, MessageFlag.SendMore);
Result := SendString(Data[I], Flags);
if Result < 0 then
Break;
end;
end;
end;
function TZMQPair.SocketType: ZMQ;
var
RawType: Integer;
OptionSize: Integer;
begin
RawType := 0;
OptionSize := SizeOf(RawType);
zmq_getsockopt(FSocket, ZMQ_TYPE, @RawType, @OptionSize);
Result := ZMQ(RawType)
end;
procedure TZMQPair.ForwardMessage(Pair: IZMQPair);
const
SEND_FLAGS: array[Boolean] of Byte = (0, ZMQ_SNDMORE);
var
msg: TZmqMsg;
flag: Byte;
begin
repeat
zmq_msg_init(@msg);
zmq_recvmsg(FSocket, @msg, 0);
flag := SEND_FLAGS[HaveMore];
zmq_sendmsg((Pair as TZMQPair).FSocket, @msg, flag);
zmq_msg_close(@msg);
until flag = 0;
end;
{ TZMQPoll }
procedure TZMQPoll.RegisterPair(const Pair: IZMQPair; Events: PollEvents;
const Event: TZMQPollEvent);
var
P: PZmqPollItem;
begin
SetLength(FPollItems, Length(FPollItems) + 1);
P := @FPollItems[Length(FPollItems) - 1];
P.socket := (Pair as TZMQPair).FSocket;
P.fd := 0;
P.events := Byte(Events);
P.revents := 0;
SetLength(FPollEvents, Length(FPollEvents) + 1);
FPollEvents[Length(FPollEvents) - 1] := Event;
end;
function TZMQPoll.PollOnce(Timeout: Integer): Integer;
begin
Result := zmq_poll(@FPollItems[0], Length(FPollItems), Timeout);
end;
procedure TZMQPoll.FireEvents;
var
I: Integer;
begin
for I := 0 to Length(FPollItems) - 1 do
if (FPollEvents[I] <> nil) and ((FPollItems[I].revents and FPollItems[I].events) <> 0) then
FPollEvents[I](PollEvents(Byte(FPollItems[I].revents)));
end;
end.
|
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 16384,0,0}
{
by Behdad Esfahbod
Algorithmic Problems Book
April '2000
Problem 159 Backtrack Method
}
program
Sitting;
const
MaxNum = 200;
var
N, M : Integer;
CL, CW : array [0 .. MaxNum * 2] of record L, W, R : Integer; end;
IndL, IndW : array [1 .. MaxNum + 1] of Integer;
S, A : array [1 .. MaxNum] of Integer;
Mark : array [1 .. MaxNum] of Boolean;
T : Integer;
H : Integer;
I, J, K : Integer;
CC : Longint;
procedure ReadInput;
begin
Assign(Input, 'input.txt');
Reset(Input);
Readln(N, M);
for I := 1 to M do
begin
with CL[2 * I - 1] do
Readln(L, W, R);
with CL[2 * I] do
begin
L := CL[2 * I - 1].R; W := CL[2 * I - 1].W; R := CL[2 * I - 1].L;
end;
end;
M := M * 2;
Close(Input);
end;
procedure NoSolution;
begin
Assign(Output, 'output.txt');
Rewrite(Output);
Writeln('No Solution');
Close(Output);
end;
procedure Sort(l, r: Integer);
var
i, j, x: integer;
begin
i := l; j := r; x := cl[(l+r) DIV 2].l;
repeat
while cl[i].l < x do i := i + 1;
while x < cl[j].l do j := j - 1;
if i <= j then
begin
cl[0] := cl[i]; cl[i] := cl[j]; cl[j] := cl[0];
i := i + 1; j := j - 1;
end;
until i > j;
if l < j then Sort(l, j);
if i < r then Sort(i, r);
end;
procedure Sort2(l, r: Integer);
var
i, j, x: integer;
begin
i := l; j := r; x := cw[(l+r) DIV 2].w;
repeat
while cw[i].w < x do i := i + 1;
while x < cw[j].w do j := j - 1;
if i <= j then
begin
cw[0] := cw[i]; cw[i] := cw[j]; cw[j] := cw[0];
i := i + 1; j := j - 1;
end;
until i > j;
if l < j then Sort2(l, j);
if i < r then Sort2(i, r);
end;
procedure Found;
begin
Writeln(CC);
Assign(Output, 'output.txt');
Rewrite(Output);
for I := 1 to N do
Write(A[I], ' ');
Close(Output);
Halt;
end;
procedure Swap (I, J : Integer);
begin
T := A[I]; A[I] := A[J]; A[J] := T;
end;
procedure Put (X : Integer);
begin
for I := IndL[X] to IndL[X + 1] - 1 do
begin
Inc(S[CL[I].R]);
Dec(S[CL[I].W]);
end;
for I := IndW[X] to IndW[X + 1] - 1 do
if Mark[CW[I].L] then
Dec(S[CW[I].R]);
Mark[X] := True;
end;
procedure Pick (X : Integer);
begin
Mark[X] := False;
for I := IndL[X] to IndL[X + 1] - 1 do
begin
Dec(S[CL[I].R]);
Inc(S[CL[I].W]);
end;
for I := IndW[X] to IndW[X + 1] - 1 do
if Mark[CW[I].L] then
Inc(S[CW[I].R]);
end;
procedure BT;
var
I : Integer;
begin Inc(CC);
Inc(H);
if H > N then
Found;
for I := H to N do
if S[A[I]] = 0 then
begin
Swap(H, I);
Put(A[H]);
BT;
Pick(A[H]);
Swap(H, I);
end;
Dec(H);
end;
procedure Solve;
begin
Sort(1, M);
CW := CL;
Sort2(1, M);
for I := 1 to N + 1 do begin IndL[I] := M + 1; IndW[I] := M + 1; end;
for I := M downto 1 do begin IndL[CL[I].L] := I; IndW[CW[I].W] := I; end;
for I := N downto 1 do
begin
if IndL[I] = M + 1 then IndL[I] := IndL[I + 1];
if IndW[I] = M + 1 then IndW[I] := IndW[I + 1];
end;
for I := 1 to N do A[I] := I;
for I := 1 to M do if CL[I].L < CL[I].R then Inc(S[CL[I].W]);
BT;
end;
begin
ReadInput;
Solve;
NoSolution;
end.
|
unit xElecBreak;
interface
uses xElecLine, xElecPoint, System.Classes, System.SysUtils;
type
/// <summary>
/// 断路器
/// </summary>
TElecBreak = class
private
FInLineN: TElecLine;
FOutLineA: TElecLine;
FInLineB: TElecLine;
FInLineC: TElecLine;
FInLineA: TElecLine;
FOnBreakChange: TNotifyEvent;
FIsBreakOn: Boolean;
FOutLineN: TElecLine;
FOutLineB: TElecLine;
FOutLineC: TElecLine;
FBreakName: string;
procedure SetIsBreakOn(const Value: Boolean);
public
constructor Create;
destructor Destroy; override;
/// <summary>
/// 断路器名称
/// </summary>
property BreakName : string read FBreakName write FBreakName;
/// <summary>
/// A相进线
/// </summary>
property InLineA : TElecLine read FInLineA write FInLineA;
/// <summary>
/// B相进线
/// </summary>
property InLineB : TElecLine read FInLineB write FInLineB;
/// <summary>
/// C相进线
/// </summary>
property InLineC : TElecLine read FInLineC write FInLineC;
/// <summary>
/// N相进线
/// </summary>
property InLineN : TElecLine read FInLineN write FInLineN;
/// <summary>
/// A相进线
/// </summary>
property OutLineA : TElecLine read FOutLineA write FOutLineA;
/// <summary>
/// B相进线
/// </summary>
property OutLineB : TElecLine read FOutLineB write FOutLineB;
/// <summary>
/// C相进线
/// </summary>
property OutLineC : TElecLine read FOutLineC write FOutLineC;
/// <summary>
/// N相进线
/// </summary>
property OutLineN : TElecLine read FOutLineN write FOutLineN;
/// <summary>
/// 是否闭合
/// </summary>
property IsBreakOn : Boolean read FIsBreakOn write SetIsBreakOn;
/// <summary>
/// 开关状态改变
/// </summary>
property OnBreakChange : TNotifyEvent read FOnBreakChange write FOnBreakChange;
public
/// <summary>
/// 清空电压值
/// </summary>
procedure ClearVolVlaue;
/// <summary>
/// 清除权值
/// </summary>
procedure ClearWValue;
/// <summary>
/// 清空电流列表
/// </summary>
procedure ClearCurrentList;
end;
implementation
{ TElecBreak }
procedure TElecBreak.ClearCurrentList;
begin
FInLineA.ClearCurrentList;
FInLineB.ClearCurrentList;
FInLineC.ClearCurrentList;
FInLineN.ClearCurrentList;
FOutLineA.ClearCurrentList;
FOutLineB.ClearCurrentList;
FOutLineC.ClearCurrentList;
FOutLineN.ClearCurrentList;
end;
procedure TElecBreak.ClearVolVlaue;
begin
end;
procedure TElecBreak.ClearWValue;
begin
FInLineA.ClearWValue;
FInLineB.ClearWValue;
FInLineC.ClearWValue;
FInLineN.ClearWValue;
FOutLineA.ClearWValue;
FOutLineB.ClearWValue;
FOutLineC.ClearWValue;
FOutLineN.ClearWValue;
end;
constructor TElecBreak.Create;
begin
FInLineA := TElecLine.Create;
FInLineB := TElecLine.Create;
FInLineC := TElecLine.Create;
FInLineN := TElecLine.Create;
FOutLineA := TElecLine.Create;
FOutLineB := TElecLine.Create;
FOutLineC := TElecLine.Create;
FOutLineN := TElecLine.Create;
FIsBreakOn:= True;
FBreakName:= '断路器';
end;
destructor TElecBreak.Destroy;
begin
FInLineA.Free;
FInLineB.Free;
FInLineC.Free;
FInLineN.Free;
FOutLineA.Free;
FOutLineB.Free;
FOutLineC.Free;
FOutLineN.Free;
inherited;
end;
procedure TElecBreak.SetIsBreakOn(const Value: Boolean);
begin
FIsBreakOn := Value;
end;
end.
|
unit rtfprocessor;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, IniFiles, strutils, cmtutil, rtfutil;
type
TOnProgress = procedure(perc1: Integer) of object;
TOnLog = procedure(message: String) of object;
EVerseRefException = class(Exception);
TRtfProcessor = class(TObject)
private
cmtUtil: TCmtUtil;
biblebooksIni: TIniFile;
FOnProgress: TOnProgress;
FOnLog: TOnLog;
public
procedure processRtf(rtf, twmFilename: String);
procedure processHeader(rtfSnippet: String);
procedure processSnippet(rtfSnippet: String);
property OnProgress: TOnProgress read FOnProgress write FOnProgress;
property OnLog: TOnLog read FOnLog write FOnLog;
end;
implementation
procedure TRtfProcessor.processRtf(rtf, twmFilename: String);
var
pos, previouspos, total: Integer;
begin
biblebooksIni := TIniFile.Create('biblebooks.ini');
cmtUtil := TCmtUtil.Create;
cmtUtil.createDB(twmFilename);
try
previousPos := 0;
total := Length(rtf);
pos := rtf.IndexOf('\''f7');
if (pos >= 0) then
begin
processHeader(rtf.Substring(0, pos));
previouspos := pos+4;
pos := rtf.IndexOf('\''f7', previouspos);
end;
while pos > 0 do
begin
processSnippet(rtf.Substring(previousPos, pos-previousPos));
previouspos := pos+4;
pos := rtf.IndexOf('\''f7', previouspos);
if Assigned(FOnProgress) then FOnProgress((pos+1)*100 div total);
end;
// Text snippet after the last marker, before the closing curly brace
if previouspos > 0 then
begin
processSnippet(rtf.Substring(previousPos, rtf.LastIndexOf('}')-previousPos));
end;
if Assigned(FOnProgress) then FOnProgress(100);
finally
cmtUtil.close();
cmtUtil.Free();
biblebooksIni.Free();
end;
end;
procedure TRtfProcessor.processHeader(rtfSnippet: String);
begin
//TODO: process header #defines
end;
procedure TRtfProcessor.processSnippet(rtfSnippet: String);
var
verseRef, data: String;
i, bi, ci, fvi, tvi: Integer;
verseRefArray: array of String;
begin
if (rtfSnippet.Trim <> '') then
begin
// Verse reference, on the first line
verseRef := rtfSnippet.Substring(0, rtfSnippet.IndexOf('\par')).Trim();
// Strip leading rtf commands
while (verseRef.indexOf('\') = 0) do
begin
i := verseRef.indexOf(' ');
verseRef := verseRef.Substring(i, Length(verseRef)-1).Trim();
end;
// Strip trailing rtf commands
while (verseRef.indexOf('\') > 0) do
begin
verseRef := verseRef.Substring(0, verseRef.indexOf('\')).Trim();
end;
if Assigned(FOnLog) then FOnLog(verseRef);
verseRefArray := verseRef.Split([' ',':','-']);
bi := bibleBooksIni.ReadInteger('biblebooks', verseRefArray[0], 0);
if (bi = 0) then
raise EVerseRefException.Create('Unknown bible book '+verserefArray[0]);
ci := StrToInt(IfThen(Length(verseRefArray)>1, verseRefArray[1], '0'));
fvi := StrToInt(IfThen(Length(verseRefArray)>2, verseRefArray[2], '0'));
tvi := StrToInt(IfThen(Length(verseRefArray)>3, verseRefArray[3], '0'));
// Entry text, from the second line onwards
data := createTopicHeader()
+ (rtfSnippet.Substring(rtfSnippet.indexOf('\par')+4, Length(rtfSnippet)-rtfSnippet.IndexOf('\par')-4))
+ createTopicFooter();
cmtUtil.addTopic(bi, ci, fvi, tvi, data);
end;
end;
end.
|
{**********************************************}
{ TWindRoseSeries }
{ TClockSeries }
{ Copyright (c) 1998-2004 by David Berneda }
{**********************************************}
unit TeeRose;
{$I TeeDefs.inc}
interface
Uses {$IFNDEF LINUX}
Windows,
{$ENDIF}
SysUtils, Classes,
{$IFDEF CLX}
QGraphics, QExtCtrls,
{$ELSE}
Graphics, ExtCtrls,
{$ENDIF}
TeEngine, Chart, TeCanvas, Series, TeePolar;
{ This unit contains two Series components:
TWindRoseSeries -- A Polar Series displaying Wind directions.
TClockSeries -- A Polar Series showing a watch.
}
Type TCustom2DPolarSeries=class(TCustomPolarSeries)
protected
Procedure GalleryChanged3D(Is3D:Boolean); override;
Procedure PrepareForGallery(IsEnabled:Boolean); override;
end;
TWindRoseSeries=class(TCustom2DPolarSeries)
private
FMirrorLabels : Boolean;
procedure SetMirrorLabels(const Value: Boolean);
protected
Function GetCircleLabel(Const Angle:Double; Index:Integer):String; override;
class Function GetEditorClass:String; override;
Procedure PrepareForGallery(IsEnabled:Boolean); override;
public
Constructor Create(AOwner: TComponent); override;
published
property Active;
property ColorEachPoint;
property HorizAxis;
property SeriesColor;
property VertAxis;
property AngleIncrement;
property AngleValues;
property Brush;
property CircleBackColor;
property CircleGradient;
property CircleLabels default True;
property CircleLabelsFont;
property CircleLabelsInside;
property CircleLabelsRotated;
property CirclePen;
property CloseCircle;
property MirrorLabels:Boolean read FMirrorLabels write SetMirrorLabels default False; // 7.0
property Pen;
property Pointer;
property RadiusIncrement;
property RadiusValues;
property RotationAngle default 90;
end;
TClockSeriesStyle=(cssDecimal,cssRoman);
TClockSeries=class;
TClockSeriesGetTimeEvent=procedure(Sender:TClockSeries; Var ATime:TDateTime) of object;
TClockSeries=class(TCustom2DPolarSeries)
private
FOnGetTime : TClockSeriesGetTimeEvent;
FPenHours : TChartPen;
FPenMinutes : TChartPen;
FPenSeconds : TChartPen;
FStyle : TClockSeriesStyle;
OldAxesVisible : Boolean;
ITimer : TTimer;
Procedure SetPenHours(Value:TChartPen);
Procedure SetPenMinutes(Value:TChartPen);
Procedure SetPenSeconds(Value:TChartPen);
Procedure SetStyle(Value:TClockSeriesStyle);
Procedure OnTimerExpired(Sender:TObject);
protected
Procedure DoBeforeDrawValues; override;
Procedure DrawAllValues; override;
Function GetCircleLabel(Const Angle:Double; Index:Integer):String; override;
class Function GetEditorClass:String; override;
Procedure SetParentChart(Const Value:TCustomAxisPanel); override;
public
Constructor Create(AOwner: TComponent); override;
Destructor Destroy; override;
Procedure Assign(Source:TPersistent); override;
Function ClockTime:TDateTime; // 7.0
Function CountLegendItems:Integer; override;
Function LegendItemColor(LegendIndex:Integer):TColor; override;
Function LegendString( LegendIndex:Integer;
LegendTextStyle:TLegendTextStyle ):String; override; // 7.0
Function NumSampleValues:Integer; override;
property Timer:TTimer read ITimer;
published
property Active;
property Brush;
property CircleBackColor;
property CircleGradient;
property Circled default True;
property CircleLabels default True;
property CircleLabelsFont;
property CircleLabelsInside;
property CircleLabelsRotated;
property CirclePen;
property PenHours:TChartPen read FPenHours write SetPenHours;
property PenMinutes:TChartPen read FPenMinutes write SetPenMinutes;
property PenSeconds:TChartPen read FPenSeconds write SetPenSeconds;
property RotationAngle default 90;
property ShowInLegend default False; { 5.02 }
property Style:TClockSeriesStyle read FStyle write SetStyle
default cssRoman;
property Transparency; { 5.02 }
{ events }
property OnGetTime : TClockSeriesGetTimeEvent read FOnGetTime
write FOnGetTime;
end;
implementation
uses
TeeProCo;
{ TCustom2DPolarSeries }
Procedure TCustom2DPolarSeries.GalleryChanged3D(Is3D:Boolean);
begin
inherited;
ParentChart.View3D:=False;
end;
Procedure TCustom2DPolarSeries.PrepareForGallery(IsEnabled:Boolean);
begin
inherited;
CircleLabelsFont.Size:=6;
Pointer.HorizSize:=2;
Pointer.VertSize:=2;
end;
{ TWindRoseSeries }
Constructor TWindRoseSeries.Create(AOwner: TComponent);
begin
inherited;
CircleLabels:=True;
RotationAngle:=90;
end;
// Alternate method
(*
function DegreesToWindDir(const Angle: Double): String;
const WindDirs: Array[0..15] of String =
('N','NNW','NW','WNW','W','WSW','SW','SSW','S','SSE','SE','ESE','E','ENE','NE','NNE' );
var i : Integer;
begin
i:=Trunc((Angle + 11.25) / (360/16));
result := WindDirs[i];
end;
*)
// Return the string corresponding to the "Angle" degree parameter
Function TWindRoseSeries.GetCircleLabel(Const Angle:Double; Index:Integer):String;
var tmp : Double;
begin
if FMirrorLabels then tmp:=360-Angle
else tmp:=Angle;
Case Round(tmp) of
0: result:='N';
15: result:='NNNW';
30: result:='NNW';
45: result:='NW';
60: result:='NWW';
75: result:='NWWW';
90: result:='W';
105: result:='SWWW';
120: result:='SWW';
135: result:='SW';
150: result:='SSW';
165: result:='SSSW';
180: result:='S';
195: result:='SSSE';
210: result:='SSE';
225: result:='SE';
240: result:='SEE';
255: result:='SEEE';
270: result:='E';
285: result:='NEEE';
300: result:='NEE';
315: result:='NE';
330: result:='NNE';
345: result:='NNNE';
360: result:='N';
else result:='';
end;
end;
class function TWindRoseSeries.GetEditorClass: String;
begin
result:='TWindRoseEditor';
end;
procedure TWindRoseSeries.PrepareForGallery(IsEnabled: Boolean);
begin
inherited;
AngleIncrement:=45;
end;
procedure TWindRoseSeries.SetMirrorLabels(const Value: Boolean);
begin
SetBooleanProperty(FMirrorLabels,Value);
end;
{ TClockSeries }
Constructor TClockSeries.Create(AOwner: TComponent);
begin
inherited;
OldAxesVisible:=True;
Pointer.Hide;
FStyle:=cssRoman;
Brush.Style:=bsSolid;
CircleLabels:=True;
RotationAngle:=90;
Circled:=True;
Add(0);
FPenHours:=CreateChartPen;
FPenMinutes:=CreateChartPen;
FPenSeconds:=CreateChartPen;
ITimer:=TTimer.Create(Self);
With ITimer do
begin
Interval:=1000;
Enabled:=True;
OnTimer:=OnTimerExpired;
end;
end;
Destructor TClockSeries.Destroy;
begin
FPenHours.Free;
FPenMinutes.Free;
FPenSeconds.Free;
ITimer.Free;
inherited;
end;
Procedure TClockSeries.OnTimerExpired(Sender:TObject);
begin
ITimer.Enabled:=False;
Repaint;
ITimer.Enabled:=True;
end;
Procedure TClockSeries.Assign(Source:TPersistent);
begin
if Source is TClockSeries then
With TClockSeries(Source) do
begin
Self.PenHours :=FPenHours;
Self.PenMinutes :=FPenMinutes;
Self.PenSeconds :=FPenSeconds;
Self.FStyle :=FStyle;
end;
inherited;
end;
Procedure TClockSeries.DoBeforeDrawValues;
var tmpBlend : TTeeBlend; { 5.02 }
begin
if Transparency>0 then
tmpBlend:=ParentChart.Canvas.BeginBlending(ParentChart.ChartRect,Transparency)
else
tmpBlend:=nil;
inherited;
if Transparency>0 then
ParentChart.Canvas.EndBlending(tmpBlend);
end;
Function TClockSeries.ClockTime:TDateTime;
begin
result:=Now;
if Assigned(FOnGetTime) then FOnGetTime(Self,result);
end;
Procedure TClockSeries.DrawAllValues;
Var X : Integer;
Y : Integer;
Procedure CalcPos(Const AAngle,ASize:Double);
begin
AngleToPos(AAngle*PiDegree,ASize*XRadius/2.0,ASize*YRadius/2.0,X,Y);
end;
Var H : Word;
M : Word;
S : Word;
Ms : Word;
tmp : TDateTime;
begin
With ParentChart.Canvas do
begin
tmp:=ClockTime;
DecodeTime(tmp,H,M,S,Ms);
AssignBrush(Self.Brush,SeriesColor);
if FPenHours.Visible then
begin
AssignVisiblePen(FPenHours);
CalcPos(360.0-(360.0*(60.0*H+M)/(12.0*60.0)),1.3);
Arrow(True,TeePoint(CircleXCenter,CircleYCenter),TeePoint(X,Y),14,20,EndZ);
end;
if FPenMinutes.Visible then
begin
AssignVisiblePen(FPenMinutes);
CalcPos(360.0-(360.0*M/60.0),1.7);
Arrow(True,TeePoint(CircleXCenter,CircleYCenter),TeePoint(X,Y),10,16,EndZ);
end;
CalcPos(360.0-(360.0*(S+(Ms/1000.0))/60.0),1.8); // 5.02
if FPenSeconds.Visible then
begin
AssignVisiblePen(FPenSeconds);
MoveTo3D(CircleXCenter,CircleYCenter,EndZ);
LineTo3D(X,Y,EndZ);
end;
With Pointer do
if Visible then
begin
PrepareCanvas(ParentChart.Canvas,Color);
Draw(X,Y);
end;
end;
end;
Procedure TClockSeries.SetParentChart(Const Value:TCustomAxisPanel);
begin
if not Assigned(Value) then
if Assigned(ParentChart) then
ParentChart.Axes.Visible:=OldAxesVisible;
inherited;
AngleIncrement:=30;
if Assigned(ParentChart) then
begin
OldAxesVisible:=ParentChart.Axes.Visible;
ParentChart.Axes.Visible:=False;
end;
end;
{ Return the string corresponding to the "Angle" degree parameter }
Function TClockSeries.GetCircleLabel(Const Angle:Double; Index:Integer):String;
Const RomanNumber:Array[1..12] of String=
('I','II','III','IV','V','VI','VII','VIII','IX','X','XI','XII');
var tmpAngle : Integer;
begin
tmpAngle:=Round((360.0-Angle)/30.0);
if FStyle=cssDecimal then Str(tmpAngle,result)
else result:=RomanNumber[tmpAngle];
end;
Procedure TClockSeries.SetPenHours(Value:TChartPen);
begin
FPenHours.Assign(Value);
end;
Procedure TClockSeries.SetPenMinutes(Value:TChartPen);
begin
FPenMinutes.Assign(Value);
end;
Procedure TClockSeries.SetPenSeconds(Value:TChartPen);
begin
FPenSeconds.Assign(Value);
end;
Procedure TClockSeries.SetStyle(Value:TClockSeriesStyle);
begin
if FStyle<>Value then
begin
FStyle:=Value;
Repaint;
end;
end;
Function TClockSeries.NumSampleValues:Integer;
begin
result:=1;
end;
class function TClockSeries.GetEditorClass: String;
begin
result:='TClockEditor';
end;
function TClockSeries.CountLegendItems: Integer;
begin
result:=1;
end;
function TClockSeries.LegendItemColor(LegendIndex: Integer): TColor;
begin
result:=clNone;
end;
function TClockSeries.LegendString(LegendIndex: Integer;
LegendTextStyle: TLegendTextStyle): String;
begin
result:=TimeToStr(ClockTime);
end;
initialization
RegisterTeeSeries( TWindRoseSeries, {$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryWindRose,
{$IFNDEF CLR}@{$ENDIF}TeeMsg_GallerySamples, 1 );
RegisterTeeSeries( TClockSeries, {$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryClock,
{$IFNDEF CLR}@{$ENDIF}TeeMsg_GallerySamples, 1 );
finalization
UnRegisterTeeSeries([ TWindRoseSeries, TClockSeries ]);
end.
|
unit PKG5020A1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Db, MemDS, DBAccess, Ora, ComCtrls, StdCtrls, OnFocusButton,
ExtCtrls, OnScheme, OnEditBaseCtrl, OnEditStdCtrl, OnEditBtnCtrl,
OnEditCombo, OnEditMdate, calen2, OnShapeLabel, OnPopupEdit, Pass,
Buttons, Grids, DBGrids;
type
TFM_MainForm = class(TForm)
SF_Main: TOnSchemeForm;
PA_BackWindow: TPanel;
SB_Help: TStatusBar;
Panel2: TPanel;
BT_Save: TOnFocusButton;
BT_Exit: TOnFocusButton;
Ora_Qry1: TOraQuery;
Ora_Grid: TOraQuery;
Shape7: TShape;
L_CurDate: TLabel;
Lempno: TLabel;
BT_Search: TOnFocusButton;
Ora_Insert: TOraQuery;
Ora_Session: TOraSession;
ED_orgnum: TOnEdit;
DBGrid1: TDBGrid;
sGrid: TStringGrid;
OnShapeLabel2: TOnShapeLabel;
BT_cancel: TOnFocusButton;
DataSource1: TDataSource;
BT_Add: TOnFocusButton;
BT_Del: TOnFocusButton;
Ora_Grid2: TOraQuery;
Ora_Order: TOraQuery;
procedure BT_ExitClick(Sender: TObject);
procedure BT_SaveClick(Sender: TObject);
procedure BT_SearchClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure Panel2Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure BT_cancelClick(Sender: TObject);
procedure sGridDblClick(Sender: TObject);
procedure DBGrid1DblClick(Sender: TObject);
procedure ED_orgnumChange(Sender: TObject);
procedure BT_AddClick(Sender: TObject);
procedure BT_DelClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
private
{ Private declarations }
function GetTime : String;
procedure InsertStdpt;
procedure CallStdpt;
procedure SelectGrid;
procedure InsertGrid;
procedure GridOrder;
procedure Retrieve;
function GetDeptList():String;
public
{ Public declarations }
GSsysdate, GSempno, GSkorname, GSgrade : String;
GSaveChk : Integer; // 저장변수
Udeptcode, Fdeptcode : String;
LIchk : Integer;
end;
var
FM_MainForm: TFM_MainForm;
implementation
{$R *.DFM}
procedure TFM_MainForm.FormCreate(Sender: TObject);
begin
Application.ProcessMessages;
SB_Help.Panels[1].Text := ' 데이타베이스에 접속중입니다...';
Ora_Session.Options.Net := True;
Ora_Session.ConnectPrompt := False;
Ora_Session.Username := Passemp(cmdline,5);
Ora_Session.Password := Passemp(cmdline,6);
Ora_Session.Server := Passemp(cmdline,7)+':'+Passemp(cmdline,9)+':'+Passemp(cmdline,8);
try
Ora_Session.Connected := True;
except on E : Exception do
Application.MessageBox(PChar('서버에 접속할 수 없습니다...'#13#13+ E.Message),'알 림',MB_OK);
end;
end;
procedure TFM_MainForm.FormActivate(Sender: TObject);
begin
GSaveChk := 0 ; // 저장변수 초기화
GetTime;
L_CurDate.Caption := copy(GSsysdate,1,4)+'/'+copy(GSsysdate,5,2)+'/'+copy(GSsysdate,7,2);
GSempno := Passemp(cmdline,1);
GSkorname := Passemp(cmdline,2);
GSgrade := copy(Passemp(cmdline,4),3,1);
Lempno.Caption := GSkorname+'('+GSempno+')';
Retrieve;
CallStdpt;
SB_Help.Panels[1].Text := '';
end;
procedure TFM_MainForm.FormShow(Sender: TObject);
begin
with sGrid do
begin
Cells[1,0] := '부서';
Cells[2,0] := '부서명';
Cells[3,0] := '상세부서';
end;
end;
procedure TFM_MainForm.BT_ExitClick(Sender: TObject);
begin
if GSaveChk = 1 then
begin
If IDOK = Application.MessageBox('변경작업 후 자료를 저장하지 않았습니다.'+#13+
'작업을 종료 하시겠습니까?','작업안내', mb_OKCancel) then
Close;
end
else
Close;
end;
procedure TFM_MainForm.BT_SaveClick(Sender: TObject);
var
i : Integer;
begin
// if sGrid.Cells[1,1] = '' then exit;
SB_Help.Panels[1].Text := '';
If IDOK = Application.MessageBox('해당 자료를 저장하시겠습니까?','안내', mb_OKCancel) then
begin
SB_Help.Panels[1].Text := '현 근무형태의 자료를 모두 삭제 중입니다..';
Application.ProcessMessages;
with Ora_Qry1 do
begin
Close;
SQL.Clear;
SQL.ADD(' DELETE FROM PKCEXDPT ');
SQL.ADD(' WHERE ORGNUM ='''+ED_orgnum.text+''' ');
EXECSQL;
end;
if sGrid.Cells[1,1] <> '' then
begin
SB_Help.Panels[1].Text := '자료 입력 중입니다..';
Application.ProcessMessages;
i := 0;
with sGrid do
begin
for i := 1 to RowCount - 1 do
begin
Udeptcode := Cells[1,i];
Udeptcode := TrimRight(Udeptcode);
InsertStdpt;
end;
end;
SB_Help.Panels[1].Text := '저장 완료..';
GSaveChk := 0; // 저장이 완료 되었을시
end
else
SB_Help.Panels[1].Text := '잘못된 데이터 입력입니다...';
// 초기화
with sGrid do
begin
RowCount := 2;
Rows[Row].Clear;
end;
end;
CallStdpt;
Retrieve;
end;
////////////////////////////////////////////////////////////////////////////////
function TFM_MainForm.GetTime;
begin
with Ora_Qry1 do
begin
Close;
SQL.Clear;
SQL.ADD(' SELECT TO_CHAR(SYSDATE,''YYYYMMDDHH24MISSD'') GSsysdate ');
SQL.ADD(' FROM DUAL ');
Open;
GSsysdate := FieldByName('GSsysdate').AsString;
Close;
end;
end;
procedure TFM_MainForm.BT_SearchClick(Sender: TObject);
begin
CallStdpt;
Retrieve;
end;
procedure TFM_MainForm.Panel2Click(Sender: TObject);
begin
SB_Help.Panels[1].Text := Passemp(cmdline,7);
end;
procedure TFM_MainForm.BT_cancelClick(Sender: TObject);
begin
SB_Help.Panels[1].Text := '';
If IDOK = Application.MessageBox('작업을 취소하시겠습니까?','작업안내', mb_OKCancel) then
begin
sGrid.RowCount := 2;
sGrid.Rows[sGrid.Row].Clear;
CallStdpt;
Retrieve;
GSaveChk := 0; // 초기화
end;
end;
procedure TFM_MainForm.sGridDblClick(Sender: TObject);
begin
with sGrid do
begin
if (Cells[1,1]= '') then exit;
Rows[Row].Clear;
GridOrder;
if RowCount <> 2 then
RowCount := RowCount -1;
end;
GSaveChk := 1;
// SelectGrid;
end;
procedure TFM_MainForm.DBGrid1DblClick(Sender: TObject);
var
i, irow : integer;
ItemChk : integer;
begin
ItemChk := 0;
Fdeptcode := Ora_Grid.FieldByName('DEPTCODE').AsString;
with sGrid do
begin
for i := 1 to RowCount -1 do
begin showmessage(Cells[1, i]+'| '+Fdeptcode);
if Cells[1, i] = Fdeptcode then
begin //ItemChk := 1;
ShowMessage('선택하신 부서가 이미 교대근무부서에 등록되어있습니다.');
Application.ProcessMessages;
system.exit;
end;
end;
end;
InsertGrid;
// GridOrder;
// SelectGrid;
end;
///////////////////////////////////////////////////////////////////////////////
procedure TFM_Mainform.CallStdpt;
var i: integer;
begin
with Ora_Grid2 do
begin
Close;
SQL.Clear;
SQL.ADD(' SELECT A.DEPTCODE, B.DEPTNAME, B.DEPTNA3 ');
SQL.ADD(' FROM PKCEXDPT A, PYCDEPT B ');
SQL.ADD(' WHERE A.ORGNUM = B.ORGNUM ');
SQL.ADD(' AND A.DEPTCODE = B.DEPTCODE ');
SQL.ADD(' AND A.ORGNUM ='''+ED_orgnum.text+''' ');
Open;
with sGrid do
begin
for i := 1 to Ora_Grid2.RecordCount do
begin
Cells[1,i] := Ora_Grid2.FieldByName('DEPTCODE').AsString;
Cells[2,i] := Ora_Grid2.FieldByName('DEPTNAME').AsString;
Cells[3,i] := Ora_Grid2.FieldByName('DEPTNA3').AsString;
next;
RowCount := i +1;
end;
end;
end;
end;
procedure TFM_Mainform.Retrieve;
begin
If ED_orgnum.Text = '' then begin
Ora_Qry1.Close;
Ora_Qry1.SQL.Clear;
Ora_Qry1.SQL.ADD(' select value1 from pimvari where gubun=''00'' and sgubun=''0001'' ');
Ora_Qry1.Open;
ED_orgnum.Text := Ora_Qry1.Fields[0].AsString;
end;
with Ora_Grid do
begin
Close;
SQL.Clear;
SQL.ADD(' SELECT A.DEPTCODE, A.DEPTNAME, A.DEPTNA3 ');
SQL.ADD(' FROM PYCDEPT A ');
SQL.ADD(' WHERE A.ORGNUM = '''+ED_orgnum.Text+''' ');
SQL.ADD(' AND A.deptcode not in (select deptcode ');
SQL.ADD(' from PKCEXDPT ');
SQL.ADD(' where A.orgnum = Orgnum) ');
SQL.ADD(' ORDER BY A.DEPTORDER ');
Open;
end;
end;
procedure TFM_Mainform.InsertGrid;
begin
with sGrid do
begin
if not ((RowCount = 1) and (Cells[1,1]= '')) or
not ((RowCount = 0) and (Cells[1,1]= '')) then
RowCount := RowCount + 1 ;
Cells[1,RowCount-1] := Copy(Fdeptcode,1,5);
Cells[2,RowCount-1] := Ora_Grid.FieldByName('DEPTNAME').AsString;
Cells[3,RowCount-1] := Ora_Grid.FieldByName('DEPTNA3').AsString;
/// sGridClick(self);
end;
GSaveChk := 1;
end;
procedure TFM_Mainform.InsertStdpt;
begin
with Ora_Insert do
begin
Close;
SQL.Clear;
SQL.ADD(' INSERT INTO PKCEXDPT ');
// SQL.ADD(' (ORGNUM, DEPTCODE, STKIND, WRITETIME, WRITEMAN) ');
SQL.ADD(' (ORGNUM, DEPTCODE, WRITETIME, WRITEMAN) ');
SQL.ADD(' VALUES ('''+ED_orgnum.text+''', '''+Udeptcode+''', ');
// SQL.ADD(' ''1'', '''+GSsysdate+''' ,'''+GSempno+''' ) ');
SQL.ADD(' '''+GSsysdate+''' ,'''+GSempno+''' ) ');
ExecSQL;
end;
end;
procedure TFM_MainForm.ED_orgnumChange(Sender: TObject);
begin
SB_Help.Panels[1].Text := '';
if Length(ED_orgnum.text) > 0 then
begin
CallStdpt;
Retrieve;
end;
end;
function TFM_Mainform.GetDeptList:String;
var
i: integer;
DeptList : String;
begin
DeptList := '';
with sGrid do
begin
for i := 1 to RowCount - 1 do
begin
if Cells[1,i] <> '' then
DeptList := DeptList+','''+Cells[1,i]+'''';
end;
end;
result := DeptList;
end;
procedure TFM_Mainform.GridOrder;
var i:integer;
begin
// 정렬
with sGrid, Ora_Order do
begin
//if Active = false then exit;
Close;
SQL.Clear;
SQL.ADD(' SELECT ORGNUM,DEPTCODE,DEPTNAME,DEPTNA3 ');
SQL.ADD(' FROM PYCDEPT ');
SQL.ADD(' WHERE ORGNUM = '''+ED_orgnum.Text+''' ');
SQL.ADD(' AND DEPTCODE in ('''''+GetDeptList+') ');
SQL.ADD(' ORDER BY DEPTORDER ');
Open;
for i := 1 to RecordCount do
begin
sGrid.Cells[1,i] := FieldByName('DEPTCODE').AsString;
sGrid.Cells[2,i] := FieldByName('DEPTNAME').AsString;
sGrid.Cells[3,i] := FieldByName('DEPTNA3').AsString;
next;
end;
end;
end;
procedure TFM_Mainform.SelectGrid;
begin
{ with Ora_Qry1 do
begin
Close;
SQL.Clear;
SQL.ADD(' SELECT A.DEPTCODE, A.DEPTNAME, A.DEPTNA3 ');
// SQL.ADD(' ,(SELECT DEPTNAME FROM PYCDEPT WHERE DEPTCODE = A.EXTCODE AND ORGNUM = '''+ED_orgnum.Text+''') EXTNAME ');
SQL.ADD(' FROM PYCDEPT A ');
SQL.ADD(' WHERE A.ORGNUM = '''+ED_orgnum.Text+''' ');
SQL.ADD(' AND A.DEPTCODE NOT IN ('' '''+GetDeptList+') ');
SQL.ADD(' ORDER BY A.DEPTORDER ');
Open;
If RecordCount > 0 then LIchk := 0;
If RecordCount < 0 then LIchk := -1;
end; }
end;
procedure TFM_MainForm.BT_AddClick(Sender: TObject);
begin
DBGrid1DblClick(DBGrid1);
end;
procedure TFM_MainForm.BT_DelClick(Sender: TObject);
begin
SB_Help.Panels[1].Text := '';
sGridDblClick(Self);
end;
end.
|
unit Hash_CheckSum;
{$I TinyDB.INC}
interface
uses Classes, HashBase;
type
THash_XOR16 = class(THash)
private
FCRC: Word;
protected
class function TestVector: Pointer; override;
public
class function DigestKeySize: Integer; override;
procedure Init; override;
procedure Calc(const Data; DataSize: Integer); override;
function DigestKey: Pointer; override;
end;
THash_XOR32 = class(THash)
private
FCRC: LongWord;
protected
class function TestVector: Pointer; override;
public
class function DigestKeySize: Integer; override;
procedure Init; override;
procedure Calc(const Data; DataSize: Integer); override;
function DigestKey: Pointer; override;
end;
THash_CRC32 = class(THash_XOR32)
private
protected
class function TestVector: Pointer; override;
public
procedure Init; override;
procedure Calc(const Data; DataSize: Integer); override;
procedure Done; override;
end;
THash_CRC16_CCITT = class(THash_XOR16)
private
protected
class function TestVector: Pointer; override;
public
procedure Init; override;
procedure Calc(const Data; DataSize: Integer); override;
end;
THash_CRC16_Standard = class(THash_XOR16)
private
protected
class function TestVector: Pointer; override;
public
procedure Calc(const Data; DataSize: Integer); override;
end;
implementation
uses SysUtils;
class function THash_XOR16.TestVector: Pointer;
asm
MOV EAX,OFFSET @Vector
RET
@Vector: DB 079h,0E8h
end;
class function THash_XOR16.DigestKeySize: Integer;
begin
Result := 2;
end;
procedure THash_XOR16.Init;
begin
FCRC := 0;
end;
procedure THash_XOR16.Calc(const Data; DataSize: Integer); assembler; register;
asm
JECXZ @Exit
PUSH EAX
MOV AX,[EAX].THash_XOR16.FCRC
@@1: ROL AX,5
XOR AL,[EDX]
INC EDX
DEC ECX
JNZ @@1
POP EDX
MOV [EDX].THash_XOR16.FCRC,AX
@Exit:
end;
function THash_XOR16.DigestKey: Pointer;
begin
Result := @FCRC;
end;
class function THash_XOR32.TestVector: Pointer;
asm
MOV EAX,OFFSET @Vector
RET
@Vector: DB 08Dh,0ADh,089h,07Fh
end;
class function THash_XOR32.DigestKeySize: Integer;
begin
Result := 4;
end;
procedure THash_XOR32.Init;
begin
FCRC := 0;
end;
procedure THash_XOR32.Calc(const Data; DataSize: Integer); assembler; register;
asm
JECXZ @Exit
PUSH EAX
MOV EAX,[EAX].THash_XOR32.FCRC
TEST ECX,1
JE @@1
XOR AX,[EDX]
INC EDX
@@1: SHR ECX,1
JECXZ @@3
@@2: ROL EAX,5
XOR AX,[EDX]
ADD EDX,2
DEC ECX
JNZ @@2
@@3: POP EDX
MOV [EDX].THash_XOR32.FCRC,EAX
@Exit:
end;
function THash_XOR32.DigestKey: Pointer;
begin
Result := @FCRC;
end;
class function THash_CRC32.TestVector: Pointer;
asm
MOV EAX,OFFSET @Vector
RET
@Vector: DB 058h,0EEh,01Fh,031h
end;
procedure THash_CRC32.Init;
begin
FCRC := $FFFFFFFF;
end;
procedure THash_CRC32.Calc(const Data; DataSize: Integer); assembler; register;
asm
PUSH EAX
MOV EAX,[EAX].THash_CRC32.FCRC
CALL CRC32
POP EDX
MOV [EDX].THash_CRC32.FCRC,EAX
end;
procedure THash_CRC32.Done;
begin
FCRC := not FCRC;
end;
class function THash_CRC16_CCITT.TestVector: Pointer;
asm
MOV EAX,OFFSET @Vector
RET
@Vector: DB 0B0h,0D1h
end;
procedure THash_CRC16_CCITT.Init;
begin
FCRC := $FFFF;
end;
procedure THash_CRC16_CCITT.Calc(const Data; DataSize: Integer);
asm
OR EDX,EDX
JE @Exit
JCXZ @Exit
PUSH EAX
MOV AX,[EAX].THash_CRC16_CCITT.FCRC
PUSH EBX
XOR EBX,EBX
@Start:
MOV BL,AH
SHL AX,8
MOV AL,[EDX]
XOR AX,CS:[EBX * 2 + OFFSET @CRC16]
INC EDX
DEC ECX
JNZ @Start
POP EBX
POP EDX
MOV [EDX].THash_CRC16_CCITT.FCRC,AX
@Exit: RET
@CRC16: DW 00000h, 01021h, 02042h, 03063h, 04084h, 050A5h, 060C6h, 070E7h
DW 08108h, 09129h, 0A14Ah, 0B16Bh, 0C18Ch, 0D1ADh, 0E1CEh, 0F1EFh
DW 01231h, 00210h, 03273h, 02252h, 052B5h, 04294h, 072F7h, 062D6h
DW 09339h, 08318h, 0B37Bh, 0A35Ah, 0D3BDh, 0C39Ch, 0F3FFh, 0E3DEh
DW 02462h, 03443h, 00420h, 01401h, 064E6h, 074C7h, 044A4h, 05485h
DW 0A56Ah, 0B54Bh, 08528h, 09509h, 0E5EEh, 0F5CFh, 0C5ACh, 0D58Dh
DW 03653h, 02672h, 01611h, 00630h, 076D7h, 066F6h, 05695h, 046B4h
DW 0B75Bh, 0A77Ah, 09719h, 08738h, 0F7DFh, 0E7FEh, 0D79Dh, 0C7BCh
DW 048C4h, 058E5h, 06886h, 078A7h, 00840h, 01861h, 02802h, 03823h
DW 0C9CCh, 0D9EDh, 0E98Eh, 0F9AFh, 08948h, 09969h, 0A90Ah, 0B92Bh
DW 05AF5h, 04AD4h, 07AB7h, 06A96h, 01A71h, 00A50h, 03A33h, 02A12h
DW 0DBFDh, 0CBDCh, 0FBBFh, 0EB9Eh, 09B79h, 08B58h, 0BB3Bh, 0AB1Ah
DW 06CA6h, 07C87h, 04CE4h, 05CC5h, 02C22h, 03C03h, 00C60h, 01C41h
DW 0EDAEh, 0FD8Fh, 0CDECh, 0DDCDh, 0AD2Ah, 0BD0Bh, 08D68h, 09D49h
DW 07E97h, 06EB6h, 05ED5h, 04EF4h, 03E13h, 02E32h, 01E51h, 00E70h
DW 0FF9Fh, 0EFBEh, 0DFDDh, 0CFFCh, 0BF1Bh, 0AF3Ah, 09F59h, 08F78h
DW 09188h, 081A9h, 0B1CAh, 0A1EBh, 0D10Ch, 0C12Dh, 0F14Eh, 0E16Fh
DW 01080h, 000A1h, 030C2h, 020E3h, 05004h, 04025h, 07046h, 06067h
DW 083B9h, 09398h, 0A3FBh, 0B3DAh, 0C33Dh, 0D31Ch, 0E37Fh, 0F35Eh
DW 002B1h, 01290h, 022F3h, 032D2h, 04235h, 05214h, 06277h, 07256h
DW 0B5EAh, 0A5CBh, 095A8h, 08589h, 0F56Eh, 0E54Fh, 0D52Ch, 0C50Dh
DW 034E2h, 024C3h, 014A0h, 00481h, 07466h, 06447h, 05424h, 04405h
DW 0A7DBh, 0B7FAh, 08799h, 097B8h, 0E75Fh, 0F77Eh, 0C71Dh, 0D73Ch
DW 026D3h, 036F2h, 00691h, 016B0h, 06657h, 07676h, 04615h, 05634h
DW 0D94Ch, 0C96Dh, 0F90Eh, 0E92Fh, 099C8h, 089E9h, 0B98Ah, 0A9ABh
DW 05844h, 04865h, 07806h, 06827h, 018C0h, 008E1h, 03882h, 028A3h
DW 0CB7Dh, 0DB5Ch, 0EB3Fh, 0FB1Eh, 08BF9h, 09BD8h, 0ABBBh, 0BB9Ah
DW 04A75h, 05A54h, 06A37h, 07A16h, 00AF1h, 01AD0h, 02AB3h, 03A92h
DW 0FD2Eh, 0ED0Fh, 0DD6Ch, 0CD4Dh, 0BDAAh, 0AD8Bh, 09DE8h, 08DC9h
DW 07C26h, 06C07h, 05C64h, 04C45h, 03CA2h, 02C83h, 01CE0h, 00CC1h
DW 0EF1Fh, 0FF3Eh, 0CF5Dh, 0DF7Ch, 0AF9Bh, 0BFBAh, 08FD9h, 09FF8h
DW 06E17h, 07E36h, 04E55h, 05E74h, 02E93h, 03EB2h, 00ED1h, 01EF0h
end;
class function THash_CRC16_Standard.TestVector: Pointer;
asm
MOV EAX,OFFSET @Vector
RET
@Vector: DB 0EDh,075h
end;
procedure THash_CRC16_Standard.Calc(const Data; DataSize: Integer);
asm
OR EDX,EDX
JE @Exit
JCXZ @Exit
PUSH EAX
MOV AX,[EAX].THash_CRC16_Standard.FCRC
PUSH EBX
XOR EBX,EBX
@Start:
MOV BL,[EDX]
XOR BL,AL
SHR AX,8
XOR AX,CS:[EBX * 2 + OFFSET @CRC16]
INC EDX
DEC ECX
JNZ @Start
POP EBX
POP EDX
MOV [EDX].THash_CRC16_Standard.FCRC,AX
@Exit: RET
@CRC16: DW 00000h, 0C0C1h, 0C181h, 00140h, 0C301h, 003C0h, 00280h, 0C241h
DW 0C601h, 006C0h, 00780h, 0C741h, 00500h, 0C5C1h, 0C481h, 00440h
DW 0CC01h, 00CC0h, 00D80h, 0CD41h, 00F00h, 0CFC1h, 0CE81h, 00E40h
DW 00A00h, 0CAC1h, 0CB81h, 00B40h, 0C901h, 009C0h, 00880h, 0C841h
DW 0D801h, 018C0h, 01980h, 0D941h, 01B00h, 0DBC1h, 0DA81h, 01A40h
DW 01E00h, 0DEC1h, 0DF81h, 01F40h, 0DD01h, 01DC0h, 01C80h, 0DC41h
DW 01400h, 0D4C1h, 0D581h, 01540h, 0D701h, 017C0h, 01680h, 0D641h
DW 0D201h, 012C0h, 01380h, 0D341h, 01100h, 0D1C1h, 0D081h, 01040h
DW 0F001h, 030C0h, 03180h, 0F141h, 03300h, 0F3C1h, 0F281h, 03240h
DW 03600h, 0F6C1h, 0F781h, 03740h, 0F501h, 035C0h, 03480h, 0F441h
DW 03C00h, 0FCC1h, 0FD81h, 03D40h, 0FF01h, 03FC0h, 03E80h, 0FE41h
DW 0FA01h, 03AC0h, 03B80h, 0FB41h, 03900h, 0F9C1h, 0F881h, 03840h
DW 02800h, 0E8C1h, 0E981h, 02940h, 0EB01h, 02BC0h, 02A80h, 0EA41h
DW 0EE01h, 02EC0h, 02F80h, 0EF41h, 02D00h, 0EDC1h, 0EC81h, 02C40h
DW 0E401h, 024C0h, 02580h, 0E541h, 02700h, 0E7C1h, 0E681h, 02640h
DW 02200h, 0E2C1h, 0E381h, 02340h, 0E101h, 021C0h, 02080h, 0E041h
DW 0A001h, 060C0h, 06180h, 0A141h, 06300h, 0A3C1h, 0A281h, 06240h
DW 06600h, 0A6C1h, 0A781h, 06740h, 0A501h, 065C0h, 06480h, 0A441h
DW 06C00h, 0ACC1h, 0AD81h, 06D40h, 0AF01h, 06FC0h, 06E80h, 0AE41h
DW 0AA01h, 06AC0h, 06B80h, 0AB41h, 06900h, 0A9C1h, 0A881h, 06840h
DW 07800h, 0B8C1h, 0B981h, 07940h, 0BB01h, 07BC0h, 07A80h, 0BA41h
DW 0BE01h, 07EC0h, 07F80h, 0BF41h, 07D00h, 0BDC1h, 0BC81h, 07C40h
DW 0B401h, 074C0h, 07580h, 0B541h, 07700h, 0B7C1h, 0B681h, 07640h
DW 07200h, 0B2C1h, 0B381h, 07340h, 0B101h, 071C0h, 07080h, 0B041h
DW 05000h, 090C1h, 09181h, 05140h, 09301h, 053C0h, 05280h, 09241h
DW 09601h, 056C0h, 05780h, 09741h, 05500h, 095C1h, 09481h, 05440h
DW 09C01h, 05CC0h, 05D80h, 09D41h, 05F00h, 09FC1h, 09E81h, 05E40h
DW 05A00h, 09AC1h, 09B81h, 05B40h, 09901h, 059C0h, 05880h, 09841h
DW 08801h, 048C0h, 04980h, 08941h, 04B00h, 08BC1h, 08A81h, 04A40h
DW 04E00h, 08EC1h, 08F81h, 04F40h, 08D01h, 04DC0h, 04C80h, 08C41h
DW 04400h, 084C1h, 08581h, 04540h, 08701h, 047C0h, 04680h, 08641h
DW 08201h, 042C0h, 04380h, 08341h, 04100h, 081C1h, 08081h, 04040h
end;
end.
|
unit Form.Browser;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Component.UAWebbrowser,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.OleCtrls, SHDocVw,
Global.LanguageString;
procedure BrowserCreate(Sender: TForm);
const
WM_AFTER_SHOW = WM_USER + 300;
type
TfBrowser = class(TForm)
procedure FormResize(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure wbPluginNavigateComplete2(ASender: TObject;
const pDisp: IDispatch; const URL: OleVariant);
procedure WmAfterShow(var Msg: TMessage); message WM_AFTER_SHOW;
procedure FormShow(Sender: TObject);
private
wbPlugin: TUAWebBrowser;
public
{ Public declarations }
end;
var
fBrowser: TfBrowser;
implementation
{$R *.dfm}
procedure BrowserCreate(Sender: TForm);
begin
if fBrowser <> Nil then FreeAndNil(fBrowser);
fBrowser := TfBrowser.Create(Sender);
try
fBrowser.ShowModal;
finally
FreeAndNil(fBrowser);
end;
end;
procedure TfBrowser.FormCreate(Sender: TObject);
begin
wbPlugin := TUAWebBrowser.Create(self);
wbPlugin.SetParentComponent(self);
wbPlugin.Navigate('about:blank');
wbPlugin.OnNavigateComplete2 := wbPluginNavigateComplete2;
end;
procedure TfBrowser.FormResize(Sender: TObject);
begin
wbPlugin.Width := ClientWidth;
wbPlugin.Height := ClientHeight;
end;
procedure TfBrowser.FormShow(Sender: TObject);
begin
PostMessage(Self.Handle, WM_AFTER_SHOW, 0, 0);
end;
procedure TfBrowser.wbPluginNavigateComplete2(ASender: TObject;
const pDisp: IDispatch; const URL: OleVariant);
begin
Caption := wbPlugin.OleObject.Document.Title;
end;
procedure TfBrowser.WmAfterShow(var Msg: TMessage);
begin
wbPlugin.Navigate(AddrSecureErase[CurrLang]);
end;
end.
|
unit LuaTree;
{$mode Delphi}{$H+}
interface
Uses LuaPas,LuaControl,ComCtrls,Controls,Classes,Types,LuaCanvas, DOM, lazutf8, LazFileUtils;
function CreateTreeView(L: Plua_State): Integer; cdecl;
type
TLuaTreeView = class(TTreeView)
LuaCtl: TLuaControl;
LuaCanvas: TLuaCanvas;
private
FDoc: TXMLDocument;
public
destructor Destroy; override;
end;
// forward
function LoadTreeFromLuaTable(L: Plua_State; idx:Integer; PN:TLuaTreeView; TI:TTreeNode):Boolean;
procedure TreeNodeToTable(L:Plua_State; Index:Integer; Sender:TObject);
implementation
Uses Forms, SysUtils, Lua, LuaImageList, LuaProperties, fileutil, XMLRead;
procedure lua_pushstring(L : Plua_State; const s : WideString); overload;
begin
lua_pushstring(L, PChar(UTF16toUTF8(s)));
end;
// **************************************************************
function BeginUpdate(L: Plua_State): Integer; cdecl;
var
lTree:TLuaTreeView;
begin
CheckArg(L, 1);
lTree := TLuaTreeView(GetLuaObject(L, 1));
lTree.BeginUpdate;
Result := 0;
end;
function EndUpdate(L: Plua_State): Integer; cdecl;
var
lTree:TLuaTreeView;
begin
CheckArg(L, 1);
lTree := TLuaTreeView(GetLuaObject(L, 1));
lTree.EndUpdate;
Result := 0;
end;
function ClearTree(L: Plua_State): Integer; cdecl;
var
lTree:TLuaTreeView;
begin
CheckArg(L, 1);
lTree := TLuaTreeView(GetLuaObject(L, 1));
if lTree <> nil then
lTree.Items.Clear;
Result := 0;
end;
function DeleteFromTree(L: Plua_State): Integer; cdecl;
var
lTree:TLuaTreeView;
TN:TTreeNode;
begin
CheckArg(L, 2);
lTree := TLuaTreeView(GetLuaObject(L, 1));
TN := lTree.Items[trunc(lua_tonumber(L,2))];
if TN <> nil then
TN.Delete;
Result := 0;
end;
function GetSelected(L: Plua_State): Integer; cdecl;
var
lTree:TLuaTreeView;
i:Integer;
begin
CheckArg(L, 1);
lTree := TLuaTreeView(GetLuaObject(L, 1));
if (lTree <> nil) and Assigned(lTree.Selected) then begin
lua_newtable(L);
for i:=0 to lTree.Selected.Count-1 do begin
lua_pushnumber(L, i + 1);
TreeNodeToTable(L,-1, lTree.Selections[i] );
lua_rawset(L,-3);
end;
end else
lua_pushnil(L);
Result := 1;
end;
function GetNode(L: Plua_State): Integer; cdecl;
var
lTree:TLuaTreeView;
TN: TTreeNode;
begin
CheckArg(L, 2);
lTree := TLuaTreeView(GetLuaObject(L, 1));
try
TN := lTree.Items[trunc(lua_tonumber(L,2))];
except
end;
if (Assigned(TN)) then begin
TreeNodeToTable(L,-1,TN)
end else
lua_pushnil(L);
Result := 1;
end;
function GetChildNodes(L: Plua_State): Integer; cdecl;
var
lTree:TLuaTreeView;
TN: TTreeNode;
i:Integer;
begin
CheckArg(L, 2);
lTree := TLuaTreeView(GetLuaObject(L, 1));
try
TN := lTree.Items[trunc(lua_tonumber(L,2))];
except
end;
if (Assigned(TN)) then begin
lua_newtable(L);
for i:= 0 to TN.Count-1 do begin
lua_pushnumber(L, i + 1);
TreeNodeToTable(L,-1, TN.Items[i] );
lua_rawset(L,-3);
end;
end else
lua_pushnil(L);
Result := 1;
end;
function LoadTreeFromLuaTable(L: Plua_State; idx:Integer; PN:TLuaTreeView; TI:TTreeNode):Boolean;
var m: Integer;
key,val:String;
P:Pointer;
NewTI:TTreeNode;
begin
result := false;
if lua_istable(L,idx) then begin
m := lua_gettop(L);
result := true;
lua_pushnil(L);
while (lua_next(L, m) <> 0) do begin
if lua_istable(L,-1) and lua_isnumber(L,-2) then begin
if TI = nil then begin
TI := PN.Items.AddChild(nil,'');
TI.ImageIndex := -1;
TI.SelectedIndex := -1;
end;
newTI := PN.Items.AddChild(TI,'');
LoadTreeFromLuaTable(L,-1,PN,newTI);
end else begin
if TI = nil then begin
TI := PN.Items.AddChild(TI,'');
TI.ImageIndex := -1;
TI.SelectedIndex := -1;
end;
key := lua_tostring(L, -2);
val := lua_tostring(L, -1);
if uppercase(key) = 'DATA' then begin
TI.Data := lua_topointer(L,-1);
end else begin
LuaSetControlProperty(L, TComponent(TI), key, -1); // value on top
end;
(*
else if uppercase(key) = 'TEXT' then begin
TI.Text := lua_tostring(L, -1);
end
else if uppercase(key) = 'IMAGE' then begin
TI.ImageIndex := trunc(lua_tonumber(L, -1)-1);
if TI.SelectedIndex = -1 then
TI.SelectedIndex := TI.ImageIndex;
end
else if uppercase(key) = 'SELECTED' then begin
TI.SelectedIndex := trunc(lua_tonumber(L, -1)-1);
end
*)
end;
lua_pop(L, 1);
end;
end;
end;
function AddToTree(L: Plua_State): Integer; cdecl;
var
lTree:TLuaTreeView;
TN,SN:TTreeNode;
n: Integer;
begin
n := lua_gettop(L);
CheckArg(L, 3);
lTree := TLuaTreeView(GetLuaObject(L, 1));
// insert as root or add node
if (lua_isnil(L,2)) then begin
SN := nil;
end else begin
SN := lTree.Items[trunc(lua_tonumber(L,2))];
end;
TN := lTree.Items.AddChild(SN,'');
// load from table or set text
if lua_istable(L,3) then begin
LoadTreeFromLuaTable(L,3,lTree,TN)
end else begin
TN.Text := lua_tostring(L,3);
end;
lua_pushnumber(L,TN.AbsoluteIndex);
Result := 1;
end;
function SetItems(L: Plua_State): Integer; cdecl;
var
lTree:TLuaTreeView;
TI:TTreeNode;
n:Integer;
begin
CheckArg(L, 2);
lTree := TLuaTreeView(GetLuaObject(L, 1));
n := lua_gettop(L);
if lua_istable(L,2) then begin
lua_pushnil(L);
while (lua_next(L, n) <> 0) do begin
LoadTreeFromLuaTable(L,n,lTree,nil);
lua_pop(L, 1);
end;
end;
result := 0;
end;
function GetItemData(L: Plua_State): Integer; cdecl;
var
lTree:TLuaTreeView;
TN: TTreeNode;
begin
CheckArg(L, 2);
lTree := TLuaTreeView(GetLuaObject(L, 1));
TN := lTree.Items[trunc(lua_tonumber(L,2))];
lua_pushlightuserdata(L,TN.Data);
Result := 1;
end;
function SetItemData(L: Plua_State): Integer; cdecl;
var
lTree:TLuaTreeView;
TN: TTreeNode;
P:Pointer;
begin
CheckArg(L, 3);
lTree := TLuaTreeView(GetLuaObject(L, 1));
TN := lTree.Items[trunc(lua_tonumber(L,2))];
TN.Data := lua_topointer(L,3);
Result := 0;
end;
function GetDOMNode(L: Plua_State): Integer; cdecl;
var
lTree:TLuaTreeView;
Node:TDOMNode;
// s:WideString;
n:integer;
function DOMnodetotable(TTN:TDOMNode):Integer;
var i:Integer;
begin
if Assigned(TTN.Attributes) then begin
lua_pushliteral(L, 'Attr');
lua_newtable(L);
for i:=0 to TTN.Attributes.Length-1 do begin
// lua_pushliteral(L, 'Name');
lua_pushstring(L, TTN.Attributes[i].NodeName);
// lua_rawset(L,-3);
// lua_pushliteral(L, 'Value');
lua_pushstring(L, TTN.Attributes[i].NodeValue);
lua_rawset(L,-3);
end;
lua_rawset(L,-3);
end;
result := i;
end;
begin
CheckArg(L, 2);
lTree := TLuaTreeView(GetLuaObject(L, 1));
n := trunc(lua_tonumber(L,2));
if Assigned(lTree.Items[n]) then
Node:=TDOMNode(lTree.Items[n].Data);
if (Assigned(Node)) then
begin
lua_newtable(L);
lua_pushliteral(L, 'Name');
lua_pushstring(L, Node.NodeName);
lua_rawset(L,-3);
lua_pushliteral(L, 'Value');
lua_pushstring(L, Node.NodeValue);
lua_rawset(L,-3);
n := DomNodeToTable(Node);
// if (n=0) then lua_pushnil(L);
end else
lua_pushnil(L);
Result := 1;
end;
function SetTreeImages(L: Plua_State): Integer; cdecl;
var
lTree:TLuaTreeView;
TI:TLuaImageList;
begin
CheckArg(L, 2);
lTree := TLuaTreeView(GetLuaObject(L, 1));
TI := TLuaImageList(GetLuaObject(L, 2));
lTree.Images := TI;
Result := 0;
end;
function SetNodeImage(L: Plua_State): Integer; cdecl;
var
lTree:TLuaTreeView;
TN: TTreeNode;
P:Pointer;
begin
CheckArg(L, 3);
lTree := TLuaTreeView(GetLuaObject(L, 1));
TN := lTree.Items[trunc(lua_tonumber(L,2))];
TN.ImageIndex := trunc(lua_tonumber(L,3));
Result := 0;
end;
function SetNodeSelectedImage(L: Plua_State): Integer; cdecl;
var
lTree:TLuaTreeView;
TN: TTreeNode;
P:Pointer;
begin
CheckArg(L, 3);
lTree := TLuaTreeView(GetLuaObject(L, 1));
TN := lTree.Items[trunc(lua_tonumber(L,2))];
TN.SelectedIndex := trunc(lua_tonumber(L,3));
Result := 0;
end;
function TreeSaveToFile(L: Plua_State): Integer; cdecl;
var
lT:TLuaTreeView;
fn:String;
begin
CheckArg(L,2);
lT := TLuaTreeView(GetLuaObject(L, 1));
lT.SaveToFile(lua_tostring(L,2));
Result := 0;
end;
function TreeLoadFromFile(L: Plua_State): Integer; cdecl;
var
lT:TLuaTreeView;
fn:String;
begin
CheckArg(L,2);
lT := TLuaTreeView(GetLuaObject(L, 1));
lT.LoadFromFile(lua_tostring(L,2));
Result := 0;
end;
// **********************************************************************************
// XML
// **********************************************************************************
function ParseXML(L: Plua_State): Integer; cdecl;
var lC:TLuaTreeView;
sux: Boolean;
procedure DoFill(AOwner:TTreeNode; Node:TDOMNode);
var
i: integer;
AItem:TTreeNode;
begin
if not Assigned(Node) then exit;
for i:=0 to Node.ChildNodes.Count - 1 do
begin
AItem:=lC.Items.AddChild(AOwner, Node.ChildNodes[i].NodeName);
AItem.Data:=Node.ChildNodes[i];
if not Assigned(lC.Selected) then
lC.Selected:=AItem;
DoFill(AItem, Node.ChildNodes[i]);
end;
end;
var b: TStringStream;
s: String;
begin
sux := false;
CheckArg(L,2);
lC := TLuaTreeView(GetLuaObject(L, 1));
s := String(lua_tostring(L,2));
if Assigned(lC.FDoc) then lC.FDoc.Free;
if FileExistsUTF8(s) then begin
try
ReadXMLFile(lC.FDoc, UTF8ToSys(s));
sux := true;
except
FreeAndNil(lC.FDoc);
end;
end else begin
try
b := TStringStream.Create(s);
b.WriteBuffer(Pointer(s)^,Length(s));
b.Seek(0,0);
ReadXMLFile(lC.FDoc, b);
b.Free;
sux := true;
except
FreeAndNil(lC.FDoc);
end;
end;
if Assigned(lC.FDoc) then begin
lC.Selected:=nil;
lC.Items.BeginUpdate;
lC.Items.Clear;
DoFill(nil, lC.FDoc);
lC.Items.EndUpdate;
end;
lua_pushboolean(L,sux);
Result := 1;
end;
function TreeGetCanvas(L: Plua_State): Integer; cdecl;
var lC:TLuaTreeView;
begin
lC := TLuaTreeView(GetLuaObject(L, 1));
lC.LuaCanvas.ToTable(L, -1, lC.Canvas);
result := 1;
end;
destructor TLuaTreeView.Destroy;
begin
if (LuaCanvas<>nil) then LuaCanvas.Free;
if Assigned(FDoc) then FDoc.Free;
inherited Destroy;
end;
procedure TreeNodeToTable(L:Plua_State; Index:Integer; Sender:TObject);
begin
SetDefaultMethods(L, Index, Sender);
LuaSetMetaFunction(L, index, '__index', @LuaGetProperty);
LuaSetMetaFunction(L, index, '__newindex', @LuaSetProperty);
end;
procedure ToTable(L:Plua_State; Index:Integer; Sender:TObject);
begin
SetDefaultMethods(L, Index, Sender);
LuaSetTableFunction(L, Index, 'BeginUpdate', BeginUpdate);
LuaSetTableFunction(L, Index, 'EndUpdate', EndUpdate);
LuaSetTableFunction(L, Index, 'Selected', GetSelected);
LuaSetTableFunction(L, Index, 'Get', GetNode);
LuaSetTableFunction(L, Index, 'GetChildNodes', GetChildNodes);
LuaSetTableFunction(L, Index, 'GetData', GetItemData);
LuaSetTableFunction(L, Index, 'SetData', SetItemData);
LuaSetTableFunction(L, Index, 'GetDOMNode', GetDOMNode);
LuaSetTableFunction(L, Index, 'Clear', ClearTree);
LuaSetTableFunction(L, Index, 'Add', AddToTree);
LuaSetTableFunction(L, Index, 'Delete', DeleteFromTree);
LuaSetTableFunction(L, Index, 'SaveToFile',@TreeSaveToFile);
LuaSetTableFunction(L, Index, 'LoadFromFile',@TreeLoadFromFile);
LuaSetTableFunction(L, Index, 'LoadXML',@ParseXML);
if (Sender.InheritsFrom(TCustomControl) or Sender.InheritsFrom(TGraphicControl)) then
LuaSetTableFunction(L, Index, 'GetCanvas', TreeGetCanvas);
LuaSetMetaFunction(L, index, '__index', @LuaGetProperty);
LuaSetMetaFunction(L, index, '__newindex', @LuaSetProperty);
end;
function CreateTreeView(L: Plua_State): Integer; cdecl;
var
lTree:TLuaTreeView;
Parent:TComponent;
Name:String;
begin
GetControlParents(L,Parent,Name);
lTree := TLuaTreeView.Create(Parent);
lTree.Parent := TWinControl(Parent);
lTree.LuaCtl := TLuaControl.Create(lTree,L,@ToTable);
if (lua_gettop(L)>0) and (GetLuaObject(L, -1) = nil) then
SetPropertiesFromLuaTable(L, TObject(lTree),-1)
else
lTree.Name := Name;
if (lTree.InheritsFrom(TCustomControl) or lTree.InheritsFrom(TGraphicControl)) then
lTree.LuaCanvas := TLuaCanvas.Create;
ToTable(L, -1, lTree);
Result := 1;
end;
end.
|
{***********************************<_INFO>************************************}
{ <Проект> Медиа-сервер }
{ }
{ <Область> 16:Медиа-контроль }
{ }
{ <Задача> Медиа-источник, предоставляющий чтение данных из файла }
{ }
{ <Автор> Фадеев Р.В. }
{ }
{ <Дата> 14.01.2011 }
{ }
{ <Примечание> Нет примечаний. }
{ }
{ <Атрибуты> ООО НПП "Спецстрой-Связь", ООО "Трисофт" }
{ }
{***********************************</_INFO>***********************************}
unit MediaServer.Stream.Source.File_;
interface
uses Windows, SysUtils, Classes, SyncObjs,uBaseClasses,
MediaServer.Stream.Source,
MediaProcessing.Definitions,MediaStream.Framer, MediaStream.DataSource.File_;
type
TMediaServerSourceFile = class;
TFileFinishedEvent = procedure (Sender: TMediaServerSourceFile; const aFileName: string) of object;
//Класс, выполняющий непосредственно получение данных (видеопотока)
TMediaServerSourceFile = class (TMediaServerSourceBasedOnMediaStream)
private
FFileName: string;
//FOnFileFinished: TFileFinishedEvent;
public
constructor Create(const aFileName: string;
aTransmitAudio: boolean //Записывать ли аудио
); overload;
destructor Destroy; override;
function Name: string; override;
function DeviceType: string; override;
function ConnectionString: string; override;
function PtzSupported: boolean; override;
//property OnFileFinished: TFileFinishedEvent read FOnFileFinished write FOnFileFinished;
//property Framer: TStreamFramer read FFramer;
end;
implementation
uses Math,Forms,ThreadNames, VFW, MediaServer.Workspace, uTrace,
MediaStream.FramerFactory,MediaStream.UrlFormats;
{ TMediaServerSourceFile }
constructor TMediaServerSourceFile.Create(const aFileName: string;aTransmitAudio: boolean);
var
aParams: TMediaStreamDataSourceConnectParams_File;
begin
aParams:=TMediaStreamDataSourceConnectParams_File.Create(aFileName,true,aTransmitAudio);
inherited Create(aParams, TMediaStreamDataSource_File, aTransmitAudio, -1);
FFileName:=aFileName;
end;
destructor TMediaServerSourceFile.Destroy;
begin
inherited;
end;
function TMediaServerSourceFile.DeviceType: string;
begin
result:='Файл';
end;
function TMediaServerSourceFile.Name: string;
begin
result:=FFileName;
end;
function TMediaServerSourceFile.ConnectionString: string;
begin
result:=MakeFileUrl(FFileName);
end;
function TMediaServerSourceFile.PtzSupported: boolean;
begin
result:=false;
end;
end.
|
unit SpectrumTypes;
interface
uses
SysUtils, Math,
OriIniFile;
type
TValue = Double;
TValueArray = array of TValue;
PValueArray = ^TValueArray;
const
CMinValue = -MaxDouble;
CMaxValue = MaxDouble;
VALUE_MIN = -MaxDouble;
VALUE_MAX = MaxDouble;
type
TSimpleSearchKind = (skFindMax, skFindMin, skFindWHM, skFindDlt, skFindAvg, skIntegral);
TDecimalSeparator = (dsAuto, dsSystem, dsPoint, dsComma);
TLineDelimiter = (ldWindows, ldUnix, ldMac, ldSpecial);
TValueDelimiter = (vdTab, vdSpace, vdCustom);
TGraphRec = record
X, Y: TValueArray;
end;
PGraphRec = ^TGraphRec;
TGraphRecs = array of TGraphRec;
TGraphRec2 = record
X, Y1, Y2: TValueArray;
end;
TAxisDirection = (adirX, adirY);
TGroupOperation = (gropSum, gropDiff, gropProd, gropQuot);
TScaleCenterKind = (sckNone, sckMax, sckMin, sckAvg, sckValue);
TScaleParams = packed record
Direction: TAxisDirection;
CenterKind: TScaleCenterKind;
CenterValue: TValue;
Value: TValue;
end;
PScaleParams = ^TScaleParams;
TNormalizeParams = packed record
Direction: TAxisDirection;
PerMaximum: Boolean;
Value: TValue;
end;
PNormalizeParams = ^TNormalizeParams;
TOffsetKind = (ofkMax, ofkMin, ofkAvg, ofkValue);
TOffsetParams = packed record
Direction: TAxisDirection;
Kind: TOffsetKind;
Value: TValue;
end;
POffsetParams = ^TOffsetParams;
TDespikeRange = (drPercent, drAbsolute);
TDespikeParams = packed record
Kind: TDespikeRange;
Min: TValue;
Max: TValue;
end;
PDespikeParams = ^TDespikeParams;
TMiscParams = packed record
Direction: TAxisDirection;
Value: TValue;
end;
PMiscParams = ^TMiscParams;
TRangeParams = packed record
Min, Max, Step: TValue;
Points: Integer;
UseStep: Boolean;
end;
PRangeParams = ^TRangeParams;
procedure CalcStep(var AParams: TRangeParams; out ACount: Integer; out AStep: TValue);
procedure Save(var AParams: TRangeParams; const Key: String; Ini: TOriIniFile); overload;
procedure Load(var AParams: TRangeParams; const Key: String; Ini: TOriIniFile); overload;
type
TRandomSampleParams = packed record
X: TRangeParams;
MinY, MaxY: TValue;
end;
PRandomSampleParams = ^TRandomSampleParams;
TFormulaParams = class
public
Formula: String;
Range: TRangeParams;
end;
TTrimParams = packed record
TrimLeft, TrimRight: Boolean;
VisibleLeft, VisibleRight: Boolean;
RefineLeft, RefineRight: Boolean;
ValueLeft, ValueRight: TValue;
end;
PTrimParams = ^TTrimParams;
TVarianceKind = (varStandard, varAllan);
TVarianceParams = record
Kind: TVarianceKind;
end;
PVarianceParams = ^TVarianceParams;
const
VarianceNames: array[TVarianceKind] of String = ('SDEV', 'ADEV');
type
ESpectrumError = class(Exception);
implementation
{%region 'TRangeParams'}
procedure CalcStep(var AParams: TRangeParams; out ACount: Integer; out AStep: TValue);
begin
with AParams do
if UseStep then
begin
ACount := Trunc((Max - Min) / Step) + 1;
AStep := Step;
end
else
begin
ACount := Points;
AStep := (Max - Min) / (Points - 1);
end;
end;
procedure Save(var AParams: TRangeParams; const Key: String; Ini: TOriIniFile);
begin
with AParams, Ini do
begin
WriteFloat(Key + '.Min', Min);
WriteFloat(Key + '.Max', Max);
WriteFloat(Key + '.Step', Step);
WriteInteger(Key + '.Points', Points);
WriteBool(Key + '.UseStep', UseStep);
end
end;
procedure Load(var AParams: TRangeParams; const Key: String; Ini: TOriIniFile);
begin
with AParams, Ini do
begin
Min := ReadFloat(Key + '.Min', 0);
Max := ReadFloat(Key + '.Max', 100);
Step := ReadFloat(Key + '.Step', 1);
Points := ReadInteger(Key + '.Points', 101);
UseStep := ReadBool(Key + '.UseStep', True);
end;
end;
{%endregion}
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC MongoDB API wrapping classes }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
{$SCOPEDENUMS ON}
unit FireDAC.Phys.MongoDBWrapper;
interface
uses
System.SysUtils, System.Classes, System.Generics.Collections, System.Rtti,
System.JSON.Types, System.JSON.Readers, System.JSON.Writers,
System.JSON.BSON, System.JSON.Builders,
FireDAC.Stan.Intf, FireDAC.Stan.Error, FireDAC.Stan.Util,
FireDAC.Phys.MongoDBCli;
type
TMongoClientLib = class;
TMongoBSONLib = class;
TMongoObject = class;
TFDMongoError = class;
EMongoNativeException = class;
TMongoError = class;
TMongoEnv = class;
TMongoOID = class;
TMongoDocument = class;
TMongoReadPreference = class;
TMongoWriteConcern = class;
TMongoExpression<T: class> = class;
IMongoCursor = interface;
TMongoPipeline = class;
TMongoQuery = class;
TMongoCommand = class;
TMongoUpdate = class;
TMongoSelector = class;
TMongoInsert = class;
TMongoIndex = class;
TMongoCursor = class;
TMongoConnection = class;
TMongoDatabase = class;
TMongoCollection = class;
/// <summary> The MongoDB query flags. </summary>
TMongoQueryFlag = (TailableCursors, SlaveOk, NoCursorTimeout, AwaitData, Exhaust, Partial);
TMongoQueryFlags = set of TMongoQueryFlag;
/// <summary> Loads the libmongoc-xxx dynamic library and obtains MongoDB API
/// entry points. </summary>
TMongoClientLib = class(TFDLibrary)
protected
procedure LoadEntries; override;
public
// mongoc.h
Fmongoc_client_new: Tmongoc_client_new;
Fmongoc_client_destroy: Tmongoc_client_destroy;
Fmongoc_client_command: Tmongoc_client_command;
Fmongoc_client_command_simple: Tmongoc_client_command_simple;
Fmongoc_client_kill_cursor: Tmongoc_client_kill_cursor;
Fmongoc_client_get_database: Tmongoc_client_get_database;
Fmongoc_client_get_collection: Tmongoc_client_get_collection;
Fmongoc_client_find_databases: Tmongoc_client_find_databases;
Fmongoc_client_get_server_status: Tmongoc_client_get_server_status;
Fmongoc_client_get_max_message_size: Tmongoc_client_get_max_message_size;
Fmongoc_client_get_max_bson_size: Tmongoc_client_get_max_bson_size;
Fmongoc_client_get_write_concern: Tmongoc_client_get_write_concern;
Fmongoc_client_set_write_concern: Tmongoc_client_set_write_concern;
Fmongoc_client_get_read_prefs: Tmongoc_client_get_read_prefs;
Fmongoc_client_set_read_prefs: Tmongoc_client_set_read_prefs;
Fmongoc_client_set_ssl_opts: Tmongoc_client_set_ssl_opts;
Fmongoc_client_get_uri: Tmongoc_client_get_uri;
// mongoc-uri.h
Fmongoc_uri_get_string: Tmongoc_uri_get_string;
// mongoc-bulk-operation.h
Fmongoc_bulk_operation_new: Tmongoc_bulk_operation_new;
Fmongoc_bulk_operation_destroy: Tmongoc_bulk_operation_destroy;
Fmongoc_bulk_operation_execute: Tmongoc_bulk_operation_execute;
Fmongoc_bulk_operation_insert: Tmongoc_bulk_operation_insert;
Fmongoc_bulk_operation_remove: Tmongoc_bulk_operation_remove;
Fmongoc_bulk_operation_remove_one: Tmongoc_bulk_operation_remove_one;
Fmongoc_bulk_operation_replace_one: Tmongoc_bulk_operation_replace_one;
Fmongoc_bulk_operation_update: Tmongoc_bulk_operation_update;
Fmongoc_bulk_operation_update_one: Tmongoc_bulk_operation_update_one;
// mongoc-collection.h
Fmongoc_collection_aggregate: Tmongoc_collection_aggregate;
Fmongoc_collection_destroy: Tmongoc_collection_destroy;
Fmongoc_collection_command: Tmongoc_collection_command;
Fmongoc_collection_command_simple: Tmongoc_collection_command_simple;
Fmongoc_collection_count: Tmongoc_collection_count;
Fmongoc_collection_count_with_opts: Tmongoc_collection_count_with_opts;
Fmongoc_collection_drop: Tmongoc_collection_drop;
Fmongoc_collection_drop_index: Tmongoc_collection_drop_index;
Fmongoc_collection_create_index: Tmongoc_collection_create_index;
Fmongoc_collection_find_indexes: Tmongoc_collection_find_indexes;
Fmongoc_collection_find: Tmongoc_collection_find;
Fmongoc_collection_insert: Tmongoc_collection_insert;
Fmongoc_collection_update: Tmongoc_collection_update;
Fmongoc_collection_save: Tmongoc_collection_save;
Fmongoc_collection_remove: Tmongoc_collection_remove;
Fmongoc_collection_rename: Tmongoc_collection_rename;
Fmongoc_collection_find_and_modify: Tmongoc_collection_find_and_modify;
Fmongoc_collection_stats: Tmongoc_collection_stats;
Fmongoc_collection_create_bulk_operation: Tmongoc_collection_create_bulk_operation;
Fmongoc_collection_get_read_prefs: Tmongoc_collection_get_read_prefs;
Fmongoc_collection_set_read_prefs: Tmongoc_collection_set_read_prefs;
Fmongoc_collection_get_write_concern: Tmongoc_collection_get_write_concern;
Fmongoc_collection_set_write_concern: Tmongoc_collection_set_write_concern;
Fmongoc_collection_get_name: Tmongoc_collection_get_name;
Fmongoc_collection_get_last_error: Tmongoc_collection_get_last_error;
Fmongoc_collection_validate: Tmongoc_collection_validate;
// mongoc-cursor.h
Fmongoc_cursor_destroy: Tmongoc_cursor_destroy;
Fmongoc_cursor_more: Tmongoc_cursor_more;
Fmongoc_cursor_next: Tmongoc_cursor_next;
Fmongoc_cursor_error: Tmongoc_cursor_error;
Fmongoc_cursor_current: Tmongoc_cursor_current;
Fmongoc_cursor_is_alive: Tmongoc_cursor_is_alive;
// mongoc-database.h
Fmongoc_database_get_name: Tmongoc_database_get_name;
Fmongoc_database_remove_user: Tmongoc_database_remove_user;
Fmongoc_database_remove_all_users: Tmongoc_database_remove_all_users;
Fmongoc_database_add_user: Tmongoc_database_add_user;
Fmongoc_database_destroy: Tmongoc_database_destroy;
Fmongoc_database_command: Tmongoc_database_command;
Fmongoc_database_command_simple: Tmongoc_database_command_simple;
Fmongoc_database_drop: Tmongoc_database_drop;
Fmongoc_database_has_collection: Tmongoc_database_has_collection;
Fmongoc_database_create_collection: Tmongoc_database_create_collection;
Fmongoc_database_get_read_prefs: Tmongoc_database_get_read_prefs;
Fmongoc_database_set_read_prefs: Tmongoc_database_set_read_prefs;
Fmongoc_database_get_write_concern: Tmongoc_database_get_write_concern;
Fmongoc_database_set_write_concern: Tmongoc_database_set_write_concern;
Fmongoc_database_find_collections: Tmongoc_database_find_collections;
Fmongoc_database_get_collection: Tmongoc_database_get_collection;
// mongoc-index.h
Fmongoc_index_opt_get_default: Tmongoc_index_opt_get_default;
Fmongoc_index_opt_init: Tmongoc_index_opt_init;
// mongoc-init.h
Fmongoc_init: Tmongoc_init;
Fmongoc_cleanup: Tmongoc_cleanup;
// mongoc-log.h
Fmongoc_log_set_handler: Tmongoc_log_set_handler;
Fmongoc_log_default_handler: Tmongoc_log_default_handler;
Fmongoc_log_level_str: Tmongoc_log_level_str;
// mongoc-matcher.h
Fmongoc_matcher_new: Tmongoc_matcher_new;
Fmongoc_matcher_match: Tmongoc_matcher_match;
Fmongoc_matcher_destroy: Tmongoc_matcher_destroy;
// mongoc-read-prefs.h
Fmongoc_read_prefs_new: Tmongoc_read_prefs_new;
Fmongoc_read_prefs_destroy: Tmongoc_read_prefs_destroy;
Fmongoc_read_prefs_copy: Tmongoc_read_prefs_copy;
Fmongoc_read_prefs_get_mode: Tmongoc_read_prefs_get_mode;
Fmongoc_read_prefs_set_mode: Tmongoc_read_prefs_set_mode;
Fmongoc_read_prefs_get_tags: Tmongoc_read_prefs_get_tags;
Fmongoc_read_prefs_set_tags: Tmongoc_read_prefs_set_tags;
Fmongoc_read_prefs_add_tag: Tmongoc_read_prefs_add_tag;
Fmongoc_read_prefs_is_valid: Tmongoc_read_prefs_is_valid;
// mongoc-write-concern.h
Fmongoc_write_concern_new: Tmongoc_write_concern_new;
Fmongoc_write_concern_destroy: Tmongoc_write_concern_destroy;
Fmongoc_write_concern_copy: Tmongoc_write_concern_copy;
Fmongoc_write_concern_get_fsync: Tmongoc_write_concern_get_fsync;
Fmongoc_write_concern_set_fsync: Tmongoc_write_concern_set_fsync;
Fmongoc_write_concern_get_journal: Tmongoc_write_concern_get_journal;
Fmongoc_write_concern_set_journal: Tmongoc_write_concern_set_journal;
Fmongoc_write_concern_get_w: Tmongoc_write_concern_get_w;
Fmongoc_write_concern_set_w: Tmongoc_write_concern_set_w;
Fmongoc_write_concern_get_wtag: Tmongoc_write_concern_get_wtag;
Fmongoc_write_concern_set_wtag: Tmongoc_write_concern_set_wtag;
Fmongoc_write_concern_get_wtimeout: Tmongoc_write_concern_get_wtimeout;
Fmongoc_write_concern_set_wtimeout: Tmongoc_write_concern_set_wtimeout;
Fmongoc_write_concern_get_wmajority: Tmongoc_write_concern_get_wmajority;
Fmongoc_write_concern_set_wmajority: Tmongoc_write_concern_set_wmajority;
constructor Create(AOwningObj: TObject = nil);
/// <summary> Loads libmongoc-xxx dynamic library. Arguments are optional
/// and mutually exclusive:
/// * AVendorHome - specifies vendor home, which is parent MongoDB
/// installation folder;
/// * AVendorLib - path and name to the libmongoc-xxx dynamic library. </summary>
procedure Load(const AVendorHome, AVendorLib: String);
end;
/// <summary> Loads the libbson-xxx dynamic library and obtains BSON API entry
/// points. libbson-xxx must be loaded before libmongoc-xxx. </summary>
TMongoBSONLib = class(TFDLibrary)
private
[weak] FCLib: TMongoClientLib;
protected
procedure LoadEntries; override;
public
// bson-context.h
Fbson_context_new: Tbson_context_new;
Fbson_context_destroy: Tbson_context_destroy;
Fbson_context_get_default: Tbson_context_get_default;
// bson-oid.h
Fbson_oid_compare: Tbson_oid_compare;
Fbson_oid_copy: Tbson_oid_copy;
Fbson_oid_init: Tbson_oid_init;
Fbson_oid_init_from_string: Tbson_oid_init_from_string;
Fbson_oid_to_string: Tbson_oid_to_string;
Fbson_oid_get_time_t: Tbson_oid_get_time_t;
// bson.h
Fbson_mem_set_vtable: Tbson_mem_set_vtable;
Fbson_init: Tbson_init;
Fbson_init_static: Tbson_init_static;
Fbson_reinit: Tbson_reinit;
Fbson_new: Tbson_new;
Fbson_destroy: Tbson_destroy;
Fbson_get_data: Tbson_get_data;
Fbson_free: Tbson_free;
Fbson_init_from_json: Tbson_init_from_json;
Fbson_as_json: Tbson_as_json;
Fbson_copy_to: Tbson_copy_to;
Fbson_concat: Tbson_concat;
Fbson_append_array: Tbson_append_array;
Fbson_append_document: Tbson_append_document;
Fbson_append_bool: Tbson_append_bool;
Fbson_append_code: Tbson_append_code;
Fbson_append_code_with_scope: Tbson_append_code_with_scope;
Fbson_append_double: Tbson_append_double;
Fbson_append_int32: Tbson_append_int32;
Fbson_append_int64: Tbson_append_int64;
Fbson_append_null: Tbson_append_null;
Fbson_append_oid: Tbson_append_oid;
Fbson_append_regex: Tbson_append_regex;
Fbson_append_utf8: Tbson_append_utf8;
Fbson_append_time_t: Tbson_append_time_t;
Fbson_append_timeval: Tbson_append_timeval;
Fbson_append_date_time: Tbson_append_date_time;
Fbson_append_binary: Tbson_append_binary;
// bson-iter.h
Fbson_iter_init: Tbson_iter_init;
Fbson_iter_find: Tbson_iter_find;
Fbson_iter_find_descendant: Tbson_iter_find_descendant;
Fbson_iter_next: Tbson_iter_next;
Fbson_iter_recurse: Tbson_iter_recurse;
Fbson_iter_key: Tbson_iter_key;
Fbson_iter_type: Tbson_iter_type;
Fbson_iter_binary: Tbson_iter_binary;
Fbson_iter_bool: Tbson_iter_bool;
Fbson_iter_code: Tbson_iter_code;
Fbson_iter_double: Tbson_iter_double;
Fbson_iter_int32: Tbson_iter_int32;
Fbson_iter_int64: Tbson_iter_int64;
Fbson_iter_oid: Tbson_iter_oid;
Fbson_iter_regex: Tbson_iter_regex;
Fbson_iter_utf8: Tbson_iter_utf8;
Fbson_iter_time_t: Tbson_iter_time_t;
Fbson_iter_date_time: Tbson_iter_date_time;
constructor Create(ACLib: TMongoClientLib);
/// <summary> Loads libbson-xxx dynamic library. It will be loaded from the
/// same folder where libmongoc-xxx resides. </summary>
procedure Load;
/// <summary> Unloads libbson-xxx dynamic library. </summary>
procedure Unload; override;
/// <summary> Returns a reference to assocciated libmongoc-xxx dynamic library. </summary>
property CLib: TMongoClientLib read FCLib;
end;
/// <summary> A base class for all MongoDB API wrapping classes. This is an
/// abstract class, responsible for live cycle of an API handle. And it
/// provides references to client libraries, environment and error objects. </summary>
TMongoObject = class abstract(TObject)
private
FEnv: TMongoEnv;
FHandle: Pmongoc_handle_t;
FOwnHandle: Boolean;
[weak] FOwningObj: TObject;
function GetHandle: Pmongoc_handle_t;
procedure SetHandle(const AValue: Pmongoc_handle_t);
function GetError: TMongoError; inline;
function GetCLib: TMongoClientLib; inline;
function GetBLib: TMongoBSONLib; inline;
protected
/// <summary> Descendant classes override this method to release MongoDB API handle. </summary>
procedure InternalFreeHandle; virtual;
/// <summary> FreeHandle method clears existing handle, optionally releasing
/// API handle, when it is owned by this object. </summary>
procedure FreeHandle; virtual;
/// <summary> Descendant classes override this method to provide additional
/// API handle setup. It is called right after the API handle is allocated. </summary>
procedure HandleAllocated; virtual;
/// <summary> Creates new object and assigns references to environment and
/// owning objects. </summary>
constructor Create(AEnv: TMongoEnv; AOwningObj: TObject); overload;
/// <summary> Creates new object, assigns references to environment and
/// owning objects, and sets the MongoDB API handle which will be owned
/// by this object. </summary>
constructor Create(AEnv: TMongoEnv; AOwningObj: TObject; AHandle: Pmongoc_handle_t); overload;
public
destructor Destroy; override;
/// <summary> Returns reference to environment object. </summary>
property Env: TMongoEnv read FEnv;
/// <summary> Returns reference to MongoDB C driver library object. Shortcut to Env.CLib. </summary>
property CLib: TMongoClientLib read GetCLib;
/// <summary> Returns reference to BSON library object. Shortcut to Env.BLib. </summary>
property BLib: TMongoBSONLib read GetBLib;
/// <summary> Returns reference to error handling object. Shortcut to Env.Error. </summary>
property Error: TMongoError read GetError;
/// <summary> Returns reference to an object owning this object. </summary>
property OwningObj: TObject read FOwningObj;
/// <summary> Allows to get / set MongoDB API handle. Descendant classes
/// assign FHandle private variable directly. When Handle is set to
/// a not nil value, then the handle must be released by the setter. </summary>
property Handle: Pmongoc_handle_t read GetHandle write SetHandle;
end;
/// <summary> An error item, keeping specific MongoDB error information. At
/// moment it is only Domain property. </summary>
TFDMongoError = class(TFDDBError)
private
FDomain: Cardinal;
protected
procedure Assign(ASrc: TFDDBError); override;
procedure LoadFromStorage(const AStorage: IFDStanStorage); override;
procedure SaveToStorage(const AStorage: IFDStanStorage); override;
public
/// <summary> Returns MongoDB error domain code. </summary>
property Domain: Cardinal read FDomain;
end;
/// <summary> An exception object, specific to MongoDB. The EMongoNativeException
/// constructor knows how to get required information from the TMongoError. </summary>
EMongoNativeException = class(EFDDBEngineException)
private
function GetErrors(AIndex: Integer): TFDMongoError; inline;
protected
function GetErrorClass: TFDDBErrorClass; override;
function AppendError(ALevel, AErrorCode: Integer; ADomain: Cardinal;
const AMessage: String; ARowIndex: Integer): TFDMongoError; overload;
public
constructor Create(AError: TMongoError); overload;
/// <summary> Returns MongoDB error item by index. </summary>
property Errors[AIndex: Integer]: TFDMongoError read GetErrors; default;
end;
/// <summary> Incapsulates MongoDB bson_error_t structure, required to handle
/// server errors. The CheckError method verifies the structure state and
/// if required raises EMongoNativeException exception. </summary>
TMongoError = class(TMongoObject)
private
FBError: bson_error_t;
public
/// <summary> When AMethod value is specified, then raises EMongoNativeException
/// exception unconditionally with AMethod name in exception message. When
/// AMethod is not specified, then checks bson_error_t structure and if it has
/// an error, then corresponding EMongoNativeException is raised. </summary>
procedure CheckError(AInitiator: TObject = nil; const AMethod: String = '');
/// <summary> Returns MongoDB API error structure. </summary>
property BError: bson_error_t read FBError;
end;
/// <summary> The service object grouping together references to the client
/// libraries, error handling object, character set encoders, tracer, etc.
/// Application should create at least one TMongoEnv object. A single
/// TMongoEnv object and all other objects sharing the same TMongoEnv object
/// must be used by a single thread in each moment of time. </summary>
TMongoEnv = class(TObject)
private
FCLib: TMongoClientLib;
FBLib: TMongoBSONLib;
FError: TMongoError;
FBuffer: TFDBuffer;
FANSI: TFDEncoder;
FUTF8: TFDEncoder;
[weak] FOwningObj: TObject;
FDateTimeZoneHandling: TJsonDateTimeZoneHandling;
{$IFDEF FireDAC_MONITOR}
FMonitor: IFDMoniClient;
FTracing: Boolean;
function GetTracing: Boolean;
{$ENDIF}
public
/// <summary> Creates MongoDB environment object. The ACLib and ABLib parameters
/// are mandatory. </summary>
constructor Create(ACLib: TMongoClientLib; ABLib: TMongoBSONLib; AOwningObj: TObject);
destructor Destroy; override;
/// <summary> Creates new instance of MongoDB document. </summary>
function NewDoc: TMongoDocument;
{$IFDEF FireDAC_MONITOR}
procedure Trace(const AMsg: String; const AArgs: array of const); overload;
procedure Trace(AKind: TFDMoniEventKind; AStep: TFDMoniEventStep;
const AMsg: String; const AArgs: array of const); overload;
property Tracing: Boolean read GetTracing write FTracing;
property Monitor: IFDMoniClient read FMonitor write FMonitor;
{$ENDIF}
/// <summary> Returns reference to MongoDB C driver library object. </summary>
property CLib: TMongoClientLib read FCLib;
/// <summary> Returns reference to BSON library object. </summary>
property BLib: TMongoBSONLib read FBLib;
/// <summary> Returns reference to error handling object. </summary>
property Error: TMongoError read FError;
/// <summary> Returns reference to ANSI to UCS2 encoder. </summary>
property ANSI: TFDEncoder read FANSI;
/// <summary> Returns reference to UTF8 to UCS2 encoder. </summary>
property UTF8: TFDEncoder read FUTF8;
/// <summary> Returns reference to dynamic buffer. </summary>
property Buffer: TFDBuffer read FBuffer;
/// <summary> Returns reference to owning object. </summary>
property OwningObj: TObject read FOwningObj;
/// <summary> Specifies time zone mode. </summary>
property DateTimeZoneHandling: TJsonDateTimeZoneHandling read FDateTimeZoneHandling
write FDateTimeZoneHandling default TJsonDateTimeZoneHandling.Local;
end;
/// <summary> Incapsulates MongoDB bson_oid_t structure, representing OID,
/// which is equivalent to TJsonOid. </summary>
TMongoOID = class(TMongoObject)
private
function GetAsDateTime: TDateTime;
function GetAsString: String;
procedure SetAsString(const AValue: String);
function GetAsOid: TJsonOid; inline;
procedure SetAsOid(const AValue: TJsonOid); inline;
protected
procedure InternalFreeHandle; override;
public
/// <summary> Creates new MongoDB API OID wrapping object. </summary>
constructor Create(AEnv: TMongoEnv; AOwningObj: TObject);
/// <summary> Initialize by new semi-random value. </summary>
procedure Init;
/// <summary> Erases the OID by setting it to sequence of zero bytes. </summary>
procedure Clear;
/// <summary> Assigns another OID object to this object. </summary>
procedure Assign(ASource: TMongoOID);
/// <summary> Returns date part of OID value. </summary>
property AsDateTime: TDateTime read GetAsDateTime;
/// <summary> Gets / sets OID value using hexadecimal representation. </summary>
property AsString: String read GetAsString write SetAsString;
/// <summary> Gets / set OID value using TJsonOID representation. </summary>
property AsOid: TJsonOid read GetAsOid write SetAsOid;
end;
/// <summary> Incapsulates MongoDB bson_t structure. This is the key entity in
/// MongoDB API, responsible for data exchange, building queries, processing
/// errors, etc. The MongoDB API is all around bson_t. TMongoDocument provides
/// several sub-API's:
/// * Builder property returns reference to TJSONObjectBuilder BSON builder;
/// * Iterator function returns reference to TJSONIterator BSON iterator;
/// * several Add, Append, etc methods provide simplified access to the builder. </summary>
TMongoDocument = class(TMongoObject)
private type
THandleType = (ReadInternal, ReadExternal, WriteExternal, RTL);
TBuilder = class sealed(TJSONObjectBuilder)
private
[weak] FDoc: TMongoDocument;
protected
procedure DoResetWriter(AWriter: TJsonWriter); override;
function DoGetReader(AWriter: TJsonWriter): TJsonReader; override;
procedure DoReleaseReader(AWriter: TJsonWriter; AReader: TJsonReader); override;
procedure DoWriteCustomVariant(AWriter: TJsonWriter; const AValue: Variant); override;
public
constructor Create(const AJSONWriter: TJSONWriter; ADoc: TMongoDocument);
end;
TIterator = class sealed(TJSONIterator)
private
FStream: TMemoryStream;
FReader: TBsonReader;
protected
procedure DoRewindReader(AReader: TJsonReader); override;
public
constructor Create(ADoc: TMongoDocument);
destructor Destroy; override;
end;
private
[weak] FParentObj: TObject;
FStream: TMemoryStream;
FWriter: TBsonWriter;
FBuilder: TJSONObjectBuilder;
FHandleType: THandleType;
procedure ErrorReadOnly;
procedure Cleanup(AClearBuilder: Boolean);
procedure AttachToImpl(const AValue: Pbson_t);
procedure CheckClosed;
function GetAsReadHandle: Pbson_t;
procedure SetAsReadHandle(const AValue: Pbson_t);
function GetAsWriteHandle: Pbson_t;
function GetAsJSON: String;
procedure SetAsJSON(const AValue: String);
function GetInObject: Boolean; inline;
function GetPairs: TJSONCollectionBuilder.TPairs; inline;
function GetInArray: Boolean; inline;
function GetElements: TJSONCollectionBuilder.TElements; inline;
function GetBuilder: TJSONObjectBuilder;
protected
/// <summary> Release handle and other resource of this document. </summary>
procedure InternalFreeHandle; override;
/// <summary> Creates new empty MongoDB BSON document. Used internaly. </summary>
constructor Create(AEnv: TMongoEnv; AOwningObj, AParentObj: TObject); overload;
/// <summary> Returns reference to the current document builder object pairs object. </summary>
property Pairs: TJSONCollectionBuilder.TPairs read GetPairs;
/// <summary> Returns reference to the current document builder array elements object. </summary>
property Elements: TJSONCollectionBuilder.TElements read GetElements;
public
/// <summary> Creates new empty MongoDB BSON document. AEnv specifies MongoDB
/// API environment object, which is mandatory argument. </summary>
constructor Create(AEnv: TMongoEnv); overload;
destructor Destroy; override;
// writing
/// <summary> Assigns content of ASource document to this document. </summary>
procedure Assign(ASource: TMongoDocument);
/// <summary> Clears content of this document and returns reference to
/// this object. </summary>
function Clear: TMongoDocument;
/// <summary> Closes open and unclosed nested objects and arrays. </summary>
procedure Close;
/// <summary> Adds an object key-value pair or array item of String type.
/// For arrays the AKey value is ignored. Returns reference to this object. </summary>
function Add(const AKey: String; const AValue: String): TMongoDocument; overload;
/// <summary> Adds an object key-value pair or array item of Int32 type.
/// For arrays the AKey value is ignored. Returns reference to this object. </summary>
function Add(const AKey: String; const AValue: Int32): TMongoDocument; overload;
/// <summary> Adds an object key-value pair or array item of Int64 type.
/// For arrays the AKey value is ignored. Returns reference to this object. </summary>
function Add(const AKey: String; const AValue: Int64): TMongoDocument; overload;
/// <summary> Adds an object key-value pair or array item of Extended type.
/// For arrays the AKey value is ignored. Returns reference to this object. </summary>
function Add(const AKey: String; const AValue: Extended): TMongoDocument; overload;
/// <summary> Adds an object key-value pair or array item of Boolean type.
/// For arrays the AKey value is ignored. Returns reference to this object. </summary>
function Add(const AKey: String; const AValue: Boolean): TMongoDocument; overload;
/// <summary> Adds an object key-value pair or array item of TDateTime type.
/// For arrays the AKey value is ignored. Returns reference to this object. </summary>
function Add(const AKey: String; const AValue: TDateTime): TMongoDocument; overload;
/// <summary> Adds an object key-value pair or array item of TBytes type.
/// Optionally ABinaryType may be specified, which corresponds to BSON
/// binary subtypes. For arrays the AKey value is ignored. Returns reference
/// to this object. </summary>
function Add(const AKey: String; const AValue: TBytes;
ABinaryType: TJsonBinaryType = TJsonBinaryType.Generic): TMongoDocument; overload;
/// <summary> Adds an object key-value pair or array item of TMongoOID type.
/// For arrays the AKey value is ignored. Returns reference to this object. </summary>
function Add(const AKey: String; const AValue: TMongoOID): TMongoDocument; overload;
/// <summary> Adds an object key-value pair or array item of TJsonOid type.
/// For arrays the AKey value is ignored. Returns reference to this object. </summary>
function Add(const AKey: String; const AValue: TJsonOid): TMongoDocument; overload;
/// <summary> Adds an object key-value pair or array item of TJsonRegEx type.
/// For arrays the AKey value is ignored. Returns reference to this object. </summary>
function Add(const AKey: string; const AValue: TJsonRegEx): TMongoDocument; overload;
/// <summary> Adds an object key-value pair or array item of TJsonDBRef type.
/// For arrays the AKey value is ignored. Returns reference to this object. </summary>
function Add(const AKey: string; const AValue: TJsonDBRef): TMongoDocument; overload;
/// <summary> Adds an object key-value pair or array item of TJsonCodeWScope type.
/// For arrays the AKey value is ignored. Returns reference to this object. </summary>
function Add(const AKey: string; const AValue: TJsonCodeWScope): TMongoDocument; overload;
/// <summary> Adds an object key-value pair or array item of TVarRec type.
/// This method is usefull when processing open array values.
/// For arrays the AKey value is ignored. Returns reference to this object. </summary>
function Add(const AKey: String; const AValue: TVarRec): TMongoDocument; overload;
/// <summary> Adds a nested array using AValues open array as the array items.
/// The open array represents a "parsed" JSON. To add:
/// * a key value pair, first must be specified key name, followed by value;
/// * an array item, just a value must be specified;
/// * a nested object, its key-value pairs must be surrounded by '{' and '};
/// * a nested array, its key-value pairs must be surrounded by '[' and ']'.
/// For example:
/// * Add('coords', [123.45, 80.90])
/// -> "coords": [123.45, 80.90]
/// * Add('grades', ['{', 'grade', 'A', 'score', 11, '}', '{', 'grade', 'B', 'score', 17, '}'])
/// -> "grades": [{"grade": "A", "score": 11}, {"grade": "B", "score": 17}]
/// For arrays the AKey value is ignored. Returns reference to this object. </summary>
function Add(const AKey: String; const AValues: array of const): TMongoDocument; overload;
/// <summary> Adds an object key-value pair or array item of a type represented
/// by the Variant data type. For arrays the AKey value is ignored. Returns
/// reference to this object. </summary>
function Add(const AKey: String; const AValue: Variant): TMongoDocument; overload;
/// <summary> Adds an object key-value pair or array item of Null type.
/// For arrays the AKey value is ignored. Returns reference to this object. </summary>
function AddNull(const AKey: String): TMongoDocument;
/// <summary> Adds an object key-value pair or array item of Undefined type.
/// For arrays the AKey value is ignored. Returns reference to this object. </summary>
function AddUndefined(const AKey: String): TMongoDocument;
/// <summary> Adds an object key-value pair or array item of MinKey type.
/// For arrays the AKey value is ignored. Returns reference to this object. </summary>
function AddMinKey(const AKey: String): TMongoDocument;
/// <summary> Adds an object key-value pair or array item of MaxKey type.
/// For arrays the AKey value is ignored. Returns reference to this object. </summary>
function AddMaxKey(const AKey: String): TMongoDocument;
/// <summary> Open a new nested array. For parent arrays the AKey value is
/// ignored. Returns reference to this object. </summary>
function BeginArray(const AKey: String): TMongoDocument;
/// <summary> Closes a nested array. Returns reference to this object. </summary>
function EndArray: TMongoDocument;
/// <summary> Open a new nested object. For parent arrays the AKey value is
/// ignored. Returns reference to this object. </summary>
function BeginObject(const AKey: String): TMongoDocument;
/// <summary> Closes a nested object. Returns reference to this object. </summary>
function EndObject: TMongoDocument;
/// <summary> Appends the content of ADoc document to the end of this document.
/// Returns reference to this object. </summary>
function Append(const ADoc: TMongoDocument): TMongoDocument; overload;
/// <summary> Appends the content of AJSON document to the end of this document.
/// Returns reference to this object. </summary>
function Append(const AJSON: String): TMongoDocument; overload;
/// <summary> Appends an open array representing a "parsed" JSON to the end
/// of this document. To add:
/// * a key value pair, first must be specified key name, followed by value;
/// * an array item, just a value must be specified;
/// * a nested object, its key-value pairs must be surrounded by '{' and '};
/// * a nested array, its key-value pairs must be surrounded by '[' and ']'.
/// For example:
/// * Append(['coords', '[', 123.45, 80.90, ']'])
/// -> appends: "coords": [123.45, 80.90]
/// * Append(['grades', '[', '{', 'grade', 'A', 'score', 11, '}', '{', 'grade', 'B', 'score', 17, '}', ']'])
/// -> appends: "grades": [{"grade": "A", "score": 11}, {"grade": "B", "score": 17}]
/// Returns reference to this object. </summary>
function Append(const AItems: array of const): TMongoDocument; overload;
// R/O
/// <summary> Returns True when the current document level belongs to
/// opened nested array. </summary>
property InArray: Boolean read GetInArray;
/// <summary> Returns True when the current document level belongs to
/// opened nested object. </summary>
property InObject: Boolean read GetInObject;
/// <summary> Returns reference to JSON builder. The builder object is
/// owned by this document object. </summary>
property Builder: TJSONObjectBuilder read GetBuilder;
/// <summary> Creates and returns reference to JSON iterator. The caller
/// should free the iterator object after usage. </summary>
function Iterator: TJSONIterator;
/// <summary> Iterates through all document elements and calls AFunc
/// for each element. As argument AFunc receives reference to iterator,
/// pointing to current document element. When AFunc returns True, then
/// the method continues iterating. When False, then stops immediately. </summary>
procedure Iterate(AFunc: TJSONIterator.TIterateFunc);
// R/W
/// <summary> Gets/sets the content of this document as an JSON string. </summary>
property AsJSON: String read GetAsJSON write SetAsJSON;
/// <summary> Gets BSON API document handle, which will be read only
/// by MongoDB/BSON API. Or set BSON API document handle, which will
/// be read only by this object interface. </summary>
property AsReadHandle: Pbson_t read GetAsReadHandle write SetAsReadHandle;
/// <summary> Gets BSON API document handle, which will be filled by
/// MongoDB/BSON API. After that this document may be read using this
/// object interface. </summary>
property AsWriteHandle: Pbson_t read GetAsWriteHandle;
end;
/// <summary> Incapsulates MongoDB mongoc_read_prefs_t structure, representing
/// MongoDB API read preferences. All other MongoDB API wrapping classes provide
/// access to objects representing default read preferences.
/// More: http://docs.mongodb.org/master/core/read-preference/ </summary>
TMongoReadPreference = class(TMongoObject)
public type
/// <summary> See http://docs.mongodb.org/master/core/read-preference/#read-preference-modes. </summary>
TReadMode = (Primary, Secondary, PrimaryPreferred, SecondaryPreferred, Nearest);
private
FTags: TMongoDocument;
function GetMode: TReadMode;
procedure SetMode(const AValue: TReadMode);
function GetTags: TMongoDocument;
procedure SetTags(const AValue: TMongoDocument);
protected
/// <summary> Release handle of this read preference object. </summary>
procedure InternalFreeHandle; override;
public
/// <summary> Creates new read preference object. </summary>
constructor Create(AEnv: TMongoEnv; AOwningObj: TObject;
AHandle: Pmongoc_read_prefs_t = nil);
destructor Destroy; override;
/// <summary> Assigns settings of existing read preference object to this object. </summary>
procedure Assign(ASource: TMongoReadPreference);
/// <summary> See http://docs.mongodb.org/master/core/read-preference/#tag-sets. </summary>
procedure AddTag(ATag: TMongoDocument);
/// <summary> Gets/sets current read mode of this read preference object. </summary>
property Mode: TReadMode read GetMode write SetMode default TReadMode.Primary;
/// <summary> Gets/sets current tags of this read preference object. </summary>
property Tags: TMongoDocument read GetTags write SetTags;
end;
/// <summary> Incapsulates MongoDB mongoc_write_concern_t structure, representing
/// MongoDB API write concerns. All other MongoDB API wrapping classes provide
/// access to objects representing default write concerns.
/// More: http://docs.mongodb.org/master/core/write-concern/ </summary>
TMongoWriteConcern = class(TMongoObject)
public type
/// <summary> See http://api.mongodb.org/c/current/mongoc_write_concern_t.html. </summary>
TWriteLevel = (Default, ErrorsIgnored, Unacknowledged, Majority);
private
function GetFsync: Boolean;
procedure SetFsync(const AValue: Boolean);
function GetJournal: Boolean;
procedure SetJournal(const AValue: Boolean);
function GetLevel: TWriteLevel;
procedure SetLevel(const AValue: TWriteLevel);
function GetMajority: Integer;
procedure SetMajority(const AValue: Integer);
function GetTag: String;
procedure SetTag(const AValue: String);
function GetTimeout: Integer;
procedure SetTimeout(const AValue: Integer);
protected
/// <summary> Release handle of this write concern object. </summary>
procedure InternalFreeHandle; override;
public
/// <summary> Creates new write concern object. </summary>
constructor Create(AEnv: TMongoEnv; AOwningObj: TObject;
AHandle: Pmongoc_write_concern_t = nil);
/// <summary> Assigns settings of existing write concern object to this object. </summary>
procedure Assign(ASource: TMongoWriteConcern);
/// <summary> Gets/sets current write concern level of this write concern object. </summary>
property Level: TWriteLevel read GetLevel write SetLevel default TWriteLevel.Default;
/// <summary> Gets/sets if a fsync must be performed before indicating write success. </summary>
property Fsync: Boolean read GetFsync write SetFsync;
/// <summary> Gets/sets if the write must have been journaled before indicating success. </summary>
property Journal: Boolean read GetJournal write SetJournal;
/// <summary> Gets/sets if the write must have been propagated to a majority
/// of nodes before indicating write success. Assignment to this property will
/// set Level to Majority. The value is a timeout in msecs to propogate the
/// changes before considering the write request failed. </summary>
property Majority: Integer read GetMajority write SetMajority;
/// <summary> Gets/sets the write tag that must be satistified for the write to indicate
/// success. Write tags are preset write concerns configured on your MongoDB server. </summary>
property Tag: String read GetTag write SetTag;
/// <summary> Gets/sets the timeout in milliseconds that the server should wait before
/// idicating that the write has failed. This is not the same as a socket timeout. </summary>
property Timeout: Integer read GetTimeout write SetTimeout;
end;
/// <summary> Represents "fluent" style MongoDB expression builder. This class
/// is a generic base class and should not be used directly by an application.
/// The API replicates TMongoDocument API and adds Exp and End methods. The
/// End method finishes an expression and forwards control to a parent builder. </summary>
TMongoExpression<T: class> = class abstract(TObject)
private
FDoc: TMongoDocument;
function GetAsJSON: String; inline;
function GetInArray: Boolean; inline;
function GetInObject: Boolean; inline;
procedure SetAsJSON(const AValue: String); inline;
protected
constructor Create(AEnv: TMongoEnv; AOwningObj: TObject; AParentObj: T); overload;
public
constructor Create(AEnv: TMongoEnv); overload;
destructor Destroy; override;
procedure Assign(ASource: TMongoExpression<T>); inline;
function Clear: TMongoExpression<T>; inline;
procedure Close; inline;
// General writing methods
function Add(const AKey: String; const AValue: String): TMongoExpression<T>; overload; inline;
function Add(const AKey: String; const AValue: Int32): TMongoExpression<T>; overload; inline;
function Add(const AKey: String; const AValue: Int64): TMongoExpression<T>; overload; inline;
function Add(const AKey: String; const AValue: Extended): TMongoExpression<T>; overload; inline;
function Add(const AKey: String; const AValue: Boolean): TMongoExpression<T>; overload; inline;
function Add(const AKey: String; const AValue: TDateTime): TMongoExpression<T>; overload; inline;
function Add(const AKey: String; const AValue: TBytes;
ABinaryType: TJsonBinaryType = TJsonBinaryType.Generic): TMongoExpression<T>; overload; inline;
function Add(const AKey: String; const AValue: TMongoOID): TMongoExpression<T>; overload; inline;
function Add(const AKey: String; const AValue: TJsonOid): TMongoExpression<T>; overload;
function Add(const AKey: string; const AValue: TJsonRegEx): TMongoExpression<T>; overload;
function Add(const AKey: string; const AValue: TJsonDBRef): TMongoExpression<T>; overload;
function Add(const AKey: string; const AValue: TJsonCodeWScope): TMongoExpression<T>; overload;
function Add(const AKey: String; const AValue: TVarRec): TMongoExpression<T>; overload; inline;
function Add(const AKey: String; const AValues: array of const): TMongoExpression<T>; overload;
function Add(const AKey: String; const AValue: Variant): TMongoExpression<T>; overload; inline;
function AddNull(const AKey: String): TMongoExpression<T>; overload; inline;
function AddUndefined(const AKey: String): TMongoExpression<T>; overload; inline;
function AddMinKey(const AKey: String): TMongoExpression<T>; overload; inline;
function AddMaxKey(const AKey: String): TMongoExpression<T>; overload; inline;
function BeginArray(const AKey: String): TMongoExpression<T>; inline;
function EndArray: TMongoExpression<T>; inline;
function BeginObject(const AKey: String): TMongoExpression<T>; inline;
function EndObject: TMongoExpression<T>; inline;
function Append(const ADoc: TMongoDocument): TMongoExpression<T>; overload; inline;
function Append(const AJSON: String): TMongoExpression<T>; overload; inline;
function Append(const AItems: array of const): TMongoExpression<T>; overload;
// Expression specific methods
/// <summary> Appends "AField": AExpression to current expression.
/// Returns reference to this object. </summary>
function Exp(const AField, AExpression: String): TMongoExpression<T>;
/// <summary> Finishes this command stage and returns reference to
/// parent command object. </summary>
function &End: T; inline;
// R/O
property InArray: Boolean read GetInArray;
property InObject: Boolean read GetInObject;
property Doc: TMongoDocument read FDoc;
function Builder: TJSONObjectBuilder; inline;
function Iterator: TJSONIterator; inline;
// R/W
property AsJSON: String read GetAsJSON write SetAsJSON;
end;
/// <summary> Represents result set cursor interface. The interface is
/// implemented by:
/// * "fluent" style command builders, where a command returns a result set.
/// So, casting a builder to the interface will execute the command and
/// provide a cursor.
/// * TMongoCursor.TDefault class, which is the default interface
/// implementation.
/// </summary>
IMongoCursor = interface(IInterface)
['{7D8AF712-3FA8-459B-BF9B-4EC7E55B7359}']
// private
function GetDoc: TMongoDocument;
function GetIsAlive: Boolean;
// public
/// <summary> Moves the cursor to the next document. Right after execution
/// of a command, cursor stays before a first document. So, first Next call
/// positions the cursor on first document. If document is found, then
/// new document is loaded into Doc document and method returns True,
/// otherwise - False. </summary>
function Next: Boolean; overload;
/// <summary> Similar to above Next method, but loads the document into
/// specified ADoc document. </summary>
function Next(ADoc: TMongoDocument): Boolean; overload;
/// <summary> Returns reference to last fetched document using Next method. </summary>
property Doc: TMongoDocument read GetDoc;
/// <summary> Returns True if the cursor is alive. </summary>
property IsAlive: Boolean read GetIsAlive;
end;
/// <summary> Represents "fluent" style MongoDB Pipeline builder.
/// For more details see:
/// * http://docs.mongodb.org/manual/core/aggregation-pipeline/
/// * http://docs.mongodb.org/manual/reference/operator/aggregation/
/// The builder key methods, like Project, Match, Group, return subbuilders
/// for corresponding pipeline stages. A TMongoPipeline object may be:
/// * created explicitly and submit to TMongoCollection.Aggregate method.
/// This allows to reuse the pipeline object.
/// * obtained from overloaded TMongoCollection.Aggregate method, then
/// casted to IMongoCursor to execute pipeline and get a result set cursor.
/// </summary>
TMongoPipeline = class(TInterfacedObject, IMongoCursor)
protected type
TGetCursor = reference to function(APipeline: TMongoPipeline): IMongoCursor;
/// <summary> Base class for pipeline stage and operation classes. </summary>
TOperation = class abstract(TObject)
protected
[weak] FPipeline: TMongoPipeline;
FWriter: TMongoDocument;
constructor Create(APipeline: TMongoPipeline);
class function GetOperator: String; virtual; abstract;
class function GetInline: Boolean; virtual;
public
destructor Destroy; override;
/// <summary> Finishes this stage and returns reference to parent
/// pipeline object. </summary>
function &End: TMongoPipeline; inline;
/// <summary> Returns reference to stage containing document. </summary>
property Writer: TMongoDocument read FWriter;
end;
TOperationClass = class of TOperation;
TInlineOperation = class abstract(TOperation)
protected
class function GetInline: Boolean; override;
procedure SetValue(const AValue: Variant);
end;
/// <summary> Implements pipeline Limit stage. </summary>
TLimit = class sealed(TInlineOperation)
protected
class function GetOperator: String; override;
end;
/// <summary> Implements pipeline Skip stage. </summary>
TSkip = class sealed(TInlineOperation)
protected
class function GetOperator: String; override;
end;
/// <summary> Implements pipeline Unwind stage. </summary>
TUnwind = class sealed(TInlineOperation)
protected
class function GetOperator: String; override;
end;
/// <summary> Implements pipeline Sample stage. </summary>
TSample = class sealed(TOperation)
protected
class function GetOperator: String; override;
/// <summary> Sets the Size attribute of Sample stage. </summary>
procedure SetValue(const AValue: Integer);
end;
/// <summary> Implements pipeline Lookup stage. </summary>
TLookup = class sealed(TOperation)
protected
class function GetOperator: String; override;
/// <summary> Setups attributes of Lookup stage. </summary>
procedure Setup(const AFrom, ALocalField, AForeignField, AAs: String);
end;
/// <summary> Implements pipeline Out stage. </summary>
TOut = class sealed(TInlineOperation)
protected
class function GetOperator: String; override;
end;
/// <summary> Implements pipeline IndexStats stage. </summary>
TIndexStats = class sealed(TOperation)
protected
class function GetOperator: String; override;
/// <summary> Setups IndexStats stage. </summary>
procedure Setup();
end;
public type
TExpression = class sealed(TMongoExpression<TMongoPipeline>)
end;
/// <summary> Implements pipeline Projection stage. </summary>
TProjection = class sealed(TOperation)
protected
class function GetOperator: String; override;
public
/// <summary> Clears content of projection stage. </summary>
function Clear: TProjection; inline;
/// <summary> Appends JSON construction to projection stage. </summary>
function Append(const AJSON: String): TProjection; inline;
/// <summary> Excludes _ID attribute from result of projection stage. </summary>
function NoID: TProjection; inline;
/// <summary> Includes AField attribute into result of projection stage. </summary>
function Field(const AField: String): TProjection; inline;
/// <summary> Starts inclusion of new AField attribute into result of
/// projection stage, which will be of nested document type. </summary>
function FieldBegin(const AField: String): TProjection; inline;
/// <summary> Finishes inclusion of attribute started by previous
/// FieldBegin call. </summary>
function FieldEnd: TProjection; inline;
/// <summary> Includes AField calculated attribute into result of
/// projection stage. </summary>
function Exp(const AField, AExpression: String): TProjection;
end;
/// <summary> Implements pipeline Sort stage. </summary>
TSort = class sealed(TOperation)
protected
class function GetOperator: String; override;
public
/// <summary> Clears content of sort stage. </summary>
function Clear: TSort; inline;
/// <summary> Appends JSON construction to sort stage. </summary>
function Append(const AJSON: String): TSort; inline;
/// <summary> Includes AName attribute into sort stage. </summary>
function Field(const AName: String; AAscending: Boolean = True): TSort;
/// <summary> Applies special sorting by "$meta: textScore" for
/// AName attribute. </summary>
function TextScore(const AName: String): TSort;
end;
/// <summary> Implements pipeline GeoNear stage. </summary>
TGeoNear = class sealed(TOperation)
public type
TQuery = class sealed(TMongoExpression<TGeoNear>)
public
/// <summary> Finishes Query part of geoNear stage and returns reference
/// to parent geoNear object. </summary>
function &End: TGeoNear;
end;
private
FQuery: TQuery;
protected
class function GetOperator: String; override;
public
destructor Destroy; override;
/// <summary> Clears content of geoNear stage. </summary>
function Clear: TGeoNear; inline;
/// <summary> Appends JSON construction to geoNear stage. </summary>
function Append(const AJSON: String): TGeoNear; inline;
/// <summary> Specifies the point for which to find the closest documents. </summary>
function &Near(ALatitude, ALongitude: Extended): TGeoNear;
/// <summary> When true, then MongoDB uses spherical geometry to
/// calculate distances in meters. </summary>
function Spherical(AValue: Boolean): TGeoNear;
/// <summary> Specifies the maximum number of documents to return. </summary>
function Limit(AValue: Integer): TGeoNear;
/// <summary> Specifies the minimum and maximum distances from the
/// center point that the documents can be. Specify -1 when one of
/// the limits should not be used. </summary>
function Distance(AMin, AMax: Integer): TGeoNear;
/// <summary> ADistField specifies the output field that contains the
/// calculated distance. ALocsField specifies the output field that
/// identifies the location used to calculate the distance. </summary>
function Output(const ADistField: String; const ALocsField: String = ''): TGeoNear;
/// <summary> Limits the results to the documents that match the query. </summary>
function Query(const AJSON: String = ''): TQuery;
end;
/// <summary> Implements pipeline options. </summary>
TOptions = class sealed(TObject)
private
FExplain: Boolean;
FBatchSize: Integer;
FUseCursor: Boolean;
FAllowDiskUse: Boolean;
FMaxTimeMS: Integer;
procedure Save(AWriter: TMongoDocument);
public
/// <summary> Assigns content of other AOptions object to this one. </summary>
procedure Assign(AOptions: TOptions);
/// <summary> Specifies to return the information on the processing of
/// the pipeline. For more details see:
/// * https://docs.mongodb.org/manual/reference/method/db.collection.aggregate/#example-aggregate-method-explain-option
/// </summary>
property Explain: Boolean read FExplain write FExplain default False;
/// <summary> Enables writing to temporary files. For more details see:
/// * https://docs.mongodb.org/manual/reference/method/db.collection.aggregate/#example-aggregate-method-external-sort
/// </summary>
property AllowDiskUse: Boolean read FAllowDiskUse write FAllowDiskUse default False;
/// <summary> Enables cursor usage. Used together with BatchSize. For more details see:
/// * https://docs.mongodb.org/manual/reference/method/db.collection.aggregate/#example-aggregate-method-initial-batch-size
/// </summary>
property UseCursor: Boolean read FUseCursor write FUseCursor default False;
/// <summary> Specifies the initial batch size for the cursor. Used together with UseCursor. For more details see:
/// * https://docs.mongodb.org/manual/reference/method/db.collection.aggregate/#example-aggregate-method-initial-batch-size
/// </summary>
property BatchSize: Integer read FBatchSize write FBatchSize default 0;
/// <summary> Specifies the maximum time to execute the pipeline. </summary>
property MaxTimeMS: Integer read FMaxTimeMS write FMaxTimeMS default 0;
end;
private
FEnv: TMongoEnv;
[weak] FOwningObj: TObject;
FGetCursor: TGetCursor;
FOperations: TStringList;
FOptions: TOptions;
FPWriter: TMongoDocument;
FOWriter: TMongoDocument;
function GetCursor: IMongoCursor;
function GetOperation(AType: TOperationClass; const ATypeName: String;
const AJSON: String): TObject;
function GetOptions: TOptions;
function GetFinalPipelineBSON: TMongoDocument;
function GetFinalOptionsBSON: TMongoDocument;
protected
/// <summary> Creates new TMongoPipeline instance. This constructor is used
/// internally by TMongoCollection.Aggregate(TMongoQueryFlags) overloaded method.
/// </summary>
constructor Create(AEnv: TMongoEnv; AOwningObj: TObject; AGetCursor: TGetCursor); overload;
/// <summary> Returns reference to IMongoCursor. </summary>
property Cursor: IMongoCursor read GetCursor implements IMongoCursor;
public
/// <summary> Creates new TMongoPipeline instance. This instance may be executed
/// using TMongoCollection.Aggregate(TMongoPipeline) overloaded method.
/// </summary>
constructor Create(AEnv: TMongoEnv); overload;
destructor Destroy; override;
/// <summary> Returns reference to $project stage builder, which passes only
/// specified fields to the next stage. Optionally may be specified JSON
/// string representing this stage. For more details see:
/// * https://docs.mongodb.org/manual/reference/operator/aggregation/project/
/// </summary>
function Project(const AJSON: String = ''): TProjection;
/// <summary> Returns reference to $match stage builder, which filters the
/// documents. Optionally may be specified JSON string representing this
/// stage. For more details see:
/// * https://docs.mongodb.org/manual/reference/operator/aggregation/match/
/// </summary>
function Match(const AJSON: String = ''): TExpression;
/// <summary> Returns reference to $redact stage builder, which restricts the
/// content of documents. Optionally may be specified JSON string representing
/// this stage. For more details see:
/// * https://docs.mongodb.org/manual/reference/operator/aggregation/redact/
/// </summary>
function Redact(const AJSON: String = ''): TExpression;
/// <summary> Limits the number of documents passed to the next stage.
/// For more details see:
/// * https://docs.mongodb.org/manual/reference/operator/aggregation/limit/
/// </summary>
function Limit(const AValue: Integer): TMongoPipeline;
/// <summary> Skips over the specified number of documents.
/// For more details see:
/// * https://docs.mongodb.org/manual/reference/operator/aggregation/skip/
/// </summary>
function Skip(const AValue: Integer): TMongoPipeline;
/// <summary> Deconstructs an array field from the input documents to output
/// a document for each element. APath specifies array field path.
/// For more details see:
/// * https://docs.mongodb.org/manual/reference/operator/aggregation/unwind/
/// </summary>
function Unwind(const APath: String): TMongoPipeline;
/// <summary> Returns reference to $group stage builder, which groups
/// documents by some specified expression. Optionally may be specified
/// JSON string representing this stage. For more details see:
/// * https://docs.mongodb.org/manual/reference/operator/aggregation/group/
/// </summary>
function Group(const AJSON: String = ''): TExpression;
/// <summary> Randomly selects the specified number of documents from its input.
/// For more details see:
/// * https://docs.mongodb.com/manual/reference/operator/aggregation/sample/
/// </summary>
function Sample(const AValue: Integer): TMongoPipeline;
/// <summary> Returns reference to $sort stage builder, which sorts documents
/// by some specified document atributes. Optionally may be specified
/// JSON string representing this stage. For more details see:
/// * https://docs.mongodb.org/manual/reference/operator/aggregation/sort/
/// </summary>
function Sort(const AJSON: String = ''): TSort;
/// <summary> Returns reference to $geoNear stage builder, which outputs
/// documents in order of nearest to farthest from a specified point.
/// Optionally may be specified JSON string representing this stage.
/// For more details see:
/// * https://docs.mongodb.com/manual/reference/operator/aggregation/geoNear/
/// </summary>
function GeoNear(const AJSON: String = ''): TGeoNear;
/// <summary> Performs a join to a collection to filter in documents from
/// the "joined" collection for processing. For more details see:
/// * https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/
/// </summary>
function Lookup(const AFrom, ALocalField, AForeignField, AAs: String): TMongoPipeline;
/// <summary> Writes documents to a specified collection. ACollectionName
/// specifies collection name. For more details see:
/// * https://docs.mongodb.org/manual/reference/operator/aggregation/out/
/// </summary>
function &Out(const ACollectionName: String): TMongoPipeline;
/// <summary> Returns statistics regarding the use of each index for
/// the collection. For more details see:
/// * https://docs.mongodb.com/manual/reference/operator/aggregation/indexStats/
/// </summary>
function IndexStats(): TMongoPipeline;
/// <summary> Returns reference to a generic stage builder identified by AName.
/// Optionally may be specified JSON string representing this stage. For
/// more details see:
/// * https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/
/// </summary>
function Stage(const AName : String; const AJSON: String = ''): TExpression;
/// <summary> Explicitly executes pipeline and returns cursor. Note, that
/// casting TMongoPipeline object to IMongoCursor will implicitly execute
/// pipeline. Note, this method may be used only when pipeline object
/// was created by TMongoCollection.Aggregate(TMongoQueryFlags) method. </summary>
function Open: IMongoCursor;
/// <summary> Returns reference to pipeline options. </summary>
property Options: TOptions read GetOptions;
/// <summary> Returns MongoDB document representing pipeline with
/// all provided stages. </summary>
property FinalPipelineBSON: TMongoDocument read GetFinalPipelineBSON;
/// <summary> Returns MongoDB document representing pipeline options. </summary>
property FinalOptionsBSON: TMongoDocument read GetFinalOptionsBSON;
end;
/// <summary> Represents "fluent" style MongoDB Query builder.
/// For more details see:
/// * http://docs.mongodb.org/manual/tutorial/query-documents/
/// * http://docs.mongodb.org/manual/reference/method/db.collection.find/
/// The builder key methods, like Project, Match, Sort, return subbuilders
/// for corresponding query parts. A TMongoQuery object may be:
/// * created explicitly and submit to TMongoCollection.Find or Count method.
/// This allows to reuse the query object.
/// * obtained from overloaded TMongoCollection.Find or Count method, then
/// casted to IMongoCursor to execute query and get a result set cursor.
/// </summary>
TMongoQuery = class(TInterfacedObject, IMongoCursor)
protected type
TGetCursor = reference to function(AQuery: TMongoQuery): IMongoCursor;
TGetCount = reference to function(AQuery: TMongoQuery): Int64;
/// <summary> Base class for query operation classes. </summary>
TOperation = class abstract(TObject)
private
[weak] FQuery: TMongoQuery;
FWriter: TMongoDocument;
constructor Create(AQuery: TMongoQuery);
public
destructor Destroy; override;
/// <summary> Finishes this operation and returns reference to parent
/// query object. </summary>
function &End: TMongoQuery; inline;
/// <summary> Returns reference to operation containing document. </summary>
property Writer: TMongoDocument read FWriter;
end;
public type
TExpression = class sealed(TMongoExpression<TMongoQuery>)
end;
/// <summary> Implements query projection. </summary>
TProjection = class sealed(TOperation)
public
/// <summary> Clears content of query projection. </summary>
function Clear: TProjection; inline;
/// <summary> Appends JSON construction to query projection. </summary>
function Append(const AJSON: String): TProjection; inline;
/// <summary> Excludes _ID attribute from result of query. </summary>
function NoID: TProjection; inline;
/// <summary> Includes or excludes AField attribute from result of query. </summary>
function Field(const AField: String; AInclude: Boolean = True): TProjection; inline;
/// <summary> Includes several AFields fields into result of query. </summary>
function Include(const AFields: array of String): TProjection;
/// <summary> Excludes several AFields fields from result of query. </summary>
function Exclude(const AFields: array of String): TProjection;
/// <summary> Includes special "$meta: textScore" atribute into result of query. </summary>
function TextScore(const AField: String): TProjection;
/// <summary> Includes AField array slice of ACount length into result of query. </summary>
function Slice(const AField: String; ACount: Integer): TProjection; overload;
/// <summary> Includes AField array slice of ACount length starting from ASkip
/// item into result of query. </summary>
function Slice(const AField: String; ASkip, ACount: Integer): TProjection; overload;
end;
/// <summary> Implements query sorting. </summary>
TSort = class sealed(TOperation)
public
/// <summary> Clears content of query sorting. </summary>
function Clear: TSort; inline;
/// <summary> Appends JSON construction to query sorting. </summary>
function Append(const AJSON: String): TSort; inline;
/// <summary> Includes AName attribute into query sorting. </summary>
function Field(const AName: String; AAscending: Boolean = True): TSort;
/// <summary> Includes several AFields attributes into query sorting
/// by ascending order. </summary>
function Ascending(const AFields: array of String): TSort;
/// <summary> Includes several AFields attributes into query sorting
/// by descending order. </summary>
function Descending(const AFields: array of String): TSort;
/// <summary> Applies special sorting by "$meta: textScore" for
/// AName attribute. </summary>
function TextScore(const AName: String): TSort;
end;
/// <summary> Implements query options. </summary>
TOptions = class sealed(TObject)
private
FComment: String;
FExplain: Boolean;
FHint: String;
FMaxScan: Integer;
FMaxTimeMS: Integer;
FReturnKey: Boolean;
FSnapshot: Boolean;
FBatchSize: Integer;
procedure Save(AWriter: TMongoDocument);
public
/// <summary> Assigns content of other AOptions object to this one. </summary>
procedure Assign(AOptions: TOptions);
/// <summary> Adds a comment to the query to identify queries in the
/// database profiler output. For more details see:
/// * https://docs.mongodb.org/manual/reference/operator/meta/comment/ </summary>
property Comment: String read FComment write FComment;
/// <summary> Forces MongoDB to report on query execution plans.
/// For more details see:
/// * https://docs.mongodb.org/manual/reference/operator/meta/explain/ </summary>
property Explain: Boolean read FExplain write FExplain default False;
/// <summary> Forces MongoDB to use a specific index.
/// For more details see:
/// * https://docs.mongodb.org/manual/reference/operator/meta/hint/ </summary>
property Hint: String read FHint write FHint;
/// <summary> Limits the number of documents scanned.
/// For more details see:
/// * https://docs.mongodb.org/manual/reference/operator/meta/maxScan/ </summary>
property MaxScan: Integer read FMaxScan write FMaxScan default 0;
/// <summary> Specifies a cumulative time limit in milliseconds for processing operations on a cursor.
/// For more details see:
/// * https://docs.mongodb.org/manual/reference/operator/meta/maxTimeMS/ </summary>
property MaxTimeMS: Integer read FMaxTimeMS write FMaxTimeMS default 0;
/// <summary> Forces the cursor to only return fields included in the index.
/// For more details see:
/// * https://docs.mongodb.org/manual/reference/operator/meta/returnKey/ </summary>
property ReturnKey: Boolean read FReturnKey write FReturnKey default False;
/// <summary> Forces the query to use the index on the _id field.
/// For more details see:
/// * https://docs.mongodb.org/manual/reference/operator/meta/snapshot/ </summary>
property Snapshot: Boolean read FSnapshot write FSnapshot default False;
/// <summary> Specifies the number of documents to return in each batch of
/// the response from the MongoDB instance. For more details see:
/// * https://docs.mongodb.org/manual/reference/method/cursor.batchSize/ </summary>
property BatchSize: Integer read FBatchSize write FBatchSize default 0;
end;
private
FEnv: TMongoEnv;
[weak] FOwningObj: TObject;
FGetCursor: TGetCursor;
FGetCount: TGetCount;
FProject: TProjection;
FMatch: TExpression;
FSort: TSort;
FOptions: TOptions;
FLimit: Integer;
FSkip: Integer;
FQWriter: TMongoDocument;
FPWriter: TMongoDocument;
function GetCursor: IMongoCursor;
function GetFinalQueryBSON: TMongoDocument;
function GetFinalCountBSON: TMongoDocument;
function GetFinalProjectBSON: TMongoDocument;
protected
/// <summary> Creates new TMongoQuery instance. This constructor is used
/// internally by TMongoCollection.Find(TMongoQueryFlags) overloaded method.
/// </summary>
constructor Create(AEnv: TMongoEnv; AOwningObj: TObject; AGetCursor: TGetCursor); overload;
/// <summary> Creates new TMongoQuery instance. This constructor is used
/// internally by TMongoCollection.Count(TMongoQueryFlags) overloaded method.
/// </summary>
constructor Create(AEnv: TMongoEnv; AOwningObj: TObject; AGetCount: TGetCount); overload;
procedure DoGetFinalQueryBSON(AWriter: TMongoDocument); virtual;
procedure DoGetFinalProjectBSON(AWriter: TMongoDocument); virtual;
/// <summary> Returns reference to IMongoCursor. </summary>
property Cursor: IMongoCursor read GetCursor implements IMongoCursor;
public
/// <summary> Creates new TMongoQuery instance. This instance may be executed
/// using TMongoCollection.Find(TMongoQuery), Count(TMongoQuery) overloaded methods.
/// </summary>
constructor Create(AEnv: TMongoEnv); overload;
destructor Destroy; override;
/// <summary> Returns reference to projection builder, which specifies
/// the fields to return using projection operators. Optionally may be
/// specified JSON string representing projection. For more details see:
/// * https://docs.mongodb.org/manual/reference/method/db.collection.find/
/// </summary>
function Project(const AJSON: String = ''): TProjection;
/// <summary> Returns reference to match builder, which specifies
/// selection criteria using query operators. Optionally may be
/// specified JSON string representing match criteria. For more details see:
/// * https://docs.mongodb.org/manual/reference/method/db.collection.find/
/// </summary>
function Match(const AJSON: String = ''): TExpression;
/// <summary> Returns reference to sort builder, which specifies
/// the order in which the query returns matching documents. Optionally
/// may be specified JSON string representing this stage. For more details see:
/// * https://docs.mongodb.org/manual/reference/method/cursor.sort/
/// </summary>
function Sort(const AJSON: String = ''): TSort;
/// <summary> Returns reference to query options. </summary>
function Options: TOptions;
/// <summary> Specifies the maximum number of documents the cursor will return.
/// For more details see:
/// * https://docs.mongodb.org/manual/reference/method/cursor.limit/
/// </summary>
function Limit(const AValue: Integer): TMongoQuery;
/// <summary> Specifies where MongoDB begins returning results.
/// For more details see:
/// * https://docs.mongodb.org/manual/reference/method/cursor.skip/
/// </summary>
function Skip(const AValue: Integer): TMongoQuery;
/// <summary> Explicitly executes query and returns cursor. Note, that
/// casting TMongoQuery object to IMongoCursor will implicitly execute
/// query. Note, this method may be used only when query object was
/// created by TMongoCollection.Find(TMongoQueryFlags) overloaded method. </summary>
function Open: IMongoCursor;
/// <summary> Executes cound query and returns the records count. Note,
/// this method may be used only when count query object was created
/// by TMongoCollection.Count(TMongoQueryFlags) overloaded method. </summary>
function Value: Int64;
/// <summary> Returns MongoDB document representing Find command query. </summary>
property FinalQueryBSON: TMongoDocument read GetFinalQueryBSON;
/// <summary> Returns MongoDB document representing Count command query. </summary>
property FinalCountBSON: TMongoDocument read GetFinalCountBSON;
/// <summary> Returns MongoDB document representing projection. </summary>
property FinalProjectBSON: TMongoDocument read GetFinalProjectBSON;
end;
/// <summary> Represents "fluent" style MongoDB Command builder. It mostly
/// repeats TMongoQuery API, but adds Command method allowing to specify
/// MongoDB command verb. A TMongoCommand object may be:
/// * created explicitly and submit to TMongoCollection.Command method.
/// This allows to reuse the command object.
/// * obtained from overloaded TMongoCollection.Command method, then
/// casted to IMongoCursor to execute command and get a result set cursor.
/// </summary>
TMongoCommand = class(TMongoQuery)
private
FCommand: TMongoDocument;
protected
/// <summary> Creates new TMongoCommand instance. This constructor is used
/// internally by TMongoCollection methods. </summary>
constructor Create(AEnv: TMongoEnv; AOwningObj: TObject); overload;
procedure DoGetFinalQueryBSON(AWriter: TMongoDocument); override;
public
/// <summary> Creates new TMongoCommand instance. This instance may be executed
/// using TMongoCollection.Command(TMongoCommand) overloaded method.
/// </summary>
constructor Create(AEnv: TMongoEnv); overload;
destructor Destroy; override;
/// <summary> Appends AArgs arguments to the command. </summary>
function Command(const AArgs: array of const): TMongoCommand; overload;
/// <summary> Appends AJSON arguments to the command. </summary>
function Command(const AJSON: String): TMongoCommand; overload;
end;
/// <summary> Represents "fluent" style MongoDB Update builder.
/// For more details see:
/// * http://docs.mongodb.org/manual/tutorial/modify-documents/
/// * https://docs.mongodb.org/manual/reference/operator/update/
/// The builder key methods, like Inc, Mul, Set, return subbuilders
/// for corresponding update command parts. A TMongoUpdate object may be:
/// * created explicitly and submit to TMongoCollection.Update method.
/// This allows to reuse the update object.
/// * obtained from overloaded TMongoCollection.Update method, then
/// call Exec method to execute update command.
/// If update command fails, then exception will be raised. Otherwise
/// the number of updated documents may be get from TMongoCollection
/// DocsModified and DocsUpserted properties.
/// </summary>
TMongoUpdate = class(TObject)
protected type
TRunUpdate = reference to procedure(AUpdate: TMongoUpdate);
public type
TExpression = class sealed (TMongoExpression<TMongoUpdate>)
end;
TModifier = class(TObject)
protected type
TOperation = class abstract(TObject)
private
[weak] FModifier: TModifier;
FWriter: TMongoDocument;
protected
constructor Create(AModifier: TModifier);
function Field(const AName: String; const AValue: Variant): TOperation;
class function GetOperator: String; virtual; abstract;
public
destructor Destroy; override;
function &End: TModifier; inline;
property Writer: TMongoDocument read FWriter;
end;
TOperationClass = class of TOperation;
public type
TInc = class sealed(TOperation)
protected
class function GetOperator: String; override;
public
function Field(const AName: String; const AValue: Variant): TInc; inline;
end;
TMul = class sealed(TOperation)
protected
class function GetOperator: String; override;
public
function Field(const AName: String; const AValue: Variant): TMul; inline;
end;
TRename = class sealed(TOperation)
protected
class function GetOperator: String; override;
public
function Field(const AOldName, ANewName: String): TRename; inline;
end;
TSetOnInsert = class sealed(TOperation)
protected
class function GetOperator: String; override;
public
function Field(const AName: String; const AValue: Variant): TSetOnInsert; inline;
end;
TSet = class sealed(TOperation)
protected
class function GetOperator: String; override;
public
function Field(const AName: String; const AValue: Variant): TSet; inline;
end;
TUnset = class sealed(TOperation)
protected
class function GetOperator: String; override;
public
function Field(const AName: String): TUnset; inline;
end;
TMin = class sealed(TOperation)
protected
class function GetOperator: String; override;
public
function Field(const AName: String; const AValue: Variant): TMin; inline;
end;
TMax = class sealed(TOperation)
protected
class function GetOperator: String; override;
public
function Field(const AName: String; const AValue: Variant): TMax; inline;
end;
TCurrentDate = class sealed(TOperation)
protected
class function GetOperator: String; override;
public
function AsDate(const AName: String): TCurrentDate;
function AsTimestamp(const AName: String): TCurrentDate;
end;
TArrayOperation = class abstract(TOperation)
protected
function Field(const AName: String; const AValues: Variant;
AEach, AClose: Boolean): TArrayOperation; overload;
function Field(const AName: String; const AValues: array of const;
AEach, AClose: Boolean): TArrayOperation; overload;
end;
TAddToSet = class sealed(TArrayOperation)
protected
class function GetOperator: String; override;
public
function Field(const AName: String; const AValues: Variant;
AEach: Boolean = True): TAddToSet; overload;
function Field(const AName: String; const AValues: array of const;
AEach: Boolean = True): TAddToSet; overload;
end;
TPop = class sealed(TArrayOperation)
protected
class function GetOperator: String; override;
public
function First(const AName: String): TPop;
function Last(const AName: String): TPop;
end;
TPull = class sealed(TArrayOperation)
protected
class function GetOperator: String; override;
public
function Field(const AName: String; const AValue: Variant): TPull;
function Where(const AName: String; const AValue: String): TPull;
end;
TPullAll = class sealed(TArrayOperation)
protected
class function GetOperator: String; override;
public
function Field(const AName: String; const AValues: Variant): TPullAll; overload;
function Field(const AName: String; const AValues: array of const): TPullAll; overload;
end;
TPush = class sealed(TArrayOperation)
protected
class function GetOperator: String; override;
public
function Field(const AName: String; const AValues: Variant;
AEach: Boolean = True; ASlice: Integer = MaxInt;
const ASort: String = ''): TPush; overload;
function Field(const AName: String; const AValues: array of const;
AEach: Boolean = True; ASlice: Integer = MaxInt;
const ASort: String = ''): TPush; overload;
end;
TPushAll = class sealed(TArrayOperation)
protected
class function GetOperator: String; override;
public
function Field(const AName: String; const AValues: Variant): TPushAll; overload;
function Field(const AName: String; const AValues: array of const): TPushAll; overload;
end;
private
[weak] FUpdate: TMongoUpdate;
FOperations: TStringList;
FWriter: TMongoDocument;
FCustomJSON: String;
constructor Create(AUpdate: TMongoUpdate);
function GetOperation(AType: TOperationClass; const AJSON: String): TOperation;
function GetFinalBSON: TMongoDocument;
public
destructor Destroy; override;
function Clear: TModifier;
function Inc(const AJSON: String = ''): TInc; inline;
function Mul(const AJSON: String = ''): TMul; inline;
function Rename(const AJSON: String = ''): TRename; inline;
function SetOnInsert(const AJSON: String = ''): TSetOnInsert; inline;
function &Set(const AJSON: String = ''): TSet; inline;
function Unset(const AJSON: String = ''): TUnset; inline;
function Min(const AJSON: String = ''): TMin; inline;
function Max(const AJSON: String = ''): TMax; inline;
function CurrentDate(const AJSON: String = ''): TCurrentDate; inline;
function AddToSet(const AJSON: String = ''): TAddToSet; inline;
function Pop(const AJSON: String = ''): TPop; inline;
function Pull(const AJSON: String = ''): TPull; inline;
function PullAll(const AJSON: String = ''): TPullAll; inline;
function Push(const AJSON: String = ''): TPush; inline;
function PushAll(const AJSON: String = ''): TPushAll; inline;
function &End: TMongoUpdate; inline;
end;
private
FEnv: TMongoEnv;
[weak] FOwningObj: TObject;
FRunUpdate: TRunUpdate;
FModifier: TModifier;
FMatcher: TExpression;
function GetFinalModifyBSON: TMongoDocument;
function GetFinalMatchBSON: TMongoDocument;
protected
constructor Create(AEnv: TMongoEnv; AOwningObj: TObject; ARunUpdate: TRunUpdate); overload;
procedure DoGetFinalModifyBSON(AWriter: TMongoDocument); virtual;
procedure DoGetFinalMatchBSON(AWriter: TMongoDocument); virtual;
public
constructor Create(AEnv: TMongoEnv); overload;
destructor Destroy; override;
function Match(const AJSON: String = ''): TExpression;
function Modify(const AJSON: String = ''): TModifier;
procedure Exec;
// property RO
property FinalModifyBSON: TMongoDocument read GetFinalModifyBSON;
property FinalMatchBSON: TMongoDocument read GetFinalMatchBSON;
end;
/// <summary> Represents "fluent" style MongoDB Selector builder.
/// For more details see:
/// * http://docs.mongodb.org/manual/reference/method/db.collection.remove/
/// * http://docs.mongodb.org/manual/reference/operator/query/
/// The builder Match method return subbuilder for selector. An object
/// of this class may be:
/// * created explicitly and submit to TMongoCollection.Remove method.
/// This allows to reuse the selector object.
/// * obtained from overloaded TMongoCollection.Remove method, then
/// call Exec method to execute remove command.
/// </summary>
TMongoSelector = class(TObject)
protected type
TRunOper = reference to procedure(ASelector: TMongoSelector);
public type
TExpression = class sealed(TMongoExpression<TMongoSelector>)
end;
private
FEnv: TMongoEnv;
[weak] FOwningObj: TObject;
FMatcher: TExpression;
FRunOper: TRunOper;
function GetFinalMatchBSON: TMongoDocument;
protected
constructor Create(AEnv: TMongoEnv; AOwningObj: TObject; ARunOper: TRunOper); overload;
procedure DoGetFinalMatchBSON(AWriter: TMongoDocument); virtual;
public
constructor Create(AEnv: TMongoEnv); overload;
destructor Destroy; override;
function Match(const AJSON: String = ''): TExpression;
procedure Exec;
// property RO
property FinalMatchBSON: TMongoDocument read GetFinalMatchBSON;
end;
/// <summary> Represents "fluent" style MongoDB Insert builder.
/// For more details see:
/// * http://docs.mongodb.org/manual/tutorial/insert-documents/
/// * http://docs.mongodb.org/manual/reference/method/db.collection.insert/
/// The builder Values method returns document subbuilder. A TMongoInsert
/// object may be:
/// * created explicitly and submit to TMongoCollection.Insert method.
/// This allows to reuse the builder.
/// * obtained from overloaded TMongoCollection.Insert method, then
/// call Exec method to execute insert command.
/// If insert command fails, then exception will be raised. Otherwise
/// the number of inserted documents may be get from TMongoCollection
/// DocsInserted property.
/// Although MongoDB Insert command allows to insert an array of documents,
/// the TMongoCollection.Insert and this builder are limited to a single
/// document. To insert multiple documents use TMongoCollection.BeginBulk,
/// EndBulk API. </summary>
TMongoInsert = class(TObject)
protected type
TRunOper = reference to procedure(ASelector: TMongoInsert);
public type
TExpression = class sealed(TMongoExpression<TMongoInsert>)
end;
private
FEnv: TMongoEnv;
[weak] FOwningObj: TObject;
FValues: TExpression;
FRunOper: TRunOper;
function GetFinalValuesBSON: TMongoDocument;
protected
constructor Create(AEnv: TMongoEnv; AOwningObj: TObject; ARunOper: TRunOper); overload;
procedure DoGetFinalValuesBSON(AWriter: TMongoDocument); virtual;
public
constructor Create(AEnv: TMongoEnv); overload;
destructor Destroy; override;
function Values(const AJSON: String = ''): TExpression;
procedure Exec;
// property RO
property FinalValuesBSON: TMongoDocument read GetFinalValuesBSON;
end;
/// <summary> Represents "fluent" style MongoDB Index definition builder.
/// For more details see:
/// * http://docs.mongodb.org/manual/tutorial/create-an-index/
/// * http://docs.mongodb.org/manual/reference/method/db.collection.createIndex/
/// The Keys method returns index keys subbuilder. The Options property
/// allows specify index name and other attributes. A TMongoIndex object
/// may be created explicitly and submit to TMongoCollection.CreateIndex
/// method. </summary>
TMongoIndex = class(TObject)
public type
TKeys = class sealed(TObject)
private
FWriter: TMongoDocument;
constructor Create(AIndex: TMongoIndex);
public
destructor Destroy; override;
function Field(const AName: String; AAscending: Boolean = True): TKeys; overload;
function Field(const AName: String; const AKind: String): TKeys; overload;
function Ascending(const AFields: array of String): TKeys;
function Descending(const AFields: array of String): TKeys;
end;
TOptions = class sealed(TObject)
private
[weak] FIndex: TMongoIndex;
FOpts: mongoc_index_opt_t;
FName: String;
FBName: TFDByteString;
procedure SetName(const AValue: String);
constructor Create(AIndex: TMongoIndex);
public
property Name: String read FName write SetName;
property Background: Boolean read FOpts.background write FOpts.background default False;
property Unique: Boolean read FOpts.unique write FOpts.unique default False;
property DropDups: Boolean read FOpts.drop_dups write FOpts.drop_dups default False;
property Sparse: Boolean read FOpts.sparse write FOpts.sparse default False;
property ExpireAfter: Integer read FOpts.expire_after_seconds write FOpts.expire_after_seconds default 0;
end;
private
FEnv: TMongoEnv;
[weak] FOwningObj: TObject;
FKeys: TKeys;
FOptions: TOptions;
public
constructor Create(AEnv: TMongoEnv); overload;
destructor Destroy; override;
function Keys(const AJSON: String = ''): TKeys;
property Options: TOptions read FOptions;
end;
/// <summary> Incapsulates MongoDB mongoc_cursor_t structure. This class is
/// responsible for fetching result set documents from a cursor returned
/// by a command. Application should not create objects of this class
/// directly. </summary>
TMongoCursor = class(TMongoObject)
protected type
TDefault = class(TInterfacedObject, IMongoCursor)
private
FCursor: TMongoCursor;
FReleaseObj: TObject;
protected
// IMongoCursor
function GetDoc: TMongoDocument;
function GetIsAlive: Boolean;
function Next: Boolean; overload;
function Next(ADoc: TMongoDocument): Boolean; overload;
// other
constructor Create(AEnv: TMongoEnv; AOwningObj: TObject;
AReleaseObj: TObject; AHandle: Pmongoc_handle_t);
public
destructor Destroy; override;
end;
private
FDoc: TMongoDocument;
FEof: Boolean;
function GetDoc: TMongoDocument;
function GetIsAlive: Boolean;
protected
procedure InternalFreeHandle; override;
public
destructor Destroy; override;
function Next: Boolean; overload;
function Next(ADoc: TMongoDocument): Boolean; overload;
property Doc: TMongoDocument read GetDoc;
property IsAlive: Boolean read GetIsAlive;
end;
/// <summary> Incapsulates MongoDB mongoc_client_t structure. This class is
/// responsible for managing connection to a MongoDB server. Also it provides
/// access to database and collection objects. </summary>
TMongoConnection = class(TMongoObject)
private
FReadPreference: TMongoReadPreference;
FWriteConcern: TMongoWriteConcern;
FPEMFile, FPEMPwd, FCAFile, FCADir, FCRLFile: TFDByteString;
Fmongoc_ssl_opt: mongoc_ssl_opt_t;
FDatabase: TMongoDatabase;
FCollection: TMongoCollection;
function Getmax_bson_size: Integer;
function Getmax_message_size: Integer;
function InternalGetDatabase(const ADBName: String; ANew: Boolean): TMongoDatabase;
function InternalGetCollection(const ADBName, AColName: String; ANew: Boolean): TMongoCollection;
function GetCollectionsProp(const ADBName, AColName: String): TMongoCollection;
function GetDatabasesProp(const ADBName: String): TMongoDatabase;
function GetServerVersion: TFDVersion;
function GetURI: String;
protected
procedure InternalFreeHandle; override;
procedure FreeHandle; override;
procedure HandleAllocated; override;
public
constructor Create(AEnv: TMongoEnv; AOwningObj: TObject);
constructor CreateUsingHandle(AEnv: TMongoEnv; AHandle: Pmongoc_handle_t; AOwningObj: TObject);
destructor Destroy; override;
// handle connection
procedure Open(const AUri: String);
procedure SSLInit(const APEMFile, APEMPwd, ACAFile, ACADir, ACRLFile: String;
AWeakValid: Boolean);
procedure Close; inline;
procedure Ping;
function GetServerStatus: TMongoDocument;
// databases and collections
function ListDatabases: IMongoCursor;
function GetDatabase(const ADBName: String): TMongoDatabase;
function GetCollection(const ADBName, AColName: String): TMongoCollection;
// execute commands
function Command(const ADBName: String; ACommand: TMongoCommand; AFlags: TMongoQueryFlags = []): IMongoCursor; overload;
function Command(const ADBName: String; const AJSON: String; AFlags: TMongoQueryFlags = []): IMongoCursor; overload;
function CommandSimple(const ADBName: String; ACommand: TMongoDocument): TMongoDocument; overload;
function CommandSimple(const ADBName: String; const AJSON: String): TMongoDocument; overload;
// DBRef lookup
function Dereference(const ADBRef: TJsonDBRef): TMongoDocument;
// props
property URI: String read GetURI;
property max_message_size: Integer read Getmax_message_size;
property max_bson_size: Integer read Getmax_bson_size;
property ServerVersion: TFDVersion read GetServerVersion;
property ReadPreference: TMongoReadPreference read FReadPreference;
property WriteConcern: TMongoWriteConcern read FWriteConcern;
property Databases[const ADBName: String]: TMongoDatabase read GetDatabasesProp; default;
property Collections[const ADBName, AColName: String]: TMongoCollection read GetCollectionsProp;
end;
/// <summary> Incapsulates MongoDB mongoc_database_t structure. This class
/// represents a single MongoDB database. It allows to manage database,
/// collections and users inside of this database. Also it provides access
/// to collection objects. Application cannot create instance of this class
/// directly. Instead it should use TMongoConnection:
/// * TMongoConnection.GetDatabase to get new instance of TMongoDatabase
/// * TMongoConnection.Databases to get a shared instance of TMongoDatabase
/// </summary>
TMongoDatabase = class(TMongoObject)
private
FCollection: TMongoCollection;
FReadPreference: TMongoReadPreference;
FWriteConcern: TMongoWriteConcern;
function GetName: String;
function InternalGetCollection(const AColName: String; ANew: Boolean): TMongoCollection;
function GetCollectionsProp(const AColName: String): TMongoCollection;
protected
procedure InternalFreeHandle; override;
procedure FreeHandle; override;
procedure HandleAllocated; override;
constructor Create(AEnv: TMongoEnv; AOwningObj: TObject; AHandle: Pmongoc_database_t);
public
destructor Destroy; override;
// manage DB users
procedure Drop;
procedure AddUser(const AUserName, APassword: String; ARoles, ACustomData: TMongoDocument);
procedure DropUser(const AUserName: String);
procedure DropAllUsers;
// manage DB collections
function ListCollections(ASelector: TMongoSelector = nil): IMongoCursor;
function HasCollection(const AName: String): Boolean;
procedure CreateCollection(const AName: String; AOptions: TMongoDocument);
procedure DropCollection(const AName: String; AIgnoreObjNotExists: Boolean = False);
function GetCollection(const AColName: String): TMongoCollection;
// execute commands
function Command(ACommand: TMongoCommand; AFlags: TMongoQueryFlags = []): IMongoCursor; overload;
function Command(const AJSON: String; AFlags: TMongoQueryFlags = []): IMongoCursor; overload;
function CommandSimple(ACommand: TMongoDocument): TMongoDocument; overload;
function CommandSimple(const AJSON: String): TMongoDocument; overload;
// DBRef lookup
function Dereference(const ADBRef: TJsonDBRef): TMongoDocument;
// props
property Name: String read GetName;
property ReadPreference: TMongoReadPreference read FReadPreference;
property WriteConcern: TMongoWriteConcern read FWriteConcern;
property Collections[const AColName: String]: TMongoCollection read GetCollectionsProp; default;
end;
/// <summary> Incapsulates MongoDB mongoc_collection_t structure. This class
/// represents a single MongoDB collection and provides methods to manage
/// collection, modify and query it data. Application cannot create instance
/// of this class directly. Instead it should use TMongoConnection or TMongoDatabase:
/// * TMongoConnection.GetCollection to get new instance of TMongoCollection
/// * TMongoConnection.Collections to get a shared instance of TMongoCollection
/// * TMongoDatabase.GetCollection to get new instance of TMongoCollection
/// * TMongoDatabase.Collections to get a shared instance of TMongoCollection
/// </summary>
TMongoCollection = class(TMongoObject)
public type
TInsertFlag = (ContinueOnError, NoValidate);
TInsertFlags = set of TInsertFlag;
TRemoveFlag = (SingleRemove);
TRemoveFlags = set of TRemoveFlag;
TUpdateFlag = (Upsert, MultiUpdate);
TUpdateFlags = set of TUpdateFlag;
private
FReadPreference: TMongoReadPreference;
FWriteConcern: TMongoWriteConcern;
FLastError: TMongoDocument;
FBulkHandle: Pmongoc_bulk_operation_t;
FDocsInserted: Int64;
FDocsMatched: Int64;
FDocsModified: Int64;
FDocsRemoved: Int64;
FDocsUpserted: Int64;
FLastOID: TMongoOID;
FLastID: Variant;
function GetName: String;
function GetDB: String;
function GetNS: String;
procedure ResetCounts;
procedure ProcessWriteResult(AReply: TMongoDocument; ABulk, AFailed: Boolean);
function GetLastError: TMongoDocument;
function GetIsBulk: Boolean;
procedure EnsureID(ADocument: TMongoDocument);
function AggregateBase(APipeline: TMongoPipeline; AReleasePipeline: Boolean;
AFlags: TMongoQueryFlags): IMongoCursor;
function FindBase(AQuery: TMongoQuery; AReleaseQuery: Boolean;
AFlags: TMongoQueryFlags): IMongoCursor;
protected
procedure InternalFreeHandle; override;
procedure FreeHandle; override;
procedure HandleAllocated; override;
constructor Create(AEnv: TMongoEnv; AOwningObj: TObject; AHandle: Pmongoc_collection_t);
public
destructor Destroy; override;
// manage collection
procedure Drop(AIgnoreObjNotExists: Boolean = False);
procedure Rename(const ANewDB, ANewName: String; ADropTarget: Boolean = True);
function Validate(AOptions: TMongoDocument): TMongoDocument;
function Statistics(AOptions: TMongoDocument): TMongoDocument;
// manage collection indexes
function ListIndexes: IMongoCursor;
procedure CreateIndex(AIndex: TMongoIndex);
procedure DropIndex(const AName: String; AIgnoreObjNotExists: Boolean = False);
// collection updating
procedure BeginBulk(AOrdered: Boolean = True);
procedure EndBulk;
procedure CancelBulk;
procedure Insert(ADocument: TMongoDocument; AFlags: TInsertFlags = []); overload;
procedure Insert(AInsert: TMongoInsert; AFlags: TInsertFlags = []); overload;
function Insert(AFlags: TInsertFlags = []): TMongoInsert; overload;
procedure Remove(ASelector: TMongoSelector; AFlags: TRemoveFlags = []); overload;
function Remove(AFlags: TRemoveFlags = []): TMongoSelector; overload;
procedure RemoveAll;
procedure Update(AUpdate: TMongoUpdate; AFlags: TUpdateFlags = [TUpdateFlag.MultiUpdate]); overload;
function Update(AFlags: TUpdateFlags = [TUpdateFlag.MultiUpdate]): TMongoUpdate; overload;
// collection querying
function Count(AQuery: TMongoQuery; AFlags: TMongoQueryFlags = []): Int64; overload;
function Count(AFlags: TMongoQueryFlags = []): TMongoQuery; overload;
function Aggregate(APipeline: TMongoPipeline; AFlags: TMongoQueryFlags = []): IMongoCursor; overload;
function Aggregate(AFlags: TMongoQueryFlags = []): TMongoPipeline; overload;
function Find(AQuery: TMongoQuery; AFlags: TMongoQueryFlags = []): IMongoCursor; overload;
function Find(AFlags: TMongoQueryFlags = []): TMongoQuery; overload;
// execute commands
function Command(ACommand: TMongoCommand; AFlags: TMongoQueryFlags = []): IMongoCursor; overload;
function Command(const AJSON: String; AFlags: TMongoQueryFlags = []): IMongoCursor; overload;
function CommandSimple(ACommand: TMongoDocument): TMongoDocument; overload;
function CommandSimple(const AJSON: String): TMongoDocument; overload;
// DBRef lookup
function Dereference(const AOid: TJsonOid): TMongoDocument;
// props / state
property Name: String read GetName;
property DB: String read GetDB;
property NS: String read GetNS;
property IsBulk: Boolean read GetIsBulk;
property LastError: TMongoDocument read GetLastError;
property LastID: Variant read FLastID;
property DocsInserted: Int64 read FDocsInserted;
property DocsMatched: Int64 read FDocsMatched;
property DocsModified: Int64 read FDocsModified;
property DocsRemoved: Int64 read FDocsRemoved;
property DocsUpserted: Int64 read FDocsUpserted;
// props / options
property ReadPreference: TMongoReadPreference read FReadPreference;
property WriteConcern: TMongoWriteConcern read FWriteConcern;
end;
implementation
uses
System.Variants, System.DateUtils, Data.SqlTimSt, Data.FmtBcd,
FireDAC.Stan.Consts;
{-------------------------------------------------------------------------------}
const
// mongoc.h
smongoc_client_new: String = 'mongoc_client_new';
smongoc_client_destroy: String = 'mongoc_client_destroy';
smongoc_client_command: String = 'mongoc_client_command';
smongoc_client_command_simple: String = 'mongoc_client_command_simple';
smongoc_client_kill_cursor: String = 'mongoc_client_kill_cursor';
smongoc_client_get_database: String = 'mongoc_client_get_database';
smongoc_client_get_collection: String = 'mongoc_client_get_collection';
smongoc_client_find_databases: String = 'mongoc_client_find_databases';
smongoc_client_get_server_status: String = 'mongoc_client_get_server_status';
smongoc_client_get_max_message_size: String = 'mongoc_client_get_max_message_size';
smongoc_client_get_max_bson_size: String = 'mongoc_client_get_max_bson_size';
smongoc_client_get_write_concern: String = 'mongoc_client_get_write_concern';
smongoc_client_set_write_concern: String = 'mongoc_client_set_write_concern';
smongoc_client_get_read_prefs: String = 'mongoc_client_get_read_prefs';
smongoc_client_set_read_prefs: String = 'mongoc_client_set_read_prefs';
smongoc_client_set_ssl_opts: String = 'mongoc_client_set_ssl_opts';
smongoc_client_get_uri: String = 'mongoc_client_get_uri';
// mongoc-uri.h
smongoc_uri_get_string: String = 'mongoc_uri_get_string';
// mongoc-bulk-operation.h
smongoc_bulk_operation_new: String = 'mongoc_bulk_operation_new';
smongoc_bulk_operation_destroy: String = 'mongoc_bulk_operation_destroy';
smongoc_bulk_operation_execute: String = 'mongoc_bulk_operation_execute';
smongoc_bulk_operation_insert: String = 'mongoc_bulk_operation_insert';
smongoc_bulk_operation_remove: String = 'mongoc_bulk_operation_remove';
smongoc_bulk_operation_remove_one: String = 'mongoc_bulk_operation_remove_one';
smongoc_bulk_operation_replace_one: String = 'mongoc_bulk_operation_replace_one';
smongoc_bulk_operation_update: String = 'mongoc_bulk_operation_update';
smongoc_bulk_operation_update_one: String = 'mongoc_bulk_operation_update_one';
// mongoc-collection.h
smongoc_collection_aggregate: String = 'mongoc_collection_aggregate';
smongoc_collection_destroy: String = 'mongoc_collection_destroy';
smongoc_collection_command: String = 'mongoc_collection_command';
smongoc_collection_command_simple: String = 'mongoc_collection_command_simple';
smongoc_collection_count: String = 'mongoc_collection_count';
smongoc_collection_count_with_opts: String = 'mongoc_collection_count_with_opts';
smongoc_collection_drop: String = 'mongoc_collection_drop';
smongoc_collection_drop_index: String = 'mongoc_collection_drop_index';
smongoc_collection_create_index: String = 'mongoc_collection_create_index';
smongoc_collection_find_indexes: String = 'mongoc_collection_find_indexes';
smongoc_collection_find: String = 'mongoc_collection_find';
smongoc_collection_insert: String = 'mongoc_collection_insert';
smongoc_collection_update: String = 'mongoc_collection_update';
smongoc_collection_save: String = 'mongoc_collection_save';
smongoc_collection_remove: String = 'mongoc_collection_remove';
smongoc_collection_rename: String = 'mongoc_collection_rename';
smongoc_collection_find_and_modify: String = 'mongoc_collection_find_and_modify';
smongoc_collection_stats: String = 'mongoc_collection_stats';
smongoc_collection_create_bulk_operation: String = 'mongoc_collection_create_bulk_operation';
smongoc_collection_get_read_prefs: String = 'mongoc_collection_get_read_prefs';
smongoc_collection_set_read_prefs: String = 'mongoc_collection_set_read_prefs';
smongoc_collection_get_write_concern: String = 'mongoc_collection_get_write_concern';
smongoc_collection_set_write_concern: String = 'mongoc_collection_set_write_concern';
smongoc_collection_get_name: String = 'mongoc_collection_get_name';
smongoc_collection_get_last_error: String = 'mongoc_collection_get_last_error';
smongoc_collection_validate: String = 'mongoc_collection_validate';
// mongoc-cursor.h
smongoc_cursor_destroy: String = 'mongoc_cursor_destroy';
smongoc_cursor_more: String = 'mongoc_cursor_more';
smongoc_cursor_next: String = 'mongoc_cursor_next';
smongoc_cursor_error: String = 'mongoc_cursor_error';
smongoc_cursor_current: String = 'mongoc_cursor_current';
smongoc_cursor_is_alive: String = 'mongoc_cursor_is_alive';
// mongoc-database.h
smongoc_database_get_name: String = 'mongoc_database_get_name';
smongoc_database_remove_user: String = 'mongoc_database_remove_user';
smongoc_database_remove_all_users: String = 'mongoc_database_remove_all_users';
smongoc_database_add_user: String = 'mongoc_database_add_user';
smongoc_database_destroy: String = 'mongoc_database_destroy';
smongoc_database_command: String = 'mongoc_database_command';
smongoc_database_command_simple: String = 'mongoc_database_command_simple';
smongoc_database_drop: String = 'mongoc_database_drop';
smongoc_database_has_collection: String = 'mongoc_database_has_collection';
smongoc_database_create_collection: String = 'mongoc_database_create_collection';
smongoc_database_get_read_prefs: String = 'mongoc_database_get_read_prefs';
smongoc_database_set_read_prefs: String = 'mongoc_database_set_read_prefs';
smongoc_database_get_write_concern: String = 'mongoc_database_get_write_concern';
smongoc_database_set_write_concern: String = 'mongoc_database_set_write_concern';
smongoc_database_find_collections: String = 'mongoc_database_find_collections';
smongoc_database_get_collection: String = 'mongoc_database_get_collection';
// mongoc-index.h
smongoc_index_opt_get_default: String = 'mongoc_index_opt_get_default';
smongoc_index_opt_init: String = 'mongoc_index_opt_init';
// mongoc-init.h
smongoc_init: String = 'mongoc_init';
smongoc_cleanup: String = 'mongoc_cleanup';
// mongoc-log.h
smongoc_log_set_handler: String = 'mongoc_log_set_handler';
smongoc_log_default_handler: String = 'mongoc_log_default_handler';
smongoc_log_level_str: String = 'mongoc_log_level_str';
// mongoc-matcher.h
smongoc_matcher_new: String = 'mongoc_matcher_new';
smongoc_matcher_match: String = 'mongoc_matcher_match';
smongoc_matcher_destroy: String = 'mongoc_matcher_destroy';
// mongoc-read-prefs.h
smongoc_read_prefs_new: String = 'mongoc_read_prefs_new';
smongoc_read_prefs_destroy: String = 'mongoc_read_prefs_destroy';
smongoc_read_prefs_copy: String = 'mongoc_read_prefs_copy';
smongoc_read_prefs_get_mode: String = 'mongoc_read_prefs_get_mode';
smongoc_read_prefs_set_mode: String = 'mongoc_read_prefs_set_mode';
smongoc_read_prefs_get_tags: String = 'mongoc_read_prefs_get_tags';
smongoc_read_prefs_set_tags: String = 'mongoc_read_prefs_set_tags';
smongoc_read_prefs_add_tag: String = 'mongoc_read_prefs_add_tag';
smongoc_read_prefs_is_valid: String = 'mongoc_read_prefs_is_valid';
// mongoc-write-concern.h
smongoc_write_concern_new: String = 'mongoc_write_concern_new';
smongoc_write_concern_destroy: String = 'mongoc_write_concern_destroy';
smongoc_write_concern_copy: String = 'mongoc_write_concern_copy';
smongoc_write_concern_get_fsync: String = 'mongoc_write_concern_get_fsync';
smongoc_write_concern_set_fsync: String = 'mongoc_write_concern_set_fsync';
smongoc_write_concern_get_journal: String = 'mongoc_write_concern_get_journal';
smongoc_write_concern_set_journal: String = 'mongoc_write_concern_set_journal';
smongoc_write_concern_get_w: String = 'mongoc_write_concern_get_w';
smongoc_write_concern_set_w: String = 'mongoc_write_concern_set_w';
smongoc_write_concern_get_wtag: String = 'mongoc_write_concern_get_wtag';
smongoc_write_concern_set_wtag: String = 'mongoc_write_concern_set_wtag';
smongoc_write_concern_get_wtimeout: String = 'mongoc_write_concern_get_wtimeout';
smongoc_write_concern_set_wtimeout: String = 'mongoc_write_concern_set_wtimeout';
smongoc_write_concern_get_wmajority: String = 'mongoc_write_concern_get_wmajority';
smongoc_write_concern_set_wmajority: String = 'mongoc_write_concern_set_wmajority';
// bson-context.h
sbson_context_new: String = 'bson_context_new';
sbson_context_destroy: String = 'bson_context_destroy';
sbson_context_get_default: String = 'bson_context_get_default';
// bson-oid.h
sbson_oid_compare: String = 'bson_oid_compare';
sbson_oid_copy: String = 'bson_oid_copy';
sbson_oid_init: String = 'bson_oid_init';
sbson_oid_init_from_string: String = 'bson_oid_init_from_string';
sbson_oid_to_string: String = 'bson_oid_to_string';
sbson_oid_get_time_t: String = 'bson_oid_get_time_t';
// bson.h
sbson_mem_set_vtable: String = 'bson_mem_set_vtable';
sbson_init: String = 'bson_init';
sbson_init_static: String = 'bson_init_static';
sbson_reinit: String = 'bson_reinit';
sbson_new: String = 'bson_new';
sbson_destroy: String = 'bson_destroy';
sbson_get_data: String = 'bson_get_data';
sbson_free: String = 'bson_free';
sbson_init_from_json: String = 'bson_init_from_json';
sbson_as_json: String = 'bson_as_json';
sbson_copy_to: String = 'bson_copy_to';
sbson_concat: String = 'bson_concat';
sbson_append_array: String = 'bson_append_array';
sbson_append_document: String = 'bson_append_document';
sbson_append_bool: String = 'bson_append_bool';
sbson_append_code: String = 'bson_append_code';
sbson_append_code_with_scope: String = 'bson_append_code_with_scope';
sbson_append_double: String = 'bson_append_double';
sbson_append_int32: String = 'bson_append_int32';
sbson_append_int64: String = 'bson_append_int64';
sbson_append_null: String = 'bson_append_null';
sbson_append_oid: String = 'bson_append_oid';
sbson_append_regex: String = 'bson_append_regex';
sbson_append_utf8: String = 'bson_append_utf8';
sbson_append_time_t: String = 'bson_append_time_t';
sbson_append_timeval: String = 'bson_append_timeval';
sbson_append_date_time: String = 'bson_append_date_time';
sbson_append_binary: String = 'bson_append_binary';
// bson-iter.h
sbson_iter_init: String = 'bson_iter_init';
sbson_iter_find: String = 'bson_iter_find';
sbson_iter_find_descendant: String = 'bson_iter_find_descendant';
sbson_iter_next: String = 'bson_iter_next';
sbson_iter_recurse: String = 'bson_iter_recurse';
sbson_iter_key: String = 'bson_iter_key';
sbson_iter_type: String = 'bson_iter_type';
sbson_iter_binary: String = 'bson_iter_binary';
sbson_iter_bool: String = 'bson_iter_bool';
sbson_iter_code: String = 'bson_iter_code';
sbson_iter_double: String = 'bson_iter_double';
sbson_iter_int32: String = 'bson_iter_int32';
sbson_iter_int64: String = 'bson_iter_int64';
sbson_iter_oid: String = 'bson_iter_oid';
sbson_iter_regex: String = 'bson_iter_regex';
sbson_iter_utf8: String = 'bson_iter_utf8';
sbson_iter_time_t: String = 'bson_iter_time_t';
sbson_iter_date_time: String = 'bson_iter_date_time';
{-------------------------------------------------------------------------------}
function QF2mqft(AFlags: TMongoQueryFlags): mongoc_query_flags_t;
begin
Result := MONGOC_QUERY_NONE;
if TMongoQueryFlag.TailableCursors in AFlags then
Result := Result or MONGOC_QUERY_TAILABLE_CURSOR;
if TMongoQueryFlag.SlaveOk in AFlags then
Result := Result or MONGOC_QUERY_SLAVE_OK;
if TMongoQueryFlag.NoCursorTimeout in AFlags then
Result := Result or MONGOC_QUERY_NO_CURSOR_TIMEOUT;
if TMongoQueryFlag.AwaitData in AFlags then
Result := Result or MONGOC_QUERY_AWAIT_DATA;
if TMongoQueryFlag.Exhaust in AFlags then
Result := Result or MONGOC_QUERY_EXHAUST;
if TMongoQueryFlag.Partial in AFlags then
Result := Result or MONGOC_QUERY_PARTIAL;
end;
{-------------------------------------------------------------------------------}
{ TMongoClientLib }
{-------------------------------------------------------------------------------}
constructor TMongoClientLib.Create(AOwningObj: TObject);
begin
inherited Create(S_FD_MongoId, AOwningObj);
end;
{-------------------------------------------------------------------------------}
procedure TMongoClientLib.Load(const AVendorHome, AVendorLib: String);
const
C_MongoDll: String = 'libmongoc-1.0' + C_FD_DLLExt;
var
sDLLName: String;
begin
sDLLName := AVendorHome;
if sDLLName <> '' then
sDLLName := FDNormPath(FDNormPath(sDLLName) + C_FD_DLLFolder);
if AVendorLib <> '' then
sDLLName := sDLLName + AVendorLib
else
sDLLName := sDLLName + C_MongoDll;
inherited Load([sDLLName], True);
end;
{-------------------------------------------------------------------------------}
procedure TMongoClientLib.LoadEntries;
begin
// mongoc.h
Fmongoc_client_new := GetProc(smongoc_client_new);
Fmongoc_client_destroy := GetProc(smongoc_client_destroy);
Fmongoc_client_command := GetProc(smongoc_client_command);
Fmongoc_client_command_simple := GetProc(smongoc_client_command_simple);
Fmongoc_client_kill_cursor := GetProc(smongoc_client_kill_cursor);
Fmongoc_client_get_database := GetProc(smongoc_client_get_database);
Fmongoc_client_get_collection := GetProc(smongoc_client_get_collection);
Fmongoc_client_find_databases := GetProc(smongoc_client_find_databases);
Fmongoc_client_get_server_status := GetProc(smongoc_client_get_server_status);
Fmongoc_client_get_max_message_size := GetProc(smongoc_client_get_max_message_size);
Fmongoc_client_get_max_bson_size := GetProc(smongoc_client_get_max_bson_size);
Fmongoc_client_get_write_concern := GetProc(smongoc_client_get_write_concern);
Fmongoc_client_set_write_concern := GetProc(smongoc_client_set_write_concern);
Fmongoc_client_get_read_prefs := GetProc(smongoc_client_get_read_prefs);
Fmongoc_client_set_read_prefs := GetProc(smongoc_client_set_read_prefs);
Fmongoc_client_set_ssl_opts := GetProc(smongoc_client_set_ssl_opts, False);
Fmongoc_client_get_uri := GetProc(smongoc_client_get_uri);
// mongoc-uri.h
Fmongoc_uri_get_string := GetProc(smongoc_uri_get_string);
// mongoc-bulk-operation.h
Fmongoc_bulk_operation_new := GetProc(smongoc_bulk_operation_new);
Fmongoc_bulk_operation_destroy := GetProc(smongoc_bulk_operation_destroy);
Fmongoc_bulk_operation_execute := GetProc(smongoc_bulk_operation_execute);
Fmongoc_bulk_operation_insert := GetProc(smongoc_bulk_operation_insert);
Fmongoc_bulk_operation_remove := GetProc(smongoc_bulk_operation_remove);
Fmongoc_bulk_operation_remove_one := GetProc(smongoc_bulk_operation_remove_one);
Fmongoc_bulk_operation_replace_one := GetProc(smongoc_bulk_operation_replace_one);
Fmongoc_bulk_operation_update := GetProc(smongoc_bulk_operation_update);
Fmongoc_bulk_operation_update_one := GetProc(smongoc_bulk_operation_update_one);
// mongoc-collection.h
Fmongoc_collection_aggregate := GetProc(smongoc_collection_aggregate);
Fmongoc_collection_destroy := GetProc(smongoc_collection_destroy);
Fmongoc_collection_command := GetProc(smongoc_collection_command);
Fmongoc_collection_command_simple := GetProc(smongoc_collection_command_simple);
Fmongoc_collection_count := GetProc(smongoc_collection_count);
Fmongoc_collection_count_with_opts := GetProc(smongoc_collection_count_with_opts);
Fmongoc_collection_drop := GetProc(smongoc_collection_drop);
Fmongoc_collection_drop_index := GetProc(smongoc_collection_drop_index);
Fmongoc_collection_create_index := GetProc(smongoc_collection_create_index);
Fmongoc_collection_find_indexes := GetProc(smongoc_collection_find_indexes);
Fmongoc_collection_find := GetProc(smongoc_collection_find);
Fmongoc_collection_insert := GetProc(smongoc_collection_insert);
Fmongoc_collection_update := GetProc(smongoc_collection_update);
Fmongoc_collection_save := GetProc(smongoc_collection_save);
Fmongoc_collection_remove := GetProc(smongoc_collection_remove);
Fmongoc_collection_rename := GetProc(smongoc_collection_rename);
Fmongoc_collection_find_and_modify := GetProc(smongoc_collection_find_and_modify);
Fmongoc_collection_stats := GetProc(smongoc_collection_stats);
Fmongoc_collection_create_bulk_operation := GetProc(smongoc_collection_create_bulk_operation);
Fmongoc_collection_get_read_prefs := GetProc(smongoc_collection_get_read_prefs);
Fmongoc_collection_set_read_prefs := GetProc(smongoc_collection_set_read_prefs);
Fmongoc_collection_get_write_concern := GetProc(smongoc_collection_get_write_concern);
Fmongoc_collection_set_write_concern := GetProc(smongoc_collection_set_write_concern);
Fmongoc_collection_get_name := GetProc(smongoc_collection_get_name);
Fmongoc_collection_get_last_error := GetProc(smongoc_collection_get_last_error);
Fmongoc_collection_validate := GetProc(smongoc_collection_validate);
// mongoc-cursor.h
Fmongoc_cursor_destroy := GetProc(smongoc_cursor_destroy);
Fmongoc_cursor_more := GetProc(smongoc_cursor_more);
Fmongoc_cursor_next := GetProc(smongoc_cursor_next);
Fmongoc_cursor_error := GetProc(smongoc_cursor_error);
Fmongoc_cursor_current := GetProc(smongoc_cursor_current);
Fmongoc_cursor_is_alive := GetProc(smongoc_cursor_is_alive);
// mongoc-database.h
Fmongoc_database_get_name := GetProc(smongoc_database_get_name);
Fmongoc_database_remove_user := GetProc(smongoc_database_remove_user);
Fmongoc_database_remove_all_users := GetProc(smongoc_database_remove_all_users);
Fmongoc_database_add_user := GetProc(smongoc_database_add_user);
Fmongoc_database_destroy := GetProc(smongoc_database_destroy);
Fmongoc_database_command := GetProc(smongoc_database_command);
Fmongoc_database_command_simple := GetProc(smongoc_database_command_simple);
Fmongoc_database_drop := GetProc(smongoc_database_drop);
Fmongoc_database_has_collection := GetProc(smongoc_database_has_collection);
Fmongoc_database_create_collection := GetProc(smongoc_database_create_collection);
Fmongoc_database_get_read_prefs := GetProc(smongoc_database_get_read_prefs);
Fmongoc_database_set_read_prefs := GetProc(smongoc_database_set_read_prefs);
Fmongoc_database_get_write_concern := GetProc(smongoc_database_get_write_concern);
Fmongoc_database_set_write_concern := GetProc(smongoc_database_set_write_concern);
Fmongoc_database_find_collections := GetProc(smongoc_database_find_collections);
Fmongoc_database_get_collection := GetProc(smongoc_database_get_collection);
// mongoc-index.h
Fmongoc_index_opt_get_default := GetProc(smongoc_index_opt_get_default);
Fmongoc_index_opt_init := GetProc(smongoc_index_opt_init);
// mongoc-init.h
Fmongoc_init := GetProc(smongoc_init);
Fmongoc_cleanup := GetProc(smongoc_cleanup);
// mongoc-log.h
Fmongoc_log_set_handler := GetProc(smongoc_log_set_handler);
Fmongoc_log_default_handler := GetProc(smongoc_log_default_handler);
Fmongoc_log_level_str := GetProc(smongoc_log_level_str);
// mongoc-matcher.h
Fmongoc_matcher_new := GetProc(smongoc_matcher_new);
Fmongoc_matcher_match := GetProc(smongoc_matcher_match);
Fmongoc_matcher_destroy := GetProc(smongoc_matcher_destroy);
// mongoc-read-prefs.h
Fmongoc_read_prefs_new := GetProc(smongoc_read_prefs_new);
Fmongoc_read_prefs_destroy := GetProc(smongoc_read_prefs_destroy);
Fmongoc_read_prefs_copy := GetProc(smongoc_read_prefs_copy);
Fmongoc_read_prefs_get_mode := GetProc(smongoc_read_prefs_get_mode);
Fmongoc_read_prefs_set_mode := GetProc(smongoc_read_prefs_set_mode);
Fmongoc_read_prefs_get_tags := GetProc(smongoc_read_prefs_get_tags);
Fmongoc_read_prefs_set_tags := GetProc(smongoc_read_prefs_set_tags);
Fmongoc_read_prefs_add_tag := GetProc(smongoc_read_prefs_add_tag);
Fmongoc_read_prefs_is_valid := GetProc(smongoc_read_prefs_is_valid);
// mongoc-write-concern.h
Fmongoc_write_concern_new := GetProc(smongoc_write_concern_new);
Fmongoc_write_concern_destroy := GetProc(smongoc_write_concern_destroy);
Fmongoc_write_concern_copy := GetProc(smongoc_write_concern_copy);
Fmongoc_write_concern_get_fsync := GetProc(smongoc_write_concern_get_fsync);
Fmongoc_write_concern_set_fsync := GetProc(smongoc_write_concern_set_fsync);
Fmongoc_write_concern_get_journal := GetProc(smongoc_write_concern_get_journal);
Fmongoc_write_concern_set_journal := GetProc(smongoc_write_concern_set_journal);
Fmongoc_write_concern_get_w := GetProc(smongoc_write_concern_get_w);
Fmongoc_write_concern_set_w := GetProc(smongoc_write_concern_set_w);
Fmongoc_write_concern_get_wtag := GetProc(smongoc_write_concern_get_wtag);
Fmongoc_write_concern_set_wtag := GetProc(smongoc_write_concern_set_wtag);
Fmongoc_write_concern_get_wtimeout := GetProc(smongoc_write_concern_get_wtimeout);
Fmongoc_write_concern_set_wtimeout := GetProc(smongoc_write_concern_set_wtimeout);
Fmongoc_write_concern_get_wmajority := GetProc(smongoc_write_concern_get_wmajority);
Fmongoc_write_concern_set_wmajority := GetProc(smongoc_write_concern_set_wmajority);
end;
{-------------------------------------------------------------------------------}
{ TMongoBSONLib }
{-------------------------------------------------------------------------------}
constructor TMongoBSONLib.Create(ACLib: TMongoClientLib);
begin
inherited Create(ACLib.DriverID, ACLib.OwningObj);
FCLib := ACLib;
end;
{-------------------------------------------------------------------------------}
{$IFDEF MSWINDOWS}
function _malloc(num_bytes: TFDsize_t): Pointer; cdecl;
begin
if num_bytes < SizeOf(Pointer) then
num_bytes := SizeOf(Pointer);
GetMem(Result, num_bytes);
end;
function _calloc(n_members, num_bytes: TFDsize_t): Pointer; cdecl;
begin
GetMem(Result, n_members * num_bytes);
FillChar(Result^, n_members * num_bytes, 0);
end;
function _realloc(mem: Pointer; num_bytes: TFDsize_t): Pointer; cdecl;
begin
Result := mem;
if (num_bytes > 0) and (num_bytes < SizeOf(Pointer)) then
num_bytes := SizeOf(Pointer);
ReallocMem(Result, num_bytes);
end;
procedure _free(mem: Pointer); cdecl;
begin
FreeMem(mem);
end;
{$ENDIF}
procedure TMongoBSONLib.Load;
const
C_BSONDll: String = 'libbson';
var
i: Integer;
sPath: String;
{$IFDEF MSWINDOWS}
rMemTab: bson_mem_vtable_t;
{$ENDIF}
begin
sPath := ExtractFilePath(FCLib.DLLName) + C_BSONDll;
i := FCLib.DLLName.LastDelimiter('-');
if i >= 0 then
sPath := sPath + FCLib.DLLName.Substring(i)
else
sPath := sPath + C_FD_DLLExt;
inherited Load([sPath], True);
{$IFDEF MSWINDOWS}
rMemTab.malloc := @_malloc;
rMemTab.calloc := @_calloc;
rMemTab.realloc := @_realloc;
rMemTab.free := @_free;
Fbson_mem_set_vtable(@rMemTab);
{$ENDIF}
if FCLib.hDLL <> 0 then
FCLib.Fmongoc_init();
end;
{-------------------------------------------------------------------------------}
procedure TMongoBSONLib.Unload;
begin
if FCLib.hDLL <> 0 then
FCLib.Fmongoc_cleanup();
inherited Unload;
end;
{-------------------------------------------------------------------------------}
procedure TMongoBSONLib.LoadEntries;
begin
// bson-context.h
Fbson_context_new := GetProc(sbson_context_new);
Fbson_context_destroy := GetProc(sbson_context_destroy);
Fbson_context_get_default := GetProc(sbson_context_get_default);
// bson-oid.h
Fbson_oid_compare := GetProc(sbson_oid_compare);
Fbson_oid_copy := GetProc(sbson_oid_copy);
Fbson_oid_init := GetProc(sbson_oid_init);
Fbson_oid_init_from_string := GetProc(sbson_oid_init_from_string);
Fbson_oid_to_string := GetProc(sbson_oid_to_string);
Fbson_oid_get_time_t := GetProc(sbson_oid_get_time_t);
// bson.h
Fbson_mem_set_vtable := GetProc(sbson_mem_set_vtable);
Fbson_init := GetProc(sbson_init);
Fbson_init_static := GetProc(sbson_init_static);
fbson_reinit := GetProc(sbson_reinit);
Fbson_new := GetProc(sbson_new);
Fbson_destroy := GetProc(sbson_destroy);
Fbson_get_data := GetProc(sbson_get_data);
Fbson_free := GetProc(sbson_free);
Fbson_init_from_json := GetProc(sbson_init_from_json);
Fbson_as_json := GetProc(sbson_as_json);
Fbson_copy_to := GetProc(sbson_copy_to);
Fbson_concat := GetProc(sbson_concat);
Fbson_append_array := GetProc(sbson_append_array);
Fbson_append_document := GetProc(sbson_append_document);
Fbson_append_bool := GetProc(sbson_append_bool);
Fbson_append_code := GetProc(sbson_append_code);
Fbson_append_code_with_scope := GetProc(sbson_append_code_with_scope);
Fbson_append_double := GetProc(sbson_append_double);
Fbson_append_int32 := GetProc(sbson_append_int32);
Fbson_append_int64 := GetProc(sbson_append_int64);
Fbson_append_null := GetProc(sbson_append_null);
Fbson_append_oid := GetProc(sbson_append_oid);
Fbson_append_regex := GetProc(sbson_append_regex);
Fbson_append_utf8 := GetProc(sbson_append_utf8);
Fbson_append_time_t := GetProc(sbson_append_time_t);
Fbson_append_timeval := GetProc(sbson_append_timeval);
Fbson_append_date_time := GetProc(sbson_append_date_time);
Fbson_append_binary := GetProc(sbson_append_binary);
// bson-iter.h
Fbson_iter_init := GetProc(sbson_iter_init);
Fbson_iter_find := GetProc(sbson_iter_find);
Fbson_iter_find_descendant := GetProc(sbson_iter_find_descendant);
Fbson_iter_next := GetProc(sbson_iter_next);
Fbson_iter_recurse := GetProc(sbson_iter_recurse);
Fbson_iter_key := GetProc(sbson_iter_key);
Fbson_iter_type := GetProc(sbson_iter_type);
Fbson_iter_binary := GetProc(sbson_iter_binary);
Fbson_iter_bool := GetProc(sbson_iter_bool);
Fbson_iter_code := GetProc(sbson_iter_code);
Fbson_iter_double := GetProc(sbson_iter_double);
Fbson_iter_int32 := GetProc(sbson_iter_int32);
Fbson_iter_int64 := GetProc(sbson_iter_int64);
Fbson_iter_oid := GetProc(sbson_iter_oid);
Fbson_iter_regex := GetProc(sbson_iter_regex);
Fbson_iter_utf8 := GetProc(sbson_iter_utf8);
Fbson_iter_time_t := GetProc(sbson_iter_time_t);
Fbson_iter_date_time := GetProc(sbson_iter_date_time);
end;
{-------------------------------------------------------------------------------}
{ TMongoObject }
{-------------------------------------------------------------------------------}
constructor TMongoObject.Create(AEnv: TMongoEnv; AOwningObj: TObject);
begin
inherited Create;
FEnv := AEnv;
FOwningObj := AOwningObj;
FOwnHandle := True;
end;
{-------------------------------------------------------------------------------}
constructor TMongoObject.Create(AEnv: TMongoEnv; AOwningObj: TObject;
AHandle: Pmongoc_handle_t);
begin
Create(AEnv, AOwningObj);
FHandle := AHandle;
end;
{-------------------------------------------------------------------------------}
destructor TMongoObject.Destroy;
begin
FreeHandle;
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
procedure TMongoObject.InternalFreeHandle;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TMongoObject.FreeHandle;
begin
if FOwnHandle and (Handle <> nil) then
InternalFreeHandle;
FHandle := nil;
FOwnHandle := True;
end;
{-------------------------------------------------------------------------------}
procedure TMongoObject.HandleAllocated;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
function TMongoObject.GetHandle: Pmongoc_handle_t;
begin
if Self = nil then
Result := nil
else
Result := FHandle;
end;
{-------------------------------------------------------------------------------}
procedure TMongoObject.SetHandle(const AValue: Pmongoc_handle_t);
begin
if Handle <> AValue then begin
if Handle <> nil then
FreeHandle;
FHandle := AValue;
FOwnHandle := FHandle = nil;
if Handle <> nil then
HandleAllocated;
end;
end;
{-------------------------------------------------------------------------------}
function TMongoObject.GetError: TMongoError;
begin
Result := FEnv.Error;
end;
{-------------------------------------------------------------------------------}
function TMongoObject.GetCLib: TMongoClientLib;
begin
Result := FEnv.CLib;
end;
{-------------------------------------------------------------------------------}
function TMongoObject.GetBLib: TMongoBSONLib;
begin
Result := FEnv.BLib;
end;
{-------------------------------------------------------------------------------}
{ TFDMongoError }
{-------------------------------------------------------------------------------}
procedure TFDMongoError.Assign(ASrc: TFDDBError);
begin
inherited Assign(ASrc);
if ASrc is TFDMongoError then
FDomain := TFDMongoError(ASrc).FDomain;
end;
{-------------------------------------------------------------------------------}
procedure TFDMongoError.LoadFromStorage(const AStorage: IFDStanStorage);
begin
inherited LoadFromStorage(AStorage);
FDomain := AStorage.ReadLongWord('Domain', 0);
end;
{-------------------------------------------------------------------------------}
procedure TFDMongoError.SaveToStorage(const AStorage: IFDStanStorage);
begin
inherited SaveToStorage(AStorage);
AStorage.WriteInteger('Domain', Domain, 0);
end;
{-------------------------------------------------------------------------------}
{ EMongoNativeException }
{-------------------------------------------------------------------------------}
constructor EMongoNativeException.Create(AError: TMongoError);
var
sMsg: String;
begin
sMsg := AError.Env.ANSI.Decode(@AError.BError.message[0]);
inherited Create(er_FD_MongoGeneral, FDExceptionLayers([S_FD_LPhys,
AError.FEnv.CLib.DriverID]) + sMsg);
AppendError(1, AError.BError.code, AError.BError.domain, sMsg, -1);
{$IFDEF FireDAC_MONITOR}
AError.Env.Trace(ekError, esProgress, 'ERROR: ' + Message,
['Domain', AError.BError.domain]);
{$ENDIF}
AError.FBError.domain := 0;
AError.FBError.code := 0;
FillChar(AError.FBError.message[0], SizeOf(AError.FBError.message), 0);
end;
{-------------------------------------------------------------------------------}
function EMongoNativeException.AppendError(ALevel, AErrorCode: Integer;
ADomain: Cardinal; const AMessage: String; ARowIndex: Integer): TFDMongoError;
var
sObj: String;
eKind: TFDCommandExceptionKind;
i1: Integer;
i2: Integer;
begin
sObj := '';
eKind := ekOther;
case AErrorCode of
MONGOC_ERROR_STREAM_SOCKET,
MONGOC_ERROR_STREAM_CONNECT,
13053:
eKind := ekServerGone;
MONGOC_ERROR_CLIENT_AUTHENTICATE:
eKind := ekUserPwdInvalid;
MONGOC_ERROR_QUERY_COMMAND_NOT_FOUND:
eKind := ekObjNotExists;
11000:
begin
i1 := Pos(': ', AMessage);
if i1 > 0 then begin
i2 := Pos(' dup key', AMessage, i1);
if i2 > 0 then
sObj := Copy(AMessage, i1 + 2, i2 - i1 - 2);
end;
eKind := ekUKViolated;
end;
end;
Result := TFDMongoError(AppendError(ALevel, AErrorCode, AMessage, sObj,
eKind, -1, ARowIndex));
Result.FDomain := ADomain;
end;
{-------------------------------------------------------------------------------}
function EMongoNativeException.GetErrorClass: TFDDBErrorClass;
begin
Result := TFDMongoError;
end;
{-------------------------------------------------------------------------------}
function EMongoNativeException.GetErrors(AIndex: Integer): TFDMongoError;
begin
Result := TFDMongoError(inherited Errors[AIndex]);
end;
{-------------------------------------------------------------------------------}
{ TMongoError }
{-------------------------------------------------------------------------------}
procedure TMongoError.CheckError(AInitiator: TObject = nil; const AMethod: String = '');
var
oEx: EMongoNativeException;
begin
if (FBError.domain = 0) and (FBError.code = 0) and (AMethod = '') then
Exit;
if AInitiator = nil then
AInitiator := OwningObj;
if (FBError.domain = 0) and (FBError.code = 0) then
FDException(AInitiator, [S_FD_LPhys, Env.CLib.DriverID], er_FD_MongoError, [AMethod])
else begin
oEx := EMongoNativeException.Create(Self);
FDException(AInitiator, oEx {$IFDEF FireDAC_Monitor}, Env.Tracing {$ENDIF});
end;
end;
{-------------------------------------------------------------------------------}
{ TMongoEnv }
{-------------------------------------------------------------------------------}
constructor TMongoEnv.Create(ACLib: TMongoClientLib; ABLib: TMongoBSONLib;
AOwningObj: TObject);
begin
inherited Create;
FCLib := ACLib;
FBLib := ABLib;
FError := TMongoError.Create(Self, AOwningObj);
FOwningObj := AOwningObj;
FBuffer := TFDBuffer.Create;
FANSI := TFDEncoder.Create(FBuffer);
FANSI.Encoding := ecANSI;
FUTF8 := TFDEncoder.Create(FBuffer);
FUTF8.Encoding := ecUTF8;
end;
{-------------------------------------------------------------------------------}
destructor TMongoEnv.Destroy;
begin
FDFreeAndNil(FError);
FDFreeAndNil(FBuffer);
FDFreeAndNil(FANSI);
FDFreeAndNil(FUTF8);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
function TMongoEnv.NewDoc: TMongoDocument;
begin
Result := TMongoDocument.Create(Self);
end;
{$IFDEF FireDAC_MONITOR}
{-------------------------------------------------------------------------------}
function TMongoEnv.GetTracing: Boolean;
begin
Result := (FMonitor <> nil) and FMonitor.Tracing and FTracing;
end;
{-------------------------------------------------------------------------------}
procedure TMongoEnv.Trace(const AMsg: String; const AArgs: array of const);
begin
if GetTracing then
FMonitor.Notify(ekVendor, esProgress, OwningObj, AMsg, AArgs);
end;
{-------------------------------------------------------------------------------}
procedure TMongoEnv.Trace(AKind: TFDMoniEventKind; AStep: TFDMoniEventStep;
const AMsg: String; const AArgs: array of const);
begin
if GetTracing then
FMonitor.Notify(AKind, AStep, OwningObj, AMsg, AArgs);
end;
{$ENDIF}
{-------------------------------------------------------------------------------}
{ TMongoOID }
{-------------------------------------------------------------------------------}
constructor TMongoOID.Create(AEnv: TMongoEnv; AOwningObj: TObject);
begin
inherited Create(AEnv, AOwningObj);
GetMem(FHandle, SizeOf(bson_oid_t));
end;
{-------------------------------------------------------------------------------}
procedure TMongoOID.InternalFreeHandle;
begin
FreeMem(FHandle);
FHandle := nil;
end;
{-------------------------------------------------------------------------------}
procedure TMongoOID.Init;
begin
BLib.Fbson_oid_init(Handle, nil);
end;
{-------------------------------------------------------------------------------}
procedure TMongoOID.Clear;
begin
FillChar(Handle^, SizeOf(bson_oid_t), 0);
end;
{-------------------------------------------------------------------------------}
procedure TMongoOID.Assign(ASource: TMongoOID);
begin
BLib.Fbson_oid_copy(ASource.Handle, Handle);
end;
{-------------------------------------------------------------------------------}
function TMongoOID.GetAsDateTime: TDateTime;
begin
Result := UnixToDateTime(BLib.Fbson_oid_get_time_t(Handle), False);
end;
{-------------------------------------------------------------------------------}
function TMongoOID.GetAsString: String;
var
buff: array [0 .. 63] of Byte;
begin
BLib.Fbson_oid_to_string(Handle, PFDAnsiString(@buff[0]));
Result := Env.ANSI.Decode(@buff[0]);
end;
{-------------------------------------------------------------------------------}
procedure TMongoOID.SetAsString(const AValue: String);
var
sb: TFDByteString;
begin
sb := Env.ANSI.Encode(AValue);
BLib.Fbson_oid_init_from_string(Handle, PFDAnsiString(PByte(sb)));
end;
{-------------------------------------------------------------------------------}
function TMongoOID.GetAsOid: TJsonOid;
begin
Result := TJsonOid(Handle^);
end;
{-------------------------------------------------------------------------------}
procedure TMongoOID.SetAsOid(const AValue: TJsonOid);
begin
TJsonOid(Handle^) := AValue;
end;
{-------------------------------------------------------------------------------}
{ TMongoDocument.TBuilder }
{-------------------------------------------------------------------------------}
constructor TMongoDocument.TBuilder.Create(const AJSONWriter: TJSONWriter;
ADoc: TMongoDocument);
begin
inherited Create(AJSONWriter);
FDoc := ADoc;
ExtendedJsonMode := TJsonExtendedJsonMode.StrictMode;
DateTimeZoneHandling := ADoc.Env.DateTimeZoneHandling;
end;
{-------------------------------------------------------------------------------}
function TMongoDocument.TBuilder.DoGetReader(AWriter: TJsonWriter): TJsonReader;
var
oWStr, oRStr: TFDReadSharedMemoryStream;
begin
oWStr := (AWriter as TBsonWriter).Writer.BaseStream as TFDReadSharedMemoryStream;
oRStr := TFDReadSharedMemoryStream.Create;
oRStr.SetData(oWStr.Memory, oWStr.Size);
Result := TBsonReader.Create(oRStr);
Result.DateTimeZoneHandling := AWriter.DateTimeZoneHandling;
end;
{-------------------------------------------------------------------------------}
procedure TMongoDocument.TBuilder.DoReleaseReader(AWriter: TJsonWriter;
AReader: TJsonReader);
var
oRStr: TFDReadSharedMemoryStream;
begin
oRStr := (AReader as TBsonReader).Reader.BaseStream as TFDReadSharedMemoryStream;
FDFree(oRStr);
FDFree(AReader);
end;
{-------------------------------------------------------------------------------}
procedure TMongoDocument.TBuilder.DoResetWriter(AWriter: TJsonWriter);
begin
FDoc.Cleanup(False);
end;
{-------------------------------------------------------------------------------}
procedure TMongoDocument.TBuilder.DoWriteCustomVariant(AWriter: TJsonWriter;
const AValue: Variant);
begin
if VarIsFMTBcd(AValue) then
AWriter.WriteValue(Extended(AValue))
else if VarIsSQLTimeStamp(AValue) or VarIsSQLTimeStampOffset(AValue) then
AWriter.WriteValue(TDateTime(AValue))
else
inherited DoWriteCustomVariant(AWriter, AValue);
end;
{-------------------------------------------------------------------------------}
{ TMongoDocument.TIterator }
{-------------------------------------------------------------------------------}
constructor TMongoDocument.TIterator.Create(ADoc: TMongoDocument);
begin
ADoc.CheckClosed;
FStream := TFDReadSharedMemoryStream.Create;
TFDReadSharedMemoryStream(FStream).SetData(ADoc.FStream.Memory, ADoc.FStream.Size);
FReader := TBsonReader.Create(FStream);
FReader.DateTimeZoneHandling := ADoc.Env.DateTimeZoneHandling;
inherited Create(FReader);
end;
{-------------------------------------------------------------------------------}
destructor TMongoDocument.TIterator.Destroy;
begin
FDFreeAndNil(FReader);
FDFreeAndNil(FStream);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
procedure TMongoDocument.TIterator.DoRewindReader(AReader: TJsonReader);
var
oRStr: TFDReadSharedMemoryStream;
begin
oRStr := (AReader as TBsonReader).Reader.BaseStream as TFDReadSharedMemoryStream;
oRStr.Position := 0;
end;
{-------------------------------------------------------------------------------}
{ TMongoDocument }
{-------------------------------------------------------------------------------}
constructor TMongoDocument.Create(AEnv: TMongoEnv; AOwningObj, AParentObj: TObject);
begin
inherited Create(AEnv, AOwningObj);
FParentObj := AParentObj;
FStream := TFDReadSharedMemoryStream.Create;
FWriter := TBsonWriter.Create(FStream);
FWriter.DateTimeZoneHandling := AEnv.DateTimeZoneHandling;
FBuilder := TBuilder.Create(FWriter, Self);
FBuilder.BeginObject;
FHandleType := THandleType.RTL;
end;
{-------------------------------------------------------------------------------}
constructor TMongoDocument.Create(AEnv: TMongoEnv);
begin
Create(AEnv, AEnv.OwningObj, TObject(nil));
end;
{-------------------------------------------------------------------------------}
destructor TMongoDocument.Destroy;
begin
inherited Destroy;
FDFreeAndNil(FBuilder);
FDFreeAndNil(FWriter);
FDFreeAndNil(FStream);
end;
{-------------------------------------------------------------------------------}
procedure TMongoDocument.InternalFreeHandle;
begin
Cleanup(True);
end;
{-------------------------------------------------------------------------------}
procedure TMongoDocument.ErrorReadOnly;
begin
FDException(OwningObj, [S_FD_LPhys, S_FD_MongoId], er_FD_MongoDocReadOnly, []);
end;
{-------------------------------------------------------------------------------}
procedure TMongoDocument.Cleanup(AClearBuilder: Boolean);
begin
if AClearBuilder then
FBuilder.Clear;
case FHandleType of
THandleType.ReadInternal:
begin
FStream.Size := 0;
FreeMem(FHandle, SizeOf(bson_t));
FHandle := nil;
end;
THandleType.ReadExternal:
TFDReadSharedMemoryStream(FStream).SetData(nil, 0);
THandleType.WriteExternal:
begin
BLib.Fbson_destroy(FHandle);
FreeMem(FHandle, SizeOf(bson_t));
FHandle := nil;
end;
THandleType.RTL:
FStream.Size := 0;
end;
FHandleType := THandleType.RTL;
end;
{-------------------------------------------------------------------------------}
procedure TMongoDocument.AttachToImpl(const AValue: Pbson_t);
var
pData: Pointer;
iLen: Cardinal;
begin
if AValue = nil then begin
pData := nil;
iLen := 0;
end
else begin
iLen := AValue^.len;
pData := BLib.Fbson_get_data(AValue);
end;
TFDReadSharedMemoryStream(FStream).SetData(pData, iLen);
end;
{-------------------------------------------------------------------------------}
procedure TMongoDocument.CheckClosed;
begin
case FHandleType of
THandleType.ReadInternal,
THandleType.RTL:
FWriter.Flush;
THandleType.WriteExternal:
AttachToImpl(FHandle);
end;
end;
{-------------------------------------------------------------------------------}
function TMongoDocument.GetAsReadHandle: Pbson_t;
begin
if Self = nil then begin
Result := nil;
Exit;
end;
CheckClosed;
if FHandleType in [THandleType.RTL, THandleType.ReadExternal] then begin
if FHandle = nil then
GetMem(FHandle, SizeOf(bson_t));
if not BLib.Fbson_init_static(FHandle, FStream.Memory, FStream.Size) then
FDException(OwningObj, [S_FD_LPhys, S_FD_MongoId], er_FD_MongoFailedInitBSON, []);
FHandleType := THandleType.ReadInternal;
end;
Result := FHandle;
end;
{-------------------------------------------------------------------------------}
procedure TMongoDocument.SetAsReadHandle(const AValue: Pbson_t);
begin
Cleanup(True);
AttachToImpl(AValue);
FHandleType := THandleType.ReadExternal;
end;
{-------------------------------------------------------------------------------}
function TMongoDocument.GetAsWriteHandle: Pbson_t;
begin
if Self = nil then begin
Result := nil;
Exit;
end;
Cleanup(True);
if FHandle = nil then
GetMem(FHandle, SizeOf(bson_t));
BLib.Fbson_init(FHandle);
Result := FHandle;
FHandleType := THandleType.WriteExternal;
end;
{-------------------------------------------------------------------------------}
function TMongoDocument.GetAsJSON: String;
begin
if Self = nil then
Result := ''
else begin
CheckClosed;
Result := FBuilder.AsJSON;
end;
end;
{-------------------------------------------------------------------------------}
procedure TMongoDocument.SetAsJSON(const AValue: String);
begin
FBuilder
.Clear
.BeginObject
.AddPairs(AValue);
end;
{-------------------------------------------------------------------------------}
function TMongoDocument.GetInObject: Boolean;
begin
Result := FBuilder.ParentType = TJSONCollectionBuilder.TParentType.Pairs;
end;
{-------------------------------------------------------------------------------}
function TMongoDocument.GetPairs: TJSONCollectionBuilder.TPairs;
begin
Result := FBuilder.ParentObject;
end;
{-------------------------------------------------------------------------------}
function TMongoDocument.GetInArray: Boolean;
begin
Result := FBuilder.ParentType = TJSONCollectionBuilder.TParentType.Elements;
end;
{-------------------------------------------------------------------------------}
function TMongoDocument.GetElements: TJSONCollectionBuilder.TElements;
begin
Result := FBuilder.ParentArray;
end;
{-------------------------------------------------------------------------------}
function TMongoDocument.GetBuilder: TJSONObjectBuilder;
begin
if FBuilder.ParentType = TJSONCollectionBuilder.TParentType.None then
ErrorReadOnly;
Result := FBuilder;
end;
{-------------------------------------------------------------------------------}
function TMongoDocument.Iterator: TJSONIterator;
begin
Result := TIterator.Create(Self);
end;
{-------------------------------------------------------------------------------}
procedure TMongoDocument.Iterate(AFunc: TJSONIterator.TIterateFunc);
var
oIter: TJSONIterator;
begin
oIter := Iterator;
try
oIter.Iterate(AFunc);
finally
oIter.Free;
end;
end;
{-------------------------------------------------------------------------------}
procedure TMongoDocument.Assign(ASource: TMongoDocument);
begin
FBuilder.ExtendedJsonMode := ASource.FBuilder.ExtendedJsonMode;
FBuilder.DateTimeZoneHandling := ASource.FBuilder.DateTimeZoneHandling;
FBuilder
.Clear
.BeginObject
.AddPairs(ASource.FBuilder);
end;
{-------------------------------------------------------------------------------}
function TMongoDocument.Clear: TMongoDocument;
begin
FBuilder
.Clear
.BeginObject;
Result := Self;
end;
{-------------------------------------------------------------------------------}
procedure TMongoDocument.Close;
begin
while True do
case FBuilder.ParentType of
TJSONCollectionBuilder.TParentType.None: Break;
TJSONCollectionBuilder.TParentType.Elements: EndArray;
TJSONCollectionBuilder.TParentType.Pairs: EndObject;
end;
end;
{-------------------------------------------------------------------------------}
function TMongoDocument.Add(const AKey, AValue: String): TMongoDocument;
begin
case FBuilder.ParentType of
TJSONCollectionBuilder.TParentType.None: ErrorReadOnly;
TJSONCollectionBuilder.TParentType.Elements: Elements.Add(AValue);
TJSONCollectionBuilder.TParentType.Pairs: Pairs.Add(AKey, AValue);
end;
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoDocument.Add(const AKey: String; const AValue: Int32): TMongoDocument;
begin
case FBuilder.ParentType of
TJSONCollectionBuilder.TParentType.None: ErrorReadOnly;
TJSONCollectionBuilder.TParentType.Elements: Elements.Add(AValue);
TJSONCollectionBuilder.TParentType.Pairs: Pairs.Add(AKey, AValue);
end;
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoDocument.Add(const AKey: String; const AValue: Int64): TMongoDocument;
begin
case FBuilder.ParentType of
TJSONCollectionBuilder.TParentType.None: ErrorReadOnly;
TJSONCollectionBuilder.TParentType.Elements: Elements.Add(AValue);
TJSONCollectionBuilder.TParentType.Pairs: Pairs.Add(AKey, AValue);
end;
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoDocument.Add(const AKey: String; const AValue: Extended): TMongoDocument;
begin
case FBuilder.ParentType of
TJSONCollectionBuilder.TParentType.None: ErrorReadOnly;
TJSONCollectionBuilder.TParentType.Elements: Elements.Add(AValue);
TJSONCollectionBuilder.TParentType.Pairs: Pairs.Add(AKey, AValue);
end;
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoDocument.Add(const AKey: String; const AValue: Boolean): TMongoDocument;
begin
case FBuilder.ParentType of
TJSONCollectionBuilder.TParentType.None: ErrorReadOnly;
TJSONCollectionBuilder.TParentType.Elements: Elements.Add(AValue);
TJSONCollectionBuilder.TParentType.Pairs: Pairs.Add(AKey, AValue);
end;
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoDocument.Add(const AKey: String; const AValue: TDateTime): TMongoDocument;
begin
case FBuilder.ParentType of
TJSONCollectionBuilder.TParentType.None: ErrorReadOnly;
TJSONCollectionBuilder.TParentType.Elements: Elements.Add(AValue);
TJSONCollectionBuilder.TParentType.Pairs: Pairs.Add(AKey, AValue);
end;
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoDocument.Add(const AKey: String; const AValue: TBytes;
ABinaryType: TJsonBinaryType = TJsonBinaryType.Generic): TMongoDocument;
begin
case FBuilder.ParentType of
TJSONCollectionBuilder.TParentType.None: ErrorReadOnly;
TJSONCollectionBuilder.TParentType.Elements: Elements.Add(AValue, ABinaryType);
TJSONCollectionBuilder.TParentType.Pairs: Pairs.Add(AKey, AValue, ABinaryType);
end;
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoDocument.Add(const AKey: String; const AValue: TMongoOID): TMongoDocument;
begin
Result := Add(AKey, TJsonOid(AValue.Handle^));
end;
{-------------------------------------------------------------------------------}
function TMongoDocument.Add(const AKey: String; const AValue: TJsonOid): TMongoDocument;
begin
case FBuilder.ParentType of
TJSONCollectionBuilder.TParentType.None: ErrorReadOnly;
TJSONCollectionBuilder.TParentType.Elements: Elements.Add(AValue);
TJSONCollectionBuilder.TParentType.Pairs: Pairs.Add(AKey, AValue);
end;
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoDocument.Add(const AKey: String; const AValue: TJsonRegEx): TMongoDocument;
begin
case FBuilder.ParentType of
TJSONCollectionBuilder.TParentType.None: ErrorReadOnly;
TJSONCollectionBuilder.TParentType.Elements: Elements.Add(AValue);
TJSONCollectionBuilder.TParentType.Pairs: Pairs.Add(AKey, AValue);
end;
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoDocument.Add(const AKey: String; const AValue: TJsonDBRef): TMongoDocument;
begin
case FBuilder.ParentType of
TJSONCollectionBuilder.TParentType.None: ErrorReadOnly;
TJSONCollectionBuilder.TParentType.Elements: Elements.Add(AValue);
TJSONCollectionBuilder.TParentType.Pairs: Pairs.Add(AKey, AValue);
end;
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoDocument.Add(const AKey: String; const AValue: TJsonCodeWScope): TMongoDocument;
begin
case FBuilder.ParentType of
TJSONCollectionBuilder.TParentType.None: ErrorReadOnly;
TJSONCollectionBuilder.TParentType.Elements: Elements.Add(AValue);
TJSONCollectionBuilder.TParentType.Pairs: Pairs.Add(AKey, AValue);
end;
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoDocument.Add(const AKey: String; const AValue: TVarRec): TMongoDocument;
begin
case FBuilder.ParentType of
TJSONCollectionBuilder.TParentType.None: ErrorReadOnly;
TJSONCollectionBuilder.TParentType.Elements: Elements.Add(AValue);
TJSONCollectionBuilder.TParentType.Pairs: Pairs.Add(AKey, AValue);
end;
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoDocument.Add(const AKey: String; const AValues: array of const): TMongoDocument;
var
oElems: TJSONCollectionBuilder.TElements;
begin
oElems := nil;
case FBuilder.ParentType of
TJSONCollectionBuilder.TParentType.None: ErrorReadOnly;
TJSONCollectionBuilder.TParentType.Elements: oElems := Elements.BeginArray;
TJSONCollectionBuilder.TParentType.Pairs: oElems := Pairs.BeginArray(AKey);
end;
oElems.AddElements(AValues);
oElems.EndArray;
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoDocument.Add(const AKey: String; const AValue: Variant): TMongoDocument;
begin
case FBuilder.ParentType of
TJSONCollectionBuilder.TParentType.None: ErrorReadOnly;
TJSONCollectionBuilder.TParentType.Elements: Elements.Add(AValue);
TJSONCollectionBuilder.TParentType.Pairs: Pairs.Add(AKey, AValue);
end;
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoDocument.AddNull(const AKey: String): TMongoDocument;
begin
case FBuilder.ParentType of
TJSONCollectionBuilder.TParentType.None: ErrorReadOnly;
TJSONCollectionBuilder.TParentType.Elements: Elements.AddNull;
TJSONCollectionBuilder.TParentType.Pairs: Pairs.AddNull(AKey);
end;
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoDocument.AddUndefined(const AKey: String): TMongoDocument;
begin
case FBuilder.ParentType of
TJSONCollectionBuilder.TParentType.None: ErrorReadOnly;
TJSONCollectionBuilder.TParentType.Elements: Elements.AddUndefined;
TJSONCollectionBuilder.TParentType.Pairs: Pairs.AddUndefined(AKey);
end;
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoDocument.AddMinKey(const AKey: String): TMongoDocument;
begin
case FBuilder.ParentType of
TJSONCollectionBuilder.TParentType.None: ErrorReadOnly;
TJSONCollectionBuilder.TParentType.Elements: Elements.AddMinKey;
TJSONCollectionBuilder.TParentType.Pairs: Pairs.AddMinKey(AKey);
end;
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoDocument.AddMaxKey(const AKey: String): TMongoDocument;
begin
case FBuilder.ParentType of
TJSONCollectionBuilder.TParentType.None: ErrorReadOnly;
TJSONCollectionBuilder.TParentType.Elements: Elements.AddMaxKey;
TJSONCollectionBuilder.TParentType.Pairs: Pairs.AddMaxKey(AKey);
end;
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoDocument.BeginArray(const AKey: String): TMongoDocument;
begin
case FBuilder.ParentType of
TJSONCollectionBuilder.TParentType.None: ErrorReadOnly;
TJSONCollectionBuilder.TParentType.Elements: Elements.BeginArray;
TJSONCollectionBuilder.TParentType.Pairs: Pairs.BeginArray(AKey);
end;
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoDocument.EndArray: TMongoDocument;
begin
case FBuilder.ParentType of
TJSONCollectionBuilder.TParentType.None: ErrorReadOnly;
else Elements.EndArray;
end;
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoDocument.BeginObject(const AKey: String): TMongoDocument;
begin
case FBuilder.ParentType of
TJSONCollectionBuilder.TParentType.None: ErrorReadOnly;
TJSONCollectionBuilder.TParentType.Elements: Elements.BeginObject;
TJSONCollectionBuilder.TParentType.Pairs: Pairs.BeginObject(AKey);
end;
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoDocument.EndObject: TMongoDocument;
begin
case FBuilder.ParentType of
TJSONCollectionBuilder.TParentType.None: ErrorReadOnly;
else Pairs.EndObject;
end;
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoDocument.Append(const ADoc: TMongoDocument): TMongoDocument;
begin
case FBuilder.ParentType of
TJSONCollectionBuilder.TParentType.None: ErrorReadOnly;
TJSONCollectionBuilder.TParentType.Elements: Elements.AddElements(ADoc.FBuilder);
TJSONCollectionBuilder.TParentType.Pairs: Pairs.AddPairs(ADoc.FBuilder);
end;
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoDocument.Append(const AJSON: String): TMongoDocument;
begin
if AJSON <> '' then
case FBuilder.ParentType of
TJSONCollectionBuilder.TParentType.None: ErrorReadOnly;
TJSONCollectionBuilder.TParentType.Elements: Elements.AddElements(AJSON);
TJSONCollectionBuilder.TParentType.Pairs: Pairs.AddPairs(AJSON);
end;
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoDocument.Append(const AItems: array of const): TMongoDocument;
begin
case FBuilder.ParentType of
TJSONCollectionBuilder.TParentType.None: ErrorReadOnly;
TJSONCollectionBuilder.TParentType.Elements: Elements.AddElements(AItems);
TJSONCollectionBuilder.TParentType.Pairs: Pairs.AddPairs(AItems);
end;
Result := Self;
end;
{-------------------------------------------------------------------------------}
{ TMongoReadPreference }
{-------------------------------------------------------------------------------}
constructor TMongoReadPreference.Create(AEnv: TMongoEnv; AOwningObj: TObject;
AHandle: Pmongoc_read_prefs_t);
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_read_prefs_new, ['read_mode', MONGOC_READ_PRIMARY]);
end;
{$ENDIF}
begin
inherited Create(AEnv, AOwningObj);
if AHandle = nil then begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
FHandle := CLib.Fmongoc_read_prefs_new(MONGOC_READ_PRIMARY);
end
else begin
FHandle := AHandle;
FOwnHandle := False;
end;
FTags := TMongoDocument.Create(AEnv, AOwningObj, Self);
end;
{-------------------------------------------------------------------------------}
destructor TMongoReadPreference.Destroy;
begin
FDFreeAndNil(FTags);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
procedure TMongoReadPreference.InternalFreeHandle;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_read_prefs_destroy, ['read_prefs', Handle]);
end;
{$ENDIF}
begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
CLib.Fmongoc_read_prefs_destroy(Handle);
end;
{-------------------------------------------------------------------------------}
procedure TMongoReadPreference.Assign(ASource: TMongoReadPreference);
begin
Mode := ASource.Mode;
Tags := ASource.Tags;
end;
{-------------------------------------------------------------------------------}
function TMongoReadPreference.GetMode: TReadMode;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_read_prefs_get_mode, ['read_prefs', Handle]);
end;
{$ENDIF}
begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
case CLib.Fmongoc_read_prefs_get_mode(Handle) of
MONGOC_READ_PRIMARY: Result := TReadMode.Primary;
MONGOC_READ_SECONDARY: Result := TReadMode.Secondary;
MONGOC_READ_PRIMARY_PREFERRED: Result := TReadMode.PrimaryPreferred;
MONGOC_READ_SECONDARY_PREFERRED: Result := TReadMode.SecondaryPreferred;
MONGOC_READ_NEAREST: Result := TReadMode.Nearest;
else Result := TReadMode.Primary;
end;
end;
{-------------------------------------------------------------------------------}
procedure TMongoReadPreference.SetMode(const AValue: TReadMode);
var
iMode: Cardinal;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_read_prefs_set_mode, ['read_prefs', Handle, 'mode', iMode]);
end;
{$ENDIF}
begin
case AValue of
TReadMode.Primary: iMode := MONGOC_READ_PRIMARY;
TReadMode.Secondary: iMode := MONGOC_READ_SECONDARY;
TReadMode.PrimaryPreferred: iMode := MONGOC_READ_PRIMARY_PREFERRED;
TReadMode.SecondaryPreferred: iMode := MONGOC_READ_SECONDARY_PREFERRED;
TReadMode.Nearest: iMode := MONGOC_READ_NEAREST;
else iMode := MONGOC_READ_PRIMARY;
end;
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
CLib.Fmongoc_read_prefs_set_mode(Handle, iMode);
end;
{-------------------------------------------------------------------------------}
function TMongoReadPreference.GetTags: TMongoDocument;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_read_prefs_get_tags, ['read_prefs', Handle]);
end;
{$ENDIF}
begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
FTags.AsReadHandle := CLib.Fmongoc_read_prefs_get_tags(Handle);
Result := FTags;
end;
{-------------------------------------------------------------------------------}
procedure TMongoReadPreference.SetTags(const AValue: TMongoDocument);
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_read_prefs_set_tags, ['read_prefs', Handle, 'tags', AValue.AsJSON]);
end;
{$ENDIF}
begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
CLib.Fmongoc_read_prefs_set_tags(Handle, AValue.AsReadHandle);
end;
{-------------------------------------------------------------------------------}
procedure TMongoReadPreference.AddTag(ATag: TMongoDocument);
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_read_prefs_add_tag, ['read_prefs', Handle, 'tags', ATag.AsJSON]);
end;
{$ENDIF}
begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
CLib.Fmongoc_read_prefs_add_tag(Handle, ATag.AsReadHandle);
end;
{-------------------------------------------------------------------------------}
{ TMongoWriteConcern }
{-------------------------------------------------------------------------------}
constructor TMongoWriteConcern.Create(AEnv: TMongoEnv; AOwningObj: TObject;
AHandle: Pmongoc_write_concern_t);
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_write_concern_new, []);
end;
{$ENDIF}
begin
inherited Create(AEnv, AOwningObj);
if AHandle = nil then begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
FHandle := CLib.Fmongoc_write_concern_new();
end
else begin
FHandle := AHandle;
FOwnHandle := False;
end;
end;
{-------------------------------------------------------------------------------}
procedure TMongoWriteConcern.InternalFreeHandle;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_write_concern_destroy, ['write_concern', Handle]);
end;
{$ENDIF}
begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
CLib.Fmongoc_write_concern_destroy(Handle);
end;
{-------------------------------------------------------------------------------}
procedure TMongoWriteConcern.Assign(ASource: TMongoWriteConcern);
begin
Level := ASource.Level;
Fsync := ASource.Fsync;
Journal := ASource.Journal;
Majority := ASource.Majority;
Tag := ASource.Tag;
Timeout := ASource.Timeout;
end;
{-------------------------------------------------------------------------------}
function TMongoWriteConcern.GetLevel: TWriteLevel;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_write_concern_get_w, ['write_concern', Handle]);
end;
{$ENDIF}
begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
case CLib.Fmongoc_write_concern_get_w(Handle) of
MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED: Result := TWriteLevel.Unacknowledged;
MONGOC_WRITE_CONCERN_W_ERRORS_IGNORED: Result := TWriteLevel.ErrorsIgnored;
MONGOC_WRITE_CONCERN_W_DEFAULT: Result := TWriteLevel.Default;
MONGOC_WRITE_CONCERN_W_MAJORITY: Result := TWriteLevel.Majority;
else Result := TWriteLevel.Default;
end;
end;
{-------------------------------------------------------------------------------}
procedure TMongoWriteConcern.SetLevel(const AValue: TWriteLevel);
var
iMode: Integer;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_write_concern_set_w, ['write_concern', Handle, 'w', iMode]);
end;
{$ENDIF}
begin
case AValue of
TWriteLevel.Default: iMode := MONGOC_WRITE_CONCERN_W_DEFAULT;
TWriteLevel.ErrorsIgnored: iMode := MONGOC_WRITE_CONCERN_W_ERRORS_IGNORED;
TWriteLevel.Unacknowledged: iMode := MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED;
TWriteLevel.Majority: iMode := MONGOC_WRITE_CONCERN_W_MAJORITY;
else iMode := MONGOC_WRITE_CONCERN_W_DEFAULT;
end;
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
CLib.Fmongoc_write_concern_set_w(Handle, iMode);
end;
{-------------------------------------------------------------------------------}
function TMongoWriteConcern.GetFsync: Boolean;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_write_concern_get_fsync, ['write_concern', Handle]);
end;
{$ENDIF}
begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
Result := CLib.Fmongoc_write_concern_get_fsync(Handle);
end;
{-------------------------------------------------------------------------------}
procedure TMongoWriteConcern.SetFsync(const AValue: Boolean);
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_write_concern_set_fsync, ['write_concern', Handle, 'fsync_', AValue]);
end;
{$ENDIF}
begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
CLib.Fmongoc_write_concern_set_fsync(Handle, AValue);
end;
{-------------------------------------------------------------------------------}
function TMongoWriteConcern.GetJournal: Boolean;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_write_concern_get_journal, ['write_concern', Handle]);
end;
{$ENDIF}
begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
Result := CLib.Fmongoc_write_concern_get_journal(Handle);
end;
{-------------------------------------------------------------------------------}
procedure TMongoWriteConcern.SetJournal(const AValue: Boolean);
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_write_concern_set_journal, ['write_concern', Handle, 'journal', AValue]);
end;
{$ENDIF}
begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
CLib.Fmongoc_write_concern_set_journal(Handle, AValue);
end;
{-------------------------------------------------------------------------------}
function TMongoWriteConcern.GetMajority: Integer;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_write_concern_get_wmajority, ['write_concern', Handle]);
end;
{$ENDIF}
begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
Result := CLib.Fmongoc_write_concern_get_wmajority(Handle);
end;
{-------------------------------------------------------------------------------}
procedure TMongoWriteConcern.SetMajority(const AValue: Integer);
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_write_concern_set_wmajority, ['write_concern', Handle,
'wtimeout_msec', AValue]);
end;
{$ENDIF}
begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
CLib.Fmongoc_write_concern_set_wmajority(Handle, AValue);
end;
{-------------------------------------------------------------------------------}
function TMongoWriteConcern.GetTag: String;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_write_concern_get_wtag, ['write_concern', Handle]);
end;
{$ENDIF}
begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
Result := Env.UTF8.Decode(Pointer(CLib.Fmongoc_write_concern_get_wtag(Handle)));
end;
{-------------------------------------------------------------------------------}
procedure TMongoWriteConcern.SetTag(const AValue: String);
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_write_concern_set_wtag, ['write_concern', Handle, 'tag', AValue]);
end;
{$ENDIF}
begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
CLib.Fmongoc_write_concern_set_wtag(Handle, PFDAnsiString(PByte(Env.UTF8.Encode(AValue))));
end;
{-------------------------------------------------------------------------------}
function TMongoWriteConcern.GetTimeout: Integer;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_write_concern_get_wtimeout, ['write_concern', Handle]);
end;
{$ENDIF}
begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
Result := CLib.Fmongoc_write_concern_get_wtimeout(Handle);
end;
{-------------------------------------------------------------------------------}
procedure TMongoWriteConcern.SetTimeout(const AValue: Integer);
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_write_concern_set_wtimeout, ['write_concern', Handle,
'wtimeout_msec', AValue]);
end;
{$ENDIF}
begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
CLib.Fmongoc_write_concern_set_wtimeout(Handle, AValue);
end;
{-------------------------------------------------------------------------------}
{ TMongoExpression }
{-------------------------------------------------------------------------------}
constructor TMongoExpression<T>.Create(AEnv: TMongoEnv; AOwningObj: TObject; AParentObj: T);
begin
inherited Create;
FDoc := TMongoDocument.Create(AEnv, AOwningObj, AParentObj);
end;
{-------------------------------------------------------------------------------}
constructor TMongoExpression<T>.Create(AEnv: TMongoEnv);
begin
Create(AEnv, nil, nil);
end;
{-------------------------------------------------------------------------------}
destructor TMongoExpression<T>.Destroy;
begin
FDFreeAndNil(FDoc);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
function TMongoExpression<T>.GetAsJSON: String;
begin
Result := FDoc.AsJSON;
end;
{-------------------------------------------------------------------------------}
procedure TMongoExpression<T>.SetAsJSON(const AValue: String);
begin
FDoc.AsJSON := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TMongoExpression<T>.Assign(ASource: TMongoExpression<T>);
begin
FDoc.Assign(ASource.FDoc);
end;
{-------------------------------------------------------------------------------}
function TMongoExpression<T>.Clear: TMongoExpression<T>;
begin
FDoc.Clear;
Result := Self;
end;
{-------------------------------------------------------------------------------}
procedure TMongoExpression<T>.Close;
begin
FDoc.Close;
end;
{-------------------------------------------------------------------------------}
function TMongoExpression<T>.Exp(const AField, AExpression: String): TMongoExpression<T>;
begin
Result := Append('{"' + AField + '":' + AExpression + '}');
end;
{-------------------------------------------------------------------------------}
function TMongoExpression<T>.Builder: TJSONObjectBuilder;
begin
Result := FDoc.Builder;
end;
{-------------------------------------------------------------------------------}
function TMongoExpression<T>.Iterator: TJSONIterator;
begin
Result := FDoc.Iterator;
end;
{-------------------------------------------------------------------------------}
function TMongoExpression<T>.Add(const AKey, AValue: String): TMongoExpression<T>;
begin
FDoc.Add(AKey, AValue);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoExpression<T>.Add(const AKey: String; const AValue: Int32): TMongoExpression<T>;
begin
FDoc.Add(AKey, AValue);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoExpression<T>.Add(const AKey: String; const AValue: Int64): TMongoExpression<T>;
begin
FDoc.Add(AKey, AValue);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoExpression<T>.Add(const AKey: String; const AValue: Extended): TMongoExpression<T>;
begin
FDoc.Add(AKey, AValue);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoExpression<T>.Add(const AKey: String; const AValue: Boolean): TMongoExpression<T>;
begin
FDoc.Add(AKey, AValue);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoExpression<T>.Add(const AKey: String; const AValue: TDateTime): TMongoExpression<T>;
begin
FDoc.Add(AKey, AValue);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoExpression<T>.Add(const AKey: String; const AValue: TBytes;
ABinaryType: TJsonBinaryType = TJsonBinaryType.Generic): TMongoExpression<T>;
begin
FDoc.Add(AKey, AValue, ABinaryType);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoExpression<T>.Add(const AKey: String; const AValue: TMongoOID): TMongoExpression<T>;
begin
FDoc.Add(AKey, AValue);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoExpression<T>.Add(const AKey: String; const AValue: TJsonOid): TMongoExpression<T>;
begin
FDoc.Add(AKey, AValue);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoExpression<T>.Add(const AKey: String; const AValue: TJsonRegEx): TMongoExpression<T>;
begin
FDoc.Add(AKey, AValue);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoExpression<T>.Add(const AKey: String; const AValue: TJsonDBRef): TMongoExpression<T>;
begin
FDoc.Add(AKey, AValue);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoExpression<T>.Add(const AKey: String; const AValue: TJsonCodeWScope): TMongoExpression<T>;
begin
FDoc.Add(AKey, AValue);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoExpression<T>.Add(const AKey: String; const AValues: array of const): TMongoExpression<T>;
begin
FDoc.Add(AKey, AValues);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoExpression<T>.Add(const AKey: String; const AValue: Variant): TMongoExpression<T>;
begin
FDoc.Add(AKey, AValue);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoExpression<T>.Add(const AKey: String; const AValue: TVarRec): TMongoExpression<T>;
begin
FDoc.Add(AKey, AValue);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoExpression<T>.AddNull(const AKey: String): TMongoExpression<T>;
begin
FDoc.AddNull(AKey);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoExpression<T>.AddUndefined(const AKey: String): TMongoExpression<T>;
begin
FDoc.AddUndefined(AKey);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoExpression<T>.AddMaxKey(const AKey: String): TMongoExpression<T>;
begin
FDoc.AddMaxKey(AKey);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoExpression<T>.AddMinKey(const AKey: String): TMongoExpression<T>;
begin
FDoc.AddMinKey(AKey);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoExpression<T>.Append(const AItems: array of const): TMongoExpression<T>;
begin
FDoc.Append(AItems);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoExpression<T>.Append(const AJSON: String): TMongoExpression<T>;
begin
FDoc.Append(AJSON);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoExpression<T>.Append(const ADoc: TMongoDocument): TMongoExpression<T>;
begin
FDoc.Append(ADoc);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoExpression<T>.GetInArray: Boolean;
begin
Result := FDoc.InArray;
end;
{-------------------------------------------------------------------------------}
function TMongoExpression<T>.BeginArray(const AKey: String): TMongoExpression<T>;
begin
FDoc.BeginArray(AKey);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoExpression<T>.EndArray: TMongoExpression<T>;
begin
FDoc.EndArray;
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoExpression<T>.GetInObject: Boolean;
begin
Result := FDoc.InObject;
end;
{-------------------------------------------------------------------------------}
function TMongoExpression<T>.BeginObject(const AKey: String): TMongoExpression<T>;
begin
FDoc.BeginObject(AKey);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoExpression<T>.EndObject: TMongoExpression<T>;
begin
FDoc.EndObject;
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoExpression<T>.&End: T;
begin
Result := FDoc.FParentObj as T;
end;
{-------------------------------------------------------------------------------}
{ TMongoPipeline.TOperation }
{-------------------------------------------------------------------------------}
constructor TMongoPipeline.TOperation.Create(APipeline: TMongoPipeline);
begin
inherited Create;
FPipeline := APipeline;
FWriter := TMongoDocument.Create(APipeline.FEnv, APipeline.FOwningObj, APipeline);
end;
{-------------------------------------------------------------------------------}
destructor TMongoPipeline.TOperation.Destroy;
begin
FDFreeAndNil(FWriter);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
class function TMongoPipeline.TOperation.GetInline: Boolean;
begin
Result := False;
end;
{-------------------------------------------------------------------------------}
function TMongoPipeline.TOperation.&End: TMongoPipeline;
begin
Result := FPipeline;
end;
{-------------------------------------------------------------------------------}
{ TMongoPipeline.TInlineOperation }
{-------------------------------------------------------------------------------}
class function TMongoPipeline.TInlineOperation.GetInline: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
procedure TMongoPipeline.TInlineOperation.SetValue(const AValue: Variant);
begin
Writer.Clear;
Writer.Add(GetOperator, AValue);
end;
{-------------------------------------------------------------------------------}
{ TMongoPipeline.TLimit }
{-------------------------------------------------------------------------------}
class function TMongoPipeline.TLimit.GetOperator: String;
begin
Result := '$limit';
end;
{-------------------------------------------------------------------------------}
{ TMongoPipeline.TSkip }
{-------------------------------------------------------------------------------}
class function TMongoPipeline.TSkip.GetOperator: String;
begin
Result := '$skip';
end;
{-------------------------------------------------------------------------------}
{ TMongoPipeline.TSample }
{-------------------------------------------------------------------------------}
class function TMongoPipeline.TSample.GetOperator: String;
begin
Result := '$sample';
end;
{-------------------------------------------------------------------------------}
procedure TMongoPipeline.TSample.SetValue(const AValue: Integer);
begin
FWriter.Clear;
FWriter.Add('size', AValue);
end;
{-------------------------------------------------------------------------------}
{ TMongoPipeline.TUnwind }
{-------------------------------------------------------------------------------}
class function TMongoPipeline.TUnwind.GetOperator: String;
begin
Result := '$unwind';
end;
{-------------------------------------------------------------------------------}
{ TMongoPipeline.TLookup }
{-------------------------------------------------------------------------------}
class function TMongoPipeline.TLookup.GetOperator: String;
begin
Result := '$lookup';
end;
{-------------------------------------------------------------------------------}
procedure TMongoPipeline.TLookup.Setup(const AFrom, ALocalField, AForeignField, AAs: String);
begin
FWriter.Clear;
FWriter.Add('from', AFrom);
FWriter.Add('localField', ALocalField);
FWriter.Add('foreignField', AForeignField);
FWriter.Add('as', AAs);
end;
{-------------------------------------------------------------------------------}
{ TMongoPipeline.TOut }
{-------------------------------------------------------------------------------}
class function TMongoPipeline.TOut.GetOperator: String;
begin
Result := '$out';
end;
{-------------------------------------------------------------------------------}
{ TMongoPipeline.TIndexStats }
{-------------------------------------------------------------------------------}
class function TMongoPipeline.TIndexStats.GetOperator: String;
begin
Result := '$indexStats';
end;
{-------------------------------------------------------------------------------}
procedure TMongoPipeline.TIndexStats.Setup;
begin
FWriter.Clear;
end;
{-------------------------------------------------------------------------------}
{ TMongoPipeline.TProjection }
{-------------------------------------------------------------------------------}
class function TMongoPipeline.TProjection.GetOperator: String;
begin
Result := '$project';
end;
{-------------------------------------------------------------------------------}
function TMongoPipeline.TProjection.Clear: TProjection;
begin
FWriter.Clear;
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoPipeline.TProjection.Append(const AJSON: String): TProjection;
begin
FWriter.Append(AJSON);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoPipeline.TProjection.NoID: TProjection;
begin
FWriter.Add('_id', False);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoPipeline.TProjection.Field(const AField: String): TProjection;
begin
FWriter.Add(AField, True);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoPipeline.TProjection.FieldBegin(const AField: String): TProjection;
begin
FWriter.BeginObject(AField);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoPipeline.TProjection.FieldEnd: TProjection;
begin
FWriter.EndObject;
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoPipeline.TProjection.Exp(const AField, AExpression: String): TProjection;
begin
FWriter.Append('{"' + AField + '":' + AExpression + '}');
Result := Self;
end;
{-------------------------------------------------------------------------------}
{ TMongoPipeline.TSort }
{-------------------------------------------------------------------------------}
class function TMongoPipeline.TSort.GetOperator: String;
begin
Result := '$sort';
end;
{-------------------------------------------------------------------------------}
function TMongoPipeline.TSort.Clear: TSort;
begin
FWriter.Clear;
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoPipeline.TSort.Append(const AJSON: String): TSort;
begin
FWriter.Append(AJSON);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoPipeline.TSort.Field(const AName: String; AAscending: Boolean = True): TSort;
var
iVal: Integer;
begin
if AAscending then
iVal := 1
else
iVal := -1;
FWriter.Add(AName, iVal);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoPipeline.TSort.TextScore(const AName: String): TSort;
begin
FWriter.BeginObject(AName);
FWriter.Add('$meta', 'textScore');
FWriter.EndObject;
Result := Self;
end;
{-------------------------------------------------------------------------------}
{ TMongoPipeline.TGeoNear.TQuery }
{-------------------------------------------------------------------------------}
function TMongoPipeline.TGeoNear.TQuery.&End: TGeoNear;
begin
Result := FDoc.FParentObj as TGeoNear;
Result.FWriter.BeginObject('query');
Result.FWriter.Append(FDoc);
Result.FWriter.EndObject;
end;
{-------------------------------------------------------------------------------}
{ TMongoPipeline.TGeoNear }
{-------------------------------------------------------------------------------}
destructor TMongoPipeline.TGeoNear.Destroy;
begin
FDFreeAndNil(FQuery);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
class function TMongoPipeline.TGeoNear.GetOperator: String;
begin
Result := '$geoNear';
end;
{-------------------------------------------------------------------------------}
function TMongoPipeline.TGeoNear.Clear: TGeoNear;
begin
FWriter.Clear;
if FQuery <> nil then
FQuery.Clear;
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoPipeline.TGeoNear.Append(const AJSON: String): TGeoNear;
begin
FWriter.Append(AJSON);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoPipeline.TGeoNear.Near(ALatitude, ALongitude: Extended): TGeoNear;
begin
FWriter.BeginObject('near');
FWriter.Add('type', 'Point');
FWriter.BeginArray('coordinates');
FWriter.Add('0', ALatitude);
FWriter.Add('1', ALongitude);
FWriter.EndArray;
FWriter.EndObject;
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoPipeline.TGeoNear.Spherical(AValue: Boolean): TGeoNear;
begin
FWriter.Add('spherical', AValue);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoPipeline.TGeoNear.Limit(AValue: Integer): TGeoNear;
begin
FWriter.Add('limit', AValue);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoPipeline.TGeoNear.Distance(AMin, AMax: Integer): TGeoNear;
begin
if AMin >= 0 then
FWriter.Add('minDistance', AMin);
if AMax >= 0 then
FWriter.Add('maxDistance', AMax);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoPipeline.TGeoNear.Output(const ADistField, ALocsField: String): TGeoNear;
begin
FWriter.Add('distanceField', ADistField);
if ALocsField <> '' then
FWriter.Add('includeLocs', ALocsField);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoPipeline.TGeoNear.Query(const AJSON: String): TQuery;
begin
if FQuery = nil then
FQuery := TQuery.Create(FPipeline.FEnv, FPipeline.FOwningObj, Self);
Result := FQuery;
end;
{-------------------------------------------------------------------------------}
{ TMongoPipeline.TOptions }
{-------------------------------------------------------------------------------}
procedure TMongoPipeline.TOptions.Save(AWriter: TMongoDocument);
begin
AWriter.Clear;
if Explain then
AWriter.Add('explain', True);
if AllowDiskUse then
AWriter.Add('allowDiskUse', True);
if UseCursor then begin
AWriter.BeginObject('cursor');
AWriter.Add('batchSize', BatchSize);
AWriter.EndObject;
end;
if MaxTimeMS > 0 then
AWriter.Add('maxTimeMS', MaxTimeMS);
end;
{-------------------------------------------------------------------------------}
procedure TMongoPipeline.TOptions.Assign(AOptions: TOptions);
begin
Explain := AOptions.Explain;
AllowDiskUse := AOptions.AllowDiskUse;
UseCursor := AOptions.UseCursor;
BatchSize := AOptions.BatchSize;
MaxTimeMS := AOptions.MaxTimeMS;
end;
{-------------------------------------------------------------------------------}
{ TMongoPipeline }
{-------------------------------------------------------------------------------}
constructor TMongoPipeline.Create(AEnv: TMongoEnv);
begin
inherited Create;
FEnv := AEnv;
FOwningObj := AEnv.OwningObj;
FOperations := TFDStringList.Create(True);
end;
{-------------------------------------------------------------------------------}
constructor TMongoPipeline.Create(AEnv: TMongoEnv; AOwningObj: TObject;
AGetCursor: TMongoPipeline.TGetCursor);
begin
Create(AEnv);
FOwningObj := AOwningObj;
FGetCursor := AGetCursor;
end;
{-------------------------------------------------------------------------------}
destructor TMongoPipeline.Destroy;
begin
FDFreeAndNil(FPWriter);
FDFreeAndNil(FOWriter);
FDFreeAndNil(FOptions);
FDFreeAndNil(FOperations);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
function TMongoPipeline.GetOperation(AType: TOperationClass;
const ATypeName: String; const AJSON: String): TObject;
var
sName: String;
begin
if AType <> nil then begin
sName := AType.GetOperator;
Result := TOperationClass(AType).Create(Self);
end
else begin
sName := ATypeName;
Result := TExpression.Create(FEnv, FOwningObj, Self);
end;
FOperations.AddObject(sName, Result);
if AJSON <> '' then
if Result is TExpression then
TExpression(Result).Append(AJSON)
else if Result is TOperation then
TOperation(Result).Writer.Append(AJSON);
end;
{-------------------------------------------------------------------------------}
function TMongoPipeline.GetFinalPipelineBSON: TMongoDocument;
var
i: Integer;
oOper: TOperation;
oWrt: TMongoDocument;
begin
if FPWriter = nil then
FPWriter := TMongoDocument.Create(FEnv, FOwningObj, Self);
FPWriter.Clear;
FPWriter.BeginArray('pipeline');
for i := 0 to FOperations.Count - 1 do begin
if FOperations.Objects[i] is TOperation then begin
oOper := TOperation(FOperations.Objects[i]);
oWrt := oOper.Writer;
end
else begin
oOper := nil;
oWrt := TExpression(FOperations.Objects[i]).FDoc;
end;
FPWriter.BeginObject(IntToStr(i));
if (oOper = nil) or not oOper.GetInline then
FPWriter.BeginObject(FOperations[i]);
FPWriter.Append(oWrt);
if (oOper = nil) or not oOper.GetInline then
FPWriter.EndObject;
FPWriter.EndObject;
end;
FPWriter.EndArray;
Result := FPWriter;
end;
{-------------------------------------------------------------------------------}
function TMongoPipeline.GetFinalOptionsBSON: TMongoDocument;
begin
if FOptions <> nil then begin
if FOWriter = nil then
FOWriter := TMongoDocument.Create(FEnv, FOwningObj, Self);
FOWriter.Clear;
FOptions.Save(FOWriter);
end;
Result := FOWriter;
end;
{-------------------------------------------------------------------------------}
function TMongoPipeline.Project(const AJSON: String = ''): TProjection;
begin
Result := TProjection(GetOperation(TProjection, '', AJSON));
end;
{-------------------------------------------------------------------------------}
function TMongoPipeline.Match(const AJSON: String = ''): TExpression;
begin
Result := TExpression(GetOperation(nil, '$match', AJSON));
end;
{-------------------------------------------------------------------------------}
function TMongoPipeline.Redact(const AJSON: String = ''): TExpression;
begin
Result := TExpression(GetOperation(nil, '$redact', AJSON));
end;
{-------------------------------------------------------------------------------}
function TMongoPipeline.Limit(const AValue: Integer): TMongoPipeline;
begin
TLimit(GetOperation(TLimit, '', '')).SetValue(AValue);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoPipeline.Skip(const AValue: Integer): TMongoPipeline;
begin
TSkip(GetOperation(TSkip, '', '')).SetValue(AValue);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoPipeline.Unwind(const APath: String): TMongoPipeline;
begin
TUnwind(GetOperation(TUnwind, '', '')).SetValue(APath);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoPipeline.Group(const AJSON: String = ''): TExpression;
begin
Result := TExpression(GetOperation(nil, '$group', AJSON));
end;
{-------------------------------------------------------------------------------}
function TMongoPipeline.Sample(const AValue: Integer): TMongoPipeline;
begin
TSample(GetOperation(TSample, '', '')).SetValue(AValue);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoPipeline.Sort(const AJSON: String = ''): TSort;
begin
Result := TSort(GetOperation(TSort, '', AJSON));
end;
{-------------------------------------------------------------------------------}
function TMongoPipeline.GeoNear(const AJSON: String): TGeoNear;
begin
Result := TGeoNear(GetOperation(TGeoNear, '', AJSON));
end;
{-------------------------------------------------------------------------------}
function TMongoPipeline.Lookup(const AFrom, ALocalField, AForeignField,
AAs: String): TMongoPipeline;
begin
TLookup(GetOperation(TLookup, '', '')).Setup(AFrom, ALocalField, AForeignField, AAs);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoPipeline.&Out(const ACollectionName: String): TMongoPipeline;
begin
TOut(GetOperation(TOut, '', '')).SetValue(ACollectionName);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoPipeline.IndexStats(): TMongoPipeline;
begin
TIndexStats(GetOperation(TIndexStats, '', '')).Setup;
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoPipeline.Stage(const AName, AJSON: String): TExpression;
begin
Result := TExpression(GetOperation(nil, AName, AJSON));
end;
{-------------------------------------------------------------------------------}
function TMongoPipeline.GetOptions: TOptions;
begin
if FOptions = nil then
FOptions := TOptions.Create;
Result := FOptions;
end;
{-------------------------------------------------------------------------------}
function TMongoPipeline.GetCursor: IMongoCursor;
begin
if not Assigned(FGetCursor) then
FDException(FOwningObj, [S_FD_LPhys, FEnv.CLib.DriverID],
er_FD_MongoCursorError, ['Aggregate']);
Result := FGetCursor(Self);
end;
{-------------------------------------------------------------------------------}
function TMongoPipeline.Open: IMongoCursor;
begin
Result := Self;
end;
{-------------------------------------------------------------------------------}
{ TMongoQuery.TOperation }
{-------------------------------------------------------------------------------}
constructor TMongoQuery.TOperation.Create(AQuery: TMongoQuery);
begin
inherited Create;
FQuery := AQuery;
FWriter := TMongoDocument.Create(FQuery.FEnv, FQuery.FOwningObj, AQuery);
end;
{-------------------------------------------------------------------------------}
destructor TMongoQuery.TOperation.Destroy;
begin
FDFreeAndNil(FWriter);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
function TMongoQuery.TOperation.&End: TMongoQuery;
begin
Result := FQuery;
end;
{-------------------------------------------------------------------------------}
{ TMongoQuery.TProjection }
{-------------------------------------------------------------------------------}
function TMongoQuery.TProjection.Clear: TProjection;
begin
FWriter.Clear;
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoQuery.TProjection.Append(const AJSON: String): TProjection;
begin
FWriter.Append(AJSON);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoQuery.TProjection.NoID: TProjection;
begin
FWriter.Add('_id', False);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoQuery.TProjection.Field(const AField: String; AInclude: Boolean = True): TProjection;
begin
FWriter.Add(AField, AInclude);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoQuery.TProjection.Include(const AFields: array of String): TProjection;
var
i: Integer;
begin
for i := Low(AFields) to High(AFields) do
Field(AFields[i], True);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoQuery.TProjection.Exclude(const AFields: array of String): TProjection;
var
i: Integer;
begin
for i := Low(AFields) to High(AFields) do
Field(AFields[i], False);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoQuery.TProjection.TextScore(const AField: String): TProjection;
begin
FWriter.BeginObject(AField);
FWriter.Add('$meta', 'textScore');
FWriter.EndObject;
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoQuery.TProjection.Slice(const AField: String; ACount: Integer): TProjection;
begin
FWriter.BeginObject(AField);
FWriter.Add('$slice', ACount);
FWriter.EndObject;
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoQuery.TProjection.Slice(const AField: String; ASkip, ACount: Integer): TProjection;
begin
FWriter.BeginObject(AField);
FWriter.BeginArray('$slice');
FWriter.Add('0', ASkip);
FWriter.Add('1', ACount);
FWriter.EndArray;
FWriter.EndObject;
Result := Self;
end;
{-------------------------------------------------------------------------------}
{ TMongoQuery.TSort }
{-------------------------------------------------------------------------------}
function TMongoQuery.TSort.Clear: TSort;
begin
FWriter.Clear;
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoQuery.TSort.Append(const AJSON: String): TSort;
begin
FWriter.Append(AJSON);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoQuery.TSort.Field(const AName: String; AAscending: Boolean): TSort;
var
iVal: Integer;
begin
if AAscending then
iVal := 1
else
iVal := -1;
FWriter.Add(AName, iVal);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoQuery.TSort.Ascending(const AFields: array of String): TSort;
var
i: Integer;
begin
for i := Low(AFields) to High(AFields) do
Field(AFields[i], True);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoQuery.TSort.Descending(const AFields: array of String): TSort;
var
i: Integer;
begin
for i := Low(AFields) to High(AFields) do
Field(AFields[i], False);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoQuery.TSort.TextScore(const AName: String): TSort;
begin
FWriter.BeginObject(AName);
FWriter.Add('$meta', 'textScore');
FWriter.EndObject;
Result := Self;
end;
{-------------------------------------------------------------------------------}
{ TMongoQuery.TOptions }
{-------------------------------------------------------------------------------}
procedure TMongoQuery.TOptions.Save(AWriter: TMongoDocument);
begin
if Comment <> '' then
AWriter.Add('$comment', Comment);
if Explain then
AWriter.Add('$explain', True);
if Hint <> '' then
AWriter.Append('{"$hint":' + Hint + '}');
if MaxScan <> 0 then
AWriter.Add('$maxScan', MaxScan);
if MaxTimeMS <> 0 then
AWriter.Add('$maxTimeMS', MaxTimeMS);
if ReturnKey then
AWriter.Add('$returnKey', True);
if Snapshot then
AWriter.Add('$snapshot', True);
end;
{-------------------------------------------------------------------------------}
procedure TMongoQuery.TOptions.Assign(AOptions: TOptions);
begin
Comment := AOptions.Comment;
Explain := AOptions.Explain;
Hint := AOptions.Hint;
MaxScan := AOptions.MaxScan;
MaxTimeMS := AOptions.MaxTimeMS;
ReturnKey := AOptions.ReturnKey;
Snapshot := AOptions.Snapshot;
BatchSize := AOptions.BatchSize;
end;
{-------------------------------------------------------------------------------}
{ TMongoQuery }
{-------------------------------------------------------------------------------}
constructor TMongoQuery.Create(AEnv: TMongoEnv);
begin
inherited Create;
FEnv := AEnv;
FOwningObj := AEnv.OwningObj;
FQWriter := TMongoDocument.Create(FEnv, Self, Self);
FPWriter := TMongoDocument.Create(FEnv, Self, Self);
end;
{-------------------------------------------------------------------------------}
constructor TMongoQuery.Create(AEnv: TMongoEnv; AOwningObj: TObject;
AGetCursor: TGetCursor);
begin
Create(AEnv);
FOwningObj := AOwningObj;
FQWriter.FOwningObj := AOwningObj;
FPWriter.FOwningObj := AOwningObj;
FGetCursor := AGetCursor;
end;
{-------------------------------------------------------------------------------}
constructor TMongoQuery.Create(AEnv: TMongoEnv; AOwningObj: TObject;
AGetCount: TGetCount);
begin
Create(AEnv);
FOwningObj := AOwningObj;
FQWriter.FOwningObj := AOwningObj;
FPWriter.FOwningObj := AOwningObj;
FGetCount := AGetCount;
end;
{-------------------------------------------------------------------------------}
destructor TMongoQuery.Destroy;
begin
FDFreeAndNil(FProject);
FDFreeAndNil(FMatch);
FDFreeAndNil(FSort);
FDFreeAndNil(FOptions);
FDFreeAndNil(FPWriter);
FDFreeAndNil(FQWriter);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
function TMongoQuery.Project(const AJSON: String = ''): TProjection;
begin
if FProject = nil then
FProject := TProjection.Create(Self);
Result := FProject;
if AJSON <> '' then
Result.Writer.Append(AJSON);
end;
{-------------------------------------------------------------------------------}
function TMongoQuery.Match(const AJSON: String = ''): TExpression;
begin
if FMatch = nil then
FMatch := TExpression.Create(FEnv, FOwningObj, Self);
Result := FMatch;
if AJSON <> '' then
Result.Append(AJSON);
end;
{-------------------------------------------------------------------------------}
function TMongoQuery.Sort(const AJSON: String = ''): TSort;
begin
if FSort = nil then
FSort := TSort.Create(Self);
Result := FSort;
if AJSON <> '' then
Result.Writer.Append(AJSON);
end;
{-------------------------------------------------------------------------------}
function TMongoQuery.Options: TOptions;
begin
if FOptions = nil then
FOptions := TOptions.Create;
Result := FOptions;
end;
{-------------------------------------------------------------------------------}
function TMongoQuery.Limit(const AValue: Integer): TMongoQuery;
begin
FLimit := AValue;
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoQuery.Skip(const AValue: Integer): TMongoQuery;
begin
FSkip := AValue;
Result := Self;
end;
{-------------------------------------------------------------------------------}
procedure TMongoQuery.DoGetFinalQueryBSON(AWriter: TMongoDocument);
begin
// nothing
end;
{-------------------------------------------------------------------------------}
function TMongoQuery.GetFinalQueryBSON: TMongoDocument;
begin
FQWriter.Clear;
if (FMatch <> nil) or (FSort <> nil) then begin
FQWriter.BeginObject('$query');
if FMatch <> nil then
FQWriter.Append(FMatch.FDoc);
FQWriter.EndObject;
end;
if FSort <> nil then begin
FQWriter.BeginObject('$orderby');
FQWriter.Append(FSort.FWriter);
FQWriter.EndObject;
end;
if FOptions <> nil then
FOptions.Save(FQWriter);
Result := FQWriter;
DoGetFinalQueryBSON(Result);
end;
{-------------------------------------------------------------------------------}
function TMongoQuery.GetFinalCountBSON: TMongoDocument;
begin
FQWriter.Clear;
if FMatch <> nil then
FQWriter.Append(FMatch.FDoc);
if FOptions <> nil then
FOptions.Save(FQWriter);
Result := FQWriter;
DoGetFinalQueryBSON(Result);
end;
{-------------------------------------------------------------------------------}
procedure TMongoQuery.DoGetFinalProjectBSON(AWriter: TMongoDocument);
begin
// nothing
end;
{-------------------------------------------------------------------------------}
function TMongoQuery.GetFinalProjectBSON: TMongoDocument;
begin
if (Self = nil) or (FProject = nil) then
Result := nil
else begin
Result := FProject.Writer;
DoGetFinalProjectBSON(Result);
end;
end;
{-------------------------------------------------------------------------------}
function TMongoQuery.GetCursor: IMongoCursor;
begin
if not Assigned(FGetCursor) then
FDException(FOwningObj, [S_FD_LPhys, FEnv.CLib.DriverID],
er_FD_MongoCursorError, ['Find']);
Result := FGetCursor(Self);
end;
{-------------------------------------------------------------------------------}
function TMongoQuery.Open: IMongoCursor;
begin
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoQuery.Value: Int64;
begin
if not Assigned(FGetCount) then
FDException(FOwningObj, [S_FD_LPhys, FEnv.CLib.DriverID],
er_FD_MongoExecuteError, ['Count']);
Result := FGetCount(Self);
end;
{-------------------------------------------------------------------------------}
{ TMongoCommand }
{-------------------------------------------------------------------------------}
constructor TMongoCommand.Create(AEnv: TMongoEnv);
begin
inherited Create(AEnv);
FCommand := TMongoDocument.Create(AEnv, Self, Self);
end;
{-------------------------------------------------------------------------------}
constructor TMongoCommand.Create(AEnv: TMongoEnv; AOwningObj: TObject);
begin
Create(AEnv);
FOwningObj := AOwningObj;
FCommand.FOwningObj := AOwningObj;
end;
{-------------------------------------------------------------------------------}
destructor TMongoCommand.Destroy;
begin
FDFreeAndNil(FCommand);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
function TMongoCommand.Command(const AArgs: array of const): TMongoCommand;
begin
FCommand.Append(AArgs);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoCommand.Command(const AJSON: String): TMongoCommand;
begin
FCommand.Append(AJSON);
Result := Self;
end;
{-------------------------------------------------------------------------------}
procedure TMongoCommand.DoGetFinalQueryBSON(AWriter: TMongoDocument);
begin
AWriter.Append(FCommand);
inherited DoGetFinalQueryBSON(AWriter);
end;
{-------------------------------------------------------------------------------}
{ TMongoUpdate.TModifier.TOperation }
{-------------------------------------------------------------------------------}
constructor TMongoUpdate.TModifier.TOperation.Create(AModifier: TModifier);
begin
inherited Create;
FModifier := AModifier;
FWriter := TMongoDocument.Create(FModifier.FUpdate.FEnv, FModifier.FUpdate.FOwningObj,
FModifier.FUpdate);
end;
{-------------------------------------------------------------------------------}
destructor TMongoUpdate.TModifier.TOperation.Destroy;
begin
FDFreeAndNil(FWriter);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.TOperation.Field(const AName: String;
const AValue: Variant): TOperation;
begin
FWriter.Add(AName, AValue);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.TOperation.&End: TModifier;
begin
Result := FModifier;
end;
{-------------------------------------------------------------------------------}
{ TMongoUpdate.TModifier.TInc }
{-------------------------------------------------------------------------------}
class function TMongoUpdate.TModifier.TInc.GetOperator: String;
begin
Result := '$inc';
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.TInc.Field(const AName: String;
const AValue: Variant): TInc;
begin
Result := TInc(inherited Field(AName, AValue));
end;
{-------------------------------------------------------------------------------}
{ TMongoUpdate.TModifier.TMul }
{-------------------------------------------------------------------------------}
class function TMongoUpdate.TModifier.TMul.GetOperator: String;
begin
Result := '$mul';
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.TMul.Field(const AName: String;
const AValue: Variant): TMul;
begin
Result := TMul(inherited Field(AName, AValue));
end;
{-------------------------------------------------------------------------------}
{ TMongoUpdate.TModifier.TRename }
{-------------------------------------------------------------------------------}
class function TMongoUpdate.TModifier.TRename.GetOperator: String;
begin
Result := '$rename';
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.TRename.Field(const AOldName,
ANewName: String): TRename;
begin
Result := TRename(inherited Field(AOldName, ANewName));
end;
{-------------------------------------------------------------------------------}
{ TMongoUpdate.TModifier.TSetOnInsert }
{-------------------------------------------------------------------------------}
class function TMongoUpdate.TModifier.TSetOnInsert.GetOperator: String;
begin
Result := '$setOnInsert';
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.TSetOnInsert.Field(const AName: String;
const AValue: Variant): TSetOnInsert;
begin
Result := TSetOnInsert(inherited Field(AName, AValue));
end;
{-------------------------------------------------------------------------------}
{ TMongoUpdate.TModifier.TSet }
{-------------------------------------------------------------------------------}
class function TMongoUpdate.TModifier.TSet.GetOperator: String;
begin
Result := '$set';
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.TSet.Field(const AName: String;
const AValue: Variant): TSet;
begin
Result := TSet(inherited Field(AName, AValue));
end;
{-------------------------------------------------------------------------------}
{ TMongoUpdate.TModifier.TUnset }
{-------------------------------------------------------------------------------}
class function TMongoUpdate.TModifier.TUnset.GetOperator: String;
begin
Result := '$unset';
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.TUnset.Field(const AName: String): TUnset;
begin
Result := TUnset(inherited Field(AName, ''));
end;
{-------------------------------------------------------------------------------}
{ TMongoUpdate.TModifier.TMin }
{-------------------------------------------------------------------------------}
class function TMongoUpdate.TModifier.TMin.GetOperator: String;
begin
Result := '$min';
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.TMin.Field(const AName: String;
const AValue: Variant): TMin;
begin
Result := TMin(inherited Field(AName, AValue));
end;
{-------------------------------------------------------------------------------}
{ TMongoUpdate.TModifier.TMax }
{-------------------------------------------------------------------------------}
class function TMongoUpdate.TModifier.TMax.GetOperator: String;
begin
Result := '$max';
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.TMax.Field(const AName: String;
const AValue: Variant): TMax;
begin
Result := TMax(inherited Field(AName, AValue));
end;
{-------------------------------------------------------------------------------}
{ TMongoUpdate.TModifier.TCurrentDate }
{-------------------------------------------------------------------------------}
class function TMongoUpdate.TModifier.TCurrentDate.GetOperator: String;
begin
Result := '$currentDate';
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.TCurrentDate.AsDate(const AName: String): TCurrentDate;
begin
FWriter.BeginObject(AName);
FWriter.Add('$type', 'date');
FWriter.EndObject;
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.TCurrentDate.AsTimestamp(const AName: String): TCurrentDate;
begin
FWriter.BeginObject(AName);
FWriter.Add('$type', 'timestamp');
FWriter.EndObject;
Result := Self;
end;
{-------------------------------------------------------------------------------}
{ TMongoUpdate.TModifier.TArrayOperation }
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.TArrayOperation.Field(const AName: String;
const AValues: Variant; AEach, AClose: Boolean): TArrayOperation;
begin
if VarIsArray(AValues) then begin
if AEach then begin
FWriter.BeginObject(AName);
FWriter.Add('$each', AValues);
end
else
FWriter.Add(AName, AValues);
if AEach then
if AClose then
FWriter.EndObject;
end
else
inherited Field(AName, AValues);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.TArrayOperation.Field(const AName: String;
const AValues: array of const; AEach, AClose: Boolean): TArrayOperation;
begin
if High(AValues) - Low(AValues) + 1 > 1 then begin
if AEach then begin
FWriter.BeginObject(AName);
FWriter.Add('$each', AValues);
end
else
FWriter.Add(AName, AValues);
if AEach then
if AClose then
FWriter.EndObject;
end
else
Writer.Add(AName, AValues[Low(AValues)]);
Result := Self;
end;
{-------------------------------------------------------------------------------}
{ TMongoUpdate.TModifier.TAddToSet }
{-------------------------------------------------------------------------------}
class function TMongoUpdate.TModifier.TAddToSet.GetOperator: String;
begin
Result := '$addToSet';
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.TAddToSet.Field(const AName: String;
const AValues: Variant; AEach: Boolean = True): TAddToSet;
begin
Result := TAddToSet(inherited Field(AName, AValues, AEach, True));
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.TAddToSet.Field(const AName: String;
const AValues: array of const; AEach: Boolean = True): TAddToSet;
begin
Result := TAddToSet(inherited Field(AName, AValues, AEach, True));
end;
{-------------------------------------------------------------------------------}
{ TMongoUpdate.TModifier.TPop }
{-------------------------------------------------------------------------------}
class function TMongoUpdate.TModifier.TPop.GetOperator: String;
begin
Result := '$pop';
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.TPop.First(const AName: String): TPop;
begin
Result := TPop(inherited Field(AName, -1));
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.TPop.Last(const AName: String): TPop;
begin
Result := TPop(inherited Field(AName, 1));
end;
{-------------------------------------------------------------------------------}
{ TMongoUpdate.TModifier.TPull }
{-------------------------------------------------------------------------------}
class function TMongoUpdate.TModifier.TPull.GetOperator: String;
begin
Result := '$pull';
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.TPull.Field(const AName: String;
const AValue: Variant): TPull;
begin
Result := TPull(inherited Field(AName, AValue));
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.TPull.Where(const AName, AValue: String): TPull;
begin
FWriter.BeginObject(AName);
FWriter.Append(AValue);
FWriter.EndObject;
Result := Self;
end;
{-------------------------------------------------------------------------------}
{ TMongoUpdate.TModifier.TPullAll }
{-------------------------------------------------------------------------------}
class function TMongoUpdate.TModifier.TPullAll.GetOperator: String;
begin
Result := '$pullAll';
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.TPullAll.Field(const AName: String;
const AValues: Variant): TPullAll;
begin
Result := TPullAll(inherited Field(AName, AValues, False, True));
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.TPullAll.Field(const AName: String;
const AValues: array of const): TPullAll;
begin
Result := TPullAll(inherited Field(AName, AValues, False, True));
end;
{-------------------------------------------------------------------------------}
{ TMongoUpdate.TModifier.TPush }
{-------------------------------------------------------------------------------}
class function TMongoUpdate.TModifier.TPush.GetOperator: String;
begin
Result := '$push';
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.TPush.Field(const AName: String;
const AValues: Variant; AEach: Boolean = True; ASlice: Integer = MaxInt;
const ASort: String = ''): TPush;
var
lModifiers: Boolean;
begin
lModifiers := (ASlice <> MaxInt) or (ASort <> '');
inherited Field(AName, AValues, AEach, not lModifiers);
if lModifiers then begin
if ASlice <> MaxInt then
FWriter.Add('$slice', ASlice);
if ASort <> '' then
FWriter.Append('{"$sort": {' + ASort + '}}');
FWriter.EndObject;
end;
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.TPush.Field(const AName: String;
const AValues: array of const; AEach: Boolean = True; ASlice: Integer = MaxInt;
const ASort: String = ''): TPush;
var
lModifiers: Boolean;
begin
lModifiers := (ASlice <> MaxInt) or (ASort <> '');
inherited Field(AName, AValues, AEach, not lModifiers);
if lModifiers then begin
if ASlice <> MaxInt then
FWriter.Add('$slice', ASlice);
if ASort <> '' then
FWriter.Append('{"$sort": {' + ASort + '}}');
FWriter.EndObject;
end;
Result := Self;
end;
{-------------------------------------------------------------------------------}
{ TMongoUpdate.TModifier.TPushAll }
{-------------------------------------------------------------------------------}
class function TMongoUpdate.TModifier.TPushAll.GetOperator: String;
begin
Result := '$pushAll';
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.TPushAll.Field(const AName: String;
const AValues: Variant): TPushAll;
begin
Result := TPushAll(inherited Field(AName, AValues, False, True));
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.TPushAll.Field(const AName: String;
const AValues: array of const): TPushAll;
begin
Result := TPushAll(inherited Field(AName, AValues, False, True));
end;
{-------------------------------------------------------------------------------}
{ TMongoUpdate.TModifier }
{-------------------------------------------------------------------------------}
constructor TMongoUpdate.TModifier.Create(AUpdate: TMongoUpdate);
begin
inherited Create;
FUpdate := AUpdate;
FOperations := TFDStringList.Create(True);
end;
{-------------------------------------------------------------------------------}
destructor TMongoUpdate.TModifier.Destroy;
begin
FDFreeAndNil(FWriter);
FDFreeAndNil(FOperations);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.Clear: TModifier;
begin
FOperations.Clear;
FCustomJSON := '';
FWriter.Clear;
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.GetOperation(AType: TOperationClass;
const AJSON: String): TOperation;
var
i: Integer;
begin
i := FOperations.IndexOf(AType.GetOperator);
if i = -1 then begin
Result := AType.Create(Self);
FOperations.AddObject(Result.GetOperator, Result);
end
else
Result := TOperation(FOperations.Objects[i]);
if AJSON <> '' then
Result.FWriter.Append(AJSON);
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.GetFinalBSON: TMongoDocument;
var
i: Integer;
oWrt: TMongoDocument;
begin
if FWriter = nil then
FWriter := TMongoDocument.Create(FUpdate.FEnv, FUpdate.FOwningObj, FUpdate);
FWriter.Clear;
if FCustomJSON <> '' then
FWriter.Append(FCustomJSON);
for i := 0 to FOperations.Count - 1 do begin
FWriter.BeginObject(FOperations[i]);
oWrt := TOperation(FOperations.Objects[i]).FWriter;
FWriter.Append(oWrt);
FWriter.EndObject;
end;
Result := FWriter;
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.Inc(const AJSON: String = ''): TInc;
begin
Result := TInc(GetOperation(TInc, AJSON));
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.Mul(const AJSON: String = ''): TMul;
begin
Result := TMul(GetOperation(TMul, AJSON));
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.Rename(const AJSON: String = ''): TRename;
begin
Result := TRename(GetOperation(TRename, AJSON));
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.SetOnInsert(const AJSON: String = ''): TSetOnInsert;
begin
Result := TSetOnInsert(GetOperation(TSetOnInsert, AJSON));
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.&Set(const AJSON: String = ''): TSet;
begin
Result := TSet(GetOperation(TSet, AJSON));
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.Unset(const AJSON: String = ''): TUnset;
begin
Result := TUnset(GetOperation(TUnset, AJSON));
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.Min(const AJSON: String = ''): TMin;
begin
Result := TMin(GetOperation(TMin, AJSON));
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.Max(const AJSON: String = ''): TMax;
begin
Result := TMax(GetOperation(TMax, AJSON));
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.CurrentDate(const AJSON: String = ''): TCurrentDate;
begin
Result := TCurrentDate(GetOperation(TCurrentDate, AJSON));
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.AddToSet(const AJSON: String): TAddToSet;
begin
Result := TAddToSet(GetOperation(TAddToSet, AJSON));
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.Pop(const AJSON: String): TPop;
begin
Result := TPop(GetOperation(TPop, AJSON));
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.Pull(const AJSON: String): TPull;
begin
Result := TPull(GetOperation(TPull, AJSON));
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.PullAll(const AJSON: String): TPullAll;
begin
Result := TPullAll(GetOperation(TPullAll, AJSON));
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.Push(const AJSON: String): TPush;
begin
Result := TPush(GetOperation(TPush, AJSON));
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.PushAll(const AJSON: String): TPushAll;
begin
Result := TPushAll(GetOperation(TPushAll, AJSON));
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.TModifier.&End: TMongoUpdate;
begin
Result := FUpdate;
end;
{-------------------------------------------------------------------------------}
{ TMongoUpdate }
{-------------------------------------------------------------------------------}
constructor TMongoUpdate.Create(AEnv: TMongoEnv);
begin
inherited Create;
FEnv := AEnv;
FOwningObj := AEnv.OwningObj;
end;
{-------------------------------------------------------------------------------}
constructor TMongoUpdate.Create(AEnv: TMongoEnv; AOwningObj: TObject;
ARunUpdate: TRunUpdate);
begin
Create(AEnv);
FOwningObj := AOwningObj;
FRunUpdate := ARunUpdate;
end;
{-------------------------------------------------------------------------------}
destructor TMongoUpdate.Destroy;
begin
FDFreeAndNil(FModifier);
FDFreeAndNil(FMatcher);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.Match(const AJSON: String = ''): TExpression;
begin
if FMatcher = nil then
FMatcher := TExpression.Create(FEnv, FOwningObj, Self);
Result := FMatcher;
if AJSON <> '' then
Result.Append(AJSON);
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.Modify(const AJSON: String = ''): TModifier;
begin
if FModifier = nil then
FModifier := TModifier.Create(Self);
Result := FModifier;
if AJSON <> '' then
Result.FCustomJSON := AJSON;
end;
{-------------------------------------------------------------------------------}
procedure TMongoUpdate.DoGetFinalModifyBSON(AWriter: TMongoDocument);
begin
// nothing
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.GetFinalModifyBSON: TMongoDocument;
begin
if (Self = nil) or (FModifier = nil) then
Result := nil
else begin
Result := FModifier.GetFinalBSON;
DoGetFinalModifyBSON(Result);
end;
end;
{-------------------------------------------------------------------------------}
procedure TMongoUpdate.DoGetFinalMatchBSON(AWriter: TMongoDocument);
begin
// nothing
end;
{-------------------------------------------------------------------------------}
function TMongoUpdate.GetFinalMatchBSON: TMongoDocument;
begin
if (Self = nil) or (FMatcher = nil) then
Result := nil
else begin
Result := FMatcher.FDoc;
DoGetFinalMatchBSON(Result);
end;
end;
{-------------------------------------------------------------------------------}
procedure TMongoUpdate.Exec;
begin
if not Assigned(FRunUpdate) then
FDException(FOwningObj, [S_FD_LPhys, FEnv.CLib.DriverID],
er_FD_MongoExecuteError, ['Update']);
FRunUpdate(Self);
end;
{-------------------------------------------------------------------------------}
{ TMongoSelector }
{-------------------------------------------------------------------------------}
constructor TMongoSelector.Create(AEnv: TMongoEnv);
begin
inherited Create;
FEnv := AEnv;
FOwningObj := AEnv.OwningObj;
end;
{-------------------------------------------------------------------------------}
constructor TMongoSelector.Create(AEnv: TMongoEnv; AOwningObj: TObject;
ARunOper: TRunOper);
begin
Create(AEnv);
FOwningObj := AOwningObj;
FRunOper := ARunOper;
end;
{-------------------------------------------------------------------------------}
destructor TMongoSelector.Destroy;
begin
FDFreeAndNil(FMatcher);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
function TMongoSelector.Match(const AJSON: String = ''): TExpression;
begin
if FMatcher = nil then
FMatcher := TExpression.Create(FEnv, FOwningObj, Self);
Result := FMatcher;
if AJSON <> '' then
Result.Append(AJSON);
end;
{-------------------------------------------------------------------------------}
procedure TMongoSelector.DoGetFinalMatchBSON(AWriter: TMongoDocument);
begin
// nothing
end;
{-------------------------------------------------------------------------------}
function TMongoSelector.GetFinalMatchBSON: TMongoDocument;
begin
if (Self = nil) or (FMatcher = nil) then
Result := nil
else begin
Result := FMatcher.FDoc;
DoGetFinalMatchBSON(Result);
end;
end;
{-------------------------------------------------------------------------------}
procedure TMongoSelector.Exec;
begin
if not Assigned(FRunOper) then
FDException(FOwningObj, [S_FD_LPhys, FEnv.CLib.DriverID],
er_FD_MongoExecuteError, ['Remove']);
FRunOper(Self);
end;
{-------------------------------------------------------------------------------}
{ TMongoInsert }
{-------------------------------------------------------------------------------}
constructor TMongoInsert.Create(AEnv: TMongoEnv);
begin
inherited Create;
FEnv := AEnv;
FOwningObj := AEnv.OwningObj;
end;
{-------------------------------------------------------------------------------}
constructor TMongoInsert.Create(AEnv: TMongoEnv; AOwningObj: TObject;
ARunOper: TRunOper);
begin
Create(AEnv);
FOwningObj := AOwningObj;
FRunOper := ARunOper;
end;
{-------------------------------------------------------------------------------}
destructor TMongoInsert.Destroy;
begin
FDFreeAndNil(FValues);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
function TMongoInsert.Values(const AJSON: String = ''): TMongoInsert.TExpression;
begin
if FValues = nil then
FValues := TExpression.Create(FEnv, FOwningObj, Self);
Result := FValues;
if AJSON <> '' then
Result.Append(AJSON);
end;
{-------------------------------------------------------------------------------}
procedure TMongoInsert.DoGetFinalValuesBSON(AWriter: TMongoDocument);
begin
// nothing
end;
{-------------------------------------------------------------------------------}
function TMongoInsert.GetFinalValuesBSON: TMongoDocument;
begin
if (Self = nil) or (FValues = nil) then
Result := nil
else begin
Result := FValues.FDoc;
DoGetFinalValuesBSON(Result);
end;
end;
{-------------------------------------------------------------------------------}
procedure TMongoInsert.Exec;
begin
if not Assigned(FRunOper) then
FDException(FOwningObj, [S_FD_LPhys, FEnv.CLib.DriverID],
er_FD_MongoExecuteError, ['Insert']);
FRunOper(Self);
end;
{-------------------------------------------------------------------------------}
{ TMongoIndex.TKeys }
{-------------------------------------------------------------------------------}
constructor TMongoIndex.TKeys.Create(AIndex: TMongoIndex);
begin
inherited Create;
FWriter := TMongoDocument.Create(AIndex.FEnv, AIndex.FOwningObj, AIndex);
end;
{-------------------------------------------------------------------------------}
destructor TMongoIndex.TKeys.Destroy;
begin
FDFreeAndNil(FWriter);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
function TMongoIndex.TKeys.Field(const AName: String; AAscending: Boolean = True): TKeys;
var
iVal: Integer;
begin
if AAscending then
iVal := 1
else
iVal := -1;
FWriter.Add(AName, iVal);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoIndex.TKeys.Field(const AName, AKind: String): TKeys;
begin
FWriter.Add(AName, AKind);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoIndex.TKeys.Ascending(const AFields: array of String): TKeys;
var
i: Integer;
begin
for i := Low(AFields) to High(AFields) do
Field(AFields[i], True);
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TMongoIndex.TKeys.Descending(const AFields: array of String): TKeys;
var
i: Integer;
begin
for i := Low(AFields) to High(AFields) do
Field(AFields[i], False);
Result := Self;
end;
{-------------------------------------------------------------------------------}
{ TMongoIndex.TOptions }
{-------------------------------------------------------------------------------}
constructor TMongoIndex.TOptions.Create(AIndex: TMongoIndex);
begin
inherited Create;
FIndex := AIndex;
FIndex.FEnv.CLib.Fmongoc_index_opt_init(@FOpts);
end;
{-------------------------------------------------------------------------------}
procedure TMongoIndex.TOptions.SetName(const AValue: String);
begin
if FName <> AValue then begin
FName := AValue;
if AValue = '' then begin
SetLength(FBName, 0);
FOpts.name := nil;
end
else begin
FBName := FIndex.FEnv.UTF8.Encode(AValue);
FOpts.name := PFDAnsiString(FBName);
end;
end;
end;
{-------------------------------------------------------------------------------}
{ TMongoIndex }
{-------------------------------------------------------------------------------}
constructor TMongoIndex.Create(AEnv: TMongoEnv);
begin
inherited Create;
FEnv := AEnv;
FOwningObj := AEnv.OwningObj;
FKeys := TKeys.Create(Self);
FOptions := TOptions.Create(Self);
end;
{-------------------------------------------------------------------------------}
destructor TMongoIndex.Destroy;
begin
FDFreeAndNil(FKeys);
FDFreeAndNil(FOptions);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
function TMongoIndex.Keys(const AJSON: String = ''): TKeys;
begin
if AJSON <> '' then
FKeys.FWriter.Append(AJSON);
Result := FKeys;
end;
{-------------------------------------------------------------------------------}
{ TMongoCursor }
{-------------------------------------------------------------------------------}
destructor TMongoCursor.Destroy;
begin
FDFreeAndNil(FDoc);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
procedure TMongoCursor.InternalFreeHandle;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_cursor_destroy, ['cursor', Handle]);
end;
{$ENDIF}
begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
CLib.Fmongoc_cursor_destroy(Handle);
end;
{-------------------------------------------------------------------------------}
function TMongoCursor.Next(ADoc: TMongoDocument): Boolean;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_cursor_next, ['cursor', Handle]);
end;
{$ENDIF}
var
pBson: Pbson_t;
begin
if FEof then
Exit(False);
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
Result := CLib.Fmongoc_cursor_next(Handle, @pBson);
FEof := not Result;
ADoc.AsReadHandle := pBson;
if not Result and CLib.Fmongoc_cursor_error(Handle, @Env.Error.FBError) then
Env.Error.CheckError(OwningObj);
end;
{-------------------------------------------------------------------------------}
function TMongoCursor.Next: Boolean;
begin
Result := Next(Doc);
end;
{-------------------------------------------------------------------------------}
function TMongoCursor.GetDoc: TMongoDocument;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace('TMongoCursor.GetDoc', ['cursor', Handle, 'doc', FDoc.AsJSON]);
end;
{$ENDIF}
begin
if FDoc = nil then
FDoc := TMongoDocument.Create(Env, OwningObj, Self);
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
Result := FDoc;
end;
{-------------------------------------------------------------------------------}
function TMongoCursor.GetIsAlive: Boolean;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_cursor_is_alive, ['cursor', Handle, 'result', Result]);
end;
{$ENDIF}
begin
Result := CLib.Fmongoc_cursor_is_alive(Handle);
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
end;
{-------------------------------------------------------------------------------}
{ TMongoCursor.TDefault }
{-------------------------------------------------------------------------------}
constructor TMongoCursor.TDefault.Create(AEnv: TMongoEnv; AOwningObj: TObject;
AReleaseObj: TObject; AHandle: Pmongoc_handle_t);
begin
inherited Create;
FReleaseObj := AReleaseObj;
FCursor := TMongoCursor.Create(AEnv, AOwningObj, AHandle);
end;
{-------------------------------------------------------------------------------}
destructor TMongoCursor.TDefault.Destroy;
begin
FDFreeAndNil(FCursor);
FDFreeAndNil(FReleaseObj);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
function TMongoCursor.TDefault.GetDoc: TMongoDocument;
begin
Result := FCursor.Doc;
end;
{-------------------------------------------------------------------------------}
function TMongoCursor.TDefault.GetIsAlive: Boolean;
begin
Result := FCursor.IsAlive;
end;
{-------------------------------------------------------------------------------}
function TMongoCursor.TDefault.Next: Boolean;
begin
Result := FCursor.Next;
end;
{-------------------------------------------------------------------------------}
function TMongoCursor.TDefault.Next(ADoc: TMongoDocument): Boolean;
begin
Result := FCursor.Next(ADoc);
end;
{-------------------------------------------------------------------------------}
{ TMongoConnection }
{-------------------------------------------------------------------------------}
constructor TMongoConnection.Create(AEnv: TMongoEnv; AOwningObj: TObject);
begin
inherited Create(AEnv, AOwningObj);
FReadPreference := TMongoReadPreference.Create(AEnv, AOwningObj, nil);
FWriteConcern := TMongoWriteConcern.Create(AEnv, AOwningObj, nil);
end;
{-------------------------------------------------------------------------------}
constructor TMongoConnection.CreateUsingHandle(AEnv: TMongoEnv;
AHandle: Pmongoc_handle_t; AOwningObj: TObject);
begin
inherited Create(AEnv, AOwningObj, AHandle);
FOwnHandle := False;
FReadPreference := TMongoReadPreference.Create(AEnv, AOwningObj, nil);
FWriteConcern := TMongoWriteConcern.Create(AEnv, AOwningObj, nil);
if AHandle <> nil then
HandleAllocated;
end;
{-------------------------------------------------------------------------------}
destructor TMongoConnection.Destroy;
begin
inherited Destroy;
FDFreeAndNil(FReadPreference);
FDFreeAndNil(FWriteConcern);
end;
{-------------------------------------------------------------------------------}
procedure TMongoConnection.InternalFreeHandle;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_client_destroy, ['client', Handle]);
end;
{$ENDIF}
begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
CLib.Fmongoc_client_destroy(Handle);
end;
{-------------------------------------------------------------------------------}
procedure TMongoConnection.FreeHandle;
begin
FDFreeAndNil(FCollection);
FDFreeAndNil(FDatabase);
ReadPreference.Handle := nil;
WriteConcern.Handle := nil;
inherited FreeHandle;
end;
{-------------------------------------------------------------------------------}
procedure TMongoConnection.HandleAllocated;
begin
inherited HandleAllocated;
ReadPreference.Handle := CLib.Fmongoc_client_get_read_prefs(Handle);
WriteConcern.Handle := CLib.Fmongoc_client_get_write_concern(Handle);
end;
{-------------------------------------------------------------------------------}
function TMongoConnection.GetURI: String;
begin
if Handle = nil then
Result := ''
else
Result := Env.ANSI.Decode(Pointer(CLib.Fmongoc_uri_get_string(CLib.Fmongoc_client_get_uri(Handle))));
end;
{-------------------------------------------------------------------------------}
function TMongoConnection.Getmax_bson_size: Integer;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_client_get_max_bson_size, ['client', Handle]);
end;
{$ENDIF}
begin
if Handle = nil then
Result := 1024 * 1024 * 16
else begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
Result := CLib.Fmongoc_client_get_max_bson_size(Handle);
end;
end;
{-------------------------------------------------------------------------------}
function TMongoConnection.Getmax_message_size: Integer;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_client_get_max_message_size, ['client', Handle]);
end;
{$ENDIF}
begin
if Handle = nil then
Result := 1024 * 1024 * 48
else begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
Result := CLib.Fmongoc_client_get_max_message_size(Handle);
end;
end;
{-------------------------------------------------------------------------------}
procedure TMongoConnection.Open(const AUri: String);
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_client_new, ['uri_string', AUri]);
end;
{$ENDIF}
begin
Close;
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
FHandle := CLib.Fmongoc_client_new(PFDAnsiString(PByte(Env.ANSI.Encode(AUri))));
FOwnHandle := True;
if Handle = nil then
FDException(OwningObj, [S_FD_LPhys, Env.CLib.DriverID], er_FD_MongoBadURI, []);
HandleAllocated;
end;
{-------------------------------------------------------------------------------}
procedure TMongoConnection.SSLInit(const APEMFile, APEMPwd, ACAFile, ACADir,
ACRLFile: String; AWeakValid: Boolean);
begin
if not Assigned(CLib.Fmongoc_client_set_ssl_opts) then
FDCapabilityNotSupported(OwningObj, [S_FD_LPhys, Env.CLib.DriverID]);
FPEMFile := Env.ANSI.Encode(APEMFile);
FPEMPwd := Env.ANSI.Encode(APEMPwd);
FCAFile := Env.ANSI.Encode(ACAFile);
FCADir := Env.ANSI.Encode(ACADir);
FCRLFile := Env.ANSI.Encode(ACRLFile);
if APEMFile <> '' then
Fmongoc_ssl_opt.pem_file := PFDAnsiString(PByte(FPEMFile));
if APEMPwd <> '' then
Fmongoc_ssl_opt.pem_pwd := PFDAnsiString(PByte(FPEMPwd));
if ACAFile <> '' then
Fmongoc_ssl_opt.ca_file := PFDAnsiString(PByte(FCAFile));
if ACADir <> '' then
Fmongoc_ssl_opt.ca_dir := PFDAnsiString(PByte(FCADir));
if ACRLFile <> '' then
Fmongoc_ssl_opt.crl_file := PFDAnsiString(PByte(FCRLFile));
Fmongoc_ssl_opt.weak_cert_validation := AWeakValid;
CLib.Fmongoc_client_set_ssl_opts(Handle, @Fmongoc_ssl_opt);
end;
{-------------------------------------------------------------------------------}
procedure TMongoConnection.Close;
begin
FreeHandle;
end;
{-------------------------------------------------------------------------------}
procedure TMongoConnection.Ping;
begin
FDFree(CommandSimple('test', '{"ping": 1}'));
end;
{-------------------------------------------------------------------------------}
function TMongoConnection.GetServerStatus: TMongoDocument;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_client_get_server_status, ['client', Handle]);
end;
{$ENDIF}
begin
Result := TMongoDocument.Create(Env, OwningObj, Self);
try
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
if not CLib.Fmongoc_client_get_server_status(Handle, nil, Result.AsWriteHandle,
@Env.Error.FBError) then
Env.Error.CheckError(OwningObj, smongoc_client_get_server_status);
except
FDFree(Result);
raise;
end;
end;
{-------------------------------------------------------------------------------}
function TMongoConnection.GetServerVersion: TFDVersion;
var
oReply: TMongoDocument;
oIter: TJSONIterator;
begin
oReply := CommandSimple('test', '{"buildInfo": 1}');
oIter := oReply.Iterator;
try
if oIter.Next('version') then
Result := FDVerStr2Int(oIter.AsString)
else
Result := 0;
finally
FDFree(oIter);
FDFree(oReply);
end;
end;
{-------------------------------------------------------------------------------}
function TMongoConnection.ListDatabases: IMongoCursor;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_client_find_databases, ['client', Handle]);
end;
{$ENDIF}
var
hCrs: Pmongoc_cursor_t;
begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
hCrs := CLib.Fmongoc_client_find_databases(Handle, @Env.Error.FBError);
if hCrs = nil then
Env.Error.CheckError(OwningObj, smongoc_client_find_databases);
Result := TMongoCursor.TDefault.Create(Env, OwningObj, nil, hCrs);
end;
{-------------------------------------------------------------------------------}
function TMongoConnection.InternalGetDatabase(const ADBName: String;
ANew: Boolean): TMongoDatabase;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_client_get_database, ['client', Handle, 'name', ADBName]);
end;
{$ENDIF}
var
hDB: Pmongoc_database_t;
begin
if not ANew and (FDatabase <> nil) and
(AnsiCompareText(ADBName, FDatabase.Name) = 0) then begin
Result := FDatabase;
Exit;
end;
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
hDB := CLib.Fmongoc_client_get_database(Handle,
PFDAnsiString(PByte(Env.ANSI.Encode(ADBName))));
if hDB = nil then
Env.Error.CheckError(OwningObj, smongoc_client_get_database);
if ANew then
Result := TMongoDatabase.Create(Env, OwningObj, hDB)
else begin
if FDatabase = nil then
FDatabase := TMongoDatabase.Create(Env, OwningObj, hDB)
else begin
FDatabase.Handle := hDB;
FDatabase.FOwnHandle := True;
end;
Result := FDatabase;
end;
end;
{-------------------------------------------------------------------------------}
function TMongoConnection.InternalGetCollection(const ADBName, AColName: String;
ANew: Boolean): TMongoCollection;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_client_get_collection, ['client', Handle, 'db', ADBName,
'collection', AColName]);
end;
{$ENDIF}
var
hCol: Pmongoc_collection_t;
begin
if not ANew and (FCollection <> nil) and
(AnsiCompareText(ADBName, FCollection.DB) = 0) and
(AnsiCompareText(AColName, FCollection.Name) = 0) then begin
Result := FCollection;
Exit;
end;
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
hCol := CLib.Fmongoc_client_get_collection(Handle,
PFDAnsiString(PByte(Env.ANSI.Encode(ADBName))),
PFDAnsiString(PByte(Env.ANSI.Encode(AColName))));
if hCol = nil then
Env.Error.CheckError(OwningObj, smongoc_client_get_collection);
if ANew then
Result := TMongoCollection.Create(Env, OwningObj, hCol)
else begin
if FCollection = nil then
FCollection := TMongoCollection.Create(Env, OwningObj, hCol)
else begin
FCollection.Handle := hCol;
FCollection.FOwnHandle := True;
end;
Result := FCollection;
end;
end;
{-------------------------------------------------------------------------------}
function TMongoConnection.GetDatabase(const ADBName: String): TMongoDatabase;
begin
Result := InternalGetDatabase(ADBName, True);
end;
{-------------------------------------------------------------------------------}
function TMongoConnection.GetDatabasesProp(const ADBName: String): TMongoDatabase;
begin
Result := InternalGetDatabase(ADBName, False);
end;
{-------------------------------------------------------------------------------}
function TMongoConnection.GetCollection(const ADBName, AColName: String): TMongoCollection;
begin
Result := InternalGetCollection(ADBName, AColName, True);
end;
{-------------------------------------------------------------------------------}
function TMongoConnection.GetCollectionsProp(const ADBName, AColName: String): TMongoCollection;
begin
Result := InternalGetCollection(ADBName, AColName, False);
end;
{-------------------------------------------------------------------------------}
function TMongoConnection.Command(const ADBName: String; ACommand: TMongoCommand;
AFlags: TMongoQueryFlags = []): IMongoCursor;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_client_command, ['client', Handle, 'db_name', ADBName,
'flags', QF2mqft(AFlags), 'skip', ACommand.FSkip, 'limit', ACommand.FLimit,
'batch_size', ACommand.Options.BatchSize, 'query', ACommand.FinalQueryBSON.AsJSON,
'fields', ACommand.FinalProjectBSON.AsJSON]);
end;
{$ENDIF}
var
hCrs: Pmongoc_cursor_t;
begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
hCrs := CLib.Fmongoc_client_command(Handle,
PFDAnsiString(PByte(Env.ANSI.Encode(ADBName))), QF2mqft(AFlags),
ACommand.FSkip, ACommand.FLimit, ACommand.Options.BatchSize,
ACommand.FinalQueryBSON.AsReadHandle, ACommand.FinalProjectBSON.AsReadHandle, nil);
if hCrs = nil then
Env.Error.CheckError(OwningObj, smongoc_client_command);
Result := TMongoCursor.TDefault.Create(Env, OwningObj, nil, hCrs);
end;
{-------------------------------------------------------------------------------}
function TMongoConnection.Command(const ADBName: String; const AJSON: String;
AFlags: TMongoQueryFlags = []): IMongoCursor;
var
oCmd: TMongoCommand;
begin
oCmd := TMongoCommand.Create(Env, FOwningObj);
try
oCmd.Command(AJSON);
Result := Command(ADBName, oCmd, AFlags);
finally
FDFree(oCmd);
end;
end;
{-------------------------------------------------------------------------------}
function TMongoConnection.CommandSimple(const ADBName: String; ACommand: TMongoDocument): TMongoDocument;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_client_command_simple, ['client', Handle, 'db_name', ADBName,
'command', ACommand.AsJSON]);
end;
{$ENDIF}
begin
Result := TMongoDocument.Create(Env, OwningObj, Self);
try
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
if not CLib.Fmongoc_client_command_simple(Handle,
PFDAnsiString(PByte(Env.ANSI.Encode(ADBName))), ACommand.AsReadHandle,
nil, Result.AsWriteHandle, @Env.Error.FBError) then
Env.Error.CheckError(OwningObj, smongoc_client_command_simple);
except
FDFree(Result);
raise;
end;
end;
{-------------------------------------------------------------------------------}
function TMongoConnection.CommandSimple(const ADBName: String; const AJSON: String): TMongoDocument;
var
oCmd: TMongoDocument;
begin
oCmd := TMongoDocument.Create(Env, OwningObj, Self);
try
oCmd.Append(AJSON);
Result := CommandSimple(ADBName, oCmd);
finally
FDFree(oCmd);
end;
end;
{-------------------------------------------------------------------------------}
function TMongoConnection.Dereference(const ADBRef: TJsonDBRef): TMongoDocument;
begin
if ADBRef.DB = '' then
FDException(OwningObj, [S_FD_LPhys, Env.CLib.DriverID],
er_FD_MongoDBRefInvalid, [ADBRef.AsString]);
Result := Databases[ADBRef.DB].Dereference(ADBRef);
end;
{-------------------------------------------------------------------------------}
{ TMongoDatabase }
{-------------------------------------------------------------------------------}
constructor TMongoDatabase.Create(AEnv: TMongoEnv; AOwningObj: TObject;
AHandle: Pmongoc_database_t);
begin
inherited Create(AEnv, AOwningObj, AHandle);
FReadPreference := TMongoReadPreference.Create(AEnv, AOwningObj,
CLib.Fmongoc_database_get_read_prefs(AHandle));
FWriteConcern := TMongoWriteConcern.Create(AEnv, AOwningObj,
CLib.Fmongoc_database_get_write_concern(AHandle));
end;
{-------------------------------------------------------------------------------}
destructor TMongoDatabase.Destroy;
begin
inherited Destroy;
FDFreeAndNil(FReadPreference);
FDFreeAndNil(FWriteConcern);
end;
{-------------------------------------------------------------------------------}
procedure TMongoDatabase.InternalFreeHandle;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_database_destroy, ['database', Handle]);
end;
{$ENDIF}
begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
CLib.Fmongoc_database_destroy(Handle);
end;
{-------------------------------------------------------------------------------}
procedure TMongoDatabase.FreeHandle;
begin
FDFreeAndNil(FCollection);
FReadPreference.Handle := nil;
FWriteConcern.Handle := nil;
inherited FreeHandle;
end;
{-------------------------------------------------------------------------------}
procedure TMongoDatabase.HandleAllocated;
begin
inherited HandleAllocated;
FReadPreference.Handle := CLib.Fmongoc_database_get_read_prefs(Handle);
FWriteConcern.Handle := CLib.Fmongoc_database_get_write_concern(Handle);
end;
{-------------------------------------------------------------------------------}
function TMongoDatabase.GetName: String;
begin
Result := Env.ANSI.Decode(Pointer(CLib.Fmongoc_database_get_name(Handle)));
end;
{-------------------------------------------------------------------------------}
procedure TMongoDatabase.Drop;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_database_drop, ['database', Handle]);
end;
{$ENDIF}
begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
if not CLib.Fmongoc_database_drop(Handle, @Env.Error.FBError) then
Env.Error.CheckError(OwningObj, smongoc_database_drop);
end;
{-------------------------------------------------------------------------------}
procedure TMongoDatabase.AddUser(const AUserName, APassword: String;
ARoles, ACustomData: TMongoDocument);
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_database_add_user, ['database', Handle, 'username', AUserName,
'password', APassword, 'roles', ARoles.AsJSON, 'custom_data', ACustomData.AsJSON]);
end;
{$ENDIF}
begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
if not CLib.Fmongoc_database_add_user(Handle,
PFDAnsiString(PByte(Env.ANSI.Encode(AUserName))),
PFDAnsiString(PByte(Env.ANSI.Encode(APassword))),
ARoles.AsReadHandle, ACustomData.AsReadHandle, @Env.Error.FBError) then
Env.Error.CheckError(OwningObj, smongoc_database_add_user);
end;
{-------------------------------------------------------------------------------}
procedure TMongoDatabase.DropUser(const AUserName: String);
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_database_remove_user, ['database', Handle, 'username', AUserName]);
end;
{$ENDIF}
begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
if not CLib.Fmongoc_database_remove_user(Handle,
PFDAnsiString(PByte(Env.ANSI.Encode(AUserName))), @Env.Error.FBError) then
Env.Error.CheckError(OwningObj, smongoc_database_remove_user);
end;
{-------------------------------------------------------------------------------}
procedure TMongoDatabase.DropAllUsers;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_database_remove_all_users, ['database', Handle]);
end;
{$ENDIF}
begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
if not CLib.Fmongoc_database_remove_all_users(Handle, @Env.Error.FBError) then
Env.Error.CheckError(OwningObj, smongoc_database_remove_all_users);
end;
{-------------------------------------------------------------------------------}
function TMongoDatabase.ListCollections(ASelector: TMongoSelector = nil): IMongoCursor;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_database_find_collections, ['database', Handle,
'filter', ASelector.FinalMatchBSON.AsJSON]);
end;
{$ENDIF}
var
hCrs: Pmongoc_cursor_t;
begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
hCrs := CLib.Fmongoc_database_find_collections(Handle,
ASelector.FinalMatchBSON.AsReadHandle, @Env.Error.FBError);
if hCrs = nil then
Env.Error.CheckError(OwningObj, smongoc_database_find_collections);
Result := TMongoCursor.TDefault.Create(Env, OwningObj, nil, hCrs);
end;
{-------------------------------------------------------------------------------}
function TMongoDatabase.HasCollection(const AName: String): Boolean;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_database_has_collection, ['database', Handle, 'name', AName]);
end;
{$ENDIF}
begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
Result := CLib.Fmongoc_database_has_collection(Handle,
PFDAnsiString(PByte(Env.ANSI.Encode(AName))), @Env.Error.FBError);
if not Result then
Env.Error.CheckError(OwningObj);
end;
{-------------------------------------------------------------------------------}
procedure TMongoDatabase.CreateCollection(const AName: String; AOptions: TMongoDocument);
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_database_create_collection, ['database', Handle,
'name', AName, 'options', AOptions.AsJSON]);
end;
{$ENDIF}
var
hCol: Pmongoc_collection_t;
begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
hCol := CLib.Fmongoc_database_create_collection(Handle,
PFDAnsiString(PByte(Env.ANSI.Encode(AName))), AOptions.AsReadHandle,
@Env.Error.FBError);
if hCol = nil then
Env.Error.CheckError(OwningObj, smongoc_database_create_collection);
if FCollection = nil then
FCollection := TMongoCollection.Create(Env, OwningObj, hCol)
else begin
FCollection.Handle := hCol;
FCollection.FOwnHandle := True;
end;
end;
{-------------------------------------------------------------------------------}
procedure TMongoDatabase.DropCollection(const AName: String; AIgnoreObjNotExists: Boolean = False);
begin
Collections[AName].Drop(AIgnoreObjNotExists);
end;
{-------------------------------------------------------------------------------}
function TMongoDatabase.InternalGetCollection(const AColName: String; ANew: Boolean): TMongoCollection;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_database_get_collection, ['database', Handle, 'name', AColName]);
end;
{$ENDIF}
var
hCol: Pmongoc_collection_t;
begin
if not ANew and (FCollection <> nil) and
(AnsiCompareText(AColName, FCollection.Name) = 0) then begin
Result := FCollection;
Exit;
end;
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
hCol := CLib.Fmongoc_database_get_collection(Handle,
PFDAnsiString(PByte(Env.ANSI.Encode(AColName))));
if ANew then
Result := TMongoCollection.Create(Env, OwningObj, hCol)
else begin
if FCollection = nil then
FCollection := TMongoCollection.Create(Env, OwningObj, hCol)
else begin
FCollection.Handle := hCol;
FCollection.FOwnHandle := True;
end;
Result := FCollection;
end;
end;
{-------------------------------------------------------------------------------}
function TMongoDatabase.GetCollection(const AColName: String): TMongoCollection;
begin
Result := InternalGetCollection(AColName, True);
end;
{-------------------------------------------------------------------------------}
function TMongoDatabase.GetCollectionsProp(const AColName: String): TMongoCollection;
begin
Result := InternalGetCollection(AColName, False);
end;
{-------------------------------------------------------------------------------}
function TMongoDatabase.Command(ACommand: TMongoCommand; AFlags: TMongoQueryFlags = []): IMongoCursor;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_database_command, ['database', Handle,
'flags', QF2mqft(AFlags), 'skip', ACommand.FSkip, 'limit', ACommand.FLimit,
'batch_size', ACommand.Options.BatchSize, 'query', ACommand.FinalQueryBSON.AsJSON,
'fields', ACommand.FinalProjectBSON.AsJSON]);
end;
{$ENDIF}
var
hCrs: Pmongoc_cursor_t;
begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
hCrs := CLib.Fmongoc_database_command(Handle, QF2mqft(AFlags), ACommand.FSkip,
ACommand.FLimit, ACommand.Options.BatchSize, ACommand.FinalQueryBSON.AsReadHandle,
ACommand.FinalProjectBSON.AsReadHandle, nil);
if hCrs = nil then
Env.Error.CheckError(OwningObj, smongoc_database_command);
Result := TMongoCursor.TDefault.Create(Env, OwningObj, nil, hCrs);
end;
{-------------------------------------------------------------------------------}
function TMongoDatabase.Command(const AJSON: String; AFlags: TMongoQueryFlags = []): IMongoCursor;
var
oCmd: TMongoCommand;
begin
oCmd := TMongoCommand.Create(Env, FOwningObj);
try
oCmd.Command(AJSON);
Result := Command(oCmd, AFlags);
finally
FDFree(oCmd);
end;
end;
{-------------------------------------------------------------------------------}
function TMongoDatabase.CommandSimple(ACommand: TMongoDocument): TMongoDocument;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_database_command_simple, ['database', Handle,
'command', ACommand.AsJSON]);
end;
{$ENDIF}
begin
Result := TMongoDocument.Create(Env, OwningObj, Self);
try
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
if not CLib.Fmongoc_database_command_simple(Handle, ACommand.AsReadHandle,
nil, Result.AsWriteHandle, @Env.Error.FBError) then
Env.Error.CheckError(OwningObj, smongoc_database_command_simple);
except
FDFree(Result);
raise;
end;
end;
{-------------------------------------------------------------------------------}
function TMongoDatabase.CommandSimple(const AJSON: String): TMongoDocument;
var
oCmd: TMongoDocument;
begin
oCmd := TMongoDocument.Create(Env, OwningObj, Self);
try
oCmd.Append(AJSON);
Result := CommandSimple(oCmd);
finally
FDFree(oCmd);
end;
end;
{-------------------------------------------------------------------------------}
function TMongoDatabase.Dereference(const ADBRef: TJsonDBRef): TMongoDocument;
begin
Result := nil;
if not (((ADBRef.DB = '') or AnsiSameText(ADBRef.DB, Name)) and
(ADBRef.Ref <> '')) then
FDException(OwningObj, [S_FD_LPhys, Env.CLib.DriverID],
er_FD_MongoDBRefInvalid, [ADBRef.AsString]);
try
Result := Collections[ADBRef.Ref].Dereference(ADBRef.Id);
except
on E: EFDException do
if E.FDCode = er_FD_MongoDBRefNotFound then
FDException(OwningObj, [S_FD_LPhys, Env.CLib.DriverID],
er_FD_MongoDBRefNotFound, [ADBRef.AsString])
else
raise;
end;
end;
{-------------------------------------------------------------------------------}
{ TMongoCollection }
{-------------------------------------------------------------------------------}
constructor TMongoCollection.Create(AEnv: TMongoEnv; AOwningObj: TObject;
AHandle: Pmongoc_collection_t);
begin
inherited Create(AEnv, AOwningObj, AHandle);
FReadPreference := TMongoReadPreference.Create(AEnv, AOwningObj,
CLib.Fmongoc_collection_get_read_prefs(AHandle));
FWriteConcern := TMongoWriteConcern.Create(AEnv, AOwningObj,
CLib.Fmongoc_collection_get_write_concern(AHandle));
FLastOID := TMongoOID.Create(AEnv, AOwningObj);
end;
{-------------------------------------------------------------------------------}
destructor TMongoCollection.Destroy;
begin
inherited Destroy;
FDFreeAndNil(FLastError);
FDFreeAndNil(FReadPreference);
FDFreeAndNil(FWriteConcern);
FDFreeAndNil(FLastOID);
end;
{-------------------------------------------------------------------------------}
procedure TMongoCollection.InternalFreeHandle;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_collection_destroy, ['collection', Handle]);
end;
{$ENDIF}
begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
CLib.Fmongoc_collection_destroy(Handle);
end;
{-------------------------------------------------------------------------------}
procedure TMongoCollection.FreeHandle;
begin
CancelBulk;
FReadPreference.Handle := nil;
FWriteConcern.Handle := nil;
if FLastError <> nil then
FLastError.Handle := nil;
inherited FreeHandle;
end;
{-------------------------------------------------------------------------------}
procedure TMongoCollection.HandleAllocated;
begin
inherited HandleAllocated;
FReadPreference.Handle := CLib.Fmongoc_collection_get_read_prefs(Handle);
FWriteConcern.Handle := CLib.Fmongoc_collection_get_write_concern(Handle);
end;
{-------------------------------------------------------------------------------}
function TMongoCollection.GetName: String;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_collection_get_name, ['collection', Handle]);
end;
{$ENDIF}
begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
Result := Env.ANSI.Decode(Pointer(CLib.Fmongoc_collection_get_name(Handle)));
end;
{-------------------------------------------------------------------------------}
function TMongoCollection.GetDB: String;
begin
Result := Env.ANSI.Decode(Pointer(@P_mongoc_collection_t(Handle)^.db[0]));
end;
{-------------------------------------------------------------------------------}
function TMongoCollection.GetNS: String;
begin
Result := Env.ANSI.Decode(Pointer(@P_mongoc_collection_t(Handle)^.ns[0]),
P_mongoc_collection_t(Handle)^.nslen);
end;
{-------------------------------------------------------------------------------}
procedure TMongoCollection.Drop(AIgnoreObjNotExists: Boolean = False);
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_collection_drop, ['collection', Handle]);
end;
{$ENDIF}
begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
if not CLib.Fmongoc_collection_drop(Handle, @Env.Error.FBError) and
((Env.Error.FBError.code <> MONGOC_ERROR_QUERY_COMMAND_NOT_FOUND) or
not AIgnoreObjNotExists) then
Env.Error.CheckError(OwningObj, smongoc_collection_drop);
end;
{-------------------------------------------------------------------------------}
procedure TMongoCollection.Rename(const ANewDB, ANewName: String;
ADropTarget: Boolean = True);
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_collection_rename, ['collection', Handle,
'new_db', ANewDB, 'new_name', ANewName,
'drop_target_before_rename', ADropTarget]);
end;
{$ENDIF}
begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
if not CLib.Fmongoc_collection_rename(Handle,
PFDAnsiString(PByte(Env.ANSI.Encode(ANewDB))),
PFDAnsiString(PByte(Env.ANSI.Encode(ANewName))),
ADropTarget, @Env.Error.FBError) then
Env.Error.CheckError(OwningObj, smongoc_collection_rename);
end;
{-------------------------------------------------------------------------------}
function TMongoCollection.Validate(AOptions: TMongoDocument): TMongoDocument;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_collection_validate, ['collection', Handle,
'options', AOptions.AsJSON]);
end;
{$ENDIF}
begin
Result := TMongoDocument.Create(Env, OwningObj, Self);
try
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
if not CLib.Fmongoc_collection_validate(Handle, AOptions.AsReadHandle,
Result.AsWriteHandle, @Env.Error.FBError) then
Env.Error.CheckError(OwningObj, smongoc_collection_validate);
except
FDFree(Result);
raise;
end;
end;
{-------------------------------------------------------------------------------}
function TMongoCollection.Statistics(AOptions: TMongoDocument): TMongoDocument;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_collection_stats, ['collection', Handle,
'options', AOptions.AsJSON]);
end;
{$ENDIF}
begin
Result := TMongoDocument.Create(Env, OwningObj, Self);
try
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
if not CLib.Fmongoc_collection_stats(Handle, AOptions.AsReadHandle,
Result.AsWriteHandle, @Env.Error.FBError) then
Env.Error.CheckError(OwningObj, smongoc_collection_stats);
except
FDFree(Result);
raise;
end;
end;
{-------------------------------------------------------------------------------}
function TMongoCollection.ListIndexes: IMongoCursor;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_collection_find_indexes, ['collection', Handle]);
end;
{$ENDIF}
var
hCrs: Pmongoc_cursor_t;
begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
hCrs := CLib.Fmongoc_collection_find_indexes(Handle, @Env.Error.FBError);
if hCrs = nil then
Env.Error.CheckError(OwningObj, smongoc_collection_find_indexes);
Result := TMongoCursor.TDefault.Create(Env, OwningObj, nil, hCrs);
end;
{-------------------------------------------------------------------------------}
procedure TMongoCollection.CreateIndex(AIndex: TMongoIndex);
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_collection_create_index, ['collection', Handle,
'keys', AIndex.FKeys.FWriter.AsJSON, 'name', AIndex.FOptions.Name]);
end;
{$ENDIF}
begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
if not CLib.Fmongoc_collection_create_index(Handle,
AIndex.FKeys.FWriter.AsReadHandle,
@AIndex.FOptions.FOpts, @Env.Error.FBError) then
Env.Error.CheckError(OwningObj, smongoc_collection_create_index);
end;
{-------------------------------------------------------------------------------}
procedure TMongoCollection.DropIndex(const AName: String; AIgnoreObjNotExists: Boolean = False);
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_collection_drop_index, ['collection', Handle,
'index_name', AName]);
end;
{$ENDIF}
begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
try
if not CLib.Fmongoc_collection_drop_index(Handle,
PFDAnsiString(PByte(Env.ANSI.Encode(AName))), @Env.Error.FBError) then
Env.Error.CheckError(OwningObj, smongoc_collection_drop_index);
except
on E: EFDDBEngineException do
if not AIgnoreObjNotExists or (E.Kind <> ekObjNotExists) then
raise;
end;
end;
{-------------------------------------------------------------------------------}
procedure TMongoCollection.ResetCounts;
begin
FDocsInserted := -1;
FDocsMatched := -1;
FDocsModified := -1;
FDocsRemoved := -1;
FDocsUpserted := -1;
end;
{-------------------------------------------------------------------------------}
procedure TMongoCollection.ProcessWriteResult(AReply: TMongoDocument; ABulk, AFailed: Boolean);
var
oIter: TJSONIterator;
oExc: EMongoNativeException;
lReset: Boolean;
procedure ProcessErrors(const AErrorGroup: String;
AExc: EMongoNativeException; var AReset: Boolean);
var
iIndex: Integer;
iCode: Integer;
sMsg: string;
begin
if oIter.Next(AErrorGroup) then begin
oIter.Recurse;
while oIter.Next do begin
oIter.Recurse;
iIndex := -1;
iCode := -1;
sMsg := '';
if oIter.Next('index') then
iIndex := oIter.AsInteger;
if oIter.Next('code') then
iCode := oIter.AsInteger;
if oIter.Next('errmsg') then
sMsg := oIter.AsString;
if AReset then begin
oExc.Clear;
AReset := False;
end;
oExc.AppendError(oExc.ErrorCount + 1, iCode, 0, sMsg, iIndex);
oIter.Return;
end;
oIter.Return;
end;
end;
begin
oIter := AReply.Iterator;
try
if oIter.Next('nInserted') then
FDocsInserted := oIter.AsInteger;
if oIter.Next('nMatched') then
FDocsMatched := oIter.AsInteger;
if oIter.Next('nModified') then
FDocsModified := oIter.AsInteger;
if oIter.Next('nRemoved') then
FDocsRemoved := oIter.AsInteger;
if oIter.Next('nUpserted') then
FDocsUpserted := oIter.AsInteger;
if ABulk and AFailed and
(ExceptObject <> nil) and (ExceptObject is EMongoNativeException) then begin
oExc := EMongoNativeException(ExceptObject);
lReset := True;
ProcessErrors('writeErrors', oExc, lReset);
ProcessErrors('writeConcernError', oExc, lReset);
end;
finally
FDFree(oIter);
end;
end;
{-------------------------------------------------------------------------------}
function TMongoCollection.GetLastError: TMongoDocument;
begin
if FLastError = nil then
FLastError := TMongoDocument.Create(Env, OwningObj, Self);
FLastError.AsReadHandle := CLib.Fmongoc_collection_get_last_error(Handle);
Result := FLastError;
end;
{-------------------------------------------------------------------------------}
function TMongoCollection.GetIsBulk: Boolean;
begin
Result := FBulkHandle <> nil;
end;
{-------------------------------------------------------------------------------}
procedure TMongoCollection.BeginBulk(AOrdered: Boolean);
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_collection_create_bulk_operation, ['collection', Handle,
'ordered', AOrdered]);
end;
{$ENDIF}
begin
if FBulkHandle <> nil then
FDException(OwningObj, [S_FD_LPhys, Env.CLib.DriverID], er_FD_MongoBulkError, []);
ResetCounts;
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
FBulkHandle := CLib.Fmongoc_collection_create_bulk_operation(Handle, AOrdered,
WriteConcern.Handle);
end;
{-------------------------------------------------------------------------------}
procedure TMongoCollection.EndBulk;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_bulk_operation_execute, ['bulk', FBulkHandle]);
end;
{$ENDIF}
var
oReply: TMongoDocument;
lFailed: Boolean;
begin
if FBulkHandle = nil then
FDException(OwningObj, [S_FD_LPhys, Env.CLib.DriverID], er_FD_MongoBulkError, []);
oReply := TMongoDocument.Create(Env, OwningObj, Self);
lFailed := False;
try
try
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
if CLib.Fmongoc_bulk_operation_execute(FBulkHandle, oReply.AsWriteHandle,
@Env.Error.FBError) = 0 then
Env.Error.CheckError(OwningObj, smongoc_bulk_operation_execute);
except
lFailed := True;
raise;
end;
finally
ProcessWriteResult(oReply, True, lFailed);
CancelBulk;
FDFree(oReply);
end;
end;
{-------------------------------------------------------------------------------}
procedure TMongoCollection.CancelBulk;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_bulk_operation_destroy, ['bulk', FBulkHandle]);
end;
{$ENDIF}
begin
if FBulkHandle <> nil then begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
CLib.Fmongoc_bulk_operation_destroy(FBulkHandle);
FBulkHandle := nil;
end;
end;
{-------------------------------------------------------------------------------}
procedure TMongoCollection.EnsureID(ADocument: TMongoDocument);
var
oIter: TJSONIterator;
begin
oIter := ADocument.Iterator;
try
if oIter.Next('_id') then
if oIter.&Type = TJsonToken.Oid then begin
FLastOID.AsOid := oIter.AsOid;
FLastID := FLastOID.AsString;
end
else
FLastID := oIter.AsVariant
else begin
FLastOID.Init;
FLastID := FLastOID.AsString;
ADocument.Add('_id', FLastOID);
end;
finally
FDFree(oIter);
end;
end;
{-------------------------------------------------------------------------------}
procedure TMongoCollection.Insert(ADocument: TMongoDocument; AFlags: TInsertFlags = []);
var
iFlags: mongoc_insert_flags_t;
lFailed: Boolean;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_bulk_operation_insert, ['bulk', FBulkHandle, 'document', ADocument.AsJSON]);
end;
procedure Trace2;
begin
Env.Trace(smongoc_collection_insert, ['collection', Handle, 'flags', iFlags,
'document', ADocument.AsJSON]);
end;
{$ENDIF}
begin
EnsureID(ADocument);
if IsBulk then begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
CLib.Fmongoc_bulk_operation_insert(FBulkHandle, ADocument.AsReadHandle);
end
else begin
ResetCounts;
lFailed := False;
try
try
iFlags := MONGOC_INSERT_NONE;
if TInsertFlag.ContinueOnError in AFlags then
iFlags := iFlags or MONGOC_INSERT_CONTINUE_ON_ERROR;
if TInsertFlag.NoValidate in AFlags then
iFlags := iFlags or MONGOC_INSERT_NO_VALIDATE;
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace2;
{$ENDIF}
if not CLib.Fmongoc_collection_insert(Handle, iFlags, ADocument.AsReadHandle,
nil, @Env.Error.FBError) then
Env.Error.CheckError(OwningObj, smongoc_collection_insert);
except
lFailed := True;
raise;
end;
finally
ProcessWriteResult(LastError, False, lFailed);
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TMongoCollection.Insert(AInsert: TMongoInsert; AFlags: TInsertFlags = []);
begin
Insert(AInsert.FinalValuesBSON, AFlags);
end;
{-------------------------------------------------------------------------------}
function TMongoCollection.Insert(AFlags: TInsertFlags = []): TMongoInsert;
begin
Result := TMongoInsert.Create(Env, OwningObj,
procedure(AInsert: TMongoInsert)
begin
try
Insert(AInsert.FinalValuesBSON, AFlags);
finally
FDFree(AInsert);
end;
end
);
end;
{-------------------------------------------------------------------------------}
procedure TMongoCollection.Remove(ASelector: TMongoSelector; AFlags: TRemoveFlags = []);
var
iFlags: mongoc_remove_flags_t;
lFreeSel: Boolean;
lFailed: Boolean;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_bulk_operation_remove_one, ['bulk', FBulkHandle,
'selector', ASelector.FinalMatchBSON.AsJSON]);
end;
procedure Trace2;
begin
Env.Trace(smongoc_bulk_operation_remove, ['bulk', FBulkHandle,
'selector', ASelector.FinalMatchBSON.AsJSON]);
end;
procedure Trace3;
begin
Env.Trace(smongoc_collection_remove, ['collection', Handle,
'flags', iFlags, 'selector', ASelector.FinalMatchBSON.AsJSON]);
end;
{$ENDIF}
begin
lFreeSel := ASelector = nil;
if lFreeSel then
ASelector := TMongoSelector.Create(Env);
// selector handle must be non nil
if ASelector.FMatcher = nil then
ASelector.Match();
try
if IsBulk then
if TRemoveFlag.SingleRemove in AFlags then begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
CLib.Fmongoc_bulk_operation_remove_one(FBulkHandle,
ASelector.FinalMatchBSON.AsReadHandle);
end
else begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace2;
{$ENDIF}
CLib.Fmongoc_bulk_operation_remove(FBulkHandle,
ASelector.FinalMatchBSON.AsReadHandle);
end
else begin
ResetCounts;
lFailed := False;
try
try
iFlags := MONGOC_REMOVE_NONE;
if TRemoveFlag.SingleRemove in AFlags then
iFlags := iFlags or MONGOC_REMOVE_SINGLE_REMOVE;
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace3;
{$ENDIF}
if not CLib.Fmongoc_collection_remove(Handle, iFlags,
ASelector.FinalMatchBSON.AsReadHandle, nil, @Env.Error.FBError) then
Env.Error.CheckError(OwningObj, smongoc_collection_remove);
except
lFailed := True;
raise;
end;
finally
ProcessWriteResult(LastError, False, lFailed);
end;
end;
finally
if lFreeSel then
FDFree(ASelector);
end;
end;
{-------------------------------------------------------------------------------}
function TMongoCollection.Remove(AFlags: TRemoveFlags = []): TMongoSelector;
begin
Result := TMongoSelector.Create(Env, OwningObj,
procedure(ASelector: TMongoSelector)
begin
try
Remove(ASelector, AFlags);
finally
FDFree(ASelector);
end;
end
);
end;
{-------------------------------------------------------------------------------}
procedure TMongoCollection.RemoveAll;
begin
Remove(nil, []);
end;
{-------------------------------------------------------------------------------}
procedure TMongoCollection.Update(AUpdate: TMongoUpdate;
AFlags: TUpdateFlags = [TUpdateFlag.MultiUpdate]);
var
iFlags: mongoc_update_flags_t;
lFailed: Boolean;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_bulk_operation_update_one, ['bulk', FBulkHandle,
'selector', AUpdate.FinalMatchBSON.AsJSON,
'document', AUpdate.FinalModifyBSON.AsJSON,
'upsert', TUpdateFlag.Upsert in AFlags]);
end;
procedure Trace2;
begin
Env.Trace(smongoc_bulk_operation_update, ['bulk', FBulkHandle,
'selector', AUpdate.FinalMatchBSON.AsJSON,
'document', AUpdate.FinalModifyBSON.AsJSON,
'upsert', TUpdateFlag.Upsert in AFlags]);
end;
procedure Trace3;
begin
Env.Trace(smongoc_collection_update, ['collection', Handle, 'flags', iFlags,
'selector', AUpdate.FinalMatchBSON.AsJSON,
'document', AUpdate.FinalModifyBSON.AsJSON]);
end;
{$ENDIF}
begin
if IsBulk then
if not (TUpdateFlag.MultiUpdate in AFlags) then begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
CLib.Fmongoc_bulk_operation_update_one(FBulkHandle, AUpdate.FinalMatchBSON.AsReadHandle,
AUpdate.FinalModifyBSON.AsReadHandle, TUpdateFlag.Upsert in AFlags);
end
else begin
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace2;
{$ENDIF}
CLib.Fmongoc_bulk_operation_update(FBulkHandle, AUpdate.FinalMatchBSON.AsReadHandle,
AUpdate.FinalModifyBSON.AsReadHandle, TUpdateFlag.Upsert in AFlags);
end
else begin
ResetCounts;
lFailed := False;
try
try
iFlags := MONGOC_UPDATE_NONE;
if TUpdateFlag.Upsert in AFlags then
iFlags := iFlags or MONGOC_UPDATE_UPSERT;
if TUpdateFlag.MultiUpdate in AFlags then
iFlags := iFlags or MONGOC_UPDATE_MULTI_UPDATE;
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace3;
{$ENDIF}
if not CLib.Fmongoc_collection_update(Handle, iFlags, AUpdate.FinalMatchBSON.AsReadHandle,
AUpdate.FinalModifyBSON.AsReadHandle, nil, @Env.Error.FBError) then
Env.Error.CheckError(OwningObj, smongoc_collection_update);
except
lFailed := True;
raise;
end;
finally
ProcessWriteResult(LastError, False, lFailed);
end;
end;
end;
{-------------------------------------------------------------------------------}
function TMongoCollection.Update(AFlags: TUpdateFlags = [TUpdateFlag.MultiUpdate]): TMongoUpdate;
begin
Result := TMongoUpdate.Create(Env, OwningObj,
procedure(AUpdate: TMongoUpdate)
begin
try
Update(AUpdate, AFlags);
finally
FDFree(AUpdate);
end;
end
);
end;
{-------------------------------------------------------------------------------}
function TMongoCollection.Count(AQuery: TMongoQuery; AFlags: TMongoQueryFlags = []): Int64;
var
lDestroy: Boolean;
iFlags: mongoc_query_flags_t;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_collection_count, ['collection', Handle,
'flags', iFlags, 'query', AQuery.FinalCountBSON.AsJSON,
'skip', AQuery.FSkip, 'limit', AQuery.FLimit]);
end;
{$ENDIF}
begin
lDestroy := AQuery = nil;
if AQuery = nil then
AQuery := TMongoQuery.Create(Env);
try
iFlags := QF2mqft(AFlags);
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
Result := CLib.Fmongoc_collection_count(Handle, iFlags,
AQuery.FinalCountBSON.AsReadHandle, AQuery.FSkip, AQuery.FLimit,
nil, @Env.Error.FBError);
if Result = -1 then
Env.Error.CheckError(OwningObj);
finally
if lDestroy then
FDFree(AQuery);
end;
end;
{-------------------------------------------------------------------------------}
function TMongoCollection.Count(AFlags: TMongoQueryFlags = []): TMongoQuery;
begin
Result := TMongoQuery.Create(Env, FOwningObj,
function(AQuery: TMongoQuery): Int64
begin
try
Result := Count(AQuery, AFlags);
finally
FDFree(AQuery);
end;
end
);
end;
{-------------------------------------------------------------------------------}
function TMongoCollection.AggregateBase(APipeline: TMongoPipeline;
AReleasePipeline: Boolean; AFlags: TMongoQueryFlags): IMongoCursor;
var
hCrs: Pmongoc_cursor_t;
oReleaseObj: TObject;
iFlags: mongoc_query_flags_t;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_collection_aggregate, ['collection', Handle,
'flags', iFlags, 'pipeline', APipeline.FinalPipelineBSON.AsJSON,
'options', APipeline.FinalOptionsBSON.AsJSON]);
end;
{$ENDIF}
begin
iFlags := QF2mqft(AFlags);
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
hCrs := CLib.Fmongoc_collection_aggregate(Handle, iFlags,
APipeline.FinalPipelineBSON.AsReadHandle, APipeline.FinalOptionsBSON.AsReadHandle, nil);
if hCrs = nil then
Env.Error.CheckError(OwningObj, smongoc_collection_aggregate);
if AReleasePipeline then
oReleaseObj := APipeline
else
oReleaseObj := nil;
Result := TMongoCursor.TDefault.Create(Env, OwningObj, oReleaseObj, hCrs);
end;
{-------------------------------------------------------------------------------}
function TMongoCollection.Aggregate(APipeline: TMongoPipeline;
AFlags: TMongoQueryFlags = []): IMongoCursor;
begin
Result := AggregateBase(APipeline, False, AFlags);
end;
{-------------------------------------------------------------------------------}
function TMongoCollection.Aggregate(AFlags: TMongoQueryFlags = []): TMongoPipeline;
begin
Result := TMongoPipeline.Create(Env, FOwningObj,
function(APipeline: TMongoPipeline): IMongoCursor
begin
Result := AggregateBase(APipeline, True, AFlags);
end
);
end;
{-------------------------------------------------------------------------------}
function TMongoCollection.FindBase(AQuery: TMongoQuery; AReleaseQuery: Boolean;
AFlags: TMongoQueryFlags): IMongoCursor;
var
hCrs: Pmongoc_cursor_t;
oReleaseObj: TObject;
iFlags: mongoc_query_flags_t;
lDestroy: Boolean;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_collection_find, ['collection', Handle, 'flags', iFlags,
'skip', AQuery.FSkip, 'limit', AQuery.FLimit, 'batch_size', AQuery.Options.BatchSize,
'query', AQuery.FinalQueryBSON.AsJSON, 'fields', AQuery.FinalProjectBSON.AsJSON]);
end;
{$ENDIF}
begin
lDestroy := AQuery = nil;
if AQuery = nil then
AQuery := TMongoQuery.Create(Env);
try
iFlags := QF2mqft(AFlags);
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
hCrs := CLib.Fmongoc_collection_find(Handle, iFlags, AQuery.FSkip,
AQuery.FLimit, AQuery.Options.BatchSize, AQuery.FinalQueryBSON.AsReadHandle,
AQuery.FinalProjectBSON.AsReadHandle, nil);
if hCrs = nil then
Env.Error.CheckError(OwningObj, smongoc_collection_find);
if AReleaseQuery then
oReleaseObj := AQuery
else
oReleaseObj := nil;
Result := TMongoCursor.TDefault.Create(Env, OwningObj, oReleaseObj, hCrs);
finally
if lDestroy then
FDFree(AQuery);
end;
end;
{-------------------------------------------------------------------------------}
function TMongoCollection.Find(AQuery: TMongoQuery; AFlags: TMongoQueryFlags = []): IMongoCursor;
begin
Result := FindBase(AQuery, False, AFlags);
end;
{-------------------------------------------------------------------------------}
function TMongoCollection.Find(AFlags: TMongoQueryFlags = []): TMongoQuery;
begin
Result := TMongoQuery.Create(Env, FOwningObj,
function(AQuery: TMongoQuery): IMongoCursor
begin
Result := FindBase(AQuery, True, AFlags);
end
);
end;
{-------------------------------------------------------------------------------}
function TMongoCollection.Command(ACommand: TMongoCommand; AFlags: TMongoQueryFlags = []): IMongoCursor;
var
hCrs: Pmongoc_cursor_t;
iFlags: mongoc_query_flags_t;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_collection_command, ['collection', Handle, 'flags', iFlags,
'skip', ACommand.FSkip, 'limit', ACommand.FLimit, 'batch_size', ACommand.Options.BatchSize,
'command', ACommand.FinalQueryBSON.AsJSON, 'fields', ACommand.FinalProjectBSON.AsJSON]);
end;
{$ENDIF}
begin
iFlags := QF2mqft(AFlags);
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
hCrs := CLib.Fmongoc_collection_command(Handle, iFlags, ACommand.FSkip,
ACommand.FLimit, ACommand.Options.BatchSize, ACommand.FinalQueryBSON.AsReadHandle,
ACommand.FinalProjectBSON.AsReadHandle, nil);
if hCrs = nil then
Env.Error.CheckError(OwningObj, smongoc_collection_command);
Result := TMongoCursor.TDefault.Create(Env, OwningObj, nil, hCrs);
end;
{-------------------------------------------------------------------------------}
function TMongoCollection.Command(const AJSON: String; AFlags: TMongoQueryFlags = []): IMongoCursor;
var
oCmd: TMongoCommand;
begin
oCmd := TMongoCommand.Create(Env, FOwningObj);
try
oCmd.Command(AJSON);
Result := Command(oCmd, AFlags);
finally
FDFree(oCmd);
end;
end;
{-------------------------------------------------------------------------------}
function TMongoCollection.CommandSimple(ACommand: TMongoDocument): TMongoDocument;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Env.Trace(smongoc_collection_command_simple, ['collection', Handle,
'command', ACommand.AsJSON]);
end;
{$ENDIF}
begin
Result := TMongoDocument.Create(Env, OwningObj, Self);
try
{$IFDEF FireDAC_MONITOR}
if Env.Tracing then Trace1;
{$ENDIF}
if not CLib.Fmongoc_collection_command_simple(Handle, ACommand.AsReadHandle,
nil, Result.AsWriteHandle, @Env.Error.FBError) then
Env.Error.CheckError(OwningObj, smongoc_collection_command_simple);
except
FDFree(Result);
raise;
end;
end;
{-------------------------------------------------------------------------------}
function TMongoCollection.CommandSimple(const AJSON: String): TMongoDocument;
var
oCmd: TMongoDocument;
begin
oCmd := TMongoDocument.Create(Env, OwningObj, Self);
try
oCmd.Append(AJSON);
Result := CommandSimple(oCmd);
finally
FDFree(oCmd);
end;
end;
{-------------------------------------------------------------------------------}
function TMongoCollection.Dereference(const AOid: TJsonOid): TMongoDocument;
var
oCrs: IMongoCursor;
begin
oCrs := Find()
.Match
.BeginObject('_id')
.Add('$eq', AOid)
.EndObject
.&End;
Result := TMongoDocument.Create(Env, OwningObj, TObject(nil));
try
if not oCrs.Next(Result) then
FDException(OwningObj, [S_FD_LPhys, Env.CLib.DriverID],
er_FD_MongoDBRefNotFound, [AOid.AsString]);
except
FDFreeAndNil(Result);
raise;
end;
end;
{-------------------------------------------------------------------------------}
function MongoNativeExceptionLoad(const AStorage: IFDStanStorage): TObject;
begin
Result := EMongoNativeException.Create;
EMongoNativeException(Result).LoadFromStorage(AStorage);
end;
{-------------------------------------------------------------------------------}
initialization
FDStorageManager().RegisterClass(EMongoNativeException, 'MongoNativeException',
@MongoNativeExceptionLoad, @FDExceptionSave);
end.
|
unit P_ProjectInfo;
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.ExtCtrls,
Vcl.DBCtrls, Vcl.WinXCtrls, Vcl.Mask, Vcl.Grids, Vcl.DBGrids, Vcl.ToolWin,
Vcl.ComCtrls, Vcl.Buttons, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf,
FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.DataSet,
FireDAC.Comp.Client;
type
TProjectInfo = class(TForm)
Panel1: TPanel;
Label2: TLabel;
First: TSpeedButton;
Prior: TSpeedButton;
Next: TSpeedButton;
Last: TSpeedButton;
Label3: TLabel;
Label4: TLabel;
Label1: TLabel;
Label6: TLabel;
Label7: TLabel;
ToolBar1: TToolBar;
Panel2: TPanel;
ProjectInfoDBGrid: TDBGrid;
DBEdit2: TDBEdit;
DBEdit1: TDBEdit;
Insert: TButton;
Modify: TButton;
Delete: TButton;
Inquiry: TButton;
Save: TButton;
Refresh: TButton;
ProjectInfoSearchBox: TSearchBox;
ProjcetMemberDBGrid: TDBGrid;
DBEdit3: TDBEdit;
DBEdit4: TDBEdit;
Panel3: TPanel;
ProjectInfoDBRadioGroup: TDBRadioGroup;
Cancel: TButton;
FDQuery1: TFDQuery;
DataSource1: TDataSource;
Add: TButton;
Remove: TButton;
ProjectMemberCountFDQuery: TFDQuery;
ProjectInfoDBLookupComboBox: TDBLookupComboBox;
FDQuery1P_ID: TIntegerField;
FDQuery1P_NAME: TWideStringField;
FDQuery1P_STARTDATE: TSQLTimeStampField;
FDQuery1P_ENDDATE: TSQLTimeStampField;
FDQuery1P_MANAGER_ID: TStringField;
FDQuery1P_MEMBERCOUNT: TStringField;
FDQuery1P_STATUS: TIntegerField;
procedure RefreshClick(Sender: TObject);
procedure CancelClick(Sender: TObject);
procedure SaveClick(Sender: TObject);
procedure DeleteClick(Sender: TObject);
procedure ModifyClick(Sender: TObject);
procedure InsertClick(Sender: TObject);
procedure FirstClick(Sender: TObject);
procedure PriorClick(Sender: TObject);
procedure NextClick(Sender: TObject);
procedure LastClick(Sender: TObject);
procedure ProjectInfoSearchBoxChange(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure InquiryClick(Sender: TObject);
procedure DBEdit1KeyPress(Sender: TObject; var Key: Char);
procedure AddClick(Sender: TObject);
procedure RemoveClick(Sender: TObject);
private
{ Private declarations }
procedure UpdateMemberCount(const AddProjectId: Integer);
procedure AddMember(const AddProjectId, AddMemberId: Integer);
public
{ Public declarations }
end;
var
ProjectInfo: TProjectInfo;
implementation
{$R *.dfm}
uses
P_DataModule, P_Department, P_Insa, P_Main, P_ProjectMember;
var
SaveProjectInfo : Boolean;
procedure TProjectInfo.InsertClick(Sender: TObject);
begin
TDataModule.ProjectTable.Insert;
ProjectInfo.DBEdit1.SetFocus;
end;
procedure TProjectInfo.ModifyClick(Sender: TObject);
begin
TDataModule.ProjectTable.Edit;
if MessageDlg('정말 수정하시겠습니까?', mtConfirmation, [mbYes, mbNo],0) = mrYes then
try
TDataModule.ProjectTable.Edit;
except
on e:Exception do
ShowMessage(e.Message);
end;
end;
procedure TProjectInfo.DBEdit1KeyPress(Sender: TObject; var Key: Char);
begin
if key = #13 then
SelectNext(ActiveControl, true, true);
end;
procedure TProjectInfo.DeleteClick(Sender: TObject);
begin
if MessageDlg('정말 삭제하시겠습니까?', mtConfirmation, [mbYes, mbNo],0) = mrYes then
try
TDataModule.ProjectTable.Delete;
except
on e:Exception do
ShowMessage(e.Message);
end;
end;
procedure TProjectInfo.InquiryClick(Sender: TObject);
begin
ProjectInfoDBGrid.DataSource := DataSource1;
Fdquery1.Refresh;
end;
procedure TProjectInfo.RefreshClick(Sender: TObject);
begin
TDataModule.ProjectTable.Refresh;
end;
procedure TProjectInfo.RemoveClick(Sender: TObject);
begin
TDataModule.FDConnection1.StartTransaction;
try
TDataModule.ProjectMemberTable.Delete;
UpdateMemberCount(TDataModule.ProjectMemberTable.FieldByName('P_ID').AsInteger);
TDataModule.FDConnection1.Commit;
except
TDataModule.FDConnection1.Rollback;
end;
end;
procedure TProjectInfo.SaveClick(Sender: TObject);
begin
if SaveProjectInfo then
TDataModule.ProjectTable.Post;
end;
procedure TProjectInfo.UpdateMemberCount(const AddProjectId: Integer);
var
MemberCount: Integer;
begin
ProjectMemberCountFDQuery.Close;
ProjectMemberCountFDQuery.ParamByName('P_ID').AsInteger := AddProjectId;
ProjectMemberCountFDQuery.Open;
MemberCount := ProjectMemberCountFDQuery.Fields[0].AsInteger;
TDataModule.ProjectTable.Edit;
TDataModule.ProjectTable.FieldByName('P_MEMBERCOUNT').AsInteger := MemberCount;
TDataModule.ProjectTable.Post;
end;
procedure TProjectInfo.AddClick(Sender: TObject);
var
ProjectId, MemberId: Integer;
begin
TDataModule.ProjectMemberTable.Create(nil);
try
ProjectMember.ShowModal;
ProjectId := TDataModule.ProjectTable.FieldByName('P_ID').AsInteger;
MemberId := ProjectMember.SelectMemberId;
if MemberId <> -1 then
AddMember(ProjectId, MemberId);
finally
ProjectMember.Free;
end;
end;
procedure TProjectInfo.AddMember(const AddProjectId, AddMemberId: Integer);
var
MbCnt: Integer;
begin
TDataModule.FDConnection1.StartTransaction;
try
TDataModule.ProjectMemberTable.Insert;
TDataModule.ProjectMemberTable.FieldByName('P_ID').AsInteger := AddProjectId;
TDataModule.ProjectMemberTable.FieldByName('M_ID').AsInteger := AddMemberId;
TDataModule.ProjectMemberTable.Post;
UpdateMemberCount(AddProjectId);
TDataModule.FDConnection1.Commit
except
TDataModule.FDConnection1.Rollback;
end;
end;
procedure TProjectInfo.CancelClick(Sender: TObject);
begin
TDataModule.DeptTable.Cancel;
end;
procedure TProjectInfo.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
ProjectInfo := nil;
end;
procedure TProjectInfo.FormShow(Sender: TObject);
begin
DBEdit1.Text := '';
DBEdit2.Text := '';
DBEdit3.Text := '';
DBEdit4.Text := '';
SaveProjectInfo := False;
end;
procedure TProjectInfo.ProjectInfoSearchBoxChange(Sender: TObject);
begin
TDataModule.ProjectTable.IndexFieldNames := 'P_ID';
TDataModule.ProjectTable.IndexFieldNames := 'P_NAME';
TDataModule.ProjectTable.IndexFieldNames := 'P_STARTDATE';
TDataModule.ProjectTable.IndexFieldNames := 'P_ENDDATE';
TDataModule.ProjectTable.IndexFieldNames := 'P_MANAGER_ID';
TDataModule.ProjectTable.IndexFieldNames := 'P_MEMBERCOUNT';
TDataModule.ProjectTable.IndexFieldNames := 'P_STATUS';
TDataModule.ProjectTable.FindNearest([ProjectInfoSearchBox.Text]);
end;
procedure TProjectInfo.FirstClick(Sender: TObject);
begin
FDQuery1.First;
TDataModule.ProjectTable.First;
end;
procedure TProjectInfo.PriorClick(Sender: TObject);
begin
if Not FDQuery1.Bof then
FDQuery1.Prior;
if Not TDataModule.ProjectTable.Bof then
TDataModule.ProjectTable.Prior;
end;
procedure TProjectInfo.NextClick(Sender: TObject);
begin
if Not FDQuery1.Bof then
FDQuery1.Prior;
if Not TDataModule.ProjectTable.Eof then
TDataModule.ProjectTable.Next;
end;
procedure TProjectInfo.LastClick(Sender: TObject);
begin
FDQuery1.Last;
TDataModule.ProjectTable.Last;
end;
end.
|
unit PackBriefFormU;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Db, DBClient, StdCtrls, Grids, DBGrids, ComCtrls, ActnList;
type
TPackBriefForm = class(TForm)
PageControl1: TPageControl;
TabSheet1: TTabSheet;
Button1: TButton;
Button2: TButton;
Button3: TButton;
Button4: TButton;
DBGridNotPacked: TDBGrid;
Label1: TLabel;
Label2: TLabel;
NotPackedDataSet: TClientDataSet;
DataSource1: TDataSource;
PackedDataSet: TClientDataSet;
DataSource2: TDataSource;
DBGridPacked: TDBGrid;
FilterDataSet: TClientDataSet;
ActionList1: TActionList;
PackAction: TAction;
PackAllAction: TAction;
NotPackedAction: TAction;
NotPackedAllAction: TAction;
Button5: TButton;
Button6: TButton;
OKAction: TAction;
CustomerTreeDataSet: TClientDataSet;
procedure FormCreate(Sender: TObject);
procedure NotPackedDataSetFilterRecord(DataSet: TDataSet;
var Accept: Boolean);
procedure PackedDataSetFilterRecord(DataSet: TDataSet;
var Accept: Boolean);
procedure PackActionExecute(Sender: TObject);
procedure NotPackedActionExecute(Sender: TObject);
procedure Resync;
procedure PackAllActionExecute(Sender: TObject);
procedure NotPackedAllActionExecute(Sender: TObject);
procedure PackActionUpdate(Sender: TObject);
procedure NotPackedActionUpdate(Sender: TObject);
procedure PackRecord;
procedure NotPackRecord;
procedure OKActionExecute(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
PackBriefForm: TPackBriefForm;
implementation
uses ClientDataModuleU;
{$R *.DFM}
procedure TPackBriefForm.FormCreate(Sender: TObject);
begin
ClientDataModule.GetCustomersList;
PackedDataSet.CloneCursor(ClientDataModule.CustomerListDataSet, False, True);
NotPackedDataSet.CloneCursor(ClientDataModule.CustomerListDataSet, False, True);
FilterDataSet.FieldDefs.Assign(ClientDataModule.CustomerListDataSet.FieldDefs);
FilterDataSet.CreateDataSet;
//FilterDataSet.EmptyDataSet;
//FilterDataSet.Active := True;
try
CustomerTreeDataSet.LoadFromFile('custtree');
with CustomerTreeDataSet do
begin
First;
while not EOF do
begin
FilterDataSet.AppendRecord([FieldByName('CustNo').AsInteger,
FieldByName('Company').AsString]);
Next;
end;
end;
except
end;
PackedDataSet.OnFilterRecord := PackedDataSetFilterRecord;
PackedDataSet.Active := True;
PackedDataSet.Filtered := True;
NotPackedDataSet.OnFilterRecord := NotPackedDataSetFilterRecord;
NotPackedDataSet.Active := True;
NotPackedDataSet.Filtered := True;
end;
procedure TPackBriefForm.NotPackedDataSetFilterRecord(DataSet: TDataSet;
var Accept: Boolean);
begin
Accept := not FilterDataSet.Active or not FilterDataSet.Locate('CustNo', DataSet.FieldByName('CustNo').AsInteger, []);
end;
procedure TPackBriefForm.PackedDataSetFilterRecord(DataSet: TDataSet;
var Accept: Boolean);
begin
Accept := FilterDataSet.Active and FilterDataSet.Locate('CustNo', DataSet.FieldByName('CustNo').AsInteger, []);
end;
procedure TPackBriefForm.PackActionExecute(Sender: TObject);
var
i: Integer;
begin
with NotPackedDataSet do
begin
if DBGridNotPacked.SelectedRows.Count = 0 then
PackRecord
else
for i := 0 to DBGridNotPacked.SelectedRows.Count - 1 do
begin
Bookmark := DBGridNotPacked.SelectedRows.Items[i];
PackRecord;
end;
end;
Resync;
end;
procedure TPackBriefForm.NotPackedActionExecute(Sender: TObject);
var
i: Integer;
begin
with PackedDataSet do
begin
if DBGridPacked.SelectedRows.Count = 0 then
NotPackRecord
else
for i := 0 to DBGridPacked.SelectedRows.Count - 1 do
begin
Bookmark := DBGridPacked.SelectedRows.Items[i];
NotPackRecord;
end;
end;
Resync;
end;
procedure TPackBriefForm.Resync;
procedure ResyncDataSet(DS: TClientDataSet);
var
R: Integer;
begin
with DS do
begin
R := RecNo;
Filtered := False;
Filtered := True;
if R <= RecordCount then
RecNo := R
else
Last;
end;
end;
begin
ResyncDataSet(PackedDataSet);
DBGridNotPacked.SelectedRows.Clear;
ResyncDataSet(NotpackedDataSet);
DBGridPacked.SelectedRows.Clear;
end;
procedure TPackBriefForm.PackAllActionExecute(Sender: TObject);
begin
with NotPackedDataSet do
begin
First;
while not EOF do
begin
PackRecord;
Next;
end;
end;
Resync;
end;
procedure TPackBriefForm.NotPackedAllActionExecute(Sender: TObject);
begin
with PackedDataSet do
begin
First;
while not EOF do
begin
NotPackRecord;
Next;
end;
end;
Resync;
end;
procedure TPackBriefForm.PackActionUpdate(Sender: TObject);
begin
PackAction.Enabled := NotPackedDataSet.RecordCount > 0;
end;
procedure TPackBriefForm.NotPackedActionUpdate(Sender: TObject);
begin
NotPackedAction.Enabled := PackedDataSet.RecordCount > 0;
end;
procedure TPackBriefForm.PackRecord;
begin
with NotPackedDataSet do
if not FilterDataSet.Locate('CustNo', FieldByName('CustNo').AsInteger, []) then
FilterDataSet.AppendRecord([FieldByName('CustNo').AsInteger,
FieldByName('Company').AsString]);
end;
procedure TPackBriefForm.NotPackRecord;
begin
with PackedDataSet do
if FilterDataSet.Locate('CustNo', FieldByName('CustNo').AsInteger, []) then
FilterDataSet.Delete;
end;
procedure TPackBriefForm.OKActionExecute(Sender: TObject);
begin
Screen.Cursor := crHourGlass;
try
with CustomerTreeDataSet do
begin
Close;
end;
with PackedDataSet do
begin
First;
while not EOF do
begin
ClientDataModule.AddCustomerToBriefcase(CustomerTreeDataSet,
FieldByName('CustNo').AsInteger);
Next;
end;
end;
CustomerTreeDataSet.SaveToFile('custtree');
ClientDataModule.GetPartsList;
ClientDataModule.PartsListDataSet.SaveToFile('partlist');
finally
Screen.Cursor := crDefault;
end;
ModalResult := mrOk;
end;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TDemoClass=class(TObject)
{Un champ bidon qui occupe 1KB}
Field:array[0..1023] of Byte;
constructor Create;
destructor Destroy; override;
procedure doCreate;
procedure doDestroy;
class function NewInstance: TObject; override;
procedure FreeInstance; override;
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
end;
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Button3: TButton;
Button4: TButton;
CheckBox1: TCheckBox;
CheckBox2: TCheckBox;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{ TDemoClass }
{Le code ajouté dans le constructeur est regroupé dans doCreate pour ne pas avoir à passer par l'assembleur
pour l'extraire}
constructor TDemoClass.Create;
begin
doCreate;
end;
{Le code ajouté dans le destructeur est regroupé dans doDestroy pour ne pas avoir à passer par l'assembleur
pour l'extraire}
destructor TDemoClass.Destroy;
begin
doDestroy;
end;
class function TDemoClass.NewInstance: TObject;
begin
ShowMessage('1 - Calling NewInstance'#13' '+IntToStr(InstanceSize)+' Bytes will be allocated');
Result:=inherited NewInstance;
end;
{Le code de doCreate devrait être écrit dans le constructeur, mais ça simplifie l'exemple de le mettre ici}
procedure TDemoClass.doCreate;
begin
ShowMessage('2 - Calling Constructor');
if Form1.CheckBox1.Checked then
raise Exception.Create('Exception raised in constructor');
end;
procedure TDemoClass.AfterConstruction;
begin
ShowMessage('3 - Calling AfterConstruction');
inherited;
end;
procedure TDemoClass.BeforeDestruction;
begin
ShowMessage('4 - Calling BeforeDestruction');
inherited;
end;
{Le code de doDestroy devrait être écrit dans le destructeur, mais ça simplifie l'exemple de le mettre ici}
procedure TDemoClass.doDestroy;
begin
ShowMessage('5 - Calling Destructor');
if Form1.CheckBox2.Checked then
raise Exception.Create('Exception raised in destructor');
end;
procedure TDemoClass.FreeInstance;
begin
ShowMessage('6 - Calling FreeInstance'#13' '+IntToStr(InstanceSize)+' Bytes will be unallocated');
inherited;
end;
{ TForm1 }
{Simulation du code automatiquement généré par Delphi lors de la création "normale" d'un object}
procedure TForm1.Button1Click(Sender: TObject);
var
o:TDemoClass;
tmp:TObject;
begin
tmp:=TDemoClass.NewInstance;
try
TDemoClass(tmp).doCreate;
tmp.AfterConstruction;
except
tmp.Destroy;
raise;
end;
o:=TDemoClass(tmp);
end;
{Création "normale" d'un object}
procedure TForm1.Button2Click(Sender: TObject);
var
o:TDemoClass;
begin
o:=TDemoClass.Create;
end;
{Ce que ne FAIT PAS Delphi: code pour libérer toutes les resources lors de la destruction, même en cas
d'erreur dans le destructeur}
procedure TForm1.Button3Click(Sender: TObject);
var
o:TDemoClass;
begin
o:=TDemoClass.Create;
try
o.BeforeDestruction;
o.doDestroy;
finally
o.FreeInstance;
end;
end;
{Destruction "normale" d'un object: si une exception est levée dans le destructeur, la mémoire occupée par
l'instance (en tout InstanceSize octets, ici au moins 1KB) n'est pas libérée}
procedure TForm1.Button4Click(Sender: TObject);
var
o:TDemoClass;
begin
o:=TDemoClass.Create;
o.Destroy;
end;
end.
|
using System;
using System.Globalization;
using System.Web.Mvc;
namespace $rootnamespace$.Models.Binds
{
public class DecimalModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
ValueProviderResult valueResult = bindingContext.ValueProvider
.GetValue(bindingContext.ModelName);
ModelState modelState = new ModelState { Value = valueResult };
object actualValue = null;
if (!string.IsNullOrEmpty(valueResult.AttemptedValue))
{
try
{
// Tries to figure out how many decimal characters we have after the decimal separator.
string value = valueResult.AttemptedValue;
int decimals = 0;
// Make sure it will break the checking right after discovering how many decimal characters there is after the decimal character.
while (true)
{
if (value[value.Length - 3] == ',' || value[value.Length - 3] == '.')
{
decimals = 2;
break;
}
if (value[value.Length - 4] == ',' || value[value.Length - 4] == '.')
{
decimals = 3;
break;
}
if (value[value.Length - 5] == ',' || value[value.Length - 5] == ',')
{
decimals = 4;
break;
}
break;
}
// Replace all special characters in order to make the proper conversion from the string to the decimal.
string final_value;
final_value = value.Replace(",", "").Replace(".", "");
// Insert the decimal character at the correct position given the ammount of decimal characters we retrieved.
final_value = final_value.Insert(final_value.Length - decimals, ".");
// Converts the actual decimal.
actualValue = Convert.ToDecimal(final_value, CultureInfo.InvariantCulture);
}
catch (FormatException e)
{
modelState.Errors.Add(e);
}
}
bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
return actualValue;
}
}
} |
unit AnimalsForm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
FMX.Layouts, FMX.Memo, AnimalsClasses, FMX.Media, FMX.Controls.Presentation,
FMX.ScrollBox;
type
TForm1 = class(TForm)
Memo1: TMemo;
Button2: TButton;
RadioButton1: TRadioButton;
RadioButton2: TRadioButton;
Panel1: TPanel;
MediaPlayer1: TMediaPlayer;
Button1: TButton;
procedure Button2Click(Sender: TObject);
procedure RadioButton1Change(Sender: TObject);
procedure RadioButton2Change(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
MyAnimal: TAnimal;
public
procedure Show (const msg: string);
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
const
SoundsFolder = '..\..\'; // windows only
procedure TForm1.Button1Click(Sender: TObject);
begin
if MyAnimal is TDog then
Show (TDog(MyAnimal).Eat)
else if MyAnimal is TCat then
Show (TCat(MyAnimal).Eat);
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
Show (MyAnimal.Voice);
MediaPlayer1.FileName := SoundsFolder + MyAnimal.Voice + '.wav';
MediaPlayer1.Play;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
MyAnimal := TCat.Create;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
MyAnimal.Free;
end;
procedure TForm1.RadioButton1Change(Sender: TObject);
begin
MyAnimal.Free;
MyAnimal := TCat.Create;
end;
procedure TForm1.RadioButton2Change(Sender: TObject);
begin
MyAnimal.Free;
MyAnimal := TDog.Create;
end;
procedure TForm1.Show(const Msg: string);
begin
Memo1.Lines.Add(Msg);
end;
end.
|
unit SearchProductByParamValuesQuery;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseQuery, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt,
Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.StdCtrls, StrHelper,
DSWrap;
type
TSearchProductByParamValuesW = class(TDSWrap)
private
FFamilyID: TFieldWrap;
FProductId: TFieldWrap;
public
constructor Create(AOwner: TComponent); override;
property FamilyID: TFieldWrap read FFamilyID;
property ProductId: TFieldWrap read FProductId;
end;
TqSearchProductByParamValues = class(TQueryBase)
private
FW: TSearchProductByParamValuesW;
{ Private declarations }
public
constructor Create(AOwner: TComponent); override;
procedure Execute(AProductCategoryId: Integer);
function GetSQL(AParamSubParamID: Integer; const AParamValues: String): String;
property W: TSearchProductByParamValuesW read FW;
{ Public declarations }
end;
implementation
{$R *.dfm}
constructor TqSearchProductByParamValues.Create(AOwner: TComponent);
begin
inherited;
FW := TSearchProductByParamValuesW.Create(FDQuery);
end;
function TqSearchProductByParamValues.GetSQL(AParamSubParamID: Integer; const
AParamValues: String): String;
begin
Assert(AParamSubParamID > 0);
Assert(not AParamValues.IsEmpty);
Result := FDQuery.SQL.Text.Replace('(0)', AParamSubParamID.ToString);
Result := Result.Replace('(1)', AParamSubParamID.ToString);
Result := Result.Replace('(2)', Format('(%s)', [AParamValues]));
end;
procedure TqSearchProductByParamValues.Execute(AProductCategoryId: Integer);
begin
Assert(AProductCategoryId > 0);
FDQuery.ParamByName('ProductCategoryId').Value := AProductCategoryId;
FDQuery.ExecSQL;
end;
constructor TSearchProductByParamValuesW.Create(AOwner: TComponent);
begin
inherited;
FFamilyID := TFieldWrap.Create(Self, 'FamilyID');
FProductId := TFieldWrap.Create(Self, 'ProductId');
end;
end.
|
unit JWT.RS;
interface
uses System.SysUtils, JWT, ipcrsa, ipctypes;
type
TJWTSigner_RSA = class abstract(TInterfacedObject, IJWTSigner)
private
FCipher: TipcRSA;
protected
class function HashAlgorithm: TipcrsaHashAlgorithms; virtual; abstract;
class function UsePSS: Boolean; virtual; abstract;
function Sign(Key, Input: TBytes): TBytes;
function Validate(Key, Input, Signature: TBytes): Boolean;
public
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
end;
TJWTSigner_RSA256 = class(TJWTSigner_RSA)
protected
class function HashAlgorithm: TipcrsaHashAlgorithms; override;
class function UsePSS: Boolean; override;
end;
TJWTSigner_RSA384 = class(TJWTSigner_RSA)
protected
class function HashAlgorithm: TipcrsaHashAlgorithms; override;
class function UsePSS: Boolean; override;
end;
TJWTSigner_RSA512 = class(TJWTSigner_RSA)
protected
class function HashAlgorithm: TipcrsaHashAlgorithms; override;
class function UsePSS: Boolean; override;
end;
TJWTSigner_RSAPSS256 = class(TJWTSigner_RSA)
protected
class function HashAlgorithm: TipcrsaHashAlgorithms; override;
class function UsePSS: Boolean; override;
end;
TJWTSigner_RSAPSS384 = class(TJWTSigner_RSA)
protected
class function HashAlgorithm: TipcrsaHashAlgorithms; override;
class function UsePSS: Boolean; override;
end;
TJWTSigner_RSAPSS512 = class(TJWTSigner_RSA)
protected
class function HashAlgorithm: TipcrsaHashAlgorithms; override;
class function UsePSS: Boolean; override;
end;
implementation
uses JWKS;
procedure TJWTSigner_RSA.AfterConstruction;
begin
inherited;
FCipher := TipcRSA.Create(nil);
end;
procedure TJWTSigner_RSA.BeforeDestruction;
begin
FCipher.Free;
inherited;
end;
function TJWTSigner_RSA.Sign(Key, Input: TBytes): TBytes;
begin
FCipher.Reset;
FCipher.UsePSS := UsePSS;
FCipher.HashAlgorithm := HashAlgorithm;
FCipher.Key.PrivateKey := TEncoding.ANSI.GetString(Key);
FCipher.InputMessageB := Input;
FCipher.Sign;
Result := FCipher.HashSignatureB;
end;
function TJWTSigner_RSA.Validate(Key, Input, Signature: TBytes): Boolean;
begin
FCipher.Reset;
FCipher.UsePSS := UsePSS;
FCipher.HashAlgorithm := HashAlgorithm;
FCipher.SignerKey.PublicKey := TEncoding.ANSI.GetString(Key);
FCipher.InputMessageB := Input;
FCipher.HashSignatureB := Signature;
Result := FCipher.VerifySignature;
end;
class function TJWTSigner_RSA256.HashAlgorithm: TipcrsaHashAlgorithms;
begin
Result := rhaSHA256;
end;
class function TJWTSigner_RSA384.HashAlgorithm: TipcrsaHashAlgorithms;
begin
Result := rhaSHA384;
end;
class function TJWTSigner_RSA384.UsePSS: Boolean;
begin
Result := False;
end;
class function TJWTSigner_RSA512.HashAlgorithm: TipcrsaHashAlgorithms;
begin
Result := rhaSHA512;
end;
class function TJWTSigner_RSA512.UsePSS: Boolean;
begin
Result := False;
end;
class function TJWTSigner_RSA256.UsePSS: Boolean;
begin
Result := False;
end;
class function TJWTSigner_RSAPSS256.HashAlgorithm: TipcrsaHashAlgorithms;
begin
Result := rhaSHA256;
end;
class function TJWTSigner_RSAPSS256.UsePSS: Boolean;
begin
Result := True;
end;
class function TJWTSigner_RSAPSS384.HashAlgorithm: TipcrsaHashAlgorithms;
begin
Result := rhaSHA384;
end;
class function TJWTSigner_RSAPSS384.UsePSS: Boolean;
begin
Result := True;
end;
class function TJWTSigner_RSAPSS512.HashAlgorithm: TipcrsaHashAlgorithms;
begin
Result := rhaSHA512;
end;
class function TJWTSigner_RSAPSS512.UsePSS: Boolean;
begin
Result := True;
end;
initialization
TJWTSigner.Register(RS256, TJWTSigner_RSA256);
TJWTSigner.Register(RS384, TJWTSigner_RSA384);
TJWTSigner.Register(RS512, TJWTSigner_RSA512);
TJWTSigner.Register(PS256, TJWTSigner_RSAPSS256);
TJWTSigner.Register(PS384, TJWTSigner_RSAPSS384);
TJWTSigner.Register(PS512, TJWTSigner_RSAPSS512);
end.
|
unit BrickCamp.Repositories.TEmployee;
interface
uses
System.JSON,
Spring.Container.Injection,
Spring.Container.Common,
BrickCamp.IDB,
BrickCamp.Model.TEmployee,
BrickCamp.Repositories.IEmployee;
type
TEmployeeRepository = class(TInterfacedObject, IEmployeeRepository)
protected
[Inject]
FDb: IBrickCampDb;
public
function GetOne(const Id: Integer): TEmployee;
function GetList: TJSONArray;
procedure Insert(const Employee: TEmployee);
procedure Update(const Employee: TEmployee);
procedure Delete(const Id: Integer);
end;
implementation
uses
Spring.Collections,
MARS.Core.Utils;
{ TEmployeeRepository }
procedure TEmployeeRepository.Delete(const Id: Integer);
var
Employee: TEmployee;
begin
Employee := FDb.GetSession.FindOne<TEmployee>(Id);
if Assigned(Employee) then
FDb.GetSession.Delete(Employee);
end;
function TEmployeeRepository.GetList: TJSONArray;
var
LList: IList<TEmployee>;
LItem: TEmployee;
begin
LList := FDb.GetSession.FindAll<TEmployee>;
result := TJSONArray.Create;
for LItem in LList do
Result.Add(ObjectToJson(LItem));
end;
function TEmployeeRepository.GetOne(const Id: Integer): TEmployee;
begin
result := FDb.GetSession.FindOne<TEmployee>(Id);
end;
procedure TEmployeeRepository.Insert(const Employee: TEmployee);
begin
FDb.GetSession.Insert(Employee);
end;
procedure TEmployeeRepository.Update(const Employee: TEmployee);
begin
FDb.GetSession.Update(Employee);
end;
end.
|
unit Security.User.Interfaces;
interface
Type
TUserNotifyEvent = procedure(aID: Int64; aName: String; aEmail: String; aActive: Boolean; aPassword: String; aUserID: Integer; aIsUser: Boolean; var aError: string; var aChanged: Boolean) of Object;
TResultNotifyEvent = procedure(const aResult: Boolean = false) of Object;
Type
iPrivateUserEvents = interface
['{3023A08C-1ED5-4A65-B127-1FF9D340EB3B}']
{ Strict private declarations }
procedure setID(Value: Int64);
function getID: Int64;
function getUpdatedAt: TDateTime;
procedure setUpdatedAt(const Value: TDateTime);
procedure setNameUser(Value: String);
function getNameUser: String;
procedure setEmail(Value: String);
function getEmail: String;
procedure setActive(Value: Boolean);
function getActive: Boolean;
procedure setPassword(Value: String);
function getPassword: String;
procedure setMatrixID(Value: Integer);
function getMatrixID: Integer;
procedure setIsMatrix(Value: Boolean);
function getIsMatrix: Boolean;
procedure setOnUser(const Value: TUserNotifyEvent);
function getOnUser: TUserNotifyEvent;
procedure setOnResult(const Value: TResultNotifyEvent);
function getOnResult: TResultNotifyEvent;
end;
iUserViewEvents = interface(iPrivateUserEvents)
['{7F0739A8-F041-4DBB-8A3C-235C8FE5325A}']
{ Published declarations - Properties }
property ID: Int64 read getID write setID;
property UpdatedAt: TDateTime read getUpdatedAt write setUpdatedAt;
property NameUser: String read getNameUser write setNameUser;
property Email: String read getEmail write setEmail;
property Active: Boolean read getActive write setActive;
property Password: String read getPassword write setPassword;
property MatrixID: Integer read getMatrixID write setMatrixID;
property IsMatrix: Boolean read getIsMatrix write setIsMatrix;
{ Published declarations - Events }
property OnUser: TUserNotifyEvent read getOnUser write setOnUser;
property OnResult: TResultNotifyEvent read getOnResult write setOnResult;
end;
iPrivateUserViewProperties = interface
['{E58223C7-8FCF-48C4-B2EB-D93EB6FB84ED}']
{ Private declarations }
function getComputerIP: string;
function getServerIP: string;
function getSigla: string;
function getUpdatedAt: string;
function getVersion: string;
procedure setComputerIP(const Value: string);
procedure setServerIP(const Value: string);
procedure setSigla(const Value: string);
procedure setUpdatedAt(const Value: string);
procedure setVersion(const Value: string);
end;
iUserViewProperties = interface(iPrivateUserViewProperties)
['{487E4F2B-62DD-4353-AC0C-7E43CB4FDA8C}']
{ Public declarations }
property ComputerIP: string read getComputerIP write setComputerIP;
property ServerIP: string read getServerIP write setServerIP;
property Sigla: string read getSigla write setSigla;
property Version: string read getVersion write setVersion;
property UpdatedAt: string read getUpdatedAt write setUpdatedAt;
end;
iUserView = interface
['{134C82E6-CCD9-4C0C-BB57-6A2E978CBEA2}']
// function Properties: iPermissionViewProperties;
function Events: iUserViewEvents;
end;
implementation
end.
|
unit TestThread.Trim.Helper.Partition;
{
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, OS.ProcessOpener, Thread.Trim.Helper.Partition.OS, SysUtils;
type
// Test methods for class TOSPartitionTrimmer
TestTOSPartitionTrimmer = class(TTestCase)
strict private
FOSPartitionTrimmer: TOSPartitionTrimmer;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestParseProgress;
end;
implementation
const
DriveOptimizerString83: String =
'Microsoft Drive Optimizer'#$D#$A +
'Copyright (c) 2013 Microsoft Corp.'#$D#$A#$D#$A +
'다시 잘라내기(Windows (C:)) 호출 중...'#$D#$D#$A#$D#$A#$D#$A +
'1 단계를 수행하는 중'#$D#$A#$D#9 +
'다시 잘라내기: 0% 완료...'#$D#9 +
'다시 잘라내기: 57% 완료...'#$D#9 +
'다시 잘라내기: 58% 완료...'#$D#9 +
'다시 잘라내기: 69% 완료...'#$D#9 +
'다시 잘라내기: 71% 완료...'#$D#9 +
'다시 잘라내기: 72% 완료...'#$D#9 +
'다시 잘라내기: 83% 완료...'#$D#9;
DriveOptimizerString100: String =
'Microsoft Drive Optimizer'#$D#$A +
'Copyright (c) 2013 Microsoft Corp.'#$D#$A#$D#$A +
'다시 잘라내기(Windows (C:)) 호출 중...'#$D#$D#$A#$D#$A#$D#$A +
'1 단계를 수행하는 중'#$D#$A#$D#9 +
'다시 잘라내기: 0% 완료...'#$D#9 +
'다시 잘라내기: 57% 완료...'#$D#9 +
'다시 잘라내기: 58% 완료...'#$D#9 +
'다시 잘라내기: 69% 완료...'#$D#9 +
'다시 잘라내기: 71% 완료...'#$D#9 +
'다시 잘라내기: 72% 완료...'#$D#9 +
'다시 잘라내기: 83% 완료...'#$D#9 +
'다시 잘라내기: 93% 완료...'#$D#9 +
'다시 잘라내기: 100% 완료. '#$D#$A#$D#$A +
'작업을 완료했습니다.'#$D#$A#$D#$A +
'Post Defragmentation Report:'#$D#$A#$D#$D#$A#9 +
'볼륨 정보:'#$D#$A#9#9 +
'볼륨 크기 = 111.34 GB'#$D#$A#9#9 +
'사';
procedure TestTOSPartitionTrimmer.SetUp;
begin
FOSPartitionTrimmer := TOSPartitionTrimmer.Create('');
end;
procedure TestTOSPartitionTrimmer.TearDown;
begin
FOSPartitionTrimmer.Free;
FOSPartitionTrimmer := nil;
end;
procedure TestTOSPartitionTrimmer.TestParseProgress;
begin
FOSPartitionTrimmer.ParseProgress(DriveOptimizerString83);
CheckEquals(83, FOSPartitionTrimmer.Progress);
FOSPartitionTrimmer.ParseProgress(DriveOptimizerString100);
CheckEquals(100, FOSPartitionTrimmer.Progress);
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTOSPartitionTrimmer.Suite);
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.Phys.MSSQLDef;
interface
uses
System.SysUtils, System.Classes, FireDAC.Stan.Intf;
type
// TFDPhysMSSQLConnectionDefParams
// Generated for: FireDAC MSSQL driver
TFDMSSQLVariantFormat = (vfString, vfBinary);
TFDMSSQLMetaCaseInsCat = (mciChoose, mciFalse, mciTrue);
/// <summary> TFDPhysMSSQLConnectionDefParams class implements FireDAC MSSQL driver specific connection definition class. </summary>
TFDPhysMSSQLConnectionDefParams = class(TFDConnectionDefParams)
private
function GetDriverID: String;
procedure SetDriverID(const AValue: String);
function GetODBCAdvanced: String;
procedure SetODBCAdvanced(const AValue: String);
function GetLoginTimeout: Integer;
procedure SetLoginTimeout(const AValue: Integer);
function GetServer: String;
procedure SetServer(const AValue: String);
function GetNetwork: String;
procedure SetNetwork(const AValue: String);
function GetAddress: String;
procedure SetAddress(const AValue: String);
function GetOSAuthent: Boolean;
procedure SetOSAuthent(const AValue: Boolean);
function GetMARS: Boolean;
procedure SetMARS(const AValue: Boolean);
function GetWorkstation: String;
procedure SetWorkstation(const AValue: String);
function GetLanguage: String;
procedure SetLanguage(const AValue: String);
function GetEncrypt: Boolean;
procedure SetEncrypt(const AValue: Boolean);
function GetVariantFormat: TFDMSSQLVariantFormat;
procedure SetVariantFormat(const AValue: TFDMSSQLVariantFormat);
function GetExtendedMetadata: Boolean;
procedure SetExtendedMetadata(const AValue: Boolean);
function GetApplicationName: String;
procedure SetApplicationName(const AValue: String);
function GetMetaDefCatalog: String;
procedure SetMetaDefCatalog(const AValue: String);
function GetMetaDefSchema: String;
procedure SetMetaDefSchema(const AValue: String);
function GetMetaCurCatalog: String;
procedure SetMetaCurCatalog(const AValue: String);
function GetMetaCurSchema: String;
procedure SetMetaCurSchema(const AValue: String);
function GetMetaCaseIns: Boolean;
procedure SetMetaCaseIns(const AValue: Boolean);
function GetMetaCaseInsCat: TFDMSSQLMetaCaseInsCat;
procedure SetMetaCaseInsCat(const AValue: TFDMSSQLMetaCaseInsCat);
published
property DriverID: String read GetDriverID write SetDriverID stored False;
property ODBCAdvanced: String read GetODBCAdvanced write SetODBCAdvanced stored False;
property LoginTimeout: Integer read GetLoginTimeout write SetLoginTimeout stored False;
property Server: String read GetServer write SetServer stored False;
property Network: String read GetNetwork write SetNetwork stored False;
property Address: String read GetAddress write SetAddress stored False;
property OSAuthent: Boolean read GetOSAuthent write SetOSAuthent stored False;
property MARS: Boolean read GetMARS write SetMARS stored False default True;
property Workstation: String read GetWorkstation write SetWorkstation stored False;
property Language: String read GetLanguage write SetLanguage stored False;
property Encrypt: Boolean read GetEncrypt write SetEncrypt stored False;
property VariantFormat: TFDMSSQLVariantFormat read GetVariantFormat write SetVariantFormat stored False default vfString;
property ExtendedMetadata: Boolean read GetExtendedMetadata write SetExtendedMetadata stored False;
property ApplicationName: String read GetApplicationName write SetApplicationName stored False;
property MetaDefCatalog: String read GetMetaDefCatalog write SetMetaDefCatalog stored False;
property MetaDefSchema: String read GetMetaDefSchema write SetMetaDefSchema stored False;
property MetaCurCatalog: String read GetMetaCurCatalog write SetMetaCurCatalog stored False;
property MetaCurSchema: String read GetMetaCurSchema write SetMetaCurSchema stored False;
property MetaCaseIns: Boolean read GetMetaCaseIns write SetMetaCaseIns stored False;
property MetaCaseInsCat: TFDMSSQLMetaCaseInsCat read GetMetaCaseInsCat write SetMetaCaseInsCat stored False default mciChoose;
end;
implementation
uses
FireDAC.Stan.Consts;
// TFDPhysMSSQLConnectionDefParams
// Generated for: FireDAC MSSQL driver
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLConnectionDefParams.GetDriverID: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Common_DriverID];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLConnectionDefParams.SetDriverID(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Common_DriverID] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLConnectionDefParams.GetODBCAdvanced: String;
begin
Result := FDef.AsString[S_FD_ConnParam_ODBC_ODBCAdvanced];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLConnectionDefParams.SetODBCAdvanced(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_ODBC_ODBCAdvanced] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLConnectionDefParams.GetLoginTimeout: Integer;
begin
Result := FDef.AsInteger[S_FD_ConnParam_Common_LoginTimeout];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLConnectionDefParams.SetLoginTimeout(const AValue: Integer);
begin
FDef.AsInteger[S_FD_ConnParam_Common_LoginTimeout] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLConnectionDefParams.GetServer: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Common_Server];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLConnectionDefParams.SetServer(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Common_Server] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLConnectionDefParams.GetNetwork: String;
begin
Result := FDef.AsString[S_FD_ConnParam_MSSQL_Network];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLConnectionDefParams.SetNetwork(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_MSSQL_Network] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLConnectionDefParams.GetAddress: String;
begin
Result := FDef.AsString[S_FD_ConnParam_MSSQL_Address];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLConnectionDefParams.SetAddress(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_MSSQL_Address] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLConnectionDefParams.GetOSAuthent: Boolean;
begin
Result := FDef.AsYesNo[S_FD_ConnParam_Common_OSAuthent];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLConnectionDefParams.SetOSAuthent(const AValue: Boolean);
begin
FDef.AsYesNo[S_FD_ConnParam_Common_OSAuthent] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLConnectionDefParams.GetMARS: Boolean;
begin
if not FDef.HasValue(S_FD_ConnParam_MSSQL_MARS) then
Result := True
else
Result := FDef.AsYesNo[S_FD_ConnParam_MSSQL_MARS];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLConnectionDefParams.SetMARS(const AValue: Boolean);
begin
FDef.AsYesNo[S_FD_ConnParam_MSSQL_MARS] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLConnectionDefParams.GetWorkstation: String;
begin
Result := FDef.AsString[S_FD_ConnParam_MSSQL_Workstation];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLConnectionDefParams.SetWorkstation(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_MSSQL_Workstation] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLConnectionDefParams.GetLanguage: String;
begin
Result := FDef.AsString[S_FD_ConnParam_MSSQL_Language];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLConnectionDefParams.SetLanguage(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_MSSQL_Language] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLConnectionDefParams.GetEncrypt: Boolean;
begin
Result := FDef.AsYesNo[S_FD_ConnParam_MSSQL_Encrypt];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLConnectionDefParams.SetEncrypt(const AValue: Boolean);
begin
FDef.AsYesNo[S_FD_ConnParam_MSSQL_Encrypt] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLConnectionDefParams.GetVariantFormat: TFDMSSQLVariantFormat;
var
s: String;
begin
s := FDef.AsString[S_FD_ConnParam_MSSQL_VariantFormat];
if CompareText(s, 'String') = 0 then
Result := vfString
else if CompareText(s, 'Binary') = 0 then
Result := vfBinary
else
Result := vfString;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLConnectionDefParams.SetVariantFormat(const AValue: TFDMSSQLVariantFormat);
const
C_VariantFormat: array[TFDMSSQLVariantFormat] of String = ('String', 'Binary');
begin
FDef.AsString[S_FD_ConnParam_MSSQL_VariantFormat] := C_VariantFormat[AValue];
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLConnectionDefParams.GetExtendedMetadata: Boolean;
begin
Result := FDef.AsBoolean[S_FD_ConnParam_Common_ExtendedMetadata];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLConnectionDefParams.SetExtendedMetadata(const AValue: Boolean);
begin
FDef.AsBoolean[S_FD_ConnParam_Common_ExtendedMetadata] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLConnectionDefParams.GetApplicationName: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Common_ApplicationName];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLConnectionDefParams.SetApplicationName(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Common_ApplicationName] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLConnectionDefParams.GetMetaDefCatalog: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Common_MetaDefCatalog];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLConnectionDefParams.SetMetaDefCatalog(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Common_MetaDefCatalog] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLConnectionDefParams.GetMetaDefSchema: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Common_MetaDefSchema];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLConnectionDefParams.SetMetaDefSchema(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Common_MetaDefSchema] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLConnectionDefParams.GetMetaCurCatalog: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Common_MetaCurCatalog];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLConnectionDefParams.SetMetaCurCatalog(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Common_MetaCurCatalog] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLConnectionDefParams.GetMetaCurSchema: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Common_MetaCurSchema];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLConnectionDefParams.SetMetaCurSchema(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Common_MetaCurSchema] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLConnectionDefParams.GetMetaCaseIns: Boolean;
begin
Result := FDef.AsBoolean[S_FD_ConnParam_Common_MetaCaseIns];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLConnectionDefParams.SetMetaCaseIns(const AValue: Boolean);
begin
FDef.AsBoolean[S_FD_ConnParam_Common_MetaCaseIns] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLConnectionDefParams.GetMetaCaseInsCat: TFDMSSQLMetaCaseInsCat;
var
s: String;
begin
s := FDef.AsString[S_FD_ConnParam_MSSQL_MetaCaseInsCat];
if CompareText(s, 'Choose') = 0 then
Result := mciChoose
else if CompareText(s, 'False') = 0 then
Result := mciFalse
else if CompareText(s, 'True') = 0 then
Result := mciTrue
else
Result := mciChoose;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSSQLConnectionDefParams.SetMetaCaseInsCat(const AValue: TFDMSSQLMetaCaseInsCat);
const
C_MetaCaseInsCat: array[TFDMSSQLMetaCaseInsCat] of String = ('Choose', 'False', 'True');
begin
FDef.AsString[S_FD_ConnParam_MSSQL_MetaCaseInsCat] := C_MetaCaseInsCat[AValue];
end;
end.
|
{ Module of routines that deal with showing a message to the user and
* getting his response.
}
module gui_message;
define gui_message;
define gui_message_str;
define gui_message_msg;
define gui_message_msg_stat;
%include 'gui2.ins.pas';
type
butt_t = record {data about one user-selectable button}
lx, rx, by, ty: real; {button area, including border}
str: string_var80_t; {button text}
on: boolean; {button is enabled}
end;
message_t = record {private data for displaying message to user}
tparm: rend_text_parms_t; {text control parameters, TORG = UM}
msg: string_list_t; {list of message text lines}
tx, ty: real; {top message text line anchor point}
tby: real; {bottom Y of text region}
col_back: rend_rgb_t; {background color}
col_fore: rend_rgb_t; {foreground color}
butt_yes: butt_t; {info about YES button}
butt_no: butt_t; {info about NO button}
butt_abort: butt_t; {info about ABORT button}
end;
{
*************************************************************************
*
* GUI_MESSAGE_DRAW (WIN, M)
*
* This is the official draw routine for the message window. M is the
* private data for this message.
}
procedure gui_message_draw ( {official draw routine for message window}
in out win: gui_win_t; {window to draw}
in out m: message_t); {private data for this message}
val_param; internal;
var
tp: rend_text_parms_t; {local copy of text control parameters}
{
*****************************
*
* Local subroutine BUTTON (B)
* This routine is local to GUI_MESSAGE_DRAW.
*
* Draw the button B, if enabled. The text parameters must already be set,
* including TORG = MID.
}
procedure button ( {draw button, if enabled}
in b: butt_t); {button descriptor}
val_param;
begin
if not b.on then return; {button is disabled ?}
if gui_win_clip (win, b.lx, b.rx, b.by, b.ty) then begin {not all clipped off ?}
rend_set.rgb^ (0.80, 0.80, 0.80); {button background color}
rend_prim.clear_cwind^; {clear button to background color}
rend_set.rgb^ (0.0, 0.0, 0.0); {set border color}
rend_set.cpnt_2d^ (b.lx + 1.4, b.by + 1.4); {draw button inner border}
rend_prim.vect_2d^ (b.lx + 1.4, b.ty - 1.4);
rend_prim.vect_2d^ (b.rx - 1.4, b.ty - 1.4);
rend_prim.vect_2d^ (b.rx - 1.4, b.by + 1.4);
rend_prim.vect_2d^ (b.lx + 1.4, b.by + 1.4);
rend_set.cpnt_2d^ ( {go to button center}
(b.lx + b.rx) * 0.5, (b.by + b.ty) * 0.5);
rend_prim.text^ (b.str.str, b.str.len); {draw the button text}
end;
end;
{
*****************************
*
* Start of GUI_MESSAGE_DRAW.
}
begin
rend_set.rgb^ (m.col_back.red, m.col_back.grn, m.col_back.blu); {clear background}
rend_prim.clear_cwind^;
tp := m.tparm; {make local copy of text parameters}
rend_set.rgb^ (0.0, 0.0, 0.0); {set border color}
rend_set.cpnt_2d^ (0.4, 0.4); {draw outer window border}
rend_prim.vect_2d^ (0.4, win.rect.dy - 0.4);
rend_prim.vect_2d^ (win.rect.dx - 0.4, win.rect.dy - 0.4);
rend_prim.vect_2d^ (win.rect.dx - 0.4, 0.4);
rend_prim.vect_2d^ (0.4, 0.4);
{
* Draw the message text lines.
}
if gui_win_clip (win, 1.0, win.rect.dx - 1.0, m.tby, win.rect.dy - 1.0) then begin
rend_set.text_parms^ (tp);
rend_set.cpnt_2d^ (m.tx, m.ty); {go to first line anchor point}
rend_set.rgb^ (m.col_fore.red, m.col_fore.red, m.col_fore.red); {text color}
string_list_pos_abs (m.msg, 1); {init to first text line}
while m.msg.str_p <> nil do begin {once for each message text line}
rend_prim.text^ (m.msg.str_p^.str, m.msg.str_p^.len); {draw this text line}
string_list_pos_rel (m.msg, 1); {advance to next text line}
end; {back to do this next text line}
end;
{
* Draw the buttons.
}
tp.start_org := rend_torg_mid_k; {anchor to middle of text string}
rend_set.text_parms^ (tp); {set text parameters for buttons}
button (m.butt_yes); {draw the buttons, if enabled}
button (m.butt_no);
button (m.butt_abort);
end;
{
*************************************************************************
*
* Subroutine GUI_MESSAGE (PARENT, MSTR, COL_BACK, COL_FORE,
* BUTT_TRUE, BUTT_FALSE, BUTT_ABORT, RESP)
*
* This is the low level "worker" routine for displaying a message to the
* user and getting some sort of yes/no, true/false response. The call
* arguments are:
*
* PARENT - Parent window to display message box within.
*
* MSTR - The messag to display. This will automatically be wrapped onto
* multiple lines to fit within the window width.
*
* COL_BACK, COL_FORE - Background and foreground colors. The foreground
* color will be used to draw the message text on top of an area previously
* cleared to the background color.
*
* BUTT_TRUE, BUTT_FALSE, BUTT_ABORT - Text for the three types of action
* buttons supported. An empty string causes that button to not be
* drawn. These three buttons correspond to the yes/no/abort
* GUI_MSGRESP_K_T returned response.
*
* RESP - Returned response. Note that the ABORT response is always possible
* even if an abort button is not supplied. The ABORT response is returned
* whenever an event is encountered that is not explicitly handled by
* this routine. The event is pushed back onto the event queue and
* RESP is set to GUI_MSGRESP_ABORT_K. Often the ABORT response will be
* interpreted the same as the NO or FALSE response.
*
* The displayed message box is always erased before this routine returns.
}
procedure gui_message ( {low level routine to display message to user}
in out parent: gui_win_t; {window to display message box within}
in mstr: univ string_var_arg_t; {string to display, will be wrapped at blanks}
in col_back: rend_rgb_t; {background color}
in col_fore: rend_rgb_t; {foreground (text) color}
in butt_true: univ string_var_arg_t; {text for TRUE button, may be empty}
in butt_false: univ string_var_arg_t; {text for FALSE button, may be empty}
in butt_abort: univ string_var_arg_t; {text for ABORT button, may be empty}
out resp: gui_msgresp_k_t); {TRUE/FALSE/ABORT response from user}
val_param;
var
lspace: real; {size of vertical gap between text lines}
thigh: real; {height of raw text lines}
space: real; {width of space character}
m: message_t; {private data for this message}
win: gui_win_t; {private window for this message}
bv, up, ll: vect_2d_t; {text string size and position parameters}
nbutt: sys_int_machine_t; {number of enabled buttons}
htext, hbutt: real; {heights of text and button areas}
hjbutt: real; {height of just a button}
height: real; {height needed for whole window}
f: real; {scratch floating point number}
x: real; {scratc X coordinate}
rend_level: sys_int_machine_t; {initial RENDlib graphics mode level}
ev: rend_event_t; {event descriptor}
p: vect_2d_t; {scratch 2D coordinate}
pnt: vect_2d_t; {pointer coordinate in our window space}
xb, yb, ofs: vect_2d_t; {save copy of old RENDlib 2D transform}
n: sys_int_machine_t; {scratch counter}
modk: rend_key_mod_t; {modifier keys}
kid: gui_key_k_t; {key ID}
c: char; {scratch character}
label
event_next, leave_hit, leave_abort, leave;
{
*****************************
*
* Local subroutine INIT_BUTTON (B, NAME)
* This routine is local to GUI_MESSAGE.
*
* Init the button descriptor B. The displayed button text is NAME.
* B.RX will be set to the required width to display the button.
}
procedure init_button ( {initialize button descriptor}
in out b: butt_t; {button descriptor to initialize}
in name: univ string_var_arg_t); {button text, may be empty}
val_param;
var
bv, up, ll: vect_2d_t; {text string size and position parameters}
begin
b.str.max := size_char(b.str.str); {init var strings}
string_copy (name, b.str); {save button text}
if b.str.len <= 0
then begin {no name string, disable this button}
b.on := false; {this button is disabled}
b.rx := 0.0; {button requires no width to draw}
end
else begin {the button will be enabled}
b.on := true; {enable the button}
rend_get.txbox_txdraw^ ( {measure button text string}
b.str.str, b.str.len, {string and string length}
bv, up, ll); {returned string metrics}
b.rx := bv.x + space + 2.0; {width is text, space, and border widths}
b.rx := trunc(b.rx + 0.9); {round to whole pixel width}
end
;
b.lx := 0.0;
b.by := 0.0;
b.ty := 0.0;
end;
{
*****************************
*
* Start of routine GUI_MESSAGE.
}
begin
rend_dev_set (parent.all_p^.rend_dev); {make sure right RENDlib device is current}
rend_get.enter_level^ (rend_level); {save initial graphics mode level}
rend_set.enter_rend^; {make sure we are in graphics mode}
rend_get.text_parms^ (m.tparm); {save current text parameters}
m.tparm.rot := 0.0; {set some required parameters}
m.tparm.end_org := rend_torg_down_k;
rend_set.text_parms^ (m.tparm); {update the current text state}
lspace := m.tparm.size * m.tparm.lspace; {vertical gap between lines}
thigh := m.tparm.size * m.tparm.height; {character cell height}
rend_get.txbox_txdraw^ ( {measure space char}
' ', 1, {string and string length to measure}
bv, up, ll); {returned string metrics}
space := bv.x; {save width of space character}
nbutt := 0; {init number of enabled buttons}
init_button (m.butt_yes, butt_true);
if m.butt_yes.on then nbutt := nbutt + 1;
init_button (m.butt_no, butt_false);
if m.butt_no.on then nbutt := nbutt + 1;
init_button (m.butt_abort, butt_abort);
if m.butt_abort.on then nbutt := nbutt + 1;
{
* Create our private window. This will be originally made the same size
* as the parent window. It will later be adjusted. This allows using
* the window's dynamic memory context for allocating associated memory.
}
gui_win_child ( {create private window for the message}
win, {window to create}
parent, {parent window}
2.0, 0.0, {lower left corner}
parent.rect.dx - 4.0, parent.rect.dy); {displacement to opposite corner}
string_list_init (m.msg, win.mem_p^); {create message lines list}
gui_string_wrap ( {wrap message text into separate lines}
mstr, {text string to wrap}
win.rect.dx - 2.0 - space, {width to wrap lines to}
m.msg); {returned list of separate lines}
{
* Find desired height of message window and adjust its size and position.
}
htext := {height of text area}
thigh * m.msg.n + {height of all the text lines}
lspace * (m.msg.n + 1); {gaps around text lines}
htext := trunc(htext + 0.9); {round text area height to whole pixels}
hjbutt := {height of just a button}
4.0 + {borders}
thigh + {one line of text}
2.0 * lspace * 0.6; {space above and below label text}
hjbutt := trunc(hjbutt + 0.9); {round button height to whole pixels}
if nbutt = 0
then begin {no buttons}
hbutt := 0.0;
end
else begin {buttons are present}
hbutt := hjbutt + lspace * 0.5; {raw button plus space below it}
end
;
hbutt := trunc(hbutt + 0.9); {round button area height to whole pixels}
height := htext + hbutt + 2.0; {whole window height, including border}
gui_win_resize ( {adjust message window size and position}
win, {window to adjust}
2.0, {left edge X}
trunc((parent.rect.dy - height) * 0.5), {bottom Y}
parent.rect.dx - 4.0, {width}
height); {height}
{
* Fill in the rest of the message object.
}
if m.msg.n <= 1
then begin {only one message line, center it}
m.tx := win.rect.dx * 0.5;
m.tparm.start_org := rend_torg_um_k;
end
else begin {multiple message lines, left justify}
m.tx := 1.0 + space * 0.5;
m.tparm.start_org := rend_torg_ul_k;
end
;
m.ty := win.rect.dy - lspace; {Y of top of top text line}
m.tby := win.rect.dy - htext; {bottom Y of text area}
m.col_back := col_back; {save background color}
m.col_fore := col_fore; {save foreground color}
m.butt_yes.ty := m.tby; {set button top}
m.butt_yes.by := m.butt_yes.ty - hjbutt; {set button bottom}
m.butt_no.ty := m.butt_yes.ty; {copy Y coordinates to the other buttons}
m.butt_no.by := m.butt_yes.by;
m.butt_abort.ty := m.butt_yes.ty;
m.butt_abort.by := m.butt_yes.by;
f := m.butt_yes.rx + m.butt_no.rx + m.butt_abort.rx; {width of all the buttons}
f := (win.rect.dx - f) / (nbutt + 1); {width of gaps around buttons}
f := max(0.0, f); {never less than no space at all}
x := 0.0; {init starting coordinate}
if m.butt_yes.on then begin {YES button enabled, set coordinates ?}
m.butt_yes.lx := x + f; {init left edge}
m.butt_yes.lx := trunc(m.butt_yes.lx + 0.5); {snap to pixel boundary}
m.butt_yes.rx := m.butt_yes.lx + m.butt_yes.rx; {find button right edge}
x := m.butt_yes.rx; {update current X accross}
end;
if m.butt_no.on then begin {NO button enabled, set coordinates ?}
m.butt_no.lx := x + f; {init left edge}
m.butt_no.lx := trunc(m.butt_no.lx + 0.5); {snap to pixel boundary}
m.butt_no.rx := m.butt_no.lx + m.butt_no.rx; {find button right edge}
x := m.butt_no.rx; {update current X accross}
end;
if m.butt_abort.on then begin {ABORT button enabled, set coordinates ?}
m.butt_abort.lx := x + f; {init left edge}
m.butt_abort.lx := trunc(m.butt_abort.lx + 0.5); {snap to pixel boundary}
m.butt_abort.rx := m.butt_abort.lx + m.butt_abort.rx; {find button right edge}
end;
{
* All the configuration state has been set. Now draw the window.
}
gui_win_set_app_pnt (win, addr(m)); {set private data to pass to draw routine}
gui_win_set_draw (win, univ_ptr(addr(gui_message_draw))); {set draw routine}
gui_win_draw_all (win); {draw the window}
gui_win_xf2d_set (win); {set RENDlib 2D space to our private window}
{
* Event loop. Back here for each new event until abort or button select.
}
event_next: {back here to get each new event}
rend_set.enter_level^ (0); {make sure not in graphics mode}
rend_event_get (ev); {get the next event}
case ev.ev_type of {what kind of event is this ?}
{
************************************************
*
* Event POINTER MOTION
}
rend_ev_pnt_move_k: ; {pointer movement is ignored}
{
************************************************
*
* Event KEY
}
rend_ev_key_k: begin {a key just transitioned}
if not ev.key.down then goto event_next; {ignore key releases}
modk := ev.key.modk; {get modifier keys}
if rend_key_mod_alt_k in modk {ALT active, this key not for us ?}
then goto leave_abort;
kid := gui_key_k_t(ev.key.key_p^.id_user); {make GUI library ID for this key}
modk := modk - [rend_key_mod_shiftlock_k]; {ignore shift lock}
p.x := ev.key.x;
p.y := ev.key.y;
rend_set.enter_rend^; {make sure in graphics mode}
rend_get.bxfpnt_2d^ (p, pnt); {PNT is pointer coordinate in our space}
case kid of {which one of our keys is it ?}
gui_key_mouse_left_k: begin {LEFT MOUSE BUTTON}
if {pointer outside our area ?}
(pnt.x < 0.0) or (pnt.x > win.rect.dx) or
(pnt.y < 0.0) or (pnt.y > win.rect.dy)
then begin
goto leave_abort; {this event is for someone else}
end;
if modk <> [] then goto event_next;
if nbutt = 0 then begin {no buttons active ?}
resp := gui_msgresp_abort_k; {left click dismisses the message}
goto leave_hit;
end;
if {hit YES button ?}
m.butt_yes.on and {button is enabled ?}
(pnt.x >= m.butt_yes.lx) and (pnt.x <= m.butt_yes.rx) and {inside butt area ?}
(pnt.y >= m.butt_yes.by) and (pnt.y <= m.butt_yes.ty)
then begin
resp := gui_msgresp_yes_k;
goto leave_hit;
end;
if {hit NO button ?}
m.butt_no.on and {button is enabled ?}
(pnt.x >= m.butt_no.lx) and (pnt.x <= m.butt_no.rx) and {inside butt area ?}
(pnt.y >= m.butt_no.by) and (pnt.y <= m.butt_no.ty)
then begin
resp := gui_msgresp_no_k;
goto leave_hit;
end;
if {hit ABORT button ?}
m.butt_abort.on and {button is enabled ?}
(pnt.x >= m.butt_abort.lx) and (pnt.x <= m.butt_abort.rx) and {inside butt area ?}
(pnt.y >= m.butt_abort.by) and (pnt.y <= m.butt_abort.ty)
then begin
resp := gui_msgresp_abort_k;
goto leave_hit;
end;
goto event_next; {not hit button, ignore mouse click}
end;
gui_key_mouse_right_k: begin {RIGHT MOUSE BUTTON}
if {pointer outside our area ?}
(pnt.x < 0.0) or (pnt.x > win.rect.dx) or
(pnt.y < 0.0) or (pnt.y > win.rect.dy)
then begin
goto leave_abort; {this event is for someone else}
end;
end;
gui_key_esc_k: begin {ESCAPE key}
if modk <> [] then goto event_next;
resp := gui_msgresp_abort_k;
goto leave_hit;
end;
gui_key_enter_k: begin {ENTER key}
if modk <> [] then goto event_next;
if m.butt_yes.on then begin
resp := gui_msgresp_yes_k;
goto leave_hit;
end;
if m.butt_no.on then begin
resp := gui_msgresp_no_k;
goto leave_hit;
end;
resp := gui_msgresp_abort_k;
goto leave_hit;
end;
gui_key_char_k: begin {character key}
c := gui_event_char (ev); {get character represented by key event}
c := string_upcase_char (c); {make upper case for matching}
n := 0; {init number of buttons matched to this char}
if {matches first char of YES button ?}
m.butt_yes.on and {the button is enabled ?}
(string_upcase_char (m.butt_yes.str.str[1]) = c) {matches first character ?}
then begin
resp := gui_msgresp_yes_k;
n := n + 1;
end;
if {matches first char of NO button ?}
m.butt_no.on and {the button is enabled ?}
(string_upcase_char (m.butt_no.str.str[1]) = c) {matches first character ?}
then begin
resp := gui_msgresp_no_k;
n := n + 1;
end;
if {matches first char of ABORT button ?}
m.butt_abort.on and {the button is enabled ?}
(string_upcase_char (m.butt_abort.str.str[1]) = c) {matches first character ?}
then begin
resp := gui_msgresp_abort_k;
n := n + 1;
end;
if n = 1 then goto leave_hit; {char uniquely matches a single button ?}
end;
end; {end of key ID cases}
end; {end of event KEY case}
{
************************************************
*
* Event WIPED_RECT
}
rend_ev_wiped_rect_k: begin {rectangular region needs redraw}
gui_win_draw ( {redraw a region}
win.all_p^.root_p^, {redraw from the root window down}
ev.wiped_rect.x, {left X}
ev.wiped_rect.x + ev.wiped_rect.dx, {right X}
win.all_p^.root_p^.rect.dy - ev.wiped_rect.y - ev.wiped_rect.dy, {bottom Y}
win.all_p^.root_p^.rect.dy - ev.wiped_rect.y); {top Y}
end;
{
************************************************
}
otherwise {any event type we don't explicitly handle}
goto leave_abort;
end; {end of event type cases}
goto event_next; {back to process next event}
{
* The last event can not be handled by this routine. It will be pushed
* back onto the event queue for some other routine to handle. We will
* return with the ABORT response.
}
leave_abort:
resp := gui_msgresp_abort_k; {as if ABORT button hit}
if ev.ev_type <> rend_ev_none_k then begin {there is an event ?}
rend_event_push (ev); {push event back onto queue}
end;
goto leave;
{
* A button was hit. RESP is already set.
}
leave_hit:
goto leave;
{
* Common exit point.
}
leave:
gui_win_delete (win); {delete private window for this message}
rend_set.xform_2d^ (xb, yb, ofs); {restore original 2D transform}
rend_set.enter_level^ (rend_level); {restore original graphics level}
end;
{
*************************************************************************
*
* Function GUI_MESSAGE_STR (PARENT, MSGTYPE, MSTR)
*
* Display a message and wait for user response. PARENT is the parent window
* to display the message box within. MSGTYPE selects one of several
* pre-defined message types. The message type selects the colors, which
* of the YES/NO/ABORT buttons are enabled, and the text to appear for
* each enabled button. MSTR is the message to display to the user. It
* will be wrapped onto multiple lines as needed.
*
* The function returns one of these values:
*
* GUI_MSGRESP_YES_K - The user picked the yes or otherwise affirmative choice.
*
* GUI_MSGRESP_NO_K - The user picked the no or otherwise negative choice.
*
* GUI_MSGRESP_ABORT_K - The user explicitly aborted the operation or an
* event occurred that caused an implicit abort.
}
function gui_message_str ( {display message and get user response}
in out parent: gui_win_t; {window to display message box within}
in msgtype: gui_msgtype_k_t; {overall type or intent of message}
in mstr: univ string_var_arg_t) {string to display, will be wrapped at blanks}
:gui_msgresp_k_t; {TRUE/FALSE/ABORT response from user}
val_param;
var
cback, cfore: rend_rgb_t; {background and foreground colors}
by, bn, ba: string_var80_t; {YES, NO, and ABORT button labels}
resp: gui_msgresp_k_t; {response from user}
begin
by.max := size_char(by.str); {init local var strings}
bn.max := size_char(bn.str);
ba.max := size_char(ba.str);
by.len := 0; {init all buttons to disabled}
bn.len := 0;
ba.len := 0;
case msgtype of {what type of message is this ?}
gui_msgtype_info_k: begin {informational, user must acknoledge}
cback.red := 0.15;
cback.grn := 0.6;
cback.blu := 0.15;
cfore.red := 1.0;
cfore.grn := 1.0;
cfore.blu := 1.0;
string_f_message (by, 'gui', 'button_ok', nil, 0);
end;
gui_msgtype_infonb_k: begin {info text only, no buttons, user must cancel}
cback.red := 0.15;
cback.grn := 0.6;
cback.blu := 0.15;
cfore.red := 1.0;
cfore.grn := 1.0;
cfore.blu := 1.0;
end;
gui_msgtype_yesno_k: begin {user must make yes/no choice}
cback.red := 0.40;
cback.grn := 0.75;
cback.blu := 0.40;
cfore.red := 0.0;
cfore.grn := 0.0;
cfore.blu := 0.0;
string_f_message (by, 'gui', 'button_yes', nil, 0);
string_f_message (bn, 'gui', 'button_no', nil, 0);
end;
gui_msgtype_todo_k: begin {user must perform some action}
cback.red := 0.15;
cback.grn := 0.15;
cback.blu := 0.75;
cfore.red := 1.0;
cfore.grn := 1.0;
cfore.blu := 1.0;
string_f_message (by, 'gui', 'button_done', nil, 0);
string_f_message (ba, 'gui', 'button_abort', nil, 0);
end;
gui_msgtype_prob_k: begin {problem occurred, can continue}
cback.red := 0.75;
cback.grn := 0.40;
cback.blu := 0.15;
cfore.red := 1.0;
cfore.grn := 1.0;
cfore.blu := 1.0;
string_f_message (by, 'gui', 'button_continue', nil, 0);
string_f_message (ba, 'gui', 'button_abort', nil, 0);
end;
gui_msgtype_err_k: begin {error occurred, must abort operation}
cback.red := 0.75;
cback.grn := 0.15;
cback.blu := 0.15;
cfore.red := 1.0;
cfore.grn := 1.0;
cfore.blu := 1.0;
string_f_message (ba, 'gui', 'button_abort', nil, 0);
end;
otherwise {unexpected message type}
gui_message_str := gui_msgresp_abort_k;
return;
end; {end of message type cases}
gui_message ( {call low level routine to do the work}
parent, {parent window to draw message within}
mstr, {message string}
cback, {background color}
cfore, {foreground color}
by, bn, ba, {YES, NO, and ABORT button labels, if any}
resp); {returned response from user}
gui_message_str := resp; {pass back response from user}
end;
{
*************************************************************************
*
* Function GUI_MESSAGE_MSG (PARENT, MSGTYPE, SUBSYS, MSG, PARMS, N_PARMS)
*
* Just like funtion GUI_MESSAGE_STR, except that the message text is
* specified as an MSG file message instead of a string. SUBSYS, MSG, PARMS,
* and N_PARMS are the usual parameters for specifying an MSG file message.
}
function gui_message_msg ( {display message and get user response}
in out parent: gui_win_t; {window to display message box within}
in msgtype: gui_msgtype_k_t; {overall type or intent of message}
in subsys: string; {name of subsystem, used to find message file}
in msg: string; {message name withing subsystem file}
in parms: univ sys_parm_msg_ar_t; {array of parameter descriptors}
in n_parms: sys_int_machine_t) {number of parameters in PARMS}
:gui_msgresp_k_t; {TRUE/FALSE/ABORT response from user}
val_param;
var
str: string_var8192_t; {message string}
begin
str.max := size_char(str.str); {init local var string}
string_f_message (str, subsys, msg, parms, n_parms); {expand message to string}
gui_message_msg := gui_message_str ( {call lower routine to do the work}
parent, {parent window to display message in}
msgtype, {message type}
str); {message string}
end;
{
*************************************************************************
*
* Function GUI_MESSAGE_MSG_STAT (PARENT, MSGTYPE,
* STAT, SUBSYS, MSG, PARMS, N_PARMS)
*
* Just like funtion GUI_MESSAGE_MSG, except that the message associated
* with STAT is also displayed. SUBSYS, MSG, PARMS, and N_PARMS are the
* usual parameters for specifying an MSG file message.
}
function gui_message_msg_stat ( {display err and user message, get response}
in out parent: gui_win_t; {window to display message box within}
in msgtype: gui_msgtype_k_t; {overall type or intent of message}
in stat: sys_err_t; {error status code}
in subsys: string; {name of subsystem, used to find message file}
in msg: string; {message name withing subsystem file}
in parms: univ sys_parm_msg_ar_t; {array of parameter descriptors}
in n_parms: sys_int_machine_t) {number of parameters in PARMS}
:gui_msgresp_k_t; {YES/NO/ABORT response from user}
val_param;
var
str: string_var8192_t; {message string}
s: string_var8192_t; {scratch string for building message string}
begin
str.max := size_char(str.str); {init local var strings}
s.max := size_char(s.str);
sys_error_string (stat, str); {init overall message with STAT message}
string_f_message (s, subsys, msg, parms, n_parms); {get caller message string}
if (str.len > 0) and (s.len > 0) then begin {have both STAT and caller message ?}
string_appendn (str, ''(10)(10), 2); {leave blank line between the two messages}
end;
string_append (str, s); {add on caller message expansion string}
gui_message_msg_stat := gui_message_str ( {call lower routine to do the work}
parent, {parent window to display message in}
msgtype, {message type}
str); {message string}
end;
|
unit ltr35api;
interface
uses SysUtils, ltrapitypes, ltrapidefine, ltrapi;
const
// Размер строки с именем модуля в структуре #TINFO_LTR35
LTR35_NAME_SIZE = 8;
// Размер строки с серийным номером модуля в структуре #TINFO_LTR35
LTR35_SERIAL_SIZE = 16;
// Количество каналов ЦАП
LTR35_DAC_CHANNEL_CNT = 8;
// Количество выходов для каждого канала ЦАП
LTR35_DAC_CH_OUTPUTS_CNT = 2;
// Максимальное количество цифровых линий
LTR35_DOUT_LINES_MAX_CNT = 16;
// Номер канала, соответствующий выводу на цифровые линии (если считать от 0)
LTR35_CH_NUM_DIGOUTS = 8;
// Максимальное количество отсчетов в странице ЦАП в режиме циклического автогенератора
LTR35_MAX_POINTS_PER_PAGE = (4*1024*1024);
// Количество арифметических синусоидальных генераторов в модуле
LTR35_ARITH_SRC_CNT = 4;
// Максимальное значение частоты преобразования ЦАП, которое можно установить
LTR35_DAC_FREQ_MAX = 192000;
// Минимальное значение частоты преобразования ЦАП, которое можно установить
LTR35_DAC_FREQ_MIN = 72000;
{ Штатное значение частота преобразования ЦАП, для которого проверяются
все метрологические характеристики модуля }
LTR35_DAC_FREQ_DEFAULT = 192000;
// Максимальное значение коэф. затухания
LTR35_ATTENUATION_MAX = 119.5;
// Максимальный код ЦАП
LTR35_DAC_CODE_MAX = $7FFFFF;
// Код ЦАП, соответствующий максимальному значению диапазона в Вольтах
LTR35_DAC_SCALE_CODE_MAX = $600000;
{ Устанавливаемое по умолчанию количество прочитанных отсчетов для выдачи
периодического статуса в потоковом режиме }
LTR35_STREAM_STATUS_PERIOD_DEFAULT = 1024;
{ Максимальное значение количества отсчетов для выдачи
периодического статуса в потоковом режиме }
LTR35_STREAM_STATUS_PERIOD_MAX = 1024;
{ Минимальное значение количества отсчетов для выдачи
периодического статуса в потоковом режиме }
LTR35_STREAM_STATUS_PERIOD_MIN = 8;
{ Адрес, с которого начинается пользовательская область flash-памяти }
LTR35_FLASH_USERDATA_ADDR = $100000;
{ Размер пользовательской области flash-памяти }
LTR35_FLASH_USERDATA_SIZE = $700000;
{ Минимальный размер блока для стирания во flash-памяти модуля }
LTR35_FLASH_ERASE_BLOCK_SIZE = 1024;
{ -------------- Коды ошибок, специфичные для LTR35 ------------------------}
LTR35_ERR_INVALID_SYNT_FREQ = -10200; // Задана неподдерживаемая частота синтезатора
LTR35_ERR_PLL_NOT_LOCKED = -10201; // Ошибка захвата PLL
LTR35_ERR_INVALID_CH_SOURCE = -10202; // Задано неверное значение источника данных для канала
LTR35_ERR_INVALID_CH_RANGE = -10203; // Задано неверное значение диапазона канала
LTR35_ERR_INVALID_DATA_FORMAT = -10204; // Задано неверное значение формата данных
LTR35_ERR_INVALID_MODE = -10205; // Задано неверное значение режима работы
LTR35_ERR_INVALID_DAC_RATE = -10206; // Задано неверное значение скорости выдачи на ЦАП
LTR35_ERR_INVALID_SYNT_CNTRS = -10207; // Задано недопустимое значение счетчиков синтезатора
LTR35_ERR_INVALID_ATTENUATION = -10208; // Задано неверное значение коэффициента затухания канала ЦАП
LTR35_ERR_UNSUPPORTED_CONFIG = -10209; // Заданная конфигурация ЦАП не поддерживается
LTR35_ERR_INVALID_STREAM_STATUS_PERIOD = -10210; // Задано неверное количество отсчетов для выдачи статуса в потоковом режиме
LTR35_ERR_DAC_CH_NOT_PRESENT = -10211; // Выбранный канал ЦАП отсутствует в данном модуле
LTR35_ERR_DAC_NO_SDRAM_CH_ENABLED = -10212; // Не разрешен ни один канал ЦАП на вывод из SDRAM
LTR35_ERR_DAC_DATA_NOT_ALIGNED = -10213; // Данные ЦАП не выравнены на кол-во разрешенных каналов
LTR35_ERR_NO_DATA_LOADED = -10214; // Не было подгружено ни одного отсчета
LTR35_ERR_LTRD_UNSUP_STREAM_MODE = -10215; // Данная версия ltrd/LtrServer не поддерживает потоковый режим LTR35
LTR35_ERR_MODE_UNSUP_FUNC = -10216; // Данная функция не поддерживается в установленном режиме
LTR35_ERR_INVALID_ARITH_GEN_NUM = -10217; // Задано неверное значение номера арифметического генератора
{ --------- Флаги для управления цифровыми выходами ------------ }
LTR35_DIGOUT_WORD_DIS_H = $00020000; { Запрещение (перевод в третье состояние)
старшей половины цифровых выходов.
Имеет значение только для LTR35-3. }
LTR35_DIGOUT_WORD_DIS_L = $00010000; { Запрещение младшей половины цифровых выходов }
{ --------- Флаги для подготовки данных. ----------------------- }
LTR35_PREP_FLAGS_VOLT = $00000001; { Флаг указывает, что данные на входе
заданны в вольтах и их нужно перевести в коды }
{ --------- Флаги состояния модуля. ---------------------------- }
LTR35_STATUS_FLAG_PLL_LOCK = $0001; { Признак захвата PLL в момент передачи статуса.
Если равен нулю, то модуль неработоспособен. }
LTR35_STATUS_FLAG_PLL_LOCK_HOLD = $0002; { Признак, что захват PLL не пропадал с момента предыдущей
передачи статуса. Должен быть установлен во всех статусах,
кроме первого }
{ ---------- Формат данных для передачи данных модулю ---------- }
LTR35_FORMAT_24 = 0; // 24-битный формат. Один отсчет занимает два 32-битных слова LTR
LTR35_FORMAT_20 = 1; // 20-битный формат. Один отсчет занимает одно 32-битное слово LTR
{ ---------- Режим работы модуля ------------------------------- }
LTR35_MODE_CYCLE = 0; { Режим циклического автогенератора. Данные подкачиваются
в буфер перед запуском выдачи, после чего выдаются
по кругу без подкачки. }
LTR35_MODE_STREAM = 1; { Потоковый режим. Данные постоянно подкачиваются
в очередь и выдаются при наличии на вывод }
{ ---------- Используемый выход для канала ЦАП ------------------ }
LTR35_DAC_OUT_FULL_RANGE = 0; { Выход 1:1 с диапазоном от -10 до +10 для
LTR35-1 и от -2 до +20 для LTR35-2 }
LTR35_DAC_OUT_DIV_RANGE = 1; { Выход 1:5 для LTR35-1 или выход 1:10
для LTR35-2 }
{ ---------- Источники сигнала для каналов ЦАП ------------------ }
LTR35_CH_SRC_SDRAM = 0; { Сигнал берется из буфера в SDRAM модуля.
При этом буфер работает циклически или в виде
очереди в зависимости от режима }
LTR35_CH_SRC_SIN1 = 1; { Синус от первого арифметического синусоидального
генератора }
LTR35_CH_SRC_COS1 = 2; { Косинус от первого арифметического синусоидального
генератора }
LTR35_CH_SRC_SIN2 = 3; { Синус от второго арифметического синусоидального
генератора }
LTR35_CH_SRC_COS2 = 4; { Косинус от второго арифметического синусоидального
генератора }
LTR35_CH_SRC_SIN3 = 5; { Синус от третьего арифметического синусоидального
генератора }
LTR35_CH_SRC_COS3 = 6; { Косинус от третьего арифметического синусоидального
генератора }
LTR35_CH_SRC_SIN4 = 7; { Синус от четвертого арифметического синусоидального
генератора }
LTR35_CH_SRC_COS4 = 8; { Косинус от четвертого арифметического синусоидального
генератора }
{ ------------ Скорость выдачи данных. -------------------------- }
LTR35_DAC_RATE_DOUBLE = 1; // Частота синтезатора, деленная на 384
LTR35_DAC_RATE_QUAD = 2; // Частота синтезатора, деленная на 192
{ ------------ Флаги для записи во flash-память модуля ---------- }
{ Признак, что записываемая область памяти уже стерта и не требуется
дополнительно стирать обновляемые сектора }
LTR35_FLASH_WRITE_ALREDY_ERASED = $00001;
{ ------------ Модификации модуля LTR35 ------------------------ }
LTR35_MOD_UNKNOWN = 0; // Неизвестная (не поддерживаемая библиотекой) модификация
LTR35_MOD_1 = 1; // LTR35-1
LTR35_MOD_2 = 2; // LTR35-2
LTR35_MOD_3 = 3; // LTR35-3
{$A4}
{ Калибровочные коэффициенты }
type TLTR35_CBR_COEF = record
Offset : Single; // Код смещения
Scale : Single; // Коэффициент шкалы
end;
{ Описание выхода ЦАП. }
type TLTR35_DAC_OUT_DESCR = record
AmpMax : double; // Максимальное пиковое значение амплитуды сигнала для данного выхода
AmpMin : Double; // Минимальное пиковое значение амплитуды сигнала для данного выхода */
CodeMax : Integer; //Код ЦАП, соответствующий максимальной амплитуде
CodeMin : Integer; // Код ЦАП, соответствующий минимальной амплитуде
Reserved : array [0..2] of LongWord; // Резервные поля
end;
{ Информация о модуле }
TINFO_LTR35 = record
Name : Array [0..LTR35_NAME_SIZE-1] of AnsiChar; // Название модуля (оканчивающаяся нулем ASCII-строка)
Serial : Array [0..LTR35_SERIAL_SIZE-1] of AnsiChar; //Серийный номер модуля (оканчивающаяся нулем ASCII-строка)
VerFPGA : Word; // Версия прошивки ПЛИС модуля (действительна только после ее загрузки)
VerPLD : Byte; //Версия прошивки PLD
Modification : Byte; // Модификация модуля. Одно из значений из #e_LTR35_MODIFICATION
DacChCnt : Byte; // Количество установленных каналов ЦАП
DoutLineCnt : Byte; // Количество линий цифрового вывода
{ Описание параметров выходов для данной модификации модуля }
DacOutDescr : array [0..LTR35_DAC_CH_OUTPUTS_CNT-1] of TLTR35_DAC_OUT_DESCR;
Reserved1 : array [0..25] of LongWord; // Резервные поля
{ Заводские калибровочные коэффициенты }
CbrCoef : array [0..LTR35_DAC_CHANNEL_CNT-1] of array [0..LTR35_DAC_CH_OUTPUTS_CNT-1] of TLTR35_CBR_COEF;
{ Дополнительные резервные поля }
Reserved2 : array [0..64*LTR35_DAC_CHANNEL_CNT*LTR35_DAC_CH_OUTPUTS_CNT-1] of LongWord;
end;
{ Настройки канала ЦАП }
TLTR35_CHANNEL_CONFIG = record
Enabled : Boolean; // Разрешение выдачи сигнала для данного канала
Output : Byte; // Используемый выход для данного канала (значение из #e_LTR35_DAC_OUTPUT)
Source : Byte; // Источник данных для данного канала (значение из #e_LTR35_CH_SRC)
ArithAmp : Double; // Амплитуда сигнала в режиме арифметического генератора
ArithOffs : Double; // Смещение сигнала в режиме арифметического генератора
Attenuation : Double; // Коэффициент затухания в dB (от 0 до 119.5 с шагом 0.5)
Reserved : array [0..7] of LongWord; // Резервные поля
end;
{ Настройки арифметического генератора. }
TLTR35_ARITH_SRC_CONFIG = record
Phase : Double; // Начальная фаза сигнала в радианах
Delta : Double; // Приращение фазы сигнала для каждого значения, выведенного на ЦАП, в радианах
Reserved : array [0..31] of LongWord; // Резервные поля
end;
{ Настройки синтезатора. }
TLTR35_SYNT_CONFIG = record
b : Word; // Коэффициент b в настройках синтезатора
r : Word; // Коэффициент r в настройках синтезатора
a : Byte; // Коэффициент a в настройках синтезатора
end;
{ Настройки модуля. }
TLTR35_CONFIG = record
// Настройки каналов ЦАП.
Ch : array [0..LTR35_DAC_CHANNEL_CNT-1] of TLTR35_CHANNEL_CONFIG;
// Настройки арифметических генероторов.
ArithSrc : array [0..LTR35_ARITH_SRC_CNT-1] of TLTR35_ARITH_SRC_CONFIG;
Mode : Byte; // Режим работы модуля (значение из #e_LTR35_MODE).
DataFmt : Byte; // Формат данных (значение из #e_LTR35_DATA_FORMAT).
DacRate : Byte; { Скорости выдачи (константа из #e_LTR35_RATE).
Как правило заполняется с помощью функции LTR35_FillFreq(). }
Synt : TLTR35_SYNT_CONFIG; { Настройки синтезатора.
Как правило заполняется с помощью функции LTR35_FillFreq().}
StreamStatusPeriod : Word; { Период передачи статусных слов. В потоковом
режиме ([Mode](@ref TLTR35_CONFIG::Mode)
= #LTR35_MODE_STREAM) статусное слово будет
передаваться после вывода каждых
StreamStatusPeriod слов из буфера.
0 означает выбор значения по-умолчанию. }
EchoEnable : Byte; { Разрешение передачи эхо-данных от одного
выбранного канала. }
EchoChannel : Byte; { При разрешенной передачи эхо-данных определяет
номер канала, которому будут соответствовать
эти данные }
Reserved: Array [0..62] of LongWord; // Резервные поля (должны быть установлены в 0)
end;
{ Параметры текущего состояния модуля. }
TLTR35_STATE = record
FpgaState : Byte; { Текущее состояние ПЛИС. Одно из значений из e_LTR_FPGA_STATE }
Run : Byte; { Признак, запущен ли сейчас вывод на ЦАП (в потоковом режиме
или в режиме циклического автогенератора) }
DacFreq : Double; { Установленная частота ЦАП. Обновляется после
вызова LTR35_Configure(). }
EnabledChCnt : Byte; { Количество разрешенных каналов ЦАП. Обновляется после
вызова LTR35_Configure(). }
SDRAMChCnt : Byte; { Количество разрешенных каналов ЦАП, отсчеты для
которых берутся из буфера модуля. Обновляется после
вызова LTR35_Configure(). }
ArithChCnt : Byte; { Количество разрешенных каналов ЦАП, настроенных
на режим арифметического генератора. Обновляется после
вызова LTR35_Configure(). }
Reserved : array [0..32-1] of LongWord; // Резервные поля
end;
PTLTR35_INTARNAL = ^TLTR35_INTARNAL;
TLTR35_INTARNAL = record
end;
{ Управляющая структура модуля. }
TLTR35 = record
size : integer; { Размер структуры. Заполняется в LTR35_Init(). }
Channel : TLTR; { Структура, содержащая состояние соединения с
ltrd или LtrServer.
Не используется напрямую пользователем. }
{ Указатель на непрозрачную структуру с внутренними параметрами,
используемыми исключительно библиотекой и недоступными для пользователя. }
Internal : PTLTR35_INTARNAL;
Cfg : TLTR35_CONFIG; { Настройки модуля. Заполняются пользователем
перед вызовом LTR35_Configure() }
{ Состояние модуля и рассчитанные параметры. Поля изменяются функциями
библиотеки. Пользовательской программой могут использоваться
только для чтения. }
State : TLTR35_STATE;
ModuleInfo : TINFO_LTR35; // Информация о модуле
end;
pTLTR35=^TLTR35;
{$A+}
// Инициализация описателя модуля
Function LTR35_Init(out hnd: TLTR35): Integer;
// Установить соединение с модулем.
Function LTR35_Open(var hnd: TLTR35; net_addr : LongWord; net_port : LongWord;
csn: string; slot: Word): Integer;
// Закрытие соединения с модулем
Function LTR35_Close(var hnd: TLTR35): Integer;
// Проверка, открыто ли соединение с модулем.
Function LTR35_IsOpened(var hnd: TLTR35): Integer;
// Подбор коэффициентов для получения заданной частоты преобразования ЦАП.
Function LTR35_FillFreq(out cfg: TLTR35_CONFIG; freq : Double; out fnd_freq: double): Integer; overload;
Function LTR35_FillFreq(out cfg: TLTR35_CONFIG; freq : Double): Integer; overload;
// Запись настроек в модуль.
Function LTR35_Configure(var hnd: TLTR35) : Integer;
// Передача данных ЦАП и цифровых выходов в модуль.
Function LTR35_Send(var hnd: TLTR35; var data : array of LongWord; size : LongWord; timeout : LongWord) : Integer;
// Подготовка данных для передачи в модуль.
Function LTR35_PrepareData(var hnd: TLTR35; var dac_data : array of Double;
var dac_size : LongWord;
var dout_data : array of LongWord;
var dout_size : LongWord;
flags : LongWord;
out result_data : array of LongWord;
var result_size : LongWord) : Integer;
// Подготовка данных ЦАП для передачи в модуль.
Function LTR35_PrepareDacData(var hnd: TLTR35; var dac_data : array of Double;
size : LongWord; flags : LongWord;
var result_data : array of LongWord;
out result_size : LongWord) : Integer;
// Смена страницы вывода в режиме циклического автогенератора
Function LTR35_SwitchCyclePage(var hnd: TLTR35; flags: LongWord; tout: LongWord): Integer;
// Запуск выдачи данных в потоковом режиме.
Function LTR35_StreamStart(var hnd: TLTR35; flags: LongWord): Integer;
// Останов выдачи данных.
Function LTR35_Stop(var hnd: TLTR35; flags: LongWord): Integer;
// Останов выдачи данных с заданным временем ожидания ответа.
Function LTR35_StopWithTout(var hnd: TLTR35; flags: LongWord; tout: LongWord): Integer;
// Изменение частоты для арифметического генератора.
Function LTR35_SetArithSrcDelta(var hnd: TLTR35; gen_num: Byte; delta: double): Integer;
// Изменение амплитуды и смещения арифметического сигнала.
Function LTR35_SetArithAmp(var hnd: TLTR35; ch_num: Byte; amp: Double; offset: double): Integer;
// Прием эхо-данных от модуля.
Function LTR35_RecvEchoResp(var hnd: TLTR35; out data : array of integer;
out tmark : array of Integer;
size : LongWord; timeout: LongWord): Integer;
// Получение сообщения об ошибке.
Function LTR35_GetErrorString(err: Integer) : string;
// Проверка, разрешена ли работа ПЛИС модуля.
Function LTR35_FPGAIsEnabled(var hnd: TLTR35; out enabled: LongBool): Integer;
// Разрешение работы ПЛИС модуля.
Function LTR35_FPGAEnable(var hnd: TLTR35; enable: LongBool): Integer;
// Получение информации о состоянии модуля.
Function LTR35_GetStatus(var hnd: TLTR35; out status : LongWord): Integer;
// Чтение данных из flash-памяти модуля
Function LTR35_FlashRead(var hnd: TLTR35; addr: LongWord; out data : array of byte; size: LongWord): Integer;
// Запись данных во flash-память модуля
Function LTR35_FlashWrite(var hnd: TLTR35; addr: LongWord; var data : array of byte; size: LongWord; flags : LongWord): Integer;
// Стирание области flash-память модуля
Function LTR35_FlashErase(var hnd: TLTR35; addr: LongWord; size: LongWord): Integer;
implementation
Function _init(out hnd: TLTR35): Integer; {$I ltrapi_callconvention}; external 'ltr35api' name 'LTR35_Init';
Function _open(var hnd: TLTR35; net_addr : LongWord; net_port : LongWord; csn: PAnsiChar; slot: Word): Integer; {$I ltrapi_callconvention}; external 'ltr35api' name 'LTR35_Open';
Function _close(var hnd: TLTR35): Integer; {$I ltrapi_callconvention}; external 'ltr35api' name 'LTR35_Close';
Function _is_opened(var hnd: TLTR35): Integer; {$I ltrapi_callconvention}; external 'ltr35api' name 'LTR35_IsOpened';
Function _fill_freq(out cfg: TLTR35_CONFIG; freq : Double; out fnd_freq: double): Integer; {$I ltrapi_callconvention}; external 'ltr35api' name 'LTR35_FillFreq';
Function _configure(var hnd: TLTR35): Integer; {$I ltrapi_callconvention}; external 'ltr35api' name 'LTR35_Configure';
Function _send(var hnd: TLTR35; var data; size: LongWord; timeout : LongWord): Integer; {$I ltrapi_callconvention}; external 'ltr35api' name 'LTR35_Send';
Function _prepare_data(var hnd: TLTR35; var dac_data; var dac_size : LongWord;
var dout_data; var dout_size : LongWord; flags : LongWord;
out result; var snd_size : LongWord) : Integer; {$I ltrapi_callconvention}; external 'ltr35api' name 'LTR35_PrepareData';
// Подготовка данных ЦАП для передачи в модуль.
Function _prepare_dac_data(var hnd: TLTR35; var dac_data; size : LongWord;
flags : LongWord; var result; out snd_size : LongWord) : Integer; {$I ltrapi_callconvention}; external 'ltr35api' name 'LTR35_PrepareDacData';
Function _switch_cycle_page(var hnd: TLTR35; flags: LongWord; tout: LongWord): Integer; {$I ltrapi_callconvention}; external 'ltr35api' name 'LTR35_SwitchCyclePage';
Function _stream_start(var hnd: TLTR35; flags: LongWord): Integer; {$I ltrapi_callconvention}; external 'ltr35api' name 'LTR35_StreamStart';
Function _stop(var hnd: TLTR35; flags: LongWord): Integer; {$I ltrapi_callconvention}; external 'ltr35api' name 'LTR35_Stop';
Function _stop_with_tout(var hnd: TLTR35; flags: LongWord; tout: LongWord): Integer; {$I ltrapi_callconvention}; external 'ltr35api' name 'LTR35_StopWithTout';
Function _set_arith_src_delta(var hnd: TLTR35; gen_num: Byte; delta: double): Integer; {$I ltrapi_callconvention}; external 'ltr35api' name 'LTR35_SetArithSrcDelta';
Function _set_arith_amp(var hnd: TLTR35; ch_num: Byte; amp: Double; offset: double): Integer; {$I ltrapi_callconvention}; external 'ltr35api' name 'LTR35_SetArithAmp';
Function _recv_echo_resp(var hnd: TLTR35; out data; out tmark; size : LongWord;
timeout: LongWord): Integer; {$I ltrapi_callconvention}; external 'ltr35api' name 'LTR35_RecvEchoResp';
Function _get_err_str(err : integer) : PAnsiChar; {$I ltrapi_callconvention}; external 'ltr35api' name 'LTR35_GetErrorString';
Function _fpga_is_enabled(var hnd: TLTR35; out enabled: LongBool): Integer; {$I ltrapi_callconvention}; external 'ltr35api' name 'LTR35_FPGAIsEnabled';
Function _fpga_enable(var hnd: TLTR35; enable: LongBool): Integer; {$I ltrapi_callconvention}; external 'ltr35api' name 'LTR35_FPGAEnable';
Function _get_status(var hnd: TLTR35; out status : LongWord): Integer; {$I ltrapi_callconvention}; external 'ltr35api' name 'LTR35_GetStatus';
Function _flash_read(var hnd: TLTR35; addr: LongWord; out data; size: LongWord): Integer; {$I ltrapi_callconvention}; external 'ltr35api' name 'LTR35_FlashRead';
Function _flash_write(var hnd: TLTR35; addr: LongWord; var data : array of byte; size: LongWord; flags : LongWord): Integer; {$I ltrapi_callconvention}; external 'ltr35api' name 'LTR35_FlashWrite';
Function _flash_erase(var hnd: TLTR35; addr: LongWord; size: LongWord): Integer; {$I ltrapi_callconvention}; external 'ltr35api' name 'LTR35_FlashErase';
Function LTR35_Init(out hnd: TLTR35): Integer;
begin
LTR35_Init:=_init(hnd);
end;
Function LTR35_Open(var hnd: TLTR35; net_addr : LongWord; net_port : LongWord; csn: string; slot: Word): Integer;
begin
LTR35_Open:=_open(hnd, net_addr, net_port, PAnsiChar(AnsiString(csn)), slot);
end;
Function LTR35_Close(var hnd: TLTR35): Integer;
begin
LTR35_Close:=_close(hnd);
end;
Function LTR35_IsOpened(var hnd: TLTR35): Integer;
begin
LTR35_IsOpened:=_is_opened(hnd);
end;
Function LTR35_FillFreq(out cfg: TLTR35_CONFIG; freq : Double; out fnd_freq: double): Integer; overload;
begin
LTR35_FillFreq:=_fill_freq(cfg, freq, fnd_freq);
end;
Function LTR35_FillFreq(out cfg: TLTR35_CONFIG; freq : Double): Integer; overload;
begin
LTR35_FillFreq:=LTR35_FillFreq(cfg, freq, PDouble(nil)^);
end;
Function LTR35_Configure(var hnd: TLTR35) : Integer;
begin
LTR35_Configure:=_configure(hnd);
end;
Function LTR35_Send(var hnd: TLTR35; var data : array of LongWord; size : LongWord; timeout : LongWord) : Integer;
begin
LTR35_Send:=_send(hnd, data, size, timeout);
end;
Function LTR35_PrepareData(var hnd: TLTR35; var dac_data : array of Double;
var dac_size : LongWord;
var dout_data : array of LongWord;
var dout_size : LongWord;
flags : LongWord;
out result_data : array of LongWord;
var result_size : LongWord) : Integer;
begin
LTR35_PrepareData:=_prepare_data(hnd, dac_data, dac_size, dout_data, dout_size, flags, result_data, result_size);
end;
// Подготовка данных ЦАП для передачи в модуль.
Function LTR35_PrepareDacData(var hnd: TLTR35; var dac_data : array of Double;
size : LongWord; flags : LongWord;
var result_data : array of LongWord;
out result_size : LongWord) : Integer;
begin
LTR35_PrepareDacData:=_prepare_dac_data(hnd, dac_data, size, flags, result_data, result_size);
end;
Function LTR35_SwitchCyclePage(var hnd: TLTR35; flags: LongWord; tout: LongWord): Integer;
begin
LTR35_SwitchCyclePage:=_switch_cycle_page(hnd, flags, tout);
end;
Function LTR35_StreamStart(var hnd: TLTR35; flags: LongWord): Integer;
begin
LTR35_StreamStart:=_stream_start(hnd, flags);
end;
Function LTR35_Stop(var hnd: TLTR35; flags: LongWord): Integer;
begin
LTR35_Stop:=_stop(hnd, flags);
end;
Function LTR35_StopWithTout(var hnd: TLTR35; flags: LongWord; tout: LongWord): Integer;
begin
LTR35_StopWithTout:=_stop_with_tout(hnd, flags, tout);
end;
Function LTR35_SetArithSrcDelta(var hnd: TLTR35; gen_num: Byte; delta: double): Integer;
begin
LTR35_SetArithSrcDelta:=_set_arith_src_delta(hnd, gen_num, delta);
end;
Function LTR35_SetArithAmp(var hnd: TLTR35; ch_num: Byte; amp: Double; offset: double): Integer;
begin
LTR35_SetArithAmp:=_set_arith_amp(hnd, ch_num, amp, offset);
end;
Function LTR35_RecvEchoResp(var hnd: TLTR35; out data : array of integer;
out tmark : array of Integer;
size : LongWord; timeout: LongWord): Integer;
begin
LTR35_RecvEchoResp:=_recv_echo_resp(hnd, data, tmark, size, timeout);
end;
function LTR35_GetErrorString(err: Integer) : string;
begin
LTR35_GetErrorString:=string(_get_err_str(err));
end;
Function LTR35_FPGAIsEnabled(var hnd: TLTR35; out enabled: LongBool): Integer;
begin
LTR35_FPGAIsEnabled:=_fpga_is_enabled(hnd, enabled);
end;
Function LTR35_FPGAEnable(var hnd: TLTR35; enable: LongBool): Integer;
begin
LTR35_FPGAEnable:=_fpga_enable(hnd, enable);
end;
Function LTR35_GetStatus(var hnd: TLTR35; out status : LongWord): Integer;
begin
LTR35_GetStatus:=_get_status(hnd, status);
end;
Function LTR35_FlashRead(var hnd: TLTR35; addr: LongWord; out data : array of byte; size: LongWord): Integer;
begin
LTR35_FlashRead:=_flash_read(hnd, addr, data, size);
end;
Function LTR35_FlashWrite(var hnd: TLTR35; addr: LongWord; var data : array of byte; size: LongWord; flags : LongWord): Integer;
begin
LTR35_FlashWrite:=_flash_write(hnd, addr, data, size, flags);
end;
Function LTR35_FlashErase(var hnd: TLTR35; addr: LongWord; size: LongWord): Integer;
begin
LTR35_FlashErase:=_flash_erase(hnd, addr, size);
end;
end.
|
unit uConfig;
interface
uses
Vcl.Forms,System.SysUtils;
const
WORK_DIR:string='pp'; // 工作目录
WEB_DIR:string='web'; // 保存网页的子目录名
WEB_CACHE='cache';
DATA_DIR:string='data'; // 保存数据的目录
APP_DIR:string='app'; // app的目录
XML_FILE:string='config.xml';//xml配置参数文件
XML_FILE_G:string='configg.xml';//xml配置参数文件
BAIDU_APP_ID:string='16197183';
BAIDU_API_KEY:string='5G4tOXwCGG5buEFPrZGGykal';
BAIDU_SECRET_KEY:string='ceAs9I9xHUzrxs0OWfEBed2HnA4CerLS';
VER_G:string='vg.dat';
VER_M:string='vm.dat';
LOG_NAME:string='ppLog.txt';
SWF_NAME:ansiString='crypt.swf'; //flash文件
SOCKET_NAME:ansiString='socket.dat'; //socket数据文件
FFMPEG_NAME:ansiString='ffmpeg.exe'; //socket数据文件
MMCFG_NAME:ansiString='mm.cfg'; //log配置文件
var
workdir,webdir,datadir,appdir:string;// 工作目录,保存网页的子目录
configFile,configFile2,verg,verm,webCache,socketFile,flashfile,logfile,ffmpegFile,mmcfgFile:string;//xml配置参数文件
isInit:boolean=false;
procedure init();
implementation
uses
uxml;
procedure init();
var
me:String;
begin
isInit:=true;
me:=application.ExeName;
workdir:=extractfiledir(me)+'\'+WORK_DIR;
if(not DirectoryExists(workdir))then ForceDirectories(workdir);
webdir:=workdir+'\'+WEB_DIR;
if(not DirectoryExists(webdir))then ForceDirectories(webdir);
webCache:=webdir+'\'+WEB_CACHE;
if(not directoryexists(webCache))then forcedirectories(webCache);
datadir:=workdir+'\'+DATA_DIR;
if(not directoryexists(datadir))then forcedirectories(datadir);
appdir:=workdir+'\'+APP_DIR;
if(not directoryexists(appdir))then forcedirectories(appdir);
configFile:=workdir+'\'+XML_FILE;
configFile2:=workdir+'\'+XML_FILE_G;
verg:=workdir+'\'+VER_G;
verm:=workdir+'\'+VER_M;
if(not fileexists(configFile))then uxml.createXml;
logfile:=datadir+'\'+LOG_NAME;
socketFile:=datadir+'\'+SOCKET_NAME;
flashfile:= workdir+'\'+SWF_NAME;
ffmpegFile:=appdir+'\ffmpeg\'+FFMPEG_NAME;
mmcfgFile:=workdir+'\'+MMCFG_NAME;
end;
begin
init();
end.
|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Data.DBXEncryption;
interface
uses
Data.DBXPlatform,
System.SysUtils;
type
/// <summary> Cypher class using PC1 128bit key encryption algorithm.
/// </summary>
/// <remarks>
/// Details at http://membres.lycos.fr/pc1/.
///
/// </remarks>
TPC1Cypher = class sealed
private
///Remporary field for use only while implementing this as an XOR Cypher
TEMPXORVeri: Byte;
public
/// <summary> Default constructor.
/// </summary>
constructor Create; overload;
/// <summary> Key based constructor
///
/// </summary>
/// <param name="key">String - Symmetric key</param>
constructor Create(const Key: UnicodeString); overload;
/// <summary> Encrypts the byte argument using the encryption key.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="c">byte - un-encrypted byte</param>
/// <returns>encrypted byte</returns>
function Cypher(const C: Byte): Byte;
/// <summary> Decrypts the encrypted byte
///
/// </summary>
/// <param name="c">byte - encrypted byte</param>
/// <returns>byte - decrypted byte</returns>
function Decypher(const C: Byte): Byte;
/// <summary> Set the 128bit (16 bytes) key. They key is formed from the ASCII code
/// </summary>
/// <remarks> They key is formed from the ASCII code
/// of the character string passed as argument. If the key is shorter, space
/// character is appended. If the key is longer, only the first 16 characters
/// are used. After internal key is build the parameter is preserved for
/// future use.
///
/// </remarks>
/// <param name="key">String - string out of which key is made, should not be null</param>
/// <returns>boolean - false if the key was partially used</returns>
function SetEncryptionKey(const Key: UnicodeString): Boolean;
/// <summary> Resets the encryption registers, the object can be reused for a new
/// encryption or decryption.
/// </summary>
procedure Reset;
protected
function GetEncryptionKey: UnicodeString;
private
/// <returns>false is key length was different from KEYLEN and eventually space
/// characters were added</returns>
function Init: Boolean;
function Assemble: Integer;
function Code(const I: Integer): Integer;
private
FSi: Integer;
FX1a2: Integer;
FX1a0: TDBXInt32s;
/// <summary> Key holder
/// </summary>
FCle: TBytes;
/// <summary> User password
/// </summary>
FCypherKey: UnicodeString;
public
property EncryptionKey: UnicodeString read GetEncryptionKey;
private
const Keylen = 16;
end;
implementation
uses
Data.DBXCommon,
System.Math,
Data.DBXClientResStrs;
function GenerateKey(KeyLength: Integer): string;
const
Chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!';
var
str: string;
I, Len: Integer;
begin
Randomize;
Len := Length(Chars);
Result := '';
for I := 0 to KeyLength - 1 do
Result := Result + Chars[Random(Len) + 1];
end;
constructor TPC1Cypher.Create;
begin
SetLength(FX1a0,8);
SetLength(FCle,Keylen);
inherited Create;
SetEncryptionKey(GenerateKey(16));
end;
constructor TPC1Cypher.Create(const Key: UnicodeString);
begin
SetLength(FX1a0,8);
SetLength(FCle,Keylen);
inherited Create;
SetEncryptionKey(Key);
end;
function TPC1Cypher.Init: Boolean;
var
I: Integer;
Len: Integer;
begin
Len := Min(Length(FCypherKey),Keylen);
for i := 0 to Len - 1 do
FCle[I] := Ord((FCypherKey[1+I]));
for i := Len to 15 do
FCle[I] := Byte(32);
for i := 0 to Length(FX1a0) - 1 do
FX1a0[I] := 0;
FSi := 0;
FX1a2 := 0;
Result := Len <> Keylen;
end;
function TPC1Cypher.Assemble: Integer;
var
Inter: Integer;
begin
FX1a0[0] := ((FCle[0] and 255) shl 8) or (FCle[1] and 255);
Inter := Code(0);
FX1a0[1] := FX1a0[0] xor (((FCle[2] and 255) shl 8) or (FCle[3] and 255));
Inter := Inter xor Code(1);
FX1a0[2] := FX1a0[1] xor (((FCle[4] and 255) shl 8) or (FCle[5] and 255));
Inter := Inter xor Code(2);
FX1a0[3] := FX1a0[2] xor (((FCle[6] and 255) shl 8) or (FCle[7] and 255));
Inter := Inter xor Code(3);
FX1a0[4] := FX1a0[3] xor (((FCle[8] and 255) shl 8) or (FCle[9] and 255));
Inter := Inter xor Code(4);
FX1a0[5] := FX1a0[4] xor (((FCle[10] and 255) shl 8) or (FCle[11] and 255));
Inter := Inter xor Code(5);
FX1a0[6] := FX1a0[5] xor (((FCle[12] and 255) shl 8) or (FCle[13] and 255));
Inter := Inter xor Code(6);
FX1a0[7] := FX1a0[6] xor (((FCle[14] and 255) shl 8) or (FCle[15] and 255));
Inter := Inter xor Code(7);
Result := Inter;
end;
function TPC1Cypher.Code(const I: Integer): Integer;
var
Dx: Integer;
Ax: Integer;
Cx: Integer;
Bx: Integer;
Tmp: Integer;
begin
Dx := FX1a2 + I;
Ax := FX1a0[I];
Cx := 346;
Bx := 20021;
Tmp := Ax;
Ax := FSi;
FSi := Tmp;
Tmp := Ax;
Ax := Dx;
Dx := Tmp;
if Ax <> 0 then
Ax := Ax * Bx;
Tmp := Ax;
Ax := Cx;
Cx := Tmp;
if Ax <> 0 then
begin
Ax := Ax * FSi;
Cx := Cx + Ax;
end;
Tmp := Ax;
Ax := FSi;
FSi := Tmp;
Ax := Ax * Bx;
Dx := Dx + Cx;
IncrAfter(Ax);
FX1a2 := Dx;
FX1a0[I] := Ax;
Result := Ax xor Dx;
end;
function TPC1Cypher.Cypher(const C: Byte): Byte;
var
Inter: Integer;
Cfc: Integer;
Cfd: Integer;
Compte: Integer;
begin
Inter := Assemble;
Cfc := (Inter shr 8) and 255;
Cfd := (Inter and 255);
for compte := 0 to 15 do
FCle[Compte] := Byte(((FCle[Compte] and 255) xor (C and 255)));
Result := Byte((C xor (Cfc xor Cfd)));
end;
function TPC1Cypher.Decypher(const C: Byte): Byte;
var
Inter: Integer;
Cfc: Integer;
Cfd: Integer;
Res: Byte;
Compte: Integer;
begin
Inter := Assemble;
Cfc := (Inter shr 8) and 255;
Cfd := (Inter and 255);
Res := Byte((C xor (Cfc xor Cfd)));
for compte := 0 to 15 do
FCle[Compte] := Byte(((FCle[Compte] and 255) xor (Res and 255)));
Result := Res;
end;
function TPC1Cypher.SetEncryptionKey(const Key: UnicodeString): Boolean;
var
I: Integer;
begin
if StringIsNil(Key) then
raise TDBXError.Create(0, SKeyNotNull);
FCypherKey := Key;
Result := Init;
TEMPXORVeri := 0;
for I := 1 to Length(Key) do
begin
TEMPXORVeri := TEMPXORVeri xor Ord(Key[I]);
end;
end;
function TPC1Cypher.GetEncryptionKey: UnicodeString;
begin
Result := FCypherKey;
end;
procedure TPC1Cypher.Reset;
begin
Init;
end;
end.
|
unit MD.Model.Client;
interface
type TClient = class
private
Fid: Integer;
Fname: String;
FlastName: string;
Fphone: String;
public
property id: Integer read Fid write Fid;
property name: String read Fname write Fname;
property lastName: string read FlastName write FlastName;
property phone: String read Fphone write Fphone;
end;
implementation
end.
|
{******************************************}
{ }
{ vtk GridReport library }
{ }
{ Copyright (c) 2003 by vtkTools }
{ }
{******************************************}
{ Contains @link(TvgrBevelLabel) - this component combines possibilities of TBevel and TLabel.
See also:
vgr_FontComboBox,vgr_ControlBar,vgr_ColorButton}
unit vgr_Label;
interface
{$I vtk.inc}
uses
Classes, Controls, StdCtrls, Windows, Graphics, Math;
type
{ Specify position of the beveled line
vgrlbsCenterLine - line vertically centered in the control
vgrlbsTopLine - line are top aligned in the control
vgrlbsBottomLine - line are bottom aligned in the control }
TvgrLabelBevelStyle = (vgrlbsCenterLine, vgrlbsTopLine, vgrlbsBottomLine);
/////////////////////////////////////////////////
//
// TvgrBevelLabel
//
/////////////////////////////////////////////////
{ TvgrBevelLabel combines possibilities of TBevel and TLabel.
Use TextWidthPercent property to specify ratio between areas of the text and beveled line.
Use BevelStyle property to specify position of the beveled line. }
TvgrBevelLabel = class(TCustomLabel)
private
FTextWidthPercent: Integer;
FBevelStyle: TvgrLabelBevelStyle;
procedure SetTextWidthPercent(Value: Integer);
procedure SetBevelStyle(Value: TvgrLabelBevelStyle);
function GetTextWidth: Integer;
protected
procedure AdjustBounds; override;
procedure Paint; override;
property TextWidth: Integer read GetTextWidth;
public
{Creates a TvgrBevelLabel control.
AOwner is the component that is responsible for freeing the label.
It becomes the value of the Owner property.}
constructor Create(AOwner: TComponent); override;
published
{ Use TextWidthPercent property to specify ratio between areas of the text and beveled line. }
property TextWidthPercent: Integer read FTextWidthPercent write SetTextWidthPercent default 100;
{ Use BevelStyle property to specify position of the beveled line. }
property BevelStyle: TvgrLabelBevelStyle read FBevelStyle write SetBevelStyle default vgrlbsCenterLine;
property Align;
property Alignment;
property Anchors;
property BiDiMode;
property Caption;
property Color nodefault;
property Constraints;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property FocusControl;
property Font;
property ParentBiDiMode;
property ParentColor;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowAccelChar;
property ShowHint;
property Transparent;
property Layout;
property Visible;
property WordWrap;
property OnClick;
{$IFDEF VTK_D6_OR_D7}
property OnContextPopup;
{$ENDIF}
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
{$IFDEF VTK_D6_OR_D7}
property OnMouseEnter;
property OnMouseLeave;
{$ENDIF}
property OnStartDock;
property OnStartDrag;
end;
implementation
uses
vgr_Functions;
const
Alignments: array[TAlignment] of Word = (DT_LEFT, DT_RIGHT, DT_CENTER);
WordWraps: array[Boolean] of Word = (0, DT_WORDBREAK);
/////////////////////////////////////////////////
//
// TvgrBevelLabel
//
/////////////////////////////////////////////////
constructor TvgrBevelLabel.Create(AOwner: TComponent);
begin
inherited;
{$IFDEF VGR_DEMO}
ShowDemoWarning;
{$ENDIF}
AutoSize := False;
FTextWidthPercent := 100;
end;
procedure TvgrBevelLabel.SetTextWidthPercent(Value: Integer);
begin
if FTextWidthPercent <> Value then
begin
FTextWidthPercent := Value;
Invalidate;
end;
end;
procedure TvgrBevelLabel.SetBevelStyle(Value: TvgrLabelBevelStyle);
begin
if FBevelStyle <> Value then
begin
FBevelStyle := Value;
Invalidate;
end;
end;
function TvgrBevelLabel.GetTextWidth: Integer;
var
ARect: TRect;
begin
Result := MulDiv(ClientRect.Right - ClientRect.Left, FTextWidthPercent, 100);
ARect := ClientRect;
DoDrawText(ARect, DT_CALCRECT or DT_EXPANDTABS or WordWraps[WordWrap] or Alignments[Alignment] or DT_CALCRECT);
Result := Min(Result, ARect.Right - ARect.Left);
end;
procedure TvgrBevelLabel.AdjustBounds;
begin
end;
procedure TvgrBevelLabel.Paint;
const
cBevelOffset = 2;
var
Rect, CalcRect: TRect;
DrawStyle: Longint;
Color1, Color2: TColor;
ATextWidth: Integer;
procedure DrawLine(AColor: TColor; X1, Y1, X2, Y2: Integer);
begin
with Canvas do
begin
Brush.Color := AColor;
FillRect(Classes.Rect(X1, Y1, X2, Y2));
end;
end;
procedure DrawBevel(AFrom, ATo: Integer);
var
Y: Integer;
begin
with ClientRect do
case BevelStyle of
vgrlbsCenterLine:
Y := Top + (Bottom - Top - 2) div 2;
vgrlbsTopLine:
Y := Top + cBevelOffset;
else
Y := Bottom - 2 - cBevelOffset;
end;
DrawLine(Color1, AFrom, Y, ATo, Y + 1);
DrawLine(Color2, AFrom, Y + 1, ATo, Y + 2);
end;
begin
with Canvas do
begin
if not Transparent then
begin
Brush.Color := Self.Color;
Brush.Style := bsSolid;
FillRect(ClientRect);
end;
Brush.Style := bsClear;
ATextWidth := Self.TextWidth;
Rect := ClientRect;
with Rect do
case Alignment of
taRightJustify: Left := Right - ATextWidth;
taCenter:
begin
Left := Left + (Right - Left - ATextWidth) div 2;
Right := Left + ATextWidth;
end;
else
Right := Left + ATextWidth;
end;
{ DoDrawText takes care of BiDi alignments }
DrawStyle := DT_EXPANDTABS or WordWraps[WordWrap] or Alignments[Alignment];
{ Calculate vertical layout }
if Layout <> tlTop then
begin
CalcRect := Rect;
DoDrawText(CalcRect, DrawStyle or DT_CALCRECT);
if Layout = tlBottom then OffsetRect(Rect, 0, Height - CalcRect.Bottom)
else OffsetRect(Rect, 0, (Height - CalcRect.Bottom) div 2);
end;
DoDrawText(Rect, DrawStyle);
{ Draw bevel }
Color1 := clBtnShadow;
Color2 := clBtnHighlight;
Brush.Style := bsSolid;
case Alignment of
taRightJustify: DrawBevel(ClientRect.Left, Rect.Left - 2);
taCenter:
begin
DrawBevel(ClientRect.Left, Rect.Left - 2);
DrawBevel(Rect.Right + 2, ClientRect.Right);
end;
else
DrawBevel(Rect.Right + 2, ClientRect.Right);
end;
end;
end;
end.
|
unit uExceptions;
interface
uses SysUtils, uExceptionCodes;
type
TException = class(Exception)
end;
TFatalException = class(TException)
end;
procedure RaiseExeption(const aCode: integer);
procedure RaiseFatalException(const aCode: integer);
procedure ContractFailure;
procedure Warn(const aMessage: string);
implementation
procedure ContractFailure;
begin
RaiseExeption(CONTRACT_EXCEPT);
end;
procedure RaiseExeption(const aCode: integer);
begin
raise TException.Create('Error Message');
end;
procedure RaiseFatalException(const aCode: integer);
begin
raise TFatalException.Create('Error message');
end;
procedure Warn(const aMessage: string);
begin
//
end;
end.
|
// -------------------------------------------------------------------------------
// Descrição: Um programa em Pascal que calcule a média aritmética de 4 valores
// inteiros
// -------------------------------------------------------------------------------
//Autor : Fernando Gomes
//Data : 19/08/2021
// -------------------------------------------------------------------------------
Program Media_aritmetica_de_4_valores_inteiros ;
//Seção de Declarações das variáveis
var
num1, num2, num3, num4: integer;
Media: real;
Begin
//Pede ao usuario que insira os 4 numeros inteiros
Write('Digite o primeiro número: ');
Readln(num1);
Write('Digite o segundo número: ');
Readln(num2);
Write('Digite o terceiro número: ');
Readln(num3);
Write('Digite o quarto número: ');
Readln(num4);
Media := (num1 + num2 + num3 + num4)/4;
Writeln();
Write('A media dos 4 valores inteiros é: ',Media:6:2);
End. |
{
Copyright (C) Alexey Torgashin, uvviewsoft.com
License: MPL 2.0 or LGPL
}
unit ATSynEdit_Cmp_Filenames;
{$mode objfpc}{$H+}
interface
uses
SysUtils,
FileUtil,
Classes,
URIParser,
ATStringProc;
procedure CalculateCompletionFilenames(AResult: TStringList;
const ACurDir, AText, AFileMask,
APrefixDir, APrefixFile: string; AddDirSlash, AURIEncode: boolean);
implementation
const
//GenDelims = [':', '/', '?', '#', '[', ']', '@'];
SubDelims = ['!', '$', '&', '''', '(', ')', '*', '+', ',', ';', '='];
ALPHA = ['A'..'Z', 'a'..'z'];
DIGIT = ['0'..'9'];
Unreserved = ALPHA + DIGIT + ['-', '.', '_', '~'];
ValidPathChars = Unreserved + SubDelims + ['@', ':', '/'];
//copy from FPC's URIParser unit
function Escape(const s: String; const Allowed: TSysCharSet): String;
var
i, L: Integer;
P: PChar;
begin
L := Length(s);
for i := 1 to Length(s) do
if not (s[i] in Allowed) then Inc(L,2);
if L = Length(s) then
begin
Result := s;
Exit;
end;
SetLength(Result, L);
P := @Result[1];
for i := 1 to Length(s) do
begin
if not (s[i] in Allowed) then
begin
P^ := '%'; Inc(P);
StrFmt(P, '%.2x', [ord(s[i])]); Inc(P);
end
else
P^ := s[i];
Inc(P);
end;
end;
function EscapeWebFilename(const s: String): String;
begin
Result:= Escape(s, ValidPathChars);
end;
function IsValueFilename(const S: string): boolean;
begin
Result:= false;
if Pos('://', S)>0 then exit;
Result:= true;
end;
(*
function IsHiddenFilename(const fn: string): boolean; inline;
begin
{$ifdef windows}
Result:= (FileGetAttr(fn) and (faHidden or faSysFile))<>0;
{$else}
Result:= SBeginsWith(ExtractFileName(fn), '.');
{$endif}
end;
*)
procedure CalculateCompletionFilenames(AResult: TStringList;
const ACurDir, AText, AFileMask,
APrefixDir, APrefixFile: string; AddDirSlash, AURIEncode: boolean);
//
function MaybeEscape(const S: string): string;
begin
if AURIEncode then
Result:= Escape(S, ValidPathChars)
else
Result:= S;
end;
//
var
FinderDirs: TFileSearcher;
FinderFiles: TFileSearcher;
L: TStringList;
SDirName, SFileName, SItem, SItemShort: string;
SRes: string;
begin
AResult.Clear;
if (AText<>'') and not IsValueFilename(AText) then exit;
if ACurDir='' then exit;
SDirName:= ACurDir+'/'+ExtractFileDir(AText);
if not DirectoryExists(SDirName) then exit;
SFileName:= ExtractFileName(AText);
L:= TStringList.Create;
FinderDirs:= TListDirectoriesSearcher.Create(L);
FinderFiles:= TListFileSearcher.Create(L);
try
L.Clear;
FinderDirs.FileAttribute:= faAnyFile and not (faHidden{%H-} or faSysFile{%H-});
FinderDirs.Search(SDirName, AllFilesMask, false{SubDirs});
L.Sort;
for SItem in L do
begin
SItemShort:= ExtractFileName(SItem);
if (SFileName='') or SBeginsWith(SItemShort, SFileName) then
begin
SRes:= APrefixDir+'|'+MaybeEscape(SItemShort);
if AddDirSlash then
SRes+= '/';
AResult.Add(SRes);
end;
end;
L.Clear;
FinderFiles.FileAttribute:= faAnyFile and not (faHidden{%H-} or faSysFile{%H-});
FinderFiles.Search(SDirName, AFileMask, false{SubDirs});
L.Sort;
for SItem in L do
begin
SItemShort:= MaybeEscape(ExtractFileName(SItem));
if (SFileName='') or SBeginsWith(SItemShort, SFileName) then
AResult.Add(APrefixFile+'|'+SItemShort);
end;
finally
FreeAndNil(L);
FreeAndNil(FinderDirs);
FreeAndNil(FinderFiles);
end;
end;
end.
|
unit Options;
interface
uses
Strg, Disk,
Windows, SysUtils, Classes, Dialogs;
type
TScreenSource = (ssRegion, ssFull, ssWindow);
TScreenOption = record
strict private
FScreenSource : TScreenSource;
FLeft, FTop, FWidth, FHeight : integer;
FTargetWindow : integer;
function GetLeft: integer;
function GetTop: integer;
function GetCanCapture: boolean;
public
WithCursor : boolean;
procedure Init;
procedure SetScreenRegion(ALeft,ATop,AWidth,AHeight:integer);
procedure SetFullScreen;
procedure SetTargetWindow(const Value: integer);
private
function GetBitmapHeight: integer;
function GetBitmapWidth: integer;
public
property CanCapture : boolean read GetCanCapture;
property ScreenSource : TScreenSource read FScreenSource;
property Left : integer read GetLeft;
property Top : integer read GetTop;
property Width : integer read FWidth;
property Height : integer read FHeight;
property BitmapWidth : integer read GetBitmapWidth;
property BitmapHeight : integer read GetBitmapHeight;
property TargetWindow : integer read FTargetWindow;
end;
TAudioOption = record
Mic : integer;
SystemAudio : boolean;
VolumeMic : real;
VvolumeSystem : real;
procedure Init;
end;
TYouTubeOption = record
OnAir : boolean;
StreamKey : string;
procedure Init;
end;
TOptions = class
private
FRID : string;
FVideoFilename : string;
FMinimizeOnRecording: boolean;
function GetFFmpegExecuteParams: string;
function GetFFmpegControllerParams: string;
public
constructor Create;
destructor Destroy; override;
class function Obj:TOptions;
procedure LoadFromFile;
procedure SaveToFile;
public
ScreenOption : TScreenOption;
AudioOption : TAudioOption;
YouTubeOption : TYouTubeOption;
property MinimizeOnRecording : boolean read FMinimizeOnRecording write FMinimizeOnRecording;
property VideoFilename : string read FVideoFilename;
property FFmpegControllerParams: string read GetFFmpegControllerParams;
property FFmpegExecuteParams: string read GetFFmpegExecuteParams;
end;
implementation
{ TScreenOption }
function TScreenOption.GetBitmapHeight: integer;
const BITMAP_CELL_HEIGHT = 2;
begin
Result := FHeight;
if (Result mod BITMAP_CELL_HEIGHT) <> 0 then Result := Result + BITMAP_CELL_HEIGHT - (Result mod BITMAP_CELL_HEIGHT);
end;
function TScreenOption.GetBitmapWidth: integer;
const BITMAP_CELL_WIDTH = 8;
begin
Result := FWidth;
if (Result mod BITMAP_CELL_WIDTH) <> 0 then Result := Result + BITMAP_CELL_WIDTH - (Result mod BITMAP_CELL_WIDTH);
end;
function TScreenOption.GetCanCapture: boolean;
begin
Result := not ((FScreenSource = ssWindow) and (FTargetWindow = 0));
end;
function TScreenOption.GetLeft: integer;
var
WindowRect : TRect;
begin
Result := FLeft;
if FTargetWindow > 0 then begin
GetWindowRect(FTargetWindow, WindowRect);
Result := WindowRect.Left;
end;
end;
function TScreenOption.GetTop: integer;
var
WindowRect : TRect;
begin
Result := FTop;
if FTargetWindow > 0 then begin
GetWindowRect(FTargetWindow, WindowRect);
Result := WindowRect.Top;
end;
end;
procedure TScreenOption.Init;
begin
FScreenSource := ssFull;
FLeft := 0;
FTop := 0;
FWidth := 0;
FHeight := 0;
FTargetWindow := -1;
WithCursor := true;
end;
procedure TScreenOption.SetFullScreen;
begin
FScreenSource := ssFull;
FLeft := 0;
FTop := 0;
FWidth := GetSystemMetrics(SM_CXSCREEN);
FHeight := GetSystemMetrics(SM_CYSCREEN);
FTargetWindow := -1;
end;
procedure TScreenOption.SetScreenRegion(ALeft, ATop, AWidth, AHeight: integer);
begin
FScreenSource := ssRegion;
FLeft := ALeft;
FTop := ATop;
FWidth := AWidth;
FHeight := AHeight;
FTargetWindow := -1;
end;
procedure TScreenOption.SetTargetWindow(const Value: integer);
var
WindowRect : TRect;
begin
FScreenSource := ssWindow;
FTargetWindow := Value;
if FTargetWindow > 0 then begin
GetWindowRect(FTargetWindow, WindowRect);
FWidth := WindowRect.Width;
FHeight := WindowRect.Height;
end;
end;
{ TAudioOption }
procedure TAudioOption.Init;
begin
Mic := -1;
SystemAudio := false;
VolumeMic := 1.0;
VvolumeSystem := 1.0;
end;
{ TYouTubeOption }
procedure TYouTubeOption.Init;
begin
OnAir := false;
StreamKey := '';
end;
{ TOptions }
var
MyObject : TOptions = nil;
class function TOptions.Obj: TOptions;
begin
if MyObject = nil then MyObject := TOptions.Create;
Result := MyObject;
end;
procedure TOptions.SaveToFile;
begin
// TODO:
end;
constructor TOptions.Create;
begin
inherited;
FMinimizeOnRecording := false;
FRID := RandomStr(16);
FVideoFilename := RandomStr(16) + '.mp4';
end;
destructor TOptions.Destroy;
begin
inherited;
end;
function TOptions.GetFFmpegControllerParams: string;
const
fmt : string = '{"rid": "%s", "mic": %d, "system-audio": %s, "volume-mic": %f, "volume-system": %f, "window-handle": %d, "speed": "%s", "left": %d, "top": %d, "width": %d, "height": %d, "with-cursor": %s}';
begin
Result := Format(fmt,
[
FRID, AudioOption.Mic, LowerCase(BoolToStr(AudioOption.SystemAudio, true)), AudioOption.VolumeMic, AudioOption.VvolumeSystem,
ScreenOption.TargetWindow, 'veryfast', ScreenOption.Left, ScreenOption.Top, ScreenOption.Width, ScreenOption.Height, LowerCase(BoolToStr(ScreenOption.WithCursor, true))
]
);
end;
function TOptions.GetFFmpegExecuteParams: string;
const
fmt_live : string = '-framerate 20 -f rawvideo -pix_fmt rgb32 -video_size %dx%d -i \\.\pipe\video-%s -f f32le -acodec pcm_f32le -ar 44100 -ac 1 -i \\.\pipe\audio-%s -f flv rtmp://a.rtmp.youtube.com/live2/%s';
fmt_file : string = '-framerate 20 -f rawvideo -pix_fmt rgb32 -video_size %dx%d -i \\.\pipe\video-%s -f f32le -acodec pcm_f32le -ar 44100 -ac 1 -i \\.\pipe\audio-%s "%s"';
begin
if YouTubeOption.OnAir then begin
Result := Format(fmt_live,
[ScreenOption.BitmapWidth, ScreenOption.BitmapHeight, FRID, FRID, YouTubeOption.StreamKey]
);
end else begin
FVideoFilename := GetTempDirectory + RandomStr(16) + '.mp4';
Result := Format(fmt_file,
[ScreenOption.BitmapWidth, ScreenOption.BitmapHeight, FRID, FRID, FVideoFilename]
);
end;
end;
procedure TOptions.LoadFromFile;
begin
// TODO:
end;
initialization
MyObject := TOptions.Create;
MyObject.AudioOption.Init;
MyObject.ScreenOption.Init;
MyObject.ScreenOption.SetFullScreen;
MyObject.YouTubeOption.Init;
end.
// ffmpeg -framerate 20 -f rawvideo -pix_fmt rgb32 -video_size 1920x1080 -i \\.\pipe\video-1234 -f f32le -acodec pcm_f32le -ar 44100 -ac 1 -i \\.\pipe\audio-1234 test.mp4
// ffmpeg -framerate 10 -f rawvideo -pix_fmt rgb32 -video_size 1920x1080 -i \\.\pipe\pipe-video -f s16le -acodec pcm_s16le -ar 44100 -ac 1 -i \\.\pipe\pipe-audio -f flv rtmp://a.rtmp.youtube.com/live2/62eu-pfcr-y6g5-1tp7-cq8j
|
unit UOrdemServico;
interface
uses SysUtils, Classes, UCliente, UUsuario, UCondicaoPagamento, UProdutoOS,
UParcelas;
type OrdemServico = class
private
protected
NumOS : Integer;
umCliente : Cliente;
umUsuario : Usuario;
umaCondicaoPgto : CondicaoPagamento;
umProdutoOS : ProdutoOS;
umaParcela : Parcelas;
ListaProdutos : TList;
ListaParcelas : TList;
status : string[15];
dataEntrada : TDateTime;
dataSaida : TDateTime;
dataCadastro : TDateTime;
dataAlteracao : TDateTime;
observacao : string[255];
public
Constructor CrieObjeto;
Destructor Destrua_Se;
Procedure setNumOS (vNumOS : Integer);
Procedure setUmCliente (vCliente : Cliente);
Procedure setUmUsuario (vUsuario : Usuario);
Procedure setUmaCondicaoPagamento (vCondicaoPagamento : CondicaoPagamento);
procedure setUmProdutoOS (vProdutoOS : ProdutoOS);
Procedure setStatus (vStatus : String);
Procedure setDataEntrada (vDataEntrada : TDateTime);
Procedure setDataSaida (vDataSaida : TDateTime);
Procedure setDataCadastro (vDataCadastro : TDateTime);
Procedure setDataAlteracao (vDataAlteracao : TDateTime);
Procedure setObservacao (vObservacao : String);
Function getNumOS : Integer;
Function getUmCliente : Cliente;
Function getUmUsuario : Usuario;
Function getUmaCondicaoPagamento : CondicaoPagamento;
Function getUmProdutoOS : ProdutoOS;
Function getStatus : String;
Function getDataEntrada : TDateTime;
Function getDataSaida : TDateTime;
Function getDataCadastro : TDateTime;
Function getDataAlteracao : TDateTime;
Function getObservacao : String;
//Produto
procedure CrieObejtoProduto;
procedure addProdutoOS(vProdutoOS : ProdutoOS);
function getProdutoOS(produto:Integer):ProdutoOS;
procedure LimparListaProduto;
procedure removeItemProdutoOS(Index : Integer);
function CountProdutos : Integer;
//Parcelas
procedure CrieObjetoParcela;
procedure addParcelas(vParcelas : Parcelas);
function getParcelas(parcela:Integer):Parcelas;
procedure LimparListaParcelas;
function CountParcelas : Integer;
end;
implementation
{ OrdemServico }
constructor OrdemServico.CrieObjeto;
var dataAtual : TDateTime;
begin
dataAtual := Date;
NumOS := 0;
umCliente := Cliente.CrieObjeto;
umUsuario := Usuario.CrieObjeto;
umaCondicaoPgto := CondicaoPagamento.CrieObjeto;
ListaProdutos := TList.Create;
ListaParcelas := TList.Create;
status := '';
observacao := '';
dataEntrada := dataAtual;
dataSaida := dataAtual;
dataCadastro := dataAtual;
dataAlteracao := dataAtual;
end;
destructor OrdemServico.Destrua_Se;
begin
ListaProdutos.Destroy;
ListaParcelas.Destroy;
end;
function OrdemServico.getDataAlteracao: TDateTime;
begin
Result := dataAlteracao;
end;
function OrdemServico.getDataCadastro: TDateTime;
begin
Result := dataCadastro;
end;
function OrdemServico.getDataEntrada: TDateTime;
begin
Result := dataEntrada;
end;
function OrdemServico.getDataSaida: TDateTime;
begin
Result := dataSaida;
end;
function OrdemServico.getNumOs: Integer;
begin
Result := NumOs;
end;
function OrdemServico.getObservacao: String;
begin
Result := observacao;
end;
function OrdemServico.getStatus: String;
begin
Result := status;
end;
function OrdemServico.getUmaCondicaoPagamento: CondicaoPagamento;
begin
Result := umaCondicaoPgto;
end;
function OrdemServico.getUmCliente: Cliente;
begin
Result := umCliente;
end;
function OrdemServico.getUmUsuario: Usuario;
begin
Result := umUsuario;
end;
procedure OrdemServico.setDataAlteracao(vDataAlteracao: TDateTime);
begin
dataAlteracao := vDataAlteracao;
end;
procedure OrdemServico.setDataCadastro(vDataCadastro: TDateTime);
begin
dataCadastro := vDataCadastro;
end;
procedure OrdemServico.setDataEntrada(vDataEntrada: TDateTime);
begin
dataEntrada := vDataEntrada;
end;
procedure OrdemServico.setDataSaida(vDataSaida: TDateTime);
begin
dataSaida := vDataSaida;
end;
procedure OrdemServico.setNumOs(vNumOs: Integer);
begin
NumOs := vNumOs;
end;
procedure OrdemServico.setObservacao(vObservacao: String);
begin
observacao := vObservacao;
end;
procedure OrdemServico.setStatus(vStatus: String);
begin
status := vStatus;
end;
procedure OrdemServico.setUmaCondicaoPagamento(vCondicaoPagamento: CondicaoPagamento);
begin
umaCondicaoPgto := vCondicaoPagamento;
end;
procedure OrdemServico.setUmCliente(vCliente: Cliente);
begin
umCliente := vCliente;
end;
procedure OrdemServico.setUmUsuario(vUsuario: Usuario);
begin
umUsuario := vUsuario;
end;
//Produtos
procedure OrdemServico.CrieObejtoProduto;
begin
umProdutoOS := ProdutoOS.CrieObjeto;
end;
procedure OrdemServico.addProdutoOS(vProdutoOS : ProdutoOS);
begin
ListaProdutos.Add(vProdutoOS);
end;
function OrdemServico.CountProdutos: Integer;
begin
Result := ListaProdutos.Count;
end;
procedure OrdemServico.removeItemProdutoOS(Index: Integer);
begin
ListaProdutos.Delete(Index);
end;
function OrdemServico.getProdutoOS(produto: Integer): ProdutoOS;
begin
Result := ListaProdutos[produto];
end;
procedure OrdemServico.LimparListaProduto;
var i : Integer;
begin
for i := 0 to ListaProdutos.Count -1 do
ProdutoOS(ListaProdutos[i]).Free;
ListaProdutos.Clear;
end;
procedure OrdemServico.setUmProdutoOS(vProdutoOS : ProdutoOS);
begin
umProdutoOS := vProdutoOS;
end;
function OrdemServico.getUmProdutoOS: ProdutoOS;
begin
Result := umProdutoOS;
end;
//Parcelas
procedure OrdemServico.CrieObjetoParcela;
begin
umaParcela := Parcelas.CrieObjeto;
end;
procedure OrdemServico.addParcelas(vParcelas: Parcelas);
begin
ListaParcelas.Add(vParcelas);
end;
function OrdemServico.CountParcelas: Integer;
begin
Result := ListaParcelas.Count;
end;
function OrdemServico.getParcelas(parcela: Integer): Parcelas;
begin
Result := ListaParcelas[parcela];
end;
procedure OrdemServico.LimparListaParcelas;
var i : Integer;
begin
for i := 0 to ListaParcelas.Count -1 do
Parcelas(ListaParcelas[i]).Free;
ListaParcelas.Clear;
end;
end.
|
{***********************************************************************
Unit gfx_crypt.PAS v1.2 0801
(c) by Andreas Moser, amoser@amoser.de,
Delphi version : Delphi 4
gfx_crypt is part of the gfx_library collection
You may use this sourcecode for your freewareproducts.
You may modify this source-code for your own use.
You may recompile this source-code for your own use.
All functions, procedures and classes may NOT be used in commercial
products without the permission of the author. For parts of this library
not written by me, you have to ask for permission by their
respective authors.
Disclaimer of warranty: "This software is supplied as is. The author
disclaims all warranties, expressed or implied, including, without
limitation, the warranties of merchantability and of fitness for any
purpose. The author assumes no liability for damages, direct or
consequential, which may result from the use of this software."
All brand and product names are marks or registered marks of their
respective companies.
Please report bugs to:
Andreas Moser amoser@amoser.de
********************************************************************************}
unit gfx_crypt;
interface
uses SysUtils,
classes,
Windows,
JPEG,
Graphics,
io_files,
gfx_basedef,
gfx_files;
{$R-}
procedure EncryptBitmapToFile(SourceBitmap:TBitmap;Key:Integer;Filename:String);
procedure DecryptBitmapFromFile(DestBitmap:TBitmap;Key:Integer;Filename:String);
// Internal functions
procedure EncryptBMP(SourceBitmap,EncryptBitmap:TBitmap;Key:Integer);
procedure DecryptBMP(SourceBitmap,DecryptBitmap:TBitmap;Key:Integer);
implementation
procedure EncryptBitmapToFile(SourceBitmap:TBitmap;Key:Integer;Filename:String);
var EncryptBitmap:TBitmap;
begin
EncryptBitmap:=TBitmap.Create;
try
EncryptBMP(SourceBitmap,EncryptBitmap,Key);
_SaveBMP(EncryptBitmap,Filename);
finally
EncryptBitmap.Free;
end;
end;
procedure DecryptBitmapFromFile(DestBitmap:TBitmap;Key:Integer;Filename:String);
var DecryptBitmap:TBitmap;
begin
DecryptBitmap:=TBitmap.Create;
try
_LoadBMP(DecryptBitmap,Filename);
DecryptBMP(DecryptBitmap,DestBitmap,Key);
finally
DecryptBitmap.Free;
end;
end;
procedure EncryptBMP(SourceBitmap,EncryptBitmap:TBitmap;Key:Integer);
var
i,j,count :integer;
rndValue :byte;
rowSrc,rowDest :pByteArray;
BEGIN
SetBitmapsEql(SourceBitmap,encryptBitmap);
count := abs(Integer(SourceBitmap.Scanline[1])-Integer(SourceBitmap.Scanline[0]));
RandSeed := Key;
for j := 0 to SourceBitmap.Height-1 do
begin
RowSrc := SourceBitmap.Scanline[j];
RowDest := encryptBitmap.Scanline[j];
for i := 0 TO count-1 do
begin
rndValue := Random(256);
RowDest[i] := RowSrc[i] XOR rndValue
end;
end;
end;
procedure DecryptBMP(SourceBitmap,DecryptBitmap:TBitmap;Key:Integer);
var
i,j,count :integer;
rndValue :byte;
rowSrc,rowDest :pByteArray;
BEGIN
SetBitmapsEql(SourceBitmap,DecryptBitmap);
count := abs(Integer(SourceBitmap.Scanline[1])-Integer(SourceBitmap.Scanline[0]));
RandSeed := Key;
for j := 0 to SourceBitmap.Height-1 do
begin
RowSrc := SourceBitmap.Scanline[j];
RowDest := DecryptBitmap.Scanline[j];
for i := 0 TO count-1 do
begin
RndValue := Random(256);
RowDest[i] := RowSrc[i] XOR RndValue
end;
end;
end;
end.
|
{
************************************************************************************************************************
SpiderPage: Contains TSpiderPage component which used to link external HTML files, and use Tag for dynamic contents
Author: Motaz Abdel Azeem
email: motaz@code.sd
Home page: http://code.sd
License: LGPL
Last modifie: 31.7.2012
Jul/2010 - Modified by Luiz Américo
* Remove LCL dependency
************************************************************************************************************************
}
unit SpiderPage;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
TTagEvent = procedure(Sender: TObject; ATag: string; var TagReplacement: string) of object;
{ TSpiderPage }
TSpiderPage = class(TComponent)
private
fPageFileName: string;
fOnTag : TTagEvent;
fTagStart: string;
fTagStop: string;
procedure SetTagStop(ATagStop: string);
{ Private declarations }
protected
{ Protected declarations }
function GetContent: string;
public
constructor Create(TheOwner: TComponent); override;
property Contents: string read GetContent;
{ Public declarations }
published
property PageFileName: string read fPageFileName write fPageFileName;
property TagStart: string read fTagStart write fTagStart;
property TagStop: string read fTagStop write SetTagStop;
property OnTag: TTagEvent read fOnTag write fOnTag;
{ Published declarations }
end;
implementation
{ TSpiderPage }
procedure TSpiderPage.SetTagStop(ATagStop: string);
begin
if ATagStop = fTagStart then
raise Exception.Create('TagStop should not be equal to TagStart')
else
fTagStop:= ATagStop;
end;
function TSpiderPage.GetContent: string;
var
F: TextFile;
Line: string;
OnTagAssigned: Boolean;
ATag: string;
TagReplacement: string;
begin
if FileExists(fPageFileName) then
begin
OnTagAssigned:= Assigned(fOnTag);
AssignFile(F, fPageFileName);
Reset(F);
while not Eof(F) do
begin
Readln(F, Line);
if OnTagAssigned then
while (Pos(fTagStart, Line) > 0) and (Pos(fTagStop, Line) > 0) do
begin
ATag:= Copy(Line, Pos(fTagStart, Line) + Length(fTagStart), Length(Line));
if Pos(fTagStop, ATag) > 0 then
begin
ATag:= Copy(ATag, 1, Pos(fTagStop, ATag) - 1);
TagReplacement:= '';
fOnTag(self, ATag, TagReplacement);
if TagReplacement = '' then
begin
Result:= Result + Copy(Line, 1, Pos(fTagStart, Line) + Length(fTagStart) - 1);
Delete(Line, 1, Pos(fTagStart, Line) + Length(fTagStart) - 1);
end
else
Line:= StringReplace(Line, fTagStart + ATag + fTagStop, TagReplacement, [rfIgnoreCase]);
end
else
begin
Result:= Result + Copy(Line, 1, Pos(fTagStart, Line) + Length(fTagStart) - 1);
Delete(Line, 1, Pos(fTagStart, Line) + Length(fTagStart) - 1);
end;
end;
Result:= Result + Line + #10;
end;
CloseFile(F);
end
else
raise Exception.Create('File: ' + fPageFileName + ' not found');
end;
constructor TSpiderPage.Create(TheOwner: TComponent);
begin
inherited Create(TheOwner);
fTagStart:= '@';
fTagStop:= ';';
end;
end.
|
//2006-11-17 ZswangY37 No.1 修改 鼠标点击的时候没有触发OnSelectionChange事件
//2007-01-02 ZswangY37 No.1 完善 处理没有MouseDown的MouseMove事件(双击文件对话框的时候会出现)
unit LovelyHex20;
interface
uses
Windows, Messages, SysUtils, Classes, Controls, Graphics, Forms;
type
TWMImeChar = packed record
Msg: Cardinal;
case Integer of
0:
(
CharCode: Word;
KeyData: Longint;
Result: Longint
);
1:
(
CharCode1: Byte;
CharCode2: Byte
);
end;
type
TMouseObject = (moNone, moAddress, moHex, moChar);
type
TLovelyHex20 = class(TCustomControl)
private
{ Private declarations }
FMemoryStream: TMemoryStream;
FBaseAddress: Integer;
FLineCount: Integer;
FVisibleChars: Integer;
FTopLine: Integer;
FLeftLine: Integer;
FRowIndex: Integer;
FVisibleLines: Integer;
FItemHeight: Integer;
FItemWidth: Integer;
FColIndex: Integer;
FColType: TMouseObject;
FReadOnly: Boolean;
FSelLength: Integer;
FSelStart: Integer;
FAnchorStart: Integer;
FAnchorOffset: Integer;
FHexChar: Char;
FOnSelectionChange: TNotifyEvent;
FChangeDataSize: Boolean;
FMouseDown: Boolean;
procedure WMGetDlgCode(var Message: TWMGetDlgCode); message WM_GETDLGCODE;
procedure WMVScroll(var Message: TWMVScroll); message WM_VSCROLL;
procedure WMHScroll(var Message: TWMHScroll); message WM_HSCROLL;
procedure WMSize(var Message: TWMSize); message WM_SIZE;
procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED;
procedure AdjustScrollBars;
procedure SetRowIndex(Value: Integer);
procedure SetColIndex(Value: Integer);
procedure SetLeftLine(Value: Integer);
procedure SetTopLine(Value: Integer);
procedure SetBaseAddress(const Value: Integer);
function LineViewText(mLineIndex: Integer): string;
function SelectionViewText(mColType: TMouseObject; mLineIndex: Integer; mStart, mEnd: Integer): string;
property TopLine: Integer read FTopLine write SetTopLine;
property LeftLine: Integer read FLeftLine write SetLeftLine;
function MouseObject(mPoint: TPoint; var nCoordinate: TPoint): TMouseObject;
function CoordinateToPoint(mMouseObject: TMouseObject; mCoordinate: TPoint): TPoint;
function PositionToCoordinate(mPosition: Integer): TPoint;
function CoordinatePosition(mCoordinate: TPoint): Integer;
function ColToChar(mColType: TMouseObject; mCol: Integer): Integer;
procedure SetColType(const Value: TMouseObject);
function RowMaxIndex(mRowIndex: Integer): Integer;
procedure SetReadOnly(const Value: Boolean);
procedure SetSelLength(const Value: Integer);
procedure SetSelStart(Value: Integer);
procedure SetAnchorOffset(Value: Integer);
procedure WMIMECHAR(var Msg: TWMImeChar); message WM_IME_CHAR;
procedure WMCHAR(var Msg: TWMChar); message WM_CHAR;
protected
{ Protected declarations }
function GetSelText: string; virtual;
procedure SetSelText(const Value: string); virtual;
procedure DoChange; virtual;
procedure SelectionChange; virtual;
procedure CreateParams(var Params: TCreateParams); override;
procedure Paint; override;
procedure DoExit; override;
procedure DoEnter; override;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
function DoMouseWheelDown(Shift: TShiftState; MousePos: TPoint): Boolean; override;
function DoMouseWheelUp(Shift: TShiftState; MousePos: TPoint): Boolean; override;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure LoadFromBuffer(const mBuffer; mSize: Integer);
procedure LoadFromStream(mStream: TStream);
procedure LoadFromFile(mFileName: TFileName);
procedure SaveToStream(mStream: TStream);
procedure SaveToFile(mFileName: TFileName);
procedure SaveToBuffer(var nBuffer; mSize: Integer);
property MemoryStream: TMemoryStream read FMemoryStream;
property BaseAddress: Integer read FBaseAddress write SetBaseAddress; //基地址
property RowIndex: Integer read FRowIndex write SetRowIndex; //当前行数
property ColIndex: Integer read FColIndex write SetColIndex; //当前列数
property ColType: TMouseObject read FColType write SetColType; //当前列是否十六进制
property SelStart: Integer read FSelStart write SetSelStart; //选择文本的开始位置
property SelLength: Integer read FSelLength write SetSelLength; //选择文本的长度
property SelText: string read GetSelText write SetSelText; //选中的文本
property AnchorOffset: Integer read FAnchorOffset write SetAnchorOffset;
function ScrollIntoView: Boolean;
procedure UpdateCaret;
published
{ Published declarations }
property Align;
property Anchors;
property Enabled;
property Font;
property Color;
property ReadOnly: Boolean read FReadOnly write SetReadOnly default False; //是否只读
property ChangeDataSize: Boolean read FChangeDataSize write FChangeDataSize default True; //是否能改变大小
property ParentFont;
property ParentColor;
property PopupMenu;
property TabOrder;
property TabStop;
property Visible;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnSelectionChange: TNotifyEvent read FOnSelectionChange write FOnSelectionChange; //选这点改变
end;
procedure Register;
implementation
uses Math, CommonFunctions51;
procedure Register;
begin
RegisterComponents('Lovely20', [TLovelyHex20]);
end;
{ TLovelyHex20 }
procedure TLovelyHex20.AdjustScrollBars;
var
vScrollInfo: TScrollInfo;
begin
SetScrollRange(Handle, SB_VERT, 0, FLineCount, True);
SetScrollRange(Handle, SB_HORZ, 0, 76, True);
vScrollInfo.fMask := SIF_PAGE;
vScrollInfo.nPage := FVisibleLines;
SetScrollInfo(Handle, SB_VERT, vScrollInfo, True);
vScrollInfo.fMask := SIF_PAGE;
vScrollInfo.nPage := FVisibleChars;
SetScrollInfo(Handle, SB_HORZ, vScrollInfo, True);
end;
procedure TLovelyHex20.CMFontChanged(var Message: TMessage);
begin
inherited;
Canvas.Font := Self.Font;
DoChange;
end;
function TLovelyHex20.CoordinateToPoint(mMouseObject: TMouseObject;
mCoordinate: TPoint): TPoint;
begin
case mMouseObject of
moChar, moHex:
begin
Result.Y := mCoordinate.Y * FItemHeight;
Result.X := ColToChar(mMouseObject, mCoordinate.X) * FItemWidth;
end;
moAddress:
begin
Result.Y := mCoordinate.Y * FItemHeight;
Result.X := 0;
end;
else Result := Point(-1, -1);
end;
Result.X := Result.X - FLeftLine * FItemWidth;
Result.Y := Result.Y - FTopLine * FItemHeight;
end;
constructor TLovelyHex20.Create(AOwner: TComponent);
begin
inherited;
ControlStyle := [csFramed, csCaptureMouse];
Width := 300;
Height := 200;
ParentColor := False;
Color := clWindow;
FMemoryStream := TMemoryStream.Create;
DoubleBuffered := True;
FChangeDataSize := True;
FColType := moHex;
end;
procedure TLovelyHex20.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
with Params do
begin
Style := Style or WS_VSCROLL or WS_HSCROLL;
end;
end;
destructor TLovelyHex20.Destroy;
begin
FMemoryStream.Free;
inherited;
end;
procedure TLovelyHex20.DoChange;
begin
FItemHeight := Canvas.TextHeight('A');
FItemWidth := Canvas.TextWidth('D');
FLineCount := (FMemoryStream.Size div 16) + 1;
FVisibleChars := (ClientWidth div Canvas.TextWidth('D')) + 1;
FVisibleLines := (ClientHeight div FItemHeight) + 1;
LeftLine := Min(LeftLine, 76 - FVisibleChars + 1);
TopLine := Min(TopLine, FLineCount - FVisibleLines + 1);
AdjustScrollBars;
UpdateCaret;
Invalidate;
ScrollIntoView;
if Assigned(FOnSelectionChange) then FOnSelectionChange(Self);
end;
function TLovelyHex20.DoMouseWheelDown(Shift: TShiftState;
MousePos: TPoint): Boolean;
begin
Result := inherited DoMouseWheelDown(Shift, MousePos);
Perform(WM_VSCROLL, MakeWParam(SB_PAGEDOWN, 0), 0);
end;
function TLovelyHex20.DoMouseWheelUp(Shift: TShiftState;
MousePos: TPoint): Boolean;
begin
Result := inherited DoMouseWheelUp(Shift, MousePos);
Perform(WM_VSCROLL, MakeWParam(SB_PAGEUP, 0), 0);
end;
procedure TLovelyHex20.KeyDown(var Key: Word; Shift: TShiftState);
var
vCaretPoint: TPoint;
begin
inherited;
case Key of
VK_BACK:
begin
if not FChangeDataSize then Exit;
if FSelLength <= 0 then
begin
if FSelStart <= 0 then Exit;
Dec(FSelStart);
if Stream_Delete(FMemoryStream, FSelStart, 1) then
begin
vCaretPoint := PositionToCoordinate(FSelStart);
FColIndex := vCaretPoint.X;
FRowIndex := vCaretPoint.Y;
DoChange;
end;
end
else begin
if Stream_Delete(FMemoryStream, FSelStart, FSelLength) then
begin
FSelLength := 0;
vCaretPoint := PositionToCoordinate(FSelStart + FSelLength);
FColIndex := vCaretPoint.X;
FRowIndex := vCaretPoint.Y;
DoChange;
end;
end;
end;
VK_DELETE:
begin
if not FChangeDataSize then Exit;
if FSelLength <= 0 then
begin
if Stream_Delete(FMemoryStream, FSelStart, 1) then DoChange;
end
else begin
if Stream_Delete(FMemoryStream, FSelStart, FSelLength) then
begin
FSelLength := 0;
vCaretPoint := PositionToCoordinate(FSelStart + FSelLength);
FColIndex := vCaretPoint.X;
FRowIndex := vCaretPoint.Y;
DoChange;
end;
end;
end;
VK_SHIFT:
begin
if FSelLength <= 0 then
begin
FAnchorStart := FSelStart;
FAnchorOffset := 0;
FHexChar := #0;
end;
end;
VK_DOWN:
begin
if ssShift in Shift then
AnchorOffset := AnchorOffset + 16
else
begin
RowIndex := RowIndex + 1;
SelectionChange;
end;
end;
VK_UP:
begin
if ssShift in Shift then
AnchorOffset := AnchorOffset - 16
else
begin
RowIndex := RowIndex - 1;
SelectionChange;
end;
end;
VK_NEXT:
begin
RowIndex := RowIndex + FVisibleLines;
if ssShift in Shift then
else SelectionChange;
end;
VK_PRIOR:
begin
RowIndex := RowIndex - FVisibleLines;
if ssShift in Shift then
else SelectionChange;
end;
VK_HOME:
begin
ColIndex := 0;
if ssCtrl in Shift then RowIndex := 0;
if ssShift in Shift then
else SelectionChange;
end;
VK_END:
begin
ColIndex := 15;
if ssCtrl in Shift then RowIndex := FLineCount - 1;
if ssShift in Shift then
else SelectionChange;
end;
VK_LEFT:
begin
if ssShift in Shift then
AnchorOffset := AnchorOffset - 1
else
begin
if ColIndex > 0 then
ColIndex := ColIndex - 1
else if RowIndex > 0 then
begin
RowIndex := RowIndex - 1;
ColIndex := RowMaxIndex(RowIndex);
end;
SelectionChange;
end;
end;
VK_RIGHT:
begin
if ssShift in Shift then
AnchorOffset := AnchorOffset + 1
else
begin
if ColIndex < 15 then
ColIndex := ColIndex + 1
else if RowIndex < FLineCount - 1 then
begin
ColIndex := 0;
RowIndex := RowIndex + 1;
end;
SelectionChange;
end;
end;
VK_TAB: if ColType = moHex then ColType := moChar else ColType := moHex;
end;
end;
function TLovelyHex20.LineViewText(mLineIndex: Integer): string;
const
cHexDigits : array[0..15] of Char = '0123456789ABCDEF';
var
I, L: Integer;
vBytes: array[0..15] of Byte;
S: string;
begin
Result := ''; //StringOfChar(' ', 76);
if mLineIndex < 0 then Exit;
FMemoryStream.Position := mLineIndex * 16;
L := FMemoryStream.Read(vBytes, 16);
Result := Format('%.8x ', [FBaseAddress + mLineIndex * 16]);
S := '';
for I := 0 to 15 do
begin
if I = 8 then Result := Result + ' ';
if I < L then
begin
if vBytes[I] in [32..126] then
S := S + Chr(vBytes[I])
else S := S + '.';
Result := Result + cHexDigits[vBytes[I] shr $04] +
cHexDigits[vBytes[I] and $0F] + ' '
end else
begin
Result := Result + ' ';
S := S + ' ';
end;
end;
Result := Result + ' ' + S;
end;
procedure TLovelyHex20.LoadFromFile(mFileName: TFileName);
begin
if FileExists(mFileName) then
FMemoryStream.LoadFromFile(mFileName)
else FMemoryStream.Clear;
FSelLength := 0;
FSelStart := 0;
FColIndex := 0;
FRowIndex := 0;
DoChange;
end;
procedure TLovelyHex20.LoadFromStream(mStream: TStream);
begin
FMemoryStream.Clear;
FMemoryStream.LoadFromStream(mStream);
FSelLength := 0;
FSelStart := 0;
FColIndex := 0;
FRowIndex := 0;
DoChange;
end;
procedure TLovelyHex20.MouseDown(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
var
vCoordinate: TPoint;
begin
inherited;
FMouseDown := True;
if not Focused then SetFocus;
if Button = mbRight then Exit;
case MouseObject(Point(X, Y), vCoordinate) of
moAddress: ;
moHex:
begin
FColIndex := vCoordinate.X;
FColType := moHex;
FRowIndex := vCoordinate.Y;
FSelStart := Max(Min(CoordinatePosition(vCoordinate), FMemoryStream.Size), 0);
vCoordinate := PositionToCoordinate(FSelStart);
FColIndex := vCoordinate.X;
FRowIndex := vCoordinate.Y;
FAnchorStart := FSelStart;
FAnchorOffset := 0;
FHexChar := #0;
SelLength := 0;
UpdateCaret;
SelectionChange;
end;
moChar:
begin
FColIndex := vCoordinate.X;
FColType := moChar;
RowIndex := vCoordinate.Y;
FSelStart := Max(Min(CoordinatePosition(vCoordinate), FMemoryStream.Size), 0);
vCoordinate := PositionToCoordinate(FSelStart);
FColIndex := vCoordinate.X;
FRowIndex := vCoordinate.Y;
FAnchorStart := FSelStart;
FAnchorOffset := 0;
FHexChar := #0;
SelLength := 0;
UpdateCaret;
SelectionChange; //2006-11-17 ZswangY37 No.1
end;
moNone:;
end;
end;
procedure TLovelyHex20.MouseMove(Shift: TShiftState; X, Y: Integer);
var
vCoordinate: TPoint;
vAnchorType: TMouseObject;
begin
inherited;
if not Focused then Exit;
{ TODO -c2006.11.17 -oZswangY37 : 考虑拖拽移动内容 }
if FMouseDown and (ssLeft in Shift) then //2007-01-02 ZswangY37 No.1
begin
vCoordinate := CoordinateToPoint(FColType, Point(15, 0));
if X >= vCoordinate.X + FItemWidth then
begin
vCoordinate := CoordinateToPoint(FColType, Point(0, 0));
X := vCoordinate.X;
Y := Y + FItemHeight;
end;
vCoordinate := CoordinateToPoint(FColType, Point(0, 0));
X := Max(vCoordinate.X, X);
vCoordinate := CoordinateToPoint(FColType, Point(15, 0));
X := Min(vCoordinate.X, X);
vAnchorType := MouseObject(Point(X, Y), vCoordinate);
if vAnchorType <> FColType then Exit;
AnchorOffset := CoordinatePosition(vCoordinate) - FAnchorStart;
end;
case MouseObject(Point(X, Y), vCoordinate) of
moAddress: Cursor := crDefault;
moHex: Cursor := crIBeam;
moChar: Cursor := crIBeam;
moNone: Cursor := crDefault;
end;
end;
function TLovelyHex20.MouseObject(mPoint: TPoint;
var nCoordinate: TPoint): TMouseObject;
var
vRow, vCol: Integer;
begin
vRow := (mPoint.Y + FItemHeight * FTopLine) div FItemHeight;
vCol := (mPoint.X + FItemWidth * FLeftLine + FItemWidth div 2) div FItemWidth;
case vCol of
0..9:
begin
Result := moAddress;
nCoordinate.X := vRow;
nCoordinate.Y := vRow;
end;
10..58:
begin
Result := moHex;
case vCol of
10..33: nCoordinate.X := (vCol - 10) div 3;
34..35: nCoordinate.X := 8;
36..58:
begin
nCoordinate.X := (vCol - 11) div 3;
end;
else nCoordinate.X := vCol;
end;
nCoordinate.Y := vRow;
end;
60..76:
begin
Result := moChar;
nCoordinate.X := Min(vCol - 60, 15);
nCoordinate.Y := vRow;
end;
else Result := moNone;
end;
end;
procedure TLovelyHex20.Paint;
var
I: Integer;
vSelStart, vSelEnd: TPoint;
vCurrLine: Integer;
vPoint: TPoint;
vRect: TRect;
vUnColType: TMouseObject;
begin
inherited;
Canvas.Brush.Style := bsClear;
Canvas.Font.Assign(Font);
if FSelLength > 0 then
begin
vSelStart := PositionToCoordinate(FSelStart);
vSelEnd := PositionToCoordinate(FSelStart + FSelLength - 1);
end;
for I := 0 to FVisibleLines - 1 do
begin
vCurrLine := I + FTopLine;
if vCurrLine >= FLineCount then Break;
Canvas.TextOut(
-FItemWidth * FLeftLine, I * FItemHeight, LineViewText(vCurrLine));
///////Begin 绘制选中区域
if (FSelLength > 0) and
(vCurrLine >= vSelStart.Y) and (vCurrLine <= vSelEnd.Y) then
begin
Canvas.Brush.Color := clHighlight;
Canvas.Font.Color := clHighlightText;
if (vCurrLine = vSelStart.Y) and (vCurrLine = vSelEnd.Y) then
begin
vPoint := CoordinateToPoint(FColType, Point(vSelStart.X, vCurrLine));
Canvas.TextOut(
vPoint.X, vPoint.Y, SelectionViewText(FColType, vCurrLine, vSelStart.X, vSelEnd.X));
end else if vCurrLine = vSelStart.Y then
begin
vPoint := CoordinateToPoint(FColType, Point(vSelStart.X, vCurrLine));
Canvas.TextOut(
vPoint.X, vPoint.Y, SelectionViewText(FColType, vCurrLine, vSelStart.X, 15));
end else if vCurrLine = vSelEnd.Y then
begin
vPoint := CoordinateToPoint(FColType, Point(0, vCurrLine));
Canvas.TextOut(
vPoint.X, vPoint.Y, SelectionViewText(FColType, vCurrLine, 0, vSelEnd.X))
end else if (vCurrLine > vSelStart.Y) and (vCurrLine < vSelEnd.Y) then
begin
vPoint := CoordinateToPoint(FColType, Point(0, vCurrLine));
Canvas.TextOut(
vPoint.X, vPoint.Y, SelectionViewText(FColType, vCurrLine, 0, 15))
end;
Canvas.Brush.Style := bsClear;
if FColType = moChar then
vUnColType := moHex
else vUnColType := moChar;
if (vCurrLine = vSelStart.Y) and (vCurrLine = vSelEnd.Y) then
begin
vRect.TopLeft := CoordinateToPoint(vUnColType, Point(vSelStart.X, vCurrLine));
vRect.BottomRight := CoordinateToPoint(vUnColType, Point(vSelEnd.X, vCurrLine));
vRect.BottomRight.X := vRect.BottomRight.X + FItemWidth *(1 + Ord(vUnColType = moHex));
vRect.BottomRight.Y := vRect.BottomRight.Y + FItemHeight;
Canvas.Rectangle(vRect);
end else if vCurrLine = vSelStart.Y then
begin
vRect.TopLeft := CoordinateToPoint(vUnColType, Point(vSelStart.X, vCurrLine));
vRect.BottomRight := CoordinateToPoint(vUnColType, Point(15, vCurrLine));
vRect.BottomRight.X := vRect.BottomRight.X + FItemWidth *(1 + Ord(vUnColType = moHex));
vRect.BottomRight.Y := vRect.BottomRight.Y + FItemHeight;
Canvas.MoveTo(vRect.TopLeft.X, vRect.TopLeft.Y);
Canvas.LineTo(vRect.TopLeft.X, vRect.BottomRight.Y);
Canvas.MoveTo(vRect.BottomRight.X, vRect.TopLeft.Y);
Canvas.LineTo(vRect.BottomRight.X, vRect.BottomRight.Y);
Canvas.MoveTo(vRect.TopLeft.X, vRect.TopLeft.Y);
Canvas.LineTo(vRect.BottomRight.X, vRect.TopLeft.Y);
vRect.BottomRight := CoordinateToPoint(vUnColType, Point(0, vCurrLine));
vRect.BottomRight.Y := vRect.BottomRight.Y + FItemHeight;
Canvas.MoveTo(vRect.TopLeft.X, vRect.BottomRight.Y);
Canvas.LineTo(vRect.BottomRight.X, vRect.BottomRight.Y);
end else if vCurrLine = vSelEnd.Y then
begin
vRect.TopLeft := CoordinateToPoint(vUnColType, Point(0, vCurrLine));
vRect.BottomRight := CoordinateToPoint(vUnColType, Point(vSelEnd.X, vCurrLine));
vRect.BottomRight.X := vRect.BottomRight.X + FItemWidth *(1 + Ord(vUnColType = moHex));
vRect.BottomRight.Y := vRect.BottomRight.Y + FItemHeight;
Canvas.MoveTo(vRect.TopLeft.X, vRect.TopLeft.Y);
Canvas.LineTo(vRect.TopLeft.X, vRect.BottomRight.Y);
Canvas.MoveTo(vRect.BottomRight.X, vRect.TopLeft.Y);
Canvas.LineTo(vRect.BottomRight.X, vRect.BottomRight.Y);
Canvas.MoveTo(vRect.TopLeft.X, vRect.BottomRight.Y);
Canvas.LineTo(vRect.BottomRight.X, vRect.BottomRight.Y);
vRect.TopLeft := CoordinateToPoint(vUnColType, Point(vSelEnd.X, vCurrLine));
vRect.TopLeft.X := vRect.TopLeft.X + FItemWidth *(1 + Ord(vUnColType = moHex));
vRect.BottomRight := CoordinateToPoint(vUnColType, Point(15, vCurrLine));
vRect.BottomRight.X := vRect.BottomRight.X + FItemWidth *(1 + Ord(vUnColType = moHex));
Canvas.MoveTo(vRect.TopLeft.X, vRect.TopLeft.Y);
Canvas.LineTo(vRect.BottomRight.X, vRect.TopLeft.Y);
end else if (vCurrLine > vSelStart.Y) and (vCurrLine < vSelEnd.Y) then
begin
vRect.TopLeft := CoordinateToPoint(vUnColType, Point(0, vCurrLine));
vRect.BottomRight := CoordinateToPoint(vUnColType, Point(15, vCurrLine));
vRect.BottomRight.X := vRect.BottomRight.X + FItemWidth *(1 + Ord(vUnColType = moHex));
vRect.BottomRight.Y := vRect.BottomRight.Y + FItemHeight;
Canvas.MoveTo(vRect.TopLeft.X, vRect.TopLeft.Y);
Canvas.LineTo(vRect.TopLeft.X, vRect.BottomRight.Y);
Canvas.MoveTo(vRect.BottomRight.X, vRect.TopLeft.Y);
Canvas.LineTo(vRect.BottomRight.X, vRect.BottomRight.Y);
end;
Canvas.Font.Assign(Font);
end;
///////End 绘制选中区域
end;
end;
procedure TLovelyHex20.SaveToFile(mFileName: TFileName);
begin
FMemoryStream.SaveToFile(mFileName);
end;
procedure TLovelyHex20.SaveToStream(mStream: TStream);
begin
FMemoryStream.SaveToStream(mStream);
end;
function TLovelyHex20.ScrollIntoView: Boolean;
var
vCharIndex: Integer;
begin
Result := False;
if FRowIndex < FTopLine then
begin
Result := True;
TopLine := FRowIndex;
end
else if FRowIndex >= (FTopLine + FVisibleLines) - 1 then
begin
TopLine := FRowIndex - (FVisibleLines - 2);
Result := True;
end;
vCharIndex := ColToChar(FColType, FColIndex);
if vCharIndex < FLeftLine then
begin
Result := True;
LeftLine := vCharIndex;
end
else if vCharIndex >= (FLeftLine + FVisibleChars) - 1 then
begin
Result := True;
LeftLine := vCharIndex - (FVisibleChars - 2);
end;
AdjustScrollBars;
end;
procedure TLovelyHex20.SetBaseAddress(const Value: Integer);
begin
FBaseAddress := Value;
Invalidate;
end;
procedure TLovelyHex20.SetRowIndex(Value: Integer);
var
R: TRect;
begin
if Value <> FRowIndex then
begin
if Value < 0 then Value := 0;
if Value >= FLineCount then Value := FLineCount - 1;
if (FRowIndex >= FTopLine) and (FRowIndex < FTopLine + FVisibleLines - 1) then
begin
R := Bounds(0, 0, 1, FItemHeight);
OffsetRect(R, 0, (FRowIndex - FTopLine) * FItemHeight);
Windows.InvalidateRect(Handle, @R, True);
end;
FRowIndex := Value;
R := Bounds(0, 0, 1, FItemHeight);
OffsetRect(R, 0, (FRowIndex - FTopLine) * FItemHeight);
Windows.InvalidateRect(Handle, @R, True);
if FRowIndex = FLineCount - 1 then
begin
ColIndex := Min(ColIndex, RowMaxIndex(FRowIndex));
ScrollIntoView;
UpdateCaret;
Exit;
end;
ScrollIntoView;
UpdateCaret;
end;
end;
procedure TLovelyHex20.SetLeftLine(Value: Integer);
var
LinesMoved: Integer;
vRect: TRect;
begin
if Value <> FLeftLine then
begin
if Value < 0 then Value := 0;
if Value >= 76 then Value := 76 - 1;
LinesMoved := FLeftLine - Value;
FLeftLine := Value;
SetScrollPos(Handle, SB_HORZ, FLeftLine, True);
if Abs(LinesMoved) = 1 then
begin
vRect := Bounds(1, 0, ClientWidth - FItemWidth, ClientHeight);
if LinesMoved = 1 then OffsetRect(vRect, FItemWidth, 0);
ScrollWindow(Handle, FItemWidth * LinesMoved, 0, @vRect, nil);
if LinesMoved = -1 then
begin
vRect.Left := ClientWidth - FItemWidth;
vRect.Right := ClientWidth;
end
else
begin
vRect.Left := 0;
vRect.Right := FItemWidth;
end;
InvalidateRect(Handle, @vRect, False);
end else Invalidate;
UpdateCaret;
end;
end;
procedure TLovelyHex20.SetTopLine(Value: Integer);
var
LinesMoved: Integer;
vRect: TRect;
begin
if Value <> FTopLine then
begin
if Value < 0 then Value := 0;
if Value >= FLineCount then Value := FLineCount - 1;
LinesMoved := FTopLine - Value;
FTopLine := Value;
SetScrollPos(Handle, SB_VERT, FTopLine, True);
if Abs(LinesMoved) = 1 then
begin
vRect := Bounds(1, 0, ClientWidth, ClientHeight - FItemHeight);
if LinesMoved = 1 then OffsetRect(vRect, 0, FItemHeight);
ScrollWindow(Handle, 0, FItemHeight * LinesMoved, @vRect, nil);
if LinesMoved = -1 then
begin
vRect.Top := ClientHeight - FItemHeight;
vRect.Bottom := ClientHeight;
end
else
begin
vRect.Top := 0;
vRect.Bottom := FItemHeight;
end;
InvalidateRect(Handle, @vRect, False);
end else Invalidate;
UpdateCaret;
end;
end;
procedure TLovelyHex20.UpdateCaret;
var
vPos: TPoint;
begin
DestroyCaret;
if not Focused then Exit;
if FSelLength > 0 then Exit;
CreateCaret(Handle, 0, 2, Canvas.TextHeight('|'));
ShowCaret(Handle);
vPos := CoordinateToPoint(FColType, Point(FColIndex, FRowIndex));
if (FColType = moHex) and (FHexChar <> #0) then
vPos.X := vPos.X + FItemWidth * 2;
SetCaretPos(vPos.X, vPos.Y);
end;
procedure TLovelyHex20.WMGetDlgCode(var Message: TWMGetDlgCode);
begin
Message.Result := DLGC_WANTARROWS or DLGC_WANTTAB;
end;
procedure TLovelyHex20.WMHScroll(var Message: TWMHScroll);
var
NewLeftLine: Integer;
LinesMoved: Integer;
vRect: TRect;
begin
inherited;
if not Focused then SetFocus;
NewLeftLine := FLeftLine;
case Message.ScrollCode of
SB_LINEDOWN: Inc(NewLeftLine);
SB_LINEUP: Dec(NewLeftLine);
SB_PAGEDOWN: Inc(NewLeftLine, FVisibleLines - 1);
SB_PAGEUP: Dec(NewLeftLine, FVisibleLines - 1);
SB_THUMBPOSITION, SB_THUMBTRACK: NewLeftLine := Message.Pos;
end;
if NewLeftLine >= 76 - FVisibleChars + 1 then
NewLeftLine := 76 - FVisibleChars + 1;
if NewLeftLine < 0 then NewLeftLine := 0;
if NewLeftLine <> FLeftLine then
begin
LinesMoved := FLeftLine - NewLeftLine;
FLeftLine := NewLeftLine;
SetScrollPos(Handle, SB_HORZ, FLeftLine, True);
if Abs(LinesMoved) = 1 then
begin
vRect := Bounds(0, 0, ClientWidth - FItemWidth, ClientHeight);
if LinesMoved = 1 then OffsetRect(vRect, FItemWidth, 0);
ScrollWindow(Handle, FItemWidth * LinesMoved, 0, @vRect, nil);
if LinesMoved = -1 then
begin
vRect.Left := ClientWidth;
vRect.Right := ClientWidth - FItemWidth;
end else
begin
vRect.Left := 0;
vRect.Right := FItemWidth;
end;
Windows.InvalidateRect(Handle, @vRect, False);
end else Invalidate;
UpdateCaret;
end;
end;
procedure TLovelyHex20.WMSize(var Message: TWMSize);
begin
inherited;
DoChange;
end;
procedure TLovelyHex20.WMVScroll(var Message: TWMVScroll);
{$J+}
const
vPos: Integer = 0;
vTracking: Boolean = False;
vMouseY: Integer = 0;
{$J-}
var
NewTopLine: Integer;
LinesMoved: Integer;
I: Integer;
vRect: TRect;
begin
inherited;
if not Focused then SetFocus;
NewTopLine := FTopLine;
case Message.ScrollCode of
SB_LINEDOWN: Inc(NewTopLine);
SB_LINEUP: Dec(NewTopLine);
SB_PAGEDOWN: Inc(NewTopLine, FVisibleLines div 2);
SB_PAGEUP: Dec(NewTopLine, FVisibleLines div 2);
SB_THUMBPOSITION: vTracking := False;
SB_THUMBTRACK:
begin
if not vTracking then
begin
vPos := Message.Pos;
vMouseY := Mouse.CursorPos.Y;
end;
vTracking := True;
I := Message.Pos - vPos;
if (I > 0) and (vMouseY > Mouse.CursorPos.Y) then
I := (Message.Pos) - (High(Smallint) * 2 + vPos);
if (I < 0) and (vMouseY < Mouse.CursorPos.Y) then
I := (High(Smallint) * 2 + Message.Pos) - vPos;
NewTopLine := GetScrollPos(Handle, SB_VERT) + I;
vPos := Message.Pos;
vMouseY := Mouse.CursorPos.Y;
end;
end;
if NewTopLine >= FLineCount - FVisibleLines + 1 then
NewTopLine := FLineCount - FVisibleLines + 1;
if NewTopLine < 0 then NewTopLine := 0;
if NewTopLine <> FTopLine then
begin
LinesMoved := FTopLine - NewTopLine;
FTopLine := NewTopLine;
SetScrollPos(Handle, SB_VERT, FTopLine, True);
if Abs(LinesMoved) = 1 then
begin
vRect := Bounds(0, 0, ClientWidth, ClientHeight - FItemHeight);
if LinesMoved = 1 then OffsetRect(vRect, 0, FItemHeight);
ScrollWindow(Handle, 0, FItemHeight * LinesMoved, @vRect, nil);
if LinesMoved = -1 then
begin
vRect.Top := ClientHeight - FItemHeight;
vRect.Bottom := ClientHeight;
end else
begin
vRect.Top := 0;
vRect.Bottom := FItemHeight;
end;
Windows.InvalidateRect(Handle, @vRect, False);
end else Invalidate;
UpdateCaret;
end;
end;
procedure TLovelyHex20.SetColIndex(Value: Integer);
var
R: TRect;
vCharIndex: Integer;
begin
if Value <> FColIndex then
begin
if Value < 0 then Value := 0;
if Value > RowMaxIndex(FRowIndex) then Value := RowMaxIndex(FRowIndex);
FColIndex := Value;
vCharIndex := ColToChar(FColType, FColIndex);
if (vCharIndex >= FLeftLine) and (vCharIndex < FLeftLine + 76 - 1) then
begin
R := Bounds(0, 0, 1, FItemHeight);
OffsetRect(R, (vCharIndex - FLeftLine) * FItemWidth, 0);
Windows.InvalidateRect(Handle, @R, True);
end;
FColIndex := Value;
vCharIndex := ColToChar(FColType, FColIndex);
R := Bounds(0, 0, 1, FItemHeight);
OffsetRect(R, (vCharIndex - FLeftLine) * FItemWidth, 0);
Windows.InvalidateRect(Handle, @R, True);
ScrollIntoView;
UpdateCaret;
end;
end;
procedure TLovelyHex20.SetColType(const Value: TMouseObject);
begin
if FColType = Value then Exit;
FColType := Value;
ScrollIntoView;
UpdateCaret;
Invalidate;
end;
function TLovelyHex20.RowMaxIndex(mRowIndex: Integer): Integer;
begin
if mRowIndex < 0 then
Result := 0
else if mRowIndex >= FLineCount then
Result := 0
else if mRowIndex = FLineCount - 1 then
Result := FMemoryStream.Size mod 16
else Result := 15;
end;
function TLovelyHex20.ColToChar(mColType: TMouseObject;
mCol: Integer): Integer;
begin
Result := 0;
case mColType of
moChar: Result := 60 + mCol;
moHex:
begin
case mCol of
0..7: Result := 10 + mCol * 3;
8..15: Result := 11 + mCol * 3;
end;
end;
end;
end;
procedure TLovelyHex20.SetReadOnly(const Value: Boolean);
begin
if FReadOnly = Value then Exit;
FReadOnly := Value;
if FReadOnly then Cursor := crDefault;
end;
procedure TLovelyHex20.SetSelLength(const Value: Integer);
var
vCaretPoint: TPoint;
begin
if FSelLength = Value then Exit;
FSelLength := Max(Min(Value, FMemoryStream.Size - FSelStart), 0);
if Assigned(FOnSelectionChange) then FOnSelectionChange(Self);
vCaretPoint := PositionToCoordinate(FSelStart + FSelLength);
FColIndex := vCaretPoint.X;
FRowIndex := vCaretPoint.Y;
Invalidate;
end;
procedure TLovelyHex20.SetSelStart(Value: Integer);
var
vCaretPoint: TPoint;
begin
if FSelStart = Value then Exit;
FSelStart := Max(Min(Value, FMemoryStream.Size), 0);
FSelLength := Max(Min(FSelLength, FMemoryStream.Size - FSelStart), 0);
if Assigned(FOnSelectionChange) then FOnSelectionChange(Self);
vCaretPoint := PositionToCoordinate(FSelStart + FSelLength);
FColIndex := vCaretPoint.X;
FRowIndex := vCaretPoint.Y;
Invalidate;
end;
procedure TLovelyHex20.SelectionChange;
var
vSelLength: Integer;
begin
vSelLength := FSelLength;
FSelStart := Max(Min(FRowIndex * 16 + FColIndex, FMemoryStream.Size), 0);
FSelLength := 0;
FHexChar := #0;
if vSelLength > 0 then Invalidate;
UpdateCaret;
if Assigned(FOnSelectionChange) then FOnSelectionChange(Self);
// TForm(Parent).Caption := Format('SelStart:%d SelLength:%d', [FSelStart, FSelLength]);
end;
function TLovelyHex20.PositionToCoordinate(mPosition: Integer): TPoint;
begin
Result := Point(-1, -1);
if mPosition < 0 then Exit;
if mPosition > FMemoryStream.Size then Exit;
Result.X := mPosition mod 16;
Result.Y := mPosition div 16;
end;
function TLovelyHex20.SelectionViewText(mColType: TMouseObject;
mLineIndex: Integer; mStart, mEnd: Integer): string;
const
cHexDigits : array[0..15] of Char = '0123456789ABCDEF';
var
I, L: Integer;
vBytes: array[0..15] of Byte;
S: string;
begin
Result := '';
if mLineIndex < 0 then Exit;
FMemoryStream.Position := mLineIndex * 16;
L := FMemoryStream.Read(vBytes, 16);
S := '';
for I := Max(0, mStart) to Min(15, mEnd) do
begin
case mColType of
moHex: if I = 8 then Result := Result + ' ';
moChar: ;
end;
if I < L then
begin
case mColType of
moHex:
Result := Result + cHexDigits[vBytes[I] shr $04] +
cHexDigits[vBytes[I] and $0F] + ' ';
moChar:
if vBytes[I] in [32..126] then
Result := Result + Chr(vBytes[I])
else Result := Result + '.';
end;
end;
end;
if mColType = moHex then Result := Trim(Result);
end;
procedure TLovelyHex20.SetAnchorOffset(Value: Integer);
var
vCaretPoint: TPoint;
begin
if FAnchorStart = Value then Exit;
if FAnchorStart + Value < 0 then Exit;
if FAnchorStart + Value > FMemoryStream.Size then Exit;
FAnchorOffset := Value;
FSelLength := Abs(FAnchorOffset);
if FAnchorOffset < 0 then
begin
FSelStart := FAnchorStart + FAnchorOffset;
vCaretPoint := PositionToCoordinate(FSelStart);
end else
begin
FSelStart := FAnchorStart;
vCaretPoint := PositionToCoordinate(FSelStart + FSelLength);
end;
FColIndex := vCaretPoint.X;
FRowIndex := vCaretPoint.Y;
ScrollIntoView;
UpdateCaret;
Invalidate;
if Assigned(FOnSelectionChange) then FOnSelectionChange(Self);
// TForm(Parent).Caption := Format('SelStart:%d SelLength:%d', [FSelStart, FSelLength]);
end;
procedure TLovelyHex20.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
var
vCoordinate: TPoint;
begin
inherited;
FMouseDown := False;
case MouseObject(Point(X, Y), vCoordinate) of
moAddress: Cursor := crDefault;
moHex: Cursor := crIBeam;
moChar: Cursor := crIBeam;
moNone: Cursor := crDefault;
end;
end;
function TLovelyHex20.CoordinatePosition(mCoordinate: TPoint): Integer;
begin
Result :=
Max(Min(mCoordinate.Y * 16 + mCoordinate.X, FMemoryStream.Size), 0);
end;
procedure TLovelyHex20.WMCHAR(var Msg: TWMChar);
var
vChar: Char;
vCoordinate: TPoint;
vRect: TRect;
vSelStart: Integer;
begin
inherited;
if FReadOnly then Exit;
if not FChangeDataSize and (FSelStart >= FMemoryStream.Size) then Exit;
case Msg.CharCode of
0..27, 128..255: Exit;
end;
FMemoryStream.Position := FSelStart;
vSelStart := FSelStart;
if FColType = moHex then
begin
case Msg.CharCode of
Ord('0')..Ord('9'): ;
Ord('A')..Ord('F'): ;
Ord('a')..Ord('f'): ;
else Exit;
end;
if FHexChar = #0 then
begin
FHexChar := Char(Msg.CharCode);
vChar := Char(StrToIntDef('$' + FHexChar, 0));
end else
begin
vChar := Char(StrToIntDef('$' + FHexChar + Char(Msg.CharCode), 0));
FSelStart := FSelStart + 1;
FHexChar := #0;
end;
end else if FColType = moChar then
begin
vChar := Char(Msg.CharCode);
FSelStart := FSelStart + 1;
end;
{ TODO -c2006.11.17 -oZswangY37 : 考虑采用插入模式输入 }
// Stream_Insert(FMemoryStream, FSelStart - 1, vChar, 1);
FMemoryStream.Position := vSelStart;
FMemoryStream.Write(vChar, SizeOf(vChar));
vCoordinate := PositionToCoordinate(FSelStart);
FRowIndex := vCoordinate.Y;
FColIndex := vCoordinate.X;
if FSelStart = FMemoryStream.Size then
DoChange;
if FSelLength > 0 then
begin
FSelLength := 0;
Invalidate;
end else
begin
vCoordinate := PositionToCoordinate(vSelStart);
vRect.TopLeft := CoordinateToPoint(moChar, vCoordinate);
vRect.BottomRight.X := vRect.TopLeft.X + FItemWidth;
vRect.BottomRight.Y := vRect.TopLeft.Y + FItemHeight;
Windows.InvalidateRect(Handle, @vRect, True);
vRect.TopLeft := CoordinateToPoint(moHex, vCoordinate);
vRect.BottomRight.X := vRect.TopLeft.X + FItemWidth * 3;
vRect.BottomRight.Y := vRect.TopLeft.Y + FItemHeight;
Windows.InvalidateRect(Handle, @vRect, True);
end;
UpdateCaret;
end;
procedure TLovelyHex20.WMIMECHAR(var Msg: TWMImeChar);
var
vCoordinate: TPoint;
vRect: TRect;
begin
inherited;
if FReadOnly then Exit;
FMemoryStream.Position := FSelStart;
if FColType = moChar then
begin
{ TODO -c2006.11.17 -oZswangY37 : 考虑采用插入模式输入 }
FMemoryStream.Write(Msg.CharCode, 2);
FSelStart := FSelStart + 2;
vCoordinate := PositionToCoordinate(FSelStart);
FRowIndex := vCoordinate.Y;
FColIndex := vCoordinate.X;
if FSelStart = FMemoryStream.Size then
DoChange;
if FSelLength > 0 then
begin
FSelLength := 0;
Invalidate;
end else
begin
vCoordinate := PositionToCoordinate(FSelStart - 2);
vRect.TopLeft := CoordinateToPoint(moChar, vCoordinate);
vRect.BottomRight.X := vRect.TopLeft.X + FItemWidth * 2;
vRect.BottomRight.Y := vRect.TopLeft.Y + FItemHeight;
Windows.InvalidateRect(Handle, @vRect, True);
vRect.TopLeft := CoordinateToPoint(moHex, vCoordinate);
vRect.BottomRight.X := vRect.TopLeft.X + FItemWidth * 4 * 2;
vRect.BottomRight.Y := vRect.TopLeft.Y + FItemHeight;
Windows.InvalidateRect(Handle, @vRect, True);
end;
UpdateCaret;
end;
end;
function TLovelyHex20.GetSelText: string;
begin
Result := '';
if FSelLength <= 0 then Exit;
SetLength(Result, FSelLength);
FMemoryStream.Position := FSelStart;
FMemoryStream.Read(Result[1], FSelLength);
end;
procedure TLovelyHex20.SetSelText(const Value: string);
var
vCaretPoint: TPoint;
L: Integer;
begin
L := Length(Value);
if (L <= 0) and (FSelLength <= 0) then Exit;
if FSelLength > 0 then
Stream_Delete(FMemoryStream, FSelStart, FSelLength);
if L > 0 then
Stream_Insert(FMemoryStream, FSelStart, Value[1], L);
FSelLength := 0;
FSelStart := FSelStart + L;
vCaretPoint := PositionToCoordinate(FSelStart + FSelLength);
FColIndex := vCaretPoint.X;
FRowIndex := vCaretPoint.Y;
DoChange;
end;
procedure TLovelyHex20.DoEnter;
begin
inherited;
UpdateCaret;
end;
procedure TLovelyHex20.DoExit;
begin
inherited;
UpdateCaret;
end;
procedure TLovelyHex20.LoadFromBuffer(const mBuffer; mSize: Integer);
begin
FMemoryStream.Clear;
FMemoryStream.Write(mBuffer, mSize);
FSelLength := 0;
FSelStart := 0;
FColIndex := 0;
FRowIndex := 0;
DoChange;
end;
procedure TLovelyHex20.SaveToBuffer(var nBuffer; mSize: Integer);
begin
FMemoryStream.Position := 0;
FMemoryStream.Read(nBuffer, mSize);
end;
end.
|
unit HIScore;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.SQLite,
FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs, FireDAC.VCLUI.Wait, Data.DB,
FireDAC.Comp.Client, FireDac.Dapt, Vcl.Grids;
type
THiscore = Record
initials: String[3];
num_moves: Integer;
end;
THiscoreList = array of THiScore;
THiScoreForm = class(TForm)
Conn: TFDConnection;
HiScoreGrid: TStringGrid;
private
procedure CheckTableExist();
function LoadHiScores(): THiscoreList;
procedure UpdateGrid(scores: THiscoreList);
public
constructor Create(owner: TComponent); override;
end;
var
HiScoreForm: THiScoreForm;
implementation
{$R *.dfm}
constructor THiScoreForm.Create(owner: TComponent);
begin
inherited Create(owner);
// Open connection
Conn.Open();
// Ensure that the hiscores table exist.
CheckTableExist();
// Load hiscores and update the grid
UpdateGrid(LoadHiscores());
// Close connection
Conn.Close();
end;
procedure THiScoreForm.CheckTableExist();
var
query: TFDQuery;
begin
// Check if hi score table exists
query := TFDQuery.Create(nil);
query.Connection := Conn;
query.SQL.Text := 'SELECT 1 FROM sqlite_master WHERE type=''table'' AND name=''hiscores'';';
query.OpenOrExecute();
if query.IsEmpty then
// Hi score table does not exist yet.
begin
query.Free();
query := TFDQuery.Create(nil);
query.Connection := Conn;
query.SQL.Text := 'CREATE TABLE hiscores (initials CHAR(3), num_moves INT);';
query.ExecSQL();
query.Free();
end
else query.Free();
end;
function THiscoreForm.LoadHiScores(): THiscoreList;
var
query: TFDQuery;
idx: Integer;
allScores: THiscoreList;
score: ^THiscore;
begin
query := TFDQuery.Create(nil);
query.Connection := Conn;
query.SQL.Text := 'SELECT initials, num_moves FROM hiscores ORDER BY num_moves ASC, initials ASC LIMIT 10;';
query.OpenOrExecute();
if not query.IsEmpty then
begin
// Resize the array to the number of db rows (max 10)
SetLength(allScores, query.RecordCount);
idx := 0;
// Move to db row
query.First();
while not query.Eof do
begin
// For each db row, set the pointer to a specific record in the
// array and write the fields.
score := @allScores[idx];
score.initials := query.FieldByName('initials').Value;
score.num_moves := query.FieldByName('num_moves').Value;
idx := idx + 1;
query.Next();
end;
end;
query.Free();
Result := allScores;
end;
procedure THiscoreForm.UpdateGrid(scores: THiscoreList);
var
i: Integer;
begin
for i := Low(scores) to High(scores) do
begin
HiscoreGrid.Cells[0, i] := scores[i].initials;
HiScoreGrid.Cells[1, i] := IntToStr(scores[i].num_moves);
end;
end;
end.
|
unit iaExample.ProducerThread;
interface
uses
System.Classes,
System.Generics.Collections;
type
TProducerState = (ProducerWorking,
ProducerDone,
ProducerAbortedWithException);
TExampleLinkedProducerThread = class(TThread)
private
fTaskQueue:TThreadedQueue<TObject>;
fQueueTimeout:Cardinal;
fNumberOfTasksToProduce:Integer;
fThreadState:TProducerState;
fTasksProduced:Integer;
fTasksOverflow:Integer;
fQueueFailures:Integer;
public
constructor Create(const pTaskQueue:TThreadedQueue<TObject>; const pQueueTimeout:Cardinal; const pNumberOfTasksToProduce:Integer);
procedure Execute(); override;
property ThreadState:TProducerState read fThreadState write fThreadState;
property TasksProduced:Integer read fTasksProduced write fTasksProduced;
property TasksOverflow:Integer read fTasksOverflow write fTasksOverflow;
property QueueFailures:Integer read fQueueFailures write fQueueFailures;
end;
implementation
uses
System.SysUtils,
System.SyncObjs,
System.RTTI,
iaExample.TaskData,
iaTestSupport.Log;
constructor TExampleLinkedProducerThread.Create(const pTaskQueue:TThreadedQueue<TObject>; const pQueueTimeout:Cardinal; const pNumberOfTasksToProduce:Integer);
const
CreateSuspendedParam = False;
begin
self.FreeOnTerminate := False;
fTaskQueue := pTaskQueue;
fQueueTimeout := pQueueTimeout;
fNumberOfTasksToProduce := pNumberOfTasksToProduce;
fThreadState := TProducerState.ProducerWorking;
inherited Create(CreateSuspendedParam);
end;
procedure TExampleLinkedProducerThread.Execute();
var
i:Integer;
vPushResult:TWaitResult;
vTaskItem:TExampleTaskData;
begin
NameThreadForDebugging('ExampleLinkedProducer_' + FormatDateTime('hhnnss.zzzz', Now));
try
for i := 1 to fNumberOfTasksToProduce do
begin
vTaskItem := TExampleTaskData.Create(i, IntToStr(i));
vPushResult := fTaskQueue.PushItem(vTaskItem);
if vPushResult = TWaitResult.wrSignaled then
begin
Inc(fTasksProduced);
end
else
begin
if (vPushResult = TWaitResult.wrTimeout) then
begin
if fQueueTimeout = INFINITE then
begin
//shouldn't get here
LogIt('PushItem logic failure: Queue timeout was INFINITE but the Push resulted in Timeout');
Inc(fQueueFailures);
end
else
begin
//Timeout was specified and the queue is full, keep producing
//Normal code would likely be to keep trying to add item created to queue
Inc(fTasksOverflow);
end;
end
else
begin
LogIt('PushItem failed: ' + TRttiEnumerationType.GetName(vPushResult));
Inc(fQueueFailures);
end;
vTaskItem.Free();
end;
end;
fThreadState := TProducerState.ProducerDone;
except on E:Exception do
begin
LogIt('Producer thread exception trapped: ' + E.Message);
fThreadState := TProducerState.ProducerAbortedWithException;
end;
end;
end;
end.
|
unit DatesForm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
FMX.Layouts, FMX.Memo, FMX.Controls.Presentation, FMX.ScrollBox;
type
TForm1 = class(TForm)
Memo1: TMemo;
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
procedure Show (const msg: string);
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
type
TDate = class
Month, Day, Year: Integer;
procedure SetValue (m, d, y: Integer);
function LeapYear: Boolean;
end;
type
THusband = class;
TWife = class
husband: THusband;
end;
THusband = class
wife: TWife;
end;
procedure TDate.SetValue(m, d, y: Integer);
begin
Month := m;
Day := d;
Year := y;
end;
function TDate.LeapYear: Boolean;
begin
// call IsLeapYear in SysUtils.pas
Result := IsLeapYear (Year);
end;
procedure TForm1.Button1Click(Sender: TObject);
var
ADay: TDate;
begin
// create
ADay := TDate.Create;
// use
ADay.SetValue (1, 1, 2016);
if ADay.LeapYear then
Show ('Leap year: ' + IntToStr (ADay.Year));
// free the memory (for non ARC platforms)
ADay.Free;
end;
procedure TForm1.Show(const Msg: string);
begin
Memo1.Lines.Add(Msg);
end;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Test Server }
{ }
{ Copyright (c) 2001 Borland Software Corporation }
{ }
{*******************************************************}
unit SvrMainForm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ActnList, StdCtrls, SvrHTTP, Menus, Registry,
ExtCtrls, ComCtrls,
SvrLog, SvrLogFrame, SvrStatsFrame;
type
TWebAppDbgMainForm = class(TForm)
pbToggle: TButton;
ActionList1: TActionList;
ToggleServerAction: TAction;
MainMenu1: TMainMenu;
PropertiesItem: TMenuItem;
StartServer1: TMenuItem;
StopServer1: TMenuItem;
Properties1: TMenuItem;
Exit1: TMenuItem;
N1: TMenuItem;
N2: TMenuItem;
Help1: TMenuItem;
About1: TMenuItem;
ExitAction: TAction;
StopAction: TAction;
StartAction: TAction;
AboutAction: TAction;
PropertiesAction: TAction;
BrowseAction: TAction;
PopupMenu1: TPopupMenu;
Properties2: TMenuItem;
StartServer2: TMenuItem;
StopServer2: TMenuItem;
Exit2: TMenuItem;
Label2: TLabel;
Home: TLabel;
MainUpdateAction: TAction;
ClearAction: TAction;
Label1: TLabel;
Port: TLabel;
GroupBox1: TGroupBox;
LogFrame: TLogFrame;
ToggleLogAction: TAction;
CheckBox1: TCheckBox;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
StatsFrame: TStatsFrame;
procedure ToggleServerActionExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ToggleServerActionUpdate(Sender: TObject);
procedure StopActionExecute(Sender: TObject);
procedure StopActionUpdate(Sender: TObject);
procedure StartActionExecute(Sender: TObject);
procedure StartActionUpdate(Sender: TObject);
procedure PropertiesActionExecute(Sender: TObject);
procedure ExitActionExecute(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure HomeClick(Sender: TObject);
procedure HideActionExecute(Sender: TObject);
procedure SysTray1DblClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure MainUpdateActionExecute(Sender: TObject);
procedure MainUpdateActionUpdate(Sender: TObject);
procedure ToggleLogActionExecute(Sender: TObject);
procedure ToggleLogActionUpdate(Sender: TObject);
procedure AboutActionExecute(Sender: TObject);
private
FShowAtStartup: Boolean;
FActiveAtStartup: Boolean;
FHideOnClose: Boolean;
FWebServer: TCustomWebServer;
FLogOn: Boolean;
function GetSearchPath: string;
function GetServerActive: Boolean;
function GetServerPort: Integer;
procedure SetSearchPath(const Value: string);
procedure SetServerActive(const Value: Boolean);
procedure SetServerPort(const Value: Integer);
function GetDefaultURL: string;
procedure SetDefaultURL(const Value: string);
function CreateRegistry: TRegIniFile;
procedure Load(Reg: TRegIniFile);
procedure Save(Reg: TRegIniFile);
function GetTranslatedDefaultURL: string;
procedure OnLog(Sender: TObject; Transaction: TTransactionLogEntry;
var Release: Boolean);
function GetLogMax: Integer;
procedure SetLogMax(const Value: Integer);
function GetLogDelete: Integer;
procedure SetLogDelete(const Value: Integer);
property ServerActive: Boolean read GetServerActive write SetServerActive;
property ServerSearchPath: string read GetSearchPath write SetSearchPath;
property ServerPort: Integer read GetServerPort write SetServerPort;
property DefaultURL: string read GetDefaultURL write SetDefaultURL;
property TranslatedDefaultURL: string read GetTranslatedDefaultURL;
property LogMax: Integer read GetLogMax write SetLogMax;
property LogDelete: Integer read GetLogDelete write SetLogDelete;
property ShowAtStartup: Boolean read FShowAtStartup write FShowAtStartup;
property ActiveAtStartup: Boolean read FActiveAtStartup write FActiveAtStartup;
property HideOnClose: Boolean read FHideOnClose write FHideOnClose;
property LogOn: Boolean read FLogOn write FLogOn;
end;
var
WebAppDbgMainForm: TWebAppDbgMainForm;
implementation
uses SvrPropDlg, ShellAPI, SvrConst, WebAppDbgAbout;
{$R *.dfm}
procedure TWebAppDbgMainForm.ToggleServerActionExecute(Sender: TObject);
begin
ServerActive := not ServerActive;
end;
procedure TWebAppDbgMainForm.FormCreate(Sender: TObject);
var
Reg: TRegIniFile;
begin
Caption := sWebAppDebugger;
Application.Title := sWebAppDebugger;
FWebServer := TCustomWebServer.Create(Self);
FWebServer.OnLog := OnLog;
FWebServer.Port := 1024;
FWebServer.DefaultURL := 'ServerInfo.ServerInfo'; // Do not localize
FWebServer.SearchPath := '$(DELPHI)\source\webmidas;$(DELPHI)\demos\websnap\images'; // Do not localize
LogOn := True;
ShowAtStartup := True;
ActiveAtStartup := False;
Reg := CreateRegistry;
try
Load(Reg);
finally
Reg.CloseKey;
Reg.Free;
end;
if ActiveAtStartup then
FWebServer.Active := True;
end;
procedure TWebAppDbgMainForm.ToggleServerActionUpdate(Sender: TObject);
begin
if ServerActive then
(Sender as TAction).Caption := sStopServer
else
(Sender as TAction).Caption := sStartServer;
end;
procedure TWebAppDbgMainForm.StopActionExecute(Sender: TObject);
begin
ServerActive := False;
end;
procedure TWebAppDbgMainForm.StopActionUpdate(Sender: TObject);
begin
(Sender as TAction).Enabled := ServerActive;
end;
procedure TWebAppDbgMainForm.StartActionExecute(Sender: TObject);
begin
ServerActive := True;
end;
procedure TWebAppDbgMainForm.StartActionUpdate(Sender: TObject);
begin
(Sender as TAction).Enabled := not ServerActive;
end;
function TWebAppDbgMainForm.GetSearchPath: string;
begin
Result := FWebServer.SearchPath;
end;
function TWebAppDbgMainForm.GetServerActive: Boolean;
begin
Result := FWebServer.Active;
end;
function TWebAppDbgMainForm.GetServerPort: Integer;
begin
Result := FWebServer.Port;
end;
procedure TWebAppDbgMainForm.SetSearchPath(const Value: string);
begin
FWebServer.SearchPath := Value;
end;
procedure TWebAppDbgMainForm.SetServerActive(const Value: Boolean);
begin
FWebServer.Active := Value;
end;
procedure TWebAppDbgMainForm.SetServerPort(const Value: Integer);
begin
if ServerActive and (Value <> FWebServer.Port) then
begin
FWebServer.Active := False;
FWebServer.Port := Value;
FWebServer.Active := True;
end
else
FWebServer.Port := Value;
end;
procedure TWebAppDbgMainForm.PropertiesActionExecute(Sender: TObject);
var
Reg: TRegIniFile;
begin
with TDlgProperties.Create(Application) do
try
ServerPort := Self.ServerPort;
ServerSearchPath := Self.ServerSearchPath;
DefaultURL := Self.DefaultURL;
LogMax := Self.LogMax;
LogDelete := Self.LogDelete;
ShowAtStartup := Self.ShowAtStartup;
ActiveAtStartup := Self.ActiveAtStartup;
HideOnClose := Self.HideOnClose;
LogFrame := Self.LogFrame;
if ShowModal = mrOk then
begin
Self.ServerPort := ServerPort;
Self.ServerSearchPath := ServerSearchPath;
Self.DefaultURL := DefaultURL;
Self.LogMax := LogMax;
Self.LogDelete := LogDelete;
Self.ShowAtStartup := ShowAtStartup;
Self.ActiveAtStartup := ActiveAtStartup;
Self.HideOnClose := HideOnClose;
UpdateColumns;
Reg := CreateRegistry;
try
Save(Reg);
finally
Reg.CloseKey;
Reg.Free;
end;
end;
finally
Free;
end;
end;
procedure TWebAppDbgMainForm.ExitActionExecute(Sender: TObject);
begin
Application.Terminate;
end;
procedure TWebAppDbgMainForm.FormDestroy(Sender: TObject);
var
Reg: TRegIniFile;
begin
LogFrame.SynchColumnInfo;
Reg := CreateRegistry;
try
Save(Reg);
finally
Reg.CloseKey;
Reg.Free;
end;
FWebServer.Free;
end;
procedure TWebAppDbgMainForm.HomeClick(Sender: TObject);
begin
// Add browse code here
if ServerActive then
if TranslatedDefaultURL <> '' then
ShellExecute(Application.Handle, nil,
PChar(TranslatedDefaultURL), nil, nil, SW_SHOWNOACTIVATE);
end;
function TWebAppDbgMainForm.GetDefaultURL: string;
begin
Result := FWebServer.DefaultURL;
end;
procedure TWebAppDbgMainForm.SetDefaultURL(const Value: string);
begin
FWebServer.DefaultURL := Value;
end;
function TWebAppDbgMainForm.CreateRegistry: TRegIniFile;
const
sKey = '\Software\Borland\WebAppDbg'; { do not localize }
begin
Result := TRegIniFile.Create;
try
Result.RootKey := HKEY_LOCAL_MACHINE;
if not Result.OpenKey(sKey, True) then
raise Exception.CreateFmt(sCouldNotOpenRegKey, [sKey]);
except
Result.Free;
raise;
end;
end;
const
sPort = 'Port';
sPath = 'Path';
sDefaultURL = 'DefaultURL';
sLogMax = 'LogMax';
sLogDelete = 'LogDelete';
sShowAtStartup = 'ShowAtStartup';
sActiveAtStartup = 'ActiveAtStartup';
sColumns = 'Columns';
sHideOnClose = 'HideOnClose';
sLogOn = 'LogOn';
sLeft = 'Left';
sTop = 'Top';
sWidth = 'Width';
sHeight = 'Height';
sWindowState = 'WindowState';
procedure TWebAppDbgMainForm.Save(Reg: TRegIniFile);
begin
Reg.WriteInteger('', sPort, ServerPort);
Reg.WriteString('', sPath, ServerSearchPath);
Reg.WriteString('', sDefaultURL, DefaultURL);
Reg.WriteInteger('', sLogMax, LogMax);
Reg.WriteInteger('', sLogDelete, LogDelete);
Reg.WriteBool('', sShowAtStartup, ShowAtStartup);
Reg.WriteBool('', sActiveAtStartup, ActiveAtStartup);
Reg.WriteBool('', sHideOnClose, HideOnClose);
Reg.WriteBool('', sLogOn, LogOn);
Reg.WriteInteger('', sWindowState, Integer(Self.WindowState));
if WindowState = wsNormal then
begin
Reg.WriteInteger('', sLeft, Self.Left);
Reg.WriteInteger('', sTop, Self.Top);
Reg.WriteInteger('', sWidth, Self.Width);
Reg.WriteInteger('', sHeight, Self.Height);
end;
LogFrame.Save(Reg, sColumns);
end;
procedure TWebAppDbgMainForm.Load(Reg: TRegIniFile);
begin
ServerPort := Reg.ReadInteger('', sPort, ServerPort);
ServerSearchPath := Reg.ReadString('', sPath, ServerSearchPath);
DefaultURL := Reg.ReadString('', sDefaultURL, DefaultURL);
LogMax := Reg.ReadInteger('', sLogMax, LogMax);
LogDelete := Reg.ReadInteger('', sLogDelete, LogDelete);
ShowAtStartup := Reg.ReadBool('', sShowAtStartup, ShowAtStartup);
ActiveAtStartup := Reg.ReadBool('', sActiveAtStartup, ActiveAtStartup);
HideOnClose := Reg.ReadBool('', sHideOnClose, HideOnClose);
LogOn := Reg.ReadBool('', sLogOn, LogOn);
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);
Self.WindowState := TWindowState(Reg.ReadInteger('', sWindowState, Integer(Self.WindowState)));
end;
LogFrame.Load(Reg, sColumns);
end;
procedure TWebAppDbgMainForm.HideActionExecute(Sender: TObject);
begin
Visible := False;
end;
procedure TWebAppDbgMainForm.SysTray1DblClick(Sender: TObject);
begin
Visible := not Visible;
end;
procedure TWebAppDbgMainForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TWebAppDbgMainForm.MainUpdateActionExecute(Sender: TObject);
begin
//
end;
procedure TWebAppDbgMainForm.MainUpdateActionUpdate(Sender: TObject);
begin
if (TranslatedDefaultURL <> '') then
Home.Caption := TranslatedDefaultURL
else
Home.Caption := sNoDefaultURL;
if ServerActive and (TranslatedDefaultURL <> '') then
begin
Home.Font.Color := clHighlight;
Home.Font.Style := [fsUnderline];
Home.Cursor := crHandPoint;
end
else
begin
Home.Font.Color := clWindowText;
Home.Font.Style := [];
Home.Cursor := crDefault;
end;
Port.Caption := IntToStr(ServerPort);
end;
function TWebAppDbgMainForm.GetTranslatedDefaultURL: string;
begin
Result := FWebServer.TranslatedDefaultURL;
end;
procedure TWebAppDbgMainForm.OnLog(Sender: TObject; Transaction: TTransactionLogEntry;
var Release: Boolean);
begin
StatsFrame.LogStatistics(Transaction);
if LogOn then
begin
LogFrame.Add(Transaction);
Release := False;
end
else
Release := True;
end;
function TWebAppDbgMainForm.GetLogMax: Integer;
begin
Result := LogFrame.LogMax;
end;
procedure TWebAppDbgMainForm.SetLogMax(const Value: Integer);
begin
LogFrame.LogMax := Value;
end;
function TWebAppDbgMainForm.GetLogDelete: Integer;
begin
Result := LogFrame.LogDelete;
end;
procedure TWebAppDbgMainForm.SetLogDelete(const Value: Integer);
begin
LogFrame.LogDelete := Value;
end;
procedure TWebAppDbgMainForm.ToggleLogActionExecute(Sender: TObject);
begin
FLogOn := CheckBox1.Checked;
end;
procedure TWebAppDbgMainForm.ToggleLogActionUpdate(Sender: TObject);
begin
(Sender as TAction).Checked := FLogOn;
end;
procedure TWebAppDbgMainForm.AboutActionExecute(Sender: TObject);
begin
ShowAboutBox;
end;
end.
|
unit MTLogger;
interface
uses
Windows, SysUtils, Classes, SyncObjs, MTUtils;
type
TLoggerThread = class(TThread)
private
FLogFileName: string;
Event: TEvent;
CritSect: TCriticalSection; // Для защиты списка строк
LogStrings: TStringList;
protected
procedure Execute; override;
public
constructor Create(LogFileName: string);
destructor Destroy; override;
procedure AddToLog(const Msg: string);
end;
var
DefLogger: TLoggerThread;
AllowMessageBoxIfError: Boolean = False;
procedure CreateDefLogger(DefLogFileName: string);
procedure FreeDefLogger;
// Записывает заданную строку текста в указанный файл
procedure WriteStringToTextFile(AFileName: string; Msg: string);
implementation
procedure CreateDefLogger(DefLogFileName: string);
begin
if DefLogger = nil then
DefLogger := TLoggerThread.Create(DefLogFileName);
end;
procedure FreeDefLogger;
begin
FreeAndNil(DefLogger);
end;
procedure WriteStringToTextFile(AFileName: string; Msg: string);
var
AFile: TextFile;
begin
try
// Открываем файл при каждом добавлении строки! При большом объеме записи
// в лог файл это очень нерационально!
AssignFile(AFile, AFileName);
if FileExists(AFileName) then
Append(AFile)
else
Rewrite(AFile);
Writeln(AFile, Msg);
CloseFile(AFile);
except
on E: Exception do
begin
// Внимание! В реальном приложении выдача пользователю сообщения об ошибке
// записи в лог-файл недопустима!
if AllowMessageBoxIfError then
ThreadShowMessageFmt('Ошибка при записи в файл [%s] строки "%s": %s', [AFileName, Msg, E.Message]);
end;
end;
end;
{ TLoggerThread }
procedure TLoggerThread.AddToLog(const Msg: string);
begin
CritSect.Enter;
try
LogStrings.Add(Format('%s [P:%d T:%d] - %s', [FormatDateTime('dd.mm.yyyy hh:nn:ss.zzz', Now),
GetCurrentProcessId, GetCurrentThreadId, Msg]));
finally
CritSect.Leave;
end;
Event.SetEvent;
end;
constructor TLoggerThread.Create(LogFileName: string);
const
STATE_NONSIGNALED = FALSE;
AUTO_RESET = FALSE;
begin
inherited Create(False);
// Создаём объект "Event" в состоянии "nonsignaled" и просим, чтобы
// он автоматически переходил в состояние "nonsignaled" после WaitFor
Event := TEvent.Create(nil, AUTO_RESET, STATE_NONSIGNALED, '', False);
// Создаём список строк LogStrings
LogStrings := TStringList.Create;
// Создаём критическую секцию для защиты списка строк от одновременного
// доступа из нескольких потоков
CritSect := TCriticalSection.Create;
FLogFileName := LogFileName;
end;
destructor TLoggerThread.Destroy;
begin
// Очень важно, чтобы вызов Terminate был раньше вызова SetEvent!
Terminate; // 1. Выставляем флаг Terminated
Event.SetEvent; // 2. Переводим Event в состояние SIGNALED
inherited; // 3. Дожидаемся выхода из метода Execute
Event.Free; // 4. Уничтожаем объект Event
CritSect.Free;
LogStrings.Free;
end;
procedure TLoggerThread.Execute;
var
TmpList: TStringList;
begin
while True do
begin
// Завершаем работу потока в том случае, если пользователь выходит из программы,
// а поток успел скинуть в лог-файл все сообщения из списка LogStrings
if Terminated and (LogStrings.Count = 0) then Exit;
// Ожидаем переключения объекта Event в состояние signaled, но не более 2х секунд
// При вызове метода TLoggerThread.AddToLog выполняется вызов Event.SetEvent,
// однако лучше перестраховаться и не делать ожидание бесконечным
Event.WaitFor(2000);
// Проверяем свойство Count без критической секции (это безопасно)
if LogStrings.Count > 0 then
begin
TmpList := TStringList.Create;
try
// 1. Входим в критическую секцию
CritSect.Enter;
try
// 2. Копируем все строки из LogStrings в TmpList
TmpList.Assign(LogStrings);
// 3. Очищаем список LogStrings
LogStrings.Clear;
finally
// 4. Выходим из критической секции
CritSect.Leave;
end;
// Список TmpList является локальным, поэтому его не нужно защищать
// критической секцией.
// 5. За одно действие записываем все строки из списка TmpList в лог-файл
WriteStringToTextFile(FLogFileName, Trim(TmpList.Text));
finally
TmpList.Free;
end;
end;
end;
end;
end.
|
unit F2C;
interface
function FF2C(Fahrenheit:Double):Double;stdcall;export;
implementation
function FF2C(Fahrenheit:Double):Double;stdcall;
begin
Result:=(Fahrenheit-32)*(5/9);
end;
{ exports
FF2C; }
end.
|
(**********************************************************************************)
(* Code generated with NexusDB Enterprise Manager Data Dictionary Code Generator *)
(* 2020-12-31 16:36:38 *)
(* *)
(* Version: 4.5024 *)
(* *)
(**********************************************************************************)
unit NxDbToolsDbEvolution_1;
interface
uses
nxdb,
nxsdTypes,
nxsdDataDictionary;
type
TnxcgProgressCallback =
procedure(const aTableName : String;
var aStatus : TnxTaskStatus;
var aCancel : Boolean) of object;
type
TnxcgGetPasswordCallback =
procedure(const aTableName : String;
var aPassword : string) of object;
procedure BuildAndEvolveDatabase(aDatabase : TnxDatabase;
aProgressCallback : TnxcgProgressCallback = nil;
aGetPasswordCallback : TnxcgGetPasswordCallback = nil;
const aPassword : String = '');
procedure RestructureDatabase(aDatabase : TnxDatabase;
aProgressCallback : TnxcgProgressCallback = nil;
aGetPasswordCallback : TnxcgGetPasswordCallback = nil;
const aPassword : String = '');
procedure PackDatabase(aDatabase : TnxDatabase;
aProgressCallback : TnxcgProgressCallback = nil;
aGetPasswordCallback : TnxcgGetPasswordCallback = nil;
const aPassword : String = '');
function TableCount: Integer;
function DatabaseVersion: Cardinal;
function DatabaseVersionStr: String;
function GetTableDictionary(aDatabase : TnxDatabase; const aTableName : String): TnxDataDictionary;
implementation
uses
{$IFDEF NXWINAPI}nxWinAPI{$ELSE}Windows{$ENDIF},
Classes,
Math,
SysUtils,
StrUtils,
Variants,
DBCommon,
nxllTypes,
nxllBde,
nxllException,
nxllWideString,
nxsdConst,
nxsdDataDictionaryStrings,
nxsdDataDictionaryRefInt,
nxsdDataDictionaryFulltext,
nxsdDataDictionaryAudit,
nxsdFilterEngineSimpleExpression,
nxsdFilterEngineSql,
nxsdServerEngine,
nxsdFieldMapperDescriptor,
nxsdTableMapperDescriptor;
type
TnxcgCreateDictCallback = function(aDatabase : TnxDatabase): TnxDataDictionary;
// BuNxSqlButtonsDb
function __BuNxSqlButtonsDb(aDatabase : TnxDatabase): TnxDataDictionary;
begin
Result := TnxDataDictionary.Create;
try
with Result do begin
AddRecordDescriptor(TnxBaseRecordDescriptor);
with FieldsDescriptor do begin
AddField('BtnId', '', nxtAutoInc, 10, 0, False);
AddField('PanelNum', '', nxtByte, 1, 0, True);
AddField('BtnTop', '', nxtInt32, 2, 0, True);
AddField('BtnLeft', '', nxtInt32, 10, 0, True);
AddField('BtnWidth', '', nxtInt32, 10, 0, True);
AddField('Caption', '', nxtWideString, 25, 0, True);
AddField('ExtraText', '', nxtWideString, 15, 0, False);
AddField('CursorBeforeThisChar', '', nxtChar, 1, 0, False);
with AddField('SpaceAfterCursor', '', nxtBoolean, 0, 0, False) do
with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do
AsVariant := False;
with AddField('UseExtendedSql', '', nxtBoolean, 0, 0, False) do
with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do
AsVariant := False;
AddField('SqlCode', '', nxtBLOBMemo, 0, 0, False);
end;
with EnsureIndicesDescriptor do begin
with AddIndex('BtnId', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do
Add(GetFieldFromName('BtnId'));
with AddIndex('PanelNum', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do
Add(GetFieldFromName('PanelNum'));
end;
CheckValid(False);
end;
except
FreeAndNil(Result);
raise;
end;
end;
// NxDbSqlToolsPrjs
function __NxDbSqlToolsPrjs(aDatabase : TnxDatabase): TnxDataDictionary;
begin
Result := TnxDataDictionary.Create;
try
with Result do begin
with AddRecordDescriptor(TnxHeapRecordDescriptor) as TnxHeapRecordDescriptor do begin
RecordEngine := 'Variable';
AddRecordCompressionDescriptor;
end;
with FieldsDescriptor do begin
AddField('PrjName', '', nxtWideString, 30, 0, True);
AddField('PrjPath', '', nxtWideString, 255, 0, False);
with AddField('TransportID', '0=tcip, 2=pipe, 3=local', nxtInt32, 10, 0, False) do
with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do
AsVariant := 4;
AddField('Server', '', nxtWideString, 95, 0, False);
AddField('Alias', '', nxtWideString, 95, 0, False);
AddField('PassFileSaveLoc', '', nxtWideString, 255, 0, False);
AddField('DbPassWord', '', nxtWideString, 255, 0, False);
AddField('Memo', '', nxtBLOBMemo, 0, 0, False);
end;
with EnsureIndicesDescriptor do
with AddIndex('PrjName', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do
Add(GetFieldFromName('PrjName'));
CheckValid(False);
end;
except
FreeAndNil(Result);
raise;
end;
end;
// NxSqlButtonsDb
function __NxSqlButtonsDb(aDatabase : TnxDatabase): TnxDataDictionary;
begin
Result := TnxDataDictionary.Create;
try
with Result do begin
AddRecordDescriptor(TnxBaseRecordDescriptor);
with FieldsDescriptor do begin
AddField('BtnId', '', nxtAutoInc, 10, 0, False);
AddField('PanelNum', '', nxtByte, 1, 0, True);
AddField('BtnTop', '', nxtInt32, 2, 0, True);
AddField('BtnLeft', '', nxtInt32, 10, 0, True);
AddField('BtnWidth', '', nxtInt32, 10, 0, True);
AddField('Caption', '', nxtWideString, 25, 0, True);
AddField('ExtraText', '', nxtWideString, 15, 0, False);
AddField('CursorBeforeThisChar', '', nxtChar, 1, 0, False);
with AddField('SpaceAfterCursor', '', nxtBoolean, 0, 0, False) do
with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do
AsVariant := False;
with AddField('UseExtendedSql', '', nxtBoolean, 0, 0, False) do
with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do
AsVariant := False;
AddField('SqlCode', '', nxtBLOBMemo, 0, 0, False);
AddField('Color', '', nxtInt64, 11, 0, False);
AddField('Hints', '', nxtWideString, 255, 0, False);
AddField('NexusDbHelpUrl', '', nxtWideString, 255, 0, False);
end;
with EnsureIndicesDescriptor do begin
with AddIndex('BtnId', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do
Add(GetFieldFromName('BtnId'));
with AddIndex('PanelNum', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do
Add(GetFieldFromName('PanelNum'));
end;
CheckValid(False);
end;
except
FreeAndNil(Result);
raise;
end;
end;
// TransportLUT
function __TransportLUT(aDatabase : TnxDatabase): TnxDataDictionary;
begin
Result := TnxDataDictionary.Create;
try
with Result do begin
AddRecordDescriptor(TnxBaseRecordDescriptor);
with FieldsDescriptor do begin
AddField('TransportID', '', nxtInt32, 10, 0, False);
AddField('Name', '', nxtWideString, 10, 0, False);
end;
CheckValid(False);
end;
except
FreeAndNil(Result);
raise;
end;
end;
type
TnxcgTableInfo = record
TableName : String;
Callback : TnxcgCreateDictCallback;
end;
const
TableInfos : array[0..3] of TnxcgTableInfo =
((TableName : 'BuNxSqlButtonsDb'; Callback : __BuNxSqlButtonsDb),
(TableName : 'NxDbSqlToolsPrjs'; Callback : __NxDbSqlToolsPrjs),
(TableName : 'NxSqlButtonsDb'; Callback : __NxSqlButtonsDb),
(TableName : 'TransportLUT'; Callback : __TransportLUT));
function TableCount: Integer;
begin
Result := Length(TableInfos);
end;
function DatabaseVersion: Cardinal;
begin
Result := Cardinal($01000000);
end;
function DatabaseVersionStr: String;
begin
Result :=
Format('%d.%d.%d.%d',
[(DatabaseVersion and $ff000000) shr 24,
(DatabaseVersion and $00ff0000) shr 16,
(DatabaseVersion and $0000ff00) shr 8,
(DatabaseVersion and $000000ff)]);
end;
function GetTableDictionary(aDatabase : TnxDatabase; const aTableName : String): TnxDataDictionary;
var
I : Integer;
begin
Result := nil;
for I := Low(TableInfos) to High(TableInfos) do
if SameText(aTableName, TableInfos[I].TableName) then begin
Result := TableInfos[I].Callback(aDatabase);
break;
end;
end;
procedure RestructureTable(aDatabase : TnxDatabase;
const aTableName, aPassword : String;
aNewDict : TnxDataDictionary;
aProgressCallback : TnxcgProgressCallback;
var aCancelTask : Boolean;
aFreeDict : Boolean = False);
var
OldDict : TnxDataDictionary;
Mapper : TnxTableMapperDescriptor;
TaskInfo : TnxAbstractTaskInfo;
Completed : Boolean;
TaskStatus : TnxTaskStatus;
begin
try
OldDict := TnxDataDictionary.Create;
try
nxCheck(aDatabase.GetDataDictionaryEx(aTableName, aPassword, OldDict));
if (aPassword <> '') and (aNewDict.EncryptionEngine = '') then
aNewDict.EncryptionEngine := OldDict.EncryptionEngine;
if OldDict.IsEqual(aNewDict) then
Exit;
Mapper := TnxTableMapperDescriptor.Create;
try
Mapper.MapAllTablesAndFieldsByName(OldDict, aNewDict, dlaFail);
nxCheck(aDatabase.RestructureTableEx(aTableName, aPassword, aNewDict, Mapper, TaskInfo));
if Assigned(TaskInfo) then
try
repeat
if not aCancelTask then
TaskInfo.GetStatus(Completed, TaskStatus);
if not Completed then begin
if Assigned(aProgressCallback) then
aProgressCallback(aTableName, TaskStatus, aCancelTask);
if not aCancelTask then
Sleep(100)
else
nxCheck(TaskInfo.Cancel);
end;
until Completed or aCancelTask;
nxCheck(TaskStatus.tsErrorCode);
finally
TaskInfo.Free;
end;
finally
Mapper.Free;
end;
finally
OldDict.Free;
end;
finally
if aFreeDict then
aNewDict.Free;
end;
end;
procedure PackTable(aDatabase : TnxDatabase;
const aTableName, aPassword : String;
aProgressCallback : TnxcgProgressCallback;
var aCancelTask : Boolean);
var
TaskInfo : TnxAbstractTaskInfo;
Completed : Boolean;
TaskStatus : TnxTaskStatus;
begin
nxCheck(aDatabase.PackTableEx(aTableName, aPassword, TaskInfo));
if Assigned(TaskInfo) then
try
repeat
if not aCancelTask then
TaskInfo.GetStatus(Completed, TaskStatus);
if not Completed then begin
if Assigned(aProgressCallback) then
aProgressCallback(aTableName, TaskStatus, aCancelTask);
if not aCancelTask then
Sleep(100)
else
nxCheck(TaskInfo.Cancel);
end;
until Completed or aCancelTask;
nxCheck(TaskStatus.tsErrorCode);
finally
TaskInfo.Free;
end;
end;
procedure BuildAndEvolveTable(aDatabase : TnxDatabase;
const aTableName, aPassword : String;
aCreateDictCallback : TnxcgCreateDictCallback;
aProgressCallback : TnxcgProgressCallback;
var aCancelTask : Boolean);
var
Dict : TnxDataDictionary;
begin
Dict := aCreateDictCallback(aDatabase);
if Assigned(Dict) then
try
if not aDatabase.TableExists(aTableName, aPassword) then
aDatabase.CreateTable(False, aTableName, aPassword, Dict)
else
RestructureTable(aDatabase, aTableName,
aPassword, Dict, aProgressCallback, aCancelTask);
finally
Dict.Free;
end;
end;
procedure BuildAndEvolveDatabase(aDatabase : TnxDatabase;
aProgressCallback : TnxcgProgressCallback = nil;
aGetPasswordCallback : TnxcgGetPasswordCallback = nil;
const aPassword : String = '');
var
I : Integer;
CancelTask : Boolean;
Password : string;
begin
CancelTask := False;
for I := Low(TableInfos) to High(TableInfos) do begin
Password := aPassword;
if Assigned(aGetPasswordCallback) then
aGetPasswordCallback(TableInfos[I].TableName, Password);
BuildAndEvolveTable(aDatabase,
TableInfos[I].TableName, Password,
TableInfos[I].Callback, aProgressCallback, CancelTask);
if CancelTask then
Exit;
end;
end;
procedure RestructureDatabase(aDatabase : TnxDatabase;
aProgressCallback : TnxcgProgressCallback = nil;
aGetPasswordCallback : TnxcgGetPasswordCallback = nil;
const aPassword : String = '');
var
I : Integer;
CancelTask : Boolean;
Password : string;
begin
CancelTask := False;
for I := Low(TableInfos) to High(TableInfos) do begin
Password := aPassword;
if Assigned(aGetPasswordCallback) then
aGetPasswordCallback(TableInfos[I].TableName, Password);
RestructureTable(aDatabase,
TableInfos[I].TableName, Password,
TableInfos[I].Callback(aDatabase), aProgressCallback, CancelTask, True);
if CancelTask then
Exit;
end;
end;
procedure PackDatabase(aDatabase : TnxDatabase;
aProgressCallback : TnxcgProgressCallback = nil;
aGetPasswordCallback : TnxcgGetPasswordCallback = nil;
const aPassword : String = '');
var
I : Integer;
CancelTask : Boolean;
Password : string;
begin
CancelTask := False;
for I := Low(TableInfos) to High(TableInfos) do begin
Password := aPassword;
if Assigned(aGetPasswordCallback) then
aGetPasswordCallback(TableInfos[I].TableName, Password);
PackTable(aDatabase, TableInfos[I].TableName,
Password, aProgressCallback, CancelTask);
if CancelTask then
Exit;
end;
end;
end.
|
(**********************************************************************************)
(* Code generated with NexusDB Enterprise Manager Data Dictionary Code Generator *)
(* *)
(* Version: 3,0401 *)
(* *)
(**********************************************************************************)
unit ncProdU;
interface
uses
nxdb,
nxsdTypes,
nxsdDataDictionary;
type
TnxcgProgressCallback =
procedure(const aTableName : String;
var aStatus : TnxTaskStatus;
var aCancel : Boolean) of object;
procedure BuildAndEvolveProduComIndices(aDatabase : TnxDatabase;
aProgressCallback : TnxcgProgressCallback = nil;
const aPassword : String = '');
procedure RestructureProduComIndices(aDatabase : TnxDatabase;
aProgressCallback : TnxcgProgressCallback = nil;
const aPassword : String = '');
procedure RestructureProduSemIndices(aDatabase : TnxDatabase;
aProgressCallback : TnxcgProgressCallback = nil;
const aPassword : String = '');
procedure PackProdu(aDatabase : TnxDatabase;
aProgressCallback : TnxcgProgressCallback = nil;
const aPassword : String = '');
implementation
uses
{$IFDEF NXWINAPI}nxWinAPI{$ELSE}Windows{$ENDIF},
Classes,
Math,
SysUtils,
StrUtils,
Variants,
DBCommon,
nxllTypes,
nxllBde,
nxllException,
nxllWideString,
nxsdConst,
nxsdDataDictionaryStrings,
nxsdDataDictionaryRefInt,
nxsdDataDictionaryFulltext,
nxsdFilterEngineSimpleExpression,
nxsdFilterEngineSql,
nxsdServerEngine,
nxsdTableMapperDescriptor;
type
TnxcgCreateDictCallback = function(aDatabase : TnxDatabase): TnxDataDictionary;
// produ
function __produComIndices(aDatabase : TnxDatabase): TnxDataDictionary;
begin
Result := TnxDataDictionary.Create;
try
with Result do begin
with FilesDescriptor do
AddFile('idx', nxbs4K, 'indices');
AddRecordDescriptor(TnxBaseRecordDescriptor);
with FieldsDescriptor do begin
AddField('id', '', nxtAutoInc, 10, 0, False);
AddField('codbar', '', nxtShortString, 14, 0, True);
AddField('descricao', '', nxtShortString, 55, 0, False);
AddField('unid', '', nxtShortString, 5, 0, False);
AddField('imagem', '', nxtBLOBGraphic, 0, 0, False);
AddField('md5', '', nxtShortString, 32, 0, False);
AddField('categoria', '', nxtShortString, 35, 0, False);
end;
with EnsureIndicesDescriptor do begin
with AddIndex('pk', 1, idNone), KeyDescriptor as TnxCompKeyDescriptor do
Add(GetFieldFromName('id'));
with AddIndex('idx_codbar', 1, idAll), KeyDescriptor as TnxCompKeyDescriptor do
Add(GetFieldFromName('codbar'));
if GetIndexFromName('Sequential Access Index') >= 0 then
RemoveIndex(GetIndexFromName('Sequential Access Index'));
DefaultIndex := GetIndexFromName('pk');
end;
CheckValid(False);
end;
except
FreeAndNil(Result);
raise;
end;
end;
function __produSemIndices(aDatabase : TnxDatabase): TnxDataDictionary;
begin
Result := TnxDataDictionary.Create;
try
with Result do begin
AddRecordDescriptor(TnxBaseRecordDescriptor);
with FieldsDescriptor do begin
AddField('id', '', nxtAutoInc, 10, 0, False);
AddField('codbar', '', nxtShortString, 14, 0, True);
AddField('descricao', '', nxtShortString, 55, 0, False);
AddField('unid', '', nxtShortString, 5, 0, False);
AddField('imagem', '', nxtBLOBGraphic, 0, 0, False);
AddField('md5', '', nxtShortString, 32, 0, False);
AddField('categoria', '', nxtShortString, 35, 0, False);
end;
with EnsureIndicesDescriptor do begin
if GetIndexFromName('pk') >= 0 then
RemoveIndex(GetIndexFromName('pk'));
if GetIndexFromName('idx_codbar') >= 0 then
RemoveIndex(GetIndexFromName('idx_codbar'));
end;
with FilesDescriptor do
if GetFileFromExt('idx') >= 0 then
RemoveFile(GetFileFromExt('idx'));
CheckValid(False);
end;
except
FreeAndNil(Result);
raise;
end;
end;
type
TnxcgTableInfo = record
TableName : String;
Callback : TnxcgCreateDictCallback;
end;
procedure RestructureTable(aDatabase : TnxDatabase;
const aTableName, aPassword : String;
aNewDict : TnxDataDictionary;
aProgressCallback : TnxcgProgressCallback;
var aCancelTask : Boolean;
aFreeDict : Boolean = False);
var
OldDict : TnxDataDictionary;
Mapper : TnxTableMapperDescriptor;
TaskInfo : TnxAbstractTaskInfo;
Completed : Boolean;
TaskStatus : TnxTaskStatus;
begin
try
OldDict := TnxDataDictionary.Create;
try
nxCheck(aDatabase.GetDataDictionaryEx(aTableName, aPassword, OldDict));
if (aPassword <> '') and (aNewDict.EncryptionEngine = '') then
aNewDict.EncryptionEngine := OldDict.EncryptionEngine;
if OldDict.IsEqual(aNewDict) then
Exit;
Mapper := TnxTableMapperDescriptor.Create;
try
Mapper.MapAllTablesAndFieldsByName(OldDict, aNewDict);
nxCheck(aDatabase.RestructureTableEx(aTableName, aPassword, aNewDict, Mapper, TaskInfo));
if Assigned(TaskInfo) then
try
while True do begin
TaskInfo.GetStatus(Completed, TaskStatus);
if Assigned(aProgressCallback) then
aProgressCallback(aTableName, TaskStatus, aCancelTask);
if Completed then
break;
if aCancelTask then
nxCheck(TaskInfo.Cancel);
end;
finally
TaskInfo.Free;
end;
finally
Mapper.Free;
end;
finally
OldDict.Free;
end;
finally
if aFreeDict then
aNewDict.Free;
end;
end;
procedure PackTable(aDatabase : TnxDatabase;
const aTableName, aPassword : String;
aProgressCallback : TnxcgProgressCallback;
var aCancelTask : Boolean);
var
TaskInfo : TnxAbstractTaskInfo;
Completed : Boolean;
TaskStatus : TnxTaskStatus;
begin
nxCheck(aDatabase.PackTableEx(aTableName, aPassword, TaskInfo));
if Assigned(TaskInfo) then
try
while True do begin
TaskInfo.GetStatus(Completed, TaskStatus);
if Assigned(aProgressCallback) then
aProgressCallback(aTableName, TaskStatus, aCancelTask);
if Completed then
break;
if aCancelTask then
nxCheck(TaskInfo.Cancel);
end;
finally
TaskInfo.Free;
end;
end;
procedure BuildAndEvolveTable(aDatabase : TnxDatabase;
const aTableName, aPassword : String;
aCreateDictCallback : TnxcgCreateDictCallback;
aProgressCallback : TnxcgProgressCallback;
var aCancelTask : Boolean);
var
Dict : TnxDataDictionary;
begin
Dict := aCreateDictCallback(aDatabase);
if Assigned(Dict) then
try
if not aDatabase.TableExists(aTableName, aPassword) then
aDatabase.CreateTable(False, aTableName, aPassword, Dict)
else
RestructureTable(aDatabase, aTableName,
aPassword, Dict, aProgressCallback, aCancelTask);
finally
Dict.Free;
end;
end;
procedure BuildAndEvolveProduComIndices(aDatabase : TnxDatabase;
aProgressCallback : TnxcgProgressCallback;
const aPassword : String);
var
CancelTask : Boolean;
begin
CancelTask := False;
BuildAndEvolveTable(aDatabase,
'produ', aPassword,
__produComIndices, aProgressCallback, CancelTask);
if CancelTask then
Exit;
end;
procedure RestructureProduComIndices(aDatabase : TnxDatabase;
aProgressCallback : TnxcgProgressCallback;
const aPassword : String);
var
CancelTask : Boolean;
begin
CancelTask := False;
RestructureTable(aDatabase,
'produ', aPassword,
__produComIndices(aDatabase), aProgressCallback, CancelTask, True);
if CancelTask then
Exit;
end;
procedure RestructureProduSemIndices(aDatabase : TnxDatabase;
aProgressCallback : TnxcgProgressCallback;
const aPassword : String);
var
CancelTask : Boolean;
begin
CancelTask := False;
RestructureTable(aDatabase,
'produ', aPassword,
__produSemIndices(aDatabase), aProgressCallback, CancelTask, True);
if CancelTask then
Exit;
end;
procedure PackProdu(aDatabase : TnxDatabase;
aProgressCallback : TnxcgProgressCallback;
const aPassword : String);
var
CancelTask : Boolean;
begin
CancelTask := False;
PackTable(aDatabase, 'produ',
aPassword, aProgressCallback, CancelTask);
if CancelTask then
Exit;
end;
end.
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2019 The Bitcoin Core developers
// Copyright (c) 2020-2020 Skybuck Flying
// Copyright (c) 2020-2020 The Delphicoin Developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
// Bitcoin file: src/primitives/transaction.h
// Bitcoin file: src/primitives/transaction.cpp
// Bitcoin commit hash: f656165e9c0d09e654efabd56e6581638e35c26c
unit Unit_UnserializeTransaction;
interface
implementation
// /**
// * A flag that is ORed into the protocol version to designate that a transaction
// * should be (un)serialized without witness data.
// * Make sure that this does not collide with any of the values in `version.h`
// * or with `ADDRV2_FORMAT`.
// */
static const int SERIALIZE_TRANSACTION_NO_WITNESS = 0x40000000;
struct CMutableTransaction;
/**
* Basic transaction serialization format:
* - int32_t nVersion
* - std::vector<CTxIn> vin
* - std::vector<CTxOut> vout
* - uint32_t nLockTime
*
* Extended transaction serialization format:
* - int32_t nVersion
* - unsigned char dummy = 0x00
* - unsigned char flags (!= 0)
* - std::vector<CTxIn> vin
* - std::vector<CTxOut> vout
* - if (flags & 1):
* - CTxWitness wit;
* - uint32_t nLockTime
*/
template<typename Stream, typename TxType>
inline void UnserializeTransaction(TxType& tx, Stream& s) {
const bool fAllowWitness = !(s.GetVersion() & SERIALIZE_TRANSACTION_NO_WITNESS);
s >> tx.nVersion;
unsigned char flags = 0;
tx.vin.clear();
tx.vout.clear();
/* Try to read the vin. In case the dummy is there, this will be read as an empty vector. */
s >> tx.vin;
if (tx.vin.size() == 0 && fAllowWitness) {
/* We read a dummy or an empty vin. */
s >> flags;
if (flags != 0) {
s >> tx.vin;
s >> tx.vout;
}
} else {
/* We read a non-empty vin. Assume a normal vout follows. */
s >> tx.vout;
}
if ((flags & 1) && fAllowWitness) {
/* The witness flag is present, and we support witnesses. */
flags ^= 1;
for (size_t i = 0; i < tx.vin.size(); i++) {
s >> tx.vin[i].scriptWitness.stack;
}
if (!tx.HasWitness()) {
/* It's illegal to encode witnesses when all witness stacks are empty. */
throw std::ios_base::failure("Superfluous witness record");
}
}
if (flags) {
/* Unknown flag in the serialization */
throw std::ios_base::failure("Unknown transaction optional data");
}
s >> tx.nLockTime;
}
end.
|
unit FrameRegisterUser;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, StdCtrls, ExtCtrls, ExtDlgs, DataBases, Dialogs;
const
FRAME_LOGIN = 1;
type
{ TFrameRegisterUser }
TFrameRegisterUser = class(TFrame)
Bevel: TBevel;
ButtonRegister: TButton;
ButtonAvatar: TButton;
ButtonCancel: TButton;
CheckBox: TCheckBox;
EditName: TLabeledEdit;
EditMail: TLabeledEdit;
EditPassword: TLabeledEdit;
EditPasswordEmail: TLabeledEdit;
EditHostIncoming: TLabeledEdit;
EditHostOutgoing: TLabeledEdit;
EditPortImap: TLabeledEdit;
EditPortSmtp: TLabeledEdit;
Image: TImage;
LabelAvatar: TLabel;
OpenPictureDialog: TOpenPictureDialog;
Panel: TPanel;
procedure ButtonAvatarClick(Sender: TObject);
procedure ButtonCancelClick(Sender: TObject);
procedure ButtonRegisterClick(Sender: TObject);
procedure CheckBoxChange(Sender: TObject);
procedure FrameResize(Sender: TObject);
private
{ private declarations }
ToBackPage: integer; // Индекс предыдущей страницы
public
procedure FirstRegistration;
procedure NotFirstRegistration(BackPage: integer = 0);
end;
implementation
{$R *.lfm}
uses Main;
{ TFrameRegisterUser }
procedure TFrameRegisterUser.FrameResize(Sender: TObject);
begin
Panel.Left := TFrame(Sender).Width div 2 - Panel.Width div 2;
Panel.Top := TFrame(Sender).Height div 2 - Panel.Height div 2 - 30;
end;
procedure TFrameRegisterUser.FirstRegistration;
// При первой реге убираем кнопку "отмена"
begin
ButtonCancel.Visible := False;
ButtonRegister.Left := TFrame(self).Width - ButtonRegister.Width - ButtonAvatar.Left;
end;
procedure TFrameRegisterUser.NotFirstRegistration(BackPage: integer);
// При последующих регах ставим кнопку "отмена"
begin
ButtonCancel.Visible := True;
ButtonCancel.Left := TFrame(self).Width - ButtonCancel.Width - ButtonAvatar.Left;
ButtonRegister.Left := ButtonCancel.Left - ButtonRegister.Width - 4;
ToBackPage := BackPage;
end;
procedure TFrameRegisterUser.ButtonAvatarClick(Sender: TObject);
// Выбор аватарки
begin
if OpenPictureDialog.Execute then
Image.Picture.LoadFromFile(OpenPictureDialog.FileName);
end;
procedure TFrameRegisterUser.ButtonCancelClick(Sender: TObject);
// Возврат на предыдущую страницу
begin
case ToBackPage of
FRAME_LOGIN: MainForm.ShowLoginFrame;
end;
end;
procedure TFrameRegisterUser.ButtonRegisterClick(Sender: TObject);
// Регистрация нового пользователя
begin
// Проверка полей
if not DataBase.AddUser(EditName.Text, EditPassword.Text, EditMail.Text, OpenPictureDialog.FileName) then
MessageDlg('Ошибка', 'Ошибка 1: Возникли проблемы с созданием нового пользователя...', TMSgDlgType.mtError, [mbOK], 0)
else
// Пользователь создан требуется войти в систему
if DataBase.Login(EditMail.Text, EditPassword.Text) then
begin
DataBase.AddTransport(DataBase.CurrentUserID, CONNECTIONTYPE_EMAIL, StrToInt(EditPortImap.Text), StrToInt(EditPortSmtp.Text),
EditHostIncoming.Text, EditHostOutgoing.Text, EditMail.Text, EditPasswordEmail.Text);
MainForm.ShowFrameDialogs;
end
else
raise Exception.Create('Системная ошибка при создании нового пользователя...');
end;
procedure TFrameRegisterUser.CheckBoxChange(Sender: TObject);
// Показать скрыть пароль
begin
if CheckBox.Checked then
begin
EditPassword.EchoMode := emPassword;
EditPasswordEmail.EchoMode := emPassword;
end
else
begin
EditPassword.EchoMode := emNormal;
EditPasswordEmail.EchoMode := emNormal;
end;
end;
end.
|
{
Oracle Deploy System ver.1.0 (ORDESY)
by Volodymyr Sedler aka scribe
2016
Desc: wrap/deploy/save objects of oracle database.
No warranty of using this program.
Just Free.
With bugs, suggestions please write to justscribe@yahoo.com
On Github: github.com/justscribe/ORDESY
Dialog to show the list of all schemes with ability to create/edit/delete.
}
unit uSchemeList;
interface
uses
// ORDESY Modules
{$IFDEF Debug}
uLog,
{$ENDIF}
uORDESY,
// Delphi Modules
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;
type
TfmSchemeList = class(TForm)
pnlControl: TPanel;
lbxList: TListBox;
btnAdd: TButton;
btnDelete: TButton;
btnEdit: TButton;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure UpdateList(aProjectList: TORDESYProjectList);
procedure btnDeleteClick(Sender: TObject);
procedure btnAddClick(Sender: TObject);
procedure btnEditClick(Sender: TObject);
private
ProjectList: TORDESYProjectList;
end;
function ShowSchemeListDialog(aProjectList: TORDESYProjectList): boolean;
implementation
{$R *.dfm}
uses
uMain;
function ShowSchemeListDialog(aProjectList: TORDESYProjectList): boolean;
begin
with TfmSchemeList.Create(Application) do
try
Result:= false;
ProjectList:= aProjectList;
UpdateList(ProjectList);
ShowModal;
Result:= true;
finally
Free;
end;
end;
procedure TfmSchemeList.btnAddClick(Sender: TObject);
begin
fmMain.AddScheme(Self);
UpdateList(ProjectList);
end;
procedure TfmSchemeList.btnDeleteClick(Sender: TObject);
var
reply: word;
iScheme: TOraScheme;
begin
if (lbxList.Count > 0) and (lbxList.ItemIndex >= 0) and (lbxList.Items.Objects[lbxList.ItemIndex] is TOraScheme) then
begin
iScheme:= TOraScheme(lbxList.Items.Objects[lbxList.ItemIndex]);
reply:= MessageBox(Handle, PChar('Delete scheme: ' + iScheme.Login + '?' + #13#10), PChar('Confirm'), 36);
if reply = IDYES then
begin
if ProjectList.RemoveSchemeById(iScheme.Id) then
UpdateList(ProjectList)
else
ShowMessage('Can''t delete.');
end;
end;
end;
procedure TfmSchemeList.btnEditClick(Sender: TObject);
begin
if (lbxList.Count > 0) and (lbxList.ItemIndex >= 0) and (lbxList.Items.Objects[lbxList.ItemIndex] is TOraScheme) then
begin
fmMain.EditScheme(TOraScheme(lbxList.Items.Objects[lbxList.ItemIndex]));
UpdateList(ProjectList);
end;
end;
procedure TfmSchemeList.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action:= caFree;
end;
procedure TfmSchemeList.UpdateList(aProjectList: TORDESYProjectList);
var
i: integer;
iScheme: TOraScheme;
begin
lbxList.Clear;
for i := 0 to aProjectList.OraSchemeCount - 1 do
begin
iScheme:= aProjectList.GetOraSchemeByIndex(i);
lbxList.AddItem(inttostr(iScheme.Id) + ':|' + iScheme.Login, iScheme);
end;
end;
end.
|
unit uClassMessageDTO;
interface
uses
REST.Json.Types;
{$M+}
type
TChatDTO = class
private
FFirst_Name: string;
FId: Integer;
FLast_Name: string;
FType: string;
FUsername: string;
published
property First_Name: string read FFirst_Name write FFirst_Name;
property Id: Integer read FId write FId;
property Last_Name: string read FLast_Name write FLast_Name;
property &Type: string read FType write FType;
property Username: string read FUsername write FUsername;
end;
TFromDTO = class
private
FFirst_Name: string;
FId: Integer;
FIs_Bot: Boolean;
FLanguage_Code: string;
FLast_Name: string;
FUsername: string;
published
property First_Name: string read FFirst_Name write FFirst_Name;
property Id: Integer read FId write FId;
property Is_Bot: Boolean read FIs_Bot write FIs_Bot;
property Language_Code: string read FLanguage_Code write FLanguage_Code;
property Last_Name: string read FLast_Name write FLast_Name;
property Username: string read FUsername write FUsername;
end;
TMessageDTO = class
private
FChat: TChatDTO;
FDate: Integer;
FFrom: TFromDTO;
FMessage_Id: Integer;
FText: string;
published
property Chat: TChatDTO read FChat write FChat;
property Date: Integer read FDate write FDate;
property From: TFromDTO read FFrom write FFrom;
property Message_Id: Integer read FMessage_Id write FMessage_Id;
property Text: string read FText write FText;
public
constructor Create;
destructor Destroy; override;
end;
TChatMessageDTO = class
private
[JSONNameAttribute('message')]
FMessage: TMessageDTO;
FUpdate_Id: Integer;
published
property Message: TMessageDTO read FMessage write FMessage;
property Update_Id: Integer read FUpdate_Id write FUpdate_Id;
public
constructor Create;
destructor Destroy; override;
end;
implementation
{ TMessageDTO }
constructor TMessageDTO.Create;
begin
inherited;
FFrom := TFromDTO.Create;
FChat := TChatDTO.Create;
end;
destructor TMessageDTO.Destroy;
begin
FFrom.Free;
FChat.Free;
inherited;
end;
{ TChatMessageDTO }
constructor TChatMessageDTO.Create;
begin
FMessage := TMessageDTO.Create;
end;
destructor TChatMessageDTO.Destroy;
begin
FMessage.Free;
inherited;
end;
end.
|
unit vr_fpclasses;
{$mode delphi}{$H+}
{$I vrode.inc}
interface
uses
Classes, SysUtils, RtlConsts, vr_SysUtils, Types;
type
{ TvrThreadListHelper }
TvrThreadListHelper = class helper for TThreadList
public
procedure Insert(const AIndex: Integer; AItem: Pointer);
function IndexOf(const AItem: Pointer): Integer;
function IsEmpty: Boolean;
function GetItem(const AIndex: Integer; out AItem: Pointer): Boolean;
function Items: TPointerDynArray;
class function LockedGet(const AThreadList: TThreadList; out AList: TList): Boolean;
class function LockedCreateIfNil(var AList: TThreadList; ANewItem: Pointer): Boolean;
class function LockedFreeAndNilIfEmpty(var AList: TThreadList; ARemoveIndex: Integer = -1): Boolean; overload;
class function LockedFreeAndNilIfEmpty(var AList: TThreadList; ARemoveItem: Pointer = nil): Boolean; overload;
end;
procedure InitThreads;
{$IFNDEF VER3}
type
{ TvrThreadHelper }
TvrThreadHelper = class helper for TThread
private
class function GetCurrentThread: TThread; static;
public
class property CurrentThread: TThread read GetCurrentThread;
end;
{$ENDIF}
implementation
{$IFNDEF VER3}
var
ExternalThreads: TThreadList;
threadvar
CurrentThreadVar: TThread;
type
{ this type is used by TThread.GetCurrentThread if the thread does not yet
have a value in CurrentThreadVar (Note: the main thread is also created as
a TExternalThread) }
{ TExternalThread }
TExternalThread = class(TThread)
protected
{ dummy method to remove the warning }
procedure Execute; override;
public
constructor Create;
destructor Destroy; override;
procedure AfterConstruction; override;
end;
procedure TExternalThread.Execute;
begin
{ empty }
end;
constructor TExternalThread.Create;
begin
FThreadID := GetCurrentThreadID;
ExternalThreads.Add(Self);
//FExternalThread := True;
{ the parameter is unimportant if FExternalThread is True }
//inherited Create(False);
//with ExternalThreads.LockList do
// try
// Add(Self);
// finally
// ExternalThreads.UnlockList;
// end;
end;
destructor TExternalThread.Destroy;
begin
ExternalThreads.Remove(Self);
//inherited;
//if not ExternalThreadsCleanup then
// with ExternalThreads.LockList do
// try
// Extract(Self);
// finally
// ExternalThreads.UnlockList;
// end;
end;
procedure TExternalThread.AfterConstruction;
begin
//inherited AfterConstruction;
end;
{ TvrThreadHelper }
class function TvrThreadHelper.GetCurrentThread: TThread; static;
begin
Result := CurrentThreadVar;
if not Assigned(Result) then begin
Result := TExternalThread.Create;
CurrentThreadVar := Result;
end;
end;
{$ENDIF NOT VER3}
{ TvrThreadListHelper }
function TvrThreadListHelper.GetItem(const AIndex: Integer; out AItem: Pointer): Boolean;
var
lst: TList;
begin
lst := LockList;
try
Result := (AIndex >= 0) and (AIndex < lst.Count);
if Result then
AItem := lst[AIndex]
else
AItem := nil;
finally
UnlockList;
end;
end;
function TvrThreadListHelper.Items: TPointerDynArray;
var
lst: TList;
i: Integer;
begin
lst := LockList;
try
SetLength(Result, lst.Count);
for i := 0 to lst.Count - 1 do
Result[i] := lst[i];
finally
UnlockList;
end;
end;
class function TvrThreadListHelper.LockedGet(const AThreadList: TThreadList; out
AList: TList): Boolean;
begin
LockVar;
try
Result := AThreadList <> nil;
if Result then
AList := AThreadList.LockList
else
AList := nil;
finally
UnLockVar;
end;
end;
class function TvrThreadListHelper.LockedCreateIfNil(var AList: TThreadList;
ANewItem: Pointer): Boolean;
begin
LockVar;
try
Result := AList = nil;
if Result then
AList := TThreadList.Create;
if ANewItem <> nil then
AList.Add(ANewItem);
finally
UnLockVar;
end;
end;
class function TvrThreadListHelper.LockedFreeAndNilIfEmpty(
var AList: TThreadList; ARemoveIndex: Integer): Boolean;
var
lst: TList;
begin
lst := AList.LockList;
try
if (ARemoveIndex >= 0) and (ARemoveIndex < lst.Count) then
lst.Delete(ARemoveIndex);
finally
AList.UnlockList;
end;
Result := LockedFreeAndNilIfEmpty(AList, nil);
end;
class function TvrThreadListHelper.LockedFreeAndNilIfEmpty(var AList: TThreadList;
ARemoveItem: Pointer): Boolean;
var
lst: TThreadList = nil;
l: TList = nil;
begin
LockVar;
try
if AList = nil then
Exit(True);
l := AList.LockList;
if ARemoveItem <> nil then
l.Remove(ARemoveItem);
Result := l.Count = 0;
if Result then
begin
lst := AList;
AList := nil;
lst.UnlockList;
end
else
AList.UnlockList;
finally
UnLockVar;
end;
if lst <> nil then
lst.Free;
end;
procedure TvrThreadListHelper.Insert(const AIndex: Integer; AItem: Pointer);
var
lst: TList;
begin
lst := LockList;
try
if (Duplicates=dupAccept) or
// make sure it's not already in the list
(lst.IndexOf(AItem)=-1) then
lst.Insert(AIndex, AItem)
else if (Duplicates=dupError) then
lst.Error(SDuplicateItem,{%H-}PtrUInt(AItem));
finally
UnlockList;
end;
end;
function TvrThreadListHelper.IndexOf(const AItem: Pointer): Integer;
var
lst: TList;
begin
lst := LockList;
try
Result := lst.IndexOf(AItem);
finally
UnlockList;
end;
end;
function TvrThreadListHelper.IsEmpty: Boolean;
var
lst: TList;
begin
lst := LockList;
try
Result := lst.Count = 0;
finally
UnlockList;
end;
end;
type
TThreadManagerPatch = record
OldBeginThread: TBeginThreadHandler;
OldEndThread: TEndThreadHandler;
OldThreadFunc: TThreadFunc;
Count: Integer;
end;
var
ThreadManagerPatch: TThreadManagerPatch;
{$IFNDEF VER3}
function _NewThreadFunc(parameter : pointer) : ptrint;
begin
CurrentThreadVar := TThread(parameter);
Result := ThreadManagerPatch.OldThreadFunc(parameter);
end;
{$ENDIF}
function _NewBeginTread(sa : Pointer;stacksize : PtrUInt; ThreadFunction : TThreadFunc;
p : pointer;creationFlags : dword; var ThreadId : TThreadID) : TThreadID;
begin
{$IFDEF VER3}
Result := ThreadManagerPatch.OldBeginThread(sa, stacksize, ThreadFunction,
p, creationFlags, ThreadId);
{$ELSE}
if not Assigned(ThreadManagerPatch.OldThreadFunc) then
ThreadManagerPatch.OldThreadFunc := ThreadFunction;
Result := ThreadManagerPatch.OldBeginThread(sa, stacksize, _NewThreadFunc,
p, creationFlags, ThreadId);
{$ENDIF}
Inc(ThreadManagerPatch.Count);
end;
procedure _NewEndThread(ExitCode : DWord);
begin
Dec(ThreadManagerPatch.Count);
ThreadManagerPatch.OldEndThread(ExitCode);
end;
procedure _InitTM;
var
tm: TThreadManager;
begin
{$IFNDEF VER3}
ExternalThreads := TThreadList.Create;{$ENDIF}
if not GetThreadManager(tm{%H-}) or
(@tm.BeginThread = nil) then Exit;
ThreadManagerPatch.OldBeginThread := tm.BeginThread;
ThreadManagerPatch.OldEndThread := tm.EndThread;
ThreadManagerPatch.OldThreadFunc := nil;
tm.BeginThread := _NewBeginTread;
tm.EndThread := _NewEndThread;
SetThreadManager(tm);
end;
{$IFNDEF VER3}
procedure _Fin;
var
lst: TList;
i: Integer;
begin
lst := ExternalThreads.LockList;
try
for i := lst.Count - 1 downto 0 do
TThread(lst[i]).Free;
finally
ExternalThreads.UnlockList;
end;
FreeAndNil(ExternalThreads);
end;
{$ENDIF}
procedure _WaitThreadsTerminated(AMSec: Integer);
begin
while AMSec > 0 do
begin
if ThreadManagerPatch.Count <= 0 then
begin
Exit;
end;
CheckSynchronize();
Sleep(10);
Dec(AMSec, 10);
end;
end;
procedure InitThreads;
begin
_InitTM;
end;
//{$IFNDEF MOBILE_DEVICE}
initialization
_InitTM;//{$ENDIF}
finalization
{$IFNDEF VER3}
_Fin;{$ENDIF}
_WaitThreadsTerminated(10000);
end.
|
unit eSocial.Models.Components.Connections.DBExpress;
interface
uses
System.SysUtils,
System.Classes,
Data.DB,
SimpleDS,
Data.DBXFirebird,
Data.SqlExpr,
Data.FMTBcd,
Datasnap.Provider,
Datasnap.DBClient,
eSocial.Models.Components.Connections.Interfaces;
type
TModelComponentConnectionDBExpress = class(TInterfacedObject, iModelComponentConnection)
private
FConnection : TSQLConnection;
FQuery : TSQLQuery;
FProvider : TDataSetProvider;
FClient : TClientDataSet;
function ExistParam(aParamName : String) : Boolean;
protected
constructor Create(aDataBase : String);
public
destructor Destroy; override;
class function New(aDataBase : String) : iModelComponentConnection;
function Active(aValue : Boolean) : iModelComponentConnection;
function AddParam (aParam : String; aValue : Smallint) : iModelComponentConnection; overload;
function AddParam (aParam : String; aValue : Integer) : iModelComponentConnection; overload;
function AddParam (aParam : String; aValue : String) : iModelComponentConnection; overload;
function AddParam (aParam : String; aValue : TDateTime) : iModelComponentConnection; overload;
function DataSet : TDataSet;
function ExecSQL : iModelComponentConnection;
function FetchParams : iModelComponentConnection;
function Open : iModelComponentConnection;
function SQL(aValue : String) : iModelComponentConnection;
function SQLClear : iModelComponentConnection;
end;
implementation
{ TModelComponentConnectionDBExpress }
constructor TModelComponentConnectionDBExpress.Create(aDataBase : String);
begin
try
FConnection := TSQLConnection.Create(nil);
FConnection.ConnectionName := 'FBConnection';
FConnection.DriverName := 'Firebird';
FConnection.LoginPrompt := False;
with FConnection do
begin
Params.Clear;
Params.Values['DriverName'] := 'Firebird';
Params.Values['RoleName'] := 'RoleName';
Params.Values['User_Name'] := 'GERASYS.TI';
Params.Values['Password'] := 'gsti2010';
Params.Values['ServerCharSet'] := 'WIN1252';
Params.Values['SQLDialect'] := '3';
Params.Values['ErrorResourceFile']:= '';
Params.Values['LocaleCode'] := '0000';
Params.Values['BlobSize'] := '-1';
Params.Values['CommitRetain'] := 'False';
Params.Values['WaitOnLocks'] := 'True';
Params.Values['IsolationLevel'] := 'ReadCommitted';
Params.Values['Trim Char'] := 'False';
Params.Values['DataBase'] := aDataBase;
end;
FQuery := TSQLQuery.Create(nil);
FQuery.SQLConnection := FConnection;
FQuery.SQL.Clear;
FProvider := TDataSetProvider.Create(nil);
FProvider.Options := [poAllowCommandText, poUseQuoteChar];
FProvider.UpdateMode := TUpdateMode.upWhereKeyOnly;
FProvider.Exported := False;
FProvider.DataSet := FQuery;
FClient := TClientDataSet.Create(nil);
FClient.SetProvider( FProvider );
FClient.StoreDefs := True;
FConnection.Connected := True; // Testa os parâmetros de conexão
FConnection.Connected := False;
except
On E : Exception do
raise Exception.Create('Erro na conexão!' + #13 + E.Message);
end;
end;
destructor TModelComponentConnectionDBExpress.Destroy;
begin
FClient.DisposeOf;
FProvider.DisposeOf;
FQuery.DisposeOf;
FConnection.DisposeOf;
inherited;
end;
class function TModelComponentConnectionDBExpress.New(aDataBase : String): iModelComponentConnection;
begin
Result := Self.Create(aDataBase);
end;
function TModelComponentConnectionDBExpress.Active(aValue: Boolean): iModelComponentConnection;
begin
Result := Self;
FClient.Active := aValue;
end;
function TModelComponentConnectionDBExpress.AddParam(aParam: String; aValue: Integer): iModelComponentConnection;
begin
Result := Self;
if ExistParam(aParam) then
FClient.ParamByName(aParam).AsInteger := aValue;
end;
function TModelComponentConnectionDBExpress.AddParam(aParam, aValue: String): iModelComponentConnection;
begin
Result := Self;
if ExistParam(aParam) then
FClient.ParamByName(aParam).AsString := aValue;
end;
function TModelComponentConnectionDBExpress.DataSet: TDataSet;
begin
Result := FClient;
end;
function TModelComponentConnectionDBExpress.ExecSQL: iModelComponentConnection;
begin
Result := Self;
try
if FClient.Active then
FClient.Close;
if FQuery.Active then
FQuery.Close;
FQuery.ExecSQL;
except
On E : Exception do
raise Exception.Create('Erro na execução do Script SQL.' + #13 + E.Message);
end;
end;
function TModelComponentConnectionDBExpress.ExistParam(aParamName: String): Boolean;
begin
Result := Assigned(FClient.Params.FindParam(aParamName));
end;
function TModelComponentConnectionDBExpress.FetchParams: iModelComponentConnection;
begin
Result := Self;
FClient.SetProvider( FProvider );
FClient.FetchParams;
end;
function TModelComponentConnectionDBExpress.Open: iModelComponentConnection;
begin
Result := Self;
FClient.SetProvider( FProvider );
FClient.Open;
end;
function TModelComponentConnectionDBExpress.SQL(aValue: String): iModelComponentConnection;
begin
Result := Self;
if FClient.Active then
FClient.Close;
if FQuery.Active then
FQuery.Close;
FQuery.SQL.Add(aValue);
end;
function TModelComponentConnectionDBExpress.SQLClear: iModelComponentConnection;
begin
Result := Self;
if FClient.Active then
FClient.Close;
if FQuery.Active then
FQuery.Close;
FClient.Params.Clear;
FQuery.SQL.Clear;
end;
function TModelComponentConnectionDBExpress.AddParam(aParam: String; aValue: TDateTime): iModelComponentConnection;
begin
Result := Self;
if ExistParam(aParam) then
FClient.ParamByName(aParam).AsDateTime := aValue;
end;
function TModelComponentConnectionDBExpress.AddParam(aParam: String; aValue: Smallint): iModelComponentConnection;
begin
Result := Self;
if ExistParam(aParam) then
FClient.ParamByName(aParam).AsSmallInt := aValue;
end;
end.
|
unit Main;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
FMXTee.Engine, FMXTee.Procs, FMXTee.Chart, FMX.TabControl, FMX.Edit,
{$IFDEF ANDROID}
AndroidApi.Helpers, FMX.Platform.Android, Androidapi.JNI.Widget, FMX.Helpers.Android,
{$ENDIF}
FMX.Objects, FMX.Controls.Presentation, FMXTee.Series, FMX.ListBox, Math,
FMX.ComboEdit, System.Notification;
type
TMainForm = class(TForm)
ToolBar1: TToolBar;
Label1: TLabel;
Image1: TImage;
Label2: TLabel;
Edit1: TEdit;
Label3: TLabel;
Edit2: TEdit;
Label4: TLabel;
TabControl1: TTabControl;
TabItem1: TTabItem;
TabItem2: TTabItem;
Chart1: TChart;
TrackBar1: TTrackBar;
Label5: TLabel;
Series1: TLineSeries;
Button3: TButton;
Button1: TButton;
Button4: TButton;
ProgressBar1: TProgressBar;
NotificationCenter1: TNotificationCenter;
ComboEdit1: TComboEdit;
procedure TrackBar1Change(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure Button3Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
type MyOpt=array[1..3] of Double;
var
MainForm: TMainForm;
step:real;
xn,xk,y:real;
Options:MyOpt;
implementation
{$R *.fmx}
// Наша функция
function myf(x:real):real;
begin
if (x<=0) then myf:=2
else if (x>0) and (x<20) then myf:=10*exp(-0.08*x)*sin(x)
else myf:=5;
end;
procedure TMainForm.Button1Click(Sender: TObject);
var f:textfile; i:integer;
begin
// Загрузка изображения из карты памяти
{$IFDEF ANDROID}
Image1.Bitmap.LoadFromFile('/mnt/sdcard/'+ComboEdit1.Text);
{$ENDIF}
{$IFDEF MSWINDOWS}
Image1.Bitmap.LoadFromFile('C:\'+ComboEdit1.Text);
{$ENDIF}
// Сохранение настроек начальных значений в текстовый файл
Options[1]:=xn;
Options[2]:=xk;
Options[3]:=step;
{$IFDEF ANDROID}
assignfile(f,'/mnt/sdcard/myopt_lab4.txt');
{$ENDIF}
{$IFDEF MSWINDOWS}
assignfile(f,'c:\myopt_lab4.txt');
{$ENDIF}
rewrite(f);
for i := 1 to 3 do
begin
writeln(f,Options[i]);
end;
closefile(f);
{$IFDEF ANDROID}
TJToast.JavaClass.makeText(TAndroidHelper.Context, StrToJCharSequence('Настройки сохранены в файл!'), TJToast.JavaClass.LENGTH_LONG).show;
{$ENDIF}
{$IFDEF MSWINDOWS}
ShowMessage('Настройки сохранены в файл!');
{$ENDIF}
end;
// Поиск файлов изображений на карте памяти
procedure TMainForm.Button3Click(Sender: TObject);
var f:tsearchrec;
begin
{$IFDEF ANDROID}
if findfirst('/mnt/sdcard/*.jpg',faanyfile,f)<>0 then exit;
{$ENDIF}
{$IFDEF MSWINDOWS}
if findfirst('C:\*.jpg',faanyfile,f)<>0 then exit;
{$ENDIF}
ComboEdit1.Items.Add(f.name);
while findnext(f)=0 do
begin
ComboEdit1.Items.Add(f.Name);
end;
findclose(f);
end;
procedure TMainForm.Button4Click(Sender: TObject);
var Notification:TNotification; x:real;
begin
Chart1.Series[0].Clear;
// Ввод данных //
try
xn:=StrToFloat(Edit1.Text);
except on EConvertError do
begin
ShowMessage('Неверное начальное значение!');
Exit;
end;
end;
try
xk:=StrToFloat(Edit2.Text);
except on EConvertError do
begin
ShowMessage('Неверное конечное значение!');
Exit;
end;
end;
//************************************************//
x:=xn;
ProgressBar1.Min:=xn;
Progressbar1.Max:=xk;
while(xk>x) do
begin
Application.ProcessMessages;
y:=myf(x);
x:=x+step;
Chart1.Series[0].AddXY(x,y);
ProgressBar1.Value:=x;
end;
// Вывод уведомления
if NotificationCenter1.Supported then
begin
Notification:=NotificationCenter1.CreateNotification;
try
Notification.Name:='Lab4';
Notification.AlertBody:='График построен!';
Notification.FireDate:=Now+EncodeTime(0,0,5,0);
NotificationCenter1.ScheduleNotification(Notification);
finally
Notification.DisposeOf;
end;
end;
end;
procedure TMainForm.FormShow(Sender: TObject);
var f:textfile; i:integer;
begin
{$IFDEF ANDROID}
if FileExists('/mnt/sdcard/myopt_lab4.txt') then
{$ENDIF}
{$IFDEF MSWINDOWS}
if FileExists('C:\myopt_lab4.txt') then
{$ENDIF}
begin
{$IFDEF ANDROID}
assignfile(f,'/mnt/sdcard/myopt_lab4.txt');
{$ENDIF}
{$IFDEF MSWINDOWS}
assignfile(f,'C:\myopt_lab4.txt');
{$ENDIF}
reset(f);
for i := 1 to 3 do
begin
readln(f,Options[i]);
end;
Edit1.Text:=Options[1].ToString();
Edit2.Text:=Options[2].ToString();
TrackBar1.Value:=Options[3];
closefile(f);
end;
end;
procedure TMainForm.TrackBar1Change(Sender: TObject);
begin
Label5.Text:='Значение шага '+FloatToStr(Trackbar1.Value);
step:=Trackbar1.Value;
end;
end.
|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Data.DBXCommonResStrs;
interface
resourcestring
SBadVariantType = 'Unsupported variant type: %s';
SAlreadyRegistered = '%s class already registered';
SNotRegistered = '%s class is not registered';
SInvalidClassRegister = '%s class registered with a nil class reference';
SInvalidClassName = '%s class cannot be found in %s';
SCannotFreeClassRegistry = 'Cannot free TClassRegistry.ClassRegistry';
SDllLoadError = 'Unable to load %s (ErrorCode %d). It may be missing from the system path.';
SDllProcLoadError = 'Unable to find procedure %s';
SUnknownDriver = 'Unknown driver: %s';
SInvalidArgument = 'Invalid argument: %s';
SInvalidTransaction = 'Invalid transaction Object';
SNotImplemented = 'Feature not implemented';
SRequiredProperty = '%s property not set';
SDriverLoadError = '%s driver cannot be loaded. Make sure your project either uses the %s unit or uses packages so the %s package can be loaded dynamically';
SReaderNew = 'Reader Next method has not been called';
SReaderClosed = 'Reader has no more rows';
SReadOnlyType = '%s type cannot be modified';
SReadOnlyParameter = '%s parameter cannot be modified';
SSetSingletonOnce = 'Cannot set this singleton instance more than once or after it has been retrieved one or more times';
SConnectionFactoryInitFailed = 'Cannot find connection files from application directory (%s) or the system registry (%s).';
SInvalidDelegationDepth = 'Cannot delegate a connection more than 16 times: %s';
SInvalidOrdinal = 'Invalid Ordinal: %d';
SDefaultErrorMessage = 'DBX Error: %s';
SErrorCode = 'Error Code: ';
SAlreadyPrepared = 'Command can only be prepared once';
SInvalidTypeAccess = '%s value type cannot be accessed as %s value type';
SDriverAlreadyLoaded = 'A driver instance with the %s name has already been loaded.';
SConnectionClosed = 'Operation failed. Connection was closed';
SMetaDataLoadError = 'Could not find metadata: %s; package: %s. Add %s to your uses.';
SJSONByteStream = 'JSON byte stream cannot be parsed correctly into a JSON value';
SNoStatementToExecute = 'No statement to execute';
SAdditionalInfo = '%s. Vendor error message: %s.';
SInvalidDataType = 'dbExpress driver does not support the %s data type';
SUnmatchedBrace = 'Unmatched brace found in format string: %s';
SParameterIndexOutOfRange = 'Unmatched brace found in format string: %d';
SConnectTimeout = 'Connect request timed out after %s milliseconds';
SInvalidCommand = 'Unrecognized command: %s';
SINVALID_TRACE_FLAG =
'%s is an invalid setting for the %s property.'#13#10
+'Use ''%s'' or a semicolon separated list of one or more of the following:'#13#10
+'%s %s %s %s %s %s %s %s %s %s %s %s';
SFieldValueMissing = 'Internal: Field %s has no serialized value';
SFieldExpected = 'Internal: Field %s conversion is incomplete';
SArrayExpected = 'Internal: Array expected instead of %s';
SNoArray = 'Internal: Array expected instead of nil';
STypeExpected = 'Internal: Type expected';
STypeFieldsPairExpected = 'Internal: Type fields pair expected';
SValueExpected = 'Internal: JSON value expected instead of %s';
SInvalidContext = 'Internal: Current context cannot accept a value';
SObjectExpectedForPair = 'Internal: Object context expected when processing a pair';
SInvalidContextForPair = 'Internal: Current context cannot accept a pair';
STypeNotSupported = 'Internal: Type %s is not currently supported';
SNoTypeInterceptorExpected = 'Field attribute should provide a field interceptor instead of a type one on field %s';
SInconsistentConversion = 'Internal: Conversion failed, converted object is most likely incomplete';
SNoConversionForType = 'Internal: No conversion possible for type: %s';
SNoFieldFoundForType = 'Internal: Field %s cannot be found in type %s';
SNoValueConversionForField = 'Internal: Value %s cannot be converted to be assigned to field %s in type %s';
SNoConversionAvailableForValue = 'Value %s cannot be converted into %s. You may use a user-defined reverter';
SInvalidTypeForField = 'Cannot set value for field %s as it is expected to be an array instead of %s';
SCannotCreateType = 'Internal: Cannot instantiate type %s';
SCannotCreateObject = 'The input value is not a valid Object';
SObjectNotFound = 'Internal: Object type %s not found for id: %s';
SUnexpectedPairName = 'Internal: Invalid pair name %s: expected %s or %s';
SInvalidJSONFieldType = 'Un-marshaled array cannot be set as a field value. A reverter may be missing for field %s of %s';
SObjectExpectedInArray = 'Object expected at position %d in JSON array %s';
SStringExpectedInArray = 'String expected at position %d in JSON array %s';
SArrayExpectedForField = 'JSON array expected for field %s in JSON %s';
SObjectExpectedForField = 'JSON object expected for field %s in JSON %s';
SStringExpectedForField = 'JSON string expected for field %s in JSON %s';
SNoProductNameFound = 'No Product name found for Data Provider. No metadata can be provided.';
SNoDialectForProduct = 'No metadata could be loaded for: %s.';
SDialectTypeNotFound = 'Could not locate the type: %s.';
SBeforeRow = 'Invoke Next before getting data from a reader.';
SAfterRow = 'No more data in reader.';
SUnknownDataType = 'Unknown Data Type';
SNoMetadataProvider = 'Cannot load metadata for %s.';
SUnexpectedMetaDataType = 'Unexpected metadata type';
SInsertNotCalled = 'Must call Insert before Post.';
SPostNotCalled = 'Must call Post before moving away from a new row.';
SMustKeepOriginalColumnOrder = 'Additional columns must be added after the prescribed columns.';
SObjectNotSupported = 'Objecta are not supported with this metadata store.';
SUnexpectedDataType = 'Unexpected data type %s';
SDriverAlreadyRegistered = 'Driver already registered: ';
SNotDefinedIn = 'No "%s" defined in %s';
SDBXErrNone = 'None';
SDBXErrWarning = 'Warning';
SDBXErrNoMemory = 'Insufficient memory to complete the operation';
SDBXErrUnsupportedFieldType = 'Unsupported field type';
SDBXErrInvalidHandle = 'Unexpected internal error. DBX Object such as a connection, command, or reader may already be closed.';
SDBXErrNotSupported = 'Not supported';
SDBXErrInvalidTime = 'Invalid time';
SDBXErrInvalidType = 'Invalid type';
SDBXErrInvalidOrdinal = 'Invalid ordinal';
SDBXErrInvalidParameter = 'Invalid parameter';
SDBXErrEOF = 'No more rows';
SDBXErrParameterNotSet = 'Parameter not set';
SDBXErrInvalidUserOrPassword = 'Invalid username or password';
SDBXErrInvalidPrecision = 'Invalid precision';
SDBXErrInvalidLength = 'Invalid length';
SDBXErrInvalidIsolationLevel = 'Invalid isolation level';
SDBXErrInvalidTransactionId = 'Invalid transaction id';
SDBXErrDuplicateTransactionId = 'Duplicate transaction id';
SDBXErrDriverRestricted = 'Driver restricted';
SDBXErrTransactionActive = 'Transaction active';
SDBXErrMultipleTransactionNotEnabled = 'Multiple transaction not enabled';
SDBXErrConnectionFailed = 'Connection failed';
SDBXErrDriverInitFailed = 'Driver could not be properly initialized. Client library may be missing, not installed properly, of the wrong version, or the driver may be missing from the system path.';
SDBXErrOptimisticLockFailed = 'Optimistic lock failed';
SDBXErrInvalidReference = 'Invalid reference';
SDBXErrNoTable = 'No table';
SDBXErrMissingParameterMarker = 'Missing parameter marker';
SDBXErrNotImplemented = 'Not implemented';
SDBXErrDriverIncompatible = 'Driver incompatible';
SDBXErrInvalidArgument = 'Invalid argument';
SDBXErrNoData = 'No data';
SDBXErrVendorError = 'Vendor error';
SDBXErrUnrecognizedCommandType = 'Unrecognized command type.';
SDBXErrSchemaNameUnspecified = 'Schema or user name separated by a ''.'' must be specified.';
SDBXErrDatabaseUnspecified = 'Database must be specified.';
SDBXErrLibraryNameUnspecified = 'LibraryName must be specified.';
SDBXErrGetDriverFuncUnspecified = 'GetDriverFunc must be specified.';
SDBXErrVendorLibUnspecified = 'VendorLib must be specified';
SInvalidOrderByColumn = 'Table cannot use column %s in an order by operation since it does not exist';
SIllegalArgument = 'Illegal argument';
SUnsupportedOperation = 'Unsupported operation';
SUnexpectedStringOverflow = 'Unexpected string overflow. Length(''%s'') >= %s)';
SUTF8InvalidHeaderByte = 'UTF8: Type cannot be determined out of header byte at position %s';
SUTF8UnexpectedByte = 'UTF8: An unexpected continuation byte in %s-byte UTF8 in position %s';
SUTF8Start = 'UTF8: A start byte not followed by enough continuation bytes in position %s';
SInvalidJsonStream = 'Cannot convert JSON input into a stream';
SNoConversionToJSON = 'Cannot convert DBX type %s into a JSON value';
SNoConversionToDBX = 'Cannot convert JSON value %s input into %s';
SNoJSONConversion = 'No conversion exists for JSON value %s';
SIsLiteralSupported = 'Literal Supported';
SDataType = 'Platform Type Name';
SCatalogName = 'Catalog Name';
SProcedureType = 'Procedure Type';
SUnclosedQuotes = 'Unclosed quotes were found in the metadata query: %s.';
SDefaultValue = 'Default Value';
SForeignKeyName = 'Foreign Key Name';
SIndexName = 'Index Name';
SIsUnsigned = 'Unsigned';
SIsUnique = 'Unique';
SPrimaryKeyName = 'Primary Key Name';
SIsAscending = 'Ascending';
SOrdinalOutOfRange = 'Ordinal is outside the bounds of this cursor.';
SScale = 'Scale';
SColumnName = 'Column Name';
STableSchemaName = 'Table Schema Name';
SPrimaryColumnName = 'Primary Column Name';
SOrdinal = 'Ordinal';
SWrongAccessorForType = 'Wrong accessor method used for the datatype: %s.';
SIsCaseSensitive = 'Case Sensitive';
SMinimumVersion = 'Minimum Version';
SIsSearchableWithLike = 'Searchable With Like';
SCreateParameters = 'Create Parameters';
SPackageName = 'Package Name';
SParameterMode = 'Parameter Mode';
SPrecision = 'Precision';
SIsBestMatch = 'Best Match';
SMissingImplementation = 'This method must be implemented in a derived class.';
SNoSchemaNameSpecified = 'No schema name specified.';
SMaximumVersion = 'Maximum Version';
SIsAutoIncrement = 'Auto Increment';
SLiteralSuffix = 'Literal Suffix';
SCreateFormat = 'Create Format';
SSchemaName = 'Schema Name';
SIsConcurrencyType = 'Concurrency';
SReservedWord = 'Reserved Word';
SPrimaryCatalogName = 'Primary Catalog Name';
SUserName = 'User Name';
SExternalDefinition = 'External Definition';
STypeName = 'Type Name';
SIsNullable = 'Nullable';
SProviderDbType = 'Provider Type';
SIsFixedLength = 'Fixed Length';
SIsSearchable = 'Searchable';
SConstraintName = 'Constraint Name';
SUnknownSchemaName = 'Unknown schema name specified: %s';
SParameterName = 'Parameter Name';
STableType = 'Table Type';
SViewName = 'View Name';
SMinimumScale = 'Minimum Scale';
SColumnSize = 'Column Size';
SIsUnicode = 'Unicode';
SIsFixedPrecisionScale = 'Fixed Precision';
SUnexpectedSymbol = 'Could not parse the %1:s metadata command. Problem found near: %0:s. Original query: %2:s.';
SUnknownTableType = 'Unknown table type specified:';
SMetaDataCommandExpected = 'A MetaData command was expected here e.g. GetTables.';
SLiteralPrefix = 'Literal Prefix';
SIsPrimary = 'Primary';
SSynonymName = 'Synonym Name';
SRoleName = 'Role Name';
STableCatalogName = 'Table Catalog Name';
SMaximumScale = 'Maximum Scale';
SPrimarySchemaName = 'Primary Schema Name';
SMustCallNextFirst = 'Cursor is positioned before the first row, move to the next row before getting data';
SDbxDataType = 'DbxType';
SIsLong = 'Long';
SPrimaryTableName = 'Primary Table Name';
SMaxInline = 'Max Inline';
STableName = 'Table Name';
SProcedureName = 'Procedure Name';
SIsAutoIncrementable = 'AutoIncrementable';
SPastEndOfCursor = 'No more data.';
SDefinition = 'Definition';
SNoTypeWithEnoughPrecision = 'The best type match in %s for the column: %s is %s. But it is does not have sufficient precision.';
SCannotBeUsedForAutoIncrement = 'The best type match in %s for the column: %s is %s. But is cannot be used for an auto increment column.';
SNoBlobTypeFound = 'No long %2:s type found for the column: %1:s in %0:s.';
STypeNameNotFound = 'Data type: %s is not recognized for SQL dialect.';
SWrongViewDefinition = 'A view definition must start with the CREATE keyword.';
SNoSignedTypeFound = 'The best type match in %s for the column: %s is %s. But it is unsigned.';
SCannotHoldWantedPrecision = 'The best type match in %s for the column: %s is %s. But the max precision is: %s which is less than the specified: %s.';
SCannotHoldWantedScale = 'The best type match in %s for the column: %s is %s. But the max scale is: %s which is less than the specified: %s.';
STypeNotFound = 'No %2:s type found for the column: %1:s in %0:s.';
SCannotHoldUnicodeChars = 'The best type match in %s for the column: %s is %s. But it cannot hold unicode characters.';
SCannotRecreateConstraint = 'The constraint: %s could not be recreated, because the column: %s was dropped.';
SUnknownColumnName = 'The Data type: %s requires a column: %s, which does not exist on the Column collection.';
SUnsupportedType = 'Unsupported data type: %s';
SParameterNotSet = 'Parameter not set for column number %s';
SInvalidHandle = 'Invalid Handle';
implementation
end.
|
UNIT TurtleGr;
{ turtle routines }
{$N+}
interface
TYPE
{ ================================================================== }
TurtleRec = RECORD
{ Don't touch these things }
{ The Procedures handle everything }
X,
Y : SINGLE;
StepSize,
Theta : SINGLE;
Draw : BOOLEAN;
END;
{ Use these procedures }
PROCEDURE Init(VAR t : TurtleRec; StartX,StartY : SINGLE);
{ Position turtle at pixel (X,Y) }
PROCEDURE Turn(VAR t : TurtleRec; angle : SINGLE);
{ rotate turtle to an angle RELATIVE to current direction. }
PROCEDURE ChangeStep(VAR t : TurtleRec; PixelsPerStep : SINGLE);
PROCEDURE StartDrawing(VAR t : TurtleRec);
{ Make Turtle Movements visible }
PROCEDURE StopDrawing(VAR t : TurtleRec);
{ Make Turtle movements invisible }
PROCEDURE Step(VAR t : TurtleRec);
{ Move Turtle One Step according to step size and angle }
PROCEDURE Point(VAR t : TurtleRec; X1,Y1,X2,Y2 : SINGLE);
{point turtle parallel to line described by x1,y1-x2,y2}
{ ================================================================== }
implementation
USES
GraphPrm {LineDraw};
VAR
HaPiRadian : SINGLE;
{ ------------------------------------------------------------ }
PROCEDURE Init(VAR t : TurtleRec;StartX,StartY : SINGLE);
BEGIN
t.x := StartX;
t.y := StartY;
t.StepSize := 1;
t.Theta := 0;
t.Draw := FALSE;
END;
{ ------------------------------------------------------------ }
PROCEDURE Turn(VAR t : TurtleRec; angle : SINGLE);
BEGIN
t.Theta := (t.Theta + angle);
{ ensure a valid angle }
REPEAT
IF t.Theta >= 360.0 THEN
t.Theta := t.Theta - 360.0
ELSE IF t.Theta < 0.0 THEN
t.Theta := 360.0 + t.Theta;
UNTIL (t.Theta < 360.0) AND NOT (t.Theta < 0.0)
END;
{ ------------------------------------------------------------ }
PROCEDURE ChangeStep(VAR t : TurtleRec; PixelsPerStep : SINGLE);
BEGIN
t.StepSize := PixelsPerStep;
END;
{ ------------------------------------------------------------ }
PROCEDURE StartDrawing(VAR t : TurtleRec);
BEGIN
t.Draw := TRUE;
END;
{ ------------------------------------------------------------ }
PROCEDURE StopDrawing(VAR t : TurtleRec);
BEGIN
t.Draw := FALSE;
END;
{ ------------------------------------------------------------ }
PROCEDURE Step(VAR t : TurtleRec);
VAR
OldX, OldY : SINGLE;
BEGIN
OldX := t.X;
OldY := t.Y;
t.X := t.X + t.StepSize * cos(t.Theta*HaPiRadian);
t.Y := t.Y + t.StepSize * sin(t.Theta*HaPiRadian);
IF t.Draw THEN
DrawLine(TRUNC(OldX),TRUNC(OldY),TRUNC(t.X),TRUNC(t.Y),15);
END;
{ ------------------------------------------------------------ }
PROCEDURE Point(VAR t : TurtleRec; X1,Y1,X2,Y2 : SINGLE);
BEGIN
IF (X2-X1) = 0 THEN
IF Y2 > Y1 THEN
t.Theta := 90.0
ELSE
t.Theta := 270.0
ELSE
t.Theta := ArcTan((Y2-Y1)/(X2-X1)) / HaPiRadian;
IF X1 > X2 THEN
t.Theta := t.Theta + 180;
END;
{ ------------------------------------------------------------ }
BEGIN
HaPiRadian := Pi / 180.0;
END. |
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ SOAP Support }
{ }
{ Copyright (c) 2001 Borland Software Corporation }
{ }
{*******************************************************}
unit WSDLNode;
interface
uses Classes, WebNode, OpConvert, XMLDOc, XMLIntf, WSDLItems, TypInfo;
type
TWSDLView = class(TComponent)
private
FPortType: string;
FPort: string;
FOperation: string;
FService: string;
FWSDL: TWSDLItems;
FIWSDL: IXMLDocument;
procedure SetWSDL(Value: TWSDLItems);
public
IntfInfo: PTypeInfo;
published
property PortType: string read FPortType write FPortType;
property Port: string read FPort write FPort;
property Operation: string read FOperation write FOperation;
property Service: string read FService write FService;
property WSDL: TWSDLItems read FWSDL write SetWSDL;
end;
TWSDLClientNode = class(TComponent, IWebNode)
private
FWSDLView: TWSDLView;
FTransportNode: IWebNode;
procedure SetTransportNode(Value: IWebNode);
public
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure Execute(const DataMsg: WideString; Resp: TStream);
published
property WSDLView: TWSDLView read FWSDLView write FWSDLView;
property TransportNode: IWebNode read FTransportNode write SetTransportNode;
end;
implementation
{ TWSDLClientNode }
procedure TWSDLClientNode.Execute(const DataMsg: WideString; Resp: TStream);
begin
end;
procedure TWSDLClientNode.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
if (Operation = opRemove) and AComponent.IsImplementorOf(FTransportNode) then
FTransportNode := nil;
end;
procedure TWSDLClientNode.SetTransportNode(Value: IWebNode);
begin
if Assigned(Value) then
begin
ReferenceInterface(FTransportNode, opRemove);
FTransportNode := Value;
ReferenceInterface(FTransportNode, opInsert);
end;
end;
{ TWSDLView }
procedure TWSDLView.SetWSDL(Value: TWSDLItems);
begin
if Assigned(Value) then
begin
FWSDL := Value;
FIWSDL := Value as IXMLDocument;
end;
end;
end.
|
unit LCLIntF;
{
LLCL - FPC/Lazarus Light LCL
based upon
LVCL - Very LIGHT VCL
----------------------------
This file is a part of the Light LCL (LLCL).
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/.
This Source Code Form is "Incompatible With Secondary Licenses",
as defined by the Mozilla Public License, v. 2.0.
Copyright (c) 2015-2016 ChrisF
Based upon the Very LIGHT VCL (LVCL):
Copyright (c) 2008 Arnaud Bouchez - http://bouchez.info
Portions Copyright (c) 2001 Paul Toth - http://tothpaul.free.fr
Version 1.02:
Version 1.01:
* File creation.
Notes:
- very basic unit specific to FPC/Lazarus (not used with Delphi).
}
{$IFDEF FPC}
{$define LLCL_FPC_MODESECTION}
{$I LLCLFPCInc.inc} // For mode
{$undef LLCL_FPC_MODESECTION}
{$ENDIF}
{$I LLCLOptions.inc} // Options
//------------------------------------------------------------------------------
interface
uses
LLCLOSInt,
Windows;
const
LM_USER = Windows.WM_USER;
function CallWindowProc(lpPrevWndFunc: TFarProc; Handle: HWND; Msg: UINT; WParam: WParam; LParam: LParam): integer;
function PostMessage(Handle: HWND; Msg: Cardinal; WParam: WParam; LParam: LParam): boolean;
function SendMessage(Handle: HWND; Msg: Cardinal; WParam: WParam; LParam: LParam): LRESULT;
function MakeLong(A, B: word): DWORD; inline;
function MakeWParam(l, h: word): WPARAM; inline;
function MakeLParam(l, h: word): LPARAM; inline;
function MakeLResult(l, h: word): LRESULT; inline;
//------------------------------------------------------------------------------
implementation
{$IFDEF FPC}
{$PUSH} {$HINTS OFF}
{$ENDIF}
//------------------------------------------------------------------------------
function CallWindowProc(lpPrevWndFunc: TFarProc; Handle: HWND; Msg: UINT; WParam: WParam; LParam: LParam): integer;
begin
result := LLCL_CallWindowProc(lpPrevWndFunc, Handle, Msg, WParam, LParam);
end;
function PostMessage(Handle: HWND; Msg: Cardinal; WParam: WParam; LParam: LParam): boolean;
begin
result := LLCL_PostMessage(Handle, Msg, WParam, LParam);
end;
function SendMessage(Handle: HWND; Msg: Cardinal; WParam: WParam; LParam: LParam): LRESULT;
begin
result := LLCL_SendMessage(Handle, Msg, WParam, LParam);
end;
function MakeLong(A, B: word): DWORD; inline;
begin
result := A or (B shl 16);
end;
function MakeWParam(l, h: word): WPARAM; inline;
begin
result := MakeLong(l, h);
end;
function MakeLParam(l, h: word): LPARAM; inline;
begin
result := MakeLong(l, h);
end;
function MakeLResult(l, h: word): LRESULT; inline;
begin
result := MakeLong(l, h);
end;
//------------------------------------------------------------------------------
{$IFDEF FPC}
{$POP}
{$ENDIF}
end.
|
unit Amazon.Marshaller;
interface
uses System.Rtti, System.TypInfo, System.Classes, System.StrUtils,
System.SysUtils,
Amazon.Utils, Amazon.Interfaces, Generics.Collections;
type
TAmazonMarshallerAttribute = class(TCustomAttribute)
private
fsTagName: string;
public
constructor Create(const aTagName: string);
property TagName: string read fsTagName write fsTagName;
end;
TAmazonMarshaller = class(TInterfacedObject, IAmazonMarshaller)
protected
private
procedure CloseJSONArray(var aJSON: TStringList;
aCloseBracket: UTF8String = ']'; aIsClass: Boolean = false);
procedure OpenJSONArray(var aJSON: TStringList; aParentTagName: UTF8String;
aOpenBracket: UTF8String = '[');
procedure AddJSONArray(var aJSON: TStringList;
fsTagName, fsTagValue: UTF8String);
procedure AddJSONString(aTypeKind: TTypeKind; var aJSON: TStringList;
aTagName, aTagValue: UTF8String; aIsClass: Boolean;
var aIsOpenBracket: Boolean; aIsListJSONArray: Boolean = false;
aIsSubOpenBracket: Boolean = false);
function IsAnyKindOfGenericList(AType: TRttiType): Boolean;
public
procedure GetSubRttiAttributekeys(var aJSON: TStringList;
aParentTagName: string; aCtx: TRttiContext; aObject: TObject;
aIsClass: Boolean = false; aIsOpenBracket: Boolean = false;
aIsListJSONArray: Boolean = false);
end;
implementation
constructor TAmazonMarshallerAttribute.Create(const aTagName: string);
begin
fsTagName := aTagName;
end;
procedure TAmazonMarshaller.GetSubRttiAttributekeys(var aJSON: TStringList;
aParentTagName: string; aCtx: TRttiContext; aObject: TObject;
aIsClass: Boolean = false; aIsOpenBracket: Boolean = false;
aIsListJSONArray: Boolean = false);
var
I: Integer;
prop: TRttiProperty;
fsTagName, fsTagValue, fsPropName: UTF8String;
a: TCustomAttribute;
fRttiType: TRttiType;
val: TValue;
// FList: Tlist;
FObject: TObject;
FIsSubOpenBracket: Boolean;
FObjectList: TObjectList<TObject>;
begin
FIsSubOpenBracket := false;
if aIsClass then
begin
if IsAnyKindOfGenericList(aCtx.GetType(aObject.ClassType)) then
begin
// FList := Tlist(aObject);
FObjectList := TObjectList<TObject>(aObject);
OpenJSONArray(aJSON, aParentTagName);
for I := 0 to FObjectList.Count - 1 do
begin
FObject := FObjectList[I];
// FObject := TObject(FList.Items[i]);
GetSubRttiAttributekeys(aJSON, aParentTagName, aCtx, FObject, false,
true, true);
end;
CloseJSONArray(aJSON);
Exit;
end
else
begin
OpenJSONArray(aJSON, aParentTagName, '{');
aIsOpenBracket := true;
end;
end
else if aIsListJSONArray then
begin
OpenJSONArray(aJSON, '', '{');
FIsSubOpenBracket := true;
aIsOpenBracket := false;
end;
for prop in aCtx.GetType(aObject.ClassType).GetProperties do
begin
fsPropName := prop.Name;
for a in prop.GetAttributes do
begin
fsTagName := TAmazonMarshallerAttribute(a).TagName;
fRttiType := prop.PropertyType;
case fRttiType.TypeKind of
tkInteger, tkLString, tkWString, tkString:
begin
val := prop.GetValue(aObject);
fsTagValue := val.ToString;
AddJSONString(fRttiType.TypeKind, aJSON, fsTagName, fsTagValue,
aIsClass, aIsOpenBracket, aIsListJSONArray, FIsSubOpenBracket);
end;
tkClass:
begin
val := prop.GetValue(aObject);
GetSubRttiAttributekeys(aJSON, fsTagName, aCtx, val.AsObject, true);
end;
end;
FIsSubOpenBracket := false;
end;
end;
if aIsClass then
CloseJSONArray(aJSON, '}', aIsClass)
else if aIsListJSONArray then
begin
FIsSubOpenBracket := false;
CloseJSONArray(aJSON, '}', false);
end;
end;
function TAmazonMarshaller.IsAnyKindOfGenericList(AType: TRttiType): Boolean;
begin
Result := false;
while AType <> nil do
begin
Result := StartsText('TList<', AType.Name);
if Result then
Exit;
AType := AType.BaseType;
end;
end;
procedure TAmazonMarshaller.AddJSONString(aTypeKind: TTypeKind;
var aJSON: TStringList; aTagName, aTagValue: UTF8String; aIsClass: Boolean;
var aIsOpenBracket: Boolean; aIsListJSONArray: Boolean = false;
aIsSubOpenBracket: Boolean = false);
Var
lsJSONLine: UTF8String;
begin
case aTypeKind of
tkInteger:
begin
lsJSONLine := DoubleQuotedStr(aTagName) + ':' + aTagValue;
end
else
lsJSONLine := DoubleQuotedStr(aTagName) + ':' + DoubleQuotedStr(aTagValue);
end;
If not aIsClass then
begin
if aJSON.Count > 0 then
begin
if aIsListJSONArray then
begin
if not aIsSubOpenBracket then
aJSON.Strings[aJSON.Count - 1] := aJSON.Strings[aJSON.Count - 1] + ','
end
else if Not aIsOpenBracket then
aJSON.Strings[aJSON.Count - 2] := aJSON.Strings[aJSON.Count - 2] + ','
end;
aJSON.Add(lsJSONLine);
end
else
begin
if aIsOpenBracket then
begin
aJSON.Strings[aJSON.Count - 1] := aJSON.Strings[aJSON.Count - 1] +
lsJSONLine;
aIsOpenBracket := false;
end
else
aJSON.Strings[aJSON.Count - 1] := aJSON.Strings[aJSON.Count - 1] + ',' +
lsJSONLine;
end;
end;
procedure TAmazonMarshaller.AddJSONArray(var aJSON: TStringList;
fsTagName, fsTagValue: UTF8String);
Var
lsJSONLine: UTF8String;
begin
lsJSONLine := '{' + DoubleQuotedStr(fsTagName) + ':' +
DoubleQuotedStr(fsTagValue) + '}';
aJSON.Add(lsJSONLine);
end;
procedure TAmazonMarshaller.OpenJSONArray(var aJSON: TStringList;
aParentTagName: UTF8String; aOpenBracket: UTF8String = '[');
Var
lsJSONLine: UTF8String;
begin
if aParentTagName <> '' then
begin
lsJSONLine := '"' + aParentTagName + '": ' + aOpenBracket;
if aJSON.Count > 0 then
begin
aJSON.Strings[aJSON.Count - 1] := aJSON.Strings[aJSON.Count - 1] + ',';
end
end
else
lsJSONLine := aOpenBracket;
aJSON.Add(lsJSONLine);
end;
procedure TAmazonMarshaller.CloseJSONArray(var aJSON: TStringList;
aCloseBracket: UTF8String = ']'; aIsClass: Boolean = false);
begin
if Not aIsClass then
aJSON.Add(aCloseBracket)
else
aJSON.Strings[aJSON.Count - 1] := aJSON.Strings[aJSON.Count - 1] +
aCloseBracket;
end;
end.
|
unit rOptions;
interface
uses SysUtils, Classes, ORNet, ORFn, uCore, rCore, rTIU, rConsults;
procedure rpcGetNotifications(aResults: TStrings);
procedure rpcGetOrderChecks(aResults: TStrings);
function rpcGetNotificationDefaults: String;
function rpcGetSurrogateInfo: String;
procedure rpcCheckSurrogate(surrogate: Int64; var ok: boolean; var msg: string);
//procedure rpcSetSurrogateInfo(aString: String);
procedure rpcSetSurrogateInfo(aString: String; var ok: boolean; var msg: string);
procedure rpcClearNotifications;
procedure rpcSetNotifications(aList: TStringList);
procedure rpcSetOrderChecks(aList: TStringList);
procedure rpcSetOtherStuff(aString: String);
procedure rpcSetCopyPaste(aString: String);
function rpcGetCopyPaste: String;
procedure rpcGetOtherTabs(aResults: TStrings);
function rpcGetOther: String;
procedure rpcSetOther(info: String);
procedure rpcGetCosigners(const StartFrom: string; Direction: Integer; aResults: TStrings);
function rpcGetDefaultCosigner: String;
procedure rpcSetDefaultCosigner(value: Int64);
function rpcGetSubject: boolean;
procedure rpcSetSubject(value: boolean);
procedure rpcGetClasses(aResults: TStrings);
procedure rpcGetTitlesForClass(value: integer; const StartFrom: string; Direction: Integer; aResults: TStrings);
procedure rpcGetTitlesForUser(value: integer; aResults: TStrings);
function rpcGetTitleDefault(value: integer): integer;
procedure rpcSaveDocumentDefaults(classvalue, titledefault: integer; aList: TStrings);
procedure rpcGetLabDays(var InpatientDays: integer; var OutpatientDays: integer);
procedure rpcGetLabUserDays(var InpatientDays: integer; var OutpatientDays: integer);
procedure rpcGetApptDays(var StartDays: integer; var StopDays: integer);
procedure rpcGetApptUserDays(var StartDays: integer; var StopDays: integer);
procedure rpcSetDays(InpatientDays, OutpatientDays, StartDays, StopDays: integer);
procedure rpcGetImagingDays(var MaxNum: integer; var StartDays: integer; var StopDays: integer);
procedure rpcGetImagingUserDays(var MaxNum: integer; var StartDays: integer; var StopDays: integer);
procedure rpcSetImagingDays(MaxNum, StartDays, StopDays: integer);
procedure rpcGetReminders(Dest: TStrings);
procedure rpcSetReminders(aList: TStringList);
function rpcGetListOrder: Char;
procedure rpcGetClinicUserDays(var StartDays: integer; var StopDays: integer);
procedure rpcGetClinicDefaults(var mon, tues, wed, thurs, fri, sat, sun: integer);
procedure rpcGetListSourceDefaults(var provider, treating, list, ward, pcmm: integer);
procedure rpcSetClinicDefaults(StartDays, StopDays, mon, tues, wed, thurs, fri, sat, sun: integer);
procedure rpcSetPtListDefaults(PLSource: string; PLSort: Char; prov, spec, team, ward, pcmm: integer);
procedure rpcGetPersonalLists(Dest: TStrings);
procedure rpcGetAllTeams(Dest: TStrings);
procedure rpcGetTeams(Dest: TStrings);
procedure rpcGetATeams(Dest: TStrings);
procedure rpcGetPcmmTeams(Dest: TStrings);
procedure rpcDeleteList(aString: String);
function rpcNewList(aString: String; Visibility: integer): String;
procedure rpcSaveListChanges(aList: TStrings; aListIEN, aListVisibility: integer);
procedure rpcListUsersByTeam(Dest: TStrings; teamid: integer);
procedure rpcListUsersByPcmmTeam(Dest: TStrings; teamid: integer);
procedure rpcRemoveList(aListIEN: integer);
procedure rpcAddList(aListIEN: integer);
procedure rpcGetCombo(aResults: TStrings);
procedure rpcSetCombo(aList: TStrings);
procedure rpcGetDefaultReportsSetting(var int1: integer; var int2: integer; var int3: integer);
procedure rpcDeleteUserLevelReportsSetting;
procedure rpcActiveDefaultSetting;
procedure rpcSetDefaultReportsSetting(aString: string);
procedure rpcSetIndividualReportSetting(aString1:string; aString2:string);
procedure rpcRetrieveDefaultSetting(var int1: integer; var int2: integer; var int3: integer; var msg: string);
procedure rpcGetRangeForMeds(var startDt, stopDt: TFMDateTime);
procedure rpcPutRangeForMeds(TheVal: string);
procedure rpcGetRangeForMedsIn(var startDt, stopDt: TFMDateTime);
procedure rpcPutRangeForMedsIn(TheVal: string);
procedure rpcGetRangeForMedsOp(var startDt, stopDt: TFMDateTime);
procedure rpcPutRangeForMedsOp(TheVal: string);
procedure rpcGetRangeForEncs(var StartDays, StopDays: integer; DefaultParams: Boolean);
procedure rpcPutRangeForEncs(StartDays, StopDays: string);
procedure rpcGetEncFutureDays(var FutureDays: string);
implementation
//..............................................................................
procedure rpcGetNotifications(aResults: TStrings);
begin
CallVistA('ORWTPP GETNOT', [nil], aResults);
MixedCaseList(aResults);
end;
procedure rpcGetOrderChecks(aResults: TStrings);
begin
CallVistA('ORWTPP GETOC', [nil], aResults);
MixedCaseList(aResults);
end;
function rpcGetNotificationDefaults: String;
begin
CallVistA('ORWTPP GETNOTO', [nil], Result);
end;
function rpcGetSurrogateInfo: String;
begin
CallVistA('ORWTPP GETSURR', [nil], Result);
Result := MixedCase(Result);
end;
procedure rpcCheckSurrogate(surrogate: Int64; var ok: boolean; var msg: string);
var
value: string;
begin
CallVistA('ORWTPP CHKSURR', [surrogate], value);
ok := Piece(value, '^', 1) = '1';
msg := Piece(value, '^', 2);
end;
(*procedure rpcSetSurrogateInfo(aString: String);
begin
CallV('ORWTPP SAVESURR', [aString]);
end;*)
procedure rpcSetSurrogateInfo(aString: String; var ok: boolean; var msg: string);
var
value: string;
begin
CallVistA('ORWTPP SAVESURR', [aString], value);
ok := Piece(value, '^', 1) = '1';
msg := Piece(value, '^', 2);
end;
procedure rpcClearNotifications;
begin
CallVistA('ORWTPP CLEARNOT', [nil]);
end;
procedure rpcSetNotifications(aList: TStringList);
begin
CallVistA('ORWTPP SAVENOT', [aList]);
end;
procedure rpcSetOrderChecks(aList: TStringList);
begin
CallVistA('ORWTPP SAVEOC', [aList]);
end;
procedure rpcSetOtherStuff(aString: String);
begin
CallVistA('ORWTPP SAVENOTO', [aString]);
end;
procedure rpcSetCopyPaste(aString: String);
begin
CallVistA('ORWTIU SVCPIDNT', [aString]);
end;
//..............................................................................
function rpcGetCopyPaste: String;
begin
CallVistA('ORWTIU LDCPIDNT', [nil], Result);
end;
procedure rpcGetOtherTabs(aResults: TStrings);
begin
CallVistA('ORWTPO GETTABS', [nil], aResults);
MixedCaseList(aResults);
end;
function rpcGetOther: String;
begin
CallVistA('ORWTPP GETOTHER', [nil], Result);
end;
procedure rpcSetOther(info: String);
begin
CallVistA('ORWTPP SETOTHER', [info]);
end;
procedure rpcGetCosigners(const StartFrom: string; Direction: Integer; aResults: TStrings);
begin
CallVistA('ORWTPP GETCOS', [StartFrom, Direction], aResults);
MixedCaseList(aResults);
end;
function rpcGetDefaultCosigner: String;
begin
CallVistA('ORWTPP GETDCOS', [nil], Result);
end;
procedure rpcSetDefaultCosigner(value: Int64);
begin
CallVistA('ORWTPP SETDCOS', [value])
end;
function rpcGetSubject: boolean;
var
value: string;
begin
CallVistA('ORWTPP GETSUB', [nil], value);
Result := (value = '1');
end;
procedure rpcSetSubject(value: boolean);
begin
CallVistA('ORWTPP SETSUB', [value])
end;
procedure rpcGetClasses(aResults: TStrings);
begin
CallVistA('ORWTPN GETCLASS', [nil], aResults);
MixedCaseList(aResults);
end;
procedure rpcGetTitlesForClass(value: integer; const StartFrom: string; Direction: Integer; aResults: TStrings);
begin
CallVistA('TIU LONG LIST OF TITLES', [value, StartFrom, Direction], aResults);
end;
procedure rpcGetTitlesForUser(value: integer; aResults: TStrings);
begin
CallVistA('ORWTPP GETTU', [value], aResults);
end;
function rpcGetTitleDefault(value: integer): integer;
begin
CallVistA('ORWTPP GETTD', [value], Result, -1);
end;
procedure rpcSaveDocumentDefaults(classvalue, titledefault: integer; aList: TStrings);
begin
CallVistA('ORWTPP SAVET', [classvalue, titledefault, aList]);
end;
//..............................................................................
procedure rpcGetLabDays(var InpatientDays: integer; var OutpatientDays:integer);
var
values: string;
begin
CallVistA('ORWTPO CSLABD', [nil], values);
InpatientDays := strtointdef(Piece(values, '^', 1), 0);
OutpatientDays := strtointdef(Piece(values, '^', 2), 0);
end;
procedure rpcGetLabUserDays(var InpatientDays: integer; var OutpatientDays: integer);
var
values: string;
begin
CallVistA('ORWTPP CSLAB', [nil], values);
InpatientDays := -strtointdef(Piece(values, '^', 1), 0);
OutpatientDays := -strtointdef(Piece(values, '^', 2), 0);
end;
procedure rpcGetApptDays(var StartDays: integer; var StopDays: integer);
var
values, start, stop: string;
begin
CallVistA('ORWTPD1 GETCSDEF', [nil], values);
start := Piece(values, '^', 1);
stop := Piece(values, '^', 2);
StartDays := strtointdef(Piece(start, 'T', 2), 0);
StopDays := strtointdef(Piece(stop, 'T', 2), 0);
end;
procedure rpcGetApptUserDays(var StartDays: integer; var StopDays: integer);
var
values, start, stop: string;
begin
CallVistA('ORWTPD1 GETCSRNG', [nil], values);
start := Piece(values, '^', 1);
stop := Piece(values, '^', 2);
StartDays := strtointdef(Piece(start, 'T', 2), 0);
StopDays := strtointdef(Piece(stop, 'T', 2), 0);
end;
procedure rpcSetDays(InpatientDays, OutpatientDays, StartDays, StopDays: integer);
var
values: string;
begin
values := '';
values := values + inttostr(InpatientDays) + '^';
values := values + inttostr(OutpatientDays) + '^';
values := values + inttostr(StartDays) + '^';
values := values + inttostr(StopDays) + '^';
CallVistA('ORWTPD1 PUTCSRNG', [values]);
end;
procedure rpcGetImagingDays(var MaxNum: integer; var StartDays: integer; var StopDays: integer);
var
values, max, start, stop: string;
begin
CallVistA('ORWTPO GETIMGD', [nil], values);
//values := 'T-120;T;;;100';
start := Piece(values, ';', 1);
stop := Piece(values, ';', 2);
max := Piece(values, ';', 5);
StartDays := strtointdef(Piece(start, 'T', 2), 0);
StopDays := strtointdef(Piece(stop, 'T', 2), 0);
MaxNum := strtointdef(max, 0);
end;
procedure rpcGetImagingUserDays(var MaxNum: integer; var StartDays: integer; var StopDays: integer);
var
values, max, start, stop: string;
begin
CallVistA('ORWTPP GETIMG', [nil], values);
//values := 'T-180;T;;;15';
start := Piece(values, ';', 1);
stop := Piece(values, ';', 2);
max := Piece(values, ';', 5);
StartDays := strtointdef(Piece(start, 'T', 2), 0);
StopDays := strtointdef(Piece(stop, 'T', 2), 0);
MaxNum := strtointdef(max, 0);
end;
procedure rpcSetImagingDays(MaxNum, StartDays, StopDays: integer);
begin
CallVistA('ORWTPP SETIMG', [MaxNum, StartDays, StopDays]);
end;
//..............................................................................
procedure rpcGetReminders(Dest: TStrings);
begin
CallVistA('ORWTPP GETREM', [nil], Dest);
MixedCaseList(Dest);
end;
procedure rpcSetReminders(aList: TStringList);
begin
CallVistA('ORWTPP SETREM', [aList]);
end;
//..............................................................................
function rpcGetListOrder: Char;
var
aResult: String;
begin
CallVistA('ORWTPP SORTDEF', [nil], aResult);
Result := CharAt(aResult, 1);
end;
procedure rpcGetClinicUserDays(var StartDays: integer; var StopDays: integer);
var
values, start, stop: string;
begin
CallVistA('ORWTPP CLRANGE', [nil], values);
start := Piece(values, '^', 1);
stop := Piece(values, '^', 2);
StartDays := strtointdef(Piece(start, 'T', 2), 0);
StopDays := strtointdef(Piece(stop, 'T', 2), 0);
end;
procedure rpcGetClinicDefaults(var mon, tues, wed, thurs, fri, sat, sun: integer);
var
values: string;
begin
CallVistA('ORWTPP CLDAYS', [nil], values);
mon := strtointdef(Piece(values, '^', 1), 0);
tues := strtointdef(Piece(values, '^', 2), 0);
wed := strtointdef(Piece(values, '^', 3), 0);
thurs := strtointdef(Piece(values, '^', 4), 0);
fri := strtointdef(Piece(values, '^', 5), 0);
sat := strtointdef(Piece(values, '^', 6), 0);
sun := strtointdef(Piece(values, '^', 7), 0);
end;
procedure rpcGetListSourceDefaults(var provider, treating, list, ward, pcmm: integer);
var
values: string;
begin
CallVistA('ORWTPP LSDEF', [nil], values);
provider := strtointdef(Piece(values, '^', 1), 0);
treating := strtointdef(Piece(values, '^', 2), 0);
list := strtointdef(Piece(values, '^', 3), 0);
ward := strtointdef(Piece(values, '^', 4), 0);
pcmm := strtointdef(Piece(values, '^', 6), 0);
end;
procedure rpcSetClinicDefaults(StartDays, StopDays, mon, tues, wed, thurs, fri, sat, sun: integer);
var
values: string;
begin
values := '';
values := values + inttostr(StartDays) + '^';
values := values + inttostr(StopDays) + '^';
values := values + inttostr(mon) + '^';
values := values + inttostr(tues) + '^';
values := values + inttostr(wed) + '^';
values := values + inttostr(thurs) + '^';
values := values + inttostr(fri) + '^';
values := values + inttostr(sat) + '^';
values := values + inttostr(sun) + '^';
CallVistA('ORWTPP SAVECD', [values]);
end;
procedure rpcSetPtListDefaults(PLSource: string; PLSort: Char; prov, spec, team, ward, pcmm: integer);
// TDP - Modified 5/27/2014 - Changed PLSource to string and added pcmm input
var
values: string;
begin
values := '';
values := values + PLSource + '^';
values := values + PLSort + '^';
values := values + inttostr(prov) + '^';
values := values + inttostr(spec) + '^';
values := values + inttostr(team) + '^';
values := values + inttostr(ward) + '^';
values := values + inttostr(pcmm) + '^'; // TDP - Added 5/27/2014
CallVistA('ORWTPP SAVEPLD', [values]);
end;
//..............................................................................
procedure rpcGetPersonalLists(Dest: TStrings);
begin
CallVistA('ORWTPP PLISTS', [nil], Dest);
MixedCaseList(Dest);
end;
procedure rpcGetAllTeams(Dest: TStrings);
begin
CallVistA('ORWTPP PLTEAMS', [nil], Dest);
MixedCaseList(Dest);
end;
procedure rpcGetTeams(Dest: TStrings);
begin
CallVistA('ORWTPP TEAMS', [nil], Dest);
MixedCaseList(Dest);
end;
procedure rpcGetATeams(Dest: TStrings);
begin
CallVistA('ORWTPT ATEAMS', [nil], Dest);
MixedCaseList(Dest);
end;
procedure rpcGetPcmmTeams(Dest: TStrings);
begin
CallVistA('ORWTPP PCMTEAMS', [nil], Dest);
MixedCaseList(Dest);
end;
procedure rpcDeleteList(aString: String);
begin
CallVistA('ORWTPP DELLIST', [aString]);
end;
function rpcNewList(aString: String; Visibility: integer): String;
begin
CallVistA('ORWTPP NEWLIST', [aString, Visibility], Result);
Result := MixedCase(Result);
end;
procedure rpcSaveListChanges(aList: TStrings; aListIEN, aListVisibility: integer);
begin
CallVistA('ORWTPP SAVELIST', [aList, aListIEN, aListVisibility]);
end;
procedure rpcListUsersByTeam(Dest: TStrings; teamid: integer);
begin
CallVistA('ORWTPT GETTEAM', [teamid], Dest);
MixedCaseList(Dest);
end;
procedure rpcListUsersByPcmmTeam(Dest: TStrings; teamid: integer);
begin
CallVistA('ORWTPT GETPTEAM', [teamid], Dest);
MixedCaseList(Dest);
end;
procedure rpcRemoveList(aListIEN: integer);
begin
CallVistA('ORWTPP REMLIST', [aListIEN]);
end;
procedure rpcAddList(aListIEN: integer);
begin
CallVistA('ORWTPP ADDLIST', [aListIEN]);
end;
//..............................................................................
procedure rpcGetCombo(aResults: TStrings);
begin
CallVistA('ORWTPP GETCOMBO', [nil], aResults);
MixedCaseList(aResults);
end;
procedure rpcSetCombo(aList: TStrings);
begin
CallVistA('ORWTPP SETCOMBO', [aList]);
end;
//..............................................................................
procedure rpcGetDefaultReportsSetting(var int1: integer; var int2: integer; var int3: integer);
var
values: string;
startoffset,stopoffset: string;
begin
CallVistA('ORWTPD GETDFLT', [nil], values);
if length(values)=0 then
exit;
startoffset := Piece(values,';',1);
delete(startoffset,1,1);
stopoffset := Piece(values,';',2);
delete(stopoffset,1,1);
int1 := strtointdef(startoffset,0);
int2 := strtointdef(stopoffset,0);
int3:= strtointdef(Piece(values, ';', 3), 100); // max occurences
end;
procedure rpcDeleteUserLevelReportsSetting;
begin
CallVistA('ORWTPD DELDFLT',[nil]);
end;
procedure rpcActiveDefaultSetting;
begin
CallVistA('ORWTPD ACTDF',[nil]);
end;
procedure rpcSetDefaultReportsSetting(aString: string);
begin
CallVistA('ORWTPD SUDF',[aString]);
end;
procedure rpcSetIndividualReportSetting(aString1:string; aString2:string);
begin
CallVistA('ORWTPD SUINDV',[aString1,aString2]);
end;
procedure rpcRetrieveDefaultSetting(var int1: integer; var int2: integer; var int3: integer; var msg: string);
var
values: string;
startoffset,stopoffset: string;
begin
CallVistA('ORWTPD RSDFLT',[nil], values);
if length(values)=0 then
begin
msg := 'NODEFAULT';
exit;
end;
startoffset := Piece(values,';',1);
delete(startoffset,1,1);
stopoffset := Piece(values,';',2);
delete(stopoffset,1,1);
int1 := strtointdef(startoffset,0);
int2 := strtointdef(stopoffset,0);
int3:= strtointdef(Piece(values, ';', 3), 100); // max occurences
end;
procedure rpcGetRangeForMeds(var startDt, stopDt: TFMDateTime);
var
rst,sDt,eDt: string;
td: TFMDateTime;
begin
CallVistA('ORWTPD GETOCM', [nil], rst);
sDt := Piece(rst,';',1);
if lowerCase(sDt) <> 't' then
Delete(sDt,1,1);
eDt := Piece(rst,';',2);
if lowerCase(eDt) <> 't' then
Delete(eDt,1,1);
td := FMToday;
if Length(sDt)>0 then
startDt := FMDateTimeOffsetBy(td, StrToIntDef(sDt,0));
if Length(eDt)>0 then
stopDt := FMDateTimeOffsetBy(td, StrToIntDef(eDt,0));
end;
procedure rpcPutRangeForMeds(TheVal: string);
begin
CallVistA('ORWTPD PUTOCM',[TheVal]);
end;
procedure rpcGetRangeForMedsIn(var startDt, stopDt: TFMDateTime);
var
rst,sDt,eDt: string;
td: TFMDateTime;
begin
CallVistA('ORWTPD GETOCMIN', [nil], rst);
sDt := Piece(rst,';',1);
if lowerCase(sDt) <> 't' then
Delete(sDt,1,1);
eDt := Piece(rst,';',2);
if lowerCase(eDt) <> 't' then
Delete(eDt,1,1);
td := FMToday;
if Length(sDt)>0 then
startDt := FMDateTimeOffsetBy(td, StrToIntDef(sDt,0));
if Length(eDt)>0 then
stopDt := FMDateTimeOffsetBy(td, StrToIntDef(eDt,0));
end;
procedure rpcPutRangeForMedsIn(TheVal: string);
begin
CallVistA('ORWTPD PUTOCMIN',[TheVal]);
end;
procedure rpcGetRangeForMedsOp(var startDt, stopDt: TFMDateTime);
var
rst,sDt,eDt: string;
td: TFMDateTime;
begin
CallVistA('ORWTPD GETOCMOP', [nil], rst);
sDt := Piece(rst,';',1);
if lowerCase(sDt) <> 't' then
Delete(sDt,1,1);
eDt := Piece(rst,';',2);
if lowerCase(eDt) <> 't' then
Delete(eDt,1,1);
td := FMToday;
if Length(sDt)>0 then
startDt := FMDateTimeOffsetBy(td, StrToIntDef(sDt,0));
if Length(eDt)>0 then
stopDt := FMDateTimeOffsetBy(td, StrToIntDef(eDt,0));
end;
procedure rpcPutRangeForMedsOp(TheVal: string);
begin
CallVistA('ORWTPD PUTOCMOP',[TheVal]);
end;
procedure rpcGetRangeForEncs(var StartDays, StopDays: integer; DefaultParams: Boolean);
var
Start, Stop, Values: string;
begin
if DefaultParams then
CallVistA('ORWTPD1 GETEFDAT', [nil], Values)
else
CallVistA('ORWTPD1 GETEDATS', [nil], Values);
Start := Piece(Values, '^', 1);
Stop := Piece(Values, '^', 2);
StartDays := StrToIntDef(Start, 0);
StopDays := StrToIntDef(Stop, 0);
end;
procedure rpcPutRangeForEncs(StartDays, StopDays: string);
var
values: string;
begin
values := '';
values := values + StartDays + '^';
values := values + StopDays;
CallVistA('ORWTPD1 PUTEDATS',[values]);
end;
procedure rpcGetEncFutureDays(var FutureDays: string);
begin
CallVistA('ORWTPD1 GETEAFL', [nil], FutureDays);
end;
end.
|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Data.DBXDb2MetaDataWriter;
interface
uses
Data.DBXMetaDataWriter;
type
TDBXDb2MetaDataWriter = class(TDBXBaseMetaDataWriter)
public
constructor Create;
procedure Open; override;
protected
function IsSerializedIsolationSupported: Boolean; override;
function IsIndexNamesGlobal: Boolean; override;
function IsDescendingIndexConstraintsSupported: Boolean; override;
function GetSqlAutoIncrementKeyword: UnicodeString; override;
end;
implementation
uses
Data.DBXDb2MetaDataReader;
constructor TDBXDb2MetaDataWriter.Create;
begin
inherited Create;
Open;
end;
procedure TDBXDb2MetaDataWriter.Open;
begin
if FReader = nil then
FReader := TDBXDb2MetaDataReader.Create;
end;
function TDBXDb2MetaDataWriter.IsSerializedIsolationSupported: Boolean;
begin
Result := False;
end;
function TDBXDb2MetaDataWriter.IsIndexNamesGlobal: Boolean;
begin
Result := True;
end;
function TDBXDb2MetaDataWriter.IsDescendingIndexConstraintsSupported: Boolean;
begin
Result := False;
end;
function TDBXDb2MetaDataWriter.GetSqlAutoIncrementKeyword: UnicodeString;
begin
Result := 'GENERATED BY DEFAULT AS IDENTITY';
end;
end.
|
//
// Created by the DataSnap proxy generator.
// 2016-01-26 ¿ÀÈÄ 1:34:54
//
unit ServerMethods;
interface
uses System.JSON, Data.DBXCommon, Data.DBXClient, Data.DBXDataSnap, Data.DBXJSON, Datasnap.DSProxy, System.Classes, System.SysUtils, Data.DB, Data.SqlExpr, Data.DBXDBReaders, Data.DBXCDSReaders, Data.DBXJSONReflect;
type
TServerMethods1Client = class(TDSAdminClient)
private
FEchoStringCommand: TDBXCommand;
FReverseStringCommand: TDBXCommand;
FLog_inCommand: TDBXCommand;
Fmark_upCommand: TDBXCommand;
FGradecheckCommand: TDBXCommand;
FsignGradecheckCommand: TDBXCommand;
FSignupCommand: TDBXCommand;
FtotalCommand: TDBXCommand;
public
constructor Create(ADBXConnection: TDBXConnection); overload;
constructor Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); overload;
destructor Destroy; override;
function EchoString(Value: string): string;
function ReverseString(Value: string): string;
function Log_in(sdt_num: Integer; sdt_pw: string): Integer;
procedure mark_up(MK_STDNAME: string; MK_SDTDEPTNUM: string; MK_SBJTNAME: string; MK_PROFNAME: string; MK_ROOM: string; MK_DIV: string; MK_SDTNUM: Integer; MK_SBJTNUM: Integer; MK_SBJTCLASS: Integer; MK_PROFNUM: Integer; MK_GRADE: Integer);
function Gradecheck(sdt_num: Integer): Integer;
function signGradecheck(sdt_num: Integer): Integer;
procedure Signup(sign_STDNAME: string; sign_SDTDEPTNUM: string; sign_SBJTNAME: string; sign_PROFNAME: string; sign_ROOM: string; sign_DIV: string; sign_SDTNUM: Integer; sign_SBJTNUM: Integer; sign_SBJTCLASS: Integer; sign_PROFNUM: Integer; sign_GRADE: Integer);
function total(sbjt_num: Integer; sbjt_class: Integer): Boolean;
end;
implementation
function TServerMethods1Client.EchoString(Value: string): string;
begin
if FEchoStringCommand = nil then
begin
FEchoStringCommand := FDBXConnection.CreateCommand;
FEchoStringCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FEchoStringCommand.Text := 'TServerMethods1.EchoString';
FEchoStringCommand.Prepare;
end;
FEchoStringCommand.Parameters[0].Value.SetWideString(Value);
FEchoStringCommand.ExecuteUpdate;
Result := FEchoStringCommand.Parameters[1].Value.GetWideString;
end;
function TServerMethods1Client.ReverseString(Value: string): string;
begin
if FReverseStringCommand = nil then
begin
FReverseStringCommand := FDBXConnection.CreateCommand;
FReverseStringCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FReverseStringCommand.Text := 'TServerMethods1.ReverseString';
FReverseStringCommand.Prepare;
end;
FReverseStringCommand.Parameters[0].Value.SetWideString(Value);
FReverseStringCommand.ExecuteUpdate;
Result := FReverseStringCommand.Parameters[1].Value.GetWideString;
end;
function TServerMethods1Client.Log_in(sdt_num: Integer; sdt_pw: string): Integer;
begin
if FLog_inCommand = nil then
begin
FLog_inCommand := FDBXConnection.CreateCommand;
FLog_inCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FLog_inCommand.Text := 'TServerMethods1.Log_in';
FLog_inCommand.Prepare;
end;
FLog_inCommand.Parameters[0].Value.SetInt32(sdt_num);
FLog_inCommand.Parameters[1].Value.SetWideString(sdt_pw);
FLog_inCommand.ExecuteUpdate;
Result := FLog_inCommand.Parameters[2].Value.GetInt32;
end;
procedure TServerMethods1Client.mark_up(MK_STDNAME: string; MK_SDTDEPTNUM: string; MK_SBJTNAME: string; MK_PROFNAME: string; MK_ROOM: string; MK_DIV: string; MK_SDTNUM: Integer; MK_SBJTNUM: Integer; MK_SBJTCLASS: Integer; MK_PROFNUM: Integer; MK_GRADE: Integer);
begin
if Fmark_upCommand = nil then
begin
Fmark_upCommand := FDBXConnection.CreateCommand;
Fmark_upCommand.CommandType := TDBXCommandTypes.DSServerMethod;
Fmark_upCommand.Text := 'TServerMethods1.mark_up';
Fmark_upCommand.Prepare;
end;
Fmark_upCommand.Parameters[0].Value.SetWideString(MK_STDNAME);
Fmark_upCommand.Parameters[1].Value.SetWideString(MK_SDTDEPTNUM);
Fmark_upCommand.Parameters[2].Value.SetWideString(MK_SBJTNAME);
Fmark_upCommand.Parameters[3].Value.SetWideString(MK_PROFNAME);
Fmark_upCommand.Parameters[4].Value.SetWideString(MK_ROOM);
Fmark_upCommand.Parameters[5].Value.SetWideString(MK_DIV);
Fmark_upCommand.Parameters[6].Value.SetInt32(MK_SDTNUM);
Fmark_upCommand.Parameters[7].Value.SetInt32(MK_SBJTNUM);
Fmark_upCommand.Parameters[8].Value.SetInt32(MK_SBJTCLASS);
Fmark_upCommand.Parameters[9].Value.SetInt32(MK_PROFNUM);
Fmark_upCommand.Parameters[10].Value.SetInt32(MK_GRADE);
Fmark_upCommand.ExecuteUpdate;
end;
function TServerMethods1Client.Gradecheck(sdt_num: Integer): Integer;
begin
if FGradecheckCommand = nil then
begin
FGradecheckCommand := FDBXConnection.CreateCommand;
FGradecheckCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FGradecheckCommand.Text := 'TServerMethods1.Gradecheck';
FGradecheckCommand.Prepare;
end;
FGradecheckCommand.Parameters[0].Value.SetInt32(sdt_num);
FGradecheckCommand.ExecuteUpdate;
Result := FGradecheckCommand.Parameters[1].Value.GetInt32;
end;
function TServerMethods1Client.signGradecheck(sdt_num: Integer): Integer;
begin
if FsignGradecheckCommand = nil then
begin
FsignGradecheckCommand := FDBXConnection.CreateCommand;
FsignGradecheckCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FsignGradecheckCommand.Text := 'TServerMethods1.signGradecheck';
FsignGradecheckCommand.Prepare;
end;
FsignGradecheckCommand.Parameters[0].Value.SetInt32(sdt_num);
FsignGradecheckCommand.ExecuteUpdate;
Result := FsignGradecheckCommand.Parameters[1].Value.GetInt32;
end;
procedure TServerMethods1Client.Signup(sign_STDNAME: string; sign_SDTDEPTNUM: string; sign_SBJTNAME: string; sign_PROFNAME: string; sign_ROOM: string; sign_DIV: string; sign_SDTNUM: Integer; sign_SBJTNUM: Integer; sign_SBJTCLASS: Integer; sign_PROFNUM: Integer; sign_GRADE: Integer);
begin
if FSignupCommand = nil then
begin
FSignupCommand := FDBXConnection.CreateCommand;
FSignupCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FSignupCommand.Text := 'TServerMethods1.Signup';
FSignupCommand.Prepare;
end;
FSignupCommand.Parameters[0].Value.SetWideString(sign_STDNAME);
FSignupCommand.Parameters[1].Value.SetWideString(sign_SDTDEPTNUM);
FSignupCommand.Parameters[2].Value.SetWideString(sign_SBJTNAME);
FSignupCommand.Parameters[3].Value.SetWideString(sign_PROFNAME);
FSignupCommand.Parameters[4].Value.SetWideString(sign_ROOM);
FSignupCommand.Parameters[5].Value.SetWideString(sign_DIV);
FSignupCommand.Parameters[6].Value.SetInt32(sign_SDTNUM);
FSignupCommand.Parameters[7].Value.SetInt32(sign_SBJTNUM);
FSignupCommand.Parameters[8].Value.SetInt32(sign_SBJTCLASS);
FSignupCommand.Parameters[9].Value.SetInt32(sign_PROFNUM);
FSignupCommand.Parameters[10].Value.SetInt32(sign_GRADE);
FSignupCommand.ExecuteUpdate;
end;
function TServerMethods1Client.total(sbjt_num: Integer; sbjt_class: Integer): Boolean;
begin
if FtotalCommand = nil then
begin
FtotalCommand := FDBXConnection.CreateCommand;
FtotalCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FtotalCommand.Text := 'TServerMethods1.total';
FtotalCommand.Prepare;
end;
FtotalCommand.Parameters[0].Value.SetInt32(sbjt_num);
FtotalCommand.Parameters[1].Value.SetInt32(sbjt_class);
FtotalCommand.ExecuteUpdate;
Result := FtotalCommand.Parameters[2].Value.GetBoolean;
end;
constructor TServerMethods1Client.Create(ADBXConnection: TDBXConnection);
begin
inherited Create(ADBXConnection);
end;
constructor TServerMethods1Client.Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean);
begin
inherited Create(ADBXConnection, AInstanceOwner);
end;
destructor TServerMethods1Client.Destroy;
begin
FEchoStringCommand.DisposeOf;
FReverseStringCommand.DisposeOf;
FLog_inCommand.DisposeOf;
Fmark_upCommand.DisposeOf;
FGradecheckCommand.DisposeOf;
FsignGradecheckCommand.DisposeOf;
FSignupCommand.DisposeOf;
FtotalCommand.DisposeOf;
inherited;
end;
end.
|
program gitrev;
uses
Classes, SysUtils, uGetOpt, getopts, uGitCalls, strutils, dateutils;
const
OptionsLong: array[1..7] of TOption = (
(Name: 'help'; Has_Arg: No_Argument; Flag: nil; Value: 'h'),
(Name: 'path'; Has_Arg: No_Argument; Flag: nil; Value: #0),
(Name: 'format'; Has_Arg: Required_Argument; Flag: nil; Value: 'f'),
(Name: 'echo'; Has_Arg: No_Argument; Flag: nil; Value: 'e'),
(Name: 'delimiter'; Has_Arg: Required_Argument; Flag: nil; Value: 'd'),
(Name: 'insert'; Has_Arg: Required_Argument; Flag: nil; Value: 'i'),
(Name: ''; Has_Arg: 0; Flag: nil; Value: #0)
);
OptionShort = 'h?f:ed:i:';
var
optDescriptFormatString: string = '$branch$ $hash6$ $mod$ $timeutc$';
optInsertDelimiter: string = '{REV}'':''{/REV}';
function Timestamp(dt: TDateTime): string;
begin
DateTimeToString(Result, 'yyyy-mm-dd"T"hh:nn:ss', dt);
end;
function GetDescriptor: string;
begin
Result:= optDescriptFormatString;
Result:= StringReplace(Result, '$root$', GitRootPath, [rfReplaceAll, rfIgnoreCase]);
Result:= StringReplace(Result, '$branch$', GitBranch, [rfReplaceAll, rfIgnoreCase]);
Result:= StringReplace(Result, '$hash$', GitHash, [rfReplaceAll, rfIgnoreCase]);
Result:= StringReplace(Result, '$hash6$', Copy(GitHash, 1, 6), [rfReplaceAll, rfIgnoreCase]);
Result:= StringReplace(Result, '$mod$', IfThen(GitIsModified, '(modified)',''), [rfReplaceAll, rfIgnoreCase]);
Result:= StringReplace(Result, '$svnrev$', GitSvnLatest, [rfReplaceAll, rfIgnoreCase]);
Result:= StringReplace(Result, '$time$', Timestamp(Now), [rfReplaceAll, rfIgnoreCase]);
Result:= StringReplace(Result, '$timeutc$', Timestamp(LocalTimeToUniversal(Now))+'Z', [rfReplaceAll, rfIgnoreCase]);
end;
procedure InsertInto(FName: string);
var
fl: TStringList;
i,s,e: integer;
modified: boolean;
mstart, mend, l: string;
begin
fl:= TStringList.Create;
try
fl.LoadFromFile(FName);
modified:= false;
i:= pos(':', optInsertDelimiter);
if i > 0 then begin
mstart:= Copy(optInsertDelimiter, 1, i-1);
mend:= Copy(optInsertDelimiter, i+1, MaxInt);
end else begin
mstart:= optInsertDelimiter;
mend:= optInsertDelimiter;
end;
for i:= 0 to fl.Count - 1 do begin
l:= fl[i];
s:= Pos(mstart, l);
if s=0 then Continue;
e:= PosEx(mend, l, s + Length(mstart));
if e=0 then Continue;
l:= Copy(l, 1, s-1) + mstart + GetDescriptor + mend + Copy(l, e + Length(mend), MaxInt);
fl[i]:= l;
modified:= true;
end;
if modified then
fl.SaveToFile(FName);
finally
FreeAndNil(fl);
end;
end;
procedure ProcessOption(const opt: string; const OptArg: string);
begin
case opt of
'path': begin
WriteLn(GitRootPath);
end;
'f': begin
optDescriptFormatString:= OptArg;
end;
'e': begin
WriteLn(GetDescriptor);
end;
'd': begin
optInsertDelimiter:= OptArg;
end;
'i': begin
InsertInto(OptArg);
end;
'h',
'?': begin
WriteLn(ExtractFileName(ParamStr(0)),' [commands]');
WriteLn('Commands: (executed in order specified on commandline)');
WriteLn(' --path');
WriteLn(' Output current git repo root path');
WriteLn(' -f|--format "formatstring"');
WriteLn(' Specify format string to use for output');
WriteLn(' -e|--echo ');
WriteLn(' Evaluate current format and output to stdout');
WriteLn(' -d|--delimiter "begin:end" ');
WriteLn(' Specify colon-separated begin and end markers for file insert mode');
WriteLn(' -i|--insert "filename" ');
WriteLn(' Evaluate current format and replace part between delimiters in file');
Halt(0);
end;
else
WriteLn(ErrOutput, 'Unknown option: ', opt);
end;
end;
begin
HandleAllOptions(OptionShort, @OptionsLong[1], @ProcessOption);
end.
|
{ ***************************************************************************
Copyright (c) 2016-2020 Kike Pérez
Unit : Quick.Core.Mvc.Extensions.Entity.Rest
Description : Core MVC Extensions TaskControl
Author : Kike Pérez
Version : 1.0
Created : 12/03/2020
Modified : 09/06/2020
This file is part of QuickCore: https://github.com/exilon/QuickCore
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.Core.Mvc.Extensions.Entity.Rest;
{$i QuickCore.inc}
interface
uses
{$IFDEF DEBUG_ENTITY}
Quick.Debug.Utils,
{$ENDIF}
System.SysUtils,
System.Variants,
System.Rtti,
System.Generics.Collections,
Quick.Core.MVC,
Quick.Core.Entity,
Quick.HttpServer.Types,
Quick.Core.Mvc.Controller,
Quick.Core.Mvc.ActionResult,
Quick.Core.Entity.Request,
Quick.Core.Entity.DAO;
type
TEntityRestMVCServerExtension = class(TMVCServerExtension)
class function UseRestApi<T : TDBContext> : TMVCServer;
end;
[Route('api')]
[Authorize]
TEntityRestController<T : TDBContext> = class(THttpController)
private
fDBContext : TDBContext;
function GetWhereId(aModel: TEntityModel; const aId : string): string;
public
constructor Create(aDBContext : T);
published
[HttpPost('query/select')]
function SelectQuery(const [FromBody]request: TEntitySelectRequest) : IActionResult;
[HttpPost('query/update')]
function UpdateQuery(const [FromBody]request: TEntityUpdateRequest) : IActionResult;
[HttpPost('query/delete')]
function DeleteQuery(const [FromBody]request: TEntityDeleteRequest) : IActionResult;
[HttpGet('{table}/{id}')]
function Get(const table : string; id : string) : IActionResult;
[HttpPost('{table}')]
function Add(const table : string; const [FromBody]value : string) : IActionResult;
[HttpPut('{table}/{id}')]
function Update(const table: string; const id : string; const [FromBody]value: string): IActionResult;
[HttpDelete('{table}/{id}')]
function Delete(const table : string; id : string) : IActionResult;
end;
implementation
{ TEntityRestMVCServerExtension }
class function TEntityRestMVCServerExtension.UseRestApi<T>: TMVCServer;
begin
Result := MVCServer;
if MVCServer.Services.IsRegistered<T>('') then
begin
MVCServer.AddController(TEntityRestController<T>);
end
else raise Exception.Create('DBContext dependency not found. Need to be added before!');
end;
{ TEntityRestController }
constructor TEntityRestController<T>.Create(aDBContext : T);
begin
fDBContext := aDBContext as TDBContext;
end;
function TEntityRestController<T>.GetWhereId(aModel: TEntityModel; const aId : string): string;
begin
if (aModel.PrimaryKey.DataType >= TFieldDataType.dtInteger) and
(aModel.PrimaryKey.DataType <= TFieldDataType.dtFloat) then Result := Format('%s = %s',[aModel.PrimaryKey.Name,aId])
else Result := Format('%s = "%s"',[aModel.PrimaryKey.Name,aId]);
end;
function TEntityRestController<T>.SelectQuery(const request: TEntitySelectRequest): IActionResult;
var
dbset : TDBSet<TEntity>;
linq : IEntityLinqQuery<TEntity>;
reslinq : IEntityResult<TEntity>;
list : TObjectList<TEntity>;
begin
{$IFDEF DEBUG_ENTITY}
TDebugger.Enter(Self,'SelectQuery').TimeIt;
{$ENDIF}
list := nil;
dbset := fDBContext.GetDBSet(request.Table);
//set where clause
linq := dbset.Where(request.WhereClause);
//set order clause
if not request.Order.IsEmpty then
begin
if request.OrderAsc then linq.OrderBy(request.Order)
else linq.OrderByDescending(request.Order);
end;
//select
list := TObjectList<TEntity>.Create(True);
if request.Limit = 1 then list.Add(linq.SelectFirst)
else if request.Limit = -1 then list.Add(linq.SelectLast)
else
begin
linq.SelectTop(request.Limit).ToObjectList(list);
end;
try
Result := Json(list,True);
finally
list.Free;
end;
end;
function TEntityRestController<T>.UpdateQuery(const request: TEntityUpdateRequest): IActionResult;
begin
{$IFDEF DEBUG_ENTITY}
TDebugger.Enter(Self,'UpdateQuery');
{$ENDIF}
end;
function TEntityRestController<T>.DeleteQuery(const request: TEntityDeleteRequest): IActionResult;
begin
{$IFDEF DEBUG_ENTITY}
TDebugger.Enter(Self,'DeleteQuery');
{$ENDIF}
end;
function TEntityRestController<T>.Get(const table: string; id: string): IActionResult;
var
dbset : TDBSet<TEntity>;
entity : TEntity;
begin
{$IFDEF DEBUG_ENTITY}
TDebugger.Enter(Self,'Get').TimeIt;
{$ENDIF}
dbset := fDBContext.GetDBSet(table);
entity := dbset.Where(GetWhereId(dbset.Model,id),[]).SelectFirst;
if entity = nil then HttpContext.RaiseHttpErrorNotFound(nil,'register not found in database');
Result := Json(entity,True);
end;
function TEntityRestController<T>.Add(const table: string; const value: string): IActionResult;
var
dbset : TDBSet<TEntity>;
entity : TEntity;
begin
{$IFDEF DEBUG_ENTITY}
TDebugger.Enter(Self,'Add').TimeIt;
{$ENDIF}
dbset := fDBContext.GetDBSet(table);
entity := dbset.Model.Table.Create;
Self.HttpContext.RequestServices.Serializer.Json.ToObject(entity,value);
if dbset.Add(entity) then Result := Self.StatusCode(THttpStatusCode.Created,'')
else HttpContext.RaiseHttpErrorNotFound(nil,'Cannot add register to database!');
end;
function TEntityRestController<T>.Update(const table: string; const id : string; const value: string): IActionResult;
var
dbset : TDBSet<TEntity>;
entity : TEntity;
begin
{$IFDEF DEBUG_ENTITY}
TDebugger.Enter(Self,'Update').TimeIt;
{$ENDIF}
dbset := fDBContext.GetDBSet(table);
entity := dbset.Model.Table.Create;
Self.HttpContext.RequestServices.Serializer.Json.ToObject(entity,value);
if VarIsEmpty(entity.FieldByName(dbset.Model.PrimaryKey.Name)) then HttpContext.RaiseHttpErrorBadRequest(nil,'not defined Primary Key!');
if dbset.Update(entity) then Result := Ok
else HttpContext.RaiseHttpErrorNotFound(nil,'Cannot update register to database!');
end;
function TEntityRestController<T>.Delete(const table: string; id: string): IActionResult;
var
dbset : TDBSet<TEntity>;
begin
{$IFDEF DEBUG_ENTITY}
TDebugger.Enter(Self,'Delete').TimeIt;
{$ENDIF}
dbset := fDBContext.GetDBSet(table);
if dbset.Where(GetWhereId(dbset.Model,id),[]).Delete then Result := Ok
else HttpContext.RaiseHttpErrorNotFound(nil,'register not found in database');
end;
end.
|
unit MgCanvas;
interface
uses
Windows, Classes, Controls, MgScene, MgBackend;
type
TMgCanvas = class(TCustomControl)
private
FScene: TMgScene;
FBackEnd: TMgBackend;
protected
procedure Paint; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Line(X1, Y1, X2, Y2: Integer);
procedure VerticalLine(X, Y1, Y2: Integer);
procedure HorizontalLine(X1, X2, Y: Integer);
published
property Scene: TMgScene read FScene;
property Align;
property Anchors;
property AutoSize;
property Constraints;
property Cursor;
property DragCursor;
property DragMode;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property OnClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheel;
property OnMouseWheelDown;
property OnMouseWheelUp;
property OnMouseEnter;
property OnMouseLeave;
property OnResize;
property OnStartDrag;
end;
implementation
uses
MgPrimitives, MgBackendGDI;
{ TMgCanvas }
constructor TMgCanvas.Create(AOwner: TComponent);
begin
inherited;
FScene := TMgScene.Create(Self);
FBackEnd := TMgBackendGDI.Create;
end;
destructor TMgCanvas.Destroy;
begin
FBackEnd.Free;
FScene.Free;
inherited;
end;
procedure TMgCanvas.Paint;
begin
inherited;
FBackEnd.RenderScene(FScene, Canvas.Handle);
end;
procedure TMgCanvas.Line(X1, Y1, X2, Y2: Integer);
begin
FScene.AddPrimitive(TMgPrimitiveLine.Create(X1, Y1, X2, Y2));
end;
procedure TMgCanvas.VerticalLine(X, Y1, Y2: Integer);
begin
FScene.AddPrimitive(TMgPrimitiveVerticalLine.Create(X, Y1, Y2));
end;
procedure TMgCanvas.HorizontalLine(X1, X2, Y: Integer);
begin
FScene.AddPrimitive(TMgPrimitiveHorizontalLine.Create(X1, X2, Y));
end;
end.
|
unit Estoque;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxLookAndFeels,
cxLookAndFeelPainters, Vcl.Menus, dxSkinsCore, dxSkinBlack, dxSkinBlue,
dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom,
dxSkinDarkSide, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle,
dxSkinFoggy, dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary,
dxSkinLilian, dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin,
dxSkinMetropolis, dxSkinMetropolisDark, dxSkinMoneyTwins,
dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green,
dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black,
dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinOffice2013DarkGray,
dxSkinOffice2013LightGray, dxSkinOffice2013White, dxSkinPumpkin,
dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus,
dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008,
dxSkinTheAsphaltWorld, dxSkinsDefaultPainters, dxSkinValentine,
dxSkinVS2010, dxSkinWhiteprint, dxSkinXmas2008Blue, cxControls,
cxContainer, cxEdit, Data.DB, cxTextEdit, cxLabel, Vcl.DBCtrls,
Vcl.Grids, Vcl.DBGrids, cxGroupBox, Vcl.StdCtrls, cxButtons, Vcl.ExtCtrls,
cxMaskEdit, cxDropDownEdit;
type
TfrmEstoque = class(TForm)
Panel1: TPanel;
btnGravar: TcxButton;
btnCancelar: TcxButton;
cxGroupBox1: TcxGroupBox;
cxGroupBox2: TcxGroupBox;
cxComboBox1: TcxComboBox;
cxGroupBox3: TcxGroupBox;
cxGroupBox4: TcxGroupBox;
cxTextEdit1: TcxTextEdit;
cxButton2: TcxButton;
DBGrid1: TDBGrid;
DBGrid2: TDBGrid;
cxButton3: TcxButton;
cxButton1: TcxButton;
cxTextEdit2: TcxTextEdit;
cxTextEdit3: TcxTextEdit;
cxGroupBox5: TcxGroupBox;
cxGroupBox6: TcxGroupBox;
dsTblItemMov: TDataSource;
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmEstoque: TfrmEstoque;
implementation
uses
UDM;
{$R *.dfm}
end.
|
unit uFileSystemCreateDirectoryOperation;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,
uFileSourceCreateDirectoryOperation,
uFileSource, uFileSystemFileSource;
type
TFileSystemCreateDirectoryOperation = class(TFileSourceCreateDirectoryOperation)
private
FFileSystemFileSource: IFileSystemFileSource;
public
constructor Create(aTargetFileSource: IFileSource;
aCurrentPath: String;
aDirectoryPath: String); override;
procedure Initialize; override;
procedure MainExecute; override;
procedure Finalize; override;
end;
implementation
uses
uFileSourceOperationUI, uLog, uLng, uGlobs, DCOSUtils, uAdministrator;
constructor TFileSystemCreateDirectoryOperation.Create(
aTargetFileSource: IFileSource;
aCurrentPath: String;
aDirectoryPath: String);
begin
FFileSystemFileSource := aTargetFileSource as IFileSystemFileSource;
inherited Create(aTargetFileSource, aCurrentPath, aDirectoryPath);
end;
procedure TFileSystemCreateDirectoryOperation.Initialize;
begin
end;
procedure TFileSystemCreateDirectoryOperation.MainExecute;
begin
if FileGetAttrUAC(AbsolutePath) <> faInvalidAttributes then
begin
AskQuestion(Format(rsMsgErrDirExists, [AbsolutePath]), '', [fsourOk], fsourOk, fsourOk);
end
else if ForceDirectoriesUAC(AbsolutePath) = False then
begin
if (log_dir_op in gLogOptions) and (log_errors in gLogOptions) then
logWrite(Thread, Format(rsMsgLogError+rsMsgLogMkDir, [AbsolutePath]), lmtError);
AskQuestion(Format(rsMsgErrForceDir, [AbsolutePath]), '', [fsourOk], fsourOk, fsourOk);
end
else
begin
if (log_dir_op in gLogOptions) and (log_success in gLogOptions) then
logWrite(Thread, Format(rsMsgLogSuccess+rsMsgLogMkDir,[AbsolutePath]), lmtSuccess);
end;
end;
procedure TFileSystemCreateDirectoryOperation.Finalize;
begin
end;
end.
|
unit ksVirtualListViewTest;
interface
uses
DUnitX.TestFramework,
ksTypes,
ksCommon,
ksVirtualListView;
type
[TestFixture]
TksVirtualListViewTest = class(TObject)
private
FListView: TksVirtualListView;
FEventFired: Boolean;
procedure Add100Items;
public
[Setup]
procedure Setup;
[TearDown]
procedure TearDown;
// tests...
[Test] procedure TestGetCheckedCount;
[Test] procedure Test1000Items;
[Test] procedure TestClearItems;
[Test] procedure TestScrollToLastItem;
[Test] procedure TestAccessories;
[Test] procedure TestGetItemFromPos;
[Test] procedure TestTotalItemHeight;
[Test] procedure TestTopItem;
[Test] procedure TestItemHorzAlignments;
[Test] procedure TestItemVertAlignments;
[Test] procedure TestTextWidth;
[Test] procedure TestTextHeight;
[Test] procedure TestTextHeightMultiLine;
end;
implementation
uses SysUtils, System.UITypes, System.UIConsts, System.Classes;
//----------------------------------------------------------------------------------------------------
procedure TksVirtualListViewTest.Setup;
begin
FListView := TksVirtualListView.Create(nil);
FEventFired := False;
end;
procedure TksVirtualListViewTest.TearDown;
begin
FListView.Free;
end;
//----------------------------------------------------------------------------------------------------
procedure TksVirtualListViewTest.Add100Items;
var
ICount: integer;
begin
// arrange
// act
FListView.BeginUpdate;
try
for ICount := 1 to 100 do
FListView.Items.Add('Item '+IntToStr(ICount), 'a sub title', 'the detail', atNone);
finally
FListView.EndUpdate;
end;
end;
procedure TksVirtualListViewTest.TestGetCheckedCount;
var
ICount: integer;
begin
FListView.CheckBoxes.Visible := True;
FListView.CheckBoxes.Mode := TksSelectionType.ksMultiSelect;
Add100Items;
for ICount := 1 to 100 do
begin
if ICount mod 2 = 0 then
FListView.Items[ICount-1].Checked := True;
end;
Assert.AreEqual(50, FListView.Items.CheckedCount);
end;
procedure TksVirtualListViewTest.TestGetItemFromPos;
var
AItem: TksVListItem;
begin
Add100Items;
AItem := FListView.Items.ItemAtPos(10, 600);
Assert.AreEqual(13, AItem.Index);
end;
procedure TksVirtualListViewTest.TestItemHorzAlignments;
var
ICount: TAlignment;
begin
for ICount := Low(TAlignment) to High(TAlignment) do
begin
with FListView.Items.Add('', '', '') do
AddText(30, 0, 'TEST').HorzAlign := ICount;
end;
Assert.AreEqual(3, FListView.Items.Count);
end;
procedure TksVirtualListViewTest.TestItemVertAlignments;
var
ICount: TVerticalAlignment;
begin
for ICount := Low(TVerticalAlignment) to High(TVerticalAlignment) do
begin
with FListView.Items.Add('', '', '') do
AddText(30, 0, 'TEST').VertAlign := ICount;
end;
Assert.AreEqual(3, FListView.Items.Count);
end;
procedure TksVirtualListViewTest.Test1000Items;
var
ICount: integer;
begin
// arrange
// act
FListView.BeginUpdate;
try
for ICount := 1 to 1000 do
FListView.Items.Add('Item '+IntToStr(ICount), 'a sub title', 'the detail', atNone);
finally
FListView.EndUpdate;
end;
// assert
Assert.AreEqual(1000, FListView.Items.Count);
end;
procedure TksVirtualListViewTest.TestAccessories;
var
ICount: TksAccessoryType;
begin
FListView.BeginUpdate;
for ICount := Low(TksAccessoryType) to High(TksAccessoryType) do
FListView.Items.Add('Item', '', '', ICount);
FListView.EndUpdate;
end;
procedure TksVirtualListViewTest.TestClearItems;
begin
// arrange
Add100Items;
// act
FListView.ClearItems;
// assert
Assert.AreEqual(True, FListView.IsEmpty);
end;
procedure TksVirtualListViewTest.TestScrollToLastItem;
var
AResult: Extended;
begin
// arrange
Add100Items;
// act
FListView.ScrollToBottom(False);
// assert
AResult := FListView.ScrollPos;
Assert.AreEqual(4350.0, AResult);
end;
procedure TksVirtualListViewTest.TestTextHeight;
var
AHeight: string;
begin
FListView.Items.Add('This is a test', '', '');
AHeight := FormatFloat('0.00', FListView.Items[0].Title.Height);
Assert.AreEqual('18.29', AHeight);
end;
procedure TksVirtualListViewTest.TestTextHeightMultiLine;
var
AHeight: string;
begin
FListView.Items.Add('This is a test'+#13+'This is the second line...'+#13+'And the third :-)', '', '');
AHeight := FormatFloat('0.00', FListView.Items[0].Title.Height);
Assert.AreEqual('52.87', AHeight);
end;
procedure TksVirtualListViewTest.TestTextWidth;
var
AWidth: string;
begin
FListView.Items.Add('This is a test', '', '');
AWidth := FormatFloat('0.00', FListView.Items[0].Title.Width);
Assert.AreEqual('70.92', AWidth);
end;
procedure TksVirtualListViewTest.TestTopItem;
begin
Add100Items;
Assert.AreEqual(0, FListView.TopItem.Index);
end;
procedure TksVirtualListViewTest.TestTotalItemHeight;
begin
Add100Items;
Assert.AreEqual(4400, Integer(Round(FListView.TotalItemHeight)));
end;
initialization
TDUnitX.RegisterTestFixture(TksVirtualListViewTest);
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
/// <summary>Classes and Helper utililities for dealing with WinRT interfaces and strings</summary>
unit System.Win.WinRT;
interface
uses
Winapi.WinRT, System.RTTI, System.SysUtils, System.TypInfo;
type
/// <summary>Exception base class for all WinRT exceptions </summary>
EWinRTException = class(Exception);
/// <summary>Base Delphi object needed for Windows Runtime classes. Implements IInspectable interface</summary>
TInspectableObject = class(TInterfacedObject, IInspectable)
protected
FIIDS: array of TGUID;
public
/// <summary>Gets the interfaces that are implemented by the current Windows Runtime class</summary>
function GetIids(out iidCount: Cardinal; out iids: PGUID): HRESULT; stdcall;
/// <summary>Gets the fully qualified name of the current Windows Runtime object</summary>
function GetRuntimeClassName(out className: HSTRING): HRESULT; stdcall;
/// <summary>Gets the trust level of the current Windows Runtime object</summary>
function GetTrustLevel(out trust: TrustLevel): HRESULT; stdcall;
end;
/// <summary>Helper needed to automate life cycle of HSTRING type and conversions from/to string</summary>
TWindowsString = record
strict private
type
TWindowsStringNexus = class(TInterfacedObject)
private
FString: HSTRING;
public
constructor Create(AString: HSTRING);
destructor Destroy; override;
end;
PWindowsString = ^TWindowsString;
private
FNexus: IInterface;
FHandle: HSTRING;
FValid: Boolean;
public
constructor Create(const S: string); overload;
/// <summary>Checks that the internal HSTRING was created successfully</summary>
property Valid: Boolean read FValid;
class operator Implicit(const S: TWindowsString): HSTRING; inline;
class operator Explicit(const S: string): TWindowsString;
/// <summary>Gets the string representation of the given HSTRING</summary>
class function HStringToString(const hs: HSTRING): string; static;
end;
/// <summary>Record helper for HSTRING</summary>
THStringHelper = record helper for HSTRING
/// <summary>Gets the string representation of the given HSTRING</summary>
function ToString: string; inline;
end;
/// <summary>Custom atribute to store the Class Name of an imported WinRT class</summary>
WinRTClassNameAttribute = class(TCustomAttribute)
private
FSignature: string;
public
constructor Create(const S: string);
/// <summary>Gets the signature of the Class</summary>
property Signature: string read FSignature;
end;
{$M+}
/// <summary>Helper used to import a WinRT class</summary>
TWinRTImportHelper = class
private
class var FContext: TRttiContext;
class constructor Create;
class destructor Destroy;
public
/// <summary>Gets the UIID of a given interface</summary>
class function GetUIID<T: IInterface>: TGUID; static;
/// <summary>Gets the WinRT ActivationFactory related to the given TypeInfo. Also gets it's Class Name</summary>
class function GetFactoryOrStatics(ATypeInfo: PTypeInfo; var AClassName: HSTRING): IInspectable;
/// <summary>Gets the WinRT ActivateInstance related to the given TypeInfo. Also gets it's Class Name</summary>
class function CreateInstance(ATypeInfo: PTypeInfo; var AClassName: HSTRING): IInspectable;
/// <summary>Gets the Class Name of a Class Type</summary>
class function GetClassName(const ClassType: TRttiType): HSTRING;
/// <summary>Cached RTTI Context to share among all WinRTImport</summary>
class property Context: TRttiContext read FContext;
end;
/// <summary>Base class of all WinRT Imports</summary>
TWinRTImport = class
protected
/// <summary>Inline function to use ImporHelper sibling</summary>
class function GetFactoryOrStatics(ATypeInfo: PTypeInfo; var AClassName: HSTRING): IInspectable; inline;
/// <summary>Inline function to use ImporHelper sibling</summary>
class function CreateInstance(ATypeInfo: PTypeInfo; var AClassName: HSTRING): IInspectable; inline;
end;
TWinRTGenericImportF<F: IInspectable> = class(TWinRTImport)
private
class var FRTClassName: HSTRING;
class var FFactory: F;
class function GetFactory: F; static;
class destructor Destroy;
public
class property Factory: F read GetFactory;
class property RTClassName: HSTRING read FRTClassName;
end;
TWinRTGenericImportS<S: IInspectable> = class(TWinRTImport)
private
class var FRTClassName: HSTRING;
class var FStatics: S;
class function GetStatics: S; static;
class destructor Destroy;
public
class property RTClassName: HSTRING read FRTClassName;
class property Statics: S read GetStatics;
end;
TWinRTGenericImportI<I: IInspectable> = class(TWinRTImport)
private
class var FRTClassName: HSTRING;
class destructor Destroy;
public
class function Create: I; static;
class property RTClassName: HSTRING read FRTClassName;
end;
TWinRTGenericImportF2<F1, F2: IInspectable> = class(TWinRTGenericImportF<F1>)
private
class var FFactory2: F2;
class function GetFactory2: F2; static;
public
class property Factory2: F2 read GetFactory2;
end;
TWinRTGenericImportF2S<F1, F2, S: IInspectable> = class(TWinRTGenericImportF2<F1, F2>)
private
class var FStatics: S;
class function GetStatics: S; static;
public
class property Statics: S read GetStatics;
end;
TWinRTGenericImportFS<F, S: IInspectable> = class(TWinRTGenericImportF<F>)
private
class var FStatics: S;
class function GetStatics: S; static;
public
class property Statics: S read GetStatics;
end;
TWinRTGenericImportFI<F: IInspectable; I: IInspectable> = class(TWinRTGenericImportF<F>)
public
class function Create: I; static;
end;
TWinRTGenericImportS2<S1, S2: IInspectable> = class(TWinRTGenericImportS<S1>)
private
class var FStatics2: S2;
class function GetStatics2: S2; static;
public
class property Statics2: S2 read GetStatics2;
end;
TWinRTGenericImportSI<S: IInspectable; I: IInspectable> = class(TWinRTGenericImportS<S>)
public
class function Create: I; static;
end;
TWinRTGenericImportF2I<F1, F2, I: IInspectable> = class(TWinRTGenericImportF2<F1, F2>)
public
class function Create: I; static;
end;
TWinRTGenericImportFS2<F, S1, S2: IInspectable> = class(TWinRTGenericImportFS<F, S1>)
private
class var FStatics2: S2;
class function GetStatics2: S2; static;
public
class property Statics2: S2 read GetStatics2;
end;
TWinRTGenericImportFSI<F, S, I: IInspectable> = class(TWinRTGenericImportFS<F, S>)
public
class function Create: I; static;
end;
TWinRTGenericImportS2I<S1, S2, I: IInspectable> = class(TWinRTGenericImportS2<S1, S2>)
public
class function Create: I; static;
end;
TWinRTGenericImportS3<S1, S2, S3: IInspectable> = class(TWinRTGenericImportS2<S1, S2>)
private
class var FStatics3: S3;
class function GetStatics3: S3; static;
public
class property Statics3: S3 read GetStatics3;
end;
TWinRTGenericImportS3I<S1, S2, S3, I: IInspectable> = class(TWinRTGenericImportS3<S1, S2, S3>)
public
class function Create: I; static;
end;
TWinRTGenericImportS4<S1, S2, S3, S4: IInspectable> = class(TWinRTGenericImportS3<S1, S2, S3>)
private
class var FStatics4: S4;
class function GetStatics4: S4; static;
public
class property Statics4: S4 read GetStatics4;
end;
TWinRTGenericImportS5<S1, S2, S3, S4, S5: IInspectable> = class(TWinRTGenericImportS4<S1, S2, S3, S4>)
private
class var FStatics5: S5;
class function GetStatics5: S5; static;
public
class property Statics5: S5 read GetStatics5;
end;
TWinRTGenericImportS6<S1, S2, S3, S4, S5, S6: IInspectable> = class(TWinRTGenericImportS5<S1, S2, S3, S4, S5>)
private
class var FStatics6: S6;
class function GetStatics6: S6; static;
public
class property Statics6: S6 read GetStatics6;
end;
TWinRTGenericImportS3O<S1, S2, S3: IInspectable; O: IUnknown> = class(TWinRTGenericImportS3<S1, S2, S3>)
private
class var FInterop: O;
class function GetInterop: O; static;
public
class property Interop: O read GetInterop;
end;
TWinRTGenericImportSO<S: IInspectable; O: IUnknown> = class(TWinRTGenericImportS<S>)
private
class var FInterop: O;
class function GetInterop: O; static;
public
class property Interop: O read GetInterop;
end;
TWinRTGenericImportS2O<S1, S2: IInspectable; O: IUnknown> = class(TWinRTGenericImportS2<S1, S2>)
private
class var FInterop: O;
class function GetInterop: O; static;
public
class property Interop: O read GetInterop;
end;
{$M-}
var
RoInitType: RO_INIT_TYPE = RO_INIT_MULTITHREADED;
implementation
uses
System.RTLConsts;
var
SaveInitProc: Pointer;
InitWinRTCalled: Boolean = False;
NeedToUninitialize: Boolean = False;
function Succeeded(Res: HRESULT): Boolean;
begin
Result := Res and $80000000 = 0;
end;
procedure InitWinRT;
begin
if InitWinRTCalled then
Exit;
if SaveInitProc <> nil then
TProcedure(SaveInitProc);
if TOSVersion.Check(6, 2) then
NeedToUninitialize := Succeeded(RoInitialize(RoInitType));
InitWinRTCalled := True;
end;
{ TInspectableObject }
function TInspectableObject.GetIids(out iidCount: Cardinal;
out iids: PGUID): HRESULT;
var
Cxt: TRttiContext;
Typ: TRttiType;
IntfTable: PInterfaceTable;
begin
if Length(FIIDS) = 0 then
begin
Cxt := TRttiContext.Create;
try
Typ := Cxt.GetType(Self.ClassType);
IntfTable := Typ.GetInterfaceTable;
SetLength(FIIDS, IntfTable^.EntryCount - 2);
Move(IntfTable^.Entries[0], FIIDS[0], IntfTable^.EntryCount);
finally
Cxt.Free;
end;
end;
iidCount := Length(FIIDS);
if Length(FIIDS) > 0 then
iids := @FIIDS[0]
else
iids := nil;
Result := S_OK;
end;
function TInspectableObject.GetRuntimeClassName(out className: HSTRING): HRESULT;
var
Str: string;
begin
Str := Self.className;
Result := WindowsCreateString(PChar(Str), Length(Str), className);
end;
function TInspectableObject.GetTrustLevel(out trust: TrustLevel): HRESULT;
begin
trust := TrustLevel.BaseTrust;
Result := S_OK;
end;
{ TWindowsString.TWindowsStringNexus }
constructor TWindowsString.TWindowsStringNexus.Create(AString: HSTRING);
begin
inherited Create;
FString := AString;
end;
destructor TWindowsString.TWindowsStringNexus.Destroy;
begin
WindowsDeleteString(FString);
inherited Destroy;
end;
{ TWindowsString }
constructor TWindowsString.Create(const S: string);
begin
FValid := Succeeded(WindowsCreateString(PChar(S), System.Length(S), FHandle));
FNexus := TWindowsStringNexus.Create(FHandle);
end;
class operator TWindowsString.Explicit(const S: string): TWindowsString;
begin
Result := TWindowsString.Create(S);
end;
class operator TWindowsString.Implicit(const S: TWindowsString): HSTRING;
begin
Result := S.FHandle;
end;
class function TWindowsString.HStringToString(const hs: HSTRING): string;
begin
Result := WindowsGetStringRawBuffer(hs, nil);
end;
{ WinRTClassNameAttribute }
constructor WinRTClassNameAttribute.Create(const S: string);
begin
FSignature := S;
end;
{ TWinRTImportHelper }
class constructor TWinRTImportHelper.Create;
begin
FContext := TRttiContext.Create;
end;
class destructor TWinRTImportHelper.Destroy;
begin
FContext.Free;
end;
class function TWinRTImportHelper.CreateInstance(ATypeInfo: PTypeInfo; var AClassName: HSTRING): IInspectable;
var
LType: TRttiType;
LTypeData: PTypeData;
LCreated: IInspectable;
LGUID: TGUID;
begin
LType := TWinRTImportHelper.Context.GetType(ATypeInfo);
LTypeData := GetTypeData(ATypeInfo);
if LType = nil then
raise EWinRTException.CreateFmt(SWinRTNoRTTI, [TWindowsString.HStringToString(AClassName)]);
LGUID := LTypeData^.Guid;
if AClassName <= 0 then
AClassName := TWinRTImportHelper.GetClassName(LType);
if not Succeeded(RoActivateInstance(AClassName, LCreated)) then
raise EWinRTException.CreateFmt(SWinRTInstanceError, [TWindowsString.HStringToString(AClassName)]);
if LCreated.QueryInterface(LGUID, Result) <> 0 then
raise EWinRTException.CreateFmt(SWinRTICreatedError, [TWindowsString.HStringToString(AClassName)]);
end;
class function TWinRTImportHelper.GetFactoryOrStatics(ATypeInfo: PTypeInfo; var AClassName: HSTRING): IInspectable;
var
LType: TRttiType;
LTypeData: PTypeData;
LCreated: IInspectable;
LGUID: TGUID;
begin
LType := TWinRTImportHelper.Context.GetType(ATypeInfo);
LTypeData := GetTypeData(ATypeInfo);
if LType = nil then
raise EWinRTException.CreateFmt(SWinRTNoRTTI, [TWindowsString.HStringToString(AClassName)]);
LGUID := LTypeData^.Guid;
if AClassName <= 0 then
AClassName := TWinRTImportHelper.GetClassName(LType);
if not Succeeded(RoGetActivationFactory(AClassName, LGUID, LCreated)) then
raise EWinRTException.CreateFmt(SWinRTFactoryError, [TWindowsString.HStringToString(AClassName)]);
if LCreated.QueryInterface(LGUID, Result) <> 0 then
raise EWinRTException.CreateFmt(SWinRTWrongFactoryError, [TWindowsString.HStringToString(AClassName)]);
end;
class function TWinRTImportHelper.GetUIID<T>: TGUID;
begin
Result := GetTypeData(TypeInfo(T))^.Guid;
end;
class function TWinRTImportHelper.GetClassName(const ClassType: TRttiType): HSTRING;
var
Attrs: TArray<TCustomAttribute>;
Sig: WinRTClassNameAttribute;
LStr: string;
begin
Attrs := ClassType.GetAttributes;
if Length(Attrs) > 0 then
begin
Sig := WinRTClassNameAttribute(Attrs[0]);
LStr := Sig.Signature;
end
else
LStr := '';
if not Succeeded(WindowsCreateString(PWideChar(LStr), Length(LStr), Result)) then
raise EWinRTException.CreateFmt(SWinRTHStringError, [LStr]);
end;
{ TWinRTImport }
class function TWinRTImport.CreateInstance(ATypeInfo: PTypeInfo; var AClassName: HSTRING): IInspectable;
begin
Result := TWinRTImportHelper.CreateInstance(ATypeInfo, AClassName);
end;
class function TWinRTImport.GetFactoryOrStatics(ATypeInfo: PTypeInfo; var AClassName: HSTRING): IInspectable;
begin
Result := TWinRTImportHelper.GetFactoryOrStatics(ATypeInfo, AClassName);
end;
{ TWinRTGenericImportFI<F,I> }
class function TWinRTGenericImportFI<F, I>.Create: I;
begin
Result := I(CreateInstance(TypeInfo(I), FRTClassName));
end;
{ TWinRTGenericImportF<F> }
class destructor TWinRTGenericImportF<F>.Destroy;
begin
if TOSVersion.Check(6, 2) then
WindowsDeleteString(FRTClassName);
end;
class function TWinRTGenericImportF<F>.GetFactory: F;
begin
if FFactory = nil then
FFactory := F(GetFactoryOrStatics(TypeInfo(F), FRTClassName));
Result := FFactory;
end;
{ TWinRTGenericImportI<I> }
class function TWinRTGenericImportI<I>.Create: I;
begin
Result := I(CreateInstance(TypeInfo(I), FRTClassName));
end;
{ TWinRTGenericImportS<T> }
class destructor TWinRTGenericImportS<S>.Destroy;
begin
if TOSVersion.Check(6, 2) then
WindowsDeleteString(FRTClassName);
end;
class function TWinRTGenericImportS<S>.GetStatics: S;
begin
if FStatics = nil then
FStatics := S(GetFactoryOrStatics(TypeInfo(S), FRTClassName));
Result := FStatics;
end;
class destructor TWinRTGenericImportI<I>.Destroy;
begin
if TOSVersion.Check(6, 2) then
WindowsDeleteString(FRTClassName);
end;
{ TWinRTGenericImportFS<F, S> }
class function TWinRTGenericImportFS<F, S>.GetStatics: S;
begin
if FStatics = nil then
FStatics := S(GetFactoryOrStatics(TypeInfo(S), FRTClassName));
Result := FStatics;
end;
{ TWinRTGenericImportSI<S, I> }
class function TWinRTGenericImportSI<S, I>.Create: I;
begin
Result := I(CreateInstance(TypeInfo(I), FRTClassName));
end;
{ TWinRTGenericImportS2<S1, S2> }
class function TWinRTGenericImportS2<S1, S2>.GetStatics2: S2;
begin
if FStatics2 = nil then
FStatics2 := S2(GetFactoryOrStatics(TypeInfo(S2), FRTClassName));
Result := FStatics2;
end;
{ TWinRTGenericImportS3<S1, S2, S3> }
class function TWinRTGenericImportS3<S1, S2, S3>.GetStatics3: S3;
begin
if FStatics3 = nil then
FStatics3 := S3(GetFactoryOrStatics(TypeInfo(S3), FRTClassName));
Result := FStatics3;
end;
{ TWinRTGenericImportFSI<F, S, I> }
class function TWinRTGenericImportFSI<F, S, I>.Create: I;
begin
Result := I(CreateInstance(TypeInfo(I), FRTClassName));
end;
{ TWinRTGenericImportFS2<F, S1, S2> }
class function TWinRTGenericImportFS2<F, S1, S2>.GetStatics2: S2;
begin
if FStatics2 = nil then
FStatics2 := S2(GetFactoryOrStatics(TypeInfo(S2), FRTClassName));
Result := FStatics2;
end;
{ TWinRTGenericImportF2<F1, F2> }
class function TWinRTGenericImportF2<F1, F2>.GetFactory2: F2;
begin
if FFactory2 = nil then
FFactory2 := F2(GetFactoryOrStatics(TypeInfo(F2), FRTClassName));
Result := FFactory2;
end;
{ TWinRTGenericImportF2I<F1, F2, I> }
class function TWinRTGenericImportF2I<F1, F2, I>.Create: I;
begin
Result := I(CreateInstance(TypeInfo(I), FRTClassName));
end;
{ TWinRTGenericImportS2I<S1, S2, I> }
class function TWinRTGenericImportS2I<S1, S2, I>.Create: I;
begin
Result := I(CreateInstance(TypeInfo(I), FRTClassName));
end;
{ TWinRTGenericImportSO<S, O> }
class function TWinRTGenericImportSO<S, O>.GetInterop: O;
begin
if FInterop = nil then
if Statics.QueryInterface(TWinRTImportHelper.GetUIID<O>, FInterop) <> 0 then
raise EWinRTException.Create(SWinRTInteropError);
Result := FInterop;
end;
{ TWinRTGenericImportS2O<S1, S2, O> }
class function TWinRTGenericImportS2O<S1, S2, O>.GetInterop: O;
begin
if FInterop = nil then
if Statics.QueryInterface(TWinRTImportHelper.GetUIID<O>, FInterop) <> 0 then
raise EWinRTException.Create(SWinRTInteropError);
Result := FInterop;
end;
{ THStringHelper }
function THStringHelper.ToString: string;
begin
Result := TWindowsString.HStringToString(Self);
end;
{ TWinRTGenericImportS3I<S1, S2, S3, I> }
class function TWinRTGenericImportS3I<S1, S2, S3, I>.Create: I;
begin
Result := I(CreateInstance(TypeInfo(I), FRTClassName));
end;
{ TWinRTGenericImportS4<S1, S2, S3, S4> }
class function TWinRTGenericImportS4<S1, S2, S3, S4>.GetStatics4: S4;
begin
if FStatics4 = nil then
FStatics4 := S4(GetFactoryOrStatics(TypeInfo(S4), FRTClassName));
Result := FStatics4;
end;
{ TWinRTGenericImportS3O<S1, S2, S3, O> }
class function TWinRTGenericImportS3O<S1, S2, S3, O>.GetInterop: O;
begin
if FInterop = nil then
if Statics.QueryInterface(TWinRTImportHelper.GetUIID<O>, FInterop) <> 0 then
raise EWinRTException.Create(SWinRTInteropError);
Result := FInterop;
end;
{ TWinRTGenericImportS5<S1, S2, S3, S4, S5> }
class function TWinRTGenericImportS5<S1, S2, S3, S4, S5>.GetStatics5: S5;
begin
if FStatics5 = nil then
FStatics5 := S5(GetFactoryOrStatics(TypeInfo(S5), FRTClassName));
Result := FStatics5;
end;
{ TWinRTGenericImportS6<S1, S2, S3, S4, S5, S6> }
class function TWinRTGenericImportS6<S1, S2, S3, S4, S5, S6>.GetStatics6: S6;
begin
if FStatics6 = nil then
FStatics6 := S6(GetFactoryOrStatics(TypeInfo(S6), FRTClassName));
Result := FStatics6;
end;
{ TWinRTGenericImportF2S<F1, F2, S> }
class function TWinRTGenericImportF2S<F1, F2, S>.GetStatics: S;
begin
if FStatics = nil then
FStatics := S(GetFactoryOrStatics(TypeInfo(S), FRTClassName));
Result := FStatics;
end;
initialization
if not IsLibrary then
begin
SaveInitProc := InitProc;
InitProc := @InitWinRT;
end;
finalization
if NeedToUninitialize and TOSVersion.Check(6, 2) then
RoUninitialize;
end.
|
unit Winapi.Svc;
{$MINENUMSIZE 4}
interface
uses
Winapi.WinNt;
const
// 88
SERVICE_NO_CHANGE = Cardinal(-1);
// 138
SERVICE_ACCEPT_STOP = $00000001;
SERVICE_ACCEPT_PAUSE_CONTINUE = $00000002;
SERVICE_ACCEPT_SHUTDOWN = $00000004;
SERVICE_ACCEPT_PARAMCHANGE = $00000008;
SERVICE_ACCEPT_NETBINDCHANGE = $00000010;
SERVICE_ACCEPT_HARDWAREPROFILECHANGE = $00000020;
SERVICE_ACCEPT_POWEREVENT = $00000040;
SERVICE_ACCEPT_SESSIONCHANGE = $00000080;
SERVICE_ACCEPT_PRESHUTDOWN = $00000100;
SERVICE_ACCEPT_TIMECHANGE = $00000200;
SERVICE_ACCEPT_TRIGGEREVENT = $00000400;
SERVICE_ACCEPT_USER_LOGOFF = $00000800;
SERVICE_ACCEPT_LOWRESOURCES = $00002000;
SERVICE_ACCEPT_SYSTEMLOWRESOURCES = $00004000;
// 157
SC_MANAGER_CONNECT = $0001;
SC_MANAGER_CREATE_SERVICE = $0002;
SC_MANAGER_ENUMERATE_SERVICE = $0004;
SC_MANAGER_LOCK = $0008;
SC_MANAGER_QUERY_LOCK_STATUS = $0010;
SC_MANAGER_MODIFY_BOOT_CONFIG = $0020;
SC_MANAGER_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED or $3F;
ScmAccessMapping: array [0..5] of TFlagName = (
(Value: SC_MANAGER_CONNECT; Name: 'Connect'),
(Value: SC_MANAGER_CREATE_SERVICE; Name: 'Create service'),
(Value: SC_MANAGER_ENUMERATE_SERVICE; Name: 'Enumerate services'),
(Value: SC_MANAGER_LOCK; Name: 'Lock'),
(Value: SC_MANAGER_QUERY_LOCK_STATUS; Name: 'Query lock status'),
(Value: SC_MANAGER_MODIFY_BOOT_CONFIG; Name: 'Modify boot config')
);
ScmAccessType: TAccessMaskType = (
TypeName: 'SCM';
FullAccess: SC_MANAGER_ALL_ACCESS;
Count: Length(ScmAccessMapping);
Mapping: PFlagNameRefs(@ScmAccessMapping);
);
// 177
SERVICE_QUERY_CONFIG = $0001;
SERVICE_CHANGE_CONFIG = $0002;
SERVICE_QUERY_STATUS = $0004;
SERVICE_ENUMERATE_DEPENDENTS = $0008;
SERVICE_START = $0010;
SERVICE_STOP = $0020;
SERVICE_PAUSE_CONTINUE = $0040;
SERVICE_INTERROGATE = $0080;
SERVICE_USER_DEFINED_CONTROL = $0100;
SERVICE_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED or $1FF;
ServiceAccessMapping: array [0..8] of TFlagName = (
(Value: SERVICE_QUERY_CONFIG; Name: 'Query config'),
(Value: SERVICE_CHANGE_CONFIG; Name: 'Change config'),
(Value: SERVICE_QUERY_STATUS; Name: 'Query status'),
(Value: SERVICE_ENUMERATE_DEPENDENTS; Name: 'Enumerate dependents'),
(Value: SERVICE_START; Name: 'Start'),
(Value: SERVICE_STOP; Name: 'Stop'),
(Value: SERVICE_PAUSE_CONTINUE; Name: 'Pause/continue'),
(Value: SERVICE_INTERROGATE; Name: 'Interrogate'),
(Value: SERVICE_USER_DEFINED_CONTROL; Name: 'User-defined control')
);
ServiceAccessType: TAccessMaskType = (
TypeName: 'service';
FullAccess: SERVICE_ALL_ACCESS;
Count: Length(ServiceAccessMapping);
Mapping: PFlagNameRefs(@ServiceAccessMapping);
);
// WinNt.21364
SERVICE_WIN32_OWN_PROCESS = $00000010;
SERVICE_WIN32_SHARE_PROCESS = $00000020;
type
TScmHandle = NativeUInt;
TServiceStatusHandle = NativeUInt;
TScLock = NativeUInt;
// WinNt.21392
TServiceStartType = (
ServiceBootStart = 0,
ServiceSystemStart = 1,
ServiceAutoStart = 2,
ServiceDemandStart = 3,
ServiceDisabled = 4
);
// WinNt.21401
TServiceErrorControl = (
ServiceErrorIgnore = 0,
ServiceErrorNormal = 1,
ServiceErrorSevere = 2,
ServiceErrorCritical = 3
);
// 101
TServiceControl = (
ServiceControlReserved = 0,
ServiceControlStop = 1,
ServiceControlPause = 2,
ServiceControlContinue = 3,
ServiceControlInterrogate = 4,
ServiceControlShutdown = 5,
ServiceControlParamChange = 6,
ServiceControlNetbindAdd = 7,
ServiceControlNetbindRemove = 8,
ServiceControlNetbindEnable = 9,
ServiceControlNetbindDisable = 10,
ServiceControlDeviceEvent = 11,
ServiceControlHardwareProfileChange = 12,
ServiceControlPowerEvent = 13,
ServiceControlSessionChange = 14,
ServiceControlPreshutdown = 15,
ServiceControlTimeChange = 16,
ServiceControlUserLogoff = 17
);
// 127
TServiceState = (
ServiceStopped = 1,
ServiceStartPending = 2,
ServiceStopPending = 3,
ServiceRunning = 4,
ServiceContinuePending = 5,
ServicePausePending = 6,
ServicePaused = 7
);
// 206
TServiceConfigLevel = (
ServiceConfigReserved = 0,
ServiceConfigDescription = 1, // q, s: TServiceDescription
ServiceConfigFailureActions = 2, // q, s: TServiceFailureActions
ServiceConfigDelayedAutoStartInfo = 3, // q, s: LongBool
ServiceConfigFailureActionsFlag = 4, // q, s: LongBool
ServiceConfigServiceSidInfo = 5, // q, s: TServiceSidType
ServiceConfigRequiredPrivilegesInfo = 6, // q, s: TServiceRequiredPrivilegesInfo
ServiceConfigPreshutdownInfo = 7, // q, s: Cardinal (timeout in ms)
ServiceConfigTriggerInfo = 8, // q, s:
ServiceConfigPreferredNode = 9, // q, s:
ServiceConfigReserved1 = 10,
ServiceConfigReserved2 = 11,
ServiceConfigLaunchProtected = 12 // q, s: TServiceLaunchProtected
);
// 306
TServiceContolLevel = (
ServiceContolStatusReasonInfo = 1 // TServiceControlStatusReasonParamsW
);
// 311
TServiceSidType = (
ServiceSidTypeNone = 0,
ServiceSidTypeUnrestricted = 1,
ServiceSidTypeRestricted = 3
);
// 354, Win 8.1+
TServiceLaunchProtected = (
ServiceLaunchProtectedNone = 0,
ServiceLaunchProtectedWindows = 1,
ServiceLaunchProtectedWindowsLight = 2,
ServiceLaunchProtectedAntimalwareLight = 3
);
// 508
TServiceDescription = record
Description: PWideChar;
end;
PServiceDescription = ^TServiceDescription;
// 522
TScActionType = (
ScActionNone = 0,
ScActionRestart = 1,
ScActionReboot = 2,
ScActionRunCommand = 3,
ScActionOwnRestart = 4
);
// 530
TScAction = record
ActionType: TScActionType;
Delay: Cardinal;
end;
PScAction = ^TScAction;
// 548
TServiceFailureActions = record
ResetPeriod: Cardinal;
RebootMsg: PWideChar;
Command: PWideChar;
Actions: Cardinal;
lpsaActions: PScAction;
end;
PServiceFailureActions = ^TServiceFailureActions;
// 599
TServiceRequiredPrivilegesInfo = record
RequiredPrivileges: PWideChar; // multi-sz
end;
PServiceRequiredPrivilegesInfo = ^TServiceRequiredPrivilegesInfo;
// 707
TScStatusType = (
ScStatusProcessInfo = 0 // TServiceStatusProcess
);
// 723
TServiceStatus = record
ServiceType: Cardinal;
CurrentState: TServiceState;
ControlsAccepted: Cardinal;
Win32ExitCode: Cardinal;
ServiceSpecificExitCode: Cardinal;
CheckPoint: Cardinal;
WaitHint: Cardinal;
end;
PServiceStatus = ^TServiceStatus;
// 733
TServiceStatusProcess = record
ServiceType: Cardinal;
CurrentState: TServiceState;
ControlsAccepted: Cardinal;
Win32ExitCode: Cardinal;
ServiceSpecificExitCode: Cardinal;
CheckPoint: Cardinal;
WaitHint: Cardinal;
ProcessId: Cardinal;
ServiceFlags: Cardinal;
end;
PServiceStatusProcess = ^TServiceStatusProcess;
// 827
TQueryServiceConfigW = record
ServiceType: Cardinal;
StartType: TServiceStartType;
ErrorControl: TServiceErrorControl;
BinaryPathName: PWideChar;
LoadOrderGroup: PWideChar;
TagId: Cardinal;
Dependencies: PWideChar;
ServiceStartName: PWideChar;
DisplayName: PWideChar;
end;
PQueryServiceConfigW = ^TQueryServiceConfigW;
TServiceArgsW = array [ANYSIZE_ARRAY] of PWideChar;
PServiceArgsW = ^TServiceArgsW;
// 868
TServiceMainFunction = procedure (NumServicesArgs: Integer;
ServiceArgVectors: PServiceArgsW) stdcall;
// 893
TServiceTableEntryW = record
ServiceName: PWideChar;
ServiceProc: TServiceMainFunction;
end;
PServiceTableEntryW = ^TServiceTableEntryW;
// 924
THandlerFunctionEx = function(Control: TServiceControl; EventType: Cardinal;
EventData: Pointer; Context: Pointer): Cardinal; stdcall;
// 991
TServiceControlStatusReasonParamsW = record
Reason: Cardinal;
Comment: PWideChar;
ServiceStatus: TServiceStatusProcess;
end;
PServiceControlStatusReasonParamsW = ^TServiceControlStatusReasonParamsW;
// 1041
function ChangeServiceConfigW(hService: TScmHandle; dwServiceType: Cardinal;
dwStartType: TServiceStartType; dwErrorControl: TServiceErrorControl;
pBinaryPathName: PWideChar; pLoadOrderGroup: PWideChar; pdwTagId: PCardinal;
pDependencies: PWideChar; pServiceStartName: PWideChar; pPassword: PWideChar;
pDisplayName: PWideChar): LongBool; stdcall; external advapi32;
// 1071
function ChangeServiceConfig2W(hService: TScmHandle;
InfoLevel: TServiceConfigLevel; pInfo: Pointer): LongBool; stdcall;
external advapi32;
// 1083
function CloseServiceHandle(hSCObject: TScmHandle): LongBool; stdcall;
external advapi32;
// 1092
function ControlService(hService: TScmHandle; dwControl: TServiceControl;
out lpServiceStatus: TServiceStatus): LongBool; stdcall; external advapi32;
// 1121
function CreateServiceW(hSCManager: TScmHandle; lpServiceName: PWideChar;
lpDisplayName: PWideChar; dwDesiredAccess: TAccessMask;
dwServiceType: Cardinal; dwStartType: TServiceStartType; dwErrorControl:
TServiceErrorControl; lpBinaryPathName: PWideChar; lpLoadOrderGroup:
PWideChar; lpdwTagId: PCardinal; lpDependencies: PWideChar;
lpServiceStartName: PWideChar; lpPassword: PWideChar): TScmHandle; stdcall;
external advapi32;
// 1145
function DeleteService(hService: TScmHandle): LongBool; stdcall;
external advapi32;
// 1312
function GetServiceDisplayNameW(hSCManager: TScmHandle;
lpServiceName: PWideChar; lpDisplayName: PWideChar; var cchBuffer: Cardinal):
LongBool; stdcall; external advapi32;
// 1334
function LockServiceDatabase(hSCManager: TScmHandle): TScLock; stdcall;
external advapi32;
// 1364
function OpenSCManagerW(lpMachineName: PWideChar; lpDatabaseName: PWideChar;
dwDesiredAccess: TAccessMask): TScmHandle; stdcall; external advapi32;
// 1388
function OpenServiceW(hSCManager: TScmHandle; lpServiceName: PWideChar;
dwDesiredAccess: Cardinal): TScmHandle; stdcall; external advapi32;
// 1414
function QueryServiceConfigW(hService: TScmHandle;
pServiceConfig: PQueryServiceConfigW; cbBufSize: Cardinal;
out BytesNeeded: Cardinal): LongBool; stdcall; external advapi32;
// 1457
function QueryServiceConfig2W(hService: TScmHandle;
InfoLevel: TServiceConfigLevel; Buffer: Pointer; BufSize: Cardinal;
out BytesNeeded: Cardinal): LongBool; stdcall; external advapi32;
// 1515
function QueryServiceObjectSecurity(hService: TScmHandle; SecurityInformation:
TSecurityInformation; SecurityDescriptor: PSecurityDescriptor;
cbBufSize: Cardinal; out cbBytesNeeded: Cardinal): LongBool; stdcall;
external advapi32;
// 1528
function QueryServiceStatus(hService: TScmHandle;
out ServiceStatus: TServiceStatus): LongBool; stdcall; external advapi32;
// 1537
function QueryServiceStatusEx(hService: TScmHandle; InfoLevel: TScStatusType;
Buffer: Pointer; BufSize: Cardinal; out BytesNeeded: Cardinal): LongBool;
stdcall; external advapi32;
// 1584
function RegisterServiceCtrlHandlerExW(lpServiceName: PWideChar;
lpHandlerProc: THandlerFunctionEx; lpContext: Pointer): TServiceStatusHandle;
stdcall; external advapi32;
// 1599
function SetServiceObjectSecurity(hService: TScmHandle;
SecurityInformation: TSecurityInformation; const SecurityDescriptor:
TSecurityDescriptor): LongBool; stdcall; external advapi32;
// 1608
function SetServiceStatus(hServiceStatus: TServiceStatusHandle;
const ServiceStatus: TServiceStatus): LongBool; stdcall; external advapi32;
// 1622
function StartServiceCtrlDispatcherW(lpServiceStartTable: PServiceTableEntryW):
LongBool; stdcall; external advapi32;
// 1644
function StartServiceW(hService: TScmHandle; dwNumServiceArgs: Cardinal;
lpServiceArgVectors: TArray<PWideChar>): LongBool; stdcall; external advapi32;
// 1665
function UnlockServiceDatabase(ScLock: TScLock): LongBool; stdcall;
external advapi32;
// 1711
function ControlServiceExW(hService: TScmHandle; dwControl: TServiceControl;
InfoLevel: TServiceContolLevel; pControlParams: Pointer): LongBool; stdcall;
external advapi32;
implementation
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.EventEngine.Intf;
{$I ADAPT.inc}
interface
uses
{$IFDEF ADAPT_USE_EXPLICIT_UNIT_NAMES}
System.Classes,
{$ELSE}
Classes,
{$ENDIF ADAPT_USE_EXPLICIT_UNIT_NAMES}
ADAPT, ADAPT.Intf, ADAPT.Threadsafe,
ADAPT.Collections.Intf;
{$I ADAPT_RTTI.inc}
type
{ Forward Declarations }
IADEvent = interface;
TADEventBase = class;
IADEventListener = interface;
IADEventThread = interface;
{ Class References }
TADEventBaseClass = class of TADEventBase;
{ Enums }
TADEventDispatchMethod = (dmQueue, dmStack);
TADEventDispatchTarget = (dtThreads);
TADEventOrigin = (eoInternal, eoReplay, eoRemote, eoUnknown);
TADEventState = (esNotDispatched, esScheduled, esDispatched, esProcessing, esProcessed, esCancelled);
TADEventListenerRegistrationMode = (elrmAutomatic, elrmManual);
{ Sets }
TADEventDispatchTargets = set of TADEventDispatchTarget;
{ Exceptions }
EADEventEngineException = class(EADException);
EADEventEngineEventException = class(EADEventEngineException);
EADEventEngineEventListenerException = class(EADEventEngineException);
EADEventEngineEventListenerCallbackUnassigned = class(EADEventEngineEventListenerException);
EADEventEngineEventThreadException = class(EADEventEngineException);
{ Generic Collections }
IADEventList = IADList<IADEvent>;
IADEventListenerMap = IADMap<TADEventBaseClass, IADEventListener>;
/// <summary><c>Fundamental Interface for all Event Types.</c></summary>
/// <remarks>
/// <para><c>Remember that Events do NOT provide functionality, only information.</c></para>
/// </remarks>
IADEvent = interface(IADInterface)
['{CAFF660F-37F4-49B3-BBCC-15096C4B8E50}']
// Getters
/// <returns><c>The Time at which the Event was Created.</c></returns>
function GetCreatedTime: ADFloat;
/// <returns><c>The Time Differential (Delta) between Dispatch and Now.</c></returns>
function GetDelta: ADFloat;
/// <returns><c>The Time (in Seconds) after which the Event should be Dispatched.</c></returns>
/// <remarks>
/// <para><c>Value represents an Offset (in Seconds) from DispatchTime</c></para>
/// <para><c>0 = Instant Dispatch (no Scheduling)</c></para>
/// <para><c>Default = </c>0</para>
/// </remarks>
function GetDispatchAfter: ADFloat;
/// <returns><c>The Physical Reference Time at which the Event should be Dispatched by the Scheduler.</c></returns>
function GetDispatchAt: ADFloat;
/// <returns><c>The Method by which the Event was Dispatched.</c></returns>
/// <remarks><c>We either Queue an Event, or Stack it!</c></remarks>
function GetDispatchMethod: TADEventDispatchMethod;
/// <returns><c>The Targets to which this Event is allowed to be Dispatched.</c></returns>
/// <remarks>
/// <para><c>Default = ADAPT_EVENTENGINE_DEFAULT_TARGETS (meaning that there are no restrictions)</c></para>
/// <para><c>By default, we want to allow the Event to be processed by ALL available PreProcessors</c></para>
/// </remarks>
function GetDispatchTargets: TADEventDispatchTargets;
/// <returns><c>The Reference Time at which the Event was Dispatched.</c></returns>
function GetDispatchTime: ADFloat;
/// <returns><c>The Duration of Time after which the Event will Expire once Dispatched.</c></returns>
/// <remarks><c>Default will be 0.00 (Never Expires)</c></remarks>
function GetExpiresAfter: ADFloat;
/// <returns><c>Where this Event came from.</c></returns>
function GetEventOrigin: TADEventOrigin;
/// <returns><c>The Reference Time at which the Event was First Processed.</c></returns>
function GetProcessedTime: ADFloat;
/// <returns><c>Current State of this Event.</c></returns>
function GetState: TADEventState;
// Setters
// Management Methods
/// <summary><c>Dispatches the Event through the Event Engine Queue.</c></summary>
procedure Queue; overload;
/// <summary><c>Dispatches the Event through the Event Engine Queue.</c></summary>
/// <remarks><c>Defines an instance-specific Expiry Time.</c></remarks>
procedure Queue(const AExpiresAfter: ADFloat); overload;
/// <summary><c>Schedules the Event for Dispatch through the Event Engine Queue.</c></summary>
procedure QueueSchedule(const AScheduleFor: ADFloat);
/// <summary><c>Dispatches the Event through the Event Engine Stack.</c></summary>
procedure Stack; overload;
/// <summary><c>Dispatches the Event through the Event Engine Stack.</c></summary>
/// <remarks><c>Defines an instance-specific Expiry Time.</c></remarks>
procedure Stack(const AExpiresAfter: ADFloat); overload;
/// <summary><c>Schedules the Event for Dispatch through the Event Engine Stack.</c></summary>
procedure StackSchedule(const AScheduleFor: ADFloat);
// Properties
/// <summary><c>The Time at which the Event was Created.</c></summary>
property CreatedTime: ADFloat read GetCreatedTime;
/// <returns><c>The Time Differential (Delta) between Dispatch and Now.</c></returns>
property Delta: ADFloat read GetDelta;
/// <returns><c>The Time (in Seconds) after which the Event should be Dispatched.</c></returns>
/// <remarks>
/// <para><c>Value represents an Offset (in Seconds) from DispatchTime</c></para>
/// <para><c>0 = Instant Dispatch (no Scheduling)</c></para>
/// <para><c>Default = </c>0</para>
/// </remarks>
property DispatchAfter: ADFloat read GetDispatchAfter;
/// <returns><c>The Physical Reference Time at which the Event should be Dispatched by the Scheduler.</c></returns>
property DispatchAt: ADFloat read GetDispatchAt;
/// <returns><c>The Method by which the Event was Dispatched.</c></returns>
/// <remarks><c>We either Queue an Event, or Stack it!</c></remarks>
property DispatchMethod: TADEventDispatchMethod read GetDispatchMethod;
/// <returns><c>The Targets to which this Event is allowed to be Dispatched.</c></returns>
/// <remarks>
/// <para><c>Default = ADAPT_EVENTENGINE_DEFAULT_TARGETS (meaning that there are no restrictions)</c></para>
/// <para><c>By default, we want to allow the Event to be processed by ALL available PreProcessors</c></para>
/// </remarks>
property DispatchTargets: TADEventDispatchTargets read GetDispatchTargets;
/// <returns><c>The Reference Time at which the Event was Dispatched.</c></returns>
property DispatchTime: ADFloat read GetDispatchTime;
/// <returns><c>The Duration of Time after which the Event will Expire once Dispatched.</c></returns>
/// <remarks><c>Default will be 0.00 (Never Expires)</c></remarks>
property ExpiresAfter: ADFloat read GetExpiresAfter;
/// <returns><c>Where this Event came from.</c></returns>
property EventOrigin: TADEventOrigin read GetEventOrigin;
/// <returns><c>The Reference Time at which the Event was First Processed.</c></returns>
property ProcessedTime: ADFloat read GetProcessedTime;
/// <returns><c>Current State of this Event.</c></returns>
property State: TADEventState read GetState;
end;
/// <summary><c>The Absolute Abstract Base Class for all Event Types.</c></summary>
/// <remarks><c>Inherit from </c>TADEvent<c> instead of this class!!</c></remarks>
TADEventBase = class abstract(TADObjectTS, IADEvent)
protected
// Getters
{ IADEvent }
function GetCreatedTime: ADFloat; virtual; abstract;
function GetDelta: ADFloat; virtual; abstract;
function GetDispatchAfter: ADFloat; virtual; abstract;
function GetDispatchAt: ADFloat; virtual; abstract;
function GetDispatchMethod: TADEventDispatchMethod; virtual; abstract;
function GetDispatchTargets: TADEventDispatchTargets; virtual; abstract;
function GetDispatchTime: ADFloat; virtual; abstract;
function GetExpiresAfter: ADFloat; virtual; abstract;
function GetEventOrigin: TADEventOrigin; virtual; abstract;
function GetProcessedTime: ADFloat; virtual; abstract;
function GetState: TADEventState; virtual; abstract;
public
// Management Methods
{ IADEvent }
procedure Queue; overload; virtual; abstract;
procedure Queue(const AExpiresAfter: ADFloat); overload; virtual; abstract;
procedure QueueSchedule(const AScheduleFor: ADFloat); virtual; abstract;
procedure Stack; overload; virtual; abstract;
procedure Stack(const AExpiresAfter: ADFloat); overload; virtual; abstract;
procedure StackSchedule(const AScheduleFor: ADFloat); virtual; abstract;
// Properties
{ IADEvent }
property CreatedTime: ADFloat read GetCreatedTime;
property Delta: ADFloat read GetDelta;
property DispatchAfter: ADFloat read GetDispatchAfter;
property DispatchAt: ADFloat read GetDispatchAt;
property DispatchMethod: TADEventDispatchMethod read GetDispatchMethod;
property DispatchTargets: TADEventDispatchTargets read GetDispatchTargets;
property DispatchTime: ADFloat read GetDispatchTime;
property ExpiresAfter: ADFloat read GetExpiresAfter;
property EventOrigin: TADEventOrigin read GetEventOrigin;
property ProcessedTime: ADFloat read GetProcessedTime;
property State: TADEventState read GetState;
end;
{ Callbacks }
TADEventCallback<T: TADEventBase> = procedure(const AEvent: T) of object;
/// <summary><c>Event Listeners are invoked when their relevent Event Type is processed through the Event Engine.</c></summary>
IADEventListener = interface(IADInterface)
['{08B3A941-6D79-4165-80CE-1E45B5E35A9A}']
// Getters
/// <returns><c>A reference to the Event Thread owning this Listener.</c></returns>
/// <remarks>
/// <para><c>Could be </c>nil<c> if the Listener has no owning Event Thread.</c></para>
/// </remarks>
function GetEventThread: IADEventThread;
/// <returns><c>The Reference Time of the last processed Event.</c></returns>
function GetLastProcessed: ADFloat;
/// <returns>The Maximum Age (Delta) of an Event before this Listener will no longer process it.</c></returns>
function GetMaxAge: ADFloat;
/// <returns>
/// <para>True<c> if this Listener will only process an Event if it is newer than the last Processed Event.</c></para>
/// <para>False<c> if this Listener doesn't care whether an Event is newer or older than the last Processed Event.</c></para>
/// </returns>
function GetNewestOnly: Boolean;
// Setters
/// <summary><c>Defines the Maximum Age (Delta) of an Event before this Listener will no longer process it.</c></summary>
procedure SetMaxAge(const AMaxAge: ADFloat);
/// <summary><c>Defines whether or not this Listener will only process an Event if it is newer than the last Processed Event.</c></summary>
procedure SetNewestOnly(const ANewestOnly: Boolean);
// Management Methods
/// <summary><c>Executes an Event<c></summary>
procedure ExecuteEvent(const AEvent: TADEventBase);
/// <summary><c>Registers the Event Listner so that it can begin processing Events.</c></summary>
procedure Register;
/// <summary><c>Unregisters the Event Listener. It will no longer respond to Events.</c></summary>
procedure Unregister;
// Properties
/// <returns><c>A reference to the Event Thread owning this Listener.</c></returns>
/// <remarks>
/// <para><c>Could be </c>nil<c> if the Listener has no owning Event Thread.</c></para>
/// </remarks>
property EventThread: IADEventThread read GetEventThread;
/// <summary><c>Defines the Maximum Age (Delta) of an Event before this Listener will no longer process it.</c></summary>
/// <returns>The Maximum Age (Delta) of an Event before this Listener will no longer process it.</c></returns>
property MaxAge: ADFloat read GetMaxAge write SetMaxAge;
/// <summary><c>Defines whether or not this Listener will only process an Event if it is newer than the last Processed Event.</c></summary>
/// <returns>
/// <para>True<c> if this Listener will only process an Event if it is newer than the last Processed Event.</c></para>
/// <para>False<c> if this Listener doesn't care whether an Event is newer or older than the last Processed Event.</c></para>
/// </returns>
property NewestOnly: Boolean read GetNewestOnly write SetNewestOnly;
end;
/// <summary><c>Any Type containing an Event Queue and Stack.</c></summary>
IADEventContainer = interface(IADInterface)
['{6189CACA-B75D-4A5D-881A-61BE88C9ABC5}']
// Getters
/// <returns><c>The combined number of Events currently contained within the Queue and Stack.</c></returns>
function GetEventCount: Integer;
/// <returns><c>The number of Events currently contained within the Queue.</c></returns>
function GetEventQueueCount: Integer;
/// <returns><c>The number of Events currently contained within the Stack.</c></returns>
function GetEventStackCount: Integer;
/// <returns><c>The overall Limit to the number of Events the Queue and Stack (combined) can contain at any one time.</c></returns>
function GetMaxEventCount: Integer;
// Setters
/// <summary><c>Defines the Limit to the number of Events the Queue and Stack (combined) can contain at any one time.</c></summary>
procedure SetMaxEventCount(const AMaxEventCount: Integer);
// Management Methods
/// <summary><c>Places the given Event into this Container's Event Queue.</c></summary>
procedure QueueEvent(const AEvent: TADEventBase);
/// <summary><c>Places the given Event into this Container's Event Stack.</c></summary>
procedure StackEvent(const AEVent: TADEventBase);
// Properties
/// <returns><c>The combined number of Events currently contained within the Queue and Stack.</c></returns>
property EventCount: Integer read GetEventCount;
/// <returns><c>The number of Events currently contained within the Queue.</c></returns>
property EventQueueCount: Integer read GetEventQueueCount;
/// <returns><c>The number of Events currently contained within the Stack.</c></returns>
property EventStackCount: Integer read GetEventStackCount;
/// <summary><c>Defines the Limit to the number of Events the Queue and Stack (combined) can contain at any one time.</c></summary>
/// <returns><c>The overall Limit to the number of Events the Queue and Stack (combined) can contain at any one time.</c></returns>
property MaxEventCount: Integer read GetMaxEventCount write SetMaxEventCount;
end;
/// <summary><c>Event Threads are specialized "Precision Threads" designed to process Asynchronous Events.</c></summary>
IADEventThread = interface(IADInterface)
['{0374AD53-2EB7-45BB-8402-1FD34D40512B}']
// Getters
/// <returns>
/// <para>True<c> if the Event Thread Pauses when there are no pending Events in the Queue or Stack</c></para>
/// <para>False<c> if the Event Thread continues to Tick regardless of whether or not there are pending Events.</c></para>
/// </returns>
function GetPauseOnNoEvent: Boolean;
// Setters
/// <summary><c>Define whether or not the Event Thread Pauses when there are no pending Events in the Queue or Stack.</c></summary>
procedure SetPauseOnNoEvent(const APauseOnNoEvent: Boolean);
// Management Methods
/// <summary><c>Registers an Event Listener with this Event Thread.</c></summary>
procedure RegisterEventListener(const AEventListener: IADEventListener);
/// <summary><c>Unregisters and Event Listener from this Event Thread.</c></summary>
procedure UnregisterEventListener(const AEventListener: IADEventListener);
// Properties
/// <summary><c>Define whether or not the Event Thread Pauses when there are no pending Events in the Queue or Stack.</c></summary>
/// <returns>
/// <para>True<c> if the Event Thread Pauses when there are no pending Events in the Queue or Stack</c></para>
/// <para>False<c> if the Event Thread continues to Tick regardless of whether or not there are pending Events.</c></para>
/// </returns>
property PauseOnNoEvent: Boolean read GetPauseOnNoEvent write SetPauseOnNoEvent;
end;
/// <summary><c>Public Interface for the Event Engine.</c></summary>
IADEventEngine = interface(IADInterface)
['{6E6D99BF-BAD7-4E43-8CA6-3CF25F262329}']
// Getters
/// <returns><c>The Global Maximum number of Events the Engine can handle at any one time.</c></returns>
function GetGlobalMaxEvents: Integer;
// Setters
/// <summary><c>Defines the Global Maximum number of Events the Engine can handle at any one time.</c></returns>
procedure SetGlobalMaxEvents(const AGlobalMaxEvents: Integer);
// Management Methods
/// <summary><c>Dispatches the given Event across the entire Event Engine via the Queues.</c></summary>
procedure QueueEvent(const AEvent: IADEvent);
/// <summary><c>Dispatches the given Event across the entire Event Engine via the Stacks.</c></summary>
procedure StackEvent(const AEvent: IADEvent);
// Properties
/// <summary><c>Defines the Global Maximum number of Events the Engine can handle at any one time.</c></returns>
/// <returns><c>The Global Maximum number of Events the Engine can handle at any one time.</c></returns>
property GlobalMaxEvents: Integer read GetGlobalMaxEvents write SetGlobalMaxEvents;
end;
implementation
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.