text stringlengths 14 6.51M |
|---|
unit Ths.Erp.Database.Table.PersonelPDKSKart;
interface
{$I ThsERP.inc}
uses
SysUtils, Classes, Dialogs, Forms, Windows, Controls, Types, DateUtils,
FireDAC.Stan.Param, System.Variants, Data.DB,
Ths.Erp.Database,
Ths.Erp.Database.Table;
type
TPersonelPDKSKart = class(TTable)
private
FKartID: TFieldDB;
FPersonelNo: TFieldDB;
FKartNo: TFieldDB;
FIsActive: TFieldDB;
protected
published
constructor Create(OwnerDatabase:TDatabase);override;
public
procedure SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); override;
procedure SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); override;
procedure Insert(out pID: Integer; pPermissionControl: Boolean=True); override;
procedure Update(pPermissionControl: Boolean=True); override;
function Clone():TTable;override;
Property KartID: TFieldDB read FKartID write FKartID;
Property PersonelNo: TFieldDB read FPersonelNo write FPersonelNo;
Property KartNo: TFieldDB read FKartNo write FKartNo;
Property IsActive: TFieldDB read FIsActive write FIsActive;
end;
implementation
uses
Ths.Erp.Constants,
Ths.Erp.Database.Singleton;
constructor TPersonelPDKSKart.Create(OwnerDatabase:TDatabase);
begin
TableName := 'personel_pdks_kart';
SourceCode := '1000';
inherited Create(OwnerDatabase);
FKartID := TFieldDB.Create('kart_id', ftString, '');
FPersonelNo := TFieldDB.Create('personel_ no', ftInteger, 0);
FKartNo := TFieldDB.Create('kart_no', ftInteger, 0);
FIsActive := TFieldDB.Create('is_active', ftBoolean, 0);
end;
procedure TPersonelPDKSKart.SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptRead, pPermissionControl) then
begin
with QueryOfDS do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLSelectCmd(TableName, [
TableName + '.' + Self.Id.FieldName,
TableName + '.' + FKartID.FieldName,
TableName + '.' + FPersonelNo.FieldName,
TableName + '.' + FKartNo.FieldName,
TableName + '.' + FIsActive.FieldName
]) +
'WHERE 1=1 ' + pFilter;
Open;
Active := True;
Self.DataSource.DataSet.FindField(Self.Id.FieldName).DisplayLabel := 'ID';
Self.DataSource.DataSet.FindField(FKartID.FieldName).DisplayLabel := 'Kart ID';
Self.DataSource.DataSet.FindField(FPersonelNo.FieldName).DisplayLabel := 'Personel No';
Self.DataSource.DataSet.FindField(FKartNo.FieldName).DisplayLabel := 'Kart No';
Self.DataSource.DataSet.FindField(FIsActive.FieldName).DisplayLabel := 'Aktif?';
end;
end;
end;
procedure TPersonelPDKSKart.SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptRead, pPermissionControl) then
begin
if (pLock) then
pFilter := pFilter + ' FOR UPDATE OF ' + TableName + ' NOWAIT';
with QueryOfList do
begin
Close;
SQL.Text := Database.GetSQLSelectCmd(TableName, [
TableName + '.' + Self.Id.FieldName,
TableName + '.' + FKartID.FieldName,
TableName + '.' + FPersonelNo.FieldName,
TableName + '.' + FKartNo.FieldName,
TableName + '.' + FIsActive.FieldName
]) +
'WHERE 1=1 ' + pFilter;
Open;
FreeListContent();
List.Clear;
while NOT EOF do
begin
Self.Id.Value := FormatedVariantVal(FieldByName(Self.Id.FieldName).DataType, FieldByName(Self.Id.FieldName).Value);
FKartID.Value := FormatedVariantVal(FieldByName(FKartID.FieldName).DataType, FieldByName(FKartID.FieldName).Value);
FPersonelNo.Value := FormatedVariantVal(FieldByName(FPersonelNo.FieldName).DataType, FieldByName(FPersonelNo.FieldName).Value);
FKartNo.Value := FormatedVariantVal(FieldByName(FKartNo.FieldName).DataType, FieldByName(FKartNo.FieldName).Value);
FIsActive.Value := FormatedVariantVal(FieldByName(FIsActive.FieldName).DataType, FieldByName(FIsActive.FieldName).Value);
List.Add(Self.Clone());
Next;
end;
Close;
end;
end;
end;
procedure TPersonelPDKSKart.Insert(out pID: Integer; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptAddRecord, pPermissionControl) then
begin
with QueryOfInsert do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLInsertCmd(TableName, QUERY_PARAM_CHAR, [
FKartID.FieldName,
FPersonelNo.FieldName,
FKartNo.FieldName,
FIsActive.FieldName
]);
NewParamForQuery(QueryOfInsert, FKartID);
NewParamForQuery(QueryOfInsert, FPersonelNo);
NewParamForQuery(QueryOfInsert, FKartNo);
NewParamForQuery(QueryOfInsert, FIsActive);
Open;
if (Fields.Count > 0) and (not Fields.FieldByName(Self.Id.FieldName).IsNull) then
pID := Fields.FieldByName(Self.Id.FieldName).AsInteger
else
pID := 0;
EmptyDataSet;
Close;
end;
Self.notify;
end;
end;
procedure TPersonelPDKSKart.Update(pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptUpdate, pPermissionControl) then
begin
with QueryOfUpdate do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLUpdateCmd(TableName, QUERY_PARAM_CHAR, [
FKartID.FieldName,
FPersonelNo.FieldName,
FKartNo.FieldName,
FIsActive.FieldName
]);
NewParamForQuery(QueryOfUpdate, FKartID);
NewParamForQuery(QueryOfUpdate, FPersonelNo);
NewParamForQuery(QueryOfUpdate, FKartNo);
NewParamForQuery(QueryOfUpdate, FIsActive);
NewParamForQuery(QueryOfUpdate, Id);
ExecSQL;
Close;
end;
Self.notify;
end;
end;
function TPersonelPDKSKart.Clone():TTable;
begin
Result := TPersonelPDKSKart.Create(Database);
Self.Id.Clone(TPersonelPDKSKart(Result).Id);
FKartID.Clone(TPersonelPDKSKart(Result).FKartID);
FPersonelNo.Clone(TPersonelPDKSKart(Result).FPersonelNo);
FKartNo.Clone(TPersonelPDKSKart(Result).FKartNo);
FIsActive.Clone(TPersonelPDKSKart(Result).FIsActive);
end;
end.
|
unit NumPlanMasterFrame;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, NxColumnClasses, NxColumns, NxScrollControl,
NxCustomGridControl, NxCustomGrid, NxGrid, ItemsDef, ComCtrls, Core,
NxEdit;
type
TfrmNumPlanMaster = class(TFrame)
grp1: TGroupBox;
lbl1: TLabel;
lbl2: TLabel;
edTicketsCount: TEdit;
edPagesCount: TEdit;
grp2: TGroupBox;
lbl3: TLabel;
cbbOddPages: TComboBox;
lbl4: TLabel;
cbbEvenPages: TComboBox;
grp3: TGroupBox;
ngLabels: TNextGrid;
nxTextCol1: TNxTextColumn;
nxTextCol2: TNxTextColumn;
nxCBox1: TNxComboBoxColumn;
nxCBox2: TNxComboBoxColumn;
btnOK: TBitBtn;
pbProgress: TProgressBar;
grpRows: TGroupBox;
ngRows: TNextGrid;
nncRowNumber: TNxNumberColumn;
nncRowPlaces: TNxNumberColumn;
nseRowCount: TNxSpinEdit;
lbRowCount: TLabel;
nsePlacesInRow: TNxSpinEdit;
lbPlacesInRow: TLabel;
cbbRow: TComboBox;
cbbPlace: TComboBox;
lbRow: TLabel;
lbPlace: TLabel;
btnCreateRowList: TButton;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnOKClick(Sender: TObject);
procedure edTicketsCountChange(Sender: TObject);
procedure btnCreateRowListClick(Sender: TObject);
procedure ngRowsAfterEdit(Sender: TObject; ACol, ARow: Integer;
Value: WideString);
private
{ Private declarations }
function GetNewPage(var iPagesCount: Integer; PageTpl: TNumPageTpl): TNumPage;
function GetActionStr(LabelName: string; First: Boolean = false): string;
procedure UpdatePlacesCount();
public
{ Public declarations }
NumProject: TNumProject;
Form: TForm;
function Start(): boolean;
procedure DoError(msg: string);
destructor Destroy; override;
procedure CngLanguageNPM();
end;
var
sAskRewriteRowList: string = 'Перезаписать таблицу рядов?';
sGrpRowsCaption: string = 'Список рядов';
sWrongTicketCount: string = 'Неправильно задано количество билетов!';
sEmptyBaseValueForNumerator: string = 'Не задано начальное значение для нумератора';
PlanMastCreated: Boolean = False;
const
ciRowListRowId = 0;
ciRowListPlacesId = 1;
implementation
uses MainForm, IniFiles;
{$R *.dfm}
destructor TfrmNumPlanMaster.Destroy;
var
i: Integer;
begin
PlanMastCreated:= False;
//NumProject.Options.Params['row_count']:=IntToStr(nseRowCount.AsInteger);
NumProject.Options.Params['row_count']:=IntToStr(ngRows.RowCount);
NumProject.Options.Params['places_in_row']:=nsePlacesInRow.AsString;
for i:=0 to ngRows.RowCount-1 do
begin
NumProject.Options.Params['row_'+IntToStr(i+1)]:=ngRows.Cell[ciRowListPlacesId, i].AsString;
end;
NumProject.Options.SaveToBase();
inherited Destroy();
end;
function TfrmNumPlanMaster.Start(): Boolean;
var
i, n: Integer;
nlt: TNumLabelTpl;
begin
Result:=false;
if not Assigned(NumProject) then
begin
DoError('Не выбран проект!');
if Assigned(Form) then Form.Close();
Exit;
end;
if NumProject.PagesTpl.Count=0 then
begin
DoError('Не заполнены шаблоны листов!');
if Assigned(Form) then Form.Close();
Exit;
end;
if NumProject.NumLabelsTpl.Count=0 then
begin
DoError('Не заполнены шаблоны нумераторов!');
if Assigned(Form) then Form.Close();
Exit;
end;
edTicketsCount.Text:=IntToStr(NumProject.NumPlanItems.Count);
edPagesCount.Text:='';
// PagesTpl lists
cbbOddPages.Clear();
for i:=0 to NumProject.PagesTpl.Count-1 do
begin
cbbOddPages.AddItem(NumProject.PagesTpl[i].Name, NumProject.PagesTpl[i]);
end;
cbbOddPages.ItemIndex:=0;
cbbEvenPages.Clear();
for i:=0 to NumProject.PagesTpl.Count-1 do
begin
cbbEvenPages.AddItem(NumProject.PagesTpl[i].Name, NumProject.PagesTpl[i]);
end;
cbbEvenPages.ItemIndex:=0;
// Numerators
ngLabels.BeginUpdate();
nxCBox1.Items.Clear();
nxCBox1.Items.Add('+1');
nxCBox1.Items.Add('-1');
nxCBox1.Items.Add('=');
nxCBox2.Items.Clear();
nxCBox2.Items.Add('+1');
nxCBox2.Items.Add('-1');
nxCBox2.Items.Add('=');
for i:=0 to NumProject.NumLabelsTpl.Count-1 do
begin
nlt:=NumProject.NumLabelsTpl[i];
ngLabels.AddRow();
ngLabels.Cell[0, i].ObjectReference:=nlt;
ngLabels.Cells[0, i]:=nlt.Name;
ngLabels.Cells[1, i]:=nlt.BaseValue;
ngLabels.Cells[2, i]:='=';
ngLabels.Cells[3, i]:=nlt.Action;
end;
ngLabels.EndUpdate();
Result:=true;
// Row and Place numerators
cbbRow.Clear();
cbbPlace.Clear();
for i:=0 to NumProject.NumLabelsTpl.Count-1 do
begin
nlt:=NumProject.NumLabelsTpl[i];
cbbRow.AddItem(nlt.Name, nlt);
cbbPlace.AddItem(nlt.Name, nlt);
end;
// Default Row numerator
i:=cbbRow.Items.IndexOf(csRow);
if i <> -1 then cbbRow.ItemIndex := i;
// Default Place numerator
i:=cbbPlace.Items.IndexOf(csPlace);
if i <> -1 then cbbPlace.ItemIndex := i;
// Row count
nseRowCount.AsInteger:=StrToIntDef(NumProject.Options.Params['row_count'], 0);
nsePlacesInRow.AsInteger:=StrToIntDef(NumProject.Options.Params['places_in_row'], 0);
// === Row list
ngRows.RowCount:=nseRowCount.AsInteger;
for i:=0 to ngRows.RowCount-1 do
begin
ngRows.Cell[ciRowListRowId, i].AsInteger:=i+1;
ngRows.Cell[ciRowListPlacesId, i].AsInteger:=StrToIntDef(NumProject.Options.Params['row_'+IntToStr(i+1)] , nsePlacesInRow.AsInteger);
end;
//
PlanMastCreated:= True;
CngLanguageNPM();
end;
procedure TfrmNumPlanMaster.CngLanguageNPM();
var
Part:string;
begin
if not Assigned(LangFile) then Exit;
if PlanMastCreated then
begin
Part:= 'NumPlanMaster';
Self.btnOK.Caption:= LangFile.ReadString(Part, 'sbtnOk', Self.btnOK.Caption);
Self.grp1.Caption:= LangFile.ReadString(Part, 'sgrp1', Self.grp1.Caption);
Self.lbl1.Caption:= LangFile.ReadString(Part, 'slbl1', Self.lbl1.Caption);
Self.lbl2.Caption:= LangFile.ReadString(Part,'slbl2', Self.lbl2.Caption);
Self.grp2.Caption:= LangFile.ReadString(Part, 'sgrp2', Self.grp2.Caption);
Self.lbl3.Caption:= LangFile.ReadString(Part, 'slbl3', Self.lbl3.Caption);
Self.lbl4.Caption:= LangFile.ReadString(Part, 'slbl4', Self.lbl4.Caption);
Self.grp3.Caption:= LangFile.ReadString(Part, 'sgrp3', Self.grp3.Caption);
Self.nxCBox1.Header.Caption:= LangFile.ReadString(Part, 'snxCBox1', Self.nxCBox1.Header.Caption);
Self.nxCBox2.Header.Caption:= LangFile.ReadString(Part, 'snxCBox2', Self.nxCBox2.Header.Caption);
Self.nxTextCol1.Header.Caption:= LangFile.ReadString(Part, 'snxTextCol1', Self.nxTextCol1.Header.Caption);
Self.nxTextCol2.Header.Caption:= LangFile.ReadString(Part, 'snxTextCol2', Self.nxTextCol2.Header.Caption);
end;
end;
procedure TfrmNumPlanMaster.DoError(msg: string);
begin
ShowMessage(msg);
Exit;
end;
procedure TfrmNumPlanMaster.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if Assigned(Form) then Form.Release();
end;
function TfrmNumPlanMaster.GetNewPage(var iPagesCount: Integer; PageTpl: TNumPageTpl): TNumPage;
begin
Inc(iPagesCount);
Result:=TNumPage.Create(NumProject);
Result.Order:=iPagesCount;
Result.NumPageTpl:=PageTpl;
Result.Write();
NumProject.Pages.Add(Result);
end;
function TfrmNumPlanMaster.GetActionStr(LabelName: string; First: Boolean = false): string;
var
i: Integer;
begin
for i:=0 to ngLabels.RowCount-1 do
begin
if LabelName = ngLabels.Cells[0, i] then
begin
if First then Result:=ngLabels.Cells[2, i] else Result:=ngLabels.Cells[3, i];
Exit;
end;
end;
Result:='';
end;
procedure TfrmNumPlanMaster.btnOKClick(Sender: TObject);
var
i, m, n, n1, n2: integer;
iTicketsCount, iPagesCount: integer;
iCurRow, iCurPlace, iCurMaxPlace: integer;
npi: TNumPlanItem;
nld, LastNld: TNumLabelData;
nlt: TNumLabelTpl;
nldl: TNumLabelDataList;
CurTicket: TTicket;
CurNumPage: TNumPage;
PageTpl1, PageTpl2: TNumPageTpl;
Page1TicketCount, Page2TicketCount: Integer;
slLastValues: TStringList;
slLastActions: TStringList;
sName, sValue, sAction: string;
Duplicated: Boolean;
begin
iTicketsCount:=StrToIntDef(edTicketsCount.Text, 0);
// Check tickets count
if iTicketsCount <= 0 then
begin
DoError(sWrongTicketCount);
Exit;
end;
// Check numerators
for i:=0 to NumProject.NumLabelsTpl.Count-1 do
begin
if Length(Trim(ngLabels.Cells[1, i]))=0 then
begin
DoError(sEmptyBaseValueForNumerator+' '+ngLabels.Cells[0, i]);
Exit;
end;
end;
StartTransaction();
// Delete NumPlanItems
NumProject.NumPlanItems.DeleteFromBase(true);
NumProject.Pages.DeleteFromBase();
// Delete NumLabelData for whole project
nldl:=TNumLabelDataList.Create(true);
nldl.NumProject:=CurProject;
nldl.DeleteFromBase();
nldl.Free();
// Create NumPlanItems
PageTpl1:=TNumPageTpl(cbbOddPages.Items.Objects[cbbOddPages.ItemIndex]);
PageTpl2:=TNumPageTpl(cbbEvenPages.Items.Objects[cbbEvenPages.ItemIndex]);
PageTpl1.Read(true);
if PageTpl2<>PageTpl1 then PageTpl2.Read(true);
Page1TicketCount:=PageTpl1.Tickets.Count;
Page2TicketCount:=PageTpl2.Tickets.Count;
pbProgress.Min:=1;
pbProgress.Max:=iTicketsCount;
pbProgress.Visible:=True;
iPagesCount:=0;
slLastValues:=TStringList.Create();
slLastActions:=TStringList.Create();
for i:=0 to NumProject.NumLabelsTpl.Count-1 do
begin
sName:=NumProject.NumLabelsTpl[i].Name;
slLastValues.Values[sName]:='';
slLastActions.Values[sName]:='=';
end;
iCurRow:=1; iCurPlace:=1; iCurMaxPlace:=0;
if ngRows.RowCount>0 then iCurMaxPlace:=ngRows.Cell[ciRowListPlacesId, 0].AsInteger;
n1:=Page1TicketCount; n2:=0;
CurTicket:=nil;
CurNumPage:=nil;
for n:=1 to iTicketsCount do
begin
pbProgress.Position:=n;
if (n mod 10)=0 then Application.ProcessMessages();
if n1 = Page1TicketCount then CurNumPage:=GetNewPage(iPagesCount, PageTpl1);
if n2 = Page2TicketCount then CurNumPage:=GetNewPage(iPagesCount, PageTpl2);
if n1>0 then
begin
CurTicket:=PageTpl1.Tickets[Page1TicketCount-n1];
Dec(n1);
if n1=0 then
begin
n2:=Page2TicketCount;
end;
end
else if n2>0 then
begin
CurTicket:=PageTpl2.Tickets[Page2TicketCount-n2];
Dec(n2);
if n2=0 then
begin
n1:=Page1TicketCount;
end;
end;
npi:=TNumPlanItem.Create(NumProject);
npi.Order:=n;
npi.State:='';
npi.Ticket:=CurTicket;
npi.NumPage:=CurNumPage;
NumProject.NumPlanItems.Add(npi);
if not Assigned(CurTicket.Tpl) then
begin
Core.AddCmd('WARNING '+sTicketTplErr+' '+CurTicket.Name);
Continue;
end;
// Calculate current values/actions
for i:=0 to NumProject.NumLabelsTpl.Count-1 do
begin
sName:=NumProject.NumLabelsTpl[i].Name;
sValue:=slLastValues.Values[sName];
sAction:=slLastActions.Values[sName];
if sName = cbbRow.Text then
begin
sValue:=IntToStr(iCurRow);
sAction:='=';
if iCurPlace=1 then
begin
sAction:='+';
if iCurRow=1 then sAction:='=1';
end;
end
else if sName = cbbPlace.Text then
begin
sValue:=IntToStr(iCurPlace);
sAction:='+';
if iCurPlace=1 then
begin
sAction:='=1';
end;
// next place/row
if iCurPlace = iCurMaxPlace then
begin
Inc(iCurRow);
iCurPlace:=1;
iCurMaxPlace:=0;
if iCurRow <= ngRows.RowCount then iCurMaxPlace:=ngRows.Cell[ciRowListPlacesId, iCurRow-1].AsInteger;
end
else Inc(iCurPlace);
end
else
begin
if n=1 then
begin
sAction:=GetActionStr(sName, true);
sValue:=NumProject.NumLabelsTpl[i].BaseValue;
end
else
begin
sAction:=GetActionStr(sName, false);
sValue:=ApplyAction(sValue, sAction);
end;
end;
slLastValues.Values[sName]:=sValue;
slLastActions.Values[sName]:=sAction;
end;
for i:=0 to CurTicket.Tpl.NumLabels.Count-1 do
begin
nlt:=CurTicket.Tpl.NumLabels[i].NumLabelTpl;
if not Assigned(nlt) then
begin
Core.AddCmd('WARNING '+sNumLabelTplErr);
Continue;
end;
// Check for duplicates
Duplicated:=False;
for m:=0 to npi.NumLabelDataList.Count-1 do
begin
if npi.NumLabelDataList[m].NumLabelTpl = nlt then
begin
Duplicated:=True;
Break;
end;
end;
if Duplicated then Continue;
nld:=TNumLabelData.Create(NumProject);
nld.NumPlanItem:=npi;
nld.NumLabelTpl:=nlt;
sName:=nlt.Name;
nld.Action:=slLastActions.Values[sName];
nld.Value:=slLastValues.Values[sName];
npi.NumLabelDataList.Add(nld);
//nld.Write();
end;
npi.Write(true);
end;
slLastActions.Free();
slLastValues.Free();
CloseTransaction();
//NumProject.NumPlanItems.SaveToBase();
pbProgress.Visible:=False;
Core.CmdQueue.AddCmd('REFRESH NUM_PLAN');
Core.CmdQueue.AddCmd('REFRESH TICKETS_LIST');
end;
procedure TfrmNumPlanMaster.edTicketsCountChange(Sender: TObject);
var
i, n, n1, n2: integer;
iTicketsCount, iPagesCount: integer;
PageTpl1, PageTpl2: TNumPageTpl;
Page1TicketCount, Page2TicketCount: Integer;
bOdd: Boolean;
begin
iTicketsCount:=StrToIntDef(edTicketsCount.Text, 0);
if iTicketsCount=0 then Exit;
if cbbOddPages.Items.Count=0 then Exit;
if cbbEvenPages.Items.Count=0 then Exit;
// Create NumPlanItems
PageTpl1:=TNumPageTpl(cbbOddPages.Items.Objects[cbbOddPages.ItemIndex]);
PageTpl2:=TNumPageTpl(cbbEvenPages.Items.Objects[cbbEvenPages.ItemIndex]);
Page1TicketCount:=PageTpl1.Tickets.Count;
Page2TicketCount:=PageTpl2.Tickets.Count;
if (Page1TicketCount+Page2TicketCount)=0 then Exit;
i:=0; bOdd:=True;
iPagesCount:=0;
while i < iTicketsCount do
begin
if bOdd then Inc(i, Page1TicketCount) else Inc(i, Page2TicketCount);
Inc(iPagesCount);
bOdd:=not bOdd;
end;
edPagesCount.Text:=IntToStr(iPagesCount);
end;
procedure TfrmNumPlanMaster.btnCreateRowListClick(Sender: TObject);
var
i: integer;
begin
if ngRows.RowCount > 0 then
begin
// Are you sure?
if Application.MessageBox(PAnsiChar(sAskRewriteRowList), PAnsiChar(sAskDeleteCaption), MB_OKCANCEL) <> IDOK then Exit;
end;
ngRows.RowCount:=nseRowCount.AsInteger;
for i:=0 to nseRowCount.AsInteger-1 do
begin
ngRows.Cell[ciRowListRowId, i].AsInteger := i+1;
ngRows.Cell[ciRowListPlacesId, i].AsInteger := nsePlacesInRow.AsInteger;
end;
UpdatePlacesCount();
end;
procedure TfrmNumPlanMaster.UpdatePlacesCount();
var
i, n: Integer;
begin
n:=0;
for i:=0 to ngRows.RowCount-1 do
begin
n:=n+ngRows.Cell[ciRowListPlacesId, i].AsInteger;
end;
grpRows.Caption:=sGrpRowsCaption+' ('+IntToStr(n)+')';
end;
procedure TfrmNumPlanMaster.ngRowsAfterEdit(Sender: TObject; ACol,
ARow: Integer; Value: WideString);
begin
UpdatePlacesCount();
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2015-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit EMSHosting.ResourceManager;
interface
{$HPPEMIT LINKUNIT}
uses
System.Generics.Collections, System.SysUtils,
EMS.ResourceAPI;
type
TEMSEndpointManagerImpl = class(TEMSEndpointManager)
private
FResources: TList<TEMSResource>;
class procedure Init;
class function GetInstance: TEMSEndpointManagerImpl; static;
protected
// Override
function GetResources: TArray<TEMSResource>; override;
public
constructor Create;
destructor Destroy; override;
// Internal
function FindByBaseURL(const ABaseURL: string): TArray<TEMSResource>;
function FindByName(const AName: string): TEMSResource;
// Override
procedure RegisterResource(const AResource: TEMSResource); override;
class property Instance: TEMSEndpointManagerImpl read GetInstance;
end;
TEMSEndpointAuthorizationImpl = class(TEMSEndpointAuthorization)
public type
TACL = TEMSEndpointAuthorization.TACL;
private
FACL: TDictionary<string, TACL>;
FAllowCreator: TDictionary<string, Boolean>;
class function GetInstance: TEMSEndpointAuthorizationImpl; static;
class procedure Init;
public
constructor Create;
destructor Destroy; override;
// Internal
procedure RegisterACL(const AName: string; const AACL: TACL);
// Some endpoints are always allowed for the the creator of the resource item (e.g.; User)
procedure RegisterAllowCreator(const AResourceName: string; const AEndpointNames: TArray<string>);
function AllowCreator(const AName: string): Boolean;
function AllowCreatorEndpoints(const AResource: string): TArray<string>;
// Override
procedure Authorize(const AContext: TEndpointContext; const AACL: TACL); override;
function FindACL(const AName: string; out AACL: TACL): Boolean; override;
class property Instance: TEMSEndpointAuthorizationImpl read GetInstance;
end;
implementation
uses EMSHosting.Helpers, EMSHosting.Consts, System.Generics.Defaults;
{ TEMSEndpointManagerImpl }
constructor TEMSEndpointManagerImpl.Create;
begin
FResources := TObjectList<TEMSResource>.Create;
end;
destructor TEMSEndpointManagerImpl.Destroy;
begin
FResources.Free;
inherited;
end;
function TEMSEndpointManagerImpl.FindByBaseURL(
const ABaseURL: string): TArray<TEMSResource>;
var
LList: TLIst<TEMSResource>;
LEMSResource: TEMSResource;
begin
LList := TList<TEMSResource>.Create;
try
for LEMSResource in FResources do
begin
if LEMSResource.IsBaseURL(ABaseURL) then
LList.Add(LEMSResource);
end;
Result := LList.ToArray;
finally
LList.Free;
end;
end;
function TEMSEndpointManagerImpl.FindByName(
const AName: string): TEMSResource;
var
LEMSResource: TEMSResource;
begin
Result := nil;
for LEMSResource in FResources do
if SameText(LEMSResource.Name, AName) then
begin
if Result <> nil then
raise Exception.Create('Duplicate');
Result := LEMSResource;
end;
end;
class function TEMSEndpointManagerImpl.GetInstance: TEMSEndpointManagerImpl;
begin
Result := TEMSEndpointManager.Instance as TEMSEndpointManagerImpl;
end;
function TEMSEndpointManagerImpl.GetResources: TArray<TEMSResource>;
begin
Result := FResources.ToArray;
end;
class procedure TEMSEndpointManagerImpl.Init;
begin
TEMSEndpointManager.FEndpointManagerFactory :=
function: TEMSEndpointManager
begin
Result := TEMSEndpointManagerImpl.Create;
end;
end;
class procedure TEMSEndpointAuthorizationImpl.Init;
begin
TEMSEndpointAuthorization.FEndpointAuthorizationFactory :=
function: TEMSEndpointAuthorization
begin
Result := TEMSEndpointAuthorizationImpl.Create;
end;
end;
procedure TEMSEndpointManagerImpl.RegisterResource(const AResource: TEMSResource);
begin
TLogHelpers.LogRegisterResource(AResource);
FResources.Add(AResource);
end;
procedure TEMSEndpointAuthorizationImpl.RegisterACL(const AName: string; const AACL: TACL);
begin
FACL.AddOrSetValue(AName, AACL);
end;
procedure TEMSEndpointAuthorizationImpl.RegisterAllowCreator(const AResourceName: string;
const AEndpointNames: TArray<string>);
var
S: string;
begin
// This should be called before we register ACL
Assert(FACL.Count = 0);
// Should be form of resource.endpoint
for S in AEndpointNames do
FAllowCreator.AddOrSetValue(AResourceName + '.' + S, True);
end;
{ TEMSEndpointAuthorizationImpl }
function TEMSEndpointAuthorizationImpl.AllowCreator(
const AName: string): Boolean;
begin
if not FAllowCreator.TryGetValue(AName, Result) then
Result := False;
end;
function TEMSEndpointAuthorizationImpl.AllowCreatorEndpoints(
const AResource: string): TArray<string>;
var
LName: string;
LNames: TList<string>;
LCompare: string;
begin
LCompare := AResource + '.';
LNames := TList<string>.Create;
try
for LName in FAllowCreator.Keys do
begin
if LName.StartsWith(LCompare, True) then
LNames.Add(LName);
end;
Result := LNames.ToArray;
finally
LNames.Free;
end;
end;
procedure TEMSEndpointAuthorizationImpl.Authorize(
const AContext: TEndpointContext; const AACL: TACL);
const
sSampleID = '00000000-0000-0000-0000-000000000000'; // do not localize
function IsUserID(const AValue: string): Boolean;
begin
Result := (Length(AValue) = Length(sSampleID)) and
(AValue.IndexOf('-') = 8);
end;
var
S: string;
begin
if TEndpointContext.TAuthenticate.MasterSecret in AContext.Authenticated then
Exit; // OK
if AACL.IsPublic then
Exit; // OK
if AContext.User = nil then
AContext.Response.RaiseUnauthorized; // User not found
Assert(IsUserID(sSampleID));
for S in AACL.Users do
begin
if S = '*' then
Exit // OK
else if S = AContext.User.UserID then
begin
Assert(IsUserID(S));
Exit // OK
end
else if (S = AContext.User.UserName) and not IsUserID(S) then
Exit // OK
end;
for S in AACL.Groups do
begin
if S = '*' then
begin
if AContext.User.Groups.Count > 0 then
Exit // OK
end
else if AContext.User.Groups.Contains(S) then
Exit // OK
end;
if not AACL.AllowCreator then
// If we get here then no group or user match
AContext.Response.RaiseUnauthorized
else
// Authorize creator when execute method
TEndpointHelpers.SetCreatorRequired(AContext);
end;
constructor TEMSEndpointAuthorizationImpl.Create;
begin
FACL := TObjectDictionary<string, TACL>.Create([doOwnsValues], TIStringComparer.Ordinal);
FAllowCreator := TDictionary<string, Boolean>.Create(TIStringComparer.Ordinal);
end;
destructor TEMSEndpointAuthorizationImpl.Destroy;
begin
FACL.Free;
FAllowCreator.Free;
inherited;
end;
function TEMSEndpointAuthorizationImpl.FindACL(const AName: string;
out AACL: TACL): Boolean;
begin
Result := FACL.TryGetValue(AName, AACL);
end;
class function TEMSEndpointAuthorizationImpl.GetInstance: TEMSEndpointAuthorizationImpl;
begin
Result := TEMSEndpointAuthorization.Instance as TEMSEndpointAuthorizationImpl;
end;
initialization
TEMSEndpointManagerImpl.Init;
TEMSEndpointAuthorizationImpl.Init;
end.
|
unit Amazon.DynamoDB;
interface
uses Amazon.Client, Amazon.Request, System.Classes, System.Generics.Collections,
Amazon.Response, Amazon.Utils, Amazon.Marshaller, System.Rtti, System.TypInfo,
Amazon.Interfaces, System.AnsiStrings, System.SysUtils;
Const
cDynamoDB_targetPrefix = 'DynamoDB_20120810';
cDynamoDB_service = 'dynamodb';
type
TAmazonDynamoDBRequest = class(TAmazonRequest)
protected
private
public
Constructor Create; virtual;
end;
TAmazonDynamoDBMarshaller = class(TAmazonMarshaller)
protected
private
public
function AmazonDynamoDBRequestToJSON(aAmazonDynamoDBRequest
: TAmazonDynamoDBRequest): UTF8String;
end;
TAmazonDynamoDBResponse = class(TAmazonResponse)
protected
private
public
constructor Create(aAmazonResponse: IAmazonResponse);
end;
TAmazonDynamoDBClient = class(TAmazonClient)
protected
private
public
procedure InitClient(aprofile: UTF8String; asecret_key: UTF8String;
aaccess_key: UTF8String; aregion: UTF8String); override;
[TAmazonMarshallerAttribute('CreateTable')]
function CreateTable(aAmazonDynamoDBRequest: TAmazonDynamoDBRequest)
: TAmazonDynamoDBResponse;
end;
[TAmazonMarshallerAttribute('ProvisionedThroughput')]
TProvisionedThroughput = class(TObject)
protected
private
fsReadCapacityUnits: Integer;
fsWriteCapacityUnits: Integer;
public
published
[TAmazonMarshallerAttribute('ReadCapacityUnits')]
property ReadCapacityUnits: Integer read fsReadCapacityUnits
write fsReadCapacityUnits;
[TAmazonMarshallerAttribute('WriteCapacityUnits')]
property WriteCapacityUnits: Integer read fsWriteCapacityUnits
write fsWriteCapacityUnits;
end;
[TAmazonMarshallerAttribute('KeySchemaElement')]
TKeySchemaElement = class(TObject)
protected
private
fsAttributeName: UTF8String;
fsKeyType: UTF8String;
public
constructor Create(aAttributeName: UTF8String = '';
aKeyType: UTF8String = '');
published
[TAmazonMarshallerAttribute('AttributeName')]
property AttributeName: UTF8String read fsAttributeName
write fsAttributeName;
[TAmazonMarshallerAttribute('KeyType')]
property KeyType: UTF8String read fsKeyType write fsKeyType;
end;
[TAmazonMarshallerAttribute('AttributeDefinition')]
TAttributeDefinition = class(TObject)
protected
private
fsAttributeName: UTF8String;
fsAttributeType: UTF8String;
public
constructor Create(aAttributeName: UTF8String = '';
aAttributeType: UTF8String = '');
published
[TAmazonMarshallerAttribute('AttributeName')]
property AttributeName: UTF8String read fsAttributeName
write fsAttributeName;
[TAmazonMarshallerAttribute('AttributeType')]
property AttributeType: UTF8String read fsAttributeType
write fsAttributeType;
end;
TCreateTableRequest = class(TAmazonDynamoDBRequest)
protected
private
fsTableName: UTF8String;
FAttributeDefinitions: TList<TAttributeDefinition>;
FKeySchema: TList<TKeySchemaElement>;
FProvisionedThroughput: TProvisionedThroughput;
public
constructor Create; override;
destructor Destory;
published
[TAmazonMarshallerAttribute('TableName')]
property TableName: UTF8String read fsTableName write fsTableName;
[TAmazonMarshallerAttribute('AttributeDefinitions')]
property AttributeDefinitions: TList<TAttributeDefinition>
read FAttributeDefinitions write FAttributeDefinitions;
[TAmazonMarshallerAttribute('KeySchema')]
property KeySchema: TList<TKeySchemaElement> read FKeySchema
write FKeySchema;
[TAmazonMarshallerAttribute('ProvisionedThroughput')]
property ProvisionedThroughput: TProvisionedThroughput
read FProvisionedThroughput write FProvisionedThroughput;
end;
implementation
Constructor TAmazonDynamoDBRequest.Create;
begin
targetPrefix := cDynamoDB_targetPrefix;
end;
constructor TKeySchemaElement.Create(aAttributeName: UTF8String = '';
aKeyType: UTF8String = '');
begin
fsAttributeName := aAttributeName;
fsKeyType := aKeyType;
end;
constructor TAttributeDefinition.Create(aAttributeName: UTF8String = '';
aAttributeType: UTF8String = '');
begin
fsAttributeName := aAttributeName;
fsAttributeType := aAttributeType;
end;
constructor TCreateTableRequest.Create;
begin
inherited;
FAttributeDefinitions := TList<TAttributeDefinition>.Create;
FKeySchema := TList<TKeySchemaElement>.Create;
ProvisionedThroughput := TProvisionedThroughput.Create;
end;
destructor TCreateTableRequest.Destory;
begin
FProvisionedThroughput.Free;
FKeySchema.Free;
FAttributeDefinitions.Free;
end;
procedure TAmazonDynamoDBClient.InitClient(aprofile: UTF8String;
asecret_key: UTF8String; aaccess_key: UTF8String; aregion: UTF8String);
begin
inherited InitClient(aprofile, asecret_key, aaccess_key, aregion);
service := cDynamoDB_service;
end;
function TAmazonDynamoDBClient.CreateTable(aAmazonDynamoDBRequest
: TAmazonDynamoDBRequest): TAmazonDynamoDBResponse;
var
FAmazonDynamoDBMarshaller: TAmazonDynamoDBMarshaller;
FAmazonResponse: IAmazonResponse;
begin
Try
aAmazonDynamoDBRequest.operationName := 'CreateTable';
FAmazonDynamoDBMarshaller := TAmazonDynamoDBMarshaller.Create;
aAmazonDynamoDBRequest.request_parameters :=
FAmazonDynamoDBMarshaller.AmazonDynamoDBRequestToJSON
(aAmazonDynamoDBRequest);
FAmazonResponse := MakeRequest(aAmazonDynamoDBRequest, FAmazonRESTClient);
Result := TAmazonDynamoDBResponse.Create(FAmazonResponse);
Finally
FAmazonDynamoDBMarshaller := NIL;
FAmazonResponse := NIl;
End;
end;
function TAmazonDynamoDBMarshaller.AmazonDynamoDBRequestToJSON
(aAmazonDynamoDBRequest: TAmazonDynamoDBRequest): UTF8String;
var
Fctx: TRttiContext;
FJSON: tStringList;
begin
Try
Fctx := TRttiContext.Create;
FJSON := tStringList.Create;
GetSubRttiAttributekeys(FJSON, '', Fctx, aAmazonDynamoDBRequest);
Result := '{' + StringReplace(FJSON.Text, #13#10, '', [rfReplaceAll]) + '}';
Finally
FJSON.Free;
Fctx.Free;
End;
end;
constructor TAmazonDynamoDBResponse.Create(aAmazonResponse: IAmazonResponse);
begin
ResponseText := aAmazonResponse.ResponseText;
ResponseCode := aAmazonResponse.ResponseCode;
Response := aAmazonResponse.Response;
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{ Copyright and license exceptions noted in source }
{ }
{*******************************************************}
unit Posix.ArpaInet;
{$WEAKPACKAGEUNIT}
{$HPPEMIT NOUSINGNAMESPACE}
interface
uses Posix.Base, Posix.NetinetIn, Posix.SysSocket;
{$I ArpaInetAPI.inc}
type
in_port_t = Posix.NetinetIn.in_port_t;
{$EXTERNALSYM in_port_t}
in_addr_t = Posix.NetinetIn.in_addr_t;
{$EXTERNALSYM in_addr_t}
in_addr = Posix.NetinetIn.in_addr;
{$EXTERNALSYM in_addr}
{$IFDEF ANDROID}
function htonl(hostlong: UInt32): UInt32; inline;
{$EXTERNALSYM htonl}
function htons(hostshort: UInt16): UInt16; inline;
{$EXTERNALSYM htons}
function ntohl(netong: UInt32): UInt32; inline;
{$EXTERNALSYM ntohl}
function ntohs(netshort: UInt16): UInt16; inline;
{$EXTERNALSYM ntohs}
{$ELSE}
function htonl(hostlong: UInt32): UInt32; cdecl;
external libc name _PU + 'htonl';
{$EXTERNALSYM htonl}
function htons(hostshort: UInt16): UInt16; cdecl;
external libc name _PU + 'htons';
{$EXTERNALSYM htons}
function ntohl(netong: UInt32): UInt32; cdecl;
external libc name _PU + 'ntohl';
{$EXTERNALSYM ntohl}
function ntohs(netshort: UInt16): UInt16; cdecl;
external libc name _PU + 'ntohs';
{$EXTERNALSYM ntohs}
{$ENDIF ANDROID}
implementation
{$IFDEF ANDROID}
function swap16(x: UInt16): UInt16; inline;
begin
Result := ((x and $ff) shl 8) or ((x and $ff00) shr 8);
end;
function swap32(x: UInt32): UInt32; inline;
begin
Result := ((x and $ff) shl 24) or ((x and $ff00) shl 8) or
((x and $ff0000) shr 8) or ((x and $ff000000) shr 24);
end;
{$IFDEF ARM} // big endian
function htons(hostshort: UInt16): UInt16; inline;
begin
Result := hostshort;
end;
function htonl(hostlong: UInt32): UInt32; inline;
begin
Result := hostlong;
end;
function ntohl(netong: UInt32): UInt32; inline;
begin
Result := netong;
end;
function ntohs(netshort: UInt16): UInt16; inline;
begin
Result := netshort;
end;
{$ELSE} // little endian
function htons(hostshort: UInt16): UInt16; inline;
begin
Result := swap16(hostshort);
end;
function htonl(hostlong: UInt32): UInt32; inline;
begin
Result := swap32(hostlong);
end;
function ntohl(netong: UInt32): UInt32; inline;
begin
Result := swap32(netong);
end;
function ntohs(netshort: UInt16): UInt16; inline;
begin
Result := swap16(netshort);
end;
{$ENDIF ARM}
{$ENDIF ANDROID}
end.
|
{
ID: nhutqua1
PROG: milk2
LANG: PASCAL
}
const fileinp = 'milk2.in';
fileout = 'milk2.out';
var n,max1,max2:longint;
s,e:array[1..5000] of longint;
procedure Init;
var i:longint;
begin
assign(input,fileinp); reset(input);
readln(n);
for i:=1 to n do
readln(s[i],e[i]);
close(input);
end;
procedure Sort;
var i,j,t1,t2:longint;
begin
for i:=1 to n-1 do
for j:=i+1 to n do
if s[i] > s[j] then
begin
t1:=s[i];
t2:=e[i];
s[i]:=s[j];
e[i]:=e[j];
s[j]:=t1;
e[j]:=t2;
end;
end;
procedure Analyse;
var i:longint;
begin
max1:=e[1] - s[1];
max2:=0;
for i:=2 to n do
begin
if (s[i] <= e[i-1]) then
begin
s[i]:=s[i-1];
if e[i-1] > e[i] then e[i]:=e[i-1];
if (e[i] - s[i] > max1) then max1:=e[i]-s[i];
end;
if (s[i] > e[i-1]) then
begin
if s[i] - e[i-1] > max2 then max2:=s[i]-e[i-1];
end;
end;
end;
procedure Print;
begin
assign(output,fileout); rewrite(output);
writeln(max1,' ',max2);
close(output);
end;
begin
Init;
Sort;
Analyse;
Print;
end.
|
{******************************************************************************}
{ }
{ VCLThemeSelector: Form for Preview and Selection of VCL Style }
{ }
{ Copyright (c) 2020 (Ethea S.r.l.) }
{ Author: Carlo Barazzetta }
{ Contributor: Nicola Tambascia }
{ }
{ https://github.com/EtheaDev/VCLThemeSelector }
{ }
{******************************************************************************}
{ }
{ 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 FVCLThemeSelector;
interface
uses
Winapi.Windows
, System.Actions
, System.Classes
, Vcl.ActnList
, Vcl.ExtCtrls
, Vcl.Forms
, Vcl.StdCtrls
, Vcl.Graphics
, Vcl.Controls;
const
VCLThemeSelectorVersion = '1.2.0';
DEFAULT_MAXROWS = 3;
DEFAULT_MAXCOLUMNS = 4;
resourcestring
SELECT_THEME = 'Select Light or Dark theme';
APPLY_THEME = 'Apply';
CANCEL_THEME = 'Cancel';
LIGHT_THEMES = 'Light themes';
DARK_THEMES = 'Dark themes';
PREVIEW_THEME = 'Preview';
THEME_SELECTED = 'New Selected theme: %s';
THEME_PREVIEW_VALUES =
'File'+sLineBreak+
'Edit'+sLineBreak+
'View'+sLineBreak+
'Help'+sLineBreak+
'Text editor'+sLineBreak+
'Normal'+sLineBreak+
'Hot'+sLineBreak+
'Pressed'+sLineBreak+
'Disabled'+sLineBreak+
'Required'+sLineBreak+
'Readonly'+sLineBreak+
'Check'+sLineBreak+
'Page 1'+sLineBreak+
'Page 2'+sLineBreak+
'Page 3'+sLineBreak;
type
TVCLThemeSelectorForm = class(TForm)
LeftScrollBox: TScrollBox;
paButtons: TPanel;
ActionListAppereance: TActionList;
acApplyStyle: TAction;
acCancel: TAction;
LeftFlowPanel: TFlowPanel;
StyleLabel: TPanel;
paRight: TPanel;
btApply: TButton;
btCancel: TButton;
RightScrollBox: TScrollBox;
RightFlowPanel: TFlowPanel;
TopPanel: TPanel;
LightPanel: TPanel;
DarkPanel: TPanel;
procedure SelectionClick(Sender: TObject);
procedure acApplyStyleExecute(Sender: TObject);
procedure acCancelExecute(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure acApplyStyleUpdate(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ScrollBoxMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
procedure FormAfterMonitorDpiChanged(Sender: TObject; OldDPI,
NewDPI: Integer);
private
FPreviousStyleName : string;
FStyleName : string;
FExcludeWindows: Boolean;
FMaxRows: Integer;
FMaxColumns: Integer;
procedure UpdateLabel;
procedure UpdateButtons;
procedure BuildPreviewPanels;
protected
procedure Loaded; override;
public
constructor Create(AOwner: TComponent); override;
constructor CreatePreview(AOwner: TComponent;
const AExcludeWindows: Boolean;
const AMaxRows: Integer = DEFAULT_MAXROWS;
const AMaxColumns: Integer = DEFAULT_MAXCOLUMNS);
end;
//Class to register Theme attributes (like dark or light)
TThemeType = (ttLight, ttDark);
TThemeAttribute = class
StyleName: String;
ThemeType: TThemeType;
EditRequiredColor: TColor;
EditReadonlyColor: TColor;
end;
//function to get Theme Attributes
function GetStyleAttributes(const AStyleName: string;
out AThemeAttribute: TThemeAttribute): Boolean;
//function to launch form
function ShowVCLThemeSelector(var AStyleName: string;
const AExcludeWindows: Boolean = False;
const AMaxRows: Integer = DEFAULT_MAXROWS;
const AMaxColumns: Integer = DEFAULT_MAXCOLUMNS): boolean;
//Utilities to read/write application preferences from/to Registry
function ReadAppStyleFromReg(const CompanyName, ApplicationName: string) : string;
procedure WriteAppStyleToReg(const CompanyName, ApplicationName, AppStyle : string);
procedure ReadAppStyleAndFontFromReg(const CompanyName, ApplicationName: string;
out AAppStyle: string; const AFont: TFont);
procedure WriteAppStyleAndFontToReg(const CompanyName, ApplicationName: string;
const AAppStyle: string; const AFont: TFont);
implementation
{$R *.dfm}
uses
Vcl.Themes
{$IF CompilerVersion > 33}
, CBVCLStylePreviewForm
{$ENDIF}
, CBVCLStylePreview
, Winapi.Messages
, System.UITypes
, System.SysUtils
, System.Win.Registry
, System.Math
, System.Generics.Collections;
var
ThemeAttributes: TList<TThemeAttribute>;
function GetStyleAttributes(const AStyleName: string;
out AThemeAttribute: TThemeAttribute): Boolean;
var
LThemeAttribute: TThemeAttribute;
begin
for LThemeAttribute in ThemeAttributes do
begin
if SameText(AStyleName, LThemeAttribute.StyleName) then
begin
AThemeAttribute := LThemeAttribute;
Exit(True);
end;
end;
Result := False;
AThemeAttribute := nil;
end;
procedure FreeThemesAttributes;
var
LThemeAttribute: TThemeAttribute;
begin
for LThemeAttribute in ThemeAttributes do
LThemeAttribute.Free;
ThemeAttributes.Free;
end;
procedure RegisterThemeAttributes(
const AVCLStyleName: string;
const AThemeType: TThemeType;
const AEditRequiredColor: TColor;
const AEditReadonlyColor: TColor);
var
LThemeAttribute: TThemeAttribute;
procedure UpdateThemeAttributes;
begin
LThemeAttribute.StyleName := AVCLStyleName;
LThemeAttribute.ThemeType := AThemeType;
LThemeAttribute.EditRequiredColor := StyleServices.GetSystemColor(AEditRequiredColor);
LThemeAttribute.EditReadonlyColor := StyleServices.GetSystemColor(AEditReadonlyColor);
end;
begin
for LThemeAttribute in ThemeAttributes do
begin
if SameText(LThemeAttribute.StyleName, AVCLStyleName) then
begin
UpdateThemeAttributes;
Exit; //Found: exit
end;
end;
//not found
LThemeAttribute := TThemeAttribute.Create;
ThemeAttributes.Add(LThemeAttribute);
UpdateThemeAttributes;
end;
procedure InitDefaultThemesAttributes;
begin
ThemeAttributes := TList<TThemeAttribute>.Create;
if StyleServices.Enabled then
begin
//Non themed Windows Style
RegisterThemeAttributes('Windows',ttLight, clInfoBk, clWebLightgrey);
//High-DPI Themes (Delphi 10.4)
RegisterThemeAttributes('Aqua Light Slate' ,ttLight, clWebLightYellow , clWebLightgrey);
RegisterThemeAttributes('Copper' ,ttLight, clWebLightCoral , clWebLightgrey);
RegisterThemeAttributes('CopperDark' ,ttDark , clWebDarkSlategray, clDkGray );
RegisterThemeAttributes('Coral' ,ttLight, clWebLightCoral , clWebLightgrey);
RegisterThemeAttributes('Diamond' ,ttLight, clWebLightYellow , clWebLightgrey);
RegisterThemeAttributes('Emerald' ,ttLight, clWebLightGreen , clWebLightgrey);
RegisterThemeAttributes('Glow' ,ttDark , clWebDarkSlategray, clWebDarkGray );
RegisterThemeAttributes('Iceberg Classico' ,ttLight, clWebLightSkyBlue , clWebLightgrey);
RegisterThemeAttributes('Lavender Classico' ,ttLight, clWebLightSteelBlue,clWebLightgrey);
RegisterThemeAttributes('Sky' ,ttLight, clWebLightYellow , clWebLightgrey);
RegisterThemeAttributes('Slate Classico' ,ttLight, clWebLightYellow , clWebLightgrey);
RegisterThemeAttributes('Sterling' ,ttLight, clWebLightYellow , clWebLightgrey);
RegisterThemeAttributes('Tablet Dark' ,ttDark , clWebDarkSlategray, clWebDarkGray);
RegisterThemeAttributes('Tablet Light' ,ttLight, clWebLightYellow , clWebLightgrey);
RegisterThemeAttributes('Windows10' ,ttLight, clWebLightYellow , clWebAliceBlue);
RegisterThemeAttributes('Windows10 Blue' ,ttDark, clWebLightSkyBlue , clWebLightgrey);
RegisterThemeAttributes('Windows10 Dark' ,ttDark, clWebDarkBlue , clWebDarkGray );
RegisterThemeAttributes('Windows10 Green' ,ttDark, clWebLightGreen , clWebLightgrey);
RegisterThemeAttributes('Windows10 Purple' ,ttDark, clWebLightPink , clWebLightgrey);
RegisterThemeAttributes('Windows10 SlateGray',ttDark, clWebDarkSlategray, clDkGray );
RegisterThemeAttributes('Glossy' ,ttDark, clWebDarkSlategray, clDkGray );
RegisterThemeAttributes('Windows10 BlackPearl',ttDark, clWebFirebrick , clDkGray );
RegisterThemeAttributes('Windows10 Blue Whale',ttDark, clWebDarkSlategray, clDkGray );
RegisterThemeAttributes('Windows10 Clear Day',ttLight, clWebLightYellow , clWebLightgrey);
RegisterThemeAttributes('Windows10 Malibu' ,ttLight, clWebLightYellow , clWebLightgrey);
//Non High DPI Themes
RegisterThemeAttributes('Amakrits' ,ttDark , clWebDarkSlategray, clDkGray );
RegisterThemeAttributes('Amethyst Kamri' ,ttLight, clWebLightYellow , clWebLightgrey);
RegisterThemeAttributes('Auric' ,ttDark , clWebDarkSlategray, clDkGray );
RegisterThemeAttributes('Carbon' ,ttDark , clWebDarkSlategray, clDkGray );
RegisterThemeAttributes('Cyan Dusk' ,ttLight, clWebLightYellow , clWebLightgrey);
RegisterThemeAttributes('Charcoal Dark Slate',ttDark , clWebDarkSlategray, clDkGray );
RegisterThemeAttributes('Luna' ,ttLight, clWebLightYellow , clWebLightgrey);
RegisterThemeAttributes('Material Oxford Blue',ttDark, clWebDarkSlategray, clDkGray );
RegisterThemeAttributes('Onyx Blue' ,ttDark , clWebDarkSlategray, clDkGray );
RegisterThemeAttributes('Ruby Graphite' ,ttDark , clWebDarkRed, clDkGray );
RegisterThemeAttributes('Sapphire Kamri' ,ttLight, clWebLightYellow , clWebLightgrey);
RegisterThemeAttributes('Smokey Quartz Kamri',ttLight, clWebLightYellow , clWebLightgrey);
RegisterThemeAttributes('Turquoise Gray' ,ttLight, clWebLightYellow , clWebLightgrey);
RegisterThemeAttributes('Windows10 Blue Whale LE',ttDark,clWebLightYellow, clDkGray );
end;
end;
procedure ReadAppStyleAndFontFromReg(const CompanyName, ApplicationName: string;
out AAppStyle: string; const AFont: TFont);
var
FRegistry : TRegistry;
RegistryKey : string;
begin
FRegistry := TRegistry.Create(KEY_ALL_ACCESS);
try
FRegistry.RootKey := HKEY_CURRENT_USER;
RegistryKey := Format('\Software\%s\%s',[CompanyName, ApplicationName]);
FRegistry.OpenKey(RegistryKey, True);
//Read Application Style
AAppStyle := FRegistry.ReadString('AppStyle');
if AAppStyle = '' then
AAppStyle := 'Windows';
//Read font attributes
if Assigned(AFont) then
begin
if FRegistry.ValueExists('FontName') then
AFont.Name := FRegistry.ReadString('FontName');
if FRegistry.ValueExists('FontHeight') then
AFont.Height := FRegistry.ReadInteger('FontHeight');
if FRegistry.ValueExists('FontColor') then
AFont.Color := TColor(FRegistry.ReadInteger('FontColor'));
end;
finally
FRegistry.Free;
end;
end;
procedure WriteAppStyleAndFontToReg(const CompanyName, ApplicationName: string;
const AAppStyle: string; const AFont: TFont);
var
FRegistry : TRegistry;
RegistryKey : string;
begin
FRegistry := TRegistry.Create(KEY_ALL_ACCESS);
try
RegistryKey := Format('\Software\%s\%s',[CompanyName, ApplicationName]);
FRegistry.RootKey := HKEY_CURRENT_USER;
FRegistry.OpenKey(RegistryKey, True);
FRegistry.WriteString('AppStyle',AAppStyle);
if Assigned(AFont) then
begin
FRegistry.WriteString('FontName',AFont.Name);
FRegistry.WriteInteger('FontHeight',AFont.Height);
FRegistry.WriteInteger('FontColor',AFont.Color);
FRegistry.WriteBool('FontBold',fsBold in AFont.Style);
FRegistry.WriteBool('FontItalic',fsItalic in AFont.Style);
FRegistry.WriteBool('FontUnderline',fsUnderline in AFont.Style);
FRegistry.WriteBool('FontStrikeOut',fsStrikeOut in AFont.Style);
end;
finally
FRegistry.Free;
end;
end;
function ReadAppStyleFromReg(const CompanyName, ApplicationName: string) : string;
var
LFont: TFont;
begin
LFont := nil;
ReadAppStyleAndFontFromReg(CompanyName, ApplicationName, Result, LFont);
end;
procedure WriteAppStyleToReg(const CompanyName, ApplicationName, AppStyle : string);
begin
WriteAppStyleAndFontToReg(CompanyName, ApplicationName, AppStyle, nil);
end;
function ShowVCLThemeSelector(var AStyleName: string;
const AExcludeWindows: Boolean = False;
const AMaxRows: Integer = DEFAULT_MAXROWS;
const AMaxColumns: Integer = DEFAULT_MAXCOLUMNS): boolean;
var
fmVCLStyleSelector: TVCLThemeSelectorForm;
begin
Screen.Cursor := crHourGlass;
Try
fmVCLStyleSelector := TVCLThemeSelectorForm.CreatePreview(nil,
AExcludeWindows, AMaxRows, AMaxColumns);
try
Screen.Cursor := crDefault;
Result := (fmVCLStyleSelector.ShowModal = mrOk);
if Result then
AStyleName := fmVCLStyleSelector.FStyleName;
finally
fmVCLStyleSelector.Free;
end;
Finally
Screen.Cursor := crDefault;
End;
end;
procedure TVCLThemeSelectorForm.acApplyStyleExecute(Sender: TObject);
begin
inherited;
ModalResult := mrOk;
end;
procedure TVCLThemeSelectorForm.acApplyStyleUpdate(Sender: TObject);
begin
inherited;
acApplyStyle.Enabled := (FPreviousStyleName <> FStyleName);
end;
procedure TVCLThemeSelectorForm.acCancelExecute(Sender: TObject);
begin
inherited;
ModalResult := mrCancel;
end;
constructor TVCLThemeSelectorForm.Create(AOwner: TComponent);
begin
inherited;
FMaxRows := DEFAULT_MAXROWS;
FMaxColumns := DEFAULT_MAXCOLUMNS;
end;
constructor TVCLThemeSelectorForm.CreatePreview(
AOwner: TComponent; const AExcludeWindows: Boolean;
const AMaxRows: Integer = DEFAULT_MAXROWS;
const AMaxColumns: Integer = DEFAULT_MAXCOLUMNS);
begin
FExcludeWindows := AExcludeWindows;
FMaxRows := AMaxRows;
FMaxColumns := AMaxColumns;
inherited Create(AOwner);
end;
procedure TVCLThemeSelectorForm.BuildPreviewPanels;
var
i : Integer;
LStyleName, LActiveStyleName: string;
LStyleNames: TStringList;
LpnPreview: TPanel;
LpnButton: TButton;
{$IF CompilerVersion > 33}
LVCLPreviewForm: TCBVCLPreviewForm;
{$ENDIF}
LVCLPreview: TCBVclStylesPreview;
LCountStyle, LCountLight, LCountDark: Integer;
LNumRows : integer;
LCalcHeight, LCalcWidth : Integer;
LHeight, LWidth : Integer;
LMonitor: TMonitor;
LMonitorMargin: Integer;
LScrollBarWidth: Integer;
LThemeAttribute: TThemeAttribute;
LIsLight: Boolean;
const
MARGIN = 4;
begin
LActiveStyleName := TStyleManager.ActiveStyle.Name;
LStyleNames := TStringList.Create;
LCountStyle := 0;
LCountLight := 0;
LCountDark := 0;
LpnPreview := nil;
try
for i := 0 to High(TStyleManager.StyleNames) do
LStyleNames.Add(TStyleManager.StyleNames[i]);
LStyleNames.Sort;
for i := 0 to LStyleNames.Count -1 do
begin
LStyleName := LStyleNames.Strings[i];
//Jump Windows Style if requested
if FExcludeWindows and (LStyleName = 'Windows') then
Continue;
GetStyleAttributes(LStyleName, LThemeAttribute);
if Assigned(LThemeAttribute) then
LIsLight := LThemeAttribute.ThemeType = ttLight
else
LIsLight := True;
if LIsLight then
begin
LpnPreview := TPanel.Create(LeftFlowPanel);
Inc(LCountLight);
end
else
begin
LpnPreview := TPanel.Create(RightFlowPanel);
Inc(LCountDark);
end;
Inc(LCountStyle);
//First assign size
LpnPreview.Height := PREVIEW_HEIGHT;
LpnPreview.Width := PREVIEW_WIDTH;
LpnPreview.Margins.Left := MARGIN;
LpnPreview.Margins.Top := MARGIN;
LpnPreview.Margins.Bottom := MARGIN;
LpnPreview.Margins.Right := MARGIN;
//Then parent the control, so it is scaled correctly
if LIsLight then
LpnPreview.Parent := LeftFlowPanel
else
LpnPreview.Parent := RightFlowPanel;
LpnPreview.Align := alLeft;
LpnPreview.AlignWithMargins := True;
LpnButton := TButton.Create(LpnPreview);
LpnButton.Parent := LpnPreview;
LpnButton.Align := alTop;
LpnButton.OnClick := SelectionClick;
LpnButton.Caption := LStyleName;
LpnButton.Cursor := crHandPoint;
{$IF CompilerVersion > 33}
if TStyleManager.ActiveStyle.Name = 'Windows' then
begin
//If the application Style is "Windows" cannot use per-control styles
LVCLPreviewForm := nil;
LVCLPreview := TCBVclStylesPreview.Create(LpnPreview);
end
else
begin
//Use per-control styles
LVCLPreview := nil;
LVCLPreviewForm := TCBVCLPreviewForm.Create(LpnPreview);
LVCLPreviewForm.Caption := PREVIEW_THEME;
LVCLPreviewForm.SetCaptions(THEME_PREVIEW_VALUES);
LVCLPreviewForm.CustomStyle := TStyleManager.Style[LStyleName];
if Assigned(LThemeAttribute) then
begin
LVCLPreviewForm.FRequiredTextEdit.StyleElements := [seBorder];
LVCLPreviewForm.FRequiredTextEdit.Color := LThemeAttribute.EditRequiredColor;
LVCLPreviewForm.FRequiredTextEdit.Font.Color := TStyleManager.Style[LStyleName].GetSystemColor(clWindowText);
LVCLPreviewForm.FReadonlyTextEdit.StyleElements := [seBorder];
LVCLPreviewForm.FReadonlyTextEdit.Color := LThemeAttribute.EditReadonlyColor;
LVCLPreviewForm.FReadonlyTextEdit.Font.Color := TStyleManager.Style[LStyleName].GetSystemColor(clWindowText);
end;
LVCLPreviewForm.Parent := LpnPreview;
LVCLPreviewForm.Align := alClient;
if LStyleName = 'Windows' then
begin
LVCLPreviewForm.StyleElements := [];
LVCLPreviewForm.TabControl.StyleElements := [];
end;
end;
{$ELSE}
//Before 10.4 cannot use per-control styles
LVCLPreview := TCBVclStylesPreview.Create(LpnPreview);
{$ENDIF}
if Assigned(LVCLPreview) then
begin
LVCLPreview.Caption := PREVIEW_THEME;
LVCLPreview.SetEditColors(LThemeAttribute.EditRequiredColor,
LThemeAttribute.EditReadonlyColor);
LVCLPreview.SetCaptions(THEME_PREVIEW_VALUES);
LVCLPreview.Parent := LpnPreview;
LVCLPreview.CustomStyle := TStyleManager.Style[LStyleName];
LVCLPreview.Align := alClient;
end;
if SameText(LStyleName, LActiveStyleName) then
begin
FPreviousStyleName := LStyleName;
FStyleName := LStyleName;
LpnButton.Font.Style := [fsBold];
end;
{$IF CompilerVersion > 33}
if Assigned(LVCLPreviewForm) then
LVCLPreviewForm.FormShow(LVCLPreview);
{$ENDIF}
end;
if LCountLight > LCountDark then
begin
RightScrollBox.Align := alRight;
LeftScrollBox.Align := alClient;
end;
if (LCountStyle mod FMaxColumns) <> 0 then
LNumRows := (LCountStyle div FMaxColumns) + 1
else
LNumRows := (LCountStyle div FMaxColumns);
Self.Constraints.MaxHeight := Screen.Height;
LHeight := (LpnPreview.Height+(LpnPreview.Margins.Top+LpnPreview.Margins.Bottom*2));
LWidth := (LpnPreview.Width+(LpnPreview.Margins.Left+LpnPreview.Margins.Right*2));
LCalcHeight := (LHeight*Min(LNumRows, FMaxRows))+paButtons.Height + TopPanel.Height;
LCalcWidth := (LWidth*FMaxColumns);
LMonitor := Screen.MonitorFromWindow(Self.Handle);
LMonitorMargin := 100;
//Check Max height available
if (LCalcHeight > LMonitor.Height - LMonitorMargin) or
(LNumRows > FMaxRows) or
(LCalcWidth > LMonitor.Width - LMonitorMargin) then
begin
//Show scrollbar
LScrollBarWidth := GetSystemMetrics(SM_CXVSCROLL);
LCalcHeight := Min(LHeight * FMaxRows + paButtons.Height + TopPanel.Height,
LMonitor.Height - LMonitorMargin);
Self.Constraints.MinHeight := LCalcHeight;
Self.ClientHeight := LCalcHeight;
LeftScrollBox.VertScrollBar.Visible := True;
RightScrollBox.VertScrollBar.Visible := True;
i := FMaxColumns;
while True do
begin
LCalcWidth := LWidth * i + (LScrollBarWidth * 2) + 6;
if LCalcWidth <= LMonitor.Width - LMonitorMargin then
break
else
Dec(i);
end;
Self.Constraints.MinWidth := LCalcWidth;
Self.ClientWidth := LCalcWidth;
end
else
begin
LeftScrollBox.VertScrollBar.Visible := False;
RightScrollBox.VertScrollBar.Visible := False;
//Self.BorderStyle := bsDialog;
Self.Constraints.MinHeight := LCalcHeight;
Self.ClientHeight := LCalcHeight;
if LCountStyle < FMaxColumns then
begin
Self.Constraints.MinWidth := (LWidth*LCountStyle);
Self.ClientWidth := (LWidth*LCountStyle);
end
else
begin
Self.Constraints.MinWidth := LWidth*FMaxColumns;
Self.ClientWidth := LWidth*FMaxColumns;
end;
end;
finally
LStyleNames.Free;
end;
end;
procedure TVCLThemeSelectorForm.FormAfterMonitorDpiChanged(Sender: TObject;
OldDPI, NewDPI: Integer);
begin
if ParentFont and (Application.MainForm.Monitor.Handle <> Self.Monitor.Handle) then
Font.Height := MulDiv(Font.Height, NewDPI, OldDPI);
end;
procedure TVCLThemeSelectorForm.FormCreate(Sender: TObject);
begin
Caption := SELECT_THEME;
acApplyStyle.Caption := APPLY_THEME;
acCancel.Caption := CANCEL_THEME;
LightPanel.Caption := LIGHT_THEMES;
DarkPanel.Caption := DARK_THEMES;
UpdateButtons;
UpdateLabel;
end;
procedure TVCLThemeSelectorForm.UpdateButtons;
begin
btApply.Action := acApplyStyle;
btCancel.Action := acCancel;
end;
procedure TVCLThemeSelectorForm.UpdateLabel;
begin
if FPreviousStyleName <> FStyleName then
begin
StyleLabel.Caption := Format(THEME_SELECTED,[FStyleName]);
StyleLabel.Visible := True;
end
else
StyleLabel.Visible := False;
end;
procedure TVCLThemeSelectorForm.FormResize(Sender: TObject);
begin
inherited;
LeftFlowPanel.Height := ClientRect.Bottom-ClientRect.Top-paButtons.Height;
RightFlowPanel.Height := LeftFlowPanel.Height;
LightPanel.Width := ClientWidth div 2 -1;
if RightScrollBox.Align = alClient then
begin
LeftScrollBox.Width := ClientWidth div 2;
LeftScrollBox.VertScrollBar.Range := RightScrollBox.VertScrollBar.Range;
end
else
begin
RightScrollBox.Width := ClientWidth div 2;
RightScrollBox.VertScrollBar.Range := LeftScrollBox.VertScrollBar.Range;
end;
end;
procedure TVCLThemeSelectorForm.Loaded;
begin
ParentFont := False;
//Note: the form uses Screen.IconFont by default
Font.Name := Screen.IconFont.Name;
Font.Height := Muldiv(Screen.IconFont.Height, 96, Screen.IconFont.PixelsPerInch);
{$IFDEF D10_1+}
OnAfterMonitorDpiChanged := FormAfterMonitorDpiChanged;
{$ENDIF}
inherited;
//Build Preview panels
BuildPreviewPanels;
end;
procedure TVCLThemeSelectorForm.SelectionClick(Sender: TObject);
var
LButton: TButton;
LPanel: TPanel;
I, J : integer;
begin
if (Sender is TButton) then
begin
LButton := TButton(Sender);
FStyleName := LButton.Caption;
LButton.Font.Style := [fsBold];
for I := 0 to LeftFlowPanel.ComponentCount-1 do
begin
if (LeftFlowPanel.Components[I] is TPanel) then
begin
LPanel := TPanel(LeftFlowPanel.Components[I]);
for J := 0 to LPanel.ComponentCount-1 do
begin
if (LPanel.Components[J] is TButton) and (LButton <> LPanel.Components[J]) then
TButton(LPanel.Components[J]).Font.Style := [];
end;
end;
end;
UpdateLabel;
if btApply.CanFocus then
btApply.SetFocus;
end;
end;
procedure TVCLThemeSelectorForm.ScrollBoxMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
Var
msg: Cardinal;
code: Cardinal;
i, n: Integer;
begin
Handled := true;
If ssShift In Shift Then
msg := WM_HSCROLL
Else
msg := WM_VSCROLL;
If WheelDelta > 0 Then
code := SB_LINEUP
Else
code := SB_LINEDOWN;
n := Mouse.WheelScrollLines * 4; //Speed Up scrolling
For i:= 1 to n Do
begin
LeftScrollBox.Perform( msg, code, 0 );
RightScrollBox.Perform( msg, code, 0 );
end;
LeftScrollBox.Perform( msg, SB_ENDSCROLL, 0 );
RightScrollBox.Perform( msg, SB_ENDSCROLL, 0 );
end;
initialization
InitDefaultThemesAttributes;
finalization
FreeThemesAttributes;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLCurvesAndSurfaces<p>
Bezier and B-Spline Curve and Surface Routines.<p>
<b>History : </b><font size=-1><ul>
<li>10/11/12 - PW - Added CPP compatibility: changed vector arrays to records
<li>31/03/07 - DaStr - Added $I GLScene.inc
<li>11/05/04 - SG - Some fixes for BSpline calculations (rational BSplines
are still still broken). Minor knot vector changes.
<li>20/08/03 - SG - Removed weights realizing it's an inefficient way
to do things, control points should be weighted
before being used to calculate a surface or curve.
<li>18/08/03 - SG - Added weights to calculations.
<li>17/07/03 - SG - Added surface routines.
Minor changes to procedure parameters.
<li>10/07/03 - SG - Creation
</ul></font>
}
unit GLCurvesAndSurfaces;
interface
{$I GLScene.inc}
uses
GLVectorGeometry, GLVectorLists;
type
TBSplineContinuity = (bscUniformNonPeriodic, bscUniformPeriodic);
function BezierCurvePoint(t : single; n : integer; cp : PAffineVectorArray) : TAffineVector;
function BezierSurfacePoint(s,t : single; m,n : integer; cp : PAffineVectorArray) : TAffineVector;
procedure GenerateBezierCurve(Steps : Integer; ControlPoints, Vertices : TAffineVectorList);
procedure GenerateBezierSurface(Steps, Width, Height : Integer; ControlPoints, Vertices : TAffineVectorList);
function BSplinePoint(t : single; n,k : integer; knots : PSingleArray; cp : PAffineVectorArray) : TAffineVector;
function BSplineSurfacePoint(s,t : single; m,n,k1,k2 : integer; uknots, vknots : PSingleArray; cp : PAffineVectorArray) : TAffineVector;
procedure GenerateBSpline(Steps,Order : Integer; KnotVector : TSingleList; ControlPoints, Vertices : TAffineVectorList);
procedure GenerateBSplineSurface(Steps, UOrder, VOrder, Width, Height : Integer; UKnotVector, VKnotVector : TSingleList; ControlPoints, Vertices : TAffineVectorList);
procedure GenerateKnotVector(KnotVector : TSingleList; NumberOfPoints, Order : Integer; Continuity : TBSplineContinuity);
implementation
uses SysUtils;
function Factorial(n : Integer) : Single;
var
i : integer;
begin
if (n<0) or (n>32) then
Exception.Create('Invalid factorial parameter: n = '+IntToStr(n));
Result:=1;
for i:=2 to n do
Result:=Result*i;
end;
// ------------------------------------------------------------
// Bezier routines
// ------------------------------------------------------------
function BernsteinBasis(n,i : Integer; t : Single) : Single;
var
ti, tni : Single;
begin
if (t=0) and (i=0) then ti:=1 else ti:=PowerInteger(t,i);
if (n=i) and (t=1) then tni:=1 else tni:=PowerInteger(1-t,Integer(n-i));
Result:=(Factorial(n)/(Factorial(i)*Factorial(n-i)))*ti*tni;
end;
function BezierCurvePoint(t : single; n : integer; cp : PAffineVectorArray) : TAffineVector;
var
i : integer;
b : Single;
begin
Result:=NullVector;
for i:=0 to n-1 do begin
b:=BernsteinBasis(n-1,i,t);
Result.V[0]:=Result.V[0]+cp[i].V[0]*b;
Result.V[1]:=Result.V[1]+cp[i].V[1]*b;
Result.V[2]:=Result.V[2]+cp[i].V[2]*b;
end;
end;
function BezierSurfacePoint(s,t : single; m,n : integer; cp : PAffineVectorArray) : TAffineVector;
var
i,j : integer;
b1,b2 : Single;
begin
Result:=NullVector;
for j:=0 to n-1 do
for i:=0 to m-1 do begin
b1:=BernsteinBasis(m-1,i,s);
b2:=BernsteinBasis(n-1,j,t);
Result.V[0]:=Result.V[0]+cp[j*m+i].V[0]*b1*b2;
Result.V[1]:=Result.V[1]+cp[j*m+i].V[1]*b1*b2;
Result.V[2]:=Result.V[2]+cp[j*m+i].V[2]*b1*b2;
end;
end;
procedure GenerateBezierCurve(Steps : Integer; ControlPoints, Vertices : TAffineVectorList);
var
i : Integer;
begin
Vertices.Count:=Steps;
for i:=0 to Steps-1 do
Vertices[i]:=BezierCurvePoint(i/(Steps-1),ControlPoints.Count,ControlPoints.List);
end;
procedure GenerateBezierSurface(Steps, Width, Height : Integer; ControlPoints, Vertices : TAffineVectorList);
var
i,j : Integer;
begin
Vertices.Count:=Steps*Steps;
for j:=0 to Steps-1 do
for i:=0 to Steps-1 do
Vertices[i+j*Steps]:=BezierSurfacePoint(i/(Steps-1),j/(Steps-1),Width,Height,ControlPoints.List);
end;
// ------------------------------------------------------------
// B-Spline routines
// ------------------------------------------------------------
function BSplineBasis(i,k,n : integer; u : Single; knots : PSingleArray) : Single;
var
v1,v2 : single;
begin
if (u<knots[i]) or (u>knots[i+k]) then begin
Result:=0;
end else if k=1 then begin
Result:=0;
if (u>=knots[i]) and (u<knots[i+1]) then
Result:=1;
end else if (i=n-1) and (u = knots[i+k]) then begin
Result:=1;
end else begin
v1:=(knots[i+k-1]-knots[i]);
v2:=(knots[i+k]-knots[i+1]);
if v1<>0 then
v1:=(u-knots[i])/v1*BSplineBasis(i,k-1,n,u,knots);
if v2<>0 then
v2:=(knots[i+k]-u)/v2*BSplineBasis(i+1,k-1,n,u,knots);
Result:=v1+v2;
end;
end;
function BSplinePoint(t : single; n,k : integer; knots : PSingleArray; cp : PAffineVectorArray) : TAffineVector;
var
i : integer;
b : array of Single;
det : Single;
begin
SetLength(b,n);
for i:=0 to n-1 do b[i]:=BSplineBasis(i,k,n,t,knots);
det:=0;
for i:=0 to n-1 do det:=det+b[i];
Result:=NullVector;
for i:=0 to n-1 do begin
if det<>0 then b[i]:=b[i]/det else b[i]:=0;
Result.V[0]:=Result.V[0]+cp[i].V[0]*b[i];
Result.V[1]:=Result.V[1]+cp[i].V[1]*b[i];
Result.V[2]:=Result.V[2]+cp[i].V[2]*b[i];
end;
SetLength(b,0);
end;
function BSplineSurfacePoint(s,t : single; m,n,k1,k2 : integer; uknots, vknots : PSingleArray; cp : PAffineVectorArray) : TAffineVector;
var
i,j : integer;
b1,b2 : array of Single;
det1,det2 : Single;
begin
SetLength(b1,m);
SetLength(b2,n);
det1:=0; det2:=0;
for i:=0 to m-1 do b1[i]:=BSplineBasis(i,k1,m,s,uknots);
for i:=0 to n-1 do b2[i]:=BSplineBasis(i,k2,n,t,vknots);
for i:=0 to m-1 do det1:=det1+b1[i];
for i:=0 to n-1 do det2:=det2+b2[i];
Result:=NullVector;
for j:=0 to n-1 do begin
if det2<>0 then b2[j]:=b2[j]/det2 else b2[j]:=0;
for i:=0 to m-1 do begin
if det1<>0 then b1[i]:=b1[i]/det1 else b1[i]:=0;
Result.V[0]:=Result.V[0]+cp[j*m+i].V[0]*b1[i]*b2[j];
Result.V[1]:=Result.V[1]+cp[j*m+i].V[1]*b1[i]*b2[j];
Result.V[2]:=Result.V[2]+cp[j*m+i].V[2]*b1[i]*b2[j];
end;
end;
end;
procedure GenerateBSpline(Steps,Order : Integer; KnotVector : TSingleList; ControlPoints, Vertices : TAffineVectorList);
var
i : Integer;
begin
Vertices.Clear;
Vertices.Count:=Steps;
for i:=0 to Steps-1 do
Vertices[i]:=BSplinePoint(i/(Steps-1),ControlPoints.Count,Order+1,@KnotVector.List[0],ControlPoints.List);
end;
procedure GenerateBSplineSurface(Steps, UOrder, VOrder, Width, Height : Integer; UKnotVector, VKnotVector : TSingleList; ControlPoints, Vertices : TAffineVectorList);
var
i,j : Integer;
begin
Vertices.Clear;
Vertices.Count:=Steps*Steps;
for j:=0 to Steps-1 do
for i:=0 to Steps-1 do
Vertices[i+j*Steps]:=BSplineSurfacePoint(i/(Steps-1),j/(Steps-1),Width,Height,UOrder+1,VOrder+1,@UKnotVector.List[0],@VKnotVector.List[0],ControlPoints.List);
end;
procedure GenerateKnotVector(KnotVector : TSingleList; NumberOfPoints, Order : Integer; Continuity : TBSplineContinuity);
var
i,n,k : integer;
begin
KnotVector.Clear;
k:=Order+1;
n:=NumberOfPoints-1;
case Continuity of
// Open curve
bscUniformNonPeriodic : begin
for i:=0 to n+k do begin
if i<k then KnotVector.Add(0)
else if i>n then KnotVector.Add(n-k+2)
else KnotVector.Add(i-k+1);
end;
end;
// Closed curve
bscUniformPeriodic : begin
for i:=0 to n+k do begin
KnotVector.Add(i);
end;
KnotVector.Scale(1/KnotVector.Sum);
end;
end;
end;
end.
|
{***********************************<_INFO>************************************}
{ <Проект> Медиа-сервер }
{ }
{ <Область> 16:Медиа-контроль }
{ }
{ <Задача> Медиа-источник, предоставляющий видео-данные путем снимков }
{ экрана }
{ }
{ <Автор> Фадеев Р.В. }
{ }
{ <Дата> 14.01.2011 }
{ }
{ <Примечание> Нет примечаний. }
{ }
{ <Атрибуты> ООО НПП "Спецстрой-Связь", ООО "Трисофт" }
{ }
{***********************************</_INFO>***********************************}
unit MediaServer.Stream.Source.ScreenCapture;
interface
uses Windows, SysUtils, Classes, SyncObjs,uBaseClasses,
MediaServer.Stream.Source,
MediaProcessing.Definitions;
type
//Класс, выполняющий непосредственно получение данных (видеопотока) из камеры
TMediaServerSourceScreenCapture = class (TMediaServerSource)
private
FEmitThread : TThreadObjectVar<TThread>;
FFps: integer;
procedure OnFrameReceived(const aFormat: TMediaStreamDataHeader;
aData: pointer; aDataSize:cardinal;
aInfo: pointer; aInfoSize: cardinal);
protected
function GetStreamType(aMediaType: TMediaType): TStreamType; override;
public
constructor Create(aFps: integer); overload;
destructor Destroy; override;
procedure DoOpen(aSync: boolean); override;
procedure DoClose; override;
procedure WaitWhileConnecting(aTimeout: integer); override;
function Opened: Boolean; override;
function Name: string; override;
function DeviceType: string; override;
function ConnectionString: string; override;
function StreamInfo: TBytes; override;
function PtzSupported: boolean; override;
//property Framer: TStreamFramer read FFramer;
end;
implementation
uses Math,Forms,Graphics, MediaServer.Workspace,uTrace,MediaStream.FramerFactory,ThreadNames,
IdGlobal;
type
TScreenCaptureThread = class (TThread)
private
FCurrentBmpInfoHeader: TBitmapInfoHeader;
FOwner: TMediaServerSourceScreenCapture;
FOpenLock: TCriticalSection;
FMemDC : HDC;
FBitmap : HBITMAP;
FDib: pointer;
procedure PrepareBitmap;
function StreamInfo: TBytes;
//function StreamType: TStreamType;
protected
procedure Capture;
procedure Execute; override;
public
constructor Create(aOwner: TMediaServerSourceScreenCapture);
destructor Destroy; override;
end;
function GetCaptureThread(aThread : TThreadObjectVar<TThread>): TScreenCaptureThread;
begin
result:=aThread.Value as TScreenCaptureThread;
Assert(result<>nil);
end;
{ TScreenCaptureThread }
procedure TScreenCaptureThread.Capture;
var
aScreenDC: HDC;
hbmpOldTarget: HGDIOBJ;
aFormat: TMediaStreamDataHeader;
begin
Assert(FMemDC<>0);
PrepareBitmap;
aScreenDC := GetDC (0);
try
// 3. выбираем битмап в контекст
hbmpOldTarget := SelectObject(FMemDC, FBitmap);
try
// 4. делаем блит
Win32Check(BitBlt(FMemDC,
0, 0,
FCurrentBmpInfoHeader.biWidth,
FCurrentBmpInfoHeader.biHeight,
aScreenDC,
0, 0, // логические координаты исходного растра
SRCCOPY
));
finally
// 5. отцепляем битмап
SelectObject(FMemDC, hbmpOldTarget);
end;
// 7. распоряжаемся битмапом
//UpturnImage(FDib,FCurrentBmpInfoHeader);
aFormat.Assign(FCurrentBmpInfoHeader);
aFormat.VideoReversedVertical:=false;
Include(aFormat.biFrameFlags,ffKeyFrame);
FOwner.OnFrameReceived(aFormat, FDib,FCurrentBmpInfoHeader.biSizeImage,@FCurrentBmpInfoHeader,sizeof(FCurrentBmpInfoHeader));
finally
ReleaseDC (0, aScreenDC );
end;
end;
constructor TScreenCaptureThread.Create(aOwner: TMediaServerSourceScreenCapture);
begin
FOwner:=aOwner;
FOpenLock:=TCriticalSection.Create;
FCurrentBmpInfoHeader.biBitCount:=24;
FCurrentBmpInfoHeader.biClrImportant:=0;
FCurrentBmpInfoHeader.biClrUsed:=0;
FCurrentBmpInfoHeader.biCompression:=BI_RGB;
FCurrentBmpInfoHeader.biWidth:=0;
FCurrentBmpInfoHeader.biHeight:=0; //Присвоится позже
FCurrentBmpInfoHeader.biPlanes:=1;
FCurrentBmpInfoHeader.biSize:=sizeof(BITMAPINFOHEADER);
FCurrentBmpInfoHeader.biXPelsPerMeter:=0;
FCurrentBmpInfoHeader.biYPelsPerMeter:=0;
inherited Create(false);
end;
destructor TScreenCaptureThread.Destroy;
begin
inherited;
FreeAndNil(FOpenLock);
end;
function TScreenCaptureThread.StreamInfo: TBytes;
begin
FOpenLock.Enter;
try
result:=RawToBytes(FCurrentBmpInfoHeader,sizeof(FCurrentBmpInfoHeader));
finally
FOpenLock.Leave;
end;
end;
procedure TScreenCaptureThread.Execute;
var
aStart,aStop,aDelta:cardinal;
aInterval: cardinal;
begin
SetCurrentThreadName('Source: '+ClassName);
if FOwner.FFps=0 then
aInterval:=40
else
aInterval:=1000 div FOwner.FFps;
PrepareBitmap;
FMemDC:=CreateCompatibleDC(0);
try
while not Terminated do
begin
try
aStart:=GetTickCount;
Capture;
aStop:=GetTickCount;
aDelta:=aStop-aStart;
if aDelta<aInterval then
Sleep(aInterval-aDelta);
except
on E:Exception do
begin
sleep(100);
//TODO может прервать?
end;
end;
end;
finally
DeleteDC(FMemDC);
DeleteObject(FBitmap);
end;
end;
procedure TScreenCaptureThread.PrepareBitmap;
var
w,h: integer;
aBitmapInfo: TBitmapInfo;
begin
w:=Screen.Width;
h:=Screen.Height;
// 1. создаем контекст
if (FCurrentBmpInfoHeader.biWidth<>W) or (FCurrentBmpInfoHeader.biHeight<>H) then
begin
FOpenLock.Enter;
try
if FBitmap<>0 then
DeleteObject(FBitmap);
FBitmap:=0;
FCurrentBmpInfoHeader.biWidth:=W;
FCurrentBmpInfoHeader.biHeight:=H;
FCurrentBmpInfoHeader.biSizeImage:=W*H*3;
aBitmapInfo.bmiHeader:=FCurrentBmpInfoHeader;
FBitmap :=CreateDIBSection(FMemDC, aBitmapInfo, DIB_RGB_COLORS, FDib, 0, 0); // true-color
Win32Check(FBitmap<>0);
finally
FOpenLock.Leave;
end;
end;
end;
{ TMediaServerSourceScreenCapture }
constructor TMediaServerSourceScreenCapture.Create(aFps: integer);
begin
inherited Create(-1);
FEmitThread:=TThreadObjectVar<TThread>.Create;
FFps:=aFps;
end;
destructor TMediaServerSourceScreenCapture.Destroy;
begin
inherited;
FreeAndNil(FEmitThread);
end;
function TMediaServerSourceScreenCapture.DeviceType: string;
begin
result:='Рабочий стол';
end;
function TMediaServerSourceScreenCapture.Name: string;
begin
result:='Screen Capture';
end;
procedure TMediaServerSourceScreenCapture.OnFrameReceived(
const aFormat: TMediaStreamDataHeader;
aData: pointer; aDataSize:cardinal;
aInfo: pointer; aInfoSize: cardinal);
begin
// aB.Init(aData,aDataSize,aFormat.VideoWidth,aFormat.VideoHeight,aFormat.VideoBitCount);
// aBitmap:=TBitmap.Create;
// aB.CopyToBitmap(aBitmap,false);
// aBitmap.SaveToFile('C:\1.bmp');
DoDataReceived(aFormat, aData,aDataSize, aInfo,aInfoSize);
end;
procedure TMediaServerSourceScreenCapture.DoOpen(aSync: boolean);
begin
if Opened then
exit;
Close;
FEmitThread.Value:=TScreenCaptureThread.Create(self);
if Assigned(OnConnectionOk) then
OnConnectionOk(self);
end;
procedure TMediaServerSourceScreenCapture.DoClose;
begin
FEmitThread.FreeValue;
end;
function TMediaServerSourceScreenCapture.ConnectionString: string;
begin
result:='';
end;
function TMediaServerSourceScreenCapture.Opened: Boolean;
begin
result:=FEmitThread.Value<>nil;
end;
function TMediaServerSourceScreenCapture.StreamInfo: TBytes;
begin
FEmitThread.Lock;
try
CheckConnected;
result:=GetCaptureThread(FEmitThread).StreamInfo;
finally
FEmitThread.Unlock;
end;
end;
function TMediaServerSourceScreenCapture.GetStreamType(aMediaType: TMediaType): TStreamType;
begin
if aMediaType=mtVideo then
result:=stRGB
else
result:=0;
end;
function TMediaServerSourceScreenCapture.PtzSupported: boolean;
begin
result:=false;
end;
procedure TMediaServerSourceScreenCapture.WaitWhileConnecting(aTimeout: integer);
begin
inherited;
end;
end.
|
unit XMLDataBindingUtilsTest;
interface
uses
TestFramework;
type
TXMLDataBindingUtilsTest = class(TTestCase)
protected
procedure CheckEqualsDateTime(AExpected, AActual: TDateTime; const AMsg: string = '');
published
procedure ToXMLDate;
procedure ToXMLTime;
procedure ToXMLDateTime;
procedure ToDate;
procedure ToTime;
procedure ToDateTime;
end;
implementation
uses
DateUtils,
SysUtils,
XMLDataBindingUtils;
const
DateDelta = 0.00000001;
{ TXMLDateUtilsTest }
procedure TXMLDataBindingUtilsTest.ToXMLDate;
begin
CheckEquals('2008-05-23', DateTimeToXML(EncodeDate(2008, 5, 23), xdtDate));
end;
procedure TXMLDataBindingUtilsTest.ToXMLTime;
var
date: TDateTime;
begin
date := EncodeTime(14, 38, 02, 507);
CheckEquals('14:38:02', DateTimeToXML(date, xdtTime, []), 'No time fragments');
CheckEquals('14:38:02.507', DateTimeToXML(date, xdtTime, [xtfMilliseconds]), 'Milliseconds');
// (MvR) 23-4-2008: dit werkt alleen met GMT+1 locale...
CheckEquals('14:38:02.507+01:00', DateTimeToXML(date, xdtTime), 'All time fragments');
end;
procedure TXMLDataBindingUtilsTest.ToXMLDateTime;
var
date: TDateTime;
begin
date := EncodeDate(2008, 5, 23) + EncodeTime(14, 38, 02, 507);
CheckEquals('2008-05-23T14:38:02', DateTimeToXML(date, xdtDateTime, []), 'No time fragments');
CheckEquals('2008-05-23T14:38:02.507', DateTimeToXML(date, xdtDateTime, [xtfMilliseconds]), 'Milliseconds');
// (MvR) 23-4-2008: dit werkt alleen met GMT+1 locale...
CheckEquals('2008-05-23T14:38:02.507+01:00', DateTimeToXML(date, xdtDateTime), 'All time fragments');
end;
procedure TXMLDataBindingUtilsTest.ToDate;
begin
CheckEqualsDateTime(EncodeDate(2008, 5, 23), XMLToDateTime('2008-05-23', xdtDate));
end;
procedure TXMLDataBindingUtilsTest.ToTime;
var
date: TDateTime;
begin
date := EncodeTime(14, 38, 02, 0);
CheckEqualsDateTime(date, XMLToDateTime('14:38:02', xdtTime), 'No time fragments');
date := EncodeTime(14, 38, 02, 507);
CheckEqualsDateTime(date, XMLToDateTime('14:38:02.507', xdtTime), 'Milliseconds');
// (MvR) 23-4-2008: dit werkt alleen met GMT+1 locale...
CheckEqualsDateTime(IncHour(date, -1), XMLToDateTime('14:38:02.507+02:00', xdtTime), 'All time fragments');
CheckEqualsDateTime(IncHour(date), XMLToDateTime('14:38:02.507Z', xdtTime), 'All time fragments');
end;
procedure TXMLDataBindingUtilsTest.ToDateTime;
var
date: TDateTime;
begin
date := EncodeDate(2008, 5, 23) + EncodeTime(14, 38, 02, 0);
CheckEqualsDateTime(date, XMLToDateTime('2008-05-23T14:38:02', xdtDateTime), 'No time fragments');
date := EncodeDate(2008, 5, 23) + EncodeTime(14, 38, 02, 507);
CheckEqualsDateTime(date, XMLToDateTime('2008-05-23T14:38:02.507', xdtDateTime), 'Milliseconds');
// (MvR) 23-4-2008: dit werkt alleen met GMT+1 locale...
CheckEqualsDateTime(date, XMLToDateTime('2008-05-23T14:38:02.507+01:00', xdtDateTime), 'All time fragments');
end;
procedure TXMLDataBindingUtilsTest.CheckEqualsDateTime(AExpected, AActual: TDateTime; const AMsg: string);
begin
if Abs(AExpected - AActual) > DateDelta then
FailNotEquals(DateTimeToStr(AExpected), DateTimeToStr(AActual), AMsg);
end;
initialization
RegisterTest('XMLDataBindingUtils', TXMLDataBindingUtilsTest.Suite);
end.
|
unit EntregadorProxy;
interface
uses
System.SysUtils, InterfacePizzaria, Pizzaria;
type
TEntregador = class(TInterfacedObject, IPizzaria)
private
Pizzaria: TPizzaria;
Pizza: string;
public
constructor Create(Pizza: string);
procedure EntregarPizzas;
procedure ReceberDinheiro;
destructor Destroy; override;
end;
implementation
{ TEntregador }
constructor TEntregador.Create(Pizza: string);
begin
Self.Pizza := Pizza;
end;
destructor TEntregador.Destroy;
begin
Pizzaria.Free;
inherited;
end;
procedure TEntregador.EntregarPizzas;
begin
if Pizzaria = nil then
Pizzaria := TPizzaria.Create(Pizza);
Pizzaria.EntregarPizzas;
end;
procedure TEntregador.ReceberDinheiro;
begin
if Pizzaria = nil then
Pizzaria := TPizzaria.Create(Pizza);
Pizzaria.ReceberDinheiro;
end;
end.
|
(**
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.
@stopdocumentation
**)
Unit TestCommonFunctions;
Interface
Uses
TestFramework,
Windows,
SysUtils,
Classes,
Graphics,
ITHelper.ExternalProcessInfo,
ITHelper.CommonFunctions;
Type
TestApplicationFunctions = Class(TTestCase)
Published
Procedure TestLike;
Procedure TestDGHFindOnPath;
Procedure TestDGHCreateProcess;
Procedure TestDGHPathRelativePathTo;
End;
Implementation
Type
TDGHCreateProcessHandler = Class
Strict Private
FOutput: TStringList;
Strict Protected
Public
Constructor Create(Output: TStringList);
Procedure IdleHandler;
Procedure ProcessMsgHandler(Const strMsg: String; Var boolAbort: Boolean);
Property Output: TStringList Read FOutput;
End;
{ TDGHCreateProcessHandler }
Constructor TDGHCreateProcessHandler.Create(Output: TStringList);
Begin
FOutput := Output;
End;
Procedure TDGHCreateProcessHandler.IdleHandler;
Begin
// Do nothing;
End;
Procedure TDGHCreateProcessHandler.ProcessMsgHandler(Const strMsg: String; Var boolAbort: Boolean);
Begin
FOutput.Add(strMsg);
End;
Procedure TestApplicationFunctions.TestDGHCreateProcess;
Var
Process : TITHProcessInfo;
ProcMsgHndr: TDGHCreateProcessHandler;
iResult : Integer;
slLines : TStringList;
strDrive : String;
Begin
strDrive := ExtractFileDrive(ParamStr(0));
Process.FEnabled := True;
Process.FEXE := strDrive + '\HoylD\RAD Studio\Library\Test\SuccessConsoleApp.exe';
Process.FParams := '';
Process.FDir := strDrive + '\HoylD\RAD Studio\Library\Test\';
slLines := TStringList.Create;
Try
ProcMsgHndr := TDGHCreateProcessHandler.Create(slLines);
Try
iResult := DGHCreateProcess(Process, ProcMsgHndr.ProcessMsgHandler, ProcMsgHndr.IdleHandler);
CheckEquals(0, iResult, 'SuccessConsoleApp ERRORLEVEL');
CheckEquals(2, ProcMsgHndr.Output.Count);
CheckEquals('This allocation runs successfully and', ProcMsgHndr.Output[0]);
CheckEquals('returns an ERRORLEVEL = 0.', ProcMsgHndr.Output[1]);
slLines.Clear;
Process.FEXE := strDrive + '\HoylD\RAD Studio\Library\Test\FailureConsoleApp.exe';
iResult := DGHCreateProcess(Process, ProcMsgHndr.ProcessMsgHandler,
ProcMsgHndr.IdleHandler);
CheckEquals(1, iResult, 'SuccessConsoleApp ERRORLEVEL');
CheckEquals(2, ProcMsgHndr.Output.Count);
CheckEquals('This allocation runs and fails and', ProcMsgHndr.Output[0]);
CheckEquals('in doing so returns an ERRORLEVEL = 1.', ProcMsgHndr.Output[1]);
Finally
ProcMsgHndr.Free;
End;
Finally
slLines.Free;
End;
End;
Procedure TestApplicationFunctions.TestDGHFindOnPath;
Var
strFileName: String;
Begin
strFileName := 'notepad.exe';
Check(DGHFindOnPath(strFileName, ''), 'Check for notepad.exe');
CheckEquals('C:\Windows\notepad.exe', strFileName);
strFileName := 'regedit.exe';
Check(DGHFindOnPath(strFileName, ''), 'Check for regedit.exe');
CheckEquals('C:\Windows\regedit.exe', strFileName);
strFileName := 'cmd.exe';
Check(DGHFindOnPath(strFileName, ''), 'Check for cmd.exe');
CheckEquals('C:\Windows\System32\cmd.exe', strFileName);
End;
Procedure TestApplicationFunctions.TestDGHPathRelativePathTo;
Var
strFile: String;
Begin
strFile :=
'E:\Hoyld\Borland Studio Projects\IDE Addins\Integrated Testing Helper\Source\TestingHelperWizard.pas';
CheckEquals(True, DGHPathRelativePathTo('E:\Hoyld\Borland Studio Projects\', strFile));
CheckEquals
('IDE Addins\Integrated Testing Helper\Source\TestingHelperWizard.pas', strFile);
strFile :=
'E:\Hoyld\Borland Studio Projects\IDE Addins\Integrated Testing Helper\Source\TestingHelperWizard.pas';
CheckEquals(True, DGHPathRelativePathTo('E:\Hoyld\Borland Studio Projects\Library\',
strFile));
CheckEquals
('..\IDE Addins\Integrated Testing Helper\Source\TestingHelperWizard.pas', strFile);
strFile :=
'E:\Hoyld\Borland Studio Projects\IDE Addins\Integrated Testing Helper\Source\TestingHelperWizard.pas';
CheckEquals(True, DGHPathRelativePathTo
('E:\Hoyld\borland studio projects\Library\Tests\', strFile));
CheckEquals
('..\..\IDE Addins\Integrated Testing Helper\Source\TestingHelperWizard.pas',
strFile);
strFile := 'TestingHelperWizard.pas';
CheckEquals(False, DGHPathRelativePathTo('E:\Hoyld\borland studio projects\', strFile));
CheckEquals('TestingHelperWizard.pas', strFile);
strFile :=
'\\CJVRUG1\Grouped\Hoyld\Borland Studio Projects\IDE Addins\Integrated Testing Helper\Source\TestingHelperWizard.pas';
CheckEquals(True, DGHPathRelativePathTo
('\\CJVRUG1\Grouped\Hoyld\borland studio projects\', strFile));
CheckEquals
('IDE Addins\Integrated Testing Helper\Source\TestingHelperWizard.pas', strFile);
strFile :=
'\\CJVRUG2\Grouped\Hoyld\Borland Studio Projects\IDE Addins\Integrated Testing Helper\Source\TestingHelperWizard.pas';
CheckEquals(False, DGHPathRelativePathTo
('\\CJVRUG1\Grouped\Hoyld\borland studio projects\', strFile));
CheckEquals
('\\CJVRUG2\Grouped\Hoyld\Borland Studio Projects\IDE Addins\Integrated Testing Helper\Source\TestingHelperWizard.pas',
strFile);
End;
Procedure TestApplicationFunctions.TestLike;
Const
strText = 'Mary had a little lamb';
Begin
Check(Like('mary*', strText), '1');
Check(Not Like('mry*', strText), '2');
Check(Like('*lamb', strText), '3');
Check(Not Like('*lmb', strText), '4');
Check(Like('*little*', strText), '5');
Check(Not Like('*litle*', strText), '6');
Check(Like('*had*little*', strText), '7');
Check(Not Like('*had*litle*', strText), '8');
Check(Not Like('*little*had*', strText), '9');
Check(Like('*library*testprojectdll*;*', 'Library TestProjectDLL;'), '10');
Check(Like('*', ''));
Check(Like('*', strText));
End;
Initialization
// Register any test cases with the test runner
RegisterTest('Common Functions', TestApplicationFunctions.Suite);
End.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC Moni base classes }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.Moni.Base;
interface
{$IFDEF FireDAC_MONITOR}
uses
System.Classes,
FireDAC.Stan.Intf, FireDAC.Stan.Factory;
type
TFDMoniClientBase = class;
TFDMoniClientLinkBase = class;
TFDMoniClientBase = class(TFDObject, IFDMoniClient)
private
FName: TComponentName;
FFailure: Boolean;
FTracing: Boolean;
FEventKinds: TFDMoniEventKinds;
FOutputHandler: IFDMoniClientOutputHandler;
protected
// IFDMoniClient
function GetTracing: Boolean;
procedure SetTracing(const AValue: Boolean);
function GetName: TComponentName;
procedure SetName(const AValue: TComponentName);
function GetEventKinds: TFDMoniEventKinds;
procedure SetEventKinds(const AValue: TFDMoniEventKinds);
function GetOutputHandler: IFDMoniClientOutputHandler;
procedure SetOutputHandler(const AValue: IFDMoniClientOutputHandler);
procedure ResetFailure;
procedure Notify(AKind: TFDMoniEventKind; AStep: TFDMoniEventStep;
ASender: TObject; const AMsg: String; const AArgs: array of const); virtual;
function RegisterAdapter(const AAdapter: IFDMoniAdapter): LongWord; virtual;
procedure UnregisterAdapter(const AAdapter: IFDMoniAdapter); virtual;
procedure AdapterChanged(const AAdapter: IFDMoniAdapter); virtual;
// other
function DoTracingChanged: Boolean; virtual;
function OperationAllowed: Boolean; virtual;
procedure GetObjectNames(ASender: TObject; out AClassName, AName: String);
// TFDObject
procedure Finalize; override;
public
procedure Initialize; override;
end;
TFDMoniOutputEvent = procedure (ASender: TFDMoniClientLinkBase;
const AClassName, AObjName, AMessage: String) of object;
TFDMoniClientLinkBase = class(TComponent, IFDMoniClientOutputHandler)
private
FClient: IFDMoniClient;
FOnOutput: TFDMoniOutputEvent;
FDesignTracing: Boolean;
function GetEventKinds: TFDMoniEventKinds;
procedure SetEventKinds(const AValue: TFDMoniEventKinds);
function GetTracing: Boolean;
procedure SetTracing(const AValue: Boolean);
procedure SetOnOutput(const AValue: TFDMoniOutputEvent);
protected
// IFDMoniClientOutputHandler
procedure HandleOutput(const AClassName, AObjName, AMessage: String); virtual;
// other
function GetMoniClient: IFDMoniClient; virtual; abstract;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Notify(AKind: TFDMoniEventKind; AStep: TFDMoniEventStep;
ASender: TObject; const AMsg: String; const AArgs: array of const); virtual;
property MoniClient: IFDMoniClient read FClient;
property Tracing: Boolean read GetTracing write SetTracing default False;
published
property EventKinds: TFDMoniEventKinds read GetEventKinds write SetEventKinds
default [ekLiveCycle .. ekComponent];
property OnOutput: TFDMoniOutputEvent read FOnOutput write SetOnOutput;
end;
{$ENDIF}
implementation
{$IFDEF FireDAC_MONITOR}
uses
System.SysUtils,
FireDAC.Stan.Consts, FireDAC.Stan.Util;
{-------------------------------------------------------------------------------}
{ TFDMoniClientBase }
{-------------------------------------------------------------------------------}
procedure TFDMoniClientBase.Initialize;
begin
inherited Initialize;
FEventKinds := [ekLiveCycle .. ekComponent];
end;
{-------------------------------------------------------------------------------}
function TFDMoniClientBase.GetName: TComponentName;
begin
Result := FName;
end;
{-------------------------------------------------------------------------------}
procedure TFDMoniClientBase.SetName(const AValue: TComponentName);
begin
FName := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDMoniClientBase.GetEventKinds: TFDMoniEventKinds;
begin
Result := FEventKinds;
end;
{-------------------------------------------------------------------------------}
procedure TFDMoniClientBase.SetEventKinds(const AValue: TFDMoniEventKinds);
begin
FEventKinds := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDMoniClientBase.GetOutputHandler: IFDMoniClientOutputHandler;
begin
Result := FOutputHandler;
end;
{-------------------------------------------------------------------------------}
procedure TFDMoniClientBase.SetOutputHandler(const AValue: IFDMoniClientOutputHandler);
begin
FOutputHandler := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDMoniClientBase.GetTracing: Boolean;
begin
Result := FTracing;
end;
{-------------------------------------------------------------------------------}
procedure TFDMoniClientBase.SetTracing(const AValue: Boolean);
begin
if (FTracing <> AValue) and not FFailure and OperationAllowed then begin
FTracing := AValue;
try
if not DoTracingChanged then
if AValue then begin
FTracing := False;
FFailure := True;
end;
except
SetTracing(False);
FFailure := True;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDMoniClientBase.ResetFailure;
begin
FFailure := False;
end;
{-------------------------------------------------------------------------------}
procedure TFDMoniClientBase.Notify(AKind: TFDMoniEventKind;
AStep: TFDMoniEventStep; ASender: TObject; const AMsg: String;
const AArgs: array of const);
begin
// nothing
end;
{-------------------------------------------------------------------------------}
function TFDMoniClientBase.RegisterAdapter(const AAdapter: IFDMoniAdapter): LongWord;
begin
// nothing
Result := 0;
end;
{-------------------------------------------------------------------------------}
procedure TFDMoniClientBase.UnregisterAdapter(const AAdapter: IFDMoniAdapter);
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDMoniClientBase.AdapterChanged(const AAdapter: IFDMoniAdapter);
begin
// nothing
end;
{-------------------------------------------------------------------------------}
function TFDMoniClientBase.OperationAllowed: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDMoniClientBase.DoTracingChanged: Boolean;
begin
// nothing
Result := True;
end;
{-------------------------------------------------------------------------------}
procedure TFDMoniClientBase.Finalize;
begin
SetTracing(False);
end;
{-------------------------------------------------------------------------------}
type
__TInterfacedObject = class(TInterfacedObject)
end;
procedure TFDMoniClientBase.GetObjectNames(ASender: TObject; out AClassName, AName: String);
var
iRefCount: Integer;
oObjIntf: IFDStanObject;
begin
AName := '';
if ASender <> nil then begin
AClassName := ASender.ClassName;
if (ASender <> nil) and (ASender is TInterfacedObject) then begin
iRefCount := __TInterfacedObject(ASender).FRefCount;
__TInterfacedObject(ASender).FRefCount := 2;
try
if Supports(ASender, IFDStanObject, oObjIntf) then begin
AName := oObjIntf.GetName;
oObjIntf := nil;
end;
finally
__TInterfacedObject(ASender).FRefCount := iRefCount;
end;
end;
if AName = '' then begin
if ASender is TComponent then
AName := TComponent(ASender).Name;
if AName = '' then
AName := '$' + IntToHex(Integer(ASender), 8);
end;
end
else
AClassName := '<nil>';
end;
{-------------------------------------------------------------------------------}
{ TFDMoniClientLinkBase }
{-------------------------------------------------------------------------------}
constructor TFDMoniClientLinkBase.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FClient := GetMoniClient;
end;
{-------------------------------------------------------------------------------}
destructor TFDMoniClientLinkBase.Destroy;
begin
SetOnOutput(nil);
FClient.Tracing := False;
FClient := nil;
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
function TFDMoniClientLinkBase.GetEventKinds: TFDMoniEventKinds;
begin
Result := MoniClient.EventKinds;
end;
{-------------------------------------------------------------------------------}
procedure TFDMoniClientLinkBase.SetEventKinds(const AValue: TFDMoniEventKinds);
begin
MoniClient.EventKinds := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDMoniClientLinkBase.GetTracing: Boolean;
begin
if csDesigning in ComponentState then
Result := FDesignTracing
else
Result := MoniClient.Tracing;
end;
{-------------------------------------------------------------------------------}
procedure TFDMoniClientLinkBase.SetTracing(const AValue: Boolean);
begin
if csDesigning in ComponentState then
FDesignTracing := AValue
else
MoniClient.Tracing := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDMoniClientLinkBase.SetOnOutput(const AValue: TFDMoniOutputEvent);
begin
if Assigned(AValue) then
MoniClient.OutputHandler := Self as IFDMoniClientOutputHandler
else
MoniClient.OutputHandler := nil;
FOnOutput := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDMoniClientLinkBase.HandleOutput(
const AClassName, AObjName, AMessage: String);
begin
if Assigned(FOnOutput) and not (csDestroying in ComponentState) then
FOnOutput(Self, AClassName, AObjName, AMessage);
end;
{-------------------------------------------------------------------------------}
procedure TFDMoniClientLinkBase.Notify(AKind: TFDMoniEventKind;
AStep: TFDMoniEventStep; ASender: TObject; const AMsg: String;
const AArgs: array of const);
begin
MoniClient.Notify(AKind, AStep, ASender, AMsg, AArgs);
end;
{$ENDIF}
end.
|
unit fNoteST;
{
Text Search CQ: HDS00002856
This Unit Contains the Dialog Used to Capture the Text that will be
searched for in the current notes view.
}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, ORCtrls, StdCtrls, ORFn, uTIU, fAutoSz, VA508AccessibilityManager;
type
TfrmNotesSearchText = class(TfrmAutoSz)
lblSearchInfo: TLabel;
edtSearchText: TEdit;
lblAuthor: TLabel;
cmdOK: TButton;
cmdCancel: TButton;
procedure cmdCancelClick(Sender: TObject);
procedure cmdOKClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormResize(Sender: TObject);
private
FChanged: Boolean;
FSearchString: string;
end;
TSearchContext = record
Changed: Boolean;
SearchString: string;
end;
procedure SelectSearchText(FontSize: Integer; var SearchText: String; var SearchContext: TSearchContext; FormCaption: String = 'List Signed Notes by Author');
implementation
{$R *.DFM}
uses rTIU, rCore, uCore, rMisc, VAUtils;
const
TX_SEARCH_TEXT = 'Select a search string or press Cancel.';
TX_SEARCH_CAP = 'Missing search string';
procedure SelectSearchText(FontSize: Integer; var SearchText: String; var SearchContext: TSearchContext; FormCaption: String = 'List Signed Notes by Author');
{ displays author select form for progress notes and returns a record of the selection }
var
frmNotesSearchText: TfrmNotesSearchText;
W, H: integer;
// CurrentAuthor: Int64;
begin
frmNotesSearchText := TfrmNotesSearchText.Create(Application);
try
frmNotesSearchText.Caption := FormCaption;
with frmNotesSearchText do
begin
edtSearchText.Text:=SearchText;
Font.Size := FontSize;
W := ClientWidth;
H := ClientHeight;
ResizeToFont(FontSize, W, H);
// ClientWidth := W; pnlBase.Width := W;
// ClientHeight := H; pnlBase.Height := W;
FChanged := False;
Show;
edtSearchText.SetFocus;
Hide;
ShowModal;
If edtSearchText.Text<>'' then
with SearchContext do
begin
Changed := FChanged;
SearchString := FSearchString;
end; {with SearchContext}
end; {with frmNotesSearchText}
finally
frmNotesSearchText.Release;
end;
end;
procedure TfrmNotesSearchText.cmdCancelClick(Sender: TObject);
begin
FChanged:=False;
Close;
end;
procedure TfrmNotesSearchText.cmdOKClick(Sender: TObject);
begin
if edtSearchText.Text = '' then
begin
InfoBox(TX_SEARCH_TEXT, TX_SEARCH_CAP, MB_OK or MB_ICONWARNING);
Exit;
end;
FChanged := True;
FSearchString := edtSearchText.Text;
Close;
end;
procedure TfrmNotesSearchText.FormShow(Sender: TObject);
begin
SetFormPosition(Self);
end;
procedure TfrmNotesSearchText.FormDestroy(Sender: TObject);
begin
SaveUserBounds(Self);
end;
procedure TfrmNotesSearchText.FormResize(Sender: TObject);
begin
inherited;
lblSearchInfo.Width := edtSearchText.Width;
end;
end.
|
unit IdDsnNewMessagePart;
interface
uses
Buttons, Classes, Controls, Dialogs, ExtCtrls, Forms, IdMessage,
StdCtrls;
type
TfrmNewMessagePart = class(TForm)
Panel2: TPanel;
btnOk: TButton;
btnCancel: TButton;
lbTypes: TListBox;
procedure lbTypesClick(Sender: TObject);
procedure lbTypesDblClick(Sender: TObject);
protected
public
class function PromptForMsgPart(AMsg : TIdMessage): Boolean;
end;
implementation
{$R *.dfm}
uses
Graphics, IdGlobal,
SysUtils;
class function TfrmNewMessagePart.PromptForMsgPart(AMsg : TIdMessage): Boolean;
begin
with TfrmNewMessagePart.Create(nil) do try
Result := (ShowModal = mrOk);
if Result then begin
case lbTypes.ItemIndex of
{ Attachment - TIdAttachment }
0 : TIdAttachment.Create( AMsg.MessageParts, '');
{ Text - TIdText }
1 : TIdText.Create(AMsg.MessageParts);
end; //case cboType.ItemIndex of
end; //if Result then
finally Free; end;
end;
procedure TfrmNewMessagePart.lbTypesClick(Sender: TObject);
begin
btnOk.Enabled := lbTypes.ItemIndex <> -1
end;
procedure TfrmNewMessagePart.lbTypesDblClick(Sender: TObject);
begin
if btnOk.Enabled then begin
btnOk.Click;
end;
end;
end.
|
{(*}
(*------------------------------------------------------------------------------
Delphi Code formatter source code
The Original Code is frClarify.pas, released April 2000.
The Initial Developer of the Original Code is Anthony Steele.
Portions created by Anthony Steele are Copyright (C) 1999-2008 Anthony Steele.
All Rights Reserved.
Contributor(s): Anthony Steele.
The contents of this file are subject to the Mozilla Public License Version 1.1
(the "License"). you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.mozilla.org/NPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied.
See the License for the specific language governing rights and limitations
under the License.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 or later (the "GPL")
See http://www.gnu.org/licenses/gpl.html
------------------------------------------------------------------------------*)
{*)}
unit frClarifyBlocks;
{$I JcfGlobal.inc}
interface
uses
{ delphi }
Classes, Controls, Forms,
StdCtrls, ExtCtrls,
{ local}
frmBaseSettingsFrame;
type
TfClarifyBlocks = class(TfrSettingsFrame)
rgBlockBegin: TRadioGroup;
rgBlock: TRadioGroup;
rgEndElse: TRadioGroup;
Label1: TLabel;
rgElseIf: TRadioGroup;
rgElseBegin: TRadioGroup;
private
public
constructor Create(AOwner: TComponent); override;
procedure Read; override;
procedure Write; override;
end;
implementation
uses JcfSettings, SettingsTypes, JcfHelp;
{$ifdef FPC}
{$R *.lfm}
{$else}
{$R *.dfm}
{$endif}
constructor TfClarifyBlocks.Create(AOwner: TComponent);
begin
inherited;
fiHelpContext := HELP_CLARIFY_BLOCKS;
end;
{-------------------------------------------------------------------------------
worker procs }
procedure TfClarifyBlocks.Read;
begin
with JcfFormatSettings.Returns do
begin
{ block styles }
rgBlockBegin.ItemIndex := Ord(BlockBeginStyle);
rgBlock.ItemIndex := Ord(BlockStyle);
rgEndElse.ItemIndex := Ord(EndElseStyle);
rgElseIf.ItemIndex := Ord(ElseIfStyle);
rgElseBegin.ItemIndex := Ord(ElseBeginStyle);
end;
end;
procedure TfClarifyBlocks.Write;
begin
with JcfFormatSettings.Returns do
begin
{ block styles }
BlockBeginStyle := TTriOptionStyle(rgBlockBegin.ItemIndex);
BlockStyle := TTriOptionStyle(rgBlock.ItemIndex);
EndElseStyle := TTriOptionStyle(rgEndElse.ItemIndex);
ElseIfStyle := TTriOptionStyle(rgElseIf.ItemIndex);
ElseBeginStyle := TTriOptionStyle(rgElseBegin.ItemIndex);
end;
end;
{-------------------------------------------------------------------------------
event handlers }
end.
|
unit Amazon.DelphiRESTClient;
interface
uses classes, SysUtils, Amazon.Interfaces, REST.Client, REST.Types,
REST.HttpClient;
const
cAccept = CONTENTTYPE_APPLICATION_JSON + ', ' + CONTENTTYPE_TEXT_PLAIN +
'; q=0.9, ' + CONTENTTYPE_TEXT_HTML + ';q=0.8,';
cAcceptCharset = 'UTF-8, *;q=0.8';
cUserAgent = 'Embarcadero RESTClient/' + RESTCLIENT_VERSION;
type
TAmazonDelphiRestClient = class(TInterfacedObject, IAmazonRestClient)
private
fsAccept: string;
fsAcceptCharset: string;
fsContent_type: string;
fiErrorCode: Integer;
fsErrorMessage: String;
fsUserAgent: string;
FHttpClient: TRESTHTTP;
protected
function GetResponseCode: Integer;
function GetResponseText: String;
function GetContent_type: string;
function GetErrorCode: Integer;
procedure SetContent_type(value: string);
function GetErrorMessage: String;
function GetAcceptCharset: string;
procedure SetAcceptCharset(value: string);
function GetAccept: string;
procedure SetAccept(value: string);
function GetUserAgent: string;
procedure SetUserAgent(value: string);
public
constructor Create;
destructor Destory;
procedure AddHeader(aName, aValue: UTF8String);
procedure Post(aUrl: string; aRequest: UTF8String;
var aResponse: UTF8String);
property ResponseCode: Integer read GetResponseCode;
property ResponseText: string read GetResponseText;
property Content_type: String read GetContent_type write SetContent_type;
property ErrorCode: Integer read GetErrorCode;
property ErrorMessage: String read GetErrorMessage;
property UserAgent: string read GetUserAgent write SetUserAgent;
property AcceptCharset: string read GetAcceptCharset write SetAcceptCharset;
property Accept: string read GetAccept write SetAccept;
end;
implementation
constructor TAmazonDelphiRestClient.Create;
begin
fsContent_type := '';
fiErrorCode := 0;
fsErrorMessage := '';
fsAccept := '';
fsAcceptCharset :='';
fsUserAgent := '';
FHttpClient := TRESTHTTP.Create;
end;
destructor TAmazonDelphiRestClient.Destory;
begin
FHttpClient.Free;
end;
procedure TAmazonDelphiRestClient.AddHeader(aName, aValue: UTF8String);
begin
FHttpClient.Request.CustomHeaders.SetValue(aName, aValue);
end;
procedure TAmazonDelphiRestClient.Post(aUrl: string; aRequest: UTF8String;
var aResponse: UTF8String);
Var
FSource, FResponseContent: TStringStream;
begin
Try
Try
FSource := TStringStream.Create(aRequest, TEncoding.ANSI);
FSource.Position := 0;
FResponseContent := TStringStream.Create;
FHttpClient.Request.Accept := Accept;
FHttpClient.Request.AcceptCharset := AcceptCharset;
FHttpClient.Request.UserAgent := UserAgent;
FHttpClient.Request.ContentType := Content_type;
FHttpClient.Post(aUrl, FSource, FResponseContent);
aResponse := FResponseContent.DataString;
Except
on E: Exception do
begin
// fiErrorCode := E.Message
fsErrorMessage := E.Message;
if Trim(aResponse) = '' then
aResponse := fsErrorMessage;
end;
end;
Finally
FResponseContent.Free;
FSource.Free;
End;
end;
function TAmazonDelphiRestClient.GetResponseCode: Integer;
begin
Result := FHttpClient.ResponseCode;
end;
function TAmazonDelphiRestClient.GetResponseText: String;
begin
Result := FHttpClient.ResponseText;
end;
function TAmazonDelphiRestClient.GetContent_type: string;
begin
Result := fsContent_type;
end;
function TAmazonDelphiRestClient.GetErrorCode: Integer;
begin
Result := fiErrorCode;
end;
procedure TAmazonDelphiRestClient.SetContent_type(value: string);
begin
fsContent_type := value;
end;
function TAmazonDelphiRestClient.GetErrorMessage: String;
begin
Result := fsErrorMessage;
end;
function TAmazonDelphiRestClient.GetUserAgent: string;
begin
if Trim(fsUserAgent) = '' then
fsUserAgent := cUserAgent;
Result := fsUserAgent;
end;
procedure TAmazonDelphiRestClient.SetUserAgent(value: string);
begin
fsUserAgent := value;
end;
function TAmazonDelphiRestClient.GetAcceptCharset: string;
begin
if Trim(fsAcceptCharset) = '' then
fsAcceptCharset := cAcceptCharset;
Result := fsAcceptCharset;
end;
procedure TAmazonDelphiRestClient.SetAcceptCharset(value: string);
begin
fsAcceptCharset := value;
end;
function TAmazonDelphiRestClient.GetAccept: string;
begin
if Trim(fsAccept) = '' then
fsAccept := cAccept;
Result := fsAccept;
end;
procedure TAmazonDelphiRestClient.SetAccept(value: string);
begin
fsAccept := value;
end;
end.
|
UNIT LinkedList;
{$MODE Delphi}
INTERFACE
TYPE TLinkedNode = CLASS
PUBLIC
CONSTRUCTOR create(o : TObject);
DESTRUCTOR destroy();
FUNCTION getObject() : TObject;
FUNCTION getNext() : TLinkedNode;
FUNCTION getPrev() : TLinkedNode;
PROTECTED
obj : TObject;
next : TLinkedNode;
prev : TLinkedNode;
END;
TYPE TLinkedList = CLASS
PUBLIC
CONSTRUCTOR create();
DESTRUCTOR destroy();
FUNCTION isEmpty() : BOOLEAN;
FUNCTION getFirst() : TLinkedNode;
FUNCTION getLast() : TLinkedNode;
PROCEDURE reverse();
FUNCTION iterate(VAR n : TLinkedNode) : BOOLEAN;
FUNCTION release(n : TLinkedNode) : TObject; OVERLOAD;
FUNCTION release(o : TObject) : TObject; OVERLOAD;
FUNCTION findObject(o : TObject) : TLinkedNode;
FUNCTION insert(prev : TLinkedNode; o : TObject) : TLinkedNode; OVERLOAD;
FUNCTION insert(prev : TLinkedNode; n : TLinkedNode) : TLinkedNode; OVERLOAD;
FUNCTION insertFront(n : TLinkedNode) : TLinkedNode; OVERLOAD;
FUNCTION insertFront(o : TObject) : TLinkedNode; OVERLOAD;
FUNCTION insertBack(n : TLinkedNode) : TLinkedNode; OVERLOAD;
FUNCTION insertBack(o : TObject) : TLinkedNode; OVERLOAD;
PRIVATE
first : TLinkedNode;
last : TLinkedNode;
END;
IMPLEMENTATION
CONSTRUCTOR TLinkedNode.create(o : TObject);
BEGIN
obj := o;
next := NIL;
prev := NIL;
END;
DESTRUCTOR TLinkedNode.destroy();
BEGIN
INHERITED destroy();
END;
FUNCTION TLinkedNode.getObject() : TObject;
BEGIN
getObject := obj;
END;
FUNCTION TLinkedNode.getNext() : TLinkedNode;
BEGIN
getNext := next;
END;
FUNCTION TLinkedNode.getPrev() : TLinkedNode;
BEGIN
getPrev := prev;
END;
CONSTRUCTOR TLinkedList.create();
BEGIN
first := NIL;
last := NIL;
END;
DESTRUCTOR TLinkedList.destroy();
VAR ptr, n : TLinkedNode;
BEGIN
ptr := first;
WHILE ptr <> NIL DO
BEGIN
n := ptr.next;
ptr.obj.Destroy();
ptr.destroy();
ptr := n;
END;
END;
FUNCTION TLinkedList.isEmpty(): BOOLEAN;
BEGIN
isEmpty := (first = NIL);
END;
FUNCTION TLinkedList.getFirst() : TLinkedNode;
BEGIN
getFirst := first;
END;
FUNCTION TLinkedList.getLast() : TLinkedNode;
BEGIN
getLast := last;
END;
PROCEDURE TLinkedList.reverse();
VAR ptr, swap : TLinkedNode;
BEGIN
ptr := getFirst();
WHILE ptr <> NIL DO
BEGIN
swap := ptr.next;
ptr.next := ptr.prev;
ptr.prev := swap;
ptr := swap;
END;
END;
FUNCTION TLinkedList.iterate(VAR n : TLinkedNode) : BOOLEAN;
BEGIN
IF n = NIL THEN
n := getFirst()
ELSE
n := n.getNext();
iterate := n <> NIL;
END;
FUNCTION TLinkedList.release(n : TLinkedNode) : TObject;
BEGIN
IF n.getPrev() <> NIL THEN
n.prev.next := n.next;
IF n.getNext() <> NIL THEN
n.next.prev := n.prev;
IF n = first THEN
first := n.getNext();
IF n = last THEN
last := n.getPrev();
release := n.getObject();
n.destroy();
END;
FUNCTION TLinkedList.release(o : TObject) : TObject;
VAR ptr : TLinkedNode;
BEGIN
ptr := findObject(o);
IF ptr <> NIL THEN
release := release(ptr)
ELSE
release := NIL;
END;
FUNCTION TLinkedList.findObject(o : TObject) : TLinkedNode;
VAR ptr : TLinkedNode;
BEGIN
ptr := getFirst();
WHILE (ptr <> NIL) AND (ptr.getObject() <> o) DO
ptr := ptr.getNext();
findObject := ptr;
END;
FUNCTION TLinkedList.insert(prev : TLinkedNode; n : TLinkedNode) : TLinkedNode;
BEGIN
IF prev = NIL THEN
BEGIN
IF first <> NIL THEN
BEGIN
first.prev := n;
n.next := first;
END;
first := n;
END
ELSE
BEGIN
n.next := prev.getNext();
n.prev := prev;
IF prev.getNext() <> NIL THEN
prev.next.prev := n;
prev.next := n;
END;
IF prev = last THEN
last := n;
insert := n;
END;
FUNCTION TLinkedList.insert(prev : TLinkedNode; o : TObject) : TLinkedNode;
BEGIN
insert := insert(prev, TLinkedNode.create(o));
END;
FUNCTION TLinkedList.insertFront(n : TLinkedNode) : TLinkedNode;
BEGIN
insertFront := insert(NIL, n);
END;
FUNCTION TLinkedList.insertFront(o : TObject) : TLinkedNode;
BEGIN
insertFront := insertFront(TLinkedNode.create(o));
END;
FUNCTION TLinkedList.insertBack(n : TLinkedNode) : TLinkedNode;
BEGIN
insertBack := insert(last, n);
END;
FUNCTION TLinkedList.insertBack(o : TObject) : TLinkedNode;
BEGIN
insertBack := insertBack(TLinkedNode.create(o));
END;
END.
|
unit Payment;
interface
uses
ActiveClient, PaymentMethod, System.Classes, SysUtils, System.Rtti, DateUtils;
type
TPaymentType = (ptPrincipal,ptInterest,ptPenalty);
TPaymentDetail = class
strict private
FPaymentId: string;
FPaymentDate: TDateTime;
FLoan: TLoan;
FRemarks: string;
FCancelled: boolean;
FPrincipal: currency;
FInterest: currency;
FPenalty: currency;
FPaymentType: TPaymentType;
FIsFullPayment: boolean;
function GetTotalAmount: currency;
function GetHasInterest: boolean;
function GetHasPrincipal: boolean;
function GetPenalty: boolean;
function PostInterest(const interest: currency; const loanId: string;
const ADate: TDateTime; const source, status: string): string;
function GetNewScheduleDate(const ACurrentDate, ANextDate: TDateTime): TDateTime;
procedure SaveInterest;
procedure UpdateInterestSchedule;
public
property Loan: TLoan read FLoan write FLoan;
property TotalAmount: currency read GetTotalAmount;
property Remarks: string read FRemarks write FRemarks;
property Cancelled: boolean read FCancelled write FCancelled;
property Principal: currency read FPrincipal write FPrincipal;
property Interest: currency read FInterest write FInterest;
property Penalty: currency read FPenalty write FPenalty;
property HasPrincipal: boolean read GetHasPrincipal;
property HasInterest: boolean read GetHasInterest;
property HasPenalty: boolean read GetPenalty;
property PaymentType: TPaymentType read FPaymentType write FPaymentType;
property PaymentId: string read FPaymentId write FPaymentId;
property PaymentDate: TDateTime read FPaymentDate write FPaymentDate;
property IsFullPayment: boolean read FIsFullPayment write FIsFullPayment;
function PaymentTypeToString(const payType: TPaymentType): string;
function IsScheduled: boolean;
function IsAdvanced: boolean;
function IsLate: boolean;
procedure Post;
end;
TPayment = class
private
FClient: TActiveClient;
FPaymentId: string;
FReceiptNo: string;
FDate: TDateTime;
FDetails: array of TPaymentDetail;
FPostDate: TDateTime;
FReferenceNo: string;
FLocationCode: string;
FPaymentMethod: TPaymentMethod;
FWithdrawn: currency;
FWithdrawalId: string;
FIsAdvance: boolean;
procedure SaveDetails;
procedure UpdateLoanRecord;
procedure SaveRebate(ALoan: TLoan);
function GetDetail(const i: integer): TPaymentDetail;
function GetTotalAmount: currency;
function GetDetailCount: integer;
function GetIsPosted: boolean;
function GetIsNew: boolean;
function GetIsWithdrawal: boolean;
function GetIsLate: boolean;
function GetChangeAmount: currency;
public
property Client: TActiveClient read FClient write FClient;
property PaymentId: string read FPaymentId write FPaymentId;
property ReceiptNo: string read FReceiptNo write FReceiptNo;
property Date: TDateTime read FDate write FDate;
property Details[const i: integer]: TPaymentDetail read GetDetail;
property TotalAmount: currency read GetTotalAmount;
property DetailCount: integer read GetDetailCount;
property PostDate: TDateTime read FPostDate write FPostDate;
property ReferenceNo: string read FReferenceNo write FReferenceNo;
property IsPosted: boolean read GetIsPosted;
property LocationCode: string read FLocationCode write FLocationCode;
property IsNew: boolean read GetIsNew;
property PaymentMethod: TPaymentMethod read FPaymentMethod write FPaymentMethod;
property Withdrawn: currency read FWithdrawn write FWithdrawn;
property WithdrawalId: string read FWithdrawalId write FWithdrawalId;
property IsWithdrawal: boolean read GetIsWithdrawal;
property IsAdvance: boolean read FIsAdvance write FIsAdvance;
property IsLate: boolean read GetIsLate;
property ChangeAmount: currency read GetChangeAmount;
procedure Add;
procedure AddDetail(const detail: TPaymentDetail);
procedure RemoveDetail(const loan: TLoan);
procedure Save;
procedure Retrieve;
function DetailExists(const loan: TLoan): boolean;
constructor Create;
destructor Destroy; reintroduce;
end;
var
pmt: TPayment;
implementation
uses
PaymentData, IFinanceDialogs, DBUtil, Posting, IFinanceGlobal, Ledger, AppConstants, LoanClassification;
constructor TPayment.Create;
begin
if pmt <> nil then pmt := self
else begin
inherited Create;
FPaymentMethod := TPaymentMethod.Create;
end;
end;
destructor TPayment.Destroy;
begin
if pmt = self then pmt := nil;
end;
procedure TPayment.Add;
begin
with dmPayment do
begin
dstPayment.Open;
dstPayment.Append;
end;
end;
procedure TPayment.AddDetail(const detail: TPaymentDetail);
begin
SetLength(FDetails,Length(FDetails)+1);
FDetails[Length(FDetails)-1] := detail;
end;
procedure TPayment.RemoveDetail(const loan: TLoan);
var
i, ii, len: integer;
detail: TPaymentDetail;
begin
len := Length(FDetails);
ii := 0;
for i := 0 to len - 1 do
begin
detail := FDetails[i];
if detail.Loan.Id <> loan.Id then
begin
FDetails[ii] := detail;
Inc(ii);
end;
end;
SetLength(FDetails,Length(FDetails) - 1);
end;
procedure TPayment.Save;
var
LPosting: TPosting;
begin
LPosting := TPosting.Create;
try
try
with dmPayment do
begin
// retrieve interest and loan records
// this is for updating purposes
dstInterests.Parameters.ParamByName('@entity_id').Value := FClient.Id;
dstInterests.Open;
dstLoans.Parameters.ParamByName('@entity_id').Value := FClient.Id;
dstLoans.Open;
dstPayment.Post;
SaveDetails;
UpdateLoanRecord;
LPosting.Post(self);
dstPayment.UpdateBatch;
dstPaymentDetail.UpdateBatch;
dstInterests.UpdateBatch;
dstLoans.UpdateBatch;
dstRebate.UpdateBatch;
end;
except
on E: Exception do begin
dmPayment.dstPayment.CancelBatch;
dmPayment.dstPaymentDetail.CancelBatch;
dmPayment.dstInterests.CancelBatch;
dmPayment.dstLoans.CancelBatch;
dmPayment.dstRebate.CancelBatch;
ShowErrorBox('An error has occured during payment posting. Entry has been cancelled.');
end;
end;
finally
LPosting.Free;
// dmPayment.dstPayment.Close;
// dmPayment.dstPaymentDetail.Close;
dmPayment.dstInterests.Close;
dmPayment.dstLoans.Close;
end;
end;
procedure TPayment.SaveDetails;
var
i, cnt: integer;
begin
try
with dmPayment.dstPaymentDetail do
begin
cnt := GetDetailCount - 1;
Open;
for i := 0 to cnt do
begin
FDetails[i].PaymentId := FPaymentId;
FDetails[i].PaymentDate := FDate;
// principal
if FDetails[i].HasPrincipal then
begin
Append;
FieldByName('payment_id').AsString := FPaymentId;
FieldByName('loan_id').AsString := FDetails[i].Loan.Id;
FieldByName('payment_amt').AsCurrency := FDetails[i].Principal;
FieldByName('payment_type').AsString := FDetails[i].PaymentTypeToString(ptPrincipal);
FieldByName('remarks').AsString := FDetails[i].Remarks;
FieldByName('balance').AsCurrency := FDetails[i].Loan.Balance - FDetails[i].Principal;
Post;
end;
// interest
if FDetails[i].HasInterest then
begin
Append;
FieldByName('payment_id').AsString := FPaymentId;
FieldByName('loan_id').AsString := FDetails[i].Loan.Id;
FieldByName('payment_amt').AsCurrency := FDetails[i].Interest;
FieldByName('payment_type').AsString := FDetails[i].PaymentTypeToString(ptInterest);
FieldByName('remarks').AsString := FDetails[i].Remarks;
if FDetails[i].IsFullPayment then FieldByName('balance').AsCurrency := 0
else FieldByName('balance').AsCurrency := FDetails[i].Loan.InterestDueOnPaymentDate - FDetails[i].Interest;
Post;
end;
// penalty
if FDetails[i].HasPenalty then
begin
Append;
FieldByName('payment_id').AsString := FPaymentId;
FieldByName('loan_id').AsString := FDetails[i].Loan.Id;
FieldByName('payment_amt').AsCurrency := FDetails[i].Penalty;
FieldByName('payment_type').AsString := FDetails[i].PaymentTypeToString(ptPenalty);
FieldByName('remarks').AsString := FDetails[i].Remarks;
Post;
end;
// rebate
if FDetails[i].Loan.HasRebate then SaveRebate(FDetails[i].Loan);
FDetails[i].Post;
end;
end;
except
on E: Exception do Abort;
end;
end;
procedure TPayment.SaveRebate(ALoan: TLoan);
begin
with dmPayment.dstRebate do
begin
if not Active then Open;
Append;
FieldByName('rebate_amt').AsCurrency := ALoan.Rebate;
FieldByName('loan_id').AsString := ALoan.Id;
Post;
end;
end;
procedure TPayment.UpdateLoanRecord;
var
detail: TPaymentDetail;
balance, intDeficit, prcDeficit: currency;
begin
// update the principal balance (field loan_balance)
// update the last transaction date
// update principal and interest deficits
// update the loan status for full payment
try
for detail in FDetails do
begin
with dmPayment.dstLoans do
begin
if Locate('loan_id',detail.Loan.Id,[]) then
begin
balance := detail.Loan.Balance - detail.Principal;
// if FDate <= detail.Loan.NextPayment then prcDeficit := detail.Loan.PrincipalDeficit - detail.Principal
// else prcDeficit := detail.Loan.PrincipalDeficit + (detail.Loan.PrincipalAmortisation - detail.Principal);
prcDeficit := detail.Loan.PrincipalDeficit - detail.Principal;
if FDate > detail.Loan.NextPayment then
intDeficit := detail.Loan.InterestDeficit + (detail.Loan.InterestDueOnPaymentDate - detail.Interest) // (detail.Loan.InterestAdditional - detail.Interest)
else
intDeficit := detail.Loan.InterestDeficit + (detail.Loan.InterestDueOnPaymentDate - detail.Interest);
Edit;
FieldByName('balance').AsCurrency := balance;
FieldByName('prc_deficit').AsCurrency := prcDeficit;
FieldByName('int_deficit').AsCurrency := intDeficit;
FieldByName('last_trans_date').AsDateTime := FDate;
if detail.IsFullPayment then FieldByName('status_id').AsString := 'X';
Post;
end;
end;
end;
except
on E: Exception do ShowErrorBox(E.Message);
end;
end;
procedure TPayment.Retrieve;
var
detail: TPaymentDetail;
loan: TLoan;
currentLoanId: string;
begin
// head
with dmPayment.dstPayment do
begin
Close;
Open;
end;
// detail
with dmPayment.dstPaymentDetail do
begin
Close;
Open;
while not Eof do
begin
// loan details..instantiate for every loan ID.. NOT for every row
// Reason: each detail will contain the PRINCIPAL, INTEREST and PENALTY amounts
if (not Assigned(loan)) or (loan.Id <> currentLoanId) then
begin
loan := TLoan.Create;
loan.Id := FieldByName('loan_id').AsString;
loan.LoanTypeName := FieldByName('loan_type_name').AsString;
loan.AccountTypeName := FieldByName('acct_type_name').AsString;
loan.Balance := FieldByName('balance').AsCurrency;
detail := TPaymentDetail.Create;
detail.Loan := loan;
detail.Remarks := FieldByName('remarks').AsString;
detail.Cancelled := FieldByName('is_cancelled').AsInteger = 1;
end;
// set principal, interest, penalty
if FieldByName('payment_type').AsString = 'PRN' then
detail.Principal := FieldByName('payment_amt').AsCurrency
else if FieldByName('payment_type').AsString = 'INT' then
detail.Interest := FieldByName('payment_amt').AsCurrency
else if FieldByName('payment_type').AsString = 'PEN' then
detail.Penalty := FieldByName('payment_amt').AsCurrency;
Next;
currentLoanId := FieldByName('loan_id').AsString;
if (Eof) or (loan.Id <> currentLoanId) then AddDetail(detail);
end;
end;
end;
function TPayment.GetChangeAmount: currency;
begin
if IsWithdrawal then Result := Withdrawn - TotalAmount
else Result := 0;
end;
function TPayment.GetDetail(const i: Integer): TPaymentDetail;
begin
Result := FDetails[i];
end;
function TPayment.GetTotalAmount: currency;
var
pd: TPaymentDetail;
begin
Result := 0;
for pd in FDetails do Result := Result + pd.Principal + pd.Interest + pd.Penalty;
end;
function TPayment.DetailExists(const loan: TLoan): boolean;
var
pd: TPaymentDetail;
begin
Result := false;
for pd in FDetails do
begin
if pd.Loan.Id = loan.Id then
begin
Result := true;
Exit;
end;
end;
end;
function TPayment.GetDetailCount: integer;
begin
Result := Length(FDetails);
end;
function TPayment.GetIsPosted: boolean;
begin
Result := FPostDate > 0;
end;
function TPayment.GetIsWithdrawal: boolean;
begin
Result := FPaymentMethod.Method = mdBankWithdrawal;
end;
function TPayment.GetIsLate: boolean;
begin
Result := FDate > ifn.AppDate;
end;
function TPayment.GetIsNew: boolean;
begin
Result := FPaymentId = '';
end;
function TPaymentDetail.GetHasInterest: boolean;
begin
Result := FInterest > 0;
end;
function TPaymentDetail.GetHasPrincipal: boolean;
begin
Result := FPrincipal > 0;
end;
function TPaymentDetail.GetPenalty: boolean;
begin
Result := FPenalty > 0;
end;
function TPaymentDetail.GetNewScheduleDate(const ACurrentDate,
ANextDate: TDateTime): TDateTime;
var
month1, day1, year1: word;
month2, day2, year2: word;
LNextDate: TDateTime;
begin
LNextDate := ANextDate;
DecodeDate(ACurrentDate,year1,month1,day1);
DecodeDate(LNextDate,year2,month2,day2);
// if dates are of the same month.. increment to the next month
if month2 = month1 then
begin
LNextDate := IncMonth(LNextDate);
DecodeDate(LNextDate,year2,month2,day2);
end;
if (month2 = MonthFebruary) and (DaysBetween(LNextDate,ACurrentDate) < ifn.DaysInAMonth)then
Result := IncDay(ACurrentDate,ifn.DaysInAMonth)
else if (day1 = 31) and (month2 <> MonthFebruary) then
Result := EncodeDate(year2,month2,30)
else Result := EncodeDate(year2,month2,day1);
end;
function TPaymentDetail.GetTotalAmount: currency;
begin
Result := FPrincipal + FInterest + FPenalty;
end;
function TPaymentDetail.IsAdvanced: boolean;
begin
Result := FPaymentDate < FLoan.NextPayment;
end;
function TPaymentDetail.IsLate: boolean;
begin
Result := FPaymentDate > FLoan.NextPayment;
end;
function TPaymentDetail.IsScheduled: boolean;
begin
Result := FPaymentDate = FLoan.NextPayment;
end;
function TPaymentDetail.PaymentTypeToString(
const payType: TPaymentType): string;
begin
case payType of
ptPrincipal: Result := 'PRN';
ptInterest: Result := 'INT';
ptPenalty: Result := 'PEN';
end;
end;
procedure TPaymentDetail.Post;
var
debitLedger, creditLedger: TLedger;
balance, payment: currency;
i, cnt: integer;
caseType: string;
paymentType: TPaymentTypes;
begin
payment := 0;
// post the payment in the ledger
for paymentType := TPaymentTypes.PRN to TPaymentTypes.PEN do
begin
// get the amount and casetype to be posted
case paymentType of
PRN:
begin
caseType := TRttiEnumerationType.GetName<TCaseTypes>(TCaseTypes.PRC);
payment := FPrincipal;
end;
INT:
begin
caseType := TRttiEnumerationType.GetName<TCaseTypes>(TCaseTypes.ITS);
payment := FInterest;
// update interest schedule
{if ((FLoan.IsDiminishing) and (FLoan.DiminishingType = dtFixed)) or (FIsFullPayment) then
if ((FLoan.HasInterestComputed) or (FLoan.HasInterestAdditional)) or (FIsFullPayment)
or (DayOfTheMonth(FPaymentDate) = 30)then
UpdateInterestSchedule; }
// save unposted interest
if (FIsFullPayment) or
((FLoan.IsDiminishing) and (FLoan.DiminishingType = dtFixed)) then
SaveInterest;
end;
PEN:
begin
caseType := TRttiEnumerationType.GetName<TCaseTypes>(TCaseTypes.PNT);
payment := FPenalty;
end;
end;
i := 0;
cnt := FLoan.LedgerCount - 1;
balance := payment;
while (balance > 0) and (i <= cnt) do
begin
debitLedger := FLoan.Ledger[i];
if (debitLedger.CaseType = caseType) and (debitLedger.Debit > 0) then
begin
creditLedger := TLedger.Create;
// set the amount and the status
if debitLedger.Debit <= balance then
begin
creditLedger.Credit := debitLedger.Debit;
debitLedger.NewStatus := TRttiEnumerationType.GetName<TLedgerRecordStatus>(TLedgerRecordStatus.CLS);
end
else creditLedger.Credit := balance;
creditLedger.RefPostingId := debitLedger.PostingId;
creditLedger.EventObject := TRttiEnumerationType.GetName<TEventObjects>(TEventObjects.PAY);
creditLedger.PrimaryKey := FPaymentId;
creditLedger.CaseType := caseType;
creditLedger.ValueDate := FPaymentDate;
creditLedger.CurrentStatus := TRttiEnumerationType.GetName<TLedgerRecordStatus>(TLedgerRecordStatus.OPN);
creditLedger.Debit := 0;
FLoan.AddLedger(creditLedger);
balance := balance - creditLedger.Credit;
end;
Inc(i);
end; // end while
// for extra payment.. add the amount to the last credit ledger
// this happens when payment is before payment date
// normal practice is to collect the monthly amortization regardless of when payment is made
// this is only applicable to diminishing fixed loans
if balance > 0 then creditLedger.Credit := creditLedger.Credit + balance;
end;
end;
function TPaymentDetail.PostInterest(const interest: currency; const loanId: string;
const ADate: TDateTime; const source, status: string): string;
var
interestId: string;
begin
interestId := GetInterestId;
with dmPayment.dstInterests do
begin
Append;
FieldByName('interest_id').AsString := interestId;
FieldByName('loan_id').AsString := loanId;
FieldByName('interest_amt').AsCurrency := interest;
FieldByName('interest_date').AsDateTime := ADate;
FieldByName('interest_src').AsString := source;
FieldByName('interest_status_id').AsString := status;
Post;
end;
Result := interestId;
end;
procedure TPaymentDetail.SaveInterest;
var
LLedger: TLedger;
i, cnt: integer;
interestId, loanId, source, status: string;
interest: currency;
interestDate: TDateTime;
begin
try
cnt := FLoan.LedgerCount - 1;
for i := 0 to cnt do
begin
LLedger := FLoan.Ledger[i];
if (LLedger.EventObject = TRttiEnumerationType.GetName<TEventObjects>(TEventObjects.ITR))
and (LLedger.CaseType = TRttiEnumerationType.GetName<TCaseTypes>(TCaseTypes.ITS)) then
begin
if not LLedger.Posted then
begin
if (not FIsFullPayment)
or ((FIsFullPayment) and ((LLedger.FullPayment) or ((FLoan.IsDiminishing) and (FLoan.DiminishingType = dtFixed)))) then
begin
interest := LLedger.Debit;
loanId := FLoan.Id;
interestDate := LLedger.ValueDate;
source := TRttiEnumerationType.GetName<TInterestSource>(TInterestSource.PYT);
status := TRttiEnumerationType.GetName<TInterestStatus>(TInterestStatus.T);
interestId := PostInterest(interest,loanId,interestDate,source,status);
LLedger.PrimaryKey := interestId;
end;
end;
end;
end;
finally
end;
end;
procedure TPaymentDetail.UpdateInterestSchedule;
var
newScheduleDate, interestDate: TDateTime;
m, d, y, mm, dd, yy, pm, pd, py, nm, nd, ny: word;
pending: boolean;
i, monthsRemaining: integer;
sameMonth: boolean;
newInterest, LBalance: currency;
begin
DecodeDate(FLoan.NextPayment,ny,nm,nd);
DecodeDate(FPaymentDate,py,pm,pd);
sameMonth := (ny = py) and (nm = pm); // payment is the same as the month of the scheduled interest but not on the scheduled date
if (FPaymentDate < FLoan.NextPayment) and (sameMonth) then i := 0
else i := 1;
try
with dmPayment.dstInterests do
begin
// filter the dataset
Filter := 'loan_id = ' + QuotedStr(FLoan.Id);
LBalance := FLoan.Balance - FPrincipal;
// get the remaining months to loan due date
// used to determine number of months to post interest
monthsRemaining := FLoan.ApprovedTerm - MonthsBetween(FPaymentDate,FLoan.ReleaseDate);
newScheduleDate := FPaymentDate;
{$region 'NEW SOLUTION'}
while i < monthsRemaining do
begin
pending := FieldByName('interest_status_id').AsString =
TRttiEnumerationType.GetName<TInterestStatus>(TInterestStatus.P);
if pending then
begin
// newDate := IncMonth(FPaymentDate,i);
newScheduleDate := GetNewScheduleDate(newScheduleDate,IncMonth(FPaymentDate,i));
interestDate := FieldByName('interest_date').AsDateTime;
DecodeDate(newScheduleDate,y,m,d);
DecodeDate(interestDate,yy,mm,dd);
Edit;
if ((py = yy) and (pm = mm)) or (FIsFullPayment) then // change the status of the PENDING interest of month of the payment date
FieldByName('interest_status_id').AsString :=
TRttiEnumerationType.GetName<TInterestStatus>(TInterestStatus.D)
else if (y = yy) and (m = mm) and (d <> dd) then
begin
if HasPrincipal then
begin
newInterest := LBalance * FLoan.InterestInDecimal;
FieldByName('interest_amt').AsCurrency := newInterest;
LBalance := LBalance - (FLoan.ReleaseAmount / FLoan.ApprovedTerm);
end;
FieldByName('interest_date').AsDateTime := newScheduleDate;
end;
Post;
Inc(i);
end;
Inc(i);
end;
{$endregion}
{$region 'OLD SOLUTION'}
while not Eof do
begin
pending := FieldByName('interest_status_id').AsString =
TRttiEnumerationType.GetName<TInterestStatus>(TInterestStatus.P);
if pending then
begin
// newDate := IncMonth(FPaymentDate,i);
newScheduleDate := GetNewScheduleDate(newScheduleDate,IncMonth(FPaymentDate,i));
interestDate := FieldByName('interest_date').AsDateTime;
DecodeDate(newScheduleDate,y,m,d);
DecodeDate(interestDate,yy,mm,dd);
Edit;
if ((py = yy) and (pm = mm)) or (FIsFullPayment) then // change the status of the PENDING interest of month of the payment date
FieldByName('interest_status_id').AsString :=
TRttiEnumerationType.GetName<TInterestStatus>(TInterestStatus.D)
else if (y = yy) and (m = mm) and (d <> dd) then
begin
if HasPrincipal then
begin
newInterest := LBalance * FLoan.InterestInDecimal;
FieldByName('interest_amt').AsCurrency := newInterest;
LBalance := LBalance - (FLoan.ReleaseAmount / FLoan.ApprovedTerm);
end;
FieldByName('interest_date').AsDateTime := newScheduleDate;
end;
Post;
Inc(i);
end;
Next;
end;
{$endregion}
end;
finally
end;
end;
end.
|
unit bool_arithmetic_2;
interface
implementation
function GetBool(B: Boolean): Boolean;
begin
Result := B;
end;
var R1, R2: Int32;
procedure Test;
begin
if not GetBool(False) then
R1 := 11
else
R1 := 22;
if not GetBool(True) then
R2 := 11
else
R2 := 22;
end;
initialization
Test();
finalization
Assert(R1 = 11);
Assert(R2 = 22);
end. |
unit mainUnit;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtDlgs, StdCtrls, ComCtrls, ExtCtrls, Buttons, ToolWin, ImgList;
type
TForm1 = class(TForm)
SavePictureDialog1: TSavePictureDialog;
OpenPictureDialog1: TOpenPictureDialog;
ScrollBox1: TScrollBox;
Image1: TImage;
ToolBar1: TToolBar;
OpenBtn: TToolButton;
SaveBtn: TToolButton;
Panel2: TPanel;
ProgressBar1: TProgressBar;
ImageList1: TImageList;
procedure SavePictureDialog1TypeChange(Sender: TObject);
procedure Image1Progress(Sender: TObject; Stage: TProgressStage;
PercentDone: Byte; RedrawNow: Boolean; const R: TRect;
const Msg: String);
procedure SavePictureDialog1Close(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure OpenBitBtnClick(Sender: TObject);
procedure SaveBitBtnClick(Sender: TObject);
procedure ToolBar1Resize(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
uses jpeg;
const DeltaH : Integer = 80;
var Quality : TJpegQualityRange;
ProgressiveEnc : Boolean;
procedure TForm1.FormCreate(Sender: TObject);
var s: string;
begin
s :=GraphicFilter(TBitmap)+'|'+GraphicFilter(TJpegImage);
OpenPictureDialog1.Filter := s;
SavePictureDialog1.Filter := s;
end;
procedure TForm1.OpenBitBtnClick(Sender: TObject);
begin
if OpenPictureDialog1.Execute
then
begin
Image1.Picture.LoadFromFile(OpenPictureDialog1.FileName);
SaveBtn.Enabled := True;
end;
end;
procedure TForm1.SaveBitBtnClick(Sender: TObject);
var ji : TJpegImage;
begin
with SavePictureDialog1 do
begin
FilterIndex := 1;
FileName := '';
if not Execute then Exit;
if Pos('.',FileName)=0 then
if (FilterIndex=1) then
FileName := FileName + '.bmp'
else
FileName := FileName + '.jpg';
if (FilterIndex=1) then
Image1.Picture.Bitmap.SaveToFile(FileName)
else
begin
ji := TJpegImage.Create;
ji.CompressionQuality := Quality;
ji.ProgressiveEncoding := ProgressiveEnc;
ji.OnProgress := Image1Progress;
ji.Assign(Image1.Picture.Bitmap);
ji.SaveToFile(FileName);
ji.Free;
end;
end;
end;
procedure TForm1.SavePictureDialog1TypeChange(Sender: TObject);
var ParentHandle:THandle;wRect:TRect;
PicPanel,PaintPanel:TPanel;QEdit : TEdit;
begin
With Sender as TSavePictureDialog do
begin
//родительская панель
PicPanel := (FindComponent('PicturePanel') as TPanel);
if not Assigned(PicPanel) then Exit;
ParentHandle:=GetParent(Handle);
//панель-сосед сверху
PaintPanel:=(FindComponent('PaintPanel') as TPanel);
PaintPanel.Align := alNone;
if FilterIndex >1 then
begin
GetWindowRect(ParentHandle,WRect);
SetWindowPos(ParentHandle,0,0,0,WRect.Right-WRect.Left,
WRect.Bottom-WRect.Top+DeltaH,SWP_NOMOVE+SWP_NOZORDER);
GetWindowRect(Handle,WRect);
SetWindowPos(handle,0,0,0,WRect.Right-WRect.Left,
WRect.Bottom-WRect.Top+DeltaH,SWP_NOMOVE+SWP_NOZORDER);
PicPanel.Height := PicPanel.Height+DeltaH;
if FindComponent('JLabel')=nil then
with TLabel.Create(Sender as TSavePictureDialog) do
begin
Parent := PicPanel;
Name := 'JLabel';
Caption := 'Quality';
Left := 5;//Width := PicPanel.Width - 10;
Height := 25;
Top := PaintPanel.Top+PaintPanel.Height+5;
end;
if FindComponent('JEdit')=nil then
begin
QEdit := TEdit.Create(Sender as TSavePictureDialog);
with QEdit do
begin
Parent := PicPanel;
Name:='JEdit';
Text := '75';
Left:=50;Width := 50;
Height := 25;
Top := PaintPanel.Top+PaintPanel.Height+5;
end;
end;
if FindComponent('JUpDown')=nil then
with TUpDown.Create(Sender as TSavePictureDialog) do
begin
Parent := PicPanel;
Name:='JUpDown';
Associate := QEdit;
Increment := 5;
Min := 1; Max := 100;
Position := 75;
end;
if FindComponent('JCheck')=nil then
with TCheckBox.Create(Sender as TSavePictureDialog) do
begin
Name:='JCheck';
Caption:='Progressive Encoding';
Parent:=PicPanel;
Left:=5;Width := PicPanel.Width - 10;
Height:=25;
Top := PaintPanel.Top+PaintPanel.Height+35;
end;
end
else
SavePictureDialog1Close(Sender);
end;
end;
procedure TForm1.Image1Progress(Sender: TObject; Stage: TProgressStage;
PercentDone: Byte; RedrawNow: Boolean; const R: TRect;
const Msg: String);
begin
case Stage of
psStarting: begin
Progressbar1.Position := 0;
Progressbar1.Max := 100;
end;
psEnding: begin
Progressbar1.Position := 0;
end;
psRunning: begin
Progressbar1.Position := PercentDone;
end;
end;
end;
procedure TForm1.SavePictureDialog1Close(Sender: TObject);
var PicPanel : TPanel; ParentHandle : THandle; WRect : TRect;
begin
With Sender as TSavePictureDialog do
begin
PicPanel := (FindComponent('PicturePanel') as TPanel);
if not Assigned(PicPanel) then Exit;
ParentHandle:=GetParent(Handle);
if ParentHandle=0 then Exit;
if FindComponent('JLabel')<>nil then
try
FindComponent('JLabel').Free;
FindComponent('JEdit').Free;
ProgressiveEnc := (FindComponent('JCheck') as TCheckBox).Checked;
FindComponent('JCheck').Free;
Quality := (FindComponent('JUpDown') as TUpDown).Position;
FindComponent('JUpDown').Free;
PicPanel.Height:=PicPanel.Height-DeltaH;
GetWindowRect(Handle,WRect);
SetWindowPos(Handle,0,0,0,WRect.Right-WRect.Left,
WRect.Bottom-WRect.Top-DeltaH,SWP_NOMOVE+SWP_NOZORDER);
GetWindowRect(ParentHandle,WRect);
SetWindowPos(ParentHandle,0,0,0,WRect.Right-WRect.Left,
WRect.Bottom-WRect.Top-DeltaH,SWP_NOMOVE+SWP_NOZORDER);
FilterIndex := 1;
except
ShowMessage('Dialog resizing error');
end;
end;
end;
procedure TForm1.ToolBar1Resize(Sender: TObject);
begin
Panel2.Width := ToolBar1.Width - Panel2.Left;
end;
end.
|
unit uGBMontaSelect;
interface
uses
System.SysUtils, System.Classes, Vcl.Forms, Vcl.Controls;
type
TGBMontaSelect = class(TComponent)
private
_RetornouValor: Boolean;
FParams: TStrings;
FFiltros: TStrings;
Ftabelas: TStrings;
FExibePergunta: Boolean;
FLarguras: TStrings;
FCaseSentive: TStrings;
FCamposChave: TStrings;
FDescricao: TStrings;
FUsaDistinct: Boolean;
FCaption: String;
FColunas: TStrings;
FTipoDeDado: TStrings;
FValoresChave: TStrings;
procedure SetCamposChave(const Value: TStrings);
procedure SetCaption(const Value: String);
procedure SetCaseSentive(const Value: TStrings);
procedure SetColunas(const Value: TStrings);
procedure SetDescricao(const Value: TStrings);
procedure SetExibePergunta(const Value: Boolean);
procedure SetFiltros(const Value: TStrings);
procedure SetLarguras(const Value: TStrings);
procedure SetParams(const Value: TStrings);
procedure Settabelas(const Value: TStrings);
procedure SetTipoDeDado(const Value: TStrings);
procedure SetUsaDistinct(const Value: Boolean);
procedure SetValoresChave(const Value: TStrings);
{ Private declarations }
protected
{ Protected declarations }
public
function executar: Boolean;
function RetornouValor: Boolean;
constructor Create(AOwner: TComponent); override;
{ Public declarations }
published
property Caption : String read FCaption write SetCaption;
property CamposChave : TStrings read FCamposChave write SetCamposChave;
property CaseSentive : TStrings read FCaseSentive write SetCaseSentive;
property Colunas : TStrings read FColunas write SetColunas;
property Descricao : TStrings read FDescricao write SetDescricao;
property ExibePergunta : Boolean read FExibePergunta write SetExibePergunta default False;
property Filtros : TStrings read FFiltros write SetFiltros;
property Larguras : TStrings read FLarguras write SetLarguras;
property Params : TStrings read FParams write SetParams;
property Tabelas : TStrings read Ftabelas write Settabelas;
property TipoDeDado : TStrings read FTipoDeDado write SetTipoDeDado;
property UsaDistinct : Boolean read FUsaDistinct write SetUsaDistinct default False;
property ValoresChave : TStrings read FValoresChave write SetValoresChave;
{ Published declarations }
end;
procedure Register;
implementation
uses FSeleciona;
procedure Register;
begin
RegisterComponents('Gabalt10', [TGBMontaSelect]);
end;
{ TGBMontaSelect }
constructor TGBMontaSelect.Create(AOwner: TComponent);
begin
inherited;
Self.FCamposChave := TStringList.Create;
Self.Ftabelas := TStringList.Create;
Self.FColunas := TStringList.Create;
Self.FDescricao := TStringList.Create;
Self.FFiltros := TStringList.Create;
Self.FLarguras := TStringList.Create;
Self.FParams := TStringList.Create;
Self.FCaseSentive := TStringList.Create;
Self.FTipoDeDado := TStringList.Create;
Self.FValoresChave:= TStringList.Create;
_RetornouValor := False;
end;
function TGBMontaSelect.executar: Boolean;
begin
result := False;
frmSeleciona := TfrmSeleciona.Create(Application, Self);
frmSeleciona.ShowModal;
_RetornouValor := frmSeleciona.ModalResult = mrOk;
frmSeleciona.Free;
end;
function TGBMontaSelect.RetornouValor: Boolean;
begin
result := _RetornouValor;
end;
procedure TGBMontaSelect.SetCamposChave(const Value: TStrings);
begin
FCamposChave.Text := Value.Text;
end;
procedure TGBMontaSelect.SetCaption(const Value: String);
begin
FCaption := Value;
end;
procedure TGBMontaSelect.SetCaseSentive(const Value: TStrings);
begin
FCaseSentive.Text := Value.Text;
end;
procedure TGBMontaSelect.SetColunas(const Value: TStrings);
begin
FColunas.Text := Value.Text;
end;
procedure TGBMontaSelect.SetDescricao(const Value: TStrings);
begin
FDescricao.Text := Value.Text;
end;
procedure TGBMontaSelect.SetExibePergunta(const Value: Boolean);
begin
FExibePergunta := Value;
end;
procedure TGBMontaSelect.SetFiltros(const Value: TStrings);
begin
FFiltros.Text := Value.Text;
end;
procedure TGBMontaSelect.SetLarguras(const Value: TStrings);
begin
FLarguras.Text := Value.Text;
end;
procedure TGBMontaSelect.SetParams(const Value: TStrings);
begin
FParams.Text := Value.Text;
end;
procedure TGBMontaSelect.Settabelas(const Value: TStrings);
begin
Ftabelas.Text := Value.Text;
end;
procedure TGBMontaSelect.SetTipoDeDado(const Value: TStrings);
begin
FTipoDeDado.Text := Value.Text;
end;
procedure TGBMontaSelect.SetUsaDistinct(const Value: Boolean);
begin
FUsaDistinct := Value;
end;
procedure TGBMontaSelect.SetValoresChave(const Value: TStrings);
begin
FValoresChave.Text := Value.Text;
end;
end.
|
unit MovimentoDeCaixaAplicacao;
interface
uses Classes,
{ Fluente }
DataUtil, UnModelo, Componentes, UnAplicacao,
UnMovimentoDeCaixaListaRegistrosModelo,
UnMovimentoDeCaixaListaRegistrosView,
UnMovimentoDeCaixaRegistroView,
UnMovimentoDeCaixaImpressaoView;
type
TMovimentoDeCaixaAplicacao = class(TAplicacao, IResposta)
private
FMovimentoDeCaixaListaRegistrosView: ITela;
public
function AtivarAplicacao: TAplicacao; override;
procedure Responder(const Chamada: TChamada);
function Descarregar: TAplicacao; override;
function Preparar(const ConfiguracaoAplicacao: TConfiguracaoAplicacao = nil):
TAplicacao; override;
end;
implementation
{ TMovimentoDeContaCorrenteAplicacao }
function TMovimentoDeCaixaAplicacao.AtivarAplicacao: TAplicacao;
begin
Self.FMovimentoDeCaixaListaRegistrosView :=
TMovimentoDeCaixaListaRegistrosView.Create(nil)
.Modelo(Self.FFabricaDeModelos
.ObterModelo('MovimentoDeCaixaListaRegistrosModelo'))
.Controlador(Self)
.Preparar;
Self.FMovimentoDeCaixaListaRegistrosView.ExibirTela;
Result := Self;
end;
function TMovimentoDeCaixaAplicacao.Descarregar: TAplicacao;
begin
Result := Self;
end;
function TMovimentoDeCaixaAplicacao.Preparar(
const ConfiguracaoAplicacao: TConfiguracaoAplicacao = nil): TAplicacao;
begin
Result := Self;
end;
procedure TMovimentoDeCaixaAplicacao.Responder(const Chamada: TChamada);
var
_OidRegistro: string;
_acao: AcaoDeRegistro;
_modelo: TModelo;
_registroView: ITela;
begin
_modelo := Self.FFabricaDeModelos
.ObterModelo('MovimentoDeCaixaRegistroModelo');
_acao := RetornarAcaoDeRegistro(
Chamada.ObterParametros.Ler('acao').ComoInteiro);
if _acao in [adrIncluir, adrCarregar] then
begin
if _acao = adrIncluir then
_modelo.Incluir
else
begin
_OidRegistro := Chamada.ObterParametros.Ler('oid').ComoTexto;
_modelo.CarregarPor(
Criterio.Campo('cxmv_oid').igual(_OidRegistro).obter);
end;
_registroView := TMovimentoDeCaixaRegistroView.Create(nil)
.Modelo(_modelo)
.Controlador(Self)
.Preparar;
try
_registroView.ExibirTela;
finally
_registroView.Descarregar;
end;
end
else
if _acao = adrOutra then
begin
_modelo := (Chamada.ObterParametros.Ler('modelo').ComoObjeto
as TModelo);
_registroView := TMovimentoDeCaixaImpressaoView.Create(nil)
.Controlador(Self)
.Modelo(_modelo)
.Preparar;
try
_registroView.ExibirTela;
finally
_registroView.Descarregar;
end;
end
end;
initialization
RegisterClass(TMovimentoDeCaixaAplicacao);
end.
|
unit Ths.Erp.Database.Table.Arac.Hareket;
interface
{$I ThsERP.inc}
uses
SysUtils, Classes, Dialogs, Forms, Windows, Controls, Types, DateUtils,
FireDAC.Stan.Param, System.Variants, Data.DB,
Ths.Erp.Database
, Ths.Erp.Database.Table
;
type
THareket = class(TTable)
private
FYetkili: TFieldDB;
FSurucu: TFieldDB;
FPlaka: TFieldDB;
FGorev: TFieldDB;
FCikisYeri: TFieldDB;
FCikisKM: TFieldDB;
FCikisTarihi: TFieldDB;
FVarisYeri: TFieldDB;
FVarisKM: TFieldDB;
FVarisTarihi: TFieldDB;
FAciklama: TFieldDB;
FSure: TFieldDB;
protected
procedure BusinessUpdate(pPermissionControl: Boolean); override;
published
constructor Create(pOwnerDatabase: TDatabase); override;
public
procedure SelectToDatasource(pFilter: string; pPermissionControl: Boolean = True); override;
procedure SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean = True); override;
procedure Insert(out pID: Integer; pPermissionControl: Boolean = True); override;
procedure Update(pPermissionControl: Boolean = True); override;
function Clone(): TTable; override;
property Yetkili: TFieldDB read FYetkili write FYetkili;
property Surucu: TFieldDB read FSurucu write FSurucu;
property Plaka: TFieldDB read FPlaka write FPlaka;
property Gorev: TFieldDB read FGorev write FGorev;
property CikisYeri: TFieldDB read FCikisYeri write FCikisYeri;
property CikisKM: TFieldDB read FCikisKM write FCikisKM;
property CikisTarihi: TFieldDB read FCikisTarihi write FCikisTarihi;
property VarisYeri: TFieldDB read FVarisYeri write FVarisYeri;
property VarisKM: TFieldDB read FVarisKM write FVarisKM;
property VarisTarihi: TFieldDB read FVarisTarihi write FVarisTarihi;
property Aciklama: TFieldDB read FAciklama write FAciklama;
property Sure: TFieldDB read FSure write FSure;
end;
implementation
uses
Ths.Erp.Constants,
Ths.Erp.Database.Singleton;
{ TAracHareketi }
constructor THareket.Create(pOwnerDatabase:TDatabase);
begin
inherited Create(pOwnerDatabase);
TableName := 'arac_hareketi';
SourceCode := '1000';
FYetkili := TFieldDB.Create('yetkili', ftString, '');
FSurucu := TFieldDB.Create('surucu', ftString, '');
FPlaka := TFieldDB.Create('plaka', ftString, '');
FGorev := TFieldDB.Create('gorev', ftString, '');
FCikisYeri := TFieldDB.Create('cikis_yeri', ftString, 0);
FCikisKM := TFieldDB.Create('cikis_km', ftInteger, 0);
FCikisTarihi := TFieldDB.Create('cikis_tarihi', ftDateTime, '');
FVarisYeri := TFieldDB.Create('varis_yeri', ftString, '');
FVarisKM := TFieldDB.Create('varis_km', ftInteger, 0);
FVarisTarihi := TFieldDB.Create('varis_tarihi', ftDateTime, 0);
FAciklama := TFieldDB.Create('aciklama', ftString, '');
FSure := TFieldDB.Create('sure', ftString, '');
end;
procedure THareket.SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptRead, pPermissionControl) then
begin
with QueryOfDS do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLSelectCmd(TableName, [
TableName + '.' + Self.Id.FieldName,
TableName + '.' + FYetkili.FieldName,
TableName + '.' + FSurucu.FieldName,
TableName + '.' + FPlaka.FieldName,
TableName + '.' + FGorev.FieldName,
TableName + '.' + FCikisYeri.FieldName,
TableName + '.' + FCikisKM.FieldName,
TableName + '.' + FCikisTarihi.FieldName,
TableName + '.' + FVarisYeri.FieldName,
TableName + '.' + FVarisKM.FieldName,
TableName + '.' + FVarisTarihi.FieldName,
TableName + '.' + FAciklama.FieldName,
TableName + '.' + FSure.FieldName
]) +
'WHERE 1=1 ' + pFilter;
Open;
Active := True;
Self.DataSource.DataSet.FindField(Self.Id.FieldName).DisplayLabel := 'Id';
Self.DataSource.DataSet.FindField(FYetkili.FieldName).DisplayLabel := 'Yetkili';
Self.DataSource.DataSet.FindField(FSurucu.FieldName).DisplayLabel := 'Sürücü';
Self.DataSource.DataSet.FindField(FPlaka.FieldName).DisplayLabel := 'Plaka';
Self.DataSource.DataSet.FindField(FGorev.FieldName).DisplayLabel := 'Görev';
Self.DataSource.DataSet.FindField(FCikisYeri.FieldName).DisplayLabel := 'Çıkış Yeri';
Self.DataSource.DataSet.FindField(FCikisKM.FieldName).DisplayLabel := 'Çıkış KM';
Self.DataSource.DataSet.FindField(FCikisTarihi.FieldName).DisplayLabel := 'Çıkış Tarihi';
Self.DataSource.DataSet.FindField(FVarisYeri.FieldName).DisplayLabel := 'Varış Yeri';
Self.DataSource.DataSet.FindField(FVarisKM.FieldName).DisplayLabel := 'Varış KM';
Self.DataSource.DataSet.FindField(FVarisTarihi.FieldName).DisplayLabel := 'Varış Tarihi';
Self.DataSource.DataSet.FindField(FAciklama.FieldName).DisplayLabel := 'Açıklama';
Self.DataSource.DataSet.FindField(FSure.FieldName).DisplayLabel := 'Süre';
end;
end;
end;
procedure THareket.SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptRead, pPermissionControl) then
begin
if (pLock) then
pFilter := pFilter + ' FOR UPDATE OF ' + TableName + ' NOWAIT';
with QueryOfList do
begin
Close;
SQL.Text := Database.GetSQLSelectCmd(TableName, [
TableName + '.' + Self.Id.FieldName,
TableName + '.' + FYetkili.FieldName,
TableName + '.' + FSurucu.FieldName,
TableName + '.' + FPlaka.FieldName,
TableName + '.' + FGorev.FieldName,
TableName + '.' + FCikisYeri.FieldName,
TableName + '.' + FCikisKM.FieldName,
TableName + '.' + FCikisTarihi.FieldName,
TableName + '.' + FVarisYeri.FieldName,
TableName + '.' + FVarisKM.FieldName,
TableName + '.' + FVarisTarihi.FieldName,
TableName + '.' + FAciklama.FieldName,
TableName + '.' + FSure.FieldName
]) +
'WHERE 1=1 ' + pFilter;
Open;
FreeListContent();
List.Clear;
while NOT EOF do
begin
Self.Id.Value := FormatedVariantVal(FieldByName(Self.Id.FieldName).DataType, FieldByName(Self.Id.FieldName).Value);
FYetkili.Value := FormatedVariantVal(FieldByName(FYetkili.FieldName).DataType, FieldByName(FYetkili.FieldName).Value);
FSurucu.Value := FormatedVariantVal(FieldByName(FSurucu.FieldName).DataType, FieldByName(FSurucu.FieldName).Value);
FPlaka.Value := FormatedVariantVal(FieldByName(FPlaka.FieldName).DataType, FieldByName(FPlaka.FieldName).Value);
FGorev.Value := FormatedVariantVal(FieldByName(FGorev.FieldName).DataType, FieldByName(FGorev.FieldName).Value);
FCikisYeri.Value := FormatedVariantVal(FieldByName(FCikisYeri.FieldName).DataType, FieldByName(FCikisYeri.FieldName).Value);
FCikisKM.Value := FormatedVariantVal(FieldByName(FCikisKM.FieldName).DataType, FieldByName(FCikisKM.FieldName).Value);
FCikisTarihi.Value := FormatedVariantVal(FieldByName(FCikisTarihi.FieldName).DataType, FieldByName(FCikisTarihi.FieldName).Value);
FVarisYeri.Value := FormatedVariantVal(FieldByName(FVarisYeri.FieldName).DataType, FieldByName(FVarisYeri.FieldName).Value);
FVarisKM.Value := FormatedVariantVal(FieldByName(FVarisKM.FieldName).DataType, FieldByName(FVarisKM.FieldName).Value);
FVarisTarihi.Value := FormatedVariantVal(FieldByName(FVarisTarihi.FieldName).DataType, FieldByName(FVarisTarihi.FieldName).Value);
FAciklama.Value := FormatedVariantVal(FieldByName(FAciklama.FieldName).DataType, FieldByName(FAciklama.FieldName).Value);
FSure.Value := FormatedVariantVal(FieldByName(FSure.FieldName).DataType, FieldByName(FSure.FieldName).Value);
List.Add(Self.Clone());
Next;
end;
Close;
end;
end;
end;
procedure THareket.Insert(out pID: Integer; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptAddRecord, pPermissionControl) then
begin
with QueryOfInsert do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLInsertCmd(TableName, QUERY_PARAM_CHAR, [
FYetkili.FieldName,
FSurucu.FieldName,
FPlaka.FieldName,
FGorev.FieldName,
FCikisYeri.FieldName,
FCikisKM.FieldName,
FCikisTarihi.FieldName,
FVarisYeri.FieldName,
FVarisKM.FieldName,
FVarisTarihi.FieldName,
FAciklama.FieldName,
FSure.FieldName
]);
NewParamForQuery(QueryOfInsert, FYetkili);
NewParamForQuery(QueryOfInsert, FSurucu);
NewParamForQuery(QueryOfInsert, FPlaka);
NewParamForQuery(QueryOfInsert, FGorev);
NewParamForQuery(QueryOfInsert, FCikisYeri);
NewParamForQuery(QueryOfInsert, FCikisKM);
NewParamForQuery(QueryOfInsert, FCikisTarihi);
NewParamForQuery(QueryOfInsert, FVarisYeri);
NewParamForQuery(QueryOfInsert, FVarisKM);
NewParamForQuery(QueryOfInsert, FVarisTarihi);
NewParamForQuery(QueryOfInsert, FAciklama);
NewParamForQuery(QueryOfInsert, FSure);
Open;
if (Fields.Count > 0) and (not Fields.FieldByName(Self.Id.FieldName).IsNull) then
pID := Fields.FieldByName(Self.Id.FieldName).AsInteger
else
pID := 0;
EmptyDataSet;
Close;
end;
Self.notify;
end;
end;
procedure THareket.Update(pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptUpdate, pPermissionControl) then
begin
with QueryOfUpdate do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLUpdateCmd(TableName, QUERY_PARAM_CHAR, [
FYetkili.FieldName,
FSurucu.FieldName,
FPlaka.FieldName,
FGorev.FieldName,
FCikisYeri.FieldName,
FCikisKM.FieldName,
FCikisTarihi.FieldName,
FVarisYeri.FieldName,
FVarisKM.FieldName,
FVarisTarihi.FieldName,
FAciklama.FieldName,
FSure.FieldName
]);
NewParamForQuery(QueryOfUpdate, FYetkili);
NewParamForQuery(QueryOfUpdate, FSurucu);
NewParamForQuery(QueryOfUpdate, FPlaka);
NewParamForQuery(QueryOfUpdate, FGorev);
NewParamForQuery(QueryOfUpdate, FCikisYeri);
NewParamForQuery(QueryOfUpdate, FCikisKM);
NewParamForQuery(QueryOfUpdate, FCikisTarihi);
NewParamForQuery(QueryOfUpdate, FVarisYeri);
NewParamForQuery(QueryOfUpdate, FVarisKM);
NewParamForQuery(QueryOfUpdate, FVarisTarihi);
NewParamForQuery(QueryOfUpdate, FAciklama);
NewParamForQuery(QueryOfUpdate, FSure);
NewParamForQuery(QueryOfUpdate, Id);
ExecSQL;
Close;
end;
Self.notify;
end;
end;
procedure THareket.BusinessUpdate(pPermissionControl: Boolean);
begin
inherited;
Self.Update(pPermissionControl);
end;
function THareket.Clone():TTable;
begin
Result := THareket.Create(Database);
Self.Id.Clone(THareket(Result).Id);
FYetkili.Clone(THareket(Result).FYetkili);
FSurucu.Clone(THareket(Result).FSurucu);
FPlaka.Clone(THareket(Result).FPlaka);
FGorev.Clone(THareket(Result).FGorev);
FCikisYeri.Clone(THareket(Result).FCikisYeri);
FCikisKM.Clone(THareket(Result).FCikisKM);
FCikisTarihi.Clone(THareket(Result).FCikisTarihi);
FVarisYeri.Clone(THareket(Result).FVarisYeri);
FVarisKM.Clone(THareket(Result).FVarisKM);
FVarisTarihi.Clone(THareket(Result).FVarisTarihi);
FAciklama.Clone(THareket(Result).FAciklama);
FSure.Clone(THareket(Result).FSure);
end;
end.
|
{ Routines for sending CAN frames.
}
module can_recv;
define can_recv_check;
define can_recv;
%include 'can2.ins.pas';
{
********************************************************************************
*
* Function CAN_RECV_CHECK (CL)
*
* Returns TRUE if a received CAN frame is immediately available, and FALSE if
* none is.
}
function can_recv_check ( {find whether received CAN frame available}
in out cl: can_t) {state for this use of the library}
:boolean; {CAN frame is immediately available}
val_param;
var
fr: can_frame_t;
stat: sys_err_t;
begin
can_recv_check := false; {init to no CAN frame available}
if can_queue_ent_avail (cl.inq) then begin {a frame is in the input queue ?}
can_recv_check := true;
return;
end;
if cl.recv_p <> nil then begin {explicit frame fetch routine exists ?}
if cl.recv_p^(addr(cl), cl.dat_p, 0.0, fr, stat) then begin {got a new frame ?}
can_queue_put (cl.inq, fr); {save the frame in the input queue}
can_recv_check := true; {a frame is now immediately available ?}
end;
end;
end;
{
********************************************************************************
*
* Function CAN_RECV (CL, TOUT, FRAME, STAT)
*
* Get the next received CAN frame. This routine waits up to TOUT seconds. If
* a received CAN frame is available in that time, the description of the frame
* is returned in FRAME and the function returns TRUE. If no CAN frame is
* available within the timeout, then the function returns FALSE and the
* contents of FRAME is undefined.
}
function can_recv ( {get next received CAN frame}
in out cl: can_t; {state for this use of the library}
in tout: real; {timeout seconds or SYS_TIMEOUT_NONE_k}
out frame: can_frame_t; {CAN frame if function returns TRUE}
out stat: sys_err_t) {completion status}
:boolean; {TRUE with frame, FALSE with timeout or error}
val_param;
begin
sys_error_none (stat); {init to no error}
if cl.recv_p = nil then begin {driver pushes frames asynchronously onto queue ?}
can_recv := can_queue_get(cl.inq, tout, frame); {get next frame from queue with timeout}
return;
end;
{
* The driver has a explicit frame get routine for us to call.
}
if can_queue_get(cl.inq, 0.0, frame) then begin {get frame from queue, if any}
can_recv := true; {indicate returning with a frame ?}
return;
end;
can_recv := cl.recv_p^ ( {call driver routine to get the frame}
addr(cl), cl.dat_p, tout, frame, stat);
end;
|
unit IdGopherConsts;
{*******************************************************}
{ }
{ Indy IdGopherConsts - this just contains }
{ Constants used for writing Gopher servers }
{ and clients }
{ }
{ Copyright (C) 2000 Winshoes Working Group }
{ Original author: Pete Mee and moved to }
{ this unit by J. Peter Mugaas }
{ 2000-April-23 }
{ }
{*******************************************************}
interface
uses IdGlobal;
Const
{Item constants - comments taken from RFC}
IdGopherItem_Document = '0'; // Item is a file
IdGopherItem_Directory = '1'; // Item is a directory
IdGopherItem_CSO = '2'; // Item is a CSO phone-book server
IdGopherItem_Error = '3'; // Error
IdGopherItem_BinHex = '4'; // Item is a BinHexed Macintosh file.
IdGopherItem_BinDOS = '5'; // Item is DOS binary archive of some sort.
// Client must read until the TCP connection closes. Beware.
IdGopherItem_UUE = '6'; // Item is a UNIX uuencoded file.
IdGopherItem_Search = '7'; // Item is an Index-Search server.
IdGopherItem_Telnet = '8'; // Item points to a text-based telnet session.
IdGopherItem_Binary = '9'; // Item is a binary file.
// Client must read until the TCP connection closes. Beware.
IdGopherItem_Redundant = '+'; // Item is a redundant server
IdGopherItem_TN3270 = 'T'; // Item points to a text-based tn3270 session.
IdGopherItem_GIF = 'g'; // Item is a GIF format graphics file.
IdGopherItem_Image = ':'; // Item is some kind of image file.
// Client decides how to display. Was 'I', but depracted
IdGopherItem_Image2 = 'I'; //Item is some kind of image file -
// this was drepreciated
{Items discovered outside of Gopher RFC - "Gopher+"}
IdGopherItem_Sound = '<'; //Was 'S', but deprecated
IdGopherItem_Sound2 = 'S'; //This was depreciated but should be used with clients
IdGopherItem_Movie = ';'; //Was 'M', but deprecated
IdGopherItem_HTML = 'h';
IdGopherItem_MIME = 'M'; //See above for a potential conflict with Movie
IdGopherItem_Information = 'i'; // Not a file - just information
IdGopherPlusIndicator = IdGopherItem_Redundant; // Observant people will note
// the conflict here...!
IdGopherPlusInformation = '!'; // Formatted information
IdGopherPlusDirectoryInformation = '$';
//Gopher+ additional information
IdGopherPlusInfo = '+INFO: ';
{ Info format is the standard Gopher directory entry + TAB + '+'.
The info is contained on the same line as the '+INFO: '}
IdGopherPlusAdmin = '+ADMIN:' + EOL;
{ Admin block required for every item. The '+ADMIN:' occurs on a
line of it's own (starting with a space) and is followed by
the fields - one per line.
Required fields:
' Admin: ' [+ comments] + '<' + admin e-mail address + '>'
' ModDate: ' [+ comments] + '<' + dateformat:YYYYMMDDhhnnss + '>'
Optional fields regardless of location:
' Score: ' + relevance-ranking
' Score-range: ' + lower-bound + ' ' + upper-bound
Optional fields recommended at the root only:
' Site: ' + site-name
' Org: ' + organization-description
' Loc: ' + city + ', ' + state + ', ' + country
' Geog: ' + latitude + ' ' + longitude
' TZ: ' + GMT-offset
Additional recorded possibilities:
' Provider: ' + item-provider-name
' Author: ' + author
' Creation-Date: ' + '<' + YYYYMMDDhhnnss + '>'
' Expiration-Date: ' + '<' + YYYYMMDDhhnnss + '>'
}
IdGopherPlusViews = '+VIEWS:' + EOL;
{ View formats are one per line:
' ' + mime/type [+ langcode] + ': <' + size estimate + '>'
' ' + logcode = ' ' + ISO-639-Code + '_' + ISO-3166-Code
}
IdGopherPlusAbstract = '+ABSTRACT:' + EOL;
{ Is followed by a (multi-)line description. Line(s) begin with
a space.}
IdGopherPlusAsk = '+ASK:';
//Questions for +ASK section:
IdGopherPlusAskPassword = 'AskP: ';
IdGopherPlusAskLong = 'AskL: ';
IdGopherPlusAskFileName = 'AskF: ';
// Prompted responses for +ASK section:
IdGopherPlusSelect = 'Select: '; // Multi-choice, multi-selection
IdGopherPlusChoose = 'Choose: '; // Multi-choice, single-selection
IdGopherPlusChooseFile = 'ChooseF: '; //Multi-choice, single-selection
//Known response types:
IdGopherPlusData_BeginSign = '+-1' + EOL;
IdGopherPlusData_EndSign = EOL + '.' + EOL;
IdGopherPlusData_UnknownSize = '+-2' + EOL;
IdGopherPlusData_ErrorBeginSign = '--1' + EOL;
IdGopherPlusData_ErrorUnknownSize = '--2' + EOL;
IdGopherPlusError_NotAvailable = '1';
IdGopherPlusError_TryLater = '2';
IdGopherPlusError_ItemMoved = '3';
implementation
end. |
unit uAnimationThread;
interface
uses
Classes, Windows, Controls, Graphics;
type
TAnimationThread = class(TThread)
private
{ Private declarations }
FWnd: HWND;
FPaintRect: TRect;
FbkColor, FfgColor: TColor;
FInterval: integer;
protected
procedure Execute; override;
public
constructor Create(paintsurface : TWinControl; {Control to paint on }
paintrect : TRect; {area for animation bar }
bkColor, barcolor : TColor; {colors to use }
interval : integer); {wait in msecs between paints}
end;
implementation
constructor TAnimationThread.Create(paintsurface : TWinControl;
paintrect : TRect; bkColor, barcolor : TColor; interval : integer);
begin
inherited Create(True);
FWnd := paintsurface.Handle;
FPaintRect := paintrect;
FbkColor := bkColor;
FfgColor := barColor;
FInterval := interval;
FreeOnterminate := True;
Resume;
end; { TAnimationThread.Create }
procedure TAnimationThread.Execute;
var
image : TBitmap;
DC : HDC;
left, right : integer;
increment : integer;
imagerect : TRect;
state : (incRight, incLeft, decLeft, decRight);
begin
Image := TBitmap.Create;
try
with Image do
begin
Width := FPaintRect.Right - FPaintRect.Left;
Height := FPaintRect.Bottom - FPaintRect.Top;
imagerect := Rect(0, 0, Width, Height);
end; { with }
left := 0;
right := 0;
increment := imagerect.right div 50;
state := Low(State);
while not Terminated do
begin
with Image.Canvas do
begin
Brush.Color := FbkColor;
FillRect(imagerect);
case state of
incRight:
begin
Inc(right, increment);
if right > imagerect.right then
begin
right := imagerect.right;
Inc(state);
end; { if }
end; { Case incRight }
incLeft:
begin
Inc(left, increment);
if left >= right then
begin
left := right;
Inc(state);
end; { if }
end; { Case incLeft }
decLeft:
begin
Dec(left, increment);
if left <= 0 then
begin
left := 0;
Inc(state);
end; { if }
end; { Case decLeft }
decRight:
begin
Dec(right, increment);
if right <= 0 then
begin
right := 0;
state := incRight;
end; { if }
end; { Case decLeft }
end; { Case }
Brush.Color := FfgColor;
FillRect(Rect(left, imagerect.top, right, imagerect.bottom));
end; { with }
DC := GetDC(FWnd);
if DC <> 0 then
try
BitBlt(DC,
FPaintRect.Left,
FPaintRect.Top,
imagerect.right,
imagerect.bottom,
Image.Canvas.handle, 0, 0, SRCCOPY);
finally
ReleaseDC(FWnd, DC);
end;
Sleep(FInterval);
end; { While }
finally
Image.Free;
end;
InvalidateRect(FWnd, nil, True);
end; { TAnimationThread.Execute }
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLSCrossXML<p>
<b>History : </b><font size=-1><ul>
<li>23/08/10 - Yar - Creation
</ul></font>
}
unit GLSCrossXML;
interface
uses
Classes,
SysUtils,
Variants,
XMLIntf,
XMLDoc,
XMLDom;
type
GLSXMLDocument = IXMLDocument;
GLSXMLNode = IXMLNode;
GLSDOMNode = IDOMNode;
function GLSNewXMLDocument: GLSXMLDocument;
procedure ReleaseXMLDocument(var ADoc: GLSXMLDocument);
procedure WriteXMLFile(var ADoc: GLSXMLDocument; AStream: TStream); overload;
procedure ReadXMLFile(var ADoc: GLSXMLDocument; AStream: TStream); overload;
procedure WriteXMLFile(var ADoc: GLSXMLDocument; AFileName: string); overload;
procedure ReadXMLFile(var ADoc: GLSXMLDocument; AFileName: string); overload;
function GetXMLAttribute(const XMLNode: GLSXMLNode; const AttrName: string; out Value: string): Boolean; overload;
function GetXMLAttribute(const XMLNode: GLSXMLNode; Idx: Integer): GLSXMLNode; overload;
procedure SetXMLAttribute(const XMLNode: GLSXMLNode; const AttrName: string; const Value: string); overload;
procedure SetXMLAttribute(const DOMNode: GLSDOMNode; const AttrName: string; const Value: string); overload;
function GetXMLAttributeCount(const XMLNode: GLSXMLNode): Integer;
function FindXMLNode(const ParentNode: GLSXMLNode; const NodeName: string; out ChildNode: GLSXMLNode): Boolean;
function CreateDOMNode(const ParentNode: GLSDOMNode; const NodeName: string): GLSDOMNode;
procedure SetXMLText(const DOMNode: GLSDOMNode; const AText: string);
function GetXMLText(const XMLNode: GLSXMLNode; out AText: string): Boolean;
implementation
function GLSNewXMLDocument: GLSXMLDocument;
begin
Result := NewXMLDocument();
end;
procedure ReleaseXMLDocument(var ADoc: GLSXMLDocument);
begin
ADoc := nil;
end;
procedure WriteXMLFile(var ADoc: GLSXMLDocument; AStream: TStream);
begin
ADoc.SaveToStream(AStream);
end;
procedure ReadXMLFile(var ADoc: GLSXMLDocument; AStream: TStream);
begin
ADoc.LoadFromStream(AStream);
end;
procedure WriteXMLFile(var ADoc: GLSXMLDocument; AFileName: string); overload;
begin
ADoc.SaveToFile(AFileName);
end;
procedure ReadXMLFile(var ADoc: GLSXMLDocument; AFileName: string); overload;
begin
ADoc.LoadFromFile(AFileName);
end;
function GetXMLAttribute(const XMLNode: GLSXMLNode; const AttrName: string; out Value: string): Boolean;
var
attr: OleVariant;
begin
attr := 0;
attr := XMLNode.Attributes[AttrName];
Result := not VarIsNull(attr);
if Result then
Value := attr;
end;
procedure SetXMLAttribute(const XMLNode: GLSXMLNode; const AttrName: string; const Value: string);
begin
XMLNode.Attributes[AttrName] := Value;
end;
procedure SetXMLAttribute(const DOMNode: GLSDOMNode; const AttrName: string; const Value: string);
var
E: IDOMElement;
begin
E := DOMNode as IDOMElement;
E.SetAttribute(AttrName, Value);
end;
function FindXMLNode(const ParentNode: GLSXMLNode; const NodeName: string; out ChildNode: GLSXMLNode): Boolean;
begin
ChildNode := ParentNode.ChildNodes.FindNode(NodeName);
Result := Assigned(ChildNode);
end;
function CreateDOMNode(const ParentNode: GLSDOMNode; const NodeName: string): GLSDOMNode;
begin
Result := ParentNode.OwnerDocument.CreateElement(NodeName);
ParentNode.AppendChild(Result);
end;
procedure SetXMLText(const DOMNode: GLSDOMNode; const AText: string);
begin
DOMNode.AppendChild(DOMNode.ownerDocument.createTextNode(AText));
end;
function GetXMLText(const XMLNode: GLSXMLNode; out AText: string): Boolean;
begin
AText := XMLNode.Text;
Result := Length(AText)>0;
end;
function GetXMLAttributeCount(const XMLNode: GLSXMLNode): Integer;
begin
Result := XMLNode.AttributeNodes.Count;
end;
function GetXMLAttribute(const XMLNode: GLSXMLNode; Idx: Integer): GLSXMLNode;
begin
Result := XMLNode.AttributeNodes[Idx];
end;
end.
|
unit FieldInfoUnit;
interface
uses
System.Generics.Collections;
type
TFieldInfo = class(TObject)
private
FErrorMessage: string;
FFieldName: string;
FIsCellUnion: Boolean;
FRequired: Boolean;
FSize: Integer;
protected
public
constructor Create(AFieldName: string; ARequired: Boolean = False;
AErrorMessage: String = ''; AIsCellUnion: Boolean = False; ASize: Integer =
1000);
property ErrorMessage: string read FErrorMessage write FErrorMessage;
property FieldName: string read FFieldName write FFieldName;
property IsCellUnion: Boolean read FIsCellUnion write FIsCellUnion;
property Required: Boolean read FRequired write FRequired;
property Size: Integer read FSize write FSize;
end;
TFieldsInfo = class(TList<TFieldInfo>)
public
function Find(const AFieldName: string): TFieldInfo;
end;
TFieldInfoEx = class(TFieldInfo)
private
FDisplayLabel: string;
FExist: Boolean;
public
constructor Create(AFieldName: string; ARequired: Boolean = False;
AErrorMessage: String = ''; ADisplayLabel: String = ''; AIsCellUnion:
Boolean = False; ASize: Integer = 1000);
property DisplayLabel: string read FDisplayLabel;
property Exist: Boolean read FExist write FExist;
end;
TFieldsInfoEx = class(TList<TFieldInfoEx>)
public
function Find(const ADisplayLabel: string; AChild: Boolean): TFieldInfoEx;
end;
implementation
uses System.SysUtils;
constructor TFieldInfo.Create(AFieldName: string; ARequired: Boolean = False;
AErrorMessage: String = ''; AIsCellUnion: Boolean = False; ASize: Integer =
1000);
begin
Assert(not AFieldName.IsEmpty);
FFieldName := AFieldName;
FRequired := ARequired;
FErrorMessage := AErrorMessage;
FIsCellUnion := AIsCellUnion;
FSize := ASize;
if FRequired then
Assert(not FErrorMessage.IsEmpty);
end;
function TFieldsInfo.Find(const AFieldName: string): TFieldInfo;
begin
Assert(not AFieldName.IsEmpty);
for Result in Self do
begin
if Result.FieldName = AFieldName then
Exit;
end;
Result := nil;
end;
constructor TFieldInfoEx.Create(AFieldName: string; ARequired: Boolean = False;
AErrorMessage: String = ''; ADisplayLabel: String = ''; AIsCellUnion:
Boolean = False; ASize: Integer = 1000);
begin
Assert(not AFieldName.IsEmpty);
FFieldName := AFieldName;
FDisplayLabel := ADisplayLabel;
FRequired := ARequired;
FErrorMessage := AErrorMessage;
FIsCellUnion := AIsCellUnion;
FSize := ASize;
if FRequired then
Assert(not FErrorMessage.IsEmpty);
end;
function TFieldsInfoEx.Find(const ADisplayLabel: string; AChild: Boolean):
TFieldInfoEx;
var
S: string;
begin
Assert(not ADisplayLabel.IsEmpty);
for Result in Self do
begin
S := Result.DisplayLabel.ToUpper.Trim;
{
if AChild then
begin
i := S.IndexOf('|');
if i < 0 then
Continue;
S := S.Substring(i + 1);
end;
}
if S.StartsWith(ADisplayLabel.ToUpper.Trim) then
Exit;
end;
Result := nil;
end;
end.
|
{
"SyncObjcs" - Copyright (c) Danijel Tkalcec
@exclude
}
unit rtcSyncObjs;
interface
{$INCLUDE rtcDefs.inc}
uses
{$IFDEF CLR}
System.Threading;
{$ELSE}
SyncObjs,
Windows;
{$ENDIF}
type
TRtcWaitResult = (wr_Signaled, wr_Timeout, wr_Abandoned, wr_Error);
TRtcCritSec=class
private
{$IFDEF CLR}
CS:System.Threading.Mutex;
{$ELSE}
CS:TRTLCriticalSection;
{$ENDIF}
public
constructor Create; virtual;
destructor Destroy; override;
procedure Enter;
procedure Leave;
end;
TRtcRWSec=class
private
WriteSec:TEvent;
{$IFDEF CLR}
PassSec,ReadSec:System.Threading.Mutex;
{$ELSE}
PassSec,ReadSec:TRTLCriticalSection;
{$ENDIF}
Cnt,Cnt3:longint;
public
constructor Create;
destructor Destroy; override;
procedure EnterRead; // Normal reader, no hurry.
procedure LeaveRead;
procedure ForceWrite; // Need to write as fast as possible, force readers to stop reading.
procedure EnterWrite; // Normal writer, no hurry.
procedure LeaveWrite;
procedure ForceRead; // Need to read as fast as possible, ignore waiting writers.
procedure DoneRead; // Done reading.
end;
TRtcEvent=class
private
CS:TEvent;
public
constructor Create(ManualReset,InitialState:boolean);
destructor Destroy; override;
function WaitFor(Timeout: LongWord): TRtcWaitResult;
procedure SetEvent;
procedure ResetEvent;
end;
implementation
{ TRtcCritSec }
constructor TRtcCritSec.Create;
begin
inherited;
{$IFDEF CLR}
CS:=System.Threading.Mutex.Create;
{$ELSE}
InitializeCriticalSection(CS);
{$ENDIF}
end;
destructor TRtcCritSec.Destroy;
begin
{$IFDEF CLR}
CS.Free;
{$ELSE}
DeleteCriticalSection(CS);
{$ENDIF}
inherited;
end;
procedure TRtcCritSec.Enter;
begin
{$IFDEF CLR}
CS.WaitOne;
{$ELSE}
EnterCriticalSection(CS);
{$ENDIF}
end;
procedure TRtcCritSec.Leave;
begin
{$IFDEF CLR}
CS.ReleaseMutex;
{$ELSE}
LeaveCriticalSection(CS);
{$ENDIF}
end;
{ TRtcEvent }
constructor TRtcEvent.Create(ManualReset, InitialState: boolean);
begin
inherited Create;
CS:=TEvent.Create(nil,ManualReset,InitialState,'');
end;
destructor TRtcEvent.Destroy;
begin
CS.Free;
inherited;
end;
procedure TRtcEvent.ResetEvent;
begin
CS.ResetEvent;
end;
procedure TRtcEvent.SetEvent;
begin
CS.SetEvent;
end;
function TRtcEvent.WaitFor(Timeout: LongWord): TRtcWaitResult;
begin
case CS.WaitFor(Timeout) of
wrSignaled: Result:=wr_Signaled;
wrTimeout: Result:=wr_Timeout;
wrAbandoned:Result:=wr_Abandoned;
else Result:=wr_Error;
end;
end;
{ TRtcRWSec }
constructor TRtcRWSec.Create;
begin
inherited;
Cnt:=0;Cnt3:=0;
{$IFDEF CLR}
PassSec:=System.Threading.Mutex.Create;
ReadSec:=System.Threading.Mutex.Create;
{$ELSE}
InitializeCriticalSection(PassSec);
InitializeCriticalSection(ReadSec);
{$ENDIF}
WriteSec:=TEvent.Create(nil,False,True,''); // Auto-reset
end;
destructor TRtcRWSec.Destroy;
begin
{$IFDEF CLR}
PassSec.Free;
ReadSec.Free;
{$ELSE}
DeleteCriticalSection(PassSec);
DeleteCriticalSection(ReadSec);
{$ENDIF}
WriteSec.Free;
inherited;
end;
procedure TRtcRWSec.EnterRead;
begin
{$IFDEF CLR}
PassSec.WaitOne;
PassSec.ReleaseMutex;
{$ELSE}
EnterCriticalSection(PassSec);
LeaveCriticalSection(PassSec);
{$ENDIF}
{$IFDEF CLR}
ReadSec.WaitOne;
{$ELSE}
EnterCriticalSection(ReadSec);
{$ENDIF}
try
if (Cnt=0) and (Cnt3=0) then // There are no readers inside
WriteSec.WaitFor(INFINITE); // Block all writers, this is the first reader.
Inc(Cnt);
finally
{$IFDEF CLR}
ReadSec.ReleaseMutex;
{$ELSE}
LeaveCriticalSection(ReadSec);
{$ENDIF}
end;
end;
procedure TRtcRWSec.ForceRead;
var
OK:boolean;
begin
OK:=False;
{$IFDEF CLR}
ReadSec.WaitOne;
{$ELSE}
EnterCriticalSection(ReadSec);
{$ENDIF}
try
if Cnt>0 then // There are normal readers inside, writers are blocked.
begin
Inc(Cnt3);
OK:=True;
end;
finally
{$IFDEF CLR}
ReadSec.ReleaseMutex;
{$ELSE}
LeaveCriticalSection(ReadSec);
{$ENDIF}
end;
if not OK then
begin
{$IFDEF CLR}
PassSec.WaitOne;
PassSec.ReleaseMutex;
{$ELSE}
EnterCriticalSection(PassSec);
LeaveCriticalSection(PassSec);
{$ENDIF}
{$IFDEF CLR}
ReadSec.WaitOne;
{$ELSE}
EnterCriticalSection(ReadSec);
{$ENDIF}
try
if (Cnt=0) and (Cnt3=0) then // There are no readers inside
WriteSec.WaitFor(INFINITE); // Block all writers
Inc(Cnt3);
finally
{$IFDEF CLR}
ReadSec.ReleaseMutex;
{$ELSE}
LeaveCriticalSection(ReadSec);
{$ENDIF}
end;
end;
end;
procedure TRtcRWSec.LeaveRead;
begin
{$IFDEF CLR}
ReadSec.WaitOne;
{$ELSE}
EnterCriticalSection(ReadSec);
{$ENDIF}
try
Dec(Cnt);
if (Cnt=0) and (Cnt3=0) then
WriteSec.SetEvent; // Un-block writers
finally
{$IFDEF CLR}
ReadSec.ReleaseMutex;
{$ELSE}
LeaveCriticalSection(ReadSec);
{$ENDIF}
end;
end;
procedure TRtcRWSec.DoneRead;
begin
{$IFDEF CLR}
ReadSec.WaitOne;
{$ELSE}
EnterCriticalSection(ReadSec);
{$ENDIF}
try
Dec(Cnt3);
if (Cnt=0) and (Cnt3=0) then
WriteSec.SetEvent; // Un-block writers
finally
{$IFDEF CLR}
ReadSec.ReleaseMutex;
{$ELSE}
LeaveCriticalSection(ReadSec);
{$ENDIF}
end;
end;
procedure TRtcRWSec.EnterWrite;
begin
{$IFDEF CLR}
PassSec.WaitOne;
{$ELSE}
EnterCriticalSection(PassSec);
{$ENDIF}
WriteSec.WaitFor(INFINITE);
end;
procedure TRtcRWSec.ForceWrite;
begin
{$IFDEF CLR}
PassSec.WaitOne;
{$ELSE}
EnterCriticalSection(PassSec);
{$ENDIF}
WriteSec.WaitFor(INFINITE);
end;
procedure TRtcRWSec.LeaveWrite;
begin
WriteSec.SetEvent;
{$IFDEF CLR}
PassSec.ReleaseMutex;
{$ELSE}
LeaveCriticalSection(PassSec);
{$ENDIF}
end;
end.
|
unit TestRunOnConst;
{ AFS 4 April 2k
This unit compiles but is not semantically meaningfull
it is test cases for the code formatting utility
line breaking of record consts
test by obfuscating & de-obfuscating
}
interface
type
TFnorfType = (eFnord1, eFnord2, eTheOtherFnord);
TFnordRecord = record
sWord: string;
eFnordType: TFnorfType;
bTheOther: Boolean;
end;
{ the problem is really the semicolons - why couldn't they have used commas?
Semicolons here must be treated differently to *everywhere* else
i.e. everywhere else there is always a new line after the semicolon
}
const
FnordMap: array [0..11] of TFnordRecord =
(
(sWord: 'bob'; eFnordType: eFnord1; bTheOther: True),
(sWord: 'was'; eFnordType: eTheOtherFnord; bTheOther: False),
(sWord: 'here'; eFnordType: eFnord2; bTheOther: True),
(sWord: 'some'; eFnordType: eFnord1; bTheOther: False),
(sWord: 'time'; eFnordType: eTheOtherFnord; bTheOther: True),
(sWord: 'after'; eFnordType: eFnord1; bTheOther: False),
(sWord: 'midnight'; eFnordType: eFnord2; bTheOther: True),
(sWord: 'bob'; eFnordType: eFnord1; bTheOther: True),
(sWord: 'was'; eFnordType: eTheOtherFnord; bTheOther: False),
(sWord: 'here'; eFnordType: eFnord2; bTheOther: True),
(sWord: 'some'; eFnordType: eFnord1; bTheOther: False),
(sWord: 'time'; eFnordType: eTheOtherFnord; bTheOther: True)
);
const
MyFnord: TFnordRecord = (sWord: 'bob'; eFnordType: eFnord1; bTheOther: True);
implementation
const
SomeStrings: array [1..14] of string =
('Fnord',
'Fnord',
'Fnord',
'Fnord',
'Fnord',
'Fnord Fnord Fnord Fnord Fnord Fnord Fnord Fnord Fnord Fnord',
'Fnord',
'Fnord',
'This is a somewhat longer string which, although it digesses a bit just to gain length, does not contain very many fnords',
'Fnord',
'Fnord',
'Fnord Fnord Fnord',
'Fnord',
'Fnord');
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{ : GLS.FileDXF<p>
Support-Code to load DXF (Drawing eXchange Files) TGLFreeForm or
TGLActor Components in GLScene.<p>
Note that you must manually add this unit to one of your project's uses
to enable support for DXF at run-time.<p>
Turn on TwoSideLighting in your Buffer! DXF-Faces have no defined winding order
<b>History : </b><font size=-1><ul>
<li>05/12/14 - PW - Added to GLScene_Runtime.dpk
<li>08/01/06 - JCD - Now works with MaterialLibrary=NIL. (will not load any material, still assigns materialnames to meshobj)
<li>04/01/06 - JCD - Layer conversion code, material creation, code cleanup</li>
<li>24/04/04 - JCD - some basic stream code copied from GLScene Wavefront OBJ-Importer (09/09/03)</li>
</ul><p>
(c) 2004-2006 Jörn Daub http://www.daubnet.com<p>
surrendered to Mozilla Public License for use in GLScene.
Original author (Jörn Daub) retains the right to make changes without
surrendering the modified code.
}
unit GLFileDXF;
interface
uses
System.Classes, System.SysUtils,
// GLS
GLApplicationFileIO, GLVectorGeometry, GLVectorLists, GLScene, GLTexture,
GLVectorFileObjects, GLMaterial;
type
TGLDXFVectorFile = class(TVectorFile)
private
FSourceStream: TStream; { Load from this stream }
FBuffer: String; { Buffer and current line }
FLineNo: Integer; { current Line number - for error messages }
FEof: Boolean; { Stream done? }
FBufPos: Integer; { Position in the buffer }
HasPushedCode: Boolean;
PushedCode: Integer;
FLayers: TStringList;
FBlocks: TStringList;
FLastpercentdone: BYTE;
protected
procedure PushCode(code: Integer);
function GetCode: Integer;
procedure SkipTable;
procedure SkipSection;
// procedure DoProgress (Stage: TGLProgressStage; PercentDone: single; RedrawNow: Boolean; const Msg: string);
function NeedMesh(basemesh: TGLBaseMesh; layer: STRING): TMeshObject;
function NeedFaceGroup(m: TMeshObject; fgmode: TFaceGroupMeshMode;
fgmat: STRING): TFGVertexIndexList;
procedure NeedMeshAndFaceGroup(basemesh: TGLBaseMesh; layer: STRING;
fgmode: TFaceGroupMeshMode; fgmat: STRING; var m: TMeshObject;
var fg: TFGVertexIndexList);
function ReadLine: STRING;
// Read a single line of text from the source stream, set FEof to true when done.
function ReadInt: Integer;
function ReadDouble: double;
procedure ReadTables;
procedure ReadLayer;
procedure ReadLayerTable;
procedure ReadBlocks;
procedure ReadInsert(basemesh: TGLBaseMesh);
procedure ReadEntity3Dface(basemesh: TGLBaseMesh);
procedure ReadEntityPolyLine(basemesh: TGLBaseMesh);
procedure ReadEntities(basemesh: TGLBaseMesh);
public
class function Capabilities: TDataFileCapabilities; override;
procedure LoadFromStream(aStream: TStream); override;
end;
implementation
procedure BuildNormals(m: TMeshObject); FORWARD;
const
DXFcolorsRGB: ARRAY [1 .. 255] OF LONGINT = ($FF0000, $FFFF00, $00FF00,
$00FFFF, $0000FF, $FF00FF, $000000, $000000, $000000, $FF0000, $FF8080,
$A60000, $A65353, $800000, $804040, $4D0000, $4D2626, $260000, $261313,
$FF4000, $FF9F80, $A62900, $A66853, $802000, $805040, $4D1300, $4D3026,
$260A00, $261813, $FF8000, $FFBF80, $A65300, $A67C53, $804000, $806040,
$4D2600, $4D3926, $261300, $261D13, $FFBF00, $FFDF80, $A67C00, $A69153,
$806000, $807040, $4D3900, $4D4326, $261D00, $262113, $FFFF00, $FFFF80,
$A6A600, $A6A653, $808000, $808040, $4D4D00, $4D4D26, $262600, $262613,
$BFFF00, $DFFF80, $7CA600, $91A653, $608000, $708040, $394D00, $434D26,
$1D2600, $212613, $80FF00, $BFFF80, $53A600, $7CA653, $408000, $608040,
$264D00, $394D26, $132600, $1D2613, $40FF00, $9FFF80, $29A600, $68A653,
$208000, $508040, $134D00, $304D26, $0A2600, $182613, $00FF00, $80FF80,
$00A600, $53A653, $008000, $408040, $004D00, $264D26, $002600, $132613,
$00FF40, $80FF9F, $00A629, $53A668, $008020, $408050, $004D13, $264D30,
$00260A, $132618, $00FF80, $80FFBF, $00A653, $53A67C, $008040, $408060,
$004D26, $264D39, $002613, $13261D, $00FFBF, $80FFDF, $00A67C, $53A691,
$008060, $408070, $004D39, $264D43, $00261D, $132621, $00FFFF, $80FFFF,
$00A6A6, $53A6A6, $008080, $408080, $004D4D, $264D4D, $002626, $132626,
$00BFFF, $80DFFF, $007CA6, $5391A6, $006080, $407080, $00394D, $26434D,
$001D26, $132126, $0080FF, $80BFFF, $0053A6, $537CA6, $004080, $406080,
$00264D, $26394D, $001326, $131D26, $0040FF, $809FFF, $0029A6, $5368A6,
$002080, $405080, $00134D, $26304D, $000A26, $131826, $0000FF, $8080FF,
$0000A6, $5353A6, $000080, $404080, $00004D, $26264D, $000026, $131326,
$4000FF, $9F80FF, $2900A6, $6853A6, $200080, $504080, $13004D, $30264D,
$0A0026, $181326, $8000FF, $BF80FF, $5300A6, $7C53A6, $400080, $604080,
$26004D, $39264D, $130026, $1D1326, $BF00FF, $DF80FF, $7C00A6, $9153A6,
$600080, $704080, $39004D, $43264D, $1D0026, $211326, $FF00FF, $FF80FF,
$A600A6, $A653A6, $800080, $804080, $4D004D, $4D264D, $260026, $261326,
$FF00BF, $FF80DF, $A6007C, $A65391, $800060, $804070, $4D0039, $4D2643,
$26001D, $261321, $FF0080, $FF80BF, $A60053, $A6537C, $800040, $804060,
$4D0026, $4D2639, $260013, $26131D, $FF0040, $FF809F, $A60029, $A65368,
$800020, $804050, $4D0013, $4D2630, $26000A, $261318, $545454, $767676,
$989898, $BBBBBB, $DDDDDD, $FFFFFF);
const
BufSize = 65536; { Load input data in chunks of BufSize Bytes. }
LineLen = 100; { Allocate memory for the current line in chunks }
function RGB2BGR(bgr: LONGINT): LONGINT;
begin
result := ((bgr SHR 16) and $FF) or (bgr AND $FF00) or
((bgr SHL 16) and $FF0000)
end;
function StreamEOF(S: TStream): Boolean;
begin { Is the stream at its end? }
result := (S.Position >= S.Size);
end;
class function TGLDXFVectorFile.Capabilities: TDataFileCapabilities;
begin
result := [dfcRead];
end;
function TGLDXFVectorFile.ReadLine: STRING;
var
j: Integer;
FLine: STRING;
NewlineChar: CHAR;
procedure FillBuffer;
var
l: Integer;
begin
l := FSourceStream.Size - FSourceStream.Position;
if l > BufSize then
l := BufSize;
SetLength(FBuffer, l);
FSourceStream.Read(FBuffer[1], l);
FBufPos := 1;
end;
begin
Inc(FLineNo);
if FBufPos < 1 then
FillBuffer;
j := 1;
while True do
begin
if FBufPos > Length(FBuffer) then
begin
if StreamEOF(FSourceStream) then
begin
FEof := True;
break;
end
else
FillBuffer
end
else
begin
case FBuffer[FBufPos] of
#10, #13:
begin
NewlineChar := FBuffer[FBufPos];
Inc(FBufPos);
if FBufPos > Length(FBuffer) then
if StreamEOF(FSourceStream) then
break
else
FillBuffer;
if ((FBuffer[FBufPos] = #10) or (FBuffer[FBufPos] = #13)) and
(FBuffer[FBufPos] <> NewlineChar) then
Inc(FBufPos);
break;
end;
else
if j > Length(FLine) then
SetLength(FLine, Length(FLine) + LineLen);
if FBuffer[FBufPos] = #9 then
FLine[j] := #32
else
FLine[j] := FBuffer[FBufPos];
Inc(FBufPos);
Inc(j);
end;
end;
end;
SetLength(FLine, j - 1);
ReadLine := Trim(FLine);
end;
{
procedure TGLDXFVectorFile.DoProgress (Stage: TGLProgressStage; PercentDone: single; RedrawNow: Boolean; const Msg: string);
var perc:BYTE;
begin
// If the following line stops your compiler, just comment this function
if @owner.OnProgress<>NIL then
begin
perc:=round(percentdone);
if (perc<>Flastpercentdone) or (msg<>'') or redrawnow then
owner.OnProgress (owner,stage,perc,redrawnow,msg);
Flastpercentdone:=perc;
end;
end;
}
procedure TGLDXFVectorFile.PushCode(code: Integer);
begin
PushedCode := code;
HasPushedCode := True;
end;
function TGLDXFVectorFile.GetCode: Integer;
var
S: STRING;
begin
if HasPushedCode then
begin
GetCode := PushedCode;
HasPushedCode := FALSE;
end
else
begin
S := ReadLine;
result := StrToIntDef(S, -1);
if result = -1 then
raise Exception.create('Invalid DXF Code ' + S + ' on Line #' +
IntToStr(FLineNo));
end;
end;
function TGLDXFVectorFile.ReadDouble: double;
var
S: String;
c: CHAR;
begin
c := FormatSettings.DecimalSeparator;
FormatSettings.DecimalSeparator := '.';
S := Trim(ReadLine);
result := StrToFloat(S);
FormatSettings.DecimalSeparator := c;
end;
function TGLDXFVectorFile.ReadInt: Integer;
var
S: String;
begin
S := Trim(ReadLine);
result := StrToInt(S);
end;
procedure TGLDXFVectorFile.SkipSection;
var
S: String;
code: Integer;
begin
repeat
code := GetCode;
S := ReadLine;
until (code = 0) and (S = 'ENDSEC');
end;
procedure TGLDXFVectorFile.SkipTable;
var
S: String;
code: Integer;
begin
repeat
code := GetCode;
S := ReadLine;
until (code = 0) and (S = 'ENDTAB');
end;
procedure TGLDXFVectorFile.ReadLayer;
var
layername, color: String;
code: Integer;
begin
color := '1';
repeat
code := GetCode;
case code of
0:
;
2:
layername := ReadLine;
70:
ReadLine; // freeze and lock flags
62:
color := ReadLine;
else
ReadLine;
end;
until code = 0;
PushCode(0);
FLayers.AddObject(layername, POINTER(StrToIntDef(color, 1)));
end;
procedure TGLDXFVectorFile.ReadLayerTable;
var
S: STRING;
code: Integer;
begin
repeat
code := GetCode;
S := ReadLine;
if (code = 0) and (S = 'LAYER') then
ReadLayer;
until (code = 0) and (S = 'ENDTAB');
end;
procedure TGLDXFVectorFile.ReadTables;
var
S: String;
code: Integer;
begin
repeat
code := GetCode;
S := ReadLine;
if (code = 0) and (S = 'TABLE') then
begin
code := GetCode;
S := ReadLine;
if (code = 2) then
if S = 'LAYER' then
ReadLayerTable
else
SkipTable; // LTYPE, STYLE, UCS, and more currently skipped
end
until (code = 0) and (S = 'ENDSEC');
end;
procedure TGLDXFVectorFile.ReadBlocks;
var
S: String;
code: Integer;
blockname: String;
blockmesh: TGLFreeForm;
begin
// This code reads blocks into orphaned TGLFreeForms.
// ReadInsert then either copies or parents this object to its parent
// unused blocks are freed upon completion
repeat
code := GetCode;
S := ReadLine;
if (code = 0) and (S = 'BLOCK') then
begin
blockmesh := TGLFreeForm.create(owner);
blockmesh.IgnoreMissingTextures := True;
blockmesh.MaterialLibrary := owner.MaterialLibrary;
blockmesh.OnProgress := NIL;
blockname := 'DXFBLOCK' + IntToStr(FBlocks.count);
repeat
code := GetCode;
case code of
0:
;
2:
blockname := ReadLine;
else
S := ReadLine;
end;
until code = 0;
PushCode(0);
FBlocks.AddObject(blockname, blockmesh);
ReadEntities(blockmesh);
// basemesh.Direction.SetVector(0,1,0);
// code:=GetCode;
// s:=ReadLine;
// asm nop end;
end;
until (code = 0) and (S = 'ENDSEC');
end;
procedure TGLDXFVectorFile.ReadInsert(basemesh: TGLBaseMesh);
var
code, idx, indexoffset: Integer;
i, j, k: Integer;
blockname, S: STRING;
pt, insertpoint, scale: TAffineVector;
blockmesh: TGLBaseMesh;
// blockproxy :TGLProxyObject;
mo_block: TMeshObject;
mo_base: TMeshObject;
fg_block, fg_base: TFGVertexIndexList;
begin
blockname := '';
insertpoint := NullVector;
scale := XYZvector;
repeat // see ReadBlocks for details
code := GetCode;
case code of
0:
;
2:
blockname := ReadLine;
10:
insertpoint.X := ReadDouble;
20:
insertpoint.Y := ReadDouble;
30:
insertpoint.Z := ReadDouble;
41:
scale.X := ReadDouble;
42:
scale.Y := ReadDouble;
43:
scale.Z := ReadDouble;
else
S := ReadLine;
end;
until code = 0;
idx := FBlocks.IndexOf(blockname);
if idx >= 0 then
begin
blockmesh := FBlocks.Objects[idx] as TGLBaseMesh;
// FLAT STRUCTURES
// Insert a block into its parent by copying the contents.
// the blockmesh will be freed upon completion, leaving only the copies.
for i := 0 to blockmesh.MeshObjects.count - 1 do
begin
mo_block := blockmesh.MeshObjects[i];
mo_base := NeedMesh(basemesh, mo_block.name);
indexoffset := mo_base.vertices.count;
for j := 0 to mo_block.vertices.count - 1 do
begin
pt := mo_block.vertices[j];
ScaleVector(pt, scale);
AddVector(pt, insertpoint);
mo_base.vertices.Add(pt);
end;
for j := 0 to mo_block.FaceGroups.count - 1 do
begin
fg_block := mo_block.FaceGroups[j] as TFGVertexIndexList;
fg_base := NeedFaceGroup(mo_base, fg_block.mode,
fg_block.MaterialName);
for k := 0 to fg_block.VertexIndices.count - 1 do
begin
fg_base.VertexIndices.Add(fg_block.VertexIndices[k] +
indexoffset);
end;
end;
end;
// TREE STRUCTURES
// Instead of copying the contents of the block, they are parented to the
// base mesh. If the block already has a parent, a proxy object is created.
// WARNING: THE CODE BELOW DOES NOT WORK.
(*
if blockmesh.Parent =NIL then
begin
blockmesh.Position.AsAffineVector:=insertpoint;
blockmesh.ShowAxes:=TRUE;
basemesh.AddChild(blockmesh);
for i:=0 to blockmesh.MeshObjects.Count-1 do
BuildNormals(blockmesh.MeshObjects[i]);
end
else
begin
blockproxy:=TGLproxyObject.CreateAsChild(basemesh);
blockproxy.MasterObject:=blockmesh;
blockproxy.Position.AsAffineVector:=insertpoint;
blockproxy.ShowAxes:=TRUE;
end;
*)
end;
PushCode(0);
end;
function TGLDXFVectorFile.NeedMesh(basemesh: TGLBaseMesh; layer: STRING)
: TMeshObject;
var
i: Integer;
begin
i := 0;
while (i < basemesh.MeshObjects.count) and
not(basemesh.MeshObjects[i].name = layer) do
Inc(i);
if i < basemesh.MeshObjects.count then
result := basemesh.MeshObjects[i]
else
begin
result := TMeshObject.CreateOwned(basemesh.MeshObjects);
result.mode := momFaceGroups;
result.name := layer;
end;
end;
function TGLDXFVectorFile.NeedFaceGroup(m: TMeshObject;
fgmode: TFaceGroupMeshMode; fgmat: STRING): TFGVertexIndexList;
var
i: Integer;
acadcolor: LONGINT;
libmat: TGLLibMaterial;
fg: TFGVertexIndexList;
begin
i := 0;
while (i < m.FaceGroups.count) and
not((m.FaceGroups[i] is TFGVertexIndexList) and
((m.FaceGroups[i] as TFGVertexIndexList).mode = fgmode) and
(m.FaceGroups[i].MaterialName = fgmat)) do
Inc(i);
if i < m.FaceGroups.count then
fg := m.FaceGroups[i] as TFGVertexIndexList
else
begin
fg := TFGVertexIndexList.CreateOwned(m.FaceGroups);
fg.mode := fgmode;
fg.MaterialName := fgmat;
if owner.MaterialLibrary <> NIL then
begin
libmat := owner.MaterialLibrary.Materials.GetLibMaterialByName(fgmat);
if libmat = NIL then // create a colored material
begin
acadcolor := StrToIntDef(fgmat, 0);
if acadcolor in [1 .. 255] then
begin
libmat := owner.MaterialLibrary.Materials.Add;
libmat.name := fgmat;
libmat.Material.FrontProperties.Diffuse.AsWinColor :=
RGB2BGR(DXFcolorsRGB[acadcolor]);
libmat.Material.BackProperties.Diffuse.AsWinColor :=
RGB2BGR(DXFcolorsRGB[acadcolor]);
libmat.Material.FaceCulling := fcNoCull;
end;
end;
end;
end;
result := fg;
end;
procedure TGLDXFVectorFile.NeedMeshAndFaceGroup(basemesh: TGLBaseMesh;
layer: STRING; fgmode: TFaceGroupMeshMode; fgmat: STRING;
var m: TMeshObject; var fg: TFGVertexIndexList);
begin
m := NeedMesh(basemesh, layer);
fg := NeedFaceGroup(m, fgmode, fgmat);
end;
procedure TGLDXFVectorFile.ReadEntity3Dface(basemesh: TGLBaseMesh);
var
code, i: Integer;
pts: ARRAY [0 .. 3] of TAffineVector;
isquad: Boolean;
fg: TFGVertexIndexList;
color, layer: STRING;
m: TMeshObject;
begin
color := '';
layer := '';
isquad := FALSE;
for i := 0 to 3 do
pts[i] := NullVector;
repeat
code := GetCode;
case code of
0:
;
8:
layer := ReadLine; // Layer
10:
pts[0].X := ReadDouble;
11:
pts[1].X := ReadDouble;
12:
pts[2].X := ReadDouble;
13:
begin
pts[3].X := ReadDouble;
isquad := True
end;
20:
pts[0].Y := ReadDouble;
21:
pts[1].Y := ReadDouble;
22:
pts[2].Y := ReadDouble;
23:
begin
pts[3].Y := ReadDouble;
isquad := True
end;
30:
pts[0].Z := ReadDouble;
31:
pts[1].Z := ReadDouble;
32:
pts[2].Z := ReadDouble;
33:
begin
pts[3].Z := ReadDouble;
isquad := True
end;
62:
color := ReadLine; // Color
else
ReadLine;
end;
until code = 0;
PushCode(0);
isquad := isquad and ((pts[2].X <> pts[3].X) or (pts[2].Y <> pts[3].Y) or
(pts[2].Z <> pts[3].Z));
if isquad then
NeedMeshAndFaceGroup(basemesh, layer, fgmmQuads, color, m, fg)
else
NeedMeshAndFaceGroup(basemesh, layer, fgmmTriangles, color, m, fg);
fg.Add(m.vertices.FindOrAdd(pts[0]));
fg.Add(m.vertices.FindOrAdd(pts[1]));
fg.Add(m.vertices.FindOrAdd(pts[2]));
if isquad then
fg.Add(m.vertices.FindOrAdd(pts[3]));
end;
procedure TGLDXFVectorFile.ReadEntityPolyLine(basemesh: TGLBaseMesh);
procedure ReadPolylineVertex(m: TMeshObject; vertexindexbase: Integer);
var
color: STRING;
pt: TAffineVector;
fg: TFGVertexIndexList;
code, idx, i70, i71, i72, i73, i74: Integer;
begin
color := '';
pt := NullVector;
i70 := 0;
i71 := 0;
i72 := 0;
i73 := 0;
i74 := 0;
repeat
code := GetCode;
case code of
0:
;
5:
ReadLine; // ID :=ReadHex16;
8:
ReadLine; // ignore per vertex layer. Polyline vertices cannot cross layers!
10:
pt.X := ReadDouble;
20:
pt.Y := ReadDouble;
30:
pt.Z := ReadDouble;
62:
color := ReadLine;
70:
i70 := ReadInt;
71:
i71 := abs(ReadInt);
// negative values should hide points... we cannot
72:
i72 := abs(ReadInt);
73:
i73 := abs(ReadInt);
74:
i74 := abs(ReadInt);
100:
ReadLine; // Subclass Marker
330:
ReadLine; // Soft Pointer?
else
ReadLine;
end;
until code = 0;
PushCode(0);
if (color = '') or (color = '256') or (color = 'BYLAYER') then
begin
idx := FLayers.IndexOf(m.name);
if idx >= 0 then
color := IntToStr(LONGINT(FLayers.Objects[idx]));
end;
if i70 and 192 = 192 then
begin
m.vertices.Add(pt);
end
else if i70 and 192 = 128 then
begin
i71 := i71 - 1 + vertexindexbase;
i72 := i72 - 1 + vertexindexbase;
i73 := i73 - 1 + vertexindexbase;
if i74 = 0 then
begin
fg := NeedFaceGroup(m, fgmmTriangles, color);
fg.Add(i71);
fg.Add(i72);
fg.Add(i73);
end
else
begin
i74 := i74 - 1 + vertexindexbase;
fg := NeedFaceGroup(m, fgmmQuads, color);
fg.Add(i71);
fg.Add(i72);
fg.Add(i73);
fg.Add(i74);
end
end
else
// hmm?
end;
var
m: TMeshObject;
code, vertexindexbase: Integer;
S, layer: STRING;
begin
m := NIL;
vertexindexbase := 0;
repeat
code := GetCode;
S := ReadLine;
if (code = 8) then
begin
layer := S;
m := NeedMesh(basemesh, layer);
vertexindexbase := m.vertices.count;
end;
if (code = 0) and (S = 'VERTEX') and (m <> NIL) then
ReadPolylineVertex(m, vertexindexbase);
until (code = 0) and (S = 'SEQEND');
repeat
code := GetCode;
if code <> 0 then
ReadLine;
until (code = 0);
PushCode(0);
end;
procedure TGLDXFVectorFile.ReadEntities(basemesh: TGLBaseMesh);
var
code: Integer;
S: STRING;
begin
repeat
code := GetCode;
// DoProgress (psRunning,FSourceStream.Position/FSourceStream.Size*100,false,'');
case code of
0:
begin
S := ReadLine;
if S = 'POLYLINE' then
ReadEntityPolyLine(basemesh)
else if S = '3DFACE' then
ReadEntity3Dface(basemesh)
else if S = 'INSERT' then
ReadInsert(basemesh)
else if S = 'ENDSEC' then
begin
end
else if S = 'ENDBLK' then
begin
end
else
(*
asm
nop
end // put breakpoint here to catch other entities
*)
end;
else
S := ReadLine;
end;
until (code = 0) and ((S = 'ENDSEC') or (S = 'ENDBLK'));
end;
// build normals
procedure BuildNormals(m: TMeshObject);
var
i, j: Integer;
v1, v2, v3, v4, n: TAffineVector;
begin
for i := 0 to m.vertices.count - 1 do
m.Normals.Add(0, 0, 0);
for i := 0 to m.FaceGroups.count - 1 do
if m.FaceGroups[i] is TFGVertexIndexList then
with m.FaceGroups[i] as TFGVertexIndexList do
case mode of
fgmmTriangles:
begin
for j := 0 to (VertexIndices.count div 3) - 1 do
begin
v1 := m.vertices[VertexIndices[j * 3]];
v2 := m.vertices[VertexIndices[j * 3 + 1]];
v3 := m.vertices[VertexIndices[j * 3 + 2]];
n := CalcPlaneNormal(v1, v2, v3);
m.Normals.items[VertexIndices[j * 3]] :=
VectorAdd(m.Normals.items[VertexIndices[j * 3]], n);
m.Normals.items[VertexIndices[j * 3 + 1]] :=
VectorAdd(m.Normals.items[VertexIndices[j * 3 + 1]], n);
m.Normals.items[VertexIndices[j * 3 + 2]] :=
VectorAdd(m.Normals.items[VertexIndices[j * 3 + 2]], n);
end;
end;
fgmmQuads:
begin
for j := 0 to (VertexIndices.count div 4) - 1 do
begin
v1 := m.vertices[VertexIndices[j * 4]];
v2 := m.vertices[VertexIndices[j * 4 + 1]];
v3 := m.vertices[VertexIndices[j * 4 + 2]];
v4 := m.vertices[VertexIndices[j * 4 + 3]];
n := CalcPlaneNormal(v1, v2, v3);
m.Normals.items[VertexIndices[j * 4]] :=
VectorAdd(m.Normals.items[VertexIndices[j * 4]], n);
m.Normals.items[VertexIndices[j * 4 + 1]] :=
VectorAdd(m.Normals.items[VertexIndices[j * 4 + 1]], n);
m.Normals.items[VertexIndices[j * 4 + 2]] :=
VectorAdd(m.Normals.items[VertexIndices[j * 4 + 2]], n);
m.Normals.items[VertexIndices[j * 4 + 3]] :=
VectorAdd(m.Normals.items[VertexIndices[j * 4 + 3]], n);
end;
end;
end;
for i := 0 to m.Normals.count - 1 do
m.Normals.items[i] := VectorNormalize(m.Normals.items[i]);
end;
procedure TGLDXFVectorFile.LoadFromStream(aStream: TStream);
var
S: STRING;
code, i: Integer;
begin
FLastpercentdone := 1;
/// DoProgress (psStarting,0,false,'Starting');
FEof := FALSE;
FSourceStream := aStream;
FLineNo := 0;
HasPushedCode := FALSE;
FLayers := TStringList.create;
FBlocks := TStringList.create;
while not FEof do
begin
/// DoProgress (psStarting,FSourceStream.Position/FSourceStream.Size*90,false,'');
code := GetCode;
if (code = 0) then
begin
S := ReadLine;
if S = 'EOF' then
break
else if S = 'SECTION' then
begin
code := GetCode;
if code <> 2 then
raise Exception.create('Name must follow Section' + ' on Line #' +
IntToStr(FLineNo))
else
begin
S := ReadLine;
if S = 'HEADER' then
SkipSection
else if S = 'BLOCKS' then
ReadBlocks
else if S = 'ENTITIES' then
ReadEntities(owner)
else if S = 'CLASSES' then
SkipSection
else if S = 'TABLES' then
ReadTables
else if S = 'OBJECTS' then
SkipSection
else
SkipSection;
end
end
else if S = 'ENDSEC' then
raise Exception.create('SECTION/ENDSEC Mismatch' + ' on Line #' +
IntToStr(FLineNo))
end
else
S := ReadLine; // raise Exception.create ('Invalid Group Code');
end;
// calc normals
FLayers.free;
for i := FBlocks.count - 1 downto 0 do
(FBlocks.Objects[i] as TGLFreeForm).free;
FBlocks.free;
for i := 0 to owner.MeshObjects.count - 1 do
BuildNormals(owner.MeshObjects[i]);
/// DoProgress (psEnding,100,false,'');
end;
initialization
RegisterVectorFileFormat('dxf', 'AutoCAD Exchange Format', TGLDXFVectorFile);
end.
|
unit IdAllHeaderCoders;
interface
{$i IdCompilerDefines.inc}
{
Note that this unit is simply for listing ALL Header coders in Indy.
The user could then add this unit to a uses clause in their program and
have all Header coders linked into their program.
ABSOLUTELY NO CODE is permitted in this unit.
}
// RLebeau 2/14/09: this forces C++Builder to link to this unit so
// the units can register themselves correctly at program startup...
(*$HPPEMIT '#pragma link "IdAllHeaderCoders"'*)
implementation
uses
IdHeaderCoderPlain,
IdHeaderCoder2022JP,
{$IFNDEF DOTNET}
IdHeaderCoderUTF,
{$ENDIF}
IdHeaderCoderIndy;
{dee-duh-de-duh, that's all folks.}
end.
|
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls;
type
{ TfrmDistance }
TfrmDistance = class(TForm)
btnShowDistance: TButton;
cboFrom: TComboBox;
cboTo: TComboBox;
lblDistance: TLabel;
lblTo: TLabel;
lblFrom: TLabel;
procedure btnShowDistanceClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
var
frmDistance: TfrmDistance;
implementation
{$R *.lfm}
const
NoOfCities = 3;
Cities: array[1..NoOfCities] of string = ('Durban','Cape Town','Johannesburg');
Distances: array[1..NoOfCities, 1..NoOfCities] of integer
= ((0, 1660, 598), //Durban src
(1660, 0, 1405), //Cape Town src
(598, 1405, 0)); //Joburg src
{ TfrmDistance }
procedure TfrmDistance.btnShowDistanceClick(Sender: TObject);
var
FromCity, ToCity: integer;
begin
//get the selected cities
FromCity:=cboFrom.ItemIndex+1;
ToCity:=cboTo.ItemIndex+1;
//display relevant distance
lblDistance.Caption:=IntToStr(Distances[FromCity, ToCity]) + 'km';
end;
procedure TfrmDistance.FormCreate(Sender: TObject);
var
I: integer;
begin
//add the cities to both comboboxes
for I:=1 to NoOfCities do
begin
cboFrom.Items.Add(Cities[I]);
cboTo.Items.Add(Cities[I]);
end;
//set defaults in ComboBoxes to 1st city
cboFrom.ItemIndex:=0;
cboTo.ItemIndex:=0;
end;
end.
|
unit uWorkEffort;
{$mode objfpc}{$H+}
interface
uses
SynCommons, mORMot, uForwardDeclaration;//Classes, SysUtils;
type
// 1
TSQLTimeEntry = class(TSQLRecord)
private
fParty: TSQLPartyID;
fFromDate: TDateTime;
fThruDate: TDateTime;
fRateType: TSQLRateTypeID;
fWorkEffort: TSQLWorkEffortID;
fTimesheet: TSQLTimesheetID;
fInvoice: TSQLInvoiceID;
fInvoiceItemSeq: Integer;
fHours: Double;
fComments: RawUTF8;
published
property Party: TSQLPartyID read fParty write fParty;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
property RateType: TSQLRateTypeID read fRateType write fRateType;
property WorkEffort: TSQLWorkEffortID read fWorkEffort write fWorkEffort;
property Timesheet: TSQLTimesheetID read fTimesheet write fTimesheet;
property Invoice: TSQLInvoiceID read fInvoice write fInvoice;
property InvoiceItemSeq: Integer read fInvoiceItemSeq write fInvoiceItemSeq;
property Hours: Double read fHours write fHours;
property Comments: RawUTF8 read fComments write fComments;
end;
// 2
TSQLTimesheet = class(TSQLRecord)
private
fParty: TSQLPartyID;
fClientParty: TSQLPartyID;
fFromDate: TDateTime;
fThruDate: TDateTime;
fStatus: TSQLStatusItemID;
fApprovedByUserLogin: TSQLUserLoginID;
fComments: RawUTF8;
published
property Party: TSQLPartyID read fParty write fParty;
property ClientParty: TSQLPartyID read fClientParty write fClientParty;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
property Status: TSQLStatusItemID read fStatus write fStatus;
property ApprovedByUserLogin: TSQLUserLoginID read fApprovedByUserLogin write fApprovedByUserLogin;
property Comments: RawUTF8 read fComments write fComments;
end;
// 3
TSQLTimesheetRole = class(TSQLRecord)
private
fTimesheet: TSQLTimesheetID;
fParty: TSQLPartyID;
fRoleType: TSQLRoleTypeID;
published
property Timesheet: TSQLTimesheetID read fTimesheet write fTimesheet;
property Party: TSQLPartyID read fParty write fParty;
property RoleType: TSQLRoleTypeID read fRoleType write fRoleType;
end;
// 4
TSQLApplicationSandbox = class(TSQLRecord)
private
fWorkEffort: Integer;
fParty: Integer;
fRoleType: Integer;
fFromDate: TDateTime;
fRuntimeData: TSQLRuntimeDataID;
published
property WorkEffort: Integer read fWorkEffort write fWorkEffort;
property Party: Integer read fParty write fParty;
property RoleType: Integer read fRoleType write fRoleType;
property FromDate: TDateTime read fFromDate write fFromDate;
property RuntimeData: TSQLRuntimeDataID read fRuntimeData write fRuntimeData;
end;
// 5
TSQLCommunicationEventWorkEff = class(TSQLRecord)
private
fWorkEffort: TSQLWorkEffortID;
fCommunicationEvent: TSQLCommunicationEventID;
fDescription: RawUTF8;
published
property WorkEffort: TSQLWorkEffortID read fWorkEffort write fWorkEffort;
property CommunicationEvent: TSQLCommunicationEventID read fCommunicationEvent write fCommunicationEvent;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 6
TSQLDeliverable = class(TSQLRecord)
private
fDeliverableType: TSQLDeliverableTypeID;
fDeliverableName: RawUTF8;
fDescription: RawUTF8;
published
property DeliverableType: TSQLDeliverableTypeID read fDeliverableType write fDeliverableType;
property DeliverableName: RawUTF8 read fDeliverableName write fDeliverableName;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 7
TSQLDeliverableType = class(TSQLRecord)
private
fName: RawUTF8;
FDescription: RawUTF8;
published
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 8
TSQLWorkEffort = class(TSQLRecord)
private
fEncode: RawUTF8;
fWorkEffortType: TSQLWorkEffortTypeID;
fCurrentStatus: TSQLStatusItemID;
fLastStatusUpdate: TDateTime;
fWorkEffortPurposeType: TSQLWorkEffortPurposeTypeID;
fWorkEffortParent: TSQLWorkEffortID;
fScopeEnum: TSQLEnumerationID;
fPriority: Integer;
fPercentComplete: Integer;
fWorkEffortName: RawUTF8;
fShowAsEnum: Integer;
fSendNotificationEmail: Boolean;
fDescription: RawUTF8;
fLocationDesc: RawUTF8;
fEstimatedStartDate: TDateTime;
fEstimatedCompletionDate: TDateTime;
fActualStartDate: TDateTime;
fActualCompletionDate: TDateTime;
fEstimatedMilliSeconds: Double;
fEstimatedSetupMillis: Double;
fEstimateCalcMethod: TSQLCustomMethodID;
fActualMilliSeconds: Double;
fActualSetupMillis: Double;
fTotalMilliSecondsAllowed: Double;
fTotalMoneyAllowed: Currency;
fMoneyUom: TSQLUomID;
fSpecialTerms: RawUTF8;
fTimeTransparency: Integer;
fUniversal: RawUTF8;
fSourceReference: Integer;
fFixedAsset: TSQLFixedAssetID;
fFacility: TSQLFacilityID;
fInfoUrl: RawUTF8;
fRecurrenceInfo: TSQLRecurrenceInfoID;
fTempExpr: TSQLTemporalExpressionID;
fRuntimeData: TSQLRuntimeDataID;
fNote: TSQLNoteDataID;
fServiceLoaderName: RawUTF8;
fQuantityToProduce: Double;
fQuantityProduced: Double;
fQuantityRejected: Double;
fReservPersons: Double;
fReserv2ndPPPerc: Double;
fReservNthPPPerc: Double;
fAccommodationMap: TSQLAccommodationMapID;
fAccommodationSpot: TSQLAccommodationSpotID;
fRevisionNumber: Integer;
fCreatedDate: TDateTime;
fCreatedByUserLogin: TSQLUserLoginID;
fLastModifiedDate: TDateTime;
fLastModifiedByUserLogin: TSQLUserLoginID;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property WorkEffortType: TSQLWorkEffortTypeID read fWorkEffortType write fWorkEffortType;
property CurrentStatus: TSQLStatusItemID read fCurrentStatus write fCurrentStatus;
property LastStatusUpdate: TDateTime read fLastStatusUpdate write fLastStatusUpdate;
property WorkEffortPurposeType: TSQLWorkEffortPurposeTypeID read fWorkEffortPurposeType write fWorkEffortPurposeType;
property WorkEffortParent: TSQLWorkEffortID read fWorkEffortParent write fWorkEffortParent;
property ScopeEnum: TSQLEnumerationID read fScopeEnum write fScopeEnum;
property Priority: Integer read fPriority write fPriority;
property PercentComplete: Integer read fPercentComplete write fPercentComplete;
property WorkEffortName: RawUTF8 read fWorkEffortName write fWorkEffortName;
property ShowAsEnum: Integer read fShowAsEnum write fShowAsEnum;
property SendNotificationEmail: Boolean read fSendNotificationEmail write fSendNotificationEmail;
property Description: RawUTF8 read fDescription write fDescription;
property LocationDesc: RawUTF8 read fLocationDesc write fLocationDesc;
property EstimatedStartDate: TDateTime read fEstimatedStartDate write fEstimatedStartDate;
property EstimatedCompletionDate: TDateTime read fEstimatedCompletionDate write fEstimatedCompletionDate;
property ActualStartDate: TDateTime read fActualStartDate write fActualStartDate;
property ActualCompletionDate: TDateTime read fActualCompletionDate write fActualCompletionDate;
property EstimatedMilliSeconds: Double read fEstimatedMilliSeconds write fEstimatedMilliSeconds;
property EstimatedSetupMillis: Double read fEstimatedSetupMillis write fEstimatedSetupMillis;
property EstimateCalcMethod: TSQLCustomMethodID read fEstimateCalcMethod write fEstimateCalcMethod;
property ActualMilliSeconds: Double read fActualMilliSeconds write fActualMilliSeconds;
property ActualSetupMillis: Double read fActualSetupMillis write fActualSetupMillis;
property TotalMilliSecondsAllowed: Double read fTotalMilliSecondsAllowed write fTotalMilliSecondsAllowed;
property TotalMoneyAllowed: Currency read fTotalMoneyAllowed write fTotalMoneyAllowed;
property MoneyUom: TSQLUomID read fMoneyUom write fMoneyUom;
property SpecialTerms: RawUTF8 read fSpecialTerms write fSpecialTerms;
property TimeTransparency: Integer read fTimeTransparency write fTimeTransparency;
property Universal: RawUTF8 read fUniversal write fUniversal;
property SourceReference: Integer read fSourceReference write fSourceReference;
property FixedAsset: TSQLFixedAssetID read fFixedAsset write fFixedAsset;
property Facility: TSQLFacilityID read fFacility write fFacility;
property InfoUrl: RawUTF8 read fInfoUrl write fInfoUrl;
property RecurrenceInfo: TSQLRecurrenceInfoID read fRecurrenceInfo write fRecurrenceInfo;
property TempExpr: TSQLTemporalExpressionID read fTempExpr write fTempExpr;
property RuntimeData: TSQLRuntimeDataID read fRuntimeData write fRuntimeData;
property Note: TSQLNoteDataID read fNote write fNote;
property ServiceLoaderName: RawUTF8 read fServiceLoaderName write fServiceLoaderName;
property QuantityToProduce: Double read fQuantityToProduce write fQuantityToProduce;
property QuantityProduced: Double read fQuantityProduced write fQuantityProduced;
property QuantityRejected: Double read fQuantityRejected write fQuantityRejected;
property ReservPersons: Double read fReservPersons write fReservPersons;
property Reserv2ndPPPerc: Double read fReserv2ndPPPerc write fReserv2ndPPPerc;
property ReservNthPPPerc: Double read fReservNthPPPerc write fReservNthPPPerc;
property AccommodationMap: TSQLAccommodationMapID read fAccommodationMap write fAccommodationMap;
property AccommodationSpot: TSQLAccommodationSpotID read fAccommodationSpot write fAccommodationSpot;
property RevisionNumber: Integer read fRevisionNumber write fRevisionNumber;
property CreatedDate: TDateTime read fCreatedDate write fCreatedDate;
property CreatedByUserLogin: TSQLUserLoginID read fCreatedByUserLogin write fCreatedByUserLogin;
property LastModifiedDate: TDateTime read fLastModifiedDate write fLastModifiedDate;
property LastModifiedByUserLogin: TSQLUserLoginID read fLastModifiedByUserLogin write fLastModifiedByUserLogin;
end;
// 9
TSQLWorkEffortAssoc = class(TSQLRecord)
private
fWorkEffortIdFrom: TSQLWorkEffortID;
fWorkEffortIdTo: TSQLWorkEffortID;
fWorkEffortAssocType: TSQLWorkEffortAssocTypeID;
fSequenceNum: Integer;
fFromDate: TDateTime;
fThruDate: TDateTime;
published
property WorkEffortIdFrom: TSQLWorkEffortID read fWorkEffortIdFrom write fWorkEffortIdFrom;
property WorkEffortIdTo: TSQLWorkEffortID read fWorkEffortIdTo write fWorkEffortIdTo;
property WorkEffortAssocType: TSQLWorkEffortAssocTypeID read fWorkEffortAssocType write fWorkEffortAssocType;
property SequenceNum: Integer read fSequenceNum write fSequenceNum;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
end;
// 10
TSQLWorkEffortAssocAttribute = class(TSQLRecord)
private
fWorkEffortIdFrom: TSQLWorkEffortID;
fWorkEffortIdTo: TSQLWorkEffortID;
fWorkEffortAssocType: TSQLWorkEffortAssocTypeID;
fFromDate: TDateTime;
fAttrName: TSQLInventoryItemTypeAttrID;
fAttrValue: RawUTF8;
fAttrDescription: RawUTF8;
published
property WorkEffortIdFrom: TSQLWorkEffortID read fWorkEffortIdFrom write fWorkEffortIdFrom;
property WorkEffortIdTo: TSQLWorkEffortID read fWorkEffortIdTo write fWorkEffortIdTo;
property WorkEffortAssocType: TSQLWorkEffortAssocTypeID read fWorkEffortAssocType write fWorkEffortAssocType;
property FromDate: TDateTime read fFromDate write fFromDate;
property AttrName: TSQLInventoryItemTypeAttrID read fAttrName write fAttrName;
property AttrValue: RawUTF8 read fAttrValue write fAttrValue;
property AttrDescription: RawUTF8 read fAttrDescription write fAttrDescription;
end;
// 11
TSQLWorkEffortAssocType = class(TSQLRecord)
private
fParent: TSQLWorkEffortAssocTypeID;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
published
property Parent: TSQLWorkEffortAssocTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 12
TSQLWorkEffortAssocTypeAttr = class(TSQLRecord)
private
fWorkEffortAssocType: TSQLWorkEffortAssocTypeID;
fAttrName: TSQLInventoryItemTypeAttrID;
fDescription: RawUTF8;
published
property WorkEffortAssocType: TSQLWorkEffortAssocTypeID read fWorkEffortAssocType write fWorkEffortAssocType;
property AttrName: TSQLInventoryItemTypeAttrID read fAttrName write fAttrName;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 13
TSQLWorkEffortAttribute = class(TSQLRecord)
private
fWorkEffort: TSQLWorkEffortID;
fAttrName: TSQLInventoryItemTypeAttrID;
fAttrValue: RawUTF8;
fAttrDescription: RawUTF8;
published
property WorkEffort: TSQLWorkEffortID read fWorkEffort write fWorkEffort;
property AttrName: TSQLInventoryItemTypeAttrID read fAttrName write fAttrName;
property AttrValue: RawUTF8 read fAttrValue write fAttrValue;
property AttrDescription: RawUTF8 read fAttrDescription write fAttrDescription;
end;
// 14
TSQLWorkEffortBilling = class(TSQLRecord)
private
fWorkEffort: TSQLWorkEffortID;
fInvoice: TSQLInvoiceID;
fInvoiceItemSeq: Integer;
fPercentage: Double;
published
property WorkEffort: TSQLWorkEffortID read fWorkEffort write fWorkEffort;
property Invoice: TSQLInvoiceID read fInvoice write fInvoice;
property InvoiceItemSeq: Integer read fInvoiceItemSeq write fInvoiceItemSeq;
property Percentage: Double read fPercentage write fPercentage;
end;
// 15
TSQLWorkEffortContactMech = class(TSQLRecord)
private
fWorkEffort: TSQLWorkEffortID;
fContactMech: TSQLContactMechID;
fFromDate: TDateTime;
fThruDate: TDateTime;
fComments: RawUTF8;
published
property WorkEffort: TSQLWorkEffortID read fWorkEffort write fWorkEffort;
property ContactMech: TSQLContactMechID read fContactMech write fContactMech;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
property Comments: RawUTF8 read fComments write fComments;
end;
// 16
TSQLWorkEffortContent = class(TSQLRecord)
private
fWorkEffort: TSQLWorkEffortID;
fContent: TSQLContentID;
fWorkEffortContentType: TSQLWorkEffortContentTypeID;
fFromDate: TDateTime;
fThruDate: TDateTime;
published
property WorkEffort: TSQLWorkEffortID read fWorkEffort write fWorkEffort;
property Content: TSQLContentID read fContent write fContent;
property WorkEffortContentType: TSQLWorkEffortContentTypeID read fWorkEffortContentType write fWorkEffortContentType;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
end;
// 17
TSQLWorkEffortContentType = class(TSQLRecord)
private
fParent: TSQLWorkEffortContentTypeID;
fName: RawUTF8;
FDescription: RawUTF8;
published
property Parent: TSQLWorkEffortContentTypeID read fParent write fParent;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 18
TSQLWorkEffortDeliverableProd = class(TSQLRecord)
private
fWorkEffort: TSQLWorkEffortID;
fDeliverable: TSQLDeliverableID;
published
property WorkEffort: TSQLWorkEffortID read fWorkEffort write fWorkEffort;
property Deliverable: TSQLDeliverableID read fDeliverable write fDeliverable;
end;
// 19
TSQLWorkEffortEventReminder = class(TSQLRecord)
private
fWorkEffort: TSQLWorkEffortID;
fSequence: Integer;
fContactMech: TSQLContactMechID;
fParty: TSQLPartyID;
fReminderDateTime: TDateTime;
fRepeatCount: Integer;
fRepeatInterval: Integer;
fCurrentCount: Integer;
fReminderOffset: Integer;
fLocale: Integer;
fTimeZone: Integer;
published
property WorkEffort: TSQLWorkEffortID read fWorkEffort write fWorkEffort;
property Sequence: Integer read fSequence write fSequence;
property ContactMech: TSQLContactMechID read fContactMech write fContactMech;
property Party: TSQLPartyID read fParty write fParty;
property ReminderDateTime: TDateTime read fReminderDateTime write fReminderDateTime;
property RepeatCount: Integer read fRepeatCount write fRepeatCount;
property RepeatInterval: Integer read fRepeatInterval write fRepeatInterval;
property CurrentCount: Integer read fCurrentCount write fCurrentCount;
property ReminderOffset: Integer read fReminderOffset write fReminderOffset;
property Locale: Integer read fLocale write fLocale;
property TimeZone: Integer read fTimeZone write fTimeZone;
end;
// 20
TSQLWorkEffortFixedAssetAssign = class(TSQLRecord)
private
fWorkEffort: TSQLWorkEffortID;
fFixedAsset: TSQLFixedAssetID;
fStatus: TSQLStatusItemID;
fFromDate: TDateTime;
fThruDate: TDateTime;
fAvailabilityStatus: TSQLStatusItemID;
fAllocatedCost: Currency;
fComments: RawUTF8;
published
property WorkEffort: TSQLWorkEffortID read fWorkEffort write fWorkEffort;
property FixedAsset: TSQLFixedAssetID read fFixedAsset write fFixedAsset;
property Status: TSQLStatusItemID read fStatus write fStatus;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
property AvailabilityStatus: TSQLStatusItemID read fAvailabilityStatus write fAvailabilityStatus;
property AllocatedCost: Currency read fAllocatedCost write fAllocatedCost;
property Comments: RawUTF8 read fComments write fComments;
end;
// 21
TSQLWorkEffortFixedAssetStd = class(TSQLRecord)
private
fWorkEffort: TSQLWorkEffortID;
fFixedAssetType: TSQLFixedAssetTypeID;
fEstimatedQuantity: Double;
fEstimatedDuration: Double;
fEstimatedCost: Currency;
published
property WorkEffort: TSQLWorkEffortID read fWorkEffort write fWorkEffort;
property FixedAssetType: TSQLFixedAssetTypeID read fFixedAssetType write fFixedAssetType;
property EstimatedQuantity: Double read fEstimatedQuantity write fEstimatedQuantity;
property EstimatedDuration: Double read fEstimatedDuration write fEstimatedDuration;
property EstimatedCost: Currency read fEstimatedCost write fEstimatedCost;
end;
// 22
TSQLWorkEffortGoodStandard = class(TSQLRecord)
private
fWorkEffort: TSQLWorkEffortID;
fProduct: TSQLProductID;
fWorkEffortGoodStdType: TSQLWorkEffortGoodStandardTypeID;
fFromDate: TDateTime;
fThruDate: TDateTime;
fStatus: TSQLStatusItemID;
fEstimatedQuantity: Double;
fEstimatedCost: Currency;
published
property WorkEffort: TSQLWorkEffortID read fWorkEffort write fWorkEffort;
property Product: TSQLProductID read fProduct write fProduct;
property WorkEffortGoodStdType: TSQLWorkEffortGoodStandardTypeID read fWorkEffortGoodStdType write fWorkEffortGoodStdType;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
property Status: TSQLStatusItemID read fStatus write fStatus;
property EstimatedQuantity: Double read fEstimatedQuantity write fEstimatedQuantity;
property EstimatedCost: Currency read fEstimatedCost write fEstimatedCost;
end;
// 23
TSQLWorkEffortGoodStandardType = class(TSQLRecord)
private
fParent: TSQLWorkEffortGoodStandardTypeID;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
published
property Parent: TSQLWorkEffortGoodStandardTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 24
TSQLWorkEffortIcalData = class(TSQLRecord)
private
fWorkEffort: TSQLWorkEffortID;
fIcalData: TSQLRawBlob;
published
property WorkEffort: TSQLWorkEffortID read fWorkEffort write fWorkEffort;
property IcalData: TSQLRawBlob read fIcalData write fIcalData;
end;
// 25
TSQLWorkEffortInventoryAssign = class(TSQLRecord)
private
fWorkEffort: TSQLWorkEffortID;
fInventoryItem: TSQLInventoryItemID;
fStatus: TSQLStatusItemID;
fQuantity: Double;
published
property WorkEffort: TSQLWorkEffortID read fWorkEffort write fWorkEffort;
property InventoryItem: TSQLInventoryItemID read fInventoryItem write fInventoryItem;
property Status: TSQLStatusItemID read fStatus write fStatus;
property Quantity: Double read fQuantity write fQuantity;
end;
// 26
TSQLWorkEffortInventoryProduced = class(TSQLRecord)
private
fWorkEffort: TSQLWorkEffortID;
fInventoryItem: TSQLInventoryItemID;
published
property WorkEffort: TSQLWorkEffortID read fWorkEffort write fWorkEffort;
property InventoryItem: TSQLInventoryItemID read fInventoryItem write fInventoryItem;
end;
// 27
TSQLWorkEffortCostCalc = class(TSQLRecord)
private
fWorkEffort: TSQLWorkEffortID;
fCostComponentType: TSQLCostComponentTypeID;
fCostComponentCalc: TSQLCostComponentCalcID;
fFromDate: TDateTime;
fThruDate: TDateTime;
published
property WorkEffort: TSQLWorkEffortID read fWorkEffort write fWorkEffort;
property CostComponentType: TSQLCostComponentTypeID read fCostComponentType write fCostComponentType;
property CostComponentCalc: TSQLCostComponentCalcID read fCostComponentCalc write fCostComponentCalc;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
end;
// 28
TSQLWorkEffortKeyword = class(TSQLRecord)
private
fWorkEffort: TSQLWorkEffortID;
fKeyword: RawUTF8;
fRelevancyWeight: Integer;
published
property WorkEffort: TSQLWorkEffortID read fWorkEffort write fWorkEffort;
property Keyword: RawUTF8 read fKeyword write fKeyword;
property RelevancyWeight: Integer read fRelevancyWeight write fRelevancyWeight;
end;
// 29
TSQLWorkEffortNote = class(TSQLRecord)
private
fWorkEffort: TSQLWorkEffortID;
fNote: TSQLNoteDataID;
fInternalNote: Boolean;
published
property WorkEffort: TSQLWorkEffortID read fWorkEffort write fWorkEffort;
property Note: TSQLNoteDataID read fNote write fNote;
property InternalNote: Boolean read fInternalNote write fInternalNote;
end;
// 30
TSQLWorkEffortPartyAssignment = class(TSQLRecord)
private
fWorkEffort: TSQLWorkEffortID;
fParty: TSQLPartyID;
fRoleType: TSQLRoleTypeID;
fFromDate: TDateTime;
fThruDate: TDateTime;
fAssignedByUserLogin: TSQLUserLoginID;
fStatus: TSQLStatusItemID;
fStatusDateTime: TDateTime;
fExpectationEnum: TSQLEnumerationID;
fDelegateReasonEnum: TSQLEnumerationID;
fFacility: TSQLFacilityID;
fComments: RawUTF8;
fMustRsvp: Boolean;
fAvailabilityStatus: TSQLStatusItemID;
published
property WorkEffort: TSQLWorkEffortID read fWorkEffort write fWorkEffort;
property Party: TSQLPartyID read fParty write fParty;
property RoleType: TSQLRoleTypeID read fRoleType write fRoleType;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
property AssignedByUserLogin: TSQLUserLoginID read fAssignedByUserLogin write fAssignedByUserLogin;
property Status: TSQLStatusItemID read fStatus write fStatus;
property StatusDateTime: TDateTime read fStatusDateTime write fStatusDateTime;
property ExpectationEnum: TSQLEnumerationID read fExpectationEnum write fExpectationEnum;
property DelegateReasonEnum: TSQLEnumerationID read fDelegateReasonEnum write fDelegateReasonEnum;
property Facility: TSQLFacilityID read fFacility write fFacility;
property Comments: RawUTF8 read fComments write fComments;
property MustRsvp: Boolean read fMustRsvp write fMustRsvp;
property AvailabilityStatus: TSQLStatusItemID read fAvailabilityStatus write fAvailabilityStatus;
end;
// 31
TSQLWorkEffortPurposeType = class(TSQLRecord)
private
fParent: TSQLWorkEffortPurposeTypeID;
fName: RawUTF8;
FDescription: RawUTF8;
published
property Parent: TSQLWorkEffortPurposeTypeID read fParent write fParent;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 32
TSQLWorkEffortReview = class(TSQLRecord)
private
fWorkEffort: TSQLWorkEffortID;
fUserLogin: TSQLUserLoginID;
fReviewDate: TDateTime;
fStatus: TSQLStatusItemID;
fPostedAnonymous: Boolean;
fRating: Double;
fReviewText: TSQLRawBlob;
published
property WorkEffort: TSQLWorkEffortID read fWorkEffort write fWorkEffort;
property UserLogin: TSQLUserLoginID read fUserLogin write fUserLogin;
property ReviewDate: TDateTime read fReviewDate write fReviewDate;
property Status: TSQLStatusItemID read fStatus write fStatus;
property PostedAnonymous: Boolean read fPostedAnonymous write fPostedAnonymous;
property Rating: Double read fRating write fRating;
property ReviewText: TSQLRawBlob read fReviewText write fReviewText;
end;
// 33
TSQLWorkEffortSearchConstraint = class(TSQLRecord)
private
fWorkEffortSearchResult: TSQLWorkEffortSearchResultID;
fConstraintSeq: Integer;
fConstraintName: RawUTF8;
fInfoString: RawUTF8;
fIncludeSubWorkEfforts: Boolean;
fIsAnd: Boolean;
fAnyPrefix: Boolean;
fAnySuffix: Boolean;
fRemoveStems: Boolean;
fLowValue: RawUTF8;
fHighValue: RawUTF8;
published
property WorkEffortSearchResult: TSQLWorkEffortSearchResultID read fWorkEffortSearchResult write fWorkEffortSearchResult;
property ConstraintSeq: Integer read fConstraintSeq write fConstraintSeq;
property ConstraintName: RawUTF8 read fConstraintName write fConstraintName;
property InfoString: RawUTF8 read fInfoString write fInfoString;
property IncludeSubWorkEfforts: Boolean read fIncludeSubWorkEfforts write fIncludeSubWorkEfforts;
property IsAnd: Boolean read fIsAnd write fIsAnd;
property AnyPrefix: Boolean read fAnyPrefix write fAnyPrefix;
property AnySuffix: Boolean read fAnySuffix write fAnySuffix;
property RemoveStems: Boolean read fRemoveStems write fRemoveStems;
property LowValue: RawUTF8 read fLowValue write fLowValue;
property HighValue: RawUTF8 read fHighValue write fHighValue;
end;
// 34
TSQLWorkEffortSearchResult = class(TSQLRecord)
private
fVisit: Integer;
fOrderByName: RawUTF8;
fIsAscending: Boolean;
fNumResults: Integer;
fSecondsTotal: Double;
fSearchDate: TDateTime;
published
property Visit: Integer read fVisit write fVisit;
property OrderByName: RawUTF8 read fOrderByName write fOrderByName;
property IsAscending: Boolean read fIsAscending write fIsAscending;
property NumResults: Integer read fNumResults write fNumResults;
property SecondsTotal: Double read fSecondsTotal write fSecondsTotal;
property SearchDate: TDateTime read fSearchDate write fSearchDate;
end;
// 35
TSQLWorkEffortSkillStandard = class(TSQLRecord)
private
fWorkEffort: TSQLWorkEffortID;
fSkillType: TSQLSkillTypeID;
fEstimatedNumPeople: Double;
fEstimatedDuration: Double;
fEstimatedCost: Currency;
published
property WorkEffort: TSQLWorkEffortID read fWorkEffort write fWorkEffort;
property SkillType: TSQLSkillTypeID read fSkillType write fSkillType;
property EstimatedNumPeople: Double read fEstimatedNumPeople write fEstimatedNumPeople;
property EstimatedDuration: Double read fEstimatedDuration write fEstimatedDuration;
property EstimatedCost: Currency read fEstimatedCost write fEstimatedCost;
end;
// 36
TSQLWorkEffortStatus = class(TSQLRecord)
private
fWorkEffort: TSQLWorkEffortID;
fStatus: TSQLStatusItemID;
fStatusDatetime: TDateTime;
fSetByUserLogin: TSQLUserLoginID;
fReason: RawUTF8;
published
property WorkEffort: TSQLWorkEffortID read fWorkEffort write fWorkEffort;
property Status: TSQLStatusItemID read fStatus write fStatus;
property StatusDatetime: TDateTime read fStatusDatetime write fStatusDatetime;
property SetByUserLogin: TSQLUserLoginID read fSetByUserLogin write fSetByUserLogin;
property Reason: RawUTF8 read fReason write fReason;
end;
// 37
TSQLWorkEffortTransBox = class(TSQLRecord)
private
fprocessWorkEffort: TSQLWorkEffortID;
fToActivity: Integer;
fTransition: Integer;
published
property processWorkEffort: TSQLWorkEffortID read fprocessWorkEffort write fprocessWorkEffort;
property ToActivity: Integer read fToActivity write fToActivity;
property Transition: Integer read fTransition write fTransition;
end;
// 38
TSQLWorkEffortType = class(TSQLRecord)
private
fEncode: RawUTF8;
fParentEncode: RawUTF8;
fParent: TSQLWorkEffortTypeID;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property ParentEncode: RawUTF8 read fParentEncode write fParentEncode;
property Parent: TSQLWorkEffortTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 39
TSQLWorkEffortTypeAttr = class(TSQLRecord)
private
fWorkEffortType: TSQLWorkEffortTypeID;
fAttrName: TSQLWorkEffortAttributeID;
fDescription: RawUTF8;
published
property WorkEffortType: TSQLWorkEffortTypeID read fWorkEffortType write fWorkEffortType;
property AttrName: TSQLWorkEffortAttributeID read fAttrName write fAttrName;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 40
TSQLWorkEffortSurveyAppl = class(TSQLRecord)
private
fWorkEffort: TSQLWorkEffortID;
fSurvey: TSQLSurveyID;
fFromDate: TDateTime;
fThruDate: TDateTime;
published
property WorkEffort: TSQLWorkEffortID read fWorkEffort write fWorkEffort;
property Survey: TSQLSurveyID read fSurvey write fSurvey;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
end;
implementation
uses
Classes, SysUtils;
// 1
class procedure TSQLWorkEffort.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLWorkEffort;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLWorkEffort.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','WorkEffort.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
finally
Rec.Free;
end;
end;
// 2
class procedure TSQLWorkEffortType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLWorkEffortType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLWorkEffortType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','WorkEffortType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update WorkEffortType set Parent=(select c.id from WorkEffortType c where c.Encode=WorkEffortType.ParentEncode);');
finally
Rec.Free;
end;
end;
end.
|
unit QueryExecutor;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,ZConnection, ZDataset,udm;
type
{ TQueryExecutor }
TOnQueryEvent = procedure(Sender: TObject ; ASQL: string) of object;
TQueryExecutor = class(TThread)
private
FOnAfterExecSQL: TNotifyEvent;
FOnQueryError: TOnQueryEvent;
FQuery: TZQuery;
FList: TStringList;
FSQLQueue: integer;
FOnExecQuery: TOnQueryEvent;
procedure DecList;
public
constructor Create(ASQLList: TStringList);
destructor Destroy;
property SQLQueue: integer read FSQLQueue write FSQLQueue;
property OnAfterExecSQL: TNotifyEvent read FOnAfterExecSQL write FOnAfterExecSQL;
property OnExecQuery: TOnQueryEvent read FOnExecQuery write FOnExecQuery;
property OnQueryError: TOnQueryEvent read FOnQueryError write FOnQueryError;
protected
procedure Execute; override;
end;
{ TQueryList }
TQueryList = class
private
FFExecutor: TQueryExecutor;
FOnExecQuery: TOnQueryEvent;
FOnQueryError: TOnQueryEvent;
FSQLList: TStringList;
FExecutor: TQueryExecutor;
FSQLQueue: integer;
procedure OnAfterExecSQL(Sender: TObject);
procedure EvOnExecQuery(Sender: TObject ; SQL: string);
procedure EvOnQueryError(Sender: TObject ; SQL: string);
public
constructor Create;
destructor Destroy;
procedure AddJob(ASQL: string);
property SQLQueue: integer read FSQLQueue write FSQLQueue;
property Executor: TQueryExecutor read FFExecutor;
property OnExecQuery: TOnQueryEvent read FOnExecQuery write FOnExecQuery;
property OnQueryError: TOnQueryEvent read FOnQueryError write FOnQueryError;
end;
implementation
{ TQueryExecutor }
procedure TQueryExecutor.DecList;
begin
FList.Delete(0);
end;
constructor TQueryExecutor.Create(ASQLList: TStringList);
begin
inherited Create(True);
FQuery := TZQuery.Create(nil);
FQuery.Connection := dm.zConn;
FList := ASQLList;
FreeOnTerminate:=True;
end;
destructor TQueryExecutor.Destroy;
begin
FreeAndNil(FQuery);
inherited;
end;
procedure TQueryExecutor.Execute;
var
asql : string;
begin
FreeOnTerminate:=True;
while (true) and (not Terminated) do
begin
try
if FList.Count < 1 then
begin
Sleep(500);
Continue;
end;
if Trim(FList[0]) = '' then
begin
Sleep(500);
Continue;
end;
with FQuery do
begin
Close;
asql := FList[0];
sql.Text:=asql;
if Assigned(FOnExecQuery) then
FOnExecQuery(Self,asql);
ExecSQL;
FSQLQueue:=FList.Count;
if Assigned(FOnAfterExecSQL) then
FOnAfterExecSQL(Self);
Synchronize(@DecList);
//FList.Delete(0);
//FList.Delete(0);
//sleep(50)
end;
except
with dm do
begin
//zConn.Disconnect;
if Assigned(FOnQueryError) then
FOnQueryError(Self,asql);
zConn.Connect;
end;
end;
end;
end;
{ TQueryExecutor }
procedure TQueryList.OnAfterExecSQL(Sender: TObject);
begin
FSQLQueue:=FSQLList.Count;
end;
procedure TQueryList.EvOnExecQuery(Sender: TObject; SQL: string);
begin
if Assigned(FOnExecQuery) then
FOnExecQuery(Sender,SQL);
end;
procedure TQueryList.EvOnQueryError(Sender: TObject; SQL: string);
begin
if Assigned(FOnQueryError) then
FOnQueryError(Sender,SQL);
end;
constructor TQueryList.Create;
begin
FSQLList := TStringList.Create;
FExecutor := TQueryExecutor.Create(FSQLList);
FExecutor.OnAfterExecSQL:=@OnAfterExecSQL;
FExecutor.OnExecQuery:=@EvOnExecQuery;
FExecutor.Resume;
end;
destructor TQueryList.Destroy;
begin
FreeAndNil(FSQLList);
FExecutor.Terminate;
end;
procedure TQueryList.AddJob(ASQL: string);
begin
FSQLList.Add(ASQL);
end;
end.
|
unit DataBaseUnit;
interface
uses
FireDAC.Comp.Client;
type
TDataBase = class(TObject)
private const
database: String = 'database';
class procedure CreateNewDataBase(const ADataBaseFolder, AApplicationFolder
: String); static;
class function CreateTempDatabaseFileName: string; static;
class function DatabaseFileName: string; static;
class function GetDataBaseFile(const ADataBaseFolder: String;
var AFileName: string; var AVersion: Double; AMaxVersion: Double)
: Boolean; static;
class function EmptyDatabaseFileName: string; static;
class function GetUpdateScript(Version: Integer; ADBMigrationFolder: String)
: string; static;
class function UpdateDatabaseStructure(ADBMigrationFolder: String;
ALastVersion: Integer; const ADataBaseFileName: String): Integer; static;
protected
public
class function OpenDBConnection(AConnection: TFDConnection;
const ADataBaseFolder, ADBMigrationFolder, AApplicationFolder: String)
: Boolean; static;
end;
implementation
uses
System.Types, System.IOUtils, System.SysUtils, ProjectConst, DialogUnit,
VersionQuery, Winapi.Windows;
class procedure TDataBase.CreateNewDataBase(const ADataBaseFolder,
AApplicationFolder: String);
var
ADataBaseFileName: string;
AEmptyDatabaseFileName: string;
begin
// определяемся с именем файла "пустой" базы данных
AEmptyDatabaseFileName := TPath.Combine(AApplicationFolder,
EmptyDatabaseFileName);
if not TFile.Exists(AEmptyDatabaseFileName) then
raise Exception.Create(Format('Не могу создать пустую базу данных.' + #13#10
+ 'Не найден файл %s', [EmptyDatabaseFileName]));
// Формируем полное имя базы данных
ADataBaseFileName := TPath.Combine(ADataBaseFolder, DatabaseFileName);
TFile.Copy(AEmptyDatabaseFileName, ADataBaseFileName);
end;
class function TDataBase.CreateTempDatabaseFileName: string;
begin
Result := FormatDateTime('"database "yyyy-mm-dd" "hh-nn-ss".db"', Now);
end;
class function TDataBase.GetDataBaseFile(const ADataBaseFolder: String;
var AFileName: string; var AVersion: Double; AMaxVersion: Double): Boolean;
var
AMaxVer: Double;
AMaxVerFileName: string;
m: TStringDynArray;
p: Integer;
begin
Assert(not ADataBaseFolder.IsEmpty);
Result := False;
AMaxVer := 0;
AMaxVerFileName := '';
// Ищем какую-либо версию базы данных
m := TDirectory.GetFiles(ADataBaseFolder,
function(const Path: string; const SearchRec: TSearchRec): Boolean
Var
AExt: String;
AFile_Name: string;
AVer: Double;
SVer: String;
begin
Result := False;
AExt := TPath.GetExtension(SearchRec.Name);
if AExt <> '.db' then
Exit;
AFile_Name := TPath.GetFileNameWithoutExtension(SearchRec.Name).ToLower;
p := AFile_Name.IndexOf(database);
// Имя файла базы данных должно начинаться с database
if p <> 0 then
Exit;
// Имя файла от версии отделено пробелом или нижним подчёркиванием
SVer := AFile_Name.Substring(database.Length).Trim([' ', '_']);
if (SVer = '') and (AMaxVer = 0) then
begin
AMaxVer := 1;
AMaxVerFileName := SearchRec.Name;
Result := True;
Exit;
end;
AVer := StrToFloatDef(SVer.Replace('.', ','), 0);
if AVer = 0 then
Exit;
if (AVer > AMaxVer) and (AVer <= AMaxVersion) then
begin
AMaxVer := AVer;
AMaxVerFileName := SearchRec.Name;
Result := True;
Exit;
end;
end);
// Не нашли ни одного подходящего файла
if AMaxVerFileName = '' then
Exit;
AFileName := TPath.Combine(ADataBaseFolder, AMaxVerFileName);
AVersion := AMaxVer;
Result := True;
end;
class function TDataBase.DatabaseFileName: string;
begin
Result := Format('database %.1f', [ProgramVersion]).Replace(',', '.') + '.db';
end;
class function TDataBase.EmptyDatabaseFileName: string;
begin
Result := Format('empty %.1f', [ProgramVersion]).Replace(',', '.') + '.db';
end;
class function TDataBase.GetUpdateScript(Version: Integer;
ADBMigrationFolder: String): string;
var
AFileName: string;
begin
Assert(not ADBMigrationFolder.IsEmpty);
if TDirectory.Exists(ADBMigrationFolder) then
begin
AFileName := TPath.Combine(ADBMigrationFolder, Format('%d.sql', [Version]));
if TFile.Exists(AFileName) then
begin
Result := TFile.ReadAllText(AFileName);
end
else
begin
raise Exception.CreateFmt
('Невозможно произвести обновление базы данных.'#13#10'Не найдена файл %s.',
[AFileName]);
end;
end
else
raise Exception.Create
('Невозможно произвести обновление базы данных.'#13#10'Не найдена папка Update.');
end;
class function TDataBase.OpenDBConnection(AConnection: TFDConnection;
const ADataBaseFolder, ADBMigrationFolder, AApplicationFolder: String): Boolean;
var
ADataBaseFileName: String;
ADBVersion: Integer;
AFileName: string;
ANewFileName: string;
AVersion: Double;
begin
// Result := False;
Assert(AConnection <> nil);
Assert(not ADataBaseFolder.IsEmpty);
Assert(not ADBMigrationFolder.IsEmpty);
Assert(not AApplicationFolder.IsEmpty);
try
// Ищем подходящий нам файл базы данных
if GetDataBaseFile(ADataBaseFolder, AFileName, AVersion, ProgramVersion)
then
begin
// Если подходящий файл базы данных найден
Assert(AVersion <= Double(ProgramVersion));
if AVersion < ProgramVersion then
begin
Result := TDialog.Create.UpdateDataBaseDialog(AVersion, ProgramVersion);
// Отказались от обновления БД
if not Result then
Exit;
ANewFileName := TPath.Combine(ADataBaseFolder,
CreateTempDatabaseFileName);
TFile.Copy(AFileName, ANewFileName);
try
// Обновляем структуру БД
UpdateDatabaseStructure(ADBMigrationFolder, DBVersion, ANewFileName);
except
// При обновлении версии БД произошла какая-то ошибка
on E: Exception do
begin
// Удаляем временный файл
try
TFile.Delete(ANewFileName);
except
;
end;
raise Exception.CreateFmt
('Ошибка при обновлении структуры базы данных.'#13#10'%s',
[E.Message]);
end;
end;
if not RenameFile(ANewFileName, ADatabaseFileName) then
raise Exception.CreateFmt('Не могу переименовать файл %s в %s',
[ANewFileName, DatabaseFileName]);
end;
end
else
begin
Result := TDialog.Create.CreateNewDatabaseDialog;
// Отказались от создания новой базы данных
if not Result then
Exit;
// Создаём новую БД
CreateNewDataBase(ADataBaseFolder, AApplicationFolder);
end;
// Формируем полное имя базы данных
ADataBaseFileName := TPath.Combine(ADataBaseFolder, DatabaseFileName);
// Если дошли до этого места, значит файл базы данных или был обновлён, или создан, или сразу существовал
if not TFile.Exists(ADataBaseFileName) then
raise Exception.CreateFmt('Не найден файл базы данных %s',
[ADataBaseFileName]);
AConnection.DriverName := sDriverName;
AConnection.Params.DriverID := sDriverName;
AConnection.Params.database := ADataBaseFileName;
// Устанавливаем соединение с БД
AConnection.Open();
// Проверяем версию БД в самой БД
ADBVersion := TQueryVersion.GetDBVersion;
if ADBVersion <> DBVersion then
begin
Result := TDialog.Create.UpdateDataBaseDialog2;
// Отказались от обновления БД
if not Result then
Exit;
AConnection.Close;
ANewFileName := TPath.Combine(ADataBaseFolder,
CreateTempDatabaseFileName);
TFile.Copy(AFileName, ANewFileName);
try
// Обновляем структуру БД
UpdateDatabaseStructure(ADBMigrationFolder, DBVersion, ANewFileName);
except
// При обновлении версии БД произошла какая-то ошибка
on E: Exception do
begin
// Удаляем временный файл
try
TFile.Delete(ANewFileName);
except
;
end;
raise Exception.CreateFmt
('Ошибка при обновлении структуры базы данных.'#13#10'%s',
[E.Message]);
end;
end;
TFile.Delete(ADataBaseFileName);
if not RenameFile(ANewFileName, ADatabaseFileName) then
raise Exception.CreateFmt('Не могу переименовать файл %s в %s',
[ANewFileName, ADatabaseFileName]);
end;
// Устанавливаем соединение с БД
AConnection.Open();
// Проверяем версию БД в самой БД
ADBVersion := TQueryVersion.GetDBVersion;
if ADBVersion <> DBVersion then
begin
raise Exception.CreateFmt
('Неверная версия базы данных (надо %d, имеем %d)',
[DBVersion, ADBVersion]);
end;
Result := True;
except
on E: Exception do
begin
Result := False;
TDialog.Create.ErrorMessageDialog(E.Message);
end;
end;
end;
class function TDataBase.UpdateDatabaseStructure(ADBMigrationFolder: String;
ALastVersion: Integer; const ADataBaseFileName: String): Integer;
var
ASQL: string;
AUpdateConnection: TFDConnection;
m: TArray<String>;
s: string;
begin
Assert(ALastVersion > 0);
Assert(not ADBMigrationFolder.IsEmpty);
AUpdateConnection := TFDConnection.Create(nil);
try
AUpdateConnection.DriverName := sDriverName;
AUpdateConnection.Params.database := ADataBaseFileName;
// AUpdateConnection.Params.DriverID := sDriverName;
AUpdateConnection.Connected := True;
// Текущая версия БД
Result := AUpdateConnection.ExecSQLScalar('select version from dbVersion');
// Если у нас и так последняя версия БД или Версия БД больше чем надо
if Result >= ALastVersion then
Exit;
// пока текущая версия БД не последняя
while Result < ALastVersion do
begin
// Получаем очередной скрипт для обновления БД
ASQL := GetUpdateScript(Result + 1, ADBMigrationFolder);
m := ASQL.Split([#13#10#13#10]);
// Начинаем транзакцию
AUpdateConnection.StartTransaction;
try
for s in m do
begin
ASQL := s.Trim([' ', #13, #10]);
if ASQL.IsEmpty then
Continue;
AUpdateConnection.ExecSQL(ASQL); // Выполняем обновление структуры БД
end;
AUpdateConnection.ExecSQL // Выполняем обновление версии БД
(String.Format('update dbVersion set version = %d', [Result + 1]));
except
// Если во время обновления структуры БД произошла ошибка
AUpdateConnection.Rollback;
raise;
end;
AUpdateConnection.Commit;
// Переход к следующей версии прошёл успешно!
Inc(Result);
end;
finally
AUpdateConnection.Connected := False;
FreeAndNil(AUpdateConnection);
end;
end;
end.
|
unit TStringsUnit;
interface
implementation
uses System;
type
TStrings<TData> = class
private
type
TItem = record
Key: string;
Value: TData;
end;
TItemList = array of TItem;
var
FList: TItemList;
FSorted: Boolean;
function GetCount: Int32;
function GetName(Index: Int32): string;
function GetValue(Index: Int32): TData;
procedure QuickSort(Values: TItemList; L, R: Int32);
public
procedure Add(const Str: string);
procedure Sort;
property Count: Int32 read GetCount;
property Sorted: Boolean read FSorted;
property Names[Index: Int32]: string read GetName;
property Values[Index: Int32]: TData read GetValue;
function Find(const S: string; var Index: Int32): Boolean;
function IndexOf(const S: string): Int32;
end;
function Compare(const L, R: string): Int32;
begin
if L < R then
Result := -1
else if L > R then
Result := 1
else
Result := 0;
end;
function TStrings<TData>.Find(const S: string; var Index: Integer): Boolean;
var
L, H, I, C: Integer;
begin
Result := False;
L := 0;
H := Count - 1;
while L <= H do
begin
I := (L + H) shr 1;
C := Compare(FList[I].Key, S);
if C < 0 then L := I + 1 else
begin
H := I - 1;
if C = 0 then
begin
Result := True;
Index := I;
Exit;
//if Duplicates <> dupAccept then L := I;
end;
end;
end;
Index := L;
end;
function TStrings<TData>.IndexOf(const S: string): Int32;
begin
if not Find(S, Result) then
Result := -1;
end;
function TStrings<TData>.GetCount: Int32;
begin
Result := Length(FList);
end;
function TStrings<TData>.GetName(Index: Int32): string;
begin
Result := FList[Index].Key;
end;
function TStrings<TData>.GetValue(Index: Int32): TData;
begin
Result := FList[Index].Value;
end;
procedure TStrings<TData>.Add(const Str: string);
var
Len: Int32;
begin
Len := Length(FList);
SetLength(FList, Len + 1);
FList[Len].Key := Str;
end;
procedure TStrings<TData>.QuickSort(Values: TItemList; L, R: Int32);
var
I, J: Int32;
pivot: string;
temp: TItem;
begin
if (Length(Values) = 0) or ((R - L) <= 0) then
Exit;
repeat
I := L;
J := R;
pivot := Values[L + (R - L) shr 1].Key;
repeat
while Compare(Values[I].Key, pivot) < 0 do
Inc(I);
while Compare(Values[J].Key, pivot) > 0 do
Dec(J);
if I <= J then
begin
if I <> J then
begin
temp := Values[I];
Values[I] := Values[J];
Values[J] := temp;
end;
Inc(I);
Dec(J);
end;
until I > J;
if L < J then
QuickSort(Values, L, J);
L := I;
until I >= R;
end;
procedure TStrings<TData>.Sort;
begin
QuickSort(FList, Low(FList), High(FList));
end;
type
TStr = TStrings<Int32>;
var Str: TStr;
Idx: Int32;
GC: Int32;
procedure Test;
begin
Str := TStr.Create();
Str.Add('aaa');
Str.Add('ccc');
Str.Add('bbb');
Str.Sort();
GC := Str.Count;
Idx := Str.IndexOf('bbb');
end;
initialization
Test();
finalization
Assert(GC = 3);
Assert(Idx = 1);
Assert(Str.Names[0] = 'aaa');
Assert(Str.Names[1] = 'bbb');
Assert(Str.Names[2] = 'ccc');
end. |
unit uPopupMenuCxGrid;
interface
uses Classes, Forms, Menus, Windows, cxGrid, Dialogs, DBClient, DB;
type TTipoSelecao = (tsMarcarTodos, tsInverterSelecao);
type TPopupMenuSelecionar = class(TObject)
private
fPopupMenu : TPopupMenu;
fCxGrid : TcxGrid;
fCds : TClientDataSet;
protected
procedure createMenuItems; virtual; abstract;
procedure beforePopup; virtual; abstract;
function AddSubMenuItem(AMenuItem: TMenuItem; ACaption: String; AOnClick: TNotifyEvent; ATag: Integer): TMenuItem;
function AddMenuItem(ACaption: String; AOnClick: TNotifyEvent; ATag: Integer): TMenuItem;
public
constructor Create;
destructor Destroy; override;
procedure Popup(AGrid: TcxGrid; ACds: TClientDataSet; X, Y: Integer); virtual;
procedure PopupFromCursor(AGrid: TcxGrid; ACds: TClientDataSet);
end;
TCxGridPopupMenuSelecionar = class(TPopupMenuSelecionar)
private
fSelecionarTodosItem : TMenuItem;
fInverterSelecaoItem : TMenuItem;
procedure doSelecionarTodos(Sender: TObject);
procedure doInverterSelecao(Sender: TObject);
procedure selecao(Acds: TClientDataSet; ATipoSelecao: TTipoSelecao);
protected
procedure BeforePopup; override;
procedure CreateMenuItems; override;
end;
TcxGridPopupMenuManager = class(TCxGridPopupMenuSelecionar)
private
gridPopupMenu : TCxGridPopupMenuSelecionar;
protected
constructor CreateInstance;
class function AccessInstance(Request: Integer): TcxGridPopupMenuManager;
public
constructor Create;
destructor Destroy; override;
class function Instance: TcxGridPopupMenuManager;
class procedure ReleaseInstance;
function ShowGridPopupMenu(Grid: TcxGrid; ACds: TClientDataSet): Boolean;
end;
implementation
const
stSelecionarTodos = 'Marcar Todos';
stInverterSelecao = 'Inverter Seleção';
{ TPopupMenuSelecionar }
function TPopupMenuSelecionar.AddMenuItem(ACaption: String; AOnClick: TNotifyEvent; ATag: Integer): TMenuItem;
begin
result := AddSubMenuItem(fPopupMenu.Items, ACaption, AOnClick, ATag);
end;
function TPopupMenuSelecionar.AddSubMenuItem(AMenuItem: TMenuItem; ACaption: String; AOnClick: TNotifyEvent; ATag: Integer): TMenuItem;
begin
Result := TMenuItem.Create(nil);
Result.Caption := ACaption;
Result.OnClick := AOnClick;
Result.Tag := ATag;
AMenuItem.Add(Result);
end;
constructor TPopupMenuSelecionar.Create;
begin
inherited create;
fPopupMenu := TPopupMenu.Create(nil);
CreateMenuItems;
end;
destructor TPopupMenuSelecionar.Destroy;
begin
fPopupMenu.Free;
inherited Destroy;
end;
procedure TPopupMenuSelecionar.Popup(AGrid: TcxGrid; ACds: TClientDataSet; X, Y: Integer);
begin
fCxGrid := AGrid;
fCds := ACds;
fCxGrid.PopupMenu := fPopupMenu;
BeforePopup;
//fPopupMenu.Popup(X, Y);
end;
procedure TPopupMenuSelecionar.PopupFromCursor(AGrid: TcxGrid; ACds: TClientDataSet);
var
Point: TPoint;
begin
GetCursorPos(Point);
Popup(AGrid, ACds, Point.X, Point.Y);
end;
{ TCxGridPopupMenuSelecionar }
procedure TCxGridPopupMenuSelecionar.BeforePopup;
begin
inherited;
//
end;
procedure TCxGridPopupMenuSelecionar.CreateMenuItems;
var
MenuItem: TMenuItem;
Align : TAlignment;
begin
fSelecionarTodosItem := AddMenuItem(stSelecionarTodos, doSelecionarTodos, 0);
fInverterSelecaoItem := AddMenuItem(stInverterSelecao, doInverterSelecao, 1);
end;
procedure TCxGridPopupMenuSelecionar.doInverterSelecao(Sender: TObject);
begin
selecao(fCds, tsInverterSelecao);
end;
procedure TCxGridPopupMenuSelecionar.doSelecionarTodos(Sender: TObject);
begin
selecao(fCds, tsMarcarTodos);
end;
procedure TCxGridPopupMenuSelecionar.selecao(Acds: TClientDataSet; ATipoSelecao: TTipoSelecao);
var
b : TBookmark;
begin
if Acds.Active then
begin
b := Acds.GetBookmark;
Acds.DisableControls;
try
Acds.First;
while not Acds.Eof do
begin
Acds.Edit;
//////////////////////////////////////////////////////////////////////////
/// Para funcionar corretamente, o campo checkbox da grid, deve ser o
/// primeiro campo da instrução select
//////////////////////////////////////////////////////////////////////////
if ATipoSelecao = tsMarcarTodos then
Acds.FieldByName('Selecionar').Value := 'S'
else
if Acds.FieldByName('Selecionar').AsString = 'S' then
Acds.FieldByName('Selecionar').Value := 'N'
else
Acds.FieldByName('Selecionar').Value := 'S';
Acds.Post;
Acds.Next;
end;
finally
Acds.EnableControls;
Acds.GotoBookmark(b);
Acds.FreeBookmark(b);
end;
end;
end;
{ TcxGridPopupMenuManager }
class function TcxGridPopupMenuManager.AccessInstance(Request: Integer): TcxGridPopupMenuManager;
var
FInstance : TcxGridPopupMenuManager;
begin
FInstance := nil;
case Request of
0 : ;
1 : if not Assigned(FInstance) then FInstance := CreateInstance;
2 : FInstance := nil;
//else
//raise Exception.CreateFmt('Illegal request %d in AccessInstance',
//[Request]); //
end;
Result := FInstance;
end;
constructor TcxGridPopupMenuManager.Create;
begin
inherited Create;
//raise Exception.CreateFmt('Access class %s through Instance only',
//[ClassName]);
end;
constructor TcxGridPopupMenuManager.CreateInstance;
begin
inherited create;
gridPopupMenu := TCxGridPopupMenuSelecionar.Create;
end;
destructor TcxGridPopupMenuManager.Destroy;
begin
if AccessInstance(1) = Self then AccessInstance(2);
gridPopupMenu.Free;
inherited;
end;
class function TcxGridPopupMenuManager.Instance: TcxGridPopupMenuManager;
begin
Result := AccessInstance(1);
end;
class procedure TcxGridPopupMenuManager.ReleaseInstance;
begin
AccessInstance(0).Free;
end;
function TcxGridPopupMenuManager.ShowGridPopupMenu(Grid: TcxGrid; ACds: TClientDataSet): boolean;
begin
gridPopupMenu.PopupFromCursor(Grid, ACds);
Result := True;
end;
end.
|
unit bool_arith_mixed_3;
interface
implementation
var G1, G2, G3, G4: boolean;
function GetBool(Cond: Boolean): Boolean;
begin
Result := Cond;
end;
procedure Test1;
begin
G1 := GetBool(true) or GetBool(false) or not GetBool(true);
end;
procedure Test2;
begin
G2 := GetBool(false) or GetBool(true) or not GetBool(true);
end;
procedure Test3;
begin
G3 := GetBool(False) or GetBool(False) or not GetBool(False);
end;
procedure Test4;
begin
G4 := GetBool(False) or GetBool(False) or not GetBool(True);
end;
initialization
Test1();
Test2();
Test3();
Test4();
finalization
Assert(G1);
Assert(G2);
Assert(G3);
Assert(not G4);
end. |
unit uConversoes;
interface
uses
uInterfaces, Classes, SysUtils, StrUtils, Dialogs, Rtti;
type
EValorObrigatorio = class(Exception);
TConverteTexto = class(TInterfacedObject, IConversao)
private
FTexto : String;
procedure SetTexto(const Value : string);
public
property Texto : String read FTexto write SetTexto;
function Converter(Texto : String) : String; virtual; abstract;
end;
TConverteInvertido = class(TConverteTexto)
public
function Converter(Texto : String) : String; override;
end;
TConvertePrimeiraMaiuscula = class(TConverteTexto)
public
function Converter(Texto : String) : String; override;
end;
TConverteOrdenado = class(TConverteTexto)
public
function Converter(Texto : String) : String; override;
end;
implementation
procedure TConverteTexto.SetTexto(const Value: string);
begin
try
if Value = EmptyStr then
raise EValorObrigatorio.Create('Necessário preencher o campo texto!')
else
FTexto := Value;
except
On E:EValorObrigatorio do
ShowMessage(E.Message);
end;
end;
function TConverteInvertido.Converter(Texto : String) : String;
begin
Result := ReverseString(Texto);
end;
function TConvertePrimeiraMaiuscula.Converter(Texto : String) : String;
var
i: integer;
espaco: boolean;
begin
Texto := LowerCase(Trim(Texto));
for i := 1 to Length(Texto) do
begin
if i = 1 then
Texto[i] := UpCase(Texto[i])
else
begin
if i <> Length(Texto) then
begin
espaco := (Texto[i] = ' ');
if espaco then
Texto[i+1] := UpCase(Texto[i+1]);
end;
end;
end;
Result := Texto;
end;
function TConverteOrdenado.Converter(Texto : String) : String;
var
i : integer;
ListaTexto : TStringList;
begin
ListaTexto := TStringList.Create;
try
Texto := StringReplace(Trim(Texto), ' ', EmptyStr, [rfReplaceAll]);
for i:=1 to length(Texto) do
begin
ListaTexto.Add(Texto[i]);
end;
ListaTexto.Sort;
Texto := '';
for i:=0 to ListaTexto.Count - 1 do
begin
Texto := Texto + ListaTexto[i];
end;
Result := Texto;
finally
FreeAndNil(ListaTexto);
end;
end;
end.
|
{$A+,B-,E-,F+,G+,I-,N-,O-,P-,Q-,R-,S-,T-,V-,X-}
{-------------------------------
Palette unit - Turbo Pascal 7.0
-----------------------------------}
unit palette;
interface
type
rgbpal = record
r,g,b : byte;
end;
pal_type = array[0..255] of rgbpal;
procedure pal_entry(color,red,green,blue:byte);
procedure pal_set(which:pointer);
procedure pal_all(red,green,blue:byte);
procedure pal_fade(which:pointer; delay:word);
procedure pal_light(which:pointer; delay:word);
procedure pal_unfade(which:pointer; delay:word);
procedure pal_unlight(which:pointer; delay:word);
procedure pal_modify(delay:integer; which:pointer; r,g,b:integer);
procedure pal_work2pal(which:pointer);
procedure vga_pal16;
procedure pal_spread(r,g,b:word; pal:pointer; radd,gadd,badd:integer; start,ending:word);
procedure pal_copy(pal:pointer; starting,ending,upto:integer);
procedure pal_change(pal:pointer; r,g,b:integer; start,ending:integer);
implementation
{$l palette.obj}
procedure pal_entry(color,red,green,blue:byte); external;
procedure pal_set(which:pointer); external;
procedure pal_all(red,green,blue:byte); external;
procedure pal_fade(which:pointer; delay:word); external;
procedure pal_light(which:pointer; delay:word); external;
procedure pal_unfade(which:pointer; delay:word); external;
procedure pal_unlight(which:pointer; delay:word); external;
procedure pal_modify(delay:integer; which:pointer; r,g,b:integer); external;
procedure pal_work2pal(which:pointer); external;
procedure vga_pal16; external;
procedure pal_spread(r,g,b:word; pal:pointer; radd,gadd,badd:integer; start,ending:word); external;
procedure pal_copy(pal:pointer; starting,ending,upto:integer); external;
procedure pal_change(pal:pointer; r,g,b:integer; start,ending:integer); external;
begin
end.
|
unit adot.Collections.Sets;
{
TSet<T>
record type with full set of (compatible) overloaded operators:
- can be initialized either by Init/Create or assigment operator:
S.Init([1,2,3]); // call Init to initialize
S := [1,2,3]; // same
- default string comparer is case insensitive
S := ['one','two'];
Assert('ONE' in S);
- supports all logical operators (and,or,xor)
A := [1,2,3];
B := [2,3,4];
Assert((A and B).Count = 2);
Assert(A or B = TSet<integer>.Create([1,2,3,4]));
- supports all compare operators (<,<=,=,<>,>,>=)
A := [1,2];
B := [1,2,3,4];
Assert(A < B);
- supports IN,Add,Subtract,Implicit,Explicit operators
A := [1,2];
B := [1,2,3,4];
Assert(B - A = TSet<integer>.Create([3,4]));
- has .OwnsValues property (can be used as TObjectSet<T>)
- can be sent as parameter similar to regular object pointer, all changes will be visible in the source set
procedure RemoveNegative(S: TSet<integer>); // "var" specifier can be used as well
var Value: integer;
begin
for Value in S.ToArray do
if Value < 0 then
S.Remove(Value);
end;
// "const" (as in following example) should be avoided.
// For const params compiler will not trigger internal interface ref counter.
// If TSet is not stored explicitly in some variable then it may lead to memory leak.
function CountPositives(const S: TSet<integer>): integer;
var Value: integer;
begin
result := 0;
for Value in S do
if Value > 0 then
inc(result);
end;
- supports automatic reference counting (no need to destruct manually)
var S: TSet<string>;
begin
S := ['1','2','test'];
assert('1' in S);
end;
- based on TDictionary, performance penalty (in comparing with TDictionary) is close to zero
TSetClass<T>
class based implementation (not so handy as record based TSet<T>, but sometime
class or manual life time control is required).
}
interface
uses
adot.Collections.Types,
adot.Types,
System.Generics.Collections,
System.Generics.Defaults;
type
TSetDataStorage<T> = class(TDictionary<T, TEmptyRec>)
protected
procedure KeyNotify(const Value: T; Action: TCollectionNotification); override;
private
{ TDictionary hides FComparer in private section, we have to keep the copy }
FDataComparer: IEqualityComparer<T>;
FOwnsValues: boolean;
procedure SetOwnsValues(const Value: boolean);
property OwnsValues: boolean read FOwnsValues write SetOwnsValues;
property DataComparer: IEqualityComparer<T> read FDataComparer;
constructor Create(ACapacity: Integer; const AComparer: IEqualityComparer<T>); reintroduce;
end;
TSet<T> = record
private
FData: TSetDataStorage<T>; { valid as long as FDataIntf is alive }
FDataIntf: IInterfacedObject<TObject>; { maintains lifecycle }
function GetCount: Integer;
function GetOnNotify: TCollectionNotifyEvent<T>;
procedure SetOnNotify(const Value: TCollectionNotifyEvent<T>);
function GetComparer: IEqualityComparer<T>;
function GetEmpty: Boolean;
function GetOwnsValues: boolean;
procedure SetOwnsValues(const Value: boolean);
function GetCollection: TEnumerable<T>;
function GetContainsValue(const AValue: T): boolean;
procedure SetContainsValue(const AValue: T; const AContains: boolean);
public
type
{ we can't define it as "TSetDataStorage<T>.TKeyEnumerator", delphi 10.2.3 fails to compile (internal error) }
TEnumerator = TDictionary<T, TEmptyRec>.TKeyEnumerator;
procedure Init; overload;
procedure Init(ACapacity: Integer; const AComparer: IEqualityComparer<T> = nil); overload;
procedure Init(const AValues: TEnumerable<T>; const AComparer: IEqualityComparer<T> = nil); overload;
procedure Init(const AValues: TArray<T>; const AComparer: IEqualityComparer<T> = nil); overload;
procedure Init(const AValues: array of T; const AComparer: IEqualityComparer<T> = nil); overload;
class function Create: TSet<T>; overload; static;
class function Create(ACapacity: Integer; const AComparer: IEqualityComparer<T> = nil): TSet<T>; overload; static;
class function Create(const AValues: TEnumerable<T>; const AComparer: IEqualityComparer<T> = nil): TSet<T>; overload; static;
class function Create(const AValues: TArray<T>; const AComparer: IEqualityComparer<T> = nil): TSet<T>; overload; static;
class function Create(const AValues: array of T; const AComparer: IEqualityComparer<T> = nil): TSet<T>; overload; static;
function GetEnumerator: TEnumerator;
procedure Add(const AValue: T); overload;
procedure Add(const AValues: TEnumerable<T>); overload;
procedure Add(const AValues: TArray<T>); overload;
procedure Add(const AValues: array of T); overload;
procedure Add(const AValues: TSet<T>); overload;
procedure Remove(const AValue: T); overload;
procedure Remove(const AValues: TEnumerable<T>); overload;
procedure Remove(const AValues: TArray<T>); overload;
procedure Remove(const AValues: TSet<T>); overload;
{ Normally it is preferred to use syntax "Item in MySet" }
function Contains(const AValue: T): Boolean; overload;
function Contains(const AValues: TEnumerable<T>) : Boolean; overload;
function Contains(const AValues: TArray<T>) : Boolean; overload;
function Contains(const AValues: TSet<T>) : Boolean; overload;
function Extract(const Value: T): T;
procedure CopyFrom(const Src: TSet<T>);
function Copy: TSet<T>;
function ToArray: TArray<T>;
function ToString: string;
function ToText(const ValuesDelimiter: string = #13#10): string;
procedure Clear; { Unlike Init it does not initialize the structure, it only removes data, all props remain unchanged }
procedure TrimExcess;
class operator In(const a: T; b: TSet<T>) : Boolean;
class operator In(const a: TEnumerable<T>; b: TSet<T>) : Boolean;
class operator In(const a: TArray<T>; b: TSet<T>) : Boolean;
class operator In(const a: TSet<T>; b: TSet<T>) : Boolean;
class operator Implicit(const a : TEnumerable<T>) : TSet<T>;
class operator Implicit(const a : TArray<T>) : TSet<T>;
class operator Explicit(const a : TEnumerable<T>) : TSet<T>;
class operator Explicit(const a : TArray<T>) : TSet<T>;
class operator Add(a: TSet<T>; const b: T ): TSet<T>;
class operator Add(a: TSet<T>; const b: TEnumerable<T> ): TSet<T>;
class operator Add(a: TSet<T>; const b: TArray<T> ): TSet<T>;
class operator Add(a: TSet<T>; const b: TSet<T> ): TSet<T>;
class operator Add(const a: T; b: TSet<T>): TSet<T>;
class operator Add(const a: TEnumerable<T>; b: TSet<T>): TSet<T>;
class operator Add(const a: TArray<T>; b: TSet<T>): TSet<T>;
class operator Subtract(a: TSet<T>; const b: T ): TSet<T>;
class operator Subtract(a: TSet<T>; const b: TEnumerable<T> ): TSet<T>;
class operator Subtract(a: TSet<T>; const b: TArray<T> ): TSet<T>;
class operator Subtract(a: TSet<T>; const b: TSet<T> ): TSet<T>;
class operator Subtract(const a: T; b: TSet<T>): TSet<T>;
class operator Subtract(const a: TEnumerable<T>; b: TSet<T>): TSet<T>;
class operator Subtract(const a: TArray<T>; b: TSet<T>): TSet<T>;
{ To compare TEnumerable<T>/TArray<T> againt TSet<T>, we convert them to TSet<T> anyway.
It can be done by Implicit operator, no need to overload Equal operator for TEnumerable<T>/TArray<T>.
It is correct for some other operators as well (GreaterThan etc). }
class operator Equal(const a: TSet<T>; const b: TSet<T> ): Boolean;
class operator NotEqual(const a: TSet<T>; const b: TSet<T> ): Boolean;
class operator GreaterThanOrEqual(const a: TSet<T>; const b: TEnumerable<T> ): Boolean;
class operator GreaterThanOrEqual(const a: TSet<T>; const b: TArray<T> ): Boolean;
class operator GreaterThanOrEqual(const a: TSet<T>; const b: TSet<T> ): Boolean;
class operator GreaterThan(const a: TSet<T>; const b: TSet<T> ): Boolean;
class operator LessThan(const a: TSet<T>; const b: TEnumerable<T> ): Boolean;
class operator LessThan(const a: TSet<T>; const b: TArray<T> ): Boolean;
class operator LessThan(const a: TSet<T>; const b: TSet<T> ): Boolean;
class operator LessThanOrEqual(const a: TSet<T>; const b: TSet<T> ): Boolean;
class operator LogicalAnd(const a: TSet<T>; const b: TEnumerable<T> ): TSet<T>;
class operator LogicalAnd(const a: TSet<T>; const b: TArray<T> ): TSet<T>;
class operator LogicalAnd(const a: TSet<T>; const b: TSet<T> ): TSet<T>;
class operator LogicalOr(const a: TSet<T>; const b: TEnumerable<T> ): TSet<T>;
class operator LogicalOr(const a: TSet<T>; const b: TArray<T> ): TSet<T>;
class operator LogicalOr(const a: TSet<T>; const b: TSet<T> ): TSet<T>;
class operator LogicalXor(const a: TSet<T>; const b: TSet<T> ): TSet<T>;
property Count: Integer read GetCount;
property Empty: Boolean read GetEmpty;
property OwnsValues: boolean read GetOwnsValues write SetOwnsValues;
property OnNotify: TCollectionNotifyEvent<T> read GetOnNotify write SetOnNotify;
property Comparer: IEqualityComparer<T> read GetComparer;
property Collection: TEnumerable<T> read GetCollection;
property ContainsValue[const Value: T]: boolean read GetContainsValue write SetContainsValue; default;
end;
TSetClass<T> = class(TEnumerableExt<T>)
private
FData: TSetDataStorage<T>;
function GetCount: integer;
function GetComparer: IEqualityComparer<T>;
procedure SetOwnsValues(AOwnsValues: boolean);
function GetOwnsValues: boolean;
function GetContainsValue(const AValue: T): boolean;
procedure SetContainsValue(const AValue: T; const AContains: boolean);
function GetOnNotify: TCollectionNotifyEvent<T>;
procedure SetOnNotify(const Value: TCollectionNotifyEvent<T>);
function GetEmpty: Boolean;
protected
type
TEnumerator = TDictionary<T, TEmptyRec>.TKeyEnumerator;
function DoGetEnumerator: TEnumerator<T>; override;
public
constructor Create(ACapacity: integer = 0; AComparer: IEqualityComparer<T> = nil); overload;
constructor Create(const AValues: TArray<T>; AComparer: IEqualityComparer<T> = nil); overload;
constructor Create(const AValues: TEnumerable<T>; AComparer: IEqualityComparer<T> = nil); overload;
destructor Destroy; override;
procedure Add(const AValue: T); overload;
procedure Add(const AValues: TArray<T>); overload;
procedure Add(const AValues: TEnumerable<T>); overload;
procedure Remove(const AValue: T); overload;
procedure Remove(const AValues: TArray<T>); overload;
procedure Remove(const AValues: TEnumerable<T>); overload;
function Contains(const AValue: T): boolean; overload;
function Contains(const AValues: TArray<T>): boolean; overload;
function Contains(const AValues: TEnumerable<T>): boolean; overload;
procedure Clear;
function ToArray: TArray<T>; override;
property Count: integer read GetCount;
property Empty: Boolean read GetEmpty;
property OwnsValues: boolean read GetOwnsValues write SetOwnsValues;
property OnNotify: TCollectionNotifyEvent<T> read GetOnNotify write SetOnNotify;
property Comparer: IEqualityComparer<T> read GetComparer;
property ContainsValue[const Value: T]: boolean read GetContainsValue write SetContainsValue; default;
end;
implementation
uses
adot.Collections,
adot.Tools,
adot.Tools.RTTI,
System.SysUtils;
{ TSetDataStorage<T> }
constructor TSetDataStorage<T>.Create(ACapacity: Integer; const AComparer: IEqualityComparer<T>);
begin
if AComparer = nil
then FDataComparer := TComparerUtils.DefaultEqualityComparer<T>
else FDataComparer := AComparer;
inherited Create(ACapacity, FDataComparer);
end;
procedure TSetDataStorage<T>.KeyNotify(const Value: T; Action: TCollectionNotification);
begin
inherited;
if FOwnsValues and (Action = TCollectionNotification.cnRemoved) then
PObject(@Value)^.DisposeOf;
end;
procedure TSetDataStorage<T>.SetOwnsValues(const Value: boolean);
begin
if Value and not TRttiUtils.IsInstance<T> then
raise Exception.Create('Generic type is not a class.');
FOwnsValues := Value;
end;
{ TSet<T> }
class operator TSet<T>.Add(a: TSet<T>; const b: TSet<T>): TSet<T>;
begin
result.CopyFrom(a);
result.Add(b);
end;
class operator TSet<T>.Add(a: TSet<T>; const b: TArray<T>): TSet<T>;
begin
result.CopyFrom(a);
result.Add(b);
end;
class operator TSet<T>.Add(a: TSet<T>; const b: TEnumerable<T>): TSet<T>;
begin
result.CopyFrom(a);
result.Add(b);
end;
class operator TSet<T>.Add(const a: TArray<T>; b: TSet<T>): TSet<T>;
begin
result.CopyFrom(b);
result.Add(a);
end;
class operator TSet<T>.Add(const a: TEnumerable<T>; b: TSet<T>): TSet<T>;
begin
result.CopyFrom(b);
result.Add(a);
end;
class operator TSet<T>.Add(const a: T; b: TSet<T>): TSet<T>;
begin
result.CopyFrom(b);
result.Add(a);
end;
procedure TSet<T>.Add(const AValues: TArray<T>);
var
I: Integer;
EmptyRec: TEmptyRec;
begin
for I := Low(AValues) to High(AValues) do
FData.AddOrSetValue(AValues[I], EmptyRec);
end;
procedure TSet<T>.Add(const AValues: TEnumerable<T>);
var
Value: T;
EmptyRec: TEmptyRec;
begin
for Value in AValues do
FData.AddOrSetValue(Value, EmptyRec);
end;
procedure TSet<T>.Add(const AValue: T);
var EmptyRec: TEmptyRec;
begin
FData.AddOrSetValue(AValue, EmptyRec);
end;
class operator TSet<T>.Add(a: TSet<T>; const b: T): TSet<T>;
begin
result.CopyFrom(a);
result.Add(b);
end;
procedure TSet<T>.Add(const AValues: TSet<T>);
var
Value: T;
EmptyRec: TEmptyRec;
begin
for Value in AValues do
FData.AddOrSetValue(Value, EmptyRec);
end;
procedure TSet<T>.Add(const AValues: array of T);
var
Value: T;
EmptyRec: TEmptyRec;
begin
for Value in AValues do
FData.AddOrSetValue(Value, EmptyRec);
end;
procedure TSet<T>.Clear;
begin
FData.Clear;
end;
function TSet<T>.Contains(const AValue: T): Boolean;
begin
result := FData.ContainsKey(AValue);
end;
function TSet<T>.Contains(const AValues: TEnumerable<T>): Boolean;
var
Value: T;
begin
for Value in AValues do
if not FData.ContainsKey(Value) then
Exit(False);
result := True;
end;
function TSet<T>.Contains(const AValues: TArray<T>): Boolean;
var
Value: T;
begin
for Value in AValues do
if not FData.ContainsKey(Value) then
Exit(False);
result := True;
end;
function TSet<T>.Contains(const AValues: TSet<T>): Boolean;
var
Value: T;
begin
for Value in AValues do
if not FData.ContainsKey(Value) then
Exit(False);
result := True;
end;
function TSet<T>.Copy: TSet<T>;
begin
result.CopyFrom(Self);
end;
procedure TSet<T>.CopyFrom(const Src: TSet<T>);
begin
Init(Src.Count*3 shr 1, Src.Comparer);
{ Doesn't make sense to copy when OwnsValues=True
(when item deleted in source, it became invalid) }
assert(not Src.OwnsValues or Src.Empty);
OwnsValues := Src.OwnsValues;
OnNotify := Src.OnNotify;
Add(Src);
end;
class function TSet<T>.Create(const AValues: TEnumerable<T>; const AComparer: IEqualityComparer<T>): TSet<T>;
begin
result.Init(AValues, AComparer);
end;
class function TSet<T>.Create(ACapacity: Integer; const AComparer: IEqualityComparer<T>): TSet<T>;
begin
result.Init(ACapacity, AComparer);
end;
class function TSet<T>.Create(const AValues: TArray<T>; const AComparer: IEqualityComparer<T>): TSet<T>;
begin
result.Init(AValues, AComparer);
end;
class function TSet<T>.Create(const AValues: array of T; const AComparer: IEqualityComparer<T>): TSet<T>;
begin
result.Init(AValues, AComparer);
end;
class function TSet<T>.Create: TSet<T>;
begin
result.Init;
end;
class operator TSet<T>.Equal(const a, b: TSet<T>): Boolean;
begin
result := (a.Count = b.Count) and a.Contains(b);
end;
class operator TSet<T>.Explicit(const a: TArray<T>): TSet<T>;
begin
result.Init;
result.Add(a);
end;
class operator TSet<T>.Explicit(const a: TEnumerable<T>): TSet<T>;
begin
result.Init;
result.Add(a);
end;
function TSet<T>.Extract(const Value: T): T;
begin
{ generates TData.KeyNotify(Valuie, cnExtracted), no need to set OwnsValues=False }
result := FData.ExtractPair(Value).Key;
end;
function TSet<T>.GetCollection: TEnumerable<T>;
begin
result := FData.Keys;
end;
function TSet<T>.GetComparer: IEqualityComparer<T>;
begin
result := FData.DataComparer;
end;
function TSet<T>.GetContainsValue(const AValue: T): boolean;
begin
result := FData.ContainsKey(AValue);
end;
function TSet<T>.GetCount: Integer;
begin
result := FData.Count;
end;
function TSet<T>.GetEmpty: Boolean;
begin
result := FData.Count = 0;
end;
function TSet<T>.GetEnumerator: TEnumerator;
begin
result := FData.Keys.GetEnumerator;
end;
function TSet<T>.GetOnNotify: TCollectionNotifyEvent<T>;
begin
result := FData.OnKeyNotify;
end;
function TSet<T>.GetOwnsValues: boolean;
begin
result := FData.OwnsValues;
end;
class operator TSet<T>.GreaterThan(const a, b: TSet<T>): Boolean;
begin
result := (a.Count > b.Count) and a.Contains(b);
end;
class operator TSet<T>.GreaterThanOrEqual(const a, b: TSet<T>): Boolean;
begin
result := a.Contains(b);
end;
class operator TSet<T>.GreaterThanOrEqual(const a: TSet<T>; const b: TArray<T>): Boolean;
begin
result := a.Contains(b);
end;
class operator TSet<T>.GreaterThanOrEqual(const a: TSet<T>; const b: TEnumerable<T>): Boolean;
begin
result := a.Contains(b);
end;
class operator TSet<T>.Implicit(const a: TEnumerable<T>): TSet<T>;
begin
result.Init;
result.Add(a);
end;
class operator TSet<T>.Implicit(const a: TArray<T>): TSet<T>;
begin
result.Init;
result.Add(a);
end;
class operator TSet<T>.In(const a: TSet<T>; b: TSet<T>): Boolean;
begin
result := b.Contains(a);
end;
class operator TSet<T>.In(const a: TArray<T>; b: TSet<T>): Boolean;
begin
result := b.Contains(a);
end;
class operator TSet<T>.In(const a: TEnumerable<T>; b: TSet<T>): Boolean;
begin
result := b.Contains(a);
end;
class operator TSet<T>.In(const a: T; b: TSet<T>): Boolean;
begin
result := b.Contains(a);
end;
procedure TSet<T>.Init(ACapacity: Integer; const AComparer: IEqualityComparer<T>);
begin
Self := Default(TSet<T>);
FData := TSetDataStorage<T>.Create(ACapacity, AComparer);
FDataIntf := TInterfacedObject<TObject>.Create(FData);
end;
procedure TSet<T>.Init;
begin
Init(0, nil);
end;
procedure TSet<T>.Init(const AValues: array of T; const AComparer: IEqualityComparer<T>);
begin
Init(Length(AValues)*3 shr 1, AComparer);
Add(AValues);
end;
procedure TSet<T>.Init(const AValues: TArray<T>; const AComparer: IEqualityComparer<T>);
begin
Init(Length(AValues)*3 shr 1, AComparer);
Add(AValues);
end;
procedure TSet<T>.Init(const AValues: TEnumerable<T>; const AComparer: IEqualityComparer<T>);
begin
Init(0, AComparer);
Add(AValues);
end;
class operator TSet<T>.LessThan(const a, b: TSet<T>): Boolean;
begin
result := not a.Contains(b);
end;
class operator TSet<T>.LessThan(const a: TSet<T>; const b: TArray<T>): Boolean;
begin
result := not a.Contains(b);
end;
class operator TSet<T>.LessThan(const a: TSet<T>; const b: TEnumerable<T>): Boolean;
begin
result := not a.Contains(b);
end;
class operator TSet<T>.LessThanOrEqual(const a, b: TSet<T>): Boolean;
begin
result := (a.Count <= b.Count) or not a.Contains(b); { not (A > B) }
end;
class operator TSet<T>.LogicalAnd(const a: TSet<T>; const b: TEnumerable<T>): TSet<T>;
var
Value: T;
begin
result.Init;
for Value in b do
if a.Contains(Value) then
result.Add(Value);
end;
class operator TSet<T>.LogicalAnd(const a, b: TSet<T>): TSet<T>;
var
Value: T;
begin
if a.Count > b.Count then
result := b and a
else
begin
result.Init;
for Value in a do
if b.Contains(Value) then
result.Add(Value);
end;
end;
class operator TSet<T>.LogicalAnd(const a: TSet<T>; const b: TArray<T>): TSet<T>;
var
Value: T;
begin
result.Init;
for Value in b do
if a.Contains(Value) then
result.Add(Value);
end;
class operator TSet<T>.LogicalOr(const a: TSet<T>; const b: TEnumerable<T>): TSet<T>;
begin
result.CopyFrom(a);
result.Add(b);
end;
class operator TSet<T>.LogicalOr(const a: TSet<T>; const b: TArray<T>): TSet<T>;
begin
result.CopyFrom(a);
result.Add(b);
end;
class operator TSet<T>.LogicalOr(const a, b: TSet<T>): TSet<T>;
begin
result.CopyFrom(a);
result.Add(b);
end;
class operator TSet<T>.LogicalXor(const a, b: TSet<T>): TSet<T>;
var
Value: T;
begin
result.Init;
for Value in A do
if not B.Contains(Value) then
result.Add(Value);
for Value in B do
if not A.Contains(Value) then
result.Add(Value);
end;
class operator TSet<T>.NotEqual(const a, b: TSet<T>): Boolean;
begin
result := (a.Count <> b.Count) or not a.Contains(b);
end;
procedure TSet<T>.Remove(const AValue: T);
begin
FData.Remove(AValue);
end;
procedure TSet<T>.Remove(const AValues: TSet<T>);
var
Value: T;
begin
for Value in AValues do
FData.Remove(Value);
end;
procedure TSet<T>.Remove(const AValues: TArray<T>);
var
Value: T;
begin
for Value in AValues do
FData.Remove(Value);
end;
procedure TSet<T>.Remove(const AValues: TEnumerable<T>);
var
Value: T;
begin
for Value in AValues do
FData.Remove(Value);
end;
procedure TSet<T>.SetContainsValue(const AValue: T; const AContains: boolean);
var
EmptyRec: TEmptyRec;
begin
if AContains
then FData.AddOrSetValue(AValue, EmptyRec)
else FData.Remove(AValue);
end;
procedure TSet<T>.SetOnNotify(const Value: TCollectionNotifyEvent<T>);
begin
FData.OnKeyNotify := Value;
end;
procedure TSet<T>.SetOwnsValues(const Value: boolean);
begin
FData.OwnsValues := Value;
end;
class operator TSet<T>.Subtract(const a: TArray<T>; b: TSet<T>): TSet<T>;
var
Value: T;
begin
result.Init;
for Value in a do
if not b.Contains(Value) then
result.Add(Value);
end;
class operator TSet<T>.Subtract(a: TSet<T>; const b: TArray<T>): TSet<T>;
begin
result.CopyFrom(a);
result.Remove(b);
end;
class operator TSet<T>.Subtract(a: TSet<T>; const b: TEnumerable<T>): TSet<T>;
begin
result.CopyFrom(a);
result.Remove(b);
end;
class operator TSet<T>.Subtract(a: TSet<T>; const b: T): TSet<T>;
begin
result.CopyFrom(a);
result.Remove(b);
end;
class operator TSet<T>.Subtract(const a: TEnumerable<T>; b: TSet<T>): TSet<T>;
var
Value: T;
begin
result.Init;
for Value in a do
if not b.Contains(Value) then
result.Add(Value);
end;
class operator TSet<T>.Subtract(const a: T; b: TSet<T>): TSet<T>;
begin
result.Init;
if not b.Contains(a) then
result.Add(a);
end;
class operator TSet<T>.Subtract(a: TSet<T>; const b: TSet<T>): TSet<T>;
begin
result.CopyFrom(a);
result.Remove(b);
end;
function TSet<T>.ToArray: TArray<T>;
begin
result := FData.Keys.ToArray;
end;
function TSet<T>.ToString: string;
begin
result := ToText(' ');
end;
function TSet<T>.ToText(const ValuesDelimiter: string): string;
var
Builder: TStringBuilder;
V: T;
N: Boolean;
Values: TArray<T>;
begin
Values := ToArray;
TArray.Sort<T>(Values);
Builder := TStringBuilder.Create;
try
N := False;
for V in Values do
begin
if N then
Builder.Append(ValuesDelimiter)
else
N := True;
Builder.Append(TRttiUtils.ValueAsString<T>(V));
end;
result := Builder.ToString;
finally
Builder.Free;
end;
end;
procedure TSet<T>.TrimExcess;
begin
FData.TrimExcess;
end;
{ TSetClass<T> }
procedure TSetClass<T>.Add(const AValues: TEnumerable<T>);
var
EmptyRec: TEmptyRec;
Value: T;
begin
for Value in AValues do
FData.AddOrSetValue(Value, EmptyRec);
end;
procedure TSetClass<T>.Add(const AValues: TArray<T>);
var
EmptyRec: TEmptyRec;
Value: T;
begin
for Value in AValues do
FData.AddOrSetValue(Value, EmptyRec);
end;
procedure TSetClass<T>.Add(const AValue: T);
var
EmptyRec: TEmptyRec;
begin
FData.AddOrSetValue(AValue, EmptyRec);
end;
procedure TSetClass<T>.Clear;
begin
FData.Clear;
end;
function TSetClass<T>.Contains(const AValues: TArray<T>): boolean;
var
Value: T;
begin
for Value in AValues do
if not FData.ContainsKey(Value) then
Exit(False);
result := True;
end;
function TSetClass<T>.Contains(const AValues: TEnumerable<T>): boolean;
var
Value: T;
begin
for Value in AValues do
if not FData.ContainsKey(Value) then
Exit(False);
result := True;
end;
function TSetClass<T>.Contains(const AValue: T): boolean;
begin
result := FData.ContainsKey(AValue);
end;
constructor TSetClass<T>.Create(ACapacity: integer; AComparer: IEqualityComparer<T>);
begin
FData := TSetDataStorage<T>.Create(ACapacity, AComparer);
end;
constructor TSetClass<T>.Create(const AValues: TEnumerable<T>; AComparer: IEqualityComparer<T>);
begin
FData := TSetDataStorage<T>.Create(0, AComparer);
Add(AValues);
end;
constructor TSetClass<T>.Create(const AValues: TArray<T>; AComparer: IEqualityComparer<T>);
begin
FData := TSetDataStorage<T>.Create(Length(AValues)*3 shr 1, AComparer);
Add(AValues);
end;
destructor TSetClass<T>.Destroy;
begin
FreeAndNil(FData);
inherited;
end;
function TSetClass<T>.DoGetEnumerator: TEnumerator<T>;
begin
result := FData.Keys.GetEnumerator;
end;
function TSetClass<T>.GetComparer: IEqualityComparer<T>;
begin
result := FData.DataComparer;
end;
function TSetClass<T>.GetContainsValue(const AValue: T): boolean;
begin
result := FData.ContainsKey(AValue);
end;
function TSetClass<T>.GetCount: integer;
begin
result := FData.Count;
end;
function TSetClass<T>.GetEmpty: Boolean;
begin
result := FData.Count = 0;
end;
function TSetClass<T>.GetOnNotify: TCollectionNotifyEvent<T>;
begin
result := FData.OnKeyNotify;
end;
function TSetClass<T>.GetOwnsValues: boolean;
begin
result := FData.OwnsValues;
end;
procedure TSetClass<T>.Remove(const AValues: TArray<T>);
var
Value: T;
begin
for Value in AValues do
FData.Remove(Value);
end;
procedure TSetClass<T>.Remove(const AValue: T);
begin
FData.Remove(AValue);
end;
procedure TSetClass<T>.Remove(const AValues: TEnumerable<T>);
var
Value: T;
begin
for Value in AValues do
FData.Remove(Value);
end;
procedure TSetClass<T>.SetContainsValue(const AValue: T; const AContains: boolean);
var
EmptyRec: TEmptyRec;
begin
if AContains
then FData.AddOrSetValue(AValue, EmptyRec)
else FData.Remove(AValue);
end;
procedure TSetClass<T>.SetOnNotify(const Value: TCollectionNotifyEvent<T>);
begin
FData.OnKeyNotify := Value;
end;
procedure TSetClass<T>.SetOwnsValues(AOwnsValues: boolean);
begin
FData.OwnsValues := AOwnsValues;
end;
function TSetClass<T>.ToArray: TArray<T>;
begin
result := FData.Keys.ToArray;
end;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,WinInet, StdCtrls,Registry,ShellAPI;
type
TForm1 = class(TForm)
Button1: TButton;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
type
TRasConn = record
Size: DWORD;
Handle: THandle;
Name: array[0..20] of AnsiChar;
end;
TRasEnumConnections = function(var RasConn: TRasConn; var Size: DWORD;
var Connections: DWORD): DWORD stdcall;
TRasHangUp = function(Handle: THandle): DWORD stdcall;
var
Form1: TForm1;
l:TStringList;
implementation
{$R *.dfm}
function DisconnectDialUp: Boolean;
var
Lib: HINST;
RasEnumConnections: TRasEnumConnections;
RasHangUp: TRasHangUp;
RasConn: TRasConn;
Code, Size, Connections: DWORD;
begin
Result := True;
try
Lib := LoadLibrary('rasapi32.dll');
try
if Lib = 0 then
Abort;
RasEnumConnections := GetProcAddress(Lib, 'RasEnumConnectionsA');
if not Assigned(@RasEnumConnections) then
Abort;
RasHangUp := GetProcAddress(Lib, 'RasHangUpA');
if not Assigned(@RasHangUp) then
Abort;
FillChar(RasConn, SizeOf(RasConn), 0);
RasConn.Size := SizeOf(RasConn);
Code := RasEnumConnections(RasConn, Size, Connections);
if (Connections <> 1) or (Code <> 0) then
Abort;
if RasHangUp(RasConn.Handle) <> 0 then
Abort;
Sleep(3000);
finally
FreeLibrary(Lib);
end;
except
on E: EAbort do
Result := False;
else
raise;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
if DisconnectDialUp = true then
ShowMessage('Соединение разорвано')
else
ShowMessage('Не удалось разорвать соединение');
end;
end.
|
////////////////////////////////////////////////////////////////////////////////////
//
//
// FileName : SUIImagePanel.pas
// Creater : Shen Min
// Date : 2001-10-15
// Comment :
//
// Copyright (c) 2002-2003 Sunisoft
// http://www.sunisoft.com
// Email: support@sunisoft.com
//
////////////////////////////////////////////////////////////////////////////////////
unit SUIImagePanel;
interface
{$I SUIPack.inc}
uses Windows, Extctrls, Graphics, Classes, Messages, Controls, SysUtils, Forms,
SUIPublic, SUIThemes, SUIMgr;
type
TsuiPanel = class(TCustomPanel)
private
m_BorderColor : TColor;
m_UIStyle : TsuiUIStyle;
m_FileTheme : TsuiFileTheme;
m_TitleBitmap : TBitmap;
m_ShowButton : Boolean;
m_InButton : Boolean;
m_Poped : Boolean;
m_OnPush : TNotifyEvent;
m_OnPop : TNotifyEvent;
m_Height : Integer;
m_Moving : Boolean;
m_FromTheme : Boolean;
m_CaptionFontColor : TColor;
procedure WMERASEBKGND(var Msg : TMessage); message WM_ERASEBKGND;
procedure SetBorderColor(const Value: TColor);
procedure SetFileTheme(const Value: TsuiFileTheme);
procedure SetUIStyle(const Value: TsuiUIStyle);
procedure SetShowButton(const Value: Boolean);
procedure SetHeight2(const Value: Integer);
procedure SetCaptionFontColor(const Value: TColor);
function GetPushed: Boolean;
procedure PaintButton();
protected
procedure Paint(); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure AlignControls(AControl: TControl; var Rect: TRect); override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure Resize(); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
procedure Pop();
procedure Push();
property Pushed : Boolean read GetPushed;
published
property FileTheme : TsuiFileTheme read m_FileTheme write SetFileTheme;
property UIStyle : TsuiUIStyle read m_UIStyle write SetUIStyle;
property BorderColor : TColor read m_BorderColor write SetBorderColor;
property Font;
property Caption;
property ShowButton : Boolean read m_ShowButton write SetShowButton;
property Height : Integer read m_Height write SetHeight2;
property CaptionFontColor : TColor read m_CaptionFontColor write SetCaptionFontColor;
property BiDiMode;
property Anchors;
property Align;
property TabStop;
property TabOrder;
property Color;
property Visible;
property PopupMenu;
property OnPush : TNotifyEvent read m_OnPush write m_OnPush;
property OnPop : TNotifyEvent read m_OnPop write m_OnPop;
property OnCanResize;
property OnClick;
property OnConstrainedResize;
property OnDockDrop;
property OnDockOver;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnGetSiteInfo;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnResize;
property OnStartDock;
property OnStartDrag;
property OnUnDock;
end;
TsuiDrawStyle = (suiNormal, suiStretch, suiTile);
TsuiCustomPanel = class(TCustomPanel)
private
m_Picture : TPicture;
m_Transparent : Boolean;
m_AutoSize : Boolean;
m_CaptionPosX: Integer;
m_CaptionPosY: Integer;
m_DrawStyle : TsuiDrawStyle;
m_LastDrawCaptionRect : TRect;
procedure ApplyAutoSize();
procedure ApplyTransparent();
procedure SetPicture(const Value: TPicture);
procedure SetAutoSize(const Value: Boolean); reintroduce;
procedure SetCaptionPosX(const Value: Integer);
procedure SetCaptionPosY(const Value: Integer);
procedure SetDrawStyle(const Value: TsuiDrawStyle);
procedure CMTEXTCHANGED(var Msg : TMessage); message CM_TEXTCHANGED;
procedure WMERASEBKGND(var Msg : TMessage); message WM_ERASEBKGND;
protected
procedure Paint(); override;
procedure ClearPanel(); virtual;
procedure RepaintText(Rect : TRect); virtual;
procedure PictureChanged(Sender: TObject); virtual;
procedure SetTransparent(const Value: Boolean); virtual;
procedure Resize(); override;
property Picture : TPicture read m_Picture write SetPicture;
property Transparent : Boolean Read m_Transparent Write SetTransparent default false;
property AutoSize : Boolean Read m_AutoSize Write SetAutoSize;
property CaptionPosX : Integer read m_CaptionPosX write SetCaptionPosX;
property CaptionPosY : Integer read m_CaptionPosY write SetCaptionPosY;
property DrawStyle : TsuiDrawStyle read m_DrawStyle write SetDrawStyle;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
end;
TsuiImagePanel = class(TsuiCustomPanel)
published
property BiDiMode;
property BorderWidth;
property Anchors;
property Picture;
property Transparent;
property AutoSize;
property Alignment;
property Align;
property Font;
property TabStop;
property TabOrder;
property Caption;
property Color;
property DrawStyle;
property Visible;
property PopupMenu;
property OnCanResize;
property OnClick;
property OnConstrainedResize;
property OnDockDrop;
property OnDockOver;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnGetSiteInfo;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnResize;
property OnStartDock;
property OnStartDrag;
property OnUnDock;
end;
implementation
{ TsuiCustomPanel }
procedure TsuiCustomPanel.ApplyAutoSize;
begin
if m_AutoSize then
begin
if (
(Align <> alTop) and
(Align <> alBottom) and
(Align <> alClient)
) then
Width := m_Picture.Width;
if (
(Align <> alLeft) and
(Align <> alRight) and
(Align <> alClient)
) then
Height := m_Picture.Height;
end;
end;
procedure TsuiCustomPanel.ApplyTransparent;
begin
if m_Picture.Graphic.Transparent <> m_Transparent then
m_Picture.Graphic.Transparent := m_Transparent;
end;
procedure TsuiCustomPanel.ClearPanel;
begin
Canvas.Brush.Color := Color;
if ParentWindow <> 0 then
Canvas.FillRect(ClientRect);
end;
procedure TsuiCustomPanel.CMTEXTCHANGED(var Msg: TMessage);
begin
RepaintText(m_LastDrawCaptionRect);
Repaint();
end;
constructor TsuiCustomPanel.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
m_Picture := TPicture.Create();
ASSERT(m_Picture <> nil);
m_Picture.OnChange := PictureChanged;
m_CaptionPosX := -1;
m_CaptionPosY := -1;
BevelInner := bvNone;
BevelOuter := bvNone;
Repaint();
end;
destructor TsuiCustomPanel.Destroy;
begin
if m_Picture <> nil then
begin
m_Picture.Free();
m_Picture := nil;
end;
inherited;
end;
procedure TsuiCustomPanel.Paint;
var
uDrawTextFlag : Cardinal;
Rect : TRect;
Buf : TBitmap;
begin
Buf := TBitmap.Create();
Buf.Height := Height;
Buf.Width := Width;
if m_Transparent then
DoTrans(Buf.Canvas, self);
if Assigned(m_Picture.Graphic) then
begin
if m_DrawStyle = suiStretch then
Buf.Canvas.StretchDraw(ClientRect, m_Picture.Graphic)
else if m_DrawStyle = suiTile then
TileDraw(Buf.Canvas, m_Picture, ClientRect)
else
Buf.Canvas.Draw(0, 0, m_Picture.Graphic);
end
else if not m_Transparent then
begin
Buf.Canvas.Brush.Color := Color;
Buf.Canvas.FillRect(ClientRect);
end;
Buf.Canvas.Brush.Style := bsClear;
if Trim(Caption) <> '' then
begin
Buf.Canvas.Font := Font;
if (m_CaptionPosX <> -1) and (m_CaptionPosY <> -1) then
begin
Buf.Canvas.TextOut(m_CaptionPosX, m_CaptionPosY, Caption);
m_LastDrawCaptionRect := Classes.Rect(
m_CaptionPosX,
m_CaptionPosY,
m_CaptionPosX + Buf.Canvas.TextWidth(Caption),
m_CaptionPosY + Buf.Canvas.TextWidth(Caption)
);
end
else
begin
Rect := ClientRect;
uDrawTextFlag := DT_CENTER;
if Alignment = taRightJustify then
uDrawTextFlag := DT_RIGHT
else if Alignment = taLeftJustify then
uDrawTextFlag := DT_LEFT;
DrawText(Buf.Canvas.Handle, PChar(Caption), -1, Rect, uDrawTextFlag or DT_SINGLELINE or DT_VCENTER);
m_LastDrawCaptionRect := Rect;
end;
end;
BitBlt(Canvas.Handle, 0, 0, Width, Height, Buf.Canvas.Handle, 0, 0, SRCCOPY);
Buf.Free();
end;
procedure TsuiCustomPanel.PictureChanged(Sender: TObject);
begin
if m_Picture.Graphic <> nil then
begin
if m_AutoSize then
ApplyAutoSize();
ApplyTransparent();
end;
ClearPanel();
RePaint();
end;
procedure TsuiCustomPanel.RepaintText(Rect: TRect);
begin
// not implete
end;
procedure TsuiCustomPanel.Resize;
begin
inherited;
Repaint();
end;
procedure TsuiCustomPanel.SetAutoSize(const Value: Boolean);
begin
m_AutoSize := Value;
if m_Picture.Graphic <> nil then
ApplyAutoSize();
end;
procedure TsuiCustomPanel.SetCaptionPosX(const Value: Integer);
begin
m_CaptionPosX := Value;
RePaint();
end;
procedure TsuiCustomPanel.SetCaptionPosY(const Value: Integer);
begin
m_CaptionPosY := Value;
RePaint();
end;
procedure TsuiCustomPanel.SetDrawStyle(const Value: TsuiDrawStyle);
begin
m_DrawStyle := Value;
ClearPanel();
Repaint();
end;
procedure TsuiCustomPanel.SetPicture(const Value: TPicture);
begin
m_Picture.Assign(Value);
ClearPanel();
Repaint();
end;
procedure TsuiCustomPanel.SetTransparent(const Value: Boolean);
begin
m_Transparent := Value;
if m_Picture.Graphic <> nil then
ApplyTransparent();
Repaint();
end;
procedure TsuiCustomPanel.WMERASEBKGND(var Msg: TMessage);
begin
// do nothing;
end;
{ TsuiPanel }
procedure TsuiPanel.AlignControls(AControl: TControl; var Rect: TRect);
begin
Rect.Left := Rect.Left + 3;
Rect.Right := Rect.Right - 3;
Rect.Bottom := Rect.Bottom - 3;
Rect.Top := m_TitleBitmap.Height + 3;
inherited AlignControls(AControl, Rect);
end;
constructor TsuiPanel.Create(AOwner: TComponent);
begin
inherited;
m_TitleBitmap := TBitmap.Create();
m_ShowButton := true;
m_InButton := false;
m_Poped := true;
m_Moving := false;
Width := 100;
Height := 100;
m_FromTheme := false;
UIStyle := GetSUIFormStyle(AOwner);
end;
destructor TsuiPanel.Destroy;
begin
m_TitleBitmap.Free();
inherited;
end;
function TsuiPanel.GetPushed: Boolean;
begin
Result := not m_Poped;
end;
procedure TsuiPanel.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
inherited;
if (m_ShowButton) and (Y <= m_TitleBitmap.Height) then
PaintButton();
end;
procedure TsuiPanel.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
begin
inherited;
if Button <> mbLeft then
Exit;
if m_InButton then
begin
if m_Poped then
Push()
else
Pop();
end;
Repaint();
end;
procedure TsuiPanel.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (
(Operation = opRemove) and
(AComponent = m_FileTheme)
)then
begin
m_FileTheme := nil;
ContainerApplyUIStyle(self, SUI_THEME_DEFAULT, nil);
SetUIStyle(SUI_THEME_DEFAULT);
end;
end;
procedure TsuiPanel.Paint;
var
Buf : TBitmap;
R : TRect;
Btn : TBitmap;
MousePoint : TPoint;
Index : Integer;
begin
Buf := TBitmap.Create();
Buf.Width := inherited Width;
Buf.Height := Height;
Buf.Canvas.Brush.Color := Color;
Buf.Canvas.Pen.Color := m_BorderColor;
Buf.Canvas.Rectangle(ClientRect);
R := Rect(1, 0, inherited Width - 1, m_TitleBitmap.Height);
Buf.Canvas.StretchDraw(R, m_TitleBitmap);
Buf.Canvas.Brush.Style := bsClear;
Buf.Canvas.Font.Assign(Font);
Buf.Canvas.Font.Color := m_CaptionFontColor;
if (BidiMode = bdRightToLeft) and SysLocale.MiddleEast then
begin
Dec(R.Right, 10);
if m_ShowButton and (Align <> alClient) and (Align <> alLeft) and (Align <> alRight) then
Dec(R.Right, 10);
DrawText(Buf.Canvas.Handle, PChar(Caption), -1, R, DT_VCENTER or DT_SINGLELINE or DT_RIGHT);
R.Right := inherited Width - 1;
end
else
begin
R.Left := 10;
DrawText(Buf.Canvas.Handle, PChar(Caption), -1, R, DT_VCENTER or DT_SINGLELINE or DT_LEFT);
end;
if m_ShowButton and (Align <> alClient) and (Align <> alLeft) and (Align <> alRight) then
begin
Btn := TBitmap.Create();
Btn.LoadFromResourceName(hInstance, 'PANEL_BUTTON');
R.Left := R.Right - Btn.Width div 4 - 4;
R.Top := (R.Bottom - Btn.Height) div 2;
R.Bottom := R.Top + Btn.Height;
R.Right := R.Left + Btn.Width div 4;
GetCursorPos(MousePoint);
MousePoint := ScreenToClient(MousePoint);
if InRect(MousePoint, R) then
begin
if m_Poped then
Index := 2
else
Index := 4;
m_InButton := true;
end
else
begin
if m_Poped then
Index := 1
else
Index := 3;
m_InButton := false;
end;
SpitBitmap(Btn, Btn, 4, Index);
Buf.Canvas.Draw(Width - Btn.Width - 4, (R.Bottom - Btn.Height) div 2 + 2, Btn);
Btn.Free();
end;
BitBlt(Canvas.Handle, 0, 0, Width, Height, Buf.Canvas.Handle, 0, 0, SRCCOPY);
Buf.Free();
end;
procedure TsuiPanel.PaintButton;
var
Btn : TBitmap;
R : TRect;
MousePoint : TPoint;
Index : Integer;
begin
R := Rect(1, 0, inherited Width - 1, m_TitleBitmap.Height);
if m_ShowButton and (Align <> alClient) and (Align <> alLeft) and (Align <> alRight) then
begin
Btn := TBitmap.Create();
Btn.LoadFromResourceName(hInstance, 'PANEL_BUTTON');
R.Left := R.Right - Btn.Width div 4 - 4;
R.Top := (R.Bottom - Btn.Height) div 2;
R.Bottom := R.Top + Btn.Height;
R.Right := R.Left + Btn.Width div 4;
GetCursorPos(MousePoint);
MousePoint := ScreenToClient(MousePoint);
if InRect(MousePoint, R) then
begin
if m_Poped then
Index := 2
else
Index := 4;
m_InButton := true;
end
else
begin
if m_Poped then
Index := 1
else
Index := 3;
m_InButton := false;
end;
SpitBitmap(Btn, Btn, 4, Index);
Canvas.Draw(Width - Btn.Width - 4, (R.Bottom - Btn.Height) div 2 + 2, Btn);
Btn.Free();
end;
end;
procedure TsuiPanel.Pop;
begin
m_Moving := true;
while inherited Height + 15 < m_Height do
begin
inherited Height := inherited Height + 15;
Refresh();
Application.ProcessMessages();
end;
inherited Height := m_Height;
Refresh();
m_Moving := false;
m_Poped := true;
Repaint();
if Assigned (m_OnPop) then
m_OnPop(self);
end;
procedure TsuiPanel.Push;
var
InnerHeight : Integer;
begin
if (Align = alClient) or (Align = alLeft) or (Align = alRight) then
raise Exception.Create('Can''t push when Align is alClient, alLeft or alRight.');
InnerHeight := m_TitleBitmap.Height;
if InnerHeight = 0 then
InnerHeight := 20;
m_Moving := true;
while inherited Height - 15 > InnerHeight do
begin
inherited Height := inherited Height - 15;
Refresh();
Application.ProcessMessages();
end;
inherited Height := InnerHeight;
Refresh();
m_Moving := false;
m_Poped := false;
Repaint();
if Assigned(m_OnPush) then
m_OnPush(self);
end;
procedure TsuiPanel.Resize;
begin
inherited;
if (not m_Moving) and m_Poped then
begin
m_Height := inherited Height;
end;
end;
procedure TsuiPanel.SetBorderColor(const Value: TColor);
begin
m_BorderColor := Value;
Repaint();
end;
procedure TsuiPanel.SetCaptionFontColor(const Value: TColor);
begin
m_CaptionFontColor := Value;
Repaint();
end;
procedure TsuiPanel.SetFileTheme(const Value: TsuiFileTheme);
begin
m_FileTheme := Value;
m_FromTheme := true;
SetUIStyle(m_UIStyle);
m_FromTheme := false;
end;
procedure TsuiPanel.SetHeight2(const Value: Integer);
begin
m_Height := Value;
if (csDesigning in ComponentState) or m_Poped then
inherited Height := m_Height;
end;
procedure TsuiPanel.SetShowButton(const Value: Boolean);
begin
m_ShowButton := Value;
Repaint();
end;
procedure TsuiPanel.SetUIStyle(const Value: TsuiUIStyle);
var
OutUIStyle : TsuiUIStyle;
begin
m_UIStyle := Value;
if m_FromTheme and (m_UIStyle <> FromThemeFile) then
Exit;
Color := clWhite;
if UsingFileTheme(m_FileTheme, m_UIStyle, OutUIStyle) then
begin
m_FileTheme.GetBitmap(SUI_THEME_SIDECHENNEL_BAR_IMAGE, m_TitleBitmap);
m_BorderColor := m_FileTheme.GetColor(SUI_THEME_CONTROL_BORDER_COLOR);
m_CaptionFontColor := m_FileTheme.GetColor(SUI_THEME_CONTROL_FONT_COLOR);
if (
(m_CaptionFontColor = 131072) or
(m_CaptionFontColor = 262144) or
(m_CaptionFontColor = 196608) or
(m_CaptionFontColor = 327680) or
(m_CaptionFontColor = 8016662) or
(m_CaptionFontColor = 2253583)
) then
m_CaptionFontColor := clBlack
else
m_CaptionFontColor := clWhite;
end
else
begin
GetInsideThemeBitmap(OutUIStyle, SUI_THEME_SIDECHENNEL_BAR_IMAGE, m_TitleBitmap);
m_BorderColor := GetInsideThemeColor(OutUIStyle, SUI_THEME_CONTROL_BORDER_COLOR);
{$IFDEF RES_MACOS}
if OutUIStyle = MacOS then
m_CaptionFontColor := clBlack
else
{$ENDIF}
m_CaptionFontColor := GetInsideThemeColor(OutUIStyle, SUI_THEME_MENU_SELECTED_FONT_COLOR);
end;
Height := Height - 1;
Height := Height + 1;
Repaint();
end;
procedure TsuiPanel.WMERASEBKGND(var Msg: TMessage);
begin
// do nothing
end;
end.
|
unit ArticleLocDAOU;
interface
uses
ArticleLocDTOU, APIUtilsU, FireDAC.UI.Intf, FireDAC.FMXUI.Wait,
FireDAC.Stan.Intf, FireDAC.Comp.UI, FireDAC.Stan.ExprFuncs,
FireDAC.Phys.SQLiteDef, FireDAC.Phys, FireDAC.Phys.SQLite,
FireDAC.Comp.Client, IOUtils, System.Generics.Collections, BarCodeLocDTOU;
type TListArticleLocDTO=TObjectList<TArticleLocDTO>;
type TArticleLocDAO=class(TObject)
FArticleLocDTO:TArticleLocDTO;
private
function getDataFromWeb:TListArticleLocDTO;
public
constructor create(oArticleLocDTO:TArticleLocDTO);overload;
constructor create;overload;
function save(varticleLocDTO:TArticleLocDTO):integer;
function isExist(varticleLocDTO:TArticleLocDTO):boolean;
function delete(varticleLocDTO:TArticleLocDTO):integer;
function getNbrArticle:integer;
function getNbrLike(str:string):integer;
function getListArticleLocs:TListArticleLocDTO;
function getListByText(textLike:string):TListArticleLocDTO;
function getMaxIdArticle: string;
procedure loadData(var varticleLocDTO: TarticleLocDTO);
procedure importDataFromWebToLocal;
procedure deleteAll;
{sadaoui :ajouter prix de carton}
function Prixcarton(varticleLocDTO:TArticleLocDTO):double;
{fin sadaoui}
{sadaoui :ajouter prix de carton}
function getFirstBarCodeLocDTO(vArticlelocDTO:TArticleLocDTO): TBarCodeLocDTO;
{fin sadaoui}
end;
implementation
uses
System.SysUtils, FMX.Dialogs, UConnection, MainU, ArticleWebDAOU,
ArticleWebDTOU, BarCodeLocDAOU;
{ ArticleLocDAO }
constructor TArticleLocDAO.create(oArticleLocDTO: TArticleLocDTO);
begin
Self.FArticleLocDTO:=oArticleLocDTO;
end;
constructor TArticleLocDAO.create;
begin
end;
function TArticleLocDAO.delete(varticleLocDTO:TArticleLocDTO): integer;
begin
with TFdQuery.Create(nil) do
begin
try
if isExist(varticleLocDTO) then
begin
Connection:=Main.oconnection;
SQL.Add('delete from tarticleloc ');
SQL.Add(' where idArticleloc='+QuotedStr(varticleLocDTO.idarticleloc));
ExecSQL;
end;
finally
DisposeOf;
end;
end;
end;
function TArticleLocDAO.getListArticleLocs:TListArticleLocDTO;
var varticleLocDTO:TArticleLocDTO;
i:integer;
begin
result:=TListArticleLocDTO.Create();
with TFDQuery.Create(nil) do
begin
i:=0;
Connection:=Main.oconnection;
SQL.Add('select * from tarticleloc');
Active:=true;
First;
while not Eof do
begin
varticleLocDTO:=TArticleLocDTO.create(FieldByName('idarticleloc').AsString);
varticleLocDTO.idarticleloc:=FieldByName('idarticleloc').AsString;
varticleLocDTO.desarticleloc:=FieldByName('desarticleloc').AsString;
varticleLocDTO.lastprixachat:=FieldByName('lastprixachat').AsFloat;
varticleLocDTO.prixvente:=FieldByName('prixvente').AsFloat;
varticleLocDTO.uart:=FieldByName('uart').AsString;
varticleLocDTO.lastqteachat:=FieldByName('lastqteachat').AsFloat;
varticleLocDTO.qtestock:=FieldByName('qtestock').AsFloat;
result.Add(varticleLocDTO);
Next;
Inc(i);
end;
end;
end;
function TArticleLocDAO.getListByText(textLike: string): TListArticleLocDTO;
var
ArtList:TListArticleLocDTO;
OArt:TArticleLocDTO;
i:Integer;
vNbrLike:integer;
varticleLocDTO:TArticleLocDTO;
begin
if textLike<>'' then
begin
result:=TListArticleLocDTO.Create();
with TFDQuery.Create(nil) do
begin
i:=0;
Connection:=Main.oconnection;
SQL.Add('select * from tarticleloc where desarticleloc like '+QuotedStr('%'+textLike+'%'));
Active:=true;
First;
while not Eof do
begin
varticleLocDTO:=TArticleLocDTO.create(FieldByName('idarticleloc').AsString);
varticleLocDTO.idarticleloc:=FieldByName('idarticleloc').AsString;
varticleLocDTO.desarticleloc:=FieldByName('desarticleloc').AsString;
varticleLocDTO.lastprixachat:=FieldByName('lastprixachat').AsFloat;
varticleLocDTO.prixvente:=FieldByName('prixvente').AsFloat;
varticleLocDTO.uart:=FieldByName('uart').AsString;
varticleLocDTO.lastqteachat:=FieldByName('lastqteachat').AsFloat;
varticleLocDTO.qtestock:=FieldByName('qtestock').AsFloat;
result.Add(varticleLocDTO);
Next;
Inc(i);
end;
end;
end;
end;
function TArticleLocDAO.getNbrArticle: integer;
begin
with TFdQuery.Create(nil) do
begin
try
Connection:=Main.oconnection;
SQL.Add('select count(*) as nbr from tarticleloc ');
Active:=true;
result:=FieldByName('nbr').AsInteger;
Active:=false;
finally
Active:=false;
DisposeOf;
end;
end;
end;
function TArticleLocDAO.getDataFromWeb:TListArticleLocDTO;
var oListArticleLocDTO:TListArticleLocDTO;
oArticleWebDAO:TArticleWebDAO;
oArticleWebDTO:TArticleWebDTO;
oArticleLocDTO:TArticleLocDTO;
oListArticleWebDTO:TListArticleWebDTO;
begin
oArticleWebDAO:=TArticleWebDAO.create();
oListArticleLocDTO:=TListArticleLocDTO.Create;
oListArticleWebDTO:=oArticleWebDAO.getArticles;
for oArticleWebDTO in oListArticleWebDTO do
begin
oArticleLocDTO:=TArticleLocDTO.create;
oArticleLocDTO.idarticleloc:=oArticleWebDTO.idarticle;
oArticleLocDTO.desarticleloc:=oArticleWebDTO.desarticle;
oArticleLocDTO.lastprixachat:=oArticleWebDTO.lastprixachat;
oArticleLocDTO.prixvente:=oArticleWebDTO.prixvente;
oArticleLocDTO.lastqteachat:=oArticleWebDTO.lastqteachat;
oArticleLocDTO.qtestock:=oArticleWebDTO.qtestock;
oArticleLocDTO.uart:=oArticleWebDTO.uart;
oListArticleLocDTO.Add(oArticleLocDTO);
// oArticleLocDTO.DisposeOf;
end;
Result:=oListArticleLocDTO;
end;
function TArticleLocDAO.getFirstBarCodeLocDTO(
vArticlelocDTO: TArticleLocDTO): TBarCodeLocDTO;
var obarcodeLocDTO:TBarCodeLocDTO;
begin
with TFdQuery.Create(nil) do
begin
try
Connection:=Main.oconnection;
SQL.Add('select * from tbarcodeloc where idarticleloc='+
QuotedStr(varticleLocDTO.idarticleloc));
Active:=true;
obarcodeLocDTO:=TBarCodeLocDTO.create;
obarcodeLocDTO.idarticleloc:=FieldByName('idarticleloc').AsString;
obarcodeLocDTO.idbarcodeloc:=FieldByName('idbarcodeloc').AsString;
//ShowMessage(obarcodeLocDTO.idbarcodeloc);
Result:=obarcodeLocDTO;
Active:=false;
finally
Active:=false;
DisposeOf;
end;
end;
end;
procedure TArticleLocDAO.deleteAll;
begin
with TFdQuery.Create(nil) do
begin
try
Connection:=Main.oconnection;
SQL.Add('delete from tarticleloc ');
ExecSQL;
finally
DisposeOf;
end;
end;
end;
procedure TArticleLocDAO.importDataFromWebToLocal;
var oListArticleLocDTO:TListArticleLocDTO;
oLisTArticleWebDTO:TLisTArticleWebDTO;
oArticleLocDAO:TArticleWebDAO;
oArticleWebDAO:TArticleWebDAO;
oArticleLocDTO:TArticleLocDTO;
i:integer;
begin
oListArticleLocDTO:=Self.getDataFromWeb;
i:=0;
Self.deleteAll;
for oArticleLocDTO in oListArticleLocDTO do
begin
inc(i);
Self.save(oArticleLocDTO);
end;
ShowMessage('transfert terminé');
end;
function TArticleLocDAO.isExist(varticleLocDTO:TArticleLocDTO):boolean;
begin
with TFdQuery.Create(nil) do
begin
result:=false;
try
Connection:=Main.oconnection;
SQL.Add('select count(*) from tarticleloc where idarticleloc='+
QuotedStr(varticleLocDTO.idarticleloc));
Active:=true;
result:=Fields[0].AsInteger>0;
Active:=false;
finally
Active:=false;
DisposeOf;
end;
end;
end;
function TArticleLocDAO.save(varticleLocDTO:TArticleLocDTO):integer;
begin
with TFdQuery.Create(nil) do
begin
try
if not isExist(varticleLocDTO) then
begin
Connection:=Main.oconnection;
SQL.Add('insert into tarticleloc (idArticleloc,desArticleloc,LastPrixAchat,PrixVente,');
SQL.Add('UArt,LastQteAchat) values (');
SQL.Add(QuotedStr(varticleLocDTO.idarticleloc)+',');
SQL.Add(QuotedStr(varticleLocDTO.desarticleloc)+',');
SQL.Add(QuotedStr(floattostr(varticleLocDTO.lastprixachat))+',');
SQL.Add(QuotedStr(floattostr(varticleLocDTO.prixvente))+',');
SQL.Add(QuotedStr(varticleLocDTO.uart)+',');
SQL.Add(QuotedStr(floattostr(varticleLocDTO.lastqteachat))+')');
ExecSQL;
end else
begin
Connection:=Main.oconnection;
SQL.Add('update tarticleloc set ');
SQL.Add('desArticleloc='+QuotedStr(varticleLocDTO.desArticleloc)+',');
SQL.Add('LastPrixAchat='+QuotedStr(floattostr(varticleLocDTO.LastPrixAchat))+',');
SQL.Add('PrixVente='+QuotedStr(floattostr(varticleLocDTO.PrixVente))+',');
SQL.Add('UArt='+QuotedStr(varticleLocDTO.UArt)+',');
SQL.Add('LastQteAchat='+QuotedStr(floattostr(varticleLocDTO.LastQteAchat)));
SQL.Add(' where idArticleloc='+QuotedStr(varticleLocDTO.idarticleloc));
ExecSQL;
end;
finally
DisposeOf;
end;
end;
end;
function TArticleLocDAO.getNbrLike(str:String): integer;
begin
with TFdQuery.Create(nil) do
begin
try
Connection:=Main.oconnection;
SQL.Add('select count(*) from tarticleloc where desarticleloc like '+QuotedStr('%'+str+'%'));
Active:=true;
result:=Fields[0].AsInteger;
Active:=false;
finally
Active:=false;
DisposeOf;
end;
end;
end;
procedure TArticleLocDAO.loadData(var varticleLocDTO: TarticleLocDTO);
begin
with TFdQuery.Create(nil) do
begin
try
Connection:=Main.oconnection;
SQL.Add('select * from tarticleloc where idarticleloc='+
QuotedStr(varticleLocDTO.idarticleloc));
Active:=true;
varticleLocDTO.desarticleloc:=FieldByName('desarticleloc').AsString;
varticleLocDTO.lastprixachat:=FieldByName('lastprixachat').AsFloat;
varticleLocDTO.prixvente:=FieldByName('prixvente').AsFloat;
varticleLocDTO.uart:=FieldByName('uart').AsString;
varticleLocDTO.qtestock:=FieldByName('qtestock').AsFloat;
varticleLocDTO.lastqteachat:=FieldByName('lastqteachat').AsFloat;
finally
Active:=false;
DisposeOf;
end;
end;
end;
function TArticleLocDAO.Prixcarton(varticleLocDTO: TArticleLocDTO): double;
begin
with TFdQuery.Create(nil) do
begin
try
Connection:=Main.oconnection;
SQL.Add('select lastprixachat*lastqteachat as montant '+
' from tarticleloc' );
SQL.Add(' where tarticleloc.idarticleloc='+QuotedStr(varticleLocDTO.idarticleloc));
Active:=true;
if Fields[0].AsString<>'' then Result:=Fields[0].AsFloat else
result:=0;
finally
Active:=false;
DisposeOf;
end;
end;
end;
function TArticleLocDAO.getMaxIdArticle: string;
begin
end;
end.
|
unit Test.InterfacedObject;
interface
uses
Deltics.Smoketest;
type
TInterfacedObjectTests = class(TTest)
private
fOnDestroyCallCount: Integer;
procedure OnDestroyCallCounter(aSender: TObject);
published
procedure SetupMethod;
procedure InterfacedObjectLifetimeIsNotReferenceCounted;
procedure InterfacedObjectLifetimeIsExplicit;
end;
implementation
uses
Deltics.InterfacedObjects,
Deltics.Multicast;
{ TInterfacedObjectTests }
procedure TInterfacedObjectTests.OnDestroyCallCounter(aSender: TObject);
begin
Inc(fOnDestroyCallCount);
end;
procedure TInterfacedObjectTests.SetupMethod;
begin
fOnDestroyCallCount := 0;
end;
procedure TInterfacedObjectTests.InterfacedObjectLifetimeIsExplicit;
var
sut: TInterfacedObject;
intf: IUnknown;
iod: IOn_Destroy;
begin
sut := TInterfacedObject.Create;
try
iod := sut.On_Destroy;
iod.Add(OnDestroyCallCounter);
iod := NIL;
intf := sut;
intf := NIL;
finally
sut.Free;
Test('TInterfaceObject.On_Destroy calls').Assert(fOnDestroyCallCount).Equals(1);
end;
end;
procedure TInterfacedObjectTests.InterfacedObjectLifetimeIsNotReferenceCounted;
var
sut: TInterfacedObject;
intf: IUnknown;
iod: IOn_Destroy;
begin
sut := TInterfacedObject.Create;
try
iod := sut.On_Destroy;
iod.Add(OnDestroyCallCounter);
iod := NIL;
intf := sut;
intf := NIL;
Test('TInterfaceObject.On_Destroy calls').Assert(fOnDestroyCallCount).Equals(0);
finally
sut.Free;
end;
end;
end.
|
program HammingDistance;
{$mode objfpc}{$H+}
uses {$IFDEF UNIX} {$IFDEF UseCThreads}
cthreads, {$ENDIF} {$ENDIF}
Classes,
SysUtils,
CustApp,
hammingdistances;
type
{ THammingDistance }
THammingDistance = class(TCustomApplication)
protected
procedure DoRun; override;
public
constructor Create(TheOwner: TComponent); override;
destructor Destroy; override;
procedure WriteHelp; virtual;
end;
{ THammingDistance }
procedure THammingDistance.DoRun;
var
ErrorMsg, First, Second: string;
begin
// quick check parameters
ErrorMsg := CheckOptions('hfs', 'help first second');
if ErrorMsg <> '' then
begin
ShowException(Exception.Create(ErrorMsg));
Terminate;
Exit;
end;
// parse parameters
if HasOption('h', 'help') then
begin
WriteHelp;
Terminate;
Exit;
end;
if HasOption('f', 'first') then
begin
First := GetOptionValue('f', 'first');
end;
if HasOption('s', 'second') then
begin
Second := GetOptionValue('s', 'second');
end;
WriteLn(GetHammingDistance(First, Second));
Terminate;
end;
constructor THammingDistance.Create(TheOwner: TComponent);
begin
inherited Create(TheOwner);
StopOnException := True;
end;
destructor THammingDistance.Destroy;
begin
inherited Destroy;
end;
procedure THammingDistance.WriteHelp;
begin
{ add your help code here }
writeln('Usage: ', ExeName, ' -h');
end;
var
Application: THammingDistance;
begin
Application := THammingDistance.Create(nil);
Application.Title := 'Hamming Distance';
Application.Run;
Application.Free;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC Advantage Database Server Call Interface }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.Phys.ADSCli;
interface
uses
FireDAC.Stan.Consts, FireDAC.Stan.Intf;
const
{$IFDEF MSWINDOWS}
{$IFDEF FireDAC_32}
C_ADSDll: String = 'ACE32' + C_FD_DLLExt;
{$ELSE}
C_ADSDll: String = 'ACE64' + C_FD_DLLExt;
{$ENDIF}
{$ENDIF}
{$IFDEF POSIX}
C_ADSDll: String = 'libace' + C_FD_DLLExt;
{$ENDIF}
type
UNSIGNED64 = UInt64;
SIGNED64 = Int64;
UNSIGNED32 = Cardinal;
SIGNED32 = Integer;
UNSIGNED16 = Word;
SIGNED16 = SmallInt;
UNSIGNED8 = Byte;
SIGNED8 = ShortInt;
PUNSIGNED64 = ^UNSIGNED64;
PSIGNED64 = ^SIGNED64;
PUNSIGNED32 = ^UNSIGNED32;
PSIGNED32 = ^SIGNED32;
PUNSIGNED16 = ^UNSIGNED16;
PSIGNED16 = ^SIGNED16;
PUNSIGNED8 = ^UNSIGNED8;
PSIGNED8 = ^SIGNED8;
PPWideChar = ^PWideChar;
AceChar = SIGNED8;
PAceChar = ^AceChar;
AceBinary = Byte;
PAceBinary = ^AceBinary;
ADSHANDLE = NativeUInt;
PADSHANDLE = ^ADSHANDLE;
TADSTimeStamp = record
lDate: SIGNED32;
lTime: SIGNED32;
end;
const
// SQL Timeout value
ADS_DEFAULT_SQL_TIMEOUT = $0000; // Default client SQL timeout.
// Logical constants
ADS_FALSE = 0;
ADS_TRUE = 1;
// This is for parameters to routines that accept a default setting
ADS_DEFAULT = 0;
// character set types
ADS_ANSI = 1;
ADS_OEM = 2;
CZECH_VFP_CI_AS_1250 = 3;
GENERAL_VFP_CI_AS_1250 = 4;
HUNGARY_VFP_CI_AS_1250 = 5;
MACHINE_VFP_BIN_1250 = 6;
POLISH_VFP_CI_AS_1250 = 7;
SLOVAK_VFP_CI_AS_1250 = 8;
MACHINE_VFP_BIN_1251 = 9;
RUSSIAN_VFP_CI_AS_1251 = 10;
DUTCH_VFP_CI_AS_1252 = 11;
GENERAL_VFP_CI_AS_1252 = 12;
GERMAN_VFP_CI_AS_1252 = 13;
ICELAND_VFP_CI_AS_1252 = 14;
MACHINE_VFP_BIN_1252 = 15;
NORDAN_VFP_CI_AS_1252 = 16;
SPANISH_VFP_CI_AS_1252 = 17;
SWEFIN_VFP_CI_AS_1252 = 18;
UNIQWT_VFP_CS_AS_1252 = 19;
GREEK_VFP_CI_AS_1253 = 20;
MACHINE_VFP_BIN_1253 = 21;
GENERAL_VFP_CI_AS_1254 = 22;
MACHINE_VFP_BIN_1254 = 23;
TURKISH_VFP_CI_AS_1254 = 24;
DUTCH_VFP_CI_AS_437 = 25;
GENERAL_VFP_CI_AS_437 = 26;
GERMAN_VFP_CI_AS_437 = 27;
ICELAND_VFP_CI_AS_437 = 28;
MACHINE_VFP_BIN_437 = 29;
NORDAN_VFP_CI_AS_437 = 30;
SPANISH_VFP_CI_AS_437 = 31;
SWEFIN_VFP_CI_AS_437 = 32;
UNIQWT_VFP_CS_AS_437 = 33;
GENERAL_VFP_CI_AS_620 = 34;
MACHINE_VFP_BIN_620 = 35;
POLISH_VFP_CI_AS_620 = 36;
GREEK_VFP_CI_AS_737 = 37;
MACHINE_VFP_BIN_737 = 38;
DUTCH_VFP_CI_AS_850 = 39;
GENERAL_VFP_CI_AS_850 = 40;
ICELAND_VFP_CI_AS_850 = 41;
MACHINE_VFP_BIN_850 = 42;
NORDAN_VFP_CI_AS_850 = 43;
SPANISH_VFP_CI_AS_850 = 44;
SWEFIN_VFP_CI_AS_850 = 45;
UNIQWT_VFP_CS_AS_850 = 46;
CZECH_VFP_CI_AS_852 = 47;
GENERAL_VFP_CI_AS_852 = 48;
HUNGARY_VFP_CI_AS_852 = 49;
MACHINE_VFP_BIN_852 = 50;
POLISH_VFP_CI_AS_852 = 51;
SLOVAK_VFP_CI_AS_852 = 52;
GENERAL_VFP_CI_AS_857 = 53;
MACHINE_VFP_BIN_857 = 54;
TURKISH_VFP_CI_AS_857 = 55;
GENERAL_VFP_CI_AS_861 = 56;
ICELAND_VFP_CI_AS_861 = 57;
MACHINE_VFP_BIN_861 = 58;
GENERAL_VFP_CI_AS_865 = 59;
MACHINE_VFP_BIN_865 = 60;
NORDAN_VFP_CI_AS_865 = 61;
SWEFIN_VFP_CI_AS_865 = 62;
MACHINE_VFP_BIN_866 = 63;
RUSSIAN_VFP_CI_AS_866 = 64;
CZECH_VFP_CI_AS_895 = 65;
GENERAL_VFP_CI_AS_895 = 66;
MACHINE_VFP_BIN_895 = 67;
SLOVAK_VFP_CI_AS_895 = 68;
DANISH_ADS_CS_AS_1252 = 69;
DUTCH_ADS_CS_AS_1252 = 70;
ENGL_AMER_ADS_CS_AS_1252 = 71;
ENGL_CAN_ADS_CS_AS_1252 = 72;
ENGL_UK_ADS_CS_AS_1252 = 73;
FINNISH_ADS_CS_AS_1252 = 74;
FRENCH_ADS_CS_AS_1252 = 75;
FRENCH_CAN_ADS_CS_AS_1252 = 76;
GERMAN_ADS_CS_AS_1252 = 77;
ICELANDIC_ADS_CS_AS_1252 = 78;
ITALIAN_ADS_CS_AS_1252 = 79;
NORWEGIAN_ADS_CS_AS_1252 = 80;
PORTUGUESE_ADS_CS_AS_1252 = 81;
SPANISH_ADS_CS_AS_1252 = 82;
SPAN_MOD_ADS_CS_AS_1252 = 83;
SWEDISH_ADS_CS_AS_1252 = 84;
RUSSIAN_ADS_CS_AS_1251 = 85;
ASCII_ADS_CS_AS_1252 = 86;
TURKISH_ADS_CS_AS_1254 = 87;
POLISH_ADS_CS_AS_1250 = 88;
BALTIC_ADS_CS_AS_1257 = 89;
UKRAINIAN_ADS_CS_AS_1251 = 90;
DUDEN_DE_ADS_CS_AS_1252 = 91;
USA_ADS_CS_AS_437 = 92;
DANISH_ADS_CS_AS_865 = 93;
DUTCH_ADS_CS_AS_850 = 94;
FINNISH_ADS_CS_AS_865 = 95;
FRENCH_ADS_CS_AS_863 = 96;
GERMAN_ADS_CS_AS_850 = 97;
GREEK437_ADS_CS_AS_437 = 98;
GREEK851_ADS_CS_AS_851 = 99;
ICELD850_ADS_CS_AS_850 = 100;
ICELD861_ADS_CS_AS_861 = 101;
ITALIAN_ADS_CS_AS_850 = 102;
NORWEGN_ADS_CS_AS_865 = 103;
PORTUGUE_ADS_CS_AS_860 = 104;
SPANISH_ADS_CS_AS_852 = 105;
SWEDISH_ADS_CS_AS_865 = 106;
MAZOVIA_ADS_CS_AS_852 = 107;
PC_LATIN_ADS_CS_AS_852 = 108;
ISOLATIN_ADS_CS_AS_850 = 109;
RUSSIAN_ADS_CS_AS_866 = 110;
NTXCZ852_ADS_CS_AS_852 = 111;
NTXCZ895_ADS_CS_AS_895 = 112;
NTXSL852_ADS_CS_AS_852 = 113;
NTXSL895_ADS_CS_AS_895 = 114;
NTXHU852_ADS_CS_AS_852 = 115;
NTXPL852_ADS_CS_AS_852 = 116;
TURKISH_ADS_CS_AS_857 = 117;
BOSNIAN_ADS_CS_AS_775 = 118;
ADS_MAX_CHAR_SETS = 118;
// rights checking options
ADS_CHECKRIGHTS = 1;
ADS_IGNORERIGHTS = 2;
// In version 10, the default behavior is changed to never do the rights
// checking for performance reasons. The client side existence checks are very
// expensive and are unnecessary in almost all situations. If an application
// requires the old behavior, it can be restored with AdsSetRightsChecking and
// passing it the appropriate flag below.
ADS_RESPECT_RIGHTS_CHECKING = $00000001; // pre v10 behavior
ADS_IGNORE_RIGHTS_CHECKING = $00000002; // post v10 behavior
// options for connecting to Advantage servers - can be ORed together
ADS_INC_USERCOUNT = $00000001;
ADS_STORED_PROC_CONN = $00000002;
ADS_COMPRESS_ALWAYS = $00000004;
ADS_COMPRESS_NEVER = $00000008;
ADS_COMPRESS_INTERNET = $0000000C;
ADS_REPLICATION_CONNECTION = $00000010;
ADS_UDP_IP_CONNECTION = $00000020;
ADS_IPX_CONNECTION = $00000040;
ADS_TCP_IP_CONNECTION = $00000080;
ADS_TCP_IP_V6_CONNECTION = $00000100;
ADS_NOTIFICATION_CONNECTION = $00000200;
// Reserved 0x00000400
// Reserved 0x00000800
ADS_TLS_CONNECTION = $00001000;
// >= v 11
ADS_CHECK_FREE_TABLE_ACCESS = $00002000;
// options for opening/create tables - can be ORed together
ADS_EXCLUSIVE = $00000001;
ADS_READONLY = $00000002;
ADS_SHARED = $00000004;
ADS_CLIPPER_MEMOS = $00000008;
ADS_TABLE_PERM_READ = $00000010;
ADS_TABLE_PERM_UPDATE = $00000020;
ADS_TABLE_PERM_INSERT = $00000040;
ADS_TABLE_PERM_DELETE = $00000080;
ADS_REINDEX_ON_COLLATION_MISMATCH = $00000100;
ADS_IGNORE_COLLATION_MISMATCH = $00000200;
ADS_FREE_TABLE = $00001000; // Mutually exclusive with ADS_DICTIONARY_BOUND_TABLE
ADS_TEMP_TABLE = $00002000; // Mutually exclusive with ADS_DICTIONARY_BOUND_TABLE
ADS_DICTIONARY_BOUND_TABLE = $00004000; // Mutually exclusive with ADS_FREE_TABLE or ADS_TEMP_TABLE
ADS_CACHE_READS = $20000000; // Enable caching of reads on the table
ADS_CACHE_WRITES = $40000000; // Enable caching of reads & writes on the table
// When adding entry in here, make sure the corresponding
// entry is added in aceunpub.h and ensure that there is no
// conflict.
// Options for creating indexes - can be ORed together
ADS_ASCENDING = $00000000;
ADS_UNIQUE = $00000001;
ADS_COMPOUND = $00000002;
ADS_CUSTOM = $00000004;
ADS_DESCENDING = $00000008;
ADS_USER_DEFINED = $00000010;
// Options specifically for FTS indexes 0020 - 0200
ADS_FTS_INDEX = $00000020; // This is implied for AdsCreateFTSIndex
ADS_FTS_FIXED = $00000040; // Do not maintain the index with record updates
ADS_FTS_CASE_SENSITIVE = $00000080; // Make the index case sensitive
ADS_FTS_KEEP_SCORE = $00000100; // Track word counts in the index for faster SCORE()
ADS_FTS_PROTECT_NUMBERS = $00000200; // Don't break numbers on commas and periods
ADS_NOT_AUTO_OPEN = $00000400; // Don't make this an auto open index in data dictionary
ADS_CANDIDATE = $00000800; // true unique CDX index (equivalent to ADS_UNIQUE for FDIs)
ADS_BINARY_INDEX = $00001000; // logical index with a bitmap for data
// Options concerning the parameters supplied to the AdsCreateFTSIndex 00002000 - 00004000
ADS_FTS_ENCODE_UTF8 = $00002000;
ADS_FTS_ENCODE_UTF16 = $00004000;
// >= v 12
ADS_ONLINE = $00200000; // Perform ONLINE create with table open shared
// Options concerning Unicode string in the indexes 20000000 - 40000000
ADS_UCHAR_KEY_SHORT = $20000000;
ADS_UCHAR_KEY_LONG = $40000000;
ADS_UCHAR_KEY_XLONG = $60000000;
// Option to force index version
ADS_ALLOW_MULTIPLE_COLLATION = $0004000;
// Options for returning string values
ADS_NONE = $0000;
ADS_LTRIM = $0001;
ADS_RTRIM = $0002;
ADS_TRIM = $0003;
ADS_GET_UTF8 = $0004;
ADS_DONT_CHECK_CONV_ERR = $0008;
// >= v 11
ADS_GET_FORMAT_ANSI = $0010;
ADS_GET_FORMAT_WEB = $0030;
// >= v 12
ADS_GET_GUID_MIME = $0100; // MIME ENCODED
ADS_GET_GUID_FILE = $0200; // FILE ENCODED
ADS_GET_GUID_NUMBERS = $0400; // ONLY NUMBER
ADS_GET_GUID_REGISTRY = $0800; // REGISTRY Format - default
// locking compatibility
ADS_COMPATIBLE_LOCKING = 0;
ADS_PROPRIETARY_LOCKING = 1;
// settings for seeks
ADS_SOFTSEEK = $0001;
ADS_HARDSEEK = $0002;
ADS_SEEKGT = $0004;
// data types for seeks (and scopes)
ADS_RAWKEY = 1; // no conversion performed on given data
ADS_STRINGKEY = 2; // data given as a string
ADS_DOUBLEKEY = 4; // data is a pointer to 8 byte double
ADS_WSTRINGKEY = 8; // data given as a UTF16 string
// Option for AdsBuildRawKey100
ADS_GET_DEFAULT_KEY_LENGTH = $00000000;
ADS_GET_PARTIAL_FULL_KEY_LENGTH = $00000001;
ADS_GET_FULL_KEY_LENGTH = $00000002;
ADS_GET_PRIMARY_WEIGHT_LENGTH = $00000004;
// For retrieving scope settings
ADS_TOP = 1;
ADS_BOTTOM = 2;
// for calls that can optionally use filters
ADS_RESPECTFILTERS = $0001;
ADS_IGNOREFILTERS = $0002;
ADS_RESPECTSCOPES = $0003;
// This value is only used with GetRecordCount: It can be ORed in with the
// ignore filter value to force a read from the table header to get the most
// current record count.
ADS_REFRESHCOUNT = $0004;
// Server type constants
ADS_LOCAL_SERVER = $0001;
ADS_REMOTE_SERVER = $0002;
ADS_AIS_SERVER = $0004;
// ACE Handle types
ADS_CONNECTION = 1;
ADS_TABLE = 2;
ADS_INDEX_ORDER = 3;
ADS_STATEMENT = 4;
ADS_CURSOR = 5;
ADS_DATABASE_CONNECTION = 6;
// ADS_SYS_ADMIN_CONNECTION = 7 obsolete
ADS_FTS_INDEX_ORDER = 8;
// ACE Cursor ReadOnly settings
ADS_CURSOR_READONLY = 1;
ADS_CURSOR_READWRITE = 2;
// ACE Cursor Constrain settings
ADS_CONSTRAIN = 1;
ADS_NO_CONSTRAIN = 2;
// Select Field Read settings
ADS_READ_ALL_COLUMNS = 1;
ADS_READ_SELECT_COLUMNS = 2;
// Data dictionary new contraint property validation options
ADS_NO_VALIDATE = 0; // Do not validate records against the new constraint
ADS_VALIDATE_NO_SAVE = 1; // Delete record not meeting the constraint from the table, no save
ADS_VALIDATE_WRITE_FAIL = 2; // Validate the records against the new constraint and overwrite
// the fail table with records not meeting the constraint.
ADS_VALIDATE_APPEND_FAIL = 3; // Validate the records against the new constraint and append
// the failed records into the fail table
ADS_VALIDATE_RETURN_ERROR = 4; // Validate the records against the new constraint and return
// error if there is any record not meeting the constraint
// Possible result values from AdsCompareBookmarks.
ADS_CMP_LESS = -1;
ADS_CMP_EQUAL = 0;
ADS_CMP_GREATER = 1;
// Property values for the AdsGetConnectionProperty API
ADS_CONNECTIONPROP_USERNAME = 0;
ADS_CONNECTIONPROP_PASSWORD = 1;
ADS_CONNECTIONPROP_PROTOCOL = 2;
ADS_CONNECTIONPROP_ENCRYPTION_TYPE = 3;
ADS_CONNECTIONPROP_FIPS_MODE = 4;
ADS_CONNECTIONPROP_CERTIFICATE_FILE = 5;
ADS_CONNECTIONPROP_CIPHER_SUITE = 6;
ADS_CONNECTIONPROP_COMMON_NAME = 7;
ADS_CONNECTIONPROP_USING_TCP_IP = 1;
ADS_CONNECTIONPROP_USING_TLC = 5;
// Options for the AdsGetRecordCRC API
ADS_CRC_LOCALLY = 1;
ADS_CRC_IGNOREMEMOPAGES = 2;
// Options for notification events
ADS_EVENT_ASYNC = 1;
ADS_EVENT_WITH_DATA = 2; // Allow data to be passed with this event
// Options for the AdsCancelUpdate90 API
ADS_PRESERVE_ERR = $0001;
// property for AdsGetIntProperty API
ADS_CODE_PAGE = 1;
// Success return code
AE_SUCCESS = 0;
// Error codes
AE_ALLOCATION_FAILED = 5001;
AE_COMM_MISMATCH = 5002;
AE_DATA_TOO_LONG = 5003;
AE_FILE_NOT_FOUND = 5004;
AE_INSUFFICIENT_BUFFER = 5005;
AE_INVALID_BOOKMARK = 5006;
AE_INVALID_CALLBACK = 5007;
AE_INVALID_CENTURY = 5008;
AE_INVALID_DATEFORMAT = 5009;
AE_INVALID_DECIMALS = 5010;
AE_INVALID_EXPRESSION = 5011;
AE_INVALID_FIELDDEF = 5012;
AE_INVALID_FILTER_OPTION = 5013;
AE_INVALID_INDEX_HANDLE = 5014;
AE_INVALID_INDEX_NAME = 5015;
AE_INVALID_INDEX_ORDER_NAME = 5016;
AE_INVALID_INDEX_TYPE = 5017;
AE_INVALID_HANDLE = 5018;
AE_INVALID_OPTION = 5019;
AE_INVALID_PATH = 5020;
AE_INVALID_POINTER = 5021;
AE_INVALID_RECORD_NUMBER = 5022;
AE_INVALID_TABLE_HANDLE = 5023;
AE_INVALID_CONNECTION_HANDLE = 5024;
AE_INVALID_TABLETYPE = 5025;
AE_INVALID_WORKAREA = 5026;
AE_INVALID_CHARSETTYPE = 5027;
AE_INVALID_LOCKTYPE = 5028;
AE_INVALID_RIGHTSOPTION = 5029;
AE_INVALID_FIELDNUMBER = 5030;
AE_INVALID_KEY_LENGTH = 5031;
AE_INVALID_FIELDNAME = 5032;
AE_NO_DRIVE_CONNECTION = 5033;
AE_FILE_NOT_ON_SERVER = 5034;
AE_LOCK_FAILED = 5035;
AE_NO_CONNECTION = 5036;
AE_NO_FILTER = 5037;
AE_NO_SCOPE = 5038;
AE_NO_TABLE = 5039;
AE_NO_WORKAREA = 5040;
AE_NOT_FOUND = 5041;
AE_NOT_IMPLEMENTED = 5042;
AE_MAX_THREADS_EXCEEDED = 5043;
AE_START_THREAD_FAIL = 5044;
AE_TOO_MANY_INDEXES = 5045;
AE_TOO_MANY_TAGS = 5046;
AE_TRANS_OUT_OF_SEQUENCE = 5047;
AE_UNKNOWN_ERRCODE = 5048;
AE_UNSUPPORTED_COLLATION = 5049;
AE_NAME_TOO_LONG = 5050;
AE_DUPLICATE_ALIAS = 5051;
AE_TABLE_CLOSED_IN_TRANSACTION = 5053;
AE_PERMISSION_DENIED = 5054;
AE_STRING_NOT_FOUND = 5055;
AE_UNKNOWN_CHAR_SET = 5056;
AE_INVALID_OEM_CHAR_FILE = 5057;
AE_INVALID_MEMO_BLOCK_SIZE = 5058;
AE_NO_FILE_FOUND = 5059;
AE_NO_INF_LOCK = 5060;
AE_INF_FILE_ERROR = 5061;
AE_RECORD_NOT_LOCKED = 5062;
AE_ILLEGAL_COMMAND_DURING_TRANS = 5063;
AE_TABLE_NOT_SHARED = 5064;
AE_INDEX_ALREADY_OPEN = 5065;
AE_INVALID_FIELD_TYPE = 5066;
AE_TABLE_NOT_EXCLUSIVE = 5067;
AE_NO_CURRENT_RECORD = 5068;
AE_PRECISION_LOST = 5069;
AE_INVALID_DATA_TYPE = 5070;
AE_DATA_TRUNCATED = 5071;
AE_TABLE_READONLY = 5072;
AE_INVALID_RECORD_LENGTH = 5073;
AE_NO_ERROR_MESSAGE = 5074;
AE_INDEX_SHARED = 5075;
AE_INDEX_EXISTS = 5076;
AE_CYCLIC_RELATION = 5077;
AE_INVALID_RELATION = 5078;
AE_INVALID_DAY = 5079;
AE_INVALID_MONTH = 5080;
AE_CORRUPT_TABLE = 5081;
AE_INVALID_BINARY_OFFSET = 5082;
AE_BINARY_FILE_ERROR = 5083;
AE_INVALID_DELETED_BYTE_VALUE = 5084;
AE_NO_PENDING_UPDATE = 5085;
AE_PENDING_UPDATE = 5086;
AE_TABLE_NOT_LOCKED = 5087;
AE_CORRUPT_INDEX = 5088;
AE_AUTOOPEN_INDEX = 5089;
AE_SAME_TABLE = 5090;
AE_INVALID_IMAGE = 5091;
AE_COLLATION_SEQUENCE_MISMATCH = 5092;
AE_INVALID_INDEX_ORDER = 5093;
AE_TABLE_CACHED = 5094;
AE_INVALID_DATE = 5095;
AE_ENCRYPTION_NOT_ENABLED = 5096;
AE_INVALID_PASSWORD = 5097;
AE_TABLE_ENCRYPTED = 5098;
AE_SERVER_MISMATCH = 5099;
AE_INVALID_USERNAME = 5100;
AE_INVALID_VALUE = 5101;
AE_INVALID_CONTINUE = 5102;
AE_UNRECOGNIZED_VERSION = 5103;
AE_RECORD_ENCRYPTED = 5104;
AE_UNRECOGNIZED_ENCRYPTION = 5105;
AE_INVALID_SQLSTATEMENT_HANDLE = 5106;
AE_INVALID_SQLCURSOR_HANDLE = 5107;
AE_NOT_PREPARED = 5108;
AE_CURSOR_NOT_CLOSED = 5109;
AE_INVALID_SQL_PARAM_NUMBER = 5110;
AE_INVALID_SQL_PARAM_NAME = 5111;
AE_INVALID_COLUMN_NUMBER = 5112;
AE_INVALID_COLUMN_NAME = 5113;
AE_INVALID_READONLY_OPTION = 5114;
AE_IS_CURSOR_HANDLE = 5115;
AE_INDEX_EXPR_NOT_FOUND = 5116;
AE_NOT_DML = 5117;
AE_INVALID_CONSTRAIN_TYPE = 5118;
AE_INVALID_CURSORHANDLE = 5119;
AE_OBSOLETE_FUNCTION = 5120;
AE_TADSDATASET_GENERAL = 5121;
AE_UDF_OVERWROTE_BUFFER = 5122;
AE_INDEX_UDF_NOT_SET = 5123;
AE_CONCURRENT_PROBLEM = 5124;
AE_INVALID_DICTIONARY_HANDLE = 5125;
AE_INVALID_PROPERTY_ID = 5126;
AE_INVALID_PROPERTY = 5127;
AE_DICTIONARY_ALREADY_EXISTS = 5128;
AE_INVALID_FIND_HANDLE = 5129;
AE_DD_REQUEST_NOT_COMPLETED = 5130;
AE_INVALID_OBJECT_ID = 5131;
AE_INVALID_OBJECT_NAME = 5132;
AE_INVALID_PROPERTY_LENGTH = 5133;
AE_INVALID_KEY_OPTIONS = 5134;
AE_CONSTRAINT_VALIDATION_ERROR = 5135;
AE_INVALID_OBJECT_TYPE = 5136;
AE_NO_OBJECT_FOUND = 5137;
AE_PROPERTY_NOT_SET = 5138;
AE_NO_PRIMARY_KEY_EXISTS = 5139;
AE_LOCAL_CONN_DISABLED = 5140;
AE_RI_RESTRICT = 5141;
AE_RI_CASCADE = 5142;
AE_RI_FAILED = 5143;
AE_RI_CORRUPTED = 5144;
AE_RI_UNDO_FAILED = 5145;
AE_RI_RULE_EXISTS = 5146;
AE_COLUMN_CANNOT_BE_NULL = 5147;
AE_MIN_CONSTRAINT_VIOLATION = 5148;
AE_MAX_CONSTRAINT_VIOLATION = 5149;
AE_RECORD_CONSTRAINT_VIOLATION = 5150;
AE_CANNOT_DELETE_TEMP_INDEX = 5151;
AE_RESTRUCTURE_FAILED = 5152;
AE_INVALID_STATEMENT = 5153;
AE_STORED_PROCEDURE_FAILED = 5154;
AE_INVALID_DICTIONARY_FILE = 5155;
AE_NOT_MEMBER_OF_GROUP = 5156;
AE_ALREADY_MEMBER_OF_GROUP = 5157;
AE_INVALID_OBJECT_RIGHT = 5158;
AE_INVALID_OBJECT_PERMISSION = 5158; // Note that this is same as above. The word
// permission is more commonly used.
AE_CANNOT_OPEN_DATABASE_TABLE = 5159;
AE_INVALID_CONSTRAINT = 5160;
AE_NOT_ADMINISTRATOR = 5161;
AE_NO_TABLE_ENCRYPTION_PASSWORD = 5162;
AE_TABLE_NOT_ENCRYPTED = 5163;
AE_INVALID_ENCRYPTION_VERSION = 5164;
AE_NO_STORED_PROC_EXEC_RIGHTS = 5165;
AE_DD_UNSUPPORTED_DEPLOYMENT = 5166;
AE_INFO_AUTO_CREATION_OCCURRED = 5168;
AE_INFO_COPY_MADE_BY_CLIENT = 5169;
AE_DATABASE_REQUIRES_NEW_SERVER = 5170;
AE_COLUMN_PERMISSION_DENIED = 5171;
AE_DATABASE_REQUIRES_NEW_CLIENT = 5172;
AE_INVALID_LINK_NUMBER = 5173;
AE_LINK_ACTIVATION_FAILED = 5174;
AE_INDEX_COLLATION_MISMATCH = 5175;
AE_ILLEGAL_USER_OPERATION = 5176;
AE_TRIGGER_FAILED = 5177;
AE_NO_ASA_FUNCTION_FOUND = 5178;
AE_VALUE_OVERFLOW = 5179;
AE_UNRECOGNIZED_FTS_VERSION = 5180;
AE_TRIG_CREATION_FAILED = 5181;
AE_MEMTABLE_SIZE_EXCEEDED = 5182;
AE_OUTDATED_CLIENT_VERSION = 5183;
AE_FREE_TABLE = 5184;
AE_LOCAL_CONN_RESTRICTED = 5185;
AE_OLD_RECORD = 5186;
AE_QUERY_NOT_ACTIVE = 5187;
AE_KEY_EXCEEDS_PAGE_SIZE = 5188;
AE_TABLE_FOUND = 5189;
AE_TABLE_NOT_FOUND = 5190;
AE_LOCK_OBJECT = 5191;
AE_INVALID_REPLICATION_IDENT = 5192;
AE_ILLEGAL_COMMAND_DURING_BACKUP = 5193;
AE_NO_MEMO_FILE = 5194;
AE_SUBSCRIPTION_QUEUE_NOT_EMPTY = 5195;
AE_UNABLE_TO_DISABLE_TRIGGERS = 5196;
AE_UNABLE_TO_ENABLE_TRIGGERS = 5197;
AE_BACKUP = 5198;
AE_FREETABLEFAILED = 5199;
AE_BLURRY_SNAPSHOT = 5200;
AE_INVALID_VERTICAL_FILTER = 5201;
AE_INVALID_USE_OF_HANDLE_IN_AEP = 5202;
AE_COLLATION_NOT_RECOGNIZED = 5203;
AE_INVALID_COLLATION = 5204;
AE_NOT_VFP_NULLABLE_FIELD = 5205;
AE_NOT_VFP_VARIABLE_FIELD = 5206;
AE_ILLEGAL_EVENT_COMMAND = 5207;
AE_KEY_CANNOT_BE_NULL = 5208;
AE_COLLATIONS_DO_NOT_MATCH = 5209;
AE_INVALID_APPID = 5210;
AE_UNICODE_CONVERSION = 5211;
AE_UNICODE_COLLATION = 5212;
AE_SERVER_ENUMERATION_ERROR = 5213;
AE_UNABLE_TO_LOAD_SSL = 5214;
AE_UNABLE_TO_VERIFY_SIGNATURE = 5215;
AE_UNABLE_TO_LOAD_SSL_ENTRYPOINT = 5216;
AE_CRYPTO_ERROR = 5217;
AE_UNRECOGNIZED_CIPHER = 5218;
AE_FIPS_MODE_ENCRYPTION = 5219; // FIPS mode encryption violation
AE_FIPS_REQUIRED = 5220;
AE_FIPS_NOT_ALLOWED = 5221;
AE_FIPS_MODE_FAILED = 5222;
AE_PASSWORD_REQUIRED = 5223; // the additional error info should include details on type of password
AE_CONNECTION_TIMED_OUT = 5224;
// >= v 11
AE_DELTA_SUPPORT_NOT_POSSIBLE = 5225; // Cannot enable web delta functionality
AE_QUERY_LOGGING_ERROR = 5226; // the additional error info should include specifics
// >= v 12
AE_COMPRESSION_FAILED = 5227;
AE_INVALID_DATA = 5228;
AE_ROWVERSION_REQUIRED = 5229;
// Supported file types
ADS_DATABASE_TABLE = ADS_DEFAULT;
ADS_NTX = 1;
ADS_CDX = 2;
ADS_ADT = 3;
ADS_VFP = 4;
// for retrieving file names of tables
ADS_BASENAME = 1;
ADS_BASENAMEANDEXT = 2;
ADS_FULLPATHNAME = 3;
ADS_DATADICTIONARY_NAME = 4;
ADS_TABLE_OPEN_NAME = 5;
// Advantage Optimized Filter (AOF) optimization levels
ADS_OPTIMIZED_FULL = 1;
ADS_OPTIMIZED_PART = 2;
ADS_OPTIMIZED_NONE = 3;
// Advantage Optimized Filter (AOF) options
ADS_DYNAMIC_AOF = $00000000; // default
ADS_RESOLVE_IMMEDIATE = $00000001;
ADS_RESOLVE_DYNAMIC = $00000002;
ADS_KEYSET_AOF = $00000004;
ADS_FIXED_AOF = $00000008;
ADS_KEEP_AOF_PLAN = $00000010;
ADS_ENCODE_UTF16 = $00002000; // Used in AdsSetFilter100 options as well
ADS_ENCODE_UTF8 = $00004000; // Used in AdsSetFitler100 options as well
// Advantage Optimized Filter (AOF) customization options
ADS_AOF_ADD_RECORD = 1;
ADS_AOF_REMOVE_RECORD = 2;
ADS_AOF_TOGGLE_RECORD = 3;
// Stored procedure or trigger type
ADS_STORED_PROC = $00000001;
ADS_COMSTORED_PROC = $00000002; // means we know for sure this is a com
// aep. Before 7.1 we couldn't distinguish.
ADS_SCRIPT_PROC = $00000004; // Stored procedure written in SQL script
// Bit mask used by AdsDDAddProcedure to specify that the procedure returns an varying
// output cursor. Used in the ulInvokeType param.
// >= v 11
ADS_PROC_VARYING_OUTPUT = $00001000; // Stored procedure returns varying output
// Table (and related file) encryption types when using v10
ADS_ENCRYPTION_RC4 = 3; // RC4 Encryption
ADS_ENCRYPTION_AES128 = 5; // 128-bit AES in CTR mode, PBKDF2 key derivation
ADS_ENCRYPTION_AES256 = 6; // 256-bit AES in CTR mode, PBKDF2 key derivation
// some maximum values used by the client
// NOTE: constants meant for string length exclude space for null terminator
ADS_MAX_DATEMASK = 12;
ADS_MAX_ERROR_LEN = 600;
ADS_MAX_INDEX_EXPR_LEN = 510; // this is only accurate for index expressions
ADS_MAX_KEY_LENGTH = 4082; // maximum key value length. This is the max key length
// of FDI indexes. Max CDX key length is 240. Max
// NTX key length is 256
ADS_MAX_FIELD_NAME = 128;
ADS_MAX_DBF_FIELD_NAME = 10; // maximum length of field name in a DBF
ADS_MAX_INDEXES = 15; // physical index files, NOT index orders
ADS_MAX_PATH = 260;
ADS_MAX_TABLE_NAME = 255; // long file name
ADS_MAX_TAG_NAME = 128;
ADS_MAX_TAGS = 256; // maximum for CDX/FDI file
ADS_MAX_OBJECT_NAME = 200; // maximum length of DD object name
ADS_MAX_TABLE_AND_PATH = ADS_MAX_TABLE_NAME + ADS_MAX_PATH;
// Valid range of page sizes for FDI indexes. The default page size is 512
// bytes. Before using another page size, please read the section titled
// "Index Page Size" in the Advantage Client Engine help file (ace.hlp)
ADS_MIN_ADI_PAGESIZE = 512;
ADS_MAX_ADI_PAGESIZE = 8192;
// data types
ADS_TYPE_UNKNOWN = 0;
ADS_LOGICAL = 1; // 1 byte logical value
ADS_NUMERIC = 2; // DBF character style numeric
ADS_DATE = 3; // Date field. With ADS_NTX, ADS_CDX, and
// ADS_VFP< this is an 8 byte field of the form
// CCYYMMDD. With ADS_ADT, it is a 4 byte
// Julian date.
ADS_STRING = 4; // Character data
ADS_MEMO = 5; // Variable length character data
// the following are extended data types
ADS_BINARY = 6; // BLOB - any data
ADS_IMAGE = 7; // BLOB - bitmap
ADS_VARCHAR = 8; // variable length character field
ADS_COMPACTDATE = 9; // DBF date represented with 3 bytes
ADS_DOUBLE = 10; // IEEE 8 byte floating point
ADS_INTEGER = 11; // IEEE 4 byte signed long integer
// the following are supported with the FDT format
ADS_SHORTINT = 12; // IEEE 2 byte signed short integer
ADS_TIME = 13; // 4 byte long integer representing
// milliseconds since midnight
ADS_TIMESTAMP = 14; // 8 bytes. High order 4 bytes are a
// long integer representing Julian date.
// Low order 4 bytes are a long integer
// representing milliseconds since
// midnight
ADS_AUTOINC = 15; // 4 byte auto-increment value
ADS_RAW = 16; // Untranslated data
ADS_CURDOUBLE = 17; // IEEE 8 byte floating point currency
ADS_MONEY = 18; // 8 byte, 4 implied decimal Currency Field
ADS_LONGINT = 19; // 8 byte integer. Deprecated. Use ADS_LONGINT instead.
ADS_LONGLONG = 19; // 8 byte integer
ADS_CISTRING = 20; // CaSe INSensiTIVE character data
ADS_ROWVERSION = 21; // 8 byte integer, incremented for every update, unique to entire table
ADS_MODTIME = 22; // 8 byte timestamp, updated when record is updated
ADS_VARCHAR_FOX = 23; // Visual FoxPro varchar field
ADS_VARBINARY_FOX = 24; // Visual FoxPro varbinary field
ADS_SYSTEM_FIELD = 25; // For internal usage
ADS_NCHAR = 26; // Unicode Character data
ADS_NVARCHAR = 27; // Unpadded Unicode Character data
ADS_NMEMO = 28; // Variable Length Unicode Data
ADS_GUID = 29; // 16-byte binary data
ADS_MAX_FIELD_TYPE = 30;
ADS_FOXGENERAL = 51; // FoxPro General Field - stores an OLE object
ADS_FOXPICTURE = 52; // FoxPro Picture Field
// supported User Defined Function types to be used with AdsRegisterUDF
ADS_INDEX_UDF = 1;
// Constant for AdsMgGetConfigInfo
ADS_MAX_CFG_PATH = 256;
// Constants for AdsMgGetServerType
// Note ADS_MGMT_NETWARE_SERVER remains for backwards compatibility only
ADS_MGMT_NETWARE_SERVER = 1;
ADS_MGMT_NETWARE4_OR_OLDER_SERVER = 1;
ADS_MGMT_NT_SERVER = 2;
ADS_MGMT_LOCAL_SERVER = 3;
ADS_MGMT_WIN9X_SERVER = 4;
ADS_MGMT_NETWARE5_OR_NEWER_SERVER = 5;
ADS_MGMT_LINUX_SERVER = 6;
ADS_MGMT_NT_SERVER_64_BIT = 7;
ADS_MGMT_LINUX_SERVER_64_BIT = 8;
// Constants for AdsMgGetLockOwner
ADS_MGMT_NO_LOCK = 1;
ADS_MGMT_RECORD_LOCK = 2;
ADS_MGMT_FILE_LOCK = 3;
// Constants for MgGetInstallInfo
ADS_REG_OWNER_LEN = 36;
ADS_REVISION_LEN = 16;
ADS_INST_DATE_LEN = 16;
ADS_OEM_CHAR_NAME_LEN = 16;
ADS_ANSI_CHAR_NAME_LEN = 16;
ADS_SERIAL_NUM_LEN = 16;
// Constants for MgGetOpenTables
ADS_MGMT_MAX_PATH = 260;
ADS_MGMT_PROPRIETARY_LOCKING = 1;
ADS_MGMT_CDX_LOCKING = 2;
ADS_MGMT_NTX_LOCKING = 3;
ADS_MGMT_ADT_LOCKING = 4;
ADS_MGMT_COMIX_LOCKING = 5;
ADS_MAX_USER_NAME = 50;
ADS_MAX_ADDRESS_SIZE = 30;
ADS_MAX_MGMT_APPID_SIZE = 70;
// -------------------------------------------------------------------------
// Management API structures
const
// The following Management API values can be freely changed by you to fit
// your application's needs.
ADS_LOCK_ARRAY_SIZE = 400;
ADS_THREAD_ARRAY_SIZE = 50;
ADS_TABLE_ARRAY_SIZE = 200;
ADS_INDEX_ARRAY_SIZE = 200;
ADS_USER_ARRAY_SIZE = 200;
type
ADS_MGMT_COMM_STATS = packed record
dPercentCheckSums: double; { 0f pkts with checksum failures }
ulTotalPackets: UNSIGNED32; { Total packets received }
ulRcvPktOutOfSeq: UNSIGNED32; { Receive packets out of sequence }
ulNotLoggedIn: UNSIGNED32; { Packet owner not logged in }
ulRcvReqOutOfSeq: UNSIGNED32; { Receive requests out of sequence }
ulCheckSumFailures: UNSIGNED32; { Checksum failures }
ulDisconnectedUsers: UNSIGNED32; { Server initiated disconnects }
ulPartialConnects: UNSIGNED32; { Removed partial connections }
ulInvalidPackets: UNSIGNED32; { Rcvd invalid packets (NT only) }
ulRecvFromErrors: UNSIGNED32; { RecvFrom failed (NT only) }
ulSendToErrors: UNSIGNED32; { SendTo failed (NT only) }
end;
PADS_MGMT_COMM_STATS = ^ADS_MGMT_COMM_STATS;
ADS_MGMT_CONFIG_PARAMS = packed record
ulNumConnections: UNSIGNED32; { number connections }
ulNumWorkAreas: UNSIGNED32; { number work areas }
ulNumTables: UNSIGNED32; { number tables }
ulNumIndexes: UNSIGNED32; { number indexes }
ulNumLocks: UNSIGNED32; { number locks }
ulUserBufferSize: UNSIGNED32; { user buffer }
ulStatDumpInterval: UNSIGNED32; { statistics dump interval }
ulErrorLogMax: UNSIGNED32; { max size of error log }
ulNumTPSHeaderElems: UNSIGNED32; { number TPS header elems }
ulNumTPSVisibilityElems: UNSIGNED32; { number TPS vis elems }
ulNumTPSMemoTransElems: UNSIGNED32; { number TPS memo elems }
usNumRcvECBs: UNSIGNED16; { number rcv ECBs (NLM only) }
usNumSendECBs: UNSIGNED16; { number send ECBs (NLM only) }
usNumBurstPackets: UNSIGNED16; { number packets per burst }
usNumWorkerThreads: UNSIGNED16; { number worker threads }
ulSortBuffSize: UNSIGNED32; { index sort buffer size }
aucErrorLog: array[0..ADS_MAX_CFG_PATH - 1] of AceChar; { error log path }
aucSemaphore: array[0..ADS_MAX_CFG_PATH - 1] of AceChar; { semaphore file path }
aucTransaction: array[0..ADS_MAX_CFG_PATH - 1] of AceChar; { TPS log file path }
ucReserved3: UNSIGNED8; { reserved }
ucReserved4: UNSIGNED8; { reserved }
usSendIPPort: UNSIGNED16; { NT Service IP send port # }
usReceiveIPPort: UNSIGNED16; { NT Service IP rcv port # }
ucUseIPProtocol: UNSIGNED8; { Win9x only. Which protocol to use }
ucFlushEveryUpdate: UNSIGNED8; { Win9x specific }
ulGhostTimeout: UNSIGNED32; { Diconnection time for partial connections }
ulFlushFrequency: UNSIGNED32; { For local server only }
ulKeepAliveTimeOut: UNSIGNED32; { When not using semaophore files. In milliseconds }
ucDisplayNWLoginNames: UNSIGNED8;{ Display connections using user names. }
ucUseSemaphoreFiles: UNSIGNED8; { Whether or not to use semaphore files }
ucUseDynamicAOFs: UNSIGNED8;
ucUseInternet: UNSIGNED8; { 0 if an Internet port is not specified. }
usInternetPort: UNSIGNED16; { Internet Port }
usMaxConnFailures: UNSIGNED16; { Maximum Internet connection failures allowed. }
ulInternetKeepAlive: UNSIGNED32; { In Milliseconds }
usCompressionLevel: UNSIGNED16; { Compression option at server. ADS_COMPRESS_NEVER, }
{ ADS_COMPRESS_INTERNET, or ADS_COMPRESS_ALWAYS }
ulNumQueries: UNSIGNED32; { number of queries }
usReceiveSSLPort: UNSIGNED16; { Port number used for SSL }
end;
PADS_MGMT_CONFIG_PARAMS = ^ADS_MGMT_CONFIG_PARAMS;
ADS_MGMT_CONFIG_MEMORY = packed record
ulTotalConfigMem: UNSIGNED32; { Total mem taken by cfg params }
ulConnectionMem: UNSIGNED32; { memory taken by connections }
ulWorkAreaMem: UNSIGNED32; { memory taken by work areas }
ulTableMem: UNSIGNED32; { memory taken by tables }
ulIndexMem: UNSIGNED32; { memory taken by indexes }
ulLockMem: UNSIGNED32; { memory taken by locks }
ulUserBufferMem: UNSIGNED32; { memory taken by user buffer }
ulTPSHeaderElemMem: UNSIGNED32; { memory taken by TPS hdr elems }
ulTPSVisibilityElemMem: UNSIGNED32; { memory taken by TPS vis elems }
ulTPSMemoTransElemMem: UNSIGNED32; { mem taken by TPS memo elems }
ulRcvEcbMem: UNSIGNED32; { mem taken by rcv ECBs (NLM) }
ulSendEcbMem: UNSIGNED32; { mem taken by send ECBs (NLM) }
ulWorkerThreadMem: UNSIGNED32; { mem taken by worker threads }
ulQueryMem: UNSIGNED32; { mem taken by queries }
end;
PADS_MGMT_CONFIG_MEMORY = ^ADS_MGMT_CONFIG_MEMORY;
ADS_MGMT_INSTALL_INFO = packed record
ulUserOption: UNSIGNED32; { User option purchased }
aucRegisteredOwner: array[0..ADS_REG_OWNER_LEN - 1] of AceChar; { Registered owner }
aucVersionStr: array[0..ADS_REVISION_LEN - 1] of AceChar; { Advantage version }
aucInstallDate: array[0..ADS_INST_DATE_LEN - 1] of AceChar; { Install date string }
aucOemCharName: array[0..ADS_OEM_CHAR_NAME_LEN - 1] of AceChar; { OEM char language }
aucAnsiCharName: array[0..ADS_ANSI_CHAR_NAME_LEN - 1] of AceChar;{ ANSI char language }
aucEvalExpireDate: array[0..ADS_INST_DATE_LEN - 1] of AceChar; { Eval expiration date }
aucSerialNumber: array[0..ADS_SERIAL_NUM_LEN - 1] of AceChar; { Serial number string }
// >= v 11
ulMaxStatefulUsers: UNSIGNED32; { How many stateful connections allowed }
ulMaxStatelessUsers: UNSIGNED32; { How many stateless connections allowed }
end;
PADS_MGMT_INSTALL_INFO = ^ADS_MGMT_INSTALL_INFO;
ADS_MGMT_UPTIME_INFO = packed record
usDays: UNSIGNED16; { Number of days server has been up }
usHours: UNSIGNED16; { Number of hours server has been up }
usMinutes: UNSIGNED16; { Number of minutes server has been up }
usSeconds: UNSIGNED16; { Number of seconds server has been up }
end;
PADS_MGMT_UPTIME_INFO = ^ADS_MGMT_UPTIME_INFO;
ADS_MGMT_USAGE_INFO = packed record
ulInUse: UNSIGNED32; { Number of items in use }
ulMaxUsed: UNSIGNED32; { Max number of items ever used }
ulRejected:UNSIGNED32; { Number of items rejected }
end;
PADS_MGMT_USAGE_INFO = ^ADS_MGMT_USAGE_INFO;
ADS_MGMT_ACTIVITY_INFO = packed record
ulOperations: UNSIGNED32; { Number operations since started }
ulLoggedErrors: UNSIGNED32; { Number logged errors }
stUpTime: ADS_MGMT_UPTIME_INFO; { Length of time ADS has been up }
stUsers: ADS_MGMT_USAGE_INFO; { Users in use, max, rejected }
stConnections: ADS_MGMT_USAGE_INFO; { Conns in use, max, rejected }
stWorkAreas: ADS_MGMT_USAGE_INFO; { WAs in use, max, rejected }
stTables: ADS_MGMT_USAGE_INFO; { Tables in use, max, rejected }
stIndexes: ADS_MGMT_USAGE_INFO; { Indexes in use, max, rejected }
stLocks: ADS_MGMT_USAGE_INFO; { Locks in use, max, rejected }
stTpsHeaderElems: ADS_MGMT_USAGE_INFO; { TPS header elems in use, max }
stTpsVisElems: ADS_MGMT_USAGE_INFO; { TPS vis elems in use, max }
stTpsMemoElems: ADS_MGMT_USAGE_INFO; { TPS memo elems in use, max }
stWorkerThreads: ADS_MGMT_USAGE_INFO; { Worker threads in use, max }
stQueries: ADS_MGMT_USAGE_INFO; { Queries in use, max, rejected }
// >= v 11
stStatefulUsers: ADS_MGMT_USAGE_INFO; { Stateful users in use }
stStatelessUsers:ADS_MGMT_USAGE_INFO; { Stateless users in use }
end;
PADS_MGMT_ACTIVITY_INFO = ^ADS_MGMT_ACTIVITY_INFO;
ADS_MGMT_USER_INFO = packed record
aucUserName: array[0..ADS_MAX_USER_NAME - 1] of AceChar; { Name of connected user }
usConnNumber: UNSIGNED16; { NetWare conn # (NLM only) }
aucDictionaryName: array[0..ADS_MAX_USER_NAME - 1] of AceChar; { Dictionary user name }
aucAddress: array[0..ADS_MAX_ADDRESS_SIZE - 1] of AceChar;{ Network address of user }
aucOSUserLoginName: array[0..ADS_MAX_USER_NAME - 1] of AceChar; { OS user login name }
aucTSAddress: array[0..ADS_MAX_ADDRESS_SIZE - 1] of AceChar;{ Terminal Services client IP Address }
aucApplicationID: array[0..ADS_MAX_MGMT_APPID_SIZE - 1] of AceChar; { application id }
ulAveRequestCost: UNSIGNED32; { estimated average cost of each server request }
usReserved1: UNSIGNED16; { reserved to maintain byte alignment (ace.pas structs are not packed) }
end;
PADS_MGMT_USER_INFO = ^ADS_MGMT_USER_INFO;
ADSMgUserArray = array[0..ADS_USER_ARRAY_SIZE - 1] of ADS_MGMT_USER_INFO;
PADSMgUserArray = ^ADSMgUserArray;
ADS_MGMT_TABLE_INFO = packed record
aucTableName: array[0..ADS_MGMT_MAX_PATH - 1] of AceChar; { Fully qualified table name }
usLockType: UNSIGNED16; { Advantage locking mode }
end;
PADS_MGMT_TABLE_INFO = ^ADS_MGMT_TABLE_INFO;
ADSMgTableArray = array[0..ADS_TABLE_ARRAY_SIZE - 1] of ADS_MGMT_TABLE_INFO;
PADSMgTableArray = ^ADSMgTableArray;
ADS_MGMT_INDEX_INFO = packed record
aucIndexName: array[0..ADS_MGMT_MAX_PATH - 1] of AceChar; { Fully qualified table name }
end;
PADS_MGMT_INDEX_INFO = ^ADS_MGMT_INDEX_INFO;
ADSMgIndexArray = array[0..ADS_INDEX_ARRAY_SIZE - 1] of ADS_MGMT_INDEX_INFO;
PADSMgIndexArray = ^ADSMgIndexArray;
ADS_MGMT_RECORD_INFO = packed record
ulRecordNumber: UNSIGNED32; { Record number that is locked }
end;
PADS_MGMT_RECORD_INFO = ^ADS_MGMT_RECORD_INFO;
ADSMgLocksArray = array[0..ADS_LOCK_ARRAY_SIZE - 1] of ADS_MGMT_RECORD_INFO;
PADSMgLocksArray = ^ADSMgLocksArray;
ADS_MGMT_THREAD_ACTIVITY = packed record
ulThreadNumber: UNSIGNED32; { Thread Number }
usOpCode: UNSIGNED16; { Operation in progress }
aucUserName: array[0..ADS_MAX_USER_NAME - 1] of AceChar; { Name of user }
usConnNumber: UNSIGNED16; { NetWare conn num (NLM only) }
usReserved1: UNSIGNED16; { Reserved }
aucOSUserLoginName: array[0..ADS_MAX_USER_NAME - 1] of AceChar; { OS user login name }
end;
PADS_MGMT_THREAD_ACTIVITY = ^ADS_MGMT_THREAD_ACTIVITY;
ADSMgThreadsArray = array[0..ADS_THREAD_ARRAY_SIZE - 1] of ADS_MGMT_THREAD_ACTIVITY;
PADSMgThreadsArray = ^ADSMgThreadsArray;
// GUID structure
ADS_GUID_DATA = packed record
Data1: UNSIGNED32;
Data2: UNSIGNED16;
Data3: UNSIGNED16;
Data4: UNSIGNED64;
end;
// -------------------------------------------------------------------------
// Data dictionary properties related constants and structure
ADD_FIELD_DESC = packed record
usFieldType: UNSIGNED16;
usFieldLength: UNSIGNED16;
usFieldDecimal: UNSIGNED16;
end;
PFDD_FIELD_DESC = ^ADD_FIELD_DESC;
const
ADS_DD_PROPERTY_NOT_AVAIL = $FFFF;
ADS_DD_MAX_PROPERTY_LEN = $FFFE;
ADS_DD_MAX_OBJECT_NAME_LEN = 200;
ADS_DD_MAX_LINK_INFO_SIZE = 2 * ADS_DD_MAX_OBJECT_NAME_LEN + ADS_MAX_PATH + 3;
ADS_DD_UNKNOWN_OBJECT = 0;
ADS_DD_TABLE_OBJECT = 1;
ADS_DD_RELATION_OBJECT = 2;
ADS_DD_INDEX_FILE_OBJECT = 3;
ADS_DD_FIELD_OBJECT = 4;
ADS_DD_COLUMN_OBJECT = 4;
ADS_DD_INDEX_OBJECT = 5;
ADS_DD_VIEW_OBJECT = 6;
ADS_DD_VIEW_OR_TABLE_OBJECT = 7; // Used in AdsFindFirst/NextTable
ADS_DD_USER_OBJECT = 8;
ADS_DD_USER_GROUP_OBJECT = 9;
ADS_DD_PROCEDURE_OBJECT = 10;
ADS_DD_DATABASE_OBJECT = 11;
ADS_DD_LINK_OBJECT = 12;
ADS_DD_TABLE_VIEW_OR_LINK_OBJECT = 13;// Used in v6.2 AdsFindFirst/NextTable
ADS_DD_TRIGGER_OBJECT = 14;
ADS_DD_PUBLICATION_OBJECT = 15;
ADS_DD_ARTICLE_OBJECT = 16; // the things (tables) that get published
ADS_DD_SUBSCRIPTION_OBJECT = 17; // indicates where a publication goes
ADS_DD_FUNCTION_OBJECT = 18; // User defined function
ADS_DD_PACKAGE_OBJECT = 19; // function and stored procedure packages
ADS_DD_QUALIFIED_TRIGGER_OBJ = 20; // Used in AdsDDFindFirst/NextObject
ADS_DD_PERMISSION_OBJECT = 21;
// >= v 12
ADS_DD_DATABASE_TRIGGER_OBJ = 22; // Used in AdsDDFindFirst/NextObject
// Common properties numbers < 100
ADS_DD_COMMENT = 1;
ADS_DD_VERSION = 2;
ADS_DD_USER_DEFINED_PROP = 3;
ADS_DD_OBJECT_NAME = 4;
ADS_DD_TRIGGERS_DISABLED = 5;
ADS_DD_OBJECT_ID = 6;
ADS_DD_OPTIONS = 7;
// bit options for ADS_DD_QUERY_VIA_ROOT
ADS_DD_QVR_OPT_QUERY = $00000001;
ADS_DD_QVR_OPT_PROCEDURE = $00000002;
// Database properties between 100 and 199
ADS_DD_DEFAULT_TABLE_PATH = 100;
ADS_DD_ADMIN_PASSWORD = 101;
ADS_DD_TEMP_TABLE_PATH = 102;
ADS_DD_LOG_IN_REQUIRED = 103;
ADS_DD_VERIFY_ACCESS_RIGHTS = 104;
ADS_DD_ENCRYPT_TABLE_PASSWORD = 105;
ADS_DD_ENCRYPT_NEW_TABLE = 106;
ADS_DD_ENABLE_INTERNET = 107;
ADS_DD_INTERNET_SECURITY_LEVEL = 108;
ADS_DD_MAX_FAILED_ATTEMPTS = 109;
ADS_DD_ALLOW_ADSSYS_NET_ACCESS = 110;
ADS_DD_VERSION_MAJOR = 111; // properties for customer dd version
ADS_DD_VERSION_MINOR = 112;
ADS_DD_LOGINS_DISABLED = 113;
ADS_DD_LOGINS_DISABLED_ERRSTR = 114;
ADS_DD_FTS_DELIMITERS = 115;
ADS_DD_FTS_NOISE = 116;
ADS_DD_FTS_DROP_CHARS = 117;
ADS_DD_FTS_CONDITIONAL_CHARS = 118;
ADS_DD_ENCRYPTED = 119;
ADS_DD_ENCRYPT_INDEXES = 120;
ADS_DD_QUERY_LOG_TABLE = 121;
ADS_DD_ENCRYPT_COMMUNICATION = 122;
ADS_DD_DEFAULT_TABLE_RELATIVE_PATH = 123;
ADS_DD_TEMP_TABLE_RELATIVE_PATH = 124;
ADS_DD_DISABLE_DLL_CACHING = 125;
ADS_DD_DATA_ENCRYPTION_TYPE = 126;
ADS_DD_FTS_DELIMITERS_W = 127;
ADS_DD_FTS_NOISE_W = 128;
ADS_DD_FTS_DROP_CHARS_W = 129;
ADS_DD_FTS_CONDITIONAL_CHARS_W = 130;
// >= v 11
ADS_DD_QUERY_VIA_ROOT = 131;
// >= v 12
ADS_DD_ENFORCE_MAX_FAILED_LOGINS = 132;
ADS_DD_DATABASE_TRIGGER_TYPES = 133; // for internal use
// Table properties between 200 and 299
ADS_DD_TABLE_VALIDATION_EXPR = 200;
ADS_DD_TABLE_VALIDATION_MSG = 201;
ADS_DD_TABLE_PRIMARY_KEY = 202;
ADS_DD_TABLE_AUTO_CREATE = 203;
ADS_DD_TABLE_TYPE = 204;
ADS_DD_TABLE_PATH = 205;
ADS_DD_TABLE_FIELD_COUNT = 206;
ADS_DD_TABLE_RI_GRAPH = 207;
ADS_DD_TABLE_OBJ_ID = 208;
ADS_DD_TABLE_RI_XY = 209;
ADS_DD_TABLE_IS_RI_PARENT = 210;
ADS_DD_TABLE_RELATIVE_PATH = 211;
ADS_DD_TABLE_CHAR_TYPE = 212;
ADS_DD_TABLE_DEFAULT_INDEX = 213;
ADS_DD_TABLE_ENCRYPTION = 214;
ADS_DD_TABLE_MEMO_BLOCK_SIZE = 215;
ADS_DD_TABLE_PERMISSION_LEVEL = 216;
ADS_DD_TABLE_TRIGGER_TYPES = 217;
ADS_DD_TABLE_TRIGGER_OPTIONS = 218;
ADS_DD_TABLE_CACHING = 219;
ADS_DD_TABLE_TXN_FREE = 220;
ADS_DD_TABLE_VALIDATION_EXPR_W = 221;
// >= v 11
ADS_DD_TABLE_WEB_DELTA = 222;
// >= v 12
ADS_DD_TABLE_CONCURRENCY_ENABLED = 223; // for OData concurrency control
// Bit values for the ADS_DD_FIELD_OPTIONS property
ADS_DD_FIELD_OPT_VFP_BINARY = $00000001; // field has NOCPTRANS option
ADS_DD_FIELD_OPT_VFP_NULLABLE = $00000002; // field can be physicall set to NULL
// >= v 12
ADS_DD_FIELD_OPT_COMPRESSED = $00010000; // Field may be compressed, ADT memo, nmemo and blob
// Field properties between 300 - 399
ADS_DD_FIELD_DEFAULT_VALUE = 300;
ADS_DD_FIELD_CAN_NULL = 301;
ADS_DD_FIELD_MIN_VALUE = 302;
ADS_DD_FIELD_MAX_VALUE = 303;
ADS_DD_FIELD_VALIDATION_MSG = 304;
ADS_DD_FIELD_DEFINITION = 305;
ADS_DD_FIELD_TYPE = 306;
ADS_DD_FIELD_LENGTH = 307;
ADS_DD_FIELD_DECIMAL = 308;
ADS_DD_FIELD_NUM = 309;
ADS_DD_FIELD_OPTIONS = 310;
ADS_DD_FIELD_DEFAULT_VALUE_W = 311;
ADS_DD_FIELD_MIN_VALUE_W = 312;
ADS_DD_FIELD_MAX_VALUE_W = 313;
// Index tag properties between 400 - 499
ADS_DD_INDEX_FILE_NAME = 400;
ADS_DD_INDEX_EXPRESSION = 401;
ADS_DD_INDEX_CONDITION = 402;
ADS_DD_INDEX_OPTIONS = 403;
ADS_DD_INDEX_KEY_LENGTH = 404;
ADS_DD_INDEX_KEY_TYPE = 405;
ADS_DD_INDEX_FTS_MIN_LENGTH = 406;
ADS_DD_INDEX_FTS_DELIMITERS = 407;
ADS_DD_INDEX_FTS_NOISE = 408;
ADS_DD_INDEX_FTS_DROP_CHARS = 409;
ADS_DD_INDEX_FTS_CONDITIONAL_CHARS = 410;
ADS_DD_INDEX_COLLATION = 411;
ADS_DD_INDEX_FTS_DELIMITERS_W = 412;
ADS_DD_INDEX_FTS_NOISE_W = 413;
ADS_DD_INDEX_FTS_DROP_CHARS_W = 414;
ADS_DD_INDEX_FTS_CONDITIONAL_CHARS_W = 415;
// RI properties between 500-599
ADS_DD_RI_PARENT_GRAPH = 500;
ADS_DD_RI_PRIMARY_TABLE = 501;
ADS_DD_RI_PRIMARY_INDEX = 502;
ADS_DD_RI_FOREIGN_TABLE = 503;
ADS_DD_RI_FOREIGN_INDEX = 504;
ADS_DD_RI_UPDATERULE = 505;
ADS_DD_RI_DELETERULE = 506;
ADS_DD_RI_NO_PKEY_ERROR = 507;
ADS_DD_RI_CASCADE_ERROR = 508;
// User properties between 600-699
ADS_DD_USER_GROUP_NAME = 600;
// View properties between 700-749
ADS_DD_VIEW_STMT = 700;
ADS_DD_VIEW_STMT_LEN = 701;
ADS_DD_VIEW_TRIGGER_TYPES = 702;
ADS_DD_VIEW_TRIGGER_OPTIONS = 703;
ADS_DD_VIEW_STMT_W = 704;
// Stored procedure properties 800-899
ADS_DD_PROC_INPUT = 800;
ADS_DD_PROC_OUTPUT = 801;
ADS_DD_PROC_DLL_NAME = 802;
ADS_DD_PROC_DLL_FUNCTION_NAME = 803;
ADS_DD_PROC_INVOKE_OPTION = 804;
ADS_DD_PROC_SCRIPT = 805;
ADS_DD_PROC_SCRIPT_W = 806;
// Index file properties 900-999
ADS_DD_INDEX_FILE_PATH = 900;
ADS_DD_INDEX_FILE_PAGESIZE = 901;
ADS_DD_INDEX_FILE_RELATIVE_PATH = 902;
ADS_DD_INDEX_FILE_TYPE = 903;
// Object rights properties 1001 - 1099 . They can be used
// with either user or user group objects.
ADS_DD_TABLES_RIGHTS = 1001;
ADS_DD_VIEWS_RIGHTS = 1002;
ADS_DD_PROCS_RIGHTS = 1003;
ADS_DD_OBJECTS_RIGHTS = 1004;
ADS_DD_FREE_TABLES_RIGHTS = 1005;
// User Properties 1101 - 1199
ADS_DD_USER_PASSWORD = 1101;
ADS_DD_USER_GROUP_MEMBERSHIP = 1102;
ADS_DD_USER_BAD_LOGINS = 1103;
// >= v 11
ADS_DD_CURRENT_USER_PASSWORD = 1104;
ADS_DD_REQUIRE_OLD_PASSWORD = 1105;
// User group Properties 1201 - 1299
// None at this moment.
// Link properties 1301 - 1399
ADS_DD_LINK_PATH = 1300;
ADS_DD_LINK_OPTIONS = 1301;
ADS_DD_LINK_USERNAME = 1302;
ADS_DD_LINK_RELATIVE_PATH = 1303;
// Trigger properties 1400 - 1499
ADS_DD_TRIG_TABLEID = 1400;
ADS_DD_TRIG_EVENT_TYPE = 1401;
ADS_DD_TRIG_TRIGGER_TYPE = 1402;
ADS_DD_TRIG_CONTAINER_TYPE = 1403;
ADS_DD_TRIG_CONTAINER = 1404;
ADS_DD_TRIG_FUNCTION_NAME = 1405;
ADS_DD_TRIG_PRIORITY = 1406;
ADS_DD_TRIG_OPTIONS = 1407;
ADS_DD_TRIG_TABLENAME = 1408;
ADS_DD_TRIG_CONTAINER_W = 1409;
// Publication properties 1500 - 1599
ADS_DD_PUBLICATION_OPTIONS = 1500;
// Publication article properties 1600 - 1699
ADS_DD_ARTICLE_FILTER = 1600; // horizontal filter (optional)
ADS_DD_ARTICLE_ID_COLUMNS = 1601; // columns that identify the target row
ADS_DD_ARTICLE_ID_COLUMN_NUMBERS = 1602; // array of the field numbers
ADS_DD_ARTICLE_FILTER_SHORT = 1603; // short version of the expression
ADS_DD_ARTICLE_INCLUDE_COLUMNS = 1604; // Vertical filter (inclusion list)
ADS_DD_ARTICLE_EXCLUDE_COLUMNS = 1605; // Vertical filter (exclusion list)
ADS_DD_ARTICLE_INC_COLUMN_NUMBERS = 1606; // Retrieve column nums to replicate
ADS_DD_ARTICLE_INSERT_MERGE = 1607; // Use SQL MERGE with INSERTs
ADS_DD_ARTICLE_UPDATE_MERGE = 1608; // Use SQL MERGE with UPDATEs
ADS_DD_ARTICLE_FILTER_W = 1609; // horizontal filter (optional)
// Subscription article properties 1700 - 1799
ADS_DD_SUBSCR_PUBLICATION_NAME = 1700; // Name of the publication (for reading)
ADS_DD_SUBSCR_TARGET = 1701; // full path of target database
ADS_DD_SUBSCR_USERNAME = 1702; // user name to use to connect to target
ADS_DD_SUBSCR_PASSWORD = 1703; // password for connecting
ADS_DD_SUBSCR_FORWARD = 1704; // boolean flag: forward updates that came from a replication?
ADS_DD_SUBSCR_ENABLED = 1705; // boolean flag: Replication enabled on this subscription?
ADS_DD_SUBSCR_QUEUE_NAME = 1706; // replication queue
ADS_DD_SUBSCR_OPTIONS = 1707; // for future use
ADS_DD_SUBSCR_QUEUE_NAME_RELATIVE = 1708; // replication queue relative to the DD
ADS_DD_SUBSCR_PAUSED = 1709; // boolean flag: Replication paused on this subscription?
ADS_DD_SUBSCR_COMM_TCP_IP = 1710; // boolean flag: TRUE for TCP/IP communications
ADS_DD_SUBSCR_COMM_TCP_IP_V6 = 1711; // boolean flag: TRUE for TCP/IP V6 communications
ADS_DD_SUBSCR_COMM_UDP_IP = 1712; // boolean flag: TRUE for UDP/IP communications
ADS_DD_SUBSCR_COMM_IPX = 1713; // boolean flag: TRUE for IPX communications
ADS_DD_SUBSCR_OPTIONS_INTERNAL = 1714; // internal ID to get ALL options incl COMM types
ADS_DD_SUBSCR_COMM_TLS = 1715; // boolean flag: TRUE for TLS communications
ADS_DD_SUBSCR_CONNECTION_STR = 1716; // Free form connection string for new AdsConnect101 API
// AdsMgKillUser90 Constants
ADS_PROPERTY_UNSPECIFIED = $0000;
ADS_DONT_KILL_APPID = $0001;
ADS_DD_LEVEL_0 = 0;
ADS_DD_LEVEL_1 = 1;
ADS_DD_LEVEL_2 = 2;
// Referential Integrity (RI) update and delete rules
ADS_DD_RI_CASCADE = 1;
ADS_DD_RI_RESTRICT = 2;
ADS_DD_RI_SETNULL = 3;
ADS_DD_RI_SETDEFAULT = 4;
// Default Field Value Options
ADS_DD_DFV_UNKNOWN = 1;
ADS_DD_DFV_NONE = 2;
ADS_DD_DFV_VALUES_STORED = 3;
// Supported permissions in the data dictionary
ADS_PERMISSION_NONE = $00000000;
ADS_PERMISSION_READ = $00000001;
ADS_PERMISSION_UPDATE = $00000002;
ADS_PERMISSION_EXECUTE = $00000004;
ADS_PERMISSION_INHERIT = $00000008;
ADS_PERMISSION_INSERT = $00000010;
ADS_PERMISSION_DELETE = $00000020;
ADS_PERMISSION_LINK_ACCESS = $00000040;
ADS_PERMISSION_CREATE = $00000080;
ADS_PERMISSION_ALTER = $00000100;
ADS_PERMISSION_DROP = $00000200;
ADS_PERMISSION_WITH_GRANT = $80000000;
ADS_PERMISSION_ALL_WITH_GRANT = $8FFFFFFF;
ADS_PERMISSION_ALL = $FFFFFFFF;
// special code that can be used as the input to specify
// which special permission to retrieve.
ADS_GET_PERMISSIONS_WITH_GRANT = $8000FFFF;
ADS_GET_PERMISSIONS_CREATE = $FFFF0080;
ADS_GET_PERMISSIONS_CREATE_WITH_GRANT = $8FFFFF8F;
// Link DD options
ADS_LINK_GLOBAL = $00000001;
ADS_LINK_AUTH_ACTIVE_USER = $00000002;
ADS_LINK_PATH_IS_STATIC = $00000004;
// Trigger event types
ADS_TRIGEVENT_INSERT = 1;
ADS_TRIGEVENT_UPDATE = 2;
ADS_TRIGEVENT_DELETE = 3;
// Dictionary (system) trigger event types
// >= v 12
ADS_TRIGEVENT_OPEN_TABLE = 4;
ADS_TRIGEVENT_CLOSE_TABLE = 5;
ADS_TRIGEVENT_CONNECT = 6;
ADS_TRIGEVENT_DISCONNECT = 7;
// Trigger types
ADS_TRIGTYPE_BEFORE = $00000001;
ADS_TRIGTYPE_INSTEADOF = $00000002;
ADS_TRIGTYPE_AFTER = $00000004;
ADS_TRIGTYPE_CONFLICTON = $00000008;
// Trigger container types
ADS_TRIG_WIN32DLL = 1;
ADS_TRIG_COM = 2;
ADS_TRIG_SCRIPT = 3;
// Trigger options, if changed or adding more please inspect code
// in RemoveTriggerFromDictionary
ADS_TRIGOPTIONS_NO_VALUES = $00000000;
ADS_TRIGOPTIONS_WANT_VALUES = $00000001;
ADS_TRIGOPTIONS_WANT_MEMOS_AND_BLOBS = $00000002;
ADS_TRIGOPTIONS_DEFAULT = $00000003; // default is to include vals and memos
ADS_TRIGOPTIONS_NO_TRANSACTION = $00000004; // don't use implicit transactions
// Table permission verification levels.
// level 1 is all columns searchable, even those without permission.
// level 2 is default. Permission to the column is required to search or filter on a column.
// level 3 is most restricted. Only static SQL cursor is allowed.
ADS_DD_TABLE_PERMISSION_LEVEL_1 = 1;
ADS_DD_TABLE_PERMISSION_LEVEL_2 = 2;
ADS_DD_TABLE_PERMISSION_LEVEL_3 = 3;
// AdsDDRenameObject options
ADS_KEEP_TABLE_FILE_NAME = $00000001;
// AdsDDCreateArticle options
ADS_IDENTIFY_BY_PRIMARY = $00000001;
ADS_IDENTIFY_BY_ALL = $00000002;
// AdsDDCreateSubscription options
ADS_SUBSCR_QUEUE_IS_STATIC = $00000001;
ADS_SUBSCR_AIS_TARGET = $00000002; // use AIS to connect to target
ADS_SUBSCR_IGNORE_FAILED_REP = $00000004; // Delete failed replication updates from the queue
ADS_SUBSCR_LOG_FAILED_REP_DATA = $00000008; // if set, show data of failed replication updates in
// the error log.
//ADS_UDP_IP_CONNECTION = $00000020 // These connection type constants are stored in the
//ADS_IPX_CONNECTION = $00000040 // options of the subscription, so don't use these values
//ADS_TCP_IP_CONNECTION = $00000080 // for other subscription properties.
//ADS_TCP_IP_V6_CONNECTION = $00000100
// AdsGetFieldLength10 options
ADS_CODEUNIT_LENGTH = ADS_DEFAULT; // length in code units (characters)
ADS_BYTE_LENGTH = $00000001; // length in bytes
ADS_BYTE_LENGTH_IN_BUFFER = $00000002; // physical length of data in bytes in the record buffer
// Options for AdsFindServers
ADS_FS_MULTICAST_ONLY = $00000001; // Only perform multicast step
ADS_FS_CONNECT_ALL = $00000002; // Attempt to connect to every address returned
// in order to gather server name
// Table caching property modes, used with AdsDDSetTableProperty etc.
ADS_TABLE_CACHE_NONE = $0000;
ADS_TABLE_CACHE_READS = $0001;
ADS_TABLE_CACHE_WRITES = $0002;
// Connection string encryption options as strings.
ADS_ENCRYPT_STRING_RC4 = 'RC4';
ADS_ENCRYPT_STRING_AES128 = 'AES128';
ADS_ENCRYPT_STRING_AES256 = 'AES256';
// Connection string cipher suite options as strings.
ADS_CIPHER_SUITE_STRING_RC4 = 'RC4-MD5';
ADS_CIPHER_SUITE_STRING_AES128 = 'AES128-SHA';
ADS_CIPHER_SUITE_STRING_AES256 = 'AES256-SHA';
// System alias which always resolves to the root dictionary
// defined by ADS_ROOT_DICTIONARY server configuration setting
ADS_ROOT_DD_ALIAS = '__rootdd';
// Options for the AdsGetKeyFilter
ADS_FILTER_FORMAT_ODATA = $00000001;
ADS_FILTER_ENCODE_UTF8 = $00000002;
type
// stored procedure functions must be of this type
TSTORED_PROCEDURE_PTR = function (
ulConnectionID: UNSIGNED32; // (I) value used to associate a user/connection
// and can be used to track the state
pucUserName: PUNSIGNED8; // (I) the user name who invoked this procedure
pucPassword: PUNSIGNED8; // (I) the user's password in encrypted form
pucProcName: PUNSIGNED8; // (I) the stored procedure name
ulRecNum: PUNSIGNED32; // (I) reserved for triggers
pucTable1: PUNSIGNED8; // (I) table one. For Stored Proc this table
// contains all input parameters. For
// triggers, it contains the original field
// values if the trigger is an OnUpdate or
// OnDelete
pucTable2: PUNSIGNED8 // (I) table two. For Stored Proc this table
// is empty and the users function will
// optionally add rows to it as output.
// For triggers, it contains the new field
// values if the trigger is an OnUpdate or
// OnInsert
): UNSIGNED32; {$IFDEF WIN32} stdcall; {$ENDIF} {$IFDEF POSIX} cdecl; {$ENDIF}
TSTARTUP_PROCEDURE_PTR = function (
ulConnectionID: UNSIGNED32; // (I) value used to associate a user/connection
// and can be used to track the state
pucUserName: PUNSIGNED8; // (I) the user name who invoked this procedure
pucPassword: PUNSIGNED8 // (I) the user's password in encrypted form
): UNSIGNED32; {$IFDEF WIN32} stdcall; {$ENDIF} {$IFDEF POSIX} cdecl; {$ENDIF}
TSHUTDOWN_PROCEDURE_PTR = function (
ulConnectionID: UNSIGNED32; // (I) value used to associate a user/connection
// and can be used to track the state
pucUserName: PUNSIGNED8; // (I) the user name who invoked this procedure
pucPassword: PUNSIGNED8 // (I) the user's password in encrypted form
): UNSIGNED32; {$IFDEF WIN32} stdcall; {$ENDIF} {$IFDEF POSIX} cdecl; {$ENDIF}
TSTORED_PROCEDURE2_PTR = function (
ulConnectionID: UNSIGNED32; // (I) value used to associate a user/connection
// and can be used to track the state
hConnection: ADSHANDLE; // (I) active connection to be used by the procedure
pulNumRowsAffected: PUNSIGNED32 // (O) the number of rows affected
): UNSIGNED32; {$IFDEF WIN32} stdcall; {$ENDIF} {$IFDEF POSIX} cdecl; {$ENDIF}
TSTARTUP_PROCEDURE2_PTR = function (
ulConnectionID: UNSIGNED32; // (I) value used to associate a user/connection
// and can be used to track the state
hConnection: ADSHANDLE // (I) active connection to be used by the procedure
): UNSIGNED32; {$IFDEF WIN32} stdcall; {$ENDIF} {$IFDEF POSIX} cdecl; {$ENDIF}
TSHUTDOWN_PROCEDURE2_PTR = function (
ulConnectionID: UNSIGNED32; // (I) value used to associate a user/connection
// and can be used to track the state
hConnection: ADSHANDLE // (I) active connection to be used by the procedure
): UNSIGNED32; {$IFDEF WIN32} stdcall; {$ENDIF} {$IFDEF POSIX} cdecl; {$ENDIF}
TTRIGGER_FUNCTION_PTR = function (
ulConnectionID: UNSIGNED32; // (I) Unique ID identifying the user causing this trig
hConnection: ADSHANDLE; // (I) Active ACE connection handle user can perform
// operations on
pucTriggerName: PUNSIGNED8; // (I) Name of trigger in the dictionary
pucTableName: PUNSIGNED8; // (I) Name of the base table that caused the trigger
ulEventType: UNSIGNED32; // (I) Flag with event type (insert, update, etc.)
ulTriggerType: UNSIGNED32; // (I) Flag with trigger type (before, after, etc.)
ulRecNo: UNSIGNED32 // (I) Record number of the record being modified
): UNSIGNED32; {$IFDEF WIN32} stdcall; {$ENDIF} {$IFDEF POSIX} cdecl; {$ENDIF}
TGET_INTERFACE_VERSION_PTR = function (
): UNSIGNED32; {$IFDEF WIN32} stdcall; {$ENDIF} {$IFDEF POSIX} cdecl; {$ENDIF}
// This data type defines what type of function to pass to
// AdsRegisterCallbackFunction().
TCallbackFunction = function(usPercent: UNSIGNED16; ulCallbackID: UNSIGNED32): UNSIGNED32;
{$IFDEF WIN32} stdcall; {$ENDIF} {$IFDEF POSIX} cdecl; {$ENDIF}
TCallbackFunction101 = function(usPercent: UNSIGNED16; qCallbackID: SIGNED64): UNSIGNED32;
{$IFDEF WIN32} stdcall; {$ENDIF} {$IFDEF POSIX} cdecl; {$ENDIF}
// This data type defines what type of function to pass to
// AdsRegisterProgressCallback().
TProgressCallback = function(usPercent: UNSIGNED16): UNSIGNED32;
{$IFDEF WIN32} stdcall; {$ENDIF} {$IFDEF POSIX} cdecl; {$ENDIF}
// This data type defines what type of function to pass to
// AdsRegisterSQLAbortFunc().
TSQLAbortFunc = function(): UNSIGNED32;
{$IFDEF WIN32} stdcall; {$ENDIF} {$IFDEF POSIX} cdecl; {$ENDIF}
// This data type defines the type of function that AdsRegisterUDF() takes
// as a parameter. This should be used to cast the real function, which has
// different parameters. See the documentation for AdsRegisterUDF for more
// information
TUDFFunc = function(): UNSIGNED32;
{$IFDEF WIN32} stdcall; {$ENDIF} {$IFDEF POSIX} cdecl; {$ENDIF}
// This type allows a numeric field value to be passed into functions
// that expect field names. If the user prefers to use column number,
// then calls like this can be made:
// ulRet = AdsGetDouble( hTable, ADSFIELD( 1 ), &dVal );
// Where the first column is a numeric value to retrieve.
ADSFIELD = PAceChar;
// With data dicitonaries it is possible for a table to have more than
// fifty index tags. If you need more than fifty tags you will
// need to declare a new array with a larger size.
ADSIndexArray = array[0..ADS_MAX_TAGS - 1] of ADSHANDLE;
PADSIndexArray = ^ADSIndexArray;
TAdsAddCustomKey = function( hIndex: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsAppendRecord = function( hTable: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsApplicationExit = function:UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsAtBOF = function( hTable: ADSHANDLE;
pbBof: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsAtEOF = function( hTable: ADSHANDLE;
pbEof: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsBeginTransaction = function( hConnect: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsBinaryToFile = function( hTable: ADSHANDLE;
pucFldName: PAceChar;
pucFileName: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsCacheOpenCursors = function( usOpen: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsCacheOpenTables = function( usOpen: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsCacheRecords = function( hTable: ADSHANDLE;
usNumRecords: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsCancelUpdate = function( hTable: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsCancelUpdate90 = function( hTable: ADSHANDLE;
ulOptions: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsCheckExistence = function( hConnect: ADSHANDLE;
pucFileName: PAceChar;
pusOnDisk: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsClearAllScopes = function( hTable: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsClearDefault = function:UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsClearFilter = function( hTable: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsClearRelation = function( hTableParent: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsClearScope = function( hIndex: ADSHANDLE;
usScopeOption: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsCloneTable = function( hTable: ADSHANDLE;
phClone: pADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsCloseAllIndexes = function( hTable: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsCloseAllTables = function:UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsCloseIndex = function( hIndex: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsCloseTable = function( hTable: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsCloseCachedTables = function( hConnection: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsCommitTransaction = function( hConnect: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsConnect = function( pucServerName: PAceChar;
phConnect: pADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsConnect26 = function( pucServerName: PAceChar;
usServerTypes: UNSIGNED16;
phConnect: pADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsConnect60 = function( pucServerPath: PAceChar;
usServerTypes: UNSIGNED16;
pucUserName: PAceChar;
pucPassword: PAceChar;
ulOptions: UNSIGNED32;
phConnect: pADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsConnect101 = function( pucConnectString: PAceChar;
phConnectionOptions: pADSHANDLE;
phConnect: pADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsClearCachePool = function( pucConnectString: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsReapUnusedConnections = function:UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsIsConnectionAlive = function( hConnect: ADSHANDLE;
pbConnectionIsAlive: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsContinue = function( hTable: ADSHANDLE;
pbFound: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsConvertTable = function( hObj: ADSHANDLE;
usFilterOption: UNSIGNED16;
pucFile: PAceChar;
usTableType: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsCopyTable = function( hObj: ADSHANDLE;
usFilterOption: UNSIGNED16;
pucFile: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsCopyTableContents = function( hObjFrom: ADSHANDLE;
hTableTo: ADSHANDLE;
usFilterOption: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsCopyTableStructure = function( hTable: ADSHANDLE;
pucFile: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsCreateIndex = function( hObj: ADSHANDLE;
pucFileName: PAceChar;
pucTag: PAceChar;
pucExpr: PAceChar;
pucCondition: PAceChar;
pucWhile: PAceChar;
ulOptions: UNSIGNED32;
phIndex: pADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsCreateIndex61 = function( hObj: ADSHANDLE;
pucFileName: PAceChar;
pucTag: PAceChar;
pucExpr: PAceChar;
pucCondition: PAceChar;
pucWhile: PAceChar;
ulOptions: UNSIGNED32;
ulPageSize: UNSIGNED32;
phIndex: pADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsCreateIndex90 = function( hObj: ADSHANDLE;
pucFileName: PAceChar;
pucTag: PAceChar;
pucExpr: PAceChar;
pucCondition: PAceChar;
pucWhile: PAceChar;
ulOptions: UNSIGNED32;
ulPageSize: UNSIGNED32;
pucCollation: PAceChar;
phIndex: pADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsCreateFTSIndex = function( hTable: ADSHANDLE;
pucFileName: PAceChar;
pucTag: PAceChar;
pucField: PAceChar;
ulPageSize: UNSIGNED32;
ulMinWordLen: UNSIGNED32;
ulMaxWordLen: UNSIGNED32;
usUseDefaultDelim: UNSIGNED16;
pvDelimiters: pointer;
usUseDefaultNoise: UNSIGNED16;
pvNoiseWords: pointer;
usUseDefaultDrop: UNSIGNED16;
pvDropChars: pointer;
usUseDefaultConditionals: UNSIGNED16;
pvConditionalChars: pointer;
pucCollation: PAceChar;
pucReserved1: PAceChar;
ulOptions: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsCreateTable = function( hConnection: ADSHANDLE;
pucName: PAceChar;
pucAlias: PAceChar;
usTableType: UNSIGNED16;
usCharType: UNSIGNED16;
usLockType: UNSIGNED16;
usCheckRights: UNSIGNED16;
usMemoSize: UNSIGNED16;
pucFields: PAceChar;
phTable: pADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsCreateTable71 = function( hConnection: ADSHANDLE;
pucName: PAceChar;
pucDBObjName: PAceChar;
usTableType: UNSIGNED16;
usCharType: UNSIGNED16;
usLockType: UNSIGNED16;
usCheckRights: UNSIGNED16;
usMemoSize: UNSIGNED16;
pucFields: PAceChar;
ulOptions: UNSIGNED32;
phTable: pADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsCreateTable90 = function( hConnection: ADSHANDLE;
pucName: PAceChar;
pucDBObjName: PAceChar;
usTableType: UNSIGNED16;
usCharType: UNSIGNED16;
usLockType: UNSIGNED16;
usCheckRights: UNSIGNED16;
usMemoSize: UNSIGNED16;
pucFields: PAceChar;
ulOptions: UNSIGNED32;
pucCollation: PAceChar;
phTable: pADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDCreate = function( pucDictionaryPath: PAceChar;
usEncrypt: UNSIGNED16;
pucDescription: PAceChar;
phDictionary: pADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDCreate101 = function( pucConnectString: PAceChar;
phConnectOptions: pADSHANDLE;
phDictionary: pADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDCreateRefIntegrity = function( hDictionary: ADSHANDLE;
pucRIName: PAceChar;
pucFailTable: PAceChar;
pucParentTableName: PAceChar;
pucParentTagName: PAceChar;
pucChildTableName: PAceChar;
pucChildTagName: PAceChar;
usUpdateRule: UNSIGNED16;
usDeleteRule: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDCreateRefIntegrity62 = function( hDictionary: ADSHANDLE;
pucRIName: PAceChar;
pucFailTable: PAceChar;
pucParentTableName: PAceChar;
pucParentTagName: PAceChar;
pucChildTableName: PAceChar;
pucChildTagName: PAceChar;
usUpdateRule: UNSIGNED16;
usDeleteRule: UNSIGNED16;
pucNoPrimaryError: PAceChar;
pucCascadeError: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDRemoveRefIntegrity = function( hDictionary: ADSHANDLE;
pucRIName: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDGetDatabaseProperty = function( hObject: ADSHANDLE;
usPropertyID: UNSIGNED16;
pvProperty: pointer;
pusPropertyLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDGetFieldProperty = function( hObject: ADSHANDLE;
pucTableName: PAceChar;
pucFieldName: PAceChar;
usPropertyID: UNSIGNED16;
pvProperty: pointer;
pusPropertyLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDGetIndexFileProperty = function( hObject: ADSHANDLE;
pucTableName: PAceChar;
pucIndexFileName: PAceChar;
usPropertyID: UNSIGNED16;
pvProperty: pointer;
pusPropertyLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDGetIndexProperty = function( hObject: ADSHANDLE;
pucTableName: PAceChar;
pucIndexName: PAceChar;
usPropertyID: UNSIGNED16;
pvProperty: pointer;
pusPropertyLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDGetLinkProperty = function( hConnect: ADSHANDLE;
pucLinkName: PAceChar;
usPropertyID: UNSIGNED16;
pvProperty: pointer;
pusPropertyLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDGetTableProperty = function( hObject: ADSHANDLE;
pucTableName: PAceChar;
usPropertyID: UNSIGNED16;
pvProperty: pointer;
pusPropertyLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDGetUserGroupProperty = function( hObject: ADSHANDLE;
pucUserGroupName: PAceChar;
usPropertyID: UNSIGNED16;
pvProperty: pointer;
pusPropertyLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDGetUserProperty = function( hObject: ADSHANDLE;
pucUserName: PAceChar;
usPropertyID: UNSIGNED16;
pvProperty: pointer;
pusPropertyLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDGetViewProperty = function( hObject: ADSHANDLE;
pucViewName: PAceChar;
usPropertyID: UNSIGNED16;
pvProperty: pointer;
pusPropertyLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDGetTriggerProperty = function( hObject: ADSHANDLE;
pucTriggerName: PAceChar;
usPropertyID: UNSIGNED16;
pvProperty: pointer;
pusPropertyLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDGetProcedureProperty = function( hObject: ADSHANDLE;
pucProcName: PAceChar;
usPropertyID: UNSIGNED16;
pvProperty: pointer;
pusPropertyLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDGetRefIntegrityProperty = function( hObject: ADSHANDLE;
pucRIName: PAceChar;
usPropertyID: UNSIGNED16;
pucProperty: PAceChar;
pusPropertyLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDGetPermissions = function( hDBConn: ADSHANDLE;
pucGrantee: PAceChar;
usObjectType: UNSIGNED16;
pucObjectName: PAceChar;
pucParentName: PAceChar;
usGetInherited: UNSIGNED16;
pulPermissions: PUNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDGrantPermission = function( hAdminConn: ADSHANDLE;
usObjectType: UNSIGNED16;
pucObjectName: PAceChar;
pucParentName: PAceChar;
pucGrantee: PAceChar;
ulPermissions: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDRevokePermission = function( hAdminConn: ADSHANDLE;
usObjectType: UNSIGNED16;
pucObjectName: PAceChar;
pucParentName: PAceChar;
pucGrantee: PAceChar;
ulPermissions: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDSetDatabaseProperty = function( hDictionary: ADSHANDLE;
usPropertyID: UNSIGNED16;
pvProperty: pointer;
usPropertyLen: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDSetFieldProperty = function( hDictionary: ADSHANDLE;
pucTableName: PAceChar;
pucFieldName: PAceChar;
usPropertyID: UNSIGNED16;
pvProperty: pointer;
usPropertyLen: UNSIGNED16;
usValidateOption: UNSIGNED16;
pucFailTable: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDSetProcedureProperty = function( hDictionary: ADSHANDLE;
pucProcedureName: PAceChar;
usPropertyID: UNSIGNED16;
pvProperty: pointer;
usPropertyLen: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDSetTableProperty = function( hDictionary: ADSHANDLE;
pucTableName: PAceChar;
usPropertyID: UNSIGNED16;
pvProperty: pointer;
usPropertyLen: UNSIGNED16;
usValidateOption: UNSIGNED16;
pucFailTable: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDSetUserGroupProperty = function( hDictionary: ADSHANDLE;
pucUserGroupName: PAceChar;
usPropertyID: UNSIGNED16;
pvProperty: pointer;
usPropertyLen: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDSetUserProperty = function( hDictionary: ADSHANDLE;
pucUserName: PAceChar;
usPropertyID: UNSIGNED16;
pvProperty: pointer;
usPropertyLen: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDSetViewProperty = function( hDictionary: ADSHANDLE;
pucViewName: PAceChar;
usPropertyID: UNSIGNED16;
pvProperty: pointer;
usPropertyLen: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDSetObjectAccessRights = function( hDictionary: ADSHANDLE;
pucObjectName: PAceChar;
pucAccessorName: PAceChar;
pucAllowedAccess: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDAddProcedure = function( hDictionary: ADSHANDLE;
pucName: PAceChar;
pucContainer: PAceChar;
pucProcName: PAceChar;
ulInvokeOption: UNSIGNED32;
pucInParams: PAceChar;
pucOutParams: PAceChar;
pucComments: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDAddProcedure100 = function( hDictionary: ADSHANDLE;
pucName: PAceChar;
pwcContainer: PWideChar;
pucProcName: PAceChar;
ulInvokeOption: UNSIGNED32;
pucInParams: PAceChar;
pucOutParams: PAceChar;
pucComments: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDAddTable = function( hDictionary: ADSHANDLE;
pucTableName: PAceChar;
pucTablePath: PAceChar;
usTableType: UNSIGNED16;
usCharType: UNSIGNED16;
pucIndexFiles: PAceChar;
pucComments: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDAddTable90 = function( hDictionary: ADSHANDLE;
pucTableName: PAceChar;
pucTablePath: PAceChar;
usTableType: UNSIGNED16;
usCharType: UNSIGNED16;
pucIndexFiles: PAceChar;
pucComments: PAceChar;
pucCollation: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDAddView = function( hDictionary: ADSHANDLE;
pucName: PAceChar;
pucComments: PAceChar;
pucSQL: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDAddView100 = function( hDictionary: ADSHANDLE;
pucName: PAceChar;
pucComments: PAceChar;
pwcSQL: PWideChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDCreateTrigger = function( hDictionary: ADSHANDLE;
pucName: PAceChar;
pucTableName: PAceChar;
ulTriggerType: UNSIGNED32;
ulEventTypes: UNSIGNED32;
ulContainerType: UNSIGNED32;
pucContainer: PAceChar;
pucFunctionName: PAceChar;
ulPriority: UNSIGNED32;
pucComments: PAceChar;
ulOptions: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDCreateTrigger100 = function( hDictionary: ADSHANDLE;
pucName: PAceChar;
pucTableName: PAceChar;
ulTriggerType: UNSIGNED32;
ulEventTypes: UNSIGNED32;
ulContainerType: UNSIGNED32;
pwcContainer: PWideChar;
pucFunctionName: PAceChar;
ulPriority: UNSIGNED32;
pucComments: PAceChar;
ulOptions: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDRemoveTrigger = function( hDictionary: ADSHANDLE;
pucName: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDAddIndexFile = function( hDictionary: ADSHANDLE;
pucTableName: PAceChar;
pucIndexFilePath: PAceChar;
pucComment: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDCreateUser = function( hDictionary: ADSHANDLE;
pucGroupName: PAceChar;
pucUserName: PAceChar;
pucPassword: PAceChar;
pucDescription: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDAddUserToGroup = function( hDictionary: ADSHANDLE;
pucGroupName: PAceChar;
pucUserName: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDRemoveUserFromGroup = function( hDictionary: ADSHANDLE;
pucGroupName: PAceChar;
pucUserName: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDDeleteUser = function( hDictionary: ADSHANDLE;
pucUserName: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDCreateUserGroup = function( hDictionary: ADSHANDLE;
pucGroupName: PAceChar;
pucDescription: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDDeleteUserGroup = function( hDictionary: ADSHANDLE;
pucGroupName: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDDeleteIndex = function( hDictionary: ADSHANDLE;
pucTableName: PAceChar;
pucIndexName: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDRemoveIndexFile = function( hDictionary: ADSHANDLE;
pucTableName: PAceChar;
pucIndexFileName: PAceChar;
usDeleteFile: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDRemoveProcedure = function( hDictionary: ADSHANDLE;
pucName: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDRemoveTable = function( hObject: ADSHANDLE;
pucTableName: PAceChar;
usDeleteFiles: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDRemoveView = function( hDictionary: ADSHANDLE;
pucName: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDRenameObject = function( hDictionary: ADSHANDLE;
pucObjectName: PAceChar;
pucNewObjectName: PAceChar;
usObjectType: UNSIGNED16;
ulOptions: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDMoveObjectFile = function( hDictionary: ADSHANDLE;
usObjectType: UNSIGNED16;
pucObjectName: PAceChar;
pucNewPath: PAceChar;
pucIndexFiles: PAceChar;
pucParent: PAceChar;
ulOptions: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDFindFirstObject = function( hObject: ADSHANDLE;
usFindObjectType: UNSIGNED16;
pucParentName: PAceChar;
pucObjectName: PAceChar;
pusObjectNameLen: PUNSIGNED16;
phFindHandle: pADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDFindNextObject = function( hObject: ADSHANDLE;
hFindHandle: ADSHANDLE;
pucObjectName: PAceChar;
pusObjectNameLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDFindClose = function( hObject: ADSHANDLE;
hFindHandle: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDCreateLink = function( hDBConn: ADSHANDLE;
pucLinkAlias: PAceChar;
pucLinkedDDPath: PAceChar;
pucUserName: PAceChar;
pucPassword: PAceChar;
ulOptions: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDModifyLink = function( hDBConn: ADSHANDLE;
pucLinkAlias: PAceChar;
pucLinkedDDPath: PAceChar;
pucUserName: PAceChar;
pucPassword: PAceChar;
ulOptions: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDDropLink = function( hDBConn: ADSHANDLE;
pucLinkedDD: PAceChar;
usDropGlobal: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDCreatePublication = function( hDictionary: ADSHANDLE;
pucPublicationName: PAceChar;
pucComments: PAceChar;
ulOptions: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDGetPublicationProperty = function( hObject: ADSHANDLE;
pucPublicationName: PAceChar;
usPropertyID: UNSIGNED16;
pvProperty: pointer;
pusPropertyLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDSetPublicationProperty = function( hDictionary: ADSHANDLE;
pucPublicationName: PAceChar;
usPropertyID: UNSIGNED16;
pvProperty: pointer;
usPropertyLen: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDDeletePublication = function( hDictionary: ADSHANDLE;
pucPublicationName: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDCreateArticle = function( hDictionary: ADSHANDLE;
pucPublicationName: PAceChar;
pucObjectName: PAceChar;
pucRowIdentColumns: PAceChar;
pucFilter: PAceChar;
ulOptions: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDCreateArticle100 = function( hDictionary: ADSHANDLE;
pucPublicationName: PAceChar;
pucObjectName: PAceChar;
pucRowIdentColumns: PAceChar;
pwcFilter: PWideChar;
ulOptions: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDGetArticleProperty = function( hObject: ADSHANDLE;
pucPublicationName: PAceChar;
pucObjectName: PAceChar;
usPropertyID: UNSIGNED16;
pvProperty: pointer;
pusPropertyLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDSetArticleProperty = function( hDictionary: ADSHANDLE;
pucPublicationName: PAceChar;
pucObjectName: PAceChar;
usPropertyID: UNSIGNED16;
pvProperty: pointer;
usPropertyLen: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDDeleteArticle = function( hDictionary: ADSHANDLE;
pucPublicationName: PAceChar;
pucObjectName: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDCreateSubscription = function( hDictionary: ADSHANDLE;
pucSubscriptionName: PAceChar;
pucPublicationName: PAceChar;
pucTarget: PAceChar;
pucUser: PAceChar;
pucPassword: PAceChar;
pucReplicationQueue: PAceChar;
usForward: UNSIGNED16;
pucComments: PAceChar;
ulOptions: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDGetSubscriptionProperty = function( hObject: ADSHANDLE;
pucSubscriptionName: PAceChar;
usPropertyID: UNSIGNED16;
pvProperty: pointer;
pusPropertyLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDSetSubscriptionProperty = function( hDictionary: ADSHANDLE;
pucSubscriptionName: PAceChar;
usPropertyID: UNSIGNED16;
pvProperty: pointer;
usPropertyLen: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDDeleteSubscription = function( hDictionary: ADSHANDLE;
pucSubscriptionName: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDecryptRecord = function( hTable: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDecryptTable = function( hTable: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDeleteCustomKey = function( hIndex: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDeleteIndex = function( hIndex: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDeleteRecord = function( hTable: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetKeyColumn = function( hCursor: ADSHANDLE;
pucKeyColumn: PAceChar;
pusLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetKeyFilter = function( hTable: ADSHANDLE;
pucValuesTable: PUNSIGNED8;
ulOptions: UNSIGNED32;
pucFilter: PUNSIGNED8;
pulLength: PUNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDisableEncryption = function( hTable: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDisableLocalConnections = function:UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDisconnect = function( hConnect: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsEnableEncryption = function( hTable: ADSHANDLE;
pucPassword: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsEncryptRecord = function( hTable: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsEncryptTable = function( hTable: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsEvalLogicalExpr = function( hTable: ADSHANDLE;
pucExpr: PAceChar;
pbResult: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsEvalLogicalExprW = function( hTable: ADSHANDLE;
pwcExpr: PWideChar;
pbResult: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsEvalNumericExpr = function( hTable: ADSHANDLE;
pucExpr: PAceChar;
pdResult: pDOUBLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsEvalStringExpr = function( hTable: ADSHANDLE;
pucExpr: PAceChar;
pucResult: PAceChar;
pusLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsEvalTestExpr = function( hTable: ADSHANDLE;
pucExpr: PAceChar;
pusType: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsExtractKey = function( hIndex: ADSHANDLE;
pucKey: PAceChar;
pusLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsFailedTransactionRecovery = function( pucServer: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsFileToBinary = function( hTable: ADSHANDLE;
pucFldName: PAceChar;
usBinaryType: UNSIGNED16;
pucFileName: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsFindConnection = function( pucServerName: PAceChar;
phConnect: pADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsFindConnection25 = function( pucFullPath: PAceChar;
phConnect: pADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsFindClose = function( hConnect: ADSHANDLE;
lHandle: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsFindFirstTable = function( hConnect: ADSHANDLE;
pucFileMask: PAceChar;
pucFirstFile: PAceChar;
pusFileLen: PUNSIGNED16;
plHandle: pADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsFindNextTable = function( hConnect: ADSHANDLE;
lHandle: ADSHANDLE;
pucFileName: PAceChar;
pusFileLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsFindFirstTable62 = function( hConnect: ADSHANDLE;
pucFileMask: PAceChar;
pucFirstDD: PAceChar;
pusDDLen: PUNSIGNED16;
pucFirstFile: PAceChar;
pusFileLen: PUNSIGNED16;
plHandle: pADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsFindNextTable62 = function( hConnect: ADSHANDLE;
lHandle: ADSHANDLE;
pucDDName: PAceChar;
pusDDLen: PUNSIGNED16;
pucFileName: PAceChar;
pusFileLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetAllIndexes = function( hTable: ADSHANDLE;
ahIndex: PADSIndexArray;
pusArrayLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetFTSIndexes = function( hTable: ADSHANDLE;
ahIndex: PADSIndexArray;
pusArrayLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetFTSIndexInfo = function( hIndex: ADSHANDLE;
pucOutput: PAceChar;
pulBufLen: PUNSIGNED32;
ppucField: pPChar;
pulMinWordLen: PUNSIGNED32;
pulMaxWordLen: PUNSIGNED32;
ppucDelimiters: pPChar;
ppucNoiseWords: pPChar;
ppucDropChars: pPChar;
ppucConditionalChars: pPChar;
ppucReserved1: pPChar;
ppucReserved2: pPChar;
pulOptions: PUNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetFTSIndexInfoW = function( hIndex: ADSHANDLE;
pwcOutput: PWideChar;
pulBufLen: PUNSIGNED32;
ppwcField: pPWideChar;
pulMinWordLen: PUNSIGNED32;
pulMaxWordLen: PUNSIGNED32;
ppwcDelimiters: pPWideChar;
ppwcNoiseWords: pPWideChar;
ppwcDropChars: pPWideChar;
ppwcConditionalChars: pPWideChar;
ppwcReserved1: pPWideChar;
ppwcReserved2: pPWideChar;
pulOptions: PUNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetAllLocks = function( hTable: ADSHANDLE;
aulLocks: pointer;
pusArrayLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetAllTables = function( ahTable: pointer;
pusArrayLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetBinary = function( hTable: ADSHANDLE;
pucFldName: PAceChar;
ulOffset: UNSIGNED32;
pucBuf: PAceBinary;
pulLen: PUNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetBinaryLength = function( hTable: ADSHANDLE;
pucFldName: PAceChar;
pulLength: PUNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetBookmark = function( hTable: ADSHANDLE;
phBookmark: pADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetBookmark60 = function( hObj: ADSHANDLE;
pucBookmark: PAceChar;
pulLength: PUNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetBookmarkLength = function( hObj: ADSHANDLE;
pulLength: PUNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsCompareBookmarks = function( pucBookmark1: PAceChar;
pucBookmark2: PAceChar;
plResult: pSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetCollationLang = function( pucLang: PAceChar;
pusLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetCollation = function( hConnect: ADSHANDLE;
pucCollation: PAceChar;
pusLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetIntProperty = function( hObj: ADSHANDLE;
ulPropertyID: UNSIGNED32;
pulProperty: PUNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetConnectionType = function( hConnect: ADSHANDLE;
pusConnectType: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetTransactionCount = function( hConnect: ADSHANDLE;
pulTransactionCount: PUNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetConnectionPath = function( hConnect: ADSHANDLE;
pucConnectionPath: PAceChar;
pusLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetConnectionProperty = function( hConnect: ADSHANDLE;
usPropertyID: UNSIGNED16;
pvProperty: pointer;
pulPropertyLen: PUNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetDate = function( hTable: ADSHANDLE;
pucFldName: PAceChar;
pucBuf: PAceChar;
pusLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetDateFormat = function( pucFormat: PAceChar;
pusLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetDateFormat60 = function( hConnect: ADSHANDLE;
pucFormat: PAceChar;
pusLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetDecimals = function( pusDecimals: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetDefault = function( pucDefault: PAceChar;
pusLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetDeleted = function( pbUseDeleted: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetDouble = function( hTable: ADSHANDLE;
pucFldName: PAceChar;
pdValue: pDOUBLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetEpoch = function( pusCentury: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetErrorString = function( ulErrCode: UNSIGNED32;
pucBuf: PAceChar;
pusBufLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetExact = function( pbExact: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetExact22 = function( hObj: ADSHANDLE;
pbExact: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetField = function( hTable: ADSHANDLE;
pucFldName: PAceChar;
pucBuf: PAceChar;
pulLen: PUNSIGNED32;
usOption: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetFieldW = function( hObj: ADSHANDLE;
pucFldName: PAceChar;
pwcBuf: PWideChar;
pulLen: PUNSIGNED32;
usOption: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetFieldDecimals = function( hTable: ADSHANDLE;
pucFldName: PAceChar;
pusDecimals: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetFieldLength = function( hTable: ADSHANDLE;
pucFldName: PAceChar;
pulLength: PUNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetFieldName = function( hTable: ADSHANDLE;
usFld: UNSIGNED16;
pucName: PAceChar;
pusBufLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetFieldNum = function( hTable: ADSHANDLE;
pucFldName: PAceChar;
pusNum: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetFieldOffset = function( hTable: ADSHANDLE;
pucFldName: PAceChar;
pulOffset: PUNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetFieldType = function( hTable: ADSHANDLE;
pucFldName: PAceChar;
pusType: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetFilter = function( hTable: ADSHANDLE;
pucFilter: PAceChar;
pusLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetHandleLong = function( hObj: ADSHANDLE;
pulVal: PUNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetHandleType = function( hObj: ADSHANDLE;
pusType: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetIndexCondition = function( hIndex: ADSHANDLE;
pucExpr: PAceChar;
pusLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetIndexExpr = function( hIndex: ADSHANDLE;
pucExpr: PAceChar;
pusLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetIndexFilename = function( hIndex: ADSHANDLE;
usOption: UNSIGNED16;
pucName: PAceChar;
pusLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetIndexHandle = function( hTable: ADSHANDLE;
pucIndexOrder: PAceChar;
phIndex: pADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetIndexHandleByOrder = function( hTable: ADSHANDLE;
usOrderNum: UNSIGNED16;
phIndex: pADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetIndexHandleByExpr = function( hTable: ADSHANDLE;
pucExpr: PAceChar;
ulDescending: UNSIGNED32;
phIndex: pADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetIndexName = function( hIndex: ADSHANDLE;
pucName: PAceChar;
pusLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetIndexOrderByHandle = function( hIndex: ADSHANDLE;
pusIndexOrder: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetJulian = function( hTable: ADSHANDLE;
pucFldName: PAceChar;
plDate: pSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetKeyCount = function( hIndex: ADSHANDLE;
usFilterOption: UNSIGNED16;
pulCount: PUNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetKeyNum = function( hIndex: ADSHANDLE;
usFilterOption: UNSIGNED16;
pulKey: PUNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetKeyLength = function( hIndex: ADSHANDLE;
pusKeyLength: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetKeyType = function( hIndex: ADSHANDLE;
usKeyType: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetLastError = function( pulErrCode: PUNSIGNED32;
pucBuf: PAceChar;
pusBufLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetLastTableUpdate = function( hTable: ADSHANDLE;
pucDate: PAceChar;
pusDateLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetLogical = function( hTable: ADSHANDLE;
pucFldName: PAceChar;
pbValue: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetLong = function( hTable: ADSHANDLE;
pucFldName: PAceChar;
plValue: pSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetLongLong = function( hTable: ADSHANDLE;
pucFldName: PAceChar;
pqValue: pSIGNED64 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetMemoBlockSize = function( hTable: ADSHANDLE;
pusBlockSize: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetMemoLength = function( hTable: ADSHANDLE;
pucFldName: PAceChar;
pulLength: PUNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetMemoDataType = function( hTable: ADSHANDLE;
pucFldName: PAceChar;
pusType: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetMilliseconds = function( hTable: ADSHANDLE;
pucFldName: PAceChar;
plTime: pSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetMoney = function( hTbl: ADSHANDLE;
pucFldName: PAceChar;
pqValue: pSIGNED64 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetActiveLinkInfo = function( hDBConn: ADSHANDLE;
usLinkNum: UNSIGNED16;
pucLinkInfo: PAceChar;
pusBufferLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetNumActiveLinks = function( hDBConn: ADSHANDLE;
pusNumLinks: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetNumFields = function( hTable: ADSHANDLE;
pusCount: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetNumIndexes = function( hTable: ADSHANDLE;
pusNum: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetNumFTSIndexes = function( hTable: ADSHANDLE;
pusNum: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetNumLocks = function( hTable: ADSHANDLE;
pusNum: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetNumOpenTables = function( pusNum: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetRecord = function( hTable: ADSHANDLE;
pucRec: PAceChar;
pulLen: PUNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetRecordCount = function( hTable: ADSHANDLE;
usFilterOption: UNSIGNED16;
pulCount: PUNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetRecordNum = function( hTable: ADSHANDLE;
usFilterOption: UNSIGNED16;
pulRec: PUNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetRecordLength = function( hTable: ADSHANDLE;
pulLength: PUNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetRecordCRC = function( hTable: ADSHANDLE;
pulCRC: PUNSIGNED32;
ulOptions: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetRelKeyPos = function( hIndex: ADSHANDLE;
pdPos: pDOUBLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetScope = function( hIndex: ADSHANDLE;
usScopeOption: UNSIGNED16;
pucScope: PAceChar;
pusBufLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetSearchPath = function( pucPath: PAceChar;
pusLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetServerName = function( hConnect: ADSHANDLE;
pucName: PAceChar;
pusLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetServerTime = function( hConnect: ADSHANDLE;
pucDateBuf: PAceChar;
pusDateBufLen: PUNSIGNED16;
plTime: pSIGNED32;
pucTimeBuf: PAceChar;
pusTimeBufLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetShort = function( hTable: ADSHANDLE;
pucFldName: PAceChar;
psValue: pSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetString = function( hTable: ADSHANDLE;
pucFldName: PAceChar;
pucBuf: PAceChar;
pulLen: PUNSIGNED32;
usOption: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetStringW = function( hObj: ADSHANDLE;
pucFldName: PAceChar;
pwcBuf: PWideChar;
pulLen: PUNSIGNED32;
usOption: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetTableAlias = function( hTable: ADSHANDLE;
pucAlias: PAceChar;
pusLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetTableCharType = function( hTable: ADSHANDLE;
pusCharType: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetTableConnection = function( hTable: ADSHANDLE;
phConnect: pADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetTableFilename = function( hTable: ADSHANDLE;
usOption: UNSIGNED16;
pucName: PAceChar;
pusLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetTableHandle = function( pucName: PAceChar;
phTable: pADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetTableHandle25 = function( hConnect: ADSHANDLE;
pucName: PAceChar;
phTable: pADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetTableLockType = function( hTable: ADSHANDLE;
pusLockType: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetTableMemoSize = function( hTable: ADSHANDLE;
pusMemoSize: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetTableOpenOptions = function( hTable: ADSHANDLE;
pulOptions: PUNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetTableRights = function( hTable: ADSHANDLE;
pusRights: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetTableType = function( hTable: ADSHANDLE;
pusType: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetTime = function( hTable: ADSHANDLE;
pucFldName: PAceChar;
pucBuf: PAceChar;
pusLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetVersion = function( pulMajor: PUNSIGNED32;
pulMinor: PUNSIGNED32;
pucLetter: PAceChar;
pucDesc: PAceChar;
pusDescLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGotoBookmark = function( hTable: ADSHANDLE;
hBookmark: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGotoBookmark60 = function( hObj: ADSHANDLE;
pucBookmark: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGotoBottom = function( hObj: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGotoRecord = function( hTable: ADSHANDLE;
ulRec: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGotoTop = function( hObj: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsImageToClipboard = function( hTable: ADSHANDLE;
pucFldName: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsInTransaction = function( hConnect: ADSHANDLE;
pbInTrans: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsIsEmpty = function( hTable: ADSHANDLE;
pucFldName: PAceChar;
pbEmpty: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsIsExprValid = function( hTable: ADSHANDLE;
pucExpr: PAceChar;
pbValid: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsIsFound = function( hObj: ADSHANDLE;
pbFound: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsIsIndexCompound = function( hIndex: ADSHANDLE;
pbCompound: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsIsIndexCandidate = function( hIndex: ADSHANDLE;
pbCandidate: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsIsIndexNullable = function( hIndex: ADSHANDLE;
pbNullable: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsIsIndexCustom = function( hIndex: ADSHANDLE;
pbCustom: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsIsIndexDescending = function( hIndex: ADSHANDLE;
pbDescending: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsIsIndexPrimaryKey = function( hIndex: ADSHANDLE;
pbPrimaryKey: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsIsIndexFTS = function( hIndex: ADSHANDLE;
pbFTS: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsIsIndexUnique = function( hIndex: ADSHANDLE;
pbUnique: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsIsRecordDeleted = function( hTable: ADSHANDLE;
pbDeleted: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsIsRecordEncrypted = function( hTable: ADSHANDLE;
pbEncrypted: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsIsRecordLocked = function( hTable: ADSHANDLE;
ulRec: UNSIGNED32;
pbLocked: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsIsRecordVisible = function( hObj: ADSHANDLE;
pbVisible: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsIsServerLoaded = function( pucServer: PAceChar;
pbLoaded: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsIsTableEncrypted = function( hTable: ADSHANDLE;
pbEncrypted: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsIsTableLocked = function( hTable: ADSHANDLE;
pbLocked: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsLocate = function( hTable: ADSHANDLE;
pucExpr: PAceChar;
bForward: UNSIGNED16;
pbFound: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsLockRecord = function( hTable: ADSHANDLE;
ulRec: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsLockTable = function( hTable: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsLookupKey = function( hIndex: ADSHANDLE;
pucKey: PAceChar;
usKeyLen: UNSIGNED16;
usDataType: UNSIGNED16;
pbFound: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsMgConnect = function( pucServerName: PAceChar;
pucUserName: PAceChar;
pucPassword: PAceChar;
phMgmtHandle: pADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsMgDisconnect = function( hMgmtHandle: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsMgGetCommStats = function( hMgmtHandle: ADSHANDLE;
pstCommStats: pADS_MGMT_COMM_STATS;
pusStructSize: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsMgResetCommStats = function( hMgmtHandle: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsMgDumpInternalTables = function( hMgmtHandle: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsMgGetConfigInfo = function( hMgmtHandle: ADSHANDLE;
pstConfigValues: pADS_MGMT_CONFIG_PARAMS;
pusConfigValuesStructSize: PUNSIGNED16;
pstConfigMemory: pADS_MGMT_CONFIG_MEMORY;
pusConfigMemoryStructSize: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsMgGetInstallInfo = function( hMgmtHandle: ADSHANDLE;
pstInstallInfo: pADS_MGMT_INSTALL_INFO;
pusStructSize: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsMgGetActivityInfo = function( hMgmtHandle: ADSHANDLE;
pstActivityInfo: pADS_MGMT_ACTIVITY_INFO;
pusStructSize: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsMgGetUserNames = function( hMgmtHandle: ADSHANDLE;
pucFileName: PAceChar;
astUserInfo: PADSMgUserArray;
pusArrayLen: PUNSIGNED16;
pusStructSize: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsMgGetOpenTables = function( hMgmtHandle: ADSHANDLE;
pucUserName: PAceChar;
usConnNumber: UNSIGNED16;
astOpenTableInfo: PADSMgTableArray;
pusArrayLen: PUNSIGNED16;
pusStructSize: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsMgGetOpenIndexes = function( hMgmtHandle: ADSHANDLE;
pucTableName: PAceChar;
pucUserName: PAceChar;
usConnNumber: UNSIGNED16;
astOpenIndexInfo: PADSMgIndexArray;
pusArrayLen: PUNSIGNED16;
pusStructSize: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsMgGetLocks = function( hMgmtHandle: ADSHANDLE;
pucTableName: PAceChar;
pucUserName: PAceChar;
usConnNumber: UNSIGNED16;
astRecordInfo: PADSMgLocksArray;
pusArrayLen: PUNSIGNED16;
pusStructSize: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsMgGetServerType = function( hMgmtHandle: ADSHANDLE;
pusServerType: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsMgKillUser = function( hMgmtHandle: ADSHANDLE;
pucUserName: PAceChar;
usConnNumber: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsMgGetWorkerThreadActivity = function( hMgmtHandle: ADSHANDLE;
astWorkerThreadActivity: PADSMgThreadsArray;
pusArrayLen: PUNSIGNED16;
pusStructSize: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsMgGetLockOwner = function( hMgmtHandle: ADSHANDLE;
pucTableName: PAceChar;
ulRecordNumber: UNSIGNED32;
pstUserInfo: pADS_MGMT_USER_INFO;
pusStructSize: PUNSIGNED16;
pusLockType: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsNullTerminateStrings = function( bNullTerminate: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsOpenIndex = function( hTable: ADSHANDLE;
pucName: PAceChar;
ahIndex: PADSIndexArray;
pusArrayLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsOpenTable = function( hConnect: ADSHANDLE;
pucName: PAceChar;
pucAlias: PAceChar;
usTableType: UNSIGNED16;
usCharType: UNSIGNED16;
usLockType: UNSIGNED16;
usCheckRights: UNSIGNED16;
ulOptions: UNSIGNED32;
phTable: pADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsOpenTable90 = function( hConnect: ADSHANDLE;
pucName: PAceChar;
pucAlias: PAceChar;
usTableType: UNSIGNED16;
usCharType: UNSIGNED16;
usLockType: UNSIGNED16;
usCheckRights: UNSIGNED16;
ulOptions: UNSIGNED32;
pucCollation: PAceChar;
phTable: pADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsOpenTable101 = function( hConnect: ADSHANDLE;
pucName: PAceChar;
phTable: pADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsPackTable = function( hTable: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsPackTable120 = function( hTable: ADSHANDLE;
ulMemoBlockSize: UNSIGNED32;
ulOptions: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsRecallRecord = function( hTable: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsRecallAllRecords = function( hTable: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsRefreshRecord = function( hTable: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsClearProgressCallback = function:UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsRegisterProgressCallback = function( Callback: TProgressCallback ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsRegisterCallbackFunction = function( Callback: TCallbackFunction;
ulCallbackID: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsRegisterCallbackFunction101 = function( Callback: TCallbackFunction101;
qCallbackID: SIGNED64 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsClearCallbackFunction = function:UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetSQLTimeout = function( hObj: ADSHANDLE;
ulTimeout: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsReindex = function( hObject: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsReindex61 = function( hObject: ADSHANDLE;
ulPageSize: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsReindexFTS = function( hObject: ADSHANDLE;
ulPageSize: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsResetConnection = function( hConnect: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsRollbackTransaction = function( hConnect: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSeek = function( hIndex: ADSHANDLE;
pucKey: PAceChar;
usKeyLen: UNSIGNED16;
usDataType: UNSIGNED16;
usSeekType: UNSIGNED16;
pbFound: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSeekLast = function( hIndex: ADSHANDLE;
pucKey: PAceChar;
usKeyLen: UNSIGNED16;
usDataType: UNSIGNED16;
pbFound: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetBinary = function( hTable: ADSHANDLE;
pucFldName: PAceChar;
usBinaryType: UNSIGNED16;
ulTotalLength: UNSIGNED32;
ulOffset: UNSIGNED32;
pucBuf: PAceBinary;
ulLen: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetCollationLang = function( pucLang: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetCollation = function( hConnect: ADSHANDLE;
pucCollation: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetDate = function( hObj: ADSHANDLE;
pucFldName: PAceChar;
pucValue: PAceChar;
usLen: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetDateFormat = function( pucFormat: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetDateFormat60 = function( hConnect: ADSHANDLE;
pucFormat: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetDecimals = function( usDecimals: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetDefault = function( pucDefault: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsShowDeleted = function( bShowDeleted: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetDouble = function( hObj: ADSHANDLE;
pucFldName: PAceChar;
dValue: DOUBLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetEmpty = function( hObj: ADSHANDLE;
pucFldName: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetEpoch = function( usCentury: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetExact = function( bExact: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetExact22 = function( hObj: ADSHANDLE;
bExact: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetField = function( hObj: ADSHANDLE;
pucFldName: PAceChar;
pucBuf: PAceChar;
ulLen: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetFieldW = function( hObj: ADSHANDLE;
pucFldName: PAceChar;
pwcBuf: PWideChar;
ulLen: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetFilter = function( hTable: ADSHANDLE;
pucFilter: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetFilter100 = function( hTable: ADSHANDLE;
pvFilter: pointer;
ulOptions: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetHandleLong = function( hObj: ADSHANDLE;
ulVal: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetJulian = function( hObj: ADSHANDLE;
pucFldName: PAceChar;
lDate: SIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetLogical = function( hObj: ADSHANDLE;
pucFldName: PAceChar;
bValue: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetLong = function( hObj: ADSHANDLE;
pucFldName: PAceChar;
lValue: SIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetLongLong = function( hObj: ADSHANDLE;
pucFldName: PAceChar;
qValue: SIGNED64 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetMilliseconds = function( hObj: ADSHANDLE;
pucFldName: PAceChar;
lTime: SIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetMoney = function( hObj: ADSHANDLE;
pucFldName: PAceChar;
qValue: SIGNED64 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetRecord = function( hObj: ADSHANDLE;
pucRec: PAceChar;
ulLen: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetRelation = function( hTableParent: ADSHANDLE;
hIndexChild: ADSHANDLE;
pucExpr: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetRelKeyPos = function( hIndex: ADSHANDLE;
dPos: DOUBLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetScope = function( hIndex: ADSHANDLE;
usScopeOption: UNSIGNED16;
pucScope: PAceChar;
usScopeLen: UNSIGNED16;
usDataType: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetScopedRelation = function( hTableParent: ADSHANDLE;
hIndexChild: ADSHANDLE;
pucExpr: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetSearchPath = function( pucPath: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetServerType = function( usServerOptions: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetShort = function( hObj: ADSHANDLE;
pucFldName: PAceChar;
sValue: SIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetString = function( hObj: ADSHANDLE;
pucFldName: PAceChar;
pucBuf: PAceChar;
ulLen: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetStringW = function( hObj: ADSHANDLE;
pucFldName: PAceChar;
pwcBuf: PWideChar;
ulLen: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetStringFromCodePage = function( hObj: ADSHANDLE;
ulCodePage: UNSIGNED32;
pucFldName: PAceChar;
pucBuf: PAceChar;
ulLen: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetTime = function( hObj: ADSHANDLE;
pucFldName: PAceChar;
pucValue: PAceChar;
usLen: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsShowError = function( pucTitle: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSkip = function( hObj: ADSHANDLE;
lRecs: SIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSkipUnique = function( hIndex: ADSHANDLE;
lRecs: SIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsThreadExit = function:UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsUnlockRecord = function( hTable: ADSHANDLE;
ulRec: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsUnlockTable = function( hTable: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
{* AdsVerifyPassword is obsolete; retained for backward compatibility.
* Use AdsIsEncryptionEnabled instead.
*}
TAdsVerifyPassword = function( hTable: ADSHANDLE;
pusEnabled: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsIsEncryptionEnabled = function( hTable: ADSHANDLE;
pusEnabled: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsWriteAllRecords = function:UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsWriteRecord = function( hTable: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsZapTable = function( hTable: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetAOF = function( hTable: ADSHANDLE;
pucFilter: PAceChar;
usOptions: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetAOF100 = function( hTable: ADSHANDLE;
pvFilter: pointer;
ulOptions: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsEvalAOF = function( hTable: ADSHANDLE;
pucFilter: PAceChar;
pusOptLevel: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsEvalAOF100 = function( hTable: ADSHANDLE;
pvFilter: pointer;
ulOptions: UNSIGNED32;
pusOptLevel: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsClearAOF = function( hTable: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsRefreshAOF = function( hTable: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetAOF = function( hTable: ADSHANDLE;
pucFilter: PAceChar;
pusLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetAOF100 = function( hTable: ADSHANDLE;
ulOptions: UNSIGNED32;
pvFilter: pointer;
pulLen: PUNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetAOFOptLevel = function( hTable: ADSHANDLE;
pusOptLevel: PUNSIGNED16;
pucNonOpt: PAceChar;
pusLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetAOFOptLevel100 = function( hTable: ADSHANDLE;
pusOptLevel: PUNSIGNED16;
pvNonOpt: pointer;
pulExprLen: PUNSIGNED32;
ulOptions: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsIsRecordInAOF = function( hTable: ADSHANDLE;
ulRecordNum: UNSIGNED32;
pusIsInAOF: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsCustomizeAOF = function( hTable: ADSHANDLE;
ulNumRecords: UNSIGNED32;
pulRecords: PUNSIGNED32;
usOption: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsInitRawKey = function( hIndex: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsBuildRawKey = function( hIndex: ADSHANDLE;
pucKey: PAceChar;
var pusKeyLen: Word ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsBuildRawKey100 = function( hIndex: ADSHANDLE;
pucKey: PAceChar;
pusKeyLen: PUNSIGNED16;
ulOptions: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsCreateSQLStatement = function( hConnect: ADSHANDLE;
phStatement: pADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsPrepareSQL = function( hStatement: ADSHANDLE;
pucSQL: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsPrepareSQLW = function( hStatement: ADSHANDLE;
pwcSQL: PWideChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsCachePrepareSQL = function( hConnect: ADSHANDLE;
pucSQL: PAceChar;
phStatement: pADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsCachePrepareSQLW = function( hConnect: ADSHANDLE;
pwcSQL: PWideChar;
phStatement: pADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsExecuteSQL = function( hStatement: ADSHANDLE;
phCursor: pADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsExecuteSQLDirect = function( hStatement: ADSHANDLE;
pucSQL: PAceChar;
phCursor: pADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsExecuteSQLDirectW = function( hStatement: ADSHANDLE;
pwcSQL: PWideChar;
phCursor: pADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsCloseSQLStatement = function( hStatement: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsStmtSetTableRights = function( hStatement: ADSHANDLE;
usCheckRights: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsStmtSetTableReadOnly = function( hStatement: ADSHANDLE;
usReadOnly: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsStmtSetTableLockType = function( hStatement: ADSHANDLE;
usLockType: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsStmtSetTableCharType = function( hStatement: ADSHANDLE;
usCharType: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsStmtSetTableType = function( hStatement: ADSHANDLE;
usTableType: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsStmtSetTableCollation = function( hStatement: ADSHANDLE;
pucCollation: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsStmtConstrainUpdates = function( hStatement: ADSHANDLE;
usConstrain: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsStmtEnableEncryption = function( hStatement: ADSHANDLE;
pucPassword: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsStmtDisableEncryption = function( hStatement: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsStmtSetTablePassword = function( hStatement: ADSHANDLE;
pucTableName: PAceChar;
pucPassword: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsStmtClearTablePasswords = function( hStatement: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsStmtReadAllColumns = function( hStatement: ADSHANDLE;
usReadColumns: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsClearSQLParams = function( hStatement: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetTimeStamp = function( hObj: ADSHANDLE;
pucFldName: PAceChar;
pucBuf: PAceChar;
ulLen: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsClearSQLAbortFunc = function:UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsRegisterSQLAbortFunc = function( Callback: TSQLAbortFunc ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsRegisterUDF = function( hObj: ADSHANDLE;
usType: UNSIGNED16;
Callback: TUDFFunc ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetNumParams = function( hStatement: ADSHANDLE;
pusNumParams: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetLastAutoinc = function( hObj: ADSHANDLE;
pulAutoIncVal: PUNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsIsIndexUserDefined = function( hIndex: ADSHANDLE;
pbUserDefined: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsRestructureTable = function( hObj: ADSHANDLE;
pucName: PAceChar;
pucPassword: PAceChar;
usTableType: UNSIGNED16;
usCharType: UNSIGNED16;
usLockType: UNSIGNED16;
usCheckRights: UNSIGNED16;
pucAddFields: PAceChar;
pucDeleteFields: PAceChar;
pucChangeFields: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsRestructureTable90 = function( hObj: ADSHANDLE;
pucName: PAceChar;
pucPassword: PAceChar;
usTableType: UNSIGNED16;
usCharType: UNSIGNED16;
usLockType: UNSIGNED16;
usCheckRights: UNSIGNED16;
pucAddFields: PAceChar;
pucDeleteFields: PAceChar;
pucChangeFields: PAceChar;
pucCollation: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsRestructureTable120 = function( hObj: ADSHANDLE;
pucName: PAceChar;
pucPassword: PAceChar;
usTableType: UNSIGNED16;
usCharType: UNSIGNED16;
usLockType: UNSIGNED16;
usCheckRights: UNSIGNED16;
pucAddFields: PAceChar;
pucDeleteFields: PAceChar;
pucChangeFields: PAceChar;
pucCollation: PAceChar;
ulMemoBlockSize: UNSIGNED32;
ulOptions: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetSQLStatementHandle = function( hCursor: ADSHANDLE;
phStmt: pADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetSQLStatement = function( hStmt: ADSHANDLE;
pucSQL: PAceChar;
pusLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsFlushFileBuffers = function( hTable: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDDeployDatabase = function( pucDestination: PAceChar;
pucDestinationPassword: PAceChar;
pucSource: PAceChar;
pucSourcePassword: PAceChar;
usServerTypes: UNSIGNED16;
usValidateOption: UNSIGNED16;
usBackupFiles: UNSIGNED16;
ulOptions: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsVerifySQL = function( hStatement: ADSHANDLE;
pucSQL: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsVerifySQLW = function( hStatement: ADSHANDLE;
pwcSQL: PWideChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDisableUniqueEnforcement = function( hConnection: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsEnableUniqueEnforcement = function( hConnection: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDisableRI = function( hConnection: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsEnableRI = function( hConnection: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDisableAutoIncEnforcement = function( hConnection: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsEnableAutoIncEnforcement = function( hConnection: ADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsRollbackTransaction80 = function( hConnect: ADSHANDLE;
pucSavepoint: PAceChar;
ulOptions: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsCreateSavepoint = function( hConnect: ADSHANDLE;
pucSavepoint: PAceChar;
ulOptions: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDFreeTable = function( pucTableName: PAceChar;
pucPassword: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDSetIndexProperty = function( hAdminConn: ADSHANDLE;
pucTableName: PAceChar;
pucIndexName: PAceChar;
usPropertyID: UNSIGNED16;
pvProperty: pointer;
usPropertyLen: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsIsFieldBinary = function( hTable: ADSHANDLE;
pucFldName: PAceChar;
pbBinary: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsIsNull = function( hTable: ADSHANDLE;
pucFldName: PAceChar;
pbNull: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsIsNullable = function( hTable: ADSHANDLE;
pucFldName: PAceChar;
pbNullable: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetNull = function( hTable: ADSHANDLE;
pucFldName: PAceChar ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetTableCollation = function( hTbl: ADSHANDLE;
pucCollation: PAceChar;
pusLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetIndexCollation = function( hIndex: ADSHANDLE;
pucCollation: PAceChar;
pusLen: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetDataLength = function( hTable: ADSHANDLE;
pucFldName: PAceChar;
ulOptions: UNSIGNED32;
pulLength: PUNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetIndexDirection = function( hIndex: ADSHANDLE;
usReverseDirection: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsMgKillUser90 = function( hMgmtHandle: ADSHANDLE;
pucUserName: PAceChar;
usConnNumber: UNSIGNED16;
usPropertyID: UNSIGNED16;
pvProperty: pointer;
usPropertyLen: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsGetFieldLength100 = function( hTable: ADSHANDLE;
pucFldName: PAceChar;
ulOptions: UNSIGNED32;
pulLength: PUNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetRightsChecking = function( ulOptions: UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetTableTransactionFree = function( hTable: ADSHANDLE;
usTransFree: UNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsIsTableTransactionFree = function( hTable: ADSHANDLE;
pusTransFree: PUNSIGNED16 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsFindServers = function( ulOptions: UNSIGNED32;
phTable: pADSHANDLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsDDSetTriggerProperty = function( hDictionary : ADSHANDLE;
pucTriggerName : PAceChar;
usPropertyID : UNSIGNED16;
pvProperty : pointer;
usPropertyLen : UNSIGNED16 ) : UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsBinaryToFileW = function( hTable: ADSHANDLE;
pucFldName: PAceChar;
pwcFileName: PWideChar ) : UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsFileToBinaryW = function( hTable: ADSHANDLE;
pucFldName: PAceChar;
usBinaryType: UNSIGNED16;
pwcFileName: PWideChar ) : UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
// Undocumented
TAdsConvertStringToJulian = function( pucJulian : PAceChar;
usLen : UNSIGNED16;
pdJulian : PDOUBLE ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
TAdsSetTimeStampRaw = function( hObj : ADSHANDLE;
pucFldName : PAceChar;
pucBuf : PAceChar;
ulLen : UNSIGNED32 ):UNSIGNED32; {$IFDEF WIN32}stdcall;{$ENDIF}{$IFDEF POSIX}cdecl;{$ENDIF}
implementation
end.
|
unit DriveInfoSet;
interface
uses Classes,
sysUtils,
InternalTypes;
type
tDriveInfoSet = class(tStringList)
private
public
constructor Create();
function AddSizeFromSize(TotalSize, FreeSize : uInt64; Key : String) : Boolean;
function GetJSON() : AnsiString;
procedure dumpData();
end;
implementation
uses DriveStat;
constructor tDriveInfoSet.Create();
begin
// Sorted := true;
Duplicates := dupError;
OwnsObjects := True;
end;
function tDriveInfoSet.AddSizeFromSize(TotalSize, FreeSize : uInt64; Key : String) : Boolean;
var i : Integer;
var DStat : tDriveStat;
begin
if key='' then
key := '_n/a_';
i := indexOf(Key);
if i = -1 then
begin
DStat := tDriveStat.Create;
DStat.TotalS := TotalSize;
DStat.FreeS := FreeSize;
i := AddObject(Key,DStat);
//writeln('added [',i,'] key=',Key);
Result := False;
end
else
Result := True;
end;
procedure tDriveInfoSet.dumpData();
var i : integer;
var DStat : tDriveStat;
begin
writeln('=-=-=-=-=-=-=-=-=-=');
for i:= 0 to pred(Count) do
begin
DStat := Objects[i] as tDriveStat;
writeln('[',i,']', Strings[i],':>',IntToStr(DStat.FreeS),' free on ',IntToStr(DStat.TotalS));
end;
writeln;
end;
function tDriveInfoSet.GetJSON() : AnsiString;
var i : integer;
var DStat : tDriveStat;
begin
Result := '"DriveInfoSet" : [';
for i:= 0 to pred(Count) do
begin
DStat := Objects[i] as tDriveStat;
Result := Result + '{ "Name" : "'+Strings[i]+
'", "TotalSize" : '+IntToStr(DStat.TotalS)+
', "FreeSize" : '+IntToStr(DStat.FreeS)+'}'+
VirguleLast[i<>pred(count)];
end;
Result := Result + ']'
end;
end. |
unit PullSupplierMain;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Corba, CosEvent, PullSupplier_Impl;
type
TForm1 = class(TForm)
Edit1: TEdit;
Label1: TLabel;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
Pull_Supplier_Skeleton : PullSupplier;
Event_Channel : EventChannel;
Pull_Consumer : ProxyPullConsumer;
procedure CorbaInit;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.CorbaInit;
begin
CorbaInitialize;
// Create the skeleton and register it with the boa
Pull_Supplier_Skeleton := TPullSupplierSkeleton.Create('Jack B Quick', TPullSupplier.Create);
BOA.SetScope( RegistrationScope(1) );
BOA.ObjIsReady(Pull_Supplier_Skeleton as _Object);
//bind to the event channel and get a PullConsumerProxy object
Event_Channel := TEventChannelHelper.bind;
Pull_Consumer := Event_Channel.for_suppliers.obtain_pull_consumer;
//connect the Skeleton to the Event Service
Pull_Consumer.connect_pull_supplier(Pull_Supplier_Skeleton);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
CorbaInit;
end;
end.
|
unit FrmQuestionListC;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uQuestionList, uQuestionInfo, FrmQInfoC;
type
TfQuestionListC = class(TfQuestionList)
private
{ Private declarations }
protected
/// <summary>
/// 创建考题信息界面
/// </summary>
function CreateQuestionFrom : TfQuestionInfo; override;
public
{ Public declarations }
end;
var
fQuestionListC: TfQuestionListC;
implementation
{$R *.dfm}
{ TfQuestionListC }
function TfQuestionListC.CreateQuestionFrom: TfQuestionInfo;
begin
Result := TfQInfo.Create(Application);
end;
end.
|
unit NumPlanFrame;
{#DEFINE DEBUG}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, NxColumns, NxColumnClasses, NxScrollControl,
NxCustomGridControl, NxCustomGrid, NxGrid, StdCtrls, ItemsDef, ComCtrls,
ToolWin, ActnList, Core;
type
TfrmNumPlan = class(TFrame)
grpNumPlan: TGroupBox;
ngNumPlan: TNextGrid;
nxIncColNumber: TNxIncrementColumn;
tlbNumPlan: TToolBar;
btnActions: TToolButton;
btnValues: TToolButton;
actlstNumPlan: TActionList;
actClose: TAction;
btnClose: TToolButton;
actActions: TAction;
actValues: TAction;
btn1: TToolButton;
actHelp: TAction;
btnHelp: TToolButton;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ngNumPlanAfterEdit(Sender: TObject; ACol, ARow: Integer;
Value: WideString);
procedure actlstNumPlanExecute(Action: TBasicAction;
var Handled: Boolean);
procedure DummyAction(Sender: TObject);
private
{ Private declarations }
slTicketTpl: TStringList;
slPageTpl: TStringList;
procedure CreateGrid();
procedure UpdateGrid();
procedure SaveGrid();
public
{ Public declarations }
NumProject: TNumProject;
Form: TForm;
PageID: Integer;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure GridTest();
procedure Start();
procedure Refresh();
end;
const
iFixedCols = 3;
iFixedRows = 0;
{#IFDEF DEBUG}
var
DT: TDateTime;
{#ENDIF}
implementation
uses DateUtils, MainForm;
{$R *.dfm}
constructor TfrmNumPlan.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
slTicketTpl:=TStringList.Create();
slPageTpl:=TStringList.Create();
end;
destructor TfrmNumPlan.Destroy();
begin
FreeAndNil(slPageTpl);
FreeAndNil(slTicketTpl);
inherited Destroy();
end;
procedure TfrmNumPlan.GridTest();
var
i, n: Integer;
s: string;
nl: TNumLabel;
nlt: TNumLabelTpl;
begin
if not NumProject.NumLabelsTpl.LoadFromBase() then Exit;
ngNumPlan.BeginUpdate();
for i:=0 to NumProject.NumLabelsTpl.Count-1 do
begin
nlt:=NumProject.NumLabelsTpl[i];
ngNumPlan.Columns.Add(TNxTextColumn, nlt.Name);
ngNumPlan.Columns.Item[i+iFixedCols].Options:=ngNumPlan.Columns.Item[i+iFixedCols].Options+[coEditing];
end;
ngNumPlan.AddRow(1000);
for i:=0 to NumProject.NumLabelsTpl.Count-1 do
begin
for n:=0 to ngNumPlan.RowCount-1 do
begin
s:='+1';
if i=4 then s:='=';
ngNumPlan.Cells[i+iFixedCols, n]:=s;
end;
end;
ngNumPlan.EndUpdate();
end;
procedure TfrmNumPlan.CreateGrid();
var
i, n, m: Integer;
sv, sa: string;
nl: TNumLabel;
nlt: TNumLabelTpl;
NumPlanItem: TNumPlanItem;
NumLabelData: TNumLabelData;
begin
{#IFDEF DEBUG}
DT:=Now();
{#ENDIF}
//if not NumProject.NumLabelsTpl.LoadFromBase() then Exit;
//if not NumProject.NumPlanItems.LoadFromBase() then Exit;
// TicketTpl combo box items
slTicketTpl.Clear();
for i:=0 to NumProject.TicketTplList.Count-1 do
begin
slTicketTpl.AddObject(NumProject.TicketTplList[i].Name, NumProject.TicketTplList[i]);
end;
// PageTpl combo box items
slPageTpl.Clear();
for i:=0 to NumProject.PagesTpl.Count-1 do
begin
slPageTpl.AddObject(NumProject.PagesTpl[i].Name, NumProject.PagesTpl[i]);
end;
{#IFDEF DEBUG}
DebugMsg('Preprocessing '+IntToStr(MilliSecondsBetween(DT, Now))+' ms', 'NumPlanFrm');
{#ENDIF}
ngNumPlan.BeginUpdate();
// Add columns
// Шаблон билета и шаблон листа
ngNumPlan.Columns.AddColumns(TNxComboBoxColumn, iFixedCols-1);
ngNumPlan.Columns.Item[iFixedCols-2].Header.Caption:='Шабл.билета';
ngNumPlan.Columns.Item[iFixedCols-2].Options:=ngNumPlan.Columns.Item[iFixedCols-2].Options+[coEditing];
ngNumPlan.Columns.Item[iFixedCols-2].Options:=ngNumPlan.Columns.Item[iFixedCols-2].Options-[coCanSort];
(ngNumPlan.Columns.Item[iFixedCols-2] as TNxComboBoxColumn).Items:=slTicketTpl;
ngNumPlan.Columns.Item[iFixedCols-1].Header.Caption:='Шабл.листа';
ngNumPlan.Columns.Item[iFixedCols-1].Options:=ngNumPlan.Columns.Item[iFixedCols-1].Options+[coEditing];
ngNumPlan.Columns.Item[iFixedCols-1].Options:=ngNumPlan.Columns.Item[iFixedCols-1].Options-[coCanSort];
(ngNumPlan.Columns.Item[iFixedCols-1] as TNxComboBoxColumn).Items:=slPageTpl;
// Нумераторы
if (ngNumPlan.Columns.Count-iFixedCols) < NumProject.NumLabelsTpl.Count then
begin
ngNumPlan.Columns.AddColumns(TNxTextColumn, NumProject.NumLabelsTpl.Count-ngNumPlan.Columns.Count+iFixedCols);
end;
for i:=0 to NumProject.NumLabelsTpl.Count-1 do
begin
nlt:=NumProject.NumLabelsTpl[i];
ngNumPlan.Columns.Item[i+iFixedCols].Header.Caption:=nlt.Name;
ngNumPlan.Columns.Item[i+iFixedCols].Options:=ngNumPlan.Columns.Item[i+iFixedCols].Options+[coEditing];
ngNumPlan.Columns.Item[i+iFixedCols].Options:=ngNumPlan.Columns.Item[i+iFixedCols].Options-[coCanSort];
end;
// Add rows
if (ngNumPlan.RowCount-iFixedRows) < NumProject.NumPlanItems.Count then
begin
ngNumPlan.AddRow(NumProject.NumPlanItems.Count - ngNumPlan.RowCount + iFixedRows);
end;
ngNumPlan.EndUpdate();
{#IFDEF DEBUG}
DebugMsg('Created '+IntToStr(ngNumPlan.RowCount)+' rows in '+IntToStr(MilliSecondsBetween(DT, Now))+' ms', 'NumPlanFrm');
{#ENDIF}
UpdateGrid();
end;
procedure TfrmNumPlan.UpdateGrid();
var
i, n, m: Integer;
t1, t2, t3, t4: Integer;
dt1, dt2, dt3, dt4: TDateTime;
sv, sa, sPrevAction: string;
nlt: TNumLabelTpl;
NumPlanItem: TNumPlanItem;
NumLabelData: TNumLabelData;
begin
{#IFDEF DEBUG}
DT:=Now();
t1:=0; t2:=0; t3:=0; t4:=0;
{#ENDIF}
ngNumPlan.BeginUpdate();
StartTransaction();
// Fill NumPlan items
NumProject.NumPlanItems.SortByOrder();
for n:=0 to NumProject.NumPlanItems.Count-1 do
begin
{#IFDEF DEBUG}
dt1:=Now();
{#ENDIF}
NumPlanItem:=NumProject.NumPlanItems[n];
if NumPlanItem.NumLabelDataList.Count < 0 then Continue;
if not Assigned(NumPlanItem.NumPage) then Continue;
if not Assigned(NumPlanItem.NumPage.NumPageTpl) then Continue;
if not Assigned(NumPlanItem.Ticket) then Continue;
if not Assigned(NumPlanItem.Ticket.Tpl) then Continue;
{#IFDEF DEBUG}
t4:=t4+MilliSecondsBetween(dt1, Now);
{#ENDIF}
ngNumPlan.Cell[iFixedCols-1, n].ObjectReference:=nil;
ngNumPlan.Cell[iFixedCols-1, n].AsString:=NumPlanItem.NumPage.NumPageTpl.Name;
ngNumPlan.Cell[iFixedCols-2, n].ObjectReference:=nil;
ngNumPlan.Cell[iFixedCols-2, n].AsString:=NumPlanItem.Ticket.Tpl.Name;
// Read NumLabels
for i:=0 to NumProject.NumLabelsTpl.Count-1 do
begin
{#IFDEF DEBUG}
dt2:=Now();
{#ENDIF}
nlt:=NumProject.NumLabelsTpl[i];
sv:='';
sa:='';
sPrevAction:='';
NumLabelData:=nil;
for m:=0 to NumPlanItem.NumLabelDataList.Count-1 do
begin
{#IFDEF DEBUG}
dt3:=Now();
{#ENDIF}
NumLabelData:=NumPlanItem.NumLabelDataList[m];
if NumLabelData.NumLabelTpl.ID = nlt.ID then
begin
sv:=NumLabelData.Value;
sa:=NumLabelData.Action;
Break;
end;
{#IFDEF DEBUG}
t3:=t3+MilliSecondsBetween(dt3, Now);
{#ENDIF}
end;
ngNumPlan.Cell[i+iFixedCols, n].ObjectReference:=NumLabelData;
if btnActions.Down then
begin
ngNumPlan.Cell[i+iFixedCols, n].AsString:=sa;
ngNumPlan.Cell[i+iFixedCols, n].Hint:=sv;
if n>0 then sPrevAction:=ngNumPlan.Cell[i+iFixedCols, n-1].AsString;
end;
if btnValues.Down then
begin
ngNumPlan.Cell[i+iFixedCols, n].AsString:=sv;
ngNumPlan.Cell[i+iFixedCols, n].Hint:=sa;
if n>0 then sPrevAction:=ngNumPlan.Cell[i+iFixedCols, n-1].Hint;
end;
// Выделение цветом изменения действия
if sa<>sPrevAction then ngNumPlan.Cell[i+iFixedCols, n].Color:=clSkyBlue
else ngNumPlan.Cell[i+iFixedCols, n].Color:=clWindow;
//ngNumPlan.Cells[i+iFixedCols, n]:=sv;
//ngNumPlan.Cell[i+iFixedCols, n].Hint:=sa;
{#IFDEF DEBUG}
t2:=t2+MilliSecondsBetween(dt2, Now);
{#ENDIF}
end;
{#IFDEF DEBUG}
t1:=t1+MilliSecondsBetween(dt1, Now);
{#ENDIF}
end;
CloseTransaction();
ngNumPlan.EndUpdate();
{#IFDEF DEBUG}
DebugMsg('Updated '+IntToStr(ngNumPlan.RowCount)+' rows in '+IntToStr(MilliSecondsBetween(DT, Now))+' ms', 'NumPlanFrm');
DebugMsg('t1='+IntToStr(t1)+' t2='+IntToStr(t2)+' t3='+IntToStr(t3)+' t4='+IntToStr(t4)+' ms', 'NumPlanFrm');
{#ENDIF}
end;
procedure TfrmNumPlan.SaveGrid();
var
n, i: Integer;
nld: TNumLabelData;
begin
StartTransaction();
//ngNumPlan.BeginUpdate();
{ // Save NumPlan items
for n:=0 to ngNumPlan.RowCount-1 do
begin
for i:=0 to ngNumPlan.Columns.Count-1 do
begin
// Save item values
nld:=TNumLabelData(ngNumPlan.Cell[n, i].ObjectReference);
if Assigned(nld) then
begin
if (nld.Value <> sVal) and (nld.Action <> sAct) then
begin
nld.Value:=sVal;
if sAct<>'' then nld.Action:=sAct;
nld.Write();
end;
end;
end;
end;
} CloseTransaction();
end;
procedure TfrmNumPlan.Start();
begin
btnValues.Down:=True;
CreateGrid();
end;
procedure TfrmNumPlan.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if Assigned(Form) then Form.Release();
end;
procedure TfrmNumPlan.ngNumPlanAfterEdit(Sender: TObject; ACol,
ARow: Integer; Value: WideString);
var
i, n: Integer;
sAct, sVal, sText: string;
sPrevValue, sPrevAction: string;
nld: TNumLabelData;
ActMode: Boolean;
begin
if ACol < iFixedCols then Exit;
ActMode:=btnActions.Down;
n:=0;
// Проверка изменения значения
nld:=TNumLabelData(ngNumPlan.Cell[ACol, ARow].ObjectReference);
if Assigned(nld) then
begin
if ActMode
then sText:=nld.Action
else sText:=nld.Value;
end;
if sText = Trim(Value) then Exit;
// Поиск предыдущего значения
i:=ARow-1;
if i<0 then i:=0;
sPrevValue:='';
sPrevAction:='';
nld:=TNumLabelData(ngNumPlan.Cell[ACol, i].ObjectReference);
if Assigned(nld) then
begin
sPrevValue:=nld.Value;
sPrevAction:=nld.Action;
end;
StartTransaction();
for i:=ARow to ngNumPlan.RowCount-1 do
begin
sAct:='';
sVal:='';
if ActMode then
begin
sAct:=ngNumPlan.Cell[ACol, i].AsString;
end
else
begin
sVal:=ngNumPlan.Cell[ACol, i].AsString;
if i = ARow then sAct:='='+sVal
else sAct:=ngNumPlan.Cell[ACol, i].Hint;
end;
if sAct<>'' then sVal:=ApplyAction(sPrevValue, sAct);
//sPrevValue:=sVal;
// Выделение цветом изменения действия
if sAct<>sPrevAction then ngNumPlan.Cell[ACol, i].Color:=clSkyBlue
else ngNumPlan.Cell[ACol, i].Color:=clWindow;
// Save item values
nld:=TNumLabelData(ngNumPlan.Cell[ACol, i].ObjectReference);
if Assigned(nld) then
begin
if (nld.Value <> sVal) or (nld.Action <> sAct) then
begin
nld.Value:=sVal;
if sAct<>'' then nld.Action:=sAct;
nld.Write();
end;
sPrevValue:=nld.Value;
sPrevAction:=nld.Action;
end;
if ActMode then
begin
ngNumPlan.Cell[ACol, i].AsString:=sAct;
ngNumPlan.Cell[ACol, i].Hint:=sVal;
end
else
begin
ngNumPlan.Cell[ACol, i].AsString:=sVal;
ngNumPlan.Cell[ACol, i].Hint:=sAct;
end;
end;
CloseTransaction();
end;
procedure TfrmNumPlan.Refresh();
begin
UpdateGrid();
end;
procedure TfrmNumPlan.DummyAction(Sender: TObject);
begin
//
end;
procedure TfrmNumPlan.actlstNumPlanExecute(Action: TBasicAction;
var Handled: Boolean);
begin
if Action = actClose then
begin
Core.AddCmd('CLOSE '+IntToStr(PageID));
end
else if Action = actActions then
begin
if actActions.Checked then Exit;
actActions.Checked:=True;
actValues.Checked:=False;
UpdateGrid();
end
else if Action = actValues then
begin
if actValues.Checked then Exit;
actActions.Checked:=False;
actValues.Checked:=True;
UpdateGrid();
end
else if Action = actHelp then
begin
Application.HelpCommand(HELP_CONTEXT, 9)
end;
end;
end.
|
unit uDB;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Forms, math, Types,
FIBDatabase, pFIBDatabase, FIBQuery, pFIBQuery, pFIBProps, IniFiles,
StrUtils, Generics.Collections, Generics.Defaults, uGameItems;
type
TMoonDB = class
protected
class var FInstance: TMoonDB;
class constructor ClassCreate;
private
FFloatFormat: TFormatSettings;
FConnected: boolean;
FIBDatabase: TpFIBDatabase;
FIBQuery: TpFIBQuery;
FIBQueryCurs,
FIBQueryCursOut: TpFIBQuery;
FIBTransaction: TpFIBTransaction;
public
class function GetInstance: TMoonDB; static;
constructor Create;
destructor Destory;
property FloatFormat: TFormatSettings read FFloatFormat;
property Connected: boolean read FConnected;
function Connect: boolean;
procedure Commit;
function GetStrategyList: TpFIBQuery;
function GetGameItemGroupID(GroupName: string): integer;
function GetGameItemID(Name: string): integer;
function GetGameItem(Name: string): TGameItem; overload;
function GetGameItem(ID: integer): TGameItem; overload;
function UpdateTechnologies(techs: TGameItems): boolean; overload;
function UpdateTechnologies(tech: TGameItem): boolean; overload;
function ClearTechDeps: boolean;
function GetTechDeps(ItemName: string): TGameItems; overload;
function GetTechDeps(ItemID: integer): TGameItems; overload;
function UpdateTechDeps(techdeps: TGameItems): boolean; overload;
function UpdateTechDeps(techdep: TGameItem): boolean; overload;
function UpdateMyPlanets(imp: TImperium): boolean;
function UpdateMyPlanet(pl: TPlanet; serial: integer = 0): boolean;
function DeleteMyPlanets(serial: integer = 0): boolean;
function GetPlanetBuildType(PlanetID: integer): integer;
function GetPlanetBuildTree(BuildType: integer): TGameItems;
function GetImperiumBuildTree: TGameItems;
function ClearUniverse: boolean;
function AddSystem(Galaxy, System: integer): boolean;
function GetSystemToScan(cnt: integer): TpFIBQuery;
function ClearPlanetSystem(Galaxy, System: integer): boolean;
function UpdatePlanetSystem(PlanetSystem: TPlanetSystem): boolean;
function GetPlanet(coords: TGameCoords): TEnemyPlanet;
function AddPlanet(pl: TEnemyPlanet): boolean;
function UpdateUsers(users: TUserList): boolean;
function UpdateUser(user: TUser): boolean;
function UpdateShipBook(ships: TShips): boolean; overload;
function UpdateShipBook(ship: TShip): boolean; overload;
function GetShipBook(name: string): TShip;
function UpdateBuildingBook(Buildings: TGameItems): boolean; overload;
function UpdateBuildingBook(Building: TGameItem): boolean; overload;
function intGetBuildingRes(name: string; level: integer): TGameRes;
function GetBuildingKoef(name: string): Extended;
function GetBuildingRes(name: string; level: integer): TGameRes;
function GetBuildingLength(name: string; level: integer): TDateTime;
function SetParam(ParamName, ParamValue: string): boolean; overload;
function SetParam(ParamName: string; ParamValue: int64): boolean; overload;
function GetParam(ParamName: string; Default: string = ''): string; overload;
function GetParam(ParamName: string; Default: int64 = 0): int64; overload;
end;
implementation
{ TMoonDB }
function TMoonDB.AddPlanet(pl: TEnemyPlanet): boolean;
begin
Result := false;
try
FIBQuery.SQL.Text := 'update or insert into universe ' +
'(galaxy, system, planet, name, user_id, have_moon, have_crashfield, last_update) values (' +
IntToStr(pl.Coords.Galaxy) + ',' +
IntToStr(pl.Coords.System) + ',' +
IntToStr(pl.Coords.Planet) + ',''' +
Trim(pl.Name) + ''',' +
IntToStr(pl.UserID) + ',' +
IntToStr(integer(pl.HaveMoon)) + ',' +
IntToStr(integer(pl.HaveCrashField)) + ',' +
'current_timestamp ) matching (galaxy, system, planet)';
FIBQuery.ExecQuery;
Result := true;
except
end;
end;
function TMoonDB.AddSystem(Galaxy, System: integer): boolean;
begin
Result := false;
if not FConnected then exit;
try
FIBQuery.SQL.Text := 'insert into universe (galaxy, system, planet, name) values ' +
'(' + IntToStr(Galaxy) + ', ' + IntToStr(System) + ', 0, ''[' +
IntToStr(Galaxy) + ',' + IntToStr(System) + ']'')';
FIBQuery.ExecQuery;
Result := true;
except
end;
end;
class constructor TMoonDB.ClassCreate;
begin
inherited;
FInstance := nil;
end;
function TMoonDB.ClearPlanetSystem(Galaxy, System: integer): boolean;
begin
Result := false;
try
FIBQuery.SQL.Text := 'delete from UNIVERSE where ' +
'(system=' + IntToStr(System) + ') and ' +
'(galaxy=' + IntToStr(Galaxy) + ') and ' +
'(planet <> 0)';
FIBQuery.ExecQuery;
Result := true;
except
end;
end;
function TMoonDB.ClearTechDeps: boolean;
begin
Result := false;
if not FConnected then exit;
try
FIBQuery.SQL.Text := 'delete from TECH_DEPS ';
FIBQuery.ExecQuery;
Result := true;
except
end;
end;
function TMoonDB.ClearUniverse: boolean;
begin
Result := false;
try
FIBQuery.SQL.Text := 'delete from UNIVERSE';
FIBQuery.ExecQuery;
Commit;
Result := true;
except
end;
end;
procedure TMoonDB.Commit;
begin
FIBTransaction.Commit;
end;
function TMoonDB.Connect: boolean;
begin
Result := false;
if Connected then exit;
with TIniFile.Create(ExtractFilePath(Application.ExeName) + '2moons.ini')do
try
FIBDatabase.DBName :=
ReadString('DB', 'path', 'C:\Projects\!chrome\2moons\2moons.fdb');
FIBDatabase.DBParams.Values['user_name'] :=
ReadString('DB', 'username', 'SYSDBA');
FIBDatabase.DBParams.Values['password'] :=
ReadString('DB', 'password', 'masterkey');
FIBDatabase.DBParams.Values['lc_ctype'] := 'utf-8';
FIBDatabase.SQLDialect := 3;
FIBDatabase.WaitForRestoreConnect := 100;
FIBDatabase.Open(true);
finally
Free;
end;
FConnected := FIBDatabase.Connected;
Result := FConnected;
end;
constructor TMoonDB.Create;
begin
inherited;
FFloatFormat := TFormatSettings.Create;
FFloatFormat.DecimalSeparator := '.';
FIBDatabase := TpFIBDatabase.Create(nil);
FIBTransaction := TpFIBTransaction.Create(nil);
FIBDatabase.DefaultTransaction := FIBTransaction;
FIBDatabase.DefaultUpdateTransaction := FIBTransaction;
FIBQuery := TpFIBQuery.Create(nil);
FIBQuery.Database := FIBDatabase;
FIBQuery.Options := FIBQuery.Options + [qoStartTransaction];
FIBQuery.GoToFirstRecordOnExecute := false;
FIBQueryCurs := TpFIBQuery.Create(nil);
FIBQueryCurs.Database := FIBDatabase;
FIBQueryCurs.Options := FIBQueryCurs.Options + [qoStartTransaction];
FIBQueryCurs.GoToFirstRecordOnExecute := true;
FIBQueryCursOut := TpFIBQuery.Create(nil);
FIBQueryCursOut.Database := FIBDatabase;
FIBQueryCursOut.Options := FIBQueryCursOut.Options + [qoStartTransaction];
FIBQueryCursOut.GoToFirstRecordOnExecute := true;
end;
function TMoonDB.DeleteMyPlanets(serial: integer): boolean;
begin
Result := false;
try
FIBQuery.SQL.Text := 'delete from MY_PLANETS where ' +
'(serial<>' + IntToStr(serial) + ')';
FIBQuery.ExecQuery;
Result := true;
except
end;
end;
destructor TMoonDB.Destory;
begin
inherited;
end;
function TMoonDB.GetGameItem(Name: string): TGameItem;
begin
Result.ID := 0;
if not FConnected then exit;
try
FIBQueryCurs.Close;
FIBQueryCurs.SQL.Text := 'select g.*, gs.Name as GROUP_NAME from gitems g, gitem_groups gs where ' +
'(g.GROUP_ID=gs.ID) and ' +
'(g.name=''' + Name + ''') ';
FIBQueryCurs.ExecQuery;
if Trim(FIBQueryCurs.FieldByName('NAME').AsString) = '' then exit;
Result.ID := FIBQueryCurs.FieldByName('ID').AsInteger;
Result.GroupName := FIBQueryCurs.FieldByName('GROUP_NAME').AsString;
Result.Name := FIBQueryCurs.FieldByName('NAME').AsString;
FIBQueryCurs.Close;
except
end;
end;
function TMoonDB.intGetBuildingRes(name: string; level: integer): TGameRes;
begin
Result.Clear;
if not FConnected then exit;
try
FIBQueryCurs.Close;
FIBQueryCurs.SQL.Text := 'select * from BUILDING_BOOK where ' +
'(id=' + IntToStr(GetGameItemID(name)) + ') and ' +
'(build_level=' + IntToStr(level) + ')';
FIBQueryCurs.ExecQuery;
if FIBQueryCurs.FieldByName('ID').AsString = '' then exit;
Result.Metal := FIBQueryCurs.FieldByName('BUILD_ME').AsInt64;
Result.Crystal := FIBQueryCurs.FieldByName('BUILD_CRY').AsInt64;
Result.Deiterium := FIBQueryCurs.FieldByName('BUILD_DEI').AsInt64;
FIBQueryCurs.Close;
except
end;
end;
function TMoonDB.GetBuildingKoef(name: string): Extended;
var
k,
k1,
k2,
k3: extended;
begin
Result := 2;
k1 := 0;
k2 := 0;
k3 := 0;
if not FConnected then exit;
try
FIBQueryCurs.Close;
FIBQueryCurs.SQL.Text :=
'select B1.ID, B1.BUILD_LEVEL, B2.BUILD_LEVEL, B1.BUILD_ME MM, B2.BUILD_ME NM, B1.BUILD_CRY MC, B2.BUILD_CRY NC, ' +
' B1.BUILD_DEI MD, B2.BUILD_DEI ND ' +
'from BUILDING_BOOK B1 ' +
'left join BUILDING_BOOK B2 on (B2.ID = B1.ID and B2.BUILD_LEVEL = B1.BUILD_LEVEL - 1) ' +
'where (B2.ID is not null) and ' +
' (B1.ID = 1) ' +
'order by B1.BUILD_LEVEL ' +
'rows 1';
FIBQueryCurs.ExecQuery;
if FIBQueryCurs.FieldByName('ID').AsString = '' then exit;
if FIBQueryCurs.FieldByName('NM').AsDouble <> 0 then
k1 := FIBQueryCurs.FieldByName('MM').AsDouble / FIBQueryCurs.FieldByName('NM').AsDouble;
if FIBQueryCurs.FieldByName('NC').AsDouble <> 0 then
k2 := FIBQueryCurs.FieldByName('MC').AsDouble / FIBQueryCurs.FieldByName('NC').AsDouble;
if FIBQueryCurs.FieldByName('ND').AsDouble <> 0 then
k3 := FIBQueryCurs.FieldByName('MD').AsDouble / FIBQueryCurs.FieldByName('ND').AsDouble;
FIBQueryCurs.Close;
k := max(k1, max(k2, k3));
if (k > 1.1) and (k < 10) then Result := k;
except
end;
end;
function TMoonDB.GetBuildingLength(name: string; level: integer): TDateTime;
begin
Result := 0;
if not FConnected then exit;
try
FIBQueryCurs.Close;
FIBQueryCurs.SQL.Text := 'select * from BUILDING_BOOK where ' +
'(id=' + IntToStr(GetGameItemID(name)) + ') and ' +
'(build_level=' + IntToStr(level) + ')';
FIBQueryCurs.ExecQuery;
if FIBQueryCurs.FieldByName('ID').AsString = '' then exit;
Result := FIBQueryCurs.FieldByName('BUILD_TIME').AsDateTime;
FIBQueryCurs.Close;
except
end;
end;
function TMoonDB.GetBuildingRes(name: string; level: integer): TGameRes;
var
k: extended;
begin
Result := intGetBuildingRes(name, level);
if Result.Eq0 then
begin
Result := intGetBuildingRes(name, 0);
k := GetBuildingKoef(name);
Result.Mul(Round(Power(k, level)));
end;
end;
function TMoonDB.GetGameItem(ID: integer): TGameItem;
begin
Result.ID := 0;
if not FConnected then exit;
try
FIBQueryCurs.Close;
FIBQueryCurs.SQL.Text := 'select * from gitem_groups where ' +
'(id=' + IntToStr(ID) + ') ';
FIBQueryCurs.ExecQuery;
if Trim(FIBQueryCurs.FieldByName('NAME').AsString) = '' then exit;
Result.ID := FIBQueryCurs.FieldByName('ID').AsInteger;
FIBQueryCurs.Close;
except
end;
end;
function TMoonDB.GetGameItemGroupID(GroupName: string): integer;
begin
Result := 0;
if not FConnected then exit;
try
FIBQueryCurs.Close;
FIBQueryCurs.SQL.Text := 'select * from gitem_groups where ' +
'(name=''' + GroupName + ''') ';
FIBQueryCurs.ExecQuery;
if Trim(FIBQueryCurs.FieldByName('NAME').AsString) = '' then exit;
Result := FIBQueryCurs.FieldByName('ID').AsInteger;
FIBQueryCurs.Close;
except
end;
end;
function TMoonDB.GetGameItemID(Name: string): integer;
begin
Result := GetGameItem(Name).ID;
end;
function TMoonDB.GetImperiumBuildTree: TGameItems;
begin
SetLength(Result, 0);
if not FConnected then exit;
try
FIBQueryCurs.Close;
FIBQueryCurs.SQL.Text :=
'with BT ' +
'as (select distinct PLANET_BUILD_TYPE TYPE_ID ' +
' from MY_PLANETS ' +
' where PLANET_BUILD_TYPE is not null) ' +
'select TT.ID, TT.NAME, max(TT.LVL) LVL ' +
'from BT, PLANET_TYPE_TECH_TREE(BT.TYPE_ID) TT ' +
'where TT.GROUP_ID = 3 ' +
'group by TT.ID, TT.NAME ';
FIBQueryCurs.ExecQuery;
while not FIBQueryCurs.Eof do
begin
if Trim(FIBQueryCurs.FieldByName('NAME').AsString) = '' then continue;
SetLength(Result, length(Result) + 1);
Result[length(Result) - 1].ID :=
FIBQueryCurs.FieldByName('ID').AsInteger;
Result[length(Result) - 1].Name :=
FIBQueryCurs.FieldByName('NAME').AsString;
Result[length(Result) - 1].Tag := 3;
Result[length(Result) - 1].GroupName :=
'Исследования';
Result[length(Result) - 1].Level :=
FIBQueryCurs.FieldByName('LVL').AsInteger;
FIBQueryCurs.Next;
end;
FIBQueryCurs.Close;
except
end;
end;
class function TMoonDB.GetInstance: TMoonDB;
begin
if not Assigned(FInstance) then
FInstance := TMoonDB.Create;
Result := FInstance;
end;
function TMoonDB.GetParam(ParamName: string; Default: string = ''): string;
begin
Result := Default;
if not FConnected then exit;
try
FIBQueryCurs.Close;
FIBQueryCurs.SQL.Text := 'select * from params where NAME=''' + ParamName + ''' ';
FIBQueryCurs.ExecQuery;
Result := FIBQueryCurs.FieldByName('VAL').AsString;
FIBQueryCurs.Close;
except
Result := Default;
end;
end;
function TMoonDB.GetParam(ParamName: string; Default: int64): int64;
begin
Result := StrToIntDef(GetParam(ParamName, IntToStr(Default)), Default);
end;
function TMoonDB.GetPlanet(coords: TGameCoords): TEnemyPlanet;
begin
Result.isEmpty := true;
if not FConnected then exit;
try
FIBQueryCurs.Close;
FIBQueryCurs.SQL.Text := 'select * from universe where ' +
'(galaxy=' + IntToStr(coords.Galaxy) + ') and ' +
'(system=' + IntToStr(coords.System) + ') and ' +
'(planet=' + IntToStr(coords.Planet) + ')';
FIBQueryCurs.ExecQuery;
if Trim(FIBQueryCurs.FieldByName('NAME').AsString) = '' then exit;
Result.Coords := coords;
Result.Name := FIBQueryCurs.FieldByName('NAME').AsString;
Result.UserID := FIBQueryCurs.FieldByName('USER_ID').AsInt64;
Result.isEmpty := false;
FIBQueryCurs.Close;
except
end;
end;
function TMoonDB.GetPlanetBuildTree(BuildType: integer): TGameItems;
begin
SetLength(Result, 0);
if not FConnected then exit;
try
FIBQueryCurs.Close;
FIBQueryCurs.SQL.Text := 'select * from PLANET_TYPE_TECH_TREE(' +
IntToStr(BuildType) + ') ';
FIBQueryCurs.ExecQuery;
while not FIBQueryCurs.Eof do
begin
if Trim(FIBQueryCurs.FieldByName('NAME').AsString) = '' then continue;
SetLength(Result, length(Result) + 1);
Result[length(Result) - 1].ID :=
FIBQueryCurs.FieldByName('ID').AsInteger;
Result[length(Result) - 1].Name :=
FIBQueryCurs.FieldByName('NAME').AsString;
Result[length(Result) - 1].Tag :=
FIBQueryCurs.FieldByName('GROUP_ID').AsInteger;
Result[length(Result) - 1].GroupName :=
FIBQueryCurs.FieldByName('GROUP_NAME').AsString;
Result[length(Result) - 1].Level :=
FIBQueryCurs.FieldByName('LVL').AsInteger;
FIBQueryCurs.Next;
end;
FIBQueryCurs.Close;
except
end;
end;
function TMoonDB.GetPlanetBuildType(PlanetID: integer): integer;
begin
Result := -1;
if not FConnected then exit;
try
FIBQueryCurs.Close;
FIBQueryCurs.SQL.Text := 'select * from my_planets where ' +
'(id=' + IntToStr(PlanetID) + ') ';
FIBQueryCurs.ExecQuery;
if FIBQueryCurs.FieldByName('PLANET_BUILD_TYPE').IsNull then exit;
Result := FIBQueryCurs.FieldByName('PLANET_BUILD_TYPE').AsInteger;
FIBQueryCurs.Close;
except
end;
end;
function TMoonDB.GetShipBook(name: string): TShip;
begin
Result.Clear;
if not FConnected then exit;
try
FIBQueryCurs.Close;
FIBQueryCurs.SQL.Text := 'select * from ship_book where ' +
'(name=''' + name + ''') ';
FIBQueryCurs.ExecQuery;
if Trim(FIBQueryCurs.FieldByName('NAME').AsString) = '' then exit;
Result.ID := FIBQueryCurs.FieldByName('ID').AsInteger;
Result.Name := FIBQueryCurs.FieldByName('NAME').AsString;
Result.Tag := FIBQueryCurs.FieldByName('TAG').AsString;
Result.BuildRes.Metal := FIBQueryCurs.FieldByName('BUILD_ME').AsInt64;
Result.BuildRes.Crystal := FIBQueryCurs.FieldByName('BUILD_CRY').AsInt64;
Result.BuildRes.Deiterium := FIBQueryCurs.FieldByName('BUILD_DEI').AsInt64;
Result.BuildTime := FIBQueryCurs.FieldByName('BUILD_TIME').AsDateTime;
FIBQueryCurs.Close;
except
end;
end;
function TMoonDB.GetStrategyList: TpFIBQuery;
begin
Result := nil;
if not Connected then exit;
try
FIBQueryCursOut.SQL.Text :=
'select * from strategy ' +
'order by id';
FIBQueryCursOut.ExecQuery;
Result := FIBQueryCursOut;
except
end;
end;
function TMoonDB.GetSystemToScan(cnt: integer): TpFIBQuery;
begin
Result := nil;
if not Connected then exit;
try
FIBQueryCursOut.SQL.Text :=
'select first ' + IntToStr(cnt) + ' * from universe where planet = 0 ' +
'order by LAST_UPDATE, galaxy, system';
FIBQueryCursOut.ExecQuery;
Result := FIBQueryCursOut;
except
end;
end;
function TMoonDB.GetTechDeps(ItemName: string): TGameItems;
begin
Result := GetTechDeps(GetGameItemID(ItemName));
end;
function TMoonDB.GetTechDeps(ItemID: integer): TGameItems;
begin
SetLength(Result, 0);
if not FConnected then exit;
try
FIBQueryCurs.Close;
FIBQueryCurs.SQL.Text := 'select * from GET_TECH_DEP(' +
IntToStr(ItemID) + ') ';
FIBQueryCurs.ExecQuery;
while not FIBQueryCurs.Eof do
begin
if Trim(FIBQueryCurs.FieldByName('ITEM_ID').AsString) = '' then continue;
SetLength(Result, length(Result) + 1);
Result[length(Result) - 1].ID :=
FIBQueryCurs.FieldByName('ITEM_ID').AsInteger;
Result[length(Result) - 1].Tag :=
FIBQueryCurs.FieldByName('GROUP_ID').AsInteger;
Result[length(Result) - 1].GroupName :=
FIBQueryCurs.FieldByName('GROUP_NAME').AsString;
Result[length(Result) - 1].Name :=
FIBQueryCurs.FieldByName('NAME').AsString;
Result[length(Result) - 1].Level :=
FIBQueryCurs.FieldByName('LEVEL').AsInteger;
FIBQueryCurs.Next;
end;
FIBQueryCurs.Close;
except
end;
end;
function TMoonDB.SetParam(ParamName: string; ParamValue: int64): boolean;
begin
Result := SetParam(ParamName, IntToStr(ParamValue));
end;
function TMoonDB.UpdateBuildingBook(Buildings: TGameItems): boolean;
var
i: Integer;
begin
Result := true;
for i := 0 to length(Buildings) - 1 do
Result := Result and UpdateBuildingBook(Buildings[i]);
end;
function TMoonDB.UpdateBuildingBook(Building: TGameItem): boolean;
begin
Result := false;
if not FConnected then exit;
try
FIBQuery.SQL.Text := 'update or insert into BUILDING_BOOK ' +
'(id, build_level, tag, build_me, build_cry, build_dei, build_time, last_update) values (' +
IntToStr(Building.ID) + ',' +
IntToStr(Building.Level) + ',' +
IntToStr(Building.Tag) + ',' +
IntToStr(Building.BuildRes.Metal) + ',' +
IntToStr(Building.BuildRes.Crystal) + ',' +
IntToStr(Building.BuildRes.Deiterium) + ',''' +
DateTimeToStr(Building.BuildTime) + ''',' +
'current_timestamp) matching (id, build_level)';
FIBQuery.ExecQuery;
Result := true;
except
end;
end;
function TMoonDB.UpdateMyPlanet(pl: TPlanet; serial: integer = 0): boolean;
begin
Result := false;
if not FConnected then exit;
try
FIBQuery.SQL.Text := 'update or insert into MY_PLANETS ' +
'(id, galaxy, system, planet, is_moon, name, serial, last_update) values (' +
IntToStr(pl.ID) + ',' +
IntToStr(pl.Coords.Galaxy) + ',' +
IntToStr(pl.Coords.System) + ',' +
IntToStr(pl.Coords.Planet) + ',' +
IntToStr(integer(pl.isMoon)) + ',''' +
pl.Name + ''',' +
IntToStr(serial) + ',' +
'current_timestamp) matching (id)';
FIBQuery.ExecQuery;
Result := true;
except
end;
end;
function TMoonDB.UpdateMyPlanets(imp: TImperium): boolean;
var
serial,
i: Integer;
begin
Result := true;
serial := GetTickCount;
for i := 0 to imp.PlanetsCount - 1 do
Result := Result and UpdateMyPlanet(imp.GetPlanetI(i), serial);
Result := Result and DeleteMyPlanets(serial);
end;
function TMoonDB.UpdatePlanetSystem(PlanetSystem: TPlanetSystem): boolean;
var
i: Integer;
begin
Result := false;
if not FConnected then exit;
if length(PlanetSystem) > 0 then
try
ClearPlanetSystem(
PlanetSystem[0].Coords.Galaxy,
PlanetSystem[0].Coords.System);
FIBQuery.SQL.Text := 'update or insert into universe ' +
'(galaxy, system, planet, last_update) values (' +
IntToStr(PlanetSystem[0].Coords.Galaxy) + ',' +
IntToStr(PlanetSystem[0].Coords.System) + ',' +
'0,' +
'current_timestamp ) matching (galaxy, system, planet)';
FIBQuery.ExecQuery;
for i := 0 to length(PlanetSystem) - 1 do
if not PlanetSystem[i].isEmpty then
AddPlanet(PlanetSystem[i]);
Result := true;
except
end;
end;
function TMoonDB.UpdateShipBook(ship: TShip): boolean;
begin
Result := false;
if not FConnected then exit;
try
FIBQuery.SQL.Text := 'update or insert into SHIP_BOOK ' +
'(id, name, tag, build_me, build_cry, build_dei, build_time, last_update) values (' +
IntToStr(ship.ID) + ',''' +
ship.Name + ''',''' +
ship.Tag + ''',' +
IntToStr(ship.BuildRes.Metal) + ',' +
IntToStr(ship.BuildRes.Crystal) + ',' +
IntToStr(ship.BuildRes.Deiterium) + ',''' +
DateTimeToStr(ship.BuildTime) + ''',' +
'current_timestamp) matching (id)';
FIBQuery.ExecQuery;
Result := true;
except
end;
end;
function TMoonDB.UpdateTechDeps(techdeps: TGameItems): boolean;
var
i: Integer;
begin
Result := true;
for i := 0 to length(techdeps) - 1 do
Result := Result and UpdateTechDeps(techdeps[i]);
end;
function TMoonDB.UpdateTechDeps(techdep: TGameItem): boolean;
begin
Result := false;
if not FConnected then exit;
try
FIBQuery.SQL.Text := 'update or insert into TECH_DEPS ' +
'(item_id, dep_item_id, level, last_update) values (' +
IntToStr(techdep.ID) + ',' +
IntToStr(GetGameItemID(techdep.Name)) + ',' +
IntToStr(techdep.Level) + ',' +
'current_timestamp) matching (item_id, dep_item_id)';
FIBQuery.ExecQuery;
Result := true;
except
end;
end;
function TMoonDB.UpdateTechnologies(tech: TGameItem): boolean;
begin
Result := false;
if not FConnected then exit;
try
FIBQuery.SQL.Text := 'update or insert into GITEMS ' +
'(id, group_id, name, last_update) values (' +
IntToStr(tech.ID) + ',''' +
IntToStr(GetGameItemGroupID(tech.GroupName)) + ''',''' +
tech.Name + ''',' +
'current_timestamp) matching (id)';
FIBQuery.ExecQuery;
Result := true;
except
end;
end;
function TMoonDB.UpdateTechnologies(techs: TGameItems): boolean;
var
i: Integer;
begin
Result := true;
for i := 0 to length(techs) - 1 do
Result := Result and UpdateTechnologies(techs[i]);
end;
function TMoonDB.UpdateShipBook(ships: TShips): boolean;
var
i: Integer;
begin
Result := true;
for i := 0 to length(ships) - 1 do
Result := Result and UpdateShipBook(ships[i]);
end;
function TMoonDB.UpdateUser(user: TUser): boolean;
begin
Result := false;
if not FConnected then exit;
try
FIBQuery.SQL.Text := 'update or insert into gamers ' +
'(id, name, alliance, score, last_update) values (' +
IntToStr(user.ID) + ',''' +
user.Name + ''',''' +
user.Alliance + ''',' +
IntToStr(user.Score) + ',' +
'current_timestamp) matching (id)';
FIBQuery.ExecQuery;
Result := true;
except
end;
end;
function TMoonDB.UpdateUsers(users: TUserList): boolean;
var
i: Integer;
begin
Result := true;
for i := 0 to length(users) - 1 do
Result := Result and UpdateUser(users[i]);
end;
function TMoonDB.SetParam(ParamName, ParamValue: string): boolean;
begin
Result := false;
if not FConnected then exit;
try
FIBQuery.SQL.Text := 'update or insert into params (id, name, val) values ' +
'(gen_id(gen_params_id,1), ''' + ParamName + ''', ''' + ParamValue + ''') matching (name)';
FIBQuery.ExecQuery;
Commit;
Result := true;
except
end;
end;
end.
|
unit MCProject;
interface
uses Word, System.Generics.Collections, System.SysUtils, System.Types,
System.UITypes, System.Classes, System.Math,
System.Variants, FMX.Objects, FMX.StdCtrls, FMX.Types, FMX.Layouts;
type
TMCProject = class
private
FFilePath: string;
FWordList: TStringList;
FDefList: TStringList;
FWithoutDef: boolean;
public
constructor Create;
destructor Destroy; override;
procedure OpenFile(FilePath: string);
procedure Save(FilePath: String);
property FilePath: string read FFilePath write FFilePath;
property WordList: TStringList read FWordList write FWordList;
property DefList: TStringList read FDefList write FDefList;
property WithoutDef: boolean read FWithoutDef write FWithoutDef default false;
end;
implementation
constructor TMCProject.Create;
begin
FWordList := TStringList.Create;
FDefList := TStringList.Create;
FFilePath := '';
end;
destructor TMCProject.Destroy;
begin
FWordList.Free;
FDefList.Free;
FFilePath := '';
end;
procedure TMCProject.OpenFile(FilePath: string);
var
ts: TStringList;
i: integer;
begin
ts := TStringList.Create;
try
ts.LoadFromFile(FilePath);
if ts.Strings[0] <> '//WordList' then
raise Exception.Create('Ceci n''est pas un fichier MarmotCrossword!');
i := 1;
while ts.Strings[i] <> '//DefList' do
begin
FWordList.Add(ts.Strings[i]);
i := i + 1;
end;
i := i + 1;
while i < ts.Count do
begin
FDefList.Add(ts.Strings[i]);
i := i + 1;
end;
if FWordList.Count <> FDefList.Count then
raise Exception.Create
('Le nombre de mots ne correspond pas au nombre de définitions...');
finally
ts.Free;
end;
end;
procedure TMCProject.Save(FilePath: String);
var
ts: TStringList;
i: Integer;
begin
ts := TStringList.Create;
ts.Add('//WordList');
try
for i := 0 to FWordList.Count - 1 do
ts.Add(FWordList.Strings[i]);
ts.Add('//DefList');
for i := 0 to FDefList.Count - 1 do
ts.Add(FDefList.Strings[i]);
ts.SaveToFile(FilePath);
finally
ts.Free;
end;
end;
end.
|
//-----------------------------------------
// Maciej Czekański
// maves90@gmail.com
//-----------------------------------------
unit Math;
//----------------------------------------------------------------------------------------
interface
//----------------------------------------------------------------------------------------
CONST
EPSILON = 0.000001; // Dokładność do której przybliżane jest 0
TYPE
// Klasa reprezentująca wektor 2D. Przeładowuje podstawowe operatory takie jak dodawanie czy negacja.
TVector2 = object
public
x, y: Real;
function Len: Real;
function SquareLen: Real;
procedure Normalize;
end;
// Struktura opisująca prostokąt. Jego boki są zawsze równoległe do osi X oraz Y.
TRectF = record
x, y, width, height: Real;
end;
// Podstawowe operacje na wektorach
operator -(v: TVector2):TVector2;
operator +(a, b: TVector2):TVector2;
operator -(a, b: TVector2):TVector2;
operator *(s: Real; v: TVector2):TVector2;
operator *(v:TVector2; s: Real): TVector2;
operator /(v: TVector2; s: Real):TVector2;
operator =(a, b: TVector2): boolean;
operator =(a, b: TRectF): boolean;
// Iloczyn skalarny
function Dot( a, b: TVector2): Real;
// Iloczyn wektorowy
function CrossRight(a: TVector2): TVector2;
function CrossLeft(a: TVector2): TVector2;
// Odbicie
function Reflect( I, N: TVector2): TVector2;
// Projekcja wektora na wektor
function Project( a, b: TVector2): TVector2;
// Przycina podaną wartość do danego przedziału
function Clamp(var x: Real; a, b: Real): Real;
//----------------------------------------------------------------------------------------
// K O L I Z J E
//----------------------------------------------------------------------------------------
// parametr outVec w poniższych funkcjach oznacza najkrótszy wektor o jaki należy przesunąć kolidujący obiekt
// aby kolizja nie występowała.
// Funkcja sprawdzająca czy dany punkt znajduje się wewnątrz wielokąta.
// Podany wielokąt musi być wypukły.
function PointInPolygon(P: TVector2; Verts: array of TVector2): boolean;
// Funkcja sprawdzająca czy odcinek przecina wielokąt
function SegmentToPolygon( startP, endP: TVector2; verts: array of TVector2; out nearN, farN: TVector2): boolean;
// Funkcje pomocnicze
function AxisSeparatePolygons( var axis: TVector2; polyA, polyB: array of TVector2): boolean;
function FindPushVec( pushVectors: array of TVector2; n: longint): TVector2;
procedure CalculateInterval( axis: TVector2; poly: array of TVector2; out min, max: Real);
// Funkcja sprawdzająca czy wielokąt przecina wielokąt
function PolygonToPolygon( polyA, polyB: array of TVector2; out pushVec: TVector2): boolean;
// Funkcja sprawdzająca czy odcinek przecina koło
function CircleToSegment( circlePos: TVector2; radius: Real; A, B: TVector2; out pushVec: TVector2): boolean;
// Funkcja sprawdzająca czy prosta przecina okrąg
function CircleToLine( circlePos: TVector2; radius: Real; A, B: TVector2; out pushVec: TVector2 ): boolean;
// Funkcja sprawdzająca czy Wielokąt przecina koło
function CircleToPolygon( circlePos: TVector2; radius: Real; poly: array of TVector2; out pushVec: TVector2): boolean;
//funkcja sprawdzająca czy koło przecina koło
function CircleToCircle( circlePosA: TVector2; radiusA: Real; circlePosB: TVector2; radiusB: Real; out pushVec: TVector2): boolean;
// Funkcja sprawdzająca czy koło przecina prostokąt
function CircleToRect( center: TVector2; radius: Real; rect: TRectF; out N: TVector2): boolean;
// Funkcja sprwdzająca czy punkt znajduje się wewnątrz prostokąta
function PointInRect( x, y: Real; rect: TRectF ): boolean;
// Funkcja sprawdzająca czy prostokąt przecina prostokąt
function RectToRect( a, b: TRectF ): boolean;
//----------------------------------------------------------------------------------------
implementation
//----------------------------------------------------------------------------------------
operator -(v: TVector2):TVector2;
begin
result.x := -v.x;
result.y := -v.y;
end;
operator +(a, b: TVector2): TVector2;
begin
result.x := a.x + b.x;
result.y := a.y + b.y;
end;
operator -(a, b: TVector2): TVector2;
begin
result.x := a.x - b.x;
result.y := a.y - b.y;
end;
operator *(s: Real; v: TVector2) :TVector2;
begin
result.x := s*v.x;
result.y := s*v.y;
end;
operator *(v:TVector2; s: Real): TVector2;
begin
result.x := s*v.x;
result.y := s*v.y;
end;
operator /(v: TVector2; s: Real):TVector2;
begin
result.x := v.x/s;
result.y := v.y/s;
end;
operator =(a, b: TVector2): boolean;
begin
result:= (a.x = b.x) AND (a.y = b.y);
end;
function TVector2.Len: Real;
begin
result := sqrt((x*x) + (y*y));
end;
function TVector2.SquareLen: Real;
begin
result := (x*x) + (y*y);
end;
procedure TVector2.Normalize;
VAR
invLen: Real;
begin
if Len < EPSILON then
exit;
invLen := 1.0/Len;
x := x*invLen;
y := y*invLen;
end;
function Dot(a, b: TVector2):Real;
begin
result:= (a.x*b.x) + (a.y*b.y);
end;
function CrossRight(a: TVector2): TVector2;
begin
result.x := -a.y;
result.y := a.x;
end;
function CrossLeft(a: TVector2):TVector2;
begin
result.x := a.y;
result.y := -a.x;
end;
function Reflect( I, N: TVector2): TVector2;
var
d: Real;
begin
d:= Dot(I, N);
result.x:= I.x - 2.0*d*N.x;
result.y:= I.y - 2.0*d*N.y;
end;
function Project( a, b: TVector2): TVector2;
VAR
dp: Real;
begin
dp:= Dot(a,b);
result.x:= (dp/b.SquareLen)*b.x;
result.y:= (dp/b.SquareLen)*b.y;
end;
function Clamp(var x: Real; a, b: Real): Real;
begin
if x < a then
x:= a
else if x > b then
x:= b;
result:= x;
end;
operator =(a, b: TRectF): boolean;
begin
result:= (a.x = b.x) AND (a.y = b.y) AND (a.width = b.width) AND (a.height = b.height);
end;
// Kolizje
function PointInPolygon(P: TVector2; verts: array of TVector2): boolean;
VAR
i, j: longint;
vecA, vecB: TVector2;
begin
j:= high(verts);
for i:= 0 to high(verts) do begin
vecA:= CrossRight(verts[i] - verts[j]);
vecB:= P - verts[j];
if Dot(vecB, vecA) > 0.0 then begin
result:= false;
exit;
end;
j:= i;
end;
result:= true;
end;
function SegmentToPolygon( startP, endP: TVector2; verts: array of TVector2; out nearN, farN: TVector2): boolean;
var
i, j: longint;
denom, numer, tclip, tnear, tfar: Real;
xDir, En, D: TVector2;
begin
xDir:= endP - startP;
tnear:= 0.0;
tfar:= 1.0;
j:= high(verts);
for i:= 0 to high(verts) do begin
En:= CrossRight(verts[i] - verts[j]);
D:= verts[j] - startP;
denom:= Dot(En, D);
numer:= Dot(En, xDir);
if abs(numer) < 1e-5 then begin
if denom < 0.0 then begin
result:= false;
exit;
end;
end
else begin
tclip:= denom/numer;
if numer < 0.0 then begin
if tclip > tfar then begin
result:= false;
exit;
end;
if tclip > tnear then begin
tnear:= tclip;
nearN:= startP + xDir*tnear;
end;
end
else begin
if tclip < tnear then begin
result:= false;
exit;
end;
if tclip < tfar then begin
tfar:= tclip;
farN:= startP + xDir*tfar;
end;
end;
end;
j:= i;
end;
result:= true;
end;
function PolygonToPolygon( polyA, polyB: array of TVector2; out pushVec: TVector2): boolean;
var
i, j, axisCount: longint;
En: TVector2;
axis: array[0..64] of TVector2;
polyAPos, polyBPos: TVector2;
begin
axisCount:= 0;
polyAPos.x:= 0;
polyAPos.y:= 0;
polyBPos.x:= 0;
polyBPos.y:= 0;
j:= high(polyA);
for i:= 0 to high(polyA) do begin
polyAPos := polyAPos + polyA[i];
En:= CrossRight(polyA[i] - polyA[j]);
axis[axisCount]:= En;
if AxisSeparatePolygons(axis[axisCount], polyA, polyB) = true then begin
result:= false;
exit;
end;
j:= i;
inc(axisCount);
end;
polyAPos:= polyAPos / length(polyA);
j:= high(polyB);
for i:= 0 to high(polyB) do begin
polyBPos:= polyBPos + polyB[i];
En:= CrossRight(polyB[i] - polyB[j]);
axis[axisCount]:= En;
if AxisSeparatePolygons(axis[axisCount], polyA, polyB) = true then begin
result:= false;
exit;
end;
j:= i;
inc(axisCount);
end;
polyBPos:= polyBPos / length(polyB);
pushVec := FindPushVec(axis, axisCount);
if Dot(pushVec, polyBPos - polyAPos) < 0 then
pushVec := -pushVec;
result:= true;
end;
function AxisSeparatePolygons( var axis: TVector2; polyA, polyB: array of TVector2): boolean;
var
minA, maxA, minB, maxB: Real;
d0, d1, depth: Real;
axis_len_sq: Real;
begin
CalculateInterval(axis, polyA, minA, maxA);
CalculateInterval(axis, polyB, minB, maxB);
if (minA > maxB) or (minB > maxA) then begin
result:= true;
exit;
end;
d0:= maxA - minB;
d1:= maxB - minA;
if d0 < d1 then begin
depth:= d0;
end
else begin
depth:= d1;
end;
axis_len_sq:= Dot(axis, axis);
Axis:= Axis*(depth/axis_len_sq);
result:= false;
end;
function FindPushVec( pushVectors: array of TVector2; n: longint): TVector2;
var
minLenSq, lenSq: Real;
i: longint;
begin
result:= pushVectors[0];
minLenSq:= Dot(pushVectors[0], pushVectors[0]);
for i:= 1 to n-1 do begin
lenSq:= Dot(pushVectors[i], pushVectors[i]);
if lenSq < minLenSq then begin
minLenSq:= lenSq;
result:= pushVectors[i];
end;
end;
end;
procedure CalculateInterval( axis: TVector2; poly: array of TVector2; out min, max: Real);
var
i: longint;
d: Real;
begin
d:= Dot(axis, poly[0]);
min:= d;
max:= d;
for i:= 0 to high(poly) do begin
d:= Dot(axis, poly[i]);
if d < min then begin
min:= d;
end
else if d > max then begin
max:= d;
end;
end;
end;
{
function CircleToPolygon( circlePos: TVector2; radius: Real; poly: array of TVector2; out pushVec: TVector2): boolean;
var
i: longint;
closestPoint: TVector2;
dist, distSq, newDistSq: Real;
polyPos: TVector2;
begin
polyPos.x:= 0;
polyPos.y:= 0;
closestPoint:= poly[0];
distSq:= (circlePos - poly[0]).SquareLen;
polyPos:= poly[0];
for i:= 1 to high(poly) do begin
polyPos := polyPos + poly[i];
newDistSq:= (circlePos - poly[i]).SquareLen;
if newDistSq < distSq then begin
distSq:= newDistSq;
closestPoint:= poly[i];
end;
end;
polyPos:= polyPos / length(poly);
if distSq > radius*radius then begin
result:= false;
exit;
end;
dist:= sqrt(distSq);
pushVec:= (circlePos - closestPoint) * ((radius - dist) / dist);
if Dot(pushVec, circlePos - polyPos) < 0 then
pushVec := -pushVec;
result:= true;
end;
}
// Kolizja z prostą wygląda podobnie, tylko bez clamp
function CircleToSegment( circlePos: TVector2; radius: Real; A, B: TVector2; out pushVec: TVector2): boolean;
var
dir, diff, D, closest: TVector2;
t, dist: Real;
begin
dir:= B - A;
diff:= circlePos - A;
t:= Dot(diff, dir) / Dot(dir, dir);
Clamp(t, 0.0, 1.0);
closest:= A + t*dir;
D:= circlePos - closest;
dist:= d.Len;
if dist <= radius then
begin
result:= true;
pushVec:= d;
pushVec.Normalize;
pushVec:= (radius-dist)*pushVec;
pushVec:=pushVec/5; //? :| :TODO:
exit;
end;
result:= false;
end;
function CircleToLine( circlePos: TVector2; radius: Real; A, B: TVector2; out pushVec: TVector2 ): boolean;
var
dir, diff, d, closest: TVector2;
t, dist: Real;
begin
dir:= B - A;
diff:= circlePos - A;
t:= Dot(diff, dir) / Dot(dir, dir);
closest:= A + t*dir;
D:= circlePos - closest;
dist:= d.Len;
if dist <= radius then
begin
result:= true;
pushVec:= d;
pushVec.Normalize;
pushVec:= (radius-dist)*pushVec;
pushVec:=pushVec/5; //? :| :TODO:
exit;
end;
result:= false;
end;
// Sprawdzam po której stronie ściany znajduje się środek okręgu. Są 3 przypadki:
//1. Dla każdej ściany środek leży po lewej stronie - NIE DOPUŚCIĆ do takiej sytuacji
//2. Dla jednej ściany środek lezy po prawej - kolizja okrąg-odcinek
// odległość okrąg-prosta na której leży ściana < 0
// nie musiby sprawdzać czy rzut znajduje się na krawędzi bo wtedy zachodzi przypadek 3.
//3. Dla dwóch ścian środek leży po prawej - kolizja okrąg-punkt z najbliższym wierzchołkiem
function CircleToPolygon( circlePos: TVector2; radius: Real; poly: array of TVector2; out pushVec: TVector2): boolean;
var
i, j: longint;
N, V, closestVertex: TVector2;
numEdges: longint;
newDist, distToEdge, distToVertex: Real;
begin
distToEdge:= 10e4;
distToVertex:= 10e4;
numEdges:= 0;
closestVertex := poly[0];
j:= high(poly);
for i:= 0 to high(poly) do begin
N:= CrossRight(poly[i] - poly[j]); // normalna ściany
N.Normalize;
V:= circlePos - poly[i]; // wektor wierzchołek-środekOkręgu
newDist:= Dot(N, V);
if newDist > 0.0 then begin
Inc(numEdges);
end;
if abs(newDist) < distToEdge then begin
distToEdge:= abs(newDist);
pushVec:= N;
end;
newDist:= (circlePos - poly[i]).Len;
if newDist < distToVertex then begin
distToVertex := newDist;
closestVertex:= poly[i];
end;
j:= i;
end;
if numEdges = 1 then begin // kolizja okrąg-prosta
//WriteLn(1);
if distToEdge < radius then begin
result:= true;
exit;
end
end
else if numEdges = 2 then begin // kolizja okrąg-punkt
//WriteLn(2);
if PointInPolygon( circlePos, closestVertex) = true then begin
result:= true;
pushVec:= (circlePos-closestVertex);
exit;
end;
end;
result:= false;
end;
function CircleToCircle( circlePosA: TVector2; radiusA: Real; circlePosB: TVector2; radiusB: Real; out pushVec: TVector2): boolean;
var
diff: TVector2;
dist: Real;
begin
diff:= circlePosB - circlePosA;
dist:= diff.Len;
if dist < radiusA + radiusB then begin
pushVec:= diff;
pushVec.Normalize;
pushVec:= (dist - radiusA - radiusB)*pushVec;
result:= true;
exit;
end;
result:= false;
end;
function CircleToRect( center: TVector2; radius: Real; rect: TRectF; out N: TVector2): boolean;
var
distX, distY, absDistX, absDistY, halfW, halfH: Real;
cornerDistSq: Real;
temp, tempN: TVector2;
begin
halfW:= rect.width * 0.5;
halfH:= rect.height * 0.5;
distX:= center.x - rect.x - halfW;
distY:= center.y - rect.y - halfH;
absDistX:= abs(distX);
absDistY:= abs(distY);
if absDistX > (halfW + radius) then begin
result:= false;
exit;
end;
if absDistY > (halfH + radius) then begin
result:= false;
exit;
end;
if absDistX <= halfW then begin
result:= true;
if distY < 0 then // okrąg ponad prostokątem
N.y:= rect.y -radius - center.y
else
N.y:= rect.y + rect.height + radius - center.y;
N.x:= 0;
exit;
end;
if absDistY <= halfH then begin
result:= true;
if distX < 0 then
N.x:= rect.x - radius - center.x
else
N.x:= rect.x + rect.width + radius - center.x;
N.y:=0;
exit;
end;
cornerDistSq:= ((absDistX - halfW)*(absDistX - halfW))
+ ((absDistY - halfH)*(absDistY - halfH));
result:= cornerDistSq <= radius*radius;
if (distX > 0) and (distY > 0) then begin
N.x:= center.x - rect.x - rect.width;
N.y:= center.y - rect.y - rect.height;
end
else if (distX > 0) and (distY < 0) then begin
N.x:= center.x - rect.x - rect.width;
N.y:= center.y - rect.y;
end
else if (distX < 0) and (distY > 0) then begin
N.x:= center.x - rect.x;
N.y:= center.y - rect.y - rect.height;
end
else if (distX < 0) and (distY < 0) then begin
N.x:= center.x - rect.x;
N.y:= center.y - rect.y;
end;
tempN:= n;
tempN.Normalize;
temp:= center - tempN*radius;
N:= (center-N) - temp;
end;
function PointInRect( x, y: Real; rect: TRectF): boolean;
begin
result:= (x >= rect.x) AND
(x <= rect.x + rect.width) AND
(y >= rect.y) AND
(y <= rect.y + rect.height);
end;
function RectToRect( a, b: TRectF ): boolean;
begin
result:= (a.x < b.x + b.width) AND
(a.x + a.width > b.x) AND
(a.y < b.y + b.height) AND
(a.y + a.height > b.y);
end;
//-----------------------------------------
begin
end. |
unit mystruct_c;
{This file was generated on 11 Aug 2000 20:16:59 GMT by version 03.03.03.C1.06}
{of the Inprise VisiBroker idl2pas CORBA IDL compiler. }
{Please do not edit the contents of this file. You should instead edit and }
{recompile the original IDL which was located in the file mystruct.idl. }
{Delphi Pascal unit : mystruct_c }
{derived from IDL module : default }
interface
uses
CORBA,
mystruct_i;
type
TMyStructTypeHelper = class;
TMyStructType = class;
TAccountHelper = class;
TAccountStub = class;
TMyStructTypeHelper = class
class procedure Insert (var _A: CORBA.Any; const _Value : mystruct_i.MyStructType);
class function Extract(const _A: CORBA.Any): mystruct_i.MyStructType;
class function TypeCode : CORBA.TypeCode;
class function RepositoryId: string;
class function Read (const _Input : CORBA.InputStream) : mystruct_i.MyStructType;
class procedure Write(const _Output : CORBA.OutputStream; const _Value : mystruct_i.MyStructType);
end;
TMyStructType = class (TInterfacedObject, mystruct_i.MyStructType)
private
s : SmallInt;
l : Integer;
st : AnsiString;
constructor Create; overload;
public
function _get_s : SmallInt; virtual;
procedure _set_s ( const _value : SmallInt ); virtual;
function _get_l : Integer; virtual;
procedure _set_l ( const _value : Integer ); virtual;
function _get_st : AnsiString; virtual;
procedure _set_st ( const _value : AnsiString ); virtual;
constructor Create (const s : SmallInt;
const l : Integer;
const st : AnsiString
); overload;
end;
TAccountHelper = class
class procedure Insert (var _A: CORBA.Any; const _Value : mystruct_i.Account);
class function Extract(var _A: CORBA.Any) : mystruct_i.Account;
class function TypeCode : CORBA.TypeCode;
class function RepositoryId : string;
class function Read (const _Input : CORBA.InputStream) : mystruct_i.Account;
class procedure Write(const _Output : CORBA.OutputStream; const _Value : mystruct_i.Account);
class function Narrow(const _Obj : CORBA.CORBAObject; _IsA : Boolean = False) : mystruct_i.Account;
class function Bind(const _InstanceName : string = ''; _HostName : string = '') : mystruct_i.Account; overload;
class function Bind(_Options : BindOptions; const _InstanceName : string = ''; _HostName: string = '') : mystruct_i.Account; overload;
end;
TAccountStub = class(CORBA.TCORBAObject, mystruct_i.Account)
public
function balance ( const inMyStruct : mystruct_i.MyStructType;
out outMyStruct : mystruct_i.MyStructType;
var inoutMyStruct : mystruct_i.MyStructType): Single; virtual;
end;
implementation
class procedure TMyStructTypeHelper.Insert(var _A : CORBA.Any; const _Value : mystruct_i.MyStructType);
var
_Output : CORBA.OutputStream;
begin
_Output := ORB.CreateOutputStream;
TMyStructTypeHelper.Write(_Output, _Value);
ORB.PutAny(_A, TMyStructTypeHelper.TypeCode, _Output);
end;
class function TMyStructTypeHelper.Extract(const _A : CORBA.Any) : mystruct_i.MyStructType;
var
_Input : CORBA.InputStream;
begin
Orb.GetAny(_A, _Input);
Result := TMyStructTypeHelper.Read(_Input);
end;
class function TMyStructTypeHelper.TypeCode : CORBA.TypeCode;
var
_Seq: StructMemberSeq;
begin
SetLength(_Seq, 3);
_Seq[0].Name := 's';
_Seq[0].TC := ORB.CreateTC(Integer(tk_short));
_Seq[1].Name := 'l';
_Seq[1].TC := ORB.CreateTC(Integer(tk_long));
_Seq[2].Name := 'st';
_Seq[2].TC := ORB.CreateTC(Integer(tk_string));
Result := ORB.MakeStructureTypecode(RepositoryID, 'MyStructType', _Seq);
end;
class function TMyStructTypeHelper.RepositoryId : string;
begin
Result := 'IDL:MyStructType:1.0';
end;
class function TMyStructTypeHelper.Read(const _Input : CORBA.InputStream) : mystruct_i.MyStructType;
var
_Value : mystruct_c.TMyStructType;
begin
_Value := mystruct_c.TMyStructType.Create;
_Input.ReadShort(_Value.s);
_Input.ReadLong(_Value.l);
_Input.ReadString(_Value.st);
Result := _Value;
end;
class procedure TMyStructTypeHelper.Write(const _Output : CORBA.OutputStream; const _Value : mystruct_i.MyStructType);
begin
_Output.WriteShort(_Value.s);
_Output.WriteLong(_Value.l);
_Output.WriteString(_Value.st);
end;
constructor TMyStructType.Create;
begin
inherited Create;
end;
constructor TMyStructType.Create(const s: SmallInt;
const l: Integer;
const st: AnsiString);
begin
Self.s := s;
Self.l := l;
Self.st := st;
end;
function TMyStructType._get_s: SmallInt;
begin
Result := s;
end;
procedure TMyStructType._set_s(const _Value : SmallInt);
begin
s := _Value;
end;
function TMyStructType._get_l: Integer;
begin
Result := l;
end;
procedure TMyStructType._set_l(const _Value : Integer);
begin
l := _Value;
end;
function TMyStructType._get_st: AnsiString;
begin
Result := st;
end;
procedure TMyStructType._set_st(const _Value : AnsiString);
begin
st := _Value;
end;
class procedure TAccountHelper.Insert(var _A : CORBA.Any; const _Value : mystruct_i.Account);
begin
_A := Orb.MakeObjectRef( TAccountHelper.TypeCode, _Value as CORBA.CORBAObject);
end;
class function TAccountHelper.Extract(var _A : CORBA.Any): mystruct_i.Account;
var
_obj : Corba.CorbaObject;
begin
_obj := Orb.GetObjectRef(_A);
Result := TAccountHelper.Narrow(_obj, True);
end;
class function TAccountHelper.TypeCode : CORBA.TypeCode;
begin
Result := ORB.CreateInterfaceTC(RepositoryId, 'Account');
end;
class function TAccountHelper.RepositoryId : string;
begin
Result := 'IDL:Account:1.0';
end;
class function TAccountHelper.Read(const _Input : CORBA.InputStream) : mystruct_i.Account;
var
_Obj : CORBA.CORBAObject;
begin
_Input.ReadObject(_Obj);
Result := Narrow(_Obj, True)
end;
class procedure TAccountHelper.Write(const _Output : CORBA.OutputStream; const _Value : mystruct_i.Account);
begin
_Output.WriteObject(_Value as CORBA.CORBAObject);
end;
class function TAccountHelper.Narrow(const _Obj : CORBA.CORBAObject; _IsA : Boolean) : mystruct_i.Account;
begin
Result := nil;
if (_Obj = nil) or (_Obj.QueryInterface(mystruct_i.Account, Result) = 0) then
exit;
if _IsA and _Obj._IsA(RepositoryId) then
Result := TAccountStub.Create(_Obj);
end;
class function TAccountHelper.Bind(const _InstanceName : string = ''; _HostName: string = '') : mystruct_i.Account;
begin
Result := Narrow(ORB.bind(RepositoryId, _InstanceName, _HostName), True);
end;
class function TAccountHelper.Bind(_Options : BindOptions; const _InstanceName : string = ''; _HostName : string = '') : mystruct_i.Account;
begin
Result := Narrow(ORB.bind(RepositoryId, _Options, _InstanceName, _HostName), True);
end;
function TAccountStub.balance ( const inMyStruct : mystruct_i.MyStructType;
out outMyStruct : mystruct_i.MyStructType;
var inoutMyStruct : mystruct_i.MyStructType): Single;
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('balance',True, _Output);
mystruct_c.TMyStructTypeHelper.Write(_Output, inMyStruct);
mystruct_c.TMyStructTypeHelper.Write(_Output, inoutMyStruct);
inherited _Invoke(_Output, _Input);
_Input.ReadFloat(Result);
outMyStruct := mystruct_c.TMyStructTypeHelper.Read(_Input);
inoutMyStruct := mystruct_c.TMyStructTypeHelper.Read(_Input);
end;
initialization
end. |
unit if32_const_1;
interface
function Test: float32; export;
implementation
uses System;
function Test: float32;
begin
Result := 0.0003;
end;
initialization
Test();
finalization
end. |
unit DW.RegisterFCM;
(*
DelphiWorlds PushClient project
------------------------------------------
A cross-platform method of using Firebase Cloud Messaging (FCM) to receive push notifications
This project was inspired by the following article:
http://thundaxsoftware.blogspot.co.id/2017/01/firebase-cloud-messaging-with-delphi.html
*)
{$I DW.GlobalDefines.inc}
interface
uses
// RTL
System.Classes;
type
TFCMRequestCompleteEvent = procedure (Sender: TObject; const Success: Boolean; const RequestResult: string) of object;
TRegisterFCM = class(TObject)
private
FOnRequestComplete: TFCMRequestCompleteEvent;
procedure DoParseResult(const AContent: string);
procedure DoRequestComplete(const ASuccess: Boolean; const ARequestResult: string);
procedure DoRegister(const AServerKey: string; const ARequest: TStream);
procedure DoRegisterAPNToken(const AServerKey, ARequest: string);
public
/// <summary>
/// Sends a request to Google APIs to convert an APNs token to an FCM token
/// </summary>
/// <remarks>
/// AAppBundleID should match the bundle id for the app specified on FCM
/// AServerKey is the server key specified on FCM
/// AToken is the iOS device token returned when starting the APS push service
/// </remarks>
procedure RegisterAPNToken(const AAppBundleID, AServerKey, AToken: string; const ASandbox: Boolean = False);
property OnRequestComplete: TFCMRequestCompleteEvent read FOnRequestComplete write FOnRequestComplete;
end;
implementation
uses
// RTL
System.SysUtils, System.Net.HttpClient, System.Net.URLClient, System.NetConsts, System.JSON, System.Threading,
// REST
REST.Types;
const
cSandboxValues: array[Boolean] of string = ('false', 'true');
cHTTPResultOK = 200;
cFCMIIDBatchImportURL = 'https://iid.googleapis.com/iid/v1:batchImport';
cFCMAuthorizationHeader = 'Authorization';
cFCMAuthorizationHeaderValuePair = 'key=%s';
cResultsValueName = 'results';
cStatusValueName = 'status';
cRegistrationTokenValueName = 'registration_token';
cStatusValueOK = 'OK';
cFCMResultError = 'FCM Result Error: %s';
cFCMJSONError = 'FCM Unexpected JSON: %s';
cHTTPError = 'HTTP Error: %s. Response: %s';
cFCMRequestJSONTemplate = '{ "application": "%s", "sandbox": %s, "apns_tokens": [ "%s" ] }';
{ TRegisterFCM }
procedure TRegisterFCM.DoRequestComplete(const ASuccess: Boolean; const ARequestResult: string);
begin
if Assigned(FOnRequestComplete) then
begin
TThread.Synchronize(nil,
procedure
begin
FOnRequestComplete(Self, ASuccess, ARequestResult);
end
);
end;
end;
procedure TRegisterFCM.DoParseResult(const AContent: string);
var
LResponse: TJSONValue;
LResult: TJSONObject;
LResults: TJSONArray;
LToken, LStatus: string;
LIsParseOK: Boolean;
begin
LIsParseOK := False;
LResponse := TJSONObject.ParseJSONValue(AContent);
if (LResponse <> nil) and LResponse.TryGetValue<TJSONArray>(cResultsValueName, LResults) then
try
if (LResults.Count > 0) and (LResults.Items[0] is TJSONObject) then
begin
LResult := TJSONObject(LResults.Items[0]);
LResult.TryGetValue<string>(cRegistrationTokenValueName, LToken);
LResult.TryGetValue<string>(cStatusValueName, LStatus);
if not LStatus.IsEmpty then
begin
LIsParseOK := True;
if not LStatus.Equals(cStatusValueOK) then
DoRequestComplete(False, Format(cFCMResultError, [LStatus]))
else if not LToken.IsEmpty then
DoRequestComplete(True, LToken) // Status of OK, token present
else
LIsParseOK := False; // Status of OK, but token missing
end;
end;
finally
LResponse.Free;
end;
if not LIsParseOK then
DoRequestComplete(False, Format(cFCMJSONError, [AContent]));
end;
procedure TRegisterFCM.DoRegister(const AServerKey: string; const ARequest: TStream);
var
LHTTP: THTTPClient;
LResponse: IHTTPResponse;
begin
// Use the native HTTP client to send the request
LHTTP := THTTPClient.Create;
try
LHTTP.CustomHeaders[cFCMAuthorizationHeader] := Format(cFCMAuthorizationHeaderValuePair, [AServerKey]);
LHTTP.ContentType := CONTENTTYPE_APPLICATION_JSON;
LResponse := LHTTP.Post(cFCMIIDBatchImportURL, ARequest);
if LResponse.StatusCode = cHTTPResultOK then
DoParseResult(LResponse.ContentAsString)
else
DoRequestComplete(False, Format(cHTTPError, [LResponse.StatusText, LResponse.ContentAsString]));
finally
LHTTP.Free;
end;
end;
procedure TRegisterFCM.DoRegisterAPNToken(const AServerKey, ARequest: string);
var
LStream: TStream;
begin
LStream := TStringStream.Create(ARequest);
try
DoRegister(AServerKey, LStream);
finally
LStream.Free;
end;
end;
procedure TRegisterFCM.RegisterAPNToken(const AAppBundleID, AServerKey, AToken: string; const ASandbox: Boolean = False);
begin
// Do the request asynch via TTask
TTask.Run(
procedure
begin
DoRegisterAPNToken(AServerKey, Format(cFCMRequestJSONTemplate, [AAppBundleID, cSandboxValues[ASandbox], AToken]));
end
);
end;
end.
|
{*
* Tyler Filla
* February 4, 2019
* CS 4500-001 :: Intro to Software Profession
*
* This program intends to implement the specified game and program behavior: A
* strongly-connected digraph is drawn on an imaginary game board, and a marker
* is randomly moved along the edges until all nodes have been visited. Each
* node counts the number of times it has been visited, and some statistics are
* produced after the game completes.
*
* The words "node" and "circle" are used interchangeably. Also, the words
* "arrow" and "edge" are used interchangeably.
*
* FILES: An input file containing a description of a strongly-connected digraph
* must be supplied and named 'HW1infile.txt' in the current working directory.
* A transcript will be produced in the file 'HW1fillaOutfile.txt'. These files
* are considered mission critical, so I/O errors may cause early termination.
*
* INPUT FILE FORMAT: The input file must conform to a strict textual format:
* - One line containing the integer number N, the number of circles (nodes)
* - One line containing the integer number K, the number of arrows (edges)
* - K lines, one edge (arrow) per line, containing two integer numbers each
* - The first integer number, per line, is the source circle number
* - The second integer number, per line, is the destination circle number
*
* The program will make a good faith effort to identify issues in formatting;
* however, not every pathological input file has been tested.
*
* GOOD INPUT FILE EXAMPLE:
* 4
* 5
* 1 2
* 2 1
* 2 3
* 3 4
* 4 1
*
* In this example, four circles are described (N=4 on the first line). Five
* arrows (K=5 on the second line) are to be provided by the five following
* lines. The third line prescribes an arrow from circle 1 to circle 2, the
* fourth line prescribes an arrow from circle 2 to circle 1, and so on.
* Gameplay can proceed without error.
*
* BAD INPUT FILE EXAMPLE:
* 4
* 5
* 1 2
* 2 1
* 2 3
* 3 4
*
* This is an example of a bad input file whose formatting issues will be
* identified by the program. As you can see, five arrows are prescribed (K=5 on
* the second line), but only four are defined in the lines that follow. The
* program will abort on account of premature EOF.
*
* INTERNALS: The program represents each circle (node) as a record with three
* members: Number, Marks, and Arrows. The Number integer associates each circle
* with its numeric index (starting with 1, not 0). The Marks integer counts the
* total number of checkmarks placed on the circle. The Arrows member is a
* dynamic array of pointers to other circles. Each arrow is represented in
* memory as a pointer to the destination node stored inside the source node.
*
* Basic statistics are kept in global variables as the game progresses. These
* include tallies on total- and uniquely-marked circles, as well as a counter
* for the total number of checkmarks drawn (visits made) overall.
*
* NOTE: All program output, less unhandled exceptions, is mirrored to the
* output file via a custom "MyWriteLn" function that composes two "WriteLn"
* calls. I wished to find a redirection system in Pascal similar to C++'s
* std::ios::rdbuf(...), but I was unable to. My final solution is less elegant,
* but it works.
*}
{ Enable exceptions if not already. }
{$I+}
{$mode objfpc}
program main;
uses sysutils, regexpr;
const
{ The name of the input file. }
C_FILENAME_IN = 'HW1infile.txt';
{ The name of the output file. }
C_FILENAME_OUT = 'HW1fillaOutfile.txt';
type
{*
* An exception for input file errors.
*
* This is a catch-all exception thrown by the input file parser procedure
* when something doesn't go its way. Its message contains more details.
*}
EInputFileException = class(Exception);
{ Pointer to TCircle. See below. }
TCirclePtr = ^TCircle;
{*
* A circle on the whiteboard.
*
* One of these records tracks the relevant state of exactly one circle drawn
* on the imaginary whiteboard. Each circle knows its number (thus obviating
* the need to iterate the global circle array), and each circle counts its
* virtual checkmarks.
*
* The in-memory graph construction is based on simple pointers.
*}
TCircle = record
{ The number assigned to this circle. }
Number: integer;
{ The number of checkmarks placed on the circle. }
Marks: integer;
{ Connections to other circles (the arrows originating here). }
Arrows: array of TCirclePtr;
end;
var
{ The output text file. }
OutputFile: TextFile;
{ The number N. The number of circles in play. }
N: integer;
{ The number K. The number of arrows in play. }
K: integer;
{ Tracker for all allocated circles. }
AllCircles: array of TCircle;
{ A pointer to the current circle. }
CurrentCircle: TCirclePtr;
{ The unique number of circles marked. }
UniqueCirclesMarked: integer;
{ The total number of marks distributed. }
TotalCircleMarks: integer;
{ The maximum number of marks in any one circle. }
MaxSingleCircleMarks: integer;
{*
* Write output to stdout and the output file.
*
* @param Text The output text
*}
procedure MyWriteLn(const Text: string);
begin
{ To screen. Output is standard output. }
WriteLn(Output, Text);
{ To file. OutputFile is program-global. }
WriteLn(OutputFile, Text);
end;
{*
* Set up the circles from the given input file.
*
* @param Name The input file name
*}
procedure InitCirclesFromFile(const Name: string);
var
{ The opened input file. }
InputFile: TextFile;
{ An iterator index over 1..K. }
i: integer;
{ A temporary arrow string. }
ArrowStr: string;
{ A regular expression to arrow details. }
ArrowRegExpr: TRegExpr;
{ A temporary number of an arrow. }
ArrowNum: integer;
{ A temporary index of an arrow's source circle. }
ArrowSrc: integer;
{ A temporary index of an arrow's destination circle. }
ArrowDest: integer;
begin
MyWriteLn(Format('Initializing from input file %s', [Name]));
{ The input file. }
AssignFile(InputFile, Name);
{ Create the regular expression for pulling out arrow details. }
ArrowRegExpr := TRegExpr.Create;
ArrowRegExpr.Expression := '\d+';
try
try
{ Open the input file for read. }
Reset(InputFile);
{ Try to read variable N (number of circles). }
if Eof(InputFile) then
raise EInputFileException.create('Failed to read N: Premature EOF');
try
ReadLn(InputFile, N);
except
on E: Exception do
raise EInputFileException.create(Format('Failed to read N: %s: %s', [E.ClassName, E.Message]));
end;
{ Check range of N (from 2 to 10). }
if (N < 2) or (N > 10) then
raise EInputFileException.create(Format('N is out of range: %d', [N]));
{ Allocate N circles. }
SetLength(AllCircles, N);
{ Initialize allocated circles. }
for i := 1 to N do
begin
AllCircles[i - 1].Number := i;
AllCircles[i - 1].Marks := 0;
AllCircles[i - 1].Arrows := nil;
end;
{ Try to read variable K (number of arrows). }
if Eof(InputFile) then
raise EInputFileException.create('Failed to read K: Premature EOF');
try
ReadLn(InputFile, K);
except
on E: Exception do
raise EInputFileException.create(Format('Failed to read K: %s: %s', [E.ClassName, E.Message]));
end;
{ Check range of K (from 2 to 100). }
if (K < 2) or (K > 100) then
raise EInputFileException.create(Format('K is out of range: %d', [K]));
{ Read in K arrow definitions. }
for ArrowNum := 1 to K do
begin
{ Try to read arrow string. }
if Eof(InputFile) then
raise EInputFileException.create(Format('Failed to read arrow %d: Premature EOF', [ArrowNum]));
try
ReadLn(InputFile, ArrowStr);
except
on E: Exception do
raise EInputFileException.create(Format('Failed to read arrow %d: %s: %s', [ArrowNum, E.ClassName, E.Message]));
end;
{ Pull source and destination indices from line. }
if ArrowRegExpr.Exec(ArrowStr) then
begin
{ Pull source. }
try
ArrowSrc := ArrowRegExpr.Match[0].ToInteger;
except
on E: Exception do
raise EInputFileException.create(Format('Failed to read arrow %d source: %s: %s', [ArrowNum, E.ClassName, E.Message]));
end;
{ Pull destination. }
ArrowRegExpr.ExecNext;
try
ArrowDest := ArrowRegExpr.Match[0].ToInteger;
except
on E: Exception do
raise EInputFileException.create(Format('Failed to read arrow %d destination: %s: %s', [ArrowNum, E.ClassName, E.Message]));
end;
end;
{ Check range of arrow source index (from 1 to N). }
if (ArrowSrc < 1) or (ArrowSrc > N) then
raise EInputFileException.create(Format('Source index for arrow %d is out of range: %d', [ArrowNum, ArrowSrc]));
{ Check range of arrow destination index (from 1 to N). }
if (ArrowDest < 1) or (ArrowDest > N) then
raise EInputFileException.create(Format('Destination index for arrow %d is out of range: %d', [ArrowNum, ArrowDest]));
{ Establish the arrow connection in memory. This increments the length
of the source circle's arrow array and appends to it a pointer to
the destination circle. }
SetLength(AllCircles[ArrowSrc - 1].Arrows, Length(AllCircles[ArrowSrc - 1].Arrows) + 1);
AllCircles[ArrowSrc - 1].Arrows[High(AllCircles[ArrowSrc - 1].Arrows)] := @AllCircles[ArrowDest - 1];
end;
{ Set the first circle as current. }
CurrentCircle := @AllCircles[0];
except
{ Rethrow miscellaneous I/O errors under catch-all exception. }
on E: EInOutError do
raise EInputFileException.create(Format('Failed to read input file: %s: %s ', [E.ClassName, E.Message]));
end;
finally
{ Close the input file. }
CloseFile(InputFile);
{ Free arrow regular expression. }
ArrowRegExpr.Free;
end;
end;
{*
* Mark the current circle.
*}
procedure MarkCurrentCircle;
begin
{ Increment global mark statistic. }
Inc(TotalCircleMarks);
{ Increment the mark count on the current circle. }
Inc(CurrentCircle^.Marks);
{ Update maximum mark count if needed. }
if CurrentCircle^.Marks > MaxSingleCircleMarks then
MaxSingleCircleMarks := CurrentCircle^.Marks;
MyWriteLn(Format('Marked circle %d (up to %d mark(s))', [CurrentCircle^.Number, CurrentCircle^.Marks]));
end;
{*
* Carry out the game.
*}
procedure PlayGame;
var
{ The number of arrows from the current circle. This varies over gameplay. }
NumArrows: integer;
{ The last circle we were in. }
LastCircle: TCirclePtr;
{ The last randomly-chosen arrow index. }
ChosenArrow: integer;
begin
{ Core gameplay loop. Stops after all circles have been marked. }
while (UniqueCirclesMarked < N) do
begin
MyWriteLn('');
MyWriteLn(Format('Currently in circle %d', [CurrentCircle^.Number]));
{ Count arrows leaving the current circle. }
NumArrows := Length(CurrentCircle^.Arrows);
MyWriteLn(Format('-> %d arrow(s) point away from circle %d', [NumArrows, CurrentCircle^.Number]));
{ If no arrows are available, exit with error. This should not happen if
the input describes a strongly-connected digraph, but we handle the
error anyway. The user might have made a typo in the input file. }
if NumArrows = 0 then
begin
MyWriteLn(Format('FAIL: Stuck on circle %d: No arrows to follow', [CurrentCircle^.Number]));
MyWriteLn('The configured graph is not strongly-connected! Bailing out...');
Exit;
end;
{ Remember the current circle. }
LastCircle := CurrentCircle;
{ Randomly choose the next circle from the available arrows. }
ChosenArrow := Random(NumArrows);
CurrentCircle := CurrentCircle^.Arrows[ChosenArrow];
MyWriteLn(Format('Moved marker from circle %d to circle %d via arrow %d', [LastCircle^.Number, CurrentCircle^.Number, ChosenArrow]));
{ Mark the new current circle. }
MarkCurrentCircle();
{ If there was no mark on the circle to begin with... }
if CurrentCircle^.Marks = 1 then
begin
{ ... then we just hit it for the first time. Increment such count. }
Inc(UniqueCirclesMarked);
MyWriteLn(Format('-> Hit circle %d for the first time', [CurrentCircle^.Number]));
MyWriteLn(Format('-> Visited %d unique circles out of %d so far', [UniqueCirclesMarked, N]));
end;
end;
end;
{ Program entry point. }
begin
UniqueCirclesMarked := 0;
TotalCircleMarks := 0;
MaxSingleCircleMarks := 0;
{ The output file. This will be used to produce a transcript of the game. }
AssignFile(OutputFile, C_FILENAME_OUT);
{ Try to open the output file for write (creating it if needed). }
try
Rewrite(OutputFile);
except
on E: EInOutError do
begin
WriteLn(Format('Failed to open output file for write: %s', [E.Message]));
Exit;
end;
end;
{ Try to initialize from the input file. }
try
InitCirclesFromFile(C_FILENAME_IN);
except
on E: EInputFileException do
begin
MyWriteLn(Format('Input file error: %s', [E.Message]));
CloseFile(OutputFile);
Exit;
end;
end;
{ Get a new random sequence. }
Randomize();
MyWriteLn('Gameplay is about to begin.');
MyWriteLn('');
{ Mark the first circle as current. }
UniqueCirclesMarked := 1;
MarkCurrentCircle();
{ Play the game. }
PlayGame();
MyWriteLn('');
MyWriteLn('Gameplay is complete!');
MyWriteLn('');
MyWriteLn('~~~ LAST RUN STATISTICS ~~~');
MyWriteLn(Format('I. There were N=%d circles in play. This was prescribed by the input file.', [N]));
MyWriteLn(Format('II. There were K=%d arrow(s) in play. This was prescribed by the input file.', [K]));
MyWriteLn(Format('III. In total, %d marks were distributed across all circles. Some circles may have received many marks depending on the graph construction.', [TotalCircleMarks]));
MyWriteLn(Format('IV. On average, each circle received %f marks.', [TotalCircleMarks / N]));
MyWriteLn(Format('V. In any one circle, the maxmimum number of marks was %d. All circles received at most this many marks during gameplay.', [MaxSingleCircleMarks]));
{ Close the output file. }
CloseFile(OutputFile);
end.
|
unit JD.Weather;
(*
JD Weather Component
Encapsulates entire JD weather system in a single component
*)
interface
uses
Winapi.Windows,
System.Classes, System.SysUtils,
JD.Weather.Intf;
type
TJDWeatherInfoSettings = class;
TJDWeatherInfoSettingsGroup = class;
TJDWeather = class;
TJDWeatherThread = class;
TJDWeatherInfoSettings = class(TPersistent)
private
FOwner: TJDWeatherInfoSettingsGroup;
FEnabled: Boolean;
FFrequency: Integer;
FCached: Boolean;
procedure SetEnabled(const Value: Boolean);
procedure SetFrequency(const Value: Integer);
procedure SetCached(const Value: Boolean);
public
constructor Create(AOwner: TJDWeatherInfoSettingsGroup);
destructor Destroy; override;
published
property Enabled: Boolean read FEnabled write SetEnabled;
property Cached: Boolean read FCached write SetCached;
property Frequency: Integer read FFrequency write SetFrequency;
end;
TJDWeatherInfoSettingsGroup = class(TPersistent)
private
FOwner: TJDWeather;
FConditions: TJDWeatherInfoSettings;
FAlerts: TJDWeatherInfoSettings;
FForecastSummary: TJDWeatherInfoSettings;
FForecastHourly: TJDWeatherInfoSettings;
FForecastDaily: TJDWeatherInfoSettings;
FMaps: TJDWeatherInfoSettings;
FAlmanac: TJDWeatherInfoSettings;
FAstronomy: TJDWeatherInfoSettings;
FHurricane: TJDWeatherInfoSettings;
FHistory: TJDWeatherInfoSettings;
FPlanner: TJDWeatherInfoSettings;
FStation: TJDWeatherInfoSettings;
procedure SetAlerts(const Value: TJDWeatherInfoSettings);
procedure SetAlmanac(const Value: TJDWeatherInfoSettings);
procedure SetAstronomy(const Value: TJDWeatherInfoSettings);
procedure SetConditions(const Value: TJDWeatherInfoSettings);
procedure SetForecastDaily(const Value: TJDWeatherInfoSettings);
procedure SetForecastHourly(const Value: TJDWeatherInfoSettings);
procedure SetForecastSummary(const Value: TJDWeatherInfoSettings);
procedure SetHistory(const Value: TJDWeatherInfoSettings);
procedure SetHurricane(const Value: TJDWeatherInfoSettings);
procedure SetMaps(const Value: TJDWeatherInfoSettings);
procedure SetPlanner(const Value: TJDWeatherInfoSettings);
procedure SetStation(const Value: TJDWeatherInfoSettings);
public
constructor Create(AOwner: TJDWeather);
destructor Destroy; override;
published
property Conditions: TJDWeatherInfoSettings read FConditions write SetConditions;
property Alerts: TJDWeatherInfoSettings read FAlerts write SetAlerts;
property ForecastSummary: TJDWeatherInfoSettings read FForecastSummary write SetForecastSummary;
property ForecastHourly: TJDWeatherInfoSettings read FForecastHourly write SetForecastHourly;
property ForecastDaily: TJDWeatherInfoSettings read FForecastDaily write SetForecastDaily;
property Maps: TJDWeatherInfoSettings read FMaps write SetMaps;
property Almanac: TJDWeatherInfoSettings read FAlmanac write SetAlmanac;
property Astronomy: TJDWeatherInfoSettings read FAstronomy write SetAstronomy;
property Hurricane: TJDWeatherInfoSettings read FHurricane write SetHurricane;
property History: TJDWeatherInfoSettings read FHistory write SetHistory;
property Planner: TJDWeatherInfoSettings read FPlanner write SetPlanner;
property Station: TJDWeatherInfoSettings read FStation write SetStation;
end;
TJDWeather = class(TComponent)
private
FLib: HMODULE;
FCreateLib: TCreateJDWeather;
FWeather: IJDWeather;
FService: IWeatherService;
FWantedMaps: TWeatherMapTypes;
FThread: TJDWeatherThread;
FOnConditions: TWeatherConditionsEvent;
FOnMaps: TWeatherMapEvent;
FOnAlerts: TWeatherAlertEvent;
FOnForecastDaily: TWeatherForecastEvent;
FOnForecastHourly: TWeatherForecastEvent;
FOnForecastSummary: TWeatherForecastEvent;
FWantedInfo: TWeatherInfoTypes;
FWantedForecasts: TWeatherForecastTypes;
procedure SetWantedMaps(const Value: TWeatherMapTypes);
procedure SetWantedInfo(const Value: TWeatherInfoTypes);
procedure SetWantedForecasts(const Value: TWeatherForecastTypes);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function Active: Boolean;
published
property WantedInfo: TWeatherInfoTypes read FWantedInfo write SetWantedInfo;
property WantedForecasts: TWeatherForecastTypes read FWantedForecasts write SetWantedForecasts;
property WantedMaps: TWeatherMapTypes read FWantedMaps write SetWantedMaps;
property OnConditions: TWeatherConditionsEvent read FOnConditions write FOnConditions;
property OnAlerts: TWeatherAlertEvent read FOnAlerts write FOnAlerts;
property OnForecastSummary: TWeatherForecastEvent read FOnForecastSummary write FOnForecastSummary;
property OnForecastHourly: TWeatherForecastEvent read FOnForecastHourly write FOnForecastHourly;
property OnForecastDaily: TWeatherForecastEvent read FOnForecastDaily write FOnForecastDaily;
property OnMaps: TWeatherMapEvent read FOnMaps write FOnMaps;
end;
TJDWeatherThread = class(TThread)
private
FOwner: TJDWeather;
protected
procedure Execute; override;
public
constructor Create(AOwner: TJDWeather); reintroduce;
destructor Destroy; override;
end;
implementation
{ TJDWeatherInfoSettings }
constructor TJDWeatherInfoSettings.Create(AOwner: TJDWeatherInfoSettingsGroup);
begin
FOwner:= AOwner;
Frequency:= 300; //5 Minutes
end;
destructor TJDWeatherInfoSettings.Destroy;
begin
inherited;
end;
procedure TJDWeatherInfoSettings.SetCached(const Value: Boolean);
begin
FCached := Value;
end;
procedure TJDWeatherInfoSettings.SetEnabled(const Value: Boolean);
begin
FEnabled := Value;
end;
procedure TJDWeatherInfoSettings.SetFrequency(const Value: Integer);
begin
FFrequency := Value;
end;
{ TJDWeatherInfoSettingsGroup }
constructor TJDWeatherInfoSettingsGroup.Create(AOwner: TJDWeather);
begin
FOwner:= AOwner;
FConditions:= TJDWeatherInfoSettings.Create(Self);
FAlerts:= TJDWeatherInfoSettings.Create(Self);
FForecastSummary:= TJDWeatherInfoSettings.Create(Self);
FForecastHourly:= TJDWeatherInfoSettings.Create(Self);
FForecastDaily:= TJDWeatherInfoSettings.Create(Self);
FMaps:= TJDWeatherInfoSettings.Create(Self);
FAlmanac:= TJDWeatherInfoSettings.Create(Self);
FAstronomy:= TJDWeatherInfoSettings.Create(Self);
FHurricane:= TJDWeatherInfoSettings.Create(Self);
FHistory:= TJDWeatherInfoSettings.Create(Self);
FPlanner:= TJDWeatherInfoSettings.Create(Self);
FStation:= TJDWeatherInfoSettings.Create(Self);
end;
destructor TJDWeatherInfoSettingsGroup.Destroy;
begin
FStation.Free;
FPlanner.Free;
FHistory.Free;
FHurricane.Free;
FAstronomy.Free;
FAlmanac.Free;
FMaps.Free;
FForecastDaily.Free;
FForecastHourly.Free;
FForecastSummary.Free;
FAlerts.Free;
FConditions.Free;
inherited;
end;
procedure TJDWeatherInfoSettingsGroup.SetAlerts(
const Value: TJDWeatherInfoSettings);
begin
FAlerts.Assign(Value);
end;
procedure TJDWeatherInfoSettingsGroup.SetAlmanac(
const Value: TJDWeatherInfoSettings);
begin
FAlmanac.Assign(Value);
end;
procedure TJDWeatherInfoSettingsGroup.SetAstronomy(
const Value: TJDWeatherInfoSettings);
begin
FAstronomy.Assign(Value);
end;
procedure TJDWeatherInfoSettingsGroup.SetConditions(
const Value: TJDWeatherInfoSettings);
begin
FConditions.Assign(Value);
end;
procedure TJDWeatherInfoSettingsGroup.SetForecastDaily(
const Value: TJDWeatherInfoSettings);
begin
FForecastDaily.Assign(Value);
end;
procedure TJDWeatherInfoSettingsGroup.SetForecastHourly(
const Value: TJDWeatherInfoSettings);
begin
FForecastHourly.Assign(Value);
end;
procedure TJDWeatherInfoSettingsGroup.SetForecastSummary(
const Value: TJDWeatherInfoSettings);
begin
FForecastSummary.Assign(Value);
end;
procedure TJDWeatherInfoSettingsGroup.SetHistory(
const Value: TJDWeatherInfoSettings);
begin
FHistory.Assign(Value);
end;
procedure TJDWeatherInfoSettingsGroup.SetHurricane(
const Value: TJDWeatherInfoSettings);
begin
FHurricane.Assign(Value);
end;
procedure TJDWeatherInfoSettingsGroup.SetMaps(
const Value: TJDWeatherInfoSettings);
begin
FMaps.Assign(Value);
end;
procedure TJDWeatherInfoSettingsGroup.SetPlanner(
const Value: TJDWeatherInfoSettings);
begin
FPlanner.Assign(Value);
end;
procedure TJDWeatherInfoSettingsGroup.SetStation(
const Value: TJDWeatherInfoSettings);
begin
FStation.Assign(Value);
end;
{ TJDWeather }
constructor TJDWeather.Create(AOwner: TComponent);
var
EC: Integer;
begin
inherited;
FService:= nil;
try
FLib:= LoadLibrary('JDWeather.dll');
if FLib <> 0 then begin
FCreateLib:= GetProcAddress(FLib, 'CreateJDWeather');
if Assigned(FCreateLib) then begin
try
FWeather:= FCreateLib(ExtractFilePath(ParamStr(0)));
FWeather._AddRef;
//TODO: Select default service
if FWeather.Services.Count > 0 then
Self.FService:= FWeather.Services.Items[0];
except
on E: Exception do begin
raise Exception.Create('Failed to create new instance of "IJDWeather": '+E.Message);
end;
end;
end else begin
raise Exception.Create('Function "CreateJDWeather" not found!');
end;
end else begin
EC:= GetLastError;
raise Exception.Create('LoadLibrary failed with error code '+IntToStr(EC));
end;
except
on E: Exception do begin
raise Exception.Create('Failed to load JDWeather library: '+E.Message);
end;
end;
end;
destructor TJDWeather.Destroy;
begin
FWeather._Release;
FWeather:= nil;
inherited;
end;
procedure TJDWeather.SetWantedForecasts(const Value: TWeatherForecastTypes);
begin
FWantedForecasts := Value;
if Assigned(FService) then begin
//FService.WantedForecasts:= Value; //TODO
end;
end;
procedure TJDWeather.SetWantedInfo(const Value: TWeatherInfoTypes);
begin
FWantedInfo := Value;
if Assigned(FService) then begin
//FService.WantedInfo:= Value; //TODO
end;
end;
procedure TJDWeather.SetWantedMaps(const Value: TWeatherMapTypes);
begin
FWantedMaps:= Value;
if Assigned(FService) then begin
//FService.WantedMaps:= Value; //TODO
end;
end;
function TJDWeather.Active: Boolean;
begin
Result:= Assigned(FService);
end;
{ TJDWeatherThread }
constructor TJDWeatherThread.Create(AOwner: TJDWeather);
begin
inherited Create(True);
FOwner:= AOwner;
end;
destructor TJDWeatherThread.Destroy;
begin
inherited;
end;
procedure TJDWeatherThread.Execute;
begin
while not Terminated do begin
end;
end;
end.
|
unit ComponentsExGroupUnit2;
interface
uses
BaseComponentsGroupUnit2, CategoryParametersGroupUnit2,
CategoryParametersQuery2, Data.DB, NotifyEvents, System.Classes,
System.Contnrs, FireDAC.Stan.Option, FireDAC.Stan.Intf,
System.Generics.Collections, ComponentsExQuery, FamilyExQuery,
ProductParametersQuery, CustomComponentsQuery;
type
TComponentsExGroup2 = class(TBaseComponentsGroup2)
procedure OnFDQueryUpdateRecord(ASender: TDataSet;
ARequest: TFDUpdateRequest; var AAction: TFDErrorAction;
AOptions: TFDUpdateRowOptions);
private
FAllParameterFields: TDictionary<Integer, String>;
FApplyUpdateEvents: TObjectList;
FCatParamsGroup: TCategoryParametersGroup2;
FFieldIndex: Integer;
FFreeFields: TList<String>;
FMark: string;
FOnParamOrderChange: TNotifyEventsEx;
FqComponentsEx: TQueryComponentsEx;
FqFamilyEx: TQueryFamilyEx;
FqProductParameters: TQueryProductParameters;
const
FFieldPrefix: string = 'Field';
FFreeFieldCount = 20;
procedure ApplyUpdate(AQueryCustomComponents: TQueryCustomComponents;
AFamily: Boolean);
procedure DoAfterOpen(Sender: TObject);
procedure DoBeforeOpen(Sender: TObject);
procedure DoOnApplyUpdateComponent(Sender: TObject);
procedure DoOnApplyUpdateFamily(Sender: TObject);
function GetNextFieldName: String;
function GetqCategoryParameters: TQueryCategoryParameters2;
function GetqComponentsEx: TQueryComponentsEx;
function GetqFamilyEx: TQueryFamilyEx;
function GetqProductParameters: TQueryProductParameters;
procedure UpdateParameterValue(AComponentID: Integer;
const AParamSubParamID: Integer; const AVaramValue: String);
protected
// TODO: ClearUpdateCount
procedure LoadParameterValues;
property qCategoryParameters: TQueryCategoryParameters2
read GetqCategoryParameters;
property qProductParameters: TQueryProductParameters
read GetqProductParameters;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure AddClient; override;
procedure RemoveClient; override;
function GetIDParameter(const AFieldName: String): Integer;
procedure TryRefresh;
procedure UpdateFields;
property AllParameterFields: TDictionary<Integer, String>
read FAllParameterFields;
property CatParamsGroup: TCategoryParametersGroup2 read FCatParamsGroup;
property Mark: string read FMark;
property qComponentsEx: TQueryComponentsEx read GetqComponentsEx;
property qFamilyEx: TQueryFamilyEx read GetqFamilyEx;
property OnParamOrderChange: TNotifyEventsEx read FOnParamOrderChange;
end;
implementation
uses
System.SysUtils, FireDAC.Comp.Client, DBRecordHolder, DSWrap;
{ TfrmComponentsMasterDetail }
constructor TComponentsExGroup2.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FAllParameterFields := TDictionary<Integer, String>.Create();
FApplyUpdateEvents := TObjectList.Create;
FMark := '!';
FCatParamsGroup := TCategoryParametersGroup2.Create(Self);
// Сначала будем открывать компоненты, чтобы при открытии семейства знать сколько у него компонент
// Компоненты и семейства не связаны как главный-подчинённый главным для них является категория
QList.Add(qComponentsEx);
QList.Add(qFamilyEx);
TNotifyEventWrap.Create(qFamilyEx.W.BeforeOpen, DoBeforeOpen, EventList);
TNotifyEventWrap.Create(qComponentsEx.W.BeforeOpen, DoBeforeOpen, EventList);
TNotifyEventWrap.Create(qFamilyEx.W.AfterOpen, DoAfterOpen, EventList);
FOnParamOrderChange := TNotifyEventsEx.Create(Self);
FFreeFields := TList<String>.Create;
end;
destructor TComponentsExGroup2.Destroy;
begin
FreeAndNil(FOnParamOrderChange);
FreeAndNil(FAllParameterFields);
FreeAndNil(FApplyUpdateEvents);
FreeAndNil(FFreeFields);
inherited;
end;
procedure TComponentsExGroup2.AddClient;
begin
// Сначала обновим компоненты,
// чтобы при обновлении семейств знать сколько компонентов входит в семейство
qComponentsEx.AddClient;
qFamilyEx.AddClient;
end;
procedure TComponentsExGroup2.ApplyUpdate(AQueryCustomComponents
: TQueryCustomComponents; AFamily: Boolean);
var
// AQueryCustomComponents: TQueryCustomComponents;
AField: TField;
AFieldName: String;
AParamSubParamID: Integer;
// ADataSet: TFDQuery;
// ANewValue: String;
// AOldValue: String;
begin
// AQueryCustomComponents := Sender as TQueryCustomComponents;
// ADataSet := AQueryCustomComponents.FDQuery;
Assert(AQueryCustomComponents.RecordHolder <> nil);
// Цикл по всем добавленным полям
CatParamsGroup.qCategoryParameters.FDQuery.First;
while not CatParamsGroup.qCategoryParameters.FDQuery.Eof do
begin
AParamSubParamID := CatParamsGroup.qCategoryParameters.W.ParamSubParamId.
F.AsInteger;
AFieldName := AllParameterFields[AParamSubParamID];
AField := AQueryCustomComponents.W.Field(AFieldName);
// AField.OldValue <> AField.Value почему-то не работает
// AOldValue := VarToStrDef(AQueryCustomComponents.RecordHolder.Field[AFieldName], '');
// ANewValue := VarToStrDef(AField.Value, '');
// Если значение данного параметра изменилось
if AQueryCustomComponents.RecordHolder.Field[AFieldName] <> AField.Value
then
begin
// Обновляем значение параметра на сервере
UpdateParameterValue(AQueryCustomComponents.W.PK.AsInteger,
AParamSubParamID, AField.AsString);
end;
// Переходим к следующему подпараметру
CatParamsGroup.qCategoryParameters.FDQuery.Next;
end;
end;
procedure TComponentsExGroup2.RemoveClient;
begin
qComponentsEx.RemoveClient;
qFamilyEx.RemoveClient;
end;
procedure TComponentsExGroup2.DoAfterOpen(Sender: TObject);
begin
LoadParameterValues;
end;
procedure TComponentsExGroup2.DoBeforeOpen(Sender: TObject);
var
AData: TQueryCustomComponents;
AFDQuery: TFDQuery;
AFieldName: String;
AFieldType: TFieldType;
AParamSubParamID: Integer;
ASize: Integer;
I: Integer;
begin
// Очищаем словарь параметров
FAllParameterFields.Clear;
// Очищаем список "свободных" полей
FFreeFields.Clear;
AData := (Sender as TDSWrap).Obj as TQueryCustomComponents;
AFDQuery := AData.FDQuery;
AFDQuery.Fields.Clear;
AFDQuery.FieldDefs.Clear;
// Обновляем описания полей
AFDQuery.FieldDefs.Update;
FFieldIndex := 0;
AFieldType := ftWideString;
ASize := 200;
// В списке параметров могли произойти изменения (порядок, видимость)
FCatParamsGroup.qCategoryParameters.LoadFromMaster(AData.ParentValue, True);
FCatParamsGroup.qCategoryParameters.FDQuery.First;
while not FCatParamsGroup.qCategoryParameters.FDQuery.Eof do
begin
AParamSubParamID := FCatParamsGroup.qCategoryParameters.W.ParamSubParamId.
F.AsInteger;
// Если для такого параметра в SQL запросе поля не существует
if not AData.ParameterFields.ContainsKey(AParamSubParamID) then
begin
// Получаем поле со случайным именем
AFieldName := GetNextFieldName; // GetFieldName(AParamSubParamId);
// Добавляем очередное поле
AFDQuery.FieldDefs.Add(AFieldName, AFieldType, ASize);
FAllParameterFields.Add(AParamSubParamID, AFieldName);
end
else
FAllParameterFields.Add(AParamSubParamID,
AData.ParameterFields[AParamSubParamID]);
FCatParamsGroup.qCategoryParameters.FDQuery.Next;
end;
// Добавляем некоторое количество свободных полей
for I := 0 to FFreeFieldCount - 1 do
begin
AFieldName := GetNextFieldName;
// Добавляем очередное поле
AFDQuery.FieldDefs.Add(AFieldName, AFieldType, ASize);
FFreeFields.Add(AFieldName);
end;
// Создаём поля
AData.W.CreateDefaultFields(False);
FCatParamsGroup.qCategoryParameters.FDQuery.First;
while not FCatParamsGroup.qCategoryParameters.FDQuery.Eof do
begin
AParamSubParamID := FCatParamsGroup.qCategoryParameters.W.ParamSubParamId.
F.AsInteger;
if not AData.ParameterFields.ContainsKey(AParamSubParamID) then
begin
AFieldName := FAllParameterFields[AParamSubParamID];
AFDQuery.FieldByName(AFieldName).FieldKind := fkInternalCalc;
end;
FCatParamsGroup.qCategoryParameters.FDQuery.Next;
end;
// Помечаем свободные поля как внутренние вычисляемые
for AFieldName in FFreeFields do
begin
AFDQuery.FieldByName(AFieldName).FieldKind := fkInternalCalc;
end;
end;
procedure TComponentsExGroup2.DoOnApplyUpdateComponent(Sender: TObject);
begin
ApplyUpdate(Sender as TQueryCustomComponents, False);
end;
procedure TComponentsExGroup2.DoOnApplyUpdateFamily(Sender: TObject);
begin
ApplyUpdate(Sender as TQueryCustomComponents, True);
end;
function TComponentsExGroup2.GetIDParameter(const AFieldName: String): Integer;
var
S: string;
begin
S := AFieldName.Remove(0, FFieldPrefix.Length);
Result := S.ToInteger();
end;
function TComponentsExGroup2.GetNextFieldName: String;
begin
Inc(FFieldIndex);
Result := Format('%s_%d', [FFieldPrefix, FFieldIndex]);
end;
function TComponentsExGroup2.GetqCategoryParameters: TQueryCategoryParameters2;
begin
Result := CatParamsGroup.qCategoryParameters;
end;
function TComponentsExGroup2.GetqComponentsEx: TQueryComponentsEx;
begin
if FqComponentsEx = nil then
FqComponentsEx := TQueryComponentsEx.Create(Self);
Result := FqComponentsEx;
end;
function TComponentsExGroup2.GetqFamilyEx: TQueryFamilyEx;
begin
if FqFamilyEx = nil then
FqFamilyEx := TQueryFamilyEx.Create(Self);
Result := FqFamilyEx;
end;
function TComponentsExGroup2.GetqProductParameters: TQueryProductParameters;
begin
if FqProductParameters = nil then
FqProductParameters := TQueryProductParameters.Create(Self);
Result := FqProductParameters;
end;
procedure TComponentsExGroup2.LoadParameterValues;
var
AField: TField;
qryComponents: TQueryCustomComponents;
AFieldName: String;
ANewValue: string;
AParamSubParamID: Integer;
AValue: string;
S: string;
begin
// Во время загрузки из БД ничего в БД сохранять не будем
FApplyUpdateEvents.Clear;
qFamilyEx.SaveValuesAfterEdit := False;
qComponentsEx.SaveValuesAfterEdit := False;
// qFamilyEx.AutoTransaction := True;
// qComponentsEx.AutoTransaction := True;
// Загружаем значения параметров из БД принудительно
qProductParameters.SearchByProductCategoryId(qFamilyEx.ParentValue);
qFamilyEx.FDQuery.DisableControls;
qComponentsEx.FDQuery.DisableControls;
try
// Цикл по значениям параметров текущей категории
qProductParameters.FDQuery.First;
while not qProductParameters.FDQuery.Eof do
begin
if qProductParameters.W.ParentProductID.F.IsNull then
qryComponents := qFamilyEx
else
qryComponents := qComponentsEx;
qryComponents.W.LocateByPK(qProductParameters.W.ProductID.F.Value, True);
AParamSubParamID := qProductParameters.W.ParamSubParamId.F.AsInteger;
// Возможно значение подпараметра в БД есть, а сам подпараметр отвязали
// Или для такого параметра в SQL запросе поля СУЩЕСТВУЕТ
if (not(AllParameterFields.ContainsKey(AParamSubParamID))) or
(qryComponents.ParameterFields.ContainsKey(AParamSubParamID)) then
begin
qProductParameters.FDQuery.Next;
Continue;
end;
AFieldName := AllParameterFields[AParamSubParamID];
S := qProductParameters.W.Value.F.AsString.Trim;
if not S.IsEmpty then
begin
AField := qryComponents.FDQuery.FindField(AFieldName);
Assert(AField <> nil);
// Добавляем ограничители, чтобы потом можно было фильтровать
ANewValue := Format('%s%s%s',
[FMark, qProductParameters.W.Value.F.AsString.Trim, FMark]);
AValue := AField.AsString.Trim;
if AValue <> '' then
AValue := AValue + #13#10;
AValue := AValue + ANewValue;
// AField.FieldKind;
qryComponents.W.TryEdit;
AField.AsString := AValue;
qryComponents.W.TryPost;
qryComponents.FDQuery.ChangeCount;
end;
qProductParameters.FDQuery.Next;
end;
finally
qFamilyEx.FDQuery.First;
qComponentsEx.FDQuery.First;
qComponentsEx.FDQuery.EnableControls;
qFamilyEx.FDQuery.EnableControls;
end;
// Подписываемся на событие, чтобы сохранить
TNotifyEventWrap.Create(qFamilyEx.On_ApplyUpdate, DoOnApplyUpdateFamily,
FApplyUpdateEvents);
TNotifyEventWrap.Create(qComponentsEx.On_ApplyUpdate,
DoOnApplyUpdateComponent, FApplyUpdateEvents);
qFamilyEx.SaveValuesAfterEdit := True;
qComponentsEx.SaveValuesAfterEdit := True;
// Завершаем транзакцию
Connection.Commit;
end;
procedure TComponentsExGroup2.OnFDQueryUpdateRecord(ASender: TDataSet;
ARequest: TFDUpdateRequest; var AAction: TFDErrorAction;
AOptions: TFDUpdateRowOptions);
begin
AAction := eaApplied;
end;
procedure TComponentsExGroup2.TryRefresh;
begin
// Обновляем если они не заблокированы
qComponentsEx.TryRefresh;
qFamilyEx.TryRefresh;
end;
procedure TComponentsExGroup2.UpdateFields;
var
AFieldName: string;
AID: Integer;
AParamSubParamID: Integer;
// AProductCategoryID: Integer;
ARecHolder: TRecordHolder;
OK: Boolean;
begin
// Обрабатываем удалённые подпараметры
for ARecHolder in qCategoryParameters.DeletedSubParams do
begin
AParamSubParamID := ARecHolder.Field
[qCategoryParameters.W.ParamSubParamId.FieldName];
// AProductCategoryID := ARecHolder.Field
// [qCategoryParameters.ProductCategoryID.FieldName];
OK := FAllParameterFields.ContainsKey(AParamSubParamID);
Assert(OK);
AFieldName := FAllParameterFields[AParamSubParamID];
FAllParameterFields.Remove(AParamSubParamID);
// Добавляем поля в список свободных
FFreeFields.Add(AFieldName);
// Удаляем данные удалённого параметра
// TqUpdateParameterValuesParamSubParam.DoDelete(AParamSubParamID,
// AProductCategoryID);
end;
// Обрабатываем изменённые подпараметры
for ARecHolder in qCategoryParameters.EditedSubParams do
begin
AParamSubParamID := ARecHolder.Field
[qCategoryParameters.W.ParamSubParamId.FieldName];
AID := ARecHolder.Field[qCategoryParameters.W.PKFieldName];
qCategoryParameters.W.LocateByPK(AID, True);
Assert(AParamSubParamID <> qCategoryParameters.W.ParamSubParamId.F.
AsInteger);
OK := FAllParameterFields.ContainsKey(AParamSubParamID);
Assert(OK);
AFieldName := FAllParameterFields[AParamSubParamID];
FAllParameterFields.Remove(AParamSubParamID);
FAllParameterFields.Add(qCategoryParameters.W.ParamSubParamId.F.AsInteger,
AFieldName);
// Переносим данные с со старого подпараметра на новый
// TqUpdateParameterValuesParamSubParam.DoUpdate
// (qCategoryParameters.ParamSubParamId.AsInteger, AParamSubParamID,
// qCategoryParameters.ProductCategoryID.AsInteger)
end;
// Обрабатываем добавленные подпараметры
for ARecHolder in qCategoryParameters.InsertedSubParams do
begin
Assert(FFreeFields.Count > 0);
AParamSubParamID := ARecHolder.Field
[qCategoryParameters.W.ParamSubParamId.FieldName];
// Такого подпараметра ещё не должно быть
OK := FAllParameterFields.ContainsKey(AParamSubParamID);
Assert(not OK);
// Задействуем первое свободное поле
FAllParameterFields.Add(AParamSubParamID, FFreeFields[0]);
FFreeFields.Delete(0);
end;
end;
procedure TComponentsExGroup2.UpdateParameterValue(AComponentID: Integer;
const AParamSubParamID: Integer; const AVaramValue: String);
var
AValue: string;
k: Integer;
m: TArray<String>;
S: string;
begin
Assert(AComponentID > 0);
Assert(AParamSubParamID > 0);
// Фильтруем значения параметров
qProductParameters.W.ApplyFilter(AComponentID, AParamSubParamID);
qProductParameters.FDQuery.First;
S := AVaramValue;
m := S.Split([#13]);
k := 0;
for S in m do
begin
AValue := S.Trim([FMark.Chars[0], #13, #10]);
if not AValue.IsEmpty then
begin
Inc(k);
if not(qProductParameters.FDQuery.Eof) then
qProductParameters.W.TryEdit
else
begin
qProductParameters.W.TryAppend;
qProductParameters.W.ParamSubParamId.F.AsInteger := AParamSubParamID;
qProductParameters.W.ProductID.F.AsInteger := AComponentID;
end;
qProductParameters.W.Value.F.AsString := AValue;
qProductParameters.W.TryPost;
qProductParameters.FDQuery.Next;
end;
end;
// Удаляем "лишние" значения
while qProductParameters.FDQuery.RecordCount > k do
begin
qProductParameters.FDQuery.Last;
qProductParameters.FDQuery.Delete;
end;
qProductParameters.FDQuery.Filtered := False;
end;
end.
|
unit MediaStorage.RecordStorage.Visual.RecordsViewer;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtendControls, ComCtrls, ExtCtrls, ActnList,
ToolWin, ImgList,Menus,
MediaStorage.RecordStorage, Data.DB, MemDS, Vcl.Grids, Vcl.DBGrids,
MultiSelectDBGrid, SortDBGrid;
const
WM_SET_FILE_EXISTS_STATUS = WM_USER+200;
type
TRecordSourceListItemData = record
Name: string;
//Url : string;
Id : TrsRecordSourceId;
//ReserveConnectionString: string;
//Available : boolean;
end;
TfrmMediaStorageRecordsView = class(TFrame)
ilImages: TImageList;
alActions: TActionList;
acCheckFileExists: TAction;
mmLog: TExtendMemo;
Splitter2: TSplitter;
acProperties: TAction;
acPlay: TAction;
acCopy: TAction;
acCopyFileNameToClipboard: TAction;
pmRecords: TPopupMenu;
N1: TMenuItem;
dlgSave: TSaveDialogEx;
paRecordSources: TPanel;
Label1: TLabel;
lvRecordSources: TSortDBGrid;
Splitter1: TSplitter;
pcData: TPageControlEx;
tsData: TTabSheet;
Panel2: TPanel;
Label2: TLabel;
lvRecords: TSortDBGrid;
ToolBar1: TToolBar;
ToolButton7: TToolButton;
ToolButton3: TToolButton;
ToolButton8: TToolButton;
ToolButton6: TToolButton;
ToolButton5: TToolButton;
tsWelcome: TTabSheet;
acRefresh: TAction;
tsEmpty: TTabSheet;
paWelcome: TPanel;
paLoad: TPanel;
laRefresh: TExtendLabel;
Label3: TLabel;
Label4: TLabel;
edLoadFrom: TExtendDateTimePicker;
edLoadTo: TExtendDateTimePicker;
ToolButton1: TToolButton;
laLoadDataAjust: TExtendLabel;
acDeleteAbsent: TAction;
ToolButton2: TToolButton;
acDelete: TAction;
ToolButton4: TToolButton;
ToolButton9: TToolButton;
ToolBar2: TToolBar;
ToolButton18: TToolButton;
acRecordSourceRefresh: TAction;
acRecordSourceGetStatistics: TAction;
ToolButton10: TToolButton;
taRecordSources: TMemDataSet;
dsRecordSources: TDataSource;
taRecordSourcesID: TStringField;
taRecordSourcesNAME: TStringField;
taRecordSourcesMINDATE: TDateTimeField;
taRecordSourcesMAXDATE: TDateTimeField;
taRecordSourcesRECORD_COUNT: TIntegerField;
taRecordSourcesTOTAL_DURATION: TDateTimeField;
acRecordSourceDelete: TAction;
ToolButton11: TToolButton;
ToolButton12: TToolButton;
dsRecords: TDataSource;
taRecords: TMemDataSet;
taRecordsID: TStringField;
taRecordsNAME: TStringField;
taRecordsBEGIN: TDateTimeField;
taRecordsEND: TDateTimeField;
taRecordsTRANSPORT: TStringField;
taRecordsPATH: TStringField;
taRecordsDATA_TRANSPORT: TVariantField;
taRecordsACCESSIBLE: TSmallintField;
taRecordsOWNER: TStringField;
procedure acDeleteUpdate(Sender: TObject);
procedure lvRecordsDeletion(Sender: TObject; Item: TListItem);
procedure acDumpUpdate(Sender: TObject);
procedure acCheckFileExistsExecute(Sender: TObject);
procedure acPropertiesExecute(Sender: TObject);
procedure acPlayExecute(Sender: TObject);
procedure acCopyExecute(Sender: TObject);
procedure acCopyFileNameToClipboardUpdate(Sender: TObject);
procedure acCopyFileNameToClipboardExecute(Sender: TObject);
procedure acRefreshExecute(Sender: TObject);
procedure laRefreshClick(Sender: TObject);
procedure paWelcomeResize(Sender: TObject);
procedure laLoadDataAjustClick(Sender: TObject);
procedure acDeleteAbsentExecute(Sender: TObject);
procedure acDeleteExecute(Sender: TObject);
procedure acRecordSourceRefreshExecute(Sender: TObject);
procedure acRecordSourceGetStatisticsExecute(Sender: TObject);
procedure lvRecordSourcesChangeRecord(Sender: TObject);
procedure taRecordSourcesTOTAL_DURATIONGetText(Sender: TField;
var Text: string; DisplayText: Boolean);
procedure acRecordSourceDeleteUpdate(Sender: TObject);
procedure acRecordSourceDeleteExecute(Sender: TObject);
procedure taRecordsACCESSIBLEGetText(Sender: TField; var Text: string;
DisplayText: Boolean);
private
FRecordStorage: TRecordStorage;
FRetrieveInfoThread: TThread;
procedure UpdateRecordsForCurrentRecordSource;
procedure UpdateRecordSources;
procedure WmSetFileExistsStatus(var Message: TMessage); message WM_SET_FILE_EXISTS_STATUS;
function GetRecordSource(index: integer): TRecordSourceListItemData;
protected
procedure Log(const aMessage: string);
public
procedure Init(aRecordStorage: TRecordStorage);
function RecordSourceCount: integer;
property RecordSources[index: integer]:TRecordSourceListItemData read GetRecordSource;
function IsSelectedRecordSource: boolean;
function SetSelectedRecordSource(const aSourceName: string):boolean; overload;
function SetSelectedRecordSource(const aCurrentRecordSourceId: TrsRecordSourceId):boolean; overload;
function SelectedRecordSource:TRecordSourceListItemData;
destructor Destroy; override;
constructor Create(aOwner: TComponent); override;
end;
implementation
uses Math, Variants, SyncObjs, VCLUtils,DateUtils, ClipBrd,uBaseClasses, uBaseUtils, ufmProgressWithBar, MediaStream.Framer,MediaStream.FramerFactory,
MediaStorage.Transport,MediaStorage.Transport.Samba,MediaStorage.Transport.FileServer,
MediaStorage.RecordStorage.Visual.RecordPreview,ufmChooseItems;
{$R *.DFM}
type
TRetrieveFileInfoThread = class (TThread)
private
FRecords: TrsRecordObjectInfoArray;
FOwner: TfrmMediaStorageRecordsView;
protected
procedure Execute; override;
constructor Create(aOwner: TfrmMediaStorageRecordsView; const aRecords: TrsRecordObjectInfoArray);
end;
TCopyFileThread = class (TThread)
private
FSourceTransport: IRecordObjectTransport;
FDestStream: TStream;
FProcessedBytes: TThreadVar<int64>;
protected
procedure Execute; override;
public
constructor Create(const aSourceTransport: IRecordObjectTransport; aDestStream: TStream);
destructor Destroy; override;
function ProcessedBytes: int64;
end;
type
TRecordStorageReadDataProgress = class
private
FForm: TfmProgressWithBar;
procedure OnRecordStorageReadProgress(aSender: TRecordStorage; aPosition, aSize: int64; var aContinue: boolean);
public
constructor Create(aOwner: TfrmMediaStorageRecordsView; const aText: string);
destructor Destroy; override;
end;
function GetTransport(const aV: variant): IRecordObjectTransport;
begin
Assert(VarIsType(aV, varUnknown));
if not Supports(aV, IRecordObjectTransport, Result) then
result:=nil;
end;
{ TRecordStorageReadDataProgress }
constructor TRecordStorageReadDataProgress.Create(aOwner: TfrmMediaStorageRecordsView; const aText: string);
begin
FForm:=TfmProgressWithBar.Create(Application);
FForm.Caption:='Чтение данных';
FForm.Text:=aText;
//FForm.SetMarqueeMode;
FForm.Show;
FForm.Repaint;
end;
destructor TRecordStorageReadDataProgress.Destroy;
begin
FreeAndNil(FForm);
inherited;
end;
procedure TRecordStorageReadDataProgress.OnRecordStorageReadProgress(aSender: TRecordStorage; aPosition, aSize: int64; var aContinue: boolean);
begin
if FForm.ModalResult=mrCancel then
begin
aContinue:=false;
exit;
end;
if aSize>1024 then
begin
FForm.SetProgressMode(100,aPosition*100 div aSize);
FForm.Repaint;
if aSize>1024*1024 then
FForm.laStatus.Caption:=Format('Прочитано %d МБ из %d МБ',[aPosition div 1024 div 1024, aSize div 1024 div 1024])
else
FForm.laStatus.Caption:=Format('Прочитано %d КБ из %d КБ',[aPosition div 1024, aSize div 1024]);
Application.ProcessMessages;
end;
end;
{ TRetrieveFileInfoThread }
constructor TRetrieveFileInfoThread.Create(aOwner: TfrmMediaStorageRecordsView;
const aRecords: TrsRecordObjectInfoArray);
begin
inherited Create(false);
FOwner:=aOwner;
FRecords:=aRecords;
end;
procedure TRetrieveFileInfoThread.Execute;
var
i: Integer;
aStatus: integer;
begin
for i := 0 to High(FRecords) do
begin
if Terminated then
break;
try
if FRecords[i].Transport.FileExists then
aStatus:=1
else
aStatus:=0
except
aStatus:=0; //правильно ли?
end;
SendMessage(FOwner.WindowHandle,WM_SET_FILE_EXISTS_STATUS, WParam(PChar(FRecords[i].Id)),aStatus);
end;
end;
{ TCopyFileThread }
constructor TCopyFileThread.Create(
const aSourceTransport: IRecordObjectTransport; aDestStream: TStream);
begin
FSourceTransport:=aSourceTransport;
FDestStream:=aDestStream;
FProcessedBytes:=TThreadVar<int64>.Create;
inherited Create(false);
end;
destructor TCopyFileThread.Destroy;
begin
FreeAndNil(FProcessedBytes);
inherited;
end;
procedure TCopyFileThread.Execute;
const
BufSize = 1024;
var
aSourceStream: TStream;
N: Integer;
Buffer: PByte;
aReader: IRecordObjectReader;
begin
aReader:=FSourceTransport.GetReader;
aSourceStream:=aReader.GetStream;
GetMem(Buffer, BufSize);
try
while true do
begin
N:=aSourceStream.Read(Buffer^, BufSize);
FDestStream.WriteBuffer(Buffer^, N);
FProcessedBytes.Value:=aSourceStream.Position;
if N<BufSize then
break;
end;
finally
FreeMem(Buffer, BufSize);
end;
aReader:=nil;
end;
function TCopyFileThread.ProcessedBytes: int64;
begin
result:=FProcessedBytes.Value;
end;
{ TfmSystemConsole }
constructor TfrmMediaStorageRecordsView.Create(aOwner: TComponent);
begin
inherited;
pcData.ShowTabs:=false;
pcData.ActivePage:=tsEmpty;
edLoadTo.DateTime:=Now;
edLoadFrom.DateTime:=Now-7;
end;
destructor TfrmMediaStorageRecordsView.Destroy;
begin
FreeAndNil(FRetrieveInfoThread);
taRecords.EmptyTable;
taRecordSources.EmptyTable;
inherited;
end;
procedure TfrmMediaStorageRecordsView.Init(aRecordStorage: TRecordStorage);
begin
TWaitCursor.SetUntilIdle;
FRecordStorage:=aRecordStorage;
Caption:=Caption+': '+FRecordStorage.GetConnectionString;
acDelete.Visible:=aRecordStorage.RecordWriteableAccess<>nil;
acDeleteAbsent.Visible:=aRecordStorage.RecordWriteableAccess<>nil;
acRecordSourceDelete.Visible:=aRecordStorage.RecordSourceWriteableAccess<>nil;
UpdateRecordSources;
end;
function TfrmMediaStorageRecordsView.IsSelectedRecordSource: boolean;
begin
result:=lvRecordSources.IsCurrentRecord;
end;
procedure TfrmMediaStorageRecordsView.laLoadDataAjustClick(Sender: TObject);
var
aStart,aEnd:TDateTime;
begin
FRecordStorage.GetRecordSourceDateRanges(SelectedRecordSource.Id,aStart,aEnd);
if aStart=0 then
MsgBox.MessageInfo(Handle,'В хранилище отсутствуют записи для данного источника');
edLoadFrom.DateTime:=aStart;
edLoadTo.DateTime:=aEnd;
end;
procedure TfrmMediaStorageRecordsView.laRefreshClick(Sender: TObject);
begin
UpdateRecordsForCurrentRecordSource;
end;
procedure TfrmMediaStorageRecordsView.lvRecordSourcesChangeRecord(
Sender: TObject);
begin
if not IsSelectedRecordSource then
pcData.ActivePage:=tsEmpty
else
pcData.ActivePage:=tsWelcome;
end;
procedure TfrmMediaStorageRecordsView.paWelcomeResize(Sender: TObject);
begin
paLoad.Left:=(paWelcome.Width-paLoad.Width) div 2;
paLoad.Top:=(paWelcome.Height-paLoad.Height) div 2;
end;
function TfrmMediaStorageRecordsView.RecordSourceCount: integer;
begin
result:=lvRecordSources.DataSource.DataSet.RecordCount;
end;
function TfrmMediaStorageRecordsView.SelectedRecordSource: TRecordSourceListItemData;
begin
if not IsSelectedRecordSource then
raise Exception.Create('Не выбран источник записей');
result:=GetRecordSource(taRecordSources.RecNo-1);
end;
function TfrmMediaStorageRecordsView.SetSelectedRecordSource(const aCurrentRecordSourceId: TrsRecordSourceId): boolean;
var
i: Integer;
begin
result:=false;
for i := 0 to RecordSourceCount-1 do
if RecordSources[i].Id.Equals(aCurrentRecordSourceId) then
begin
taRecordSources.RecNo:=i+1;
result:=true;
break;
end;
end;
function TfrmMediaStorageRecordsView.SetSelectedRecordSource(const aSourceName: string): boolean;
var
i: Integer;
begin
result:=false;
for i := 0 to RecordSourceCount-1 do
if RecordSources[i].Name=aSourceName then
begin
taRecordSources.RecNo:=i+1;
result:=true;
break;
end;
end;
procedure TfrmMediaStorageRecordsView.taRecordsACCESSIBLEGetText(Sender: TField; var Text: string; DisplayText: Boolean);
begin
if Sender.IsNull then
else if Sender.Value=1 then
Text:='Да'
else if Sender.Value=0 then
Text:='Нет'
else if Sender.Value=2 then
Text:='?'
else
Text:='Ошибка';
end;
procedure TfrmMediaStorageRecordsView.taRecordSourcesTOTAL_DURATIONGetText(
Sender: TField; var Text: string; DisplayText: Boolean);
var
aDT: TDateTime;
begin
if (Sender.IsNull) or (Sender.Value=0) then
Text:=''
else begin
aDT:=Sender.Value;
Text:=TimeToStr(Sender.Value);
if aDT>1 then
begin
Text:=Format('%d дн. %s',[Trunc(aDT),Text]);
end;
end;
end;
procedure TfrmMediaStorageRecordsView.acDeleteAbsentExecute(Sender: TObject);
var
aBk: TBookmark;
aTransport: IRecordObjectTransport;
begin
inherited;
TWaitCursor.SetUntilIdle;
taRecords.DisableControls;
try
aBk:=taRecords.Bookmark;
taRecords.First;
while not taRecords.EOF do
begin
aTransport:=GetTransport(taRecordsDATA_TRANSPORT.Value);
if not aTransport.FileExists then
begin
TArgumentValidation.NotNil(FRecordStorage.RecordWriteableAccess).DeleteRecord(taRecordsID.Value);
Log(Format('Файл "%s" не существует. Удален',[aTransport.ConnectionString]));
end;
taRecords.Next;
end;
if taRecords.BookmarkValid(aBk) then
taRecords.Bookmark:=aBk;
finally
taRecords.EnableControls;
end;
UpdateRecordsForCurrentRecordSource;
end;
procedure TfrmMediaStorageRecordsView.acDeleteExecute(Sender: TObject);
begin
TArgumentValidation.NotNil(FRecordStorage.RecordWriteableAccess).DeleteRecord(taRecordsID.Value);
taRecords.Delete;
end;
procedure TfrmMediaStorageRecordsView.acDeleteUpdate(Sender: TObject);
begin
inherited;
TAction(Sender).Enabled:=lvRecords.IsCurrentRecord;
end;
procedure TfrmMediaStorageRecordsView.UpdateRecordsForCurrentRecordSource;
var
aRecords: TrsRecordObjectInfoArray;
i: integer;
aRecordSourceId: TrsRecordSourceId;
aProgress: TRecordStorageReadDataProgress;
begin
FreeAndNil(FRetrieveInfoThread);
aRecords:=nil;
if IsSelectedRecordSource then
begin
TWaitCursor.SetUntilIdle;
taRecords.DisableControls;
try
aProgress:=TRecordStorageReadDataProgress.Create(self,Format('Чтение записей с %s по %s',[DateToStr(edLoadFrom.DateTime),DateToStr(edLoadTo.DateTime)]));
try
taRecords.Open;
taRecords.EmptyTable;
aRecordSourceId:=SelectedRecordSource.Id;
aRecords:=FRecordStorage.GetRecords(
aRecordSourceId,
Trunc(edLoadFrom.DateTime),
Trunc(edLoadTo.DateTime)+1-1/SecsPerDay,
aProgress.OnRecordStorageReadProgress);
aProgress.FForm.Text:=Format('Построение списка (%d записей)',[Length(aRecords)]);
aProgress.FForm.SetProgressMode(Length(aRecords),0);
aProgress.FForm.Repaint;
for i:=0 to High(aRecords) do
begin
taRecords.Append;
taRecordsID.Value:=aRecords[i].Id;
taRecordsNAME.Value:=ExtractFileName(aRecords[i].Transport.ConnectionString);
taRecordsPATH.Value:=ExtractFileDir(aRecords[i].Transport.ConnectionString);
taRecordsOWNER.Value:=aRecords[i].Owner;
if aRecords[i].StartDateTime<>0 then
taRecordsBEGIN.Value:=aRecords[i].StartDateTime;
if aRecords[i].EndDateTime<>0 then
taRecordsEND.Value:=aRecords[i].EndDateTime;
taRecordsTRANSPORT.Value:=aRecords[i].Transport.Name;
taRecordsDATA_TRANSPORT.Value:=aRecords[i].Transport;
taRecordsACCESSIBLE.Value:=2;
taRecords.Post;
aProgress.FForm.SetProgressMode(Length(aRecords),i+1);
//aProgress.FForm.Repaint;
end;
aProgress.FForm.Text:=Format('Сортировка списка (%d записей)',[Length(aRecords)]);
aProgress.FForm.Repaint;
taRecords.SortOnFields(taRecordsBEGIN.FieldName);
taRecords.First;
finally
aProgress.Free;
end;
finally
taRecords.EnableControls;
end;
pcData.ActivePage:=tsData;
end;
FRetrieveInfoThread:=TRetrieveFileInfoThread.Create(self,aRecords);
end;
procedure TfrmMediaStorageRecordsView.UpdateRecordSources;
var
aRSs: TrsRecordSourceInfoArray;
i: integer;
aBk: TBookmark;
begin
aRSs:=nil;
aBk:=taRecordSources.Bookmark;
taRecordSources.DisableControls;
try
taRecordSources.Open;
taRecordSources.EmptyTable;
aRSs:=FRecordStorage.GetAllRecordSources;
for i:=0 to High(aRSs) do
begin
taRecordSources.Append;
taRecordSourcesID.Value:=aRSs[i].Id.Name;
taRecordSourcesNAME.Value:=aRSs[i].Name;
taRecordSources.Post;
end;
taRecordSources.First;
if taRecordSources.BookmarkValid(aBk) then
taRecordSources.Bookmark:=aBk;
finally
taRecordSources.EnableControls;
end;
lvRecordSourcesChangeRecord(nil); //Автоматом не срабатывает, потому что DisableControls
end;
procedure TfrmMediaStorageRecordsView.WmSetFileExistsStatus(var Message: TMessage);
var
aBk: TBookmark;
begin
taRecords.DisableControls;
try
aBk:=taRecords.Bookmark;
if taRecords.Locate(taRecordsID.FieldName,string(PChar(Message.WParam)),[loCaseInsensitive]) then
begin
taRecords.Edit;
try
taRecordsACCESSIBLE.Value:=Message.LParam;
finally
taRecords.Post;
end;
if taRecords.BookmarkValid(aBk) then
taRecords.Bookmark:=aBk;
end;
finally
taRecords.EnableControls;
end;
end;
procedure TfrmMediaStorageRecordsView.lvRecordsDeletion(Sender: TObject;
Item: TListItem);
begin
inherited;
TObject(Item.Data).Free;
Item.Data:=nil;
end;
procedure TfrmMediaStorageRecordsView.acDumpUpdate(Sender: TObject);
begin
inherited;
TAction(Sender).Enabled:=lvRecords.IsCurrentRecord;
end;
procedure TfrmMediaStorageRecordsView.acRecordSourceDeleteExecute(Sender: TObject);
var
aStart,aEnd:TDateTime;
aDialog: TfmChooseItems;
aSourceNames: TArray<variant>;
aSourceIds: TArray<variant>;
aSourceId: TrsRecordSourceId;
i: integer;
begin
if not MsgBox.Confirm(Handle,'Вы уверены, что хотите удалить выбранный источник?') then
exit;
TWaitCursor.SetUntilIdle;
FRecordStorage.GetRecordSourceDateRanges(SelectedRecordSource.Id,aStart,aEnd);
if (aStart<>0) then
begin
if RecordSourceCount>1 then
begin
case MsgBox.ConfirmYesNoCancelFmt(Handle,'Удаляемый источник имеет записи. Вы хотите перенести эти записи на другой источник?',[]) of
ID_YES:
begin
aSourceNames:=taRecordSources.GetAllValues(taRecordSourcesNAME);
aSourceIds:=taRecordSources.GetAllValues(taRecordSourcesID);
aDialog:=TfmChooseItems.Create(Application);
try
aDialog.RadioMode:=true;
aDialog.Init('Выберите новый источник для записей','Удаляемый источник содержит записи. Укажите другой источник, куда они будут перенесены');
for i := 0 to High(aSourceNames) do
begin
if aSourceIds[i]<>SelectedRecordSource.Id.Name then
aDialog.AddItem(aSourceNames[i],false,pointer(i));
end;
if aDialog.ShowModal=mrOk then
begin
i:=aDialog.FindFirstCheckedItem;
Assert(i<>-1);
i:=integer(aDialog.ItemData[i]);
aSourceId.Init(aSourceIds[i]);
TArgumentValidation.NotNil(FRecordStorage.RecordWriteableAccess).MoveRecords(SelectedRecordSource.Id,aSourceId);
end
else begin
exit; //!!!
end;
finally
aDialog.Free;
end;
end;
ID_NO: ;
ID_CANCEL:
exit;
end;
end
else begin
if not MsgBox.Confirm(Handle,'Удаляемый источник имеет записи, которые будут также удалены. Вы уверены, что хотите удалить источник?') then
exit;
end;
end;
TArgumentValidation.NotNil(FRecordStorage.RecordSourceWriteableAccess).DeleteRecordSource(SelectedRecordSource.Id);
acRecordSourceRefresh.Execute;
end;
procedure TfrmMediaStorageRecordsView.acRecordSourceDeleteUpdate(
Sender: TObject);
begin
TAction(Sender).Enabled:=IsSelectedRecordSource;
end;
procedure TfrmMediaStorageRecordsView.acRecordSourceGetStatisticsExecute(Sender: TObject);
var
aMin,aMax: TDateTime;
i,j: integer;
aIds: TArray<variant>;
aId: TrsRecordSourceId;
aRecords: TrsRecordObjectInfoArray;
aDuration: TDateTime;
aBk: TBookmark;
begin
TWaitCursor.SetUntilIdle;
aBk:=taRecordSources.Bookmark;
taRecordSources.DisableControls;
try
taRecordSourcesMINDATE.Visible:=true;
taRecordSourcesMAXDATE.Visible:=true;
taRecordSourcesRECORD_COUNT.Visible:=true;
taRecordSourcesTOTAL_DURATION.Visible:=true;
aIds:=taRecordSources.GetAllValues(taRecordSourcesID);
for i := 0 to High(aIds) do
begin
aId.Init(aIds[i]);
FRecordStorage.GetRecordSourceDateRanges(aId, aMin,aMax);
aRecords:=FRecordStorage.GetRecords(aId);
taRecordSources.Locate(taRecordSourcesID.FieldName,aIds[i],[loCaseInsensitive]);
taRecordSources.Edit;
if aMin=0 then
taRecordSourcesMINDATE.Clear
else
taRecordSourcesMINDATE.Value:=aMin;
if aMax=0 then
taRecordSourcesMAXDATE.Clear
else
taRecordSourcesMAXDATE.Value:=aMax;
taRecordSourcesRECORD_COUNT.Value:=Length(aRecords);
aDuration:=0;
for j := 0 to High(aRecords) do
if (aRecords[j].StartDateTime<>0) and (aRecords[j].EndDateTime<>0) then
aDuration:=aDuration+(aRecords[j].EndDateTime-aRecords[j].StartDateTime);
taRecordSourcesTOTAL_DURATION.Value:=aDuration;
taRecordSources.Post;
end;
if taRecordSources.BookmarkValid(aBk) then
taRecordSources.Bookmark:=aBk;
finally
taRecordSources.EnableControls;
end;
if acRecordSourceGetStatistics.Tag=0 then
begin
if paRecordSources.Width<500 then
paRecordSources.Width:=500;
lvRecordSources.ColumnSizes.FitColumns();
end;
acRecordSourceGetStatistics.Tag:=1;
end;
procedure TfrmMediaStorageRecordsView.Log(const aMessage: string);
begin
mmLog.Lines.Add(aMessage);
SendMessage(mmLog.Handle,EM_LINESCROLL,0,mmLog.Lines.Count-1);
end;
function TfrmMediaStorageRecordsView.GetRecordSource(index: integer): TRecordSourceListItemData;
begin
result.Id.Init(taRecordSources.DirectGetFieldData(index,taRecordSourcesID.FieldName));
result.Name:=taRecordSources.DirectGetFieldData(index,taRecordSourcesNAME.FieldName);
end;
procedure TfrmMediaStorageRecordsView.acCheckFileExistsExecute(Sender: TObject);
var
s: string;
aTransport : IRecordObjectTransport;
aStart,aStop: cardinal;
res : boolean;
i: integer;
begin
inherited;
s:='\\127.0.0.1\C$\FileStorageFiles\Files\IP Video\Files\';
if InputQuery('Имя файла','Введите имя файла, включая имя компьютера',s) then
begin
Application.ProcessMessages;
Log(Format('Выполняется проверка наличия файла "%s"...',[s]));
TWaitCursor.SetUntilIdle;
for i:=0 to 1 do
begin
aStart:=GetTickCount;
try
if i=0 then
aTransport:=TRecordObjectTransport_NetworkPath.Create(s)
else
aTransport:=TRecordObjectTransport_FileServer.Create(s);
res:=aTransport.FileExists;
aStop:=GetTickCount;
Log(Format(' Транспорт %s: Результат=%s, Время=%d мс',[aTransport.Name,fsiBaseUtils.BoolToStr(res),aStop-aStart]));
except
on E:Exception do
Log(Format(' Транспорт %s: Ошибка= "%s", Время=%d мс',[aTransport.Name,E.Message,GetTickCount-aStart]));
end;
Application.ProcessMessages;
end;
end;
end;
procedure TfrmMediaStorageRecordsView.acPropertiesExecute(Sender: TObject);
var
aTransport: IRecordObjectTransport;
aTransportReader : IRecordObjectReader;
aReader:TStreamFramer;
aStream: TStream;
aFPS: string;
begin
aTransport:=GetTransport(taRecordsDATA_TRANSPORT.Value);
aTransportReader:=aTransport.GetReader;
TWaitCursor.SetUntilIdle;
aReader:= GetFramerClassFromFileName(aTransport.ConnectionString).Create;
try
aStream:=aTransportReader.GetStream;
aReader.OpenStream(aStream);
Log(Format('Размер:%d',[aStream.Size]));
if aReader.VideoInfo.State=isOK then
begin
Log(Format('Разрешение:%dx%d',[aReader.VideoInfo.Width,aReader.VideoInfo.Height]));
if aReader.RandomAccess<>nil then
begin
Log(Format('Длина видео, мсек:%d',[aReader.RandomAccess.StreamInfo.Length]));
aFPS:='?';
if aReader.RandomAccess.StreamInfo.Length>0 then
aFPS:=FormatFloat('0.0',aReader.RandomAccess.StreamInfo.VideoFrameCount/(aReader.RandomAccess.StreamInfo.Length/1000));
//Log(Format('Длина аудио, мсек:%d',[aReader.Statistics.AudioTotalLength]));
Log(Format('FPS:%s',[aFPS]));
Log(Format('Кадров: VI:%d',[aReader.RandomAccess.StreamInfo.VideoFrameCount]));
end;
end;
finally
aReader.Free;
end;
aTransportReader:=nil;
end;
procedure TfrmMediaStorageRecordsView.acRefreshExecute(Sender: TObject);
begin
pcData.ActivePage:=tsWelcome;
end;
procedure TfrmMediaStorageRecordsView.acRecordSourceRefreshExecute(Sender: TObject);
begin
UpdateRecordSources;
end;
procedure TfrmMediaStorageRecordsView.acCopyExecute(Sender: TObject);
var
aDestStream : TFileStream;
aCopyThread: TCopyFileThread;
s: AnsiString;
aFileSize,aProcessedBytes: int64;
aProgress: TfmProgressWithBar;
aStartTicks,aDeltaTicks: cardinal;
aTransport: IRecordObjectTransport;
begin
inherited;
aTransport:=GetTransport(taRecordsDATA_TRANSPORT.Value);
dlgSave.DefaultExt:=ExtractFileExt(aTransport.ConnectionString);
dlgSave.FileName:=ExtractFileName(aTransport.ConnectionString);
if dlgSave.Execute then
begin
TWaitCursor.SetUntilIdle;
aDestStream:=TFileStream.Create(dlgSave.FileName,fmCreate);
try
aFileSize:=aTransport.FileSize;
aProcessedBytes:=0;
aProgress:=TfmProgressWithBar.Create(Application);
try
aProgress.CancelButtonEnabled:=false; //TODO
aProgress.SetProgressMode(100,0);
aProgress.Text:='Инициализация чтения...';
aProgress.Show;
aStartTicks:=GetTickCount;
aCopyThread:=TCopyFileThread.Create(aTransport,aDestStream);
while not aCopyThread.Finished do
begin
aProcessedBytes:=aCopyThread.ProcessedBytes;
if aProcessedBytes>0 then //Иначе еще не кончилась инициализация
begin
aProgress.SetProgressMode(aProcessedBytes*100 div aFileSize);
aDeltaTicks:=(GetTickCount-aStartTicks);
aProgress.Text:=Format('Скачано: %.2f МБ из %.2f МБ. Время: %d сек. Скорость: %d КБ/сек',
[
aProcessedBytes/1024/1024,
aFileSize/1024/1024,
aDeltaTicks div 1000,
aProcessedBytes div Max(aDeltaTicks,1)
]);
end;
Application.ProcessMessages;
end;
if aCopyThread.FatalException<>nil then
begin
if aCopyThread.FatalException is Exception then
MsgBox.Error(Handle,aCopyThread.FatalException as Exception)
else
MsgBox.MessageFailure(Handle,'Во время копирования произошла ошибка');
end
else begin
aProgress.Hide;
aDeltaTicks:=(GetTickCount-aStartTicks);
MsgBox.MessageInfo(Handle,
Format('Копирование выполнено. Время: %d сек. Скорость: %d КБ/сек. Размер: %.2f МБ',
[
aDeltaTicks div 1000,
aProcessedBytes div Max(aDeltaTicks,1),
aFileSize/1024/1024]));
end;
finally
aProgress.Free;
end;
finally
aDestStream.Free;
end;
aDestStream:=TFileStream.Create(ChangeFileExt(dlgSave.FileName,'.info'),fmCreate);
try
s:=Format('Id=%s'#13#10+
'ConnectionString=%s'#13#10+
'StartDateTime=%s'#13#10+
'EndDateTime=%s'#13#10,
[taRecordsID.Value,
aTransport.ConnectionString,
DateTimeToStr(taRecordsBEGIN.Value),
DateTimeToStr(taRecordsEND.Value)]);
aDestStream.WriteBuffer(PAnsiChar(s)^,Length(s));
finally
aDestStream.Free;
end;
end;
end;
procedure TfrmMediaStorageRecordsView.acCopyFileNameToClipboardExecute(Sender: TObject);
var
aTransport: IRecordObjectTransport;
begin
aTransport:=GetTransport(taRecordsDATA_TRANSPORT.Value);
Clipboard.Open;
Clipboard.AsText:=aTransport.ConnectionString;
Clipboard.Close;
end;
procedure TfrmMediaStorageRecordsView.acCopyFileNameToClipboardUpdate(Sender: TObject);
begin
inherited;
TAction(Sender).Enabled:=lvRecords.IsCurrentRecord;
end;
procedure TfrmMediaStorageRecordsView.acPlayExecute(Sender: TObject);
var
aRecords: TrsRecordObjectInfoArray;
begin
SetLength(aRecords,1);
aRecords[0].Id:=taRecordsID.Value;
aRecords[0].StartDateTime:=taRecordsBEGIN.Value;
aRecords[0].EndDateTime:=taRecordsEND.Value;
aRecords[0].Transport:=GetTransport(taRecordsDATA_TRANSPORT.Value);
TfmMediaStorageRecordPreview.Run(aRecords);
end;
end.
|
unit uDAO;
interface
uses
System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.FB,
FireDAC.Phys.FBDef, FireDAC.VCLUI.Wait, Data.DB, FireDAC.Comp.Client,
FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt,
FireDAC.Comp.DataSet, FireDAC.Phys.IBBase;
type
TDAO = class(TDataModule)
Conexao: TFDConnection;
qryPessoalAtividades: TFDQuery;
dsPessoalAtividades: TDataSource;
qryPedidos: TFDQuery;
qryItensPedido: TFDQuery;
dsPedidos: TDataSource;
dsItensPedido: TDataSource;
FDPhysFBDriverLink1: TFDPhysFBDriverLink;
private
{ Private declarations }
public
{ Public declarations }
function pesquisarPessoalAtividades(Args:String): Boolean;
function pesquisarPedidos(): Boolean;
end;
var
DAO: TDAO;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
{ TDAO }
function TDAO.pesquisarPedidos: Boolean;
begin
try
if not(Conexao.Connected) then
Conexao.Open();
with qryPedidos do
begin
sql.Clear;
sql.Add('SELECT * FROM PEDIDOS');
Open();
end;
qryItensPedido.Open();
Result := True;
except
on E: exception do
begin
Result := False;
end;
end;
end;
function TDAO.pesquisarPessoalAtividades(Args: String): Boolean;
begin
try
if not(Conexao.Connected) then
Conexao.Open();
with qryPessoalAtividades do
begin
sql.Clear;
sql.Add('SELECT * FROM PESSOAL P INNER JOIN ATIVIDADES A ON A.CODIGO = P.ATIVIDADE WHERE P.NOME LIKE :NOME');
ParamByName('NOME').AsString := '%'+Args+'%';
Open();
end;
Result := True;
except
on E: exception do
begin
Result := False;
end;
end;
end;
end.
|
unit UnitHydrasExplorer;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Grids, DBGrids, ExtCtrls, ComCtrls, DB, DBCtrls, UnitVariables,
Buttons, DBTables ;
type
TFormHydrasExplorer = class(TForm)
DataSourceRegions: TDataSource;
DataSourceStations: TDataSource;
DataSourceCapteurs: TDataSource;
DataSourceRoot: TDataSource;
OpenDialog1: TOpenDialog;
PanelContent: TPanel;
Splitter1: TSplitter;
Splitter2: TSplitter;
PanelStation: TPanel;
LabelRegions: TLabel;
DBGridRoot: TDBGrid;
Panel2: TPanel;
LabelCapteurs: TLabel;
DBGridStations: TDBGrid;
PanelStations: TPanel;
LabelStations: TLabel;
DBGridRegions: TDBGrid;
PanelHaut: TPanel;
SpeedButton1: TSpeedButton;
LabelPath: TLabel;
EditPath: TEdit;
procedure ouvreRegion(Region: String);
procedure DBGridRootCellClick(Column: TColumn);
procedure DBGridStationsCellClick(Column: TColumn);
procedure FormCreate(Sender: TObject);
procedure SpeedButton1Click(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
{ Public declarations }
end;
var
_PATH : string;
localTableRoot : TTable;
localTableRegions : TTable;
localTableStations : TTable;
FormHydrasExplorer: TFormHydrasExplorer;
implementation
uses UnitConfiguration, UnitDataModuleDatas;
{$R *.dfm}
procedure TFormHydrasExplorer.ouvreRegion(Region: String);
begin
DataModuleDatas.ouvreTable(IncludeTrailingPathDelimiter(Region) + _HYDRAS_TABLE_ROOT, localTableRegions);
end;
procedure TFormHydrasExplorer.DBGridRootCellClick(Column: TColumn);
begin
If DBGridRoot.DataSource = DataSourceRoot
Then Begin
DataSourceRegions.DataSet := nil;
DBGridRegions.DataSource := nil;
If localTableRoot.FieldByName('GB_MDATEI').IsNull then exit;
If DataModuleDatas.ouvreTable(_PATH + localTableRoot.FieldValues['GB_MDATEI'] + '.DB', localTableRegions)
Then Begin
DataSourceRegions.DataSet := localTableRegions;
DBGridRegions.DataSource := DataSourceRegions;
End;
End;
end;
procedure TFormHydrasExplorer.DBGridStationsCellClick(Column: TColumn);
var
temp: string;
begin
if Not localTableRegions.Fields[0].IsNull
Then Begin
DataSourceStations.DataSet := nil;
DBGridStations.DataSource := nil;
If localTableRegions.FieldByName('GBM_MSNR').IsNull then exit;
temp := localTableRegions.FieldValues['GBM_MSNR'];
insert('.', temp, 9);
If DataModuleDatas.ouvreTable(IncludeTrailingPathDelimiter(_PATH + temp) + _HYDRAS_TABLE_SENSOR, localTableStations)
Then Begin
DataSourceStations.DataSet := localTableStations;
DBGridStations.DataSource := DataSourceStations;
End;
End;
end;
procedure TFormHydrasExplorer.FormCreate(Sender: TObject);
begin
localTableRoot := TTable.Create(nil);
localTableStations := TTable.Create(nil);
localTableRegions := TTable.Create(nil);
end;
procedure TFormHydrasExplorer.SpeedButton1Click(Sender: TObject);
Begin
With OpenDialog1
Do Begin
DefaultExt := 'DB';
Filename := _HYDRAS_TABLE_ROOT;
Filter := _HYDRAS_TABLE_ROOT;
Options := [ofReadOnly, OfPathMustExist, ofFileMustExist];
If Execute
Then Begin
EditPath.Text := ExtractFileName(ExcludeTrailingPathDelimiter(ExtractFilePath(Filename)));
_PATH := IncludeTrailingPathDelimiter(ExtractFilePath(Filename));
DataModuleDatas.ouvreTable(Filename, localTableRoot);
DataSourceRoot.DataSet := localTableRoot;
DBGridRoot.DataSource := DataSourceRoot;
End;
End;
End;
procedure TFormHydrasExplorer.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
localTableRoot.Free;
localTableRegions.Free;
localTableStations.Free;
end;
end.
|
{
@html(<b>)
Memory Manager
@html(</b>)
- Copyright (c) Danijel Tkalcec
@html(<br><br>)
To enable the use of the RTC Memory manager in your project,
you have to put the rtcMemory unit as first unit in your Project's USES clause.
In addition to that, you have to DEFINE the "RtcMemManager" compiler directive.
@html(<br><br>)
If this compiler directive is not declared, the standard Delphi Memory manager
will be used, even if you use the rtcMemory unit in your project file.
}
unit rtcMemory;
{$INCLUDE rtcDefs.inc}
{$IFNDEF FPC}
{$O-}
{$ENDIF}
interface
{$IFDEF RtcMemManager}
uses
memLocalHeap, // LocalHeapManager
memManager, // Mem_Manager
rtcSyncObjs;
const
// Default settings for heap management (do not modify!)
LargeHeap_Info:THeapInfo = (minsize:2048; blocksize:256; alloc:4; pool:128;
free:true; freeany:true; organize:true; sysmem:true);
{$ENDIF}
const
// Automatically initialize the memory manager?
AutoInit_Mem:boolean=True;
{ If @true, Mem_Manager will be used for larger blocks and LocalHeapManager for smaller blocks.
If @false, Mem_Manager will NOT BE USED. }
UseMemManager:boolean=True;
// Size of min. block which will be stored using our Heap Manager
MinBlockStored:integer = 512;
// @exclude
function MemGetBufferSize(Heap:byte):longint;
// @exclude
function MemGetTotalFree(Heap:byte):longint;
// @exclude
function MemGetTotalSize(Heap:byte):longint;
// @exclude
function MemGetUnusedSize(Heap:byte):longint;
// @exclude
function MemGetFragmentCount(Heap:byte):longint;
{ Get Complete Heap Status }
function Get_HeapStatus:THeapStatus;
{ Check the ammount of memoy in use (bytes) }
function Get_MemoryInUse:longint;
{ Check how much Address Space is used by the Application (KB) }
function Get_AddressSpaceUsed: Cardinal;
{ Initialize the Memory manager.
This will be called automatically in unit initialization,
if @Link(AutoInit_Mem) is set to @true (default setting). }
procedure Init_Mem;
implementation
uses SysUtils, Windows;
function Get_AddressSpaceUsed: Cardinal;
var
LMemoryStatus: TMemoryStatus;
begin
{Set the structure size}
LMemoryStatus.dwLength := SizeOf(LMemoryStatus);
{Get the memory status}
GlobalMemoryStatus(LMemoryStatus);
{The result is the total address space less the free address space}
Result := (LMemoryStatus.dwTotalVirtual - LMemoryStatus.dwAvailVirtual) shr 10;
end;
{$IFDEF RtcMemManager}
var
DMA:TMemoryManager;
RealHeap:TLocalHeapManager;
LargeHeap:TMem_Manager;
MM_CS:TRtcCritSec;
Inside_Mem:integer;
MemReady:boolean=False;
SysMemReady:boolean=False;
{ Global Memory Manager }
function MemGetBufferSize(Heap:byte):longint;
begin
MM_CS.Enter;
try
if not MemReady then
Result:=0
else
Result:=LargeHeap.GetBufferSize(Heap);
finally
MM_CS.Leave;
end;
end;
function MemGetTotalFree(Heap:byte):longint;
begin
MM_CS.Enter;
try
if not MemReady then
Result:=0
else
Result:=LargeHeap.GetTotalFree(Heap);
finally
MM_CS.Leave;
end;
end;
function MemGetTotalSize(Heap:byte):longint;
begin
MM_CS.Enter;
try
if not MemReady then
Result:=0
else
Result:=LargeHeap.GetTotalSize(Heap);
finally
MM_CS.Leave;
end;
end;
function MemGetUnusedSize(Heap:byte):longint;
begin
MM_CS.Enter;
try
if not MemReady then
Result:=0
else
Result:=LargeHeap.GetUnusedSize(Heap);
finally
MM_CS.Leave;
end;
end;
function MemGetFragmentCount(Heap:byte):longint;
begin
MM_CS.Enter;
try
if not MemReady then
Result:=0
else
Result:=LargeHeap.GetFragmentCount(Heap);
finally
MM_CS.Leave;
end;
end;
function Free_Mem(p:pointer):longint;
begin
MM_CS.Enter;
try
Inc(Inside_Mem);
if Inside_Mem=1 then
begin
if LargeHeap.Free_Mem(p) then
Result:=0
else
Result:=RealHeap.Free_Mem(p);
end
else
Result:=RealHeap.Free_Mem(p);
finally
Dec(Inside_Mem);
MM_CS.Leave;
end;
end;
function Get_Mem(size:longint):pointer;
begin
MM_CS.Enter;
try
Inc(Inside_Mem);
if (size<=MinBlockStored) or // small block, prefer Delphi Memory manager
(Inside_Mem>1) then // or ... called from inside our Mem. Manager, need Delphi manager
begin
Result:=RealHeap.Get_Mem(size);
if Result=nil then
OutOfMemoryError;
{if (Result=nil) and (Inside_Mem=1) then
Result:=LargeHeap.Get_Mem(size);}
end
else
begin
Result:=LargeHeap.Get_Mem(size);
if Result=nil then
OutOfMemoryError;
{Result:=RealHeap.Get_Mem(size);}
end;
finally
Dec(Inside_Mem);
MM_CS.Leave;
end;
end;
function Realloc_Mem(P: Pointer; Size: Integer): Pointer;
var
OldSize:integer;
lh:boolean;
begin
if Size=0 then
begin
if p<>nil then Free_Mem(p);
Result:=nil;
end
else if p=nil then
begin
Result:=Get_Mem(size);
end
else
begin
Result:=nil;
MM_CS.Enter;
try
Inc(Inside_Mem);
if Inside_Mem=1 then
begin
OldSize:=LargeHeap.Check_Mem(p);
if OldSize=0 then
begin
OldSize:=RealHeap.Check_Mem(p);
lh:=False;
end
else
lh:=True;
end
else
begin
OldSize:=RealHeap.Check_Mem(p);
lh:=False;
end;
if (size>OldSize) or // growing
(size<OldSize-16) then // shrinking for at least 16 bytes
begin
if not lh then
Result:=RealHeap.Realloc_Mem(p,size);
end
else // not changing size
Result:=p;
if Result=nil then
begin
// Allocate New Block
Dec(Inside_Mem);
try
Result:=Get_Mem(size);
finally
Inc(Inside_Mem);
end;
if Result<>nil then
begin
// Copy old Block to new location
if size<OldSize then Move(p^,Result^,size)
else Move(p^,Result^,OldSize);
// Free old Block
if lh then
LargeHeap.Free_Mem(p)
else
RealHeap.Free_Mem(p);
end
else
begin
if size<OldSize then
Result:=p // return old memory block, without resizing
else
begin
// free old memory block, return NIL
if lh then
LargeHeap.Free_Mem(p)
else
RealHeap.Free_Mem(p);
end;
end;
end;
finally
Dec(Inside_Mem);
MM_CS.Leave;
end;
end;
if Result=nil then
OutOfMemoryError;
end;
const
NewMemMgr: TMemoryManager = (
GetMem: Get_Mem;
FreeMem: Free_Mem;
ReallocMem: Realloc_Mem);
function Free_Mem2(p:pointer):longint;
begin
Result:=RealHeap.Free_Mem(p);
end;
function Get_Mem2(size:longint):pointer;
begin
Result:=RealHeap.Get_Mem(size);
end;
function Realloc_Mem2(P: Pointer; Size: Integer): Pointer;
begin
Result:=RealHeap.Realloc_Mem(p,Size);
end;
const
SysMemMgr: TMemoryManager = (
GetMem: Get_Mem2;
FreeMem: Free_Mem2;
ReallocMem: Realloc_Mem2);
function Get_HeapStatus:THeapStatus;
begin
MM_CS.Enter;
try
if SysMemReady then
begin
Result:=RealHeap.Get_HeapStatus;
if MemReady then
begin
Inc(Result.TotalAddrSpace, LargeHeap.Total_AddrSpace);
Inc(Result.TotalAllocated, LargeHeap.Total_Alloc);
Inc(Result.TotalFree, MemGetTotalFree(0));
end;
end
else
Result:=GetHeapStatus;
finally
MM_CS.Leave;
end;
end;
function Get_MemoryInUse:longint;
begin
MM_CS.Enter;
try
if SysMemReady then
begin
Result:=RealHeap.Total_Alloc;
if MemReady then
Inc(Result, LargeHeap.Total_Alloc);
end
else
Result:=GetHeapStatus.TotalAllocated;
finally
MM_CS.Leave;
end;
end;
procedure Init_Mem;
begin
MM_CS.Enter;
try
if UseMemManager then
begin
if not MemReady then
begin
RealHeap:=TLocalHeapManager.Create;
Inside_Mem:=0;
LargeHeap:=TMem_Manager.Create(True);
LargeHeap.HeapInfo:=LargeHeap_Info;
GetMemoryManager(DMA);
SetMemoryManager(NewMemMgr);
SysMemReady:=True;
MemReady:=True;
end;
end
else
begin
if not SysMemReady then
begin
RealHeap:=TLocalHeapManager.Create;
GetMemoryManager(DMA);
SetMemoryManager(SysMemMgr);
SysMemReady:=True;
end;
end;
finally
MM_CS.Leave;
end;
end;
initialization
MM_CS:=TRtcCritSec.Create;
if AutoInit_Mem then Init_Mem;
{$ELSE}
function MemGetBufferSize(Heap:byte):longint;
begin
Result:=0;
end;
function MemGetTotalFree(Heap:byte):longint;
begin
Result:=0;
end;
function MemGetTotalSize(Heap:byte):longint;
begin
Result:=0;
end;
function MemGetUnusedSize(Heap:byte):longint;
begin
Result:=0;
end;
function MemGetFragmentCount(Heap:byte):longint;
begin
Result:=0;
end;
function Get_HeapStatus:THeapStatus;
begin
{$IFDEF FPC}
GetHeapStatus(Result);
{$ELSE}
Result:=GetHeapStatus;
{$ENDIF}
end;
function Get_MemoryInUse:longint;
begin
{$IFDEF FPC}
Result:=Get_HeapStatus.CurrHeapUsed;
{$ELSE}
Result:=GetHeapStatus.TotalAllocated;
{$ENDIF}
end;
procedure Init_Mem;
begin
end;
{$ENDIF}
end.
|
//Ejercicio 14
//Matemáticamente,
//ln(a^b) = b * ln(a)
//e^ln(x) = x
//Use estas propiedades, el operador de multiplicación ( * ) y las funciones estándar
//de Pascal ln y exp para escribir una expresión en Pascal que produzca el valor de a^b.
program ejercicio14;
var b : integer;
a, pot : real;
begin
writeln('Ingrese valor de a y b separados por un espacio');
readln(a,b);
pot := exp(b*ln(a));
writeln('ele valor de a^b es: ',pot:5:2)
end.
|
{*******************************************************}
{ }
{ Delphi LiveBindings Framework }
{ Copyright(c) 2012-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Data.Bind.DBXScope;
interface
uses
System.Classes, System.SysUtils, System.TypInfo, Data.DB, Data.Bind.Components,
System.Bindings.Helper, System.Generics.Collections, System.Bindings.CustomScope,
System.Bindings.CustomWrapper, System.Bindings.Factories, System.Bindings.EvalProtocol,
Data.Bind.DBScope, Data.Bind.ObjectScope, Data.SQLExpr, Datasnap.DBClient,
Datasnap.Provider;
type
TCustomParamsAdapter = class(TBaseRemoteAdapter)
private
FCustomSQLDataSet: TCustomSQLDataSet;
FDeferActivate: Boolean;
FBeforeExecute: TAdapterNotifyEvent;
FAfterExecute: TAdapterNotifyEvent;
procedure SetCustomSQLDataSet(const Value: TCustomSQLDataSet);
procedure SetSQLDataSet(const Value: TSQLDataSet);
function GetSQLDataSet: TSQLDataSet;
procedure SetSQLQuery(const Value: TSQLQuery);
function GetSQLQuery: TSQLQuery;
procedure MakeParamField<T>(AParam: TParam);
procedure AddFields;
function GetParams: TParams; virtual;
function GetSQLServerMethod: TSQLServerMethod;
function GetSQLStoredProc: TSQLStoredProc;
procedure SetSQLServerMethod(const Value: TSQLServerMethod);
procedure SetSQLStoredProc(const Value: TSQLStoredProc);
protected
procedure SetActive(AValue: Boolean); override;
procedure Loaded; override;
function GetCanModify: Boolean; override;
procedure OnActiveChanged(Sender: TObject);
procedure DoBeforeOpen; override;
procedure DoAfterOpen; override;
procedure DoAfterClose; override;
function GetCanActivate: Boolean; override;
function GetCount: Integer; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure DoAfterExecute; virtual;
procedure DoExecute; virtual;
procedure DoBeforeExecute; virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Execute; virtual;
property SQLDataSet: TSQLDataSet read GetSQLDataSet write SetSQLDataSet;
property SQLQuery: TSQLQuery read GetSQLQuery write SetSQLQuery;
property SQLServerMethod: TSQLServerMethod read GetSQLServerMethod write SetSQLServerMethod;
property SQLStoredProc: TSQLStoredProc read GetSQLStoredProc write SetSQLStoredProc;
property BeforeExecute: TAdapterNotifyEvent read FBeforeExecute write FBeforeExecute;
property AfterExecute: TAdapterNotifyEvent read FAfterExecute write FAfterExecute;
end;
TParamsAdapter = class(TCustomParamsAdapter)
published
property SQLQuery;
property SQLDataSet;
property SQLStoredProc;
property SQLServerMethod;
property Active;
property AutoPost;
property BeforeExecute;
property AfterExecute;
end;
TCustomBindSourceDBX = class;
TSubDataSetProvider = class(TDataSetProvider)
private
procedure SetDataSet(ADataSet: TDataSet);
public
destructor Destroy; override;
private
function GetDataSet: TDataSet;
public
published
[Stored(False)]
property DataSet: TDataSet read GetDataSet stored False;
end;
// publish all properties
TSubSQLDataSet = class(TSQLDataSet)
private
procedure SetSQLConnection(AConnection: TSQLConnection);
function GetSQLConnection: TSQLConnection;
public
destructor Destroy; override;
published
property SQLConnection: TSQLConnection read GetSQLConnection;
end;
// publish all properties
TSubClientDataSet = class(TClientDataSet)
private
FReconcileError: string;
procedure SetProviderName(const AName: string);
function GetBindScope: TCustomBindSourceDBX;
function GetProviderName: string;
procedure DefaultOnReconcileError(DataSet: TCustomClientDataSet;
E: EReconcileError; UpdateKind: TUpdateKind;
var Action: TReconcileAction);
procedure AutoApplyUpdates;
protected
procedure DoAfterPost; override;
procedure DoAfterDelete; override;
published
[Stored(False)]
property ProviderName: string read GetProviderName stored False;
end;
TCustomBindSourceDBX = class(TCustomBindSourceDB, ISubDataSet)
private
FClientDataSet: TSubClientDataSet;
FProvider: TSubDataSetProvider;
FSQLDataSet: TSubSQLDataSet;
FAutoApply: Boolean;
procedure AllocSQLDataSet;
procedure AllocClientDataSet;
procedure AllocProvider;
procedure SetActive(const Value: Boolean);
function GetCommandText: string;
function GetCommandType: TSQLCommandType;
function GetDbxCommandType: string;
function GetMaxBlobSize: Integer;
function GetParamCheck: Boolean;
function GetParams: TParams;
function GetSortFieldNames: string;
function GetSqlConnection: TSQLConnection;
procedure SetCommandText(const Value: string);
procedure SetCommandType(const Value: TSQLCommandType);
procedure SetDbxCommandType(const Value: string);
procedure SetMaxBlobSize(const Value: Integer);
procedure SetParamCheck(const Value: Boolean);
procedure SetParams(const Value: TParams);
procedure SetSortFieldNames(const Value: string);
procedure SetSqlConnection(const Value: TSQLConnection);
function GetSubDataSource: TSubDataSource;
function GetMasterFields: string;
function GetMasterSource: TCustomBindSourceDBX;
procedure SetMasterDataSource(const Value: TCustomBindSourceDBX);
procedure SetMasterFields(const Value: string);
function GetIndexFieldNames: string;
procedure SetIndexFieldNames(const Value: string);
procedure Reactivate;
function GetSchemaName: string;
procedure SetSchemaName(const Value: string);
protected
function GetActive: Boolean; override;
procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override;
{ ISubDataSet }
function GetSubDataSet: TDataSet;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property SubSQLDataSet: TSubSQLDataSet read FSQLDataSet;
property SubDataSource: TSubDataSource read GetSubDataSource;
property SubClientDataSet: TSubClientDataSet read FClientDataSet;
property SubProvider: TSubDataSetProvider read FProvider;
property Active: Boolean read GetActive write SetActive;
property CommandText: string read GetCommandText write SetCommandText;
property CommandType: TSQLCommandType read GetCommandType write SetCommandType;
property DbxCommandType: string read GetDbxCommandType write SetDbxCommandType;
property MaxBlobSize: Integer read GetMaxBlobSize write SetMaxBlobSize;
property ParamCheck: Boolean read GetParamCheck write SetParamCheck;
property Params: TParams read GetParams write SetParams;
property SortFieldNames: string read GetSortFieldNames write SetSortFieldNames;
property SQLConnection: TSQLConnection read GetSqlConnection write SetSqlConnection;
[Default(True)]
property AutoApply: Boolean read FAutoApply write FAutoApply default True;
property MasterSource: TCustomBindSourceDBX read GetMasterSource write SetMasterDataSource;
property MasterFields: string read GetMasterFields write SetMasterFields;
property IndexFieldNames: string read GetIndexFieldNames write SetIndexFieldNames;
property SchemaName: string read GetSchemaName write SetSchemaName;
end;
TBindSourceDBX = class(TCustomBindSourceDBX)
published
property SubSQLDataSet;
property SubDataSource;
property SubClientDataSet;
property SubProvider;
[Stored(False)]
property Active stored False;
[Stored(False)]
property CommandText stored False;
[Stored(False)]
property CommandType stored False;
[Stored(False)]
property DbxCommandType stored False;
[Stored(False)]
property MaxBlobSize stored False;
[Stored(False)]
property ParamCheck stored False;
[Stored(False)]
property Params stored False;
[Stored(False)]
property SortFieldNames stored False;
property SQLConnection;
property AutoApply;
property ApplyMaxErrors;
property ScopeMappings;
property MasterFields;
property MasterSource;
property IndexFieldNames;
property SchemaName;
end;
implementation
uses
System.Rtti;
type
// Utilities to create adapter fields
TFieldUtils = class
public
class function CreateField<T>(AAdapter: TBindSourceAdapter;
const AName: string; AType: TScopeMemberType;
AValueReader: TValueReader<T>): TBindSourceAdapterField; overload; static;
class function CreateField<T>(AAdapter: TBindSourceAdapter;
const AName: string; AType: TScopeMemberType;
AValueReader: TValueReader<T>;
AValueWriter: TValueWriter<T>): TBindSourceAdapterField; overload; static;
end;
{ TFieldUtils }
class function TFieldUtils.CreateField<T>(AAdapter: TBindSourceAdapter;
const AName: string; AType: TScopeMemberType;
AValueReader: TValueReader<T>): TBindSourceAdapterField;
var
LGetMemberObject: IGetMemberObject;
LTypeInfo: PTypeInfo;
begin
LGetMemberObject := TBindSourceAdapterGetMemberObject.Create(AAdapter);
LTypeInfo := System.TypeInfo(T);
Result := TBindSourceAdapterReadField<T>.Create(AAdapter, AName,
TBindSourceAdapterFieldType.Create(LTypeInfo.NameFld.ToString,
LTypeInfo.Kind),
LGetMemberObject,
AValueReader, AType);
end;
class function TFieldUtils.CreateField<T>(AAdapter: TBindSourceAdapter;
const AName: string; AType: TScopeMemberType;
AValueReader: TValueReader<T>;
AValueWriter: TValueWriter<T>): TBindSourceAdapterField;
var
LGetMemberObject: IGetMemberObject;
LTypeInfo: PTypeInfo;
begin
LGetMemberObject := TBindSourceAdapterGetMemberObject.Create(AAdapter);
LTypeInfo := System.TypeInfo(T);
Result := TBindSourceAdapterReadWriteField<T>.Create(AAdapter, AName,
TBindSourceAdapterFieldType.Create(LTypeInfo.NameFld.ToString,
LTypeInfo.Kind),
LGetMemberObject,
AValueReader, AValueWriter, AType);
end;
{ TCustomBindSourceDBX }
constructor TCustomBindSourceDBX.Create(AOwner: TComponent);
begin
inherited;
FAutoApply := True;
AllocSQLDataSet;
AllocProvider;
FProvider.SetDataSet(FSQLDataSet);
AllocClientDataSet;
FClientDataSet.SetProviderName(FProvider.Name);
end;
destructor TCustomBindSourceDBX.Destroy;
begin
inherited;
end;
function TCustomBindSourceDBX.GetActive: Boolean;
begin
Result := FClientDataSet.Active
end;
procedure TCustomBindSourceDBX.GetChildren(Proc: TGetChildProc;
Root: TComponent);
begin
SubClientDataSet.GetChildren(Proc, Root);
end;
function TCustomBindSourceDBX.GetCommandText: string;
begin
Result := FSQLDataSet.CommandText;
end;
function TCustomBindSourceDBX.GetCommandType: TSQLCommandType;
begin
Result := FSQLDataSet.CommandType;
end;
function TCustomBindSourceDBX.GetDbxCommandType: string;
begin
Result := FSQLDataSet.DbxCommandType;
end;
function TCustomBindSourceDBX.GetIndexFieldNames: string;
begin
Result := FClientDataSet.IndexFieldNames;
end;
function TCustomBindSourceDBX.GetSubDataSet: TDataSet;
begin
Result := SubClientDataSet;
end;
function TCustomBindSourceDBX.GetSubDataSource: TSubDataSource;
begin
Result := Self.DataSource as TSubDataSource;
end;
function TCustomBindSourceDBX.GetMasterFields: string;
begin
Result := FClientDataSet.MasterFields;
end;
function TCustomBindSourceDBX.GetMasterSource: TCustomBindSourceDBX;
var
LDataSource: TDataSource;
begin
Result := nil;
LDataSource := FClientDataSet.MasterSource;
if LDataSource <> nil then
if LDataSource.Owner is TCustomBindSourceDBX then
begin
Result := TCustomBindSourceDBX(LDataSource.Owner);
end;
end;
function TCustomBindSourceDBX.GetMaxBlobSize: Integer;
begin
Result := FSQLDataSet.MaxBlobSize;
end;
function TCustomBindSourceDBX.GetParamCheck: Boolean;
begin
Result := FSQLDataSet.ParamCheck;
end;
function TCustomBindSourceDBX.GetParams: TParams;
begin
Result := FSQLDataSet.Params;
end;
function TCustomBindSourceDBX.GetSchemaName: string;
begin
Result := FSQLDataSet.SchemaName;
end;
function TCustomBindSourceDBX.GetSortFieldNames: string;
begin
Result := FSQLDataSet.SortFieldNames;
end;
function TCustomBindSourceDBX.GetSqlConnection: TSQLConnection;
begin
Result := FSQLDataSet.SQLConnection;
end;
procedure TCustomBindSourceDBX.SetActive(const Value: Boolean);
begin
FClientDataSet.Active := Value;
end;
procedure TCustomBindSourceDBX.Reactivate;
begin
if Active then
begin
Active := False;
Active := True;
end;
end;
procedure TCustomBindSourceDBX.SetCommandText(const Value: string);
begin
if FSQLDataSet.CommandText <> Value then
begin
FSQLDataSet.CommandText := Value;
Reactivate;
end;
end;
procedure TCustomBindSourceDBX.SetCommandType(
const Value: TSQLCommandType);
begin
if FSQLDataSet.CommandType <> Value then
begin
FSQLDataSet.CommandType := Value;
Active := False;
end;
end;
procedure TCustomBindSourceDBX.SetDbxCommandType(const Value: string);
begin
if FSQLDataSet.DbxCommandType <> Value then
begin
FSQLDataSet.DbxCommandType := Value;
Active := False;
end;
end;
procedure TCustomBindSourceDBX.SetIndexFieldNames(const Value: string);
begin
FClientDataSet.IndexFieldNames := Value;
end;
procedure TCustomBindSourceDBX.SetMasterDataSource(
const Value: TCustomBindSourceDBX);
begin
if Value = nil then
FClientDataSet.MasterSource := nil
else
FClientDataSet.MasterSource := Value.SubDataSource;
end;
procedure TCustomBindSourceDBX.SetMasterFields(const Value: string);
begin
FClientDataSet.MasterFields := Value;
end;
procedure TCustomBindSourceDBX.SetMaxBlobSize(const Value: Integer);
begin
FSQLDataSet.MaxBlobSize := Value;
end;
procedure TCustomBindSourceDBX.SetParamCheck(const Value: Boolean);
begin
FSQLDataSet.ParamCheck := Value;
end;
procedure TCustomBindSourceDBX.SetParams(const Value: TParams);
begin
FSQLDataSet.Params := Value;
end;
procedure TCustomBindSourceDBX.SetSchemaName(const Value: string);
begin
if FSQLDataSet.SchemaName <> Value then
begin
FSQLDataSet.SchemaName := Value;
Active := False;
end;
end;
procedure TCustomBindSourceDBX.SetSortFieldNames(const Value: string);
begin
if FSQLDataSet.SortFieldNames <> Value then
begin
FSQLDataSet.SortFieldNames := Value;
Reactivate;
end;
end;
procedure TCustomBindSourceDBX.SetSqlConnection(
const Value: TSQLConnection);
begin
FSQLDataSet.SetSQLConnection(Value);
end;
procedure TCustomBindSourceDBX.AllocSQLDataSet;
begin
FSQLDataSet := TSubSQLDataSet.Create(Self);
FSQLDataSet.Name := 'SubSQLDataSet'; { Do not localize }
FSQLDataSet.SetSubComponent(True);
end;
procedure TCustomBindSourceDBX.AllocClientDataSet;
begin
FClientDataSet := TSubClientDataSet.Create(Self);
FClientDataSet.Name := 'SubClientDataSet'; { Do not localize }
FClientDataSet.SetSubComponent(True);
Self.DataComponent := FClientDataSet;
end;
procedure TCustomBindSourceDBX.AllocProvider;
begin
FProvider := TSubDataSetProvider.Create(Self);
FProvider.Name := 'SubProvider'; { Do not localize }
FProvider.SetSubComponent(True);
end;
{ TSubClientDataSet }
procedure TSubClientDataSet.DefaultOnReconcileError(DataSet: TCustomClientDataSet; E: EReconcileError;
UpdateKind: TUpdateKind; var Action: TReconcileAction);
begin
FReconcileError := E.Message;
end;
procedure TSubClientDataSet.AutoApplyUpdates;
var
LHaveOnReconcileError: Boolean;
begin
if GetBindScope.AutoApply then
begin
LHaveOnReconcileError := Assigned(OnReconcileError);
if not LHaveOnReconcileError then
OnReconcileError := DefaultOnReconcileError;
try
FReconcileError := '';
// Ignore max errors when auto apply
ApplyUpdates(1);
if FReconcileError <> '' then
begin
raise EBindCompError.Create(FReconcileError);
end;
finally
if not LHaveOnReconcileError then
OnReconcileError := nil;
end;
end;
end;
procedure TSubClientDataSet.DoAfterDelete;
begin
AutoApplyUpdates;
inherited;
end;
procedure TSubClientDataSet.DoAfterPost;
begin
AutoApplyUpdates;
inherited;
end;
function TSubClientDataSet.GetBindScope: TCustomBindSourceDBX;
begin
Result := Owner as TCustomBindSourceDBX;
end;
function TSubClientDataSet.GetProviderName: string;
begin
Result := inherited ProviderName;
end;
procedure TSubClientDataSet.SetProviderName(const AName: string);
begin
inherited ProviderName := AName;
end;
{ TSubSQLDataSet }
destructor TSubSQLDataSet.Destroy;
begin
inherited;
end;
function TSubSQLDataSet.GetSQLConnection: TSQLConnection;
begin
Result := inherited SQLConnection;
end;
procedure TSubSQLDataSet.SetSQLConnection(AConnection: TSQLConnection);
begin
inherited SQLConnection := AConnection;
end;
{ TIntDataSetProvider }
destructor TSubDataSetProvider.Destroy;
begin
inherited;
end;
function TSubDataSetProvider.GetDataSet: TDataSet;
begin
Result := inherited DataSet;
end;
procedure TSubDataSetProvider.SetDataSet(ADataSet: TDataSet);
begin
inherited DataSet := ADataSet;
end;
{ TCustomSQLParamsAdapter }
constructor TCustomParamsAdapter.Create(AOwner: TComponent);
begin
inherited;
end;
procedure TCustomParamsAdapter.DoAfterOpen;
begin
end;
procedure TCustomParamsAdapter.DoBeforeExecute;
begin
if Assigned(FBeforeExecute) then FBeforeExecute(Self);
end;
procedure TCustomParamsAdapter.DoBeforeOpen;
begin
inherited;
if FCustomSQLDataSet is TSQLStoredProc then
begin
TSQLStoredProc(FCustomSQLDataSet).Prepared := True;
end;
AddFields;
end;
procedure TCustomParamsAdapter.DoAfterClose;
begin
inherited;
//ClearFields;
end;
procedure TCustomParamsAdapter.DoAfterExecute;
begin
if Assigned(FAfterExecute) then FAfterExecute(Self);
end;
function TCustomParamsAdapter.GetCanModify: Boolean;
begin
Result := True;
end;
destructor TCustomParamsAdapter.Destroy;
begin
inherited;
end;
procedure TCustomParamsAdapter.DoExecute;
begin
if FCustomSQLDataSet <> nil then
begin
if FCustomSQLDataSet is TSQLStoredProc then
TSQLStoredProc(FCustomSQLDataSet).ExecProc
else if FCustomSQLDataSet is TSQLQuery then
begin
// check if sql is a query or executed statement
if TSQLQuery(FCustomSQLDataSet).SQL.Text.Trim.ToUpper.IndexOf('SELECT') = 0 then
begin
if FCustomSQLDataSet.Active then
FCustomSQLDataSet.Close;
FCustomSQLDataSet.Open;
end
else
TSQLQuery(FCustomSQLDataSet).ExecSQL;
end
else if (FCustomSQLDataSet is TSQLDataSet) and (TSQLDataSet(FCustomSQLDataSet).CommandType = ctQuery) then
begin
if TSQLDataSet(FCustomSQLDataSet).CommandText.Trim.ToUpper.IndexOf('SELECT') = 0 then
begin
if FCustomSQLDataSet.Active then
FCustomSQLDataSet.Close;
FCustomSQLDataSet.Open;
end
else
TSQLDataSet(FCustomSQLDataSet).ExecSQL;
end
else // all else - just query
begin
if FCustomSQLDataSet.Active then
FCustomSQLDataSet.Close;
FCustomSQLDataSet.Open;
end;
end;
Self.DataSetChanged;
end;
procedure TCustomParamsAdapter.Execute;
begin
Active := True;
if Self.State in [TBindSourceAdapterState.seEdit, TBindSourceAdapterState.seInsert] then
Post;
DoBeforeExecute;
DoExecute;
DoAfterExecute;
end;
function TCustomParamsAdapter.GetCount: Integer;
begin
Result := 1;
end;
function TCustomParamsAdapter.GetSQLDataSet: TSQLDataSet;
begin
if FCustomSQLDataSet is TSQLDataSet then
Result := FCustomSQLDataSet as TSQLDataSet
else
Result := nil;
end;
function TCustomParamsAdapter.GetParams: TParams;
begin
if FCustomSQLDataSet is TSQLDataSet then
Result := TSQLDataSet(FCustomSQLDataSet).Params
else if FCustomSQLDataSet is TSQLQuery then
Result := TSQLQuery(FCustomSQLDataSet).Params
else if FCustomSQLDataSet is TSQLStoredProc then
Result := TSQLStoredProc(FCustomSQLDataSet).Params
else
Result := nil;
end;
function TCustomParamsAdapter.GetSQLQuery: TSQLQuery;
begin
if FCustomSQLDataSet is TSQLQuery then
Result := FCustomSQLDataSet as TSQLQuery
else
Result := nil;
end;
function TCustomParamsAdapter.GetSQLServerMethod: TSQLServerMethod;
begin
if FCustomSQLDataSet is TSqlServerMethod then
Result := FCustomSQLDataSet as TSQLServerMethod
else
Result := nil;
end;
function TCustomParamsAdapter.GetSQLStoredProc: TSQLStoredProc;
begin
if FCustomSQLDataSet is TSQLStoredProc then
Result := FCustomSQLDataSet as TSQLStoredProc
else
Result := nil;
end;
procedure TCustomParamsAdapter.Loaded;
begin
inherited;
if FDeferActivate then
try
Active := True;
except
// Ignore exception during load
end;
end;
procedure TCustomParamsAdapter.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if Operation = TOperation.opRemove then
begin
if AComponent = FCustomSQLDataSet then
FCustomSQLDataSet := nil;
end;
end;
procedure TCustomParamsAdapter.OnActiveChanged(Sender: TObject);
begin
if FCustomSQLDataSet <> nil then
begin
if FCustomSQLDataSet.Active then
AddFields
// else
// ClearFields;
end;
end;
procedure TCustomParamsAdapter.SetActive(AValue: Boolean);
begin
if csLoading in ComponentState then
begin
if AValue then
begin
FDeferActivate := True;
Exit;
end;
end;
inherited;
end;
procedure TCustomParamsAdapter.SetCustomSQLDataSet(
const Value: TCustomSQLDataSet);
begin
if FCustomSQLDataSet <> Value then
if FCustomSQLDataSet <> nil then
FCustomSQLDataSet.RemoveFreeNotification(Self);
FCustomSQLDataSet := Value;
if FCustomSQLDataSet <> nil then
FCustomSQLDataSet.FreeNotification(Self);
end;
procedure TCustomParamsAdapter.SetSQLDataSet(const Value: TSQLDataSet);
begin
SetCustomSQLDataSet(Value);
end;
procedure TCustomParamsAdapter.SetSQLQuery(const Value: TSQLQuery);
begin
SetCustomSQLDataSet(Value);
end;
procedure TCustomParamsAdapter.SetSQLServerMethod(
const Value: TSQLServerMethod);
begin
SetCustomSQLDataSet(Value);
end;
procedure TCustomParamsAdapter.SetSQLStoredProc(const Value: TSQLStoredProc);
begin
SetCustomSQLDataSet(Value);
end;
procedure TCustomParamsAdapter.MakeParamField<T>(AParam: TParam);
var
LField: TBindSourceAdapterField;
LParamReader: TValueReader<T>;
LParamWriter: TValueWriter<T>;
LTypeName: string;
LTypeKind: TTypeKind;
begin
LParamWriter := nil;
LParamReader := nil;
LTypeName := PTypeInfo(TypeInfo(T)).NameFld.ToString;
LTypeKind := PTypeInfo(TypeInfo(T)).Kind;
case AParam.ParamType of
//ptUnknown: ;
ptInput,
ptOutput,
ptInputOutput,
ptResult:
begin
// Note that a param name rather than TParam is stored to make adapter fields less sensitive to destruction of TParam by the command.
// Two reasons. 1) can't tell when a TParam is destroyed. 2) LiveBindings designer shows fields even if the command is closed.
if AParam.ParamType in [ptInput, ptInputOutput] then
LParamWriter := TValueWriterProc<T>.Create(AParam.Name,
procedure(AName: string; AValue: T)
var
LParam: TParam;
begin
if FCustomSQLDataSet <> nil then
begin
LParam := FCustomSQLDataSet.ParamByName(AName); //raises exception if not found
//LParam.Value := TValue.From<T>(AValue).ToString;
case LTypeKind of
//tkUnknown,tkClassRef,tkPointer,tkProcedure,tkSet,tkClass,tkMethod,tkArray,tkRecord,tkMRecord,tkInterface,tkDynArray,
tkEnumeration:
if SameText('boolean', LTypeName) then
LParam.AsBoolean := TValue.From<T>(AValue).AsType<Boolean>
else
raise Exception.CreateFmt('Unsupported ParamType "%s" %s to %s',
[LParam.Name, GetEnumName(TypeInfo(TParamType), Integer(LParam.ParamType)), LTypeName]);
tkInteger:
LParam.AsInteger := TValue.From<T>(AValue).AsType<Integer>;
tkInt64:
LParam.AsLargeInt := TValue.From<T>(AValue).AsType<Int64>;
tkFloat:
LParam.AsFloat := TValue.From<T>(AValue).AsType<Extended>;
tkLString,tkWString,tkUString,tkString,tkWChar,tkChar:
LParam.AsString := TValue.From<T>(AValue).AsType<string>;
tkVariant:
LParam.Value := TValue.From<T>(AValue).AsType<Variant>;
else
raise Exception.CreateFmt('Unsupported ParamType "%s" %s to %s',
[LParam.Name, GetEnumName(TypeInfo(TParamType), Integer(AParam.ParamType)), LTypeName]);
end;
end;
end);
LParamReader := TValueReaderFunc<T>.Create(AParam.Name,
function(AName: string): T
var
LParam: TParam;
begin
if FCustomSQLDataSet <> nil then
begin
LParam := FCustomSQLDataSet.ParamByName(AName); //raises exception if not found
if LParam.IsNull then
begin
case LTypeKind of
//tkUnknown,tkClassRef,tkPointer,tkProcedure,tkSet,tkClass,tkMethod,tkArray,tkRecord,tkMRecord,tkInterface,tkDynArray,
tkEnumeration:
if SameText('boolean', LTypeName) then
Result := TValue.From<Boolean>(False).AsType<T>
else
raise Exception.CreateFmt('Unsupported ParamType "%s" %s to %s',
[LParam.Name, GetEnumName(TypeInfo(TParamType), Integer(LParam.ParamType)), LTypeName]);
tkInteger:
Result := TValue.From<Integer>(0).AsType<T>;
tkInt64:
Result := TValue.From<Int64>(0).AsType<T>;
tkFloat:
Result := TValue.From<Extended>(0).AsType<T>;
tkLString,tkWString,tkUString,tkString,tkWChar,tkChar:
Result := TValue.From<string>('').AsType<T>;
tkVariant:
Result := TValue.From<Variant>(0).AsType<T>; // might not be supported anyhow
else
raise Exception.CreateFmt('Unsupported ParamType "%s" %s to %s',
[LParam.Name, GetEnumName(TypeInfo(TParamType), Integer(AParam.ParamType)), LTypeName]);
end;
end
else
begin
case LTypeKind of
//tkUnknown,tkClassRef,tkPointer,tkProcedure,tkSet,tkClass,tkMethod,tkArray,tkRecord,tkMRecord,tkInterface,tkDynArray,
tkEnumeration:
if SameText('boolean', LTypeName) then
Result := TValue.From<Boolean>(LParam.AsBoolean).AsType<T>
else
raise Exception.CreateFmt('Unsupported ParamType "%s" %s to %s',
[LParam.Name, GetEnumName(TypeInfo(TParamType), Integer(LParam.ParamType)), LTypeName]);
tkInteger:
Result := TValue.From<Integer>(LParam.AsInteger).AsType<T>;
tkInt64:
Result := TValue.From<Int64>(LParam.AsLargeInt).AsType<T>;
tkFloat:
Result := TValue.From<Extended>(LParam.AsFloat).AsType<T>;
tkLString,tkWString,tkUString,tkString,tkWChar,tkChar:
Result := TValue.From<string>(LParam.AsString).AsType<T>;
tkVariant:
Result := TValue.From<Variant>(LParam.Value).AsType<T>; // might not be supported anyhow
else
raise Exception.CreateFmt('Unsupported ParamType "%s" %s to %s',
[LParam.Name, GetEnumName(TypeInfo(TParamType), Integer(AParam.ParamType)), LTypeName]);
end;
end;
end
else
raise Exception.Create('FCustomSQLDataSet was nil!');
end);
if LParamWriter <> nil then
LField := TFieldUtils.CreateField<T>(Self, AParam.Name,
TScopeMemberType.mtText,
LParamReader,
LParamWriter)
else
LField := TFieldUtils.CreateField<T>(Self, AParam.Name,
TScopeMemberType.mtText,
LParamReader);
Self.AddField(LField);
end;
else
raise Exception.CreateFmt('Unsupported ParamType "%s" %s', [AParam.Name, GetEnumName(TypeInfo(TParamType), Integer(AParam.ParamType))]);
end;
end;
procedure TCustomParamsAdapter.AddFields;
var
I: Integer;
LParams: TParams;
LParam: TParam;
begin
ClearFields;
if FCustomSQLDataSet <> nil then
begin
LParams := GetParams;
for I := 0 to LParams.Count - 1 do
begin
LParam := LParams[I];
case LParam.DataType of
//ftUnknown,ftBCD,ftTime,ftDateTime,ftDate,
//ftBytes,ftVarBytes,ftAutoInc,ftBlob,ftGraphic,ftFmtMemo,ftParadoxOle,ftDBaseOle,ftTypedBinary,ftCursor,ftADT,
//ftArray,ftReference,ftDataSet,ftOraBlob,ftOraClob,ftInterface,ftIDispatch,ftGuid,ftTimeStamp,ftFMTBcd,
//ftOraTimeStamp,ftOraInterval,ftExtended,ftConnection,ftParams,ftStream,ftTimeStampOffset,ftObject,
TFieldType.ftWord: MakeParamField<Word>(LParam);
TFieldType.ftByte: MakeParamField<Byte>(LParam);
TFieldType.ftLongWord: MakeParamField<LongWord>(LParam);
TFieldType.ftSmallint,TFieldType.ftShortint,TFieldType.ftInteger: MakeParamField<Integer>(LParam);
TFieldType.ftLargeint: MakeParamField<Int64>(LParam);
TFieldType.ftSingle: MakeParamField<Single>(LParam);
TFieldType.ftFloat: MakeParamField<Extended>(LParam);
TFieldType.ftCurrency: MakeParamField<Currency>(LParam);
TFieldType.ftBoolean: MakeParamField<Boolean>(LParam);
TFieldType.ftMemo,TFieldType.ftWideMemo,TFieldType.ftFixedWideChar,
TFieldType.ftString,TFieldType.ftFixedChar,
TFieldType.ftWideString: MakeParamField<string>(LParam);
TFieldType.ftVariant: MakeParamField<Variant>(LParam);
else
raise Exception.CreateFmt('Unsupported param "%s" %s', [LParam.Name, GetEnumName(TypeInfo(TFieldType), Integer(LParam.DataType))]);
end;
end;
end;
end;
function TCustomParamsAdapter.GetCanActivate: Boolean;
begin
Result := (FCustomSQLDataSet <> nil);
end;
end.
|
unit uModel.PessoaContato;
interface
uses System.SysUtils, System.Classes,
uModel.Interfaces;
type
TPessoaContatoModel = class(TInterfacedObject, iPessoaContatoModel)
private
FId: Integer;
FIdPessoa: Integer;
FTipo: string;
FContato: string;
public
constructor Create;
destructor Destroy; override;
class function New: iPessoaContatoModel;
function Id: Integer; overload;
function Id(Value: Integer): iPessoaContatoModel; overload;
function IdPessoa: Integer; overload;
function IdPessoa(Value: Integer): iPessoaContatoModel; overload;
function Tipo: string; overload;
function Tipo(Value: string): iPessoaContatoModel; overload;
function Contato: string; overload;
function Contato(Value: string): iPessoaContatoModel; overload;
end;
implementation
{ TPessoaContatoModel }
constructor TPessoaContatoModel.Create;
begin
end;
destructor TPessoaContatoModel.Destroy;
begin
inherited;
end;
class function TPessoaContatoModel.New: iPessoaContatoModel;
begin
Result := Self.Create;
end;
function TPessoaContatoModel.Id: Integer;
begin
Result := FId;
end;
function TPessoaContatoModel.Id(Value: Integer): iPessoaContatoModel;
begin
Result := Self;
FId := Value;
end;
function TPessoaContatoModel.IdPessoa(Value: Integer): iPessoaContatoModel;
begin
Result := Self;
FIdPessoa := Value;
end;
function TPessoaContatoModel.IdPessoa: Integer;
begin
Result := FIdPessoa;
end;
function TPessoaContatoModel.Tipo: string;
begin
Result := FTipo;
end;
function TPessoaContatoModel.Tipo(Value: string): iPessoaContatoModel;
begin
Result := Self;
FTipo := Value;
end;
function TPessoaContatoModel.Contato(Value: string): iPessoaContatoModel;
begin
Result := Self;
FContato := Value;
end;
function TPessoaContatoModel.Contato: string;
begin
Result := FContato;
end;
end.
|
unit main;
interface
uses
Winapi.Windows, Winapi.Messages,
System.SysUtils, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms,
Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls,
//GLS
GLObjects, GLWin32Viewer, dws2Comp, GLScene,
dws2OpenGL1x, GLDWS2Objects, dws2Exprs, GLTexture, GLCadencer, GLAsyncTimer,
GLBitmapFont, GLWindowsFont, GLHUDObjects,
dws2VectorGeometry, GLCoordinates, GLCrossPlatform, GLBaseClasses, GLScriptDWS2,
GLRenderContextInfo;
type
TForm1 = class(TForm)
GLDelphiWebScriptII1: TGLDelphiWebScriptII;
dws2OpenGL1xUnit1: Tdws2OpenGL1xUnit;
GLScene1: TGLScene;
GLSceneViewer1: TGLSceneViewer;
GLCamera1: TGLCamera;
GLLightSource1: TGLLightSource;
GLDirectOpenGL1: TGLDirectOpenGL;
GLDummyCube1: TGLDummyCube;
GLCadencer1: TGLCadencer;
AsyncTimer1: TGLAsyncTimer;
GLHUDText1: TGLHUDText;
GLWindowsBitmapFont1: TGLWindowsBitmapFont;
Panel2: TPanel;
CompileButton: TButton;
Script: TMemo;
dws2VectorGeometryUnit1: Tdws2VectorGeometryUnit;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure GLDirectOpenGL1Render(Sender: TObject;
var rci: TRenderContextInfo);
procedure GLSceneViewer1MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
procedure GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
procedure AsyncTimer1Timer(Sender: TObject);
procedure CompileButtonClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
mx, my : Integer;
Prog : TProgram;
Errors : Boolean;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses OpenGL1x, GLContext;
procedure TForm1.FormCreate(Sender: TObject);
begin
CompileButtonClick(Self);
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
Prog.Free;
end;
procedure TForm1.CompileButtonClick(Sender: TObject);
begin
Prog.Free;
Prog:=GLDelphiWebScriptII1.Compile(Script.Text);
Errors:=False;
GLDirectOpenGL1.Visible:=True;
GLDirectOpenGL1.StructureChanged;
end;
procedure TForm1.GLDirectOpenGL1Render(Sender: TObject;
var rci: TRenderContextInfo);
begin
if Errors then exit;
try
Prog.Execute;
CheckOpenGLError;
except
on E : Exception do begin
GLHUDText1.ModulateColor.AsWinColor:=clRed;
GLHUDText1.Text:='Error: '+E.Message;
Errors:=True;
GLDirectOpenGL1.Visible:=False;
Exit;
end;
end;
Errors:=False;
end;
procedure TForm1.GLSceneViewer1MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
mx:=x;
my:=y;
end;
procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
begin
if ssLeft in Shift then
GLCamera1.MoveAroundTarget(my-y, mx-x);
mx:=x;
my:=y;
end;
procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
begin
GLDirectOpenGL1.Turn(20*deltaTime);
end;
procedure TForm1.AsyncTimer1Timer(Sender: TObject);
begin
if not Errors then begin
GLHUDText1.ModulateColor.AsWinColor:=clNavy;
GLHUDText1.Text:=GLSceneViewer1.FramesPerSecondText;
end;
GLSceneViewer1.ResetPerformanceMonitor;
end;
end.
|
unit UnitActualizarPorReferencias;
interface
uses
global, frm_connection, SysUtils, ZDataset, ZConnection, Classes, Dialogs;
var
pdbError: string;
function dbExec(sSQLCommand: string; paramNames, paramValues: TStringList; Owner: TComponent): boolean;
function actualizarTablasActOrden(WbsNuevo, WbsOrig, orden: string; AOwner: TComponent): boolean;
implementation
function dbExec(sSQLCommand: string; paramNames, paramValues: TStringList; Owner: TComponent): boolean;
var
ZExec: TZQuery;
ii: integer;
begin
result := true;
pdbError := '';//reiniciar el error DB
ZExec := TZQuery.Create(Owner); //crear el componente
ZExec.Connection := connection.ZConnection;
ZExec.Active := false;
ZExec.SQL.Clear;
ZExec.SQL.Add(sSQLCommand);//agregar la instruccion
for ii := 0 to paramNames.Count - 1 do begin //agregar los parametros
ZExec.ParamByName(paramNames[ii]).Value := paramValues[ii];
end;
try
ZExec.ExecSQL;
except
on E: exception do begin //se devuelve falso y se registra el error
pdbError := E.Message;
result := false;
end;
end;
ZExec.Free;
end;
function actualizarTablasActOrden(WbsNuevo, WbsOrig, orden: string; AOwner: TComponent): boolean;
var
sSQL, sTabla, sBloque: string;
paramNames, paramValues: TStringList;
begin
paramNames := TStringList.Create; paramValues := TStringList.Create;
//actualizar solo las wbs
sBloque :=
' SET sWbs = :wbs ' +
'WHERE sContrato = :contrato AND sIdConvenio = :convenio '+
'AND sWbs = :wbsOrig AND sNumeroOrden = :orden';
paramNames.Add('wbs');paramNames.Add('contrato');paramNames.Add('convenio');paramNames.Add('wbsOrig');paramNames.Add('orden');
paramValues.Add(WbsNuevo);paramValues.Add(global_contrato);paramValues.Add(global_convenio);paramValues.Add(WbsOrig);paramValues.Add(orden);
sTabla := 'avancesxactividad';
sSQL := 'UPDATE ' + sTabla + sBloque;
if not dbExec(sSQL, paramNames, paramValues, AOwner) then
showmessage(pdbError);
sTabla := 'bitacoradepaquetes';
sSQL := 'UPDATE ' + sTabla + sBloque;
dbExec(sSQL, paramNames, paramValues, AOwner);
sTabla := 'distribuciondeactividades';
sSQL := 'UPDATE ' + sTabla + sBloque;
dbExec(sSQL, paramNames, paramValues, AOwner);
sTabla := 'ordenes_programamensual';
sSQL := 'UPDATE ' + sTabla + sBloque;
dbExec(sSQL, paramNames, paramValues, AOwner);
paramNames.Clear; paramNames.Clear;
//actualizar solo las wbs, sin convenio
sBloque :=
' SET sWbs = :wbs ' +
'WHERE sContrato = :contrato '+
'AND sWbs = :wbsOrig AND sNumeroOrden = :orden';
paramNames.Add('wbs');paramNames.Add('contrato');paramNames.Add('wbsOrig');paramNames.Add('orden');
paramValues.Add(WbsNuevo);paramValues.Add(global_contrato);paramValues.Add(WbsOrig);paramValues.Add(orden);
sTabla := 'actividadesxgrupo';
sSQL := 'UPDATE ' + sTabla + sBloque;
dbExec(sSQL, paramNames, paramValues, AOwner);
sTabla := 'bitacoradealcances';
sSQL := 'UPDATE ' + sTabla + sBloque;
dbExec(sSQL, paramNames, paramValues, AOwner);
sTabla := 'estimacionxpartida';
sSQL := 'UPDATE ' + sTabla + sBloque;
dbExec(sSQL, paramNames, paramValues, AOwner);
sTabla := 'estimacionxpartidaprov';
sSQL := 'UPDATE ' + sTabla + sBloque;
dbExec(sSQL, paramNames, paramValues, AOwner);
sTabla := 'bitacoradeactividades';
sSQL := 'UPDATE ' + sTabla + sBloque;
dbExec(sSQL, paramNames, paramValues, AOwner);
end;
end.
|
unit LLCLZlib;
{
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.
* Zlib interface for the Light LCL implemented
}
{$IFDEF FPC}
{$define LLCL_FPC_MODESECTION}
{$I LLCLFPCInc.inc} // For mode
{$undef LLCL_FPC_MODESECTION}
{$ENDIF}
{$ifdef FPC_OBJFPC} {$define LLCL_OBJFPC_MODE} {$endif} // Object pascal mode
{$I LLCLOptions.inc} // Options
// Zlib option checks
{$if Defined(LLCL_OPT_USEZLIBDLL) and Defined(LLCL_OPT_USEZLIBOBJ)}
{$error Can't have several Zlib options at the same time}
{$ifend}
{$if Defined(LLCL_OPT_USEZLIBDLLDYN) and (not Defined(LLCL_OPT_USEZLIBDLL))}
{$error Can't have the dynamic DLL Zlib option without LLCL_OPT_USEZLIBDLL}
{$ifend}
//------------------------------------------------------------------------------
interface
// The destination buffer must be large enough to hold the entire compressed/uncompressed data
function LLCL_compress(dest: PByte; var destLen: cardinal; source: PByte; sourceLen: cardinal): integer;
function LLCL_compress2(dest: PByte; var destLen: cardinal; source: PByte; sourceLen: cardinal; level: integer): integer;
function LLCL_uncompress(dest: PByte; var destLen: cardinal; source: PByte; sourceLen: cardinal): integer;
//------------------------------------------------------------------------------
implementation
{$if Defined(LLCL_OPT_USEZLIBDLLDYN)}
uses
LLCLOSInt,
Windows;
{$ifend LLCL_OPT_USEZLIBDLLDYN}
{$IFDEF FPC}
{$PUSH} {$HINTS OFF}
{$ENDIF}
{$if Defined(LLCL_OPT_USEZLIBDLL) or Defined(LLCL_OPT_USEZLIBOBJ)}
type
PBytef = PByte;
{$IFDEF FPC}
TAlloc_func = function (opaque: pointer; items, size: cardinal): pointer; cdecl;
TFree_func = procedure (opaque, ptr: pointer); cdecl;
{$ELSE FPC}
{$if Defined(LLCL_OPT_USEZLIBOBJ)}
TAlloc_func = function (opaque: pointer; items, size: cardinal): pointer;
TFree_func = procedure (opaque, ptr: pointer);
{$else LLCL_OPT_USEZLIBOBJ}
TAlloc_func = function (opaque: pointer; items, size: cardinal): pointer; cdecl;
TFree_func = procedure (opaque, ptr: pointer); cdecl;
{$ifend LLCL_OPT_USEZLIBOBJ}
{$ENDIF FPC}
TZStreamRec = packed record
next_in: PBytef; // next input byte
avail_in: cardinal; // number of bytes available at next_in
total_in: cardinal; // total number of input bytes read so far
next_out: PBytef; // next output byte should be put there
avail_out: cardinal; // remaining free space at next_out
total_out: cardinal; // total number of bytes output so far
msg: PChar; // last error message, NULL if no error
internal_state: pointer; // not visible by applications
zalloc: TAlloc_func; // used to allocate the internal state
zfree: TFree_func; // used to free the internal state
opaque: pointer; // private data object passed to zalloc and zfree
data_type: integer; // best guess about the data type: binary or text
adler: cardinal; // adler32 value of the uncompressed data
reserved: cardinal; // reserved for future use
end;
{$if Defined(LLCL_OPT_USEZLIBOBJ)} // Obj
const
zlib_version: ansistring = '1.2.8';
Z_FINISH = 4;
Z_OK = 0;
Z_STREAM_END = 1;
Z_NEED_DICT = 2;
Z_DATA_ERROR = -3;
Z_BUF_ERROR = -5;
Z_DEFAULT_COMPRESSION = -1;
{$IFNDEF FPC}
z_errmsg: array [0..pred(10)] of string = (
'need dictionary', // Z_NEED_DICT 2
'stream end', // Z_STREAM_END 1
'', // Z_OK 0
'file error', // Z_ERRNO (-1)
'stream error', // Z_STREAM_ERROR (-2)
'data error', // Z_DATA_ERROR (-3)
'insufficient memory', // Z_MEM_ERROR (-4)
'buffer error', // Z_BUF_ERROR (-5)
'incompatible version', // Z_VERSION_ERROR (-6)
'' );
{$ENDIF NFPC}
{$IFDEF FPC}
{$if Defined(CPU64) or Defined(CPU64BITS)}
{$L ZlibObj\win64\adler32.o}
{$L ZlibObj\win64\crc32.o}
{$L ZlibObj\win64\deflate.o}
{$L ZlibObj\win64\infback.o}
{$L ZlibObj\win64\inffast.o}
{$L ZlibObj\win64\inflate.o}
{$L ZlibObj\win64\inftrees.o}
{$L ZlibObj\win64\match.o}
{$L ZlibObj\win64\trees.o}
{$L ZlibObj\win64\zutil.o}
{$else}
{$L ZlibObj\win32\adler32.o}
{$L ZlibObj\win32\crc32.o}
{$L ZlibObj\win32\deflate.o}
{$L ZlibObj\win32\infback.o}
{$L ZlibObj\win32\inffast.o}
{$L ZlibObj\win32\inflate.o}
{$L ZlibObj\win32\inftrees.o}
{$L ZlibObj\win32\match.o}
{$L ZlibObj\win32\trees.o}
{$L ZlibObj\win32\zutil.o}
{$ifend}
function deflateInit_(var strm: TZStreamRec; level: integer; version: PAnsiChar; stream_size: integer): integer; cdecl; external;
function deflate(var strm: TZStreamRec; flush: integer): integer; cdecl; external;
function deflateEnd(var strm: TZStreamRec): integer; cdecl; external;
function inflateInit_(var strm: TZStreamRec; version: PAnsiChar; stream_size: integer): integer; cdecl; external;
function inflate(var strm: TZStreamRec; flush: integer): integer; cdecl; external;
function inflateEnd(var strm: TZStreamRec): integer; cdecl; external;
//
function zcalloc(opaque: pointer; items, size: cardinal): pointer; cdecl; forward;
procedure zcfree(opaque, ptr: pointer); cdecl; forward;
function _malloc(size: cardinal): pointer; cdecl; [public, alias: '_malloc']; forward;
procedure _free(ptr: pointer); cdecl; [public, alias: '_free']; forward;
{$ELSE FPC}
{$if Defined(CPU64) or Defined(CPU64BITS)}
{$L ZlibObj\win64\deflate.obj}
{$L ZlibObj\win64\inflate.obj}
{$L ZlibObj\win64\inftrees.obj}
{$L ZlibObj\win64\infback.obj}
{$L ZlibObj\win64\inffast.obj}
{$L ZlibObj\win64\trees.obj}
{$L ZlibObj\win64\compress.obj}
{$L ZlibObj\win64\adler32.obj}
{$L ZlibObj\win64\crc32.obj}
{$else}
{$L ZlibObj\win32\deflate.obj}
{$L ZlibObj\win32\inflate.obj}
{$L ZlibObj\win32\inftrees.obj}
{$L ZlibObj\win32\infback.obj}
{$L ZlibObj\win32\inffast.obj}
{$L ZlibObj\win32\trees.obj}
{$L ZlibObj\win32\compress.obj}
{$L ZlibObj\win32\adler32.obj}
{$L ZlibObj\win32\crc32.obj}
{$ifend}
function deflateInit_(var strm: TZStreamRec; level: integer; version: PAnsiChar; stream_size: integer): integer; external;
function deflate(var strm: TZStreamRec; flush: integer): integer; external;
function deflateEnd(var strm: TZStreamRec): integer; external;
function inflateInit_(var strm: TZStreamRec; version: PAnsiChar; stream_size: integer): integer; external;
function inflate(var strm: TZStreamRec; flush: integer): integer; external;
function inflateEnd(var strm: TZStreamRec): integer; external;
//
function zcalloc(opaque: pointer; items, size: cardinal): pointer; forward;
procedure zcfree(opaque, ptr: pointer); forward;
function memset(ptr: pointer; value: byte; num: integer): pointer; cdecl; forward;
procedure memcpy(destination, source: pointer; num: integer); cdecl; forward;
{$if (not Defined(CPU64)) and (not Defined(CPU64BITS))}
procedure _llmod; forward;
{$ifend}
{$ENDIF FPC}
{$else LLCL_OPT_USEZLIBOBJ} // DLL
const
zlib_dll = 'zlib1.dll';
{$if Defined(LLCL_OPT_USEZLIBDLLDYN)} // Dynamic DLL
Z_ERRNO = -1;
var
ZlibDllHandle: HMODULE = 0;
inflateInit_: function(var strm: TZStreamRec; version: PAnsiChar; stream_size: integer): integer; cdecl;
inflate: function(var strm: TZStreamRec; flush: integer): integer; cdecl;
inflateEnd: function(var strm: TZStreamRec): integer; cdecl;
compress: function(dest: PBytef; var destLen: cardinal; source: PBytef; sourceLen: cardinal): integer; cdecl;
compress2: function(dest: PBytef; var destLen: cardinal; source: PBytef; sourceLen: cardinal; level: integer): integer; cdecl;
uncompress: function(dest: PBytef; var destLen: cardinal; source: PBytef; sourceLen: cardinal): integer; cdecl;
function LLCL_LoadZlib(): boolean; forward;
{$else LLCL_OPT_USEZLIBDLLDYN} // Static DLL
function inflateInit_(var strm: TZStreamRec; version: PAnsiChar; stream_size: integer): integer; cdecl; external zlib_dll;
function inflate(var strm: TZStreamRec; flush: integer): integer; cdecl; external zlib_dll;
function inflateEnd(var strm: TZStreamRec): integer; cdecl; external zlib_dll;
function compress(dest: PBytef; var destLen: cardinal; source: PBytef; sourceLen: cardinal): integer; cdecl external zlib_dll;
function compress2(dest: PBytef; var destLen: cardinal; source: PBytef; sourceLen: cardinal; level: integer): integer; cdecl external zlib_dll;
function uncompress(dest: PBytef; var destLen: cardinal; source: PBytef; sourceLen: cardinal): integer; cdecl external zlib_dll;
{$ifend LLCL_OPT_USEZLIBDLLDYN}
{$ifend LLCL_OPT_USEZLIBOBJ}
{$else LLCL_OPT_USEZLIBDLL or LLCL_OPT_USEZLIBOBJ} // PazZlib
uses
{$IFDEF FPC}PasZlib{$ELSE}SysUtils, gZlib, ZUtil, zCompres, zUnCompr{$ENDIF};
{$ifend LLCL_OPT_USEZLIBDLL or LLCL_OPT_USEZLIBOBJ}
//------------------------------------------------------------------------------
{$if Defined(LLCL_OPT_USEZLIBDLL) or Defined(LLCL_OPT_USEZLIBOBJ)}
// Obj
{$if Defined(LLCL_OPT_USEZLIBOBJ)}
{$IFDEF FPC}
function zcalloc(opaque: pointer; items, size: cardinal): pointer; cdecl;
begin
GetMem(result, items * size);
end;
procedure zcfree(opaque, ptr: pointer); cdecl;
begin
FreeMem(ptr);
end;
// _malloc and _free not used, if zcalloc and zcfree are used
function _malloc(size: cardinal): pointer; cdecl;
begin
GetMem(result, size);
end;
procedure _free(ptr: pointer); cdecl;
begin
FreeMem(ptr);
end;
{$ELSE FPC}
function zcalloc(opaque: pointer; items, size: cardinal): pointer;
begin
GetMem(result, items * size);
end;
procedure zcfree(opaque, ptr: pointer);
begin
FreeMem(ptr);
end;
function memset(ptr: pointer; value: byte; num: integer): pointer; cdecl;
begin
FillChar(ptr^, num, value);
result := ptr;
end;
procedure memcpy(destination, source: pointer; num: integer); cdecl;
begin
Move(source^, destination^, num);
end;
{$if (not Defined(CPU64)) and (not Defined(CPU64BITS))}
procedure _llmod;
asm
jmp System.@_llmod;
end;
{$ifend}
{$ENDIF FPC}
function LLCL_compress(dest: PByte; var destLen: cardinal; source: PByte; sourceLen: cardinal): integer;
begin
result := LLCL_compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
end;
function LLCL_compress2(dest: PByte; var destLen: cardinal; source: PByte; sourceLen: cardinal; level: integer): integer;
var ZSR: TZStreamRec;
begin
FillChar(ZSR, SizeOf(ZSR), 0);
ZSR.next_in := PBytef(source);
ZSR.avail_in := sourceLen;
ZSR.next_out := PBytef(dest);
ZSR.avail_out := destLen;
ZSR.zalloc := {$IFDEF LLCL_OBJFPC_MODE}@{$ENDIF}zcalloc;
ZSR.zfree := {$IFDEF LLCL_OBJFPC_MODE}@{$ENDIF}zcfree;
result := deflateInit_(ZSR, level, @zlib_version[1], SizeOf(ZSR));
if result<>Z_OK then exit;
result := deflate(ZSR, Z_FINISH);
if result<>Z_STREAM_END then
begin
deflateEnd(ZSR);
if (result=Z_OK) then
result := Z_BUF_ERROR;
exit;
end;
destLen := ZSR.total_out;
result := deflateEnd(ZSR);
end;
function LLCL_uncompress(dest: PByte; var destLen: cardinal; source: PByte; sourceLen: cardinal): integer;
var ZSR: TZStreamRec;
begin
FillChar(ZSR, SizeOf(ZSR), 0);
ZSR.next_in := PBytef(source);
ZSR.avail_in := sourceLen;
ZSR.next_out := PBytef(dest);
ZSR.avail_out := destLen;
ZSR.zalloc := {$IFDEF LLCL_OBJFPC_MODE}@{$ENDIF}zcalloc;
ZSR.zfree := {$IFDEF LLCL_OBJFPC_MODE}@{$ENDIF}zcfree;
result := inflateInit_(ZSR, @zlib_version[1], SizeOf(ZSR));
if result<>Z_OK then exit;
result := inflate(ZSR, Z_FINISH);
if result<>Z_STREAM_END then
begin
inflateEnd(ZSR);
if (result=Z_NEED_DICT) or ((result=Z_BUF_ERROR) and (sourceLen=0)) then
result := Z_DATA_ERROR;
exit;
end;
destLen := ZSR.total_out;
result := inflateEnd(ZSR);
end;
{$else LLCL_OPT_USEZLIBOBJ}
// DLL (static or dynamic)
function LLCL_compress(dest: PByte; var destLen: cardinal; source: PByte; sourceLen: cardinal): integer;
begin
{$if Defined(LLCL_OPT_USEZLIBDLLDYN)}
if not LLCL_LoadZlib() then
begin
result := Z_ERRNO;
exit;
end;
{$ifend LLCL_OPT_USEZLIBDLLDYN}
result := compress(PBytef(dest), destLen, PBytef(source), sourceLen);
end;
function LLCL_compress2(dest: PByte; var destLen: cardinal; source: PByte; sourceLen: cardinal; level: integer): integer;
begin
{$if Defined(LLCL_OPT_USEZLIBDLLDYN)}
if not LLCL_LoadZlib() then
begin
result := Z_ERRNO;
exit;
end;
{$ifend LLCL_OPT_USEZLIBDLLDYN}
result := compress2(PBytef(dest), destLen, PBytef(source), sourceLen, level);
end;
function LLCL_uncompress(dest: PByte; var destLen: cardinal; source: PByte; sourceLen: cardinal): integer;
begin
{$if Defined(LLCL_OPT_USEZLIBDLLDYN)}
if not LLCL_LoadZlib() then
begin
result := Z_ERRNO;
exit;
end;
{$ifend LLCL_OPT_USEZLIBDLLDYN}
result := uncompress(PBytef(dest), destLen, PBytef(source), sourceLen);
end;
{$ifend LLCL_OPT_USEZLIBOBJ}
{$else LLCL_OPT_USEZLIBDLL or LLCL_OPT_USEZLIBOBJ}
// PasZlib
function LLCL_compress(dest: PByte; var destLen: cardinal; source: PByte; sourceLen: cardinal): integer;
begin
{$IFDEF FPC}
result := compress(PChar(dest), destLen, PChar(source), sourceLen);
{$ELSE FPC}
result := compress(PBytef(dest), destLen, PByteArray(source)^, sourceLen);
{$ENDIF FPC}
end;
function LLCL_compress2(dest: PByte; var destLen: cardinal; source: PByte; sourceLen: cardinal; level: integer): integer;
begin
{$IFDEF FPC}
result := compress2(PChar(dest), destLen, PChar(source), sourceLen, level);
{$ELSE FPC}
result := compress2(PBytef(dest), destLen, PByteArray(source)^, sourceLen, level);
{$ENDIF FPC}
end;
function LLCL_uncompress(dest: PByte; var destLen: cardinal; source: PByte; sourceLen: cardinal): integer;
begin
{$IFDEF FPC}
result := uncompress(PChar(dest), destLen, PChar(source), sourceLen);
{$ELSE FPC}
result := uncompress(PBytef(dest), destLen, PByteArray(source)^, sourceLen);
{$ENDIF FPC}
end;
{$ifend LLCL_OPT_USEZLIBDLL or LLCL_OPT_USEZLIBOBJ}
//------------------------------------------------------------------------------
// Dynamic DLL
{$if Defined(LLCL_OPT_USEZLIBDLLDYN)}
function LLCL_LoadZlib(): boolean;
begin
result := false;
if ZlibDllHandle=0 then
begin
inflateInit_ := nil; inflate := nil; inflateEnd := nil;
compress := nil; compress2 := nil; uncompress := nil;
ZlibDllHandle := LLCL_LoadLibrary(zlib_dll);
end;
if ZlibDllHandle=0 then exit;
if not Assigned(inflateInit_) then
{$IFDEF LLCL_OBJFPC_MODE}FARPROC(inflateInit_){$ELSE}@inflateInit_{$ENDIF}
:= LLCL_GetProcAddress(ZlibDllHandle, 'inflateInit_');
if not Assigned(inflate) then
{$IFDEF LLCL_OBJFPC_MODE}FARPROC(inflate){$ELSE}@inflate{$ENDIF}
:= LLCL_GetProcAddress(ZlibDllHandle, 'inflate');
if not Assigned(inflateEnd) then
{$IFDEF LLCL_OBJFPC_MODE}FARPROC(inflateEnd){$ELSE}@inflateEnd{$ENDIF}
:= LLCL_GetProcAddress(ZlibDllHandle, 'inflateEnd');
if not Assigned(compress) then
{$IFDEF LLCL_OBJFPC_MODE}FARPROC(compress){$ELSE}@compress{$ENDIF}
:= LLCL_GetProcAddress(ZlibDllHandle, 'compress');
if not Assigned(compress) then
{$IFDEF LLCL_OBJFPC_MODE}FARPROC(compress){$ELSE}@compress{$ENDIF}
:= LLCL_GetProcAddress(ZlibDllHandle, 'compress');
if not Assigned(compress2) then
{$IFDEF LLCL_OBJFPC_MODE}FARPROC(compress2){$ELSE}@compress2{$ENDIF}
:= LLCL_GetProcAddress(ZlibDllHandle, 'compress2');
if not Assigned(uncompress) then
{$IFDEF LLCL_OBJFPC_MODE}FARPROC(uncompress){$ELSE}@uncompress{$ENDIF}
:= LLCL_GetProcAddress(ZlibDllHandle, 'uncompress');
if (not Assigned(inflateInit_)) or (not Assigned(inflate)) or (not Assigned(inflateEnd))
or (not Assigned(compress)) or (not Assigned(compress2)) or (not Assigned(uncompress)) then
exit;
result := true;
end;
initialization
finalization
if ZlibDllHandle<>0 then
begin
LLCL_FreeLibrary(ZlibDllHandle);
ZlibDllHandle := 0;
end;
{$ifend LLCL_OPT_USEZLIBDLLDYN}
{$IFDEF FPC}
{$POP}
{$ENDIF}
end.
|
unit Auth;
interface
uses InternetHTTP, Dialogs, SysUtils, hwid_impl, JSON;
type
TAuthInputData = record
Login: string[14];
Password: string[14];
end;
TAuthOutputData = record
LaunchParams: string[38];
Login: string[14];
end;
function IsAuth(Data:TAuthInputData): boolean;
var
Authdata:TAuthOutputData;
const
key: Byte = 7;
implementation
function GenerateToken: string;
const
Letters: string = 'abcdef1234567890'; //string with all possible chars
var
I: integer;
begin
Randomize;
for I := 1 to 16 do
Result := Result + Letters[Random(15) + 1];
end;
function cryptString(str: string): string;
var
I: integer;
begin
for I := 1 to Length(str) do
begin
result := result + chr(ord(str[i]) + key);
end;
end;
function decryptString(str: string): string;
var
I: integer;
begin
for I := 1 to Length(str) do
begin
result := result + chr(ord(str[i]) - key);
end;
end;
function IsAuth(Data: TAuthInputData): boolean;
var
Res, Token: string;
Size: LongWord;
PostData: pointer;
r: tresults_array_dv;
begin
Size := 0;
Token := GenerateToken;
AddPOSTField(PostData, Size, 'username', CryptString(Data.Login));
AddPOSTField(PostData, Size, 'password', CryptString(Data.Password));
AddPOSTField(PostData, Size, 'clientToken', CryptString(Token));
AddPOSTField(PostData, Size, 'hid', CryptString(IntToStr(getHardDriveComputerID(r))));
Res := HTTPPost('http://www.happyminers.ru/MineCraft/auth16xpost.php', PostData, Size);
if (Res = 'Bad login') OR (Res = '') then //проверка не прошла
Result := false
else begin
Authdata.LaunchParams := Token + ':' + decryptString(getJsonStr('accessToken', Res));
Authdata.Login := Data.Login;
Result := true; //проверка прошла
end;
end;
end.
|
unit uIRCRichEdit;
interface
uses RichEditURL, Graphics;
type
TIRCRichEdit = class(TRichEditURL)
private
procedure DoSetIRCText(const AText: string; const AAppend: Boolean);
procedure SetSelBgColor(const AColor: TColor);
function GetIRCColor(const AColorIndex: Integer; const ADefault: TColor): TColor;
public
procedure AddIRCText(const AText: string);
procedure SetIRCText(const AText: string);
end;
const
IndentDelim = #4;
implementation
uses SysUtils, fMain, uIRCColors, RichEdit;
{ TIRCRichEdit }
procedure TIRCRichEdit.AddIRCText(const AText: string);
begin
DoSetIRCText(AText, True);
end;
procedure TIRCRichEdit.SetSelBgColor(const AColor: TColor);
var
Format: CHARFORMAT2;
begin
FillChar(Format, SizeOf(Format), 0);
with Format do
begin
cbSize := SizeOf(Format);
dwMask := CFM_BACKCOLOR;
crBackColor := AColor;
Perform(EM_SETCHARFORMAT, SCF_SELECTION, Longint(@Format));
end;
end;
function TIRCRichEdit.GetIRCColor(const AColorIndex: Integer; const ADefault: TColor): TColor;
begin
if (AColorIndex >= Low(IRCColors)) and (AColorIndex <= High(IRCColors)) then
Result := IRCColors[AColorIndex]
else
Result := ADefault;
end;
procedure TIRCRichEdit.DoSetIRCText(const AText: string; const AAppend: Boolean);
var
I: Integer;
TotalText, SoFar, FgColor, BgColor: string;
InColor, FgRead, BgRead, CommaFound: Boolean;
procedure AddTextSoFar;
begin
if SoFar <> '' then
begin
SelText := SoFar;
TotalText := TotalText + SoFar;
SoFar := '';
end;
end;
procedure SetupStartingColor;
begin
FgRead := True;
BgRead := True;
if FgColor <> '' then
SelAttributes.Color := GetIRCColor(StrToInt(FgColor), Font.Color);
if BgColor <> '' then
SetSelBgColor(GetIRCColor(StrToInt(BgColor), Color));
FgColor := '';
BgColor := '';
end;
begin
TotalText := '';
if not AAppend then
Clear;
SelStart := Length(Text);
SelAttributes.Style := [];
SelAttributes.Color := Font.Color;
SetSelBgColor(Color);
if AAppend and (Text <> '') then
begin
SelText := #13#10;
end;
Paragraph.LeftIndent := Paragraph.FirstIndent;
InColor := False;
SoFar := '';
FgColor := '';
BgColor := '';
FgRead := False;
BgRead := False;
CommaFound := False;
for I := 1 to Length(AText) do
begin
if AText[I] = IndentDelim then
begin
Paragraph.LeftIndent := Trunc(MainForm.Canvas.TextWidth(TotalText + SoFar) * 0.76);
end else if AText[I] = BoldChar then
begin
AddTextSoFar;
if fsBold in SelAttributes.Style then
SelAttributes.Style := SelAttributes.Style - [fsBold]
else
SelAttributes.Style := SelAttributes.Style + [fsBold];
end else if AText[I] = ItalicChar then
begin
AddTextSoFar;
if fsItalic in SelAttributes.Style then
SelAttributes.Style := SelAttributes.Style - [fsItalic]
else
SelAttributes.Style := SelAttributes.Style + [fsItalic];
end else if AText[I] = UnderlineChar then
begin
AddTextSoFar;
if fsUnderline in SelAttributes.Style then
SelAttributes.Style := SelAttributes.Style - [fsUnderline]
else
SelAttributes.Style := SelAttributes.Style + [fsUnderline];
end else if AText[I] = ClearChar then
begin
AddTextSoFar;
SelAttributes.Style := [];
SelAttributes.Color := Font.Color;
SetSelBgColor(Color);
end else if AText[I] = ColorChar then
begin
AddTextSoFar;
InColor := True;
FgColor := '';
BgColor := '';
FgRead := False;
BgRead := False;
CommaFound := False;
end else
begin
if InColor and (not FgRead or not BgRead) then
begin
if not FgRead then
begin
if AText[I] = ',' then
begin
FgRead := True;
CommaFound := True;
end else if StrToIntDef(AText[I], -1) = -1 then
begin
SetupStartingColor;
SoFar := SoFar + AText[I];
end else
begin
FgColor := FgColor + AText[I];
FgRead := Length(FgColor) >= 2;
end;
end else
begin
if AText[I] = ',' then
begin
CommaFound := True;
end else if StrToIntDef(AText[I], -1) = -1 then
begin
SetupStartingColor;
SoFar := SoFar + AText[I];
end else if CommaFound then
begin
BgColor := BgColor + AText[I];
BgRead := Length(BgColor) >= 2;
if BgRead then
SetupStartingColor;
end else
begin
SoFar := SoFar + AText[I];
end;
end;
end else
begin
FgColor := '';
BgColor := '';
SoFar := SoFar + AText[I];
end;
if (Length(SoFar) > 0) and (SoFar[Length(SoFar)] = IndentDelim) then
Delete(SoFar, Length(SoFar), 1);
end;
end;
AddTextSoFar;
SelAttributes.Style := [];
SelAttributes.Color := Font.Color;
SetSelBgColor(Color);
end;
procedure TIRCRichEdit.SetIRCText(const AText: string);
begin
DoSetIRCText(AText, False);
end;
end.
|
unit Security.Permission.Interfaces;
interface
Type
TPermissionNotifyEvent = procedure(aID: Int64; aCan: string; aName: string; var aError: string; var aChanged: boolean) of Object;
TResultNotifyEvent = procedure(const aResult: boolean = false) of Object;
Type
iPrivatePermissionEvents = interface
['{DCE42688-962D-4AA4-B719-7058C8714386}']
{ Strict private declarations }
{ Strict private declarations }
function getID: Int64;
procedure setID(const Value: Int64);
function getUpdatedAt: TDateTime;
procedure setUpdatedAt(const Value: TDateTime);
function getCan: string;
procedure setCan(const Value: string);
function getNamePermission: string;
procedure setNamePermission(const Value: string);
procedure setOnPermission(const Value: Security.Permission.Interfaces.TPermissionNotifyEvent);
function getOnPermission: Security.Permission.Interfaces.TPermissionNotifyEvent;
procedure setOnResult(const Value: Security.Permission.Interfaces.TResultNotifyEvent);
function getOnResult: Security.Permission.Interfaces.TResultNotifyEvent;
end;
iPermissionViewEvents = interface(iPrivatePermissionEvents)
['{9047BD6E-6181-49F0-95CD-123155EC0EA9}']
{ Public declarations }
property OnPermission: TPermissionNotifyEvent read getOnPermission write setOnPermission;
property OnResult: TResultNotifyEvent read getOnResult write setOnResult;
end;
iPrivatePermissionViewProperties = interface
['{DCE42688-962D-4AA4-B719-7058C8714386}']
{ 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;
iPermissionViewProperties = interface(iPrivatePermissionViewProperties)
['{9047BD6E-6181-49F0-95CD-123155EC0EA9}']
{ 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;
iPermissionView = interface
['{87FEC43E-4C47-47D7-92F6-E0B6A532E49D}']
// function Properties: iPermissionViewProperties;
function Events: iPermissionViewEvents;
end;
implementation
end.
|
unit julian;
(*@/// interface *)
interface
uses
(*$ifdef ver80 *)
winprocs,
wintypes,
(*$else *)
Windows,
(*$endif *)
Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, moon, main, consts, ah_tool;
type
(*@/// Tfrm_julian = class(TForm) *)
Tfrm_julian = class(TForm)
lbl_julian: TLabel;
edt_julian: TEdit;
grp_utc: TGroupBox;
lbl_utc: TLabel;
btn_now: TButton;
btn_ok: TButton;
btn_cancel: TButton;
procedure btn_nowClick(Sender: TObject);
procedure edt_julianChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
public
date: TDateTime;
procedure set_edit;
end;
(*@\\\*)
var
frm_julian: Tfrm_julian;
(*@\\\0000000B28*)
(*@/// implementation *)
implementation
{$R *.DFM}
(*$i moontool.inc *)
(*$i ah_def.inc *)
(*@/// procedure Tfrm_julian.btn_nowClick(Sender: TObject); *)
procedure Tfrm_julian.btn_nowClick(Sender: TObject);
begin
date:=now;
set_edit;
end;
(*@\\\*)
(*@/// procedure Tfrm_julian.set_edit; *)
procedure Tfrm_julian.set_edit;
begin
edt_julian.text:=FloatToStrF(Julian_date(date),ffFixed,12,5);
end;
(*@\\\000000030D*)
(*@/// procedure Tfrm_julian.edt_julianChange(Sender: TObject); *)
procedure Tfrm_julian.edt_julianChange(Sender: TObject);
var
j_date: extended;
valid: boolean;
begin
valid:=false;
try
j_date:=StrToFloat(edt_julian.text);
date:=Delphi_Date(j_date);
lbl_utc.caption:=date2string(date);
valid:=true;
except
end;
btn_ok.enabled:=valid;
if not valid then begin
date:=0;
lbl_utc.caption:=LoadStr(SInvalid);
end;
end;
(*@\\\0000000805*)
(*@/// procedure Tfrm_julian.FormCreate(Sender: TObject); *)
procedure Tfrm_julian.FormCreate(Sender: TObject);
begin
lbl_julian.caption:=loadStr(SJulianDate);
self.caption:=LoadStr(SSetJulian);
btn_now.caption:=LoadStr(SNow);
grp_utc.caption:=LoadStr(SUTC);
(*$ifdef delphi_ge_4 *)
btn_ok.caption:=SOKButton;
btn_cancel.caption:=SCancelButton;
(*$else *)
btn_ok.caption:=LoadStr(SOKButton);
btn_cancel.caption:=LoadStr(SCancelButton);
(*$endif *)
helpcontext:=hc_setjulian;
end;
(*@\\\0000000E1D*)
(*@/// procedure Tfrm_julian.FormShow(Sender: TObject); *)
procedure Tfrm_julian.FormShow(Sender: TObject);
begin
set_edit;
end;
(*@\\\*)
(*@\\\0000000B01*)
(*$ifndef ver80 *) (*$warnings off*) (*$endif *)
end.
(*@\\\000E000401000431000505000505*)
|
{ ***************************************************************************
Copyright (c) 2016-2020 Kike Pérez
Unit : Quick.DAO.QueryGenerator.MSAccess
Description : DAO MSAccess Query Generator
Author : Kike Pérez
Version : 1.0
Created : 22/06/2018
Modified : 31/03/2020
This file is part of QuickDAO: https://github.com/exilon/QuickDAO
***************************************************************************
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.DAO.QueryGenerator.MSAccess;
interface
{$i QuickDAO.inc}
uses
Classes,
SysUtils,
Quick.Commons,
Quick.DAO;
type
TMSAccessQueryGenerator = class(TDAOQueryGenerator,IDAOQueryGenerator)
public
function Name : string;
function CreateTable(const aTable : TDAOModel) : string;
function ExistsTable(aModel : TDAOModel) : string;
function ExistsColumn(aModel : TDAOModel; const aFieldName : string) : string;
function AddColumn(aModel : TDAOModel; aField : TDAOField) : string;
function SetPrimaryKey(aModel : TDAOModel) : string;
function CreateIndex(aModel : TDAOModel; aIndex : TDAOIndex) : string;
function Select(const aTableName, aFieldNames : string; aLimit : Integer; const aWhere : string; aOrderFields : string; aOrderAsc : Boolean) : string;
function Sum(const aTableName, aFieldName, aWhere: string): string;
function Count(const aTableName : string; const aWhere : string) : string;
function Add(const aTableName: string; const aFieldNames, aFieldValues : string) : string;
function AddOrUpdate(const aTableName: string; const aFieldNames, aFieldValues : string) : string;
function Update(const aTableName, aFieldPairs, aWhere : string) : string;
function Delete(const aTableName : string; const aWhere : string) : string;
function DateTimeToDBField(aDateTime : TDateTime) : string;
function DBFieldToDateTime(const aValue : string) : TDateTime;
end;
implementation
const
{$IFNDEF FPC}
DBDATATYPES : array of string = ['text(%d)','text','char(%d)','int','integer','bigint','decimal(%d,%d)','bit','date','time','datetime','datetime','datetime'];
{$ELSE}
DBDATATYPES : array[0..10] of string = ('text(%d)','text','char(%d)','int','integer','bigint','decimal(%d,%d)','bit','date','time','datetime','datetime','datetime');
{$ENDIF}
{ TMSSQLQueryGenerator }
function TMSAccessQueryGenerator.Add(const aTableName, aFieldNames, aFieldValues: string): string;
var
querytext : TStringList;
begin
querytext := TStringList.Create;
try
querytext.Add(Format('INSERT INTO [%s]',[aTableName]));
querytext.Add(Format('(%s)',[aFieldNames]));
querytext.Add(Format('VALUES(%s)',[aFieldValues]));
Result := querytext.Text;
finally
querytext.Free;
end;
end;
function TMSAccessQueryGenerator.AddColumn(aModel: TDAOModel; aField: TDAOField) : string;
var
datatype : string;
querytext : TStringList;
begin
querytext := TStringList.Create;
try
querytext.Add(Format('ALTER TABLE [%s]',[aModel.TableName]));
if aField.DataType = dtFloat then
begin
datatype := Format(DBDATATYPES[Integer(aField.DataType)],[aField.DataSize,aField.Precision])
end
else
begin
if aField.DataSize > 0 then datatype := Format(DBDATATYPES[Integer(aField.DataType)],[aField.DataSize])
else datatype := DBDATATYPES[Integer(aField.DataType)];
end;
querytext.Add(Format('ADD [%s] %s',[aField.Name,datatype]));
Result := querytext.Text;
finally
querytext.Free;
end;
end;
function TMSAccessQueryGenerator.CreateIndex(aModel: TDAOModel; aIndex: TDAOIndex) : string;
var
querytext : TStringList;
begin
Exit;
querytext := TStringList.Create;
try
querytext.Add(Format('IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = ''PK_%s'' AND object_id = OBJECT_ID(''%s''))',[aIndex.FieldNames[0],aModel.TableName]));
querytext.Add('BEGIN');
querytext.Add(Format('CREATE INDEX PK_%s ON [%s] (%s);',[aIndex.FieldNames[0],aModel.TableName,aIndex.FieldNames[0]]));
querytext.Add('END');
Result := querytext.Text;
finally
querytext.Free;
end;
end;
function TMSAccessQueryGenerator.CreateTable(const aTable: TDAOModel) : string;
var
field : TDAOField;
datatype : string;
querytext : TStringList;
begin
querytext := TStringList.Create;
try
//querytext.Add(Format('IF NOT EXISTS (SELECT Count(MSysObjects.Id) AS CountOfId FROM MSysObjects WHERE MSysObjects.Type IN (1,4,6) AND MSysObjects.name = ''%s'')',[aTable.TableName]));
//querytext.Add('BEGIN');
querytext.Add(Format('CREATE TABLE [%s] (',[aTable.TableName]));
for field in aTable.Fields do
begin
if field.DataType = dtFloat then
begin
datatype := Format(DBDATATYPES[Integer(field.DataType)],[field.DataSize,field.Precision])
end
else
begin
if field.DataSize > 0 then datatype := Format(DBDATATYPES[Integer(field.DataType)],[field.DataSize])
else datatype := DBDATATYPES[Integer(field.DataType)];
end;
if field.DataType = dtAutoID then querytext.Add(Format('[%s] %s IDENTITY(1,1),',[field.Name,datatype]))
else querytext.Add(Format('[%s] %s,',[field.Name,datatype]))
end;
if not aTable.PrimaryKey.Name.IsEmpty then
begin
querytext.Add(Format('PRIMARY KEY(%s)',[aTable.PrimaryKey.Name]));
end
else querytext[querytext.Count-1] := Copy(querytext[querytext.Count-1],1,querytext[querytext.Count-1].Length-1);
//querytext.Add('END');
Result := querytext.Text;
finally
querytext.Free;
end;
end;
function TMSAccessQueryGenerator.ExistsColumn(aModel: TDAOModel; const aFieldName: string) : string;
var
querytext : TStringList;
begin
querytext := TStringList.Create;
try
querytext.Add('SELECT Name FROM sys.columns');
querytext.Add(Format('WHERE object_id = OBJECT_ID(''%s'')',[aModel.TableName]));
Result := querytext.Text;
finally
querytext.Free;
end;
end;
function TMSAccessQueryGenerator.ExistsTable(aModel: TDAOModel): string;
var
querytext : TStringList;
begin
querytext := TStringList.Create;
try
querytext.Add('GRANT SELECT ON MSysObjects TO Admin;');
//querytext.Add(Format('SELECT name FROM MSysObjects WHERE MSysObjects.Type IN (1,4,6) AND MSysObjects.name = ''%s''',[aModel.TableName]));
Result := querytext.Text;
finally
querytext.Free;
end;
end;
function TMSAccessQueryGenerator.Name: string;
begin
Result := 'MSACCESS';
end;
function TMSAccessQueryGenerator.SetPrimaryKey(aModel: TDAOModel) : string;
var
querytext : TStringList;
begin
querytext := TStringList.Create;
try
//querytext.Add('IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS');
//querytext.Add(Format('WHERE CONSTRAINT_TYPE = ''PRIMARY KEY'' AND TABLE_NAME = ''%s'' AND TABLE_SCHEMA =''dbo'')',[aModel.TableName]));
//querytext.Add('BEGIN');
//querytext.Add(Format('ALTER TABLE [%s] ADD CONSTRAINT PK_%s PRIMARY KEY (%s)',[aModel.TableName,aModel.PrimaryKey,aModel.PrimaryKey]));
//querytext.Add('END');
Result := querytext.Text;
finally
querytext.Free;
end;
end;
function TMSAccessQueryGenerator.Sum(const aTableName, aFieldName, aWhere: string): string;
var
querytext : TStringList;
begin
querytext := TStringList.Create;
try
querytext.Add(Format('SELECT SUM (%s) FROM [%s] WHERE %s',[aTableName,aFieldName,aWhere]));
Result := querytext.Text;
finally
querytext.Free;
end;
end;
function TMSAccessQueryGenerator.Select(const aTableName, aFieldNames: string; aLimit: Integer;
const aWhere: string; aOrderFields: string; aOrderAsc: Boolean) : string;
var
orderdir : string;
querytext : TStringList;
toplimit : string;
begin
querytext := TStringList.Create;
try
//define limited query clause
if aLimit > 0 then toplimit := Format('TOP %d ',[aLimit])
else toplimit := '';
//define select-where clauses
if aFieldNames.IsEmpty then querytext.Add(Format('SELECT %s* FROM [%s] WHERE %s',[toplimit,aTableName,aWhere]))
else querytext.Add(Format('SELECT %s%s FROM [%s] WHERE %s',[toplimit,aFieldNames,aTableName,aWhere]));
//define orderby clause
if not aOrderFields.IsEmpty then
begin
if aOrderAsc then orderdir := 'ASC'
else orderdir := 'DESC';
querytext.Add(Format('ORDER BY %s %s',[aOrderFields,orderdir]));
end;
Result := querytext.Text;
finally
querytext.Free;
end;
end;
function TMSAccessQueryGenerator.AddOrUpdate(const aTableName: string; const aFieldNames, aFieldValues : string) : string;
var
querytext : TStringList;
begin
querytext := TStringList.Create;
try
querytext.Add(Format('INSERT OR REPLACE INTO [%s]',[aTableName]));
querytext.Add(Format('(%s)',[aFieldNames]));
querytext.Add(Format('VALUES(%s)',[aFieldValues]));
Result := querytext.Text;
finally
querytext.Free;
end;
end;
function TMSAccessQueryGenerator.Update(const aTableName, aFieldPairs, aWhere : string) : string;
var
querytext : TStringList;
begin
querytext := TStringList.Create;
try
querytext.Add(Format('UPDATE [%s]',[aTableName]));
querytext.Add(Format('SET %s',[aFieldPairs]));
querytext.Add(Format('WHERE %s',[aWhere]));
Result := querytext.Text;
finally
querytext.Free;
end;
end;
function TMSAccessQueryGenerator.Count(const aTableName : string; const aWhere : string) : string;
begin
Result := Format('SELECT COUNT(*) AS cnt FROM [%s] WHERE %s',[aTableName,aWhere]);
end;
function TMSAccessQueryGenerator.DateTimeToDBField(aDateTime: TDateTime): string;
begin
Result := FormatDateTime('YYYY/MM/DD hh:nn:ss',aDateTime);
end;
function TMSAccessQueryGenerator.DBFieldToDateTime(const aValue: string): TDateTime;
begin
Result := StrToDateTime(aValue);
end;
function TMSAccessQueryGenerator.Delete(const aTableName, aWhere: string) : string;
begin
Result := Format('SELECT COUNT(*) AS cnt FROM [%s] WHERE %s',[aTableName,aWhere]);
end;
end.
|
unit ncPRFrmPrintTipo;
{
ResourceString: Dario 13/03/13
}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uFrmComSombra, cxGraphics, cxControls, cxLookAndFeels,
cxLookAndFeelPainters, cxStyles, cxCustomData, cxFilter, cxData,
cxDataStorage, cxEdit, DB, cxDBData, cxImageComboBox, cxTextEdit, cxContainer,
Menus, kbmMemTable, cxClasses, StdCtrls, cxButtons, LMDPNGImage, ExtCtrls,
cxLabel, cxGridLevel, cxGridBandedTableView, cxGridDBBandedTableView,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGridCustomView,
cxGrid, LMDControl, LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel,
LMDSimplePanel, cxNavigator;
type
TFrmPrintTipo = class(TFrmComSombra)
LMDSimplePanel3: TLMDSimplePanel;
grid: TcxGrid;
tv: TcxGridDBTableView;
tvImg: TcxGridDBColumn;
tvDescr: TcxGridDBColumn;
tvID: TcxGridDBColumn;
tvDescr2: TcxGridDBColumn;
tv2: TcxGridDBBandedTableView;
tv2Img: TcxGridDBBandedColumn;
tv2Descr: TcxGridDBBandedColumn;
gl: TcxGridLevel;
lbTot: TcxLabel;
LMDSimplePanel1: TLMDSimplePanel;
Image2: TImage;
lbTitulo: TcxLabel;
btnCancelar: TcxButton;
btnContinuar: TcxButton;
cxStyleRepository1: TcxStyleRepository;
cxStyle1: TcxStyle;
cxStyle2: TcxStyle;
dsTipo: TDataSource;
mtTipo: TkbmMemTable;
mtTipoImg: TIntegerField;
mtTipoDescr: TStringField;
mtTipoDescr2: TStringField;
mtTipoID: TIntegerField;
mtTipoValor: TCurrencyField;
cxStyle3: TcxStyle;
procedure LMDSimplePanel3Enter(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure tvDescrCustomDrawCell(Sender: TcxCustomGridTableView;
ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo;
var ADone: Boolean);
procedure tvFocusedRecordChanged(Sender: TcxCustomGridTableView;
APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord;
ANewItemRecordFocusingChanged: Boolean);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure tvDblClick(Sender: TObject);
private
{ Private declarations }
FPaginas : Integer;
procedure RefreshTot;
public
function ObtemTipoImp(var aTipoImp: Integer; aPag: integer; aCancelar: Boolean): Boolean;
{ Public declarations }
end;
var
FrmPrintTipo: TFrmPrintTipo;
implementation
uses ncImgImp, ncTipoImp, ncClassesBase;
// START resource string wizard section
resourcestring
SPorPágina = ' por página';
SSelecionar = 'Selecionar';
SSair = 'Sair';
SPáginaS = ' página(s) = ';
// END resource string wizard section
{$R *.dfm}
procedure TFrmPrintTipo.FormClose(Sender: TObject; var Action: TCloseAction);
begin
inherited;
Action := caFree;
end;
procedure TFrmPrintTipo.FormCreate(Sender: TObject);
var i: integer;
begin
inherited;
dsTipo.Dataset := nil;
try
mtTipo.Active := True;
for i := 0 to gTiposImp.Count-1 do begin
mtTipo.Append;
mtTipoImg.Value := gTiposImp.Itens[i].ImgID;
mtTipoDescr.Value := gTiposImp.Itens[i].Nome;
mtTipoDescr2.Value := FloatToStrF(gTiposImp.Itens[i].Valor, ffCurrency, 10, 2) + SPorPágina;
mtTipoValor.Value := gTiposImp.Itens[i].Valor;
mtTipoID.Value := gTiposImp.Itens[i].ID;
mtTipo.Post;
end;
mtTipo.First;
finally
dsTipo.Dataset := mtTipo;
end;
end;
procedure TFrmPrintTipo.FormShow(Sender: TObject);
begin
inherited;
RefreshTot;
end;
procedure TFrmPrintTipo.LMDSimplePanel3Enter(Sender: TObject);
begin
inherited;
lbTot.Visible := True;
lbTitulo.Style.TextColor := $00404040;
btnContinuar.Enabled := True;
end;
function TFrmPrintTipo.ObtemTipoImp(var aTipoImp: Integer; aPag: Integer; aCancelar: Boolean): Boolean;
begin
if not aCancelar then begin
btnContinuar.Caption := SSelecionar;
btnCancelar.Caption := SSair;
btnCancelar.Width := 55;
end;
FPaginas := aPag;
mtTipo.Locate('ID', aTipoImp, []); // do not localize
if ShowModal=mrOk then begin
Result := True;
aTipoImp := mtTipoID.Value;
end else
Result := (ModalResult<>mrCancel);
end;
procedure TFrmPrintTipo.RefreshTot;
begin
lbTot.Caption := IntToStr(FPaginas)+ SPáginaS + FloatToStrF(mtTipoValor.Value * FPaginas, ffCurrency, 10, 2);
end;
procedure TFrmPrintTipo.tvDblClick(Sender: TObject);
begin
inherited;
if btnContinuar.Enabled then
btnContinuar.Click;
end;
procedure TFrmPrintTipo.tvDescrCustomDrawCell(Sender: TcxCustomGridTableView;
ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo;
var ADone: Boolean);
var R: TRect;
begin
R := AViewInfo.Bounds;
ACanvas.FillRect(AviewInfo.Bounds);
R.Bottom := R.Top + ((R.Bottom - R.Top) div 2);
ACanvas.DrawTexT(AViewInfo.Text, R, cxAlignLeft or cxShowEndEllipsis or cxAlignBottom);
ACanvas.Font.Style := [];
ACanvas.Font.Size := 8;
// ACanvas.Font.Color := clGray;
R.Top := R.Bottom + 1;
R.Bottom := AViewInfo.Bounds.Bottom;
ACanvas.DrawTexT(AViewInfo.GridRecord.Values[tvDescr2.Index], R, cxAlignLeft or cxShowEndEllipsis or cxAlignTop);
ADone := True;
end;
procedure TFrmPrintTipo.tvFocusedRecordChanged(Sender: TcxCustomGridTableView;
APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord;
ANewItemRecordFocusingChanged: Boolean);
begin
inherited;
RefreshTot;
end;
end.
|
unit ClassData;
interface
uses Controls, Classes, Windows, SysUtils;
type EDataError = class( Exception );
PZastavka = ^TZastavka;
PSpoj = ^TSpoj;
PRozvrhy = ^TRozvrhy;
PRozvrh = ^TRozvrh;
PMinuty = ^TMinuty;
PSpojInfo = ^TSpojInfo;
TBlizka = record
Min : integer;
Zast : PZastavka;
end;
TZastavka = record
Nazov : string;
Pasmo : byte;
NaZnamenie : boolean;
Spoje : TList;
BlizkeZast : array of TBlizka;
Cislo : integer;
Sur : TPoint;
end;
TStav = (Plus,Minus,Normal);
TSpoj = record
Cislo : integer;
Typ : byte;
{TYP
0 - autobus
1 - elektricka
2 - trolejbus
3 - nocak
}
Stav : TStav;
Rozvrhy : PRozvrhy;
NaZastavke : PZastavka;
Info : PSpojInfo;
Opacny : PSpoj;
Next, Prev : PSpoj;
NextMin : integer;
end;
TRozvrhy = record
Zvlast : boolean;
Rozvrh : array[0..3] of PRozvrh;
end;
TRozvrh = array[0..23] of PMinuty;
TMinuty = record
Stav : TStav;
Cas : byte;
Next : PMinuty;
end;
TSpojInfo = record
Zaciatok, Koniec : PZastavka;
Spoj, OpacnySpoj : PSpoj;
end;
TData = class
private
EsteNeplatne, UzNeplatne : TStringList;
FPeso : integer;
//DATA :
//pomocne procedury :
procedure SpracujRiadokP( S : string; var Pasmo : byte; var Nazov : string );
procedure SpracujRiadokO( S : string; var Offset : byte; var Nazov : string );
procedure DealokujRozvrhy( Rozvrhy : PRozvrhy );
procedure DataNacitajSubory;
procedure SpravZoznamZastavok;
procedure NacitajZastavky( Subor : string );
procedure ZoradZastavky;
procedure PriradZastavkeRozvrh;
procedure NacitajRozvrh( Subor : string );
function CisloZastavky( Zastavka : string ) : word;
procedure PriradRozvrh( PNewRozvrhy : PRozvrhy; OldRozvrhy : TRozvrhy; Offset : word; Spoj : PSpoj );
procedure UpravSpojeInfo;
procedure DataPriradZastavkamSur;
procedure VypisNeplatne;
procedure SetPeso( Value : integer );
public
//Data :
Zastavky : TList;
SpojeInfo : TList;
ZoznamSpojov : TList;
constructor Create;
destructor Destroy; override;
property Peso : integer read FPeso write SetPeso;
end;
var Data : TData;
implementation
uses Graphics, Dialogs, Konstanty;
//==============================================================================
//==============================================================================
//
// Constructor
//
//==============================================================================
//==============================================================================
constructor TData.Create;
begin
inherited Create;
Zastavky := TList.Create;
SpojeInfo := TList.Create;
ZoznamSpojov := TList.Create;
EsteNeplatne := TStringList.Create;
UzNeplatne := TStringList.Create;
try
//DATA :
DataNacitajSubory;
DataPriradZastavkamSur;
except
end;
VypisNeplatne;
EsteNeplatne.Free;
UzNeplatne.Free;
end;
//==============================================================================
//==============================================================================
//
// Destructor
//
//==============================================================================
//==============================================================================
procedure TData.DealokujRozvrhy( Rozvrhy : PRozvrhy );
var I, J : integer;
P1, P2 : PMinuty;
begin
for I := 0 to 2 do
begin
for J := 0 to 23 do
begin
P1 := Rozvrhy.Rozvrh[I]^[J];
while P1 <> nil do
begin
P2 := P1^.Next;
Dispose( P1 );
P1 := P2;
end;
end;
Dispose( PRozvrh( Rozvrhy.Rozvrh[I] ) );
end;
end;
destructor TData.Destroy;
var I,J : integer;
begin
//ROZVRHY :
for I := 0 to Zastavky.Count-1 do
begin
for J := 0 to TZastavka( Zastavky[I]^ ).Spoje.Count-1 do
begin
DealokujRozvrhy( PRozvrhy( TSpoj( TZastavka( Zastavky[I]^ ).Spoje[J]^ ).Rozvrhy ) );
Dispose( PSpoj( TZastavka( Zastavky[I]^ ).Spoje[J] ) );
end;
TZastavka( Zastavky[I]^ ).Spoje.Free;
SetLength( TZastavka( Zastavky[I]^ ).BlizkeZast , 0 );
Dispose( PZastavka( Zastavky[I] ) );
end;
Zastavky.Free;
for I := 0 to SpojeInfo.Count-1 do
Dispose( PSpojInfo( SpojeInfo[I] ) );
SpojeInfo.Free;
ZoznamSpojov.Free;
inherited;
end;
//==============================================================================
//==============================================================================
//
// Pomocne procedury
//
//==============================================================================
//==============================================================================
//==============================================================================
//==============================================================================
//
// D A T A
//
//==============================================================================
//==============================================================================
//==============================================================================
// Pomocne procedury
//==============================================================================
procedure TData.SpracujRiadokP( S : string; var Pasmo : byte; var Nazov : string );
var I : integer;
PomS : string;
begin
Pasmo := 0;
Nazov := '';
if S = '' then exit;
I := 1;
while S[I] <> ' ' do
Inc( I );
Inc( I );
PomS := '';
while S[I] <> ' ' do
begin
PomS := PomS + S[I];
Inc( I );
end;
Pasmo := StrToInt( PomS );
Inc( I );
while I <= Length( S ) do
begin
Nazov := Nazov + S[I];
Inc( I );
end;
end;
procedure TData.SpracujRiadokO( S : string; var Offset : byte; var Nazov : string );
var I : integer;
PomS : string;
begin
Nazov := '';
if S = '' then exit;
I := 1;
PomS := '';
while S[I] <> ' ' do
begin
PomS := PomS + S[I];
Inc( I );
end;
Offset := StrToInt( PomS );
Inc( I );
while S[I] <> ' ' do
Inc( I );
Inc( I );
while I <= Length( S ) do
begin
Nazov := Nazov + S[I];
Inc( I );
end;
end;
//==============================================================================
// Zoznam zastavok
//==============================================================================
procedure TData.NacitajZastavky( Subor : string );
var Fin : TextFile;
PlatnyOd, PlatnyDo, DatumDnes : string;
Den, Mes, Rok : word;
DenDnes, MesDnes, RokDnes : word;
PNovaZastavka : PZastavka;
CisloSpoja : string;
Nazov : string;
Pasmo : byte;
S : string;
I : integer;
begin
AssignFile( Fin , Subor );
{$I-}
Reset( Fin );
{$I+}
if IOResult <> 0 then
raise EDataError.Create( 'Nedá sa otvoriť datový súbor '+Subor+' !' );
Readln( Fin , CisloSpoja );
Readln( Fin , S );
//Aktualny datum :
DateTimeToString( DatumDnes , 'ddmmyyyy' , Date );
DenDnes := StrToInt( Copy( DatumDnes , 1 , 2 ) );
MesDnes := StrToInt( Copy( DatumDnes , 3 , 2 ) );
RokDnes := StrToInt( Copy( DatumDnes , 5 , 4 ) );
//Platnost od :
Readln( Fin , PlatnyOd );
Den := StrToInt( Copy( PlatnyOd , 1 , 2 ) );
Mes := StrToInt( Copy( PlatnyOd , 4 , 2 ) );
Rok := StrToInt( Copy( PlatnyOd , 7 , 4 ) );
if (RokDnes < Rok) or
((RokDnes = Rok) and
((MesDnes < Mes) or
((MesDnes = Mes) and
(DenDnes < Den)))) then
EsteNeplatne.Add( CisloSpoja );
//Platnost do :
Readln( Fin , PlatnyDo );
Den := StrToInt( Copy( PlatnyDo , 1 , 2 ) );
Mes := StrToInt( Copy( PlatnyDo , 4 , 2 ) );
Rok := StrToInt( Copy( PlatnyDo , 7 , 4 ) );
if (RokDnes > Rok) or
((RokDnes = Rok) and
((MesDnes > Mes) or
((MesDnes = Mes) and
(DenDnes > Den)))) then
UzNeplatne.Add( CisloSpoja );
Readln( Fin , S );
SpracujRiadokP( S , Pasmo , Nazov );
repeat
try
New( PNovaZastavka );
Zastavky.Add( PNovaZastavka );
except
raise EDataError.Create( 'Nedostatok pamäte !' );
end;
Delete( Nazov , Pos( '+' , Nazov ) , 1 ) ;
I := Pos( '-' , Nazov );
if (I > 0) and
(I < 3) then
Delete( Nazov , I , 1 ) ;
if Nazov[1] = 'z' then
begin
Delete( Nazov , 1 , 1 );
PNovaZastavka^.NaZnamenie := True;
end
else
PNovaZastavka^.NaZnamenie := False;
PNovaZastavka^.Nazov := Nazov;
PNovaZastavka^.Pasmo := Pasmo;
PNovaZastavka^.Sur.X := 0;
PNovaZastavka^.Sur.Y := 0;
Readln( Fin , S );
SpracujRiadokP( S , Pasmo , Nazov );
until Nazov = 'KONIEC';
CloseFile( Fin );
end;
function Porovnaj( P1, P2 : pointer ) : integer;
var S1, S2 : string;
begin
S1 := string( P1^ );
S2 := string( P2^ );
Result := 0;
if S1 = S2 then
exit;
if S1 < S2 then Result := -1;
if S1 > S2 then Result := 1;
end;
procedure TData.ZoradZastavky;
var I : integer;
begin
Zastavky.Sort( Porovnaj );
for I := 1 to Zastavky.Count-1 do
if (TZastavka( Zastavky[I-1]^ ).Nazov = TZastavka( Zastavky[I]^ ).Nazov) then
begin
Dispose( PZastavka( Zastavky[I-1] ) );
Zastavky[I-1] := nil;
end;
Zastavky.Pack;
for I := 0 to Zastavky.Count-1 do
TZastavka( Zastavky[I]^ ).Cislo := I;
end;
procedure TData.SpravZoznamZastavok;
var SR : TSearchRec;
I : integer;
begin
FindFirst( ROZVRHY_DIR+'\*.mhd' , faAnyFile , SR );
NacitajZastavky( ROZVRHY_DIR+'\'+SR.Name );
while FindNext( SR ) = 0 do
NacitajZastavky( ROZVRHY_DIR+'\'+SR.Name );
FindClose( SR );
ZoradZastavky;
for I := 0 to Zastavky.Count-1 do
TZastavka( Zastavky[I]^ ).Spoje := TList.Create;
end;
//==============================================================================
// Priradenie rozvrhov
//==============================================================================
function TData.CisloZastavky( Zastavka : string ) : word;
var I, J, K : integer;
begin
I := -1;
J := Zastavky.Count;
K := (I+J) div 2;
while TZastavka( Zastavky[K]^ ).Nazov <> Zastavka do
begin
if TZastavka( Zastavky[K]^ ).Nazov > Zastavka then J := K
else I := K;
K := (I+J) div 2;
end;
Result := K;
end;
procedure TData.PriradRozvrh( PNewRozvrhy : PRozvrhy; OldRozvrhy : TRozvrhy; Offset : word; Spoj : PSpoj );
var I, J : integer;
P1 : array[0..23] of PMinuty;
PFrom : PMinuty;
OldTime, NewTime : integer;
NewHour : integer;
begin
for I := 0 to 3 do
begin
New( PNewRozvrhy.Rozvrh[I] );
for J := 0 to 23 do
PNewRozvrhy.Rozvrh[I]^[J] := nil;
end;
for I := 0 to 2 do
begin
for J := 0 to 23 do P1[J] := nil;
for J := 0 to 23 do
begin
PFrom := OldRozvrhy.Rozvrh[I]^[J];
while PFrom <> nil do
begin
OldTime := PFrom^.Cas;
NewTime := OldTime + Offset;
NewHour := J+(NewTime div 60);
if NewHour > 23 then break;
if (Spoj^.Stav = Normal) or
((Spoj^.Stav = Plus) and
(PFrom^.Stav = Plus)) or
((Spoj^.Stav = Minus) and
(PFrom^.Stav <> Minus)) then
begin
if P1[NewHour] = nil then
begin
New( PNewRozvrhy.Rozvrh[I]^[NewHour] );
P1[NewHour] := PNewRozvrhy.Rozvrh[I]^[NewHour];
end
else
begin
New( P1[NewHour]^.Next );
P1[NewHour] := P1[NewHour]^.Next;
end;
P1[NewHour]^.Cas := NewTime-((NewTime div 60)*60);
P1[NewHour]^.Next := nil;
P1[NewHour]^.Stav := PFrom^.Stav;
end;
PFrom := PFrom^.Next;
end;
end;
end;
end;
procedure TData.NacitajRozvrh( Subor : string );
var CisloSpoja : byte;
TypSpoja : char;
Nazov : string;
Off : byte;
Zoznam : array[1..100] of
record
Stav : TStav;
Cislo : word;
Offset : byte;
end;
Pocet : byte;
Rozvrhy : TRozvrhy;
PNewMinuty, P1 : PMinuty;
PNewSpoj : PSpoj;
PNewRozvrhy : PRozvrhy;
Dalsi : PSpoj;
PNewSpojInfo : PSpojInfo;
I, J, K, N : integer;
S : string;
function NacitajMinuty : PMinuty;
var c : char;
S : string;
begin
Result := nil;
Read( c );
while (c = ' ') and
(not EoLn( Input )) do
Read( c );
if EoLn( Input ) then
begin
readln;
exit;
end;
S := c;
repeat
Read( c );
if c <> ' ' then S := S + c;
until (c = ' ') or
(EoLn( Input ));
if EoLn( Input ) then readln;
if S = '-1' then exit;
New( Result );
c := S[Length(S)];
case c of
'+' : begin
Result^.Stav := Plus;
Delete( S , Length(S) , 1 );
end;
'-' : begin
Result^.Stav := Minus;
Delete( S , Length(S) , 1 );
end;
else Result^.Stav := Normal;
end;
Result^.Cas := StrToInt( S );
Result^.Next := nil;
end;
begin
AssignFile( Input , Subor );
{$I-}
Reset( Input );
{$I+}
if IOResult <> 0 then
raise EDataError.Create( 'Nedá sa otvoriť datový súbor '+Subor+' !' );
Readln( CisloSpoja );
Readln( TypSpoja );
// Vytvorenie zoznamu zastavok :
Readln;
Readln;
Pocet := 0;
Off := 0;
Readln( S );
SpracujRiadokO( S , Off , Nazov );
repeat
Inc( Pocet );
Zoznam[ Pocet ].Stav := Normal;
if Pos( '+' , Nazov ) > 0 then
begin
Delete( Nazov , Pos( '+' , Nazov ) , 1 );
Zoznam[ Pocet ].Stav := Plus;
end
else
begin
I := Pos( '-' , Nazov );
if (I > 0) and
(I < 3) then
begin
Delete( Nazov , I , 1 );
Zoznam[ Pocet ].Stav := Minus;
end;
end;
if Nazov[1] = 'z' then Delete( Nazov , 1 , 1 );
Zoznam[ Pocet ].Cislo := CisloZastavky( Nazov );
Zoznam[ Pocet ].Offset := Off;
Readln( S );
SpracujRiadokO( S , Off , Nazov );
until Nazov = 'KONIEC';
Readln( N );
// Nacitanie zakladneho rozvrhu :
for K := 0 to N-1 do
begin
New( PRozvrh( Rozvrhy.Rozvrh[K] ) );
for I := 0 to 23 do
begin
Rozvrhy.Rozvrh[K]^[I] := nil;
PNewMinuty := NacitajMinuty;
if PNewMinuty = nil then continue;
Rozvrhy.Rozvrh[K]^[I] := PNewMinuty;
P1 := Rozvrhy.Rozvrh[K]^[I];
repeat
PNewMinuty := NacitajMinuty;
P1^.Next := PNewMinuty;
P1 := PNewMinuty;
until P1 = nil;
end;
end;
// Vytvorenie noveho spoja :
Dalsi := nil;
for I := Pocet downto 1 do
begin
New( PNewSpoj );
if (Dalsi <> nil) then Dalsi^.Prev := PNewSpoj;
if I = 1 then
begin
New( PNewSpojInfo );
SpojeInfo.Add( PNewSpojInfo );
PNewSpojInfo^.Spoj := PNewSpoj;
PNewSpojInfo^.OpacnySpoj := nil;
PNewSpojInfo^.Zaciatok := Zastavky[ Zoznam[1].Cislo ];
PNewSpojInfo^.Koniec := Zastavky[ Zoznam[Pocet].Cislo ];
end;
with TZastavka( Zastavky[ Zoznam[I].Cislo ]^ ) do
begin
PNewSpoj^.Cislo := CisloSpoja;
PNewSpoj^.Opacny := nil;
K := -1;
for J := 0 to Spoje.Count-1 do
if TSpoj( Spoje[J]^ ).Cislo = PNewSpoj^.Cislo then
begin
if (TSpoj( Spoje[J]^ ).Opacny <> nil) then break;
K := 0;
TSpoj( Spoje[J]^ ).Opacny := PNewSpoj;
PNewSpoj^.Opacny := PSpoj( Spoje[J] );
break;
end;
if K = -1 then Spoje.Add( PNewSpoj );
with PNewSpoj^ do
begin
Cislo := CisloSpoja;
case TypSpoja of
'A' : Typ := 0;
'E' : Typ := 1;
'T' : Typ := 2;
'N' : Typ := 3;
end;
Stav := Zoznam[I].Stav;
Info := nil;
New( PNewRozvrhy );
Rozvrhy := PNewRozvrhy;
Next := Dalsi;
Prev := nil;
NaZastavke := PZastavka( Zastavky[ Zoznam[I].Cislo ] );
Dalsi := PNewSpoj;
end;
end;
if I < Pocet then
PNewSpoj^.NextMin := Zoznam[I+1].Offset-Zoznam[I].Offset
else
PNewSpoj^.NextMin := 0;
PriradRozvrh( PNewRozvrhy , Rozvrhy , Zoznam[I].Offset , PNewSpoj );
end;
// Dealokacia :
DealokujRozvrhy( @Rozvrhy );
CloseFile( Input );
end;
procedure TData.PriradZastavkeRozvrh;
var SR : TSearchRec;
begin
FindFirst( ROZVRHY_DIR+'\*.mhd' , faAnyFile , SR );
repeat
NacitajRozvrh( ROZVRHY_DIR+'\'+SR.Name );
until FindNext( SR ) <> 0;
end;
//==============================================================================
// Upravenie informácii o spojoch
//==============================================================================
function PorovnajSpojeInfo( P1 , P2 : pointer ) : integer;
begin
Result := 0;
if TSpojInfo( P1^ ).Spoj^.Cislo < TSpojInfo( P2^ ).Spoj^.Cislo then Result := -1;
if TSpojInfo( P1^ ).Spoj^.Cislo > TSpojInfo( P2^ ).Spoj^.Cislo then Result := 1;
end;
procedure TData.UpravSpojeInfo;
var I, J : integer;
Spoj : PSpoj;
PNewInfo : PSpojInfo;
begin
SpojeInfo.Sort( PorovnajSpojeInfo );
for I := 1 to SpojeInfo.Count-1 do
if TSpojInfo( SpojeInfo[I-1]^ ).Spoj^.Cislo = TSpojInfo( SpojeInfo[I]^ ).Spoj^.Cislo then
begin
TSpojInfo( SpojeInfo[I]^ ).OpacnySpoj := TSpojInfo( SpojeInfo[I-1]^ ).Spoj;
Dispose( PSpojInfo( SpojeInfo[I-1] ) );
SpojeInfo[I-1] := nil;
end;
SpojeInfo.Pack;
ZoznamSpojov.Clear;
J := SpojeInfo.Count-1;
for I := 0 to J do
begin
ZoznamSpojov.Add( SpojeInfo[I] );
Spoj := TSpojInfo( SpojeInfo[I]^ ).Spoj;
while Spoj <> nil do
begin
Spoj^.Info := PSpojInfo( SpojeInfo[I] );
Spoj := Spoj^.Next;
end;
New( PNewInfo );
SpojeInfo.Add( PNewInfo );
with PNewInfo^ do
begin
Zaciatok := PSpojInfo( SpojeInfo[I] )^.Koniec;
Koniec := PSpojInfo( SpojeInfo[I] )^.Zaciatok;
Spoj := TSpojInfo( SpojeInfo[I]^ ).OpacnySpoj;
OpacnySpoj := TSpojInfo( SpojeInfo[I]^ ).Spoj;
end;
Spoj := TSpojInfo( SpojeInfo[I]^ ).OpacnySpoj;
while Spoj <> nil do
begin
Spoj^.Info := PNewInfo;
Spoj := Spoj^.Next;
end;
end;
end;
//==============================================================================
// Nacitanie datovych suborov
//==============================================================================
procedure TData.DataNacitajSubory;
var SR : TSearchRec;
begin
if FindFirst( ROZVRHY_DIR+'\*.mhd' , faAnyFile , SR ) <> 0 then
raise EDataError.Create( 'Nebol nájdený žiadny datový súbor!' );
FindClose( SR );
SpravZoznamZastavok;
PriradZastavkeRozvrh;
UpravSpojeInfo;
end;
//==============================================================================
// Prirad zastavkam suradnice
//==============================================================================
procedure TData.DataPriradZastavkamSur;
var I : integer;
Nazov : string;
Suradnice : TPoint;
begin
AssignFile( Input , ZASTAVKY_FILE );
{$I-}
Reset( Input );
{$I+}
if IOResult <> 0 then exit;
I := 0;
while not EoF( Input ) do
begin
Readln( Nazov );
Readln( Suradnice.X );
Readln( Suradnice.Y );
if (Nazov > TZastavka( Zastavky[I]^ ).Nazov) then
while (I < Zastavky.Count-1) and
(Nazov > TZastavka( Zastavky[I]^ ).Nazov) do
Inc( I );
if (Nazov = TZastavka( Zastavky[I]^ ).Nazov) then
begin
TZastavka( Zastavky[I]^ ).Sur := Suradnice;
if I < Zastavky.Count-1 then Inc( I );
end;
end;
CloseFile( Input );
end;
//==============================================================================
// Properties
//==============================================================================
procedure TData.SetPeso( Value : integer );
var I : integer;
Spravene : array of boolean;
Pixle : integer;
procedure SirSa( Cislo : integer );
var I : integer;
d : real;
begin
Spravene[ Cislo ] := True;
for I := 0 to Zastavky.Count-1 do
begin
d := Round( Sqrt( Sqr( TZastavka( Zastavky[I]^ ).Sur.X - TZastavka( Zastavky[Cislo]^ ).Sur.X ) +
Sqr( TZastavka( Zastavky[I]^ ).Sur.Y - TZastavka( Zastavky[Cislo]^ ).Sur.Y ) ) );
if (not Spravene[I]) and
(d <= Pixle) then
begin
SetLength( TZastavka( Zastavky[I]^ ).BlizkeZast , Length( TZastavka( Zastavky[I]^ ).BlizkeZast )+1 );
TZastavka( Zastavky[I]^ ).BlizkeZast[ Length( TZastavka( Zastavky[I]^ ).BlizkeZast )-1 ].Zast := Zastavky[ Cislo ];
TZastavka( Zastavky[I]^ ).BlizkeZast[ Length( TZastavka( Zastavky[I]^ ).BlizkeZast )-1 ].Min := Round( d / (10*Pixle*SPEED) );
SetLength( TZastavka( Zastavky[Cislo]^ ).BlizkeZast , Length( TZastavka( Zastavky[Cislo]^ ).BlizkeZast )+1 );
TZastavka( Zastavky[Cislo]^ ).BlizkeZast[ Length( TZastavka( Zastavky[Cislo]^ ).BlizkeZast )-1 ].Zast := Zastavky[ I ];
TZastavka( Zastavky[Cislo]^ ).BlizkeZast[ Length( TZastavka( Zastavky[Cislo]^ ).BlizkeZast )-1 ].Min := Round( d / (10*Pixle*SPEED) );
SirSa( I );
end;
end;
end;
begin
if (Value = FPeso) then exit;
FPeso := Value;
Pixle := Round( (HEKTOMETER/100)*FPeso );
SetLength( Spravene , Zastavky.Count );
for I := 0 to Length( Spravene )-1 do
begin
Spravene[I] := False;
SetLength( TZastavka( Zastavky[I]^ ).BlizkeZast , 0 );
end;
if FPeso = 0 then exit;
for I := 0 to Length( Spravene )-1 do
if not Spravene[I] then SirSa( I );
end;
//==============================================================================
//==============================================================================
//
// Neplatne
//
//==============================================================================
//==============================================================================
procedure TData.VypisNeplatne;
var I : integer;
S : string;
begin
S := '';
for I := 0 to EsteNeplatne.Count-1 do
begin
S := S + EstenePlatne[I];
if I < EsteNeplatne.Count-1 then S := S+', ';
end;
if EsteNeplatne.Count > 0 then
MessageDlg( 'Rozvrhy týchto spojov sú ešte neplatné : '+S , mtWarning , [mbOk] , 0 );
S := '';
for I := 0 to UzNeplatne.Count-1 do
begin
S := S + UzNeplatne[I];
if I < UzNeplatne.Count-1 then S := S+', ';
end;
if UzNeplatne.Count > 0 then
MessageDlg( 'Rozvrhy týchto spojov sú už neplatné : '+S , mtWarning , [mbOk] , 0 );
end;
end.
|
unit LuaScriptEngine;
interface
uses
SysUtils, Classes, Lua, pLua, LuaWrapper;
type
TScriptModule = class(TDataModule)
procedure DataModuleCreate(Sender: TObject);
private
procedure LoadLibs(LuaWrapper : TLua);
procedure ScriptExceptionHandler( Title: ansistring; Line: Integer; Msg: ansistring;
var handled : Boolean);
public
Lua : TLua;
procedure Execute(Source : AnsiString);
end;
var
ScriptModule: TScriptModule;
implementation
{$R *.dfm}
procedure TScriptEngine.DataModuleCreate(Sender: TObject);
begin
Lua := TLua.Create(self);
Lua.LibName := 'Script';
Lua.OnLoadLibs := @LoadLibs;
Lua.OnException := @ScriptExceptionHandler;
end;
procedure TScriptEngine.LoadLibs(LuaWrapper : TLua);
begin
LuaWrapper.RegisterLuaMethod('Clear', @lua_Clear);
LuaWrapper.RegisterLuaMethod('print', @lua_print);
LuaWrapper.RegisterLuaMethod('HexToInt', @lua_HexToInt);
LuaWrapper.RegisterLuaMethod('SetCanvasSize', @lua_SetCanvasSize);
RegisterTurtle(LuaWrapper);
end;
procedure TScriptEngine.ScriptExceptionHandler(Title: ansistring;
Line: Integer; Msg: ansistring; var handled: Boolean);
begin
Handled := true;
frmMain.memOutput.Lines.Add(format('%s (%d): %s', [Title, Line, msg]));
end;
procedure TScriptEngine.Execute(Source: AnsiString);
begin
TurtleCanvas := Canvas;
Lua.LoadScript(Source);
Lua.Execute;
end;
initialization
end.
|
unit BCEditor.Editor.Search.Highlighter;
interface
uses
Classes, Graphics, BCEditor.Editor.Search.Highlighter.Colors, BCEditor.Types;
type
TBCEditorSearchHighlighter = class(TPersistent)
strict private
FAlphaBlending: Byte;
FColors: TBCEditorSearchColors;
FOnChange: TBCEditorSearchChangeEvent;
procedure SetAlphaBlending(const Value: Byte);
procedure SetColors(const Value: TBCEditorSearchColors);
procedure DoChange;
procedure SetOnChange(Value: TBCEditorSearchChangeEvent);
public
constructor Create;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
published
property AlphaBlending: Byte read FAlphaBlending write SetAlphaBlending default 255;
property Colors: TBCEditorSearchColors read FColors write SetColors;
property OnChange: TBCEditorSearchChangeEvent read FOnChange write SetOnChange;
end;
implementation
{ TBCEditorSearchHighlighter }
constructor TBCEditorSearchHighlighter.Create;
begin
inherited;
FAlphaBlending := 255;
FColors := TBCEditorSearchColors.Create;
end;
destructor TBCEditorSearchHighlighter.Destroy;
begin
FColors.Free;
inherited;
end;
procedure TBCEditorSearchHighlighter.Assign(Source: TPersistent);
begin
if Assigned(Source) and (Source is TBCEditorSearchHighlighter) then
with Source as TBCEditorSearchHighlighter do
begin
Self.FAlphaBlending := FAlphaBlending;
Self.FColors.Assign(Colors);
Self.DoChange;
end
else
inherited Assign(Source);
end;
procedure TBCEditorSearchHighlighter.DoChange;
begin
if Assigned(FOnChange) then
FOnChange(scRefresh);
end;
procedure TBCEditorSearchHighlighter.SetOnChange(Value: TBCEditorSearchChangeEvent);
begin
FOnChange := Value;
FColors.OnChange := FOnChange;
end;
procedure TBCEditorSearchHighlighter.SetColors(const Value: TBCEditorSearchColors);
begin
FColors.Assign(Value);
end;
procedure TBCEditorSearchHighlighter.SetAlphaBlending(const Value: Byte);
begin
if Value <> FAlphaBlending then
begin
FAlphaBlending := Value;
DoChange;
end;
end;
end.
|
unit Contatos2.model.conexao;
interface
uses
contatos2.model.interfaces, FireDAC.Comp.Client, FireDAC.Stan.def, FireDAC.Phys.MSAccDef, FireDAC.Phys,
FireDAC.Phys.ODBCBase, FireDAC.Phys.MSAcc, FireDAC.dapt, FireDAC.UI.Intf,
FireDAC.FMXUI.Wait, FireDAC.Comp.UI, FireDAC.Stan.Async;
Type
TConexao = Class(TInterfacedObject, iconexao)
Private
fConexao : tfdconnection;
class var FCon : iconexao;
Public
Constructor Create;
Destructor Destroy; Override;
Class function New: iconexao;
Function conexao: tfdconnection;
End;
implementation
uses
System.SysUtils;
{ TConexao }
function TConexao.conexao: tfdconnection;
begin
Result:= Fconexao;
end;
constructor TConexao.Create;
begin
Fconexao := TFDConnection.Create(nil);
fconexao.DriverName:= 'MSAcc';
Fconexao.Params.Database:= ExtractFilePath(paramstr(0))+'bd\contatos.mdb';
fconexao.LoginPrompt:= false;
fConexao.Open;
end;
destructor TConexao.Destroy;
begin
FreeAndNil(Fconexao);
inherited;
end;
class function TConexao.New: iconexao;
begin
if not Assigned(fcon) then
fcon := self.Create;
Result := Fcon;
end;
end.
|
unit Tests.TCommand;
interface
uses
DUnitX.TestFramework,
System.Classes,
System.SysUtils,
System.Generics.Collections,
Pattern.Command;
{$M+}
type
[TestFixture]
TestCommnd_Basic = class(TObject)
strict private
FOwnerComponent: TComponent;
public
[Setup]
procedure Setup;
[TearDown]
procedure TearDown;
published
procedure Test_ExecuteCommandAndCheckActive;
procedure Test_NotExecuteCommand_CounterZero;
procedure Test_ExecuteCommand2x;
end;
[TestFixture]
TestCommnd_StrigsCommand = class(TObject)
private
FOwnerComponent: TComponent;
FStrings: TStringList;
public
[Setup]
procedure Setup;
[TearDown]
procedure TearDown;
published
procedure NoGuardAssert_WithProperInjection;
procedure ChangeStringList_AfterExecute;
procedure GuardException_NoInjection;
end;
[TestFixture]
TestCommnd_Advanced = class(TObject)
private
FComponent: TComponent;
FStringPrime: TStringList;
FStringNonPrime: TStringList;
FMemStream: TMemoryStream;
FList: TList<Integer>;
public
[Setup]
procedure Setup;
[TearDown]
procedure TearDown;
published
procedure Execute_TestPrimes;
procedure Execute_TestNonPrimes;
procedure Execute_TestStream;
procedure Execute_ProcessOnlyPrimes;
end;
implementation
// ------------------------------------------------------------------------
// Test Basic Command - TCommandA
// ------------------------------------------------------------------------
type
TCommandA = class(TCommand)
strict private
FActive: boolean;
FCount: Integer;
strict protected
procedure DoExecute; override;
public
property Active: boolean read FActive write FActive;
property Count: Integer read FCount write FCount;
end;
procedure TCommandA.DoExecute;
begin
Active := True;
Count := Count + 1;
end;
// ------------------------------------------------------------------------
procedure TestCommnd_Basic.Setup;
begin
FOwnerComponent := TComponent.Create(nil);
end;
procedure TestCommnd_Basic.TearDown;
begin
FOwnerComponent.Free;
end;
procedure TestCommnd_Basic.Test_ExecuteCommandAndCheckActive;
var
CommandA: TCommandA;
begin
CommandA := TCommandA.Create(FOwnerComponent);
CommandA.Execute;
Assert.IsTrue(CommandA.Active, 'TCommanndA.Active property expected True');
Assert.AreEqual(1, CommandA.Count);
end;
procedure TestCommnd_Basic.Test_NotExecuteCommand_CounterZero;
var
CommandA: TCommandA;
begin
CommandA := TCommandA.Create(FOwnerComponent);
Assert.AreEqual(0, CommandA.Count);
end;
procedure TestCommnd_Basic.Test_ExecuteCommand2x;
var
CommandA: TCommandA;
begin
CommandA := TCommandA.Create(FOwnerComponent);
CommandA.Execute;
CommandA.Execute;
Assert.AreEqual(2, CommandA.Count);
end;
// ------------------------------------------------------------------------
// TestCommndFactory_StrigListCommand
// ------------------------------------------------------------------------
type
TCommandStringList = class(TCommand)
strict private
FCount: Integer;
FLines: TStringList;
strict protected
procedure DoGuard; override;
procedure DoExecute; override;
public
property Count: Integer read FCount write FCount;
published
property Lines: TStringList read FLines write FLines;
end;
{$REGION 'implementation TCommandStringList'}
procedure TCommandStringList.DoGuard;
begin
System.Assert(Lines <> nil);
end;
procedure TCommandStringList.DoExecute;
begin
inherited;
Count := Count + 1;
Lines.Add(Format('%.3d', [Count]));
end;
{$ENDREGION}
procedure TestCommnd_StrigsCommand.Setup;
begin
FOwnerComponent := TComponent.Create(nil);
FStrings := TStringList.Create;
end;
procedure TestCommnd_StrigsCommand.TearDown;
begin
FStrings.Free;
FOwnerComponent.Free;
end;
procedure TestCommnd_StrigsCommand.NoGuardAssert_WithProperInjection;
begin
TCommand.AdhocExecute<TCommandStringList>([FStrings]);
// Check if there was any exception above
Assert.Pass;
end;
procedure TestCommnd_StrigsCommand.ChangeStringList_AfterExecute;
var
CommandStrings: TCommandStringList;
begin
CommandStrings := TCommandStringList.Create(FOwnerComponent);
CommandStrings.WithInjections([FStrings]);
CommandStrings.Execute;
CommandStrings.Execute;
FStrings.Delete(0);
Assert.AreEqual(1, FStrings.Count);
Assert.AreEqual(1, CommandStrings.Lines.Count);
end;
procedure TestCommnd_StrigsCommand.GuardException_NoInjection;
begin
Assert.WillRaiseDescendant(
procedure
begin
TCommand.AdhocExecute<TCommandStringList>([]);
end, EAssertionFailed);
end;
// ------------------------------------------------------------------------
// TestCommndFactory_StrigListCommand
// ------------------------------------------------------------------------
type
TAdvancedCommand = class(TCommand)
private
FCount: Integer;
FNonPrimeLines: TStrings;
FPrimeLines: TStrings;
FComponent: TComponent;
FStream: TStream;
FListInt: TList<Integer>;
FProcessNonPrimeNumbers: boolean;
procedure WriteIntegerToStream(aValue: Integer);
class function isPrime(num: Integer): boolean;
strict protected
procedure DoGuard; override;
procedure DoExecute; override;
public
constructor Create(AOwner: TComponent); override;
property Count: Integer read FCount write FCount;
published
property Stream: TStream read FStream write FStream;
property PrimeLines: TStrings read FPrimeLines write FPrimeLines;
property Component: TComponent read FComponent write FComponent;
property ProcessNonPrimeNumbers: boolean read FProcessNonPrimeNumbers
write FProcessNonPrimeNumbers;
property NonPrimeLines: TStrings read FNonPrimeLines write FNonPrimeLines;
property ListInt: TList<Integer> read FListInt write FListInt;
end;
{$REGION 'implementation TAdvancedCommand'}
procedure TAdvancedCommand.DoGuard;
begin
System.Assert(Stream <> nil);
System.Assert(PrimeLines <> nil);
System.Assert(Component <> nil);
System.Assert(NonPrimeLines <> nil);
System.Assert(ListInt <> nil);
end;
class function TAdvancedCommand.isPrime(num: Integer): boolean;
var
M: Integer;
begin
if num <= 1 then
exit(false);
for M := 2 to (num div 2) do
if num mod M = 0 then
exit(false);
exit(True);
end;
procedure TAdvancedCommand.WriteIntegerToStream(aValue: Integer);
begin
Stream.Write(aValue, SizeOf(aValue));
end;
constructor TAdvancedCommand.Create(AOwner: TComponent);
begin
inherited;
ProcessNonPrimeNumbers := True;
end;
procedure TAdvancedCommand.DoExecute;
var
i: Integer;
begin
inherited;
PrimeLines.Clear;
NonPrimeLines.Clear;
WriteIntegerToStream(ListInt.Count);
for i := 0 to ListInt.Count - 1 do
begin
WriteIntegerToStream(ListInt[i]);
if isPrime(ListInt[i]) then
PrimeLines.Add(Format('%d is prime', [ListInt[i]]))
else if ProcessNonPrimeNumbers then
NonPrimeLines.Add(ListInt[i].ToString);
end;
with Component do
begin
Name := 'A' + Component.Name;
Tag := ListInt.Count;
end;
Count := ListInt.Count;
end;
{$ENDREGION}
procedure TestCommnd_Advanced.Setup;
begin
FComponent := TComponent.Create(nil);
FStringPrime := TStringList.Create;
FStringNonPrime := TStringList.Create;
FMemStream := TMemoryStream.Create;
FList := TList<Integer>.Create;
end;
procedure TestCommnd_Advanced.TearDown;
begin
FStringPrime.Free;
FStringNonPrime.Free;
FMemStream.Free;
FList.Free;
FComponent.Free;
end;
procedure TestCommnd_Advanced.Execute_TestPrimes;
begin
with FList do
begin
Clear;
AddRange([10, 13, 20, 17, 100, 101, 105]);
end;
TCommand.AdhocExecute<TAdvancedCommand>([FComponent, FStringPrime,
FStringNonPrime, FMemStream, FList]);
Assert.AreEqual(3, FStringPrime.Count);
Assert.AreEqual('13 is prime', FStringPrime[0]);
Assert.AreEqual('17 is prime', FStringPrime[1]);
Assert.AreEqual('101 is prime', FStringPrime[2]);
end;
procedure TestCommnd_Advanced.Execute_TestNonPrimes;
begin
with FList do
begin
Clear;
AddRange([10, 13, 20, 17, 100, 101, 105]);
end;
TCommand.AdhocExecute<TAdvancedCommand>([FComponent, FStringPrime,
FStringNonPrime, FMemStream, FList]);
Assert.AreEqual(4, FStringNonPrime.Count);
Assert.AreEqual('10', FStringNonPrime[0]);
Assert.AreEqual('20', FStringNonPrime[1]);
Assert.AreEqual('100', FStringNonPrime[2]);
Assert.AreEqual('105', FStringNonPrime[3]);
end;
procedure TestCommnd_Advanced.Execute_TestStream;
begin
with FList do
begin
Clear;
AddRange([10, 13, 20, 17, 100, 101, 105]);
end;
TCommand.AdhocExecute<TAdvancedCommand>([FComponent, FStringPrime,
FStringNonPrime, FMemStream, FList]);
Assert.AreEqual(32, Integer(FMemStream.Size));
end;
procedure TestCommnd_Advanced.Execute_ProcessOnlyPrimes;
begin
with FList do
begin
Clear;
AddRange([10, 13, 20, 17, 100, 101, 105]);
end;
TCommand.AdhocExecute<TAdvancedCommand>([FComponent, FStringPrime,
FStringNonPrime, FMemStream, FList, false]);
Assert.AreEqual(3, FStringPrime.Count);
Assert.AreEqual(0, FStringNonPrime.Count);
end;
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
initialization
end.
|
{***************************************************************************
*
* Orion-project.org Lazarus Helper Library
* Copyright (C) 2016-2017 by Nikolay Chunosov
*
* This file is part of the Orion-project.org Lazarus Helper Library
* https://github.com/Chunosov/orion-lazarus
*
* This Library is free software: you can redistribute it and/or modify it
* under the terms of the MIT License. See enclosed LICENSE.txt for details.
*
***************************************************************************}
unit OriNotifier;
interface
uses
Classes, Contnrs;
type
TPublisher = class
strict private
FSubscribers: TObjectList;
public
constructor Create;
destructor Destroy; override;
class procedure Unsubscribe(AEvent: TNotifyEvent);
class procedure Subscribe(const ATopic: String; AEvent: TNotifyEvent);
class procedure Publish(Sender: TObject; const ATopic: String);
end;
implementation
uses
SysUtils;
var
Publisher: TPublisher;
function HashOf(const Key: string): Cardinal; inline;
var
I: Integer;
begin
Result := 0;
for I := 1 to Length(Key) do
Result := ((Result shl 2) or (Result shr (SizeOf(Result)*8 - 2))) xor Ord(Key[I]);
end;
{$region 'TSubscriber'}
type
TSubscriber = class
strict private
public
Topic: Cardinal;
Event: TNotifyEvent;
constructor Create(ATopic: Cardinal; AEvent: TNotifyEvent);
end;
constructor TSubscriber.Create(ATopic: Cardinal; AEvent: TNotifyEvent);
begin
Topic := ATopic;
Event := AEvent;
end;
{$endregion}
{$region 'TPublisher'}
constructor TPublisher.Create;
begin
FSubscribers := TObjectList.Create(True);
end;
destructor TPublisher.Destroy;
begin
FSubscribers.Free;
end;
class procedure TPublisher.Subscribe(const ATopic: String; AEvent: TNotifyEvent);
var
I: Integer;
T: Cardinal;
begin
if not Assigned(Publisher) then
Publisher := TPublisher.Create;
T := HashOf(ATopic);
for I := 0 to Publisher.FSubscribers.Count-1 do
with TSubscriber(Publisher.FSubscribers[I]) do
if (Topic = T) and (Addr(AEvent) = Addr(Event)) then
Exit;
Publisher.FSubscribers.Add(TSubscriber.Create(T, AEvent));
end;
class procedure TPublisher.Publish(Sender: TObject; const ATopic: String);
var
I: Integer;
T: Cardinal;
begin
if Assigned(Publisher) then
begin
T := HashOf(ATopic);
for I := 0 to Publisher.FSubscribers.Count-1 do
with TSubscriber(Publisher.FSubscribers[I]) do
if (Topic = T) and Assigned(Event) then
Event(Sender);
end;
end;
class procedure TPublisher.Unsubscribe(AEvent: TNotifyEvent);
var
I: Integer;
begin
for I := Publisher.FSubscribers.Count-1 downto 0 do
if Addr(TSubscriber(Publisher.FSubscribers[I]).Event) = Addr(AEvent) then
begin
Publisher.FSubscribers[I].Free;
Publisher.FSubscribers.Delete(I);
end;
end;
{$endregion}
initialization
finalization
if Assigned(Publisher) then Publisher.Free;
end.
|
unit ORM.Model.SALARY_HISTORY;
interface
uses
Spring.Persistence.Mapping.Attributes;
{$M+}
type
[Entity]
[Table('SALARY_HISTORY')]
TSalaryHistory = class
private
FId: Integer;
FChangeDate: TDateTime;
FUpdaterId: string;
FOldSalary: Double;
FPercentChange: Double;
FNewSalary: Double;
public
[UniqueConstraint]
[Column('EMP_NO', [cpRequired, cpPrimaryKey, cpNotNull])]
[ForeignJoinColumn('EMP_NO', 'EMPLOYEE', 'EMP_NO', [fsOnDeleteCascade, fsOnUpdateCascade])]
property Id: Integer read FId write FId;
[Column('CHANGE_DATE')]
property ChangeDate: TDateTime read FChangeDate write FChangeDate;
[Column('UPDATER_ID', [], 20)]
property UpdaterId: string read FUpdaterId write FUpdaterId;
[Column('OLD_SALARY', [], 10, 0, 2)]
property OldSalary: Double read FOldSalary write FOldSalary;
[Column('PERCENT_CHANGE')]
property PercentChange: Double read FPercentChange write FPercentChange;
[Column('NEW_SALARY')]
property NewSalary: Double read FNewSalary write FNewSalary;
end;
{$M-}
implementation
end.
|
{ Copyright (C) 1998-2018, written by Shkolnik Mike, Scalabium
E-Mail: mshkolnik@scalabium.com
mshkolnik@yahoo.com
WEB: http://www.scalabium.com
}
unit SMPanel;
interface
{$I SMVersion.inc}
uses
Classes, Windows, Messages, Controls, Graphics, ExtCtrls;
type
TSMGrabberPlace = (gpTop, gpLeft, gpBottom, gpRight);
{$IFDEF SM_ADD_ComponentPlatformsAttribute}
[ComponentPlatformsAttribute(pidWin32 or pidWin64)]
{$ENDIF}
TSMFramePanel = class(TPanel)
private
FIcon: TIcon;
FGrabberSize: Integer;
FGrabberPlace: TSMGrabberPlace;
FMoveable: Boolean;
FOnClose: TNotifyEvent;
FOnCaptionClick: TNotifyEvent;
IsCloseClicked, IsCaptionClicked: Boolean;
procedure SetGrabberSize(Value: Integer);
procedure SetGrabberPlace(Value: TSMGrabberPlace);
procedure SetIcon(Value: TIcon);
procedure WMLButtonDown(var Message: TWMLButtonDown); message WM_LBUTTONDOWN;
procedure WMLButtonUp(var Message: TWMLButtonUp); message WM_LBUTTONUP;
protected
procedure AlignControls(AControl: TControl; var Rect: TRect); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Paint; override;
property Canvas;
published
property GrabberSize: Integer read FGrabberSize write SetGrabberSize default 12;
property GrabberPlace: TSMGrabberPlace read FGrabberPlace write SetGrabberPlace default gpTop;
property Moveable: Boolean read FMoveable write FMoveable default False;
property Icon: TIcon read FIcon write SetIcon;
property OnCaptionClick: TNotifyEvent read FOnCaptionClick write FOnCaptionClick;
property OnClose: TNotifyEvent read FOnClose write FOnClose;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('SMComponents', [TSMFramePanel]);
end;
constructor TSMFramePanel.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FGrabberSize := 12;
FGrabberPlace := gpTop;
FMoveable := False;
BevelOuter := bvNone;
FIcon := TIcon.Create;
end;
destructor TSMFramePanel.Destroy;
begin
FIcon.Free;
inherited Destroy;
end;
procedure TSMFramePanel.AlignControls(AControl: TControl; var Rect: TRect);
begin
case GrabberPlace of
gpLeft,
gpRight: Inc(Rect.Left, 10);
gpTop,
gpBottom: Inc(Rect.Top, 10);
end;
InflateRect(Rect, -1, -1);
if Ctl3d then
InflateRect(Rect, -1, -1);
inherited AlignControls(AControl, Rect)
end;
procedure TSMFramePanel.SetGrabberSize(Value: Integer);
begin
if (Value <> FGrabberSize) then
begin
FGrabberSize := Value;
Invalidate;
end;
end;
procedure TSMFramePanel.SetGrabberPlace(Value: TSMGrabberPlace);
begin
if (Value <> FGrabberPlace) then
begin
FGrabberPlace := Value;
Invalidate;
end;
end;
procedure TSMFramePanel.SetIcon(Value: TIcon);
begin
FIcon.Assign(Value);
Invalidate;
end;
procedure TSMFramePanel.Paint;
procedure DrawCloseButton(Left, Top: Integer);
begin
DrawFrameControl(Canvas.Handle, Rect(Left, Top, Left+FGrabberSize-2,
Top+FGrabberSize-2), DFC_CAPTION, DFCS_CAPTIONCLOSE);
end;
procedure DrawGrabberLine(Left, Top, Right, Bottom: Integer);
begin
with Canvas do
begin
Pen.Color := clBtnHighlight;
MoveTo(Right, Top);
LineTo(Left, Top);
LineTo(Left, Bottom);
Pen.Color := clBtnShadow;
LineTo(Right, Bottom);
LineTo(Right, Top-1);
end;
end;
var
ARect: TRect;
begin
inherited Paint;
ARect := ClientRect;
with ARect do
case GrabberPlace of
gpLeft,
gpRight: begin
if not FIcon.Empty then
begin
Bottom := Bottom - GrabberSize - 2;
DrawIconEx(Canvas.Handle, 0, Bottom+1, Icon.Handle, GrabberSize, GrabberSize, 0, 0, {DI_DEFAULTSIZE or} DI_NORMAL);
end;
DrawCloseButton(Left+1, Top+1);
DrawGrabberLine(Left+3, Top+GrabberSize+1, Left+5, Bottom-2);
DrawGrabberLine(Left+6, Top+GrabberSize+1, Left+8, Bottom-2);
end;
gpTop,
gpBottom: begin
if not FIcon.Empty then
begin
Left := Left + GrabberSize + 1;
DrawIconEx(Canvas.Handle, 0, 0, Icon.Handle, GrabberSize, GrabberSize, 0, 0, {DI_DEFAULTSIZE or} DI_NORMAL);
end;
DrawCloseButton(Right-GrabberSize+1, Top+1);
DrawGrabberLine(Left+2, Top+3, Right-GrabberSize-2, Top+5);
DrawGrabberLine(Left+2, Top+6, Right-GrabberSize-2, Top+8);
end
end;
end;
procedure TSMFramePanel.WMLButtonDown(var Message: TWMLButtonDown);
begin
inherited;
IsCloseClicked := False;
IsCaptionClicked := False;
case GrabberPlace of
gpLeft,
gpRight: begin
if (Message.YPos < 15) then
IsCloseClicked := True;
if (Message.XPos < 15) then
IsCaptionClicked := True;
end;
gpTop,
gpBottom: begin
if (Message.XPos > Width - 15) then
IsCloseClicked := True;
if (Message.YPos < 15) then
IsCaptionClicked := True;
end;
end;
ReleaseCapture;
if IsCaptionClicked and not IsCloseClicked then
begin
if Assigned(OnCaptionClick) then
OnCaptionClick(Self);
if Moveable then
Perform(WM_SysCommand, $F012, 0)
end
end;
procedure TSMFramePanel.WMLButtonUp(var Message: TWMLButtonUp);
begin
inherited;
if IsCloseClicked and IsCaptionClicked then
begin
if Assigned(OnClose) then
OnClose(Self);
Visible := False;
end;
IsCloseClicked := False;
IsCaptionClicked := False;
end;
end.
|
program FRACSC3D;
{$M 50000, 0, 655360}
{$I Float.INC}
uses MathLib0,
Sculpt3D,
FracSurf { DoFractal, AlgorithmType };
CONST
Size = 4;
Size2 = 8; { 2 * Size }
ReliefFactor = 0.5; { between 0 and 1 }
TYPE
Surface = ARRAY[0..Size,0..Size] OF WORD;
SculptSurface = ARRAY[0..Size,0..Size] OF VertexPtr;
SculptPerim = SculptSurface {ARRAY[0..4*Size-1] OF VertexPtr }
(* will become psuedo 2D array *);
SurfPtr = ^Surface;
SculptSurfacePtr = ^SculptSurface;
SculptPerimPtr = ^SculptPerim;
VAR
Floating : BOOLEAN;
TerrainObj : ObjectRec;
Terrain : ObjectPtr;
FractalSurf : SurfPtr;
{ --------------------------------------------------------- }
FUNCTION ndx(i,j : WORD) : WORD;
{ Converts perimeter indicies of 2D array to 1D }
{ for max speed no error checking on indicies! }
BEGIN
ndx := i + j + (ORD(j > i) * Size2);
END;
{ --------------------------------------------------------- }
PROCEDURE ConnectToGround( obj : ObjectPtr;
x, y : WORD;
Surf : SculptSurfacePtr;
Perim : SculptPerimPtr );
VAR
prop : FaceProperty;
BEGIN
{ link edges of x side to floor }
IF (x = 0) OR (x = Size) THEN
BEGIN
{ link to vertex directly below }
Link(obj, Surf^[x,y], Perim^[x,y], prop);
IF y < Size THEN
{ also link to vertex adjacent to make triangle }
Link(obj, Surf^[x,y], Perim^[x,y+1], prop);
{ END; }
END;
{ link edges of y side to floor }
IF (y = 0) OR (y = Size) THEN
BEGIN
{ link to vertex directly below }
Link(obj, Surf^[x,y], Perim^[x,y], prop);
IF x < Size THEN
{ also link to vertex adjacent to make triangle }
Link(obj, Surf^[x,y], Perim^[x+1,y], prop);
{ END; }
END;
{ connect the edges of the floor }
IF (Y = 0) AND (x < Size) THEN
BEGIN
Link(obj, Perim^[x,0], Perim^[x+1,0],prop);
Link(obj, Perim^[x,Size], Perim^[x+1,Size],prop);
END
ELSE IF (Y < Size) { x must = 0 } THEN
BEGIN
Link(obj, Perim^[0,y], Perim^[0,y+1],prop);
Link(obj, Perim^[Size,y], Perim^[Size,y+1],prop);
END;
END {ConnectToGround};
{ --------------------------------------------------------- }
PROCEDURE MakeFractalObject(obj : ObjectPtr; SurfB : SurfPtr);
VAR
Surf : SculptSurfacePtr;
Perim : SculptPerimPtr;
x, y : WORD;
prop : FaceProperty;
BEGIN
{ allocate surface structures }
GetMem(Surf,SizeOf(SculptSurface));
GetMem(Perim,SizeOf(SculptPerim));
IF (Surf = NIL) OR (Perim=NIL) THEN
BEGIN
Writeln('Not Enough Memory!');
Halt;
END;
{ initialize vertex structures for surface }
FOR x := 0 TO Size DO
FOR y := 0 TO Size DO
BEGIN
IF NOT Floating AND
( (x=0) OR (y=0) OR (x=Size) OR (y=size) ) THEN
BEGIN
{ make floor perimeter vertices }
Perim^[x,y] := NewVertex(x, y, 0, obj^.vertices);
obj^.vertices := Perim^[x,y];
END;
{ put altitude data in vertices }
Surf^[x,y] := NewVertex(x,y,SurfB^[x,y],obj^.vertices);
obj^.vertices := Surf^[x,y];
END;
{ END; }
{ Okay, we've transfered the data so get rid of the orig. surface }
FreeMem(SurfB,SizeOf(Surface));
{ make triangles and link vertices on surface }
FOR x := 0 TO Size DO
BEGIN
FOR y := 0 TO Size DO
BEGIN
IF x < Size THEN
{ link to adjacent vertex on x axis }
Link(obj, Surf^[x,y], Surf^[x+1,y], prop);
{END;}
IF y < Size THEN
{ link to adjacent vertex on y axis }
Link(obj, Surf^[x,y], Surf^[x,y+1], prop);
{END;}
IF (x < Size) AND (y < Size) THEN
{ link to diagonally adjacent vertex to make triangle }
Link(obj, Surf^[x,y], Surf^[x+1,y+1], prop);
{END;}
IF NOT Floating AND
( (x=0) OR (y=0) OR (x=Size) OR (y=Size) ) THEN
ConnectToGround(obj, x, y, Surf, Perim);
END { FOR y };
END { FOR x };
FreeMem(Surf,SizeOf(SculptSurface));
FreeMem(Perim,SizeOf(SculptPerim));
END {MakeFractalObject};
VAR
x, y : WORD;
BEGIN
Floating := (paramstr(1) = 'F');
NewObject(TerrainObj);
Terrain := @TerrainObj;
GetMem(FractalSurf,SizeOf(Surface));
IF FractalSurf = NIL THEN
BEGIN
Writeln('Not enough memory for fractal surface');
HALT;
END;
Writeln('Computing Fractal');
{ DoFractal(FractalSurf^, ReliefFactor, Voss); }
FOR x := 0 TO Size DO
FOR y := 0 TO Size DO
FractalSurf^[x,y] := 10;
Writeln('Making Object');
MakeFractalObject(Terrain,FractalSurf);
Writeln('Euler Number:',GetEulerNum);
WriteLn('Done');
END. |
unit PascalCoin.FMX.Frame.Settings;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
FMX.Controls.Presentation, FMX.Layouts, System.Actions, FMX.ActnList,
PascalCoin.FMX.Frame.Base, FMX.ListBox, FrameStand,
PascalCoin.FMX.Frame.Settings.Node;
type
TSettingsFrame = class(TBaseFrame)
ButtonLayout: TLayout;
SaveButton: TButton;
CancelButton: TButton;
MainLayout: TLayout;
ActionList: TActionList;
SaveAction: TAction;
CancelAction: TAction;
AdvancedOptionsSwitch: TSwitch;
AdvancedOptionsLayout: TLayout;
AdvancedOptionsLabel: TLabel;
NodesLayout: TLayout;
NodesHeadingLayout: TLayout;
NodesHeadingLabel: TLabel;
NodesList: TListBox;
ListBoxItem1: TListBoxItem;
SettingsFrameStand: TFrameStand;
AddNodeButton: TSpeedButton;
MultiAccountLayout: TLayout;
MultiAccountLabel: TLabel;
MultiAccountSwitch: TSwitch;
UnlockTimeLayout: TLayout;
UnlockTimeLabel: TLabel;
UnlockTimeCombo: TComboBox;
SpeedButton1: TSpeedButton;
AddNodeAction: TAction;
SelectNodeAction: TAction;
procedure AddNodeActionExecute(Sender: TObject);
procedure AdvancedOptionsSwitchSwitch(Sender: TObject);
procedure CancelActionExecute(Sender: TObject);
procedure MultiAccountSwitchSwitch(Sender: TObject);
procedure SaveActionExecute(Sender: TObject);
procedure UnlockTimeComboChange(Sender: TObject);
private
{ Private declarations }
FNodeFrame: TFrameInfo<TEditNodeFrame>;
procedure LoadValues;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
end;
implementation
{$R *.fmx}
uses PascalCoin.FMX.DataModule, PascalCoin.FMX.Wallet.Shared,
PascalCoin.FMX.Strings;
{ TSettingsFrame }
constructor TSettingsFrame.Create(AOwner: TComponent);
begin
inherited;
LoadValues;
MultiAccountLabel.Hint := SEnablingThisWillAllowYouToAutoma;
end;
procedure TSettingsFrame.AddNodeActionExecute(Sender: TObject);
var
lName, lURI: string;
begin
FNodeFrame := SettingsFrameStand.New<TEditNodeFrame>(NodesList);
FNodeFrame.Frame.OnCancel := procedure
begin
FNodeFrame.Hide(100,
procedure
begin
FNodeFrame.Close;
FNodeFrame := nil;
end);
end;
FNodeFrame.Frame.OnOk := procedure
begin
lName := FNodeFrame.Frame.NodeName;
lURI := FNodeFrame.Frame.URI;
FNodeFrame.Hide(100,
procedure
begin
FNodeFrame.Close;
FNodeFrame := nil;
end);
end;
FNodeFrame.Show;
end;
procedure TSettingsFrame.LoadValues;
var
lNode: TNodeRecord;
lItem: TListBoxItem;
begin
AdvancedOptionsSwitch.OnSwitch := nil;
AdvancedOptionsSwitch.IsChecked := MainDataModule.Settings.AdvancedOptions;
AdvancedOptionsSwitch.OnSwitch := AdvancedOptionsSwitchSwitch;
MultiAccountSwitch.OnSwitch := nil;
MultiAccountSwitch.IsChecked :=
MainDataModule.Settings.AutoMultiAccountTransactions;
MultiAccountSwitch.OnSwitch := MultiAccountSwitchSwitch;
UnlockTimeCombo.OnChange := nil;
case MainDataModule.Settings.UnlockTime of
0:
UnlockTimeCombo.ItemIndex := 0;
1:
UnlockTimeCombo.ItemIndex := 1;
10:
UnlockTimeCombo.ItemIndex := 3;
30:
UnlockTimeCombo.ItemIndex := 4;
60:
UnlockTimeCombo.ItemIndex := 5;
end;
UnlockTimeCombo.OnChange := UnlockTimeComboChange;
NodesList.BeginUpdate;
NodesList.Clear;
for lNode in MainDataModule.Settings.Nodes do
begin
lItem := TListBoxItem.Create(NodesList);
lItem.Parent := NodesList;
lItem.ItemData.Text := lNode.Name;
lItem.ItemData.Detail := lNode.URI;
if SameText(lNode.URI, MainDataModule.Settings.SelectedNodeURI) then
lItem.ItemData.Accessory := TListBoxItemData.TAccessory.aCheckmark;
end;
NodesList.EndUpdate;
end;
procedure TSettingsFrame.MultiAccountSwitchSwitch(Sender: TObject);
begin
MainDataModule.Settings.AutoMultiAccountTransactions :=
MultiAccountSwitch.IsChecked;
end;
procedure TSettingsFrame.AdvancedOptionsSwitchSwitch(Sender: TObject);
begin
MainDataModule.Settings.AdvancedOptions := AdvancedOptionsSwitch.IsChecked;
end;
procedure TSettingsFrame.CancelActionExecute(Sender: TObject);
begin
LoadValues;
end;
procedure TSettingsFrame.SaveActionExecute(Sender: TObject);
begin
MainDataModule.SaveSettings;
end;
procedure TSettingsFrame.UnlockTimeComboChange(Sender: TObject);
var
lMinutes: Integer;
begin
case UnlockTimeCombo.ItemIndex of
0:
MainDataModule.Settings.UnlockTime := 0;
1:
MainDataModule.Settings.UnlockTime := 1;
2:
MainDataModule.Settings.UnlockTime := 10;
3:
MainDataModule.Settings.UnlockTime := 30;
4:
MainDataModule.Settings.UnlockTime := 60;
end;
end;
end.
|
unit uPerfLog;
interface
uses Classes, SysUtils, Windows;
type
TPerfLog = class
private
FArq : Text;
FName : String;
FStart : Cardinal;
FActive : Boolean;
procedure SetActive(const Value: Boolean);
public
constructor Create;
destructor Destroy; override;
procedure Start(aName: String);
procedure Done;
property Active: Boolean
read FActive write SetActive;
end;
var
PerfLog: TPerfLog = nil;
implementation
{ TPerfLog }
function SMS(C: Cardinal): String;
begin
Str((C/1000):1:3, Result);
end;
constructor TPerfLog.Create;
begin
FActive := False;
FName := '';
FStart := 0;
end;
destructor TPerfLog.Destroy;
begin
Active := False;
inherited;
end;
procedure TPerfLog.Done;
begin
if FStart>0 then begin
if FActive then
Writeln(FArq, FormatDateTime('dd/mm/yyyy hh:mm:ss', Now) + ' - ' + FName + ': ' + SMS(GetTickCount-FStart));
FStart := 0;
FName := '';
end;
end;
procedure TPerfLog.SetActive(const Value: Boolean);
var S: String;
begin
if Value = FActive then Exit;
if Value then begin
S := ExtractFilePath(ParamStr(0)) + 'perflog.txt';
Assign(FArq, S);
Rewrite(FArq);
Writeln(FArq, 'Ativado em ' + FormatDateTime('dd/mm/yyyy hh:mm:ss', Now));
end else begin
Writeln(FArq, 'Destivado em ' + FormatDateTime('dd/mm/yyyy hh:mm:ss', Now));
CloseFile(FArq);
end;
FActive := Value;
end;
procedure TPerfLog.Start(aName: String);
begin
FStart := GetTickCount;
FName := aName;
end;
initialization
PerfLog := TPerfLog.Create;
finalization
if Assigned(PerfLog) then
PerfLog.Free;
end.
|
unit BufferInterpreter.NVMe;
interface
uses
SysUtils,
BufferInterpreter, Device.SMART.List, MeasureUnit.DataSize;
type
TSMARTValueID = (
None,
CriticalWarning,
TemperatureInKelvin,
AvailableSpare,
PercentageUsed,
DataUnitsReadInLBA,
DataUnitsWrittenInLBA,
HostReadCommands,
HostWriteCommands,
ControllerBusyTime,
PowerCycles,
PowerOnHours,
UnsafeShutdowns,
MediaErrors,
NumberOfErrorInformationLogEntries);
TNVMeBufferInterpreter = class(TBufferInterpreter)
public
function BufferToIdentifyDeviceResult(
const Buffer: TSmallBuffer): TIdentifyDeviceResult; override;
function BufferToSMARTValueList(
const Buffer: TSmallBuffer): TSMARTValueList; override;
function LargeBufferToIdentifyDeviceResult(
const Buffer: TLargeBuffer): TIdentifyDeviceResult; override;
function LargeBufferToSMARTValueList(
const Buffer: TLargeBuffer): TSMARTValueList; override;
function BufferToCapacityAndLBA(const Buffer: TLargeBuffer):
TIdentifyDeviceResult;
private
BufferInterpreting: TLargeBuffer;
function GetFirmwareFromBuffer: String;
function GetLBASizeFromBuffer: Cardinal;
function GetModelFromBuffer: String;
function GetSerialFromBuffer: String;
function GetLBASize(const Buffer: TLargeBuffer): Integer;
function GetDataSetManagementSupported: Boolean;
function SeparateCriticalWarningFrom(const Buffer: TSmallBuffer):
TSMARTValueEntry;
function SeparateTemperatureFrom(const Buffer: TSmallBuffer):
TSMARTValueEntry;
function SeparateAvailableSpareFrom(const Buffer: TSmallBuffer):
TSMARTValueEntry;
function SeparatePercentageUsedFrom(const Buffer: TSmallBuffer):
TSMARTValueEntry;
function SeparateDataUnitsReadFrom(const Buffer: TSmallBuffer):
TSMARTValueEntry;
function SeparateDataUnitsWrittenFrom(const Buffer: TSmallBuffer):
TSMARTValueEntry;
function SeparateHostReadCommandsFrom(const Buffer: TSmallBuffer):
TSMARTValueEntry;
function SeparateHostWriteCommandsFrom(
const Buffer: TSmallBuffer): TSMARTValueEntry;
function SeparateControllerBusyTimeFrom(
const Buffer: TSmallBuffer): TSMARTValueEntry;
function SeparatePowerCyclesFrom(const Buffer: TSmallBuffer):
TSMARTValueEntry;
function SeparatePowerOnHoursFrom(const Buffer: TSmallBuffer):
TSMARTValueEntry;
function SeparateUnsafeShutdownsFrom(const Buffer: TSmallBuffer):
TSMARTValueEntry;
function SeparateMediaErrorsFrom(const Buffer: TSmallBuffer):
TSMARTValueEntry;
function SeparateNumberOfErrorsFrom(const Buffer: TSmallBuffer):
TSMARTValueEntry;
end;
implementation
{ TNVMeBufferInterpreter }
function TNVMeBufferInterpreter.BufferToSMARTValueList(
const Buffer: TSmallBuffer): TSMARTValueList;
begin
result := TSMARTValueList.Create;
result.Add(SeparateCriticalWarningFrom(Buffer));
result.Add(SeparateTemperatureFrom(Buffer));
result.Add(SeparateAvailableSpareFrom(Buffer));
result.Add(SeparatePercentageUsedFrom(Buffer));
result.Add(SeparateDataUnitsReadFrom(Buffer));
result.Add(SeparateDataUnitsWrittenFrom(Buffer));
result.Add(SeparateHostReadCommandsFrom(Buffer));
result.Add(SeparateHostWriteCommandsFrom(Buffer));
result.Add(SeparateControllerBusyTimeFrom(Buffer));
result.Add(SeparatePowerCyclesFrom(Buffer));
result.Add(SeparatePowerOnHoursFrom(Buffer));
result.Add(SeparateUnsafeShutdownsFrom(Buffer));
result.Add(SeparateMediaErrorsFrom(Buffer));
result.Add(SeparateNumberOfErrorsFrom(Buffer));
end;
function TNVMeBufferInterpreter.SeparateCriticalWarningFrom(
const Buffer: TSmallBuffer): TSMARTValueEntry;
begin
FillChar(result, SizeOf(result), 0);
result.ID := Ord(TSMARTValueID.CriticalWarning);
result.RAW := Buffer[0];
end;
function TNVMeBufferInterpreter.SeparateTemperatureFrom(
const Buffer: TSmallBuffer): TSMARTValueEntry;
var
CurrentByte: Integer;
const
TemperatureStart = 1;
TemperatureEnd = 2;
begin
FillChar(result, SizeOf(result), 0);
result.ID := Ord(TSMARTValueID.TemperatureInKelvin);
result.RAW := 0;
for CurrentByte := TemperatureEnd downto TemperatureStart do
begin
result.RAW := result.RAW shl 8;
result.RAW := result.RAW + Buffer[CurrentByte];
end;
end;
function TNVMeBufferInterpreter.SeparateAvailableSpareFrom(
const Buffer: TSmallBuffer): TSMARTValueEntry;
begin
FillChar(result, SizeOf(result), 0);
result.ID := Ord(TSMARTValueID.AvailableSpare);
result.RAW := Buffer[3];
result.Threshold := Buffer[4];
end;
function TNVMeBufferInterpreter.SeparatePercentageUsedFrom(
const Buffer: TSmallBuffer): TSMARTValueEntry;
begin
FillChar(result, SizeOf(result), 0);
result.ID := Ord(TSMARTValueID.PercentageUsed);
result.RAW := Buffer[5];
end;
function TNVMeBufferInterpreter.SeparateDataUnitsReadFrom(
const Buffer: TSmallBuffer): TSMARTValueEntry;
var
CurrentByte: Integer;
const
ReadStart = 32;
ReadEnd = 47;
begin
FillChar(result, SizeOf(result), 0);
result.ID := Ord(TSMARTValueID.DataUnitsReadInLBA);
result.RAW := 0;
for CurrentByte := ReadEnd downto ReadStart do
begin
result.RAW := result.RAW shl 8;
result.RAW := result.RAW + Buffer[CurrentByte];
end;
end;
function TNVMeBufferInterpreter.SeparateDataUnitsWrittenFrom(
const Buffer: TSmallBuffer): TSMARTValueEntry;
var
CurrentByte: Integer;
const
WrittenStart = 48;
WrittenEnd = 63;
begin
FillChar(result, SizeOf(result), 0);
result.ID := Ord(TSMARTValueID.DataUnitsWrittenInLBA);
result.RAW := 0;
for CurrentByte := WrittenEnd downto WrittenStart do
begin
result.RAW := result.RAW shl 8;
result.RAW := result.RAW + Buffer[CurrentByte];
end;
end;
function TNVMeBufferInterpreter.SeparateHostReadCommandsFrom(
const Buffer: TSmallBuffer): TSMARTValueEntry;
var
CurrentByte: Integer;
const
ReadStart = 64;
ReadEnd = 79;
begin
FillChar(result, SizeOf(result), 0);
result.ID := Ord(TSMARTValueID.HostReadCommands);
result.RAW := 0;
for CurrentByte := ReadEnd downto ReadStart do
begin
result.RAW := result.RAW shl 8;
result.RAW := result.RAW + Buffer[CurrentByte];
end;
end;
function TNVMeBufferInterpreter.SeparateHostWriteCommandsFrom(
const Buffer: TSmallBuffer): TSMARTValueEntry;
var
CurrentByte: Integer;
const
WriteStart = 80;
WriteEnd = 95;
begin
FillChar(result, SizeOf(result), 0);
result.ID := Ord(TSMARTValueID.HostWriteCommands);
result.RAW := 0;
for CurrentByte := WriteEnd downto WriteStart do
begin
result.RAW := result.RAW shl 8;
result.RAW := result.RAW + Buffer[CurrentByte];
end;
end;
function TNVMeBufferInterpreter.SeparateControllerBusyTimeFrom(
const Buffer: TSmallBuffer): TSMARTValueEntry;
var
CurrentByte: Integer;
const
BusyTimeStart = 96;
BusyTimeEnd = 111;
begin
FillChar(result, SizeOf(result), 0);
result.ID := Ord(TSMARTValueID.ControllerBusyTime);
result.RAW := 0;
for CurrentByte := BusyTimeEnd downto BusyTimeStart do
begin
result.RAW := result.RAW shl 8;
result.RAW := result.RAW + Buffer[CurrentByte];
end;
end;
function TNVMeBufferInterpreter.SeparatePowerCyclesFrom(
const Buffer: TSmallBuffer): TSMARTValueEntry;
var
CurrentByte: Integer;
const
PowerCycleStart = 112;
PowerCycleEnd = 127;
begin
FillChar(result, SizeOf(result), 0);
result.ID := Ord(TSMARTValueID.PowerCycles);
result.RAW := 0;
for CurrentByte := PowerCycleEnd downto PowerCycleStart do
begin
result.RAW := result.RAW shl 8;
result.RAW := result.RAW + Buffer[CurrentByte];
end;
end;
function TNVMeBufferInterpreter.SeparatePowerOnHoursFrom(
const Buffer: TSmallBuffer): TSMARTValueEntry;
var
CurrentByte: Integer;
const
PowerOnHoursStart = 128;
PowerOnHoursEnd = 143;
begin
FillChar(result, SizeOf(result), 0);
result.ID := Ord(TSMARTValueID.PowerOnHours);
result.RAW := 0;
for CurrentByte := PowerOnHoursEnd downto PowerOnHoursStart do
begin
result.RAW := result.RAW shl 8;
result.RAW := result.RAW + Buffer[CurrentByte];
end;
end;
function TNVMeBufferInterpreter.SeparateUnsafeShutdownsFrom(
const Buffer: TSmallBuffer): TSMARTValueEntry;
var
CurrentByte: Integer;
const
UnsafeShutdownsStart = 144;
UnsafeShutdownsEnd = 159;
begin
FillChar(result, SizeOf(result), 0);
result.ID := Ord(TSMARTValueID.UnsafeShutdowns);
result.RAW := 0;
for CurrentByte := UnsafeShutdownsEnd downto UnsafeShutdownsStart do
begin
result.RAW := result.RAW shl 8;
result.RAW := result.RAW + Buffer[CurrentByte];
end;
end;
function TNVMeBufferInterpreter.SeparateMediaErrorsFrom(
const Buffer: TSmallBuffer): TSMARTValueEntry;
var
CurrentByte: Integer;
const
MediaErrorsStart = 160;
MediaErrorsEnd = 175;
begin
FillChar(result, SizeOf(result), 0);
result.ID := Ord(TSMARTValueID.MediaErrors);
result.RAW := 0;
for CurrentByte := MediaErrorsEnd downto MediaErrorsStart do
begin
result.RAW := result.RAW shl 8;
result.RAW := result.RAW + Buffer[CurrentByte];
end;
end;
function TNVMeBufferInterpreter.SeparateNumberOfErrorsFrom(
const Buffer: TSmallBuffer): TSMARTValueEntry;
var
CurrentByte: Integer;
const
NumberOfErrorsStart = 176;
NumberOfErrorsEnd = 191;
begin
FillChar(result, SizeOf(result), 0);
result.ID := Ord(TSMARTValueID.NumberOfErrorInformationLogEntries);
result.RAW := 0;
for CurrentByte := NumberOfErrorsEnd downto NumberOfErrorsStart do
begin
result.RAW := result.RAW shl 8;
result.RAW := result.RAW + Buffer[CurrentByte];
end;
end;
function TNVMeBufferInterpreter.GetModelFromBuffer: String;
const
ModelStart = 24;
ModelEnd = 63;
var
CurrentByte: Integer;
begin
result := '';
for CurrentByte := ModelStart to ModelEnd do
result := result + Chr(BufferInterpreting[CurrentByte]);
result := Trim(result);
end;
function TNVMeBufferInterpreter.GetDataSetManagementSupported: Boolean;
const
DataSetManagementStart = 520;
begin
result := (BufferInterpreting[DataSetManagementStart] and 4) = 4;
end;
function TNVMeBufferInterpreter.GetFirmwareFromBuffer: String;
const
FirmwareStart = 64;
FirmwareEnd = 71;
var
CurrentByte: Integer;
begin
result := '';
for CurrentByte := FirmwareStart to FirmwareEnd do
result := result + Chr(BufferInterpreting[CurrentByte]);
result := Trim(result);
end;
function TNVMeBufferInterpreter.GetSerialFromBuffer: String;
const
SerialStart = 4;
SerialEnd = 23;
var
CurrentByte: Integer;
begin
result := '';
for CurrentByte := SerialStart to SerialEnd do
result := result + Chr(BufferInterpreting[CurrentByte]);
result := Trim(result);
end;
function TNVMeBufferInterpreter.LargeBufferToIdentifyDeviceResult(
const Buffer: TLargeBuffer): TIdentifyDeviceResult;
const
SSDRate = 1;
begin
BufferInterpreting := Buffer;
result.Model := GetModelFromBuffer;
result.Firmware := GetFirmwareFromBuffer;
result.Serial := GetSerialFromBuffer;
result.UserSizeInKB := 0;
result.SATASpeed := TSATASpeed.NotSATA;
result.LBASize := GetLBASizeFromBuffer;
result.RotationRate.Supported := true;
result.RotationRate.Value := SSDRate;
result.IsDataSetManagementSupported := GetDataSetManagementSupported;
end;
function TNVMeBufferInterpreter.LargeBufferToSMARTValueList(
const Buffer: TLargeBuffer): TSMARTValueList;
var
SmallBuffer: TSmallBuffer;
begin
Move(Buffer, SmallBuffer, SizeOf(SmallBuffer));
result := BufferToSMARTValueList(SmallBuffer);
end;
function TNVMeBufferInterpreter.GetLBASizeFromBuffer: Cardinal;
const
ATA_LBA_SIZE = 512;
begin
result := ATA_LBA_SIZE;
end;
function TNVMeBufferInterpreter.GetLBASize(const Buffer: TLargeBuffer): Integer;
var
CurrentByte: Integer;
const
LBASizeStart = 8;
LBASizeEnd = 11;
begin
result := 0;
for CurrentByte := LBASizeStart to LBASizeEnd do
begin
result := result shl 8;
result := result + Buffer[CurrentByte];
end;
end;
function TNVMeBufferInterpreter.BufferToCapacityAndLBA(
const Buffer: TLargeBuffer): TIdentifyDeviceResult;
function ByteToDenaryKB: TDatasizeUnitChangeSetting;
begin
result.FNumeralSystem := Denary;
result.FFromUnit := ByteUnit;
result.FToUnit := KiloUnit;
end;
var
CurrentByte: Integer;
ResultInByte: UInt64;
const
LBAStart = 0;
LBAEnd = 7;
begin
ResultInByte := 0;
for CurrentByte := LBAStart to LBAEnd do
begin
ResultInByte := ResultInByte shl 8;
ResultInByte := ResultInByte + Buffer[CurrentByte];
end;
result.LBASize := GetLBASize(Buffer);
result.UserSizeInKB := round(
ChangeDatasizeUnit(ResultInByte * result.LBASize, ByteToDenaryKB));
end;
function TNVMeBufferInterpreter.BufferToIdentifyDeviceResult(
const Buffer: TSmallBuffer): TIdentifyDeviceResult;
var
LargeBuffer: TLargeBuffer;
begin
Move(Buffer, LargeBuffer, SizeOf(Buffer));
result := LargeBufferToIdentifyDeviceResult(LargeBuffer);
end;
end.
|
{$F-,A+,O+,G+,R-,S+,I+,Q-,V-,B-,X+,T-,P-,D-,L-,N-,E+}
unit Comm;
interface
procedure cCheckIt;
procedure cCheckUser;
procedure cClearInBuffer;
procedure cClearOutBuffer;
function cCommInfo : Byte;
function cFossilInstalled : Boolean;
procedure cHangUp;
procedure cInitFossil;
function cModemRinging : Boolean;
procedure cModemWrite(S : String);
function cNoCarrier : Boolean;
function cOutBufferEmpty : Boolean;
procedure cRaiseDTR;
function cSetBaud(B : LongInt) : Boolean;
function cSetupCommunications : Boolean;
procedure cTerminateFossil;
implementation
uses Crt, Dos,
Global, Fossil, Strings, StatBar, Misc, Logs, Output,
DateTime;
function cSetBaud(B : LongInt) : Boolean;
begin
cSetBaud := True;
if not ModemIO then Exit;
cSetBaud := SetBaud(Modem^.ComPort,B,cCommInfo);
end;
function cOutBufferEmpty : Boolean;
begin
if not ModemIO then Exit;
cOutBufferEmpty := OutBufferEmpty(Modem^.ComPort);
end;
function cCommInfo : Byte;
var CommInfo : Byte;
begin
if (Modem^.Parity='N') and (Modem^.DataBits=8) and (Modem^.StopBits=1) then CommInfo := N81 else
if (Modem^.Parity='N') and (Modem^.DataBits=8) and (Modem^.StopBits=2) then CommInfo := N82 else
if (Modem^.Parity='N') and (Modem^.DataBits=7) and (Modem^.StopBits=1) then CommInfo := N71 else
if (Modem^.Parity='N') and (Modem^.DataBits=7) and (Modem^.StopBits=2) then CommInfo := N72 else
if (Modem^.Parity='E') and (Modem^.DataBits=8) and (Modem^.StopBits=1) then CommInfo := E81 else
if (Modem^.Parity='E') and (Modem^.DataBits=8) and (Modem^.StopBits=2) then CommInfo := E82 else
if (Modem^.Parity='E') and (Modem^.DataBits=7) and (Modem^.StopBits=1) then CommInfo := E71 else
if (Modem^.Parity='E') and (Modem^.DataBits=7) and (Modem^.StopBits=2) then CommInfo := E72 else
if (Modem^.Parity='O') and (Modem^.DataBits=8) and (Modem^.StopBits=1) then CommInfo := O81 else
if (Modem^.Parity='O') and (Modem^.DataBits=8) and (Modem^.StopBits=2) then CommInfo := O82 else
if (Modem^.Parity='O') and (Modem^.DataBits=7) and (Modem^.StopBits=1) then CommInfo := O71 else
if (Modem^.Parity='O') and (Modem^.DataBits=7) and (Modem^.StopBits=2) then CommInfo := O72 else
CommInfo := N81;
cCommInfo := CommInfo;
end;
function cSetupCommunications : Boolean;
var OK : Boolean;
begin
OK := True;
if (not ModemOff) and (ModemIO) then
begin
OK := cFossilInstalled;
if OK then ActivatePort(Modem^.ComPort);
if OK then OK := SetBaud(Modem^.ComPort,Modem^.BaudRate,cCommInfo);
end;
cSetupCommunications := OK;
end;
procedure cCheckIt;
begin
if UserOn then sbUpdate;
if not LocalIO then
begin
{ if (dtTimeStr12 = '6:42am') or
(dtTimeStr12 = '6:43am') or
(dtTimeStr12 = '6:44am') or
(dtTimeStr12 = '6:45am') or
(dtTimeStr12 = '6:46am') or
(dtTimeStr12 = '6:47am') or
(dtTimeStr12 = '6:48am') or
(dtTimeStr12 = '6:49am') or
(dtTimeStr12 = '6:50am') then HangUp := True;}
if (HangUp) and (not cNoCarrier) then
begin
HungUp := False;
if not asDoor then cHangUp;
RemoteOut := False;
LocalIO := True;
ModemIO := False;
end else
if cNoCarrier then
begin
HangUp := True;
HungUp := True;
logWrite('Carrier lost');
if not asDoor then cHangUp;
RemoteOut := False;
LocalIO := True;
ModemIO := False;
end;
end;
if oprType > oprDOS then mTimeSlice;
end;
procedure cCheckUser;
begin
if (not ChatModeOn) and (timeCheck) and (UserOn) and (LoggedIn) and (not HangUp) and (mTimeLeft('S') < 1) then
begin
oStringLn(strTimeExpired);
logWrite('User''s time expired.');
HangUp := True;
end;
cCheckIt;
end;
function cNoCarrier : Boolean;
begin
cNoCarrier := False;
if not ModemIO then Exit;
cNoCarrier := not CarrierDetected(Modem^.ComPort);
end;
function cModemRinging : Boolean;
begin
cModemRinging := (ModemIO) and (ModemRinging(Modem^.ComPort));
end;
procedure cClearOutBuffer;
begin
if ModemIO then ClearOutBuffer(Modem^.ComPort);
end;
procedure cClearInBuffer;
begin
if ModemIO then ClearInBuffer(Modem^.ComPort);
end;
procedure cHangUp;
begin
if ModemIO then
begin
DTR(Modem^.ComPort,LOWER);
Delay(500);
DTR(Modem^.ComPort,RAISE);
end;
end;
procedure cRaiseDTR;
begin
if ModemIO then DTR(Modem^.ComPort,RAISE);
end;
procedure cInitFossil;
begin
if ModemIO then ActivatePort(Modem^.ComPort);
end;
procedure cTerminateFossil;
begin
if ModemIO then DeactivatePort(Modem^.ComPort);
end;
function cFossilInstalled : Boolean;
begin
cFossilInstalled := (ModemOff) or (FossilPresent);
end;
procedure cModemWrite(S : String);
var P : Byte;
begin
if not ModemIO then Exit;
for P := 1 to Length(S) do
begin
case S[P] of
'|' : ComWrite(Modem^.ComPort,#13);
'~' : Delay(500);
'^' : cHangUp;
else ComWriteChar(Modem^.ComPort,S[P]);
end;
end;
end;
end. |
unit Broker_impl;
{This file was generated on 16 Jun 2000 16:15:16 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 broker.idl. }
{Delphi Pascal unit : Broker_impl }
{derived from IDL module : Broker }
interface
uses
SysUtils,
CORBA,
Broker_i,
Broker_c;
type
TMoneyMarket = class;
TMarginAccount = class;
TInvestmentAccount = class;
TMoneyMarket = class(TInterfacedObject, Broker_i.MoneyMarket)
protected
_interest_rate : Single;
public
constructor Create;
function interest_rate : Single;
end;
TMarginAccount = class(TInterfacedObject, Broker_i.MarginAccount)
protected
_margin_rate : Single;
public
constructor Create;
function margin_rate : Single;
end;
TInvestmentAccount = class(Broker_impl.TMoneyMarket, Broker_i.MarginAccount, Broker_i.InvestmentAccount)
protected
_margin_rate : Single;
_balance : Single;
public
constructor Create;
function balance : Single;
function margin_rate : Single;
function interest_rate : Single;
end;
implementation
uses ServerMain;
constructor TMoneyMarket.Create;
begin
inherited;
_interest_rate := 7.00;
end;
function TMoneyMarket.interest_rate : Single;
begin
Result := _interest_rate;
Form1.Memo1.Lines.Add('Got a Money Market Interest Rate request');
end;
constructor TMarginAccount.Create;
begin
inherited;
_margin_rate := 9.00;
end;
function TMarginAccount.margin_rate : Single;
begin
result := _margin_rate;
end;
constructor TInvestmentAccount.Create;
begin
inherited;
_margin_rate := Random * 10;
_balance := Random * 10000;
_interest_rate := 15.00;
end;
function TInvestmentAccount.balance : Single;
begin
Result := _balance;
Form1.Memo1.Lines.Add('Got a Margin Account Balance request');
end;
function TInvestmentAccount.margin_rate : Single;
begin
Result := _margin_rate;
Form1.Memo1.Lines.Add('Got a Margin Account Margin Rate request');
end;
function TInvestmentAccount.interest_rate : Single;
begin
result := _interest_rate;
end;
initialization
Randomize;
end.
|
unit Dominio;
interface
uses Classes, Data.DB,
{ helsonsant }
Util, DataUtil;
type
TCampo = class
private
FNome: string;
FDescricao: string;
FFlagChave: Boolean;
FFlagAtualizar: Boolean;
FVisivel: Boolean;
FTamanho: Integer;
FFormato: string;
FObrigatorio: Boolean;
public
constructor Create(const NomeDoCampo: string); reintroduce;
function Nome(const Nome: string): TCampo;
function Descricao(const Descricao: String): TCampo;
function AtivarChave: TCampo;
function AtivarAtualizacao: TCampo;
function DesativarAtualizacao: TCampo;
function AtivarVisualizacao: TCampo;
function DesativarVisualizacao: TCampo;
function Tamanho(const Tamanho: Integer): TCampo;
function Formato(const Formato: string): TCampo;
function TornarObrigatorio: TCampo;
function EhChave: Boolean;
function EhAtualizavel: Boolean;
function EhVisivel: Boolean;
function EhObrigatorio: Boolean;
function ObterNome: string;
function ObterTamanho: Integer;
function ObterFormato: string;
function ObterDescricao: string;
end;
TCampos = class(TStringList)
public
function Adicionar(const Campo: TCampo): TCampos;
function Campo(const NomeDoCampo: string): TCampo;
end;
TFabricaDeCampos = class
public
class function ObterCampo(const NomeDoCampo: string): TCampo;
class function ObterCampoChave(const NomeDoCampo: string): TCampo;
class function ObterCampoVisivel(const NomeDoCampo: string;
const Descricao: string; const Tamanho: Integer;
const Formato: string = ''): TCampo;
end;
TDominio = class;
TEntidades = class(TStringList)
public
function Adicionar(const Entidade: TDominio): TEntidades;
end;
TRegraDeNegocio = reference to function (Modelo: TObject): Boolean;
TDominio = class(TPersistent)
private
FEntidade: string;
FSql: TSql;
FCampos: TCampos;
FDetalhes: TEntidades;
FAntesDePostarRegistro: TDataSetNotifyEvent;
FRegraDeNegocioGerencial: TRegraDeNegocio;
public
constructor Create(const Entidade: string); reintroduce;
property EventoAntesDePostarRegistro: TDataSetNotifyEvent read FAntesDePostarRegistro;
property EventoRegraDeNegocioGerencial: TRegraDeNegocio read FRegraDeNegocioGerencial;
function Sql: TSql;
function Campos: TCampos;
function Detalhes: TEntidades;
function Entidade: string;
function AntesDePostarRegistro(const Evento: TDataSetNotifyEvent): TDominio;
function RegraDeNegocioGerencial(
const RegraDeNegocio: TRegraDeNegocio): TDominio;
end;
implementation
{ TCampo }
function TCampo.AtivarAtualizacao: TCampo;
begin
Self.FFlagAtualizar := True;
Result := Self;
end;
function TCampo.AtivarChave: TCampo;
begin
Self.FFlagChave := True;
Result := Self;
end;
function TCampo.AtivarVisualizacao: TCampo;
begin
Self.FVisivel := True;
Result := Self;
end;
constructor TCampo.Create(const NomeDoCampo: string);
begin
inherited Create;
Self.FNome := NomeDoCampo;
Self.FFlagChave := False;
Self.FFlagAtualizar := True;
Self.FVisivel := False;
Self.FObrigatorio := False;
end;
function TCampo.DesativarAtualizacao: TCampo;
begin
Self.FFlagAtualizar := False;
Result := Self;
end;
function TCampo.DesativarVisualizacao: TCampo;
begin
Self.FVisivel := False;
Result := Self;
end;
function TCampo.Descricao(const Descricao: String): TCampo;
begin
Self.FDescricao := Descricao;
Result := Self;
end;
function TCampo.EhAtualizavel: Boolean;
begin
Result := Self.FFlagAtualizar;
end;
function TCampo.EhChave: Boolean;
begin
Result := Self.FFlagChave;
end;
function TCampo.EhObrigatorio: Boolean;
begin
Result := Self.FObrigatorio;
end;
function TCampo.EhVisivel: Boolean;
begin
Result := Self.FVisivel;
end;
function TCampo.Formato(const Formato: string): TCampo;
begin
Self.FFormato := Formato;
Result := Self;
end;
function TCampo.Nome(const Nome: string): TCampo;
begin
Self.FNome := Nome;
Result := Self;
end;
function TCampo.ObterDescricao: string;
begin
Result := Self.FDescricao;
end;
function TCampo.ObterFormato: string;
begin
Result := Self.FFormato;
end;
function TCampo.ObterNome: string;
begin
Result := Self.FNome;
end;
function TCampo.ObterTamanho: Integer;
begin
Result := Self.FTamanho;
end;
function TCampo.Tamanho(const Tamanho: Integer): TCampo;
begin
Self.FTamanho := Tamanho;
Result := Self;
end;
function TCampo.TornarObrigatorio: TCampo;
begin
Self.FObrigatorio := True;
Result := Self;
end;
{ TFabricaDeCampos }
class function TFabricaDeCampos.ObterCampo(
const NomeDoCampo: string): TCampo;
begin
Result := TCampo.Create(NomeDoCampo)
.AtivarAtualizacao;
end;
class function TFabricaDeCampos.ObterCampoChave(
const NomeDoCampo: string): TCampo;
begin
Result := TCampo.Create(NomeDoCampo)
.AtivarChave
.AtivarAtualizacao;
end;
class function TFabricaDeCampos.ObterCampoVisivel(const NomeDoCampo,
Descricao: string; const Tamanho: Integer;
const Formato: string): TCampo;
begin
Result := TCampo.Create(NomeDoCampo)
.Descricao(Descricao)
.AtivarChave
.AtivarAtualizacao
.AtivarVisualizacao
.Tamanho(Tamanho)
.Formato(Formato);
end;
{ TDominio }
function TDominio.AntesDePostarRegistro(const Evento: TDataSetNotifyEvent): TDominio;
begin
Self.FAntesDePostarRegistro := Evento;
Result := Self;
end;
function TDominio.Campos: TCampos;
begin
Result := Self.FCampos;
end;
constructor TDominio.Create(const Entidade: string);
begin
inherited Create;
Self.FEntidade := Entidade;
Self.FSql := TSql.Create;
Self.FCampos := TCampos.Create;
Self.FDetalhes := TEntidades.Create;
end;
function TDominio.Detalhes: TEntidades;
begin
Result := Self.FDetalhes;
end;
function TDominio.Entidade: string;
begin
Result := Self.FEntidade;
end;
function TDominio.Sql: TSql;
begin
Result := Self.FSql;
end;
function TDominio.RegraDeNegocioGerencial(
const RegraDeNegocio: TRegraDeNegocio): TDominio;
begin
Self.FRegraDeNegocioGerencial := RegraDeNegocio;
Result := Self;
end;
{ TCampos }
function TCampos.Adicionar(const Campo: TCampo): TCampos;
begin
Self.AddObject(Campo.ObterNome, Campo);
Result := Self;
end;
function TCampos.Campo(const NomeDoCampo: string): TCampo;
var
_indice: Integer;
begin
_indice := Self.IndexOf(NomeDoCampo);
Result := nil;
if _indice > -1 then
Result := Self.GetObject(_indice) as TCampo;
end;
{ TEntidades }
function TEntidades.Adicionar(const Entidade: TDominio): TEntidades;
begin
Self.AddObject(Entidade.Entidade, Entidade);
Result := Self;
end;
end.
|
unit h_Functions;
interface
uses SysUtils, Variants, winapi.windows, System.classes, vcl.forms, vcl.dialogs, vcl.Graphics, vcl.controls, vcl.stdctrls,
cxgraphics, cxGridCustomTableView, FireDac.comp.client, cxtextedit, RegExpr, WinSvc, TLHelp32,
System.Win.registry,
v_dir, v_Env,
dateutils, vcl.Printers,
cxCheckBox;
function GetConsoleWindow: HWND; stdcall; external 'kernel32';
type
TcxViewInfoAcess = class(TcxGridTableDataCellViewInfo);
TcxPainterAccess = class(TcxGridTableDataCellPainter);
type
TFunctions = class
public
class function CleanSpecialChars(Value: String; const ReplaceWith: string = ''): string;
class function ClearUTF8(Value: string): string;
// Remover caracteres especiais ou substituílos por um caractere específico
class function replace(const _value, _from, _to: Variant; const ResultType: Integer = 256): Variant; overload; static;
class function replace(const _value: Variant; _from: array of Variant; _value_to_replace: Variant; const ResultType: Integer = 256): Variant;
overload; static;
class function replace(const _value, _from: Variant; const ResultType: Integer = 256): Variant; overload; static;
class function replace(const _value: Variant; _from: array of Variant; const ResultType: Integer = 256): Variant; overload; static;
// Substituir valores e definir tipo de retorno da variável
class procedure Write_Log(xMessage: String);
// Escrever Log
class procedure ExecuteCommand(xComand: String; const sw_state: Integer = sw_hide);
// Executar comandos no SO
class function SearchFiles(Dir, Pattern: string): TArray<string>;
// Buscar arquivos em um diretório por um identificador específico ou extensão
class function LoadContent(FromFile: string): string;
// Carregar Conteúdo de um arquivo
class function IfThen(const __Condition: boolean; const if_True: Variant; const if_False: Variant): Variant; overload;
class function IfThen(const ACondition: boolean; const ATrue: Char; const AFalse: Char = #0): Char; overload;
class function IfThen(const ValueToCompare: Variant; const arrPossibilities: array of Variant; const ArrTrue: array of Variant): Variant; overload;
class function IfThen(const __Condition: boolean; const if_True, if_False: TFDQuery): TFDQuery; overload;
class function IfThen(const arrPossibilities: array of boolean; ArrTrue: array of Variant): Variant; overload;
class function IfThen(const __Condition: boolean; const if_True, if_False: tobject): tobject; overload;
// Funções para comparações diretas com retornos de valores
class function CheckOpen(Ref: TForm): boolean;
// Vericiar se a janela já está aberta
class function SelectFile(CurrentDir: string = 'C:\'; Filters: string = ''): string;
class function SelectFolder: string;
// Abrir dialog para selecionar arquivos
class function ColorByStatus(Value: Variant; arrValues: array of Variant; ArrColors: array of Integer): Integer;
// Retorna cor baseada nas possibilidades descritas
class procedure ChangeEnabled(controls: array of tcontrol; state: boolean);
// Alterar enabled de um grupo de componentes
class procedure ChangeChecked(controls: array of tcontrol; state: boolean);
// Alterar checks states
class procedure ClearFields(edits: array of TEdit); overload;
class procedure ClearFields(form: TForm); overload;
// Limpar Edits
class procedure SaveToFile(const FileName, Content: string);
// Salvar algum conteúdo para um arquivo
class function ArrayOf(const Value: string; const ArrayFilled: array of string): boolean;
// Verificar se todos os index de um array são identicos ao valor informado
class procedure StripedGrid(ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo);
// Zebrar cxGrid
class function arrToStr(arrValue: array of string): string; overload;
class function arrToStr(arrValue: TStringList): string; overload;
class function arrToStr(arrInteger: array of Integer): string; overload;
// transformar um array de strings em uma string
class procedure setImageByStatus(Value: array of Variant; IndexValue: array of Integer; ACanvas: TcxCanvas; fieldIndex: Integer; imgList: tcxImageList;
var AViewInfo: TcxGridTableDataCellViewInfo);
// selecionar uma imagem em um grid por um status
class function genData(Value: string; countOf: Integer): string;
// retorna uma determinada quantidade de caracteres definidos pelos parametros
class function getSubRegex(const Value: string; Regex: string): string;
// retorna os matches de uma consulta por regex
class function matchRegex(const Value: string; regexToValidate: string): boolean;
class function OnlyNumbers(Tecla: Char): Char;
// permite apenas numeros nos campos das views
class function OnlyLetters(key: Char): Char;
// only Letters allowed into fields
class function isKeyNumLetter(Tecla: Word): boolean;
// verifica se a key digitada é um valor alphanumerico
class function CheckService(nService: string): boolean;
// veriifca se o serviço está instalado
class function CheckProcess(const ExeName: String): Integer;
// conta a quantidade de instancias abertas de um exe
class function isRunning(const ExeName: string): boolean;
// verifica se um programa está em execução
class procedure RunOnStartup(sProgTitle, sCmdLine: string; bRunOnce: boolean);
// escrever no registro do computador para aplicação rodar ao iniciar
class procedure KillProcess(ExeFileName: string);
// matar um processo
class function CodeDecode(StrValue: String; Cryptit: boolean): String;
// criptografar strings
class function getPrinters: TStrings;
// list all printers installed in the machine
class function validatePrinter(Value: string): string;
// validate printer
class function getIndex(const i: Integer; arrValues: array of Variant): Variant;
// get index in array
class procedure configureSSLTTL;
// configuração de conteúdo para emissão de NF
class function AttachDisk(pathfrom: string): string;
// mapping a disk on pc
class function ValidateVariant(Value: Variant): Variant;
// verifica se variant está nulo e retorna 0 caso aceite a condição
class procedure RunExe(path: string);
// execute a windows .exe file with following parameters /silent /nocancel
class function GetSubArray(arrValues: array of Variant; indexToReturn: array of boolean): TArray<Variant>;
// pass a array and mark with true or false the indexes wich must return
class procedure changeAttr(attrs: array of Variant; Value: Variant);
// change a group of attrs with value
/// <summary>
/// Verifica se um form está instanciado.
/// Caso esteja, o mata e libera a instancia da memória
/// </summary>
/// <param name="referencedForm">
/// Form a ser verificado
/// </param>
class procedure releaseForm(referencedForm: TForm);
class function sumField(qry: TFDQuery; field: string): extended;
end;
implementation
uses h_Files;
class function TFunctions.CleanSpecialChars(Value: String; const ReplaceWith: string): string;
begin
Value := replace(Value, '/', ReplaceWith);
Value := replace(Value, '@', ReplaceWith);
Value := replace(Value, '$', ReplaceWith);
Value := replace(Value, '#', ReplaceWith);
Value := replace(Value, '!', ReplaceWith);
Value := replace(Value, '%', ReplaceWith);
Value := replace(Value, '¨', ReplaceWith);
Value := replace(Value, '&', ReplaceWith);
Value := replace(Value, '*', ReplaceWith);
Value := replace(Value, '(', ReplaceWith);
Value := replace(Value, ')', ReplaceWith);
Value := replace(Value, '-', ReplaceWith);
Value := replace(Value, '.', ReplaceWith);
Value := replace(Value, ',', ReplaceWith);
Value := replace(Value, #39, ReplaceWith);
Value := replace(Value, '^', ReplaceWith);
Value := replace(Value, '°', ReplaceWith);
Value := replace(Value, '?', ReplaceWith);
Value := replace(Value, 'ª', ReplaceWith);
Value := replace(Value, '´', ReplaceWith);
Value := replace(Value, '`', ReplaceWith);
Value := replace(Value, '¹', ReplaceWith);
Value := replace(Value, '²', ReplaceWith);
Value := replace(Value, '³', ReplaceWith);
Value := replace(Value, '£', ReplaceWith);
Value := replace(Value, '¢', ReplaceWith);
Value := replace(Value, '¬', ReplaceWith);
Value := replace(Value, '§', ReplaceWith);
Value := replace(Value, '~', ReplaceWith);
Value := replace(Value, '+', ReplaceWith);
Value := replace(Value, '=', ReplaceWith);
Value := replace(Value, '"', ReplaceWith);
Value := replace(Value, '\', ReplaceWith);
Value := replace(Value, '|', ReplaceWith);
Value := replace(Value, '[', ReplaceWith);
Value := replace(Value, ']', ReplaceWith);
Value := replace(Value, '{', ReplaceWith);
Value := replace(Value, '}', ReplaceWith);
Value := replace(Value, ':', ReplaceWith);
Value := replace(Value, ';', ReplaceWith);
Value := replace(Value, '>', ReplaceWith);
Value := replace(Value, '<', ReplaceWith);
Value := replace(Value, 'Ç', 'C');
Value := replace(Value, 'ç', 'c');
Value := replace(Value, '"', ReplaceWith);
Value := replace(Value, 'º', ReplaceWith);
Value := replace(Value, ':', ReplaceWith);
result := Value;
end;
class procedure TFunctions.ClearFields(form: TForm);
var
i: Integer;
begin
for i := 0 to form.ComponentCount - 1 do
if form.Components[i] is TEdit then
TEdit(form.Components[i]).Clear;
end;
class function TFunctions.ClearUTF8(Value: string): string;
const
arrLc: string = 'ÁÂÃÀÉÊÈÍÎÌÓÔÕÒÚÛÙáâãàéêèíîìóôõòúûùÇç';
arrL: string = 'AAAAEEEIIIOOOOUUUaaaaeeeiiioooouuuCc';
var
i, x: Integer;
begin
if Value <> emptystr then
for i := Low(arrLc) to High(arrLc) do
for x := 1 to length(Value) do
if Value[x] = arrLc[i] then
Value[x] := arrL[i];
result := Value;
end;
class function TFunctions.replace(const _value: Variant; _from: array of Variant; _value_to_replace: Variant; const ResultType: Integer): Variant;
var
i: Integer;
xvalue: String;
begin
xvalue := _value;
for i := Low(_from) to High(_from) do
xvalue := varastype(StringReplace(xvalue, _from[i], _value_to_replace, [RFREPLACEALL]), ResultType);
result := xvalue;
end;
class function TFunctions.replace(const _value, _from, _to: Variant; const ResultType: Integer): Variant;
var
xvalue: Variant;
begin
xvalue := _value;
if (xvalue = emptystr) and (ResultType in [vardouble, varInteger, varInt64, varDate]) then
xvalue := 0;
result := varastype(StringReplace(xvalue, _from, _to, [RFREPLACEALL]), ResultType);
end;
class procedure TFunctions.releaseForm(referencedForm: TForm);
begin
if TFunctions.CheckOpen(referencedForm) then
begin
referencedForm.Close;
referencedForm := nil;
end;
end;
class function TFunctions.replace(const _value: Variant; _from: array of Variant; const ResultType: Integer): Variant;
begin
result := replace(_value, _from, '', ResultType);
end;
class function TFunctions.replace(const _value, _from: Variant; const ResultType: Integer): Variant;
begin
result := replace(_value, _from, '', ResultType);
end;
class procedure TFunctions.Write_Log(xMessage: string);
procedure CompacLogs;
var
FilesCompac: TArray<String>;
i: smallint;
mes_anterior, compacarq: string;
begin
try
mes_anterior := formatdatetime('mm_yyyy', incmonth(date, -1));
compacarq := TDir.LogFolder + 'SMC_LIGHT_' + mes_anterior + '.zip';
if (formatdatetime('dd', now) = '01') and (not FileExists(compacarq)) then
begin
FilesCompac := SearchFiles(TDir.LogFolder, '*' + mes_anterior + '.log');
if FilesCompac <> nil then
begin
for i := Low(FilesCompac) to High(FilesCompac) do
begin
if TFunctions.replace(FilesCompac[i], ' ') <> '' then
begin
TFile.CpacDpac(TDir.LogFolder + FilesCompac[i], compacarq, true);
TFile.Delete(TDir.LogFolder + FilesCompac[i]);
end;
end;
Write_Log('Logs do mês ' + mes_anterior + ' foram compactados em ' + compacarq + ' !');
end;
end;
except
end;
end;
var
xLogFile: TextFile;
msg: String;
begin
try
CompacLogs;
xMessage := StringReplace(xMessage, slinebreak, ' ', [RFREPLACEALL]);
AssignFile(xLogFile, TDir.LogFile);
if FileExists(TDir.LogFile) then
Append(xLogFile)
else
Rewrite(xLogFile);
msg := formatdatetime('[dd/mm/yyyy HH:MM:SS ', now) + 'PC(' + TEnv.MachineName + ')IP(' + TEnv.getIp(TEnv.MachineName) + ')USER(' + TEnv.username + ')]: '
+ xMessage;
writeln(xLogFile, msg);
CloseFile(xLogFile);
except
exit
end;
end;
class procedure TFunctions.ExecuteCommand(xComand: String; const sw_state: Integer = sw_hide);
var
tmpStartupInfo: TStartupInfo;
tmpProcessInformation: TProcessInformation;
tmpProgram: String;
begin
tmpProgram := trim(xComand);
FillChar(tmpStartupInfo, SizeOf(tmpStartupInfo), #0);
with tmpStartupInfo do
begin
cb := SizeOf(TStartupInfo);
wShowWindow := sw_hide;
dwFlags := STARTF_USESHOWWINDOW;
lpDesktop := nil;
hStdOutput := 0;
end;
if CreateProcess(nil, PCHAR(tmpProgram), nil, nil, false, CREATE_NO_WINDOW or NORMAL_PRIORITY_CLASS, nil, nil, tmpStartupInfo, tmpProcessInformation) then
begin
while WaitForSingleObject(tmpProcessInformation.hProcess, 10) > 0 do
begin
WaitForSingleObject(tmpProcessInformation.hProcess, INFINITE);
end;
CloseHandle(tmpProcessInformation.hProcess);
CloseHandle(tmpProcessInformation.hThread);
end;
end;
class function TFunctions.SearchFiles(Dir, Pattern: string): TArray<string>;
var
qtderec: Integer;
searchResult: TSearchRec;
Files: TArray<string>;
begin
qtderec := 1;
if findfirst(Dir + Pattern, faAnyFile, searchResult) = 0 then
begin
SetLength(Files, qtderec);
repeat
Files[qtderec - 1] := searchResult.Name;
Inc(qtderec);
SetLength(Files, qtderec);
until FindNext(searchResult) <> 0;
end;
result := Files;
end;
class function TFunctions.LoadContent(FromFile: string): string;
var
str_cont: TStringList;
Content: string;
begin
str_cont := TStringList.create;
str_cont.LoadFromFile(FromFile);
Content := str_cont.Text;
str_cont.destroy;
result := Content;
end;
class function TFunctions.IfThen(const ACondition: boolean; const ATrue: Char; const AFalse: Char = #0): Char;
begin
if ACondition then
result := ATrue
else
result := AFalse
end;
class function TFunctions.IfThen(const __Condition: boolean; const if_True: Variant; const if_False: Variant): Variant;
begin
if __Condition then
result := if_True
else
result := if_False
end;
class function TFunctions.IfThen(const ValueToCompare: Variant; const arrPossibilities: array of Variant; const ArrTrue: array of Variant): Variant;
var
i: Integer;
begin
for i := Low(arrPossibilities) to High(arrPossibilities) do
if ValueToCompare = arrPossibilities[i] then
begin
result := ArrTrue[i];
Break;
end
else
result := ValueToCompare;
end;
class function TFunctions.IfThen(const __Condition: boolean; const if_True, if_False: TFDQuery): TFDQuery;
begin
if __Condition then
result := if_True
else
result := if_False;
end;
class function TFunctions.IfThen(const arrPossibilities: array of boolean; ArrTrue: array of Variant): Variant;
var
i: Integer;
begin
for i := Low(arrPossibilities) to High(arrPossibilities) do
if arrPossibilities[i] then
begin
result := ArrTrue[i];
Break;
end;
end;
class function TFunctions.CheckOpen(Ref: TForm): boolean;
var
i: Word;
begin
result := false;
for i := 0 to Screen.FormCount - 1 do
if Screen.forms[i] = Ref then
begin
if (Ref.Enabled = true) and (Ref.Visible = true) then
Ref.SetFocus;
result := true;
Break;
end;
end;
class function TFunctions.SelectFile(CurrentDir: string = 'C:\'; Filters: string = ''): string;
var
openDialog: topendialog;
begin
try
openDialog := topendialog.create(nil);
openDialog.InitialDir := CurrentDir;
openDialog.Options := [ofFileMustExist];
openDialog.Filter := Filters + '|Todos os Tipos|*.*';
openDialog.FilterIndex := 1;
if openDialog.Execute then
result := openDialog.FileName
else
result := emptystr;
finally
openDialog.Free;
end;
end;
class function TFunctions.SelectFolder: string;
var
openDialog: TFileOpenDialog;
begin
try
openDialog := TFileOpenDialog.create(nil);
openDialog.Options := [fdoPickFolders, fdoPathMustExist, fdoForceFileSystem];
openDialog.OkButtonLabel := 'Selecionar pasta';
if openDialog.Execute then
result := openDialog.FileName
else
result := emptystr;
finally
openDialog.Free;
end;
end;
class function TFunctions.ColorByStatus(Value: Variant; arrValues: array of Variant; ArrColors: array of Integer): Integer;
var
kindof, i: Integer;
begin
result := clWhite;
kindof := varType(Value) and VarTypeMask;
if (kindof = varInteger) or (kindof = vardouble) then
begin
if Value <= arrValues[0] then
result := ArrColors[0]
else if (Value > arrValues[0]) and (Value < arrValues[1]) then
result := ArrColors[1]
else if Value >= arrValues[1] then
result := ArrColors[2]
end
else
begin
for i := Low(arrValues) to High(arrValues) do
if Value = arrValues[i] then
result := ArrColors[i]
end;
end;
class procedure TFunctions.configureSSLTTL;
begin
TFunctions.ExecuteCommand('reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /f /v "SecureProtocols" /t REG_DWORD /d "160"');
end;
class function TFunctions.arrToStr(arrValue: TStringList): string;
var
arr_str: array of string;
i: Integer;
begin
SetLength(arr_str, arrValue.Count);
for i := Low(arr_str) to High(arr_str) do
arr_str[i] := arrValue.Strings[i];
result := self.arrToStr(arr_str);
end;
class function TFunctions.AttachDisk(pathfrom: string): string;
type
TTipoDrive = (tdRemovivel, tdFixo, tdRede, tdCDROM, tdRAMDISK, tdNenhum);
function GetTipoDrive(LetraDrive: Char): TTipoDrive;
begin
case GetDriveType(PCHAR(LetraDrive + '\')) of
DRIVE_REMOVABLE:
result := tdRemovivel;
DRIVE_FIXED:
result := tdFixo;
DRIVE_REMOTE:
result := tdRemovivel;
DRIVE_CDROM:
result := tdCDROM;
DRIVE_RAMDISK:
result := tdRAMDISK;
else
// DRIVE_NO_ROOT_DIR :
result := tdNenhum;
end;
end;
function DriveExist(LetrDrive: Char): boolean;
begin
result := GetTipoDrive(LetrDrive) <> tdNenhum;
end;
var
err: DWord;
PServer, PLetra: PCHAR;
i: Integer;
Begin
PLetra := 'M:';
if not DriveExist(Char(PLetra)) then
begin
PServer := stringtoolestr(pathfrom + #0);
WNetAddConnection(PServer, '', PLetra);
end;
End;
class procedure TFunctions.changeAttr(attrs: array of Variant; Value: Variant);
var
i: Integer;
begin
for i := Low(attrs) to High(attrs) do
attrs[i] := Value;
end;
class procedure TFunctions.ChangeChecked(controls: array of tcontrol; state: boolean);
var
i: Integer;
begin
for i := 0 to length(controls) - 1 do
begin
if controls[i] is TCheckBox then
TCheckBox(controls[i]).Checked := state
else if controls[i] is TcxCheckBox then
TcxCheckBox(controls[i]).Checked := state
end;
end;
class procedure TFunctions.ChangeEnabled(controls: array of tcontrol; state: boolean);
var
i: Integer;
begin
for i := 0 to length(controls) - 1 do
begin
controls[i].Enabled := state;
end;
end;
class procedure TFunctions.ClearFields(edits: array of TEdit);
var
i: Integer;
begin
for i := 0 to length(edits) - 1 do
begin
edits[i].Text := '';
end;
end;
class procedure TFunctions.SaveToFile(const FileName, Content: string);
var
xxFile: TStringList;
begin
xxFile := TStringList.create;
xxFile.Text := Content;
xxFile.SaveToFile(FileName);
xxFile.Free;
end;
class function TFunctions.ArrayOf(const Value: string; const ArrayFilled: array of string): boolean;
var
i: Integer;
begin
for i := Low(ArrayFilled) to High(ArrayFilled) do
if Value = ArrayFilled[i] then
result := true
else
begin
result := false;
Break;
end;
end;
class procedure TFunctions.StripedGrid(ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo);
begin
if Odd(AViewInfo.GridRecord.RecordIndex) Then
ACanvas.Brush.Color := clWebGainsboro
else
ACanvas.Brush.Color := clWhite;
if AViewInfo.GridRecord.Selected then
begin
ACanvas.Brush.Color := rgb(24, 108, 242);
ACanvas.font.Color := clWhite;
end;
end;
class function TFunctions.sumField(qry: TFDQuery; field: string): extended;
var
_qry: TFDQuery;
begin
result := 0;
_qry := qry;
_qry.Fetchall;
_qry.First;
with _qry do
while not eof do
begin
result := result + fieldbyname(field).AsExtended;
next;
end;
end;
class function TFunctions.validatePrinter(Value: string): string;
var
hostname: string;
begin
hostname := '\\' + TEnv.MachineName + '\';
result := TFunctions.IfThen(copy(Value, 1, length(hostname)) = hostname, replace(Value, hostname), Value);
end;
class function TFunctions.ValidateVariant(Value: Variant): Variant;
begin
result := TFunctions.IfThen(Value = null, 0, varastype(Value, vardouble));
end;
class function TFunctions.matchRegex(const Value: string; regexToValidate: string): boolean;
begin
result := (self.getSubRegex(Value, regexToValidate) <> '');
end;
class function TFunctions.arrToStr(arrValue: array of string): string;
var
i: Integer;
begin
if length(arrValue) <> 0 then
begin
result := arrValue[0];
for i := 1 to High(arrValue) do
result := result + ',' + arrValue[i];
end;
end;
class procedure TFunctions.setImageByStatus(Value: array of Variant; IndexValue: array of Integer; ACanvas: TcxCanvas; fieldIndex: Integer;
imgList: tcxImageList; var AViewInfo: TcxGridTableDataCellViewInfo);
var
APainter: TcxPainterAccess;
procedure SetImage(Value: array of Variant; IndexValue: array of Integer);
var
i: Integer;
begin
for i := Low(Value) to High(Value) do
if AViewInfo.GridRecord.Values[fieldIndex] = Value[i] then
with AViewInfo.ClientBounds do
imgList.Draw(ACanvas.Canvas, Left + 3, Top + 1, IndexValue[i]);
end;
begin
if not(AViewInfo.EditViewInfo is TcxCustomTextEditViewInfo) then
exit;
APainter := TcxPainterAccess(TcxViewInfoAcess(AViewInfo).GetPainterClass.create(ACanvas, AViewInfo));
with APainter do
begin
try
with TcxCustomTextEditViewInfo(AViewInfo.EditViewInfo).TextRect do
Left := Left + imgList.Width + 1;
DrawContent;
DrawBorders;
SetImage(Value, IndexValue);
finally
Free;
end;
end;
end;
class function TFunctions.genData(Value: string; countOf: Integer): string;
var
i: Integer;
begin
for i := 1 to countOf do
result := result + Value;
end;
class function TFunctions.getIndex(const i: Integer; arrValues: array of Variant): Variant;
begin
result := arrValues[i]
end;
class function TFunctions.getPrinters: TStrings;
var
prt: string;
prtList: TStringList;
begin
result := nil;
prtList := TStringList.create;
for prt in printer.Printers do
prtList.Append(IfThen(copy(prt, 1, 2) = '\\', prt, '\\' + TEnv.MachineName + '\' + prt));
if prtList.Count <> 0 then
result := prtList;
end;
class function TFunctions.GetSubArray(arrValues: array of Variant; indexToReturn: array of boolean): TArray<Variant>;
var
i: Integer;
begin
if length(arrValues) <> length(indexToReturn) then
raise Exception.create('[GetSubArrayError]: Arrays must have the same length.');
SetLength(result, length(arrValues));
for i := Low(arrValues) to High(arrValues) do
if indexToReturn[i] then
result[i] := arrValues[i];
end;
class function TFunctions.getSubRegex(const Value: string; Regex: string): string;
var
r: TRegExpr;
begin
result := '';
r := TRegExpr.create;
try
r.Expression := Regex;
if r.Exec(Value) then
REPEAT
result := result + r.Match[0];
UNTIL not r.ExecNext;
finally
r.Free;
end;
end;
class function TFunctions.OnlyLetters(key: Char): Char;
begin
if not(key in ['a' .. 'z', 'A' .. 'Z', Char(8), Char(3), Char(22), Char(32), Char(24), Char(127)]) then
result := #0
else
result := key;
{ Char(3) = Ctrl C
Char(8) = BackSpace
Char(22) = Ctrl V
Char(24) = Ctrl X
Char(127) = Del }
end;
class function TFunctions.OnlyNumbers(Tecla: Char): Char;
begin
if not(Tecla in ['0' .. '9', Char(3), Char(8), Char(22), Char(24), Char(44), Char(127)]) then
result := #0
else
result := Tecla;
{ Char(3) = Ctrl C
Char(8) = BackSpace
Char(22) = Ctrl V
Char(24) = Ctrl X
Char(44) = ,
Char(127) = Del }
end;
class function TFunctions.isKeyNumLetter(Tecla: Word): boolean;
begin
if Tecla in [Word('0') .. Word('9'), Word('a') .. Word('z'), Word('A') .. Word('Z'), Word(VK_BACK), Word(VK_DELETE)] then
result := true
else
result := false;
end;
class function TFunctions.CheckService(nService: string): boolean;
const
SERVICE_KERNEL_DRIVER = $00000001;
SERVICE_FILE_SYSTEM_DRIVER = $00000002;
SERVICE_ADAPTER = $00000004;
SERVICE_RECOGNIZER_DRIVER = $00000008;
SERVICE_DRIVER = (SERVICE_KERNEL_DRIVER or SERVICE_FILE_SYSTEM_DRIVER or SERVICE_RECOGNIZER_DRIVER);
SERVICE_WIN32_OWN_PROCESS = $00000010;
SERVICE_WIN32_SHARE_PROCESS = $00000020;
SERVICE_WIN32 = (SERVICE_WIN32_OWN_PROCESS or SERVICE_WIN32_SHARE_PROCESS);
SERVICE_INTERACTIVE_PROCESS = $00000100;
SERVICE_TYPE_ALL = (SERVICE_WIN32 or SERVICE_ADAPTER or SERVICE_DRIVER or SERVICE_INTERACTIVE_PROCESS);
procedure ServiceGetList(sMachine: string; dwServiceType, dwServiceState: DWord; slServicesList: TStrings);
const
cnMaxServices = 4096;
type
TSvcA = array [0 .. cnMaxServices] of TEnumServiceStatus;
PSvcA = ^TSvcA;
var
j: Integer;
schm: SC_Handle;
nServices, nResumeHandle, nBytesNeeded: DWord;
ssa: PSvcA;
wideStr: pwidechar;
begin
schm := OpenSCManager(PCHAR(sMachine), Nil, SC_MANAGER_ALL_ACCESS);
if (schm > 0) then
begin
nResumeHandle := 0;
New(ssa);
EnumServicesStatus(schm, dwServiceType, dwServiceState, ssa^[0], SizeOf(ssa^), nBytesNeeded, nServices, nResumeHandle);
for j := 0 to nServices - 1 do
begin
wideStr := ssa^[j].lpServiceName;
slServicesList.Add(String(AnsiString(wideStr)));
end;
Dispose(ssa);
CloseServiceHandle(schm);
end;
end;
var
list: TStringList;
i: Integer;
begin
list := TStringList.create;
ServiceGetList('', SERVICE_WIN32, SERVICE_STATE_ALL, list);
result := (list.IndexOf(nService) <> -1);
list.Free;
end;
class function TFunctions.CheckProcess(const ExeName: String): Integer;
var
ContinueLoop: BOOL;
FSnapshotHandle: THandle;
FProcessEntry32: TProcessEntry32;
begin
try
FSnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
FProcessEntry32.dwSize := SizeOf(FProcessEntry32);
ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32);
result := 0;
while Integer(ContinueLoop) <> 0 do
begin
if ((UpperCase(extractfilename(FProcessEntry32.szExeFile)) = UpperCase(ExeName)) or (UpperCase(FProcessEntry32.szExeFile) = UpperCase(ExeName))) then
Inc(result);
ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32);
end;
CloseHandle(FSnapshotHandle);
except
on e: Exception do
begin
raise Exception.create(e.Message + slinebreak + 'Erro ao iniciar o sistema!');
Write_Log(e.Message + slinebreak + 'Erro ao iniciar o sistema!');
end;
end;
end;
class function TFunctions.isRunning(const ExeName: string): boolean;
begin
result := (CheckProcess(ExeName) > 0);
end;
class procedure TFunctions.RunExe(path: string);
begin
self.ExecuteCommand(path + ' /verysilent /nocancel');
end;
class procedure TFunctions.RunOnStartup(sProgTitle, sCmdLine: string; bRunOnce: boolean);
var
sKey: string;
reg: TRegIniFile;
begin
if (bRunOnce) then
sKey := 'Once'
else
sKey := '';
reg := TRegIniFile.create('');
reg.RootKey := HKEY_LOCAL_MACHINE;
reg.WriteString('Software\Microsoft' + 'Windows\CurrentVersion\Run\' + sKey + #0, sProgTitle, sCmdLine);
reg.Free;
end;
class procedure TFunctions.KillProcess(ExeFileName: string);
const
PROCESS_TERMINATE = $0001;
var
ContinueLoop: BOOL;
FSnapshotHandle: THandle;
FProcessEntry32: TProcessEntry32;
begin
FSnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
FProcessEntry32.dwSize := SizeOf(FProcessEntry32);
ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32);
while Integer(ContinueLoop) <> 0 do
begin
if ((UpperCase(extractfilename(FProcessEntry32.szExeFile)) = UpperCase(ExeFileName)) or (UpperCase(FProcessEntry32.szExeFile) = UpperCase(ExeFileName)))
then
TerminateProcess(OpenProcess(PROCESS_TERMINATE, BOOL(0), FProcessEntry32.th32ProcessID), 0);
ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32);
end;
CloseHandle(FSnapshotHandle);
end;
class function TFunctions.CodeDecode(StrValue: String; Cryptit: boolean): String;
var
Simbolos: array [0 .. 2] of String;
x: Integer;
begin
Simbolos[1] := 'ABCDEFGHIJLMNOPQRSTUVXZYWKabcdefghijlmnopqrstuvxzywk1234567890 ~!@#$%^&*()/_-';
Simbolos[2] := 'ÂÀ©Øû׃çêùÿ5Üø£úñѪº¿®¬¼ëèïÙýÄÅÉæÆôöò»ÁáâäàåíóÇüé¾¶§÷ÎÏ-+ÌÓ߸°¨·¹³²Õµþîì¡«½│♦○';
if Cryptit then
begin
for x := 1 to length(trim(StrValue)) do
if pos(copy(StrValue, x, 1), Simbolos[1]) > 0 then
result := result + copy(Simbolos[2], pos(copy(StrValue, x, 1), Simbolos[1]), 1);
end
else
begin
for x := 1 to length(trim(StrValue)) do
if pos(copy(StrValue, x, 1), Simbolos[2]) > 0 then
result := result + copy(Simbolos[1], pos(copy(StrValue, x, 1), Simbolos[2]), 1);
end;
end;
class function TFunctions.IfThen(const __Condition: boolean; const if_True, if_False: tobject): tobject;
begin
if __Condition then
result := if_True
else
result := if_False;
end;
class function TFunctions.arrToStr(arrInteger: array of Integer): string;
var
arrString: array of string;
i: Integer;
begin
SetLength(arrString, length(arrInteger));
for i := Low(arrInteger) to High(arrInteger) do
arrString[i] := IntToStr(arrInteger[i]);
result := TFunctions.arrToStr(arrString);
end;
end.
|
{**********************************************************************
* 文件名称: MyPub.pas
* 版本信息:2014.07(lnk)
* 文件描述:
存放所有通用函数,加入函数请按例子说明好函数功能、参数、
返回值等信息,必要时给出调用实例
* 创 建 者:qianlnk
* 创建时间:2014.07.19
***********************************************************************}
unit MyPub;
interface
uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Variants,
Controls, Forms, Dialogs, ExtCtrls, StdCtrls, DBClient, DB, Mask,
DBCtrls, URLMON, AdoDB,Math,Vcl.ComCtrls,Vcl.Buttons
;
{**********************************************************************
过程功能:通用ADO查询,根据用户输入SQL检索数据
参数说明:adoqry—TADOQuery组件,sqltxt-SQL语句
历史信息:2014.07.19 created by qianlnk
**********************************************************************}
procedure OpenAdoQuery(adoQry: TADOquery; sqltxt: widestring);
{**********************************************************************
过程功能:通用ADO执行,根据用户输入SQL提交数据
参数说明:adoqry1—TADOQuery组件,sqltxt-EXECSQL语句
历史信息:2014.07.19 created by qianlnk
**********************************************************************}
procedure ExecAdoQuery(adoQry: TADOquery; sqltxt: widestring);
//过程功能:通用ADODataSet执行,根据用户输入SQLCOMMAND检索数据
procedure OpenAdoDataSet(adoDataSet: TADODataSet; commandStr: widestring);
{**********************************************************************
过程功能:窗口屏幕焦点控制,支持回车跳到下一控件
参数说明:参数对应组件keyDown方法中的参数
历史信息:2014.07.19 created by qianlnk
**********************************************************************}
procedure ControlKey(var Key: Word; Shift: TShiftState);
{**********************************************************************
过程功能:窗口居中
参数说明:无
历史信息:2014.07.19 created by qianlnk
**********************************************************************}
procedure PutFormCenter(subForm: TForm; MainForm: TForm);
{**********************************************************************
过程功能:弹窗位置设置
参数说明:无
历史信息:2014.08.05 created by qianlnk
**********************************************************************}
procedure SetSubFormPlace(subForm: TForm);
{**********************************************************************
过程功能:判断Edit不能为空
参数说明:Edit1 输入框
MainForm 调用该过程的窗体
历史信息:2014.07.19 created by qianlnk
**********************************************************************}
function EditValid(Edit1: TEdit; strMsg: string; MainForm: TForm):boolean;
{**********************************************************************
函数功能:消息提示弹窗
参数说明:sTitle 弹窗标题
sMsg 消息
MainForm 调用该弹窗的窗体 用于弹窗居中
btnCount 按钮数量
历史信息:2014.07.19 created by qianlnk
**********************************************************************}
function ShowMsg(sTitle: Widestring; sMsg: widestring; MainForm: TForm; btnCount:Integer = 1):Integer;
{**********************************************************************
过程功能:向combobox中添加数据库选项
参数说明:qry1查询结果集
itemName选项代码
IsDel是否清空
历史信息:2014.08.04 created by qianlnk
**********************************************************************}
procedure AddItemToCommbox(qry1: TADOQuery; itemName: string;
cbb1:TComboBox; IsDel:Boolean = True);
{**********************************************************************
过程功能:获取treeview的结点及子节点的text值,用逗号隔开
参数说明:strText
node
历史信息:2014.08.05 created by qianlnk
**********************************************************************}
procedure GetTvTextAndChild(var strText: string; node: TTreeNode);
{**********************************************************************
过程功能:获取treeview的结点Node同级结点及子节点的text值,用逗号隔开
参数说明:strText
node
历史信息:2014.08.05 created by qianlnk
**********************************************************************}
procedure GetAllTvTextAfterNode(var strText: string; node: TTreeNode);
{**********************************************************************
过程功能:设置treeview的结点Node和同级结点及他们的子节点的状态
参数说明:node
state
历史信息:2014.08.05 created by qianlnk
**********************************************************************}
procedure SetTvNodeStateIndex(node: TTreeNode; nState: Integer);
{**********************************************************************
过程功能:展开treeview的结点
参数说明:treeview
历史信息:2014.08.05 created by qianlnk
**********************************************************************}
procedure ExpandTvItem(tv: TTreeView);
{**********************************************************************
过程功能:在treeview的结点前画一个复选框
参数说明:treeview
历史信息:2014.08.09 created by qianlnk
**********************************************************************}
procedure DrowChkBoxForTv(tv: TTreeView);
{**********************************************************************
过程功能:将指定容器下的所有编辑控件设置为只读
参数说明:AComponent: TComponent
历史信息:2014.08.06 created by qianlnk
**********************************************************************}
procedure SetReadOnly(AComponent: TComponent);
{**********************************************************************
过程功能:创建操作日志
参数说明:adoQry qry控件 用于操作
UserId 用户ID
Module 模块名称
type 操作类型
remark 操作描述
历史信息:2014.08.07 created by qianlnk
**********************************************************************}
procedure MakeLog(adoQry: TADOquery; UserId: Integer; sModule: string;
sType: string; sRemark: string);
{**********************************************************************
过程功能:判断插入的指定字段值是否重复
参数说明:sCloum --字段
sValue --值
sTbale --表
历史信息:2014.08.06 created by qianlnk
**********************************************************************}
function IsExist(adoQry: TADOquery; sCloum: string; sValue:string; sTable:string):Boolean;
{**********************************************************************
过程功能:获取下一条记录的FID
参数说明:adoQry: TADOquery
sTbale
历史信息:2014.08.06 created by qianlnk
**********************************************************************}
function GetNextID(adoQry: TADOquery; sTable:string):Integer;
{**********************************************************************
过程功能:拼接结果集的记录
参数说明:adoQry: TADOquery --结果集
sColumn: --要拼接的列名
历史信息:2014.08.06 created by qianlnk
**********************************************************************}
function wm_concat(adoQry: TADOquery; sColumn:string):string;
{**********************************************************************
过程功能:初始化模块权限
参数说明:adoQry: TADOquery
frm: --模块主窗体
sModileId: --模块版本号
nUser: --当前登录用户
历史信息:2014.08.06 created by qianlnk
**********************************************************************}
procedure InitModuleLimit(adoqry: TADOQuery; frm: TForm;
sModileId: string; nUser: integer);
{**********************************************************************
过程功能:对容器下的所有编辑控件输入的数据进行安全检查 防止黑客的SQL注入
参数说明:AComponent: TComponent
frm: 被判断的容器所在的窗体 用于消息显示
历史信息:2014.08.20 created by qianlnk
描 述:所有的SQL查询发生时必须调用该过程
**********************************************************************}
function SafeCheck(AComponent: TComponent; frm:TForm):Boolean;
//在 SafeCheck中调用
function CheckString(sContent:string;frm:TForm):Boolean;
{---------------------------------------------------------------------}
{ 实现 }
{---------------------------------------------------------------------}
implementation
uses uShowMsg;
//过程功能:通用ADO查询,根据用户输入SQL检索数据
procedure OpenAdoQuery(adoQry: TADOquery; sqltxt: widestring);
begin
with adoQry do
begin
if active then close;
SQL.clear;
SQL.add(sqltxt);
open;
end;
end;
//过程功能:通用ADO执行,根据用户输入SQL提交数据
procedure ExecAdoQuery(adoQry: TADOquery; sqltxt: widestring);
begin
with adoQry do
begin
if active then close;
SQL.clear;
SQL.add(sqltxt);
EXECSQL;
end;
end;
//过程功能:通用ADO执行,根据用户输入SQL提交数据
procedure OpenAdoDataSet(adoDataSet: TADODataSet; commandStr: widestring);
begin
with adoDataSet do
begin
if active then close;
CommandText := commandStr;
open;
end;
end;
//窗口屏幕快键控制
procedure ControlKey(var Key: Word; Shift: TShiftState);
var
CurForm: TForm;
CurControl: TWinControl;
bSelectNext: boolean;
begin
CurForm := Screen.ActiveForm;
CurControl := CurForm.ActiveControl;
if Shift = [] then
begin
case Key of
VK_RETURN:
begin
bSelectNext := FALSE;
if (CurControl is TEdit) then bSelectNext := TRUE;
if (CurControl is TCombobox) then bSelectNext := TRUE;
if (CurControl is TMaskEdit) then bSelectNext := TRUE;
if (CurControl is TDBEdit) then bSelectNext := TRUE;
//if (CurControl is TDateTime) then bSelectNext := TRUE;
if bSelectNext then CurForm.Perform(CM_DIALOGKEY, VK_TAB, 0);
end;
end;
end;
end;
//窗口居中
procedure PutFormCenter(subForm: TForm; MainForm: TForm);
begin
subForm.Left := (MainForm.Width - subForm.Width) div 2 + MainForm.Left;
subForm.Top := (MainForm.Height - subForm.Height)div 2 + MainForm.Top;
end;
//弹窗位置设置
procedure SetSubFormPlace(subForm: TForm);
begin
subForm.Top := 105;
subForm.Left := (screen.Width - subForm.Width) div 2;
end;
//函数功能:消息提示弹窗
function ShowMsg(sTitle: Widestring; sMsg: widestring; MainForm: TForm; btnCount:Integer = 1):Integer;
var msgLen : integer;
begin
FrmShowMsg := TFrmShowMsg.Create(Application);
msgLen := length(sMsg) * 10;
with FrmShowMsg do
begin
if msgLen > 180 then
begin
width := msgLen + 130;
end
else
begin
width := 350;
end;
height := 150;
Caption := sTitle;
m_msg := sMsg;
lbMsg.Left := 85;
lbMsg.Top := 30;
if btnCount = 1 then
begin
btnCancle.Visible := False;
btnSure.Visible := True;
btnSure.Left := FrmShowMsg.Width - btnSure.Width - 20;
end
else
begin
btnCancle.Visible := True;
btnSure.Visible := True;
btnSure.Left := FrmShowMsg.Width - btnSure.Width - btnSure.Width - 30;
btnCancle.Left := FrmShowMsg.Width - btnCancle.Width - 20;
end;
PutFormCenter(FrmShowMsg,MainForm);
end;
//if FrmShowMsg.ShowModal = IDOK then
begin
Result := FrmShowMsg.ShowModal;
end;
FrmShowMsg.Release;
end;
//判断Edit不能为空
function EditValid(Edit1: TEdit; strMsg:string ; MainForm: TForm):boolean;
begin
if (trim(Edit1.Text)='') then
begin
ShowMsg('系统提示', '请输入完整的' + strMsg, MainForm);
if Edit1.Enabled then Edit1.SetFocus;
result := TRUE;
end
else
result := FALSE;
end;
//加载数据选项到选项框
procedure AddItemToCommbox(qry1: TADOQuery; itemName: string;
cbb1:TComboBox;IsDel:Boolean = True);
var i: Integer;
begin
if IsDel then
begin
cbb1.Clear;
end;
if(qry1.RecordCount = 0) then
begin
Exit;
end;
for i := 0 to qry1.RecordCount - 1 do
begin
cbb1.Items.Add(trim(qry1.FieldValues[itemName]));
qry1.Next;
end;
if cbb1.Items.count <>0 then
cbb1.ItemIndex := 0;
end;
//获取treeview的结点及其子节点的text值,用逗号隔开
procedure GetTvTextAndChild(var strText: string; node: TTreeNode);
var
tmpNode: TTreeNode;
begin
tmpNode := node;
if tmpNode <> nil then
begin
if strText = '' then
begin
strText := '''' + tmpNode.Text + '''';
end
else
begin
strText := strText + ',' + '''' + tmpNode.Text + '''';
end;
if tmpNode.HasChildren then
begin
GetAllTvTextAfterNode(strText,tmpNode.getFirstChild);
end;
end;
end;
//获取treeview的结点Node和同级结点以及他们的子节点的text值,用逗号隔开
procedure GetAllTvTextAfterNode(var strText: string; node: TTreeNode);
var
tmpNode: TTreeNode;
begin
tmpNode := node;
while tmpNode <> nil do
begin
if strText = '' then
begin
strText := '''' + tmpNode.Text + '''';
end
else
begin
strText := strText + ',' + '''' + tmpNode.Text + '''';
end;
if tmpNode.HasChildren then
begin
GetAllTvTextAfterNode(strText,tmpNode.getFirstChild);
end;
tmpNode := tmpNode.getNextSibling;
end;
end;
//设置treeview的结点Node和同级结点及他们的子节点的状态
procedure SetTvNodeStateIndex(node: TTreeNode; nState: Integer);
var
tmpNode: TTreeNode;
begin
tmpNode := node;
while tmpNode <> nil do
begin
tmpNode.StateIndex := nState;
if tmpNode.HasChildren then
begin
SetTvNodeStateIndex(tmpNode.getFirstChild,nState);
end;
tmpNode := tmpNode.getNextSibling;
end;
end;
//展开treeview所有结点
procedure ExpandTvItem(tv: TTreeView);
var i:Integer;
begin
for i := 0 to tv.Items.Count - 1 do
begin
tv.Items[i].Expanded := True;
end;
end;
//将指定容器下的所有编辑控件设置为只读
procedure SetReadOnly(AComponent: TComponent);
var i: Integer;
begin
//说明:没有控制到的控件请在这里添加
if AComponent is TEdit then TEdit(AComponent).ReadOnly := True;
if AComponent is TComboBox then TComboBox(AComponent).Enabled := False;
if AComponent is TMemo then TMemo(AComponent).ReadOnly := True;
if AComponent is TCheckBox then TCheckBox(AComponent).Enabled := False;
if AComponent is TDateTimePicker then TDateTimePicker(AComponent).Enabled := False;
if AComponent is TWinControl then //控件仍是容器则递归
begin
for i := 0 to TWinControl(AComponent).ControlCount - 1 do
begin
SetReadOnly(TWinControl(AComponent).Controls[i]);
end;
end;
end;
//创建操作日志
procedure MakeLog(adoQry: TADOquery; UserId: Integer; sModule: string; sType: string; sRemark: string);
var sqltxt: string;
//FID: Integer;
begin
//FID := GetNextID(adoQry,'tLog');
sqltxt := 'Insert into tLog(FUserID, FDate, FModule, FType, FRemark) '
+ 'values(' + IntToStr(UserId) + ',getdate(),''' + sModule
+ ''',''' + sType + ''',''' + sRemark + ''')';
ExecAdoQuery(adoQry,sqltxt);
end;
{**********************************************************************
过程功能:判断插入的指定字段值是否重复
参数说明:sCloum --字段
sValue --值
sTbale --表
历史信息:2014.08.06 created by qianlnk
**********************************************************************}
function IsExist(adoQry: TADOquery; sCloum: string; sValue:string; sTable:string):Boolean;
var sqltxt:string;
begin
sqltxt := 'select * from ' + sTable + ' where ' + sCloum + ' = ''' + sValue + ''' ';
OpenAdoQuery(adoQry,sqltxt);
if adoQry.RecordCount > 0 then
begin
Result := True;
end
else
begin
Result := False;
end;
end;
//获取下一条记录的FID
function GetNextID(adoQry: TADOquery; sTable:string):Integer;
var sqltxt: string;
begin
sqltxt := 'select isnull(max(FID),0) as FID from ' + sTable;
OpenAdoQuery(adoQry,sqltxt);
if adoQry.RecordCount = 0 then
begin
Result := 1;
end
else
begin
Result := StrToInt(trim((adoQry.FieldByName('FID').AsString))) + 1;
end;
end;
//在treeview的结点前画一个复选框
procedure DrowChkBoxForTv(tv: TTreeView);
var i:Integer;
begin
for i := 0 to tv.Items.Count - 1 do
begin
tv.Items[i].StateIndex := 1;
end;
end;
//拼接结果集的记录
function wm_concat(adoQry: TADOquery; sColumn:string):string;
var sRes: string;
i: Integer;
begin
if adoQry.RecordCount = 0 then
begin
Result := '';
Exit;
end;
for i := 0 to adoQry.RecordCount - 1 do
begin
if sRes = '' then
begin
sRes := adoQry.FieldByName(sColumn).AsString;
end
else
begin
sRes := sRes + ',' + adoQry.FieldByName(sColumn).AsString;
end;
adoQry.Next;
end;
Result := sRes;
end;
//初始化模块权限
procedure InitModuleLimit(adoqry: TADOQuery; frm: TForm; sModileId: string; nUser:integer);
var i: Integer;
Compon : TComponent;
OldLeft: Integer; //上一个组件的left值
sqltxt: string;
j: Integer;
sFuncs: WideString;
begin
OldLeft := 5;
sqltxt := 'select FFuncCaption from tModuleFunc where FModuleID = (select FID from tModule where FCode = ''' + sModileId + ''')'
+ 'and FID in(select FModuleFuncID from tFuncLimit where FUserID = '+ IntToStr(nUser) +')';
OpenAdoQuery(adoqry,sqltxt);
sFuncs := wm_concat(adoqry,'FFuncCaption');
for i := 0 to frm.ComponentCount - 1 do
begin
Compon := frm.Components[i];
if Compon is TBitBtn then
begin
if (Compon As TBitBtn).Visible = False then
begin //不干扰系统设计时的设置
Continue;
end;
if Pos((Compon As TBitBtn).Caption,sFuncs) > 0 then
begin
(Compon As TBitBtn).Visible := False;
end
else
begin
(Compon As TBitBtn).Visible := True;
end;
if (Compon As TBitBtn).Visible and ((Compon As TBitBtn).Caption <> '查询') then
begin
(Compon As TBitBtn).Left := OldLeft;
OldLeft := OldLeft + (Compon As TBitBtn).Width;
end;
end;
end;
end;
//对容器下的所有编辑控件输入的数据进行安全检查 防止黑客的SQL注入
function SafeCheck(AComponent: TComponent; frm:TForm):Boolean;
var i: Integer;
sContent: string;//编辑框中的内容
nFlag: Integer;
begin
//说明:没有控制到的编辑控件请在这里添加
if AComponent is TEdit then
begin
sContent := TEdit(AComponent).Text;
if CheckString(sContent,frm) then
begin
TEdit(AComponent).SetFocus;
Result := True;
Exit;
end;
end;
if AComponent is TComboBox then
begin
sContent := TComboBox(AComponent).Text;
if CheckString(sContent,frm) then
begin
TComboBox(AComponent).SetFocus;
Result := True;
Exit;
end;
end;
if AComponent is TMemo then
begin
sContent := TMemo(AComponent).Text;
if CheckString(sContent,frm) then
begin
TMemo(AComponent).SetFocus;
Result := True;
Exit;
end;
end;
// nFlag 数据类型标记目前先不用
if AComponent is TWinControl then //控件仍是容器则递归
begin
for i := 0 to TWinControl(AComponent).ControlCount - 1 do
begin
if SafeCheck(TWinControl(AComponent).Controls[i],frm) then
begin
Result := True;
Exit;
end;
end;
end;
Result := False;
end;
const
CK_SQLInjection: array[0..13] of string=(
'''',';','--','/*','#','SELECT','DELETE','DROP','INSERT','UNION',
'UPDATE','ALTER','CREATE','EXEC'
);
function CheckString(sContent:string;frm:TForm):Boolean;
var i :Integer;
begin
// 过滤对SQL语句敏感的字符串
for I := 0 to 13 do
begin
if Pos(CK_SQLInjection[i],UpperCase(sContent))>0 then
begin
ShowMsg('错误','输入的信息不允许包含['+ CK_SQLInjection[i] +']!',frm);
Result := True;
Exit;
end;
end;
Result := False;
end;
end.
|
unit revvoc;
interface
Procedure Playkey(k:char);
Procedure LoadVocFile(filename:string);
Procedure LoadVocPointer(filename:string);
procedure play_voc_pointer(buf : pointer; size:word);
{ resetdsp returns true if reset was successful }
{ base should be 1 for base address 210h, 2 for 220h etc... }
function reset_dsp(base : word) : boolean;
{ write dac sets the speaker output level }
procedure write_dac(level : byte);
{ readdac reads the microphone input level }
function read_dac : byte;
{ speakeron connects the dac to the speaker }
function speaker_on: byte;
{ speakeroff disconnects the dac from the speaker, }
{ but does not affect the dac operation }
function speaker_off: byte;
{ functions to pause dma playback }
procedure dma_pause;
procedure dma_continue;
{ playback plays a sample of a given size back at a given frequency using }
{ dma channel 1. the sample must not cross a page boundry }
procedure play_back(sound : pointer; size : word; frequency : word);
{ plays voc-file }
procedure play_voc(filename : string; buf : pointer);
{ true if playing voc }
function done_playing:boolean;
Procedure LoadAndPlay(num:integer);
Procedure Loadvoc(num:integer);
implementation
uses crt,revdat,revconst,revtech;
var dsp_reset : word;
dsp_read_data : word;
dsp_write_data : word;
dsp_write_status : word;
dsp_data_avail : word;
since_midnight : longint absolute $40:$6C;
playing_till : longint;
Procedure LoadAndPlay(num:integer);
begin
if voc then
begin
extractpointerfromdat(config^.vocs[num],vocp,vsize);
dma_pause;
play_voc_pointer(vocp,vsize);
dma_continue;
end;
end;
Procedure Loadvoc(num:integer);
begin
if voc then
begin
extractpointerfromdat(config^.vocs[num],vocp,vsize);
end;
end;
Procedure Playkey(k:char);
begin
if voc and (k in [#72,#80,#75,#77,#13,#81,#73,#79,#71,#27]) then
begin
dma_pause;
play_voc_pointer(vocp,vsize);
dma_continue;
end;
end;
Procedure LoadVocFile(filename:string);
var f:file; n:word; size:word;
begin
extractfilefromdat(filename);
assign(f,filename);
reset(f,1);blockread(f,vocp^,max,n);
close(f);
deletedatfile(filename);
end;
Procedure LoadVocPointer(filename:string);
var f:file; n:word; size:word;
begin
if voc then
begin
extractpointerfromdat(filename,vocp,size);
play_voc_pointer(vocp,size);
end;
end;
function reset_dsp(base : word) : boolean;
begin
base := base * $10;
{ calculate the port addresses }
dsp_reset := base + $206;
dsp_read_data := base + $20a;
dsp_write_data := base + $20c;
dsp_write_status := base + $20c;
dsp_data_avail := base + $20e;
{ reset the dsp, and give some nice long delays just to be safe }
port[dsp_reset] := 1;
delay(10);
port[dsp_reset] := 0;
delay(10);
reset_dsp := (port[dsp_data_avail] and $80 = $80) and
(port[dsp_read_data] = $aa);
end;
procedure write_dsp(value : byte);
begin
while port[dsp_write_status] and $80 <> 0 do;
port[dsp_write_data] := value;
end;
function read_dsp : byte;
begin
while port[dsp_data_avail] and $80 = 0 do;
read_dsp := port[dsp_read_data];
end;
procedure write_dac(level : byte);
begin
write_dsp($10);
write_dsp(level);
end;
function read_dac : byte;
begin
write_dsp($20);
read_dac := read_dsp;
end;
function speaker_on: byte;
begin
write_dsp($d1);
end;
function speaker_off: byte;
begin
write_dsp($d3);
end;
procedure dma_continue;
begin
playing_till := since_midnight + playing_till;
write_dsp($d4);
end;
procedure dma_pause;
begin
playing_till := playing_till - since_midnight;
write_dsp($d0);
end;
procedure play_back(sound : pointer; size : word; frequency : word);
var time_constant : word;
page : word;
offset : word;
begin
speaker_on;
size := size - 1;
{ set up the dma chip }
offset := seg(sound^) shl 4 + ofs(sound^)+32;
page := (seg(sound^) +(ofs(sound^)+32) shr 4) shr 12;
port[$0a] := 5;
port[$0c] := 0;
port[$0b] := $49;
port[$02] := lo(offset);
port[$02] := hi(offset);
port[$83] := page;
port[$03] := lo(size);
port[$03] := hi(size);
port[$0a] := 1;
{ set the playback frequency }
time_constant := 256 - 1000000 div frequency;
write_dsp($40);
write_dsp(time_constant);
{ set the playback type (8-bit) }
write_dsp($14);
write_dsp(lo(size));
write_dsp(hi(size));
end;
procedure play_voc(filename : string; buf : pointer);
var f : file;
s : word;
freq : word;
h : record
signature : array[1..20] of char; { vendor's name }
data_start : word; { start of data in file }
version : integer; { min. driver version required }
id : integer; { 1 - complement of version field
+$1234 } end; { used to indentify a .voc
file }
d : record
id : byte; { = 1 }
len : array[1..3] of byte; { length of voice data (len data + 2) }
sr : byte; { sr = 256 - (1,000,000 / sampling rate) }
pack : byte; { 0 : unpacked, 1 : 4-bit, 2 : 2.6 bit, 3:
2 bit packed } end;
var n:word;
begin
{$i-}
if pos('.', filename) = 0 then filename := filename + '.voc';
assign(f, filename);
reset(f, 1);
blockread(f, h, 26);
blockread(f, d, 6);
freq := round(1000000 / (256 - d.sr));
s := ord(d.len[3]) + ord(d.len[2]) * 256 + ord(d.len[1]) * 256 * 256;
(*
writeln('-----------header----------');
writeln('signature: ', h.signature);
writeln('data_start: ', h.data_start);
writeln('version: ', hi(h.version), '.', lo(h.version));
writeln('id: ', h.id);
writeln;
writeln('------------data-----------');
writeln('id: ', d.id);
writeln('len: ', s);
writeln('sr: ', d.sr);
writeln('freq: ', freq);
writeln('pack: ', d.pack);
*)
n:=1;
{ while n>0 do
begin}
blockread(f, buf^, s,n);
playing_till := since_midnight + round(s / freq * 18.20648193);
play_back(buf, s, freq);
{ end;}
close(f);
end;
procedure play_voc_pointer(buf : pointer; size:word);
var f : file;
s : word;
freq : word;
h : record
signature : array[1..20] of char; { vendor's name }
data_start : word; { start of data in file }
version : integer; { min. driver version required }
id : integer; { 1 - complement of version field
+$1234 } end; { used to indentify a .voc
file }
d : record
id : byte; { = 1 }
len : array[1..3] of byte; { length of voice data (len data + 2) }
sr : byte; { sr = 256 - (1,000,000 / sampling rate) }
pack : byte; { 0 : unpacked, 1 : 4-bit, 2 : 2.6 bit, 3:
2 bit packed } end;
var n,i:word;
begin
{ move32fast(mem[seg(buf^):ofs(buf^)+i-1],mem[seg(h):ofs(h)+i-1],1);+}
move32fast(mem[seg(buf^):ofs(buf^)],h,26);
move32fast(mem[seg(buf^):ofs(buf^)+26],d,6);
freq := round(1000000 / (256 - d.sr));
s := ord(d.len[3]) + ord(d.len[2]) * 256 + ord(d.len[1]) * 256 * 256;
n:=1;
playing_till := since_midnight + round(s / freq * 18.20648193);
{ move32fast(mem[seg(buf^):ofs(buf^)+32],mem[seg(buf^):ofs(buf^)],size-32);}
play_back(buf, s, freq);
end;
function done_playing:boolean;
begin
done_playing:= since_midnight > playing_till;
end;
begin
if not reset_dsp(2) then
begin
voc:=false;
voc_start:=false;
end
else
begin
voc_Start:=true;
voc:=true;
end;
end. |
{********************************************}
{ TeeChart Pro PDF Canvas and Exporting }
{ Copyright (c) 2002-2004 by Marjan Slatinek }
{ and David Berneda }
{ All Rights Reserved }
{ }
{ Some features taken from }
{ Nishita's PDF Creation VCL (TNPDF) }
{ ( with permission ) }
{ }
{********************************************}
unit TeePDFCanvas;
{$I TeeDefs.inc}
interface
uses {$IFNDEF LINUX}
Windows,
{$ENDIF}
Classes,
{$IFDEF CLX}
QGraphics, QForms, Types,
{$ELSE}
Graphics, Forms,
{$IFNDEF CLR}
Jpeg,
{$ENDIF}
{$ENDIF}
TeCanvas, TeeProcs, TeeExport, Math;
Type
// Base pdf object definition (taken from PDF reference )
PFontData = ^TFontData;
TFontData = record
FontBBox: TRect;
FirstChar, LastChar: Integer;
CapHeight: Integer;
Ascent: Integer;
Descent: Integer;
MaxWidth: Integer;
AvgWidth: Integer;
ItalicAngle: Integer;
DigAspX, DigAspY: Integer;
CharWidths: Array [0..255] of Integer;
end;
TImageType = (itJPEG, itBitmap, itUnknown);
TTeePDFImageListEntry = class(TObject)
private
FObjectNumber: Integer;
FHeight: Integer;
FWidth: Integer;
FGraphic: TGraphic;
procedure DefineImageData;
procedure SetObjectNumber(const Value: Integer);
function GetImageType: TImageType;
function GetDataLength: Integer;
public
property ObjectNumber: Integer read FObjectNumber write SetObjectNumber;
property Width: Integer read FWidth;
property Height: Integer read FHeight;
property DataLength: Integer read GetDataLength;
property ImageType: TImageType read GetImageType;
procedure WriteDataToStream(AStream: TStream);
Constructor Create(AGraphic: TGraphic);
end;
TTeePDFImageList = class(TObject)
private
IImageList: TList;
function EqualImages(i1,i2: TGraphic): boolean;
function GetCount: Integer;
function GetImageEntry(Index: Integer): TTeePDFImageListEntry;
public
property Items[Index: Integer]: TTeePDFImageListEntry read GetImageEntry;
property ItemsCount: Integer read GetCount;
function AddItem(AGraphic: TGraphic): Integer;
function Find(AGraphic: TGraphic): Integer;
Constructor Create;
Destructor Destroy; override;
end;
TTeePDFFontListEntry = class (TObject)
private
FFontData: TFontData;
FPDFName: String;
FObjectNumber: Integer;
procedure DefineFontData(AFont: TFont);
procedure SetObjectNumber(const Value: Integer);
public
property PDFName: String read FPDFName;
property ObjectNumber: Integer read FObjectNumber write SetObjectNumber;
property FontData: TFontData read FFontData;
Constructor Create(AFont: TFont);
end;
TTeePDFFontList = class (TObject)
private
IFontList: TList;
function GetFontEntry(Index: Integer): TTeePDFFontListEntry;
function GetCount: Integer;
public
property Items[Index: Integer]: TTeePDFFontListEntry read GetFontEntry;
property ItemsCount: Integer read GetCount;
function AddItem(AFont: TFont; AHandle: TTeeCanvasHandle): Integer;
function Find(AFont: TFont): Integer;
Constructor Create;
Destructor Destroy; override;
end;
TPDFChartObject = class(TObject)
private
FContents: TStream;
FFontArray: TTeePDFFontList;
FImageArray: TTeePDFImageList;
function GetLength: Integer;
public
property Contents: TStream read FContents;
property Length: Integer read GetLength;
property FontArray: TTeePDFFontList read FFontArray;
property ImageArray: TTeePDFImageList read FImageArray;
procedure SaveToStream(AStream: TStream);
Constructor Create;
Destructor Destroy; override;
end;
TTeePDFPage = class(TObject)
private
IObjCount, CatalogNum, ParentNum, ResourceNum: Integer;
tmpSt: String;
OffsetList: TStringList;
FChartObject: TPDFChartObject;
XRefPos: Integer;
FPageHeight: Integer;
FPageWidth: Integer;
procedure AddToOffset(Offset: Integer);
procedure WriteHeader(AStream: TStream);
procedure WriteInfo(AStream: TStream);
procedure WriteTTFonts(AStream: TStream);
procedure WriteImages(AStream: TStream);
procedure WriteResources(AStream: TStream);
procedure WritePages(AStream: TStream);
procedure WritePage(AStream: TStream);
procedure WriteCatalog(AStream: TStream);
procedure WriteXRef(AStream: TStream);
procedure WriteTrailer(AStream: TStream);
procedure SetPageHeight(const Value: Integer);
procedure SetPageWidth(const Value: Integer);
public
property PageWidth: Integer read FPageWidth write SetPageWidth;
property PageHeight: Integer read FPageHeight write SetPageHeight;
property ChartObject: TPDFChartObject read FChartObject;
procedure SaveToStream(AStream: TStream);
Constructor Create;
Destructor Destroy; override;
end;
TPDFCanvas = class(TTeeCanvas3D)
private
{ Private declarations }
FBackColor : TColor;
FBackMode : TCanvasBackMode;
IWidth,
IHeight: Integer;
FX,
FY: Double;
IClipCalled: boolean;
tmpSt: String;
FEmbeddedFonts: boolean;
FCStream: TStream;
FContents: TPDFChartObject;
Function BrushProperties(Brush: TBrush): String;
Function FontProperties(Font: TTeeFont; var FontIndex: Integer): String;
Function InternalBezCurve(ax1,ay1,ax2,ay2,ax3,ay3: double): String;
procedure InternalDrawArc(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer; MoveTo0: boolean; DrawPie: boolean);
Procedure InternalDrawImage(sx, sy, tx,ty: double; ImageIndex: Integer);
Procedure InternalRect(Const Rect:TRect; UsePen,IsRound:Boolean);
Function PenProperties(Pen: TPen): String;
Function PointToStr(X, Y: double):String;
Function SelectFont(Font: TFont): Integer;
Function SelectImage(Graphic: TGraphic): integer;
procedure SetEmbeddedFonts(const Value: boolean);
Function SetPenStyle(PenStyle: TPenStyle): String;
function TextToPDFText(AText: String): String;
Function TheBounds:String;
Procedure TranslateVertCoord(var Y: double);
Function ValidGraphic(Graphic: TGraphic):Boolean;
protected
{ Protected declarations }
Function GetBackColor:TColor; override;
Function GetBackMode:TCanvasBackMode; override;
Function GetMonochrome:Boolean; override;
Procedure PolygonFour; override;
Procedure SetBackColor(Color:TColor); override;
Procedure SetBackMode(Mode:TCanvasBackMode); override;
procedure SetPixel(X, Y: Integer; Value: TColor); override;
procedure SetPixel3D(X,Y,Z:Integer; Value: TColor); override;
Procedure SetMonochrome(Value:Boolean); override;
public
{ Public declarations }
Constructor Create(AChartObject: TPDFChartObject);
Destructor Destroy; override;
Function InitWindow( DestCanvas:TCanvas;
A3DOptions:TView3DOptions;
ABackColor:TColor;
Is3D:Boolean;
Const UserRect:TRect):TRect; override;
procedure WriteToStream(AStream: TStream);
{ 2d }
Function TextWidth(Const St:String):Integer; override;
Function TextHeight(Const St:String):Integer; override;
{ 3d }
procedure Arc(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer); override;
procedure Draw(X, Y: Integer; Graphic: TGraphic); override;
procedure FillRect(const Rect: TRect); override;
procedure Ellipse(X1, Y1, X2, Y2: Integer); override;
procedure LineTo(X,Y:Integer); override;
procedure MoveTo(X,Y:Integer); override;
procedure Pie(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer); override;
procedure Rectangle(X0,Y0,X1,Y1:Integer); override;
procedure RoundRect(X1, Y1, X2, Y2, X3, Y3: Integer); override;
procedure StretchDraw(const Rect: TRect; Graphic: TGraphic); override;
Procedure TextOut(X,Y:Integer; const Text:String); override;
Procedure DoHorizLine(X0,X1,Y:Integer); override;
Procedure DoVertLine(X,Y0,Y1:Integer); override;
procedure ClipRectangle(Const Rect:TRect); override;
procedure ClipCube(Const Rect:TRect; MinZ,MaxZ:Integer); override;
procedure UnClipRectangle; override;
Procedure GradientFill( Const Rect:TRect;
StartColor,EndColor:TColor;
Direction:TGradientDirection;
Balance:Integer=50); override;
procedure RotateLabel(x,y:Integer; Const St:String; RotDegree:Double); override;
procedure RotateLabel3D(x,y,z:Integer;
Const St:String; RotDegree:Double); override;
Procedure Line(X0,Y0,X1,Y1:Integer); override;
Procedure Polygon(const Points: array of TPoint); override;
{ 3d }
Procedure ShowImage(DestCanvas,DefaultCanvas:TCanvas; Const UserRect:TRect); override;
procedure EllipseWithZ(X1, Y1, X2, Y2, Z:Integer); override;
Procedure HorizLine3D(Left,Right,Y,Z:Integer); override;
procedure LineTo3D(X,Y,Z:Integer); override;
Procedure LineWithZ(X0,Y0,X1,Y1,Z:Integer); override;
procedure MoveTo3D(X,Y,Z:Integer); override;
Procedure TextOut3D(X,Y,Z:Integer; const Text:String); override;
Procedure VertLine3D(X,Top,Bottom,Z:Integer); override;
Procedure ZLine3D(X,Y,Z0,Z1:Integer); override;
property EmbeddedFonts: boolean read FEmbeddedFonts write SetEmbeddedFonts default False;
end;
TPDFExportFormat=class(TTeeExportFormat)
protected
Procedure DoCopyToClipboard; override;
public
function Description:String; override;
function FileExtension:String; override;
function FileFilter:String; override;
Function PDFPage: TTeePDFPage;
function ChartObject: TPDFChartObject;
Function Options(Check:Boolean=True):TForm; override;
Procedure SaveToStream(Stream:TStream); override;
end;
procedure WriteStringToStream(Stream: TStream; S:String);
procedure TeeSaveToPDFFile( APanel:TCustomTeePanel; const FileName: WideString;
AWidth:Integer=0;
AHeight: Integer=0);
implementation
Uses {$IFDEF CLX}
QClipbrd,
{$ELSE}
Clipbrd,
{$ENDIF}
TeeConst, SysUtils;
Const CRLF = #13+#10;
function FormatIntToString(Value: integer; Len: integer): string;
var S: string;
i, j: integer;
begin
Result := '';
if Value < 0 then S := '0' else S := IntToStr(Value);
i := Len - Length(S);
for j := 0 to i - 1 do Result := Result + '0';
Result := Result + S;
end;
procedure WriteStringToStream(Stream: TStream; S:String);
begin
Stream.Write(S[1],Length(S));
end;
function PDFFontName(AFont: TFont): String;
var tmpSt: String;
begin
tmpSt := AFont.Name;
if (fsBold in AFont.Style) then tmpSt := tmpSt+',Bold';
if (fsItalic in AFont.Style) then tmpSt := tmpSt+',Italic';
while Pos(' ', tmpSt) > 0 do
Delete(tmpSt,Pos(' ',tmpSt),1);
Result := tmpSt;
end;
{ Convert , to . }
procedure FixSeparator(var St: String);
begin
while Pos(',', St) > 0 do
St[Pos(',', St)] := '.';
end;
Function PDFColor(AColor:TColor):String;
const tmp=1/255.0;
begin
AColor:=ColorToRGB(AColor);
Result:= FormatFloat('0.00',GetRVAlue(AColor)*tmp) + ' ' +
FormatFloat('0.00',GetGVAlue(AColor)*tmp) + ' ' +
FormatFloat('0.00',GetBVAlue(AColor)*tmp);
FixSeparator(Result);
end;
Function TPDFCanvas.InternalBezCurve(ax1,ay1,ax2,ay2,ax3,ay3: double): String;
begin
Result := FormatFloat('0.000',ax1)+ ' ' + FormatFloat('0.000',ay1) + ' ' +
FormatFloat('0.000',ax2)+ ' ' + FormatFloat('0.000',ay2) + ' ' +
FormatFloat('0.000',ax3)+ ' ' + FormatFloat('0.000',ay3) + ' c'+CRLF;
end;
Procedure TPDFCanvas.ShowImage(DestCanvas,DefaultCanvas:TCanvas; Const UserRect:TRect);
begin
//
end;
procedure TPDFCanvas.Rectangle(X0,Y0,X1,Y1:Integer);
begin
InternalRect(TeeRect(X0,Y0,X1,Y1),True,False);
end;
procedure TPDFCanvas.MoveTo(X, Y: Integer);
begin
FX := X;
FY := Y;
end;
procedure TPDFCanvas.LineTo(X, Y: Integer);
begin
tmpSt := PenProperties(Pen) + ' ' + PointToStr(FX,FY)+' m ' + PointToStr(X,Y)+' l S'+CRLF;
WriteStringToStream(FCStream,tmpSt);
FX := X;
FY := Y;
end;
procedure TPDFCanvas.ClipRectangle(Const Rect:TRect);
var tmpB, tmpT: double;
begin
IClipCalled := True;
WriteStringToStream(FCStream,'q'+CRLF);
tmpB := Rect.Bottom;
tmpT := Rect.Top;
TranslateVertCoord(tmpB);
TranslateVertCoord(tmpT);
tmpSt := tmpSt+FormatFloat('0.00',Rect.Left)+' '+ FormatFloat('0.00',tmpB)+ ' ' +
FormatFloat('0.00',Rect.Right-Rect.Left)+' ' + FormatFloat('0.00',tmpT-tmpB)+' re W n'+CRLF;
FixSeparator(tmpSt);
WriteStringToStream(FCStream,tmpSt);
end;
procedure TPDFCanvas.ClipCube(Const Rect:TRect; MinZ,MaxZ:Integer);
begin
{ Not implemented }
end;
procedure TPDFCanvas.UnClipRectangle;
begin
if IClipCalled then
begin
WriteStringToStream(FCStream,'Q'+CRLF);
IClipCalled := false;
end;
end;
function TPDFCanvas.GetBackColor:TColor;
begin
result:=FBackColor;
end;
procedure TPDFCanvas.SetBackColor(Color:TColor);
begin
FBackColor:=Color;
end;
procedure TPDFCanvas.SetBackMode(Mode:TCanvasBackMode);
begin
FBackMode:=Mode;
end;
Function TPDFCanvas.GetMonochrome:Boolean;
begin
result:=False;
end;
Procedure TPDFCanvas.SetMonochrome(Value:Boolean);
begin
{ Not implemented }
end;
Function TPDFCanvas.ValidGraphic(Graphic: TGraphic):Boolean;
begin
result:=(Graphic is TBitmap)
{$IFNDEF CLR}{$IFNDEF CLX}or (Graphic is TJPEGImage){$ENDIF}{$ENDIF};
end;
procedure TPDFCanvas.StretchDraw(const Rect: TRect; Graphic: TGraphic);
begin
if ValidGraphic(Graphic) then
InternalDrawImage( Abs(Rect.Right - Rect.Left),
Abs(Rect.Bottom - Rect.Top),
Rect.Left,IHeight-Rect.Bottom,SelectImage(Graphic));
end;
procedure TPDFCanvas.Draw(X, Y: Integer; Graphic: TGraphic);
begin
if ValidGraphic(Graphic) then
InternalDrawImage(Graphic.Width,Graphic.Height,X,IHeight-Y-Graphic.Height,SelectImage(Graphic));
end;
Function TPDFCanvas.TheBounds:String;
begin
IWidth := Bounds.Right - Bounds.Left;
IHeight := Bounds.Bottom - Bounds.Top;
end;
Function TPDFCanvas.PointToStr(X,Y:double):String;
begin
TranslateVertCoord(Y);
tmpSt := FormatFloat('0.000',X)+' '+FormatFloat('0.000',Y);
FixSeparator(tmpSt);
Result := tmpSt;
end;
Procedure TPDFCanvas.GradientFill( Const Rect:TRect;
StartColor,EndColor:TColor;
Direction:TGradientDirection;
Balance:Integer=50);
begin
{ Not implemented }
end;
procedure TPDFCanvas.FillRect(const Rect: TRect);
begin
InternalRect(Rect,False,False);
end;
Procedure TPDFCanvas.InternalRect(Const Rect:TRect; UsePen, IsRound:Boolean);
var tmpB,tmpT: double;
begin
if (Brush.Style<>bsClear) or (UsePen and (Pen.Style<>psClear)) then
begin
tmpSt := PenProperties(Pen) + ' ' + BrushProperties(Brush)+ ' ';
tmpB := Rect.Bottom;
tmpT := Rect.Top;
TranslateVertCoord(tmpB);
TranslateVertCoord(tmpT);
tmpSt := tmpSt+FormatFloat('0.000',Rect.Left)+' '+ FormatFloat('0.000',tmpB)+ ' ' +
FormatFloat('0.000',Rect.Right-Rect.Left)+' ' + FormatFloat('0.000',tmpT-tmpB)+' re';
FixSeparator(tmpSt);
WriteStringToStream(FCStream,tmpSt);
if (Brush.Style<>bsClear) then
begin
if (Pen.Style<>psClear) then WriteStringToStream(FCStream,' B'+CRLF)
else WriteStringToStream(FCStream,' f'+CRLF);
end else WriteStringToStream(FCStream,' S'+CRLF);
end;
end;
procedure TPDFCanvas.Ellipse(X1, Y1, X2, Y2: Integer);
begin
EllipseWithZ(X1,Y1,X2,Y2,0);
end;
procedure TPDFCanvas.EllipseWithZ(X1, Y1, X2, Y2, Z: Integer);
var ra,rb,xc,yc: double;
const Bez = 0.552;
begin
if (Brush.Style<>bsClear) or (Pen.Style<>psClear) then
begin
WriteStringToStream(FCStream,PenProperties(Pen) + ' ' + BrushProperties(Brush)+ ' ');
Calc3DPos(X1,Y1,Z);
Calc3DPos(X2,Y2,Z);
ra := (X2 - X1)*0.5;
rb := (Y2 - Y1)*0.5;
xc := (X2 + X1)*0.5;
yc := (Y2 + Y1)*0.5;
TranslateVertCoord(yc);
tmpSt := FormatFloat('0.000',xc+ra)+ ' ' + FormatFloat('0.000',yc)+ ' m ';
{ 4-arc version of drawing circle/ellipse }
{ Q1, Q2, Q3 and Q4 cp}
tmpSt := tmpSt + InternalBezCurve(xc+ra, yc+Bez*rb, xc+Bez*ra, yc+rb, xc, yc+rb);
tmpSt := tmpSt + InternalBezCurve(xc-Bez*ra, yc+rb, xc-ra, yc+Bez*rb, xc-ra, yc);
tmpSt := tmpSt + InternalBezCurve(xc-ra, yc-Bez*rb, xc-Bez*ra, yc-rb, xc, yc-rb);
tmpSt := tmpSt + InternalBezCurve(xc+Bez*ra, yc-rb, xc+ra, yc-Bez*rb, xc+ra, yc);
FixSeparator(tmpSt);
WriteStringToStream(FCStream,tmpSt);
if (Brush.Style<>bsClear) then
begin
if (Pen.Style<>psClear) then WriteStringToStream(FCStream,' B'+CRLF)
else WriteStringToStream(FCStream,' f'+CRLF);
end else WriteStringToStream(FCStream,' S'+CRLF);
end;
end;
procedure TPDFCanvas.SetPixel3D(X,Y,Z:Integer; Value: TColor);
begin
if Pen.Style<>psClear then
begin
Calc3DPos(x,y,z);
Pen.Color:=Value;
MoveTo(x,y);
LineTo(x,y);
end;
end;
procedure TPDFCanvas.SetPixel(X, Y: Integer; Value: TColor);
begin
if Pen.Style<>psClear then
begin
Pen.Color:=Value;
MoveTo(x,y);
LineTo(x,y);
end;
end;
procedure TPDFCanvas.Arc(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer);
begin
InternalDrawArc(X1, Y1, X2, Y2, X3, Y3, X4, Y4, True,False);
end;
procedure TPDFCanvas.Pie(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer);
begin
InternalDrawArc(X1, Y1, X2, Y2, X3, Y3, X4, Y4, False, True);
end;
procedure TPDFCanvas.RoundRect(X1, Y1, X2, Y2, X3, Y3: Integer);
begin
InternalRect(TeeRect(X1,Y1,X2,Y2),True,True);
end;
Procedure TPDFCanvas.TextOut3D(X,Y,Z:Integer; const Text:String);
begin
RotateLabel3D(X,Y,Z,Text,0);
end;
Procedure TPDFCanvas.TextOut(X,Y:Integer; const Text:String);
begin
TextOut3D(X,Y,0,Text);
end;
procedure TPDFCanvas.MoveTo3D(X,Y,Z:Integer);
begin
Calc3DPos(x,y,z);
MoveTo(x,y);
end;
procedure TPDFCanvas.LineTo3D(X,Y,Z:Integer);
begin
Calc3DPos(x,y,z);
LineTo(x,y);
end;
Procedure TPDFCanvas.DoHorizLine(X0,X1,Y:Integer);
begin
MoveTo(X0,Y);
LineTo(X1,Y);
end;
Procedure TPDFCanvas.DoVertLine(X,Y0,Y1:Integer);
begin
MoveTo(X,Y0);
LineTo(X,Y1);
end;
procedure TPDFCanvas.RotateLabel3D(x,y,z:Integer; Const St:String; RotDegree:Double);
Procedure DoText(AX,AY: double; RotRad: double);
var tw,th: double;
vcos, vsin : double;
xc,yc: double;
FontIndex: Integer;
begin
WriteStringToStream(FCStream,PDFColor(Font.Color)+' rg ');
WriteStringToStream(FCStream,'BT ');
if Assigned(IFont) then WriteStringToStream(FCStream,FontProperties(IFont,FontIndex)+' ')
else WriteStringToStream(FCStream,FontProperties(TTeeFont(Font),FontIndex)+' ');
{ Get text width and height }
th := TextHeight(St);
if (TextAlign and TA_CENTER)=TA_CENTER then tw := TextWidth(St)*0.5
else if (TextAlign and TA_RIGHT)=TA_RIGHT then tw := TextWidth(St)
else tw := 0 ;
{$IFNDEF LINUX}
{ FIX :
the system uses 72 Pixelsperinch as a base line figure, most systems are
96 DPI or if your in large Font Mode then 120 DPI
So when using the TextWidth/TextHeight of the currently selected font, you get the wrong answer
}
tw := tw*72/FContents.FontArray.Items[FontIndex].FontData.DigAspX;
th := th*72/FContents.FontArray.Items[FontIndex].FontData.DigAspY;
{$ENDIF}
TranslateVertCoord(AY);
{ rotation elements }
vcos := Cos(RotRad);
vsin := Sin(RotRad);
{ rotated values }
xc := AX - (tw*vcos-th*vsin);
yc := AY - (tw*vsin+th*vcos);
tmpSt := FormatFloat('0.000',vcos)+ ' ' + FormatFloat('0.000',vsin)+ ' '+
FormatFloat('0.000',-vsin)+ ' ' + FormatFloat('0.000',vcos)+ ' '+
FormatFloat('0.000',xc)+ ' ' + FormatFloat('0.000',yc)+ ' Tm ';
FixSeparator(tmpSt);
WriteStringToStream(FCStream,tmpSt);
WriteStringToStream(FCStream,'('+TextToPDFText(St)+') Tj ');
WriteStringToStream(FCStream,'ET'+CRLF);
end;
var tmpX : Integer;
tmpY : Integer;
begin
Calc3DPos(X,Y,Z);
if Assigned(IFont) then
With IFont.Shadow do
if (HorizSize<>0) or (VertSize<>0) then
begin
if HorizSize<0 then
begin
tmpX:=X;
X:=X-HorizSize;
end
else tmpX:=X+HorizSize;
if VertSize<0 then
begin
tmpY:=Y;
Y:=Y-VertSize;
end
else tmpY:=Y+VertSize;
DoText(tmpX,tmpY, RotDegree*0.01745329);
end;
DoText(X,Y, RotDegree*0.01745329);
end;
procedure TPDFCanvas.RotateLabel(x,y:Integer; Const St:String; RotDegree:Double);
begin
RotateLabel3D(x,y,0,St,RotDegree);
end;
Procedure TPDFCanvas.Line(X0,Y0,X1,Y1:Integer);
begin
MoveTo(X0,Y0);
LineTo(X1,Y1);
end;
Procedure TPDFCanvas.HorizLine3D(Left,Right,Y,Z:Integer);
begin
MoveTo3D(Left,Y,Z);
LineTo3D(Right,Y,Z);
end;
Procedure TPDFCanvas.VertLine3D(X,Top,Bottom,Z:Integer);
begin
MoveTo3D(X,Top,Z);
LineTo3D(X,Bottom,Z);
end;
Procedure TPDFCanvas.ZLine3D(X,Y,Z0,Z1:Integer);
begin
MoveTo3D(X,Y,Z0);
LineTo3D(X,Y,Z1);
end;
Procedure TPDFCanvas.LineWithZ(X0,Y0,X1,Y1,Z:Integer);
begin
MoveTo3D(X0,Y0,Z);
LineTo3D(X1,Y1,Z);
end;
Function TPDFCanvas.GetBackMode:TCanvasBackMode;
begin
result:=FBackMode;
end;
Procedure TPDFCanvas.PolygonFour;
begin
Polygon(IPoints);
end;
Procedure TPDFCanvas.Polygon(const Points: Array of TPoint);
var t: Integer;
begin
if (Brush.Style<>bsClear) or (Pen.Style<>psClear) then
begin
if (Pen.Style<>psClear) then
WriteStringToStream(FCStream,PenProperties(Pen)+' ');
WriteStringToStream(FCStream,PointToStr(Points[0].X,Points[0].Y)+' m'+CRLF);
for t:=1 to High(Points) do
WriteStringToStream(FCStream,PointToStr(Points[t].X,Points[t].Y)+' l'+CRLF);
WriteStringToStream(FCStream,'h ');
if (Brush.Style<>bsClear) then
begin
WriteStringToStream(FCStream,BrushProperties(Brush));
if (Pen.Style<>psClear) then WriteStringToStream(FCStream,' B'+CRLF)
else WriteStringToStream(FCStream,' f'+CRLF);
end else WriteStringToStream(FCStream,' S'+CRLF);
end;
end;
function TPDFCanvas.InitWindow(DestCanvas: TCanvas;
A3DOptions: TView3DOptions; ABackColor: TColor; Is3D: Boolean;
const UserRect: TRect): TRect;
begin
result:=inherited InitWindow(DestCanvas,A3DOptions,ABackColor,Is3D,UserRect);
IClipCalled := False;
TheBounds;
end;
function TPDFCanvas.SelectFont(Font: TFont): Integer;
begin
Result := FContents.FontArray.Find(Font);
if Result = -1 then Result := FContents.FontArray.AddItem(Font,Handle);
end;
procedure TPDFCanvas.InternalDrawArc(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer; MoveTo0: boolean; DrawPie: boolean);
var fccwc: double;
procedure Rotate(var ax,ay: double; Angle: double);
var tx,ty: double;
vcos, vsin: double;
begin
vcos := Cos(Angle);
vsin := Sin(Angle);
tx := ax;
ty := ay;
ax := vcos*tx - vsin*ty;
ay := vsin*tx + vcos*ty;
end;
procedure ArcSegment(ax, ay, ra, rb, midtheta, hangle: double; amt0: Integer);
var ax1,ay1,ax2,ay2,ax3,ay3: double;
ax0,ay0: double;
hTheta: double;
vcos, vsin: double;
begin
if ra < rb then SwapDouble(ra,rb);
htheta := Abs(hangle);
vcos := Cos(htheta);
vsin := Sin(htheta);
ax0 := ra*vcos;
ay0 := -fccwc*ra*vsin;
Rotate(ax0,ay0,midtheta);
if (amt0 = 1) then tmpSt := FormatFloat('0.000',ax+ax0)+ ' ' + FormatFloat('0.000',ay+ay0) + ' m'+CRLF
else if (amt0 = 0) then tmpSt := FormatFloat('0.000',ax+ax0)+ ' ' + FormatFloat('0.000',ay+ay0) + ' l'+CRLF
else tmpSt := '';
ax1 := ra*(4.0 - vcos)/3.0;
ax2 := ax1;
ay1 := ra*fccwc *(1.0 - vcos) * (vcos - 3.0) / (3.0*vsin);
ay2 := -ay1;
ax3 := ra*vcos;
ay3 := fccwc*ra*vsin;
Rotate(ax1, ay1, midtheta);
Rotate(ax2, ay2, midtheta);
Rotate(ax3, ay3, midtheta);
tmpSt := tmpSt+InternalBezCurve(ax+ax1,ay+ay1,ax+ax2,ay+ay2,ax+ax3,ay+ay3);
FixSeparator(tmpSt);
WriteStringToStream(FCStream,tmpSt);
end;
var SegCount,i: Integer;
CurrAngle, Span : double;
AngleBump, hBump: double;
x,y,a,b,StartAngle,EndAngle: double;
rat,tr: double;
begin
if (Brush.Style<>bsClear) or (Pen.Style<>psClear) then
begin
WriteStringToStream(FCStream,PenProperties(Pen));
if (Brush.Style<>bsClear) and (DrawPie) then
WriteStringToStream(FCStream,' '+ BrushProperties(Brush)+CRLF)
else WriteStringToStream(FCStream,' ');
{ center pos + radius }
x := (X1 + X2)*0.5;
y := (Y1 + Y2)*0.5;
a := (X2 - X1)*0.5;
b := (Y2 - Y1)*0.5;
{ this is only approx. algorithm }
if a <> b then
begin
WriteStringToStream(FCStream,'q'+CRLF);
if a>b then
begin
rat := b/a;
tr := y*(1.0-rat);
tmpSt := '1 0 0 ' + FormatFloat('0.000',rat) + ' 0 '+ FormatFloat('0.000',tr);
end else
begin
rat := a/b;
tr := x*(1.0-rat);
tmpSt := FormatFloat('0.000',rat)+ ' 0 0 1 '+ FormatFloat('0.000',tr) + ' 0';
end;
FixSeparator(tmpSt);
tmpSt := tmpSt + ' cm'+CRLF;
WriteStringToStream(FCStream,tmpSt);
end;
{ StartAngle }
CurrAngle := Math.ArcTan2(Y-Y3, X3 - X);
if CurrAngle<0 then CurrAngle:=2.0*Pi+CurrAngle;
StartAngle := CurrAngle;
{ EndAngle }
Currangle := Math.ArcTan2(Y-Y4, X4 - X);
if CurrAngle<=0 then CurrAngle:=2.0*Pi+CurrAngle;
EndAngle := CurrAngle;
If DrawPie then WriteStringToStream(FCStream,PointToStr(x,y)+' m'+CRLF);
TranslateVertCoord(y);
fccwc := 1.0;
SegCount := 1;
Span := EndAngle - StartAngle;
if EndAngle < StartAngle then fccwc := -1.0;
while (Abs(Span)/SegCount > Pi*0.5) do Inc(SegCount);
AngleBump := Span/SegCount;
hBump := 0.5*AngleBump;
CurrAngle := StartAngle + hBump;
for i := 0 to SegCount -1 do
begin
if i = 0 then ArcSegment(x,y,a,b,CurrAngle,hBump,Integer(MoveTo0))
else ArcSegment(x,y,a,b,CurrAngle,hBump,-1);
CurrAngle := CurrAngle + AngleBump;
end;
if (Brush.Style<>bsClear) and (DrawPie) then
if (Pen.Style<>psClear) then WriteStringToStream(FCStream,' h B'+CRLF) else WriteStringToStream(FCStream,' h f'+CRLF)
else if DrawPie then WriteStringToStream(FCStream,' s'+CRLF)
else if Not(DrawPie) then WriteStringToStream(FCStream,' S'+CRLF);
if a<>b then WriteStringToStream(FCStream,'Q'+CRLF);
end;
end;
{ Transform ( , ) and \ characters}
function TPDFCanvas.TextToPDFText(AText: String): String;
begin
AText := StringReplace(AText,'\','\\',[rfReplaceAll,rfIgnoreCase]);
AText := StringReplace(AText,'(','\(',[rfReplaceAll,rfIgnoreCase]);
AText := StringReplace(AText,')','\)',[rfReplaceAll,rfIgnoreCase]);
Result := AText;
end;
function TPDFCanvas.TextHeight(const St: String): Integer;
begin
Result := inherited TextHeight(St);
end;
function TPDFCanvas.TextWidth(const St: String): Integer;
begin
Result := inherited TextWidth(St);
end;
procedure TPDFCanvas.InternalDrawImage(sx, sy, tx,ty: double;
ImageIndex: Integer);
begin
WriteStringToStream(FCStream,'q ');
tmpSt := FormatFloat('0.000',sx) + ' 0 0 ' +
FormatFloat('0.000',sy) + ' ' + FormatFloat('0.000',tx) + ' ' +
FormatFloat('0.000',ty);
FixSeparator(tmpSt);
tmpSt := tmpSt + ' cm /Im'+ IntToStr(ImageIndex)+' Do Q';
WriteStringToStream(FCStream, tmpSt+CRLF);
end;
procedure TPDFCanvas.SetEmbeddedFonts(const Value: boolean);
begin
FEmbeddedFonts := Value;
end;
procedure TPDFCanvas.WriteToStream(AStream: TStream);
begin
end;
constructor TPDFCanvas.Create(AChartObject: TPDFChartObject);
begin
inherited Create;
FBackMode := cbmTransparent;
UseBuffer:=False;
FContents := AChartObject;
FCStream := FContents.Contents;
end;
{ TPDFExportFormat }
function TPDFExportFormat.Description: String;
begin
result:=TeeMsg_AsPDF;
end;
function TPDFExportFormat.FileExtension: String;
begin
result:='pdf';
end;
function TPDFExportFormat.FileFilter: String;
begin
result:=TeeMsg_PDFFilter;
end;
procedure TPDFExportFormat.DoCopyToClipboard;
(*var
buf: PChar;
buflen : Integer;
*)
begin
(*With PDFPage do
try
bufLen := Size;
Position := 0;
buf := AllocMem(buflen+1);
try
Read(buf^,buflen+1);
ClipBoard.AsText:=buf; // SetTextBuf(buf);
finally
FreeMem(buf);
end;
finally
Free;
end;
*)
end;
function TPDFExportFormat.Options(Check:Boolean): TForm;
begin
result:=nil;
end;
procedure TPDFExportFormat.SaveToStream(Stream: TStream);
begin
with PDFPage do
try
SaveToStream(Stream);
finally
Free;
end;
end;
type TTeePanelAccess=class(TCustomTeePanel);
function TPDFExportFormat.PDFPage: TTeePDFPage;
var tmp : TCanvas3D;
begin { return a panel or chart in PDF format into a StringList }
CheckSize;
Result := TTeePDFPage.Create;
Panel.AutoRepaint := False;
try
Result.PageWidth := Width;
Result.PageHeight := Height;
{$IFNDEF CLR}
tmp:=TTeePanelAccess(Panel).InternalCanvas;
TTeePAnelAccess(Panel).InternalCanvas:=nil;
{$ENDIF}
Panel.Canvas := TPDFCanvas.Create(Result.ChartObject);
try
Panel.Draw(Panel.Canvas.ReferenceCanvas,TeeRect(0,0,Width,Height));
finally
Panel.Canvas:=tmp;
end;
finally
Panel.AutoRepaint:=True;
end;
end;
procedure TeeSaveToPDFFile( APanel:TCustomTeePanel; const FileName: WideString;
AWidth:Integer=0;
AHeight: Integer=0);
begin { save panel or chart to filename in VML (html) format }
with TPDFExportFormat.Create do
try
Panel:=APanel;
Height:=AHeight;
Width:=AWidth;
SaveToFile(FileName);
finally
Free;
end;
end;
procedure TPDFCanvas.TranslateVertCoord(var Y: double);
begin
{ vertical coordinate is reversed in PDF !! }
Y := IHeight - Y;
end;
function TPDFCanvas.SetPenStyle(PenStyle: TPenStyle): String;
begin
case PenStyle of
psSolid : Result := '[ ] 0 d';
psDash : Result := '[3 3] 0 d';
psDot : Result := '[2] 1 d';
psDashDot : Result := '[3 2] 2 d';
else Result := '[ ] 0 d';
end;
end;
function TPDFCanvas.PenProperties(Pen: TPen): String;
begin
Result := PDFColor(Pen.Color)+ ' RG ' +
IntToStr(Pen.Width)+' w ' +
SetPenStyle(Pen.Style);
end;
function TPDFCanvas.BrushProperties(Brush: TBrush): String;
begin
Result := PDFColor(Brush.Color)+' rg';
end;
destructor TPDFCanvas.Destroy;
begin
inherited Destroy;
end;
function TPDFCanvas.FontProperties(Font: TTeeFont; var FontIndex: Integer): String;
begin
FontIndex := SelectFont(Font);
Result := '/F'+ IntToStr(FontIndex) + ' ' +
IntToStr(Font.Size)+ ' Tf '+
IntToStr(Font.InterCharSize) + ' Tc ';
end;
{ TFontListEntry }
constructor TTeePDFFontListEntry.Create(AFont: TFont);
begin
inherited Create;
FPDFName := PDFFontName(AFont);
DefineFontData(AFont);
end;
procedure TTeePDFFontListEntry.DefineFontData(AFont: TFont);
var FontInfo: {$IFNDEF CLR}^{$ENDIF}TOutlineTextMetric;
fnt: HFont;
m_hdcFont: HDC;
begin
{$IFNDEF CLR}
New(FontInfo);
{$ENDIF}
try
fnt := CreateFont(-1000, 0, 0, 0, FW_DONTCARE, 0, 0, 0,
{$IFDEF CLX}
1
{$ELSE}
DEFAULT_CHARSET
{$ENDIF},
OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
DEFAULT_QUALITY, DEFAULT_PITCH or FF_DONTCARE,
{$IFNDEF CLR}PChar{$ENDIF}(AFont.Name));
m_hdcFont := GetDC(0);
SelectObject(m_hdcFont, fnt);
DeleteObject( fnt );
GetOutlineTextMetrics(m_hdcFont,SizeOf(TOutlineTextMetric),FontInfo);
With FFontData do
begin
DigAspX := FontInfo.otmTextMetrics.tmDigitizedAspectX;
DigAspY := FontInfo.otmTextMetrics.tmDigitizedAspectY;
FontBBox := FontInfo.otmrcFontBox;
FirstChar := Ord(FontInfo.otmTextMetrics.tmFirstChar);
LastChar := Ord(FontInfo.otmTextMetrics.tmLastChar);
CapHeight := FontInfo.otmsCapEmHeight;
Ascent := FontInfo.otmTextMetrics.tmAscent;
Descent := -FontInfo.otmTextMetrics.tmDescent;
MaxWidth := FontInfo.otmTextMetrics.tmMaxCharWidth;
AvgWidth := FontInfo.otmTextMetrics.tmAveCharWidth;
ItalicAngle := FontInfo.otmItalicAngle;
GetCharWidth(m_hdcFont,0,255,CharWidths);
end;
finally
{$IFNDEF CLR}
Dispose(FontInfo);
{$ENDIF}
end;
end;
{ TFontList }
function TTeePDFFontList.AddItem(AFont: TFont; AHandle: TTeeCanvasHandle): Integer;
begin
Result := IFontList.Add(TTeePDFFontListEntry.Create(AFont));
end;
constructor TTeePDFFontList.Create;
begin
inherited;
IFontList := TList.Create;
end;
destructor TTeePDFFontList.Destroy;
var i: Integer;
begin
for i := 0 to IFontList.Count - 1 do TTeePDFFontListEntry(IFontList.Items[i]).Free;
IFontList.Free;
inherited Destroy;
end;
function TTeePDFFontList.Find(AFont: TFont): Integer;
var i: Integer;
tmpName: String;
begin
Result := -1;
tmpName := PDFFontName(AFont);
for i := 0 to IFontList.Count - 1 do
if tmpName = TTeePDFFontListEntry(IFontList.Items[i]).PDFName then
begin
Result := i;
Break;
end;
end;
function TTeePDFFontList.GetCount: Integer;
begin
Result := IFontList.Count;
end;
function TTeePDFFontList.GetFontEntry(Index: Integer): TTeePDFFontListEntry;
begin
Result := TTeePDFFontListEntry(IFontList.Items[Index]);
end;
function TPDFExportFormat.ChartObject: TPDFChartObject;
var tmp : TCanvas3D;
begin { return a panel or chart in PDF format into a StringList }
CheckSize;
Result := TPDFChartObject.Create;
Panel.AutoRepaint := False;
try
{$IFNDEF CLR}
tmp := TTeePanelAccess(Panel).InternalCanvas;
TTeePAnelAccess(Panel).InternalCanvas := nil;
{$ENDIF}
Panel.Canvas := TPDFCanvas.Create(Result);
try
Panel.Draw(Panel.Canvas.ReferenceCanvas,TeeRect(0,0,Width,Height));
finally
Panel.Canvas:=tmp;
end;
finally
Panel.AutoRepaint:=True;
end;
end;
{ TPDFChartObject }
constructor TPDFChartObject.Create;
begin
inherited Create;
FFontArray := TTeePDFFontList.Create;
FImageArray := TTeePDFImageList.Create;
FContents := TMemoryStream.Create;
end;
destructor TPDFChartObject.Destroy;
begin
FFontArray.Free;
FImageArray.Free;
FContents.Free;
inherited;
end;
function TPDFChartObject.GetLength: Integer;
begin
Result := FContents.Size;
end;
procedure TPDFChartObject.SaveToStream(AStream: TStream);
begin
WriteStringToStream(AStream,'<< /Length '+IntToStr(GetLength)+ ' >>'+CRLF);
WriteStringToStream(AStream,'stream'+CRLF);
AStream.CopyFrom(FContents,0);
WriteStringToStream(AStream,'endstream'+CRLF);
end;
{ TTeePDFPage }
procedure TTeePDFPage.AddToOffset(Offset: Integer);
begin
OffsetList.Add(FormatIntToString(OffSet, 10));
end;
constructor TTeePDFPage.Create;
begin
inherited Create;
IObjCount := 0;
FChartObject := TPDFChartObject.Create;
OffsetList := TStringList.Create;
end;
destructor TTeePDFPage.Destroy;
begin
FChartObject.Free;
OffsetList.Clear;
inherited;
end;
procedure TTeePDFPage.SaveToStream(AStream: TStream);
begin
WriteHeader(AStream);
WriteInfo(AStream);
// write chart canvas code
Inc(IObjCount);
AddToOffset(AStream.Size);
WriteStringToStream(AStream,IntToStr(IObjCount)+ ' 0 obj'+CRLF);
FChartObject.SaveToStream(AStream);
WriteStringToStream(AStream,'endobj'+CRLF);
// TT fonts
WriteTTFonts(AStream);
// Additional images, if they exist
WriteImages(AStream);
// Resources
WriteResources(AStream);
// Pages and page
WritePages(AStream);
WritePage(AStream);
WriteCatalog(AStream);
WriteXRef(AStream);
WriteStringToStream(AStream,'%%EOF'+CRLF);
end;
procedure TTeePDFPage.SetPageHeight(const Value: Integer);
begin
FPageHeight := Value;
end;
procedure TTeePDFPage.SetPageWidth(const Value: Integer);
begin
FPageWidth := Value;
end;
procedure TTeePDFPage.WriteCatalog(AStream: TStream);
begin
Inc(IObjCount);
CatalogNum := IObjCount;
AddToOffset(AStream.Size);
WriteStringToStream(AStream,IntToStr(IObjCount)+' 0 obj'+CRLF);
WriteStringToStream(AStream,'<< /Type /Catalog' + CRLF);
WriteStringToStream(AStream,'/Pages ' + IntToStr(ParentNum) + ' 0 R'+ CRLF);
WriteStringToStream(AStream,'>>'+CRLF);
WriteStringToStream(AStream,'endobj'+CRLF);
end;
procedure TTeePDFPage.WriteHeader(AStream: TStream);
begin
WriteStringToStream(AStream,'%PDF-1.4'+CRLF);
end;
procedure TTeePDFPage.WriteImages(AStream: TStream);
var i: Integer;
begin
with FChartObject.ImageArray do
begin
for i := 0 to ItemsCount -1 do
begin
Inc(IObjCount);
AddToOffset(AStream.Size);
Items[i].ObjectNumber := IObjCount;
WriteStringToStream(AStream,IntToStr(IObjCount)+' 0 obj'+CRLF);
WriteStringToStream(AStream,'<< /Type /XObject'+CRLF);
WriteStringToStream(AStream,'/Subtype /Image'+CRLF);
WriteStringToStream(AStream,'/Name /Im'+IntToStr(i)+CRLF);
WriteStringToStream(AStream,'/Length '+IntToStr(Items[i].DataLength)+CRLF);
WriteStringToStream(AStream,'/Width '+IntToStr(Items[i].Width)+CRLF);
WriteStringToStream(AStream,'/Height '+IntToStr(Items[i].Height)+CRLF);
WriteStringToStream(AStream,'/ColorSpace /DeviceRGB'+CRLF);
WriteStringToStream(AStream,'/BitsPerComponent 8'+CRLF);
if Items[i].ImageType = itJPEG then WriteStringToStream(AStream,'/Filter [/DCTDecode]'+CRLF);
WriteStringToStream(AStream,'>>'+CRLF);
WriteStringToStream(AStream,'stream'+CRLF);
Items[i].WriteDataToStream(AStream);
WriteStringToStream(AStream,'endstream'+CRLF);
WriteStringToStream(AStream,'endobj'+CRLF);
end;
end;
end;
procedure TTeePDFPage.WriteInfo(AStream: TStream);
begin
Inc(IObjCount);
AddToOffset(AStream.Size);
WriteStringToStream(AStream,IntToStr(IObjCount)+' 0 obj'+CRLF);
tmpSt := '<<'+CRLF+'/Creator (' + TeeMsg_Version +')'+CRLF+'/Producer (' + TeeMsg_Version+')'+CRLF+
'/CreationDate (D:'+FormatDateTime('YYYYMMDDHHmmSS',Now)+')'+CRLF+'/ModDate ()' + CRLF +
'/Keywords ()'+CRLF+'/Title (TChart Export)' + CRLF+'>>'+CRLF;
WriteStringToStream(AStream, tmpSt);
WriteStringToStream(AStream,'endobj'+CRLF);
end;
procedure TTeePDFPage.WritePage(AStream: TStream);
begin
Inc(IObjCount);
AddToOffset(AStream.Size);
WriteStringToStream(AStream,IntToStr(IObjCount)+' 0 obj'+CRLF);
WriteStringToStream(AStream,'<< /Type /Page' + CRLF + '/Parent '+IntToStr(ParentNum)+ ' 0 R'+CRLF);
WriteStringToStream(AStream,'/MediaBox [ 0 0 ' + IntToStr(FPageWidth) + ' ' + IntToStr(FPageHeight) + ' ]'+CRLF);
WriteStringToStream(AStream,'/Contents 2 0 R'+CRLF);
WriteStringToStream(AStream,'/Resources ' + IntToStr(ResourceNum)+' 0 R'+CRLF);
WriteStringToStream(AStream,'>>'+CRLF);
WriteStringToStream(AStream,'endobj'+CRLF);
end;
procedure TTeePDFPage.WritePages(AStream: TStream);
begin
Inc(IObjCount);
AddToOffset(AStream.Size);
ParentNum := IObjCount;
WriteStringToStream(AStream,IntToStr(IObjCount)+' 0 obj'+CRLF);
// Must be followed by WritePage call, otherwise object reference will not be correct
tmpSt := '<< /Type /Pages' + CRLF + '/Kids [' + IntToStr(IObjCount+1)+' 0 R]'+CRLF+
'/Count 1'+CRLF+'>>'+CRLF;
WriteStringToStream(AStream,tmpSt);
WriteStringToStream(AStream,'endobj'+CRLF);
end;
procedure TTeePDFPage.WriteResources(AStream: TStream);
var i: Integer;
begin
Inc(IObjCount);
ResourceNum := IObjCount;
AddToOffset(AStream.Size);
WriteStringToStream(AStream,IntToStr(IObjCount)+' 0 obj'+CRLF);
WriteStringToStream(AStream,'<< /ProcSet [/PDF /Text /ImageC]'+CRLF);
With FChartObject do
begin
WriteStringToStream(AStream,'/Font << '+CRLF);
for i := 0 to FontArray.ItemsCount -1 do
WriteStringToStream(AStream,'/F'+IntToStr(i) + ' ' + IntToStr(FontArray.Items[i].ObjectNumber)+' 0 R'+CRLF);
WriteStringToStream(AStream,'>>'+CRLF);
WriteStringToStream(AStream,'/XObject << '+CRLF);
for i := 0 to ImageArray.ItemsCount -1 do
WriteStringToStream(AStream,'/Im'+IntToStr(i) + ' ' + IntToStr(ImageArray.Items[i].ObjectNumber)+' 0 R'+CRLF);
WriteStringToStream(AStream,'>>'+CRLF);
end;
WriteStringToStream(AStream,'>>'+CRLF);
WriteStringToStream(AStream,'endobj'+CRLF);
end;
procedure TTeePDFFontListEntry.SetObjectNumber(const Value: Integer);
begin
FObjectNumber := Value;
end;
procedure TTeePDFPage.WriteTrailer(AStream: TStream);
begin
WriteStringToStream(AStream,'trailer'+CRLF);
WriteStringToStream(AStream,'<< /Size '+ IntToStr(IObjCount)+CRLF);
WriteStringToStream(AStream,'/Root '+ IntToStr(CatalogNum)+ ' 0 R'+CRLF);
WriteStringToStream(AStream,'/Info 1 0 R'+CRLF);
WriteStringToStream(AStream,'>>'+CRLF);
WriteStringToStream(AStream,'startxref'+CRLF);
WriteStringToStream(AStream,IntToStr(XRefPos)+CRLF);
end;
procedure TTeePDFPage.WriteTTFonts(AStream: TStream);
var i,j: Integer;
begin
With FChartObject.FontArray do
begin
for i := 0 to ItemsCount -1 do
begin
// font header
Inc(IObjCount);
AddToOffset(AStream.Size);
Items[i].ObjectNumber := IObjCount;
WriteStringToStream(AStream,IntToStr(IObjCount)+' 0 obj'+CRLF);
WriteStringToStream(AStream,'<< /Type /Font'+CRLF);
WriteStringToStream(AStream,'/Subtype /TrueType'+CRLF);
WriteStringToStream(AStream,'/BaseFont /'+ Items[i].PDFName+CRLF);
WriteStringToStream(AStream,'/Name /F'+IntToStr(i)+CRLF);
WriteStringToStream(AStream,'/FirstChar '+ IntToStr(Items[i].FontData.FirstChar)+CRLF);
WriteStringToStream(AStream,'/LastChar '+ IntToStr(Items[i].FontData.LastChar)+CRLF);
WriteStringToStream(AStream,'/Encoding /WinAnsiEncoding'+CRLF);
WriteStringToStream(AStream,'/FontDescriptor '+ IntToStr(IObjCount+1)+ ' 0 R'+CRLF);
WriteStringToStream(AStream,'/Widths '+ IntToStr(IObjCount+2)+' 0 R'+CRLF);
WriteStringToStream(AStream,'>>'+CRLF);
WriteStringToStream(AStream,'endobj'+CRLF);
// Font descriptor
Inc(IObjCount);
AddToOffset(AStream.Size);
WriteStringToStream(AStream,IntToStr(IObjCount)+' 0 obj'+CRLF);
WriteStringToStream(AStream,'<< /Type /FontDescriptor'+CRLF);
WriteStringToStream(AStream,'/FontName /'+ Items[i].PDFName+CRLF);
WriteStringToStream(AStream,'/Flags 32'+CRLF);
With Items[i].FontData do
begin
WriteStringToStream(AStream,'/FontBBox ['+
IntToStr(FontBBox.Left)+ ' ' +
IntToStr(FontBBox.Bottom)+ ' ' +
IntToStr(FontBBox.Right)+ ' ' +
IntToStr(FontBBox.Top)+ ']' + CRLF);
WriteStringToStream(AStream,'/CapHeight ' + IntToStr(CapHeight)+CRLF);
WriteStringToStream(AStream,'/Ascent ' + IntToStr(Ascent)+CRLF);
WriteStringToStream(AStream,'/Descent ' + IntToStr(Descent)+CRLF);
WriteStringToStream(AStream,'/MaxWidth ' + IntToStr(MaxWidth)+CRLF);
WriteStringToStream(AStream,'/AvgWidth ' + IntToStr(AvgWidth)+CRLF);
WriteStringToStream(AStream,'/ItalicAngle ' + IntToStr(ItalicAngle)+CRLF);
WriteStringToStream(AStream,'/StemV 0'+CRLF);
end;
WriteStringToStream(AStream,'>>'+CRLF);
WriteStringToStream(AStream,'endobj'+CRLF);
// Font widths
Inc(IObjCount);
AddToOffset(AStream.Size);
WriteStringToStream(AStream,IntToStr(IObjCount)+' 0 obj'+CRLF);
WriteStringToStream(AStream,'['+CRLF);
tmpSt := '';
for j := Items[i].FontData.FirstChar to Items[i].FontData.LastChar do
if (j mod 15 = 14) then tmpSt := tmpSt + IntToStr(Items[i].FontData.CharWidths[j]) + ' '+CRLF
else tmpSt := tmpSt + IntToStr(Items[i].FontData.CharWidths[j]) + ' ';
WriteStringToStream(AStream,tmpSt+CRLF);
WriteStringToStream(AStream,']'+CRLF);
WriteStringToStream(AStream,'endobj'+CRLF);
end;
end;
end;
procedure TTeePDFPage.WriteXRef(AStream: TStream);
var i: Integer;
begin
Inc(IObjCount);
// no need to add xref to xref itself.
XRefPos := AStream.Size;
WriteStringToStream(AStream,'xref'+CRLF);
WriteStringToStream(AStream,'0 '+IntToStr(IObjCount)+CRLF);
WriteStringToStream(AStream,'0000000000 65535 f'+CRLF);
for i := 0 to OffSetList.Count - 1 do
WriteStringToStream(AStream,OffsetList.Strings[i]+' ' + FormatIntToString(0,5)+' n'+ CRLF);
WriteTrailer(AStream);
end;
{ TTeePDFImageList }
function TTeePDFImageList.AddItem(AGraphic: TGraphic): Integer;
begin
Result := IImageList.Add(TTeePDFImageListEntry.Create(AGraphic));
end;
constructor TTeePDFImageList.Create;
begin
inherited;
IImageList := TList.Create;
end;
destructor TTeePDFImageList.Destroy;
var i: Integer;
begin
for i := 0 to IImageList.Count - 1 do TTeePDFImageListEntry(IImageList.Items[i]).Free;
IImageList.Free;
inherited Destroy;
end;
function TTeePDFImageList.EqualImages(i1, i2: TGraphic): Boolean;
var ms: TMemoryStream;
s1,s2: String;
b:Boolean;
begin
{$IFNDEF CLR}
ms := TMemoryStream.Create;
try
i1.SaveToStream(ms);
ms.Position := 0;
SetLength(s1,ms.Size);
ms.Read(S1[1],Length(s1));
ms.Clear;
i2.SaveToStream(ms);
ms.Position := 0;
SetLength(s2,ms.Size);
ms.Read(S2[1],Length(s2));
finally
ms.Free;
end;
b:=s1=s2;
result:=b;
{$ELSE}
result:=False;
{$ENDIF}
end;
function TTeePDFImageList.Find(AGraphic: TGraphic): Integer;
var i: Integer;
begin
Result := -1;
for i := 0 to ItemsCount-1 do
if EqualImages(AGraphic,Items[i].FGraphic) then
begin
Result := i;
Break;
end;
end;
function TTeePDFImageList.GetCount: Integer;
begin
Result := IImageList.Count;
end;
function TTeePDFImageList.GetImageEntry(
Index: Integer): TTeePDFImageListEntry;
begin
Result := TTeePDFImageListEntry(IImageList.Items[Index]);
end;
{ TTeePDFImageListEntry }
constructor TTeePDFImageListEntry.Create(AGraphic: TGraphic);
begin
inherited Create;
FGraphic := AGraphic;
DefineImageData;
end;
procedure TTeePDFImageListEntry.DefineImageData;
begin
FWidth := FGraphic.Width;
FHeight := FGraphic.Height;
end;
function TTeePDFImageListEntry.GetDataLength: Integer;
var ms : TMemoryStream;
begin
ms := TMemoryStream.Create;
try
FGraphic.SaveToStream(ms);
Result := ms.Size;
finally
ms.Free;
end;
end;
function TTeePDFImageListEntry.GetImageType: TImageType;
begin
{$IFNDEF CLR}
{$IFNDEF CLX}
if (FGraphic is TJPEGImage) then Result := itJPEG
else
{$ENDIF}
{$ENDIF}
if (FGraphic is TBitmap) then Result := itBitmap
else Result := itUnknown;
end;
procedure TTeePDFImageListEntry.SetObjectNumber(const Value: Integer);
begin
FObjectNumber := Value;
end;
function TPDFCanvas.SelectImage(Graphic: TGraphic): integer;
begin
Result := FContents.ImageArray.Find(Graphic);
if Result = -1 then Result := FContents.ImageArray.AddItem(Graphic);
end;
procedure TTeePDFImageListEntry.WriteDataToStream(AStream: TStream);
const BytesPerPixel={$IFDEF CLX}4{$ELSE}3{$ENDIF};
var x,y: Integer;
pb: {$IFDEF CLR}IntPtr{$ELSE}PByteArray{$ENDIF};
b: Byte;
begin
{$IFNDEF CLR}
{$IFNDEF CLX}
if FGraphic is TJpegImage then
(FGraphic as TJpegImage).SaveToStream(AStream)
else
{$ENDIF}
{$ENDIF}
if FGraphic is TBitmap then
with (FGraphic as TBitmap) do
begin
if PixelFormat<>TeePixelFormat then PixelFormat:=TeePixelFormat;
{$IFNDEF CLR}
for y := 0 to Height -1 do
begin
pb := ScanLine[y];
x := 0;
while x < Width*BytesPerPixel do
begin
b := pb[x];
pb[x] := pb[x+2];
pb[x+2] := b;
AStream.Write(pb[x],3);
Inc(x,BytesPerPixel);
end;
end;
{$ENDIF}
end;
WriteStringToStream(AStream,CRLF);
end;
initialization
RegisterTeeExportFormat(TPDFExportFormat);
finalization
UnRegisterTeeExportFormat(TPDFExportFormat);
end.
|
unit uSHA;
interface
uses
Windows, Classes, uOpenSSLConst;
const
SHA_LBLOCK = 16;
SHA_CBLOCK = SHA_LBLOCK * 4;///* SHA treats input data as a
//* contiguous array of 32 bit
//* wide big-endian values. */
SHA_LAST_BLOCK = (SHA_CBLOCK-8);
SHA_DIGEST_LENGTH = 20;
SHA256_CBLOCK = (SHA_LBLOCK*4); //* SHA-256 treats input data as a
//* contiguous array of 32 bit
//* wide big-endian values. */
SHA224_DIGEST_LENGTH = 28;
SHA256_DIGEST_LENGTH = 32;
SHA384_DIGEST_LENGTH = 48;
SHA512_DIGEST_LENGTH = 64;
SHA512_CBLOCK = (SHA_LBLOCK*8); ///* SHA-512 treats input data as a
//* contiguous array of 64 bit
//* wide big-endian values. */
type
SHA_LONG = Cardinal;
SHA_LONG64 = Int64;
// typedef struct SHAstate_st
// {
// SHA_LONG h0,h1,h2,h3,h4;
// SHA_LONG Nl,Nh;
// SHA_LONG data[SHA_LBLOCK];
// unsigned int num;
// } SHA_CTX;
SHAstate_st = record
h0,h1,h2,h3,h4: SHA_LONG;
Nl,Nh : SHA_LONG;
data : array[0..SHA_LBLOCK-1] of SHA_LONG;
num : Cardinal;
end;
SHA_CTX = SHAstate_st;
PSHA_CTX = ^SHA_CTX;
//typedef struct SHA256state_st
// {
// SHA_LONG h[8];
// SHA_LONG Nl,Nh;
// SHA_LONG data[SHA_LBLOCK];
// unsigned int num,md_len;
// } SHA256_CTX;
SHA256state_st = record
h : array[0..7] of SHA_LONG;
Nl,Nh : SHA_LONG;
data : array[0..SHA_LBLOCK - 1] of SHA_LONG;
num,md_len: Cardinal;
end;
SHA256_CTX = SHA256state_st;
PSHA256_CTX = ^SHA256_CTX;
//typedef struct SHA512state_st
// {
// SHA_LONG64 h[8];
// SHA_LONG64 Nl,Nh;
// union {
// SHA_LONG64 d[SHA_LBLOCK];
// unsigned char p[SHA512_CBLOCK];
// } u;
// unsigned int num,md_len;
// } SHA512_CTX;
_u = record
d: array[0..SHA_LBLOCK] of SHA_LONG64;
p: array[0..SHA512_CBLOCK - 1] of Byte;
end;
SHA512state_st = record
h: array[0..7] of SHA_LONG64;
Nl,Nh: SHA_LONG64;
u: _u;
num,md_len: Cardinal;
end;
//SHA
//int SHA_Init(SHA_CTX *c);
function SHA_Init(c: PSHA_CTX): Integer; cdecl; external LIBEAY32;
//int SHA_Update(SHA_CTX *c, const void *data, size_t len);
function SHA_Update(c: PSHA_CTX; data: Pointer; len: size_t): Integer; cdecl; external LIBEAY32;
//int SHA_Final(unsigned char *md, SHA_CTX *c);
function SHA_Final(md: array of Byte; c: PSHA_CTX): Integer; cdecl; external LIBEAY32;
//unsigned char *SHA(const unsigned char *d, size_t n, unsigned char *md);
function SHA(const d: PByte; n: size_t; md: array of Byte): PByte; cdecl; external LIBEAY32;
//SHA1
//int SHA1_Init(SHA_CTX *c);
function SHA1_Init(c: PSHA_CTX): Integer; cdecl; external LIBEAY32;
//int SHA1_Update(SHA_CTX *c, const void *data, size_t len);
function SHA1_Update(c: PSHA_CTX; data: Pointer; len: size_t): Integer; cdecl; external LIBEAY32;
//int SHA1_Final(unsigned char *md, SHA_CTX *c);
function SHA1_Final(md: array of Byte; c: PSHA_CTX): Integer; cdecl; external LIBEAY32;
//unsigned char *SHA1(const unsigned char *d, size_t n, unsigned char *md);
function SHA1(const d: PByte; n: size_t; md: array of Byte): PByte; cdecl; external LIBEAY32;
//SHA224
//int SHA224_Init(SHA256_CTX *c);
function SHA224_Init(c: PSHA256_CTX): Integer; cdecl; external LIBEAY32;
//int SHA224_Update(SHA256_CTX *c, const void *data, size_t len);
function SHA224_Update(c: PSHA256_CTX; data: Pointer; len: size_t): Integer; cdecl; external LIBEAY32;
//int SHA224_Final(unsigned char *md, SHA256_CTX *c);
function SHA224_Final(md: array of Byte; c: PSHA256_CTX): Integer; cdecl; external LIBEAY32;
//unsigned char *SHA224(const unsigned char *d, size_t n,unsigned char *md);
function SHA224(const d: PByte; n: size_t; md: array of Byte): PByte; cdecl; external LIBEAY32;
//SHA256
//int SHA256_Init(SHA256_CTX *c);
function SHA256_Init(c: PSHA256_CTX): Integer; cdecl; external LIBEAY32;
//int SHA256_Update(SHA256_CTX *c, const void *data, size_t len);
function SHA256_Update(c: PSHA256_CTX; data: Pointer; len: size_t): Integer; cdecl; external LIBEAY32;
//int SHA256_Final(unsigned char *md, SHA256_CTX *c);
function SHA256_Final(md: array of Byte; c: PSHA256_CTX): Integer; cdecl; external LIBEAY32;
//unsigned char *SHA256(const unsigned char *d, size_t n,unsigned char *md);
function SHA256(const d: PByte; n: size_t; md: array of Byte): PByte; cdecl; external LIBEAY32;
implementation
end.
|
{*******************************************************}
{ }
{ Delphi REST Client Framework }
{ }
{ Copyright(c) 2013-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
/// <summary>
/// REST.Client is a foundation for simplifying the creation of specific REST API Clients.
/// </summary>
unit REST.Client;
interface
uses
System.SysUtils, System.JSON, System.Classes, System.Generics.Collections,
System.Net.URLClient, System.Net.HttpClient, System.JSON.Writers, System.JSON.Readers,
Data.Bind.ObjectScope, Data.Bind.Components,
REST.HttpClient, REST.Types, REST.BindSource;
{$SCOPEDENUMS ON}
const
RESTCLIENT_VERSION = '1.0';
type
IRESTResponseJSON = interface;
TRESTRequestParameter = class;
TRESTRequestParameterList = class;
TCustomRESTRequest = class;
TCustomRESTResponse = class;
TCustomRESTClient = class;
TCustomAuthenticator = class;
TSubRESTRequestBindSource = class;
TSubRESTResponseBindSource = class;
TSubRESTClientBindSource = class;
IRESTResponseJSON = interface
['{71F5FA19-69CC-4384-AC0A-D6E30AD5CC95}']
procedure AddJSONChangedEvent(const ANotify: TNotifyEvent);
procedure RemoveJSONChangedEvent(const ANotify: TNotifyEvent);
procedure GetJSONResponse(out AJSONValue: TJSONValue; out AHasOwner: Boolean);
function HasJSONResponse: Boolean;
function HasResponseContent: Boolean;
end;
/// <summary>
/// Parameter for REST requests
/// </summary>
TRESTRequestParameter = class(TCollectionItem)
private
FName: string;
FValue: string;
FStream: TStream;
FStreamOwner: Boolean;
FKind: TRESTRequestParameterKind;
FContentType: TRESTContentType;
FOptions: TRESTRequestParameterOptions;
function KindIsStored: Boolean;
procedure SetKind(const AValue: TRESTRequestParameterKind);
procedure SetName(const AValue: string);
procedure SetOptions(const AValue: TRESTRequestParameterOptions);
procedure SetValue(const AValue: string);
procedure SetContentType(const AValue: TRESTContentType);
procedure ReleaseStream;
procedure NotifyParameterChanged(AValueChanged: Boolean);
function GetBytes: TBytes;
public
constructor Create(ACollection: TCollection); override;
destructor Destroy; override;
procedure Assign(ASource: TPersistent); override;
procedure SetStream(const AValue: TStream; AOwnership: TRESTObjectOwnership = ooCopy);
function AddValue(const AValue: string): TRESTRequestParameter;
/// <summary>
/// Return a human-readable representation of this parameter
/// </summary>
/// <returns>String</returns>
function ToString: string; override;
function GetDisplayName: string; override;
/// <summary>
/// Stream value of the parameter
/// </summary>
property Stream: TStream read FStream;
property StreamOwner: Boolean read FStreamOwner;
property Bytes: TBytes read GetBytes;
published
/// <summary>
/// Type of the parameter
/// </summary>
property Kind: TRESTRequestParameterKind read FKind write SetKind stored KindIsStored;
/// <summary>
/// Name of the parameter
/// </summary>
property Name: string read FName write SetName;
/// <summary>
/// Additional processing options
/// </summary>
property Options: TRESTRequestParameterOptions read FOptions write SetOptions default [];
/// <summary>
/// Value of the parameter
/// </summary>
property Value: string read FValue write SetValue;
/// <summary>
/// <para>
/// If ContentType is set to a specific value, then this will be used as actual content-type for the
/// corresponding PUT or POST request. UTF-8 encoding will be applied unless doNotEncode is specified in Options.
/// </para>
/// <para>
/// If left empty, the content type will be chosen basically depending on the number of existing parameters,
/// that go into the requests body.
/// </para>
/// <para>
/// Single parameter will use application/x-www-form-urlencoded, multiple parameters multipart/mixed instead.
/// </para>
/// </summary>
/// <remarks>
/// This property is only relevant for PUT and POST request. GET/DELETE request do not have a content-type.
/// </remarks>
property ContentType: TRESTContentType read FContentType write SetContentType default TRESTContentType.ctNone;
end;
TRESTRequestParameterDict = TDictionary<string, TRESTRequestParameter>;
TRESTRequestParameterArray = TArray<TRESTRequestParameter>;
IRESTRequestParameterListOwnerNotify = interface
['{48713C06-9469-4648-BCF9-FF83C6A58F5D}']
procedure ParameterListChanged;
procedure ParameterValueChanged;
end;
/// <summary>
/// Container for parameters that will be associated with a REST request.
/// </summary>
/// <seealso cref="TRESTRequestParameter" />
TRESTRequestParameterList = class(TOwnedCollection)
private type
TEnumerator = class(TCollectionEnumerator)
public
function GetCurrent: TRESTRequestParameter; inline;
property Current: TRESTRequestParameter read GetCurrent;
end;
protected
function GetItem(AIndex: Integer): TRESTRequestParameter;
procedure SetItem(AIndex: Integer; const AValue: TRESTRequestParameter);
function GetAttrCount: Integer; override;
function GetAttr(AIndex: Integer): string; override;
function GetItemAttr(AIndex, AItemIndex: Integer): string; override;
procedure Update(AItem: TCollectionItem); override;
public
constructor Create(const AOwner: TComponent);
function GetEnumerator: TEnumerator;
/// <summary>
/// Shortcut to Add(AName, AValue, Cookie) overload
/// </summary>
/// <param name="AName">Name of the cookie to add</param>
/// <param name="AValue">Value of the cookie to add</param>
function AddCookie(const AName, AValue: string): TRESTRequestParameter;
/// <summary>
/// Shortcut to Add(name, value, HttpHeader) overload
/// </summary>
/// <param name="AName">Name of the header to add</param>
/// <param name="AValue">Value of the header to add</param>
function AddHeader(const AName, AValue: string): TRESTRequestParameter;
/// <summary>
/// Calls Add() for all public, published &readable properties of obj
/// </summary>
/// <param name="AObject">The object with properties to add as parameters</param>
procedure AddObject(AObject: TObject); overload;
/// <summary>
/// Calls Add() for all public, readable properties specified in the white list
/// </summary>
/// <example>
/// request.AddObject(product, "ProductId", "Price", ...);
/// </example>
/// <param name="AObject">The object with properties to add as parameters</param>
/// <param name="WhiteList">The names of the properties to include</param>
procedure AddObject(AObject: TObject; WhiteList: TStrings); overload;
/// <summary>
/// Adds an empty parameter to the collection.
/// </summary>
function AddItem: TRESTRequestParameter; overload;
/// <summary>
/// Adds a parameter to the collection. If a parameter of the same name already exists, then the previous parameter
/// will be overwritten. There are five kinds of parameters:
/// - GetOrPost: Either a QueryString value or encoded form value based on method
/// - HttpHeader: Adds the name/value pair to the HTTP request's Headers collection
/// - UrlSegment: Inserted into URL if there is a matching url token e.g. {AccountId}
/// - Cookie: Adds the name/value pair to the HTTP request's Cookies collection
/// - RequestBody: Used by AddBody() (not recommended to use directly)
/// </summary>
/// <param name="AName">Name of the parameter</param>
/// <param name="AValue">Value of the parameter</param>
/// <param name="AKind">The kind of parameter to add</param>
/// <param name="AOptions">Set of parameter options </param>
function AddItem(const AName, AValue: string; AKind: TRESTRequestParameterKind;
AOptions: TRESTRequestParameterOptions = []): TRESTRequestParameter; overload;
property Items[index: Integer]: TRESTRequestParameter read GetItem write SetItem; default;
procedure Delete(const AParam: TRESTRequestParameter); overload;
procedure Delete(const AName: string); overload;
function IndexOf(const AParam: TRESTRequestParameter): Integer; overload;
function IndexOf(const AName: string): Integer; overload;
/// <summary>
/// Adds a HTTP parameter to the request. If a parameter of the same name already exists, then the previous parameter
/// will be removed and freed. (QueryString for GET, DELETE, OPTIONS and HEAD; Encoded form for POST and PUT)
/// </summary>
/// <param name="AName">Name of the parameter</param>
/// <param name="AValue">Value of the parameter</param>
function AddItem(const AName, AValue: string): TRESTRequestParameter; overload;
/// <summary>
/// Adds a parameter to the request. If a parameter of the same name already exists, then the previous parameter
/// will be removed and freed.<br /><br />There are five kinds of parameters: - GetOrPost: Either a QueryString
/// value or encoded form value based on method - HttpHeader: Adds the name/value pair to the HTTP request's
/// Headers collection - UrlSegment: Inserted into URL if there is a matching url token e.g. {AccountId} -
/// Cookie: Adds the name/value pair to the HTTP request's Cookies collection - RequestBody: Used by AddBody()
/// (not recommended to use directly)
/// </summary>
/// <param name="AName">
/// Name of the parameter
/// </param>
/// <param name="AValue">
/// Value of the parameter
/// </param>
/// <param name="AKind">
/// The kind of parameter to add
/// </param>
/// <param name="AOptions">
/// Options for processing the parameter
/// </param>
/// <param name="AContentType">
/// Content type of the parameter, for body parameters. Set to TRESTContentType.ctNone if no specific content type is needed.
/// </param>
function AddItem(const AName, AValue: string; const AKind: TRESTRequestParameterKind;
const AOptions: TRESTRequestParameterOptions; AContentType: TRESTContentType): TRESTRequestParameter;
overload;
/// <summary>
/// Adds a parameter to the request. If a parameter of the same name already exists, then the previous parameter
/// will be removed and freed.<br /><br />There are five kinds of parameters: - GetOrPost: Either a QueryString
/// value or encoded form value based on method - HttpHeader: Adds the name/value pair to the HTTP request's
/// Headers collection - UrlSegment: Inserted into URL if there is a matching url token e.g. {AccountId} -
/// Cookie: Adds the name/value pair to the HTTP request's Cookies collection - RequestBody: Used by AddBody()
/// (not recommended to use directly)
/// </summary>
/// <param name="AName">
/// Name of the parameter
/// </param>
/// <param name="AValue">
/// Value of the parameter
/// </param>
/// <param name="AKind">
/// The kind of parameter to add
/// </param>
/// <param name="AOptions">
/// Options for processing the parameter
/// </param>
/// <param name="AContentType">
/// Content type of the parameter, for body parameters. Set to TRESTContentType.ctNone if no specific content type is needed.
/// </param>
function AddItem(const AName: string; const AValue: TBytes; const AKind: TRESTRequestParameterKind;
const AOptions: TRESTRequestParameterOptions; AContentType: TRESTContentType): TRESTRequestParameter;
overload;
/// <summary>
/// Adds a parameter to the request. If a parameter of the same name already exists, then the previous parameter
/// will be removed and freed.<br /><br />There are five kinds of parameters: - GetOrPost: Either a QueryString
/// value or encoded form value based on method - HttpHeader: Adds the name/value pair to the HTTP request's
/// Headers collection - UrlSegment: Inserted into URL if there is a matching url token e.g. {AccountId} -
/// Cookie: Adds the name/value pair to the HTTP request's Cookies collection - RequestBody: Used by AddBody()
/// (not recommended to use directly)
/// </summary>
/// <param name="AName">
/// Name of the parameter
/// </param>
/// <param name="AValue">
/// Value of the parameter
/// </param>
/// <param name="AKind">
/// The kind of parameter to add
/// </param>
/// <param name="AOptions">
/// Options for processing the parameter
/// </param>
/// <param name="AContentType">
/// Content type of the parameter, for body parameters. Set to TRESTContentType.ctNone if no specific content type is needed.
/// </param>
/// <param name="AOwnsStream">
/// Defines how parameter owns the stream.
/// </param>
function AddItem(const AName: string; const AValue: TStream; const AKind: TRESTRequestParameterKind;
const AOptions: TRESTRequestParameterOptions; AContentType: TRESTContentType;
AOwnsStream: TRESTObjectOwnership = ooCopy): TRESTRequestParameter;
overload;
/// <summary>
/// Shortcut to Add(name, value, UrlSegment) overload
/// </summary>
/// <param name="AName">Name of the segment to add</param>
/// <param name="AValue">Value of the segment to add</param>
procedure AddUrlSegment(const AName, AValue: string);
/// <summary>
/// Locates a request parameter by its name. Returns nil if no matching parameter is found.
/// </summary>
/// <param name="AName">
/// The parameter's name (Key)
/// </param>
function ParameterByName(const AName: string): TRESTRequestParameter;
/// <summary>
/// Locates a request parameter by its index.
/// </summary>
/// <param name="AIndex">
/// The parameter's index
/// </param>
function ParameterByIndex(AIndex: Integer): TRESTRequestParameter;
/// <summary>
/// checks the existance of a parameter with the given name
/// </summary>
/// <param name="AName">Name of the Parameter</param>
function ContainsParameter(const AName: string): Boolean;
/// <summary>
/// Creates URLSegement parameters from a full URL string.
/// </summary>
function CreateURLSegmentsFromString(const AUrlPath: string): Boolean;
/// <summary>
/// Creates GET parameters from a full URL string.
/// </summary>
procedure CreateGetParamsFromUrl(const AUrlPath: string);
/// <summary>
/// Adds ABodyContent as Body parameter to the request.
/// </summary>
/// <remarks>
/// An already existing body parameter will NOT be replaced/deleted!
/// </remarks>
procedure AddBody(const ABodyContent: string; AContentType: TRESTContentType = ctNone); overload;
/// <summary>
/// Serializes obj to JSON and adds it to the request body.
/// </summary>
/// <remarks>
/// An already existing body parameter will be replaced/deleted!
/// </remarks>
procedure AddBody<T: class, constructor>(const AObject: T;
AOwnsObject: TRESTObjectOwnership = ooApp); overload;
/// <summary>
/// Encodes the string representation of a JSON Object and adds it to the request body.
/// </summary>
/// <remarks>
/// An already existing body parameter will be replaced/deleted!
/// </remarks>
procedure AddBody(const AObject: TJsonObject;
AOwnsObject: TRESTObjectOwnership = ooApp); overload;
/// <summary>
/// Adds ABodyContent as Body parameter to the request.
/// </summary>
/// <remarks>
/// An already existing body parameter will be replaced/deleted!
/// </remarks>
procedure AddBody(const ABodyContent: TStream; AContentType: TRESTContentType = ctNone;
AOwnsStream: TRESTObjectOwnership = ooCopy); overload;
end;
TExecuteMethod = procedure of object;
/// <summary>
/// Provides classes and support for asynchronous execution of REST client requests.
/// </summary>
TRESTExecutionThread = class(TThread)
private
FCompletionHandler: TCompletionHandler;
FCompletionHandlerWithError: TCompletionHandlerWithError;
FExecuteMethod: TExecuteMethod;
FSynchronized: Boolean;
FRequest: TCustomRESTRequest;
FExceptObject: TObject;
protected
procedure HandleCompletion;
procedure HandleCompletionWithError;
procedure Execute; override;
public
constructor Create(AExecuteMethod: TExecuteMethod; ARequest: TCustomRESTRequest;
ACompletionHandler: TCompletionHandler; ASynchronized: Boolean; AFreeThread: Boolean = True; ACompletionHandlerWithError: TCompletionHandlerWithError = nil);
end;
TCustomRESTRequestNotifyEvent = procedure(Sender: TCustomRESTRequest) of object;
/// <summary>
/// Container for data used to make requests
/// </summary>
TCustomRESTRequest = class(TBaseObjectBindSourceDelegate, IRESTRequestParameterListOwnerNotify)
public type
TNotify = class(TRESTComponentNotify)
public
procedure ParameterListChanged(Sender: TObject); virtual;
end;
TNotifyList = TRESTComponentNotifyList<TNotify>;
/// <summary>
/// Wrapper class around the body request parameter
/// <summary>
TBody = class
private
FParams: TRESTRequestParameterList;
FJSONTextWriter: TJsonTextWriter;
FJSONStream: TStream;
procedure ClearWriter;
function GetJSONWriter: TJsonTextWriter;
public
constructor Create;
destructor Destroy; override;
/// <summary>
/// Adds ABodyContent as Body parameter to the request.
/// </summary>
/// <remarks>
/// An already existing body parameter will NOT be replaced/deleted!
/// </remarks>
procedure Add(const ABodyContent: string; AContentType: TRESTContentType = ctNone); overload;
/// <summary>
/// Serializes obj to JSON and adds it to the request body.
/// </summary>
/// <param name="AObject">The object to serialize</param>
/// <param name="AOwnsObject">Defines who will own the object.</param>
/// <remarks>
/// An already existing body parameter will be replaced/deleted!
/// </remarks>
procedure Add<T: class, constructor>(AObject: T; AOwnsObject: TRESTObjectOwnership = ooApp); overload;
/// <summary>
/// Encodes the string representation of a JSON Object and adds it to the request body.
/// </summary>
/// <param name="AObject">The object to serialize</param>
/// <param name="AOwnsObject">Defines who will own the object.</param>
/// <remarks>
/// An already existing body parameter will be replaced/deleted!
/// </remarks>
procedure Add(AObject: TJsonObject; AOwnsObject: TRESTObjectOwnership = ooApp); overload;
/// <summary>
/// Adds ABodyContent as Body parameter to the request.
/// </summary>
/// <remarks>
/// An already existing body parameter will be replaced/deleted!
/// </remarks>
procedure Add(ABodyContent: TStream; AContentType: TRESTContentType = ctNone;
AOwnsStream: TRESTObjectOwnership = ooCopy); overload;
/// <summary>
/// Removes all body parameters (TRESTRequestParameterKind.pkREQUESTBODY) from the TRESTRequestParameterList.
/// and clears the JSONWriter
/// </summary>
procedure ClearBody;
property JSONWriter: TJsonTextWriter read GetJSONWriter;
end;
private
FAccept: string;
FAcceptCharset: string;
FAcceptEncoding: string;
FHandleRedirects: Boolean;
FMethod: TRESTRequestMethod;
FPosting: Boolean;
FAutoCreateParams: Boolean;
FParams: TRESTRequestParameterList;
FTransientParams: TRESTRequestParameterList;
FResource: string;
FTimeout: Integer;
FClient: TCustomRESTClient;
FResponse: TCustomRESTResponse;
FBindSource: TSubRESTRequestBindSource;
FNotifyList: TNotifyList;
FURLAlreadyEncoded : boolean;
FBody: TBody;
FRequestContentType : string;
FOnAfterExecute: TCustomRESTRequestNotifyEvent;
FExecutionPerformance: TExecutionPerformance;
FOnHTTPProtocolError: TCustomRESTRequestNotifyEvent;
FSynchronizedEvents: Boolean;
FResourceSuffix: string;
function AcceptIsStored: Boolean;
function AcceptCharSetIsStored: Boolean;
function MethodIsStored: Boolean;
procedure SetAccept(const AValue: string);
procedure SetAcceptCharset(const AValue: string);
procedure SetHandleRedirects(const AValue: Boolean);
procedure SetClient(const AValue: TCustomRESTClient);
function GetParams: TRESTRequestParameterList;
function GetExecutionPerformance: TExecutionPerformance;
procedure SetParams(const AValue: TRESTRequestParameterList);
procedure SetAutoCreateParams(const AValue: Boolean);
procedure ProcessResponse(const AURL: string; AResponseStream: TMemoryStream; const AContent: string);
function GetMethod: TRESTRequestMethod;
function GetResource: string;
function GetTimeout: Integer;
procedure SetAcceptEncoding(const AValue: string);
procedure SetMethod(const AValue: TRESTRequestMethod);
procedure SetResource(const AValue: string);
procedure SetTimeout(const AValue: Integer);
function GetResponse: TCustomRESTResponse;
procedure SetResponse(const AResponse: TCustomRESTResponse);
procedure SetSynchronizedEvents(const AValue: Boolean);
function GetFullResource: string;
procedure SetResourceSuffix(const AValue: string);
function IsQueryParam(const AParam: TRESTRequestParameter;
AContentType: TRESTContentType): Boolean;
function GetFullURL: string;
protected
procedure Loaded; override;
function GetClient: TCustomRESTClient; virtual;
function CreateBindSource: TBaseObjectBindSource; override;
function CreateRequestBindSource: TSubRESTRequestBindSource; virtual;
procedure ParameterListChanged; virtual;
procedure ParameterValueChanged; virtual;
procedure PropertyValueChanged; virtual;
procedure DoResponseChanged; virtual;
procedure DoResponseChanging; virtual;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
/// <summary>
/// OnAfterExecute dispatch method. Called internally.
/// </summary>
procedure DoAfterExecute; virtual;
procedure DoBeforeExecute; virtual;
/// <summary>
/// OnHTTPProtocol dispatch method. Called internally.
/// </summary>
procedure DoHTTPProtocolError; virtual;
procedure DoApplyCookieParams(const AParamList: TRESTRequestParameterArray; const CookieURL: string); virtual;
procedure DoApplyHeaderParams(const AParamList: TRESTRequestParameterArray); virtual;
procedure DoApplyURLSegments(const AParamList: TRESTRequestParameterArray; var AURL: string); virtual;
/// <summary>
/// Prepares the actual query string to have all parameters, values encoded properly
/// </summary>
/// <param name="AParamList">
/// The list where query parameters are taken from
/// </param>
/// <param name="AContentType">
/// The content type for the body.
/// </param>
/// <param name="AURL">
/// Will be appended with all parameters
/// </param>
procedure DoPrepareQueryString(const AParamList: TRESTRequestParameterArray;
AContentType: TRESTContentType; var AURL: string); virtual;
/// <summary>
/// Creates a stream that contains all relevant parameters in a stream that represents a either list of
/// name-value pairs or a HTTP Multi-Part structure - depending on the requests content-type.
/// </summary>
/// <param name="AParamList">
/// The list where request body parameters are taken from,
/// </param>
/// <param name="AContentType">
/// The content type for the body.
/// </param>
/// <param name="ABodyStream">
/// Will point to a newly created stream, containing the body.
/// </param>
/// <param name="ABodyStreamOwner">
/// When True, then caller is responsible for ABodyStream destruction.
/// When False, then REST library owns the ABodyStream stream.
/// </param>
procedure DoPrepareRequestBody(AParamList: TRESTRequestParameterArray;
AContentType: TRESTContentType; var ABodyStream: TStream; var ABodyStreamOwner: Boolean); virtual;
/// <summary>
/// HandleEvent ensures that an event handler (like DoAfterExecute) is ran synchronized or not depending on
/// SynchronizedEvents
/// </summary>
/// <seealso cref="TCustomRESTClient.SynchronizedEvents" />
procedure HandleEvent(AEventHandler: TMethod);
property NotifyList: TNotifyList read FNotifyList;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
(*
/// <summary>
/// Used by the default deserializers to explicitly set which date format string to use when parsing dates.
/// </summary>
string DateFormat { get; set; }
*)
/// <summary>
/// Based on the parameters the content-type is "x-www-form-urlencoded", "multipart/formdata" (e.g. for
/// file-transfer etc.) or a specific content-type as set by at least one of the parameters.
/// </summary>
function ContentType: TRESTContentType; overload;
function ContentType(const AParamsArray: TRESTRequestParameterArray): TRESTContentType; overload;
/// <summary>
/// Adds a HTTP parameter to the request. If a parameter of the same name already exists, then the previous parameter
/// will be removed and freed. (QueryString for GET, DELETE, OPTIONS and HEAD; Encoded form for POST and PUT)
/// </summary>
/// <param name="AName">Name of the parameter</param>
/// <param name="AValue">Value of the parameter</param>
procedure AddParameter(const AName, AValue: string); overload;
/// <summary>
/// Adds an Json formatted HTTP parameter to the request. If a parameter of the same name already exists, then
/// the previous parameter will be removed and freed. (QueryString for GET, DELETE, OPTIONS and HEAD; Encoded
/// form for POST and PUT)
/// </summary>
/// <param name="AName">
/// Name of the parameter
/// </param>
/// <param name="AJsonObject">
/// Value of the parameter, will be formatted as Json
/// </param>
/// <param name="AFreeJson">
/// If True, the Json Object in AJsonObject will be fred automatcially
/// </param>
procedure AddParameter(const AName: string; AJsonObject: TJSONObject; AFreeJson: boolean = True); overload;
procedure AddParameter(const AName: string; AJsonObject: TJSONObject; AOwnsObject: TRESTObjectOwnership {= ooREST}); overload;
/// <summary>
/// Adds a parameter to the request. If a parameter of the same name already exists, then the previous parameter
/// will be removed and freed. There are five kinds of parameters: - GetOrPost: Either a QueryString value or
/// encoded form value based on method - HttpHeader: Adds the name/value pair to the HTTP request's Headers
/// collection - UrlSegment: Inserted into URL if there is a matching url token e.g. {AccountId} - Cookie: Adds
/// the name/value pair to the HTTP request's Cookies collection - RequestBody: Used by AddBody() (not
/// recommended to use directly)
/// </summary>
/// <param name="AName">
/// Name of the parameter
/// </param>
/// <param name="AValue">
/// Value of the parameter
/// </param>
/// <param name="AKind">
/// The kind of parameter to add
/// </param>
procedure AddParameter(const AName, AValue: string; const AKind: TRESTRequestParameterKind); overload;
/// <summary>
/// Adds a parameter to the request. If a parameter of the same name already exists, then the previous parameter
/// will be removed and freed.<br /><br />There are five kinds of parameters: - GetOrPost: Either a QueryString
/// value or encoded form value based on method - HttpHeader: Adds the name/value pair to the HTTP request's
/// Headers collection - UrlSegment: Inserted into URL if there is a matching url token e.g. {AccountId} -
/// Cookie: Adds the name/value pair to the HTTP request's Cookies collection - RequestBody: Used by AddBody()
/// (not recommended to use directly)
/// </summary>
/// <param name="AName">
/// Name of the parameter
/// </param>
/// <param name="AValue">
/// Value of the parameter
/// </param>
/// <param name="AKind">
/// The kind of parameter to add
/// </param>
/// <param name="AOptions">
/// Options for processing the parameter
/// </param>
procedure AddParameter(const AName, AValue: string; const AKind: TRESTRequestParameterKind;
const AOptions: TRESTRequestParameterOptions); overload;
/// <summary>
/// Add an authentication parameter
/// </summary>
procedure AddAuthParameter(const AName, AValue: string; const AKind: TRESTRequestParameterKind;
const AOptions: TRESTRequestParameterOptions = []); overload;
function CreateUnionParameterList: TRESTRequestParameterArray;
/// <summary>
/// Adds ABodyContent as Body parameter to the request.
/// </summary>
/// <remarks>
/// An already existing body parameter will NOT be replaced/deleted!
/// </remarks>
procedure AddBody(const ABodyContent: string; AContentType: TRESTContentType = ctNone); overload;
/// <summary>
/// Serializes obj to JSON and adds it to the request body.
/// </summary>
/// <param name="AObject">The object to serialize</param>
/// <remarks>
/// An already existing body parameter will be replaced/deleted!
/// </remarks>
procedure AddBody<T: class, constructor>(AObject: T); overload;
/// <summary>
/// Encodes the string representation of a JSON Object and adds it to the request body.
/// </summary>
/// <param name="AObject">The object to serialize</param>
/// <param name="AOwnsObject">Defines who will own the object.</param>
/// <remarks>
/// An already existing body parameter will be replaced/deleted!
/// </remarks>
procedure AddBody(AObject: TJsonObject; AOwnsObject: TRESTObjectOwnership = ooApp); overload;
/// <summary>
/// Adds ABodyContent as Body parameter to the request.
/// </summary>
/// <remarks>
/// An already existing body parameter will be replaced/deleted!
/// </remarks>
procedure AddBody(ABodyContent: TStream; AContentType: TRESTContentType = ctNone;
AOwnsStream: TRESTObjectOwnership = ooCopy); overload;
/// <summary>
/// Removes all body parameters (TRESTRequestParameterKind.pkREQUESTBODY) from the request.
/// </summary>
procedure ClearBody;
/// <summary>
/// Adds file content to the request. If same AName parameter already exists, then the previous content
/// will be replaced by new one.
/// </summary>
/// <param name="AName">Name of the parameter</param>
/// <param name="AFileName">Path to the file</param>
/// <param name="AContentType">Content type of the file, for HTTP body parameter.
/// If AContentType=ctNone program automatically define the Content type of the file</param>
procedure AddFile(const AName, AFileName: string; AContentType: TRESTContentType = TRESTContentType.ctNone); overload;
/// <summary>
/// Adds file content to the request. Only one file can be added.
/// If this function is executed second time, then previous content will be replaced by new one.
/// </summary>
/// <param name="AFileName">Path to the file</param>
/// <param name="AContentType">Content type of the file, for HTTP body parameter.
/// If AContentType=ctNone program automatically define the Content type of the file</param>
procedure AddFile(const AFileName: string; AContentType: TRESTContentType = TRESTContentType.ctNone); overload;
/// <summary>
/// Sets all fields to their default value. No state information is kept. If Response
/// is assigned, then Response.ResetToDefaults is called too.
/// </summary>
procedure ResetToDefaults;
/// <summary>
/// Exceutes an actual HTTP request
/// </summary>
/// <exception cref="ERESTException">
/// Anything which is NOT an HTTP protocol exception.
/// </exception>
/// <remarks>
/// Execute does NOT raise HTTP protocol exceptions, instead TCustomRESTClient.Response.StatusCode should be checked
/// for desired values. In many cases a 2xx StatusCode signals "succes" - other status codes don't need to be
/// errors though. It depends on the actual REST API.
/// </remarks>
procedure Execute;
/// <summary>
/// <para>
/// Executes a request asynchronously, i.e. run it in its own thread. There is no automatic serialization op
/// property access though, which means that while the execution thread runs, properties of all involved
/// TCustomRESTClient and TCustomRESTRequest instances should not be touched from other threads (including the main thread)
/// <br /><br />Using ExecuteAsync is strongly recommended on mobile platforms. iOS (and likely Android) will
/// terminate an application if it considers the main thread to be unresponsive, which would be the case if
/// there is a running request which takes more than a second or two to return.
/// </para>
/// <para>
/// The idea behind this is that the UI runs in the main thread and mobile devices should respond to user
/// interaction basically immediately. Sluggish behaviour (caused by blocking the main thread) is considered
/// unacceptable on these small devices.
/// </para>
/// </summary>
/// <param name="ACompletionHandler">
/// An anonymous method that will be run after the execution completed
/// </param>
/// <param name="ASynchronized">
/// Specifies if ACompletioHandler will be run in the main thread's (True) or execution thread's (False) context
/// </param>
/// <param name="AFreeThread">
/// If True, then the execution thread will be freed after it completed
/// </param>
/// <param name="ACompletionHandlerWithError">
/// An anonymous method that will be run if an exception is raised during execution
/// </param>
/// <returns>
/// Returns a reference to the execution thread. Should only be used if AFreeThread=False, as other wise the
/// reference may get invalid unexpectedly.
/// </returns>
function ExecuteAsync(ACompletionHandler: TCompletionHandler = nil; ASynchronized: Boolean = True;
AFreeThread: Boolean = True; ACompletionHandlerWithError: TCompletionHandlerWithError = nil): TRESTExecutionThread;
/// <summary>
/// Builds the final URL that will be executed. this includes also the placeholders for url-segments
/// as well as query-parameters
/// </summary>
function GetFullRequestURL(AIncludeParams: Boolean = True): string;
/// <summary>
/// Transient Params are typically create and re-created by
/// Authenticators. They are not persistent and will not be visible at
/// designtime.
/// In case of a naming-conflict any transient param will override a
/// normal parameter.
/// </summary>
property TransientParams: TRESTRequestParameterList read FTransientParams;
/// <summary>
/// Specifies if "url-segment" parameters should be created automatically from the baseurl/resource.
/// No other parameter types are affected.
/// </summary>
/// <example>
/// request.Resource = "Products/{ProductId}";
/// This will create a parameter "ProductID" (with no value assigned).
/// If a parameter of the same name already existed
/// the old parameter will <i>not</i> be overwritten.
/// </example>
property AutoCreateParams: Boolean read FAutoCreateParams write SetAutoCreateParams default True;
/// <summary>
/// <para>
/// Specifies the Content-Type that is accepted for the response.
/// </para>
/// <para>
/// Defaults to : application/json,text/plain;q=0.9,text/html;q=0.8<br />We are after JSON, which is why it has
/// the highest quality factor (default 1.0)
/// </para>
/// </summary>
property Accept: string read FAccept write SetAccept stored AcceptIsStored;
/// <summary>
/// Specifies the charset that the response is expected to be encoded in. Defaults to UTF-8.
/// </summary>
property AcceptCharset: string read FAcceptCharset write SetAcceptCharset stored AcceptCharSetIsStored;
/// <summary>
/// Specifies the accepted encoding. Defaults to empty string, which means "identity encoding".
/// </summary>
/// <value>
/// To allow for compressed responses set to "gzip, deflate"
/// </value>
property AcceptEncoding: string read FAcceptEncoding write SetAcceptEncoding;
/// <summary>
/// Specifies if the HTTP client should follow possible redirects (301, 303) for this request. Default =True
/// </summary>
/// <remarks>
/// See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
/// </remarks>
property HandleRedirects: Boolean read FHandleRedirects write SetHandleRedirects default True;
property Client: TCustomRESTClient read GetClient write SetClient;
/// <summary>
/// Determines what HTTP method to use for this request. Supported methods: GET, POST, PUT, DELETE, HEAD, OPTIONS
/// Default is GET
/// </summary>
property Method: TRESTRequestMethod read GetMethod write SetMethod stored MethodIsStored;
/// <summary>
/// Container of all HTTP parameters to be passed with the request.
/// See AddParameter() for explanation of the types of parameters that can be passed
/// </summary>
property Params: TRESTRequestParameterList read GetParams write SetParams;
/// <summary>
/// This property is a wrapper around the "body" request parameter.
/// </summary>
property Body: TBody read FBody;
/// <summary>
/// The Resource path to make the request against.
/// Tokens are substituted with UrlSegment parameters and match by name.
/// Should not include the scheme or domain. Do not include leading slash.
/// Combined with RestClient.BaseUrl to assemble final URL:
/// {BaseUrl}/{Resource} (BaseUrl is scheme + domain, e.g. http://example.com)
/// </summary>
/// <example>
/// // example for url token replacement
/// request.Resource = "Products/{ProductId}";
/// request.AddParameter("ProductId", 123, ParameterType.UrlSegment);
/// </example>
property Resource: string read GetResource write SetResource;
property ResourceSuffix: string read FResourceSuffix write SetResourceSuffix;
property FullResource: string read GetFullResource;
/// <summary>
/// After executing a Request, it will fill in all values from the HTTP answer to this TCustomRESTResponse
/// instance. An instance can either be assigned explicitly (e.g. in the IDE) or can be left empty, in which case
/// TCustomRESTRequest will create an instance on demand.
/// </summary>
property Response: TCustomRESTResponse read GetResponse write SetResponse;
/// <summary>
/// Timeout in milliseconds to be used for the request.
/// </summary>
property Timeout: Integer read GetTimeout write SetTimeout default 30000;
/// <summary>
/// OnAfterExecute gets fired after TRESTCRequest.Execute has finished and the Response has been processed. Any
/// observers will get notified <i>before</i> OnAfterExecute fires.
/// </summary>
property OnAfterExecute: TCustomRESTRequestNotifyEvent read FOnAfterExecute write FOnAfterExecute;
/// <summary>
/// Provides detailed information about the performance of the execution of a request.
/// </summary>
property ExecutionPerformance: TExecutionPerformance read GetExecutionPerformance;
/// <summary>
/// Specifies if Events (such as OnAfterExecute) should run in the context of the main
/// thread (True) or in the context of an arbitrary thread - which was created by the developer or by using
/// ExecuteAsync.
/// </summary>
// <seealso cref="TCustomRESTRequest.ExecuteAsync" />
property SynchronizedEvents: Boolean read FSynchronizedEvents write SetSynchronizedEvents default True;
/// <summary>
/// <para>
/// OnHTTPProtocolError gets fired when the server returns a status code other than 200 - OK
/// </para>
/// <para>
/// Check AClient.Response.StatusCode for the actual status.
/// </para>
/// <para>
/// This event will not get fired if a non HTTP-related exception occurs during execution. This includes, but
/// is not limited to timeout and server not found related exceptions.
/// </para>
/// </summary>
property OnHTTPProtocolError: TCustomRESTRequestNotifyEvent read FOnHTTPProtocolError write FOnHTTPProtocolError;
property BindSource: TSubRESTRequestBindSource read FBindSource;
/// <summary>
/// In rare scenarios, there might be services that provide urls that contain
/// encoded parameters. these urls must not be encoded again. set this flag to True
/// to avoid double-encoding.
/// </summary>
property URLAlreadyEncoded: boolean read FURLAlreadyEncoded write FURLAlreadyEncoded;
end;
/// <summary>
/// LiveBindings adapter for TCustomRESTRequest. Create bindable members
/// </summary>
TRESTRequestAdapter = class(TRESTComponentAdapter)
public type
TNotify = class(TCustomRESTRequest.TNotify)
private
FAdapter: TRESTRequestAdapter;
constructor Create(const AAdapter: TRESTRequestAdapter);
public
procedure ParameterListChanged(Sender: TObject); override;
procedure PropertyValueChanged(Sender: TObject); override;
end;
private
FRequest: TCustomRESTRequest;
FNotify: TNotify;
procedure SetRequest(const ARequest: TCustomRESTRequest);
procedure AddParameterFields;
procedure ParameterListChanged;
procedure AddPropertyFields;
protected
procedure CreatePropertyFields; virtual;
procedure DoChangePosting; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
function GetCanActivate: Boolean; override;
procedure AddFields; override;
function GetSource: TBaseLinkingBindSource; override;
public
constructor Create(AComponent: TComponent); override;
destructor Destroy; override;
procedure GetMemberNames(AList: TStrings); override;
property Request: TCustomRESTRequest read FRequest write SetRequest;
end;
/// <summary>
/// LiveBindings bindsource for TCustomRESTRequest. Creates adapter.
/// </summary>
TCustomRESTRequestBindSource = class(TRESTComponentBindSource)
private
FAdapter: TRESTRequestAdapter;
function GetRequest: TCustomRESTRequest;
procedure SetRequest(const Value: TCustomRESTRequest);
protected
function CreateRequestAdapter: TRESTRequestAdapter; virtual;
function CreateAdapter: TRESTComponentAdapter; override;
public
property Request: TCustomRESTRequest read GetRequest write SetRequest;
property Adapter: TRESTRequestAdapter read FAdapter;
end;
/// <summary>
/// LiveBindings bindsource for TCustomRESTRequest. Publishes subcomponent properties
/// </summary>
TSubRESTRequestBindSource = class(TCustomRESTRequestBindSource)
published
property AutoActivate;
property AutoEdit;
property AutoPost;
end;
TRESTRequest = class(TCustomRESTRequest)
published
property Accept;
property AcceptCharset;
property AcceptEncoding;
property AutoCreateParams;
property HandleRedirects;
property Client;
property Method;
property Params;
property Resource;
property ResourceSuffix;
property Response;
property Timeout;
property OnAfterExecute;
property ExecutionPerformance;
property SynchronizedEvents;
property OnHTTPProtocolError;
property BindSource;
end;
/// <summary>
/// Base class for TCustomRESTResponse
/// </summary>
TCustomRESTResponse = class(TBaseObjectBindSourceDelegate, IRESTResponseJSON)
public type
TNotify = TRESTJSONComponentNotify;
TNotifyList = TRESTComponentNotifyList<TNotify>;
TUpdateOption = (PropertyValueChanged, JSONValueChanged);
TUpdateOptions = set of TUpdateOption;
TJSONValueError = (NoContent, NoJSON, InvalidRootElement);
TJSONValueErrorEvent = procedure(Sender: TObject; AUpdateError: TJSONValueError; const AMessage: string) of object;
EJSONValueError = class(ERESTException)
private
FError: TJSONValueError;
public
constructor Create(AError: TJSONValueError; const AMessage: string);
property Error: TJSONValueError read FError;
end;
public type
TStatus = record
private
[weak] FResponse: TCustomRESTResponse;
public
function Success: Boolean;
function ClientError: Boolean;
function SuccessOK_200: Boolean;
function SucessCreated_201: Boolean;
function ClientErrorBadRequest_400: Boolean;
function ClientErrorUnauthorized_401: Boolean;
function ClientErrorForbidden_403: Boolean;
function ClientErrorNotFound_404: Boolean;
function ClientErrorNotAcceptable_406: Boolean;
function ClientErrorDuplicate_409: Boolean;
end;
private
FStatus: TStatus;
FUpdating: Integer;
FUpdateOptions: TUpdateOptions;
FContent: string;
FContentEncoding: string;
FContentType: string;
FErrorMessage: string;
FHeaders: TStrings;
FRawBytes: TBytes;
FFullRequestURI: string;
FJSONValue: TJsonValue;
FJSONStreamReader: TStreamReader;
FJSONTextReader: TJsonTextReader;
FJSONStream: TStream;
FRootElement: string;
FServer: string;
FStatusCode: Integer;
FStatusText: string;
FBindSource: TSubRESTResponseBindSource;
FNotifyList: TNotifyList;
FJSONNotifyList: TList<TNotifyEvent>;
function GetHeaders: TStrings;
function GetJSONValue: TJsonValue;
procedure SetRootElement(const AValue: string);
function GetStatusCode: Integer;
procedure SetStatusCode(const AValue: Integer);
function GetStatusText: string;
procedure SetStatusText(const AValue: string);
function GetContentEncoding: string;
function GetContent: string;
function GetContentLength: cardinal;
procedure SetContentEncoding(const AValue: string);
function GetContentType: string;
procedure SetContentType(const AValue: string);
function GetErrorMessage: string;
procedure SetErrorMessage(const AValue: string);
function GetFullRequestURI: string;
procedure SetFullRequestURI(const AValue: string);
function GetServer: string;
procedure SetServer(const AValue: string);
function GetStatus: TStatus;
function GetJSONText: string;
function GetJSONReader: TJSONTextReader;
protected
procedure BeginUpdate;
procedure EndUpdate;
function IsUpdating: Boolean;
function CreateBindSource: TBaseObjectBindSource; override;
procedure PropertyValueChanged; virtual;
procedure JSONValueChanged; virtual;
procedure SetContent(const AContent: string);
procedure SetRawBytes(const AStream: TStream);
{ IRESTResponseJSON }
procedure AddJSONChangedEvent(const ANotify: TNotifyEvent);
procedure RemoveJSONChangedEvent(const ANotify: TNotifyEvent);
procedure GetJSONResponse(out AJSONValue: TJSONValue; out AHasOwner: Boolean);
function HasJSONResponse: Boolean;
function HasResponseContent: Boolean;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
/// <summary>
/// Simple and rough attempt to extract simple parameters out of a response content. Will certainly not work for
/// all scenarios, but might be convenient in some situations
/// </summary>
/// <remarks>
/// Works on text/html and application/json conten-types.
/// </remarks>
/// <example>
/// <para>
/// text/html
/// </para>
/// <para>
/// oauth_token=abc123&oauth_token_secret=def456&oauth_callback_confirmed=true
/// </para>
/// <para>
/// application/json
/// </para>
/// <para>
/// { "oauth_token" : "abc123", "oauth_token_secret" : "def456", "oauth_callback_confirmed" : true }
/// </para>
/// </example>
function GetSimpleValue(const AName: string; var AValue: string): Boolean;
/// <summary>
/// Sets all fields to their default value. No state information, such as Content,
/// StatusCode etc is kept.
/// </summary>
procedure ResetToDefaults;
/// <summary>
/// Encoding of the response content. Used for compression (e.g. deflate, gzip).
/// The actual RAWBytes or Content string would already be decoded though.
/// Thus this property is for reference purposes only.
/// </summary>
property ContentEncoding: string read GetContentEncoding write SetContentEncoding;
/// <summary>
/// Length in bytes of the response content
/// </summary>
property ContentLength: cardinal read GetContentLength;
/// <summary>
/// MIME content type of response
/// </summary>
property ContentType: string read GetContentType write SetContentType;
(*
/// <summary>
/// Cookies returned by server with the response
/// </summary>
IList<RestResponseCookie> Cookies { get; }
*)
(*
/// <summary>
/// Headers returned by server with the response
/// </summary>
IList<Parameter> Headers { get; }
*)
(*
/// <summary>
/// Status of the request. Will return Error for transport errors.
/// HTTP errors will still return ResponseStatus.Completed, check StatusCode instead
/// </summary>
ResponseStatus ResponseStatus { get; set; }
*)
/// <summary>
/// HTTP protocol error that occured during request
/// </summary>
property ErrorMessage: string read GetErrorMessage write SetErrorMessage;
/// <summary>
/// HTTP response header-lines
/// </summary>
property Headers: TStrings read GetHeaders;
/// <summary>
/// <para>
/// Response content string parsed as JSON value. Nil, if content does not successfully parse.
/// </para>
/// <para>
/// If TCustomRESTRequest.RootValue has a value, then the content needs to represent a Json object (not an array that
/// is), and the result will be the value of the pair with the name "RootElement". RootElement supports a "dot" syntax. Example:
/// {response:{"name":"Smith", "phone":"1234", "orders":[{...}, {...}]}}
/// In that case setting RootElement to "response" would return the whol customer object.
/// Setting RootElement to "response.orders" would return the array of order objects.
/// </para>
/// </summary>
/// <remarks>
/// This method returns TJSONValue by intention. The developer has to know and decide if this would cast to
/// TJSONObject or TJSONArray (or possibly other types), as this depends on the actual API call.
/// The returned JSONValue is owned by the RESTResponse, which means that the developer must not free this.
/// </remarks>
/// <example>
/// <para>
/// {result : {customer:"John Doe", address:"Silicon Valley"}}
/// </para>
/// <para>
/// With RootElement set to "result", JSONValue will return the inner customer object:
/// </para>
/// <para>
/// {customer:"John Doe", address:"Silicon Valley"}
/// </para>
/// </example>
/// <seealso cref="RootElement" />
property JSONValue: TJsonValue read GetJSONValue;
property JSONText: string read GetJSONText;
property JSONReader: TJSONTextReader read GetJSONReader;
(*
/// <summary>
/// Description of HTTP status returned
/// </summary>
string StatusDescription { get; set; }
*)
/// <summary>
/// Response content as bytes array.
/// </summary>
/// <remarks>
/// RAWBytes is already decoded using the charset as sent by the sever. They are in default Unicode encoding that
/// is.
/// </remarks>
property RawBytes: TBytes read FRawBytes;
/// <summary>
/// The fully qualified request URI that lead to this response.
/// </summary>
property FullRequestURI: string read GetFullRequestURI write SetFullRequestURI;
/// <summary>
/// Server identifier, e.g. "Microsoft-IIS/7.0"
/// </summary>
property Server: string read GetServer write SetServer;
/// <summary>
/// HTTP response status code
/// </summary>
property StatusCode: Integer read GetStatusCode write SetStatusCode;
/// <summary>
/// HTTP response status text
/// </summary>
property StatusText: string read GetStatusText write SetStatusText;
/// <summary>
/// String representation of response content
/// </summary>
property Content: string read GetContent;
/// <summary>
/// Optional path into the JSON response content. The path identifies a starting point for loading the JSONValue property.
/// Sample RootElement paths: "foo", "foo.bar", "[0].foo", "foo.bar[0]".
/// </summary>
property RootElement: string read FRootElement write SetRootElement;
property BindSource: TSubRESTResponseBindSource read FBindSource;
property NotifyList: TNotifyList read FNotifyList;
property Status: TStatus read GetStatus;
end;
/// <summary>
/// LiveBindings adapter for TCustomRESTResponse. Create bindable members
/// </summary>
TRESTResponseAdapter = class(TRESTComponentAdapter)
public type
TNotify = class(TCustomRESTResponse.TNotify)
private
FAdapter: TRESTResponseAdapter;
constructor Create(const AAdapter: TRESTResponseAdapter);
public
procedure PropertyValueChanged(Sender: TObject); override;
end;
private
FResponse: TCustomRESTResponse;
FNotify: TNotify;
procedure SetResponse(const AResponse: TCustomRESTResponse);
procedure AddPropertyFields;
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
function GetCanActivate: Boolean; override;
procedure AddFields; override;
function GetSource: TBaseLinkingBindSource; override;
public
constructor Create(AComponent: TComponent); override;
destructor Destroy; override;
property Response: TCustomRESTResponse read FResponse write SetResponse;
end;
/// <summary>
/// LiveBindings bindsource for TCustomRESTResponse. Creates adapter
/// </summary>
TCustomRESTResponseBindSource = class(TRESTComponentBindSource)
private
FAdapter: TRESTResponseAdapter;
function GetResponse: TCustomRESTResponse;
procedure SetResponse(const Value: TCustomRESTResponse);
protected
function CreateAdapter: TRESTComponentAdapter; override;
public
property Response: TCustomRESTResponse read GetResponse write SetResponse;
property Adapter: TRESTResponseAdapter read FAdapter;
end;
/// <summary>
/// LiveBindings bindsource for TCustomRESTRequest. Publishes subcomponent properties
/// </summary>
TSubRESTResponseBindSource = class(TCustomRESTResponseBindSource)
published
property AutoActivate;
property AutoEdit;
property AutoPost;
end;
TRESTResponse = class(TCustomRESTResponse)
published
property Content;
property ContentLength;
property ContentType;
property ContentEncoding;
property RootElement;
property BindSource;
end;
/// <summary>
/// Used for event handlers of TCustomRESTClient
/// </summary>
TCustomRESTClientNotifyEvent = procedure(Sender: TCustomRESTClient) of object;
/// <summary>
/// TCustomRESTClient is an easy to use class for accessing REST APIs. It is typically used by inheriting from it in a
/// specific REST API class.
/// </summary>
/// <remarks>
/// <para>
/// TCustomRESTClient works with JSON only. XML as transport format is not supported that is.<br />HTTP and HTTPS urls
/// are supported.
/// </para>
/// </remarks>
/// <example>
/// TTwitterchAPI = class(TCustomRESTClient)<br /> procedure Tweet(AMessage: string);<br />end;
/// </example>
TCustomRESTClient = class(TBaseObjectBindSourceDelegate, IRESTRequestParameterListOwnerNotify)
public type
TNotify = class(TRESTComponentNotify)
public
procedure ParameterListChanged(Sender: TObject); virtual;
end;
TNotifyList = TRESTComponentNotifyList<TNotify>;
private
FBindSource: TSubRESTClientBindSource;
FNotifyList: TNotifyList;
FOnHTTPProtocolError: TCustomRESTClientNotifyEvent;
FAutoCreateParams: Boolean;
FParams: TRESTRequestParameterList;
FTransientParams: TRESTRequestParameterList;
FAuthenticator: TCustomAuthenticator;
FBaseURL: string;
FFallbackCharsetEncoding: string;
FSynchronizedEvents: Boolean;
FRaiseExceptionOn500: Boolean;
FHttpClient: TRESTHTTP;
FPosting: Boolean;
function FallbackCharsetEncodingIsStored: Boolean;
function UserAgentIsStored: Boolean;
procedure SetParams(const AValue: TRESTRequestParameterList);
procedure SetAutoCreateParams(const AValue: Boolean);
// Getters and Setters
function GetProxyPassword: string;
function GetProxyPort: Integer;
function GetProxyServer: string;
function GetProxyUsername: string;
procedure SetBaseURL(const AValue: string);
procedure SetProxyPassword(const AValue: string);
procedure SetProxyPort(const AValue: Integer);
procedure SetProxyServer(const AValue: string);
procedure SetProxyUsername(const AValue: string);
procedure SetUserAgent(const AValue: string);
function GetParams: TRESTRequestParameterList;
function GetFallbackCharsetEncoding: string;
procedure SetFallbackCharsetEncoding(const AValue: string);
function GetAuthenticator: TCustomAuthenticator;
procedure SetAuthenticator(const AValue: TCustomAuthenticator);
function GetBaseURL: string;
function GetAccept: string;
procedure SetAccept(const AValue: string);
function GetUserAgent: string;
function GetAllowCookies: Boolean;
procedure SetAllowCookies(const AValue: Boolean);
function GetHandleRedirects: Boolean;
procedure SetHandleRedirects(const AValue: Boolean);
function GetAcceptCharset: string;
procedure SetAcceptCharset(const AValue: string);
function GetAcceptEncoding: string;
procedure SetAcceptEncoding(const AValue: string);
function GetContentType: string;
procedure SetContentType(const AValue: string);
function GetHttpClient: TRESTHTTP;
procedure SetSynchronizedEvents(const AValue: Boolean);
function GetOnValidateCertificate: TValidateCertificateEvent;
procedure SetOnValidateCertificate(const Value: TValidateCertificateEvent);
function GetRedirectsWithGET: THTTPRedirectsWithGET;
function GetSecureProtocols: THTTPSecureProtocols;
function GetNeedClientCertificateEvent: TNeedClientCertificateEvent;
function GetAuthEvent: TCredentialsStorage.TCredentialAuthevent;
procedure SetRedirectsWithGET(const AValue: THTTPRedirectsWithGET);
procedure SetSecureProtocols(const AValue: THTTPSecureProtocols);
procedure SetNeedClientCertificateEvent(const AValue: TNeedClientCertificateEvent);
procedure SetAuthEvent(const AValue: TCredentialsStorage.TCredentialAuthevent);
property HTTPClient: TRESTHTTP read GetHttpClient;
protected
property NotifyList: TNotifyList read FNotifyList;
procedure ParameterListChanged; virtual;
procedure ParameterValueChanged; virtual;
procedure PropertyValueChanged; virtual;
function CreateBindSource: TBaseObjectBindSource; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
/// <summary>
/// (Re-)creates the actual Http client and applies default values.
/// </summary>
procedure CreateHttpClient;
/// <summary>
/// OnHTTPProtocol dispatch method. Called internally.
/// </summary>
procedure DoHTTPProtocolError; virtual;
/// <summary>
/// HandleEvent ensures that an event handler is ran synchronized or not depending on
/// SynchronizedEvents
/// </summary>
/// <seealso cref="TCustomRESTClient.SynchronizedEvents" />
procedure HandleEvent(AEventHandler: TMethod); virtual;
public
/// <summary>
/// Instantiates a client to the given REST API service.
/// </summary>
/// <param name="ABaseApiURL">
/// This is the base URL for the REST API. E.g.: http://your.server.com/service/api/
/// </param>
constructor Create(const ABaseApiURL: string); reintroduce; overload;
/// <summary>
/// Instantiates a client to the given REST API service, with no BaseURL being set.
/// </summary>
constructor Create(AOwner: TComponent); overload; override;
destructor Destroy; override;
/// <summary>
/// Adds a HTTP parameter to the request. If a parameter of the same name already exists, then the previous parameter
/// will be removed and freed. (QueryString for GET, DELETE, OPTIONS and HEAD; Encoded form for POST and PUT)
/// </summary>
/// <param name="AName">Name of the parameter</param>
/// <param name="AValue">Value of the parameter</param>
procedure AddParameter(const AName, AValue: string); overload;
/// <summary>
/// Adds a parameter to the request. If a parameter of the same name already exists, then the previous parameter
/// will be removed and freed. There are five kinds of parameters:
/// - GetOrPost: Either a QueryString value or encoded form value based on method
/// - HttpHeader: Adds the name/value pair to the HTTP request's Headers collection
/// - UrlSegment: Inserted into URL if there is a matching url token e.g. {AccountId}
/// - Cookie: Adds the name/value pair to the HTTP request's Cookies collection
/// - RequestBody: Used by AddBody() (not recommended to use directly)
/// </summary>
/// <param name="AName">Name of the parameter</param>
/// <param name="AValue">Value of the parameter</param>
/// <param name="AKind">The kind of parameter to add</param>
procedure AddParameter(const AName, AValue: string; const AKind: TRESTRequestParameterKind); overload;
/// <summary>
/// Adds a parameter to the request. If a parameter of the same name already exists, then the previous parameter
/// will be removed and freed.<br /><br />There are five kinds of parameters: - GetOrPost: Either a QueryString
/// value or encoded form value based on method - HttpHeader: Adds the name/value pair to the HTTP request's
/// Headers collection - UrlSegment: Inserted into URL if there is a matching url token e.g. {AccountId} -
/// Cookie: Adds the name/value pair to the HTTP request's Cookies collection - RequestBody: Used by AddBody()
/// (not recommended to use directly)
/// </summary>
/// <param name="AName">
/// Name of the parameter
/// </param>
/// <param name="AValue">
/// Value of the parameter
/// </param>
/// <param name="AKind">
/// The kind of parameter to add
/// </param>
/// <param name="AOptions">
/// Options for processing the parameter
/// </param>
procedure AddParameter(const AName, AValue: string; const AKind: TRESTRequestParameterKind;
const AOptions: TRESTRequestParameterOptions); overload;
/// <summary>
/// Add an authentication parameter. Auth-params are always transient.
/// </summary>
procedure AddAuthParameter(const AName, AValue: string; const AKind: TRESTRequestParameterKind;
const AOptions: TRESTRequestParameterOptions = []); overload;
procedure SetCookie(const ACookie, AURL: string);
procedure SetHTTPHeader(const AName, AValue: string);
function GetEntity<T: class, constructor>(const AResource: string): T;
/// <summary>
/// Sends a GET request and tries to map the result to a List of instances
/// of class <T>
/// </summary>
function GetEntityList<T: class, constructor>(const AResource: string): TObjectList<T>;
/// <summary>
/// Sends a GET request and tries to map the result to an Array of instances
/// of class <T> This function calls GetEntityList internally.
/// </summary>
function GetEntityArray<T: class, constructor>(const AQuery: string): TArray<T>;
/// <summary>
/// Sends a POST request to "insert" an AEntity to the service resources
/// </summary>
function PostEntity<T: class, constructor>(const AResource: string; AEntity: T): TJSONObject;
/// <summary>
/// Resets the RESTClient to default values and clears all entries. The internal
/// HTTPClient will also be recreated.
/// </summary>
procedure ResetToDefaults;
procedure Disconnect;
/// <summary>
/// Transient Params are typically created and re-created by
/// Authenticators. They are not persistent and will not be visible at
/// designtime.
/// In case of a naming-conflict any transient param will override a
/// normal parameter.
/// </summary>
property TransientParams: TRESTRequestParameterList read FTransientParams;
/// <summary>
/// Controls the automatic creation of request-params of type "url-segment" only. no
/// other param-types are afftected.
/// </summary>
property AutoCreateParams: Boolean read FAutoCreateParams write SetAutoCreateParams default True;
/// <summary>
/// Specifies a to be used Authenticator. If left empty, no specific authentication will be used.
/// </summary>
/// <example>
/// <para>
/// LClient := TCustomRESTClient.Create('http://www.example.com');<br />//This is a professional password on a closed
/// course. Do not try this at home!<br />LBasicAuth := THTTPBasicAuthenticator.Create('JohnDoe', 'secret');
/// </para>
/// <para>
/// // RestClient owns its Authenticator through an Interface reference, so technically you do not need to
/// destroy<br /> // an Authenticator on its own.<br />LClient.Authenticator := LBasicAuth;
/// </para>
/// </example>
// <seealso cref="TSimpleAuthenticator">
// Simple Authentication
// </seealso>
// <seealso cref="THTTPBasicAuthenticator">
// Basic Authentication
// </seealso>
// <seealso cref="TOAuth1Authenticator">
// OAuth1 Authentication
// </seealso>
// <seealso cref="TOAuth2Authenticator">
// OAuth2 Authentication
// </seealso>
property Authenticator: TCustomAuthenticator read GetAuthenticator write SetAuthenticator;
property Accept: string read GetAccept write SetAccept;
property AcceptCharset: string read GetAcceptCharset write SetAcceptCharset;
property AcceptEncoding: string read GetAcceptEncoding write SetAcceptEncoding;
property AllowCookies: Boolean read GetAllowCookies write SetAllowCookies default True;
/// <summary>
/// Base URL for all API calls. All request resources and parameters will be appended to this URL
/// </summary>
/// <remarks>
/// Setting the BaseURL ensures, that a possibly trailing slash is removed.
/// </remarks>
/// <example>
/// https://api.twitter.com/
/// </example>
property BaseURL: string read GetBaseURL write SetBaseURL;
/// <summary>
/// ContentType for a POST or PUT requests. This property will be used internally while TRESTClient.Execute.
/// </summary>
property ContentType: string read GetContentType write SetContentType;
/// <summary>
/// <para>
/// Specifies a character encoding for strings, which will be used if the server does not specify one.
/// </para>
/// <para>
/// RFC2616 technically specifies ISO-8859-1 as default character, but
/// <see href="http://www.w3.org/TR/html4/charset.html" /> section 5.2.2 clearly says that this specification
/// has proven useless.
/// </para>
/// <para>
/// There are some (many?) servers/APIs that actually use UTF-8, but "forget" to specify that in their
/// responses. As UTF-8 is a defacto-standard for Web/HTPP anyway, 'UTF-8' is used as default here.
/// </para>
/// <para>
/// If FallbackCharsetEncoding is set to '' (empty string) or 'raw', then the current default encoding will be
/// used - which usually won't make much sense.
/// </para>
/// </summary>
/// <remarks>
/// RAWBytes, will always return an undecoded array of bytes as sent by the server.
/// </remarks>
property FallbackCharsetEncoding: string read GetFallbackCharsetEncoding
write SetFallbackCharsetEncoding stored FallbackCharsetEncodingIsStored;
/// <summary>
/// Container of all HTTP parameters to be passed with each request.
/// See Params.Add() for explanation of the types of parameters that can be passed.
/// Priority of Params is as follows - highest priority first:
/// 1 : Transient Parameters
/// 2 : Parameters supplied by the RESTRequest
/// 3 : Parameters supplied by the RESTClient
/// Example: if there are two parameters with the same name, one transient, the other
/// </summary>
property Params: TRESTRequestParameterList read GetParams write SetParams;
property HandleRedirects: Boolean read GetHandleRedirects write SetHandleRedirects
default True;
property RedirectsWithGET: THTTPRedirectsWithGET read GetRedirectsWithGET
write SetRedirectsWithGET default CHTTPDefRedirectsWithGET;
property SecureProtocols: THTTPSecureProtocols read GetSecureProtocols
write SetSecureProtocols default CHTTPDefSecureProtocols;
/// <summary>
/// Password for proxy authentication (optional)
/// </summary>
property ProxyPassword: string read GetProxyPassword write SetProxyPassword;
/// <summary>
/// Port for HTTP proxy server.
/// </summary>
/// <value>
/// Will be ignored if 0
/// </value>
property ProxyPort: Integer read GetProxyPort write SetProxyPort default 0;
/// <summary>
/// Server name for proxy server. Specify a fully qualified domain name or IP address. Proxy settings will be
/// ignored if left empty.
/// </summary>
property ProxyServer: string read GetProxyServer write SetProxyServer;
/// <summary>
/// User name for proxy authentication (optional).
/// </summary>
property ProxyUsername: string read GetProxyUsername write SetProxyUsername;
/// <summary>
/// Specifies if an Exception should be raised if a 500 Protocol exception occurs. Defaults to True;
/// </summary>
property RaiseExceptionOn500: Boolean read FRaiseExceptionOn500 write FRaiseExceptionOn500 default True;
/// <summary>
/// Specifies if Events (such as OnAfterExecute or OnHTTPProtocolError) should run in the context of the main
/// thread (True) or in the context of an arbitrary thread - which was created by the developer or by using
/// ExecuteAsync.
/// </summary>
// <seealso cref="TCustomRESTRequest.ExecuteAsync" />
property SynchronizedEvents: Boolean read FSynchronizedEvents
write SetSynchronizedEvents default True;
/// <summary>
/// Defaults to 'Embarcadero RESTClient/{version}'
/// </summary>
/// <remarks>
/// See http://tools.ietf.org/html/rfc2616#section-14.43
/// </remarks>
property UserAgent: string read GetUserAgent write SetUserAgent stored UserAgentIsStored;
/// <summary>
/// <para>
/// OnHTTPProtocolError gets fired when the server returns a status code other than 200 - OK
/// </para>
/// <para>
/// Check AClient.Response.StatusCode for the actual status.
/// </para>
/// <para>
/// This event will not get fired if a non HTTP-related exception occurs during execution. This includes, but
/// is not limited to timeout and server not found related exceptions.
/// </para>
/// </summary>
property OnHTTPProtocolError: TCustomRESTClientNotifyEvent
read FOnHTTPProtocolError write FOnHTTPProtocolError;
property BindSource: TSubRESTClientBindSource read FBindSource;
/// <summary>Validate the certificate provided by a secure (HTTPS) server</summary>
property OnValidateCertificate: TValidateCertificateEvent
read GetOnValidateCertificate write SetOnValidateCertificate;
property OnNeedClientCertificate: TNeedClientCertificateEvent
read GetNeedClientCertificateEvent write SetNeedClientCertificateEvent;
property OnAuthEvent: TCredentialsStorage.TCredentialAuthevent
read GetAuthEvent write SetAuthEvent;
end;
/// <summary>
/// LiveBindings adapter for TCustomRESTClient. Create bindable members
/// </summary>
TRESTClientAdapter = class(TRESTComponentAdapter)
public type
TNotify = class(TCustomRESTClient.TNotify)
private
FAdapter: TRESTClientAdapter;
constructor Create(const AAdapter: TRESTClientAdapter);
public
procedure ParameterListChanged(Sender: TObject); override;
procedure PropertyValueChanged(Sender: TObject); override;
end;
private
FClient: TCustomRESTClient;
FNotify: TNotify;
procedure SetClient(const AClient: TCustomRESTClient);
procedure AddParameterFields;
procedure ParameterListChanged;
procedure AddPropertyFields;
protected
procedure DoChangePosting; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
function GetCanActivate: Boolean; override;
procedure AddFields; override;
function GetSource: TBaseLinkingBindSource; override;
public
constructor Create(AComponent: TComponent); override;
destructor Destroy; override;
procedure GetMemberNames(AList: TStrings); override;
property Client: TCustomRESTClient read FClient write SetClient;
end;
/// <summary>
/// LiveBindings bindsource for TCustomRESTResponse. Creates adapter
/// </summary>
TCustomRESTClientBindSource = class(TRESTComponentBindSource)
private
FAdapter: TRESTClientAdapter;
function GetClient: TCustomRESTClient;
procedure SetClient(const AValue: TCustomRESTClient);
protected
function CreateAdapter: TRESTComponentAdapter; override;
public
property Client: TCustomRESTClient read GetClient write SetClient;
property Adapter: TRESTClientAdapter read FAdapter;
end;
/// <summary>
/// LiveBindings bindsource for TCustomRESTClient. Publishes subcomponent properties
/// </summary>
TSubRESTClientBindSource = class(TCustomRESTClientBindSource)
published
property AutoActivate;
property AutoEdit;
property AutoPost;
end;
TRESTClient = class(TCustomRESTClient)
published
property Authenticator;
property Accept;
property AcceptCharset;
property AcceptEncoding;
property AllowCookies;
property AutoCreateParams;
property BaseURL;
property ContentType;
property FallbackCharsetEncoding;
property Params;
property HandleRedirects;
property RedirectsWithGET;
property SecureProtocols;
property ProxyPassword;
property ProxyPort;
property ProxyServer;
property ProxyUsername;
property RaiseExceptionOn500;
property SynchronizedEvents;
property UserAgent;
property OnHTTPProtocolError;
property BindSource;
property OnValidateCertificate;
property OnNeedClientCertificate;
property OnAuthEvent;
end;
TAuthenticateEvent = procedure(ARequest: TCustomRESTRequest; var ADone: Boolean) of object;
/// <summary>
/// Base class for all authenticators authenticators are attached to the rest-clients
/// </summary>
TCustomAuthenticator = class(TBaseObjectBindSourceDelegate)
protected type
TNotify = TRESTComponentNotify;
TNotifyList = TRESTComponentNotifyList<TNotify>;
private
FNotifyList: TNotifyList;
FOnAuthenticate: TAuthenticateEvent;
protected
procedure PropertyValueChanged; virtual;
property NotifyList: TNotifyList read FNotifyList;
/// <summary>
/// does the actual authentication by extending the request with parameters and data as needed
/// </summary>
procedure DoAuthenticate(ARequest: TCustomRESTRequest); virtual; abstract;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Authenticate(ARequest: TCustomRESTRequest);
procedure ResetToDefaults; virtual;
published
property OnAuthenticate: TAuthenticateEvent read FOnAuthenticate write FOnAuthenticate;
end;
/// <summary>
/// LiveBindings adapter for TCustomAuthenticator. Descendents add bindable members.
/// </summary>
TRESTAuthenticatorAdapter<T: TCustomAuthenticator> = class(TRESTComponentAdapter)
private
FAuthenticator: T;
procedure SetAuthenticator(const AAuthenticator: T);
protected type
TNotify = TRESTComponentAdapter.TNotify;
private
FNotify: TNotify;
protected
function GetSource: TBaseLinkingBindSource; override;
procedure DoAuthenticatorChanging; virtual;
procedure DoAuthenticatorChanged; virtual;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
function GetCanActivate: Boolean; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Authenticator: T read FAuthenticator write SetAuthenticator;
end;
/// <summary>
/// LiveBindings bindsource for TCustomAuthenticator. Creates adapter.
/// </summary>
TRESTAuthenticatorBindSource<T: TCustomAuthenticator> = class(TRESTComponentBindSource)
private
FAdapter: TRESTAuthenticatorAdapter<T>;
function GetAuthenticator: TCustomAuthenticator;
procedure SetAuthenticator(const Value: TCustomAuthenticator);
protected
function CreateAdapter: TRESTComponentAdapter; override;
function CreateAdapterT: TRESTAuthenticatorAdapter<T>; virtual;
public
property Authenticator: TCustomAuthenticator read GetAuthenticator write SetAuthenticator;
property Adapter: TRESTAuthenticatorAdapter<T> read FAdapter;
published
property AutoActivate;
property AutoEdit;
property AutoPost;
end;
/// <summary>
/// Download a file
/// </summary>
TDownloadURL = class
private
class procedure CheckForError(const AResponse: TCustomRESTResponse); static;
public
class procedure DownloadRawBytes(const AURL: string; const AStream: TStream); static;
end;
implementation
uses
{$IFDEF MACOS}
Macapi.CoreFoundation,
{$ENDIF}
System.Math, System.Types, System.Rtti, System.StrUtils, System.TypInfo,
System.NetEncoding, System.JSON.Types, System.Net.Mime,
Data.Bind.Json, // JSON LiveBindings converters
REST.Json, REST.Consts, REST.Utils;
const
sRequestDefaultAccept = CONTENTTYPE_APPLICATION_JSON + ', ' +
CONTENTTYPE_TEXT_PLAIN + '; q=0.9, ' + CONTENTTYPE_TEXT_HTML + ';q=0.8,';
// UTF-8 is prefered, any other is good, but marked down
sRequestDefaultAcceptCharset = 'utf-8, *;q=0.8';
sDefaultFallbackCharSetEncoding = 'utf-8';
sDefaultUserAgent = 'Embarcadero RESTClient/' + RESTCLIENT_VERSION;
sBody = 'body';
sFile = 'file';
function RESTFindDefaultRequest(AComp: TComponent): TCustomRESTRequest;
begin
Result := TRESTFindDefaultComponent.FindDefaultT<TCustomRESTRequest>(AComp);
end;
function RESTFindDefaultResponse(AComp: TComponent): TCustomRESTResponse;
begin
Result := TRESTFindDefaultComponent.FindDefaultT<TCustomRESTResponse>(AComp);
end;
function RESTFindDefaultClient(AComp: TComponent): TCustomRESTClient;
begin
Result := TRESTFindDefaultComponent.FindDefaultT<TCustomRESTClient>(AComp);
end;
function RESTFindDefaultAuthenticator(AComp: TComponent): TCustomAuthenticator;
begin
Result := TRESTFindDefaultComponent.FindDefaultT<TCustomAuthenticator>(AComp);
end;
/// <summary>
/// Iterates through all components of the same owner (typically a form)
/// and looks for TRESTRequests having no response assigned. if found,
/// the new component is just assigned as response.
/// </summary>
procedure AssignResponseToRESTRequests(AResponse: TCustomRESTResponse);
begin
TRESTFindDefaultComponent.FindAllT<TCustomRESTRequest>(AResponse,
procedure(AComp: TCustomRESTRequest)
begin
if AComp.Response = nil then
AComp.Response := AResponse;
end);
end;
/// <summary>
/// Iterates through all components of the same owner (typically a form)
/// and looks for TRESTRequests having no client assigned. if found, the
/// new component is just assigned as client.
/// </summary>
procedure AssignClientToRESTRequests(AClient: TCustomRESTClient);
begin
TRESTFindDefaultComponent.FindAllT<TCustomRESTRequest>(AClient,
procedure(AComp: TCustomRESTRequest)
begin
if AComp.Client = nil then
AComp.Client := AClient;
end);
end;
/// <summary>
/// Iterates through all components of the same owner (typically a form)
/// and looks for TRESTClients having no authenticator assigned. if found,
/// the new component is just assigned as authenticator.
/// </summary>
procedure AssignAuthenticatorToRESTClients(AAuthenticator: TCustomAuthenticator);
begin
TRESTFindDefaultComponent.FindAllT<TCustomRESTClient>(AAuthenticator,
procedure(AComp: TCustomRESTClient)
begin
if AComp.Authenticator = nil then
AComp.Authenticator := AAuthenticator;
end);
end;
{ TRESTRequestParameter }
procedure TRESTRequestParameter.Assign(ASource: TPersistent);
var
LParam: TRESTRequestParameter;
begin
if ASource is TRESTRequestParameter then
begin
LParam := TRESTRequestParameter(ASource);
FName := LParam.Name;
FValue := LParam.Value;
FStream := LParam.Stream;
FStreamOwner := False;
FKind := LParam.Kind;
FOptions := LParam.Options;
FContentType := LParam.ContentType;
end
else
inherited Assign(ASource);
end;
constructor TRESTRequestParameter.Create(ACollection: TCollection);
begin
inherited Create(ACollection);
FName := '';
FValue := '';
FKind := DefaulTRESTRequestParameterKind;
FOptions := [];
FContentType := DefaultRESTContentType;
end;
destructor TRESTRequestParameter.Destroy;
begin
ReleaseStream;
inherited Destroy;
end;
procedure TRESTRequestParameter.ReleaseStream;
begin
if FStream <> nil then
begin
if StreamOwner then
FStream.Free;
FStream := nil;
end;
end;
procedure TRESTRequestParameter.NotifyParameterChanged(AValueChanged: Boolean);
var
LNotify: IRESTRequestParameterListOwnerNotify;
begin
if (Collection is TRESTRequestParameterList) and (Collection.Owner <> nil) then
if TRESTRequestParameterList(Collection).UpdateCount = 0 then
if Supports(Collection.Owner, IRESTRequestParameterListOwnerNotify, LNotify) then
if AValueChanged then
LNotify.ParameterValueChanged
else
LNotify.ParameterListChanged;
end;
function TRESTRequestParameter.GetDisplayName: string;
begin
Result := FName;
end;
function TRESTRequestParameter.KindIsStored: Boolean;
begin
Result := Kind <> DefaulTRESTRequestParameterKind;
end;
procedure TRESTRequestParameter.SetContentType(const AValue: TRESTContentType);
begin
if FContentType <> AValue then
begin
FContentType := AValue;
Changed(False);
end;
end;
procedure TRESTRequestParameter.SetKind(const AValue: TRESTRequestParameterKind);
begin
if FKind <> AValue then
begin
FKind := AValue;
Changed(False);
end;
end;
procedure TRESTRequestParameter.SetName(const AValue: string);
begin
if FName <> AValue then
begin
FName := AValue;
Changed(False);
NotifyParameterChanged(False);
end;
end;
procedure TRESTRequestParameter.SetOptions(const AValue: TRESTRequestParameterOptions);
begin
if FOptions <> AValue then
begin
FOptions := AValue;
Changed(False);
end;
end;
procedure TRESTRequestParameter.SetValue(const AValue: string);
begin
if FValue <> AValue then
begin
FValue := AValue;
Changed(False);
NotifyParameterChanged(True);
end;
end;
procedure TRESTRequestParameter.SetStream(const AValue: TStream;
AOwnership: TRESTObjectOwnership);
begin
if FStream <> AValue then
begin
ReleaseStream;
if AOwnership = ooCopy then
begin
FStream := TMemoryStream.Create;
try
FStream.CopyFrom(AValue, 0);
except
FreeAndNil(FStream);
raise;
end;
end
else
FStream := AValue;
FStreamOwner := AOwnership in [ooCopy, ooREST];
Changed(False);
NotifyParameterChanged(True);
end;
end;
function TRESTRequestParameter.GetBytes: TBytes;
begin
if (Stream <> nil) and (Stream is TBytesStream) then
Result := TBytesStream(Stream).Bytes
else
Result := nil;
end;
function TRESTRequestParameter.AddValue(const AValue: string): TRESTRequestParameter;
var
LValue: string;
begin
if Options * [poFlatArray, poPHPArray, poListArray] = [] then
Options := Options + [poFlatArray];
LValue := Value;
if LValue <> '' then
LValue := LValue + ';';
LValue := LValue + AValue;
Value := LValue;
Result := Self;
end;
function TRESTRequestParameter.ToString: string;
var
LEncode: string;
LValue: string;
begin
if poDoNotEncode in FOptions then
LEncode := ''
else
LEncode := ' / E';
if Stream <> nil then
LValue := '(stream)'
else
LValue := FValue;
Result := Format('[%s%s] %s=%s',
[RESTRequestParameterKindToString(FKind), LEncode, FName, LValue])
end;
{ TRESTRequestParameterList }
constructor TRESTRequestParameterList.Create(const AOwner: TComponent);
begin
inherited Create(AOwner, TRESTRequestParameter);
end;
procedure TRESTRequestParameterList.CreateGetParamsFromUrl(const AUrlPath: string);
var
LParams: TStrings;
i: Integer;
LParam: TRESTRequestParameter;
LName: string;
LPHPArray: Boolean;
begin
LParams := nil;
BeginUpdate;
try
ExtractGetParams(AUrlPath, LParams);
for i := 0 to LParams.Count - 1 do
begin
LName := LParams.Names[i];
LPHPArray := LName.EndsWith('[]');
if LPHPArray then
LName := LName.Substring(0, LName.Length - 2);
LParam := ParameterByName(LName);
if LParam <> nil then
LParam.AddValue(LParams.ValueFromIndex[i])
else
begin
LParam := AddItem;
LParam.Kind := TRESTRequestParameterKind.pkGETorPOST;
LParam.Name := LName;
LParam.Value := LParams.ValueFromIndex[i];
if LPHPArray then
LParam.Options := LParam.Options + [poPHPArray];
end;
end;
finally
EndUpdate;
LParams.Free;
end;
end;
procedure TRESTRequestParameterList.Delete(const AParam: TRESTRequestParameter);
var
i: Integer;
begin
i := IndexOf(AParam);
if i <> -1 then
Delete(i);
end;
procedure TRESTRequestParameterList.Delete(const AName: string);
begin
Delete(ParameterByName(AName));
end;
function TRESTRequestParameterList.CreateURLSegmentsFromString(const AUrlPath: string): Boolean;
var
LNewParams: TStringList;
LName: string;
LParam: TRESTRequestParameter;
i: Integer;
begin
Result := False;
LNewParams := nil;
BeginUpdate;
try
LNewParams := TStringList.Create;
ExtractURLSegmentNames(AUrlPath, LNewParams);
// first, delete unmatched parameters - parameters that
// were defined here in the collection but are not
// part of the new url-string any more
for i := Count - 1 downto 0 do
begin
LParam := Items[i];
// we only process autocreated params of type url-segment
if (LParam.Kind = TRESTRequestParameterKind.pkURLSEGMENT) and
(TRESTRequestParameterOption.poAutoCreated in LParam.Options) then
begin
if LNewParams.IndexOf(LParam.Name) < 0 then
begin
Delete(LParam);
// return True to indicate changes made
Result := True;
end;
end;
end;
// now add new parameters but without overriding existing
// params in case of naming-conflicts
for LName in LNewParams do
if (LName <> '') and not ContainsParameter(LName) then
begin
LParam := AddItem;
LParam.Name := LName;
LParam.Kind := TRESTRequestParameterKind.pkURLSEGMENT;
LParam.Options := LParam.Options + [TRESTRequestParameterOption.poAutoCreated];
// return True to indicate changes made
Result := True;
end;
finally
EndUpdate;
LNewParams.Free;
end;
end;
function TRESTRequestParameterList.GetAttr(AIndex: Integer): string;
begin
case AIndex of
0:
Result := sParameterName;
1:
Result := sParameterValue;
2:
Result := sParameterKind;
else
Result := ''; { do not localize }
end;
end;
function TRESTRequestParameterList.GetAttrCount: Integer;
begin
Result := 3;
end;
function TRESTRequestParameterList.GetEnumerator: TEnumerator;
begin
Result := TEnumerator.Create(Self);
end;
function TRESTRequestParameterList.GetItem(AIndex: Integer): TRESTRequestParameter;
begin
Result := TRESTRequestParameter(inherited Items[AIndex]);
end;
function TRESTRequestParameterList.GetItemAttr(AIndex, AItemIndex: Integer): string;
begin
case AIndex of
0:
begin
Result := Items[AItemIndex].Name;
if Result = '' then
Result := IntToStr(AItemIndex);
end;
1:
Result := Items[AItemIndex].Value;
2:
Result := System.TypInfo.GetEnumName(TypeInfo(TRESTRequestParameterKind),
Integer(Items[AItemIndex].Kind));
else
Result := '';
end;
end;
function TRESTRequestParameterList.IndexOf(const AName: string): Integer;
var
i: Integer;
LName: string;
begin
Result := -1;
if AName = '' then
Exit;
LName := AName.ToLower;
for i := 0 to Count - 1 do
if Items[i].Name.ToLower = LName then
Exit(i);
end;
function TRESTRequestParameterList.IndexOf(const AParam: TRESTRequestParameter): Integer;
var
i: Integer;
begin
Result := -1;
if AParam = nil then
Exit;
for i := 0 to Count - 1 do
if Items[i] = AParam then
Exit(i);
end;
function TRESTRequestParameterList.AddCookie(const AName, AValue: string): TRESTRequestParameter;
begin
Result := AddItem(AName, AValue, TRESTRequestParameterKind.pkCOOKIE);
end;
function TRESTRequestParameterList.AddHeader(const AName, AValue: string): TRESTRequestParameter;
begin
Result := AddItem(AName, AValue, TRESTRequestParameterKind.pkHTTPHEADER);
end;
function TRESTRequestParameterList.AddItem: TRESTRequestParameter;
begin
Result := Add as TRESTRequestParameter;
end;
procedure TRESTRequestParameterList.AddObject(AObject: TObject);
var
LContext: TRttiContext;
LType: TRttiType;
LProperty: TRttiProperty;
begin
LContext := TRttiContext.Create;
LType := LContext.GetType(AObject.ClassType);
for LProperty in LType.GetProperties do
if LProperty.Visibility in [TMemberVisibility.mvPublic, TMemberVisibility.mvPublished] then
AddItem(LProperty.Name, LProperty.GetValue(AObject).ToString);
end;
procedure TRESTRequestParameterList.AddObject(AObject: TObject; WhiteList: TStrings);
var
LContext: TRttiContext;
LType: TRttiType;
LProperty: TRttiProperty;
begin
LContext := TRttiContext.Create;
LType := LContext.GetType(AObject.ClassType);
for LProperty in LType.GetProperties do
if LProperty.Visibility in [TMemberVisibility.mvPublic, TMemberVisibility.mvPublished] then
if WhiteList.IndexOf(LProperty.Name) >= 0 then
AddItem(LProperty.Name, LProperty.GetValue(AObject).ToString);
end;
function TRESTRequestParameterList.AddItem(const AName, AValue: string): TRESTRequestParameter;
begin
Result := AddItem(AName, AValue, TRESTRequestParameterKind.pkGETorPOST);
end;
function TRESTRequestParameterList.AddItem(const AName, AValue: string; AKind: TRESTRequestParameterKind;
AOptions: TRESTRequestParameterOptions): TRESTRequestParameter;
begin
Result := AddItem(AName, AValue, AKind, AOptions, DefaultRESTContentType);
end;
function TRESTRequestParameterList.AddItem(const AName, AValue: string; const AKind: TRESTRequestParameterKind;
const AOptions: TRESTRequestParameterOptions; AContentType: TRESTContentType): TRESTRequestParameter;
var
i: Integer;
begin
BeginUpdate;
try
i := IndexOf(AName);
if i = -1 then
Result := AddItem
else
Result := Items[i];
Result.Name := AName;
Result.Value := AValue;
Result.Kind := AKind;
Result.Options := AOptions;
Result.ContentType := AContentType;
finally
EndUpdate;
end;
end;
function TRESTRequestParameterList.AddItem(const AName: string; const AValue: TBytes; const AKind: TRESTRequestParameterKind;
const AOptions: TRESTRequestParameterOptions; AContentType: TRESTContentType): TRESTRequestParameter;
var
i: Integer;
begin
BeginUpdate;
try
i := IndexOf(AName);
if i = -1 then
Result := AddItem
else
Result := Items[i];
Result.Name := AName;
Result.SetStream(TBytesStream.Create(AValue), ooREST);
Result.Kind := AKind;
Result.Options := AOptions;
Result.ContentType := AContentType;
finally
EndUpdate;
end;
end;
function TRESTRequestParameterList.AddItem(const AName: string; const AValue: TStream; const AKind: TRESTRequestParameterKind;
const AOptions: TRESTRequestParameterOptions; AContentType: TRESTContentType; AOwnsStream: TRESTObjectOwnership): TRESTRequestParameter;
var
i: Integer;
begin
BeginUpdate;
try
i := IndexOf(AName);
if i = -1 then
Result := AddItem
else
Result := Items[i];
Result.Name := AName;
Result.SetStream(AValue, AOwnsStream);
Result.Kind := AKind;
Result.Options := AOptions;
Result.ContentType := AContentType;
finally
EndUpdate;
end;
end;
procedure TRESTRequestParameterList.AddUrlSegment(const AName, AValue: string);
begin
AddItem(AName, AValue, TRESTRequestParameterKind.pkURLSEGMENT);
end;
function TRESTRequestParameterList.ParameterByIndex(AIndex: Integer): TRESTRequestParameter;
begin
Result := Items[AIndex];
end;
function TRESTRequestParameterList.ParameterByName(const AName: string): TRESTRequestParameter;
var
i: Integer;
begin
i := IndexOf(AName);
if i <> -1 then
Result := Items[i]
else
Result := nil;
end;
procedure TRESTRequestParameterList.SetItem(AIndex: Integer; const AValue: TRESTRequestParameter);
begin
inherited SetItem(AIndex, TCollectionItem(AValue));
end;
procedure TRESTRequestParameterList.Update(AItem: TCollectionItem);
var
LNotify: IRESTRequestParameterListOwnerNotify;
begin
inherited;
// Entire list changed
if (Owner <> nil) and (AItem = nil) then
if Supports(Owner, IRESTRequestParameterListOwnerNotify, LNotify) then
LNotify.ParameterListChanged;
end;
function TRESTRequestParameterList.ContainsParameter(const AName: string): Boolean;
begin
Result := IndexOf(AName) >= 0;
end;
{ TRESTRequestParameterList.TEnumerator }
function TRESTRequestParameterList.TEnumerator.GetCurrent: TRESTRequestParameter;
begin
Result := TRESTRequestParameter(inherited GetCurrent);
end;
{ TRESTExecutionThread }
constructor TRESTExecutionThread.Create(AExecuteMethod: TExecuteMethod; ARequest: TCustomRESTRequest;
ACompletionHandler: TCompletionHandler; ASynchronized: Boolean; AFreeThread: Boolean = True;
ACompletionHandlerWithError: TCompletionHandlerWithError = nil);
begin
inherited Create(False);
FreeOnTerminate := AFreeThread;
FCompletionHandler := ACompletionHandler;
FExecuteMethod := AExecuteMethod;
FSynchronized := ASynchronized;
FRequest := ARequest;
FCompletionHandlerWithError := ACompletionHandlerWithError;
end;
procedure TRESTExecutionThread.Execute;
begin
try
FExecuteMethod;
if FSynchronized then
Synchronize(HandleCompletion) // Just synchronize. No need to Queue
else
HandleCompletion;
except
if Assigned(FCompletionHandlerWithError) then
try
FExceptObject := AcquireExceptionObject;
try
if FSynchronized then
Synchronize(HandleCompletionWithError)
else
HandleCompletionWithError;
finally
FExceptObject.Free;
end;
except
end;
end;
end;
procedure TRESTExecutionThread.HandleCompletion;
begin
if Assigned(FCompletionHandler) then
FCompletionHandler;
end;
procedure TRESTExecutionThread.HandleCompletionWithError;
begin
if Assigned(FCompletionHandlerWithError) then
FCompletionHandlerWithError(FExceptObject);
end;
procedure TRESTRequestParameterList.AddBody(const ABodyContent: string;
AContentType: TRESTContentType);
var
LGUID: TGUID;
LGuidString: string;
LBodyContent: string;
begin
// A body does not have a specific name, but as names need to be unique, we are using a GUID here
CreateGUID(LGUID);
LGuidString := LGUID.ToString;
LGuidString := LGuidString.Replace('{', '', [rfReplaceAll]);
LGuidString := LGuidString.Replace('}', '', [rfReplaceAll]);
LGuidString := LGuidString.Replace('-', '', [rfReplaceAll]);
LGuidString := sBody + LGuidString;
LBodyContent := ABodyContent;
AddItem(LGUIDString, LBodyContent, TRESTRequestParameterKind.pkREQUESTBODY,
[], AContentType);
end;
procedure TRESTRequestParameterList.AddBody(const AObject: TJsonObject;
AOwnsObject: TRESTObjectOwnership);
var
LBodyContent: string;
begin
try
LBodyContent := TJson.JsonEncode(AObject);
AddItem(sBody, LBodyContent, TRESTRequestParameterKind.pkREQUESTBODY,
[], TRESTContentType.ctAPPLICATION_JSON);
finally
if AOwnsObject = ooREST then
AObject.Free;
end;
end;
procedure TRESTRequestParameterList.AddBody(const ABodyContent: TStream;
AContentType: TRESTContentType; AOwnsStream: TRESTObjectOwnership);
begin
AddItem(sBody, ABodyContent, TRESTRequestParameterKind.pkREQUESTBODY,
[poDoNotEncode], AContentType, AOwnsStream);
end;
procedure TRESTRequestParameterList.AddBody<T>(const AObject: T;
AOwnsObject: TRESTObjectOwnership = ooApp);
var
LJSONObject: TJSONObject;
begin
LJSONObject := nil;
try
LJSONObject := TJson.ObjectToJsonObject(AObject);
AddBody(LJSONObject);
finally
LJSONObject.Free;
if AOwnsObject = ooREST then
AObject.Free;
end;
end;
{ TCustomRESTRequest }
constructor TCustomRESTRequest.Create(AOwner: TComponent);
begin
// it is important to create the notify-list before
// calling the inherited constructor
FNotifyList := TNotifyList.Create;
inherited Create(AOwner);
// if we do get a client as owner, we just use
// it. otherwise we look around and try to find
// an existing client (maybe on the same form)
if AOwner is TCustomRESTClient then
Client := TCustomRESTClient(AOwner)
else if RESTComponentIsDesigning(Self) then
Client := RESTFindDefaultClient(Self);
if AOwner is TCustomRESTResponse then
Response := TCustomRESTResponse(AOwner)
else if RESTComponentIsDesigning(Self) then
Response := RESTFindDefaultResponse(Self);
FAutoCreateParams := True;
FParams := TRESTRequestParameterList.Create(Self);
FTransientParams := TRESTRequestParameterList.Create(Self);
FBody := TBody.Create;
ResetToDefaults;
end;
function TCustomRESTRequest.CreateRequestBindSource: TSubRESTRequestBindSource;
begin
Result := TSubRESTRequestBindSource.Create(Self);
end;
function TCustomRESTRequest.CreateBindSource: TBaseObjectBindSource;
begin
FBindSource := CreateRequestBindSource;
FBindSource.Name := 'BindSource'; { Do not localize }
FBindSource.SetSubComponent(True);
FBindSource.Request := Self;
Result := FBindSource;
end;
destructor TCustomRESTRequest.Destroy;
begin
FreeAndNil(FNotifyList);
FreeAndNil(FParams);
FreeAndNil(FTransientParams);
FBody.Free;
inherited Destroy;
end;
procedure TCustomRESTRequest.DoAfterExecute;
begin
if Assigned(FOnAfterExecute) then
FOnAfterExecute(Self);
end;
procedure TCustomRESTRequest.DoBeforeExecute;
begin
end;
procedure TCustomRESTRequest.DoApplyCookieParams(const AParamList: TRESTRequestParameterArray; const CookieURL: string);
var
LParameter: TRESTRequestParameter;
LName: string;
LValue: string;
begin
for LParameter in AParamList do
if LParameter.Kind = TRESTRequestParameterKind.pkCOOKIE then
begin
if TRESTRequestParameterOption.poDoNotEncode in LParameter.Options then
begin
LName := LParameter.Name;
LValue := LParameter.Value;
end
else
begin
LName := URIEncode(LParameter.Name);
LValue := URIEncode(LParameter.Value);
end;
FClient.SetCookie(LName + '=' + LValue, CookieURL);
end;
end;
procedure TCustomRESTRequest.DoApplyHeaderParams(const AParamList: TRESTRequestParameterArray);
var
LParameter: TRESTRequestParameter;
LValue: string;
LName: string;
begin
for LParameter in AParamList do
if LParameter.Kind = TRESTRequestParameterKind.pkHTTPHEADER then
begin
if TRESTRequestParameterOption.poDoNotEncode in LParameter.Options then
begin
LName := LParameter.Name;
LValue := LParameter.Value;
end
else
begin
LName := URIEncode(LParameter.Name);
LValue := URIEncode(LParameter.Value);
end;
FClient.SetHTTPHeader(LName, LValue);
end;
end;
procedure TCustomRESTRequest.DoApplyURLSegments(const AParamList: TRESTRequestParameterArray; var AURL: string);
var
LParameter: TRESTRequestParameter;
LReplace: string;
begin
for LParameter in AParamList do
if LParameter.Kind = TRESTRequestParameterKind.pkURLSEGMENT then
begin
LReplace := '{' + LParameter.Name + '}';
// Trailing '/' needed to pass blank value
if (LParameter.Value = '') and (AURL.Length > LReplace.Length) and
SameText(AURL.Substring(AURL.Length - LReplace.Length), LReplace) then
AURL := AURL + '/';
AURL := StringReplace(AURL, LReplace, LParameter.Value, [rfReplaceAll, rfIgnoreCase]);
end;
end;
procedure TCustomRESTRequest.DoHTTPProtocolError;
begin
if Assigned(FOnHTTPProtocolError) then
FOnHTTPProtocolError(Self);
end;
function TCustomRESTRequest.CreateUnionParameterList: TRESTRequestParameterArray;
var
LList: TList<TRESTRequestParameter>;
LParam: TRESTRequestParameter;
procedure MergeParam(const AParam: TRESTRequestParameter; const AList: TList<TRESTRequestParameter>);
var
i: Integer;
begin
for i := 0 to AList.Count - 1 do
if SameText(AParam.Name, AList[i].Name) then
begin
// an empty auto-created param will never override an other parameter
if (poAutoCreated in AParam.Options) and (AParam.Value = '') then
Exit;
AList.Delete(i);
AList.Insert(i, AParam);
Exit;
end;
AList.Add(AParam);
end;
begin
// create the complete list of parameters for this request
// please note that we do have four sources:
// (1) a list of parameters belonging to the client
// (2) a list of TRANSIENT parameters belonging to the client
// (3) a list of parameters belonging to the request
// (4) a list of TRANSIENT parameters belonging to the request
//
// --> in case of a conflict,
// the request overrides the client with one exception:
// params can be auto-created by the components while
// parsing parts of the url or resource. these params
// do not have a value by default. if the user created
// a parameter manually and provided a value, then this
// value is used and will not be overriden by the empty
// auto-created param
LList := TList<TRESTRequestParameter>.Create;
try
// first, the default params from the client
if FClient <> nil then
for LParam in FClient.Params do
MergeParam(LParam, LList);
// next, our own default params, overriding any existing params
for LParam in Params do
MergeParam(LParam, LList);
// next, the transient params from the client, overriding any existing params
if FClient <> nil then
for LParam in FClient.TransientParams do
MergeParam(LParam, LList);
// now our own transient params, overriding any existing params
for LParam in TransientParams do
MergeParam(LParam, LList);
Result := LList.ToArray;
finally
LList.Free;
end;
end;
procedure TCustomRESTRequest.DoPrepareRequestBody(AParamList: TRESTRequestParameterArray;
AContentType: TRESTContentType; var ABodyStream: TStream; var ABodyStreamOwner: Boolean);
var
LParam: TRESTRequestParameter;
LParamString: string;
LParamName: string;
LParamValue: string;
LMultipartFormData: TMultipartFormData;
LBuffer: TBytes;
begin
Assert(Client <> nil);
ABodyStreamOwner := True;
LMultipartFormData := nil;
try
// the goal is to embedd all relevant params into a stream
case AContentType of
TRESTContentType.ctAPPLICATION_X_WWW_FORM_URLENCODED:
begin
ABodyStream := TStringStream.Create;
end;
TRESTContentType.ctMULTIPART_FORM_DATA:
begin
LMultipartFormData := TMultipartFormData.Create(False);
FRequestContentType := LMultipartFormData.MimeTypeHeader;
ABodyStream := LMultipartFormData.Stream;
end;
else
begin
ABodyStream := TStringStream.Create;
end;
end;
for LParam in AParamList do
begin
if (LParam.Kind = TRESTRequestParameterKind.pkGETorPOST) and not IsQueryParam(LParam, AContentType) or
(LParam.Kind in [TRESTRequestParameterKind.pkREQUESTBODY, TRESTRequestParameterKind.pkFile]) then
begin
if AContentType = TRESTContentType.ctMULTIPART_FORM_DATA then
begin
// Multipart
// For multipart names of body parameters are written - in contrast to WWWForm (see below)
if LParam.Stream <> nil then
LMultipartFormData.AddStream(LParam.Name, LParam.Stream, LParam.Value,
ContentTypeToString(LParam.ContentType))
else if LParam.Kind = TRESTRequestParameterKind.pkFile then
LMultipartFormData.AddFile(LParam.Name, LParam.Value,
ContentTypeToString(LParam.ContentType))
else
LMultipartFormData.AddField(LParam.Name, LParam.Value)
end
else if AContentType = TRESTContentType.ctAPPLICATION_X_WWW_FORM_URLENCODED then
begin
// WWWForm
// http://www.w3.org/MarkUp/html-spec/html-spec_8.html#SEC8.2.1
// Both Key and Value are escaped and URL encoded - by default
if not (TRESTRequestParameterOption.poDoNotEncode in LParam.Options) then
begin
LParamName := URIEncode(LParam.Name);
LParamValue := URIEncode(LParam.Value);
end
else
begin
LParamName := LParam.Name;
LParamValue := LParam.Value;
end;
// If this is a body parameter, then we are interested in its value only.
// In contrast to multipart its name is ignored that is (see above)
if LParam.Kind = TRESTRequestParameterKind.pkREQUESTBODY then
LParamString := LParamValue
else
LParamString := LParamName + '=' + LParamValue;
// Parameters are separated using an Apmersand,
// so if there is already something the stream, we need a separator first
if ABodyStream.Position > 0 then
TStringStream(ABodyStream).WriteString('&');
TStringStream(ABodyStream).WriteString(LParamString);
end
else
if LParam.Stream <> nil then
begin
FreeAndNil(ABodyStream);
ABodyStream := LParam.Stream;
ABodyStreamOwner := False;
end
else
begin
Assert(ABodyStream is TStringStream);
if TRESTRequestParameterOption.poDoNotEncode in LParam.Options then
TStringStream(ABodyStream).WriteString(LParam.FValue)
else
begin
LBuffer := TEncoding.UTF8.GetBytes(LParam.Value);
TStringStream(ABodyStream).WriteData(LBuffer, Length(LBuffer));
end;
end;
end;
end;
finally
LMultipartFormData.Free;
end;
end;
function TCustomRESTRequest.ExecuteAsync(ACompletionHandler: TCompletionHandler = nil; ASynchronized: boolean = True;
AFreeThread: boolean = True; ACompletionHandlerWithError: TCompletionHandlerWithError = nil): TRESTExecutionThread;
begin
Result := TRESTExecutionThread.Create(Execute, Self, ACompletionHandler,
ASynchronized, AFreeThread, ACompletionHandlerWithError);
end;
procedure TCustomRESTRequest.Execute;
var
LParamsList: TRESTRequestParameterArray;
LURL: string;
LResponseStream: TMemoryStream;
LContentType: TRESTContentType;
LBodyStream: TStream;
LBodyStreamOwner: Boolean;
LContent: string;
LCharSet: string;
LParam: TRESTRequestParameter;
LContentIsString: Boolean;
LEncoding: TEncoding;
LLowerContentType: string;
LMimeKind: TMimeTypes.TKind;
LExt: string;
begin
FExecutionPerformance.Start;
DoBeforeExecute;
// If no client then raise an exception
if FClient = nil then
raise ERESTException.Create(sNoClientAttached);
// If a response-object was attached to this response we will use it
// If no response exists yet, then one is created on the fly and will be managed
// otherwise we do create a new response-object and return a reference
// to it.
if FResponse = nil then
begin
FResponse := TCustomRESTResponse.Create(Self);
DoResponseChanged;
end;
FResponse.BeginUpdate;
try
if FClient.Authenticator <> nil then
FClient.Authenticator.Authenticate(Self);
if FBody.FParams.Count > 0 then
for LParam in FBody.FParams do
if LParam.Stream <> nil then
FParams.AddItem(LParam.FName, LParam.Stream, LParam.FKind,
LParam.Options, LParam.ContentType, ooApp)
else
FParams.AddItem(LParam.FName, LParam.Value, LParam.FKind,
LParam.Options, LParam.ContentType);
if FBody.FJSONTextWriter <> nil then
FBody.FJSONTextWriter.Close;
if (FBody.FJSONStream <> nil) and (FBody.FJSONStream.Size > 0) then
FParams.AddItem(sBody, FBody.FJSONStream, TRESTRequestParameterKind.pkREQUESTBODY,
[], TRESTContentType.ctAPPLICATION_JSON);
LParamsList := CreateUnionParameterList;
LContentType := ContentType(LParamsList);
FRequestContentType := ContentTypeToString(LContentType);
// Build the full request URL
LURL := GetFullURL;
DoApplyURLSegments(LParamsList, LURL);
// URL encoding BEFORE parameters are attached, which may bring their own encoding
if not URLAlreadyEncoded then
LURL := TURI.Create(LURL).Encode;
DoApplyCookieParams(LParamsList, LURL);
FClient.HTTPClient.Request.CustomHeaders.Clear;
DoApplyHeaderParams(LParamsList);
DoPrepareQueryString(LParamsList, LContentType, LURL);
// Set several default headers for handling content-types, encoding, acceptance etc.
FClient.Accept := Accept;
FClient.HandleRedirects := HandleRedirects;
// We always allow cookies. Many API's just send session cookies.
// Making that a configuration option is pointless
FClient.AllowCookies := True;
FClient.AcceptCharset := AcceptCharset;
FClient.AcceptEncoding := AcceptEncoding;
FClient.HTTPClient.ConnectTimeout := Timeout;
FClient.HTTPClient.ReadTimeout := Timeout;
LBodyStream := nil;
LBodyStreamOwner := True;
LResponseStream := nil;
try
if LContentType <> ctNone then
begin
// POST, PUT and PATCH requests typically include a body, so all relevant params
// go into a body stream. The body stream has to consider the actual content-type
// (wwwform vs. multipart).
DoPrepareRequestBody(LParamsList, LContentType, LBodyStream, LBodyStreamOwner);
FClient.ContentType := FRequestContentType;
end;
LResponseStream := TMemoryStream.Create;
FExecutionPerformance.PreProcessingDone;
try
case Method of
TRESTRequestMethod.rmGET:
FClient.HTTPClient.Get(LURL, LBodyStream, LResponseStream);
TRESTRequestMethod.rmPOST:
FClient.HTTPClient.Post(LURL, LBodyStream, LResponseStream);
TRESTRequestMethod.rmPUT:
FClient.HTTPClient.Put(LURL, LBodyStream, LResponseStream);
TRESTRequestMethod.rmDELETE:
FClient.HTTPClient.Delete(LURL, LBodyStream, LResponseStream);
TRESTRequestMethod.rmPATCH:
FClient.HTTPClient.Patch(LURL, LBodyStream, LResponseStream);
else
raise EInvalidOperation.Create(sUnknownRequestMethod);
end;
FExecutionPerformance.ExecutionDone;
LContentIsString := False;
LEncoding := nil;
try
LLowerContentType := LowerCase(Client.HTTPClient.Response.ContentType);
LCharSet := Client.HTTPClient.Response.CharSet;
if LCharSet <> '' then
LContentIsString := True
else
begin
TMimeTypes.Default.GetTypeInfo(LLowerContentType, LExt, LMimeKind);
// Skip if blank or 'raw'
if (FClient.FallbackCharsetEncoding <> '') and
not SameText(REST_NO_FALLBACK_CHARSET, FClient.FallbackCharsetEncoding) then
begin
// Skip some obvious binary types
if LMimeKind <> TMimeTypes.TKind.Binary then
begin
LEncoding := TEncoding.GetEncoding(FClient.FallbackCharsetEncoding);
LContentIsString := True;
end;
end
else
begin
// Even if no fallback, handle some obvious string types
if LMimeKind = TMimeTypes.TKind.Text then
LContentIsString := True;
end;
end;
if LContentIsString then
LContent := FClient.HTTPClient.Response.ContentAsString(LEncoding);
finally
LEncoding.Free;
end;
except
// any kind of server/protocol error
on E: EHTTPProtocolException do
begin
FExecutionPerformance.ExecutionDone;
// we keep measuring only for protocal errors, i.e. where
// the server actually answered, not for other exceptions.
LContent := E.ErrorMessage; // Full error description
// Fill RESTResponse with actual response data - error handler might want to access it
ProcessResponse(LURL, LResponseStream, LContent);
if (E.ErrorCode >= 500) and Client.RaiseExceptionOn500 then
Exception.RaiseOuterException(ERESTException.Create(E.Message));
HandleEvent(DoHTTPProtocolError);
end;
// Unknown error, might even be on the client side. raise it!
on E: Exception do
begin
// If Execute raises an Exception, then the developer should have look into the actual BaseException
Exception.RaiseOuterException(ERESTException.CreateFmt(sRESTRequestFailed, [E.Message]));
end;
end;
// Fill RESTResponse with actual response data
ProcessResponse(LURL, LResponseStream, LContent);
// Performance timers do not care about events or observers
FExecutionPerformance.PostProcessingDone;
// Eventhandlers AFTER Observers
HandleEvent(DoAfterExecute);
finally
FClient.Disconnect;
LResponseStream.Free;
if LBodyStreamOwner then
LBodyStream.Free;
end;
finally
FResponse.EndUpdate;
end;
end;
procedure TCustomRESTRequest.AddFile(const AName, AFileName: string; AContentType: TRESTContentType = TRESTContentType.ctNone);
begin
FParams.AddItem(AName, AFileName, TRESTRequestParameterKind.pkFile, [], AContentType);
end;
procedure TCustomRESTRequest.AddFile(const AFileName: string; AContentType: TRESTContentType = TRESTContentType.ctNone);
begin
AddFile(sFile, AFileName, AContentType);
end;
procedure TCustomRESTRequest.AddBody(const ABodyContent: string; AContentType: TRESTContentType = TRESTContentType.ctNone);
begin
FParams.AddBody(ABodyContent, AContentType);
end;
procedure TCustomRESTRequest.AddBody<T>(AObject: T);
begin
FParams.AddBody(AObject);
end;
function TCustomRESTRequest.AcceptIsStored: Boolean;
begin
Result := Accept <> sRequestDefaultAccept;
end;
function TCustomRESTRequest.AcceptCharSetIsStored: Boolean;
begin
Result := AcceptCharset <> sRequestDefaultAcceptCharset;
end;
procedure TCustomRESTRequest.AddAuthParameter(const AName, AValue: string; const AKind: TRESTRequestParameterKind;
const AOptions: TRESTRequestParameterOptions);
begin
AddParameter(AName, AValue, AKind, AOptions + [TRESTRequestParameterOption.poTransient]);
end;
procedure TCustomRESTRequest.AddBody(ABodyContent: TStream; AContentType: TRESTContentType = TRESTContentType.ctNone;
AOwnsStream: TRESTObjectOwnership = TRESTObjectOwnership.ooCopy);
begin
FParams.AddBody(ABodyContent, AContentType, AOwnsStream);
end;
procedure TCustomRESTRequest.AddBody(AObject: TJsonObject; AOwnsObject: TRESTObjectOwnership);
begin
FParams.AddBody(AObject, AOwnsObject);
end;
procedure TCustomRESTRequest.AddParameter(const AName, AValue: string);
begin
AddParameter(AName, AValue, TRESTRequestParameterKind.pkGETorPOST, []);
end;
procedure TCustomRESTRequest.AddParameter(const AName, AValue: string; const AKind: TRESTRequestParameterKind);
begin
AddParameter(AName, AValue, AKind, []);
end;
procedure TCustomRESTRequest.AddParameter(const AName, AValue: string; const AKind: TRESTRequestParameterKind;
const AOptions: TRESTRequestParameterOptions);
begin
// decide where to put the parameter to
if TRESTRequestParameterOption.poTransient in AOptions then
begin
if TransientParams.ParameterByName(AName) <> nil then
TransientParams.Delete(AName);
TransientParams.AddItem(AName, AValue, AKind, AOptions);
end
else
begin
if Params.ParameterByName(AName) <> nil then
Params.Delete(AName);
Params.AddItem(AName, AValue, AKind, AOptions);
end;
end;
procedure TCustomRESTRequest.AddParameter(const AName: string; AJsonObject: TJSONObject; AFreeJson: Boolean = True);
begin
try
Params.AddItem(AName, AJsonObject.ToString, TRESTRequestParameterKind.pkGETorPOST,
[], TRESTContentType.ctAPPLICATION_JSON);
finally
if AFreeJson then
AJsonObject.Free;
end;
end;
procedure TCustomRESTRequest.AddParameter(const AName: string;
AJsonObject: TJSONObject; AOwnsObject: TRESTObjectOwnership {= ooREST});
begin
AddParameter(AName, AJsonObject, AOwnsObject = ooREST);
end;
procedure TCustomRESTRequest.ClearBody;
var
i: Integer;
begin
for i := Params.Count - 1 downto 0 do
if Params.Items[i].Kind = TRESTRequestParameterKind.pkREQUESTBODY then
Params.Delete(i);
FBody.ClearBody;
end;
function TCustomRESTRequest.IsQueryParam(const AParam: TRESTRequestParameter;
AContentType: TRESTContentType): Boolean;
begin
Result :=
(AParam.Kind = TRESTRequestParameterKind.pkGETorPOST) and (
(Method in [TRESTRequestMethod.rmGET, TRESTRequestMethod.rmDELETE]) or
(Method in [TRESTRequestMethod.rmPOST, TRESTRequestMethod.rmPUT, TRESTRequestMethod.rmPATCH]) and
(AContentType = TRESTContentType.ctNone)) or
(AParam.Kind = TRESTRequestParameterKind.pkQUERY);
end;
function TCustomRESTRequest.ContentType(const AParamsArray: TRESTRequestParameterArray): TRESTContentType;
var
LParam: TRESTRequestParameter;
LNumBodyParams: Integer;
LNumPostGetParams: Integer;
LSpecificContentType: TRESTContentType;
begin
LNumBodyParams := 0;
LNumPostGetParams := 0;
LSpecificContentType := ctNone;
for LParam in AParamsArray do
begin
if (Method in [TRESTRequestMethod.rmGET, TRESTRequestMethod.rmDELETE]) and
not (LParam.Kind in [TRESTRequestParameterKind.pkREQUESTBODY,
TRESTRequestParameterKind.pkFILE]) then
Continue;
if LParam.Kind = TRESTRequestParameterKind.pkFILE then
begin
LSpecificContentType := TRESTContentType.ctMULTIPART_FORM_DATA;
Break;
end;
if LParam.ContentType <> ctNone then
LSpecificContentType := LParam.ContentType;
if LParam.Kind = TRESTRequestParameterKind.pkREQUESTBODY then
Inc(LNumBodyParams)
else if LParam.Kind = TRESTRequestParameterKind.pkGETorPOST then
Inc(LNumPostGetParams);
end;
// If there is a specific ContentType set in at least one of the params, then we use that one
if LSpecificContentType <> ctNone then
Result := LSpecificContentType
// "multipart" is neccessary if we have more than one
// body-parameter or body-parameters as well as post/get-parameters
// (wich should be quite unusual, but "multipart" is the only
// way to go in that situation) - otherwise we just do simple
// form-urlencoded to keep the request as small as possible
else if LNumBodyParams > 1 then
Result := TRESTContentType.ctMULTIPART_FORM_DATA
else if (LNumBodyParams > 0) and (LNumPostGetParams > 0) then
Result := TRESTContentType.ctMULTIPART_FORM_DATA
else if not (Method in [TRESTRequestMethod.rmGET, TRESTRequestMethod.rmDELETE]) or
(LNumBodyParams > 0) then
Result := TRESTContentType.ctAPPLICATION_X_WWW_FORM_URLENCODED
else
Result := TRESTContentType.ctNone;
end;
function TCustomRESTRequest.ContentType: TRESTContentType;
begin
Result := ContentType(CreateUnionParameterList);
end;
procedure TCustomRESTRequest.DoPrepareQueryString(const AParamList: TRESTRequestParameterArray;
AContentType: TRESTContentType; var AURL: string);
var
LParam: TRESTRequestParameter;
LName: string;
LValue: string;
LConcat: string;
function ExpandArray(const AValue, AListSep: string): string;
var
LValues: TArray<string>;
LValue: string;
i: Integer;
begin
LValues := AValue.Split([';'], TStringSplitOptions.None);
for i := 0 to High(LValues) do
begin
if i > 0 then
Result := Result + AListSep;
LValue := LValues[i];
if not (TRESTRequestParameterOption.poDoNotEncode in LParam.Options) then
LValue := TNetEncoding.URL.EncodeForm(LValue);
Result := Result + LValue;
end;
end;
begin
// the goal is to embedd all relevant params into the url.
for LParam in AParamList do
if IsQueryParam(LParam, AContentType) then
begin
LName := URIEncode(LParam.Name);
LValue := LParam.Value;
if poFlatArray in LParam.Options then
LValue := LName + '=' + ExpandArray(LValue, '&' + LName + '=')
else if poPHPArray in LParam.Options then
LValue := LName + '[]=' + ExpandArray(LValue, '&' + LName + '[]=')
else if poListArray in LParam.Options then
LValue := LName + '=' + ExpandArray(LValue, ',')
else
begin
if not (TRESTRequestParameterOption.poDoNotEncode in LParam.Options) then
LValue := TNetEncoding.URL.EncodeForm(LParam.Value);
LValue := LName + '=' + LValue;
end;
if Pos('?', AURL) = 0 then
LConcat := '?'
else
LConcat := '&';
AURL := AURL + LConcat + LValue;
end;
end;
function TCustomRESTRequest.GetClient: TCustomRESTClient;
begin
Result := FClient;
end;
function TCustomRESTRequest.GetExecutionPerformance: TExecutionPerformance;
begin
Result := FExecutionPerformance;
end;
function TCustomRESTRequest.GetFullURL: string;
var
LFullRes: string;
begin
if FClient <> nil then
Result := FClient.BaseURL
else
Result := '';
LFullRes := FullResource;
if LFullRes > '' then
begin
if not Result.EndsWith('/') and not (
LFullRes.StartsWith('/') or LFullRes.StartsWith('?') or LFullRes.StartsWith('#')) then
Result := Result + '/';
Result := Result + LFullRes;
end;
end;
function TCustomRESTRequest.GetFullRequestURL(AIncludeParams: Boolean): string;
var
AParamList: TRESTRequestParameterArray;
LContentType: TRESTContentType;
begin
Result := GetFullURL;
AParamList := CreateUnionParameterList;
DoApplyURLSegments(AParamList, Result);
if AIncludeParams then
begin
LContentType := ContentType(AParamList);
DoPrepareQueryString(AParamList, LContentType, Result);
end;
end;
function TCustomRESTRequest.GetFullResource: string;
begin
Result := Resource;
if (Resource <> '') and (ResourceSuffix <> '') then
begin
if Resource.EndsWith('/') then
Result := Resource.Substring(0, Resource.Length - 1)
else
Result := Resource;
if ResourceSuffix.StartsWith('/') then
Result := Resource + ResourceSuffix
else
Result := Resource + '/' + ResourceSuffix;
end
else if Resource <> '' then
Result := Resource
else if ResourceSuffix <> '' then
Result := ResourceSuffix;
end;
procedure TCustomRESTRequest.ProcessResponse(const AURL: string; AResponseStream: TMemoryStream; const AContent: string);
var
i: Integer;
LResponse: TRESTHTTP.IResponse;
LHeaders: TRESTHTTP.IHeaderList;
begin
// transfer the received data from the http-request to the rest-response
LResponse := FClient.HTTPClient.Response;
LHeaders := LResponse.Headers;
FResponse.ResetToDefaults;
FResponse.FullRequestURI := AURL;
FResponse.Server := LHeaders.Values['server'];
FResponse.ContentType := LResponse.ContentType;
FResponse.ContentEncoding := LResponse.ContentEncoding;
FResponse.StatusCode := FClient.HTTPClient.ResponseCode;
FResponse.StatusText := FClient.HTTPClient.ResponseText;
for i := 0 to LHeaders.Count - 1 do
FResponse.Headers.Add(LHeaders.Names[i] + '=' + LHeaders.Values[LHeaders.Names[i]]);
Response.SetContent(AContent);
Response.SetRawBytes(AResponseStream);
end;
function TCustomRESTRequest.GetMethod: TRESTRequestMethod;
begin
Result := FMethod;
end;
function TCustomRESTRequest.GetParams: TRESTRequestParameterList;
begin
Result := FParams;
end;
function TCustomRESTRequest.GetResource: string;
begin
Result := FResource;
end;
function TCustomRESTRequest.GetResponse: TCustomRESTResponse;
begin
Result := FResponse;
end;
function TCustomRESTRequest.GetTimeout: Integer;
begin
Result := FTimeout;
end;
procedure TCustomRESTRequest.HandleEvent(AEventHandler: TMethod);
begin
// Handle Synchronized if we are NOT already in the main thread
// NEVER call synchronize on the MainThread - that might shift the island!
if SynchronizedEvents and (System.MainThreadID <> TThread.CurrentThread.ThreadID) then
TThread.Synchronize(TThread.CurrentThread, AEventHandler)
else
AEventHandler;
end;
procedure TCustomRESTRequest.Loaded;
begin
inherited Loaded;
if FullResource <> '' then
if FAutoCreateParams then
// Can't delete parameters when expressions are executing
FParams.CreateURLSegmentsFromString(FullResource);
end;
function TCustomRESTRequest.MethodIsStored: Boolean;
begin
Result := Method <> DefaultRESTRequestMethod;
end;
procedure TCustomRESTRequest.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
if Operation = opRemove then
if AComponent = FClient then
FClient := nil
else if AComponent = FResponse then
FResponse := nil;
end;
procedure TCustomRESTRequest.ParameterListChanged;
begin
if NotifyList <> nil then
NotifyList.Notify(
procedure(ANotify: TNotify)
begin
ANotify.ParameterListChanged(Self);
end);
end;
procedure TCustomRESTRequest.ParameterValueChanged;
begin
PropertyValueChanged;
end;
procedure TCustomRESTRequest.PropertyValueChanged;
begin
if NotifyList <> nil then
NotifyList.Notify(
procedure(ANotify: TNotify)
begin
ANotify.PropertyValueChanged(Self);
end);
end;
procedure TCustomRESTRequest.ResetToDefaults;
begin
Method := DefaultRESTRequestMethod;
Resource := '';
ResourceSuffix := '';
Timeout := 30000; // Some servers may be slow. Esp if they just recycled and need to start up on their first request
Accept := sRequestDefaultAccept;
AcceptCharset := sRequestDefaultAcceptCharset;
HandleRedirects := True;
FExecutionPerformance.Clear;
FURLAlreadyEncoded := False;
FParams.Clear;
FTransientParams.Clear;
FBody.ClearBody;
if FClient <> nil then
FClient.ContentType := '';
if FResponse <> nil then
FResponse.ResetToDefaults;
// we intentionally do not reset "FAutoCreateParams"
end;
procedure TCustomRESTRequest.SetAccept(const AValue: string);
begin
if FAccept <> AValue then
begin
FAccept := AValue;
PropertyValueChanged;
end;
end;
procedure TCustomRESTRequest.SetAcceptCharset(const AValue: string);
begin
if FAcceptCharset <> AValue then
begin
FAcceptCharset := AValue;
PropertyValueChanged;
end;
end;
procedure TCustomRESTRequest.SetAcceptEncoding(const AValue: string);
begin
if FAcceptEncoding <> AValue then
begin
FAcceptEncoding := AValue;
PropertyValueChanged;
end;
end;
procedure TCustomRESTRequest.SetAutoCreateParams(const AValue: Boolean);
begin
if AValue <> FAutoCreateParams then
begin
FAutoCreateParams := AValue;
PropertyValueChanged;
// if this option gets activated, we can just
// start to create some params from the resource
if FAutoCreateParams then
FParams.CreateURLSegmentsFromString(FullResource);
end;
end;
procedure TCustomRESTRequest.SetClient(const AValue: TCustomRESTClient);
begin
if AValue <> FClient then
begin
if FClient <> nil then
FClient.RemoveFreeNotification(Self);
FClient := AValue;
if FClient <> nil then
FClient.FreeNotification(Self);
PropertyValueChanged;
end;
end;
procedure TCustomRESTRequest.SetHandleRedirects(const AValue: Boolean);
begin
if FHandleRedirects <> AValue then
begin
FHandleRedirects := AValue;
PropertyValueChanged;
end;
end;
procedure TCustomRESTRequest.SetMethod(const AValue: TRESTRequestMethod);
begin
if FMethod <> AValue then
begin
FMethod := AValue;
PropertyValueChanged;
end;
end;
procedure TCustomRESTRequest.SetParams(const AValue: TRESTRequestParameterList);
begin
FParams.Assign(AValue);
end;
procedure TCustomRESTRequest.SetResource(const AValue: string);
begin
if AValue <> FResource then
begin
FResource := AValue;
// resources should not begin with a slash
// but they may end with an slash
while StartsText('/', FResource) do
System.Delete(FResource, 1, 1);
if not (csLoading in ComponentState) then
begin
if FAutoCreateParams and not FPosting then
// Can't delete parameters when expressions are executing
FParams.CreateURLSegmentsFromString(FullResource);
PropertyValueChanged;
end;
end;
end;
procedure TCustomRESTRequest.SetResourceSuffix(const AValue: string);
begin
if AValue <> FResourceSuffix then
begin
FResourceSuffix := AValue;
// resources should not begin with a slash
// but they may end with an slash
while StartsText('/', FResourceSuffix) do
System.Delete(FResourceSuffix, 1, 1);
if not (csLoading in ComponentState) then
begin
if FAutoCreateParams and not FPosting then
// Can't delete parameters when expressions are executing
FParams.CreateURLSegmentsFromString(FullResource);
PropertyValueChanged;
end;
end;
end;
procedure TCustomRESTRequest.SetResponse(const AResponse: TCustomRESTResponse);
begin
if AResponse <> FResponse then
begin
DoResponseChanging;
if FResponse <> nil then
FResponse.RemoveFreeNotification(Self);
FResponse := AResponse;
if FResponse <> nil then
FResponse.FreeNotification(Self);
DoResponseChanged;
end;
end;
procedure TCustomRESTRequest.DoResponseChanging;
begin
//
end;
procedure TCustomRESTRequest.DoResponseChanged;
begin
//
end;
procedure TCustomRESTRequest.SetSynchronizedEvents(const AValue: Boolean);
begin
if FSynchronizedEvents <> AValue then
begin
FSynchronizedEvents := AValue;
PropertyValueChanged;
end;
end;
procedure TCustomRESTRequest.SetTimeout(const AValue: Integer);
begin
if AValue <> FTimeout then
begin
FTimeout := AValue;
PropertyValueChanged;
end;
end;
{ TRESTRequestAdapter }
procedure TRESTRequestAdapter.AddFields;
begin
AddPropertyFields;
AddParameterFields;
end;
procedure TRESTRequestAdapter.AddParameterFields;
procedure ClearParameterFields;
var
i: Integer;
begin
for i := Fields.Count - 1 downto 0 do
if (Fields[i] is TReadWriteField<string>) and (TReadWriteField<string>(Fields[i]).Persistent <> nil) then
Fields.Delete(i);
end;
procedure MakeParameterFieldNames(const ADictionary: TDictionary<string, TRESTRequestParameter>);
const
sPrefix = 'Params.';
var
i: Integer;
LParams: TRESTRequestParameterList;
LParam: TRESTRequestParameter;
LName: string;
LIndex: Integer;
LSuffix: string;
begin
Assert(ADictionary.Count = 0);
LParams := FRequest.Params;
for i := 0 to LParams.Count - 1 do
begin
LParam := LParams[i];
if TRESTRequestParameterOption.poTransient in LParam.Options then
// Skip authentication header, for example
Continue;
LName := LParam.Name;
if LName = '' then
LName := IntToStr(LParam.Index);
LName := sPrefix + LName;
LIndex := 1;
LSuffix := '';
while ADictionary.ContainsKey(LName + LSuffix) do
begin
LSuffix := IntToStr(LIndex);
Inc(LIndex);
end;
ADictionary.Add(LName + LSuffix, LParam);
end;
end;
procedure MakeParameterField(const AParam: TRESTRequestParameter; const AFieldName: string;
const AGetMemberObject: IGetMemberObject);
begin
CreateReadWriteField<string>(AFieldName, AGetMemberObject, TScopeMemberType.mtText,
function: string
begin
Result := AParam.Value;
end,
procedure(AValue: string)
begin
AParam.Value := AValue;
end, AParam); // Parameter is member of field
end;
var
LDictionary: TDictionary<string, TRESTRequestParameter>;
LPair: TPair<string, TRESTRequestParameter>;
LGetMemberObject: IGetMemberObject;
begin
CheckInactive;
ClearParameterFields;
if FRequest <> nil then
begin
LDictionary := TDictionary<string, TRESTRequestParameter>.Create;
try
MakeParameterFieldNames(LDictionary);
LGetMemberObject := TBindSourceAdapterGetMemberObject.Create(Self);
for LPair in LDictionary do
MakeParameterField(LPair.Value, LPair.Key, LGetMemberObject);
finally
LDictionary.Free;
end;
end;
end;
procedure TRESTRequestAdapter.AddPropertyFields;
procedure ClearPropertyFields;
var
i: Integer;
begin
for i := Fields.Count - 1 downto 0 do
if not (Fields[i] is TReadWriteField<string>) or (TReadWriteField<string>(Fields[i]).Persistent = nil) then
Fields.Delete(i);
end;
begin
CheckInactive;
ClearPropertyFields;
if FRequest <> nil then
CreatePropertyFields;
end;
procedure TRESTRequestAdapter.CreatePropertyFields;
const
sResource = 'Resource';
sResourceSuffix = 'ResourceSuffix';
var
LGetMemberObject: IGetMemberObject;
begin
LGetMemberObject := TBindSourceAdapterGetMemberObject.Create(Self);
CreateReadWriteField<string>(sResource, LGetMemberObject, TScopeMemberType.mtText,
function: string
begin
Result := FRequest.Resource;
end,
procedure(AValue: string)
begin
FRequest.Resource := AValue;
end);
CreateReadWriteField<string>(sResourceSuffix, LGetMemberObject, TScopeMemberType.mtText,
function: string
begin
Result := FRequest.ResourceSuffix;
end,
procedure(AValue: string)
begin
FRequest.ResourceSuffix := AValue;
end);
end;
constructor TRESTRequestAdapter.Create(AComponent: TComponent);
begin
inherited Create(AComponent);
FNotify := TNotify.Create(Self);
end;
destructor TRESTRequestAdapter.Destroy;
begin
inherited Destroy;
if FRequest <> nil then
if FRequest.NotifyList <> nil then
FRequest.NotifyList.RemoveNotify(FNotify);
FNotify.Free;
end;
function TRESTRequestAdapter.GetCanActivate: Boolean;
begin
Result := FRequest <> nil;
end;
procedure TRESTRequestAdapter.GetMemberNames(AList: TStrings);
var
LField: TBindSourceAdapterField;
begin
for LField in Fields do
if LField is TReadWriteField<string> then
// Provide object so that LiveBindings designer can select in designer when member is clicked
AList.AddObject(LField.MemberName, TReadWriteField<string>(LField).Persistent)
else
AList.Add(LField.MemberName);
end;
function TRESTRequestAdapter.GetSource: TBaseLinkingBindSource;
begin
Result := FRequest;
end;
procedure TRESTRequestAdapter.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
// clean up component-references
if Operation = opRemove then
if AComponent = FRequest then
Request := nil
end;
procedure TRESTRequestAdapter.DoChangePosting;
begin
if FRequest <> nil then
FRequest.FPosting := Posting;
end;
procedure TRESTRequestAdapter.ParameterListChanged;
begin
if (FRequest <> nil) and not (csLoading in FRequest.ComponentState) then
if Active and not Posting then
begin
// Force parameters to be recreated
Active := False;
Active := True;
end;
end;
procedure TRESTRequestAdapter.SetRequest(const ARequest: TCustomRESTRequest);
var
LActive: Boolean;
begin
if FRequest <> ARequest then
begin
if FRequest <> nil then
begin
if FRequest.NotifyList <> nil then
FRequest.NotifyList.RemoveNotify(FNotify);
FRequest.RemoveFreeNotification(Self);
end;
LActive := Active;
Active := False;
// Assert(FRequest = nil); // expect one-to-one request/adapter
FRequest := ARequest;
if FRequest <> nil then
begin
if FRequest.NotifyList <> nil then
FRequest.NotifyList.AddNotify(FNotify);
FRequest.FreeNotification(Self);
end;
if LActive and CanActivate then
Active := True;
end;
end;
{ TRESTRequestAdapter.TRequestNotify }
constructor TRESTRequestAdapter.TNotify.Create(const AAdapter: TRESTRequestAdapter);
begin
FAdapter := AAdapter;
end;
procedure TRESTRequestAdapter.TNotify.ParameterListChanged(Sender: TObject);
begin
if FAdapter <> nil then
FAdapter.ParameterListChanged;
end;
procedure TRESTRequestAdapter.TNotify.PropertyValueChanged(Sender: TObject);
begin
if FAdapter <> nil then
FAdapter.RefreshFields;
end;
{ TCustomRESTRequest.TNotify }
procedure TCustomRESTRequest.TNotify.ParameterListChanged(Sender: TObject);
begin
//
end;
{ TCustomRESTRequestBindSource }
function TCustomRESTRequestBindSource.CreateAdapter: TRESTComponentAdapter;
begin
FAdapter := CreateRequestAdapter;
Result := FAdapter;
end;
function TCustomRESTRequestBindSource.CreateRequestAdapter: TRESTRequestAdapter;
begin
Result := TRESTRequestAdapter.Create(Self);
end;
function TCustomRESTRequestBindSource.GetRequest: TCustomRESTRequest;
begin
Result := FAdapter.Request;
end;
procedure TCustomRESTRequestBindSource.SetRequest(const Value: TCustomRESTRequest);
begin
FAdapter.Request := Value;
end;
{ TCustomRESTResponse }
constructor TCustomRESTResponse.Create(AOwner: TComponent);
begin
FStatus.FResponse := Self;
// it is important to create the notify-list before
// calling the inherited constructor
FNotifyList := TNotifyList.Create;
FJSONNotifyList := TList<TNotifyEvent>.Create;
inherited Create(AOwner);
// if the owner is a form or a tdatamodule, we will iterate
// through all components and see if there's a request without
// a response. if there is, then we just assign ourself to it.
if RESTComponentIsDesigning(Self) then
AssignResponseToRESTRequests(Self);
FHeaders := TStringList.Create;
ResetToDefaults;
end;
function TCustomRESTResponse.CreateBindSource: TBaseObjectBindSource;
begin
FBindSource := TSubRESTResponseBindSource.Create(Self);
FBindSource.Name := 'BindSource'; { Do not localize }
FBindSource.SetSubComponent(True);
FBindSource.Response := Self;
Result := FBindSource;
end;
destructor TCustomRESTResponse.Destroy;
begin
FreeAndNil(FHeaders);
FreeAndNil(FNotifyList);
FreeAndNil(FJSONNotifyList);
FreeAndNil(FJSONValue);
FreeAndNil(FJSONTextReader);
FreeAndNil(FJSONStreamReader);
FreeAndNil(FJSONStream);
inherited Destroy;
end;
function TCustomRESTResponse.GetContent: string;
begin
Result := FContent;
end;
function TCustomRESTResponse.GetContentEncoding: string;
begin
Result := FContentEncoding;
end;
function TCustomRESTResponse.GetContentLength: cardinal;
begin
Result := Length(FRawBytes);
end;
function TCustomRESTResponse.GetContentType: string;
begin
Result := FContentType;
end;
function TCustomRESTResponse.GetErrorMessage: string;
begin
Result := FErrorMessage;
end;
function TCustomRESTResponse.GetFullRequestURI: string;
begin
Result := FFullRequestURI;
end;
function TCustomRESTResponse.GetHeaders: TStrings;
begin
Result := FHeaders;
end;
function TCustomRESTResponse.GetJSONValue: TJsonValue;
var
LTemp: Boolean;
begin
Result := nil;
if Content <> '' then
try
GetJSONResponse(Result, LTemp);
except
// This method ignores exceptions
end;
end;
function TCustomRESTResponse.HasJSONResponse: Boolean;
var
LJSONValue: TJSONValue;
begin
Result := FJSONValue <> nil;
if not Result then
begin
LJSONValue := TJSONObject.ParseJSONValue(Content);
try
Result := LJSONValue <> nil;
finally
LJSONValue.Free;
end;
end;
end;
function TCustomRESTResponse.HasResponseContent: Boolean;
begin
Result := ContentLength > 0;
end;
function TCustomRESTResponse.GetJSONReader: TJSONTextReader;
begin
if FJSONTextReader = nil then
begin
FJSONStream := TBytesStream.Create(RawBytes);
FJSONStreamReader := TStreamReader.Create(FJSONStream);
FJSONTextReader := TJsonTextReader.Create(FJSONStreamReader);
end;
Result := FJSONTextReader;
end;
procedure TCustomRESTResponse.GetJSONResponse(out AJSONValue: TJSONValue;
out AHasOwner: Boolean);
var
LJSONValue: TJsonValue;
LPathValue: TJSONValue;
begin
if FJSONValue = nil then
begin
if Content = '' then
raise EJSONValueError.Create(TJSONValueError.NoContent, sResponseContentIsEmpty);
LJSONValue := TJSONObject.ParseJSONValue(Content);
try
if LJSONValue = nil then
raise EJSONValueError.Create(TJSONValueError.NoJSON, sResponseContentIsNotJSON);
if (RootElement <> '') and (LJSONValue <> nil) then
if LJSONValue.TryGetValue<TJSONValue>(RootElement, LPathValue) then
begin
LPathValue.Owned := False; // Need to decouple form parent, to avoid memleak
LJsonValue.Free;
LJsonValue := LPathValue;
end
else
// Invalid path
raise EJSONValueError.Create(TJSONValueError.InvalidRootElement, Format(sResponseInvalidRootElement, [RootElement]));
except
LJSONValue.Free;
raise;
end;
FJSONValue := LJSONValue;
end;
AJSONValue := FJSONValue;
AHasOwner := True;
end;
function TCustomRESTResponse.GetJSONText: string;
begin
if JSONValue <> nil then
Result := JSONValue.Format
else
Result := '';
end;
function TCustomRESTResponse.GetServer: string;
begin
Result := FServer;
end;
function TCustomRESTResponse.GetSimpleValue(const AName: string; var AValue: string): Boolean;
var
LJSONObj: TJSONObject;
LJSONPair: TJSONPair;
begin
Result := False;
// plain text
if SameText(ContentType, CONTENTTYPE_TEXT_HTML) or SameText(ContentType, CONTENTTYPE_TEXT_PLAIN) then
begin
if ContainsText(Content, AName + '=') then
begin
AValue := Copy(Content, Pos(AName + '=', Content) + Length(AName) + 1, Length(Content));
if (Pos('&', AValue) > 0) then
AValue := Copy(AValue, 1, Pos('&', AValue) - 1);
Result := True;
end;
end
// Json
else if SameText(ContentType, CONTENTTYPE_APPLICATION_JSON) then
begin
LJSONObj := TJSONObject.ParseJSONValue(Content) as TJSONObject;
if LJSONObj <> nil then
begin
LJSONPair := LJSONObj.Get(AName);
if LJSONPair <> nil then
begin
AValue := LJSONPair.JSONValue.Value;
Result := True;
end;
LJSONObj.Free; // <-- the jsonobject will also free the jsonpair!
end;
end;
end;
function TCustomRESTResponse.GetStatus: TStatus;
begin
Result := FStatus;
end;
function TCustomRESTResponse.GetStatusCode: Integer;
begin
Result := FStatusCode;
end;
function TCustomRESTResponse.GetStatusText: string;
begin
Result := FStatusText;
end;
procedure TCustomRESTResponse.JSONValueChanged;
var
LNotifyEvent: TNotifyEvent;
begin
if IsUpdating then
Include(FUpdateOptions, TUpdateOption.JSONValueChanged)
else if (NotifyList <> nil) then
begin
NotifyList.Notify(
procedure(ANotify: TNotify)
begin
ANotify.JSONValueChanged(Self);
end);
for LNotifyEvent in FJSONNotifyList do
LNotifyEvent(Self);
end;
end;
function TCustomRESTResponse.IsUpdating: Boolean;
begin
Result := FUpdating > 0;
end;
procedure TCustomRESTResponse.AddJSONChangedEvent(const ANotify: TNotifyEvent);
begin
Assert(not FJSONNotifyList.Contains(ANotify));
if not FJSONNotifyList.Contains(ANotify) then
FJSONNotifyList.Add(ANotify);
end;
procedure TCustomRESTResponse.BeginUpdate;
begin
if not IsUpdating then
FUpdateOptions := [];
Inc(FUpdating);
end;
procedure TCustomRESTResponse.EndUpdate;
begin
if IsUpdating then
begin
Dec(FUpdating);
if not IsUpdating then
begin
if TUpdateOption.PropertyValueChanged in FUpdateOptions then
PropertyValueChanged;
if TUpdateOption.JSONValueChanged in FUpdateOptions then
JSONValueChanged;
FUpdateOptions := [];
end;
end;
end;
procedure TCustomRESTResponse.PropertyValueChanged;
begin
if IsUpdating then
Include(FUpdateOptions, TUpdateOption.PropertyValueChanged)
else if NotifyList <> nil then
NotifyList.Notify(
procedure(ANotify: TNotify)
begin
ANotify.PropertyValueChanged(Self);
end);
end;
procedure TCustomRESTResponse.RemoveJSONChangedEvent(
const ANotify: TNotifyEvent);
begin
Assert(FJSONNotifyList.Contains(ANotify));
FJSONNotifyList.Remove(ANotify);
end;
procedure TCustomRESTResponse.ResetToDefaults;
begin
BeginUpdate;
try
SetLength(FRawBytes, 0);
FContent := '';
ContentEncoding := '';
ContentType := '';
ErrorMessage := '';
FullRequestURI := '';
Server := '';
StatusCode := 0;
StatusText := '';
Headers.Clear;
FreeAndNil(FJSONValue);
// Content property changed
PropertyValueChanged;
FreeAndNil(FJSONTextReader);
FreeAndNil(FJSONStreamReader);
FreeAndNil(FJSONStream);
JSONValueChanged;
finally
EndUpdate;
end;
end;
procedure TCustomRESTResponse.SetContent(const AContent: string);
begin
FContent := AContent;
FJSONValue := nil;
// Content property changed
PropertyValueChanged;
JSONValueChanged;
end;
procedure TCustomRESTResponse.SetContentEncoding(const AValue: string);
begin
if AValue <> FContentEncoding then
begin
FContentEncoding := AValue;
PropertyValueChanged;
end;
end;
procedure TCustomRESTResponse.SetContentType(const AValue: string);
begin
if AValue <> FContentType then
begin
FContentType := AValue;
PropertyValueChanged;
end;
end;
procedure TCustomRESTResponse.SetErrorMessage(const AValue: string);
begin
if AValue <> FErrorMessage then
begin
FErrorMessage := AValue;
PropertyValueChanged;
end;
end;
procedure TCustomRESTResponse.SetFullRequestURI(const AValue: string);
begin
if AValue <> FFullRequestURI then
begin
FFullRequestURI := AValue;
PropertyValueChanged;
end;
end;
procedure TCustomRESTResponse.SetRawBytes(const AStream: TStream);
begin
SetLength(FRawBytes, AStream.Size);
AStream.Position := 0;
AStream.Read(FRawBytes, AStream.Size);
end;
procedure TCustomRESTResponse.SetRootElement(const AValue: string);
begin
if FRootElement <> AValue then
begin
FRootElement := AValue;
FreeAndNil(FJSONValue);
PropertyValueChanged;
JSONValueChanged;
end;
end;
procedure TCustomRESTResponse.SetServer(const AValue: string);
begin
if AValue <> FServer then
begin
FServer := AValue;
PropertyValueChanged;
end;
end;
procedure TCustomRESTResponse.SetStatusCode(const AValue: Integer);
begin
if AValue <> FStatusCode then
begin
FStatusCode := AValue;
PropertyValueChanged;
end;
end;
procedure TCustomRESTResponse.SetStatusText(const AValue: string);
begin
if AValue <> FStatusText then
begin
FStatusText := AValue;
PropertyValueChanged;
end;
end;
{ TCustomRESTClient }
constructor TCustomRESTClient.Create(const ABaseApiURL: string);
begin
// sometimes the order *IS* important.
// first we do create the notifylist,
// then we can call the inherited constructor.
FNotifyList := TNotifyList.Create;
inherited Create(nil);
FHttpClient := nil;
FParams := TRESTRequestParameterList.Create(Self);
FTransientParams := TRESTRequestParameterList.Create(Self);
ResetToDefaults;
// This calls CreateHTTPClient internally
BaseURL := ABaseApiURL;
end;
constructor TCustomRESTClient.Create(AOwner: TComponent);
begin
// sometimes the order *IS* important.
// first we do create the notifylist,
// then we can call the inherited constructor.
FNotifyList := TNotifyList.Create;
inherited Create(AOwner);
FHttpClient := nil;
FParams := TRESTRequestParameterList.Create(Self);
FTransientParams := TRESTRequestParameterList.Create(Self);
ResetToDefaults;
if AOwner is TCustomAuthenticator then
Authenticator := AOwner as TCustomAuthenticator
else if RESTComponentIsDesigning(Self) then
begin
Authenticator := RESTFindDefaultAuthenticator(Self);
AssignClientToRESTRequests(Self);
end;
end;
function TCustomRESTClient.CreateBindSource: TBaseObjectBindSource;
begin
FBindSource := TSubRESTClientBindSource.Create(Self);
FBindSource.Name := 'BindSource'; { Do not localize }
FBindSource.SetSubComponent(True);
FBindSource.Client := Self;
Result := FBindSource;
end;
destructor TCustomRESTClient.Destroy;
begin
FreeAndNil(FHttpClient);
FreeAndNil(FParams);
FreeAndNil(FTransientParams);
FAuthenticator := nil;
inherited Destroy;
FreeAndNil(FNotifyList);
end;
procedure TCustomRESTClient.Disconnect;
begin
// Do nothing
end;
procedure TCustomRESTClient.SetCookie(const ACookie, AURL: string);
begin
HTTPClient.AddServerCookie(ACookie, AURL);
end;
procedure TCustomRESTClient.AddParameter(const AName, AValue: string);
begin
AddParameter(AName, AValue, TRESTRequestParameterKind.pkGETorPOST, []);
end;
procedure TCustomRESTClient.AddParameter(const AName, AValue: string; const AKind: TRESTRequestParameterKind);
begin
AddParameter(AName, AValue, AKind, []);
end;
procedure TCustomRESTClient.AddAuthParameter(const AName, AValue: string; const AKind: TRESTRequestParameterKind;
const AOptions: TRESTRequestParameterOptions);
begin
AddParameter(AName, AValue, AKind, AOptions + [TRESTRequestParameterOption.poTransient]);
end;
procedure TCustomRESTClient.AddParameter(const AName, AValue: string; const AKind: TRESTRequestParameterKind;
const AOptions: TRESTRequestParameterOptions);
begin
// decide where to put the parameter to
if TRESTRequestParameterOption.poTransient in AOptions then
begin
if TransientParams.ParameterByName(AName) <> nil then
TransientParams.Delete(AName);
TransientParams.AddItem(AName, AValue, AKind, AOptions);
end
else
begin
if Params.ParameterByName(AName) <> nil then
Params.Delete(AName);
Params.AddItem(AName, AValue, AKind, AOptions);
end;
end;
procedure TCustomRESTClient.CreateHttpClient;
begin
FreeAndNil(FHttpClient);
FHttpClient := TRESTHTTP.Create;
// This is handled by default in THttpClient, but to be safe we do this here anyway
FHttpClient.AllowCookies := True;
end;
procedure TCustomRESTClient.DoHTTPProtocolError;
begin
if Assigned(FOnHTTPProtocolError) then
FOnHTTPProtocolError(Self);
end;
function TCustomRESTClient.GetAccept: string;
begin
Result := HTTPClient.Request.Accept;
end;
function TCustomRESTClient.GetAcceptCharset: string;
begin
if HTTPClient.Request <> nil then
Result := HTTPClient.Request.AcceptCharset
else
Result := '';
end;
function TCustomRESTClient.GetAcceptEncoding: string;
begin
if HTTPClient.Request <> nil then
Result := HTTPClient.Request.AcceptEncoding
else
Result := '';
end;
function TCustomRESTClient.GetAllowCookies: Boolean;
begin
if HTTPClient.Request <> nil then
Result := HTTPClient.AllowCookies
else
Result := False;
end;
function TCustomRESTClient.GetAuthenticator: TCustomAuthenticator;
begin
Result := FAuthenticator;
end;
function TCustomRESTClient.GetBaseURL: string;
begin
Result := FBaseURL;
end;
function TCustomRESTClient.GetContentType: string;
begin
if HTTPClient <> nil then
Result := HTTPClient.Request.ContentType
else
Result := '';
end;
function TCustomRESTClient.GetEntity<T>(const AResource: string): T;
var
LRequest: TRESTRequest;
begin
LRequest := TRESTRequest.Create(Self);
try
LRequest.Method := rmGET;
LRequest.Resource := AResource;
LRequest.Execute;
Result := T(LRequest.Response.JSONValue);
finally
LRequest.Free;
end;
end;
function TCustomRESTClient.GetEntityArray<T>(const AQuery: string): TArray<T>;
var
LList: TObjectList<T>;
i: Integer;
begin
LList := GetEntityList<T>(AQuery);
if LList = nil then
Exit(nil);
SetLength(Result, LList.Count);
for i := 0 to LList.Count - 1 do
Result[i] := LList[i];
end;
function TCustomRESTClient.GetEntityList<T>(const AResource: string): TObjectList<T>;
var
LResponse: string;
LJsonResponse: TJSONObject;
LResponseArray: TJSONArray;
i: Integer;
LItem: T;
LJSONObject: TJSONObject;
LRequest: TRESTRequest;
begin
Result := nil;
LRequest := TRESTRequest.Create(Self);
try
LRequest.Method := rmGET;
LRequest.Resource := AResource;
LRequest.Execute;
// Parse response as Json and try interpreting it as Array
LResponseArray := LRequest.Response.JSONValue as TJSONArray;
if LResponseArray <> nil then
begin
Result := TObjectList<T>.Create;
// The array's items are supposed to be representations of class <T>
for i := 0 to LResponseArray.Count - 1 do
begin
LJSONObject := LResponseArray.Items[i] as TJSONObject;
LItem := TJson.JsonToObject<T>(LJSONObject);
Result.Add(LItem);
end;
end
else
raise ERESTException.CreateFmt(sResponseDidNotReturnArray, [T.Classname]);
finally
LRequest.Free;
end;
end;
function TCustomRESTClient.GetFallbackCharsetEncoding: string;
begin
Result := FFallbackCharsetEncoding;
end;
function TCustomRESTClient.GetHandleRedirects: Boolean;
begin
if HTTPClient <> nil then
Result := HTTPClient.HandleRedirects
else
Result := False;
end;
function TCustomRESTClient.GetHttpClient: TRESTHTTP;
begin
Result := FHttpClient;
end;
function TCustomRESTClient.GetOnValidateCertificate: TValidateCertificateEvent;
begin
Result := FHttpClient.OnValidateCertificate;
end;
function TCustomRESTClient.GetParams: TRESTRequestParameterList;
begin
Result := FParams;
end;
function TCustomRESTClient.GetProxyPassword: string;
begin
Result := FHttpClient.ProxyParams.ProxyPassword;
end;
function TCustomRESTClient.GetProxyPort: Integer;
begin
Result := FHttpClient.ProxyParams.ProxyPort;
end;
function TCustomRESTClient.GetProxyServer: string;
begin
Result := FHttpClient.ProxyParams.ProxyServer;
end;
function TCustomRESTClient.GetProxyUsername: string;
begin
Result := FHttpClient.ProxyParams.ProxyUsername;
end;
function TCustomRESTClient.GetUserAgent: string;
begin
if HTTPClient.Request <> nil then
Result := HTTPClient.Request.UserAgent
else
Result := '';
end;
procedure TCustomRESTClient.HandleEvent(AEventHandler: TMethod);
begin
// Handle Synchronized if we are NOT already in the main thread
// NEVER call synchronize on the MainThread - that might shift the island!
if SynchronizedEvents and (System.MainThreadID <> TThread.CurrentThread.ThreadID) then
TThread.Synchronize(TThread.CurrentThread, AEventHandler)
else
AEventHandler;
end;
function TCustomRESTClient.FallbackCharsetEncodingIsStored: Boolean;
begin
Result := sDefaultFallbackCharSetEncoding <> FallbackCharsetEncoding;
end;
function TCustomRESTClient.PostEntity<T>(const AResource: string; AEntity: T): TJSONObject;
var
LRequest: TRESTRequest;
begin
LRequest := TRESTRequest.Create(Self);
try
LRequest.Method := rmPOST;
LRequest.Resource := AResource;
LRequest.AddBody(AEntity);
LRequest.Execute;
if LRequest.Response.JSONValue <> nil then
Result := LRequest.Response.JSONValue as TJSONObject;
finally
LRequest.Free;
end;
end;
procedure TCustomRESTClient.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
if Operation = opRemove then
if AComponent = FAuthenticator then
FAuthenticator := nil;
end;
procedure TCustomRESTClient.ParameterListChanged;
begin
if NotifyList <> nil then
NotifyList.Notify(
procedure(ANotify: TNotify)
begin
ANotify.ParameterListChanged(Self);
end);
end;
procedure TCustomRESTClient.ParameterValueChanged;
begin
PropertyValueChanged;
end;
procedure TCustomRESTClient.PropertyValueChanged;
begin
if NotifyList <> nil then
NotifyList.Notify(
procedure(ANotify: TNotify)
begin
ANotify.PropertyValueChanged(Self);
end);
end;
procedure TCustomRESTClient.ResetToDefaults;
begin
CreateHttpClient;
BaseURL := '';
ProxyServer := '';
ProxyPort := 0;
ProxyUsername := '';
ProxyPassword := '';
UserAgent := sDefaultUserAgent;
FallbackCharsetEncoding := sDefaultFallbackCharSetEncoding;
FSynchronizedEvents := True;
FRaiseExceptionOn500 := True;
FAutoCreateParams := True;
FParams.Clear;
FTransientParams.Clear;
end;
procedure TCustomRESTClient.SetAccept(const AValue: string);
begin
if HTTPClient.Request.Accept <> AValue then
begin
HTTPClient.Request.Accept := AValue;
PropertyValueChanged;
end;
end;
procedure TCustomRESTClient.SetAcceptCharset(const AValue: string);
begin
if HTTPClient.Request <> nil then
HTTPClient.Request.AcceptCharset := AValue;
end;
procedure TCustomRESTClient.SetAcceptEncoding(const AValue: string);
begin
if HTTPClient <> nil then
HTTPClient.Request.AcceptEncoding := AValue;
end;
procedure TCustomRESTClient.SetAllowCookies(const AValue: Boolean);
begin
if HTTPClient <> nil then
HTTPClient.AllowCookies := AValue;
end;
procedure TCustomRESTClient.SetAuthenticator(const AValue: TCustomAuthenticator);
begin
if AValue <> FAuthenticator then
begin
if FAuthenticator <> nil then
FAuthenticator.RemoveFreeNotification(Self);
FAuthenticator := AValue;
if FAuthenticator <> nil then
FAuthenticator.FreeNotification(Self);
PropertyValueChanged;
end;
end;
procedure TCustomRESTClient.SetAutoCreateParams(const AValue: Boolean);
begin
if AValue <> FAutoCreateParams then
begin
FAutoCreateParams := AValue;
PropertyValueChanged;
// if this option gets activated, we can just
// start to create some params from the resource
if FAutoCreateParams then
FParams.CreateURLSegmentsFromString(FBaseURL);
end;
end;
procedure TCustomRESTClient.SetBaseURL(const AValue: string);
var
LOldValue: string;
begin
if (AValue <> FBaseURL) or (AValue = '') then
begin
LOldValue := FBaseURL;
FBaseURL := TURI.FixupForREST(AValue);
if FAutoCreateParams and not FPosting then
// Can't delete parameters when expressions are executing
FParams.CreateURLSegmentsFromString(FBaseURL);
// This is handled by default in THttpClient, but to be safe we do this here anyway
PropertyValueChanged;
end;
end;
procedure TCustomRESTClient.SetContentType(const AValue: string);
begin
if HTTPClient <> nil then
HTTPClient.Request.ContentType := AValue;
end;
procedure TCustomRESTClient.SetFallbackCharsetEncoding(const AValue: string);
begin
if AValue <> FFallbackCharsetEncoding then
begin
FFallbackCharsetEncoding := AValue;
PropertyValueChanged;
end;
end;
procedure TCustomRESTClient.SetHandleRedirects(const AValue: Boolean);
begin
if HTTPClient <> nil then
HTTPClient.HandleRedirects := AValue;
end;
procedure TCustomRESTClient.SetHTTPHeader(const AName, AValue: string);
begin
HTTPClient.Request.CustomHeaders.Values[AName] := AValue;
end;
procedure TCustomRESTClient.SetOnValidateCertificate(
const Value: TValidateCertificateEvent);
begin
FHttpClient.OnValidateCertificate := Value;
end;
procedure TCustomRESTClient.SetParams(const AValue: TRESTRequestParameterList);
begin
FParams.Assign(AValue);
end;
procedure TCustomRESTClient.SetProxyPassword(const AValue: string);
begin
if AValue <> FHttpClient.ProxyParams.ProxyPassword then
begin
FHttpClient.ProxyParams.ProxyPassword := AValue;
PropertyValueChanged;
end;
end;
procedure TCustomRESTClient.SetProxyPort(const AValue: Integer);
begin
if AValue <> FHttpClient.ProxyParams.ProxyPort then
begin
FHttpClient.ProxyParams.ProxyPort := AValue;
PropertyValueChanged;
end;
end;
procedure TCustomRESTClient.SetProxyServer(const AValue: string);
begin
if AValue <> FHttpClient.ProxyParams.ProxyServer then
begin
FHttpClient.ProxyParams.ProxyServer := AValue;
PropertyValueChanged;
end;
end;
procedure TCustomRESTClient.SetProxyUsername(const AValue: string);
begin
if AValue <> FHttpClient.ProxyParams.ProxyUsername then
begin
FHttpClient.ProxyParams.ProxyUsername := AValue;
PropertyValueChanged;
end;
end;
procedure TCustomRESTClient.SetSynchronizedEvents(const AValue: Boolean);
begin
if AValue <> FSynchronizedEvents then
begin
FSynchronizedEvents := AValue;
PropertyValueChanged;
end;
end;
procedure TCustomRESTClient.SetUserAgent(const AValue: string);
begin
if HTTPClient.Request <> nil then
if AValue <> HTTPClient.Request.UserAgent then
begin
HTTPClient.Request.UserAgent := AValue;
PropertyValueChanged;
end;
end;
function TCustomRESTClient.UserAgentIsStored: Boolean;
begin
Result := UserAgent <> sDefaultUserAgent;
end;
function TCustomRESTClient.GetRedirectsWithGET: THTTPRedirectsWithGET;
begin
Result := HTTPClient.RedirectsWithGET;
end;
function TCustomRESTClient.GetSecureProtocols: THTTPSecureProtocols;
begin
Result := HTTPClient.SecureProtocols;
end;
function TCustomRESTClient.GetNeedClientCertificateEvent: TNeedClientCertificateEvent;
begin
Result := HTTPClient.OnNeedClientCertificate;
end;
function TCustomRESTClient.GetAuthEvent: TCredentialsStorage.TCredentialAuthevent;
begin
Result := HTTPClient.OnAuthEvent;
end;
procedure TCustomRESTClient.SetRedirectsWithGET(const AValue: THTTPRedirectsWithGET);
begin
HTTPClient.RedirectsWithGET := AValue;
end;
procedure TCustomRESTClient.SetSecureProtocols(const AValue: THTTPSecureProtocols);
begin
HTTPClient.SecureProtocols := AValue;
end;
procedure TCustomRESTClient.SetNeedClientCertificateEvent(const AValue: TNeedClientCertificateEvent);
begin
HTTPClient.OnNeedClientCertificate := AValue;
end;
procedure TCustomRESTClient.SetAuthEvent(const AValue: TCredentialsStorage.TCredentialAuthevent);
begin
HTTPClient.OnAuthEvent := AValue;
end;
{ TCustomAuthenticator }
procedure TCustomAuthenticator.Authenticate(ARequest: TCustomRESTRequest);
var
LDone: Boolean;
begin
LDone := False;
if Assigned(FOnAuthenticate) then
FOnAuthenticate(ARequest, LDone);
if not LDone then
begin
Assert(Assigned(ARequest));
DoAuthenticate(ARequest);
end;
end;
constructor TCustomAuthenticator.Create(AOwner: TComponent);
begin
// sometimes the order *IS* important.
// first we do create the notifylist,
// then we can call the inherited constructor.
FNotifyList := TNotifyList.Create;
inherited Create(AOwner);
if RESTComponentIsDesigning(Self) then
AssignAuthenticatorToRESTClients(Self);
end;
destructor TCustomAuthenticator.Destroy;
begin
inherited Destroy;
FreeAndNil(FNotifyList);
end;
procedure TCustomAuthenticator.PropertyValueChanged;
begin
if NotifyList <> nil then
NotifyList.Notify(
procedure(ANotify: TNotify)
begin
ANotify.PropertyValueChanged(Self);
end);
end;
procedure TCustomAuthenticator.ResetToDefaults;
begin
// nothing here
// Do NOT delete an assigned OnAuthenticate event!
end;
{ TRESTAuthenticatorAdapter }
procedure TRESTAuthenticatorAdapter<T>.SetAuthenticator(const AAuthenticator: T);
var
LActive: Boolean;
begin
if FAuthenticator <> AAuthenticator then
begin
DoAuthenticatorChanging;
if FAuthenticator <> nil then
FAuthenticator.RemoveFreeNotification(Self);
LActive := Active;
Active := False;
FAuthenticator := AAuthenticator;
DoAuthenticatorChanged;
if FAuthenticator <> nil then
FAuthenticator.FreeNotification(Self);
if LActive and CanActivate then
Active := True;
end;
end;
procedure TRESTAuthenticatorAdapter<T>.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
// clean up component-references
if Operation = opRemove then
if AComponent = TComponent(FAuthenticator) then
Authenticator := nil
end;
constructor TRESTAuthenticatorAdapter<T>.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FNotify := TNotify.Create(Self);
end;
destructor TRESTAuthenticatorAdapter<T>.Destroy;
begin
FreeAndNil(FNotify);
inherited Destroy;
end;
procedure TRESTAuthenticatorAdapter<T>.DoAuthenticatorChanged;
begin
if Authenticator <> nil then
if Authenticator.NotifyList <> nil then
Authenticator.NotifyList.AddNotify(FNotify);
end;
procedure TRESTAuthenticatorAdapter<T>.DoAuthenticatorChanging;
begin
if Authenticator <> nil then
if Authenticator.NotifyList <> nil then
Authenticator.NotifyList.RemoveNotify(FNotify);
end;
function TRESTAuthenticatorAdapter<T>.GetCanActivate: Boolean;
begin
Result := FAuthenticator <> nil;
end;
function TRESTAuthenticatorAdapter<T>.GetSource: TBaseLinkingBindSource;
begin
Result := FAuthenticator;
end;
{ TRESTAuthenticatorBindSource }
function TRESTAuthenticatorBindSource<T>.CreateAdapter: TRESTComponentAdapter;
begin
FAdapter := CreateAdapterT;
Result := FAdapter;
end;
function TRESTAuthenticatorBindSource<T>.CreateAdapterT: TRESTAuthenticatorAdapter<T>;
begin
Result := TRESTAuthenticatorAdapter<T>.Create(Self);
end;
function TRESTAuthenticatorBindSource<T>.GetAuthenticator: TCustomAuthenticator;
begin
Result := FAdapter.Authenticator;
end;
procedure TRESTAuthenticatorBindSource<T>.SetAuthenticator(const Value: TCustomAuthenticator);
begin
FAdapter.Authenticator := T(Value);
end;
{ TCustomRESTResponseBindSource }
function TCustomRESTResponseBindSource.CreateAdapter: TRESTComponentAdapter;
begin
FAdapter := TRESTResponseAdapter.Create(Self);
Result := FAdapter;
end;
function TCustomRESTResponseBindSource.GetResponse: TCustomRESTResponse;
begin
Result := FAdapter.Response;
end;
procedure TCustomRESTResponseBindSource.SetResponse(const Value: TCustomRESTResponse);
begin
FAdapter.Response := Value;
end;
{ TRESTResponseAdapter }
procedure TRESTResponseAdapter.SetResponse(const AResponse: TCustomRESTResponse);
var
LActive: Boolean;
begin
if FResponse <> AResponse then
begin
if FResponse <> nil then
begin
if FResponse.NotifyList <> nil then
FResponse.NotifyList.RemoveNotify(FNotify);
FResponse.RemoveFreeNotification(Self);
end;
LActive := Active;
Active := False;
FResponse := AResponse;
if FResponse <> nil then
begin
if FResponse.NotifyList <> nil then
FResponse.NotifyList.AddNotify(FNotify);
FResponse.FreeNotification(Self);
end;
if LActive and CanActivate then
Active := True;
end;
end;
procedure TRESTResponseAdapter.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
// clean up component-references
if Operation = opRemove then
if AComponent = FResponse then
Response := nil
end;
constructor TRESTResponseAdapter.Create(AComponent: TComponent);
begin
inherited Create(AComponent);
FNotify := TNotify.Create(Self);
end;
destructor TRESTResponseAdapter.Destroy;
begin
inherited Destroy;
if FResponse <> nil then
if FResponse.NotifyList <> nil then
FResponse.NotifyList.RemoveNotify(FNotify);
FNotify.Free;
end;
procedure TRESTResponseAdapter.AddFields;
begin
AddPropertyFields;
end;
procedure TRESTResponseAdapter.AddPropertyFields;
const
sContent = 'Content';
sContentType = 'ContentType';
sContentLength = 'ContentLength'; // Integer
sContentEncoding = 'ContentEncoding';
sErrorMessage = 'ErrorMessage';
sFullRequestURI = 'FullRequestURI'; // read only
sRootElement = 'RootElement';
sServer = 'Server';
sStatusCode = 'StatusCode'; // Integer
sStatusText = 'StatusText';
sHeaders = 'Headers';
sJSONValue = 'JSONValue';
sJSONText = 'JSONText';
var
LGetMemberObject: IGetMemberObject;
begin
CheckInactive;
ClearFields;
if FResponse <> nil then
begin
LGetMemberObject := TBindSourceAdapterGetMemberObject.Create(Self);
CreateReadOnlyField<string>(sContent, LGetMemberObject, TScopeMemberType.mtText,
function: string
begin
Result := FResponse.Content;
end);
CreateReadOnlyField<string>(sContentType, LGetMemberObject, TScopeMemberType.mtText,
function: string
begin
Result := FResponse.ContentType;
end);
CreateReadOnlyField<Integer>(sContentLength, LGetMemberObject, TScopeMemberType.mtInteger,
function: Integer
begin
Result := FResponse.ContentLength;
end);
CreateReadOnlyField<string>(sContentEncoding, LGetMemberObject, TScopeMemberType.mtText,
function: string
begin
Result := FResponse.ContentEncoding;
end);
CreateReadOnlyField<string>(sErrorMessage, LGetMemberObject, TScopeMemberType.mtText,
function: string
begin
Result := FResponse.ErrorMessage;
end);
CreateReadOnlyField<string>(sFullRequestURI, LGetMemberObject, TScopeMemberType.mtText,
function: string
begin
Result := FResponse.FullRequestURI;
end);
CreateReadWriteField<string>(sRootElement, LGetMemberObject, TScopeMemberType.mtText,
function: string
begin
Result := FResponse.RootElement;
end,
procedure(AValue: string)
begin
FResponse.RootElement := AValue;
end);
CreateReadOnlyField<string>(sServer, LGetMemberObject, TScopeMemberType.mtText,
function: string
begin
Result := FResponse.Server;
end);
CreateReadOnlyField<Integer>(sStatusCode, LGetMemberObject, TScopeMemberType.mtInteger,
function: Integer
begin
Result := FResponse.StatusCode;
end);
CreateReadOnlyField<string>(sStatusText, LGetMemberObject, TScopeMemberType.mtText,
function: string
begin
Result := FResponse.StatusText;
end);
CreateReadOnlyField<TStrings>(sHeaders, LGetMemberObject, TScopeMemberType.mtMemo,
function: TStrings
begin
Result := FResponse.Headers;
end);
CreateReadOnlyField<TJsonValue>(sJSONValue, LGetMemberObject, TScopeMemberType.mtObject,
function: TJsonValue
begin
Result := FResponse.JSONValue;
end);
CreateReadOnlyField<string>(sJSONText, LGetMemberObject, TScopeMemberType.mtText,
function: string
begin
Result := FResponse.JSONText;
end);
end;
end;
function TRESTResponseAdapter.GetCanActivate: Boolean;
begin
Result := FResponse <> nil;
end;
function TRESTResponseAdapter.GetSource: TBaseLinkingBindSource;
begin
Result := FResponse;
end;
{ TRESTResponseAdapter.TNotify }
constructor TRESTResponseAdapter.TNotify.Create(const AAdapter: TRESTResponseAdapter);
begin
FAdapter := AAdapter;
end;
procedure TRESTResponseAdapter.TNotify.PropertyValueChanged(Sender: TObject);
begin
if FAdapter <> nil then
FAdapter.RefreshFields;
end;
{ TRESTClientAdapter }
procedure TRESTClientAdapter.SetClient(const AClient: TCustomRESTClient);
var
LActive: Boolean;
begin
if FClient <> AClient then
begin
if FClient <> nil then
begin
if FClient.NotifyList <> nil then
FClient.NotifyList.RemoveNotify(FNotify);
FClient.RemoveFreeNotification(Self);
end;
LActive := Active;
Active := False;
FClient := AClient;
if FClient <> nil then
begin
if FClient.NotifyList <> nil then
FClient.NotifyList.AddNotify(FNotify);
FClient.FreeNotification(Self);
end;
if LActive and CanActivate then
Active := True;
end;
end;
procedure TRESTClientAdapter.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
// clean up component-references
if Operation = opRemove then
if AComponent = FClient then
Client := nil
end;
procedure TRESTClientAdapter.ParameterListChanged;
begin
if (FClient <> nil) and not (csLoading in FClient.ComponentState) then
if Active and not Posting then
begin
// Force parameters to be recreated
Active := False;
Active := True;
end;
end;
constructor TRESTClientAdapter.Create(AComponent: TComponent);
begin
inherited Create(AComponent);
FNotify := TNotify.Create(Self);
end;
destructor TRESTClientAdapter.Destroy;
begin
inherited Destroy;
if FClient <> nil then
if FClient.NotifyList <> nil then
FClient.NotifyList.RemoveNotify(FNotify);
FNotify.Free;
end;
procedure TRESTClientAdapter.DoChangePosting;
begin
if FClient <> nil then
FClient.FPosting := Posting;
end;
procedure TRESTClientAdapter.AddFields;
begin
AddPropertyFields;
AddParameterFields;
end;
procedure TRESTClientAdapter.AddParameterFields;
procedure ClearParameterFields;
var
i: Integer;
begin
for i := Fields.Count - 1 downto 0 do
if (Fields[i] is TReadWriteField<string>) and
(TReadWriteField<string>(Fields[i]).Persistent <> nil) then
Fields.Delete(i);
end;
procedure MakeParameterFieldNames(const ADictionary: TDictionary<string, TRESTRequestParameter>);
const
sPrefix = 'Params.';
var
i: Integer;
LParams: TRESTRequestParameterList;
LParam: TRESTRequestParameter;
LName: string;
LIndex: Integer;
LSuffix: string;
begin
Assert(ADictionary.Count = 0);
LParams := FClient.Params;
for i := 0 to LParams.Count - 1 do
begin
LParam := LParams[i];
if TRESTRequestParameterOption.poTransient in LParam.Options then
// Skip authentication header, for example
Continue;
LName := LParam.Name;
if LName = '' then
LName := IntToStr(LParam.Index);
LName := sPrefix + LName;
LIndex := 1;
LSuffix := '';
while ADictionary.ContainsKey(LName + LSuffix) do
begin
LSuffix := IntToStr(LIndex);
Inc(LIndex);
end;
ADictionary.Add(LName + LSuffix, LParam);
end;
end;
procedure MakeParameterField(const AParam: TRESTRequestParameter; const AFieldName: string;
const AGetMemberObject: IGetMemberObject);
begin
CreateReadWriteField<string>(AFieldName, AGetMemberObject, TScopeMemberType.mtText,
function: string
begin
Result := AParam.Value;
end,
procedure(AValue: string)
begin
AParam.Value := AValue;
end, AParam); // Parameter is member of field
end;
var
LDictionary: TDictionary<string, TRESTRequestParameter>;
LPair: TPair<string, TRESTRequestParameter>;
LGetMemberObject: IGetMemberObject;
begin
CheckInactive;
ClearParameterFields;
if FClient <> nil then
begin
LDictionary := TDictionary<string, TRESTRequestParameter>.Create;
try
MakeParameterFieldNames(LDictionary);
LGetMemberObject := TBindSourceAdapterGetMemberObject.Create(Self);
for LPair in LDictionary do
MakeParameterField(LPair.Value, LPair.Key, LGetMemberObject);
finally
LDictionary.Free;
end;
end;
end;
procedure TRESTClientAdapter.AddPropertyFields;
const
sBaseURL = 'BaseURL';
var
LGetMemberObject: IGetMemberObject;
begin
CheckInactive;
ClearFields;
if FClient <> nil then
begin
LGetMemberObject := TBindSourceAdapterGetMemberObject.Create(Self);
CreateReadWriteField<string>(sBaseURL, LGetMemberObject, TScopeMemberType.mtText,
function: string
begin
Result := FClient.BaseURL;
end,
procedure(AValue: string)
begin
FClient.BaseURL := AValue;
end);
end;
end;
function TRESTClientAdapter.GetCanActivate: Boolean;
begin
Result := FClient <> nil;
end;
procedure TRESTClientAdapter.GetMemberNames(AList: TStrings);
var
LField: TBindSourceAdapterField;
begin
for LField in Fields do
if LField is TReadWriteField<string> then
// Provide object so that LiveBindings designer can select in designer when member is clicked
AList.AddObject(LField.MemberName, TReadWriteField<string>(LField).Persistent)
else
AList.Add(LField.MemberName);
end;
function TRESTClientAdapter.GetSource: TBaseLinkingBindSource;
begin
Result := FClient;
end;
{ TCustomRESTClient.TNotify }
procedure TCustomRESTClient.TNotify.ParameterListChanged(Sender: TObject);
begin
//
end;
{ TCustomRESTClientBindSource }
function TCustomRESTClientBindSource.CreateAdapter: TRESTComponentAdapter;
begin
FAdapter := TRESTClientAdapter.Create(Self);
Result := FAdapter;
end;
function TCustomRESTClientBindSource.GetClient: TCustomRESTClient;
begin
Result := FAdapter.Client;
end;
procedure TCustomRESTClientBindSource.SetClient(const AValue: TCustomRESTClient);
begin
FAdapter.Client := AValue;
end;
{ TRESTClientAdapter.TNotify }
constructor TRESTClientAdapter.TNotify.Create(const AAdapter: TRESTClientAdapter);
begin
FAdapter := AAdapter;
end;
procedure TRESTClientAdapter.TNotify.ParameterListChanged(Sender: TObject);
begin
if FAdapter <> nil then
FAdapter.ParameterListChanged;
end;
procedure TRESTClientAdapter.TNotify.PropertyValueChanged(Sender: TObject);
begin
if FAdapter <> nil then
FAdapter.RefreshFields;
end;
{ TCustomRESTResponse.EJSONValueError }
constructor TCustomRESTResponse.EJSONValueError.Create(AError: TJSONValueError;
const AMessage: string);
begin
inherited Create(AMessage);
FError := AError;
end;
{ TDownloadURL }
class procedure TDownloadURL.DownloadRawBytes(const AURL: string; const AStream: TStream);
var
LRequest: TRESTRequest;
LClient: TRESTClient;
LPosition: Integer;
begin
LClient := TRESTClient.Create(AUrl);
try
LRequest := TRESTRequest.Create(LClient);
LClient.FallbackCharsetEncoding := REST_NO_FALLBACK_CHARSET;
LRequest.SynchronizedEvents := False;
LRequest.Execute;
CheckForError(LRequest.Response);
LPosition := AStream.Position;
AStream.Write(LRequest.Response.RawBytes, 0, Length(LRequest.Response.RawBytes));
AStream.Position := LPosition;
finally
LClient.Free;
end;
end;
class procedure TDownloadURL.CheckForError(const AResponse: TCustomRESTResponse);
begin
if AResponse.StatusCode >= 300 then
raise ERequestError.Create(AResponse.StatusCode, AResponse.StatusText, AResponse.Content);
end;
{ TCustomRESTResponse.TStatus }
function TCustomRESTResponse.TStatus.ClientError: Boolean;
begin
Result := (FResponse.StatusCode >= 400) and (FResponse.StatusCode < 500);
end;
function TCustomRESTResponse.TStatus.ClientErrorBadRequest_400: Boolean;
begin
Result := FResponse.StatusCode = 400;
end;
function TCustomRESTResponse.TStatus.ClientErrorDuplicate_409: Boolean;
begin
Result := FResponse.StatusCode = 409;
end;
function TCustomRESTResponse.TStatus.ClientErrorForbidden_403: Boolean;
begin
Result := FResponse.StatusCode = 403;
end;
function TCustomRESTResponse.TStatus.ClientErrorNotAcceptable_406: Boolean;
begin
Result := FResponse.StatusCode = 406;
end;
function TCustomRESTResponse.TStatus.ClientErrorNotFound_404: Boolean;
begin
Result := FResponse.StatusCode = 404;
end;
function TCustomRESTResponse.TStatus.ClientErrorUnauthorized_401: Boolean;
begin
Result := FResponse.StatusCode = 401;
end;
function TCustomRESTResponse.TStatus.Success: Boolean;
begin
Result := (FResponse.StatusCode >= 200) and (FResponse.StatusCode < 300);
end;
function TCustomRESTResponse.TStatus.SuccessOK_200: Boolean;
begin
Result := FResponse.StatusCode = 200;
end;
function TCustomRESTResponse.TStatus.SucessCreated_201: Boolean;
begin
Result := FResponse.StatusCode = 201;
end;
{ TCustomRESTRequest.TBody }
procedure TCustomRESTRequest.TBody.Add(AObject: TJsonObject; AOwnsObject: TRESTObjectOwnership);
begin
FParams.AddBody(AObject, AOwnsObject);
end;
procedure TCustomRESTRequest.TBody.Add(const ABodyContent: string;
AContentType: TRESTContentType);
begin
FParams.AddBody(ABodyContent, AContentType);
end;
procedure TCustomRESTRequest.TBody.Add(ABodyContent: TStream;
AContentType: TRESTContentType; AOwnsStream: TRESTObjectOwnership);
begin
FParams.AddBody(ABodyContent, AContentType, AOwnsStream);
end;
procedure TCustomRESTRequest.TBody.Add<T>(AObject: T; AOwnsObject: TRESTObjectOwnership);
begin
FParams.AddBody(AObject, AOwnsObject);
end;
procedure TCustomRESTRequest.TBody.ClearWriter;
begin
FreeAndNil(FJSONTextWriter);
FreeAndNil(FJSONStream);
end;
procedure TCustomRESTRequest.TBody.ClearBody;
begin
FParams.Clear;
ClearWriter;
end;
constructor TCustomRESTRequest.TBody.Create;
begin
inherited Create;
FParams := TRESTRequestParameterList.Create(nil);
end;
destructor TCustomRESTRequest.TBody.Destroy;
begin
FreeAndNil(FParams);
FreeAndNil(FJSONTextWriter);
FreeAndNil(FJSONStream);
inherited Destroy;
end;
function TCustomRESTRequest.TBody.GetJSONWriter: TJsonTextWriter;
begin
if FJSONTextWriter = nil then
begin
FJSONStream := TMemoryStream.Create;
FJSONTextWriter := TJsonTextWriter.Create(FJSONStream);
end;
Result := FJSONTextWriter;
end;
end.
|
unit FUNC_Menu_ABMC;
interface
uses FUNC_REG_Pacientes, FUNC_REG_Estadisticas,
FUNC_Registros, ARCH_REG_Pacientes, ARCH_REG_Estadisticas;
procedure Menu_ABMC(VAR ARCH_Personas: ARCHIVO_Pacientes; VAR ARCH_Estadisticas: ARCHIVO_Estadisticas;
VAR R_Persona: REG_Persona; VAR R_Estadisticas: REG_Estadisticas);
implementation
uses graph, wincrt, Graph_Graficos, FUNC_ARCH_REGITROS_PACIENTES_Y_ESTADISTICAS,
Funciones_Buscar, Funciones_Ordenar, FUNC_SUB_MENU_MODIFICAR;
procedure Alta(VAR ARCH_Personas: ARCHIVO_Pacientes; VAR ARCH_Estadisticas: ARCHIVO_Estadisticas;
VAR R_Persona: REG_Persona; VAR R_Estadisticas: REG_Estadisticas);
Var
Existencia_de_DNI: Boolean;
DNI_Str: string;
opcion: Char;
begin
repeat
DNI_Str:= '';
Inicializar_Registro_Persona(R_Persona);
Inicializar_Registro_Estadisticas(R_Estadisticas);
Abrir_archivo_pacientes_para_lectura_escritura(ARCH_Personas);
IF ioresult = 0 THEN
begin
Close(ARCH_Personas);
repeat
Cargar_DNI(R_Persona.DNI);
If R_Persona.DNI > 0 then
begin
Abrir_archivo_pacientes_para_lectura_escritura(ARCH_Personas);
Existencia_de_DNI:= Verificar_Existencia_del_DNI(ARCH_Personas, R_Persona.DNI);
Close(ARCH_Personas);
Str(R_Persona.DNI, DNI_Str);
if Existencia_de_DNI = False then
begin
Pos_Datos_Ingresados(('DNI: ' + DNI_Str), 16, 3);
Cargar_Datos(R_Persona,R_Estadisticas);
end
else
begin
Bar(GetX, GetY, 29*16, 128+10*16);
Mostrar_MSJ(('Error, el DNI ' + DNI_Str + ' ya existe'),'Pulse una tecla para volver a igresar el DNI...');
Readkey;
Bar(3*15, 16*10, 57*16,16*16);
end;
end;
until((Existencia_de_DNI = False) OR (R_Persona.DNI = 0));
end
else
begin
Str(R_Persona.DNI, DNI_Str);
Cargar_DNI(R_Persona.DNI);
if R_Persona.DNI > 0 then
begin
Pos_Datos_Ingresados(('DNI: ' + DNI_Str), 16, 3);
Cargar_Datos(R_Persona,R_Estadisticas);
end;
end;
if ((R_Persona.DNI > 0) AND (Existencia_de_DNI = False)) then
begin
Mostrar_MSJ('Esta seguro de agregar a esta persona al sistema?', '[Y]/[N]');
repeat
opcion:= Upcase(readkey);
until(opcion in ['Y', 'N']);
if (opcion = 'Y') then
begin
Guarda_Registro_Persona(ARCH_Personas, R_Persona);
Guarda_Registro_Estadisticas(ARCH_Estadisticas, R_Estadisticas);
Mostrar_MSJ('El paciente persona fue agregada con exito', 'Presione una tecla para continuar');
end
else
begin
Mostrar_MSJ('El paciente no fue agregada al sistema', 'Presione una tecla para continuar');
end;
readkey;
Mostrar_MSJ('Desea volver a ingresar otra persona al sistema?', '[Y]/[N]');
repeat
opcion:= Upcase(readkey);
until(opcion in ['Y', 'N']);
if opcion = 'Y' then
begin
Bar(3*15, 10*16, 57*16,16*16);
SetFillStyle(SolidFill, 91);
Bar(27*16, 2*16, 27*16+46*16, 10*16);
end;
end;
until not ((opcion = 'Y'));
cleardevice;
end;
procedure Consulta(VAR ARCH_Personas: ARCHIVO_Pacientes; VAR ARCH_Estadisticas: ARCHIVO_Estadisticas);
var
DNI: LongWord;
DNI_STR: String;
Pos: LongInt;
R_Persona: REG_Persona;
R_Estadisticas: REG_Estadisticas;
begin
DNI_STR:= '';
Abrir_ARCHIVO_pacientes_y_Estadisticas(ARCH_Personas, ARCH_Estadisticas);
if IoResult <> 0 then
begin
Mostrar_MSJ(('Error, archivo no encontrado'), 'Pulse una tecla para continuar');
Readkey;
Bar(3*15, 16*10, 57*16,16*16);
end
else
begin
Cargar_DNI(DNI);
if DNI > 0 then
begin
Str(DNI, DNI_STR);
BBIN_DNI(ARCH_Personas, DNI, Pos);
if Pos > -1 then
begin
cargar_un_elemento_del_archivo_estadisticas_una_posicion_especifica(ARCH_Estadisticas, R_Estadisticas, Pos);
if R_Estadisticas.Dado_de_baja = False then
begin
Rectangle(3*16, 18*16, 63*16, 32*16);
SetFillStyle(SolidFill, 92);
bar(3*16+1, 18*16+1, 63*16-1, 32*16-1);
SetFillStyle(SolidFill, 91);
cargar_un_elemento_del_archivo_pacientes_una_posicion_especifica(ARCH_Personas, R_Persona, Pos);
Mostrar_Datos_del_paciente(R_Persona, R_Estadisticas);
readkey;
end
else
begin
Mostrar_MSJ(('El usuario con DNI ' + DNI_STR + ' esta dado de baja'), 'Pulse una tecla para continuar');
Readkey;
Bar(3*15, 16*10, 57*16,16*16);
end;
end
else
begin
Mostrar_MSJ(('No se encontro ningun paciente con el DNI ' + DNI_STR), 'Pulse una tecla para continuar');
Readkey;
Bar(3*15, 16*10, 57*16,16*16);
end;
end;
Cerrar_ARCHIVO_pacientes_y_Estadisticas(ARCH_Personas, ARCH_Estadisticas);
end;
end;
procedure Baja(VAR ARCH_Estadisticas: ARCHIVO_Estadisticas; VAR ARCH_Personas: ARCHIVO_Pacientes; VAR R_Estadisticas: REG_Estadisticas);
Var
DNI: LongWord;
DNI_STR: String;
Pos: LongInt;
begin
DNI:= 0;
Abrir_archivo_estadisticas_para_lectura_escritura(ARCH_Estadisticas);
if IoResult <> 0 then
begin
Mostrar_MSJ(('Error, archivo no encontrado'), 'Pulse una tecla para continuar');
Readkey;
Bar(3*15, 16*10, 57*16,16*16);
end
else
begin
Cargar_DNI(DNI);
if DNI > 0 then
begin
Abrir_archivo_pacientes_para_lectura_escritura(ARCH_Personas);
BBIN_DNI(ARCH_Personas, DNI, Pos);
Close(ARCH_Personas);
if Pos > -1 then
begin
cargar_un_elemento_del_archivo_estadisticas_una_posicion_especifica(ARCH_Estadisticas, R_Estadisticas, Pos);
Cargar_dado_de_baja(R_Estadisticas.Dado_de_baja);
Sobre_escribir_un_elemento_en_archivo_Estadisticas(ARCH_Estadisticas, R_Estadisticas, Pos);
end
else
begin
Str(DNI, DNI_STR);
Mostrar_MSJ(('No se encontro ningun paciente con el DNI ' + DNI_STR), 'Pulse una tecla para continuar');
Readkey;
Bar(3*15, 16*10, 57*16,16*16);
end;
end;
Close(ARCH_Estadisticas);
end;
end;
procedure Menu_ABMC(VAR ARCH_Personas: ARCHIVO_Pacientes; VAR ARCH_Estadisticas: ARCHIVO_Estadisticas;
VAR R_Persona: REG_Persona; VAR R_Estadisticas: REG_Estadisticas);
var
opcion: Char;
begin
Abrir_ARCHIVO_pacientes_y_Estadisticas(ARCH_Personas, ARCH_Estadisticas);
if ioresult = 0 then
begin
insercion_de_menor_a_mayor_de_DNI_De_Archivos(ARCH_Personas, ARCH_Estadisticas);
Cerrar_ARCHIVO_pacientes_y_Estadisticas(ARCH_Personas, ARCH_Estadisticas);
end;
cleardevice;
Rectangle(3*16,16*2, 26*16,16*9);
SetFillStyle(SolidFill, 92);
Bar(3*16+1,2*16+1, 26*16-1,9*16-1);
SetFillStyle(SolidFill, 91);
OutTextXY(4*16, 16*3,'[1]-Alta');
OutTextXY(4*16, 16*4,'[2]-Baja');
OutTextXY(4*16, 16*5,'[3]-Modificacion');
OutTextXY(4*16, 16*6,'[4]-Consulta');
OutTextXY(4*16, 16*7,'[ESC]-Atras');
repeat
Opcion:= Upcase(readkey);
until((Opcion in ['1'..'4']) OR (Opcion = #27));
CASE Opcion OF
'1':
Alta(ARCH_Personas, ARCH_Estadisticas, R_Persona, R_Estadisticas);
'2':
Baja(ARCH_Estadisticas, ARCH_Personas, R_Estadisticas);
'3':
Modificar_Registro(ARCH_Personas, ARCH_Estadisticas, R_Persona, R_Estadisticas);
'4':
Consulta(ARCH_Personas, ARCH_Estadisticas);
end;
end;
end. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.